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
commit 7294ab74c738b5c516d058dbc6538672bc0da599 Author: Emond Papegaaij <[email protected]> AuthorDate: Thu Nov 5 18:19:03 2026 +0100 Answer failed island calls and fix loading islands under a filter path and in dev mode Running Wicket Islands in a real application, the Treasure Hunt example, showed several defects. An island call that could not reach its island was answered the way Wicket answers any listener invocation in that situation: a redirect to an error page or to a re-rendered page. The island's promise never settled. The client now sends the island's key with each call, and the endpoint answers 'expired' when it reaches a different island instance, as on a page recreated after expiry; Island allows its listener to be called after expiry so the check can run. A request cycle listener, installed with the settings, answers island calls that fail earlier: an expired, stale or removed page as 'expired', a call that is not allowed or not authorized as 'forbidden'. The URLs of island modules were rendered relative to the servlet context, which misses the Wicket filter path; they are now generated from the mounted resource reference. In development, the dev-server loader renders Vite's csp-nonce meta tag, so the styles Vite injects pass a nonce-based Content Security Policy. The Vite plugin no longer imports vite at runtime, which failed when the plugin was installed as a link. It gains an adapter option: island modules export a plain component and the generated entry wraps it, which keeps them eligible for React Fast Refresh. wicket-islands-react provides the options as the reactIslands preset in wicket-islands-react/vite (replacing wicket-islands-react/preamble), and takes wicket-islands as a peer dependency. Co-Authored-By: Claude Opus 5.5 <[email protected]> --- .../wicket-islands/npm/package-lock.json | 6 +- .../wicket-islands/npm/packages/react/package.json | 12 +-- .../react/src/{preamble.d.ts => vite.d.ts} | 8 ++ .../packages/react/src/{preamble.js => vite.js} | 20 ++-- .../npm/packages/runtime/src/runtime.ts | 7 +- .../npm/packages/runtime/test/runtime.test.ts | 7 +- .../npm/packages/vite-plugin/src/index.d.ts | 19 +++- .../npm/packages/vite-plugin/src/index.js | 29 ++++-- .../npm/packages/vite-plugin/test/plugin.test.ts | 17 +++- .../java/org/apache/wicket/islands/Island.java | 10 ++ .../org/apache/wicket/islands/IslandAnswer.java | 58 ++++++++++++ .../wicket/islands/IslandCallFailureListener.java | 94 ++++++++++++++++++ .../wicket/islands/IslandEndpointBehavior.java | 40 ++++---- .../org/apache/wicket/islands/IslandSettings.java | 30 +++--- .../islands/modules/ViteDevServerModuleLoader.java | 17 +++- .../islands/modules/ViteManifestModuleLoader.java | 34 +++++-- .../wicket/islands/IslandCallFailureTest.java | 105 +++++++++++++++++++++ .../apache/wicket/islands/IslandDevServerTest.java | 15 +++ .../apache/wicket/islands/IslandRenderTest.java | 17 ++++ .../org/apache/wicket/islands/IslandTestCase.java | 18 +++- .../wicket/islands/NonBookmarkableIslandPage.java} | 12 ++- 21 files changed, 497 insertions(+), 78 deletions(-) diff --git a/wicket-experimental/wicket-islands/npm/package-lock.json b/wicket-experimental/wicket-islands/npm/package-lock.json index 1cb750a256..22a028156f 100644 --- a/wicket-experimental/wicket-islands/npm/package-lock.json +++ b/wicket-experimental/wicket-islands/npm/package-lock.json @@ -2196,12 +2196,10 @@ "name": "wicket-islands-react", "version": "0.0.0", "license": "Apache-2.0", - "dependencies": { - "wicket-islands": "0.0.0" - }, "peerDependencies": { "react": "^19.0.0", - "react-dom": "^19.0.0" + "react-dom": "^19.0.0", + "wicket-islands": "0.0.0" } }, "packages/runtime": { diff --git a/wicket-experimental/wicket-islands/npm/packages/react/package.json b/wicket-experimental/wicket-islands/npm/packages/react/package.json index cf69b8c3c0..93e4d37d6d 100644 --- a/wicket-experimental/wicket-islands/npm/packages/react/package.json +++ b/wicket-experimental/wicket-islands/npm/packages/react/package.json @@ -6,16 +6,14 @@ "type": "module", "exports": { ".": "./src/index.tsx", - "./preamble": { - "types": "./src/preamble.d.ts", - "default": "./src/preamble.js" + "./vite": { + "types": "./src/vite.d.ts", + "default": "./src/vite.js" } }, - "dependencies": { - "wicket-islands": "0.0.0" - }, "peerDependencies": { "react": "^19.0.0", - "react-dom": "^19.0.0" + "react-dom": "^19.0.0", + "wicket-islands": "0.0.0" } } diff --git a/wicket-experimental/wicket-islands/npm/packages/react/src/preamble.d.ts b/wicket-experimental/wicket-islands/npm/packages/react/src/vite.d.ts similarity index 85% copy from wicket-experimental/wicket-islands/npm/packages/react/src/preamble.d.ts copy to wicket-experimental/wicket-islands/npm/packages/react/src/vite.d.ts index f1350e5fdc..ea92a60e6e 100644 --- a/wicket-experimental/wicket-islands/npm/packages/react/src/preamble.d.ts +++ b/wicket-experimental/wicket-islands/npm/packages/react/src/vite.d.ts @@ -19,3 +19,11 @@ * Installs React Fast Refresh in a page Vite does not serve itself. */ export declare const reactRefreshPreamble: string; + +/** + * The options of the Wicket Islands Vite plugin for React islands. + */ +export declare const reactIslands: { + adapter: string; + devPreamble: string; +}; diff --git a/wicket-experimental/wicket-islands/npm/packages/react/src/preamble.js b/wicket-experimental/wicket-islands/npm/packages/react/src/vite.js similarity index 75% rename from wicket-experimental/wicket-islands/npm/packages/react/src/preamble.js rename to wicket-experimental/wicket-islands/npm/packages/react/src/vite.js index 0569298995..7bf7a05017 100644 --- a/wicket-experimental/wicket-islands/npm/packages/react/src/preamble.js +++ b/wicket-experimental/wicket-islands/npm/packages/react/src/vite.js @@ -16,12 +16,7 @@ */ /** - * Installs React Fast Refresh in a page Vite does not serve itself. Pass it to the Wicket Islands - * Vite plugin, which runs it before any island module in development: - * - * ```js - * wicketIslands({ islands: { ... }, devPreamble: reactRefreshPreamble }) - * ``` + * Installs React Fast Refresh in a page Vite does not serve itself. */ export const reactRefreshPreamble = `import RefreshRuntime from '/@react-refresh'; RefreshRuntime.injectIntoGlobalHook(window); @@ -29,3 +24,16 @@ window.$RefreshReg$ = () => {}; window.$RefreshSig$ = () => (type) => type; window.__vite_plugin_react_preamble_installed__ = true; `; + +/** + * The options of the Wicket Islands Vite plugin for React islands: island modules export a plain + * component, which keeps them eligible for Fast Refresh. + * + * ```js + * wicketIslands({ islands: { 'treasure-board': 'src/TreasureBoard.tsx' }, ...reactIslands }) + * ``` + */ +export const reactIslands = { + adapter: 'wicket-islands-react', + devPreamble: reactRefreshPreamble +}; 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 4d31be6e9f..6f58bf235b 100644 --- a/wicket-experimental/wicket-islands/npm/packages/runtime/src/runtime.ts +++ b/wicket-experimental/wicket-islands/npm/packages/runtime/src/runtime.ts @@ -29,6 +29,7 @@ const DATA_NAME = 'wicket-islands'; const PARAM_CALL = 'island-call'; const PARAM_CALL_ID = 'island-call-id'; const PARAM_PAYLOAD = 'island-payload'; +const PARAM_KEY = 'island-key'; interface IslandState { props: unknown; @@ -195,7 +196,11 @@ export class IslandRuntime { } const id = String(++this.callSequence); - const parameters: Record<string, string> = { [PARAM_CALL]: name, [PARAM_CALL_ID]: id }; + const parameters: Record<string, string> = { + [PARAM_CALL]: name, + [PARAM_CALL_ID]: id, + [PARAM_KEY]: island.key + }; if (payload !== undefined) { parameters[PARAM_PAYLOAD] = JSON.stringify(payload); } 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 fddf3d8fd1..25510ee93e 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 @@ -102,6 +102,7 @@ describe('IslandRuntime', () => { expect(attributes.ep).toEqual({ 'island-call': 'probe', 'island-call-id': '1', + 'island-key': 'k1', 'island-payload': '{"x":1,"y":2}' }); }); @@ -111,7 +112,11 @@ describe('IslandRuntime', () => { ignore(recorder.context.call('reset')); - expect(requests[0].attributes.ep).toEqual({ 'island-call': 'reset', 'island-call-id': '1' }); + expect(requests[0].attributes.ep).toEqual({ + 'island-call': 'reset', + 'island-call-id': '1', + 'island-key': 'k1' + }); }); it('resolves a call after the components of the response are updated', async () => { diff --git a/wicket-experimental/wicket-islands/npm/packages/vite-plugin/src/index.d.ts b/wicket-experimental/wicket-islands/npm/packages/vite-plugin/src/index.d.ts index a30e5bcc45..8d94fd3d8c 100644 --- a/wicket-experimental/wicket-islands/npm/packages/vite-plugin/src/index.d.ts +++ b/wicket-experimental/wicket-islands/npm/packages/vite-plugin/src/index.d.ts @@ -19,19 +19,28 @@ import type { Plugin } from 'vite'; export interface WicketIslandsOptions { /** - * The island modules by island type, relative to Vite's root. Each module's default export is - * the island, made by a framework adapter, e.g. `defineIsland` of wicket-islands-react. + * The island modules by island type, relative to Vite's root. With an adapter, each module's + * default export is a component of the adapter's framework; without one, it is an island + * module made by an adapter's `defineIsland`. */ islands: Record<string, string>; /** - * Code run before any island module in development, e.g. `reactRefreshPreamble` of - * wicket-islands-react/preamble. + * The framework adapter whose `defineIsland` turns a module's default export into an island, + * e.g. `wicket-islands-react`. Exporting the plain component keeps the module eligible for the + * framework's hot reload. + */ + adapter?: string; + + /** + * Code run before any island module in development, e.g. React Fast Refresh's preamble. */ devPreamble?: string; } /** - * Builds the islands of a Wicket application and serves them to it in development. + * Builds the islands of a Wicket application and serves them to it in development. A framework + * adapter provides the `adapter` and `devPreamble` options as a preset, e.g. `reactIslands` of + * wicket-islands-react/vite. */ export default function wicketIslands(options: WicketIslandsOptions): Plugin; diff --git a/wicket-experimental/wicket-islands/npm/packages/vite-plugin/src/index.js b/wicket-experimental/wicket-islands/npm/packages/vite-plugin/src/index.js index 3e52f8cbf2..cd4e91eddd 100644 --- a/wicket-experimental/wicket-islands/npm/packages/vite-plugin/src/index.js +++ b/wicket-experimental/wicket-islands/npm/packages/vite-plugin/src/index.js @@ -16,7 +16,6 @@ */ import path from 'node:path'; -import { normalizePath } from 'vite'; const TYPE_PATTERN = /^[A-Za-z0-9_-]+$/; const ENTRY_PREFIX = 'virtual:wicket-island:'; @@ -30,8 +29,9 @@ const DEV_PATH = '/@wicket-islands/'; * Wicket application running in development mode. * * Each island type becomes an input of the build named after the type, so Wicket finds its - * entry in the manifest. Its entry module imports the island's module and registers it with the - * runtime. In development, the module for a type is served at `/@wicket-islands/<type>`. + * entry in the manifest. Its entry module imports the island's module, turns its default export + * into an island with the adapter's `defineIsland` when an adapter is given, and registers it with + * the runtime. In development, the entry for a type is served at `/@wicket-islands/<type>`. * * @param {import('./index').WicketIslandsOptions} options * @returns {import('vite').Plugin} @@ -59,6 +59,9 @@ export default function wicketIslands(options) { input: Object.fromEntries(Object.keys(islands) .map(type => [type, ENTRY_PREFIX + type])) } + }, + optimizeDeps: { + entries: Object.values(islands) } }; }, @@ -94,9 +97,15 @@ export default function wicketIslands(options) { lines.push(`import ${JSON.stringify(PREAMBLE_ID)};`); } lines.push( - `import island from ${JSON.stringify(normalizePath(path.resolve(root, file)))};`, - `import { registerIsland } from 'wicket-islands';`, - `registerIsland(${JSON.stringify(type)}, island);`); + `import island from ${JSON.stringify(toPosixPath(path.resolve(root, file)))};`, + `import { registerIsland } from 'wicket-islands';`); + if (options.adapter) { + lines.push( + `import { defineIsland } from ${JSON.stringify(options.adapter)};`, + `registerIsland(${JSON.stringify(type)}, defineIsland(island));`); + } else { + lines.push(`registerIsland(${JSON.stringify(type)}, island);`); + } return lines.join('\n'); }, @@ -113,3 +122,11 @@ export default function wicketIslands(options) { } }; } + +/** + * @param {string} file + * @returns {string} + */ +function toPosixPath(file) { + return file.split(path.sep).join('/'); +} diff --git a/wicket-experimental/wicket-islands/npm/packages/vite-plugin/test/plugin.test.ts b/wicket-experimental/wicket-islands/npm/packages/vite-plugin/test/plugin.test.ts index eadc550932..ed988dde4a 100644 --- a/wicket-experimental/wicket-islands/npm/packages/vite-plugin/test/plugin.test.ts +++ b/wicket-experimental/wicket-islands/npm/packages/vite-plugin/test/plugin.test.ts @@ -26,9 +26,10 @@ function hook(plugin: object, name: string): Hook { return (plugin as Record<string, Hook>)[name]; } -function plugin(command: 'build' | 'serve', devPreamble?: string) { +function plugin(command: 'build' | 'serve', devPreamble?: string, adapter?: string) { const instance = wicketIslands({ islands: { 'treasure-board': 'src/islands/TreasureBoard.tsx' }, + adapter, devPreamble }); const config = hook(instance, 'config')({}, { command, mode: 'development' }); @@ -44,10 +45,22 @@ describe('wicketIslands', () => { build: { manifest: true, rollupOptions: { input: { 'treasure-board': 'virtual:wicket-island:treasure-board' } } - } + }, + optimizeDeps: { entries: ['src/islands/TreasureBoard.tsx'] } }); }); + it('wraps the default export with the adapter\'s defineIsland', () => { + const { instance } = plugin('build', undefined, 'wicket-islands-react'); + + expect(hook(instance, 'load')('\0wicket-island:treasure-board')).toBe([ + 'import island from "/app/src/islands/TreasureBoard.tsx";', + 'import { registerIsland } from \'wicket-islands\';', + 'import { defineIsland } from "wicket-islands-react";', + 'registerIsland("treasure-board", defineIsland(island));' + ].join('\n')); + }); + it('generates an entry that registers the island module', () => { const { instance } = plugin('build', 'preamble();'); const id = hook(instance, 'resolveId')('virtual:wicket-island:treasure-board'); 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 340d3c2684..537b1ebbd3 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 @@ -210,6 +210,16 @@ public class Island<P> extends WebComponent implements IGenericComponent<P, Isla return endpoint.handler().handle(request, call); } + /** + * Lets calls reach a page Wicket recreated after the original expired. The recreated island has + * a new key, so the call is answered as expired instead of being handled. + */ + @Override + public boolean canCallListenerAfterExpiry() + { + return true; + } + @Override protected void onComponentTag(ComponentTag tag) { diff --git a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandAnswer.java b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandAnswer.java new file mode 100644 index 0000000000..bfba9e9e70 --- /dev/null +++ b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandAnswer.java @@ -0,0 +1,58 @@ +/* + * 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 java.util.List; + +import org.apache.wicket.islands.serializer.IIslandSerializer; + +/** + * Builds the answer to an island call: the value of the data entry the client runtime reads. + */ +final class IslandAnswer +{ + static final String DATA_NAME = "wicket-islands"; + + static final String EXPIRED_MESSAGE = "The page has expired or changed. Reload it to continue."; + + private IslandAnswer() + { + } + + static String success(IIslandSerializer serializer, String callId, Object value, + List<String> invalidations) + { + return answer(serializer, callId, "\"ok\":true,\"value\":" + serializer.toJson(value), + invalidations); + } + + static String failure(IIslandSerializer serializer, String callId, String kind, + List<String> messages, List<String> invalidations) + { + return answer(serializer, callId, + "\"ok\":false,\"error\":{\"kind\":" + serializer.toJson(kind) + ",\"messages\":" + + serializer.toJson(messages) + "}", + invalidations); + } + + private static String answer(IIslandSerializer serializer, String callId, String outcome, + List<String> invalidations) + { + return "{\"call\":" + serializer.toJson(callId) + "," + outcome + ",\"invalidate\":" + + serializer.toJson(invalidations) + "}"; + } +} diff --git a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandCallFailureListener.java b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandCallFailureListener.java new file mode 100644 index 0000000000..40772dbb90 --- /dev/null +++ b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandCallFailureListener.java @@ -0,0 +1,94 @@ +/* + * 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 java.util.List; + +import org.apache.wicket.authorization.AuthorizationException; +import org.apache.wicket.core.request.handler.ComponentNotFoundException; +import org.apache.wicket.core.request.handler.ListenerInvocationNotAllowedException; +import org.apache.wicket.core.request.mapper.StalePageException; +import org.apache.wicket.protocol.http.PageExpiredException; +import org.apache.wicket.request.IRequestCycle; +import org.apache.wicket.request.IRequestHandler; +import org.apache.wicket.request.cycle.IRequestCycleListener; +import org.apache.wicket.request.cycle.RequestCycle; +import org.apache.wicket.request.http.WebRequest; +import org.apache.wicket.request.http.WebResponse; + +/** + * Answers an island call that fails before it reaches its island, because the page expired or + * changed, or the call is not allowed. Without it, Wicket would redirect the browser to an error + * page or a re-rendered page, and the island would never learn what happened to its call. + */ +final class IslandCallFailureListener implements IRequestCycleListener +{ + @Override + public IRequestHandler onException(RequestCycle cycle, Exception ex) + { + if (!(cycle.getRequest() instanceof WebRequest request) || !request.isAjax()) + { + return null; + } + String callId = request.getPostParameters() + .getParameterValue(IslandEndpointBehavior.PARAM_CALL_ID) + .toOptionalString(); + if (callId == null) + { + return null; + } + + String kind; + String message; + if (ex instanceof PageExpiredException || ex instanceof StalePageException || + ex instanceof ComponentNotFoundException) + { + kind = "expired"; + message = IslandAnswer.EXPIRED_MESSAGE; + } + else if (ex instanceof ListenerInvocationNotAllowedException || + ex instanceof AuthorizationException) + { + kind = "forbidden"; + message = "The call is not allowed."; + } + else + { + return null; + } + + return new AnswerHandler(IslandAnswer.failure(IslandSettings.get().getSerializer(), callId, + kind, List.of(message), List.of())); + } + + /** + * Writes an Ajax response that holds nothing but the answer. + */ + private record AnswerHandler(String answer) implements IRequestHandler + { + @Override + public void respond(IRequestCycle requestCycle) + { + WebResponse response = (WebResponse)requestCycle.getResponse(); + response.setContentType("text/xml; charset=UTF-8"); + response.disableCaching(); + response.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?><ajax-response><data name=\"" + + IslandAnswer.DATA_NAME + "\"><![CDATA[" + answer.replace("]]>", "]]]]><![CDATA[>") + + "]]></data></ajax-response>"); + } + } +} diff --git a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandEndpointBehavior.java b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandEndpointBehavior.java index 5198dce4a9..0046fca296 100644 --- a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandEndpointBehavior.java +++ b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandEndpointBehavior.java @@ -48,7 +48,7 @@ final class IslandEndpointBehavior extends AbstractDefaultAjaxBehavior static final String PARAM_PAYLOAD = "island-payload"; - static final String DATA_NAME = "wicket-islands"; + static final String PARAM_KEY = "island-key"; @Override protected void updateAjaxAttributes(AjaxRequestAttributes attributes) @@ -71,29 +71,42 @@ final class IslandEndpointBehavior extends AbstractDefaultAjaxBehavior String callId = parameters.getParameterValue(PARAM_CALL_ID).toString(""); String name = parameters.getParameterValue(PARAM_CALL).toString(""); String payload = parameters.getParameterValue(PARAM_PAYLOAD).toOptionalString(); + String key = parameters.getParameterValue(PARAM_KEY).toString(""); IIslandSerializer serializer = IslandSettings.get().getSerializer(); IslandCall call = new IslandCall(island, target); + List<String> invalidations = call.getInvalidations(); + + String answer; + if (!island.getKey().equals(key)) + { + answer = IslandAnswer.failure(serializer, callId, "expired", + List.of(IslandAnswer.EXPIRED_MESSAGE), invalidations); + target.addData(IslandAnswer.DATA_NAME, answer); + return; + } - String outcome; try { Object result = island.invoke(name, payload, call); - outcome = "\"ok\":true,\"value\":" + serializer.toJson(result); + answer = IslandAnswer.success(serializer, callId, result, invalidations); } catch (IslandCallRejectedException e) { - outcome = failure(serializer, "invalid", e.getMessages()); + answer = IslandAnswer.failure(serializer, callId, "invalid", e.getMessages(), + invalidations); } catch (IslandSerializationException e) { LOG.debug("Island call '{}' on {} failed to (de)serialize", name, island.getPath(), e); - outcome = failure(serializer, "invalid", - List.of(detail(e, "The call's payload or result could not be converted."))); + answer = IslandAnswer.failure(serializer, callId, "invalid", + List.of(detail(e, "The call's payload or result could not be converted.")), + invalidations); } catch (AuthorizationException e) { - outcome = failure(serializer, "forbidden", List.of("The call is not allowed.")); + answer = IslandAnswer.failure(serializer, callId, "forbidden", + List.of("The call is not allowed."), invalidations); } catch (ReplaceHandlerException e) { @@ -102,18 +115,11 @@ final class IslandEndpointBehavior extends AbstractDefaultAjaxBehavior catch (RuntimeException e) { LOG.error("Island call '{}' on {} failed", name, island.getPath(), e); - outcome = failure(serializer, "error", - List.of(detail(e, "The call failed on the server."))); + answer = IslandAnswer.failure(serializer, callId, "error", + List.of(detail(e, "The call failed on the server.")), invalidations); } - target.addData(DATA_NAME, "{\"call\":" + serializer.toJson(callId) + "," + outcome + - ",\"invalidate\":" + serializer.toJson(call.getInvalidations()) + "}"); - } - - private static String failure(IIslandSerializer serializer, String kind, List<String> messages) - { - return "\"ok\":false,\"error\":{\"kind\":" + serializer.toJson(kind) + ",\"messages\":" + - serializer.toJson(messages) + "}"; + target.addData(IslandAnswer.DATA_NAME, answer); } private static String detail(RuntimeException e, String message) 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 afb9256026..1d8ffd40e1 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 @@ -73,8 +73,11 @@ public class IslandSettings private volatile ViteManifestModuleLoader manifestModuleLoader; + private ResourceReference assets; + /** - * Installs the settings in an application and mounts the resource serving the built files. + * Installs the settings in an application, mounts the resource serving the built files and + * registers the listener that answers island calls failing before they reach their island. * * @param application * the application @@ -85,18 +88,19 @@ public class IslandSettings Args.notNull(application, "application"); IslandSettings settings = new IslandSettings(); - application.setMetaData(KEY, settings); - application.mountResource(MOUNT_PATH, - new ResourceReference(IslandSettings.class, "assets") + settings.assets = new ResourceReference(IslandSettings.class, "assets") + { + private static final long serialVersionUID = 1L; + + @Override + public IResource getResource() { - private static final long serialVersionUID = 1L; - - @Override - public IResource getResource() - { - return new IslandAssetResource(settings::getManifestModuleLoader); - } - }); + return new IslandAssetResource(settings::getManifestModuleLoader); + } + }; + application.setMetaData(KEY, settings); + application.mountResource(MOUNT_PATH, settings.assets); + application.getRequestCycleListeners().add(new IslandCallFailureListener()); return settings; } @@ -210,7 +214,7 @@ public class IslandSettings ViteManifestModuleLoader loader = manifestModuleLoader; if (loader == null) { - loader = new ViteManifestModuleLoader(basePath, manifestFile, MOUNT_PATH + "/"); + loader = new ViteManifestModuleLoader(basePath, manifestFile, assets); manifestModuleLoader = loader; } return loader; diff --git a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/modules/ViteDevServerModuleLoader.java b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/modules/ViteDevServerModuleLoader.java index fb8747edb9..65c459b67f 100644 --- a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/modules/ViteDevServerModuleLoader.java +++ b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/modules/ViteDevServerModuleLoader.java @@ -16,9 +16,13 @@ */ package org.apache.wicket.islands.modules; +import org.apache.wicket.csp.ContentSecurityPolicySettings; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.head.JavaScriptHeaderItem; import org.apache.wicket.markup.head.JavaScriptReferenceType; +import org.apache.wicket.markup.head.MetaDataHeaderItem; +import org.apache.wicket.protocol.http.WebApplication; +import org.apache.wicket.request.cycle.RequestCycle; import org.apache.wicket.util.lang.Args; import org.apache.wicket.util.string.Strings; @@ -27,8 +31,10 @@ import org.apache.wicket.util.string.Strings; * development. * <p> * Renders Vite's client and, for each island type, the module the Wicket Islands Vite plugin - * serves at <code>/@wicket-islands/<type></code>. The dev server's origin must be allowed by - * the page's Content Security Policy for scripts and connections. + * serves at <code>/@wicket-islands/<type></code>. When the page has a Content Security Policy + * with nonces, it also renders the nonce in the <code>csp-nonce</code> meta tag Vite reads, so the + * style elements Vite injects carry it. The dev server's origin must be allowed for connections, + * for Vite's hot module replacement. * * @since 12.0.0 */ @@ -48,6 +54,13 @@ public class ViteDevServerModuleLoader implements IIslandModuleLoader @Override public void renderHead(String islandType, IHeaderResponse response) { + ContentSecurityPolicySettings csp = WebApplication.get().getCspSettings(); + if (csp.isNonceEnabled()) + { + response.render(new MetaDataHeaderItem(MetaDataHeaderItem.META_TAG) + .addTagAttribute("property", "csp-nonce") + .addTagAttribute("nonce", csp.getNonce(RequestCycle.get()))); + } response.render(JavaScriptHeaderItem.forUrl(devServerUrl + "/@vite/client") .setType(JavaScriptReferenceType.MODULE)); response.render(JavaScriptHeaderItem.forUrl(devServerUrl + "/@wicket-islands/" + islandType) diff --git a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/modules/ViteManifestModuleLoader.java b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/modules/ViteManifestModuleLoader.java index 00aeaff9e9..9083a7dcbb 100644 --- a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/modules/ViteManifestModuleLoader.java +++ b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/modules/ViteManifestModuleLoader.java @@ -26,6 +26,8 @@ import org.apache.wicket.markup.head.CssHeaderItem; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.head.JavaScriptHeaderItem; import org.apache.wicket.markup.head.JavaScriptReferenceType; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.apache.wicket.request.resource.ResourceReference; import org.apache.wicket.util.lang.Args; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -35,8 +37,8 @@ import org.slf4j.LoggerFactory; * <p> * The build's output directory is expected under a base path on the classpath, with Vite's * manifest in it. Each island type is an input of the build whose name is the island type; its - * entry module and style sheets are rendered from the manifest, and served by - * {@link IslandAssetResource}. + * entry module and style sheets are rendered from the manifest, and served by an + * {@link IslandAssetResource} mounted under the given reference. * * @since 12.0.0 */ @@ -48,7 +50,7 @@ public class ViteManifestModuleLoader implements IIslandModuleLoader private final String manifestFile; - private final String urlPrefix; + private final ResourceReference assets; private volatile ViteManifest manifest; @@ -59,15 +61,15 @@ public class ViteManifestModuleLoader implements IIslandModuleLoader * the classpath location of the build's output directory, ending in a slash * @param manifestFile * the manifest, relative to the base path - * @param urlPrefix - * the context-relative URL under which {@link IslandAssetResource} serves the - * files, ending in a slash + * @param assets + * the mounted reference of the {@link IslandAssetResource} serving the files; the + * path of a file is passed as its indexed parameters */ - public ViteManifestModuleLoader(String basePath, String manifestFile, String urlPrefix) + public ViteManifestModuleLoader(String basePath, String manifestFile, ResourceReference assets) { this.basePath = Args.notEmpty(basePath, "basePath"); this.manifestFile = Args.notEmpty(manifestFile, "manifestFile"); - this.urlPrefix = Args.notEmpty(urlPrefix, "urlPrefix"); + this.assets = Args.notNull(assets, "assets"); } /** @@ -134,9 +136,21 @@ public class ViteManifestModuleLoader implements IIslandModuleLoader for (String css : current.collectCss(key)) { - response.render(CssHeaderItem.forUrl(urlPrefix + css)); + response.render(CssHeaderItem.forReference(assets, toParameters(css), null)); } - response.render(JavaScriptHeaderItem.forUrl(urlPrefix + current.getChunk(key).file()) + response.render(JavaScriptHeaderItem + .forReference(assets, toParameters(current.getChunk(key).file()), null) .setType(JavaScriptReferenceType.MODULE)); } + + private static PageParameters toParameters(String file) + { + PageParameters parameters = new PageParameters(); + String[] segments = file.split("/"); + for (int i = 0; i < segments.length; i++) + { + parameters.set(i, segments[i]); + } + return parameters; + } } diff --git a/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/IslandCallFailureTest.java b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/IslandCallFailureTest.java new file mode 100644 index 0000000000..9451fd1110 --- /dev/null +++ b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/IslandCallFailureTest.java @@ -0,0 +1,105 @@ +/* + * 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 java.util.Map; + +import org.apache.wicket.request.Url; +import org.junit.jupiter.api.Test; + +/** + * Island calls that cannot reach their island are answered, not redirected. + */ +class IslandCallFailureTest extends IslandTestCase +{ + @Test + void callWithAnotherKeyIsExpired() + { + IslandTestPage page = tester.startPage(IslandTestPage.class); + + prepareCall("add", "1", "{\"amount\":1}", "not-the-key"); + tester.executeBehavior(page.island.getBehaviors(IslandEndpointBehavior.class).get(0)); + + assertEquals("expired", error(answer()).get("kind")); + assertEquals("count 0", page.label.getDefaultModelObjectAsString()); + } + + @Test + void callOnARecreatedPageIsExpired() + { + IslandTestPage page = tester.startPage(IslandTestPage.class); + Url url = callbackUrl(page); + String key = page.island.getKey(); + tester.getSession().getPageManager().clear(); + + prepareCall("add", "1", "{\"amount\":1}", key); + tester.executeAjaxUrl(url); + + assertEquals("expired", error(answer()).get("kind")); + } + + @Test + void callOnAnExpiredPageIsExpired() + { + IslandTestPage page = tester.startPage(new NonBookmarkableIslandPage("x")); + Url url = callbackUrl(page); + String key = page.island.getKey(); + tester.getSession().getPageManager().clear(); + + prepareCall("add", "1", "{\"amount\":1}", key); + tester.executeAjaxUrl(url); + + assertEquals("expired", error(answer()).get("kind")); + } + + @Test + void callOnAStalePageIsExpired() + { + IslandTestPage page = tester.startPage(IslandTestPage.class); + Url url = callbackUrl(page); + tester.startPage(page); + + prepareCall("add", "1", "{\"amount\":1}", page.island.getKey()); + tester.executeAjaxUrl(url); + + assertEquals("expired", error(answer()).get("kind")); + } + + @Test + void callOnAHiddenIslandIsForbidden() + { + IslandTestPage page = tester.startPage(IslandTestPage.class); + Url url = callbackUrl(page); + page.island.setVisible(false); + + prepareCall("add", "1", "{\"amount\":1}", page.island.getKey()); + tester.executeAjaxUrl(url); + + Map<String, Object> error = error(answer()); + assertEquals("forbidden", error.get("kind")); + assertFalse(tester.getLastResponseAsString().contains("count 1")); + } + + private static Url callbackUrl(IslandTestPage page) + { + return Url.parse( + page.island.getBehaviors(IslandEndpointBehavior.class).get(0).getCallbackUrl()); + } +} diff --git a/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/IslandDevServerTest.java b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/IslandDevServerTest.java index 0511a44d12..506f2dd52c 100644 --- a/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/IslandDevServerTest.java +++ b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/IslandDevServerTest.java @@ -19,6 +19,8 @@ package org.apache.wicket.islands; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.util.regex.Pattern; + import org.junit.jupiter.api.Test; /** @@ -46,4 +48,17 @@ class IslandDevServerTest extends IslandTestCase response); assertFalse(response.contains("test-island-abc123.js"), response); } + + @Test + void rendersTheCspNonceForVite() + { + tester.getApplication().getCspSettings().blocking().strict(); + + tester.startPage(IslandTestPage.class); + + String response = tester.getLastResponseAsString(); + assertTrue(Pattern.compile("<meta property=\"csp-nonce\" nonce=\"[^\"]+\"") + .matcher(response) + .find(), response); + } } 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 99b4e4079f..fb55439c56 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 @@ -28,6 +28,7 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.wicket.model.Model; +import org.apache.wicket.request.Url; import org.apache.wicket.util.tester.TagTester; import org.junit.jupiter.api.Test; @@ -122,6 +123,22 @@ class IslandRenderTest extends IslandTestCase assertTrue(shared > 0 && own > shared, "imported style sheets come first: " + response); } + @Test + void renderedModuleUrlServesTheModule() + { + tester.startPage(IslandTestPage.class); + Url pageUrl = tester.getLastRequest().getUrl(); + Matcher src = Pattern.compile("<script type=\"module\" src=\"([^\"]+)\"") + .matcher(tester.getLastResponseAsString()); + assertTrue(src.find()); + + pageUrl.resolveRelative(Url.parse(src.group(1))); + tester.executeUrl(pageUrl.toString()); + + assertEquals(200, tester.getLastResponse().getStatus()); + assertEquals("export default {};\n", tester.getLastResponseAsString()); + } + @Test void entryMissingFromTheManifestFails() { diff --git a/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/IslandTestCase.java b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/IslandTestCase.java index eb36c8f8f4..bbdec8ec75 100644 --- a/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/IslandTestCase.java +++ b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/IslandTestCase.java @@ -83,11 +83,19 @@ abstract class IslandTestCase extends WicketTestCase * * @return the island's answer */ - @SuppressWarnings("unchecked") Map<String, Object> call(String name, String callId, String payload) { IslandTestPage page = (IslandTestPage)tester.getLastRenderedPage(); + prepareCall(name, callId, payload, page.island.getKey()); + tester.executeBehavior(page.island.getBehaviors(IslandEndpointBehavior.class).get(0)); + return answer(); + } + + void prepareCall(String name, String callId, String payload, String key) + { tester.getRequest().setMethod("POST"); + tester.getRequest().getPostParameters().setParameterValue(IslandEndpointBehavior.PARAM_KEY, + key); tester.getRequest().getPostParameters().setParameterValue(IslandEndpointBehavior.PARAM_CALL, name); tester.getRequest().getPostParameters().setParameterValue( @@ -97,8 +105,14 @@ abstract class IslandTestCase extends WicketTestCase tester.getRequest().getPostParameters().setParameterValue( IslandEndpointBehavior.PARAM_PAYLOAD, payload); } - tester.executeBehavior(page.island.getBehaviors(IslandEndpointBehavior.class).get(0)); + } + /** + * @return the answer in the last response + */ + @SuppressWarnings("unchecked") + Map<String, Object> answer() + { String response = tester.getLastResponseAsString(); Matcher matcher = DATA.matcher(response); assertTrue(matcher.find(), response); diff --git a/wicket-experimental/wicket-islands/npm/packages/react/src/preamble.d.ts b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/NonBookmarkableIslandPage.java similarity index 74% rename from wicket-experimental/wicket-islands/npm/packages/react/src/preamble.d.ts rename to wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/NonBookmarkableIslandPage.java index f1350e5fdc..36b00b09c8 100644 --- a/wicket-experimental/wicket-islands/npm/packages/react/src/preamble.d.ts +++ b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/NonBookmarkableIslandPage.java @@ -14,8 +14,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +package org.apache.wicket.islands; /** - * Installs React Fast Refresh in a page Vite does not serve itself. + * An {@link IslandTestPage} Wicket cannot recreate once it expired. */ -export declare const reactRefreshPreamble: string; +public class NonBookmarkableIslandPage extends IslandTestPage +{ + private static final long serialVersionUID = 1L; + + public NonBookmarkableIslandPage(String unused) + { + } +}
