@autter/runtime-cli 1.0.0 → 1.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/vite.cjs CHANGED
@@ -24,40 +24,11 @@ __export(vite_exports, {
24
24
  default: () => vite_default
25
25
  });
26
26
  module.exports = __toCommonJS(vite_exports);
27
- var import_node_path2 = require("path");
28
-
29
- // src/inject.ts
30
- var import_promises2 = require("fs/promises");
27
+ var import_node_path3 = require("path");
31
28
 
32
- // src/debug-id.ts
33
- var import_node_crypto = require("crypto");
34
- var DEBUG_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
35
- function normalizeDebugId(value) {
36
- if (typeof value !== "string") return null;
37
- const id = value.trim().toLowerCase();
38
- return DEBUG_ID_RE.test(id) ? id : null;
39
- }
40
- function debugIdFor(bytes) {
41
- const hash = (0, import_node_crypto.createHash)("sha256").update(bytes).digest();
42
- hash[6] = hash[6] & 15 | 64;
43
- hash[8] = hash[8] & 63 | 128;
44
- const hex = hash.subarray(0, 16).toString("hex");
45
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
46
- }
47
- var DEBUG_ID_COMMENT_RE = /^\/\/# debugId=([0-9a-fA-F-]{36})[ \t]*\r?$/gm;
48
- function readDebugIdComment(code) {
49
- let found = null;
50
- for (const match of code.matchAll(DEBUG_ID_COMMENT_RE)) found = normalizeDebugId(match[1]) ?? found;
51
- return found;
52
- }
53
- var DEBUG_ID_REGISTRY = "_autterDebugIds";
54
- function debugIdSnippet(id) {
55
- return `;!function(){try{var g="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},s=(new g.Error).stack;s&&((g.${DEBUG_ID_REGISTRY}=g.${DEBUG_ID_REGISTRY}||{})[s]="${id}")}catch(e){}}();`;
56
- }
57
- var SNIPPET_RE = /\(g\._autterDebugIds=g\._autterDebugIds\|\|\{\}\)\[s\]="[0-9a-f]{8}-/;
58
- function hasDebugIdSnippet(code) {
59
- return SNIPPET_RE.test(code);
60
- }
29
+ // src/build.ts
30
+ var import_node_fs2 = require("fs");
31
+ var import_node_path2 = require("path");
61
32
 
62
33
  // src/files.ts
63
34
  var import_node_fs = require("fs");
@@ -97,7 +68,7 @@ function mapPathFor(js, code) {
97
68
  const sibling = `${js}.map`;
98
69
  return (0, import_node_fs.existsSync)(sibling) ? sibling : null;
99
70
  }
