@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.
Files changed (57) hide show
  1. package/README.md +1 -1
  2. package/dist/generated.d.mts +23 -2
  3. package/dist/runtime/app-router.d.mts +10 -10
  4. package/dist/runtime/app-router.mjs +119 -83
  5. package/dist/runtime/browser-payloads.mjs +2 -1
  6. package/dist/runtime/client-files.d.mts +11 -0
  7. package/dist/runtime/client-files.mjs +42 -0
  8. package/dist/runtime/client-ready.d.mts +3 -2
  9. package/dist/runtime/document-root.mjs +1 -1
  10. package/dist/runtime/entry.browser.d.mts +1 -1
  11. package/dist/runtime/entry.browser.mjs +8 -12
  12. package/dist/runtime/entry.rsc.mjs +148 -102
  13. package/dist/runtime/entry.ssr.d.mts +21 -1
  14. package/dist/runtime/entry.ssr.mjs +10 -13
  15. package/dist/runtime/head-scripts.d.mts +18 -0
  16. package/dist/runtime/head-scripts.mjs +159 -0
  17. package/dist/runtime/hydrating-pathname.d.mts +16 -0
  18. package/dist/runtime/hydrating-pathname.mjs +26 -0
  19. package/dist/runtime/mount.d.mts +16 -11
  20. package/dist/runtime/mount.mjs +29 -18
  21. package/dist/runtime/payload.d.mts +22 -23
  22. package/dist/runtime/payload.mjs +11 -16
  23. package/dist/runtime/prefetch.d.mts +60 -25
  24. package/dist/runtime/prefetch.mjs +166 -38
  25. package/dist/runtime/recover.d.mts +2 -0
  26. package/dist/runtime/recover.mjs +11 -7
  27. package/dist/runtime/redirect.d.mts +20 -14
  28. package/dist/runtime/redirect.mjs +42 -15
  29. package/dist/runtime/request-scope.d.mts +1 -1
  30. package/dist/runtime/request-scope.mjs +11 -23
  31. package/dist/runtime/server.d.mts +6 -0
  32. package/dist/runtime/server.mjs +3 -0
  33. package/dist/runtime/stylesheets.d.mts +13 -0
  34. package/dist/runtime/stylesheets.mjs +15 -0
  35. package/dist/serve.d.mts +1 -0
  36. package/dist/serve.mjs +5 -11
  37. package/dist/{static-6z8_6B1U.d.mts → static-DnbgGIoy.d.mts} +2 -1
  38. package/dist/static-file-BAjwBMMl.mjs +1274 -0
  39. package/dist/{static-host-C6D_11Gp.mjs → static-host-B-1fAfAw.mjs} +49 -74
  40. package/dist/vercel.d.mts +1 -2
  41. package/dist/vercel.mjs +20 -20
  42. package/dist/vite.d.mts +1 -1
  43. package/dist/vite.mjs +232 -1469
  44. package/docs/GUIDE.md +6 -3
  45. package/docs/llms.txt +8 -4
  46. package/docs/references/csp.md +11 -9
  47. package/docs/references/deploy.md +17 -20
  48. package/docs/references/errors.md +0 -34
  49. package/docs/references/params.md +5 -5
  50. package/docs/references/routing.md +104 -20
  51. package/package.json +6 -6
  52. package/dist/runtime/redirect-file.d.mts +0 -20
  53. package/dist/runtime/redirect-file.mjs +0 -42
  54. package/dist/runtime/tree-pathname.d.mts +0 -2
  55. package/dist/runtime/tree-pathname.mjs +0 -11
  56. package/dist/server.d.mts +0 -110
  57. package/dist/server.mjs +0 -97
@@ -1,39 +1,10 @@
1
+ import { b as FALLBACK_SEGMENT, c as isParamSegment, n as safeJoin, t as isFile } from "./static-file-BAjwBMMl.mjs";
1
2
  import { normalizePathname, withBase, withoutBase } from "@k8ordo/router";
2
- import { readFile, stat } from "node:fs/promises";
3
+ import { readFile } from "node:fs/promises";
3
4
  import path from "node:path";
4
5
  import { constants, createBrotliCompress, createGzip } from "node:zlib";
5
6
  import compressible from "compressible";
6
7
  import Negotiator from "negotiator";
