@uniflowed/vite 0.0.0-alpha.9 → 0.2.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/driver.js CHANGED
@@ -6,7 +6,12 @@
6
6
  // `uf start` spawn.
7
7
  //
8
8
  // <host> driver.js dev --root <dir> [--mode <m>] [--host <h>] [--port <n>] [--strict-port]
9
- // <host> driver.js build --root <dir> [--mode <m>] [--out-dir <dir>]
9
+ // [--uf-env-file <file>]...
10
+ // <host> driver.js build --root <dir> [--mode <m>] [--out-dir <dir>] [--target <target>]
11
+ // [--prerender everything|possible|nothing]
12
+ // [--static-build] [--because <sentence>]
13
+ // <host> driver.js library --root <dir> [--mode <m>] [--out-dir <dir>]
14
+ // --entry <file>... --format <es|cjs>... [--external <name>]...
10
15
  // <host> driver.js compile --root <dir> [--mode <m>] [--out-dir <dir>] --assets <file> --bundle <dir>
11
16
  // <host> driver.js deploy --root <dir> [--mode <m>] [--out-dir <dir>] --adapter <name> --work <dir> --output <dir>
12
17
  // <host> driver.js preview --root <dir> [--mode <m>] [--out-dir <dir>] [--host <h>] [--port <n>]
@@ -19,6 +24,12 @@
19
24
  // environment — see `viteConfig` below and `crates/uf_config/src/env_files.rs`.
20
25
  // `start` has no Vite in it and therefore no mode.
21
26
  //
27
+ // `--uf-env-file` names those files, one flag each, so `dev` can watch them and
28
+ // say when one moved; nothing here reads their contents. The prefix is load
29
+ // bearing: node claims `--env-file` for itself and honours it wherever it
30
+ // appears on the command line, script arguments included, so a driver argument
31
+ // by that name is an argument node eats and then exits 9 over.
32
+ //
22
33
  // `uf` in Rust owns the terminal; this process owns Vite. They talk over
23
34
  // stdout, one JSON event per line (see `./internal/events.js`), and the driver
24
35
  // exits when its stdin closes so it cannot outlive the command that started
@@ -28,22 +39,50 @@
28
39
  // Rust side reads a config that may hold functions and plugin instances: the
29
40
  // one host that can evaluate the file evaluates it.
30
41
 
42
+ import { randomUUID } from "node:crypto";
31
43
  import { createServer as createHttpServer } from "node:http";
