@k8ordo/framework 2.3.1 → 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 (65) hide show
  1. package/README.md +28 -13
  2. package/dist/cli.mjs +3 -3
  3. package/dist/generated.d.mts +13 -13
  4. package/dist/headers-BxB_jJVk.mjs +73 -0
  5. package/dist/index.d.mts +3 -2
  6. package/dist/index.mjs +1 -1
  7. package/dist/paths-type-DXpmjaOr.d.mts +43 -0
  8. package/dist/runtime/app-router.mjs +21 -8
  9. package/dist/runtime/browser-payloads.mjs +1 -1
  10. package/dist/runtime/client-files.d.mts +6 -5
  11. package/dist/runtime/client-files.mjs +17 -9
  12. package/dist/runtime/client-ready.d.mts +7 -1
  13. package/dist/runtime/client-ready.mjs +2 -1
  14. package/dist/runtime/cookies.d.mts +2 -0
  15. package/dist/runtime/cookies.mjs +2 -1
  16. package/dist/runtime/ended.d.mts +7 -0
  17. package/dist/runtime/ended.mjs +14 -0
  18. package/dist/runtime/entry.browser.mjs +1 -1
  19. package/dist/runtime/entry.rsc.d.mts +38 -2
  20. package/dist/runtime/entry.rsc.mjs +97 -31
  21. package/dist/runtime/entry.ssr.d.mts +7 -1
  22. package/dist/runtime/entry.ssr.mjs +12 -6
  23. package/dist/runtime/guard.d.mts +15 -10
  24. package/dist/runtime/guard.mjs +8 -2
  25. package/dist/runtime/mount.mjs +1 -1
  26. package/dist/runtime/page-boundary.mjs +2 -2
  27. package/dist/runtime/params.d.mts +5 -4
  28. package/dist/runtime/params.mjs +2 -2
  29. package/dist/runtime/payload.d.mts +19 -4
  30. package/dist/runtime/payload.mjs +20 -5
  31. package/dist/runtime/prefetch.d.mts +29 -8
  32. package/dist/runtime/prefetch.mjs +95 -24
  33. package/dist/runtime/redirect.d.mts +13 -7
  34. package/dist/runtime/redirect.mjs +25 -9
  35. package/dist/runtime/request-scope.d.mts +37 -2
  36. package/dist/runtime/request-scope.mjs +60 -3
  37. package/dist/runtime/request.d.mts +6 -1
  38. package/dist/runtime/request.mjs +7 -2
  39. package/dist/runtime/route.d.mts +4 -2
  40. package/dist/runtime/route.mjs +13 -5
  41. package/dist/runtime/server.d.mts +5 -5
  42. package/dist/runtime/server.mjs +2 -2
  43. package/dist/runtime/shell.d.mts +2 -1
  44. package/dist/serve.d.mts +4 -0
  45. package/dist/serve.mjs +29 -14
  46. package/dist/static-Be3xIqd8.d.mts +62 -0
  47. package/dist/{static-file-BAjwBMMl.mjs → static-file-BS-WEiwu.mjs} +311 -134
  48. package/dist/{static-host-B-1fAfAw.mjs → static-host-tIDLqV8c.mjs} +1 -1
  49. package/dist/vercel.d.mts +18 -1
  50. package/dist/vercel.mjs +131 -19
  51. package/dist/vite.d.mts +6 -3
  52. package/dist/vite.mjs +366 -156
  53. package/docs/GUIDE.md +173 -46
  54. package/docs/llms.txt +129 -65
  55. package/docs/references/actions.md +14 -5
  56. package/docs/references/boundaries.md +23 -2
  57. package/docs/references/csp.md +91 -2
  58. package/docs/references/deploy.md +154 -25
  59. package/docs/references/errors.md +57 -12
  60. package/docs/references/guards.md +100 -29
  61. package/docs/references/params.md +234 -126
  62. package/docs/references/routing.md +358 -75
  63. package/package.json +18 -13
  64. package/dist/shared-dir-CNXFRZgP.mjs +0 -9
  65. package/dist/static-DnbgGIoy.d.mts +0 -61
@@ -1,4 +1,4 @@
1
- import { b as FALLBACK_SEGMENT, c as isParamSegment, n as safeJoin, t as isFile } from "./static-file-BAjwBMMl.mjs";
1
+ import { E as FALLBACK_SEGMENT, d as isParamSegment, n as safeJoin, t as isFile } from "./static-file-BS-WEiwu.mjs";
2
2
  import { normalizePathname, withBase, withoutBase } from "@k8ordo/router";
3
3
  import { readFile } from "node:fs/promises";
