@k8ordo/framework 3.0.0 → 4.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.
Files changed (55) hide show
  1. package/README.md +6 -4
  2. package/dist/cli.mjs +3 -3
  3. package/dist/generated.d.mts +12 -13
  4. package/dist/index.d.mts +3 -3
  5. package/dist/index.mjs +1 -1
  6. package/dist/paths-type-DXpmjaOr.d.mts +43 -0
  7. package/dist/runtime/app-router.mjs +1 -1
  8. package/dist/runtime/browser-payloads.mjs +1 -1
  9. package/dist/runtime/cookies.d.mts +2 -0
  10. package/dist/runtime/cookies.mjs +2 -1
  11. package/dist/runtime/ended.d.mts +7 -0
  12. package/dist/runtime/ended.mjs +14 -0
  13. package/dist/runtime/entry.browser.mjs +1 -1
  14. package/dist/runtime/entry.rsc.d.mts +17 -7
  15. package/dist/runtime/entry.rsc.mjs +42 -33
  16. package/dist/runtime/entry.ssr.d.mts +1 -0
  17. package/dist/runtime/entry.ssr.mjs +4 -3
  18. package/dist/runtime/guard.d.mts +15 -10
  19. package/dist/runtime/guard.mjs +8 -2
  20. package/dist/runtime/mount.mjs +1 -1
  21. package/dist/runtime/page-boundary.mjs +2 -2
  22. package/dist/runtime/params.d.mts +5 -4
  23. package/dist/runtime/params.mjs +2 -2
  24. package/dist/runtime/redirect.d.mts +13 -7
  25. package/dist/runtime/redirect.mjs +25 -9
  26. package/dist/runtime/request-scope.d.mts +37 -2
  27. package/dist/runtime/request-scope.mjs +60 -3
  28. package/dist/runtime/request.d.mts +6 -1
  29. package/dist/runtime/request.mjs +7 -2
  30. package/dist/runtime/route.d.mts +4 -2
  31. package/dist/runtime/route.mjs +13 -5
  32. package/dist/runtime/server.d.mts +5 -5
  33. package/dist/runtime/server.mjs +2 -2
  34. package/dist/runtime/shell.d.mts +2 -1
  35. package/dist/serve.d.mts +4 -0
  36. package/dist/serve.mjs +26 -13
  37. package/dist/{static-c-nX9Juk.d.mts → static-Be3xIqd8.d.mts} +19 -12
  38. package/dist/{static-file-BEk_xO5y.mjs → static-file-BS-WEiwu.mjs} +180 -136
  39. package/dist/{static-host-CyAmsL_7.mjs → static-host-tIDLqV8c.mjs} +1 -1
  40. package/dist/vercel.d.mts +18 -1
  41. package/dist/vercel.mjs +104 -7
  42. package/dist/vite.d.mts +6 -3
  43. package/dist/vite.mjs +155 -65
  44. package/docs/GUIDE.md +149 -21
  45. package/docs/llms.txt +102 -47
  46. package/docs/references/actions.md +14 -5
  47. package/docs/references/boundaries.md +23 -2
  48. package/docs/references/csp.md +91 -2
  49. package/docs/references/deploy.md +85 -16
  50. package/docs/references/errors.md +18 -10
  51. package/docs/references/guards.md +100 -29
  52. package/docs/references/params.md +91 -22
  53. package/docs/references/routing.md +171 -31
  54. package/package.json +15 -10
  55. package/dist/paths-type-DtsL8JuC.d.mts +0 -19