32
- import { register } from "node:module";
33
- import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
44
+ import { builtinModules, register } from "node:module";
45
+ import { esmExternalRequirePlugin } from "rolldown/plugins";
46
+ import { installFlowHooks } from "@uniflowed/host/internal/sync-hooks.js";
47
+ import { cpSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
34
48
  import path from "node:path";
35
49
  import { pathToFileURL } from "node:url";
36
50
 
37
- import { emit, errorEvent, eventLogger, reportRenderError } from "./internal/events.js";
51
+ import { COMPILE_ASSETS_ID, compileAssetsPlugin } from "./internal/compile-assets.js";
52
+ import { servesRemoteImages } from "./internal/image-endpoint.js";
53
+ import {
54
+ survivingImports,
55
+ unavailableOnWorkers,
56
+ workerBuiltinWarnings,
57
+ } from "./internal/worker-builtins.js";
58
+ import { emit, errorEvent, eventLogger } from "./internal/events.js";
38
59
  import { loadUfConfig, projectConfig } from "./internal/config.js";
39
- import { send, toRequest } from "./internal/http.js";
60
+ import { send, toAddressRequest, toRequest } from "./internal/http.js";
61
+ import { createOpenApiDocument } from "./internal/openapi.js";
40
62
  import { withProjectConfig } from "./merge.js";
41
- import { VIRTUAL, scanRoutes } from "./internal/routes.js";
63
+ import { FLIGHT_VIRTUAL, RSC_ENVIRONMENT } from "./internal/flight.js";
64
+ import { MODULE_GRAPH_FILE, createModuleGraphCollector } from "./internal/module-graph.js";
65
+ import { VIRTUAL, resolveRouteTarget, routingRulesOf, scanRoutes } from "./internal/routes.js";
42
66
  import {
67
+ BUILD_ID_FILE,
68
+ DOCUMENT_ASSETS_FILE,
69
+ PARTIAL_PRERENDER_FILE,
70
+ REGENERATED_DIRECTORY,
71
+ REGENERATION_FILE,
72
+ answerRouting,
73
+ answersInFrontOfFiles,
43
74
  assetsFromManifest,
75
+ buildIdentity,
76
+ createPrerenderGate,
44
77
  createServeHandler,
78
+ deploymentIdFor,
79
+ documentAssetsFor,
80
+ forViteBase,
45
81
  loadBuild,
46
82
  nodeListener,
83
+ providerSpecifier,
84
+ readPartialPrerenders,
85
+ readRegeneration,
47
86
  withRequest,
48
87
  } from "./internal/serve.js";
49
88
 
@@ -52,6 +91,16 @@ function argument(name) {
52
91
  return at === -1 ? null : process.argv[at + 1];
53
92
  }
54
93
 
94
+ /** Every value of a repeated argument, in the order they were given. */
95
+ function argumentAll(name) {
96
+ const values = [];
97
+ for (let at = 0; at < process.argv.length; at += 1) {
98
+ if (process.argv[at] === name && process.argv[at + 1] != null)
99
+ values.push(process.argv[at + 1]);
100
+ }
101
+ return values;
102
+ }
103
+
55
104
  function flag(name) {
56
105
  return process.argv.includes(name);
57
106
  }
@@ -66,11 +115,23 @@ process.env.UF_PROJECT_ROOT = root;
66
115
  // hooks for that; Bun is started with `--preload` on the same package's
67
116
  // preload instead, and has no `register`.
68
117
  //
118
+ // Deno has no `register` either, and it gets its hooks *here* rather than from
119
+ // a preload, for a reason that is about order. While a Deno `load` hook is
120
+ // registered, `require()` of a native addon fails — and Vite requires one,
121
+ // Rolldown's binding. The static imports above have already loaded Vite by
122
+ // this line, binding included, so hooks installed now see only what is
123
+ // imported after them: the config, and the `@uniflowed/*` modules this driver
124
+ // reaches dynamically. They are the in-thread hooks a new enough Node takes
125
+ // through `@uniflowed/host/register` too; see
126
+ // `@uniflowed/host/internal/sync-hooks.js`.
127
+ //
69
128
  // The hooks live in `@uniflowed/host` rather than here: they are how Flow runs
70
129
  // on a Capability JS Host, and nothing in them is Vite's. `uf test` reaches for
71
130
  // the same package, which is what stopped a test run from depending on a
72
131
  // bundler it never loads.
73
- if (typeof Bun === "undefined" && typeof Deno === "undefined") {
132
+ if (typeof Deno !== "undefined") {
133
+ installFlowHooks(root);
134
+ } else if (typeof Bun === "undefined") {
74
135
  register("@uniflowed/host/internal/node-hooks.js", import.meta.url, { data: { root } });
75
136
  }
76
137
 
@@ -78,7 +139,7 @@ process.stdin.on("end", () => process.exit(0));
78
139
  process.stdin.on("error", () => process.exit(0));
79
140
  process.stdin.resume();
80
141
 
81
- const commands = { dev, build, compile, deploy, preview, start, config: printConfig };
142
+ const commands = { dev, build, library, compile, deploy, preview, start, config: printConfig };
82
143
  const run = commands[command];
83
144
  if (run == null) {
84
145
  emit("error", { message: `unknown driver command ${JSON.stringify(command)}` });
@@ -90,6 +151,33 @@ run().catch((error) => {
90
151
  process.exit(1);
91
152
  });
92
153
 
154
+ /**
155
+ * What this build is called, for anything that outlives it.
156
+ *
157
+ * `UF_BUILD_ID` when it is set, and a fresh random name otherwise — which is
158
+ * `crates/uf_rsc`'s `BuildId::from_env_or_generate` exactly, reading the same
159
+ * variable, because it is the same question asked by a different half of the
160
+ * toolchain. Two artefacts that have to *be* one build say so with the
161
+ * variable; everything else gets a name no other build has.
162
+ *
163
+ * Minted once per build and written into the build, never per process. Four
164
+ * servers started from one artefact are one build and must share one cache;
165
+ * generating this where the server starts would give them four, which is worse
166
+ * than none at all — four copies of everything written into one directory and
167
+ * none of them read.
168
+ *
169
+ * Not a hash of the output. A content hash would be reproducible, which is
170
+ * appealing and wrong here: two builds with identical client bundles can have
171
+ * different server behaviour — a loader's body moves and no asset hash does —
172
+ * and a cache keyed by one would serve the old loader's documents. A name that
173
+ * changes whenever the build ran is the conservative direction to be wrong in.
174
+ */
175
+ function mintBuildId() {
176
+ const named = process.env.UF_BUILD_ID;
177
+ if (typeof named === "string" && named.trim() !== "") return named.trim();
178
+ return randomUUID().replaceAll("-", "");
179
+ }
180
+
93
181
  /** Load `uf.config.js`, reporting where it was found. */
94
182
  async function loadConfig() {
95
183
  const { config, file } = await loadUfConfig(root);
@@ -97,6 +185,15 @@ async function loadConfig() {
97
185
  return config;
98
186
  }
99
187
 
188
+ /**
189
+ * `app.router.basePath` as the driver uses it: `""` at the root, `"/docs"`
190
+ * otherwise. Read where the build writes asset URLs and file names, because a
191
+ * prerendered document is written outside Vite's HTML transform.
192
+ */
193
+ function basePathOf(config) {
194
+ return routingRulesOf(config.app?.router).basePath;
195
+ }
196
+
100
197
  /** The Vite inline config a uf config describes. */
101
198
  async function viteConfig(config, mode) {
102
199
  const { default: uniflowed } = await import("./index.js");
@@ -107,6 +204,7 @@ async function viteConfig(config, mode) {
107
204
  const port = Number(argument("--port") ?? dev.port ?? 5173);
108
205
  const allowedHosts =
109
206
  Array.isArray(dev.allowedHosts) && dev.allowedHosts.length > 0 ? dev.allowedHosts : undefined;
207
+ const routeTarget = resolveRouteTarget(config, argument("--target"));
110
208
 
111
209
  // What uf generates from the semantics it owns: where the project is, which
112
210
  // plugins make Flow compile, and the few settings uf enforces rather than
@@ -135,9 +233,31 @@ async function viteConfig(config, mode) {
135
233
  configFile: false,
136
234
  envDir: false,
137
235
  mode,
236
+ // Vite's dependency cache, kept in the project whatever is above it.
237
+ // Vite's own default is the nearest `package.json`'s `node_modules/.vite`,
238
+ // and a uf project needs no `package.json`. One inside another repository
239
+ // pre-bundled into that repository's `node_modules`, in one directory
240
+ // shared with every other such project there and emptied by each dev
241
+ // server that started — which is how two `uf dev` servers came to answer
242
+ // each other's pre-bundled files with `504 Outdated Optimize Dep`
243
+ // (ubugeeei-prod/uf#1141).
244
+ //
245
+ // This directory rather than `.vite` or `.uf/cache/vite`, because it is
246
+ // where Vite already puts the cache for a project with its own
247
+ // `package.json`, so nothing moves for one: the URLs stay
248
+ // `/node_modules/.vite/deps/…`, and the files stay under `node_modules`,
249
+ // which git ignores, Vite's watcher skips and Vite's sourcemap ignore list
250
+ // treats as somebody else's code. `cacheDir` is shared config, so every
251
+ // environment's optimizer follows it — `deps`, `deps_ssr`, `deps_rsc` —
252
+ // and a project's own `vite.cacheDir` is merged over it like any option.
253
+ cacheDir: path.join(root, "node_modules", ".vite"),
254
+ // `app.router.basePath`: where Vite serves the modules in development, and
255
+ // what it puts in front of every asset URL a build writes.
256
+ base: basePathOf(config) === "" ? "/" : `${basePathOf(config)}/`,
138
257
  clearScreen: false,
139
258
  customLogger: eventLogger(argument("--log-level") ?? "info"),
140
- plugins: [uniflowed({ root, config })],
259
+ // One `uf transform` for every pass this process runs; see the option.
260
+ plugins: [uniflowed({ root, config, target: routeTarget, shareTransformAcrossBuilds: true })],
141
261
  server: {
142
262
  host,
143
263
  port,
@@ -182,129 +302,43 @@ async function viteConfig(config, mode) {
182
302
  * Vite in middleware mode serves nothing on its own: with no `index.html` at
183
303
  * the project root it answers every navigation with "Cannot GET /", which is
184
304
  * what `uf dev` used to do for every project it started. A uf project has no
185
- * `index.html` — the document comes from a layout — so the server has to render
186
- * it, which is what this middleware does:
187
- *
188
- * 1. load the server entry through `ssrLoadModule`, so it is transformed the
189
- * same way the browser's copy is and picks up edits without a restart;
190
- * 2. run the middleware guarding this path, which may answer instead;
191
- * 3. render the URL, pointing the client script at the dev entry rather than
192
- * at a built asset;
193
- * 4. hand the HTML to `transformIndexHtml`, which is what injects the HMR
194
- * client and lets any Vite plugin see the document.
195
- *
196
- * Step 4 is why `uf dev` collects the stream instead of piping it: Vite's HTML
197
- * hook takes a whole document and any plugin may rewrite any part of it, so
198
- * there is no first byte to send until it has run. `uf start` and `uf preview`
199
- * have no such hook and stream — see `internal/serve.js` — and it is worth
200
- * being clear that this is a property of the development server rather than of
201
- * the renderer. Streaming through the transform is ubugeeei-prod/uf#374.
202
- *
203
- * Anything Vite already serves — a module, a public file — never reaches this,
204
- * because the middleware runs after Vite's own.
305
+ * `index.html` — the document comes from a layout — so the server has to
306
+ * render it.
307
+ *
308
+ * That rendering is **not** here. It is one middleware, in `./index.js`'s
309
+ * `configureServer`, and this function installs none of its own. It used to
310
+ * install a second one, and two middlewares rendering the same request is how
311
+ * `uf dev` came to answer a route handler with a page and a redirect without
312
+ * its `Location`: `configureServer`'s post hook runs inside `createServer`,
313
+ * and anything added here runs after it returns, so of the two the plugin's
314
+ * was always the one that decided. See ubugeeei-prod/uf#349 and #338, and the
315
+ * comment above that middleware for what it now has to do.
316
+ *
317
+ * What is left here is the half that is genuinely the driver's: the Vite
318
+ * config, the socket, the event channel back to `uf`, and the two watchers
319
+ * below.
205
320
  */
206
321
  async function dev() {
207
322
  const { createServer } = await import("vite");
208
323
  const config = await loadConfig();
324
+ const routeTarget = resolveRouteTarget(config, argument("--target"));
209
325
  // The mode is uf's to decide, not this file's: `uf dev` resolves `--mode`,
210
326
  // the profile `uf env use` wrote and `env.active` before it starts anything,
211
327
  // and always passes the answer. The fallback is for a driver started by hand.
212
328
  const inline = await viteConfig(config, argument("--mode") ?? "development");
213
329
  const server = await createServer({ ...inline, appType: "custom" });
214
330
 
215
- // In dev the browser loads the client entry from Vite, not from a manifest;
216
- // its stylesheets arrive through that module rather than as <link> tags.
217
- const assets = { scripts: [`/@id/${VIRTUAL.client}`], styles: [], preloads: [] };
218
-
219
- server.middlewares.use(async (request, response, next) => {
220
- const url = request.originalUrl ?? request.url ?? "/";
221
- // Declared out here so the catch below can still settle: a request that
222
- // failed is a request that happened, and a middleware that logged its
223
- // arrival is owed its callback either way.
224
- let lifecycle = null;
225
- try {
226
- const entry = await server.ssrLoadModule(VIRTUAL.server);
227
- const asRequest = await toRequest(request, server.config);
228
-
229
- // The request begins here and ends when the document has been written,
230
- // which is what `after()` promises and what `uf preview`, `uf start` and
231
- // a compiled binary all do too — a middleware that logs a response's
232
- // status has to mean the same thing in development as in production.
233
- // `entry.beginRequest` rather than an import: the storage that holds the
234
- // request belongs to the application's own copy of `@uniflowed/server`.
235
- // See `internal/serve.js` and ubugeeei-prod/uf#389.
236
- lifecycle = entry.beginRequest(asRequest);
237
- const answered = await lifecycle.run(async () => {
238
- // Middleware first, above everything: it guards a subtree, so it has to
239
- // run for a page, for a route handler, and for a path under it that
240
- // matches neither. Running it inside the dispatcher and again inside the
241
- // renderer would have left `/dashboard/typo` unguarded and run it twice
242
- // for a path that is both.
243
- const guarded = await entry.runMiddleware(asRequest);
244
- if (guarded != null) {
245
- await send(response, guarded);
246
- return true;
247
- }
248
-
249
- // Route handlers next, and for every method: a handler is the only
250
- // thing that answers a POST, and it may also answer a GET for a path
251
- // that has no page.
252
- const handled = await entry.dispatch(asRequest);
253
- if (handled != null) {
254
- await send(response, handled);
255
- return true;
256
- }
257
-
258
- // Only a navigation reaches the renderer. A page cannot answer a POST,
259
- // and letting one try would turn a missing handler into a rendered page
260
- // with a 200 rather than a 404.
261
- if (request.method !== "GET" && request.method !== "HEAD") {
262
- return false;
263
- }
264
-
265
- const result = await entry.render(url, assets, {
266
- // A boundary that threw after the shell went out. `result.error` cannot
267
- // carry it — the caller already has the result by then — so the
268
- // terminal hears about it here or not at all.
269
- onError: (error) => reportRenderError(server, url, error),
270
- });
271
- if (result.error != null) reportRenderError(server, url, result.error);
272
- const html = await server.transformIndexHtml(url, await result.text());
273
- response.statusCode = result.status ?? 200;
274
- response.setHeader("content-type", "text/html; charset=utf-8");
275
- response.end(html);
276
- return true;
277
- });
278
-
279
- if (!answered) {
280
- // The one path where uf is not the one writing the response: a
281
- // non-navigation nothing claimed goes back to Vite's chain. The guard
282
- // has still run and may have deferred work, so `close` — the socket
283
- // saying the response is over, however it ended — is the only honest
284
- // signal left that the bytes are out.
285
- response.once("close", lifecycle.settle);
286
- next();
287
- return;
288
- }
289
- await lifecycle.settle();
290
- } catch (error) {
291
- if (lifecycle != null) await lifecycle.settle();
292
- // Map the stack back onto the Flow source before it reaches the overlay.
293
- if (error instanceof Error) server.ssrFixStacktrace(error);
294
- next(error);
295
- }
296
- });
297
-
298
331
  await server.listen();
299
332
  const urls = server.resolvedUrls ?? { local: [], network: [] };
300
333
  emit("listening", {
301
334
  local: urls.local,
302
335
  network: urls.network,
303
- routes: scanRoutes(path.resolve(root, config.app?.router?.root ?? "app")).routes.map(
304
- (route) => route.path,
305
- ),
336
+ routes: scanRoutes(path.resolve(root, config.app?.router?.root ?? "app"), {
337
+ target: routeTarget,
338
+ }).routes.map((route) => route.path),
306
339
  });
307
340
  watchSources(server);
341
+ watchEnvFiles(server);
308
342
 
309
343
  const shutdown = async () => {
310
344
  await server.close();
@@ -351,6 +385,45 @@ function watchSources(server) {
351
385
  }
352
386
  }
353
387
 
388
+ /**
389
+ * Restart the server when one of the `.env` files uf read changes.
390
+ *
391
+ * uf reads the `.env` cascade itself, in Rust, before this process starts —
392
+ * one parser, one precedence, one answer for every command (see `viteConfig`
393
+ * above and `crates/uf_config/src/env_files.rs`) — and `envDir: false` turns
394
+ * Vite's own file loading off so there cannot be two answers. The cost of that
395
+ * was that nothing watched them: a value edited while `uf dev` ran changed
396
+ * nothing until somebody restarted the command by hand, and the guide had to
397
+ * document it as a limitation. See ubugeeei-prod/uf#428.
398
+ *
399
+ * `uf` passes the files it would consult with `--uf-env-file`, one per file, in
400
+ * cascade order, whether or not each exists today — a `.env.local` *created*
401
+ * while the server runs changes the answer exactly as much as an edit to one
402
+ * that was already there, and watching only what was read would have missed
403
+ * it. They are added to Vite's watcher explicitly because they are in no
404
+ * module graph, which is the same reason the RSC manifest is added in
405
+ * `index.js`.
406
+ *
407
+ * What is emitted is "these values are stale", and the Rust side restarts this
408
+ * process with the files re-read. A restart rather than a hot update is the
409
+ * honest granularity: a prefixed value reaches the browser by substitution
410
+ * into the bundle, so a new value has to be substituted again, and every
411
+ * module that read one has to be re-evaluated. Vite's watcher is still the
412
+ * only watcher — a second one over the same tree, in Rust, would be a second
413
+ * answer to "did this file change".
414
+ */
415
+ function watchEnvFiles(server) {
416
+ const files = argumentAll("--uf-env-file").map((file) => path.resolve(root, file));
417
+ if (files.length === 0) return;
418
+ const watched = new Set(files);
419
+ server.watcher.add(files);
420
+ for (const event of ["add", "change", "unlink"]) {
421
+ server.watcher.on(event, (file) => {
422
+ if (watched.has(path.resolve(file))) emit("env-changed", { file, change: event });
423
+ });
424
+ }
425
+ }
426
+
354
427
  /**
355
428
  * The preview server: the build, as Vite serves it.
356
429
  *
@@ -370,22 +443,52 @@ function watchSources(server) {
370
443
  * The static middleware still runs first, and that is deliberate rather than
371
444
  * incidental; see `internal/serve.js` for why `uf start` orders itself the
372
445
  * same way.
446
+ *
447
+ * One request is the exception, and it is the only thing uf mounts in *front*
448
+ * of Vite here: a request carrying the draft cookie, which no front door may
449
+ * answer from a prerendered document. `createStaticHandler` applies that rule
450
+ * and cannot reach a request Vite's file middleware answered first, so under
451
+ * `uf preview` draft mode appeared to be off while it worked under `uf dev`
452
+ * and `uf start` — ubugeeei-prod/uf#620. `configurePreviewServer` is where a
453
+ * middleware goes ahead of Vite's own; the hook's *body* runs before they are
454
+ * installed and a function it returns runs after, which is why this is a body
455
+ * and the handler below is a `use` on the started server.
373
456
  */
374
457
  async function preview() {
375
458
  const { preview: startPreview } = await import("vite");
376
459
  const config = await loadConfig();
460
+ const routeTarget = resolveRouteTarget(config, argument("--target"));
377
461
  const inline = await viteConfig(config, argument("--mode") ?? "production");
378
- const build = await loadBuild({
379
- root,
380
- outDir: inline.build.outDir,
381
- serverDir: path.join(".uf", "build", "server"),
382
- });
462
+ // A build that declared it emits no server has none to mount. `uf` refuses
463
+ // `uf start` for such a project and lets this one through, because a preview
464
+ // of files *is* the deployment: what a static host does with `dist/` is
465
+ // exactly what Vite's preview server does with it, and mounting a request
466
+ // handler behind it would make this preview right about a deployment that is
467
+ // not the one happening. See `uf_cli`'s `commands::serve`.
468
+ const staticBuild = flag("--static-build");
469
+ const build = staticBuild
470
+ ? null
471
+ : await loadBuild({
472
+ root,
473
+ outDir: inline.build.outDir,
474
+ serverDir: path.join(".uf", "build", "server"),
475
+ });
383
476
 
384
- const server = await startPreview({ ...inline, appType: "custom" });
385
- const handle = createServeHandler(build);
386
- server.middlewares.use(async (request, response, next) => {
477
+ // One handler for both positions in the chain. A draft request meets it in
478
+ // front of Vite's file middleware and every other request meets it behind,
479
+ // and because it is the same handler the two give the same answer — which is
480
+ // the whole reason `uf preview` exists.
481
+ const handle =
482
+ build == null
483
+ ? null
484
+ : createServeHandler({
485
+ ...build,
486
+ cache: config.app?.rendering?.cache,
487
+ images: config.app?.builtins?.images,
488
+ });
489
+ const answer = (previewServer) => async (request, response, next) => {
387
490
  try {
388
- const asRequest = await toRequest(request, server.config);
491
+ const asRequest = await toRequest(request, previewServer.config);
389
492
  // The same lifecycle `uf start` gets from `nodeListener`, spelled out
390
493
  // because this door is Vite's connect chain rather than a bare
391
494
  // `node:http` server: the whole request runs inside it, and it settles
@@ -398,14 +501,107 @@ async function preview() {
398
501
  } catch (error) {
399
502
  next(error);
400
503
  }
504
+ };
505
+
506
+ const mayAnswerFromPrerender = createPrerenderGate();
507
+ const draftFirst = {
508
+ name: "uf:draft-before-files",
509
+ configurePreviewServer(previewServer) {
510
+ // `app.router.headers` and `redirects`, first of all: a redirect answers
511
+ // before a file is looked for, and a header is pinned on the response so
512
+ // it survives the `writeHead` Vite's file middleware writes its own
513
+ // with. `uf start` and every adapter put the same two in front of their
514
+ // static half; the application's own answers get them from
515
+ // `createServeHandler` behind. See `internal/serve.js`'s `answerRouting`.
516
+ const routing = build?.entry?.routing;
517
+ if (answersInFrontOfFiles(routing)) {
518
+ previewServer.middlewares.use((request, response, next) => {
519
+ answerRouting(routing, toAddressRequest(request), response)
520
+ .then((answered) => {
521
+ if (answered) return;
522
+ // The bare base path is the root, which Vite only knows as
523
+ // `/docs/`; see `forViteBase`.
524
+ forViteBase(routing, request);
525
+ next();
526
+ })
527
+ .catch(next);
528
+ });
529
+ }
530
+ // A prerendered payload is a file whose extension Vite's static middleware
531
+ // knows no type for, and the router hands bytes to React only when they
532
+ // are answered as a payload — so a navigation on a preview would silently
533
+ // become a document load. Set here, in front of the file server, which
534
+ // keeps a type it did not choose.
535
+ previewServer.middlewares.use((request, response, next) => {
536
+ if ((request.url ?? "").split("?")[0].endsWith("/__uf.flight")) {
537
+ response.setHeader("content-type", "text/x-component");
538
+ }
539
+ if ((request.url ?? "").split("?")[0] === "/.well-known/apple-app-site-association") {
540
+ response.setHeader("content-type", "application/json; charset=utf-8");
541
+ }
542
+ next();
543
+ });
544
+ if (handle == null) return;
545
+ const run = answer(previewServer);
546
+ previewServer.middlewares.use((request, response, next) => {
547
+ // Not `await`ed by connect, which takes no promise: the gate is
548
+ // resolved inside and `next()` is called from there. A rejection is a
549
+ // `next(error)` for the same reason.
550
+ mayAnswerFromPrerender(request.headers.cookie ?? null)
551
+ .then((mayAnswer) => (mayAnswer ? next() : run(request, response, next)))
552
+ .catch(next);
553
+ });
554
+ },
555
+ };
556
+
557
+ const server = await startPreview({
558
+ ...inline,
559
+ appType: "custom",
560
+ plugins: [...(inline.plugins ?? []), draftFirst],
401
561
  });
562
+ if (handle != null) {
563
+ server.middlewares.use(answer(server));
564
+ }
565
+ // The rewrite rule a single-page deployment needs, in the one place uf can
566
+ // apply one. A `["csr"]` build writes `index.html` and nothing else that is a
567
+ // page, so a file server answers `/` and 404s every other URL — and this
568
+ // preview exists to be believed about the deployment. A host serving that
569
+ // build has to send unmatched paths to the shell, so a preview that did not
570
+ // would be right about a deployment nobody is doing.
571
+ //
572
+ // Behind the static middleware, which is what makes it a *fallback*: a real
573
+ // file still wins, so `/assets/client.js` is still the chunk and not the
574
+ // shell. And `Accept: text/html` only, so a `fetch` for a missing JSON file
575
+ // gets a 404 rather than a document — the failure mode of a fallback that
576
+ // answers everything is a parse error two layers away from the missing file.
577
+ if (flag("--spa-fallback")) {
578
+ const shell = path.resolve(root, inline.build.outDir, "index.html");
579
+ server.middlewares.use((request, response, next) => {
580
+ if (request.method !== "GET" && request.method !== "HEAD") return next();
581
+ if (!(request.headers.accept ?? "").includes("text/html")) return next();
582
+ if (!existsSync(shell)) return next();
583
+ response.statusCode = 200;
584
+ response.setHeader("content-type", "text/html; charset=utf-8");
585
+ response.end(request.method === "HEAD" ? undefined : readFileSync(shell));
586
+ return undefined;
587
+ });
588
+ }
402
589
 
403
590
  const urls = server.resolvedUrls ?? { local: [], network: [] };
404
591
  emit("listening", {
405
592
  local: urls.local,
406
593
  network: urls.network,
407
- routes: build.entry.routes.map((route) => route.path),
408
- handlers: build.entry.handlers.map((handler) => handler.path),
594
+ // From the filesystem when there is no bundle to ask, which is the same
595
+ // scan `dev` reports from. The count is what a reader checks the build
596
+ // against, so answering "0 routes" for a static site that has thirty would
597
+ // be the report being wrong about the thing it exists to report.
598
+ routes:
599
+ build == null
600
+ ? scanRoutes(path.resolve(root, config.app?.router?.root ?? "app"), {
601
+ target: routeTarget,
602
+ }).routes.map((route) => route.path)
603
+ : build.entry.routes.map((route) => route.path),
604
+ handlers: build == null ? [] : build.entry.handlers.map((handler) => handler.path),
409
605
  });
410
606
 
411
607
  const shutdown = async () => {
@@ -447,7 +643,16 @@ async function start() {
447
643
 
448
644
  const host = argument("--host") ?? process.env.HOST ?? "0.0.0.0";
449
645
  const port = Number(argument("--port") ?? process.env.PORT ?? 3000);
450
- const server = createHttpServer(nodeListener(createServeHandler(build), build.entry));
646
+ const server = createHttpServer(
647
+ nodeListener(
648
+ createServeHandler({
649
+ ...build,
650
+ cache: config.app?.rendering?.cache,
651
+ images: config.app?.builtins?.images,
652
+ }),
653
+ build.entry,
654
+ ),
655
+ );
451
656
 
452
657
  await new Promise((resolve, reject) => {
453
658
  server.once("error", reject);
@@ -482,18 +687,76 @@ async function build() {
482
687
  const inline = await viteConfig(config, mode);
483
688
  const outDir = path.resolve(root, inline.build.outDir);
484
689
  const serverDir = path.join(root, ".uf", "build", "server");
690
+ // How much of the route table to prerender, and whether the server bundle
691
+ // survives the build. Both are `uf`'s answer rather than this file's: they
692
+ // come from two settings in `uf.config.js` that only mean something read
693
+ // together, and `uf_config`'s `RenderingPlan` is where they are. A driver
694
+ // started by hand gets the behaviour every uf build had before either
695
+ // setting was read.
696
+ const prerender = argument("--prerender") ?? "possible";
697
+ const staticBuild = flag("--static-build");
698
+ const because = argument("--because") ?? "this build prerenders every route";
699
+
700
+ // 0. The rsc graph, for an application React Server Components render: the
701
+ // route table and every server component, resolved under `react-server`.
702
+ // First, because it is what finds the client modules the next pass has
703
+ // to build; `./internal/flight.js` has the order and the reason for it.
704
+ const flight = flightStateOf(inline);
705
+ // `uf build --analyze`: the graph every bundle below is built from, for uf
706
+ // to attribute to routes; see `./internal/module-graph.js`. A client module
707
+ // is an entry the browser loads because a server component names it, not on
708
+ // every page, so it is not one of the client bundle's shared entries.
709
+ const graph = flag("--analyze")
710
+ ? createModuleGraphCollector(root, {
711
+ isReference: (file) => flight?.clientModules.has(file) ?? false,
712
+ })
713
+ : null;
714
+ if (graph != null) {
715
+ inline.plugins = [...(inline.plugins ?? []), graph.plugin];
716
+ }
717
+ // What this build is called, minted before anything is bundled: the rsc
718
+ // graph bakes the public half into every payload it renders, and the
719
+ // documents below carry it in their head. See `deploymentIdFor`.
720
+ const buildId = mintBuildId();
721
+ const deployment = deploymentIdFor(buildId);
722
+ const rscDir = path.join(root, ".uf", "build", "rsc");
723
+ if (flight != null) {
724
+ flight.deployment = deployment;
725
+ emit("phase", { name: "rsc" });
726
+ await buildRscGraph(vite, inline, flight, { outDir: rscDir, conditions: null });
727
+ }
485
728
 
486
729
  // 1. The client: everything the browser loads, with a manifest so the
487
- // server render knows which script and stylesheet tags to write.
730
+ // server render knows which script and stylesheet tags to write. Under
731
+ // React Server Components that is the entry and one entry per client
732
+ // module, each keeping its export names, because a payload asks for a
733
+ // chunk by its URL and for a component by its export.
488
734
  emit("phase", { name: "client" });
735
+ const references = flight == null ? [] : [...flight.clientModules].sort();
736
+ const input = { client: VIRTUAL.client };
737
+ references.forEach((file, index) => {
738
+ input[`client-reference-${index}`] = file;
739
+ });
489
740
  await vite.build({
490
741
  ...inline,
491
742
  build: {
492
743
  ...inline.build,
493
- rollupOptions: { input: { client: VIRTUAL.client } },
744
+ rollupOptions:
745
+ flight == null ? { input } : { input, preserveEntrySignatures: "exports-only" },
494
746
  },
495
747
  });
496
748
  const manifest = readManifest(outDir);
749
+ if (flight != null) {
750
+ recordClientChunks(flight, manifest, references, rscDir, basePathOf(config));
751
+ // What the summary's "pages in the client bundle" reads. None: a browser
752
+ // that hydrates a payload imports no page, whichever route it is on.
753
+ emit("rsc-split", {
754
+ pages: 0,
755
+ routes: scanRoutes(path.resolve(root, config.app?.router?.root ?? "app"), {
756
+ target: resolveRouteTarget(config, argument("--target")),
757
+ }).routes.length,
758
+ });
759
+ }
497
760
 
498
761
  // 2. The server entry, bundled for the host, outside `dist/` so it is never
499
762
  // deployed by accident.
@@ -513,12 +776,66 @@ async function build() {
513
776
  },
514
777
  },
515
778
  });
516
-
517
- // 3. Every static route, rendered to an HTML document.
779
+ // What this build is, beside the bundle it is about. One line, written by
780
+ // every build and read by nothing unless a project turned a durable cache on
781
+ // — at which point it is the thing that stops a deploy answering the new
782
+ // build's URLs with the previous build's documents. See
783
+ // `packages/server/internal/cache-key.js`, which argues the whole of it, and
784
+ // `internal/serve.js`'s `buildIdentity`, which is what reads this.
785
+ writeFileSync(path.join(serverDir, BUILD_ID_FILE), `${buildId}\n`);
786
+
787
+ // Every bundle is built by here, and the prerender below builds none.
788
+ graph?.write(path.join(root, ".uf", "build", "meta", MODULE_GRAPH_FILE));
789
+
790
+ // 3. Which routes this build renders when, and every route it renders now.
791
+ //
792
+ // The decision comes from `uf.config.js` and is made in Rust — see
793
+ // `uf_config`'s `RenderingPlan` — because `app.rendering.modes` and
794
+ // `build.staticBuild` are two settings that have to be read together. It
795
+ // arrives here as one word, and this is where it meets the route table.
518
796
  emit("phase", { name: "prerender" });
519
797
  const server = await import(pathToFileURL(path.join(serverDir, "server.js")).href);
520
- const assets = assetsFromManifest(manifest);
521
- const pages = await staticPaths(server.routes);
798
+ const assets = {
799
+ ...(flight == null
800
+ ? assetsFromManifest(manifest, basePathOf(config))
801
+ : flightAssets(manifest, references, rscDir, outDir, basePathOf(config))),
802
+ // Which build these URLs are. Every document names it, a browser sends it
803
+ // back, and a server on another build refuses rather than answering with
804
+ // ids and chunks the page does not have. See `deploymentIdFor`.
805
+ deployment,
806
+ };
807
+ // Recorded beside the server bundle, because whatever serves this build
808
+ // later cannot recompute them from the client manifest alone; see
809
+ // `documentAssetsFor`.
810
+ writeFileSync(path.join(serverDir, DOCUMENT_ASSETS_FILE), `${JSON.stringify(assets, null, 2)}\n`);
811
+ const openapi = await createOpenApiDocument(server.handlers);
812
+ const openapiFile = path.join(root, ".uf", "build", "meta", "openapi.json");
813
+ mkdirSync(path.dirname(openapiFile), { recursive: true });
814
+ writeFileSync(openapiFile, `${JSON.stringify(openapi, null, 2)}\n`);
815
+ const plan = await renderingPlan(server, prerender);
816
+ emit("rendering", {
817
+ prerender,
818
+ prerendered: plan.urls.length,
819
+ perRequest: plan.perRequest.map((route) => route.path),
820
+ });
821
+ // A build that has to prerender everything, and a route it cannot: the
822
+ // refusal ubugeeei-prod/uf#336 and ubugeeei-prod/uf#385 are both about.
823
+ // Before the loop below, so no document is written for a build that is not
824
+ // going to be one, and with the whole list rather than the first item — a
825
+ // project that has just narrowed `rendering.modes` wants to see every route
826
+ // the narrowing costs it, not one per rebuild.
827
+ if (prerender === "everything" && plan.perRequest.length > 0) {
828
+ const listed = plan.perRequest.map((entry) => ` ${entry.path} — ${entry.why}`).join("\n");
829
+ emit("error", {
830
+ message:
831
+ `${plan.perRequest.length} ${plural(plan.perRequest.length, "route")} in this project ` +
832
+ `can only be answered by a server, and ${because}\n${listed}\n\n` +
833
+ "Give each page a `generateStaticParams` and take out the handlers and middleware, or " +
834
+ 'allow `"ssr"` in `app.rendering.modes` and deploy a server.',
835
+ });
836
+ process.exit(1);
837
+ }
838
+ const pages = plan.urls;
522
839
 
523
840
  // A route that throws fails *that route*, and the rest of the build still
524
841
  // happens. This loop had no `try`: the first page to throw rejected out of
@@ -541,28 +858,120 @@ async function build() {
541
858
  failures.push(url);
542
859
  emit("page-failed", { url, ...errorEvent(error) });
543
860
  };
861
+ //
862
+ // Each prerender runs inside a fill that stores nothing, so what a page states
863
+ // with `cacheLife`, `cacheTag` and `noStore` is something this loop can read
864
+ // rather than a call that throws for want of a scope.
865
+ //
866
+ // A page is written for regeneration when `uf` passed `--regenerate` — `isr`
867
+ // allowed in `app.rendering.modes`, `rendering.cache.route` on, and a server
868
+ // deployed to regenerate it — and the page stated a lifetime, called no
869
+ // `noStore`, and answered 200. Its document goes under
870
+ // `REGENERATED_DIRECTORY` rather than at its own URL, so no static half
871
+ // answers the page: the server does, starting from this document, until the
872
+ // lifetime has passed. What it stated goes into `REGENERATION_FILE` beside the
873
+ // server bundle. Every other page is the document it has always been.
874
+ //
875
+ // A tag without a lifetime is not enough, for the route cache's own reason:
876
+ // an entry with no end is one another process could serve from its memory
877
+ // for ever after `revalidateTag` took it out of the shared store.
878
+ //
879
+ // A page is written as a static shell when `uf` passed `--partial` — `ppr`
880
+ // allowed in `app.rendering.modes` and a server deployed to fill it — and the
881
+ // page read `cookies()`, `headers()` or `draftMode()` inside a `<Suspense>`
882
+ // boundary. The prerender then answers with a `shell` instead of a document:
883
+ // the markup React could render without a request, and React's record of the
884
+ // holes. Nothing is written under `dist/` for it, neither a document nor a
885
+ // payload, because a shell on its own is a page whose holes never fill and
886
+ // the browser hydrates from the request's payload. The shell goes into
887
+ // `PARTIAL_PRERENDER_FILE` beside the server bundle, and every server that
888
+ // serves this build answers the page from there. A page that read the
889
+ // request outside every boundary still fails, naming what it read.
890
+ const { collectCacheDeclarations } = await import("@uniflowed/server/cache");
891
+ const regenerate = flag("--regenerate");
892
+ const partialPrerender = flag("--partial");
893
+ const regenerated = {};
894
+ const partial = {};
544
895
  for (const url of pages) {
545
- let result;
896
+ let declared;
897
+ const renderedAt = Date.now();
546
898
  try {
547
- result = await server.prerender(url, assets);
899
+ declared = await collectCacheDeclarations(() =>
900
+ server.prerender(url, assets, partialPrerender ? { partial: true } : undefined),
901
+ );
548
902
  } catch (error) {
549
903
  failed(url, error);
550
904
  continue;
551
905
  }
906
+ const result = declared.value;
552
907
  if (result.error != null) {
553
908
  failed(url, result.error);
554
909
  continue;
555
910
  }
556
- const file = htmlPathFor(outDir, url);
911
+ if (result.shell != null) {
912
+ partial[url] = result.shell;
913
+ emit("page", {
914
+ url,
915
+ file: path.relative(root, path.join(serverDir, PARTIAL_PRERENDER_FILE)),
916
+ status: result.status,
917
+ bytes: Buffer.byteLength(result.shell.html),
918
+ regenerates: false,
919
+ partial: true,
920
+ });
921
+ continue;
922
+ }
923
+ const lifetime = declared.lifetime;
924
+ const regenerates =
925
+ regenerate && result.status === 200 && declared.denied == null && lifetime != null;
926
+ // The trailing-slash policy decides a served page's file name; a page the
927
+ // build regenerates keeps the one layout the regeneration reads.
928
+ const file = regenerates
929
+ ? htmlPathFor(path.join(outDir, REGENERATED_DIRECTORY), url)
930
+ : htmlPathFor(outDir, url, routingRulesOf(config.app?.router).trailingSlash);
557
931
  mkdirSync(path.dirname(file), { recursive: true });
558
932
  writeFileSync(file, result.html);
933
+ // The payload the document was rendered from, beside it: what a browser
934
+ // navigating to this route fetches, from whatever serves the files. Beside
935
+ // the document wherever the document went, so a page written for
936
+ // regeneration leaves no file at its route's own payload URL answering with
937
+ // the build's copy for ever; the server answers that URL instead.
938
+ if (result.payload != null) {
939
+ // Beside the route's directory whatever the document is called:
940
+ // `guide/index.html` and `guide.html` both put it at `guide/__uf.flight`.
941
+ const payloadDirectory =
942
+ path.basename(file) === "index.html" ? path.dirname(file) : file.slice(0, -".html".length);
943
+ mkdirSync(payloadDirectory, { recursive: true });
944
+ writeFileSync(path.join(payloadDirectory, "__uf.flight"), result.payload);
945
+ }
946
+ if (regenerates) {
947
+ regenerated[url] = {
948
+ document: regeneratedDocumentUrl(url),
949
+ renderedAt,
950
+ revalidate: lifetime.revalidate,
951
+ expire: lifetime.expire ?? null,
952
+ tags: declared.tags,
953
+ };
954
+ }
559
955
  emit("page", {
560
956
  url,
561
957
  file: path.relative(root, file),
562
958
  status: result.status,
563
959
  bytes: Buffer.byteLength(result.html),
960
+ regenerates,
564
961
  });
565
962
  }
963
+ if (Object.keys(regenerated).length > 0) {
964
+ writeFileSync(
965
+ path.join(serverDir, REGENERATION_FILE),
966
+ `${JSON.stringify({ pages: regenerated }, null, 2)}\n`,
967
+ );
968
+ }
969
+ if (Object.keys(partial).length > 0) {
970
+ writeFileSync(
971
+ path.join(serverDir, PARTIAL_PRERENDER_FILE),
972
+ `${JSON.stringify({ pages: partial })}\n`,
973
+ );
974
+ }
566
975
  // One `404.html`, from the boundary at the router root: a static host serves
567
976
  // a single error document for the whole site, so the nested boundaries a
568
977
  // project declares are the server's and the client's to render, not
@@ -570,7 +979,7 @@ async function build() {
570
979
  //
571
980
  // The condition is "there is a root boundary", not "there is any boundary",
572
981
  // because `/__uf_not_found__` is a path at the root: a project whose only
573
- // `_uf.not-found.js` is in `app/guide/` would otherwise get a `404.html`
982
+ // `$not-found.js` is in `app/guide/` would otherwise get a `404.html`
574
983
  // rendered from the framework's bare default, which is worse than the file
575
984
  // it used to write, which was none.
576
985
  //
@@ -582,7 +991,50 @@ async function build() {
582
991
  // host would then serve uf's error page to every visitor who mistyped a URL,
583
992
  // and nothing between the throw and the deploy would have mentioned it.
584
993
  let attempted = pages.length;
585
- if (server.notFound.some((boundary) => boundary.path === "/")) {
994
+ // The single-page build's whole output, written here because it is the one
995
+ // document this build has and the loop above had no route to write it for.
996
+ //
997
+ // Twice, to two names, and the second is the load-bearing one. `index.html`
998
+ // is what a host serves for `/`; `404.html` is what a static host serves for
999
+ // every path it has no file for, which under this plan is *every other URL
1000
+ // in the application*. Without it a deployment of `dist/` answers `/` and
1001
+ // 404s `/orders` — a build with a hole in it, found from a 404, which is the
1002
+ // failure ubugeeei-prod/uf#336 is about wearing a different hat.
1003
+ //
1004
+ // It is still the host's rewrite rule that makes this correct, and the two
1005
+ // files are what uf can do without one: a host with a proper SPA fallback
1006
+ // serves `index.html` and never looks at `404.html`, and a host with only an
1007
+ // error document (Pages, Netlify, an S3 bucket) serves `404.html` and gets
1008
+ // the same bytes with a 404 status — which is the right status for a URL
1009
+ // this application does not have, and the not-found boundary is what the
1010
+ // browser then renders into it.
1011
+ if (prerender === "shell") {
1012
+ const html = server.shellDocument(assets);
1013
+ for (const [file, url, status] of [
1014
+ ["index.html", "/", 200],
1015
+ ["404.html", "/404", 404],
1016
+ ]) {
1017
+ const target = path.join(outDir, file);
1018
+ writeFileSync(target, html);
1019
+ attempted += 1;
1020
+ emit("page", {
1021
+ url,
1022
+ file: path.relative(root, target),
1023
+ status,
1024
+ bytes: Buffer.byteLength(html),
1025
+ });
1026
+ }
1027
+ }
1028
+ // Not for a build that prerenders nothing. `404.html` is a file a static
1029
+ // host serves for every path it has no file for, and a project whose
1030
+ // `rendering.modes` allows only `ssr` has no such host: its not-found
1031
+ // boundary is rendered per request, by the server, with the right status.
1032
+ //
1033
+ // Nor for a shell build, which has just written its own: the boundary this
1034
+ // would render is one the *browser* renders in that plan, and a document
1035
+ // holding the framework's 404 markup would be served in place of the shell
1036
+ // for every URL the host could not match.
1037
+ else if (prerender !== "nothing" && server.notFound.some((boundary) => boundary.path === "/")) {
586
1038
  attempted += 1;
587
1039
  // `/404` rather than `/__uf_not_found__`: the internal path is how the
588
1040
  // router is asked, and the file the reader is looking for is `404.html`.
@@ -629,10 +1081,161 @@ async function build() {
629
1081
  process.exit(1);
630
1082
  }
631
1083
 
1084
+ // `build.staticBuild` is "prerender everything and emit no server bundle",
1085
+ // and this is the second half of it. The bundle is still *built*: the
1086
+ // prerender renders through it, so a build with no server bundle at any
1087
+ // point would be a build with no documents either. What the declaration is
1088
+ // about is what is left behind — so it goes once the last document is
1089
+ // written, and `uf start`, `uf preview` and every server adapter then find
1090
+ // nothing to serve, which is the honest outcome for a project that said it
1091
+ // deploys files.
1092
+ if (staticBuild) rmSync(serverDir, { recursive: true, force: true });
1093
+
632
1094
  emit("done", { outDir: path.relative(root, outDir), pages: pages.length });
633
1095
  process.exit(0);
634
1096
  }
635
1097
 
1098
+ /**
1099
+ * The library build, for a project whose `app.router.enabled` is false.
1100
+ *
1101
+ * `build` above is an application build and has no other mode: it links
1102
+ * `virtual:uf/client`, which imports the router and the project's `app.js`.
1103
+ * A library has neither, so `uf build` in a project `uf create lib`
1104
+ * scaffolded failed at the first pass with `Could not resolve '<root>/app.js'`
1105
+ * — a file a library does not have and never had. See ubugeeei-prod/uf#268.
1106
+ *
1107
+ * This is the fourth thing the driver does, beside `dev`, `build` and
1108
+ * `compile`, and it is one pass per format over one input list. Which of the
1109
+ * two builds runs is **not decided here**: `uf` resolves it from the config
1110
+ * (`uf_config`'s `LibraryPlan`) and spawns this subcommand, the same way
1111
+ * `--prerender` arrives as one word rather than as two settings for this file
1112
+ * to read together.
1113
+ *
1114
+ * # The three ways it differs from the application build
1115
+ *
1116
+ * * **Every dependency stays an import.** `--external` names them, and
1117
+ * `uf` computes the list from the project's own manifest —
1118
+ * `dependencies`, `peerDependencies`, `optionalDependencies` — so a
1119
+ * library ships its own modules and nobody else's. That is the opposite
1120
+ * of the application build, which inlines what it can because an
1121
+ * application is the end of the line and a library is not: a bundled copy
1122
+ * of React inside a library is a second React in every application that
1123
+ * installs it.
1124
+ * * **One output per entry, named after the entry.** `index.js` becomes
1125
+ * `dist/index.js`; `internal/parse.js` becomes `dist/internal/parse.js`.
1126
+ * The path rather than the basename, so two entries cannot collide at the
1127
+ * moment one would overwrite the other.
1128
+ * * **No manifest, no prerender, no server bundle.** There is no document to
1129
+ * write and no route table to write it from.
1130
+ *
1131
+ * Vite's own `build.lib` does the work. uf owns *that* a library is a
1132
+ * different build and what goes into it; how this builder performs one is the
1133
+ * builder's, which is the same line `build` draws around `rollupOptions`.
1134
+ */
1135
+ async function library() {
1136
+ const vite = await import("vite");
1137
+ const config = await loadConfig();
1138
+ const inline = await viteConfig(config, argument("--mode") ?? "production");
1139
+ const outDir = path.resolve(root, inline.build.outDir);
1140
+ const entries = argumentAll("--entry");
1141
+ const formats = argumentAll("--format");
1142
+ const external = argumentAll("--external");
1143
+ if (entries.length === 0) {
1144
+ throw new Error("uf: `driver.js library` needs at least one --entry");
1145
+ }
1146
+ if (formats.length === 0) {
1147
+ throw new Error("uf: `driver.js library` needs at least one --format");
1148
+ }
1149
+
1150
+ // Keyed by the entry's path without its extension, which is what Vite's lib
1151
+ // mode turns into the output file name.
1152
+ const input = {};
1153
+ for (const entry of entries) {
1154
+ input[entryName(entry)] = path.resolve(root, entry);
1155
+ }
1156
+
1157
+ const isExternal = externalTest(external);
1158
+ // One pass per format rather than one build with several outputs: Vite's
1159
+ // lib mode writes a whole `outDir` per format, and the second pass must not
1160
+ // empty what the first wrote. So `emptyOutDir` is true exactly once, on the
1161
+ // first, which is also what makes a build that dropped an entry leave no
1162
+ // stale copy of it behind.
1163
+ let first = true;
1164
+ for (const format of formats) {
1165
+ emit("phase", { name: `library (${format})` });
1166
+ await vite.build({
1167
+ ...inline,
1168
+ build: {
1169
+ ...inline.build,
1170
+ // Vite's `manifest` maps source modules to hashed browser assets. A
1171
+ // library has neither — its file names are its API — and writing one
1172
+ // would put a `.vite/` directory into a published tarball.
1173
+ manifest: false,
1174
+ outDir,
1175
+ emptyOutDir: first,
1176
+ lib: {
1177
+ entry: input,
1178
+ formats: [format],
1179
+ fileName: (_format, name) => `${name}.${format === "cjs" ? "cjs" : "js"}`,
1180
+ },
1181
+ rollupOptions: { external: isExternal },
1182
+ },
1183
+ });
1184
+ first = false;
1185
+ }
1186
+
1187
+ emit("done", { outDir: path.relative(root, outDir), pages: 0 });
1188
+ process.exit(0);
1189
+ }
1190
+
1191
+ /**
1192
+ * The output name for one entry: its path, without the extension.
1193
+ *
1194
+ * Not the basename. `index.js` and `internal/index.js` are two entries a
1195
+ * library can reasonably have, and under a basename they are one file written
1196
+ * twice — the second silently winning, which is a published package whose
1197
+ * subpath export is somebody else's module.
1198
+ */
1199
+ function entryName(entry) {
1200
+ const normalised = entry.replace(/\\/g, "/").replace(/^\.\//, "");
1201
+ const dot = normalised.lastIndexOf(".");
1202
+ const slash = normalised.lastIndexOf("/");
1203
+ return dot > slash ? normalised.slice(0, dot) : normalised;
1204
+ }
1205
+
1206
+ /**
1207
+ * Whether an import is somebody else's module.
1208
+ *
1209
+ * Three checks, and only the one over `names` is a policy uf decided. `names`
1210
+ * is what `uf` read out of the project's manifest and passed as `--external`,
1211
+ * and a subpath of one of those names — `@scope/pkg/deep` for `@scope/pkg` —
1212
+ * is the same package. The other two are the host's built-in modules, and they
1213
+ * are a fact rather than a decision: `node:fs` has no bytes to inline.
1214
+ *
1215
+ * A bare relative or absolute id is never external, which is the rule that
1216
+ * makes this a library build at all: what the author wrote is bundled, and
1217
+ * what they installed is imported.
1218
+ */
1219
+ function externalTest(names) {
1220
+ const declared = new Set(names);
1221
+ // The host's built-in module names, unprefixed. `node:`-prefixed ids are
1222
+ // caught by the first check whatever the host is; this set is for the bare
1223
+ // spellings — `fs`, `path`, `stream` — which a dependency written before the
1224
+ // prefix existed still uses. Read from the running host rather than written
1225
+ // down, because the list grows and a stale copy of it here would be a
1226
+ // bundled `node:worker_threads` that cannot be bundled.
1227
+ const builtins = new Set(builtinModules ?? []);
1228
+ return (id) => {
1229
+ if (id.startsWith("node:")) return true;
1230
+ if (builtins.has(id)) return true;
1231
+ if (declared.has(id)) return true;
1232
+ for (const name of declared) {
1233
+ if (id.startsWith(`${name}/`)) return true;
1234
+ }
1235
+ return false;
1236
+ };
1237
+ }
1238
+
636
1239
  /**
637
1240
  * Link the whole application into one JavaScript file, for `uf build --compile`.
638
1241
  *
@@ -690,21 +1293,42 @@ async function compile() {
690
1293
  }
691
1294
  const assets = path.resolve(root, assetsArgument);
692
1295
  const bundleDir = path.resolve(root, bundleArgument);
1296
+ // The compiled binary answers from `@uniflowed/server/standalone`, which has
1297
+ // no `/__uf/image` — and it would still carry pages whose `Image` writes the
1298
+ // endpoint's URLs. Refused by name rather than compiled into a binary whose
1299
+ // remote images are all 404s. See docs/app/guide/assets.
1300
+ if (servesRemoteImages(config.app?.builtins?.images)) {
1301
+ throw new Error(
1302
+ "uf: app.builtins.images.remotePatterns lists remote hosts, and a `--compile` binary " +
1303
+ "has no /__uf/image to answer them: it carries neither the `uf` encoder nor a place " +
1304
+ "to name one. Serve the build with `uf start` or an `--adapter`, or remove the remote " +
1305
+ "patterns. See docs/app/guide/assets.",
1306
+ );
1307
+ }
693
1308
 
694
1309
  emit("phase", { name: "standalone" });
695
1310
 
696
1311
  // The entry is written to disk rather than served as another virtual module:
697
- // it is generated per build (it names this build's asset file), and a real
1312
+ // it is generated per build (it bakes in this build's document), and a real
698
1313
  // file is the version a person can open when a compiled binary misbehaves.
699
1314
  const entry = path.join(bundleDir, "entry.js");
700
1315
  mkdirSync(bundleDir, { recursive: true });
701
- const specifier = `./${path.relative(bundleDir, assets)}`;
702
- writeFileSync(entry, entrySource(specifier, assetsFromManifest(readManifest(outDir))));
1316
+ writeFileSync(
1317
+ entry,
1318
+ entrySource(
1319
+ path.relative(root, assets),
1320
+ await documentAssetsFor(path.join(root, ".uf", "build", "server"), readManifest(outDir)),
1321
+ ),
1322
+ );
1323
+
1324
+ // The rsc graph `uf build` built, and the client chunks its references name.
1325
+ const flight = flightStateOf(inline);
1326
+ if (flight != null) loadFlightBuild(flight, path.join(root, ".uf", "build", "rsc"));
703
1327
 
704
1328
  await vite.build({
705
1329
  ...inline,
706
1330
  customLogger: eventLogger("warn"),
707
- plugins: [...inline.plugins, nativeAddonGuard()],
1331
+ plugins: [...inline.plugins, nativeAddonGuard(), compileAssetsPlugin(assets)],
708
1332
  ssr: { ...(inline.ssr ?? {}), noExternal: true },
709
1333
  build: {
710
1334
  ...inline.build,
@@ -737,46 +1361,182 @@ async function compile() {
737
1361
  * of what an adapter is, and keeping the differences in one object is what
738
1362
  * stops a second one from quietly becoming a second application.
739
1363
  *
740
- * `bun`, `deno` and `static` are deliberately absent; `uf_config`'s
1364
+ * `static` is deliberately absent; `uf_config`'s
741
1365
  * `DeployAdapter::is_implemented` is the other half of that fact and
742
- * `docs/app/reference/cli/_uf.page.mdx` says why for each of them.
1366
+ * `docs/app/reference/cli/$page.mdx` says why.
1367
+ *
1368
+ * `regenerationStore` is where a target keeps the pages a build regenerates
1369
+ * when `rendering.cache.store` names nothing: a disk for a process with one,
1370
+ * Workers KV for a Worker, and `null` for a Lambda, which keeps nothing between
1371
+ * invocations and is refused by name instead. A regenerated page kept only in
1372
+ * memory would go back to the build's copy on every restart, which is a page
1373
+ * that travels back in time. See [`deploy`].
1374
+ *
1375
+ * `streams: false` marks the one target whose responses are buffered whole.
1376
+ * A page the build prerendered partially is worth nothing there — its shell is
1377
+ * the part that was meant to arrive first — so such a build is refused by name
1378
+ * rather than deployed as a page that waits for its slowest hole.
743
1379
  */
744
1380
  const ADAPTERS = {
745
1381
  node: {
746
- entries: (document) => ({
747
- handler: handlerEntrySource(document),
748
- server: nodeEntrySource("./handler.js"),
1382
+ entries: (document, cache, build, schedules, regeneration, images, partial) => ({
1383
+ handler: handlerEntrySource(
1384
+ document,
1385
+ cache,
1386
+ NODE_CAPABILITIES,
1387
+ build,
1388
+ regeneration,
1389
+ images,
1390
+ partial,
1391
+ ),
1392
+ server: nodeEntrySource("./handler.js", schedules),
1393
+ }),
1394
+ regenerationStore: "filesystem",
1395
+ },
1396
+ // The same two files as `node`, with `@uniflowed/server/bun` in place of
1397
+ // `@uniflowed/server/node`. That module is `./internal/static.js` for every
1398
+ // decision and `Bun.file` for the bytes, which is where the measured win is
1399
+ // — see ubugeeei-prod/uf#391 and the header of `packages/server/bun.js`.
1400
+ //
1401
+ // No `conditions` of its own, unlike `edge`. Bun honours a `bun` export
1402
+ // condition and this deliberately does not ask for it: the measured win is
1403
+ // `Bun.serve` and `Bun.file` and not resolution, so asking would trade a
1404
+ // `handler.js` that is byte-for-byte `node`'s — which is what
1405
+ // `every_adapter_answers_exactly_what_the_node_adapter_answers` checks, and
1406
+ // what makes an adapter one file rather than one application — for whichever
1407
+ // build a dependency happens to ship behind that condition, tested by
1408
+ // nobody here. `edge` pays that price because it must: there is no
1409
+ // `node:stream` in a Worker.
1410
+ bun: {
1411
+ entries: (document, cache, build, schedules, regeneration, images, partial) => ({
1412
+ handler: handlerEntrySource(
1413
+ document,
1414
+ cache,
1415
+ BUN_CAPABILITIES,
1416
+ build,
1417
+ regeneration,
1418
+ images,
1419
+ partial,
1420
+ ),
1421
+ server: bunEntrySource("./handler.js", schedules),
749
1422
  }),
1423
+ regenerationStore: "filesystem",
1424
+ },
1425
+ deno: {
1426
+ entries: (document, cache, build, schedules, regeneration, images, partial) => ({
1427
+ handler: handlerEntrySource(
1428
+ document,
1429
+ cache,
1430
+ DENO_CAPABILITIES,
1431
+ build,
1432
+ regeneration,
1433
+ images,
1434
+ partial,
1435
+ ),
1436
+ server: denoEntrySource("./handler.js", schedules),
1437
+ }),
1438
+ regenerationStore: "filesystem",
750
1439
  },
751
1440
  // The same two files. What `--adapter container` adds is a `Dockerfile` and
752
1441
  // a `.dockerignore`, and both are plain text that `uf` writes beside this
753
1442
  // output rather than anything the bundler produces — see `uf_cli`'s
754
1443
  // `commands::deploy`.
755
1444
  container: {
756
- entries: (document) => ({
757
- handler: handlerEntrySource(document),
758
- server: nodeEntrySource("./handler.js"),
1445
+ entries: (document, cache, build, schedules, regeneration, images, partial) => ({
1446
+ handler: handlerEntrySource(
1447
+ document,
1448
+ cache,
1449
+ NODE_CAPABILITIES,
1450
+ build,
1451
+ regeneration,
1452
+ images,
1453
+ partial,
1454
+ ),
1455
+ server: nodeEntrySource("./handler.js", schedules),
759
1456
  }),
1457
+ regenerationStore: "filesystem",
760
1458
  },
761
1459
  edge: {
762
- entries: (document) => ({
763
- handler: handlerEntrySource(document),
764
- worker: workerEntrySource("./handler.js"),
1460
+ entries: (document, cache, build, schedules, regeneration, images, partial) => ({
1461
+ handler: handlerEntrySource(
1462
+ document,
1463
+ cache,
1464
+ EDGE_CAPABILITIES,
1465
+ build,
1466
+ regeneration,
1467
+ images,
1468
+ partial,
1469
+ ),
1470
+ worker: workerEntrySource("./handler.js", schedules),
765
1471
  }),
1472
+ // Workers KV, through the same module seam a project's own provider goes
1473
+ // through. `packages/server/cache-kv.js` argues KV over the Cache API: the
1474
+ // seam has to find every entry under a tag, and the Cache API cannot list
1475
+ // what it holds.
1476
+ regenerationStore: "@uniflowed/server/cache/kv",
766
1477
  // `workerd` first, so React resolves to the build that has
767
1478
  // `renderToReadableStream` and no `node:stream`. `browser` and `module`
768
1479
  // after it are Vite's own SSR defaults, kept so a dependency with no
769
1480
  // worker condition still resolves the way it does for every other target.
770
1481
  conditions: ["workerd", "worker", "edge-light", "browser", "module", "import", "default"],
1482
+ // A Worker has no filesystem, so uf's built-in durable provider cannot run
1483
+ // here. Refused by name at the build rather than linked into a bundle that
1484
+ // fails on its first `node:fs` import — the deployment rule is that a
1485
+ // target which cannot provide a durable store says so, and this is the one
1486
+ // target that cannot.
1487
+ filesystem: false,
1488
+ // And the Node built-ins it has only as stubs, which the link reports by
1489
+ // module and importer. See `./internal/worker-builtins.js`.
1490
+ workerBuiltins: true,
771
1491
  },
772
1492
  serverless: {
773
- entries: (document) => ({
774
- handler: handlerEntrySource(document),
1493
+ entries: (document, cache, build, _schedules, regeneration, images, partial) => ({
1494
+ handler: handlerEntrySource(
1495
+ document,
1496
+ cache,
1497
+ SERVERLESS_CAPABILITIES,
1498
+ build,
1499
+ regeneration,
1500
+ images,
1501
+ partial,
1502
+ ),
775
1503
  lambda: lambdaEntrySource("./handler.js"),
776
1504
  }),
1505
+ // A Lambda's memory lasts one instance and its disk is that instance's
1506
+ // `/tmp`, so neither is somewhere a regenerated page survives. A build that
1507
+ // regenerates pages has to name a provider module; see [`deploy`].
1508
+ regenerationStore: null,
1509
+ // And `@uniflowed/server/lambda` buffers every response into the one
1510
+ // result an invocation returns, so a page's static shell would reach the
1511
+ // browser with its holes, not before them. A build that prerendered a page
1512
+ // partially is refused by name; see [`deploy`].
1513
+ streams: false,
777
1514
  },
778
1515
  };
779
1516
 
1517
+ /**
1518
+ * How each target says what it can do: the module, and the name to call.
1519
+ *
1520
+ * A pair of strings rather than a value, because this is the module that
1521
+ * *writes* `handler.js` and never imports what it writes: the capabilities
1522
+ * belong to the deployed application's copy of `@uniflowed/server`, not to the
1523
+ * driver's. It is the same reason `beginRequest` is re-exported from the
1524
+ * generated file rather than reached for here — see `handlerEntrySource`.
1525
+ *
1526
+ * Nothing is passed for `websocket` or `queue`, and that is not an oversight:
1527
+ * uf defines both and implements neither, so a generated file that invented
1528
+ * one would be inventing an upgrade for a runtime it cannot see. What the call
1529
+ * does supply is the target's name and its two facts, which is what turns "an
1530
+ * upgrade is not available" into "the serverless host cannot hold a socket
1531
+ * open" and what lets `@uniflowed/server/lambda` refuse a queue that would be
1532
+ * dropped.
1533
+ */
1534
+ const NODE_CAPABILITIES = { module: "@uniflowed/server/node", name: "nodeCapabilities" };
1535
+ const BUN_CAPABILITIES = { module: "@uniflowed/server/bun", name: "bunCapabilities" };
1536
+ const DENO_CAPABILITIES = { module: "@uniflowed/server/deno", name: "denoCapabilities" };
1537
+ const EDGE_CAPABILITIES = { module: "@uniflowed/server/edge", name: "edgeCapabilities" };
1538
+ const SERVERLESS_CAPABILITIES = { module: "@uniflowed/server/lambda", name: "lambdaCapabilities" };
1539
+
780
1540
  /**
781
1541
  * Link the application into a directory that can be copied, for
782
1542
  * `uf build --adapter`.
@@ -819,6 +1579,16 @@ const ADAPTERS = {
819
1579
  * copying every file in it is bulk work over the whole build, which belongs in
820
1580
  * Rust rather than in the host process — the same division `--compile` makes
821
1581
  * with its embedded assets.
1582
+ *
1583
+ * # `--adapter static` never reaches this function
1584
+ *
1585
+ * It is the one implemented target with no application to link: a static host
1586
+ * returns files, and `uf build` has already written them. So `uf` copies the
1587
+ * output directory itself and never spawns this driver for it, which is why
1588
+ * [`ADAPTERS`] has six rows and not seven. What that target does instead of
1589
+ * linking is refuse a project whose route handlers, middleware, unprerendered
1590
+ * routes or server actions a static host cannot answer — in Rust, because the
1591
+ * facts it needs are the route table and what the prerender reported.
822
1592
  */
823
1593
  async function deploy() {
824
1594
  const vite = await import("vite");
@@ -831,6 +1601,12 @@ async function deploy() {
831
1601
  if (adapter == null || workArgument == null || outputArgument == null) {
832
1602
  throw new Error("uf: `driver.js deploy` needs --adapter, --work and --output");
833
1603
  }
1604
+ // What the project declared, read by `uf`'s own walk of the route handlers
1605
+ // and handed over rather than found again here — one reading of a module,
1606
+ // and the same list `wrangler.json`'s `triggers.crons` is written from.
1607
+ // Absent on an older `uf` spawning a newer driver, which is a build with no
1608
+ // schedules rather than an error. See ubugeeei-prod/uf#531.
1609
+ const schedules = JSON.parse(argument("--schedules") ?? "[]");
834
1610
  // The Rust side has already refused every adapter it has no implementation
835
1611
  // for, by name and with the issue that tracks it. This is the second half of
836
1612
  // that fact rather than a duplicate of it: the driver may be spawned by a
@@ -855,14 +1631,97 @@ async function deploy() {
855
1631
  // file is the version a person can open when a deployed directory
856
1632
  // misbehaves.
857
1633
  mkdirSync(work, { recursive: true });
858
- const document = assetsFromManifest(readManifest(outDir));
859
- const entries = shape.entries(document);
1634
+ const document = await documentAssetsFor(
1635
+ path.join(root, ".uf", "build", "server"),
1636
+ readManifest(outDir),
1637
+ );
1638
+ // Whatever `build` above minted, so a durable cache in the deployed artefact
1639
+ // is keyed by the build that produced it and not by the moment it was
1640
+ // packaged. Read rather than minted again for exactly that reason: a second
1641
+ // `randomUUID()` here would key the adapter's copy differently from the one
1642
+ // `uf start` serves out of `.uf/build/`, which is two caches for one build.
1643
+ const buildId = await buildIdentity(root, path.join(".uf", "build", "server"));
1644
+ const declaredCache = config.app?.rendering?.cache;
1645
+ if (shape.filesystem === false && declaredCache?.store === "filesystem") {
1646
+ throw new Error(
1647
+ `uf: rendering.cache.store is "filesystem" and \`--adapter ${adapter}\` has no ` +
1648
+ "filesystem. Name a module exporting `createCacheProvider` instead — a KV " +
1649
+ "namespace or a Redis behind the same seam — or leave the store in memory. See " +
1650
+ "docs/app/guide/cache.",
1651
+ );
1652
+ }
1653
+ // The pages this build regenerates, and where this target keeps what it
1654
+ // regenerates when the project named no store: the adapter's
1655
+ // `regenerationStore`. A target with nowhere refuses by name and lists the
1656
+ // pages, rather than deploying pages that every cold start takes back to the
1657
+ // build's copy.
1658
+ const regeneration = await readRegeneration(path.join(root, ".uf", "build", "server"));
1659
+ let cacheConfig = declaredCache;
1660
+ if (regeneration != null && declaredCache?.store == null) {
1661
+ if (shape.regenerationStore == null) {
1662
+ const pages = Object.keys(regeneration.pages);
1663
+ throw new Error(
1664
+ `uf: this build regenerates ${pages.length} ${plural(pages.length, "page")} ` +
1665
+ `(${pages.join(", ")}), and \`--adapter ${adapter}\` has nowhere of its own to keep ` +
1666
+ "a regenerated page: an instance's memory and its /tmp both go with the instance. " +
1667
+ "Name a module exporting `createCacheProvider` in rendering.cache.store, or leave " +
1668
+ "`isr` out of app.rendering.modes to prerender those pages as documents that do not " +
1669
+ "change. See docs/app/guide/rendering.",
1670
+ );
1671
+ }
1672
+ cacheConfig = { ...declaredCache, store: shape.regenerationStore };
1673
+ }
1674
+ // The pages this build prerendered partially. Their static shells are baked
1675
+ // into `handler.js`, and a target that cannot send a shell before its holes
1676
+ // refuses them by name: a partial prerender answered by a buffered response
1677
+ // is a page that waits for its slowest hole, which is exactly the page it
1678
+ // was prerendered not to be.
1679
+ const partial = await readPartialPrerenders(path.join(root, ".uf", "build", "server"));
1680
+ if (partial != null && shape.streams === false) {
1681
+ const pages = Object.keys(partial.pages);
1682
+ throw new Error(
1683
+ `uf: this build prerendered ${pages.length} ${plural(pages.length, "page")} partially ` +
1684
+ `(${pages.join(", ")}), and \`--adapter ${adapter}\` buffers every response, so the ` +
1685
+ "static shell would arrive with its holes rather than before them. Deploy with an " +
1686
+ "adapter that streams — node, bun, deno, container or edge — or export " +
1687
+ '`dynamic = "force-dynamic"` from those pages to render each of them whole per ' +
1688
+ "request. See docs/app/guide/rendering.",
1689
+ );
1690
+ }
1691
+ const images = await imageEndpointFor(adapter, config.app?.builtins?.images);
1692
+ const entries = shape.entries(
1693
+ document,
1694
+ cacheConfig,
1695
+ buildId,
1696
+ schedules,
1697
+ regeneration,
1698
+ images,
1699
+ partial,
1700
+ );
860
1701
  const input = {};
861
1702
  for (const name of Object.keys(entries)) {
862
1703
  writeFileSync(path.join(work, `${name}.js`), entries[name]);
863
1704
  input[name] = path.join(work, `${name}.js`);
864
1705
  }
865
1706
 
1707
+ // An application React Server Components render bundles the rsc graph into
1708
+ // its server, and a target with export conditions of its own needs that graph
1709
+ // resolved under them as well: React's Flight server has a Node build and a
1710
+ // worker build, exactly as its HTML renderer does.
1711
+ const flight = flightStateOf(inline);
1712
+ if (flight != null) {
1713
+ loadFlightBuild(flight, path.join(root, ".uf", "build", "rsc"));
1714
+ // The id `build` recorded, and not a new one: a Worker's payloads have to
1715
+ // name the same build its documents do.
1716
+ flight.deployment = document.deployment ?? null;
1717
+ if (shape.conditions != null) {
1718
+ await buildRscGraph(vite, inline, flight, {
1719
+ outDir: path.join(work, "rsc"),
1720
+ conditions: shape.conditions,
1721
+ });
1722
+ }
1723
+ }
1724
+
866
1725
  const ssr = { ...(inline.ssr ?? {}), noExternal: true };
867
1726
  if (shape.conditions != null) {
868
1727
  // Which build of a dependency this target gets, and it is the difference
@@ -877,7 +1736,29 @@ async function deploy() {
877
1736
  await vite.build({
878
1737
  ...inline,
879
1738
  customLogger: eventLogger("warn"),
880
- plugins: [...inline.plugins, nativeAddonGuard()],
1739
+ plugins: [
1740
+ ...inline.plugins,
1741
+ nativeAddonGuard(),
1742
+ ...(shape.workerBuiltins === true
1743
+ ? [
1744
+ workerBuiltinGuard(),
1745
+ esmExternalRequirePlugin({ external: [...builtinModules, /^node:/] }),
1746
+ ]
1747
+ : []),
1748
+ ],
1749
+ // Fixed, because this bundle inlines every dependency and so both of each
1750
+ // React package's builds, and a runtime lookup of `NODE_ENV` in a worker
1751
+ // finds nothing and picks the development one. React's Flight client's
1752
+ // development build constructs a `WeakRef` for every response, which
1753
+ // workerd does not have: every document the edge artefact rendered was a
1754
+ // `ReferenceError`. The production build has none, and is the one a
1755
+ // deployment means.
1756
+ define: {
1757
+ ...(inline.define ?? {}),
1758
+ "process.env.NODE_ENV": JSON.stringify(
1759
+ inline.mode === "development" ? "development" : "production",
1760
+ ),
1761
+ },
881
1762
  ssr,
882
1763
  build: {
883
1764
  ...inline.build,
@@ -894,6 +1775,10 @@ async function deploy() {
894
1775
  emptyOutDir: false,
895
1776
  rollupOptions: {
896
1777
  input,
1778
+ // Workers provide the selected built-ins, but cannot use Node's
1779
+ // createRequire(import.meta.url) runtime helper. External requires
1780
+ // above become ESM imports; the remaining helpers are platform neutral.
1781
+ ...(shape.workerBuiltins === true ? { platform: "neutral" } : {}),
897
1782
  output: {
898
1783
  entryFileNames: "[name].js",
899
1784
  // Route modules are lazy `import()`s, so the server bundle splits
@@ -929,24 +1814,299 @@ async function deploy() {
929
1814
  * out — `server.js` below does exactly that through
930
1815
  * `@uniflowed/server/node`, and a worker hands `settle` to `ctx.waitUntil`.
931
1816
  * It comes from the bundle rather than from the host's own
932
- * `@uniflowed/server`, because the request lives in an `AsyncLocalStorage`
933
- * belonging to a module instance and the instance the application reads is the
934
- * one inlined here. See ubugeeei-prod/uf#389.
1817
+ * `@uniflowed/server`, because the request store is shared only by copies of
1818
+ * one release of that package and the release the application reads is the one
1819
+ * inlined here. See ubugeeei-prod/uf#389.
935
1820
  *
936
1821
  * The document's script and stylesheet URLs are baked in here because they
937
1822
  * come from the client manifest, which exists at this moment and not in the
938
1823
  * directory that gets copied.
1824
+ *
1825
+ * `cache` is `rendering.cache` from `uf.config.js`, and this is where two of
1826
+ * its four switches stop being a field in a JSON file: a build that turned
1827
+ * `route` or `fetch` on constructs a store here and hands it to the handler,
1828
+ * and a build that turned neither on writes the file it always wrote, byte for
1829
+ * byte. The store is constructed in the *generated* module rather than reached
1830
+ * for inside `@uniflowed/server` for the same reason `beginRequest` is
1831
+ * re-exported above — a module-level singleton belongs to whichever copy of the
1832
+ * package a bundler happened to give it, and the copy that matters is the one
1833
+ * the application resolved. See ubugeeei-prod/uf#277 and #389.
1834
+ *
1835
+ * # And where a durable store is named
1836
+ *
1837
+ * `rendering.cache.store` is the fifth key, and it is the one that turns the
1838
+ * store into a shared one: `"filesystem"` links uf's built-in provider, and
1839
+ * anything else is a module specifier the project wrote, imported here by name
1840
+ * so the bundler links it like any other dependency of the application. Neither
1841
+ * appears at all when the key is absent, which is what a default project keeps.
1842
+ *
1843
+ * `build` is baked in beside it, and it is the reason this can be an `import`
1844
+ * at all rather than something read at boot: the build id is a fact about the
1845
+ * artefact being written, known here and nowhere later. `internal/serve.js`'s
1846
+ * `buildIdentity` is where it came from and
1847
+ * `packages/server/internal/cache-key.js` is why it exists.
939
1848
  */
940
- function handlerEntrySource(document) {
1849
+ function handlerEntrySource(document, cache, capabilities, build, regeneration, images, partial) {
1850
+ const route = cache?.route === true;
1851
+ const fetchCache = cache?.fetch === true;
1852
+ const dataCache = cache?.data === true;
1853
+ // Nothing at all when both switches are off, so a default project's
1854
+ // `handler.js` is the file it has always been. A cache that appears in
1855
+ // generated output nobody asked for is the second half of the complaint
1856
+ // #277 makes about the first half.
1857
+ const store = route || fetchCache || dataCache;
1858
+ const durable = store ? durableStoreSource(root, cache, build) : null;
1859
+ const options = [
1860
+ "app",
1861
+ `document: ${JSON.stringify(document)}`,
1862
+ ...(store ? ["cache"] : []),
1863
+ "capabilities",
1864
+ // The pages this build regenerates, baked in beside the document and for
1865
+ // the same reason: the manifest exists on the machine doing the build, and
1866
+ // the deployed directory has only what this file carries.
1867
+ ...(store && regeneration != null ? [`regeneration: ${JSON.stringify(regeneration)}`] : []),
1868
+ ...(images == null ? [] : ["images"]),
1869
+ // The static shells of the pages it prerendered partially, for the same
1870
+ // reason. Absent for a build with none, so its `handler.js` is unchanged.
1871
+ ...(partial != null ? [`partial: ${JSON.stringify(partial)}`] : []),
1872
+ ].join(", ");
1873
+ // The image endpoint keeps its variants over the same durable provider when
1874
+ // there is one, so it needs the store constructor even for a build whose
1875
+ // route cache is off; `imageEndpointSource` argues the rest.
1876
+ const imageDurable =
1877
+ images == null || store ? null : durableStoreSource(root, cache, build, { required: false });
1878
+ const linkedDurable = durable ?? imageDurable;
1879
+ const cacheImport =
1880
+ store || imageDurable != null
1881
+ ? 'import { createCacheStore } from "@uniflowed/server/cache";\n'
1882
+ : "";
1883
+ const providerImport = linkedDurable == null ? "" : `${linkedDurable.import}\n`;
1884
+ const imageSource = images == null ? null : imageEndpointSource(images, linkedDurable, build);
1885
+ const from = JSON.stringify(capabilities.module);
1886
+ const capabilityImport = `import { ${capabilities.name} } from ${from};`;
941
1887
  return `// Generated by \`uf build --adapter\`. Not checked in, not edited.
942
1888
  import { createFetchHandler } from "@uniflowed/server/fetch";
943
- import * as app from ${JSON.stringify(VIRTUAL.server)};
944
-
945
- export const fetch = createFetchHandler({ app, document: ${JSON.stringify(document)} });
1889
+ ${cacheImport}${providerImport}${capabilityImport}
1890
+ ${imageSource == null ? "" : imageSource.imports}import * as app from ${JSON.stringify(VIRTUAL.server)};
1891
+
1892
+ ${
1893
+ store
1894
+ ? `// \`rendering.cache\` from uf.config.js. ${
1895
+ durable == null
1896
+ ? `One store per process: it is
1897
+ // emptied by a restart and is not shared with any other instance of this
1898
+ // application.`
1899
+ : `Entries are kept by ${durable.what},
1900
+ // under this build's identity, so a restart finds them where it left them and
1901
+ // every process of this deployment reads one store — and \`revalidateTag\` in
1902
+ // any of them takes an entry out of the store all of them fill from.`
1903
+ } See ubugeeei-prod/uf#277.
1904
+ const cache = { store: createCacheStore(${
1905
+ durable == null ? "" : `{ provider: ${durable.provider}, build: ${JSON.stringify(build)} }`
1906
+ }), route: ${String(route)}, fetch: ${String(fetchCache)}, data: ${String(dataCache)} };
1907
+
1908
+ `
1909
+ : ""
1910
+ }// What this target can do, and it is not the same for all six: whether a
1911
+ // response body reaches the client as it is produced, and whether the process
1912
+ // is still there once it has. A route handler that streams events or takes a
1913
+ // socket asks through this rather than finding out in production. Nothing is
1914
+ // passed for the upgrade or the queue — uf defines both and implements
1915
+ // neither. See \`@uniflowed/server/socket\` and \`@uniflowed/server/queue\`.
1916
+ const capabilities = ${capabilities.name}();
1917
+ ${imageSource == null ? "" : `\n${imageSource.declaration}`}
1918
+ export const fetch = createFetchHandler({ ${options} });
946
1919
  export const beginRequest = app.beginRequest;
1920
+ // \`app.router\`'s redirects and headers, for the entry beside this file to put
1921
+ // in front of its static half. Rewrites are \`fetch\`'s own.
1922
+ export const routing = app.routing;
1923
+
1924
+ export default { fetch, beginRequest, routing };
1925
+ `;
1926
+ }
1927
+
1928
+ /**
1929
+ * The import and the expression that give a generated handler a durable store.
1930
+ *
1931
+ * `null` for `"memory"` and for a project that said nothing, which is every
1932
+ * project until one asks: persistence is a second opt-in on top of `route` and
1933
+ * `fetch`, not something a build decides on a project's behalf.
1934
+ *
1935
+ * The directory is baked in as written rather than resolved here, and that is
1936
+ * deliberate. This function runs on the machine doing the build; the path has
1937
+ * to mean something on the machine doing the *serving*, which may be a
1938
+ * container with one writable mount or a Lambda with only `/tmp`. A relative
1939
+ * one is resolved against the working directory at boot, by the provider, where
1940
+ * the answer is a fact rather than a guess.
1941
+ *
1942
+ * The specifier is resolved against the project for the same reason
1943
+ * `internal/serve.js`'s `providerSpecifier` does it: `"./cache/redis.js"` in
1944
+ * `uf.config.js` is relative to the project, and this file is written into
1945
+ * `.uf/deploy/work/`, where that path means nothing. Absolute is safe here
1946
+ * because the bundler inlines the module rather than emitting the specifier.
1947
+ *
1948
+ * @param {string} root
1949
+ * @param {{store?: string, storeDir?: string}} cache
1950
+ * @param {string | null} build
1951
+ */
1952
+ function durableStoreSource(root, cache, build, { required = true } = {}) {
1953
+ const named = cache?.store ?? "memory";
1954
+ if (named === "memory") return null;
1955
+ if (build == null) {
1956
+ // Only the image endpoint asks without requiring one: its variants are a
1957
+ // cache of somebody else's images rather than of this build's documents,
1958
+ // and memory is a correct, colder, answer for them.
1959
+ if (!required) return null;
1960
+ throw new Error(
1961
+ `uf: rendering.cache.store is ${JSON.stringify(named)}, which keeps entries between ` +
1962
+ "restarts, and this build has no identity to key them by. Run `uf build` so one is " +
1963
+ "written, or set UF_BUILD_ID. Without one the deployment would answer this build's " +
1964
+ "URLs with the previous build's documents.",
1965
+ );
1966
+ }
1967
+ const directory = JSON.stringify(cache?.storeDir ?? path.join(".uf", "cache", "route"));
1968
+ if (named === "filesystem") {
1969
+ return {
1970
+ import: 'import { createFilesystemCache } from "@uniflowed/server/cache/filesystem";',
1971
+ provider: `createFilesystemCache({ directory: ${directory} })`,
1972
+ what: "uf's filesystem provider",
1973
+ };
1974
+ }
1975
+ const from = JSON.stringify(providerSpecifier(root, named));
1976
+ return {
1977
+ import: `import { createCacheProvider } from ${from};`,
1978
+ provider: `createCacheProvider({ build: ${JSON.stringify(build)}, directory: ${directory} })`,
1979
+ what: `${named}'s provider`,
1980
+ };
1981
+ }
1982
+
1983
+ /**
1984
+ * What `--adapter` links for `/__uf/image`, or `null` for a project with no
1985
+ * remote images.
1986
+ *
1987
+ * A deployed directory has no `uf` in it, so the encoder `uf start` uses is
1988
+ * not there to link, and each target gets the one it has:
1989
+ *
1990
+ * * **`edge`**: Cloudflare's Images binding, through
1991
+ * `@uniflowed/server/image/edge` — the platform's own image service, handed
1992
+ * bytes uf fetched and checked rather than a URL it would fetch itself.
1993
+ * `uf` declares the binding in `wrangler.json` when it finds this linked.
1994
+ * * **Every other target**: the module `app.builtins.images.transformer`
1995
+ * names, exporting `createImageTransformer`. `node`, `bun`, `deno`,
1996
+ * `container` and `serverless` have no image service to delegate to, and a
1997
+ * project that deploys to one names the encoder it has — `sharp`, a WASM
1998
+ * codec, a call to a service it runs — behind the same seam `uf` sits behind.
1999
+ *
2000
+ * A target with neither is refused here, by name, rather than linked with an
2001
+ * endpoint that fetches every image and then fails to encode it.
2002
+ *
2003
+ * @param {string} adapter
2004
+ * @param {object | undefined} images `app.builtins.images`
2005
+ */
2006
+ async function imageEndpointFor(adapter, images) {
2007
+ if (!servesRemoteImages(images)) return null;
2008
+ const defaults = await import("@uniflowed/server/image");
2009
+ const settings = {
2010
+ remotePatterns: images.remotePatterns,
2011
+ widths: images.widths ?? defaults.DEFAULT_WIDTHS,
2012
+ quality: images.quality ?? defaults.DEFAULT_QUALITY,
2013
+ qualities: images.qualities ?? [],
2014
+ };
2015
+ if (adapter === "edge") {
2016
+ return { kind: "edge", settings };
2017
+ }
2018
+ const named = images.transformer;
2019
+ if (typeof named !== "string" || named === "") {
2020
+ throw new Error(
2021
+ `uf: app.builtins.images.remotePatterns lists remote hosts, and \`--adapter ${adapter}\` ` +
2022
+ "has no image encoder to link: uf encodes with the `uf` binary under `uf start` and " +
2023
+ "`uf preview`, and a deployed directory does not carry it. Name a module exporting " +
2024
+ "`createImageTransformer` in app.builtins.images.transformer, deploy with " +
2025
+ "`--adapter edge` to use Cloudflare's image binding, or remove the remote patterns. " +
2026
+ "See docs/app/guide/assets.",
2027
+ );
2028
+ }
2029
+ return {
2030
+ kind: "module",
2031
+ settings,
2032
+ specifier: providerSpecifier(root, named),
2033
+ // Never on a deployment: a switch for a test that serves its own images.
2034
+ allowPrivateAddresses: images.dangerouslyAllowPrivateAddresses === true,
2035
+ };
2036
+ }
947
2037
 
948
- export default { fetch, beginRequest };
2038
+ /**
2039
+ * The lines `handler.js` needs for the endpoint [`imageEndpointFor`] chose.
2040
+ *
2041
+ * `durable` is the provider the route cache links, when it links one, so the
2042
+ * variants live where the project already said entries survive a restart; a
2043
+ * Worker with none keeps them in the isolate's memory.
2044
+ *
2045
+ * @param {{kind: "edge" | "module", settings: object, specifier?: string, allowPrivateAddresses?: boolean}} images
2046
+ * @param {{provider: string} | null} durable
2047
+ * @param {string | null} build
2048
+ */
2049
+ function imageEndpointSource(images, durable, build) {
2050
+ const imports =
2051
+ images.kind === "edge"
2052
+ ? 'import { createImageEndpoint, MAX_MEMORY_VARIANTS } from "@uniflowed/server/image";\n' +
2053
+ 'import { cloudflareImageTransform, edgeImageFetch } from "@uniflowed/server/image/edge";\n'
2054
+ : 'import { createImageEndpoint, MAX_MEMORY_VARIANTS } from "@uniflowed/server/image";\n' +
2055
+ 'import { nodeImageFetch } from "@uniflowed/server/image/node";\n' +
2056
+ `import { createImageTransformer } from ${JSON.stringify(images.specifier)};\n`;
2057
+ const fetch =
2058
+ images.kind === "edge"
2059
+ ? "edgeImageFetch()"
2060
+ : `nodeImageFetch(${images.allowPrivateAddresses ? "{ allowPrivateAddresses: true }" : ""})`;
2061
+ const transform =
2062
+ images.kind === "edge" ? "cloudflareImageTransform()" : "createImageTransformer()";
2063
+ const store =
2064
+ durable == null
2065
+ ? ""
2066
+ : `\n store: createCacheStore({ provider: ${durable.provider}, build: ${JSON.stringify(
2067
+ build,
2068
+ )}, maxEntries: MAX_MEMORY_VARIANTS }),`;
2069
+ const declaration = `// \`/__uf/image\`, for the remote hosts app.builtins.images.remotePatterns
2070
+ // lists. See \`@uniflowed/server/image\` and ubugeeei-prod/uf#958.
2071
+ const images = createImageEndpoint({
2072
+ ...${JSON.stringify(images.settings)},
2073
+ fetch: ${fetch},
2074
+ transform: ${transform},${store}
2075
+ });
949
2076
  `;
2077
+ return { imports, declaration };
2078
+ }
2079
+
2080
+ /**
2081
+ * The lines a process entry needs to run what the project declared.
2082
+ *
2083
+ * Shared by `nodeEntrySource` and `bunEntrySource` because the two differ in
2084
+ * which module they take `serve` from and in nothing else — and a schedule
2085
+ * that behaved differently between them would be the drift the whole seam
2086
+ * exists to prevent. Empty strings when a project declared none, so the entry
2087
+ * a default project gets is the file it has always been.
2088
+ */
2089
+ function scheduleLines(module, schedules) {
2090
+ const declared = schedules ?? [];
2091
+ if (declared.length === 0) {
2092
+ return { imports: "", declarations: "", option: "" };
2093
+ }
2094
+ const built = declared
2095
+ .map(
2096
+ (schedule) =>
2097
+ ` routeSchedule({ handle: fetch, beginRequest, path: ${JSON.stringify(
2098
+ schedule.path,
2099
+ )}, cron: ${JSON.stringify(schedule.cron)} }),`,
2100
+ )
2101
+ .join("\n");
2102
+ return {
2103
+ imports: `import { routeSchedule } from ${JSON.stringify(module)};\n`,
2104
+ // A schedule runs the route by asking the application for it, so a
2105
+ // scheduled run and a request for the same path are one code path. See
2106
+ // ubugeeei-prod/uf#531.
2107
+ declarations: `\nconst schedules = [\n${built}\n];\n`,
2108
+ option: ", schedules",
2109
+ };
950
2110
  }
951
2111
 
952
2112
  /**
@@ -958,18 +2118,19 @@ export default { fetch, beginRequest };
958
2118
  * request answered by `uf start` go through one implementation, not two that
959
2119
  * agree today.
960
2120
  */
961
- function nodeEntrySource(handlerSpecifier) {
2121
+ function nodeEntrySource(handlerSpecifier, schedules) {
2122
+ const cron = scheduleLines("@uniflowed/server/schedule", schedules);
962
2123
  return `// Generated by \`uf build --adapter node\`. Not checked in, not edited.
963
2124
  import path from "node:path";
964
2125
  import { fileURLToPath } from "node:url";
965
2126
 
966
2127
  import { serve } from "@uniflowed/server/node";
967
-
2128
+ ${cron.imports}
968
2129
  // \`beginRequest\` comes from the handler beside this file rather than from
969
2130
  // \`@uniflowed/server/node\` above, because the request has to be established in
970
2131
  // the storage the *application* reads, which is the copy bundled into
971
2132
  // \`handler.js\`. See ubugeeei-prod/uf#389.
972
- import { beginRequest, fetch } from ${JSON.stringify(handlerSpecifier)};
2133
+ import { beginRequest, fetch, routing } from ${JSON.stringify(handlerSpecifier)};
973
2134
 
974
2135
  // Resolved from this file and not from the working directory: a process
975
2136
  // manager, a container entrypoint and a person in a shell each start a server
@@ -977,18 +2138,160 @@ import { beginRequest, fetch } from ${JSON.stringify(handlerSpecifier)};
977
2138
  // assets when it was started from inside itself would be a deployment with a
978
2139
  // trap in it.
979
2140
  const staticDir = path.join(path.dirname(fileURLToPath(import.meta.url)), "static");
980
-
2141
+ ${cron.declarations}
981
2142
  // Not \`await serve(...)\` at the top level. uf parses that now
982
2143
  // (ubugeeei-prod/uf#204) and this entry is a module, so it would work; \`.catch\`
983
2144
  // is the better spelling regardless — a server that cannot take its port should
984
2145
  // say so and exit non-zero, rather than die as an unhandled rejection.
985
- serve({ handle: fetch, staticDir, beginRequest }).catch((error) => {
2146
+ serve({ handle: fetch, staticDir, beginRequest, routing${cron.option} }).catch((error) => {
2147
+ process.stderr.write(\`uf: \${error?.message ?? String(error)}\\n\`);
2148
+ process.exit(1);
2149
+ });
2150
+ `;
2151
+ }
2152
+
2153
+ /**
2154
+ * The oldest Bun that can run what this adapter writes.
2155
+ *
2156
+ * Kept equal to `uf_runtime`'s `BUN_MINIMUM` by
2157
+ * `the_bun_entry_refuses_a_bun_older_than_the_declared_minimum`, which reads
2158
+ * the number out of the artefact rather than out of this file — two places
2159
+ * holding one version is exactly the shape that lets them disagree.
2160
+ *
2161
+ * Why there is a floor at all: React's published server build contains a
2162
+ * labelled statement in `else` position — `else a: if (…)`, in every
2163
+ * `react-dom-server*.production.js` including the `bun` one — and Bun's engine
2164
+ * rejects it with `Cannot find scope for the label 'a'` before this release.
2165
+ * Bun 1.3.13 rejects the built `handler.js`; 1.3.14 imports it and serves it.
2166
+ * It is ordinary ES that Node runs, uf does not emit it, and the `bun` export
2167
+ * condition does not avoid it, so there is nothing for uf to lower. See
2168
+ * ubugeeei-prod/uf#1048.
2169
+ */
2170
+ const MINIMUM_BUN = "1.3.14";
2171
+
2172
+ /**
2173
+ * The source of `server.js`: the Bun socket around that handler.
2174
+ *
2175
+ * `nodeEntrySource`'s twin, and identical but for the module it imports
2176
+ * `serve` from — `@uniflowed/server/bun` exports the same signature on
2177
+ * purpose, so that the two adapters are one contract and a project moving
2178
+ * between them changes a flag and nothing else.
2179
+ *
2180
+ * # Why the handler is imported dynamically
2181
+ *
2182
+ * The one place this is *not* `nodeEntrySource`'s twin. A static
2183
+ * `import … from "./handler.js"` is linked before a single statement of this
2184
+ * file runs, so a version check written above it would never execute: Bun
2185
+ * would fail parsing `handler.js` and the sentence explaining why would never
2186
+ * be reached. `await import()` puts the check first, which is the same move
2187
+ * `denoEntrySource` makes to get its globals in before the handler is
2188
+ * evaluated.
2189
+ */
2190
+ function bunEntrySource(handlerSpecifier, schedules) {
2191
+ const cron = scheduleLines("@uniflowed/server/schedule", schedules);
2192
+ return `// Generated by \`uf build --adapter bun\`. Not checked in, not edited.
2193
+ import path from "node:path";
2194
+ import { fileURLToPath } from "node:url";
2195
+
2196
+ import { serve } from "@uniflowed/server/bun";
2197
+ ${cron.imports}
2198
+ // The Bun this build needs. React's server build carries a labelled statement
2199
+ // in \`else\` position that Bun's engine rejects before this release, so an
2200
+ // older Bun cannot parse \`handler.js\` at all — see ubugeeei-prod/uf#1048.
2201
+ //
2202
+ // This runs *before* the handler is imported, and that ordering is the whole
2203
+ // point: a static import would be linked first and the parse would fail with
2204
+ // Bun's message rather than this one.
2205
+ const MINIMUM_BUN = ${JSON.stringify(MINIMUM_BUN)};
2206
+
2207
+ function ufBunIsOlderThanMinimum(version) {
2208
+ const actual = String(version).split(".");
2209
+ const floor = MINIMUM_BUN.split(".");
2210
+ for (let index = 0; index < floor.length; index += 1) {
2211
+ const mine = Number.parseInt(actual[index], 10);
2212
+ const want = Number.parseInt(floor[index], 10);
2213
+ if (!Number.isFinite(mine)) return true;
2214
+ if (mine !== want) return mine < want;
2215
+ }
2216
+ return false;
2217
+ }
2218
+
2219
+ if (typeof Bun !== "undefined" && ufBunIsOlderThanMinimum(Bun.version)) {
2220
+ process.stderr.write(
2221
+ \`uf: this build needs Bun \${MINIMUM_BUN} or newer, and this is Bun \${Bun.version}. \` +
2222
+ "React's server build uses a labelled statement Bun rejects before " +
2223
+ \`\${MINIMUM_BUN}, so \\\`handler.js\\\` beside this file cannot be parsed here. \` +
2224
+ "Upgrade with \`bun upgrade\`, or build with \`--adapter node\` and run it on Node.\\n",
2225
+ );
2226
+ process.exit(1);
2227
+ }
2228
+
2229
+ // \`beginRequest\` comes from the handler beside this file rather than from
2230
+ // \`@uniflowed/server/bun\` above, because the request has to be established in
2231
+ // the storage the *application* reads, which is the copy bundled into
2232
+ // \`handler.js\`. See ubugeeei-prod/uf#389.
2233
+ const { beginRequest, fetch, routing } = await import(${JSON.stringify(handlerSpecifier)});
2234
+
2235
+ // Resolved from this file and not from the working directory: a process
2236
+ // manager, a container entrypoint and a person in a shell each start a server
2237
+ // from wherever they happen to be, and a directory that only served its own
2238
+ // assets when it was started from inside itself would be a deployment with a
2239
+ // trap in it.
2240
+ const staticDir = path.join(path.dirname(fileURLToPath(import.meta.url)), "static");
2241
+ ${cron.declarations}
2242
+ serve({ handle: fetch, staticDir, beginRequest, routing${cron.option} }).catch((error) => {
986
2243
  process.stderr.write(\`uf: \${error?.message ?? String(error)}\\n\`);
987
2244
  process.exit(1);
988
2245
  });
989
2246
  `;
990
2247
  }
991
2248
 
2249
+ /**
2250
+ * The source of `server.js`: the Deno socket around that handler.
2251
+ *
2252
+ * The same generated contract as Node and Bun, with `@uniflowed/server/deno`
2253
+ * owning the host-specific pieces. The static directory is resolved with
2254
+ * `import.meta.url` alone so the entry carries no `node:` imports.
2255
+ */
2256
+ function denoEntrySource(handlerSpecifier, schedules) {
2257
+ const cron = scheduleLines("@uniflowed/server/schedule", schedules);
2258
+ return `// Generated by \`uf build --adapter deno\`. Not checked in, not edited.
2259
+ import { serve } from "@uniflowed/server/deno";
2260
+ ${cron.imports}
2261
+ // \`beginRequest\` comes from the handler beside this file rather than from
2262
+ // \`@uniflowed/server/deno\` above, because the request has to be established in
2263
+ // the storage the *application* reads, which is the copy bundled into
2264
+ // \`handler.js\`. See ubugeeei-prod/uf#389.
2265
+ //
2266
+ // Deno has no Node globals, but dependency bundles may still carry a CommonJS
2267
+ // production branch that expects a few of them. Establish the small environment
2268
+ // shape before \`handler.js\` is evaluated, which requires a dynamic import here
2269
+ // rather than a static one.
2270
+ globalThis.process ??= { env: {} };
2271
+ globalThis.process.env ??= {};
2272
+ globalThis.process.env.NODE_ENV ??= "production";
2273
+ globalThis.Buffer ??= {
2274
+ byteLength(value) {
2275
+ return new TextEncoder().encode(String(value)).byteLength;
2276
+ },
2277
+ };
2278
+ globalThis.setImmediate ??= (callback, ...args) => setTimeout(callback, 0, ...args);
2279
+ globalThis.clearImmediate ??= (handle) => clearTimeout(handle);
2280
+ const { beginRequest, fetch, routing } = await import(${JSON.stringify(handlerSpecifier)});
2281
+
2282
+ // Resolved from this file and not from the working directory: a process
2283
+ // manager and a person in a shell each start a server from wherever they
2284
+ // happen to be, and a directory that only served its own assets when it was
2285
+ // started from inside itself would be a deployment with a trap in it.
2286
+ const staticDir = decodeURIComponent(new URL("./static", import.meta.url).pathname);
2287
+ ${cron.declarations}
2288
+ serve({ handle: fetch, staticDir, beginRequest, routing${cron.option} }).catch((error) => {
2289
+ console.error(\`uf: \${error?.message ?? String(error)}\`);
2290
+ Deno.exit(1);
2291
+ });
2292
+ `;
2293
+ }
2294
+
992
2295
  /**
993
2296
  * The source of `worker.js`: the Cloudflare Workers entry around that handler.
994
2297
  *
@@ -1001,13 +2304,47 @@ serve({ handle: fetch, staticDir, beginRequest }).catch((error) => {
1001
2304
  * `nodeEntrySource` gives: the request has to be established in the storage the
1002
2305
  * *application* reads. See ubugeeei-prod/uf#389.
1003
2306
  */
1004
- function workerEntrySource(handlerSpecifier) {
2307
+ function workerEntrySource(handlerSpecifier, schedules) {
2308
+ const declared = schedules ?? [];
2309
+ // Nothing at all when the project declared none, so a `worker.js` without
2310
+ // schedules is the file it has always been — and `wrangler.json` carries no
2311
+ // `triggers` for it either, so there is nothing to call the export that
2312
+ // would not be there.
2313
+ if (declared.length === 0) {
2314
+ return `// Generated by \`uf build --adapter edge\`. Not checked in, not edited.
2315
+ import { createWorkerFetch, installWorkerLogger } from "@uniflowed/server/edge";
2316
+
2317
+ import { beginRequest, fetch as handle, routing } from ${JSON.stringify(handlerSpecifier)};
2318
+
2319
+ // After the imports, so a logger the application installed while it loaded is
2320
+ // the one that stays; see \`installWorkerLogger\`.
2321
+ installWorkerLogger();
2322
+
2323
+ export default { fetch: createWorkerFetch({ handle, beginRequest, routing }) };
2324
+ `;
2325
+ }
2326
+
2327
+ // The expression Cloudflare fires, mapped to the route that answers it.
2328
+ // `event.cron` arrives spelled exactly as `wrangler.json` spells it, and
2329
+ // `uf` writes both from one list, so the two cannot disagree.
2330
+ const routes = Object.fromEntries(declared.map((schedule) => [schedule.cron, schedule.path]));
1005
2331
  return `// Generated by \`uf build --adapter edge\`. Not checked in, not edited.
1006
- import { createWorkerFetch } from "@uniflowed/server/edge";
2332
+ import { createWorkerFetch, createWorkerScheduled, installWorkerLogger } from "@uniflowed/server/edge";
1007
2333
 
1008
- import { beginRequest, fetch as handle } from ${JSON.stringify(handlerSpecifier)};
2334
+ import { beginRequest, fetch as handle, routing } from ${JSON.stringify(handlerSpecifier)};
1009
2335
 
1010
- export default { fetch: createWorkerFetch({ handle, beginRequest }) };
2336
+ // After the imports, so a logger the application installed while it loaded is
2337
+ // the one that stays; see \`installWorkerLogger\`.
2338
+ installWorkerLogger();
2339
+
2340
+ // \`triggers.crons\` in the wrangler.json beside this file names these same
2341
+ // expressions. See ubugeeei-prod/uf#531.
2342
+ const routes = ${JSON.stringify(routes, null, 2)};
2343
+
2344
+ export default {
2345
+ fetch: createWorkerFetch({ handle, beginRequest, routing }),
2346
+ scheduled: createWorkerScheduled({ handle, beginRequest, routes }),
2347
+ };
1011
2348
  `;
1012
2349
  }
1013
2350
 
@@ -1031,7 +2368,7 @@ import { fileURLToPath } from "node:url";
1031
2368
 
1032
2369
  import { createLambdaHandler } from "@uniflowed/server/lambda";
1033
2370
 
1034
- import { beginRequest, fetch as handle } from ${JSON.stringify(handlerSpecifier)};
2371
+ import { beginRequest, fetch as handle, routing } from ${JSON.stringify(handlerSpecifier)};
1035
2372
 
1036
2373
  // Resolved from this file and not from the working directory: Lambda sets the
1037
2374
  // working directory to the task root today and is under no obligation to keep
@@ -1039,7 +2376,7 @@ import { beginRequest, fetch as handle } from ${JSON.stringify(handlerSpecifier)
1039
2376
  // deployment with a trap in it.
1040
2377
  const staticDir = path.join(path.dirname(fileURLToPath(import.meta.url)), "static");
1041
2378
 
1042
- export const handler = createLambdaHandler({ handle, beginRequest, staticDir });
2379
+ export const handler = createLambdaHandler({ handle, beginRequest, staticDir, routing });
1043
2380
  `;
1044
2381
  }
1045
2382
 
@@ -1050,8 +2387,14 @@ export const handler = createLambdaHandler({ handle, beginRequest, staticDir });
1050
2387
  * bytes of `dist/`. The document's script and stylesheet URLs are baked in
1051
2388
  * here because they come from the client manifest, which exists at this moment
1052
2389
  * and not inside the binary.
2390
+ *
2391
+ * `assetsFile` is the generated payload's path, and it appears in a comment
2392
+ * rather than in the import: the module enters the graph under a virtual id so
2393
+ * that uf's Flow transform never meets eight megabytes of base64. The reason
2394
+ * that matters is `./internal/compile-assets.js`; naming the file here is what
2395
+ * keeps a reader of the generated entry able to find the bytes it carries.
1053
2396
  */
1054
- function entrySource(assetsSpecifier, document) {
2397
+ function entrySource(assetsFile, document) {
1055
2398
  // Not `await serve(...)` at the top level. uf parses that now
1056
2399
  // (ubugeeei-prod/uf#204) and this entry is a module, so it would work;
1057
2400
  // `.catch` is the better spelling regardless: a binary that cannot take its
@@ -1059,7 +2402,11 @@ function entrySource(assetsSpecifier, document) {
1059
2402
  // unhandled rejection.
1060
2403
  return `// Generated by \`uf build --compile\`. Not checked in, not edited.
1061
2404
  import { serve } from "@uniflowed/server/standalone";
1062
- import { assets } from ${JSON.stringify(assetsSpecifier)};
2405
+ // Every file \`uf build\` wrote, base64 in one string. It is on disk at
2406
+ // ${assetsFile}, and it is imported under a virtual id so that uf's
2407
+ // Flow transform is never asked to parse it — see \`@uniflowed/vite\`'s
2408
+ // \`internal/compile-assets.js\` for why that matters.
2409
+ import { assets } from ${JSON.stringify(COMPILE_ASSETS_ID)};
1063
2410
  import * as app from ${JSON.stringify(VIRTUAL.server)};
1064
2411
 
1065
2412
  serve({ app, assets, document: ${JSON.stringify(document)} }).catch((error) => {
@@ -1105,6 +2452,38 @@ function nativeAddonGuard() {
1105
2452
  };
1106
2453
  }
1107
2454
 
2455
+ /**
2456
+ * Say which Node built-ins the Worker being linked reaches and does not have.
2457
+ *
2458
+ * `--adapter edge` only. Every import the bundler resolves passes through here,
2459
+ * and one naming a module `./internal/worker-builtins.js` measured as a stub at
2460
+ * the compatibility date uf writes is kept with the file that imported it. Only
2461
+ * the ones still in the output are reported — see `survivingImports` for the
2462
+ * fixture that showed why — and as warnings rather than a refusal, for the
2463
+ * reason that module gives: a deployment at a newer date may have the module,
2464
+ * and uf cannot see that deployment. What it can do is say, before anything is
2465
+ * uploaded, which request is going to answer 500 and why.
2466
+ */
2467
+ function workerBuiltinGuard() {
2468
+ const reached = [];
2469
+ return {
2470
+ name: "uf:worker-builtins",
2471
+ enforce: "pre",
2472
+ resolveId(source, importer) {
2473
+ if (importer != null && unavailableOnWorkers(source) != null) {
2474
+ reached.push({ specifier: source, importer });
2475
+ }
2476
+ return null;
2477
+ },
2478
+ generateBundle(_options, bundle) {
2479
+ const chunks = Object.values(bundle).filter((output) => output.type === "chunk");
2480
+ for (const warning of workerBuiltinWarnings(survivingImports(reached, chunks), root)) {
2481
+ this.warn(warning);
2482
+ }
2483
+ },
2484
+ };
2485
+ }
2486
+
1108
2487
  /** `word`, pluralised for `count`. */
1109
2488
  function plural(count, word) {
1110
2489
  return count === 1 ? word : `${word}s`;
@@ -1116,6 +2495,138 @@ async function printConfig() {
1116
2495
  process.exit(0);
1117
2496
  }
1118
2497
 
2498
+ /**
2499
+ * The React Server Components state `@uniflowed/vite` shares with this driver,
2500
+ * or `null` for an application rendered from its modules.
2501
+ *
2502
+ * Read off the plugin rather than decided again here: `rendersFlight` in
2503
+ * `./internal/flight.js` decides from the same `uf.config.js`, and a second
2504
+ * reading of it would be the one that drifts.
2505
+ */
2506
+ function flightStateOf(inline) {
2507
+ const plugins = (inline.plugins ?? []).flat(Number.POSITIVE_INFINITY);
2508
+ return plugins.find((plugin) => plugin?.name === "uf:flow")?.api?.flight ?? null;
2509
+ }
2510
+
2511
+ /** What a later command needs of the rsc build, written beside its output. */
2512
+ const FLIGHT_BUILD_FILE = "uf-flight.json";
2513
+
2514
+ /**
2515
+ * Build the rsc graph into `outDir`.
2516
+ *
2517
+ * `conditions` are a deploy target's own, added to `react-server`; `null` is
2518
+ * the Node server `uf build` writes. Vite's builder rather than `vite.build`,
2519
+ * because the rsc graph is an environment of its own and `vite.build` builds
2520
+ * the two Vite always has.
2521
+ */
2522
+ async function buildRscGraph(vite, inline, state, { outDir, conditions }) {
2523
+ const environment = {
2524
+ build: {
2525
+ outDir,
2526
+ emptyOutDir: true,
2527
+ rollupOptions: {
2528
+ input: { index: FLIGHT_VIRTUAL.entry },
2529
+ output: { entryFileNames: "[name].js", format: "es" },
2530
+ },
2531
+ },
2532
+ };
2533
+ if (conditions != null) {
2534
+ environment.resolve = {
2535
+ conditions: ["react-server", ...conditions],
2536
+ externalConditions: ["react-server", ...conditions],
2537
+ };
2538
+ }
2539
+ const builder = await vite.createBuilder({
2540
+ ...inline,
2541
+ customLogger: eventLogger("warn"),
2542
+ environments: { [RSC_ENVIRONMENT]: environment },
2543
+ });
2544
+ await builder.build(builder.environments[RSC_ENVIRONMENT]);
2545
+ state.rscOutput = path.join(outDir, "index.js");
2546
+ }
2547
+
2548
+ /**
2549
+ * Record the chunk each client module was built into, and write it down.
2550
+ *
2551
+ * Written down because `uf build --adapter` and `uf build --compile` bundle
2552
+ * the server again in a process of their own, and a reference in the rsc
2553
+ * output names its module by path, which only this build's manifest turns
2554
+ * into a URL.
2555
+ */
2556
+ function recordClientChunks(state, manifest, references, rscDir, base = "") {
2557
+ for (const file of references) {
2558
+ const key = path.relative(root, file).split(path.sep).join("/");
2559
+ const chunk = manifest[key];
2560
+ if (chunk == null) {
2561
+ throw new Error(
2562
+ `uf: the client build wrote no chunk for ${key}, which a server component renders as a ` +
2563
+ "client component",
2564
+ );
2565
+ }
2566
+ state.chunkUrls.set(file, `${base}/${chunk.file}`);
2567
+ }
2568
+ writeFileSync(
2569
+ path.join(rscDir, FLIGHT_BUILD_FILE),
2570
+ `${JSON.stringify({ chunkUrls: [...state.chunkUrls] }, null, 2)}\n`,
2571
+ );
2572
+ }
2573
+
2574
+ /** What `recordClientChunks` wrote, for a command that runs after `uf build`. */
2575
+ function loadFlightBuild(state, rscDir) {
2576
+ const file = path.join(rscDir, FLIGHT_BUILD_FILE);
2577
+ if (!existsSync(file)) {
2578
+ throw new Error(
2579
+ `uf: ${path.relative(root, file)} is missing, so there is no rsc graph to render routes ` +
2580
+ "with; run `uf build` first",
2581
+ );
2582
+ }
2583
+ state.chunkUrls = new Map(JSON.parse(readFileSync(file, "utf8")).chunkUrls);
2584
+ state.rscOutput = path.join(rscDir, "index.js");
2585
+ }
2586
+
2587
+ /**
2588
+ * The tags a document React Server Components render needs.
2589
+ *
2590
+ * `assetsFromManifest`'s, with stylesheets from three places in the order they
2591
+ * cascade: the rsc graph's first — every layout's and every server component's
2592
+ * — then the client entry's, then each client module's own, which the client
2593
+ * build emits beside that module's chunk and no import from the entry reaches.
2594
+ *
2595
+ * The rsc build's emitted files are copied under `dist/` so those URLs resolve,
2596
+ * and only its assets: a server bundle's JavaScript is never a deployable file.
2597
+ */
2598
+ function flightAssets(manifest, references, rscDir, outDir, base = "") {
2599
+ const assets = assetsFromManifest(manifest, base);
2600
+ const styles = new Set();
2601
+ const rscManifest = path.join(rscDir, ".vite", "manifest.json");
2602
+ if (existsSync(rscManifest)) {
2603
+ const rscStyles = assetsFromManifest(
2604
+ JSON.parse(readFileSync(rscManifest, "utf8")),
2605
+ base,
2606
+ ).styles;
2607
+ for (const href of rscStyles) styles.add(href);
2608
+ }
2609
+ const rscAssets = path.join(rscDir, "assets");
2610
+ if (existsSync(rscAssets)) {
2611
+ cpSync(rscAssets, path.join(outDir, "assets"), {
2612
+ recursive: true,
2613
+ filter: (from) => !/\.(?:[cm]?js|map)$/.test(from),
2614
+ });
2615
+ }
2616
+ for (const href of assets.styles) styles.add(href);
2617
+ const seen = new Set();
2618
+ const visit = (key) => {
2619
+ if (seen.has(key)) return;
2620
+ seen.add(key);
2621
+ const chunk = manifest[key];
2622
+ if (chunk == null) return;
2623
+ for (const css of chunk.css ?? []) styles.add(`${base}/${css}`);
2624
+ for (const imported of chunk.imports ?? []) visit(imported);
2625
+ };
2626
+ for (const file of references) visit(path.relative(root, file).split(path.sep).join("/"));
2627
+ return { ...assets, styles: [...styles] };
2628
+ }
2629
+
1119
2630
  function readManifest(outDir) {
1120
2631
  const file = path.join(outDir, ".vite", "manifest.json");
1121
2632
  if (!existsSync(file)) throw new Error(`uf: the client build wrote no manifest at ${file}`);
@@ -1123,24 +2634,151 @@ function readManifest(outDir) {
1123
2634
  }
1124
2635
 
1125
2636
  /**
1126
- * The URLs to prerender: every route without parameters, plus every set of
1127
- * parameters a page's `generateStaticParams` returns.
2637
+ * What this build renders now, and what it leaves for a server.
2638
+ *
2639
+ * The rendering decision, per route, and it has three answers rather than the
2640
+ * two `staticPaths` used to have:
2641
+ *
2642
+ * * **prerender it** — a route with no parameters, or a route whose page
2643
+ * exports `generateStaticParams`, once per set of parameters it returns;
2644
+ * * **leave it to the server** — a route with parameters and no
2645
+ * `generateStaticParams`, or a page that has said `export const dynamic =
2646
+ * "force-dynamic"`;
2647
+ * * **refuse** — which is not decided here. This function reports what it
2648
+ * found and the caller, which knows whether the project allows a server,
2649
+ * is the one that turns "there is a route here a static host cannot
2650
+ * answer" into an error.
2651
+ *
2652
+ * `dynamic` is the spelling ubugeeei-prod/uf#336 asked for: a route with *no*
2653
+ * parameters whose content depends on the request had no way to say so, and
2654
+ * `generateStaticParams` cannot say it — there are no parameters to generate.
2655
+ * It is Next.js's name for the same declaration, because a person arriving
2656
+ * from `app/` should not have to learn a second word for a decision they have
2657
+ * already made once.
2658
+ *
2659
+ * Two of Next's four values are missing and are not silently accepted:
2660
+ * `"force-static"` and `"error"` are refused by name, because each is a
2661
+ * *constraint* on a page that uf does not yet check, and accepting one would
2662
+ * be reading a declaration and ignoring it — the failure the two issues behind
2663
+ * this function are about.
2664
+ *
2665
+ * Handlers and middleware are in the same list, and they belong there: this is
2666
+ * the list of things that need a process, and a `$route.js` needs one more
2667
+ * obviously than any page does. They carry no per-route render — the build has
2668
+ * never written a file for either — so they appear only when the answer might
2669
+ * be a refusal.
2670
+ *
2671
+ * @param {{routes: Route[], handlers: Handler[], middleware: Middleware[]}} server
2672
+ * @param {"everything" | "possible" | "nothing"} prerender
1128
2673
  */
1129
- async function staticPaths(routes) {
2674
+ async function renderingPlan(server, prerender) {
1130
2675
  const urls = [];
1131
- for (const route of routes) {
2676
+ const perRequest = [];
2677
+
2678
+ // One document, and it is no route's, so there is no route to ask anything
2679
+ // about. `perRequest` is empty rather than "every route": nothing here is
2680
+ // left for a server — the browser answers all of it — and listing routes
2681
+ // under a heading that means "these need a process" would be a build
2682
+ // describing itself wrongly to `uf`, which prints that list.
2683
+ if (prerender === "shell") {
2684
+ return { urls: [], perRequest: [] };
2685
+ }
2686
+
2687
+ // Nothing is prerendered and nothing is refused, so no page module is
2688
+ // loaded: a project that renders everything per request should not pay for
2689
+ // a `generateStaticParams` this build will not call.
2690
+ if (prerender === "nothing") {
2691
+ return {
2692
+ urls,
2693
+ perRequest: server.routes.map((route) => ({
2694
+ path: route.path,
2695
+ why: "this build prerenders nothing",
2696
+ })),
2697
+ };
2698
+ }
2699
+
2700
+ for (const route of server.routes) {
2701
+ // Every page module, and not only the parameterised ones: `dynamic` is a
2702
+ // declaration any page can make. A module that cannot be imported at all
2703
+ // is a failure of *that route*, so a route with no parameters goes into
2704
+ // the prerender anyway and the loop below reports it the way it has always
2705
+ // reported a page that throws — named, with the rest of the build still
2706
+ // happening. A parameterised one still rejects out of the build, which is
2707
+ // what it did before there was anything else to load a page module for.
2708
+ let module;
2709
+ try {
2710
+ module = await route.page();
2711
+ } catch (error) {
2712
+ if (route.params.length > 0) throw error;
2713
+ urls.push(route.path);
2714
+ continue;
2715
+ }
2716
+ const declared = module.dynamic ?? "auto";
2717
+ if (declared !== "auto" && declared !== "force-dynamic") {
2718
+ throw new Error(
2719
+ `uf: ${route.file} exports \`dynamic = ${JSON.stringify(declared)}\`, and uf reads ` +
2720
+ '`"auto"` and `"force-dynamic"`. `"force-static"` and `"error"` are Next.js values ' +
2721
+ "for constraints uf does not check yet, and accepting one would be reading a " +
2722
+ "declaration and ignoring it.",
2723
+ );
2724
+ }
2725
+ if (declared === "force-dynamic") {
2726
+ perRequest.push({
2727
+ path: route.path,
2728
+ why: 'its page exports `dynamic = "force-dynamic"`',
2729
+ });
2730
+ continue;
2731
+ }
1132
2732
  if (route.params.length === 0) {
1133
2733
  urls.push(route.path);
1134
2734
  continue;
1135
2735
  }
1136
- const module = await route.page();
1137
2736
  const generate = module.generateStaticParams;
1138
- if (typeof generate !== "function") continue;
2737
+ if (typeof generate !== "function") {
2738
+ perRequest.push({
2739
+ path: route.path,
2740
+ why: "it has parameters and its page exports no `generateStaticParams`",
2741
+ });
2742
+ continue;
2743
+ }
1139
2744
  for (const params of await generate()) {
1140
2745
  urls.push(fillParams(route.path, params));
1141
2746
  }
1142
2747
  }
1143
- return urls;
2748
+
2749
+ for (const handler of server.handlers ?? []) {
2750
+ perRequest.push({
2751
+ path: handler.path,
2752
+ why: "it is a route handler, and a handler answers a request rather than producing a file",
2753
+ });
2754
+ }
2755
+ for (const entry of server.middleware ?? []) {
2756
+ // A middleware is reported by the path it guards rather than by the route
2757
+ // it guards, which is why it cannot be folded into the loop above: it runs
2758
+ // for a page, for a handler, and for a path under it that is neither, so
2759
+ // "which route is this" has no single answer.
2760
+ perRequest.push({
2761
+ path: `${entry.path === "/" ? "" : entry.path}/*`,
2762
+ why: "a middleware guards it, and a middleware runs once per request",
2763
+ });
2764
+ }
2765
+ // And `app.router`'s three lists, by the source each rule matches: a file
2766
+ // can be neither a redirect nor a rewrite, and a header a file is served
2767
+ // with is the host's to add rather than the file's.
2768
+ for (const [key, what] of [
2769
+ ["redirects", "a redirect"],
2770
+ ["rewrites", "a rewrite"],
2771
+ ["headers", "a response header"],
2772
+ ]) {
2773
+ for (const rule of server.routing?.[key] ?? []) {
2774
+ perRequest.push({
2775
+ path: rule.source,
2776
+ why: `\`app.router.${key}\` names it, and ${what} is answered when a request arrives`,
2777
+ });
2778
+ }
2779
+ }
2780
+
2781
+ return { urls, perRequest };
1144
2782
  }
1145
2783
 
1146
2784
  function fillParams(routePath, params) {
@@ -1160,9 +2798,36 @@ function fillParams(routePath, params) {
1160
2798
  .join("/");
1161
2799
  }
1162
2800
 
1163
- function htmlPathFor(outDir, url) {
1164
- const pathname = url.split("?")[0].replace(/^\/+/, "");
1165
- return pathname === ""
1166
- ? path.join(outDir, "index.html")
2801
+ /**
2802
+ * The file a prerendered page is written to.
2803
+ *
2804
+ * `guide/index.html`, which every static host serves at `/guide/` and most at
2805
+ * `/guide`, unless `app.router.trailingSlash` is `"never"` — then `guide.html`,
2806
+ * which the same hosts serve at `/guide` without a redirect to the slash.
2807
+ * Next.js's static export makes the same choice from the same setting.
2808
+ */
2809
+ function htmlPathFor(outDir, url, trailingSlash = "ignore") {
2810
+ const pathname = url.split("?")[0].replace(/^\/+/, "").replace(/\/+$/, "");
2811
+ if (pathname === "") return path.join(outDir, "index.html");
2812
+ return trailingSlash === "never"
2813
+ ? path.join(outDir, `${pathname}.html`)
1167
2814
  : path.join(outDir, pathname, "index.html");
1168
2815
  }
2816
+
2817
+ /**
2818
+ * The URL path at which a static half answers the document `htmlPathFor`
2819
+ * wrote for `url` under `REGENERATED_DIRECTORY`.
2820
+ *
2821
+ * Ending in a slash, so every host answers it with that directory's
2822
+ * `index.html` in the same way: a Node static half tries `index.html` for such
2823
+ * a path, and a Worker's assets binding serves it without the redirect it
2824
+ * answers `…/index.html` with.
2825
+ */
2826
+ function regeneratedDocumentUrl(url) {
2827
+ const pathname = url.split("?")[0].replace(/^\/+/, "").replace(/\/+$/, "");
2828
+ const encoded = pathname
2829
+ .split("/")
2830
+ .map((segment) => encodeURIComponent(segment))
2831
+ .join("/");
2832
+ return pathname === "" ? `/${REGENERATED_DIRECTORY}/` : `/${REGENERATED_DIRECTORY}/${encoded}/`;
2833
+ }