@starko-one/sdk 0.0.0-stage → 0.1.0-beta.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.
Files changed (108) hide show
  1. package/CHANGELOG.md +248 -0
  2. package/LICENSE +17 -0
  3. package/NOTICE +58 -0
  4. package/README.md +81 -2
  5. package/dist/api-BAFm4Lxj.d.ts +558 -0
  6. package/dist/api-DNrctwJu.d.cts +558 -0
  7. package/dist/browser/index.cjs +168 -0
  8. package/dist/browser/index.d.cts +131 -0
  9. package/dist/browser/index.d.ts +131 -0
  10. package/dist/browser/index.js +7 -0
  11. package/dist/build/rollup.cjs +22 -0
  12. package/dist/build/rollup.d.cts +34 -0
  13. package/dist/build/rollup.d.ts +34 -0
  14. package/dist/build/rollup.js +3 -0
  15. package/dist/build/vite.cjs +51 -0
  16. package/dist/build/vite.d.cts +23 -0
  17. package/dist/build/vite.d.ts +23 -0
  18. package/dist/build/vite.js +46 -0
  19. package/dist/build/webpack.cjs +18 -0
  20. package/dist/build/webpack.d.cts +39 -0
  21. package/dist/build/webpack.d.ts +39 -0
  22. package/dist/build/webpack.js +3 -0
  23. package/dist/chunk-2PM4FRM5.cjs +431 -0
  24. package/dist/chunk-335HNCOJ.js +249 -0
  25. package/dist/chunk-3AW5B2WW.js +115 -0
  26. package/dist/chunk-3R5TQAWD.js +216 -0
  27. package/dist/chunk-6H5MOPTQ.cjs +1230 -0
  28. package/dist/chunk-7TKNT3QJ.cjs +2487 -0
  29. package/dist/chunk-A4WLNFMU.cjs +220 -0
  30. package/dist/chunk-ALYFFOPR.cjs +134 -0
  31. package/dist/chunk-BVVFVRMO.js +1113 -0
  32. package/dist/chunk-CIHNKN62.cjs +15 -0
  33. package/dist/chunk-CMGCH6HD.js +1212 -0
  34. package/dist/chunk-D6QAPQ7L.cjs +56 -0
  35. package/dist/chunk-DUO5V6WZ.js +213 -0
  36. package/dist/chunk-EC2WZ6PG.js +90 -0
  37. package/dist/chunk-EFURLFJT.cjs +187 -0
  38. package/dist/chunk-EROUORMY.js +53 -0
  39. package/dist/chunk-LXBXFOAP.cjs +96 -0
  40. package/dist/chunk-MF6SA6DB.js +563 -0
  41. package/dist/chunk-N5R6ORIB.js +413 -0
  42. package/dist/chunk-N6R6BWHK.cjs +142 -0
  43. package/dist/chunk-QAGGN2T7.cjs +225 -0
  44. package/dist/chunk-QV4HRIDD.cjs +659 -0
  45. package/dist/chunk-TKNDYQB3.cjs +583 -0
  46. package/dist/chunk-UI5YC4TH.js +131 -0
  47. package/dist/chunk-VEHZYLK6.cjs +1151 -0
  48. package/dist/chunk-VNCWOGTI.js +12 -0
  49. package/dist/chunk-VWNIOGE6.js +180 -0
  50. package/dist/chunk-WDKRKGYF.js +608 -0
  51. package/dist/chunk-XOZIXBUK.js +2462 -0
  52. package/dist/chunk-ZS3K3SDR.cjs +258 -0
  53. package/dist/cli/index.cjs +2780 -0
  54. package/dist/common-DLFAqL2d.d.cts +36 -0
  55. package/dist/common-DbSXkaw6.d.ts +36 -0
  56. package/dist/dedupe-Bh5riD8Z.d.cts +13 -0
  57. package/dist/dedupe-DoYiSx-9.d.ts +13 -0
  58. package/dist/handler-BcnsnvhF.d.cts +82 -0
  59. package/dist/handler-qHzilC9T.d.ts +82 -0
  60. package/dist/index.cjs +309 -0
  61. package/dist/index.d.cts +187 -0
  62. package/dist/index.d.ts +187 -0
  63. package/dist/index.js +4 -0
  64. package/dist/next/client.cjs +113 -0
  65. package/dist/next/client.d.cts +26 -0
  66. package/dist/next/client.d.ts +26 -0
  67. package/dist/next/client.js +41 -0
  68. package/dist/next/config.cjs +277 -0
  69. package/dist/next/config.d.cts +193 -0
  70. package/dist/next/config.d.ts +193 -0
  71. package/dist/next/config.js +263 -0
  72. package/dist/next/index.cjs +148 -0
  73. package/dist/next/index.d.cts +32 -0
  74. package/dist/next/index.d.ts +32 -0
  75. package/dist/next/index.js +59 -0
  76. package/dist/node/index.cjs +257 -0
  77. package/dist/node/index.d.cts +145 -0
  78. package/dist/node/index.d.ts +145 -0
  79. package/dist/node/index.js +83 -0
  80. package/dist/options-BUhWuWJX.d.cts +79 -0
  81. package/dist/options-BUhWuWJX.d.ts +79 -0
  82. package/dist/react/index.cjs +107 -0
  83. package/dist/react/index.d.cts +84 -0
  84. package/dist/react/index.d.ts +84 -0
  85. package/dist/react/index.js +103 -0
  86. package/dist/scope-D1ouJm2h.d.cts +628 -0
  87. package/dist/scope-D1ouJm2h.d.ts +628 -0
  88. package/dist/server-edge-7624N3WF.cjs +51 -0
  89. package/dist/server-edge-BEEXWL7T.js +48 -0
  90. package/dist/server-node-ET4LIPEC.cjs +27 -0
  91. package/dist/server-node-TQUVMZUC.js +24 -0
  92. package/dist/session-C_WzbEN2.d.cts +4 -0
  93. package/dist/session-C_WzbEN2.d.ts +4 -0
  94. package/dist/session-propagation-Pr0Zb9Zn.d.cts +30 -0
  95. package/dist/session-propagation-RM5py1bp.d.ts +30 -0
  96. package/dist/starko.min.js +6 -0
  97. package/docs/browser.md +386 -0
  98. package/docs/configuration.md +310 -0
  99. package/docs/nextjs.md +488 -0
  100. package/docs/node.md +427 -0
  101. package/docs/other-backends.md +232 -0
  102. package/docs/privacy.md +112 -0
  103. package/docs/react.md +187 -0
  104. package/docs/source-maps.md +482 -0
  105. package/docs/troubleshooting.md +263 -0
  106. package/docs/widget.md +84 -0
  107. package/docs/wire-format.md +547 -0
  108. package/package.json +191 -4
