@nifrajs/web 2.14.1 → 3.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.
Files changed (145) hide show
  1. package/dist/boundary.d.ts +158 -0
  2. package/dist/boundary.d.ts.map +1 -0
  3. package/dist/boundary.js +237 -0
  4. package/dist/boundary.js.map +1 -0
  5. package/dist/build-plan.d.ts +228 -0
  6. package/dist/build-plan.d.ts.map +1 -0
  7. package/dist/build-plan.js +514 -0
  8. package/dist/build-plan.js.map +1 -0
  9. package/dist/build-vite.d.ts +2 -1
  10. package/dist/build-vite.d.ts.map +1 -1
  11. package/dist/build-vite.js +5 -3
  12. package/dist/build-vite.js.map +1 -1
  13. package/dist/build.d.ts +2 -197
  14. package/dist/build.d.ts.map +1 -1
  15. package/dist/build.js +92 -515
  16. package/dist/build.js.map +1 -1
  17. package/dist/chunk-names.d.ts.map +1 -1
  18. package/dist/chunk-names.js +3 -2
  19. package/dist/chunk-names.js.map +1 -1
  20. package/dist/dev-ssr-graph.d.ts.map +1 -1
  21. package/dist/dev-ssr-graph.js +63 -28
  22. package/dist/dev-ssr-graph.js.map +1 -1
  23. package/dist/diagnostic.d.ts.map +1 -1
  24. package/dist/diagnostic.js +9 -2
  25. package/dist/diagnostic.js.map +1 -1
  26. package/dist/fonts-google.d.ts.map +1 -1
  27. package/dist/fonts-google.js +3 -1
  28. package/dist/fonts-google.js.map +1 -1
  29. package/dist/fs.d.ts.map +1 -1
  30. package/dist/fs.js +2 -1
  31. package/dist/fs.js.map +1 -1
  32. package/dist/index.d.ts +16 -589
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +23 -1824
  35. package/dist/index.js.map +1 -1
  36. package/dist/internal/codegen.d.ts +68 -0
  37. package/dist/internal/codegen.d.ts.map +1 -0
  38. package/dist/internal/codegen.js +317 -0
  39. package/dist/internal/codegen.js.map +1 -0
  40. package/dist/internal/fetcher-runtime.d.ts +19 -0
  41. package/dist/internal/fetcher-runtime.d.ts.map +1 -0
  42. package/dist/internal/fetcher-runtime.js +26 -0
  43. package/dist/internal/fetcher-runtime.js.map +1 -0
  44. package/dist/internal/head-merge.d.ts +2 -0
  45. package/dist/internal/head-merge.d.ts.map +1 -1
  46. package/dist/internal/head-merge.js +17 -1
  47. package/dist/internal/head-merge.js.map +1 -1
  48. package/dist/internal/identity-policy.d.ts +51 -0
  49. package/dist/internal/identity-policy.d.ts.map +1 -0
  50. package/dist/internal/identity-policy.js +67 -0
  51. package/dist/internal/identity-policy.js.map +1 -0
  52. package/dist/internal/parity.d.ts +104 -8
  53. package/dist/internal/parity.d.ts.map +1 -1
  54. package/dist/internal/parity.js +472 -56
  55. package/dist/internal/parity.js.map +1 -1
  56. package/dist/internal/query-runtime.d.ts +8 -0
  57. package/dist/internal/query-runtime.d.ts.map +1 -0
  58. package/dist/internal/query-runtime.js +29 -0
  59. package/dist/internal/query-runtime.js.map +1 -0
  60. package/dist/internal/render-document.d.ts +372 -0
  61. package/dist/internal/render-document.d.ts.map +1 -0
  62. package/dist/internal/render-document.js +744 -0
  63. package/dist/internal/render-document.js.map +1 -0
  64. package/dist/internal/runtime-contract.d.ts +48 -0
  65. package/dist/internal/runtime-contract.d.ts.map +1 -0
  66. package/dist/internal/runtime-contract.js +27 -0
  67. package/dist/internal/runtime-contract.js.map +1 -0
  68. package/dist/internal/web-app.d.ts +171 -0
  69. package/dist/internal/web-app.d.ts.map +1 -0
  70. package/dist/internal/web-app.js +844 -0
  71. package/dist/internal/web-app.js.map +1 -0
  72. package/dist/islands.d.ts +50 -2
  73. package/dist/islands.d.ts.map +1 -1
  74. package/dist/islands.js +96 -36
  75. package/dist/islands.js.map +1 -1
  76. package/dist/manifest.d.ts +41 -6
  77. package/dist/manifest.d.ts.map +1 -1
  78. package/dist/manifest.js.map +1 -1
  79. package/dist/module-graph.d.ts.map +1 -1
  80. package/dist/module-graph.js +22 -9
  81. package/dist/module-graph.js.map +1 -1
  82. package/dist/nano.d.ts +125 -0
  83. package/dist/nano.d.ts.map +1 -0
  84. package/dist/nano.js +190 -0
  85. package/dist/nano.js.map +1 -0
  86. package/dist/plugins/css-modules.js +2 -2
  87. package/dist/plugins/css-modules.js.map +1 -1
  88. package/dist/plugins/kit.d.ts +12 -0
  89. package/dist/plugins/kit.d.ts.map +1 -1
  90. package/dist/plugins/kit.js +62 -12
  91. package/dist/plugins/kit.js.map +1 -1
  92. package/dist/plugins/postcss.js +2 -2
  93. package/dist/plugins/postcss.js.map +1 -1
  94. package/dist/plugins/scss.js +2 -2
  95. package/dist/plugins/scss.js.map +1 -1
  96. package/dist/plugins/stylex.d.ts +70 -0
  97. package/dist/plugins/stylex.d.ts.map +1 -0
  98. package/dist/plugins/stylex.js +166 -0
  99. package/dist/plugins/stylex.js.map +1 -0
  100. package/dist/plugins/svg.js +2 -2
  101. package/dist/plugins/svg.js.map +1 -1
  102. package/dist/render-seam.d.ts +5 -0
  103. package/dist/render-seam.d.ts.map +1 -1
  104. package/dist/render-seam.js +10 -0
  105. package/dist/render-seam.js.map +1 -1
  106. package/dist/router.d.ts +11 -1
  107. package/dist/router.d.ts.map +1 -1
  108. package/dist/router.js +254 -47
  109. package/dist/router.js.map +1 -1
  110. package/dist/vite.d.ts.map +1 -1
  111. package/dist/vite.js +34 -16
  112. package/dist/vite.js.map +1 -1
  113. package/package.json +49 -2
  114. package/src/boundary.ts +407 -0
  115. package/src/build-plan.ts +741 -0
  116. package/src/build-vite.ts +6 -7
  117. package/src/build.ts +120 -730
  118. package/src/chunk-names.ts +3 -2
  119. package/src/dev-ssr-graph.ts +63 -28
  120. package/src/diagnostic.ts +14 -2
  121. package/src/fonts-google.ts +3 -1
  122. package/src/fs.ts +2 -1
  123. package/src/index.ts +107 -2553
  124. package/src/internal/codegen.ts +400 -0
  125. package/src/internal/fetcher-runtime.ts +36 -0
  126. package/src/internal/head-merge.ts +19 -1
  127. package/src/internal/identity-policy.ts +94 -0
  128. package/src/internal/parity.ts +603 -71
  129. package/src/internal/query-runtime.ts +31 -0
  130. package/src/internal/render-document.ts +1116 -0
  131. package/src/internal/runtime-contract.ts +54 -0
  132. package/src/internal/web-app.ts +1114 -0
  133. package/src/islands.ts +106 -40
  134. package/src/manifest.ts +50 -3
  135. package/src/module-graph.ts +23 -9
  136. package/src/nano.ts +246 -0
  137. package/src/plugins/css-modules.ts +2 -2
  138. package/src/plugins/kit.ts +65 -12
  139. package/src/plugins/postcss.ts +2 -2
  140. package/src/plugins/scss.ts +2 -2
  141. package/src/plugins/stylex.ts +298 -0
  142. package/src/plugins/svg.ts +2 -2
  143. package/src/render-seam.ts +6 -0
  144. package/src/router.ts +293 -51
  145. package/src/vite.ts +41 -15
package/dist/index.js CHANGED
@@ -7,26 +7,32 @@
7
7
  * the adapter interprets them. That keeps this package both framework-agnostic and free
8
8
  * of DOM types: it is pure server orchestration + string building.
9
9
  */
10
- import { NIFRA_BACKEND_MOUNT, } from "@nifrajs/core/mount";
11
- import { server, urlPartsOf } from "@nifrajs/core/server";
12
- import { DEFERRED_ERROR_CODE, DEFERRED_RUNTIME, defer, MAP_DEFERRED_SOURCE, ndjsonStream, prepareDeferred, } from "./deferred.js";
13
- import { isDraftEnabled } from "./draft.js";
14
- import { trustedHeadAttributes } from "./internal/head-attributes.js";
15
- // Head resolution/merging. Defined in an internal module so `@nifrajs/web/client` can export the same
16
- // two functions to the generated client entry without dragging THIS module (and its server code) into
17
- // the browser graph - see internal/head-merge.ts. Re-exported here so the public API is unchanged.
18
- import { mergeHeads, resolveMeta } from "./internal/head-merge.js";
19
- import { jsStringLiteral } from "./internal/js-string.js";
20
- import { EXECUTABLE_SCRIPT_TYPES, INERT_SCRIPT_TYPES } from "./internal/script-types.js";
21
- import { ISR_REVALIDATE_HEADER, ISR_REVALIDATE_TAGS_HEADER, serializeISRTags } from "./isr.js";
22
- import { generateLlmsTxt } from "./llms-txt.js";
23
- import { ACTION_GLOBAL, DATA_GLOBAL, LAYOUT_DATA_GLOBAL, ROOT_ATTRIBUTE, ROUTE_GLOBAL, } from "./render-seam.js";
24
- import { createMatcher, DATA_HEADER, NAV_FROM_HEADER, PRERENDERED_GLOBAL, REDIRECT_HEADER, RETAIN_HEADER, REVALIDATE_HEADER, STATUS_HEADER, } from "./router.js";
25
- import { searchOf, searchOfChain } from "./search.js";
26
10
  // Draft / preview mode - a signed cookie that flips `ctx.draft` for loaders + bypasses ISR for editors.
11
+ export { assertStaticBoundaryImports, boundaryDescriptors, boundaryModeKey, MemoryStaticBoundaryCache, resolveDynamicBoundaries, resolveStaticBoundaries, startDynamicBoundaries, } from "./boundary.js";
12
+ export { assertRenderAdapterConformance, RenderAdapterConformanceError, } from "./conformance.js";
13
+ // Deferred loader data (`defer()` + the `Deferred<T>` type) - consumed by the adapter's `<Await>`.
14
+ export { defer } from "./deferred.js";
27
15
  export { DRAFT_COOKIE, disableDraft, enableDraft, isDraftEnabled, previewEndpoint, } from "./draft.js";
28
16
  // Font optimization - a CLS-safe `@font-face` generator + a preload `<link>` for self-hosted fonts.
29
17
  export { fontFace, fontPreload, } from "./fonts.js";
18
+ export { generateClientEntry, generateRouteSearchTypes, generateServerManifest, } from "./internal/codegen.js";
19
+ // Generated client entries intentionally import the browser router from the client subpath:
20
+ // `import { createClientRouter, createMatcher, mergeHeads, resolveMeta } from "@nifrajs/web/client"`.
21
+ export { mergeHeads, resolveMeta } from "./internal/head-merge.js";
22
+ export { canonical, gone, jsonLd, notFound, openGraph, redirect, renderPage, renderPageResult, revalidate, serializeData, statusPage, unsafeInlineScript, } from "./internal/render-document.js";
23
+ export { DEFAULT_DEV_PORT, PRE_HYDRATION_GUARD, } from "./internal/runtime-contract.js";
24
+ /**
25
+ * The two file-name conventions that decide what never reaches a browser: a `*.server` module is
26
+ * EMPTIED in the client build, a `*.fn` module is REPLACED with client stubs.
27
+ *
28
+ * Exported because more than the bundlers need them. `nifra dev --bun` cannot transform (Bun's dev
29
+ * bundler takes no plugins) so it must REFUSE instead, and a refusal driven by its own hand-written
30
+ * glob drifts from the transform - which is how `.fn.mts` came to be stubbed by both build pipelines
31
+ * and waved through by the guard that exists to stop it leaking. Anything deciding "is this module
32
+ * server-only" should import the matcher rather than re-encode it.
33
+ */
34
+ export { SERVER_FN_MODULE, SERVER_ONLY_MODULE } from "./internal/server-boundary.js";
35
+ export { createWebApp, } from "./internal/web-app.js";
30
36
  // ISR (incremental static regeneration): a pluggable cache store + the `withISR` stale-while-revalidate
31
37
  // wrapper for rendered SSR responses.
32
38
  export { ISR_REVALIDATE_HEADER, ISR_REVALIDATE_TAGS_HEADER, ISR_STATUS_HEADER, KVCacheStore, MemoryCacheStore, revalidateEndpoint, withISR, } from "./isr.js";
@@ -40,1820 +46,13 @@ export { resolvePublicPath, servePublicDir, } from "./public-dir.js";
40
46
  // Keyed query-cache (agnostic) - a `query(key, fn)` primitive (dedup + staleness + invalidation + GC)
41
47
  // consumed by the per-adapter `useQuery`/`createQuery` bindings.
42
48
  export { createMutation, createQueryClient, hashQueryKey, } from "./query.js";
49
+ export { ACTION_GLOBAL, BOUNDARY_GLOBAL, DATA_GLOBAL, LAYOUT_DATA_GLOBAL, ROOT_ATTRIBUTE, ROUTE_GLOBAL, setSsrModuleLoader, ssrModuleLoader, } from "./render-seam.js";
43
50
  // Agnostic client-side router core (pure + DOM-free) - consumed by per-adapter Router bindings.
44
51
  // `DATA_HEADER` marks a navigation's data-only GET; `createWebApp` answers it with loader JSON.
45
52
  export { createClientRouter, createMatcher, DATA_HEADER, NAV_FROM_HEADER, REDIRECT_HEADER, RETAIN_HEADER, REVALIDATE_HEADER, STATUS_HEADER, } from "./router.js";
46
- // Deferred loader data (`defer()` + the `Deferred<T>` type) - consumed by the adapter's `<Await>`.
47
- export { defer, mergeHeads, resolveMeta };
48
- export { assertRenderAdapterConformance, RenderAdapterConformanceError, } from "./conformance.js";
49
- export { ACTION_GLOBAL, DATA_GLOBAL, LAYOUT_DATA_GLOBAL, ROOT_ATTRIBUTE, ROUTE_GLOBAL, setSsrModuleLoader, ssrModuleLoader, } from "./render-seam.js";
50
53
  // The search-derivation primitive: parse a URL query, validate it against a route's `searchSchema`
51
54
  // (fail-closed to defaults), or return the raw parsed query when there is none. Both the server (loader
52
55
  // ctx + `renderPage`) and a client adapter mount call this with the same URL + schema, so the two sides