package/dist/vite.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { A as emitRoutesModule, C as SHELL_HEADER, D as decodePathname, E as FALLBACK_SEGMENT, F as parseRouteTree, I as slotOf, M as FRAMEWORK, N as ROUTE_METHODS, O as LOCALES_MODULE, P as fallbackShapes, S as SERVER_STYLESHEETS_HEADER, T as readServerStylesheets, _ as suppliedFrom, a as catchAllPath, b as NONCE_HEADER, c as fileAt, d as patternsNeedingPaths, f as patternsOf, g as shadowedShells, h as routeFileRefusals, i as answersOf, j as unreachableRoutes, k as emitRegisterModule, l as isConcrete, m as planRefusals, o as catchAllRefusals, p as planPaths, s as dirFor, v as CLIENT_DEPS_HEADER, w as readClientDeps, x as NOT_FOUND_HEADER, y as CLIENT_FILES_PATH } from "./static-file-BEk_xO5y.mjs";
1
+ import { A as emitRegisterModule, C as SHELL_HEADER, D as decodePathname, E as FALLBACK_SEGMENT, F as fallbackShapes, I as parseRouteTree, L as restDirOf, M as unreachableRoutes, N as ROUTE_METHODS, O as LOCALES_MODULE, P as FRAMEWORK, R as slotOf, S as SERVER_STYLESHEETS_HEADER, T as readServerStylesheets, _ as suppliedFrom, a as answersOf, b as NONCE_HEADER, c as dirFor, f as patternsNeedingPaths, g as shadowedShells, h as routeFileRefusals, i as answeringPatterns, j as emitRoutesModule, k as ROUTES_DIR, l as fileAt, m as planRefusals, o as catchAllPath, p as planPaths, r as SITEMAP_PATHNAME, s as catchAllRefusals, u as isConcrete, v as CLIENT_DEPS_HEADER, w as readClientDeps, x as NOT_FOUND_HEADER, y as CLIENT_FILES_PATH } from "./static-file-BS-WEiwu.mjs";
2
2
  import { a as sharedDir, i as headersRefusal, n as formatHeaders, r as headersPlugin } from "./headers-BxB_jJVk.mjs";
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-CyAmsL_7.mjs";
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-tIDLqV8c.mjs";
4
4
  import { findPackageJSON } from "node:module";
5
5
  import { normalizePathname, withBase, withoutBase } from "@k8ordo/router";
6
6
  import { fileURLToPath, pathToFileURL } from "node:url";
@@ -8,6 +8,7 @@ import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
8
8
  import path from "node:path";
9
9
  import { build, isCSSRequest, parseSync } from "vite";
10
10
  import { transformRscCssExport } from "@vitejs/plugin-rsc/plugin";
11
+ import { getCompatibleVersions } from "baseline-browser-mapping";
11
12
  import { existsSync } from "node:fs";
12
13
  import react from "@vitejs/plugin-react";
13
14
  import rsc, { getPluginApi } from "@vitejs/plugin-rsc";
@@ -37,8 +38,9 @@ const scanRoutes = async (dir) => {
37
38
  };
38
39
  try {
39
40
  return (await walk("")).toSorted();
40
- } catch {
41
- return [];
41
+ } catch (error) {
42
+ if (error.code === "ENOENT" && error.path === dir) throw new Error(`the route files live in ${ROUTES_DIR}/, and ${dir} does not exist`, { cause: error });
43
+ throw error;
42
44
  }
43
45
  };
44
46
  /**
@@ -64,17 +66,8 @@ const READS_EXPORTS = /* @__PURE__ */ new Set([
64
66
  "layout",
65
67
  "route"
66
68
  ]);
67
- /**
68
- * What each page, layout and route.ts exports, by file. A file that cannot be
69
- * read exports nothing.
70
- */
71
- const readExports = async (routesDir, files) => new Map(await Promise.all(files.filter((file) => READS_EXPORTS.has(slotOf(file) ?? "")).map(async (file) => {
72
- try {
73
- return [file, exportsOf(await readFile(path.join(routesDir, file), "utf8"), file)];
74
- } catch {
75
- return [file, /* @__PURE__ */ new Set()];
76
- }
77
- })));
69
+ /** What each page, layout and route.ts exports, by file. */
70
+ const readExports = async (routesDir, files) => new Map(await Promise.all(files.filter((file) => READS_EXPORTS.has(slotOf(file) ?? "")).map(async (file) => [file, exportsOf(await readFile(path.join(routesDir, file), "utf8"), file)])));
78
71
  /**
79
72
  * The pages that export `search` — a url schema of `@k8ordo/state` saying
80
73
  * what of the search they read. Only a page: a layout renders under pages
@@ -96,12 +89,20 @@ const silentRoutes = (exported) => [...exported].filter(([file, names]) => slotO
96
89
  }));
97
90
  /** Whether the application's manifest lists `name`. */
98
91
  const dependsOn = async (root, name) => {
92
+ let text;
99
93
  try {
100
- const manifest = JSON.parse(await readFile(path.join(root, "package.json"), "utf8"));
101
- return name in (manifest.dependencies ?? {}) || name in (manifest.devDependencies ?? {});
102
- } catch {
103
- return false;
94
+ text = await readFile(path.join(root, "package.json"), "utf8");
95
+ } catch (error) {
96
+ if (error.code === "ENOENT") return false;
97
+ throw error;
104
98
  }
99
+ let manifest;
100
+ try {
101
+ manifest = JSON.parse(text);
102
+ } catch (error) {
103
+ throw new Error(`${path.join(root, "package.json")} is not JSON, so which packages the application depends on cannot be read`, { cause: error });
104
+ }
105
+ return name in (manifest.dependencies ?? {}) || name in (manifest.devDependencies ?? {});
105
106
  };