4
4
  import path from "node:path";
package/dist/vercel.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import "./static-DnbgGIoy.mjs";
1
+ import "./static-Be3xIqd8.mjs";
2
2
  import { Plugin } from "vite";
3
3
  /**
4
4
  * A route as Vercel's Build Output API (v3) reads it, written to
@@ -37,6 +37,17 @@ type VercelOptions = {
37
37
  * answered, before `404.html`.
38
38
  */
39
39
  readonly beforeNotFound?: readonly VercelRoute[];
40
+ /**
41
+ * Under `mode: 'server'`, how long the function may run for one request,
42
+ * in seconds, or `'max'` for the plan's maximum. Without it, Vercel's
43
+ * default for the plan.
44
+ */
45
+ readonly maxDuration?: number | 'max';
46
+ /**
47
+ * Under `mode: 'server'`, the Vercel regions the function is deployed to
48
+ * (`['hnd1']`). Without it, the project's own setting.
49
+ */
50
+ readonly regions?: readonly string[];
40
51
  };
41
52
  /**
42
53
  * Deploys the application to Vercel: after `vite build`, the build is also
@@ -51,6 +62,12 @@ type VercelOptions = {
51
62
  * own routes around them, written as given: `beforeFiles` ahead of every
52
63
  * file, `beforeNotFound` ahead of `404.html`. A file a `route.ts` wrote is
53
64
  * served with the `Content-Type` its `GET` answered.
65
+ *
66
+ * Vercel stops a function once its answer is sent, unless told through
67
+ * `@vercel/functions`. So when the application imports `waitUntil` from
68
+ * `@k8ordo/framework/server`, the function hands the handler that package's
69
+ * `waitUntil`, bundled in from the application's own install of it — and
70
+ * without one the build stops, naming the modules that import it.
54
71
  */
55
72
  export declare const vercel: (options?: VercelOptions) => Plugin;
56
73
  export type { VercelOptions, VercelRoute };
package/dist/vercel.mjs CHANGED
@@ -1,8 +1,68 @@
1
- import { c as isParamSegment, t as isFile } from "./static-file-BAjwBMMl.mjs";
2
- import { t as sharedDir } from "./shared-dir-CNXFRZgP.mjs";
1
+ import { a as sharedDir, t as declaredHeaders } from "./headers-BxB_jJVk.mjs";
2
+ import { d as isParamSegment, t as isFile } from "./static-file-BS-WEiwu.mjs";
3
3
  import { withBase } from "@k8ordo/router";
4
4
  import { cp, rm, writeFile } from "node:fs/promises";
5
5
  import path from "node:path";
6
+ import { build, parseSync } from "vite";
7
+ // src/vercel-wait-until.ts
8
+ /** The entry `waitUntil` is imported from. */
9
+ const SERVER_ENTRY = "@k8ordo/framework/server";
10
+ /** The package Vercel keeps a function running through. */
11
+ const VERCEL_FUNCTIONS = "@vercel/functions";
12
+ const BUNDLE = "virtual:k8ordo/vercel-wait-until";
13
+ /** The file in the function that is `@vercel/functions`' `waitUntil`. */
14
+ const WAIT_UNTIL_FILE = "wait-until.mjs";
15
+ /**
16
+ * Whether a compiled module takes `waitUntil` from `@k8ordo/framework/server`:
17
+ * imported or re-exported by name, or possibly, through `import * as` or
18
+ * `export *`, which name nothing — counted, since the other mistake is a
19
+ * function Vercel stops with the work unfinished. A type-only import is gone
20
+ * by the time a module is compiled.
21
+ */
22
+ const importsWaitUntil = (code) => {
23
+ if (!code.includes(SERVER_ENTRY)) return false;
24
+ const { errors, module } = parseSync("module.js", code, { sourceType: "module" });
25
+ if (errors.length > 0) return false;
26
+ return module.staticImports.some(({ moduleRequest, entries }) => moduleRequest.value === SERVER_ENTRY && entries.some(({ importName }) => importName.kind === "NamespaceObject" || importName.name === "waitUntil")) || module.staticExports.some(({ entries }) => entries.some(({ moduleRequest, importName }) => moduleRequest?.value === SERVER_ENTRY && (importName.kind === "All" || importName.kind === "AllButDefault" || importName.name === "waitUntil")));
27
+ };
28
+ const missingFunctions = (users) => `the build for Vercel cannot keep the function running after its answer — on Vercel waitUntil() goes through ${VERCEL_FUNCTIONS}, which is not installed here, and ${users.length === 1 ? "this imports" : "these import"} waitUntil from ${SERVER_ENTRY}:\n${users.map((file) => ` ${file}`).join("\n")}\ninstall ${VERCEL_FUNCTIONS} in this application`;
29
+ /**
30
+ * `@vercel/functions`' `waitUntil`, as the application at `root` resolves
31
+ * the package, bundled into `WAIT_UNTIL_FILE` of the function at `func`: a
32
+ * function holds nothing but its own directory. A build of its own, as
33
+ * `dist/server.js` is, because what it bundles is not the application's code
34
+ * and takes none of its config. Without the package it stops, naming
35
+ * `users`, the modules that import `waitUntil`.
36
+ */
37
+ const bundleWaitUntil = async (root, func, users) => {
38
+ await build({
39
+ root,
40
+ configFile: false,
41
+ logLevel: "warn",
42
+ publicDir: false,
43
+ plugins: [{
44
+ name: "k8ordo:vercel-wait-until",
45
+ async resolveId(id) {
46
+ if (id === BUNDLE) return `\0${BUNDLE}`;
47
+ if (id !== VERCEL_FUNCTIONS) return null;
48
+ const found = await this.resolve(id, path.join(root, "package.json"), { skipSelf: true });
49
+ if (found === null) throw new Error(missingFunctions(users));
50
+ return found;
51
+ },
52
+ load: (id) => id === `\0${BUNDLE}` ? `export { waitUntil } from ${JSON.stringify(VERCEL_FUNCTIONS)};\n` : null
53
+ }],
54
+ environments: { ssr: { resolve: { noExternal: true } } },
55
+ build: {
56
+ ssr: true,
57
+ outDir: func,
58
+ emptyOutDir: false,
59
+ rolldownOptions: {
60
+ input: BUNDLE,
61
+ output: { entryFileNames: WAIT_UNTIL_FILE }
62
+ }
63
+ }
64
+ });
65
+ };
6
66
  // src/vercel-output.ts