7
- // ../framework-engine/dist/runtime/pathname.mjs
8
- /**
9
- * A pathname as the URL carries it, decoded for the filesystem — the one
10
- * thing the static writer and the server's file lookup both have to do
11
- * before deciding whether the result may name a file. `null` for an escape
12
- * that cannot be decoded or a NUL byte, neither of which is a name.
13
- */
14
- const decodePathname = (pathname) => {
15
- let decoded;
16
- try {
17
- decoded = decodeURIComponent(pathname);
18
- } catch {
19
- return null;
20
- }
21
- return decoded.includes("\0") ? null : decoded;
22
- };
23
- /**
24
- * A segment no route declares: a pathname that only a catch-all answers is
25
- * built with it — the static build's `404.html`, and the handler's search
26
- * for the not-found nearest a page that said `notFound()`.
27
- */
28
- const NOT_FOUND_SEGMENT = "__k8ordo-not-found__";
29
- /**
30
- * The segment a shell is written under, in place of each value it leaves to
31
- * the browser: `/ja/posts/!fallback`. No route directory can be named it (`!`
32
- * is outside the grammar's literal segments), and neither
33
- * `encodeURIComponent` nor the URL parser rewrites `!`, so a host that
34
- * re-encodes a rewrite target finds the directory under the same spelling.
35
- */
36
- const FALLBACK_SEGMENT = "!fallback";
37
8
  // ../framework-engine/dist/runtime/payload-path.mjs
38
9
  /**
39
10
  * Where a page's RSC payload lives. It has to be a plain path, not a header
@@ -88,7 +59,6 @@ const BUILT_COMMENT = "# @k8ordo/framework: built URLs the rules below would als
88
59
  const SHELL_COMMENT = "# @k8ordo/framework: values the build did not write, answered by their fallback.tsx's shell";
89
60
  /** What Cloudflare reads as a placeholder: `:` and a letter, anywhere. */
90
61
  const PLACEHOLDER = /:[A-Za-z]\w*/u;