106
107
  /**
107
108
  * Where the application declares its locale set: `null` when it does not
@@ -161,7 +162,6 @@ const generate = async (options) => {
161
162
  });
162
163
  const registerSource = emitRegisterModule({
163
164
  routesModule: "./routes.gen",
164
- stateModule: withState ? "@k8ordo/state" : null,
165
165
  localesModule: localeSet?.exportsLocales === true ? importPath(options.outDir, localeSet.module.replace(/\.ts$/u, "")) : null,
166
166
  mode: options.mode
167
167
  });
@@ -231,6 +231,42 @@ const mdxCss = () => ({
231
231
  };
232
232
  }
233
233
  });
234
+ // ../framework-engine/dist/plugin/targets.mjs
235
+ const NAMES = {
236
+ chrome: ["chrome", "chrome"],
237
+ edge: ["edge", "edge"],
238
+ firefox: ["firefox", "firefox"],
239
+ safari: ["safari", "safari"],
240
+ safari_ios: ["ios", "ios_saf"]
241
+ };
242
+ /** `versions`, as baseline-browser-mapping lists them, in Vite's two forms. */
243
+ const targetsOf = (versions) => {
244
+ const build = [];
245
+ const lightningcss = {};
246
+ for (const { browser, version } of versions) {
247
+ const names = NAMES[browser];
248
+ if (names === void 0) continue;
249
+ const [major = 0, minor = 0, patch = 0] = version.split(".").map(Number);
250
+ build.push(`${names[0]}${version}`);
251
+ lightningcss[names[1]] = major << 16 | minor << 8 | patch;
252
+ }
253
+ return {
254
+ build,
255
+ lightningcss
256
+ };
257
+ };
258
+ /**
259
+ * The browsers that ship every feature Baseline has newly available: the
260
+ * ones the family is written for.
261
+ */
262
+ const newlyAvailableTargets = () => {
263
+ const date = /* @__PURE__ */ new Date();
264
+ date.setMonth(date.getMonth() + 30);
265
+ return targetsOf(getCompatibleVersions({
266
+ widelyAvailableOnDate: date.getTime(),
267
+ suppressWarnings: true
268
+ }));
269
+ };
234
270
  // ../framework-engine/dist/plugin/core.mjs
235
271
  const VIRTUAL_ROUTES = "virtual:k8ordo/routes";
236
272
  const VIRTUAL_LOCALES = "virtual:k8ordo/locales";