100
- async function walk(dir, out) {
71
+ async function walk(dir, out, pattern = BUNDLE_RE) {
101
72
  let entries;
102
73
  try {
103
74
  entries = await (0, import_promises.readdir)(dir, { withFileTypes: true });
@@ -107,9 +78,46 @@ async function walk(dir, out) {
107
78
  for (const entry of entries) {
108
79
  if (entry.name === "node_modules") continue;
109
80
  const full = (0, import_node_path.join)(dir, entry.name);
110
- if (entry.isDirectory()) await walk(full, out);
111
- else if (entry.isFile() && BUNDLE_RE.test(entry.name)) out.push(full);
81
+ if (entry.isDirectory()) await walk(full, out, pattern);
82
+ else if (entry.isFile() && pattern.test(entry.name)) out.push(full);
83
+ }
84
+ }
85
+ var CSS_SOURCE_MAPPING_URL_RE = /\/\*[#@] sourceMappingURL=([^\s*]+)\s*\*\/\s*$/;
86
+ function pointsAt(file, url, map) {
87
+ if (!url || /^[a-z][\w+.-]*:/i.test(url) || url.startsWith("/")) return false;
88
+ let path = url.split(/[?#]/)[0];
89
+ try {
90
+ path = decodeURIComponent(path);
91
+ } catch {
112
92
  }
93
+ return (0, import_node_path.resolve)((0, import_node_path.dirname)(file), path) === map;
94
+ }
95
+ async function stripReference(file, map) {
96
+ let code;
97
+ try {
98
+ code = await (0, import_promises.readFile)(file, "utf8");
99
+ } catch {
100
+ return;
101
+ }
102
+ let stripped = code;
103
+ if (BUNDLE_RE.test(file)) {
104
+ if (pointsAt(file, readSourceMappingUrl(code), map)) stripped = stripSourceMappingUrl(code);
105
+ } else if (file.endsWith(".css")) {
106
+ const match = CSS_SOURCE_MAPPING_URL_RE.exec(code);
107
+ if (match && pointsAt(file, match[1], map)) stripped = code.slice(0, match.index).replace(/\n?$/, "\n");
108
+ }
109
+ if (stripped !== code) await (0, import_promises.writeFile)(file, stripped);
110
+ }
111
+ async function removeSourceMaps(maps, owners = /* @__PURE__ */ new Map()) {
112
+ const removed = [];
113
+ for (const map of [...new Set(maps)].sort()) {
114
+ if (!(0, import_node_fs.existsSync)(map)) continue;
115
+ await (0, import_promises.rm)(map, { force: true });
116
+ removed.push(map);
117
+ const owner = owners.get(map) ?? map.replace(/\.map$/, "");
118
+ await stripReference(owner, map);
119
+ }
120
+ return removed;
113
121
  }
114
122
  async function findBundles(dir, files) {
115
123
  const root = (0, import_node_path.resolve)(dir);
@@ -133,6 +141,39 @@ async function findBundles(dir, files) {
133
141
  return bundles;
134
142
  }
135
143
 
144
+ // src/inject.ts
145
+ var import_promises2 = require("fs/promises");
146
+
147
+ // src/debug-id.ts
148
+ var import_node_crypto = require("crypto");
149
+ var DEBUG_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
150
+ function normalizeDebugId(value) {
151
+ if (typeof value !== "string") return null;
152
+ const id = value.trim().toLowerCase();
153
+ return DEBUG_ID_RE.test(id) ? id : null;
154
+ }
155
+ function debugIdFor(bytes) {
156
+ const hash = (0, import_node_crypto.createHash)("sha256").update(bytes).digest();
157
+ hash[6] = hash[6] & 15 | 64;
158
+ hash[8] = hash[8] & 63 | 128;
159
+ const hex = hash.subarray(0, 16).toString("hex");
160
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
161
+ }
162
+ var DEBUG_ID_COMMENT_RE = /^\/\/# debugId=([0-9a-fA-F-]{36})[ \t]*\r?$/gm;
163
+ function readDebugIdComment(code) {
164
+ let found = null;
165
+ for (const match of code.matchAll(DEBUG_ID_COMMENT_RE)) found = normalizeDebugId(match[1]) ?? found;
166
+ return found;
167
+ }
168
+ var DEBUG_ID_REGISTRY = "_autterDebugIds";
169
+ function debugIdSnippet(id) {
170
+ return `;!function(){try{var g="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},s=(new g.Error).stack;s&&((g.${DEBUG_ID_REGISTRY}=g.${DEBUG_ID_REGISTRY}||{})[s]="${id}")}catch(e){}}();`;
171
+ }
172
+ var SNIPPET_RE = /\(g\._autterDebugIds=g\._autterDebugIds\|\|\{\}\)\[s\]="[0-9a-f]{8}-/;
173
+ function hasDebugIdSnippet(code) {
174
+ return SNIPPET_RE.test(code);
175
+ }
176
+
136
177
  // src/inject.ts
137
178
  var SNIPPET_LINE_KEY = "x_autter_snippet_line";
138
179
  function snippetLine(code) {
@@ -235,6 +276,8 @@ async function injectDir(dir, options = {}) {
235
276
  // src/upload.ts
236
277
  var import_node_crypto2 = require("crypto");
237
278
  var import_promises3 = require("fs/promises");
279
+ var import_node_util = require("util");
280
+ var import_node_zlib = require("zlib");
238
281
 
239
282
  // src/release.ts
240
283
  var import_node_child_process = require("child_process");
@@ -280,9 +323,385 @@ function resolveRelease(explicit, env = process.env, cwd = process.cwd()) {
280
323
  );
281
324
  }
282
325
 
326
+ // src/scopes.ts
327
+ var import_acorn = require("acorn");
328
+ var SCOPES_KEY = "x_autter_scopes";
329
+ var SCOPES_VERSION = 1;
330
+ var BASE_OPTIONS = {
331
+ ecmaVersion: "latest",
332
+ allowHashBang: true,
333
+ allowReturnOutsideFunction: true,
334
+ allowReserved: true
335
+ };
336
+ function parseBundle(code) {
337
+ try {
338
+ return (0, import_acorn.parse)(code, {
339
+ ...BASE_OPTIONS,
340
+ sourceType: "module",
341
+ allowAwaitOutsideFunction: true,
342
+ allowImportExportEverywhere: true
343
+ });
344
+ } catch (moduleError) {
345
+ try {
346
+ return (0, import_acorn.parse)(code, { ...BASE_OPTIONS, sourceType: "script" });
347
+ } catch (scriptError) {
348
+ const pos = (err) => typeof err.pos === "number" ? err.pos : -1;
349
+ throw pos(scriptError) > pos(moduleError) ? scriptError : moduleError;
350
+ }
351
+ }
352
+ }
353
+ function isNode(value) {
354
+ return typeof value === "object" && value !== null && typeof value.type === "string";
355
+ }
356
+ var IDENTIFIER_NAME_RE = /^[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*$/u;
357
+ function identifierToken(node) {
358
+ if (!isNode(node)) return null;
359
+ if (node.type === "Identifier") return { offset: node.start, name: node.name, literal: false };
360
+ if (node.type === "PrivateIdentifier") return { offset: node.start, name: `#${node.name}`, literal: false };
361
+ return null;
362
+ }
363
+ function literalToken(node) {
364
+ if (!isNode(node) || node.type !== "Literal" || typeof node.value !== "string") return null;
365
+ return IDENTIFIER_NAME_RE.test(node.value) ? { offset: node.start, name: node.value, literal: true } : null;
366
+ }
367
+ function keyToken(property) {
368
+ if (!property.computed) {
369
+ const id = identifierToken(property.key);
370
+ if (id) return id;
371
+ }
372
+ return literalToken(property.key);
373
+ }
374
+ function bindingToken(target) {
375
+ if (!isNode(target)) return null;
376
+ if (target.type === "Identifier") return identifierToken(target);
377
+ if (target.type === "MemberExpression") {
378
+ return target.computed ? literalToken(target.property) : identifierToken(target.property);
379
+ }
380
+ return null;
381
+ }
382
+ function contextTokens(node, parent) {
383
+ let token = null;
384
+ switch (parent?.type) {
385
+ case "VariableDeclarator":
386
+ if (parent.init === node) token = bindingToken(parent.id);
387
+ break;
388
+ case "AssignmentExpression":
389
+ case "AssignmentPattern":
390
+ if (parent.right === node) token = bindingToken(parent.left);
391
+ break;
392
+ case "Property":
393
+ case "PropertyDefinition":
394
+ case "MethodDefinition":
395
+ if (parent.value === node) token = keyToken(parent);
396
+ break;
397
+ }
398
+ return token ? [token] : [];
399
+ }
400
+ function classTokens(path) {
401
+ if (!path || path.node.type !== "ClassDeclaration" && path.node.type !== "ClassExpression") return [];
402
+ const own = identifierToken(path.node.id);
403
+ return [...own ? [own] : [], ...contextTokens(path.node, path.parent?.node)];
404
+ }
405
+ function describe(path) {
406
+ const fn = path.node;
407
+ const parent = path.parent?.node;
408
+ const own = identifierToken(fn.id);
409
+ const isMethod = parent?.type === "MethodDefinition" || parent?.type === "Property" && parent.value === fn && (parent.method === true || parent.kind !== "init");
410
+ let context;
411
+ if (parent?.type === "MethodDefinition" && parent.kind === "constructor") {
412
+ context = classTokens(path.parent?.parent?.parent ?? null);
413
+ } else {
414
+ context = contextTokens(fn, parent);
415
+ }
416
+ return {
417
+ start: fn.start,
418
+ end: fn.end,
419
+ own,
420
+ recoverAt: !own && fn.type !== "ArrowFunctionExpression" && !isMethod ? fn.start : null,
421
+ context
422
+ };
423
+ }
424
+ var FUNCTION_TYPES = /* @__PURE__ */ new Set(["FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression"]);
425
+ function classInitializer(path) {
426
+ const node = path.node;
427
+ let range = null;
428
+ if (node.type === "StaticBlock") range = node;
429
+ else if (node.type === "PropertyDefinition" && isNode(node.value) && !FUNCTION_TYPES.has(node.value.type)) range = node.value;
430
+ if (!range) return null;
431
+ return { start: range.start, end: range.end, own: null, recoverAt: null, context: classTokens(path.parent?.parent ?? null) };
432
+ }
433
+ function collectFunctions(program) {
434
+ const found = [];
435
+ const stack = [{ node: program, parent: null }];
436
+ for (let path = stack.pop(); path; path = stack.pop()) {
437
+ const node = path.node;
438
+ if (FUNCTION_TYPES.has(node.type)) found.push(describe(path));
439
+ else {
440
+ const initializer = classInitializer(path);
441
+ if (initializer) found.push(initializer);
442
+ }
443
+ for (const key in node) {
444
+ const value = node[key];
445
+ if (Array.isArray(value)) {
446
+ for (let i = value.length - 1; i >= 0; i--) if (isNode(value[i])) stack.push({ node: value[i], parent: path });
447
+ } else if (isNode(value)) {
448
+ stack.push({ node: value, parent: path });
449
+ }
450
+ }
451
+ }
452
+ return found;
453
+ }
454
+ function lineStarts(code) {
455
+ const starts = [0];
456
+ for (let i = 0; i < code.length; i++) {
457
+ const c = code.charCodeAt(i);
458
+ if (c === 10 || c === 8232 || c === 8233) starts.push(i + 1);
459
+ else if (c === 13) {
460
+ if (code.charCodeAt(i + 1) === 10) i++;
461
+ starts.push(i + 1);
462
+ }
463
+ }
464
+ return starts;
465
+ }
466
+ function positionOf(starts, offset) {
467
+ let lo = 0;
468
+ let hi = starts.length - 1;
469
+ while (lo < hi) {
470
+ const mid = lo + hi + 1 >> 1;
471
+ if (starts[mid] <= offset) lo = mid;
472
+ else hi = mid - 1;
473
+ }
474
+ return [lo, offset - starts[lo]];
475
+ }
476
+ var BASE64 = new Int8Array(128).fill(-1);
477
+ for (const [i, ch] of [..."ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"].entries()) BASE64[ch.charCodeAt(0)] = i;
478
+ function findSegments(mappings, wanted) {
479
+ let line = 0;
480
+ let column = 0;
481
+ let source = 0;
482
+ let originalLine = 0;
483
+ let originalColumn = 0;
484
+ let name = 0;
485
+ let want = wanted.get(0);
486
+ const fields = [0, 0, 0, 0, 0];
487
+ let i = 0;
488
+ while (i < mappings.length) {
489
+ const ch = mappings.charCodeAt(i);
490
+ if (ch === 59) {
491
+ line++;
492
+ column = 0;
493
+ want = wanted.get(line);
494
+ i++;
495
+ continue;
496
+ }
497
+ if (ch === 44) {
498
+ i++;
499
+ continue;
500
+ }
501
+ let count = 0;
502
+ while (i < mappings.length) {
503
+ const next = mappings.charCodeAt(i);
504
+ if (next === 44 || next === 59) break;
505
+ let value = 0;
506
+ let shift = 0;
507
+ let digit;
508
+ do {
509
+ const code = mappings.charCodeAt(i++);
510
+ digit = code < 128 ? BASE64[code] : -1;
511
+ if (digit < 0 || shift > 30) throw new Error("invalid mappings");
512
+ value |= (digit & 31) << shift;
513
+ shift += 5;
514
+ } while (digit & 32);
515
+ const decoded = value & 1 ? -(value >>> 1) : value >>> 1;
516
+ if (count < 5) fields[count] = decoded;
517
+ count++;
518
+ }
519
+ column += fields[0];
520
+ if (count >= 4) {
521
+ source += fields[1];
522
+ originalLine += fields[2];
523
+ originalColumn += fields[3];
524
+ }
525
+ if (count >= 5) name += fields[4];
526
+ if (want && want.get(column) === null) {
527
+ want.set(column, {
528
+ source: count >= 4 ? source : -1,
529
+ line: originalLine,
530
+ column: originalColumn,
531
+ name: count >= 5 ? name : -1
532
+ });
533
+ }
534
+ }
535
+ }
536
+ function looksMangled(name) {
537
+ return name.replace(/^#/, "").length <= 2;
538
+ }
539
+ var IDENTIFIER_AT_RE = /[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*/uy;
540
+ var OWN_NAME_AT_RE = /(?:async\s+)?function\b\s*\*?\s*([$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*)/uy;
541
+ var NOT_A_NAME = new Set(
542
+ "abstract async await break case catch class const continue debugger declare default delete do else enum export extends false finally for function get if implements import in instanceof interface let new null of override package private protected public readonly return set static super switch this throw true try typeof var void while with yield".split(" ")
543
+ );
544
+ var NameResolver = class {
545
+ constructor(map, segmentAt) {
546
+ this.segmentAt = segmentAt;
547
+ this.names = Array.isArray(map.names) ? map.names : [];
548
+ this.sourcesContent = Array.isArray(map.sourcesContent) ? map.sourcesContent : [];
549
+ }
550
+ segmentAt;
551
+ names;
552
+ sourcesContent;
553
+ sourceLines = /* @__PURE__ */ new Map();
554
+ originalLine(segment) {
555
+ if (segment.source < 0) return null;
556
+ let lines = this.sourceLines.get(segment.source);
557
+ if (lines === void 0) {
558
+ const content = this.sourcesContent[segment.source];
559
+ lines = typeof content === "string" ? content.split(/\r\n|[\n\r\u2028\u2029]/) : null;
560
+ this.sourceLines.set(segment.source, lines);
561
+ }
562
+ return lines?.[segment.line] ?? null;
563
+ }
564
+ /** The original identifier at a segment's source position. */
565
+ identifierAt(segment, re, group = 0) {
566
+ const text = this.originalLine(segment);
567
+ if (text === null) return null;
568
+ re.lastIndex = segment.column;
569
+ const found = re.exec(text)?.[group];
570
+ return found && !NOT_A_NAME.has(found) ? found : null;
571
+ }
572
+ /** Original name of a token: the map's `names` at its exact position;
573
+ * else the generated name when it isn't mangled; else the identifier
574
+ * at the mapped position in `sourcesContent`. Null when unknown. */
575
+ resolve(token) {
576
+ if (token.literal) return token.name;
577
+ const segment = this.segmentAt(token.offset);
578
+ if (segment && segment.name >= 0) {
579
+ const name = this.names[segment.name];
580
+ if (typeof name === "string" && name) return name;
581
+ }
582
+ if (!looksMangled(token.name)) return token.name;
583
+ return segment ? this.identifierAt(segment, IDENTIFIER_AT_RE) : null;
584
+ }
585
+ /** The name a minifier removed from `function name() {}`, read from the
586
+ * original source at the function's mapped start. */
587
+ recover(offset) {
588
+ const segment = this.segmentAt(offset);
589
+ return segment ? this.identifierAt(segment, OWN_NAME_AT_RE, 1) : null;
590
+ }
591
+ };
592
+ var BASE64_DIGITS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
593
+ function vlq(value) {
594
+ let rest = value < 0 ? -value << 1 | 1 : value << 1;
595
+ let out = "";
596
+ do {
597
+ let digit = rest & 31;
598
+ rest >>>= 5;
599
+ if (rest > 0) digit |= 32;
600
+ out += BASE64_DIGITS[digit];
601
+ } while (rest > 0);
602
+ return out;
603
+ }
604
+ function encodeScopes(entries) {
605
+ const parts = [];
606
+ let line = 0;
607
+ let previousStart = 0;
608
+ let previousName = 0;
609
+ let firstOnLine = true;
610
+ for (const [startLine, startColumn, endLine, endColumn, nameIndex] of entries) {
611
+ if (startLine > line) {
612
+ parts.push(";".repeat(startLine - line));
613
+ line = startLine;
614
+ previousStart = 0;
615
+ firstOnLine = true;
616
+ }
617
+ if (!firstOnLine) parts.push(",");
618
+ firstOnLine = false;
619
+ let segment = vlq(startColumn - previousStart) + vlq(endLine - startLine) + vlq(endLine === startLine ? endColumn - startColumn : endColumn);
620
+ previousStart = startColumn;
621
+ if (nameIndex >= 0) {
622
+ segment += vlq(nameIndex - previousName);
623
+ previousName = nameIndex;
624
+ }
625
+ parts.push(segment);
626
+ }
627
+ return parts.join("");
628
+ }
629
+ function computeScopes(code, map) {
630
+ try {
631
+ return scopesOf(code, map);
632
+ } catch (err) {
633
+ return { error: err instanceof Error ? err.message : String(err) };
634
+ }
635
+ }
636
+ function scopesOf(code, map) {
637
+ if (typeof map.mappings !== "string") return { error: "the map has no mappings string" };
638
+ let functions;
639
+ try {
640
+ functions = collectFunctions(parseBundle(code));
641
+ } catch (err) {
642
+ return { error: `could not parse the bundle: ${err instanceof Error ? err.message : String(err)}` };
643
+ }
644
+ const starts = lineStarts(code);
645
+ const wanted = /* @__PURE__ */ new Map();
646
+ const want = (offset) => {
647
+ const [line, column] = positionOf(starts, offset);
648
+ let columns = wanted.get(line);
649
+ if (!columns) wanted.set(line, columns = /* @__PURE__ */ new Map());
650
+ columns.set(column, null);
651
+ };
652
+ for (const fn of functions) {
653
+ if (fn.own && !fn.own.literal) want(fn.own.offset);
654
+ if (fn.recoverAt !== null) want(fn.recoverAt);
655
+ for (const token of fn.context) if (!token.literal) want(token.offset);
656
+ }
657
+ try {
658
+ findSegments(map.mappings, wanted);
659
+ } catch (err) {
660
+ return { error: `could not read the map: ${err instanceof Error ? err.message : String(err)}` };
661
+ }
662
+ const resolver = new NameResolver(map, (offset) => {
663
+ const [line, column] = positionOf(starts, offset);
664
+ return wanted.get(line)?.get(column) ?? null;
665
+ });
666
+ functions.sort((a, b) => a.start - b.start || b.end - a.end);
667
+ const mapNames = Array.isArray(map.names) ? map.names : [];
668
+ const nameIndex = /* @__PURE__ */ new Map();
669
+ mapNames.forEach((name, index) => {
670
+ if (typeof name === "string" && !nameIndex.has(name)) nameIndex.set(name, index);
671
+ });
672
+ const extraNames = [];
673
+ const indexOf = (name) => {
674
+ let index = nameIndex.get(name);
675
+ if (index === void 0) {
676
+ index = mapNames.length + extraNames.push(name) - 1;
677
+ nameIndex.set(name, index);
678
+ }
679
+ return index;
680
+ };
681
+ const entries = functions.map((fn) => {
682
+ let name = fn.own ? resolver.resolve(fn.own) : null;
683
+ if (name === null && fn.recoverAt !== null) name = resolver.recover(fn.recoverAt);
684
+ for (const token of fn.context) {
685
+ if (name !== null) break;
686
+ name = resolver.resolve(token);
687
+ }
688
+ const index = name !== null ? indexOf(name) : fn.own || fn.context.length > 0 ? indexOf(null) : -1;
689
+ const [startLine, startColumn] = positionOf(starts, fn.start);
690
+ const [endLine, endColumn] = positionOf(starts, fn.end);
691
+ return [startLine, startColumn, endLine, endColumn, index];
692
+ });
693
+ return { scopes: { version: SCOPES_VERSION, names: extraNames, scopes: encodeScopes(entries) } };
694
+ }
695
+
283
696
  // src/upload.ts
284
697
  var DEFAULT_ENDPOINT = "https://otlp.autter.dev";
285
- var MAX_UPLOAD_BYTES = 5 * 1024 * 1024;
698
+ var MAX_MAP_CHARS = 32 * 1024 * 1024;
699
+ var MAX_UPLOAD_BYTES = MAX_MAP_CHARS + 1024 * 1024;
700
+ var LEGACY_MAX_BYTES = 5 * 1024 * 1024;
701
+ var UPLOAD_KEY_PREFIX = "autter_rtu_";
702
+ var CLIENT_KEY_PREFIX = "autter_rtc_";
703
+ var KEY_ADVICE = "set AUTTER_RUNTIME_KEY to an upload-only key (autter_rtu_\u2026, recommended for CI: it can only upload source maps) or the full server key (autter_rt_\u2026, also works)";
704
+ var gzip = (0, import_node_util.promisify)(import_node_zlib.gzip);
286
705
  var CHECK_BATCH = 500;
287
706
  var MAX_ATTEMPTS = 3;
288
707
  function resolveEndpoint(flag, env = process.env) {
@@ -299,7 +718,16 @@ function storedMapJson(map) {
299
718
  const { sourcesContent: _omitted, ...safe } = map;
300
719
  return JSON.stringify(safe);
301
720
  }
302
- async function prepare(bundle, urlPrefix, release) {
721
+ function bytesOf(buffer) {
722
+ return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
723
+ }
724
+ function fits(json, body) {
725
+ return json.length <= MAX_MAP_CHARS && Buffer.byteLength(body) <= MAX_UPLOAD_BYTES;
726
+ }
727
+ function uploadBody(release, filename, debugId, json) {
728
+ return `{"release":${JSON.stringify(release)},"filename":${JSON.stringify(filename)},${debugId ? `"debugId":${JSON.stringify(debugId)},` : ""}"map":${json}}`;
729
+ }
730
+ async function prepare(bundle, urlPrefix, release, log, compress) {
303
731
  let map;
304
732
  try {
305
733
  map = JSON.parse(await (0, import_promises3.readFile)(bundle.map, "utf8"));
@@ -311,17 +739,31 @@ async function prepare(bundle, urlPrefix, release) {
311
739
  }
312
740
  const code = await (0, import_promises3.readFile)(bundle.js, "utf8");
313
741
  const debugId = readDebugIdComment(code) ?? normalizeDebugId(map.debugId);
314
- const json = storedMapJson(map);
315
742
  const filename = servedFilename(urlPrefix, bundle.path);
316
- const body = `{"release":${JSON.stringify(release)},"filename":${JSON.stringify(filename)},${debugId ? `"debugId":${JSON.stringify(debugId)},` : ""}"map":${json}}`;
743
+ const { [SCOPES_KEY]: _stale, ...plain } = map;
744
+ const scopes = computeScopes(code, map);
745
+ let json = storedMapJson(plain);
746
+ if ("scopes" in scopes) {
747
+ const scoped = storedMapJson({ ...plain, [SCOPES_KEY]: scopes.scopes });
748
+ if (fits(scoped, uploadBody(release, filename, debugId, scoped))) json = scoped;
749
+ else if (fits(json, uploadBody(release, filename, debugId, json))) {
750
+ log(`warning: ${bundle.path}: its map is over 32 MB with function scopes, so it is uploaded without them (frames keep call-site names)`);
751
+ }
752
+ } else {
753
+ log(`warning: ${bundle.path}: no function scopes (${scopes.error}); its map is uploaded without them (frames keep call-site names)`);
754
+ }
755
+ const body = uploadBody(release, filename, debugId, json);
317
756
  return {
318
757
  bundle,
319
- body,
758
+ // Maps are text that compresses several times over; the ingester
759
+ // inflates the body (Content-Encoding: gzip).
760
+ body: compress && fits(json, body) ? bytesOf(await gzip(body)) : new Uint8Array(0),
320
761
  path: bundle.path,
321
762
  filename,
322
763
  debugId,
323
764
  hash: (0, import_node_crypto2.createHash)("sha256").update(json).digest("hex"),
324
- bytes: Buffer.byteLength(body)
765
+ bytes: Buffer.byteLength(body),
766
+ mapChars: json.length
325
767
  };
326
768
  }
327
769
  var FatalUploadError = class extends Error {
@@ -349,14 +791,14 @@ async function uploadDir(dir, options = {}) {
349
791
  };
350
792
  const items = [];
351
793
  for (const bundle of await findBundles(dir, options.files)) {
352
- const prepared = await prepare(bundle, options.urlPrefix, release);
794
+ const prepared = await prepare(bundle, options.urlPrefix, release, log, !options.dryRun);
353
795
  if ("error" in prepared) {
354
796
  summary.failed.push({ path: bundle.path, filename: servedFilename(options.urlPrefix, bundle.path), error: prepared.error });
355
- } else if (prepared.bytes > MAX_UPLOAD_BYTES) {
797
+ } else if (prepared.mapChars > MAX_MAP_CHARS || prepared.bytes > MAX_UPLOAD_BYTES) {
356
798
  summary.failed.push({
357
799
  path: prepared.path,
358
800
  filename: prepared.filename,
359
- error: `map is ${(prepared.bytes / 1048576).toFixed(1)} MB without sourcesContent; the ingester accepts up to 5 MB`
801
+ error: `map is ${(prepared.mapChars / 1048576).toFixed(1)} MB without sourcesContent; the ingester accepts up to 32 MB`
360
802
  });
361
803
  } else {
362
804
  items.push(prepared);
@@ -367,11 +809,15 @@ async function uploadDir(dir, options = {}) {
367
809
  return summary;
368
810
  }
369
811
  const key = (options.key ?? env.AUTTER_RUNTIME_KEY ?? "").trim();
370
- if (!key) throw new FatalUploadError("no ingest key: set AUTTER_RUNTIME_KEY to a server key (autter_rt_\u2026)");
371
- if (key.startsWith("autter_rtc_")) {
372
- throw new FatalUploadError("AUTTER_RUNTIME_KEY is a publishable client key (autter_rtc_\u2026); uploads need a server key (autter_rt_\u2026)");
812
+ if (!key) throw new FatalUploadError(`no ingest key: ${KEY_ADVICE}`);
813
+ if (key.startsWith(CLIENT_KEY_PREFIX)) {
814
+ throw new FatalUploadError(`AUTTER_RUNTIME_KEY is a publishable client key (autter_rtc_\u2026), which cannot upload source maps: ${KEY_ADVICE}`);
373
815
  }
816
+ const rejected = (status, detail) => new FatalUploadError(
817
+ `the ingester rejected the key (${status}): ${detail}` + (key.startsWith(UPLOAD_KEY_PREFIX) ? " (upload keys, autter_rtu_\u2026, need ingester 1.7.0 or later; the server key works with any)" : "")
818
+ );
374
819
  const headers = { "content-type": "application/json", authorization: `Bearer ${key}` };
820
+ const uploadHeaders = { ...headers, "content-encoding": "gzip" };
375
821
  const skipped = /* @__PURE__ */ new Set();
376
822
  for (let start = 0; start < items.length && !summary.legacyIngester; start += CHECK_BATCH) {
377
823
  const batch = items.slice(start, start + CHECK_BATCH);
@@ -391,9 +837,7 @@ async function uploadDir(dir, options = {}) {
391
837
  );
392
838
  break;
393
839
  }
394
- if (res.status === 401 || res.status === 403) {
395
- throw new FatalUploadError(`the ingester rejected the key (${res.status}): ${(await res.text()).slice(0, 300)}`);
396
- }
840
+ if (res.status === 401 || res.status === 403) throw rejected(res.status, (await res.text()).slice(0, 300));
397
841
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
398
842
  const body = await res.json();
399
843
  const present = new Set(Array.isArray(body.present) ? body.present : []);
@@ -413,7 +857,7 @@ async function uploadDir(dir, options = {}) {
413
857
  let status = 0;
414
858
  let detail = "";
415
859
  try {
416
- const res = await doFetch(`${endpoint}/v1/sourcemaps`, { method: "POST", headers, body: item.body });
860
+ const res = await doFetch(`${endpoint}/v1/sourcemaps`, { method: "POST", headers: uploadHeaders, body: item.body });
417
861
  status = res.status;
418
862
  if (res.ok) {
419
863
  uploaded.push(item);
@@ -424,12 +868,16 @@ async function uploadDir(dir, options = {}) {
424
868
  detail = err.message;
425
869
  }
426
870
  if (status === 401 || status === 403) {
427
- fatal = new FatalUploadError(`the ingester rejected the key (${status}): ${detail}`);
871
+ fatal = rejected(status, detail);
428
872
  return;
429
873
  }
430
874
  const retryable = status === 0 || status === 429 || status >= 500;
431
875
  if (!retryable || attempt >= MAX_ATTEMPTS) {
432
- summary.failed.push({ path: item.path, filename: item.filename, error: status ? `HTTP ${status}: ${detail}` : detail });
876
+ let error = status ? `HTTP ${status}: ${detail}` : detail;
877
+ if (status === 413 && item.bytes > LEGACY_MAX_BYTES) {
878
+ error += ` (this map is ${(item.bytes / 1048576).toFixed(1)} MB; ingester 1.6.0 and older accept up to 5 MB, newer ones 32 MB)`;
879
+ }
880
+ summary.failed.push({ path: item.path, filename: item.filename, error });
433
881
  return;
434
882
  }
435
883
  await sleep(500 * 2 ** (attempt - 1));
@@ -462,6 +910,18 @@ function strip(item) {
462
910
  }
463
911
 
464
912
  // src/build.ts
913
+ function buildKey(options) {
914
+ const key = (options.key ?? process.env.AUTTER_RUNTIME_KEY ?? "").trim();
915
+ return key || null;
916
+ }
917
+ function shouldGenerateMaps(options) {
918
+ return options.upload === false || Boolean(options.dryRun) || buildKey(options) !== null;
919
+ }
920
+ function logMapsNotGenerated(options) {
921
+ if (!options.silent) {
922
+ console.log("[autter-runtime] AUTTER_RUNTIME_KEY is not set: no source maps generated, nothing uploaded");
923
+ }
924
+ }
465
925
  function formatUploadSummary(summary) {
466
926
  const lines = [];
467
927
  const verb = summary.dryRun ? "would upload" : "uploaded";
@@ -480,46 +940,90 @@ async function processBuildOutput(input) {
480
940
  const log = (line) => {
481
941
  if (!options.silent) console.log(`[autter-runtime] ${line}`);
482
942
  };
483
- const result = { injected: [], upload: null };
943
+ const result = { injected: [], upload: null, removedMaps: [] };
944
+ let outcome = "they were uploaded";
945
+ const owners = /* @__PURE__ */ new Map();
946
+ if (input.ownMaps) {
947
+ for (const bundle of await findBundles(input.dir, input.files)) owners.set(bundle.map, bundle.js);
948
+ }
484
949
  try {
485
- result.injected = await injectDir(input.dir, {
486
- files: input.files,
487
- dryRun: options.dryRun,
488
- stripSourceMappingUrl: input.stripSourceMappingUrl
489
- });
490
- const changed = result.injected.filter((r) => r.status === "injected").length;
491
- if (result.injected.length) {
492
- log(`debug ids: ${changed} bundle(s) injected, ${result.injected.length - changed} already had one`);
950
+ try {
951
+ result.injected = await injectDir(input.dir, {
952
+ files: input.files,
953
+ dryRun: options.dryRun,
954
+ stripSourceMappingUrl: input.stripSourceMappingUrl
955
+ });
956
+ const changed = result.injected.filter((r) => r.status === "injected").length;
957
+ if (result.injected.length) {
958
+ log(`debug ids: ${changed} bundle(s) injected, ${result.injected.length - changed} already had one`);
959
+ }
960
+ for (const bad of result.injected.filter((r) => r.status === "invalid-map")) log(`skipped ${bad.path}: its map is not valid JSON`);
961
+ if (options.upload === false) return result;
962
+ const key = buildKey(options);
963
+ if (!key && !options.dryRun) {
964
+ outcome = "AUTTER_RUNTIME_KEY is not set";
965
+ if (result.injected.length && !input.ownMaps) log("AUTTER_RUNTIME_KEY is not set: source maps were not uploaded");
966
+ return result;
967
+ }
968
+ if (!result.injected.some((r) => r.status !== "invalid-map")) {
969
+ outcome = "no bundle had a usable map to upload";
970
+ return result;
971
+ }
972
+ result.upload = await uploadDir(input.dir, {
973
+ files: input.files,
974
+ release: options.release,
975
+ urlPrefix: options.urlPrefix ?? input.urlPrefix,
976
+ endpoint: options.endpoint,
977
+ key: key ?? void 0,
978
+ dryRun: options.dryRun,
979
+ concurrency: options.concurrency,
980
+ deleteAfterUpload: options.deleteAfterUpload ?? input.deleteAfterUpload,
981
+ log
982
+ });
983
+ for (const line of formatUploadSummary(result.upload)) log(line);
984
+ const { failed, uploaded, skipped, dryRun } = result.upload;
985
+ if (dryRun) outcome = "dry run, nothing was uploaded";
986
+ else if (failed.length) {
987
+ outcome = `${failed.length} of ${failed.length + uploaded.length + skipped.length} could not be uploaded (${failed[0].error})`;
988
+ }
989
+ if (failed.length && options.failOnError) {
990
+ throw new Error(`${failed.length} source map upload(s) failed`);
991
+ }
992
+ } catch (err) {
993
+ const message = err instanceof Error ? err.message : String(err);
994
+ if (outcome === "they were uploaded") outcome = `the upload failed (${message})`;
995
+ if (options.failOnError) throw new Error(`[autter-runtime] source maps: ${message}`);
996
+ if (!options.silent) console.warn(`[autter-runtime] source maps: ${message}`);
493
997
  }
494
- for (const bad of result.injected.filter((r) => r.status === "invalid-map")) log(`skipped ${bad.path}: its map is not valid JSON`);
495
- if (options.upload === false) return result;
496
- const key = options.key ?? process.env.AUTTER_RUNTIME_KEY;
497
- if (!key && !options.dryRun) {
498
- if (result.injected.length) log("AUTTER_RUNTIME_KEY is not set: source maps were not uploaded");
499
- return result;
998
+ } finally {
999
+ await cleanUp();
1000
+ }
1001
+ return result;
1002
+ async function cleanUp() {
1003
+ if (!input.ownMaps) return;
1004
+ const maps = /* @__PURE__ */ new Set([...input.maps ?? [], ...owners.keys()]);
1005
+ const rel = (path) => (0, import_node_path2.relative)(input.dir, path).split(import_node_path2.sep).join("/");
1006
+ if (options.upload === false || options.deleteAfterUpload === false) {
1007
+ const kept = [...maps].filter((map) => (0, import_node_fs2.existsSync)(map));
1008
+ if (kept.length) {
1009
+ log(
1010
+ `kept ${kept.length} source map(s) this plugin generated (${options.upload === false ? "upload: false" : "deleteAfterUpload: false"}): they expose your source, so upload them with \`autter-runtime sourcemaps upload --delete-after-upload\` or keep them out of the deploy`
1011
+ );
1012
+ }
1013
+ return;
500
1014
  }
501
- if (!result.injected.some((r) => r.status !== "invalid-map")) return result;
502
- result.upload = await uploadDir(input.dir, {
503
- files: input.files,
504
- release: options.release,
505
- urlPrefix: options.urlPrefix ?? input.urlPrefix,
506
- endpoint: options.endpoint,
507
- key,
508
- dryRun: options.dryRun,
509
- concurrency: options.concurrency,
510
- deleteAfterUpload: options.deleteAfterUpload ?? input.deleteAfterUpload,
511
- log
512
- });
513
- for (const line of formatUploadSummary(result.upload)) log(line);
514
- if (result.upload.failed.length && options.failOnError) {
515
- throw new Error(`${result.upload.failed.length} source map upload(s) failed`);
1015
+ try {
1016
+ await removeSourceMaps(maps, owners);
1017
+ } catch (err) {
1018
+ const message = `could not delete the source maps this plugin generated (${err instanceof Error ? err.message : String(err)}): keep them out of the deploy`;
1019
+ if (options.failOnError) throw new Error(`[autter-runtime] ${message}`);
1020
+ if (!options.silent) console.warn(`[autter-runtime] ${message}`);
1021
+ }
1022
+ result.removedMaps = [...maps].filter((map) => !(0, import_node_fs2.existsSync)(map)).map(rel).sort();
1023
+ if (result.removedMaps.length) {
1024
+ log(`removed ${result.removedMaps.length} source map(s) this plugin generated, so they are not deployed: ${outcome}`);
516
1025
  }
517
- } catch (err) {
518
- const message = `source maps: ${err instanceof Error ? err.message : String(err)}`;
519
- if (options.failOnError) throw new Error(`[autter-runtime] ${message}`);
520
- if (!options.silent) console.warn(`[autter-runtime] ${message}`);
521
1026
  }
522
- return result;
523
1027
  }
524
1028
 
525
1029
  // src/vite.ts
@@ -535,7 +1039,11 @@ function autterSourceMaps(options = {}) {
535
1039
  config(config) {
536
1040
  isVite = true;
537
1041
  const current = config.build?.sourcemap;
538
- if (current === void 0 || current === false) {
1042
+ if ((current === void 0 || current === false) && !config.build?.ssr) {
1043
+ if (!shouldGenerateMaps(options)) {
1044
+ logMapsNotGenerated(options);
1045
+ return void 0;
1046
+ }
539
1047
  enabledMaps = true;
540
1048
  return { build: { sourcemap: "hidden" } };
541
1049
  }
@@ -550,21 +1058,40 @@ function autterSourceMaps(options = {}) {
550
1058
  },
551
1059
  outputOptions(output) {
552
1060
  if (isVite || output.sourcemap !== void 0 && output.sourcemap !== false) return null;
1061
+ if (!shouldGenerateMaps(options)) {
1062
+ logMapsNotGenerated(options);
1063
+ return null;
1064
+ }
553
1065
  enabledMaps = true;
554
1066
  return { ...output, sourcemap: "hidden" };
555
1067
  },
556
1068
  async writeBundle(output, bundle) {
557
- const environment = this?.environment;
558
- if (ssr || environment?.config?.consumer === "server") return;
559
- const dir = output.dir ?? (output.file ? (0, import_node_path2.dirname)(output.file) : void 0);
1069
+ const dir = output.dir ?? (output.file ? (0, import_node_path3.dirname)(output.file) : void 0);
560
1070
  if (!dir) return;
561
- const files = Object.values(bundle).filter((file) => file.type === "chunk").map((file) => (0, import_node_path2.resolve)(dir, file.fileName));
1071
+ const maps = Object.values(bundle).filter((file) => file.fileName.endsWith(".map")).map((file) => (0, import_node_path3.resolve)(dir, file.fileName));
1072
+ const environment = this?.environment;
1073
+ if (ssr || environment?.config?.consumer === "server") {
1074
+ if (enabledMaps && options.deleteAfterUpload !== false) {
1075
+ try {
1076
+ const removed = await removeSourceMaps(maps);
1077
+ if (removed.length && !options.silent) {
1078
+ console.log(`[autter-runtime] removed ${removed.length} source map(s) this plugin generated for a server bundle (not uploaded)`);
1079
+ }
1080
+ } catch (err) {
1081
+ if (!options.silent) console.warn(`[autter-runtime] could not delete server source maps: ${err instanceof Error ? err.message : String(err)}`);
1082
+ }
1083
+ }
1084
+ return;
1085
+ }
1086
+ const files = Object.values(bundle).filter((file) => file.type === "chunk").map((file) => (0, import_node_path3.resolve)(dir, file.fileName));
562
1087
  await processBuildOutput({
563
1088
  dir,
564
1089
  files,
1090
+ maps,
565
1091
  urlPrefix: base,
566
1092
  options,
567
- deleteAfterUpload: enabledMaps
1093
+ deleteAfterUpload: enabledMaps,
1094
+ ownMaps: enabledMaps
568
1095
  });
569
1096
  }
570
1097
  };