91
- const PARAM_SEGMENT = /^:[A-Za-z_]\w*$/u;
92
62
  const decodeSegment = (segment) => {
93
63
  try {
94
64
  return decodeURIComponent(segment);
@@ -135,7 +105,7 @@ const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
135
105
  */
136
106
  const shellRules = (shells, base) => {
137
107
  const patterns = [...new Set(shells.map((shell) => shell.pattern))];
138
- const known = (shell) => shell.location.split("/").filter((segment) => segment !== "" && !PARAM_SEGMENT.test(segment)).length;
108
+ const known = (shell) => shell.location.split("/").filter((segment) => segment !== "" && !isParamSegment(segment)).length;
139
109
  const ordered = shells.toSorted((a, b) => patterns.indexOf(a.pattern) - patterns.indexOf(b.pattern) || known(b) - known(a) || compare(a.location, b.location));
140
110
  const documents = [];
141
111
  const payloads = [];
@@ -146,7 +116,7 @@ const shellRules = (shells, base) => {
146
116
  from: ["", ""],
147
117
  to: ""
148
118
  };
149
- if (!PARAM_SEGMENT.test(segment)) {
119
+ if (!isParamSegment(segment)) {
150
120
  const [sent, canonical] = spellingsOf(segment);
151
121
  return {
152
122
  from: [sent, canonical],
@@ -175,10 +145,37 @@ const shellRules = (shells, base) => {
175
145
  }
176
146
  return byFrom([...documents, ...payloads]);
177
147
  };
148
+ const PLACEHOLDER_OR_SPLAT = new RegExp(`(${PLACEHOLDER.source}|\\*)`, "u");
178
149
  /** A `from` as Cloudflare matches it: anchored, a placeholder one segment. */
179
- const cloudflarePattern = (from) => new RegExp(`^${from.split(/(:[A-Za-z]\w*|\*)/u).map((part, index) => index % 2 === 0 ? RegExp.escape(part) : part === "*" ? ".*" : "[^/]+").join("")}$`, "u");
150
+ const cloudflarePattern = (from) => new RegExp(`^${from.split(PLACEHOLDER_OR_SPLAT).map((part, index) => index % 2 === 0 ? RegExp.escape(part) : part === "*" ? ".*" : "[^/]+").join("")}$`, "u");
180
151
  /** Whether Cloudflare's matching of `from` takes the pathname. */
181
152
  const cloudflareMatches = (from, pathname) => cloudflarePattern(from).test(pathname);
153
+ /** The first of the rules whose `from` Cloudflare's matching takes a URL with. */
154
+ const firstMatchOf = (rules) => {
155
+ const matchers = rules.map((rule) => ({
156
+ rule,
157
+ pattern: cloudflarePattern(rule.from)
158
+ }));
159
+ return (url) => matchers.find(({ pattern }) => pattern.test(url))?.rule;
160
+ };
161
+ /**
162
+ * The payload URL of each built URL that is not a page — a `redirect.ts`, a
163
+ * `route.ts`'s file — that a shell's payload rule would catch, as a browser
164
+ * sends it and canonically, answered with that shell's HTML: a client
165
+ * navigation to it then becomes a document load instead of rendering the
166
+ * shell.
167
+ */
168
+ const notPageRules = (notPages, shells, base) => {
169
+ const firstMatch = firstMatchOf(shells);
170
+ return notPages.flatMap((page) => pathSpellings(payloadPathFor(page)).flatMap((spelled) => {
171
+ const from = withBase(spelled, base);
172
+ const rule = firstMatch(from);
173
+ return rule?.to.endsWith("/index.rsc") === true ? [{
174
+ from,
175
+ to: rule.to.slice(0, -9)
176
+ }] : [];
177
+ }));
178
+ };
182
179
  /** The files a host serves that no rule needs to repeat. */
183
180
  const isOwnFile = (file) => file === "_redirects" || file === "_headers" || file.split("/").includes("!fallback");
184
181
  /** The URLs a file answers at: itself, and a page's directory or name. */
@@ -194,24 +191,17 @@ const urlsOf = (file) => {
194
191
  * itself (Cloudflare applies rules before files, and a static rule is looked
195
192
  * up first) — as a browser sends it and canonically, both answered with the
196
193
  * canonical spelling, which Cloudflare re-encodes a target into and would
197
- * otherwise redirect to — and the payload URL of a built URL that is not a page — a
198
- * `redirect.ts` or a `route.ts` file — answered with the shell's HTML, so a
199
- * client navigation to it becomes a document load instead of rendering the
200
- * shell. A URL a rule could not list as itself (Cloudflare and Netlify read
201
- * `:b` in `/a:b` as a placeholder, `*` as a splat) is left out and returned
202
- * in `unlisted`; a `from` the application's own rules already have is left
203
- * to them.
194
+ * otherwise redirect to — and `notPageRules`. A URL a rule could not list as
195
+ * itself (Cloudflare and Netlify read `:b` in `/a:b` as a placeholder, `*` as
196
+ * a splat) is left out and returned in `unlisted`; a `from` the
197
+ * application's own rules already have is left to them.
204
198
  *
205
199
  * @param files the client build's files, relative to it, POSIX separators
206
200
  * @param notPages pathnames written without a payload, in the table's terms
207
201
  * @param own the `from`s of the application's own `_redirects`
208
202
  */
209
203
  const builtRules = (files, notPages, shells, own, base) => {
210
- const matchers = shells.map((rule) => ({
211
- rule,
212
- pattern: cloudflarePattern(rule.from)
213
- }));
214
- const firstMatch = (url) => matchers.find(({ pattern }) => pattern.test(url))?.rule;
204
+ const firstMatch = firstMatchOf(shells);
215
205
  const rules = [];
216
206
  const unlisted = /* @__PURE__ */ new Set();
217
207
  const list = (from, to) => {
@@ -236,16 +226,21 @@ const builtRules = (files, notPages, shells, own, base) => {
236
226
  }
237
227
  }
238
228
  }
239
- for (const page of notPages) for (const spelled of pathSpellings(payloadPathFor(page))) {
240
- const from = withBase(spelled, base);
241
- const rule = firstMatch(from);
242
- if (rule?.to.endsWith("/index.rsc") === true) list(from, rule.to.slice(0, -9));
243
- }
229
+ for (const { from, to } of notPageRules(notPages, shells, base)) list(from, to);
244
230
  return {
245
231
  rules: byFrom(rules).toSorted((a, b) => compare(a.from, b.from)),
246
232
  unlisted: [...unlisted].toSorted(compare)
247
233
  };
248
234
  };
235
+ /**
236
+ * What a host that serves its files first applies once none answered:
237
+ * `notPageRules`, then the shells' — `_redirects`' order, its built URLs'
238
+ * own rules aside, which such a host has no need of.
239
+ */
240
+ const rewritesAfterFiles = (shells, notPages, base) => {
241
+ const shellRewrites = shellRules(shells, base);
242
+ return [...byFrom(notPageRules(notPages, shellRewrites, base)).toSorted((a, b) => compare(a.from, b.from)), ...shellRewrites];
243
+ };
249
244
  const lineOf = (rule) => `${rule.from} ${rule.to} 200`;
250
245
  /**
251
246
  * The `_redirects` file: the built URLs, the application's own rules
@@ -324,32 +319,12 @@ const rewriteFor = (rules, pathname) => {
324
319
  const wanted = segmentsOf(rule.from);
325
320
  if (wanted.length === given.length && wanted.every((segment, index) => {
326
321
  const at = given[index];
327
- return PARAM_SEGMENT.test(segment) ? at !== "" : segment === at;
322
+ return isParamSegment(segment) ? at !== "" : segment === at;
328
323
  })) return rule.to;
329
324
  }
330
325
  return null;
331
326
  };
332
- // src/static-file.ts
333
- /**
334
- * Where a request pathname is allowed to land inside the build output.
335
- * Traversal is not a case to weigh at request time: a URL may only ever name
336
- * a file under the client build, and anything else resolves to nothing.
337
- */
338
- const safeJoin = (root, pathname) => {
339
- const decoded = decodePathname(pathname);
340
- if (decoded === null) return null;
341
- const resolved = path.resolve(root, `.${path.posix.normalize(decoded)}`);
342
- if (resolved !== root && !resolved.startsWith(root + path.sep)) return null;
343
- return resolved;
344
- };
345
327
  // src/static-host.ts
346
- const isFile = async (candidate) => {
347
- try {
348
- return (await stat(candidate)).isFile();
349
- } catch {
350
- return false;
351
- }
352
- };
353
328
  /** The file a URL names in the client build: itself, or a directory's index.html. */
354
329
  const fileAt = async (client, pathname, base) => {
355
330
  const own = withoutBase(pathname, base);
@@ -398,4 +373,4 @@ const readRules = async (client) => {
398
373
  }
399
374
  return parseRedirects(text);
400
375
  };
401
- export { pagePathFor as _, cloudflareCounts as a, NOT_FOUND_SEGMENT as b, rewriteFor as c, ENCODINGS as d, SUFFIX as f, isPayloadPath as g, streamingCompressor as h, builtRules as i, rulesOf as l, negotiateEncoding as m, resolveStatic as n, cloudflareMatches as o, isCompressible as p, safeJoin as r, formatRedirects as s, readRules as t, shellRules as u, payloadPathFor as v, decodePathname as x, FALLBACK_SEGMENT as y };
376
+ export { isPayloadPath as _, cloudflareCounts as a, rewriteFor as c, shellRules as d, ENCODINGS as f, streamingCompressor as g, negotiateEncoding as h, builtRules as i, rewritesAfterFiles as l, isCompressible as m, resolveStatic as n, cloudflareMatches as o, SUFFIX as p, PLACEHOLDER as r, formatRedirects as s, readRules as t, rulesOf as u, pagePathFor as v, payloadPathFor as y };
package/dist/vercel.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import "./static-6z8_6B1U.mjs";
1
+ import "./static-DnbgGIoy.mjs";
2
2
  import { Plugin } from "vite";
3
3
  /**
4
4
  * A route as Vercel's Build Output API (v3) reads it, written to
@@ -25,7 +25,6 @@ type VercelRoute = {
25
25
  readonly caseSensitive?: boolean;
26
26
  readonly has?: ReadonlyArray<{
27
27
  readonly type: 'header';
28
- /** Lowercase, as Vercel compares it. */
29
28
  readonly key: string;
30
29
  readonly value?: string;
31
30
  }>;
package/dist/vercel.mjs CHANGED
@@ -1,6 +1,7 @@
1
+ import { c as isParamSegment, t as isFile } from "./static-file-BAjwBMMl.mjs";
1
2
  import { t as sharedDir } from "./shared-dir-CNXFRZgP.mjs";
2
3
  import { withBase } from "@k8ordo/router";
3
- import { cp, rm, stat, writeFile } from "node:fs/promises";
4
+ import { cp, rm, writeFile } from "node:fs/promises";
4
5
  import path from "node:path";
5
6
  // src/vercel-output.ts
6
7
  /** The function every request that names no file is rewritten to. */
@@ -32,8 +33,6 @@ const configFor = (base) => ({
32
33
  immutableAssets(base)
33
34
  ]
34
35
  });
35
- /** A `from` placeholder of `_redirects`: one segment. */
36
- const PLACEHOLDER = /^:[A-Za-z]\w*$/u;
37
36
  /**
38
37
  * A `_redirects` rule as a route of Vercel's: `from` as an anchored regex —
39
38
  * a placeholder one segment, every literal run escaped whole, so it starts
@@ -48,7 +47,7 @@ const routeOf = (rule) => {
48
47
  let literal = "";
49
48
  for (const [index, segment] of rule.from.split("/").entries()) {
50
49
  const run = index === 0 ? segment : `/${segment}`;
51
- if (index > 0 && PLACEHOLDER.test(segment)) {
50
+ if (index > 0 && isParamSegment(segment)) {
52
51
  source += `${RegExp.escape(`${literal}/`)}[^/]+`;
53
52
  literal = "";
54
53
  } else literal += run;
@@ -70,7 +69,7 @@ const routeOf = (rule) => {
70
69
  * where the extension says the same, so no file is left to the types Vercel
71
70
  * gives an extension.
72
71
  */
73
- const staticConfigFor = ({ base, rewrites, notFound, types }, { beforeFiles = [], beforeNotFound = [] }) => ({
72
+ const staticConfigFor = (base, { rewrites, notFound, types }, { beforeFiles = [], beforeNotFound = [] }) => ({
74
73
  version: 3,
75
74
  routes: [
76
75
  ...beforeFiles,
@@ -104,14 +103,8 @@ const FUNCTION_CONFIG = {
104
103
  */
105
104
  const isCompressedCopy = async (file) => {
106
105
  const original = file.replace(/\.(?:br|gz)$/u, "");
107
- if (original === file) return false;
108
- try {
109
- return (await stat(original)).isFile();
110
- } catch {
111
- return false;
112
- }
106
+ return original !== file && await isFile(original);
113
107
  };
114
- /** The nearest directory holding both. */
115
108
  const json = (value) => `${JSON.stringify(value, null, 2)}\n`;
116
109
  /**
117
110
  * The build laid out as Vercel's Build Output API (v3) reads it, under
@@ -145,18 +138,18 @@ const writeVercelOutput = async (root, dirs, base) => {
145
138
  * own — no function. `_redirects` stays behind: Vercel never reads it, and
146
139
  * would serve it as a file.
147
140
  */
148
- const writeStaticVercelOutput = async (output, routes = {}) => {
149
- const dir = path.join(output.root, ".vercel", "output");
141
+ const writeStaticVercelOutput = async ({ root, client, base }, output, routes = {}) => {
142
+ const dir = path.join(root, ".vercel", "output");
150
143
  await rm(dir, {
151
144
  recursive: true,
152
145
  force: true
153
146
  });
154
- const redirects = path.join(output.client, "_redirects");
155
- await cp(output.client, path.join(dir, "static", output.base), {
147
+ const redirects = path.join(client, "_redirects");
148
+ await cp(client, path.join(dir, "static", base), {
156
149
  recursive: true,
157
150
  filter: (source) => source !== redirects
158
151
  });
159
- await writeFile(path.join(dir, "config.json"), json(staticConfigFor(output, routes)));
152
+ await writeFile(path.join(dir, "config.json"), json(staticConfigFor(base, output, routes)));
160
153
  };
161
154
  // src/vercel.ts
162
155
  /**
@@ -175,19 +168,26 @@ const writeStaticVercelOutput = async (output, routes = {}) => {
175
168
  */
176
169
  const vercel = (options = {}) => {
177
170
  const { beforeFiles, beforeNotFound } = options;
178
- for (const route of [...beforeFiles ?? [], ...beforeNotFound ?? []]) for (const { key } of route.has ?? []) if (key !== key.toLowerCase()) throw new Error(`vercel() route ${route.src} has the header key "${key}" — write it lowercase ("${key.toLowerCase()}"), as Vercel compares it`);
179
171
  let isStatic = false;
180
172
  let logger;
173
+ let root = "";
174
+ let base = "/";
175
+ let client = "";
181
176
  return {
182
177
  name: "k8ordo:vercel",
183
178
  apply: "build",
184
179
  configResolved(config) {
185
180
  isStatic = config.plugins.some((plugin) => plugin.name === "k8ordo:static");
186
- ({logger} = config);
181
+ ({logger, root, base} = config);
182
+ client = path.resolve(root, config.environments.client?.build.outDir ?? "dist/client");
187
183
  if (!isStatic && (beforeFiles !== void 0 || beforeNotFound !== void 0)) throw new Error("vercel() takes beforeFiles and beforeNotFound under mode: 'static' only — under mode: 'server' the handler answers every URL no file names");
188
184
  },
189
185
  api: { async writeStatic(output) {
190
- await writeStaticVercelOutput(output, options);
186
+ await writeStaticVercelOutput({
187
+ root,
188
+ client,
189
+ base
190
+ }, output, options);
191
191
  logger?.info("k8ordo: wrote .vercel/output");
192
192
  } },
193
193
  buildApp: {
package/dist/vite.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { n as ContentSecurityPolicy, r as EngineOptions, t as StaticOptions } from "./static-6z8_6B1U.mjs";
1
+ import { n as ContentSecurityPolicy, r as EngineOptions, t as StaticOptions } from "./static-DnbgGIoy.mjs";
2
2
  import { PluginOption } from "vite";
3
3
  export type ServerOptions = EngineOptions & {
4
4
  /**