@warlock.js/web 5.0.2 → 5.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +250 -0
- package/README.md +126 -12
- package/esm/build/contribution.d.mts +11 -4
- package/esm/build/contribution.mjs +46 -22
- package/esm/build/contribution.mjs.map +1 -1
- package/esm/build/discover-pages.mjs +318 -44
- package/esm/build/discover-pages.mjs.map +1 -1
- package/esm/build/generate-client-registry.mjs +47 -13
- package/esm/build/generate-client-registry.mjs.map +1 -1
- package/esm/build/generate-pages-barrel.mjs +55 -13
- package/esm/build/generate-pages-barrel.mjs.map +1 -1
- package/esm/build/page-default-export.mjs +48 -0
- package/esm/build/page-default-export.mjs.map +1 -0
- package/esm/build/page-routes-manifest.mjs +21 -0
- package/esm/build/page-routes-manifest.mjs.map +1 -0
- package/esm/build/public-files.mjs +45 -0
- package/esm/build/public-files.mjs.map +1 -0
- package/esm/build/read-route-exports.mjs +1 -1
- package/esm/build/read-route-exports.mjs.map +1 -1
- package/esm/client/build-hydrated-tree.mjs +40 -9
- package/esm/client/build-hydrated-tree.mjs.map +1 -1
- package/esm/client/hydrate-page.mjs +1 -1
- package/esm/client/hydrate-page.mjs.map +1 -1
- package/esm/client/navigation/current-route.d.mts +1 -1
- package/esm/client/navigation/current-route.mjs +1 -1
- package/esm/client/navigation/current-route.mjs.map +1 -1
- package/esm/client/navigation/fetch-page-data.mjs +1 -1
- package/esm/client/navigation/fetch-page-data.mjs.map +1 -1
- package/esm/client/navigation/navigation-root.mjs +44 -7
- package/esm/client/navigation/navigation-root.mjs.map +1 -1
- package/esm/client/navigation/prefetch.mjs +1 -1
- package/esm/client/navigation/prefetch.mjs.map +1 -1
- package/esm/client/navigation/refresh.d.mts +1 -1
- package/esm/client/navigation/refresh.mjs +1 -1
- package/esm/client/navigation/refresh.mjs.map +1 -1
- package/esm/client/navigation/scroll-to-fragment.mjs +26 -0
- package/esm/client/navigation/scroll-to-fragment.mjs.map +1 -0
- package/esm/client/navigation/verbs.d.mts +1 -1
- package/esm/client/navigation/verbs.mjs +1 -1
- package/esm/client/navigation/verbs.mjs.map +1 -1
- package/esm/client/runtime/index.d.mts +2 -1
- package/esm/client/runtime/index.mjs +2 -1
- package/esm/client/runtime/manifest.d.mts +1 -1
- package/esm/client/runtime/manifest.mjs +3 -2
- package/esm/client/runtime/manifest.mjs.map +1 -1
- package/esm/client/runtime/matcher.d.mts +13 -1
- package/esm/client/runtime/matcher.mjs +13 -1
- package/esm/client/runtime/matcher.mjs.map +1 -1
- package/esm/client/runtime/types.d.mts +15 -2
- package/esm/components/default-app.mjs +1 -1
- package/esm/components/default-app.mjs.map +1 -1
- package/esm/components/document-context.d.mts +40 -2
- package/esm/components/document-context.mjs +1 -1
- package/esm/components/document-context.mjs.map +1 -1
- package/esm/components/head.d.mts +1 -1
- package/esm/components/head.mjs +1 -1
- package/esm/components/head.mjs.map +1 -1
- package/esm/components/link.d.mts +1 -1
- package/esm/components/link.mjs +1 -1
- package/esm/components/link.mjs.map +1 -1
- package/esm/components/scripts.d.mts +1 -1
- package/esm/components/scripts.mjs +4 -2
- package/esm/components/scripts.mjs.map +1 -1
- package/esm/context.d.mts +6 -102
- package/esm/hydration/index.mjs +1 -1
- package/esm/hydration/index.mjs.map +1 -1
- package/esm/hydration-payload.d.mts +1 -1
- package/esm/hydration-payload.mjs +37 -8
- package/esm/hydration-payload.mjs.map +1 -1
- package/esm/index.d.mts +4 -3
- package/esm/loaders.d.mts +7 -36
- package/esm/metadata.d.mts +15 -1
- package/esm/metadata.mjs +45 -0
- package/esm/metadata.mjs.map +1 -0
- package/esm/props.d.mts +16 -8
- package/esm/route.d.mts +2 -17
- package/esm/routing/compose-route-path.d.mts +1 -1
- package/esm/routing/compose-route-path.mjs +1 -1
- package/esm/routing/compose-route-path.mjs.map +1 -1
- package/esm/routing/data-request.mjs +1 -1
- package/esm/routing/data-request.mjs.map +1 -1
- package/esm/routing/filesystem-route.mjs +45 -0
- package/esm/routing/filesystem-route.mjs.map +1 -0
- package/esm/routing/layout-policy.mjs +1 -1
- package/esm/routing/layout-policy.mjs.map +1 -1
- package/esm/routing/navigator.mjs +1 -1
- package/esm/routing/navigator.mjs.map +1 -1
- package/esm/routing/query-string.d.mts +1 -1
- package/esm/routing/query-string.mjs +1 -1
- package/esm/routing/query-string.mjs.map +1 -1
- package/esm/routing/route-identity.mjs +1 -1
- package/esm/routing/route-identity.mjs.map +1 -1
- package/esm/routing/route-table.d.mts +1 -1
- package/esm/routing/route-table.mjs +1 -1
- package/esm/routing/route-table.mjs.map +1 -1
- package/esm/routing/router-events.d.mts +1 -1
- package/esm/routing/router-events.mjs +1 -1
- package/esm/routing/router-events.mjs.map +1 -1
- package/esm/routing/url-fragment.mjs +120 -0
- package/esm/routing/url-fragment.mjs.map +1 -0
- package/esm/runtime/register-modules.d.mts +19 -0
- package/esm/runtime/register-modules.mjs +22 -0
- package/esm/runtime/register-modules.mjs.map +1 -0
- package/esm/server/build-hydration-payload.mjs +2 -1
- package/esm/server/build-hydration-payload.mjs.map +1 -1
- package/esm/server/client-asset-url-prefix.d.mts +1 -1
- package/esm/server/client-asset-url-prefix.mjs +1 -1
- package/esm/server/client-asset-url-prefix.mjs.map +1 -1
- package/esm/server/create-page-module-loader.d.mts +1 -1
- package/esm/server/create-page-module-loader.mjs +2 -1
- package/esm/server/create-page-module-loader.mjs.map +1 -1
- package/esm/server/create-page-route-handler.d.mts +58 -6
- package/esm/server/create-page-route-handler.mjs +127 -40
- package/esm/server/create-page-route-handler.mjs.map +1 -1
- package/esm/server/dev-server.mjs +2 -13
- package/esm/server/dev-server.mjs.map +1 -1
- package/esm/server/error-page.d.mts +14 -0
- package/esm/server/error-page.mjs +39 -0
- package/esm/server/error-page.mjs.map +1 -0
- package/esm/server/execute-page-request.d.mts +7 -4
- package/esm/server/execute-page-request.mjs +79 -80
- package/esm/server/execute-page-request.mjs.map +1 -1
- package/esm/server/execute-page-request.types.d.mts +33 -92
- package/esm/server/hydration-client-url.d.mts +1 -1
- package/esm/server/hydration-client-url.mjs +2 -2
- package/esm/server/hydration-client-url.mjs.map +1 -1
- package/esm/server/index.d.mts +6 -5
- package/esm/server/index.mjs +4 -4
- package/esm/server/install-page-routes-from-manifest.d.mts +17 -7
- package/esm/server/install-page-routes-from-manifest.mjs +91 -8
- package/esm/server/install-page-routes-from-manifest.mjs.map +1 -1
- package/esm/server/install-page-routes.d.mts +32 -13
- package/esm/server/install-page-routes.mjs +112 -32
- package/esm/server/install-page-routes.mjs.map +1 -1
- package/esm/server/install-production-page-routes.mjs +3 -31
- package/esm/server/install-production-page-routes.mjs.map +1 -1
- package/esm/server/match-page-route.mjs +2 -2
- package/esm/server/match-page-route.mjs.map +1 -1
- package/esm/server/not-found-page.d.mts +126 -0
- package/esm/server/not-found-page.mjs +157 -0
- package/esm/server/not-found-page.mjs.map +1 -0
- package/esm/server/page-context.d.mts +3 -9
- package/esm/server/page-context.mjs +3 -16
- package/esm/server/page-context.mjs.map +1 -1
- package/esm/server/page-file-change.mjs +77 -0
- package/esm/server/page-file-change.mjs.map +1 -0
- package/esm/server/page-manifest.d.mts +25 -10
- package/esm/server/page-manifest.mjs +1 -1
- package/esm/server/page-manifest.mjs.map +1 -1
- package/esm/server/page-render-bundle.mjs +38 -0
- package/esm/server/page-render-bundle.mjs.map +1 -0
- package/esm/server/page-route-reload.mjs +54 -0
- package/esm/server/page-route-reload.mjs.map +1 -0
- package/esm/server/register-production-public-files.mjs +40 -0
- package/esm/server/register-production-public-files.mjs.map +1 -0
- package/esm/server/render-page.d.mts +11 -14
- package/esm/server/render-page.mjs +154 -28
- package/esm/server/render-page.mjs.map +1 -1
- package/esm/server/resolve-page-metadata.mjs +2 -2
- package/esm/server/resolve-page-metadata.mjs.map +1 -1
- package/esm/server/resolve-validation-data.mjs +1 -1
- package/esm/server/resolve-validation-data.mjs.map +1 -1
- package/esm/server/settle-page-response.d.mts +58 -1
- package/esm/server/settle-page-response.mjs +111 -46
- package/esm/server/settle-page-response.mjs.map +1 -1
- package/esm/server/stylesheet-urls.d.mts +41 -30
- package/esm/server/stylesheet-urls.mjs +137 -52
- package/esm/server/stylesheet-urls.mjs.map +1 -1
- package/esm/server/unregistered-pages.mjs +42 -0
- package/esm/server/unregistered-pages.mjs.map +1 -0
- package/esm/server/web-connector-factory.d.mts +2 -3
- package/esm/server/web-connector-factory.mjs +6 -4
- package/esm/server/web-connector-factory.mjs.map +1 -1
- package/esm/server/web-connector.d.mts +1 -1
- package/esm/server/web-connector.mjs +233 -18
- package/esm/server/web-connector.mjs.map +1 -1
- package/esm/shared.d.mts +18 -3
- package/esm/shared.mjs +3 -7
- package/esm/shared.mjs.map +1 -1
- package/esm/validation.d.mts +1 -1
- package/esm/vite/app-convention-aliases.mjs +1 -1
- package/esm/vite/app-convention-aliases.mjs.map +1 -1
- package/esm/vite/build-client.d.mts +1 -1
- package/esm/vite/build-client.mjs +2 -2
- package/esm/vite/build-client.mjs.map +1 -1
- package/esm/vite/gate-a-resolve.d.mts +1 -1
- package/esm/vite/gate-a-resolve.mjs +67 -13
- package/esm/vite/gate-a-resolve.mjs.map +1 -1
- package/esm/vite/gate-b-secrets.d.mts +1 -1
- package/esm/vite/gate-b-secrets.mjs +35 -17
- package/esm/vite/gate-b-secrets.mjs.map +1 -1
- package/esm/vite/gate-c-verify.d.mts +1 -1
- package/esm/vite/gate-c-verify.mjs +6 -6
- package/esm/vite/gate-c-verify.mjs.map +1 -1
- package/esm/vite/hydration-entries.d.mts +1 -1
- package/esm/vite/hydration-entries.mjs +10 -6
- package/esm/vite/hydration-entries.mjs.map +1 -1
- package/esm/vite/index.d.mts +9 -6
- package/esm/vite/index.mjs +124 -11
- package/esm/vite/index.mjs.map +1 -1
- package/esm/vite/page-registry-plugin.d.mts +22 -3
- package/esm/vite/page-registry-plugin.mjs +247 -2
- package/esm/vite/page-registry-plugin.mjs.map +1 -1
- package/esm/vite/projection.d.mts +2 -2
- package/esm/vite/projection.mjs +38 -15
- package/esm/vite/projection.mjs.map +1 -1
- package/llms-full.txt +241 -49
- package/llms.txt +6 -2
- package/package.json +3 -3
- package/skills/add-web-to-an-app/SKILL.md +3 -3
- package/skills/create-a-page/SKILL.md +130 -7
- package/skills/load-page-data/SKILL.md +92 -12
- package/skills/navigate-on-the-client/SKILL.md +3 -1
- package/skills/serve-styles/SKILL.md +13 -12
- package/skills/use-layouts/SKILL.md +20 -8
- package/skills/write-the-root/SKILL.md +5 -1
- package/esm/server/buffered-response.d.mts +0 -58
- package/esm/server/buffered-response.mjs +0 -115
- package/esm/server/buffered-response.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"discover-pages.mjs","names":[],"sources":["../../../../../../../web/src/build/discover-pages.ts"],"sourcesContent":["/**\n * Static discovery of the application's page graph — the ONE scan every\n * provider shares.\n *\n * This module has a single responsibility: look at the filesystem and produce\n * the recipe. It writes nothing, knows nothing about the generated barrel, and\n * imports neither Vite nor a single application module. Everything that turns\n * the recipe into an artefact (the production barrel, the dev plugin, the\n * generated client entry) lives with that artefact and consumes\n * {@link discoverPages}.\n *\n * The reason it is one module rather than one function per consumer: two\n * scanners that agree today drift tomorrow, and a page that exists for the\n * server but not the client is the silent failure that costs a day to find.\n * Sharing the scan makes that disagreement impossible by construction instead\n * of catchable by test.\n *\n * \"Static\" means WITHOUT RUNNING THE APPLICATION — this module globs\n * `*.page.tsx`, `layout.tsx` and `root.tsx`, and reads each page's declared\n * `route` and each layout's declared `prefix` by PARSING the source\n * ({@link readRouteExports}). It still imports no application module.\n *\n * The route a page is served under is the one the page DECLARES, not the one\n * its directory suggests, so that is the route discovery reports. The\n * composition — EVERY layout `prefix` on the page's path, outermost first, plus\n * the page's own `route` path — and the fallback used when a route omits its\n * name are mirrored from the server's installer (`installPageRoutes`),\n * deliberately and in one direction: build and boot agree because one of them\n * copies the other, not because two conventions were written to match.\n *\n * Discovery also CLASSIFIES each layout — does its module have a default\n * export, does it export `middleware` — because the layout policy\n * ({@link \"../routing/layout-policy.ts\"}) owns the rule but may not touch a\n * filesystem to learn the facts the rule needs. That classification is another\n * parse, never an import: a layout is read exactly the way a page's `route` is.\n */\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { parse } from \"@babel/parser\";\nimport { composeRoutePath } from \"../routing/compose-route-path\";\nimport { NestedLayoutsNotSupportedError, selectPageLayout } from \"../routing/layout-policy\";\nimport { deriveFallbackRouteName } from \"../routing/route-identity\";\nimport type { RouteExportsReadResult } from \"./read-route-exports\";\nimport { NonLiteralRouteExportError, readRouteExports } from \"./read-route-exports\";\n\nexport type DiscoverPagesOptions = {\n /** Absolute path to the application root (where `package.json` lives). */\n appRoot: string;\n /** Source directory name under `appRoot`; defaults to `\"src\"`. */\n srcDir?: string;\n};\n\nexport type DiscoveredPage = {\n /**\n * The page's route name: the `name` its `route` export declares, or the\n * server's own fallback derivation — `<module>.<declared path with dots>` for\n * a page in a module's web tree, the dotted path alone for one in the global\n * tree, and `index` when neither has anything to say.\n *\n * Unique across the whole graph — {@link discoverPages} refuses to return a\n * result where it is not.\n */\n routeName: string;\n /**\n * The page's EFFECTIVE route path: the declared `prefix` of EVERY layout on\n * its path — outermost first, wherever in the ancestry each lives — composed\n * in order with the page's own declared `route` path, which is the path the\n * server registers it under. A layout that declares no `prefix` contributes\n * nothing. Always `/`-prefixed.\n *\n * Every layout, not just the rendering one: a `prefix`-only layout is a real\n * segment of the URL its subtree lives under, and skipping it would serve the\n * subtree from a path nobody wrote down.\n */\n routePath: string;\n /** Absolute path to the `*.page.tsx` file. */\n pageFile: string;\n /** The web root this page was found under — the root its layout chain climbs to. */\n webRoot: string;\n /** Absolute paths of every `layout.tsx` from the web root down to the page's own directory, OUTERMOST FIRST. */\n layouts: string[];\n /**\n * The page's middleware chain: the subset of {@link layouts} whose modules\n * export `middleware`, OUTERMOST FIRST — the order they must run in.\n *\n * Source files rather than the middleware values themselves, because\n * discovery never runs application code: this says WHICH layouts contribute a\n * guard, and the consumer that already loads those modules reads the values\n * off them.\n *\n * Empty when no layout on the path declares middleware, which is the common\n * case; a page with no layouts always has an empty chain.\n */\n middlewareLayouts: string[];\n /** Absolute path to the global `root.tsx` every page renders inside, when it exists. */\n appFile?: string;\n};\n\n/** Raised when two pages claim one route name. */\nexport class DuplicatePageRouteNameError extends Error {\n public constructor(\n public readonly routeName: string,\n public readonly firstFile: string,\n public readonly secondFile: string,\n ) {\n super(\n `Two pages resolve to the same route name \"${routeName}\": \"${firstFile}\" and ` +\n `\"${secondFile}\". A route name identifies exactly one page, so the second ` +\n \"page would be unreachable. To fix: rename one of the files, or move it so \" +\n \"its directory gives it a different route name.\",\n );\n this.name = \"DuplicatePageRouteNameError\";\n }\n}\n\nexport function toPosix(value: string): string {\n return value.replace(/\\\\/g, \"/\");\n}\n\nfunction isDirectory(candidate: string): boolean {\n try {\n return fs.statSync(candidate).isDirectory();\n } catch {\n return false;\n }\n}\n\nexport function isFile(candidate: string): boolean {\n try {\n return fs.statSync(candidate).isFile();\n } catch {\n return false;\n }\n}\n\n/**\n * The two page roots: the global `src/web/**` tree and each\n * module's `src/app/<module>/web/**` tree. Both are optional; a project with\n * neither has zero pages, which is a legal empty state.\n */\nexport function discoverWebRoots(srcRoot: string): string[] {\n const roots: string[] = [];\n const globalRoot = path.join(srcRoot, \"web\");\n\n if (isDirectory(globalRoot)) {\n roots.push(globalRoot);\n }\n\n const appDir = path.join(srcRoot, \"app\");\n\n if (isDirectory(appDir)) {\n for (const entry of fs.readdirSync(appDir, { withFileTypes: true }).sort(byName)) {\n if (!entry.isDirectory()) continue;\n\n const moduleWebRoot = path.join(appDir, entry.name, \"web\");\n\n if (isDirectory(moduleWebRoot)) {\n roots.push(moduleWebRoot);\n }\n }\n }\n\n return roots;\n}\n\nfunction byName(left: { name: string }, right: { name: string }): number {\n return left.name < right.name ? -1 : left.name > right.name ? 1 : 0;\n}\n\nexport type DiscoveredPageFile = {\n /** Absolute path to the `*.page.tsx` file. */\n pageFile: string;\n /** The web root ({@link discoverWebRoots}) this page was found under. */\n webRoot: string;\n};\n\n/**\n * The subject list: every `*.page.tsx` under BOTH web roots, one call for the\n * whole graph.\n *\n * Unlike {@link discoverPages}, this reads no `route` or `prefix` export and\n * throws on nothing — it answers only \"which page files exist\", so a provider\n * that still resolves a page's route by its own means (dev's\n * `ssrLoadModule`-driven installer, chiefly) can share the walk without\n * inheriting the static-parsing refusals that answering \"what route is this\"\n * requires.\n */\nexport function discoverPageFiles(srcRoot: string): DiscoveredPageFile[] {\n const found: DiscoveredPageFile[] = [];\n\n for (const webRoot of discoverWebRoots(srcRoot)) {\n for (const pageFile of walkFiles(webRoot, (fileName) => fileName.endsWith(\".page.tsx\"))) {\n found.push({ pageFile, webRoot });\n }\n }\n\n return found;\n}\n\n/** Every file under `dir` (recursive) whose name matches `predicate`. */\nexport function walkFiles(dir: string, predicate: (fileName: string) => boolean): string[] {\n const found: string[] = [];\n\n for (const entry of fs.readdirSync(dir, { withFileTypes: true }).sort(byName)) {\n const full = path.join(dir, entry.name);\n\n if (entry.isDirectory()) {\n found.push(...walkFiles(full, predicate));\n } else if (entry.isFile() && predicate(entry.name)) {\n found.push(full);\n }\n }\n\n return found;\n}\n\n/**\n * A page's layout chain: every `layout.tsx` in the directories from its web\n * root down to its own directory, OUTERMOST FIRST.\n *\n * Dev's installer reads only the nearest layout today, because its page module\n * triple holds a single layout; the recipe carries the whole chain so the\n * runtime side can compose\n * nested layouts without a second discovery pass. The nearest layout is always\n * the LAST element, so a consumer that still wants dev's one-layout behaviour\n * reads `layouts.at(-1)`.\n */\nexport function layoutChainFor(pageFile: string, webRoot: string): string[] {\n const chain: string[] = [];\n const relativeDir = path.relative(webRoot, path.dirname(pageFile));\n const segments = relativeDir === \"\" ? [] : relativeDir.split(path.sep);\n\n let current = webRoot;\n\n for (let index = 0; index <= segments.length; index++) {\n if (index > 0) {\n current = path.join(current, segments[index - 1]);\n }\n\n const candidate = path.join(current, \"layout.tsx\");\n\n if (isFile(candidate)) {\n chain.push(candidate);\n }\n }\n\n return chain;\n}\n\nfunction compareStrings(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0;\n}\n\n/**\n * The total order every consumer sees, and the reason discovery returns an\n * array rather than a set: the page's SOURCE FILE PATH, lexicographic, POSIX.\n *\n * Serialization order only; matching precedence is a property of the route\n * grammar, not of this array.\n *\n * The file path rather than the route path, now that the route is the declared\n * one: a page's route can be rewritten by editing one line, which would reorder\n * an artefact that has not otherwise changed, while the file it lives in is the\n * stable identity the artefact is built from. It also carries no suggestion of\n * precedence — nobody reads \"sorted by file name\" as \"most specific first\",\n * which is the misreading a route-path order invites.\n *\n * Lexicographic because it is byte-comparable output across every provider,\n * which keeps diffs stable and keeps filesystem enumeration order out of the\n * artefact: two machines that list a directory differently must still produce\n * byte-identical output, or a build is only reproducible by luck.\n */\nfunction comparePages(left: DiscoveredPage, right: DiscoveredPage): number {\n return compareStrings(toPosix(left.pageFile), toPosix(right.pageFile));\n}\n\nfunction assertUniqueRouteNames(pages: readonly DiscoveredPage[], appRoot: string): void {\n const fileByRouteName = new Map<string, string>();\n\n for (const page of pages) {\n const existing = fileByRouteName.get(page.routeName);\n const relative = toPosix(path.relative(appRoot, page.pageFile));\n\n if (existing !== undefined) {\n throw new DuplicatePageRouteNameError(page.routeName, existing, relative);\n }\n\n fileByRouteName.set(page.routeName, relative);\n }\n}\n\n/** Raised when a `*.page.tsx` declares no `route` export. */\nexport class MissingRouteExportError extends Error {\n public constructor(public readonly pageFile: string) {\n super(\n `\"${pageFile}\" is a page file but declares no \\`route\\` export. A page with no route is a ` +\n \"page the dev server would still serve and production would 404 on, so the build refuses \" +\n `it instead. For example: export const route = \"/list\";`,\n );\n this.name = \"MissingRouteExportError\";\n }\n}\n\n/**\n * The declared exports of one file, or a thrown\n * {@link NonLiteralRouteExportError} when they cannot be read without running\n * the application. Layouts are read once per run and remembered: a layout is\n * the nearest one for every page beside it, and parsing it once per page would\n * be the same answer bought repeatedly.\n */\nfunction readDeclarations(sourceFile: string, cache: Map<string, RouteExportsReadResult>) {\n let result = cache.get(sourceFile);\n\n if (result === undefined) {\n result = readRouteExports(sourceFile);\n cache.set(sourceFile, result);\n }\n\n if (!result.ok) {\n throw new NonLiteralRouteExportError(result.rejection);\n }\n\n return result;\n}\n\n/**\n * What a layout DOES, read by parsing it — the facts the layout policy's rule\n * needs and, being a pure module, cannot go and find for itself.\n */\ntype LayoutShape = {\n /**\n * Whether the module has a default export — the export that puts an element\n * in the document, and therefore the one thing that makes a layout count\n * against the single-rendering-layout rule.\n */\n renders: boolean;\n /** Whether the module exports `middleware`, or might via a re-export this cannot see through. */\n hasMiddleware: boolean;\n};\n\n/**\n * Parses one layout and reports its shape. Remembered per run for the same\n * reason declarations are: a layout is on the path of every page beneath it.\n */\nfunction readLayoutShape(layoutFile: string, cache: Map<string, LayoutShape>): LayoutShape {\n const cached = cache.get(layoutFile);\n\n if (cached !== undefined) return cached;\n\n const source = fs.readFileSync(layoutFile, \"utf-8\");\n let program: ReturnType<typeof parse>[\"program\"];\n\n try {\n program = parse(source, {\n sourceType: \"module\",\n // Every file this reads is a layout, i.e. `.tsx`.\n plugins: [\"typescript\", \"jsx\"],\n errorRecovery: false,\n }).program;\n } catch (error) {\n throw new Error(\n `Cannot read the exports of \"${layoutFile}\": the file could not be parsed ` +\n `(${(error as Error).message}). Fix the syntax error and the build will continue.`,\n );\n }\n\n const shape: LayoutShape = { renders: false, hasMiddleware: false };\n\n for (const statement of program.body) {\n if (statement.type === \"ExportDefaultDeclaration\") {\n shape.renders = true;\n continue;\n }\n\n // `export * from \"./guard\"` cannot re-export a default — the language\n // excludes it — but it CAN contribute `middleware`, and no parse can see\n // through it without resolving and reading another module. Reading it as\n // \"no middleware here\" is exactly the silent unguarding this slice exists\n // to prevent, so it is read as \"possibly\" and fails loudly downstream.\n if (statement.type === \"ExportAllDeclaration\") {\n shape.hasMiddleware = true;\n continue;\n }\n\n if (statement.type !== \"ExportNamedDeclaration\" || statement.exportKind === \"type\") continue;\n\n for (const specifier of statement.specifiers) {\n if (specifier.type !== \"ExportSpecifier\" || specifier.exportKind === \"type\") continue;\n\n const exported =\n specifier.exported.type === \"Identifier\"\n ? specifier.exported.name\n : specifier.exported.value;\n\n if (exported === \"default\") shape.renders = true;\n if (exported === \"middleware\") shape.hasMiddleware = true;\n }\n\n const { declaration } = statement;\n\n if (declaration === null || declaration === undefined) continue;\n\n if (declaration.type === \"VariableDeclaration\") {\n for (const declarator of declaration.declarations) {\n if (declarator.id.type === \"Identifier\" && declarator.id.name === \"middleware\") {\n shape.hasMiddleware = true;\n }\n }\n\n continue;\n }\n\n if (\n (declaration.type === \"FunctionDeclaration\" || declaration.type === \"ClassDeclaration\") &&\n declaration.id?.name === \"middleware\"\n ) {\n shape.hasMiddleware = true;\n }\n }\n\n cache.set(layoutFile, shape);\n\n return shape;\n}\n\n/**\n * Scans both web roots and returns the pages in a defined total order.\n *\n * Zero pages is a legal result, not an error: a project may be configured\n * with web and have nothing to serve yet. What is an error is a `*.page.tsx`\n * with no `route` export, which is refused rather than silently omitted — an\n * artefact that leaves a page out is a page the dev server still serves and\n * production 404s on; two pages claiming one route name, which this refuses\n * to return at all — the alternative is an artefact in which one of them is\n * silently unreachable; a `route` or `prefix` that cannot be read without\n * running the application, which is refused before any page is reported at\n * all; and a page whose layout chain holds more than one RENDERING layout, which\n * the production installer would refuse anyway — discovery refuses it first so\n * that artefact is never produced.\n */\nexport function discoverPages(options: DiscoverPagesOptions): DiscoveredPage[] {\n const { appRoot } = options;\n const srcRoot = path.join(appRoot, options.srcDir ?? \"src\");\n const webRoots = discoverWebRoots(srcRoot);\n const appFile = path.join(srcRoot, \"web\", \"root.tsx\");\n const hasAppFile = isFile(appFile);\n const declarations = new Map<string, RouteExportsReadResult>();\n const layoutShapes = new Map<string, LayoutShape>();\n const relativeToApp = (file: string) => toPosix(path.relative(appRoot, file));\n\n const pages: DiscoveredPage[] = [];\n\n for (const webRoot of webRoots) {\n for (const pageFile of walkFiles(webRoot, (fileName) => fileName.endsWith(\".page.tsx\"))) {\n const { route } = readDeclarations(pageFile, declarations);\n\n if (route === undefined) {\n throw new MissingRouteExportError(relativeToApp(pageFile));\n }\n\n // The policy decides which layout the page RENDERS INSIDE, from the FULL\n // enumerated chain: a layout anywhere on the ancestry path counts, not\n // just one in the page's own directory. Discovery supplies the one fact\n // the rule needs and the pure policy cannot learn — whether each layout\n // renders anything at all.\n const layouts = layoutChainFor(pageFile, webRoot);\n const shapes = layouts.map((layoutFile) => readLayoutShape(layoutFile, layoutShapes));\n const selection = selectPageLayout(\n layouts.map((layout, index) => ({ layout, renders: shapes[index].renders })),\n );\n\n if (selection.type === \"rejected\") {\n throw new NestedLayoutsNotSupportedError(\n relativeToApp(pageFile),\n selection.layouts.map(relativeToApp),\n );\n }\n\n // Every layout that declares a guard, outermost first. Both installers\n // now CONCATENATE the whole chain into the pipeline's single layout slot\n // (`../server/install-page-routes.ts`, `../server/install-page-routes-from-manifest.ts`),\n // so a guard anywhere on the path runs, in this order — which is why the\n // temporary refusal that used to stand here is gone rather than relaxed.\n const middlewareLayouts = layouts.filter((_, index) => shapes[index].hasMiddleware);\n\n // EVERY prefix on the path, outermost first: a `prefix`-only layout is\n // still a segment of the URL, and composing only the rendering layout's\n // would serve the subtree from a path nobody declared.\n const layoutPrefix = layouts.reduce(\n (composed, layoutFile) =>\n composeRoutePath(composed, readDeclarations(layoutFile, declarations).prefix ?? \"/\"),\n \"/\",\n );\n\n pages.push({\n routeName:\n route.name ??\n deriveFallbackRouteName({\n routePath: route.path,\n sourceFile: relativeToApp(pageFile),\n }),\n routePath: composeRoutePath(layoutPrefix, route.path),\n pageFile,\n webRoot,\n layouts,\n middlewareLayouts,\n ...(hasAppFile ? { appFile } : {}),\n });\n }\n }\n\n pages.sort(comparePages);\n\n assertUniqueRouteNames(pages, appRoot);\n\n return pages;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmGA,IAAa,8BAAb,cAAiD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wBAAwB,cAAc,QAAQ,CAAC;EAQ3D,MAAM,UAAU,eAAe,UAAU,OAAO;EAChD,MAAM,SAAS,QAAQ,KAAK,eAAe,gBAAgB,YAAY,YAAY,CAAC;EACpF,MAAM,YAAY,iBAChB,QAAQ,KAAK,QAAQ,WAAW;GAAE;GAAQ,SAAS,OAAO,MAAM,CAAC;EAAQ,EAAE,CAC7E;EAEA,IAAI,UAAU,SAAS,YACrB,MAAM,IAAI,+BACR,cAAc,QAAQ,GACtB,UAAU,QAAQ,IAAI,aAAa,CACrC;EAQF,MAAM,oBAAoB,QAAQ,QAAQ,GAAG,UAAU,OAAO,MAAM,CAAC,aAAa;EAKlF,MAAM,eAAe,QAAQ,QAC1B,UAAU,eACT,iBAAiB,UAAU,iBAAiB,YAAY,YAAY,CAAC,CAAC,UAAU,GAAG,GACrF,GACF;EAEA,MAAM,KAAK;GACT,WACE,MAAM,QACN,wBAAwB;IACtB,WAAW,MAAM;IACjB,YAAY,cAAc,QAAQ;GACpC,CAAC;GACH,WAAW,iBAAiB,cAAc,MAAM,IAAI;GACpD;GACA;GACA;GACA;GACA,GAAI,aAAa,EAAE,QAAQ,IAAI,CAAC;EAClC,CAAC;CACH;CAGF,MAAM,KAAK,YAAY;CAEvB,uBAAuB,OAAO,OAAO;CAErC,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"discover-pages.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/build/discover-pages.ts"],"sourcesContent":["/**\n * Static discovery of the application's page graph — the ONE scan every\n * provider shares.\n *\n * This module has a single responsibility: look at the filesystem and produce\n * the recipe. It writes nothing, knows nothing about the generated barrel, and\n * imports neither Vite nor a single application module. Everything that turns\n * the recipe into an artefact (the production barrel, the dev plugin, the\n * generated client entry) lives with that artefact and consumes\n * {@link discoverPages}.\n *\n * The reason it is one module rather than one function per consumer: two\n * scanners that agree today drift tomorrow, and a page that exists for the\n * server but not the client is the silent failure that costs a day to find.\n * Sharing the scan makes that disagreement impossible by construction instead\n * of catchable by test.\n *\n * \"Static\" means WITHOUT RUNNING THE APPLICATION — this module globs\n * `*.page.tsx`, `layout.tsx` and `root.tsx`, and reads each page's declared\n * `route` and each layout's declared `prefix` by PARSING the source\n * ({@link readRouteExports}). It still imports no application module.\n *\n * An explicit `route` export wins. Otherwise the URL is derived from the page's\n * path beneath `src/web`: directories contribute segments, `(groups)` do not,\n * `index.page.tsx` claims its directory, and `[id]` becomes `:id`. A layout\n * `prefix` replaces its own directory segment. The same recipe is emitted to\n * every provider so build and boot cannot drift.\n *\n * Discovery also CLASSIFIES each layout — does its module have a default\n * export, does it export `middleware` — because the layout policy\n * ({@link \"../routing/layout-policy.ts\"}) owns the rule but may not touch a\n * filesystem to learn the facts the rule needs. That classification is another\n * parse, never an import: a layout is read exactly the way a page's `route` is.\n *\n * And it CHECKS the page's `metadata` keys ({@link UnknownMetadataKeyError}) —\n * see that error and {@link readMetadataKeys} for why a type alone does not\n * close that hole.\n */\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { parse } from \"@babel/parser\";\nimport { composeRoutePath } from \"../routing/compose-route-path\";\n// `../server/not-found-page` is imported for its CONSTANTS and its filename\n// predicate only — that module has no runtime imports of its own, precisely so\n// this edge cannot drag the render pipeline into the build. What a not-found\n// page is, and what identity it carries, is decided in one place for discovery\n// and both installers.\nimport {\n isNotFoundPageFile,\n NotFoundPageDeclaresRouteError,\n NOT_FOUND_ROUTE_NAME,\n NOT_FOUND_ROUTE_PATH,\n} from \"../server/not-found-page\";\n// The metadata key set, as VALUES. `../metadata` is a types-plus-constants\n// module with no runtime imports of its own (both its imports are `import\n// type`), so this costs the build nothing and buys the one thing a parse cannot\n// get from a type: the list of keys a page is allowed to write.\nimport { METADATA_KEYS, OPEN_GRAPH_KEYS, TWITTER_KEYS } from \"../metadata\";\nimport { NestedLayoutsNotSupportedError, selectPageLayout } from \"../routing/layout-policy\";\nimport {\n deriveFilesystemRouteName,\n deriveFilesystemRoutePath,\n} from \"../routing/filesystem-route\";\nimport { deriveFallbackRouteName } from \"../routing/route-identity\";\nimport { assertPageHasDefaultExport } from \"./page-default-export\";\nimport type { RouteExportsReadResult } from \"./read-route-exports\";\nimport { NonLiteralRouteExportError, readRouteExports } from \"./read-route-exports\";\n\nexport type DiscoverPagesOptions = {\n /** Absolute path to the application root (where `package.json` lives). */\n appRoot: string;\n /** Source directory name under `appRoot`; defaults to `\"src\"`. */\n srcDir?: string;\n};\n\nexport type DiscoveredRoutablePage = {\n /** A browsable page. Error pages are deliberately a different discovery kind. */\n type: \"page\";\n /**\n * The page's route name: the `name` its `route` export declares, or its\n * filesystem identity as dotted segments, with groups omitted.\n *\n * Unique across the whole graph — {@link discoverPages} refuses to return a\n * result where it is not.\n */\n routeName: string;\n /**\n * The page's effective route path. Explicit routes retain their existing\n * layout-prefix composition. Derived routes use filesystem segments, with\n * each declared layout prefix replacing that layout directory's segment.\n * Always `/`-prefixed.\n */\n routePath: string;\n /** Absolute path to the `*.page.tsx` file. */\n pageFile: string;\n /** The web root this page was found under — the root its layout chain climbs to. */\n webRoot: string;\n /** Absolute paths of every `layout.tsx` from the web root down to the page's own directory, OUTERMOST FIRST. */\n layouts: string[];\n /**\n * The page's middleware chain: the subset of {@link layouts} whose modules\n * export `middleware`, OUTERMOST FIRST — the order they must run in.\n *\n * Source files rather than the middleware values themselves, because\n * discovery never runs application code: this says WHICH layouts contribute a\n * guard, and the consumer that already loads those modules reads the values\n * off them.\n *\n * Empty when no layout on the path declares middleware, which is the common\n * case; a page with no layouts always has an empty chain.\n */\n middlewareLayouts: string[];\n /** Absolute path to the global `root.tsx` every page renders inside, when it exists. */\n appFile?: string;\n};\n\n/** The one application error boundary. It deliberately has no route identity. */\nexport type DiscoveredErrorPage = {\n type: \"error\";\n /** Absolute path to the sole `error.page.tsx` beneath `src/web`. */\n pageFile: string;\n webRoot: string;\n appFile?: string;\n};\n\n/** The complete static web graph: routable leaves plus the optional error boundary. */\nexport type DiscoveredPage = DiscoveredRoutablePage | DiscoveredErrorPage;\n\nexport function isDiscoveredRoutablePage(page: DiscoveredPage): page is DiscoveredRoutablePage {\n return page.type === \"page\";\n}\n\nexport function isErrorPageFile(file: string): boolean {\n return path.basename(file) === \"error.page.tsx\";\n}\n\nexport class DuplicateErrorPageError extends Error {\n public constructor(firstFile: string, secondFile: string) {\n super(\n `Two error pages were found: \"${firstFile}\" and \"${secondFile}\". An application may own exactly one \\`error.page.tsx\\` anywhere beneath src/web.`,\n );\n this.name = \"DuplicateErrorPageError\";\n }\n}\n\nexport class ErrorPageDeclaresRouteError extends Error {\n public constructor(pageFile: string) {\n super(\n `The error page \"${pageFile}\" exports \\`route\\`. error.page.tsx is an error boundary, not a browsable page; remove the route export.`,\n );\n this.name = \"ErrorPageDeclaresRouteError\";\n }\n}\n\n/** Raised when two pages claim one route name. */\nexport class DuplicatePageRouteNameError extends Error {\n public constructor(\n public readonly routeName: string,\n public readonly firstFile: string,\n public readonly secondFile: string,\n ) {\n super(\n `Two pages resolve to the same route name \"${routeName}\": \"${firstFile}\" and ` +\n `\"${secondFile}\". A route name identifies exactly one page, so the second ` +\n \"page would be unreachable. To fix: rename one of the files, or move it so \" +\n \"its directory gives it a different route name.\",\n );\n this.name = \"DuplicatePageRouteNameError\";\n }\n}\n\n/** Raised when two different page files resolve to one effective URL. */\nexport class DuplicatePageRoutePathError extends Error {\n public constructor(\n public readonly routePath: string,\n public readonly firstFile: string,\n public readonly secondFile: string,\n ) {\n super(\n `Two pages resolve to the same route path \"${routePath}\": \"${firstFile}\" and ` +\n `\"${secondFile}\". Each URL may identify exactly one page. Rename or move one file, ` +\n \"or give one page an explicit route with a different path.\",\n );\n this.name = \"DuplicatePageRoutePathError\";\n }\n}\n\nexport function toPosix(value: string): string {\n return value.replace(/\\\\/g, \"/\");\n}\n\nfunction isDirectory(candidate: string): boolean {\n try {\n return fs.statSync(candidate).isDirectory();\n } catch {\n return false;\n }\n}\n\nexport function isFile(candidate: string): boolean {\n try {\n return fs.statSync(candidate).isFile();\n } catch {\n return false;\n }\n}\n\n/**\n * The page root. It is optional; a project without it has zero pages, which is\n * a legal empty state.\n */\nexport function discoverWebRoots(srcRoot: string): string[] {\n const webRoot = path.join(srcRoot, \"web\");\n\n return isDirectory(webRoot) ? [webRoot] : [];\n}\n\nfunction byName(left: { name: string }, right: { name: string }): number {\n return left.name < right.name ? -1 : left.name > right.name ? 1 : 0;\n}\n\nexport type DiscoveredPageFile = {\n /** Absolute path to the `*.page.tsx` file. */\n pageFile: string;\n /** The web root ({@link discoverWebRoots}) this page was found under. */\n webRoot: string;\n};\n\n/**\n * The subject list: every `*.page.tsx` under the page root, one call for the\n * whole graph.\n *\n * Unlike {@link discoverPages}, this reads no `route` or `prefix` export and\n * throws on nothing — it answers only \"which page files exist\", so a provider\n * that still resolves a page's route by its own means (dev's\n * `ssrLoadModule`-driven installer, chiefly) can share the walk without\n * inheriting the static-parsing refusals that answering \"what route is this\"\n * requires.\n */\nexport function discoverPageFiles(srcRoot: string): DiscoveredPageFile[] {\n const found: DiscoveredPageFile[] = [];\n\n for (const webRoot of discoverWebRoots(srcRoot)) {\n for (const pageFile of walkFiles(webRoot, (fileName) => fileName.endsWith(\".page.tsx\"))) {\n found.push({ pageFile, webRoot });\n }\n }\n\n return found;\n}\n\n/** Every file under `dir` (recursive) whose name matches `predicate`. */\nexport function walkFiles(dir: string, predicate: (fileName: string) => boolean): string[] {\n const found: string[] = [];\n\n for (const entry of fs.readdirSync(dir, { withFileTypes: true }).sort(byName)) {\n const full = path.join(dir, entry.name);\n\n if (entry.isDirectory()) {\n found.push(...walkFiles(full, predicate));\n } else if (entry.isFile() && predicate(entry.name)) {\n found.push(full);\n }\n }\n\n return found;\n}\n\n/**\n * A page's layout chain: every `layout.tsx` in the directories from its web\n * root down to its own directory, OUTERMOST FIRST.\n *\n * Dev's installer reads only the nearest layout today, because its page module\n * triple holds a single layout; the recipe carries the whole chain so the\n * runtime side can compose\n * nested layouts without a second discovery pass. The nearest layout is always\n * the LAST element, so a consumer that still wants dev's one-layout behaviour\n * reads `layouts.at(-1)`.\n */\nexport function layoutChainFor(pageFile: string, webRoot: string): string[] {\n const chain: string[] = [];\n const relativeDir = path.relative(webRoot, path.dirname(pageFile));\n const segments = relativeDir === \"\" ? [] : relativeDir.split(path.sep);\n\n let current = webRoot;\n\n for (let index = 0; index <= segments.length; index++) {\n if (index > 0) {\n current = path.join(current, segments[index - 1]);\n }\n\n const candidate = path.join(current, \"layout.tsx\");\n\n if (isFile(candidate)) {\n chain.push(candidate);\n }\n }\n\n return chain;\n}\n\nfunction compareStrings(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0;\n}\n\n/**\n * The total order every consumer sees, and the reason discovery returns an\n * array rather than a set: the page's SOURCE FILE PATH, lexicographic, POSIX.\n *\n * Serialization order only; matching precedence is a property of the route\n * grammar, not of this array.\n *\n * The file path rather than the route path, now that the route is the declared\n * one: a page's route can be rewritten by editing one line, which would reorder\n * an artefact that has not otherwise changed, while the file it lives in is the\n * stable identity the artefact is built from. It also carries no suggestion of\n * precedence — nobody reads \"sorted by file name\" as \"most specific first\",\n * which is the misreading a route-path order invites.\n *\n * Lexicographic because it is byte-comparable output across every provider,\n * which keeps diffs stable and keeps filesystem enumeration order out of the\n * artefact: two machines that list a directory differently must still produce\n * byte-identical output, or a build is only reproducible by luck.\n */\nfunction comparePages(left: DiscoveredPage, right: DiscoveredPage): number {\n return compareStrings(toPosix(left.pageFile), toPosix(right.pageFile));\n}\n\nfunction assertUniqueRouteNames(pages: readonly DiscoveredRoutablePage[], appRoot: string): void {\n const fileByRouteName = new Map<string, string>();\n\n for (const page of pages) {\n const existing = fileByRouteName.get(page.routeName);\n const relative = toPosix(path.relative(appRoot, page.pageFile));\n\n if (existing !== undefined) {\n throw new DuplicatePageRouteNameError(page.routeName, existing, relative);\n }\n\n fileByRouteName.set(page.routeName, relative);\n }\n}\n\n/**\n * A page's declared `route.path` is a choice its author made deliberately, so\n * two pages that both declare the same path are the author's call, not an\n * accident — {@link assertUniqueRouteNames} is what keeps each of them\n * reachable by name. What this refuses is a COLLISION NOBODY CHOSE: at least\n * one side's path is filesystem-derived, which is exactly the case a rename\n * or a new file can produce without anyone noticing two pages now answer the\n * same URL. The reserved not-found path (`\"*\"`) is never a candidate here\n * either way — it identifies no browsable URL, and {@link assertUniqueRouteNames}\n * already refuses a second `404.page.tsx` by its own reserved name.\n */\nfunction assertUniqueRoutePaths(\n pages: readonly DiscoveredRoutablePage[],\n appRoot: string,\n explicitFiles: ReadonlySet<string>,\n): void {\n const fileByRoutePath = new Map<string, string>();\n\n for (const page of pages) {\n if (page.routePath === NOT_FOUND_ROUTE_PATH) continue;\n\n const existing = fileByRoutePath.get(page.routePath);\n const relative = toPosix(path.relative(appRoot, page.pageFile));\n\n if (existing !== undefined && !(explicitFiles.has(existing) && explicitFiles.has(relative))) {\n throw new DuplicatePageRoutePathError(page.routePath, existing, relative);\n }\n\n if (existing === undefined) fileByRoutePath.set(page.routePath, relative);\n }\n}\n\n/** One key a page's `metadata` declares that nothing reads, and where it is written. */\nexport type UnknownMetadataKey = {\n /** The object it was declared in: `metadata`, `metadata.openGraph`, `metadata.twitter`. */\n container: string;\n /** The key exactly as the page wrote it. */\n key: string;\n /** 1-based line in the page file, so the message points at the character that is wrong. */\n line: number;\n /** The known key it is within two edits of, when there is one. Usually the whole answer. */\n suggestion?: string;\n};\n\n/**\n * Raised when a page's `metadata` export declares a key nothing reads.\n *\n * THE POINT OF THIS ERROR IS THE UNANNOTATED CASE. A page that writes\n * `export const metadata: PageMetadata = { tittle: \"x\" }` is already refused by\n * TypeScript, and if that were the whole story this class would not need to\n * exist. But the annotation is optional, nobody writes it, and\n * `export const metadata = { tittle: \"x\" }` is a perfectly well-typed program:\n * the compiler infers `{ tittle: string }`, has nothing to check it against, and\n * says nothing. The page is then served with no `<title>` — not a wrong title, a\n * missing one — and no error is raised anywhere, at build or at runtime, ever.\n *\n * So the check lives HERE instead, at the gate every page already passes\n * through: a page that silently omits requested metadata is worse than a build\n * that stops and says which line to fix.\n *\n * The alternative considered and rejected was a `defineMetadata({...})` wrapper,\n * which would infer the type for free. It also puts framework ceremony in every\n * page, and a page is meant to be two lines of framework surface (canon\n * `6ea0662f`). The gate gets the same safety without spending that.\n */\nexport class UnknownMetadataKeyError extends Error {\n public constructor(\n public readonly pageFile: string,\n public readonly unknownKeys: readonly UnknownMetadataKey[],\n ) {\n const findings = unknownKeys\n .map(({ container, key, line, suggestion }) => {\n const where = `line ${line}: \\`${container}.${key}\\` — no such key.`;\n\n return suggestion === undefined ? where : `${where} Did you mean \\`${suggestion}\\`?`;\n })\n .join(\"\\n \");\n\n super(\n `The \\`metadata\\` export of \"${pageFile}\" declares a key nothing reads:\\n ${findings}\\n` +\n \"Nothing writes an unknown key to `<head>`, so the tag it was meant to produce would \" +\n \"simply be absent from every response, with no error at build time or at runtime. The \" +\n \"build refuses it here instead.\\n\" +\n ` Known keys: ${METADATA_KEYS.join(\", \")}.\\n` +\n ` Inside \\`openGraph\\`: ${OPEN_GRAPH_KEYS.join(\", \")}.\\n` +\n ` Inside \\`twitter\\`: ${TWITTER_KEYS.join(\", \")}.\\n` +\n \"Annotating the export — `export const metadata: PageMetadata = { … }` — gets you the \" +\n \"same list as autocomplete in the editor, before the build runs.\",\n );\n this.name = \"UnknownMetadataKeyError\";\n }\n}\n\n/**\n * The AST types, derived from `parse`'s own return type rather than imported\n * from `@babel/types`, for the reason `read-route-exports.ts` gives: the parser\n * resolves its own copy of that package and nodes from one copy are not\n * assignable to the identical types from the other.\n */\ntype PageStatement = ReturnType<typeof parse>[\"program\"][\"body\"][number];\ntype PageExpression = Extract<PageStatement, { type: \"ExpressionStatement\" }>[\"expression\"];\ntype PageObjectExpression = Extract<PageExpression, { type: \"ObjectExpression\" }>;\ntype PageObjectProperty = Extract<\n PageObjectExpression[\"properties\"][number],\n { type: \"ObjectProperty\" }\n>;\ntype PageValueNode = PageObjectProperty[\"value\"];\n\n/** `as const`, `satisfies`, `!` and parentheses wrap a value without changing it. */\nfunction unwrapValue(node: PageValueNode): PageValueNode {\n switch (node.type) {\n case \"TSAsExpression\":\n case \"TSSatisfiesExpression\":\n case \"TSNonNullExpression\":\n case \"TypeCastExpression\":\n case \"ParenthesizedExpression\":\n return unwrapValue(node.expression);\n default:\n return node;\n }\n}\n\n/** Levenshtein distance — small strings, so the plain two-row table is the whole cost. */\nfunction editDistance(left: string, right: string): number {\n let previous = Array.from({ length: right.length + 1 }, (_, index) => index);\n\n for (let row = 1; row <= left.length; row++) {\n const current = [row];\n\n for (let column = 1; column <= right.length; column++) {\n const substitution = previous[column - 1] + (left[row - 1] === right[column - 1] ? 0 : 1);\n current[column] = Math.min(substitution, previous[column] + 1, current[column - 1] + 1);\n }\n\n previous = current;\n }\n\n return previous[right.length];\n}\n\n/**\n * The known key the written one was probably meant to be.\n *\n * Two edits, because that covers the typos this exists for — `tittle`,\n * `descriptoin`, `keywrods` — without reaching so far that `image` gets\n * suggested for `alt`. Case is ignored first, so `Title` resolves exactly.\n */\nfunction suggestKey(written: string, known: readonly string[]): string | undefined {\n const lowered = written.toLowerCase();\n const sameLetters = known.find((candidate) => candidate.toLowerCase() === lowered);\n\n if (sameLetters !== undefined) return sameLetters;\n\n let best: string | undefined;\n let bestDistance = Number.POSITIVE_INFINITY;\n\n for (const candidate of known) {\n const distance = editDistance(lowered, candidate.toLowerCase());\n\n if (distance < bestDistance) {\n best = candidate;\n bestDistance = distance;\n }\n }\n\n return bestDistance <= 2 ? best : undefined;\n}\n\n/** The name an object key denotes, or `undefined` when knowing it needs evaluation. */\nfunction propertyKeyName(property: PageObjectProperty): string | undefined {\n if (property.computed) return undefined;\n\n const { key } = property;\n\n if (key.type === \"Identifier\") return key.name;\n if (key.type === \"StringLiteral\") return key.value;\n\n return undefined;\n}\n\n/** The nested objects that carry a key set of their own. */\nconst NESTED_METADATA_KEYS: Record<string, readonly string[]> = {\n openGraph: OPEN_GRAPH_KEYS,\n twitter: TWITTER_KEYS,\n};\n\n/**\n * Every unknown key in one metadata object literal, and in the `openGraph` /\n * `twitter` literals inside it.\n *\n * A SPREAD does not suppress the check, unlike the route reader's rule: a\n * spread can only ADD keys, and no value it contributes can make a key written\n * out beside it correct. A COMPUTED key is skipped — its name is not knowable\n * without running the page, and refusing what cannot be read would fail builds\n * that are fine. Both are silence in the narrow places where the parse genuinely\n * does not know, and the annotation is the second net there.\n */\nfunction collectUnknownKeys(\n object: PageObjectExpression,\n allowed: readonly string[],\n container: string,\n into: UnknownMetadataKey[],\n): void {\n for (const property of object.properties) {\n if (property.type === \"SpreadElement\") continue;\n\n const key = propertyKeyName(property as PageObjectProperty);\n\n if (key === undefined) continue;\n\n if (!allowed.includes(key)) {\n const suggestion = suggestKey(key, allowed);\n\n into.push({\n container,\n key,\n line: property.loc?.start.line ?? 0,\n ...(suggestion === undefined ? {} : { suggestion }),\n });\n\n continue;\n }\n\n const nested = container === \"metadata\" ? NESTED_METADATA_KEYS[key] : undefined;\n\n if (nested === undefined || property.type !== \"ObjectProperty\") continue;\n\n const value = unwrapValue(property.value);\n\n if (value.type === \"ObjectExpression\") {\n collectUnknownKeys(value, nested, `${container}.${key}`, into);\n }\n }\n}\n\n/**\n * Every object literal a function form RETURNS, without descending into\n * functions nested inside it — a callback's return value is not the metadata.\n *\n * A generic walk rather than a statement-by-statement one because a `return` is\n * legal anywhere a statement is: inside an `if`, a `switch`, a `try`. Enumerating\n * the statement types that may contain one is a list that is wrong the moment\n * the language grows.\n */\nfunction collectReturnedObjects(node: unknown, into: PageObjectExpression[]): void {\n if (node === null || typeof node !== \"object\") return;\n\n if (Array.isArray(node)) {\n for (const item of node) collectReturnedObjects(item, into);\n\n return;\n }\n\n const candidate = node as { type?: string; argument?: unknown };\n\n if (\n candidate.type === \"FunctionDeclaration\" ||\n candidate.type === \"FunctionExpression\" ||\n candidate.type === \"ArrowFunctionExpression\" ||\n candidate.type === \"ObjectMethod\" ||\n candidate.type === \"ClassMethod\"\n ) {\n return;\n }\n\n if (candidate.type === \"ReturnStatement\") {\n if (candidate.argument === null || candidate.argument === undefined) return;\n\n const returned = unwrapValue(candidate.argument as PageValueNode);\n\n if (returned.type === \"ObjectExpression\") into.push(returned);\n\n // Not descending into the returned value: a `return` inside it belongs to a\n // function this walk is deliberately not entering.\n return;\n }\n\n for (const value of Object.values(node as Record<string, unknown>)) {\n collectReturnedObjects(value, into);\n }\n}\n\n/** The metadata object literals one `metadata` export declares, if any can be seen at all. */\nfunction metadataObjectsOf(init: PageValueNode): PageObjectExpression[] {\n const value = unwrapValue(init);\n\n if (value.type === \"ObjectExpression\") return [value];\n\n if (value.type === \"ArrowFunctionExpression\" || value.type === \"FunctionExpression\") {\n const body = unwrapValue(value.body as PageValueNode);\n\n // The concise arrow body — `({ data }) => ({ title: data.name })`, which is\n // how every function-form metadata export in the reference app is written.\n if (body.type === \"ObjectExpression\") return [body];\n\n const returned: PageObjectExpression[] = [];\n\n collectReturnedObjects(value.body, returned);\n\n return returned;\n }\n\n // `export const metadata = buildMetadata()`, or a bare identifier: the keys\n // are not in this file. Silent by design — see `collectUnknownKeys`.\n return [];\n}\n\n/**\n * The unknown keys a page's `metadata` export declares, read by PARSING — the\n * same rule the rest of this module lives by, and the reason this check can run\n * before anything is built.\n *\n * Empty for a page with no `metadata` export, for one whose metadata is a value\n * this file cannot see into, and for a correct one.\n */\nexport function readMetadataKeys(pageFile: string, source: string): UnknownMetadataKey[] {\n let program: ReturnType<typeof parse>[\"program\"];\n\n try {\n program = parse(source, {\n sourceType: \"module\",\n plugins: [\"typescript\", \"jsx\"],\n errorRecovery: false,\n }).program;\n } catch (error) {\n throw new Error(\n `Cannot read the \\`metadata\\` export of \"${pageFile}\": the file could not be parsed ` +\n `(${(error as Error).message}). Fix the syntax error and the build will continue.`,\n );\n }\n\n const unknownKeys: UnknownMetadataKey[] = [];\n\n for (const statement of program.body) {\n if (statement.type !== \"ExportNamedDeclaration\" || statement.exportKind === \"type\") continue;\n\n const { declaration } = statement;\n\n if (declaration?.type !== \"VariableDeclaration\") continue;\n\n for (const declarator of declaration.declarations) {\n if (declarator.id.type !== \"Identifier\" || declarator.id.name !== \"metadata\") continue;\n if (declarator.init === null || declarator.init === undefined) continue;\n\n for (const object of metadataObjectsOf(declarator.init)) {\n collectUnknownKeys(object, METADATA_KEYS, \"metadata\", unknownKeys);\n }\n }\n }\n\n return unknownKeys;\n}\n\n/**\n * The declared exports of one file, or a thrown\n * {@link NonLiteralRouteExportError} when they cannot be read without running\n * the application. Layouts are read once per run and remembered: a layout is\n * the nearest one for every page beside it, and parsing it once per page would\n * be the same answer bought repeatedly.\n *\n * `source` is the file's text when the caller already holds it — the page loop\n * reads each page once and spends that read on both the route declarations and\n * the metadata check, rather than opening the same file twice.\n */\nfunction readDeclarations(\n sourceFile: string,\n cache: Map<string, RouteExportsReadResult>,\n source?: string,\n) {\n let result = cache.get(sourceFile);\n\n if (result === undefined) {\n result = readRouteExports(sourceFile, source);\n cache.set(sourceFile, result);\n }\n\n if (!result.ok) {\n throw new NonLiteralRouteExportError(result.rejection);\n }\n\n return result;\n}\n\n/**\n * What a layout DOES, read by parsing it — the facts the layout policy's rule\n * needs and, being a pure module, cannot go and find for itself.\n */\ntype LayoutShape = {\n /**\n * Whether the module has a default export — the export that puts an element\n * in the document, and therefore the one thing that makes a layout count\n * against the single-rendering-layout rule.\n */\n renders: boolean;\n /** Whether the module exports `middleware`, or might via a re-export this cannot see through. */\n hasMiddleware: boolean;\n};\n\n/**\n * Parses one layout and reports its shape. Remembered per run for the same\n * reason declarations are: a layout is on the path of every page beneath it.\n */\nfunction readLayoutShape(layoutFile: string, cache: Map<string, LayoutShape>): LayoutShape {\n const cached = cache.get(layoutFile);\n\n if (cached !== undefined) return cached;\n\n const source = fs.readFileSync(layoutFile, \"utf-8\");\n let program: ReturnType<typeof parse>[\"program\"];\n\n try {\n program = parse(source, {\n sourceType: \"module\",\n // Every file this reads is a layout, i.e. `.tsx`.\n plugins: [\"typescript\", \"jsx\"],\n errorRecovery: false,\n }).program;\n } catch (error) {\n throw new Error(\n `Cannot read the exports of \"${layoutFile}\": the file could not be parsed ` +\n `(${(error as Error).message}). Fix the syntax error and the build will continue.`,\n );\n }\n\n const shape: LayoutShape = { renders: false, hasMiddleware: false };\n\n for (const statement of program.body) {\n if (statement.type === \"ExportDefaultDeclaration\") {\n shape.renders = true;\n continue;\n }\n\n // `export * from \"./guard\"` cannot re-export a default — the language\n // excludes it — but it CAN contribute `middleware`, and no parse can see\n // through it without resolving and reading another module. Reading it as\n // \"no middleware here\" is exactly the silent unguarding this slice exists\n // to prevent, so it is read as \"possibly\" and fails loudly downstream.\n if (statement.type === \"ExportAllDeclaration\") {\n shape.hasMiddleware = true;\n continue;\n }\n\n if (statement.type !== \"ExportNamedDeclaration\" || statement.exportKind === \"type\") continue;\n\n for (const specifier of statement.specifiers) {\n if (specifier.type !== \"ExportSpecifier\" || specifier.exportKind === \"type\") continue;\n\n const exported =\n specifier.exported.type === \"Identifier\"\n ? specifier.exported.name\n : specifier.exported.value;\n\n if (exported === \"default\") shape.renders = true;\n if (exported === \"middleware\") shape.hasMiddleware = true;\n }\n\n const { declaration } = statement;\n\n if (declaration === null || declaration === undefined) continue;\n\n if (declaration.type === \"VariableDeclaration\") {\n for (const declarator of declaration.declarations) {\n if (declarator.id.type === \"Identifier\" && declarator.id.name === \"middleware\") {\n shape.hasMiddleware = true;\n }\n }\n\n continue;\n }\n\n if (\n (declaration.type === \"FunctionDeclaration\" || declaration.type === \"ClassDeclaration\") &&\n declaration.id?.name === \"middleware\"\n ) {\n shape.hasMiddleware = true;\n }\n }\n\n cache.set(layoutFile, shape);\n\n return shape;\n}\n\n/**\n * Scans the page root and returns the pages in a defined total order.\n *\n * Zero pages is a legal result, not an error: a project may be configured\n * with web and have nothing to serve yet. What is an error is a `*.page.tsx`\n * with a route or metadata export that cannot be read statically; two pages\n * claiming one effective path or route name, which this refuses\n * to return at all — the alternative is an artefact in which one of them is\n * silently unreachable; a `route` or `prefix` that cannot be read without\n * running the application, which is refused before any page is reported at\n * all; a `metadata` export declaring a key nothing reads, which no compiler\n * catches unless the page opted into the type and which otherwise serves a page\n * with a silently missing tag; and a page whose layout chain holds more than one RENDERING layout, which\n * the production installer would refuse anyway — discovery refuses it first so\n * that artefact is never produced.\n */\nexport function discoverPages(options: DiscoverPagesOptions): DiscoveredPage[] {\n const { appRoot } = options;\n const srcRoot = path.join(appRoot, options.srcDir ?? \"src\");\n const webRoots = discoverWebRoots(srcRoot);\n const appFile = path.join(srcRoot, \"web\", \"root.tsx\");\n const hasAppFile = isFile(appFile);\n const declarations = new Map<string, RouteExportsReadResult>();\n const layoutShapes = new Map<string, LayoutShape>();\n const relativeToApp = (file: string) => toPosix(path.relative(appRoot, file));\n\n const pages: DiscoveredPage[] = [];\n const explicitRouteFiles = new Set<string>();\n let errorPage: DiscoveredErrorPage | undefined;\n\n for (const webRoot of webRoots) {\n for (const pageFile of walkFiles(webRoot, (fileName) => fileName.endsWith(\".page.tsx\"))) {\n const pageSource = fs.readFileSync(pageFile, \"utf-8\");\n assertPageHasDefaultExport(relativeToApp(pageFile), pageSource);\n const { route } = readDeclarations(pageFile, declarations, pageSource);\n if (isErrorPageFile(pageFile)) {\n if (route !== undefined) throw new ErrorPageDeclaresRouteError(relativeToApp(pageFile));\n\n if (errorPage !== undefined) {\n throw new DuplicateErrorPageError(relativeToApp(errorPage.pageFile), relativeToApp(pageFile));\n }\n\n errorPage = { type: \"error\", pageFile, webRoot, ...(hasAppFile ? { appFile } : {}) };\n continue;\n }\n const isNotFoundPage = isNotFoundPageFile(pageFile);\n\n // THE NOT-FOUND PAGE IS THE ONE PAGE WITH NO URL, in both directions.\n //\n // Every ordinary page may derive its URL from the filesystem.\n // `404.page.tsx` is reached by NOT matching, so the opposite remains the\n // error: a `route` export here reads as a promise that some path is\n // browsable, which the installers never keep.\n //\n // Discovery still reports it, with the SAME reserved identity both\n // installers register it under, so the emitted artefacts agree with the\n // server about which entry is the not-found page — and so the client\n // registry carries the module the SSR'd document has to hydrate against.\n if (isNotFoundPage && route !== undefined) {\n throw new NotFoundPageDeclaresRouteError(relativeToApp(pageFile));\n }\n\n // The page contract is not only `route`. `metadata` is the other export\n // every page may declare, and it is the one with no compiler behind it\n // unless the author opted in to a type annotation — so it is checked\n // here, by name, exactly like the route above.\n //\n // AFTER the reserved-404 route check on purpose: an impossible 404 route\n // contract is more fundamental than a malformed `<head>` declaration.\n const unknownMetadataKeys = readMetadataKeys(relativeToApp(pageFile), pageSource);\n\n if (unknownMetadataKeys.length > 0) {\n throw new UnknownMetadataKeyError(relativeToApp(pageFile), unknownMetadataKeys);\n }\n\n // The policy decides which layout the page RENDERS INSIDE, from the FULL\n // enumerated chain: a layout anywhere on the ancestry path counts, not\n // just one in the page's own directory. Discovery supplies the one fact\n // the rule needs and the pure policy cannot learn — whether each layout\n // renders anything at all.\n const layouts = layoutChainFor(pageFile, webRoot);\n const shapes = layouts.map((layoutFile) => readLayoutShape(layoutFile, layoutShapes));\n const selection = selectPageLayout(\n layouts.map((layout, index) => ({ layout, renders: shapes[index].renders })),\n );\n\n if (selection.type === \"rejected\") {\n throw new NestedLayoutsNotSupportedError(\n relativeToApp(pageFile),\n selection.layouts.map(relativeToApp),\n );\n }\n\n // Every layout that declares a guard, outermost first. Both installers\n // now CONCATENATE the whole chain into the pipeline's single layout slot\n // (`../server/install-page-routes.ts`, `../server/install-page-routes-from-manifest.ts`),\n // so a guard anywhere on the path runs, in this order — which is why the\n // temporary refusal that used to stand here is gone rather than relaxed.\n const middlewareLayouts = layouts.filter((_, index) => shapes[index].hasMiddleware);\n\n // EVERY prefix on the path, outermost first: a `prefix`-only layout is\n // still a segment of the URL, and composing only the rendering layout's\n // would serve the subtree from a path nobody declared.\n const layoutPrefix = layouts.reduce(\n (composed, layoutFile) =>\n composeRoutePath(composed, readDeclarations(layoutFile, declarations).prefix ?? \"/\"),\n \"/\",\n );\n\n const relativePageFile = toPosix(path.relative(webRoot, pageFile));\n const layoutPrefixes = Object.fromEntries(\n layouts.flatMap((layoutFile) => {\n const prefix = readDeclarations(layoutFile, declarations).prefix;\n if (prefix === undefined) return [];\n\n const directory = toPosix(path.relative(webRoot, path.dirname(layoutFile)));\n return [[directory, prefix]];\n }),\n );\n const effectiveRoutePath = isNotFoundPage\n ? NOT_FOUND_ROUTE_PATH\n : route\n ? composeRoutePath(layoutPrefix, route.path)\n : deriveFilesystemRoutePath({ pageFile: relativePageFile, layoutPrefixes });\n\n if (!isNotFoundPage && route !== undefined) {\n explicitRouteFiles.add(relativeToApp(pageFile));\n }\n\n pages.push({\n type: \"page\",\n routeName: isNotFoundPage\n ? NOT_FOUND_ROUTE_NAME\n : (route?.name ??\n (route\n ? deriveFallbackRouteName({\n routePath: route.path,\n sourceFile: relativeToApp(pageFile),\n })\n : deriveFilesystemRouteName(relativePageFile))),\n // The catch-all, which the client route matcher already understands as\n // a terminal `catch-all` token sorted LAST by specificity\n // (`../client/runtime/matcher.ts`) — so the browser resolves the\n // not-found page for a URL that matched nothing, exactly as the server\n // did, and never in preference to a real page.\n routePath: effectiveRoutePath,\n pageFile,\n webRoot,\n // THE NOT-FOUND PAGE RENDERS INSIDE THE APPLICATION ROOT AND NOTHING\n // ELSE — an EMPTY chain, not the one enumerated above.\n //\n // Both installers render it with `layoutFile: undefined`, deliberately\n // and independently (`../server/install-page-routes.ts`,\n // `../server/install-page-routes-from-manifest.ts`), for the same\n // reason the 404 page takes no loader: a path whose entire job is to\n // handle failure must not depend on chrome that can itself throw,\n // redirect, or need data. Reporting layouts here anyway put them in the\n // client registry and therefore in HYDRATION, so the server rendered\n // `App(Page)` while the browser rebuilt `App(Layout(Page))` — a\n // guaranteed mismatch on the one route nobody is watching, invisible to\n // any application that happens to have no layouts.\n //\n // Aligned by REMOVING them from the client, never by giving them to the\n // server: layouts on the not-found route would make it the most fragile\n // route in the application.\n //\n // The chain above is still enumerated and still validated, so a nested\n // layout on this page's path is refused at build time exactly as it is\n // everywhere else — what changes is only what the page renders inside.\n layouts: isNotFoundPage ? [] : layouts,\n middlewareLayouts: isNotFoundPage ? [] : middlewareLayouts,\n ...(hasAppFile ? { appFile } : {}),\n });\n }\n }\n\n // The error page is captured separately above so a second one can be\n // compared against the first before either is trusted — it joins the\n // returned graph here, once discovery knows there is exactly one.\n if (errorPage !== undefined) pages.push(errorPage);\n\n pages.sort(comparePages);\n\n const routablePages = pages.filter(isDiscoveredRoutablePage);\n assertUniqueRoutePaths(routablePages, appRoot, explicitRouteFiles);\n assertUniqueRouteNames(routablePages, appRoot);\n\n return pages;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgIA,SAAgB,yBAAyB,MAAsD;CAC7F,OAAO,KAAK,SAAS;AACvB;AAEA,SAAgB,gBAAgB,MAAuB;CACrD,OAAO,KAAK,SAAS,IAAI,MAAM;AACjC;AAEA,IAAa,0BAAb,cAA6C,MAAM;CACjD,AAAO,YAAY,WAAmB,YAAoB;EACxD,MACE,gCAAgC,UAAU,SAAS,WAAW,mFAChE;EACA,KAAK,OAAO;CACd;AACF;AAEA,IAAa,8BAAb,cAAiD,MAAM;CACrD,AAAO,YAAY,UAAkB;EACnC,MACE,mBAAmB,SAAS,yGAC9B;EACA,KAAK,OAAO;CACd;AACF;;AAGA,IAAa,8BAAb,cAAiD,MAAM;CAEnC;CACA;CACA;CAHlB,AAAO,YACL,AAAgB,WAChB,AAAgB,WAChB,AAAgB,YAChB;EACA,MACE,6CAA6C,UAAU,MAAM,UAAU,SACjE,WAAW,oLAGnB;EATgB;EACA;EACA;EAQhB,KAAK,OAAO;CACd;AACF;;AAGA,IAAa,8BAAb,cAAiD,MAAM;CAEnC;CACA;CACA;CAHlB,AAAO,YACL,AAAgB,WAChB,AAAgB,WAChB,AAAgB,YAChB;EACA,MACE,6CAA6C,UAAU,MAAM,UAAU,SACjE,WAAW,8HAEnB;EARgB;EACA;EACA;EAOhB,KAAK,OAAO;CACd;AACF;AAEA,SAAgB,QAAQ,OAAuB;CAC7C,OAAO,MAAM,QAAQ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,eAAe;GAC9B,MAAM,SAAS,iBAAiB,YAAY,YAAY,EAAE;GAC1D,IAAI,WAAW,QAAW,OAAO,CAAC;GAGlC,OAAO,CAAC,CADU,QAAQ,KAAK,SAAS,SAAS,KAAK,QAAQ,UAAU,CAAC,CACxD,GAAG,MAAM,CAAC;EAC7B,CAAC,CACH;EACA,MAAM,qBAAqB,uBAEvB,QACE,iBAAiB,cAAc,MAAM,IAAI,IACzC,0BAA0B;GAAE,UAAU;GAAkB;EAAe,CAAC;EAE9E,IAAI,CAAC,kBAAkB,UAAU,QAC/B,mBAAmB,IAAI,cAAc,QAAQ,CAAC;EAGhD,MAAM,KAAK;GACT,MAAM;GACN,WAAW,iBACP,uBACC,OAAO,SACL,QACG,wBAAwB;IACtB,WAAW,MAAM;IACjB,YAAY,cAAc,QAAQ;GACpC,CAAC,IACD,0BAA0B,gBAAgB;GAMpD,WAAW;GACX;GACA;GAsBA,SAAS,iBAAiB,CAAC,IAAI;GAC/B,mBAAmB,iBAAiB,CAAC,IAAI;GACzC,GAAI,aAAa,EAAE,QAAQ,IAAI,CAAC;EAClC,CAAC;CACH;CAMF,IAAI,cAAc,QAAW,MAAM,KAAK,SAAS;CAEjD,MAAM,KAAK,YAAY;CAEvB,MAAM,gBAAgB,MAAM,OAAO,wBAAwB;CAC3D,uBAAuB,eAAe,SAAS,kBAAkB;CACjE,uBAAuB,eAAe,OAAO;CAE7C,OAAO;AACT"}
|
|
@@ -1,4 +1,31 @@
|
|
|
1
|
-
|
|
1
|
+
import { isDiscoveredRoutablePage } from "./discover-pages.mjs";
|
|
2
|
+
|
|
3
|
+
//#region web/src/build/generate-client-registry.ts
|
|
4
|
+
/**
|
|
5
|
+
* The CLIENT half of the build→runtime handoff: the source of a generated
|
|
6
|
+
* module that carries the page graph into the BROWSER.
|
|
7
|
+
*
|
|
8
|
+
* `generate-pages-barrel.ts` is the server half. The two are deliberately not
|
|
9
|
+
* one function, because they want opposite things from the same recipe: the
|
|
10
|
+
* server barrel emits STATIC `import * as` so every page lands in the one
|
|
11
|
+
* server bundle and its route can be read off the module at boot, while the
|
|
12
|
+
* browser must never download page B to render page A — so every module
|
|
13
|
+
* reference here is a dynamic `import()`, and `name`/`path` are baked in as
|
|
14
|
+
* DATA so the client runtime can match a route before loading anything.
|
|
15
|
+
*
|
|
16
|
+
* This function is PURE. It reads no filesystem, writes no file, and does not
|
|
17
|
+
* call {@link discoverPages} — the caller passes the already-discovered graph
|
|
18
|
+
* in. That is what keeps the "one discovery run, one graph" invariant: names
|
|
19
|
+
* and paths agree with the server's because there is only ever one scan, not
|
|
20
|
+
* because two scanners were written to match.
|
|
21
|
+
*
|
|
22
|
+
* Module RESOLUTION is the one thing that legitimately differs between the dev
|
|
23
|
+
* provider and the production provider, so it is injected as
|
|
24
|
+
* {@link GenerateClientRegistryOptions.toImportSpecifier} rather than computed
|
|
25
|
+
* here. No provider-specific data — no Vite ids, no `/@fs/` prefixes, no
|
|
26
|
+
* hashed chunk urls, no HMR metadata — reaches the emitted entry, and every
|
|
27
|
+
* other property stays testable with a trivial mapper.
|
|
28
|
+
*/
|
|
2
29
|
/** The name of the array the generated module exports. */
|
|
3
30
|
const CLIENT_REGISTRY_EXPORT_NAME = "pages";
|
|
4
31
|
/** The specifier the generated module imports its entry type from. */
|
|
@@ -58,36 +85,41 @@ function assertUniqueNames(pages) {
|
|
|
58
85
|
* already module-cached by the bundler, so the correct implementation is to
|
|
59
86
|
* let the cache do the caching.
|
|
60
87
|
*/
|
|
61
|
-
function loadSource(page, toImportSpecifier) {
|
|
62
|
-
const bindings = ["
|
|
88
|
+
function loadSource(page, errorPageFile, toImportSpecifier) {
|
|
89
|
+
const bindings = ["PageModule"];
|
|
63
90
|
const specifiers = [toImportSpecifier(page.pageFile)];
|
|
64
91
|
const layoutBindings = page.layouts.map((layoutFile, index) => {
|
|
65
|
-
bindings.push(`
|
|
92
|
+
bindings.push(`layoutModule${index}`);
|
|
66
93
|
specifiers.push(toImportSpecifier(layoutFile));
|
|
67
|
-
return `
|
|
94
|
+
return `layoutModule${index}`;
|
|
68
95
|
});
|
|
69
96
|
if (page.appFile !== void 0) {
|
|
70
|
-
bindings.push("
|
|
97
|
+
bindings.push("AppModule");
|
|
71
98
|
specifiers.push(toImportSpecifier(page.appFile));
|
|
72
99
|
}
|
|
73
|
-
|
|
100
|
+
if (errorPageFile !== void 0) {
|
|
101
|
+
bindings.push("ErrorPageModule");
|
|
102
|
+
specifiers.push(toImportSpecifier(errorPageFile));
|
|
103
|
+
}
|
|
104
|
+
const app = page.appFile === void 0 ? "" : ", App: AppModule";
|
|
105
|
+
const errorPage = errorPageFile === void 0 ? "" : ", ErrorPage: ErrorPageModule";
|
|
74
106
|
return [
|
|
75
107
|
" load: async () => {",
|
|
76
108
|
` const [${bindings.join(", ")}] = await Promise.all([`,
|
|
77
109
|
...specifiers.map((specifier) => ` import(${quote(specifier)}),`),
|
|
78
110
|
" ]);",
|
|
79
111
|
"",
|
|
80
|
-
` return { Page, layouts: [${layoutBindings.join(", ")}]${app} };`,
|
|
112
|
+
` return { Page: PageModule, layouts: [${layoutBindings.join(", ")}]${app}${errorPage} };`,
|
|
81
113
|
" },"
|
|
82
114
|
];
|
|
83
115
|
}
|
|
84
|
-
function entrySource(page, toImportSpecifier) {
|
|
116
|
+
function entrySource(page, errorPageFile, toImportSpecifier) {
|
|
85
117
|
return [
|
|
86
118
|
" {",
|
|
87
119
|
" type: \"page\",",
|
|
88
120
|
` name: ${quote(page.routeName)},`,
|
|
89
121
|
` path: ${quote(page.routePath)},`,
|
|
90
|
-
...loadSource(page, toImportSpecifier),
|
|
122
|
+
...loadSource(page, errorPageFile, toImportSpecifier),
|
|
91
123
|
" },"
|
|
92
124
|
];
|
|
93
125
|
}
|
|
@@ -100,9 +132,11 @@ function entrySource(page, toImportSpecifier) {
|
|
|
100
132
|
*/
|
|
101
133
|
function generateClientRegistry(options) {
|
|
102
134
|
const { pages, toImportSpecifier } = options;
|
|
103
|
-
|
|
135
|
+
const routablePages = pages.filter(isDiscoveredRoutablePage);
|
|
136
|
+
const errorPageFile = pages.find((page) => page.type === "error")?.pageFile;
|
|
137
|
+
assertUniqueNames(routablePages);
|
|
104
138
|
const declaration = `export const ${CLIENT_REGISTRY_EXPORT_NAME}: readonly ClientPageEntry[] =`;
|
|
105
|
-
if (
|
|
139
|
+
if (routablePages.length === 0) return [
|
|
106
140
|
...HEADER,
|
|
107
141
|
"",
|
|
108
142
|
`${declaration} [];`,
|
|
@@ -112,7 +146,7 @@ function generateClientRegistry(options) {
|
|
|
112
146
|
...HEADER,
|
|
113
147
|
"",
|
|
114
148
|
`${declaration} [`,
|
|
115
|
-
...
|
|
149
|
+
...routablePages.flatMap((page) => entrySource(page, errorPageFile, toImportSpecifier)),
|
|
116
150
|
"];",
|
|
117
151
|
""
|
|
118
152
|
].join("\n");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate-client-registry.mjs","names":[],"sources":["../../../../../../../web/src/build/generate-client-registry.ts"],"sourcesContent":["/**\n * The CLIENT half of the build→runtime handoff: the source of a generated\n * module that carries the page graph into the BROWSER.\n *\n * `generate-pages-barrel.ts` is the server half. The two are deliberately not\n * one function, because they want opposite things from the same recipe: the\n * server barrel emits STATIC `import * as` so every page lands in the one\n * server bundle and its route can be read off the module at boot, while the\n * browser must never download page B to render page A — so every module\n * reference here is a dynamic `import()`, and `name`/`path` are baked in as\n * DATA so the client runtime can match a route before loading anything.\n *\n * This function is PURE. It reads no filesystem, writes no file, and does not\n * call {@link discoverPages} — the caller passes the already-discovered graph\n * in. That is what keeps the \"one discovery run, one graph\" invariant: names\n * and paths agree with the server's because there is only ever one scan, not\n * because two scanners were written to match.\n *\n * Module RESOLUTION is the one thing that legitimately differs between the dev\n * provider and the production provider, so it is injected as\n * {@link GenerateClientRegistryOptions.toImportSpecifier} rather than computed\n * here. No provider-specific data — no Vite ids, no `/@fs/` prefixes, no\n * hashed chunk urls, no HMR metadata — reaches the emitted entry, and every\n * other property stays testable with a trivial mapper.\n */\nimport type { DiscoveredPage } from \"./discover-pages\";\n\nexport type GenerateClientRegistryOptions = {\n /**\n * The discovered page graph, IN THE ORDER DISCOVERY GAVE IT.\n *\n * `discoverPages` already sorts by POSIX source-file path\n * (`discover-pages.ts:368`, comparator at `discover-pages.ts:248-250`), so\n * this emitter preserves that order rather than imposing a second one: two\n * orderings of one graph is exactly the drift the shared scan exists to\n * prevent. Serialization stability only — nothing emitted here implies\n * matching precedence, which is a property of the route grammar.\n */\n pages: readonly DiscoveredPage[];\n /** Maps an absolute source file path to the specifier the emitted module will import. */\n toImportSpecifier: (absoluteFilePath: string) => string;\n};\n\n/** The name of the array the generated module exports. */\nexport const CLIENT_REGISTRY_EXPORT_NAME = \"pages\";\n\n/** The specifier the generated module imports its entry type from. */\nconst CLIENT_RUNTIME_SPECIFIER = \"@warlock.js/web/client/runtime\";\n\n/**\n * Raised when two pages claim one route name.\n *\n * `discoverPages` promises uniqueness already (`discover-pages.ts:370`). This\n * asserts it anyway: the alternative is trusting an upstream promise and\n * emitting a registry in which one page is silently unreachable, which costs\n * far more to diagnose than the check costs to run.\n */\nexport class DuplicateClientPageNameError extends Error {\n public constructor(\n public readonly routeName: string,\n public readonly firstPageFile: string,\n public readonly secondPageFile: string,\n ) {\n super(\n `Two pages claim the client route name \"${routeName}\": \"${firstPageFile}\" and ` +\n `\"${secondPageFile}\". A route name identifies exactly one page, so the second ` +\n \"page would be unreachable in the browser. To fix: rename one page's `route` \" +\n \"export, or move the file so its directory gives it a different route name.\",\n );\n this.name = \"DuplicateClientPageNameError\";\n }\n}\n\n/**\n * Every literal the generator emits goes through here, without exception.\n * Windows separators, quotes and backslashes are all in scope, and a\n * hand-quoted literal that gets one of them wrong fails at bundle time with a\n * parse error no user can act on.\n */\nfunction quote(value: string): string {\n return JSON.stringify(value);\n}\n\nconst HEADER = [\n \"// AUTO-GENERATED by @warlock.js/web — do not edit.\",\n \"// The page graph, compiled into the CLIENT bundle.\",\n \"//\",\n \"// `name` and `path` are baked in as data so the client runtime can match a\",\n \"// route before loading anything; every module reference is a dynamic\",\n \"// `import()` so a page's code is downloaded only when that page is rendered.\",\n `import type { ClientPageEntry } from ${quote(CLIENT_RUNTIME_SPECIFIER)};`,\n];\n\nfunction assertUniqueNames(pages: readonly DiscoveredPage[]): void {\n const pageFileByName = new Map<string, string>();\n\n for (const page of pages) {\n const existing = pageFileByName.get(page.routeName);\n\n if (existing !== undefined) {\n throw new DuplicateClientPageNameError(page.routeName, existing, page.pageFile);\n }\n\n pageFileByName.set(page.routeName, page.pageFile);\n }\n}\n\n/**\n * One entry's `load`.\n *\n * It memoises NOTHING and holds no one-shot state: the runtime calls it again\n * on re-navigation to the same route, and a loader that works once and returns\n * undefined the second time is a silent blank page. Dynamic `import()` is\n * already module-cached by the bundler, so the correct implementation is to\n * let the cache do the caching.\n */\nfunction loadSource(page: DiscoveredPage, toImportSpecifier: (file: string) => string): string[] {\n const bindings = [\"Page\"];\n const specifiers = [toImportSpecifier(page.pageFile)];\n\n // Outermost first, exactly as discovery enumerated the chain — the order IS\n // the nesting, so reordering it would silently reparent the page.\n const layoutBindings = page.layouts.map((layoutFile, index) => {\n bindings.push(`layout${index}`);\n specifiers.push(toImportSpecifier(layoutFile));\n\n return `layout${index}`;\n });\n\n if (page.appFile !== undefined) {\n bindings.push(\"App\");\n specifiers.push(toImportSpecifier(page.appFile));\n }\n\n // `App` is OMITTED, never emitted as `App: undefined`: the runtime validator\n // reads an own `App` key as a promise that a module namespace is behind it.\n const app = page.appFile === undefined ? \"\" : \", App\";\n\n return [\n \" load: async () => {\",\n ` const [${bindings.join(\", \")}] = await Promise.all([`,\n ...specifiers.map((specifier) => ` import(${quote(specifier)}),`),\n \" ]);\",\n \"\",\n ` return { Page, layouts: [${layoutBindings.join(\", \")}]${app} };`,\n \" },\",\n ];\n}\n\nfunction entrySource(\n page: DiscoveredPage,\n toImportSpecifier: (file: string) => string,\n): string[] {\n return [\n \" {\",\n ' type: \"page\",',\n // Verbatim from discovery, both of them. `routePath` in particular is NOT\n // re-derived or re-normalised here: discovery already composed the layout\n // prefix with the declared route, and a second composition is a second\n // convention waiting to disagree with the server's.\n ` name: ${quote(page.routeName)},`,\n ` path: ${quote(page.routePath)},`,\n ...loadSource(page, toImportSpecifier),\n \" },\",\n ];\n}\n\n/**\n * Returns the SOURCE of the client page registry module. Writes nothing.\n *\n * Zero pages is a legal result, not an error, and it is emitted as an explicit\n * empty registry: \"built with web, no pages\" must reach the runtime as a fact\n * rather than as a missing module.\n */\nexport function generateClientRegistry(options: GenerateClientRegistryOptions): string {\n const { pages, toImportSpecifier } = options;\n\n assertUniqueNames(pages);\n\n const declaration = `export const ${CLIENT_REGISTRY_EXPORT_NAME}: readonly ClientPageEntry[] =`;\n\n if (pages.length === 0) {\n return [...HEADER, \"\", `${declaration} [];`, \"\"].join(\"\\n\");\n }\n\n return [\n ...HEADER,\n \"\",\n `${declaration} [`,\n ...pages.flatMap((page) => entrySource(page, toImportSpecifier)),\n \"];\",\n \"\",\n ].join(\"\\n\");\n}\n"],"mappings":";;AA4CA,MAAa,8BAA8B;;AAG3C,MAAM,2BAA2B;;;;;;;;;AAUjC,IAAa,+BAAb,cAAkD,MAAM;CAEpC;CACA;CACA;CAHlB,AAAO,YACL,AAAgB,WAChB,AAAgB,eAChB,AAAgB,gBAChB;EACA,MACE,0CAA0C,UAAU,MAAM,cAAc,SAClE,eAAe,oNAGvB;EATgB;EACA;EACA;EAQhB,KAAK,OAAO;CACd;AACF;;;;;;;AAQA,SAAS,MAAM,OAAuB;CACpC,OAAO,KAAK,UAAU,KAAK;AAC7B;AAEA,MAAM,SAAS;CACb;CACA;CACA;CACA;CACA;CACA;CACA,wCAAwC,MAAM,wBAAwB,EAAE;AAC1E;AAEA,SAAS,kBAAkB,OAAwC;CACjE,MAAM,iCAAiB,IAAI,IAAoB;CAE/C,KAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,WAAW,eAAe,IAAI,KAAK,SAAS;EAElD,IAAI,aAAa,QACf,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AC;EAC/D;EACA;CACF,CAAC,CAAC,KAAK,IAAI;AACb"}
|
|
1
|
+
{"version":3,"file":"generate-client-registry.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/build/generate-client-registry.ts"],"sourcesContent":["/**\r\n * The CLIENT half of the build→runtime handoff: the source of a generated\r\n * module that carries the page graph into the BROWSER.\r\n *\r\n * `generate-pages-barrel.ts` is the server half. The two are deliberately not\r\n * one function, because they want opposite things from the same recipe: the\r\n * server barrel emits STATIC `import * as` so every page lands in the one\r\n * server bundle and its route can be read off the module at boot, while the\r\n * browser must never download page B to render page A — so every module\r\n * reference here is a dynamic `import()`, and `name`/`path` are baked in as\r\n * DATA so the client runtime can match a route before loading anything.\r\n *\r\n * This function is PURE. It reads no filesystem, writes no file, and does not\r\n * call {@link discoverPages} — the caller passes the already-discovered graph\r\n * in. That is what keeps the \"one discovery run, one graph\" invariant: names\r\n * and paths agree with the server's because there is only ever one scan, not\r\n * because two scanners were written to match.\r\n *\r\n * Module RESOLUTION is the one thing that legitimately differs between the dev\r\n * provider and the production provider, so it is injected as\r\n * {@link GenerateClientRegistryOptions.toImportSpecifier} rather than computed\r\n * here. No provider-specific data — no Vite ids, no `/@fs/` prefixes, no\r\n * hashed chunk urls, no HMR metadata — reaches the emitted entry, and every\r\n * other property stays testable with a trivial mapper.\r\n */\r\nimport {\r\n isDiscoveredRoutablePage,\r\n type DiscoveredPage,\r\n type DiscoveredRoutablePage,\r\n} from \"./discover-pages\";\r\n\r\nexport type GenerateClientRegistryOptions = {\r\n /**\r\n * The discovered page graph, IN THE ORDER DISCOVERY GAVE IT.\r\n *\r\n * `discoverPages` already sorts by POSIX source-file path\r\n * (`discover-pages.ts:368`, comparator at `discover-pages.ts:248-250`), so\r\n * this emitter preserves that order rather than imposing a second one: two\r\n * orderings of one graph is exactly the drift the shared scan exists to\r\n * prevent. Serialization stability only — nothing emitted here implies\r\n * matching precedence, which is a property of the route grammar.\r\n */\r\n pages: readonly DiscoveredPage[];\r\n /** Maps an absolute source file path to the specifier the emitted module will import. */\r\n toImportSpecifier: (absoluteFilePath: string) => string;\r\n};\r\n\r\n/** The name of the array the generated module exports. */\r\nexport const CLIENT_REGISTRY_EXPORT_NAME = \"pages\";\r\n\r\n/** The specifier the generated module imports its entry type from. */\r\nconst CLIENT_RUNTIME_SPECIFIER = \"@warlock.js/web/client/runtime\";\r\n\r\n/**\r\n * Raised when two pages claim one route name.\r\n *\r\n * `discoverPages` promises uniqueness already (`discover-pages.ts:370`). This\r\n * asserts it anyway: the alternative is trusting an upstream promise and\r\n * emitting a registry in which one page is silently unreachable, which costs\r\n * far more to diagnose than the check costs to run.\r\n */\r\nexport class DuplicateClientPageNameError extends Error {\r\n public constructor(\r\n public readonly routeName: string,\r\n public readonly firstPageFile: string,\r\n public readonly secondPageFile: string,\r\n ) {\r\n super(\r\n `Two pages claim the client route name \"${routeName}\": \"${firstPageFile}\" and ` +\r\n `\"${secondPageFile}\". A route name identifies exactly one page, so the second ` +\r\n \"page would be unreachable in the browser. To fix: rename one page's `route` \" +\r\n \"export, or move the file so its directory gives it a different route name.\",\r\n );\r\n this.name = \"DuplicateClientPageNameError\";\r\n }\r\n}\r\n\r\n/**\r\n * Every literal the generator emits goes through here, without exception.\r\n * Windows separators, quotes and backslashes are all in scope, and a\r\n * hand-quoted literal that gets one of them wrong fails at bundle time with a\r\n * parse error no user can act on.\r\n */\r\nfunction quote(value: string): string {\r\n return JSON.stringify(value);\r\n}\r\n\r\nconst HEADER = [\r\n \"// AUTO-GENERATED by @warlock.js/web — do not edit.\",\r\n \"// The page graph, compiled into the CLIENT bundle.\",\r\n \"//\",\r\n \"// `name` and `path` are baked in as data so the client runtime can match a\",\r\n \"// route before loading anything; every module reference is a dynamic\",\r\n \"// `import()` so a page's code is downloaded only when that page is rendered.\",\r\n `import type { ClientPageEntry } from ${quote(CLIENT_RUNTIME_SPECIFIER)};`,\r\n];\r\n\r\nfunction assertUniqueNames(pages: readonly DiscoveredRoutablePage[]): void {\r\n const pageFileByName = new Map<string, string>();\r\n\r\n for (const page of pages) {\r\n const existing = pageFileByName.get(page.routeName);\r\n\r\n if (existing !== undefined) {\r\n throw new DuplicateClientPageNameError(page.routeName, existing, page.pageFile);\r\n }\r\n\r\n pageFileByName.set(page.routeName, page.pageFile);\r\n }\r\n}\r\n\r\n/**\r\n * One entry's `load`.\r\n *\r\n * It memoises NOTHING and holds no one-shot state: the runtime calls it again\r\n * on re-navigation to the same route, and a loader that works once and returns\r\n * undefined the second time is a silent blank page. Dynamic `import()` is\r\n * already module-cached by the bundler, so the correct implementation is to\r\n * let the cache do the caching.\r\n */\r\nfunction loadSource(\r\n page: DiscoveredRoutablePage,\r\n errorPageFile: string | undefined,\r\n toImportSpecifier: (file: string) => string,\r\n): string[] {\r\n // These bindings deliberately retain the REAL module namespace objects\r\n // returned by import(). The client lifecycle registers exports on those\r\n // namespaces before the tree builder extracts their default components.\r\n const bindings = [\"PageModule\"];\r\n const specifiers = [toImportSpecifier(page.pageFile)];\r\n\r\n // Outermost first, exactly as discovery enumerated the chain — the order IS\r\n // the nesting, so reordering it would silently reparent the page.\r\n //\r\n // Emitted VERBATIM, including the empty chain discovery reports for the\r\n // not-found page (`./discover-pages.ts`), which is what keeps hydration\r\n // rendering the same `App(Page)` the installers SSR'd. The not-found case is\r\n // NOT re-detected here: a second rule about which page gets layouts is a\r\n // second convention waiting to disagree with the server's, which is the same\r\n // reason `routePath` below is not re-composed either.\r\n const layoutBindings = page.layouts.map((layoutFile, index) => {\r\n bindings.push(`layoutModule${index}`);\r\n specifiers.push(toImportSpecifier(layoutFile));\r\n\r\n return `layoutModule${index}`;\r\n });\r\n\r\n if (page.appFile !== undefined) {\r\n bindings.push(\"AppModule\");\r\n specifiers.push(toImportSpecifier(page.appFile));\r\n }\r\n\r\n if (errorPageFile !== undefined) {\r\n bindings.push(\"ErrorPageModule\");\r\n specifiers.push(toImportSpecifier(errorPageFile));\r\n }\r\n\r\n // `App` is OMITTED, never emitted as `App: undefined`: the runtime validator\r\n // reads an own `App` key as a promise that a module namespace is behind it.\r\n const app = page.appFile === undefined ? \"\" : \", App: AppModule\";\r\n const errorPage = errorPageFile === undefined ? \"\" : \", ErrorPage: ErrorPageModule\";\r\n\r\n return [\r\n \" load: async () => {\",\r\n ` const [${bindings.join(\", \")}] = await Promise.all([`,\r\n ...specifiers.map((specifier) => ` import(${quote(specifier)}),`),\r\n \" ]);\",\r\n \"\",\r\n ` return { Page: PageModule, layouts: [${layoutBindings.join(\", \")}]${app}${errorPage} };`,\r\n \" },\",\r\n ];\r\n}\r\n\r\nfunction entrySource(\r\n page: DiscoveredRoutablePage,\r\n errorPageFile: string | undefined,\r\n toImportSpecifier: (file: string) => string,\r\n): string[] {\r\n return [\r\n \" {\",\r\n ' type: \"page\",',\r\n // Verbatim from discovery, both of them. `routePath` in particular is NOT\r\n // re-derived or re-normalised here: discovery already composed the layout\r\n // prefix with the declared route, and a second composition is a second\r\n // convention waiting to disagree with the server's.\r\n ` name: ${quote(page.routeName)},`,\r\n ` path: ${quote(page.routePath)},`,\r\n ...loadSource(page, errorPageFile, toImportSpecifier),\r\n \" },\",\r\n ];\r\n}\r\n\r\n/**\r\n * Returns the SOURCE of the client page registry module. Writes nothing.\r\n *\r\n * Zero pages is a legal result, not an error, and it is emitted as an explicit\r\n * empty registry: \"built with web, no pages\" must reach the runtime as a fact\r\n * rather than as a missing module.\r\n */\r\nexport function generateClientRegistry(options: GenerateClientRegistryOptions): string {\r\n const { pages, toImportSpecifier } = options;\r\n const routablePages = pages.filter(isDiscoveredRoutablePage);\r\n const errorPageFile = pages.find((page) => page.type === \"error\")?.pageFile;\r\n\r\n assertUniqueNames(routablePages);\r\n\r\n const declaration = `export const ${CLIENT_REGISTRY_EXPORT_NAME}: readonly ClientPageEntry[] =`;\r\n\r\n if (routablePages.length === 0) {\r\n return [...HEADER, \"\", `${declaration} [];`, \"\"].join(\"\\n\");\r\n }\r\n\r\n return [\r\n ...HEADER,\r\n \"\",\r\n `${declaration} [`,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AAkB,QAAW;EAC/B,SAAS,KAAK,iBAAiB;EAC/B,WAAW,KAAK,kBAAkB,aAAa,CAAC;CAClD;CAIA,MAAM,MAAM,KAAK,YAAY,SAAY,KAAK;CAC9C,MAAM,YAAY,kBAAkB,SAAY,KAAK;CAErD,OAAO;EACL;EACA,gBAAgB,SAAS,KAAK,IAAI,EAAE;EACpC,GAAG,WAAW,KAAK,cAAc,kBAAkB,MAAM,SAAS,EAAE,GAAG;EACvE;EACA;EACA,8CAA8C,eAAe,KAAK,IAAI,EAAE,GAAG,MAAM,UAAU;EAC3F;CACF;AACF;AAEA,SAAS,YACP,MACA,eACA,mBACU;CACV,OAAO;EACL;EACA;EAKA,aAAa,MAAM,KAAK,SAAS,EAAE;EACnC,aAAa,MAAM,KAAK,SAAS,EAAE;EACnC,GAAG,WAAW,MAAM,eAAe,iBAAiB;EACpD;CACF;AACF;;;;;;;;AASA,SAAgB,uBAAuB,SAAgD;CACrF,MAAM,EAAE,OAAO,sBAAsB;CACrC,MAAM,gBAAgB,MAAM,OAAO,wBAAwB;CAC3D,MAAM,gBAAgB,MAAM,MAAM,SAAS,KAAK,SAAS,OAAO,GAAG;CAEnE,kBAAkB,aAAa;CAE/B,MAAM,cAAc,gBAAgB,4BAA4B;CAEhE,IAAI,cAAc,WAAW,GAC3B,OAAO;EAAC,GAAG;EAAQ;EAAI,GAAG,YAAY;EAAO;CAAE,EAAE,KAAK,IAAI;CAG5D,OAAO;EACL,GAAG;EACH;EACA,GAAG,YAAY;EACf,GAAG,cAAc,SAAS,SAAS,YAAY,MAAM,eAAe,iBAAiB,CAAC;EACtF;EACA;CACF,EAAE,KAAK,IAAI;AACb"}
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import { NestedLayoutsNotSupportedError } from "../routing/layout-policy.mjs";
|
|
2
|
-
import {
|
|
3
|
-
import
|
|
2
|
+
import { NOT_FOUND_ROUTE_NAME, NOT_FOUND_ROUTE_PATH, isNotFoundPageFile } from "../server/not-found-page.mjs";
|
|
3
|
+
import { DuplicatePageRouteNameError, discoverPages, discoverWebRoots, isDiscoveredRoutablePage, isFile, layoutChainFor, toPosix, walkFiles } from "./discover-pages.mjs";
|
|
4
|
+
import { normalizeRoutePath } from "@warlock.js/core";
|
|
4
5
|
import fs from "node:fs";
|
|
6
|
+
import path from "node:path";
|
|
5
7
|
import { parse } from "@babel/parser";
|
|
6
8
|
|
|
7
|
-
//#region
|
|
9
|
+
//#region web/src/build/generate-pages-barrel.ts
|
|
8
10
|
/**
|
|
9
11
|
* The server half of the build→runtime handoff: the generated
|
|
10
12
|
* `<productionDir>/pages.ts` barrel that carries the page graph into the
|
|
@@ -71,7 +73,7 @@ const WEB_ESBUILD_PATCH = {
|
|
|
71
73
|
};
|
|
72
74
|
/** Line appended to section 4 of the generated production entry, after `./routes`. */
|
|
73
75
|
const WEB_ENTRY_IMPORT = "await import(\"./pages\");";
|
|
74
|
-
const REMEDY = "
|
|
76
|
+
const REMEDY = "move the static file into the application's public/ directory and reference it by its root URL instead (for example, public/logo.svg becomes /logo.svg). The production server build does not compile static-asset imports, ?raw/?url queries, or import.meta.url in the page graph in 5.2";
|
|
75
77
|
const ASSET_EXTENSIONS = [
|
|
76
78
|
".svg",
|
|
77
79
|
".png",
|
|
@@ -233,6 +235,21 @@ const EMPTY_BARREL_CONTENTS = [
|
|
|
233
235
|
"providePageManifest({ pages: [] });",
|
|
234
236
|
""
|
|
235
237
|
].join("\n");
|
|
238
|
+
function emptyPageBarrelContents(clientDir, publicFiles) {
|
|
239
|
+
if (publicFiles.length === 0) return EMPTY_BARREL_CONTENTS;
|
|
240
|
+
return [
|
|
241
|
+
...BARREL_HEADER,
|
|
242
|
+
"",
|
|
243
|
+
"// Zero pages were discovered, but app-owned public files still belong to",
|
|
244
|
+
"// the production browser surface and are served from the copied client tree.",
|
|
245
|
+
"providePageManifest({",
|
|
246
|
+
` clientDir: ${quote(clientDir)},`,
|
|
247
|
+
` publicFiles: ${JSON.stringify([...publicFiles])},`,
|
|
248
|
+
" pages: [],",
|
|
249
|
+
"});",
|
|
250
|
+
""
|
|
251
|
+
].join("\n");
|
|
252
|
+
}
|
|
236
253
|
async function writeBarrel(productionDir, contents) {
|
|
237
254
|
const barrelFile = path.join(productionDir, "pages.ts");
|
|
238
255
|
await fs.promises.mkdir(productionDir, { recursive: true });
|
|
@@ -251,27 +268,48 @@ async function writeBarrel(productionDir, contents) {
|
|
|
251
268
|
* hydrate.
|
|
252
269
|
*/
|
|
253
270
|
async function generatePagesBarrel(options) {
|
|
254
|
-
const { appRoot, productionDir, clientDir } = options;
|
|
271
|
+
const { appRoot, productionDir, clientDir, publicFiles = [] } = options;
|
|
255
272
|
const srcRoot = path.join(appRoot, options.srcDir ?? "src");
|
|
256
273
|
const webRoots = discoverWebRoots(srcRoot);
|
|
257
274
|
const discovered = discoverPages({
|
|
258
275
|
appRoot,
|
|
259
276
|
srcDir: options.srcDir
|
|
260
277
|
});
|
|
278
|
+
const routablePages = discovered.filter(isDiscoveredRoutablePage);
|
|
279
|
+
const errorPage = discovered.find((page) => page.type === "error");
|
|
261
280
|
if (discovered.length === 0) {
|
|
262
281
|
console.log("web configured, 0 pages");
|
|
282
|
+
const contents = emptyPageBarrelContents(clientDir, publicFiles);
|
|
263
283
|
return {
|
|
264
284
|
pageCount: 0,
|
|
265
|
-
barrelFile: await writeBarrel(productionDir,
|
|
266
|
-
contents
|
|
285
|
+
barrelFile: await writeBarrel(productionDir, contents),
|
|
286
|
+
contents,
|
|
287
|
+
pageRoutes: {
|
|
288
|
+
version: 1,
|
|
289
|
+
routes: []
|
|
290
|
+
}
|
|
267
291
|
};
|
|
268
292
|
}
|
|
269
293
|
assertNoViteOnlyImports(webRoots, appRoot);
|
|
270
294
|
const appFile = path.join(srcRoot, "web", "root.tsx");
|
|
271
|
-
if (!isFile(appFile)) throw new Error(`Cannot generate the page barrel: ${discovered.length} page(s) were discovered but the application root component "${toPosix(path.relative(appRoot, appFile))}" does not exist. Every page renders inside it.`);
|
|
295
|
+
if (routablePages.length > 0 && !isFile(appFile)) throw new Error(`Cannot generate the page barrel: ${discovered.length} page(s) were discovered but the application root component "${toPosix(path.relative(appRoot, appFile))}" does not exist. Every page renders inside it.`);
|
|
272
296
|
const layoutIdentifiers = /* @__PURE__ */ new Map();
|
|
273
297
|
const pages = [];
|
|
274
|
-
|
|
298
|
+
const pageRoutes = {
|
|
299
|
+
version: 1,
|
|
300
|
+
routes: [...routablePages.filter((page) => !isNotFoundPageFile(page.pageFile)).map((page) => ({
|
|
301
|
+
method: "GET",
|
|
302
|
+
path: normalizeRoutePath(page.routePath),
|
|
303
|
+
name: page.routeName,
|
|
304
|
+
source: toPosix(path.relative(appRoot, page.pageFile))
|
|
305
|
+
})), {
|
|
306
|
+
method: "GET",
|
|
307
|
+
path: normalizeRoutePath("*"),
|
|
308
|
+
name: NOT_FOUND_ROUTE_NAME,
|
|
309
|
+
source: routablePages.find((page) => isNotFoundPageFile(page.pageFile)) === void 0 ? "\0warlock:framework-default-404" : toPosix(path.relative(appRoot, routablePages.find((page) => isNotFoundPageFile(page.pageFile)).pageFile))
|
|
310
|
+
}]
|
|
311
|
+
};
|
|
312
|
+
for (const [index, page] of routablePages.entries()) {
|
|
275
313
|
const layouts = page.layouts.map((layoutFile) => {
|
|
276
314
|
let identifier = layoutIdentifiers.get(layoutFile);
|
|
277
315
|
if (identifier === void 0) {
|
|
@@ -290,7 +328,8 @@ async function generatePagesBarrel(options) {
|
|
|
290
328
|
});
|
|
291
329
|
}
|
|
292
330
|
const importLines = [
|
|
293
|
-
`import * as app from ${quote(importSpecifierFor(productionDir, appFile))}
|
|
331
|
+
...routablePages.length === 0 ? [] : [`import * as app from ${quote(importSpecifierFor(productionDir, appFile))};`],
|
|
332
|
+
...errorPage === void 0 ? [] : [`import * as errorPage from ${quote(importSpecifierFor(productionDir, errorPage.pageFile))};`],
|
|
294
333
|
...[...layoutIdentifiers.entries()].map(([layoutFile, identifier]) => `import * as ${identifier} from ${quote(importSpecifierFor(productionDir, layoutFile))};`),
|
|
295
334
|
...pages.map((page) => `import * as ${page.identifier} from ${quote(importSpecifierFor(productionDir, page.sourceFile))};`)
|
|
296
335
|
];
|
|
@@ -310,8 +349,10 @@ async function generatePagesBarrel(options) {
|
|
|
310
349
|
...importLines,
|
|
311
350
|
"",
|
|
312
351
|
"providePageManifest({",
|
|
313
|
-
` clientDir: ${quote(clientDir)}
|
|
314
|
-
|
|
352
|
+
...routablePages.length === 0 && publicFiles.length === 0 ? [] : [` clientDir: ${quote(clientDir)},`],
|
|
353
|
+
...publicFiles.length === 0 ? [] : [` publicFiles: ${JSON.stringify([...publicFiles])},`],
|
|
354
|
+
...routablePages.length === 0 ? [] : [` app: { module: app, sourceFile: ${relativeToApp(appFile)} },`],
|
|
355
|
+
...errorPage === void 0 ? [] : [` errorPage: { module: errorPage, sourceFile: ${relativeToApp(errorPage.pageFile)} },`],
|
|
315
356
|
" pages: [",
|
|
316
357
|
...pageEntries.map((entry) => entry.split("\n").map((line) => ` ${line}`).join("\n")),
|
|
317
358
|
" ],",
|
|
@@ -321,7 +362,8 @@ async function generatePagesBarrel(options) {
|
|
|
321
362
|
return {
|
|
322
363
|
pageCount: pages.length,
|
|
323
364
|
barrelFile: await writeBarrel(productionDir, contents),
|
|
324
|
-
contents
|
|
365
|
+
contents,
|
|
366
|
+
pageRoutes
|
|
325
367
|
};
|
|
326
368
|
}
|
|
327
369
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate-pages-barrel.mjs","names":[],"sources":["../../../../../../../web/src/build/generate-pages-barrel.ts"],"sourcesContent":["/**\n * The server half of the build→runtime handoff: the generated\n * `<productionDir>/pages.ts` barrel that carries the page graph into the\n * server bundle.\n *\n * The graph itself comes from `discover-pages.ts`, the one scan every provider\n * shares — this module is the BARREL provider and nothing more. It takes the\n * recipe, runs the Vite-switch tripwire over the sources the recipe came from,\n * and writes the file.\n *\n * \"Static\" means the FILESYSTEM ONLY — discovery globs `*.page.tsx`,\n * `layout.tsx` and `root.tsx` and never imports a single application module,\n * mirroring how the builder already globs (`production-builder.ts:184-242`).\n * The imports happen at BOOT, when the compiled barrel runs, which is what\n * makes a page that throws on import a loud pre-listen failure in production.\n *\n * This is the HEAVY half of the contribution: `contribution.ts` reaches it by\n * dynamic import inside its `generate` hook, so nothing here lands in a\n * connector's static graph.\n */\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { parse } from \"@babel/parser\";\nimport type { ConnectorEsbuildPatch } from \"@warlock.js/core\";\nimport { discoverPages, discoverWebRoots, isFile, toPosix, walkFiles } from \"./discover-pages\";\n\n// Re-exported, not redefined: discovery's helpers were this module's before the\n// split, and the callers that already reach for them here should keep getting\n// the one implementation rather than a copy that can drift from it. The nested\n// layout error re-exports from the layout policy module, the one place that\n// owns layout selection and its error contract.\nexport {\n discoverPages,\n discoverWebRoots,\n DuplicatePageRouteNameError,\n layoutChainFor,\n} from \"./discover-pages\";\nexport { NestedLayoutsNotSupportedError } from \"../routing/layout-policy\";\nexport type { DiscoveredPage, DiscoverPagesOptions } from \"./discover-pages\";\n\n/**\n * Declared BEFORE the patch that reads it. `const` is hoisted but sits in the\n * temporal dead zone, and the patch below is an object literal evaluated at\n * module load — reading this from further down the file would throw.\n */\nconst STYLE_EXTENSIONS = [\".css\", \".scss\", \".sass\", \".less\", \".styl\"];\n\n/**\n * The esbuild patch web contributes (spike-settled, contract §3a).\n *\n * NO `process.env.NODE_ENV` define: warlock assigns to `process.env.NODE_ENV`\n * at runtime (`core/src/utils/environment.ts:14`) and a define would turn that\n * assignment into an assignment to a literal.\n */\nexport const WEB_ESBUILD_PATCH: ConnectorEsbuildPatch = {\n jsx: \"automatic\",\n jsxImportSource: \"react\",\n define: {\n \"import.meta.env.DEV\": \"false\",\n \"import.meta.env.PROD\": \"true\",\n \"import.meta.env.SSR\": \"true\",\n \"import.meta.env.MODE\": '\"production\"',\n },\n /**\n * Stylesheets compile to NOTHING in the server bundle, rather than failing it.\n *\n * `root.tsx` importing `./app.css` is how Tailwind — and every other CSS\n * pipeline — is normally wired, so rejecting it meant the framework could not\n * build a styled application at all. But the server has no use for the bytes:\n * it renders HTML, and all it ever needs of a stylesheet is a URL to put in a\n * `<link>`. The CSS itself belongs to the CLIENT bundle, which Vite builds\n * from the same `root.tsx` and which handles CSS natively.\n *\n * So the import stays in the user's source, the server drops it, and Vite\n * emits the real asset. Nothing is silently lost: a stylesheet that does not\n * exist still fails the client build, loudly, where it matters.\n */\n loader: Object.fromEntries(\n STYLE_EXTENSIONS.map((extension) => [extension, \"empty\" as const]),\n ) as ConnectorEsbuildPatch[\"loader\"],\n};\n\n/** Line appended to section 4 of the generated production entry, after `./routes`. */\nexport const WEB_ENTRY_IMPORT = 'await import(\"./pages\");';\n\nconst REMEDY =\n \"remove the import from this file (move it into a client-only module, or \" +\n \"reference the asset by URL instead), or wait for the Vite-based server \" +\n \"build, which is the only build that can compile imports like this one\";\n\nconst ASSET_EXTENSIONS = [\n \".svg\",\n \".png\",\n \".jpg\",\n \".jpeg\",\n \".gif\",\n \".webp\",\n \".avif\",\n \".ico\",\n \".woff\",\n \".woff2\",\n \".ttf\",\n \".eot\",\n \".mp4\",\n \".webm\",\n];\n\nexport type GeneratePagesBarrelOptions = {\n /** Absolute path to the application root (where `package.json` lives). */\n appRoot: string;\n /** Absolute path to `.warlock/production` — where the barrel is written. */\n productionDir: string;\n /** Source directory name under `appRoot`; defaults to `\"src\"`. */\n srcDir?: string;\n /**\n * App-root-relative POSIX path of the client bundle directory\n * (`\"dist/client\"`), baked into the manifest for the runtime to read back.\n * See `PageManifest.clientDir` for why it cannot be derived at boot.\n *\n * The CALLER resolves it, from the same `context.options.outdir` the client\n * build itself writes to, so the two cannot name different directories.\n */\n clientDir: string;\n};\n\nexport type GeneratePagesBarrelResult = {\n /** How many `*.page.tsx` files discovery found across both web roots. */\n pageCount: number;\n /** Absolute path of the written barrel. Always written when this runs at all. */\n barrelFile: string;\n /** The written barrel source. */\n contents: string;\n};\n\n/** Raised by the Vite-switch tripwire. */\nexport class WebPageGraphUnsupportedImportError extends Error {\n public constructor(\n public readonly sourceFile: string,\n public readonly specifier: string,\n reason: string,\n ) {\n super(\n `Cannot build the page graph: \"${sourceFile}\" ${reason} (${specifier}). ` +\n \"Pages are compiled into the server bundle, which supports plain code imports only — \" +\n \"static assets, `?raw`/`?url` queries and `import.meta.url` are not supported there. \" +\n \"(Stylesheets ARE supported: the server bundle drops them and the client bundle emits them.) \" +\n `To fix: ${REMEDY}.`,\n );\n this.name = \"WebPageGraphUnsupportedImportError\";\n }\n}\n\nconst FROM_SPECIFIER = /\\bfrom\\s*[\"']([^\"']+)[\"']/g;\nconst BARE_IMPORT = /\\bimport\\s*[\"']([^\"']+)[\"']/g;\nconst DYNAMIC_IMPORT = /\\bimport\\s*\\(\\s*[\"']([^\"']+)[\"']\\s*\\)/g;\n\n/**\n * Blank every comment, preserving byte offsets.\n *\n * The scan below is regex over source text, so without this a specifier written\n * inside a comment is indistinguishable from a real import. That is not\n * hypothetical: documenting this very restriction — writing `import \"./app.css\"`\n * in a doc comment to explain why it is unsupported — failed the build, and the\n * error then insisted the file imported a stylesheet that it did not import.\n * Removing the real import did not help, because the comment was the match.\n *\n * Comments are replaced with spaces rather than deleted so every subsequent\n * offset, and therefore every line number in anything reported from here,\n * stays exactly where it was.\n *\n * A parse failure is deliberately NOT fatal: this function's job is to find\n * hazards, not to validate syntax. esbuild reports a genuine syntax error far\n * better than we would, and failing here would replace its clear message with a\n * worse one. On a parse failure the raw source is scanned — the pre-existing\n * behaviour, false positives and all.\n */\nfunction withoutComments(source: string): string {\n try {\n const ast = parse(source, {\n sourceType: \"module\",\n errorRecovery: true,\n plugins: [\"typescript\", \"jsx\", \"decorators-legacy\"],\n });\n\n let stripped = source;\n\n for (const comment of ast.comments ?? []) {\n const { start, end } = comment as { start: number; end: number };\n\n stripped =\n stripped.slice(0, start) + \" \".repeat(end - start) + stripped.slice(end);\n }\n\n return stripped;\n } catch {\n return source;\n }\n}\n\n/** Expects source whose comments have already been blanked by {@link withoutComments}. */\nfunction collectSpecifiers(source: string): string[] {\n const specifiers: string[] = [];\n\n for (const pattern of [FROM_SPECIFIER, BARE_IMPORT, DYNAMIC_IMPORT]) {\n pattern.lastIndex = 0;\n\n let match = pattern.exec(source);\n\n while (match !== null) {\n specifiers.push(match[1]);\n match = pattern.exec(source);\n }\n }\n\n return specifiers;\n}\n\nfunction hazardFor(specifier: string): string | undefined {\n const [base, query] = specifier.split(\"?\", 2);\n const lowered = base.toLowerCase();\n\n /*\n STYLESHEETS ARE NOT A HAZARD — see `loader` in WEB_ESBUILD_PATCH above.\n\n They used to be rejected here, which meant `import \"./app.css\"` in\n `root.tsx` — the ordinary way to wire Tailwind or any other CSS pipeline —\n failed the build outright. The server bundle now compiles them to nothing,\n because the server only ever needs a stylesheet's URL, and the client bundle\n that Vite builds from the same sources emits the real asset.\n\n STYLE_EXTENSIONS is still the single list both halves read from, so the set\n esbuild stubs and the set this check tolerates cannot drift apart.\n */\n\n if (ASSET_EXTENSIONS.some((extension) => lowered.endsWith(extension))) {\n return \"imports a static asset\";\n }\n\n if (query !== undefined && /(^|&)(raw|url)(&|=|$)/.test(query)) {\n return \"uses a bundler-specific import query\";\n }\n\n return undefined;\n}\n\n/**\n * The Vite-switch tripwire. Fails the build\n * the moment the page graph needs a capability the esbuild server build does\n * not have, naming the file, the specifier and the remedy.\n *\n * LIMITATIONS, stated on purpose — BOTH directions, because stating only one\n * is what made the other one expensive to find:\n *\n * FALSE NEGATIVES. This is a FILE-LEVEL scan of the `.ts`/`.tsx` sources under\n * the discovered web roots — it is not transitive resolution. A page that\n * imports a workspace package which itself imports CSS is not caught here; that\n * failure surfaces at esbuild time instead.\n *\n * FALSE POSITIVES. The scan is regex over source text, so anything that LOOKS\n * like a specifier counts. Comments are blanked first ({@link withoutComments})\n * because a documented example used to fail the build while insisting on an\n * import that was not there. String and template literals are NOT blanked —\n * they cannot be, since real specifiers are string literals — so a specifier\n * inside a template literal (a code sample in a docs page, say) still matches.\n * Rare, and it fails loudly rather than silently, but it is not impossible.\n */\nexport function assertNoViteOnlyImports(webRoots: readonly string[], appRoot: string): void {\n for (const webRoot of webRoots) {\n const sources = walkFiles(\n webRoot,\n (fileName) => fileName.endsWith(\".ts\") || fileName.endsWith(\".tsx\"),\n );\n\n for (const sourceFile of sources) {\n // Comments stripped ONCE, and reused by both checks below: `import.meta.url`\n // was as blind to comments as the specifier scan was, and mentioning it in\n // prose — as this very file does — would have failed the build.\n const source = withoutComments(fs.readFileSync(sourceFile, \"utf-8\"));\n const relative = toPosix(path.relative(appRoot, sourceFile));\n\n for (const specifier of collectSpecifiers(source)) {\n const reason = hazardFor(specifier);\n\n if (reason !== undefined) {\n throw new WebPageGraphUnsupportedImportError(relative, specifier, reason);\n }\n }\n\n if (source.includes(\"import.meta.url\")) {\n throw new WebPageGraphUnsupportedImportError(\n relative,\n \"import.meta.url\",\n \"uses `import.meta.url`, whose meaning changes under the bundled server build\",\n );\n }\n }\n }\n}\n\n/** `<productionDir>` -> `<file>` as an extensionless, POSIX, relative specifier. */\nfunction importSpecifierFor(productionDir: string, file: string): string {\n const relative = toPosix(path.relative(productionDir, file)).replace(/\\.tsx?$/, \"\");\n\n return relative.startsWith(\".\") ? relative : `./${relative}`;\n}\n\nfunction quote(value: string): string {\n return JSON.stringify(value);\n}\n\ninterface BarrelPage {\n identifier: string;\n sourceFile: string;\n layouts: { identifier: string; sourceFile: string }[];\n}\n\n/** Header of every generated barrel — the banner plus the one runtime import. */\nconst BARREL_HEADER = [\n \"// AUTO-GENERATED by @warlock.js/web — do not edit.\",\n \"// The page graph, compiled into the server bundle.\",\n \"// Route paths are deliberately absent: they are read off each module at boot.\",\n // The CONNECTOR subpath, never the root barrel: this file is compiled into\n // the server bundle, and `\"@warlock.js/web\"` would drag React in with it.\n 'import { providePageManifest } from \"@warlock.js/web/connector\";',\n];\n\n/**\n * The barrel written when discovery found no pages at all.\n *\n * No app entry: `root.tsx` is the root every PAGE renders inside, so with zero\n * pages there is nothing for it to wrap and requiring it would fail builds that\n * are legitimately page-free.\n */\nconst EMPTY_BARREL_CONTENTS = [\n ...BARREL_HEADER,\n \"\",\n \"// Zero pages were discovered. The empty table is still provided, because that\",\n \"// is what tells the boot-time reader \\\"this bundle WAS built with web, it just\",\n '// has no pages\" — as opposed to a bundle built without web at all, where no',\n \"// barrel runs and the manifest stays absent.\",\n \"providePageManifest({ pages: [] });\",\n \"\",\n].join(\"\\n\");\n\nasync function writeBarrel(productionDir: string, contents: string): Promise<string> {\n const barrelFile = path.join(productionDir, \"pages.ts\");\n\n await fs.promises.mkdir(productionDir, { recursive: true });\n await fs.promises.writeFile(barrelFile, contents, \"utf-8\");\n\n return barrelFile;\n}\n\n/**\n * Discovers the page graph, runs the tripwire, and writes\n * `<productionDir>/pages.ts`.\n *\n * Zero pages is NOT an error, and it is NOT silence either: the barrel is\n * written anyway carrying an empty table, so \"configured with web, no pages\"\n * reaches the runtime as a fact instead of looking identical to \"never built\n * with web\". The run also says so out loud (no silent caps). What the caller\n * skips on zero pages is the CLIENT bundle — no pages means nothing to\n * hydrate.\n */\nexport async function generatePagesBarrel(\n options: GeneratePagesBarrelOptions,\n): Promise<GeneratePagesBarrelResult> {\n const { appRoot, productionDir, clientDir } = options;\n const srcRoot = path.join(appRoot, options.srcDir ?? \"src\");\n const webRoots = discoverWebRoots(srcRoot);\n const discovered = discoverPages({ appRoot, srcDir: options.srcDir });\n\n if (discovered.length === 0) {\n console.log(\"web configured, 0 pages\");\n\n return {\n pageCount: 0,\n barrelFile: await writeBarrel(productionDir, EMPTY_BARREL_CONTENTS),\n contents: EMPTY_BARREL_CONTENTS,\n };\n }\n\n assertNoViteOnlyImports(webRoots, appRoot);\n\n const appFile = path.join(srcRoot, \"web\", \"root.tsx\");\n\n if (!isFile(appFile)) {\n throw new Error(\n `Cannot generate the page barrel: ${discovered.length} page(s) were discovered but the application root ` +\n `component \"${toPosix(path.relative(appRoot, appFile))}\" does not exist. Every page renders inside it.`,\n );\n }\n\n const layoutIdentifiers = new Map<string, string>();\n const pages: BarrelPage[] = [];\n\n for (const [index, page] of discovered.entries()) {\n const layouts = page.layouts.map((layoutFile) => {\n let identifier = layoutIdentifiers.get(layoutFile);\n\n if (identifier === undefined) {\n identifier = `l${layoutIdentifiers.size}`;\n layoutIdentifiers.set(layoutFile, identifier);\n }\n\n return { identifier, sourceFile: layoutFile };\n });\n\n pages.push({ identifier: `p${index}`, sourceFile: page.pageFile, layouts });\n }\n\n const importLines = [\n `import * as app from ${quote(importSpecifierFor(productionDir, appFile))};`,\n ...[...layoutIdentifiers.entries()].map(\n ([layoutFile, identifier]) =>\n `import * as ${identifier} from ${quote(importSpecifierFor(productionDir, layoutFile))};`,\n ),\n ...pages.map(\n (page) =>\n `import * as ${page.identifier} from ${quote(importSpecifierFor(productionDir, page.sourceFile))};`,\n ),\n ];\n\n const relativeToApp = (file: string) => quote(toPosix(path.relative(appRoot, file)));\n\n const pageEntries = pages.map((page) => {\n const layouts = page.layouts\n .map((layout) => `{ module: ${layout.identifier}, sourceFile: ${relativeToApp(layout.sourceFile)} }`)\n .join(\", \");\n\n return [\n \" {\",\n ` module: ${page.identifier},`,\n ` sourceFile: ${relativeToApp(page.sourceFile)},`,\n ` layouts: [${layouts}],`,\n \" },\",\n ].join(\"\\n\");\n });\n\n const contents = [\n ...BARREL_HEADER,\n ...importLines,\n \"\",\n \"providePageManifest({\",\n ` clientDir: ${quote(clientDir)},`,\n ` app: { module: app, sourceFile: ${relativeToApp(appFile)} },`,\n \" pages: [\",\n ...pageEntries.map((entry) =>\n entry\n .split(\"\\n\")\n .map((line) => ` ${line}`)\n .join(\"\\n\"),\n ),\n \" ],\",\n \"});\",\n \"\",\n ].join(\"\\n\");\n\n return {\n pageCount: pages.length,\n barrelFile: await writeBarrel(productionDir, contents),\n contents,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,MAAM,mBAAmB;CAAC;CAAQ;CAAS;CAAS;CAA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;GAAU;EAAQ,CAAC;CAC5E;CAEA,MAAM,cAAc;EAClB,wBAAwB,MAAM,mBAAmB,eAAe,OAAO,CAAC,EAAE;EAC1E,GAAG,CAAC,GAAG,kBAAkB,QAAQ,CAAC,CAAC,CAAC,KACjC,CAAC,YAAY,gBACZ,eAAe,WAAW,QAAQ,MAAM,mBAAmB,eAAe,UAAU,CAAC,EAAE,EAC3F;EACA,GAAG,MAAM,KACN,SACC,eAAe,KAAK,WAAW,QAAQ,MAAM,mBAAmB,eAAe,KAAK,UAAU,CAAC,EAAE,EACrG;CACF;CAEA,MAAM,iBAAiB,SAAiB,MAAM,QAAQ,KAAK,SAAS,SAAS,IAAI,CAAC,CAAC;CAEnF,MAAM,cAAc,MAAM,KAAK,SAAS;EACtC,MAAM,UAAU,KAAK,QAClB,KAAK,WAAW,aAAa,OAAO,WAAW,gBAAgB,cAAc,OAAO,UAAU,EAAE,GAAG,CAAC,CACpG,KAAK,IAAI;EAEZ,OAAO;GACL;GACA,eAAe,KAAK,WAAW;GAC/B,mBAAmB,cAAc,KAAK,UAAU,EAAE;GAClD,iBAAiB,QAAQ;GACzB;EACF,CAAC,CAAC,KAAK,IAAI;CACb,CAAC;CAED,MAAM,WAAW;EACf,GAAG;EACH,GAAG;EACH;EACA;EACA,gBAAgB,MAAM,SAAS,EAAE;EACjC,qCAAqC,cAAc,OAAO,EAAE;EAC5D;EACA,GAAG,YAAY,KAAK,UAClB,MACG,MAAM,IAAI,CAAC,CACX,KAAK,SAAS,KAAK,MAAM,CAAC,CAC1B,KAAK,IAAI,CACd;EACA;EACA;EACA;CACF,CAAC,CAAC,KAAK,IAAI;CAEX,OAAO;EACL,WAAW,MAAM;EACjB,YAAY,MAAM,YAAY,eAAe,QAAQ;EACrD;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"generate-pages-barrel.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/build/generate-pages-barrel.ts"],"sourcesContent":["/**\r\n * The server half of the build→runtime handoff: the generated\r\n * `<productionDir>/pages.ts` barrel that carries the page graph into the\r\n * server bundle.\r\n *\r\n * The graph itself comes from `discover-pages.ts`, the one scan every provider\r\n * shares — this module is the BARREL provider and nothing more. It takes the\r\n * recipe, runs the Vite-switch tripwire over the sources the recipe came from,\r\n * and writes the file.\r\n *\r\n * \"Static\" means the FILESYSTEM ONLY — discovery globs `*.page.tsx`,\r\n * `layout.tsx` and `root.tsx` and never imports a single application module,\r\n * mirroring how the builder already globs (`production-builder.ts:184-242`).\r\n * The imports happen at BOOT, when the compiled barrel runs, which is what\r\n * makes a page that throws on import a loud pre-listen failure in production.\r\n *\r\n * This is the HEAVY half of the contribution: `contribution.ts` reaches it by\r\n * dynamic import inside its `generate` hook, so nothing here lands in a\r\n * connector's static graph.\r\n */\r\nimport fs from \"node:fs\";\r\nimport path from \"node:path\";\r\nimport { parse } from \"@babel/parser\";\r\nimport { normalizeRoutePath, type ConnectorEsbuildPatch } from \"@warlock.js/core\";\r\nimport {\r\n discoverPages,\r\n discoverWebRoots,\r\n isDiscoveredRoutablePage,\r\n isFile,\r\n toPosix,\r\n walkFiles,\r\n} from \"./discover-pages\";\r\nimport {\r\n isNotFoundPageFile,\r\n NOT_FOUND_ROUTE_NAME,\r\n NOT_FOUND_ROUTE_PATH,\r\n} from \"../server/not-found-page\";\r\n\r\n// Re-exported, not redefined: discovery's helpers were this module's before the\r\n// split, and the callers that already reach for them here should keep getting\r\n// the one implementation rather than a copy that can drift from it. The nested\r\n// layout error re-exports from the layout policy module, the one place that\r\n// owns layout selection and its error contract.\r\nexport {\r\n discoverPages,\r\n discoverWebRoots,\r\n DuplicatePageRouteNameError,\r\n layoutChainFor,\r\n} from \"./discover-pages\";\r\nexport { NestedLayoutsNotSupportedError } from \"../routing/layout-policy\";\r\nexport type { DiscoveredPage, DiscoverPagesOptions } from \"./discover-pages\";\r\n\r\n/**\r\n * Declared BEFORE the patch that reads it. `const` is hoisted but sits in the\r\n * temporal dead zone, and the patch below is an object literal evaluated at\r\n * module load — reading this from further down the file would throw.\r\n */\r\nconst STYLE_EXTENSIONS = [\".css\", \".scss\", \".sass\", \".less\", \".styl\"];\r\n\r\n/**\r\n * The esbuild patch web contributes (spike-settled, contract §3a).\r\n *\r\n * NO `process.env.NODE_ENV` define: warlock assigns to `process.env.NODE_ENV`\r\n * at runtime (`core/src/utils/environment.ts:14`) and a define would turn that\r\n * assignment into an assignment to a literal.\r\n */\r\nexport const WEB_ESBUILD_PATCH: ConnectorEsbuildPatch = {\r\n jsx: \"automatic\",\r\n jsxImportSource: \"react\",\r\n define: {\r\n \"import.meta.env.DEV\": \"false\",\r\n \"import.meta.env.PROD\": \"true\",\r\n \"import.meta.env.SSR\": \"true\",\r\n \"import.meta.env.MODE\": '\"production\"',\r\n },\r\n /**\r\n * Stylesheets compile to NOTHING in the server bundle, rather than failing it.\r\n *\r\n * `root.tsx` importing `./app.css` is how Tailwind — and every other CSS\r\n * pipeline — is normally wired, so rejecting it meant the framework could not\r\n * build a styled application at all. But the server has no use for the bytes:\r\n * it renders HTML, and all it ever needs of a stylesheet is a URL to put in a\r\n * `<link>`. The CSS itself belongs to the CLIENT bundle, which Vite builds\r\n * from the same `root.tsx` and which handles CSS natively.\r\n *\r\n * So the import stays in the user's source, the server drops it, and Vite\r\n * emits the real asset. Nothing is silently lost: a stylesheet that does not\r\n * exist still fails the client build, loudly, where it matters.\r\n */\r\n loader: Object.fromEntries(\r\n STYLE_EXTENSIONS.map((extension) => [extension, \"empty\" as const]),\r\n ) as ConnectorEsbuildPatch[\"loader\"],\r\n};\r\n\r\n/** Line appended to section 4 of the generated production entry, after `./routes`. */\r\nexport const WEB_ENTRY_IMPORT = 'await import(\"./pages\");';\r\n\r\nconst REMEDY =\n \"move the static file into the application's public/ directory and reference \" +\n \"it by its root URL instead (for example, public/logo.svg becomes /logo.svg). \" +\n \"The production server build does not compile static-asset imports, ?raw/?url \" +\n \"queries, or import.meta.url in the page graph in 5.2\";\n\r\nconst ASSET_EXTENSIONS = [\r\n \".svg\",\r\n \".png\",\r\n \".jpg\",\r\n \".jpeg\",\r\n \".gif\",\r\n \".webp\",\r\n \".avif\",\r\n \".ico\",\r\n \".woff\",\r\n \".woff2\",\r\n \".ttf\",\r\n \".eot\",\r\n \".mp4\",\r\n \".webm\",\r\n];\r\n\r\nexport type GeneratePagesBarrelOptions = {\r\n /** Absolute path to the application root (where `package.json` lives). */\r\n appRoot: string;\r\n /** Absolute path to `.warlock/production` — where the barrel is written. */\r\n productionDir: string;\r\n /** Source directory name under `appRoot`; defaults to `\"src\"`. */\r\n srcDir?: string;\r\n /**\r\n * App-root-relative POSIX path of the client bundle directory\r\n * (`\"dist/client\"`), baked into the manifest for the runtime to read back.\r\n * See `PageManifest.clientDir` for why it cannot be derived at boot.\r\n *\r\n * The CALLER resolves it, from the same `context.options.outdir` the client\r\n * build itself writes to, so the two cannot name different directories.\r\n */\n clientDir: string;\n /** App-root-public file paths copied into the production client directory. */\n publicFiles?: readonly string[];\n};\r\n\r\nexport type GeneratePagesBarrelResult = {\r\n /** How many `*.page.tsx` files discovery found under the page root. */\r\n pageCount: number;\r\n /** Absolute path of the written barrel. Always written when this runs at all. */\r\n barrelFile: string;\r\n /** The written barrel source. */\r\n contents: string;\r\n /** The build-time route surface persisted beside the production output. */\r\n pageRoutes: PageRoutesManifest;\r\n};\r\n\r\nexport type PageRouteManifestEntry = {\r\n method: \"GET\";\r\n path: string;\r\n name: string;\r\n source: string;\r\n};\r\n\r\nexport type PageRoutesManifest = {\r\n version: 1;\r\n routes: PageRouteManifestEntry[];\r\n};\r\n\r\n/** Raised by the Vite-switch tripwire. */\r\nexport class WebPageGraphUnsupportedImportError extends Error {\r\n public constructor(\r\n public readonly sourceFile: string,\r\n public readonly specifier: string,\r\n reason: string,\r\n ) {\r\n super(\r\n `Cannot build the page graph: \"${sourceFile}\" ${reason} (${specifier}). ` +\r\n \"Pages are compiled into the server bundle, which supports plain code imports only — \" +\r\n \"static assets, `?raw`/`?url` queries and `import.meta.url` are not supported there. \" +\r\n \"(Stylesheets ARE supported: the server bundle drops them and the client bundle emits them.) \" +\r\n `To fix: ${REMEDY}.`,\r\n );\r\n this.name = \"WebPageGraphUnsupportedImportError\";\r\n }\r\n}\r\n\r\nconst FROM_SPECIFIER = /\\bfrom\\s*[\"']([^\"']+)[\"']/g;\r\nconst BARE_IMPORT = /\\bimport\\s*[\"']([^\"']+)[\"']/g;\r\nconst DYNAMIC_IMPORT = /\\bimport\\s*\\(\\s*[\"']([^\"']+)[\"']\\s*\\)/g;\r\n\r\n/**\r\n * Blank every comment, preserving byte offsets.\r\n *\r\n * The scan below is regex over source text, so without this a specifier written\r\n * inside a comment is indistinguishable from a real import. That is not\r\n * hypothetical: documenting this very restriction — writing `import \"./app.css\"`\r\n * in a doc comment to explain why it is unsupported — failed the build, and the\r\n * error then insisted the file imported a stylesheet that it did not import.\r\n * Removing the real import did not help, because the comment was the match.\r\n *\r\n * Comments are replaced with spaces rather than deleted so every subsequent\r\n * offset, and therefore every line number in anything reported from here,\r\n * stays exactly where it was.\r\n *\r\n * A parse failure is deliberately NOT fatal: this function's job is to find\r\n * hazards, not to validate syntax. esbuild reports a genuine syntax error far\r\n * better than we would, and failing here would replace its clear message with a\r\n * worse one. On a parse failure the raw source is scanned — the pre-existing\r\n * behaviour, false positives and all.\r\n */\r\nfunction withoutComments(source: string): string {\r\n try {\r\n const ast = parse(source, {\r\n sourceType: \"module\",\r\n errorRecovery: true,\r\n plugins: [\"typescript\", \"jsx\", \"decorators-legacy\"],\r\n });\r\n\r\n let stripped = source;\r\n\r\n for (const comment of ast.comments ?? []) {\r\n const { start, end } = comment as { start: number; end: number };\r\n\r\n stripped =\r\n stripped.slice(0, start) + \" \".repeat(end - start) + stripped.slice(end);\r\n }\r\n\r\n return stripped;\r\n } catch {\r\n return source;\r\n }\r\n}\r\n\r\n/** Expects source whose comments have already been blanked by {@link withoutComments}. */\r\nfunction collectSpecifiers(source: string): string[] {\r\n const specifiers: string[] = [];\r\n\r\n for (const pattern of [FROM_SPECIFIER, BARE_IMPORT, DYNAMIC_IMPORT]) {\r\n pattern.lastIndex = 0;\r\n\r\n let match = pattern.exec(source);\r\n\r\n while (match !== null) {\r\n specifiers.push(match[1]);\r\n match = pattern.exec(source);\r\n }\r\n }\r\n\r\n return specifiers;\r\n}\r\n\r\nfunction hazardFor(specifier: string): string | undefined {\r\n const [base, query] = specifier.split(\"?\", 2);\r\n const lowered = base.toLowerCase();\r\n\r\n /*\r\n STYLESHEETS ARE NOT A HAZARD — see `loader` in WEB_ESBUILD_PATCH above.\r\n\r\n They used to be rejected here, which meant `import \"./app.css\"` in\r\n `root.tsx` — the ordinary way to wire Tailwind or any other CSS pipeline —\r\n failed the build outright. The server bundle now compiles them to nothing,\r\n because the server only ever needs a stylesheet's URL, and the client bundle\r\n that Vite builds from the same sources emits the real asset.\r\n\r\n STYLE_EXTENSIONS is still the single list both halves read from, so the set\r\n esbuild stubs and the set this check tolerates cannot drift apart.\r\n */\r\n\r\n if (ASSET_EXTENSIONS.some((extension) => lowered.endsWith(extension))) {\r\n return \"imports a static asset\";\r\n }\r\n\r\n if (query !== undefined && /(^|&)(raw|url)(&|=|$)/.test(query)) {\r\n return \"uses a bundler-specific import query\";\r\n }\r\n\r\n return undefined;\r\n}\r\n\r\n/**\r\n * The Vite-switch tripwire. Fails the build\r\n * the moment the page graph needs a capability the esbuild server build does\r\n * not have, naming the file, the specifier and the remedy.\r\n *\r\n * LIMITATIONS, stated on purpose — BOTH directions, because stating only one\r\n * is what made the other one expensive to find:\r\n *\r\n * FALSE NEGATIVES. This is a FILE-LEVEL scan of the `.ts`/`.tsx` sources under\r\n * the discovered web roots — it is not transitive resolution. A page that\r\n * imports a workspace package which itself imports CSS is not caught here; that\r\n * failure surfaces at esbuild time instead.\r\n *\r\n * FALSE POSITIVES. The scan is regex over source text, so anything that LOOKS\r\n * like a specifier counts. Comments are blanked first ({@link withoutComments})\r\n * because a documented example used to fail the build while insisting on an\r\n * import that was not there. String and template literals are NOT blanked —\r\n * they cannot be, since real specifiers are string literals — so a specifier\r\n * inside a template literal (a code sample in a docs page, say) still matches.\r\n * Rare, and it fails loudly rather than silently, but it is not impossible.\r\n */\r\nexport function assertNoViteOnlyImports(webRoots: readonly string[], appRoot: string): void {\r\n for (const webRoot of webRoots) {\r\n const sources = walkFiles(\r\n webRoot,\r\n (fileName) => fileName.endsWith(\".ts\") || fileName.endsWith(\".tsx\"),\r\n );\r\n\r\n for (const sourceFile of sources) {\r\n // Comments stripped ONCE, and reused by both checks below: `import.meta.url`\r\n // was as blind to comments as the specifier scan was, and mentioning it in\r\n // prose — as this very file does — would have failed the build.\r\n const source = withoutComments(fs.readFileSync(sourceFile, \"utf-8\"));\r\n const relative = toPosix(path.relative(appRoot, sourceFile));\r\n\r\n for (const specifier of collectSpecifiers(source)) {\r\n const reason = hazardFor(specifier);\r\n\r\n if (reason !== undefined) {\r\n throw new WebPageGraphUnsupportedImportError(relative, specifier, reason);\r\n }\r\n }\r\n\r\n if (source.includes(\"import.meta.url\")) {\r\n throw new WebPageGraphUnsupportedImportError(\r\n relative,\r\n \"import.meta.url\",\r\n \"uses `import.meta.url`, whose meaning changes under the bundled server build\",\r\n );\r\n }\r\n }\r\n }\r\n}\r\n\r\n/** `<productionDir>` -> `<file>` as an extensionless, POSIX, relative specifier. */\r\nfunction importSpecifierFor(productionDir: string, file: string): string {\r\n const relative = toPosix(path.relative(productionDir, file)).replace(/\\.tsx?$/, \"\");\r\n\r\n return relative.startsWith(\".\") ? relative : `./${relative}`;\r\n}\r\n\r\nfunction quote(value: string): string {\r\n return JSON.stringify(value);\r\n}\r\n\r\ntype BarrelPage = {\r\n identifier: string;\r\n sourceFile: string;\r\n layouts: { identifier: string; sourceFile: string }[];\r\n};\r\n\r\n/** Header of every generated barrel — the banner plus the one runtime import. */\r\nconst BARREL_HEADER = [\r\n \"// AUTO-GENERATED by @warlock.js/web — do not edit.\",\r\n \"// The page graph, compiled into the server bundle.\",\r\n \"// Route paths are deliberately absent: they are read off each module at boot.\",\r\n // The CONNECTOR subpath, never the root barrel: this file is compiled into\r\n // the server bundle, and `\"@warlock.js/web\"` would drag React in with it.\r\n 'import { providePageManifest } from \"@warlock.js/web/connector\";',\r\n];\r\n\r\n/**\r\n * The barrel written when discovery found no pages at all.\r\n *\r\n * No app entry: `root.tsx` is the root every PAGE renders inside, so with zero\r\n * pages there is nothing for it to wrap and requiring it would fail builds that\r\n * are legitimately page-free.\r\n */\r\nconst EMPTY_BARREL_CONTENTS = [\n ...BARREL_HEADER,\r\n \"\",\r\n \"// Zero pages were discovered. The empty table is still provided, because that\",\r\n \"// is what tells the boot-time reader \\\"this bundle WAS built with web, it just\",\r\n '// has no pages\" — as opposed to a bundle built without web at all, where no',\r\n \"// barrel runs and the manifest stays absent.\",\r\n \"providePageManifest({ pages: [] });\",\r\n \"\",\r\n].join(\"\\n\");\n\nfunction emptyPageBarrelContents(clientDir: string, publicFiles: readonly string[]): string {\n if (publicFiles.length === 0) return EMPTY_BARREL_CONTENTS;\n\n return [\n ...BARREL_HEADER,\n \"\",\n \"// Zero pages were discovered, but app-owned public files still belong to\",\n \"// the production browser surface and are served from the copied client tree.\",\n \"providePageManifest({\",\n ` clientDir: ${quote(clientDir)},`,\n ` publicFiles: ${JSON.stringify([...publicFiles])},`,\n \" pages: [],\",\n \"});\",\n \"\",\n ].join(\"\\n\");\n}\n\r\nasync function writeBarrel(productionDir: string, contents: string): Promise<string> {\r\n const barrelFile = path.join(productionDir, \"pages.ts\");\r\n\r\n await fs.promises.mkdir(productionDir, { recursive: true });\r\n await fs.promises.writeFile(barrelFile, contents, \"utf-8\");\r\n\r\n return barrelFile;\r\n}\r\n\r\n/**\r\n * Discovers the page graph, runs the tripwire, and writes\r\n * `<productionDir>/pages.ts`.\r\n *\r\n * Zero pages is NOT an error, and it is NOT silence either: the barrel is\r\n * written anyway carrying an empty table, so \"configured with web, no pages\"\r\n * reaches the runtime as a fact instead of looking identical to \"never built\r\n * with web\". The run also says so out loud (no silent caps). What the caller\r\n * skips on zero pages is the CLIENT bundle — no pages means nothing to\r\n * hydrate.\r\n */\r\nexport async function generatePagesBarrel(\r\n options: GeneratePagesBarrelOptions,\r\n): Promise<GeneratePagesBarrelResult> {\r\n const { appRoot, productionDir, clientDir, publicFiles = [] } = options;\n const srcRoot = path.join(appRoot, options.srcDir ?? \"src\");\r\n const webRoots = discoverWebRoots(srcRoot);\r\n const discovered = discoverPages({ appRoot, srcDir: options.srcDir });\r\n const routablePages = discovered.filter(isDiscoveredRoutablePage);\r\n const errorPage = discovered.find((page) => page.type === \"error\");\r\n\r\n if (discovered.length === 0) {\n console.log(\"web configured, 0 pages\");\n const contents = emptyPageBarrelContents(clientDir, publicFiles);\n\n return {\n pageCount: 0,\n barrelFile: await writeBarrel(productionDir, contents),\n contents,\n pageRoutes: { version: 1, routes: [] },\r\n };\r\n }\r\n\r\n assertNoViteOnlyImports(webRoots, appRoot);\r\n\r\n const appFile = path.join(srcRoot, \"web\", \"root.tsx\");\r\n\r\n if (routablePages.length > 0 && !isFile(appFile)) {\r\n throw new Error(\r\n `Cannot generate the page barrel: ${discovered.length} page(s) were discovered but the application root ` +\r\n `component \"${toPosix(path.relative(appRoot, appFile))}\" does not exist. Every page renders inside it.`,\r\n );\r\n }\r\n\r\n const layoutIdentifiers = new Map<string, string>();\r\n const pages: BarrelPage[] = [];\r\n // Persisted paths run through the ROUTER's own `normalizeRoutePath`, the\r\n // single definition of a route path's canonical form. Discovery derives these\r\n // from the filesystem and never registers anything, so without this the\r\n // manifest records a spelling the router never serves — the catch-all is\r\n // literally `\"*\"` here and `\"/*\"` once registered — and `warlock routes:diff`\r\n // reports drift on an untouched checkout right after a successful build.\r\n const pageRoutes: PageRoutesManifest = {\r\n version: 1,\r\n routes: [\r\n ...routablePages.filter((page) => !isNotFoundPageFile(page.pageFile)).map((page) => ({\r\n method: \"GET\" as const,\r\n path: normalizeRoutePath(page.routePath),\r\n name: page.routeName,\r\n source: toPosix(path.relative(appRoot, page.pageFile)),\r\n })),\r\n {\r\n method: \"GET\" as const,\r\n path: normalizeRoutePath(NOT_FOUND_ROUTE_PATH),\r\n name: NOT_FOUND_ROUTE_NAME,\r\n source: routablePages.find((page) => isNotFoundPageFile(page.pageFile)) === undefined\r\n ? \"\\u0000warlock:framework-default-404\"\r\n : toPosix(path.relative(appRoot, routablePages.find((page) => isNotFoundPageFile(page.pageFile))!.pageFile)),\r\n },\r\n ],\r\n };\r\n\r\n for (const [index, page] of routablePages.entries()) {\r\n const layouts = page.layouts.map((layoutFile) => {\r\n let identifier = layoutIdentifiers.get(layoutFile);\r\n\r\n if (identifier === undefined) {\r\n identifier = `l${layoutIdentifiers.size}`;\r\n layoutIdentifiers.set(layoutFile, identifier);\r\n }\r\n\r\n return { identifier, sourceFile: layoutFile };\r\n });\r\n\r\n pages.push({ identifier: `p${index}`, sourceFile: page.pageFile, layouts });\r\n }\r\n\r\n const importLines = [\r\n ...(routablePages.length === 0\r\n ? []\r\n : [`import * as app from ${quote(importSpecifierFor(productionDir, appFile))};`]),\r\n ...(errorPage === undefined\r\n ? []\r\n : [`import * as errorPage from ${quote(importSpecifierFor(productionDir, errorPage.pageFile))};`]),\r\n ...[...layoutIdentifiers.entries()].map(\r\n ([layoutFile, identifier]) =>\r\n `import * as ${identifier} from ${quote(importSpecifierFor(productionDir, layoutFile))};`,\r\n ),\r\n ...pages.map(\r\n (page) =>\r\n `import * as ${page.identifier} from ${quote(importSpecifierFor(productionDir, page.sourceFile))};`,\r\n ),\r\n ];\r\n\r\n const relativeToApp = (file: string) => quote(toPosix(path.relative(appRoot, file)));\r\n\r\n const pageEntries = pages.map((page) => {\r\n const layouts = page.layouts\r\n .map((layout) => `{ module: ${layout.identifier}, sourceFile: ${relativeToApp(layout.sourceFile)} }`)\r\n .join(\", \");\r\n\r\n return [\r\n \" {\",\r\n ` module: ${page.identifier},`,\r\n ` sourceFile: ${relativeToApp(page.sourceFile)},`,\r\n ` layouts: [${layouts}],`,\r\n \" },\",\r\n ].join(\"\\n\");\r\n });\r\n\r\n const contents = [\r\n ...BARREL_HEADER,\r\n ...importLines,\n \"\",\n \"providePageManifest({\",\n ...(routablePages.length === 0 && publicFiles.length === 0\n ? []\n : [` clientDir: ${quote(clientDir)},`]),\n ...(publicFiles.length === 0\n ? []\n : [` publicFiles: ${JSON.stringify([...publicFiles])},`]),\n ...(routablePages.length === 0 ? [] : [` app: { module: app, sourceFile: ${relativeToApp(appFile)} },`]),\r\n ...(errorPage === undefined\r\n ? []\r\n : [` errorPage: { module: errorPage, sourceFile: ${relativeToApp(errorPage.pageFile)} },`]),\r\n \" pages: [\",\r\n ...pageEntries.map((entry) =>\r\n entry\r\n .split(\"\\n\")\r\n .map((line) => ` ${line}`)\r\n .join(\"\\n\"),\r\n ),\r\n \" ],\",\r\n \"});\",\r\n \"\",\r\n ].join(\"\\n\");\r\n\r\n return {\r\n pageCount: pages.length,\r\n barrelFile: await writeBarrel(productionDir, contents),\r\n contents,\r\n pageRoutes,\r\n };\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyDA,MAAM,mBAAmB;CAAC;CAAQ;CAAS;CAAS;CAAS;AAAO;;;;;;;;AASpE,MAAa,oBAA2C;CACtD,KAAK;CACL,iBAAiB;CACjB,QAAQ;EACN,uBAAuB;EACvB,wBAAwB;EACxB,uBAAuB;EACvB,wBAAwB;CAC1B;;;;;;;;;;;;;;;CAeA,QAAQ,OAAO,YACb,iBAAiB,KAAK,cAAc,CAAC,WAAW,OAAgB,CAAC,CACnE;AACF;;AAGA,MAAa,mBAAmB;AAEhC,MAAM,SACJ;AAKF,MAAM,mBAAmB;CACvB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AA8CA,IAAa,qCAAb,cAAwD,MAAM;CAE1C;CACA;CAFlB,AAAO,YACL,AAAgB,YAChB,AAAgB,WAChB,QACA;EACA,MACE,iCAAiC,WAAW,IAAI,OAAO,IAAI,UAAU,uRA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