@@ -314,6 +350,7 @@ const engine = (options, host) => {
314
350
  let devServer;
315
351
  let generating = Promise.resolve();
316
352
  const frame = /* @__PURE__ */ new Set();
353
+ const targets = newlyAvailableTargets();
317
354
  const runtime = (name) => path.join(host.runtimeDir, `${name}.mjs`);
318
355
  const routesModule = () => path.join(outDir, "routes.gen.ts");
319
356
  const generateOptions = () => ({
@@ -330,8 +367,10 @@ const engine = (options, host) => {
330
367
  const plugin = {
331
368
  name: "k8ordo:engine",
332
369
  enforce: "pre",
333
- config(_config, env) {
370
+ config(config, env) {
334
371
  return {
372
+ ...config.build?.target === void 0 && config.build?.cssTarget === void 0 ? { build: { cssTarget: targets.build } } : {},
373
+ ...config.css?.lightningcss?.targets === void 0 ? { css: { lightningcss: { targets: targets.lightningcss } } } : {},
335
374
  define: {
336
375
  "process.env.NODE_ENV": JSON.stringify(isProduction(env.mode) ? "production" : "development"),
337
376
  "import.meta.env.K8ORDO_MODE": JSON.stringify(host.mode),
@@ -378,17 +417,21 @@ const engine = (options, host) => {
378
417
  }
379
418
  };
380
419
  },
381
- configEnvironment(_name, config) {
420
+ configEnvironment(name, config) {
382
421
  const include = config.optimizeDeps?.include;
383
422
  if (include !== void 0) config.optimizeDeps = {
384
423
  ...config.optimizeDeps,
385
424
  include: include.map((entry) => entry.startsWith("@vitejs/plugin-rsc") ? `${FRAMEWORK} > ${entry}` : entry)
386
425
  };
426
+ if ((config.consumer ?? (name === "client" ? "client" : "server")) === "client" && config.build?.target === void 0) config.build = {
427
+ ...config.build,
428
+ target: targets.build
429
+ };
387
430
  },
388
431
  configResolved(config) {
389
432
  if (!config.base.startsWith("/") || config.base.startsWith("//")) throw new Error(`k8ordo serves its pages under Vite's base, so base has to be a path from the root, like '/docs/' — got '${config.base}'`);
390
433
  ({root, logger} = config);
391
- routesDir = path.resolve(root, options.routesDir ?? "src/routes");
434
+ routesDir = path.resolve(root, ROUTES_DIR);
392
435
  localesModule = path.resolve(root, LOCALES_MODULE);
393
436
  outDir = path.resolve(root, OUT_DIR);
394
437
  },
@@ -480,6 +523,21 @@ const serverActionModules = (config) => {
480
523
  * `node_modules`; the question here is about the id in hand.
481
524
  */
482
525
  const isServerActionModule = (config, id) => getPluginApi(config)?.manager.serverReferences.claimMap.has(id) ?? false;
526
+ // src/options.ts
527
+ const STATIC_ONLY = ["site", "csp"];
528
+ const TAKEN = {
529
+ static: [
530
+ "mode",
531
+ "reactCompiler",
532
+ "headers",
533
+ ...STATIC_ONLY
534
+ ],
535
+ server: [
536
+ "mode",
537
+ "reactCompiler",
538
+ "headers"
539
+ ]
540
+ };
483
541
  // src/precompress.ts
484
542
  const compress = {
485
543
  br: (data) => promisify(brotliCompress)(data, { params: {
@@ -601,12 +659,10 @@ const serverMode = () => ({
601
659
  // src/documents.ts
602
660
  const escapeMarkup = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&apos;");
603
661
  /**
604
- * The sitemap protocol's one required element per URL: `<loc>`. The site is
605
- * taken as given, without a trailing slash, and the pathname as the URL
606
- * carries it, escaped for XML.
662
+ * The sitemap protocol's one required element per URL: `<loc>`, the origin
663
+ * followed by the pathname as the URL carries it, escaped for XML.
607
664
  */
608
- const sitemap = (site, pathnames) => {
609
- const origin = site.endsWith("/") ? site.slice(0, -1) : site;
665
+ const sitemap = (origin, pathnames) => {
610
666
  return `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${pathnames.toSorted().map((pathname) => ` <url><loc>${escapeMarkup(`${origin}${pathname}`)}</loc></url>`).join("\n")}\n</urlset>\n`;
611
667
  };
612
668
  /**
@@ -695,7 +751,18 @@ const policyProblems = (policy) => {
695
751
  const SCRIPT = /<script\b([^>]*)>([\s\S]*?)<\/script[\s/>]/giu;
696
752
  const ORDER_STYLE = new RegExp(`<style\\b[^>]*\\sdata-href="${STYLESHEET_ORDER_HREF}"[^>]*>([^<]*)</style>`, "u");
697
753
  const CHARSET = /^<meta(?:\s[^>]*)?\scharset=[^>]*>/iu;
698
- const hashOf = (source) => `'sha256-${createHash("sha256").update(source.replaceAll("\r\n", "\n").replaceAll("\r", "\n")).digest("base64")}'`;
754
+ const asParsed = (source) => source.replaceAll("\r\n", "\n").replaceAll("\r", "\n");
755
+ const hashOf = (source) => `'sha256-${createHash("sha256").update(asParsed(source)).digest("base64")}'`;
756
+ /**
757
+ * An inline script of the application's as a CSP source, `'sha256-…'`: the
758
+ * hash of `text`, the string its `<script>` is given, for static mode's
759
+ * `csp` option, which adds the hashes of the framework's own scripts alone.
760
+ * A line break counts as the browser parses the page, a CR LF as one LF.
761
+ */
762
+ const scriptHash = async (text) => {
763
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(asParsed(text)));
764
+ return `'sha256-${btoa(String.fromCodePoint(...new Uint8Array(digest)))}'`;
765
+ };
699
766
  /**
700
767
  * The policy as the page's `<meta>` says it: the application's directives,
701
768
  * with the hashes added wherever a script element is decided —
@@ -789,7 +856,6 @@ const filesBelow = async (dir) => (await readdir(dir, {
789
856
  withFileTypes: true
790
857
  })).filter((entry) => entry.isFile()).map((entry) => path.relative(dir, path.join(entry.parentPath, entry.name)).split(path.sep).join("/")).toSorted();
791
858
  const messageOf = (error) => error instanceof Error ? error.message : String(error);
792
- const ORIGIN = "http://k8ordo.localhost";
793
859
  const WANTS_SERVER = "this application wants mode: 'server'";
794
860
  /** The entry whose every export answers a request. */
795
861
  const SERVER_ENTRY = "@k8ordo/framework/server";
@@ -808,6 +874,12 @@ const actionRefusal = (files) => `static build cannot ship Server Actions — a
808
874
  */
809
875
  const guardRefusal = (files) => `static build cannot run guard.ts — a file has no request to guard, and these are guards:\n${files.map((file) => ` ${file}`).join("\n")}\n${WANTS_SERVER}`;
810
876
  /**
877
+ * A `[...name]` directory answers pathnames of any depth, and a build writes
878
+ * a file per pathname it is told of — `paths.ts` gives one parameter's values,
879
+ * one segment each. Named every one at once.
880
+ */
881
+ const restRefusal = (dirs) => `static build cannot write a [...name] directory — it answers a pathname of any depth, which only a request names, and ${dirs.length === 1 ? "this is one" : "these are"}:\n${dirs.map((dir) => ` ${dir}`).join("\n")}\n${WANTS_SERVER}`;
882
+ /**
811
883
  * A page that reads the search is rendered for each search it is given, and a
812
884
  * file is the same whatever the search holds. Named every one at once.
813
885
  */
@@ -834,8 +906,9 @@ const READ_BY_NAME = /* @__PURE__ */ new Set(["route", "page"]);
834
906
  * There is no server here, and the build refuses a Server Action, because a
835
907
  * file cannot receive one.
836
908
  */
837
- const staticMode = (options) => {
909
+ const staticMode = (options, host) => {
838
910
  const { csp } = options;
911
+ const { origin } = new URL(options.site);
839
912
  const unwritablePolicy = csp === void 0 ? [] : policyProblems(csp);
840
913
  if (unwritablePolicy.length > 0) throw new Error(`the "csp" option cannot go into a page's <meta> as it is:\n${unwritablePolicy.map((problem) => ` ${problem}`).join("\n")}`);
841
914
  let root = "";
@@ -858,24 +931,24 @@ const staticMode = (options) => {
858
931
  failed,
859
932
  shapes: failed ? [] : fallbackShapes(tree),
860
933
  needing: failed ? [] : patternsNeedingPaths(tree).map((pathname) => new URLPattern({ pathname })),
861
- declared: failed ? [] : patternsOf(tree).filter((pattern) => !pattern.endsWith("/*")).map((pattern) => ({
934
+ declared: failed ? [] : answeringPatterns(tree).map(({ pattern }) => ({
862
935
  pattern,
863
936
  matcher: new URLPattern({ pathname: pattern })
864
937
  }))
865
938
  };
866
939
  })();
867
940
  /**
868
- * A paths.ts under `vite dev`, read through the RSC environment's runner —
869
- * the graph the pages are in, so it sees the application's aliases and an
870
- * edit to it, or to what it imports, is what the next call reads.
941
+ * A paths.ts under `vite dev`, asked through the handler's own entry in the
942
+ * RSC environment's runner — the graph the pages are in, so it sees the
943
+ * application's aliases, an edit to it, or to what it imports, is what the
944
+ * next call reads, and it receives the params above as the build hands them.
871
945
  */
872
- const devValues = async (file, params) => {
946
+ const devValues = async (file, above) => {
873
947
  const environment = devServer?.environments.rsc;
874
948
  if (environment === void 0 || !("runner" in environment)) throw new Error("the rsc environment cannot run a paths.ts");
875
949
  const { runner } = environment;
876
- const { default: values } = await runner.import(path.join(routesDir, file));
877
- if (typeof values !== "function") throw new TypeError(`${fromRoot(file)} has to export default a function returning its parameter's values`);
878
- return values(params);
950
+ const { pathValues } = await runner.import(path.join(host.runtimeDir, "entry.rsc.mjs"));
951
+ return pathValues(file, above);
879
952
  };
880
953
  /**
881
954
  * What the build would write, as the paths.ts files say now. Kept until a
@@ -899,7 +972,7 @@ const staticMode = (options) => {
899
972
  }
900
973
  return NO_PLAN;
901
974
  }
902
- const plan = planPaths(tree, supplied.locations);
975
+ const plan = planPaths(tree, supplied);
903
976
  for (const refusal of [...supplied.problems, ...planRefusals(plan, shadowedShells(tree, plan.shells, new Set(plan.paths)))]) {
904
977
  if (warned.has(refusal)) continue;
905
978
  warned.add(refusal);
@@ -924,7 +997,7 @@ const staticMode = (options) => {
924
997
  */
925
998
  const answerUnbuilt = async (request, response) => {
926
999
  if (request.method !== "GET" && request.method !== "HEAD") return false;
927
- const url = new URL(request.originalUrl ?? request.url ?? "/", ORIGIN);
1000
+ const url = new URL(request.originalUrl ?? request.url ?? "/", origin);
928
1001
  const own = withoutBase(url.pathname, base);
929
1002
  if (own === null) return false;
930
1003
  const payload = isPayloadPath(own);
@@ -1008,11 +1081,13 @@ const staticMode = (options) => {
1008
1081
  async handler() {
1009
1082
  const files = await scanRoutes(routesDir);
1010
1083
  const guards = files.filter((file) => slotOf(file) === "guard").map((file) => fromRoot(file));
1084
+ const restDirs = [...new Set(files.flatMap((file) => restDirOf(file) ?? []))].map((dir) => fromRoot(dir));
1011
1085
  const exported = await readExports(routesDir, files);
1012
1086
  const routes = [...exported].filter(([file]) => slotOf(file) === "route").map(([file, names]) => [fromRoot(file), unwritable(names)]).filter(([, methods]) => methods.length > 0);
1013
1087
  const searching = [...pagesReadingSearch(exported)].map((file) => fromRoot(file));
1014
1088
  const reexporting = [...exported].filter(([file, names]) => READ_BY_NAME.has(slotOf(file) ?? "") && names.has("*")).map(([file]) => fromRoot(file));
1015
1089
  const refusals = [
1090
+ ...restDirs.length > 0 ? [restRefusal(restDirs)] : [],
1016
1091
  ...guards.length > 0 ? [guardRefusal(guards)] : [],
1017
1092
  ...routes.length > 0 ? [routeRefusal(routes)] : [],
1018
1093
  ...searching.length > 0 ? [searchRefusal(searching)] : [],
@@ -1025,7 +1100,7 @@ const staticMode = (options) => {
1025
1100
  name: "k8ordo:static",
1026
1101
  configResolved(config) {
1027
1102
  ({root, plugins, base, logger} = config);
1028
- routesDir = path.resolve(root, options.routesDir ?? "src/routes");
1103
+ routesDir = path.resolve(root, ROUTES_DIR);
1029
1104
  },
1030
1105
  configureServer: {
1031
1106
  order: "pre",
@@ -1041,7 +1116,7 @@ const staticMode = (options) => {
1041
1116
  const client = path.resolve(config.root, config.environments.client?.build.outDir ?? "dist/client");
1042
1117
  const rules = await readRules(client);
1043
1118
  const answeredHere = async (request, response) => {
1044
- const url = new URL(`${ORIGIN}${request.url ?? "/"}`);
1119
+ const url = new URL(`${origin}${request.url ?? "/"}`);
1045
1120
  if (withoutBase(url.pathname, config.base) === null) return false;
1046
1121
  if (request.method !== "GET" && request.method !== "HEAD") {
1047
1122
  response.writeHead(405, { allow: "GET, HEAD" }).end();
@@ -1090,6 +1165,8 @@ const staticMode = (options) => {
1090
1165
  const [module = id] = id.split("?");
1091
1166
  const file = path.relative(routesDir, module).split(path.sep).join("/");
1092
1167
  const slot = file.startsWith("..") ? null : slotOf(file);
1168
+ const restDir = file.startsWith("..") ? null : restDirOf(file);
1169
+ if (restDir !== null) throw new Error(restRefusal([fromRoot(restDir)]));
1093
1170
  if (slot === "guard") throw new Error(guardRefusal([path.relative(root, module)]));
1094
1171
  const names = READ_BY_NAME.has(slot ?? "") ? exportsOf(await readFile(module, "utf8"), file) : /* @__PURE__ */ new Set();
1095
1172
  if (names.has("*")) throw new Error(reexportRefusal([path.relative(root, module)]));
@@ -1109,7 +1186,7 @@ const staticMode = (options) => {
1109
1186
  if (rscOut === void 0 || client === void 0) throw new Error("static build ran without the rsc/client builds");
1110
1187
  const built = await import(pathToFileURL(path.resolve(root, rscOut, "index.js")).href);
1111
1188
  const supplied = await suppliedFrom(tree, built.pathValues);
1112
- const plan = planPaths(tree, supplied.locations);
1189
+ const plan = planPaths(tree, supplied);
1113
1190
  const answers = answersOf(tree, plan.paths);
1114
1191
  const actions = serverActionModules(builder.config);
1115
1192
  const importers = [...serverImporters].toSorted();
@@ -1123,7 +1200,6 @@ const staticMode = (options) => {
1123
1200
  ];
1124
1201
  if (refusals.length > 0) throw new Error(refusals.join("\n\n"));
1125
1202
  const clientDir = path.resolve(root, client.build.outDir);
1126
- const origin = options.site === void 0 ? ORIGIN : new URL(options.site).origin;
1127
1203
  const render = {
1128
1204
  handler: built.default,
1129
1205
  payloadOf: built.payloadOf,
@@ -1143,8 +1219,8 @@ const staticMode = (options) => {
1143
1219
  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`);
1144
1220
  await writeClientFiles(clientDir, rendered);
1145
1221
  const notPages = rendered.flatMap((each) => each.kind === "route" || each.kind === "redirect" ? [each.pathname] : []);
1146
- const listed = answers.get("/sitemap.xml")?.kind === "route" ? void 0 : options.site;
1147
- if (listed !== void 0) await writeSitemap(clientDir, listed, plan.paths.filter((pathname) => !notPages.includes(pathname)).map((pathname) => withBase(pathname, base)));
1222
+ const listed = answers.get(SITEMAP_PATHNAME)?.kind !== "route";
1223
+ if (listed) await writeSitemap(clientDir, origin, plan.paths.filter((pathname) => !notPages.includes(pathname)).map((pathname) => withBase(pathname, base)));
1148
1224
  const adapter = adapterOf(builder.config.plugins);
1149
1225
  const declared = options.headers ?? {};
1150
1226
  if (Object.keys(declared).length > 0) await writeFile(path.join(clientDir, "_headers"), formatHeaders(declared, await ownPublicFile(client.build.copyPublicDir ? builder.config.publicDir : "", "_headers")));
@@ -1164,7 +1240,7 @@ const staticMode = (options) => {
1164
1240
  });
1165
1241
  builder.config.logger.info(`k8ordo: wrote ${summaryOf(plan, {
1166
1242
  notFound: notFoundAt !== null,
1167
- sitemap: listed !== void 0
1243
+ sitemap: listed
1168
1244
  })}`);
1169
1245
  }
1170
1246
  }
@@ -1251,11 +1327,6 @@ const renderPage = async (render, pathname) => {
1251
1327
  kind: "redirect",
1252
1328
  pathname
1253
1329
  };
1254
- if (status !== 200) return {
1255
- kind: "document",
1256
- files,
1257
- payload: null
1258
- };
1259
1330
  if (payload === null) return failed("render", pathname);
1260
1331
  await writeFile(path.join(dir, "index.rsc"), Buffer.from(payload));
1261
1332
  return {
@@ -1300,8 +1371,8 @@ const writeClientFiles = async (clientDir, rendered) => {
1300
1371
  const documents = rendered.flatMap((each) => each.kind === "document" && each.files !== null ? [each] : []);
1301
1372
  await writeFile(path.join(clientDir, CLIENT_FILES_PATH.slice(1)), JSON.stringify(clientFiles(new Map(documents.flatMap(({ payload, files }) => payload === null || files === null ? [] : [[payload, files]])), documents.map(({ files }) => files ?? []))));
1302
1373
  };
1303
- const writeSitemap = async (clientDir, site, pathnames) => {
1304
- await writeFile(path.join(clientDir, "sitemap.xml"), sitemap(site, pathnames));
1374
+ const writeSitemap = async (clientDir, origin, pathnames) => {
1375
+ await writeFile(path.join(clientDir, "sitemap.xml"), sitemap(origin, pathnames));
1305
1376
  };
1306
1377
  /** The type each route.ts's `GET` answered with, by the file it wrote. */
1307
1378
  const typesOf = (rendered) => new Map(rendered.flatMap((each) => each.kind === "route" && each.type !== null ? [[fileAt(each.pathname), each.type]] : []));
@@ -1339,10 +1410,7 @@ const writeHtml = async (file, { handler, payloadOf, csp }, url, { notFoundIsPag
1339
1410
  return written;
1340
1411
  }
1341
1412
  const nonce = response.headers.get(NONCE_HEADER);
1342
- if (nonce === null) {
1343
- await writeFile(file, Buffer.from(await response.arrayBuffer()));
1344
- return written;
1345
- }
1413
+ if (nonce === null) throw new Error(`${url} answered HTML without saying the nonce it signed its scripts with`);
1346
1414
  await writeFile(file, asFile(await response.text(), nonce, csp));
1347
1415
  const named = response.headers.get(CLIENT_DEPS_HEADER);
1348
1416
  const linked = response.headers.get(SERVER_STYLESHEETS_HEADER);
@@ -1376,20 +1444,42 @@ const writeBody = async (file, handler, url) => {
1376
1444
  };
1377
1445
  // src/vite.ts
1378
1446
  const RUNTIME_DIR = fileURLToPath(new URL("./runtime/", import.meta.url));
1379
- const STATIC_ONLY = ["site", "csp"];
1380
1447
  const shown = (value) => typeof value === "string" ? `'${value}'` : String(value);
1448
+ const kindOf = (value) => {
1449
+ if (value === null) return "null";
1450
+ if (Array.isArray(value)) return "an array";
1451
+ if (typeof value === "object") return "an object";
1452
+ return `a ${typeof value}`;
1453
+ };
1454
+ const notAnOrigin = (value) => {
1455
+ if (value === void 0) return "and got none";
1456
+ if (typeof value !== "string") return `and the value is not a string but ${kindOf(value)}`;
1457
+ if (value.includes("@")) return "and the site has an @, which no origin has (a username or a password comes before one, so the value is left out)";
1458
+ if (!URL.canParse(value)) return `and ${shown(value)} is not a URL`;
1459
+ const url = new URL(value);
1460
+ if (url.protocol !== "http:" && url.protocol !== "https:") return `and ${shown(value)} is served over ${url.protocol}, not http: or https:`;
1461
+ if (url.pathname !== "/") return `and ${shown(value)} has a path, ${url.pathname} — where under the origin the site sits is Vite's base`;
1462
+ if (url.search !== "") return `and ${shown(value)} has a query, ${url.search}`;
1463
+ if (url.hash !== "") return `and ${shown(value)} has a fragment, ${url.hash}`;
1464
+ return null;
1465
+ };
1381
1466
  /**
1382
1467
  * What the type already says, said again when the config is loaded: a
1383
1468
  * `vite.config.js`, or a `vite.config.ts` outside the tsconfig, is never
1384
1469
  * type-checked, and the options the type refuses do not fail on their own —
1385
- * a mode that is not `'static'` builds no files, and a `csp` under
1386
- * `mode: 'server'` is a policy the application believes it has.
1470
+ * a mode that is not `'static'` builds no files, a `csp` under
1471
+ * `mode: 'server'` is a policy the application believes it has, and a key
1472
+ * spelt wrong is an option that silently does nothing.
1387
1473
  */
1388
1474
  const checked = (options) => {
1389
1475
  const given = options ?? {};
1390
1476
  const { mode } = given;
1391
1477
  if (mode !== "static" && mode !== "server") throw new Error(`framework() needs mode: 'static' or 'server', and got ${shown(mode)}`);
1392
- if (given.paths !== void 0) throw new Error("framework() takes no paths — a parameter's values come from a paths.ts in its directory under routes/");
1478
+ const taken = TAKEN[mode];
1479
+ const unknown = Object.keys(given).filter((name) => given[name] !== void 0 && !taken.includes(name) && !STATIC_ONLY.includes(name));
1480
+ if (unknown.length > 0) throw new Error(`framework() takes no ${unknown.join(", ")} — under mode: '${mode}' it takes ${taken.join(", ")}`);
1481
+ const notOrigin = mode === "static" ? notAnOrigin(given.site) : null;
1482
+ if (notOrigin !== null) throw new Error(`mode: 'static' needs site, the origin the site is served from, like 'https://example.com' — ${notOrigin}`);
1393
1483
  const refused = headersRefusal(given.headers);
1394
1484
  if (refused !== null) throw new Error(refused);
1395
1485
  const staticOnly = STATIC_ONLY.filter((name) => given[name] !== void 0);
@@ -1409,7 +1499,7 @@ const framework = (options) => {
1409
1499
  mode: valid.mode,
1410
1500
  runtimeDir: RUNTIME_DIR
1411
1501
  }),
1412
- ...valid.mode === "static" ? staticMode(valid) : [serverMode()]
1502
+ ...valid.mode === "static" ? staticMode(valid, { runtimeDir: RUNTIME_DIR }) : [serverMode()]
1413
1503
  ];
1414
1504
  };
1415
- export { framework };
1505
+ export { framework, scriptHash };