@@ -0,0 +1,2462 @@
1
+ import { PATHS, SOURCEMAP_ROUTE_MAX_SECONDS, DEBUG_ID_GLOBAL, DEFAULT_HOST, DEBUG_ID_NAMESPACE, DEBUG_ID_COMMENT, RELEASE_GLOBAL, LIMITS, version, SOURCEMAP_MAX_BYTES, SOURCEMAP_PART_BYTES, SOURCEMAP_MAX_CHUNKS_PER_CHECK, SOURCEMAP_BULK_MAX_CHECK, SOURCEMAP_BULK_MAX_MAPS, SOURCEMAP_BULK_MAX_OBJECT_BYTES, SOURCEMAP_MAX_PARTS, SOURCEMAP_BULK_UPLOAD_CONCURRENCY, SOURCEMAP_BULK_REQUEST_CONCURRENCY, SOURCEMAP_MAX_FILE_NAME } from './chunk-3AW5B2WW.js';
2
+ import { createHash, randomBytes } from 'crypto';
3
+ import { execFileSync } from 'child_process';
4
+ import { constants, promises } from 'fs';
5
+ import path from 'path';
6
+ import { promisify } from 'util';
7
+ import { gzip as gzip$1, constants as constants$1 } from 'zlib';
8
+
9
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
10
+ function isDebugId(value) {
11
+ return typeof value === "string" && UUID_RE.test(value);
12
+ }
13
+ function createDebugId(code) {
14
+ const namespace = Buffer.from(DEBUG_ID_NAMESPACE.replace(/-/g, ""), "hex");
15
+ const digest = createHash("sha1").update(namespace).update(code, "utf8").digest();
16
+ digest[6] = digest[6] & 15 | 80;
17
+ digest[8] = digest[8] & 63 | 128;
18
+ const hex = digest.subarray(0, 16).toString("hex");
19
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
20
+ }
21
+ function debugIdComment(debugId) {
22
+ return `${DEBUG_ID_COMMENT}${debugId}`;
23
+ }
24
+ var COMMENT_LINE_RE = /^\/\/# debugId=([0-9a-fA-F-]{36})[ \t\r]*$/;
25
+ var MAX_TRAILING_LINES = 16;
26
+ function findDebugId(code) {
27
+ let end = code.length;
28
+ for (let i = 0; i < MAX_TRAILING_LINES && end > 0; i++) {
29
+ const start = code.lastIndexOf("\n", end - 1) + 1;
30
+ const line = code.slice(start, end).trim();
31
+ end = start - 1;
32
+ if (line === "") continue;
33
+ if (!line.startsWith("//")) return void 0;
34
+ const match = COMMENT_LINE_RE.exec(line);
35
+ if (match && isDebugId(match[1])) return match[1].toLowerCase();
36
+ }
37
+ return void 0;
38
+ }
39
+
40
+ // src/build/shared/prologue.ts
41
+ function findInsertionOffset(code) {
42
+ let pos = 0;
43
+ if (code.charCodeAt(0) === 65279) pos = 1;
44
+ if (code.startsWith("#!", pos)) {
45
+ const nl = code.indexOf("\n", pos);
46
+ if (nl === -1) return code.length;
47
+ pos = nl + 1;
48
+ }
49
+ let safe = pos;
50
+ for (; ; ) {
51
+ const trivia = skipTrivia(code, pos);
52
+ if (trivia === void 0) return safe;
53
+ pos = trivia.end;
54
+ const ch = code[pos];
55
+ if (ch !== '"' && ch !== "'") return pos;
56
+ const end = scanString(code, pos);
57
+ if (end === void 0) return safe;
58
+ const after = skipTrivia(code, end);
59
+ if (after === void 0) return safe;
60
+ if (code[after.end] === ";") {
61
+ pos = after.end + 1;
62
+ safe = pos;
63
+ continue;
64
+ }
65
+ if (after.end >= code.length) {
66
+ return code.length;
67
+ }
68
+ if (after.newline && !continuesExpression(code, after.end)) {
69
+ pos = after.end;
70
+ safe = pos;
71
+ continue;
72
+ }
73
+ return pos;
74
+ }
75
+ }
76
+ var LINE_TERMINATOR = /[\n\r\u2028\u2029]/;
77
+ function skipTrivia(code, from) {
78
+ let pos = from;
79
+ let newline = false;
80
+ while (pos < code.length) {
81
+ const ch = code[pos];
82
+ if (LINE_TERMINATOR.test(ch)) {
83
+ newline = true;
84
+ pos++;
85
+ } else if (/\s/.test(ch)) {
86
+ pos++;
87
+ } else if (ch === "/" && code[pos + 1] === "/") {
88
+ const nl = code.slice(pos).search(LINE_TERMINATOR);
89
+ if (nl === -1) return { end: code.length, newline };
90
+ pos += nl;
91
+ } else if (ch === "/" && code[pos + 1] === "*") {
92
+ const close = code.indexOf("*/", pos + 2);
93
+ if (close === -1) return void 0;
94
+ if (LINE_TERMINATOR.test(code.slice(pos + 2, close))) newline = true;
95
+ pos = close + 2;
96
+ } else {
97
+ break;
98
+ }
99
+ }
100
+ return { end: pos, newline };
101
+ }
102
+ function scanString(code, start) {
103
+ const quote = code[start];
104
+ let pos = start + 1;
105
+ while (pos < code.length) {
106
+ const ch = code[pos];
107
+ if (ch === quote) return pos + 1;
108
+ if (ch === "\\") {
109
+ pos += code[pos + 1] === "\r" && code[pos + 2] === "\n" ? 3 : 2;
110
+ continue;
111
+ }
112
+ if (ch === "\n" || ch === "\r") return void 0;
113
+ pos++;
114
+ }
115
+ return void 0;
116
+ }
117
+ function continuesExpression(code, pos) {
118
+ const rest = code.slice(pos, pos + 12);
119
+ if (/^(?:\+\+|--)/.test(rest)) return false;
120
+ return /^(?:[.,([?:<>=&|^%*/`+\-~]|!=|in(?![\w$])|instanceof(?![\w$]))/.test(rest);
121
+ }
122
+
123
+ // src/build/shared/snippet.ts
124
+ function jsStringLiteral(value) {
125
+ return JSON.stringify(value).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029").replace(/</g, "\\u003c");
126
+ }
127
+ function createSnippet(debugId, release) {
128
+ const id = jsStringLiteral(debugId);
129
+ const setRelease = release === void 0 ? "" : `g.${RELEASE_GLOBAL}||(g.${RELEASE_GLOBAL}=${jsStringLiteral(release)});`;
130
+ return ';!function(){try{var g="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{};' + setRelease + `var s=(new Error).stack;s&&((g.${DEBUG_ID_GLOBAL}=g.${DEBUG_ID_GLOBAL}||{})[s]=${id})}catch(e){}}();`;
131
+ }
132
+
133
+ // src/build/shared/vlq.ts
134
+ var CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
135
+ var INDEX = new Int8Array(128).fill(-1);
136
+ for (let i = 0; i < CHARS.length; i++) INDEX[CHARS.charCodeAt(i)] = i;
137
+ function decodeMappings(mappings) {
138
+ const lines = [];
139
+ let line = [];
140
+ const state = [0, 0, 0, 0, 0];
141
+ const values = [];
142
+ let value = 0;
143
+ let shift = 0;
144
+ const endSegment = () => {
145
+ if (values.length === 0) return;
146
+ if (values.length !== 1 && values.length !== 4 && values.length !== 5) {
147
+ throw new Error(`Invalid source map segment with ${values.length} fields`);
148
+ }
149
+ state[0] += values[0];
150
+ if (values.length === 1) {
151
+ line.push([state[0]]);
152
+ } else {
153
+ state[1] += values[1];
154
+ state[2] += values[2];
155
+ state[3] += values[3];
156
+ if (values.length === 5) {
157
+ state[4] += values[4];
158
+ line.push([state[0], state[1], state[2], state[3], state[4]]);
159
+ } else {
160
+ line.push([state[0], state[1], state[2], state[3]]);
161
+ }
162
+ }
163
+ values.length = 0;
164
+ };
165
+ for (let i = 0; i < mappings.length; i++) {
166
+ const code = mappings.charCodeAt(i);
167
+ if (code === 44) {
168
+ endSegment();
169
+ } else if (code === 59) {
170
+ endSegment();
171
+ lines.push(line);
172
+ line = [];
173
+ state[0] = 0;
174
+ } else {
175
+ const digit = code < 128 ? INDEX[code] : -1;
176
+ if (digit === -1) throw new Error(`Invalid base64 VLQ character ${JSON.stringify(mappings[i])}`);
177
+ value += (digit & 31) * 2 ** shift;
178
+ if (digit & 32) {
179
+ shift += 5;
180
+ } else {
181
+ const negative = value % 2 === 1;
182
+ const magnitude = Math.floor(value / 2);
183
+ values.push(negative ? -magnitude || 0 : magnitude);
184
+ value = 0;
185
+ shift = 0;
186
+ }
187
+ }
188
+ }
189
+ endSegment();
190
+ lines.push(line);
191
+ return lines;
192
+ }
193
+ function encodeValue(n) {
194
+ let vlq = n < 0 ? -n * 2 + 1 : n * 2;
195
+ let out = "";
196
+ do {
197
+ let digit = vlq % 32;
198
+ vlq = Math.floor(vlq / 32);
199
+ if (vlq > 0) digit |= 32;
200
+ out += CHARS[digit];
201
+ } while (vlq > 0);
202
+ return out;
203
+ }
204
+ function encodeMappings(lines) {
205
+ const state = [0, 0, 0, 0, 0];
206
+ let out = "";
207
+ for (let l = 0; l < lines.length; l++) {
208
+ if (l > 0) out += ";";
209
+ state[0] = 0;
210
+ const segments = lines[l];
211
+ for (let s = 0; s < segments.length; s++) {
212
+ const seg = segments[s];
213
+ if (s > 0) out += ",";
214
+ out += encodeValue(seg[0] - state[0]);
215
+ state[0] = seg[0];
216
+ if (seg.length === 1) continue;
217
+ for (let f = 1; f < seg.length; f++) {
218
+ out += encodeValue(seg[f] - state[f]);
219
+ state[f] = seg[f];
220
+ }
221
+ }
222
+ }
223
+ return out;
224
+ }
225
+
226
+ // src/build/shared/inject.ts
227
+ var SOURCE_MAPPING_URL_LINE = /^[ \t]*\/\/[#@][ \t]+sourceMappingURL=/;
228
+ function findSourceMappingUrlLine(code) {
229
+ let end = code.length;
230
+ while (end > 0) {
231
+ const start = code.lastIndexOf("\n", end - 1) + 1;
232
+ const line = code.slice(start, end);
233
+ if (line.trim() === "") {
234
+ end = start - 1;
235
+ continue;
236
+ }
237
+ return SOURCE_MAPPING_URL_LINE.test(line) ? start : void 0;
238
+ }
239
+ return void 0;
240
+ }
241
+ function planInjection(code, options = {}) {
242
+ const debugId = options.debugId ?? createDebugId(code);
243
+ const urlLine = findSourceMappingUrlLine(code);
244
+ const comment = urlLine !== void 0 ? { offset: urlLine, text: `${debugIdComment(debugId)}
245
+ ` } : {
246
+ offset: code.length,
247
+ text: `${code.length === 0 || code.endsWith("\n") ? "" : "\n"}${debugIdComment(debugId)}
248
+ `
249
+ };
250
+ const offset = Math.min(findInsertionOffset(code), comment.offset);
251
+ const atLineStart = offset === 0 || code[offset - 1] === "\n";
252
+ const snippetText = createSnippet(debugId, options.release);
253
+ const snippet = { offset, text: atLineStart ? `${snippetText}
254
+ ` : snippetText };
255
+ return { debugId, snippet, comment };
256
+ }
257
+ function applyToCode(code, insertions) {
258
+ const sorted = insertions.map((ins, index) => ({ ins, index })).sort((a, b) => a.ins.offset - b.ins.offset || a.index - b.index);
259
+ let out = "";
260
+ let at = 0;
261
+ for (const { ins } of sorted) {
262
+ out += code.slice(at, ins.offset) + ins.text;
263
+ at = ins.offset;
264
+ }
265
+ return out + code.slice(at);
266
+ }
267
+ function lineAndColumn(code, offset) {
268
+ let line = 0;
269
+ let lineStart = 0;
270
+ for (let i = code.indexOf("\n"); i !== -1 && i < offset; i = code.indexOf("\n", i + 1)) {
271
+ line++;
272
+ lineStart = i + 1;
273
+ }
274
+ return { line, column: offset - lineStart };
275
+ }
276
+ function shiftSegments(lines, line, column, text) {
277
+ while (lines.length <= line) lines.push([]);
278
+ const segments = lines[line];
279
+ const newlines = text.split("\n").length - 1;
280
+ if (newlines === 0) {
281
+ for (const seg of segments) if (seg[0] >= column) seg[0] += text.length;
282
+ return;
283
+ }
284
+ const lastLineLength = text.length - text.lastIndexOf("\n") - 1;
285
+ const before2 = [];
286
+ const after = [];
287
+ for (const seg of segments) {
288
+ if (seg[0] >= column) {
289
+ seg[0] = seg[0] - column + lastLineLength;
290
+ after.push(seg);
291
+ } else {
292
+ before2.push(seg);
293
+ }
294
+ }
295
+ const inserted = Array.from({ length: newlines - 1 }, () => []);
296
+ lines.splice(line, 1, before2, ...inserted, after);
297
+ }
298
+ var before = (a, line, column) => a.line < line || a.line === line && a.column < column;
299
+ function movedPosition(p, at) {
300
+ const newlines = at.text.split("\n").length - 1;
301
+ if (newlines === 0) return p.line === at.line ? { line: p.line, column: p.column + at.text.length } : p;
302
+ const lastLineLength = at.text.length - at.text.lastIndexOf("\n") - 1;
303
+ return { line: p.line + newlines, column: p.line === at.line ? p.column - at.column + lastLineLength : p.column };
304
+ }
305
+ function shiftAt(map, ordered) {
306
+ if (Array.isArray(map.sections)) {
307
+ const sections = map.sections.map((sec) => ({ ...sec, offset: { line: Number(sec.offset?.line) || 0, column: Number(sec.offset?.column) || 0 } }));
308
+ for (const at of ordered) {
309
+ let inside = -1;
310
+ for (let i = 0; i < sections.length; i++) if (before(sections[i].offset, at.line, at.column)) inside = i;
311
+ for (let i = 0; i < sections.length; i++) {
312
+ const sec = sections[i];
313
+ if (!before(sec.offset, at.line, at.column)) sec.offset = movedPosition(sec.offset, at);
314
+ }
315
+ if (inside >= 0) {
316
+ const sec = sections[inside];
317
+ if (!sec.map || typeof sec.map !== "object") throw new Error("Index source map sections with a `url` instead of a `map` are not supported");
318
+ const rel = { line: at.line - sec.offset.line, column: at.line === sec.offset.line ? at.column - sec.offset.column : at.column, text: at.text };
319
+ sec.map = shiftAt(sec.map, [rel]);
320
+ }
321
+ }
322
+ return { ...map, sections };
323
+ }
324
+ const lines = decodeMappings(map.mappings ?? "");
325
+ for (const at of ordered) shiftSegments(lines, at.line, at.column, at.text);
326
+ return { ...map, mappings: encodeMappings(lines) };
327
+ }
328
+ function shiftSourceMap(map, code, insertions) {
329
+ const ordered = insertions.map((ins, index) => ({ ins, index })).sort((a, b) => b.ins.offset - a.ins.offset || b.index - a.index).map(({ ins }) => ({ ...lineAndColumn(code, ins.offset), text: ins.text }));
330
+ return shiftAt(map, ordered);
331
+ }
332
+ function hasStarkoRegistration(code, debugId) {
333
+ const id = debugId.toLowerCase();
334
+ return code.includes(`(g.${DEBUG_ID_GLOBAL}=g.${DEBUG_ID_GLOBAL}||{})[s]=${jsStringLiteral(id)}`);
335
+ }
336
+ function hasNativeRegistration(code, debugId) {
337
+ const head = code.slice(0, 4096);
338
+ const id = debugId.toLowerCase();
339
+ if (!head.toLowerCase().includes(id)) return false;
340
+ if (!/_(?:sentryD|d)ebugIds\b/.test(head)) return false;
341
+ return new RegExp(`\\]\\s*=\\s*["']${id}["']`, "i").test(head);
342
+ }
343
+ function injectDebugId(code, map, options = {}) {
344
+ const existing = findDebugId(code);
345
+ if (existing) {
346
+ const withId = (m) => m.debugId === existing ? m : { ...m, debugId: existing };
347
+ if (hasStarkoRegistration(code, existing) || options.keepNativelyRegistered && hasNativeRegistration(code, existing)) {
348
+ return { code, map: map && withId(map), debugId: existing, injected: false, kind: "none" };
349
+ }
350
+ const plan2 = planInjection(code, { ...options, debugId: existing });
351
+ const newMap2 = map ? withId(shiftSourceMap(map, code, [plan2.snippet])) : void 0;
352
+ return { code: applyToCode(code, [plan2.snippet]), map: newMap2, debugId: existing, injected: true, kind: "snippet" };
353
+ }
354
+ const plan = planInjection(code, options);
355
+ const insertions = [plan.snippet, plan.comment];
356
+ const newMap = map ? { ...shiftSourceMap(map, code, insertions), debugId: plan.debugId } : void 0;
357
+ return { code: applyToCode(code, insertions), map: newMap, debugId: plan.debugId, injected: true, kind: "full" };
358
+ }
359
+ var COMMIT_ENV_VARS = [
360
+ "VERCEL_GIT_COMMIT_SHA",
361
+ "GITHUB_SHA",
362
+ "CI_COMMIT_SHA",
363
+ // GitLab
364
+ "BITBUCKET_COMMIT",
365
+ "CIRCLE_SHA1",
366
+ "CF_PAGES_COMMIT_SHA",
367
+ "RENDER_GIT_COMMIT",
368
+ "RAILWAY_GIT_COMMIT_SHA",
369
+ "COMMIT_REF",
370
+ // Netlify
371
+ "BUILDKITE_COMMIT",
372
+ "DRONE_COMMIT_SHA",
373
+ "TRAVIS_COMMIT",
374
+ "BUILD_SOURCEVERSION",
375
+ // Azure Pipelines
376
+ "CODEBUILD_RESOLVED_SOURCE_VERSION",
377
+ "HEROKU_SLUG_COMMIT",
378
+ "SOURCE_VERSION",
379
+ // Heroku
380
+ "GIT_COMMIT"
381
+ // Jenkins
382
+ ];
383
+ var BRANCH_ENV_VARS = [
384
+ "VERCEL_GIT_COMMIT_REF",
385
+ "GITHUB_HEAD_REF",
386
+ "GITHUB_REF_NAME",
387
+ "CI_COMMIT_REF_NAME",
388
+ "BITBUCKET_BRANCH",
389
+ "CIRCLE_BRANCH",
390
+ "CF_PAGES_BRANCH",
391
+ "RENDER_GIT_BRANCH",
392
+ "RAILWAY_GIT_BRANCH",
393
+ "BRANCH",
394
+ // Netlify
395
+ "BUILDKITE_BRANCH",
396
+ "DRONE_BRANCH",
397
+ "TRAVIS_BRANCH",
398
+ "BUILD_SOURCEBRANCHNAME",
399
+ "GIT_BRANCH"
400
+ ];
401
+ function clean(value) {
402
+ const trimmed = value?.trim();
403
+ return trimmed ? trimmed : void 0;
404
+ }
405
+ function firstEnv(env, names) {
406
+ for (const name of names) {
407
+ const value = clean(env[name]);
408
+ if (value) return value;
409
+ }
410
+ return void 0;
411
+ }
412
+ function git(args, cwd) {
413
+ try {
414
+ return clean(
415
+ execFileSync("git", args, {
416
+ cwd,
417
+ encoding: "utf8",
418
+ stdio: ["ignore", "pipe", "ignore"],
419
+ timeout: 5e3,
420
+ windowsHide: true
421
+ })
422
+ );
423
+ } catch {
424
+ return void 0;
425
+ }
426
+ }
427
+ function resolveCommit(options = {}) {
428
+ const env = options.env ?? process.env;
429
+ return firstEnv(env, COMMIT_ENV_VARS) ?? (options.useGit === false ? void 0 : git(["rev-parse", "HEAD"], options.cwd));
430
+ }
431
+ function resolveRelease(explicit, options = {}) {
432
+ const env = options.env ?? process.env;
433
+ const release = clean(explicit) ?? clean(env.STARKO_RELEASE) ?? resolveCommit(options);
434
+ return release === void 0 ? void 0 : release.slice(0, LIMITS.MAX_RELEASE);
435
+ }
436
+ function resolveReleaseInfo(explicit, options = {}) {
437
+ const version2 = resolveRelease(explicit, options);
438
+ if (version2 === void 0) return void 0;
439
+ const env = options.env ?? process.env;
440
+ const commit = resolveCommit(options);
441
+ let branch = firstEnv(env, BRANCH_ENV_VARS);
442
+ if (!branch && options.useGit !== false) {
443
+ const head = git(["rev-parse", "--abbrev-ref", "HEAD"], options.cwd);
444
+ if (head && head !== "HEAD") branch = head;
445
+ }
446
+ const info = { version: version2 };
447
+ if (commit) info.commit = commit;
448
+ if (branch) info.branch = branch;
449
+ return info;
450
+ }
451
+
452
+ // src/build/shared/options.ts
453
+ var DEFAULT_UPLOAD_TIMEOUT_MS = 18e4;
454
+ var DEFAULT_UPLOAD_CONCURRENCY = 8;
455
+ var MAX_UPLOAD_CONCURRENCY = 16;
456
+ var DEFAULT_BULK_UPLOAD_CONCURRENCY = SOURCEMAP_BULK_UPLOAD_CONCURRENCY;
457
+ function resolveUploadConcurrency(value, defaultValue = DEFAULT_UPLOAD_CONCURRENCY) {
458
+ if (value === void 0 || !Number.isFinite(value)) return defaultValue;
459
+ return Math.min(MAX_UPLOAD_CONCURRENCY, Math.max(1, Math.floor(value)));
460
+ }
461
+ function shouldDeleteSourcemaps(owner, options) {
462
+ if (owner === "starko") return true;
463
+ return options.deleteSourcemapsAfterUpload === true && !options.dryRun;
464
+ }
465
+ var NO_API_KEY_MESSAGE = "no API key (set apiKey or STARKO_API_KEY): source maps are not switched on, injected or uploaded, and the build output is left as it is";
466
+ function errorMessage(error) {
467
+ if (error instanceof Error) return error.message;
468
+ try {
469
+ return String(error);
470
+ } catch {
471
+ return "unknown error";
472
+ }
473
+ }
474
+ function redact(message, secrets) {
475
+ let out = message;
476
+ for (const secret of secrets) {
477
+ if (secret && secret.length >= 4) out = out.split(secret).join("[redacted]");
478
+ }
479
+ return out;
480
+ }
481
+ function createLogger(options = {}) {
482
+ const prefix = options.prefix ?? "[starko]";
483
+ const secrets = options.secrets ?? [];
484
+ const sink = options.sink ?? ((level, line) => level === "info" ? console.log(line) : level === "warn" ? console.warn(line) : console.error(line));
485
+ const write = (level) => (message) => {
486
+ if (!options.silent) sink(level, prefix ? `${prefix} ${redact(message, secrets)}` : redact(message, secrets));
487
+ };
488
+ return { info: write("info"), warn: write("warn"), error: write("error") };
489
+ }
490
+ function resolveConnection(options, env = process.env) {
491
+ const apiKey = options.apiKey?.trim() || env.STARKO_API_KEY?.trim() || void 0;
492
+ const host = (options.host?.trim() || env.STARKO_HOST?.trim() || DEFAULT_HOST).replace(/\/+$/, "");
493
+ return { apiKey, host };
494
+ }
495
+ function escapeRegExp(text) {
496
+ return text.replace(/[.+^${}()|[\]\\]/g, "\\$&");
497
+ }
498
+ function globToRegExp(glob) {
499
+ const pattern = glob.includes("/") ? glob.replace(/^\.\//, "") : `**/${glob}`;
500
+ let re = "";
501
+ for (let i = 0; i < pattern.length; i++) {
502
+ const ch = pattern[i];
503
+ if (ch === "*") {
504
+ if (pattern[i + 1] === "*") {
505
+ const slash = pattern[i + 2] === "/";
506
+ re += slash ? "(?:.*/)?" : ".*";
507
+ i += slash ? 2 : 1;
508
+ } else {
509
+ re += "[^/]*";
510
+ }
511
+ } else if (ch === "?") {
512
+ re += "[^/]";
513
+ } else {
514
+ re += escapeRegExp(ch);
515
+ }
516
+ }
517
+ return new RegExp(`^${re}$`);
518
+ }
519
+ var JS_FILE = /\.(?:m|c)?js$/;
520
+ var DEFAULT_EXCLUDE = ["**/node_modules/**"];
521
+ function toArray(value) {
522
+ if (value === void 0) return void 0;
523
+ return Array.isArray(value) ? value : [value];
524
+ }
525
+ function test(pattern, path2) {
526
+ if (typeof pattern === "string") return globToRegExp(pattern).test(path2);
527
+ pattern.lastIndex = 0;
528
+ return pattern.test(path2);
529
+ }
530
+ function createFileFilter(options) {
531
+ const include = toArray(options.include);
532
+ const exclude = toArray(options.exclude) ?? DEFAULT_EXCLUDE;
533
+ return (relativePath) => {
534
+ const path2 = relativePath.replace(/\\/g, "/");
535
+ if (!JS_FILE.test(path2)) return false;
536
+ if (include && !include.some((p) => test(p, path2))) return false;
537
+ return !exclude.some((p) => test(p, path2));
538
+ };
539
+ }
540
+ var TEMP_SUFFIX = ".starko-tmp";
541
+ var SHIFTED_FOR_FIELD = "x_starko_shifted_for";
542
+ var FILES_IN_PARALLEL = 8;
543
+ var REWRITES_IN_PARALLEL = 2;
544
+ async function forEachLimit(items, limit, fn) {
545
+ let next = 0;
546
+ const workers = Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, async () => {
547
+ while (next < items.length) {
548
+ const index = next++;
549
+ await fn(items[index], index);
550
+ }
551
+ });
552
+ await Promise.all(workers);
553
+ }
554
+ function createLimiter(limit) {
555
+ let active = 0;
556
+ const waiting = [];
557
+ return async (fn) => {
558
+ if (active >= limit) await new Promise((resolve) => waiting.push(resolve));
559
+ active++;
560
+ try {
561
+ return await fn();
562
+ } finally {
563
+ active--;
564
+ waiting.shift()?.();
565
+ }
566
+ };
567
+ }
568
+ var SOURCE_MAPPING_URL = /^[ \t]*\/\/[#@][ \t]+sourceMappingURL=[ \t]*(\S*)[ \t]*$/;
569
+ var CSS_SOURCE_MAPPING_URL = /\n?\/\*[#@] sourceMappingURL=([^*\s]+)\s*\*\/\s*$/;
570
+ var REMOTE_URL = /^(?:[a-z][a-z0-9+.-]*:)?\/\//i;
571
+ function findSourceMappingUrl(code) {
572
+ let end = code.length;
573
+ for (let i = 0; i < 16 && end > 0; i++) {
574
+ const start = code.lastIndexOf("\n", end - 1) + 1;
575
+ const line = code.slice(start, end).replace(/\r$/, "");
576
+ const lineEnd = end;
577
+ end = start - 1;
578
+ if (line.trim() === "") continue;
579
+ if (!line.trimStart().startsWith("//")) return void 0;
580
+ const match = SOURCE_MAPPING_URL.exec(line);
581
+ if (match) return { url: match[1], start, end: lineEnd };
582
+ }
583
+ return void 0;
584
+ }
585
+ function localMapReference(url) {
586
+ if (!url || url.startsWith("data:")) return void 0;
587
+ const clean2 = url.replace(/[?#].*$/, "");
588
+ let decoded = clean2;
589
+ try {
590
+ decoded = decodeURI(clean2);
591
+ } catch {
592
+ }
593
+ if (!decoded || REMOTE_URL.test(decoded) || /^[a-z][a-z0-9+.-]*:/i.test(decoded)) return void 0;
594
+ if (path.isAbsolute(decoded) || path.posix.isAbsolute(decoded) || path.win32.isAbsolute(decoded)) return void 0;
595
+ return decoded;
596
+ }
597
+ function isInside(root, target) {
598
+ const rel = path.relative(root, target);
599
+ return rel !== "" && rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);
600
+ }
601
+ async function containedFile(realRoot2, candidate) {
602
+ try {
603
+ const real = await promises.realpath(candidate);
604
+ if (!isInside(realRoot2, real)) return void 0;
605
+ return (await promises.stat(real)).isFile() ? real : void 0;
606
+ } catch {
607
+ return void 0;
608
+ }
609
+ }
610
+ async function realRoot(dir) {
611
+ return promises.realpath(path.resolve(dir));
612
+ }
613
+ async function resolveMapPath(jsPath, code, root) {
614
+ const rootReal = await realRoot(root);
615
+ const jsReal = await containedFile(rootReal, jsPath);
616
+ if (!jsReal) return void 0;
617
+ const candidates = [];
618
+ const ref = findSourceMappingUrl(code)?.url;
619
+ const local = ref === void 0 ? void 0 : localMapReference(ref);
620
+ if (local !== void 0) candidates.push(path.resolve(path.dirname(jsReal), local));
621
+ candidates.push(`${jsReal}.map`);
622
+ for (const candidate of candidates) {
623
+ const contained = await containedFile(rootReal, candidate);
624
+ if (contained) return contained;
625
+ }
626
+ return void 0;
627
+ }
628
+ async function listFiles(dir, onError) {
629
+ const out = [];
630
+ const walk = async (current, isRoot) => {
631
+ let entries;
632
+ try {
633
+ entries = await promises.readdir(current, { withFileTypes: true });
634
+ } catch (error) {
635
+ if (isRoot || !onError) throw error;
636
+ onError(current, error);
637
+ return;
638
+ }
639
+ for (const entry of entries) {
640
+ const full = path.join(current, entry.name);
641
+ if (entry.isDirectory()) await walk(full, false);
642
+ else if (entry.isFile()) out.push(full);
643
+ }
644
+ };
645
+ await walk(dir, true);
646
+ return out.sort();
647
+ }
648
+ async function findBundles(dir, filter) {
649
+ const root = await realRoot(dir);
650
+ const bundles = [];
651
+ const withoutMap = [];
652
+ const unreadable = [];
653
+ const files = await listFiles(root, (d, error) => unreadable.push({ file: toRelative(root, d), reason: errorMessage(error) }));
654
+ const found = [];
655
+ await forEachLimit(files, FILES_IN_PARALLEL, async (file, index) => {
656
+ const relativePath = toRelative(root, file);
657
+ if (!filter(relativePath)) return;
658
+ try {
659
+ const code = await promises.readFile(file, "utf8");
660
+ const mapPath = await resolveMapPath(file, code, root);
661
+ found[index] = mapPath ? { bundle: { jsPath: file, relativePath, mapPath, debugId: findDebugId(code) } } : { withoutMap: relativePath };
662
+ } catch (error) {
663
+ found[index] = { unreadable: { file: relativePath, reason: errorMessage(error) } };
664
+ }
665
+ });
666
+ for (const f of found) {
667
+ if (!f) continue;
668
+ if ("bundle" in f) bundles.push(f.bundle);
669
+ else if ("withoutMap" in f) withoutMap.push(f.withoutMap);
670
+ else unreadable.push(f.unreadable);
671
+ }
672
+ return { bundles, withoutMap, unreadable };
673
+ }
674
+ function toRelative(root, file) {
675
+ return path.relative(root, file).split(path.sep).join("/");
676
+ }
677
+ async function readMap(mapPath) {
678
+ const map = JSON.parse(await promises.readFile(mapPath, "utf8"));
679
+ if (!map || typeof map !== "object" || typeof map.version !== "number") throw new Error("not a source map");
680
+ return map;
681
+ }
682
+ function mapNamesDebugId(raw, id) {
683
+ const needle = `"debugId":"${id}"`;
684
+ const first = raw.indexOf("{");
685
+ if (first === -1 || raw.subarray(0, first).toString("utf8").trim() !== "") return false;
686
+ const at = raw.indexOf(needle);
687
+ if (at === -1) return false;
688
+ const nested = raw.indexOf("{", first + 1);
689
+ if (nested === -1 || nested > at) return true;
690
+ const tail = raw.subarray(raw.lastIndexOf(needle) + needle.length);
691
+ return tail.length <= 64 && tail.toString("utf8").trim() === "}";
692
+ }
693
+ var NOFOLLOW = constants.O_NOFOLLOW ?? 0;
694
+ async function writeTemp(file, content) {
695
+ const temp = `${file}.${randomBytes(8).toString("hex")}${TEMP_SUFFIX}`;
696
+ const handle = await promises.open(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | NOFOLLOW, 420);
697
+ try {
698
+ await handle.writeFile(content);
699
+ } finally {
700
+ await handle.close();
701
+ }
702
+ return temp;
703
+ }
704
+ async function checkReplaced(file, root) {
705
+ const st = await promises.lstat(file);
706
+ if (!st.isFile()) throw new Error(`${file} is not a regular file after it was replaced`);
707
+ if (root && !isInside(await promises.realpath(root), await promises.realpath(file))) throw new Error(`${file} is not inside ${root} after it was replaced`);
708
+ }
709
+ async function replaceFile(file, content, root) {
710
+ let temp;
711
+ try {
712
+ temp = await writeTemp(file, content);
713
+ await promises.rename(temp, file);
714
+ temp = void 0;
715
+ await checkReplaced(file, root);
716
+ } catch (error) {
717
+ if (temp) await promises.unlink(temp).catch(() => void 0);
718
+ throw error;
719
+ }
720
+ }
721
+ async function replacePair(mapPath, mapText, jsPath, jsText, root) {
722
+ let mapTemp;
723
+ let jsTemp;
724
+ try {
725
+ mapTemp = await writeTemp(mapPath, mapText);
726
+ jsTemp = await writeTemp(jsPath, jsText);
727
+ await promises.rename(mapTemp, mapPath);
728
+ mapTemp = void 0;
729
+ await promises.rename(jsTemp, jsPath);
730
+ jsTemp = void 0;
731
+ await checkReplaced(mapPath, root);
732
+ await checkReplaced(jsPath, root);
733
+ } catch (error) {
734
+ if (mapTemp) await promises.unlink(mapTemp).catch(() => void 0);
735
+ if (jsTemp) await promises.unlink(jsTemp).catch(() => void 0);
736
+ throw error;
737
+ }
738
+ }
739
+ async function removeStaleTemps(root) {
740
+ const walk = async (dir) => {
741
+ let entries;
742
+ try {
743
+ entries = await promises.readdir(dir, { withFileTypes: true });
744
+ } catch {
745
+ return;
746
+ }
747
+ for (const entry of entries) {
748
+ const full = path.join(dir, entry.name);
749
+ if (entry.name.endsWith(TEMP_SUFFIX) && (entry.isFile() || entry.isSymbolicLink())) await promises.unlink(full).catch(() => void 0);
750
+ else if (entry.isDirectory()) await walk(full);
751
+ }
752
+ };
753
+ await walk(root);
754
+ }
755
+ async function injectDirectory(dir, options) {
756
+ const root = await realRoot(dir);
757
+ if (!options.dryRun) await removeStaleTemps(root);
758
+ const { bundles, unreadable } = await findBundles(root, options.filter);
759
+ const result = { injected: [], alreadyInjected: [], skipped: [...unreadable] };
760
+ const byMap = /* @__PURE__ */ new Map();
761
+ for (const b of bundles) byMap.set(b.mapPath, [...byMap.get(b.mapPath) ?? [], b]);
762
+ const outcomes = [];
763
+ const rewrite = createLimiter(REWRITES_IN_PARALLEL);
764
+ await forEachLimit(bundles, FILES_IN_PARALLEL, async (bundle, index) => {
765
+ const file = bundle.relativePath;
766
+ try {
767
+ const code = await promises.readFile(bundle.jsPath, "utf8");
768
+ const shared = byMap.get(bundle.mapPath).length > 1;
769
+ const existing = findDebugId(code);
770
+ if (existing && (hasStarkoRegistration(code, existing) || options.keepNativelyRegistered && hasNativeRegistration(code, existing)) && mapNamesDebugId(await promises.readFile(bundle.mapPath), existing)) {
771
+ outcomes[index] = { list: "alreadyInjected", entry: { file, debugId: existing } };
772
+ return;
773
+ }
774
+ outcomes[index] = await rewrite(async () => {
775
+ const map = await readMap(bundle.mapPath);
776
+ const fingerprint = createDebugId(code);
777
+ const alreadyShifted = map[SHIFTED_FOR_FIELD] === fingerprint;
778
+ const out = injectDebugId(code, alreadyShifted ? void 0 : map, { release: options.release, keepNativelyRegistered: options.keepNativelyRegistered });
779
+ if (out.kind === "none") {
780
+ if (map.debugId !== out.debugId && !options.dryRun && !shared) {
781
+ await replaceFile(bundle.mapPath, JSON.stringify({ ...map, debugId: out.debugId }), root);
782
+ }
783
+ return { list: "alreadyInjected", entry: { file, debugId: out.debugId } };
784
+ }
785
+ if (shared) {
786
+ return { list: "skipped", entry: { file, reason: `its source map ${path.basename(bundle.mapPath)} is shared with another bundle` } };
787
+ }
788
+ if (!options.dryRun) {
789
+ const newMap = alreadyShifted ? { ...map, debugId: out.debugId } : { ...out.map, [SHIFTED_FOR_FIELD]: fingerprint };
790
+ await replacePair(bundle.mapPath, JSON.stringify(newMap), bundle.jsPath, out.code, root);
791
+ }
792
+ return { list: "injected", entry: { file, debugId: out.debugId, existingId: out.kind === "snippet" } };
793
+ });
794
+ } catch (error) {
795
+ outcomes[index] = { list: "skipped", entry: { file, reason: errorMessage(error) } };
796
+ }
797
+ });
798
+ for (const o of outcomes) {
799
+ if (!o) continue;
800
+ if (o.list === "injected") result.injected.push(o.entry);
801
+ else if (o.list === "alreadyInjected") result.alreadyInjected.push(o.entry);
802
+ else result.skipped.push(o.entry);
803
+ }
804
+ return result;
805
+ }
806
+ async function collectUploads(dir, filter) {
807
+ const { bundles, unreadable } = await findBundles(dir, filter);
808
+ const collected = await collectUploadsFor(bundles);
809
+ return { ...collected, unreadable: [...unreadable, ...collected.unreadable] };
810
+ }
811
+ async function loadMapFor(mapPath, chunkId) {
812
+ const raw = await promises.readFile(mapPath);
813
+ if (raw.includes(`"debugId":"${chunkId}"`)) return raw;
814
+ const map = JSON.parse(raw.toString("utf8"));
815
+ return Buffer.from(JSON.stringify({ ...map, debugId: chunkId }), "utf8");
816
+ }
817
+ async function collectUploadsFor(bundles) {
818
+ const result = { entries: [], missingDebugId: [], unreadable: [] };
819
+ for (const bundle of bundles) {
820
+ try {
821
+ let chunkId = bundle.debugId ?? findDebugId(await promises.readFile(bundle.jsPath, "utf8"));
822
+ if (!chunkId) {
823
+ const map = await readMap(bundle.mapPath);
824
+ chunkId = isDebugId(map.debugId) ? map.debugId.toLowerCase() : void 0;
825
+ }
826
+ if (!chunkId) {
827
+ result.missingDebugId.push(bundle.relativePath);
828
+ continue;
829
+ }
830
+ const id = chunkId;
831
+ const mapPath = bundle.mapPath;
832
+ result.entries.push({ chunkId: id, load: () => loadMapFor(mapPath, id), fileName: bundle.relativePath, jsPath: bundle.jsPath, mapPath });
833
+ } catch (error) {
834
+ result.unreadable.push({ file: bundle.relativePath, reason: errorMessage(error) });
835
+ }
836
+ }
837
+ return result;
838
+ }
839
+ function stripSourceMappingUrl(code, ref) {
840
+ let cut = ref.end;
841
+ if (code[cut] === "\n") cut++;
842
+ return code.slice(0, ref.start) + code.slice(cut);
843
+ }
844
+ var MAP_FILE = /\.map$/;
845
+ var CODE_FILE = /\.(?:m|c)?js$/;
846
+ var CSS_FILE = /\.css$/;
847
+ async function exists(file) {
848
+ try {
849
+ await promises.lstat(file);
850
+ return true;
851
+ } catch {
852
+ return false;
853
+ }
854
+ }
855
+ async function deleteAllSourcemaps(root, logger, options = {}) {
856
+ let files;
857
+ let rootReal = root;
858
+ try {
859
+ rootReal = await realRoot(root);
860
+ files = await listFiles(rootReal, (d, error) => logger?.warn(`could not read ${d}: ${errorMessage(error)}`));
861
+ } catch (error) {
862
+ if (error?.code !== "ENOENT") logger?.warn(`could not delete the source maps under ${root}: ${errorMessage(error)}`);
863
+ return 0;
864
+ }
865
+ let deleted = 0;
866
+ for (const file of files) {
867
+ if (!MAP_FILE.test(file)) continue;
868
+ try {
869
+ await promises.rm(file, { force: true });
870
+ deleted++;
871
+ } catch (error) {
872
+ logger?.warn(`could not delete ${file}: ${errorMessage(error)}`);
873
+ }
874
+ }
875
+ for (const file of files) {
876
+ const js = CODE_FILE.test(file);
877
+ if (!js && !CSS_FILE.test(file)) continue;
878
+ try {
879
+ const code = await promises.readFile(file, "utf8");
880
+ if (js) {
881
+ const ref = findSourceMappingUrl(code);
882
+ const local = ref && localMapReference(ref.url);
883
+ if (!ref || local === void 0 || !local.endsWith(".map")) continue;
884
+ if (await exists(path.resolve(path.dirname(file), local))) continue;
885
+ const rel = toRelative(rootReal, file);
886
+ if (options.keepComment && options.keepComment(rel, code)) {
887
+ if (options.onKept) options.onKept(rel);
888
+ continue;
889
+ }
890
+ await replaceFile(file, stripSourceMappingUrl(code, ref), rootReal);
891
+ } else {
892
+ const match = CSS_SOURCE_MAPPING_URL.exec(code);
893
+ const local = match && localMapReference(match[1]);
894
+ if (!match || !local || !local.endsWith(".map")) continue;
895
+ if (await exists(path.resolve(path.dirname(file), local))) continue;
896
+ await replaceFile(file, code.slice(0, match.index), rootReal);
897
+ }
898
+ } catch (error) {
899
+ logger?.warn(`could not remove the sourceMappingURL comment from ${file}: ${errorMessage(error)}`);
900
+ }
901
+ }
902
+ return deleted;
903
+ }
904
+ function stripCssSourceMappingUrl(css, shouldStrip) {
905
+ const match = CSS_SOURCE_MAPPING_URL.exec(css);
906
+ return match && shouldStrip(match[1]) ? css.slice(0, match.index) : css;
907
+ }
908
+
909
+ // src/build/shared/version.ts
910
+ var USER_AGENT = `starko-sdk-build/${version}`;
911
+
912
+ // src/build/shared/upload-core.ts
913
+ var DEFAULT_MAX_REQUESTS_PER_MINUTE = 1900;
914
+ var DEFAULT_MAX_BYTES_IN_FLIGHT = 256 * 1024 * 1024;
915
+ var MAX_RETRY_AFTER_MS = 12e4;
916
+ var MAX_RATE_LIMITED_ATTEMPTS = 8;
917
+ var ROUTE_TIMEOUT_MARGIN_MS = 15e3;
918
+ var DEFAULT_TIMEOUT_MS = 3e4;
919
+ var ROUTE_SECONDS = {
920
+ [PATHS.SOURCEMAPS_CHECK]: SOURCEMAP_ROUTE_MAX_SECONDS.CHECK,
921
+ [PATHS.SOURCEMAPS_UPLOAD]: SOURCEMAP_ROUTE_MAX_SECONDS.UPLOAD,
922
+ [PATHS.SOURCEMAPS_COMPLETE]: SOURCEMAP_ROUTE_MAX_SECONDS.COMPLETE,
923
+ [PATHS.SOURCEMAPS_BULK_CHECK]: SOURCEMAP_ROUTE_MAX_SECONDS.BULK_CHECK,
924
+ [PATHS.SOURCEMAPS_BULK_START]: SOURCEMAP_ROUTE_MAX_SECONDS.BULK_START,
925
+ [PATHS.SOURCEMAPS_BULK_FINISH]: SOURCEMAP_ROUTE_MAX_SECONDS.BULK_FINISH
926
+ };
927
+ function routeTimeoutMs(path2) {
928
+ const seconds = ROUTE_SECONDS[path2.split("?")[0]];
929
+ return seconds === void 0 ? DEFAULT_TIMEOUT_MS : seconds * 1e3 + ROUTE_TIMEOUT_MARGIN_MS;
930
+ }
931
+ function wireFileName(fileName) {
932
+ if (fileName.length <= SOURCEMAP_MAX_FILE_NAME) return fileName;
933
+ let tail = fileName.slice(fileName.length - (SOURCEMAP_MAX_FILE_NAME - 1));
934
+ const first = tail.charCodeAt(0);
935
+ if (first >= 56320 && first <= 57343) tail = tail.slice(1);
936
+ return `\u2026${tail}`;
937
+ }
938
+ function createUploadProgress() {
939
+ return { total: 0, checked: 0, uploaded: 0, skipped: 0, failed: 0, sending: 0, bytesSent: 0 };
940
+ }
941
+ var StarkoUploadError = class extends Error {
942
+ constructor(message, options = {}) {
943
+ super(message);
944
+ this.name = "StarkoUploadError";
945
+ this.status = options.status;
946
+ this.fatal = options.fatal ?? false;
947
+ }
948
+ };
949
+ function sha256Hex(data) {
950
+ return createHash("sha256").update(data).digest("hex");
951
+ }
952
+ function abortedError() {
953
+ return new StarkoUploadError("the upload was stopped (deadline reached)", { fatal: true });
954
+ }
955
+ function sleep(ms, signal) {
956
+ return new Promise((resolve, reject) => {
957
+ if (signal?.aborted) return reject(abortedError());
958
+ const onAbort = () => {
959
+ clearTimeout(timer);
960
+ reject(abortedError());
961
+ };
962
+ const timer = setTimeout(() => {
963
+ signal?.removeEventListener("abort", onAbort);
964
+ resolve();
965
+ }, ms);
966
+ signal?.addEventListener("abort", onAbort, { once: true });
967
+ });
968
+ }
969
+ function retryAfterMs(header) {
970
+ if (!header) return void 0;
971
+ const seconds = Number(header);
972
+ if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1e3;
973
+ const date = Date.parse(header);
974
+ return Number.isNaN(date) ? void 0 : Math.max(0, date - Date.now());
975
+ }
976
+ function formatDuration(ms) {
977
+ if (ms < 9950) return `${Number((Math.max(0, ms) / 1e3).toFixed(1))} s`;
978
+ const s = Math.round(ms / 1e3);
979
+ if (s < 120) return `${s} s`;
980
+ if (s < 2 * 3600) return `${Math.round(s / 60)} min`;
981
+ return `${Math.round(s / 3600)} h`;
982
+ }
983
+ function networkReason(error) {
984
+ const base = errorMessage(error);
985
+ const cause = error?.cause;
986
+ const code = typeof cause?.code === "string" ? cause.code : void 0;
987
+ if (code) return `${base} (${code})`;
988
+ if (typeof cause?.message === "string" && cause.message && cause.message !== base) return `${base} (${cause.message})`;
989
+ return base;
990
+ }
991
+ var Pacer = class {
992
+ constructor(perMinute, now = Date.now()) {
993
+ this.perMs = perMinute / 6e4;
994
+ this.burst = Math.max(1, Math.round(this.perMs * 2e3));
995
+ this.tokens = this.burst;
996
+ this.last = now;
997
+ }
998
+ /** Takes a token and returns 0, or returns how long to wait before asking again. */
999
+ reserve(now) {
1000
+ this.tokens = Math.min(this.burst, this.tokens + (now - this.last) * this.perMs);
1001
+ this.last = now;
1002
+ if (this.tokens >= 1) {
1003
+ this.tokens -= 1;
1004
+ return 0;
1005
+ }
1006
+ return Math.max(1, Math.ceil((1 - this.tokens) / this.perMs));
1007
+ }
1008
+ };
1009
+ var Budget = class {
1010
+ constructor(limit) {
1011
+ this.limit = limit;
1012
+ this.used = 0;
1013
+ this.waiters = [];
1014
+ }
1015
+ /** Weight held right now (tests). */
1016
+ get inUse() {
1017
+ return this.used;
1018
+ }
1019
+ async acquire(weight) {
1020
+ const held = await this.hold(weight);
1021
+ return () => held.release();
1022
+ }
1023
+ async hold(weight) {
1024
+ let w = Math.min(Math.max(0, weight), this.limit);
1025
+ if (this.waiters.length === 0 && (this.used === 0 || this.used + w <= this.limit)) {
1026
+ this.used += w;
1027
+ } else {
1028
+ await new Promise((resolve) => this.waiters.push({ weight: w, resolve }));
1029
+ }
1030
+ let released = false;
1031
+ return {
1032
+ release: () => {
1033
+ if (released) return;
1034
+ released = true;
1035
+ this.used -= w;
1036
+ this.drain();
1037
+ },
1038
+ resize: (next) => {
1039
+ if (released) return;
1040
+ const n = Math.min(Math.max(0, next), this.limit);
1041
+ this.used += n - w;
1042
+ w = n;
1043
+ this.drain();
1044
+ }
1045
+ };
1046
+ }
1047
+ drain() {
1048
+ while (this.waiters.length > 0) {
1049
+ const next = this.waiters[0];
1050
+ if (this.used !== 0 && this.used + next.weight > this.limit) return;
1051
+ this.waiters.shift();
1052
+ this.used += next.weight;
1053
+ next.resolve();
1054
+ }
1055
+ }
1056
+ /** Lets every waiter through (the upload is stopping; they check the stop themselves). */
1057
+ releaseAll() {
1058
+ for (const w of this.waiters.splice(0)) {
1059
+ this.used += w.weight;
1060
+ w.resolve();
1061
+ }
1062
+ }
1063
+ };
1064
+ var Channel = class {
1065
+ constructor() {
1066
+ this.items = [];
1067
+ this.waiters = [];
1068
+ this.lengthWaiters = [];
1069
+ this.closedFlag = false;
1070
+ }
1071
+ get closed() {
1072
+ return this.closedFlag;
1073
+ }
1074
+ get length() {
1075
+ return this.items.length;
1076
+ }
1077
+ push(value) {
1078
+ if (this.closedFlag) return;
1079
+ const waiter = this.waiters.shift();
1080
+ if (waiter) waiter(value);
1081
+ else {
1082
+ this.items.push(value);
1083
+ this.wakeLength();
1084
+ }
1085
+ }
1086
+ next() {
1087
+ if (this.items.length > 0) return Promise.resolve(this.items.shift());
1088
+ if (this.closedFlag) return Promise.resolve(void 0);
1089
+ return new Promise((resolve) => this.waiters.push(resolve));
1090
+ }
1091
+ /** Up to `n` queued items, without waiting. */
1092
+ take(n) {
1093
+ return this.items.splice(0, Math.max(0, n));
1094
+ }
1095
+ /** Everything queued (the queue stays open). */
1096
+ drainAll() {
1097
+ return this.items.splice(0);
1098
+ }
1099
+ /** Resolves once at least `n` items are queued, the queue is closed, or `ms` passed. */
1100
+ waitForLength(n, ms) {
1101
+ if (this.items.length >= n || this.closedFlag || ms <= 0) return Promise.resolve();
1102
+ return new Promise((resolve) => {
1103
+ const entry = {
1104
+ n,
1105
+ resolve: () => {
1106
+ clearTimeout(timer);
1107
+ resolve();
1108
+ }
1109
+ };
1110
+ const timer = setTimeout(() => {
1111
+ const at = this.lengthWaiters.indexOf(entry);
1112
+ if (at !== -1) this.lengthWaiters.splice(at, 1);
1113
+ resolve();
1114
+ }, ms);
1115
+ this.lengthWaiters.push(entry);
1116
+ });
1117
+ }
1118
+ wakeLength() {
1119
+ for (let i = this.lengthWaiters.length - 1; i >= 0; i--) {
1120
+ const w = this.lengthWaiters[i];
1121
+ if (this.items.length >= w.n || this.closedFlag) {
1122
+ this.lengthWaiters.splice(i, 1);
1123
+ w.resolve();
1124
+ }
1125
+ }
1126
+ }
1127
+ /** No more items; with `drop`, the queued ones are discarded too. */
1128
+ close(drop = false) {
1129
+ this.closedFlag = true;
1130
+ if (drop) this.items = [];
1131
+ for (const w of this.waiters.splice(0)) w(void 0);
1132
+ this.wakeLength();
1133
+ }
1134
+ async *[Symbol.asyncIterator]() {
1135
+ for (; ; ) {
1136
+ const v = await this.next();
1137
+ if (v === void 0) return;
1138
+ yield v;
1139
+ }
1140
+ }
1141
+ };
1142
+ async function readItem(item) {
1143
+ const content = item.map ?? (item.load ? await item.load() : void 0);
1144
+ if (content === void 0) throw new Error("no source map content");
1145
+ return typeof content === "string" ? Buffer.from(content, "utf8") : content;
1146
+ }
1147
+ var SecretBook = class {
1148
+ constructor(apiKey) {
1149
+ this.literals = /* @__PURE__ */ new Set();
1150
+ this.hosts = /* @__PURE__ */ new Set();
1151
+ this.add(apiKey, 4);
1152
+ }
1153
+ add(secret, minLength = 8) {
1154
+ if (secret && secret.length >= minLength) this.literals.add(secret);
1155
+ }
1156
+ /**
1157
+ * A signed URL: the URL, its query, its path with the query, and its
1158
+ * `signature` value (raw and decoded) are all redacted from then on.
1159
+ */
1160
+ addSignedUrl(raw) {
1161
+ this.add(raw);
1162
+ let url;
1163
+ try {
1164
+ url = new URL(raw);
1165
+ } catch {
1166
+ return;
1167
+ }
1168
+ this.hosts.add(url.host);
1169
+ if (url.search.length > 1) this.add(url.search.slice(1));
1170
+ this.add(`${url.pathname}${url.search}`);
1171
+ if (url.pathname.length > 1) this.add(url.pathname.slice(1));
1172
+ for (const [name, value] of url.searchParams) {
1173
+ if (/signature|sig$/i.test(name)) {
1174
+ this.add(value);
1175
+ this.add(encodeURIComponent(value));
1176
+ }
1177
+ }
1178
+ }
1179
+ redact(message) {
1180
+ let out = redact(message, Array.from(this.literals).sort((a, b) => b.length - a.length));
1181
+ out = out.replace(/([?&;](?:[a-z0-9_-]*signature|sig|x-amz-signature|x-ut-[a-z-]+|expires)=)[^&\s"'<>)]*/gi, "$1[redacted]");
1182
+ for (const host of this.hosts) {
1183
+ const escaped = host.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1184
+ out = out.replace(new RegExp(`(https?://${escaped})[/?#][^\\s"'<>)]*`, "gi"), "$1/[redacted]");
1185
+ }
1186
+ return out;
1187
+ }
1188
+ };
1189
+ var Session = class {
1190
+ constructor(options) {
1191
+ this.result = { uploaded: [], skipped: [], failed: [] };
1192
+ /** Every request waits until then (a 429's Retry-After). */
1193
+ this.pausedUntil = 0;
1194
+ this.consecutiveNetworkErrors = 0;
1195
+ /** The Starko server's clock minus ours (from its `Date` header): signed URLs expire by the server's clock. */
1196
+ this.clockOffsetMs = 0;
1197
+ this.stopListeners = /* @__PURE__ */ new Set();
1198
+ this.options = options;
1199
+ const doFetch = options.fetch ?? globalThis.fetch;
1200
+ if (typeof doFetch !== "function") throw new StarkoUploadError("global fetch is not available (Node 18 or later is required)", { fatal: true });
1201
+ this.doFetch = doFetch;
1202
+ this.host = options.host.replace(/\/+$/, "");
1203
+ this.apiKey = options.apiKey;
1204
+ this.release = options.release;
1205
+ this.retries = options.retries ?? 4;
1206
+ this.retryBaseMs = options.retryBaseMs ?? 500;
1207
+ this.maxRetryDelayMs = options.maxRetryDelayMs ?? 3e4;
1208
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
1209
+ this.maxConsecutiveNetworkErrors = Math.max(1, options.maxConsecutiveNetworkErrors ?? 3);
1210
+ this.signal = options.signal;
1211
+ this.deadlineAt = options.deadlineAt;
1212
+ this.logger = options.logger;
1213
+ this.progress = options.progress ?? createUploadProgress();
1214
+ this.pacer = new Pacer(Math.max(1, options.maxRequestsPerMinute ?? DEFAULT_MAX_REQUESTS_PER_MINUTE));
1215
+ this.budget = new Budget(Math.max(1, options.maxBytesInFlight ?? DEFAULT_MAX_BYTES_IN_FLIGHT));
1216
+ this.secrets = new SecretBook(options.apiKey);
1217
+ this.signal?.addEventListener("abort", () => this.notifyStop(), { once: true });
1218
+ }
1219
+ stopped() {
1220
+ return this.stop !== void 0 || this.signal?.aborted === true;
1221
+ }
1222
+ /** Stops everything at once with `error` (the first one wins). */
1223
+ stopWith(error) {
1224
+ this.stop ?? (this.stop = error);
1225
+ this.notifyStop();
1226
+ }
1227
+ /** Called once when the upload stops (a fatal error or the deadline); returns the unsubscribe. */
1228
+ onStop(fn) {
1229
+ if (this.stopped()) {
1230
+ fn();
1231
+ return () => void 0;
1232
+ }
1233
+ this.stopListeners.add(fn);
1234
+ return () => this.stopListeners.delete(fn);
1235
+ }
1236
+ notifyStop() {
1237
+ this.budget.releaseAll();
1238
+ for (const fn of Array.from(this.stopListeners)) {
1239
+ this.stopListeners.delete(fn);
1240
+ try {
1241
+ fn();
1242
+ } catch {
1243
+ }
1244
+ }
1245
+ }
1246
+ redact(message) {
1247
+ return this.secrets.redact(message);
1248
+ }
1249
+ info(message) {
1250
+ this.logger?.info(this.redact(message));
1251
+ }
1252
+ warn(message) {
1253
+ this.logger?.warn(this.redact(message));
1254
+ }
1255
+ fail(chunkId, fileName, error) {
1256
+ this.result.failed.push({ chunkId, fileName, error: this.redact(error) });
1257
+ this.progress.failed++;
1258
+ }
1259
+ /** The protocol this upload uses (chosen once). */
1260
+ useProtocol(protocol) {
1261
+ this.result.protocol = protocol;
1262
+ this.progress.protocol = protocol;
1263
+ }
1264
+ skip(chunkId, fileName) {
1265
+ this.result.skipped.push({ chunkId, fileName });
1266
+ this.progress.skipped++;
1267
+ }
1268
+ uploaded(chunkId, fileName, parts, sizeBytes) {
1269
+ this.result.uploaded.push({ chunkId, fileName, parts, sizeBytes });
1270
+ this.progress.uploaded++;
1271
+ }
1272
+ backoff(attempt) {
1273
+ const base = Math.min(this.retryBaseMs * 2 ** attempt, this.maxRetryDelayMs);
1274
+ return Math.round(base * (0.75 + Math.random() * 0.5));
1275
+ }
1276
+ sleep(ms) {
1277
+ return sleep(ms, this.signal);
1278
+ }
1279
+ /** Waits for a 429 pause to end and for a slot under the request rate. */
1280
+ async gate() {
1281
+ for (; ; ) {
1282
+ if (this.signal?.aborted) throw abortedError();
1283
+ const now = Date.now();
1284
+ if (this.pausedUntil > now) {
1285
+ await sleep(this.pausedUntil - now, this.signal);
1286
+ continue;
1287
+ }
1288
+ const wait = this.pacer.reserve(now);
1289
+ if (wait === 0) return;
1290
+ await sleep(wait, this.signal);
1291
+ }
1292
+ }
1293
+ /**
1294
+ * POSTs to the Starko host and returns the `{ ok: true }` body. Network
1295
+ * errors and 5xx are retried with backoff; a 429 pauses every request
1296
+ * (one stopping the upload when it asks for more than two minutes, or
1297
+ * past the deadline); 401 and 403 stop everything; a 3xx is never
1298
+ * followed; anything else non-2xx throws a non-fatal StarkoUploadError
1299
+ * carrying the status (callers decide what it means for their maps).
1300
+ */
1301
+ async request(what, path2, init) {
1302
+ const url = `${this.host}${path2}`;
1303
+ const signal = this.signal;
1304
+ const timeoutMs = this.options.timeoutMs ?? routeTimeoutMs(path2);
1305
+ let rateLimited = 0;
1306
+ for (let attempt = 0; ; ) {
1307
+ await this.gate();
1308
+ const controller = new AbortController();
1309
+ let timedOut = false;
1310
+ const timer = setTimeout(() => {
1311
+ timedOut = true;
1312
+ controller.abort();
1313
+ }, timeoutMs);
1314
+ const onAbort = () => controller.abort();
1315
+ signal?.addEventListener("abort", onAbort, { once: true });
1316
+ const done = () => {
1317
+ clearTimeout(timer);
1318
+ signal?.removeEventListener("abort", onAbort);
1319
+ };
1320
+ let res;
1321
+ let text;
1322
+ try {
1323
+ res = await this.doFetch(url, {
1324
+ method: "POST",
1325
+ headers: {
1326
+ authorization: `Bearer ${this.apiKey}`,
1327
+ "content-type": init.contentType,
1328
+ "user-agent": USER_AGENT
1329
+ },
1330
+ // Node's fetch accepts a Buffer (a Uint8Array); the DOM typings are narrower.
1331
+ body: init.body,
1332
+ // Never followed: a redirect would POST the client's source to another address.
1333
+ redirect: "manual",
1334
+ signal: controller.signal
1335
+ });
1336
+ text = await res.text();
1337
+ } catch (error) {
1338
+ done();
1339
+ if (signal?.aborted) throw abortedError();
1340
+ const reason = timedOut ? `no answer within ${Math.round(timeoutMs / 1e3)} s` : this.redact(networkReason(error));
1341
+ this.consecutiveNetworkErrors++;
1342
+ if (this.consecutiveNetworkErrors >= this.maxConsecutiveNetworkErrors) {
1343
+ throw new StarkoUploadError(`cannot reach ${this.host}: ${this.consecutiveNetworkErrors} network errors in a row (last: ${what}: ${reason})`, {
1344
+ fatal: true
1345
+ });
1346
+ }
1347
+ if (attempt >= this.retries) throw new StarkoUploadError(`${what}: network error after ${attempt + 1} attempts: ${reason}`);
1348
+ this.warn(`${what}: network error (${reason}), retrying`);
1349
+ await sleep(this.backoff(attempt), signal);
1350
+ attempt++;
1351
+ continue;
1352
+ }
1353
+ done();
1354
+ this.consecutiveNetworkErrors = 0;
1355
+ const date = Date.parse(res.headers.get("date") ?? "");
1356
+ if (!Number.isNaN(date)) this.clockOffsetMs = date - Date.now();
1357
+ if (res.status >= 300 && res.status < 400 || res.type === "opaqueredirect") {
1358
+ const location = res.headers.get("location");
1359
+ throw new StarkoUploadError(
1360
+ `${what}: ${this.host} answered with a redirect (${res.status || "3xx"}${location ? ` to ${this.redact(location)}` : ""}); source maps are never sent to another address. Set host to the address Starko answers on.`,
1361
+ { status: res.status || 307, fatal: true }
1362
+ );
1363
+ }
1364
+ let body;
1365
+ try {
1366
+ body = text ? JSON.parse(text) : void 0;
1367
+ } catch {
1368
+ body = void 0;
1369
+ }
1370
+ const serverMessage = body?.message ? `: ${this.redact(String(body.message))}` : "";
1371
+ if (res.status === 429) {
1372
+ const asked = retryAfterMs(res.headers.get("retry-after"));
1373
+ const now = Date.now();
1374
+ if (asked !== void 0 && (asked > MAX_RETRY_AFTER_MS || this.deadlineAt !== void 0 && now + asked >= this.deadlineAt)) {
1375
+ throw new StarkoUploadError(
1376
+ `${what}: the server asks to wait ${formatDuration(asked)} before the next request (429${serverMessage}); the upload stops here`,
1377
+ { status: 429, fatal: true }
1378
+ );
1379
+ }
1380
+ rateLimited++;
1381
+ if (rateLimited > MAX_RATE_LIMITED_ATTEMPTS) {
1382
+ throw new StarkoUploadError(`${what}: server answered 429 ${rateLimited} times${serverMessage}`, { status: 429 });
1383
+ }
1384
+ const wait = Math.min(asked ?? Math.max(this.backoff(rateLimited - 1), 1e3), MAX_RETRY_AFTER_MS);
1385
+ if (now + wait > this.pausedUntil + 1e3) {
1386
+ this.warn(`the server is rate limiting this API key (429${serverMessage}); pausing the upload for ${formatDuration(wait)}`);
1387
+ }
1388
+ this.pausedUntil = Math.max(this.pausedUntil, now + wait);
1389
+ continue;
1390
+ }
1391
+ if (!res.ok && init.onError) {
1392
+ const special = init.onError({ status: res.status, headers: res.headers, body }, serverMessage);
1393
+ if (special) throw special;
1394
+ }
1395
+ if (res.status === 423) {
1396
+ throw new StarkoUploadError(`${what}: Starko has disabled source-map uploads (423${serverMessage}); nothing more is sent`, { status: 423, fatal: true });
1397
+ }
1398
+ if (res.status >= 500) {
1399
+ if (attempt >= this.retries) {
1400
+ throw new StarkoUploadError(`${what}: server answered ${res.status} after ${attempt + 1} attempts${serverMessage}`, { status: res.status });
1401
+ }
1402
+ const asked = retryAfterMs(res.headers.get("retry-after"));
1403
+ const wait = asked !== void 0 ? Math.min(Math.max(asked, this.backoff(attempt)), MAX_RETRY_AFTER_MS) : Math.min(this.backoff(attempt), this.maxRetryDelayMs);
1404
+ this.warn(`${what}: server answered ${res.status}${serverMessage}, retrying in ${formatDuration(wait)}`);
1405
+ await sleep(wait, signal);
1406
+ attempt++;
1407
+ continue;
1408
+ }
1409
+ if (res.status === 401) {
1410
+ throw new StarkoUploadError(
1411
+ `Starko rejected the API key (401)${serverMessage}. Set apiKey or STARKO_API_KEY to a secret key with the sourcemaps:write scope (Starko > Settings).`,
1412
+ { status: 401, fatal: true }
1413
+ );
1414
+ }
1415
+ if (res.status === 403) {
1416
+ throw new StarkoUploadError(`Starko refused the upload (403)${serverMessage}. The API key needs the sourcemaps:write scope.`, {
1417
+ status: 403,
1418
+ fatal: true
1419
+ });
1420
+ }
1421
+ if (res.status === 409) {
1422
+ const wait = retryAfterMs(res.headers.get("retry-after"));
1423
+ if (wait !== void 0) {
1424
+ throw new StarkoUploadError(
1425
+ `${what}: Starko is receiving this map through a direct upload to its storage that may still be under way; it accepts it through this route again in ${formatDuration(wait)} (409${serverMessage}). The next build sends it.`,
1426
+ { status: 409 }
1427
+ );
1428
+ }
1429
+ throw new StarkoUploadError(
1430
+ `${what}: Starko already has a different source map for this debug id (409)${serverMessage}. A debug id is write-once; delete the stored map in Starko to replace it.`,
1431
+ { status: 409 }
1432
+ );
1433
+ }
1434
+ if (res.status === 413 && /allowance/i.test(serverMessage)) {
1435
+ throw new StarkoUploadError(`${what}: server answered 413${serverMessage}`, { status: 413, fatal: true });
1436
+ }
1437
+ if (!res.ok) {
1438
+ throw new StarkoUploadError(`${what}: server answered ${res.status}${serverMessage}`, { status: res.status });
1439
+ }
1440
+ if (!body || body.ok !== true) {
1441
+ throw new StarkoUploadError(`${what}: unexpected response${serverMessage || ` (${res.status})`}`, { status: res.status });
1442
+ }
1443
+ return body;
1444
+ }
1445
+ }
1446
+ };
1447
+ var gzip = promisify(gzip$1);
1448
+ var CHECKS_IN_FLIGHT = 4;
1449
+ function splitParts(data, size) {
1450
+ if (data.length === 0) return [data];
1451
+ const parts = [];
1452
+ for (let at = 0; at < data.length; at += size) parts.push(data.subarray(at, at + size));
1453
+ return parts;
1454
+ }
1455
+ async function runV1(s, source) {
1456
+ const options = s.options;
1457
+ const partBytes = Math.min(options.partBytes ?? SOURCEMAP_PART_BYTES, SOURCEMAP_PART_BYTES);
1458
+ if (!(partBytes > 0)) {
1459
+ s.stopWith(new StarkoUploadError("partBytes must be positive", { fatal: true }));
1460
+ return;
1461
+ }
1462
+ const concurrency = resolveUploadConcurrency(options.concurrency);
1463
+ const checkBatchSize = Math.max(1, Math.min(options.checkBatchSize ?? SOURCEMAP_MAX_CHUNKS_PER_CHECK, SOURCEMAP_MAX_CHUNKS_PER_CHECK));
1464
+ const queue = new Channel();
1465
+ const unsubscribe = s.onStop(() => queue.close(true));
1466
+ async function uploadOne(p) {
1467
+ const release = await s.budget.acquire(p.size * 2);
1468
+ if (s.stopped()) {
1469
+ release();
1470
+ return;
1471
+ }
1472
+ s.progress.sending++;
1473
+ try {
1474
+ const raw = await readItem(p.item);
1475
+ if (sha256Hex(raw) !== p.hash) throw new StarkoUploadError("the source map changed while it was being uploaded; not uploaded");
1476
+ const gz = await gzip(raw);
1477
+ const parts = splitParts(gz, partBytes);
1478
+ if (parts.length > SOURCEMAP_MAX_PARTS) {
1479
+ throw new StarkoUploadError(`source map is ${gz.length} bytes gzipped, more than ${SOURCEMAP_MAX_PARTS} parts of ${partBytes} bytes; not uploaded`);
1480
+ }
1481
+ for (let part = 0; part < parts.length; part++) {
1482
+ if (s.stopped()) return;
1483
+ const query = new URLSearchParams({
1484
+ chunk_id: p.chunkId,
1485
+ part: String(part),
1486
+ parts: String(parts.length),
1487
+ content_hash: p.hash
1488
+ });
1489
+ await s.request(
1490
+ `upload ${p.fileName ?? p.chunkId} part ${part + 1}/${parts.length}`,
1491
+ `${PATHS.SOURCEMAPS_UPLOAD}?${query.toString()}`,
1492
+ { body: parts[part], contentType: "application/octet-stream" }
1493
+ );
1494
+ s.progress.bytesSent += parts[part].length;
1495
+ }
1496
+ const complete = {
1497
+ chunk_id: p.chunkId,
1498
+ parts: parts.length,
1499
+ content_hash: p.hash,
1500
+ size_bytes: p.size
1501
+ };
1502
+ if (p.fileName) complete.file_name = wireFileName(p.fileName);
1503
+ if (s.release) complete.release = { version: s.release.version };
1504
+ await s.request(`complete ${p.fileName ?? p.chunkId}`, PATHS.SOURCEMAPS_COMPLETE, {
1505
+ body: JSON.stringify(complete),
1506
+ contentType: "application/json"
1507
+ });
1508
+ s.uploaded(p.chunkId, p.fileName, parts.length, p.size);
1509
+ } catch (error) {
1510
+ if (error instanceof StarkoUploadError && error.fatal) {
1511
+ s.stopWith(error);
1512
+ return;
1513
+ }
1514
+ s.fail(p.chunkId, p.fileName, errorMessage(error));
1515
+ } finally {
1516
+ s.progress.sending--;
1517
+ release();
1518
+ }
1519
+ }
1520
+ const workers = Array.from({ length: concurrency }, async () => {
1521
+ for (; ; ) {
1522
+ const p = await queue.next();
1523
+ if (p === void 0 || s.stopped()) return;
1524
+ await uploadOne(p);
1525
+ }
1526
+ });
1527
+ const checkSlots = new Budget(CHECKS_IN_FLIGHT);
1528
+ const checks = [];
1529
+ const dispatchCheck = (batch) => {
1530
+ checks.push(
1531
+ (async () => {
1532
+ const release = await checkSlots.acquire(1);
1533
+ try {
1534
+ if (s.stopped()) return;
1535
+ const payload = {
1536
+ chunks: batch.map((p) => ({ chunk_id: p.chunkId, content_hash: p.hash }))
1537
+ };
1538
+ if (s.release) payload.release = s.release;
1539
+ const res = await s.request("check", PATHS.SOURCEMAPS_CHECK, {
1540
+ body: JSON.stringify(payload),
1541
+ contentType: "application/json"
1542
+ });
1543
+ if (!res.data || !Array.isArray(res.data.missing)) throw new StarkoUploadError("check: response has no `missing` list");
1544
+ const missing = new Set(res.data.missing.map(String));
1545
+ s.progress.checked += batch.length;
1546
+ for (const p of batch) {
1547
+ if (missing.has(p.chunkId)) queue.push(p);
1548
+ else s.skip(p.chunkId, p.fileName);
1549
+ }
1550
+ } catch (error) {
1551
+ s.stopWith(error);
1552
+ } finally {
1553
+ release();
1554
+ }
1555
+ })()
1556
+ );
1557
+ };
1558
+ try {
1559
+ let batch = [];
1560
+ for await (const p of source) {
1561
+ if (s.stopped()) break;
1562
+ batch.push(p);
1563
+ if (batch.length >= checkBatchSize) {
1564
+ dispatchCheck(batch);
1565
+ batch = [];
1566
+ }
1567
+ }
1568
+ if (batch.length > 0 && !s.stopped()) dispatchCheck(batch);
1569
+ await Promise.all(checks);
1570
+ } catch (error) {
1571
+ s.stopWith(error);
1572
+ } finally {
1573
+ queue.close();
1574
+ }
1575
+ await Promise.all(workers);
1576
+ unsubscribe();
1577
+ }
1578
+
1579
+ // src/build/shared/upload-bulk.ts
1580
+ var gzip2 = promisify(gzip$1);
1581
+ var GZIP_OPTIONS = { level: 6, memLevel: 8, windowBits: 15, strategy: constants$1.Z_DEFAULT_STRATEGY };
1582
+ function gzipMap(raw) {
1583
+ return gzip2(raw, GZIP_OPTIONS);
1584
+ }
1585
+ var CHECKS_IN_FLIGHT2 = 4;
1586
+ var COMPRESSORS = 4;
1587
+ var PROBE_MAPS = 4;
1588
+ var EXPIRY_MARGIN_MS = 6e4;
1589
+ var MAX_STARTS_PER_MAP = 4;
1590
+ var MAX_BUSY_WAITS = 3;
1591
+ var MAX_BUSY_WAIT_MS = 6e4;
1592
+ var PUT_RETRIES = 2;
1593
+ var MAX_PUT_RETRY_AFTER_MS = 3e4;
1594
+ var MAX_FINISH_ROUNDS = 5;
1595
+ var FINISH_RETRY_MS = 1e3;
1596
+ var PUT_MS_PER_128_KIB = 1e3;
1597
+ var monotonic = () => performance.now();
1598
+ var Notifier = class {
1599
+ constructor() {
1600
+ this.waiters = [];
1601
+ }
1602
+ notify() {
1603
+ for (const w of this.waiters.splice(0)) w();
1604
+ }
1605
+ wait() {
1606
+ return new Promise((resolve) => this.waiters.push(resolve));
1607
+ }
1608
+ };
1609
+ var HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
1610
+ var SAFE_VALUE = /^[^\r\n"\\]*$/;
1611
+ function multipartBody(target, content) {
1612
+ let boundary;
1613
+ do
1614
+ boundary = `----starko-${randomBytes(16).toString("hex")}`;
1615
+ while (content.includes(boundary));
1616
+ const head = Buffer.from(
1617
+ `--${boundary}\r
1618
+ Content-Disposition: form-data; name="${target.form_field}"; filename="${target.file_name}"\r
1619
+ Content-Type: ${target.content_type}\r
1620
+ \r
1621
+ `,
1622
+ "utf8"
1623
+ );
1624
+ const tail = Buffer.from(`\r
1625
+ --${boundary}--\r
1626
+ `, "utf8");
1627
+ return { body: Buffer.concat([head, content, tail]), contentType: `multipart/form-data; boundary=${boundary}` };
1628
+ }
1629
+ async function runBulk(s, source, mode) {
1630
+ const o = s.options;
1631
+ const checkBatch = Math.max(1, Math.min(o.bulkCheckBatchSize ?? SOURCEMAP_BULK_MAX_CHECK, SOURCEMAP_BULK_MAX_CHECK));
1632
+ const mapBatch = Math.max(1, Math.min(o.bulkBatchSize ?? SOURCEMAP_BULK_MAX_MAPS, SOURCEMAP_BULK_MAX_MAPS));
1633
+ const startLingerMs = Math.max(0, o.bulkLingerMs ?? 250);
1634
+ const finishLingerMs = Math.max(0, o.bulkLingerMs ?? 2e3);
1635
+ const concurrency = resolveUploadConcurrency(o.concurrency, DEFAULT_BULK_UPLOAD_CONCURRENCY);
1636
+ const maxStorageFailures = Math.max(1, o.maxStorageFailures ?? 3);
1637
+ const configured = mode === "bulk" ? " (as configured)" : "";
1638
+ let first;
1639
+ try {
1640
+ first = await source.next();
1641
+ } catch (error) {
1642
+ s.stopWith(error);
1643
+ return;
1644
+ }
1645
+ if (first.done) return;
1646
+ let firstMissing;
1647
+ try {
1648
+ firstMissing = await bulkCheck(s, [first.value]);
1649
+ } catch (error) {
1650
+ const status = error instanceof StarkoUploadError ? error.status : void 0;
1651
+ if (status === 404 || status === 405) {
1652
+ if (mode === "bulk") {
1653
+ s.stopWith(
1654
+ new StarkoUploadError(
1655
+ `${s.host} has no bulk upload (bulk/check answered ${status}). Set uploadProtocol to "auto" or "v1" (--protocol), or update the Starko server.`,
1656
+ { status, fatal: true }
1657
+ )
1658
+ );
1659
+ return;
1660
+ }
1661
+ s.useProtocol("v1");
1662
+ s.info(`source map upload: using the v1 upload through ${s.host}: the server has no bulk upload (bulk/check answered ${status})`);
1663
+ await runV1(s, prepend(first.value, source));
1664
+ return;
1665
+ }
1666
+ s.stopWith(error);
1667
+ return;
1668
+ }
1669
+ s.useProtocol("bulk");
1670
+ s.info(`source map upload: using the bulk upload${configured}: each map goes straight to Starko's storage`);
1671
+ const compressQueue = new Channel();
1672
+ const startQueue = new Channel();
1673
+ const putQueue = new Channel();
1674
+ const finishQueue = new Channel();
1675
+ const v1Input = new Channel();
1676
+ const changed = new Notifier();
1677
+ const delayed = /* @__PURE__ */ new Set();
1678
+ let pendingMaps = 0;
1679
+ let checksDone = false;
1680
+ let startsInFlight = 0;
1681
+ let awaitingPut = 0;
1682
+ let storageProven = false;
1683
+ let storageFailuresInRow = 0;
1684
+ let storageOrigin;
1685
+ let fallenBack = false;
1686
+ let v1Done;
1687
+ let closing;
1688
+ const closeAll = (drop) => {
1689
+ for (const q of [compressQueue, startQueue, putQueue, finishQueue]) q.close(drop);
1690
+ v1Input.close(drop);
1691
+ changed.notify();
1692
+ };
1693
+ const unsubscribe = s.onStop(() => closeAll(true));
1694
+ const maybeIdle = () => {
1695
+ if (checksDone && pendingMaps === 0) closeAll(false);
1696
+ };
1697
+ const newMap = (p) => {
1698
+ pendingMaps++;
1699
+ return { p, expiresAt: 0, reserved: false, starts: 0, busyWaits: 0, puts: 0, putRestarts: 0, putOk: false, putExpired: false, finishRounds: 0, settled: false };
1700
+ };
1701
+ const settle = (m) => {
1702
+ if (m.settled) return;
1703
+ m.settled = true;
1704
+ m.held?.release();
1705
+ m.held = void 0;
1706
+ m.gz = void 0;
1707
+ pendingMaps--;
1708
+ changed.notify();
1709
+ maybeIdle();
1710
+ };
1711
+ const failMap = (m, error) => {
1712
+ if (m.settled) return;
1713
+ s.fail(m.p.chunkId, m.p.fileName, error);
1714
+ settle(m);
1715
+ };
1716
+ const notSent = (m) => settle(m);
1717
+ const handOver = (m) => {
1718
+ if (m.settled) return;
1719
+ v1Input.push(m.p);
1720
+ s.progress.checked--;
1721
+ settle(m);
1722
+ };
1723
+ const later = (ms, fn) => {
1724
+ const task = s.sleep(ms).then(fn, () => void 0);
1725
+ delayed.add(task);
1726
+ void task.finally(() => delayed.delete(task));
1727
+ };
1728
+ const routeChecked = (batch, missing) => {
1729
+ s.progress.checked += batch.length;
1730
+ for (const p of batch) {
1731
+ if (!missing.has(p.chunkId)) {
1732
+ s.skip(p.chunkId, p.fileName);
1733
+ continue;
1734
+ }
1735
+ const m = newMap(p);
1736
+ if (fallenBack) handOver(m);
1737
+ else if (closing) notSent(m);
1738
+ else compressQueue.push(m);
1739
+ }
1740
+ };
1741
+ const restart = (m, why) => {
1742
+ m.target = void 0;
1743
+ m.putOk = false;
1744
+ m.putExpired = false;
1745
+ if (fallenBack) {
1746
+ handOver(m);
1747
+ return;
1748
+ }
1749
+ if (m.starts >= MAX_STARTS_PER_MAP) {
1750
+ failMap(m, `not uploaded after ${m.starts} bulk/start requests (last: ${why}); the next build sends it`);
1751
+ return;
1752
+ }
1753
+ startQueue.push(m);
1754
+ };
1755
+ const storageFailure = (m, reason) => {
1756
+ m.putOk = false;
1757
+ m.putError = reason;
1758
+ storageFailuresInRow++;
1759
+ if (storageFailuresInRow >= maxStorageFailures) fallBack(reason);
1760
+ if (!s.stopped()) finishQueue.push(m);
1761
+ };
1762
+ const fallBack = (reason) => {
1763
+ if (fallenBack || closing || s.stopped()) return;
1764
+ const where = storageOrigin ?? "the storage host";
1765
+ const hostOnly = storageOrigin ? new URL(storageOrigin).host : "the storage host";
1766
+ if (mode === "bulk") {
1767
+ s.stopWith(
1768
+ new StarkoUploadError(
1769
+ `uploads to Starko's storage at ${where} fail (${storageFailuresInRow} in a row, last: ${reason}). The build machine must be able to reach ${hostOnly} (a proxy or a firewall may block it): allow it, or set uploadProtocol to "v1" (--protocol v1) to send every map through ${s.host}.`,
1770
+ { fatal: true }
1771
+ )
1772
+ );
1773
+ return;
1774
+ }
1775
+ fallenBack = true;
1776
+ s.result.fallback = { storageHost: hostOnly, reason };
1777
+ s.warn(
1778
+ `source map upload: uploads to Starko's storage at ${where} fail (${storageFailuresInRow} in a row, last: ${reason}); this machine probably cannot reach that host (a proxy or a firewall?). The remaining source maps go through ${s.host} instead (v1 upload), the ones already reserved for storage included. Allow ${hostOnly} for builds, or set uploadProtocol to "v1" (--protocol v1).`
1779
+ );
1780
+ v1Done = runV1(s, v1Input);
1781
+ for (const m of compressQueue.drainAll()) handOver(m);
1782
+ for (const m of startQueue.drainAll()) handOver(m);
1783
+ for (const m of putQueue.drainAll()) {
1784
+ awaitingPut--;
1785
+ handOver(m);
1786
+ }
1787
+ changed.notify();
1788
+ };
1789
+ const drain = (error) => {
1790
+ if (closing || s.stopped()) return;
1791
+ closing = error;
1792
+ for (const m of compressQueue.drainAll()) notSent(m);
1793
+ for (const m of startQueue.drainAll()) {
1794
+ if (m.reserved) startQueue.push(m);
1795
+ else notSent(m);
1796
+ }
1797
+ changed.notify();
1798
+ };
1799
+ const isCleanStop = (error) => error instanceof StarkoUploadError && error.fatal && (error.status === 429 || error.status === 413);
1800
+ const checkSlots = new Budget(CHECKS_IN_FLIGHT2);
1801
+ const checks = [];
1802
+ const dispatchCheck = (batch) => {
1803
+ checks.push(
1804
+ (async () => {
1805
+ const release = await checkSlots.acquire(1);
1806
+ try {
1807
+ if (s.stopped()) return;
1808
+ if (fallenBack) {
1809
+ for (const p of batch) v1Input.push(p);
1810
+ return;
1811
+ }
1812
+ routeChecked(batch, await bulkCheck(s, batch));
1813
+ } catch (error) {
1814
+ s.stopWith(error);
1815
+ } finally {
1816
+ release();
1817
+ }
1818
+ })()
1819
+ );
1820
+ };
1821
+ const checkLoop = (async () => {
1822
+ routeChecked([first.value], firstMissing);
1823
+ let batch = [];
1824
+ try {
1825
+ for (; ; ) {
1826
+ if (s.stopped() || closing) break;
1827
+ if (fallenBack) {
1828
+ for (const p of batch) v1Input.push(p);
1829
+ batch = [];
1830
+ for (; ; ) {
1831
+ if (s.stopped()) break;
1832
+ const next2 = await source.next();
1833
+ if (next2.done) break;
1834
+ v1Input.push(next2.value);
1835
+ }
1836
+ break;
1837
+ }
1838
+ const next = await source.next();
1839
+ if (next.done) break;
1840
+ batch.push(next.value);
1841
+ if (batch.length >= checkBatch) {
1842
+ dispatchCheck(batch);
1843
+ batch = [];
1844
+ }
1845
+ }
1846
+ if (batch.length > 0 && !s.stopped() && !closing) {
1847
+ if (fallenBack) for (const p of batch) v1Input.push(p);
1848
+ else dispatchCheck(batch);
1849
+ }
1850
+ await Promise.all(checks);
1851
+ } catch (error) {
1852
+ s.stopWith(error);
1853
+ } finally {
1854
+ checksDone = true;
1855
+ maybeIdle();
1856
+ }
1857
+ })();
1858
+ const compressors = Array.from({ length: COMPRESSORS }, async () => {
1859
+ for (; ; ) {
1860
+ const m = await compressQueue.next();
1861
+ if (m === void 0 || s.stopped()) return;
1862
+ const held = await s.budget.hold(m.p.size * 2);
1863
+ if (s.stopped()) {
1864
+ held.release();
1865
+ return;
1866
+ }
1867
+ if (fallenBack || closing) {
1868
+ held.release();
1869
+ if (fallenBack) handOver(m);
1870
+ else notSent(m);
1871
+ continue;
1872
+ }
1873
+ try {
1874
+ const raw = await readItem(m.p.item);
1875
+ if (sha256Hex(raw) !== m.p.hash) throw new StarkoUploadError("the source map changed while it was being uploaded; not uploaded");
1876
+ const gz = await gzipMap(raw);
1877
+ if (gz.length > SOURCEMAP_BULK_MAX_OBJECT_BYTES) throw new StarkoUploadError(`source map is ${gz.length} bytes gzipped, over the ${SOURCEMAP_BULK_MAX_OBJECT_BYTES}-byte limit; not uploaded`);
1878
+ m.gz = gz;
1879
+ held.resize(gz.length * 2);
1880
+ m.held = held;
1881
+ } catch (error) {
1882
+ held.release();
1883
+ failMap(m, errorMessage(error));
1884
+ continue;
1885
+ }
1886
+ if (fallenBack) handOver(m);
1887
+ else if (closing) notSent(m);
1888
+ else startQueue.push(m);
1889
+ }
1890
+ });
1891
+ const dispatcher = (queue, slots, lingerMs, size, ready, send) => (async () => {
1892
+ const inFlight = /* @__PURE__ */ new Set();
1893
+ const free = new Budget(slots);
1894
+ for (; ; ) {
1895
+ const first2 = await queue.next();
1896
+ if (first2 === void 0) break;
1897
+ while (!ready() && !s.stopped() && !queue.closed) await changed.wait();
1898
+ const release = await free.acquire(1);
1899
+ if (s.stopped()) {
1900
+ release();
1901
+ break;
1902
+ }
1903
+ const n = size();
1904
+ await queue.waitForLength(n - 1, lingerMs);
1905
+ if (s.stopped()) {
1906
+ release();
1907
+ break;
1908
+ }
1909
+ const batch = [first2, ...queue.take(n - 1)];
1910
+ const task = send(batch).finally(() => {
1911
+ release();
1912
+ inFlight.delete(task);
1913
+ });
1914
+ inFlight.add(task);
1915
+ }
1916
+ await Promise.all(inFlight);
1917
+ })();
1918
+ const handleStart = (m, entry) => {
1919
+ const message = typeof entry.message === "string" && entry.message ? `: ${entry.message}` : "";
1920
+ switch (entry.status) {
1921
+ case "upload": {
1922
+ const problem = targetProblem(entry.upload, m, s.host);
1923
+ if (problem) {
1924
+ failMap(m, `bulk/start gave an unusable upload target (${problem}); not uploaded`);
1925
+ return;
1926
+ }
1927
+ const target = entry.upload;
1928
+ s.secrets.addSignedUrl(target.url);
1929
+ storageOrigin = new URL(target.url).origin;
1930
+ m.target = target;
1931
+ m.expiresAt = expiryOf(target, monotonic(), s.clockOffsetMs);
1932
+ m.reserved = true;
1933
+ m.putExpired = false;
1934
+ if (fallenBack) {
1935
+ handOver(m);
1936
+ return;
1937
+ }
1938
+ awaitingPut++;
1939
+ putQueue.push(m);
1940
+ return;
1941
+ }
1942
+ case "uploaded":
1943
+ m.reserved = true;
1944
+ m.target = void 0;
1945
+ m.putOk = true;
1946
+ finishQueue.push(m);
1947
+ return;
1948
+ case "present":
1949
+ case "pending":
1950
+ s.skip(m.p.chunkId, m.p.fileName);
1951
+ settle(m);
1952
+ return;
1953
+ case "conflict":
1954
+ failMap(m, `Starko already has a different source map for this debug id (conflict${message}). A debug id is write-once; delete the stored map in Starko to replace it.`);
1955
+ return;
1956
+ case "busy": {
1957
+ const wait = Math.max(1, Number(entry.retry_after_s) || 1) * 1e3;
1958
+ const fits = s.deadlineAt === void 0 || Date.now() + wait < s.deadlineAt;
1959
+ if (m.busyWaits < MAX_BUSY_WAITS && wait <= MAX_BUSY_WAIT_MS && fits && !closing) {
1960
+ m.busyWaits++;
1961
+ m.starts--;
1962
+ later(wait, () => fallenBack ? restart(m, "busy") : startQueue.push(m));
1963
+ return;
1964
+ }
1965
+ failMap(m, `earlier uploads of this debug id may still be under way on the server; it accepts this map again in ${formatDuration(wait)} (busy${message}). The next build sends it.`);
1966
+ return;
1967
+ }
1968
+ case "over_allowance":
1969
+ drain(new StarkoUploadError(`bulk/start: ${entry.message || "the workspace's source-map storage allowance is reached"} (over_allowance); the upload stops here`, { status: 413, fatal: true }));
1970
+ notSent(m);
1971
+ return;
1972
+ default:
1973
+ failMap(m, `bulk/start: unexpected answer for this map (${String(entry.status)}); not uploaded`);
1974
+ }
1975
+ };
1976
+ const sendStart = async (batch) => {
1977
+ const live = batch.filter((m) => {
1978
+ if (m.settled) return false;
1979
+ if (fallenBack) {
1980
+ handOver(m);
1981
+ return false;
1982
+ }
1983
+ if (closing && !m.reserved) {
1984
+ notSent(m);
1985
+ return false;
1986
+ }
1987
+ return true;
1988
+ });
1989
+ if (live.length === 0) return;
1990
+ startsInFlight++;
1991
+ changed.notify();
1992
+ try {
1993
+ for (const m of live) m.starts++;
1994
+ const payload = {
1995
+ maps: live.map((m) => {
1996
+ const e = { chunk_id: m.p.chunkId, content_hash: m.p.hash, size_bytes: m.gz.length };
1997
+ if (m.p.fileName) e.file_name = wireFileName(m.p.fileName);
1998
+ return e;
1999
+ })
2000
+ };
2001
+ if (s.release) payload.release = s.release;
2002
+ const res = await s.request(`bulk/start (${live.length} map(s))`, PATHS.SOURCEMAPS_BULK_START, {
2003
+ body: JSON.stringify(payload),
2004
+ contentType: "application/json"
2005
+ });
2006
+ const entries = answerFor(res.data?.maps, live, "bulk/start");
2007
+ live.forEach((m, i) => handleStart(m, entries[i]));
2008
+ } catch (error) {
2009
+ if (isCleanStop(error)) {
2010
+ drain(error);
2011
+ for (const m of live) if (!m.reserved) notSent(m);
2012
+ for (const m of live) if (!m.settled) restart(m, errorMessage(error));
2013
+ } else if (error instanceof StarkoUploadError && error.fatal) {
2014
+ s.stopWith(error);
2015
+ } else {
2016
+ for (const m of live) failMap(m, errorMessage(error));
2017
+ }
2018
+ } finally {
2019
+ startsInFlight--;
2020
+ changed.notify();
2021
+ }
2022
+ };
2023
+ const startDispatcher = dispatcher(
2024
+ startQueue,
2025
+ SOURCEMAP_BULK_REQUEST_CONCURRENCY,
2026
+ startLingerMs,
2027
+ () => storageProven ? mapBatch : Math.min(mapBatch, PROBE_MAPS),
2028
+ // Until storage is known to be reachable: one small start at a time, and only when its maps were tried.
2029
+ // Then: only while the PUTs need more work, so starts carry many maps each instead of a few.
2030
+ () => fallenBack || (storageProven ? awaitingPut < concurrency * 2 : startsInFlight === 0 && awaitingPut === 0),
2031
+ sendStart
2032
+ );
2033
+ const putOne = async (m) => {
2034
+ if (m.settled) return;
2035
+ if (fallenBack) {
2036
+ awaitingPut--;
2037
+ handOver(m);
2038
+ return;
2039
+ }
2040
+ if (!m.target || m.expiresAt - monotonic() < EXPIRY_MARGIN_MS) {
2041
+ awaitingPut--;
2042
+ changed.notify();
2043
+ restart(m, "the upload URL expired");
2044
+ return;
2045
+ }
2046
+ m.puts++;
2047
+ s.progress.sending++;
2048
+ let outcome;
2049
+ try {
2050
+ outcome = await putToStorage(s, m.target, m.gz);
2051
+ } catch (error) {
2052
+ s.progress.sending--;
2053
+ awaitingPut--;
2054
+ changed.notify();
2055
+ if (s.signal?.aborted) s.stopWith(error);
2056
+ else storageFailure(m, errorMessage(error));
2057
+ return;
2058
+ }
2059
+ s.progress.sending--;
2060
+ awaitingPut--;
2061
+ changed.notify();
2062
+ if (outcome.kind === "ok") {
2063
+ m.putOk = true;
2064
+ storageFailuresInRow = 0;
2065
+ if (!storageProven) {
2066
+ storageProven = true;
2067
+ changed.notify();
2068
+ }
2069
+ s.progress.bytesSent += m.gz.length;
2070
+ finishQueue.push(m);
2071
+ return;
2072
+ }
2073
+ if (outcome.kind === "refused" && m.expiresAt - monotonic() < EXPIRY_MARGIN_MS) {
2074
+ m.putOk = false;
2075
+ m.putExpired = true;
2076
+ m.putError = outcome.reason;
2077
+ finishQueue.push(m);
2078
+ return;
2079
+ }
2080
+ storageFailure(m, outcome.reason);
2081
+ };
2082
+ const putWorkers = Array.from({ length: concurrency }, async () => {
2083
+ for (; ; ) {
2084
+ const m = await putQueue.next();
2085
+ if (m === void 0 || s.stopped()) return;
2086
+ await putOne(m);
2087
+ }
2088
+ });
2089
+ const handleFinish = (m, entry, progressed) => {
2090
+ const message = typeof entry.message === "string" && entry.message ? `: ${entry.message}` : "";
2091
+ switch (entry.status) {
2092
+ case "stored":
2093
+ case "pending":
2094
+ s.uploaded(m.p.chunkId, m.p.fileName, 1, m.p.size);
2095
+ settle(m);
2096
+ return;
2097
+ case "not_uploaded":
2098
+ if (fallenBack) {
2099
+ handOver(m);
2100
+ return;
2101
+ }
2102
+ if (m.putExpired) {
2103
+ restart(m, m.putError ?? `not_uploaded${message}`);
2104
+ return;
2105
+ }
2106
+ if (m.putOk) {
2107
+ restart(m, `not_uploaded${message}`);
2108
+ return;
2109
+ }
2110
+ if (m.putRestarts < 1 && !closing) {
2111
+ m.putRestarts++;
2112
+ restart(m, m.putError ?? `not_uploaded${message}`);
2113
+ return;
2114
+ }
2115
+ failMap(m, `could not upload to Starko's storage: ${m.putError ?? "not uploaded"}`);
2116
+ return;
2117
+ case "not_reserved":
2118
+ m.reserved = false;
2119
+ restart(m, `not_reserved${message}`);
2120
+ return;
2121
+ case "retry":
2122
+ if (!progressed) m.finishRounds++;
2123
+ if (m.finishRounds < MAX_FINISH_ROUNDS) {
2124
+ later(FINISH_RETRY_MS * Math.max(1, m.finishRounds), () => finishQueue.push(m));
2125
+ return;
2126
+ }
2127
+ failMap(m, `the server could not check the upload in ${m.finishRounds} tries (retry${message}); the next build sends it`);
2128
+ return;
2129
+ case "conflict":
2130
+ failMap(m, `Starko already has a different source map for this debug id (conflict${message}). A debug id is write-once; delete the stored map in Starko to replace it.`);
2131
+ return;
2132
+ case "failed":
2133
+ failMap(m, `the server refused the uploaded map (failed${message}); it is not sent again by this build`);
2134
+ return;
2135
+ default:
2136
+ failMap(m, `bulk/finish: unexpected answer for this map (${String(entry.status)})`);
2137
+ }
2138
+ };
2139
+ const sendFinish = async (batch) => {
2140
+ const live = batch.filter((m) => !m.settled);
2141
+ if (live.length === 0) return;
2142
+ try {
2143
+ const payload = { maps: live.map((m) => ({ chunk_id: m.p.chunkId, content_hash: m.p.hash })) };
2144
+ const res = await s.request(`bulk/finish (${live.length} map(s))`, PATHS.SOURCEMAPS_BULK_FINISH, {
2145
+ body: JSON.stringify(payload),
2146
+ contentType: "application/json"
2147
+ });
2148
+ const entries = answerFor(res.data?.maps, live, "bulk/finish");
2149
+ const progressed = entries.some((e) => e.status !== "retry");
2150
+ live.forEach((m, i) => handleFinish(m, entries[i], progressed));
2151
+ } catch (error) {
2152
+ if (error instanceof StarkoUploadError && error.fatal) s.stopWith(error);
2153
+ else for (const m of live) failMap(m, errorMessage(error));
2154
+ }
2155
+ };
2156
+ const finishDispatcher = dispatcher(finishQueue, SOURCEMAP_BULK_REQUEST_CONCURRENCY, finishLingerMs, () => mapBatch, () => true, sendFinish);
2157
+ await checkLoop;
2158
+ await Promise.all([...compressors, startDispatcher, ...putWorkers, finishDispatcher]);
2159
+ while (delayed.size > 0) await Promise.all(Array.from(delayed));
2160
+ if (v1Done) await v1Done;
2161
+ unsubscribe();
2162
+ if (closing && s.stop === void 0) s.stop = closing;
2163
+ }
2164
+ async function bulkCheck(s, batch) {
2165
+ const payload = { chunks: batch.map((p) => ({ chunk_id: p.chunkId, content_hash: p.hash })) };
2166
+ if (s.release) payload.release = s.release;
2167
+ const res = await s.request("bulk/check", PATHS.SOURCEMAPS_BULK_CHECK, {
2168
+ body: JSON.stringify(payload),
2169
+ contentType: "application/json"
2170
+ });
2171
+ if (!res.data || !Array.isArray(res.data.missing)) throw new StarkoUploadError("bulk/check: response has no `missing` list");
2172
+ return new Set(res.data.missing.map(String));
2173
+ }
2174
+ function answerFor(entries, batch, what) {
2175
+ if (!Array.isArray(entries) || entries.length !== batch.length) {
2176
+ throw new StarkoUploadError(`${what}: the answer has ${Array.isArray(entries) ? entries.length : "no"} entries for ${batch.length} map(s)`);
2177
+ }
2178
+ entries.forEach((e, i) => {
2179
+ if (!e || typeof e !== "object" || String(e.chunk_id).toLowerCase() !== batch[i].p.chunkId.toLowerCase()) {
2180
+ throw new StarkoUploadError(`${what}: the answer does not follow the request's order`);
2181
+ }
2182
+ });
2183
+ return entries;
2184
+ }
2185
+ function targetProblem(t, m, host) {
2186
+ if (!t || typeof t !== "object") return "no target";
2187
+ if (typeof t.url !== "string") return "no URL";
2188
+ let url;
2189
+ try {
2190
+ url = new URL(t.url);
2191
+ } catch {
2192
+ return "not a URL";
2193
+ }
2194
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && host.startsWith("http:"))) return `a ${url.protocol} URL`;
2195
+ if (url.username || url.password) return "credentials in the URL";
2196
+ if (t.method !== "PUT") return `method ${String(t.method)}`;
2197
+ if (!t.headers || typeof t.headers !== "object") return "no headers";
2198
+ for (const [k, v] of Object.entries(t.headers)) {
2199
+ if (!HEADER_NAME.test(k) || typeof v !== "string" || /[\r\n]/.test(v)) return "a malformed header";
2200
+ if (/^(authorization|cookie|host|content-length)$/i.test(k)) return `a ${k} header`;
2201
+ }
2202
+ for (const [field, value] of [
2203
+ ["form_field", t.form_field],
2204
+ ["file_name", t.file_name],
2205
+ ["content_type", t.content_type]
2206
+ ]) {
2207
+ if (typeof value !== "string" || !value || !SAFE_VALUE.test(value)) return `a malformed ${field}`;
2208
+ }
2209
+ if (t.size_bytes !== m.gz.length) return `size ${String(t.size_bytes)} instead of the ${m.gz.length} bytes declared`;
2210
+ if (!validSeconds(t.expires_in_s) && typeof t.expires_at !== "string") return "no expiry";
2211
+ return void 0;
2212
+ }
2213
+ var validSeconds = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0;
2214
+ function expiryOf(target, received, clockOffsetMs) {
2215
+ if (validSeconds(target.expires_in_s)) return received + target.expires_in_s * 1e3;
2216
+ const at = Date.parse(String(target.expires_at));
2217
+ if (!Number.isNaN(at)) return received + (at - (Date.now() + clockOffsetMs));
2218
+ return received + 5 * 6e4;
2219
+ }
2220
+ async function putToStorage(s, target, gz) {
2221
+ const { body, contentType } = multipartBody(target, gz);
2222
+ const headers = new Headers();
2223
+ for (const [k, v] of Object.entries(target.headers)) headers.set(k, v);
2224
+ headers.set("content-type", contentType);
2225
+ const timeoutMs = s.timeoutMs + Math.ceil(body.length / (128 * 1024)) * PUT_MS_PER_128_KIB;
2226
+ const signal = s.signal;
2227
+ let last = "";
2228
+ for (let attempt = 0; ; attempt++) {
2229
+ if (signal?.aborted) throw abortedError();
2230
+ const controller = new AbortController();
2231
+ let timedOut = false;
2232
+ const timer = setTimeout(() => {
2233
+ timedOut = true;
2234
+ controller.abort();
2235
+ }, timeoutMs);
2236
+ const onAbort = () => controller.abort();
2237
+ signal?.addEventListener("abort", onAbort, { once: true });
2238
+ let retryAfter;
2239
+ try {
2240
+ const res = await s.doFetch(target.url, {
2241
+ method: "PUT",
2242
+ headers,
2243
+ body,
2244
+ // Never followed: the body is the client's source code.
2245
+ redirect: "manual",
2246
+ signal: controller.signal
2247
+ });
2248
+ const text = await res.text().catch(() => "");
2249
+ if (res.status >= 200 && res.status < 300) return { kind: "ok" };
2250
+ if (res.status >= 300 && res.status < 400 || res.type === "opaqueredirect") {
2251
+ return { kind: "redirect", reason: `storage answered with a redirect (${res.status || "3xx"}), which is never followed` };
2252
+ }
2253
+ const detail = briefBody(s, text);
2254
+ if (res.status === 408 || res.status === 429 || res.status >= 500) {
2255
+ last = `storage answered ${res.status}${detail}`;
2256
+ if (res.status === 429) retryAfter = retryAfterMs(res.headers.get("retry-after"));
2257
+ } else {
2258
+ return { kind: "refused", reason: `storage refused the upload (${res.status}${detail})` };
2259
+ }
2260
+ } catch (error) {
2261
+ if (signal?.aborted) throw abortedError();
2262
+ last = timedOut ? `no answer from storage within ${Math.round(timeoutMs / 1e3)} s` : s.redact(networkReason(error));
2263
+ } finally {
2264
+ clearTimeout(timer);
2265
+ signal?.removeEventListener("abort", onAbort);
2266
+ }
2267
+ if (attempt >= PUT_RETRIES) return { kind: "unreachable", reason: last };
2268
+ await s.sleep(Math.min(retryAfter ?? s.backoff(attempt), MAX_PUT_RETRY_AFTER_MS));
2269
+ }
2270
+ }
2271
+ function briefBody(s, text) {
2272
+ const flat = text.replace(/\s+/g, " ").trim();
2273
+ if (!flat) return "";
2274
+ return `: ${s.redact(flat).slice(0, 160)}`;
2275
+ }
2276
+ async function* prepend(first, rest) {
2277
+ yield first;
2278
+ for (; ; ) {
2279
+ const next = await rest.next();
2280
+ if (next.done) return;
2281
+ yield next.value;
2282
+ }
2283
+ }
2284
+
2285
+ // src/build/shared/upload.ts
2286
+ async function* prepare(s, items) {
2287
+ const prepared = /* @__PURE__ */ new Map();
2288
+ for (const item of items) {
2289
+ if (s.stopped()) return;
2290
+ let raw;
2291
+ try {
2292
+ raw = await readItem(item);
2293
+ } catch (error) {
2294
+ s.fail(item.chunkId, item.fileName, `could not read the source map: ${errorMessage(error)}`);
2295
+ continue;
2296
+ }
2297
+ if (raw.length > SOURCEMAP_MAX_BYTES) {
2298
+ s.fail(item.chunkId, item.fileName, `source map is ${raw.length} bytes, over the ${SOURCEMAP_MAX_BYTES}-byte limit; not uploaded`);
2299
+ continue;
2300
+ }
2301
+ let mapDebugId;
2302
+ try {
2303
+ mapDebugId = JSON.parse(raw.toString("utf8")).debugId;
2304
+ } catch {
2305
+ s.fail(item.chunkId, item.fileName, "source map is not valid JSON; not uploaded");
2306
+ continue;
2307
+ }
2308
+ if (mapDebugId !== item.chunkId) {
2309
+ s.fail(item.chunkId, item.fileName, `the source map's debugId (${typeof mapDebugId === "string" ? mapDebugId : "missing"}) is not the bundle's debug id; not uploaded`);
2310
+ continue;
2311
+ }
2312
+ const hash = sha256Hex(raw);
2313
+ const seen = prepared.get(item.chunkId);
2314
+ if (seen) {
2315
+ if (seen.hash !== hash) {
2316
+ s.fail(item.chunkId, item.fileName, `another source map (${seen.fileName ?? "unknown file"}) has the same debug id with different content; not uploaded`);
2317
+ } else {
2318
+ s.progress.total--;
2319
+ }
2320
+ continue;
2321
+ }
2322
+ const p = { chunkId: item.chunkId, fileName: item.fileName, hash, size: raw.length, item };
2323
+ prepared.set(item.chunkId, p);
2324
+ yield p;
2325
+ }
2326
+ }
2327
+ async function uploadSourcemaps(items, options) {
2328
+ const s = new Session(options);
2329
+ s.progress.total = items.length;
2330
+ const protocol = options.protocol ?? "auto";
2331
+ if (protocol !== "auto" && protocol !== "bulk" && protocol !== "v1") {
2332
+ throw new StarkoUploadError(`unknown upload protocol "${String(protocol)}" (auto, bulk or v1)`, { fatal: true });
2333
+ }
2334
+ const source = prepare(s, items);
2335
+ try {
2336
+ if (protocol === "v1") {
2337
+ s.useProtocol("v1");
2338
+ s.info(`source map upload: using the v1 upload through ${s.host} (as configured)`);
2339
+ await runV1(s, source);
2340
+ } else {
2341
+ await runBulk(s, source, protocol);
2342
+ }
2343
+ } catch (error) {
2344
+ s.stopWith(error);
2345
+ } finally {
2346
+ await source.return(void 0);
2347
+ }
2348
+ if (s.stop !== void 0) throw sanitized(s, s.stop);
2349
+ if (s.signal?.aborted) throw abortedError();
2350
+ return s.result;
2351
+ }
2352
+ function sanitized(s, error) {
2353
+ if (error instanceof StarkoUploadError) {
2354
+ const message = s.redact(error.message);
2355
+ return message === error.message ? error : new StarkoUploadError(message, { status: error.status, fatal: error.fatal });
2356
+ }
2357
+ return new StarkoUploadError(s.redact(errorMessage(error)), { fatal: true });
2358
+ }
2359
+
2360
+ // src/build/shared/pipeline.ts
2361
+ var PROGRESS_INTERVAL_MS = 3e4;
2362
+ var MAX_FAILURE_LINES = 20;
2363
+ async function runUpload(entries, options) {
2364
+ try {
2365
+ return await runUploadUnsafe(entries, options);
2366
+ } catch (error) {
2367
+ const message = errorMessage(error);
2368
+ try {
2369
+ options.logger.error(`source map upload failed: ${message}`);
2370
+ } catch {
2371
+ }
2372
+ return { ok: false, error: message };
2373
+ }
2374
+ }
2375
+ var count = (n) => n.toLocaleString("en-US");
2376
+ function progressLine(p) {
2377
+ return `${count(p.checked)} of ${count(p.total)} checked, ${count(p.uploaded)} uploaded, ${count(p.skipped)} already on the server, ${count(p.failed)} failed`;
2378
+ }
2379
+ function stoppedSummary(p) {
2380
+ const notSent = Math.max(0, p.total - p.uploaded - p.skipped - p.failed);
2381
+ const inFlight = p.sending > 0 ? ` (${count(p.sending)} of them were being sent and were stopped)` : "";
2382
+ return `${count(p.uploaded)} of ${count(p.total)} source map(s) uploaded, ${count(p.skipped)} already on the server, ${count(p.failed)} failed, ${count(notSent)} not sent${inFlight}`;
2383
+ }
2384
+ var CONTINUES = "The next build continues from there: a map the server has completed is never sent again.";
2385
+ async function runUploadUnsafe(entries, options) {
2386
+ const { logger } = options;
2387
+ const releaseNote = options.release ? ` for release ${options.release.version}` : "";
2388
+ if (entries.length === 0) {
2389
+ logger.info("no source maps to upload");
2390
+ return { ok: true };
2391
+ }
2392
+ if (options.dryRun) {
2393
+ logger.info(`dry run: would upload ${entries.length} source map(s)${releaseNote} to ${options.host}`);
2394
+ for (const e of entries) logger.info(` ${e.fileName ?? e.mapPath ?? "?"} \u2192 ${e.chunkId}`);
2395
+ return { ok: true };
2396
+ }
2397
+ if (!options.apiKey) {
2398
+ const error = `no API key (set apiKey or STARKO_API_KEY): ${entries.length} source map(s) were not uploaded`;
2399
+ logger.warn(error);
2400
+ return { ok: false, error };
2401
+ }
2402
+ const deadlineMs = options.uploadTimeoutMs !== void 0 && options.uploadTimeoutMs > 0 ? options.uploadTimeoutMs : DEFAULT_UPLOAD_TIMEOUT_MS;
2403
+ const started = Date.now();
2404
+ const progress = createUploadProgress();
2405
+ const controller = new AbortController();
2406
+ let timer;
2407
+ const deadline = new Promise((resolve) => {
2408
+ timer = setTimeout(() => {
2409
+ controller.abort();
2410
+ resolve("deadline");
2411
+ }, deadlineMs);
2412
+ });
2413
+ const interval = options.progressIntervalMs !== void 0 && options.progressIntervalMs > 0 ? options.progressIntervalMs : PROGRESS_INTERVAL_MS;
2414
+ const ticker = setInterval(() => {
2415
+ try {
2416
+ logger.info(`source map upload: ${progressLine(progress)} (${formatDuration(Date.now() - started)} so far)`);
2417
+ } catch {
2418
+ }
2419
+ }, interval);
2420
+ ticker.unref?.();
2421
+ const upload = uploadSourcemaps(entries, {
2422
+ concurrency: options.uploadConcurrency,
2423
+ ...options.client,
2424
+ protocol: options.uploadProtocol ?? "auto",
2425
+ apiKey: options.apiKey,
2426
+ host: options.host,
2427
+ release: options.release,
2428
+ logger,
2429
+ signal: controller.signal,
2430
+ deadlineAt: started + deadlineMs,
2431
+ progress
2432
+ });
2433
+ upload.catch(() => void 0);
2434
+ let result;
2435
+ try {
2436
+ const raced = await Promise.race([upload, deadline]);
2437
+ if (raced === "deadline") {
2438
+ const error = `the upload did not finish within ${formatDuration(deadlineMs)}: ${stoppedSummary(progress)}`;
2439
+ logger.warn(
2440
+ `source map upload: ${error}. ${CONTINUES} To upload more per build, raise uploadTimeoutMs${progress.protocol === "bulk" ? "" : " (or uploadConcurrency)"}; see "Large builds" in the source maps guide.`
2441
+ );
2442
+ return { ok: false, error };
2443
+ }
2444
+ result = raced;
2445
+ } catch (error) {
2446
+ const message = controller.signal.aborted ? `the upload did not finish within ${formatDuration(deadlineMs)}: ${stoppedSummary(progress)}` : errorMessage(error);
2447
+ const partial = progress.uploaded + progress.skipped > 0 ? ` (before it stopped: ${stoppedSummary(progress)}. ${CONTINUES})` : "";
2448
+ logger.error(`source map upload failed: ${message}${controller.signal.aborted ? ` ${CONTINUES}` : partial}`);
2449
+ return { ok: false, error: message };
2450
+ } finally {
2451
+ clearTimeout(timer);
2452
+ clearInterval(ticker);
2453
+ }
2454
+ for (const f of result.failed.slice(0, MAX_FAILURE_LINES)) logger.warn(`could not upload ${f.fileName ?? f.chunkId}: ${f.error}`);
2455
+ if (result.failed.length > MAX_FAILURE_LINES) logger.warn(`\u2026 and ${count(result.failed.length - MAX_FAILURE_LINES)} more source map(s) could not be uploaded`);
2456
+ logger.info(
2457
+ `source maps${releaseNote}: ${count(result.uploaded.length)} uploaded, ${count(result.skipped.length)} already on the server, ${count(result.failed.length)} failed (${formatDuration(Date.now() - started)})`
2458
+ );
2459
+ return result.failed.length === 0 ? { ok: true, result } : { ok: false, result, error: `${result.failed.length} source map(s) could not be uploaded` };
2460
+ }
2461
+
2462
+ export { NO_API_KEY_MESSAGE, collectUploads, createFileFilter, createLogger, deleteAllSourcemaps, errorMessage, findDebugId, findSourceMappingUrl, hasNativeRegistration, hasStarkoRegistration, injectDebugId, injectDirectory, localMapReference, planInjection, resolveConnection, resolveReleaseInfo, runUpload, shouldDeleteSourcemaps, stripCssSourceMappingUrl, stripSourceMappingUrl };