@opentf/afw-build 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/compile.js CHANGED
@@ -20,17 +20,28 @@ export function validateOptions({ mode = "spa", target } = {}) {
20
20
 
21
21
  /**
22
22
  * The compiler target for one module. `server` — the module is bundled for the
23
- * server (string renderers). `dev` — a dev server or test run, which always renders
24
- * on the client. Otherwise a release browser build: CSR for an SPA, the hydrating
25
- * dual module when the server renders first.
23
+ * server (string renderers). `test` — a test run, which renders on the client.
24
+ * `dev` — a dev server's browser build: the hydrating dual module when the dev server
25
+ * renders pages first, as production does (`devRenders`, by default only for `ssr`);
26
+ * CSR otherwise. Otherwise a release browser build: CSR for an SPA, the hydrating dual
27
+ * module when the server renders first.
26
28
  */
27
- export function chooseTarget({ mode = "spa", target, server = false, dev = false } = {}) {
29
+ export function chooseTarget({ mode = "spa", target, server = false, dev = false, test = false, devRenders = mode === "ssr" } = {}) {
28
30
  if (target) return target;
29
31
  if (server) return "ssg";
30
- if (dev) return "csr";
32
+ if (test) return "csr";
33
+ if (dev) return devRenders && mode !== "spa" ? "hydrate" : "csr";
31
34
  return mode === "spa" ? "csr" : "hydrate";
32
35
  }
33
36
 
37
+ /** The compiler backend token for `target`, with `hot` selecting its refresh build. */
38
+ export function compilerTarget(target, hot = false) {
39
+ if (!hot) return target;
40
+ if (target === "csr") return "csr-hot";
41
+ if (target === "hydrate") return "hydrate-hot";
42
+ return target;
43
+ }
44
+
34
45
  /** Whether framework imports in this build resolve to the DOM-free server entry. */
35
46
  export function usesServerEntry({ target, server = false } = {}) {
36
47
  return (target ?? (server ? "ssg" : undefined)) === "ssg";
@@ -39,10 +50,10 @@ export function usesServerEntry({ target, server = false } = {}) {
39
50
  /** The framework specifiers that resolve to `@opentf/afw/server` in a server build. */
40
51
  export const FRAMEWORK_IMPORT = /^@opentf\/afw(?:\/runtime)?$/;
41
52
 
42
- /** Page, layout and 404 modules compile to route factories; the rest to components. */
53
+ /** Page, layout, 404, loading and error modules compile to route factories; the rest to components. */
43
54
  export function isRouteModule(id) {
44
55
  const base = id.split(/[\\/]/).pop().replace(SOURCE_FILTER, "");
45
- return base === "page" || base === "layout" || base === "404";
56
+ return base === "page" || base === "layout" || base === "404" || base === "loading" || base === "error";
46
57
  }
47
58
 
48
59
  /** A module that shows the compile error in place of the page or component. */
@@ -57,7 +68,7 @@ export function errorStub(text) {
57
68
 
58
69
  /**
59
70
  * Compile one module. `server` is a compiler client (compiler-client.js). `hot`
60
- * requests the refresh-instrumented CSR build. On failure, `failOnError` throws the
71
+ * requests the refresh-instrumented build of the target (CSR or hydrate). On failure, `failOnError` throws the
61
72
  * diagnostic (after `error(message)` when the toolchain reports through its own
62
73
  * channel); otherwise it logs and returns the stub, so one broken file does not
63
74
  * stop a dev server.
@@ -68,7 +79,7 @@ export async function compileModule(server, code, id, {
68
79
  target, hot = false, failOnError = false, onResult, quiet = () => {}, error,
69
80
  } = {}) {
70
81
  try {
71
- const out = await server.compile(id, code, !isRouteModule(id), hot && target === "csr" ? "csr-hot" : target);
82
+ const out = await server.compile(id, code, !isRouteModule(id), compilerTarget(target, hot));
72
83
  onResult?.(id, null);
73
84
  return typeof out === "string" ? { code: out, map: null } : { code: out.code, map: out.map ?? null };
74
85
  } catch (e) {
package/document.js CHANGED
@@ -84,7 +84,12 @@ export function stampRenderedPath(shellHtml, path) {
84
84
  export function injectHead(shellHtml, headHtml) {
85
85
  if (!headHtml) return shellHtml;
86
86
  let out = stripRouteHead(shellHtml);
87
- if (/<title[\s>]/i.test(headHtml)) out = out.replace(/<title>[\s\S]*?<\/title>\s*/i, "");
87
+ if (/<title[\s>]/i.test(headHtml)) {
88
+ // The page's title replaces the shell's. Keep the shell's as the client's fallback
89
+ // for a later page without a title (runtime/head.js `prepareRouteHead`).
90
+ out = out.replace(/<title>([\s\S]*?)<\/title>\s*/i, (_, text) =>
91
+ text.trim() ? `<meta name="afw-shell-title" content="${text.trim().replace(/"/g, "&quot;")}">\n` : "");
92
+ }
88
93
  // Function replacer so `$` in `headHtml` (e.g. a price in a meta description) is literal.
89
94
  return out.replace(/<\/head>/i, () => `${headHtml}\n</head>`);
90
95
  }
@@ -187,28 +192,38 @@ export function alternateLinks(path, i18n) {
187
192
  * `modifiedTime` adds `article:modified_time` on article pages. `notFound`: what a
188
193
  * loader's `notFound()` does — `"render"` the 404 page (a request server), or
189
194
  * `"throw"` it to the caller (static generation, which reports the path as failed).
195
+ * `errors`: what any other loader failure does — `"throw"` it (the default: static
196
+ * generation reports the path as failed), or `"render"` the route's nearest
197
+ * `error.jsx` with status 500 (a request server). Thrown `Response`s always throw.
190
198
  *
191
199
  * @returns {Promise<{ status: number, html: string, dataJson: string, loaded: boolean, metadata: object } | null>}
192
200
  * `null` when no page and no 404 page match.
193
201
  */
194
202
  export async function renderDocument(render, {
195
203
  shell, url, params = null, search = "", loaders = null, loaderContext = {}, baseUrl = "", i18n = null,
196
- preload = "", modifiedTime = null, notFound = "render",
204
+ preload = "", modifiedTime = null, notFound = "render", errors = "throw",
197
205
  } = {}) {
198
206
  const { locale, path } = splitLocale(url, i18n);
199
207
  const match = loaders?.match(url);
200
208
  let data;
201
209
  let dataJson = "";
210
+ let failure;
202
211
  if (match) {
203
212
  try {
204
213
  ({ data, json: dataJson } = await loaders.loadSerialized(match, { query: {}, ...loaderContext }));
205
214
  } catch (e) {
206
- if (e?.afwNotFound !== true || notFound === "throw") throw e;
207
- return renderNotFound(render, { shell, baseUrl, preload });
215
+ if (e?.afwNotFound === true && notFound !== "throw") return renderNotFound(render, { shell, baseUrl, preload });
216
+ // A request server renders the route's `error.jsx` (status 500); a redirect or
217
+ // refusal (`throw new Response`), a build, or a route without one keeps the throw.
218
+ if (errors !== "render" || e?.afwNotFound === true || e instanceof Response) throw e;
219
+ failure = e;
208
220
  }
209
221
  }
210
- const result = await render.renderRoute(url, params, search, { data });
222
+ const result = failure === undefined
223
+ ? await render.renderRoute(url, params, search, { data })
224
+ : await render.renderRoute(url, params, search, { error: failure });
211
225
  if (!result) return null;
226
+ if (result.dataJson) dataJson = result.dataJson;
212
227
  const { html, metadata = {}, hydration = "", status = 200 } = result;
213
228
  const alternates = alternateLinks(path, i18n);
214
229
  const meta = alternates.length ? { ...metadata, links: [...(metadata.links || []), ...alternates] } : metadata;
@@ -227,7 +242,7 @@ export async function renderDocument(render, {
227
242
  ),
228
243
  dataJson,
229
244
  );
230
- return { status, html: document, dataJson, loaded: !!match, metadata };
245
+ return { status, html: document, dataJson, loaded: !!match, metadata, route: result.route ?? null };
231
246
  }
232
247
 
233
248
  /** The 404 page as a document (`noindex`), or `null` when the app has none. */
package/index.js CHANGED
@@ -7,14 +7,18 @@ export { assertHost } from "./host.js";
7
7
  export { compileError, closeCompilers, startCompilerServer } from "./compiler-client.js";
8
8
  export {
9
9
  FRAMEWORK_IMPORT, MODES, SOURCE_FILTER, TARGETS,
10
- chooseTarget, compileModule, errorStub, isRouteModule, usesServerEntry, validateOptions,
10
+ chooseTarget, compileModule, compilerTarget, errorStub, isRouteModule, usesServerEntry, validateOptions,
11
11
  } from "./compile.js";
12
12
  export { ensureCompiler, findUp, resolveCompiler } from "./resolve-compiler.js";
13
13
  export {
14
14
  ROUTES_ID,
15
- discoverLoaders, discoverPages, findGuard, isUnpublishedPage, isUnpublishedSource,
15
+ discoverLoaders, discoverPages, findGuard, isUnpublishedPage, isUnpublishedSource, loaderPageRoutes,
16
16
  resolveAppRoot, routeKey, routesModule,
17
17
  } from "./routes.js";
18
+ export {
19
+ CONFIG_FILE, RENDERS, RENDER_OF_MODE,
20
+ clientRouteFiles, discoverRouteConfigs, folderRoute, formatRouteTable, readRouteConfigs, resolveRoutePolicies, routeManifest, routeRenders, staticPathConfigs,
21
+ } from "./route-policy.js";
18
22
  export { SERVER_ID, discoverServerFiles, hasServerFiles, serverConflicts, serverModule } from "./server.js";
19
23
  export {
20
24
  DATA_FILE, alternateLinks, escapeXml, i18nSettings, injectBeforeBody, injectHead, injectHydrationData,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opentf/afw-build",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "The toolchain-neutral core of AFW's build: compiler client, compile targets and file-based routing.",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -17,6 +17,7 @@
17
17
  "compile.js",
18
18
  "resolve-compiler.js",
19
19
  "routes.js",
20
+ "route-policy.js",
20
21
  "server.js",
21
22
  "document.js",
22
23
  "prerender.js",
package/prerender.js CHANGED
@@ -41,6 +41,8 @@ export function robotsTxt(baseUrl, hasSitemap) {
41
41
  * (marked for hydration by the caller when the client hydrates). `loaders` is the
42
42
  * loader registry, run at build time with no request and an empty query. A
43
43
  * `public/sitemap.xml` or `public/robots.txt` in `publicDir` wins over the generated one.
44
+ * `routes` (a Set of route patterns) limits the prerender to those routes and skips the
45
+ * 404 page, sitemap and robots.txt — a server app's static routes.
44
46
  *
45
47
  * @returns {Promise<{ count: number, skipped: string[], failed: string[], siteDescription: string, paths: string[] }>}
46
48
  * `siteDescription` is the site's own description (home route, else the root
@@ -48,12 +50,16 @@ export function robotsTxt(baseUrl, hasSitemap) {
48
50
  */
49
51
  export async function prerender(host, {
50
52
  render, shellHtml, outDir, publicDir, baseUrl = "", lastUpdated = {}, i18n = null, loaders = null,
51
- chunkManifest = null, onRender,
53
+ chunkManifest = null, onRender, routes = null,
52
54
  }) {
53
55
  const settings = i18nSettings(i18n);
54
56
  const locales = settings ? settings.locales : [null];
55
57
  const defaultLocale = settings?.defaultLocale ?? null;
56
- const { paths, skipped } = await render.collectRoutePaths();
58
+ // `routes`: only these route patterns, as a Set (a server app prerenders just its
59
+ // static routes; no 404 page, sitemap or robots.txt then).
60
+ const collected = await render.collectRoutePaths();
61
+ const paths = routes ? collected.paths.filter((p) => routes.has(p.route)) : collected.paths;
62
+ const skipped = routes ? collected.skipped.filter((r) => routes.has(r)) : collected.skipped;
57
63
  const preloadFor = (route) => modulepreloadTags(chunkManifest?.routes?.[route]);
58
64
 
59
65
  const failed = [];
@@ -89,6 +95,10 @@ export async function prerender(host, {
89
95
  }
90
96
  }
91
97
 
98
+ // A partial prerender (a server app's static routes) stops here: its server answers
99
+ // unknown paths and serves no sitemap of its own yet.
100
+ if (routes) return { count: rendered.length, skipped, failed, siteDescription, paths: rendered };
101
+
92
102
  // Any unmatched path is served the 404 page by static hosts.
93
103
  try {
94
104
  const notFound = await renderNotFound(render, { shell: shellHtml, baseUrl, preload: modulepreloadTags(chunkManifest?.notFound) });
@@ -0,0 +1,215 @@
1
+ // Per-route rendering: each folder's `_config.{js,ts}` declares how its pages render
2
+ // (`server`, `static`, `client`), and the nearest one up the folder tree wins. The app
3
+ // default is the root `_config.js`, else the plugin's `mode` shorthand. Resolution needs
4
+ // only the files: the compiler reads each config without running it (`route-config`), so
5
+ // the result can decide what each bundle contains before any bundle exists.
6
+
7
+ /** A folder's config file. One per folder; `.js` and `.ts` side by side is an error. */
8
+ export const CONFIG_FILE = /^_config\.(js|ts)$/;
9
+
10
+ /** The render strategies. */
11
+ export const RENDERS = ["server", "static", "client"];
12
+
13
+ /** The plugin's `mode` shorthand, as the app default it stands for. */
14
+ export const RENDER_OF_MODE = { spa: "client", ssg: "static", ssr: "server" };
15
+
16
+ const PAGE = /^page\.(mdx|md|[jt]sx)$/;
17
+ const LAYOUT = /^layout\.[jt]sx$/;
18
+
19
+ /** Folder of a `/`-separated relative path ("" for the app root). */
20
+ const folderOf = (rel) => (rel.includes("/") ? rel.slice(0, rel.lastIndexOf("/")) : "");
21
+
22
+ /** The URL pattern a folder serves: route groups `(name)` are not part of it. */
23
+ export function folderRoute(folder) {
24
+ const segments = folder.split("/").filter((s) => s && !/^\(.+\)$/.test(s));
25
+ return `/${segments.join("/")}`;
26
+ }
27
+
28
+ /** The folders from `folder` up to the app root, nearest first. */
29
+ function ancestry(folder) {
30
+ const out = [folder];
31
+ for (let f = folder; f; ) {
32
+ f = folderOf(f);
33
+ out.push(f);
34
+ }
35
+ return out;
36
+ }
37
+
38
+ const relative = (root, abs) => abs.slice(root.replace(/\/+$/, "").length + 1);
39
+
40
+ /**
41
+ * Every `_config.{js,ts}` under `root`, as a map from folder (relative, "" for the
42
+ * root) to absolute path. Excluded subtrees, dot directories and node_modules are skipped.
43
+ */
44
+ export async function discoverRouteConfigs(host, root, { exclude = [] } = {}) {
45
+ const found = new Map();
46
+ const skip = new Set(exclude);
47
+ async function visit(abs, rel) {
48
+ let entries;
49
+ try {
50
+ entries = await host.readDir(abs);
51
+ } catch {
52
+ return;
53
+ }
54
+ for (const entry of entries) {
55
+ const childRel = rel ? `${rel}/${entry.name}` : entry.name;
56
+ if ([...skip].some((name) => childRel === name || childRel.startsWith(`${name}/`))) continue;
57
+ const childAbs = host.path.join(abs, entry.name);
58
+ let isDir = entry.isDir;
59
+ let isFile = entry.isFile;
60
+ if (entry.isSymlink) {
61
+ const kind = await host.kind(childAbs);
62
+ isDir = kind === "dir";
63
+ isFile = kind === "file";
64
+ }
65
+ if (isDir) {
66
+ if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
67
+ await visit(childAbs, childRel);
68
+ } else if (isFile && CONFIG_FILE.test(entry.name)) {
69
+ if (found.has(rel)) throw new Error(`Two config files for one folder: ${found.get(rel)} and ${childAbs}. Keep one _config.js (or _config.ts).`);
70
+ found.set(rel, childAbs);
71
+ }
72
+ }
73
+ }
74
+ await visit(root, "");
75
+ return found;
76
+ }
77
+
78
+ /**
79
+ * Read each discovered config through the compiler (without running it). Returns a map
80
+ * from folder to `{ file, render, data, paths }`. A config the compiler rejects throws
81
+ * its diagnostic, which names the file and position.
82
+ */
83
+ export async function readRouteConfigs(host, compiler, configs) {
84
+ const out = new Map();
85
+ for (const [folder, file] of configs) {
86
+ const raw = await compiler.compile(file, await host.readText(file), false, "route-config");
87
+ const parsed = JSON.parse(typeof raw === "string" ? raw : raw.code);
88
+ out.set(folder, { file, render: parsed.render ?? null, data: parsed.data ?? null, paths: !!parsed.paths });
89
+ }
90
+ return out;
91
+ }
92
+
93
+ /**
94
+ * Resolve every page's policy. `pages` are absolute page/layout/404/loading/error files
95
+ * (as `discoverPages` returns); only `page.*` files are routes. `configs` is the map
96
+ * `readRouteConfigs` returns. `mode` is the plugin option as the app passed it
97
+ * (`undefined` when it did not).
98
+ *
99
+ * Returns `{ defaultRender, routes, policyOf, warnings }`:
100
+ * - `routes`: one entry per page, sorted by route — `{ route, folder, file, render, data,
101
+ * from }`, where `from` is the config file that decided `render` (or `mode` / the default).
102
+ * - `policyOf(folder)`: the same resolution for any folder (a layout's, say).
103
+ * - `warnings`: config files that govern no page.
104
+ * Throws on a conflict the app must fix: a root `render` and a `mode` together, `paths`
105
+ * outside a static folder, `data` outside a client folder.
106
+ */
107
+ export function resolveRoutePolicies({ root, pages, configs, mode }) {
108
+ const rootConfig = configs.get("");
109
+ if (rootConfig?.render && mode !== undefined) {
110
+ throw new Error(
111
+ `The app default is set twice: render "${rootConfig.render}" in ${rootConfig.file} and mode "${mode}" in the plugin options. ` +
112
+ `Set it in one place (the root _config.js).`,
113
+ );
114
+ }
115
+ if (mode !== undefined && !RENDER_OF_MODE[mode]) throw new Error(`Unknown AFW rendering mode: ${mode} (expected spa, ssg, or ssr)`);
116
+ const defaultRender = rootConfig?.render ?? RENDER_OF_MODE[mode ?? "spa"];
117
+ const defaultFrom = rootConfig?.render ? rootConfig.file : mode !== undefined ? `mode: "${mode}"` : "default";
118
+
119
+ function policyOf(folder) {
120
+ let render = null, from = null, data = null;
121
+ for (const f of ancestry(folder)) {
122
+ const c = configs.get(f);
123
+ if (!c) continue;
124
+ if (!render && c.render) { render = c.render; from = c.file; }
125
+ if (!data && c.data) data = c.data;
126
+ }
127
+ return { render: render ?? defaultRender, from: from ?? defaultFrom, data: (render ?? defaultRender) === "client" ? data ?? "server" : null };
128
+ }
129
+
130
+ // A key only means something under the strategy it belongs to.
131
+ for (const [folder, c] of configs) {
132
+ const { render } = policyOf(folder);
133
+ if (c.paths && render !== "static") {
134
+ throw new Error(`${c.file}: \`paths\` lists the pages a static route builds, but this folder renders "${render}". Remove it, or set render: "static".`);
135
+ }
136
+ if (c.data && render !== "client") {
137
+ throw new Error(`${c.file}: \`data\` applies to client routes, but this folder renders "${render}". Remove it, or set render: "client".`);
138
+ }
139
+ }
140
+
141
+ const routes = [];
142
+ const layoutFolders = pages.map((abs) => relative(root, abs)).filter((rel) => LAYOUT.test(rel.split("/").pop())).map(folderOf);
143
+ for (const abs of pages) {
144
+ const rel = relative(root, abs);
145
+ if (!PAGE.test(rel.split("/").pop())) continue;
146
+ const folder = folderOf(rel);
147
+ const policy = policyOf(folder);
148
+ // The server cannot render inside a layout it never loads.
149
+ if (policy.render !== "client") {
150
+ const client = ancestry(folder).find((f) => layoutFolders.includes(f) && policyOf(f).render === "client");
151
+ if (client !== undefined) {
152
+ throw new Error(
153
+ `${abs} renders "${policy.render}", but the layout in app/${client ? `${client}/` : ""} renders "client": ` +
154
+ `the server cannot render a page inside a layout that renders in the browser. Make this folder "client" too, or move the page out of it.`,
155
+ );
156
+ }
157
+ }
158
+ routes.push({ route: folderRoute(folder), folder, file: abs, ...policy });
159
+ }
160
+ routes.sort((a, b) => (a.route < b.route ? -1 : a.route > b.route ? 1 : a.folder < b.folder ? -1 : 1));
161
+
162
+ // `paths` lists the pages of the dynamic route in its own folder; it is not inherited.
163
+ for (const [folder, c] of configs) {
164
+ if (!c.paths) continue;
165
+ const own = routes.find((r) => r.folder === folder);
166
+ if (!own || !own.route.includes("[")) {
167
+ throw new Error(`${c.file}: \`paths\` lists the pages of a dynamic route, but this folder has no dynamic page (like [slug]/page.jsx). Move it to that page's folder.`);
168
+ }
169
+ }
170
+
171
+ const warnings = [];
172
+ for (const [folder, c] of configs) {
173
+ if (!routes.some((r) => r.folder === folder || r.folder.startsWith(folder ? `${folder}/` : ""))) {
174
+ warnings.push(`${c.file} governs no page: there is no page.* in its folder or below it.`);
175
+ }
176
+ }
177
+ return { defaultRender, routes, policyOf, warnings };
178
+ }
179
+
180
+ /**
181
+ * The route files (from `discoverPages`: pages, layouts, 404, loading and error files)
182
+ * that render in the browser: those in a folder whose policy is `client`. The generated
183
+ * route tables mark them with `clientRoute`, and the server bundle leaves them out.
184
+ */
185
+ export function clientRouteFiles({ policyOf }, root, files) {
186
+ return new Set(files.filter((abs) => policyOf(folderOf(relative(root, abs))).render === "client"));
187
+ }
188
+
189
+ /** The configs that declare `paths`, as `[routePattern, configFile]` for the server module. */
190
+ export function staticPathConfigs({ routes }, configs) {
191
+ return routes.filter((r) => configs.get(r.folder)?.paths).map((r) => [r.folder ? `/${r.folder}` : "/", configs.get(r.folder).file]);
192
+ }
193
+
194
+ /** Each route's strategy keyed by its route-table pattern (`/`, `/(legal)/privacy`), for the server module. */
195
+ export function routeRenders({ routes }) {
196
+ return Object.fromEntries(routes.map((r) => [r.folder ? `/${r.folder}` : "/", r.render]));
197
+ }
198
+
199
+ /** The resolved policies as the build prints them: route, render, and the file that decided it. */
200
+ export function formatRouteTable(routes, root = "") {
201
+ const from = (f) => (root && f.startsWith(`${root}/`) ? `app/${f.slice(root.length + 1)}` : f);
202
+ const rows = [["Route", "Render", "From"], ...routes.map((r) => [r.route, r.render + (r.data === "client" ? " (data: client)" : ""), from(r.from)])];
203
+ const widths = [0, 1].map((i) => Math.max(...rows.map((row) => row[i].length)));
204
+ return rows.map((row) => `${row[0].padEnd(widths[0])} ${row[1].padEnd(widths[1])} ${row[2]}`).join("\n");
205
+ }
206
+
207
+ /** The route manifest written beside the build (`routes.json`): what each route resolved to. */
208
+ export function routeManifest({ defaultRender, routes }, root = "") {
209
+ const rel = (f) => (root && f.startsWith(`${root}/`) ? `app/${f.slice(root.length + 1)}` : f);
210
+ return {
211
+ version: 1,
212
+ default: defaultRender,
213
+ routes: routes.map((r) => ({ route: r.route, render: r.render, ...(r.data ? { data: r.data } : {}), page: rel(r.file), from: rel(r.from) })),
214
+ };
215
+ }
package/routes.js CHANGED
@@ -10,8 +10,9 @@
10
10
  /** The specifier entries import. */
11
11
  export const ROUTES_ID = "@afw/routes";
12
12
 
13
- const PAGE_FILE = /^(page|layout|404)\.(mdx|md|jsx|tsx)$/;
13
+ const PAGE_FILE = /^(page|layout|404|loading|error)\.(mdx|md|jsx|tsx)$/;
14
14
  const LOADER_FILE = /^loader\.(js|ts)$/;
15
+ const LAYOUT_LOADER_FILE = /^layout\.loader\.(js|ts)$/;
15
16
 
16
17
  /**
17
18
  * Whether Markdown source is unpublished: frontmatter `draft: true`, or a `date`
@@ -83,9 +84,9 @@ async function walk(host, dir, pattern, exclude) {
83
84
  }
84
85
 
85
86
  /**
86
- * Page, layout and 404 files under `dir`, as absolute paths. A Markdown 404 is an
87
- * error (the runtime has no Markdown fallback route). Without `drafts`,
88
- * unpublished Markdown pages are left out.
87
+ * Page, layout, 404, loading and error files under `dir`, as absolute paths. A
88
+ * Markdown 404, loading or error file is an error (each is a component the router
89
+ * renders with props). Without `drafts`, unpublished Markdown pages are left out.
89
90
  */
90
91
  export async function discoverPages(host, dir, { exclude = [], drafts = true } = {}) {
91
92
  const out = [];
@@ -94,6 +95,10 @@ export async function discoverPages(host, dir, { exclude = [], drafts = true } =
94
95
  if (/(^|\/)404\.(mdx|md)$/.test(rel)) {
95
96
  throw new Error(`Unsupported Markdown 404 route: ${abs}. Use 404.jsx or 404.tsx instead.`);
96
97
  }
98
+ const special = /(?:^|\/)(loading|error)\.(?:mdx|md)$/.exec(rel);
99
+ if (special) {
100
+ throw new Error(`Unsupported Markdown ${special[1]} file: ${abs}. Use ${special[1]}.jsx or ${special[1]}.tsx instead.`);
101
+ }
97
102
  if (!drafts && (await isUnpublishedPage(host, abs))) continue;
98
103
  out.push(abs);
99
104
  }
@@ -101,19 +106,37 @@ export async function discoverPages(host, dir, { exclude = [], drafts = true } =
101
106
  }
102
107
 
103
108
  /** Loader files under `dir` as `[route, absPath]` pairs, sorted by route. A route
104
- * with both `loader.js` and `loader.ts` is an error. */
105
- export async function discoverLoaders(host, dir, { exclude = [] } = {}) {
109
+ * with both `loader.js` and `loader.ts` is an error. `{ layout: true }` finds
110
+ * `layout.loader.{js,ts}` files instead, keyed by their layout's folder. */
111
+ export async function discoverLoaders(host, dir, { exclude = [], layout = false } = {}) {
106
112
  const routes = new Map();
107
- for (const rel of await walk(host, dir, LOADER_FILE, new Set(exclude))) {
108
- const pattern = rel.replace(/(^|\/)loader\.(js|ts)$/, "") || "/";
113
+ for (const rel of await walk(host, dir, layout ? LAYOUT_LOADER_FILE : LOADER_FILE, new Set(exclude))) {
114
+ const pattern = rel.replace(/(^|\/)(?:layout\.)?loader\.(js|ts)$/, "") || "/";
109
115
  const route = pattern.startsWith("/") ? pattern : `/${pattern}`;
110
116
  const abs = host.path.join(dir, rel);
111
- if (routes.has(route)) throw new Error(`Conflicting loaders for ${route}: ${routes.get(route)} and ${abs}`);
117
+ if (routes.has(route)) throw new Error(`Conflicting ${layout ? "layout " : ""}loaders for ${route}: ${routes.get(route)} and ${abs}`);
112
118
  routes.set(route, abs);
113
119
  }
114
120
  return [...routes].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
115
121
  }
116
122
 
123
+ /** Does the layout at `folder` wrap the page at `route`? (Mirrors `@opentf/afw/server`.) */
124
+ const layoutWraps = (folder, route) => folder === "/" || route === folder || route.startsWith(`${folder}/`);
125
+
126
+ /**
127
+ * The page routes with loader data — their own `loader.*`, or any page beneath a
128
+ * `layout.loader.*` — which the client router fetches `__data.json` for. Mirrors
129
+ * `loaderPageRoutes` in `@opentf/afw/server`, which this package does not import.
130
+ */
131
+ export function loaderPageRoutes({ pages = [], pageLoaders = [], layoutLoaders = [] }) {
132
+ const out = new Set(pageLoaders);
133
+ for (const page of pages) if (layoutLoaders.some((folder) => layoutWraps(folder, page))) out.add(page);
134
+ return [...out].sort();
135
+ }
136
+
137
+ /** The route a `page.*` file serves: its folder (`/` for the app root). */
138
+ const pageRoute = (file, root) => routeKey(file, root).replace(/^\/app/, "").replace(/\/page\.[^/]+$/, "") || "/";
139
+
117
140
  function stripAppPrefix(filePath, appDir) {
118
141
  if (appDir) {
119
142
  const base = appDir.replace(/\/+$/, "");
@@ -161,16 +184,36 @@ export async function resolveAppRoot(host, appDir, importer) {
161
184
  *
162
185
  * @returns {Promise<{ code: string, files: string[] }>}
163
186
  */
164
- export async function routesModule(host, root, { exclude = [], drafts = true } = {}) {
187
+ export async function routesModule(host, root, { exclude = [], drafts = true, clientFiles = new Set() } = {}) {
165
188
  const pages = await discoverPages(host, root, { exclude, drafts });
166
189
  const loaders = await discoverLoaders(host, root, { exclude });
190
+ const layoutLoaders = await discoverLoaders(host, root, { exclude, layout: true });
167
191
  const guard = await findGuard(host, root);
168
- const map = pages
169
- .map((p) => ` [${JSON.stringify(routeKey(p, root))}]: () => import(${JSON.stringify(p)}),`)
170
- .join("\n");
192
+ // Route groups drop out of the URL: two groups holding the same page path collide.
193
+ const byUrl = new Map();
194
+ for (const file of pages.filter((p) => /\/page\.[^/]+$/.test(p))) {
195
+ const route = pageRoute(file, root);
196
+ const url = `/${route.split("/").filter((s) => s && !/^\(.+\)$/.test(s)).join("/")}`;
197
+ if (byUrl.has(url)) throw new Error(`Two pages answer ${url}: ${byUrl.get(url)} and ${file}. Move one to another path.`);
198
+ byUrl.set(url, file);
199
+ }
200
+ const loaderRoutes = loaderPageRoutes({
201
+ pages: pages.filter((p) => /\/page\.[^/]+$/.test(p)).map((p) => pageRoute(p, root)),
202
+ pageLoaders: loaders.map(([route]) => route),
203
+ layoutLoaders: layoutLoaders.map(([route]) => route),
204
+ });
205
+ // Entries that render in the browser (`_config.js` → `client`) are marked, so a page
206
+ // server-rendered around them adopts its layouts and builds the rest. The mark is the
207
+ // flag `clientRoute()` sets, written inline: importing the runtime here would load a
208
+ // second copy of it where a toolchain resolves a virtual module's imports elsewhere.
209
+ const entry = (p) => (clientFiles.has(p)
210
+ ? `Object.assign(() => import(${JSON.stringify(p)}), { __afwClient: true })`
211
+ : `() => import(${JSON.stringify(p)})`);
212
+ const map = pages.map((p) => ` [${JSON.stringify(routeKey(p, root))}]: ${entry(p)},`).join("\n");
171
213
  const code =
172
214
  `export const pages = {\n${map}\n};\n` +
173
- `export const loaderRoutes = ${JSON.stringify(loaders.map(([route]) => route))};\n` +
215
+ `export const loaderRoutes = ${JSON.stringify(loaderRoutes)};\n` +
174
216
  (guard ? `export { default as guard } from ${JSON.stringify(guard)};\n` : `export const guard = undefined;\n`);
175
- return { code, files: [...pages, ...loaders.map(([, file]) => file), ...(guard ? [guard] : [])] };
217
+ const loaderFiles = [...loaders, ...layoutLoaders].map(([, file]) => file);
218
+ return { code, files: [...pages, ...loaderFiles, ...(guard ? [guard] : [])] };
176
219
  }
@@ -27,8 +27,10 @@ const relativeTo = (root, file) => (file.startsWith(`${root}/`) ? file.slice(roo
27
27
  export function serverFunctionEndpoint(root, file, name) {
28
28
  const rel = relativeTo(root, file);
29
29
  if (rel === null) throw new Error(`${file}: server modules must be inside the app directory (${root})`);
30
- const folder = rel.includes("/") ? `/${rel.slice(0, rel.lastIndexOf("/"))}` : "";
31
- return `${folder}/__fn/${fnv1a64(`${rel}#${name}`)}`;
30
+ // The URL of the folder: route groups (`(app)`) are not part of it. The hash keeps
31
+ // the full path, so two groups' modules never share an endpoint.
32
+ const folder = rel.includes("/") ? rel.slice(0, rel.lastIndexOf("/")).split("/").filter((s) => !/^\(.+\)$/.test(s)).join("/") : "";
33
+ return `${folder ? `/${folder}` : ""}/__fn/${fnv1a64(`${rel}#${name}`)}`;
32
34
  }
33
35
 
34
36
  /** Every `*.server` module under `dir`, sorted, skipping dot folders, node_modules and `exclude`. */
@@ -88,20 +90,23 @@ export function serverFunctionStub(root, file, exports) {
88
90
  * The server side: for each server module, its import and the endpoint table entries.
89
91
  * `listExports(file)` returns the module's exports (see `serverExports`).
90
92
  *
91
- * @returns {Promise<{ imports: string, table: string, files: string[] }>}
93
+ * @returns {Promise<{ imports: string, table: string, files: string[], endpoints: Array<[string, string]> }>}
92
94
  */
93
95
  export async function serverFunctionTable(host, root, { exclude = [], listExports }) {
94
96
  const files = await discoverServerModules(host, root, { exclude });
95
97
  const imports = [];
96
98
  const entries = [];
99
+ const endpoints = []; // [file, endpoint]
97
100
  for (const [i, file] of files.entries()) {
98
101
  const exports = await listExports(file);
99
102
  const fns = exports.filter((e) => e.kind);
100
103
  if (!fns.length) continue;
101
104
  imports.push(`import * as sf${i} from ${JSON.stringify(file)};`);
102
105
  for (const { name } of fns) {
103
- entries.push(` [${JSON.stringify(serverFunctionEndpoint(root, file, name))}]: sf${i}[${JSON.stringify(name)}],`);
106
+ const endpoint = serverFunctionEndpoint(root, file, name);
107
+ endpoints.push([file, endpoint]);
108
+ entries.push(` [${JSON.stringify(endpoint)}]: sf${i}[${JSON.stringify(name)}],`);
104
109
  }
105
110
  }
106
- return { imports: imports.join("\n"), table: entries.join("\n"), files };
111
+ return { imports: imports.join("\n"), table: entries.join("\n"), files, endpoints };
107
112
  }
package/server.js CHANGED
@@ -12,7 +12,7 @@
12
12
  // const response = await handle(request);
13
13
  // // middleware → API routes → loader data → files → page render → fallback
14
14
 
15
- import { discoverPages, routeKey } from "./routes.js";
15
+ import { discoverPages, loaderPageRoutes, routeKey } from "./routes.js";
16
16
  import { serverFunctionTable } from "./server-functions.js";
17
17
 
18
18
  /** The specifier a server entry imports. */
@@ -21,7 +21,9 @@ export const SERVER_ID = "@afw/server";
21
21
  const ROUTE_FILE = /^route\.(jsx?|tsx?)$/;
22
22
  const MIDDLEWARE_FILE = /^_middleware\.(jsx?|tsx?)$/;
23
23
  const LOADER_FILE = /^loader\.(js|ts)$/;
24
+ const LAYOUT_LOADER_FILE = /^layout\.loader\.(js|ts)$/;
24
25
  const PAGE_FILE = /^page\.(mdx|md|jsx|tsx)$/;
26
+ const LAYOUT_FILE = /^layout\.(mdx|md|jsx|tsx)$/;
25
27
 
26
28
  async function walk(host, dir, exclude, visitFile) {
27
29
  async function visit(abs, rel) {
@@ -60,22 +62,34 @@ async function walk(host, dir, exclude, visitFile) {
60
62
  * @returns {Promise<{ routes: string[], middleware: string[], loaders: string[], pages: Map<string, string> }>}
61
63
  */
62
64
  export async function discoverServerFiles(host, dir, { exclude = [] } = {}) {
63
- const routes = [], middleware = [], loaders = [];
65
+ const routes = [], middleware = [], loaders = [], layoutLoaders = [];
64
66
  const pages = new Map(); // folder (relative, "" for the root) → page file
67
+ const layouts = new Set(); // folders with a layout.*
65
68
  await walk(host, dir, new Set(exclude), (name, abs, folder) => {
66
69
  if (ROUTE_FILE.test(name)) routes.push(abs);
67
70
  else if (MIDDLEWARE_FILE.test(name)) middleware.push(abs);
68
71
  else if (LOADER_FILE.test(name)) loaders.push(abs);
72
+ else if (LAYOUT_LOADER_FILE.test(name)) layoutLoaders.push(abs);
69
73
  else if (PAGE_FILE.test(name)) pages.set(folder, abs);
74
+ else if (LAYOUT_FILE.test(name)) layouts.add(folder);
70
75
  });
71
- return { routes: routes.sort(), middleware: middleware.sort(), loaders: loaders.sort(), pages };
76
+ return { routes: routes.sort(), middleware: middleware.sort(), loaders: loaders.sort(), layoutLoaders: layoutLoaders.sort(), pages, layouts };
72
77
  }
73
78
 
74
79
  /** Whether the app has anything for a server to run. */
75
- export function hasServerFiles({ routes, middleware, loaders }) {
76
- return routes.length + middleware.length + loaders.length > 0;
80
+ export function hasServerFiles({ routes, middleware, loaders, layoutLoaders = [] }) {
81
+ return routes.length + middleware.length + loaders.length + layoutLoaders.length > 0;
77
82
  }
78
83
 
84
+ /** Is `segment` a route group, `(name)` (a folder that is not part of the URL)? */
85
+ const isGroupSegment = (segment) => /^\(.+\)$/.test(segment);
86
+
87
+ /** The URL a folder answers (`dashboard` → `/dashboard`, `(app)/x` → `/x`, "" → `/`). */
88
+ export const folderUrl = (folder) => `/${folder.split("/").filter((s) => s && !isGroupSegment(s)).join("/")}`;
89
+
90
+ /** Is `folder` the group folder `group`, or inside it? (Relative folders, "" = root.) */
91
+ const within = (group, folder) => group === "" || folder === group || folder.startsWith(`${group}/`);
92
+
79
93
  const folderOf = (host, dir, file) => {
80
94
  const parent = host.path.dirname(file);
81
95
  return parent === dir ? "" : parent.slice(dir.length + 1);
@@ -95,6 +109,15 @@ export function serverConflicts(host, dir, files) {
95
109
  problems.push(`a page and an API route answer /${folder}: ${files.pages.get(folder)} and ${route}. Move one to another folder.`);
96
110
  }
97
111
  }
112
+ // Route groups drop out of the URL, so files in different groups can answer the same one.
113
+ const byUrl = new Map();
114
+ const answers = [...[...files.pages].map(([folder, file]) => [folder, file]), ...files.routes.map((file) => [folderOf(host, dir, file), file])];
115
+ for (const [folder, file] of answers) {
116
+ const url = folderUrl(folder);
117
+ const other = byUrl.get(url);
118
+ if (other && other.folder !== folder) problems.push(`two routes answer ${url}: ${other.file} and ${file}. Move one to another path.`);
119
+ else byUrl.set(url, { folder, file });
120
+ }
98
121
  for (const loader of files.loaders) {
99
122
  const folder = folderOf(host, dir, loader);
100
123
  if (files.pages.has(folder)) continue;
@@ -103,6 +126,9 @@ export function serverConflicts(host, dir, files) {
103
126
  `${loader} ${beside ? "sits next to a route.* API endpoint (endpoints take a Request; loaders feed pages)" : "has no sibling page.* to feed"}.`,
104
127
  );
105
128
  }
129
+ for (const loader of files.layoutLoaders ?? []) {
130
+ if (!files.layouts?.has(folderOf(host, dir, loader))) problems.push(`${loader} has no sibling layout.* to feed.`);
131
+ }
106
132
  return problems;
107
133
  }
108
134
 
@@ -116,12 +142,14 @@ export function serverConflicts(host, dir, files) {
116
142
  * exports `render` (the render API static generation needs) and
117
143
  * `createPageRenderer({ shell, baseUrl })`, a `renderPage` step built on
118
144
  * `renderDocument`. `drafts: false` leaves unpublished Markdown pages out.
145
+ * `hydrate: false` serves rendered pages without the `data-afw-hydrate` marker, for a
146
+ * browser build that cannot adopt server DOM (one compiled with the `csr` target).
119
147
  *
120
148
  * @param {{ exclude?: string[], i18n?: { locales: string[], defaultLocale?: string } | null,
121
- * pages?: boolean, drafts?: boolean }} [options]
149
+ * pages?: boolean, drafts?: boolean, hydrate?: boolean }} [options]
122
150
  * @returns {Promise<{ code: string, files: string[] }>}
123
151
  */
124
- export async function serverModule(host, root, { exclude = [], i18n = null, pages = false, drafts = true, listExports } = {}) {
152
+ export async function serverModule(host, root, { exclude = [], i18n = null, pages = false, drafts = true, hydrate = true, listExports, clientFiles = new Set(), renders = null, staticPaths = [] } = {}) {
125
153
  const files = await discoverServerFiles(host, root, { exclude });
126
154
  const problems = serverConflicts(host, root, files);
127
155
  if (problems.length) throw new Error(`AFW server routes:\n ${problems.join("\n ")}`);
@@ -129,7 +157,9 @@ export async function serverModule(host, root, { exclude = [], i18n = null, page
129
157
  imports: list.map((p, i) => `import * as ${prefix}${i} from ${JSON.stringify(p)};`).join("\n"),
130
158
  map: list.map((p, i) => ` [${JSON.stringify(p)}]: ${prefix}${i},`).join("\n"),
131
159
  });
132
- const r = group(files.routes, "r"), m = group(files.middleware, "m"), l = group(files.loaders, "l");
160
+ const r = group(files.routes, "r"), m = group(files.middleware, "m"), l = group([...files.loaders, ...files.layoutLoaders], "l");
161
+ // Every page route, so a page beneath a layout.loader.* matches without a loader of its own.
162
+ const pageRoutes = [...files.pages.keys()].map((folder) => (folder ? `/${folder}` : "/")).sort();
133
163
  const options = { appDir: root };
134
164
  if (i18n && Array.isArray(i18n.locales) && i18n.locales.length) {
135
165
  options.i18n = { locales: i18n.locales, defaultLocale: i18n.defaultLocale ?? i18n.locales[0] };
@@ -137,26 +167,62 @@ export async function serverModule(host, root, { exclude = [], i18n = null, page
137
167
  const pageFiles = pages ? await discoverPages(host, root, { exclude, drafts }) : [];
138
168
  // Server functions (docs/SERVER_FUNCTIONS.md): `listExports(file)` asks the compiler
139
169
  // which exports of a `.server` module are query()/action().
140
- const fns = listExports ? await serverFunctionTable(host, root, { exclude, listExports }) : { imports: "", table: "", files: [] };
141
- const p = group(pageFiles, "p");
170
+ const fns = listExports ? await serverFunctionTable(host, root, { exclude, listExports }) : { imports: "", table: "", files: [], endpoints: [] };
171
+ // A middleware folder inside a route group covers what the group holds — its pages'
172
+ // and API routes' folders, and its server functions' endpoints — not a URL prefix.
173
+ const groupScopes = {};
174
+ for (const file of files.middleware) {
175
+ const folder = folderOf(host, root, file);
176
+ if (!folder.split("/").some(isGroupSegment)) continue;
177
+ const scopes = [...files.pages.keys(), ...files.routes.map((f) => folderOf(host, root, f))]
178
+ .filter((f) => within(folder, f)).map((f) => `/${f}`);
179
+ const paths = fns.endpoints.filter(([f]) => within(folder, folderOf(host, root, f))).map(([, endpoint]) => endpoint);
180
+ groupScopes[`/${folder}`] = { scopes: [...new Set(scopes)].sort(), paths: paths.sort() };
181
+ }
182
+ if (Object.keys(groupScopes).length) options.groupScopes = groupScopes;
183
+ // Route files that render in the browser stay out of the server bundle: they register
184
+ // as `clientRoute()` entries, and the server render leaves their region empty.
185
+ const serverPageFiles = pageFiles.filter((f) => !clientFiles.has(f));
186
+ const p = group(serverPageFiles, "p");
187
+ const registered = pageFiles.map((f) => {
188
+ const key = JSON.stringify(routeKey(f, root));
189
+ return clientFiles.has(f) ? ` [${key}]: clientRoute(),` : ` [${key}]: p${serverPageFiles.indexOf(f)},`;
190
+ });
142
191
  const renderPart = pages
143
- ? `import { collectRoutePaths, configureI18n, registerRoutes, renderHead, renderRoute, resolveMetadata } from "@opentf/afw/server";\n` +
192
+ ? `import { clientRoute, collectRoutePaths, configureI18n, matchRoute, registerRoutes, registerStaticPaths, renderHead, renderRoute, resolveMetadata } from "@opentf/afw/server";\n` +
193
+ staticPaths.map(([, file], i) => `import sp${i} from ${JSON.stringify(file)};\n`).join("") +
144
194
  `import { renderDocument, stampHydrateSentinel } from "@opentf/afw-build/document";\n` +
145
195
  (p.imports ? `${p.imports}\n` : "") +
146
196
  (options.i18n ? `configureI18n(options.i18n);\n` : "") +
147
- `registerRoutes({\n${pageFiles.map((f, i) => ` [${JSON.stringify(routeKey(f, root))}]: p${i},`).join("\n")}\n});\n` +
197
+ `registerRoutes({\n${registered.join("\n")}\n});\n` +
198
+ (staticPaths.length ? `registerStaticPaths({\n${staticPaths.map(([route], i) => ` [${JSON.stringify(route)}]: sp${i}.paths,`).join("\n")}\n});\n` : "") +
148
199
  `export const render = { renderRoute, renderHead, collectRoutePaths, resolveMetadata };\n` +
149
- `/** A \`renderPage\` step: server-render page requests (\`GET\`/\`HEAD\`) into \`shell\`, the client's index.html. */\n` +
150
- `export function createPageRenderer({ shell: html, baseUrl = "" }) {\n` +
151
- ` const shell = stampHydrateSentinel(html);\n` +
200
+ // Each route's resolved render policy (route pattern → strategy), for the response's
201
+ // `x-afw-render` header: what decided how this page was produced.
202
+ `const renders = ${JSON.stringify(renders ?? {})};\n` +
203
+ `/**\n` +
204
+ ` * A \`renderPage\` step: server-render page requests (\`GET\`/\`HEAD\`) into \`shell\`, the client's index.html.\n` +
205
+ ` * \`readStatic(pathname)\` returns the HTML the build prerendered for a static route (or null), which is\n` +
206
+ ` * served instead of rendering; a static route's unlisted page renders per request.\n` +
207
+ ` */\n` +
208
+ `export function createPageRenderer({ shell: html, baseUrl = "", readStatic = null }) {\n` +
209
+ // Without `hydrate` (a browser build compiled for `csr`) the page is still
210
+ // server-rendered, but not marked for adoption: the client builds it fresh.
211
+ ` const shell = ${hydrate ? "stampHydrateSentinel(html)" : "html"};\n` +
152
212
  ` return async (request, { locals = {} } = {}) => {\n` +
153
213
  ` const method = request.method.toUpperCase();\n` +
154
214
  ` if (method !== "GET" && method !== "HEAD") return null;\n` +
155
215
  ` const url = new URL(request.url);\n` +
216
+ ` if (readStatic && renders[matchRoute(url.pathname)?.route] === "static") {\n` +
217
+ ` const built = await readStatic(url.pathname);\n` +
218
+ ` if (built != null) return new Response(method === "HEAD" ? null : built, {\n` +
219
+ ` headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-cache", "x-afw-render": "static" },\n` +
220
+ ` });\n` +
221
+ ` }\n` +
156
222
  ` let doc;\n` +
157
223
  ` try {\n` +
158
224
  ` doc = await renderDocument(render, {\n` +
159
- ` shell, url: url.pathname, search: url.search, loaders, baseUrl, i18n: options.i18n ?? null,\n` +
225
+ ` shell, url: url.pathname, search: url.search, loaders, baseUrl, i18n: options.i18n ?? null, errors: "render",\n` +
160
226
  ` loaderContext: { request, query: Object.fromEntries(url.searchParams), locals },\n` +
161
227
  ` });\n` +
162
228
  ` } catch (e) {\n` +
@@ -165,7 +231,7 @@ export async function serverModule(host, root, { exclude = [], i18n = null, page
165
231
  ` }\n` +
166
232
  ` if (!doc) return null;\n` +
167
233
  ` return new Response(method === "HEAD" ? null : doc.html, {\n` +
168
- ` status: doc.status, headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-cache" },\n` +
234
+ ` status: doc.status, headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-cache", ...(renders[doc.route] ? { "x-afw-render": renders[doc.route] } : {}) },\n` +
169
235
  ` });\n` +
170
236
  ` };\n` +
171
237
  `}\n`
@@ -180,9 +246,13 @@ export async function serverModule(host, root, { exclude = [], i18n = null, page
180
246
  `export const apiHandler = createApiHandler(routeModules, middlewareModules, options);\n` +
181
247
  `export const apiRoutes = createApiHandler(routeModules, {}, options);\n` +
182
248
  `export const middleware = createMiddleware(middlewareModules, options);\n` +
183
- `export const loaders = createLoaderRegistry(loaderModules, options);\n` +
249
+ `export const loaders = createLoaderRegistry(loaderModules, { ...options, pageRoutes: ${JSON.stringify(pageRoutes)} });\n` +
184
250
  `export const serverFunctions = createServerFunctions({\n${fns.table}\n});\n` +
185
- `export const loaderRoutes = ${JSON.stringify(loaderRoutePatterns(host, root, files.loaders))};\n` +
251
+ `export const loaderRoutes = ${JSON.stringify(loaderPageRoutes({
252
+ pages: pageRoutes,
253
+ pageLoaders: loaderRoutePatterns(host, root, files.loaders),
254
+ layoutLoaders: loaderRoutePatterns(host, root, files.layoutLoaders),
255
+ }))};\n` +
186
256
  renderPart +
187
257
  `/**\n` +
188
258
  ` * A Fetch handler. Inside the middleware: API routes, loader data (\`<path>/__data.json\`),\n` +
@@ -200,7 +270,7 @@ export async function serverModule(host, root, { exclude = [], i18n = null, page
200
270
  ` };\n` +
201
271
  ` return createFetchHandler(terminal, { middleware, fallback });\n` +
202
272
  `}\n`;
203
- return { code, files: [...files.routes, ...files.middleware, ...files.loaders, ...pageFiles, ...fns.files] };
273
+ return { code, files: [...files.routes, ...files.middleware, ...files.loaders, ...files.layoutLoaders, ...serverPageFiles, ...fns.files] };
204
274
  }
205
275
 
206
276
  function loaderRoutePatterns(host, root, loaders) {