@yolo-labs/yolo-cli 0.25.0 → 0.31.1

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/cli.js CHANGED
@@ -143,6 +143,16 @@ function printHelp() {
143
143
  ' tileapp publish <manifest> [opts] Submit a SIGNED manifest for marketplace review (POST /v1/publisher/publish).',
144
144
  ' [--channel beta|stable] Target channel (default: stable).',
145
145
  ' [--image-digest <d>] Consistency check: must equal the signed manifest image.digest.',
146
+ ' tileapp install <appId> [opts] Record an app grant for a workspace (POST /v1/tileapps/:appId/install).',
147
+ ' --workspace <workspaceId> Target workspace (required).',
148
+ ' [--accept-optional <perm>] Accept an optional permission (repeatable).',
149
+ ' tileapp add-tile <appId> [opts] Place an app tile in a workspace (POST /v1/workspaces/:id/tiles).',
150
+ ' --workspace <workspaceId> Target workspace (required).',
151
+ ' [--name <name>] Tile display name (default: the app manifest displayName).',
152
+ ' [--version <v>] App version to pin (default: the app\'s current version).',
153
+ ' mcp scopes [opts] Show mintable vs not-mintable MCP scopes for this session (pure read).',
154
+ ' [--agent <agentId>] Agent identity to inspect (default: substrate-cli).',
155
+ ' [--json] Emit {agentId, allowed, denied} as JSON.',
146
156
  ' serve <dir> [opts] Static file server (decision-preview / Gap 2a).',
147
157
  ' [--port <n>] Port (default: $PORT, else 3000).',
148
158
  ' [--host <h>] Bind host (default: 0.0.0.0).',
@@ -746,10 +756,161 @@ function tileAppUsage(sub, message) {
746
756
  + ' or: yolo tileapp publish <manifest.json> [--channel beta|stable] [--image-digest <d>] (marketplace)\n',
747
757
  validate: 'Usage: yolo tileapp validate <manifest.json> [--bundle-dir <dir>]\n',
748
758
  dev: 'Usage: yolo tileapp dev <manifest.json> [--port N] [--host H] [--bundle-dir <dir>] [--deny]\n',
759
+ install: 'Usage: yolo tileapp install <appId> --workspace <workspaceId> [--accept-optional <perm>]...\n',
760
+ 'add-tile': 'Usage: yolo tileapp add-tile <appId> --workspace <workspaceId> [--name <name>] [--version <v>]\n',
749
761
  };
750
762
  process.stderr.write(usage[sub]);
751
763
  return 64;
752
764
  }