53
56
  // produce the identical value by construction. An adapter's `useSearch` binding reads its result.
54
57
  export { searchOf, searchOfChain, serializeSearch } from "./search.js";
55
- /**
56
- * Pre-hydration form guard - a tiny inline script flushed in `<head>` (it runs in the window between
57
- * first paint and the island bundle taking over). It neutralizes the one real hydration footgun: a
58
- * JS-only form (a hand-wired `onSubmit` with no native fallback) submitting *natively* before its
59
- * handler is attached, which navigates the browser to a broken `?field=…` GET of the current page.
60
- *
61
- * It blocks ONLY that shape - an effective-GET form whose action targets the current document - and
62
- * only until hydration commits (`data-nifra-hydrated`, set by the client entry). Method-`post` forms
63
- * (progressive enhancement: the native POST hits the route `action`) and GET forms with a real action
64
- * (a search box → `/search`) pass through untouched. Opt out per-form with `data-native`. Static text
65
- * (no interpolation), so it can't carry injected markup. See the Hydration guide.
66
- */
67
- export const PRE_HYDRATION_GUARD = "(function(){addEventListener('submit',function(e){var f=e.target;" +
68
- "if(!f||f.tagName!=='FORM'||f.hasAttribute('data-native'))return;" +
69
- "if(document.documentElement.hasAttribute('data-nifra-hydrated'))return;" +
70
- "var m=(f.getAttribute('method')||'get').toLowerCase();if(m==='post')return;" +
71
- "var a=f.getAttribute('action');" +
72
- "if(!a||a===''||a==='#'||a===location.pathname||a===location.href)e.preventDefault()" +
73
- "},true)})()";
74
- /**
75
- * The single default port for the dev server (`@nifrajs/web/dev`, `@nifrajs/web/vite`) **and**
76
- * `nifra start`. Deliberately uncommon: `3000`/`5173`/`8080` collide with whatever else is running
77
- * (Next, Vite, a stray Node API). `4321` rarely is - and being the *same* constant across `nifra dev`
78
- * and `nifra start` means a project's URL doesn't change between commands. Override per-run with
79
- * `--port <n>` or the `PORT` env var. */
80
- export const DEFAULT_DEV_PORT = 4321;
81
- // Shared, stateless - allocated once at module load, not per render/stream.
82
- const TEXT_ENCODER = new TextEncoder();
83
- // XSS-safe `<script>` JSON escaping in a SINGLE pass: `<`/`>` would break out of the
84
- // script element; U+2028/U+2029 are valid JSON but historically break JS string literals. Built via
85
- // fromCharCode so no raw separator chars live in this source. One regex + one output string replaces
86
- // the prior four sequential `replaceAll` full-string passes.
87
- const LINE_SEP = String.fromCharCode(0x2028);
88
- const PARA_SEP = String.fromCharCode(0x2029);
89
- const SCRIPT_ESCAPE = new RegExp(`[<>${LINE_SEP}${PARA_SEP}]`, "g");
90
- const SCRIPT_ESCAPE_MAP = {
91
- "<": "\\u003c",
92
- ">": "\\u003e",
93
- [LINE_SEP]: "\\u2028",
94
- [PARA_SEP]: "\\u2029",
95
- };
96
- const NODE_RESPONSE_BODY = Symbol.for("nifra.response.body");
97
- const RESPONSE_RESULT = Symbol.for("nifra.response.result");
98
- /**
99
- * Server: render a full HTML document for a page - the adapter's hydration head + the SSR
100
- * markup (**streamed**) + the serialized loader data + the client module - as a `Response`.
101
- * The shell (`<head>` + the open container) flushes first, the adapter's app stream follows,
102
- * then the tail (data globals + client entry). Pure Web Standards, so it returns straight from
103
- * a nifra route handler and streams on any fetch runtime (Bun/Node/Deno/Workers).
104
- */
105
- export function renderPage(options) {
106
- const page = renderPageResult(options);
107
- return page instanceof Promise ? page.then((p) => p.toResponse()) : page.toResponse();
108
- }
109
- export function renderPageResult(options) {
110
- const { adapter, chain, data, actionData, clientEntry, preload = [], styles = [], prerenderedPaths = [], revalidate, revalidateTags = [], routeId, status = 200, title = "nifra", head, rootId = "root", hydrate = true, islandScripts = [], nonce, headers: extraHeaders, } = options;
111
- if (nonce !== undefined && nonce.trim() === "") {
112
- throw new TypeError("[nifra/web] renderPage nonce must be non-empty when provided");
113
- }
114
- const nonceAttr = nonce === undefined ? "" : ` nonce="${escapeAttr(nonce)}"`;
115
- const route = routeId === undefined ? "" : `window.${ROUTE_GLOBAL}=${serializeData(routeId)};`;
116
- // The SSG prerendered-path set (when an app declares it) - the client reads it to fetch a static
117
- // `_data.json` on soft-nav into a prerendered route instead of hitting the worker. Empty ⇒ omitted.
118
- const prerendered = prerenderedPaths.length === 0
119
- ? ""
120
- : `window.${PRERENDERED_GLOBAL}=${serializeData(prerenderedPaths)};`;
121
- // Split deferred values: the component sees markers (id + promise) to `<Await>`; the serialized
122
- // data carries `{__nifra_deferred: id}` placeholders (promises don't serialize). `actionData` may
123
- // also `defer()` - split it too, continuing the id space so a single registry settles both. The
124
- // inline registry runtime is emitted only when something defers, so non-deferred output is unchanged.
125
- const { forComponent, forClient, deferred } = prepareDeferred(data);
126
- // Each layout's data is split in turn, each continuing the id space, so a `defer()` in a layout
127
- // settles through the SAME registry as the page's rather than colliding on ids.
128
- const layoutSplits = [];
129
- if (options.layoutData !== undefined) {
130
- let offset = deferred.length;
131
- for (const entry of options.layoutData) {
132
- const split = prepareDeferred(entry, offset);
133
- offset += split.deferred.length;
134
- layoutSplits.push(split);
135
- }
136
- }
137
- const layoutDeferred = layoutSplits.flatMap((split) => split.deferred);
138
- const actionSplit = actionData === undefined
139
- ? undefined
140
- : prepareDeferred(actionData, deferred.length + layoutDeferred.length);
141
- // On the common page-only path (no layout loader, no action) reuse `deferred` directly instead of
142
- // allocating a fresh spread array every request.
143
- const allDeferred = layoutDeferred.length === 0 && actionSplit === undefined
144
- ? deferred
145
- : [...deferred, ...layoutDeferred, ...(actionSplit ? actionSplit.deferred : [])];
146
- // Omitted entirely when no layout has a loader - a page-only app emits exactly what it did before.
147
- const layoutTail = options.layoutData === undefined
148
- ? ""
149
- : `window.${LAYOUT_DATA_GLOBAL}=${serializeData(layoutSplits.map((split) => split.forClient))};`;
150
- // Only emit the action global when an action actually ran, so plain GET output is unchanged.
151
- const action = actionSplit === undefined
152
- ? ""
153
- : `window.${ACTION_GLOBAL}=${serializeData(actionSplit.forClient)};`;
154
- const deferredRuntime = allDeferred.length > 0 ? `<script${nonceAttr}>${DEFERRED_RUNTIME}</script>` : "";
155
- // The regex only injects the CSP nonce into the (constant) hydration head; with no nonce it's a
156
- // no-op that still scans the whole script every request. Skip it on the common no-nonce path.
157
- // The request-invariant document pieces. With a caller-supplied per-route cache (and no per-request
158
- // nonce, which would bake into them) they're built once and reused; the per-request seams - the
159
- // deferred runtime in the shell, the action/layout-data globals and the serialized loader data in
160
- // the tail - are always assembled fresh. Byte-identical to building the whole document inline.
161
- const slot = nonce === undefined && options.assemblyCache !== undefined ? options.assemblyCache : {};
162
- if (slot.shellPre === undefined) {
163
- // Matched-route chunk preloads, concatenated directly. De-duped against the entry, which is
164
- // preloaded separately below.
165
- let preloadLinks = "";
166
- for (const url of preload) {
167
- if (url !== clientEntry)
168
- preloadLinks += `<link rel="modulepreload" href="${escapeAttr(url)}">`;
169
- }
170
- // The matched route's stylesheets - `<link rel="stylesheet">` in `<head>` so CSS arrives with the
171
- // first paint (no FOUC). Render-blocking by design, and emitted regardless of `hydrate` (a static
172
- // or `_error` page still wants its styles). In dev (Vite) CSS is injected client-side instead.
173
- let styleLinks = "";
174
- for (const url of styles)
175
- styleLinks += `<link rel="stylesheet" href="${escapeAttr(url)}">`;
176
- // Island bundles are referenced only by a `<script type="module">` at the END of `<body>`, so the
177
- // browser doesn't discover them until the whole page is parsed. `modulepreload` them in `<head>`
178
- // so the fetch starts immediately, in parallel with parsing - regardless of `hydrate`.
179
- let islandPreloads = "";
180
- for (const src of islandScripts)
181
- islandPreloads += `<link rel="modulepreload" href="${escapeAttr(src)}">`;
182
- // Runs in the first-paint→hydration window to swallow a JS-only form's broken native submit. Only
183
- // on a hydrating page (a static/_error page has no client handlers, so no footgun).
184
- const hydrationGuard = hydrate ? `<script${nonceAttr}>${PRE_HYDRATION_GUARD}</script>` : "";
185
- // `<html>` attributes. `lang` defaults to `"en"`; `dir` is omitted entirely when unset, which IS
186
- // HTML's `ltr` default. Both attribute-escaped. `client.ts`'s `applyHead` mirrors this exact
187
- // defaulting on soft-nav, so a hard load and a client navigation produce the same `<html>`.
188
- const htmlAttrs = ` lang="${escapeAttr(head?.lang ?? "en")}"${head?.dir === undefined ? "" : ` dir="${escapeAttr(head.dir)}"`}`;
189
- // Marks the container for the client entry when the id is not the one the entry falls back to.
190
- const rootMarker = rootId === "root" ? "" : ` ${ROOT_ATTRIBUTE}`;
191
- // A non-hydrated page omits the adapter's hydration bootstrap entirely (Solid's `_$HY` registry
192
- // script, etc.) - there is no client takeover to feed, so it's dead bytes on a static document.
193
- // The nonce rewrite only runs when a nonce is set; with none it was a whole-string no-op scan.
194
- const rawHydrationHead = hydrate ? adapter.hydrationHead(nonce) : "";
195
- const hydrationHead = nonce === undefined
196
- ? rawHydrationHead
197
- : rawHydrationHead.replace(/<script(?![^>]*\bnonce=)(?=[\s>])/g, `<script${nonceAttr}`);
198
- // Shell up to the deferred-runtime seam: on a hydrating page that seam sits after the entry +
199
- // route-chunk preloads; a non-hydrating page has no runtime insertion at all.
200
- const entryPreloads = hydrate
201
- ? `<link rel="modulepreload" href="${escapeAttr(clientEntry ?? "")}">${preloadLinks}`
202
- : "";
203
- slot.shellPre = `<!doctype html><html${htmlAttrs}><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">${hydrationGuard}<title>${escapeHtml(head?.title ?? title)}</title>${headTags(head)}${styleLinks}${entryPreloads}`;
204
- slot.shellPost = `${islandPreloads}${hydrationHead}</head><body><div id="${escapeAttr(rootId)}"${rootMarker}>`;
205
- // Island bundles load regardless of `hydrate` - a static page (hydrate:false) ships no framework
206
- // client but can still mount no-framework islands (`@nifrajs/web/islands`).
207
- let islandTags = "";
208
- for (const src of islandScripts)
209
- islandTags += `<script type="module" src="${escapeAttr(src)}"${nonceAttr}></script>`;
210
- if (hydrate) {
211
- slot.tailPre = `<script${nonceAttr}>${route}`;
212
- slot.tailMid = prerendered;
213
- slot.tailData = `window.${DATA_GLOBAL}=`;
214
- slot.tailPost = `</script><script type="module" src="${escapeAttr(clientEntry ?? "")}"${nonceAttr}></script>${islandTags}</body></html>`;
215
- }
216
- else {
217
- slot.tailPre = "";
218
- slot.tailMid = "";
219
- slot.tailData = "";
220
- slot.tailPost = `${islandTags}</body></html>`;
221
- }
222
- }
223
- // The deferred runtime rides only on a hydrating page (a static page has no client takeover), and
224
- // only when something actually deferred - matching the pre-cache emission exactly.
225
- const runtimeSeam = hydrate && allDeferred.length > 0 ? deferredRuntime : "";
226
- const shellHtml = `${slot.shellPre}${runtimeSeam}${slot.shellPost}`;
227
- // Closes the hydration container; deferred resolve scripts go AFTER it (outside `#root`) so they
228
- // aren't part of the adapter's hydrated tree (an inline script inside it breaks hydration).
229
- const closeRootHtml = "</div>";
230
- // Tail - the loader-data globals + the client module. Module scripts defer (run after parse), so
231
- // the data global + every streamed deferred resolution are set before the entry hydrates.
232
- const tailHtml = hydrate
233
- ? `${slot.tailPre}${action}${slot.tailMid}${layoutTail}${slot.tailData}${serializeData(forClient)}${slot.tailPost}`
234
- : slot.tailPost;
235
- const headers = { "content-type": "text/html; charset=utf-8" };
236
- // Caller-supplied headers (a terminal status page's `cache-control`, say). Applied before the
237
- // framework's own below, so `content-type` and the ISR channel stay authoritative - a caller must
238
- // not be able to mislabel the document or forge the freshness header by passing them here.
239
- if (extraHeaders !== undefined) {
240
- for (const [name, value] of new Headers(extraHeaders)) {
241
- if (name !== "content-type")
242
- headers[name] = value;
243
- }
244
- }
245
- // ISR: advertise the route's freshness so a `withISR` wrapper can set this page's cache TTL. A
246
- // dedicated header (not the action-revalidation `x-nifra-revalidate`) so the TTL channel never aliases
247
- // the client's path-list channel.
248
- if (revalidate !== undefined)
249
- headers[ISR_REVALIDATE_HEADER] = String(revalidate);
250
- const serializedTags = serializeISRTags(revalidateTags);
251
- if (serializedTags !== undefined)
252
- headers[ISR_REVALIDATE_TAGS_HEADER] = serializedTags;
253
- const renderProps = {
254
- data: forComponent,
255
- actionData: actionSplit?.forComponent,
256
- // `params`/`path` thread the matched route + URL to the adapter's `useParams`/`useLocation` so they
257
- // render SSR-correct. Spread only when supplied (exactOptionalPropertyTypes) - an adapter with no
258
- // router bindings simply never reads them.
259
- ...(options.params !== undefined ? { params: options.params } : {}),
260
- ...(options.path !== undefined ? { path: options.path } : {}),
261
- // Same rule for `search`: the validated query the adapter's `useSearch` reads, spread only when the
262
- // caller supplied it (a non-router render never has it).
263
- ...(options.search !== undefined ? { search: options.search } : {}),
264
- // Spread only when present, so a page-only render produces exactly the props it did before.
265
- ...(options.layoutData !== undefined
266
- ? { layoutData: layoutSplits.map((split) => split.forComponent) }
267
- : {}),
268
- };
269
- // Fast path: nothing `defer()`s and the adapter can render synchronously to a string → buffer the
270
- // whole document in one pass. Progressive streaming only benefits pages with deferred boundaries
271
- // (those take the streaming path below); for a plain page the streaming pipeline + the framework's
272
- // streaming renderer are pure overhead vs a single sync render + concat. A buffered string body also
273
- // gets an automatic Content-Length. A render throw surfaces here exactly as the streaming path's
274
- // shell-readiness `await` does, so the `_error` boundary still maps it to a status.
275
- if (allDeferred.length === 0 && adapter.renderToString !== undefined) {
276
- const out = adapter.renderToString(chain, renderProps);
277
- return typeof out === "string"
278
- ? new BufferedRenderedPage(shellHtml + out + closeRootHtml + tailHtml, status, headers)
279
- : out.then((bodyHtml) => new BufferedRenderedPage(shellHtml + bodyHtml + closeRootHtml + tailHtml, status, headers));
280
- }
281
- return renderStreamedPage(adapter, chain, renderProps, shellHtml, closeRootHtml, allDeferred, tailHtml, status, headers, nonceAttr).then((response) => new ResponseRenderedPage(response));
282
- }
283
- async function renderStreamedPage(adapter, chain, renderProps, shellHtml, closeRootHtml, allDeferred, tailHtml, status, headers, nonceAttr) {
284
- // Streaming path - required for `defer()` (progressive `<Await>` resolution) and used by any adapter
285
- // that doesn't implement `renderToString`. Awaiting `renderToStream` resolves on shell-readiness
286
- // (React: on-shell-ready; Solid: synchronously), so a shell-render throw surfaces before any byte is
287
- // sent. A *mid*-stream failure errors the body instead.
288
- const enc = TEXT_ENCODER;
289
- const shell = enc.encode(shellHtml);
290
- const closeRoot = enc.encode(closeRootHtml);
291
- const tail = enc.encode(tailHtml);
292
- const appStream = await adapter.renderToStream(chain, renderProps);
293
- const body = streamDocument(shell, appStream, closeRoot, allDeferred, tail, enc, nonceAttr);
294
- return new Response(body, { status, headers });
295
- }
296
- class BufferedRenderedPage {
297
- [RESPONSE_RESULT] = true;
298
- body;
299
- status;
300
- headers;
301
- constructor(body, status, headers) {
302
- this.body = body;
303
- this.status = status;
304
- this.headers = headers;
305
- }
306
- toResponse() {
307
- return htmlResponse(this.body, { status: this.status, headers: this.headers });
308
- }
309
- toNodeBody() {
310
- return { status: this.status, headers: this.headers, body: this.body };
311
- }
312
- }
313
- class ResponseRenderedPage {
314
- [RESPONSE_RESULT] = true;
315
- response;
316
- constructor(response) {
317
- this.response = response;
318
- }
319
- toResponse() {
320
- return this.response;
321
- }
322
- }
323
- function htmlResponse(body, init) {
324
- const response = new Response(body, init);
325
- // @nifrajs/node can write buffered HTML straight to ServerResponse with `end(body)`, avoiding a Web
326
- // Response stream drain on Node. Non-enumerable + Symbol.for keeps this invisible to Web runtimes and
327
- // cross-package without adding a runtime dependency from @nifrajs/node to @nifrajs/web.
328
- Object.defineProperty(response, NODE_RESPONSE_BODY, { value: body });
329
- return response;
330
- }
331
- /**
332
- * Assemble the document stream: `shell` → the app `stream` (forwarded chunk-by-chunk, so a streaming
333
- * renderer's progressive flushing is preserved) → `closeRoot` → one `__nifraResolve`/`__nifraReject`
334
- * script per deferred value (emitted once its promise settles - by now the app stream has awaited
335
- * the same Suspense boundaries - and placed OUTSIDE `#root`) → `tail`. A mid-stream app error errors
336
- * the result (the body breaks) rather than silently truncating a 200.
337
- */
338
- function streamDocument(shell, stream, closeRoot, deferred, tail, enc, nonceAttr) {
339
- return new ReadableStream({
340
- async start(controller) {
341
- const reader = stream.getReader();
342
- try {
343
- controller.enqueue(shell);
344
- for (;;) {
345
- const { done, value } = await reader.read();
346
- if (done)
347
- break;
348
- controller.enqueue(value);
349
- }
350
- controller.enqueue(closeRoot);
351
- // Stream each resolution as ITS OWN promise settles - NOT in array order. A slow
352
- // defer() must not block a faster one; each script self-addresses by id, so order is irrelevant.
353
- await Promise.all(deferred.map(async (d) => {
354
- try {
355
- const value = serializeData(await d.promise);
356
- controller.enqueue(enc.encode(`<script${nonceAttr}>window.__nifraResolve(${d.id},${value})</script>`));
357
- }
358
- catch (err) {
359
- // A rejected deferred streams __nifraReject (the client `<Await>` surfaces it) - it must
360
- // not break the whole body. Redact: stream a stable opaque code, never the raw error
361
- // text; log the real reason server-side.
362
- console.error("[nifra/web] deferred value rejected:", err);
363
- controller.enqueue(enc.encode(`<script${nonceAttr}>window.__nifraReject(${d.id},${serializeData(DEFERRED_ERROR_CODE)})</script>`));
364
- }
365
- }));
366
- controller.enqueue(tail);
367
- controller.close();
368
- }
369
- catch (err) {
370
- controller.error(err);
371
- }
372
- finally {
373
- reader.releaseLock();
374
- }
375
- },
376
- });
377
- }
378
- /** A same-origin destination is an absolute path: one leading `/`, but NOT `//` (protocol-relative →
379
- * another origin). Everything else (absolute URL with a scheme, `//host`, `javascript:`, a bare
380
- * relative `foo`) is treated as off-origin and requires `external: true`. */
381
- function isSameOriginPath(location) {
382
- return location.startsWith("/") && !location.startsWith("//");
383
- }
384
- /**
385
- * Build a redirect `Response` - return it from a route `action` for the Post/Redirect/Get
386
- * pattern (POST mutates, 303 sends the browser to a fresh GET, so a reload doesn't re-submit).
387
- * Defaults to 303 (See Other); pass `{ status: 307 }` or `{ status: 308 }` to preserve the method.
388
- *
389
- * **Secure by default:** `location` must be a same-origin path (begins with `/`, not `//`). An
390
- * off-origin/absolute destination throws unless you pass `{ external: true }` - this closes the
391
- * open-redirect footgun of `return redirect(formData.get("next"))` on the no-JS (native-form) path,
392
- * which returns the action's `Response` verbatim.
393
- *
394
- * @param options redirect status and whether an off-origin destination is intentional.
395
- */
396
- export function redirect(location, options = {}) {
397
- if (options.external !== true && !isSameOriginPath(location)) {
398
- throw new Error(`[nifra/web] redirect(${JSON.stringify(location)}) is not a same-origin path. Use a path beginning with "/" (not "//"), or redirect(location, { external: true }) for a deliberate off-origin redirect. This guards against open redirects from unvalidated input.`);
399
- }
400
- // Reject CR/LF in the Location explicitly - defense-in-depth (response splitting / header
401
- // injection). Spec-correct runtimes' Headers setter throws on CR/LF, but `external: true` lets
402
- // unvalidated input reach this sink, so we don't rely on the runtime. Same posture as
403
- // serializeCookie / the SSE frame formatter, which strip CRLF at their sinks.
404
- if (/[\r\n]/.test(location)) {
405
- throw new Error(`[nifra/web] redirect location contains a CR/LF character - refusing to emit a header-injecting redirect.`);
406
- }
407
- return new Response(null, { status: options.status ?? 303, headers: { location } });
408
- }
409
- /**
410
- * The signatures a **duplicate module instance** produces during SSR, across engines.
411
- *
412
- * Two copies of React (or of `@nifrajs/core`) at the SAME version still fail, because module identity
413
- * is path-based: hooks read a dispatcher off the copy that rendered, and the component imported the
414
- * other one. The error that surfaces names a React internal, so it reads as a React bug and the actual
415
- * cause - two directories - is a long inference away. Naming the cause at the point of failure is the
416
- * difference between that and a five-second read.
417
- */
418
- const DUPLICATE_INSTANCE_SIGNATURES = [
419
- /resolveDispatcher\(\)/,
420
- /Invalid hook call/,
421
- /Cannot read propert(?:y|ies) of null \(reading '(?:use[A-Z]\w*)'\)/,
422
- /null is not an object \(evaluating '.*\.use[A-Z]\w*'\)/,
423
- ];
424
- /**
425
- * Append the likely cause to an SSR error that carries a duplicate-instance signature.
426
- *
427
- * Deliberately does NOT claim the resolved paths: `@nifrajs/web` is framework-agnostic and does not
428
- * depend on React, so it cannot resolve the copies without guessing. It names the condition and the
429
- * command that reports the paths, which is the actionable part. Returns the error untouched when the
430
- * signature does not match, so an ordinary render error reads exactly as before.
431
- */
432
- function withDuplicateInstanceHint(err) {
433
- if (!(err instanceof Error))
434
- return err;
435
- if (!DUPLICATE_INSTANCE_SIGNATURES.some((rx) => rx.test(err.message)))
436
- return err;
437
- const augmented = new Error(`${err.message}\n\n[nifra/web] This signature usually means TWO COPIES of an identity-sensitive package (react, react-dom, or @nifrajs/core) are installed at different paths. Module identity is path-based, so matching versions do NOT fix it - the copies must resolve to the same directory. Run \`nifra check\` to list the paths.`, { cause: err });
438
- augmented.name = err.name;
439
- // `stack` is optional under exactOptionalPropertyTypes; assigning `undefined` would replace a real
440
- // stack with nothing on engines that always populate it.
441
- if (err.stack !== undefined)
442
- augmented.stack = err.stack;
443
- return augmented;
444
- }
445
- /**
446
- * An action's `Response` passes straight through - except a redirect on a client-submit data
447
- * request: fetch would follow the 3xx into HTML the client can't use, so the redirect rides the
448
- * X-Nifra-Redirect header on a 204 and the client navigates. One conversion shared by the
449
- * returned- and thrown-Response paths, so `return redirect()` and `throw redirect()` agree.
450
- */
451
- function actionResponse(response, isDataRequest) {
452
- if (isDataRequest && response.status >= 300 && response.status < 400) {
453
- const location = response.headers.get("location") ?? "/";
454
- return new Response(null, { status: 204, headers: { [REDIRECT_HEADER]: location } });
455
- }
456
- return response;
457
- }
458
- /**
459
- * Narrow the route's params to the ones a layout owns.
460
- *
461
- * A layout wraps a URL prefix, so anything deeper belongs to a route beneath it. Handing it the full
462
- * set would let a layout read a param it does not own - which reads fine until the layout is reused
463
- * under a route that has no such param and the value silently becomes `undefined`.
464
- */
465
- function scopeParams(params, owned) {
466
- if (owned === undefined)
467
- return params; // hand-built manifest with no scope info: unchanged behaviour
468
- if (owned.length === 0)
469
- return EMPTY_LAYOUT_PARAMS;
470
- const scoped = {};
471
- for (const name of owned) {
472
- const value = params[name];
473
- if (value !== undefined)
474
- scoped[name] = value;
475
- }
476
- return scoped;
477
- }
478
- const EMPTY_LAYOUT_PARAMS = Object.freeze({});
479
- const EMPTY_RETAIN = new Set();
480
- /**
481
- * Marks an error as coming from a LAYOUT loader, carrying that layout's id.
482
- *
483
- * The boundary that catches it must be at or above the failing layout's own segment. The route's
484
- * innermost `_error` may live BELOW the layout that failed, and rendering there would wrap the
485
- * boundary in a layout whose data never arrived - so the page would render inside a component that
486
- * threw. A registry symbol, matching the other cross-module brands here.
487
- */
488
- const LAYOUT_ERROR_ID = Symbol.for("nifra.web.layout-error-id");
489
- const tagLayoutError = (err, layoutId) => {
490
- if (typeof err === "object" && err !== null && !(LAYOUT_ERROR_ID in err)) {
491
- Object.defineProperty(err, LAYOUT_ERROR_ID, { value: layoutId, enumerable: false });
492
- }
493
- return err;
494
- };
495
- const layoutErrorId = (err) => typeof err === "object" && err !== null
496
- ? err[LAYOUT_ERROR_ID]
497
- : undefined;
498
- const STATUS_SIGNAL = Symbol.for("nifra.web.status-signal");
499
- /** Reason phrases for the plain-text fallback, used only when the app authored no `_<status>` and no
500
- * `_404` page. Deliberately not exhaustive - anything unlisted falls back to "Error", which is more
501
- * useful than shipping a table of every RFC status for a body almost nobody will see. */
502
- const STATUS_TEXT = {
503
- 400: "Bad Request",
504
- 401: "Unauthorized",
505
- 402: "Payment Required",
506
- 403: "Forbidden",
507
- 404: "Not Found",
508
- 410: "Gone",
509
- 451: "Unavailable For Legal Reasons",
510
- 500: "Internal Server Error",
511
- };
512
- function isStatusSignal(value) {
513
- return value instanceof Response && STATUS_SIGNAL in value;
514
- }
515
- function statusSignal(status, options) {
516
- if (!Number.isInteger(status) || status < 400 || status > 599) {
517
- throw new Error(`[nifra/web] statusPage(${JSON.stringify(status)}) must be an integer 4xx or 5xx status. Use redirect() for 3xx, and return data for a successful render.`);
518
- }
519
- const response = new Response(null, { status });
520
- // Non-enumerable so the brand never lands in a structured clone or a JSON log of the response.
521
- Object.defineProperty(response, STATUS_SIGNAL, {
522
- value: { status, ...(options.headers !== undefined ? { headers: options.headers } : {}) },
523
- enumerable: false,
524
- });
525
- throw response;
526
- }
527
- /**
528
- * Render the nearest `_404` page at status **404**. `throw` it from a loader when the record does not
529
- * exist.
530
- *
531
- * This is the fix for the soft 404: a matched route whose loader finds nothing has otherwise no way to
532
- * answer 404, so the path of least resistance is to return empty data and render "not found" inside a
533
- * **200**. That looks correct in a browser and is invisible in review, which is why it ships and stays
534
- * shipped - while search engines penalise it and keep the dead URL indexed.
535
- *
536
- * Returns `never`: these throw, so a loader narrows without a redundant `return`, and the type states
537
- * the thing the "loaders `throw` redirect, actions `return` it" rule already trips people on.
538
- */
539
- export function notFound(options = {}) {
540
- return statusSignal(404, options);
541
- }
542
- /**
543
- * Render a terminal page at status **410 Gone**. `throw` it from a loader for a record that existed and
544
- * was deliberately removed - a withdrawn listing, a deleted post.
545
- *
546
- * 410 is not a pedantic 404: it tells a crawler to **drop** the URL rather than re-fetch it for weeks
547
- * on the assumption the 404 was transient. Uses `_410.tsx` if the app has one, otherwise `_404`.
548
- */
549
- export function gone(options = {}) {
550
- return statusSignal(410, options);
551
- }
552
- /**
553
- * Render a terminal page at any 4xx/5xx status - the escape hatch behind {@link notFound} and
554
- * {@link gone} (402, 451, …). Uses `_<status>.tsx` if present, otherwise `_404`.
555
- */
556
- export function statusPage(status, options = {}) {
557
- return statusSignal(status, options);
558
- }
559
- /**
560
- * Return this from an action to declare which routes the mutation changed (alongside the action's
561
- * `data`). `createWebApp` sets the `X-Nifra-Revalidate` response header; after the submit the client
562
- * marks those cached routes stale - refetching the active one and any mounted fetcher showing them -
563
- * so a mutation can refresh views beyond the one that was submitted. `data` is still surfaced to the
564
- * component as `actionData` (the wrapper is transparent to `ActionData<typeof action>`).
565
- */
566
- export function revalidate(paths, data) {
567
- return { __nifraRevalidate: paths, data };
568
- }
569
- /**
570
- * Serialize loader data for embedding inside an inline `<script>`. `JSON.stringify` alone
571
- * is NOT safe there: a string containing `</script>` or `<!--` would break out of the
572
- * script element (an XSS vector). Escape `<`/`>` to `\uXXXX`, plus the U+2028/U+2029
573
- * separators.
574
- */
575
- export function serializeData(data) {
576
- const serialized = JSON.stringify(data ?? null);
577
- // Most loader payloads contain no script-sensitive characters. Guard with chained `indexOf`
578
- // rather than a regex `.test`: each probe is a native memchr-style scan, measured ~7x faster than
579
- // the regex scan on V8 for a multi-KB payload (and the engine rejects the two >0xFF separator
580
- // probes in O(1) when the string is internally one-byte, which serialized JSON almost always is).
581
- // The same four characters are probed as the SCRIPT_ESCAPE class, so any payload the regex would
582
- // escape still takes the escape path - this is only a cheaper detector, never a security
583
- // relaxation.
584
- const needsEscape = serialized.indexOf("<") !== -1 ||
585
- serialized.indexOf(">") !== -1 ||
586
- serialized.indexOf(LINE_SEP) !== -1 ||
587
- serialized.indexOf(PARA_SEP) !== -1;
588
- return needsEscape
589
- ? serialized.replace(SCRIPT_ESCAPE, (ch) => SCRIPT_ESCAPE_MAP[ch] ?? ch)
590
- : serialized;
591
- }
592
- function escapeHtml(value) {
593
- return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
594
- }
595
- /**
596
- * Escape a `<script>` element's text content so it cannot break out of the element. Per the HTML spec,
597
- * a script's text may contain any character EXCEPT the sequences that the parser treats as element
598
- * boundaries: `</` (which would begin the end tag - `</script>` is the obvious XSS vector, but ANY `</`
599
- * starts script-data-end-tag parsing), and the comment/CDATA edges `<!--` / `]]>`. We escape the `<`
600
- * (and the `>` of `]]>`) to its JS unicode escape: inside a JS/JSON string literal `<` is the
601
- * identical character, so a JSON-LD payload is byte-equivalent after parsing - but the raw `<`/`>` the
602
- * HTML tokenizer scans for is gone. This is the JSON-LD-in-HTML rule (content is JSON, never raw HTML),
603
- * mirroring {@link serializeData}'s posture for the data-global script. Idempotent on already-safe text.
604
- */
605
- function escapeScriptContent(content) {
606
- // Order matters: rewrite `]]>` first (its `>` becomes `>`), then every `<` (covers `</` and
607
- // `<!--` in one pass). `<` → `<`; the lone `>` of `]]>` → `>`. A bare `>` elsewhere is
608
- // harmless in script data, so only the `]]>` close is targeted for `>`.
609
- return content.replaceAll("]]>", "]]\\u003e").replaceAll("<", "\\u003c");
610
- }
611
- function escapeAttr(value) {
612
- return value
613
- .replaceAll("&", "&amp;")
614
- .replaceAll('"', "&quot;")
615
- .replaceAll("<", "&lt;")
616
- .replaceAll(">", "&gt;");
617
- }
618
- /** Serialize attributes that passed the shared SSR/client head trust policy. */
619
- function tagAttrs(tag, attrs) {
620
- const trusted = trustedHeadAttributes(tag, attrs);
621
- if (trusted === null)
622
- return null;
623
- let out = "";
624
- for (const [name, value] of trusted) {
625
- if (out !== "")
626
- out += " ";
627
- out += value === true ? name : `${name}="${escapeAttr(value)}"`;
628
- }
629
- return out;
630
- }
631
- // Memoize the serialized head-tag string by the resolved `Meta` object's identity. A STATIC route
632
- // `meta` is returned by-reference from resolveMeta, so the same object recurs every request → cache
633
- // hit, and the invariant string is serialized once per route, not per request. A FUNCTION `meta`
634
- // builds a fresh object each request (new identity) → miss → recompute, exactly as needed (its
635
- // content can vary). WeakMap so a route module that's GC'd takes its entry with it.
636
- const headTagsCache = new WeakMap();
637
- function assertExecutableScriptType(type) {
638
- if (!EXECUTABLE_SCRIPT_TYPES.has(type)) {
639
- throw new TypeError(`[nifra/web] executable inline scripts accept ${[...EXECUTABLE_SCRIPT_TYPES].map((t) => JSON.stringify(t)).join(" or ")}; received ${JSON.stringify(type)}`);
640
- }
641
- }
642
- /** Render a route's `meta`/`link`/`script` as managed (`data-nifra`) head tags. Title is set
643
- * separately. XSS-safe by construction: every attribute flows through the shared tag-specific trust
644
- * policy then value escaping, and each `script[].content` through `escapeScriptContent`
645
- * (breakout-escaped) - so loader-derived strings (LLM-authored `og:*`, user content) can't inject markup
646
- * or close the tag early. String concatenation (no intermediate `.map()` arrays + spread) - parity with
647
- * the already concat-based preloadLinks/styleLinks/islandPreloads loops; byte-identical output. Result
648
- * is memoized per resolved-`Meta` identity (static meta → serialized once per route). */
649
- function headTags(head) {
650
- if (head === undefined)
651
- return "";
652
- const cached = headTagsCache.get(head);
653
- if (cached !== undefined)
654
- return cached;
655
- let out = "";
656
- if (head.meta !== undefined)
657
- for (const m of head.meta) {
658
- const attrs = tagAttrs("meta", m);
659
- if (attrs !== null)
660
- out += `<meta${attrs === "" ? "" : ` ${attrs}`} data-nifra>`;
661
- }
662
- if (head.link !== undefined)
663
- for (const l of head.link) {
664
- const attrs = tagAttrs("link", l);
665
- if (attrs !== null)
666
- out += `<link${attrs === "" ? "" : ` ${attrs}`} data-nifra>`;
667
- }
668
- // `<script>` slot - JSON-LD + other inert head scripts. `type` is attribute-escaped; `content` is
669
- // breakout-escaped (`escapeScriptContent`) so a `</script>` (or `<!--`/`]]>`) payload can't close the
670
- // element early. Managed (`data-nifra`) so a soft-nav's `applyHead` cleanly replaces it.
671
- if (head.script !== undefined)
672
- for (const s of head.script) {
673
- const type = s.type ?? "application/ld+json";
674
- if (!INERT_SCRIPT_TYPES.has(type)) {
675
- throw new TypeError(`[nifra/web] head.script only accepts inert JSON script types; received ${JSON.stringify(type)}. Use unsafeInlineScript() with a CSP nonce for executable code.`);
676
- }
677
- out += `<script type="${type}" data-nifra>${escapeScriptContent(s.content)}</script>`;
678
- }
679
- if (head.unsafeScript !== undefined)
680
- for (const s of head.unsafeScript) {
681
- if (s.unsafe !== true || s.nonce.trim() === "") {
682
- throw new TypeError("[nifra/web] executable inline scripts require a non-empty CSP nonce");
683
- }
684
- // `type` is validated, not escaped, for the same reason as the inert slot above: an unknown
685
- // value here is a bug, and escaping one would emit a nonsense script type rather than say so.
686
- // It was interpolated raw while the `nonce` beside it was escaped, so a descriptor built by hand
687
- // - `unsafeScript` is a public field, the helper is only a convenience - could close the
688
- // attribute and inject markup. Measured: `type: '"><img src=x onerror=alert(1)>'` reached the
689
- // document. An injection in the slot whose whole purpose is to make script emission trustworthy.
690
- assertExecutableScriptType(s.type);
691
- out += `<script type="${s.type}" nonce="${escapeAttr(s.nonce)}" data-nifra>${escapeScriptContent(s.content)}</script>`;
692
- }
693
- headTagsCache.set(head, out);
694
- return out;
695
- }
696
- /**
697
- * A `<link rel="canonical">` descriptor for a route's `meta.link`. The canonical URL tells search
698
- * engines which URL is authoritative for a page (deduping query-string / tracking variants).
699
- *
700
- * ```ts
701
- * export const meta = (a) => ({ link: [canonical(`https://site.com/posts/${a.params.slug}`)] })
702
- * ```
703
- */
704
- export function canonical(href) {
705
- return { rel: "canonical", href };
706
- }
707
- /**
708
- * Build the Open Graph `<meta property="og:*">` entries for a route's `meta.meta`. Returns only the
709
- * properties you supplied (plus `og:type`, defaulting to `"website"`), so it composes with other meta.
710
- *
711
- * ```ts
712
- * export const meta = { meta: [...openGraph({ title: "Nifra", image: "https://site.com/og.png" })] }
713
- * ```
714
- */
715
- export function openGraph(input) {
716
- const tags = [];
717
- const add = (property, content) => {
718
- if (content !== undefined)
719
- tags.push({ property, content });
720
- };
721
- add("og:title", input.title);
722
- add("og:description", input.description);
723
- add("og:image", input.image);
724
- add("og:url", input.url);
725
- // `og:type` always present (the spec's required property) - default "website" when unset.
726
- tags.push({ property: "og:type", content: input.type ?? "website" });
727
- return tags;
728
- }
729
- /**
730
- * Build a JSON-LD `<script type="application/ld+json">` entry for a route's `meta.script` from a plain
731
- * object. `JSON.stringify` produces the body; the head renderer breakout-escapes it (see
732
- * `escapeScriptContent`), so a string field containing `</script>` is embedded safely.
733
- *
734
- * ```ts
735
- * export const meta = {
736
- * script: [jsonLd({ "@context": "https://schema.org", "@type": "Article", headline: "Hi" })],
737
- * }
738
- * ```
739
- */
740
- export function jsonLd(data) {
741
- return { type: "application/ld+json", content: JSON.stringify(data) };
742
- }
743
- /**
744
- * Deliberately unsafe escape hatch for executable inline code. The required nonce keeps the result
745
- * compatible with a strict CSP and makes the security-sensitive choice visible at the call site.
746
- */
747
- export function unsafeInlineScript(content, options) {
748
- if (options.nonce.trim() === "") {
749
- throw new TypeError("[nifra/web] unsafeInlineScript requires a non-empty CSP nonce");
750
- }
751
- const type = options.type ?? "module";
752
- // Checked here as well as at emit: the type union is compile-time only, and this helper is the one
753
- // place a caller is told what it may pass. Failing at the call site names the argument; failing at
754
- // render names a document.
755
- assertExecutableScriptType(type);
756
- return {
757
- unsafe: true,
758
- type,
759
- nonce: options.nonce,
760
- content,
761
- };
762
- }
763
- /**
764
- * Re-issue `request` with `prefix` removed from its pathname.
765
- *
766
- * Needed because two conventions exist and both are reasonable. `createWebApp`'s auto-mount assumes a
767
- * backend that declares FULL paths (`server().post("/api/sync")`), which is right when the backend is
768
- * only ever mounted here. A backend that also runs standalone declares paths WITHOUT the prefix and
769
- * lets its own shell supply it - and mounting one of those here used to require the caller to wrap it
770
- * in a `Proxy` that rewrote every URL. Two apps wrote that same wrapper independently, which is the
771
- * signal that it belonged in the framework.
772
- *
773
- * The `Request` is rebuilt rather than mutated (`url` is read-only), preserving method, headers, body,
774
- * and duplex streaming - the body is passed through unread, so a large or streamed upload is untouched.
775
- */
776
- function stripMountPrefix(request, prefix) {
777
- const url = new URL(request.url);
778
- const rest = url.pathname.slice(prefix.length);
779
- url.pathname = rest === "" ? "/" : rest;
780
- // `url.href`, not the `URL`: this type set only declares the string and Request overloads.
781
- return new Request(url.href, request);
782
- }
783
- /**
784
- * Resolve the explicit symbol-keyed backend mount interface. The symbol seam forwards platform
785
- * context without making web depend on client.
786
- */
787
- function backendMountOf(api) {
788
- if ((typeof api !== "object" && typeof api !== "function") || api === null)
789
- return undefined;
790
- const explicit = api[NIFRA_BACKEND_MOUNT];
791
- if (typeof explicit !== "function")
792
- return undefined;
793
- return (request, platform) => explicit.call(api, request, platform);
794
- }
795
- // `createWebApp` reaches the same Request object through the mount hook and the page route. Cache the
796
- // allocation-light core split once so API mounting, path hydration, search parsing, and SSG fallback
797
- // checks do not each rescan the absolute URL. WeakMap keeps this bounded to requests that are alive.
798
- const REQUEST_URL_PARTS = new WeakMap();
799
- const urlPartsFor = (request) => {
800
- const cached = REQUEST_URL_PARTS.get(request);
801
- if (cached !== undefined)
802
- return cached;
803
- const parts = urlPartsOf(request.url);
804
- REQUEST_URL_PARTS.set(request, parts);
805
- return parts;
806
- };
807
- /**
808
- * Build a nifra app from a route manifest: every route SSRs its layout chain via `renderPage`,
809
- * and a wildcard catch-all renders `_404` (or a plain 404). Reuses @nifrajs/core's router +
810
- * lifecycle, so matching, params, and precedence are battle-tested. fs-free - feed it a
811
- * manifest from `discoverRoutes` (`@nifrajs/web/fs`) at startup, so the served app stays portable.
812
- *
813
- * **Typed platform bindings.** Pass `Env` - `createWebApp<Env>({ … })` - to declare the app's Workers
814
- * bindings ONCE. It seeds the returned `Server`'s context with `{ env: Env }` (exactly as the backend's
815
- * `server<Env>()` does), so `app.fetch(req, { env })` / `toFetchHandler(app)` type-check the `env`
816
- * argument against the declared shape - no per-binding cast at the edge entry. Per-route loaders/actions
817
- * stay typed independently of this call: annotate them with `@nifrajs/client`'s `LoaderArgs<Api, Env>`
818
- * (same `Env`) so `ctx.env.MY_KV` is typed there too. Omit the parameter and `Env` is `unknown` - the
819
- * secure default; validate at the trust boundary before use.
820
- */
821
- export function createWebApp(options) {
822
- const { adapter, manifest, clientEntry, title, api } = options;
823
- const titleOption = title === undefined ? {} : { title };
824
- // Draft/preview: when a `draftSecret` is configured, each request's signed `__nifra_draft` cookie is
825
- // verified once and surfaced to loaders/actions as `ctx.draft`. No secret ⇒ always `false` (sync, free).
826
- const draftFlag = (req) => options.draftSecret === undefined
827
- ? Promise.resolve(false)
828
- : isDraftEnabled(req, options.draftSecret);
829
- // Per-route preload chunks (spread into renderPage; omitted when unmapped, for exactOptionalPropertyTypes).
830
- const preloadOf = (id) => {
831
- const chunks = options.routePreload?.[id];
832
- return chunks ? { preload: chunks } : {};
833
- };
834
- // The matched route's stylesheet links (spread into renderPage). Per-route when the build mapped it
835
- // (`routeStyles[id]` - only the chain's CSS; an empty array ⇒ no `<link>`), else the aggregate
836
- // `styles`. Omitted entirely when CSS-free (for exactOptionalPropertyTypes).
837
- const stylesOf = (id) => {
838
- const perRoute = options.routeStyles?.[id];
839
- if (perRoute !== undefined)
840
- return { styles: perRoute };
841
- return options.styles && options.styles.length > 0 ? { styles: options.styles } : {};
842
- };
843
- // Seed the context with the declared `Env` so `app.fetch(req, { env })` / `toFetchHandler(app)` type
844
- // the platform bindings (see the `createWebApp` doc). The runtime `env` still arrives per-request via
845
- // `app.fetch(req, { env })`; this is a compile-time-only seed (`server<Env>()` casts, doesn't store).
846
- const app = server(options.server);
847
- // Before the mount hooks and before every page route, so the order-scoped hooks (`derive`,
848
- // `beforeHandle`, assurance evidence) actually bind to them - see the `use` option. A caller
849
- // cannot do this after the fact: by the time this function returns, the routes are declared.
850
- options.use?.(app);
851
- // Auto-mount the in-process backend over HTTP at `apiPrefix` (default `/api`), BEFORE page routing.
852
- // `onRequest` runs on the raw request ahead of the router, so this wins over the page wildcard `/*`
853
- // for every method (POST/GET/PUT/…) - not just the GET page routes - and a backend 404 (`/api/none`)
854
- // surfaces as the backend's own response, never the page 404. We dispatch the SAME `Request` object
855
- // (its body unread) so streamed/large bodies pass through untouched; the backend defines its routes
856
- // at the full prefixed path (`server().post("/api/sync", …)`), matching the `inProcessClient` call
857
- // sites. `apiPrefix: ""` opts out; a non-mountable `api` (no symbol mount) is left pages-only. The hook
858
- // is registered ONLY when both hold, so a pages-only app keeps core's synchronous no-hook fast path.
859
- const apiPrefix = options.apiPrefix ?? "/api";
860
- const apiStrip = options.apiStrip === true;
861
- const mountedApi = backendMountOf(api);
862
- // Longest path first, so a more specific mount (`/api/auth`) is tried before a broader one (`/api`)
863
- // regardless of the order they were declared in.
864
- const mounts = [...(options.mounts ?? [])].sort((a, b) => b.path.length - a.path.length);
865
- const underPrefix = (pathname, prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`);
866
- if (mounts.length > 0 || (apiPrefix !== "" && mountedApi !== undefined)) {
867
- app.onRequest((req, platform) => {
868
- const { pathname } = urlPartsFor(req);
869
- // Sub-app mounts win over the backend prefix: they are the more specific declaration, and an
870
- // auth handler mounted at `/api/auth` must not be swallowed by the backend mounted at `/api`.
871
- for (const mount of mounts) {
872
- if (!underPrefix(pathname, mount.path))
873
- continue;
874
- return mount.app.fetch(mount.stripPrefix === true ? stripMountPrefix(req, mount.path) : req);
875
- }
876
- // Exactly the prefix (`/api`) or a sub-path (`/api/…`) - NOT a sibling like `/apixyz` that merely
877
- // shares the prefix as a string head. Dispatch the original `req` (body intact) to the backend.
878
- if (mountedApi !== undefined && apiPrefix !== "" && underPrefix(pathname, apiPrefix)) {
879
- return mountedApi(apiStrip ? stripMountPrefix(req, apiPrefix) : req, platform);
880
- }
881
- return undefined; // not an API path → continue to page routing
882
- });
883
- }
884
- // SSG `fallback: "404"`: the set of concrete paths that actually exist for those routes. An unlisted
885
- // path under a `"404"` route is rejected (it isn't a static file, and the route declared it shouldn't
886
- // SSR on demand). O(1) membership via a Set.
887
- const prerenderedSet = new Set(options.prerenderedPaths ?? []);
888
- const matchManifestRoute = createMatcher(manifest.routes.map((route) => ({ routeId: route.id, pattern: route.pattern })));
889
- const routeById = new Map(manifest.routes.map((route) => [route.id, route]));
890
- // Load a route's layout modules (outermost layout → innermost), keeping each module whole so the
891
- // render path can take both its `default` (the component chain) AND its `meta` (the sitewide head it
892
- // contributes). Loaded lazily - the data-only and 405 branches return before any layout is needed.
893
- const loadLayoutModules = async (route) => {
894
- const modules = await Promise.all(
895
- // layoutIds only reference layouts present in the manifest (buildManifest invariant).
896
- route.layoutIds.map((id) => manifest.layouts[id].load()));
897
- // A layout is not a form target, so an `action` there is a mistake with no meaning to give it.
898
- // A `loader`, by contrast, now runs (see `runLayoutChain`).
899
- for (let i = 0; i < modules.length; i++) {
900
- if (modules[i].action === undefined)
901
- continue;
902
- const id = route.layoutIds[i];
903
- throw new Error(`[nifra/web] "${manifest.layouts[id].file}" exports an \`action\`, but layouts do not run one - only route files do. Move the mutation into the route that submits to it.`);
904
- }
905
- return modules;
906
- };
907
- /**
908
- * Run a route's layout-chain loaders, honouring declared gates.
909
- *
910
- * Returns once every **gate** has resolved, with the non-gate loaders still in flight, so the caller
911
- * can start the page loader at exactly the right moment: after anything that might reject the
912
- * request, alongside anything that merely fetches.
913
- *
914
- * The ordering is the security-relevant part. Parallel loaders are NOT an authorization boundary -
915
- * a page loader running concurrently with a guard has already queried by the time the guard says no.
916
- * Remix documents that as a footgun; here it is a declaration instead. `export const gate = true`
917
- * makes a layout blocking for everything beneath it, and nothing beneath a rejected gate runs.
918
- *
919
- * Each layout receives only the params it OWNS ({@link RouteEntry.layoutParams}), not the route's
920
- * full set, so a layout at `orgs/[org]/` cannot read a param belonging to a route below it.
921
- */
922
- /**
923
- * Layout indices a client navigation asked to keep, from {@link RETAIN_HEADER}.
924
- *
925
- * The CLIENT decides retainability: it knows each layout's scoped params (shipped in the bootstrap)
926
- * and both the old and new match, so it can tell whether a layout's own prefix changed - without the
927
- * server re-matching a path the client already matched.
928
- *
929
- * It is a HINT, not an instruction. The client is asking to keep data it already holds, which is
930
- * harmless for data and unacceptable for a guard, so `runLayoutChain` refuses to skip a gate no
931
- * matter what arrives here. Anything unparseable is ignored rather than rejected: the worst case of
932
- * a bad hint is a loader that runs when it need not.
933
- */
934
- const retainedIndices = (header) => {
935
- if (header === null || header === "")
936
- return EMPTY_RETAIN;
937
- const out = new Set();
938
- for (const part of header.split(",")) {
939
- // Digits only. `Number("")` is 0 and `Number(" ")` is 0, so a stray comma would otherwise read
940
- // as "retain index 0" and silently skip the outermost layout.
941
- if (!/^\d+$/.test(part))
942
- continue;
943
- out.add(Number(part));
944
- }
945
- return out;
946
- };
947
- /**
948
- * Validate a data-navigation's retain request against the manifest and its declared source path.
949
- * A client may ask to retain every slot it currently has; the server only honours indices whose
950
- * layout identity and owned params are unchanged. Hard document GETs never retain anything.
951
- */
952
- const validatedRetainedIndices = (req, route, params) => {
953
- if (req.headers.get(DATA_HEADER) === null)
954
- return EMPTY_RETAIN;
955
- const requested = retainedIndices(req.headers.get(RETAIN_HEADER));
956
- const from = req.headers.get(NAV_FROM_HEADER);
957
- if (requested.size === 0 || from === null)
958
- return EMPTY_RETAIN;
959
- let fromPath;
960
- try {
961
- const current = new URL(req.url);
962
- const source = new URL(from, current);
963
- if (source.origin !== current.origin)
964
- return EMPTY_RETAIN;
965
- fromPath = source.pathname + source.search;
966
- }
967
- catch {
968
- return EMPTY_RETAIN;
969
- }
970
- const previousMatch = matchManifestRoute(fromPath);
971
- if (previousMatch === null)
972
- return EMPTY_RETAIN;
973
- const previous = routeById.get(previousMatch.routeId);
974
- if (previous === undefined)
975
- return EMPTY_RETAIN;
976
- const valid = new Set();
977
- for (const index of requested) {
978
- if (route.layoutIds[index] !== previous.layoutIds[index])
979
- continue;
980
- const owned = route.layoutParams?.[index] ?? [];
981
- const previouslyOwned = previous.layoutParams?.[index] ?? [];
982
- if (owned.length !== previouslyOwned.length ||
983
- owned.some((name, i) => name !== previouslyOwned[i]) ||
984
- owned.some((name) => params[name] !== previousMatch.params[name])) {
985
- continue;
986
- }
987
- valid.add(index);
988
- }
989
- return valid;
990
- };
991
- // The validated (or raw-parsed) search a route's loader context receives; `searchOf` fails closed to
992
- // the schema's defaults on hostile input, so this never throws on an attacker-picked query.
993
- const loaderSearch = (searchSchema, request) => searchOf(searchSchema, urlPartsFor(request).search);
994
- // The route's EFFECTIVE search once its layout chain is loaded: the layout schemas merged with the
995
- // page's (page-wins), the same chain the client mount builds for `useSearch`. Used for the page loader's
996
- // `ctx.search` and the render's `RenderProps.search`, so both agree with the client and with each other.
997
- const searchChainOf = (layoutMods, mod, request) => searchOfChain([...layoutMods.map((m) => m.searchSchema), mod.searchSchema], urlPartsFor(request).search);
998
- const runLayoutChain = async (route, ctx, retain = new Set()) => {
999
- const modules = await loadLayoutModules(route);
1000
- if (!modules.some((m) => m.loader !== undefined)) {
1001
- // Nothing to run: no array is produced, so a page-only app serializes nothing extra and its
1002
- // HTML is byte-identical to before this feature.
1003
- return { modules, layoutData: undefined, retained: [], pending: Promise.resolve() };
1004
- }
1005
- const results = new Array(modules.length).fill(null);
1006
- const retained = [];
1007
- const pending = [];
1008
- for (let i = 0; i < modules.length; i++) {
1009
- const loader = modules[i]?.loader;
1010
- if (loader === undefined)
1011
- continue;
1012
- // Unchanged scope: the client keeps what it has. A GATE is never skipped - it is a guard, and a
1013
- // guard that only runs when the URL prefix changed is not a guard.
1014
- if (retain.has(i) && modules[i]?.gate !== true) {
1015
- retained.push(i);
1016
- continue;
1017
- }
1018
- const scoped = {
1019
- ...ctx,
1020
- params: scopeParams(ctx.params, route.layoutParams?.[i]),
1021
- };
1022
- if (modules[i]?.gate === true) {
1023
- // Blocking: awaited here, so a throw propagates before anything deeper is started.
1024
- try {
1025
- results[i] = await loader(scoped);
1026
- }
1027
- catch (err) {
1028
- throw tagLayoutError(err, route.layoutIds[i]);
1029
- }
1030
- continue;
1031
- }
1032
- const layoutId = route.layoutIds[i];
1033
- const index = i;
1034
- // The loader is invoked INSIDE the async function, not before it. `Promise.resolve(loader(x))`
1035
- // would let a synchronously-throwing loader escape past the rejection handler entirely - the
1036
- // exception happens while evaluating the argument, before any promise exists to reject.
1037
- pending.push((async () => {
1038
- try {
1039
- results[index] = await loader(scoped);
1040
- }
1041
- catch (err) {
1042
- throw tagLayoutError(err, layoutId);
1043
- }
1044
- })());
1045
- }
1046
- return { modules, layoutData: results, retained, pending: Promise.all(pending) };
1047
- };
1048
- /** Run only blocking layout gates before a route action. Non-gate loaders fetch render data and
1049
- * therefore run after the mutation when a native POST needs a fresh document. */
1050
- const runLayoutGates = async (route, ctx) => {
1051
- const modules = await loadLayoutModules(route);
1052
- for (let i = 0; i < modules.length; i++) {
1053
- const mod = modules[i];
1054
- if (mod?.gate !== true || mod.loader === undefined)
1055
- continue;
1056
- try {
1057
- await mod.loader({
1058
- ...ctx,
1059
- params: scopeParams(ctx.params, route.layoutParams?.[i]),
1060
- });
1061
- }
1062
- catch (err) {
1063
- throw tagLayoutError(err, route.layoutIds[i]);
1064
- }
1065
- }
1066
- return modules;
1067
- };
1068
- // Build a route's render chain + its merged `<head>` from the already-loaded layout modules + the
1069
- // page module. The chain is `[…layout components, page]`; the head merges each layout's `meta`
1070
- // export (outermost→innermost) with the page's (last), so a `head`/`meta` on `_layout.tsx`
1071
- // contributes sitewide tags. `metaArgs` (loader data + params) feed function-form `meta`s.
1072
- const resolveChainAndHead = (layoutModules, page, metaArgs) => {
1073
- const chain = [...layoutModules.map((m) => m.default), page.default];
1074
- const heads = [
1075
- ...layoutModules.map((m) => resolveMeta(m.meta, metaArgs)),
1076
- resolveMeta(page.meta, metaArgs),
1077
- ];
1078
- return { chain, head: mergeHeads(heads) };
1079
- };
1080
- // Dir a special-file id lives in: `_error`→"" , `a/b/_error`→"a/b" (and likewise for `_layout`).
1081
- const dirOfId = (id, suffix) => id === suffix ? "" : id.slice(0, id.length - suffix.length - 1);
1082
- /**
1083
- * Choose the `_error` boundary for a failure, respecting where a LAYOUT loader failed.
1084
- *
1085
- * A route error uses the nearest boundary, as it always has. A layout error must not: the nearest
1086
- * boundary can sit BELOW the layout that threw, and rendering there would wrap the boundary in that
1087
- * very layout - the one whose loader just failed and whose data therefore never arrived.
1088
- */
1089
- const boundaryFor = (route, err) => {
1090
- const ids = route.errorIds ?? [];
1091
- const failing = layoutErrorId(err);
1092
- if (failing === undefined)
1093
- return ids.at(-1);
1094
- const layoutDir = dirOfId(failing, "_layout");
1095
- // Deepest boundary at or ABOVE the failing layout's directory.
1096
- for (let i = ids.length - 1; i >= 0; i--) {
1097
- const errDir = dirOfId(ids[i], "_error");
1098
- if (errDir === "" || errDir === layoutDir || layoutDir.startsWith(`${errDir}/`))
1099
- return ids[i];
1100
- }
1101
- return undefined;
1102
- };
1103
- // The request's origin (scheme + host + port, NO trailing slash) - the one server fact `meta()` needs
1104
- // for absolute `canonical`/`og:url`/`og:image` but can't otherwise see (it also runs on the client).
1105
- // `URL.origin` is exactly that shape; it matches the browser's `location.origin` for the same URL, so
1106
- // a soft-nav's `applyHead` resolves an identical `<head>` (no hydration drift). A malformed `req.url`
1107
- // (shouldn't happen on a real request) degrades to `""` - the documented unknown-origin default -
1108
- // rather than throwing during render.
1109
- const originOf = (req) => {
1110
- try {
1111
- return new URL(req.url).origin;
1112
- }
1113
- catch {
1114
- return "";
1115
- }
1116
- };
1117
- // The request's `pathname + search` - threaded into `renderPage` so an adapter's `useLocation`/
1118
- // `useSearchParams` render the current URL server-side and hydrate against the client's initial state
1119
- // (which the client entry seeds from `location.pathname + location.search`). No hash: it never reaches
1120
- // the server. A malformed `req.url` degrades to "/" rather than throwing during render.
1121
- const pathOf = (req) => {
1122
- try {
1123
- const parts = urlPartsFor(req);
1124
- return parts.pathname + parts.search;
1125
- }
1126
- catch {
1127
- return "/";
1128
- }
1129
- };
1130
- /**
1131
- * Render the **nearest `_error` boundary** when a route's loader throws (the agnostic, server-side
1132
- * half of error UI - works on every adapter, no client takeover). The boundary renders in place of
1133
- * the page, wrapped by the layouts **at or above** its segment (deeper layouts are dropped). It's
1134
- * served **non-hydrated** at status 500: a terminal page, and rendering a boundary (not the page the
1135
- * client maps this route to) would otherwise hydrate-mismatch. The component receives `{ name,
1136
- * message }` - never the stack (no internals leak into HTML).
1137
- */
1138
- const renderError = async (route, errorId, err) => {
1139
- const errDir = dirOfId(errorId, "_error");
1140
- const keptLayoutIds = route.layoutIds.filter((id) => {
1141
- const ld = dirOfId(id, "_layout");
1142
- return ld === "" || ld === errDir || errDir.startsWith(`${ld}/`);
1143
- });
1144
- const layouts = await Promise.all(keptLayoutIds.map((id) => manifest.layouts[id].load().then((m) => m.default)));
1145
- const { default: errComp } = await (manifest.errors?.[errorId]).load();
1146
- const e = err instanceof Error ? err : new Error(String(err));
1147
- return renderPageResult({
1148
- adapter,
1149
- chain: [...layouts, errComp],
1150
- data: { name: e.name, message: e.message },
1151
- clientEntry,
1152
- routeId: errorId,
1153
- status: 500,
1154
- hydrate: false,
1155
- ...titleOption,
1156
- });
1157
- };
1158
- // The 404 response - the `_404` page (status 404) or a plain-text fallback. Shared by the wildcard
1159
- // catch-all (unmatched paths) and the `fallback: "404"` enforcement (unlisted paths under a route
1160
- // that opted out of on-demand SSR).
1161
- const renderNotFound = (path) => renderTerminalStatus(404, path);
1162
- /**
1163
- * Render a terminal-status page: the `_<status>` page if the app authored one, else `_404`, else
1164
- * plain text. Shared by the wildcard catch-all, `fallback: "404"` enforcement, and a loader's
1165
- * `notFound()` / `gone()` / `statusPage()`, so all of them resolve the page and set the status
1166
- * through one path rather than forking.
1167
- *
1168
- * Hydrates, following the `_404` precedent rather than `_error`'s non-hydrated 500: these are
1169
- * ordinary pages the client router can own, and a 404 arrived at by clicking a link should behave
1170
- * like any other route.
1171
- */
1172
- const renderTerminalStatus = async (status, path, extraHeaders) => {
1173
- const page = manifest.statusPages?.[String(status)] ?? manifest.notFound;
1174
- if (page === undefined) {
1175
- const headers = new Headers(extraHeaders);
1176
- headers.set("content-type", "text/plain; charset=utf-8");
1177
- return new Response(STATUS_TEXT[status] ?? "Error", { status, headers });
1178
- }
1179
- // The routeId decides which preload/style bundle and which client component this maps to, so it
1180
- // must name the page actually rendered - `_410` when `_410.tsx` exists, `_404` when it fell back.
1181
- const routeId = manifest.statusPages?.[String(status)] !== undefined ? `_${status}` : "_404";
1182
- const loaded = (await page.load());
1183
- const component = loaded.default;
1184
- return renderPageResult({
1185
- adapter,
1186
- chain: [component],
1187
- data: null,
1188
- clientEntry,
1189
- routeId,
1190
- // The page hydrates, so besides `path` its SSR `search` must equal the client mount's derivation for
1191
- // this routeId (`searchOf(searchSchema, url.search)`), or a status page reading `useSearch` drifts.
1192
- // Only when `path` is present (a real URL); a schema-less status page then gets the raw parsed query.
1193
- ...(path !== undefined
1194
- ? {
1195
- search: searchOf(loaded.searchSchema, path.includes("?") ? path.slice(path.indexOf("?")) : ""),
1196
- }
1197
- : {}),
1198
- // The page hydrates, so its SSR `path` must equal the client's initial
1199
- // `location.pathname+search` (an unmatched path yields no params → `{}`), or a `useLocation`
1200
- // on it would drift.
1201
- ...(path !== undefined ? { path } : {}),
1202
- status,
1203
- ...(extraHeaders !== undefined ? { headers: extraHeaders } : {}),
1204
- ...preloadOf(routeId),
1205
- ...stylesOf(routeId),
1206
- prerenderedPaths: options.prerenderedPaths ?? [],
1207
- ...titleOption,
1208
- });
1209
- };
1210
- /**
1211
- * Answer a loader's terminal-status signal, in whichever form the caller asked for.
1212
- *
1213
- * A hard navigation wants the document, so it gets the rendered boundary. A client-side navigation
1214
- * fetched DATA, not a document, so it gets an empty body plus the status on `X-Nifra-Status`, and
1215
- * the client router renders the same boundary from its own manifest. Sending the HTML back to a
1216
- * soft-nav would be answering a different question than the one asked - and skipping the header
1217
- * entirely is what leaves a crawler seeing a correct 404 while a user who clicked a link sees a
1218
- * blank page.
1219
- */
1220
- const renderStatusSignal = (req, signal) => {
1221
- const { status, headers } = signal[STATUS_SIGNAL];
1222
- if (req.headers.get(DATA_HEADER) !== null) {
1223
- const responseHeaders = new Headers(headers);
1224
- responseHeaders.set(STATUS_HEADER, String(status));
1225
- return new Response(null, { status, headers: responseHeaders });
1226
- }
1227
- return renderTerminalStatus(status, pathOf(req), headers);
1228
- };
1229
- for (const route of manifest.routes) {
1230
- // A dynamic route whose `getStaticPaths` declared `fallback: "404"` - only its prerendered paths
1231
- // exist; anything else 404s (computed once per route, not per request).
1232
- const is404Fallback = options.staticFallbacks?.[route.pattern] === "404";
1233
- // Per-route document-assembly cache (see RenderAssemblyCache): filled on the first GET render and
1234
- // reused while the route + layout MODULE IDENTITIES are unchanged. Attached only when every meta
1235
- // in the chain is static - a `meta(data)` function makes the head per-request, so those routes
1236
- // always assemble fresh. A module reload (dev HMR) yields new module objects, dropping the slot.
1237
- let assemblySlot;
1238
- let assemblySlotMod;
1239
- let assemblySlotLayouts;
1240
- const assemblyCacheFor = (mod, lms) => {
1241
- if (typeof mod.meta === "function")
1242
- return {};
1243
- for (const m of lms)
1244
- if (typeof m.meta === "function")
1245
- return {};
1246
- const layoutsUnchanged = assemblySlotLayouts !== undefined &&
1247
- assemblySlotLayouts.length === lms.length &&
1248
- assemblySlotLayouts.every((m, i) => m === lms[i]);
1249
- if (assemblySlotMod !== mod || !layoutsUnchanged) {
1250
- assemblySlot = {};
1251
- assemblySlotMod = mod;
1252
- assemblySlotLayouts = lms;
1253
- }
1254
- return { assemblyCache: assemblySlot };
1255
- };
1256
- app.register("GET", route.pattern, undefined, async (c) => {
1257
- // Enforce `fallback: "404"` before any work: an unlisted path under this route doesn't exist.
1258
- // Covers hard navigation directly; a client soft-nav's data fetch gets the 404, throws, and the
1259
- // history layer falls back to a full-page navigation (which lands here again, as a document).
1260
- if (is404Fallback && !prerenderedSet.has(urlPartsFor(c.req).pathname)) {
1261
- return renderNotFound(pathOf(c.req));
1262
- }
1263
- const mod = await route.load();
1264
- const draft = await draftFlag(c.req);
1265
- let data;
1266
- let layoutData;
1267
- let layoutModules;
1268
- let layoutRetained = [];
1269
- try {
1270
- const ctx = {
1271
- params: c.params,
1272
- request: c.req,
1273
- req: c.req,
1274
- api,
1275
- env: c.env,
1276
- draft,
1277
- search: loaderSearch(mod.searchSchema, c.req),
1278
- };
1279
- // Layout loaders run for BOTH the document and the data-only request. A gate that only ran on
1280
- // the document path would be bypassed by adding the data header, which is exactly the request
1281
- // a client navigation makes - a guard has to hold on the path an attacker can pick.
1282
- //
1283
- // `runLayoutChain` returns once every GATE has resolved, with the non-gate loaders still in
1284
- // flight. So the page loader starts as late as correctness requires and as early as speed
1285
- // allows, and both are awaited together below.
1286
- const run = await runLayoutChain(route, ctx, validatedRetainedIndices(c.req, route, c.params));
1287
- layoutModules = run.modules;
1288
- layoutRetained = run.retained;
1289
- // The page loader gets the EFFECTIVE search (layout chain + page, page-wins), now that the layout
1290
- // modules are loaded - so `ctx.search` includes a layout's shared keys (`?org`), matching `useSearch`.
1291
- const [pageData] = await Promise.all([
1292
- mod.loader
1293
- ? mod.loader({ ...ctx, search: searchChainOf(run.modules, mod, c.req) })
1294
- : null,
1295
- run.pending, // a non-gate layout loader that rejects must still surface, not go unhandled
1296
- ]);
1297
- data = pageData;
1298
- layoutData = run.layoutData;
1299
- }
1300
- catch (err) {
1301
- // A terminal-status signal (`notFound()` / `gone()` / `statusPage(n)`) renders a boundary at
1302
- // that status. Checked BEFORE the pass-through below: a signal IS a `Response`, so the order
1303
- // is what keeps a hand-rolled `throw new Response(...)` served verbatim, as it always was.
1304
- if (isStatusSignal(err))
1305
- return renderStatusSignal(c.req, err);
1306
- // A thrown `Response` is a control-flow signal (a guard's `redirect(...)`, an explicit error
1307
- // response) - let it propagate to core, which returns it as-is. Real errors render the nearest
1308
- // `_error` boundary, if any; with none, rethrow (unchanged 500 behavior).
1309
- if (err instanceof Response)
1310
- throw err;
1311
- // Let reporting plugins observe the data-layer failure before it's rendered/rethrown/500'd.
1312
- if (options.onLoaderError !== undefined) {
1313
- try {
1314
- options.onLoaderError(err, { request: c.req, params: c.params, route: route.pattern });
1315
- }
1316
- catch {
1317
- // A faulty reporter must never break error rendering.
1318
- }
1319
- }
1320
- const errorId = boundaryFor(route, err);
1321
- if (errorId === undefined)
1322
- throw err;
1323
- // A soft-nav data fetch can't render a boundary - 500 so the client falls back to a full-page
1324
- // navigation, which lands here as a document and renders the `_error` page.
1325
- if (c.req.headers.get(DATA_HEADER) !== null) {
1326
- return new Response("Internal Server Error", {
1327
- status: 500,
1328
- headers: { "content-type": "text/plain; charset=utf-8" },
1329
- });
1330
- }
1331
- return renderError(route, errorId, withDuplicateInstanceHint(err));
1332
- }
1333
- // A loader may RETURN its control-flow signal instead of throwing it - `return redirect(...)`
1334
- // reads naturally and must not silently serialize the `Response` as loader data. Mirror the
1335
- // catch above exactly: a status signal renders its boundary, any other `Response` (a
1336
- // redirect, a hand-rolled response) passes through to core verbatim - so return and throw
1337
- // are interchangeable.
1338
- if (isStatusSignal(data))
1339
- return renderStatusSignal(c.req, data);
1340
- if (data instanceof Response)
1341
- return data;
1342
- // Client-side navigation asks (via the X-Nifra-Data header) for just the loader data - no full
1343
- // document, no layout chain. A route with deferred data streams NDJSON (critical data first,
1344
- // then each deferred value as it settles); otherwise one JSON (the fast path). Same loader,
1345
- // same auth - only the transport differs.
1346
- if (c.req.headers.get(DATA_HEADER) !== null) {
1347
- const pageSplit = prepareDeferred(data);
1348
- const layoutSplits = [];
1349
- let offset = pageSplit.deferred.length;
1350
- for (const entry of layoutData ?? []) {
1351
- const split = prepareDeferred(entry, offset);
1352
- layoutSplits.push(split);
1353
- offset += split.deferred.length;
1354
- }
1355
- const deferred = [...pageSplit.deferred, ...layoutSplits.flatMap((split) => split.deferred)];
1356
- const payload = layoutData === undefined
1357
- ? pageSplit.forClient
1358
- : {
1359
- v: 1,
1360
- data: pageSplit.forClient,
1361
- layoutData: layoutSplits.map((split) => split.forClient),
1362
- retained: layoutRetained,
1363
- };
1364
- // Bare value when there is no layout data - the pre-envelope shape, so a client running older
1365
- // code against a newer server keeps working.
1366
- if (deferred.length === 0) {
1367
- return Response.json(payload ?? null);
1368
- }
1369
- return new Response(ndjsonStream(payload, deferred), {
1370
- headers: { "content-type": "application/x-ndjson; charset=utf-8" },
1371
- });
1372
- }
1373
- const chainLayoutModules = layoutModules ?? (await loadLayoutModules(route));
1374
- const { chain, head } = resolveChainAndHead(chainLayoutModules, mod, {
1375
- data,
1376
- params: c.params,
1377
- origin: originOf(c.req),
1378
- });
1379
- const hydrateRoute = mod.hydrate !== false;
1380
- try {
1381
- // `await` so a shell-render throw (renderToStream rejects before any byte) is caught here and
1382
- // can render the `_error` page - not just a loader throw. Mid-stream (post-shell) throws can't
1383
- // be recovered to a full page; the per-adapter client boundary catches client render errors.
1384
- return await renderPageResult({
1385
- adapter,
1386
- chain,
1387
- data,
1388
- head,
1389
- clientEntry,
1390
- routeId: route.id,
1391
- params: c.params,
1392
- path: pathOf(c.req),
1393
- // The effective (layout chain + page) search, matching the page loader's `ctx.search` above and
1394
- // the client mount - so `useSearch` renders SSR-correct and hydrates with no drift. `layoutModules`
1395
- // is loaded by now (the loader try succeeded to reach here).
1396
- search: searchChainOf(layoutModules ?? [], mod, c.req),
1397
- hydrate: hydrateRoute,
1398
- ...(layoutData !== undefined ? { layoutData } : {}),
1399
- ...preloadOf(route.id),
1400
- ...stylesOf(route.id),
1401
- prerenderedPaths: options.prerenderedPaths ?? [],
1402
- ...(mod.revalidate !== undefined ? { revalidate: mod.revalidate } : {}),
1403
- ...(mod.revalidateTags !== undefined ? { revalidateTags: mod.revalidateTags } : {}),
1404
- ...(mod.islandScripts !== undefined ? { islandScripts: mod.islandScripts } : {}),
1405
- ...titleOption,
1406
- ...assemblyCacheFor(mod, chainLayoutModules),
1407
- });
1408
- }
1409
- catch (err) {
1410
- // Same precedence as the loader catch above - a `meta()` may signal too.
1411
- if (isStatusSignal(err))
1412
- return renderStatusSignal(c.req, err);
1413
- if (err instanceof Response)
1414
- throw err;
1415
- // Let reporting plugins observe the data-layer failure before it's rendered/rethrown/500'd.
1416
- if (options.onLoaderError !== undefined) {
1417
- try {
1418
- options.onLoaderError(err, { request: c.req, params: c.params, route: route.pattern });
1419
- }
1420
- catch {
1421
- // A faulty reporter must never break error rendering.
1422
- }
1423
- }
1424
- const errorId = boundaryFor(route, err);
1425
- if (errorId === undefined)
1426
- throw err;
1427
- return renderError(route, errorId, withDuplicateInstanceHint(err));
1428
- }
1429
- });
1430
- // POST runs the route's `action` (mutation). A `Response` return (e.g. a `redirect(...)`)
1431
- // passes straight through; a data return re-renders the page (the loader re-runs for fresh
1432
- // data) with `actionData`. Routes without an action reject POST with 405 - not a stray 404.
1433
- app.register("POST", route.pattern, undefined, async (c) => {
1434
- const mod = await route.load();
1435
- const draft = await draftFlag(c.req);
1436
- if (mod.action === undefined) {
1437
- return new Response("Method Not Allowed", {
1438
- status: 405,
1439
- headers: { allow: "GET", "content-type": "text/plain; charset=utf-8" },
1440
- });
1441
- }
1442
- const actionContext = {
1443
- params: c.params,
1444
- request: c.req,
1445
- req: c.req,
1446
- api,
1447
- env: c.env,
1448
- draft,
1449
- search: loaderSearch(mod.searchSchema, c.req),
1450
- };
1451
- const isDataRequest = c.req.headers.get(DATA_HEADER) !== null;
1452
- let layoutModules;
1453
- let result;
1454
- try {
1455
- // A gate is an authorization boundary for everything beneath its layout, mutations included.
1456
- // Run only gates before the action; ordinary layout data loaders run after a native mutation.
1457
- layoutModules = await runLayoutGates(route, actionContext);
1458
- result = await mod.action(actionContext);
1459
- }
1460
- catch (err) {
1461
- // A THROWN Response is the same control-flow signal as a returned one (`throw redirect()`
1462
- // in a gate or an action) - route it through the same conversion as the returned-Response
1463
- // branch below, so throw and return are interchangeable on the mutation path too.
1464
- if (err instanceof Response)
1465
- return actionResponse(err, isDataRequest);
1466
- throw err;
1467
- }
1468
- // An action may wrap its data in `revalidate(paths, data)` to declare which routes it changed.
1469
- // Unwrap to the inner data; the paths ride the `X-Nifra-Revalidate` header on the data-mode
1470
- // responses (the client acts on them - a full-page POST re-runs loaders inline, so no header).
1471
- const isRevalidate = result !== null && typeof result === "object" && "__nifraRevalidate" in result;
1472
- const actionResult = isRevalidate ? result.data : result;
1473
- const revalidateHeader = isRevalidate
1474
- ? { [REVALIDATE_HEADER]: result.__nifraRevalidate.join(",") }
1475
- : {};
1476
- if (actionResult instanceof Response)
1477
- return actionResponse(actionResult, isDataRequest);
1478
- // Client submit wants just the action's data (it revalidates the loader itself); a native
1479
- // form POST re-renders the full page (loader re-runs) with the action data.
1480
- if (isDataRequest) {
1481
- // An action may `defer()` slow parts of its result - stream them (critical data first, then
1482
- // each deferred as it settles) exactly like a loader; a non-deferred action returns one JSON.
1483
- const { forClient, deferred } = prepareDeferred(actionResult);
1484
- if (deferred.length === 0)
1485
- return Response.json(actionResult ?? null, { headers: revalidateHeader });
1486
- return new Response(ndjsonStream(forClient, deferred), {
1487
- headers: { "content-type": "application/x-ndjson; charset=utf-8", ...revalidateHeader },
1488
- });
1489
- }
1490
- // Derived once and shared: the loader's `ctx.search` and the render's `RenderProps.search` are the
1491
- // SAME effective (layout chain + page) value, and the client mount rebuilds it identically. The
1492
- // layout modules are already loaded (the action ran through their gates above).
1493
- const search = searchChainOf(layoutModules, mod, c.req);
1494
- const data = mod.loader
1495
- ? await mod.loader({
1496
- params: c.params,
1497
- request: c.req,
1498
- req: c.req,
1499
- api,
1500
- env: c.env,
1501
- draft,
1502
- search,
1503
- })
1504
- : null;
1505
- const { chain, head } = resolveChainAndHead(layoutModules, mod, {
1506
- data,
1507
- params: c.params,
1508
- origin: originOf(c.req),
1509
- });
1510
- const hydrateRoute = mod.hydrate !== false;
1511
- // A full-page POST streams the action's `defer()`'d parts mid-document behind `<Await>` too -
1512
- // `renderPage` splits `actionData` like loader data (works with JS off; hydrates after).
1513
- return renderPageResult({
1514
- adapter,
1515
- chain,
1516
- data,
1517
- actionData: actionResult,
1518
- head,
1519
- clientEntry,
1520
- routeId: route.id,
1521
- params: c.params,
1522
- path: pathOf(c.req),
1523
- search,
1524
- hydrate: hydrateRoute,
1525
- ...preloadOf(route.id),
1526
- ...stylesOf(route.id),
1527
- prerenderedPaths: options.prerenderedPaths ?? [],
1528
- ...titleOption,
1529
- });
1530
- });
1531
- }
1532
- // Register llms.txt & llms-full.txt
1533
- const llmsOptions = { includeLocalGuidelines: options.publishLocalGuidelines === true };
1534
- app.register("GET", "/llms.txt", undefined, async () => {
1535
- const text = await generateLlmsTxt(false, manifest.routes, api, llmsOptions);
1536
- return new Response(text, {
1537
- headers: { "content-type": "text/plain; charset=utf-8" },
1538
- });
1539
- });
1540
- app.register("GET", "/llms-full.txt", undefined, async () => {
1541
- const text = await generateLlmsTxt(true, manifest.routes, api, llmsOptions);
1542
- return new Response(text, {
1543
- headers: { "content-type": "text/plain; charset=utf-8" },
1544
- });
1545
- });
1546
- // Wildcard catch-all: unmatched paths render `_404` (404), or a plain text 404 if absent.
1547
- app.register("GET", "/*", undefined, (c) => renderNotFound(pathOf(c.req)));
1548
- return app;
1549
- }
1550
- /**
1551
- * Codegen: emit a client-entry module (as source) that lazily imports each route's layout chain
1552
- * (so `Bun.build` with `splitting` code-splits one chunk per route), builds a `patterns` list,
1553
- * then creates the agnostic router store (with a `loadModule` hook), installs history + form
1554
- * interception, loads the initial route's chunk, and hydrates the adapter's stateful Router. The
1555
- * initial route is derived from the URL (falling back to the server-injected route id, e.g.
1556
- * `_404`), so after hydration the Router owns navigation and swaps routes without full reloads.
1557
- * Bun has no `import.meta.glob`, so file-based routing needs this. Write the result to a file and
1558
- * bundle it with `buildClient` / `Bun.build` (+ the adapter's transform).
1559
- */
1560
- export function generateClientEntry(manifest, options) {
1561
- const { clientModule, resolve } = options;
1562
- const loaderRows = [];
1563
- const patternRows = [];
1564
- const statusRoutes = {};
1565
- // Routes whose loader appends a nearest `_error` module (LAST) - the client wraps the page in the
1566
- // adapter's `errorBoundary(fallback)` for these, so a client render error shows the `_error` UI.
1567
- const errorRouteIds = [];
1568
- // Lazy loader returns the raw modules (for both the component chain + the page's `meta` export).
1569
- const lazyLoader = (files) => {
1570
- const imports = files.map((f) => `import(${jsStringLiteral(resolve(f))})`).join(", ");
1571
- return `() => Promise.all([${imports}])`;
1572
- };
1573
- for (const route of manifest.routes) {
1574
- // layoutIds only reference layouts present in the manifest (buildManifest invariant).
1575
- const files = [
1576
- ...route.layoutIds.map((id) => manifest.layouts[id].file),
1577
- route.file,
1578
- ];
1579
- // Append the nearest `_error` file LAST, so loadModule can pull it off the tail and wrap the page.
1580
- const nearestErrorId = route.errorIds?.at(-1);
1581
- const errorFile = nearestErrorId === undefined ? undefined : manifest.errors?.[nearestErrorId]?.file;
1582
- if (errorFile !== undefined) {
1583
- files.push(errorFile);
1584
- errorRouteIds.push(route.id);
1585
- }
1586
- loaderRows.push(` ${JSON.stringify(route.id)}: ${lazyLoader(files)},`);
1587
- patternRows.push(` { routeId: ${JSON.stringify(route.id)}, pattern: ${JSON.stringify(route.pattern)} },`);
1588
- }
1589
- if (manifest.notFound !== undefined) {
1590
- loaderRows.push(` "_404": ${lazyLoader([manifest.notFound.file])},`);
1591
- statusRoutes[404] = "_404";
1592
- }
1593
- for (const [status, entry] of Object.entries(manifest.statusPages ?? {})) {
1594
- const routeId = `_${status}`;
1595
- loaderRows.push(` ${JSON.stringify(routeId)}: ${lazyLoader([entry.file])},`);
1596
- statusRoutes[Number(status)] = routeId;
1597
- }
1598
- return `${[
1599
- // `/client`, never the root: the root's graph carries the server (renderPage, the static-file
1600
- // server), and Vite's dev server evaluates what it is given instead of tree-shaking it.
1601
- 'import { createClientRouter, createMatcher, mergeHeads, resolveMeta } from "@nifrajs/web/client"',
1602
- 'import { applyHead, installForms, installHistory, signalHydrated } from "@nifrajs/web/client"',
1603
- // Namespace import: `errorBoundary` is optional (an adapter may not export it). A namespace member
1604
- // access yields `undefined` if absent - unlike a named import, which would be a link error.
1605
- `import * as __adapter from ${JSON.stringify(clientModule)}`,
1606
- "const { mountRouter } = __adapter",
1607
- // The assurance hook is optional: ordinary client entries pay only for the namespace lookup, while
1608
- // hydration runners get a runtime identity from the exact adapter module that mounted the page. The
1609
- // registry is token-only and lives on a Symbol.for key so it cannot collide with app data.
1610
- "const __hydrationHook = __adapter.hydrationAssuranceHook",
1611
- 'if (__hydrationHook && typeof __hydrationHook.runtimeIdentity === "function") {',
1612
- ' const __runtimeKey = Symbol.for("nifra.hydration.runtime")',
1613
- " const __runtimeState = globalThis[__runtimeKey]",
1614
- " const __identities = __runtimeState && Array.isArray(__runtimeState.identities) ? __runtimeState.identities : []",
1615
- " globalThis[__runtimeKey] = { framework: __hydrationHook.framework, identities: [...__identities, __hydrationHook.runtimeIdentity()] }",
1616
- "}",
1617
- // The `clientModule` contract is a string specifier, so nothing type-checks that the module it
1618
- // names actually exports `mountRouter`. Without this the miss surfaces as
1619
- // "mountRouter is not a function" from inside a bundled chunk, at first paint, naming neither the
1620
- // module nor the requirement - a self-executing entry passes every build and fails only here.
1621
- `if (typeof mountRouter !== "function") throw new Error(${JSON.stringify(`[nifra/web] clientModule ${JSON.stringify(clientModule)} does not export \`mountRouter\`. ` +
1622
- "A client module must export `mountRouter({ router, routes, container })` - it is called by " +
1623
- "the generated bootstrap, so a self-executing entry will not work. Use your adapter's " +
1624
- '`/client` entry (e.g. "@nifrajs/web-react/client"), or re-export mountRouter from it.')})`,
1625
- "const errorBoundary = __adapter.errorBoundary",
1626
- // A hot update that the framework cannot actually apply must end in a reload, not in nothing.
1627
- //
1628
- // Bun's dev server applies React Fast Refresh to JSX modules. For React that patches the component
1629
- // and preserves state. For Preact it does not - the module still LOOKS Fast-Refresh-able, so the
1630
- // update is accepted and then swallowed: `bun:beforeUpdate`/`bun:afterUpdate` both fire, the server
1631
- // logs a rebuild, and the page silently keeps rendering the old code. An edit that appears to do
1632
- // nothing is the worst failure mode in a dev loop - worse than a reload, because there is no signal
1633
- // to act on. An adapter that knows its framework is in that position says so, and the entry turns
1634
- // the swallowed update into an honest full reload.
1635
- 'if (import.meta.hot && __adapter.hotUpdateNeedsReload) import.meta.hot.on("bun:afterUpdate", () => location.reload())',
1636
- `const errorRouteIds = new Set(${JSON.stringify(errorRouteIds)})`,
1637
- // Each route is a lazy loader: dynamic imports → Bun.build (splitting) emits one chunk per
1638
- // route, shared layouts/deps deduped into shared chunks, so a route's code loads only when
1639
- // visited. loadModule caches the [layouts…, page] component chain + the chain's meta list per id.
1640
- "const loaders = {",
1641
- ...loaderRows,
1642
- "}",
1643
- "const chains = {}",
1644
- "const metas = {}",
1645
- // routeId → the page module's `searchSchema` export (or undefined). Populated lazily with
1646
- // chains/metas so the mount can derive this route's typed `search` from the URL, matching the SSR.
1647
- "const searchSchemas = {}",
1648
- // routeId → the page's client-only search keys (`searchClientKeys`, or `[]`). The router reads this
1649
- // by reference to decide when a same-route search change can skip the loader fetch (re-render only).
1650
- "const searchClientKeys = {}",
1651
- "const loadModule = async (id) => {",
1652
- " if (chains[id]) return",
1653
- " const mods = await loaders[id]()",
1654
- // For an error route the `_error` module is appended LAST: wrap the page (now second-to-last) in
1655
- // the adapter's boundary so a client render error renders the `_error` UI. DOM-transparent, so the
1656
- // hydrated tree matches the SSR markup (which has no boundary). Falls back to the plain chain when
1657
- // the adapter has no `errorBoundary`.
1658
- // `metas[id]` is the chain's `meta` exports in head order (outermost layout → … → page), so a
1659
- // soft-nav merges the layout chain's head with the page's - matching the SSR `<head>` (sitewide
1660
- // layout tags persist across client navigation, no flash of page-only head). `_error` carries no
1661
- // head (a terminal boundary), so it's excluded from the meta list for error routes.
1662
- " if (errorBoundary && errorRouteIds.has(id)) {",
1663
- " const fallback = mods[mods.length - 1].default",
1664
- " const page = mods[mods.length - 2].default",
1665
- " const layouts = mods.slice(0, mods.length - 2).map((m) => m.default)",
1666
- " chains[id] = [...layouts, errorBoundary(fallback), page]",
1667
- " metas[id] = mods.slice(0, mods.length - 1).map((m) => m.meta)",
1668
- // The search-schema CHAIN is the layout modules + page (all but the appended `_error`), so a layout's
1669
- // `searchSchema` merges with the page's. Client keys come from the page (second-to-last).
1670
- " searchSchemas[id] = mods.slice(0, mods.length - 1).map((m) => m.searchSchema)",
1671
- " searchClientKeys[id] = mods[mods.length - 2].searchClientKeys ?? []",
1672
- " } else {",
1673
- " chains[id] = mods.map((m) => m.default)",
1674
- " metas[id] = mods.map((m) => m.meta)",
1675
- // The chain is every module (layouts + page); client keys come from the page (the last module).
1676
- " searchSchemas[id] = mods.map((m) => m.searchSchema)",
1677
- " searchClientKeys[id] = mods[mods.length - 1].searchClientKeys ?? []",
1678
- " }",
1679
- "}",
1680
- "const patterns = [",
1681
- ...patternRows,
1682
- "]",
1683
- // Derive the initial route from the URL (correct on refresh/deep-link); fall back to the
1684
- // server-injected route id for non-pattern routes (e.g. _404, which matches nothing).
1685
- "const matched = createMatcher(patterns)(location.pathname)",
1686
- // Map any `{__nifra_deferred: id}` placeholder in the SSR data to the registry's promise, so the
1687
- // component receives real promises to `<Await>` (a no-op when a page has no deferred data).
1688
- MAP_DEFERRED_SOURCE,
1689
- "const initial = {",
1690
- ` routeId: matched ? matched.routeId : (window.${ROUTE_GLOBAL} ?? ""),`,
1691
- " params: matched ? matched.params : {},",
1692
- // pathname + search (NOT just pathname): the SSR render threads `pathname+search` into
1693
- // `useLocation`/`useSearchParams`, so the hydrating initial state must carry the query too or a
1694
- // page reading the search string would hydrate-mismatch. The #hash is client-only (never SSR'd).
1695
- " path: location.pathname + location.search,",
1696
- ` data: mapDeferred(window.${DATA_GLOBAL}),`,
1697
- // Undefined on a page-only app, which is exactly what the router treats as "no layout data".
1698
- ` layoutData: window.${LAYOUT_DATA_GLOBAL} && window.${LAYOUT_DATA_GLOBAL}.map(mapDeferred),`,
1699
- // actionData (only set after a form POST) is in the initial state so the binding hydrates
1700
- // consistently with the server-rendered markup; mapped through `mapDeferred` too so a deferred
1701
- // action's placeholders become registry markers (a no-op when the action didn't defer).
1702
- ` actionData: mapDeferred(window.${ACTION_GLOBAL}),`,
1703
- " pending: false,",
1704
- "}",
1705
- `const statusRoutes = ${JSON.stringify(statusRoutes)}`,
1706
- "const router = createClientRouter({ patterns, initial, loadModule, statusRoutes, searchClientKeys })",
1707
- "installHistory(router)",
1708
- "installForms(router)",
1709
- // The container is found in the DOM, not baked in. `rootId` is a per-render option and this entry
1710
- // is a per-build artifact, so a hardcoded id is a guess: `renderPage({ rootId: "app" })` produced a
1711
- // perfect document that hydrated NOTHING, with no diagnostic, because the missing `#root` was
1712
- // swallowed by an `if (root)`. `renderPage` marks a custom container with `ROOT_ATTRIBUTE`; the
1713
- // default `#root` it leaves unmarked, which is what the fallback is for.
1714
- `const root = document.querySelector("body > div[${ROOT_ATTRIBUTE}]") ?? document.getElementById("root")`,
1715
- // Loud, because there is no recoverable case: this entry ships only in a document `renderPage`
1716
- // opened a container in, so reaching here means the document is not the one it was built for.
1717
- `if (!root) throw new Error(${JSON.stringify("[nifra/web] no hydration container found. The generated bootstrap mounts into the element " +
1718
- `renderPage opened the app in - the one marked \`${ROOT_ATTRIBUTE}\` when a custom \`rootId\` ` +
1719
- "is set, `#root` otherwise - and this document has neither. If you emit the document yourself, " +
1720
- 'keep `<div id="root">` around the SSR markup.')})`,
1721
- // Load the initial route's chunk, then hydrate the Router (chain is cached). The initial head
1722
- // is server-rendered; subsequent navigations update it from the matched route's meta + data.
1723
- "loadModule(initial.routeId).then(() => {",
1724
- " mountRouter({ router, routes: chains, searchSchemas, container: root })",
1725
- // Next frame: the adapter has committed its initial hydration, so handlers are attached. Flip the
1726
- // document to interactive (`data-nifra-hydrated` + `nifra:hydrated`) for apps to gate pre-hydration UI.
1727
- " requestAnimationFrame(signalHydrated)",
1728
- " router.subscribe(() => {",
1729
- " const s = router.snapshot()",
1730
- // Merge the matched route's chain meta (layouts→page) into one head - same contract as SSR.
1731
- " if (!s.pending) {",
1732
- // `origin: location.origin` matches the SSR `originOf(req)` (both are `URL.origin` for the same
1733
- // page URL), so a soft-nav re-resolves the SAME absolute canonical/og:url - no head drift.
1734
- " const args = { data: s.data, params: s.params, origin: location.origin }",
1735
- " applyHead(mergeHeads((metas[s.routeId] ?? [undefined]).map((m) => resolveMeta(m, args))))",
1736
- " }",
1737
- " })",
1738
- "})",
1739
- ].join("\n")}\n`;
1740
- }
1741
- /**
1742
- * Codegen: emit a `.d.ts` that types cross-route `navigate({ to, search })` against each route's
1743
- * `searchSchema`. It augments the {@link RouteSearch} map with `"<pattern>": SearchOf<typeof import(...)>`
1744
- * for every **static** route (one with no `:param`/`*` segment - a concrete `to` a caller can pass; a
1745
- * dynamic route's concrete path can't match its pattern key, so those keep the loose object form). Written
1746
- * by `nifra sync-routes` next to the route tree and included in the app's `tsconfig`; because it is
1747
- * regenerated from the route files, a `navigate` whose `search` no longer matches the route's schema
1748
- * becomes a `tsc` error - the same drift guarantee as nifra's typed client, no hand-maintained map.
1749
- */
1750
- export function generateRouteSearchTypes(manifest, options) {
1751
- const { resolve, module = "@nifrajs/web" } = options;
1752
- // Static routes only (no `:param` / `*` catch-all): their pattern IS a concrete `to`. Sorted for stable
1753
- // output; a dynamic route falls through to the loose `{ to: string; search?: Record<...> }` form.
1754
- const entries = manifest.routes
1755
- .filter((route) => !/[:*]/.test(route.pattern))
1756
- .map((route) => [route.pattern, resolve(route.file)])
1757
- .sort((a, b) => (a[0] < b[0] ? -1 : 1))
1758
- .map(([pattern, spec]) => ` ${JSON.stringify(pattern)}: SearchOf<typeof import(${JSON.stringify(spec)})>`);
1759
- return `${[
1760
- "// GENERATED by @nifrajs/web generateRouteSearchTypes - typed cross-route navigate({ to, search }).",
1761
- "// Regenerated from the route files; a stale navigate search shape becomes a tsc error. Do not edit.",
1762
- 'import type { SearchOf } from "@nifrajs/web"',
1763
- `declare module ${JSON.stringify(module)} {`,
1764
- " interface RouteSearch {",
1765
- ...entries,
1766
- " }",
1767
- "}",
1768
- "export {}",
1769
- ].join("\n")}\n`;
1770
- }
1771
- /**
1772
- * Codegen: emit a **server manifest** module (as source) for disk-less edge runtimes (Cloudflare
1773
- * Workers, …) - and, with a `target`, any portable server bundle. `discoverRoutes` scans `node:fs`
1774
- * and dynamic-imports each route by a *runtime* path - neither exists on workerd. This instead emits
1775
- * **statically-analyzable** imports of every route/layout/`_error`/terminal status page (so the bundler includes them) and
1776
- * rebuilds the manifest with `buildManifest` - the SAME pure logic `discoverRoutes` feeds, so patterns
1777
- * + layout chains are identical. Eager (`import * as`) by default; `lazy` emits `() => import(...)` so
1778
- * a code-splitting bundler chunks per route. The emitted module exports `manifest` (consumed by
1779
- * `createWebApp`, unchanged) + `clientEntry` (baked). Write it to a file and bundle it into the worker
1780
- * entry (see `buildServer` in `@nifrajs/web/build`).
1781
- */
1782
- // Route source files are emitted as EXTENSIONLESS import specifiers. An explicit `.tsx`/`.ts` in an
1783
- // import is a hard error under a plain `tsc` (TS5097) unless `allowImportingTsExtensions` is set - which
1784
- // only the nifra template tsconfig does - so the generated manifest failed a bare `tsc` with one error
1785
- // per route. Every bundler and `moduleResolution` still resolves the extensionless form to the source
1786
- // file, so dropping the extension costs nothing at build time and makes the output portable. Only a
1787
- // known TS/JS source extension is stripped; the map KEY keeps its extension (it is the route identifier
1788
- // `buildManifest` matches, not an import path).
1789
- const SOURCE_EXTENSION = /\.(?:[mc]?tsx?|[mc]?jsx?)$/;
1790
- function moduleSpecifier(resolved) {
1791
- return resolved.replace(SOURCE_EXTENSION, "");
1792
- }
1793
- export function generateServerManifest(manifest, options) {
1794
- const { resolve, clientEntry, styles, routeStyles, lazy = false } = options;
1795
- // Every unique source file in the manifest (routes + layouts + error/status pages), sorted for stable output.
1796
- const files = [
1797
- ...new Set([
1798
- ...manifest.routes.map((r) => r.file),
1799
- ...Object.values(manifest.layouts).map((l) => l.file),
1800
- ...Object.values(manifest.errors ?? {}).map((e) => e.file),
1801
- ...(manifest.notFound ? [manifest.notFound.file] : []),
1802
- ...Object.values(manifest.statusPages ?? {}).map((page) => page.file),
1803
- ]),
1804
- ].sort();
1805
- const header = [
1806
- "// GENERATED by @nifrajs/web generateServerManifest - route manifest for the disk-less edge",
1807
- "// (no filesystem; route imports are static specifiers the bundler resolves). buildManifest is",
1808
- "// the same pure logic discoverRoutes feeds, so patterns + layout chains match exactly.",
1809
- 'import { buildManifest, type RouteModule } from "@nifrajs/web"',
1810
- ];
1811
- const clientEntryLine = `export const clientEntry = ${JSON.stringify(clientEntry)}`;
1812
- // Baked stylesheet URLs so the server entry can pass them to createWebApp → <link rel="stylesheet">.
1813
- // Always emitted (default empty) so consumers can `import { styles, routeStyles }` unconditionally.
1814
- const stylesLine = `export const styles = ${JSON.stringify(styles ?? [])}`;
1815
- const routeStylesLine = `export const routeStyles = ${JSON.stringify(routeStyles ?? {})}`;
1816
- if (lazy) {
1817
- // Lazy: `() => import("./routes/x")` per route (static specifier → one chunk per route under a
1818
- // code-splitting bundler, loaded on first request). The map keys are the route-relative paths
1819
- // `buildManifest` expects; the importer it builds calls the per-file loader.
1820
- const loaders = files.map((file) => ` ${jsStringLiteral(file)}: () => import(${jsStringLiteral(moduleSpecifier(resolve(file)))}),`);
1821
- return `${[
1822
- ...header,
1823
- "const loaders: Record<string, () => Promise<RouteModule>> = {",
1824
- ...loaders,
1825
- "}",
1826
- clientEntryLine,
1827
- stylesLine,
1828
- routeStylesLine,
1829
- "export const manifest = buildManifest(Object.keys(loaders), (file) => () => loaders[file]())",
1830
- ].join("\n")}\n`;
1831
- }
1832
- // Eager: `import * as` per route (all bundled into the entry, parsed at boot). Index-based
1833
- // identifiers are collision-proof regardless of filename.
1834
- const imports = files.map((file, i) => `import * as m${i} from ${JSON.stringify(moduleSpecifier(resolve(file)))}`);
1835
- const entries = files.map((file, i) => ` ${JSON.stringify(file)}: m${i},`);
1836
- return `${[
1837
- ...header,
1838
- ...imports,
1839
- "const modules: Record<string, RouteModule> = {",
1840
- ...entries,
1841
- "}",
1842
- clientEntryLine,
1843
- stylesLine,
1844
- routeStylesLine,
1845
- "export const manifest = buildManifest(Object.keys(modules), (file) => () => Promise.resolve(modules[file]))",
1846
- ].join("\n")}\n`;
1847
- }
1848
- /**
1849
- * The two file-name conventions that decide what never reaches a browser: a `*.server` module is
1850
- * EMPTIED in the client build, a `*.fn` module is REPLACED with client stubs.
1851
- *
1852
- * Exported because more than the bundlers need them. `nifra dev --bun` cannot transform (Bun's dev
1853
- * bundler takes no plugins) so it must REFUSE instead, and a refusal driven by its own hand-written
1854
- * glob drifts from the transform - which is how `.fn.mts` came to be stubbed by both build pipelines
1855
- * and waved through by the guard that exists to stop it leaking. Anything deciding "is this module
1856
- * server-only" should import the matcher rather than re-encode it.
1857
- */
1858
- export { SERVER_FN_MODULE, SERVER_ONLY_MODULE } from "./internal/server-boundary.js";
1859
58
  //# sourceMappingURL=index.js.map