@k8ordo/framework 1.4.3 → 2.0.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/README.md +1 -1
- package/dist/generated.d.mts +23 -2
- package/dist/runtime/app-router.d.mts +10 -10
- package/dist/runtime/app-router.mjs +119 -83
- package/dist/runtime/browser-payloads.mjs +2 -1
- package/dist/runtime/client-files.d.mts +11 -0
- package/dist/runtime/client-files.mjs +42 -0
- package/dist/runtime/client-ready.d.mts +3 -2
- package/dist/runtime/document-root.mjs +1 -1
- package/dist/runtime/entry.browser.d.mts +1 -1
- package/dist/runtime/entry.browser.mjs +8 -12
- package/dist/runtime/entry.rsc.mjs +148 -102
- package/dist/runtime/entry.ssr.d.mts +21 -1
- package/dist/runtime/entry.ssr.mjs +10 -13
- package/dist/runtime/head-scripts.d.mts +18 -0
- package/dist/runtime/head-scripts.mjs +159 -0
- package/dist/runtime/hydrating-pathname.d.mts +16 -0
- package/dist/runtime/hydrating-pathname.mjs +26 -0
- package/dist/runtime/mount.d.mts +16 -11
- package/dist/runtime/mount.mjs +29 -18
- package/dist/runtime/payload.d.mts +22 -23
- package/dist/runtime/payload.mjs +11 -16
- package/dist/runtime/prefetch.d.mts +60 -25
- package/dist/runtime/prefetch.mjs +166 -38
- package/dist/runtime/recover.d.mts +2 -0
- package/dist/runtime/recover.mjs +11 -7
- package/dist/runtime/redirect.d.mts +20 -14
- package/dist/runtime/redirect.mjs +42 -15
- package/dist/runtime/request-scope.d.mts +1 -1
- package/dist/runtime/request-scope.mjs +11 -23
- package/dist/runtime/server.d.mts +6 -0
- package/dist/runtime/server.mjs +3 -0
- package/dist/runtime/stylesheets.d.mts +13 -0
- package/dist/runtime/stylesheets.mjs +15 -0
- package/dist/serve.d.mts +1 -0
- package/dist/serve.mjs +5 -11
- package/dist/{static-6z8_6B1U.d.mts → static-DnbgGIoy.d.mts} +2 -1
- package/dist/static-file-BAjwBMMl.mjs +1274 -0
- package/dist/{static-host-C6D_11Gp.mjs → static-host-B-1fAfAw.mjs} +49 -74
- package/dist/vercel.d.mts +1 -2
- package/dist/vercel.mjs +20 -20
- package/dist/vite.d.mts +1 -1
- package/dist/vite.mjs +232 -1469
- package/docs/GUIDE.md +6 -3
- package/docs/llms.txt +8 -4
- package/docs/references/csp.md +11 -9
- package/docs/references/deploy.md +17 -20
- package/docs/references/errors.md +0 -34
- package/docs/references/params.md +5 -5
- package/docs/references/routing.md +104 -20
- package/package.json +6 -6
- package/dist/runtime/redirect-file.d.mts +0 -20
- package/dist/runtime/redirect-file.mjs +0 -42
- package/dist/runtime/tree-pathname.d.mts +0 -2
- package/dist/runtime/tree-pathname.mjs +0 -11
- package/dist/server.d.mts +0 -110
- package/dist/server.mjs +0 -97
package/dist/vite.mjs
CHANGED
|
@@ -1,916 +1,29 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { A as slotOf, C as emitRegisterModule, D as ROUTE_METHODS, E as FRAMEWORK, O as fallbackShapes, S as LOCALES_MODULE, T as unreachableRoutes, _ as NOT_FOUND_HEADER, a as catchAllRefusals, b as FALLBACK_SEGMENT, d as planRefusals, f as routeFileRefusals, g as NONCE_HEADER, h as CLIENT_FILES_PATH, i as catchAllPath, k as parseRouteTree, l as patternsNeedingPaths, m as CLIENT_DEPS_HEADER, o as dirFor, p as shadowedShells, r as answersOf, s as fileAt, u as planPaths, v as SHELL_HEADER, w as emitRoutesModule, x as decodePathname, y as readClientDeps } from "./static-file-BAjwBMMl.mjs";
|
|
2
2
|
import { t as sharedDir } from "./shared-dir-CNXFRZgP.mjs";
|
|
3
|
-
import {
|
|
3
|
+
import { _ as isPayloadPath, a as cloudflareCounts, c as rewriteFor, d as shellRules, f as ENCODINGS, i as builtRules, l as rewritesAfterFiles, m as isCompressible, n as resolveStatic, o as cloudflareMatches, p as SUFFIX, r as PLACEHOLDER, s as formatRedirects, t as readRules, u as rulesOf, v as pagePathFor, y as payloadPathFor } from "./static-host-B-1fAfAw.mjs";
|
|
4
|
+
import { findPackageJSON } from "node:module";
|
|
4
5
|
import { normalizePathname, withBase, withoutBase } from "@k8ordo/router";
|
|
5
6
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
6
7
|
import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
|
|
7
8
|
import path from "node:path";
|
|
8
9
|
import { build, parseSync } from "vite";
|
|
10
|
+
import { existsSync } from "node:fs";
|
|
9
11
|
import react from "@vitejs/plugin-react";
|
|
10
12
|
import rsc, { getPluginApi } from "@vitejs/plugin-rsc";
|
|
11
13
|
import { promisify } from "node:util";
|
|
12
14
|
import { brotliCompress, constants, gzip } from "node:zlib";
|
|
13
15
|
import { contentType, lookup } from "mime-types";
|
|
14
16
|
import { createHash } from "node:crypto";
|
|
15
|
-
// ../framework-engine/dist/
|
|
16
|
-
const CONVENTION = {
|
|
17
|
-
"page.tsx": "page",
|
|
18
|
-
"layout.tsx": "layout",
|
|
19
|
-
"not-found.tsx": "notFound",
|
|
20
|
-
"error.tsx": "error",
|
|
21
|
-
"redirect.ts": "redirect",
|
|
22
|
-
"guard.ts": "guard",
|
|
23
|
-
"route.ts": "route",
|
|
24
|
-
"loading.tsx": "loading",
|
|
25
|
-
"fallback.tsx": "fallback"
|
|
26
|
-
};
|
|
27
|
-
const ROUTE_FILES = Object.keys(CONVENTION).join(", ");
|
|
28
|
-
const PARAM = /^\[([A-Za-z_][A-Za-z0-9_]*)\]$/u;
|
|
29
|
-
const GROUP = /^\(([A-Za-z0-9_-]+)\)$/u;
|
|
30
|
-
const LITERAL = /^[A-Za-z0-9._~-]+$/u;
|
|
31
|
-
/**
|
|
32
|
-
* A dotfile belongs to the system or an editor (`.DS_Store`, a swap file), not
|
|
33
|
-
* to the application, so a stray one must not break the build.
|
|
34
|
-
*/
|
|
35
|
-
const isHidden = (segment) => segment.startsWith(".");
|
|
36
|
-
/**
|
|
37
|
-
* Which slot a file fills, by its path relative to the routes root — `null`
|
|
38
|
-
* for anything the grammar does not read: a hidden file, or a name outside
|
|
39
|
-
* the convention (which the parse reports). One module at a time, for a
|
|
40
|
-
* caller that is handed a module rather than the tree (a dev server's
|
|
41
|
-
* transform).
|
|
42
|
-
*/
|
|
43
|
-
const slotOf = (file) => {
|
|
44
|
-
const segments = file.split("/").filter((segment) => segment !== "");
|
|
45
|
-
if (segments.some((segment) => isHidden(segment))) return null;
|
|
46
|
-
const basename = segments.at(-1);
|
|
47
|
-
if (basename === void 0) return null;
|
|
48
|
-
return CONVENTION[basename] ?? null;
|
|
49
|
-
};
|
|
50
|
-
const emptyDir = () => ({
|
|
51
|
-
files: /* @__PURE__ */ new Map(),
|
|
52
|
-
dirs: /* @__PURE__ */ new Map()
|
|
53
|
-
});
|
|
54
|
-
const build$1 = (files) => {
|
|
55
|
-
const root = emptyDir();
|
|
56
|
-
for (const file of files) {
|
|
57
|
-
const segments = file.split("/").filter((segment) => segment !== "");
|
|
58
|
-
const basename = segments.pop();
|
|
59
|
-
if (basename === void 0 || isHidden(basename)) continue;
|
|
60
|
-
if (segments.some((segment) => isHidden(segment))) continue;
|
|
61
|
-
let current = root;
|
|
62
|
-
for (const segment of segments) {
|
|
63
|
-
let next = current.dirs.get(segment);
|
|
64
|
-
if (next === void 0) {
|
|
65
|
-
next = emptyDir();
|
|
66
|
-
current.dirs.set(segment, next);
|
|
67
|
-
}
|
|
68
|
-
current = next;
|
|
69
|
-
}
|
|
70
|
-
current.files.set(basename, file);
|
|
71
|
-
}
|
|
72
|
-
return root;
|
|
73
|
-
};
|
|
74
|
-
const classify = (name, path, problems) => {
|
|
75
|
-
const param = PARAM.exec(name);
|
|
76
|
-
if (param !== null) return {
|
|
77
|
-
kind: "param",
|
|
78
|
-
key: `/:${param[1]}`,
|
|
79
|
-
param: param[1]
|
|
80
|
-
};
|
|
81
|
-
if (GROUP.exec(name) !== null) return {
|
|
82
|
-
kind: "group",
|
|
83
|
-
key: `/${name}`,
|
|
84
|
-
param: null
|
|
85
|
-
};
|
|
86
|
-
if (name.startsWith("[") || name.endsWith("]")) problems.push({
|
|
87
|
-
path,
|
|
88
|
-
message: `"${name}" is not a valid param directory — use [name] with a letter or underscore first`
|
|
89
|
-
});
|
|
90
|
-
else if (name.startsWith("(") || name.endsWith(")")) problems.push({
|
|
91
|
-
path,
|
|
92
|
-
message: `"${name}" is not a valid route group — use (name)`
|
|
93
|
-
});
|
|
94
|
-
else if (!LITERAL.test(name)) problems.push({
|
|
95
|
-
path,
|
|
96
|
-
message: `"${name}" cannot be a URL segment — use letters, digits, . _ ~ or -`
|
|
97
|
-
});
|
|
98
|
-
return {
|
|
99
|
-
kind: "literal",
|
|
100
|
-
key: `/${name}`,
|
|
101
|
-
param: null
|
|
102
|
-
};
|
|
103
|
-
};
|
|
104
|
-
const convert = (raw, name, path, kind, key, problems) => {
|
|
105
|
-
const slots = {};
|
|
106
|
-
for (const [basename, file] of raw.files) {
|
|
107
|
-
const slot = CONVENTION[basename];
|
|
108
|
-
if (slot === void 0) {
|
|
109
|
-
problems.push({
|
|
110
|
-
path: file,
|
|
111
|
-
message: `routes/ holds only ${ROUTE_FILES} — move "${basename}" out of routes/`
|
|
112
|
-
});
|
|
113
|
-
continue;
|
|
114
|
-
}
|
|
115
|
-
slots[slot] = file;
|
|
116
|
-
}
|
|
117
|
-
const here = path === "" ? "/" : path;
|
|
118
|
-
if (slots.page !== void 0 && slots.redirect !== void 0) problems.push({
|
|
119
|
-
path: slots.redirect,
|
|
120
|
-
message: `"${here}" cannot both render page.tsx and redirect — keep one`
|
|
121
|
-
});
|
|
122
|
-
if (slots.route !== void 0 && slots.page !== void 0) problems.push({
|
|
123
|
-
path: slots.route,
|
|
124
|
-
message: `"${here}" cannot both render page.tsx and answer from route.ts — keep one`
|
|
125
|
-
});
|
|
126
|
-
if (slots.route !== void 0 && slots.redirect !== void 0) problems.push({
|
|
127
|
-
path: slots.route,
|
|
128
|
-
message: `"${here}" cannot both redirect and answer from route.ts — keep one`
|
|
129
|
-
});
|
|
130
|
-
const children = [...raw.dirs.entries()].map(([childName, childRaw]) => {
|
|
131
|
-
const childPath = path === "" ? childName : `${path}/${childName}`;
|
|
132
|
-
const classified = classify(childName, childPath, problems);
|
|
133
|
-
return convert(childRaw, childName, childPath, classified.kind, classified.key, problems);
|
|
134
|
-
});
|
|
135
|
-
return {
|
|
136
|
-
name,
|
|
137
|
-
kind,
|
|
138
|
-
key,
|
|
139
|
-
path,
|
|
140
|
-
page: slots.page ?? null,
|
|
141
|
-
layout: slots.layout ?? null,
|
|
142
|
-
notFound: slots.notFound ?? null,
|
|
143
|
-
error: slots.error ?? null,
|
|
144
|
-
loading: slots.loading ?? null,
|
|
145
|
-
redirect: slots.redirect ?? null,
|
|
146
|
-
guard: slots.guard ?? null,
|
|
147
|
-
route: slots.route ?? null,
|
|
148
|
-
fallback: slots.fallback ?? null,
|
|
149
|
-
children
|
|
150
|
-
};
|
|
151
|
-
};
|
|
152
|
-
const declaresRoute = (dir) => dir.page !== null || dir.route !== null || dir.notFound !== null || dir.redirect !== null || dir.children.some(declaresRoute);
|
|
153
|
-
/**
|
|
154
|
-
* Walks the tree the way the router's own table walk does, so the patterns
|
|
155
|
-
* checked here are the patterns that will exist at runtime.
|
|
156
|
-
*/
|
|
157
|
-
const eachPattern = (dir, prefix, visit) => {
|
|
158
|
-
const here = dir.kind === "root" ? "" : prefix;
|
|
159
|
-
if (dir.page !== null) visit(here === "" ? "/" : here, dir.page);
|
|
160
|
-
if (dir.route !== null && dir.page === null) visit(here === "" ? "/" : here, dir.route);
|
|
161
|
-
if (dir.redirect !== null && dir.page === null && dir.route === null) visit(here === "" ? "/" : here, dir.redirect);
|
|
162
|
-
if (dir.notFound !== null) visit(`${here}/*`, dir.notFound);
|
|
163
|
-
for (const child of dir.children) {
|
|
164
|
-
const next = child.kind === "group" ? here : `${here}${child.key}`;
|
|
165
|
-
eachPattern(child, next, visit);
|
|
166
|
-
}
|
|
167
|
-
};
|
|
168
|
-
const checkFallback = (dir, file, pattern, params, above) => {
|
|
169
|
-
const here = dir.path === "" ? "/" : dir.path;
|
|
170
|
-
const refuse = (message) => ({ problem: {
|
|
171
|
-
path: file,
|
|
172
|
-
message
|
|
173
|
-
} });
|
|
174
|
-
if (dir.page === null) return refuse(`fallback.tsx stands in for the page.tsx beside it, and "${here}" has none`);
|
|
175
|
-
if (dir.layout !== null) return refuse(`fallback.tsx cannot sit beside layout.tsx — that layout receives every parameter of "${here}", so no shell could leave one to the browser; move the layout one directory up, or into page.tsx and fallback.tsx`);
|
|
176
|
-
if (params.length === 0) return refuse(`fallback.tsx stands in for values the build did not write, and "${pattern}" has no parameter; remove it`);
|
|
177
|
-
const open = params.filter((name) => !(above?.params ?? []).includes(name));
|
|
178
|
-
if (open.length === 0 && above !== null) return refuse(`fallback.tsx has nothing to leave to the browser — ${above.file} receives every parameter of "${pattern}"; remove fallback.tsx and list the values in paths`);
|
|
179
|
-
return { shape: {
|
|
180
|
-
pattern,
|
|
181
|
-
file,
|
|
182
|
-
page: dir.page,
|
|
183
|
-
params,
|
|
184
|
-
open,
|
|
185
|
-
layout: above?.file ?? null
|
|
186
|
-
} };
|
|
187
|
-
};
|
|
188
|
-
/**
|
|
189
|
-
* Every `fallback.tsx` the directories hold, as a shape or as the problem
|
|
190
|
-
* that refuses it — one walk, so the grammar, the generated table and the
|
|
191
|
-
* static build never disagree about which params a shell may leave open.
|
|
192
|
-
* A directory that declares no route is skipped with everything below it:
|
|
193
|
-
* that problem is reported on its own.
|
|
194
|
-
*/
|
|
195
|
-
const checkFallbacks = (tree) => {
|
|
196
|
-
const found = [];
|
|
197
|
-
const walk = (dir, prefix, inherited, above) => {
|
|
198
|
-
if (!declaresRoute(dir)) return;
|
|
199
|
-
const here = dir.kind === "root" ? "" : prefix;
|
|
200
|
-
const params = dir.kind === "param" ? [...inherited, dir.key.slice(2)] : inherited;
|
|
201
|
-
if (dir.fallback !== null) found.push(checkFallback(dir, dir.fallback, here === "" ? "/" : here, params, above));
|
|
202
|
-
const below = dir.layout === null ? above : {
|
|
203
|
-
file: dir.layout,
|
|
204
|
-
params
|
|
205
|
-
};
|
|
206
|
-
for (const child of dir.children) walk(child, child.kind === "group" ? here : `${here}${child.key}`, params, below);
|
|
207
|
-
};
|
|
208
|
-
walk(tree, "", [], null);
|
|
209
|
-
return found;
|
|
210
|
-
};
|
|
211
|
-
/**
|
|
212
|
-
* The page patterns with a `fallback.tsx` beside them that the grammar
|
|
213
|
-
* accepts, with the params a shell may leave to the browser — those no layout
|
|
214
|
-
* above the fallback receives.
|
|
215
|
-
*/
|
|
216
|
-
const fallbackShapes = (tree) => checkFallbacks(tree).flatMap((each) => each.shape === void 0 ? [] : [each.shape]);
|
|
217
|
-
const validate = (root, problems) => {
|
|
218
|
-
const walk = (dir, inherited) => {
|
|
219
|
-
let params = inherited;
|
|
220
|
-
if (dir.kind === "param") {
|
|
221
|
-
const name = dir.key.slice(2);
|
|
222
|
-
if (params.includes(name)) problems.push({
|
|
223
|
-
path: dir.path,
|
|
224
|
-
message: `":${name}" is already taken by an ancestor — params must be unique within a path`
|
|
225
|
-
});
|
|
226
|
-
params = [...params, name];
|
|
227
|
-
}
|
|
228
|
-
if (!declaresRoute(dir)) {
|
|
229
|
-
problems.push({
|
|
230
|
-
path: dir.path === "" ? "." : dir.path,
|
|
231
|
-
message: dir.layout === null ? "declares no route — every directory needs a page.tsx (or a redirect.ts or route.ts) somewhere below it" : "has a layout but no page.tsx below it, so it can never render"
|
|
232
|
-
});
|
|
233
|
-
return;
|
|
234
|
-
}
|
|
235
|
-
for (const child of dir.children) walk(child, params);
|
|
236
|
-
};
|
|
237
|
-
walk(root, []);
|
|
238
|
-
for (const each of checkFallbacks(root)) if (each.problem !== void 0) problems.push(each.problem);
|
|
239
|
-
const owners = /* @__PURE__ */ new Map();
|
|
240
|
-
eachPattern(root, "", (pattern, file) => {
|
|
241
|
-
const first = owners.get(pattern);
|
|
242
|
-
if (first === void 0) {
|
|
243
|
-
owners.set(pattern, file);
|
|
244
|
-
return;
|
|
245
|
-
}
|
|
246
|
-
problems.push({
|
|
247
|
-
path: file,
|
|
248
|
-
message: `"${pattern}" is already declared by ${first} — route groups do not separate URLs`
|
|
249
|
-
});
|
|
250
|
-
});
|
|
251
|
-
};
|
|
252
|
-
/**
|
|
253
|
-
* @param files paths relative to the routes root, POSIX separators.
|
|
254
|
-
*/
|
|
255
|
-
const parseRouteTree = (files) => {
|
|
256
|
-
const problems = [];
|
|
257
|
-
const tree = convert(build$1(files), "", "", "root", "/", problems);
|
|
258
|
-
validate(tree, problems);
|
|
259
|
-
return {
|
|
260
|
-
tree,
|
|
261
|
-
problems
|
|
262
|
-
};
|
|
263
|
-
};
|
|
264
|
-
// ../framework-engine/dist/runtime/route.mjs
|
|
265
|
-
/** The request methods a `route.ts` answers by exporting a function named so. */
|
|
266
|
-
const ROUTE_METHODS = [
|
|
267
|
-
"GET",
|
|
268
|
-
"HEAD",
|
|
269
|
-
"POST",
|
|
270
|
-
"PUT",
|
|
271
|
-
"PATCH",
|
|
272
|
-
"DELETE",
|
|
273
|
-
"OPTIONS"
|
|
274
|
-
];
|
|
275
|
-
// ../framework-engine/dist/host.mjs
|
|
276
|
-
/**
|
|
277
|
-
* The package the application actually installed. This engine is bundled
|
|
278
|
-
* into it rather than published on its own, so it is the only name
|
|
279
|
-
* resolvable from the project root: anything the optimizer is asked to
|
|
280
|
-
* prebundle is addressed through it, and the generated files name it.
|
|
281
|
-
*/
|
|
282
|
-
const FRAMEWORK = "@k8ordo/framework";
|
|
283
|
-
// ../framework-engine/dist/generate/emit.mjs
|
|
284
|
-
/** What answers a directory's own URL: its page, or its route.ts. */
|
|
285
|
-
const ownFile = (dir) => dir.page ?? dir.route;
|
|
286
|
-
/**
|
|
287
|
-
* What holds a directory's own place in the table. A redirect.ts renders
|
|
288
|
-
* nothing and is not what a guard or a schema answers for, but it matches in
|
|
289
|
-
* declaration order with the pages, literals before params, as they do.
|
|
290
|
-
*/
|
|
291
|
-
const placeOf = (dir) => ownFile(dir) ?? dir.redirect;
|
|
292
|
-
/**
|
|
293
|
-
* A directory with nothing but a page (or a route.ts, or a redirect.ts) is
|
|
294
|
-
* that, itself — except a group: it adds no segment, so the router refuses it
|
|
295
|
-
* as a leaf (it would redeclare its parent's index) and takes it only as a
|
|
296
|
-
* branch.
|
|
297
|
-
*/
|
|
298
|
-
const isLeaf = (dir) => dir.kind !== "group" && placeOf(dir) !== null && dir.layout === null && dir.error === null && dir.loading === null && dir.notFound === null && dir.children.length === 0;
|
|
299
|
-
/**
|
|
300
|
-
* What a subtree offers the matcher first: a literal, a parameter, or only a
|
|
301
|
-
* catch-all. A group contributes its children's URLs rather than one of its
|
|
302
|
-
* own, so it ranks as whatever the best of them is — otherwise a `[slug]`
|
|
303
|
-
* tucked inside a group would still be tried before a literal sibling.
|
|
304
|
-
*/
|
|
305
|
-
const rank = (dir) => {
|
|
306
|
-
if (dir.kind === "param") return 1;
|
|
307
|
-
if (dir.kind !== "group") return 0;
|
|
308
|
-
const children = dir.children.map(rank);
|
|
309
|
-
if (dir.page !== null) children.push(0);
|
|
310
|
-
if (dir.notFound !== null) children.push(2);
|
|
311
|
-
return Math.min(...children, 2);
|
|
312
|
-
};
|
|
313
|
-
/**
|
|
314
|
-
* Literal segments before parameters, and otherwise the order the directories
|
|
315
|
-
* came in. The table matches in declaration order, and the directories arrive
|
|
316
|
-
* sorted by name — under which `[slug]` precedes `about`, because `[` sorts
|
|
317
|
-
* before letters. Left alone, the most ordinary layout there is would make
|
|
318
|
-
* `/about` unreachable behind `/:slug`.
|
|
319
|
-
*
|
|
320
|
-
* A directory tree has no order of its own to honour, so the framework has to
|
|
321
|
-
* choose one; this is the only choice that makes every declared route
|
|
322
|
-
* reachable. Where it still cannot — a group holding both kinds — the
|
|
323
|
-
* unreachable route is reported rather than shipped.
|
|
324
|
-
*/
|
|
325
|
-
const order = (children) => children.toSorted((a, b) => rank(a) - rank(b));
|
|
326
|
-
const buildTable = (tree, resolve) => {
|
|
327
|
-
const entries = (dir) => {
|
|
328
|
-
const record = {};
|
|
329
|
-
const own = placeOf(dir);
|
|
330
|
-
if (own !== null) record["/"] = resolve(own);
|
|
331
|
-
for (const child of order(dir.children)) record[child.key] = node(child);
|
|
332
|
-
if (dir.notFound !== null) record["/*"] = resolve(dir.notFound);
|
|
333
|
-
return record;
|
|
334
|
-
};
|
|
335
|
-
const node = (dir) => {
|
|
336
|
-
if (isLeaf(dir)) return resolve(placeOf(dir));
|
|
337
|
-
const branch = { children: entries(dir) };
|
|
338
|
-
if (dir.layout !== null) branch.layout = resolve(dir.layout);
|
|
339
|
-
if (dir.error !== null) branch.error = resolve(dir.error);
|
|
340
|
-
if (dir.loading !== null) branch.loading = resolve(dir.loading);
|
|
341
|
-
return branch;
|
|
342
|
-
};
|
|
343
|
-
return tree.layout === null && tree.error === null && tree.loading === null ? entries(tree) : { "/": node(tree) };
|
|
344
|
-
};
|
|
345
|
-
/**
|
|
346
|
-
* Every pattern the directories declare, in the order the matcher will try
|
|
347
|
-
* them — the one walk every consumer of "which URLs does this site have"
|
|
348
|
-
* shares, so the build, the shadow check and the prerenderer never disagree
|
|
349
|
-
* about the order.
|
|
350
|
-
*/
|
|
351
|
-
const declaredPatterns = (dir, prefix = "") => {
|
|
352
|
-
const here = dir.kind === "root" ? "" : prefix;
|
|
353
|
-
const own = here === "" ? "/" : here;
|
|
354
|
-
const found = [];
|
|
355
|
-
if (dir.page !== null) found.push({
|
|
356
|
-
pattern: own,
|
|
357
|
-
file: dir.page,
|
|
358
|
-
kind: "page"
|
|
359
|
-
});
|
|
360
|
-
else if (dir.route !== null) found.push({
|
|
361
|
-
pattern: own,
|
|
362
|
-
file: dir.route,
|
|
363
|
-
kind: "route"
|
|
364
|
-
});
|
|
365
|
-
else if (dir.redirect !== null) found.push({
|
|
366
|
-
pattern: own,
|
|
367
|
-
file: dir.redirect,
|
|
368
|
-
kind: "redirect"
|
|
369
|
-
});
|
|
370
|
-
for (const child of order(dir.children)) found.push(...declaredPatterns(child, child.kind === "group" ? here : `${here}${child.key}`));
|
|
371
|
-
if (dir.notFound !== null) found.push({
|
|
372
|
-
pattern: `${here}/*`,
|
|
373
|
-
file: dir.notFound,
|
|
374
|
-
kind: "notFound"
|
|
375
|
-
});
|
|
376
|
-
return found;
|
|
377
|
-
};
|
|
378
|
-
const declared = declaredPatterns;
|
|
379
|
-
/** Every `redirect.ts`, with the pattern its directory puts it under. */
|
|
380
|
-
const declaredRedirects = (dir) => declaredPatterns(dir).filter((each) => each.kind === "redirect");
|
|
381
|
-
/** Every `route.ts`, with the pattern its directory puts it under. */
|
|
382
|
-
const declaredRouteFiles = (dir) => declaredPatterns(dir).filter((each) => each.kind === "route");
|
|
383
|
-
/**
|
|
384
|
-
* Routes that exist and can never render, because something declared earlier
|
|
385
|
-
* answers their URL. Ordering fixes the common shape — a literal beside a
|
|
386
|
-
* parameter — but a group holds URLs of both kinds under one key, and a table
|
|
387
|
-
* cannot interleave across it. Where the order cannot be made right, saying so
|
|
388
|
-
* is the only honest option left: the alternative is a page that is simply
|
|
389
|
-
* never served, with nothing to see in the directory tree.
|
|
390
|
-
*/
|
|
391
|
-
const unreachableRoutes = (tree) => {
|
|
392
|
-
const all = declared(tree);
|
|
393
|
-
const problems = [];
|
|
394
|
-
for (const [index, route] of all.entries()) {
|
|
395
|
-
if (route.pattern.includes(":") || route.pattern.includes("*")) continue;
|
|
396
|
-
const shadow = all.slice(0, index).find((earlier) => earlier.pattern !== route.pattern && new URLPattern({ pathname: earlier.pattern }).test({ pathname: route.pattern }));
|
|
397
|
-
if (shadow === void 0) continue;
|
|
398
|
-
problems.push({
|
|
399
|
-
path: route.file,
|
|
400
|
-
message: `"${route.pattern}" can never match — "${shadow.pattern}" (${shadow.file}) is declared first and answers it`
|
|
401
|
-
});
|
|
402
|
-
}
|
|
403
|
-
return problems;
|
|
404
|
-
};
|
|
405
|
-
/** What holds a route.ts's or a redirect.ts's place in the table. */
|
|
406
|
-
const ANSWERED = "answered";
|
|
407
|
-
/**
|
|
408
|
-
* What the generated files import from the router, through the framework:
|
|
409
|
-
* the application installs the router, but only ever names the framework.
|
|
410
|
-
*/
|
|
411
|
-
const GENERATED_FROM = `${FRAMEWORK}/generated`;
|
|
412
|
-
const ROUTE_REQUEST_FROM = `${FRAMEWORK}/server`;
|
|
413
|
-
const I18N = "@k8ordo/i18n";
|
|
414
|
-
/** Where an application declares its locale set, from its root. */
|
|
415
|
-
const LOCALES_MODULE = "src/i18n.ts";
|
|
416
|
-
const bannerFrom = (...sources) => `// Generated by ${FRAMEWORK} from ${sources.join(" and ")}. Do not edit.`;
|
|
417
|
-
const sanitize = (path) => {
|
|
418
|
-
const base = path.replace(/\.[jt]sx?$/u, "").replaceAll(/[^A-Za-z0-9]+/gu, "_").replaceAll(/^_+|_+$/gu, "");
|
|
419
|
-
return base === "" ? "route" : base;
|
|
420
|
-
};
|
|
421
|
-
const createNamer = () => {
|
|
422
|
-
const names = /* @__PURE__ */ new Map();
|
|
423
|
-
const used = /* @__PURE__ */ new Set();
|
|
424
|
-
return {
|
|
425
|
-
names,
|
|
426
|
-
take: (file) => {
|
|
427
|
-
const existing = names.get(file);
|
|
428
|
-
if (existing !== void 0) return existing;
|
|
429
|
-
const base = sanitize(file);
|
|
430
|
-
let name = base;
|
|
431
|
-
for (let n = 2; used.has(name); n += 1) name = `${base}_${n}`;
|
|
432
|
-
used.add(name);
|
|
433
|
-
names.set(file, name);
|
|
434
|
-
return name;
|
|
435
|
-
}
|
|
436
|
-
};
|
|
437
|
-
};
|
|
438
|
-
const pad = (depth) => " ".repeat(depth);
|
|
439
|
-
const isBranch = (node) => typeof node !== "string";
|
|
440
|
-
const renderNode = (node, depth, asserted) => {
|
|
441
|
-
if (!isBranch(node)) return believed(node, asserted);
|
|
442
|
-
const lines = ["{"];
|
|
443
|
-
if (node.layout !== void 0) lines.push(`${pad(depth + 1)}layout: ${believed(node.layout, asserted)},`);
|
|
444
|
-
if (node.error !== void 0) lines.push(`${pad(depth + 1)}error: ${believed(node.error, asserted)},`);
|
|
445
|
-
if (node.loading !== void 0) lines.push(`${pad(depth + 1)}loading: ${believed(node.loading, asserted)},`);
|
|
446
|
-
lines.push(`${pad(depth + 1)}children: {`);
|
|
447
|
-
for (const [key, child] of Object.entries(node.children)) lines.push(`${pad(depth + 2)}'${key}': ${renderNode(child, depth + 2, asserted)},`);
|
|
448
|
-
lines.push(`${pad(depth + 1)}},`, `${pad(depth)}}`);
|
|
449
|
-
return lines.join("\n");
|
|
450
|
-
};
|
|
451
|
-
const believed = (name, asserted) => {
|
|
452
|
-
const type = asserted.get(name);
|
|
453
|
-
return type === void 0 ? name : `${name} satisfies ${type}`;
|
|
454
|
-
};
|
|
455
|
-
/**
|
|
456
|
-
* What each route file is promised, by the pattern the directories put it
|
|
457
|
-
* under: a page's own pattern, and for a layout the prefix every route below
|
|
458
|
-
* it shares. Keyed by file, so the emitter can state the belief where the
|
|
459
|
-
* component is used and let the compiler check the props the file declared —
|
|
460
|
-
* the alternative is asking every route file to restate a pattern its own
|
|
461
|
-
* directory already states.
|
|
462
|
-
*
|
|
463
|
-
* A page's belief also carries the `paramsSchema` exports that run before it
|
|
464
|
-
* renders: every layout's above it that declared one, then its own. A
|
|
465
|
-
* not-found's carries the layouts' above it, which run for what they write to
|
|
466
|
-
* the render's context and never refuse it — a catch-all answers what nothing
|
|
467
|
-
* else did, so its params stay strings. A fallback's carries the layouts'
|
|
468
|
-
* above it too: a shell runs them over the params it fills, and its page's
|
|
469
|
-
* own never, since a shell has no value.
|
|
470
|
-
*/
|
|
471
|
-
const beliefs = (tree, withParams) => {
|
|
472
|
-
const found = /* @__PURE__ */ new Map();
|
|
473
|
-
const walk = (dir, prefix, inherited) => {
|
|
474
|
-
const here = dir.kind === "root" ? "" : prefix;
|
|
475
|
-
const own = here === "" ? "/" : here;
|
|
476
|
-
const layoutSchemas = dir.layout !== null && withParams.has(dir.layout) ? [...inherited, dir.layout] : inherited;
|
|
477
|
-
if (dir.layout !== null) found.set(dir.layout, {
|
|
478
|
-
pattern: own,
|
|
479
|
-
kind: "layout",
|
|
480
|
-
schemas: layoutSchemas
|
|
481
|
-
});
|
|
482
|
-
const answers = ownFile(dir);
|
|
483
|
-
if (answers !== null) found.set(answers, {
|
|
484
|
-
pattern: own,
|
|
485
|
-
kind: dir.page === null ? "route" : "page",
|
|
486
|
-
schemas: withParams.has(answers) ? [...layoutSchemas, answers] : layoutSchemas
|
|
487
|
-
});
|
|
488
|
-
if (dir.notFound !== null) found.set(dir.notFound, {
|
|
489
|
-
pattern: `${here}/*`,
|
|
490
|
-
kind: "notFound",
|
|
491
|
-
schemas: layoutSchemas
|
|
492
|
-
});
|
|
493
|
-
if (dir.error !== null) found.set(dir.error, {
|
|
494
|
-
pattern: own,
|
|
495
|
-
kind: "error",
|
|
496
|
-
schemas: []
|
|
497
|
-
});
|
|
498
|
-
if (dir.loading !== null) found.set(dir.loading, {
|
|
499
|
-
pattern: own,
|
|
500
|
-
kind: "loading",
|
|
501
|
-
schemas: []
|
|
502
|
-
});
|
|
503
|
-
if (dir.fallback !== null) found.set(dir.fallback, {
|
|
504
|
-
pattern: own,
|
|
505
|
-
kind: "fallback",
|
|
506
|
-
schemas: layoutSchemas
|
|
507
|
-
});
|
|
508
|
-
for (const child of dir.children) walk(child, child.kind === "group" ? here : `${here}${child.key}`, layoutSchemas);
|
|
509
|
-
};
|
|
510
|
-
walk(tree, "", []);
|
|
511
|
-
return found;
|
|
512
|
-
};
|
|
513
|
-
const schemaName = (componentName) => `${componentName}_params`;
|
|
514
|
-
/**
|
|
515
|
-
* The guards along each pattern's directories. A redirect is left out: it
|
|
516
|
-
* answers before any guard runs, since the URL it answers has no page to
|
|
517
|
-
* guard (the pages below its directory are guarded as usual). `/*` always
|
|
518
|
-
* carries the root's — a URL nothing answers is
|
|
519
|
-
* still below the root, and the framework's own 404 is answered under them.
|
|
520
|
-
*/
|
|
521
|
-
const guardsOf = (tree) => {
|
|
522
|
-
const stacks = /* @__PURE__ */ new Map();
|
|
523
|
-
const own = /* @__PURE__ */ new Map();
|
|
524
|
-
const walk = (dir, prefix, inherited) => {
|
|
525
|
-
const here = dir.kind === "root" ? "" : prefix;
|
|
526
|
-
const pattern = here === "" ? "/" : here;
|
|
527
|
-
const stack = dir.guard === null ? inherited : [...inherited, dir.guard];
|
|
528
|
-
if (dir.guard !== null) own.set(dir.guard, pattern);
|
|
529
|
-
if (stack.length > 0) {
|
|
530
|
-
if (ownFile(dir) !== null) stacks.set(pattern, stack);
|
|
531
|
-
if (dir.notFound !== null) stacks.set(`${here}/*`, stack);
|
|
532
|
-
}
|
|
533
|
-
for (const child of dir.children) walk(child, child.kind === "group" ? here : `${here}${child.key}`, stack);
|
|
534
|
-
};
|
|
535
|
-
walk(tree, "", []);
|
|
536
|
-
if (tree.guard !== null && !stacks.has("/*")) stacks.set("/*", [tree.guard]);
|
|
537
|
-
return {
|
|
538
|
-
stacks,
|
|
539
|
-
own
|
|
540
|
-
};
|
|
541
|
-
};
|
|
542
|
-
/**
|
|
543
|
-
* The slots a request reaches one file at a time: the page or the not-found
|
|
544
|
-
* that answers it, a route.ts, a page's shell. The table reads each of them
|
|
545
|
-
* when a request reaches it — imported with the table, it would be in the
|
|
546
|
-
* handler's own chunk, and what it renders in the browser and the CSS it
|
|
547
|
-
* imports would be in what every page loads. A layout, an error and a
|
|
548
|
-
* loading are the frame of every page below them, and a guard and a redirect
|
|
549
|
-
* answer before anything renders, so those are imported with the table.
|
|
550
|
-
*/
|
|
551
|
-
const LATE = /* @__PURE__ */ new Set([
|
|
552
|
-
"page",
|
|
553
|
-
"notFound",
|
|
554
|
-
"route",
|
|
555
|
-
"fallback"
|
|
556
|
-
]);
|
|
557
|
-
const isLate = (file) => {
|
|
558
|
-
const slot = slotOf(file);
|
|
559
|
-
return slot !== null && LATE.has(slot);
|
|
560
|
-
};
|
|
561
|
-
const emitRoutesModule = (tree, options) => {
|
|
562
|
-
const namer = createNamer();
|
|
563
|
-
const valueOf = (file) => isLate(file) ? `lazy(${namer.take(file)})` : namer.take(file);
|
|
564
|
-
const table = buildTable(tree, (file) => slotOf(file) === "route" || slotOf(file) === "redirect" ? ANSWERED : valueOf(file));
|
|
565
|
-
const routeFiles = declaredRouteFiles(tree).map((route) => ({
|
|
566
|
-
pattern: route.pattern,
|
|
567
|
-
name: namer.take(route.file)
|
|
568
|
-
}));
|
|
569
|
-
const redirects = declaredRedirects(tree).map((redirect) => ({
|
|
570
|
-
pattern: redirect.pattern,
|
|
571
|
-
name: namer.take(redirect.file)
|
|
572
|
-
}));
|
|
573
|
-
const shells = options.mode === "static" ? fallbackShapes(tree) : [];
|
|
574
|
-
for (const shape of shells) namer.take(shape.file);
|
|
575
|
-
const guarded = guardsOf(tree);
|
|
576
|
-
const guardStacks = new Map([...guarded.stacks].map(([pattern, files]) => [pattern, files.map((file) => namer.take(file))]));
|
|
577
|
-
const guardChecks = [...guarded.own].map(([file, pattern]) => `${pad(1)}${namer.take(file)} satisfies Guard<'${pattern}'>,`);
|
|
578
|
-
const hasGuards = guardChecks.length > 0;
|
|
579
|
-
const withParams = options.withParams ?? /* @__PURE__ */ new Set();
|
|
580
|
-
const withSearch = options.withSearch ?? /* @__PURE__ */ new Set();
|
|
581
|
-
const byFile = beliefs(tree, withParams);
|
|
582
|
-
const asserted = /* @__PURE__ */ new Map();
|
|
583
|
-
const stacks = /* @__PURE__ */ new Map();
|
|
584
|
-
const catchAllStacks = /* @__PURE__ */ new Map();
|
|
585
|
-
const searchReaders = /* @__PURE__ */ new Map();
|
|
586
|
-
for (const [file, name] of namer.names) {
|
|
587
|
-
const belief = byFile.get(file);
|
|
588
|
-
if (belief === void 0) continue;
|
|
589
|
-
const value = valueOf(file);
|
|
590
|
-
const layouts = belief.schemas.filter((schema) => schema !== file).map((schema) => schemaName(namer.take(schema)));
|
|
591
|
-
if (belief.kind === "layout") asserted.set(value, `Layout<'${belief.pattern}'>`);
|
|
592
|
-
else if (belief.kind === "error") asserted.set(value, "ErrorComponent");
|
|
593
|
-
else if (belief.kind === "loading") asserted.set(value, "ComponentType");
|
|
594
|
-
else if (belief.kind === "notFound") {
|
|
595
|
-
asserted.set(value, `Page<'${belief.pattern}'>`);
|
|
596
|
-
if (layouts.length > 0) catchAllStacks.set(belief.pattern, layouts);
|
|
597
|
-
} else if (belief.kind === "page" || belief.kind === "route") {
|
|
598
|
-
const { pattern } = belief;
|
|
599
|
-
if (withParams.has(file)) {
|
|
600
|
-
const module = belief.kind === "page" ? "page" : "route";
|
|
601
|
-
stacks.set(pattern, `(${module}: Loaded<typeof ${name}>) => [${[...layouts, `${module}.paramsSchema`].join(", ")}] as const`);
|
|
602
|
-
} else if (layouts.length > 0) stacks.set(pattern, `() => [${layouts.join(", ")}] as const`);
|
|
603
|
-
if (belief.kind === "route") continue;
|
|
604
|
-
if (withSearch.has(file)) searchReaders.set(pattern, `(page: Loaded<typeof ${name}>) => urlReader(page.search)`);
|
|
605
|
-
const typedBy = stacks.has(pattern) ? `ParamSchemas['${pattern}']` : "[]";
|
|
606
|
-
asserted.set(value, withSearch.has(file) ? `Page<'${pattern}', ${typedBy}, { search: SearchReads['${pattern}'] }>` : stacks.has(pattern) ? `Page<'${pattern}', ${typedBy}>` : `Page<'${pattern}'>`);
|
|
607
|
-
}
|
|
608
|
-
}
|
|
609
|
-
const body = Object.entries(table).map(([key, node]) => `${pad(1)}'${key}': ${renderNode(node, 1, asserted)},`);
|
|
610
|
-
const hasLayout = [...asserted.values()].some((type) => type.startsWith("Layout<"));
|
|
611
|
-
const hasLazy = [...namer.names.keys()].some((file) => slotOf(file) === "page" || slotOf(file) === "notFound");
|
|
612
|
-
const schemaChecks = [...namer.names].filter(([file]) => withParams.has(file)).map(([file, name]) => {
|
|
613
|
-
const belief = byFile.get(file);
|
|
614
|
-
const schema = isLate(file) ? `Loaded<typeof ${name}>['paramsSchema']` : `typeof ${schemaName(name)}`;
|
|
615
|
-
return `${pad(1)}Checked<${schema}, ParamsSchemaFor<'${belief.pattern}'>>,`;
|
|
616
|
-
});
|
|
617
|
-
const routeChecks = routeFiles.map(({ pattern, name }) => stacks.has(pattern) ? `${pad(1)}Checked<Loaded<typeof ${name}>, RouteModule<'${pattern}', ParamSchemas['${pattern}']>>,` : `${pad(1)}Checked<Loaded<typeof ${name}>, RouteModule<'${pattern}'>>,`);
|
|
618
|
-
const fallbackChecks = shells.map(({ file }) => `${pad(1)}Checked<Loaded<typeof ${namer.take(file)}>['default'], ComponentType>,`);
|
|
619
|
-
const hasChecks = schemaChecks.length + routeChecks.length + fallbackChecks.length > 0;
|
|
620
|
-
const readsLate = routeFiles.length > 0 || shells.length > 0 || searchReaders.size > 0 || [...namer.names.keys()].some((file) => withParams.has(file) && isLate(file));
|
|
621
|
-
const hasRoutes = routeFiles.length > 0;
|
|
622
|
-
const hasError = [...asserted.values()].includes("ErrorComponent");
|
|
623
|
-
const withRequest = options.mode === "server";
|
|
624
|
-
const requestLine = withRequest ? [" request: RouteRequest;"] : [];
|
|
625
|
-
const specifier = (file) => `'${options.importPrefix}/${file.replace(/\.[jt]sx?$/u, "")}'`;
|
|
626
|
-
const importLines = [...namer.names].filter(([file]) => !isLate(file)).map(([file, name]) => withParams.has(file) ? `import ${name}, { paramsSchema as ${schemaName(name)} } from ${specifier(file)};` : `import ${name} from ${specifier(file)};`);
|
|
627
|
-
const loaderLines = [...namer.names].filter(([file]) => isLate(file)).map(([file, name]) => `const ${name} = () => import(${specifier(file)});`);
|
|
628
|
-
const toMap = (map) => [...map].map(([pattern, schemas]) => `${pad(1)}'${pattern}': [${schemas.join(", ")}],`);
|
|
629
|
-
const toFunctions = (map) => [...map].map(([pattern, made]) => `${pad(1)}'${pattern}': ${made},`);
|
|
630
|
-
const typeImports = [
|
|
631
|
-
...hasError ? ["ErrorComponent"] : [],
|
|
632
|
-
...hasLayout || hasGuards ? ["ParamsOf"] : [],
|
|
633
|
-
...schemaChecks.length > 0 ? ["ParamsSchemaFor"] : [],
|
|
634
|
-
"ParsedParams"
|
|
635
|
-
];
|
|
636
|
-
return [
|
|
637
|
-
bannerFrom("routes/"),
|
|
638
|
-
"",
|
|
639
|
-
`import { defineRoutes } from '${GENERATED_FROM}';`,
|
|
640
|
-
...searchReaders.size > 0 ? [`import { urlReader } from '@k8ordo/state';`] : [],
|
|
641
|
-
`import type { ${typeImports.join(", ")} } from '${GENERATED_FROM}';`,
|
|
642
|
-
...hasLazy ? [`import { lazy } from 'react';`] : [],
|
|
643
|
-
`import type { ComponentType${hasLayout ? ", ReactNode" : ""} } from 'react';`,
|
|
644
|
-
"",
|
|
645
|
-
...importLines.length > 0 ? [...importLines, ""] : [],
|
|
646
|
-
...withRequest ? [
|
|
647
|
-
"// What a page may read of the request, under a running server only.",
|
|
648
|
-
`import type { RouteRequest } from '${ROUTE_REQUEST_FROM}';`,
|
|
649
|
-
""
|
|
650
|
-
] : [],
|
|
651
|
-
...loaderLines.length > 0 ? [
|
|
652
|
-
"// The files a request reaches one at a time, read when it does: what",
|
|
653
|
-
"// each renders in the browser, and the CSS it imports, goes only to the",
|
|
654
|
-
"// pages that render it.",
|
|
655
|
-
...loaderLines,
|
|
656
|
-
""
|
|
657
|
-
] : [],
|
|
658
|
-
"// What the renderer passes. `satisfies` below is where a route file's",
|
|
659
|
-
"// own props are checked against the pattern its directory puts it under,",
|
|
660
|
-
"// and where its params take the types the `paramsSchema` exports along",
|
|
661
|
-
"// its stack produce.",
|
|
662
|
-
"type Page<",
|
|
663
|
-
" P extends string,",
|
|
664
|
-
" S extends readonly unknown[] = [],",
|
|
665
|
-
" Q = Record<never, never>,",
|
|
666
|
-
"> = ComponentType<",
|
|
667
|
-
" {",
|
|
668
|
-
" params: ParsedParams<P, S>;",
|
|
669
|
-
" pathname: string;",
|
|
670
|
-
...requestLine.map((line) => ` ${line}`),
|
|
671
|
-
" } & Q",
|
|
672
|
-
">;",
|
|
673
|
-
...hasLayout ? [
|
|
674
|
-
"type Layout<P extends string> = ComponentType<{",
|
|
675
|
-
" params: ParamsOf<P>;",
|
|
676
|
-
" pathname: string;",
|
|
677
|
-
...requestLine,
|
|
678
|
-
" children: ReactNode;",
|
|
679
|
-
"}>;"
|
|
680
|
-
] : [],
|
|
681
|
-
...redirects.length > 0 ? [
|
|
682
|
-
"",
|
|
683
|
-
"// What a redirect.ts default-exports: where to, as a pattern the matched",
|
|
684
|
-
"// params fill in, and whether the move is permanent.",
|
|
685
|
-
"type Redirect = string | { readonly to: string; readonly permanent?: boolean };"
|
|
686
|
-
] : [],
|
|
687
|
-
...readsLate ? [
|
|
688
|
-
"",
|
|
689
|
-
"// A file read when a request reaches it, as the module it is read as.",
|
|
690
|
-
"type Loaded<L extends () => Promise<unknown>> = Awaited<ReturnType<L>>;"
|
|
691
|
-
] : [],
|
|
692
|
-
...hasChecks ? [
|
|
693
|
-
"",
|
|
694
|
-
"// `satisfies`, for an export the table holds no value of: compiles only",
|
|
695
|
-
"// when T is assignable to U.",
|
|
696
|
-
"type Checked<T extends U, U> = T;"
|
|
697
|
-
] : [],
|
|
698
|
-
"",
|
|
699
|
-
...schemaChecks.length > 0 ? [
|
|
700
|
-
"// The `paramsSchema` exports the route files declared, each checked against",
|
|
701
|
-
"// the pattern its file sits under.",
|
|
702
|
-
"export type SchemaChecks = [",
|
|
703
|
-
...schemaChecks,
|
|
704
|
-
"];",
|
|
705
|
-
""
|
|
706
|
-
] : [],
|
|
707
|
-
...hasGuards ? [
|
|
708
|
-
"// What a guard.ts default-exports: run before whatever answers below it,",
|
|
709
|
-
"// outer first. A Response ends the request there; nothing lets it through.",
|
|
710
|
-
"type Guard<P extends string> = (context: {",
|
|
711
|
-
" readonly request: Request;",
|
|
712
|
-
" readonly params: ParamsOf<P>;",
|
|
713
|
-
"}) => Response | void | Promise<Response | void>;",
|
|
714
|
-
"",
|
|
715
|
-
"// The guard.ts exports, each checked against the pattern its directory",
|
|
716
|
-
"// puts it under.",
|
|
717
|
-
"const guardChecks = [",
|
|
718
|
-
...guardChecks,
|
|
719
|
-
"] as const;",
|
|
720
|
-
"void guardChecks;",
|
|
721
|
-
""
|
|
722
|
-
] : [],
|
|
723
|
-
"// Per page pattern, the schemas that run before it renders — every",
|
|
724
|
-
"// layout above it that declared one, then its own, read off the file the",
|
|
725
|
-
"// handler read for it. The handler runs them; a schema that refuses makes",
|
|
726
|
-
"// the pattern not answer the pathname.",
|
|
727
|
-
"export const paramSchemas = {",
|
|
728
|
-
...toFunctions(stacks),
|
|
729
|
-
"} as const;",
|
|
730
|
-
"",
|
|
731
|
-
"// The same stacks, as the router types a page's params and links to it.",
|
|
732
|
-
"export type ParamSchemas = {",
|
|
733
|
-
" readonly [P in keyof typeof paramSchemas]: (typeof paramSchemas)[P] extends (...args: never) => infer S ? S : never;",
|
|
734
|
-
"};",
|
|
735
|
-
"",
|
|
736
|
-
"// Per catch-all pattern, the schemas of the layouts above its not-found.",
|
|
737
|
-
"// The handler runs them for what they write to the render (the locale a",
|
|
738
|
-
"// 404 is in); a refusal does not stop a catch-all from answering.",
|
|
739
|
-
"export const catchAllSchemas = {",
|
|
740
|
-
...toMap(catchAllStacks),
|
|
741
|
-
"} as const;",
|
|
742
|
-
"",
|
|
743
|
-
...hasRoutes ? [
|
|
744
|
-
"// What a route.ts exports: a function per request method it answers,",
|
|
745
|
-
"// handed the request and the params, answering with a Response.",
|
|
746
|
-
"type RouteHandler<",
|
|
747
|
-
" P extends string,",
|
|
748
|
-
" S extends readonly unknown[] = [],",
|
|
749
|
-
"> = (context: {",
|
|
750
|
-
" readonly request: Request;",
|
|
751
|
-
" readonly params: ParsedParams<P, S>;",
|
|
752
|
-
"}) => Response | Promise<Response>;",
|
|
753
|
-
"type RouteModule<P extends string, S extends readonly unknown[] = []> = {",
|
|
754
|
-
` readonly [M in ${ROUTE_METHODS.map((method) => `'${method}'`).join(" | ")}]?: RouteHandler<P, S>;`,
|
|
755
|
-
"};",
|
|
756
|
-
"",
|
|
757
|
-
"// The route.ts modules, each checked against the pattern its directory",
|
|
758
|
-
"// puts it under.",
|
|
759
|
-
"export type RouteChecks = [",
|
|
760
|
-
...routeChecks,
|
|
761
|
-
"];",
|
|
762
|
-
""
|
|
763
|
-
] : [],
|
|
764
|
-
...hasRoutes || redirects.length > 0 ? [
|
|
765
|
-
"// A route.ts or a redirect.ts in the table: the handler answers it from",
|
|
766
|
-
"// `routeModules` or `redirects` before anything renders, so its place",
|
|
767
|
-
"// here is only where it matches.",
|
|
768
|
-
`const ${ANSWERED} = (): null => null;`,
|
|
769
|
-
""
|
|
770
|
-
] : [],
|
|
771
|
-
"// Per page pattern that exports `search`, what reads it out of the URL —",
|
|
772
|
-
"// @k8ordo/state's reading of a url schema, made from the page's module.",
|
|
773
|
-
"// The page receives what it read, and a client navigation that changes",
|
|
774
|
-
"// the search loads it again.",
|
|
775
|
-
"export const searchReaders = {",
|
|
776
|
-
...toFunctions(searchReaders),
|
|
777
|
-
"} as const;",
|
|
778
|
-
"",
|
|
779
|
-
"// What each of those pages receives as `search`.",
|
|
780
|
-
"export type SearchReads = {",
|
|
781
|
-
" readonly [P in keyof typeof searchReaders]: (typeof searchReaders)[P] extends (...args: never) => (...args: never) => infer R ? R : never;",
|
|
782
|
-
"};",
|
|
783
|
-
"",
|
|
784
|
-
"// Per pattern, what reads the page or the not-found that answers it. The",
|
|
785
|
-
"// handler renders what it read in the place `lazy()` holds below.",
|
|
786
|
-
"export const pageModules = {",
|
|
787
|
-
...[...namer.names].filter(([file]) => slotOf(file) === "page" || slotOf(file) === "notFound").map(([file, name]) => `${pad(1)}'${byFile.get(file).pattern}': ${name},`),
|
|
788
|
-
"} as const;",
|
|
789
|
-
"",
|
|
790
|
-
"// Per pattern, what reads the route.ts that answers it, by the methods it",
|
|
791
|
-
"// exports.",
|
|
792
|
-
"export const routeModules = {",
|
|
793
|
-
...routeFiles.map(({ pattern, name }) => `${pad(1)}'${pattern}': ${name},`),
|
|
794
|
-
"} as const;",
|
|
795
|
-
"",
|
|
796
|
-
"// Per pattern, the guards that run before it answers — outer first. `/*`",
|
|
797
|
-
"// carries the root's, for a URL nothing answers.",
|
|
798
|
-
"export const guards = {",
|
|
799
|
-
...toMap(guardStacks),
|
|
800
|
-
"} as const;",
|
|
801
|
-
"",
|
|
802
|
-
"// Per pattern, where a redirect.ts sends the visitor, once the table",
|
|
803
|
-
"// matched the pattern: a directory that redirects has no page to render.",
|
|
804
|
-
"export const redirects = {",
|
|
805
|
-
...redirects.map(({ pattern, name }) => `${pad(1)}'${pattern}': ${name} satisfies Redirect,`),
|
|
806
|
-
"} as const;",
|
|
807
|
-
"",
|
|
808
|
-
...options.mode === "static" ? [
|
|
809
|
-
"// Per page pattern with a fallback.tsx: what reads its shell for a value",
|
|
810
|
-
"// the build did not write, the params a shell may leave to the browser, and",
|
|
811
|
-
"// the schemas of the layouts above it, which run over the params it fills.",
|
|
812
|
-
"export const fallbacks = {",
|
|
813
|
-
...shells.flatMap(({ pattern, file, open }) => [
|
|
814
|
-
`${pad(1)}'${pattern}': {`,
|
|
815
|
-
`${pad(2)}load: ${namer.take(file)},`,
|
|
816
|
-
`${pad(2)}open: [${open.map((param) => `'${param}'`).join(", ")}],`,
|
|
817
|
-
`${pad(2)}schemas: [${byFile.get(file).schemas.map((layout) => schemaName(namer.take(layout))).join(", ")}],`,
|
|
818
|
-
`${pad(1)}},`
|
|
819
|
-
]),
|
|
820
|
-
"} as const;",
|
|
821
|
-
...fallbackChecks.length > 0 ? [
|
|
822
|
-
"",
|
|
823
|
-
"// The fallback.tsx files, each checked as a component handed nothing.",
|
|
824
|
-
"export type FallbackChecks = [",
|
|
825
|
-
...fallbackChecks,
|
|
826
|
-
"];"
|
|
827
|
-
] : []
|
|
828
|
-
] : ["// A running server renders every value with its page: no shells.", "export const fallbacks = {} as const;"],
|
|
829
|
-
"",
|
|
830
|
-
"export const routes = defineRoutes({",
|
|
831
|
-
...body,
|
|
832
|
-
"});",
|
|
833
|
-
""
|
|
834
|
-
].join("\n");
|
|
835
|
-
};
|
|
836
|
-
/**
|
|
837
|
-
* Both packages read the app's route table through declaration merging, so
|
|
838
|
-
* the app gets typed paths everywhere without writing the ceremony itself.
|
|
839
|
-
* The router's `Register` is augmented through the framework's re-export of
|
|
840
|
-
* it, which TypeScript merges into the router's own declaration. The locale
|
|
841
|
-
* set reaches `@k8ordo/i18n`'s `Register` the same way, so every message is
|
|
842
|
-
* held to it.
|
|
843
|
-
*/
|
|
844
|
-
const emitRegisterModule = (options) => {
|
|
845
|
-
const wantsState = options.stateModule !== null && options.stateModule !== void 0;
|
|
846
|
-
const localesModule = options.localesModule ?? null;
|
|
847
|
-
const withRequest = options.mode === "server";
|
|
848
|
-
const lines = [
|
|
849
|
-
localesModule === null ? bannerFrom("routes/") : bannerFrom("routes/", LOCALES_MODULE),
|
|
850
|
-
"",
|
|
851
|
-
`import type { ParsedParamsMap } from '${GENERATED_FROM}';`,
|
|
852
|
-
...withRequest ? [`import type { RouteRequest } from '${ROUTE_REQUEST_FROM}';`] : [],
|
|
853
|
-
...localesModule === null ? [] : [`import type { LocaleOf } from '${I18N}';`],
|
|
854
|
-
...wantsState ? [`import type {} from '${options.stateModule}';`] : [],
|
|
855
|
-
...localesModule === null ? [] : [`import type { locales } from '${localesModule}';`],
|
|
856
|
-
`import type { ParamSchemas, routes, SearchReads } from '${options.routesModule}';`,
|
|
857
|
-
"",
|
|
858
|
-
`declare module '${GENERATED_FROM}' {`,
|
|
859
|
-
" interface Register {",
|
|
860
|
-
" routes: typeof routes;",
|
|
861
|
-
" // A link takes a param as the page receives it — typed by its schema.",
|
|
862
|
-
" params: ParsedParamsMap<ParamSchemas>;",
|
|
863
|
-
" // A page that exports `search` receives what it reads.",
|
|
864
|
-
" search: SearchReads;",
|
|
865
|
-
...withRequest ? [" // A route file receives the request: this is a running server.", " request: RouteRequest;"] : [],
|
|
866
|
-
" }",
|
|
867
|
-
"}"
|
|
868
|
-
];
|
|
869
|
-
if (wantsState) lines.push("", `declare module '${options.stateModule}' {`, " interface Register {", " routes: typeof routes;", " }", "}");
|
|
870
|
-
if (localesModule !== null) lines.push("", `declare module '${I18N}' {`, " interface Register {", " locale: LocaleOf<typeof locales>;", " }", "}");
|
|
871
|
-
lines.push("");
|
|
872
|
-
return lines.join("\n");
|
|
873
|
-
};
|
|
874
|
-
// ../framework-engine/dist/runtime/payload.mjs
|
|
875
|
-
/**
|
|
876
|
-
* Said by the handler under mode: 'static' alone, on the not-found a page
|
|
877
|
-
* answered with `notFound()`: the build tells it apart from a param a schema
|
|
878
|
-
* refused, which is a 404 as well.
|
|
879
|
-
*/
|
|
880
|
-
const NOT_FOUND_HEADER = "x-k8ordo-not-found";
|
|
881
|
-
/**
|
|
882
|
-
* Said by the handler under mode: 'static' alone, on a page's HTML: the
|
|
883
|
-
* nonce its inline scripts were signed with, which the build turns into the
|
|
884
|
-
* hashes a `Content-Security-Policy` names. A file cannot carry a nonce —
|
|
885
|
-
* everyone reads the same one.
|
|
886
|
-
*/
|
|
887
|
-
const NONCE_HEADER = "x-k8ordo-nonce";
|
|
17
|
+
// ../framework-engine/dist/runtime/stylesheets.mjs
|
|
888
18
|
/**
|
|
889
19
|
* The `href` of the one `<style>` the HTML render writes itself, empty, under
|
|
890
|
-
*
|
|
891
|
-
*
|
|
892
|
-
*
|
|
893
|
-
*
|
|
894
|
-
*
|
|
895
|
-
* it by hash where the policy decides a style element.
|
|
20
|
+
* `SERVER_STYLESHEETS`. React orders the precedences in `<head>` as each is
|
|
21
|
+
* first asked for, and puts a stylesheet loaded later after the last of its
|
|
22
|
+
* own; asked for first, this keeps the Server Components' stylesheets before
|
|
23
|
+
* the client components'. Under mode: 'static' it carries no nonce, and the
|
|
24
|
+
* build names it by hash where the policy decides a style element.
|
|
896
25
|
*/
|
|
897
26
|
const STYLESHEET_ORDER_HREF = "k8ordo-stylesheet-order";
|
|
898
|
-
/**
|
|
899
|
-
* Said by the handler under mode: 'static' alone, on a shell's HTML and
|
|
900
|
-
* payload: the pattern whose fallback.tsx rendered it. The table walks in its
|
|
901
|
-
* own order, so a shell pathname can be answered by another pattern than the
|
|
902
|
-
* one the build asked for, and the build compares instead of guessing.
|
|
903
|
-
*/
|
|
904
|
-
const SHELL_HEADER = "x-k8ordo-shell";
|
|
905
|
-
/**
|
|
906
|
-
* Said by the handler under mode: 'static' alone, on a page's HTML: every
|
|
907
|
-
* client component the payload it rendered names (`clientDepsHeader`) — what
|
|
908
|
-
* the HTML render was handed to link — which the build checks the HTML
|
|
909
|
-
* links.
|
|
910
|
-
*/
|
|
911
|
-
const CLIENT_DEPS_HEADER = "x-k8ordo-client-deps";
|
|
912
|
-
/** What `clientDepsHeader` said. */
|
|
913
|
-
const readClientDeps = (value) => JSON.parse(decodeURIComponent(value));
|
|
914
27
|
// ../framework-engine/dist/generate/write.mjs
|
|
915
28
|
/** The filesystem edge: everything below it is a pure function of this list. */
|
|
916
29
|
const scanRoutes = async (dir) => {
|
|
@@ -1076,6 +189,8 @@ const writeIfChanged = async (file, content) => {
|
|
|
1076
189
|
};
|
|
1077
190
|
// ../framework-engine/dist/plugin/core.mjs
|
|
1078
191
|
const VIRTUAL_ROUTES = "virtual:k8ordo/routes";
|
|
192
|
+
const VIRTUAL_LOCALES = "virtual:k8ordo/locales";
|
|
193
|
+
const NO_LOCALES = `\0${VIRTUAL_LOCALES}`;
|
|
1079
194
|
/**
|
|
1080
195
|
* The warning a module gets when the RSC plugin's list of Server Actions is
|
|
1081
196
|
* the only thing importing it dynamically. Another dynamic importer beside
|
|
@@ -1275,7 +390,11 @@ const engine = (options, host) => {
|
|
|
1275
390
|
},
|
|
1276
391
|
resolveId(source) {
|
|
1277
392
|
if (source === VIRTUAL_ROUTES) return routesModule();
|
|
393
|
+
if (source === VIRTUAL_LOCALES) return existsSync(localesModule) ? localesModule : NO_LOCALES;
|
|
1278
394
|
return null;
|
|
395
|
+
},
|
|
396
|
+
load(id) {
|
|
397
|
+
return id === NO_LOCALES ? "export {};" : null;
|
|
1279
398
|
}
|
|
1280
399
|
};
|
|
1281
400
|
return [
|
|
@@ -1453,6 +572,22 @@ const redirectPage = (to) => {
|
|
|
1453
572
|
const escaped = escapeMarkup(to);
|
|
1454
573
|
return `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="refresh" content="0;url=${escaped}"><link rel="canonical" href="${escaped}"><title>Redirecting</title></head><body><a href="${escaped}">${escaped}</a></body></html>\n`;
|
|
1455
574
|
};
|
|
575
|
+
const filesOf = (named) => new Set(named.flatMap(({ js, css }) => [...js, ...css]));
|
|
576
|
+
/** What `CLIENT_FILES_PATH` lists: each page's files, by its payload's path. */
|
|
577
|
+
const clientFiles = (pages, documents) => {
|
|
578
|
+
let everywhere;
|
|
579
|
+
for (const named of documents) {
|
|
580
|
+
const files = filesOf(named);
|
|
581
|
+
everywhere = everywhere?.intersection(files) ?? files;
|
|
582
|
+
}
|
|
583
|
+
const own = [...pages].map(([page, named]) => [page, [...filesOf(named)].filter((file) => everywhere?.has(file) !== true)]).filter(([, files]) => files.length > 0).toSorted(([a], [b]) => a < b ? -1 : 1);
|
|
584
|
+
const files = [...new Set(own.flatMap(([, listed]) => listed))].toSorted();
|
|
585
|
+
const indexOf = new Map(files.map((file, index) => [file, index]));
|
|
586
|
+
return {
|
|
587
|
+
files,
|
|
588
|
+
pages: Object.fromEntries(own.map(([page, listed]) => [page, listed.flatMap((file) => indexOf.get(file) ?? []).toSorted((a, b) => a - b)]))
|
|
589
|
+
};
|
|
590
|
+
};
|
|
1456
591
|
const IGNORED = "is ignored in a <meta> — set it as a header at the host";
|
|
1457
592
|
const HEADER_ONLY = /* @__PURE__ */ new Map([
|
|
1458
593
|
["frame-ancestors", IGNORED],
|
|
@@ -1511,6 +646,7 @@ const policyProblems = (policy) => {
|
|
|
1511
646
|
};
|
|
1512
647
|
const SCRIPT = /<script\b([^>]*)>([\s\S]*?)<\/script[\s/>]/giu;
|
|
1513
648
|
const ORDER_STYLE = new RegExp(`<style\\b[^>]*\\sdata-href="${STYLESHEET_ORDER_HREF}"[^>]*>([^<]*)</style>`, "u");
|
|
649
|
+
const CHARSET = /^<meta(?:\s[^>]*)?\scharset=[^>]*>/iu;
|
|
1514
650
|
const hashOf = (source) => `'sha256-${createHash("sha256").update(source.replaceAll("\r\n", "\n").replaceAll("\r", "\n")).digest("base64")}'`;
|
|
1515
651
|
/**
|
|
1516
652
|
* The policy as the page's `<meta>` says it: the application's directives,
|
|
@@ -1538,14 +674,8 @@ const serialize = (policy, hashes, styleHash) => {
|
|
|
1538
674
|
return [...directives].map(([name, sources]) => [name, ...sources].join(" ")).join("; ");
|
|
1539
675
|
};
|
|
1540
676
|
/**
|
|
1541
|
-
* The page as a file
|
|
1542
|
-
*
|
|
1543
|
-
* everyone reads the same file, so the nonce is taken off. With a policy,
|
|
1544
|
-
* what it signed is named by hash instead, in a `<meta>` ahead of everything
|
|
1545
|
-
* the page loads, and so is the framework's one `<style>`, which keeps the
|
|
1546
|
-
* Server Components' stylesheets first; an inline script of the
|
|
1547
|
-
* application's is the application's to allow, by its hash in that policy,
|
|
1548
|
-
* and one that reached the page from content is refused.
|
|
677
|
+
* The page as a file: without the nonce, which everyone reading the same file
|
|
678
|
+
* makes worth nothing, and with a policy, what it signed named by hash.
|
|
1549
679
|
*/
|
|
1550
680
|
const asFile = (html, nonce, policy) => {
|
|
1551
681
|
const signed = ` nonce="${nonce}"`;
|
|
@@ -1557,7 +687,8 @@ const asFile = (html, nonce, policy) => {
|
|
|
1557
687
|
if (head === null) throw new Error("the \"csp\" option needs a <head> to put its <meta> in, and this page has none");
|
|
1558
688
|
const order = ORDER_STYLE.exec(unsigned);
|
|
1559
689
|
const styleHash = order === null ? null : hashOf(order[1] ?? "");
|
|
1560
|
-
const
|
|
690
|
+
const opened = head.index + head[0].length;
|
|
691
|
+
const at = opened + (CHARSET.exec(unsigned.slice(opened))?.[0].length ?? 0);
|
|
1561
692
|
const meta = `<meta http-equiv="Content-Security-Policy" content="${escapeMarkup(serialize(policy, [...hashes], styleHash))}">`;
|
|
1562
693
|
return `${unsigned.slice(0, at)}${meta}${unsigned.slice(at)}`;
|
|
1563
694
|
};
|
|
@@ -1598,393 +729,6 @@ const writtenOutsideScripts = (html) => {
|
|
|
1598
729
|
from = end + 1;
|
|
1599
730
|
}
|
|
1600
731
|
};
|
|
1601
|
-
const REFERENCE = /&(?:amp|lt|gt|quot|#x27);/gu;
|
|
1602
|
-
const REFERENCED = /* @__PURE__ */ new Map([
|
|
1603
|
-
["&", "&"],
|
|
1604
|
-
["<", "<"],
|
|
1605
|
-
[">", ">"],
|
|
1606
|
-
[""", "\""],
|
|
1607
|
-
["'", "'"]
|
|
1608
|
-
]);
|
|
1609
|
-
const attributeOf = (tag, name) => new RegExp(`\\s${name}="([^"]*)"`, "u").exec(tag)?.[1]?.replaceAll(REFERENCE, (reference) => REFERENCED.get(reference) ?? "");
|
|
1610
|
-
/**
|
|
1611
|
-
* What of the client components a page's payload names its HTML does not
|
|
1612
|
-
* link: a stylesheet not linked as one in `<head>`, a script neither
|
|
1613
|
-
* preloaded as a module there nor loaded by a `<script>` — by component,
|
|
1614
|
-
* only those missing something. A `<link>` written into a script's text, or
|
|
1615
|
-
* into `<body>`, links nothing before the page has run; React hoists every
|
|
1616
|
-
* resource of a page it waited for into `<head>`. With no `</head>`, the
|
|
1617
|
-
* whole document is its head.
|
|
1618
|
-
*/
|
|
1619
|
-
const unlinkedDeps = (html, named) => {
|
|
1620
|
-
const outside = writtenOutsideScripts(html).join("");
|
|
1621
|
-
const end = outside.indexOf("</head>");
|
|
1622
|
-
const head = end === -1 ? outside : outside.slice(0, end);
|
|
1623
|
-
const stylesheets = /* @__PURE__ */ new Set();
|
|
1624
|
-
const modules = /* @__PURE__ */ new Set();
|
|
1625
|
-
for (const [tag] of head.matchAll(/<link\b[^>]*>/gu)) {
|
|
1626
|
-
const href = attributeOf(tag, "href");
|
|
1627
|
-
if (href === void 0) continue;
|
|
1628
|
-
const rel = attributeOf(tag, "rel");
|
|
1629
|
-
if (rel === "stylesheet") stylesheets.add(href);
|
|
1630
|
-
if (rel === "modulepreload") modules.add(href);
|
|
1631
|
-
}
|
|
1632
|
-
for (const [, attributes = ""] of html.matchAll(SCRIPT)) {
|
|
1633
|
-
const src = attributeOf(attributes, "src");
|
|
1634
|
-
if (src !== void 0) modules.add(src);
|
|
1635
|
-
}
|
|
1636
|
-
return named.map((component) => ({
|
|
1637
|
-
...component,
|
|
1638
|
-
js: component.js.filter((href) => !modules.has(href)),
|
|
1639
|
-
css: component.css.filter((href) => !stylesheets.has(href))
|
|
1640
|
-
})).filter(({ js, css }) => js.length > 0 || css.length > 0);
|
|
1641
|
-
};
|
|
1642
|
-
const counting = (count, one, many) => `${String(count)} ${count === 1 ? one : many}`;
|
|
1643
|
-
/** How many files the message names, before it counts the rest. */
|
|
1644
|
-
const LISTED = 20;
|
|
1645
|
-
/** How many pages a file's line names, before it counts the rest. */
|
|
1646
|
-
const EXAMPLES = 3;
|
|
1647
|
-
const pagesOf = (pages) => {
|
|
1648
|
-
const sorted = [...pages].toSorted();
|
|
1649
|
-
const named = sorted.slice(0, EXAMPLES).join(", ");
|
|
1650
|
-
return `${counting(sorted.length, "page", "pages")} (${sorted.length > EXAMPLES ? `${named}, …` : named})`;
|
|
1651
|
-
};
|
|
1652
|
-
/**
|
|
1653
|
-
* The error a static build stops with when HTML it wrote does not link
|
|
1654
|
-
* what the client components its payload names need: `unlinked` holds, by
|
|
1655
|
-
* page (its pathname, `404.html`, a shell's location), what each component
|
|
1656
|
-
* misses, or `null` when the handler did not say; `report` asks for the
|
|
1657
|
-
* report. Each file is named once, with how many pages miss it, a few of
|
|
1658
|
-
* them and a component that needs it, the files most pages miss first and
|
|
1659
|
-
* only so many: a component's files include what the client entry loads,
|
|
1660
|
-
* so a failure across the site would otherwise repeat the same files for
|
|
1661
|
-
* every page and component, past what a report can carry.
|
|
1662
|
-
*/
|
|
1663
|
-
const unlinkedMessage = (unlinked, report) => {
|
|
1664
|
-
const unsaid = [];
|
|
1665
|
-
const missed = /* @__PURE__ */ new Map();
|
|
1666
|
-
for (const [page, components] of unlinked) {
|
|
1667
|
-
if (components === null) {
|
|
1668
|
-
unsaid.push(page);
|
|
1669
|
-
continue;
|
|
1670
|
-
}
|
|
1671
|
-
for (const { id, name, js, css } of components) for (const file of [...css, ...js]) {
|
|
1672
|
-
const by = missed.get(file) ?? {
|
|
1673
|
-
pages: /* @__PURE__ */ new Set(),
|
|
1674
|
-
components: /* @__PURE__ */ new Map()
|
|
1675
|
-
};
|
|
1676
|
-
by.pages.add(page);
|
|
1677
|
-
by.components.set(`${id}#${name}`, name);
|
|
1678
|
-
missed.set(file, by);
|
|
1679
|
-
}
|
|
1680
|
-
}
|
|
1681
|
-
const files = [...missed].toSorted(([a, { pages: x }], [b, { pages: y }]) => y.size - x.size || (a < b ? -1 : 1));
|
|
1682
|
-
const components = new Set(files.flatMap(([, { components: needing }]) => [...needing.keys()]));
|
|
1683
|
-
return [
|
|
1684
|
-
`static build wrote HTML that does not link everything the client components its payload names need: ${[...files.length > 0 ? [`${counting(unlinked.size - unsaid.length, "HTML file misses", "HTML files miss")} ${counting(files.length, "file", "files")} of ${counting(components.size, "component", "components")}`] : [], ...unsaid.length > 0 ? [`the handler did not say what the payload of ${counting(unsaid.length, "HTML file", "HTML files")} names`] : []].join(", and ")}`,
|
|
1685
|
-
report,
|
|
1686
|
-
...unsaid.length > 0 ? [` ${pagesOf(unsaid)} — the handler did not say what its payload names`] : [],
|
|
1687
|
-
...files.slice(0, LISTED).map(([file, { pages, components: needing }]) => {
|
|
1688
|
-
const [first = "", ...others] = [...needing.values()].toSorted();
|
|
1689
|
-
return ` ${file} — ${pagesOf(pages)}, for ${first}${others.length > 0 ? ` and ${String(others.length)} more` : ""}`;
|
|
1690
|
-
}),
|
|
1691
|
-
...files.length > LISTED ? [` … and ${counting(files.length - LISTED, "more file", "more files")}`] : []
|
|
1692
|
-
].join("\n");
|
|
1693
|
-
};
|
|
1694
|
-
// src/paths.ts
|
|
1695
|
-
/**
|
|
1696
|
-
* Every pattern the table declares — pages, redirects and catch-alls — in
|
|
1697
|
-
* the order the matcher will try them. The engine's one walk, so the build
|
|
1698
|
-
* and the prerenderer agree; a redirect is a URL the site has, so it is a
|
|
1699
|
-
* file the site writes.
|
|
1700
|
-
*/
|
|
1701
|
-
const patternsOf = (dir) => declaredPatterns(dir).map((each) => each.pattern);
|
|
1702
|
-
/** A `:name` segment: a parameter a pattern, or a shell location, leaves open. */
|
|
1703
|
-
const PARAM_SEGMENT = /^:[A-Za-z_]\w*$/u;
|
|
1704
|
-
const isParamSegment = (segment) => PARAM_SEGMENT.test(segment);
|
|
1705
|
-
/**
|
|
1706
|
-
* A pathname with nothing left to fill: no `:name` segment and no `*`. A `:`
|
|
1707
|
-
* inside a segment (`/posts/a:b`) is a value like any other.
|
|
1708
|
-
*/
|
|
1709
|
-
const isConcrete = (pattern) => !pattern.includes("*") && !pattern.split("/").some((segment) => isParamSegment(segment));
|
|
1710
|
-
/**
|
|
1711
|
-
* Every catch-all the table declares. A static host answers every URL it does
|
|
1712
|
-
* not have from **one** file, so a table with a nested `not-found.tsx` cannot
|
|
1713
|
-
* be represented: whichever one the build picked, the other would never be
|
|
1714
|
-
* served. The build says so rather than choosing.
|
|
1715
|
-
*/
|
|
1716
|
-
const catchAllPatterns = (dir) => patternsOf(dir).filter((pattern) => pattern.endsWith("/*"));
|
|
1717
|
-
/**
|
|
1718
|
-
* A pathname the table can only answer with its catch-all, so the build can
|
|
1719
|
-
* render `not-found.tsx` without waiting for a visitor to find it.
|
|
1720
|
-
*
|
|
1721
|
-
* Built from the catch-all's own prefix — its literal segments kept, its
|
|
1722
|
-
* parameters filled with a segment no literal uses — and then taken one
|
|
1723
|
-
* segment deeper than the longest concrete pattern. Keeping the literals is
|
|
1724
|
-
* what reaches a `not-found.tsx` that sits under a named directory; going
|
|
1725
|
-
* deeper is what stops any real page from answering first, since parameters
|
|
1726
|
-
* consume exactly one segment each. Returns null when there is no catch-all;
|
|
1727
|
-
* which one is never in question, because the build refuses a table with more
|
|
1728
|
-
* than one.
|
|
1729
|
-
*/
|
|
1730
|
-
const catchAllPath = (dir) => {
|
|
1731
|
-
const [pattern] = catchAllPatterns(dir);
|
|
1732
|
-
if (pattern === void 0) return null;
|
|
1733
|
-
const prefix = pattern.slice(0, -2).split("/").filter(Boolean).map((segment) => segment.startsWith(":") ? NOT_FOUND_SEGMENT : segment);
|
|
1734
|
-
const depth = Math.max(prefix.length + 1, ...patternsOf(dir).filter((each) => !each.endsWith("/*")).map((each) => each.split("/").filter(Boolean).length + 1));
|
|
1735
|
-
const filler = Array.from({ length: depth - prefix.length }, () => NOT_FOUND_SEGMENT);
|
|
1736
|
-
return `/${[...prefix, ...filler].join("/")}`;
|
|
1737
|
-
};
|
|
1738
|
-
/**
|
|
1739
|
-
* The patterns the build cannot answer on its own. A catch-all is excluded:
|
|
1740
|
-
* it is rendered as the not-found file, never as a page of its own.
|
|
1741
|
-
*/
|
|
1742
|
-
const patternsNeedingPaths = (dir) => patternsOf(dir).filter((pattern) => !isConcrete(pattern) && !pattern.endsWith("/*"));
|
|
1743
|
-
/**
|
|
1744
|
-
* A shell location's pathname: each segment it leaves to the browser replaced
|
|
1745
|
-
* by the reserved one. `/ja/posts/:id` → `/ja/posts/!fallback`.
|
|
1746
|
-
*/
|
|
1747
|
-
const shellPathname = (location) => location.split("/").map((segment) => isParamSegment(segment) ? FALLBACK_SEGMENT : segment).join("/");
|
|
1748
|
-
/** The params a shell location still holds, in order. */
|
|
1749
|
-
const unknownOf = (location) => location.split("/").filter((segment) => isParamSegment(segment)).map((segment) => segment.slice(1));
|
|
1750
|
-
/**
|
|
1751
|
-
* Whether a location is one the pattern answers, segment by segment: a
|
|
1752
|
-
* literal needs the same literal; a parameter takes a value, or the same
|
|
1753
|
-
* `:name` left open — any `:name`, when names are not compared.
|
|
1754
|
-
*/
|
|
1755
|
-
const fits = (pattern, location, byName = true) => {
|
|
1756
|
-
const wanted = pattern.split("/");
|
|
1757
|
-
const given = location.split("/");
|
|
1758
|
-
if (wanted.length !== given.length) return false;
|
|
1759
|
-
return wanted.every((segment, index) => {
|
|
1760
|
-
const at = given[index];
|
|
1761
|
-
if (!isParamSegment(segment)) return segment === at;
|
|
1762
|
-
return !isParamSegment(at) || !byName || at === segment;
|
|
1763
|
-
});
|
|
1764
|
-
};
|
|
1765
|
-
/**
|
|
1766
|
-
* Static rendering cannot invent parameter values, and quietly shipping a
|
|
1767
|
-
* site missing half its pages is worse than refusing to build one. Every
|
|
1768
|
-
* parameterised pattern must be covered by a supplied path — or, for a page
|
|
1769
|
-
* with a fallback.tsx beside it, by its shell, which answers the values the
|
|
1770
|
-
* build did not write.
|
|
1771
|
-
*
|
|
1772
|
-
* The other direction counts too: a supplied path nothing matched is a typo
|
|
1773
|
-
* that would cost exactly the page it was meant to add, and a supplied value
|
|
1774
|
-
* that still contains a parameter (`/ja/blog/:slug` — what expanding only one
|
|
1775
|
-
* of two parameters leaves behind) would be written to disk as a directory
|
|
1776
|
-
* literally named `:slug` — unless its page has a fallback.tsx, when it is
|
|
1777
|
-
* where that shell stands. URLPattern accepts both, so this has to say no.
|
|
1778
|
-
*
|
|
1779
|
-
* A location goes to the first pattern in table order it fits, which is the
|
|
1780
|
-
* pattern whose URLs a host's rule for it will catch.
|
|
1781
|
-
*/
|
|
1782
|
-
const planPaths = (tree, supplied) => {
|
|
1783
|
-
const patterns = patternsOf(tree);
|
|
1784
|
-
const declared = declaredPatterns(tree).filter((each) => each.kind !== "notFound");
|
|
1785
|
-
const shapes = new Map(fallbackShapes(tree).map((shape) => [shape.pattern, shape]));
|
|
1786
|
-
const paths = patterns.filter((pattern) => isConcrete(pattern));
|
|
1787
|
-
const unresolved = [];
|
|
1788
|
-
const unusable = [];
|
|
1789
|
-
const held = [];
|
|
1790
|
-
const misnamed = [];
|
|
1791
|
-
const closed = [];
|
|
1792
|
-
const reserved = [];
|
|
1793
|
-
const located = /* @__PURE__ */ new Map();
|
|
1794
|
-
const offered = /* @__PURE__ */ new Set();
|
|
1795
|
-
const usable = [];
|
|
1796
|
-
for (const raw of supplied) {
|
|
1797
|
-
const path = normalizePathname(raw);
|
|
1798
|
-
if (path.split("/").some((segment) => decodePathname(segment) === "!fallback")) {
|
|
1799
|
-
reserved.push(path);
|
|
1800
|
-
continue;
|
|
1801
|
-
}
|
|
1802
|
-
if (isConcrete(path)) {
|
|
1803
|
-
usable.push(path);
|
|
1804
|
-
continue;
|
|
1805
|
-
}
|
|
1806
|
-
if (path.includes("*")) {
|
|
1807
|
-
unusable.push(path);
|
|
1808
|
-
continue;
|
|
1809
|
-
}
|
|
1810
|
-
const first = declared.find((each) => fits(each.pattern, path));
|
|
1811
|
-
if (first === void 0) {
|
|
1812
|
-
const loosely = declared.find((each) => fits(each.pattern, path, false));
|
|
1813
|
-
if (loosely === void 0) unusable.push(path);
|
|
1814
|
-
else misnamed.push({
|
|
1815
|
-
location: path,
|
|
1816
|
-
pattern: loosely.pattern
|
|
1817
|
-
});
|
|
1818
|
-
continue;
|
|
1819
|
-
}
|
|
1820
|
-
const shape = shapes.get(first.pattern);
|
|
1821
|
-
if (shape === void 0) {
|
|
1822
|
-
held.push({
|
|
1823
|
-
location: path,
|
|
1824
|
-
file: first.file
|
|
1825
|
-
});
|
|
1826
|
-
continue;
|
|
1827
|
-
}
|
|
1828
|
-
offered.add(first.pattern);
|
|
1829
|
-
const outside = unknownOf(path).filter((name) => !shape.open.includes(name));
|
|
1830
|
-
if (outside.length > 0) {
|
|
1831
|
-
closed.push({
|
|
1832
|
-
location: path,
|
|
1833
|
-
params: outside,
|
|
1834
|
-
layout: shape.layout ?? "",
|
|
1835
|
-
supplied: true
|
|
1836
|
-
});
|
|
1837
|
-
continue;
|
|
1838
|
-
}
|
|
1839
|
-
located.set(first.pattern, [...located.get(first.pattern) ?? [], {
|
|
1840
|
-
pattern: first.pattern,
|
|
1841
|
-
location: path,
|
|
1842
|
-
pathname: shellPathname(path)
|
|
1843
|
-
}]);
|
|
1844
|
-
}
|
|
1845
|
-
const used = new Set(paths);
|
|
1846
|
-
const shells = [];
|
|
1847
|
-
for (const pattern of patterns) {
|
|
1848
|
-
if (isConcrete(pattern) || pattern.endsWith("/*")) continue;
|
|
1849
|
-
const matcher = new URLPattern({ pathname: pattern });
|
|
1850
|
-
const covered = usable.filter((path) => matcher.test({ pathname: path }));
|
|
1851
|
-
paths.push(...covered);
|
|
1852
|
-
for (const path of covered) used.add(path);
|
|
1853
|
-
const shape = shapes.get(pattern);
|
|
1854
|
-
if (shape === void 0) {
|
|
1855
|
-
if (covered.length === 0) unresolved.push(pattern);
|
|
1856
|
-
continue;
|
|
1857
|
-
}
|
|
1858
|
-
const assigned = located.get(pattern) ?? [];
|
|
1859
|
-
if (assigned.length > 0) {
|
|
1860
|
-
shells.push(...assigned);
|
|
1861
|
-
continue;
|
|
1862
|
-
}
|
|
1863
|
-
if (offered.has(pattern)) continue;
|
|
1864
|
-
const left = shape.params.filter((name) => !shape.open.includes(name));
|
|
1865
|
-
if (left.length === 0) shells.push({
|
|
1866
|
-
pattern,
|
|
1867
|
-
location: pattern,
|
|
1868
|
-
pathname: shellPathname(pattern)
|
|
1869
|
-
});
|
|
1870
|
-
else closed.push({
|
|
1871
|
-
location: pattern,
|
|
1872
|
-
params: left,
|
|
1873
|
-
layout: shape.layout ?? "",
|
|
1874
|
-
supplied: false
|
|
1875
|
-
});
|
|
1876
|
-
}
|
|
1877
|
-
unusable.push(...usable.filter((path) => !used.has(path)));
|
|
1878
|
-
return {
|
|
1879
|
-
paths: [...new Set(paths)],
|
|
1880
|
-
shells: shells.filter((shell, index) => shells.findIndex((each) => each.pathname === shell.pathname) === index),
|
|
1881
|
-
unresolved,
|
|
1882
|
-
unusable,
|
|
1883
|
-
held,
|
|
1884
|
-
misnamed,
|
|
1885
|
-
closed,
|
|
1886
|
-
reserved
|
|
1887
|
-
};
|
|
1888
|
-
};
|
|
1889
|
-
/**
|
|
1890
|
-
* Shells whose host rule would answer URLs the table gives a pattern declared
|
|
1891
|
-
* before theirs — a page, route.ts or redirect.ts with a parameter and no
|
|
1892
|
-
* fallback.tsx of its own. A host matches the shell's location alone, so the
|
|
1893
|
-
* table's order does not reach it. Only real conflicts: where both hold a
|
|
1894
|
-
* parameter at one position, infinitely many URLs; where the two meet in one
|
|
1895
|
-
* URL, only when the build did not write it, since the written file answers.
|
|
1896
|
-
*/
|
|
1897
|
-
const shadowedShells = (tree, shells, built) => {
|
|
1898
|
-
const declared = declaredPatterns(tree).filter((each) => each.kind !== "notFound");
|
|
1899
|
-
const shapes = new Map(fallbackShapes(tree).map((shape) => [shape.pattern, shape]));
|
|
1900
|
-
const found = [];
|
|
1901
|
-
for (const shell of shells) {
|
|
1902
|
-
const shape = shapes.get(shell.pattern);
|
|
1903
|
-
if (shape === void 0) continue;
|
|
1904
|
-
const before = declared.slice(0, declared.findIndex((each) => each.pattern === shell.pattern));
|
|
1905
|
-
for (const earlier of before) {
|
|
1906
|
-
if (shapes.has(earlier.pattern) || isConcrete(earlier.pattern)) continue;
|
|
1907
|
-
const url = overlapOf(shell.location, earlier);
|
|
1908
|
-
if (url === void 0) continue;
|
|
1909
|
-
if (url !== null && built.has(url)) continue;
|
|
1910
|
-
found.push({
|
|
1911
|
-
location: shell.location,
|
|
1912
|
-
fallback: shape.file,
|
|
1913
|
-
pattern: earlier.pattern,
|
|
1914
|
-
file: earlier.file,
|
|
1915
|
-
url
|
|
1916
|
-
});
|
|
1917
|
-
}
|
|
1918
|
-
}
|
|
1919
|
-
return found;
|
|
1920
|
-
};
|
|
1921
|
-
/**
|
|
1922
|
-
* Where a location and a pattern meet: `undefined` when they never do, `null`
|
|
1923
|
-
* when a parameter on both sides at one position makes it infinitely many
|
|
1924
|
-
* URLs, and otherwise the one URL, each position fixed by one side.
|
|
1925
|
-
*/
|
|
1926
|
-
const overlapOf = (location, earlier) => {
|
|
1927
|
-
const mine = location.split("/");
|
|
1928
|
-
const theirs = earlier.pattern.split("/");
|
|
1929
|
-
if (mine.length !== theirs.length) return void 0;
|
|
1930
|
-
const url = [];
|
|
1931
|
-
for (const [index, segment] of mine.entries()) {
|
|
1932
|
-
const other = theirs[index];
|
|
1933
|
-
const open = isParamSegment(segment);
|
|
1934
|
-
const otherOpen = isParamSegment(other);
|
|
1935
|
-
if (open && otherOpen) return null;
|
|
1936
|
-
if (!open && !otherOpen && segment !== other) return void 0;
|
|
1937
|
-
url.push(open ? other : segment);
|
|
1938
|
-
}
|
|
1939
|
-
return url.join("/");
|
|
1940
|
-
};
|
|
1941
|
-
/** How a pathname is named in a message: its file, as a person finds it. */
|
|
1942
|
-
const isPage = (file) => file === "page.tsx" || file.endsWith("/page.tsx");
|
|
1943
|
-
const paramList = (params) => params.map((name) => `:${name}`).join(", ");
|
|
1944
|
-
/**
|
|
1945
|
-
* What the build refuses in a plan, each kind its own message, so fixing one
|
|
1946
|
-
* is not what reveals the next. `vite dev` logs the same words as a warning.
|
|
1947
|
-
*/
|
|
1948
|
-
const planRefusals = (plan, shadowed) => {
|
|
1949
|
-
const bare = plan.closed.filter((each) => !each.supplied);
|
|
1950
|
-
const suppliedClosed = plan.closed.filter((each) => each.supplied);
|
|
1951
|
-
return [
|
|
1952
|
-
...plan.unresolved.length > 0 ? [`static build needs pathnames for ${plan.unresolved.join(", ")} — supply them with the "paths" option`] : [],
|
|
1953
|
-
...plan.unusable.length > 0 ? [`the "paths" option supplied pathnames no route wants: ${plan.unusable.join(", ")}`] : [],
|
|
1954
|
-
...plan.held.length > 0 ? [`the "paths" option supplied pathnames that still hold a parameter, and only a page with a fallback.tsx beside it takes one: ${plan.held.map(({ location, file }) => `${location} (${file} ${isPage(file) ? "has none" : "cannot have one"})`).join(", ")}`] : [],
|
|
1955
|
-
...plan.misnamed.length > 0 ? [`the "paths" option supplied shell locations whose parameter names are not their pattern's: ${plan.misnamed.map(({ location, pattern }) => `${location} (${pattern})`).join(", ")}`] : [],
|
|
1956
|
-
...suppliedClosed.length > 0 ? [`the "paths" option supplied shell locations that leave out a parameter a layout above their fallback.tsx receives: ${suppliedClosed.map(({ location, params, layout }) => `${location} (${paramList(params)}, received by ${layout})`).join(", ")}`] : [],
|
|
1957
|
-
...bare.length > 0 ? [bare.map(({ location, params, layout }) => `static build needs shell locations for ${location} — ${layout} receives ${paramList(params)}, so the "paths" option has to fill ${params.length === 1 ? "it" : "them"}, as in ${location.split("/").map((segment) => params.some((name) => segment === `:${name}`) ? `<${segment.slice(1)}>` : segment).join("/")}`).join("\n")] : [],
|
|
1958
|
-
...plan.reserved.length > 0 ? [`the "paths" option supplied pathnames with a segment named ${FALLBACK_SEGMENT}, which the build keeps for shells: ${plan.reserved.join(", ")}`] : [],
|
|
1959
|
-
...shadowed.length > 0 ? [shadowed.map(({ location, fallback, pattern, file, url }) => url === null ? `the shell for ${location} (${fallback}) would also answer URLs ${pattern} (${file}) is declared first for — ${isPage(file) ? `give ${file} a fallback.tsx too, or supply` : "supply"} shell locations it cannot match` : `the shell for ${location} (${fallback}) would also answer ${url}, which ${file} is declared first for and the build did not write — list ${url} in "paths", or supply shell locations it cannot match`).join("\n")] : []
|
|
1960
|
-
];
|
|
1961
|
-
};
|
|
1962
|
-
/**
|
|
1963
|
-
* The directory a rendered pathname is written to. A supplied path is
|
|
1964
|
-
* URL-escaped — `/products/caf%C3%A9` — so writing it verbatim would
|
|
1965
|
-
* make a directory literally named with the escapes, which no host would then
|
|
1966
|
-
* match. Decoding is also the moment a path that leaves the output directory
|
|
1967
|
-
* has to be refused: `..` is a real URL segment and would otherwise be
|
|
1968
|
-
* resolved by `path.join`.
|
|
1969
|
-
*/
|
|
1970
|
-
const dirFor = (pathname) => {
|
|
1971
|
-
const decoded = decodePathname(pathname);
|
|
1972
|
-
if (decoded === null) throw new Error(`the "paths" option supplied a pathname with a malformed escape: ${pathname}`);
|
|
1973
|
-
if (decoded.split("/").some((segment) => segment === "..")) throw new Error(`the "paths" option supplied a pathname that leaves the output: ${pathname}`);
|
|
1974
|
-
return decoded;
|
|
1975
|
-
};
|
|
1976
|
-
/**
|
|
1977
|
-
* Whether a route.ts answers a pathname the build writes, rather than a page:
|
|
1978
|
-
* the first declared pattern that matches it says, in the matcher's order.
|
|
1979
|
-
* The catch-all never answers a pathname the build was given.
|
|
1980
|
-
*/
|
|
1981
|
-
const answeredByRoute = (dir, pathname) => {
|
|
1982
|
-
for (const each of declaredPatterns(dir)) {
|
|
1983
|
-
if (each.kind === "notFound") continue;
|
|
1984
|
-
if (new URLPattern({ pathname: each.pattern }).test({ pathname })) return each.kind === "route";
|
|
1985
|
-
}
|
|
1986
|
-
return false;
|
|
1987
|
-
};
|
|
1988
732
|
// src/static.ts
|
|
1989
733
|
const NO_SHELLS = {
|
|
1990
734
|
paths: /* @__PURE__ */ new Set(),
|
|
@@ -2056,6 +800,7 @@ const staticMode = (options) => {
|
|
|
2056
800
|
let suppliedFor;
|
|
2057
801
|
let suppliedInDev = Promise.resolve([]);
|
|
2058
802
|
const noticed = /* @__PURE__ */ new Set();
|
|
803
|
+
const fromRoot = (file) => path.relative(root, path.join(routesDir, file));
|
|
2059
804
|
const devRoutes = () => routesRead ??= (async () => {
|
|
2060
805
|
const { tree, problems } = parseRouteTree(await scanRoutes(routesDir));
|
|
2061
806
|
const failed = problems.length > 0;
|
|
@@ -2095,18 +840,9 @@ const staticMode = (options) => {
|
|
|
2095
840
|
* can be tried locally. The URL is rewritten to the shell pathname before
|
|
2096
841
|
* the RSC plugin's handler reads it; everything else passes untouched.
|
|
2097
842
|
*/
|
|
2098
|
-
const answerUnbuilt = async (request, next) => {
|
|
2099
|
-
try {
|
|
2100
|
-
await rewriteUnbuilt(request);
|
|
2101
|
-
} catch (error) {
|
|
2102
|
-
next(error);
|
|
2103
|
-
return;
|
|
2104
|
-
}
|
|
2105
|
-
next();
|
|
2106
|
-
};
|
|
2107
843
|
const rewriteUnbuilt = async (request) => {
|
|
2108
844
|
if (request.method !== "GET" && request.method !== "HEAD") return;
|
|
2109
|
-
const url = new URL(request.originalUrl ?? request.url ?? "/",
|
|
845
|
+
const url = new URL(request.originalUrl ?? request.url ?? "/", ORIGIN);
|
|
2110
846
|
const own = withoutBase(url.pathname, base);
|
|
2111
847
|
if (own === null) return;
|
|
2112
848
|
const payload = isPayloadPath(own);
|
|
@@ -2134,37 +870,37 @@ const staticMode = (options) => {
|
|
|
2134
870
|
/**
|
|
2135
871
|
* Writes `dist/client/_redirects` once every file is in place — the
|
|
2136
872
|
* built URLs a shell rule would also catch, the application's own rules
|
|
2137
|
-
* from `public/_redirects`, then the shells' — and
|
|
2138
|
-
* get wrong reading it.
|
|
2139
|
-
* its files: the payload URLs of built non-pages, then the shells'.
|
|
873
|
+
* from `public/_redirects`, then the shells' — and returns what Cloudflare
|
|
874
|
+
* would get wrong reading it.
|
|
2140
875
|
*/
|
|
2141
876
|
const writeRedirects = async ({ clientDir, shells, notPages, publicDir }) => {
|
|
2142
|
-
const
|
|
2143
|
-
logger?.warn(message);
|
|
2144
|
-
};
|
|
877
|
+
const misread = [];
|
|
2145
878
|
const shellRewrites = shellRules(shells, base);
|
|
2146
879
|
const ownFile = publicDir === null ? null : path.join(publicDir, "_redirects");
|
|
2147
880
|
let own = null;
|
|
2148
881
|
if (ownFile !== null) try {
|
|
2149
882
|
own = await readFile(ownFile, "utf8");
|
|
2150
|
-
} catch {
|
|
2151
|
-
|
|
883
|
+
} catch (error) {
|
|
884
|
+
if (error.code !== "ENOENT") throw error;
|
|
2152
885
|
}
|
|
2153
886
|
const ownRules = own === null ? [] : rulesOf(own);
|
|
2154
887
|
const hiding = ownRules.flatMap(({ line, from }) => {
|
|
2155
|
-
if (!from.includes("*") &&
|
|
888
|
+
if (!from.includes("*") && !PLACEHOLDER.test(from)) return [];
|
|
2156
889
|
const hidden = shells.find((shell) => cloudflareMatches(from, withBase(shell.pathname, base)));
|
|
2157
890
|
return hidden === void 0 ? [] : [`k8ordo: ${path.relative(root, ownFile ?? "").split(path.sep).join("/")} line "${line}" matches ${hidden.location} before its shell's rule, so that shell is never served`];
|
|
2158
891
|
});
|
|
2159
|
-
|
|
892
|
+
misread.push(...hiding);
|
|
2160
893
|
const built = builtRules(await filesBelow(clientDir), notPages, shellRewrites, ownRules.map(({ from }) => from), base);
|
|
2161
|
-
for (const from of built.unlisted)
|
|
894
|
+
for (const from of built.unlisted) {
|
|
895
|
+
const read = from.includes("*") ? "\"*\" as a splat" : `"${PLACEHOLDER.exec(from)?.[0] ?? ":"}" as a placeholder`;
|
|
896
|
+
misread.push(`k8ordo: _redirects cannot list ${from} — Cloudflare and Netlify read ${read}, so on Cloudflare a shell answers it`);
|
|
897
|
+
}
|
|
2162
898
|
const text = formatRedirects(built.rules, own, shellRewrites);
|
|
2163
899
|
await writeFile(path.join(clientDir, "_redirects"), text);
|
|
2164
900
|
const counted = cloudflareCounts(text);
|
|
2165
|
-
if (counted.static > 2e3)
|
|
2166
|
-
if (counted.dynamic > 100)
|
|
2167
|
-
return
|
|
901
|
+
if (counted.static > 2e3) misread.push(`k8ordo: _redirects has ${String(counted.static)} rules Cloudflare counts as static; it reads 2,000 and skips the rest, so a built page past them is answered by its shell there`);
|
|
902
|
+
if (counted.dynamic > 100) misread.push(`k8ordo: _redirects has ${String(counted.dynamic)} rules Cloudflare counts as dynamic; it reads 100 and ignores the rest of the file — the shell payload rules go first (navigations to those values become document loads), then document rules (those values 404)`);
|
|
903
|
+
return misread;
|
|
2168
904
|
};
|
|
2169
905
|
return [{
|
|
2170
906
|
name: "k8ordo:static-refuses",
|
|
@@ -2172,12 +908,11 @@ const staticMode = (options) => {
|
|
|
2172
908
|
order: "pre",
|
|
2173
909
|
async handler() {
|
|
2174
910
|
const files = await scanRoutes(routesDir);
|
|
2175
|
-
const
|
|
2176
|
-
const guards = files.filter((file) => slotOf(file) === "guard").map((file) => named(file));
|
|
911
|
+
const guards = files.filter((file) => slotOf(file) === "guard").map((file) => fromRoot(file));
|
|
2177
912
|
const exported = await readExports(routesDir, files);
|
|
2178
|
-
const routes = [...exported].filter(([file]) => slotOf(file) === "route").map(([file, names]) => [
|
|
2179
|
-
const searching = [...pagesReadingSearch(exported)].map((file) =>
|
|
2180
|
-
const reexporting = [...exported].filter(([file, names]) => READ_BY_NAME.has(slotOf(file) ?? "") && names.has("*")).map(([file]) =>
|
|
913
|
+
const routes = [...exported].filter(([file]) => slotOf(file) === "route").map(([file, names]) => [fromRoot(file), unwritable(names)]).filter(([, methods]) => methods.length > 0);
|
|
914
|
+
const searching = [...pagesReadingSearch(exported)].map((file) => fromRoot(file));
|
|
915
|
+
const reexporting = [...exported].filter(([file, names]) => READ_BY_NAME.has(slotOf(file) ?? "") && names.has("*")).map(([file]) => fromRoot(file));
|
|
2181
916
|
const refusals = [
|
|
2182
917
|
...guards.length > 0 ? [guardRefusal(guards)] : [],
|
|
2183
918
|
...routes.length > 0 ? [routeRefusal(routes)] : [],
|
|
@@ -2198,9 +933,10 @@ const staticMode = (options) => {
|
|
|
2198
933
|
handler(server) {
|
|
2199
934
|
devRoutes().then((routes) => routes.shapes.length > 0 ? devShells() : void 0).catch(() => void 0);
|
|
2200
935
|
return () => {
|
|
2201
|
-
server.middlewares.use((request
|
|
2202
|
-
|
|
2203
|
-
|
|
936
|
+
server.middlewares.use(middlewareOf(async (request) => {
|
|
937
|
+
await rewriteUnbuilt(request);
|
|
938
|
+
return false;
|
|
939
|
+
}));
|
|
2204
940
|
};
|
|
2205
941
|
}
|
|
2206
942
|
},
|
|
@@ -2230,18 +966,7 @@ const staticMode = (options) => {
|
|
|
2230
966
|
response.end(request.method === "HEAD" ? void 0 : await readFile(served.file));
|
|
2231
967
|
return true;
|
|
2232
968
|
};
|
|
2233
|
-
server.middlewares.use((
|
|
2234
|
-
(async () => {
|
|
2235
|
-
let answered;
|
|
2236
|
-
try {
|
|
2237
|
-
answered = await answeredHere(request, response);
|
|
2238
|
-
} catch (error) {
|
|
2239
|
-
next(error);
|
|
2240
|
-
return;
|
|
2241
|
-
}
|
|
2242
|
-
if (!answered) next();
|
|
2243
|
-
})();
|
|
2244
|
-
});
|
|
969
|
+
server.middlewares.use(middlewareOf(answeredHere));
|
|
2245
970
|
},
|
|
2246
971
|
watchChange(file) {
|
|
2247
972
|
if (!path.resolve(file).startsWith(`${routesDir}${path.sep}`)) return;
|
|
@@ -2281,141 +1006,86 @@ const staticMode = (options) => {
|
|
|
2281
1006
|
order: "post",
|
|
2282
1007
|
async handler(builder) {
|
|
2283
1008
|
const { tree } = parseRouteTree(await scanRoutes(routesDir));
|
|
2284
|
-
const
|
|
2285
|
-
const
|
|
2286
|
-
const catchAlls = catchAllPatterns(tree);
|
|
2287
|
-
const unplanned = [...planRefusals(plan, shadowedShells(tree, plan.shells, new Set(plan.paths))), ...catchAlls.length > 1 ? [`a static host answers every unknown URL from one file, so only one not-found.tsx can be represented — this table declares ${catchAlls.join(", ")}`] : []];
|
|
2288
|
-
if (unplanned.length > 0) throw new Error(unplanned.join("\n\n"));
|
|
1009
|
+
const plan = planPaths(tree, await options.paths?.(patternsNeedingPaths(tree)) ?? []);
|
|
1010
|
+
const answers = answersOf(tree, plan.paths);
|
|
2289
1011
|
const actions = serverActionModules(builder.config);
|
|
2290
1012
|
const importers = [...serverImporters].toSorted();
|
|
2291
|
-
const
|
|
2292
|
-
|
|
1013
|
+
const refusals = [
|
|
1014
|
+
...planRefusals(plan, shadowedShells(tree, plan.shells, new Set(plan.paths))),
|
|
1015
|
+
...catchAllRefusals(tree),
|
|
1016
|
+
...actions.length > 0 ? [actionRefusal(actions)] : [],
|
|
1017
|
+
...importers.length > 0 ? [serverImportRefusal(importers)] : [],
|
|
1018
|
+
...routeFileRefusals(tree, plan, answers, {
|
|
1019
|
+
site: options.site !== void 0,
|
|
1020
|
+
named: fromRoot
|
|
1021
|
+
})
|
|
1022
|
+
];
|
|
1023
|
+
if (refusals.length > 0) throw new Error(refusals.join("\n\n"));
|
|
2293
1024
|
const rscOut = builder.environments.rsc?.config.build.outDir;
|
|
2294
1025
|
const client = builder.environments.client?.config;
|
|
2295
1026
|
if (rscOut === void 0 || client === void 0) throw new Error("static build ran without the rsc/client builds");
|
|
2296
1027
|
const clientDir = path.resolve(root, client.build.outDir);
|
|
2297
1028
|
const origin = options.site === void 0 ? ORIGIN : new URL(options.site).origin;
|
|
2298
|
-
const
|
|
2299
|
-
|
|
2300
|
-
|
|
2301
|
-
|
|
2302
|
-
|
|
2303
|
-
const below = directories.find((pathname) => pathname.startsWith(`${route}/`));
|
|
2304
|
-
return below === void 0 ? [] : [`${route} — ${below} is written below it, as a directory`];
|
|
2305
|
-
});
|
|
2306
|
-
if (unfileable.length > 0) throw new Error(`static build cannot write a route.ts as a file at ${unfileable.join("; ")}`);
|
|
2307
|
-
const entry = path.resolve(root, rscOut, "index.js");
|
|
2308
|
-
const handler = (await import(pathToFileURL(entry).href)).default;
|
|
2309
|
-
const refused = [];
|
|
2310
|
-
const disowned = [];
|
|
2311
|
-
const failed = [];
|
|
2312
|
-
const redirected = /* @__PURE__ */ new Set();
|
|
2313
|
-
const unanswered = [];
|
|
2314
|
-
const unlinkedPages = /* @__PURE__ */ new Map();
|
|
2315
|
-
const unlinks = (page, missing) => {
|
|
2316
|
-
if (missing === null || missing.length > 0) unlinkedPages.set(page, missing);
|
|
1029
|
+
const render = {
|
|
1030
|
+
handler: (await import(pathToFileURL(path.resolve(root, rscOut, "index.js")).href)).default,
|
|
1031
|
+
clientDir,
|
|
1032
|
+
urlFor: (pathname) => `${origin}${withBase(pathname, base)}`,
|
|
1033
|
+
csp
|
|
2317
1034
|
};
|
|
2318
|
-
const
|
|
2319
|
-
await inParallel(plan.paths.flatMap((pathname) => {
|
|
2320
|
-
if (byRoute.has(pathname)) return [async () => {
|
|
2321
|
-
const file = path.join(clientDir, dirFor(pathname));
|
|
2322
|
-
const { status, type } = await writeRoute(file, handler, urlFor(pathname));
|
|
2323
|
-
if (status !== 200) unanswered.push(`${pathname} (${String(status)})`);
|
|
2324
|
-
else if (type !== null) types.set(path.relative(clientDir, file).split(path.sep).join("/"), type);
|
|
2325
|
-
}];
|
|
2326
|
-
const dir = path.join(clientDir, dirFor(pathname));
|
|
2327
|
-
return [async () => {
|
|
2328
|
-
const { status, notFound, unlinked } = await write(path.join(dir, "index.html"), handler, urlFor(pathname), csp, { notFoundIsPage: false });
|
|
2329
|
-
unlinks(pathname, unlinked);
|
|
2330
|
-
if (status === 404) (notFound ? disowned : refused).push(pathname);
|
|
2331
|
-
if (status === 500) failed.push(pathname);
|
|
2332
|
-
if (status === 307 || status === 308) redirected.add(pathname);
|
|
2333
|
-
if (status === 200) await write(path.join(dir, "index.rsc"), handler, urlFor(payloadPathFor(pathname)), csp, { notFoundIsPage: false });
|
|
2334
|
-
}];
|
|
2335
|
-
}));
|
|
2336
|
-
const unmatched = catchAllPath(tree);
|
|
2337
|
-
if (unmatched !== null) {
|
|
2338
|
-
const { status, unlinked } = await write(path.join(clientDir, "404.html"), handler, urlFor(unmatched), csp, { notFoundIsPage: true });
|
|
2339
|
-
unlinks("404.html", unlinked);
|
|
2340
|
-
if (status === 500) failed.push("404.html");
|
|
2341
|
-
}
|
|
1035
|
+
const notFoundAt = catchAllPath(tree);
|
|
2342
1036
|
const fallbacks = new Map(fallbackShapes(tree).map((shape) => [shape.pattern, shape.file]));
|
|
2343
|
-
const
|
|
2344
|
-
|
|
2345
|
-
|
|
2346
|
-
|
|
2347
|
-
const dir = path.join(clientDir, dirFor(shell.pathname));
|
|
2348
|
-
const answered = await write(path.join(dir, "index.html"), handler, urlFor(shell.pathname), csp, {
|
|
2349
|
-
notFoundIsPage: false,
|
|
2350
|
-
shell: shell.pattern
|
|
2351
|
-
});
|
|
2352
|
-
const named = `${shell.location} (${fallbacks.get(shell.pattern) ?? ""})`;
|
|
2353
|
-
unlinks(shell.location, answered.unlinked);
|
|
2354
|
-
if (answered.status === 500) failed.push(shell.location);
|
|
2355
|
-
else if (answered.status === 404) (answered.notFound ? shellDisowned : shellRefused).push(shell.location);
|
|
2356
|
-
else if (answered.shell === null) shellTaken.push(`the shell for ${named} was answered by another route, which took "${FALLBACK_SEGMENT}" as a value`);
|
|
2357
|
-
else if (answered.shell === shell.pattern) await write(path.join(dir, "index.rsc"), handler, urlFor(payloadPathFor(shell.pathname)), csp, {
|
|
2358
|
-
notFoundIsPage: false,
|
|
2359
|
-
shell: shell.pattern
|
|
2360
|
-
});
|
|
2361
|
-
else shellTaken.push(`the shell for ${named} was answered by ${fallbacks.get(answered.shell) ?? answered.shell}, which the table tries first — supply shell locations that pattern cannot match`);
|
|
2362
|
-
}));
|
|
2363
|
-
const unwritten = [
|
|
2364
|
-
...failed.length > 0 ? [`static build could not render ${failed.toSorted().join(", ")} — see the error above`] : [],
|
|
2365
|
-
...unlinkedPages.size > 0 ? [unlinkedMessage(unlinkedPages, bugReport())] : [],
|
|
2366
|
-
...unanswered.length > 0 ? [`static build writes a route.ts from a GET that answers 200, and these did not: ${unanswered.toSorted().join(", ")}`] : [],
|
|
2367
|
-
...refused.length > 0 ? [`the "paths" option supplied pathnames a params schema refused: ${refused.toSorted().join(", ")}`] : [],
|
|
2368
|
-
...disowned.length > 0 ? [`the "paths" option supplied pathnames whose page called notFound(): ${disowned.toSorted().join(", ")}`] : [],
|
|
2369
|
-
...shellRefused.length > 0 ? [`the "paths" option supplied shell locations a params schema refused: ${shellRefused.toSorted().join(", ")}`] : [],
|
|
2370
|
-
...shellDisowned.length > 0 ? [shellDisowned.toSorted().map((location) => `the shell for ${location} called notFound() while it rendered, and a shell has no value to disown — call notFound() from the client component that reads the value in the browser`).join("\n")] : [],
|
|
2371
|
-
...shellTaken.length > 0 ? [shellTaken.toSorted().join("\n")] : []
|
|
1037
|
+
const rendered = [
|
|
1038
|
+
...await inParallel(plan.paths.map((pathname) => () => answers.get(pathname)?.kind === "route" ? renderRoute(render, pathname) : renderPage(render, pathname))),
|
|
1039
|
+
...notFoundAt === null ? [] : [await renderNotFound(render, notFoundAt)],
|
|
1040
|
+
...await inParallel(plan.shells.map((shell) => () => renderShell(render, shell, fallbacks)))
|
|
2372
1041
|
];
|
|
2373
|
-
|
|
2374
|
-
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
|
|
2379
|
-
|
|
2380
|
-
|
|
2381
|
-
|
|
2382
|
-
|
|
2383
|
-
|
|
2384
|
-
|
|
2385
|
-
|
|
2386
|
-
|
|
2387
|
-
|
|
2388
|
-
|
|
2389
|
-
|
|
2390
|
-
|
|
2391
|
-
|
|
2392
|
-
|
|
2393
|
-
notFound: unmatched !== null,
|
|
2394
|
-
types
|
|
1042
|
+
const failures = failureMessages(rendered);
|
|
1043
|
+
if (failures.length > 0) throw new Error(failures.join("\n\n"));
|
|
1044
|
+
for (const location of await leakingShells(clientDir, plan.shells)) builder.config.logger.warn(`k8ordo: the shell for ${location} has "${FALLBACK_SEGMENT}" in its HTML — a layout wrote the shell's pathname into the page (a link, a canonical URL); derive what depends on the URL in a client component`);
|
|
1045
|
+
await writeClientFiles(clientDir, rendered);
|
|
1046
|
+
const notPages = rendered.flatMap((each) => each.kind === "route" || each.kind === "redirect" ? [each.pathname] : []);
|
|
1047
|
+
if (options.site !== void 0) await writeSitemap(clientDir, options.site, plan.paths.filter((pathname) => !notPages.includes(pathname)).map((pathname) => withBase(pathname, base)));
|
|
1048
|
+
const adapter = adapterOf(builder.config.plugins);
|
|
1049
|
+
if (plan.shells.length > 0) {
|
|
1050
|
+
const misread = await writeRedirects({
|
|
1051
|
+
clientDir,
|
|
1052
|
+
shells: plan.shells,
|
|
1053
|
+
notPages,
|
|
1054
|
+
publicDir: client.build.copyPublicDir && builder.config.publicDir !== "" ? builder.config.publicDir : null
|
|
1055
|
+
});
|
|
1056
|
+
if (adapter === void 0) for (const message of misread) builder.config.logger.warn(message);
|
|
1057
|
+
}
|
|
1058
|
+
await adapter?.writeStatic({
|
|
1059
|
+
rewrites: rewritesAfterFiles(plan.shells, notPages, base),
|
|
1060
|
+
notFound: notFoundAt !== null,
|
|
1061
|
+
types: typesOf(rendered)
|
|
2395
1062
|
});
|
|
2396
|
-
|
|
2397
|
-
|
|
2398
|
-
|
|
1063
|
+
builder.config.logger.info(`k8ordo: wrote ${summaryOf(plan, {
|
|
1064
|
+
notFound: notFoundAt !== null,
|
|
1065
|
+
sitemap: options.site !== void 0
|
|
1066
|
+
})}`);
|
|
2399
1067
|
}
|
|
2400
1068
|
}
|
|
2401
1069
|
}];
|
|
2402
1070
|
};
|
|
2403
1071
|
/**
|
|
2404
|
-
*
|
|
2405
|
-
*
|
|
2406
|
-
* the application installed.
|
|
1072
|
+
* A Connect middleware from a step that says whether it answered the request
|
|
1073
|
+
* — Connect awaits nothing, so a step that rejects reaches `next` this way.
|
|
2407
1074
|
*/
|
|
2408
|
-
const
|
|
2409
|
-
|
|
2410
|
-
|
|
2411
|
-
|
|
2412
|
-
|
|
2413
|
-
|
|
2414
|
-
|
|
2415
|
-
|
|
2416
|
-
|
|
2417
|
-
|
|
1075
|
+
const middlewareOf = (answered) => (request, response, next) => {
|
|
1076
|
+
(async () => {
|
|
1077
|
+
let done;
|
|
1078
|
+
try {
|
|
1079
|
+
done = await answered(request, response);
|
|
1080
|
+
} catch (error) {
|
|
1081
|
+
next(error);
|
|
1082
|
+
return;
|
|
1083
|
+
}
|
|
1084
|
+
if (!done) next();
|
|
1085
|
+
})();
|
|
2418
1086
|
};
|
|
1087
|
+
/** The host adapter among the plugins, if any. */
|
|
1088
|
+
const adapterOf = (plugins) => plugins.map((plugin) => plugin.api).find((api) => typeof api?.writeStatic === "function");
|
|
2419
1089
|
/**
|
|
2420
1090
|
* A render is a whole page: components, their data, and whatever the app's
|
|
2421
1091
|
* own highlighting or markdown does. Starting every one of them at once ties
|
|
@@ -2425,18 +1095,112 @@ const bugReport = () => {
|
|
|
2425
1095
|
*/
|
|
2426
1096
|
const WIDTH = 8;
|
|
2427
1097
|
const inParallel = async (tasks) => {
|
|
1098
|
+
const results = [];
|
|
2428
1099
|
let next = 0;
|
|
2429
1100
|
const worker = async () => {
|
|
2430
|
-
for (let
|
|
1101
|
+
for (let at = next++; at < tasks.length; at = next++) results[at] = await tasks[at]();
|
|
2431
1102
|
};
|
|
2432
1103
|
await Promise.all(Array.from({ length: Math.min(WIDTH, tasks.length) }, worker));
|
|
1104
|
+
return results;
|
|
1105
|
+
};
|
|
1106
|
+
const FAILURES = {
|
|
1107
|
+
render: (names) => `static build could not render ${names.join(", ")} — see the error above`,
|
|
1108
|
+
route: (names) => `static build writes a route.ts from a GET that answers 200, and these did not: ${names.join(", ")}`,
|
|
1109
|
+
refused: (names) => `the "paths" option supplied pathnames a params schema refused: ${names.join(", ")}`,
|
|
1110
|
+
disowned: (names) => `the "paths" option supplied pathnames whose page called notFound(): ${names.join(", ")}`,
|
|
1111
|
+
shellRefused: (names) => `the "paths" option supplied shell locations a params schema refused: ${names.join(", ")}`,
|
|
1112
|
+
shellDisowned: (names) => names.map((location) => `the shell for ${location} called notFound() while it rendered, and a shell has no value to disown — call notFound() from the client component that reads the value in the browser`).join("\n"),
|
|
1113
|
+
shellTaken: (names) => names.join("\n")
|
|
1114
|
+
};
|
|
1115
|
+
const failed = (failure, name) => ({
|
|
1116
|
+
kind: "failure",
|
|
1117
|
+
failure,
|
|
1118
|
+
name
|
|
1119
|
+
});
|
|
1120
|
+
/** Every kind that stopped the build, in `FAILURES`' order, each sorted. */
|
|
1121
|
+
const failureMessages = (rendered) => Object.entries(FAILURES).flatMap(([failure, message]) => {
|
|
1122
|
+
const names = rendered.flatMap((each) => each.kind === "failure" && each.failure === failure ? [each.name] : []).toSorted();
|
|
1123
|
+
return names.length === 0 ? [] : [message(names)];
|
|
1124
|
+
});
|
|
1125
|
+
const renderRoute = async ({ handler, clientDir, urlFor }, pathname) => {
|
|
1126
|
+
const { status, type } = await writeBody(path.join(clientDir, dirFor(pathname)), handler, urlFor(pathname));
|
|
1127
|
+
return status === 200 ? {
|
|
1128
|
+
kind: "route",
|
|
1129
|
+
pathname,
|
|
1130
|
+
type
|
|
1131
|
+
} : failed("route", `${pathname} (${String(status)})`);
|
|
1132
|
+
};
|
|
1133
|
+
const renderPage = async (render, pathname) => {
|
|
1134
|
+
const dir = path.join(render.clientDir, dirFor(pathname));
|
|
1135
|
+
const { status, notFound, named } = await writeHtml(path.join(dir, "index.html"), render, render.urlFor(pathname), { notFoundIsPage: false });
|
|
1136
|
+
if (status === 500) return failed("render", pathname);
|
|
1137
|
+
if (status === 404) return failed(notFound ? "disowned" : "refused", pathname);
|
|
1138
|
+
if (status === 307 || status === 308) return {
|
|
1139
|
+
kind: "redirect",
|
|
1140
|
+
pathname
|
|
1141
|
+
};
|
|
1142
|
+
if (status !== 200) return {
|
|
1143
|
+
kind: "document",
|
|
1144
|
+
named,
|
|
1145
|
+
payload: null
|
|
1146
|
+
};
|
|
1147
|
+
const payload = render.urlFor(payloadPathFor(pathname));
|
|
1148
|
+
return (await writeBody(path.join(dir, "index.rsc"), render.handler, payload)).status === 200 ? {
|
|
1149
|
+
kind: "document",
|
|
1150
|
+
named,
|
|
1151
|
+
payload: new URL(payload).pathname
|
|
1152
|
+
} : failed("render", pathname);
|
|
1153
|
+
};
|
|
1154
|
+
const renderNotFound = async (render, pathname) => {
|
|
1155
|
+
const { status, named } = await writeHtml(path.join(render.clientDir, "404.html"), render, render.urlFor(pathname), { notFoundIsPage: true });
|
|
1156
|
+
return status === 500 ? failed("render", "404.html") : {
|
|
1157
|
+
kind: "document",
|
|
1158
|
+
named,
|
|
1159
|
+
payload: null
|
|
1160
|
+
};
|
|
2433
1161
|
};
|
|
2434
|
-
|
|
2435
|
-
|
|
1162
|
+
const renderShell = async (render, shell, fallbacks) => {
|
|
1163
|
+
const dir = path.join(render.clientDir, dirFor(shell.pathname));
|
|
1164
|
+
const answered = await writeHtml(path.join(dir, "index.html"), render, render.urlFor(shell.pathname), {
|
|
1165
|
+
notFoundIsPage: false,
|
|
1166
|
+
shell: shell.pattern
|
|
1167
|
+
});
|
|
1168
|
+
const named = `${shell.location} (${fallbacks.get(shell.pattern) ?? ""})`;
|
|
1169
|
+
if (answered.status === 500) return failed("render", shell.location);
|
|
1170
|
+
if (answered.status === 404) return failed(answered.notFound ? "shellDisowned" : "shellRefused", shell.location);
|
|
1171
|
+
if (answered.shell === null) return failed("shellTaken", `the shell for ${named} was answered by another route, which took "${FALLBACK_SEGMENT}" as a value`);
|
|
1172
|
+
if (answered.shell !== shell.pattern) return failed("shellTaken", `the shell for ${named} was answered by ${fallbacks.get(answered.shell) ?? answered.shell}, which the table tries first — supply shell locations that pattern cannot match`);
|
|
1173
|
+
return (await writeBody(path.join(dir, "index.rsc"), render.handler, render.urlFor(payloadPathFor(shell.pathname)))).status === 200 ? {
|
|
1174
|
+
kind: "document",
|
|
1175
|
+
named: answered.named,
|
|
1176
|
+
payload: null
|
|
1177
|
+
} : failed("render", shell.location);
|
|
1178
|
+
};
|
|
1179
|
+
/** The shells whose HTML outside its scripts holds the shell pathname. */
|
|
1180
|
+
const leakingShells = async (clientDir, shells) => (await Promise.all(shells.map(async (shell) => {
|
|
1181
|
+
const html = await readFile(path.join(clientDir, dirFor(shell.pathname), "index.html"), "utf8");
|
|
1182
|
+
return writtenOutsideScripts(html).some((written) => written.includes("!fallback")) ? [shell.location] : [];
|
|
1183
|
+
}))).flat();
|
|
1184
|
+
const writeClientFiles = async (clientDir, rendered) => {
|
|
1185
|
+
const documents = rendered.flatMap((each) => each.kind === "document" && each.named !== null ? [each] : []);
|
|
1186
|
+
await writeFile(path.join(clientDir, CLIENT_FILES_PATH.slice(1)), JSON.stringify(clientFiles(new Map(documents.flatMap(({ payload, named }) => payload === null || named === null ? [] : [[payload, named]])), documents.map(({ named }) => named ?? []))));
|
|
1187
|
+
};
|
|
1188
|
+
const writeSitemap = async (clientDir, site, pathnames) => {
|
|
1189
|
+
await writeFile(path.join(clientDir, "sitemap.xml"), sitemap(site, pathnames));
|
|
1190
|
+
};
|
|
1191
|
+
/** The type each route.ts's `GET` answered with, by the file it wrote. */
|
|
1192
|
+
const typesOf = (rendered) => new Map(rendered.flatMap((each) => each.kind === "route" && each.type !== null ? [[fileAt(each.pathname), each.type]] : []));
|
|
1193
|
+
/** What the build says it wrote, after `k8ordo: wrote `. */
|
|
1194
|
+
const summaryOf = (plan, { notFound, sitemap: listed }) => {
|
|
1195
|
+
const shells = plan.shells.length === 0 ? "" : `, ${String(plan.shells.length)} ${plan.shells.length === 1 ? "shell" : "shells"} (${plan.shells.map((shell) => shell.location).join(", ")})`;
|
|
1196
|
+
return `${String(plan.paths.length)} routes${shells}${notFound ? " and 404.html" : ""}${listed ? " and sitemap.xml" : ""}${plan.shells.length === 0 ? "" : " and _redirects"}`;
|
|
1197
|
+
};
|
|
1198
|
+
/**
|
|
1199
|
+
* Writes the HTML the handler answered, and says with which status. A page's
|
|
2436
1200
|
* HTML says the nonce the framework signed its scripts with, which the file
|
|
2437
1201
|
* says as hashes in the application's policy, if it gave one.
|
|
2438
1202
|
*/
|
|
2439
|
-
const
|
|
1203
|
+
const writeHtml = async (file, { handler, csp }, url, { notFoundIsPage, shell }) => {
|
|
2440
1204
|
const response = await handler(new Request(url));
|
|
2441
1205
|
const notFound = response.headers.has(NOT_FOUND_HEADER);
|
|
2442
1206
|
const answered = response.headers.get(SHELL_HEADER);
|
|
@@ -2444,7 +1208,7 @@ const write = async (file, handler, url, csp, { notFoundIsPage, shell }) => {
|
|
|
2444
1208
|
status: response.status,
|
|
2445
1209
|
notFound,
|
|
2446
1210
|
shell: answered,
|
|
2447
|
-
|
|
1211
|
+
named: null
|
|
2448
1212
|
};
|
|
2449
1213
|
if (response.status === 500) {
|
|
2450
1214
|
console.error(`k8ordo: ${url} — ${await response.text()}`);
|
|
@@ -2463,22 +1227,21 @@ const write = async (file, handler, url, csp, { notFoundIsPage, shell }) => {
|
|
|
2463
1227
|
await writeFile(file, Buffer.from(await response.arrayBuffer()));
|
|
2464
1228
|
return written;
|
|
2465
1229
|
}
|
|
2466
|
-
|
|
2467
|
-
|
|
2468
|
-
const named = response.headers.get(CLIENT_DEPS_HEADER);
|
|
1230
|
+
await writeFile(file, asFile(await response.text(), nonce, csp));
|
|
1231
|
+
const said = response.headers.get(CLIENT_DEPS_HEADER);
|
|
2469
1232
|
return {
|
|
2470
1233
|
...written,
|
|
2471
|
-
|
|
1234
|
+
named: said === null ? null : readClientDeps(said)
|
|
2472
1235
|
};
|
|
2473
1236
|
};
|
|
2474
1237
|
/**
|
|
2475
|
-
* Writes
|
|
2476
|
-
* says the type it answered with
|
|
2477
|
-
* it with the type its extension says, and only an adapter that can
|
|
2478
|
-
* file's type (`vercel()`) serves the GET's. Anything but a 200 is not
|
|
2479
|
-
* the site has, and nothing is written.
|
|
1238
|
+
* Writes the body a 200 answered as it is — a route.ts's file, a payload —
|
|
1239
|
+
* and says the type it answered with: a file keeps none, so a static host
|
|
1240
|
+
* serves it with the type its extension says, and only an adapter that can
|
|
1241
|
+
* name a file's type (`vercel()`) serves the GET's. Anything but a 200 is not
|
|
1242
|
+
* a file the site has, and nothing is written.
|
|
2480
1243
|
*/
|
|
2481
|
-
const
|
|
1244
|
+
const writeBody = async (file, handler, url) => {
|
|
2482
1245
|
const response = await handler(new Request(url));
|
|
2483
1246
|
if (response.status !== 200) {
|
|
2484
1247
|
if (response.status === 500) console.error(`k8ordo: ${url} — ${await response.text()}`);
|