@warlock.js/web 5.1.0 → 5.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +174 -0
- package/README.md +126 -12
- package/esm/build/contribution.d.mts +11 -14
- package/esm/build/contribution.mjs +46 -58
- package/esm/build/contribution.mjs.map +1 -1
- package/esm/build/discover-pages.mjs +105 -45
- package/esm/build/discover-pages.mjs.map +1 -1
- package/esm/build/generate-client-registry.mjs +47 -13
- package/esm/build/generate-client-registry.mjs.map +1 -1
- package/esm/build/generate-pages-barrel.mjs +55 -13
- package/esm/build/generate-pages-barrel.mjs.map +1 -1
- package/esm/build/page-default-export.mjs +48 -0
- package/esm/build/page-default-export.mjs.map +1 -0
- package/esm/build/page-routes-manifest.mjs +21 -0
- package/esm/build/page-routes-manifest.mjs.map +1 -0
- package/esm/build/public-files.mjs +45 -0
- package/esm/build/public-files.mjs.map +1 -0
- package/esm/build/read-route-exports.mjs +1 -1
- package/esm/build/read-route-exports.mjs.map +1 -1
- package/esm/client/build-hydrated-tree.mjs +40 -9
- package/esm/client/build-hydrated-tree.mjs.map +1 -1
- package/esm/client/hydrate-page.mjs +1 -1
- package/esm/client/hydrate-page.mjs.map +1 -1
- package/esm/client/navigation/current-route.d.mts +1 -1
- package/esm/client/navigation/current-route.mjs +1 -1
- package/esm/client/navigation/current-route.mjs.map +1 -1
- package/esm/client/navigation/fetch-page-data.mjs +1 -1
- package/esm/client/navigation/fetch-page-data.mjs.map +1 -1
- package/esm/client/navigation/navigation-root.mjs +1 -1
- package/esm/client/navigation/navigation-root.mjs.map +1 -1
- package/esm/client/navigation/prefetch.mjs +1 -1
- package/esm/client/navigation/prefetch.mjs.map +1 -1
- package/esm/client/navigation/refresh.d.mts +1 -1
- package/esm/client/navigation/refresh.mjs +1 -1
- package/esm/client/navigation/refresh.mjs.map +1 -1
- package/esm/client/navigation/scroll-to-fragment.mjs +1 -1
- package/esm/client/navigation/scroll-to-fragment.mjs.map +1 -1
- package/esm/client/navigation/verbs.d.mts +1 -1
- package/esm/client/navigation/verbs.mjs +1 -1
- package/esm/client/navigation/verbs.mjs.map +1 -1
- package/esm/client/runtime/index.d.mts +2 -1
- package/esm/client/runtime/index.mjs +2 -1
- package/esm/client/runtime/manifest.d.mts +1 -1
- package/esm/client/runtime/manifest.mjs +3 -2
- package/esm/client/runtime/manifest.mjs.map +1 -1
- package/esm/client/runtime/matcher.d.mts +13 -1
- package/esm/client/runtime/matcher.mjs +13 -1
- package/esm/client/runtime/matcher.mjs.map +1 -1
- package/esm/client/runtime/types.d.mts +15 -2
- package/esm/components/default-app.mjs +1 -1
- package/esm/components/default-app.mjs.map +1 -1
- package/esm/components/document-context.d.mts +40 -2
- package/esm/components/document-context.mjs +1 -1
- package/esm/components/document-context.mjs.map +1 -1
- package/esm/components/head.d.mts +1 -1
- package/esm/components/head.mjs +1 -1
- package/esm/components/head.mjs.map +1 -1
- package/esm/components/link.d.mts +1 -1
- package/esm/components/link.mjs +1 -1
- package/esm/components/link.mjs.map +1 -1
- package/esm/components/scripts.d.mts +1 -1
- package/esm/components/scripts.mjs +4 -2
- package/esm/components/scripts.mjs.map +1 -1
- package/esm/context.d.mts +6 -102
- package/esm/hydration/index.mjs +1 -1
- package/esm/hydration/index.mjs.map +1 -1
- package/esm/hydration-payload.d.mts +1 -1
- package/esm/hydration-payload.mjs +37 -8
- package/esm/hydration-payload.mjs.map +1 -1
- package/esm/index.d.mts +4 -3
- package/esm/loaders.d.mts +7 -36
- package/esm/metadata.d.mts +1 -1
- package/esm/metadata.mjs +1 -1
- package/esm/metadata.mjs.map +1 -1
- package/esm/props.d.mts +16 -8
- package/esm/route.d.mts +2 -17
- package/esm/routing/compose-route-path.d.mts +1 -1
- package/esm/routing/compose-route-path.mjs +1 -1
- package/esm/routing/compose-route-path.mjs.map +1 -1
- package/esm/routing/data-request.mjs +1 -1
- package/esm/routing/data-request.mjs.map +1 -1
- package/esm/routing/filesystem-route.mjs +45 -0
- package/esm/routing/filesystem-route.mjs.map +1 -0
- package/esm/routing/layout-policy.mjs +1 -1
- package/esm/routing/layout-policy.mjs.map +1 -1
- package/esm/routing/navigator.mjs +1 -1
- package/esm/routing/navigator.mjs.map +1 -1
- package/esm/routing/query-string.d.mts +1 -1
- package/esm/routing/query-string.mjs +1 -1
- package/esm/routing/query-string.mjs.map +1 -1
- package/esm/routing/route-identity.mjs +1 -1
- package/esm/routing/route-identity.mjs.map +1 -1
- package/esm/routing/route-table.d.mts +1 -1
- package/esm/routing/route-table.mjs +1 -1
- package/esm/routing/route-table.mjs.map +1 -1
- package/esm/routing/router-events.d.mts +1 -1
- package/esm/routing/router-events.mjs +1 -1
- package/esm/routing/router-events.mjs.map +1 -1
- package/esm/routing/url-fragment.mjs +1 -1
- package/esm/routing/url-fragment.mjs.map +1 -1
- package/esm/runtime/register-modules.d.mts +19 -0
- package/esm/runtime/register-modules.mjs +22 -0
- package/esm/runtime/register-modules.mjs.map +1 -0
- package/esm/server/build-hydration-payload.mjs +2 -1
- package/esm/server/build-hydration-payload.mjs.map +1 -1
- package/esm/server/client-asset-url-prefix.d.mts +1 -1
- package/esm/server/client-asset-url-prefix.mjs +1 -1
- package/esm/server/client-asset-url-prefix.mjs.map +1 -1
- package/esm/server/create-page-module-loader.d.mts +1 -1
- package/esm/server/create-page-module-loader.mjs +2 -1
- package/esm/server/create-page-module-loader.mjs.map +1 -1
- package/esm/server/create-page-route-handler.d.mts +31 -6
- package/esm/server/create-page-route-handler.mjs +128 -43
- package/esm/server/create-page-route-handler.mjs.map +1 -1
- package/esm/server/dev-server.mjs +2 -13
- package/esm/server/dev-server.mjs.map +1 -1
- package/esm/server/error-page.d.mts +14 -0
- package/esm/server/error-page.mjs +39 -0
- package/esm/server/error-page.mjs.map +1 -0
- package/esm/server/execute-page-request.d.mts +7 -4
- package/esm/server/execute-page-request.mjs +79 -80
- package/esm/server/execute-page-request.mjs.map +1 -1
- package/esm/server/execute-page-request.types.d.mts +33 -92
- package/esm/server/hydration-client-url.d.mts +1 -1
- package/esm/server/hydration-client-url.mjs +2 -2
- package/esm/server/hydration-client-url.mjs.map +1 -1
- package/esm/server/index.d.mts +5 -5
- package/esm/server/index.mjs +3 -4
- package/esm/server/install-page-routes-from-manifest.d.mts +17 -7
- package/esm/server/install-page-routes-from-manifest.mjs +71 -10
- package/esm/server/install-page-routes-from-manifest.mjs.map +1 -1
- package/esm/server/install-page-routes.d.mts +32 -15
- package/esm/server/install-page-routes.mjs +91 -39
- package/esm/server/install-page-routes.mjs.map +1 -1
- package/esm/server/install-production-page-routes.mjs +3 -36
- package/esm/server/install-production-page-routes.mjs.map +1 -1
- package/esm/server/match-page-route.mjs +2 -2
- package/esm/server/match-page-route.mjs.map +1 -1
- package/esm/server/not-found-page.d.mts +1 -1
- package/esm/server/not-found-page.mjs +2 -2
- package/esm/server/not-found-page.mjs.map +1 -1
- package/esm/server/page-context.d.mts +3 -9
- package/esm/server/page-context.mjs +3 -16
- package/esm/server/page-context.mjs.map +1 -1
- package/esm/server/page-file-change.mjs +77 -0
- package/esm/server/page-file-change.mjs.map +1 -0
- package/esm/server/page-manifest.d.mts +25 -10
- package/esm/server/page-manifest.mjs +1 -1
- package/esm/server/page-manifest.mjs.map +1 -1
- package/esm/server/page-render-bundle.mjs +38 -0
- package/esm/server/page-render-bundle.mjs.map +1 -0
- package/esm/server/page-route-reload.mjs +54 -0
- package/esm/server/page-route-reload.mjs.map +1 -0
- package/esm/server/register-production-public-files.mjs +40 -0
- package/esm/server/register-production-public-files.mjs.map +1 -0
- package/esm/server/render-page.d.mts +11 -14
- package/esm/server/render-page.mjs +154 -28
- package/esm/server/render-page.mjs.map +1 -1
- package/esm/server/resolve-page-metadata.mjs +2 -2
- package/esm/server/resolve-page-metadata.mjs.map +1 -1
- package/esm/server/resolve-validation-data.mjs +1 -1
- package/esm/server/resolve-validation-data.mjs.map +1 -1
- package/esm/server/settle-page-response.d.mts +58 -1
- package/esm/server/settle-page-response.mjs +111 -46
- package/esm/server/settle-page-response.mjs.map +1 -1
- package/esm/server/stylesheet-urls.d.mts +41 -30
- package/esm/server/stylesheet-urls.mjs +137 -52
- package/esm/server/stylesheet-urls.mjs.map +1 -1
- package/esm/server/unregistered-pages.mjs +42 -0
- package/esm/server/unregistered-pages.mjs.map +1 -0
- package/esm/server/web-connector-factory.d.mts +2 -3
- package/esm/server/web-connector-factory.mjs +7 -6
- package/esm/server/web-connector-factory.mjs.map +1 -1
- package/esm/server/web-connector.d.mts +1 -1
- package/esm/server/web-connector.mjs +138 -18
- package/esm/server/web-connector.mjs.map +1 -1
- package/esm/shared.d.mts +18 -3
- package/esm/shared.mjs +3 -7
- package/esm/shared.mjs.map +1 -1
- package/esm/validation.d.mts +1 -1
- package/esm/vite/app-convention-aliases.mjs +1 -1
- package/esm/vite/app-convention-aliases.mjs.map +1 -1
- package/esm/vite/build-client.d.mts +1 -1
- package/esm/vite/build-client.mjs +2 -2
- package/esm/vite/build-client.mjs.map +1 -1
- package/esm/vite/gate-a-resolve.d.mts +1 -1
- package/esm/vite/gate-a-resolve.mjs +67 -13
- package/esm/vite/gate-a-resolve.mjs.map +1 -1
- package/esm/vite/gate-b-secrets.d.mts +1 -1
- package/esm/vite/gate-b-secrets.mjs +35 -17
- package/esm/vite/gate-b-secrets.mjs.map +1 -1
- package/esm/vite/gate-c-verify.d.mts +1 -1
- package/esm/vite/gate-c-verify.mjs +6 -6
- package/esm/vite/gate-c-verify.mjs.map +1 -1
- package/esm/vite/hydration-entries.d.mts +1 -1
- package/esm/vite/hydration-entries.mjs +2 -2
- package/esm/vite/hydration-entries.mjs.map +1 -1
- package/esm/vite/index.d.mts +9 -6
- package/esm/vite/index.mjs +124 -11
- package/esm/vite/index.mjs.map +1 -1
- package/esm/vite/page-registry-plugin.d.mts +22 -3
- package/esm/vite/page-registry-plugin.mjs +48 -14
- package/esm/vite/page-registry-plugin.mjs.map +1 -1
- package/esm/vite/projection.d.mts +2 -2
- package/esm/vite/projection.mjs +38 -15
- package/esm/vite/projection.mjs.map +1 -1
- package/llms-full.txt +220 -56
- package/llms.txt +5 -3
- package/package.json +3 -3
- package/skills/add-web-to-an-app/SKILL.md +3 -3
- package/skills/create-a-page/SKILL.md +117 -10
- package/skills/load-page-data/SKILL.md +92 -12
- package/skills/navigate-on-the-client/SKILL.md +1 -1
- package/skills/serve-styles/SKILL.md +13 -12
- package/skills/use-layouts/SKILL.md +14 -8
- package/skills/write-the-root/SKILL.md +3 -1
- package/esm/server/buffered-response.d.mts +0 -58
- package/esm/server/buffered-response.mjs +0 -115
- package/esm/server/buffered-response.mjs.map +0 -1
|
@@ -1,7 +1,8 @@
|
|
|
1
|
+
import { registerModules } from "../runtime/register-modules.mjs";
|
|
1
2
|
import { loadClientRouteComposition } from "./runtime/manifest.mjs";
|
|
2
3
|
import { createElement } from "react";
|
|
3
4
|
|
|
4
|
-
//#region
|
|
5
|
+
//#region web/src/client/build-hydrated-tree.ts
|
|
5
6
|
/**
|
|
6
7
|
* The hydration COMPOSER: payload + page registry -> the ReactNode to mount.
|
|
7
8
|
*
|
|
@@ -41,6 +42,20 @@ var UnknownHydrationPageNameError = class extends Error {
|
|
|
41
42
|
this.name = "UnknownHydrationPageNameError";
|
|
42
43
|
}
|
|
43
44
|
};
|
|
45
|
+
/**
|
|
46
|
+
* The server selected an app error page, but this browser graph cannot load it.
|
|
47
|
+
* Substituting the ordinary page would execute the component that already
|
|
48
|
+
* failed and hydrate markup the server did not render, so this path fails
|
|
49
|
+
* closed just like an unknown route name.
|
|
50
|
+
*/
|
|
51
|
+
var MissingHydrationErrorPageError = class extends Error {
|
|
52
|
+
pageName;
|
|
53
|
+
constructor(pageName) {
|
|
54
|
+
super(`Warlock hydration aborted: the server selected error.page.tsx for route ${JSON.stringify(pageName)}, but that route's client composition has no ErrorPage module. Rebuild the client page registry so it projects the discovered error page.`);
|
|
55
|
+
this.pageName = pageName;
|
|
56
|
+
this.name = "MissingHydrationErrorPageError";
|
|
57
|
+
}
|
|
58
|
+
};
|
|
44
59
|
function findEntryByName(pages, name) {
|
|
45
60
|
const entry = pages.find((candidate) => candidate.name === name);
|
|
46
61
|
if (entry === void 0) throw new UnknownHydrationPageNameError(name, pages.map((candidate) => candidate.name));
|
|
@@ -69,9 +84,10 @@ function wrap(module, data, shared, children) {
|
|
|
69
84
|
}
|
|
70
85
|
/**
|
|
71
86
|
* Compose the tree the server rendered inside `#root`: ordered layouts wrapping
|
|
72
|
-
* the Page, layouts OUTERMOST FIRST as
|
|
73
|
-
*
|
|
74
|
-
* `
|
|
87
|
+
* the selected Page or ErrorPage leaf, layouts OUTERMOST FIRST as
|
|
88
|
+
* `ClientRouteComposition` declares them. Ordinary levels receive
|
|
89
|
+
* `{ data, shared }`; the error leaf receives the serialized `{ error, status
|
|
90
|
+
* }` payload shape.
|
|
75
91
|
*
|
|
76
92
|
* ── THE APP LEVEL IS DELIBERATELY ABSENT, AND MUST STAY ABSENT ──────────────
|
|
77
93
|
* `ClientRouteComposition.App` and `payload.appData` still exist and are still
|
|
@@ -98,12 +114,27 @@ function wrap(module, data, shared, children) {
|
|
|
98
114
|
*/
|
|
99
115
|
async function buildHydratedTree(pages, payload) {
|
|
100
116
|
const composition = await loadClientRouteComposition(findEntryByName(pages, payload.name));
|
|
117
|
+
const errorPageProps = payload.errorPage;
|
|
118
|
+
const selectedPageModule = errorPageProps === void 0 ? composition.Page : composition.ErrorPage;
|
|
119
|
+
if (selectedPageModule === void 0) throw new MissingHydrationErrorPageError(payload.name);
|
|
120
|
+
registerModules([
|
|
121
|
+
...composition.App === void 0 ? [] : [composition.App],
|
|
122
|
+
...composition.layouts,
|
|
123
|
+
selectedPageModule
|
|
124
|
+
]);
|
|
101
125
|
const { shared } = payload;
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
126
|
+
let element;
|
|
127
|
+
if (errorPageProps === void 0) {
|
|
128
|
+
const Page = componentOf(selectedPageModule);
|
|
129
|
+
element = Page === void 0 ? null : createElement(Page, {
|
|
130
|
+
data: payload.pageData,
|
|
131
|
+
shared,
|
|
132
|
+
params: payload.params ?? {}
|
|
133
|
+
});
|
|
134
|
+
} else {
|
|
135
|
+
const ErrorPage = componentOf(selectedPageModule);
|
|
136
|
+
element = ErrorPage === void 0 ? null : createElement(ErrorPage, errorPageProps);
|
|
137
|
+
}
|
|
107
138
|
for (let index = composition.layouts.length - 1; index >= 0; index -= 1) element = wrap(composition.layouts[index], payload.layoutData, shared, element);
|
|
108
139
|
return element;
|
|
109
140
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build-hydrated-tree.mjs","names":[],"sources":["../../../../../../../web/src/client/build-hydrated-tree.ts"],"sourcesContent":["/**\n * The hydration COMPOSER: payload + page registry -> the ReactNode to mount.\n *\n * It takes the registry as an ARGUMENT and touches no browser global, which is\n * the whole point of it living apart from `index.ts`: every rule below is\n * testable with a hand-built registry, no bundler, no virtual module, no DOM.\n *\n * LOOKUP BY NAME, NEVER BY MATCH. `payload.name` is the identity of the entry\n * the SERVER matched for this exact request (document-context.ts's `name`\n * field). Re-deriving it from `location.pathname` with `matchClientRoute`\n * would be a second implementation of route semantics running against the one\n * request it is hydrating, free to disagree with the server that produced the\n * markup. `matchClientRoute` is for client-side NAVIGATION, where no server\n * answer exists yet.\n */\nimport { createElement, type ComponentType, type ReactNode } from \"react\";\nimport type { HydrationDocumentPayloadSource } from \"../hydration-payload\";\nimport { loadClientRouteComposition } from \"./runtime\";\nimport type { ClientPageEntry, ClientProjectedModule } from \"./runtime/types\";\n\n/** What every composed level receives — the shape `render-page.ts` uses server-side. */\ntype HydratedLevelProps = {\n readonly data: unknown;\n readonly shared: unknown;\n readonly children?: ReactNode;\n};\n\nfunction describeKnownNames(knownPageNames: readonly string[]): string {\n if (knownPageNames.length === 0) return \"The client page registry is empty.\";\n\n return `The registry knows: ${knownPageNames.map((name) => JSON.stringify(name)).join(\", \")}.`;\n}\n\n/**\n * The THIRD hydration failure case, beside an absent and a malformed payload.\n *\n * It fails CLOSED — no default entry, no nearest-path fallback, no silent\n * no-op. A registry that quietly substitutes a page produces a browser showing\n * one page's markup running another page's code, which is precisely the defect\n * this entry point was rewritten to remove; a fallback would reintroduce it\n * wearing a recovery costume. Throwing leaves the server-rendered markup on\n * screen and un-hydrated, which is degraded but honest.\n */\nexport class UnknownHydrationPageNameError extends Error {\n public constructor(\n public readonly pageName: string,\n public readonly knownPageNames: readonly string[],\n ) {\n super(\n `Warlock hydration aborted: the payload names page ${JSON.stringify(pageName)}, which is ` +\n `not in the client page registry. ${describeKnownNames(knownPageNames)} The server ` +\n \"rendered a page this browser bundle does not carry, so the server and client were \" +\n \"built from different page graphs. To fix: rebuild the client bundle, or check that \" +\n \"the page's file still exports a `route` discovery can see.\",\n );\n this.name = \"UnknownHydrationPageNameError\";\n }\n}\n\nfunction findEntryByName(\n pages: readonly ClientPageEntry[],\n name: string,\n): ClientPageEntry {\n const entry = pages.find((candidate) => candidate.name === name);\n\n if (entry === undefined) {\n throw new UnknownHydrationPageNameError(\n name,\n pages.map((candidate) => candidate.name),\n );\n }\n\n return entry;\n}\n\n/**\n * A level's component, or undefined when the module exports no default.\n *\n * Undefined is NOT an error: `render-page.ts:258` and `:279` treat a missing\n * default as a passthrough server-side, and the client tree has to match the\n * markup React is hydrating against — introducing a level here that the server\n * did not render is a hydration mismatch, not a repair.\n */\nfunction componentOf(\n module: ClientProjectedModule,\n): ComponentType<HydratedLevelProps> | undefined {\n const component = module.default;\n\n return typeof component === \"function\"\n ? (component as ComponentType<HydratedLevelProps>)\n : undefined;\n}\n\nfunction wrap(\n module: ClientProjectedModule,\n data: unknown,\n shared: unknown,\n children: ReactNode,\n): ReactNode {\n const Component = componentOf(module);\n\n if (Component === undefined) return children;\n\n return createElement(Component, { data, shared, children });\n}\n\n/**\n * Compose the tree the server rendered inside `#root`: ordered layouts wrapping\n * the Page, layouts OUTERMOST FIRST as `ClientRouteComposition` declares them,\n * each level receiving `{ data, shared }` and every wrapper additionally\n * `children`.\n *\n * ── THE APP LEVEL IS DELIBERATELY ABSENT, AND MUST STAY ABSENT ──────────────\n * `ClientRouteComposition.App` and `payload.appData` still exist and are still\n * carried; they are contracts owned elsewhere. They are simply not part of THIS\n * tree, because App is not part of the markup this tree hydrates against:\n *\n * - Server-side, `render-page.ts`'s `wrapRootward` wraps the page leaf in\n * `[\"layout\", \"app\"]` (`render-page.ts:274`), so the document React renders\n * is `App( Layout( Page ) )`.\n * - The app root is the level that owns `<html>`/`<body>` and renders\n * `<div id=\"root\">{children}</div>` inside the body. So App CONTAINS the\n * mount point — the markup actually inside `#root` is `Layout( Page )`.\n * - `hydrate-page.tsx` mounts at `#root` and nowhere else.\n *\n * Composing App here would therefore hydrate a whole `<html>` document inside a\n * `<div>` the server filled with a layout: a guaranteed hydration mismatch. If\n * you arrived here from the optional `App?` on the composition type and are\n * about to \"complete\" the tree with it — that would be the defect, not the\n * omission.\n *\n * `load()` is awaited exactly ONCE per hydration and its result reused for all\n * levels — the composition arrives whole, so calling it per layout would be\n * one network waterfall per level for no new information.\n */\nexport async function buildHydratedTree(\n pages: readonly ClientPageEntry[],\n payload: HydrationDocumentPayloadSource,\n): Promise<ReactNode> {\n const entry = findEntryByName(pages, payload.name);\n const composition = await loadClientRouteComposition(entry);\n const { shared } = payload;\n\n const Page = componentOf(composition.Page);\n let element: ReactNode =\n Page === undefined ? null : createElement(Page, { data: payload.pageData, shared });\n\n // Innermost layout wraps the page, so walk the outermost-first list backwards.\n for (let index = composition.layouts.length - 1; index >= 0; index -= 1) {\n element = wrap(composition.layouts[index]!, payload.layoutData, shared, element);\n }\n\n return element;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA2BA,SAAS,mBAAmB,gBAA2C;CACrE,IAAI,eAAe,WAAW,GAAG,OAAO;CAExC,OAAO,uBAAuB,eAAe,KAAK,SAAS,KAAK,UAAU,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,EAAE;AAC9F;;;;;;;;;;;AAYA,IAAa,gCAAb,cAAmD,MAAM;CAErC;CACA;CAFlB,AAAO,YACL,AAAgB,UAChB,AAAgB,gBAChB;EACA,MACE,qDAAqD,KAAK,UAAU,QAAQ,EAAE,8CACxC,mBAAmB,cAAc,EAAE,8OAI3E;EATgB;EACA;EAShB,KAAK,OAAO;CACd;AACF;AAEA,SAAS,gBACP,OACA,MACiB;CACjB,MAAM,QAAQ,MAAM,MAAM,cAAc,UAAU,SAAS,IAAI;CAE/D,IAAI,UAAU,QACZ,MAAM,IAAI,8BACR,MACA,MAAM,KAAK,cAAc,UAAU,IAAI,CACzC;CAGF,OAAO;AACT;;;;;;;;;AAUA,SAAS,YACP,QAC+C;CAC/C,MAAM,YAAY,OAAO;CAEzB,OAAO,OAAO,cAAc,aACvB,YACD;AACN;AAEA,SAAS,KACP,QACA,MACA,QACA,UACW;CACX,MAAM,YAAY,YAAY,MAAM;CAEpC,IAAI,cAAc,QAAW,OAAO;CAEpC,OAAO,cAAc,WAAW;EAAE;EAAM;EAAQ;CAAS,CAAC;AAC5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,eAAsB,kBACpB,OACA,SACoB;CAEpB,MAAM,cAAc,MAAM,2BADZ,gBAAgB,OAAO,QAAQ,IACY,CAAC;CAC1D,MAAM,EAAE,WAAW;CAEnB,MAAM,OAAO,YAAY,YAAY,IAAI;CACzC,IAAI,UACF,SAAS,SAAY,OAAO,cAAc,MAAM;EAAE,MAAM,QAAQ;EAAU;CAAO,CAAC;CAGpF,KAAK,IAAI,QAAQ,YAAY,QAAQ,SAAS,GAAG,SAAS,GAAG,SAAS,GACpE,UAAU,KAAK,YAAY,QAAQ,QAAS,QAAQ,YAAY,QAAQ,OAAO;CAGjF,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"build-hydrated-tree.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/client/build-hydrated-tree.ts"],"sourcesContent":["/**\n * The hydration COMPOSER: payload + page registry -> the ReactNode to mount.\n *\n * It takes the registry as an ARGUMENT and touches no browser global, which is\n * the whole point of it living apart from `index.ts`: every rule below is\n * testable with a hand-built registry, no bundler, no virtual module, no DOM.\n *\n * LOOKUP BY NAME, NEVER BY MATCH. `payload.name` is the identity of the entry\n * the SERVER matched for this exact request (document-context.ts's `name`\n * field). Re-deriving it from `location.pathname` with `matchClientRoute`\n * would be a second implementation of route semantics running against the one\n * request it is hydrating, free to disagree with the server that produced the\n * markup. `matchClientRoute` is for client-side NAVIGATION, where no server\n * answer exists yet.\n */\nimport { createElement, type ComponentType, type ReactNode } from \"react\";\nimport type {\n HydrationDocumentPayloadSource,\n SerializedErrorPageProps,\n} from \"../hydration-payload\";\nimport { registerModules } from \"../runtime/register-modules\";\nimport { loadClientRouteComposition } from \"./runtime\";\nimport type { ClientPageEntry, ClientProjectedModule } from \"./runtime/types\";\n\n/** What every composed level receives — the shape `render-page.ts` uses server-side. */\ntype HydratedLevelProps = {\n readonly data: unknown;\n readonly shared: unknown;\n readonly children?: ReactNode;\n};\n\n/** The ordinary page leaf alone receives params from the server's match. */\ntype HydratedPageProps = {\n readonly data: unknown;\n readonly shared: unknown;\n readonly params: Readonly<Record<string, string>>;\n};\n\nfunction describeKnownNames(knownPageNames: readonly string[]): string {\n if (knownPageNames.length === 0) return \"The client page registry is empty.\";\n\n return `The registry knows: ${knownPageNames.map((name) => JSON.stringify(name)).join(\", \")}.`;\n}\n\n/**\n * The THIRD hydration failure case, beside an absent and a malformed payload.\n *\n * It fails CLOSED — no default entry, no nearest-path fallback, no silent\n * no-op. A registry that quietly substitutes a page produces a browser showing\n * one page's markup running another page's code, which is precisely the defect\n * this entry point was rewritten to remove; a fallback would reintroduce it\n * wearing a recovery costume. Throwing leaves the server-rendered markup on\n * screen and un-hydrated, which is degraded but honest.\n */\nexport class UnknownHydrationPageNameError extends Error {\n public constructor(\n public readonly pageName: string,\n public readonly knownPageNames: readonly string[],\n ) {\n super(\n `Warlock hydration aborted: the payload names page ${JSON.stringify(pageName)}, which is ` +\n `not in the client page registry. ${describeKnownNames(knownPageNames)} The server ` +\n \"rendered a page this browser bundle does not carry, so the server and client were \" +\n \"built from different page graphs. To fix: rebuild the client bundle, or check that \" +\n \"the page's file still exports a `route` discovery can see.\",\n );\n this.name = \"UnknownHydrationPageNameError\";\n }\n}\n\n/**\n * The server selected an app error page, but this browser graph cannot load it.\n * Substituting the ordinary page would execute the component that already\n * failed and hydrate markup the server did not render, so this path fails\n * closed just like an unknown route name.\n */\nexport class MissingHydrationErrorPageError extends Error {\n public constructor(public readonly pageName: string) {\n super(\n `Warlock hydration aborted: the server selected error.page.tsx for route ` +\n `${JSON.stringify(pageName)}, but that route's client composition has no ErrorPage ` +\n \"module. Rebuild the client page registry so it projects the discovered error page.\",\n );\n this.name = \"MissingHydrationErrorPageError\";\n }\n}\n\nfunction findEntryByName(\n pages: readonly ClientPageEntry[],\n name: string,\n): ClientPageEntry {\n const entry = pages.find((candidate) => candidate.name === name);\n\n if (entry === undefined) {\n throw new UnknownHydrationPageNameError(\n name,\n pages.map((candidate) => candidate.name),\n );\n }\n\n return entry;\n}\n\n/**\n * A level's component, or undefined when the module exports no default.\n *\n * Undefined is NOT an error: `render-page.ts:258` and `:279` treat a missing\n * default as a passthrough server-side, and the client tree has to match the\n * markup React is hydrating against — introducing a level here that the server\n * did not render is a hydration mismatch, not a repair.\n */\nfunction componentOf<Props extends object>(\n module: ClientProjectedModule,\n): ComponentType<Props> | undefined {\n const component = module.default;\n\n return typeof component === \"function\"\n ? (component as ComponentType<Props>)\n : undefined;\n}\n\nfunction wrap(\n module: ClientProjectedModule,\n data: unknown,\n shared: unknown,\n children: ReactNode,\n): ReactNode {\n const Component = componentOf<HydratedLevelProps>(module);\n\n if (Component === undefined) return children;\n\n return createElement(Component, { data, shared, children });\n}\n\n/**\n * Compose the tree the server rendered inside `#root`: ordered layouts wrapping\n * the selected Page or ErrorPage leaf, layouts OUTERMOST FIRST as\n * `ClientRouteComposition` declares them. Ordinary levels receive\n * `{ data, shared }`; the error leaf receives the serialized `{ error, status\n * }` payload shape.\n *\n * ── THE APP LEVEL IS DELIBERATELY ABSENT, AND MUST STAY ABSENT ──────────────\n * `ClientRouteComposition.App` and `payload.appData` still exist and are still\n * carried; they are contracts owned elsewhere. They are simply not part of THIS\n * tree, because App is not part of the markup this tree hydrates against:\n *\n * - Server-side, `render-page.ts`'s `wrapRootward` wraps the page leaf in\n * `[\"layout\", \"app\"]` (`render-page.ts:274`), so the document React renders\n * is `App( Layout( Page ) )`.\n * - The app root is the level that owns `<html>`/`<body>` and renders\n * `<div id=\"root\">{children}</div>` inside the body. So App CONTAINS the\n * mount point — the markup actually inside `#root` is `Layout( Page )`.\n * - `hydrate-page.tsx` mounts at `#root` and nowhere else.\n *\n * Composing App here would therefore hydrate a whole `<html>` document inside a\n * `<div>` the server filled with a layout: a guaranteed hydration mismatch. If\n * you arrived here from the optional `App?` on the composition type and are\n * about to \"complete\" the tree with it — that would be the defect, not the\n * omission.\n *\n * `load()` is awaited exactly ONCE per hydration and its result reused for all\n * levels — the composition arrives whole, so calling it per layout would be\n * one network waterfall per level for no new information.\n */\nexport async function buildHydratedTree(\n pages: readonly ClientPageEntry[],\n payload: HydrationDocumentPayloadSource,\n): Promise<ReactNode> {\n const entry = findEntryByName(pages, payload.name);\n const composition = await loadClientRouteComposition(entry);\n const errorPageProps = payload.errorPage;\n const selectedPageModule =\n errorPageProps === undefined ? composition.Page : composition.ErrorPage;\n\n if (selectedPageModule === undefined) {\n throw new MissingHydrationErrorPageError(payload.name);\n }\n\n // Registration is the first lifecycle action after the real namespaces have\n // loaded. Keep server order: root/App, layouts outermost-to-innermost, page.\n // On the error path the selected error module replaces the ordinary Page in\n // that order; registering Page as well would run code the server did not run.\n // Component extraction and React element creation intentionally happen only\n // after every registration hook has completed synchronously.\n registerModules([\n ...(composition.App === undefined ? [] : [composition.App]),\n ...composition.layouts,\n selectedPageModule,\n ]);\n\n const { shared } = payload;\n let element: ReactNode;\n\n if (errorPageProps === undefined) {\n const Page = componentOf<HydratedPageProps>(selectedPageModule);\n element =\n Page === undefined\n ? null\n : createElement(Page, {\n data: payload.pageData,\n shared,\n params: payload.params ?? {},\n });\n } else {\n const ErrorPage = componentOf<SerializedErrorPageProps>(selectedPageModule);\n element =\n ErrorPage === undefined ? null : createElement(ErrorPage, errorPageProps);\n }\n\n // Innermost layout wraps the page, so walk the outermost-first list backwards.\n for (let index = composition.layouts.length - 1; index >= 0; index -= 1) {\n element = wrap(\n composition.layouts[index]!,\n payload.layoutData,\n shared,\n element,\n );\n }\n\n return element;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAsCA,SAAS,mBAAmB,gBAA2C;CACrE,IAAI,eAAe,WAAW,GAAG,OAAO;CAExC,OAAO,uBAAuB,eAAe,KAAK,SAAS,KAAK,UAAU,IAAI,CAAC,EAAE,KAAK,IAAI,EAAE;AAC9F;;;;;;;;;;;AAYA,IAAa,gCAAb,cAAmD,MAAM;CAErC;CACA;CAFlB,AAAO,YACL,AAAgB,UAChB,AAAgB,gBAChB;EACA,MACE,qDAAqD,KAAK,UAAU,QAAQ,EAAE,8CACxC,mBAAmB,cAAc,EAAE,8OAI3E;EATgB;EACA;EAShB,KAAK,OAAO;CACd;AACF;;;;;;;AAQA,IAAa,iCAAb,cAAoD,MAAM;CACrB;CAAnC,AAAO,YAAY,AAAgB,UAAkB;EACnD,MACE,2EACK,KAAK,UAAU,QAAQ,EAAE,0IAEhC;EALiC;EAMjC,KAAK,OAAO;CACd;AACF;AAEA,SAAS,gBACP,OACA,MACiB;CACjB,MAAM,QAAQ,MAAM,MAAM,cAAc,UAAU,SAAS,IAAI;CAE/D,IAAI,UAAU,QACZ,MAAM,IAAI,8BACR,MACA,MAAM,KAAK,cAAc,UAAU,IAAI,CACzC;CAGF,OAAO;AACT;;;;;;;;;AAUA,SAAS,YACP,QACkC;CAClC,MAAM,YAAY,OAAO;CAEzB,OAAO,OAAO,cAAc,aACvB,YACD;AACN;AAEA,SAAS,KACP,QACA,MACA,QACA,UACW;CACX,MAAM,YAAY,YAAgC,MAAM;CAExD,IAAI,cAAc,QAAW,OAAO;CAEpC,OAAO,cAAc,WAAW;EAAE;EAAM;EAAQ;CAAS,CAAC;AAC5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,eAAsB,kBACpB,OACA,SACoB;CAEpB,MAAM,cAAc,MAAM,2BADZ,gBAAgB,OAAO,QAAQ,IACY,CAAC;CAC1D,MAAM,iBAAiB,QAAQ;CAC/B,MAAM,qBACJ,mBAAmB,SAAY,YAAY,OAAO,YAAY;CAEhE,IAAI,uBAAuB,QACzB,MAAM,IAAI,+BAA+B,QAAQ,IAAI;CASvD,gBAAgB;EACd,GAAI,YAAY,QAAQ,SAAY,CAAC,IAAI,CAAC,YAAY,GAAG;EACzD,GAAG,YAAY;EACf;CACF,CAAC;CAED,MAAM,EAAE,WAAW;CACnB,IAAI;CAEJ,IAAI,mBAAmB,QAAW;EAChC,MAAM,OAAO,YAA+B,kBAAkB;EAC9D,UACE,SAAS,SACL,OACA,cAAc,MAAM;GAClB,MAAM,QAAQ;GACd;GACA,QAAQ,QAAQ,UAAU,CAAC;EAC7B,CAAC;CACT,OAAO;EACL,MAAM,YAAY,YAAsC,kBAAkB;EAC1E,UACE,cAAc,SAAY,OAAO,cAAc,WAAW,cAAc;CAC5E;CAGA,KAAK,IAAI,QAAQ,YAAY,QAAQ,SAAS,GAAG,SAAS,GAAG,SAAS,GACpE,UAAU,KACR,YAAY,QAAQ,QACpB,QAAQ,YACR,QACA,OACF;CAGF,OAAO;AACT"}
|
|
@@ -4,7 +4,7 @@ import { readHydrationPayload } from "../hydration-payload.mjs";
|
|
|
4
4
|
import { hydrateRoot } from "react-dom/client";
|
|
5
5
|
import { jsx } from "react/jsx-runtime";
|
|
6
6
|
|
|
7
|
-
//#region
|
|
7
|
+
//#region web/src/client/hydrate-page.tsx
|
|
8
8
|
/**
|
|
9
9
|
* The hydration MOUNT point — a different id from the payload script's id.
|
|
10
10
|
* Not exported anywhere as a named constant (`default-app.tsx:39` only
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hydrate-page.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"hydrate-page.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/client/hydrate-page.tsx"],"sourcesContent":["import type { ReactNode } from \"react\";\nimport { hydrateRoot } from \"react-dom/client\";\nimport { DocumentContext, type DocumentContextValue } from \"../components/document-context\";\nimport { readHydrationPayload, type HydrationDocumentPayloadSource } from \"../hydration-payload\";\nimport { hydrateShared } from \"../shared\";\n\n/**\n * The hydration MOUNT point — a different id from the payload script's id.\n * Not exported anywhere as a named constant (`default-app.tsx:39` only\n * renders the literal `<div id=\"root\">`), so a local literal is fine here:\n * the contract's no-duplicate-literal rule is specifically about the payload\n * script id, which `readHydrationPayload` already owns exclusively\n * (hydration-payload-contract-2026-08-22.md §4).\n */\nconst MOUNT_ELEMENT_ID = \"root\";\n\n/**\n * Receives the VALIDATED payload and returns the ReactNode to hydrate. A\n * callback rather than a ready-made ReactNode: composing the real Layout(Page)\n * tree needs `payload.layoutData`/`pageData`/`shared`, which only exist after\n * `readHydrationPayload()` has already succeeded — building the tree first and\n * validating second would get the order backwards.\n *\n * A Promise is allowed because the real composer resolves the page's chunk\n * through the registry's dynamic `import()`. Returning it does NOT move the\n * payload check later: the callback is still only reached once the payload has\n * validated, and only the tree it produces is awaited.\n */\nexport type BuildHydratedTree = (\n payload: HydrationDocumentPayloadSource,\n) => ReactNode | Promise<ReactNode>;\n\nfunction isPromise(value: ReactNode | Promise<ReactNode>): value is Promise<ReactNode> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\n/**\n * The awaited path's failure sink. By the time a `buildTree` promise rejects\n * the synchronous stack is gone, so there is no caller left to throw at — and\n * an un-attached rejection is a blank console, which is the silent-failure\n * class this pipeline keeps regressing into. Reported loudly, and deliberately\n * WITHOUT touching `#root`: the server's markup is correct and visible, it is\n * only un-hydrated, so clearing it would turn a degraded page into a blank one.\n */\nfunction reportHydrationFailure(error: unknown): void {\n console.error(\n \"Warlock hydration failed after the page tree was requested. The server-rendered \" +\n \"markup is left on screen un-hydrated; #root was not cleared.\",\n error,\n );\n}\n\n/**\n * The one hydration entry point. Mounts at `#root` only — the page subtree —\n * never `document`/`html`/`head`/`body` (hydration-payload-contract-2026-08-22.md\n * §2): `metadata`, `lang`, `dir`, `nonce` are not in the client payload and are\n * never touched here. `readHydrationPayload` (web/src/hydration-payload.ts,\n * Vega's slice B) is the one place ABSENT/MALFORMED are decided, so this\n * function does not re-implement that check — reusing it is what keeps the\n * two throw messages from drifting apart at a second site. On ABSENT/MALFORMED\n * it throws before touching `#root`, so the server-rendered markup stays\n * visible; nothing is cleared or re-rendered.\n *\n * Order is load-bearing and unchanged by the async tree: payload validated,\n * shared snapshot installed, `#root` resolved and its absence thrown on — all\n * SYNCHRONOUSLY, so those three failures still reject the call itself — and\n * only then is the tree built and, if it is a promise, awaited. Nothing is\n * cleared on any failure path.\n */\nexport function hydratePage(buildTree: BuildHydratedTree): void {\n const payload = readHydrationPayload(document);\n\n hydrateShared(payload.shared);\n\n const mountElement = document.getElementById(MOUNT_ELEMENT_ID);\n\n if (mountElement === null) {\n throw new Error(\n `Warlock hydration aborted: no element with id \"${MOUNT_ELEMENT_ID}\" was found. The ` +\n 'server is expected to render <div id=\"root\"> as the hydration mount point ' +\n \"(web/src/components/default-app.tsx:39).\",\n );\n }\n\n const value: DocumentContextValue = { metadata: undefined, payload };\n\n const mount = (tree: ReactNode): void => {\n hydrateRoot(\n mountElement,\n <DocumentContext.Provider value={value}>{tree}</DocumentContext.Provider>,\n );\n };\n\n const tree = buildTree(payload);\n\n if (isPromise(tree)) {\n // `void` on an ALREADY-handled chain: the rejection handler is attached\n // here, so nothing escapes as an unhandled rejection.\n void tree.then(mount, reportHydrationFailure);\n\n return;\n }\n\n mount(tree);\n}"],"mappings":";;;;;;;;;;;;;;;AAcA,MAAM,mBAAmB;AAkBzB,SAAS,UAAU,OAAoE;CACrF,OACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAQ,MAA6B,SAAS;AAElD;;;;;;;;;AAUA,SAAS,uBAAuB,OAAsB;CACpD,QAAQ,MACN,gJAEA,KACF;AACF;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,YAAY,WAAoC;CAC9D,MAAM,UAAU,qBAAqB,QAAQ;CAE7C,cAAc,QAAQ,MAAM;CAE5B,MAAM,eAAe,SAAS,eAAe,gBAAgB;CAE7D,IAAI,iBAAiB,MACnB,MAAM,IAAI,MACR,kDAAkD,iBAAiB,oIAGrE;CAGF,MAAM,QAA8B;EAAE,UAAU;EAAW;CAAQ;CAEnE,MAAM,SAAS,SAA0B;EACvC,YACE,cACA,oBAAC,gBAAgB,UAAjB;GAAiC;aAAQ;EAA+B,EAC1E;CACF;CAEA,MAAM,OAAO,UAAU,OAAO;CAE9B,IAAI,UAAU,IAAI,GAAG;EAGnB,AAAK,KAAK,KAAK,OAAO,sBAAsB;EAE5C;CACF;CAEA,MAAM,IAAI;AACZ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"current-route.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"current-route.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/client/navigation/current-route.ts"],"sourcesContent":["import type { HydrationDocumentPayloadSource } from \"../../hydration-payload\";\n\n/**\n * \"Which route am I on?\", under the name MRR spells it\n * (`@mongez/react-router` — `src/utilities.tsx`).\n *\n * ## The shift, and it is the whole point of this file\n *\n * MRR's `currentRoute()` returns the object ITS MATCHER produced: MRR is a CSR\n * router, so the browser matched the URL and the answer is the browser's own\n * conclusion. Warlock has no client matcher and must never grow one (canon\n * `9c8f878b`) — the SERVER router is the only matcher, and a second one can\n * disagree with it about the very request it is hydrating.\n *\n * So the name is MRR's because the QUESTION is the same one, but the ANSWER\n * comes from somewhere else: the matched entry's name AND ITS PARAMS travel on\n * the hydration payload (`web/src/components/document-context.ts`), and this\n * module reports what arrived. Nothing here parses a path, compares a URL to a\n * pattern, or knows that routes have shapes.\n *\n * The practical consequence for a caller: this is the server's match, so it is\n * as correct as the page on screen and it cannot drift from it — including on\n * the very first render, before any client navigation, which is most page\n * views.\n *\n * ## The params, and where they come from\n *\n * `bundle.route.params` (`web/src/server/execute-page-request.ts:288`) is the\n * router's own answer; `buildHydrationPayload` puts it on the payload and the\n * projection below hands it over unchanged. Deriving `{ id: \"42\" }` from\n * `location.pathname` here would BE the second matcher this file exists to\n * refuse — a URL and a pattern are exactly what it must never compare.\n *\n * ## Why nothing here touches `window`\n *\n * Both readers are importable from universal modules, so both can be CALLED\n * during the server render and in the gap between first paint and hydration.\n * They read module state and nothing else, so there is no browser to be missing\n * — the answer in those contexts is `undefined`, meaning \"no page has been\n * rendered into this module\", which is exactly true.\n */\n\n/**\n * What the SERVER matched for the page currently on screen.\n *\n * Deliberately not `ClientRouteMatch` (`web/src/client/runtime/types.ts`): that\n * is the deprecated client matcher's output shape, entry object and all, and\n * this is the opposite claim — a name the server sent us.\n */\nexport type MatchedRoute = {\n /** The matched page manifest entry's stable `name`, e.g. `products.details`. */\n readonly name: string;\n /**\n * The params the SERVER matched, e.g. `{ id: \"42\" }` for `/users/:id`, and\n * `{}` for a route with no dynamic segments.\n *\n * `undefined` means the payload carried no `params` key — an older build, or\n * a document cached across a deploy. It is NOT the same answer as `{}`, and\n * this module will not collapse the two: `{}` is the server saying \"this\n * route has no params\", `undefined` is the server not having said. Inventing\n * the first from the second would be a lie a caller cannot detect, which is\n * the same standard {@link previousRoute} is held to below. Every payload a\n * current server produces carries the key.\n *\n * A COPY of the payload's object, so a caller writing to it cannot reach the\n * payload the page was built from.\n */\n readonly params?: Readonly<Record<string, string>>;\n};\n\nlet current: MatchedRoute | undefined;\nlet previous: MatchedRoute | undefined;\n\n/**\n * The payload `current` was projected from, kept ONLY to recognise it again.\n *\n * `NavigationRoot` records on every render pass, because a page component must\n * be able to call `currentRoute()` while it is itself rendering — including on\n * the initial mount, where no effect has run yet. Renders are not navigations\n * though: StrictMode invokes them twice, and a parent re-render invokes them\n * again for free. One swap is one payload OBJECT, so identity is what separates\n * \"we moved\" from \"we rendered again\". Comparing names instead would both miss\n * a `/users/1` → `/users/2` move and invent one out of a double render.\n */\nlet source: HydrationDocumentPayloadSource | undefined;\n\n/**\n * Record the payload the page on screen was built from.\n *\n * Called by `NavigationRoot` during render — at mount with the hydration\n * payload, and after each swap with the fetched one. Not part of the public\n * surface: the payload is the navigation runtime's to hand over, and a caller\n * setting the current route by hand would be asserting a match that never\n * happened.\n *\n * Idempotent per payload object, so re-rendering the same page never shifts\n * {@link previousRoute}.\n */\nexport function recordCurrentRoute(payload: HydrationDocumentPayloadSource): void {\n if (source === payload) return;\n\n source = payload;\n previous = current;\n // A COPY when the payload carried params, and no key at all when it did not\n // — the projection reports what arrived and never fills a gap in.\n current =\n payload.params === undefined\n ? { name: payload.name }\n : { name: payload.name, params: { ...payload.params } };\n}\n\n/**\n * @returns what the SERVER matched for the page on screen — see this file's\n * header for why that is the answer and not a client-side match. Correct from\n * the first render of the initial page, since the hydration payload carried the\n * match with it.\n *\n * `undefined` means no page has been rendered into this module: a server\n * render, or an import evaluated before hydration mounted. Safe to call in\n * either — it does not throw and does not touch `window`.\n */\nexport function currentRoute(): MatchedRoute | undefined {\n return current;\n}\n\n/**\n * @returns the entry that was on screen BEFORE the current one, or `undefined`\n * when the current page is the one the user landed on. That `undefined` is a\n * real answer, not a missing one — there is no previous route on a first visit,\n * and reporting the current one would be a lie a caller cannot detect.\n *\n * This is the previously SWAPPED page, not the previous history entry: pressing\n * Back is itself a navigation here, so going A → B → Back leaves the previous\n * route as B. Safe to call with no browser.\n */\nexport function previousRoute(): MatchedRoute | undefined {\n return previous;\n}\n"],"mappings":";AAsEA,IAAI;AACJ,IAAI;;;;;;;;;;;;AAaJ,IAAI;;;;;;;;;;;;;AAcJ,SAAgB,mBAAmB,SAA+C;CAChF,IAAI,WAAW,SAAS;CAExB,SAAS;CACT,WAAW;CAGX,UACE,QAAQ,WAAW,SACf,EAAE,MAAM,QAAQ,KAAK,IACrB;EAAE,MAAM,QAAQ;EAAM,QAAQ,EAAE,GAAG,QAAQ,OAAO;CAAE;AAC5D;;;;;;;;;;;AAYA,SAAgB,eAAyC;CACvD,OAAO;AACT;;;;;;;;;;;AAYA,SAAgB,gBAA0C;CACxD,OAAO;AACT"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { DATA_RESPONSE_CONTENT_TYPE, WARLOCK_DATA_REQUEST_HEADER } from "../../routing/data-request.mjs";
|
|
2
2
|
|
|
3
|
-
//#region
|
|
3
|
+
//#region web/src/client/navigation/fetch-page-data.ts
|
|
4
4
|
/**
|
|
5
5
|
* Ask the server for a URL's page data instead of its document.
|
|
6
6
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch-page-data.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"fetch-page-data.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/client/navigation/fetch-page-data.ts"],"sourcesContent":["/**\n * Ask the server for a URL's page data instead of its document.\n *\n * This is the browser half of the representation split: the same route the user\n * would have loaded, asked for as JSON via the `x-warlock-data` marker. What\n * comes back is exactly the payload a full page load embeds, so the caller can\n * rebuild the tree from it with no second code path.\n *\n * ## Every failure degrades to a REAL navigation, never to an error screen\n *\n * A client navigation is an OPTIMISATION over what the browser already does\n * perfectly well. So nothing here reports a failure to the user — it reports\n * `hard-navigate`, and the caller hands the URL back to the browser. The user\n * gets the page; they just get it the slow way.\n *\n * That is what makes the whole feature safe to add: the worst case of a bug in\n * this file is the behaviour we had before the file existed. Rendering our own\n * \"navigation failed\" state would be strictly worse than the fallback we\n * already have, and would turn every unhandled edge — an auth redirect to an\n * external IdP, a maintenance page, a proxy that strips the header, a deploy\n * that changed the payload shape mid-session — into a dead end.\n */\nimport {\n DATA_RESPONSE_CONTENT_TYPE,\n WARLOCK_DATA_REQUEST_HEADER,\n WARLOCK_DATA_REQUEST_VALUE,\n} from \"../../routing/data-request\";\nimport type { HydrationDocumentPayloadSource } from \"../../hydration-payload\";\n\nexport type PageDataResult =\n | {\n type: \"payload\";\n /**\n * The payload to rebuild the tree from.\n */\n payload: HydrationDocumentPayloadSource;\n /**\n * The URL the response actually came from — NOT the one requested. A\n * redirect is followed by `fetch` transparently, so a login-required page\n * answers from `/login`, and pushing the requested URL into history would\n * leave the address bar lying about what is on screen.\n */\n url: string;\n }\n | {\n type: \"hard-navigate\";\n url: string;\n /** Why, for a console warning — never shown to the user. */\n reason: string;\n };\n\n/**\n * Whether the body is the payload we asked for.\n *\n * Checked rather than assumed because a 200 does not mean \"this came from the\n * page pipeline\": a captive portal, an SSO interstitial or a proxy error page\n * all answer 200 with HTML. Parsing that as JSON would throw; treating a\n * successful parse of *something else* as a payload would render garbage.\n */\nfunction isPayloadResponse(response: Response): boolean {\n return (response.headers.get(\"content-type\") ?? \"\").includes(DATA_RESPONSE_CONTENT_TYPE);\n}\n\n/**\n * The shape check, kept deliberately narrow: `name` is the only field the tree\n * builder cannot proceed without — it selects the page. The data fields are\n * page-defined and may legitimately be anything, including `null`.\n */\nfunction isPayloadShape(value: unknown): value is HydrationDocumentPayloadSource {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { name?: unknown }).name === \"string\"\n );\n}\n\nexport async function fetchPageData(url: string): Promise<PageDataResult> {\n let response: Response;\n\n try {\n response = await fetch(url, {\n headers: {\n [WARLOCK_DATA_REQUEST_HEADER]: WARLOCK_DATA_REQUEST_VALUE,\n accept: DATA_RESPONSE_CONTENT_TYPE,\n },\n // Same-origin credentials so a navigation carries the session exactly as\n // a document request would. Without this a client navigation could be\n // logged out while a full load of the same URL is not.\n credentials: \"same-origin\",\n // Redirects are FOLLOWED, not intercepted: the marker header is re-sent,\n // so the destination answers with a payload too, and `response.url` tells\n // us where we ended up. Handling redirects ourselves would mean\n // re-implementing the rules the browser already has.\n redirect: \"follow\",\n });\n } catch (error) {\n // Offline, DNS, CORS, an aborted connection. The browser can render its own\n // network error far better than we can fake one.\n return { type: \"hard-navigate\", url, reason: `request failed: ${String(error)}` };\n }\n\n if (!response.ok) {\n // 404, 500, 403 — all of these have a real page the server renders. Letting\n // the browser load it gets the correct status AND the correct document,\n // rather than us inventing a client-side error state that the server's own\n // error page already covers.\n return { type: \"hard-navigate\", url, reason: `status ${response.status}` };\n }\n\n if (!isPayloadResponse(response)) {\n return {\n type: \"hard-navigate\",\n url,\n reason: `unexpected content-type \"${response.headers.get(\"content-type\") ?? \"none\"}\"`,\n };\n }\n\n let parsed: unknown;\n\n try {\n parsed = await response.json();\n } catch (error) {\n return { type: \"hard-navigate\", url, reason: `malformed JSON: ${String(error)}` };\n }\n\n if (!isPayloadShape(parsed)) {\n return { type: \"hard-navigate\", url, reason: \"payload has no route name\" };\n }\n\n // `response.url` is absolute and reflects any redirect that was followed.\n // Falling back to the requested URL keeps this working under test doubles\n // that do not set it.\n return { type: \"payload\", payload: parsed, url: response.url || url };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DA,SAAS,kBAAkB,UAA6B;CACtD,QAAQ,SAAS,QAAQ,IAAI,cAAc,KAAK,IAAI,SAAS,0BAA0B;AACzF;;;;;;AAOA,SAAS,eAAe,OAAyD;CAC/E,OACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAQ,MAA6B,SAAS;AAElD;AAEA,eAAsB,cAAc,KAAsC;CACxE,IAAI;CAEJ,IAAI;EACF,WAAW,MAAM,MAAM,KAAK;GAC1B,SAAS;KACN;IACD,QAAQ;GACV;GAIA,aAAa;GAKb,UAAU;EACZ,CAAC;CACH,SAAS,OAAO;EAGd,OAAO;GAAE,MAAM;GAAiB;GAAK,QAAQ,mBAAmB,OAAO,KAAK;EAAI;CAClF;CAEA,IAAI,CAAC,SAAS,IAKZ,OAAO;EAAE,MAAM;EAAiB;EAAK,QAAQ,UAAU,SAAS;CAAS;CAG3E,IAAI,CAAC,kBAAkB,QAAQ,GAC7B,OAAO;EACL,MAAM;EACN;EACA,QAAQ,4BAA4B,SAAS,QAAQ,IAAI,cAAc,KAAK,OAAO;CACrF;CAGF,IAAI;CAEJ,IAAI;EACF,SAAS,MAAM,SAAS,KAAK;CAC/B,SAAS,OAAO;EACd,OAAO;GAAE,MAAM;GAAiB;GAAK,QAAQ,mBAAmB,OAAO,KAAK;EAAI;CAClF;CAEA,IAAI,CAAC,eAAe,MAAM,GACxB,OAAO;EAAE,MAAM;EAAiB;EAAK,QAAQ;CAA4B;CAM3E,OAAO;EAAE,MAAM;EAAW,SAAS;EAAQ,KAAK,SAAS,OAAO;CAAI;AACtE"}
|
|
@@ -10,7 +10,7 @@ import { scrollToFragment } from "./scroll-to-fragment.mjs";
|
|
|
10
10
|
import { useEffect, useLayoutEffect, useRef, useState } from "react";
|
|
11
11
|
import { jsx } from "react/jsx-runtime";
|
|
12
12
|
|
|
13
|
-
//#region
|
|
13
|
+
//#region web/src/client/navigation/navigation-root.tsx
|
|
14
14
|
function metaTag(attribute, key) {
|
|
15
15
|
return {
|
|
16
16
|
selector: `meta[${attribute}="${key}"]`,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"navigation-root.mjs","names":[],"sources":["../../../../../../../../web/src/client/navigation/navigation-root.tsx"],"sourcesContent":["import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from \"react\";\r\nimport { DocumentContext } from \"../../components/document-context\";\r\nimport type { HydrationDocumentPayloadSource } from \"../../hydration-payload\";\r\nimport type { MetadataOutput } from \"../../metadata\";\r\nimport { connectNavigator } from \"../../routing/navigator\";\r\nimport {\r\n fragmentOf,\r\n samePageFragment,\r\n withFragmentFrom,\r\n withoutFragment,\r\n} from \"../../routing/url-fragment\";\r\nimport { hydrateShared } from \"../../shared\";\r\nimport type { ClientPageEntry } from \"../runtime\";\r\nimport { recordCurrentRoute } from \"./current-route\";\r\nimport { fetchPageData } from \"./fetch-page-data\";\r\nimport { takePrefetchedPageData } from \"./prefetch\";\r\nimport { connectRefresher, createRefresher, type RefreshablePage } from \"./refresh\";\r\nimport { scrollToFragment } from \"./scroll-to-fragment\";\r\n\r\n/**\r\n * The component that makes a page REPLACEABLE.\r\n *\r\n * Hydration mounts a fixed tree — correct, because the first render must match\r\n * the server's markup byte for byte. Client navigation needs that same position\r\n * in the tree to be able to hold a *different* page later, which means state,\r\n * which means a component. This is that component and nothing more.\r\n *\r\n * ## Why the layout stays mounted\r\n *\r\n * The new tree is built by the same `buildHydratedTree` the server's payload\r\n * went through, so a navigation within one layout produces an element whose\r\n * layout components are the same types in the same positions. React reconciles\r\n * them rather than remounting, so layout state — an open menu, a scroll\r\n * container, a video — survives. That is the entire user-visible benefit of\r\n * client navigation, and it is a consequence of reusing the builder rather than\r\n * anything this file does.\r\n */\r\n\r\n/**\r\n * ONE tag `<head>` may hold at most one of, addressed the way the browser\r\n * already addresses it. No marker attribute: the tags this replaces were\r\n * rendered by `<Head/>` on the server and carry none, and a marker would make\r\n * the applier ignore exactly the tags it exists to correct — the first\r\n * navigation's.\r\n */\r\ntype ManagedTag = {\r\n /** Finds the existing tag, server-rendered or applied by a previous swap. */\r\n selector: string;\r\n create: (documentNode: Document) => Element;\r\n write: (element: Element, value: string) => void;\r\n};\r\n\r\nfunction metaTag(attribute: \"name\" | \"property\", key: string): ManagedTag {\r\n return {\r\n selector: `meta[${attribute}=\"${key}\"]`,\r\n create: documentNode => {\r\n const element = documentNode.createElement(\"meta\");\r\n\r\n element.setAttribute(attribute, key);\r\n\r\n return element;\r\n },\r\n write: (element, value) => element.setAttribute(\"content\", value),\r\n };\r\n}\r\n\r\nconst TITLE_TAG: ManagedTag = {\r\n selector: \"title\",\r\n create: documentNode => documentNode.createElement(\"title\"),\r\n write: (element, value) => {\r\n element.textContent = value;\r\n },\r\n};\r\n\r\nconst CANONICAL_TAG: ManagedTag = {\r\n selector: 'link[rel=\"canonical\"]',\r\n create: documentNode => {\r\n const element = documentNode.createElement(\"link\");\r\n\r\n element.setAttribute(\"rel\", \"canonical\");\r\n\r\n return element;\r\n },\r\n write: (element, value) => element.setAttribute(\"href\", value),\r\n};\r\n\r\n/**\r\n * The metadata, resolved into (tag, value) pairs in `<Head/>`'s ORDER and by\r\n * `<Head/>`'s RULES — including the og fallbacks and the fact that they apply\r\n * only when `openGraph` is present (`components/head.ts:21-24,43-48`).\r\n *\r\n * The duplication is deliberate and it is the known cost here. `<Head/>` is a\r\n * React component that renders elements into a tree; this writes elements into\r\n * a live `<head>` that no client tree owns. They cannot be one function today,\r\n * but they MUST agree: the head after navigating to a URL has to equal the head\r\n * after landing on it, or a share preview depends on how the visitor arrived.\r\n * The fix is a shared descriptor list both consume — see the report's followup.\r\n */\r\nfunction resolveManagedTags(\r\n metadata: MetadataOutput | undefined,\r\n): readonly (readonly [ManagedTag, string | undefined])[] {\r\n const keywords =\r\n metadata?.keywords === undefined\r\n ? undefined\r\n : Array.isArray(metadata.keywords)\r\n ? metadata.keywords.join(\", \")\r\n : (metadata.keywords as string);\r\n\r\n const openGraph = metadata?.openGraph;\r\n const twitter = metadata?.twitter;\r\n\r\n return [\r\n [TITLE_TAG, metadata?.title],\r\n [metaTag(\"name\", \"description\"), metadata?.description],\r\n [metaTag(\"name\", \"keywords\"), keywords],\r\n [CANONICAL_TAG, metadata?.canonical],\r\n [metaTag(\"name\", \"robots\"), metadata?.robots],\r\n [metaTag(\"property\", \"og:title\"), openGraph && (openGraph.title ?? metadata?.title)],\r\n [\r\n metaTag(\"property\", \"og:description\"),\r\n openGraph && (openGraph.description ?? metadata?.description),\r\n ],\r\n [metaTag(\"property\", \"og:image\"), openGraph?.image],\r\n [metaTag(\"property\", \"og:url\"), openGraph?.url],\r\n [metaTag(\"property\", \"og:type\"), openGraph?.type],\r\n [metaTag(\"name\", \"twitter:card\"), twitter?.card],\r\n [metaTag(\"name\", \"twitter:title\"), twitter?.title],\r\n [metaTag(\"name\", \"twitter:description\"), twitter?.description],\r\n [metaTag(\"name\", \"twitter:image\"), twitter?.image],\r\n ];\r\n}\r\n\r\n/**\r\n * Make `<head>` describe the page now on screen.\r\n *\r\n * ## Why this is imperative, and why that is not a shortcut\r\n *\r\n * `<Head/>` renders inside the App level, and the App level is deliberately NOT\r\n * in the hydrated tree — the client mounts at `#root`, which App contains\r\n * (`client/build-hydrated-tree.ts`'s header). So no client render can reach\r\n * `<head>`, and a swap either writes it directly or leaves the previous page's\r\n * title in the tab. It leaves it today; that is the bug.\r\n *\r\n * ## ABSENT MEANS REMOVED\r\n *\r\n * Every managed tag the new metadata does not set is REMOVED, not left alone.\r\n * `/` sets a description and `/contact-us` does not: keeping it would describe\r\n * the contact page with the home page's words to every crawler, share preview\r\n * and assistive reader that looks — a wrong answer, where an absent one is\r\n * merely absent. A title the new page does not set goes too, and the tab falls\r\n * back to the URL, which is the honest rendering of \"this page did not name\r\n * itself\".\r\n *\r\n * Only the tags `<Head/>` renders FROM METADATA are touched. The charset meta\r\n * is rendered unconditionally and belongs to the document, so it is left alone.\r\n *\r\n * Takes the document as an argument rather than reaching for the global, which\r\n * is what makes it provable in a suite with no DOM.\r\n */\r\nexport function applyDocumentMetadata(\r\n documentNode: Document,\r\n metadata: MetadataOutput | undefined,\r\n): void {\r\n for (const [tag, value] of resolveManagedTags(metadata)) {\r\n const existing = documentNode.querySelector(tag.selector);\r\n\r\n if (value === undefined) {\r\n existing?.remove();\r\n continue;\r\n }\r\n\r\n if (existing !== null) {\r\n tag.write(existing, value);\r\n continue;\r\n }\r\n\r\n const created = tag.create(documentNode);\r\n\r\n tag.write(created, value);\r\n documentNode.head.appendChild(created);\r\n }\r\n}\r\n\r\nexport type NavigationRootProps = {\r\n pages: readonly ClientPageEntry[];\r\n /** The payload the document was rendered from — the hydration one. */\r\n initialPayload: HydrationDocumentPayloadSource;\r\n /** The tree already built from {@link initialPayload}, rendered as-is first. */\r\n initialTree: ReactNode;\r\n /**\r\n * How a payload becomes a tree. Injected rather than imported so this\r\n * component is testable without the page registry or a bundler — the same\r\n * reason `hydratePage` takes its builder as an argument.\r\n */\r\n buildTree: (\r\n pages: readonly ClientPageEntry[],\r\n payload: HydrationDocumentPayloadSource,\r\n ) => Promise<ReactNode>;\r\n};\r\n\r\n/**\r\n * The page on screen. Defined in `refresh.ts` because the third field is that\r\n * file's decision: `routeSource` is the payload object `current-route.ts`\r\n * identifies the route by, which is `payload` after a navigation but the\r\n * PREVIOUS page's object after a refresh — a refresh must not shift\r\n * `previousRoute()` onto the page the user is already looking at.\r\n */\r\ntype Current = RefreshablePage;\r\n\r\nexport function NavigationRoot({\r\n pages,\r\n initialPayload,\r\n initialTree,\r\n buildTree,\r\n}: NavigationRootProps) {\r\n const [current, setCurrent] = useState<Current>({\r\n payload: initialPayload,\r\n tree: initialTree,\r\n routeSource: initialPayload,\r\n });\r\n\r\n /*\r\n The latest state, readable from the effect below — which closes over the\r\n render that created it and would otherwise see the page the user was on\r\n when the runtime connected. A ref rather than an effect dependency because\r\n re-running the effect on every swap would disconnect and reconnect the\r\n navigator mid-navigation.\r\n */\r\n const currentRef = useRef(current);\r\n\r\n currentRef.current = current;\r\n\r\n /*\r\n THE ORDERING PROBLEM, and this ref is half of the answer to it.\r\n\r\n The element a fragment names lives in the tree that has not been built yet:\r\n at the moment `apply` finishes fetching, the DOM still holds the page the\r\n user is LEAVING. Scrolling there finds nothing, and finding nothing is\r\n silent — indistinguishable from the fragment bug itself.\r\n\r\n So the fragment is not scrolled to; it is HANDED OVER. `apply` parks it here\r\n immediately before the `setCurrent` that swaps the tree, and the layout\r\n effect below — which React runs after it has committed that tree to the DOM\r\n and before the browser paints — spends it. Read the two together; neither\r\n half means anything alone.\r\n */\r\n const pendingFragment = useRef<string | undefined>(undefined);\r\n\r\n useEffect(() => {\r\n /*\r\n THE RACE THIS COUNTER EXISTS FOR. Two clicks in quick succession start two\r\n fetches; the second can easily answer first (a cached page beating an\r\n uncached one is the common case, not the exotic one). Without a token the\r\n slower FIRST response lands last and the user ends up on the page they\r\n navigated away from, with the address bar showing the other one.\r\n\r\n Every navigation takes a token; a result is applied only if its token is\r\n still the newest. Superseded responses are dropped silently — they are not\r\n errors, they are answers to a question the user stopped asking.\r\n */\r\n let token = 0;\r\n let disposed = false;\r\n /*\r\n The URL this runtime last put in the address bar, so `popstate` can tell a\r\n move BETWEEN pages from a move between two fragments of one page. Seeded\r\n with the URL the document was loaded at, which is the entry the first Back\r\n would come from.\r\n */\r\n let committedUrl = window.location.href;\r\n\r\n /**\r\n * @param honourFragment whether the URL's fragment should be SCROLLED to\r\n * once the new page is on screen. True for a navigation the app asked for\r\n * — a `<Link>` click, `navigateTo` — and false for Back/Forward, where the\r\n * browser has already restored the scroll position of the entry being\r\n * returned to and moving the page again would overwrite the user's own\r\n * position with the anchor they had scrolled away from. (Restoration is\r\n * the browser's, deliberately: canon `0342c0d4`.)\r\n *\r\n * The fragment is still PRESERVED in the URL in both cases — see below.\r\n */\r\n const apply = async (\r\n url: string,\r\n replace: boolean,\r\n honourFragment: boolean,\r\n ): Promise<void> => {\r\n const ticket = ++token;\r\n /*\r\n A prefetched response is CONSUMED, never merely read — `take` removes it,\r\n so the same speculative fetch can satisfy exactly one navigation and a\r\n second click on the same link goes to the network. That matters because\r\n the HTTP cache cannot stand in for this: dev responses are `no-store`\r\n (`server/dev-server.ts:254`) and production is `private` with no\r\n `max-age` (`server/render-page.ts:432`), so the browser will not reliably\r\n replay the speculative response on the real click.\r\n\r\n The race guard below still holds on a cache hit: `??` short-circuits the\r\n await, and the synchronous path reaches the same `ticket !== token` check.\r\n */\r\n const result = takePrefetchedPageData(url) ?? (await fetchPageData(url));\r\n\r\n if (disposed || ticket !== token) return;\r\n\r\n if (result.type === \"hard-navigate\") {\r\n // The documented degradation: hand the URL back to the browser. The\r\n // user still gets the page — see `fetch-page-data.ts`.\r\n console.warn(`Warlock navigation fell back to a full load (${result.reason}):`, url);\r\n window.location.assign(url);\r\n\r\n return;\r\n }\r\n\r\n let tree: ReactNode;\r\n\r\n try {\r\n tree = await buildTree(pages, result.payload);\r\n } catch (error) {\r\n // The payload was fine but its page chunk would not load or compose —\r\n // a stale bundle after a deploy is the realistic cause. A full load\r\n // fetches the current bundle, which is also the fix.\r\n console.warn(\"Warlock navigation could not build the page tree:\", error);\r\n window.location.assign(url);\r\n\r\n return;\r\n }\r\n\r\n if (disposed || ticket !== token) return;\r\n\r\n /*\r\n Shared state BEFORE the render that consumes it. `hydrateShared`\r\n installs the snapshot `useShared()` reads; swapping the tree first would\r\n render one frame of the new page against the previous page's shared\r\n state — locale, permissions, the current user.\r\n */\r\n hydrateShared(result.payload.shared);\r\n\r\n /*\r\n The fragment PUT BACK. `result.url` comes from `response.url`, and a\r\n fragment is never sent to a server, so the URL a navigation would\r\n otherwise be written to history from has had it stripped — which is how\r\n `<Link href=\"/docs#install\">` used to land on `/docs` with the author's\r\n fragment gone from the address bar for good.\r\n\r\n Applied on EVERY path, Back included: a popstate re-fetch that wrote\r\n `result.url` back would delete the fragment from an entry the user is\r\n merely returning to.\r\n */\r\n const finalUrl = withFragmentFrom(result.url, url);\r\n\r\n // History AFTER the fetch succeeded, never before. Pushing optimistically\r\n // would leave the address bar pointing at a page that then failed to\r\n // load, and a Back press would return to a URL the user never saw.\r\n if (replace) {\r\n window.history.replaceState(null, \"\", finalUrl);\r\n } else {\r\n window.history.pushState(null, \"\", finalUrl);\r\n }\r\n\r\n committedUrl = finalUrl;\r\n\r\n // Handed to the layout effect, which runs once React has committed the\r\n // tree below to the DOM — the first moment the target can exist. Set\r\n // unconditionally so a navigation with no fragment CLEARS a fragment left\r\n // pending by one that was superseded.\r\n pendingFragment.current = honourFragment ? fragmentOf(finalUrl) : undefined;\r\n\r\n // A navigation IS the route moving, so the fetched payload is both the\r\n // page and the route's identity.\r\n setCurrent({ payload: result.payload, tree, routeSource: result.payload });\r\n };\r\n\r\n /*\r\n The same counter `apply` above takes its tickets from, handed to\r\n `refresh()` as a predicate. ONE mechanism, not two: a refresh and a\r\n navigation can overtake each other in either direction, and separate\r\n counters would leave each blind to the other.\r\n */\r\n const claimTicket = (): (() => boolean) => {\r\n const ticket = ++token;\r\n\r\n return () => !disposed && ticket === token;\r\n };\r\n\r\n const previousRefresher = connectRefresher(\r\n createRefresher({\r\n readCurrent: () => currentRef.current,\r\n writeCurrent: setCurrent,\r\n buildTree: payload => buildTree(pages, payload),\r\n claimTicket,\r\n }),\r\n );\r\n\r\n const previousNavigator = connectNavigator((url, options) => {\r\n const replace = options?.replace === true;\r\n\r\n /*\r\n THIS page with a fragment on it — `#reviews`, or the current path spelled\r\n out with one appended. No fetch, no tree swap: the page is already here,\r\n and re-fetching it would discard its DOM and everything live in it to\r\n arrive back where we started, one round trip later. Address bar first,\r\n then the jump, which is the order the browser uses for a plain anchor.\r\n */\r\n const fragment = samePageFragment(url, window.location.href);\r\n\r\n if (fragment !== undefined) {\r\n if (replace) {\r\n window.history.replaceState(null, \"\", url);\r\n } else {\r\n window.history.pushState(null, \"\", url);\r\n }\r\n\r\n committedUrl = window.location.href;\r\n\r\n // The target is in the DOM already, so there is nothing to wait for —\r\n // and nothing to hand to the layout effect, which no swap would fire.\r\n scrollToFragment(document, fragment);\r\n\r\n return true;\r\n }\r\n\r\n void apply(url, replace, true);\r\n\r\n // Accepted: the caller suppresses the browser's default. Returning `true`\r\n // before the fetch resolves is deliberate — the decision to handle a link\r\n // cannot wait on the network without the browser having already followed\r\n // it.\r\n return true;\r\n });\r\n\r\n /*\r\n Back/Forward. The entry is already in history and the URL has already\r\n changed by the time this fires, so the page is fetched and swapped with\r\n `replace` — pushing here would append a duplicate entry and make Back\r\n require two presses.\r\n */\r\n const onPopState = (): void => {\r\n const target = window.location.href;\r\n /*\r\n A hash-only move within one page — Back off a `#section` click, or\r\n Forward onto one. The document is the same document and the tree on\r\n screen is already the right tree, so there is nothing to fetch: the\r\n browser has changed the URL and restored the position for that entry\r\n itself, and re-fetching would throw away a live page to rebuild the one\r\n already showing. Scroll restoration stays the browser's (canon\r\n `0342c0d4`), which is exactly what leaving this alone means.\r\n */\r\n const hashOnlyMove = withoutFragment(target) === withoutFragment(committedUrl);\r\n\r\n committedUrl = target;\r\n\r\n if (hashOnlyMove) return;\r\n\r\n void apply(target, true, false);\r\n };\r\n\r\n window.addEventListener(\"popstate\", onPopState);\r\n\r\n return () => {\r\n disposed = true;\r\n window.removeEventListener(\"popstate\", onPopState);\r\n connectNavigator(previousNavigator);\r\n connectRefresher(previousRefresher);\r\n };\r\n }, [pages, buildTree]);\r\n\r\n /*\r\n THE OTHER HALF OF THE ORDERING PROBLEM (see `pendingFragment` above).\r\n\r\n `useLayoutEffect`, not `useEffect`, and the difference is the whole point:\r\n React runs a layout effect after it has COMMITTED this render to the DOM and\r\n BEFORE the browser paints. That is the earliest instant the new page's\r\n elements exist — a scroll any sooner finds nothing — and the last instant\r\n before the user sees anything, so the page is never painted at the top and\r\n then jumped. `useEffect` would satisfy the first requirement and not the\r\n second: it runs after paint, which is a visible flash of the wrong position.\r\n\r\n Keyed on `current` rather than reaching for a fresh render: the effect fires\r\n on the swap that put the target in the DOM, so no polling, no rAF, no\r\n timeout. What it CANNOT wait for is content that arrives later still — an\r\n image without dimensions above the target, a component that suspends — which\r\n moves the target after we have scrolled to where it was. That is the known\r\n limit of this mechanism and it is the same one a browser has.\r\n\r\n Consumed once: the fragment is cleared as it is read, so a later re-render\r\n (a refresh, a parent's state change) does not yank the page back to an\r\n anchor the user has since scrolled away from.\r\n */\r\n useLayoutEffect(() => {\r\n const fragment = pendingFragment.current;\r\n\r\n if (fragment === undefined) return;\r\n\r\n pendingFragment.current = undefined;\r\n\r\n scrollToFragment(document, fragment);\r\n }, [current]);\r\n\r\n /*\r\n The payload whose metadata `<head>` currently reflects. Seeded with the\r\n HYDRATION payload, which is the point: on the initial mount the head is the\r\n server's own render of this very metadata, so there is nothing to correct —\r\n and re-applying would be a chance to get it wrong, since a payload from a\r\n build with no `metadata` key would wipe a head the server filled in\r\n correctly. The head is applied on SWAPS only.\r\n */\r\n const appliedMetadataSource = useRef(current.payload);\r\n\r\n useEffect(() => {\r\n if (appliedMetadataSource.current === current.payload) return;\r\n\r\n appliedMetadataSource.current = current.payload;\r\n\r\n /*\r\n Keyed on the payload's identity, so this covers a refresh as well as a\r\n navigation: `refresh()` produces a NEW payload for the page already on\r\n screen, and a page whose metadata is a function of its loader data can\r\n legitimately re-title itself when that data changes. One applier at the\r\n one place the page changes, rather than a call in each pathway that could\r\n be forgotten in the next one.\r\n */\r\n applyDocumentMetadata(document, current.payload.metadata);\r\n }, [current.payload]);\r\n\r\n /*\r\n DURING RENDER, not in an effect, and that placement is the requirement\r\n rather than a shortcut. A page component calling `currentRoute()` does it\r\n while IT is rendering, and child effects run before a parent's, so anything\r\n recorded from an effect here would be recorded too late to answer the first\r\n render of the page it describes — which on the initial mount is the only\r\n render there has been, and the server's match is all there is.\r\n\r\n Recording is keyed on the payload's identity (`current-route.ts`), so the\r\n extra passes render gives us for free — StrictMode's double invoke, a parent\r\n re-render — are recognised as the same page rather than counted as\r\n navigations.\r\n\r\n `routeSource`, NOT `payload`: they are the same object for every navigation,\r\n and differ only after a refresh, which produces a new payload for the page\r\n already on screen and must not be counted as a move (see `refresh.ts`).\r\n */\r\n recordCurrentRoute(current.routeSource);\r\n\r\n /*\r\n An INNER DocumentContext provider, nested inside the one `hydratePage`\r\n mounted. That outer provider is created once with the hydration payload and\r\n never changes, so anything reading the document context after a navigation\r\n would see the payload of the page the user has left. The nearest provider\r\n wins, so this one keeps it current.\r\n */\r\n /*\r\n `metadata` from the PAYLOAD, not `undefined`. The document context is the\r\n universal shape — the server provides the resolved metadata around the same\r\n tree — so handing the client's readers `undefined` was a lie the payload can\r\n now correct. It also removes a latent mismatch: a `<Head/>` rendered inside\r\n a Layout (not the App level) renders its tags into `#root` server-side, and\r\n hydrating that markup against `metadata: undefined` produced a tree the\r\n server never rendered.\r\n */\r\n return (\r\n <DocumentContext.Provider\r\n value={{ metadata: current.payload.metadata, payload: current.payload }}\r\n >\r\n {current.tree}\r\n </DocumentCont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e,gBAAgB,MAAM,MAAM,gBAAgB,YAAY;GAE7E,eAAe;GAEf,IAAI,cAAc;GAElB,AAAK,MAAM,QAAQ,MAAM,KAAK;EAChC;EAEA,OAAO,iBAAiB,YAAY,UAAU;EAE9C,aAAa;GACX,WAAW;GACX,OAAO,oBAAoB,YAAY,UAAU;GACjD,iBAAiB,iBAAiB;GAClC,iBAAiB,iBAAiB;EACpC;CACF,GAAG,CAAC,OAAO,SAAS,CAAC;CAwBrB,sBAAsB;EACpB,MAAM,WAAW,gBAAgB;EAEjC,IAAI,aAAa,QAAW;EAE5B,gBAAgB,UAAU;EAE1B,iBAAiB,UAAU,QAAQ;CACrC,GAAG,CAAC,OAAO,CAAC;CAUZ,MAAM,wBAAwB,OAAO,QAAQ,OAAO;CAEpD,gBAAgB;EACd,IAAI,sBAAsB,YAAY,QAAQ,SAAS;EAEvD,sBAAsB,UAAU,QAAQ;EAUxC,sBAAsB,UAAU,QAAQ,QAAQ,QAAQ;CAC1D,GAAG,CAAC,QAAQ,OAAO,CAAC;CAmBpB,mBAAmB,QAAQ,WAAW;CAkBtC,OACE,oBAAC,gBAAgB,UAAjB;EACE,OAAO;GAAE,UAAU,QAAQ,QAAQ;GAAU,SAAS,QAAQ;EAAQ;YAErE,QAAQ;CACe;AAE9B"}
|
|
1
|
+
{"version":3,"file":"navigation-root.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/client/navigation/navigation-root.tsx"],"sourcesContent":["import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from \"react\";\r\nimport { DocumentContext } from \"../../components/document-context\";\r\nimport type { HydrationDocumentPayloadSource } from \"../../hydration-payload\";\r\nimport type { MetadataOutput } from \"../../metadata\";\r\nimport { connectNavigator } from \"../../routing/navigator\";\r\nimport {\r\n fragmentOf,\r\n samePageFragment,\r\n withFragmentFrom,\r\n withoutFragment,\r\n} from \"../../routing/url-fragment\";\r\nimport { hydrateShared } from \"../../shared\";\r\nimport type { ClientPageEntry } from \"../runtime\";\r\nimport { recordCurrentRoute } from \"./current-route\";\r\nimport { fetchPageData } from \"./fetch-page-data\";\r\nimport { takePrefetchedPageData } from \"./prefetch\";\r\nimport { connectRefresher, createRefresher, type RefreshablePage } from \"./refresh\";\r\nimport { scrollToFragment } from \"./scroll-to-fragment\";\r\n\r\n/**\r\n * The component that makes a page REPLACEABLE.\r\n *\r\n * Hydration mounts a fixed tree — correct, because the first render must match\r\n * the server's markup byte for byte. Client navigation needs that same position\r\n * in the tree to be able to hold a *different* page later, which means state,\r\n * which means a component. This is that component and nothing more.\r\n *\r\n * ## Why the layout stays mounted\r\n *\r\n * The new tree is built by the same `buildHydratedTree` the server's payload\r\n * went through, so a navigation within one layout produces an element whose\r\n * layout components are the same types in the same positions. React reconciles\r\n * them rather than remounting, so layout state — an open menu, a scroll\r\n * container, a video — survives. That is the entire user-visible benefit of\r\n * client navigation, and it is a consequence of reusing the builder rather than\r\n * anything this file does.\r\n */\r\n\r\n/**\r\n * ONE tag `<head>` may hold at most one of, addressed the way the browser\r\n * already addresses it. No marker attribute: the tags this replaces were\r\n * rendered by `<Head/>` on the server and carry none, and a marker would make\r\n * the applier ignore exactly the tags it exists to correct — the first\r\n * navigation's.\r\n */\r\ntype ManagedTag = {\r\n /** Finds the existing tag, server-rendered or applied by a previous swap. */\r\n selector: string;\r\n create: (documentNode: Document) => Element;\r\n write: (element: Element, value: string) => void;\r\n};\r\n\r\nfunction metaTag(attribute: \"name\" | \"property\", key: string): ManagedTag {\r\n return {\r\n selector: `meta[${attribute}=\"${key}\"]`,\r\n create: documentNode => {\r\n const element = documentNode.createElement(\"meta\");\r\n\r\n element.setAttribute(attribute, key);\r\n\r\n return element;\r\n },\r\n write: (element, value) => element.setAttribute(\"content\", value),\r\n };\r\n}\r\n\r\nconst TITLE_TAG: ManagedTag = {\r\n selector: \"title\",\r\n create: documentNode => documentNode.createElement(\"title\"),\r\n write: (element, value) => {\r\n element.textContent = value;\r\n },\r\n};\r\n\r\nconst CANONICAL_TAG: ManagedTag = {\r\n selector: 'link[rel=\"canonical\"]',\r\n create: documentNode => {\r\n const element = documentNode.createElement(\"link\");\r\n\r\n element.setAttribute(\"rel\", \"canonical\");\r\n\r\n return element;\r\n },\r\n write: (element, value) => element.setAttribute(\"href\", value),\r\n};\r\n\r\n/**\r\n * The metadata, resolved into (tag, value) pairs in `<Head/>`'s ORDER and by\r\n * `<Head/>`'s RULES — including the og fallbacks and the fact that they apply\r\n * only when `openGraph` is present (`components/head.ts:21-24,43-48`).\r\n *\r\n * The duplication is deliberate and it is the known cost here. `<Head/>` is a\r\n * React component that renders elements into a tree; this writes elements into\r\n * a live `<head>` that no client tree owns. They cannot be one function today,\r\n * but they MUST agree: the head after navigating to a URL has to equal the head\r\n * after landing on it, or a share preview depends on how the visitor arrived.\r\n * The fix is a shared descriptor list both consume — see the report's followup.\r\n */\r\nfunction resolveManagedTags(\r\n metadata: MetadataOutput | undefined,\r\n): readonly (readonly [ManagedTag, string | undefined])[] {\r\n const keywords =\r\n metadata?.keywords === undefined\r\n ? undefined\r\n : Array.isArray(metadata.keywords)\r\n ? metadata.keywords.join(\", \")\r\n : (metadata.keywords as string);\r\n\r\n const openGraph = metadata?.openGraph;\r\n const twitter = metadata?.twitter;\r\n\r\n return [\r\n [TITLE_TAG, metadata?.title],\r\n [metaTag(\"name\", \"description\"), metadata?.description],\r\n [metaTag(\"name\", \"keywords\"), keywords],\r\n [CANONICAL_TAG, metadata?.canonical],\r\n [metaTag(\"name\", \"robots\"), metadata?.robots],\r\n [metaTag(\"property\", \"og:title\"), openGraph && (openGraph.title ?? metadata?.title)],\r\n [\r\n metaTag(\"property\", \"og:description\"),\r\n openGraph && (openGraph.description ?? metadata?.description),\r\n ],\r\n [metaTag(\"property\", \"og:image\"), openGraph?.image],\r\n [metaTag(\"property\", \"og:url\"), openGraph?.url],\r\n [metaTag(\"property\", \"og:type\"), openGraph?.type],\r\n [metaTag(\"name\", \"twitter:card\"), twitter?.card],\r\n [metaTag(\"name\", \"twitter:title\"), twitter?.title],\r\n [metaTag(\"name\", \"twitter:description\"), twitter?.description],\r\n [metaTag(\"name\", \"twitter:image\"), twitter?.image],\r\n ];\r\n}\r\n\r\n/**\r\n * Make `<head>` describe the page now on screen.\r\n *\r\n * ## Why this is imperative, and why that is not a shortcut\r\n *\r\n * `<Head/>` renders inside the App level, and the App level is deliberately NOT\r\n * in the hydrated tree — the client mounts at `#root`, which App contains\r\n * (`client/build-hydrated-tree.ts`'s header). So no client render can reach\r\n * `<head>`, and a swap either writes it directly or leaves the previous page's\r\n * title in the tab. It leaves it today; that is the bug.\r\n *\r\n * ## ABSENT MEANS REMOVED\r\n *\r\n * Every managed tag the new metadata does not set is REMOVED, not left alone.\r\n * `/` sets a description and `/contact-us` does not: keeping it would describe\r\n * the contact page with the home page's words to every crawler, share preview\r\n * and assistive reader that looks — a wrong answer, where an absent one is\r\n * merely absent. A title the new page does not set goes too, and the tab falls\r\n * back to the URL, which is the honest rendering of \"this page did not name\r\n * itself\".\r\n *\r\n * Only the tags `<Head/>` renders FROM METADATA are touched. The charset meta\r\n * is rendered unconditionally and belongs to the document, so it is left alone.\r\n *\r\n * Takes the document as an argument rather than reaching for the global, which\r\n * is what makes it provable in a suite with no DOM.\r\n */\r\nexport function applyDocumentMetadata(\r\n documentNode: Document,\r\n metadata: MetadataOutput | undefined,\r\n): void {\r\n for (const [tag, value] of resolveManagedTags(metadata)) {\r\n const existing = documentNode.querySelector(tag.selector);\r\n\r\n if (value === undefined) {\r\n existing?.remove();\r\n continue;\r\n }\r\n\r\n if (existing !== null) {\r\n tag.write(existing, value);\r\n continue;\r\n }\r\n\r\n const created = tag.create(documentNode);\r\n\r\n tag.write(created, value);\r\n documentNode.head.appendChild(created);\r\n }\r\n}\r\n\r\nexport type NavigationRootProps = {\r\n pages: readonly ClientPageEntry[];\r\n /** The payload the document was rendered from — the hydration one. */\r\n initialPayload: HydrationDocumentPayloadSource;\r\n /** The tree already built from {@link initialPayload}, rendered as-is first. */\r\n initialTree: ReactNode;\r\n /**\r\n * How a payload becomes a tree. Injected rather than imported so this\r\n * component is testable without the page registry or a bundler — the same\r\n * reason `hydratePage` takes its builder as an argument.\r\n */\r\n buildTree: (\r\n pages: readonly ClientPageEntry[],\r\n payload: HydrationDocumentPayloadSource,\r\n ) => Promise<ReactNode>;\r\n};\r\n\r\n/**\r\n * The page on screen. Defined in `refresh.ts` because the third field is that\r\n * file's decision: `routeSource` is the payload object `current-route.ts`\r\n * identifies the route by, which is `payload` after a navigation but the\r\n * PREVIOUS page's object after a refresh — a refresh must not shift\r\n * `previousRoute()` onto the page the user is already looking at.\r\n */\r\ntype Current = RefreshablePage;\r\n\r\nexport function NavigationRoot({\r\n pages,\r\n initialPayload,\r\n initialTree,\r\n buildTree,\r\n}: NavigationRootProps) {\r\n const [current, setCurrent] = useState<Current>({\r\n payload: initialPayload,\r\n tree: initialTree,\r\n routeSource: initialPayload,\r\n });\r\n\r\n /*\r\n The latest state, readable from the effect below — which closes over the\r\n render that created it and would otherwise see the page the user was on\r\n when the runtime connected. A ref rather than an effect dependency because\r\n re-running the effect on every swap would disconnect and reconnect the\r\n navigator mid-navigation.\r\n */\r\n const currentRef = useRef(current);\r\n\r\n currentRef.current = current;\r\n\r\n /*\r\n THE ORDERING PROBLEM, and this ref is half of the answer to it.\r\n\r\n The element a fragment names lives in the tree that has not been built yet:\r\n at the moment `apply` finishes fetching, the DOM still holds the page the\r\n user is LEAVING. Scrolling there finds nothing, and finding nothing is\r\n silent — indistinguishable from the fragment bug itself.\r\n\r\n So the fragment is not scrolled to; it is HANDED OVER. `apply` parks it here\r\n immediately before the `setCurrent` that swaps the tree, and the layout\r\n effect below — which React runs after it has committed that tree to the DOM\r\n and before the browser paints — spends it. Read the two together; neither\r\n half means anything alone.\r\n */\r\n const pendingFragment = useRef<string | undefined>(undefined);\r\n\r\n useEffect(() => {\r\n /*\r\n THE RACE THIS COUNTER EXISTS FOR. Two clicks in quick succession start two\r\n fetches; the second can easily answer first (a cached page beating an\r\n uncached one is the common case, not the exotic one). Without a token the\r\n slower FIRST response lands last and the user ends up on the page they\r\n navigated away from, with the address bar showing the other one.\r\n\r\n Every navigation takes a token; a result is applied only if its token is\r\n still the newest. Superseded responses are dropped silently — they are not\r\n errors, they are answers to a question the user stopped asking.\r\n */\r\n let token = 0;\r\n let disposed = false;\r\n /*\r\n The URL this runtime last put in the address bar, so `popstate` can tell a\r\n move BETWEEN pages from a move between two fragments of one page. Seeded\r\n with the URL the document was loaded at, which is the entry the first Back\r\n would come from.\r\n */\r\n let committedUrl = window.location.href;\r\n\r\n /**\r\n * @param honourFragment whether the URL's fragment should be SCROLLED to\r\n * once the new page is on screen. True for a navigation the app asked for\r\n * — a `<Link>` click, `navigateTo` — and false for Back/Forward, where the\r\n * browser has already restored the scroll position of the entry being\r\n * returned to and moving the page again would overwrite the user's own\r\n * position with the anchor they had scrolled away from. (Restoration is\r\n * the browser's, deliberately: canon `0342c0d4`.)\r\n *\r\n * The fragment is still PRESERVED in the URL in both cases — see below.\r\n */\r\n const apply = async (\r\n url: string,\r\n replace: boolean,\r\n honourFragment: boolean,\r\n ): Promise<void> => {\r\n const ticket = ++token;\r\n /*\r\n A prefetched response is CONSUMED, never merely read — `take` removes it,\r\n so the same speculative fetch can satisfy exactly one navigation and a\r\n second click on the same link goes to the network. That matters because\r\n the HTTP cache cannot stand in for this: dev responses are `no-store`\r\n (`server/dev-server.ts:254`) and production is `private` with no\r\n `max-age` (`server/render-page.ts:432`), so the browser will not reliably\r\n replay the speculative response on the real click.\r\n\r\n The race guard below still holds on a cache hit: `??` short-circuits the\r\n await, and the synchronous path reaches the same `ticket !== token` check.\r\n */\r\n const result = takePrefetchedPageData(url) ?? (await fetchPageData(url));\r\n\r\n if (disposed || ticket !== token) return;\r\n\r\n if (result.type === \"hard-navigate\") {\r\n // The documented degradation: hand the URL back to the browser. The\r\n // user still gets the page — see `fetch-page-data.ts`.\r\n console.warn(`Warlock navigation fell back to a full load (${result.reason}):`, url);\r\n window.location.assign(url);\r\n\r\n return;\r\n }\r\n\r\n let tree: ReactNode;\r\n\r\n try {\r\n tree = await buildTree(pages, result.payload);\r\n } catch (error) {\r\n // The payload was fine but its page chunk would not load or compose —\r\n // a stale bundle after a deploy is the realistic cause. A full load\r\n // fetches the current bundle, which is also the fix.\r\n console.warn(\"Warlock navigation could not build the page tree:\", error);\r\n window.location.assign(url);\r\n\r\n return;\r\n }\r\n\r\n if (disposed || ticket !== token) return;\r\n\r\n /*\r\n Shared state BEFORE the render that consumes it. `hydrateShared`\r\n installs the snapshot `useShared()` reads; swapping the tree first would\r\n render one frame of the new page against the previous page's shared\r\n state — locale, permissions, the current user.\r\n */\r\n hydrateShared(result.payload.shared);\r\n\r\n /*\r\n The fragment PUT BACK. `result.url` comes from `response.url`, and a\r\n fragment is never sent to a server, so the URL a navigation would\r\n otherwise be written to history from has had it stripped — which is how\r\n `<Link href=\"/docs#install\">` used to land on `/docs` with the author's\r\n fragment gone from the address bar for good.\r\n\r\n Applied on EVERY path, Back included: a popstate re-fetch that wrote\r\n `result.url` back would delete the fragment from an entry the user is\r\n merely returning to.\r\n */\r\n const finalUrl = withFragmentFrom(result.url, url);\r\n\r\n // History AFTER the fetch succeeded, never before. Pushing optimistically\r\n // would leave the address bar pointing at a page that then failed to\r\n // load, and a Back press would return to a URL the user never saw.\r\n if (replace) {\r\n window.history.replaceState(null, \"\", finalUrl);\r\n } else {\r\n window.history.pushState(null, \"\", finalUrl);\r\n }\r\n\r\n committedUrl = finalUrl;\r\n\r\n // Handed to the layout effect, which runs once React has committed the\r\n // tree below to the DOM — the first moment the target can exist. Set\r\n // unconditionally so a navigation with no fragment CLEARS a fragment left\r\n // pending by one that was superseded.\r\n pendingFragment.current = honourFragment ? fragmentOf(finalUrl) : undefined;\r\n\r\n // A navigation IS the route moving, so the fetched payload is both the\r\n // page and the route's identity.\r\n setCurrent({ payload: result.payload, tree, routeSource: result.payload });\r\n };\r\n\r\n /*\r\n The same counter `apply` above takes its tickets from, handed to\r\n `refresh()` as a predicate. ONE mechanism, not two: a refresh and a\r\n navigation can overtake each other in either direction, and separate\r\n counters would leave each blind to the other.\r\n */\r\n const claimTicket = (): (() => boolean) => {\r\n const ticket = ++token;\r\n\r\n return () => !disposed && ticket === token;\r\n };\r\n\r\n const previousRefresher = connectRefresher(\r\n createRefresher({\r\n readCurrent: () => currentRef.current,\r\n writeCurrent: setCurrent,\r\n buildTree: payload => buildTree(pages, payload),\r\n claimTicket,\r\n }),\r\n );\r\n\r\n const previousNavigator = connectNavigator((url, options) => {\r\n const replace = options?.replace === true;\r\n\r\n /*\r\n THIS page with a fragment on it — `#reviews`, or the current path spelled\r\n out with one appended. No fetch, no tree swap: the page is already here,\r\n and re-fetching it would discard its DOM and everything live in it to\r\n arrive back where we started, one round trip later. Address bar first,\r\n then the jump, which is the order the browser uses for a plain anchor.\r\n */\r\n const fragment = samePageFragment(url, window.location.href);\r\n\r\n if (fragment !== undefined) {\r\n if (replace) {\r\n window.history.replaceState(null, \"\", url);\r\n } else {\r\n window.history.pushState(null, \"\", url);\r\n }\r\n\r\n committedUrl = window.location.href;\r\n\r\n // The target is in the DOM already, so there is nothing to wait for —\r\n // and nothing to hand to the layout effect, which no swap would fire.\r\n scrollToFragment(document, fragment);\r\n\r\n return true;\r\n }\r\n\r\n void apply(url, replace, true);\r\n\r\n // Accepted: the caller suppresses the browser's default. Returning `true`\r\n // before the fetch resolves is deliberate — the decision to handle a link\r\n // cannot wait on the network without the browser having already followed\r\n // it.\r\n return true;\r\n });\r\n\r\n /*\r\n Back/Forward. The entry is already in history and the URL has already\r\n changed by the time this fires, so the page is fetched and swapped with\r\n `replace` — pushing here would append a duplicate entry and make Back\r\n require two presses.\r\n */\r\n const onPopState = (): void => {\r\n const target = window.location.href;\r\n /*\r\n A hash-only move within one page — Back off a `#section` click, or\r\n Forward onto one. The document is the same document and the tree on\r\n screen is already the right tree, so there is nothing to fetch: the\r\n browser has changed the URL and restored the position for that entry\r\n itself, and re-fetching would throw away a live page to rebuild the one\r\n already showing. Scroll restoration stays the browser's (canon\r\n `0342c0d4`), which is exactly what leaving this alone means.\r\n */\r\n const hashOnlyMove = withoutFragment(target) === withoutFragment(committedUrl);\r\n\r\n committedUrl = target;\r\n\r\n if (hashOnlyMove) return;\r\n\r\n void apply(target, true, false);\r\n };\r\n\r\n window.addEventListener(\"popstate\", onPopState);\r\n\r\n return () => {\r\n disposed = true;\r\n window.removeEventListener(\"popstate\", onPopState);\r\n connectNavigator(previousNavigator);\r\n connectRefresher(previousRefresher);\r\n };\r\n }, [pages, buildTree]);\r\n\r\n /*\r\n THE OTHER HALF OF THE ORDERING PROBLEM (see `pendingFragment` above).\r\n\r\n `useLayoutEffect`, not `useEffect`, and the difference is the whole point:\r\n React runs a layout effect after it has COMMITTED this render to the DOM and\r\n BEFORE the browser paints. That is the earliest instant the new page's\r\n elements exist — a scroll any sooner finds nothing — and the last instant\r\n before the user sees anything, so the page is never painted at the top and\r\n then jumped. `useEffect` would satisfy the first requirement and not the\r\n second: it runs after paint, which is a visible flash of the wrong position.\r\n\r\n Keyed on `current` rather than reaching for a fresh render: the effect fires\r\n on the swap that put the target in the DOM, so no polling, no rAF, no\r\n timeout. What it CANNOT wait for is content that arrives later still — an\r\n image without dimensions above the target, a component that suspends — which\r\n moves the target after we have scrolled to where it was. That is the known\r\n limit of this mechanism and it is the same one a browser has.\r\n\r\n Consumed once: the fragment is cleared as it is read, so a later re-render\r\n (a refresh, a parent's state change) does not yank the page back to an\r\n anchor the user has since scrolled away from.\r\n */\r\n useLayoutEffect(() => {\r\n const fragment = pendingFragment.current;\r\n\r\n if (fragment === undefined) return;\r\n\r\n pendingFragment.current = undefined;\r\n\r\n scrollToFragment(document, fragment);\r\n }, [current]);\r\n\r\n /*\r\n The payload whose metadata `<head>` currently reflects. Seeded with the\r\n HYDRATION payload, which is the point: on the initial mount the head is the\r\n server's own render of this very metadata, so there is nothing to correct —\r\n and re-applying would be a chance to get it wrong, since a payload from a\r\n build with no `metadata` key would wipe a head the server filled in\r\n correctly. The head is applied on SWAPS only.\r\n */\r\n const appliedMetadataSource = useRef(current.payload);\r\n\r\n useEffect(() => {\r\n if (appliedMetadataSource.current === current.payload) return;\r\n\r\n appliedMetadataSource.current = current.payload;\r\n\r\n /*\r\n Keyed on the payload's identity, so this covers a refresh as well as a\r\n navigation: `refresh()` produces a NEW payload for the page already on\r\n screen, and a page whose metadata is a function of its loader data can\r\n legitimately re-title itself when that data changes. One applier at the\r\n one place the page changes, rather than a call in each pathway that could\r\n be forgotten in the next one.\r\n */\r\n applyDocumentMetadata(document, current.payload.metadata);\r\n }, [current.payload]);\r\n\r\n /*\r\n DURING RENDER, not in an effect, and that placement is the requirement\r\n rather than a shortcut. A page component calling `currentRoute()` does it\r\n while IT is rendering, and child effects run before a parent's, so anything\r\n recorded from an effect here would be recorded too late to answer the first\r\n render of the page it describes — which on the initial mount is the only\r\n render there has been, and the server's match is all there is.\r\n\r\n Recording is keyed on the payload's identity (`current-route.ts`), so the\r\n extra passes render gives us for free — StrictMode's double invoke, a parent\r\n re-render — are recognised as the same page rather than counted as\r\n navigations.\r\n\r\n `routeSource`, NOT `payload`: they are the same object for every navigation,\r\n and differ only after a refresh, which produces a new payload for the page\r\n already on screen and must not be counted as a move (see `refresh.ts`).\r\n */\r\n recordCurrentRoute(current.routeSource);\r\n\r\n /*\r\n An INNER DocumentContext provider, nested inside the one `hydratePage`\r\n mounted. That outer provider is created once with the hydration payload and\r\n never changes, so anything reading the document context after a navigation\r\n would see the payload of the page the user has left. The nearest provider\r\n wins, so this one keeps it current.\r\n */\r\n /*\r\n `metadata` from the PAYLOAD, not `undefined`. The document context is the\r\n universal shape — the server provides the resolved metadata around the same\r\n tree — so handing the client's readers `undefined` was a lie the payload can\r\n now correct. It also removes a latent mismatch: a `<Head/>` rendered inside\r\n a Layout (not the App level) renders its tags into `#root` server-side, and\r\n hydrating that markup against `metadata: undefined` produced a tree the\r\n server never rendered.\r\n */\r\n return (\r\n <DocumentContext.Provider\r\n value={{ metadata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AyB;GAC7B,MAAM,SAAS,OAAO,SAAS;GAU/B,MAAM,eAAe,gBAAgB,MAAM,MAAM,gBAAgB,YAAY;GAE7E,eAAe;GAEf,IAAI,cAAc;GAElB,AAAK,MAAM,QAAQ,MAAM,KAAK;EAChC;EAEA,OAAO,iBAAiB,YAAY,UAAU;EAE9C,aAAa;GACX,WAAW;GACX,OAAO,oBAAoB,YAAY,UAAU;GACjD,iBAAiB,iBAAiB;GAClC,iBAAiB,iBAAiB;EACpC;CACF,GAAG,CAAC,OAAO,SAAS,CAAC;CAwBrB,sBAAsB;EACpB,MAAM,WAAW,gBAAgB;EAEjC,IAAI,aAAa,QAAW;EAE5B,gBAAgB,UAAU;EAE1B,iBAAiB,UAAU,QAAQ;CACrC,GAAG,CAAC,OAAO,CAAC;CAUZ,MAAM,wBAAwB,OAAO,QAAQ,OAAO;CAEpD,gBAAgB;EACd,IAAI,sBAAsB,YAAY,QAAQ,SAAS;EAEvD,sBAAsB,UAAU,QAAQ;EAUxC,sBAAsB,UAAU,QAAQ,QAAQ,QAAQ;CAC1D,GAAG,CAAC,QAAQ,OAAO,CAAC;CAmBpB,mBAAmB,QAAQ,WAAW;CAkBtC,OACE,oBAAC,gBAAgB,UAAjB;EACE,OAAO;GAAE,UAAU,QAAQ,QAAQ;GAAU,SAAS,QAAQ;EAAQ;YAErE,QAAQ;CACe;AAE9B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prefetch.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"prefetch.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/client/navigation/prefetch.ts"],"sourcesContent":["/**\n * Speculative page data, fetched on hover and spent on the click that follows.\n *\n * A prefetch is a GUESS. The user pointed at a link; they may never click it.\n * Everything about this module follows from that one fact:\n *\n * - it never reports a failure — nobody asked for this request, so nobody may\n * be told it failed. A failed prefetch leaves the cache empty and the click\n * fetches for real, which is the behaviour we had before this file existed.\n * - it never delays a click. `prefetchPageData` is fire-and-forget; the\n * navigation path reads the cache synchronously and does not wait on it.\n * - it is BOUNDED and it EXPIRES. A cached payload is a copy of a page that\n * may already have changed, so it may only be served while it is very\n * probably still true.\n *\n * ## The read side is deliberately separate from the write side\n *\n * `<Link>` writes (on hover); the navigation runtime reads (on click). Neither\n * knows about the other — they share a URL, and this module is the only thing\n * between them. That is what lets prefetch be added without touching the\n * navigation state machine.\n */\nimport type { PageDataResult } from \"./fetch-page-data\";\nimport { fetchPageData } from \"./fetch-page-data\";\n\n/** A prefetch result worth keeping — only ever a successful payload. */\nexport type PrefetchedPageData = Extract<PageDataResult, { type: \"payload\" }>;\n\n/**\n * How many pages may be held at once.\n *\n * Ten, because the working set this serves is \"links the pointer has crossed in\n * the last few seconds\", which is small by construction — a nav bar, a card\n * grid the user is scanning. A page payload is loader data, not markup, but it\n * is still measured in tens of kilobytes, so an unbounded map on a long-lived\n * SPA session is a slow leak with no upper edge. Ten covers scanning a menu and\n * costs at most a few hundred kilobytes in the worst case.\n *\n * Eviction is by INSERTION ORDER, not by recency: an entry here is written once\n * and read at most once, so there is no recency to track — the oldest guess is\n * always the one least likely to be spent.\n */\nexport const PREFETCH_CACHE_LIMIT = 10;\n\n/**\n * How long a cached payload may be served, in milliseconds.\n *\n * Thirty seconds. This is a SAFETY bound and not a performance knob: the\n * interval this feature exists to cover is hover-to-click, which is well under\n * a second, and every millisecond beyond that is pure staleness risk. A payload\n * served after the user has changed the data behind it renders a wrong page —\n * silently, and with no way for them to tell. Thirty seconds is long enough\n * that a hesitant click still hits, and short enough that no realistic\n * \"navigate away, mutate something, come back\" flow can complete inside it.\n */\nexport const PREFETCH_TTL_MS = 30_000;\n\ntype CacheEntry = {\n result: PrefetchedPageData;\n /** `Date.now()` at which this entry stops being servable. */\n expiresAt: number;\n};\n\n/**\n * Insertion-ordered by `Map` contract, which is what makes eviction a `keys()\n * .next()` and not a bookkeeping structure.\n */\nconst cache = new Map<string, CacheEntry>();\n\n/**\n * URLs with a request already in the air. Repeated `mouseenter` events on the\n * same anchor are the norm, not the exception — a pointer crossing a link fires\n * as the user's hand settles — and without this each one would be its own\n * request for the same page.\n */\nconst inFlight = new Set<string>();\n\n/**\n * Whether there is a browser to prefetch from.\n *\n * Called rather than assumed because `<Link>` is universal: the same module\n * graph is evaluated during a server render, where a speculative request would\n * be a request the server makes to itself for a page nobody is looking at.\n */\nfunction isBrowser(): boolean {\n return typeof window !== \"undefined\";\n}\n\nfunction evictOldest(): void {\n const oldest = cache.keys().next();\n\n if (oldest.done !== true) cache.delete(oldest.value);\n}\n\n/**\n * Fetch a URL's page data ahead of the click, and cache it.\n *\n * NEVER REJECTS and never reports. The returned promise exists so a test can\n * await the speculative work; callers in the component tree discard it\n * (`void prefetchPageData(url)`) and must not await it — a click that waited on\n * a guess would be slower than one that never made it.\n *\n * The caller decides WHETHER a URL may be prefetched. This function does not\n * re-derive that: it has a URL and no way to tell an in-app path from a\n * cross-origin one it must never touch. `<Link>` gates on `isInApp`.\n */\nexport async function prefetchPageData(url: string): Promise<void> {\n if (!isBrowser()) return;\n\n if (inFlight.has(url)) return;\n\n // A fresh entry means the answer is already here; an expired one is dropped\n // now so the fetch below can replace it.\n const cached = cache.get(url);\n\n if (cached !== undefined) {\n if (cached.expiresAt > Date.now()) return;\n\n cache.delete(url);\n }\n\n inFlight.add(url);\n\n try {\n const result = await fetchPageData(url);\n\n /*\n `hard-navigate` is NOT cached. It is the signal that this URL needs a full\n page load — a 404, a redirect to an interstitial, a proxy that stripped\n the marker header. Caching it would mean the click either replays a\n failure or, worse, consults an entry that cannot be rendered. The click\n re-asks and gets the same answer, correctly, through the navigation path\n that already knows how to degrade.\n */\n if (result.type !== \"payload\") return;\n\n if (cache.size >= PREFETCH_CACHE_LIMIT) evictOldest();\n\n cache.set(url, { result, expiresAt: Date.now() + PREFETCH_TTL_MS });\n } catch {\n /*\n `fetchPageData` already converts every network failure into a\n `hard-navigate`, so reaching here means something unforeseen. It is\n swallowed anyway, deliberately and without a log: this request was\n speculative, the user never asked for it, and a console full of warnings\n about requests nobody made is how a helpful optimisation becomes noise\n that hides real errors.\n */\n } finally {\n // In `finally` so a failed attempt does not poison the URL for the rest of\n // the session — the next hover is allowed to try again.\n inFlight.delete(url);\n }\n}\n\n/**\n * Take the prefetched payload for a URL, if there is a live one.\n *\n * CONSUMING: the entry is removed whether or not the caller ends up using it.\n * One hover buys one saved round trip. Serving the same payload to a second\n * navigation would double the window in which it can be wrong, in exchange for\n * a saving the user did not notice the first time.\n *\n * @returns the cached result, or `undefined` — in which case the caller fetches\n * exactly as it did before this module existed.\n */\nexport function takePrefetchedPageData(url: string): PrefetchedPageData | undefined {\n const entry = cache.get(url);\n\n if (entry === undefined) return undefined;\n\n cache.delete(url);\n\n // Expiry is checked on READ, not on a timer: a timer would keep a\n // long-lived page waking up to clean a cache that is already bounded, and an\n // entry nobody reads costs nothing but the slot it is evicted from anyway.\n return entry.expiresAt > Date.now() ? entry.result : undefined;\n}\n\n/**\n * Drop everything. For tests, and for any caller that knows the cached pages\n * are now wrong — the module-level cache would otherwise outlive a suite and\n * leak into the next one.\n */\nexport function resetPrefetchCache(): void {\n cache.clear();\n inFlight.clear();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA0CA,MAAa,uBAAuB;;;;;;;;;;;;AAapC,MAAa,kBAAkB;;;;;AAY/B,MAAM,wBAAQ,IAAI,IAAwB;;;;;;;AAQ1C,MAAM,2BAAW,IAAI,IAAY;;;;;;;;AASjC,SAAS,YAAqB;CAC5B,OAAO,OAAO,WAAW;AAC3B;AAEA,SAAS,cAAoB;CAC3B,MAAM,SAAS,MAAM,KAAK,EAAE,KAAK;CAEjC,IAAI,OAAO,SAAS,MAAM,MAAM,OAAO,OAAO,KAAK;AACrD;;;;;;;;;;;;;AAcA,eAAsB,iBAAiB,KAA4B;CACjE,IAAI,CAAC,UAAU,GAAG;CAElB,IAAI,SAAS,IAAI,GAAG,GAAG;CAIvB,MAAM,SAAS,MAAM,IAAI,GAAG;CAE5B,IAAI,WAAW,QAAW;EACxB,IAAI,OAAO,YAAY,KAAK,IAAI,GAAG;EAEnC,MAAM,OAAO,GAAG;CAClB;CAEA,SAAS,IAAI,GAAG;CAEhB,IAAI;EACF,MAAM,SAAS,MAAM,cAAc,GAAG;EAUtC,IAAI,OAAO,SAAS,WAAW;EAE/B,IAAI,MAAM,YAA8B,YAAY;EAEpD,MAAM,IAAI,KAAK;GAAE;GAAQ,WAAW,KAAK,IAAI,IAAI;EAAgB,CAAC;CACpE,QAAQ,CASR,UAAU;EAGR,SAAS,OAAO,GAAG;CACrB;AACF;;;;;;;;;;;;AAaA,SAAgB,uBAAuB,KAA6C;CAClF,MAAM,QAAQ,MAAM,IAAI,GAAG;CAE3B,IAAI,UAAU,QAAW,OAAO;CAEhC,MAAM,OAAO,GAAG;CAKhB,OAAO,MAAM,YAAY,KAAK,IAAI,IAAI,MAAM,SAAS;AACvD"}
|
|
@@ -2,7 +2,7 @@ import { hydrateShared } from "../../shared.mjs";
|
|
|
2
2
|
import { fetchPageData } from "./fetch-page-data.mjs";
|
|
3
3
|
import { routerEvents } from "../../routing/router-events.mjs";
|
|
4
4
|
|
|
5
|
-
//#region
|
|
5
|
+
//#region web/src/client/navigation/refresh.ts
|
|
6
6
|
/**
|
|
7
7
|
* A refresh is a "replace" as far as history and its listeners are concerned:
|
|
8
8
|
* no entry is pushed, and one may be replaced when the server redirects.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"refresh.mjs","names":[],"sources":["../../../../../../../../web/src/client/navigation/refresh.ts"],"sourcesContent":["import type { ReactNode } from \"react\";\nimport type { HydrationDocumentPayloadSource } from \"../../hydration-payload\";\nimport { routerEvents } from \"../../routing/router-events\";\nimport { hydrateShared } from \"../../shared\";\nimport { fetchPageData } from \"./fetch-page-data\";\n\n/**\n * Re-run the current route's loaders and re-render it — under MRR's name.\n *\n * ## The name is MRR's; the behaviour is deliberately stronger\n *\n * `@mongez/react-router`'s `refresh()` re-RENDERS the current route: it is a\n * CSR router, all the data is already in the browser, and there is nothing to\n * go and get. Warlock's page data comes from the server, so re-rendering alone\n * would show the user exactly what they were already looking at. This\n * `refresh()` therefore re-FETCHES first — the same `x-warlock-data` request a\n * client navigation makes — and then swaps the page in. Strictly more than the\n * name promises elsewhere, never less, which is why the name could be kept.\n *\n * That difference is stated on {@link refresh} itself and not only here,\n * because the developer who needs to know it is the one hovering the symbol.\n *\n * ## Why the failure mode is the opposite of a navigation's\n *\n * `fetch-page-data.ts` degrades EVERY failure to a real browser load, and that\n * is right for a navigation: the user asked to go somewhere and must arrive.\n * A refresh is the opposite situation — the user is already where they want to\n * be. Handing the URL to `window.location.assign` would throw away their scroll\n * position, their open dialogs and the form they just posted from, in exchange\n * for data they only asked to update. So a failed refresh keeps the page\n * exactly as it is and announces the error; the screen the user has is never\n * the price of a network blip.\n *\n * ## Not server actions\n *\n * The mutation is an ordinary POST to the API, and this is what you call after\n * it. Nothing here writes; nothing here knows a mutation happened.\n */\n\n/**\n * The page on screen, as the navigation runtime holds it.\n *\n * `routeSource` is the reason this type is not simply `{ payload, tree }`. See\n * {@link createRefresher} for what it carries and why it is separate from\n * `payload`.\n */\nexport type RefreshablePage = {\n /** What the tree was built from — what the document context reports. */\n payload: HydrationDocumentPayloadSource;\n /** The rendered page. */\n tree: ReactNode;\n /**\n * The payload object `current-route.ts` identifies the current ROUTE by,\n * which is the same object as `payload` after a navigation but NOT after a\n * refresh.\n */\n routeSource: HydrationDocumentPayloadSource;\n};\n\n/**\n * Everything a refresh needs that only `NavigationRoot` can provide.\n *\n * Injected rather than reached for, and kept to four members: the page on\n * screen, the swap, the tree builder, and the race counter. Everything else a\n * refresh does — the request, the shared snapshot, the address bar, the\n * lifecycle events — is this module's own and is not injected, so a test\n * exercises the real ones.\n */\nexport type RefreshRuntime = {\n /** The page on screen at the moment it is asked for, never a captured copy. */\n readCurrent: () => RefreshablePage;\n /** Put a page on screen. */\n writeCurrent: (page: RefreshablePage) => void;\n /** How a payload becomes a tree, with the page registry already bound. */\n buildTree: (payload: HydrationDocumentPayloadSource) => Promise<ReactNode>;\n /**\n * Take a ticket from the navigation runtime's race counter.\n *\n * @returns a predicate that answers whether this operation is still the\n * newest one. THE SAME counter navigations take their tickets from — a\n * refresh and a navigation can overtake each other, so a second mechanism\n * would simply fail to notice.\n */\n claimTicket: () => () => boolean;\n};\n\n/**\n * What {@link refresh} delegates to once the runtime has connected itself.\n *\n * @returns `true` when fresh data is on screen. `false` covers every other\n * outcome — no runtime, no browser, the request failed, or a newer operation\n * overtook this one — and none of them left the page in a worse state than\n * they found it.\n */\nexport type Refresher = () => Promise<boolean>;\n\n/**\n * A refresh is a \"replace\" as far as history and its listeners are concerned:\n * no entry is pushed, and one may be replaced when the server redirects.\n */\nconst REFRESH_MODE = \"replace\" as const;\n\n/**\n * Build the runtime's refresher.\n *\n * Called by `NavigationRoot`, which connects the result with\n * {@link connectRefresher}. Not part of the public surface — a caller holding\n * its own refresher would be refreshing a page it does not own.\n *\n * ## The `routeSource` decision, which lives here\n *\n * `recordCurrentRoute` (`current-route.ts`) recognises a route by its payload\n * OBJECT IDENTITY: one swap is one payload object, which is what keeps a\n * StrictMode double render from counting as a navigation. A refresh breaks that\n * assumption on its own, because it produces a brand new payload object for the\n * page already on screen — so recording it would shift `previousRoute()` to the\n * page the user is currently looking at, and a \"back to where I came from\" link\n * would point at itself.\n *\n * So a refresh that came back as the SAME entry carries the previous\n * `routeSource` forward untouched: the fresh payload renders, and the route\n * does not move, because it did not. A refresh that came back as a DIFFERENT\n * entry — a session expiring into `/login` is the ordinary cause — is a real\n * move the server made, and is recorded as one; anything else would leave\n * `currentRoute()` naming a page that is no longer on screen.\n *\n * Comparing `name` here is not route matching (canon `9c8f878b`): both names\n * were decided by the server's router and merely travelled here. Nothing in\n * this file looks at a path.\n */\nexport function createRefresher(runtime: RefreshRuntime): Refresher {\n return async () => {\n // Not merely defensive: `refresh()` is importable from a universal module,\n // so a component can call it during the server render. There is no page on\n // screen to refresh there, and no address bar to read one from.\n if (typeof window === \"undefined\") return false;\n\n // The address bar IS the current route's URL — the runtime has already put\n // the resolved URL there — so there is no second copy to drift from it.\n const url = window.location.href;\n const isCurrent = runtime.claimTicket();\n\n routerEvents.emitNavigating({ url, mode: REFRESH_MODE });\n\n const result = await fetchPageData(url);\n\n // Superseded, and silently: this is the answer to a question the user\n // stopped asking. Not an error, and not an event — the operation that\n // overtook this one emits its own outcome.\n if (!isCurrent()) return false;\n\n if (result.type === \"hard-navigate\") {\n /*\n NO `window.location.assign` HERE, and this line is the whole point of\n the file. `fetchPageData` reports a hard navigation because that is the\n correct degradation for GOING somewhere; for STAYING somewhere it would\n destroy the screen the user already has in order to deliver data they\n asked to update. The page stays; the error is announced.\n */\n const error = new Error(`Warlock refresh failed: ${result.reason}`);\n\n console.warn(\"Warlock refresh could not re-fetch the current page:\", result.reason);\n routerEvents.emitNavigationError({ url, mode: REFRESH_MODE, error });\n\n return false;\n }\n\n let tree: ReactNode;\n\n try {\n tree = await runtime.buildTree(result.payload);\n } catch (error) {\n // A stale bundle after a deploy is the realistic cause. A navigation\n // reloads to fix it; a refresh cannot, for the same reason as above.\n console.warn(\"Warlock refresh could not build the page tree:\", error);\n routerEvents.emitNavigationError({ url, mode: REFRESH_MODE, error });\n\n return false;\n }\n\n if (!isCurrent()) return false;\n\n // Shared state BEFORE the render that consumes it, exactly as a navigation\n // does it — a refresh can carry a changed locale or a changed user too.\n hydrateShared(result.payload.shared);\n\n const previous = runtime.readCurrent();\n const sameEntry = result.payload.name === previous.payload.name;\n\n /*\n Only when the server actually moved us — `result.url` is the absolute URL\n the response came from and `url` came from the address bar, so they differ\n only when a redirect was followed. REPLACE even then: a refresh is not a\n destination, and pushing would make Back need two presses to leave a page\n the user never chose to visit twice.\n\n Keyed on the URL, not on `sameEntry`: the address bar's job is to name the\n URL on screen, and a redirect that stayed within one route entry\n (`?page=2` collapsing to `?page=1`) has still changed it.\n */\n if (result.url !== url) {\n window.history.replaceState(null, \"\", result.url);\n }\n\n runtime.writeCurrent({\n payload: result.payload,\n tree,\n routeSource: sameEntry ? previous.routeSource : result.payload,\n });\n\n routerEvents.emitNavigated({ url, resolvedUrl: result.url, mode: REFRESH_MODE });\n\n return true;\n };\n}\n\nlet connected: Refresher | undefined;\n\n/**\n * Installed by the navigation runtime at mount, and torn down with `undefined`.\n *\n * The same seam shape as `routing/navigator.ts`, and for the same reason:\n * {@link refresh} is universal and must not import the client runtime, so the\n * runtime registers itself instead.\n *\n * @returns the previous refresher, so a caller that installs one can restore\n * what was there.\n */\nexport function connectRefresher(next: Refresher | undefined): Refresher | undefined {\n const previous = connected;\n\n connected = next;\n\n return previous;\n}\n\n/**\n * Re-fetch the current route's data and re-render the page with it.\n *\n * What you call after a mutation — a normal POST to your API, then this — to\n * put the server's new truth on screen without a full reload. The layout stays\n * mounted, so scroll position, open menus and playing media survive.\n *\n * ## Stronger than the `refresh()` you may know\n *\n * `@mongez/react-router`'s `refresh()` only RE-RENDERS the current route. This\n * one RE-FETCHES the route's data first and then re-renders, because in Warlock\n * the data lives on the server and a re-render alone would show the user what\n * they are already looking at. Anywhere MRR's `refresh()` was correct, this is\n * too; it simply also picks up what changed.\n *\n * ## It cannot cost you the page\n *\n * If the request fails — offline, a 500, a proxy answering HTML — the page on\n * screen is left exactly as it was and `false` comes back. There is no reload\n * and no error screen. Subscribe to `routerEvents.onNavigationError` to show\n * the user something.\n *\n * ```ts\n * await api.post(\"/products\", form);\n *\n * if (!(await refresh())) toast.error(\"Could not reload the list.\");\n * ```\n *\n * @returns `true` when fresh data is on screen. `false` when nothing was\n * applied: no client runtime is connected (a server render, or before\n * hydration), the re-fetch failed, or a navigation overtook the refresh. Safe\n * to call in any of those — it never throws.\n */\nexport async function refresh(): Promise<boolean> {\n if (!connected) return false;\n\n return connected();\n}\n"],"mappings":";;;;;;;;;AAoGA,MAAM,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BrB,SAAgB,gBAAgB,SAAoC;CAClE,OAAO,YAAY;EA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AO,UAAU;AACnB"}
|
|
1
|
+
{"version":3,"file":"refresh.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/client/navigation/refresh.ts"],"sourcesContent":["import type { ReactNode } from \"react\";\nimport type { HydrationDocumentPayloadSource } from \"../../hydration-payload\";\nimport { routerEvents } from \"../../routing/router-events\";\nimport { hydrateShared } from \"../../shared\";\nimport { fetchPageData } from \"./fetch-page-data\";\n\n/**\n * Re-run the current route's loaders and re-render it — under MRR's name.\n *\n * ## The name is MRR's; the behaviour is deliberately stronger\n *\n * `@mongez/react-router`'s `refresh()` re-RENDERS the current route: it is a\n * CSR router, all the data is already in the browser, and there is nothing to\n * go and get. Warlock's page data comes from the server, so re-rendering alone\n * would show the user exactly what they were already looking at. This\n * `refresh()` therefore re-FETCHES first — the same `x-warlock-data` request a\n * client navigation makes — and then swaps the page in. Strictly more than the\n * name promises elsewhere, never less, which is why the name could be kept.\n *\n * That difference is stated on {@link refresh} itself and not only here,\n * because the developer who needs to know it is the one hovering the symbol.\n *\n * ## Why the failure mode is the opposite of a navigation's\n *\n * `fetch-page-data.ts` degrades EVERY failure to a real browser load, and that\n * is right for a navigation: the user asked to go somewhere and must arrive.\n * A refresh is the opposite situation — the user is already where they want to\n * be. Handing the URL to `window.location.assign` would throw away their scroll\n * position, their open dialogs and the form they just posted from, in exchange\n * for data they only asked to update. So a failed refresh keeps the page\n * exactly as it is and announces the error; the screen the user has is never\n * the price of a network blip.\n *\n * ## Not server actions\n *\n * The mutation is an ordinary POST to the API, and this is what you call after\n * it. Nothing here writes; nothing here knows a mutation happened.\n */\n\n/**\n * The page on screen, as the navigation runtime holds it.\n *\n * `routeSource` is the reason this type is not simply `{ payload, tree }`. See\n * {@link createRefresher} for what it carries and why it is separate from\n * `payload`.\n */\nexport type RefreshablePage = {\n /** What the tree was built from — what the document context reports. */\n payload: HydrationDocumentPayloadSource;\n /** The rendered page. */\n tree: ReactNode;\n /**\n * The payload object `current-route.ts` identifies the current ROUTE by,\n * which is the same object as `payload` after a navigation but NOT after a\n * refresh.\n */\n routeSource: HydrationDocumentPayloadSource;\n};\n\n/**\n * Everything a refresh needs that only `NavigationRoot` can provide.\n *\n * Injected rather than reached for, and kept to four members: the page on\n * screen, the swap, the tree builder, and the race counter. Everything else a\n * refresh does — the request, the shared snapshot, the address bar, the\n * lifecycle events — is this module's own and is not injected, so a test\n * exercises the real ones.\n */\nexport type RefreshRuntime = {\n /** The page on screen at the moment it is asked for, never a captured copy. */\n readCurrent: () => RefreshablePage;\n /** Put a page on screen. */\n writeCurrent: (page: RefreshablePage) => void;\n /** How a payload becomes a tree, with the page registry already bound. */\n buildTree: (payload: HydrationDocumentPayloadSource) => Promise<ReactNode>;\n /**\n * Take a ticket from the navigation runtime's race counter.\n *\n * @returns a predicate that answers whether this operation is still the\n * newest one. THE SAME counter navigations take their tickets from — a\n * refresh and a navigation can overtake each other, so a second mechanism\n * would simply fail to notice.\n */\n claimTicket: () => () => boolean;\n};\n\n/**\n * What {@link refresh} delegates to once the runtime has connected itself.\n *\n * @returns `true` when fresh data is on screen. `false` covers every other\n * outcome — no runtime, no browser, the request failed, or a newer operation\n * overtook this one — and none of them left the page in a worse state than\n * they found it.\n */\nexport type Refresher = () => Promise<boolean>;\n\n/**\n * A refresh is a \"replace\" as far as history and its listeners are concerned:\n * no entry is pushed, and one may be replaced when the server redirects.\n */\nconst REFRESH_MODE = \"replace\" as const;\n\n/**\n * Build the runtime's refresher.\n *\n * Called by `NavigationRoot`, which connects the result with\n * {@link connectRefresher}. Not part of the public surface — a caller holding\n * its own refresher would be refreshing a page it does not own.\n *\n * ## The `routeSource` decision, which lives here\n *\n * `recordCurrentRoute` (`current-route.ts`) recognises a route by its payload\n * OBJECT IDENTITY: one swap is one payload object, which is what keeps a\n * StrictMode double render from counting as a navigation. A refresh breaks that\n * assumption on its own, because it produces a brand new payload object for the\n * page already on screen — so recording it would shift `previousRoute()` to the\n * page the user is currently looking at, and a \"back to where I came from\" link\n * would point at itself.\n *\n * So a refresh that came back as the SAME entry carries the previous\n * `routeSource` forward untouched: the fresh payload renders, and the route\n * does not move, because it did not. A refresh that came back as a DIFFERENT\n * entry — a session expiring into `/login` is the ordinary cause — is a real\n * move the server made, and is recorded as one; anything else would leave\n * `currentRoute()` naming a page that is no longer on screen.\n *\n * Comparing `name` here is not route matching (canon `9c8f878b`): both names\n * were decided by the server's router and merely travelled here. Nothing in\n * this file looks at a path.\n */\nexport function createRefresher(runtime: RefreshRuntime): Refresher {\n return async () => {\n // Not merely defensive: `refresh()` is importable from a universal module,\n // so a component can call it during the server render. There is no page on\n // screen to refresh there, and no address bar to read one from.\n if (typeof window === \"undefined\") return false;\n\n // The address bar IS the current route's URL — the runtime has already put\n // the resolved URL there — so there is no second copy to drift from it.\n const url = window.location.href;\n const isCurrent = runtime.claimTicket();\n\n routerEvents.emitNavigating({ url, mode: REFRESH_MODE });\n\n const result = await fetchPageData(url);\n\n // Superseded, and silently: this is the answer to a question the user\n // stopped asking. Not an error, and not an event — the operation that\n // overtook this one emits its own outcome.\n if (!isCurrent()) return false;\n\n if (result.type === \"hard-navigate\") {\n /*\n NO `window.location.assign` HERE, and this line is the whole point of\n the file. `fetchPageData` reports a hard navigation because that is the\n correct degradation for GOING somewhere; for STAYING somewhere it would\n destroy the screen the user already has in order to deliver data they\n asked to update. The page stays; the error is announced.\n */\n const error = new Error(`Warlock refresh failed: ${result.reason}`);\n\n console.warn(\"Warlock refresh could not re-fetch the current page:\", result.reason);\n routerEvents.emitNavigationError({ url, mode: REFRESH_MODE, error });\n\n return false;\n }\n\n let tree: ReactNode;\n\n try {\n tree = await runtime.buildTree(result.payload);\n } catch (error) {\n // A stale bundle after a deploy is the realistic cause. A navigation\n // reloads to fix it; a refresh cannot, for the same reason as above.\n console.warn(\"Warlock refresh could not build the page tree:\", error);\n routerEvents.emitNavigationError({ url, mode: REFRESH_MODE, error });\n\n return false;\n }\n\n if (!isCurrent()) return false;\n\n // Shared state BEFORE the render that consumes it, exactly as a navigation\n // does it — a refresh can carry a changed locale or a changed user too.\n hydrateShared(result.payload.shared);\n\n const previous = runtime.readCurrent();\n const sameEntry = result.payload.name === previous.payload.name;\n\n /*\n Only when the server actually moved us — `result.url` is the absolute URL\n the response came from and `url` came from the address bar, so they differ\n only when a redirect was followed. REPLACE even then: a refresh is not a\n destination, and pushing would make Back need two presses to leave a page\n the user never chose to visit twice.\n\n Keyed on the URL, not on `sameEntry`: the address bar's job is to name the\n URL on screen, and a redirect that stayed within one route entry\n (`?page=2` collapsing to `?page=1`) has still changed it.\n */\n if (result.url !== url) {\n window.history.replaceState(null, \"\", result.url);\n }\n\n runtime.writeCurrent({\n payload: result.payload,\n tree,\n routeSource: sameEntry ? previous.routeSource : result.payload,\n });\n\n routerEvents.emitNavigated({ url, resolvedUrl: result.url, mode: REFRESH_MODE });\n\n return true;\n };\n}\n\nlet connected: Refresher | undefined;\n\n/**\n * Installed by the navigation runtime at mount, and torn down with `undefined`.\n *\n * The same seam shape as `routing/navigator.ts`, and for the same reason:\n * {@link refresh} is universal and must not import the client runtime, so the\n * runtime registers itself instead.\n *\n * @returns the previous refresher, so a caller that installs one can restore\n * what was there.\n */\nexport function connectRefresher(next: Refresher | undefined): Refresher | undefined {\n const previous = connected;\n\n connected = next;\n\n return previous;\n}\n\n/**\n * Re-fetch the current route's data and re-render the page with it.\n *\n * What you call after a mutation — a normal POST to your API, then this — to\n * put the server's new truth on screen without a full reload. The layout stays\n * mounted, so scroll position, open menus and playing media survive.\n *\n * ## Stronger than the `refresh()` you may know\n *\n * `@mongez/react-router`'s `refresh()` only RE-RENDERS the current route. This\n * one RE-FETCHES the route's data first and then re-renders, because in Warlock\n * the data lives on the server and a re-render alone would show the user what\n * they are already looking at. Anywhere MRR's `refresh()` was correct, this is\n * too; it simply also picks up what changed.\n *\n * ## It cannot cost you the page\n *\n * If the request fails — offline, a 500, a proxy answering HTML — the page on\n * screen is left exactly as it was and `false` comes back. There is no reload\n * and no error screen. Subscribe to `routerEvents.onNavigationError` to show\n * the user something.\n *\n * ```ts\n * await api.post(\"/products\", form);\n *\n * if (!(await refresh())) toast.error(\"Could not reload the list.\");\n * ```\n *\n * @returns `true` when fresh data is on screen. `false` when nothing was\n * applied: no client runtime is connected (a server render, or before\n * hydration), the re-fetch failed, or a navigation overtook the refresh. Safe\n * to call in any of those — it never throws.\n */\nexport async function refresh(): Promise<boolean> {\n if (!connected) return false;\n\n return connected();\n}\n"],"mappings":";;;;;;;;;AAoGA,MAAM,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BrB,SAAgB,gBAAgB,SAAoC;CAClE,OAAO,YAAY;EAIjB,IAAI,OAAO,WAAW,aAAa,OAAO;EAI1C,MAAM,MAAM,OAAO,SAAS;EAC5B,MAAM,YAAY,QAAQ,YAAY;EAEtC,aAAa,eAAe;GAAE;GAAK,MAAM;EAAa,CAAC;EAEvD,MAAM,SAAS,MAAM,cAAc,GAAG;EAKtC,IAAI,CAAC,UAAU,GAAG,OAAO;EAEzB,IAAI,OAAO,SAAS,iBAAiB;GAQnC,MAAM,wBAAQ,IAAI,MAAM,2BAA2B,OAAO,QAAQ;GAElE,QAAQ,KAAK,wDAAwD,OAAO,MAAM;GAClF,aAAa,oBAAoB;IAAE;IAAK,MAAM;IAAc;GAAM,CAAC;GAEnE,OAAO;EACT;EAEA,IAAI;EAEJ,IAAI;GACF,OAAO,MAAM,QAAQ,UAAU,OAAO,OAAO;EAC/C,SAAS,OAAO;GAGd,QAAQ,KAAK,kDAAkD,KAAK;GACpE,aAAa,oBAAoB;IAAE;IAAK,MAAM;IAAc;GAAM,CAAC;GAEnE,OAAO;EACT;EAEA,IAAI,CAAC,UAAU,GAAG,OAAO;EAIzB,cAAc,OAAO,QAAQ,MAAM;EAEnC,MAAM,WAAW,QAAQ,YAAY;EACrC,MAAM,YAAY,OAAO,QAAQ,SAAS,SAAS,QAAQ;EAa3D,IAAI,OAAO,QAAQ,KACjB,OAAO,QAAQ,aAAa,MAAM,IAAI,OAAO,GAAG;EAGlD,QAAQ,aAAa;GACnB,SAAS,OAAO;GAChB;GACA,aAAa,YAAY,SAAS,cAAc,OAAO;EACzD,CAAC;EAED,aAAa,cAAc;GAAE;GAAK,aAAa,OAAO;GAAK,MAAM;EAAa,CAAC;EAE/E,OAAO;CACT;AACF;AAEA,IAAI;;;;;;;;;;;AAYJ,SAAgB,iBAAiB,MAAoD;CACnF,MAAM,WAAW;CAEjB,YAAY;CAEZ,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,eAAsB,UAA4B;CAChD,IAAI,CAAC,WAAW,OAAO;CAEvB,OAAO,UAAU;AACnB"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { fragmentTargetId } from "../../routing/url-fragment.mjs";
|
|
2
2
|
|
|
3
|
-
//#region
|
|
3
|
+
//#region web/src/client/navigation/scroll-to-fragment.ts
|
|
4
4
|
/**
|
|
5
5
|
* @param fragment the fragment WITHOUT its leading `#`, as
|
|
6
6
|
* `fragmentOf`/`samePageFragment` return it. Still percent-encoded — decoding
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scroll-to-fragment.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"scroll-to-fragment.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/client/navigation/scroll-to-fragment.ts"],"sourcesContent":["import { fragmentTargetId } from \"../../routing/url-fragment\";\n\n/**\n * Put the element a fragment names on screen — the browser's job, done by hand\n * because a client navigation never let the browser see the fragment.\n *\n * ## A fragment that matches nothing is NOT an error\n *\n * It does not throw, and — decided with it — it does not cause the fragment to\n * be dropped from the URL either. A browser loading `/docs#gone` shows\n * `#gone` in the address bar and leaves the page where it is; an id that has\n * not been added yet, or a page whose content moved, is an ordinary state of\n * the web and not something to report. So the return value says whether\n * anything was found, for a caller that wants to know, and every caller today\n * is free to ignore it.\n *\n * ## Why the document is an argument\n *\n * The suite runs with no DOM (`web/vitest.config.ts` — `environment: \"node\"`),\n * so a module that reached for the global `document` could only be proved in a\n * browser. The structural type below is satisfied by a real `Document` and by\n * three lines of test double, which is what makes the lookup rules provable at\n * all.\n */\n\n/** The two lookups, and nothing else this module needs from a `Document`. */\nexport type FragmentScrollDocument = {\n getElementById(id: string): { scrollIntoView(): void } | null;\n /**\n * The legacy anchor form, `<a name=\"install\">`, which browsers still honour\n * as a fragment target and older documentation pages are still full of.\n * Optional so a test double may leave it out.\n */\n getElementsByName?(name: string): ArrayLike<{ scrollIntoView(): void }>;\n};\n\n/**\n * @param fragment the fragment WITHOUT its leading `#`, as\n * `fragmentOf`/`samePageFragment` return it. Still percent-encoded — decoding\n * is this function's job, via `fragmentTargetId`.\n *\n * @returns whether a target was found and scrolled to.\n */\nexport function scrollToFragment(\n documentNode: FragmentScrollDocument,\n fragment: string,\n): boolean {\n // `/docs#` names no target. Nothing to look up, and nothing to move.\n if (fragment === \"\") return false;\n\n const id = fragmentTargetId(fragment);\n\n /*\n `getElementById`, never `querySelector(\"#\" + id)`. An id is allowed to\n contain characters that are not valid in a CSS selector — `#1`, `#a.b`,\n `#a b` — and `querySelector` THROWS on those rather than missing them, which\n would turn a link to a legal id into an exception in the middle of a\n navigation.\n */\n const target = documentNode.getElementById(id) ?? namedAnchor(documentNode, id);\n\n if (target === undefined || target === null) return false;\n\n target.scrollIntoView();\n\n return true;\n}\n\nfunction namedAnchor(\n documentNode: FragmentScrollDocument,\n name: string,\n): { scrollIntoView(): void } | undefined {\n const matches = documentNode.getElementsByName?.(name);\n\n return matches === undefined || matches.length === 0 ? undefined : matches[0];\n}\n"],"mappings":";;;;;;;;;;AA2CA,SAAgB,iBACd,cACA,UACS;CAET,IAAI,aAAa,IAAI,OAAO;CAE5B,MAAM,KAAK,iBAAiB,QAAQ;CASpC,MAAM,SAAS,aAAa,eAAe,EAAE,KAAK,YAAY,cAAc,EAAE;CAE9E,IAAI,WAAW,UAAa,WAAW,MAAM,OAAO;CAEpD,OAAO,eAAe;CAEtB,OAAO;AACT;AAEA,SAAS,YACP,cACA,MACwC;CACxC,MAAM,UAAU,aAAa,oBAAoB,IAAI;CAErD,OAAO,YAAY,UAAa,QAAQ,WAAW,IAAI,SAAY,QAAQ;AAC7E"}
|