765
+ async function runTileAppInstallCmd(args) {
766
+ let appId;
767
+ let workspaceId;
768
+ const acceptOptional = [];
769
+ for (let i = 0; i < args.length; i++) {
770
+ const a = args[i];
771
+ // A following flag must never be consumed as a value (`--workspace
772
+ // --accept-optional=x`), so reject empty values and `--`-leading values —
773
+ // same pattern as the run/plan parsers (codex gpt-5.6-sol P3, 2026-07-18).
774
+ if (a === '--workspace') {
775
+ const v = args[++i];
776
+ if (!v || v.startsWith('--'))
777
+ return tileAppUsage('install', '--workspace requires a value');
778
+ workspaceId = v;
779
+ }
780
+ else if (a.startsWith('--workspace=')) {
781
+ const v = a.slice('--workspace='.length);
782
+ if (!v)
783
+ return tileAppUsage('install', '--workspace requires a value');
784
+ workspaceId = v;
785
+ }
786
+ else if (a === '--accept-optional') {
787
+ const v = args[++i];
788
+ if (!v || v.startsWith('--'))
789
+ return tileAppUsage('install', '--accept-optional requires a value');
790
+ acceptOptional.push(v);
791
+ }
792
+ else if (a.startsWith('--accept-optional=')) {
793
+ const v = a.slice('--accept-optional='.length);
794
+ if (!v)
795
+ return tileAppUsage('install', '--accept-optional requires a value');
796
+ acceptOptional.push(v);
797
+ }
798
+ else if (!a.startsWith('-') && !appId)
799
+ appId = a;
800
+ else
801
+ return tileAppUsage('install', `unexpected argument '${a}'`);
802
+ }
803
+ if (!appId || !workspaceId)
804
+ return tileAppUsage('install', 'an appId and --workspace <workspaceId> are required');
805
+ const { runTileAppInstall, exitCodeForFailure } = await import('./tileapp-workspace.js');
806
+ const result = await runTileAppInstall({ appId, workspaceId, acceptOptional });
807
+ if (result.ok) {
808
+ process.stdout.write(`${result.output}\n`);
809
+ return 0;
810
+ }
811
+ process.stderr.write(`FAIL [${result.kind}]: ${result.message}\n`);
812
+ return exitCodeForFailure(result.kind);
813
+ }
814
+ async function runTileAppAddTileCmd(args) {
815
+ let appId;
816
+ let workspaceId;
817
+ let name;
818
+ let version;
819
+ for (let i = 0; i < args.length; i++) {
820
+ const a = args[i];
821
+ // Reject empty/`--`-leading values so a following flag is never consumed
822
+ // as a value (codex gpt-5.6-sol P3, 2026-07-18).
823
+ if (a === '--workspace') {
824
+ const v = args[++i];
825
+ if (!v || v.startsWith('--'))
826
+ return tileAppUsage('add-tile', '--workspace requires a value');
827
+ workspaceId = v;
828
+ }
829
+ else if (a.startsWith('--workspace=')) {
830
+ const v = a.slice('--workspace='.length);
831
+ if (!v)
832
+ return tileAppUsage('add-tile', '--workspace requires a value');
833
+ workspaceId = v;
834
+ }
835
+ else if (a === '--name') {
836
+ const v = args[++i];
837
+ if (!v || v.startsWith('--'))
838
+ return tileAppUsage('add-tile', '--name requires a value');
839
+ name = v;
840
+ }
841
+ else if (a.startsWith('--name=')) {
842
+ const v = a.slice('--name='.length);
843
+ if (!v)
844
+ return tileAppUsage('add-tile', '--name requires a value');
845
+ name = v;
846
+ }
847
+ else if (a === '--version') {
848
+ const v = args[++i];
849
+ if (!v || v.startsWith('--'))
850
+ return tileAppUsage('add-tile', '--version requires a value');
851
+ version = v;
852
+ }
853
+ else if (a.startsWith('--version=')) {
854
+ const v = a.slice('--version='.length);
855
+ if (!v)
856
+ return tileAppUsage('add-tile', '--version requires a value');
857
+ version = v;
858
+ }
859
+ else if (!a.startsWith('-') && !appId)
860
+ appId = a;
861
+ else
862
+ return tileAppUsage('add-tile', `unexpected argument '${a}'`);
863
+ }
864
+ if (!appId || !workspaceId)
865
+ return tileAppUsage('add-tile', 'an appId and --workspace <workspaceId> are required');
866
+ const { runTileAppAddTile, exitCodeForFailure } = await import('./tileapp-workspace.js');
867
+ const result = await runTileAppAddTile({ appId, workspaceId, name, version });
868
+ if (result.ok) {
869
+ process.stdout.write(`${result.output}\n`);
870
+ return 0;
871
+ }
872
+ process.stderr.write(`FAIL [${result.kind}]: ${result.message}\n`);
873
+ return exitCodeForFailure(result.kind);
874
+ }
875
+ async function runMcpScopesCmd(args) {
876
+ let agentId;
877
+ let jsonOutput = false;
878
+ for (let i = 0; i < args.length; i++) {
879
+ const a = args[i];
880
+ // Reject empty/`--`-leading values so a following flag is never consumed
881
+ // as a value (codex gpt-5.6-sol P3, 2026-07-18).
882
+ if (a === '--agent') {
883
+ const v = args[++i];
884
+ if (!v || v.startsWith('--')) {
885
+ process.stderr.write('yolo mcp scopes: --agent requires a value\n');
886
+ return 64;
887
+ }
888
+ agentId = v;
889
+ }
890
+ else if (a.startsWith('--agent=')) {
891
+ const v = a.slice('--agent='.length);
892
+ if (!v) {
893
+ process.stderr.write('yolo mcp scopes: --agent requires a value\n');
894
+ return 64;
895
+ }
896
+ agentId = v;
897
+ }
898
+ else if (a === '--json')
899
+ jsonOutput = true;
900
+ else {
901
+ process.stderr.write(`yolo mcp scopes: unexpected argument '${a}'\nUsage: yolo mcp scopes [--agent <agentId>] [--json]\n`);
902
+ return 64;
903
+ }
904
+ }
905
+ const { runMcpScopes, exitCodeForFailure } = await import('./mcp-scopes.js');
906
+ const result = await runMcpScopes({ agentId, outputFormat: jsonOutput ? 'json' : 'summary' });
907
+ if (result.ok) {
908
+ process.stdout.write(`${result.output}\n`);
909
+ return 0;
910
+ }
911
+ process.stderr.write(`FAIL [${result.kind}]: ${result.message}\n`);
912
+ return exitCodeForFailure(result.kind);
913
+ }
753
914
  async function runTileAppSignCmd(args) {
754
915
  let manifestPath;
755
916
  let publisherId;
@@ -1375,12 +1536,28 @@ async function main(argv) {
1375
1536
  return runTileAppValidateCmd(args.slice(2));
1376
1537
  if (sub === 'dev')
1377
1538
  return runTileAppDevCmd(args.slice(2));
1539
+ if (sub === 'install')
1540
+ return runTileAppInstallCmd(args.slice(2));
1541
+ if (sub === 'add-tile')
1542
+ return runTileAppAddTileCmd(args.slice(2));
1378
1543
  if (!sub) {
1379
- process.stderr.write('yolo: tileapp requires a subcommand (init, validate, dev, sign, publish)\n');
1544
+ process.stderr.write('yolo: tileapp requires a subcommand (init, validate, dev, sign, publish, install, add-tile)\n');
1380
1545
  return 64;
1381
1546
  }
1382
1547
  process.stderr.write(`yolo: unknown tileapp subcommand '${sub}'\n`);
1383
- process.stderr.write('Subcommands: init, validate, dev, sign, publish\n');
1548
+ process.stderr.write('Subcommands: init, validate, dev, sign, publish, install, add-tile\n');
1549
+ return 64;
1550
+ }
1551
+ if (cmd === 'mcp') {
1552
+ const sub = args[1];
1553
+ if (sub === 'scopes')
1554
+ return runMcpScopesCmd(args.slice(2));
1555
+ if (!sub) {
1556
+ process.stderr.write('yolo: mcp requires a subcommand (scopes)\n');
1557
+ return 64;
1558
+ }
1559
+ process.stderr.write(`yolo: unknown mcp subcommand '${sub}'\n`);
1560
+ process.stderr.write('Subcommands: scopes\n');
1384
1561
  return 64;
1385
1562
  }
1386
1563
  if (cmd === 'serve') {
@@ -8,11 +8,21 @@
8
8
  * - **Worker module** — esbuild ESM bundle of the entry
9
9
  * (`{bundle, format:'esm', platform:'browser',
10
10
  * conditions:['workerd','worker'], target:'es2022', write:false,
11
- * minify:true}`). If the entry already points at a BUILT `.js`/`.mjs`
12
- * module (vinext/OpenNext output, skill-directed), esbuild is
13
- * SKIPPED and the module ships byte-for-byte as-is — the size
14
- * ceilings still apply. esbuild is lazy-imported so `yolo plan`
15
- * startup never pays for it (the `serve.ts` lazy-load precedent).
11
+ * minify:true, define:{'process.env.NODE_ENV':'"production"'}}` +
12
+ * `nodeBuiltinExternalPlugin`). `NODE_ENV` is pinned to `production` so
13
+ * libraries that branch on it (React et al.) never ship their dev build on
14
+ * workerd (which has no runtime `process.env`). The plugin leaves every real
15
+ * `node:` builtin external (nodejs_compat serves the supported ones); a
16
+ * misspelled non-builtin is the only `node:` case that fails the build. It
17
+ * WARNS (not fails) when nodejs_compat is absent and when a builtin is loaded
18
+ * via `require()` (throws in an ESM Worker unless guarded). If the entry
19
+ * already points at a
20
+ * BUILT `.js`/`.mjs` module (vinext/OpenNext output, skill-directed),
21
+ * esbuild is SKIPPED and the module ships byte-for-byte as-is — the size
22
+ * ceilings still apply and the shipped text is scanned to WARN on retained
23
+ * `node:` imports and an unpinned `process.env.NODE_ENV`. esbuild is
24
+ * lazy-imported so `yolo plan` startup never pays for it (the `serve.ts`
25
+ * lazy-load precedent).
16
26
  * - **Asset manifest** — walk `assetsDir` (skip dotfiles +
17
27
  * node_modules), URL-style path → `{hash: sha256hex, size}`.
18
28
  * Pure-static ships NO module; common-api attaches the canonical
@@ -32,6 +42,7 @@
32
42
  */
33
43
  import { createHash } from 'node:crypto';
34
44
  import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
45
+ import { isBuiltin } from 'node:module';
35
46
  import path from 'node:path';
36
47
  import { fileURLToPath } from 'node:url';
37
48
  import { gzipSync } from 'node:zlib';
@@ -95,6 +106,98 @@ function vendoredFlexdbPlugin() {
95
106
  },
96
107
  };
97
108
  }
109
+ // ─── node: builtin externalization ──────────────────────────────────────────
110
+ //
111
+ // A `node:` builtin can't be bundled — esbuild's browser resolver would hard-
112
+ // fail it. We leave every REAL builtin external (workerd's nodejs_compat serves
113
+ // the ones it supports at the pinned compatibility date); the ONLY `node:` case
114
+ // that stays a build error is a non-builtin specifier (a `node:async_hook` typo
115
+ // → esbuild "Could not resolve"). Everything else externalizes and, where risky,
116
+ // WARNS post-bundle:
117
+ // - a require()-kind load → esbuild emits __require(...), which throws in an
118
+ // ESM Worker UNLESS guarded by try/catch → warn (collectExternalNodeRequires),
119
+ // don't fail — a hard error would break guarded optional-dependency probes
120
+ // - node: builtins with no nodejs_compat → warn (warnMissingNodejsCompat)
121
+ //
122
+ // Deliberately NOT a workerd compatibility oracle: which builtins a given
123
+ // compatibility-date + flag set actually serves (tls, node:fs behind
124
+ // enable_nodejs_fs_module, modules dropped by no_* flags, …) is a moving matrix
125
+ // that belongs to the runtime, not the bundler. Modeling it here only produces
126
+ // false build rejections of valid Workers. The post-ship boot probe / runtime is
127
+ // the authority on whether a module is really served.
128
+ /**
129
+ * esbuild plugin that leaves every real `node:` builtin external (any import
130
+ * kind, including require-call), so a non-builtin typo is the only `node:` case
131
+ * that stays a build error. A require()-kind load is externalized rather than
132
+ * rejected: esbuild emits `__require(...)`, which a GUARDED probe
133
+ * (`try { require("node:fs") } catch { …fallback… }`) can still catch — a hard
134
+ * rejection would break that common optional-dependency pattern. An UNGUARDED
135
+ * require of a builtin throws in an ESM Worker; that's surfaced as a post-bundle
136
+ * warning (see collectExternalNodeRequires), not a build failure.
137
+ */
138
+ function nodeBuiltinExternalPlugin() {
139
+ return {
140
+ name: 'yolo-node-builtin-external',
141
+ setup(build) {
142
+ build.onResolve({ filter: /^node:/ }, (args) => {
143
+ if (isBuiltin(args.path))
144
+ return { path: args.path, external: true };
145
+ return null; // not a builtin at all → esbuild reports "Could not resolve"
146
+ });
147
+ },
148
+ };
149
+ }
150
+ /**
151
+ * The distinct `node:<builtin>` specifiers referenced by already-bundled text
152
+ * (prebuilt worker path, which never touches esbuild). A `node:` literal in
153
+ * call position — `require(…)`, esbuild's `__require(…)`, dynamic `import(…)` —
154
+ * or after `from`/bare `import` counts. Matching any call `(` (rather than a
155
+ * specific helper name) is deliberate: bundlers rename the require helper.
156
+ * Deduped, sorted.
157
+ */
158
+ export function collectNodeBuiltinsFromText(text) {
159
+ const found = new Set();
160
+ const re = /(?:\bfrom\s*|\bimport\s*|\(\s*)['"](node:[a-zA-Z0-9_/.-]+)['"]/g;
161
+ let m;
162
+ while ((m = re.exec(text)) !== null)
163
+ found.add(m[1]);
164
+ return [...found].sort();
165
+ }
166
+ /**
167
+ * The distinct `node:` builtins loaded via a CommonJS `require(…)` / esbuild's
168
+ * `__require(…)` (any `<ident>require(` helper) in already-bundled text. These
169
+ * throw in an ESM Worker regardless of `nodejs_compat` — the esbuild path
170
+ * rejects them; the prebuilt path (esbuild skipped) can only WARN. Deduped, sorted.
171
+ */
172
+ export function collectNodeRequireCalls(text) {
173
+ const found = new Set();
174
+ // A require-CALL of a node: literal: `require("node:x")`, `__require("node:x")`.
175
+ // The leading \w* covers renamed helpers; it won't match the shim's own
176
+ // definition (that has no node: string argument).
177
+ const re = /\w*require\s*\(\s*['"](node:[a-zA-Z0-9_/.-]+)['"]/g;
178
+ let m;
179
+ while ((m = re.exec(text)) !== null)
180
+ found.add(m[1]);
181
+ return [...found].sort();
182
+ }
183
+ /**
184
+ * Push the "missing nodejs_compat" warning when a Worker references a `node:`
185
+ * builtin but that flag isn't set. Shared by the esbuild and prebuilt paths so
186
+ * `BundleOptions`' promise holds for both.
187
+ *
188
+ * Keyed strictly on `nodejs_compat` — the ONLY compatibility flag the hosting
189
+ * service accepts at ship (`ship-session.ts` ALLOWED_COMPATIBILITY_FLAGS). We
190
+ * deliberately do NOT recognize narrower flags (`nodejs_als`) or per-module
191
+ * enable flags here: suppressing the warning for a flag the server rejects
192
+ * would pass local bundling only to fail at ship with `bundle-invalid`.
193
+ */
194
+ function warnMissingNodejsCompat(nodeBuiltins, compatibilityFlags, warnings) {
195
+ if (nodeBuiltins.length === 0 || compatibilityFlags.includes('nodejs_compat'))
196
+ return;
197
+ warnings.push(`worker imports node: builtins (${nodeBuiltins.join(', ')}) but compatibilityFlags does not ` +
198
+ `include "nodejs_compat" — they resolve to nothing at runtime on workerd. Add "nodejs_compat" ` +
199
+ `to .yolo/deploy.json compatibilityFlags.`);
200
+ }
98
201
  // ─── Public types ─────────────────────────────────────────────────────────
99
202
  export const DEPLOY_CEILINGS = {
100
203
  /** CF hard per-file limit. */
@@ -106,20 +209,28 @@ export const DEPLOY_CEILINGS = {
106
209
  maxModuleBytes: 10 * 1024 * 1024,
107
210
  /** Gzipped-module size that triggers a warning (not a failure). */
108
211
  warnModuleGzipBytes: 1 * 1024 * 1024,
212
+ /**
213
+ * Sourcemap sidecar cap — mirrors the server's FINALIZE_SOURCEMAPS_MAX_BYTES
214
+ * (common-api `routes/deploy.ts`). Over this we DROP the map (+ warn) rather
215
+ * than fail the deploy or 413 late at finalize — symbolication is optional.
216
+ */
217
+ maxSourceMapBytes: 40 * 1024 * 1024,
109
218
  };
110
- // ─── Public entry ─────────────────────────────────────────────────────────
111
- export async function bundleProject(shape, cwd, ceilings = {}) {
219
+ export async function bundleProject(shape, cwd, ceilings = {}, options = {}) {
112
220
  const caps = { ...DEPLOY_CEILINGS, ...definedOnly(ceilings) };
113
221
  const warnings = [];
222
+ const compatibilityFlags = options.compatibilityFlags ?? [];
114
223
  // ── Worker module (esbuild, or as-is for pre-built entries) ────────────
115
224
  let module = null;
116
225
  let moduleSource = null;
226
+ let sourceMap = null;
117
227
  if (shape.type === 'worker') {
118
- const built = await buildWorkerModule(shape.entry, cwd, shape.prebuilt === true, caps, warnings);
228
+ const built = await buildWorkerModule(shape.entry, cwd, shape.prebuilt === true, caps, warnings, compatibilityFlags, options.sourcemaps === true);
119
229
  if (!built.ok)
120
230
  return built;
121
231
  module = built.module;
122
232
  moduleSource = built.source;
233
+ sourceMap = built.sourceMap ?? null;
123
234
  }
124
235
  // ── Asset walk + manifest + ceilings ────────────────────────────────────
125
236
  const manifest = {};
@@ -195,6 +306,7 @@ export async function bundleProject(shape, cwd, ceilings = {}) {
195
306
  module,
196
307
  workerModules: module === null ? [] : [module],
197
308
  moduleSource,
309
+ sourceMap, // sidecar — intentionally excluded from workerModules + the digest below
198
310
  fileCount,
199
311
  totalAssetBytes,
200
312
  bundleDigest: computeBundleDigest(module === null ? [] : [module], manifest),
@@ -228,11 +340,68 @@ export function computeBundleDigest(modules, manifest) {
228
340
  hash.update(JSON.stringify(entries), 'utf8');
229
341
  return `sha256:${hash.digest('hex')}`;
230
342
  }
231
- async function buildWorkerModule(entry, cwd, prebuilt, caps, warnings) {
343
+ // ─── Internals ────────────────────────────────────────────────────────────
344
+ /**
345
+ * The distinct `node:` builtin specifiers esbuild left external for this
346
+ * bundle (deduped, sorted). Empty when the Worker imports none. Used to warn
347
+ * when `nodejs_compat` is absent — the runtime, not the bundler, is where a
348
+ * missing flag bites.
349
+ */
350
+ function collectExternalNodeBuiltins(metafile) {
351
+ if (!metafile)
352
+ return [];
353
+ const found = new Set();
354
+ for (const input of Object.values(metafile.inputs)) {
355
+ for (const imp of input.imports) {
356
+ if (imp.external && imp.path.startsWith('node:'))
357
+ found.add(imp.path);
358
+ }
359
+ }
360
+ return [...found].sort();
361
+ }
362
+ /**
363
+ * Ensure the sourcemap JSON carries a `file` field naming the module it maps
364
+ * (`index.js`) — CF associates a map to its module by this field (verified live)
365
+ * and esbuild omits it. Returns the map text unchanged if it isn't parseable
366
+ * JSON (defensive; the map still ships, just possibly un-symbolicated).
367
+ */
368
+ function withMapFile(mapText, moduleName) {
369
+ try {
370
+ const parsed = JSON.parse(mapText);
371
+ if (parsed.file === moduleName)
372
+ return mapText;
373
+ parsed.file = moduleName;
374
+ return JSON.stringify(parsed);
375
+ }
376
+ catch {
377
+ return mapText;
378
+ }
379
+ }
380
+ /**
381
+ * The distinct `node:` builtins loaded via a CommonJS `require()` (esbuild
382
+ * import kind `require-call`) in this bundle. esbuild compiles these to
383
+ * `__require(...)`, which throws in an ESM Worker unless the call is guarded by
384
+ * try/catch — so we WARN (not fail), preserving the guarded optional-dependency
385
+ * pattern. Deduped, sorted.
386
+ */
387
+ function collectExternalNodeRequires(metafile) {
388
+ if (!metafile)
389
+ return [];
390
+ const found = new Set();
391
+ for (const input of Object.values(metafile.inputs)) {
392
+ for (const imp of input.imports) {
393
+ if (imp.external && imp.kind === 'require-call' && imp.path.startsWith('node:'))
394
+ found.add(imp.path);
395
+ }
396
+ }
397
+ return [...found].sort();
398
+ }
399
+ async function buildWorkerModule(entry, cwd, prebuilt, caps, warnings, compatibilityFlags, sourcemaps) {
232
400
  const entryAbs = path.resolve(cwd, entry);
233
401
  let contents;
234
402
  let name;
235
403
  let source;
404
+ let sourceMap;
236
405
  // Ship as-is ONLY for an explicitly-configured built output (deploy.json
237
406
  // worker.entry → .js/.mjs). Auto-detected `src/index.js` is SOURCE and must
238
407
  // be bundled or its imports are dropped (codex P2 r6).
@@ -250,6 +419,28 @@ async function buildWorkerModule(entry, cwd, prebuilt, caps, warnings) {
250
419
  }
251
420
  name = path.basename(entryAbs);
252
421
  source = 'prebuilt';
422
+ // esbuild never runs for prebuilt output (vinext/OpenNext), so its define +
423
+ // node: externalization can't apply — scan the shipped text directly and
424
+ // WARN instead. Mutating an opaque framework bundle would break the
425
+ // ship-as-is contract; the fix belongs in the framework build.
426
+ const prebuiltText = Buffer.from(contents).toString('utf8');
427
+ warnMissingNodejsCompat(collectNodeBuiltinsFromText(prebuiltText), compatibilityFlags, warnings);
428
+ // A require()/__require() of a node: builtin throws in an ESM Worker no
429
+ // matter what nodejs_compat is — the esbuild path rejects it, so warn here
430
+ // independently of the missing-compat warning above (which nodejs_compat
431
+ // suppresses). The framework build should emit ESM imports instead.
432
+ const nodeRequires = collectNodeRequireCalls(prebuiltText);
433
+ if (nodeRequires.length > 0) {
434
+ warnings.push(`prebuilt worker uses require() of node: builtins (${nodeRequires.join(', ')}) — a CommonJS ` +
435
+ `require of a builtin throws in an ESM Worker. Rebuild it to emit ESM \`import\`s.`);
436
+ }
437
+ if (prebuiltText.includes('process.env.NODE_ENV')) {
438
+ // A pinned build would have replaced this literal with "production"; its
439
+ // survival means NODE_ENV is unpinned → risks shipping a dev build.
440
+ warnings.push(`prebuilt worker references process.env.NODE_ENV — workerd has no runtime process.env, so an ` +
441
+ `unpinned NODE_ENV can ship a dev build (e.g. development React). Pin it in your framework ` +
442
+ `build (esbuild define 'process.env.NODE_ENV'='"production"').`);
443
+ }
253
444
  }
