@warlock.js/web 5.0.2 → 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 +250 -0
- package/README.md +126 -12
- package/esm/build/contribution.d.mts +11 -4
- package/esm/build/contribution.mjs +46 -22
- package/esm/build/contribution.mjs.map +1 -1
- package/esm/build/discover-pages.mjs +318 -44
- 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 +44 -7
- 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 +26 -0
- package/esm/client/navigation/scroll-to-fragment.mjs.map +1 -0
- 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 +15 -1
- package/esm/metadata.mjs +45 -0
- package/esm/metadata.mjs.map +1 -0
- 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 +120 -0
- package/esm/routing/url-fragment.mjs.map +1 -0
- 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 +58 -6
- package/esm/server/create-page-route-handler.mjs +127 -40
- 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 +6 -5
- package/esm/server/index.mjs +4 -4
- package/esm/server/install-page-routes-from-manifest.d.mts +17 -7
- package/esm/server/install-page-routes-from-manifest.mjs +91 -8
- package/esm/server/install-page-routes-from-manifest.mjs.map +1 -1
- package/esm/server/install-page-routes.d.mts +32 -13
- package/esm/server/install-page-routes.mjs +112 -32
- package/esm/server/install-page-routes.mjs.map +1 -1
- package/esm/server/install-production-page-routes.mjs +3 -31
- 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 +126 -0
- package/esm/server/not-found-page.mjs +157 -0
- package/esm/server/not-found-page.mjs.map +1 -0
- 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 +6 -4
- 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 +233 -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 +10 -6
- 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 +247 -2
- 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 +241 -49
- package/llms.txt +6 -2
- package/package.json +3 -3
- package/skills/add-web-to-an-app/SKILL.md +3 -3
- package/skills/create-a-page/SKILL.md +130 -7
- package/skills/load-page-data/SKILL.md +92 -12
- package/skills/navigate-on-the-client/SKILL.md +3 -1
- package/skills/serve-styles/SKILL.md +13 -12
- package/skills/use-layouts/SKILL.md +20 -8
- package/skills/write-the-root/SKILL.md +5 -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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"route-identity.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"route-identity.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/routing/route-identity.ts"],"sourcesContent":["/**\n * Route identity — the single, pure implementation of \"what is this page's\n * route path and name\". The dev installer\n * (`web/src/server/install-page-routes.ts`), the production manifest\n * installer (`web/src/server/install-page-routes-from-manifest.ts`) and\n * discovery (`web/src/build/discover-pages.ts`) each hand-derived this on\n * their own until all three were made to delegate here.\n *\n * Pure string logic only: no `fs`, no `path`, no Node built-ins. Every input\n * this module accepts is already CANONICAL — a POSIX, app-root-relative\n * source path (e.g. `\"src/app/users/web/account/settings.page.tsx\"` or\n * `\"src/web/index.page.tsx\"`) and an already-validated declared route export.\n * Turning an absolute, OS-specific file path into that canonical form is the\n * caller's job; this module refuses (see {@link NonPosixSourceFilePathError})\n * rather than guess at a normalization.\n *\n * Well-formedness of the declared `route` export itself (is it a string or an\n * object, does the object have a `path`) is the extractor's problem — already\n * rejected at build before either derivation function here is called.\n *\n * DIRECTORY CONTRACT — applies to everything in `web/src/routing/`: nothing\n * here may import `node:fs`, `node:path`, `vite`, or `fastify`. Modules in\n * this directory receive canonical values and trust nothing — they assert\n * rather than trust, but they never repair. A module that needs the\n * filesystem does not belong here. The purity is deliberate: it keeps these\n * modules consumable from the dev server, the build, the production runtime,\n * and — if ever needed — the browser client, without dragging any of those\n * environments along.\n */\n\n/** The shape a page's `route` export may declare — mirrors `PageRouteExport` in `install-page-routes.ts`. */\nexport type DeclaredRouteExport = string | { path: string; name?: string };\n\n/** The canonical form every declared `route` export resolves to. */\nexport type CanonicalRoute = {\n path: string;\n name?: string;\n};\n\n/** The canonical inputs {@link deriveFallbackRouteName} requires — see the module doc comment for what \"canonical\" means. */\nexport type RouteNameFallbackInput = {\n /** The page's declared route path, e.g. `\"/settings\"` or `\"/\"`. */\n routePath: string;\n /** The page's app-root-relative POSIX source path, e.g. `\"src/app/main/web/contact-us.page.tsx\"`. */\n sourceFile: string;\n};\n\n/**\n * Raised when a caller passes a `sourceFile` containing a backslash.\n * Canonical means canonical: this module does not normalize Windows path\n * separators on the caller's behalf.\n */\nexport class NonPosixSourceFilePathError extends Error {\n public constructor(public readonly sourceFile: string) {\n super(\n `route-identity: sourceFile \"${sourceFile}\" contains a backslash. This module's inputs ` +\n \"must already be canonical app-root-relative POSIX paths (forward slashes only) — \" +\n 'normalize with `value.replace(/\\\\\\\\/g, \"/\")` before calling deriveFallbackRouteName.',\n );\n this.name = \"NonPosixSourceFilePathError\";\n }\n}\n\n/**\n * Canonicalizes a declared `route` export — string or `{ path, name? }` —\n * into `{ path, name? }`. Requires well-formed input; an export that is\n * neither a string nor an object with a `path` is the extractor's problem,\n * already rejected before this function is ever called.\n */\nexport function canonicalizeRouteExport(route: DeclaredRouteExport): CanonicalRoute {\n if (typeof route === \"string\") {\n return { path: route };\n }\n\n return route.name === undefined ? { path: route.path } : { path: route.path, name: route.name };\n}\n\n/** Strips leading and trailing \".\" characters — mirrors `trim(value, \".\")` as used by the installer's `deriveRouteName`. */\nfunction trimDots(value: string): string {\n return value.replace(/^\\.+|\\.+$/g, \"\");\n}\n\n/**\n * The module segment a canonical source path declares, or `undefined` for a\n * global (`src/web/**`) page. `sourceFile` is `<srcDir>/app/<module>/web/...`\n * or `<srcDir>/web/...` — the first segment is the (arbitrarily named) src\n * dir, so the module test looks at the SECOND segment.\n */\nfunction moduleSegmentFor(sourceFile: string): string | undefined {\n const segments = sourceFile.split(\"/\");\n\n return segments[1] === \"app\" ? segments[2] : undefined;\n}\n\n/**\n * Derives the fallback route name for a page whose declared route carries no\n * `name` — the same derivation the dev installer's `deriveRouteName` applies\n * today (`web/src/server/install-page-routes.ts`), expressed against\n * canonical inputs instead of an absolute file path plus an `appSrcRoot`.\n *\n * The installer only ever calls its derivation for a page under\n * `<appSrcRoot>/app/**`, so a global (`src/web/**`) page has no installer\n * behaviour to mirror; for that case this function instead follows\n * discovery's own convention (`routeNameFor` in `discover-pages.ts`) — no\n * module prefix, and `\"index\"` when there is nothing left to say at all.\n *\n * Throws {@link NonPosixSourceFilePathError} when `sourceFile` contains a\n * backslash.\n */\nexport function deriveFallbackRouteName(input: RouteNameFallbackInput): string {\n const { routePath, sourceFile } = input;\n\n if (sourceFile.includes(\"\\\\\")) {\n throw new NonPosixSourceFilePathError(sourceFile);\n }\n\n const moduleName = moduleSegmentFor(sourceFile);\n const suffix = trimDots(routePath.replace(/\\//g, \".\"));\n\n if (moduleName !== undefined) {\n return suffix ? `${moduleName}.${suffix}` : moduleName;\n }\n\n return suffix || \"index\";\n}\n"],"mappings":";;;;;;AAoDA,IAAa,8BAAb,cAAiD,MAAM;CAClB;CAAnC,AAAO,YAAY,AAAgB,YAAoB;EACrD,MACE,+BAA+B,WAAW,qNAG5C;EALiC;EAMjC,KAAK,OAAO;CACd;AACF;;;;;;;AAQA,SAAgB,wBAAwB,OAA4C;CAClF,IAAI,OAAO,UAAU,UACnB,OAAO,EAAE,MAAM,MAAM;CAGvB,OAAO,MAAM,SAAS,SAAY,EAAE,MAAM,MAAM,KAAK,IAAI;EAAE,MAAM,MAAM;EAAM,MAAM,MAAM;CAAK;AAChG;;AAGA,SAAS,SAAS,OAAuB;CACvC,OAAO,MAAM,QAAQ,cAAc,EAAE;AACvC;;;;;;;AAQA,SAAS,iBAAiB,YAAwC;CAChE,MAAM,WAAW,WAAW,MAAM,GAAG;CAErC,OAAO,SAAS,OAAO,QAAQ,SAAS,KAAK;AAC/C;;;;;;;;;;;;;;;;AAiBA,SAAgB,wBAAwB,OAAuC;CAC7E,MAAM,EAAE,WAAW,eAAe;CAElC,IAAI,WAAW,SAAS,IAAI,GAC1B,MAAM,IAAI,4BAA4B,UAAU;CAGlD,MAAM,aAAa,iBAAiB,UAAU;CAC9C,MAAM,SAAS,SAAS,UAAU,QAAQ,OAAO,GAAG,CAAC;CAErD,IAAI,eAAe,QACjB,OAAO,SAAS,GAAG,WAAW,GAAG,WAAW;CAG9C,OAAO,UAAU;AACnB"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { QueryStringInput } from "./query-string.mjs";
|
|
2
2
|
|
|
3
|
-
//#region
|
|
3
|
+
//#region web/src/routing/route-table.d.ts
|
|
4
4
|
/** What `href` accepts for a `:param` segment. Rendered with `String(value)`. */
|
|
5
5
|
type RouteParameters = Readonly<Record<string, unknown>>;
|
|
6
6
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"route-table.mjs","names":[],"sources":["../../../../../../../web/src/routing/route-table.ts"],"sourcesContent":["/**\n * The name→URL primitive, and the one route table both sides read.\n *\n * `href(name, params, query)` is the DURABLE primitive; `<Link>` is sugar over\n * it. That ordering is deliberate and ratified: a function serves emails,\n * redirects, `Location` headers and non-React callers, none of which can render\n * a component — and it keeps client-side navigation, when it lands, a behaviour\n * change rather than an API change.\n *\n * ── Why a process-global table is correct HERE ───────────────────────────────\n * Module-level mutable state is normally a defect in a server that handles\n * concurrent requests, and this codebase has a real example of that defect to\n * point at: `@mongez/react-router`'s `RouterWrapper` keeps the RENDERED PAGE\n * CONTENT in a module-level binding, so request B overwrites the tree request A\n * is about to serialize. That is why it is not on the SSR path.\n *\n * A route table is the opposite kind of value. It is derived from the file\n * system at boot, identical for every request in the process, and never written\n * during a request — the same category as the compiled route table the server's\n * own router holds. Nothing here is per-request, so there is nothing for two\n * requests to race over.\n *\n * The rule that keeps it that way: `publishRouteTable` is called at INSTALL\n * time (server) or at hydration entry (browser), and never from a loader, a\n * middleware, or a component.\n */\n\nimport { queryStringOf, type QueryStringInput } from \"./query-string\";\n\n/** The two fields `href` needs. Callers may pass richer entries; the rest is ignored. */\nexport type RouteTableEntry = {\n readonly name: string;\n readonly path: string;\n};\n\n/** What `href` accepts for a `:param` segment. Rendered with `String(value)`. */\nexport type RouteParameters = Readonly<Record<string, unknown>>;\n\n/**\n * Query values; an `undefined` value is omitted rather than serialized.\n *\n * A value may be a scalar, an array of scalars, or an object one level deep —\n * the shapes `@warlock.js/core` parses back out of the URL. Anything deeper\n * throws `UnserializableQueryValueError`; the grammar and the measurements\n * behind it are documented in query-string.ts.\n */\nexport type RouteQuery = QueryStringInput;\n\nconst PARAMETER_PATTERN = /:([A-Za-z0-9_]+)|\\*/g;\n\n/**\n * ── WHY THIS LIVES ON `globalThis` AND NOT IN A MODULE BINDING ───────────────\n *\n * A plain `let` here does not work in development, and the failure is silent\n * enough to be worth spelling out.\n *\n * In dev the process runs TWO module graphs over the same files. Route\n * installation is loaded by tsx/Node (it is CLI bootstrap and imports core\n * directly), while page and layout modules are evaluated by Vite's SSR module\n * runner — which keeps its own registry and its own instance of every module it\n * transforms, `@warlock.js/web` included. So a module-level binding written by\n * the installer is not the binding `<Link>` reads during render: the installer\n * publishes into one instance and the component finds the other one empty.\n *\n * That was measured, not theorised. With a module-level `let`, every anchor on\n * a server-rendered page threw `RouteTableNotPublishedError` with an empty\n * known-names list while installation had demonstrably run.\n *\n * `Symbol.for` resolves through the per-ISOLATE symbol registry, which both\n * graphs share because they are the same isolate. So the table is one value no\n * matter which graph reaches it first, and the module keeps its module-shaped\n * API. `publishedBy` is carried for diagnosis only.\n */\nconst ROUTE_TABLE_SLOT = Symbol.for(\"warlock.web.routeTable\");\n\ntype RouteTableSlot = {\n table: Map<string, string>;\n publishedBy: string;\n};\n\ntype RouteTableHost = typeof globalThis & {\n [ROUTE_TABLE_SLOT]?: RouteTableSlot;\n};\n\n/**\n * `undefined` means \"nobody has published yet\", which is a DIFFERENT fault from\n * \"the table is published and this name is not in it\" — an empty Map would\n * conflate them and send the reader hunting a route that was never missing.\n */\nfunction readSlot(): RouteTableSlot | undefined {\n return (globalThis as RouteTableHost)[ROUTE_TABLE_SLOT];\n}\n\nexport class RouteTableNotPublishedError extends Error {\n public constructor(public readonly routeName: string) {\n super(\n `Warlock href(${JSON.stringify(routeName)}) was called before the route table was ` +\n \"published, so no route name resolves yet. The table is published once at boot — by \" +\n \"the server when it installs page routes, and by the hydration entry before it mounts. \" +\n \"Seeing this means href() ran outside both: typically a module evaluating at import \" +\n \"time, or a unit test that renders a component without publishing a table first.\",\n );\n this.name = \"RouteTableNotPublishedError\";\n }\n}\n\nexport class UnknownRouteNameError extends Error {\n public constructor(\n public readonly routeName: string,\n public readonly knownRouteNames: readonly string[],\n ) {\n super(\n `Warlock href(${JSON.stringify(routeName)}) does not name a known route. ` +\n (knownRouteNames.length === 0\n ? \"The route table is published but empty, so no page declared a `route` discovery could see.\"\n : `The table knows: ${knownRouteNames.map(name => JSON.stringify(name)).join(\", \")}.`),\n );\n this.name = \"UnknownRouteNameError\";\n }\n}\n\nexport class MissingRouteParameterError extends Error {\n public constructor(\n public readonly routeName: string,\n public readonly parameterName: string,\n public readonly routePath: string,\n ) {\n super(\n `Warlock href(${JSON.stringify(routeName)}) is missing the parameter ` +\n `${JSON.stringify(parameterName)}, required by the route path \"${routePath}\". ` +\n \"It is not defaulted: a missing parameter would otherwise be interpolated as the \" +\n \"literal text `undefined`, producing a link that renders correctly and 404s for a \" +\n \"visitor.\",\n );\n this.name = \"MissingRouteParameterError\";\n }\n}\n\nexport class UnknownRouteParameterError extends Error {\n public constructor(\n public readonly routeName: string,\n public readonly parameterNames: readonly string[],\n public readonly routePath: string,\n ) {\n super(\n `Warlock href(${JSON.stringify(routeName)}) was given ` +\n `${parameterNames.map(name => JSON.stringify(name)).join(\", \")}, which the route path ` +\n `\"${routePath}\" does not declare. Passing an undeclared parameter is a typo often ` +\n \"enough that it is refused rather than dropped; values meant for the query string go \" +\n \"in the third argument.\",\n );\n this.name = \"UnknownRouteParameterError\";\n }\n}\n\nexport class DuplicateRouteNameError extends Error {\n public constructor(\n public readonly routeName: string,\n public readonly paths: readonly [string, string],\n ) {\n super(\n `Warlock route table: two routes both claim the name ${JSON.stringify(routeName)} — ` +\n `\"${paths[0]}\" and \"${paths[1]}\". A name resolves to exactly one URL, so one of the ` +\n \"two would silently win and every link to it would be wrong half the time.\",\n );\n this.name = \"DuplicateRouteNameError\";\n }\n}\n\n/**\n * Publish the table. WHOLESALE — the previous one is discarded, not merged\n * into.\n *\n * Merging looks harmless until a page is deleted and the dev server restarts:\n * the dead name would stay resolvable, and `<Link>` would go on rendering a URL\n * the server no longer routes. The table has to be able to shrink.\n */\nexport function publishRouteTable(\n entries: readonly RouteTableEntry[],\n publishedBy = \"unnamed\",\n): void {\n const table = new Map<string, string>();\n\n for (const entry of entries) {\n const existing = table.get(entry.name);\n\n if (existing !== undefined) {\n throw new DuplicateRouteNameError(entry.name, [existing, entry.path]);\n }\n\n table.set(entry.name, entry.path);\n }\n\n (globalThis as RouteTableHost)[ROUTE_TABLE_SLOT] = { table, publishedBy };\n}\n\n/**\n * Drop the table, returning the module to its pre-boot state.\n *\n * Exists for tests: the table is process-global, so a suite that published one\n * would otherwise leak it into every later test in the same worker and pass in\n * file order while failing under `--shuffle`.\n */\nexport function resetRouteTable(): void {\n delete (globalThis as RouteTableHost)[ROUTE_TABLE_SLOT];\n}\n\n/** The published names, for diagnostics. Empty when nothing is published. */\nexport function knownRouteNames(): readonly string[] {\n const slot = readSlot();\n\n return slot === undefined ? [] : [...slot.table.keys()];\n}\n\n/** Who published the live table, for diagnosis. `undefined` when nothing has. */\nexport function routeTablePublisher(): string | undefined {\n return readSlot()?.publishedBy;\n}\n\nfunction parameterNamesOf(routePath: string): readonly string[] {\n const names: string[] = [];\n\n for (const match of routePath.matchAll(PARAMETER_PATTERN)) {\n names.push(match[1] ?? \"*\");\n }\n\n return names;\n}\n\nfunction interpolate(\n routeName: string,\n routePath: string,\n params: RouteParameters | undefined,\n): string {\n const declared = parameterNamesOf(routePath);\n const supplied = Object.keys(params ?? {}).filter(key => params?.[key] !== undefined);\n const undeclared = supplied.filter(key => !declared.includes(key));\n\n if (undeclared.length > 0) {\n throw new UnknownRouteParameterError(routeName, undeclared, routePath);\n }\n\n return routePath.replace(PARAMETER_PATTERN, match => {\n const name = match === \"*\" ? \"*\" : match.slice(1);\n const value = params?.[name];\n\n if (value === undefined) {\n throw new MissingRouteParameterError(routeName, name, routePath);\n }\n\n return encodeURIComponent(String(value));\n });\n}\n\n/**\n * Resolve a route NAME to a URL.\n *\n * A name, never a path: a moved page changes its URL and keeps its name, so\n * every call site keeps working. That is the property the hardcoded table in\n * the previous `<Link>` could not offer, because it restated six URLs by hand\n * and silently refused every other page in the app.\n *\n * The query half is delegated to `queryStringOf`, which lives next to the\n * DECODER it has to agree with. It used to live here, and being module-private\n * meant the read half could not share it — the one-writer rule held only\n * because nobody had written the second writer yet.\n *\n * @throws {UnserializableQueryValueError} when a query value nests deeper than\n * the wire format core parses can carry.\n */\nexport function href(\n name: string,\n params?: RouteParameters,\n query?: RouteQuery,\n): string {\n const slot = readSlot();\n\n if (slot === undefined) throw new RouteTableNotPublishedError(name);\n\n const routePath = slot.table.get(name);\n\n if (routePath === undefined) {\n throw new UnknownRouteNameError(name, [...slot.table.keys()]);\n }\n\n return `${interpolate(name, routePath, params)}${queryStringOf(query)}`;\n}\n"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"route-table.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/routing/route-table.ts"],"sourcesContent":["/**\n * The name→URL primitive, and the one route table both sides read.\n *\n * `href(name, params, query)` is the DURABLE primitive; `<Link>` is sugar over\n * it. That ordering is deliberate and ratified: a function serves emails,\n * redirects, `Location` headers and non-React callers, none of which can render\n * a component — and it keeps client-side navigation, when it lands, a behaviour\n * change rather than an API change.\n *\n * ── Why a process-global table is correct HERE ───────────────────────────────\n * Module-level mutable state is normally a defect in a server that handles\n * concurrent requests, and this codebase has a real example of that defect to\n * point at: `@mongez/react-router`'s `RouterWrapper` keeps the RENDERED PAGE\n * CONTENT in a module-level binding, so request B overwrites the tree request A\n * is about to serialize. That is why it is not on the SSR path.\n *\n * A route table is the opposite kind of value. It is derived from the file\n * system at boot, identical for every request in the process, and never written\n * during a request — the same category as the compiled route table the server's\n * own router holds. Nothing here is per-request, so there is nothing for two\n * requests to race over.\n *\n * The rule that keeps it that way: `publishRouteTable` is called at INSTALL\n * time (server) or at hydration entry (browser), and never from a loader, a\n * middleware, or a component.\n */\n\nimport { queryStringOf, type QueryStringInput } from \"./query-string\";\n\n/** The two fields `href` needs. Callers may pass richer entries; the rest is ignored. */\nexport type RouteTableEntry = {\n readonly name: string;\n readonly path: string;\n};\n\n/** What `href` accepts for a `:param` segment. Rendered with `String(value)`. */\nexport type RouteParameters = Readonly<Record<string, unknown>>;\n\n/**\n * Query values; an `undefined` value is omitted rather than serialized.\n *\n * A value may be a scalar, an array of scalars, or an object one level deep —\n * the shapes `@warlock.js/core` parses back out of the URL. Anything deeper\n * throws `UnserializableQueryValueError`; the grammar and the measurements\n * behind it are documented in query-string.ts.\n */\nexport type RouteQuery = QueryStringInput;\n\nconst PARAMETER_PATTERN = /:([A-Za-z0-9_]+)|\\*/g;\n\n/**\n * ── WHY THIS LIVES ON `globalThis` AND NOT IN A MODULE BINDING ───────────────\n *\n * A plain `let` here does not work in development, and the failure is silent\n * enough to be worth spelling out.\n *\n * In dev the process runs TWO module graphs over the same files. Route\n * installation is loaded by tsx/Node (it is CLI bootstrap and imports core\n * directly), while page and layout modules are evaluated by Vite's SSR module\n * runner — which keeps its own registry and its own instance of every module it\n * transforms, `@warlock.js/web` included. So a module-level binding written by\n * the installer is not the binding `<Link>` reads during render: the installer\n * publishes into one instance and the component finds the other one empty.\n *\n * That was measured, not theorised. With a module-level `let`, every anchor on\n * a server-rendered page threw `RouteTableNotPublishedError` with an empty\n * known-names list while installation had demonstrably run.\n *\n * `Symbol.for` resolves through the per-ISOLATE symbol registry, which both\n * graphs share because they are the same isolate. So the table is one value no\n * matter which graph reaches it first, and the module keeps its module-shaped\n * API. `publishedBy` is carried for diagnosis only.\n */\nconst ROUTE_TABLE_SLOT = Symbol.for(\"warlock.web.routeTable\");\n\ntype RouteTableSlot = {\n table: Map<string, string>;\n publishedBy: string;\n};\n\ntype RouteTableHost = typeof globalThis & {\n [ROUTE_TABLE_SLOT]?: RouteTableSlot;\n};\n\n/**\n * `undefined` means \"nobody has published yet\", which is a DIFFERENT fault from\n * \"the table is published and this name is not in it\" — an empty Map would\n * conflate them and send the reader hunting a route that was never missing.\n */\nfunction readSlot(): RouteTableSlot | undefined {\n return (globalThis as RouteTableHost)[ROUTE_TABLE_SLOT];\n}\n\nexport class RouteTableNotPublishedError extends Error {\n public constructor(public readonly routeName: string) {\n super(\n `Warlock href(${JSON.stringify(routeName)}) was called before the route table was ` +\n \"published, so no route name resolves yet. The table is published once at boot — by \" +\n \"the server when it installs page routes, and by the hydration entry before it mounts. \" +\n \"Seeing this means href() ran outside both: typically a module evaluating at import \" +\n \"time, or a unit test that renders a component without publishing a table first.\",\n );\n this.name = \"RouteTableNotPublishedError\";\n }\n}\n\nexport class UnknownRouteNameError extends Error {\n public constructor(\n public readonly routeName: string,\n public readonly knownRouteNames: readonly string[],\n ) {\n super(\n `Warlock href(${JSON.stringify(routeName)}) does not name a known route. ` +\n (knownRouteNames.length === 0\n ? \"The route table is published but empty, so no page declared a `route` discovery could see.\"\n : `The table knows: ${knownRouteNames.map(name => JSON.stringify(name)).join(\", \")}.`),\n );\n this.name = \"UnknownRouteNameError\";\n }\n}\n\nexport class MissingRouteParameterError extends Error {\n public constructor(\n public readonly routeName: string,\n public readonly parameterName: string,\n public readonly routePath: string,\n ) {\n super(\n `Warlock href(${JSON.stringify(routeName)}) is missing the parameter ` +\n `${JSON.stringify(parameterName)}, required by the route path \"${routePath}\". ` +\n \"It is not defaulted: a missing parameter would otherwise be interpolated as the \" +\n \"literal text `undefined`, producing a link that renders correctly and 404s for a \" +\n \"visitor.\",\n );\n this.name = \"MissingRouteParameterError\";\n }\n}\n\nexport class UnknownRouteParameterError extends Error {\n public constructor(\n public readonly routeName: string,\n public readonly parameterNames: readonly string[],\n public readonly routePath: string,\n ) {\n super(\n `Warlock href(${JSON.stringify(routeName)}) was given ` +\n `${parameterNames.map(name => JSON.stringify(name)).join(\", \")}, which the route path ` +\n `\"${routePath}\" does not declare. Passing an undeclared parameter is a typo often ` +\n \"enough that it is refused rather than dropped; values meant for the query string go \" +\n \"in the third argument.\",\n );\n this.name = \"UnknownRouteParameterError\";\n }\n}\n\nexport class DuplicateRouteNameError extends Error {\n public constructor(\n public readonly routeName: string,\n public readonly paths: readonly [string, string],\n ) {\n super(\n `Warlock route table: two routes both claim the name ${JSON.stringify(routeName)} — ` +\n `\"${paths[0]}\" and \"${paths[1]}\". A name resolves to exactly one URL, so one of the ` +\n \"two would silently win and every link to it would be wrong half the time.\",\n );\n this.name = \"DuplicateRouteNameError\";\n }\n}\n\n/**\n * Publish the table. WHOLESALE — the previous one is discarded, not merged\n * into.\n *\n * Merging looks harmless until a page is deleted and the dev server restarts:\n * the dead name would stay resolvable, and `<Link>` would go on rendering a URL\n * the server no longer routes. The table has to be able to shrink.\n */\nexport function publishRouteTable(\n entries: readonly RouteTableEntry[],\n publishedBy = \"unnamed\",\n): void {\n const table = new Map<string, string>();\n\n for (const entry of entries) {\n const existing = table.get(entry.name);\n\n if (existing !== undefined) {\n throw new DuplicateRouteNameError(entry.name, [existing, entry.path]);\n }\n\n table.set(entry.name, entry.path);\n }\n\n (globalThis as RouteTableHost)[ROUTE_TABLE_SLOT] = { table, publishedBy };\n}\n\n/**\n * Drop the table, returning the module to its pre-boot state.\n *\n * Exists for tests: the table is process-global, so a suite that published one\n * would otherwise leak it into every later test in the same worker and pass in\n * file order while failing under `--shuffle`.\n */\nexport function resetRouteTable(): void {\n delete (globalThis as RouteTableHost)[ROUTE_TABLE_SLOT];\n}\n\n/** The published names, for diagnostics. Empty when nothing is published. */\nexport function knownRouteNames(): readonly string[] {\n const slot = readSlot();\n\n return slot === undefined ? [] : [...slot.table.keys()];\n}\n\n/** Who published the live table, for diagnosis. `undefined` when nothing has. */\nexport function routeTablePublisher(): string | undefined {\n return readSlot()?.publishedBy;\n}\n\nfunction parameterNamesOf(routePath: string): readonly string[] {\n const names: string[] = [];\n\n for (const match of routePath.matchAll(PARAMETER_PATTERN)) {\n names.push(match[1] ?? \"*\");\n }\n\n return names;\n}\n\nfunction interpolate(\n routeName: string,\n routePath: string,\n params: RouteParameters | undefined,\n): string {\n const declared = parameterNamesOf(routePath);\n const supplied = Object.keys(params ?? {}).filter(key => params?.[key] !== undefined);\n const undeclared = supplied.filter(key => !declared.includes(key));\n\n if (undeclared.length > 0) {\n throw new UnknownRouteParameterError(routeName, undeclared, routePath);\n }\n\n return routePath.replace(PARAMETER_PATTERN, match => {\n const name = match === \"*\" ? \"*\" : match.slice(1);\n const value = params?.[name];\n\n if (value === undefined) {\n throw new MissingRouteParameterError(routeName, name, routePath);\n }\n\n return encodeURIComponent(String(value));\n });\n}\n\n/**\n * Resolve a route NAME to a URL.\n *\n * A name, never a path: a moved page changes its URL and keeps its name, so\n * every call site keeps working. That is the property the hardcoded table in\n * the previous `<Link>` could not offer, because it restated six URLs by hand\n * and silently refused every other page in the app.\n *\n * The query half is delegated to `queryStringOf`, which lives next to the\n * DECODER it has to agree with. It used to live here, and being module-private\n * meant the read half could not share it — the one-writer rule held only\n * because nobody had written the second writer yet.\n *\n * @throws {UnserializableQueryValueError} when a query value nests deeper than\n * the wire format core parses can carry.\n */\nexport function href(\n name: string,\n params?: RouteParameters,\n query?: RouteQuery,\n): string {\n const slot = readSlot();\n\n if (slot === undefined) throw new RouteTableNotPublishedError(name);\n\n const routePath = slot.table.get(name);\n\n if (routePath === undefined) {\n throw new UnknownRouteNameError(name, [...slot.table.keys()]);\n }\n\n return `${interpolate(name, routePath, params)}${queryStringOf(query)}`;\n}\n"],"mappings":"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"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"router-events.mjs","names":[],"sources":["../../../../../../../web/src/routing/router-events.ts"],"sourcesContent":["/**\n * The navigation lifecycle emitter — what a progress bar subscribes to.\n *\n * A client navigation is a fetch followed by a tree swap\n * (`client/navigation/navigation-root.tsx`). Nothing about that is visible to\n * the user while it is in flight, which is the whole reason this module\n * exists: a progress bar, an analytics hook or a scroll restorer needs to know\n * that a navigation STARTED, that it FINISHED, and that it FAILED — and none\n * of them should have to reach into the navigation runtime to find out.\n *\n * So the runtime announces, and anyone may listen. The listeners are strangers\n * to each other and to the runtime; that is the point.\n *\n * ## This module ships the emitter only\n *\n * Nothing here is wired into the navigation runtime yet — `navigation-root.tsx`\n * calls the `emit*` methods in a later change. Until then this is a complete,\n * self-contained emitter with no callers, which is why it has no dependency on\n * anything in `client/`.\n *\n * ## What it deliberately does NOT do\n *\n * It carries URLs as OPAQUE STRINGS. There is no matching, no parsing, no\n * \"which route is this\" — Warlock's server router is the only matcher (canon\n * 9c8f878b), and an emitter that started parsing paths would be a second one.\n * A listener that wants a route name gets it from the payload the navigation\n * produced, not from this module.\n *\n * DIRECTORY CONTRACT — see `route-identity.ts`: nothing in `web/src/routing/`\n * may import `node:fs`, `node:path`, `vite` or `fastify`. This module also\n * touches no DOM global, which is what makes it importable from a server\n * render (see below).\n *\n * ## Named for its ancestor\n *\n * `routerEvents` is the name `@mongez/react-router` used\n * (`@mongez/react-router/src/events.ts`), and the subscription ergonomics are\n * deliberately familiar: `routerEvents.onNavigating(callback)` returns\n * something you call to stop listening. The implementation is NOT ported —\n * MRR's delegates to a global `@mongez/events` bus keyed by string\n * (`\"router.navigating\"`), which reaches its router singleton and gives up\n * per-event payload typing in the process. Here the events are the object's\n * own methods, so each one carries its own payload type and a typo is a\n * compile error rather than a listener that never fires.\n *\n * MRR returns an `EventSubscription` object; this returns the unsubscribe\n * FUNCTION itself, because that is what a React `useEffect` cleanup wants to\n * be handed:\n *\n * ```ts\n * useEffect(() => routerEvents.onNavigating(() => setLoading(true)), []);\n * ```\n */\n\n/**\n * How the navigation will be written to browser history.\n *\n * `\"replace\"` covers both an explicit `<Link replace>` and a Back/Forward\n * press — the runtime replaces in both cases, because the history entry\n * already exists. A listener that wants to stay quiet during Back/Forward\n * cannot tell the two apart from here, and does not need to: what it actually\n * cares about is that no new entry is being pushed.\n */\nexport type NavigationMode = \"push\" | \"replace\";\n\n/** Emitted when a navigation begins — before anything has been fetched. */\nexport type NavigationStartPayload = {\n /** The URL the navigation was requested for, verbatim and unparsed. */\n url: string;\n mode: NavigationMode;\n};\n\n/** Emitted when a navigation has completed and the new page is on screen. */\nexport type NavigationEndPayload = {\n /** The URL the navigation was requested for — the same string {@link NavigationStartPayload} carried. */\n url: string;\n /**\n * The URL the page data actually came from, which is what landed in the\n * address bar. It differs from `url` whenever the server redirected — a\n * page that requires auth answers from `/login` (see\n * `client/navigation/fetch-page-data.ts`).\n */\n resolvedUrl: string;\n mode: NavigationMode;\n};\n\n/**\n * Emitted when a navigation could not complete.\n *\n * A failed client navigation is not a dead end — the runtime degrades to a\n * full browser load — so a listener should treat this as \"the in-flight\n * navigation is over\", not as an error to render. A progress bar hides on it.\n */\nexport type NavigationErrorPayload = {\n /** The URL the navigation was requested for. */\n url: string;\n mode: NavigationMode;\n /**\n * What went wrong. `unknown` rather than `Error` because a caught value has\n * no such guarantee — narrow it before reading `.message`.\n */\n error: unknown;\n};\n\n/** A listener for one navigation event. Its return value is ignored. */\nexport type RouterEventListener<Payload> = (payload: Payload) => void;\n\n/** Call it to stop listening. Calling it more than once is a no-op. */\nexport type RouterEventUnsubscribe = () => void;\n\n/**\n * The navigation lifecycle surface: three events, each with its own payload\n * type, each subscribable and emittable.\n *\n * The `emit*` half belongs to the navigation runtime. Nothing stops other code\n * from calling it, and nothing needs to — an emitter that lies about\n * navigations is a bug in whoever called it, not a boundary worth policing.\n */\nexport type RouterEvents = {\n /** Subscribe to the start of every navigation. @returns the unsubscribe function. */\n onNavigating: (listener: RouterEventListener<NavigationStartPayload>) => RouterEventUnsubscribe;\n /** Subscribe to every navigation that completed. @returns the unsubscribe function. */\n onNavigated: (listener: RouterEventListener<NavigationEndPayload>) => RouterEventUnsubscribe;\n /** Subscribe to every navigation that failed. @returns the unsubscribe function. */\n onNavigationError: (\n listener: RouterEventListener<NavigationErrorPayload>,\n ) => RouterEventUnsubscribe;\n /** Announce that a navigation has begun. Called by the navigation runtime. */\n emitNavigating: (payload: NavigationStartPayload) => void;\n /** Announce that a navigation has completed. Called by the navigation runtime. */\n emitNavigated: (payload: NavigationEndPayload) => void;\n /** Announce that a navigation has failed. Called by the navigation runtime. */\n emitNavigationError: (payload: NavigationErrorPayload) => void;\n};\n\n/**\n * One registration. An OBJECT rather than the callback itself, so that\n * subscribing the same function twice is two independent registrations — a\n * registry keyed by the callback would collapse them, and then one component's\n * cleanup would silently deafen another's.\n */\ntype Registration<Payload> = { listener: RouterEventListener<Payload> };\n\ntype Signal<Payload> = {\n subscribe: (listener: RouterEventListener<Payload>) => RouterEventUnsubscribe;\n emit: (payload: Payload) => void;\n};\n\n/**\n * One event's registrations and its delivery loop. A `Set` because insertion\n * order is preserved (listeners fire in subscription order) and removal is by\n * identity, which is exactly what an unsubscribe closure holds.\n */\nfunction createSignal<Payload>(eventName: string): Signal<Payload> {\n const registrations = new Set<Registration<Payload>>();\n\n return {\n subscribe: listener => {\n const registration: Registration<Payload> = { listener };\n\n registrations.add(registration);\n\n // `Set.delete` on an absent member is a no-op, so this is idempotent for\n // free — which matters because React StrictMode runs an effect's cleanup\n // twice in development.\n return () => {\n registrations.delete(registration);\n };\n },\n emit: payload => {\n /*\n A SNAPSHOT, not the live set. Listeners subscribe and unsubscribe from\n inside other listeners — a progress bar that hides itself, a one-shot\n analytics hook — and mutating the collection being iterated is how an\n emitter starts skipping listeners. Iterating a copy also fixes the\n cohort: a listener added during this emit belongs to the next\n navigation, not to the one already in flight.\n\n Removals during the emit are still honoured (the deleted-check below),\n because a listener that has just unsubscribed has said it no longer\n wants this event, and delivering it anyway is the bug that outlives the\n component.\n */\n for (const registration of [...registrations]) {\n if (!registrations.has(registration)) continue;\n\n try {\n registration.listener(payload);\n } catch (error) {\n /*\n THE POINT OF THE TRY. Everything downstream of an emit — the\n history entry, the tree swap — happens after this loop returns, so\n a listener that throws would otherwise take the navigation down\n with it. One broken progress bar is a broken progress bar; it is\n not a stuck page.\n\n Reported rather than swallowed: a listener failing silently on\n every navigation is worse than noisy. The listener STAYS\n subscribed, because one bad emit is not consent to deregister\n something the component still owns and will still try to clean up.\n */\n console.error(`Warlock routerEvents: a ${eventName} listener threw:`, error);\n }\n }\n },\n };\n}\n\n/**\n * Builds an independent emitter with no listeners.\n *\n * This is what makes the module TESTABLE without cross-test bleed, and it is\n * the escape hatch for anything that needs a private lifecycle bus. The\n * shared {@link routerEvents} is one of these, created once.\n */\nexport function createRouterEvents(): RouterEvents {\n const navigating = createSignal<NavigationStartPayload>(\"navigating\");\n const navigated = createSignal<NavigationEndPayload>(\"navigated\");\n const navigationError = createSignal<NavigationErrorPayload>(\"navigation-error\");\n\n return {\n onNavigating: navigating.subscribe,\n onNavigated: navigated.subscribe,\n onNavigationError: navigationError.subscribe,\n emitNavigating: navigating.emit,\n emitNavigated: navigated.emit,\n emitNavigationError: navigationError.emit,\n };\n}\n\n/**\n * The shared navigation lifecycle emitter — the one a progress bar subscribes\n * to and the one the navigation runtime emits on.\n *\n * ## Why a module-level singleton is safe here, when module-level state is a known SSR hazard\n *\n * Canon records MRR's `RouterWrapper.tsx:63` as the cautionary case: module\n * state that holds RENDER state is shared by every concurrent request on the\n * server, so one visitor's page leaks into another's. That hazard is about\n * *what* is held, not about module scope itself — `routing/navigator.ts` in\n * this same directory already holds a module-level registration for the same\n * reason.\n *\n * This object holds ONLY listener registrations. No current route, no payload,\n * no request-scoped anything — nothing a render reads and nothing a response\n * is built from. Two concurrent SSR requests observe the same empty listener\n * sets and neither can learn a thing about the other.\n *\n * It is also safe to IMPORT on the server: constructing it touches no DOM\n * global, no `window`, no `history`, and performs no work beyond allocating\n * three empty sets. On the server nothing subscribes and nothing emits, so it\n * simply sits there — which is the correct server behaviour for a progress\n * bar.\n *\n * A singleton (rather than a context or a factory at the call site) is what\n * lets a progress bar living anywhere in the tree — or outside React\n * entirely — hear a navigation without being handed a bus by every component\n * between it and the root. That plumbing is the reason MRR made this global\n * too. Use {@link createRouterEvents} when you want an isolated one.\n */\nexport const routerEvents: RouterEvents = createRouterEvents();\n"],"mappings":";;;;;;AAyJA,SAAS,aAAsB,WAAoC;CACjE,MAAM,gCAAgB,IAAI,IAA2B;CAErD,OAAO;EACL,YAAW,aAAY;GACrB,MAAM,eAAsC,EAAE,SAAS;GAEvD,cAAc,IAAI,YAAY;GAK9B,aAAa;IACX,cAAc,OAAO,YAAY;GACnC;EACF;EACA,OAAM,YAAW;GAcf,KAAK,MAAM,gBAAgB,CAAC,GAAG,aAAa,GAAG;IAC7C,IAAI,CAAC,cAAc,IAAI,YAAY,GAAG;IAEtC,IAAI;KACF,aAAa,SAAS,OAAO;IAC/B,SAAS,OAAO;KAad,QAAQ,MAAM,2BAA2B,UAAU,mBAAmB,KAAK;IAC7E;GACF;EACF;CACF;AACF;;;;;;;;AASA,SAAgB,qBAAmC;CACjD,MAAM,aAAa,aAAqC,YAAY;CACpE,MAAM,YAAY,aAAmC,WAAW;CAChE,MAAM,kBAAkB,aAAqC,kBAAkB;CAE/E,OAAO;EACL,cAAc,WAAW;EACzB,aAAa,UAAU;EACvB,mBAAmB,gBAAgB;EACnC,gBAAgB,WAAW;EAC3B,eAAe,UAAU;EACzB,qBAAqB,gBAAgB;CACvC;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,MAAa,eAA6B,mBAAmB"}
|
|
1
|
+
{"version":3,"file":"router-events.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/routing/router-events.ts"],"sourcesContent":["/**\n * The navigation lifecycle emitter — what a progress bar subscribes to.\n *\n * A client navigation is a fetch followed by a tree swap\n * (`client/navigation/navigation-root.tsx`). Nothing about that is visible to\n * the user while it is in flight, which is the whole reason this module\n * exists: a progress bar, an analytics hook or a scroll restorer needs to know\n * that a navigation STARTED, that it FINISHED, and that it FAILED — and none\n * of them should have to reach into the navigation runtime to find out.\n *\n * So the runtime announces, and anyone may listen. The listeners are strangers\n * to each other and to the runtime; that is the point.\n *\n * ## This module ships the emitter only\n *\n * Nothing here is wired into the navigation runtime yet — `navigation-root.tsx`\n * calls the `emit*` methods in a later change. Until then this is a complete,\n * self-contained emitter with no callers, which is why it has no dependency on\n * anything in `client/`.\n *\n * ## What it deliberately does NOT do\n *\n * It carries URLs as OPAQUE STRINGS. There is no matching, no parsing, no\n * \"which route is this\" — Warlock's server router is the only matcher (canon\n * 9c8f878b), and an emitter that started parsing paths would be a second one.\n * A listener that wants a route name gets it from the payload the navigation\n * produced, not from this module.\n *\n * DIRECTORY CONTRACT — see `route-identity.ts`: nothing in `web/src/routing/`\n * may import `node:fs`, `node:path`, `vite` or `fastify`. This module also\n * touches no DOM global, which is what makes it importable from a server\n * render (see below).\n *\n * ## Named for its ancestor\n *\n * `routerEvents` is the name `@mongez/react-router` used\n * (`@mongez/react-router/src/events.ts`), and the subscription ergonomics are\n * deliberately familiar: `routerEvents.onNavigating(callback)` returns\n * something you call to stop listening. The implementation is NOT ported —\n * MRR's delegates to a global `@mongez/events` bus keyed by string\n * (`\"router.navigating\"`), which reaches its router singleton and gives up\n * per-event payload typing in the process. Here the events are the object's\n * own methods, so each one carries its own payload type and a typo is a\n * compile error rather than a listener that never fires.\n *\n * MRR returns an `EventSubscription` object; this returns the unsubscribe\n * FUNCTION itself, because that is what a React `useEffect` cleanup wants to\n * be handed:\n *\n * ```ts\n * useEffect(() => routerEvents.onNavigating(() => setLoading(true)), []);\n * ```\n */\n\n/**\n * How the navigation will be written to browser history.\n *\n * `\"replace\"` covers both an explicit `<Link replace>` and a Back/Forward\n * press — the runtime replaces in both cases, because the history entry\n * already exists. A listener that wants to stay quiet during Back/Forward\n * cannot tell the two apart from here, and does not need to: what it actually\n * cares about is that no new entry is being pushed.\n */\nexport type NavigationMode = \"push\" | \"replace\";\n\n/** Emitted when a navigation begins — before anything has been fetched. */\nexport type NavigationStartPayload = {\n /** The URL the navigation was requested for, verbatim and unparsed. */\n url: string;\n mode: NavigationMode;\n};\n\n/** Emitted when a navigation has completed and the new page is on screen. */\nexport type NavigationEndPayload = {\n /** The URL the navigation was requested for — the same string {@link NavigationStartPayload} carried. */\n url: string;\n /**\n * The URL the page data actually came from, which is what landed in the\n * address bar. It differs from `url` whenever the server redirected — a\n * page that requires auth answers from `/login` (see\n * `client/navigation/fetch-page-data.ts`).\n */\n resolvedUrl: string;\n mode: NavigationMode;\n};\n\n/**\n * Emitted when a navigation could not complete.\n *\n * A failed client navigation is not a dead end — the runtime degrades to a\n * full browser load — so a listener should treat this as \"the in-flight\n * navigation is over\", not as an error to render. A progress bar hides on it.\n */\nexport type NavigationErrorPayload = {\n /** The URL the navigation was requested for. */\n url: string;\n mode: NavigationMode;\n /**\n * What went wrong. `unknown` rather than `Error` because a caught value has\n * no such guarantee — narrow it before reading `.message`.\n */\n error: unknown;\n};\n\n/** A listener for one navigation event. Its return value is ignored. */\nexport type RouterEventListener<Payload> = (payload: Payload) => void;\n\n/** Call it to stop listening. Calling it more than once is a no-op. */\nexport type RouterEventUnsubscribe = () => void;\n\n/**\n * The navigation lifecycle surface: three events, each with its own payload\n * type, each subscribable and emittable.\n *\n * The `emit*` half belongs to the navigation runtime. Nothing stops other code\n * from calling it, and nothing needs to — an emitter that lies about\n * navigations is a bug in whoever called it, not a boundary worth policing.\n */\nexport type RouterEvents = {\n /** Subscribe to the start of every navigation. @returns the unsubscribe function. */\n onNavigating: (listener: RouterEventListener<NavigationStartPayload>) => RouterEventUnsubscribe;\n /** Subscribe to every navigation that completed. @returns the unsubscribe function. */\n onNavigated: (listener: RouterEventListener<NavigationEndPayload>) => RouterEventUnsubscribe;\n /** Subscribe to every navigation that failed. @returns the unsubscribe function. */\n onNavigationError: (\n listener: RouterEventListener<NavigationErrorPayload>,\n ) => RouterEventUnsubscribe;\n /** Announce that a navigation has begun. Called by the navigation runtime. */\n emitNavigating: (payload: NavigationStartPayload) => void;\n /** Announce that a navigation has completed. Called by the navigation runtime. */\n emitNavigated: (payload: NavigationEndPayload) => void;\n /** Announce that a navigation has failed. Called by the navigation runtime. */\n emitNavigationError: (payload: NavigationErrorPayload) => void;\n};\n\n/**\n * One registration. An OBJECT rather than the callback itself, so that\n * subscribing the same function twice is two independent registrations — a\n * registry keyed by the callback would collapse them, and then one component's\n * cleanup would silently deafen another's.\n */\ntype Registration<Payload> = { listener: RouterEventListener<Payload> };\n\ntype Signal<Payload> = {\n subscribe: (listener: RouterEventListener<Payload>) => RouterEventUnsubscribe;\n emit: (payload: Payload) => void;\n};\n\n/**\n * One event's registrations and its delivery loop. A `Set` because insertion\n * order is preserved (listeners fire in subscription order) and removal is by\n * identity, which is exactly what an unsubscribe closure holds.\n */\nfunction createSignal<Payload>(eventName: string): Signal<Payload> {\n const registrations = new Set<Registration<Payload>>();\n\n return {\n subscribe: listener => {\n const registration: Registration<Payload> = { listener };\n\n registrations.add(registration);\n\n // `Set.delete` on an absent member is a no-op, so this is idempotent for\n // free — which matters because React StrictMode runs an effect's cleanup\n // twice in development.\n return () => {\n registrations.delete(registration);\n };\n },\n emit: payload => {\n /*\n A SNAPSHOT, not the live set. Listeners subscribe and unsubscribe from\n inside other listeners — a progress bar that hides itself, a one-shot\n analytics hook — and mutating the collection being iterated is how an\n emitter starts skipping listeners. Iterating a copy also fixes the\n cohort: a listener added during this emit belongs to the next\n navigation, not to the one already in flight.\n\n Removals during the emit are still honoured (the deleted-check below),\n because a listener that has just unsubscribed has said it no longer\n wants this event, and delivering it anyway is the bug that outlives the\n component.\n */\n for (const registration of [...registrations]) {\n if (!registrations.has(registration)) continue;\n\n try {\n registration.listener(payload);\n } catch (error) {\n /*\n THE POINT OF THE TRY. Everything downstream of an emit — the\n history entry, the tree swap — happens after this loop returns, so\n a listener that throws would otherwise take the navigation down\n with it. One broken progress bar is a broken progress bar; it is\n not a stuck page.\n\n Reported rather than swallowed: a listener failing silently on\n every navigation is worse than noisy. The listener STAYS\n subscribed, because one bad emit is not consent to deregister\n something the component still owns and will still try to clean up.\n */\n console.error(`Warlock routerEvents: a ${eventName} listener threw:`, error);\n }\n }\n },\n };\n}\n\n/**\n * Builds an independent emitter with no listeners.\n *\n * This is what makes the module TESTABLE without cross-test bleed, and it is\n * the escape hatch for anything that needs a private lifecycle bus. The\n * shared {@link routerEvents} is one of these, created once.\n */\nexport function createRouterEvents(): RouterEvents {\n const navigating = createSignal<NavigationStartPayload>(\"navigating\");\n const navigated = createSignal<NavigationEndPayload>(\"navigated\");\n const navigationError = createSignal<NavigationErrorPayload>(\"navigation-error\");\n\n return {\n onNavigating: navigating.subscribe,\n onNavigated: navigated.subscribe,\n onNavigationError: navigationError.subscribe,\n emitNavigating: navigating.emit,\n emitNavigated: navigated.emit,\n emitNavigationError: navigationError.emit,\n };\n}\n\n/**\n * The shared navigation lifecycle emitter — the one a progress bar subscribes\n * to and the one the navigation runtime emits on.\n *\n * ## Why a module-level singleton is safe here, when module-level state is a known SSR hazard\n *\n * Canon records MRR's `RouterWrapper.tsx:63` as the cautionary case: module\n * state that holds RENDER state is shared by every concurrent request on the\n * server, so one visitor's page leaks into another's. That hazard is about\n * *what* is held, not about module scope itself — `routing/navigator.ts` in\n * this same directory already holds a module-level registration for the same\n * reason.\n *\n * This object holds ONLY listener registrations. No current route, no payload,\n * no request-scoped anything — nothing a render reads and nothing a response\n * is built from. Two concurrent SSR requests observe the same empty listener\n * sets and neither can learn a thing about the other.\n *\n * It is also safe to IMPORT on the server: constructing it touches no DOM\n * global, no `window`, no `history`, and performs no work beyond allocating\n * three empty sets. On the server nothing subscribes and nothing emits, so it\n * simply sits there — which is the correct server behaviour for a progress\n * bar.\n *\n * A singleton (rather than a context or a factory at the call site) is what\n * lets a progress bar living anywhere in the tree — or outside React\n * entirely — hear a navigation without being handed a bus by every component\n * between it and the root. That plumbing is the reason MRR made this global\n * too. Use {@link createRouterEvents} when you want an isolated one.\n */\nexport const routerEvents: RouterEvents = createRouterEvents();\n"],"mappings":";;;;;;AAyJA,SAAS,aAAsB,WAAoC;CACjE,MAAM,gCAAgB,IAAI,IAA2B;CAErD,OAAO;EACL,YAAW,aAAY;GACrB,MAAM,eAAsC,EAAE,SAAS;GAEvD,cAAc,IAAI,YAAY;GAK9B,aAAa;IACX,cAAc,OAAO,YAAY;GACnC;EACF;EACA,OAAM,YAAW;GAcf,KAAK,MAAM,gBAAgB,CAAC,GAAG,aAAa,GAAG;IAC7C,IAAI,CAAC,cAAc,IAAI,YAAY,GAAG;IAEtC,IAAI;KACF,aAAa,SAAS,OAAO;IAC/B,SAAS,OAAO;KAad,QAAQ,MAAM,2BAA2B,UAAU,mBAAmB,KAAK;IAC7E;GACF;EACF;CACF;AACF;;;;;;;;AASA,SAAgB,qBAAmC;CACjD,MAAM,aAAa,aAAqC,YAAY;CACpE,MAAM,YAAY,aAAmC,WAAW;CAChE,MAAM,kBAAkB,aAAqC,kBAAkB;CAE/E,OAAO;EACL,cAAc,WAAW;EACzB,aAAa,UAAU;EACvB,mBAAmB,gBAAgB;EACnC,gBAAgB,WAAW;EAC3B,eAAe,UAAU;EACzB,qBAAqB,gBAAgB;CACvC;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,MAAa,eAA6B,mBAAmB"}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
//#region web/src/routing/url-fragment.ts
|
|
2
|
+
/**
|
|
3
|
+
* The URL FRAGMENT, kept as a first-class part of a navigation.
|
|
4
|
+
*
|
|
5
|
+
* ## The defect this file exists for
|
|
6
|
+
*
|
|
7
|
+
* A client navigation asks the server for page data with `fetch`, and a
|
|
8
|
+
* fragment is a CLIENT-SIDE construct: it is never sent, and `response.url` —
|
|
9
|
+
* the URL history is written from, because it reflects any redirect that was
|
|
10
|
+
* followed — therefore never carries one. So `<Link href="/docs#install">`
|
|
11
|
+
* pushed `/docs` and the fragment the author wrote was silently gone from the
|
|
12
|
+
* address bar: not shareable, not bookmarkable, not restorable on reload.
|
|
13
|
+
*
|
|
14
|
+
* Everything here is pure string work over `URL`, deliberately: the navigation
|
|
15
|
+
* runtime is the only place that may touch `window`, and these answers have to
|
|
16
|
+
* be provable in a suite with no browser.
|
|
17
|
+
*
|
|
18
|
+
* ## The redirect rule, which is the browser's rule
|
|
19
|
+
*
|
|
20
|
+
* When a request is redirected and the `Location` carries no fragment of its
|
|
21
|
+
* own, the ORIGINAL fragment is carried onto the destination (RFC 7231 §7.1.2).
|
|
22
|
+
* A `Location` that DOES name one wins outright. {@link withFragmentFrom} is
|
|
23
|
+
* that rule and nothing else, so a client navigation through a redirect lands
|
|
24
|
+
* where a full page load would have landed.
|
|
25
|
+
*/
|
|
26
|
+
/**
|
|
27
|
+
* The fragment of `url`, WITHOUT its leading `#`.
|
|
28
|
+
*
|
|
29
|
+
* `undefined` means there was no `#` at all, and `""` means there was one with
|
|
30
|
+
* nothing after it. The two are kept apart because they are different requests:
|
|
31
|
+
* `/docs` says nothing about a fragment, `/docs#` says "no target" — and only
|
|
32
|
+
* the second should end up written to the address bar as `#`.
|
|
33
|
+
*
|
|
34
|
+
* Plain string work rather than `new URL()`: this is asked of RELATIVE URLs
|
|
35
|
+
* (`/docs#install`, `#install`), which `URL` cannot parse without a base, and
|
|
36
|
+
* the base is `window`'s — not available on the server, and not this module's
|
|
37
|
+
* to reach for.
|
|
38
|
+
*/
|
|
39
|
+
function fragmentOf(url) {
|
|
40
|
+
const index = url.indexOf("#");
|
|
41
|
+
return index === -1 ? void 0 : url.slice(index + 1);
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* `url` with everything from its `#` onward removed.
|
|
45
|
+
*/
|
|
46
|
+
function withoutFragment(url) {
|
|
47
|
+
const index = url.indexOf("#");
|
|
48
|
+
return index === -1 ? url : url.slice(0, index);
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Carry the fragment the caller ASKED for onto the URL the response came from.
|
|
52
|
+
*
|
|
53
|
+
* The resolved URL wins when it names a fragment itself — a redirect that says
|
|
54
|
+
* `Location: /docs/v5#moved` meant it. Otherwise the requested fragment rides
|
|
55
|
+
* along, which for the overwhelmingly common case (no redirect) simply puts
|
|
56
|
+
* back what `fetch` dropped.
|
|
57
|
+
*/
|
|
58
|
+
function withFragmentFrom(resolvedUrl, requestedUrl) {
|
|
59
|
+
if (fragmentOf(resolvedUrl) !== void 0) return resolvedUrl;
|
|
60
|
+
const fragment = fragmentOf(requestedUrl);
|
|
61
|
+
return fragment === void 0 ? resolvedUrl : `${resolvedUrl}#${fragment}`;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* The `id` a fragment names, decoded.
|
|
65
|
+
*
|
|
66
|
+
* A fragment travels PERCENT-ENCODED — `#a%20b`, and every non-ASCII id is
|
|
67
|
+
* encoded by the browser the moment it reaches the address bar — while the
|
|
68
|
+
* `id` attribute in the document holds the decoded characters. Looking up the
|
|
69
|
+
* raw fragment therefore misses every id with a space or a non-Latin letter,
|
|
70
|
+
* which is a silent no-scroll indistinguishable from the bug this fixes.
|
|
71
|
+
*
|
|
72
|
+
* A malformed escape (`#100%`) is NOT an error here: `decodeURIComponent`
|
|
73
|
+
* throws on it, and a throw during a navigation would cost the page for the
|
|
74
|
+
* sake of a scroll. The raw text is returned instead, which is exactly what an
|
|
75
|
+
* `id="100%"` in the document would match.
|
|
76
|
+
*/
|
|
77
|
+
function fragmentTargetId(fragment) {
|
|
78
|
+
try {
|
|
79
|
+
return decodeURIComponent(fragment);
|
|
80
|
+
} catch {
|
|
81
|
+
return fragment;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* The fragment of a destination that is THIS page with a fragment on it —
|
|
86
|
+
* `#section`, or the current path written out in full with one appended.
|
|
87
|
+
*
|
|
88
|
+
* `undefined` means "not that": a different page, no fragment, or a URL that
|
|
89
|
+
* cannot be resolved at all. The caller navigates as it otherwise would.
|
|
90
|
+
*
|
|
91
|
+
* Such a click must NOT run a client navigation. Re-fetching the page the user
|
|
92
|
+
* is already looking at would throw away its DOM and every piece of state in
|
|
93
|
+
* it — a scrolled container, an open menu, a playing video — to arrive at the
|
|
94
|
+
* same page, and the round trip means the jump does not happen until the
|
|
95
|
+
* network answers. The browser does not do that for a plain `<a href="#x">`
|
|
96
|
+
* and neither do we: the URL is updated and the page scrolls, in that order.
|
|
97
|
+
*
|
|
98
|
+
* The comparison is on origin, path and QUERY: `?page=2#top` from `?page=1#top`
|
|
99
|
+
* is a real navigation to different data that happens to share a fragment.
|
|
100
|
+
*
|
|
101
|
+
* An EMPTY fragment (`/here#`) does not qualify — there is no target to scroll
|
|
102
|
+
* to and nothing to distinguish it from a plain re-navigation to the same page.
|
|
103
|
+
*/
|
|
104
|
+
function samePageFragment(url, currentHref) {
|
|
105
|
+
let destination;
|
|
106
|
+
let current;
|
|
107
|
+
try {
|
|
108
|
+
destination = new URL(url, currentHref);
|
|
109
|
+
current = new URL(currentHref);
|
|
110
|
+
} catch {
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
const fragment = destination.hash.slice(1);
|
|
114
|
+
if (fragment === "") return void 0;
|
|
115
|
+
return destination.origin === current.origin && destination.pathname === current.pathname && destination.search === current.search ? fragment : void 0;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
//#endregion
|
|
119
|
+
export { fragmentOf, fragmentTargetId, samePageFragment, withFragmentFrom, withoutFragment };
|
|
120
|
+
//# sourceMappingURL=url-fragment.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"url-fragment.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/routing/url-fragment.ts"],"sourcesContent":["/**\n * The URL FRAGMENT, kept as a first-class part of a navigation.\n *\n * ## The defect this file exists for\n *\n * A client navigation asks the server for page data with `fetch`, and a\n * fragment is a CLIENT-SIDE construct: it is never sent, and `response.url` —\n * the URL history is written from, because it reflects any redirect that was\n * followed — therefore never carries one. So `<Link href=\"/docs#install\">`\n * pushed `/docs` and the fragment the author wrote was silently gone from the\n * address bar: not shareable, not bookmarkable, not restorable on reload.\n *\n * Everything here is pure string work over `URL`, deliberately: the navigation\n * runtime is the only place that may touch `window`, and these answers have to\n * be provable in a suite with no browser.\n *\n * ## The redirect rule, which is the browser's rule\n *\n * When a request is redirected and the `Location` carries no fragment of its\n * own, the ORIGINAL fragment is carried onto the destination (RFC 7231 §7.1.2).\n * A `Location` that DOES name one wins outright. {@link withFragmentFrom} is\n * that rule and nothing else, so a client navigation through a redirect lands\n * where a full page load would have landed.\n */\n\n/**\n * The fragment of `url`, WITHOUT its leading `#`.\n *\n * `undefined` means there was no `#` at all, and `\"\"` means there was one with\n * nothing after it. The two are kept apart because they are different requests:\n * `/docs` says nothing about a fragment, `/docs#` says \"no target\" — and only\n * the second should end up written to the address bar as `#`.\n *\n * Plain string work rather than `new URL()`: this is asked of RELATIVE URLs\n * (`/docs#install`, `#install`), which `URL` cannot parse without a base, and\n * the base is `window`'s — not available on the server, and not this module's\n * to reach for.\n */\nexport function fragmentOf(url: string): string | undefined {\n const index = url.indexOf(\"#\");\n\n return index === -1 ? undefined : url.slice(index + 1);\n}\n\n/**\n * `url` with everything from its `#` onward removed.\n */\nexport function withoutFragment(url: string): string {\n const index = url.indexOf(\"#\");\n\n return index === -1 ? url : url.slice(0, index);\n}\n\n/**\n * Carry the fragment the caller ASKED for onto the URL the response came from.\n *\n * The resolved URL wins when it names a fragment itself — a redirect that says\n * `Location: /docs/v5#moved` meant it. Otherwise the requested fragment rides\n * along, which for the overwhelmingly common case (no redirect) simply puts\n * back what `fetch` dropped.\n */\nexport function withFragmentFrom(resolvedUrl: string, requestedUrl: string): string {\n if (fragmentOf(resolvedUrl) !== undefined) return resolvedUrl;\n\n const fragment = fragmentOf(requestedUrl);\n\n return fragment === undefined ? resolvedUrl : `${resolvedUrl}#${fragment}`;\n}\n\n/**\n * The `id` a fragment names, decoded.\n *\n * A fragment travels PERCENT-ENCODED — `#a%20b`, and every non-ASCII id is\n * encoded by the browser the moment it reaches the address bar — while the\n * `id` attribute in the document holds the decoded characters. Looking up the\n * raw fragment therefore misses every id with a space or a non-Latin letter,\n * which is a silent no-scroll indistinguishable from the bug this fixes.\n *\n * A malformed escape (`#100%`) is NOT an error here: `decodeURIComponent`\n * throws on it, and a throw during a navigation would cost the page for the\n * sake of a scroll. The raw text is returned instead, which is exactly what an\n * `id=\"100%\"` in the document would match.\n */\nexport function fragmentTargetId(fragment: string): string {\n try {\n return decodeURIComponent(fragment);\n } catch {\n return fragment;\n }\n}\n\n/**\n * The fragment of a destination that is THIS page with a fragment on it —\n * `#section`, or the current path written out in full with one appended.\n *\n * `undefined` means \"not that\": a different page, no fragment, or a URL that\n * cannot be resolved at all. The caller navigates as it otherwise would.\n *\n * Such a click must NOT run a client navigation. Re-fetching the page the user\n * is already looking at would throw away its DOM and every piece of state in\n * it — a scrolled container, an open menu, a playing video — to arrive at the\n * same page, and the round trip means the jump does not happen until the\n * network answers. The browser does not do that for a plain `<a href=\"#x\">`\n * and neither do we: the URL is updated and the page scrolls, in that order.\n *\n * The comparison is on origin, path and QUERY: `?page=2#top` from `?page=1#top`\n * is a real navigation to different data that happens to share a fragment.\n *\n * An EMPTY fragment (`/here#`) does not qualify — there is no target to scroll\n * to and nothing to distinguish it from a plain re-navigation to the same page.\n */\nexport function samePageFragment(url: string, currentHref: string): string | undefined {\n let destination: URL;\n let current: URL;\n\n try {\n destination = new URL(url, currentHref);\n current = new URL(currentHref);\n } catch {\n return undefined;\n }\n\n const fragment = destination.hash.slice(1);\n\n if (fragment === \"\") return undefined;\n\n const samePage =\n destination.origin === current.origin &&\n destination.pathname === current.pathname &&\n destination.search === current.search;\n\n return samePage ? fragment : undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,SAAgB,WAAW,KAAiC;CAC1D,MAAM,QAAQ,IAAI,QAAQ,GAAG;CAE7B,OAAO,UAAU,KAAK,SAAY,IAAI,MAAM,QAAQ,CAAC;AACvD;;;;AAKA,SAAgB,gBAAgB,KAAqB;CACnD,MAAM,QAAQ,IAAI,QAAQ,GAAG;CAE7B,OAAO,UAAU,KAAK,MAAM,IAAI,MAAM,GAAG,KAAK;AAChD;;;;;;;;;AAUA,SAAgB,iBAAiB,aAAqB,cAA8B;CAClF,IAAI,WAAW,WAAW,MAAM,QAAW,OAAO;CAElD,MAAM,WAAW,WAAW,YAAY;CAExC,OAAO,aAAa,SAAY,cAAc,GAAG,YAAY,GAAG;AAClE;;;;;;;;;;;;;;;AAgBA,SAAgB,iBAAiB,UAA0B;CACzD,IAAI;EACF,OAAO,mBAAmB,QAAQ;CACpC,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,iBAAiB,KAAa,aAAyC;CACrF,IAAI;CACJ,IAAI;CAEJ,IAAI;EACF,cAAc,IAAI,IAAI,KAAK,WAAW;EACtC,UAAU,IAAI,IAAI,WAAW;CAC/B,QAAQ;EACN;CACF;CAEA,MAAM,WAAW,YAAY,KAAK,MAAM,CAAC;CAEzC,IAAI,aAAa,IAAI,OAAO;CAO5B,OAJE,YAAY,WAAW,QAAQ,UAC/B,YAAY,aAAa,QAAQ,YACjC,YAAY,WAAW,QAAQ,SAEf,WAAW;AAC/B"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
//#region web/src/runtime/register-modules.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* The universal portion of a page or layout module namespace.
|
|
4
|
+
*
|
|
5
|
+
* `register` deliberately has no arguments and must finish synchronously: it
|
|
6
|
+
* runs while both the server and browser evaluate the same module graph.
|
|
7
|
+
*/
|
|
8
|
+
type RegisterableModuleNamespace = {
|
|
9
|
+
readonly register?: () => unknown;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* Run each module's optional universal registration hook at most once for
|
|
13
|
+
* that module namespace instance. A replacement namespace from HMR naturally
|
|
14
|
+
* has a new identity and is therefore registered again.
|
|
15
|
+
*/
|
|
16
|
+
declare function registerModules(modules: readonly RegisterableModuleNamespace[]): void;
|
|
17
|
+
//#endregion
|
|
18
|
+
export { RegisterableModuleNamespace, registerModules };
|
|
19
|
+
//# sourceMappingURL=register-modules.d.mts.map
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
//#region web/src/runtime/register-modules.ts
|
|
2
|
+
const registeredModules = /* @__PURE__ */ new WeakSet();
|
|
3
|
+
function isThenable(value) {
|
|
4
|
+
return value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Run each module's optional universal registration hook at most once for
|
|
8
|
+
* that module namespace instance. A replacement namespace from HMR naturally
|
|
9
|
+
* has a new identity and is therefore registered again.
|
|
10
|
+
*/
|
|
11
|
+
function registerModules(modules) {
|
|
12
|
+
for (const module of modules) {
|
|
13
|
+
if (registeredModules.has(module)) continue;
|
|
14
|
+
const result = module.register?.();
|
|
15
|
+
if (isThenable(result)) throw new Error("Warlock register() hooks must be synchronous and must not return a Promise or thenable.");
|
|
16
|
+
registeredModules.add(module);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
//#endregion
|
|
21
|
+
export { registerModules };
|
|
22
|
+
//# sourceMappingURL=register-modules.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"register-modules.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/runtime/register-modules.ts"],"sourcesContent":["/**\n * The universal portion of a page or layout module namespace.\n *\n * `register` deliberately has no arguments and must finish synchronously: it\n * runs while both the server and browser evaluate the same module graph.\n */\nexport type RegisterableModuleNamespace = {\n readonly register?: () => unknown;\n};\n\nconst registeredModules = new WeakSet<RegisterableModuleNamespace>();\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n value !== null &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\n/**\n * Run each module's optional universal registration hook at most once for\n * that module namespace instance. A replacement namespace from HMR naturally\n * has a new identity and is therefore registered again.\n */\nexport function registerModules(modules: readonly RegisterableModuleNamespace[]): void {\n for (const module of modules) {\n if (registeredModules.has(module)) continue;\n\n const result = module.register?.();\n\n if (isThenable(result)) {\n throw new Error(\n \"Warlock register() hooks must be synchronous and must not return a Promise or thenable.\",\n );\n }\n\n // A throwing hook (including one that returned a thenable above) is not\n // recorded, so a later route composition still exposes and can retry it.\n registeredModules.add(module);\n }\n}\n"],"mappings":";AAUA,MAAM,oCAAoB,IAAI,QAAqC;AAEnE,SAAS,WAAW,OAA+C;CACjE,OACE,UAAU,SACT,OAAO,UAAU,YAAY,OAAO,UAAU,eAC/C,OAAQ,MAA6B,SAAS;AAElD;;;;;;AAOA,SAAgB,gBAAgB,SAAuD;CACrF,KAAK,MAAM,UAAU,SAAS;EAC5B,IAAI,kBAAkB,IAAI,MAAM,GAAG;EAEnC,MAAM,SAAS,OAAO,WAAW;EAEjC,IAAI,WAAW,MAAM,GACnB,MAAM,IAAI,MACR,yFACF;EAKF,kBAAkB,IAAI,MAAM;CAC9B;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//#region
|
|
1
|
+
//#region web/src/server/build-hydration-payload.ts
|
|
2
2
|
/**
|
|
3
3
|
* Levels without a loader resolve to `undefined`, but the hydration contract
|
|
4
4
|
* requires every data key to be PRESENT.
|
|
@@ -18,6 +18,7 @@ function buildHydrationPayload(bundle) {
|
|
|
18
18
|
shared: serializableData(bundle.shared),
|
|
19
19
|
params: bundle.route.params,
|
|
20
20
|
...bundle.metadata === void 0 ? {} : { metadata: bundle.metadata },
|
|
21
|
+
...bundle.errorPage === void 0 ? {} : { errorPage: bundle.errorPage },
|
|
21
22
|
name: bundle.route.name
|
|
22
23
|
};
|
|
23
24
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build-hydration-payload.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"build-hydration-payload.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/server/build-hydration-payload.ts"],"sourcesContent":["/**\n * The ONE place the hydration payload's shape is decided.\n *\n * Two callers need the identical object and must never drift:\n *\n * `render-page.ts` embeds it in the document as `#__WARLOCK_DATA__`, which\n * is what a FULL page load hands the browser.\n * the `_loader` route returns it as JSON, which is what a CLIENT navigation\n * fetches instead of re-rendering the document.\n *\n * Drift between those two is not a cosmetic bug: the browser builds the same\n * React tree from either source, so a key present on one path and absent on the\n * other produces a page that works when you land on it and breaks when you\n * navigate to it — or the reverse, which is worse, because the first visit is\n * the one everybody tests.\n *\n * Extracted rather than duplicated for exactly that reason. It was previously\n * assembled inline inside the renderer, where the loader route could not reach\n * it without copying five lines that would then be free to diverge.\n */\nimport type { HydrationDocumentPayloadSource } from \"../components/document-context\";\nimport type { PageDataBundle } from \"./execute-page-request\";\n\n/**\n * Levels without a loader resolve to `undefined`, but the hydration contract\n * requires every data key to be PRESENT.\n *\n * An intentional `null` is preserved — a loader that returned `null` said\n * something, and flattening it would erase that. Only \"no data at all\" becomes\n * an empty object.\n */\nfunction serializableData(data: unknown): unknown {\n return data === undefined ? {} : data;\n}\n\nexport function buildHydrationPayload(bundle: PageDataBundle): HydrationDocumentPayloadSource {\n return {\n appData: serializableData(bundle.appData),\n layoutData: serializableData(bundle.layoutData),\n pageData: serializableData(bundle.pageData),\n shared: serializableData(bundle.shared),\n // The server's own match, carried for the same reason `name` is: the params\n // are an ANSWER the router already gave, and re-deriving them in the\n // browser from `location.pathname` would be a second matcher disagreeing\n // with the server about the request it is hydrating. `{}` for a route with\n // no dynamic segments — a real answer, not a missing one.\n params: bundle.route.params,\n // Spread, so \"the page produced no metadata\" is the SAME shape here and on\n // the wire. `metadata: undefined` would be a key in the in-process object\n // and no key at all after `JSON.stringify` — one type, two payload shapes,\n // which is precisely the drift this file exists to prevent. Carried whole:\n // `<Head/>` renders every member of `MetadataOutput`, so anything narrowed\n // out here is a tag the first request has and a navigation does not.\n ...(bundle.metadata === undefined ? {} : { metadata: bundle.metadata }),\n ...(bundle.errorPage === undefined ? {} : { errorPage: bundle.errorPage }),\n // The matched entry's own name, carried untransformed from stage 1\n // (`bundle.route.name` IS `matched.entry.name`, execute-page-request.ts).\n // The browser reads it to look up the page the server resolved rather than\n // re-matching the pathname — a second matcher can disagree with the server\n // about the very request it is hydrating, and on a client navigation it\n // would be disagreeing about a request the server already answered.\n name: bundle.route.name,\n };\n}\n"],"mappings":";;;;;;;;;AA+BA,SAAS,iBAAiB,MAAwB;CAChD,OAAO,SAAS,SAAY,CAAC,IAAI;AACnC;AAEA,SAAgB,sBAAsB,QAAwD;CAC5F,OAAO;EACL,SAAS,iBAAiB,OAAO,OAAO;EACxC,YAAY,iBAAiB,OAAO,UAAU;EAC9C,UAAU,iBAAiB,OAAO,QAAQ;EAC1C,QAAQ,iBAAiB,OAAO,MAAM;EAMtC,QAAQ,OAAO,MAAM;EAOrB,GAAI,OAAO,aAAa,SAAY,CAAC,IAAI,EAAE,UAAU,OAAO,SAAS;EACrE,GAAI,OAAO,cAAc,SAAY,CAAC,IAAI,EAAE,WAAW,OAAO,UAAU;EAOxE,MAAM,OAAO,MAAM;CACrB;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client-asset-url-prefix.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"client-asset-url-prefix.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/server/client-asset-url-prefix.ts"],"sourcesContent":["/**\n * The SINGLE authority for where built client assets are served.\n *\n * Two halves must agree and only one of them may own the literal:\n * `resolveHydrationClientUrl` GUARANTEES every URL it returns starts with this\n * prefix, and the production static-file route MUST mount `<clientDir>/assets`\n * at exactly this prefix by importing THIS symbol. A second `\"/assets\"`\n * literal anywhere else is a drift bug: the two copies can be edited apart,\n * and the failure mode is a silent 404 on the hydration script — the page\n * renders, never hydrates, and nothing throws.\n *\n * WHY THE `assets` SUBDIRECTORY AND NOT THE CLIENT ROOT: the client build dir\n * also contains `.vite/manifest.json`, the build→runtime handoff artifact,\n * which must NEVER be publicly served. Mounting the client root would expose\n * it. Mounting only the `assets` subdirectory keeps the manifest unreachable\n * while still serving every hashed artifact the manifest points at.\n */\nexport const CLIENT_ASSET_URL_PREFIX = \"/assets\";\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiBA,MAAa,0BAA0B"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { PageManifest } from "./page-manifest.mjs";
|
|
2
2
|
import { PageModuleLoader } from "./create-page-route-handler.mjs";
|
|
3
3
|
|
|
4
|
-
//#region
|
|
4
|
+
//#region web/src/server/create-page-module-loader.d.ts
|
|
5
5
|
/**
|
|
6
6
|
* Asked for a module this build does not contain.
|
|
7
7
|
*
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//#region
|
|
1
|
+
//#region web/src/server/create-page-module-loader.ts
|
|
2
2
|
/**
|
|
3
3
|
* Asked for a module this build does not contain.
|
|
4
4
|
*
|
|
@@ -33,6 +33,7 @@ var PageModuleNotInManifestError = class extends Error {
|
|
|
33
33
|
function createPageModuleLoader(manifest) {
|
|
34
34
|
const modulesById = /* @__PURE__ */ new Map();
|
|
35
35
|
if (manifest.app) modulesById.set(manifest.app.sourceFile, manifest.app.module);
|
|
36
|
+
if (manifest.errorPage) modulesById.set(manifest.errorPage.sourceFile, manifest.errorPage.module);
|
|
36
37
|
for (const page of manifest.pages) {
|
|
37
38
|
modulesById.set(page.sourceFile, page.module);
|
|
38
39
|
for (const layout of page.layouts) modulesById.set(layout.sourceFile, layout.module);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-page-module-loader.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"create-page-module-loader.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/server/create-page-module-loader.ts"],"sourcesContent":["/**\n * The production answer to \"how do I load a page module\".\n *\n * `createPageRouteHandler` takes loading a module as an INPUT\n * ({@link PageModuleLoader}) precisely so the two runtimes can answer it\n * differently. Dev hands it `moduleId => vite.ssrLoadModule(moduleId)`;\n * production has no Vite and nothing to evaluate — the generated `pages.ts`\n * barrel already imported every page, layout and the app root statically, and\n * {@link PageManifest} is the table those namespace objects arrived in. So the\n * production loader does not load anything: it is a LOOKUP over modules that\n * are already in memory, and this file is that lookup and nothing else.\n */\nimport type { PageModuleLoader } from \"./create-page-route-handler\";\nimport type { PageManifest } from \"./page-manifest\";\n\n/**\n * Asked for a module this build does not contain.\n *\n * Hard failure, deliberately. Every alternative — returning `undefined`, an\n * empty namespace, or falling back to a dynamic import — turns a build that\n * shipped the wrong module table into a page that renders blank, or into a\n * production process reaching for source files that are not deployed. The id\n * is in the message because the whole diagnosis is \"which id, and why is it\n * not in the table\"; the count is there because zero entries means the build\n * discovered no pages at all, which is a different fault from a mismatch.\n */\nexport class PageModuleNotInManifestError extends Error {\n public constructor(moduleId: string, knownIdCount: number) {\n super(\n `Cannot serve a page module: \"${moduleId}\" is not in this build's page manifest ` +\n `(${knownIdCount} module(s) available). Module ids are the manifest's \\`sourceFile\\` ` +\n \"values — app-root-relative POSIX paths, extension included — and must match exactly. \" +\n \"Re-run `warlock build` so the generated `pages.ts` barrel matches what is being served.\",\n );\n this.name = \"PageModuleNotInManifestError\";\n }\n}\n\n/**\n * Build the loader for ONE manifest.\n *\n * Ids are compared by exact string equality against the `sourceFile` each\n * entry carries — no lowercasing, no separator swapping, no extension\n * stripping. Both sides of that comparison come from the same generator\n * (`generatePagesBarrel` writes every `sourceFile` through one\n * app-root-relative POSIX derivation), so any spelling difference is a real\n * disagreement about which file is meant, and a normalizer would only hide it.\n *\n * A layout shared by several pages appears once per chain it belongs to; the\n * generator emits one identifier per layout file, so every occurrence of an id\n * carries the same namespace object and re-registering it is a no-op.\n */\nexport function createPageModuleLoader(manifest: PageManifest): PageModuleLoader {\n const modulesById = new Map<string, Record<string, unknown>>();\n\n if (manifest.app) {\n modulesById.set(manifest.app.sourceFile, manifest.app.module);\n }\n\n if (manifest.errorPage) {\n modulesById.set(manifest.errorPage.sourceFile, manifest.errorPage.module);\n }\n\n for (const page of manifest.pages) {\n modulesById.set(page.sourceFile, page.module);\n\n for (const layout of page.layouts) {\n modulesById.set(layout.sourceFile, layout.module);\n }\n }\n\n // `async` so an unknown id surfaces as a rejection rather than a synchronous\n // throw: the handler awaits every module through one `Promise.all`, and a\n // loader that fails both ways depending on the reason is a loader callers\n // have to guard twice.\n return async (moduleId: string) => {\n const module = modulesById.get(moduleId);\n\n if (module === undefined) {\n throw new PageModuleNotInManifestError(moduleId, modulesById.size);\n }\n\n return module;\n };\n}\n"],"mappings":";;;;;;;;;;;;AA0BA,IAAa,+BAAb,cAAkD,MAAM;CACtD,AAAO,YAAY,UAAkB,cAAsB;EACzD,MACE,gCAAgC,SAAS,0CACnC,aAAa,qPAGrB;EACA,KAAK,OAAO;CACd;AACF;;;;;;;;;;;;;;;AAgBA,SAAgB,uBAAuB,UAA0C;CAC/E,MAAM,8BAAc,IAAI,IAAqC;CAE7D,IAAI,SAAS,KACX,YAAY,IAAI,SAAS,IAAI,YAAY,SAAS,IAAI,MAAM;CAG9D,IAAI,SAAS,WACX,YAAY,IAAI,SAAS,UAAU,YAAY,SAAS,UAAU,MAAM;CAG1E,KAAK,MAAM,QAAQ,SAAS,OAAO;EACjC,YAAY,IAAI,KAAK,YAAY,KAAK,MAAM;EAE5C,KAAK,MAAM,UAAU,KAAK,SACxB,YAAY,IAAI,OAAO,YAAY,OAAO,MAAM;CAEpD;CAMA,OAAO,OAAO,aAAqB;EACjC,MAAM,SAAS,YAAY,IAAI,QAAQ;EAEvC,IAAI,WAAW,QACb,MAAM,IAAI,6BAA6B,UAAU,YAAY,IAAI;EAGnE,OAAO;CACT;AACF"}
|
|
@@ -1,7 +1,9 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { RegisterableModuleNamespace } from "../runtime/register-modules.mjs";
|
|
2
|
+
import { BufferedCookie } from "./settle-page-response.mjs";
|
|
3
|
+
import { ErrorPageModuleLoader } from "./error-page.mjs";
|
|
2
4
|
import { HttpContext, Response } from "@warlock.js/core";
|
|
3
5
|
|
|
4
|
-
//#region
|
|
6
|
+
//#region web/src/server/create-page-route-handler.d.ts
|
|
5
7
|
/**
|
|
6
8
|
* How the handler obtains a page/layout/app module, by the same id
|
|
7
9
|
* (`appFile`/`layoutFile`/`pageFile`) the caller registered it under. In dev
|
|
@@ -15,17 +17,67 @@ type PageRouteHandlerOptions = {
|
|
|
15
17
|
appFile: string; /** The page module's id. */
|
|
16
18
|
pageFile: string; /** The page's own-directory `layout.tsx`, when it has one. */
|
|
17
19
|
layoutFile?: string | undefined;
|
|
18
|
-
loadModule: PageModuleLoader; /**
|
|
20
|
+
loadModule: PageModuleLoader; /** Optional lazy application `error.page.tsx` loader. Never called on success. */
|
|
21
|
+
loadErrorPage?: ErrorPageModuleLoader;
|
|
22
|
+
/**
|
|
23
|
+
* Load the REAL layout module namespaces, outermost first, for universal
|
|
24
|
+
* registration. This stays separate from `loadModule(layoutFile)` because
|
|
25
|
+
* dev may answer that id with a synthetic wrapper whose middleware is the
|
|
26
|
+
* composition of several layouts. That wrapper is a render-pipeline detail,
|
|
27
|
+
* not a module identity, and must never enter `registerModules`' WeakSet.
|
|
28
|
+
*/
|
|
29
|
+
loadRegistrationLayouts?: () => Promise<readonly RegisterableModuleNamespace[]>; /** Browser module appended after the server-rendered document. */
|
|
19
30
|
hydrationClientModuleUrl?: string;
|
|
20
31
|
/**
|
|
21
32
|
* Stylesheet URLs for this page, emitted into `<head>` so the FIRST paint is
|
|
22
33
|
* styled. Absent or empty means the application has no CSS — it never means
|
|
23
34
|
* a stylesheet failed to resolve, which is the build's job to report.
|
|
24
35
|
*/
|
|
25
|
-
stylesheetUrls?: readonly string[];
|
|
26
|
-
|
|
36
|
+
stylesheetUrls?: readonly string[];
|
|
37
|
+
/** Same helper `dev-server.ts` exports — passed in, never imported. */
|
|
38
|
+
/**
|
|
39
|
+
* The pattern stage 1 matches `request.path` against, when it differs from
|
|
40
|
+
* the REGISTERED path. Defaults to `path`, which is right for every route
|
|
41
|
+
* whose URL is its own.
|
|
42
|
+
*
|
|
43
|
+
* Exactly one route needs it: the not-found page, registered on the catch-all
|
|
44
|
+
* `*`. `matchRoute` compares segment by segment (`./match-page-route.ts`) and
|
|
45
|
+
* has no wildcard token, so a route registered as `*` matches NOTHING — the
|
|
46
|
+
* pipeline reports no match and `renderPageRequest` answers `{ html: "",
|
|
47
|
+
* status: 404 }`. Correct status, empty document: a 404 page that never
|
|
48
|
+
* renders its own body. Handing it `requestPath => requestPath` makes the
|
|
49
|
+
* requested URL the route's pattern for that one request, so the match is
|
|
50
|
+
* trivially true and the page renders for the URL the visitor actually asked
|
|
51
|
+
* for.
|
|
52
|
+
*/
|
|
53
|
+
matchPath?: (requestPath: string) => string;
|
|
54
|
+
/**
|
|
55
|
+
* The status this route answers with when the pipeline settles on a plain
|
|
56
|
+
* `200` — the not-found route's `404`, and nothing else uses it.
|
|
57
|
+
*
|
|
58
|
+
* Applied ONLY to `200`, never as a blanket override: a `200` from this
|
|
59
|
+
* pipeline means "the document rendered and nobody objected", which for this
|
|
60
|
+
* route is precisely the not-found case. Any other settled status is a real
|
|
61
|
+
* outcome that the page or the boundary decided — a 500 from a failed render,
|
|
62
|
+
* a redirect — and overwriting it would report a broken page as a missing one.
|
|
63
|
+
*/
|
|
64
|
+
statusForRenderedOk?: number;
|
|
65
|
+
/**
|
|
66
|
+
* Exclude the page module's loader from the request triple while preserving
|
|
67
|
+
* the real namespace for `register()` and rendering. Used only by the
|
|
68
|
+
* catch-all 404 page: a missing URL must not run application data work or
|
|
69
|
+
* turn a simple miss into a second failure path.
|
|
70
|
+
*/
|
|
71
|
+
skipPageLoader?: boolean;
|
|
72
|
+
/**
|
|
73
|
+
* Replays one committed cookie through core's `Response.cookie()`. Defaults
|
|
74
|
+
* to doing exactly that (`defaultApplyBufferedCookie`, above); injectable so
|
|
75
|
+
* a caller with a different `Response` shape (or a test) can observe/replace
|
|
76
|
+
* the call.
|
|
77
|
+
*/
|
|
78
|
+
applyBufferedCookie?: (response: Response, cookie: BufferedCookie) => void;
|
|
27
79
|
};
|
|
28
|
-
type PageRouteHandler = (context: HttpContext) => Promise<void>;
|
|
80
|
+
type PageRouteHandler = (context: HttpContext) => Promise<void | Response>;
|
|
29
81
|
//#endregion
|
|
30
82
|
export { PageModuleLoader, PageRouteHandler, PageRouteHandlerOptions };
|
|
31
83
|
//# sourceMappingURL=create-page-route-handler.d.mts.map
|