@afterpack/integration-utils 0.1.0-rc.20260925T1347

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,4566 @@
1
+ //#region rolldown:runtime
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
+ key = keys[i];
11
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
+ get: ((k) => from[k]).bind(null, key),
13
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
+ });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
+ value: mod,
20
+ enumerable: true
21
+ }) : target, mod));
22
+
23
+ //#endregion
24
+ const node_fs = __toESM(require("node:fs"));
25
+ const node_path = __toESM(require("node:path"));
26
+ const node_module = __toESM(require("node:module"));
27
+ const node_zlib = __toESM(require("node:zlib"));
28
+ const node_crypto = __toESM(require("node:crypto"));
29
+ const node_url = __toESM(require("node:url"));
30
+ const node_fs_promises = __toESM(require("node:fs/promises"));
31
+ const node_child_process = __toESM(require("node:child_process"));
32
+ const __jridgewell_sourcemap_codec = __toESM(require("@jridgewell/sourcemap-codec"));
33
+ const node_os = __toESM(require("node:os"));
34
+
35
+ //#region ../protection-map/codec.mjs
36
+ const COMPACT_SCHEMA_VERSION = 5;
37
+ const DICT_FIELDS = [
38
+ "nodeKind",
39
+ "preservedReason",
40
+ "reversalClass",
41
+ "band",
42
+ "costClass",
43
+ "transform",
44
+ "category",
45
+ "phase",
46
+ "severity",
47
+ "mechanism",
48
+ "disposition",
49
+ "reason",
50
+ "proHint"
51
+ ];
52
+ const REGION_COLUMNS = [
53
+ "span",
54
+ "nodeKind",
55
+ "preservedReason",
56
+ "reversalClass",
57
+ "score",
58
+ "entropyRaw",
59
+ "transformCount",
60
+ "sizeDeltaEst",
61
+ "costClass",
62
+ "decodeOps",
63
+ "callFrames",
64
+ "band"
65
+ ];
66
+ const SPOTLIGHT_COLUMNS = [
67
+ "span",
68
+ "severity",
69
+ "mechanism",
70
+ "disposition",
71
+ "sample",
72
+ "bytes",
73
+ "reason",
74
+ "proHint",
75
+ "reversalClass"
76
+ ];
77
+ const LINEAGE_COLUMNS = [
78
+ "transform",
79
+ "category",
80
+ "phase",
81
+ "entropyGain",
82
+ "sizeDeltaEst",
83
+ "label"
84
+ ];
85
+ function regionScalar(r, col) {
86
+ switch (col) {
87
+ case "span": return r.span;
88
+ case "nodeKind": return r.nodeKind;
89
+ case "preservedReason": return r.preservedReason;
90
+ case "reversalClass": return r.reversalClass;
91
+ case "score": return r.score;
92
+ case "entropyRaw": return r.entropyRaw;
93
+ case "transformCount": return r.transformCount;
94
+ case "sizeDeltaEst": return r.sizeDeltaEst;
95
+ case "costClass": return r.perf ? r.perf.costClass : void 0;
96
+ case "decodeOps": return r.perf ? r.perf.decodeOps : void 0;
97
+ case "callFrames": return r.perf ? r.perf.callFrames : void 0;
98
+ case "band": return r.band;
99
+ default: return void 0;
100
+ }
101
+ }
102
+ function spotScalar(s, col) {
103
+ switch (col) {
104
+ case "span": return s.span;
105
+ case "severity": return s.severity;
106
+ case "mechanism": return s.mechanism;
107
+ case "disposition": return s.disposition;
108
+ case "sample": return s.sample;
109
+ case "bytes": return s.bytes;
110
+ case "reason": return s.reason;
111
+ case "proHint": return s.proHint;
112
+ case "reversalClass": return s.reversalClass;
113
+ default: return void 0;
114
+ }
115
+ }
116
+ function encodeCompact(data, { includeLineage = true } = {}) {
117
+ const files = data && Array.isArray(data.files) ? data.files : [];
118
+ const dictMaps = new Map();
119
+ const dict = {};
120
+ for (const f of DICT_FIELDS) {
121
+ dictMaps.set(f, new Map());
122
+ dict[f] = [];
123
+ }
124
+ const isNullHole = (value) => value == null;
125
+ const intern = (field, value) => {
126
+ if (isNullHole(value)) return value;
127
+ const m = dictMaps.get(field);
128
+ let idx = m.get(value);
129
+ if (idx === void 0) {
130
+ idx = dict[field].length;
131
+ dict[field].push(value);
132
+ m.set(value, idx);
133
+ }
134
+ return idx;
135
+ };
136
+ const isDict = (col) => dictMaps.has(col);
137
+ const legend = {};
138
+ const encFiles = files.map((fdoc) => {
139
+ const regions = fdoc && Array.isArray(fdoc.regions) ? fdoc.regions : [];
140
+ const spotlights = fdoc && Array.isArray(fdoc.spotlights) ? fdoc.spotlights : [];
141
+ for (const r of regions) {
142
+ const cls = r?.reversalClass;
143
+ if (cls != null && !(cls in legend)) legend[cls] = {
144
+ why: r.why == null ? null : r.why,
145
+ tier: r.tier == null ? null : r.tier,
146
+ ceiling: r.ceiling == null ? null : r.ceiling
147
+ };
148
+ }
149
+ const rcols = {};
150
+ for (const col of REGION_COLUMNS) {
151
+ const dictted = isDict(col);
152
+ const arr = new Array(regions.length);
153
+ for (let i = 0; i < regions.length; i++) {
154
+ const v = regionScalar(regions[i], col);
155
+ arr[i] = dictted ? intern(col, v) : v;
156
+ }
157
+ rcols[col] = arr;
158
+ }
159
+ if (includeLineage) {
160
+ const lin = new Array(regions.length);
161
+ const capped = {};
162
+ let hasLineage = false;
163
+ let hasCapped = false;
164
+ for (let i = 0; i < regions.length; i++) {
165
+ const steps = regions[i] && Array.isArray(regions[i].lineage) ? regions[i].lineage : [];
166
+ if (steps.length) hasLineage = true;
167
+ lin[i] = steps.map((st) => [
168
+ intern("transform", st.transform),
169
+ intern("category", st.category),
170
+ intern("phase", st.phase),
171
+ st.entropyGain,
172
+ st.sizeDeltaEst,
173
+ st.label == null ? null : st.label
174
+ ]);
175
+ const lc = regions[i]?.lineageCapped;
176
+ if (lc != null) {
177
+ capped[i] = lc;
178
+ hasCapped = true;
179
+ }
180
+ }
181
+ if (hasLineage) rcols.lineage = lin;
182
+ if (hasCapped) rcols.lineageCapped = capped;
183
+ }
184
+ const scols = {};
185
+ for (const col of SPOTLIGHT_COLUMNS) {
186
+ const dictted = isDict(col);
187
+ const arr = new Array(spotlights.length);
188
+ for (let j = 0; j < spotlights.length; j++) {
189
+ const v = spotScalar(spotlights[j], col);
190
+ arr[j] = dictted ? intern(col, v) : v;
191
+ }
192
+ scols[col] = arr;
193
+ }
194
+ return {
195
+ file: fdoc.file,
196
+ regions: {
197
+ n: regions.length,
198
+ cols: rcols
199
+ },
200
+ spotlights: {
201
+ n: spotlights.length,
202
+ cols: scols
203
+ },
204
+ aggregate: fdoc.aggregate,
205
+ ...fdoc.renamedSpans?.length ? { renamedSpans: fdoc.renamedSpans } : {},
206
+ ...fdoc.extractedSpans?.length ? { extractedSpans: fdoc.extractedSpans } : {}
207
+ };
208
+ });
209
+ const prunedDict = {};
210
+ for (const f of DICT_FIELDS) if (dict[f].length) prunedDict[f] = dict[f];
211
+ return {
212
+ schemaVersion: COMPACT_SCHEMA_VERSION,
213
+ ...data && data.spanUnits !== void 0 ? { spanUnits: data.spanUnits } : {},
214
+ generatedAt: data && data.generatedAt !== void 0 ? data.generatedAt : null,
215
+ engine: data && data.engine !== void 0 ? data.engine : null,
216
+ legend,
217
+ dict: prunedDict,
218
+ columns: {
219
+ region: REGION_COLUMNS,
220
+ spotlight: SPOTLIGHT_COLUMNS,
221
+ lineage: LINEAGE_COLUMNS
222
+ },
223
+ files: encFiles
224
+ };
225
+ }
226
+
227
+ //#endregion
228
+ //#region ../protection-map/render-core.mjs
229
+ const LINEAGE_EMBED_CAP = 20;
230
+ const PLACEHOLDER = "__AFTERPACK_DATA__";
231
+ function defaultTemplatePath() {
232
+ return (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href).resolve("@afterpack/protection-map/template.html");
233
+ }
234
+ function readDefaultTemplate() {
235
+ return (0, node_fs.readFileSync)(defaultTemplatePath(), "utf8");
236
+ }
237
+ function normalizeToFiles(raw) {
238
+ if (raw && Array.isArray(raw.files)) return raw;
239
+ return { files: [raw] };
240
+ }
241
+ function capLineage(data) {
242
+ let cappedRegions = 0;
243
+ let totalLineageStepsRemoved = 0;
244
+ for (const fileDoc of data.files || []) for (const region of fileDoc?.regions || []) if (Array.isArray(region.lineage) && region.lineage.length > LINEAGE_EMBED_CAP) {
245
+ const originalLength = region.lineage.length;
246
+ region.lineage = region.lineage.slice(0, LINEAGE_EMBED_CAP);
247
+ region.lineageCapped = originalLength;
248
+ cappedRegions += 1;
249
+ totalLineageStepsRemoved += originalLength - LINEAGE_EMBED_CAP;
250
+ }
251
+ return {
252
+ cappedRegions,
253
+ totalLineageStepsRemoved
254
+ };
255
+ }
256
+ function stripLineage(data) {
257
+ for (const fileDoc of data.files || []) for (const region of fileDoc?.regions || []) {
258
+ if (Array.isArray(region.lineage) && region.lineage.length > 0) region.lineage = [];
259
+ if (region.lineageCapped != null) delete region.lineageCapped;
260
+ }
261
+ }
262
+ function embedCompact(template, compact) {
263
+ const occurrences = template.split(PLACEHOLDER).length - 1;
264
+ if (occurrences !== 1) throw new Error(`expected exactly one "${PLACEHOLDER}" sentinel in the template, found ${occurrences}`);
265
+ const json = JSON.stringify(compact);
266
+ const base64 = (0, node_zlib.gzipSync)(Buffer.from(json, "utf8"), { level: 9 }).toString("base64");
267
+ return template.replace(PLACEHOLDER, () => base64);
268
+ }
269
+ function renderProtectionMapHtml(raw, { template, includeLineage = true } = {}) {
270
+ const data = normalizeToFiles(raw);
271
+ let cappedRegions = 0;
272
+ let totalLineageStepsRemoved = 0;
273
+ if (includeLineage) ({cappedRegions, totalLineageStepsRemoved} = capLineage(data));
274
+ else stripLineage(data);
275
+ const compact = encodeCompact(data, { includeLineage });
276
+ const html = embedCompact(template ?? readDefaultTemplate(), compact);
277
+ return {
278
+ html,
279
+ files: data.files.length,
280
+ cappedRegions,
281
+ totalLineageStepsRemoved
282
+ };
283
+ }
284
+
285
+ //#endregion
286
+ //#region src/paths.ts
287
+ const COMBINED_PROTECTION_MAP_NAME = "protectionMap.html";
288
+ function shortHash(content) {
289
+ return (0, node_crypto.createHash)("sha256").update(content, "utf8").digest("hex").slice(0, 8);
290
+ }
291
+ function resolveArtifactPaths(outPath, mode, contentHash) {
292
+ const { dir, name, ext } = (0, node_path.parse)(outPath);
293
+ const stem = (0, node_path.join)(dir, name);
294
+ return {
295
+ mapPath: `${outPath}.map`,
296
+ protectionMapPath: mode === "single" ? `${stem}.protectionMap.html` : null,
297
+ backupPath: contentHash != null ? `${stem}.backup.${contentHash}${ext}` : null
298
+ };
299
+ }
300
+ function combinedProtectionMapPath(buildDir) {
301
+ return (0, node_path.join)(buildDir, COMBINED_PROTECTION_MAP_NAME);
302
+ }
303
+ function findUpward(startDir, fileName, options = {}) {
304
+ let current = (0, node_path.resolve)(startDir);
305
+ for (;;) {
306
+ const candidate = (0, node_path.join)(current, fileName);
307
+ if ((0, node_fs.existsSync)(candidate)) return candidate;
308
+ if (options.stopAtDir?.(current)) return null;
309
+ const parent = (0, node_path.dirname)(current);
310
+ if (parent === current) return null;
311
+ current = parent;
312
+ }
313
+ }
314
+
315
+ //#endregion
316
+ //#region src/artifacts.ts
317
+ const AFTERPACK_DIR = ".afterpack";
318
+ const GITIGNORE_ENTRIES = [
319
+ ".afterpack/",
320
+ "*.protectionMap.html",
321
+ "protectionMap.html",
322
+ "*.backup.*",
323
+ "*.map"
324
+ ];
325
+ const GITIGNORE_FILE = ".gitignore";
326
+ const GITIGNORE_BLOCK_HEADER = "# AfterPack artifacts (auto-added)";
327
+ const PUBLIC_SEGMENTS = new Set([
328
+ "public",
329
+ "static",
330
+ "assets",
331
+ "dist",
332
+ "build",
333
+ "out",
334
+ "www",
335
+ "htdocs",
336
+ "_next"
337
+ ]);
338
+ const DEFAULT_LOGGER = {
339
+ warn: (m) => console.warn(m),
340
+ log: (m) => console.log(m)
341
+ };
342
+ function appendSourceMappingURL(code, mapPath) {
343
+ const comment = `//# sourceMappingURL=${(0, node_path.basename)(mapPath)}`;
344
+ if (code.includes(comment)) return code;
345
+ const needsNewline = code.length > 0 && !code.endsWith("\n");
346
+ return `${code}${needsNewline ? "\n" : ""}${comment}\n`;
347
+ }
348
+ function writeArtifacts(input) {
349
+ const { outPath, code, sourceMapJson, protectionMapJson, originalSource, policy } = input;
350
+ const mode = input.mode ?? "single";
351
+ const afterpackDir = input.afterpackDir ?? AFTERPACK_DIR;
352
+ const logger = input.logger ?? DEFAULT_LOGGER;
353
+ const hash = policy.backup && originalSource != null ? shortHash(originalSource) : void 0;
354
+ const paths = resolveArtifactPaths(outPath, mode, hash);
355
+ const result = {
356
+ codePath: outPath,
357
+ mapPath: null,
358
+ backupPath: null,
359
+ protectionMapPath: null,
360
+ wroteSourceMappingURL: false
361
+ };
362
+ if (policy.backup && originalSource != null && paths.backupPath != null) {
363
+ (0, node_fs.writeFileSync)(paths.backupPath, originalSource);
364
+ result.backupPath = paths.backupPath;
365
+ }
366
+ const willWriteMap = policy.sourceMap && sourceMapJson != null;
367
+ let finalCode = code;
368
+ if (willWriteMap && policy.emitSourceMappingURL) {
369
+ finalCode = appendSourceMappingURL(code, paths.mapPath);
370
+ result.wroteSourceMappingURL = true;
371
+ }
372
+ (0, node_fs.writeFileSync)(outPath, finalCode);
373
+ if (willWriteMap && sourceMapJson != null) {
374
+ (0, node_fs.writeFileSync)(paths.mapPath, sourceMapJson);
375
+ result.mapPath = paths.mapPath;
376
+ }
377
+ if (mode === "single" && policy.protectionMap && protectionMapJson != null) {
378
+ (0, node_fs.mkdirSync)(afterpackDir, { recursive: true });
379
+ const pmPath = (0, node_path.join)(afterpackDir, (0, node_path.basename)(paths.protectionMapPath));
380
+ if (policy.protectionMapInProd) warnProtectionMapInProd(pmPath, logger);
381
+ else logger.log(`[afterpack] wrote Protection Map -> ${pmPath} (gitignored; set protectionMap.enabled:false to skip)`);
382
+ const { html } = renderProtectionMapHtml(protectionMapJson);
383
+ (0, node_fs.writeFileSync)(pmPath, html);
384
+ result.protectionMapPath = pmPath;
385
+ }
386
+ return result;
387
+ }
388
+ const REVERSAL_CLASS_ORDER = [
389
+ "preserved",
390
+ "renamed-encoded",
391
+ "flattened-fused",
392
+ "destroyed-fused"
393
+ ];
394
+ function round4(v) {
395
+ return Math.round(v * 1e4) / 1e4;
396
+ }
397
+ function isRuntimeSource(rawPath) {
398
+ const p = rawPath ?? "";
399
+ if (p.includes("[turbopack]") || p.includes("[next]")) return true;
400
+ if (/(^|\/)webpack\/(runtime|bootstrap)/.test(p)) return true;
401
+ if (p.includes("webpack://_N_E/webpack/")) return true;
402
+ if (/node_modules\/\.pnpm\/next[@/]/.test(p)) return true;
403
+ if (/(^|\/)node_modules\/next\//.test(p)) return true;
404
+ return false;
405
+ }
406
+ function cleanSourcePath(rawPath) {
407
+ let p = rawPath ?? "";
408
+ p = p.replace(/^turbopack:\/\/\/\[project\]\//, "");
409
+ p = p.replace(/^turbopack:\/\/\//, "");
410
+ p = p.replace(/^webpack:\/\/_N_E\/\.\//, "");
411
+ p = p.replace(/^webpack:\/\/_N_E\//, "");
412
+ p = p.replace(/^webpack:\/\//, "");
413
+ p = p.replace(/^\.\//, "");
414
+ p = p.replace(/node_modules\/\.pnpm\/[^/]+\/node_modules\//, "node_modules/");
415
+ return p;
416
+ }
417
+ function computeAggregate(regions, spotlights, renamedCount = 0, directives = [], extractedCount = 0) {
418
+ const regionCount = regions.length;
419
+ let sumEntropy = 0;
420
+ let maxEntropy = 0;
421
+ let minEntropy = regionCount === 0 ? 0 : 1;
422
+ let totalTransforms = 0;
423
+ let decodeOps = 0;
424
+ let callFrames = 0;
425
+ let sizeDeltaEstTotal = 0;
426
+ const classCounts = {
427
+ preserved: 0,
428
+ "renamed-encoded": 0,
429
+ "flattened-fused": 0,
430
+ "destroyed-fused": 0
431
+ };
432
+ let maxClassRank = 0;
433
+ for (const r of regions) {
434
+ const e = typeof r.entropy === "number" ? r.entropy : 0;
435
+ sumEntropy += e;
436
+ if (e > maxEntropy) maxEntropy = e;
437
+ if (e < minEntropy) minEntropy = e;
438
+ totalTransforms += r.transformCount ?? (Array.isArray(r.lineage) ? r.lineage.length : 0);
439
+ if (r.perf) {
440
+ decodeOps += r.perf.decodeOps ?? 0;
441
+ callFrames += r.perf.callFrames ?? 0;
442
+ }
443
+ sizeDeltaEstTotal += r.sizeDeltaEst ?? 0;
444
+ const cls = r.reversalClass;
445
+ if (cls != null && cls in classCounts) classCounts[cls] += 1;
446
+ const rank = REVERSAL_CLASS_ORDER.indexOf(cls);
447
+ if (rank > maxClassRank) maxClassRank = rank;
448
+ }
449
+ let leakCount = 0;
450
+ for (const s of spotlights) if (s.severity === "leak") leakCount += 1;
451
+ return {
452
+ avgEntropy: round4(regionCount === 0 ? 0 : sumEntropy / regionCount),
453
+ maxEntropy: round4(maxEntropy),
454
+ minEntropy: round4(regionCount === 0 ? 0 : minEntropy),
455
+ totalTransforms,
456
+ renamedCount,
457
+ extractedCount,
458
+ weakRegions: spotlights.length,
459
+ leakCount,
460
+ perfCostTotal: {
461
+ decodeOps,
462
+ callFrames
463
+ },
464
+ sizeDeltaEstTotal,
465
+ classSummary: {
466
+ ...classCounts,
467
+ maxClassReached: REVERSAL_CLASS_ORDER[maxClassRank]
468
+ },
469
+ directives
470
+ };
471
+ }
472
+ const SPAN_PACK_LIMIT = 1 << 25;
473
+ function packable(v, limit) {
474
+ return v >= 0 && v < limit && (v | 0) === v;
475
+ }
476
+ function spanKey(start, end, kind) {
477
+ if (packable(start, SPAN_PACK_LIMIT) && packable(end, SPAN_PACK_LIMIT) && packable(kind, 4)) return (start * SPAN_PACK_LIMIT + end) * 4 + kind;
478
+ return `${start},${end},${kind}`;
479
+ }
480
+ function mergeEntries(entries, path) {
481
+ const regions = [];
482
+ const seenRegion = new Set();
483
+ const spotlights = [];
484
+ const seenSpot = new Set();
485
+ const renamedSpans = [];
486
+ const seenRenamed = new Set();
487
+ const extractedFlat = [];
488
+ const seenExtracted = new Set();
489
+ const directives = [];
490
+ const seenDirective = new Set();
491
+ for (const e of entries) {
492
+ for (const r of e.regions ?? []) {
493
+ const key = Array.isArray(r.span) ? `${r.span[0]},${r.span[1]}` : `~${regions.length}`;
494
+ if (seenRegion.has(key)) continue;
495
+ seenRegion.add(key);
496
+ regions.push(r);
497
+ }
498
+ for (const s of e.spotlights ?? []) {
499
+ const sp = Array.isArray(s.span) ? `${s.span[0]},${s.span[1]}` : "";
500
+ const key = `${sp}|${s.severity ?? ""}|${s.sample ?? ""}`;
501
+ if (seenSpot.has(key)) continue;
502
+ seenSpot.add(key);
503
+ spotlights.push(s);
504
+ }
505
+ for (const rn of e.renamedSpans ?? []) {
506
+ const key = spanKey(rn[0], rn[1], 0);
507
+ if (seenRenamed.has(key)) continue;
508
+ seenRenamed.add(key);
509
+ renamedSpans.push(rn);
510
+ }
511
+ const flat = e.extractedSpans ?? [];
512
+ for (let i = 0; i + 2 < flat.length; i += 3) {
513
+ const key = spanKey(flat[i], flat[i + 1], flat[i + 2]);
514
+ if (seenExtracted.has(key)) continue;
515
+ seenExtracted.add(key);
516
+ extractedFlat.push(flat[i], flat[i + 1], flat[i + 2]);
517
+ }
518
+ const agg = e.aggregate;
519
+ for (const d of agg?.directives ?? []) {
520
+ const key = typeof d === "string" ? d : JSON.stringify(d);
521
+ if (seenDirective.has(key)) continue;
522
+ seenDirective.add(key);
523
+ directives.push(d);
524
+ }
525
+ }
526
+ renamedSpans.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
527
+ const extractedCount = extractedFlat.length / 3 | 0;
528
+ const order = new Uint32Array(extractedCount);
529
+ for (let i = 0; i < extractedCount; i++) order[i] = i;
530
+ order.sort((x, y) => {
531
+ const a = x * 3;
532
+ const b = y * 3;
533
+ return extractedFlat[a] - extractedFlat[b] || extractedFlat[a + 1] - extractedFlat[b + 1] || extractedFlat[a + 2] - extractedFlat[b + 2];
534
+ });
535
+ const extractedSpans = new Array(extractedCount * 3);
536
+ for (let i = 0; i < extractedCount; i++) {
537
+ const from = order[i] * 3;
538
+ const to = i * 3;
539
+ extractedSpans[to] = extractedFlat[from];
540
+ extractedSpans[to + 1] = extractedFlat[from + 1];
541
+ extractedSpans[to + 2] = extractedFlat[from + 2];
542
+ }
543
+ regions.sort((a, b) => {
544
+ const er = (b.entropyRaw ?? 0) - (a.entropyRaw ?? 0);
545
+ if (er !== 0) return er;
546
+ const as = Array.isArray(a.span) ? a.span[0] : 0;
547
+ const bs = Array.isArray(b.span) ? b.span[0] : 0;
548
+ if (as !== bs) return as - bs;
549
+ const ae = Array.isArray(a.span) ? a.span[1] : 0;
550
+ const be = Array.isArray(b.span) ? b.span[1] : 0;
551
+ return ae - be;
552
+ });
553
+ const rep = entries.find((e) => e.file?.sourceOrigin === "original") ?? entries[0];
554
+ const file = {
555
+ ...rep.file ?? {},
556
+ path,
557
+ sourceOrigin: "original"
558
+ };
559
+ let outputSum = 0;
560
+ let bundledSum = 0;
561
+ let sawOutput = false;
562
+ let sawBundled = false;
563
+ let anyEstimated = false;
564
+ for (const e of entries) {
565
+ const m = e.file;
566
+ if (!m) continue;
567
+ if (typeof m.outputSize === "number" && Number.isFinite(m.outputSize)) {
568
+ outputSum += m.outputSize;
569
+ sawOutput = true;
570
+ }
571
+ if (typeof m.bundledInputSize === "number" && Number.isFinite(m.bundledInputSize)) {
572
+ bundledSum += m.bundledInputSize;
573
+ sawBundled = true;
574
+ }
575
+ if (m.outputSizeEstimated) anyEstimated = true;
576
+ }
577
+ if (sawBundled) file.bundledInputSize = bundledSum;
578
+ if (sawOutput) {
579
+ file.outputSize = outputSum;
580
+ file.outputSizeEstimated = anyEstimated;
581
+ }
582
+ const denom = sawBundled && bundledSum > 0 ? bundledSum : file.inputSize;
583
+ if (sawOutput && typeof denom === "number" && denom > 0) file.inflationRatio = round4(outputSum / denom);
584
+ else if (sawOutput) file.inflationRatio = 0;
585
+ return {
586
+ file,
587
+ regions,
588
+ spotlights,
589
+ renamedSpans,
590
+ extractedSpans,
591
+ aggregate: computeAggregate(regions, spotlights, renamedSpans.length, directives, extractedCount)
592
+ };
593
+ }
594
+ function buildProjectFileTree(files) {
595
+ const byPath = new Map();
596
+ const pathOrder = [];
597
+ for (const raw of files) {
598
+ const entry = raw;
599
+ const file = entry?.file;
600
+ if (!file) continue;
601
+ if (file.sourceOrigin !== "original") continue;
602
+ if (isRuntimeSource(file.path)) continue;
603
+ const clean = cleanSourcePath(file.path);
604
+ const srcKey = file.originalSource ?? "";
605
+ let bySrc = byPath.get(clean);
606
+ if (!bySrc) {
607
+ bySrc = new Map();
608
+ byPath.set(clean, bySrc);
609
+ pathOrder.push(clean);
610
+ }
611
+ const group$1 = bySrc.get(srcKey);
612
+ if (group$1) group$1.push(entry);
613
+ else bySrc.set(srcKey, [entry]);
614
+ }
615
+ const out = [];
616
+ for (const clean of pathOrder) {
617
+ const bySrc = byPath.get(clean);
618
+ const variants = [...bySrc.values()];
619
+ variants.forEach((entries, i) => {
620
+ const path = i === 0 ? clean : `${clean}#${i + 1}`;
621
+ const merged = mergeEntries(entries, path);
622
+ if (i > 0 && merged.file) merged.file.pathCollision = true;
623
+ out.push(merged);
624
+ });
625
+ }
626
+ return out;
627
+ }
628
+ function writeCombinedProtectionMap(input) {
629
+ const { buildDir, docs, policy } = input;
630
+ const afterpackDir = input.afterpackDir ?? AFTERPACK_DIR;
631
+ const logger = input.logger ?? DEFAULT_LOGGER;
632
+ if (!policy.protectionMap || docs.length === 0) return null;
633
+ (0, node_fs.mkdirSync)(afterpackDir, { recursive: true });
634
+ const outPath = (0, node_path.join)(afterpackDir, input.fileName ?? (0, node_path.basename)(combinedProtectionMapPath(buildDir)));
635
+ if (policy.protectionMapInProd) warnProtectionMapInProd(outPath, logger);
636
+ else logger.log(`[afterpack] wrote Protection Map -> ${outPath} (gitignored; set protectionMap.enabled:false to skip)`);
637
+ const flat = docs.flatMap((doc) => {
638
+ if (!doc) return [];
639
+ const f = doc.files;
640
+ return Array.isArray(f) ? f : [doc];
641
+ });
642
+ const files = buildProjectFileTree(flat);
643
+ const envelope = docs.find((d) => !!d && (d.schemaVersion !== void 0 || d.engine !== void 0));
644
+ const { html } = renderProtectionMapHtml({
645
+ schemaVersion: envelope?.schemaVersion,
646
+ spanUnits: envelope?.spanUnits,
647
+ engine: envelope?.engine,
648
+ files
649
+ }, { includeLineage: true });
650
+ (0, node_fs.writeFileSync)(outPath, html);
651
+ return outPath;
652
+ }
653
+ function warnProtectionMapInProd(pmPath, logger) {
654
+ logger.warn(`[afterpack] WARNING: the Protection Map is ENABLED in a PRODUCTION build. This LOCAL file embeds your ORIGINAL SOURCE and surviving-literal samples -- NEVER serve or commit it. Writing it to the gitignored "${pmPath}" instead of alongside the build output.`);
655
+ }
656
+ function nearestGitignore(startDir) {
657
+ return findUpward(startDir, GITIGNORE_FILE, { stopAtDir: (dir) => (0, node_fs.existsSync)((0, node_path.join)(dir, ".git")) });
658
+ }
659
+ function ensureGitignore(targetDir) {
660
+ const gitignorePath = nearestGitignore(targetDir);
661
+ if (gitignorePath === null) return [];
662
+ let existing = "";
663
+ try {
664
+ existing = (0, node_fs.readFileSync)(gitignorePath, "utf8");
665
+ } catch {
666
+ existing = "";
667
+ }
668
+ const present = new Set(existing.split(/\r?\n/).map((l) => l.trim()));
669
+ const missing = GITIGNORE_ENTRIES.filter((e) => !present.has(e));
670
+ if (missing.length === 0) return [];
671
+ const prefix = existing.length > 0 && !existing.endsWith("\n") ? "\n" : "";
672
+ const block = `${prefix}\n${GITIGNORE_BLOCK_HEADER}\n${missing.join("\n")}\n`;
673
+ (0, node_fs.writeFileSync)(gitignorePath, existing + block);
674
+ return missing;
675
+ }
676
+ function warnIfPublicPath(artifactPath, logger = DEFAULT_LOGGER) {
677
+ const segments$1 = artifactPath.split(/[\\/]/).filter(Boolean);
678
+ const hit = segments$1.find((s) => PUBLIC_SEGMENTS.has(s.toLowerCase()));
679
+ if (hit == null) return false;
680
+ logger.warn(`[afterpack] WARNING: writing "${artifactPath}" under a public/served path segment ("${hit}"). Source maps and Protection Maps must NOT be served publicly -- a served obfuscator map is full deobfuscation. Move it out of the served tree or disable the artifact for this build.`);
681
+ return true;
682
+ }
683
+
684
+ //#endregion
685
+ //#region src/source-map.ts
686
+ const SOURCE_MAPPING_URL_RE = /\/\/[#@]\s*sourceMappingURL=(\S+)\s*$/gm;
687
+ const SOURCE_MAPPING_URL_LINE_RE = /^[ \t]*\/\/[#@]\s*sourceMappingURL=\S+[ \t]*\r?\n?/gm;
688
+ function withSourceMappingURL(code, url) {
689
+ const stripped = code.replace(SOURCE_MAPPING_URL_LINE_RE, "");
690
+ if (url == null) return stripped;
691
+ const separator = stripped.length > 0 && !stripped.endsWith("\n") ? "\n" : "";
692
+ return `${stripped}${separator}//# sourceMappingURL=${url}\n`;
693
+ }
694
+ function extractSourceMappingURL(code) {
695
+ let last = null;
696
+ for (const match of code.matchAll(SOURCE_MAPPING_URL_RE)) last = match[1];
697
+ return last;
698
+ }
699
+ function isRemoteSourceMappingURL(url) {
700
+ return /^https?:\/\//i.test(url) || url.startsWith("//");
701
+ }
702
+ function decodeDataUri(url) {
703
+ if (!url.startsWith("data:")) return null;
704
+ const comma = url.indexOf(",");
705
+ if (comma === -1) return null;
706
+ const meta = url.slice(5, comma);
707
+ const payload = url.slice(comma + 1);
708
+ try {
709
+ if (/;base64/i.test(meta)) return Buffer.from(payload, "base64").toString("utf8");
710
+ return decodeURIComponent(payload);
711
+ } catch {
712
+ return null;
713
+ }
714
+ }
715
+ function discoverInputSourceMap(jsPath, code) {
716
+ const adjacent = `${jsPath}.map`;
717
+ if ((0, node_fs.existsSync)(adjacent)) try {
718
+ return (0, node_fs.readFileSync)(adjacent, "utf8");
719
+ } catch {}
720
+ let source = code;
721
+ if (source == null) try {
722
+ source = (0, node_fs.readFileSync)(jsPath, "utf8");
723
+ } catch {
724
+ return null;
725
+ }
726
+ const url = extractSourceMappingURL(source);
727
+ if (url == null) return null;
728
+ if (url.startsWith("data:")) return decodeDataUri(url);
729
+ if (isRemoteSourceMappingURL(url)) return null;
730
+ let mapPath;
731
+ try {
732
+ mapPath = (0, node_path.isAbsolute)(url) ? url : (0, node_path.resolve)((0, node_path.dirname)(jsPath), decodeURIComponent(url));
733
+ } catch {
734
+ return null;
735
+ }
736
+ if (!(0, node_fs.existsSync)(mapPath)) return null;
737
+ try {
738
+ return (0, node_fs.readFileSync)(mapPath, "utf8");
739
+ } catch {
740
+ return null;
741
+ }
742
+ }
743
+
744
+ //#endregion
745
+ //#region src/bundle.ts
746
+ const BUNDLE_JS_RE = /\.[cm]?js$/;
747
+ function collectBundleJs(bundle, outDir) {
748
+ const files = [];
749
+ const inputs = new Map();
750
+ const entries = new Map();
751
+ for (const [fileName, entry] of Object.entries(bundle)) {
752
+ if (!BUNDLE_JS_RE.test(fileName)) continue;
753
+ const source = entry.type === "chunk" ? entry.code : typeof entry.source === "string" ? entry.source : void 0;
754
+ if (source === void 0) continue;
755
+ const filePath = (0, node_path.resolve)(outDir, fileName);
756
+ files.push(filePath);
757
+ entries.set(filePath, entry);
758
+ inputs.set(filePath, {
759
+ source,
760
+ sourceMap: entry.map ? entry.map.toString() : null
761
+ });
762
+ }
763
+ return {
764
+ files,
765
+ inputs,
766
+ entries
767
+ };
768
+ }
769
+ function dataUri(json) {
770
+ return `data:application/json;charset=utf-8;base64,${Buffer.from(json, "utf8").toString("base64")}`;
771
+ }
772
+ function applyBundleOutput(bundle, entry, out, policy) {
773
+ if (entry.type !== "chunk") {
774
+ entry.source = out.code;
775
+ return;
776
+ }
777
+ const mapName = entry.sourcemapFileName ?? null;
778
+ const inlineMap = mapName == null && entry.map != null;
779
+ const emitMap = policy.sourceMap && out.sourceMap != null;
780
+ let url = null;
781
+ if (emitMap && out.sourceMap != null) {
782
+ if (mapName != null && bundle[mapName]) {
783
+ bundle[mapName].source = out.sourceMap;
784
+ url = (0, node_path.basename)(mapName);
785
+ } else if (inlineMap) url = dataUri(out.sourceMap);
786
+ } else {
787
+ if (mapName != null) delete bundle[mapName];
788
+ entry.map = null;
789
+ }
790
+ entry.code = withSourceMappingURL(out.code, policy.emitSourceMappingURL ? url : null);
791
+ }
792
+
793
+ //#endregion
794
+ //#region src/glob.ts
795
+ function normalize(value) {
796
+ return value.includes("\\") ? value.replaceAll("\\", "/") : value;
797
+ }
798
+ function segments(value) {
799
+ return value.split("/").filter((part) => part !== "");
800
+ }
801
+ function isAnchored(pattern) {
802
+ if (pattern.startsWith("/")) return true;
803
+ return pattern.length >= 2 && pattern[1] === ":" && /^[A-Za-z]$/.test(pattern[0]);
804
+ }
805
+ function segmentMatches(pattern, seg) {
806
+ if (!pattern.includes("*") && !pattern.includes("?")) return pattern === seg;
807
+ const p = [...pattern];
808
+ const s = [...seg];
809
+ let pi = 0;
810
+ let si = 0;
811
+ let star = -1;
812
+ let starSi = 0;
813
+ while (si < s.length) if (pi < p.length && p[pi] === "*") {
814
+ star = pi;
815
+ starSi = si;
816
+ pi += 1;
817
+ } else if (pi < p.length && (p[pi] === "?" || p[pi] === s[si])) {
818
+ pi += 1;
819
+ si += 1;
820
+ } else if (star >= 0) {
821
+ pi = star + 1;
822
+ starSi += 1;
823
+ si = starSi;
824
+ } else return false;
825
+ return p.slice(pi).every((c) => c === "*");
826
+ }
827
+ function segmentsMatch(pattern, path) {
828
+ let pi = 0;
829
+ let si = 0;
830
+ let star = -1;
831
+ let starSi = 0;
832
+ while (si < path.length) if (pi < pattern.length && pattern[pi] === "**") {
833
+ star = pi;
834
+ starSi = si;
835
+ pi += 1;
836
+ } else if (pi < pattern.length && segmentMatches(pattern[pi], path[si])) {
837
+ pi += 1;
838
+ si += 1;
839
+ } else if (star >= 0) {
840
+ pi = star + 1;
841
+ starSi += 1;
842
+ si = starSi;
843
+ } else return false;
844
+ return pattern.slice(pi).every((s) => s === "**");
845
+ }
846
+ function matchesPath(pattern, path) {
847
+ const pat = normalize(pattern);
848
+ const parts = segments(pat);
849
+ if (parts.length === 0) return false;
850
+ const segs = segments(normalize(path));
851
+ if (isAnchored(pat)) return segmentsMatch(parts, segs);
852
+ for (let i = 0; i <= segs.length; i++) if (segmentsMatch(parts, segs.slice(i))) return true;
853
+ return false;
854
+ }
855
+ function reachesInto(pattern, dir) {
856
+ const pat = normalize(pattern);
857
+ const parts = segments(pat);
858
+ if (parts.length === 0) return false;
859
+ if (!isAnchored(pat)) return true;
860
+ for (let k = 1; k <= parts.length; k++) if (matchesPath(`/${parts.slice(0, k).join("/")}`, dir)) return true;
861
+ return false;
862
+ }
863
+
864
+ //#endregion
865
+ //#region src/collect.ts
866
+ const BACKUP_RE = /\.backup\.[0-9a-f]{8}\.[cm]?js$/;
867
+ const NODE_MODULES = "node_modules";
868
+ function isCollectableJs(name) {
869
+ if (BACKUP_RE.test(name)) return false;
870
+ return name.endsWith(".js") || name.endsWith(".mjs") || name.endsWith(".cjs");
871
+ }
872
+ function statOrNull(path) {
873
+ try {
874
+ return (0, node_fs.statSync)(path);
875
+ } catch {
876
+ return null;
877
+ }
878
+ }
879
+ function collectJsFiles(target, options = {}) {
880
+ const stat = statOrNull(target);
881
+ if (!stat) return [];
882
+ if (!stat.isDirectory()) return isCollectableJs((0, node_path.basename)(target)) ? [target] : [];
883
+ return walkJs(target, options.include ?? [], false, options.onNestedProject);
884
+ }
885
+ function entriesOf(dir) {
886
+ try {
887
+ return (0, node_fs.readdirSync)(dir, { withFileTypes: true });
888
+ } catch {
889
+ return [];
890
+ }
891
+ }
892
+ function kindOf(entry, full) {
893
+ if (entry.isDirectory()) return "dir";
894
+ if (entry.isFile()) return "file";
895
+ const stat = statOrNull(full);
896
+ if (!stat) return null;
897
+ return stat.isDirectory() ? "dir" : "file";
898
+ }
899
+ function isNestedProject(dir) {
900
+ return (0, node_fs.existsSync)((0, node_path.join)(dir, "package.json"));
901
+ }
902
+ function walkJs(dir, include, readmitted, onNestedProject) {
903
+ const out = [];
904
+ for (const entry of entriesOf(dir)) {
905
+ const name = entry.name;
906
+ const full = (0, node_path.join)(dir, name);
907
+ const kind = kindOf(entry, full);
908
+ if (kind === null) continue;
909
+ if (kind === "dir") {
910
+ const skipped = name === NODE_MODULES;
911
+ if (!skipped && !readmitted && isNestedProject(full)) {
912
+ onNestedProject?.(full);
913
+ continue;
914
+ }
915
+ if (skipped && !include.some((pattern) => reachesInto(pattern, full))) continue;
916
+ out.push(...walkJs(full, include, readmitted || skipped, onNestedProject));
917
+ } else if (isCollectableJs(name)) {
918
+ if (readmitted && !include.some((pattern) => matchesPath(pattern, full))) continue;
919
+ out.push(full);
920
+ }
921
+ }
922
+ return out;
923
+ }
924
+ function isSourceMap(name) {
925
+ return name.endsWith(".js.map") || name.endsWith(".mjs.map") || name.endsWith(".cjs.map");
926
+ }
927
+ function collectSourceMaps(dir) {
928
+ if (!(0, node_fs.existsSync)(dir)) return [];
929
+ const out = [];
930
+ for (const entry of entriesOf(dir)) {
931
+ const name = entry.name;
932
+ const full = (0, node_path.join)(dir, name);
933
+ const kind = kindOf(entry, full);
934
+ if (kind === null) continue;
935
+ if (kind === "dir") out.push(...collectSourceMaps(full));
936
+ else if (isSourceMap(name)) out.push(full);
937
+ }
938
+ return out;
939
+ }
940
+
941
+ //#endregion
942
+ //#region src/notices.ts
943
+ const NOTICE_MESSAGE_LIMIT = 500;
944
+ const NOTICE_LIMIT = 5;
945
+ const NOTICE_CODE_LIMIT = 64;
946
+ const NOTICE_HOSTS = new Set(["afterpack.dev", "www.afterpack.dev"]);
947
+ const ESC = 27;
948
+ const BEL = 7;
949
+ const C1_CSI = 155;
950
+ const C1_OSC = 157;
951
+ function isControl(code) {
952
+ return code < 32 || code >= 127 && code <= 159;
953
+ }
954
+ function isInvisibleFormat(code) {
955
+ return code === 1564 || code >= 8203 && code <= 8207 || code >= 8234 && code <= 8238 || code >= 8288 && code <= 8297 || code === 65279;
956
+ }
957
+ function skipCsi(text, from) {
958
+ let i = from;
959
+ while (i < text.length) {
960
+ const c = text.charCodeAt(i);
961
+ i += 1;
962
+ if (c >= 64 && c <= 126) return i;
963
+ }
964
+ return i;
965
+ }
966
+ function skipOsc(text, from) {
967
+ let i = from;
968
+ while (i < text.length) {
969
+ const c = text.charCodeAt(i);
970
+ if (c === BEL) return i + 1;
971
+ if (c === ESC) return text.charCodeAt(i + 1) === 92 ? i + 2 : i + 1;
972
+ if (c === 156) return i + 1;
973
+ i += 1;
974
+ }
975
+ return i;
976
+ }
977
+ function stripTerminalControls(text) {
978
+ let out = "";
979
+ let i = 0;
980
+ while (i < text.length) {
981
+ const c = text.charCodeAt(i);
982
+ if (c === ESC) {
983
+ const next = text.charCodeAt(i + 1);
984
+ if (next === 91) i = skipCsi(text, i + 2);
985
+ else if (next === 93) i = skipOsc(text, i + 2);
986
+ else i += Number.isNaN(next) ? 1 : 2;
987
+ continue;
988
+ }
989
+ if (c === C1_CSI) {
990
+ i = skipCsi(text, i + 1);
991
+ continue;
992
+ }
993
+ if (c === C1_OSC) {
994
+ i = skipOsc(text, i + 1);
995
+ continue;
996
+ }
997
+ if (isControl(c)) {
998
+ out += c === 9 || c === 10 || c === 13 ? " " : "";
999
+ i += 1;
1000
+ continue;
1001
+ }
1002
+ if (c === 8232 || c === 8233) {
1003
+ out += " ";
1004
+ i += 1;
1005
+ continue;
1006
+ }
1007
+ if (isInvisibleFormat(c)) {
1008
+ i += 1;
1009
+ continue;
1010
+ }
1011
+ out += text[i];
1012
+ i += 1;
1013
+ }
1014
+ return out;
1015
+ }
1016
+ function sanitizeServerText(value, limit = NOTICE_MESSAGE_LIMIT) {
1017
+ if (typeof value !== "string") return "";
1018
+ const clean = stripTerminalControls(value).replace(/\s+/g, " ").trim();
1019
+ if (clean.length <= limit) return clean;
1020
+ const chars = Array.from(clean);
1021
+ return chars.length > limit ? chars.slice(0, limit).join("") : clean;
1022
+ }
1023
+ function sanitizeNoticeUrl(value) {
1024
+ if (typeof value !== "string") return null;
1025
+ let url;
1026
+ try {
1027
+ url = new URL(value.trim());
1028
+ } catch {
1029
+ return null;
1030
+ }
1031
+ if (url.protocol !== "https:") return null;
1032
+ if (!NOTICE_HOSTS.has(url.hostname) || url.port !== "") return null;
1033
+ if (url.username !== "" || url.password !== "") return null;
1034
+ const href = url.href;
1035
+ return href.length <= NOTICE_MESSAGE_LIMIT ? href : null;
1036
+ }
1037
+ function noticeSeverity(value) {
1038
+ if (value === "info") return "info";
1039
+ if (value === "error" || value === "critical") return "error";
1040
+ return "warning";
1041
+ }
1042
+ function sanitizeNotices(raw) {
1043
+ if (!Array.isArray(raw)) return [];
1044
+ const out = [];
1045
+ for (const entry of raw) {
1046
+ if (out.length >= NOTICE_LIMIT) break;
1047
+ if (typeof entry !== "object" || entry === null) continue;
1048
+ const n = entry;
1049
+ const message = sanitizeServerText(n.message);
1050
+ if (message === "") continue;
1051
+ out.push({
1052
+ severity: noticeSeverity(n.severity),
1053
+ code: sanitizeServerText(n.code, NOTICE_CODE_LIMIT),
1054
+ message,
1055
+ url: sanitizeNoticeUrl(n.url)
1056
+ });
1057
+ }
1058
+ return out;
1059
+ }
1060
+ function formatNotice(notice) {
1061
+ const head = notice.severity === "info" ? "AfterPack notice" : `AfterPack ${notice.severity}`;
1062
+ const tail = notice.url ? ` ${notice.url}` : "";
1063
+ return `${head}: ${notice.message}${tail}`;
1064
+ }
1065
+ function reportNotices(raw, logger, prefix = (m) => m) {
1066
+ const notices = sanitizeNotices(raw);
1067
+ for (const notice of notices) {
1068
+ const line = prefix(formatNotice(notice));
1069
+ if (notice.severity === "info" || !logger.warn) logger.log(line);
1070
+ else logger.warn(line);
1071
+ }
1072
+ return notices;
1073
+ }
1074
+
1075
+ //#endregion
1076
+ //#region src/registry.ts
1077
+ const PRESET_VALUES = [
1078
+ "minify",
1079
+ "light",
1080
+ "medium",
1081
+ "hard",
1082
+ "extreme"
1083
+ ];
1084
+ const TRANSFORM_KIND_VALUES = [
1085
+ "stringEncoding",
1086
+ "controlFlowFlatten",
1087
+ "opaquePredicate",
1088
+ "mixedBooleanArithmetic",
1089
+ "integerBytecode",
1090
+ "crossDependency",
1091
+ "scopeDeepen",
1092
+ "comparisonHardening",
1093
+ "selfIntegrity",
1094
+ "objectConstruction"
1095
+ ];
1096
+ const REFLECTION_ALLOW_VALUES = [
1097
+ "functionToString",
1098
+ "nameIntrospection",
1099
+ "argumentsCallee",
1100
+ "prototypeChain",
1101
+ "decoratorMetadata",
1102
+ "constructorIntrospection",
1103
+ "angular",
1104
+ "nestjs"
1105
+ ];
1106
+ const BUILD_MODE_VALUES = ["production", "development"];
1107
+ const UNLIMITED = "unlimited";
1108
+ const DIRECTIVES_ENABLED_DEFAULT = true;
1109
+ const RESERVED_FILE_FORM = "{ \"identifiers\": { \"reserved\": [{ \"glob\": \"…\", \"names\": [\"…\"] }] } }";
1110
+ const REGIONS_FILE_FORM = "{ \"regions\": [{ \"start\": 0, \"end\": 100, \"complexity\": 40 }] }";
1111
+ const CONFIG_KEYS = [
1112
+ {
1113
+ path: "seed",
1114
+ shape: "scalar",
1115
+ scope: "program",
1116
+ tier: "free",
1117
+ surface: "engine",
1118
+ item: { kind: "seed" },
1119
+ default: "a new random seed per build"
1120
+ },
1121
+ {
1122
+ path: "preset",
1123
+ shape: "scalar",
1124
+ scope: "region",
1125
+ tier: "free",
1126
+ surface: "engine",
1127
+ item: {
1128
+ kind: "enum",
1129
+ values: PRESET_VALUES
1130
+ },
1131
+ default: "light"
1132
+ },
1133
+ {
1134
+ path: "complexity",
1135
+ shape: "scalar",
1136
+ scope: "region",
1137
+ tier: "free",
1138
+ surface: "engine",
1139
+ item: {
1140
+ kind: "number",
1141
+ min: 0
1142
+ },
1143
+ default: "the preset's value; light is 2",
1144
+ namedValuesOf: "preset"
1145
+ },
1146
+ {
1147
+ path: "inflation.max",
1148
+ shape: "scalar",
1149
+ scope: "region",
1150
+ tier: "free",
1151
+ surface: "engine",
1152
+ item: {
1153
+ kind: "unbounded",
1154
+ min: 0,
1155
+ unlimited: UNLIMITED
1156
+ },
1157
+ default: "the preset's output-size ladder: 1.2 / 2 / 2.5 / 4 / 7"
1158
+ },
1159
+ {
1160
+ path: "strings.encode",
1161
+ shape: "scalar",
1162
+ scope: "region",
1163
+ tier: "free",
1164
+ surface: "engine",
1165
+ item: { kind: "boolean" },
1166
+ default: "true at any positive complexity; false at 0"
1167
+ },
1168
+ {
1169
+ path: "strings.minLength",
1170
+ shape: "scalar",
1171
+ scope: "program",
1172
+ tier: "free",
1173
+ surface: "engine",
1174
+ item: {
1175
+ kind: "number",
1176
+ min: 0,
1177
+ integer: true
1178
+ },
1179
+ default: "0"
1180
+ },
1181
+ {
1182
+ path: "strings.leaks.max",
1183
+ shape: "scalar",
1184
+ scope: "program",
1185
+ tier: "free",
1186
+ surface: "engine",
1187
+ item: {
1188
+ kind: "number",
1189
+ min: 0,
1190
+ integer: true
1191
+ },
1192
+ default: "unset; the count is reported but never fails a build"
1193
+ },
1194
+ {
1195
+ path: "strings.preserveLiterals",
1196
+ shape: "list",
1197
+ scope: "program",
1198
+ tier: "free",
1199
+ surface: "engine",
1200
+ item: { kind: "string" },
1201
+ default: "[]"
1202
+ },
1203
+ {
1204
+ path: "paths.include",
1205
+ shape: "list",
1206
+ scope: "program",
1207
+ tier: "free",
1208
+ surface: "build",
1209
+ item: { kind: "string" },
1210
+ default: "[]"
1211
+ },
1212
+ {
1213
+ path: "paths.exclude",
1214
+ shape: "list",
1215
+ scope: "program",
1216
+ tier: "free",
1217
+ surface: "engine",
1218
+ item: { kind: "string" },
1219
+ default: "[]"
1220
+ },
1221
+ {
1222
+ path: "identifiers.rename",
1223
+ shape: "scalar",
1224
+ scope: "program",
1225
+ tier: "free",
1226
+ surface: "engine",
1227
+ item: { kind: "boolean" },
1228
+ default: "true"
1229
+ },
1230
+ {
1231
+ path: "identifiers.globals.rename",
1232
+ shape: "scalar",
1233
+ scope: "program",
1234
+ tier: "free",
1235
+ surface: "engine",
1236
+ item: { kind: "boolean" },
1237
+ default: "false"
1238
+ },
1239
+ {
1240
+ path: "identifiers.reserved",
1241
+ shape: "mixedList",
1242
+ scope: "program",
1243
+ tier: "free",
1244
+ surface: "engine",
1245
+ item: { kind: "reserved" },
1246
+ default: "[]",
1247
+ configFileForm: RESERVED_FILE_FORM
1248
+ },
1249
+ {
1250
+ path: "identifiers.methods.rename",
1251
+ shape: "scalar",
1252
+ scope: "program",
1253
+ tier: "free",
1254
+ surface: "engine",
1255
+ item: { kind: "boolean" },
1256
+ default: "true"
1257
+ },
1258
+ {
1259
+ path: "reflection.allow",
1260
+ shape: "list",
1261
+ scope: "program",
1262
+ tier: "free",
1263
+ surface: "engine",
1264
+ item: {
1265
+ kind: "enum",
1266
+ values: REFLECTION_ALLOW_VALUES
1267
+ },
1268
+ default: "[]"
1269
+ },
1270
+ {
1271
+ path: "sourceMap.enabled",
1272
+ shape: "scalar",
1273
+ scope: "program",
1274
+ tier: "free",
1275
+ surface: "engine",
1276
+ item: { kind: "boolean" },
1277
+ default: "true in development when an input map exists; false in production"
1278
+ },
1279
+ {
1280
+ path: "sourceMap.sourcesContent",
1281
+ shape: "scalar",
1282
+ scope: "program",
1283
+ tier: "free",
1284
+ surface: "engine",
1285
+ item: { kind: "boolean" },
1286
+ default: "true in development; false in production"
1287
+ },
1288
+ {
1289
+ path: "sourceMap.emitUrl",
1290
+ shape: "scalar",
1291
+ scope: "program",
1292
+ tier: "free",
1293
+ surface: "build",
1294
+ item: { kind: "boolean" },
1295
+ default: "true in development; false in production"
1296
+ },
1297
+ {
1298
+ path: "protectionMap.enabled",
1299
+ shape: "scalar",
1300
+ scope: "program",
1301
+ tier: "free",
1302
+ surface: "engine",
1303
+ item: { kind: "boolean" },
1304
+ default: "true when the bundler emitted a source map"
1305
+ },
1306
+ {
1307
+ path: "protectionMap.detailed",
1308
+ shape: "scalar",
1309
+ scope: "program",
1310
+ tier: "free",
1311
+ surface: "engine",
1312
+ item: { kind: "boolean" },
1313
+ default: "true"
1314
+ },
1315
+ {
1316
+ path: "regions",
1317
+ shape: "structured",
1318
+ scope: "program",
1319
+ tier: "pro",
1320
+ surface: "engine",
1321
+ item: { kind: "region" },
1322
+ default: "[]",
1323
+ configFileForm: REGIONS_FILE_FORM
1324
+ },
1325
+ {
1326
+ path: "transforms.controlFlowFlatten.enabled",
1327
+ shape: "scalar",
1328
+ scope: "program",
1329
+ tier: "free",
1330
+ surface: "engine",
1331
+ item: { kind: "boolean" },
1332
+ default: "true"
1333
+ },
1334
+ {
1335
+ path: "transforms.opaquePredicate.enabled",
1336
+ shape: "scalar",
1337
+ scope: "program",
1338
+ tier: "free",
1339
+ surface: "engine",
1340
+ item: { kind: "boolean" },
1341
+ default: "true"
1342
+ },
1343
+ {
1344
+ path: "transforms.mixedBooleanArithmetic.enabled",
1345
+ shape: "scalar",
1346
+ scope: "program",
1347
+ tier: "free",
1348
+ surface: "engine",
1349
+ item: { kind: "boolean" },
1350
+ default: "true"
1351
+ },
1352
+ {
1353
+ path: "transforms.integerBytecode.enabled",
1354
+ shape: "scalar",
1355
+ scope: "program",
1356
+ tier: "free",
1357
+ surface: "engine",
1358
+ item: { kind: "boolean" },
1359
+ default: "true"
1360
+ },
1361
+ {
1362
+ path: "transforms.crossDependency.enabled",
1363
+ shape: "scalar",
1364
+ scope: "program",
1365
+ tier: "free",
1366
+ surface: "engine",
1367
+ item: { kind: "boolean" },
1368
+ default: "true"
1369
+ },
1370
+ {
1371
+ path: "transforms.scopeDeepen.enabled",
1372
+ shape: "scalar",
1373
+ scope: "program",
1374
+ tier: "free",
1375
+ surface: "engine",
1376
+ item: { kind: "boolean" },
1377
+ default: "true"
1378
+ },
1379
+ {
1380
+ path: "transforms.objectConstruction.enabled",
1381
+ shape: "scalar",
1382
+ scope: "program",
1383
+ tier: "free",
1384
+ surface: "engine",
1385
+ item: { kind: "boolean" },
1386
+ default: "true"
1387
+ },
1388
+ {
1389
+ path: "transforms.comparisonHardening.enabled",
1390
+ shape: "scalar",
1391
+ scope: "program",
1392
+ tier: "pro",
1393
+ surface: "engine",
1394
+ item: { kind: "boolean" },
1395
+ default: "false"
1396
+ },
1397
+ {
1398
+ path: "transforms.selfIntegrity.enabled",
1399
+ shape: "scalar",
1400
+ scope: "program",
1401
+ tier: "pro",
1402
+ surface: "engine",
1403
+ item: { kind: "boolean" },
1404
+ default: "false"
1405
+ },
1406
+ {
1407
+ path: "build.backup",
1408
+ shape: "scalar",
1409
+ scope: "program",
1410
+ tier: "free",
1411
+ surface: "build",
1412
+ item: { kind: "boolean" },
1413
+ default: "false for an in-place pass; true standalone"
1414
+ },
1415
+ {
1416
+ path: "build.autorun",
1417
+ shape: "scalar",
1418
+ scope: "program",
1419
+ tier: "free",
1420
+ surface: "build",
1421
+ item: { kind: "boolean" },
1422
+ default: "true"
1423
+ },
1424
+ {
1425
+ path: "build.mode",
1426
+ shape: "scalar",
1427
+ scope: "program",
1428
+ tier: "free",
1429
+ surface: "build",
1430
+ item: {
1431
+ kind: "enum",
1432
+ values: BUILD_MODE_VALUES
1433
+ },
1434
+ default: "detected from the environment"
1435
+ },
1436
+ {
1437
+ path: "directives.enabled",
1438
+ shape: "scalar",
1439
+ scope: "program",
1440
+ tier: "free",
1441
+ surface: "build",
1442
+ item: { kind: "boolean" },
1443
+ default: "true"
1444
+ },
1445
+ {
1446
+ path: "diagnostics.level",
1447
+ shape: "scalar",
1448
+ scope: "program",
1449
+ tier: "free",
1450
+ surface: "build",
1451
+ item: {
1452
+ kind: "enum",
1453
+ values: [
1454
+ "summary",
1455
+ "all",
1456
+ "none"
1457
+ ]
1458
+ },
1459
+ default: "summary"
1460
+ },
1461
+ {
1462
+ path: "diagnostics.format",
1463
+ shape: "scalar",
1464
+ scope: "program",
1465
+ tier: "free",
1466
+ surface: "cli",
1467
+ item: {
1468
+ kind: "enum",
1469
+ values: ["text", "json"]
1470
+ },
1471
+ default: "text"
1472
+ },
1473
+ {
1474
+ path: "telemetry.enabled",
1475
+ shape: "scalar",
1476
+ scope: "program",
1477
+ tier: "free",
1478
+ surface: "build",
1479
+ item: { kind: "boolean" },
1480
+ default: "true"
1481
+ },
1482
+ {
1483
+ path: "allowUnobfuscated",
1484
+ shape: "scalar",
1485
+ scope: "program",
1486
+ tier: "free",
1487
+ surface: "build",
1488
+ item: { kind: "boolean" },
1489
+ default: "false"
1490
+ },
1491
+ {
1492
+ path: "key",
1493
+ shape: "scalar",
1494
+ scope: "program",
1495
+ tier: "pro",
1496
+ surface: "build",
1497
+ item: { kind: "string" },
1498
+ default: "unset; builds run locally with basic protection"
1499
+ }
1500
+ ];
1501
+ const EMPTY_CONFIG = {};
1502
+ const CONFIG_BY_PATH = new Map(CONFIG_KEYS.map((k) => [k.path, k]));
1503
+ const CONFIG_PREFIXES = new Set(CONFIG_KEYS.flatMap((k) => {
1504
+ const parts = k.path.split(".");
1505
+ return parts.slice(0, -1).map((_, i) => parts.slice(0, i + 1).join("."));
1506
+ }));
1507
+ const CONFIG_CHILDREN = new Map([...CONFIG_PREFIXES].map((prefix) => [prefix, CONFIG_KEYS.filter((k) => k.path.startsWith(`${prefix}.`)).map((k) => k.path)]));
1508
+ const BY_NORMALIZED = new Map(CONFIG_KEYS.map((k) => [normalizeKey(k.path), k]));
1509
+ const CHILDREN_BY_NORMALIZED = new Map([...CONFIG_CHILDREN].map(([prefix, children]) => [normalizeKey(prefix), children]));
1510
+ const PREFIX_BY_NORMALIZED = new Map([...CONFIG_PREFIXES].map((prefix) => [normalizeKey(prefix), prefix]));
1511
+ function normalizeKey(key) {
1512
+ return key.replace(/[-_.]/g, "").toLowerCase();
1513
+ }
1514
+ function groupBooleanKey(path) {
1515
+ if (!CONFIG_PREFIXES.has(path)) return void 0;
1516
+ return CONFIG_BY_PATH.get(`${path}.enabled`);
1517
+ }
1518
+ function nearestName(name, candidates) {
1519
+ const target = normalizeKey(name);
1520
+ let best;
1521
+ for (const candidate of candidates) {
1522
+ const distance = editDistance(target, normalizeKey(candidate));
1523
+ if (distance > Math.max(2, Math.floor(target.length / 4))) continue;
1524
+ if (!best || distance < best.distance) best = {
1525
+ name: candidate,
1526
+ distance
1527
+ };
1528
+ }
1529
+ return best?.name;
1530
+ }
1531
+ function suggestKey(key) {
1532
+ const exact = BY_NORMALIZED.get(normalizeKey(key));
1533
+ if (exact) return exact.path;
1534
+ const near = nearestName(key, CONFIG_KEYS.map((k) => k.path));
1535
+ if (near) return near;
1536
+ const tail = normalizeKey(key);
1537
+ const owners = CONFIG_KEYS.filter((k) => normalizeKey(k.path.slice(k.path.lastIndexOf(".") + 1)) === tail);
1538
+ return owners.length === 1 ? owners[0].path : void 0;
1539
+ }
1540
+ function canonicalSpelling(name) {
1541
+ const norm$1 = normalizeKey(name);
1542
+ const key = BY_NORMALIZED.get(norm$1);
1543
+ if (key) return { key: key.path };
1544
+ const group$1 = CHILDREN_BY_NORMALIZED.get(norm$1);
1545
+ return group$1 && group$1.length > 0 ? { group: group$1 } : void 0;
1546
+ }
1547
+ function editDistance(a, b) {
1548
+ const prev = new Array(b.length + 1);
1549
+ const next = new Array(b.length + 1);
1550
+ for (let j = 0; j <= b.length; j++) prev[j] = j;
1551
+ for (let i = 1; i <= a.length; i++) {
1552
+ next[0] = i;
1553
+ for (let j = 1; j <= b.length; j++) next[j] = Math.min(prev[j] + 1, next[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
1554
+ for (let j = 0; j <= b.length; j++) prev[j] = next[j];
1555
+ }
1556
+ return prev[b.length];
1557
+ }
1558
+ const DOCS_URL = "https://www.afterpack.dev/docs/config";
1559
+ function unknownKeyMessage(path, surface) {
1560
+ const group$1 = CHILDREN_BY_NORMALIZED.get(normalizeKey(path));
1561
+ if (group$1 && group$1.length > 0) {
1562
+ const list = group$1.map((child) => `\`${child}\``).join(", ");
1563
+ const tail$1 = group$1.length === 1 ? `did you mean ${list}?` : `its keys are ${list}`;
1564
+ const canonical = PREFIX_BY_NORMALIZED.get(normalizeKey(path));
1565
+ const enabled = canonical ? groupBooleanKey(canonical) : void 0;
1566
+ const rule = enabled ? `; a boolean here means \`${enabled.path}\`` : "";
1567
+ return `\`${path}\` is a group of configuration keys, not a key itself (${surface}) — ${tail$1}${rule}`;
1568
+ }
1569
+ const suggestion = suggestKey(path);
1570
+ const tail = suggestion ? ` — did you mean \`${suggestion}\`?` : ` — see ${DOCS_URL}`;
1571
+ return `unknown configuration key \`${path}\` (${surface})${tail}`;
1572
+ }
1573
+ function isPlainObject(value) {
1574
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1575
+ }
1576
+ function describe(item) {
1577
+ switch (item.kind) {
1578
+ case "boolean": return "true or false";
1579
+ case "number": return item.integer ? `an integer >= ${item.min}` : `a number >= ${item.min}`;
1580
+ case "unbounded": return `a number >= ${item.min}, or the string "${item.unlimited}"`;
1581
+ case "string": return "a string";
1582
+ case "enum": return `one of: ${item.values.join(", ")}`;
1583
+ case "seed": return "a number, any string, or \"git\"";
1584
+ case "reserved": return "a name, or { \"glob\": \"…\", \"names\": [\"…\"] }";
1585
+ case "region": return "an object with numeric `start` and `end`";
1586
+ }
1587
+ }
1588
+ function misdirectedHint(key, value, spell) {
1589
+ const other = misdirectedTo(key, value);
1590
+ if (!other) return "";
1591
+ const written = spell(other.path, String(value));
1592
+ return ` — \`${String(value)}\` is a \`${other.path}\` value; write \`${written}\` instead`;
1593
+ }
1594
+ const isFiniteNumber = (v) => typeof v === "number" && Number.isFinite(v);
1595
+ const isTransformKinds = (v) => Array.isArray(v) && v.every((k) => TRANSFORM_KIND_VALUES.includes(k));
1596
+ const KINDS = `a list of: ${TRANSFORM_KIND_VALUES.join(", ")}`;
1597
+ const isNonNegative = (v) => isFiniteNumber(v) && v >= 0;
1598
+ function group(fields) {
1599
+ return {
1600
+ is: isPlainObject,
1601
+ want: "an object",
1602
+ fields
1603
+ };
1604
+ }
1605
+ const REGION_FIELDS = {
1606
+ start: {
1607
+ required: true,
1608
+ is: isFiniteNumber,
1609
+ want: "a number"
1610
+ },
1611
+ end: {
1612
+ required: true,
1613
+ is: isFiniteNumber,
1614
+ want: "a number"
1615
+ },
1616
+ complexity: {
1617
+ is: isNonNegative,
1618
+ want: "a number >= 0"
1619
+ },
1620
+ inflation: group({ max: {
1621
+ is: isNonNegative,
1622
+ want: "a number >= 0"
1623
+ } }),
1624
+ strings: group({ encode: {
1625
+ is: (v) => typeof v === "boolean",
1626
+ want: "true or false"
1627
+ } }),
1628
+ transforms: group({
1629
+ only: {
1630
+ is: isTransformKinds,
1631
+ want: KINDS
1632
+ },
1633
+ deny: {
1634
+ is: isTransformKinds,
1635
+ want: KINDS
1636
+ }
1637
+ }),
1638
+ label: {
1639
+ is: (v) => typeof v === "string",
1640
+ want: "a string"
1641
+ }
1642
+ };
1643
+ const RESERVED_FIELDS = {
1644
+ glob: {
1645
+ required: true,
1646
+ is: (v) => typeof v === "string",
1647
+ want: "a string"
1648
+ },
1649
+ names: {
1650
+ required: true,
1651
+ is: (v) => Array.isArray(v) && v.every((n) => typeof n === "string"),
1652
+ want: "a list of names"
1653
+ }
1654
+ };
1655
+ function leafNames(spec, prefix) {
1656
+ return Object.entries(spec).flatMap(([name, field]) => field.fields ? leafNames(field.fields, `${prefix}${name}.`) : [prefix + name]);
1657
+ }
1658
+ function checkFields(spec, value, prefix = "") {
1659
+ for (const name of Object.keys(value)) {
1660
+ if (name in spec) continue;
1661
+ const near = nearestName(prefix + name, Object.keys(spec).map((n) => prefix + n));
1662
+ return `item has an unknown field \`${prefix}${name}\`` + (near ? ` — did you mean \`${near}\`?` : "") + ` (allowed: ${leafNames(spec, prefix).join(", ")})`;
1663
+ }
1664
+ for (const [name, field] of Object.entries(spec)) {
1665
+ const present = value[name];
1666
+ if (present === void 0) {
1667
+ if (field.required) return `item is missing \`${prefix}${name}\` (${field.want})`;
1668
+ continue;
1669
+ }
1670
+ if (!field.is(present)) return `item's \`${prefix}${name}\` must be ${field.want}, got ${JSON.stringify(present)}`;
1671
+ if (field.fields) {
1672
+ const nested = checkFields(field.fields, present, `${prefix}${name}.`);
1673
+ if (nested) return nested;
1674
+ }
1675
+ }
1676
+ return void 0;
1677
+ }
1678
+ function expected(item, value) {
1679
+ return `expected ${describe(item)}, got ${JSON.stringify(value)}`;
1680
+ }
1681
+ function checkItem(item, value) {
1682
+ switch (item.kind) {
1683
+ case "boolean": return typeof value === "boolean" ? void 0 : expected(item, value);
1684
+ case "number": {
1685
+ if (typeof value !== "number" || !Number.isFinite(value)) return expected(item, value);
1686
+ if (value < item.min) return expected(item, value);
1687
+ if (item.integer && !Number.isInteger(value)) return expected(item, value);
1688
+ return void 0;
1689
+ }
1690
+ case "unbounded": {
1691
+ if (value === item.unlimited) return void 0;
1692
+ if (typeof value === "number" && Number.isFinite(value) && value >= item.min) return void 0;
1693
+ return `${expected(item, value)} — there is no \`Infinity\` in JSON; write "${item.unlimited}"`;
1694
+ }
1695
+ case "string": return typeof value === "string" ? void 0 : expected(item, value);
1696
+ case "enum": return typeof value === "string" && item.values.includes(value) ? void 0 : expected(item, value);
1697
+ case "seed": return typeof value === "number" || typeof value === "string" ? void 0 : expected(item, value);
1698
+ case "reserved": {
1699
+ if (typeof value === "string") return void 0;
1700
+ if (!isPlainObject(value)) return expected(item, value);
1701
+ return checkFields(RESERVED_FIELDS, value);
1702
+ }
1703
+ case "region": {
1704
+ if (!isPlainObject(value)) return expected(item, value);
1705
+ return checkFields(REGION_FIELDS, value);
1706
+ }
1707
+ }
1708
+ }
1709
+ function checkValue(key, value) {
1710
+ if (key.shape === "scalar") {
1711
+ const failure = checkItem(key.item, value);
1712
+ return failure ? `\`${key.path}\`: ${failure}` : void 0;
1713
+ }
1714
+ if (!Array.isArray(value)) return `\`${key.path}\`: expected a list of values, got ${JSON.stringify(value)}`;
1715
+ for (const entry of value) {
1716
+ const failure = checkItem(key.item, entry);
1717
+ if (failure) return `\`${key.path}\`: ${failure}`;
1718
+ }
1719
+ return void 0;
1720
+ }
1721
+ function misdirectedTo(key, value) {
1722
+ if (key.namedValuesOf === void 0 || typeof value !== "string") return void 0;
1723
+ const other = CONFIG_BY_PATH.get(key.namedValuesOf);
1724
+ if (!other || other.shape !== "scalar") return void 0;
1725
+ return checkItem(other.item, value) === void 0 ? other : void 0;
1726
+ }
1727
+ function validateConfig(input, surface) {
1728
+ const issues = [];
1729
+ const config = {};
1730
+ if (input === void 0 || input === null) return {
1731
+ config,
1732
+ issues
1733
+ };
1734
+ if (!isPlainObject(input)) {
1735
+ issues.push({
1736
+ path: "",
1737
+ message: `configuration (${surface}) must be an object`
1738
+ });
1739
+ return {
1740
+ config,
1741
+ issues
1742
+ };
1743
+ }
1744
+ walk(input, "", config, issues, surface);
1745
+ return {
1746
+ config,
1747
+ issues
1748
+ };
1749
+ }
1750
+ function walk(source, prefix, target, issues, surface) {
1751
+ for (const [name, value] of Object.entries(source)) {
1752
+ if (value === void 0) continue;
1753
+ const path = prefix ? `${prefix}.${name}` : name;
1754
+ const key = CONFIG_BY_PATH.get(path);
1755
+ if (key) {
1756
+ const failure = checkValue(key, value);
1757
+ if (failure) {
1758
+ const hint = misdirectedHint(key, value, (p, v) => `"${p}": ${JSON.stringify(v)}`);
1759
+ issues.push({
1760
+ path,
1761
+ message: `${failure} (${surface})${hint}`
1762
+ });
1763
+ } else target[name] = value;
1764
+ continue;
1765
+ }
1766
+ if (CONFIG_PREFIXES.has(path)) {
1767
+ if (isPlainObject(value)) {
1768
+ const nested = {};
1769
+ walk(value, path, nested, issues, surface);
1770
+ if (Object.keys(nested).length > 0) target[name] = nested;
1771
+ continue;
1772
+ }
1773
+ const enabled = groupBooleanKey(path);
1774
+ if (enabled && typeof value === "boolean") {
1775
+ target[name] = { enabled: value };
1776
+ continue;
1777
+ }
1778
+ }
1779
+ issues.push({
1780
+ path,
1781
+ message: unknownKeyMessage(path, surface)
1782
+ });
1783
+ }
1784
+ }
1785
+ function deepMerge(base, override) {
1786
+ const out = { ...base };
1787
+ for (const [name, value] of Object.entries(override)) {
1788
+ if (value === void 0) continue;
1789
+ const existing = out[name];
1790
+ out[name] = isPlainObject(value) && isPlainObject(existing) ? deepMerge(existing, value) : value;
1791
+ }
1792
+ return out;
1793
+ }
1794
+ function mergeInto(base, override) {
1795
+ return deepMerge(base, override);
1796
+ }
1797
+ function mergeConfig(base, override) {
1798
+ return deepMerge(base, override);
1799
+ }
1800
+ function getPath(config, path) {
1801
+ let current = config;
1802
+ for (const part of path.split(".")) {
1803
+ if (!isPlainObject(current)) return void 0;
1804
+ current = current[part];
1805
+ }
1806
+ return current;
1807
+ }
1808
+ function nest(path, value) {
1809
+ return path.split(".").reduceRight((inner, segment) => ({ [segment]: inner }), value);
1810
+ }
1811
+ function setPath(target, path, value) {
1812
+ const parts = path.split(".");
1813
+ let node = target;
1814
+ for (const part of parts.slice(0, -1)) {
1815
+ if (!isPlainObject(node[part])) node[part] = {};
1816
+ node = node[part];
1817
+ }
1818
+ node[parts[parts.length - 1]] = value;
1819
+ }
1820
+ function toEngineConfig(config) {
1821
+ const out = {};
1822
+ for (const key of CONFIG_KEYS) {
1823
+ if (key.surface !== "engine") continue;
1824
+ const value = getPath(config, key.path);
1825
+ if (value === void 0) continue;
1826
+ setPath(out, key.path, value);
1827
+ }
1828
+ return out;
1829
+ }
1830
+ function toPluginOptions(config) {
1831
+ const read = (path) => getPath(config, path);
1832
+ const set = (container) => Object.values(container).some((v) => v !== void 0) ? container : void 0;
1833
+ return {
1834
+ artifactOptions: {
1835
+ protectionMap: set({ enabled: read("protectionMap.enabled") }),
1836
+ sourceMap: set({
1837
+ enabled: read("sourceMap.enabled"),
1838
+ emitUrl: read("sourceMap.emitUrl")
1839
+ }),
1840
+ build: set({
1841
+ backup: read("build.backup"),
1842
+ mode: read("build.mode")
1843
+ }),
1844
+ allowUnobfuscated: read("allowUnobfuscated"),
1845
+ telemetry: set({ enabled: read("telemetry.enabled") })
1846
+ },
1847
+ seed: read("seed"),
1848
+ preset: read("preset"),
1849
+ complexity: read("complexity"),
1850
+ regions: read("regions"),
1851
+ directives: {
1852
+ enabled: read("directives.enabled") ?? DIRECTIVES_ENABLED_DEFAULT,
1853
+ explicit: read("directives.enabled") !== void 0
1854
+ },
1855
+ build: set({ autorun: read("build.autorun") }),
1856
+ diagnostics: set({
1857
+ level: read("diagnostics.level"),
1858
+ format: read("diagnostics.format")
1859
+ }),
1860
+ paths: set({ include: read("paths.include") }),
1861
+ key: read("key")
1862
+ };
1863
+ }
1864
+
1865
+ //#endregion
1866
+ //#region src/compat.ts
1867
+ const MIN_CORE_VERSION = "0.1.0";
1868
+ const CORE_PACKAGE = "@afterpack/core";
1869
+ const VERSION_PATTERN$1 = /^\d{1,9}\.\d{1,9}\.\d{1,9}(?:[-+][0-9A-Za-z.+-]{1,64})?$/;
1870
+ const PACKAGE_NAME_PATTERN = /^(?:@[a-z0-9][a-z0-9._-]{0,63}\/)?[a-z0-9][a-z0-9._-]{0,63}$/;
1871
+ function safeVersionString(value) {
1872
+ return typeof value === "string" && VERSION_PATTERN$1.test(value) ? value : null;
1873
+ }
1874
+ function readPackageJson(path) {
1875
+ try {
1876
+ return JSON.parse((0, node_fs.readFileSync)(path, "utf8"));
1877
+ } catch {
1878
+ return null;
1879
+ }
1880
+ }
1881
+ function ownPackage(moduleUrl) {
1882
+ try {
1883
+ const path = findUpward((0, node_path.dirname)((0, node_url.fileURLToPath)(moduleUrl)), "package.json");
1884
+ const pkg = path ? readPackageJson(path) : null;
1885
+ if (!pkg || typeof pkg.name !== "string" || !PACKAGE_NAME_PATTERN.test(pkg.name)) return null;
1886
+ const version = safeVersionString(pkg.version);
1887
+ return version ? {
1888
+ name: pkg.name,
1889
+ version
1890
+ } : null;
1891
+ } catch {
1892
+ return null;
1893
+ }
1894
+ }
1895
+ function installedCoreVersion(moduleUrl) {
1896
+ try {
1897
+ const path = (0, node_module.createRequire)(moduleUrl).resolve(`${CORE_PACKAGE}/package.json`);
1898
+ const pkg = readPackageJson(path);
1899
+ return pkg?.name === CORE_PACKAGE ? safeVersionString(pkg.version) : null;
1900
+ } catch {
1901
+ return null;
1902
+ }
1903
+ }
1904
+ const identities = new Map();
1905
+ function resolveClientIdentity(moduleUrl) {
1906
+ const key = String(moduleUrl);
1907
+ const cached = identities.get(key);
1908
+ if (cached) return cached;
1909
+ const own = ownPackage(moduleUrl);
1910
+ const identity = {
1911
+ packageName: own?.name ?? null,
1912
+ packageVersion: own?.version ?? null,
1913
+ coreVersion: installedCoreVersion(moduleUrl)
1914
+ };
1915
+ identities.set(key, identity);
1916
+ return identity;
1917
+ }
1918
+ function clientString(identity) {
1919
+ if (!identity?.packageName || !identity.packageVersion) return null;
1920
+ return `${identity.packageName}/${identity.packageVersion}`;
1921
+ }
1922
+ function releaseTriple(version) {
1923
+ if (typeof version !== "string") return null;
1924
+ const match = /^(\d{1,9})\.(\d{1,9})\.(\d{1,9})(?:[-+].*)?$/.exec(version.trim());
1925
+ if (!match) return null;
1926
+ return [
1927
+ Number(match[1]),
1928
+ Number(match[2]),
1929
+ Number(match[3])
1930
+ ];
1931
+ }
1932
+ function isBelowVersion(version, minimum) {
1933
+ const have = releaseTriple(version);
1934
+ const need = releaseTriple(minimum);
1935
+ if (!have || !need) return false;
1936
+ for (let i = 0; i < 3; i++) if (have[i] !== need[i]) return have[i] < need[i];
1937
+ return false;
1938
+ }
1939
+ const CLI_PACKAGE = "afterpack";
1940
+ function updateCommand(identity, minVersion) {
1941
+ const core = `${CORE_PACKAGE}@${safeVersionString(minVersion) ?? "latest"}`;
1942
+ const name = identity?.packageName;
1943
+ return name && name !== CORE_PACKAGE ? `npm install ${name}@latest ${core}` : `npm install ${core}`;
1944
+ }
1945
+ function npxAlternative(identity) {
1946
+ return identity?.packageName === CLI_PACKAGE ? `npx ${CLI_PACKAGE}@latest` : null;
1947
+ }
1948
+ const CLOUD_REFUSAL_SUMMARY = "This version of AfterPack is no longer supported by the AfterPack cloud.";
1949
+ const CORE_FLOOR_SUMMARY = "@afterpack/core is too old to protect this build — update @afterpack/core.";
1950
+ function requiredText(minVersion) {
1951
+ return minVersion ? `${minVersion} or newer` : "a newer release";
1952
+ }
1953
+ function installedRequiredLine(installed, minVersion) {
1954
+ const required = requiredText(minVersion);
1955
+ return installed ? `Installed ${CORE_PACKAGE} ${installed} · required ${required}` : `Required ${CORE_PACKAGE} ${required}`;
1956
+ }
1957
+ const TOKEN_STOPWORDS = new Set([
1958
+ "this",
1959
+ "is",
1960
+ "are",
1961
+ "a",
1962
+ "an",
1963
+ "the",
1964
+ "by",
1965
+ "to",
1966
+ "of",
1967
+ "or",
1968
+ "no",
1969
+ "longer",
1970
+ "required",
1971
+ "version",
1972
+ "newer",
1973
+ "for",
1974
+ "that"
1975
+ ]);
1976
+ function meaningfulTokens(text) {
1977
+ const tokens = text.toLowerCase().split(/[^a-z0-9.]+/);
1978
+ return new Set(tokens.filter((token) => token.length > 0 && !TOKEN_STOPWORDS.has(token)));
1979
+ }
1980
+ function serverAddsInfo(serverMessage, shownText) {
1981
+ const serverTokens = meaningfulTokens(serverMessage);
1982
+ if (serverTokens.size === 0) return false;
1983
+ const shownTokens = meaningfulTokens(shownText);
1984
+ let novel = 0;
1985
+ for (const token of serverTokens) if (!shownTokens.has(token)) novel++;
1986
+ return novel / serverTokens.size > .25;
1987
+ }
1988
+ function refusalLines(input) {
1989
+ const installedLine = installedRequiredLine(input.installed, input.minVersion);
1990
+ const lines = [
1991
+ input.summary,
1992
+ installedLine,
1993
+ input.fix
1994
+ ];
1995
+ if (input.npxAlt) lines.push(`or, without a local install: ${input.npxAlt}`);
1996
+ if (serverAddsInfo(input.serverMessage, `${input.summary} ${installedLine}`)) lines.push(`Server: ${input.serverMessage}`);
1997
+ return lines;
1998
+ }
1999
+ var CoreVersionError = class extends Error {
2000
+ code = "CORE_VERSION_UNSUPPORTED";
2001
+ installed;
2002
+ minimum;
2003
+ fix;
2004
+ constructor(message, installed, minimum, fix) {
2005
+ super(message);
2006
+ this.name = "CoreVersionError";
2007
+ this.installed = installed;
2008
+ this.minimum = minimum;
2009
+ this.fix = fix;
2010
+ }
2011
+ };
2012
+ function assertSupportedCore(identity, prefix = (m) => m) {
2013
+ const installed = identity?.coreVersion ?? null;
2014
+ if (installed === null || !isBelowVersion(installed, MIN_CORE_VERSION)) return;
2015
+ const fix = updateCommand(identity);
2016
+ const lines = refusalLines({
2017
+ summary: CORE_FLOOR_SUMMARY,
2018
+ installed,
2019
+ minVersion: MIN_CORE_VERSION,
2020
+ fix,
2021
+ npxAlt: npxAlternative(identity),
2022
+ serverMessage: ""
2023
+ });
2024
+ throw new CoreVersionError(prefix(lines.join("\n")), installed, MIN_CORE_VERSION, fix);
2025
+ }
2026
+ const CLOUD_UPGRADE_REQUIRED = "AFTERPACK_CLOUD_UPGRADE_REQUIRED";
2027
+ const CLOUD_SUNSET = "AFTERPACK_CLOUD_SUNSET";
2028
+ const CLOUD_API = "AFTERPACK_CLOUD_API";
2029
+ const KIND_BY_CODE = {
2030
+ [CLOUD_UPGRADE_REQUIRED]: "upgradeRequired",
2031
+ [CLOUD_SUNSET]: "sunset",
2032
+ [CLOUD_API]: "api"
2033
+ };
2034
+ const API_CODE_LIMIT = 64;
2035
+ var CloudApiError = class extends Error {
2036
+ code;
2037
+ kind;
2038
+ apiCode;
2039
+ apiMessage;
2040
+ details;
2041
+ notices;
2042
+ minVersion;
2043
+ installed;
2044
+ fix;
2045
+ constructor(input) {
2046
+ super(input.message, { cause: input.cause });
2047
+ this.name = "CloudApiError";
2048
+ this.code = input.code;
2049
+ this.kind = input.kind;
2050
+ this.apiCode = input.apiCode;
2051
+ this.apiMessage = input.apiMessage;
2052
+ this.details = input.details;
2053
+ this.notices = input.notices;
2054
+ this.minVersion = input.minVersion;
2055
+ this.installed = input.installed;
2056
+ this.fix = input.fix;
2057
+ }
2058
+ };
2059
+ function refusalApiCode(diagnostics) {
2060
+ if (!Array.isArray(diagnostics)) return null;
2061
+ for (const d of diagnostics) {
2062
+ if (!isPlainObject(d)) continue;
2063
+ const code = sanitizeServerText(d.code, API_CODE_LIMIT);
2064
+ if (code !== "") return code;
2065
+ }
2066
+ return null;
2067
+ }
2068
+ function readCloudErrorBody(error) {
2069
+ return {
2070
+ code: refusalApiCode(error.diagnostics),
2071
+ message: sanitizeServerText(error.message),
2072
+ details: isPlainObject(error.details) ? error.details : null,
2073
+ notices: Array.isArray(error.notices) ? error.notices : null
2074
+ };
2075
+ }
2076
+ function describeCloudFailure(kind, body, minVersion, identity, fix) {
2077
+ if (kind === "api") {
2078
+ if (!body.code && body.message.startsWith("cloud obfuscation failed")) return body.message;
2079
+ const code = body.code ? `${body.code}: ` : "";
2080
+ return `cloud obfuscation failed: ${code}${body.message || "the API refused the request"}`;
2081
+ }
2082
+ return refusalLines({
2083
+ summary: CLOUD_REFUSAL_SUMMARY,
2084
+ installed: identity?.coreVersion ?? null,
2085
+ minVersion,
2086
+ fix,
2087
+ npxAlt: npxAlternative(identity),
2088
+ serverMessage: body.message
2089
+ }).join("\n");
2090
+ }
2091
+ function toCloudApiError(error, options = {}) {
2092
+ if (!isPlainObject(error) && !(error instanceof Error)) return null;
2093
+ const code = error.code;
2094
+ if (typeof code !== "string") return null;
2095
+ const kind = KIND_BY_CODE[code];
2096
+ if (!kind) return null;
2097
+ const body = readCloudErrorBody(error);
2098
+ const minVersion = safeVersionString(body.details?.minVersion);
2099
+ const prefix = options.prefix ?? ((m) => m);
2100
+ const fix = updateCommand(options.identity, minVersion);
2101
+ return new CloudApiError({
2102
+ message: prefix(describeCloudFailure(kind, body, minVersion, options.identity, fix)),
2103
+ code,
2104
+ kind,
2105
+ apiCode: body.code,
2106
+ apiMessage: body.message,
2107
+ details: body.details,
2108
+ notices: sanitizeNotices(body.notices),
2109
+ minVersion,
2110
+ installed: options.identity?.coreVersion ?? null,
2111
+ fix,
2112
+ cause: error
2113
+ });
2114
+ }
2115
+
2116
+ //#endregion
2117
+ //#region src/config-file.ts
2118
+ const CONFIG_FILE_NAME = "afterpack.json";
2119
+ function findConfigFile(startDir) {
2120
+ return findUpward(startDir, CONFIG_FILE_NAME);
2121
+ }
2122
+ function loadConfigFile(startDir) {
2123
+ const path = findConfigFile(startDir);
2124
+ if (!path) return {
2125
+ path: null,
2126
+ config: EMPTY_CONFIG,
2127
+ issues: []
2128
+ };
2129
+ let raw;
2130
+ try {
2131
+ raw = JSON.parse((0, node_fs.readFileSync)(path, "utf8"));
2132
+ } catch (error) {
2133
+ const detail = error instanceof Error ? error.message : String(error);
2134
+ return {
2135
+ path,
2136
+ config: EMPTY_CONFIG,
2137
+ issues: [{
2138
+ path: CONFIG_FILE_NAME,
2139
+ message: `${path} is not valid JSON: ${detail}`
2140
+ }]
2141
+ };
2142
+ }
2143
+ const { config, issues } = validateConfig(raw, path);
2144
+ return {
2145
+ path,
2146
+ config,
2147
+ issues
2148
+ };
2149
+ }
2150
+
2151
+ //#endregion
2152
+ //#region src/config-parse.ts
2153
+ const ENV_PREFIX = "AFTERPACK_";
2154
+ function splitAssignment(token) {
2155
+ const eq = token.indexOf("=");
2156
+ if (eq < 0) return {
2157
+ key: token,
2158
+ value: true
2159
+ };
2160
+ return {
2161
+ key: token.slice(0, eq),
2162
+ value: token.slice(eq + 1)
2163
+ };
2164
+ }
2165
+ function parseScalarLiteral(raw) {
2166
+ try {
2167
+ return JSON.parse(raw);
2168
+ } catch {
2169
+ return raw;
2170
+ }
2171
+ }
2172
+ function parseListLiteral(raw) {
2173
+ const whole = parseScalarLiteral(raw);
2174
+ if (Array.isArray(whole)) return { json: whole };
2175
+ if (raw.trim() === "") return { items: [] };
2176
+ const parts = raw.split(",").map((part) => part.trim());
2177
+ if (parts.some((part) => part === "")) return { empty: true };
2178
+ return { items: parts.map(parseScalarLiteral) };
2179
+ }
2180
+ function spellKey(path, surface) {
2181
+ if (surface === "cli") return `--${path}`;
2182
+ if (surface === "env") return `${ENV_PREFIX}${path.replace(/\./g, "_")}`;
2183
+ return path;
2184
+ }
2185
+ function surfaceLabel(surface) {
2186
+ if (surface === "cli") return "command line";
2187
+ if (surface === "env") return "environment";
2188
+ return "directive";
2189
+ }
2190
+ function fileFormCta(key) {
2191
+ return key.configFileForm ?? `{ "${key.path.split(".").join("\": { \"")}": … }`;
2192
+ }
2193
+ function structuredIssue(key, surface) {
2194
+ return {
2195
+ path: key.path,
2196
+ message: `\`${key.path}\` is an object and cannot be written on the ${surfaceLabel(surface)}. Move it to afterpack.json: ${fileFormCta(key)}`
2197
+ };
2198
+ }
2199
+ function objectItemIssue(key, surface) {
2200
+ return {
2201
+ path: key.path,
2202
+ message: `\`${key.path}\` takes plain comma-separated values on the ${surfaceLabel(surface)}; an object item must move to afterpack.json: ${fileFormCta(key)}`
2203
+ };
2204
+ }
2205
+ function jsonArrayIssue(key, items, surface) {
2206
+ const flat = items.every((v) => v !== null && typeof v !== "object");
2207
+ const spelled = spellKey(key.path, surface);
2208
+ const how = flat ? `write \`${spelled}=${items.map(String).join(",")}\`${items.length === 0 ? " for an empty list" : ""}` : key.shape === "mixedList" ? `an object item must move to afterpack.json: ${fileFormCta(key)}` : `write \`${spelled}=<value>,<value>\``;
2209
+ return {
2210
+ path: key.path,
2211
+ message: `\`${key.path}\` takes comma-separated values on the ${surfaceLabel(surface)}, not a JSON array — ${how}`
2212
+ };
2213
+ }
2214
+ function spaceFormIssue(path, raw, surface) {
2215
+ const spelled = spellKey(path, surface);
2216
+ return {
2217
+ path,
2218
+ message: `\`${spelled} ${raw}\` is not a flag — the space-separated form was removed; write \`${spelled}=${raw}\``
2219
+ };
2220
+ }
2221
+ function kebabIssue(key, surface) {
2222
+ const suggestion = suggestKey(key);
2223
+ const canonical = suggestion ? ` — the canonical form is \`${spellKey(suggestion, surface)}\`` : " — keys are dot-delimited camelCase";
2224
+ return {
2225
+ path: key,
2226
+ message: `kebab-case is not a configuration key (\`${spellKey(key, surface)}\`)${canonical}`
2227
+ };
2228
+ }
2229
+ function parseAssignment(key, raw, surface) {
2230
+ const spaced = raw === true ? /^(\S+)[ \t]+(.+)$/.exec(key) : null;
2231
+ const head = spaced ? CONFIG_BY_PATH.get(spaced[1]) : void 0;
2232
+ if (spaced && head) return { issue: head.shape === "structured" ? structuredIssue(head, surface) : spaceFormIssue(head.path, spaced[2], surface) };
2233
+ if (key.includes("-")) return { issue: kebabIssue(key, surface) };
2234
+ const grouped = CONFIG_BY_PATH.has(key) ? void 0 : groupBooleanKey(key);
2235
+ const boolish = raw === true || typeof parseScalarLiteral(raw) === "boolean";
2236
+ const path = grouped && boolish ? grouped.path : key;
2237
+ const def = CONFIG_BY_PATH.get(path);
2238
+ if (!def) return { issue: {
2239
+ path: key,
2240
+ message: unknownKeyMessage(key, surfaceLabel(surface))
2241
+ } };
2242
+ if (def.shape === "structured") return { issue: structuredIssue(def, surface) };
2243
+ if (raw === true) {
2244
+ const failure$1 = checkValue(def, true);
2245
+ return failure$1 ? { issue: {
2246
+ path: key,
2247
+ message: `${failure$1} (${surfaceLabel(surface)})`
2248
+ } } : { assignment: {
2249
+ path,
2250
+ value: true
2251
+ } };
2252
+ }
2253
+ if (def.shape === "mixedList" && raw.includes("{")) return { issue: objectItemIssue(def, surface) };
2254
+ let value;
2255
+ if (def.shape === "scalar") value = parseScalarLiteral(raw);
2256
+ else {
2257
+ const parsed = parseListLiteral(raw);
2258
+ if ("json" in parsed) return { issue: jsonArrayIssue(def, parsed.json, surface) };
2259
+ if ("empty" in parsed) return { issue: {
2260
+ path: key,
2261
+ message: `\`${key}\` has an empty item in its comma-separated value (${surfaceLabel(surface)}) — write the items with no stray comma, or omit the key entirely`
2262
+ } };
2263
+ value = parsed.items;
2264
+ }
2265
+ const failure = checkValue(def, value);
2266
+ if (failure) {
2267
+ const hint = misdirectedHint(def, value, (p, v) => `${spellKey(p, surface)}=${v}`);
2268
+ return { issue: {
2269
+ path: key,
2270
+ message: `${failure} (${surfaceLabel(surface)})${hint}`
2271
+ } };
2272
+ }
2273
+ return { assignment: {
2274
+ path,
2275
+ value
2276
+ } };
2277
+ }
2278
+ function collect(assignments) {
2279
+ let config = EMPTY_CONFIG;
2280
+ for (const a of assignments) config = mergeConfig(config, nest(a.path, a.value));
2281
+ return config;
2282
+ }
2283
+ function parseCliOptions(argv) {
2284
+ const assignments = [];
2285
+ const issues = [];
2286
+ const positionals = [];
2287
+ let help = false;
2288
+ let version = false;
2289
+ for (let i = 0; i < argv.length; i++) {
2290
+ const token = argv[i];
2291
+ if (!token.startsWith("-")) {
2292
+ positionals.push(token);
2293
+ continue;
2294
+ }
2295
+ if (token === "--help") {
2296
+ help = true;
2297
+ continue;
2298
+ }
2299
+ if (token === "--version") {
2300
+ version = true;
2301
+ continue;
2302
+ }
2303
+ if (!token.startsWith("--") || token === "--") {
2304
+ issues.push({
2305
+ path: token,
2306
+ message: `\`${token}\` is not a flag — every option is written \`--key=value\` (no short flags)`
2307
+ });
2308
+ continue;
2309
+ }
2310
+ const { key, value } = splitAssignment(token.slice(2));
2311
+ const def = value === true ? CONFIG_BY_PATH.get(key) : void 0;
2312
+ const next = argv[i + 1];
2313
+ if (def !== void 0 && def.shape !== "structured" && next !== void 0 && !next.startsWith("-") && checkValue(def, true) !== void 0) {
2314
+ issues.push(spaceFormIssue(key, next, "cli"));
2315
+ const retry = parseAssignment(key, next, "cli");
2316
+ if ("issue" in retry) issues.push(retry.issue);
2317
+ i++;
2318
+ continue;
2319
+ }
2320
+ const parsed = parseAssignment(key, value, "cli");
2321
+ if ("issue" in parsed) issues.push(parsed.issue);
2322
+ else assignments.push(parsed.assignment);
2323
+ }
2324
+ return {
2325
+ config: collect(assignments),
2326
+ positionals,
2327
+ help,
2328
+ version,
2329
+ issues
2330
+ };
2331
+ }
2332
+ const LIVE_SCREAMING_ENV = new Set(["SEED", "KEY"]);
2333
+ function screamingIssue(name, suffix) {
2334
+ const dotted = suffix.replace(/_/g, ".");
2335
+ const envForm = (path) => `${ENV_PREFIX}${path.replace(/\./g, "_")}`;
2336
+ const spelling = canonicalSpelling(dotted);
2337
+ let tail = `see ${DOCS_URL}`;
2338
+ if (spelling && "key" in spelling) tail = `write \`${envForm(spelling.key)}\``;
2339
+ else if (spelling && spelling.group.length === 1) tail = `write \`${envForm(spelling.group[0])}\``;
2340
+ else if (spelling) tail = `its keys are ${spelling.group.map((k) => `\`${envForm(k)}\``).join(", ")}`;
2341
+ return {
2342
+ path: suffix,
2343
+ message: `\`${name}\` is not a configuration variable — an AfterPack variable spells its key exactly, dots as underscores and case preserved: ${tail}`
2344
+ };
2345
+ }
2346
+ function isReservedEnvSuffix(suffix) {
2347
+ if (/[a-z]/.test(suffix)) return false;
2348
+ const dotted = suffix.replace(/_/g, ".");
2349
+ return LIVE_SCREAMING_ENV.has(suffix) || canonicalSpelling(dotted) === void 0;
2350
+ }
2351
+ function parseEnvOptions(env) {
2352
+ const assignments = [];
2353
+ const issues = [];
2354
+ for (const name of Object.keys(env).sort()) {
2355
+ if (!name.startsWith(ENV_PREFIX)) continue;
2356
+ const suffix = name.slice(ENV_PREFIX.length);
2357
+ if (suffix === "" || isReservedEnvSuffix(suffix)) continue;
2358
+ const raw = env[name];
2359
+ if (raw === void 0) continue;
2360
+ if (!/[a-z]/.test(suffix)) {
2361
+ issues.push(screamingIssue(name, suffix));
2362
+ continue;
2363
+ }
2364
+ const parsed = parseAssignment(suffix.replace(/_/g, "."), raw, "env");
2365
+ if ("issue" in parsed) issues.push(parsed.issue);
2366
+ else assignments.push(parsed.assignment);
2367
+ }
2368
+ return {
2369
+ config: collect(assignments),
2370
+ issues
2371
+ };
2372
+ }
2373
+
2374
+ //#endregion
2375
+ //#region src/diagnostics.ts
2376
+ const ISSUES_URL = "https://github.com/afterpack-dev/afterpack/issues";
2377
+ const MAX_INSTANCES_PER_CODE = 5;
2378
+ const DIAGNOSTIC_MESSAGE_LIMIT = 4e3;
2379
+ const MAX_CODES_IN_SUMMARY = 6;
2380
+ const SEVERITY_RANK = {
2381
+ critical: 0,
2382
+ error: 1,
2383
+ info: 2
2384
+ };
2385
+ function isEngineDiagnostic(value) {
2386
+ if (typeof value !== "object" || value === null) return false;
2387
+ const d = value;
2388
+ return typeof d.severity === "string" && typeof d.message === "string" && typeof d.code === "string";
2389
+ }
2390
+ const DIAGNOSTIC_CODE_LIMIT = 64;
2391
+ const DIAGNOSTIC_SEVERITY_LIMIT = 16;
2392
+ const DIAGNOSTIC_FIELD_LIMIT = 500;
2393
+ function sanitizeSpan(span) {
2394
+ if (typeof span !== "object" || span === null) return null;
2395
+ const { startByte, endByte } = span;
2396
+ if (typeof startByte !== "number" || typeof endByte !== "number") return null;
2397
+ if (!Number.isFinite(startByte) || !Number.isFinite(endByte)) return null;
2398
+ return {
2399
+ startByte,
2400
+ endByte
2401
+ };
2402
+ }
2403
+ function sanitizeData(data) {
2404
+ if (typeof data !== "object" || data === null || Array.isArray(data)) return null;
2405
+ const out = {};
2406
+ for (const [key, value] of Object.entries(data)) {
2407
+ const safeKey = sanitizeServerText(key, DIAGNOSTIC_CODE_LIMIT);
2408
+ if (safeKey === "") continue;
2409
+ out[safeKey] = typeof value === "string" ? sanitizeServerText(value, DIAGNOSTIC_FIELD_LIMIT) : value;
2410
+ }
2411
+ return typeof out.kind === "string" ? out : null;
2412
+ }
2413
+ function sanitizeDiagnostic(d) {
2414
+ const out = {
2415
+ ...d,
2416
+ severity: sanitizeServerText(d.severity, DIAGNOSTIC_SEVERITY_LIMIT),
2417
+ code: sanitizeServerText(d.code, DIAGNOSTIC_CODE_LIMIT)
2418
+ };
2419
+ if (d.file != null) out.file = sanitizeServerText(d.file, DIAGNOSTIC_FIELD_LIMIT) || null;
2420
+ if (d.span != null) out.span = sanitizeSpan(d.span);
2421
+ if (d.data != null) out.data = sanitizeData(d.data);
2422
+ return out;
2423
+ }
2424
+ function sanitizeEngineDiagnostics(value) {
2425
+ if (value == null) return null;
2426
+ if (!Array.isArray(value)) return null;
2427
+ const diagnostics = value.filter(isEngineDiagnostic).map(sanitizeDiagnostic);
2428
+ return {
2429
+ diagnostics,
2430
+ malformed: value.length - diagnostics.length
2431
+ };
2432
+ }
2433
+ function collectDiagnostics(files) {
2434
+ const diagnostics = [];
2435
+ let unknownFiles = 0;
2436
+ let malformedEntries = 0;
2437
+ for (const file of files) {
2438
+ const parsed = sanitizeEngineDiagnostics(file.diagnostics);
2439
+ if (parsed === null) {
2440
+ unknownFiles += 1;
2441
+ continue;
2442
+ }
2443
+ malformedEntries += parsed.malformed;
2444
+ for (const d of parsed.diagnostics) diagnostics.push(d.file || !file.path ? d : {
2445
+ ...d,
2446
+ file: file.path
2447
+ });
2448
+ }
2449
+ return {
2450
+ diagnostics,
2451
+ unknownFiles,
2452
+ malformedEntries
2453
+ };
2454
+ }
2455
+ function resolveDiagnosticsVerbosity(option) {
2456
+ return option ?? "summary";
2457
+ }
2458
+ function formatLocator(d) {
2459
+ const span = d.span ? `bytes ${d.span.startByte}..${d.span.endByte}` : null;
2460
+ if (d.file && span) return `${d.file} ${span}`;
2461
+ return d.file || span;
2462
+ }
2463
+ function formatData(data) {
2464
+ if (!data) return null;
2465
+ const pairs = [];
2466
+ for (const [key, value] of Object.entries(data)) {
2467
+ if (key === "kind" || value === null || value === void 0) continue;
2468
+ const text = sanitizeServerText(String(value), DIAGNOSTIC_FIELD_LIMIT);
2469
+ if (typeof value === "string") pairs.push(`${key}="${text}"`);
2470
+ else if (text !== "") pairs.push(`${key}=${text}`);
2471
+ }
2472
+ return pairs.length > 0 ? pairs.join(" ") : null;
2473
+ }
2474
+ function formatDiagnostic(d) {
2475
+ const parts = [`${d.severity} ${d.code}`];
2476
+ const locator = formatLocator(d);
2477
+ if (locator) parts.push(locator);
2478
+ const message = sanitizeServerText(d.message, DIAGNOSTIC_MESSAGE_LIMIT);
2479
+ if (message) parts.push(message);
2480
+ const data = formatData(d.data);
2481
+ if (data) parts.push(data);
2482
+ return parts.join(" · ");
2483
+ }
2484
+ const DIAG_ALREADY_OBFUSCATED = "DIAG_ALREADY_OBFUSCATED";
2485
+ var AlreadyObfuscatedError = class extends Error {
2486
+ code = DIAG_ALREADY_OBFUSCATED;
2487
+ files;
2488
+ receiptPath;
2489
+ dir;
2490
+ constructor(message, files, receiptPath, dir) {
2491
+ super(message);
2492
+ this.name = "AlreadyObfuscatedError";
2493
+ this.files = files;
2494
+ this.receiptPath = receiptPath;
2495
+ this.dir = dir;
2496
+ }
2497
+ };
2498
+ const ALREADY_OBFUSCATED_FILE_CAP = 10;
2499
+ function formatAlreadyObfuscatedMessage(input) {
2500
+ const { files, receiptPath, dir } = input;
2501
+ const shown = files.slice(0, ALREADY_OBFUSCATED_FILE_CAP);
2502
+ const hidden = files.length - shown.length;
2503
+ const list = hidden > 0 ? `${shown.join(", ")}, and ${hidden} more` : shown.join(", ");
2504
+ return `error ${DIAG_ALREADY_OBFUSCATED} · ${files.length} file(s) already carry AfterPack's obfuscated output from a previous run (matched by content hash against ${receiptPath}): ${list} — rebuild from source before running AfterPack again (delete \`${dir}\` or run your bundler's clean); AfterPack output is not idempotent`;
2505
+ }
2506
+ function summarizeDiagnostics(diagnostics) {
2507
+ const summary = {
2508
+ total: 0,
2509
+ info: 0,
2510
+ error: 0,
2511
+ critical: 0,
2512
+ byCode: {}
2513
+ };
2514
+ for (const d of diagnostics) {
2515
+ summary.total += 1;
2516
+ if (d.severity === "critical" || d.severity === "error" || d.severity === "info") summary[d.severity] += 1;
2517
+ summary.byCode[d.code] = (summary.byCode[d.code] ?? 0) + 1;
2518
+ }
2519
+ return summary;
2520
+ }
2521
+ function groupByCode(diagnostics) {
2522
+ const groups = new Map();
2523
+ for (const d of diagnostics) {
2524
+ const existing = groups.get(d.code);
2525
+ if (existing) existing.push(d);
2526
+ else groups.set(d.code, [d]);
2527
+ }
2528
+ return groups;
2529
+ }
2530
+ function formatInfoSummary(infos) {
2531
+ const byCode = [...groupByCode(infos).entries()].sort((a, b) => b[1].length - a[1].length || a[0].localeCompare(b[0]));
2532
+ const shown = byCode.slice(0, MAX_CODES_IN_SUMMARY);
2533
+ const parts = shown.map(([code, list]) => `${code} x${list.length}`);
2534
+ const hidden = byCode.length - shown.length;
2535
+ if (hidden > 0) parts.push(`+${hidden} more code(s)`);
2536
+ return `${infos.length} info diagnostic(s): ${parts.join(" · ")}`;
2537
+ }
2538
+ function reportDiagnostics(input) {
2539
+ const { diagnostics, logger, prefix } = input;
2540
+ const verbosity = resolveDiagnosticsVerbosity(input.verbosity);
2541
+ const malformedEntries = input.malformedEntries ?? 0;
2542
+ const summary = summarizeDiagnostics(diagnostics);
2543
+ if (malformedEntries > 0) logger.warn(prefix(`${malformedEntries} diagnostic entry/entries did not match the engine's diagnostic contract and were dropped — treat this build's diagnostics as incomplete.`));
2544
+ if (diagnostics.length === 0) return summary;
2545
+ const infos = verbosity === "all" ? diagnostics.filter((d) => d.severity === "info") : [];
2546
+ if (infos.length > 0) {
2547
+ logger.log(prefix(formatInfoSummary(infos)));
2548
+ for (const d of infos) logger.log(prefix(formatDiagnostic(d)));
2549
+ }
2550
+ const loud = diagnostics.filter((d) => d.severity !== "info").sort((a, b) => (SEVERITY_RANK[a.severity] ?? 1) - (SEVERITY_RANK[b.severity] ?? 1));
2551
+ for (const [code, list] of groupByCode(loud)) {
2552
+ const cap = verbosity === "all" ? list.length : MAX_INSTANCES_PER_CODE;
2553
+ for (const d of list.slice(0, cap)) logger.warn(prefix(formatDiagnostic(d)));
2554
+ const hidden = list.length - cap;
2555
+ if (hidden > 0) logger.warn(prefix(`${list[0].severity} ${code} · +${hidden} more occurrence(s) (AFTERPACK_diagnostics_level=all to list them)`));
2556
+ }
2557
+ if (summary.critical > 0) logger.warn(prefix(`${summary.critical} critical diagnostic(s) above are engine bugs — please report them at ${ISSUES_URL}, quoting the code(s).`));
2558
+ return summary;
2559
+ }
2560
+
2561
+ //#endregion
2562
+ //#region src/policy.ts
2563
+ function detectProduction(env = {}, opts = {}) {
2564
+ if (opts.build?.mode !== void 0) return opts.build.mode === "production";
2565
+ return env.NODE_ENV === "production" || env.CI === "true";
2566
+ }
2567
+ function resolveReportPolicy(env = {}, userOpts = {}, signals = {}) {
2568
+ const isProduction = detectProduction(env, userOpts);
2569
+ const hasBundlerSourcemap = signals.hasBundlerSourcemap ?? false;
2570
+ const protectionMap = userOpts.protectionMap?.enabled ?? hasBundlerSourcemap;
2571
+ const autoEnableBundlerSourcemap = userOpts.protectionMap?.enabled === true && !hasBundlerSourcemap;
2572
+ const emitSourceMappingURL = userOpts.sourceMap?.emitUrl ?? !isProduction;
2573
+ const backup = userOpts.build?.backup ?? !signals.inPlaceOutput;
2574
+ const sourceMap = userOpts.sourceMap?.enabled ?? !isProduction;
2575
+ return {
2576
+ isProduction,
2577
+ protectionMap,
2578
+ autoEnableBundlerSourcemap,
2579
+ sourceMap,
2580
+ emitSourceMappingURL,
2581
+ backup,
2582
+ protectionMapInProd: isProduction && protectionMap,
2583
+ engineSourceMapOverride: userOpts.sourceMap?.enabled ?? (isProduction ? false : void 0)
2584
+ };
2585
+ }
2586
+ function resolveSourceMapEnabled(sourceMapOverride, hasInputMap) {
2587
+ if (sourceMapOverride === false) return false;
2588
+ if (sourceMapOverride === true) return true;
2589
+ return hasInputMap;
2590
+ }
2591
+ const PRESETS = PRESET_VALUES;
2592
+ const DEFAULT_PRESET = "light";
2593
+ function presetTarget(preset) {
2594
+ switch (preset) {
2595
+ case "minify": return 0;
2596
+ case "light": return 2;
2597
+ case "medium": return 8;
2598
+ case "hard": return 25;
2599
+ case "extreme": return 80;
2600
+ }
2601
+ }
2602
+ function effectiveComplexityTarget(preset, complexity) {
2603
+ return complexity ?? presetTarget(preset ?? DEFAULT_PRESET);
2604
+ }
2605
+ function buildEngineConfig(options) {
2606
+ const { filePath, policy, seed = 0, engine } = options;
2607
+ const perFileMap = "inputSourceMap" in options;
2608
+ const inputSourceMap = options.inputSourceMap ?? null;
2609
+ const sourcesContent = options.sourcesContent ?? !policy.isProduction;
2610
+ const smEnabled = perFileMap ? resolveSourceMapEnabled(policy.engineSourceMapOverride, inputSourceMap != null) : policy.engineSourceMapOverride;
2611
+ const sourceMap = { sourcesContent };
2612
+ if (smEnabled !== void 0) sourceMap.enabled = smEnabled;
2613
+ const defaults = {};
2614
+ const target = effectiveComplexityTarget(options.preset, options.complexity);
2615
+ if (options.preset !== void 0) defaults.preset = options.preset;
2616
+ if (options.preset === void 0 || options.complexity !== void 0) defaults.complexity = target;
2617
+ const config = mergeInto({
2618
+ ...defaults,
2619
+ sourceMap,
2620
+ protectionMap: { enabled: policy.protectionMap }
2621
+ }, engine ?? {});
2622
+ config.seed = seed;
2623
+ if (options.renameGlobals === true) config.identifiers = {
2624
+ ...config.identifiers,
2625
+ globals: { rename: true }
2626
+ };
2627
+ if (filePath !== void 0) config.filePath = filePath;
2628
+ if (perFileMap && smEnabled && inputSourceMap != null) config.inputSourceMap = inputSourceMap;
2629
+ if (options.regions !== void 0) config.regions = options.regions;
2630
+ return config;
2631
+ }
2632
+ function buildContext(git, client = {}) {
2633
+ const context = {};
2634
+ if (git?.commitSha) context.commitSha = git.commitSha;
2635
+ if (git?.ref) context.ref = git.ref;
2636
+ if (client.clientVersion) context.clientVersion = client.clientVersion;
2637
+ if (client.client) context.client = client.client;
2638
+ return Object.keys(context).length > 0 ? context : void 0;
2639
+ }
2640
+
2641
+ //#endregion
2642
+ //#region src/directives.ts
2643
+ const KIND_BY_LOWER = new Map(TRANSFORM_KIND_VALUES.map((k) => [k.toLowerCase(), k]));
2644
+ function parseKindList(value) {
2645
+ const parts = value.split(",").map((s) => s.trim()).filter(Boolean);
2646
+ if (parts.length === 0) return { error: "empty transform-kind list" };
2647
+ const kinds = [];
2648
+ for (const p of parts) {
2649
+ const k = KIND_BY_LOWER.get(p.toLowerCase());
2650
+ if (!k) return { error: `unknown transform kind \`${p}\`` };
2651
+ kinds.push(k);
2652
+ }
2653
+ return { kinds };
2654
+ }
2655
+ const DIRECTIVE_MARKER = "@afterpack";
2656
+ const UTF8$1 = new TextEncoder();
2657
+ function byteOffset(source, charIndex) {
2658
+ return UTF8$1.encode(source.slice(0, charIndex)).length;
2659
+ }
2660
+ function lineCol(source, charIndex) {
2661
+ let line = 1;
2662
+ let lineStart = 0;
2663
+ for (let i = 0; i < charIndex && i < source.length; i++) if (source[i] === "\n") {
2664
+ line++;
2665
+ lineStart = i + 1;
2666
+ }
2667
+ return {
2668
+ line,
2669
+ column: charIndex - lineStart + 1
2670
+ };
2671
+ }
2672
+ function scanComments(source) {
2673
+ const out = [];
2674
+ const n = source.length;
2675
+ let i = 0;
2676
+ while (i < n) {
2677
+ const c = source[i];
2678
+ if (c === "\"" || c === "'") {
2679
+ i++;
2680
+ while (i < n && source[i] !== c && source[i] !== "\n") i += source[i] === "\\" ? 2 : 1;
2681
+ i++;
2682
+ } else if (c === "`") {
2683
+ i++;
2684
+ while (i < n && source[i] !== "`") i += source[i] === "\\" ? 2 : 1;
2685
+ i++;
2686
+ } else if (c === "/" && source[i + 1] === "/") {
2687
+ const start = i;
2688
+ i += 2;
2689
+ while (i < n && source[i] !== "\n") i++;
2690
+ const body = source.slice(start + 2, i);
2691
+ if (body.includes(DIRECTIVE_MARKER)) out.push({
2692
+ kind: "line",
2693
+ start,
2694
+ end: i,
2695
+ body
2696
+ });
2697
+ } else if (c === "/" && source[i + 1] === "*") {
2698
+ const start = i;
2699
+ i += 2;
2700
+ while (i < n && !(source[i] === "*" && source[i + 1] === "/")) i++;
2701
+ out.push({
2702
+ kind: "block",
2703
+ start,
2704
+ end: Math.min(i + 2, n),
2705
+ body: source.slice(start + 2, i)
2706
+ });
2707
+ i += 2;
2708
+ } else i++;
2709
+ }
2710
+ return out;
2711
+ }
2712
+ function afterpackPayload(body) {
2713
+ const m = /^\s*@afterpack\b([\s\S]*)$/.exec(body);
2714
+ return m ? m[1].trim() : null;
2715
+ }
2716
+ const BLOCK_FORM_CTA = "open a block with `/* @afterpack <directive> */` alone on its own line and close it with `/* @afterpack end */`, or put the marker inline to scope it to the rest of that line";
2717
+ function unsupportedForm(kind, payload) {
2718
+ if (payload.startsWith(":")) return `the \`@afterpack:begin … @afterpack:end\` span form is not implemented — ${BLOCK_FORM_CTA}`;
2719
+ if (kind === "line") return `\`// @afterpack …\` line comments are not scanned — ${BLOCK_FORM_CTA}`;
2720
+ return void 0;
2721
+ }
2722
+ function classifyTier(delta) {
2723
+ const decreaseComplexity = delta.complexity === void 0 || delta.complexity === 0;
2724
+ const encode = delta.strings?.encode;
2725
+ const decreaseEncode = encode === void 0 || encode === false;
2726
+ const noMask = delta.transforms?.only === void 0 && delta.transforms?.deny === void 0;
2727
+ return decreaseComplexity && decreaseEncode && delta.inflation?.max === void 0 && noMask ? "free" : "amplifying";
2728
+ }
2729
+ function boolValue(value) {
2730
+ if (value === "on" || value === "true") return true;
2731
+ if (value === "off" || value === "false") return false;
2732
+ return void 0;
2733
+ }
2734
+ function pushDeny(delta, kinds) {
2735
+ const merged = new Set(delta.transforms?.deny ?? []);
2736
+ for (const k of kinds) merged.add(k);
2737
+ delta.transforms = {
2738
+ ...delta.transforms,
2739
+ deny: [...merged]
2740
+ };
2741
+ }
2742
+ const NOT_IMPLEMENTED_REASON = "recognised but not implemented as a per-region directive — the engine's region wire carries only complexity, inflation.max, strings.encode, transforms.only and transforms.deny; set it in afterpack.json / a CLI flag / an env var instead";
2743
+ const DIRECTIVE_KEYS = [
2744
+ {
2745
+ key: "skip",
2746
+ kind: "escapeHatch",
2747
+ bool: true,
2748
+ apply: (delta, value, notes) => {
2749
+ const on = boolValue(value);
2750
+ if (on === void 0) return "`skip` must be `on` or `off`";
2751
+ if (!on) notes.push("`skip=off` has no effect — omit the directive instead");
2752
+ else {
2753
+ delta.complexity = 0;
2754
+ delta.strings = { encode: false };
2755
+ }
2756
+ return void 0;
2757
+ }
2758
+ },
2759
+ {
2760
+ key: "controlFlow.enabled",
2761
+ kind: "escapeHatch",
2762
+ bool: true,
2763
+ apply: (delta, value, notes) => {
2764
+ const on = boolValue(value);
2765
+ if (on === void 0) return "`controlFlow.enabled` must be `on` or `off`";
2766
+ if (on) notes.push("`controlFlow.enabled=on` cannot be expressed per region — a region mask can only forbid a transform, never re-enable one the global config disabled");
2767
+ else pushDeny(delta, ["controlFlowFlatten"]);
2768
+ return void 0;
2769
+ }
2770
+ },
2771
+ {
2772
+ key: "preset",
2773
+ kind: "amplifier",
2774
+ apply: (delta, value) => {
2775
+ const preset = PRESETS.find((p) => p === value);
2776
+ if (!preset) return `unknown preset \`${value}\` (one of ${PRESETS.join(", ")})`;
2777
+ delta.complexity = presetTarget(preset);
2778
+ delta.strings = { encode: delta.complexity > 0 };
2779
+ return void 0;
2780
+ }
2781
+ },
2782
+ {
2783
+ key: "complexity",
2784
+ kind: "amplifier",
2785
+ apply: (delta, value) => {
2786
+ const n = Number(value);
2787
+ if (!Number.isFinite(n) || n < 0) return "`complexity` needs a non-negative number";
2788
+ delta.complexity = n;
2789
+ return void 0;
2790
+ }
2791
+ },
2792
+ {
2793
+ key: "inflation.max",
2794
+ kind: "amplifier",
2795
+ apply: (delta, value) => {
2796
+ const n = Number(value);
2797
+ if (!Number.isFinite(n) || n < 0) return "`inflation.max` needs a non-negative number";
2798
+ delta.inflation = { max: n };
2799
+ return void 0;
2800
+ }
2801
+ },
2802
+ {
2803
+ key: "strings.encode",
2804
+ kind: "amplifier",
2805
+ bool: true,
2806
+ apply: (delta, value) => {
2807
+ const on = boolValue(value);
2808
+ if (on === void 0) return "`strings.encode` must be `on` or `off`";
2809
+ delta.strings = { encode: on };
2810
+ return void 0;
2811
+ }
2812
+ },
2813
+ {
2814
+ key: "transforms.only",
2815
+ kind: "amplifier",
2816
+ apply: (delta, value) => {
2817
+ const { kinds, error } = parseKindList(value);
2818
+ if (error) return error;
2819
+ delta.transforms = {
2820
+ ...delta.transforms,
2821
+ only: kinds
2822
+ };
2823
+ return void 0;
2824
+ }
2825
+ },
2826
+ {
2827
+ key: "transforms.deny",
2828
+ kind: "amplifier",
2829
+ apply: (delta, value) => {
2830
+ const { kinds, error } = parseKindList(value);
2831
+ if (error || !kinds) return error;
2832
+ pushDeny(delta, kinds);
2833
+ return void 0;
2834
+ }
2835
+ },
2836
+ {
2837
+ key: "async.preserve",
2838
+ kind: "escapeHatch",
2839
+ bool: true
2840
+ },
2841
+ {
2842
+ key: "generators.preserve",
2843
+ kind: "escapeHatch",
2844
+ bool: true
2845
+ },
2846
+ {
2847
+ key: "identifiers.rename",
2848
+ kind: "escapeHatch",
2849
+ bool: true
2850
+ },
2851
+ {
2852
+ key: "identifiers.globals.rename",
2853
+ kind: "escapeHatch",
2854
+ bool: true,
2855
+ fileScope: "renameGlobals"
2856
+ },
2857
+ {
2858
+ key: "reflection.allow",
2859
+ kind: "escapeHatch"
2860
+ },
2861
+ {
2862
+ key: "strings.destructionRate",
2863
+ kind: "amplifier"
2864
+ },
2865
+ {
2866
+ key: "strings.materializationVariants",
2867
+ kind: "amplifier"
2868
+ },
2869
+ {
2870
+ key: "strings.hoistScopeBias",
2871
+ kind: "amplifier"
2872
+ },
2873
+ {
2874
+ key: "decoder.stateVarCount",
2875
+ kind: "amplifier"
2876
+ },
2877
+ {
2878
+ key: "controlFlow.deadEntries",
2879
+ kind: "amplifier"
2880
+ },
2881
+ {
2882
+ key: "codegen.useEval",
2883
+ kind: "amplifier",
2884
+ bool: true
2885
+ }
2886
+ ];
2887
+ const SPEC_BY_LOWER = new Map(DIRECTIVE_KEYS.map((s) => [s.key.toLowerCase(), s]));
2888
+ function unknownKeyError(rawKey) {
2889
+ if (rawKey.includes("-")) return `kebab-case is not a directive key (\`${rawKey}\`) — keys are dot-delimited camelCase`;
2890
+ return `unknown directive key \`${rawKey}\``;
2891
+ }
2892
+ function parseDirectivePayload(payload) {
2893
+ const notes = [];
2894
+ const fail = (keyword$1, error) => ({
2895
+ keyword: keyword$1,
2896
+ delta: {},
2897
+ tier: "free",
2898
+ notes,
2899
+ noop: true,
2900
+ error
2901
+ });
2902
+ const text = payload.trim();
2903
+ if (text === "") return fail("", "empty `@afterpack` directive");
2904
+ const tokens = text.split(/\s+/);
2905
+ const leadKey = splitAssignment(tokens[0]).key;
2906
+ if (leadKey.toLowerCase() === "end") {
2907
+ if (tokens.length > 1) return fail("end", "`@afterpack end` closes a block and takes no keys");
2908
+ return {
2909
+ keyword: "end",
2910
+ delta: {},
2911
+ tier: "free",
2912
+ notes,
2913
+ noop: false
2914
+ };
2915
+ }
2916
+ const delta = {};
2917
+ let allEscapeHatch = true;
2918
+ let keyword = leadKey;
2919
+ let renameGlobals = false;
2920
+ for (let i = 0; i < tokens.length; i++) {
2921
+ const { key: rawKey, value: rawValue } = splitAssignment(tokens[i]);
2922
+ const bare = rawValue === true;
2923
+ const spec = SPEC_BY_LOWER.get(rawKey.toLowerCase());
2924
+ if (!spec) return fail(keyword, unknownKeyError(rawKey));
2925
+ if (i === 0) keyword = spec.key;
2926
+ if (spec.kind !== "escapeHatch") allEscapeHatch = false;
2927
+ if (bare && !spec.bool) return fail(keyword, `\`${spec.key}\` needs a \`=<value>\``);
2928
+ if (spec.fileScope === "renameGlobals") {
2929
+ const on = bare ? true : boolValue(rawValue.toLowerCase());
2930
+ if (on === void 0) return fail(keyword, "`identifiers.globals.rename` must be `on` or `off`");
2931
+ if (on) renameGlobals = true;
2932
+ else notes.push("`identifiers.globals.rename=off` is the default — omit the directive instead. To keep SPECIFIC names while renaming other globals, set `identifiers.globals.rename` on and list the names to keep in `identifiers.reserved`");
2933
+ continue;
2934
+ }
2935
+ if (!spec.apply) {
2936
+ notes.push(`\`${spec.key}\` is ${NOT_IMPLEMENTED_REASON}`);
2937
+ continue;
2938
+ }
2939
+ const error = spec.apply(delta, bare ? "on" : rawValue.toLowerCase(), notes);
2940
+ if (error) return fail(keyword, error);
2941
+ }
2942
+ const noop = Object.keys(delta).length === 0;
2943
+ return {
2944
+ keyword,
2945
+ delta,
2946
+ tier: allEscapeHatch ? "free" : classifyTier(delta),
2947
+ notes,
2948
+ noop,
2949
+ renameGlobals
2950
+ };
2951
+ }
2952
+ function eolOf(source, from) {
2953
+ const nl = source.indexOf("\n", from);
2954
+ return nl < 0 ? source.length : nl;
2955
+ }
2956
+ function isInline(source, marker) {
2957
+ return source.slice(marker.end, eolOf(source, marker.end)).trim() !== "";
2958
+ }
2959
+ function lineSpan(source, marker) {
2960
+ const eol = eolOf(source, marker.end);
2961
+ if (isInline(source, marker)) return {
2962
+ start: marker.end,
2963
+ end: eol
2964
+ };
2965
+ const nextStart = eol + 1;
2966
+ return {
2967
+ start: nextStart,
2968
+ end: eolOf(source, nextStart)
2969
+ };
2970
+ }
2971
+ function record(source, parsed, marker, form, span) {
2972
+ const { line, column } = lineCol(source, marker.start);
2973
+ const region = {
2974
+ start: byteOffset(source, span.start),
2975
+ end: byteOffset(source, span.end),
2976
+ ...parsed.delta,
2977
+ label: parsed.keyword
2978
+ };
2979
+ return {
2980
+ keyword: parsed.keyword,
2981
+ form,
2982
+ tier: parsed.tier,
2983
+ line,
2984
+ column,
2985
+ region,
2986
+ charStart: span.start,
2987
+ charEnd: span.end
2988
+ };
2989
+ }
2990
+ function scanDirectives(source) {
2991
+ const directives = [];
2992
+ const diagnostics = [];
2993
+ const open = [];
2994
+ let renameGlobals = false;
2995
+ if (!source.includes(DIRECTIVE_MARKER)) return {
2996
+ regions: [],
2997
+ directives,
2998
+ diagnostics,
2999
+ renameGlobals
3000
+ };
3001
+ for (const marker of scanComments(source)) {
3002
+ const payload = afterpackPayload(marker.body);
3003
+ if (payload === null) continue;
3004
+ const at = lineCol(source, marker.start);
3005
+ const unsupported = unsupportedForm(marker.kind, payload);
3006
+ if (unsupported) {
3007
+ diagnostics.push({
3008
+ code: "DIAG_DIRECTIVE_UNSUPPORTED_FORM",
3009
+ message: unsupported,
3010
+ ...at
3011
+ });
3012
+ continue;
3013
+ }
3014
+ const parsed = parseDirectivePayload(payload);
3015
+ for (const note of parsed.notes) diagnostics.push({
3016
+ code: "DIAG_DIRECTIVE_NOT_IMPLEMENTED",
3017
+ message: note,
3018
+ ...at
3019
+ });
3020
+ if (parsed.error) {
3021
+ diagnostics.push({
3022
+ code: "DIAG_DIRECTIVE_UNKNOWN",
3023
+ message: parsed.error,
3024
+ ...at
3025
+ });
3026
+ continue;
3027
+ }
3028
+ if (parsed.renameGlobals) {
3029
+ renameGlobals = true;
3030
+ diagnostics.push({
3031
+ code: "DIAG_DIRECTIVE_REGION_TO_FILE",
3032
+ message: "`identifiers.globals.rename` cannot be scoped to a region — a global binding's references span the whole file, so a rename is wholesale; applied to the ENTIRE file instead. To keep SPECIFIC names while renaming the rest, use `identifiers.reserved`",
3033
+ ...at
3034
+ });
3035
+ }
3036
+ if (parsed.keyword === "end") {
3037
+ const opened = open.pop();
3038
+ if (!opened) {
3039
+ diagnostics.push({
3040
+ code: "DIAG_DIRECTIVE_DANGLING_END",
3041
+ message: "`@afterpack end` has no open directive",
3042
+ ...at
3043
+ });
3044
+ continue;
3045
+ }
3046
+ if (opened.parsed.noop) continue;
3047
+ directives.push(record(source, opened.parsed, opened.marker, "block", {
3048
+ start: opened.marker.end,
3049
+ end: marker.start
3050
+ }));
3051
+ continue;
3052
+ }
3053
+ if (isInline(source, marker)) {
3054
+ if (parsed.noop) continue;
3055
+ directives.push(record(source, parsed, marker, "line", {
3056
+ start: marker.end,
3057
+ end: eolOf(source, marker.end)
3058
+ }));
3059
+ } else open.push({
3060
+ parsed,
3061
+ marker
3062
+ });
3063
+ }
3064
+ for (const opened of open) {
3065
+ if (opened.parsed.noop) continue;
3066
+ directives.push(record(source, opened.parsed, opened.marker, "line", lineSpan(source, opened.marker)));
3067
+ }
3068
+ directives.sort((a, b) => a.region.start - b.region.start || a.region.end - b.region.end);
3069
+ return {
3070
+ regions: directives.map((d) => d.region),
3071
+ directives,
3072
+ diagnostics,
3073
+ renameGlobals
3074
+ };
3075
+ }
3076
+ const REFUSAL_LIST_LIMIT = 3;
3077
+ function renameGlobalsRefusalMessage(refused, fileCount) {
3078
+ const shown = refused.slice(0, REFUSAL_LIST_LIMIT).join(", ");
3079
+ const rest = refused.length > REFUSAL_LIST_LIMIT ? ` and ${refused.length - REFUSAL_LIST_LIMIT} more` : "";
3080
+ return `REFUSED \`identifiers.globals.rename\` from ${shown}${rest} — the engine takes that flag BUILD-WIDE (one shared config), so honouring it here would rename top-level bindings in all ${fileCount} file(s) of this build, not only the file that asked. Nothing was renamed. Obfuscate that file on its own to apply it.`;
3081
+ }
3082
+ function inputLabel(input, index) {
3083
+ return input.path ?? `file #${index + 1}`;
3084
+ }
3085
+ function captureDirectiveRegions(inputs, handAuthored, enabled = true) {
3086
+ if (!enabled) return {
3087
+ regions: handAuthored,
3088
+ applied: 0,
3089
+ deferredFiles: 0,
3090
+ diagnostics: [],
3091
+ renameGlobals: false,
3092
+ renameGlobalsRefused: []
3093
+ };
3094
+ if (inputs.length === 1) {
3095
+ const scan = scanDirectives(inputs[0].source);
3096
+ if (scan.regions.length === 0) return {
3097
+ regions: handAuthored,
3098
+ applied: 0,
3099
+ deferredFiles: 0,
3100
+ diagnostics: scan.diagnostics,
3101
+ renameGlobals: scan.renameGlobals,
3102
+ renameGlobalsRefused: []
3103
+ };
3104
+ return {
3105
+ regions: [...handAuthored ?? [], ...scan.regions],
3106
+ applied: scan.regions.length,
3107
+ deferredFiles: 0,
3108
+ diagnostics: scan.diagnostics,
3109
+ renameGlobals: scan.renameGlobals,
3110
+ renameGlobalsRefused: []
3111
+ };
3112
+ }
3113
+ let deferredFiles = 0;
3114
+ const renameGlobalsRefused = [];
3115
+ const diagnostics = [];
3116
+ inputs.forEach((input, index) => {
3117
+ const scan = scanDirectives(input.source);
3118
+ if (scan.regions.length > 0) deferredFiles++;
3119
+ if (scan.renameGlobals) renameGlobalsRefused.push(inputLabel(input, index));
3120
+ diagnostics.push(...scan.diagnostics);
3121
+ });
3122
+ return {
3123
+ regions: handAuthored,
3124
+ applied: 0,
3125
+ deferredFiles,
3126
+ diagnostics,
3127
+ renameGlobals: false,
3128
+ renameGlobalsRefused
3129
+ };
3130
+ }
3131
+
3132
+ //#endregion
3133
+ //#region src/git.ts
3134
+ const GIT_COMMIT_SHA_PATTERN = /^[0-9a-f]{7,40}$/;
3135
+ const GIT_REF_PATTERN = /^[A-Za-z0-9._\-/+]{1,200}$/;
3136
+ function sanitizeCommitSha(value) {
3137
+ if (typeof value !== "string") return null;
3138
+ const sha = value.trim().toLowerCase();
3139
+ return GIT_COMMIT_SHA_PATTERN.test(sha) ? sha : null;
3140
+ }
3141
+ function sanitizeGitRef(value) {
3142
+ if (typeof value !== "string") return null;
3143
+ const ref = value.trim();
3144
+ return GIT_REF_PATTERN.test(ref) ? ref : null;
3145
+ }
3146
+ function contextFrom(rawSha, rawRef) {
3147
+ const commitSha = sanitizeCommitSha(rawSha);
3148
+ const ref = sanitizeGitRef(rawRef);
3149
+ if (commitSha === null && ref === null) return null;
3150
+ const context = {};
3151
+ if (commitSha !== null) context.commitSha = commitSha;
3152
+ if (ref !== null) context.ref = ref;
3153
+ return context;
3154
+ }
3155
+ const CI_SOURCES = [
3156
+ ["GITHUB_SHA", "GITHUB_REF_NAME"],
3157
+ ["CI_COMMIT_SHA", "CI_COMMIT_REF_NAME"],
3158
+ ["VERCEL_GIT_COMMIT_SHA", "VERCEL_GIT_COMMIT_REF"],
3159
+ ["CF_PAGES_COMMIT_SHA", "CF_PAGES_BRANCH"],
3160
+ ["GIT_COMMIT", "BRANCH_NAME"]
3161
+ ];
3162
+ function ciGitContext(env) {
3163
+ for (const [shaVar, refVar] of CI_SOURCES) {
3164
+ const context = contextFrom(env[shaVar], env[refVar]);
3165
+ if (context !== null) return context;
3166
+ }
3167
+ return null;
3168
+ }
3169
+ const GIT_PROBE_TIMEOUT_MS = 2e3;
3170
+ function localGitContext(cwd) {
3171
+ let lines;
3172
+ try {
3173
+ const out = (0, node_child_process.execFileSync)("git", [
3174
+ "rev-parse",
3175
+ "HEAD",
3176
+ "--abbrev-ref",
3177
+ "HEAD"
3178
+ ], {
3179
+ cwd,
3180
+ stdio: [
3181
+ "ignore",
3182
+ "pipe",
3183
+ "ignore"
3184
+ ],
3185
+ timeout: GIT_PROBE_TIMEOUT_MS,
3186
+ maxBuffer: 64 * 1024
3187
+ }).toString();
3188
+ lines = out.split("\n").map((line) => line.trim());
3189
+ } catch {
3190
+ return null;
3191
+ }
3192
+ const ref = lines[1] === "HEAD" ? null : lines[1];
3193
+ return contextFrom(lines[0], ref);
3194
+ }
3195
+ function detectGitContext(explicit, deps = {}) {
3196
+ if (explicit) {
3197
+ const declared = contextFrom(explicit.commitSha, explicit.ref);
3198
+ if (declared !== null) return declared;
3199
+ }
3200
+ const ci = ciGitContext(deps.env ?? process.env);
3201
+ if (ci !== null) return ci;
3202
+ return (deps.localGit ?? localGitContext)(deps.cwd);
3203
+ }
3204
+
3205
+ //#endregion
3206
+ //#region src/map-color.ts
3207
+ const UTF8 = new TextEncoder();
3208
+ const utf8Len = (s) => UTF8.encode(s).length;
3209
+ const NON_ASCII = /[\u0080-\uFFFF]/;
3210
+ const HIGH_SURROGATE_START = 55296;
3211
+ const HIGH_SURROGATE_END = 56319;
3212
+ const LOW_SURROGATE_START = 56320;
3213
+ const LOW_SURROGATE_END = 57343;
3214
+ function charToByteTable(line) {
3215
+ const table = new Array(line.length + 1);
3216
+ let bytes = 0;
3217
+ let i = 0;
3218
+ while (i < line.length) {
3219
+ table[i] = bytes;
3220
+ const code = line.charCodeAt(i);
3221
+ if (code < 128) {
3222
+ bytes += 1;
3223
+ i += 1;
3224
+ continue;
3225
+ }
3226
+ if (code < 2048) {
3227
+ bytes += 2;
3228
+ i += 1;
3229
+ continue;
3230
+ }
3231
+ if (code >= HIGH_SURROGATE_START && code <= HIGH_SURROGATE_END && i + 1 < line.length) {
3232
+ const low = line.charCodeAt(i + 1);
3233
+ if (low >= LOW_SURROGATE_START && low <= LOW_SURROGATE_END) {
3234
+ table[i + 1] = bytes + 3;
3235
+ bytes += 4;
3236
+ i += 2;
3237
+ continue;
3238
+ }
3239
+ }
3240
+ bytes += 3;
3241
+ i += 1;
3242
+ }
3243
+ table[line.length] = bytes;
3244
+ return table;
3245
+ }
3246
+ var ChunkByteIndex = class {
3247
+ starts;
3248
+ ascii;
3249
+ tables;
3250
+ totalBytes;
3251
+ constructor(lines) {
3252
+ this.lines = lines;
3253
+ this.starts = new Array(lines.length);
3254
+ this.ascii = new Array(lines.length);
3255
+ this.tables = new Array(lines.length).fill(null);
3256
+ let acc = 0;
3257
+ for (let i = 0; i < lines.length; i++) {
3258
+ const line = lines[i];
3259
+ this.starts[i] = acc;
3260
+ const isAscii = !NON_ASCII.test(line);
3261
+ this.ascii[i] = isAscii;
3262
+ acc += (isAscii ? line.length : utf8Len(line)) + 1;
3263
+ }
3264
+ this.totalBytes = lines.length === 0 ? 0 : acc - 1;
3265
+ }
3266
+ byteOf(line, col) {
3267
+ if (line < 0 || line >= this.lines.length) return this.totalBytes;
3268
+ const text = this.lines[line];
3269
+ const clamped = col < 0 ? 0 : col < text.length ? col : text.length;
3270
+ if (this.ascii[line]) return this.starts[line] + clamped;
3271
+ let table = this.tables[line];
3272
+ if (table === null) {
3273
+ table = charToByteTable(text);
3274
+ this.tables[line] = table;
3275
+ }
3276
+ return this.starts[line] + table[clamped];
3277
+ }
3278
+ };
3279
+ function charToLineCol(source, charIndex) {
3280
+ let line = 0;
3281
+ let lineStart = 0;
3282
+ const stop = Math.min(charIndex, source.length);
3283
+ for (let i = 0; i < stop; i++) if (source.charCodeAt(i) === 10) {
3284
+ line++;
3285
+ lineStart = i + 1;
3286
+ }
3287
+ return {
3288
+ line,
3289
+ col: charIndex - lineStart
3290
+ };
3291
+ }
3292
+ function norm(p) {
3293
+ return p.replace(/\\/g, "/").replace(/[?#].*$/, "").replace(/^(?:\.\.?\/)+/, "");
3294
+ }
3295
+ function normEq(a, b) {
3296
+ return a === b || a.endsWith(`/${b}`) || b.endsWith(`/${a}`);
3297
+ }
3298
+ const DEFAULT_WARN = (message) => {
3299
+ console.warn(`[afterpack] ${message}`);
3300
+ };
3301
+ const countDirectives = (modules) => modules.reduce((n, m) => n + m.directives.length, 0);
3302
+ function colorRegions(chunkCode, map, modules, warn = DEFAULT_WARN) {
3303
+ const withDirectives = modules.filter((m) => m.directives.length > 0);
3304
+ if (withDirectives.length === 0) return [];
3305
+ let segsByLine = null;
3306
+ if (map && typeof map.mappings === "string") try {
3307
+ segsByLine = (0, __jridgewell_sourcemap_codec.decode)(map.mappings);
3308
+ } catch {
3309
+ segsByLine = null;
3310
+ }
3311
+ if (!segsByLine || !map) {
3312
+ warn(`DIAG_DIRECTIVE_COVERAGE_UNVERIFIED: skipped ${countDirectives(withDirectives)} @afterpack directive(s) from ${withDirectives.length} module(s) — this chunk has no decodable source map, so they cannot be placed in its bytes.`);
3313
+ return [];
3314
+ }
3315
+ const sources = map.sources ?? [];
3316
+ const normSources = sources.map((s) => s == null ? null : norm(s));
3317
+ const lines = chunkCode.split("\n");
3318
+ const index = new ChunkByteIndex(lines);
3319
+ const bySource = bucketBySource(segsByLine, lines);
3320
+ const out = [];
3321
+ const located = [];
3322
+ for (const mod of withDirectives) {
3323
+ let srcIdx = mod.srcIndex != null && mod.srcIndex >= 0 && mod.srcIndex < sources.length ? mod.srcIndex : -1;
3324
+ if (srcIdx < 0) {
3325
+ const normId = norm(mod.id);
3326
+ srcIdx = normSources.findIndex((ns) => ns != null && normEq(normId, ns));
3327
+ }
3328
+ if (srcIdx < 0) {
3329
+ warn(`DIAG_DIRECTIVE_COVERAGE_UNVERIFIED: skipped ${mod.directives.length} @afterpack directive(s) — the bundler placed \`${mod.id}\` in this chunk but its source map does not list it, so they cannot be placed in the chunk's bytes.`);
3330
+ continue;
3331
+ }
3332
+ located.push({
3333
+ mod,
3334
+ srcIdx
3335
+ });
3336
+ const segments$1 = bySource.get(srcIdx) ?? [];
3337
+ for (const d of mod.directives) {
3338
+ const start = charToLineCol(mod.source, d.charStart);
3339
+ const end = charToLineCol(mod.source, d.charEnd);
3340
+ const ranges = coverGenerated(segments$1, start, end, index);
3341
+ for (const [s, e] of ranges) out.push({
3342
+ ...d.region,
3343
+ start: s,
3344
+ end: e
3345
+ });
3346
+ }
3347
+ }
3348
+ if (out.length === 0 && located.length > 0) for (const { mod, srcIdx } of located) if ((bySource.get(srcIdx)?.length ?? 0) === 0) warn(`DIAG_DIRECTIVE_SOURCE_UNRESOLVED: \`${mod.id}\` carries ${mod.directives.length} @afterpack directive(s) but this chunk's source map has NO mapping segment anywhere for that source, so its interior cannot be resolved at all — the directive(s) were NOT applied. This is a source-map coverage gap, not tree-shaking.`);
3349
+ else warn(`DIAG_DIRECTIVE_TARGET_ELIMINATED: located \`${mod.id}\` carrying ${mod.directives.length} @afterpack directive(s) in this chunk's source map but colored 0 ranges for it — the marked code was tree-shaken, or the map's original coordinates do not line up with the captured source.`);
3350
+ return out;
3351
+ }
3352
+ function bucketBySource(segsByLine, lines) {
3353
+ const bySource = new Map();
3354
+ for (let gl = 0; gl < segsByLine.length; gl++) {
3355
+ const segs = segsByLine[gl];
3356
+ for (let i = 0; i < segs.length; i++) {
3357
+ const seg = segs[i];
3358
+ if (seg.length < 4) continue;
3359
+ const genCol = seg[0];
3360
+ const srcIdx = seg[1];
3361
+ let bucket = bySource.get(srcIdx);
3362
+ if (bucket === void 0) {
3363
+ bucket = [];
3364
+ bySource.set(srcIdx, bucket);
3365
+ }
3366
+ bucket.push({
3367
+ genLine: gl,
3368
+ genCol,
3369
+ endCol: i + 1 < segs.length ? segs[i + 1][0] : lines[gl]?.length ?? genCol,
3370
+ srcLine: seg[2],
3371
+ srcCol: seg[3]
3372
+ });
3373
+ }
3374
+ }
3375
+ return bySource;
3376
+ }
3377
+ function coverGenerated(segments$1, start, end, index) {
3378
+ const inSpan = (line, col) => {
3379
+ const afterStart = line > start.line || line === start.line && col >= start.col;
3380
+ const beforeEnd = line < end.line || line === end.line && col < end.col;
3381
+ return afterStart && beforeEnd;
3382
+ };
3383
+ const ranges = [];
3384
+ for (const seg of segments$1) {
3385
+ if (!inSpan(seg.srcLine, seg.srcCol)) continue;
3386
+ const s = index.byteOf(seg.genLine, seg.genCol);
3387
+ const e = index.byteOf(seg.genLine, seg.endCol);
3388
+ if (e > s) ranges.push([s, e]);
3389
+ }
3390
+ ranges.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
3391
+ const merged = [];
3392
+ for (const [a, b] of ranges) {
3393
+ const last = merged[merged.length - 1];
3394
+ if (last && a <= last[1]) last[1] = Math.max(last[1], b);
3395
+ else merged.push([a, b]);
3396
+ }
3397
+ return merged;
3398
+ }
3399
+
3400
+ //#endregion
3401
+ //#region src/receipt.ts
3402
+ const PROTECTION_RECEIPT_FILE = ".afterpack-protection.json";
3403
+ const PROTECTION_RECEIPT_SCHEMA = 1;
3404
+ function sha256OfBytes(bytes) {
3405
+ return (0, node_crypto.createHash)("sha256").update(bytes).digest("hex");
3406
+ }
3407
+ function sha256Of(path) {
3408
+ return sha256OfBytes((0, node_fs.readFileSync)(path));
3409
+ }
3410
+ function receiptPathOf(dir, file) {
3411
+ return (0, node_path.relative)(dir, file).split(node_path.sep).join("/");
3412
+ }
3413
+ function writeDeferredProtectionReceipt(deferred) {
3414
+ const survivingFiles = deferred.files.filter((file) => (0, node_fs.existsSync)(file));
3415
+ if (survivingFiles.length === 0) return null;
3416
+ return writeProtectionReceipt({
3417
+ ...deferred,
3418
+ files: survivingFiles
3419
+ });
3420
+ }
3421
+ function writeProtectionReceipt(input) {
3422
+ const transformed = new Set(input.transformed);
3423
+ const receipt = {
3424
+ schema: PROTECTION_RECEIPT_SCHEMA,
3425
+ tool: input.tool,
3426
+ engine: input.engine,
3427
+ engineVersion: input.engineVersion,
3428
+ seed: String(input.seed),
3429
+ seedOrigin: input.seedOrigin,
3430
+ bundler: input.bundler,
3431
+ buildId: input.buildId,
3432
+ files: input.files.map((file) => ({
3433
+ path: receiptPathOf(input.dir, file),
3434
+ sha256: sha256Of(file),
3435
+ transformed: transformed.has(file)
3436
+ })).sort((a, b) => a.path.localeCompare(b.path))
3437
+ };
3438
+ const path = (0, node_path.join)(input.dir, PROTECTION_RECEIPT_FILE);
3439
+ (0, node_fs.writeFileSync)(path, `${JSON.stringify(receipt, null, 2)}\n`);
3440
+ return path;
3441
+ }
3442
+ function parseReceipt(path) {
3443
+ let raw;
3444
+ try {
3445
+ raw = JSON.parse((0, node_fs.readFileSync)(path, "utf8"));
3446
+ } catch (error) {
3447
+ const reason = error instanceof Error ? error.message : String(error);
3448
+ return {
3449
+ error: `${path} is not valid JSON: ${reason}`,
3450
+ newerSchema: null
3451
+ };
3452
+ }
3453
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return {
3454
+ error: `${path} is not a protection receipt object`,
3455
+ newerSchema: null
3456
+ };
3457
+ const receipt = raw;
3458
+ const schema = receipt.schema;
3459
+ const newerSchema = typeof schema === "number" && Number.isInteger(schema) && schema > PROTECTION_RECEIPT_SCHEMA ? schema : null;
3460
+ const fail = (error) => ({
3461
+ error,
3462
+ newerSchema
3463
+ });
3464
+ if (typeof schema !== "number" || !Number.isInteger(schema) || schema < PROTECTION_RECEIPT_SCHEMA) return fail(`${path} has schema ${String(schema)}, which this afterpack cannot read`);
3465
+ if (!Array.isArray(receipt.files)) return fail(`${path} lists no files`);
3466
+ if (!receipt.files.every(isReceiptFile)) return fail(`${path} lists a file entry it cannot read`);
3467
+ return { receipt };
3468
+ }
3469
+ function isReceiptFile(value) {
3470
+ if (typeof value !== "object" || value === null) return false;
3471
+ const entry = value;
3472
+ return typeof entry.path === "string" && typeof entry.sha256 === "string";
3473
+ }
3474
+ const DIAG_RECEIPT_UNREADABLE = "DIAG_RECEIPT_UNREADABLE";
3475
+ var UnreadableReceiptError = class extends Error {
3476
+ code = DIAG_RECEIPT_UNREADABLE;
3477
+ receiptPath;
3478
+ schema;
3479
+ constructor(message, receiptPath, schema) {
3480
+ super(message);
3481
+ this.name = "UnreadableReceiptError";
3482
+ this.receiptPath = receiptPath;
3483
+ this.schema = schema;
3484
+ }
3485
+ };
3486
+ function verifyProtectionReceipt(dir, expectedBuildId) {
3487
+ const receiptPath = (0, node_path.join)(dir, PROTECTION_RECEIPT_FILE);
3488
+ if (!(0, node_fs.existsSync)(receiptPath)) return {
3489
+ receiptPath,
3490
+ receipt: null,
3491
+ problems: [`no protection receipt at ${receiptPath}`]
3492
+ };
3493
+ const result = parseReceipt(receiptPath);
3494
+ if (result.error !== void 0) return {
3495
+ receiptPath,
3496
+ receipt: null,
3497
+ problems: [result.error]
3498
+ };
3499
+ const parsed = result.receipt;
3500
+ const problems = [];
3501
+ if (expectedBuildId != null && parsed.buildId !== expectedBuildId) problems.push(`receipt is for build ${String(parsed.buildId)}, but this output is build ${expectedBuildId} — the tree was rebuilt without the AfterPack wrapper`);
3502
+ if (parsed.files.length === 0) problems.push("receipt records zero obfuscated files");
3503
+ const transformed = parsed.files.filter((f) => f.transformed !== false).length;
3504
+ if (parsed.files.length > 0 && transformed === 0) problems.push(`receipt lists ${parsed.files.length} file(s) but the engine changed NONE of them — this build shipped its source (check \`paths.exclude\` and AFTERPACK_paths_exclude)`);
3505
+ for (const entry of parsed.files) {
3506
+ const file = (0, node_path.join)(dir, entry.path);
3507
+ if (!(0, node_fs.existsSync)(file)) {
3508
+ problems.push(`${entry.path}: obfuscated at build time, missing now`);
3509
+ continue;
3510
+ }
3511
+ if (sha256Of(file) !== entry.sha256) problems.push(`${entry.path}: content changed since it was obfuscated`);
3512
+ }
3513
+ return {
3514
+ receiptPath,
3515
+ receipt: parsed,
3516
+ problems
3517
+ };
3518
+ }
3519
+ function findReceiptDir(startDir) {
3520
+ const receiptPath = findUpward(startDir, PROTECTION_RECEIPT_FILE);
3521
+ return receiptPath ? (0, node_path.dirname)(receiptPath) : null;
3522
+ }
3523
+ function detectAlreadyObfuscatedInputs(files, startDir, bytesByPath, prefix = (m) => m) {
3524
+ const dir = findReceiptDir(startDir);
3525
+ if (!dir) return null;
3526
+ const receiptPath = (0, node_path.join)(dir, PROTECTION_RECEIPT_FILE);
3527
+ const result = parseReceipt(receiptPath);
3528
+ if (result.error !== void 0) {
3529
+ const schema = result.newerSchema;
3530
+ if (schema === null) return null;
3531
+ throw new UnreadableReceiptError(prefix(`${receiptPath} was written by a newer AfterPack (receipt schema ${schema}), so this version cannot tell whether these files are already obfuscated — update afterpack, or rebuild from source and delete the receipt before running it again.`), receiptPath, schema);
3532
+ }
3533
+ const outputHashes = new Set(result.receipt.files.map((f) => f.sha256));
3534
+ if (outputHashes.size === 0) return null;
3535
+ const matches = files.filter((file) => {
3536
+ const bytes = bytesByPath?.get(file);
3537
+ if (bytes !== void 0) return outputHashes.has(sha256OfBytes(bytes));
3538
+ return (0, node_fs.existsSync)(file) && outputHashes.has(sha256Of(file));
3539
+ });
3540
+ return matches.length > 0 ? {
3541
+ receiptPath,
3542
+ files: matches
3543
+ } : null;
3544
+ }
3545
+
3546
+ //#endregion
3547
+ //#region src/seed.ts
3548
+ function randomSeed() {
3549
+ const b = (0, node_crypto.randomBytes)(8);
3550
+ const hi = b.readUInt32BE(0) & 2097151;
3551
+ const lo = b.readUInt32BE(4);
3552
+ return hi * 4294967296 + lo;
3553
+ }
3554
+ function gitHead() {
3555
+ try {
3556
+ const out = (0, node_child_process.execFileSync)("git", ["rev-parse", "HEAD"], { stdio: [
3557
+ "ignore",
3558
+ "pipe",
3559
+ "ignore"
3560
+ ] }).toString().trim();
3561
+ return /^[0-9a-f]{7,64}$/i.test(out) ? out : null;
3562
+ } catch {
3563
+ return null;
3564
+ }
3565
+ }
3566
+ const SEED_ENV_VAR = "AFTERPACK_SEED";
3567
+ function parseSeedValue(raw) {
3568
+ return /^-?\d+$/.test(raw) ? Number(raw) : raw;
3569
+ }
3570
+ const SEED_STATE = Symbol.for("afterpack.integration-utils.seed-sessions");
3571
+ function sharedSeedState() {
3572
+ const holder = globalThis;
3573
+ holder[SEED_STATE] ??= {
3574
+ sessions: new Map(),
3575
+ ownEnvExports: []
3576
+ };
3577
+ return holder[SEED_STATE];
3578
+ }
3579
+ const { sessions, ownEnvExports } = sharedSeedState();
3580
+ function isOwnEnvExport(env, value) {
3581
+ return ownEnvExports.some((e) => e.env === env && e.value === value);
3582
+ }
3583
+ function openGeneration(root, leg) {
3584
+ let session = sessions.get(root);
3585
+ if (!session) {
3586
+ session = {
3587
+ seed: void 0,
3588
+ generation: 1,
3589
+ legs: [],
3590
+ resolvedByLeg: new Map(),
3591
+ gitFallbackWarned: false
3592
+ };
3593
+ sessions.set(root, session);
3594
+ } else if (session.legs.includes(leg)) {
3595
+ session.seed = void 0;
3596
+ session.generation += 1;
3597
+ session.legs = [];
3598
+ session.resolvedByLeg.clear();
3599
+ session.gitFallbackWarned = false;
3600
+ }
3601
+ session.legs.push(leg);
3602
+ return session;
3603
+ }
3604
+ function resolveWithinSession(input, session, env, deps) {
3605
+ if (typeof input === "number") return {
3606
+ seed: input,
3607
+ origin: "option"
3608
+ };
3609
+ if (typeof input === "string" && input !== "git") return {
3610
+ seed: input,
3611
+ origin: "option"
3612
+ };
3613
+ if (input === "git") {
3614
+ const head = (deps.gitHead ?? gitHead)();
3615
+ if (head) return {
3616
+ seed: head,
3617
+ origin: "git"
3618
+ };
3619
+ if (!session.gitFallbackWarned) {
3620
+ session.gitFallbackWarned = true;
3621
+ (deps.warn ?? ((m) => console.warn(m)))("[afterpack] seed \"git\": no git repository / HEAD found; using a fresh random seed for this build.");
3622
+ }
3623
+ }
3624
+ const fromEnv = env[SEED_ENV_VAR];
3625
+ if (fromEnv != null && fromEnv !== "" && !isOwnEnvExport(env, fromEnv)) return {
3626
+ seed: parseSeedValue(fromEnv),
3627
+ origin: "env"
3628
+ };
3629
+ if (session.seed !== void 0) return {
3630
+ seed: session.seed,
3631
+ origin: "session"
3632
+ };
3633
+ return {
3634
+ seed: (deps.randomSeed ?? randomSeed)(),
3635
+ origin: "fresh"
3636
+ };
3637
+ }
3638
+ function resolveBuildSeed(input, scope, deps = {}) {
3639
+ const env = deps.env ?? process.env;
3640
+ const session = openGeneration(scope.root, scope.leg);
3641
+ const { seed, origin } = resolveWithinSession(input, session, env, deps);
3642
+ if (origin === "env" || origin === "fresh") session.seed = seed;
3643
+ if (origin === "fresh" && (deps.exportToEnv ?? true)) {
3644
+ const value = String(seed);
3645
+ env[SEED_ENV_VAR] = value;
3646
+ const stale = ownEnvExports.findIndex((e) => e.env === env);
3647
+ if (stale >= 0) ownEnvExports.splice(stale, 1);
3648
+ ownEnvExports.push({
3649
+ env,
3650
+ value
3651
+ });
3652
+ }
3653
+ const prior = [...session.resolvedByLeg].find(([, s]) => s !== seed);
3654
+ session.resolvedByLeg.set(scope.leg, seed);
3655
+ return {
3656
+ seed,
3657
+ origin,
3658
+ legs: [...session.legs],
3659
+ generation: session.generation,
3660
+ mismatch: prior && session.generation === 1 ? {
3661
+ leg: prior[0],
3662
+ seed: prior[1]
3663
+ } : null
3664
+ };
3665
+ }
3666
+
3667
+ //#endregion
3668
+ //#region src/summary.ts
3669
+ function fmtBytes(n) {
3670
+ if (n < 1024) return `${n} B`;
3671
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
3672
+ return `${(n / (1024 * 1024)).toFixed(2)} MB`;
3673
+ }
3674
+ function fmtElapsed(ms) {
3675
+ return ms < 1e3 ? `${Math.round(ms)}ms` : `${(ms / 1e3).toFixed(1)}s`;
3676
+ }
3677
+ function formatPassSummary(input, style, colorGlyph = (glyph) => glyph) {
3678
+ const head = style === "cli" ? colorGlyph("✓") : `[${input.label}]`;
3679
+ const files = input.fileCount === 1 ? "file" : "files";
3680
+ const tail = (input.unobfuscatedCount > 0 ? ` · ${input.unobfuscatedCount} shipped UNOBFUSCATED (fallback, cleartext)` : "") + (input.noOpCount > 0 ? ` · ${input.noOpCount} no-op (unchanged)` : "");
3681
+ return `${head} Protected ${input.fileCount} ${files} · ${fmtBytes(input.inputBytes)} → ${fmtBytes(input.outputBytes)}${tail} · ${fmtElapsed(input.elapsedMs)}`;
3682
+ }
3683
+
3684
+ //#endregion
3685
+ //#region src/telemetry.ts
3686
+ const API_URL_ENV_VAR = "AFTERPACK_API_URL";
3687
+ const DEFAULT_API_URL = "https://api.afterpack.dev";
3688
+ const TELEMETRY_ENDPOINT_PATH = "/v1/telemetry/build";
3689
+ const TELEMETRY_PAYLOAD_VERSION = 1;
3690
+ const TELEMETRY_TIMEOUT_MS = 1500;
3691
+ const INSTALL_ID_ROTATION_DAYS = 30;
3692
+ const TELEMETRY_DIAGNOSTIC_LIMIT = 20;
3693
+ const TELEMETRY_STATE_FILE = (0, node_path.join)((0, node_os.homedir)(), ".afterpack", "telemetry.json");
3694
+ const TOKEN_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
3695
+ const DATA_FIELD_WHITELIST = {
3696
+ outputUnparseable: ["parserErrorKind", "outputByteOffset"],
3697
+ parseError: ["parserErrorKind"],
3698
+ engineBug: [
3699
+ "phase",
3700
+ "transform",
3701
+ "nodeKind"
3702
+ ],
3703
+ inflationBudget: [
3704
+ "target",
3705
+ "achieved",
3706
+ "budgetRatio",
3707
+ "inflationRatio"
3708
+ ],
3709
+ configParse: [
3710
+ "category",
3711
+ "line",
3712
+ "column"
3713
+ ]
3714
+ };
3715
+ function resolveTelemetryEnabled(option, env = {}) {
3716
+ if (option !== void 0) return option;
3717
+ return !(env.NODE_ENV === "test" || env.VITEST);
3718
+ }
3719
+ const FRAMEWORK_ENTRIES = [
3720
+ {
3721
+ label: "afterpack",
3722
+ name: "cli"
3723
+ },
3724
+ {
3725
+ label: "afterpack-angular",
3726
+ name: "angular",
3727
+ pkg: "@angular/core"
3728
+ },
3729
+ {
3730
+ label: "afterpack-esbuild",
3731
+ name: "esbuild",
3732
+ pkg: "esbuild"
3733
+ },
3734
+ {
3735
+ label: "afterpack-next",
3736
+ name: "next",
3737
+ pkg: "next"
3738
+ },
3739
+ {
3740
+ label: "afterpack-rollup",
3741
+ name: "rollup",
3742
+ pkg: "rollup"
3743
+ },
3744
+ {
3745
+ label: "afterpack-vite",
3746
+ name: "vite",
3747
+ pkg: "vite"
3748
+ },
3749
+ {
3750
+ label: "afterpack-webpack",
3751
+ name: "webpack",
3752
+ pkg: "webpack"
3753
+ }
3754
+ ];
3755
+ const FRAMEWORK_BY_LABEL = new Map(FRAMEWORK_ENTRIES.map((e) => [e.label, e.name]));
3756
+ const FRAMEWORK_PACKAGE_BY_NAME = new Map(FRAMEWORK_ENTRIES.flatMap((e) => e.pkg ? [[e.name, e.pkg]] : []));
3757
+ function frameworkFromLabel(label) {
3758
+ return FRAMEWORK_BY_LABEL.get(label.split(":")[0]) ?? "unknown";
3759
+ }
3760
+ const VERSION_RANGE_PATTERN = /^[\sv0-9.\-+*xX^~><=|]{1,32}$/;
3761
+ function detectFrameworkVersion(projectRoot, framework) {
3762
+ const pkgName = FRAMEWORK_PACKAGE_BY_NAME.get(framework);
3763
+ if (!pkgName) return null;
3764
+ let deps;
3765
+ try {
3766
+ const pkg = JSON.parse((0, node_fs.readFileSync)((0, node_path.join)(projectRoot, "package.json"), "utf8"));
3767
+ deps = {
3768
+ ...pkg.dependencies,
3769
+ ...pkg.devDependencies
3770
+ };
3771
+ } catch {
3772
+ return null;
3773
+ }
3774
+ const raw = deps[pkgName];
3775
+ if (typeof raw !== "string") return null;
3776
+ const range = raw.trim();
3777
+ return VERSION_RANGE_PATTERN.test(range) && /[0-9*xX]/.test(range) ? range : null;
3778
+ }
3779
+ function complexityLabel(preset, complexity) {
3780
+ if (preset !== void 0) return preset;
3781
+ return complexity === void 0 ? "default" : "custom";
3782
+ }
3783
+ const FILE_COUNT_BUCKETS = [
3784
+ 1,
3785
+ 5,
3786
+ 20,
3787
+ 100,
3788
+ 500,
3789
+ 2e3
3790
+ ];
3791
+ function fileCountBucket(count) {
3792
+ if (!Number.isFinite(count) || count <= 0) return "0";
3793
+ let lower = 1;
3794
+ for (const upper of FILE_COUNT_BUCKETS) {
3795
+ if (count <= upper) return lower === upper ? `${upper}` : `${lower}-${upper}`;
3796
+ lower = upper + 1;
3797
+ }
3798
+ return `${FILE_COUNT_BUCKETS[FILE_COUNT_BUCKETS.length - 1]}+`;
3799
+ }
3800
+ const DURATION_BUCKETS_MS = [
3801
+ [1e3, "<1s"],
3802
+ [5e3, "1-5s"],
3803
+ [15e3, "5-15s"],
3804
+ [6e4, "15-60s"],
3805
+ [3e5, "60-300s"]
3806
+ ];
3807
+ function durationBucket(ms) {
3808
+ if (!Number.isFinite(ms) || ms < 0) return "unknown";
3809
+ for (const [upper, label] of DURATION_BUCKETS_MS) if (ms < upper) return label;
3810
+ return "300s+";
3811
+ }
3812
+ function safeScalar(value) {
3813
+ if (typeof value === "number") return Number.isFinite(value) ? value : null;
3814
+ if (typeof value === "string") return TOKEN_PATTERN.test(value) ? value : null;
3815
+ return null;
3816
+ }
3817
+ function telemetrySafeData(data) {
3818
+ if (!data || typeof data.kind !== "string") return null;
3819
+ const kind = TOKEN_PATTERN.test(data.kind) ? data.kind : null;
3820
+ if (kind === null) return null;
3821
+ const out = { kind };
3822
+ for (const field of DATA_FIELD_WHITELIST[kind] ?? []) {
3823
+ const value = safeScalar(data[field]);
3824
+ if (value !== null) out[field] = value;
3825
+ }
3826
+ return out;
3827
+ }
3828
+ function telemetrySafeSpan(d) {
3829
+ const span = d.span;
3830
+ if (!span) return null;
3831
+ const start = safeScalar(span.startByte);
3832
+ const end = safeScalar(span.endByte);
3833
+ if (typeof start !== "number" || typeof end !== "number") return null;
3834
+ if (start < 0 || end < 0) return null;
3835
+ return {
3836
+ startByte: start,
3837
+ endByte: end
3838
+ };
3839
+ }
3840
+ function telemetrySafeDiagnostic(d, severity) {
3841
+ return {
3842
+ code: TOKEN_PATTERN.test(d.code) ? d.code : "DIAG_UNKNOWN",
3843
+ severity,
3844
+ span: telemetrySafeSpan(d),
3845
+ data: telemetrySafeData(d.data)
3846
+ };
3847
+ }
3848
+ function buildTelemetryPayload(facts, ctx) {
3849
+ let errorCount = 0;
3850
+ let criticalCount = 0;
3851
+ const alerting = [];
3852
+ for (const d of facts.diagnostics) {
3853
+ if (d.severity !== "error" && d.severity !== "critical") continue;
3854
+ if (d.severity === "critical") criticalCount += 1;
3855
+ else errorCount += 1;
3856
+ alerting.push(telemetrySafeDiagnostic(d, d.severity));
3857
+ }
3858
+ if (alerting.length === 0) return null;
3859
+ const kept = alerting.slice(-TELEMETRY_DIAGNOSTIC_LIMIT);
3860
+ const env = ctx.env ?? {};
3861
+ const runtime = ctx.runtime ?? {
3862
+ node: process.versions.node,
3863
+ platform: process.platform,
3864
+ arch: process.arch
3865
+ };
3866
+ const framework = frameworkFromLabel(facts.label);
3867
+ return {
3868
+ version: TELEMETRY_PAYLOAD_VERSION,
3869
+ installId: ctx.installId,
3870
+ framework,
3871
+ frameworkVersion: detectFrameworkVersion(facts.projectRoot, framework),
3872
+ engineVersion: safeVersion(facts.engineVersion),
3873
+ clientVersion: safeVersion(facts.clientVersion),
3874
+ nodeVersion: safeVersion(runtime.node) ?? "unknown",
3875
+ os: safeToken(runtime.platform),
3876
+ arch: safeToken(runtime.arch),
3877
+ ci: env.CI === "true",
3878
+ complexity: complexityLabel(facts.preset, facts.complexity),
3879
+ fileCountBucket: fileCountBucket(facts.fileCount),
3880
+ durationBucket: durationBucket(facts.durationMs),
3881
+ diagnostics: kept,
3882
+ errorCount,
3883
+ criticalCount,
3884
+ droppedCount: alerting.length - kept.length
3885
+ };
3886
+ }
3887
+ const VERSION_PATTERN = /^[0-9][0-9A-Za-z.\-+]{0,31}$/;
3888
+ function safeVersion(value) {
3889
+ return typeof value === "string" && VERSION_PATTERN.test(value) ? value : null;
3890
+ }
3891
+ function safeToken(value) {
3892
+ return TOKEN_PATTERN.test(value) ? value : "unknown";
3893
+ }
3894
+ const TELEMETRY_NOTICE = [
3895
+ "AfterPack: anonymous build diagnostics are ON (this notice prints once).",
3896
+ "AfterPack: A build that reports an error-level diagnostic (a refused or partial build)",
3897
+ "AfterPack: sends that diagnostic's code, severity, byte offsets and typed engine",
3898
+ "AfterPack: fields, plus engine version, integration, Node version, OS/arch, bucketed",
3899
+ "AfterPack: file counts and durations, and a random install id that rotates every 30",
3900
+ "AfterPack: days.",
3901
+ "AfterPack: It never sends your source, file names, paths, project name, diagnostic",
3902
+ "AfterPack: message text, or exact byte counts. A clean build sends nothing.",
3903
+ "AfterPack: Turn it off with AFTERPACK_telemetry_enabled=false, --telemetry.enabled=false, or",
3904
+ "AfterPack: `telemetry: { enabled: false }` in your config.",
3905
+ "AfterPack: https://www.afterpack.dev/privacy"
3906
+ ];
3907
+ const INSTALL_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
3908
+ const DAY_MS = 24 * 60 * 60 * 1e3;
3909
+ function readState(file, now) {
3910
+ try {
3911
+ const parsed = JSON.parse((0, node_fs.readFileSync)(file, "utf8"));
3912
+ if (typeof parsed.installId === "string" && INSTALL_ID_PATTERN.test(parsed.installId) && typeof parsed.rotatedAt === "number") return {
3913
+ installId: parsed.installId,
3914
+ rotatedAt: parsed.rotatedAt,
3915
+ noticeShownAt: typeof parsed.noticeShownAt === "number" ? parsed.noticeShownAt : 0
3916
+ };
3917
+ } catch {}
3918
+ return {
3919
+ installId: (0, node_crypto.randomUUID)(),
3920
+ rotatedAt: now,
3921
+ noticeShownAt: 0
3922
+ };
3923
+ }
3924
+ function writeState(file, state) {
3925
+ try {
3926
+ (0, node_fs.mkdirSync)((0, node_path.dirname)(file), { recursive: true });
3927
+ (0, node_fs.writeFileSync)(file, `${JSON.stringify(state)}\n`, "utf8");
3928
+ } catch {}
3929
+ }
3930
+ function telemetryUrl(env) {
3931
+ const base = (env[API_URL_ENV_VAR] ?? DEFAULT_API_URL).replace(/\/+$/, "");
3932
+ return `${base}${TELEMETRY_ENDPOINT_PATH}`;
3933
+ }
3934
+ const TELEMETRY_BODY_LIMIT = 64 * 1024;
3935
+ async function reportTelemetryNotices(response, logger) {
3936
+ if (!response || response.status !== 202 || typeof response.text !== "function") return;
3937
+ const declared = Number(response.headers?.get?.("content-length"));
3938
+ if (Number.isFinite(declared) && declared > TELEMETRY_BODY_LIMIT) {
3939
+ await response.body?.cancel().catch(() => {});
3940
+ return;
3941
+ }
3942
+ const text = await response.text();
3943
+ if (text.length > TELEMETRY_BODY_LIMIT) return;
3944
+ let body;
3945
+ try {
3946
+ body = JSON.parse(text);
3947
+ } catch {
3948
+ return;
3949
+ }
3950
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return;
3951
+ reportNotices(body.notices, logger);
3952
+ }
3953
+ function createTelemetryReporter(deps = {}) {
3954
+ const env = deps.env ?? process.env;
3955
+ const logger = deps.logger ?? console;
3956
+ const now = deps.now ?? Date.now;
3957
+ const stateFile = deps.stateFile ?? TELEMETRY_STATE_FILE;
3958
+ const timeoutMs = deps.timeoutMs ?? TELEMETRY_TIMEOUT_MS;
3959
+ return async (facts) => {
3960
+ try {
3961
+ const at = now();
3962
+ const state = readState(stateFile, at);
3963
+ let dirty = false;
3964
+ if (at - state.rotatedAt >= INSTALL_ID_ROTATION_DAYS * DAY_MS) {
3965
+ state.installId = (0, node_crypto.randomUUID)();
3966
+ state.rotatedAt = at;
3967
+ dirty = true;
3968
+ }
3969
+ if (state.noticeShownAt === 0) {
3970
+ for (const line of TELEMETRY_NOTICE) logger.log(line);
3971
+ state.noticeShownAt = at;
3972
+ dirty = true;
3973
+ }
3974
+ if (dirty) writeState(stateFile, state);
3975
+ if (facts === null) return;
3976
+ const payload = buildTelemetryPayload(facts, {
3977
+ installId: state.installId,
3978
+ env
3979
+ });
3980
+ if (payload === null) return;
3981
+ const fetchImpl = deps.fetchImpl ?? globalThis.fetch;
3982
+ if (typeof fetchImpl !== "function") return;
3983
+ const response = await fetchImpl(telemetryUrl(env), {
3984
+ method: "POST",
3985
+ headers: { "content-type": "application/json" },
3986
+ body: JSON.stringify(payload),
3987
+ signal: AbortSignal.timeout(timeoutMs)
3988
+ });
3989
+ await reportTelemetryNotices(response, logger);
3990
+ } catch {}
3991
+ };
3992
+ }
3993
+
3994
+ //#endregion
3995
+ //#region src/pass.ts
3996
+ function silenceSummaryLines(logger, level) {
3997
+ if (level !== "none") return logger;
3998
+ return {
3999
+ warn: (m) => logger.warn(m),
4000
+ log: () => {}
4001
+ };
4002
+ }
4003
+ function parseSourceMap(json) {
4004
+ if (!json) return null;
4005
+ try {
4006
+ const m = JSON.parse(json);
4007
+ if (typeof m.mappings !== "string") return null;
4008
+ return {
4009
+ sources: m.sources ?? [],
4010
+ mappings: m.mappings,
4011
+ sourcesContent: Array.isArray(m.sourcesContent) ? m.sourcesContent : void 0
4012
+ };
4013
+ } catch {
4014
+ return null;
4015
+ }
4016
+ }
4017
+ function fileFailure(f, source) {
4018
+ if (f.status !== "success") {
4019
+ const reason = sanitizeServerText(f.error);
4020
+ if (reason) return reason;
4021
+ return f.status === "failure" ? "empty output" : `the engine reported status "${sanitizeServerText(f.status, 32)}"`;
4022
+ }
4023
+ if (typeof f.unobfuscated !== "boolean") return "the engine result does not say whether the file was obfuscated";
4024
+ if (f.code === "" && source.trim() !== "") return sanitizeServerText(f.error) || "empty output";
4025
+ return null;
4026
+ }
4027
+ async function readEngineVersion(engine) {
4028
+ try {
4029
+ return await engine.version?.() ?? null;
4030
+ } catch {
4031
+ return null;
4032
+ }
4033
+ }
4034
+ function describeLevel(preset, complexity) {
4035
+ if (complexity === void 0) return `preset "${preset ?? DEFAULT_PRESET}"`;
4036
+ if (preset === void 0) return `complexity target ${complexity}`;
4037
+ return `preset "${preset}" with complexity target ${complexity}`;
4038
+ }
4039
+ async function runObfuscationPass(options) {
4040
+ const passStartedAt = options.startedAt ?? Date.now();
4041
+ const callerAnchored = options.startedAt !== void 0;
4042
+ const { files, engine, label, gitignoreDir, combinedProtectionMap, artifactOptions = {}, env = process.env } = options;
4043
+ const logger = silenceSummaryLines(options.logger ?? DEFAULT_LOGGER, options.diagnostics);
4044
+ const prefix = (message) => `[${label}] ${message}`;
4045
+ const style = options.summaryStyle ?? "plugin";
4046
+ assertSupportedCore(options.client, prefix);
4047
+ const onDiskFiles = options.inputs ? files.filter((f) => !options.inputs?.has(f)) : files;
4048
+ const onDiskBytes = new Map(await Promise.all(onDiskFiles.map(async (filePath) => [filePath, await (0, node_fs_promises.readFile)(filePath)])));
4049
+ if (!options.emitToCaller) {
4050
+ const already = detectAlreadyObfuscatedInputs(onDiskFiles, combinedProtectionMap.buildDir, onDiskBytes, prefix);
4051
+ if (already) throw new AlreadyObfuscatedError(prefix(formatAlreadyObfuscatedMessage({
4052
+ files: already.files,
4053
+ receiptPath: already.receiptPath,
4054
+ dir: combinedProtectionMap.buildDir
4055
+ })), already.files, already.receiptPath, combinedProtectionMap.buildDir);
4056
+ }
4057
+ const resolvedSeed = resolveBuildSeed(options.seed, {
4058
+ root: gitignoreDir,
4059
+ leg: options.buildLeg ?? combinedProtectionMap.buildDir
4060
+ }, {
4061
+ env,
4062
+ warn: (m) => logger.warn(m)
4063
+ });
4064
+ const seed = resolvedSeed.seed;
4065
+ if (resolvedSeed.mismatch) logger.warn(prefix(`build seed ${seed} does not match leg "${resolvedSeed.mismatch.leg}" of this same build, which used ${resolvedSeed.mismatch.seed} — pin the same \`seed\` on every leg (or none) so the bundles share one polymorphic layout.`));
4066
+ const directivesEnabled = options.directivesEnabled ?? false;
4067
+ const bundledCapture = options.capturedByFile != null;
4068
+ const postMinifyMode = directivesEnabled && options.postMinify === true && !bundledCapture;
4069
+ const sourceByPath = new Map();
4070
+ let coloredRegionCount = 0;
4071
+ let directivesNeededMap = false;
4072
+ let postMinifyMapsSeen = 0;
4073
+ const postMinifyDiagnostics = [];
4074
+ const postMinifyRenameGlobals = [];
4075
+ const inputs = files.map((filePath) => {
4076
+ const provided = options.inputs?.get(filePath);
4077
+ const source = provided ? provided.source : (onDiskBytes.get(filePath) ?? (0, node_fs.readFileSync)(filePath)).toString("utf8");
4078
+ sourceByPath.set(filePath, source);
4079
+ const inputSourceMap = provided ? provided.sourceMap ?? null : discoverInputSourceMap(filePath, source);
4080
+ let regions;
4081
+ const modules = options.capturedByFile?.get(filePath);
4082
+ if (modules?.some((m) => m.directives.length > 0)) {
4083
+ const map = parseSourceMap(inputSourceMap);
4084
+ if (!map) directivesNeededMap = true;
4085
+ else {
4086
+ const colored = colorRegions(source, map, modules, (m) => logger.warn(prefix(m)));
4087
+ if (colored.length > 0) {
4088
+ regions = colored;
4089
+ coloredRegionCount += colored.length;
4090
+ }
4091
+ }
4092
+ } else if (postMinifyMode) {
4093
+ const map = parseSourceMap(inputSourceMap);
4094
+ if (map?.sourcesContent && map.sourcesContent.length > 0) {
4095
+ postMinifyMapsSeen += 1;
4096
+ const mods = [];
4097
+ for (let i = 0; i < map.sourcesContent.length; i++) {
4098
+ const content = map.sourcesContent[i];
4099
+ const id = map.sources[i];
4100
+ if (!content || id == null || !content.includes(DIRECTIVE_MARKER)) continue;
4101
+ const scan = scanDirectives(content);
4102
+ for (const d of scan.diagnostics) postMinifyDiagnostics.push(`${id} (${d.line}:${d.column}): ${d.message}`);
4103
+ if (scan.renameGlobals) postMinifyRenameGlobals.push(`${id} (bundled into ${filePath})`);
4104
+ if (scan.directives.length > 0) mods.push({
4105
+ id,
4106
+ source: content,
4107
+ directives: scan.directives,
4108
+ srcIndex: i
4109
+ });
4110
+ }
4111
+ if (mods.length > 0) {
4112
+ const colored = colorRegions(source, map, mods, (m) => logger.warn(prefix(m)));
4113
+ if (colored.length > 0) {
4114
+ regions = colored;
4115
+ coloredRegionCount += colored.length;
4116
+ }
4117
+ }
4118
+ }
4119
+ }
4120
+ return {
4121
+ path: filePath,
4122
+ source,
4123
+ sourceMap: inputSourceMap ?? void 0,
4124
+ regions
4125
+ };
4126
+ });
4127
+ onDiskBytes.clear();
4128
+ const hasBundlerSourcemap = (options.hasBundlerSourcemap ?? false) || inputs.some((i) => i.sourceMap != null);
4129
+ const policy = resolveReportPolicy(env, artifactOptions, {
4130
+ hasBundlerSourcemap,
4131
+ inPlaceOutput: true
4132
+ });
4133
+ ensureGitignore(combinedProtectionMap.buildDir);
4134
+ if (policy.autoEnableBundlerSourcemap && options.messages?.autoEnableBundlerSourcemap) logger.warn(prefix(options.messages.autoEnableBundlerSourcemap));
4135
+ if (options.emitToCaller && artifactOptions.build?.backup === true) logger.warn(prefix("build.backup:true is not available on this build — the obfuscated output is handed back in memory, so there is no emitted file for a `.backup.<hash>` copy to sit beside."));
4136
+ const capture = captureDirectiveRegions(inputs, options.regions, directivesEnabled && !bundledCapture && !(postMinifyMode && inputs.length > 1));
4137
+ for (const d of capture.diagnostics) logger.warn(prefix(`directive at ${d.line}:${d.column}: ${d.message}`));
4138
+ for (const d of postMinifyDiagnostics) logger.warn(prefix(`directive in ${d}`));
4139
+ const bundledRenameGlobals = [];
4140
+ if (bundledCapture && directivesEnabled) {
4141
+ for (const [file, modules] of options.capturedByFile ?? []) for (const mod of modules) if (mod.renameGlobals) bundledRenameGlobals.push(`${mod.id} (bundled into ${file})`);
4142
+ }
4143
+ const renameGlobalsRefused = [
4144
+ ...capture.renameGlobalsRefused,
4145
+ ...postMinifyRenameGlobals,
4146
+ ...bundledRenameGlobals
4147
+ ];
4148
+ if (renameGlobalsRefused.length > 0) logger.warn(prefix(renameGlobalsRefusalMessage(renameGlobalsRefused, files.length)));
4149
+ if (capture.deferredFiles > 0) logger.warn(prefix(`found @afterpack directives in ${capture.deferredFiles} file(s) but this is a multi-file build; enable the bundler's directive capture (backward-coloring) to apply them.`));
4150
+ if (coloredRegionCount > 0) logger.log(prefix(`applied ${coloredRegionCount} directive region(s) across the bundle`));
4151
+ if (directivesNeededMap) logger.warn(prefix("found @afterpack directives in a bundled file with no source map — skipped them (enable the bundler's sourcemap so they can be colored into the emitted output)."));
4152
+ if (postMinifyMode && options.directivesEnabledExplicit === true && files.length > 0 && postMinifyMapsSeen === 0 && options.messages?.directivesNeedClientMaps) logger.warn(prefix(options.messages.directivesNeedClientMaps));
4153
+ const mappedInputs = inputs.filter((i) => i.sourceMap != null).length;
4154
+ if (policy.protectionMap && files.length > 0 && mappedInputs > 0 && mappedInputs < files.length) logger.warn(prefix(`source-map coverage: ${mappedInputs}/${files.length} chunk(s) had a discoverable input source map — the other ${files.length - mappedInputs} are attributed only as opaque dist chunks, so the Protection Map under-reports their original sources.`));
4155
+ const git = artifactOptions.git === false ? null : detectGitContext(artifactOptions.git ?? null, {
4156
+ env,
4157
+ cwd: gitignoreDir
4158
+ });
4159
+ const engineConfig = buildEngineConfig({
4160
+ policy,
4161
+ seed,
4162
+ preset: options.preset,
4163
+ complexity: options.complexity,
4164
+ regions: capture.regions,
4165
+ engine: options.engineConfig,
4166
+ renameGlobals: capture.renameGlobals
4167
+ });
4168
+ if (style !== "cli") logger.log(prefix(`obfuscating ${inputs.length} file(s) at ${describeLevel(options.preset, options.complexity)} ...`));
4169
+ const engineStartedAt = Date.now();
4170
+ const prepMs = engineStartedAt - passStartedAt;
4171
+ const context = buildContext(git, {
4172
+ clientVersion: options.client?.coreVersion,
4173
+ client: clientString(options.client)
4174
+ });
4175
+ let batch;
4176
+ try {
4177
+ batch = await engine.processBatch(inputs, engineConfig, context);
4178
+ } catch (error) {
4179
+ const cloud = toCloudApiError(error, {
4180
+ identity: options.client,
4181
+ prefix
4182
+ });
4183
+ if (!cloud) throw error;
4184
+ reportNotices(cloud.notices, logger, prefix);
4185
+ throw cloud;
4186
+ }
4187
+ const engineEndedAt = Date.now();
4188
+ reportNotices(batch.notices, logger, prefix);
4189
+ const engineMs = engineEndedAt - engineStartedAt;
4190
+ const collected = collectDiagnostics(batch.files);
4191
+ const diagnosticsSummary = reportDiagnostics({
4192
+ diagnostics: collected.diagnostics,
4193
+ malformedEntries: collected.malformedEntries,
4194
+ logger,
4195
+ prefix,
4196
+ verbosity: resolveDiagnosticsVerbosity(options.diagnostics)
4197
+ });
4198
+ if (collected.unknownFiles > 0 && batch.source === "cloud") logger.warn(prefix("engine diagnostics are not returned on the Pro Cloud path — this build's diagnostics were recorded server-side."));
4199
+ const telemetry = options.telemetry;
4200
+ const telemetryEnabled = telemetry != null && resolveTelemetryEnabled(artifactOptions.telemetry?.enabled, env);
4201
+ const engineVersion = (batch.source === "cloud" ? safeVersionString(batch.engineVersion) : null) ?? await readEngineVersion(engine);
4202
+ if (telemetry && telemetryEnabled) {
4203
+ const facts = {
4204
+ label,
4205
+ projectRoot: gitignoreDir,
4206
+ diagnostics: collected.diagnostics,
4207
+ fileCount: files.length,
4208
+ durationMs: engineEndedAt - passStartedAt,
4209
+ preset: options.preset,
4210
+ complexity: options.complexity,
4211
+ engineVersion,
4212
+ clientVersion: options.clientVersion ?? options.client?.packageVersion ?? null
4213
+ };
4214
+ await telemetry(facts);
4215
+ }
4216
+ const protectionMapDocs = [];
4217
+ const sensitiveArtifactPaths = [];
4218
+ const outputs = [];
4219
+ let inputBytes = 0;
4220
+ let outputBytes = 0;
4221
+ const unobfuscatedFiles = [];
4222
+ let noOp = 0;
4223
+ const transformedFiles = [];
4224
+ const verified = [];
4225
+ for (const f of batch.files) {
4226
+ const source = sourceByPath.get(f.path);
4227
+ if (source === void 0) throw new Error(prefix(`no captured source for engine-returned path ${f.path}`));
4228
+ const failure = fileFailure(f, source);
4229
+ if (failure !== null) throw new Error(prefix(`failed to obfuscate ${f.path}: ${failure}`));
4230
+ inputBytes += Buffer.byteLength(source);
4231
+ outputBytes += Buffer.byteLength(f.code);
4232
+ if (f.unobfuscated === true) unobfuscatedFiles.push((0, node_path.basename)(f.path));
4233
+ else if (f.code === source) noOp += 1;
4234
+ else transformedFiles.push(f.path);
4235
+ if (policy.protectionMap && f.protectionMap != null) protectionMapDocs.push(f.protectionMap);
4236
+ verified.push({
4237
+ result: f,
4238
+ source
4239
+ });
4240
+ }
4241
+ if (unobfuscatedFiles.length > 0) if (artifactOptions.allowUnobfuscated === true) for (const name of unobfuscatedFiles) logger.warn(prefix(`${name} could not be obfuscated and SHIPPED AS CLEARTEXT (allowUnobfuscated:true). This is an engine bug — please report it.`));
4242
+ else throw new Error(prefix(`${unobfuscatedFiles.length} file(s) could not be obfuscated and would ship as cleartext: ${unobfuscatedFiles.join(", ")} — fix the engine or set allowUnobfuscated:true`));
4243
+ const writtenFiles = [];
4244
+ const emittedFiles = [];
4245
+ for (const { result: f, source } of verified) {
4246
+ if (options.emitToCaller) {
4247
+ outputs.push({
4248
+ path: f.path,
4249
+ code: f.code,
4250
+ sourceMap: f.sourceMap ?? null
4251
+ });
4252
+ emittedFiles.push(f.path);
4253
+ continue;
4254
+ }
4255
+ const written = writeArtifacts({
4256
+ outPath: f.path,
4257
+ code: f.code,
4258
+ sourceMapJson: f.sourceMap ?? null,
4259
+ protectionMapJson: null,
4260
+ originalSource: source,
4261
+ policy,
4262
+ mode: "framework",
4263
+ logger
4264
+ });
4265
+ writtenFiles.push(written.codePath);
4266
+ if (written.mapPath) sensitiveArtifactPaths.push(written.mapPath);
4267
+ if (written.backupPath) sensitiveArtifactPaths.push(written.backupPath);
4268
+ }
4269
+ if (!options.emitToCaller) options.afterWrite?.();
4270
+ const protectionMapPath = writeCombinedProtectionMap({
4271
+ buildDir: combinedProtectionMap.buildDir,
4272
+ docs: protectionMapDocs,
4273
+ policy,
4274
+ afterpackDir: combinedProtectionMap.afterpackDir,
4275
+ fileName: combinedProtectionMap.fileName,
4276
+ logger
4277
+ });
4278
+ if (protectionMapPath) sensitiveArtifactPaths.push(protectionMapPath);
4279
+ for (const artifactPath of sensitiveArtifactPaths) if (warnIfPublicPath(artifactPath, logger)) break;
4280
+ let receiptPath = null;
4281
+ let deferredReceipt = null;
4282
+ const engineSource = batch.source === "local" || batch.source === "cloud" ? batch.source : null;
4283
+ const receiptFields = {
4284
+ tool: label,
4285
+ engine: engineSource,
4286
+ engineVersion,
4287
+ seed,
4288
+ seedOrigin: resolvedSeed.origin,
4289
+ bundler: options.receipt?.bundler ?? "unknown",
4290
+ buildId: options.receipt?.buildId ?? null,
4291
+ transformed: transformedFiles
4292
+ };
4293
+ if (options.emitToCaller) deferredReceipt = {
4294
+ ...receiptFields,
4295
+ dir: combinedProtectionMap.buildDir,
4296
+ files: emittedFiles
4297
+ };
4298
+ else {
4299
+ receiptPath = writeProtectionReceipt({
4300
+ ...receiptFields,
4301
+ dir: combinedProtectionMap.buildDir,
4302
+ files: writtenFiles
4303
+ });
4304
+ if (style !== "cli") logger.log(prefix(`wrote protection receipt -> ${receiptPath} (afterpack verify)`));
4305
+ }
4306
+ const writeEndedAt = Date.now();
4307
+ const writeMs = writeEndedAt - engineEndedAt;
4308
+ const totalMs = writeEndedAt - passStartedAt;
4309
+ const cloudMs = engineSource === "cloud" ? engineMs : null;
4310
+ const timing = {
4311
+ totalMs,
4312
+ prepMs,
4313
+ engineMs,
4314
+ writeMs,
4315
+ cloudMs,
4316
+ engineSource,
4317
+ callerAnchored
4318
+ };
4319
+ const summaryVerbosity = resolveDiagnosticsVerbosity(options.diagnostics);
4320
+ const seedSuffix = summaryVerbosity === "all" ? ` · seed ${seed} (${resolvedSeed.mismatch ? "MISMATCH" : resolvedSeed.origin})` : "";
4321
+ logger.log(formatPassSummary({
4322
+ label,
4323
+ fileCount: files.length,
4324
+ inputBytes,
4325
+ outputBytes,
4326
+ unobfuscatedCount: unobfuscatedFiles.length,
4327
+ noOpCount: noOp,
4328
+ elapsedMs: totalMs
4329
+ }, style, options.colorGlyph) + seedSuffix);
4330
+ return {
4331
+ fileCount: files.length,
4332
+ protectionMapPath,
4333
+ receiptPath,
4334
+ deferredReceipt,
4335
+ policy,
4336
+ seed,
4337
+ seedOrigin: resolvedSeed.origin,
4338
+ timing,
4339
+ diagnostics: diagnosticsSummary,
4340
+ transformedFiles,
4341
+ ...options.emitToCaller ? { outputs } : {}
4342
+ };
4343
+ }
4344
+
4345
+ //#endregion
4346
+ //#region src/plugin-config.ts
4347
+ const PLUGIN_LOCAL_KEYS = ["git"];
4348
+ function proKeyMessage(surface) {
4349
+ return `\`key\` is not a plugin option (${surface}) — no plugin forwards it, and a bundler config is committed source. Set \`AFTERPACK_KEY\` in the environment, or \`key\` in afterpack.json, instead — without it the build runs locally, without Pro protection.`;
4350
+ }
4351
+ function normalizePluginOptions(input, localKeys, surface) {
4352
+ const config = {};
4353
+ const issues = [];
4354
+ if (input === void 0 || input === null) return {
4355
+ config,
4356
+ issues
4357
+ };
4358
+ if (!isPlainObject(input)) {
4359
+ issues.push({
4360
+ path: "",
4361
+ message: `configuration (${surface}) must be an object`
4362
+ });
4363
+ return {
4364
+ config,
4365
+ issues
4366
+ };
4367
+ }
4368
+ const local = new Set([...PLUGIN_LOCAL_KEYS, ...localKeys]);
4369
+ for (const [name, value] of Object.entries(input)) {
4370
+ if (value === void 0 || local.has(name)) continue;
4371
+ if (name === "key") {
4372
+ issues.push({
4373
+ path: name,
4374
+ message: proKeyMessage(surface)
4375
+ });
4376
+ continue;
4377
+ }
4378
+ if (CONFIG_BY_PATH.has(name)) {
4379
+ config[name] = value;
4380
+ continue;
4381
+ }
4382
+ if (CONFIG_PREFIXES.has(name)) {
4383
+ const existing = config[name];
4384
+ config[name] = isPlainObject(value) && isPlainObject(existing) ? deepMerge(existing, value) : value;
4385
+ continue;
4386
+ }
4387
+ issues.push({
4388
+ path: name,
4389
+ message: unknownKeyMessage(name, surface)
4390
+ });
4391
+ }
4392
+ return {
4393
+ config,
4394
+ issues
4395
+ };
4396
+ }
4397
+ function passSettings(resolved) {
4398
+ const settings = resolved.options;
4399
+ return {
4400
+ artifactOptions: settings.artifactOptions,
4401
+ seed: settings.seed,
4402
+ preset: settings.preset,
4403
+ complexity: settings.complexity,
4404
+ regions: settings.regions,
4405
+ engineConfig: resolved.engineConfig,
4406
+ diagnostics: settings.diagnostics?.level,
4407
+ directivesEnabled: settings.directives.enabled,
4408
+ directivesEnabledExplicit: settings.directives.explicit
4409
+ };
4410
+ }
4411
+ function unsupportedIssues(unsupported, merged, layers) {
4412
+ if (!unsupported) return [];
4413
+ const out = [];
4414
+ for (const [path, reason] of Object.entries(unsupported)) {
4415
+ const resolved = getPath(merged, path);
4416
+ if (resolved === void 0 || resolved === false) continue;
4417
+ if (Array.isArray(resolved) && resolved.length === 0) continue;
4418
+ const from = [...layers].reverse().find((l) => getPath(l.config, path) !== void 0);
4419
+ out.push(` ${from?.name ?? "configuration"}: \`${path}\` is not supported here — ${reason}`);
4420
+ }
4421
+ return out;
4422
+ }
4423
+ function applyResolvedKey(config, env = process.env) {
4424
+ const key = getPath(config, "key");
4425
+ if (typeof key === "string" && key !== "") env.AFTERPACK_KEY = key;
4426
+ }
4427
+ function sameRankConflicts(options, cli) {
4428
+ const issues = [];
4429
+ for (const key of CONFIG_KEYS) {
4430
+ const fromOptions = getPath(options, key.path);
4431
+ const fromCli = getPath(cli, key.path);
4432
+ if (fromOptions === void 0 || fromCli === void 0) continue;
4433
+ if (JSON.stringify(fromOptions) === JSON.stringify(fromCli)) continue;
4434
+ issues.push({
4435
+ path: key.path,
4436
+ message: `\`${key.path}\` is set twice at the same precedence — the options object says ${JSON.stringify(fromOptions)}, the command line says ${JSON.stringify(fromCli)}. A flag and an option rank equally, so neither wins: set it in one of them, or move it to afterpack.json.`
4437
+ });
4438
+ }
4439
+ return issues;
4440
+ }
4441
+ const NO_ARGV = {
4442
+ config: EMPTY_CONFIG,
4443
+ positionals: [],
4444
+ help: false,
4445
+ version: false,
4446
+ issues: []
4447
+ };
4448
+ function argvOnlyAnswer(cli) {
4449
+ const config = EMPTY_CONFIG;
4450
+ return {
4451
+ config,
4452
+ options: toPluginOptions(config),
4453
+ engineConfig: toEngineConfig(config),
4454
+ configFile: null,
4455
+ positionals: cli.positionals,
4456
+ help: cli.help,
4457
+ version: cli.version
4458
+ };
4459
+ }
4460
+ function resolvePluginConfig(input) {
4461
+ const cli = input.argv ? parseCliOptions(input.argv) : NO_ARGV;
4462
+ if (cli.help || cli.version) return argvOnlyAnswer(cli);
4463
+ const file = loadConfigFile(input.cwd ?? process.cwd());
4464
+ const env = parseEnvOptions(input.env ?? process.env);
4465
+ const localKeys = input.localKeys ?? [];
4466
+ const optionsSurface = `the ${input.label} options object`;
4467
+ const normalized = normalizePluginOptions(input.options, localKeys, optionsSurface);
4468
+ const options = validateConfig(normalized.config, optionsSurface);
4469
+ const explicit = mergeConfig(options.config, cli.config);
4470
+ const config = mergeConfig(mergeConfig(file.config, env.config), explicit);
4471
+ const issues = [
4472
+ ...file.issues.map((i) => ` ${file.path ?? CONFIG_FILE_NAME}: ${i.message}`),
4473
+ ...env.issues.map((i) => ` environment: ${i.message}`),
4474
+ ...[...normalized.issues, ...options.issues].map((i) => ` ${optionsSurface}: ${i.message}`),
4475
+ ...cli.issues.map((i) => ` command line: ${i.message}`),
4476
+ ...sameRankConflicts(options.config, cli.config).map((i) => ` ${i.message}`),
4477
+ ...unsupportedIssues(input.unsupported, config, [
4478
+ {
4479
+ name: file.path ?? CONFIG_FILE_NAME,
4480
+ config: file.config
4481
+ },
4482
+ {
4483
+ name: "environment",
4484
+ config: env.config
4485
+ },
4486
+ {
4487
+ name: optionsSurface,
4488
+ config: options.config
4489
+ },
4490
+ {
4491
+ name: "command line",
4492
+ config: cli.config
4493
+ }
4494
+ ])
4495
+ ];
4496
+ if (issues.length > 0) throw new Error([`[${input.label}] refusing to build with an invalid configuration:`, ...issues].join("\n"));
4497
+ applyResolvedKey(config, input.env ?? process.env);
4498
+ const pluginOptions = toPluginOptions(config);
4499
+ const supplied = isPlainObject(input.options) ? input.options : {};
4500
+ const localArtifactOptions = {};
4501
+ for (const name of PLUGIN_LOCAL_KEYS) if (supplied[name] !== void 0) localArtifactOptions[name] = supplied[name];
4502
+ return {
4503
+ config,
4504
+ options: {
4505
+ ...pluginOptions,
4506
+ artifactOptions: {
4507
+ ...pluginOptions.artifactOptions,
4508
+ ...localArtifactOptions
4509
+ }
4510
+ },
4511
+ engineConfig: toEngineConfig(config),
4512
+ configFile: file.path,
4513
+ positionals: cli.positionals,
4514
+ help: false,
4515
+ version: false
4516
+ };
4517
+ }
4518
+
4519
+ //#endregion
4520
+ exports.AlreadyObfuscatedError = AlreadyObfuscatedError;
4521
+ exports.CLOUD_REFUSAL_SUMMARY = CLOUD_REFUSAL_SUMMARY;
4522
+ exports.CONFIG_FILE_NAME = CONFIG_FILE_NAME;
4523
+ exports.CONFIG_KEYS = CONFIG_KEYS;
4524
+ exports.CORE_FLOOR_SUMMARY = CORE_FLOOR_SUMMARY;
4525
+ exports.CloudApiError = CloudApiError;
4526
+ exports.CoreVersionError = CoreVersionError;
4527
+ exports.DIAG_ALREADY_OBFUSCATED = DIAG_ALREADY_OBFUSCATED;
4528
+ exports.DIAG_RECEIPT_UNREADABLE = DIAG_RECEIPT_UNREADABLE;
4529
+ exports.PROTECTION_RECEIPT_FILE = PROTECTION_RECEIPT_FILE;
4530
+ exports.SEED_ENV_VAR = SEED_ENV_VAR;
4531
+ exports.UnreadableReceiptError = UnreadableReceiptError;
4532
+ exports.applyBundleOutput = applyBundleOutput;
4533
+ exports.applyResolvedKey = applyResolvedKey;
4534
+ exports.collectBundleJs = collectBundleJs;
4535
+ exports.collectJsFiles = collectJsFiles;
4536
+ exports.collectSourceMaps = collectSourceMaps;
4537
+ exports.createTelemetryReporter = createTelemetryReporter;
4538
+ exports.decodeDataUri = decodeDataUri;
4539
+ exports.discoverInputSourceMap = discoverInputSourceMap;
4540
+ exports.extractSourceMappingURL = extractSourceMappingURL;
4541
+ exports.findUpward = findUpward;
4542
+ exports.getPath = getPath;
4543
+ exports.installedRequiredLine = installedRequiredLine;
4544
+ exports.loadConfigFile = loadConfigFile;
4545
+ exports.mergeConfig = mergeConfig;
4546
+ exports.normalizePluginOptions = normalizePluginOptions;
4547
+ exports.npxAlternative = npxAlternative;
4548
+ exports.parseCliOptions = parseCliOptions;
4549
+ exports.parseEnvOptions = parseEnvOptions;
4550
+ exports.passSettings = passSettings;
4551
+ exports.resolveClientIdentity = resolveClientIdentity;
4552
+ exports.resolvePluginConfig = resolvePluginConfig;
4553
+ exports.resolveReportPolicy = resolveReportPolicy;
4554
+ exports.runObfuscationPass = runObfuscationPass;
4555
+ exports.sanitizeNotices = sanitizeNotices;
4556
+ exports.scanDirectives = scanDirectives;
4557
+ exports.serverAddsInfo = serverAddsInfo;
4558
+ exports.sha256Of = sha256Of;
4559
+ exports.toEngineConfig = toEngineConfig;
4560
+ exports.toPluginOptions = toPluginOptions;
4561
+ exports.validateConfig = validateConfig;
4562
+ exports.verifyProtectionReceipt = verifyProtectionReceipt;
4563
+ exports.withSourceMappingURL = withSourceMappingURL;
4564
+ exports.writeArtifacts = writeArtifacts;
4565
+ exports.writeDeferredProtectionReceipt = writeDeferredProtectionReceipt;
4566
+ exports.writeProtectionReceipt = writeProtectionReceipt;