254
445
  else {
255
446
  // Lazy-load so non-deploy verbs never pay esbuild's startup cost.
@@ -268,9 +459,23 @@ async function buildWorkerModule(entry, cwd, prebuilt, caps, warnings) {
268
459
  target: 'es2022',
269
460
  write: false,
270
461
  minify: true,
462
+ metafile: true,
463
+ // Pin production so libraries that gate on process.env.NODE_ENV (React
464
+ // et al.) never emit their dev build — workerd has no runtime
465
+ // process.env, so an unpinned NODE_ENV silently ships dev code.
466
+ define: { 'process.env.NODE_ENV': '"production"' },
271
467
  absWorkingDir: path.resolve(cwd),
272
468
  logLevel: 'silent',
273
- plugins: flexdbPlugin ? [flexdbPlugin] : [],
469
+ // sourcemaps: 'linked' adds a `//# sourceMappingURL=index.js.map`
470
+ // comment (which CF uses to associate the uploaded map) + emits the
471
+ // .map as a second output. A fixed outfile makes that comment's name
472
+ // deterministic so it matches the uploaded sidecar. OFF → the exact
473
+ // prior options → byte-identical module → stable digest.
474
+ ...(sourcemaps ? { sourcemap: 'linked', outfile: path.resolve(cwd, 'index.js') } : {}),
475
+ // nodeBuiltinExternalPlugin leaves real node: builtins external
476
+ // (nodejs_compat serves them); only a non-builtin misspelling fails the
477
+ // build. Ordered first so it wins over default resolve.
478
+ plugins: [nodeBuiltinExternalPlugin(), ...(flexdbPlugin ? [flexdbPlugin] : [])],
274
479
  });