7
67
  /** The function every request that names no file is rewritten to. */
8
68
  const FUNCTION = "handler";
@@ -20,10 +80,21 @@ const immutableAssets = (base) => ({
20
80
  continue: true,
21
81
  important: true
22
82
  });
83
+ /**
84
+ * The headers `framework()` declared, ahead of every other route: a route
85
+ * that only adds headers and goes on, so they are on whatever the routes
86
+ * after it lead to. None declared, no route.
87
+ */
88
+ const declaredRoutes = (headers) => Object.keys(headers).length === 0 ? [] : [{
89
+ src: "^/.*$",
90
+ headers,
91
+ continue: true
92
+ }];
23
93
  /** Files first, and whatever names none goes to the handler. */
24
- const configFor = (base) => ({
94
+ const configFor = (base, headers) => ({
25
95
  version: 3,
26
96
  routes: [
97
+ ...declaredRoutes(headers),
27
98
  { handle: "filesystem" },
28
99
  {
29
100
  src: "^/.*$",
@@ -61,7 +132,8 @@ const routeOf = (rule) => {
61
132
  };
62
133
  };
63
134
  /**
64
- * The application's `beforeFiles`, then the files; only what names none is
135
+ * The declared headers, the application's `beforeFiles`, then the files — a
136
+ * `beforeFiles` route may write a declared name over; only what names none is
65
137
  * rewritten — a value the build did not write to its shell, the payload URL
66
138
  * of a built URL that is not a page to HTML — and what nothing rewrote goes
67
139
  * through the application's `beforeNotFound` to the build's `404.html`. A
@@ -69,9 +141,10 @@ const routeOf = (rule) => {
69
141
  * where the extension says the same, so no file is left to the types Vercel
70
142
  * gives an extension.
71
143
  */
72
- const staticConfigFor = (base, { rewrites, notFound, types }, { beforeFiles = [], beforeNotFound = [] }) => ({
144
+ const staticConfigFor = (base, { rewrites, notFound, types }, { beforeFiles = [], beforeNotFound = [] }, headers) => ({
73
145
  version: 3,
74
146
  routes: [
147
+ ...declaredRoutes(headers),
75
148
  ...beforeFiles,
76
149
  { handle: "filesystem" },
77
150
  ...rewrites.map((rule) => routeOf(rule)),
@@ -107,49 +180,62 @@ const isCompressedCopy = async (file) => {
107
180
  };
108
181
  const json = (value) => `${JSON.stringify(value, null, 2)}\n`;
109
182
  /**
183
+ * The function's entry: the handler as `fetch`, and with `waitUntil`, the
184
+ * host's handed to it beside every request.
185
+ */
186
+ const entryFor = (handler, waitUntil) => waitUntil ? `import handler from './${handler}';\nimport { waitUntil } from './${WAIT_UNTIL_FILE}';\n\nexport default { fetch: (request) => handler(request, { waitUntil }) };\n` : `import handler from './${handler}';\n\nexport default { fetch: handler };\n`;
187
+ /**
110
188
  * The build laid out as Vercel's Build Output API (v3) reads it, under
111
189
  * `<root>/.vercel/output`: the client build as static files at Vite's `base`,
112
190
  * and the request handler as the one function behind them. Only `output/` is
113
191
  * replaced — `vercel pull` keeps the project's link and settings beside it.
192
+ * An application that calls `waitUntil()` gets `@vercel/functions`' in the
193
+ * function, and without the package installed nothing is written but the
194
+ * refusal.
114
195
  */
115
- const writeVercelOutput = async (root, dirs, base) => {
196
+ const writeVercelOutput = async (root, dirs, base, headers = {}, { maxDuration, regions, waitUntil = [] } = {}) => {
116
197
  const output = path.join(root, ".vercel", "output");
117
198
  await rm(output, {
118
199
  recursive: true,
119
200
  force: true
120
201
  });
202
+ const func = path.join(output, "functions", `${FUNCTION}.func`);
203
+ if (waitUntil.length > 0) await bundleWaitUntil(root, func, waitUntil);
121
204
  await cp(dirs.client, path.join(output, "static", base), {
122
205
  recursive: true,
123
206
  filter: async (source) => !await isCompressedCopy(source)
124
207
  });
125
- const func = path.join(output, "functions", `${FUNCTION}.func`);
126
208
  const shared = sharedDir(dirs.rsc, dirs.ssr);
127
209
  await Promise.all([dirs.rsc, dirs.ssr].map((dir) => cp(dir, path.join(func, path.relative(shared, dir)), { recursive: true })));
128
210
  const entry = path.relative(shared, path.join(dirs.rsc, "index.js")).split(path.sep).join("/");
129
- await writeFile(path.join(func, "index.mjs"), `import handler from './${entry}';\n\nexport default { fetch: handler };\n`);
211
+ await writeFile(path.join(func, "index.mjs"), entryFor(entry, waitUntil.length > 0));
130
212
  await writeFile(path.join(func, "package.json"), json({ type: "module" }));
131
- await writeFile(path.join(func, ".vc-config.json"), json(FUNCTION_CONFIG));
132
- await writeFile(path.join(output, "config.json"), json(configFor(base)));
213
+ await writeFile(path.join(func, ".vc-config.json"), json({
214
+ ...FUNCTION_CONFIG,
215
+ ...maxDuration === void 0 ? {} : { maxDuration },
216
+ ...regions === void 0 ? {} : { regions }
217
+ }));
218
+ await writeFile(path.join(output, "config.json"), json(configFor(base, headers)));
133
219
  };
134
220
  /**
135
221
  * A static build laid out as Vercel's Build Output API (v3) reads it: the
136
222
  * client build as static files at Vite's `base`, and the rewrites a host
137
223
  * applies once no file answered as routes, around them the application's
138
- * own — no function. `_redirects` stays behind: Vercel never reads it, and
139
- * would serve it as a file.
224
+ * own — no function. `_redirects` and `_headers` stay behind: Vercel reads
225
+ * neither, and would serve them as files.
140
226
  */
141
- const writeStaticVercelOutput = async ({ root, client, base }, output, routes = {}) => {
227
+ const writeStaticVercelOutput = async ({ root, client, base }, output, routes = {}, headers = {}) => {
142
228
  const dir = path.join(root, ".vercel", "output");
143
229
  await rm(dir, {
144
230
  recursive: true,
145
231
  force: true
146
232
  });
147
- const redirects = path.join(client, "_redirects");
233
+ const left = new Set(["_redirects", "_headers"].map((name) => path.join(client, name)));
148
234
  await cp(client, path.join(dir, "static", base), {
149
235
  recursive: true,
150
- filter: (source) => source !== redirects
236
+ filter: (source) => !left.has(source)
151
237
  });
152
- await writeFile(path.join(dir, "config.json"), json(staticConfigFor(base, output, routes)));
238
+ await writeFile(path.join(dir, "config.json"), json(staticConfigFor(base, output, routes, headers)));
153
239
  };
154
240
  // src/vercel.ts
155
241
  /**
@@ -165,31 +251,53 @@ const writeStaticVercelOutput = async ({ root, client, base }, output, routes =
165
251
  * own routes around them, written as given: `beforeFiles` ahead of every
166
252
  * file, `beforeNotFound` ahead of `404.html`. A file a `route.ts` wrote is
167
253
  * served with the `Content-Type` its `GET` answered.
254
+ *
255
+ * Vercel stops a function once its answer is sent, unless told through
256
+ * `@vercel/functions`. So when the application imports `waitUntil` from
257
+ * `@k8ordo/framework/server`, the function hands the handler that package's
258
+ * `waitUntil`, bundled in from the application's own install of it — and
259
+ * without one the build stops, naming the modules that import it.
168
260
  */
169
261
  const vercel = (options = {}) => {
170
- const { beforeFiles, beforeNotFound } = options;
262
+ const { beforeFiles, beforeNotFound, maxDuration, regions } = options;
171
263
  let isStatic = false;
172
264
  let logger;
173
265
  let root = "";
174
266
  let base = "/";
175
267
  let client = "";
268
+ let headers = {};
269
+ const waitUntilUsers = /* @__PURE__ */ new Set();
176
270
  return {
177
271
  name: "k8ordo:vercel",
178
272
  apply: "build",
179
273
  configResolved(config) {
180
274
  isStatic = config.plugins.some((plugin) => plugin.name === "k8ordo:static");
181
275
  ({logger, root, base} = config);
276
+ headers = declaredHeaders(config.plugins);
182
277
  client = path.resolve(root, config.environments.client?.build.outDir ?? "dist/client");
183
278
  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");
279
+ if (isStatic && (maxDuration !== void 0 || regions !== void 0)) throw new Error("vercel() takes maxDuration and regions under mode: 'server' only — under mode: 'static' there is no function for them to configure");
280
+ if (maxDuration !== void 0 && maxDuration !== "max" && !(Number.isInteger(maxDuration) && maxDuration > 0)) throw new Error(`vercel() takes maxDuration as a whole number of seconds or 'max', and got ${String(maxDuration)}`);
184
281
  },
185
282
  api: { async writeStatic(output) {
186
283
  await writeStaticVercelOutput({
187
284
  root,
188
285
  client,
189
286
  base
190
- }, output, options);
287
+ }, output, options, headers);
191
288
  logger?.info("k8ordo: wrote .vercel/output");
192
289
  } },
290
+ transform: {
291
+ order: "post",
292
+ handler(code, id) {
293
+ if (isStatic || this.environment.name !== "rsc") return null;
294
+ if (importsWaitUntil(code)) {
295
+ const [module = id] = id.split("?");
296
+ waitUntilUsers.add(path.relative(root, module));
297
+ }
298
+ return null;
299
+ }
300
+ },
193
301
  buildApp: {
194
302
  order: "post",
195
303
  async handler(builder) {
@@ -203,7 +311,11 @@ const vercel = (options = {}) => {
203
311
  client: dirOf("client"),
204
312
  rsc: dirOf("rsc"),
205
313
  ssr: dirOf("ssr")
206
- }, builder.config.base);
314
+ }, builder.config.base, headers, {
315
+ maxDuration,
316
+ regions,
317
+ waitUntil: [...waitUntilUsers].toSorted()
318
+ });
207
319
  builder.config.logger.info("k8ordo: wrote .vercel/output");
208
320
  }
209
321
  }
package/dist/vite.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { n as ContentSecurityPolicy, r as EngineOptions, t as StaticOptions } from "./static-DnbgGIoy.mjs";
1
+ import { i as EngineOptions, n as ContentSecurityPolicy, r as scriptHash, t as StaticOptions } from "./static-Be3xIqd8.mjs";
2
2
  import { PluginOption } from "vite";
3
3
  export type ServerOptions = EngineOptions & {
4
4
  /**
@@ -7,7 +7,10 @@ export type ServerOptions = EngineOptions & {
7
7
  */
8
8
  readonly mode: 'server';
9
9
  };
10
- /** `paths`, `site` and `csp` describe files, so only `mode: 'static'` takes them. */
10
+ /**
11
+ * `site` and `csp` describe files, so only `mode: 'static'` takes them, and
12
+ * it needs `site`.
13
+ */
11
14
  export type FrameworkOptions = StaticOptions | ServerOptions;
12
15
  /**
13
16
  * The application: `routes/` compiled into a route table and a request
@@ -15,4 +18,4 @@ export type FrameworkOptions = StaticOptions | ServerOptions;
15
18
  * every route, written to files (`'static'`), or per request (`'server'`).
16
19
  */
17
20
  export declare const framework: (options: FrameworkOptions) => PluginOption[];
18
- export type { ContentSecurityPolicy, StaticOptions };
21
+ export { type ContentSecurityPolicy, type StaticOptions, scriptHash };