This is an automated email from the ASF dual-hosted git repository.
papegaaij pushed a commit to branch islands
in repository https://gitbox.apache.org/repos/asf/wicket.git
The following commit(s) were added to refs/heads/islands by this push:
new 838986fcf6 Load islands from prebuilt libraries and check the runtime
protocol
838986fcf6 is described below
commit 838986fcf64d613141293c9f89f812fb85e0037f
Author: Emond Papegaaij <[email protected]>
AuthorDate: Tue Nov 17 17:10:05 2026 +0100
Load islands from prebuilt libraries and check the runtime protocol
An application could only load islands from its own Vite build: one
module loader for every island type. A team that wants to ship a set of
islands as a jar, built once and used by several applications, had no
way to plug that build in next to the application's own.
IslandSettings.addLibrary(name, basePath) now registers a prebuilt
library: a Vite build on the classpath with its manifest. Every entry of
the manifest becomes an island type the library provides. Its files are
served below wicket-islands-library/<name>/, only the files its
manifest lists. Island types of a library always load from the library,
also while the application uses the Vite dev server; all other types
still go through the application's own module loader, so both kinds of
islands work side by side on one page. A library typically registers
itself from an IInitializer, which runs before Application.init().
Registering the same name twice, or a type another library already
provides, fails at startup.
Every separately built bundle brings its own copy of the runtime, so the
copies on a page must agree on what the server renders. The server now
renders the protocol it speaks in data-wicket-island-protocol, and the
runtime keeps one instance per protocol on the page, shared by all
copies speaking it. A copy built for another protocol refuses the island
and logs why, instead of mounting it against markup it does not
understand. Island.PROTOCOL and the runtime's PROTOCOL are checked
against each other by a test.
Islands from different builds share the runtime's stores and
invalidations, but not React context or the TanStack Query cache, since
each build has its own React. The guide lists this as a limitation.
The runtime's page global is renamed from __wicketIslandsRuntime to
__wicketIslandsRuntimes, keyed by protocol; the example Selenium tests
read it there.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../examples/islands/IslandSeleniumTestCase.java | 5 +-
.../npm/packages/runtime/src/index.ts | 15 +-
.../npm/packages/runtime/src/protocol.ts | 23 +++
.../npm/packages/runtime/src/runtime.ts | 22 +++
.../npm/packages/runtime/test/runtime.test.ts | 57 ++++++-
.../npm/packages/runtime/test/wicket-fixture.ts | 4 +-
.../java/org/apache/wicket/islands/Island.java | 15 ++
.../org/apache/wicket/islands/IslandSettings.java | 164 ++++++++++++++++++++-
.../org/apache/wicket/islands/IslandSupport.java | 3 +-
.../wicket/islands/modules/ViteManifest.java | 17 +++
.../apache/wicket/islands/IslandLibraryTest.java | 157 ++++++++++++++++++++
.../apache/wicket/islands/IslandRenderTest.java | 14 ++
.../apache/wicket/islands/LibraryIslandPage.java | 46 ++++++
.../testlibrary/assets/charts-bar-111aaa.js | 1 +
.../testlibrary/assets/charts-bar-333ccc.css | 1 +
.../testlibrary/assets/charts-pie-444ddd.js | 1 +
.../islands/testlibrary/assets/vendor-222bbb.js | 1 +
.../wicket/islands/testlibrary/manifest.json | 21 +++
.../src/main/asciidoc/islands/islands_2.adoc | 56 ++++++-
.../src/main/asciidoc/islands/islands_9.adoc | 2 +
20 files changed, 607 insertions(+), 18 deletions(-)
diff --git
a/wicket-examples/src/test/java/org/apache/wicket/examples/islands/IslandSeleniumTestCase.java
b/wicket-examples/src/test/java/org/apache/wicket/examples/islands/IslandSeleniumTestCase.java
index 4bd1f9e803..019760b956 100644
---
a/wicket-examples/src/test/java/org/apache/wicket/examples/islands/IslandSeleniumTestCase.java
+++
b/wicket-examples/src/test/java/org/apache/wicket/examples/islands/IslandSeleniumTestCase.java
@@ -26,6 +26,7 @@ import java.util.stream.Collectors;
import org.apache.wicket.examples.AjaxEngineSelector.Engine;
import org.apache.wicket.examples.JettyTestCaseDecorator;
+import org.apache.wicket.islands.Island;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
@@ -148,9 +149,9 @@ public abstract class IslandSeleniumTestCase extends
JettyTestCaseDecorator
protected void assertNoLeakedIslands()
{
List<?> mountedAndHosts = (List<?>)js().executeScript("""
- return [globalThis.__wicketIslandsRuntime.mounted.size,
+ return
[globalThis.__wicketIslandsRuntimes[arguments[0]].mounted.size,
document.querySelectorAll('[data-wicket-island]').length];
- """);
+ """, Island.PROTOCOL);
assertEquals(mountedAndHosts.get(1), mountedAndHosts.get(0),
"mounted islands versus hosts in the page");
}
diff --git
a/wicket-experimental/wicket-islands/npm/packages/runtime/src/index.ts
b/wicket-experimental/wicket-islands/npm/packages/runtime/src/index.ts
index 3af80ecf64..bff5669031 100644
--- a/wicket-experimental/wicket-islands/npm/packages/runtime/src/index.ts
+++ b/wicket-experimental/wicket-islands/npm/packages/runtime/src/index.ts
@@ -15,24 +15,29 @@
* limitations under the License.
*/
+import { PROTOCOL } from './protocol';
import { IslandRuntime } from './runtime';
import type { IslandModule } from './types';
+export { PROTOCOL } from './protocol';
export { IslandRuntime } from './runtime';
export type { FormBinding, FormState } from './form';
export type { ClientStore } from './store';
export { IslandCallError } from './types';
export type { IslandCallErrorKind, IslandContext, IslandInstance, IslandModule
} from './types';
-const GLOBAL_KEY = '__wicketIslandsRuntime';
+const GLOBAL_KEY = '__wicketIslandsRuntimes';
/**
- * The runtime of the page. It is kept on the window, so a page that ends up
with two copies of
- * this package still has a single runtime.
+ * The runtime of the page for this package's protocol. It is kept on the
window, so the copies of
+ * this package in separate builds, such as an application's and a library's,
share one runtime
+ * when they speak the same protocol. A copy speaking another protocol gets a
runtime of its own,
+ * which refuses the islands the server rendered.
*/
export function runtime(): IslandRuntime {
- const scope = globalThis as { [GLOBAL_KEY]?: IslandRuntime };
- return scope[GLOBAL_KEY] ??= new IslandRuntime();
+ const scope = globalThis as { [GLOBAL_KEY]?: Record<number,
IslandRuntime> };
+ const runtimes = scope[GLOBAL_KEY] ??= {};
+ return runtimes[PROTOCOL] ??= new IslandRuntime();
}
/**
diff --git
a/wicket-experimental/wicket-islands/npm/packages/runtime/src/protocol.ts
b/wicket-experimental/wicket-islands/npm/packages/runtime/src/protocol.ts
new file mode 100644
index 0000000000..cbe9254ffb
--- /dev/null
+++ b/wicket-experimental/wicket-islands/npm/packages/runtime/src/protocol.ts
@@ -0,0 +1,23 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * The version of the protocol between the runtime and the Wicket Islands Java
module: the markup
+ * of the host, the island state, the calls and their answers. It is the same
number as
+ * `Island.PROTOCOL` on the server, and changes with it.
+ */
+export const PROTOCOL = 1;
diff --git
a/wicket-experimental/wicket-islands/npm/packages/runtime/src/runtime.ts
b/wicket-experimental/wicket-islands/npm/packages/runtime/src/runtime.ts
index 59adc35837..966db30685 100644
--- a/wicket-experimental/wicket-islands/npm/packages/runtime/src/runtime.ts
+++ b/wicket-experimental/wicket-islands/npm/packages/runtime/src/runtime.ts
@@ -18,12 +18,14 @@
import { IslandCallError, type IslandCallErrorKind, type IslandContext, type
IslandInstance,
type IslandModule } from './types';
import { HostFormBinding, type FormState } from './form';
+import { PROTOCOL } from './protocol';
import { ClientStores } from './store';
import { TOPIC_AJAX_CALL_DATA, TOPIC_AJAX_CALL_DONE, TOPIC_DOM_NODE_ADDED,
wicket,
type WicketAjaxAttributes, type WicketApi } from './wicket';
const ATTR_TYPE = 'data-wicket-island';
const ATTR_KEY = 'data-wicket-island-key';
+const ATTR_PROTOCOL = 'data-wicket-island-protocol';
const SELECTOR_STATE = ':scope > script[data-wicket-island-state]';
const SELECTOR_ROOT = ':scope > [data-wicket-island-root]';
@@ -88,6 +90,8 @@ export class IslandRuntime {
private readonly pending = new Map<string, PendingCall>();
+ private readonly refused = new WeakSet<HTMLElement>();
+
private readonly invalidationListeners = new Set<(keys: readonly
string[]) => void>();
readonly stores = new ClientStores();
@@ -162,6 +166,10 @@ export class IslandRuntime {
if (!module) {
return;
}
+ if (host.getAttribute(ATTR_PROTOCOL) !== String(PROTOCOL)) {
+ this.refuse(host, type);
+ return;
+ }
const island: MountedIsland = {
type,
@@ -184,6 +192,20 @@ export class IslandRuntime {
}
}
+ /**
+ * Leaves an island unmounted that the server rendered for another
protocol, and says why once.
+ */
+ private refuse(host: HTMLElement, type: string): void {
+ if (this.refused.has(host)) {
+ return;
+ }
+ this.refused.add(host);
+ const rendered = host.getAttribute(ATTR_PROTOCOL) ?? 'none';
+ console.error(`Wicket Islands: island ${host.id} of type
'${type}' is not mounted. The ` +
+ `server rendered it for protocol ${rendered}, but its
module was built for protocol ` +
+ `${PROTOCOL}: build it against the wicket-islands
version the server runs.`);
+ }
+
/**
* Moves a mounted island into the host Wicket rendered in place of its
old one.
*/
diff --git
a/wicket-experimental/wicket-islands/npm/packages/runtime/test/runtime.test.ts
b/wicket-experimental/wicket-islands/npm/packages/runtime/test/runtime.test.ts
index 7430aabab6..1f38d3ca85 100644
---
a/wicket-experimental/wicket-islands/npm/packages/runtime/test/runtime.test.ts
+++
b/wicket-experimental/wicket-islands/npm/packages/runtime/test/runtime.test.ts
@@ -16,7 +16,8 @@
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { cspNonce, IslandCallError, IslandRuntime, type IslandContext, type
IslandModule } from '../src/index';
+import { cspNonce, IslandCallError, IslandRuntime, PROTOCOL, registerIsland,
type IslandContext,
+ type IslandModule } from '../src/index';
import { component, data, failRequest, formHost, host, redirect, redirects,
requests, respond, setUpWicket,
stop } from './wicket-fixture';
@@ -494,7 +495,8 @@ describe('IslandRuntime', () => {
it('mounts the other islands when one host is broken', () => {
const error = vi.spyOn(console, 'error').mockImplementation(()
=> undefined);
- document.body.innerHTML = '<div id="broken"
data-wicket-island="board" data-wicket-island-key="k0">' +
+ document.body.innerHTML = '<div id="broken"
data-wicket-island="board" data-wicket-island-key="k0" ' +
+ `data-wicket-island-protocol="${PROTOCOL}">` +
'<script type="application/json"
data-wicket-island-state>{"props":</script>' +
'<div data-wicket-island-root></div></div>' +
host('board1', 'board', 'k1', { label: 'one' });
@@ -506,6 +508,33 @@ describe('IslandRuntime', () => {
error.mockRestore();
});
+ it('refuses an island the server rendered for another protocol, and
says so once', () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(()
=> undefined);
+ document.body.innerHTML = host('board1', 'board', 'k1', {
label: 'one' })
+ .replace(`data-wicket-island-protocol="${PROTOCOL}"`,
`data-wicket-island-protocol="${PROTOCOL + 1}"`) +
+ host('board2', 'board', 'k2', { label: 'two' });
+
+ runtime.register('board', recorder.module());
+ runtime.register('other', recorder.module());
+
+ expect(recorder.mounts.map(mount =>
mount.context.key)).toEqual(['k2']);
+ expect(error).toHaveBeenCalledTimes(1);
+ expect(error.mock.calls[0][0]).toContain(`rendered it for
protocol ${PROTOCOL + 1}`);
+ error.mockRestore();
+ });
+
+ it('refuses an island rendered without a protocol', () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(()
=> undefined);
+ document.body.innerHTML = host('board1', 'board', 'k1', {
label: 'one' })
+ .replace(` data-wicket-island-protocol="${PROTOCOL}"`,
'');
+
+ runtime.register('board', recorder.module());
+
+ expect(recorder.mounts).toHaveLength(0);
+ expect(error.mock.calls[0][0]).toContain('rendered it for
protocol none');
+ error.mockRestore();
+ });
+
it('does not keep an island whose module failed to mount', () => {
const error = vi.spyOn(console, 'error').mockImplementation(()
=> undefined);
document.body.innerHTML = host('board1', 'board', 'k1', {
label: 'one' }) +
@@ -557,6 +586,30 @@ describe('IslandRuntime', () => {
});
});
+describe('the runtime of the page', () => {
+ const runtimes = '__wicketIslandsRuntimes';
+
+ afterEach(() => {
+ delete (globalThis as Record<string, unknown>)[runtimes];
+ document.body.innerHTML = '';
+ });
+
+ it('is shared by the copies of the runtime speaking the same protocol',
() => {
+ setUpWicket();
+ const other = new IslandRuntime();
+ (globalThis as Record<string, unknown>)[runtimes] = { [PROTOCOL
+ 1]: other };
+ document.body.innerHTML = host('board1', 'board', 'k1', {
label: 'one' });
+ const recorder = new Recorder();
+
+ registerIsland('board', recorder.module());
+
+ const shared = (globalThis as Record<string,
unknown>)[runtimes] as Record<number, IslandRuntime>;
+ expect(shared[PROTOCOL]).toBeInstanceOf(IslandRuntime);
+ expect(shared[PROTOCOL + 1]).toBe(other);
+ expect(recorder.mounts).toHaveLength(1);
+ });
+});
+
describe('cspNonce', () => {
afterEach(() => {
document.head.innerHTML = '';
diff --git
a/wicket-experimental/wicket-islands/npm/packages/runtime/test/wicket-fixture.ts
b/wicket-experimental/wicket-islands/npm/packages/runtime/test/wicket-fixture.ts
index 24bf95626e..6a13ee58d6 100644
---
a/wicket-experimental/wicket-islands/npm/packages/runtime/test/wicket-fixture.ts
+++
b/wicket-experimental/wicket-islands/npm/packages/runtime/test/wicket-fixture.ts
@@ -17,6 +17,7 @@
import { readFileSync } from 'node:fs';
import path from 'node:path';
+import { PROTOCOL } from '../src/protocol';
/**
* Loads Wicket's plain JavaScript Ajax library into the test window, with a
fake transport: a
@@ -153,7 +154,8 @@ function hostWith(id: string, type: string, key: string,
state: object, before:
calls: url === null ? [] : ['probe'],
ajax: url === null ? undefined : { u: url, m: 'POST', ch:
`wicket-island-${id}|s` }
}).replace(/</g, '\\u003c');
- return `<div id="${id}" data-wicket-island="${type}"
data-wicket-island-key="${key}">` +
+ return `<div id="${id}" data-wicket-island="${type}"
data-wicket-island-key="${key}" ` +
+ `data-wicket-island-protocol="${PROTOCOL}">` +
before + `<script type="application/json"
data-wicket-island-state>${json}</script>` +
'<div data-wicket-island-root></div></div>';
}
diff --git
a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/Island.java
b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/Island.java
index cb0ff114da..5cac1d69c7 100644
---
a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/Island.java
+++
b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/Island.java
@@ -95,6 +95,21 @@ public class Island<P> extends WebComponent implements
IGenericComponent<P, Isla
*/
public static final String ATTR_ROOT = "data-wicket-island-root";
+ /**
+ * The attribute holding the version of the protocol the island was
rendered for.
+ */
+ public static final String ATTR_PROTOCOL =
"data-wicket-island-protocol";
+
+ /**
+ * The version of the protocol between this module and the client-side
runtime: the markup of
+ * the host, the island state, the calls and their answers. It changes
whenever one side
+ * changes in a way the other cannot follow. The runtime mounts an
island only when it was
+ * built for the same version, so a module built against another
version of the runtime, for
+ * example one in an outdated {@linkplain
IslandSettings#addLibrary(String, String) library},
+ * is refused rather than run against a server it does not understand.
+ */
+ public static final int PROTOCOL = 1;
+
private final IslandSupport island;
/**
diff --git
a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandSettings.java
b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandSettings.java
index c1d04283cb..30921b382c 100644
---
a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandSettings.java
+++
b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandSettings.java
@@ -16,6 +16,12 @@
*/
package org.apache.wicket.islands;
+import java.io.InputStream;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.regex.Pattern;
+
import org.apache.wicket.Application;
import org.apache.wicket.MetaDataKey;
import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;
@@ -23,6 +29,7 @@ import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
import org.apache.wicket.islands.modules.IIslandModuleLoader;
import org.apache.wicket.islands.modules.IslandAssetResource;
+import org.apache.wicket.islands.modules.ViteManifest;
import org.apache.wicket.islands.modules.ViteDevServerModuleLoader;
import org.apache.wicket.islands.modules.ViteManifestModuleLoader;
import org.apache.wicket.islands.serializer.IIslandSerializer;
@@ -59,11 +66,18 @@ public class IslandSettings
*/
public static final String MOUNT_PATH = "wicket-islands";
+ /**
+ * The path the files of a library are served under, followed by the
library's name.
+ */
+ public static final String LIBRARY_MOUNT_PATH =
"wicket-islands-library";
+
/**
* The path page-less endpoints are served under.
*/
public static final String ENDPOINT_PATH = "wicket-islands-call";
+ private static final Pattern LIBRARY_NAME =
Pattern.compile("[A-Za-z0-9_-]+");
+
private static final MetaDataKey<IslandSettings> KEY = new
MetaDataKey<>()
{
private static final long serialVersionUID = 1L;
@@ -89,11 +103,18 @@ public class IslandSettings
private IIslandHandleStore handleStore = new SessionHandleStore();
+ private WebApplication application;
+
+ private final Map<String, ViteManifestModuleLoader> libraries = new
ConcurrentHashMap<>();
+
+ private final Map<String, String> libraryTypes = new
ConcurrentHashMap<>();
+
/**
* Installs the settings in an application, mounts the resource serving
the built files,
* registers the listener that answers island calls failing before they
reach their island, and
* makes Ajax behaviors on a {@link FormIsland} send the hidden input
holding its value. When the
- * settings are installed already, returns them unchanged.
+ * settings are installed already, returns them unchanged, so a library
can install them from
+ * its {@link org.apache.wicket.IInitializer} as well as the
application in its {@code init()}.
*
* @param application
* the application
@@ -109,6 +130,7 @@ public class IslandSettings
return installed;
}
IslandSettings settings = new IslandSettings();
+ settings.application = application;
settings.assets = new ResourceReference(IslandSettings.class,
"assets")
{
private static final long serialVersionUID = 1L;
@@ -255,6 +277,9 @@ public class IslandSettings
}
/**
+ * Replaces the loader of the application's own islands. Islands of a
type a
+ * {@linkplain #addLibrary(String, String) library} provides keep
loading from the library.
+ *
* @param moduleLoader
* a loader to use instead of the default, {@code null} for
the default
* @return {@code this}
@@ -266,9 +291,21 @@ public class IslandSettings
}
/**
- * @return the configured loader; otherwise the dev server loader when
a dev server is set and
- * the application runs in development mode; otherwise the
loader for the build on the
- * classpath
+ * @param islandType
+ * an island type
+ * @return the loader of the library providing the type; for any other
type the application's
+ * loader, see {@link #getModuleLoader()}
+ */
+ public IIslandModuleLoader getModuleLoader(String islandType)
+ {
+ String library = libraryTypes.get(islandType);
+ return library != null ? libraries.get(library) :
getModuleLoader();
+ }
+
+ /**
+ * @return the loader of the application's own islands: the configured
loader; otherwise the
+ * dev server loader when a dev server is set and the
application runs in development
+ * mode; otherwise the loader for the build on the classpath
*/
public IIslandModuleLoader getModuleLoader()
{
@@ -296,4 +333,123 @@ public class IslandSettings
}
return loader;
}
+
+ /**
+ * Adds a library of prebuilt islands: a Vite build of island modules
on the classpath, made
+ * with the Wicket Islands Vite plugin and shipped in the jar of the
library, so that an
+ * application uses its island components without a frontend build of
its own.
+ * <p>
+ * Every entry of the build's manifest is an island type of the
library. Islands of these types
+ * load their modules from the library's build, in development mode
too; islands of any other
+ * type from the application's own build or dev server, so both can be
used on one page. The
+ * files of the build are served under {@value
#LIBRARY_MOUNT_PATH}{@code /<name>}.
+ * <p>
+ * A build contains everything its modules import, the framework and
the islands runtime among
+ * them, so a page with islands from several builds loads a copy of the
framework for each. The
+ * islands still work side by side, since each is mounted as a root of
its own; they share the
+ * client stores and the invalidations of the server, but not the
context of a framework or the
+ * query cache of an adapter. A build made against another {@link
Island#PROTOCOL protocol}
+ * than this module's is refused by the runtime: its islands are not
mounted, and the browser
+ * console says why.
+ * <p>
+ * Island types are global, so a library should prefix its types with
its name. A library
+ * adds itself from an {@link org.apache.wicket.IInitializer}, which
runs before the
+ * application's {@code init()}:
+ *
+ * <pre>
+ * public void init(Application application)
+ * {
+ * IslandSettings.install((WebApplication)application)
+ * .addLibrary("charts", "META-INF/charts-islands/");
+ * }
+ * </pre>
+ *
+ * @param name
+ * the name of the library, used in the URLs of its files:
letters, digits, '-' and
+ * '_'
+ * @param basePath
+ * the classpath location of the build's output directory,
ending in a slash, with
+ * the manifest in {@value #DEFAULT_MANIFEST_FILE}
+ * @return {@code this}
+ * @throws IllegalArgumentException
+ * if the name is invalid, or another library has it
+ * @throws IllegalStateException
+ * if the build has no manifest, or another library
provides one of its island types
+ */
+ public IslandSettings addLibrary(String name, String basePath)
+ {
+ return addLibrary(name, basePath, DEFAULT_MANIFEST_FILE);
+ }
+
+ /**
+ * Adds a library of prebuilt islands whose manifest is not in the
default location.
+ *
+ * @param name
+ * the name of the library, used in the URLs of its files:
letters, digits, '-' and
+ * '_'
+ * @param basePath
+ * the classpath location of the build's output directory,
ending in a slash
+ * @param manifestFile
+ * the location of the manifest, relative to the base path
+ * @return {@code this}
+ * @see #addLibrary(String, String)
+ */
+ public synchronized IslandSettings addLibrary(String name, String
basePath,
+ String manifestFile)
+ {
+ Args.notEmpty(name, "name");
+ Args.notEmpty(basePath, "basePath");
+ Args.notEmpty(manifestFile, "manifestFile");
+ if (!LIBRARY_NAME.matcher(name).matches())
+ {
+ throw new IllegalArgumentException(
+ "Invalid island library name '" + name + "':
use letters, digits, '-' and '_'.");
+ }
+ if (libraries.containsKey(name))
+ {
+ throw new IllegalArgumentException(
+ "The island library '" + name + "' is added
already");
+ }
+
+ Set<String> types = readLibraryTypes(name, basePath +
manifestFile);
+ for (String type : types)
+ {
+ String other = libraryTypes.get(type);
+ if (other != null)
+ {
+ throw new IllegalStateException("The island
type '" + type + "' of library '" +
+ name + "' is provided by library '" +
other + "' already");
+ }
+ }
+
+ ResourceReference files = new
ResourceReference(IslandSettings.class, "library-" + name)
+ {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public IResource getResource()
+ {
+ return new IslandAssetResource(() ->
libraries.get(name));
+ }
+ };
+ libraries.put(name, new ViteManifestModuleLoader(basePath,
manifestFile, files));
+ types.forEach(type -> libraryTypes.put(type, name));
+ application.mountResource(LIBRARY_MOUNT_PATH + "/" + name,
files);
+ return this;
+ }
+
+ private Set<String> readLibraryTypes(String name, String manifest)
+ {
+ ClassLoader classLoader = application.getApplicationSettings()
+ .getClassResolver()
+ .getClassLoader();
+ InputStream in = classLoader.getResourceAsStream(manifest);
+ if (in == null)
+ {
+ throw new IllegalStateException(
+ "No Vite manifest at '" + manifest + "' on the
classpath for island library '" +
+ name + "'");
+ }
+ return ViteManifest.read(in).getEntryNames();
+ }
}
diff --git
a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandSupport.java
b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandSupport.java
index 52f3d2ec2b..617fe1d7fe 100644
---
a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandSupport.java
+++
b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandSupport.java
@@ -200,6 +200,7 @@ final class IslandSupport implements IClusterable
}
tag.put(Island.ATTR_TYPE, type);
tag.put(Island.ATTR_KEY, key);
+ tag.put(Island.ATTR_PROTOCOL, Island.PROTOCOL);
}
/**
@@ -250,7 +251,7 @@ final class IslandSupport implements IClusterable
.addTagAttribute("property", "csp-nonce")
.addTagAttribute("nonce",
csp.getNonce(RequestCycle.get())));
}
- IslandSettings.get().getModuleLoader().renderHead(type,
response);
+ IslandSettings.get().getModuleLoader(type).renderHead(type,
response);
}
void detach()
diff --git
a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/modules/ViteManifest.java
b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/modules/ViteManifest.java
index 030614f451..66df5e0690 100644
---
a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/modules/ViteManifest.java
+++
b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/modules/ViteManifest.java
@@ -24,6 +24,7 @@ import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import java.util.TreeSet;
import org.apache.wicket.WicketRuntimeException;
import org.apache.wicket.util.lang.Args;
@@ -119,6 +120,22 @@ public final class ViteManifest
return null;
}
+ /**
+ * @return the input names of the build's entries
+ */
+ public Set<String> getEntryNames()
+ {
+ Set<String> names = new TreeSet<>();
+ for (Chunk chunk : chunks.values())
+ {
+ if (Boolean.TRUE.equals(chunk.isEntry()) &&
chunk.name() != null)
+ {
+ names.add(chunk.name());
+ }
+ }
+ return names;
+ }
+
/**
* @param key
* a manifest key
diff --git
a/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/IslandLibraryTest.java
b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/IslandLibraryTest.java
new file mode 100644
index 0000000000..3e17686dc9
--- /dev/null
+++
b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/IslandLibraryTest.java
@@ -0,0 +1,157 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.wicket.islands;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.regex.Pattern;
+
+import org.apache.wicket.util.tester.WicketTester;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Islands from a library's prebuilt build next to the application's own.
+ */
+class IslandLibraryTest extends IslandTestCase
+{
+ private static final String LIBRARY =
"org/apache/wicket/islands/testlibrary/";
+
+ @Override
+ protected void configureIslands(IslandSettings settings)
+ {
+ super.configureIslands(settings);
+ settings.addLibrary("charts", LIBRARY, "manifest.json");
+ }
+
+ @Test
+ void loadsLibraryTypesFromTheLibraryAndOtherTypesFromTheApplication()
+ {
+ tester.startPage(LibraryIslandPage.class);
+
+ String response = tester.getLastResponseAsString();
+
assertTrue(module("wicket-islands-library/charts/assets/charts-bar-111aaa.js")
+ .matcher(response)
+ .find(), response);
+
assertTrue(response.contains("/wicket-islands-library/charts/assets/charts-bar-333ccc.css"),
+ response);
+
assertTrue(module("wicket-islands/assets/test-island-abc123.js").matcher(response).find(),
+ response);
+ }
+
+ private static Pattern module(String file)
+ {
+ return Pattern.compile(
+ "<script type=\"module\" src=\"[^\"]*/" +
Pattern.quote(file) + "\"");
+ }
+
+ @Test
+ void loadsLibraryTypesFromTheLibraryWhenTheApplicationUsesTheDevServer()
+ {
+ IslandSettings.get().setDevServerUrl("http://localhost:5173/");
+
+ tester.startPage(LibraryIslandPage.class);
+
+ String response = tester.getLastResponseAsString();
+
assertTrue(module("wicket-islands-library/charts/assets/charts-bar-111aaa.js")
+ .matcher(response)
+ .find(), response);
+
assertTrue(response.contains("http://localhost:5173/@wicket-islands/test-island"),
+ response);
+ assertFalse(response.contains("@wicket-islands/charts-bar"),
response);
+ }
+
+ @Test
+ void routesEveryEntryOfTheLibraryToIt()
+ {
+ IslandSettings settings = IslandSettings.get();
+
+ assertSame(settings.getModuleLoader("charts-bar"),
settings.getModuleLoader("charts-pie"));
+ assertSame(settings.getModuleLoader(),
settings.getModuleLoader("test-island"));
+ }
+
+ @Test
+ void servesTheFilesOfTheLibrary()
+ {
+
tester.executeUrl("wicket-islands-library/charts/assets/vendor-222bbb.js");
+
+ assertEquals(200, tester.getLastResponse().getStatus());
+ assertEquals("export const vendor = 1;\n",
tester.getLastResponseAsString());
+ }
+
+ @Test
+ void servesOnlyTheFilesOfTheLibraryUnderItsPath()
+ {
+
tester.executeUrl("wicket-islands-library/charts/assets/test-island-abc123.js");
+
+ assertEquals(404, tester.getLastResponse().getStatus());
+ }
+
+ @Test
+ void refusesASecondLibraryWithTheSameName()
+ {
+ IslandSettings settings = IslandSettings.get();
+
+ assertThrows(IllegalArgumentException.class,
+ () -> settings.addLibrary("charts",
"org/apache/wicket/islands/testbuild/",
+ "manifest.json"));
+ }
+
+ @Test
+ void refusesALibraryProvidingATypeOfAnotherLibrary()
+ {
+ IslandSettings settings = IslandSettings.get();
+
+ IllegalStateException e =
assertThrows(IllegalStateException.class,
+ () -> settings.addLibrary("graphs", LIBRARY,
"manifest.json"));
+
+ assertTrue(e.getMessage().contains("'charts-bar'"),
e.getMessage());
+ settings.addLibrary("graphs",
"org/apache/wicket/islands/testbuild/", "manifest.json");
+ }
+
+ @Test
+ void refusesALibraryWithoutAManifest()
+ {
+ IslandSettings settings = IslandSettings.get();
+
+ assertThrows(IllegalStateException.class,
+ () -> settings.addLibrary("missing",
"org/apache/wicket/islands/nowhere/"));
+ }
+
+ @Test
+ void refusesAnInvalidName()
+ {
+ IslandSettings settings = IslandSettings.get();
+
+ assertThrows(IllegalArgumentException.class,
+ () -> settings.addLibrary("../charts", LIBRARY,
"manifest.json"));
+ }
+
+ /**
+ * Keeps {@link WicketTester} from following an error to an error page.
+ */
+ @Override
+ protected WicketTester
newWicketTester(org.apache.wicket.protocol.http.WebApplication app)
+ {
+ WicketTester tester = super.newWicketTester(app);
+ tester.setExposeExceptions(false);
+ return tester;
+ }
+}
diff --git
a/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/IslandRenderTest.java
b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/IslandRenderTest.java
index 8576387ef2..d7b626ffb2 100644
---
a/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/IslandRenderTest.java
+++
b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/IslandRenderTest.java
@@ -22,6 +22,9 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -66,10 +69,21 @@ class IslandRenderTest extends IslandTestCase
TagTester host = tester.getTagByWicketId("island");
assertEquals("test-island",
host.getAttribute(Island.ATTR_TYPE));
assertEquals(page.island.getKey(),
host.getAttribute(Island.ATTR_KEY));
+ assertEquals(String.valueOf(Island.PROTOCOL),
host.getAttribute(Island.ATTR_PROTOCOL));
assertEquals(page.island.getMarkupId(),
host.getAttribute("id"));
assertTrue(tester.getLastResponseAsString().contains("<div " +
Island.ATTR_ROOT + "></div>"));
}
+ @Test
+ void speaksTheProtocolOfTheRuntime() throws IOException
+ {
+ String runtime =
Files.readString(Path.of("npm/packages/runtime/src/protocol.ts"));
+
+ Matcher protocol = Pattern.compile("export const PROTOCOL =
(\\d+);").matcher(runtime);
+ assertTrue(protocol.find(), runtime);
+ assertEquals(Island.PROTOCOL,
Integer.parseInt(protocol.group(1)));
+ }
+
@Test
@SuppressWarnings("unchecked")
void stateHoldsPropsCallsAndAjaxAttributes()
diff --git
a/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/LibraryIslandPage.java
b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/LibraryIslandPage.java
new file mode 100644
index 0000000000..2575dfabcf
--- /dev/null
+++
b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/LibraryIslandPage.java
@@ -0,0 +1,46 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.wicket.islands;
+
+import org.apache.wicket.MarkupContainer;
+import org.apache.wicket.markup.IMarkupResourceStreamProvider;
+import org.apache.wicket.markup.html.WebPage;
+import org.apache.wicket.model.Model;
+import org.apache.wicket.util.resource.IResourceStream;
+import org.apache.wicket.util.resource.StringResourceStream;
+
+/**
+ * A page with an island of the application's own build next to one of a
library.
+ */
+public class LibraryIslandPage extends WebPage implements
IMarkupResourceStreamProvider
+{
+ private static final long serialVersionUID = 1L;
+
+ public LibraryIslandPage()
+ {
+ add(new Island<>("own", "test-island", Model.of("own")));
+ add(new Island<>("library", "charts-bar", Model.of("library")));
+ }
+
+ @Override
+ public IResourceStream getMarkupResourceStream(MarkupContainer
container,
+ Class<?> containerClass)
+ {
+ return new StringResourceStream("<html><head></head><body><div
wicket:id=\"own\"></div>" +
+ "<div wicket:id=\"library\"></div></body></html>");
+ }
+}
diff --git
a/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/testlibrary/assets/charts-bar-111aaa.js
b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/testlibrary/assets/charts-bar-111aaa.js
new file mode 100644
index 0000000000..ff8b4c5632
--- /dev/null
+++
b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/testlibrary/assets/charts-bar-111aaa.js
@@ -0,0 +1 @@
+export default {};
diff --git
a/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/testlibrary/assets/charts-bar-333ccc.css
b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/testlibrary/assets/charts-bar-333ccc.css
new file mode 100644
index 0000000000..b9b5afc8be
--- /dev/null
+++
b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/testlibrary/assets/charts-bar-333ccc.css
@@ -0,0 +1 @@
+.bar {}
diff --git
a/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/testlibrary/assets/charts-pie-444ddd.js
b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/testlibrary/assets/charts-pie-444ddd.js
new file mode 100644
index 0000000000..ff8b4c5632
--- /dev/null
+++
b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/testlibrary/assets/charts-pie-444ddd.js
@@ -0,0 +1 @@
+export default {};
diff --git
a/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/testlibrary/assets/vendor-222bbb.js
b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/testlibrary/assets/vendor-222bbb.js
new file mode 100644
index 0000000000..49c972483f
--- /dev/null
+++
b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/testlibrary/assets/vendor-222bbb.js
@@ -0,0 +1 @@
+export const vendor = 1;
diff --git
a/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/testlibrary/manifest.json
b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/testlibrary/manifest.json
new file mode 100644
index 0000000000..276f8d7cc8
--- /dev/null
+++
b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/testlibrary/manifest.json
@@ -0,0 +1,21 @@
+{
+ "src/BarChart.tsx": {
+ "file": "assets/charts-bar-111aaa.js",
+ "name": "charts-bar",
+ "src": "src/BarChart.tsx",
+ "isEntry": true,
+ "imports": ["_vendor-222bbb.js"],
+ "css": ["assets/charts-bar-333ccc.css"]
+ },
+ "src/PieChart.tsx": {
+ "file": "assets/charts-pie-444ddd.js",
+ "name": "charts-pie",
+ "src": "src/PieChart.tsx",
+ "isEntry": true,
+ "imports": ["_vendor-222bbb.js"]
+ },
+ "_vendor-222bbb.js": {
+ "file": "assets/vendor-222bbb.js",
+ "name": "vendor"
+ }
+}
diff --git a/wicket-user-guide/src/main/asciidoc/islands/islands_2.adoc
b/wicket-user-guide/src/main/asciidoc/islands/islands_2.adoc
index d57f001f34..fb70129449 100644
--- a/wicket-user-guide/src/main/asciidoc/islands/islands_2.adoc
+++ b/wicket-user-guide/src/main/asciidoc/islands/islands_2.adoc
@@ -49,8 +49,9 @@ protected void init()
----
_IslandSettings.install_ mounts the resource that serves the built files at
`wicket-islands/`
-and the one that serves page-less endpoints at `wicket-islands-call/`, so the
application must
-not mount anything else under those paths. It also registers a request cycle
listener that
+and the one that serves page-less endpoints at `wicket-islands-call/`;
libraries of islands are
+served under `wicket-islands-library/`. The application must not mount
anything else under these
+paths. It also registers a request cycle listener that
answers island calls which fail before they reach their island, and makes Ajax
behaviors on a
form island send its value. It returns the settings for further configuration:
@@ -63,7 +64,9 @@ form island send its value. It returns the settings for
further configuration:
only.
|_setSerializer_ |The JSON serializer, by default a _JacksonIslandSerializer_.
|_setHandleStore_ |Where the handles of page-less endpoints are kept, by
default in the session.
-|_setModuleLoader_ |Replaces how island modules are contributed to the page
header altogether.
+|_setModuleLoader_ |Replaces how the application's own island modules are
contributed to the
+page header altogether.
+|_addLibrary_ |Adds the prebuilt islands of a library, see below.
|_getPagelessEndpoints_ |The registry of page-less endpoints.
|===
@@ -254,6 +257,53 @@ connections to the dev server, over HTTP and WebSocket,
for hot module replaceme
above allows them in development mode only. `server.origin` in the Vite
configuration makes the
URLs of assets point at the dev server rather than at the Wicket application.
+=== Islands from a library
+
+A library can ship island components with their JavaScript already built, so
that an application
+uses them like any other Wicket component, without a frontend build of its
own. The library's
+build is an ordinary Vite build made with the Wicket Islands plugin, whose
output, manifest
+included, is packed into the library's jar under a path of its own, for example
+`META-INF/charts-islands/`. The library adds it from an _IInitializer_, which
Wicket runs before
+the application's _init_:
+
+[source,java]
+----
+public class ChartsInitializer implements IInitializer
+{
+ @Override
+ public void init(Application application)
+ {
+ IslandSettings.install((WebApplication)application)
+ .addLibrary("charts", "META-INF/charts-islands/");
+ }
+
+ @Override
+ public void destroy(Application application)
+ {
+ }
+}
+----
+
+Every entry of the library's manifest is an island type of the library.
Islands of these types
+load their modules from the library's build, in development mode as well;
islands of every other
+type load from the application's own build or dev server as before, so islands
of both kinds can
+be used on the same page. The files of the library are served under
+`wicket-islands-library/<name>/`. Island types are global, so a library should
prefix its types
+with its name; adding a library that provides a type another library provides
already fails.
+
+A build contains everything its modules import, the framework and the islands
runtime included.
+A page that shows islands from several builds therefore loads a copy of React
for each of them.
+The islands still work side by side, because each island is mounted as a React
root of its own.
+They share the client stores and receive the invalidations of the server, but
React context, such
+as a component library's theme, and the query cache do not cross from one
build to another.
+
+The server and the runtime speak a versioned protocol (_Island.PROTOCOL_).
Each island host
+carries the version it was rendered for, and the runtime mounts it only when
its own version is
+the same. A library built against a `wicket-islands` version with another
protocol does not
+disturb the other islands of the page: its islands stay empty, and the browser
console says which
+island was refused and why. The library has to be rebuilt against the version
the application
+runs.
+
=== Content Security Policy
Wicket's default Content Security Policy allows scripts and styles only with
the nonce of the
diff --git a/wicket-user-guide/src/main/asciidoc/islands/islands_9.adoc
b/wicket-user-guide/src/main/asciidoc/islands/islands_9.adoc
index dfb51cf495..5a7a789a31 100644
--- a/wicket-user-guide/src/main/asciidoc/islands/islands_9.adoc
+++ b/wicket-user-guide/src/main/asciidoc/islands/islands_9.adoc
@@ -37,6 +37,8 @@ a notice that the JavaScript is missing. For development, run
`npm run dev` in
* React is the only framework with an adapter. The runtime and its mount
contract are
framework-neutral, so adapters for other frameworks, such as Vue and
Angular, can follow.
* The npm packages are not published yet.
+* Islands from separate builds, such as the application's and a library's,
each bring their own
+ copy of the framework; they cannot share one.
* The frontend declares its own TypeScript types for props and payloads; they
are not generated
from the Java types yet.
* Client stores live on the client only. The server cannot seed them or update
them yet.