275
480
  }
276
481
  catch (err) {
@@ -281,13 +486,45 @@ async function buildWorkerModule(entry, cwd, prebuilt, caps, warnings) {
281
486
  message: `esbuild failed for ${entry}: ${msg}`,
282
487
  };
283
488
  }
284
- const out = result.outputFiles?.[0];
489
+ const outputs = result.outputFiles ?? [];
490
+ // The module is the non-.map output; the .map (present only with sourcemaps)
491
+ // is the sidecar.
492
+ const out = outputs.find((o) => !o.path.endsWith('.map'));
493
+ const mapOut = outputs.find((o) => o.path.endsWith('.map'));
285
494
  if (out === undefined) {
286
495
  return { ok: false, kind: 'build-failed', message: `esbuild produced no output for ${entry}` };
287
496
  }
497
+ // node: builtins were left external above; if the Worker actually imports
498
+ // any and nodejs_compat isn't enabled, they resolve to nothing at runtime.
499
+ warnMissingNodejsCompat(collectExternalNodeBuiltins(result.metafile), compatibilityFlags, warnings);
500
+ // A require()-kind load of a builtin becomes __require(...), which throws in
501
+ // an ESM Worker unless guarded — advisory (guarded probes stay valid).
502
+ const nodeRequires = collectExternalNodeRequires(result.metafile);
503
+ if (nodeRequires.length > 0) {
504
+ warnings.push(`worker loads node: builtins via require() (${nodeRequires.join(', ')}) — require() throws in an ` +
505
+ `ESM Worker unless wrapped in try/catch. Prefer an ESM \`import\`.`);
506
+ }
288
507
  contents = out.contents;
