@nifrajs/web 3.1.0 → 3.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/dist/build-plan.d.ts +228 -0
- package/dist/build-plan.d.ts.map +1 -0
- package/dist/build-plan.js +514 -0
- package/dist/build-plan.js.map +1 -0
- package/dist/build-vite.d.ts +2 -1
- package/dist/build-vite.d.ts.map +1 -1
- package/dist/build-vite.js.map +1 -1
- package/dist/build.d.ts +2 -197
- package/dist/build.d.ts.map +1 -1
- package/dist/build.js +61 -502
- package/dist/build.js.map +1 -1
- package/dist/chunk-names.d.ts.map +1 -1
- package/dist/chunk-names.js +3 -2
- package/dist/chunk-names.js.map +1 -1
- package/dist/dev-ssr-graph.d.ts.map +1 -1
- package/dist/dev-ssr-graph.js +63 -28
- package/dist/dev-ssr-graph.js.map +1 -1
- package/dist/diagnostic.d.ts.map +1 -1
- package/dist/diagnostic.js +9 -2
- package/dist/diagnostic.js.map +1 -1
- package/dist/fonts-google.d.ts.map +1 -1
- package/dist/fonts-google.js +3 -1
- package/dist/fonts-google.js.map +1 -1
- package/dist/fs.d.ts.map +1 -1
- package/dist/fs.js +2 -1
- package/dist/fs.js.map +1 -1
- package/dist/index.d.ts +15 -609
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +22 -1935
- package/dist/index.js.map +1 -1
- package/dist/internal/codegen.d.ts +68 -0
- package/dist/internal/codegen.d.ts.map +1 -0
- package/dist/internal/codegen.js +317 -0
- package/dist/internal/codegen.js.map +1 -0
- package/dist/internal/head-merge.d.ts +2 -0
- package/dist/internal/head-merge.d.ts.map +1 -1
- package/dist/internal/head-merge.js +17 -1
- package/dist/internal/head-merge.js.map +1 -1
- package/dist/internal/parity.d.ts +7 -0
- package/dist/internal/parity.d.ts.map +1 -1
- package/dist/internal/parity.js +212 -30
- package/dist/internal/parity.js.map +1 -1
- package/dist/internal/render-document.d.ts +372 -0
- package/dist/internal/render-document.d.ts.map +1 -0
- package/dist/internal/render-document.js +744 -0
- package/dist/internal/render-document.js.map +1 -0
- package/dist/internal/runtime-contract.d.ts +48 -0
- package/dist/internal/runtime-contract.d.ts.map +1 -0
- package/dist/internal/runtime-contract.js +27 -0
- package/dist/internal/runtime-contract.js.map +1 -0
- package/dist/internal/web-app.d.ts +171 -0
- package/dist/internal/web-app.d.ts.map +1 -0
- package/dist/internal/web-app.js +844 -0
- package/dist/internal/web-app.js.map +1 -0
- package/dist/islands.d.ts +48 -0
- package/dist/islands.d.ts.map +1 -1
- package/dist/islands.js +79 -0
- package/dist/islands.js.map +1 -1
- package/dist/module-graph.d.ts.map +1 -1
- package/dist/module-graph.js +22 -9
- package/dist/module-graph.js.map +1 -1
- package/dist/nano.d.ts +125 -0
- package/dist/nano.d.ts.map +1 -0
- package/dist/nano.js +190 -0
- package/dist/nano.js.map +1 -0
- package/dist/plugins/css-modules.js +2 -2
- package/dist/plugins/css-modules.js.map +1 -1
- package/dist/plugins/kit.d.ts +12 -0
- package/dist/plugins/kit.d.ts.map +1 -1
- package/dist/plugins/kit.js +62 -12
- package/dist/plugins/kit.js.map +1 -1
- package/dist/plugins/postcss.js +2 -2
- package/dist/plugins/postcss.js.map +1 -1
- package/dist/plugins/scss.js +2 -2
- package/dist/plugins/scss.js.map +1 -1
- package/dist/plugins/stylex.d.ts +70 -0
- package/dist/plugins/stylex.d.ts.map +1 -0
- package/dist/plugins/stylex.js +166 -0
- package/dist/plugins/stylex.js.map +1 -0
- package/dist/plugins/svg.js +2 -2
- package/dist/plugins/svg.js.map +1 -1
- package/dist/router.d.ts +1 -1
- package/dist/router.js +23 -23
- package/dist/router.js.map +1 -1
- package/dist/vite.d.ts.map +1 -1
- package/dist/vite.js +26 -10
- package/dist/vite.js.map +1 -1
- package/package.json +39 -3
- package/src/build-plan.ts +741 -0
- package/src/build-vite.ts +1 -4
- package/src/build.ts +84 -716
- package/src/chunk-names.ts +3 -2
- package/src/dev-ssr-graph.ts +63 -28
- package/src/diagnostic.ts +14 -2
- package/src/fonts-google.ts +3 -1
- package/src/fs.ts +2 -1
- package/src/index.ts +73 -2705
- package/src/internal/codegen.ts +400 -0
- package/src/internal/head-merge.ts +19 -1
- package/src/internal/parity.ts +215 -35
- package/src/internal/render-document.ts +1116 -0
- package/src/internal/runtime-contract.ts +54 -0
- package/src/internal/web-app.ts +1114 -0
- package/src/islands.ts +85 -0
- package/src/module-graph.ts +23 -9
- package/src/nano.ts +246 -0
- package/src/plugins/css-modules.ts +2 -2
- package/src/plugins/kit.ts +65 -12
- package/src/plugins/postcss.ts +2 -2
- package/src/plugins/scss.ts +2 -2
- package/src/plugins/stylex.ts +298 -0
- package/src/plugins/svg.ts +2 -2
- package/src/router.ts +24 -24
- package/src/vite.ts +33 -9
package/dist/build.js
CHANGED
|
@@ -7,9 +7,10 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
9
9
|
import { cp, lstat, mkdir, realpath } from "node:fs/promises";
|
|
10
|
-
import { dirname, join, relative, resolve as resolvePath, sep } from "node:path";
|
|
10
|
+
import { dirname, join, basename as pathBasename, relative, resolve as resolvePath, sep, } from "node:path";
|
|
11
11
|
import { singleCopyPlugin as declaredSingleCopyPlugin, readSingleCopyDeclaration, } from "@nifrajs/core/single-copy";
|
|
12
12
|
import { Glob } from "bun";
|
|
13
|
+
import { aggregateSizeReport, detectNodeBuiltinsInClient, detectServerOnlyInClient, formatNodeBuiltinLeak, formatServerOnlyLeak, parseManifestClientEntry, parseManifestRouteStyles, parseManifestStyles, planBuildTarget, } from "./build-plan.js";
|
|
13
14
|
import { sanitizeOutputNames } from "./chunk-names.js";
|
|
14
15
|
import { discoverRoutes } from "./fs.js";
|
|
15
16
|
import { generateClientEntry, generateServerManifest } from "./index.js";
|
|
@@ -19,6 +20,18 @@ import { generateServerFnStub, SERVER_FN_MODULE, SERVER_ONLY_MODULE, SERVER_ONLY
|
|
|
19
20
|
// `buildTarget(static)` drives the SSG prerender engine directly (it's also re-exported below).
|
|
20
21
|
import { fromBunMetafile } from "./module-graph.js";
|
|
21
22
|
import { prerenderRoutes } from "./prerender.js";
|
|
23
|
+
export * from "./build-plan.js";
|
|
24
|
+
const basename = (path) => pathBasename(path);
|
|
25
|
+
// The lazy shape declares `const loaders`, the eager shape `const modules`. Anchored at a line start,
|
|
26
|
+
// NOT `.includes("const loaders =")`: the real emit is `const loaders: Record<...> = {`, whose `:` type
|
|
27
|
+
// annotation sits between the name and the `=`, so the ` =` substring never matched and every lazy
|
|
28
|
+
// manifest was re-synced as eager (silently converting `import()` splitting into a single eager bundle).
|
|
29
|
+
const MANIFEST_IS_LAZY = /^const loaders\b/m;
|
|
30
|
+
const entryName = (file) => {
|
|
31
|
+
const base = basename(file);
|
|
32
|
+
const dot = base.lastIndexOf(".");
|
|
33
|
+
return dot === -1 ? base : base.slice(0, dot);
|
|
34
|
+
};
|
|
22
35
|
// Build-time SSG: prerender opted-in static + dynamic routes to `index.html` (+ static `_data.json`),
|
|
23
36
|
// run after `buildClient`.
|
|
24
37
|
export { cloudflarePagesRoutes, dataFileFor, htmlFileFor, prerenderRoutes, } from "./prerender.js";
|
|
@@ -191,442 +204,6 @@ export async function copyPublicDir(from, to) {
|
|
|
191
204
|
}
|
|
192
205
|
return copied.sort();
|
|
193
206
|
}
|
|
194
|
-
/** The `node:` specifier of an import edge, or undefined if it isn't a Node built-in. Reads the
|
|
195
|
-
* `original` (as-written) specifier first, falling back to the resolved `path` (an `external` node:
|
|
196
|
-
* import keeps `node:` in its path). */
|
|
197
|
-
const nodeBuiltinOf = (im) => {
|
|
198
|
-
if (im.original?.startsWith("node:"))
|
|
199
|
-
return im.original;
|
|
200
|
-
if (im.path?.startsWith("node:"))
|
|
201
|
-
return im.path;
|
|
202
|
-
return undefined;
|
|
203
|
-
};
|
|
204
|
-
/**
|
|
205
|
-
* BFS the metafile import graph for the SHORTEST user-module path that pulls `builtin` into the
|
|
206
|
-
* bundle, returning it as display labels `[entryFile, …as-written specifiers…, builtin]`. The frontier
|
|
207
|
-
* starts at every `entryInput` (the route/user entrypoints) so the reported chain begins where the dev
|
|
208
|
-
* actually wrote `import` - the actionable root, not an arbitrary internal module. Traversal crosses
|
|
209
|
-
* only NON-`node:` edges (so Bun's polyfill chain never extends the path) and stops at the first edge
|
|
210
|
-
* whose target is the builtin. Returns `[builtin]` if no entry reaches it (defensive; a flagged builtin
|
|
211
|
-
* is reachable by construction). Pure - operates on the graph, never the emitted text.
|
|
212
|
-
*/
|
|
213
|
-
function shortestBuiltinChain(inputs, entryInputs, builtin) {
|
|
214
|
-
// Each queue item carries the resolved-path node + the display chain to reach it (entry + the
|
|
215
|
-
// as-written specifier of every hop crossed so far). `seen` dedupes nodes so the BFS is linear and
|
|
216
|
-
// the first time we touch the builtin's importer is via a shortest path.
|
|
217
|
-
const seen = new Set(entryInputs);
|
|
218
|
-
let frontier = entryInputs.map((node) => ({
|
|
219
|
-
node,
|
|
220
|
-
chain: [node],
|
|
221
|
-
}));
|
|
222
|
-
while (frontier.length > 0) {
|
|
223
|
-
const next = [];
|
|
224
|
-
for (const { node, chain } of frontier) {
|
|
225
|
-
for (const im of inputs[node]?.imports ?? []) {
|
|
226
|
-
// The builtin reached via THIS edge → the chain ends here (append the builtin label). Match on
|
|
227
|
-
// the same `node:` detection the finding used (`original` first, then resolved `path`).
|
|
228
|
-
if (nodeBuiltinOf(im) === builtin)
|
|
229
|
-
return [...chain, builtin];
|
|
230
|
-
const target = im.path;
|
|
231
|
-
// Only follow edges into user (non-`node:`) modules that exist in the input graph and haven't
|
|
232
|
-
// been visited - so the polyfill subtree can't lengthen the path and there are no cycles.
|
|
233
|
-
if (target === undefined ||
|
|
234
|
-
target.startsWith("node:") ||
|
|
235
|
-
inputs[target] === undefined ||
|
|
236
|
-
seen.has(target)) {
|
|
237
|
-
continue;
|
|
238
|
-
}
|
|
239
|
-
seen.add(target);
|
|
240
|
-
// Display the hop by its as-written specifier (`../db/client.ts`, `postgres`), falling back to
|
|
241
|
-
// the resolved path - that's what the dev recognizes in their source, not the resolved path.
|
|
242
|
-
next.push({ node: target, chain: [...chain, im.original ?? target] });
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
|
-
frontier = next;
|
|
246
|
-
}
|
|
247
|
-
return [builtin]; // unreachable from any entry - degrade to just the builtin (shouldn't happen)
|
|
248
|
-
}
|
|
249
|
-
/**
|
|
250
|
-
* Scan a build's metafile for any `node:` builtin that a USER module pulled into a CLIENT output
|
|
251
|
-
* chunk, returning a sorted, deduped list of {@link NodeBuiltinFinding}s. Three graph facts combine so
|
|
252
|
-
* the report is precise AND actionable:
|
|
253
|
-
* 1. **What the user wrote** - only builtins imported by a NON-`node:` input count, so Bun's own
|
|
254
|
-
* polyfill chain (`node:crypto` → `node:buffer`/`node:stream`/…) doesn't bury the real cause.
|
|
255
|
-
* 2. **Where it landed** - the chunk is read from the per-output `inputs`, so the error names the
|
|
256
|
-
* emitted file to look at.
|
|
257
|
-
* 3. **How it got there** - the shortest import chain from a user entry to the builtin
|
|
258
|
-
* (`shortestBuiltinChain`), so the error points straight at the offending `import` line instead of
|
|
259
|
-
* leaving the dev to grep the dependency tree (the DX gap this closes).
|
|
260
|
-
* Graph-based (never the emitted text), so it survives minification and can't be fooled by a string
|
|
261
|
-
* literal that merely contains `"node:crypto"`. Pure + exported for unit testing. Empty ⇒ clean.
|
|
262
|
-
*/
|
|
263
|
-
export function detectNodeBuiltinsInClient(graph) {
|
|
264
|
-
const inputs = graph.modules;
|
|
265
|
-
// (1) The builtins a user (non-polyfill) module imports directly - the ones the author controls.
|
|
266
|
-
const userImported = new Set();
|
|
267
|
-
for (const [inputKey, input] of Object.entries(inputs)) {
|
|
268
|
-
if (inputKey.startsWith("node:"))
|
|
269
|
-
continue; // a polyfill importing another builtin - not the cause
|
|
270
|
-
for (const im of input.imports ?? []) {
|
|
271
|
-
const builtin = nodeBuiltinOf(im);
|
|
272
|
-
if (builtin !== undefined)
|
|
273
|
-
userImported.add(builtin);
|
|
274
|
-
}
|
|
275
|
-
}
|
|
276
|
-
// The entry inputs (route/user entrypoints) - the chain BFS starts here so the reported path begins
|
|
277
|
-
// at the file the dev wrote an `import` in. Each output's `entryPoint` is one such input.
|
|
278
|
-
const entryInputs = [
|
|
279
|
-
...new Set(Object.values(graph.chunks)
|
|
280
|
-
.map((o) => o.entryPoint)
|
|
281
|
-
.filter((e) => e !== undefined && !e.startsWith("node:"))),
|
|
282
|
-
];
|
|
283
|
-
// The chain per builtin is independent of the chunk, so compute it once per builtin (memoized).
|
|
284
|
-
const chainCache = new Map();
|
|
285
|
-
const chainFor = (builtin) => {
|
|
286
|
-
const cached = chainCache.get(builtin);
|
|
287
|
-
if (cached !== undefined)
|
|
288
|
-
return cached;
|
|
289
|
-
const chain = shortestBuiltinChain(inputs, entryInputs, builtin);
|
|
290
|
-
chainCache.set(builtin, chain);
|
|
291
|
-
return chain;
|
|
292
|
-
};
|
|
293
|
-
// (2) Locate which emitted chunk each user-imported builtin reached, via the per-output `inputs`.
|
|
294
|
-
const findings = new Map();
|
|
295
|
-
for (const [outPath, out] of Object.entries(graph.chunks)) {
|
|
296
|
-
for (const inputKey of out.modules) {
|
|
297
|
-
if (userImported.has(inputKey)) {
|
|
298
|
-
const chunk = basename(outPath);
|
|
299
|
-
findings.set(`${inputKey}\0${chunk}`, {
|
|
300
|
-
builtin: inputKey,
|
|
301
|
-
chunk,
|
|
302
|
-
chain: chainFor(inputKey),
|
|
303
|
-
});
|
|
304
|
-
}
|
|
305
|
-
}
|
|
306
|
-
}
|
|
307
|
-
return [...findings.values()].sort((a, b) => a.builtin === b.builtin ? a.chunk.localeCompare(b.chunk) : a.builtin.localeCompare(b.builtin));
|
|
308
|
-
}
|
|
309
|
-
// ---------------------------------------------------------------------------------------------------
|
|
310
|
-
// `server-only` poison-import guard (§3.3/§5.1). The complement to the `.server` convention + the
|
|
311
|
-
// node-builtin guard: a module of PURE server logic with NO `node:` import (a secret-bearing constant,
|
|
312
|
-
// a server-only API call) that an author wants to FAIL LOUD if it reaches the client opts in with a
|
|
313
|
-
// side-effect `import "@nifrajs/web/server-only"` (Next's `import "server-only"`). On the SERVER build
|
|
314
|
-
// the marker is an empty no-op; the CLIENT build detects - via the SAME Bun metafile graph the
|
|
315
|
-
// node-builtin guard walks - any module that imports the marker AND lands in a client chunk, and fails
|
|
316
|
-
// the build with the import chain. Graph-based (never the emitted text), so it survives minification.
|
|
317
|
-
// ---------------------------------------------------------------------------------------------------
|
|
318
|
-
/** The marker specifier an author imports to opt a module into the client-leak guard. Matched on the
|
|
319
|
-
* import edge's *as-written* `original` first (the robust signal: it's exactly what the author typed,
|
|
320
|
-
* before Bun resolves it to `src/server-only.ts` / `dist/server-only.js`). */
|
|
321
|
-
export const SERVER_ONLY_MARKER = "@nifrajs/web/server-only";
|
|
322
|
-
/** True when an import edge is the `server-only` marker import. Reads the as-written `original` (the
|
|
323
|
-
* specifier the author typed); falls back to the resolved `path`'s basename so a pre-resolved edge
|
|
324
|
-
* (no `original`) - or a workspace-relative resolution - is still recognised. */
|
|
325
|
-
const isServerOnlyMarkerImport = (im) => {
|
|
326
|
-
if (im.original === SERVER_ONLY_MARKER)
|
|
327
|
-
return true;
|
|
328
|
-
// Defensive fallback: an edge that lost its `original` but resolved to the marker module file. The
|
|
329
|
-
// marker is the only `server-only.{ts,js}` under `@nifrajs/web`, so the basename is unambiguous.
|
|
330
|
-
const path = im.path;
|
|
331
|
-
return path !== undefined && /(^|\/)server-only\.[cm]?[jt]s$/.test(path);
|
|
332
|
-
};
|
|
333
|
-
/**
|
|
334
|
-
* BFS the metafile import graph for the SHORTEST user-module path that reaches a module which imports
|
|
335
|
-
* the `server-only` marker, returning it as display labels `[entryFile, …as-written specifiers…,
|
|
336
|
-
* "<module> (marked server-only)"]`. Mirrors {@link shortestBuiltinChain}: the frontier starts at
|
|
337
|
-
* every `entryInput` so the chain begins at the file the dev wrote an `import` in; traversal crosses
|
|
338
|
-
* only NON-`node:` user edges (no cycles via `seen`); it stops at the first node whose import set
|
|
339
|
-
* contains the marker (the marked module - the actionable tail), labelling that node by the as-written
|
|
340
|
-
* specifier the previous hop used to reach it. Pure - operates on the graph, never the emitted text.
|
|
341
|
-
*/
|
|
342
|
-
function shortestServerOnlyChain(inputs, entryInputs, markedModule, resolveTarget) {
|
|
343
|
-
// The label for the marked module's tail: its as-written specifier (filled when we cross the edge
|
|
344
|
-
// that reaches it) suffixed with `(marked server-only)`; the entry case uses the entry key itself.
|
|
345
|
-
const tail = (label) => `${label} (marked server-only)`;
|
|
346
|
-
// An entry that is ITSELF the marked module - the chain is just that one node.
|
|
347
|
-
if (entryInputs.includes(markedModule))
|
|
348
|
-
return [tail(markedModule)];
|
|
349
|
-
const seen = new Set(entryInputs);
|
|
350
|
-
let frontier = entryInputs.map((node) => ({
|
|
351
|
-
node,
|
|
352
|
-
chain: [node],
|
|
353
|
-
}));
|
|
354
|
-
while (frontier.length > 0) {
|
|
355
|
-
const next = [];
|
|
356
|
-
for (const { node, chain } of frontier) {
|
|
357
|
-
for (const im of inputs[node]?.imports ?? []) {
|
|
358
|
-
// Resolve the edge's `path` to the matching INPUT-GRAPH KEY - in a real build the edge `path`
|
|
359
|
-
// is absolute while the input keys are cwd-relative, so a raw equality/lookup would miss every
|
|
360
|
-
// multi-hop user edge (and the chain would degrade to just the tail). The resolver maps both.
|
|
361
|
-
const target = resolveTarget(im);
|
|
362
|
-
if (target === undefined || target.startsWith("node:"))
|
|
363
|
-
continue;
|
|
364
|
-
// The marked module reached via THIS edge → the chain ends here (label it as the marked tail
|
|
365
|
-
// using the as-written specifier the author wrote, falling back to the resolved key).
|
|
366
|
-
if (target === markedModule)
|
|
367
|
-
return [...chain, tail(im.original ?? target)];
|
|
368
|
-
if (seen.has(target))
|
|
369
|
-
continue;
|
|
370
|
-
seen.add(target);
|
|
371
|
-
next.push({ node: target, chain: [...chain, im.original ?? target] });
|
|
372
|
-
}
|
|
373
|
-
}
|
|
374
|
-
frontier = next;
|
|
375
|
-
}
|
|
376
|
-
return [tail(markedModule)]; // unreachable from any entry (defensive; a flagged module is reachable)
|
|
377
|
-
}
|
|
378
|
-
/**
|
|
379
|
-
* Build a resolver from an import EDGE to its INPUT-GRAPH KEY. Bun's metafile records edge `path`s as
|
|
380
|
-
* ABSOLUTE paths but keys `inputs` by CWD-RELATIVE paths, so a raw `inputs[im.path]` lookup misses
|
|
381
|
-
* every user edge in a real build. The resolver: (1) an exact key match (the synthetic-metafile / unit
|
|
382
|
-
* case); else (2) the input key the absolute path ends with (`…/secrets.ts` → `packages/web/.../secrets.ts`).
|
|
383
|
-
* The longest-suffix match is taken so a shorter key can't shadow a more specific one. Pure.
|
|
384
|
-
*/
|
|
385
|
-
function inputKeyResolver(inputs) {
|
|
386
|
-
const keys = Object.keys(inputs);
|
|
387
|
-
return (im) => {
|
|
388
|
-
const path = im.path;
|
|
389
|
-
if (path === undefined)
|
|
390
|
-
return undefined;
|
|
391
|
-
if (inputs[path] !== undefined)
|
|
392
|
-
return path; // exact (synthetic keys, or already-relative paths)
|
|
393
|
-
let best;
|
|
394
|
-
for (const key of keys) {
|
|
395
|
-
// `/<key>` so a suffix match aligns on a path boundary (never a partial segment), and the longest
|
|
396
|
-
// such key wins (the most specific file).
|
|
397
|
-
if (path.endsWith(`/${key}`) && (best === undefined || key.length > best.length))
|
|
398
|
-
best = key;
|
|
399
|
-
}
|
|
400
|
-
return best;
|
|
401
|
-
};
|
|
402
|
-
}
|
|
403
|
-
/**
|
|
404
|
-
* Scan a build's metafile for any module that opts into the `server-only` marker (a side-effect
|
|
405
|
-
* `import "@nifrajs/web/server-only"`) yet landed in a CLIENT output chunk, returning a sorted, deduped
|
|
406
|
-
* list of {@link ServerOnlyFinding}s. Mirrors {@link detectNodeBuiltinsInClient}: it reads the SAME
|
|
407
|
-
* graph facts - which inputs import the marker (the "marked" modules), which chunk each landed in (the
|
|
408
|
-
* per-output `inputs`), and the shortest import chain from a user entry to it. The marker module ITSELF
|
|
409
|
-
* (which imports nothing) is excluded - only the modules that *opt in* are flagged. Pure + exported for
|
|
410
|
-
* unit testing. Empty ⇒ clean.
|
|
411
|
-
*/
|
|
412
|
-
export function detectServerOnlyInClient(graph) {
|
|
413
|
-
const inputs = graph.modules;
|
|
414
|
-
// (1) The modules that import the marker - the ones the author opted into the guard. The marker
|
|
415
|
-
// module itself is skipped: it's the import TARGET, not an opt-in (it imports nothing of its own).
|
|
416
|
-
const marked = new Set();
|
|
417
|
-
for (const [inputKey, input] of Object.entries(inputs)) {
|
|
418
|
-
if (isServerOnlyMarkerModule(inputKey))
|
|
419
|
-
continue;
|
|
420
|
-
if ((input.imports ?? []).some(isServerOnlyMarkerImport))
|
|
421
|
-
marked.add(inputKey);
|
|
422
|
-
}
|
|
423
|
-
if (marked.size === 0)
|
|
424
|
-
return [];
|
|
425
|
-
// The entry inputs - the chain BFS starts here, so the reported path begins at the file the dev
|
|
426
|
-
// wrote an `import` in. Same derivation as the node-builtin guard.
|
|
427
|
-
const entryInputs = [
|
|
428
|
-
...new Set(Object.values(graph.chunks)
|
|
429
|
-
.map((o) => o.entryPoint)
|
|
430
|
-
.filter((e) => e !== undefined && !e.startsWith("node:"))),
|
|
431
|
-
];
|
|
432
|
-
const resolveTarget = inputKeyResolver(inputs);
|
|
433
|
-
const chainCache = new Map();
|
|
434
|
-
const chainFor = (markedModule) => {
|
|
435
|
-
const cached = chainCache.get(markedModule);
|
|
436
|
-
if (cached !== undefined)
|
|
437
|
-
return cached;
|
|
438
|
-
const chain = shortestServerOnlyChain(inputs, entryInputs, markedModule, resolveTarget);
|
|
439
|
-
chainCache.set(markedModule, chain);
|
|
440
|
-
return chain;
|
|
441
|
-
};
|
|
442
|
-
// (2) Locate which emitted chunk each marked module reached, via the per-output `inputs`.
|
|
443
|
-
const findings = new Map();
|
|
444
|
-
for (const [outPath, out] of Object.entries(graph.chunks)) {
|
|
445
|
-
for (const inputKey of out.modules) {
|
|
446
|
-
if (marked.has(inputKey)) {
|
|
447
|
-
const chunk = basename(outPath);
|
|
448
|
-
findings.set(`${inputKey}\0${chunk}`, { chunk, chain: chainFor(inputKey) });
|
|
449
|
-
}
|
|
450
|
-
}
|
|
451
|
-
}
|
|
452
|
-
return [...findings.values()].sort((a, b) => {
|
|
453
|
-
const am = a.chain[a.chain.length - 1] ?? "";
|
|
454
|
-
const bm = b.chain[b.chain.length - 1] ?? "";
|
|
455
|
-
return am === bm ? a.chunk.localeCompare(b.chunk) : am.localeCompare(bm);
|
|
456
|
-
});
|
|
457
|
-
}
|
|
458
|
-
/** True when an INPUT graph key is the marker module file itself (`…/server-only.{ts,js}` under web).
|
|
459
|
-
* Excluded from the "marked" set - the marker is the import target, not an opt-in module. */
|
|
460
|
-
const isServerOnlyMarkerModule = (inputKey) => /(^|\/)server-only\.[cm]?[jt]s$/.test(inputKey);
|
|
461
|
-
// ---------------------------------------------------------------------------------------------------
|
|
462
|
-
// Guard MESSAGES - one owner for both production pipelines. The Bun build (below) and the Vite/Rollup
|
|
463
|
-
// leak-guard plugin (plugins/vite-leak-guard.ts) both call these, so a leak reads IDENTICALLY whichever
|
|
464
|
-
// bundler produced it. A second bundler must not grow a second, subtly-different wording of a security
|
|
465
|
-
// error; that is exactly the "mostly ported" outcome the neutral graph seam exists to prevent.
|
|
466
|
-
// ---------------------------------------------------------------------------------------------------
|
|
467
|
-
/** The build-failing message for `node:` builtins that reached the client bundle. `undefined` ⇒ clean. */
|
|
468
|
-
export function formatNodeBuiltinLeak(findings) {
|
|
469
|
-
if (findings.length === 0)
|
|
470
|
-
return undefined;
|
|
471
|
-
const lines = findings.map((f) => f.chain.length > 1
|
|
472
|
-
? ` - ${f.builtin} reached the client bundle via ${f.chain.join(" → ")} (chunk: ${f.chunk})`
|
|
473
|
-
: ` - ${f.builtin} reached the client bundle via ${f.chunk}`);
|
|
474
|
-
return (`[nifra/web] Node built-in(s) in the client bundle - move them behind a server-only path ` +
|
|
475
|
-
`(a loader/action runs on the server; import the \`node:\` module there, not at a route's ` +
|
|
476
|
-
`top level):\n${lines.join("\n")}`);
|
|
477
|
-
}
|
|
478
|
-
/** The build-failing message for `server-only`-marked modules that reached the client. `undefined` ⇒ clean. */
|
|
479
|
-
export function formatServerOnlyLeak(findings) {
|
|
480
|
-
if (findings.length === 0)
|
|
481
|
-
return undefined;
|
|
482
|
-
const lines = findings.map((f) => f.chain.length > 1
|
|
483
|
-
? ` - server-only module reached the client bundle via ${f.chain.join(" → ")} (chunk: ${f.chunk})`
|
|
484
|
-
: ` - server-only module reached the client bundle via ${f.chunk}`);
|
|
485
|
-
return (`[nifra/web] server-only module(s) in the client bundle - a module marked ` +
|
|
486
|
-
`\`import "${SERVER_ONLY_MARKER}"\` reached the browser. Move it behind a server-only path ` +
|
|
487
|
-
`(reach it via a loader/action, or rename it \`*.server.ts\`), so its server logic never ships ` +
|
|
488
|
-
`to the client:\n${lines.join("\n")}`);
|
|
489
|
-
}
|
|
490
|
-
const basename = (path) => path.slice(path.lastIndexOf("/") + 1);
|
|
491
|
-
/** `[name]` Bun derives for an entrypoint: basename without extension (`users/[id].tsx` → `[id]`). */
|
|
492
|
-
const entryName = (file) => {
|
|
493
|
-
const base = basename(file);
|
|
494
|
-
const dot = base.lastIndexOf(".");
|
|
495
|
-
return dot === -1 ? base : base.slice(0, dot);
|
|
496
|
-
};
|
|
497
|
-
/**
|
|
498
|
-
* Aggregate a list of measured chunks into a {@link SizeReport}: sort biggest-gzip-first (ties broken
|
|
499
|
-
* by raw bytes, then name for stable output) and sum the totals. Pure - the measurement (reading the
|
|
500
|
-
* file + `Bun.gzipSync`) happens in the orchestrator; this is the deterministic, unit-testable core.
|
|
501
|
-
*/
|
|
502
|
-
export function aggregateSizeReport(chunks) {
|
|
503
|
-
const sorted = [...chunks].sort((a, b) => b.gzip - a.gzip || b.bytes - a.bytes || a.name.localeCompare(b.name));
|
|
504
|
-
let totalBytes = 0;
|
|
505
|
-
let totalGzip = 0;
|
|
506
|
-
for (const c of sorted) {
|
|
507
|
-
totalBytes += c.bytes;
|
|
508
|
-
totalGzip += c.gzip;
|
|
509
|
-
}
|
|
510
|
-
return { chunks: sorted, totalBytes, totalGzip };
|
|
511
|
-
}
|
|
512
|
-
/** Human-readable byte count: `B`/`KB`/`MB` with one decimal above 1 KB (e.g. `12.3 KB`). Pure. */
|
|
513
|
-
export function formatBytes(bytes) {
|
|
514
|
-
if (bytes < 1024)
|
|
515
|
-
return `${bytes} B`;
|
|
516
|
-
if (bytes < 1024 * 1024)
|
|
517
|
-
return `${(bytes / 1024).toFixed(1)} KB`;
|
|
518
|
-
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
|
519
|
-
}
|
|
520
|
-
/**
|
|
521
|
-
* Render a {@link SizeReport} as a terse aligned table (biggest first) with a totals row - the text
|
|
522
|
-
* `nifra build --report` prints. Pure (string in, string out) so the formatting is unit-testable.
|
|
523
|
-
*/
|
|
524
|
-
export function renderSizeReport(report) {
|
|
525
|
-
const rows = report.chunks.map((c) => ({
|
|
526
|
-
name: c.name,
|
|
527
|
-
raw: formatBytes(c.bytes),
|
|
528
|
-
gz: formatBytes(c.gzip),
|
|
529
|
-
}));
|
|
530
|
-
// Column widths from the header + every row + the totals label, so the table never clips a value.
|
|
531
|
-
const nameW = Math.max(5, ...rows.map((r) => r.name.length), "Total".length);
|
|
532
|
-
const rawW = Math.max(3, ...rows.map((r) => r.raw.length), formatBytes(report.totalBytes).length);
|
|
533
|
-
const gzW = Math.max(4, ...rows.map((r) => r.gz.length), formatBytes(report.totalGzip).length);
|
|
534
|
-
const padEnd = (s, w) => s + " ".repeat(Math.max(0, w - s.length));
|
|
535
|
-
const padStart = (s, w) => " ".repeat(Math.max(0, w - s.length)) + s;
|
|
536
|
-
const line = (name, raw, gz) => ` ${padEnd(name, nameW)} ${padStart(raw, rawW)} ${padStart(gz, gzW)}`;
|
|
537
|
-
const out = [
|
|
538
|
-
line("Chunk", "Raw", "Gzip"),
|
|
539
|
-
line("-".repeat(nameW), "-".repeat(rawW), "-".repeat(gzW)),
|
|
540
|
-
...rows.map((r) => line(r.name, r.raw, r.gz)),
|
|
541
|
-
line("Total", formatBytes(report.totalBytes), formatBytes(report.totalGzip)),
|
|
542
|
-
];
|
|
543
|
-
return out.join("\n");
|
|
544
|
-
}
|
|
545
|
-
// The route-relative file keys the generated manifest's route map declares. Both shapes are matched by
|
|
546
|
-
// their VALUE: eager ` "routes/x.tsx": m0,` and lazy ` "routes/x.tsx": () => import("./routes/x"),`.
|
|
547
|
-
// The KEY (not the import specifier) is the route identity `discoverRoutes` produces, extension and all;
|
|
548
|
-
// the import specifier is emitted extensionless (so a bare `tsc` compiles the manifest) and could not be
|
|
549
|
-
// mapped back to the exact `.tsx`/`.ts` key. The baked `routeStyles` JSON is a single line, so its keys
|
|
550
|
-
// are never at an indented line start and never match. `[ \t]+` (not `\s+`) so the `m` anchor stays on
|
|
551
|
-
// the same line and one route-map entry cannot span two lines of source.
|
|
552
|
-
const MANIFEST_ROUTE_ENTRY = /^[ \t]+(["'])([^"'\n]+)\1\s*:\s*(?:m\d+\b|\(\s*\)\s*=>\s*import\b)/gm;
|
|
553
|
-
// The lazy shape declares `const loaders`, the eager shape `const modules`. Anchored at a line start,
|
|
554
|
-
// NOT `.includes("const loaders =")`: the real emit is `const loaders: Record<...> = {`, whose `:` type
|
|
555
|
-
// annotation sits between the name and the `=`, so the ` =` substring never matched and every lazy
|
|
556
|
-
// manifest was re-synced as eager (silently converting `import()` splitting into a single eager bundle).
|
|
557
|
-
const MANIFEST_IS_LAZY = /^const loaders\b/m;
|
|
558
|
-
// The baked client-entry line: `export const clientEntry = "…"`.
|
|
559
|
-
const MANIFEST_CLIENT_ENTRY = /export\s+const\s+clientEntry\s*=\s*["']([^"']+)["']/;
|
|
560
|
-
/**
|
|
561
|
-
* Extract the route-relative file list a committed server-manifest declares, as the same
|
|
562
|
-
* `routes/`-relative keys `discoverRoutes` produces (e.g. `docs/index.tsx`). Reads the route map's KEYS,
|
|
563
|
-
* which carry the file extension and no directory prefix - exactly discovery's shape - so the result is
|
|
564
|
-
* independent of the specifier prefix the manifest happened to import with. The `@nifrajs/web` import and
|
|
565
|
-
* the baked `clientEntry`/`styles`/`routeStyles` lines carry no route-map entry and are ignored.
|
|
566
|
-
*
|
|
567
|
-
* `_routesPrefix` is accepted for call-site compatibility but no longer needed: the keys are already
|
|
568
|
-
* prefix-free. Pure - operates on source text.
|
|
569
|
-
*/
|
|
570
|
-
export function parseManifestRouteFiles(source, _routesPrefix) {
|
|
571
|
-
const files = new Set();
|
|
572
|
-
for (const match of source.matchAll(MANIFEST_ROUTE_ENTRY)) {
|
|
573
|
-
if (match[2] !== undefined)
|
|
574
|
-
files.add(match[2]);
|
|
575
|
-
}
|
|
576
|
-
return [...files].sort();
|
|
577
|
-
}
|
|
578
|
-
/** The baked `clientEntry` URL in a committed server-manifest, or `undefined` if absent. Pure. */
|
|
579
|
-
export function parseManifestClientEntry(source) {
|
|
580
|
-
return MANIFEST_CLIENT_ENTRY.exec(source)?.[1];
|
|
581
|
-
}
|
|
582
|
-
// The baked asset lines `generateServerManifest` emits: `export const styles = […]` then
|
|
583
|
-
// `export const routeStyles = {…}`, each a JSON literal running to the next `export const`. Extracted
|
|
584
|
-
// with `indexOf` slicing rather than a lazy `[\s\S]*?` regex: the slice is multi-line by nature (a
|
|
585
|
-
// formatter can wrap a long `routeStyles` map, and missing it would silently DROP every baked
|
|
586
|
-
// stylesheet on re-sync), and a lazy scan re-walks the file per unterminated opener - quadratic.
|
|
587
|
-
function bakedManifestLiteral(source, name) {
|
|
588
|
-
const opener = `export const ${name} = `;
|
|
589
|
-
const start = source.indexOf(opener);
|
|
590
|
-
if (start === -1)
|
|
591
|
-
return undefined;
|
|
592
|
-
const from = start + opener.length;
|
|
593
|
-
const end = source.indexOf("\nexport const ", from);
|
|
594
|
-
return end === -1 ? undefined : source.slice(from, end);
|
|
595
|
-
}
|
|
596
|
-
/** Parse a baked JSON literal captured from a committed manifest, tolerating a formatter's TRAILING COMMAS
|
|
597
|
-
* (biome/prettier add one when wrapping a multi-line array/object; strict `JSON.parse` would reject it).
|
|
598
|
-
* Only a comma immediately before a closing `]`/`}` is stripped, so commas inside string values are safe. */
|
|
599
|
-
function parseManifestLiteral(raw) {
|
|
600
|
-
return JSON.parse(raw.replace(/,(\s*[\]}])/g, "$1"));
|
|
601
|
-
}
|
|
602
|
-
/** The baked top-level `styles` array in a committed server-manifest (empty if absent/unparseable). Pure. */
|
|
603
|
-
export function parseManifestStyles(source) {
|
|
604
|
-
const raw = bakedManifestLiteral(source, "styles");
|
|
605
|
-
if (raw === undefined)
|
|
606
|
-
return [];
|
|
607
|
-
try {
|
|
608
|
-
const value = parseManifestLiteral(raw);
|
|
609
|
-
return Array.isArray(value) ? value : [];
|
|
610
|
-
}
|
|
611
|
-
catch {
|
|
612
|
-
return [];
|
|
613
|
-
}
|
|
614
|
-
}
|
|
615
|
-
/** The baked per-route `routeStyles` map in a committed server-manifest (empty if absent/unparseable). Pure. */
|
|
616
|
-
export function parseManifestRouteStyles(source) {
|
|
617
|
-
const raw = bakedManifestLiteral(source, "routeStyles");
|
|
618
|
-
if (raw === undefined)
|
|
619
|
-
return {};
|
|
620
|
-
try {
|
|
621
|
-
const value = parseManifestLiteral(raw);
|
|
622
|
-
return value !== null && typeof value === "object" && !Array.isArray(value)
|
|
623
|
-
? value
|
|
624
|
-
: {};
|
|
625
|
-
}
|
|
626
|
-
catch {
|
|
627
|
-
return {};
|
|
628
|
-
}
|
|
629
|
-
}
|
|
630
207
|
/**
|
|
631
208
|
* Re-emit a committed server-manifest from a freshly-discovered route tree, PRESERVING its baked
|
|
632
209
|
* client-asset references (`clientEntry` / `styles` / `routeStyles`) and its eager-vs-lazy shape. This is
|
|
@@ -651,37 +228,6 @@ export function resyncServerManifestSource(source, manifest, routesPrefix) {
|
|
|
651
228
|
* supplies both file lists (the committed source is parsed via {@link parseManifestRouteFiles}; the
|
|
652
229
|
* fresh list comes from `discoverRoutes`). Lists need not be pre-sorted; the result is sorted.
|
|
653
230
|
*/
|
|
654
|
-
export function diffManifestRoutes(manifestFiles, discoveredFiles) {
|
|
655
|
-
const inManifest = new Set(manifestFiles);
|
|
656
|
-
const inRoutes = new Set(discoveredFiles);
|
|
657
|
-
const missing = discoveredFiles.filter((f) => !inManifest.has(f)).sort();
|
|
658
|
-
const extra = manifestFiles.filter((f) => !inRoutes.has(f)).sort();
|
|
659
|
-
return { missing, extra };
|
|
660
|
-
}
|
|
661
|
-
/** True when a drift report is clean (no missing + no extra routes). */
|
|
662
|
-
export function isManifestInSync(drift) {
|
|
663
|
-
return drift.missing.length === 0 && drift.extra.length === 0;
|
|
664
|
-
}
|
|
665
|
-
/**
|
|
666
|
-
* Format a {@link ManifestDrift} as a named, actionable error message, or `undefined` when in sync.
|
|
667
|
-
* Names the exact missing/extra routes + the one fix (regenerate the manifest by re-running the build).
|
|
668
|
-
* `manifestPath` is shown for the dev to locate the stale file. Pure.
|
|
669
|
-
*/
|
|
670
|
-
export function formatManifestDrift(drift, manifestPath = "server-manifest.ts") {
|
|
671
|
-
if (isManifestInSync(drift))
|
|
672
|
-
return undefined;
|
|
673
|
-
const lines = [
|
|
674
|
-
`[nifra/web] server-manifest drift - \`${manifestPath}\` is out of sync with routes/.`,
|
|
675
|
-
];
|
|
676
|
-
if (drift.missing.length > 0) {
|
|
677
|
-
lines.push(` Missing (in routes/, not in the manifest - these routes won't be served): ${drift.missing.join(", ")}`);
|
|
678
|
-
}
|
|
679
|
-
if (drift.extra.length > 0) {
|
|
680
|
-
lines.push(` Extra (imported by the manifest, gone from routes/ - a dangling import): ${drift.extra.join(", ")}`);
|
|
681
|
-
}
|
|
682
|
-
lines.push(" Fix: re-run the build to regenerate the server manifest, then commit it.");
|
|
683
|
-
return lines.join("\n");
|
|
684
|
-
}
|
|
685
231
|
/**
|
|
686
232
|
* Build the client bundle for a file-routed app. Writes the hashed assets + `manifest.json` to
|
|
687
233
|
* `outDir` and returns the manifest. Throws (with the bundler logs) on build failure - never
|
|
@@ -693,6 +239,20 @@ export async function buildClient(options) {
|
|
|
693
239
|
await assertIdentityParity(root);
|
|
694
240
|
const resolve = options.resolve ?? ((file) => `${routesDir}/${file}`);
|
|
695
241
|
const publicPath = options.publicPath ?? "/assets/";
|
|
242
|
+
// outDir inside publicDir folds the build output back into the public copy on the next run (the
|
|
243
|
+
// bundle lands at public/assets/assets/*), and the dev/prod parity assert then throws on paths no
|
|
244
|
+
// one authored. Reject the overlap up front - no copy behavior is correct for this layout, and the
|
|
245
|
+
// parity symptom names neither option so the cause is unrecoverable from the message.
|
|
246
|
+
const publicRoot = options.publicDir === false ? undefined : (options.publicDir ?? "public");
|
|
247
|
+
if (publicRoot !== undefined) {
|
|
248
|
+
const publicResolved = resolvePath(publicRoot);
|
|
249
|
+
const outResolved = resolvePath(outDir);
|
|
250
|
+
if (outResolved === publicResolved || outResolved.startsWith(publicResolved + sep)) {
|
|
251
|
+
throw new Error(`[nifra/web] outDir (${outResolved}) is inside publicDir (${publicResolved}). The public ` +
|
|
252
|
+
`copy would fold the build output back into itself. Move outDir outside publicDir, or ` +
|
|
253
|
+
`pass publicDir: false if the app has no hand-authored static files.`);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
696
256
|
mkdirSync(outDir, { recursive: true });
|
|
697
257
|
const routeManifest = discoverRoutes(routesDir);
|
|
698
258
|
// The bootstrap's filename is `_nifra`-namespaced (not `entry.ts`) so its `[name]` can't collide with
|
|
@@ -862,7 +422,12 @@ export async function buildClient(options) {
|
|
|
862
422
|
return [...new Set(urls)];
|
|
863
423
|
};
|
|
864
424
|
const routeStyles = {};
|
|
865
|
-
|
|
425
|
+
// A compiler plugin may attach a global stylesheet to the generated bootstrap rather than to a
|
|
426
|
+
// route entry (StyleX's atomic CSS is one example). In that shape there is no useful per-route map:
|
|
427
|
+
// emitting `routeId: []` would suppress the aggregate `styles` fallback in `createWebApp` and render
|
|
428
|
+
// SSR pages unstyled. Keep routeStyles absent until at least one authored route entry owns CSS.
|
|
429
|
+
const routeCssEntries = [...cssByEntry.keys()].filter((entry) => entry !== resolvePath(entryFile));
|
|
430
|
+
if (css.length > 0 && routeCssEntries.length > 0) {
|
|
866
431
|
for (const route of routeManifest.routes) {
|
|
867
432
|
routeStyles[route.id] = stylesFor([
|
|
868
433
|
...route.layoutIds.map((id) => routeManifest.layouts[id]?.file ?? ""),
|
|
@@ -888,6 +453,7 @@ export async function buildClient(options) {
|
|
|
888
453
|
writeFileSync(`${outDir}/manifest.json`, JSON.stringify(manifest, null, 2));
|
|
889
454
|
return manifest;
|
|
890
455
|
}
|
|
456
|
+
/** The built worker bundle - point your `wrangler.toml`'s `main` at `worker`. */
|
|
891
457
|
/**
|
|
892
458
|
* react-dom's `exports["./server"]` maps the `bun` condition to a Bun-API server build that crashes
|
|
893
459
|
* on workerd, and `Bun.build` always applies the `bun` condition (it wins over `workerd`/`edge-light`),
|
|
@@ -1130,12 +696,6 @@ export async function buildServer(options) {
|
|
|
1130
696
|
// The ONLY thing apps used to hand-write per target was the server entry (`_worker.ts`, `server-bun.ts`,
|
|
1131
697
|
// …) - so we GENERATE it here (per target) instead of asking each app to ship five near-identical files.
|
|
1132
698
|
// ===================================================================================================
|
|
1133
|
-
/** A deploy target `nifra build --target <t>` can emit. `static` is pure SSG (no server). */
|
|
1134
|
-
export const BUILD_TARGETS = ["bun", "node", "deno", "cf-pages", "vercel", "static"];
|
|
1135
|
-
/** A type guard narrowing an arbitrary string to a {@link BuildTarget}. */
|
|
1136
|
-
export function isBuildTarget(value) {
|
|
1137
|
-
return BUILD_TARGETS.includes(value);
|
|
1138
|
-
}
|
|
1139
699
|
/**
|
|
1140
700
|
* Codegen the per-target **server entry** module (source text) for `buildServer` to bundle. It imports
|
|
1141
701
|
* the app's `adapter` (from `framework.ts`), the optional `backend` (from `backend.ts`), and the
|
|
@@ -1203,14 +763,6 @@ export function generateServerEntry(options) {
|
|
|
1203
763
|
lines.push("const handler = toFetchHandler(app)", "// @ts-ignore - Deno global is present on the Deno runtime this output targets.", 'Deno.serve({ port: Number(Deno.env.get("PORT") ?? "3000") }, async (req) => {', " const { pathname } = new URL(req.url)", " const filePath = staticPath(pathname)", " if (filePath !== undefined) {", " try {", " // @ts-ignore - Deno.readFile is present on the Deno runtime.", " const body = await Deno.readFile(new URL(filePath, STATIC_ROOT))", ' const ext = pathname.slice(pathname.lastIndexOf(".") + 1)', ' return new Response(body, { headers: { "content-type": TYPES[ext] ?? "application/octet-stream" } })', " } catch {", ' return new Response("not found", { status: 404 })', " }", " }", " return handler.fetch(req)", "})");
|
|
1204
764
|
return `${lines.join("\n")}\n`;
|
|
1205
765
|
}
|
|
1206
|
-
/** The Bun.build `target` each deploy target compiles its server with (mirrors `buildServer`'s docs). */
|
|
1207
|
-
const SERVER_BUILD_TARGET = {
|
|
1208
|
-
"cf-pages": "browser", // edge conditions (workerd/edge-light)
|
|
1209
|
-
vercel: "browser", // Vercel Edge runtime
|
|
1210
|
-
deno: "browser", // Deno's Web-standard runtime runs the edge bundle
|
|
1211
|
-
node: "node", // node:* external; react-dom → its Node SSR build
|
|
1212
|
-
bun: "bun", // Bun's flagship runtime
|
|
1213
|
-
};
|
|
1214
766
|
/** Measure each emitted output file's raw + gzip size. Reads the file off disk and gzips it with
|
|
1215
767
|
* `Bun.gzipSync` (the over-the-wire weight). Async only because it reads files; the aggregation is the
|
|
1216
768
|
* pure {@link aggregateSizeReport}. */
|
|
@@ -1226,6 +778,21 @@ async function measureOutputs(paths) {
|
|
|
1226
778
|
}
|
|
1227
779
|
return chunks;
|
|
1228
780
|
}
|
|
781
|
+
/**
|
|
782
|
+
* Build a full deploy directory for `target` from a file-routed nifra app. Emits the client bundle to
|
|
783
|
+
* `<outDir>/assets/*`, then per target:
|
|
784
|
+
* - `static`: prerenders opted-in routes (`prerenderRoutes`) to `<outDir>/<path>/index.html` (+
|
|
785
|
+
* `_data.json`); needs `prerenderApp`. No server.
|
|
786
|
+
* - `cf-pages`: a `_worker.js` (edge bundle) + a `_routes.json` excluding /assets/* from the worker.
|
|
787
|
+
* - `vercel`: a `.vercel/output`-shaped function isn't emitted here - `vercel` emits the bundled edge
|
|
788
|
+
* entry as `<outDir>/index.js` (the CLI's docs point at `vercel`'s Build Output wrapper). [see note]
|
|
789
|
+
* - `deno`/`node`/`bun`: the self-hosting server bundle (`server.js`) next to the assets.
|
|
790
|
+
* The server entry is GENERATED (`generateServerEntry`) and bundled (`buildServer`); the app supplies
|
|
791
|
+
* only adapter/backend/routes. Returns the manifest + a size report. Throws on any build failure.
|
|
792
|
+
*
|
|
793
|
+
* Note: the heavier platform wrappers (`.vercel/output` v3 layout, wrangler ISR `find_additional_modules`)
|
|
794
|
+
* remain app-owned scripts; this command targets the common single-bundle deploys. See the CLI docs.
|
|
795
|
+
*/
|
|
1229
796
|
/** The default (Bun) strategy - `buildClient`/`buildServer` from this module. */
|
|
1230
797
|
export const bunBundler = {
|
|
1231
798
|
buildClient: (input) => buildClient({
|
|
@@ -1260,6 +827,7 @@ export async function buildTarget(target, options) {
|
|
|
1260
827
|
*/
|
|
1261
828
|
export async function buildTargetWith(target, options, bundler) {
|
|
1262
829
|
const { routesDir, outDir, workDir } = options;
|
|
830
|
+
const targetPlan = planBuildTarget(target, outDir);
|
|
1263
831
|
const { rmSync } = await import("node:fs");
|
|
1264
832
|
rmSync(outDir, { recursive: true, force: true });
|
|
1265
833
|
rmSync(workDir, { recursive: true, force: true });
|
|
@@ -1286,7 +854,7 @@ export async function buildTargetWith(target, options, bundler) {
|
|
|
1286
854
|
client = { ...client, publicFiles };
|
|
1287
855
|
writeFileSync(`${assetsDir}/manifest.json`, JSON.stringify(client, null, 2));
|
|
1288
856
|
}
|
|
1289
|
-
if (
|
|
857
|
+
if (targetPlan.kind === "static") {
|
|
1290
858
|
if (options.prerenderApp === undefined) {
|
|
1291
859
|
throw new Error("[nifra/web] buildTarget(static) requires `prerenderApp` (a factory `(client) => createWebApp`)");
|
|
1292
860
|
}
|
|
@@ -1312,7 +880,7 @@ export async function buildTargetWith(target, options, bundler) {
|
|
|
1312
880
|
target,
|
|
1313
881
|
outDir,
|
|
1314
882
|
client,
|
|
1315
|
-
run:
|
|
883
|
+
run: targetPlan.run,
|
|
1316
884
|
size,
|
|
1317
885
|
};
|
|
1318
886
|
}
|
|
@@ -1328,22 +896,20 @@ export async function buildTargetWith(target, options, bundler) {
|
|
|
1328
896
|
...(options.title !== undefined ? { title: options.title } : {}),
|
|
1329
897
|
...(publicFiles.length > 0 ? { publicFiles } : {}),
|
|
1330
898
|
}));
|
|
1331
|
-
const serverTarget = SERVER_BUILD_TARGET[target];
|
|
1332
899
|
const { worker } = await bundler.buildServer({
|
|
1333
900
|
routesDir,
|
|
1334
901
|
serverEntry: serverEntryPath,
|
|
1335
902
|
outDir: `${workDir}/server`,
|
|
1336
903
|
clientEntry: client.entry,
|
|
1337
|
-
target: serverTarget,
|
|
904
|
+
target: targetPlan.serverTarget,
|
|
1338
905
|
...(options.serverPlugins ? { plugins: options.serverPlugins } : {}),
|
|
1339
906
|
define: { "process.env.NODE_ENV": '"production"', ...(options.define ?? {}) },
|
|
1340
907
|
root: resolvePath(dirname(routesDir)),
|
|
1341
908
|
});
|
|
1342
909
|
// (3) Assemble the deploy dir for the target.
|
|
1343
910
|
const { cpSync } = await import("node:fs");
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
cpSync(worker, `${outDir}/_worker.js`);
|
|
911
|
+
if (targetPlan.target === "cf-pages") {
|
|
912
|
+
cpSync(worker, `${outDir}/${targetPlan.outputFile}`);
|
|
1347
913
|
// The app's real patterns, so a directory is only collapsed into a glob once the route table
|
|
1348
914
|
// proves nothing can be served beneath it.
|
|
1349
915
|
const rules = cloudflareRouteRules(publicFiles, discoverRoutes(routesDir).routes.map((route) => route.pattern));
|
|
@@ -1355,26 +921,19 @@ export async function buildTargetWith(target, options, bundler) {
|
|
|
1355
921
|
`(Cloudflare allows ${CF_MAX_ROUTE_RULES}). The other ${rules.omitted.length} file(s) are served by the ` +
|
|
1356
922
|
"worker via ASSETS instead of the CDN directly - correct, just one invocation each.");
|
|
1357
923
|
}
|
|
1358
|
-
run = `Cloudflare Pages → ${outDir} (deploy: wrangler pages deploy ${basename(outDir)})`;
|
|
1359
924
|
}
|
|
1360
|
-
else if (target === "vercel") {
|
|
1361
|
-
cpSync(worker, `${outDir}
|
|
1362
|
-
run = `Vercel edge function → ${outDir}/index.js (wrap with your vercel.json or Build Output API)`;
|
|
925
|
+
else if (targetPlan.target === "vercel") {
|
|
926
|
+
cpSync(worker, `${outDir}/${targetPlan.outputFile}`);
|
|
1363
927
|
}
|
|
1364
928
|
else {
|
|
1365
|
-
|
|
1366
|
-
cpSync(worker, `${outDir}/server.js`);
|
|
1367
|
-
const cmd = target === "node"
|
|
1368
|
-
? `node ${basename(outDir)}/server.js`
|
|
1369
|
-
: `${target} ${basename(outDir)}/server.js`;
|
|
1370
|
-
run = `${target} server → ${outDir} (run: ${cmd})`;
|
|
929
|
+
cpSync(worker, `${outDir}/${targetPlan.outputFile}`);
|
|
1371
930
|
}
|
|
1372
931
|
rmSync(workDir, { recursive: true, force: true });
|
|
1373
932
|
// Size report over the client assets + the server bundle (its parse cost matters on the edge).
|
|
1374
933
|
const clientPaths = client.assets.map((u) => assetUrlToPath(u, assetsDir));
|
|
1375
|
-
const serverPath = `${outDir}/${
|
|
934
|
+
const serverPath = `${outDir}/${targetPlan.outputFile}`;
|
|
1376
935
|
const size = aggregateSizeReport(await measureOutputs([...clientPaths, serverPath]));
|
|
1377
|
-
return { target, outDir, client, run, size };
|
|
936
|
+
return { target, outDir, client, run: targetPlan.run, size };
|
|
1378
937
|
}
|
|
1379
938
|
/** Map a client asset URL (`/assets/x-hash.js`) back to its on-disk path under `assetsDir`. The
|
|
1380
939
|
* `publicPath` prefix is always `/assets/` for these builds, so strip it and rejoin. */
|