@warlock.js/web 5.1.0 → 5.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +174 -0
- package/README.md +126 -12
- package/esm/build/contribution.d.mts +11 -14
- package/esm/build/contribution.mjs +46 -58
- package/esm/build/contribution.mjs.map +1 -1
- package/esm/build/discover-pages.mjs +105 -45
- package/esm/build/discover-pages.mjs.map +1 -1
- package/esm/build/generate-client-registry.mjs +47 -13
- package/esm/build/generate-client-registry.mjs.map +1 -1
- package/esm/build/generate-pages-barrel.mjs +55 -13
- package/esm/build/generate-pages-barrel.mjs.map +1 -1
- package/esm/build/page-default-export.mjs +48 -0
- package/esm/build/page-default-export.mjs.map +1 -0
- package/esm/build/page-routes-manifest.mjs +21 -0
- package/esm/build/page-routes-manifest.mjs.map +1 -0
- package/esm/build/public-files.mjs +45 -0
- package/esm/build/public-files.mjs.map +1 -0
- package/esm/build/read-route-exports.mjs +1 -1
- package/esm/build/read-route-exports.mjs.map +1 -1
- package/esm/client/build-hydrated-tree.mjs +40 -9
- package/esm/client/build-hydrated-tree.mjs.map +1 -1
- package/esm/client/hydrate-page.mjs +1 -1
- package/esm/client/hydrate-page.mjs.map +1 -1
- package/esm/client/navigation/current-route.d.mts +1 -1
- package/esm/client/navigation/current-route.mjs +1 -1
- package/esm/client/navigation/current-route.mjs.map +1 -1
- package/esm/client/navigation/fetch-page-data.mjs +1 -1
- package/esm/client/navigation/fetch-page-data.mjs.map +1 -1
- package/esm/client/navigation/navigation-root.mjs +1 -1
- package/esm/client/navigation/navigation-root.mjs.map +1 -1
- package/esm/client/navigation/prefetch.mjs +1 -1
- package/esm/client/navigation/prefetch.mjs.map +1 -1
- package/esm/client/navigation/refresh.d.mts +1 -1
- package/esm/client/navigation/refresh.mjs +1 -1
- package/esm/client/navigation/refresh.mjs.map +1 -1
- package/esm/client/navigation/scroll-to-fragment.mjs +1 -1
- package/esm/client/navigation/scroll-to-fragment.mjs.map +1 -1
- package/esm/client/navigation/verbs.d.mts +1 -1
- package/esm/client/navigation/verbs.mjs +1 -1
- package/esm/client/navigation/verbs.mjs.map +1 -1
- package/esm/client/runtime/index.d.mts +2 -1
- package/esm/client/runtime/index.mjs +2 -1
- package/esm/client/runtime/manifest.d.mts +1 -1
- package/esm/client/runtime/manifest.mjs +3 -2
- package/esm/client/runtime/manifest.mjs.map +1 -1
- package/esm/client/runtime/matcher.d.mts +13 -1
- package/esm/client/runtime/matcher.mjs +13 -1
- package/esm/client/runtime/matcher.mjs.map +1 -1
- package/esm/client/runtime/types.d.mts +15 -2
- package/esm/components/default-app.mjs +1 -1
- package/esm/components/default-app.mjs.map +1 -1
- package/esm/components/document-context.d.mts +40 -2
- package/esm/components/document-context.mjs +1 -1
- package/esm/components/document-context.mjs.map +1 -1
- package/esm/components/head.d.mts +1 -1
- package/esm/components/head.mjs +1 -1
- package/esm/components/head.mjs.map +1 -1
- package/esm/components/link.d.mts +1 -1
- package/esm/components/link.mjs +1 -1
- package/esm/components/link.mjs.map +1 -1
- package/esm/components/scripts.d.mts +1 -1
- package/esm/components/scripts.mjs +4 -2
- package/esm/components/scripts.mjs.map +1 -1
- package/esm/context.d.mts +6 -102
- package/esm/hydration/index.mjs +1 -1
- package/esm/hydration/index.mjs.map +1 -1
- package/esm/hydration-payload.d.mts +1 -1
- package/esm/hydration-payload.mjs +37 -8
- package/esm/hydration-payload.mjs.map +1 -1
- package/esm/index.d.mts +4 -3
- package/esm/loaders.d.mts +7 -36
- package/esm/metadata.d.mts +1 -1
- package/esm/metadata.mjs +1 -1
- package/esm/metadata.mjs.map +1 -1
- package/esm/props.d.mts +16 -8
- package/esm/route.d.mts +2 -17
- package/esm/routing/compose-route-path.d.mts +1 -1
- package/esm/routing/compose-route-path.mjs +1 -1
- package/esm/routing/compose-route-path.mjs.map +1 -1
- package/esm/routing/data-request.mjs +1 -1
- package/esm/routing/data-request.mjs.map +1 -1
- package/esm/routing/filesystem-route.mjs +45 -0
- package/esm/routing/filesystem-route.mjs.map +1 -0
- package/esm/routing/layout-policy.mjs +1 -1
- package/esm/routing/layout-policy.mjs.map +1 -1
- package/esm/routing/navigator.mjs +1 -1
- package/esm/routing/navigator.mjs.map +1 -1
- package/esm/routing/query-string.d.mts +1 -1
- package/esm/routing/query-string.mjs +1 -1
- package/esm/routing/query-string.mjs.map +1 -1
- package/esm/routing/route-identity.mjs +1 -1
- package/esm/routing/route-identity.mjs.map +1 -1
- package/esm/routing/route-table.d.mts +1 -1
- package/esm/routing/route-table.mjs +1 -1
- package/esm/routing/route-table.mjs.map +1 -1
- package/esm/routing/router-events.d.mts +1 -1
- package/esm/routing/router-events.mjs +1 -1
- package/esm/routing/router-events.mjs.map +1 -1
- package/esm/routing/url-fragment.mjs +1 -1
- package/esm/routing/url-fragment.mjs.map +1 -1
- package/esm/runtime/register-modules.d.mts +19 -0
- package/esm/runtime/register-modules.mjs +22 -0
- package/esm/runtime/register-modules.mjs.map +1 -0
- package/esm/server/build-hydration-payload.mjs +2 -1
- package/esm/server/build-hydration-payload.mjs.map +1 -1
- package/esm/server/client-asset-url-prefix.d.mts +1 -1
- package/esm/server/client-asset-url-prefix.mjs +1 -1
- package/esm/server/client-asset-url-prefix.mjs.map +1 -1
- package/esm/server/create-page-module-loader.d.mts +1 -1
- package/esm/server/create-page-module-loader.mjs +2 -1
- package/esm/server/create-page-module-loader.mjs.map +1 -1
- package/esm/server/create-page-route-handler.d.mts +31 -6
- package/esm/server/create-page-route-handler.mjs +128 -43
- package/esm/server/create-page-route-handler.mjs.map +1 -1
- package/esm/server/dev-server.mjs +2 -13
- package/esm/server/dev-server.mjs.map +1 -1
- package/esm/server/error-page.d.mts +14 -0
- package/esm/server/error-page.mjs +39 -0
- package/esm/server/error-page.mjs.map +1 -0
- package/esm/server/execute-page-request.d.mts +7 -4
- package/esm/server/execute-page-request.mjs +79 -80
- package/esm/server/execute-page-request.mjs.map +1 -1
- package/esm/server/execute-page-request.types.d.mts +33 -92
- package/esm/server/hydration-client-url.d.mts +1 -1
- package/esm/server/hydration-client-url.mjs +2 -2
- package/esm/server/hydration-client-url.mjs.map +1 -1
- package/esm/server/index.d.mts +5 -5
- package/esm/server/index.mjs +3 -4
- package/esm/server/install-page-routes-from-manifest.d.mts +17 -7
- package/esm/server/install-page-routes-from-manifest.mjs +71 -10
- package/esm/server/install-page-routes-from-manifest.mjs.map +1 -1
- package/esm/server/install-page-routes.d.mts +32 -15
- package/esm/server/install-page-routes.mjs +91 -39
- package/esm/server/install-page-routes.mjs.map +1 -1
- package/esm/server/install-production-page-routes.mjs +3 -36
- package/esm/server/install-production-page-routes.mjs.map +1 -1
- package/esm/server/match-page-route.mjs +2 -2
- package/esm/server/match-page-route.mjs.map +1 -1
- package/esm/server/not-found-page.d.mts +1 -1
- package/esm/server/not-found-page.mjs +2 -2
- package/esm/server/not-found-page.mjs.map +1 -1
- package/esm/server/page-context.d.mts +3 -9
- package/esm/server/page-context.mjs +3 -16
- package/esm/server/page-context.mjs.map +1 -1
- package/esm/server/page-file-change.mjs +77 -0
- package/esm/server/page-file-change.mjs.map +1 -0
- package/esm/server/page-manifest.d.mts +25 -10
- package/esm/server/page-manifest.mjs +1 -1
- package/esm/server/page-manifest.mjs.map +1 -1
- package/esm/server/page-render-bundle.mjs +38 -0
- package/esm/server/page-render-bundle.mjs.map +1 -0
- package/esm/server/page-route-reload.mjs +54 -0
- package/esm/server/page-route-reload.mjs.map +1 -0
- package/esm/server/register-production-public-files.mjs +40 -0
- package/esm/server/register-production-public-files.mjs.map +1 -0
- package/esm/server/render-page.d.mts +11 -14
- package/esm/server/render-page.mjs +154 -28
- package/esm/server/render-page.mjs.map +1 -1
- package/esm/server/resolve-page-metadata.mjs +2 -2
- package/esm/server/resolve-page-metadata.mjs.map +1 -1
- package/esm/server/resolve-validation-data.mjs +1 -1
- package/esm/server/resolve-validation-data.mjs.map +1 -1
- package/esm/server/settle-page-response.d.mts +58 -1
- package/esm/server/settle-page-response.mjs +111 -46
- package/esm/server/settle-page-response.mjs.map +1 -1
- package/esm/server/stylesheet-urls.d.mts +41 -30
- package/esm/server/stylesheet-urls.mjs +137 -52
- package/esm/server/stylesheet-urls.mjs.map +1 -1
- package/esm/server/unregistered-pages.mjs +42 -0
- package/esm/server/unregistered-pages.mjs.map +1 -0
- package/esm/server/web-connector-factory.d.mts +2 -3
- package/esm/server/web-connector-factory.mjs +7 -6
- package/esm/server/web-connector-factory.mjs.map +1 -1
- package/esm/server/web-connector.d.mts +1 -1
- package/esm/server/web-connector.mjs +138 -18
- package/esm/server/web-connector.mjs.map +1 -1
- package/esm/shared.d.mts +18 -3
- package/esm/shared.mjs +3 -7
- package/esm/shared.mjs.map +1 -1
- package/esm/validation.d.mts +1 -1
- package/esm/vite/app-convention-aliases.mjs +1 -1
- package/esm/vite/app-convention-aliases.mjs.map +1 -1
- package/esm/vite/build-client.d.mts +1 -1
- package/esm/vite/build-client.mjs +2 -2
- package/esm/vite/build-client.mjs.map +1 -1
- package/esm/vite/gate-a-resolve.d.mts +1 -1
- package/esm/vite/gate-a-resolve.mjs +67 -13
- package/esm/vite/gate-a-resolve.mjs.map +1 -1
- package/esm/vite/gate-b-secrets.d.mts +1 -1
- package/esm/vite/gate-b-secrets.mjs +35 -17
- package/esm/vite/gate-b-secrets.mjs.map +1 -1
- package/esm/vite/gate-c-verify.d.mts +1 -1
- package/esm/vite/gate-c-verify.mjs +6 -6
- package/esm/vite/gate-c-verify.mjs.map +1 -1
- package/esm/vite/hydration-entries.d.mts +1 -1
- package/esm/vite/hydration-entries.mjs +2 -2
- package/esm/vite/hydration-entries.mjs.map +1 -1
- package/esm/vite/index.d.mts +9 -6
- package/esm/vite/index.mjs +124 -11
- package/esm/vite/index.mjs.map +1 -1
- package/esm/vite/page-registry-plugin.d.mts +22 -3
- package/esm/vite/page-registry-plugin.mjs +48 -14
- package/esm/vite/page-registry-plugin.mjs.map +1 -1
- package/esm/vite/projection.d.mts +2 -2
- package/esm/vite/projection.mjs +38 -15
- package/esm/vite/projection.mjs.map +1 -1
- package/llms-full.txt +220 -56
- package/llms.txt +5 -3
- package/package.json +3 -3
- package/skills/add-web-to-an-app/SKILL.md +3 -3
- package/skills/create-a-page/SKILL.md +117 -10
- package/skills/load-page-data/SKILL.md +92 -12
- package/skills/navigate-on-the-client/SKILL.md +1 -1
- package/skills/serve-styles/SKILL.md +13 -12
- package/skills/use-layouts/SKILL.md +14 -8
- package/skills/write-the-root/SKILL.md +3 -1
- package/esm/server/buffered-response.d.mts +0 -58
- package/esm/server/buffered-response.mjs +0 -115
- package/esm/server/buffered-response.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"install-page-routes.mjs","names":[],"sources":["../../../../../../../web/src/server/install-page-routes.ts"],"sourcesContent":["/**\r\n * Registers every page {@link discoverPageFiles} finds under `<appSrcRoot>`\r\n * into Warlock's router (`router.get`, `core/src/router/router.ts:359-361`)\r\n * so `router.scanDevServer(fastify)` —\r\n * the sanctioned dev-server dispatch path (server matching is Warlock's\r\n * router; there is no second server matcher) — picks\r\n * it up. Replaces the two hand-rolled `fastify.get()` calls this file's\r\n * sibling, `dev-server.ts`, used to make directly.\r\n *\r\n * DELIBERATE EXCEPTION to \"web has no core dependency\", same\r\n * reasoning `dev-server.ts`'s own header comment records: this module is not\r\n * exported from either package barrel and is not part of `web/package.json`'s\r\n * dependency graph — dev/CLI bootstrap only.\r\n *\r\n * Scope note: a page's\r\n * `route.path` is now composed with the `prefix` export of EVERY `layout.tsx`\r\n * on its path — outermost first (`composeRoutePath` below) — before\r\n * registration and before the collision check, so `home.page.tsx`\r\n * (`path: \"/\"`, main layout `prefix: \"/\"`) resolves to `/` and\r\n * `products.page.tsx` (`path: \"/\"`, products layout `prefix: \"/products\"`)\r\n * resolves to `/products` — no collision. A page with no `layout.tsx` on its\r\n * path composes against the implicit root prefix `\"/\"` (e.g. `/contact-us`,\r\n * `/hydration-demo`, both unaffected by composition).\r\n *\r\n * WHICH PAGES EXIST is answered by {@link discoverPageFiles}\r\n * (`web/src/build/discover-pages.ts`) — the same walk production's build\r\n * shares — so this file owns no directory-walking of its own and serves the\r\n * global root (`<appSrcRoot>/web/**`) exactly as it serves a module's\r\n * (`<appSrcRoot>/app/<module>/web/**`). WHAT ROUTE A PAGE ANSWERS ON stays\r\n * this file's own job: each page and its nearest layout are still evaluated\r\n * through Vite (`vite.ssrLoadModule`), never read statically, because a dev\r\n * page module must be the one Vite serves, warm cache and all.\r\n */\r\nimport path from \"node:path\";\r\nimport type { ViteDevServer } from \"vite\";\r\nimport {\r\n discoverPageFiles,\r\n layoutChainFor,\r\n MissingRouteExportError,\r\n toPosix,\r\n} from \"../build/discover-pages\";\r\nimport { composeRoutePath } from \"../routing/compose-route-path\";\r\nimport { NestedLayoutsNotSupportedError, selectPageLayout } from \"../routing/layout-policy\";\r\nimport { canonicalizeRouteExport, deriveFallbackRouteName } from \"../routing/route-identity\";\r\nimport { publishRouteTable } from \"../routing/route-table\";\r\nimport type { Response, Router } from \"@warlock.js/core\";\r\nimport type { BufferedCookie } from \"./buffered-response\";\r\nimport { createPageRouteHandler } from \"./create-page-route-handler\";\r\nimport type { PipelineMiddleware } from \"./execute-page-request\";\r\nimport {\r\n createNotFoundRouteHandler,\r\n DuplicateNotFoundPageError,\r\n isNotFoundPageFile,\r\n NotFoundPageDeclaresRouteError,\r\n NOT_FOUND_ROUTE_NAME,\r\n NOT_FOUND_ROUTE_PATH,\r\n type RegisteredRouteShape,\r\n} from \"./not-found-page\";\r\n\r\n/** Re-exported so `web/src/server/index.ts`'s existing barrel export keeps resolving. */\r\nexport { composeRoutePath };\r\n\r\nexport type PageRouteExport = string | { path: string; name?: string };\r\n\r\nexport type PageModuleShape = {\r\n route?: PageRouteExport;\r\n};\r\n\r\nexport type InstalledPageRoute = {\r\n path: string;\r\n name: string;\r\n file: string;\r\n layoutFile: string | undefined;\r\n};\r\n\r\n/**\r\n * The page's app-root-relative POSIX source path, e.g.\r\n * \".../v5/app/src/app/main/web/home.page.tsx\" with appSrcRoot\r\n * \".../v5/app/src\" -> \"src/app/main/web/home.page.tsx\" — the canonical form\r\n * `deriveFallbackRouteName` (`../routing/route-identity`) requires. The first\r\n * segment's actual name is arbitrary to that function (it only inspects the\r\n * segment AFTER it), so `appSrcRoot`'s own basename is used rather than\r\n * discovering the true app root.\r\n */\r\nfunction canonicalSourceFileFor(pageFile: string, appSrcRoot: string): string {\r\n return `${path.basename(appSrcRoot)}/${toPosix(path.relative(appSrcRoot, pageFile))}`;\r\n}\r\n\r\nfunction resolveRoute(\r\n routeExport: PageRouteExport,\r\n sourceFile: string,\r\n): { path: string; name: string } {\r\n const canonical = canonicalizeRouteExport(routeExport);\r\n\r\n return {\r\n path: canonical.path,\r\n name: canonical.name ?? deriveFallbackRouteName({ routePath: canonical.path, sourceFile }),\r\n };\r\n}\r\n\r\nexport type LayoutModuleShape = {\r\n prefix?: string;\r\n /**\r\n * The default export — the thing that puts an element in the document, and\r\n * therefore the ONLY export that decides whether a layout counts against the\r\n * single-rendering-layout rule (`../routing/layout-policy.ts`). In dev the\r\n * module is loaded, so this is a fact rather than a guess.\r\n */\r\n default?: unknown;\r\n /** The layout's guards, in the order it declared them. */\r\n middleware?: readonly PipelineMiddleware[];\r\n};\r\n\r\n/** How this module gets a layout module namespace — `vite.ssrLoadModule`, in practice. */\r\ntype LoadLayout = (layoutFile: string) => Promise<LayoutModuleShape>;\r\n\r\n/**\r\n * The page's layout LEVEL, resolved from its whole chain rather than from the\r\n * one layout nearest to it.\r\n *\r\n * The render pipeline has exactly one layout slot per page\r\n * (`execute-page-request.ts`'s `PageRouteEntry[\"triple\"]`), so the chain has to\r\n * be collapsed into one module before it reaches a handler. Two things collapse\r\n * differently and both matter:\r\n *\r\n * - RENDERING is a selection: at most one layout on the chain may render, and\r\n * the policy picks it. `renders` is read off the loaded module\r\n * (`typeof module.default !== \"undefined\"`), never off the filename — a\r\n * `middleware`-only layout has no default export and is not a wrapper, and\r\n * passing a bare path to `selectPageLayout` would have it read as a rendering\r\n * one, which is the conservative default and the wrong answer here.\r\n * - MIDDLEWARE and PREFIX are compositions: every layout on the path\r\n * contributes, outermost first. A guard on an outer layout that the page's\r\n * own directory knows nothing about is exactly the guard that must still run,\r\n * and a prefix nobody composed is a URL nobody wrote down.\r\n */\r\ntype LayoutLevel = {\r\n /** Every `layout.tsx` from the web root down to the page's directory, outermost first. */\r\n chain: string[];\r\n /**\r\n * The module id the handler's layout slot is registered under, or `undefined`\r\n * when the page has no layout at all: the layout that RENDERS, or — when none\r\n * does — the nearest one, which is the slot dev has always used and so the\r\n * choice that changes nothing but the middleware for a chain with no wrapper\r\n * in it.\r\n */\r\n layoutFile: string | undefined;\r\n /** Every layout's `prefix`, composed outermost first — `discoverPages`' own reduction. */\r\n prefix: string;\r\n};\r\n\r\nasync function resolveLayoutLevel(\r\n pageFile: string,\r\n webRoot: string,\r\n loadLayout: LoadLayout,\r\n): Promise<LayoutLevel> {\r\n const chain = layoutChainFor(pageFile, webRoot);\r\n const modules = await Promise.all(chain.map(loadLayout));\r\n const selection = selectPageLayout(\r\n chain.map((layout, index) => ({\r\n layout,\r\n renders: typeof modules[index].default !== \"undefined\",\r\n })),\r\n );\r\n\r\n if (selection.type === \"rejected\") {\r\n throw new NestedLayoutsNotSupportedError(pageFile, selection.layouts);\r\n }\r\n\r\n return {\r\n chain,\r\n layoutFile: selection.type === \"selected\" ? selection.layout : chain.at(-1),\r\n prefix: modules.reduce(\r\n (composed, layoutModule) => composeRoutePath(composed, layoutModule.prefix ?? \"/\"),\r\n \"/\",\r\n ),\r\n };\r\n}\r\n\r\n/**\r\n * The layout slot's module for ONE request: the slot host's own namespace, with\r\n * the whole chain's middleware in place of its own — outermost first, which is\r\n * the order stage 3 runs the array in (`execute-page-request.ts:519-524`) and\r\n * the order an outer `optionalAuth` needs in order to have resolved an identity\r\n * before an inner `gate()` checks it.\r\n *\r\n * Loaded per call, not once at install time: a dev layout module must be the\r\n * one Vite is currently serving, edits and all.\r\n */\r\nasync function composeLayoutLevel(\r\n level: LayoutLevel & { layoutFile: string },\r\n loadLayout: LoadLayout,\r\n): Promise<LayoutModuleShape> {\r\n const modules = await Promise.all(level.chain.map(loadLayout));\r\n const host = modules[level.chain.indexOf(level.layoutFile)];\r\n\r\n return {\r\n ...host,\r\n middleware: modules.flatMap(layoutModule => [...(layoutModule.middleware ?? [])]),\r\n };\r\n}\r\n\r\nexport type InstallPageRoutesOptions = {\r\n router: Router;\r\n vite: ViteDevServer;\r\n /** v5/app/src — pages live under \"<appSrcRoot>/app/*\\/web/**\" and \"<appSrcRoot>/web/**\". */\r\n appSrcRoot: string;\r\n /** v5/app/src/web/root.tsx — the single global app-root file. */\r\n appFile: string;\r\n /** Browser module loaded after the server-rendered application and payload. */\r\n hydrationClientModuleUrl?: string;\r\n /**\r\n * Stylesheet URLs emitted into every page's `<head>`.\r\n *\r\n * In dev these are Vite source URLs; see `devStylesheetUrls` for why they\r\n * carry `?direct`.\r\n */\r\n stylesheetUrls?: readonly string[];\r\n /** Same helper `dev-server.ts` exports — passed in, not imported, to avoid a dev-server.ts <-> this-file cycle. */\r\n applyBufferedCookie: (response: Response, cookie: BufferedCookie) => void;\r\n};\r\n\r\n/**\r\n * Registers every discoverable page into `options.router`. Throws\r\n * IMMEDIATELY, naming both files, the moment two pages declare the same\r\n * `route.path` — a registration-time failure, not a runtime 404 one of them\r\n * silently loses.\r\n *\r\n * Pages with no `route` export are REFUSED, not skipped, with the same\r\n * `MissingRouteExportError` the build throws: discovery cannot invent a public\r\n * URL for an undeclared page, and a dev server that silently drops the file you\r\n * just wrote is indistinguishable from a typo in the URL.\r\n */\r\nexport async function installPageRoutes(\r\n options: InstallPageRoutesOptions,\r\n): Promise<InstalledPageRoute[]> {\r\n const {\r\n router,\r\n vite,\r\n appSrcRoot,\r\n appFile,\r\n hydrationClientModuleUrl,\r\n stylesheetUrls,\r\n applyBufferedCookie,\r\n } = options;\r\n const discovered = [...discoverPageFiles(appSrcRoot)].sort((left, right) =>\r\n left.pageFile < right.pageFile ? -1 : left.pageFile > right.pageFile ? 1 : 0,\r\n );\r\n\r\n // THE NOT-FOUND PAGE IS TAKEN OUT OF THE ORDINARY LOOP, not filtered inside\r\n // it. It has no `route` export to read, no path to compose and no collision\r\n // to check — every step below is about a page with a URL, and `404.page.tsx`\r\n // does not have one. Registering it here would put it at `/404`, which is not\r\n // a page anybody asked to be able to visit.\r\n const notFoundPageFiles = discovered.filter((page) => isNotFoundPageFile(page.pageFile));\r\n const pageFiles = discovered.filter((page) => !isNotFoundPageFile(page.pageFile));\r\n\r\n if (notFoundPageFiles.length > 1) {\r\n throw new DuplicateNotFoundPageError(notFoundPageFiles.map((page) => page.pageFile));\r\n }\r\n\r\n const installed: InstalledPageRoute[] = [];\r\n const fileByPath = new Map<string, string>();\r\n\r\n for (const { pageFile, webRoot } of pageFiles) {\r\n const pageModule = (await vite.ssrLoadModule(pageFile)) as PageModuleShape;\r\n\r\n const sourceFile = canonicalSourceFileFor(pageFile, appSrcRoot);\r\n\r\n // Same condition, same error, same wording the build already throws\r\n // (`MissingRouteExportError`, `web/src/build/discover-pages.ts`) — dev used\r\n // to `continue` here, so a page you had just written vanished into a\r\n // not-found with nothing said. One condition, one verdict.\r\n if (pageModule.route === undefined) {\r\n throw new MissingRouteExportError(sourceFile);\r\n }\r\n\r\n const { path: routePath, name } = resolveRoute(pageModule.route, sourceFile);\r\n\r\n const loadLayout: LoadLayout = layoutFile =>\r\n vite.ssrLoadModule(layoutFile) as Promise<LayoutModuleShape>;\r\n const layoutLevel = await resolveLayoutLevel(pageFile, webRoot, loadLayout);\r\n const { layoutFile, prefix: layoutPrefix } = layoutLevel;\r\n\r\n const effectivePath = composeRoutePath(layoutPrefix, routePath);\r\n\r\n const existingFile = fileByPath.get(effectivePath);\r\n\r\n if (existingFile) {\r\n throw new Error(\r\n `installPageRoutes: composed route path \"${effectivePath}\" (layout ` +\r\n `prefix \"${layoutPrefix}\" + route.path \"${routePath}\") is declared by two ` +\r\n `pages (web/src/server/install-page-routes.ts) — \"${existingFile}\" and ` +\r\n `\"${pageFile}\". Every page's composed route path must be unique.`,\r\n );\r\n }\r\n\r\n fileByPath.set(effectivePath, pageFile);\r\n\r\n router.get(\r\n effectivePath,\r\n // The handler itself is `createPageRouteHandler`\r\n // (`web/src/server/create-page-route-handler.ts`) — a named seam a\r\n // future `type: \"page\"` route can bind to, and testable without a Vite\r\n // server. Vite appears here only as the dev answer to \"how do I load a\r\n // module\"; the handler takes that as an input and knows nothing else\r\n // about it.\r\n createPageRouteHandler({\r\n path: effectivePath,\r\n name,\r\n appFile,\r\n pageFile,\r\n layoutFile,\r\n // The layout slot's id resolves to the COMPOSED level — every layout's\r\n // middleware, in chain order — and every other id goes straight to\r\n // Vite. A one-layout chain has nothing to compose, so it is left to\r\n // resolve as the exact module Vite hands back, untouched.\r\n loadModule:\r\n layoutLevel.chain.length > 1 && layoutFile !== undefined\r\n ? moduleId =>\r\n moduleId === layoutFile\r\n ? composeLayoutLevel({ ...layoutLevel, layoutFile }, loadLayout)\r\n : vite.ssrLoadModule(moduleId)\r\n : moduleId => vite.ssrLoadModule(moduleId),\r\n hydrationClientModuleUrl,\r\n stylesheetUrls,\r\n applyBufferedCookie,\r\n }),\r\n // `isPage` marks this route as SSR-served. Pages and API routes share one\r\n // router and one route-name namespace, so the router's duplicate-name\r\n // error reads this flag to say which claimant is the page.\r\n { name, isPage: true },\r\n );\r\n\r\n installed.push({ path: effectivePath, name, file: pageFile, layoutFile });\r\n }\r\n\r\n /*\r\n THE CATCH-ALL, registered LAST and only when this application has a page\r\n surface at all. \"Configured with web, no pages yet\" is a legal state, and an\r\n application serving no pages has no page 404 to answer with — its unmatched\r\n URLs stay core's to answer, exactly as they are today.\r\n\r\n Registered even when the application ships no `404.page.tsx`: the framework\r\n default still answers 404, so an application that has not written one yet\r\n gets the right STATUS from the first request, and adding the file later\r\n changes the body and nothing else.\r\n */\r\n if (discovered.length > 0) {\r\n const notFoundPageFile = notFoundPageFiles[0]?.pageFile;\r\n\r\n // Read at INSTALL time, so a `route` export on the not-found page is\r\n // refused at boot with everything else — not on the first request that\r\n // misses, which is the one request nobody is watching.\r\n if (notFoundPageFile !== undefined) {\r\n const notFoundModule = (await vite.ssrLoadModule(notFoundPageFile)) as PageModuleShape;\r\n\r\n if (notFoundModule.route !== undefined) {\r\n throw new NotFoundPageDeclaresRouteError(notFoundPageFile);\r\n }\r\n }\r\n\r\n router.get(\r\n NOT_FOUND_ROUTE_PATH,\r\n createNotFoundRouteHandler({\r\n renderPage:\r\n notFoundPageFile === undefined\r\n ? undefined\r\n : createPageRouteHandler({\r\n path: NOT_FOUND_ROUTE_PATH,\r\n name: NOT_FOUND_ROUTE_NAME,\r\n appFile,\r\n pageFile: notFoundPageFile,\r\n // NO LAYOUT, deliberately, and it is the same trade as \"no\r\n // loader on the 404 page\": a layout brings its whole chain's\r\n // middleware with it, and a guard that redirects or throws on\r\n // the not-found path turns a missing page into an incident. The\r\n // page renders inside the application root and nothing else.\r\n layoutFile: undefined,\r\n loadModule: (moduleId) => vite.ssrLoadModule(moduleId),\r\n hydrationClientModuleUrl,\r\n stylesheetUrls,\r\n applyBufferedCookie,\r\n // The URL that missed IS this route's pattern for this request.\r\n matchPath: (requestPath) => requestPath,\r\n statusForRenderedOk: 404,\r\n }),\r\n }),\r\n // `isPage` for the same reason every other page route carries it: the\r\n // router's duplicate-name error reads the flag to say which claimant is\r\n // the page.\r\n { name: NOT_FOUND_ROUTE_NAME, isPage: true },\r\n );\r\n }\r\n\r\n /*\r\n Published from the SAME loop that registered the routes, so `href()` and the\r\n router cannot disagree about where a name points. It happens here rather\r\n than in the caller because a caller that forgets leaves every `<Link>` on\r\n the server throwing at render — and dev republishes on every restart, which\r\n is why the table replaces wholesale instead of merging: a deleted page's\r\n name has to stop resolving.\r\n */\r\n publishRouteTable(installed, \"installPageRoutes (dev)\");\r\n\r\n return installed;\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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ACA;EACF,CAAC,GAID;GAAE;GAAM,QAAQ;EAAK,CACvB;EAEA,UAAU,KAAK;GAAE,MAAM;GAAe;GAAM,MAAM;GAAU;EAAW,CAAC;CAC1E;CAaA,IAAI,WAAW,SAAS,GAAG;EACzB,MAAM,mBAAmB,kBAAkB,EAAE,EAAE;EAK/C,IAAI,qBAAqB,QAGvB;QAAI,MAF0B,KAAK,cAAc,gBAAgB,EAE/C,CAAC,UAAU,QAC3B,MAAM,IAAI,+BAA+B,gBAAgB;EAC3D;EAGF,OAAO,SAEL,2BAA2B,EACzB,YACE,qBAAqB,SACjB,SACA,uBAAuB;GACrB;GACA,MAAM;GACN;GACA,UAAU;GAMV,YAAY;GACZ,aAAa,aAAa,KAAK,cAAc,QAAQ;GACrD;GACA;GACA;GAEA,YAAY,gBAAgB;GAC5B,qBAAqB;EACvB,CAAC,EACT,CAAC,GAID;GAAE,MAAM;GAAsB,QAAQ;EAAK,CAC7C;CACF;CAUA,kBAAkB,WAAW,yBAAyB;CAEtD,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"install-page-routes.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/server/install-page-routes.ts"],"sourcesContent":["/**\r\n * Registers every page {@link discoverPageFiles} finds under `<appSrcRoot>`\r\n * into Warlock's router (`router.get`, `core/src/router/router.ts:359-361`)\r\n * so `router.scanDevServer(fastify)` —\r\n * the sanctioned dev-server dispatch path (server matching is Warlock's\r\n * router; there is no second server matcher) — picks\r\n * it up. Replaces the two hand-rolled `fastify.get()` calls this file's\r\n * sibling, `dev-server.ts`, used to make directly.\r\n *\r\n * DELIBERATE EXCEPTION to \"web has no core dependency\", same\r\n * reasoning `dev-server.ts`'s own header comment records: this module is not\r\n * exported from either package barrel and is not part of `web/package.json`'s\r\n * dependency graph — dev/CLI bootstrap only.\r\n *\r\n * Scope note: a page's\r\n * `route.path` is now composed with the `prefix` export of EVERY `layout.tsx`\r\n * on its path — outermost first (`composeRoutePath` below) — before\r\n * registration and before the collision check, so `home.page.tsx`\r\n * (`path: \"/\"`, main layout `prefix: \"/\"`) resolves to `/` and\r\n * `products.page.tsx` (`path: \"/\"`, products layout `prefix: \"/products\"`)\r\n * resolves to `/products` — no collision. A page with no `layout.tsx` on its\r\n * path composes against the implicit root prefix `\"/\"` (e.g. `/contact-us`,\r\n * `/hydration-demo`, both unaffected by composition).\r\n *\r\n * WHICH PAGES EXIST is answered by {@link discoverPageFiles}\r\n * (`web/src/build/discover-pages.ts`) — the same walk production's build\r\n * shares — so this file owns no directory-walking of its own and serves the\r\n * global root (`<appSrcRoot>/web/**`) exactly as it serves a module's\r\n * (`<appSrcRoot>/app/<module>/web/**`). WHAT ROUTE A PAGE ANSWERS ON stays\r\n * this file's own job: each page and its nearest layout are still evaluated\r\n * through Vite (`vite.ssrLoadModule`), never read statically, because a dev\r\n * page module must be the one Vite serves, warm cache and all.\r\n */\r\nimport path from \"node:path\";\r\nimport type { ViteDevServer } from \"vite\";\r\nimport {\r\n discoverPageFiles,\r\n ErrorPageDeclaresRouteError,\r\n isErrorPageFile,\r\n layoutChainFor,\r\n toPosix,\r\n} from \"../build/discover-pages\";\r\nimport { NonLiteralRouteExportError, readRouteExports } from \"../build/read-route-exports\";\r\nimport { composeRoutePath } from \"../routing/compose-route-path\";\r\nimport {\r\n deriveFilesystemRouteName,\r\n deriveFilesystemRoutePath,\r\n} from \"../routing/filesystem-route\";\r\nimport { NestedLayoutsNotSupportedError, selectPageLayout } from \"../routing/layout-policy\";\r\nimport { canonicalizeRouteExport } from \"../routing/route-identity\";\r\nimport { publishRouteTable } from \"../routing/route-table\";\r\nimport { Response, type Router } from \"@warlock.js/core\";\r\nimport { createPageRouteHandler } from \"./create-page-route-handler\";\r\nimport type { ErrorPageModule } from \"./error-page\";\r\nimport type { PipelineLoader, PipelineMiddleware } from \"./execute-page-request\";\nimport { isLoaderShortCircuit } from \"./settle-page-response\";\nimport { devHandlerStylesheetUrls } from \"./stylesheet-urls\";\r\nimport {\r\n createNotFoundRouteHandler,\r\n DuplicateNotFoundPageError,\r\n isNotFoundPageFile,\r\n NotFoundPageDeclaresRouteError,\r\n NOT_FOUND_ROUTE_NAME,\r\n NOT_FOUND_ROUTE_PATH,\r\n type RegisteredRouteShape,\r\n} from \"./not-found-page\";\r\n\r\n/** Re-exported so `web/src/server/index.ts`'s existing barrel export keeps resolving. */\r\nexport { composeRoutePath };\r\n\r\nexport type PageRouteExport = string | { path: string; name?: string };\r\n\r\nexport type PageModuleShape = {\r\n route?: PageRouteExport;\r\n};\r\n\r\nexport type InstalledPageRoute = {\r\n /** The canonical declared route path, before layout-prefix composition. */\r\n declaredPath: string;\r\n path: string;\r\n name: string;\r\n file: string;\r\n layoutFile: string | undefined;\r\n};\r\n\r\n/**\r\n * Ownership key for the framework's fallback 404 route. A NUL-prefixed value\r\n * cannot be a real filesystem path, so it cannot collide with an app page's\r\n * canonical source-file key.\r\n */\r\nexport const FRAMEWORK_DEFAULT_NOT_FOUND_SOURCE_FILE = \"\\0warlock:framework-default-404\";\r\n\r\n/**\r\n * The page's application-source-relative POSIX source path used as the router's\r\n * stable ownership key. `appSrcRoot`'s own basename preserves the existing\r\n * `src/web/...` source-file convention.\r\n */\r\nfunction canonicalSourceFileFor(pageFile: string, appSrcRoot: string): string {\r\n return `${path.basename(appSrcRoot)}/${toPosix(path.relative(appSrcRoot, pageFile))}`;\r\n}\r\n\r\nfunction filesystemPageFileFor(pageFile: string, appSrcRoot: string): string {\r\n return toPosix(path.relative(path.join(appSrcRoot, \"web\"), pageFile));\r\n}\r\n\r\n/**\r\n * Resolve the stable identity used to distinguish a route-export edit from an\r\n * ordinary component-body edit. The declared path is retained before layout\r\n * composition so `/settings` under `/admin` compares with the next declared\r\n * `/settings`, not with the effective `/admin/settings` route.\r\n */\r\nexport function resolvePageRouteIdentity(\r\n routeExport: PageRouteExport | undefined,\r\n pageFile: string,\r\n appSrcRoot: string,\r\n): Pick<InstalledPageRoute, \"declaredPath\" | \"name\"> {\r\n const filesystemPageFile = filesystemPageFileFor(pageFile, appSrcRoot);\r\n\r\n if (routeExport === undefined) {\r\n return {\r\n declaredPath: deriveFilesystemRoutePath({ pageFile: filesystemPageFile }),\r\n name: deriveFilesystemRouteName(filesystemPageFile),\r\n };\r\n }\r\n\r\n const route = canonicalizeRouteExport(routeExport);\r\n\r\n return {\r\n declaredPath: route.path,\r\n name: route.name ?? deriveFilesystemRouteName(filesystemPageFile),\r\n };\r\n}\r\n\r\nexport type LayoutModuleShape = {\r\n /** Universal registration hook; invoked on this real namespace, never a composed wrapper. */\r\n register?: () => unknown;\r\n prefix?: string;\r\n /**\r\n * The default export — the thing that puts an element in the document, and\r\n * therefore the ONLY export that decides whether a layout counts against the\r\n * single-rendering-layout rule (`../routing/layout-policy.ts`). In dev the\r\n * module is loaded, so this is a fact rather than a guess.\r\n */\r\n default?: unknown;\r\n /** The layout's guards, in the order it declared them. */\r\n middleware?: readonly PipelineMiddleware[];\r\n loader?: PipelineLoader;\r\n};\r\n\r\n/** How this module gets a layout module namespace — `vite.ssrLoadModule`, in practice. */\r\ntype LoadLayout = (layoutFile: string) => Promise<LayoutModuleShape>;\r\n\r\n/**\r\n * The page's layout LEVEL, resolved from its whole chain rather than from the\r\n * one layout nearest to it.\r\n *\r\n * The render pipeline has exactly one layout slot per page\r\n * (`execute-page-request.ts`'s `PageRouteEntry[\"triple\"]`), so the chain has to\r\n * be collapsed into one module before it reaches a handler. Two things collapse\r\n * differently and both matter:\r\n *\r\n * - RENDERING is a selection: at most one layout on the chain may render, and\r\n * the policy picks it. `renders` is read off the loaded module\r\n * (`typeof module.default !== \"undefined\"`), never off the filename — a\r\n * `middleware`-only layout has no default export and is not a wrapper, and\r\n * passing a bare path to `selectPageLayout` would have it read as a rendering\r\n * one, which is the conservative default and the wrong answer here.\r\n * - MIDDLEWARE and PREFIX are compositions: every layout on the path\r\n * contributes, outermost first. A guard on an outer layout that the page's\r\n * own directory knows nothing about is exactly the guard that must still run,\r\n * and a prefix nobody composed is a URL nobody wrote down.\r\n */\r\ntype LayoutLevel = {\r\n /** Every `layout.tsx` from the web root down to the page's directory, outermost first. */\r\n chain: string[];\r\n /**\r\n * The module id the handler's layout slot is registered under, or `undefined`\r\n * when the page has no layout at all: the layout that RENDERS, or — when none\r\n * does — the nearest one, which is the slot dev has always used and so the\r\n * choice that changes nothing but the middleware for a chain with no wrapper\r\n * in it.\r\n */\r\n layoutFile: string | undefined;\r\n /** Every layout's `prefix`, composed outermost first — `discoverPages`' own reduction. */\r\n prefix: string;\r\n /** Declared prefixes keyed by layout directory relative to this page's web root. */\r\n prefixesByDirectory: Readonly<Record<string, string>>;\r\n};\r\n\r\nasync function resolveLayoutLevel(\r\n pageFile: string,\r\n webRoot: string,\r\n loadLayout: LoadLayout,\r\n): Promise<LayoutLevel> {\r\n const chain = layoutChainFor(pageFile, webRoot);\r\n const modules = await Promise.all(chain.map(loadLayout));\r\n const selection = selectPageLayout(\r\n chain.map((layout, index) => ({\r\n layout,\r\n renders: typeof modules[index].default !== \"undefined\",\r\n })),\r\n );\r\n\r\n if (selection.type === \"rejected\") {\r\n throw new NestedLayoutsNotSupportedError(pageFile, selection.layouts);\r\n }\r\n\r\n return {\r\n chain,\r\n layoutFile: selection.type === \"selected\" ? selection.layout : chain.at(-1),\r\n prefix: modules.reduce(\r\n (composed, layoutModule) => composeRoutePath(composed, layoutModule.prefix ?? \"/\"),\r\n \"/\",\r\n ),\r\n prefixesByDirectory: Object.fromEntries(\r\n chain.flatMap((layoutFile, index) => {\r\n const prefix = modules[index].prefix;\r\n\r\n return prefix === undefined\r\n ? []\r\n : [[toPosix(path.relative(webRoot, path.dirname(layoutFile))), prefix]];\r\n }),\r\n ),\r\n };\r\n}\r\n\r\n/**\r\n * The layout slot's module for ONE request: the slot host's own namespace, with\r\n * the whole chain's middleware in place of its own — outermost first, which is\r\n * the order stage 3 runs the array in (`execute-page-request.ts:519-524`) and\r\n * the order an outer `optionalAuth` needs in order to have resolved an identity\r\n * before an inner `gate()` checks it.\r\n *\r\n * Loaded per call, not once at install time: a dev layout module must be the\r\n * one Vite is currently serving, edits and all.\r\n */\r\nasync function composeLayoutLevel(\r\n level: LayoutLevel & { layoutFile: string },\r\n loadLayout: LoadLayout,\r\n): Promise<LayoutModuleShape> {\r\n const modules = await Promise.all(level.chain.map(loadLayout));\r\n const hostIndex = level.chain.indexOf(level.layoutFile);\r\n const host = modules[hostIndex];\r\n\r\n return {\r\n ...host,\r\n middleware: modules.flatMap(layoutModule => [...(layoutModule.middleware ?? [])]),\r\n loader: async (context) => {\r\n let hostData: unknown;\r\n\r\n for (let index = 0; index < modules.length; index++) {\r\n const value = await modules[index].loader?.(context);\r\n\r\n if (value instanceof Response || isLoaderShortCircuit(value)) return value;\n if (index === hostIndex) hostData = value;\r\n }\r\n\r\n return hostData;\r\n },\r\n };\r\n}\r\n\r\nexport type InstallPageRoutesOptions = {\r\n router: Router;\r\n vite: ViteDevServer;\r\n /** v5/app/src — pages live under \"<appSrcRoot>/app/*\\/web/**\" and \"<appSrcRoot>/web/**\". */\r\n appSrcRoot: string;\r\n /** v5/app/src/web/root.tsx — the single global app-root file. */\r\n appFile: string;\r\n /**\r\n * The application root Vite's dev server serves from — `dev-server.ts`'s\r\n * `paths.appRoot`, i.e. `<appRoot>/src === appSrcRoot` by default. Every\r\n * handler's stylesheet URLs are expressed relative to THIS, because that is\r\n * the root Vite's dev server actually resolves `/…` URLs against\r\n * (`stylesheet-urls.ts`'s `devStylesheetUrls`) — not `appSrcRoot`, which is\r\n * one directory level in.\r\n *\r\n * OPTIONAL and defaulted to `path.dirname(appSrcRoot)`: the caller that\r\n * wires dev boot (`web-connector.ts`) does not pass this field today, and\r\n * that default is exactly the relationship it constructs `appSrcRoot` from\r\n * (`appSrcRoot = path.join(appRoot, \"src\")`) — correct for every actual\r\n * deployment, and overridable by a caller with a non-default layout.\r\n */\r\n appRoot?: string;\r\n /** Browser module loaded after the server-rendered application and payload. */\r\n hydrationClientModuleUrl?: string;\r\n /**\r\n * UNUSED. Retained on this type only because `web-connector.ts` still builds\r\n * an options object naming it (`devStylesheetUrls(paths.appRoot,\r\n * paths.appFile)`, computed once for the whole application). Each handler\r\n * now computes its OWN stylesheet chain — `[root, ...outer-to-inner matched\r\n * layouts, page]`, via `devHandlerStylesheetUrls` — inside the registration\r\n * loop below, because a single application-wide list cannot express \"this\r\n * page's own CSS\" without also carrying every other page's.\r\n */\r\n stylesheetUrls?: readonly string[];\r\n /** Same helper `dev-server.ts` exports — passed in, not imported, to avoid a dev-server.ts <-> this-file cycle. */\r\n};\r\n\r\n/**\r\n * Registers every discoverable page into `options.router`. Throws\r\n * IMMEDIATELY, naming both files, the moment two pages declare the same\r\n * `route.path` — a registration-time failure, not a runtime 404 one of them\r\n * silently loses.\r\n *\r\n * Pages with no `route` export derive their path and name from their location\r\n * below `src/web`, using the same pure filesystem-routing helper as the build.\r\n */\r\nexport async function installPageRoutes(\r\n options: InstallPageRoutesOptions,\r\n): Promise<InstalledPageRoute[]> {\r\n const {\r\n router,\r\n vite,\r\n appSrcRoot,\r\n appFile,\r\n hydrationClientModuleUrl,\r\n } = options;\r\n // See `InstallPageRoutesOptions.appRoot` for why this default, not\r\n // `appSrcRoot` itself, is the root every handler's CSS is resolved against.\r\n const stylesheetRoot = options.appRoot ?? path.dirname(appSrcRoot);\r\n const discovered = [...discoverPageFiles(appSrcRoot)].sort((left, right) =>\r\n left.pageFile < right.pageFile ? -1 : left.pageFile > right.pageFile ? 1 : 0,\r\n );\r\n\r\n // THE NOT-FOUND PAGE IS TAKEN OUT OF THE ORDINARY LOOP, not filtered inside\r\n // it. It has no `route` export to read, no path to compose and no collision\r\n // to check — every step below is about a page with a URL, and `404.page.tsx`\r\n // does not have one. Registering it here would put it at `/404`, which is not\r\n // a page anybody asked to be able to visit.\r\n const errorPageFiles = discovered.filter((page) => isErrorPageFile(page.pageFile));\r\n const notFoundPageFiles = discovered.filter((page) => isNotFoundPageFile(page.pageFile));\r\n const pageFiles = discovered.filter(\r\n (page) => !isNotFoundPageFile(page.pageFile) && !isErrorPageFile(page.pageFile),\r\n );\r\n\r\n if (errorPageFiles.length > 1) {\r\n throw new Error(`Two error pages were found: ${errorPageFiles.map((page) => page.pageFile).join(\", \")}.`);\r\n }\r\n\r\n const errorPageFile = errorPageFiles[0]?.pageFile;\r\n\r\n // Parse only: the error boundary must remain lazy until a request actually\r\n // fails, while a route export is still rejected at install time.\r\n if (errorPageFile !== undefined) {\r\n const declarations = readRouteExports(errorPageFile);\r\n if (!declarations.ok) throw new NonLiteralRouteExportError(declarations.rejection);\r\n if (declarations.route !== undefined) throw new ErrorPageDeclaresRouteError(errorPageFile);\r\n }\r\n const loadErrorPage = errorPageFile === undefined\r\n ? undefined\r\n : () => vite.ssrLoadModule(errorPageFile) as Promise<ErrorPageModule>;\r\n\r\n if (notFoundPageFiles.length > 1) {\r\n throw new DuplicateNotFoundPageError(notFoundPageFiles.map((page) => page.pageFile));\r\n }\r\n\r\n const installed: InstalledPageRoute[] = [];\r\n const fileByPath = new Map<string, string>();\r\n\r\n for (const { pageFile, webRoot } of pageFiles) {\r\n const pageModule = (await vite.ssrLoadModule(pageFile)) as PageModuleShape;\r\n\r\n const sourceFile = canonicalSourceFileFor(pageFile, appSrcRoot);\r\n\r\n // Route identity is explicit when declared and filesystem-derived otherwise.\r\n const { declaredPath: routePath, name } = resolvePageRouteIdentity(\r\n pageModule.route,\r\n pageFile,\r\n appSrcRoot,\r\n );\r\n\r\n const loadLayout: LoadLayout = layoutFile =>\r\n vite.ssrLoadModule(layoutFile) as Promise<LayoutModuleShape>;\r\n const layoutLevel = await resolveLayoutLevel(pageFile, webRoot, loadLayout);\r\n const { layoutFile, prefix: layoutPrefix } = layoutLevel;\r\n\r\n const effectivePath = pageModule.route === undefined\r\n ? deriveFilesystemRoutePath({\r\n pageFile: filesystemPageFileFor(pageFile, appSrcRoot),\r\n layoutPrefixes: layoutLevel.prefixesByDirectory,\r\n })\r\n : composeRoutePath(layoutPrefix, routePath);\r\n\r\n const existingFile = fileByPath.get(effectivePath);\r\n\r\n if (existingFile) {\r\n throw new Error(\r\n `installPageRoutes: composed route path \"${effectivePath}\" (layout ` +\r\n `prefix \"${layoutPrefix}\" + route.path \"${routePath}\") is declared by two ` +\r\n `pages (web/src/server/install-page-routes.ts) — \"${existingFile}\" and ` +\r\n `\"${pageFile}\". Every page's composed route path must be unique.`,\r\n );\r\n }\r\n\r\n fileByPath.set(effectivePath, pageFile);\r\n\r\n // Every registered handler gets ITS OWN immutable, ordered, deduped CSS\r\n // chain: root, then every matched layout outer to inner\r\n // (`layoutLevel.chain`), then the page — the same order the render\r\n // pipeline loads that chain in, so cascade order matches load order.\r\n // Computed once here, at registration, not per request: dev re-registers\r\n // on every restart, so a stale chain cannot outlive the source edit that\r\n // changed it.\r\n const stylesheetUrls = devHandlerStylesheetUrls(stylesheetRoot, [\r\n appFile,\r\n ...layoutLevel.chain,\r\n pageFile,\r\n ]);\r\n\r\n await router.withSourceFile(sourceFile, () =>\r\n router.get(\r\n effectivePath,\r\n // The handler itself is `createPageRouteHandler`\r\n // (`web/src/server/create-page-route-handler.ts`) — a named seam a\r\n // future `type: \"page\"` route can bind to, and testable without a Vite\r\n // server. Vite appears here only as the dev answer to \"how do I load a\r\n // module\"; the handler takes that as an input and knows nothing else\r\n // about it.\r\n createPageRouteHandler({\r\n path: effectivePath,\r\n name,\r\n appFile,\r\n pageFile,\r\n layoutFile,\r\n // The layout slot's id resolves to the COMPOSED level — every layout's\r\n // middleware, in chain order — and every other id goes straight to\r\n // Vite. A one-layout chain has nothing to compose, so it is left to\r\n // resolve as the exact module Vite hands back, untouched.\r\n loadModule:\r\n layoutLevel.chain.length > 1 && layoutFile !== undefined\r\n ? moduleId =>\r\n moduleId === layoutFile\r\n ? composeLayoutLevel({ ...layoutLevel, layoutFile }, loadLayout)\r\n : vite.ssrLoadModule(moduleId)\r\n : moduleId => vite.ssrLoadModule(moduleId),\r\n // Registration tracks real module namespaces, not the composed\r\n // layout wrapper above. Loading the raw chain per request also lets\r\n // Vite hand over a replacement namespace after an HMR update; the\r\n // helper's WeakSet then gives that new identity its one invocation.\r\n loadRegistrationLayouts: () => Promise.all(layoutLevel.chain.map(loadLayout)),\r\n hydrationClientModuleUrl,\r\n loadErrorPage,\r\n stylesheetUrls,\r\n }),\r\n // `isPage` marks this route as SSR-served. Pages and API routes share one\r\n // router and one route-name namespace, so the router's duplicate-name\r\n // error reads this flag to say which claimant is the page.\r\n { name, isPage: true },\r\n ),\r\n );\r\n\r\n installed.push({\r\n declaredPath: routePath,\r\n path: effectivePath,\r\n name,\r\n file: pageFile,\r\n layoutFile,\r\n });\r\n }\r\n\r\n /*\r\n THE CATCH-ALL, registered LAST and only when this application has a page\r\n surface at all. \"Configured with web, no pages yet\" is a legal state, and an\r\n application serving no pages has no page 404 to answer with — its unmatched\r\n URLs stay core's to answer, exactly as they are today.\r\n\r\n Registered even when the application ships no `404.page.tsx`: the framework\r\n default still answers 404, so an application that has not written one yet\r\n gets the right STATUS from the first request, and adding the file later\r\n changes the body and nothing else.\r\n */\r\n if (pageFiles.length > 0 || notFoundPageFiles.length > 0) {\r\n const notFoundPageFile = notFoundPageFiles[0]?.pageFile;\r\n\r\n // Read at INSTALL time, so a `route` export on the not-found page is\r\n // refused at boot with everything else — not on the first request that\r\n // misses, which is the one request nobody is watching.\r\n if (notFoundPageFile !== undefined) {\r\n const notFoundModule = (await vite.ssrLoadModule(notFoundPageFile)) as PageModuleShape;\r\n\r\n if (notFoundModule.route !== undefined) {\r\n throw new NotFoundPageDeclaresRouteError(notFoundPageFile);\r\n }\r\n }\r\n\r\n const registerNotFoundRoute = () =>\r\n router.get(\r\n NOT_FOUND_ROUTE_PATH,\r\n createNotFoundRouteHandler({\r\n renderPage:\r\n notFoundPageFile === undefined\r\n ? undefined\r\n : createPageRouteHandler({\r\n path: NOT_FOUND_ROUTE_PATH,\r\n name: NOT_FOUND_ROUTE_NAME,\r\n appFile,\r\n pageFile: notFoundPageFile,\r\n // NO LAYOUT, deliberately, and it is the same trade as \"no\r\n // loader on the 404 page\": a layout brings its whole chain's\r\n // middleware with it, and a guard that redirects or throws on\r\n // the not-found path turns a missing page into an incident. The\r\n // page renders inside the application root and nothing else.\r\n layoutFile: undefined,\r\n loadModule: (moduleId) => vite.ssrLoadModule(moduleId),\r\n hydrationClientModuleUrl,\r\n loadErrorPage,\r\n // NO LAYOUT means no layout CSS either — just root and the\r\n // not-found page's own stylesheets, same reasoning as above.\r\n stylesheetUrls: devHandlerStylesheetUrls(stylesheetRoot, [\r\n appFile,\r\n notFoundPageFile,\r\n ]),\r\n // The URL that missed IS this route's pattern for this request.\r\n matchPath: (requestPath) => requestPath,\n statusForRenderedOk: 404,\n skipPageLoader: true,\n }),\n }),\r\n // `isPage` for the same reason every other page route carries it: the\r\n // router's duplicate-name error reads the flag to say which claimant is\r\n // the page.\r\n { name: NOT_FOUND_ROUTE_NAME, isPage: true },\r\n );\r\n\r\n if (notFoundPageFile === undefined) {\r\n await router.withSourceFile(FRAMEWORK_DEFAULT_NOT_FOUND_SOURCE_FILE, registerNotFoundRoute);\r\n } else {\r\n await router.withSourceFile(\r\n canonicalSourceFileFor(notFoundPageFile, appSrcRoot),\r\n registerNotFoundRoute,\r\n );\r\n }\r\n }\r\n\r\n /*\r\n Published from the SAME loop that registered the routes, so `href()` and the\r\n router cannot disagree about where a name points. It happens here rather\r\n than in the caller because a caller that forgets leaves every `<Link>` on\r\n the server throwing at render — and dev republishes on every restart, which\r\n is why the table replaces wholesale instead of merging: a deleted page's\r\n name has to stop resolving.\r\n */\r\n publishRouteTable(installed, \"installPageRoutes (dev)\");\r\n\r\n return installed;\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0FA,MAAa,0CAA0C;;;;;;AAOvD,SAAS,uBAAuB,UAAkB,YAA4B;CAC5E,OAAO,GAAG,KAAK,SAAS,UAAU,EAAE,GAAG,QAAQ,KAAK,SAAS,YAAY,QAAQ,CAAC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,KACjC,aAAY,KAAK,cAAc,QAAQ;GAK7C,+BAA+B,QAAQ,IAAI,YAAY,MAAM,IAAI,UAAU,CAAC;GAC5E;GACA;GACA;EACF,CAAC,GAID;GAAE;GAAM,QAAQ;EAAK,CACvB,CACF;EAEA,UAAU,KAAK;GACb,cAAc;GACd,MAAM;GACN;GACA,MAAM;GACN;EACF,CAAC;CACH;CAaA,IAAI,UAAU,SAAS,KAAK,kBAAkB,SAAS,GAAG;EACxD,MAAM,mBAAmB,kBAAkB,IAAI;EAK/C,IAAI,qBAAqB,QAGvB;QAAI,MAF0B,KAAK,cAAc,gBAAgB,GAE9C,UAAU,QAC3B,MAAM,IAAI,+BAA+B,gBAAgB;EAC3D;EAGF,MAAM,8BACJ,OAAO,SAEL,2BAA2B,EACzB,YACE,qBAAqB,SACjB,SACA,uBAAuB;GACrB;GACA,MAAM;GACN;GACA,UAAU;GAMV,YAAY;GACZ,aAAa,aAAa,KAAK,cAAc,QAAQ;GACrD;GACA;GAGA,gBAAgB,yBAAyB,gBAAgB,CACvD,SACA,gBACF,CAAC;GAED,YAAY,gBAAgB;GAC5B,qBAAqB;GACrB,gBAAgB;EAClB,CAAC,EACT,CAAC,GAID;GAAE,MAAM;GAAsB,QAAQ;EAAK,CAC7C;EAEF,IAAI,qBAAqB,QACvB,MAAM,OAAO,eAAe,yCAAyC,qBAAqB;OAE1F,MAAM,OAAO,eACX,uBAAuB,kBAAkB,UAAU,GACnD,qBACF;CAEJ;CAUA,kBAAkB,WAAW,yBAAyB;CAEtD,OAAO;AACT"}
|
|
@@ -1,35 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
//#region ../web/src/server/install-production-page-routes.ts
|
|
4
|
-
/**
|
|
5
|
-
* A manifest page whose module namespace carries no `route` export.
|
|
6
|
-
*
|
|
7
|
-
* Page discovery only emits a module it read a `route` off, so a valid build
|
|
8
|
-
* cannot produce this — a stale artifact or a hand-edited barrel can. The
|
|
9
|
-
* alternative to refusing it is a page table that silently shrinks: the
|
|
10
|
-
* operator gets a clean boot log and a 404 on a page that is demonstrably in
|
|
11
|
-
* the bundle, with nothing anywhere naming the file. The file is named here
|
|
12
|
-
* because it is the entire diagnosis.
|
|
13
|
-
*/
|
|
14
|
-
var PageManifestEntryMissingRouteError = class extends Error {
|
|
15
|
-
constructor(sourceFile) {
|
|
16
|
-
super(`Cannot serve pages: the page manifest entry for "${sourceFile}" has no \`route\` export, so it has no URL to be registered under. This build's generated \`pages.ts\` barrel does not match the sources it was generated from — re-run \`warlock build\`, and if the page is meant to be served, give it a \`route\` export.`);
|
|
17
|
-
this.name = "PageManifestEntryMissingRouteError";
|
|
18
|
-
}
|
|
19
|
-
};
|
|
20
|
-
/**
|
|
21
|
-
* Refuse the whole table before any of it is registered.
|
|
22
|
-
*
|
|
23
|
-
* Checked in one pass UP FRONT rather than per page inside the registration
|
|
24
|
-
* loop: a half-installed page table is worse than a refused boot, because it
|
|
25
|
-
* serves.
|
|
26
|
-
*/
|
|
27
|
-
function assertEveryPageDeclaresRoute(manifest) {
|
|
28
|
-
for (const page of manifest.pages) {
|
|
29
|
-
if (isNotFoundPageFile(page.sourceFile)) continue;
|
|
30
|
-
if (page.module.route === void 0) throw new PageManifestEntryMissingRouteError(page.sourceFile);
|
|
31
|
-
}
|
|
32
|
-
}
|
|
1
|
+
//#region web/src/server/install-production-page-routes.ts
|
|
33
2
|
/**
|
|
34
3
|
* Register every page the manifest carries, and connect the pipeline the
|
|
35
4
|
* handlers will run in.
|
|
@@ -40,8 +9,7 @@ function assertEveryPageDeclaresRoute(manifest) {
|
|
|
40
9
|
* it returns before doing either.
|
|
41
10
|
*/
|
|
42
11
|
async function installProductionPageRoutes(options) {
|
|
43
|
-
const { router, manifest, pageContext, sharedStore,
|
|
44
|
-
assertEveryPageDeclaresRoute(manifest);
|
|
12
|
+
const { router, manifest, pageContext, sharedStore, resolveHydrationClientModuleUrl, clientDir } = options;
|
|
45
13
|
if (manifest.pages.length === 0) return [];
|
|
46
14
|
const webServer = await import("./index.mjs");
|
|
47
15
|
webServer.connectSharedStore(sharedStore);
|
|
@@ -50,8 +18,7 @@ async function installProductionPageRoutes(options) {
|
|
|
50
18
|
router,
|
|
51
19
|
manifest,
|
|
52
20
|
hydrationClientModuleUrl: resolveHydrationClientModuleUrl(),
|
|
53
|
-
|
|
54
|
-
applyBufferedCookie
|
|
21
|
+
clientDir
|
|
55
22
|
});
|
|
56
23
|
}
|
|
57
24
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"install-production-page-routes.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"install-production-page-routes.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/server/install-production-page-routes.ts"],"sourcesContent":["/**\r\n * Standing up page serving for a BUILT application — the production half of\r\n * `WebConnector.boot()`, kept out of the connector so the mode branch there\r\n * stays one `if` and this path stays readable on its own.\r\n *\r\n * The development path answers \"which pages exist?\" by walking `app/` and\r\n * \"what is this module?\" by asking Vite to evaluate it. A production process\r\n * can ask neither question: there is no source tree beside the bundle and no\r\n * Vite. Both answers arrived at import time instead, in the generated pages\r\n * barrel's {@link PageManifest}, and everything below is what remains once\r\n * those two questions are already answered — a guard, a wiring step and a\r\n * registration step.\r\n *\r\n * NOTHING HERE REACHES FOR VITE, transitively included. `vite` is an optional\r\n * peer, so a production install does not carry it; an import that only ever\r\n * runs in development still fails at module load in production, which is why\r\n * the one import that has to happen at boot is a dynamic one and why it names\r\n * the pipeline barrel and nothing else.\r\n */\r\nimport type { Router } from \"@warlock.js/core\";\r\nimport type { SharedStoreResolver } from \"../shared\";\r\nimport type { PageContextRunner } from \"./execute-page-request\";\r\nimport type { InstalledManifestPageRoute } from \"./install-page-routes-from-manifest\";\r\nimport type { PageManifest } from \"./page-manifest\";\r\n\r\nexport type InstallProductionPageRoutesOptions = {\r\n router: Router;\r\n /** The table the generated production barrel provided at import time. */\r\n manifest: PageManifest;\r\n /**\r\n * Core's per-request context, handed over rather than imported: core is a\r\n * type-only peer of web, and two copies of core would mean two\r\n * AsyncLocalStorage stores and a page pipeline reading an empty one.\r\n */\r\n pageContext: PageContextRunner;\r\n /** Reads the current request's store out of {@link pageContext}. */\r\n sharedStore: SharedStoreResolver;\r\n /** Same helper `dev-server.ts` exports — passed in, never imported. */\r\n /**\r\n * Where the browser fetches the hydration entry from.\r\n *\r\n * A THUNK, not a value: the URL is read out of the client build's manifest,\r\n * and a build that discovered no pages has no hydration entry for that read\r\n * to find. Deferring it means a page-free production bundle boots without\r\n * demanding a file it had no reason to emit.\r\n */\r\n resolveHydrationClientModuleUrl: () => string;\r\n /**\r\n * Where the client build wrote its output. Forwarded to\r\n * `installPageRoutesFromManifest`, never read here: every registered\r\n * handler needs its OWN stylesheet chain\r\n * (`[root, ...outer-to-inner matched layouts, page]`), and the installer is\r\n * the one place that already walks the manifest's per-page layout chains to\r\n * build one.\r\n *\r\n * OPTIONAL for the same reason `PageManifest.clientDir` is: a build that\r\n * discovered zero pages emits no client bundle, so there is no directory to\r\n * name — and no page that could need a stylesheet either.\r\n */\r\n clientDir?: string;\r\n};\r\n\r\n/**\r\n * Register every page the manifest carries, and connect the pipeline the\r\n * handlers will run in.\r\n *\r\n * An empty table registers nothing and is not an error: \"built with web, no\r\n * pages\" is a legal state of a built application, and it is also the one state\r\n * where there is no pipeline to connect and no hydration entry to point at, so\r\n * it returns before doing either.\r\n */\r\nexport async function installProductionPageRoutes(\r\n options: InstallProductionPageRoutesOptions,\r\n): Promise<InstalledManifestPageRoute[]> {\r\n const {\r\n router,\r\n manifest,\r\n pageContext,\r\n sharedStore,\r\n resolveHydrationClientModuleUrl,\r\n clientDir,\r\n } = options;\r\n\r\n if (manifest.pages.length === 0) return [];\r\n\r\n // Loaded at boot rather than statically, and through the BARREL: production\r\n // has one module graph, so the barrel's instance of the pipeline is the same\r\n // instance the manifest's page modules were linked against, and connecting\r\n // the request context on it connects it for every handler registered below.\r\n // Development cannot do this — its modules live in Vite's separate graph, and\r\n // it wires the same two seams on the copy Vite evaluated.\r\n const webServer = await import(\"./index\");\r\n\r\n webServer.connectSharedStore(sharedStore);\r\n webServer.connectPageContext(pageContext);\r\n\r\n return webServer.installPageRoutesFromManifest({\r\n router,\r\n manifest,\r\n hydrationClientModuleUrl: resolveHydrationClientModuleUrl(),\r\n clientDir,\r\n });\r\n}\r\n"],"mappings":";;;;;;;;;;AAuEA,eAAsB,4BACpB,SACuC;CACvC,MAAM,EACJ,QACA,UACA,aACA,aACA,iCACA,cACE;CAEJ,IAAI,SAAS,MAAM,WAAW,GAAG,OAAO,CAAC;CAQzC,MAAM,YAAY,MAAM,OAAO;CAE/B,UAAU,mBAAmB,WAAW;CACxC,UAAU,mBAAmB,WAAW;CAExC,OAAO,UAAU,8BAA8B;EAC7C;EACA;EACA,0BAA0B,gCAAgC;EAC1D;CACF,CAAC;AACH"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//#region
|
|
1
|
+
//#region web/src/server/match-page-route.ts
|
|
2
2
|
/**
|
|
3
3
|
* Stage 1 — turn a URL into a route entry plus its params.
|
|
4
4
|
*
|
|
@@ -44,5 +44,5 @@ function matchRoute(pathname, routes) {
|
|
|
44
44
|
}
|
|
45
45
|
|
|
46
46
|
//#endregion
|
|
47
|
-
export { matchRoute };
|
|
47
|
+
export { matchPath, matchRoute };
|
|
48
48
|
//# sourceMappingURL=match-page-route.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"match-page-route.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"match-page-route.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/server/match-page-route.ts"],"sourcesContent":["import type { PageRouteEntry } from \"./execute-page-request.types\";\n\n/**\n * Stage 1 — turn a URL into a route entry plus its params.\n *\n * ⚠ **This is a SECOND matcher, and on the HTTP path it is redundant.** Core's\n * router has already matched by the time a page handler runs, and\n * `create-page-route-handler.ts` ignores the match it is handed. The one caller\n * that genuinely needs this is `renderPage(name, options)`, which synthesizes a\n * URL with no HTTP request behind it — and that path is not wired up\n * (`connectPageRoutes()` is never called).\n *\n * Removing it from the HTTP path is carded. Two things must be proven first:\n * that these params agree with core's, since `bundle.route.params` reaches the\n * hydration payload; and that dropping `bundle.route.query` — a public type\n * member — is announced rather than slipped in.\n */\n\nfunction splitSegments(path: string): string[] {\n return path.split(\"/\").filter(segment => segment.length > 0);\n}\n\nexport function matchPath(\n pattern: string,\n pathname: string,\n): Record<string, string> | undefined {\n const patternSegments = splitSegments(pattern);\n const pathSegments = splitSegments(pathname);\n\n if (patternSegments.length !== pathSegments.length) return undefined;\n\n const params: Record<string, string> = {};\n\n for (let index = 0; index < patternSegments.length; index++) {\n const patternSegment = patternSegments[index];\n const pathSegment = pathSegments[index];\n\n if (patternSegment.startsWith(\":\")) {\n params[patternSegment.slice(1)] = decodeURIComponent(pathSegment);\n continue;\n }\n\n if (patternSegment !== pathSegment) return undefined;\n }\n\n return params;\n}\n\nexport function matchRoute(\n pathname: string,\n routes: readonly PageRouteEntry[],\n): { entry: PageRouteEntry; params: Record<string, string> } | undefined {\n for (const entry of routes) {\n const params = matchPath(entry.path, pathname);\n\n if (params) return { entry, params };\n }\n\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAkBA,SAAS,cAAc,MAAwB;CAC7C,OAAO,KAAK,MAAM,GAAG,EAAE,QAAO,YAAW,QAAQ,SAAS,CAAC;AAC7D;AAEA,SAAgB,UACd,SACA,UACoC;CACpC,MAAM,kBAAkB,cAAc,OAAO;CAC7C,MAAM,eAAe,cAAc,QAAQ;CAE3C,IAAI,gBAAgB,WAAW,aAAa,QAAQ,OAAO;CAE3D,MAAM,SAAiC,CAAC;CAExC,KAAK,IAAI,QAAQ,GAAG,QAAQ,gBAAgB,QAAQ,SAAS;EAC3D,MAAM,iBAAiB,gBAAgB;EACvC,MAAM,cAAc,aAAa;EAEjC,IAAI,eAAe,WAAW,GAAG,GAAG;GAClC,OAAO,eAAe,MAAM,CAAC,KAAK,mBAAmB,WAAW;GAChE;EACF;EAEA,IAAI,mBAAmB,aAAa,OAAO;CAC7C;CAEA,OAAO;AACT;AAEA,SAAgB,WACd,UACA,QACuE;CACvE,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,SAAS,UAAU,MAAM,MAAM,QAAQ;EAE7C,IAAI,QAAQ,OAAO;GAAE;GAAO;EAAO;CACrC;AAGF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//#region
|
|
1
|
+
//#region web/src/server/not-found-page.ts
|
|
2
2
|
/**
|
|
3
3
|
* The one filename that makes a page THE not-found page.
|
|
4
4
|
*
|
|
@@ -148,7 +148,7 @@ function createNotFoundRouteHandler(options) {
|
|
|
148
148
|
await response.html(frameworkDefaultNotFoundDocument(), 404);
|
|
149
149
|
return;
|
|
150
150
|
}
|
|
151
|
-
|
|
151
|
+
return renderPage(context);
|
|
152
152
|
};
|
|
153
153
|
}
|
|
154
154
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"not-found-page.mjs","names":[],"sources":["../../../../../../../web/src/server/not-found-page.ts"],"sourcesContent":["/**\n * THE NOT-FOUND PATH — the one route in the application that answers for URLs\n * nobody declared.\n *\n * An application gets it by writing `404.page.tsx` anywhere under a web root.\n * The file is named for the status it answers with, not for a concept\n * (\"not-found\"), because `404` is the string people actually search for, and\n * the `*.page.tsx` suffix is what makes it a page in the first place.\n *\n * ── THE RULE THIS FILE EXISTS FOR ────────────────────────────────────────────\n *\n * Pages and API routes share ONE route namespace and ONE router. So a catch-all\n * page route sees every unmatched request in the process, including\n * `GET /api/uzers` — and if it renders a document for that, a `fetch()` gets\n * `<!doctype html>` back and dies inside `response.json()` with a SyntaxError\n * pointing at the parser instead of at the typo. That failure is expensive\n * precisely because the error names nothing near its cause.\n *\n * Because pages and API share one namespace there is no path-prefix rule\n * available: `/anything` may legitimately be either. The discriminator is\n * therefore the `Accept` header, and it is stated as a narrow permission rather\n * than a guess — the document is the exception, JSON is the default:\n *\n * A request renders the not-found PAGE only if\n * 1. its method is GET or HEAD, and\n * 2. `text/html` appears EXPLICITLY in its `Accept` header.\n *\n * (1) is not a heuristic about browsers. Pages are registered with\n * `router.get` and nothing else — every page route in this codebase is\n * installed by `installPageRoutes` / `installPageRoutesFromManifest`, both\n * of which call `router.get`. A `POST` therefore cannot have been meant\n * for a page, by construction. HEAD rides along because Fastify answers it\n * from the GET route.\n *\n * (2) is EXPLICIT and the word is load-bearing. A wildcard does NOT count:\n * `* /*` — what a bare `fetch()` sends — is not a request for a document,\n * it is the absence of a preference, and `text/*` claims a family rather\n * than the type. Only the literal `text/html` media range, with a non-zero\n * `q`, opens the page path. A browser address-bar navigation always sends\n * an explicit `text/html`; a `fetch()` that has not asked for one never\n * does. So the mistyped `/api/...` in a `fetch()` keeps its JSON body and\n * dies at the typo rather than inside `response.json()`.\n *\n * WHAT THE RULE CANNOT DECIDE, and does not pretend to: a browser navigating to\n * a typo'd API URL asks for `text/html`, and so is answered with the document.\n * Nothing in that request distinguishes it from a typo'd page URL — same verb,\n * same header, same absence of a match — so the rule does not guess. The status\n * is 404 either way, which is the part machines read.\n *\n * ── DEPENDENCY NOTE ──────────────────────────────────────────────────────────\n * This module has NO runtime imports. `../build/discover-pages` imports the\n * filename constant and the identity helpers from here so build discovery and\n * both installers cannot disagree about what a not-found page is, and that edge\n * must not drag the render pipeline into the build.\n */\nimport type { HttpContext } from \"@warlock.js/core\";\nimport type { PageRouteHandler } from \"./create-page-route-handler\";\n\n/**\n * The one filename that makes a page THE not-found page.\n *\n * `404.page.tsx`, not `not-found.page.tsx`: it keeps the `*.page.tsx`\n * convention every other page follows, and `404` is the token a developer\n * greps for when a URL answers with one.\n */\nexport const NOT_FOUND_PAGE_FILENAME = \"404.page.tsx\";\n\n/**\n * The path the not-found route is registered on — find-my-way's and Fastify's\n * catch-all, and the same literal core's own dev dispatcher registers\n * (`core/src/router/router.ts`, `server.route({ url: \"*\" })`).\n *\n * A catch-all has the LOWEST matching priority in both routers, so every\n * declared page and every declared API route still wins on its own path; this\n * route is only ever reached because nothing else claimed the URL.\n */\nexport const NOT_FOUND_ROUTE_PATH = \"*\";\n\n/**\n * The reserved route name the not-found page is registered under.\n *\n * Namespaced under `warlock.` because it is the framework's route rather than\n * the application's, and because the router's name namespace is shared with API\n * routes — an application that takes this name gets core's duplicate-name error,\n * which is the loud answer, not a silent overwrite.\n *\n * It is deliberately NOT published into the route table (`href()` / `<Link>`):\n * the not-found page has no URL of its own to link to.\n */\nexport const NOT_FOUND_ROUTE_NAME = \"warlock.not-found\";\n\n/** True when `sourceFile`'s basename is exactly {@link NOT_FOUND_PAGE_FILENAME}. */\nexport function isNotFoundPageFile(sourceFile: string): boolean {\n const separator = Math.max(sourceFile.lastIndexOf(\"/\"), sourceFile.lastIndexOf(\"\\\\\"));\n\n return sourceFile.slice(separator + 1) === NOT_FOUND_PAGE_FILENAME;\n}\n\n/**\n * Raised when more than one `404.page.tsx` exists.\n *\n * There is exactly one not-found route in a process, so a second file is not a\n * per-module override — it is two files claiming one route, with the winner\n * decided by directory-walk order. Both are named because the fix is to delete\n * one and the operator has to know which two are in play.\n */\nexport class DuplicateNotFoundPageError extends Error {\n public constructor(public readonly pageFiles: readonly string[]) {\n super(\n `Two or more not-found pages were found: ${pageFiles.map((file) => `\"${file}\"`).join(\", \")}. ` +\n `An application has exactly one \\`${NOT_FOUND_PAGE_FILENAME}\\` — it answers every ` +\n \"unmatched page URL in the process, so a second one would silently never render. \" +\n \"Keep one and delete the rest.\",\n );\n this.name = \"DuplicateNotFoundPageError\";\n }\n}\n\n/**\n * Raised when `404.page.tsx` declares a `route` export.\n *\n * The not-found page has no URL of its own — it is reached by NOT matching. A\n * `route` export on it reads like a promise that `/404` is browsable, and it is\n * not: the installers register this file on the catch-all and nowhere else. So\n * the export is refused rather than ignored, because a declaration the framework\n * silently drops is worse than one it rejects.\n */\nexport class NotFoundPageDeclaresRouteError extends Error {\n public constructor(public readonly pageFile: string) {\n super(\n `\"${pageFile}\" is the not-found page but declares a \\`route\\` export. ` +\n `\\`${NOT_FOUND_PAGE_FILENAME}\\` has no URL of its own — it answers every page URL that ` +\n \"matched nothing, and is never registered at a path of its own. Remove the `route` \" +\n \"export; to serve a browsable page at a fixed path, use a normal `*.page.tsx`.\",\n );\n this.name = \"NotFoundPageDeclaresRouteError\";\n }\n}\n\n/** The shape this module reads off a registered route — core's `Route`, narrowed. */\nexport type RegisteredRouteShape = {\n path: string;\n isPage?: boolean;\n};\n\n/**\n * The media range the not-found PAGE is gated on. Compared literally: a request\n * either named this exact type or it did not.\n */\nconst HTML_MEDIA_TYPE = \"text/html\";\n\n/**\n * True when `text/html` is named EXPLICITLY in an `Accept` header — the whole\n * discriminator, in one predicate.\n *\n * Wildcards are refused on purpose. `* /*` is what `fetch()` and `curl` send\n * when the caller expressed no preference at all, and `text/*` names a family;\n * neither is a request for a document, and treating either as one is what makes\n * a mistyped `/api/...` answer HTML to a JSON parser.\n *\n * `q=0` is honoured because it is the header's own way of saying \"not this\n * one\" — `Accept: text/html;q=0, application/json` is a client refusing the\n * document, and reading it as a request for one would be reading the header\n * backwards. Any other `q`, present or absent, counts.\n */\nexport function acceptsHtmlExplicitly(accept: string | undefined): boolean {\n if (!accept) return false;\n\n for (const entry of accept.split(\",\")) {\n const [rawType, ...parameters] = entry.split(\";\");\n\n if (rawType.trim().toLowerCase() !== HTML_MEDIA_TYPE) continue;\n\n const quality = parameters\n .map((parameter) => parameter.trim().toLowerCase())\n .find((parameter) => parameter.startsWith(\"q=\"));\n\n // A malformed `q` is not a refusal — only an explicit zero is.\n if (quality !== undefined && Number.parseFloat(quality.slice(2)) === 0) continue;\n\n return true;\n }\n\n return false;\n}\n\nexport type UnmatchedRequestKind = \"page\" | \"api\";\n\n/**\n * The rule, in one function — see this file's header for why it is these two\n * conditions and why the second one refuses wildcards.\n */\nexport function classifyUnmatchedRequest(input: {\n method: string;\n accept: string | undefined;\n}): UnmatchedRequestKind {\n const method = input.method.toUpperCase();\n\n // Pages are installed with `router.get`, so only these two verbs can ever\n // have been asking for one.\n if (method !== \"GET\" && method !== \"HEAD\") return \"api\";\n\n return acceptsHtmlExplicitly(input.accept) ? \"page\" : \"api\";\n}\n\n/**\n * The document served when the application ships no `404.page.tsx`.\n *\n * Deliberately a STRING, not a React render: it must survive the case where the\n * application root, a layout or the page module is exactly what is broken, and\n * a default that can itself fail is not a default. It carries no stylesheet and\n * no hydration script for the same reason — nothing here can 500.\n *\n * It answers 404 like the real page does, because the status is the part that\n * search engines, caches and monitoring read; a framework default that soft-404s\n * would teach every un-customised application to lie.\n */\nexport function frameworkDefaultNotFoundDocument(): string {\n return (\n \"<!doctype html>\" +\n '<html lang=\"en\">' +\n \"<head>\" +\n '<meta charset=\"utf-8\">' +\n '<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">' +\n '<meta name=\"robots\" content=\"noindex\">' +\n \"<title>404 — Page not found</title>\" +\n \"</head>\" +\n \"<body>\" +\n \"<h1>404 — Page not found</h1>\" +\n \"<p>This URL does not match any page.</p>\" +\n `<p>To replace this page, add <code>${NOT_FOUND_PAGE_FILENAME}</code> to a web folder ` +\n \"(for example <code>src/web/404.page.tsx</code>).</p>\" +\n \"</body>\" +\n \"</html>\"\n );\n}\n\nexport type NotFoundRouteHandlerOptions = {\n /**\n * The application's `404.page.tsx`, already built into a page handler by\n * whichever installer owns module loading — `undefined` when the application\n * ships no such file, which is what selects\n * {@link frameworkDefaultNotFoundDocument}.\n *\n * Taking a built handler rather than a module keeps this file out of the\n * render pipeline entirely: dev hands over a Vite-backed handler, production a\n * manifest-backed one, and neither difference is visible here.\n */\n renderPage?: PageRouteHandler;\n};\n\n/**\n * The handler registered on the catch-all.\n *\n * Three answers, in this order, and the order is the safety property: the API\n * check runs BEFORE anything can render, so no request that the rule calls an\n * API request can reach a React render even if the page module is broken.\n */\nexport function createNotFoundRouteHandler(\n options: NotFoundRouteHandlerOptions,\n): PageRouteHandler {\n const { renderPage } = options;\n\n return async (context: HttpContext) => {\n const { request, response } = context;\n // Node lowercases header names and collapses a repeated `Accept` into an\n // array; both forms are read, so a duplicated header cannot silently mean\n // \"no preference\".\n const accept = request.header(\"accept\");\n\n if (\n classifyUnmatchedRequest({\n method: request.method,\n accept: Array.isArray(accept) ? accept.join(\",\") : accept,\n }) === \"api\"\n ) {\n // The same body core's own dev dispatcher writes for an unmatched route\n // (`core/src/router/router.ts`), so an API 404 reads identically whether\n // it fell through to core or was declined here — and identically in\n // development and in production, which it previously was not.\n await response.send(\n { error: \"Route not found\", path: request.path, method: request.method },\n 404,\n );\n\n return;\n }\n\n if (renderPage === undefined) {\n await response.html(frameworkDefaultNotFoundDocument(), 404);\n\n return;\n }\n\n await renderPage(context);\n };\n}\n"],"mappings":";;;;;;;;AAiEA,MAAa,0BAA0B;;;;;;;;;;AAWvC,MAAa,uBAAuB;;;;;;;;;;;;AAapC,MAAa,uBAAuB;;AAGpC,SAAgB,mBAAmB,YAA6B;CAC9D,MAAM,YAAY,KAAK,IAAI,WAAW,YAAY,GAAG,GAAG,WAAW,YAAY,IAAI,CAAC;CAEpF,OAAO,WAAW,MAAM,YAAY,CAAC,MAAM;AAC7C;;;;;;;;;AAUA,IAAa,6BAAb,cAAgD,MAAM;CACjB;CAAnC,AAAO,YAAY,AAAgB,WAA8B;EAC/D,MACE,2CAA2C,UAAU,KAAK,SAAS,IAAI,KAAK,EAAE,CAAC,CAAC,KAAK,IAAI,EAAE,qCACrD,wBAAwB,oIAGhE;EANiC;EAOjC,KAAK,OAAO;CACd;AACF;;;;;;;;;;AAWA,IAAa,iCAAb,cAAoD,MAAM;CACrB;CAAnC,AAAO,YAAY,AAAgB,UAAkB;EACnD,MACE,IAAI,SAAS,6DACN,wBAAwB,8NAGjC;EANiC;EAOjC,KAAK,OAAO;CACd;AACF;;;;;AAYA,MAAM,kBAAkB;;;;;;;;;;;;;;;AAgBxB,SAAgB,sBAAsB,QAAqC;CACzE,IAAI,CAAC,QAAQ,OAAO;CAEpB,KAAK,MAAM,SAAS,OAAO,MAAM,GAAG,GAAG;EACrC,MAAM,CAAC,SAAS,GAAG,cAAc,MAAM,MAAM,GAAG;EAEhD,IAAI,QAAQ,KAAK,CAAC,CAAC,YAAY,MAAM,iBAAiB;EAEtD,MAAM,UAAU,WACb,KAAK,cAAc,UAAU,KAAK,CAAC,CAAC,YAAY,CAAC,CAAC,CAClD,MAAM,cAAc,UAAU,WAAW,IAAI,CAAC;EAGjD,IAAI,YAAY,UAAa,OAAO,WAAW,QAAQ,MAAM,CAAC,CAAC,MAAM,GAAG;EAExE,OAAO;CACT;CAEA,OAAO;AACT;;;;;AAQA,SAAgB,yBAAyB,OAGhB;CACvB,MAAM,SAAS,MAAM,OAAO,YAAY;CAIxC,IAAI,WAAW,SAAS,WAAW,QAAQ,OAAO;CAElD,OAAO,sBAAsB,MAAM,MAAM,IAAI,SAAS;AACxD;;;;;;;;;;;;;AAcA,SAAgB,mCAA2C;CACzD,OACE,gUAWsC,wBAAwB;AAKlE;;;;;;;;AAuBA,SAAgB,2BACd,SACkB;CAClB,MAAM,EAAE,eAAe;CAEvB,OAAO,OAAO,YAAyB;EACrC,MAAM,EAAE,SAAS,aAAa;EAI9B,MAAM,SAAS,QAAQ,OAAO,QAAQ;EAEtC,IACE,yBAAyB;GACvB,QAAQ,QAAQ;GAChB,QAAQ,MAAM,QAAQ,MAAM,IAAI,OAAO,KAAK,GAAG,IAAI;EACrD,CAAC,MAAM,OACP;GAKA,MAAM,SAAS,KACb;IAAE,OAAO;IAAmB,MAAM,QAAQ;IAAM,QAAQ,QAAQ;GAAO,GACvE,GACF;GAEA;EACF;EAEA,IAAI,eAAe,QAAW;GAC5B,MAAM,SAAS,KAAK,iCAAiC,GAAG,GAAG;GAE3D;EACF;EAEA,MAAM,WAAW,OAAO;CAC1B;AACF"}
|
|
1
|
+
{"version":3,"file":"not-found-page.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/server/not-found-page.ts"],"sourcesContent":["/**\n * THE NOT-FOUND PATH — the one route in the application that answers for URLs\n * nobody declared.\n *\n * An application gets it by writing `404.page.tsx` anywhere under a web root.\n * The file is named for the status it answers with, not for a concept\n * (\"not-found\"), because `404` is the string people actually search for, and\n * the `*.page.tsx` suffix is what makes it a page in the first place.\n *\n * ── THE RULE THIS FILE EXISTS FOR ────────────────────────────────────────────\n *\n * Pages and API routes share ONE route namespace and ONE router. So a catch-all\n * page route sees every unmatched request in the process, including\n * `GET /api/uzers` — and if it renders a document for that, a `fetch()` gets\n * `<!doctype html>` back and dies inside `response.json()` with a SyntaxError\n * pointing at the parser instead of at the typo. That failure is expensive\n * precisely because the error names nothing near its cause.\n *\n * Because pages and API share one namespace there is no path-prefix rule\n * available: `/anything` may legitimately be either. The discriminator is\n * therefore the `Accept` header, and it is stated as a narrow permission rather\n * than a guess — the document is the exception, JSON is the default:\n *\n * A request renders the not-found PAGE only if\n * 1. its method is GET or HEAD, and\n * 2. `text/html` appears EXPLICITLY in its `Accept` header.\n *\n * (1) is not a heuristic about browsers. Pages are registered with\n * `router.get` and nothing else — every page route in this codebase is\n * installed by `installPageRoutes` / `installPageRoutesFromManifest`, both\n * of which call `router.get`. A `POST` therefore cannot have been meant\n * for a page, by construction. HEAD rides along because Fastify answers it\n * from the GET route.\n *\n * (2) is EXPLICIT and the word is load-bearing. A wildcard does NOT count:\n * `* /*` — what a bare `fetch()` sends — is not a request for a document,\n * it is the absence of a preference, and `text/*` claims a family rather\n * than the type. Only the literal `text/html` media range, with a non-zero\n * `q`, opens the page path. A browser address-bar navigation always sends\n * an explicit `text/html`; a `fetch()` that has not asked for one never\n * does. So the mistyped `/api/...` in a `fetch()` keeps its JSON body and\n * dies at the typo rather than inside `response.json()`.\n *\n * WHAT THE RULE CANNOT DECIDE, and does not pretend to: a browser navigating to\n * a typo'd API URL asks for `text/html`, and so is answered with the document.\n * Nothing in that request distinguishes it from a typo'd page URL — same verb,\n * same header, same absence of a match — so the rule does not guess. The status\n * is 404 either way, which is the part machines read.\n *\n * ── DEPENDENCY NOTE ──────────────────────────────────────────────────────────\n * This module has NO runtime imports. `../build/discover-pages` imports the\n * filename constant and the identity helpers from here so build discovery and\n * both installers cannot disagree about what a not-found page is, and that edge\n * must not drag the render pipeline into the build.\n */\nimport type { HttpContext } from \"@warlock.js/core\";\nimport type { PageRouteHandler } from \"./create-page-route-handler\";\n\n/**\n * The one filename that makes a page THE not-found page.\n *\n * `404.page.tsx`, not `not-found.page.tsx`: it keeps the `*.page.tsx`\n * convention every other page follows, and `404` is the token a developer\n * greps for when a URL answers with one.\n */\nexport const NOT_FOUND_PAGE_FILENAME = \"404.page.tsx\";\n\n/**\n * The path the not-found route is registered on — find-my-way's and Fastify's\n * catch-all, and the same literal core's own dev dispatcher registers\n * (`core/src/router/router.ts`, `server.route({ url: \"*\" })`).\n *\n * A catch-all has the LOWEST matching priority in both routers, so every\n * declared page and every declared API route still wins on its own path; this\n * route is only ever reached because nothing else claimed the URL.\n */\nexport const NOT_FOUND_ROUTE_PATH = \"*\";\n\n/**\n * The reserved route name the not-found page is registered under.\n *\n * Namespaced under `warlock.` because it is the framework's route rather than\n * the application's, and because the router's name namespace is shared with API\n * routes — an application that takes this name gets core's duplicate-name error,\n * which is the loud answer, not a silent overwrite.\n *\n * It is deliberately NOT published into the route table (`href()` / `<Link>`):\n * the not-found page has no URL of its own to link to.\n */\nexport const NOT_FOUND_ROUTE_NAME = \"warlock.not-found\";\n\n/** True when `sourceFile`'s basename is exactly {@link NOT_FOUND_PAGE_FILENAME}. */\nexport function isNotFoundPageFile(sourceFile: string): boolean {\n const separator = Math.max(sourceFile.lastIndexOf(\"/\"), sourceFile.lastIndexOf(\"\\\\\"));\n\n return sourceFile.slice(separator + 1) === NOT_FOUND_PAGE_FILENAME;\n}\n\n/**\n * Raised when more than one `404.page.tsx` exists.\n *\n * There is exactly one not-found route in a process, so a second file is not a\n * per-module override — it is two files claiming one route, with the winner\n * decided by directory-walk order. Both are named because the fix is to delete\n * one and the operator has to know which two are in play.\n */\nexport class DuplicateNotFoundPageError extends Error {\n public constructor(public readonly pageFiles: readonly string[]) {\n super(\n `Two or more not-found pages were found: ${pageFiles.map((file) => `\"${file}\"`).join(\", \")}. ` +\n `An application has exactly one \\`${NOT_FOUND_PAGE_FILENAME}\\` — it answers every ` +\n \"unmatched page URL in the process, so a second one would silently never render. \" +\n \"Keep one and delete the rest.\",\n );\n this.name = \"DuplicateNotFoundPageError\";\n }\n}\n\n/**\n * Raised when `404.page.tsx` declares a `route` export.\n *\n * The not-found page has no URL of its own — it is reached by NOT matching. A\n * `route` export on it reads like a promise that `/404` is browsable, and it is\n * not: the installers register this file on the catch-all and nowhere else. So\n * the export is refused rather than ignored, because a declaration the framework\n * silently drops is worse than one it rejects.\n */\nexport class NotFoundPageDeclaresRouteError extends Error {\n public constructor(public readonly pageFile: string) {\n super(\n `\"${pageFile}\" is the not-found page but declares a \\`route\\` export. ` +\n `\\`${NOT_FOUND_PAGE_FILENAME}\\` has no URL of its own — it answers every page URL that ` +\n \"matched nothing, and is never registered at a path of its own. Remove the `route` \" +\n \"export; to serve a browsable page at a fixed path, use a normal `*.page.tsx`.\",\n );\n this.name = \"NotFoundPageDeclaresRouteError\";\n }\n}\n\n/** The shape this module reads off a registered route — core's `Route`, narrowed. */\nexport type RegisteredRouteShape = {\n path: string;\n isPage?: boolean;\n};\n\n/**\n * The media range the not-found PAGE is gated on. Compared literally: a request\n * either named this exact type or it did not.\n */\nconst HTML_MEDIA_TYPE = \"text/html\";\n\n/**\n * True when `text/html` is named EXPLICITLY in an `Accept` header — the whole\n * discriminator, in one predicate.\n *\n * Wildcards are refused on purpose. `* /*` is what `fetch()` and `curl` send\n * when the caller expressed no preference at all, and `text/*` names a family;\n * neither is a request for a document, and treating either as one is what makes\n * a mistyped `/api/...` answer HTML to a JSON parser.\n *\n * `q=0` is honoured because it is the header's own way of saying \"not this\n * one\" — `Accept: text/html;q=0, application/json` is a client refusing the\n * document, and reading it as a request for one would be reading the header\n * backwards. Any other `q`, present or absent, counts.\n */\nexport function acceptsHtmlExplicitly(accept: string | undefined): boolean {\n if (!accept) return false;\n\n for (const entry of accept.split(\",\")) {\n const [rawType, ...parameters] = entry.split(\";\");\n\n if (rawType.trim().toLowerCase() !== HTML_MEDIA_TYPE) continue;\n\n const quality = parameters\n .map((parameter) => parameter.trim().toLowerCase())\n .find((parameter) => parameter.startsWith(\"q=\"));\n\n // A malformed `q` is not a refusal — only an explicit zero is.\n if (quality !== undefined && Number.parseFloat(quality.slice(2)) === 0) continue;\n\n return true;\n }\n\n return false;\n}\n\nexport type UnmatchedRequestKind = \"page\" | \"api\";\n\n/**\n * The rule, in one function — see this file's header for why it is these two\n * conditions and why the second one refuses wildcards.\n */\nexport function classifyUnmatchedRequest(input: {\n method: string;\n accept: string | undefined;\n}): UnmatchedRequestKind {\n const method = input.method.toUpperCase();\n\n // Pages are installed with `router.get`, so only these two verbs can ever\n // have been asking for one.\n if (method !== \"GET\" && method !== \"HEAD\") return \"api\";\n\n return acceptsHtmlExplicitly(input.accept) ? \"page\" : \"api\";\n}\n\n/**\n * The document served when the application ships no `404.page.tsx`.\n *\n * Deliberately a STRING, not a React render: it must survive the case where the\n * application root, a layout or the page module is exactly what is broken, and\n * a default that can itself fail is not a default. It carries no stylesheet and\n * no hydration script for the same reason — nothing here can 500.\n *\n * It answers 404 like the real page does, because the status is the part that\n * search engines, caches and monitoring read; a framework default that soft-404s\n * would teach every un-customised application to lie.\n */\nexport function frameworkDefaultNotFoundDocument(): string {\n return (\n \"<!doctype html>\" +\n '<html lang=\"en\">' +\n \"<head>\" +\n '<meta charset=\"utf-8\">' +\n '<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">' +\n '<meta name=\"robots\" content=\"noindex\">' +\n \"<title>404 — Page not found</title>\" +\n \"</head>\" +\n \"<body>\" +\n \"<h1>404 — Page not found</h1>\" +\n \"<p>This URL does not match any page.</p>\" +\n `<p>To replace this page, add <code>${NOT_FOUND_PAGE_FILENAME}</code> to a web folder ` +\n \"(for example <code>src/web/404.page.tsx</code>).</p>\" +\n \"</body>\" +\n \"</html>\"\n );\n}\n\nexport type NotFoundRouteHandlerOptions = {\n /**\n * The application's `404.page.tsx`, already built into a page handler by\n * whichever installer owns module loading — `undefined` when the application\n * ships no such file, which is what selects\n * {@link frameworkDefaultNotFoundDocument}.\n *\n * Taking a built handler rather than a module keeps this file out of the\n * render pipeline entirely: dev hands over a Vite-backed handler, production a\n * manifest-backed one, and neither difference is visible here.\n */\n renderPage?: PageRouteHandler;\n};\n\n/**\n * The handler registered on the catch-all.\n *\n * Three answers, in this order, and the order is the safety property: the API\n * check runs BEFORE anything can render, so no request that the rule calls an\n * API request can reach a React render even if the page module is broken.\n */\nexport function createNotFoundRouteHandler(\n options: NotFoundRouteHandlerOptions,\n): PageRouteHandler {\n const { renderPage } = options;\n\n return async (context: HttpContext) => {\n const { request, response } = context;\n // Node lowercases header names and collapses a repeated `Accept` into an\n // array; both forms are read, so a duplicated header cannot silently mean\n // \"no preference\".\n const accept = request.header(\"accept\");\n\n if (\n classifyUnmatchedRequest({\n method: request.method,\n accept: Array.isArray(accept) ? accept.join(\",\") : accept,\n }) === \"api\"\n ) {\n // The same body core's own dev dispatcher writes for an unmatched route\n // (`core/src/router/router.ts`), so an API 404 reads identically whether\n // it fell through to core or was declined here — and identically in\n // development and in production, which it previously was not.\n await response.send(\n { error: \"Route not found\", path: request.path, method: request.method },\n 404,\n );\n\n return;\n }\n\n if (renderPage === undefined) {\n await response.html(frameworkDefaultNotFoundDocument(), 404);\n\n return;\n }\n\n return renderPage(context);\n };\n}\n"],"mappings":";;;;;;;;AAiEA,MAAa,0BAA0B;;;;;;;;;;AAWvC,MAAa,uBAAuB;;;;;;;;;;;;AAapC,MAAa,uBAAuB;;AAGpC,SAAgB,mBAAmB,YAA6B;CAC9D,MAAM,YAAY,KAAK,IAAI,WAAW,YAAY,GAAG,GAAG,WAAW,YAAY,IAAI,CAAC;CAEpF,OAAO,WAAW,MAAM,YAAY,CAAC,MAAM;AAC7C;;;;;;;;;AAUA,IAA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;EAEtC,IACE,yBAAyB;GACvB,QAAQ,QAAQ;GAChB,QAAQ,MAAM,QAAQ,MAAM,IAAI,OAAO,KAAK,GAAG,IAAI;EACrD,CAAC,MAAM,OACP;GAKA,MAAM,SAAS,KACb;IAAE,OAAO;IAAmB,MAAM,QAAQ;IAAM,QAAQ,QAAQ;GAAO,GACvE,GACF;GAEA;EACF;EAEA,IAAI,eAAe,QAAW;GAC5B,MAAM,SAAS,KAAK,iCAAiC,GAAG,GAAG;GAE3D;EACF;EAEA,OAAO,WAAW,OAAO;CAC3B;AACF"}
|
|
@@ -1,14 +1,8 @@
|
|
|
1
|
-
import { PageContextRunner
|
|
1
|
+
import { PageContextRunner } from "./execute-page-request.types.mjs";
|
|
2
2
|
|
|
3
|
-
//#region
|
|
3
|
+
//#region web/src/server/page-context.d.ts
|
|
4
4
|
/** Returns the previous runner so tests can restore it. */
|
|
5
5
|
declare function connectPageContext(runner: PageContextRunner | undefined): PageContextRunner | undefined;
|
|
6
|
-
/**
|
|
7
|
-
* Connect an additional shared-module instance that must enter every request.
|
|
8
|
-
* Production has one module graph and needs none; the dev server uses this seam
|
|
9
|
-
* for the Vite SSR graph that evaluates app code.
|
|
10
|
-
*/
|
|
11
|
-
declare function connectPageSharedScope(enter: ((store: PipelineStore) => void) | undefined): ((store: PipelineStore) => void) | undefined;
|
|
12
6
|
//#endregion
|
|
13
|
-
export { connectPageContext
|
|
7
|
+
export { connectPageContext };
|
|
14
8
|
//# sourceMappingURL=page-context.d.mts.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//#region
|
|
1
|
+
//#region web/src/server/page-context.ts
|
|
2
2
|
/**
|
|
3
3
|
* Boot-time wiring for the per-request context, once per process.
|
|
4
4
|
*
|
|
@@ -13,31 +13,18 @@
|
|
|
13
13
|
* ```
|
|
14
14
|
*/
|
|
15
15
|
let pageContextRunner;
|
|
16
|
-
let additionalSharedScopeEntry;
|
|
17
16
|
/** Returns the previous runner so tests can restore it. */
|
|
18
17
|
function connectPageContext(runner) {
|
|
19
18
|
const previous = pageContextRunner;
|
|
20
19
|
pageContextRunner = runner;
|
|
21
20
|
return previous;
|
|
22
21
|
}
|
|
23
|
-
|
|
24
|
-
* Connect an additional shared-module instance that must enter every request.
|
|
25
|
-
* Production has one module graph and needs none; the dev server uses this seam
|
|
26
|
-
* for the Vite SSR graph that evaluates app code.
|
|
27
|
-
*/
|
|
28
|
-
function connectPageSharedScope(enter) {
|
|
29
|
-
const previous = additionalSharedScopeEntry;
|
|
30
|
-
additionalSharedScopeEntry = enter;
|
|
31
|
-
return previous;
|
|
32
|
-
}
|
|
33
|
-
function enterAdditionalSharedScope(store) {
|
|
34
|
-
additionalSharedScopeEntry?.(store);
|
|
35
|
-
}
|
|
22
|
+
function enterAdditionalSharedScope(store) {}
|
|
36
23
|
function requireRunner() {
|
|
37
24
|
if (!pageContextRunner) throw new Error("executePageRequest() has no request context connected (web/src/server/page-context.ts). The pipeline opens the per-request AsyncLocalStorage frame with CORE's own context — it never owns one itself. Fix: the server bootstrap must call connectPageContext(requestContext) (and connectSharedStore(() => requestContext.getStore())) before any page request runs.");
|
|
38
25
|
return pageContextRunner;
|
|
39
26
|
}
|
|
40
27
|
|
|
41
28
|
//#endregion
|
|
42
|
-
export { connectPageContext,
|
|
29
|
+
export { connectPageContext, enterAdditionalSharedScope, requireRunner };
|
|
43
30
|
//# sourceMappingURL=page-context.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"page-context.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"page-context.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/server/page-context.ts"],"sourcesContent":["import type { PageContextRunner, PipelineStore } from \"./execute-page-request.types\";\n\n/**\n * Boot-time wiring for the per-request context, once per process.\n *\n * The pipeline never owns an `AsyncLocalStorage` — it borrows core's. A VALUE\n * import of core from web risks resolving a second core instance, and two\n * copies of core means two stores, so `core` stays a type-only peer and the\n * code that already has `requestContext` in scope hands it over:\n *\n * ```ts\n * connectPageContext(requestContext);\n * connectSharedStore(() => requestContext.getStore());\n * ```\n */\n\nlet pageContextRunner: PageContextRunner | undefined;\nlet additionalSharedScopeEntry: ((store: PipelineStore) => void) | undefined;\n\n/** Returns the previous runner so tests can restore it. */\nexport function connectPageContext(\n runner: PageContextRunner | undefined,\n): PageContextRunner | undefined {\n const previous = pageContextRunner;\n\n pageContextRunner = runner;\n\n return previous;\n}\n\nexport function enterAdditionalSharedScope(store: PipelineStore): void {\n additionalSharedScopeEntry?.(store);\n}\n\nexport function requireRunner(): PageContextRunner {\n if (!pageContextRunner) {\n throw new Error(\n \"executePageRequest() has no request context connected \" +\n \"(web/src/server/page-context.ts). The pipeline opens the per-request \" +\n \"AsyncLocalStorage frame with CORE's own context — it never owns one \" +\n \"itself. Fix: the server bootstrap must call \" +\n \"connectPageContext(requestContext) (and \" +\n \"connectSharedStore(() => requestContext.getStore())) before any \" +\n \"page request runs.\",\n );\n }\n\n return pageContextRunner;\n}\n"],"mappings":";;;;;;;;;;;;;;AAgBA,IAAI;;AAIJ,SAAgB,mBACd,QAC+B;CAC/B,MAAM,WAAW;CAEjB,oBAAoB;CAEpB,OAAO;AACT;AAEA,SAAgB,2BAA2B,OAA4B,CAEvE;AAEA,SAAgB,gBAAmC;CACjD,IAAI,CAAC,mBACH,MAAM,IAAI,MACR,uWAOF;CAGF,OAAO;AACT"}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
|
|
4
|
+
//#region web/src/server/page-file-change.ts
|
|
5
|
+
const PAGE_FILE_SUFFIX = ".page.tsx";
|
|
6
|
+
function isFile(file) {
|
|
7
|
+
try {
|
|
8
|
+
return fs.statSync(file).isFile();
|
|
9
|
+
} catch {
|
|
10
|
+
return false;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
function normalizePath(appRoot, file) {
|
|
14
|
+
return path.resolve(appRoot, file.replace(/[\\/]+/g, path.sep));
|
|
15
|
+
}
|
|
16
|
+
function pathKey(file) {
|
|
17
|
+
const normalized = file.replace(/\\/g, "/");
|
|
18
|
+
return process.platform === "win32" ? normalized.toLowerCase() : normalized;
|
|
19
|
+
}
|
|
20
|
+
function isPageFilePath(file, appSrcRoot) {
|
|
21
|
+
if (!file.endsWith(".page.tsx")) return false;
|
|
22
|
+
const relative = path.relative(appSrcRoot, file);
|
|
23
|
+
return relative !== "" && !relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative) && relative.split(path.sep)[0] === "web";
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Layouts contribute to every descendant page's derived route identity, but
|
|
27
|
+
* never own a route themselves. Keep this predicate aligned with
|
|
28
|
+
* `page-registry-plugin.ts` so a layout lifecycle event re-derives the whole
|
|
29
|
+
* page table rather than being discarded as an ordinary Vite update.
|
|
30
|
+
*/
|
|
31
|
+
function isPageLayoutFilePath(file, appSrcRoot) {
|
|
32
|
+
const relative = path.relative(appSrcRoot, file);
|
|
33
|
+
const base = path.basename(file);
|
|
34
|
+
return relative !== "" && !relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative) && relative.split(path.sep)[0] === "web" && (base === "layout.ts" || base === "layout.tsx" || /\.layout\.tsx?$/.test(base));
|
|
35
|
+
}
|
|
36
|
+
/** Error boundaries participate in reload tracking but never in router ownership. */
|
|
37
|
+
function isErrorPageFilePath(file) {
|
|
38
|
+
return path.basename(file) === "error.page.tsx";
|
|
39
|
+
}
|
|
40
|
+
function classifyPageFileChanges(changedFiles, options) {
|
|
41
|
+
const pageRoot = path.resolve(options.appRoot, options.appSrcRoot);
|
|
42
|
+
const installed = new Set(options.installedPageFiles.map((file) => pathKey(normalizePath(options.appRoot, file))));
|
|
43
|
+
const classified = {
|
|
44
|
+
added: [],
|
|
45
|
+
removed: [],
|
|
46
|
+
inspectionNeeded: []
|
|
47
|
+
};
|
|
48
|
+
const seen = /* @__PURE__ */ new Set();
|
|
49
|
+
const fileExists = options.fileExists ?? isFile;
|
|
50
|
+
for (const changedFile of changedFiles) {
|
|
51
|
+
const file = normalizePath(options.appRoot, changedFile);
|
|
52
|
+
const key = pathKey(file);
|
|
53
|
+
if (seen.has(key)) continue;
|
|
54
|
+
seen.add(key);
|
|
55
|
+
if (isPageLayoutFilePath(file, pageRoot)) {
|
|
56
|
+
(fileExists(file) ? classified.added : classified.removed).push(file);
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
if (!isPageFilePath(file, pageRoot)) continue;
|
|
60
|
+
const isInstalled = installed.has(key);
|
|
61
|
+
const isErrorPage = isErrorPageFilePath(file);
|
|
62
|
+
if (!fileExists(file)) {
|
|
63
|
+
if (isInstalled || isErrorPage) classified.removed.push(file);
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
if (isInstalled || isErrorPage) classified.inspectionNeeded.push(file);
|
|
67
|
+
else classified.added.push(file);
|
|
68
|
+
}
|
|
69
|
+
return classified;
|
|
70
|
+
}
|
|
71
|
+
function hasPageFileChanges(changes) {
|
|
72
|
+
return changes.added.length > 0 || changes.removed.length > 0 || changes.inspectionNeeded.length > 0;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
//#endregion
|
|
76
|
+
export { classifyPageFileChanges, hasPageFileChanges, isErrorPageFilePath };
|
|
77
|
+
//# sourceMappingURL=page-file-change.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"page-file-change.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/server/page-file-change.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\n\nexport const PAGE_FILE_SUFFIX = \".page.tsx\";\n\nexport type PageFileChanges = {\n added: string[];\n removed: string[];\n inspectionNeeded: string[];\n};\n\nexport type PageFileChangeOptions = {\n appRoot: string;\n appSrcRoot: string;\n installedPageFiles: readonly string[];\n fileExists?: (file: string) => boolean;\n};\n\nfunction isFile(file: string): boolean {\n try {\n return fs.statSync(file).isFile();\n } catch {\n return false;\n }\n}\n\nfunction normalizePath(appRoot: string, file: string): string {\n return path.resolve(appRoot, file.replace(/[\\\\/]+/g, path.sep));\n}\n\nfunction pathKey(file: string): string {\n const normalized = file.replace(/\\\\/g, \"/\");\n\n return process.platform === \"win32\" ? normalized.toLowerCase() : normalized;\n}\n\nexport function isPageFilePath(file: string, appSrcRoot: string): boolean {\n if (!file.endsWith(PAGE_FILE_SUFFIX)) {\n return false;\n }\n\n const relative = path.relative(appSrcRoot, file);\n\n return (\n relative !== \"\" &&\n !relative.startsWith(`..${path.sep}`) &&\n relative !== \"..\" &&\n !path.isAbsolute(relative) &&\n relative.split(path.sep)[0] === \"web\"\n );\n}\n\n/**\n * Layouts contribute to every descendant page's derived route identity, but\n * never own a route themselves. Keep this predicate aligned with\n * `page-registry-plugin.ts` so a layout lifecycle event re-derives the whole\n * page table rather than being discarded as an ordinary Vite update.\n */\nexport function isPageLayoutFilePath(file: string, appSrcRoot: string): boolean {\n const relative = path.relative(appSrcRoot, file);\n const base = path.basename(file);\n\n return (\n relative !== \"\" &&\n !relative.startsWith(`..${path.sep}`) &&\n relative !== \"..\" &&\n !path.isAbsolute(relative) &&\n relative.split(path.sep)[0] === \"web\" &&\n (base === \"layout.ts\" || base === \"layout.tsx\" || /\\.layout\\.tsx?$/.test(base))\n );\n}\n\n/** Error boundaries participate in reload tracking but never in router ownership. */\nexport function isErrorPageFilePath(file: string): boolean {\n return path.basename(file) === \"error.page.tsx\";\n}\n\nexport function classifyPageFileChanges(\n changedFiles: readonly string[],\n options: PageFileChangeOptions,\n): PageFileChanges {\n const pageRoot = path.resolve(options.appRoot, options.appSrcRoot);\n const installed = new Set(\n options.installedPageFiles.map((file) => pathKey(normalizePath(options.appRoot, file))),\n );\n const classified: PageFileChanges = { added: [], removed: [], inspectionNeeded: [] };\n const seen = new Set<string>();\n const fileExists = options.fileExists ?? isFile;\n\n for (const changedFile of changedFiles) {\n const file = normalizePath(options.appRoot, changedFile);\n const key = pathKey(file);\n\n if (seen.has(key)) {\n continue;\n }\n\n seen.add(key);\n\n // A layout has no individual router owner. Its addition, removal, or\n // in-place edit can change every descendant page's prefix/layout chain, so\n // force the existing full page-table derivation transaction. `added` is\n // deliberately the transaction's \"replacement required\" bucket here;\n // it does not claim the layout itself owns a newly-added route.\n if (isPageLayoutFilePath(file, pageRoot)) {\n (fileExists(file) ? classified.added : classified.removed).push(file);\n continue;\n }\n\n if (!isPageFilePath(file, pageRoot)) {\n continue;\n }\n\n const isInstalled = installed.has(key);\n const isErrorPage = isErrorPageFilePath(file);\n if (!fileExists(file)) {\n if (isInstalled || isErrorPage) {\n classified.removed.push(file);\n }\n continue;\n }\n\n if (isInstalled || isErrorPage) {\n classified.inspectionNeeded.push(file);\n } else {\n classified.added.push(file);\n }\n }\n\n return classified;\n}\n\nexport function hasPageFileChanges(changes: PageFileChanges): boolean {\n return (\n changes.added.length > 0 ||\n changes.removed.length > 0 ||\n changes.inspectionNeeded.length > 0\n );\n}\n"],"mappings":";;;;AAGA,MAAa,mBAAmB;AAehC,SAAS,OAAO,MAAuB;CACrC,IAAI;EACF,OAAO,GAAG,SAAS,IAAI,EAAE,OAAO;CAClC,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAS,cAAc,SAAiB,MAAsB;CAC5D,OAAO,KAAK,QAAQ,SAAS,KAAK,QAAQ,WAAW,KAAK,GAAG,CAAC;AAChE;AAEA,SAAS,QAAQ,MAAsB;CACrC,MAAM,aAAa,KAAK,QAAQ,OAAO,GAAG;CAE1C,OAAO,QAAQ,aAAa,UAAU,WAAW,YAAY,IAAI;AACnE;AAEA,SAAgB,eAAe,MAAc,YAA6B;CACxE,IAAI,CAAC,KAAK,oBAAyB,GACjC,OAAO;CAGT,MAAM,WAAW,KAAK,SAAS,YAAY,IAAI;CAE/C,OACE,aAAa,MACb,CAAC,SAAS,WAAW,KAAK,KAAK,KAAK,KACpC,aAAa,QACb,CAAC,KAAK,WAAW,QAAQ,KACzB,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e,aACjB,WAAW,QAAQ,KAAK,IAAI;GAE9B;EACF;EAEA,IAAI,eAAe,aACjB,WAAW,iBAAiB,KAAK,IAAI;OAErC,WAAW,MAAM,KAAK,IAAI;CAE9B;CAEA,OAAO;AACT;AAEA,SAAgB,mBAAmB,SAAmC;CACpE,OACE,QAAQ,MAAM,SAAS,KACvB,QAAQ,QAAQ,SAAS,KACzB,QAAQ,iBAAiB,SAAS;AAEtC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//#region
|
|
1
|
+
//#region web/src/server/page-manifest.d.ts
|
|
2
2
|
/**
|
|
3
3
|
* The build→runtime handoff table for production pages.
|
|
4
4
|
*
|
|
@@ -14,18 +14,20 @@
|
|
|
14
14
|
* `@warlock.js/web`.
|
|
15
15
|
*
|
|
16
16
|
* Entries carry MODULES + FILESYSTEM FACTS ONLY — never route paths. A page's
|
|
17
|
-
* route is read off its module (`route` export) at boot and
|
|
18
|
-
* layout `prefix
|
|
19
|
-
*
|
|
17
|
+
* route is read off its module (`route` export) at boot and, when present,
|
|
18
|
+
* composed with its layout `prefix`; when absent, the path is instead derived
|
|
19
|
+
* from the page's own `sourceFile` and its layouts' prefixes, exactly as
|
|
20
|
+
* `install-page-routes.ts:377-382` does in dev and `discover-pages.ts:925-935`
|
|
21
|
+
* does at build — so explicit-wins semantics live in one place for all three.
|
|
20
22
|
*/
|
|
21
23
|
type PageManifestLayoutEntry = {
|
|
22
|
-
/** The imported layout module namespace object (default export = component, optional `prefix`). */module: Record<string, unknown>; /** App-root-relative POSIX source path, e.g. "src/
|
|
24
|
+
/** The imported layout module namespace object (default export = component, optional `prefix`). */module: Record<string, unknown>; /** App-root-relative POSIX source path, e.g. "src/web/layout.tsx". */
|
|
23
25
|
sourceFile: string;
|
|
24
26
|
};
|
|
25
27
|
type PageManifestPageEntry = {
|
|
26
28
|
/** The imported page module namespace object (default export = component, optional `route`). */module: Record<string, unknown>;
|
|
27
29
|
/**
|
|
28
|
-
* App-root-relative POSIX source path, e.g. "src/
|
|
30
|
+
* App-root-relative POSIX source path, e.g. "src/web/home.page.tsx"
|
|
29
31
|
* — feeds FS-derived route/name fallback. The anchor is the APP ROOT, not the
|
|
30
32
|
* repo root; the two differ the moment the app does not sit at the repo root.
|
|
31
33
|
* Consumers compare these ids VERBATIM — the barrel that wrote them is the
|
|
@@ -35,6 +37,11 @@ type PageManifestPageEntry = {
|
|
|
35
37
|
sourceFile: string; /** Layout chain, outermost first. */
|
|
36
38
|
layouts: readonly PageManifestLayoutEntry[];
|
|
37
39
|
};
|
|
40
|
+
/** The optional application error boundary, kept outside the routable page table. */
|
|
41
|
+
type PageManifestErrorPageEntry = {
|
|
42
|
+
module: Record<string, unknown>;
|
|
43
|
+
sourceFile: string;
|
|
44
|
+
};
|
|
38
45
|
type PageManifest = {
|
|
39
46
|
/**
|
|
40
47
|
* Where the client bundle was written, as an APP-ROOT-RELATIVE POSIX path
|
|
@@ -50,11 +57,18 @@ type PageManifest = {
|
|
|
50
57
|
* `WarlockConfig not loaded` during connector boot, taking the whole server
|
|
51
58
|
* down before it could listen.
|
|
52
59
|
*
|
|
53
|
-
* OPTIONAL
|
|
54
|
-
*
|
|
55
|
-
* `
|
|
60
|
+
* OPTIONAL only when the build has neither pages nor public files. A
|
|
61
|
+
* zero-page build skips the hydration bundle, but still names this directory
|
|
62
|
+
* when it copied app-owned `public/` files below it. Present whenever
|
|
63
|
+
* `pages` or `publicFiles` is non-empty.
|
|
56
64
|
*/
|
|
57
65
|
clientDir?: string;
|
|
66
|
+
/**
|
|
67
|
+
* App-public file paths copied below `<clientDir>/public`, relative and
|
|
68
|
+
* POSIX. Production registers these exact URLs; it never mounts the client
|
|
69
|
+
* root and therefore never exposes `.vite/manifest.json`.
|
|
70
|
+
*/
|
|
71
|
+
publicFiles?: readonly string[];
|
|
58
72
|
/**
|
|
59
73
|
* The application root component every page renders inside.
|
|
60
74
|
*
|
|
@@ -69,7 +83,8 @@ type PageManifest = {
|
|
|
69
83
|
app?: {
|
|
70
84
|
module: Record<string, unknown>;
|
|
71
85
|
sourceFile: string;
|
|
72
|
-
};
|
|
86
|
+
}; /** An application-owned error boundary. It has no route name or path. */
|
|
87
|
+
errorPage?: PageManifestErrorPageEntry;
|
|
73
88
|
/**
|
|
74
89
|
* The page table. EMPTY IS A REAL STATE, not a missing one: an empty array
|
|
75
90
|
* means "this bundle was built with web, and it has no pages", which is what
|