289
508
  name = 'index.js';
290
509
  source = 'esbuild';
510
+ if (sourcemaps && mapOut !== undefined) {
511
+ // Name matches the `//# sourceMappingURL=index.js.map` comment esbuild
512
+ // wrote into the module (deterministic via the fixed outfile).
513
+ // CF associates the sourcemap to the module by the map's `file` field —
514
+ // verified against the live account: esbuild OMITS `file`, and without it
515
+ // CF returns minified exception stacks; adding `file` = the module name
516
+ // makes it symbolicate. (wrangler's map carries `file` too.)
517
+ const content = withMapFile(Buffer.from(mapOut.contents).toString('utf8'), name);
518
+ if (Buffer.byteLength(content, 'utf8') > caps.maxSourceMapBytes) {
519
+ // Too big to upload — drop it (the module is valid) so the deploy still
520
+ // ships, just without symbolicated stacks. Better than a late 413.
521
+ warnings.push(`sourcemap is ${formatBytes(Buffer.byteLength(content, 'utf8'))} (> ${formatBytes(caps.maxSourceMapBytes)}) — ` +
522
+ `skipping it; exceptions in deploy.logs won't be source-mapped for this release`);
523
+ }
524
+ else {
525
+ sourceMap = { name: 'index.js.map', content };
526
+ }
527
+ }
291
528
  }
292
529
  if (contents.byteLength > caps.maxModuleBytes) {
293
530
  return {
@@ -301,7 +538,7 @@ async function buildWorkerModule(entry, cwd, prebuilt, caps, warnings) {
301
538
  if (gzipBytes > caps.warnModuleGzipBytes) {
302
539
  warnings.push(`worker module is ${formatBytes(gzipBytes)} gzipped (> ${formatBytes(caps.warnModuleGzipBytes)}) — cold starts will suffer`);
303
540
  }
304
- return { ok: true, module: { name, contents }, source };
541
+ return { ok: true, module: { name, contents }, source, ...(sourceMap ? { sourceMap } : {}) };
305
542
  }
306
543
  /**
307
544
  * Depth-first walk returning sorted posix-relative file paths. Skips