@autter/runtime-cli 0.0.0-stage → 1.1.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/cli.js ADDED
@@ -0,0 +1,1031 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import { spawnSync } from "child_process";
5
+ import { existsSync as existsSync3, readFileSync } from "fs";
6
+ import { createRequire } from "module";
7
+ import { dirname as dirname2, join as join2, resolve as resolve2 } from "path";
8
+ import { parseArgs } from "util";
9
+
10
+ // src/build.ts
11
+ import { existsSync as existsSync2 } from "fs";
12
+ import { relative as relative2, sep as sep2 } from "path";
13
+
14
+ // src/files.ts
15
+ import { existsSync } from "fs";
16
+ import { readdir, readFile, rm, writeFile } from "fs/promises";
17
+ import { dirname, join, relative, resolve, sep } from "path";
18
+ var BUNDLE_RE = /\.[cm]?js$/;
19
+ var SOURCE_MAPPING_URL_RE = /^[ \t]*\/\/[#@] sourceMappingURL=([^\s'"]+)[ \t]*\r?$/gm;
20
+ function readSourceMappingUrl(code) {
21
+ let found = null;
22
+ for (const match of code.matchAll(SOURCE_MAPPING_URL_RE)) found = match[1];
23
+ return found;
24
+ }
25
+ function stripSourceMappingUrl(code) {
26
+ const lines = code.split("\n");
27
+ for (let i = lines.length - 1; i >= 0; i--) {
28
+ const line = lines[i].trim();
29
+ if (line === "") continue;
30
+ if (/^\/\/[#@] sourceMappingURL=/.test(line)) {
31
+ lines.splice(i, 1);
32
+ return lines.join("\n");
33
+ }
34
+ if (!line.startsWith("//#")) break;
35
+ }
36
+ return code;
37
+ }
38
+ function mapPathFor(js, code) {
39
+ const url = readSourceMappingUrl(code);
40
+ if (url && !/^[a-z][\w+.-]*:/i.test(url) && !url.startsWith("/")) {
41
+ let decoded = url.split(/[?#]/)[0];
42
+ try {
43
+ decoded = decodeURIComponent(decoded);
44
+ } catch {
45
+ }
46
+ const candidate = resolve(dirname(js), decoded);
47
+ if (existsSync(candidate)) return candidate;
48
+ }
49
+ const sibling = `${js}.map`;
50
+ return existsSync(sibling) ? sibling : null;
51
+ }
52
+ async function walk(dir, out, pattern = BUNDLE_RE) {
53
+ let entries;
54
+ try {
55
+ entries = await readdir(dir, { withFileTypes: true });
56
+ } catch {
57
+ return;
58
+ }
59
+ for (const entry of entries) {
60
+ if (entry.name === "node_modules") continue;
61
+ const full = join(dir, entry.name);
62
+ if (entry.isDirectory()) await walk(full, out, pattern);
63
+ else if (entry.isFile() && pattern.test(entry.name)) out.push(full);
64
+ }
65
+ }
66
+ async function findBundles(dir, files) {
67
+ const root = resolve(dir);
68
+ const candidates = [];
69
+ if (files) {
70
+ for (const file of files) if (BUNDLE_RE.test(file)) candidates.push(resolve(root, file));
71
+ } else {
72
+ await walk(root, candidates);
73
+ }
74
+ const bundles = [];
75
+ for (const js of [...new Set(candidates)].sort()) {
76
+ let code;
77
+ try {
78
+ code = await readFile(js, "utf8");
79
+ } catch {
80
+ continue;
81
+ }
82
+ const map = mapPathFor(js, code);
83
+ if (map) bundles.push({ js, map, path: relative(root, js).split(sep).join("/") });
84
+ }
85
+ return bundles;
86
+ }
87
+
88
+ // src/inject.ts
89
+ import { readFile as readFile2, writeFile as writeFile2 } from "fs/promises";
90
+
91
+ // src/debug-id.ts
92
+ import { createHash } from "crypto";
93
+ var DEBUG_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
94
+ function normalizeDebugId(value) {
95
+ if (typeof value !== "string") return null;
96
+ const id = value.trim().toLowerCase();
97
+ return DEBUG_ID_RE.test(id) ? id : null;
98
+ }
99
+ function debugIdFor(bytes) {
100
+ const hash = createHash("sha256").update(bytes).digest();
101
+ hash[6] = hash[6] & 15 | 64;
102
+ hash[8] = hash[8] & 63 | 128;
103
+ const hex = hash.subarray(0, 16).toString("hex");
104
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
105
+ }
106
+ var DEBUG_ID_COMMENT_RE = /^\/\/# debugId=([0-9a-fA-F-]{36})[ \t]*\r?$/gm;
107
+ function readDebugIdComment(code) {
108
+ let found = null;
109
+ for (const match of code.matchAll(DEBUG_ID_COMMENT_RE)) found = normalizeDebugId(match[1]) ?? found;
110
+ return found;
111
+ }
112
+ var DEBUG_ID_REGISTRY = "_autterDebugIds";
113
+ function debugIdSnippet(id) {
114
+ 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){}}();`;
115
+ }
116
+ var SNIPPET_RE = /\(g\._autterDebugIds=g\._autterDebugIds\|\|\{\}\)\[s\]="[0-9a-f]{8}-/;
117
+ function hasDebugIdSnippet(code) {
118
+ return SNIPPET_RE.test(code);
119
+ }
120
+
121
+ // src/inject.ts
122
+ var SNIPPET_LINE_KEY = "x_autter_snippet_line";
123
+ function snippetLine(code) {
124
+ let line = 0;
125
+ let i = 0;
126
+ if (code.startsWith("#!")) {
127
+ const nl = code.indexOf("\n");
128
+ if (nl < 0) return -1;
129
+ line = 1;
130
+ i = nl + 1;
131
+ }
132
+ for (; ; ) {
133
+ while (i < code.length && /\s/.test(code[i])) i++;
134
+ if (code.startsWith("//", i)) {
135
+ const nl = code.indexOf("\n", i);
136
+ if (nl < 0) return -1;
137
+ i = nl + 1;
138
+ } else if (code.startsWith("/*", i)) {
139
+ const end = code.indexOf("*/", i + 2);
140
+ if (end < 0) return -1;
141
+ i = end + 2;
142
+ } else {
143
+ break;
144
+ }
145
+ }
146
+ return code[i] === '"' || code[i] === "'" ? -1 : line;
147
+ }
148
+ function shiftMappings(mappings, at, count = 1) {
149
+ const lines = mappings.split(";");
150
+ while (lines.length < at) lines.push("");
151
+ lines.splice(at, 0, ...Array(count).fill(""));
152
+ return lines.join(";");
153
+ }
154
+ function insertBeforeTrailingComments(code, text) {
155
+ const lines = code.split("\n");
156
+ let at = lines.length;
157
+ while (at > 0) {
158
+ const line = lines[at - 1].trim();
159
+ if (line === "" || line.startsWith("//#") || line.startsWith("//@")) at--;
160
+ else break;
161
+ }
162
+ const head = lines.slice(0, at).join("\n");
163
+ const tail = lines.slice(at).join("\n");
164
+ return `${head}${head && !head.endsWith("\n") ? "\n" : ""}${text}${tail ? `
165
+ ${tail.replace(/^\n+/, "")}` : "\n"}`;
166
+ }
167
+ async function injectBundle(bundle, options = {}) {
168
+ const bytes = await readFile2(bundle.js);
169
+ const code = bytes.toString("utf8");
170
+ const base = { path: bundle.path, js: bundle.js, map: bundle.map };
171
+ let map;
172
+ try {
173
+ map = JSON.parse(await readFile2(bundle.map, "utf8"));
174
+ if (!map || typeof map !== "object") throw new Error("not an object");
175
+ } catch {
176
+ return { ...base, debugId: "", status: "invalid-map" };
177
+ }
178
+ const existing = readDebugIdComment(code);
179
+ const hasSnippet = hasDebugIdSnippet(code);
180
+ const debugId = existing ?? debugIdFor(bytes);
181
+ let out = code;
182
+ let mapDirty = false;
183
+ if (!hasSnippet) {
184
+ const shifted = typeof map[SNIPPET_LINE_KEY] === "number" ? map[SNIPPET_LINE_KEY] : null;
185
+ const line = shifted ?? snippetLine(code);
186
+ if (line >= 0 && (shifted !== null || typeof map.mappings === "string" && !("sections" in map))) {
187
+ let offset = 0;
188
+ for (let n = 0; n < line; n++) offset = out.indexOf("\n", offset) + 1;
189
+ out = `${out.slice(0, offset)}${debugIdSnippet(debugId)}
190
+ ${out.slice(offset)}`;
191
+ if (shifted === null) {
192
+ map.mappings = shiftMappings(map.mappings, line);
193
+ map[SNIPPET_LINE_KEY] = line;
194
+ mapDirty = true;
195
+ }
196
+ } else {
197
+ out = insertBeforeTrailingComments(out, debugIdSnippet(debugId));
198
+ }
199
+ }
200
+ if (!existing) out = `${out}${out.endsWith("\n") ? "" : "\n"}//# debugId=${debugId}
201
+ `;
202
+ if (options.stripSourceMappingUrl) out = stripSourceMappingUrl(out);
203
+ if (map.debugId !== debugId) {
204
+ map.debugId = debugId;
205
+ mapDirty = true;
206
+ }
207
+ const changed = mapDirty || out !== code;
208
+ if (changed && !options.dryRun) {
209
+ if (mapDirty) await writeFile2(bundle.map, JSON.stringify(map));
210
+ if (out !== code) await writeFile2(bundle.js, out);
211
+ }
212
+ return { ...base, debugId, status: changed ? "injected" : "unchanged" };
213
+ }
214
+ async function injectDir(dir, options = {}) {
215
+ const results = [];
216
+ for (const bundle of await findBundles(dir, options.files)) results.push(await injectBundle(bundle, options));
217
+ return results;
218
+ }
219
+
220
+ // src/upload.ts
221
+ import { createHash as createHash2 } from "crypto";
222
+ import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
223
+ import { promisify } from "util";
224
+ import { gzip as gzipCallback } from "zlib";
225
+
226
+ // src/release.ts
227
+ import { execFileSync } from "child_process";
228
+ var RELEASE_RE = /^[a-zA-Z0-9._-]{1,200}$/;
229
+ var RELEASE_ENV_VARS = [
230
+ "GITHUB_SHA",
231
+ "VERCEL_GIT_COMMIT_SHA",
232
+ "CF_PAGES_COMMIT_SHA",
233
+ "GIT_SHA"
234
+ ];
235
+ function gitHead(cwd = process.cwd()) {
236
+ try {
237
+ const sha = execFileSync("git", ["rev-parse", "HEAD"], {
238
+ cwd,
239
+ encoding: "utf8",
240
+ stdio: ["ignore", "pipe", "ignore"],
241
+ timeout: 1e4
242
+ }).trim();
243
+ return /^[0-9a-f]{7,64}$/.test(sha) ? sha : null;
244
+ } catch {
245
+ return null;
246
+ }
247
+ }
248
+ function resolveRelease(explicit, env = process.env, cwd = process.cwd()) {
249
+ const candidates = [
250
+ ["--release", explicit],
251
+ ...RELEASE_ENV_VARS.map((name) => [name, env[name]])
252
+ ];
253
+ for (const [source, value] of candidates) {
254
+ const release = value?.trim();
255
+ if (!release) continue;
256
+ if (!RELEASE_RE.test(release)) {
257
+ throw new Error(
258
+ `release "${release}" (from ${source}) is not valid: use 1-200 letters, digits, ".", "_" or "-" (a commit SHA works)`
259
+ );
260
+ }
261
+ return { release, source };
262
+ }
263
+ const head = gitHead(cwd);
264
+ if (head) return { release: head, source: "git" };
265
+ throw new Error(
266
+ `no release: pass --release <release>, or set one of ${RELEASE_ENV_VARS.join(", ")}, or run inside a git checkout`
267
+ );
268
+ }
269
+
270
+ // src/scopes.ts
271
+ import { parse } from "acorn";
272
+ var SCOPES_KEY = "x_autter_scopes";
273
+ var SCOPES_VERSION = 1;
274
+ var BASE_OPTIONS = {
275
+ ecmaVersion: "latest",
276
+ allowHashBang: true,
277
+ allowReturnOutsideFunction: true,
278
+ allowReserved: true
279
+ };
280
+ function parseBundle(code) {
281
+ try {
282
+ return parse(code, {
283
+ ...BASE_OPTIONS,
284
+ sourceType: "module",
285
+ allowAwaitOutsideFunction: true,
286
+ allowImportExportEverywhere: true
287
+ });
288
+ } catch (moduleError) {
289
+ try {
290
+ return parse(code, { ...BASE_OPTIONS, sourceType: "script" });
291
+ } catch (scriptError) {
292
+ const pos = (err) => typeof err.pos === "number" ? err.pos : -1;
293
+ throw pos(scriptError) > pos(moduleError) ? scriptError : moduleError;
294
+ }
295
+ }
296
+ }
297
+ function isNode(value) {
298
+ return typeof value === "object" && value !== null && typeof value.type === "string";
299
+ }
300
+ var IDENTIFIER_NAME_RE = /^[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*$/u;
301
+ function identifierToken(node) {
302
+ if (!isNode(node)) return null;
303
+ if (node.type === "Identifier") return { offset: node.start, name: node.name, literal: false };
304
+ if (node.type === "PrivateIdentifier") return { offset: node.start, name: `#${node.name}`, literal: false };
305
+ return null;
306
+ }
307
+ function literalToken(node) {
308
+ if (!isNode(node) || node.type !== "Literal" || typeof node.value !== "string") return null;
309
+ return IDENTIFIER_NAME_RE.test(node.value) ? { offset: node.start, name: node.value, literal: true } : null;
310
+ }
311
+ function keyToken(property) {
312
+ if (!property.computed) {
313
+ const id = identifierToken(property.key);
314
+ if (id) return id;
315
+ }
316
+ return literalToken(property.key);
317
+ }
318
+ function bindingToken(target) {
319
+ if (!isNode(target)) return null;
320
+ if (target.type === "Identifier") return identifierToken(target);
321
+ if (target.type === "MemberExpression") {
322
+ return target.computed ? literalToken(target.property) : identifierToken(target.property);
323
+ }
324
+ return null;
325
+ }
326
+ function contextTokens(node, parent) {
327
+ let token = null;
328
+ switch (parent?.type) {
329
+ case "VariableDeclarator":
330
+ if (parent.init === node) token = bindingToken(parent.id);
331
+ break;
332
+ case "AssignmentExpression":
333
+ case "AssignmentPattern":
334
+ if (parent.right === node) token = bindingToken(parent.left);
335
+ break;
336
+ case "Property":
337
+ case "PropertyDefinition":
338
+ case "MethodDefinition":
339
+ if (parent.value === node) token = keyToken(parent);
340
+ break;
341
+ }
342
+ return token ? [token] : [];
343
+ }
344
+ function classTokens(path) {
345
+ if (!path || path.node.type !== "ClassDeclaration" && path.node.type !== "ClassExpression") return [];
346
+ const own = identifierToken(path.node.id);
347
+ return [...own ? [own] : [], ...contextTokens(path.node, path.parent?.node)];
348
+ }
349
+ function describe(path) {
350
+ const fn = path.node;
351
+ const parent = path.parent?.node;
352
+ const own = identifierToken(fn.id);
353
+ const isMethod = parent?.type === "MethodDefinition" || parent?.type === "Property" && parent.value === fn && (parent.method === true || parent.kind !== "init");
354
+ let context;
355
+ if (parent?.type === "MethodDefinition" && parent.kind === "constructor") {
356
+ context = classTokens(path.parent?.parent?.parent ?? null);
357
+ } else {
358
+ context = contextTokens(fn, parent);
359
+ }
360
+ return {
361
+ start: fn.start,
362
+ end: fn.end,
363
+ own,
364
+ recoverAt: !own && fn.type !== "ArrowFunctionExpression" && !isMethod ? fn.start : null,
365
+ context
366
+ };
367
+ }
368
+ var FUNCTION_TYPES = /* @__PURE__ */ new Set(["FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression"]);
369
+ function classInitializer(path) {
370
+ const node = path.node;
371
+ let range = null;
372
+ if (node.type === "StaticBlock") range = node;
373
+ else if (node.type === "PropertyDefinition" && isNode(node.value) && !FUNCTION_TYPES.has(node.value.type)) range = node.value;
374
+ if (!range) return null;
375
+ return { start: range.start, end: range.end, own: null, recoverAt: null, context: classTokens(path.parent?.parent ?? null) };
376
+ }
377
+ function collectFunctions(program) {
378
+ const found = [];
379
+ const stack = [{ node: program, parent: null }];
380
+ for (let path = stack.pop(); path; path = stack.pop()) {
381
+ const node = path.node;
382
+ if (FUNCTION_TYPES.has(node.type)) found.push(describe(path));
383
+ else {
384
+ const initializer = classInitializer(path);
385
+ if (initializer) found.push(initializer);
386
+ }
387
+ for (const key in node) {
388
+ const value = node[key];
389
+ if (Array.isArray(value)) {
390
+ for (let i = value.length - 1; i >= 0; i--) if (isNode(value[i])) stack.push({ node: value[i], parent: path });
391
+ } else if (isNode(value)) {
392
+ stack.push({ node: value, parent: path });
393
+ }
394
+ }
395
+ }
396
+ return found;
397
+ }
398
+ function lineStarts(code) {
399
+ const starts = [0];
400
+ for (let i = 0; i < code.length; i++) {
401
+ const c = code.charCodeAt(i);
402
+ if (c === 10 || c === 8232 || c === 8233) starts.push(i + 1);
403
+ else if (c === 13) {
404
+ if (code.charCodeAt(i + 1) === 10) i++;
405
+ starts.push(i + 1);
406
+ }
407
+ }
408
+ return starts;
409
+ }
410
+ function positionOf(starts, offset) {
411
+ let lo = 0;
412
+ let hi = starts.length - 1;
413
+ while (lo < hi) {
414
+ const mid = lo + hi + 1 >> 1;
415
+ if (starts[mid] <= offset) lo = mid;
416
+ else hi = mid - 1;
417
+ }
418
+ return [lo, offset - starts[lo]];
419
+ }
420
+ var BASE64 = new Int8Array(128).fill(-1);
421
+ for (const [i, ch] of [..."ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"].entries()) BASE64[ch.charCodeAt(0)] = i;
422
+ function findSegments(mappings, wanted) {
423
+ let line = 0;
424
+ let column = 0;
425
+ let source = 0;
426
+ let originalLine = 0;
427
+ let originalColumn = 0;
428
+ let name = 0;
429
+ let want = wanted.get(0);
430
+ const fields = [0, 0, 0, 0, 0];
431
+ let i = 0;
432
+ while (i < mappings.length) {
433
+ const ch = mappings.charCodeAt(i);
434
+ if (ch === 59) {
435
+ line++;
436
+ column = 0;
437
+ want = wanted.get(line);
438
+ i++;
439
+ continue;
440
+ }
441
+ if (ch === 44) {
442
+ i++;
443
+ continue;
444
+ }
445
+ let count = 0;
446
+ while (i < mappings.length) {
447
+ const next = mappings.charCodeAt(i);
448
+ if (next === 44 || next === 59) break;
449
+ let value = 0;
450
+ let shift = 0;
451
+ let digit;
452
+ do {
453
+ const code = mappings.charCodeAt(i++);
454
+ digit = code < 128 ? BASE64[code] : -1;
455
+ if (digit < 0 || shift > 30) throw new Error("invalid mappings");
456
+ value |= (digit & 31) << shift;
457
+ shift += 5;
458
+ } while (digit & 32);
459
+ const decoded = value & 1 ? -(value >>> 1) : value >>> 1;
460
+ if (count < 5) fields[count] = decoded;
461
+ count++;
462
+ }
463
+ column += fields[0];
464
+ if (count >= 4) {
465
+ source += fields[1];
466
+ originalLine += fields[2];
467
+ originalColumn += fields[3];
468
+ }
469
+ if (count >= 5) name += fields[4];
470
+ if (want && want.get(column) === null) {
471
+ want.set(column, {
472
+ source: count >= 4 ? source : -1,
473
+ line: originalLine,
474
+ column: originalColumn,
475
+ name: count >= 5 ? name : -1
476
+ });
477
+ }
478
+ }
479
+ }
480
+ function looksMangled(name) {
481
+ return name.replace(/^#/, "").length <= 2;
482
+ }
483
+ var IDENTIFIER_AT_RE = /[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*/uy;
484
+ var OWN_NAME_AT_RE = /(?:async\s+)?function\b\s*\*?\s*([$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*)/uy;
485
+ var NOT_A_NAME = new Set(
486
+ "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(" ")
487
+ );
488
+ var NameResolver = class {
489
+ constructor(map, segmentAt) {
490
+ this.segmentAt = segmentAt;
491
+ this.names = Array.isArray(map.names) ? map.names : [];
492
+ this.sourcesContent = Array.isArray(map.sourcesContent) ? map.sourcesContent : [];
493
+ }
494
+ segmentAt;
495
+ names;
496
+ sourcesContent;
497
+ sourceLines = /* @__PURE__ */ new Map();
498
+ originalLine(segment) {
499
+ if (segment.source < 0) return null;
500
+ let lines = this.sourceLines.get(segment.source);
501
+ if (lines === void 0) {
502
+ const content = this.sourcesContent[segment.source];
503
+ lines = typeof content === "string" ? content.split(/\r\n|[\n\r\u2028\u2029]/) : null;
504
+ this.sourceLines.set(segment.source, lines);
505
+ }
506
+ return lines?.[segment.line] ?? null;
507
+ }
508
+ /** The original identifier at a segment's source position. */
509
+ identifierAt(segment, re, group = 0) {
510
+ const text = this.originalLine(segment);
511
+ if (text === null) return null;
512
+ re.lastIndex = segment.column;
513
+ const found = re.exec(text)?.[group];
514
+ return found && !NOT_A_NAME.has(found) ? found : null;
515
+ }
516
+ /** Original name of a token: the map's `names` at its exact position;
517
+ * else the generated name when it isn't mangled; else the identifier
518
+ * at the mapped position in `sourcesContent`. Null when unknown. */
519
+ resolve(token) {
520
+ if (token.literal) return token.name;
521
+ const segment = this.segmentAt(token.offset);
522
+ if (segment && segment.name >= 0) {
523
+ const name = this.names[segment.name];
524
+ if (typeof name === "string" && name) return name;
525
+ }
526
+ if (!looksMangled(token.name)) return token.name;
527
+ return segment ? this.identifierAt(segment, IDENTIFIER_AT_RE) : null;
528
+ }
529
+ /** The name a minifier removed from `function name() {}`, read from the
530
+ * original source at the function's mapped start. */
531
+ recover(offset) {
532
+ const segment = this.segmentAt(offset);
533
+ return segment ? this.identifierAt(segment, OWN_NAME_AT_RE, 1) : null;
534
+ }
535
+ };
536
+ var BASE64_DIGITS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
537
+ function vlq(value) {
538
+ let rest = value < 0 ? -value << 1 | 1 : value << 1;
539
+ let out = "";
540
+ do {
541
+ let digit = rest & 31;
542
+ rest >>>= 5;
543
+ if (rest > 0) digit |= 32;
544
+ out += BASE64_DIGITS[digit];
545
+ } while (rest > 0);
546
+ return out;
547
+ }
548
+ function encodeScopes(entries) {
549
+ const parts = [];
550
+ let line = 0;
551
+ let previousStart = 0;
552
+ let previousName = 0;
553
+ let firstOnLine = true;
554
+ for (const [startLine, startColumn, endLine, endColumn, nameIndex] of entries) {
555
+ if (startLine > line) {
556
+ parts.push(";".repeat(startLine - line));
557
+ line = startLine;
558
+ previousStart = 0;
559
+ firstOnLine = true;
560
+ }
561
+ if (!firstOnLine) parts.push(",");
562
+ firstOnLine = false;
563
+ let segment = vlq(startColumn - previousStart) + vlq(endLine - startLine) + vlq(endLine === startLine ? endColumn - startColumn : endColumn);
564
+ previousStart = startColumn;
565
+ if (nameIndex >= 0) {
566
+ segment += vlq(nameIndex - previousName);
567
+ previousName = nameIndex;
568
+ }
569
+ parts.push(segment);
570
+ }
571
+ return parts.join("");
572
+ }
573
+ function computeScopes(code, map) {
574
+ try {
575
+ return scopesOf(code, map);
576
+ } catch (err) {
577
+ return { error: err instanceof Error ? err.message : String(err) };
578
+ }
579
+ }
580
+ function scopesOf(code, map) {
581
+ if (typeof map.mappings !== "string") return { error: "the map has no mappings string" };
582
+ let functions;
583
+ try {
584
+ functions = collectFunctions(parseBundle(code));
585
+ } catch (err) {
586
+ return { error: `could not parse the bundle: ${err instanceof Error ? err.message : String(err)}` };
587
+ }
588
+ const starts = lineStarts(code);
589
+ const wanted = /* @__PURE__ */ new Map();
590
+ const want = (offset) => {
591
+ const [line, column] = positionOf(starts, offset);
592
+ let columns = wanted.get(line);
593
+ if (!columns) wanted.set(line, columns = /* @__PURE__ */ new Map());
594
+ columns.set(column, null);
595
+ };
596
+ for (const fn of functions) {
597
+ if (fn.own && !fn.own.literal) want(fn.own.offset);
598
+ if (fn.recoverAt !== null) want(fn.recoverAt);
599
+ for (const token of fn.context) if (!token.literal) want(token.offset);
600
+ }
601
+ try {
602
+ findSegments(map.mappings, wanted);
603
+ } catch (err) {
604
+ return { error: `could not read the map: ${err instanceof Error ? err.message : String(err)}` };
605
+ }
606
+ const resolver = new NameResolver(map, (offset) => {
607
+ const [line, column] = positionOf(starts, offset);
608
+ return wanted.get(line)?.get(column) ?? null;
609
+ });
610
+ functions.sort((a, b) => a.start - b.start || b.end - a.end);
611
+ const mapNames = Array.isArray(map.names) ? map.names : [];
612
+ const nameIndex = /* @__PURE__ */ new Map();
613
+ mapNames.forEach((name, index) => {
614
+ if (typeof name === "string" && !nameIndex.has(name)) nameIndex.set(name, index);
615
+ });
616
+ const extraNames = [];
617
+ const indexOf = (name) => {
618
+ let index = nameIndex.get(name);
619
+ if (index === void 0) {
620
+ index = mapNames.length + extraNames.push(name) - 1;
621
+ nameIndex.set(name, index);
622
+ }
623
+ return index;
624
+ };
625
+ const entries = functions.map((fn) => {
626
+ let name = fn.own ? resolver.resolve(fn.own) : null;
627
+ if (name === null && fn.recoverAt !== null) name = resolver.recover(fn.recoverAt);
628
+ for (const token of fn.context) {
629
+ if (name !== null) break;
630
+ name = resolver.resolve(token);
631
+ }
632
+ const index = name !== null ? indexOf(name) : fn.own || fn.context.length > 0 ? indexOf(null) : -1;
633
+ const [startLine, startColumn] = positionOf(starts, fn.start);
634
+ const [endLine, endColumn] = positionOf(starts, fn.end);
635
+ return [startLine, startColumn, endLine, endColumn, index];
636
+ });
637
+ return { scopes: { version: SCOPES_VERSION, names: extraNames, scopes: encodeScopes(entries) } };
638
+ }
639
+
640
+ // src/upload.ts
641
+ var DEFAULT_ENDPOINT = "https://otlp.autter.dev";
642
+ var MAX_MAP_CHARS = 32 * 1024 * 1024;
643
+ var MAX_UPLOAD_BYTES = MAX_MAP_CHARS + 1024 * 1024;
644
+ var LEGACY_MAX_BYTES = 5 * 1024 * 1024;
645
+ var gzip = promisify(gzipCallback);
646
+ var CHECK_BATCH = 500;
647
+ var MAX_ATTEMPTS = 3;
648
+ function resolveEndpoint(flag, env = process.env) {
649
+ const raw = flag || env.AUTTER_ENDPOINT || env.AUTTER_RUNTIME_ENDPOINT || env.OTEL_EXPORTER_OTLP_ENDPOINT || DEFAULT_ENDPOINT;
650
+ return raw.trim().replace(/\/+$/, "").replace(/\/v1\/[a-z-]+$/, "");
651
+ }
652
+ function servedFilename(urlPrefix, path) {
653
+ let prefix = (urlPrefix ?? "/").trim() || "/";
654
+ if (prefix.startsWith("~/")) prefix = prefix.slice(1);
655
+ if (!/^[a-z][\w+.-]*:\/\//i.test(prefix) && !prefix.startsWith("/")) prefix = `/${prefix}`;
656
+ return `${prefix.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`;
657
+ }
658
+ function storedMapJson(map) {
659
+ const { sourcesContent: _omitted, ...safe } = map;
660
+ return JSON.stringify(safe);
661
+ }
662
+ function bytesOf(buffer) {
663
+ return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
664
+ }
665
+ function fits(json, body) {
666
+ return json.length <= MAX_MAP_CHARS && Buffer.byteLength(body) <= MAX_UPLOAD_BYTES;
667
+ }
668
+ function uploadBody(release, filename, debugId, json) {
669
+ return `{"release":${JSON.stringify(release)},"filename":${JSON.stringify(filename)},${debugId ? `"debugId":${JSON.stringify(debugId)},` : ""}"map":${json}}`;
670
+ }
671
+ async function prepare(bundle, urlPrefix, release, log, compress) {
672
+ let map;
673
+ try {
674
+ map = JSON.parse(await readFile3(bundle.map, "utf8"));
675
+ } catch {
676
+ return { error: "map is not valid JSON" };
677
+ }
678
+ if (!map || map.version !== 3 || typeof map.mappings !== "string" || !Array.isArray(map.sources)) {
679
+ return { error: "not a version 3 source map with mappings and sources" };
680
+ }
681
+ const code = await readFile3(bundle.js, "utf8");
682
+ const debugId = readDebugIdComment(code) ?? normalizeDebugId(map.debugId);
683
+ const filename = servedFilename(urlPrefix, bundle.path);
684
+ const { [SCOPES_KEY]: _stale, ...plain } = map;
685
+ const scopes = computeScopes(code, map);
686
+ let json = storedMapJson(plain);
687
+ if ("scopes" in scopes) {
688
+ const scoped = storedMapJson({ ...plain, [SCOPES_KEY]: scopes.scopes });
689
+ if (fits(scoped, uploadBody(release, filename, debugId, scoped))) json = scoped;
690
+ else if (fits(json, uploadBody(release, filename, debugId, json))) {
691
+ log(`warning: ${bundle.path}: its map is over 32 MB with function scopes, so it is uploaded without them (frames keep call-site names)`);
692
+ }
693
+ } else {
694
+ log(`warning: ${bundle.path}: no function scopes (${scopes.error}); its map is uploaded without them (frames keep call-site names)`);
695
+ }
696
+ const body = uploadBody(release, filename, debugId, json);
697
+ return {
698
+ bundle,
699
+ // Maps are text that compresses several times over; the ingester
700
+ // inflates the body (Content-Encoding: gzip).
701
+ body: compress && fits(json, body) ? bytesOf(await gzip(body)) : new Uint8Array(0),
702
+ path: bundle.path,
703
+ filename,
704
+ debugId,
705
+ hash: createHash2("sha256").update(json).digest("hex"),
706
+ bytes: Buffer.byteLength(body),
707
+ mapChars: json.length
708
+ };
709
+ }
710
+ var FatalUploadError = class extends Error {
711
+ };
712
+ function sleep(ms) {
713
+ return new Promise((resolve3) => setTimeout(resolve3, ms));
714
+ }
715
+ async function uploadDir(dir, options = {}) {
716
+ const env = options.env ?? process.env;
717
+ const log = options.log ?? (() => {
718
+ });
719
+ const doFetch = options.fetch ?? fetch;
720
+ const { release, source: releaseSource } = resolveRelease(options.release, env, options.cwd);
721
+ const endpoint = resolveEndpoint(options.endpoint, env);
722
+ const summary = {
723
+ release,
724
+ releaseSource,
725
+ endpoint,
726
+ dryRun: Boolean(options.dryRun),
727
+ uploaded: [],
728
+ skipped: [],
729
+ failed: [],
730
+ legacyIngester: false,
731
+ deletedMaps: []
732
+ };
733
+ const items = [];
734
+ for (const bundle of await findBundles(dir, options.files)) {
735
+ const prepared = await prepare(bundle, options.urlPrefix, release, log, !options.dryRun);
736
+ if ("error" in prepared) {
737
+ summary.failed.push({ path: bundle.path, filename: servedFilename(options.urlPrefix, bundle.path), error: prepared.error });
738
+ } else if (prepared.mapChars > MAX_MAP_CHARS || prepared.bytes > MAX_UPLOAD_BYTES) {
739
+ summary.failed.push({
740
+ path: prepared.path,
741
+ filename: prepared.filename,
742
+ error: `map is ${(prepared.mapChars / 1048576).toFixed(1)} MB without sourcesContent; the ingester accepts up to 32 MB`
743
+ });
744
+ } else {
745
+ items.push(prepared);
746
+ }
747
+ }
748
+ if (options.dryRun) {
749
+ summary.uploaded = items.map(strip);
750
+ return summary;
751
+ }
752
+ const key = (options.key ?? env.AUTTER_RUNTIME_KEY ?? "").trim();
753
+ if (!key) throw new FatalUploadError("no ingest key: set AUTTER_RUNTIME_KEY to a server key (autter_rt_\u2026)");
754
+ if (key.startsWith("autter_rtc_")) {
755
+ throw new FatalUploadError("AUTTER_RUNTIME_KEY is a publishable client key (autter_rtc_\u2026); uploads need a server key (autter_rt_\u2026)");
756
+ }
757
+ const headers = { "content-type": "application/json", authorization: `Bearer ${key}` };
758
+ const uploadHeaders = { ...headers, "content-encoding": "gzip" };
759
+ const skipped = /* @__PURE__ */ new Set();
760
+ for (let start = 0; start < items.length && !summary.legacyIngester; start += CHECK_BATCH) {
761
+ const batch = items.slice(start, start + CHECK_BATCH);
762
+ try {
763
+ const res = await doFetch(`${endpoint}/v1/sourcemaps/check`, {
764
+ method: "POST",
765
+ headers,
766
+ body: JSON.stringify({
767
+ release,
768
+ files: batch.map((item) => ({ filename: item.filename, ...item.debugId ? { debugId: item.debugId } : {}, hash: item.hash }))
769
+ })
770
+ });
771
+ if (res.status === 404) {
772
+ summary.legacyIngester = true;
773
+ log(
774
+ "warning: this ingester predates 1.6.0, so it stores no debug ids and rejects .mjs/.cjs maps. Upgrade it: docker pull ghcr.io/autter-dev/otlp-ingester:latest"
775
+ );
776
+ break;
777
+ }
778
+ if (res.status === 401 || res.status === 403) {
779
+ throw new FatalUploadError(`the ingester rejected the key (${res.status}): ${(await res.text()).slice(0, 300)}`);
780
+ }
781
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
782
+ const body = await res.json();
783
+ const present = new Set(Array.isArray(body.present) ? body.present : []);
784
+ batch.forEach((item, index) => {
785
+ if (present.has(index)) skipped.add(item);
786
+ });
787
+ } catch (err) {
788
+ if (err instanceof FatalUploadError) throw err;
789
+ log(`warning: could not check which maps the ingester already has (${err.message}); uploading all`);
790
+ }
791
+ }
792
+ const uploaded = [];
793
+ let fatal = null;
794
+ const uploadOne = async (item) => {
795
+ for (let attempt = 1; ; attempt++) {
796
+ if (fatal) return;
797
+ let status = 0;
798
+ let detail = "";
799
+ try {
800
+ const res = await doFetch(`${endpoint}/v1/sourcemaps`, { method: "POST", headers: uploadHeaders, body: item.body });
801
+ status = res.status;
802
+ if (res.ok) {
803
+ uploaded.push(item);
804
+ return;
805
+ }
806
+ detail = (await res.text()).slice(0, 300);
807
+ } catch (err) {
808
+ detail = err.message;
809
+ }
810
+ if (status === 401 || status === 403) {
811
+ fatal = new FatalUploadError(`the ingester rejected the key (${status}): ${detail}`);
812
+ return;
813
+ }
814
+ const retryable = status === 0 || status === 429 || status >= 500;
815
+ if (!retryable || attempt >= MAX_ATTEMPTS) {
816
+ let error = status ? `HTTP ${status}: ${detail}` : detail;
817
+ if (status === 413 && item.bytes > LEGACY_MAX_BYTES) {
818
+ 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)`;
819
+ }
820
+ summary.failed.push({ path: item.path, filename: item.filename, error });
821
+ return;
822
+ }
823
+ await sleep(500 * 2 ** (attempt - 1));
824
+ }
825
+ };
826
+ const queue = items.filter((item) => !skipped.has(item));
827
+ const workers = Array.from({ length: Math.max(1, Math.min(options.concurrency ?? 8, queue.length)) }, async () => {
828
+ for (let item = queue.shift(); item; item = queue.shift()) await uploadOne(item);
829
+ });
830
+ await Promise.all(workers);
831
+ if (fatal) throw fatal;
832
+ const order = (a, b) => items.indexOf(a) - items.indexOf(b);
833
+ uploaded.sort(order);
834
+ if (options.deleteAfterUpload) {
835
+ for (const item of [...uploaded, ...skipped]) {
836
+ await rm2(item.bundle.map, { force: true });
837
+ const code = await readFile3(item.bundle.js, "utf8");
838
+ const stripped = stripSourceMappingUrl(code);
839
+ if (stripped !== code) await writeFile3(item.bundle.js, stripped);
840
+ summary.deletedMaps.push(item.bundle.map);
841
+ }
842
+ }
843
+ summary.uploaded = uploaded.map(strip);
844
+ summary.skipped = [...skipped].sort(order).map(strip);
845
+ return summary;
846
+ }
847
+ function strip(item) {
848
+ const { path, filename, debugId, hash, bytes } = item;
849
+ return { path, filename, debugId, hash, bytes };
850
+ }
851
+
852
+ // src/build.ts
853
+ function formatUploadSummary(summary) {
854
+ const lines = [];
855
+ const verb = summary.dryRun ? "would upload" : "uploaded";
856
+ for (const item of summary.uploaded) {
857
+ lines.push(`${verb} ${item.filename}${item.debugId ? ` (debug id ${item.debugId})` : ""}`);
858
+ }
859
+ for (const item of summary.skipped) lines.push(`skipped ${item.filename} (already uploaded)`);
860
+ for (const item of summary.failed) lines.push(`failed ${item.filename}: ${item.error}`);
861
+ lines.push(
862
+ `${summary.uploaded.length} ${verb}, ${summary.skipped.length} already uploaded, ${summary.failed.length} failed (release ${summary.release} from ${summary.releaseSource}, ${summary.endpoint})`
863
+ );
864
+ return lines;
865
+ }
866
+
867
+ // src/cli.ts
868
+ var USAGE = `autter-runtime \u2014 readable stack traces for Autter Runtime
869
+
870
+ Usage:
871
+ autter-runtime sourcemaps inject <dir> [--dry-run]
872
+ autter-runtime sourcemaps upload <dir> [--release <r>] [--url-prefix <prefix>]
873
+ [--endpoint <url>] [--concurrency <n>] [--delete-after-upload] [--dry-run]
874
+ autter-runtime doctor ... (provided by @autter/runtime-node)
875
+
876
+ inject Gives every .js/.mjs/.cjs bundle that has a source map a debug id
877
+ derived from its bytes: a "//# debugId=" comment, a one-line snippet
878
+ that registers it for @autter/runtime-browser, and "debugId" in the
879
+ .map. Running it again changes nothing.
880
+ upload Sends every map to <endpoint>/v1/sourcemaps with AUTTER_RUNTIME_KEY,
881
+ in parallel, skipping maps the ingester already has. Each map carries
882
+ the bundle's function scopes ("x_autter_scopes"), so stack frames are
883
+ named after the function they are in, not the call site.
884
+
885
+ Options:
886
+ --release <r> Default: $GITHUB_SHA, $VERCEL_GIT_COMMIT_SHA,
887
+ $CF_PAGES_COMMIT_SHA, $GIT_SHA, then git rev-parse HEAD
888
+ --url-prefix <prefix> Where <dir> is served from: "/" (default), "/static/",
889
+ or "https://cdn.example.com/app/"
890
+ --endpoint <url> Ingester base URL. Default: $AUTTER_ENDPOINT,
891
+ $AUTTER_RUNTIME_ENDPOINT, $OTEL_EXPORTER_OTLP_ENDPOINT,
892
+ then https://otlp.autter.dev
893
+ --concurrency <n> Parallel uploads (default 8)
894
+ --delete-after-upload Delete each .map once the ingester has it
895
+ --dry-run Show what would change or be uploaded; write and send nothing
896
+ --json Print the result as JSON
897
+ -h, --help Show this help
898
+ -v, --version Print the version
899
+
900
+ Environment:
901
+ AUTTER_RUNTIME_KEY Server ingest key (autter_rt_\u2026), required by upload`;
902
+ function ownVersion() {
903
+ try {
904
+ return JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
905
+ } catch {
906
+ return "unknown";
907
+ }
908
+ }
909
+ function delegate(pkg, args) {
910
+ let manifest;
911
+ try {
912
+ manifest = createRequire(join2(process.cwd(), "package.json")).resolve(`${pkg}/package.json`);
913
+ } catch {
914
+ return null;
915
+ }
916
+ const bin = JSON.parse(readFileSync(manifest, "utf8")).bin;
917
+ const relative3 = typeof bin === "string" ? bin : bin?.["autter-runtime"];
918
+ if (!relative3) return null;
919
+ const script = resolve2(dirname2(manifest), relative3);
920
+ if (!existsSync3(script)) return null;
921
+ const result = spawnSync(process.execPath, [script, ...args], { stdio: "inherit" });
922
+ return result.status ?? 1;
923
+ }
924
+ var SOURCEMAPS_OPTIONS = {
925
+ release: { type: "string" },
926
+ "url-prefix": { type: "string" },
927
+ endpoint: { type: "string" },
928
+ concurrency: { type: "string" },
929
+ "delete-after-upload": { type: "boolean" },
930
+ "dry-run": { type: "boolean" },
931
+ json: { type: "boolean" },
932
+ help: { type: "boolean", short: "h" }
933
+ };
934
+ async function sourcemaps(argv) {
935
+ let parsed;
936
+ try {
937
+ parsed = parseArgs({ args: argv, allowPositionals: true, options: SOURCEMAPS_OPTIONS });
938
+ } catch (err) {
939
+ console.error(`${err.message}
940
+
941
+ ${USAGE}`);
942
+ return 64;
943
+ }
944
+ const { values, positionals } = parsed;
945
+ const [action, dir, ...extra] = positionals;
946
+ if (values.help) {
947
+ console.log(USAGE);
948
+ return 0;
949
+ }
950
+ if (action !== "inject" && action !== "upload" || !dir || extra.length) {
951
+ console.error(`${action && action !== "inject" && action !== "upload" ? `unknown command: sourcemaps ${action}
952
+
953
+ ` : ""}${USAGE}`);
954
+ return 64;
955
+ }
956
+ if (!existsSync3(dir)) {
957
+ console.error(`autter-runtime: ${dir} does not exist`);
958
+ return 64;
959
+ }
960
+ const dryRun = Boolean(values["dry-run"]);
961
+ if (action === "inject") {
962
+ const results = await injectDir(dir, { dryRun });
963
+ if (values.json) {
964
+ console.log(JSON.stringify(results.map(({ path, debugId, status }) => ({ path, debugId, status })), null, 2));
965
+ } else {
966
+ for (const r of results) {
967
+ const what = r.status === "invalid-map" ? "skipped (map is not valid JSON)" : r.status === "injected" ? dryRun ? "would inject" : "injected" : "unchanged";
968
+ console.log(`${what} ${r.path}${r.debugId ? ` ${r.debugId}` : ""}`);
969
+ }
970
+ const injected = results.filter((r) => r.status === "injected").length;
971
+ console.log(
972
+ results.length ? `${results.length} bundle(s) with source maps: ${injected} ${dryRun ? "would be injected" : "injected"}, ${results.length - injected} unchanged` : `no .js/.mjs/.cjs bundles with source maps under ${dir}`
973
+ );
974
+ }
975
+ return results.some((r) => r.status === "invalid-map") ? 1 : 0;
976
+ }
977
+ const concurrency = values.concurrency === void 0 ? void 0 : Number(values.concurrency);
978
+ if (concurrency !== void 0 && (!Number.isInteger(concurrency) || concurrency < 1)) {
979
+ console.error("autter-runtime: --concurrency must be a positive integer");
980
+ return 64;
981
+ }
982
+ const summary = await uploadDir(dir, {
983
+ release: values.release,
984
+ urlPrefix: values["url-prefix"],
985
+ endpoint: values.endpoint,
986
+ concurrency,
987
+ dryRun,
988
+ deleteAfterUpload: Boolean(values["delete-after-upload"]),
989
+ log: (line) => console.error(line)
990
+ });
991
+ if (values.json) console.log(JSON.stringify(summary, null, 2));
992
+ else {
993
+ if (!summary.uploaded.length && !summary.skipped.length && !summary.failed.length) {
994
+ console.log(`no .js/.mjs/.cjs bundles with source maps under ${dir}`);
995
+ }
996
+ for (const line of formatUploadSummary(summary)) console.log(line);
997
+ }
998
+ return summary.failed.length ? 1 : 0;
999
+ }
1000
+ async function main(argv) {
1001
+ const [command, ...rest] = argv;
1002
+ if (command === "-v" || command === "--version") {
1003
+ console.log(ownVersion());
1004
+ return 0;
1005
+ }
1006
+ if (command === void 0 || command === "-h" || command === "--help" || command === "help") {
1007
+ console.log(USAGE);
1008
+ return 0;
1009
+ }
1010
+ if (command === "sourcemaps") return sourcemaps(rest);
1011
+ if (command === "doctor") {
1012
+ const code = delegate("@autter/runtime-node", argv);
1013
+ if (code !== null) return code;
1014
+ console.error("autter-runtime doctor is part of @autter/runtime-node: npx @autter/runtime-node doctor");
1015
+ return 64;
1016
+ }
1017
+ console.error(`unknown command: ${command}
1018
+
1019
+ ${USAGE}`);
1020
+ return 64;
1021
+ }
1022
+ main(process.argv.slice(2)).then(
1023
+ (code) => {
1024
+ process.exitCode = code;
1025
+ },
1026
+ (err) => {
1027
+ const message = err instanceof Error ? err.message : String(err);
1028
+ console.error(`autter-runtime: ${message}`);
1029
+ process.exitCode = 2;
1030
+ }
1031
+ );