@afterpack/integration-utils 0.2.3 → 0.2.5

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.js CHANGED
@@ -1,14 +1,200 @@
1
1
  import { createRequire } from "node:module";
2
- import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
2
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
3
+ import { accessSync, chmodSync, closeSync, constants, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
3
4
  import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } from "node:path";
4
5
  import { renderProtectionMapHtml } from "@afterpack/protection-map";
5
- import { createHash, randomBytes, randomUUID } from "node:crypto";
6
+ import { brotliCompressSync, gzipSync } from "node:zlib";
6
7
  import { fileURLToPath } from "node:url";
7
- import { readFile } from "node:fs/promises";
8
8
  import { execFileSync } from "node:child_process";
9
+ import { homedir, tmpdir, userInfo } from "node:os";
10
+ import { readFile } from "node:fs/promises";
9
11
  import { decode } from "@jridgewell/sourcemap-codec";
10
- import { homedir } from "node:os";
11
12
 
13
+ //#region src/atomic-write.ts
14
+ const STAGED_SUFFIX = ".afterpack-tmp";
15
+ function stagedPath(path) {
16
+ return `${path}${STAGED_SUFFIX}`;
17
+ }
18
+ function sha256Hex(content) {
19
+ return createHash("sha256").update(content).digest("hex");
20
+ }
21
+ function writeFileAtomic(path, content) {
22
+ const staged = stagedPath(path);
23
+ let mode = null;
24
+ try {
25
+ mode = statSync(path).mode & 4095;
26
+ } catch {
27
+ mode = null;
28
+ }
29
+ try {
30
+ writeFileSync(staged, content);
31
+ if (mode !== null) chmodSync(staged, mode);
32
+ renameSync(staged, path);
33
+ } catch (error) {
34
+ try {
35
+ rmSync(staged, { force: true });
36
+ } catch {}
37
+ throw error;
38
+ }
39
+ }
40
+
41
+ //#endregion
42
+ //#region src/angular-integrity.ts
43
+ const SRI_ATTR = /\b(src|href)\s*=\s*"([^"]+)"[^>]*\bintegrity\s*=\s*"(sha(?:256|384|512))-[^"]*"/g;
44
+ const SRI_ATTR_REVERSED = /\bintegrity\s*=\s*"(sha(?:256|384|512))-[^"]*"[^>]*\b(src|href)\s*=\s*"([^"]+)"/g;
45
+ function digest(bytes, algo, enc) {
46
+ return createHash(algo).update(bytes).digest(enc);
47
+ }
48
+ function fileFor(baseDir, ref) {
49
+ if (/^[a-z][a-z0-9+.-]*:/i.test(ref) || ref.startsWith("//")) return null;
50
+ const path = ref.split(/[?#]/)[0];
51
+ if (path === "") return null;
52
+ return join(baseDir, path);
53
+ }
54
+ function planHtmlIntegrity(browserDir, planned) {
55
+ for (const html of htmlFilesUnder(browserDir)) {
56
+ const text = readFileSync(html, "utf8");
57
+ const rewrite = (algo, ref, match) => {
58
+ const file = fileFor(browserDir, ref);
59
+ if (file === null || !existsSync(file)) return match;
60
+ const hash = digest(readFileSync(file), algo, "base64");
61
+ return match.replace(/integrity\s*=\s*"sha(?:256|384|512)-[^"]*"/, `integrity="${algo}-${hash}"`);
62
+ };
63
+ let next = text.replace(SRI_ATTR, (match, _attr, ref, algo) => rewrite(algo, ref, match));
64
+ next = next.replace(SRI_ATTR_REVERSED, (match, algo, _attr, ref) => rewrite(algo, ref, match));
65
+ if (next !== text) planned.set(html, next);
66
+ }
67
+ }
68
+ function htmlFilesUnder(dir) {
69
+ const out = [];
70
+ for (const entry of readdirSync(dir, {
71
+ recursive: true,
72
+ encoding: "utf8"
73
+ })) if (entry.endsWith(".html")) out.push(join(dir, entry));
74
+ return out;
75
+ }
76
+ const PLUGIN_LABEL = "@afterpack/angular";
77
+ function planNgswHashTable(browserDir, label, planned) {
78
+ const ngsw = join(browserDir, "ngsw.json");
79
+ if (!existsSync(ngsw)) return;
80
+ const config = JSON.parse(readFileSync(ngsw, "utf8"));
81
+ const table = config.hashTable;
82
+ if (!table) return;
83
+ for (const url of Object.keys(table)) {
84
+ const file = join(browserDir, url.replace(/^\//, ""));
85
+ if (!existsSync(file) || !statSync(file).isFile()) throw new Error(`${label}: ngsw.json names ${url}, which is not in the browser output after obfuscation. AfterPack cannot recompute the service worker hash table. Rebuild, or disable the service worker for this build.`);
86
+ table[url] = digest(planned.get(file) ?? readFileSync(file), "sha1", "hex");
87
+ }
88
+ planned.set(ngsw, `${JSON.stringify(config, null, 2)}\n`);
89
+ }
90
+ function planAngularIntegrity(outputRoot, browserDir, label = PLUGIN_LABEL) {
91
+ const refusal = angularServerManifestRefusal(outputRoot);
92
+ if (refusal !== null) throw new Error(`${label}: ${refusal} — obfuscate only the browser output, or remove @afterpack/angular from the SSR build.`);
93
+ const planned = new Map();
94
+ planHtmlIntegrity(browserDir, planned);
95
+ planNgswHashTable(browserDir, label, planned);
96
+ return planned;
97
+ }
98
+ function recomputeAngularIntegrity(outputRoot, browserDir, label = PLUGIN_LABEL) {
99
+ for (const [path, text] of planAngularIntegrity(outputRoot, browserDir, label)) writeFileAtomic(path, text);
100
+ }
101
+ function angularServerManifestRefusal(outputRoot) {
102
+ const serverDir = join(outputRoot, "server");
103
+ if (!existsSync(serverDir)) return null;
104
+ for (const entry of readdirSync(serverDir)) {
105
+ if (!/angular-app-(?:engine-)?manifest\.mjs$/.test(entry)) continue;
106
+ const text = readFileSync(join(serverDir, entry), "utf8");
107
+ if (/\bhash\s*:\s*['"`]/.test(text) || /\bintegrity\s*:/.test(text)) return `${entry} embeds asset hashes that AfterPack cannot recompute after renaming and obfuscating the browser output, so the SSR ETags would be stale. This Angular server build is not supported`;
108
+ }
109
+ return null;
110
+ }
111
+
112
+ //#endregion
113
+ //#region src/home.ts
114
+ const AFTERPACK_DIR = ".afterpack";
115
+ const STRONG_MARKERS = [
116
+ "afterpack.json",
117
+ ".git",
118
+ "package-lock.json",
119
+ "npm-shrinkwrap.json",
120
+ "pnpm-lock.yaml",
121
+ "yarn.lock",
122
+ "bun.lock",
123
+ "bun.lockb"
124
+ ];
125
+ const WEAK_MARKERS = ["package.json"];
126
+ const DIAG_AFTERPACK_DIR_IN_OUTPUT = "DIAG_AFTERPACK_DIR_IN_OUTPUT";
127
+ const DIAG_RECEIPT_UNWRITABLE = "DIAG_RECEIPT_UNWRITABLE";
128
+ var AfterpackFilesError = class extends Error {
129
+ code;
130
+ summary;
131
+ fix;
132
+ constructor(code, summary, fix) {
133
+ super(`${summary} ${fix}`);
134
+ this.name = "AfterpackFilesError";
135
+ this.code = code;
136
+ this.summary = summary;
137
+ this.fix = fix;
138
+ }
139
+ };
140
+ function realPath(path) {
141
+ const resolved = resolve(path);
142
+ try {
143
+ return realpathSync.native(resolved);
144
+ } catch {
145
+ const parent = dirname(resolved);
146
+ return parent === resolved ? resolved : join(realPath(parent), basename(resolved));
147
+ }
148
+ }
149
+ function isWithinDir(dir, path) {
150
+ const rel = relative(dir, path);
151
+ return rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
152
+ }
153
+ function markerIn(dir, markers) {
154
+ return markers.find((name) => existsSync(join(dir, name))) ?? null;
155
+ }
156
+ function nearestMarker(start, markers) {
157
+ for (let current = start;;) {
158
+ const marker = markerIn(current, markers);
159
+ if (marker) return {
160
+ root: current,
161
+ marker
162
+ };
163
+ const parent = dirname(current);
164
+ if (parent === current) return null;
165
+ current = parent;
166
+ }
167
+ }
168
+ function afterpackHome(buildDir, options = {}) {
169
+ const realBuildDir = realPath(buildDir);
170
+ const ownMarker = options.fileTarget ? markerIn(realBuildDir, STRONG_MARKERS) : null;
171
+ if (ownMarker !== null) return {
172
+ dir: join(realBuildDir, AFTERPACK_DIR),
173
+ projectRoot: realBuildDir,
174
+ marker: ownMarker,
175
+ strong: true,
176
+ buildDir: realBuildDir
177
+ };
178
+ const start = dirname(realBuildDir);
179
+ const strong = nearestMarker(start, STRONG_MARKERS);
180
+ const found = strong ?? nearestMarker(start, WEAK_MARKERS);
181
+ const projectRoot = found?.root ?? start;
182
+ const dir = join(projectRoot, AFTERPACK_DIR);
183
+ if (isWithinDir(realBuildDir, dir)) throw new AfterpackFilesError(DIAG_AFTERPACK_DIR_IN_OUTPUT, `AfterPack would keep its files in ${dir}, inside the build output ${realBuildDir}, where they would ship.`, "Point AfterPack at a build directory below your project root.");
184
+ return {
185
+ dir,
186
+ projectRoot,
187
+ marker: found?.marker ?? null,
188
+ strong: strong !== null,
189
+ buildDir: realBuildDir
190
+ };
191
+ }
192
+ function describeUnanchoredHome(home) {
193
+ if (home.marker !== null) return null;
194
+ return `no lockfile, afterpack.json, .git or package.json above ${home.buildDir}, so AfterPack keeps its files beside it, in ${home.dir}`;
195
+ }
196
+
197
+ //#endregion
12
198
  //#region src/paths.ts
13
199
  const COMBINED_PROTECTION_MAP_NAME = "protectionMap.html";
14
200
  function shortHash(content) {
@@ -40,7 +226,6 @@ function findUpward(startDir, fileName, options = {}) {
40
226
 
41
227
  //#endregion
42
228
  //#region src/artifacts.ts
43
- const AFTERPACK_DIR = ".afterpack";
44
229
  const AFTERPACK_GITIGNORE_CONTENT = "*\n";
45
230
  const PUBLIC_SEGMENTS = new Set([
46
231
  "public",
@@ -63,35 +248,55 @@ function appendSourceMappingURL(code, mapPath) {
63
248
  const needsNewline = code.length > 0 && !code.endsWith("\n");
64
249
  return `${code}${needsNewline ? "\n" : ""}${comment}\n`;
65
250
  }
66
- function writeArtifacts(input) {
67
- const { outPath, code, sourceMapJson, protectionMapJson, originalSource, policy } = input;
68
- const mode = input.mode ?? "single";
69
- const afterpackDir = input.afterpackDir ?? AFTERPACK_DIR;
70
- const logger = input.logger ?? DEFAULT_LOGGER;
251
+ function planArtifactWrites(input) {
252
+ const { outPath, code, sourceMapJson, originalSource, policy } = input;
71
253
  const hash = policy.backup && originalSource != null ? shortHash(originalSource) : void 0;
72
- const paths = resolveArtifactPaths(outPath, mode, hash);
73
- const result = {
254
+ const paths = resolveArtifactPaths(outPath, input.mode ?? "single", hash);
255
+ const plan = {
74
256
  codePath: outPath,
75
257
  mapPath: null,
76
258
  backupPath: null,
77
- protectionMapPath: null,
78
- wroteSourceMappingURL: false
259
+ wroteSourceMappingURL: false,
260
+ writes: []
79
261
  };
80
262
  if (policy.backup && originalSource != null && paths.backupPath != null) {
81
- writeFileSync(paths.backupPath, originalSource);
82
- result.backupPath = paths.backupPath;
263
+ plan.writes.push({
264
+ path: paths.backupPath,
265
+ content: originalSource
266
+ });
267
+ plan.backupPath = paths.backupPath;
83
268
  }
84
269
  const willWriteMap = policy.sourceMap && sourceMapJson != null;
85
270
  let finalCode = code;
86
271
  if (willWriteMap && policy.emitSourceMappingURL) {
87
272
  finalCode = appendSourceMappingURL(code, paths.mapPath);
88
- result.wroteSourceMappingURL = true;
273
+ plan.wroteSourceMappingURL = true;
89
274
  }
90
- writeFileSync(outPath, finalCode);
275
+ plan.writes.push({
276
+ path: outPath,
277
+ content: finalCode
278
+ });
91
279
  if (willWriteMap && sourceMapJson != null) {
92
- writeFileSync(paths.mapPath, sourceMapJson);
93
- result.mapPath = paths.mapPath;
280
+ plan.writes.push({
281
+ path: paths.mapPath,
282
+ content: sourceMapJson
283
+ });
284
+ plan.mapPath = paths.mapPath;
94
285
  }
286
+ return plan;
287
+ }
288
+ function writeArtifacts(input) {
289
+ const { protectionMapJson, policy } = input;
290
+ const mode = input.mode ?? "single";
291
+ const afterpackDir = input.afterpackDir;
292
+ const logger = input.logger ?? DEFAULT_LOGGER;
293
+ const paths = resolveArtifactPaths(input.outPath, mode);
294
+ const { writes,...planned } = planArtifactWrites(input);
295
+ for (const write of writes) writeFileAtomic(write.path, write.content);
296
+ const result = {
297
+ ...planned,
298
+ protectionMapPath: null
299
+ };
95
300
  if (mode === "single" && policy.protectionMap && protectionMapJson != null) {
96
301
  mkdirSync(afterpackDir, { recursive: true });
97
302
  ensureAfterpackGitignore(afterpackDir);
@@ -424,7 +629,7 @@ function buildProjectFileTree(files) {
424
629
  }
425
630
  function writeCombinedProtectionMap(input) {
426
631
  const { buildDir, docs, policy } = input;
427
- const afterpackDir = input.afterpackDir ?? AFTERPACK_DIR;
632
+ const afterpackDir = input.afterpackDir;
428
633
  const logger = input.logger ?? DEFAULT_LOGGER;
429
634
  if (!policy.protectionMap || docs.length === 0) return null;
430
635
  mkdirSync(afterpackDir, { recursive: true });
@@ -702,7 +907,7 @@ const CONFIG_KEYS = [
702
907
  tier: "free",
703
908
  surface: "engine",
704
909
  item: { kind: "boolean" },
705
- default: "true in development when an input map exists; false in production"
910
+ default: "false; true in development mode when an input map exists"
706
911
  },
707
912
  {
708
913
  path: "sourceMap.sourcesContent",
@@ -711,7 +916,7 @@ const CONFIG_KEYS = [
711
916
  tier: "free",
712
917
  surface: "engine",
713
918
  item: { kind: "boolean" },
714
- default: "true in development; false in production"
919
+ default: "false; true in development mode"
715
920
  },
716
921
  {
717
922
  path: "sourceMap.emitUrl",
@@ -720,7 +925,7 @@ const CONFIG_KEYS = [
720
925
  tier: "free",
721
926
  surface: "build",
722
927
  item: { kind: "boolean" },
723
- default: "true in development; false in production"
928
+ default: "false; true in development mode"
724
929
  },
725
930
  {
726
931
  path: "protectionMap.enabled",
@@ -859,7 +1064,7 @@ const CONFIG_KEYS = [
859
1064
  kind: "enum",
860
1065
  values: BUILD_MODE_VALUES
861
1066
  },
862
- default: "detected from the environment"
1067
+ default: "production, unless NODE_ENV is development"
863
1068
  },
864
1069
  {
865
1070
  path: "directives.enabled",
@@ -980,8 +1185,8 @@ function unknownKeyMessage(path, surface) {
980
1185
  if (group$1 && group$1.length > 0) {
981
1186
  const list = group$1.map((child) => `\`${child}\``).join(", ");
982
1187
  const tail$1 = group$1.length === 1 ? `did you mean ${list}?` : `its keys are ${list}`;
983
- const canonical = PREFIX_BY_NORMALIZED.get(normalizeKey(path));
984
- const enabled = canonical ? groupBooleanKey(canonical) : void 0;
1188
+ const canonical$1 = PREFIX_BY_NORMALIZED.get(normalizeKey(path));
1189
+ const enabled = canonical$1 ? groupBooleanKey(canonical$1) : void 0;
985
1190
  const rule = enabled ? `; a boolean here means \`${enabled.path}\`` : "";
986
1191
  return `\`${path}\` is a group of configuration keys, not a key itself (${surface}) — ${tail$1}${rule}`;
987
1192
  }
@@ -1315,6 +1520,15 @@ function decodeDataUri(url) {
1315
1520
  return null;
1316
1521
  }
1317
1522
  }
1523
+ function localSourceMapPath(jsPath, url) {
1524
+ if (url.startsWith("data:") || isRemoteSourceMappingURL(url)) return null;
1525
+ const path = url.replace(/[?#].*$/, "");
1526
+ try {
1527
+ return isAbsolute(path) ? path : resolve(dirname(jsPath), decodeURIComponent(path));
1528
+ } catch {
1529
+ return null;
1530
+ }
1531
+ }
1318
1532
  function discoverInputSourceMap(jsPath, code) {
1319
1533
  const adjacent = `${jsPath}.map`;
1320
1534
  if (existsSync(adjacent)) try {
@@ -1329,20 +1543,81 @@ function discoverInputSourceMap(jsPath, code) {
1329
1543
  const url = extractSourceMappingURL(source);
1330
1544
  if (url == null) return null;
1331
1545
  if (url.startsWith("data:")) return decodeDataUri(url);
1332
- if (isRemoteSourceMappingURL(url)) return null;
1333
- let mapPath;
1546
+ const mapPath = localSourceMapPath(jsPath, url);
1547
+ if (mapPath == null || !existsSync(mapPath)) return null;
1334
1548
  try {
1335
- mapPath = isAbsolute(url) ? url : resolve(dirname(jsPath), decodeURIComponent(url));
1549
+ return readFileSync(mapPath, "utf8");
1336
1550
  } catch {
1337
1551
  return null;
1338
1552
  }
1339
- if (!existsSync(mapPath)) return null;
1553
+ }
1554
+ function bundlerSourceMapPaths(jsPath, code, root) {
1555
+ const candidates = [`${jsPath}.map`];
1556
+ for (const match of code.matchAll(SOURCE_MAPPING_URL_RE)) {
1557
+ const url = match[1];
1558
+ const local = localSourceMapPath(jsPath, url);
1559
+ if (local != null) candidates.push(local);
1560
+ if (url.startsWith("/") && !url.startsWith("//")) try {
1561
+ candidates.push(resolve(root, `.${decodeURIComponent(url.replace(/[?#].*$/, ""))}`));
1562
+ } catch {}
1563
+ }
1564
+ return containedSourceMaps(candidates, root);
1565
+ }
1566
+ function realpathOrNull(path) {
1340
1567
  try {
1341
- return readFileSync(mapPath, "utf8");
1568
+ return realpathSync(path);
1342
1569
  } catch {
1343
1570
  return null;
1344
1571
  }
1345
1572
  }
1573
+ function withinRealDir(dir, root) {
1574
+ const rootReal = realpathOrNull(root);
1575
+ const real = realpathOrNull(dir);
1576
+ if (rootReal == null || real == null) return false;
1577
+ if (real === rootReal) return true;
1578
+ return real.startsWith(rootReal.endsWith(sep) ? rootReal : `${rootReal}${sep}`);
1579
+ }
1580
+ function containedSourceMaps(paths, root) {
1581
+ const found = new Set();
1582
+ for (const path of paths) {
1583
+ if (!path.endsWith(".map")) continue;
1584
+ const lexical = resolve(path);
1585
+ if (!withinRealDir(dirname(lexical), root)) continue;
1586
+ try {
1587
+ const stat = lstatSync(lexical);
1588
+ if (stat.isFile() || stat.isSymbolicLink()) found.add(lexical);
1589
+ } catch {}
1590
+ }
1591
+ return [...found];
1592
+ }
1593
+ function removeSourceMaps(paths, label) {
1594
+ let removed = 0;
1595
+ for (const path of paths) try {
1596
+ unlinkSync(path);
1597
+ removed++;
1598
+ } catch (error) {
1599
+ if (error.code === "ENOENT") continue;
1600
+ throw new Error(`[${label}] could not remove the source map ${path}, refusing to ship it: ${error}`);
1601
+ }
1602
+ return removed;
1603
+ }
1604
+ function stripCssSourceMappingURLs(paths) {
1605
+ let stripped = 0;
1606
+ for (const path of paths) {
1607
+ let css;
1608
+ try {
1609
+ css = readFileSync(path, "utf8");
1610
+ } catch (error) {
1611
+ if (error.code === "ENOENT") continue;
1612
+ throw error;
1613
+ }
1614
+ const without = withoutCssSourceMappingURL(css);
1615
+ if (without === css) continue;
1616
+ writeFileAtomic(path, without);
1617
+ stripped++;
1618
+ }
1619
+ return stripped;
1620
+ }
1346
1621
 
1347
1622
  //#endregion
1348
1623
  //#region src/bundle.ts
@@ -1374,6 +1649,39 @@ function sourceTypeForBundle(format, entries) {
1374
1649
  for (const entry of entries) if (entry.type !== "chunk") return void 0;
1375
1650
  return sourceTypeForOutputFormat(format);
1376
1651
  }
1652
+ const COMPRESSED_SIBLING = /\.(gz|br|zst|zz|deflate)$/;
1653
+ function entryBytes(entry) {
1654
+ if (entry.type === "chunk") return entry.code === void 0 ? null : Buffer.from(entry.code);
1655
+ if (typeof entry.source === "string") return Buffer.from(entry.source);
1656
+ if (entry.source !== void 0) return Buffer.from(entry.source);
1657
+ return null;
1658
+ }
1659
+ function regenerateCompressedSiblings(bundle, obfuscated, label) {
1660
+ for (const [name, entry] of Object.entries(bundle)) {
1661
+ const match = COMPRESSED_SIBLING.exec(name);
1662
+ if (match === null) continue;
1663
+ const base = name.slice(0, -match[0].length);
1664
+ if (!obfuscated.has(base)) continue;
1665
+ const bytes = entryBytes(bundle[base]);
1666
+ if (bytes === null) continue;
1667
+ if (match[1] === "gz") entry.source = gzipSync(bytes);
1668
+ else if (match[1] === "br") entry.source = brotliCompressSync(bytes);
1669
+ else throw new Error(`[${label}] ${name} is a ${match[1]} copy of the obfuscated ${base}, but AfterPack can only regenerate .gz and .br. The precompressed file would hold the plain bytes. Drop the ${match[1]} compressor, or move it after AfterPack.`);
1670
+ }
1671
+ }
1672
+ const SRI_PLUGIN_NAME = /subresource|integrity|(?:^|[^a-z])sri(?:[^a-z]|$)/i;
1673
+ function sriPluginRefusal(plugins, label) {
1674
+ const found = (plugins ?? []).find((plugin) => SRI_PLUGIN_NAME.test(plugin?.name ?? ""));
1675
+ if (!found) return null;
1676
+ return `[${label}] the "${found.name}" plugin computes subresource integrity hashes, which AfterPack cannot support: unless it runs strictly after obfuscation, the integrity attributes pin the plain bytes and the browser blocks every script. AfterPack cannot see plugin ordering, so it refuses. Remove the SRI plugin, or compute integrity from the deployed files after the build.`;
1677
+ }
1678
+ function unsaltedAssetsWarning(entries, salted) {
1679
+ const fileNames = [];
1680
+ for (const entry of entries.values()) if (entry.type !== "chunk" && !salted.has(entry.fileName)) fileNames.push(entry.fileName);
1681
+ fileNames.sort();
1682
+ if (fileNames.length === 0) return null;
1683
+ return `${fileNames.length} JS file(s) reached the bundle as plain assets rather than chunks (${fileNames.join(", ")}); the bundler fixed their content-hashed names before obfuscation, so each keeps its name while its bytes change. Serve them without long-lived caching, or import them as modules so the bundler builds them as chunks.`;
1684
+ }
1377
1685
  function dataUri(json) {
1378
1686
  return `data:application/json;charset=utf-8;base64,${Buffer.from(json, "utf8").toString("base64")}`;
1379
1687
  }
@@ -1502,7 +1810,7 @@ function collectJsFiles(target, options = {}) {
1502
1810
  if (!stat.isDirectory()) return isCollectableJs(basename(target)) ? [target] : [];
1503
1811
  return walkJs(target, options.include ?? [], false, options.onNestedProject);
1504
1812
  }
1505
- function entriesOf(dir) {
1813
+ function entriesOf$1(dir) {
1506
1814
  try {
1507
1815
  return readdirSync(dir, { withFileTypes: true });
1508
1816
  } catch {
@@ -1521,12 +1829,13 @@ function isNestedProject(dir) {
1521
1829
  }
1522
1830
  function walkJs(dir, include, readmitted, onNestedProject) {
1523
1831
  const out = [];
1524
- for (const entry of entriesOf(dir)) {
1832
+ for (const entry of entriesOf$1(dir)) {
1525
1833
  const name = entry.name;
1526
1834
  const full = join(dir, name);
1527
1835
  const kind = kindOf(entry, full);
1528
1836
  if (kind === null) continue;
1529
1837
  if (kind === "dir") {
1838
+ if (name === AFTERPACK_DIR) continue;
1530
1839
  const skipped = name === NODE_MODULES;
1531
1840
  if (!skipped && !readmitted && isNestedProject(full)) {
1532
1841
  onNestedProject?.(full);
@@ -1545,13 +1854,15 @@ const SOURCE_MAP_RE = /\.(?:[cm]?js|css)\.map$/;
1545
1854
  function collectFiles(dir, accept) {
1546
1855
  if (!existsSync(dir)) return [];
1547
1856
  const out = [];
1548
- for (const entry of entriesOf(dir)) {
1857
+ for (const entry of entriesOf$1(dir)) {
1549
1858
  const name = entry.name;
1550
1859
  const full = join(dir, name);
1551
1860
  const kind = kindOf(entry, full);
1552
1861
  if (kind === null) continue;
1553
- if (kind === "dir") out.push(...collectFiles(full, accept));
1554
- else if (accept(name)) out.push(full);
1862
+ if (kind === "dir") {
1863
+ if (name === NODE_MODULES || name === AFTERPACK_DIR || isNestedProject(full)) continue;
1864
+ out.push(...collectFiles(full, accept));
1865
+ } else if (accept(name)) out.push(full);
1555
1866
  }
1556
1867
  return out;
1557
1868
  }
@@ -1700,6 +2011,7 @@ function reportNotices(raw, logger, prefix = (m) => m) {
1700
2011
  //#region src/compat.ts
1701
2012
  const MIN_CORE_VERSION = "0.2.0";
1702
2013
  const SOURCE_TYPE_MIN_CORE_VERSION = "0.2.3";
2014
+ const FILE_SOURCE_TYPE_MIN_CORE_VERSION = "0.2.5";
1703
2015
  const CORE_PACKAGE = "@afterpack/core";
1704
2016
  const VERSION_PATTERN$1 = /^\d{1,9}\.\d{1,9}\.\d{1,9}(?:[-+][0-9A-Za-z.+-]{1,64})?$/;
1705
2017
  const PACKAGE_NAME_PATTERN = /^(?:@[a-z0-9][a-z0-9._-]{0,63}\/)?[a-z0-9][a-z0-9._-]{0,63}$/;
@@ -1774,6 +2086,9 @@ function isBelowVersion(version, minimum) {
1774
2086
  function coreSupportsSourceType(coreVersion) {
1775
2087
  return releaseTriple(coreVersion) !== null && !isBelowVersion(coreVersion, SOURCE_TYPE_MIN_CORE_VERSION);
1776
2088
  }
2089
+ function coreSupportsFileSourceType(coreVersion) {
2090
+ return releaseTriple(coreVersion) !== null && !isBelowVersion(coreVersion, FILE_SOURCE_TYPE_MIN_CORE_VERSION);
2091
+ }
1777
2092
  const CLI_PACKAGE = "afterpack";
1778
2093
  function updateCommand(identity, minVersion) {
1779
2094
  const core = `${CORE_PACKAGE}@${safeVersionString(minVersion) ?? "latest"}`;
@@ -2058,10 +2373,10 @@ function spaceFormIssue(path, raw, surface) {
2058
2373
  }
2059
2374
  function kebabIssue(key, surface) {
2060
2375
  const suggestion = suggestKey(key);
2061
- const canonical = suggestion ? ` — the canonical form is \`${spellKey(suggestion, surface)}\`` : " — keys are dot-delimited camelCase";
2376
+ const canonical$1 = suggestion ? ` — the canonical form is \`${spellKey(suggestion, surface)}\`` : " — keys are dot-delimited camelCase";
2062
2377
  return {
2063
2378
  path: key,
2064
- message: `kebab-case is not a configuration key (\`${spellKey(key, surface)}\`)${canonical}`
2379
+ message: `kebab-case is not a configuration key (\`${spellKey(key, surface)}\`)${canonical$1}`
2065
2380
  };
2066
2381
  }
2067
2382
  function parseAssignment(key, raw, surface) {
@@ -2400,7 +2715,7 @@ function reportDiagnostics(input) {
2400
2715
  //#region src/policy.ts
2401
2716
  function detectProduction(env = {}, opts = {}) {
2402
2717
  if (opts.build?.mode !== void 0) return opts.build.mode === "production";
2403
- return env.NODE_ENV === "production" || env.CI === "true";
2718
+ return env.NODE_ENV !== "development";
2404
2719
  }
2405
2720
  function resolveReportPolicy(env = {}, userOpts = {}, signals = {}) {
2406
2721
  const isProduction = detectProduction(env, userOpts);
@@ -2967,120 +3282,985 @@ function captureDirectiveRegions(inputs, handAuthored, enabled = true) {
2967
3282
  }
2968
3283
 
2969
3284
  //#endregion
2970
- //#region src/git.ts
2971
- const GIT_COMMIT_SHA_PATTERN = /^[0-9a-f]{7,40}$/;
2972
- const GIT_REF_PATTERN = /^[A-Za-z0-9._\-/+]{1,200}$/;
2973
- function sanitizeCommitSha(value) {
2974
- if (typeof value !== "string") return null;
2975
- const sha = value.trim().toLowerCase();
2976
- return GIT_COMMIT_SHA_PATTERN.test(sha) ? sha : null;
2977
- }
2978
- function sanitizeGitRef(value) {
2979
- if (typeof value !== "string") return null;
2980
- const ref = value.trim();
2981
- return GIT_REF_PATTERN.test(ref) ? ref : null;
2982
- }
2983
- function contextFrom(rawSha, rawRef) {
2984
- const commitSha = sanitizeCommitSha(rawSha);
2985
- const ref = sanitizeGitRef(rawRef);
2986
- if (commitSha === null && ref === null) return null;
2987
- const context = {};
2988
- if (commitSha !== null) context.commitSha = commitSha;
2989
- if (ref !== null) context.ref = ref;
2990
- return context;
2991
- }
2992
- const CI_SOURCES = [
2993
- ["GITHUB_SHA", "GITHUB_REF_NAME"],
2994
- ["CI_COMMIT_SHA", "CI_COMMIT_REF_NAME"],
2995
- ["VERCEL_GIT_COMMIT_SHA", "VERCEL_GIT_COMMIT_REF"],
2996
- ["CF_PAGES_COMMIT_SHA", "CF_PAGES_BRANCH"],
2997
- ["GIT_COMMIT", "BRANCH_NAME"]
2998
- ];
2999
- function ciGitContext(env) {
3000
- for (const [shaVar, refVar] of CI_SOURCES) {
3001
- const context = contextFrom(env[shaVar], env[refVar]);
3002
- if (context !== null) return context;
3003
- }
3004
- return null;
3285
+ //#region src/seed.ts
3286
+ function randomSeed() {
3287
+ const b = randomBytes(8);
3288
+ const hi = b.readUInt32BE(0) & 2097151;
3289
+ const lo = b.readUInt32BE(4);
3290
+ return hi * 4294967296 + lo;
3005
3291
  }
3006
- const GIT_PROBE_TIMEOUT_MS = 2e3;
3007
- function localGitContext(cwd) {
3008
- let lines;
3292
+ function gitHead() {
3009
3293
  try {
3010
- const out = execFileSync("git", [
3011
- "rev-parse",
3012
- "HEAD",
3013
- "--abbrev-ref",
3014
- "HEAD"
3015
- ], {
3016
- cwd,
3017
- stdio: [
3018
- "ignore",
3019
- "pipe",
3020
- "ignore"
3021
- ],
3022
- timeout: GIT_PROBE_TIMEOUT_MS,
3023
- maxBuffer: 64 * 1024
3024
- }).toString();
3025
- lines = out.split("\n").map((line) => line.trim());
3294
+ const out = execFileSync("git", ["rev-parse", "HEAD"], { stdio: [
3295
+ "ignore",
3296
+ "pipe",
3297
+ "ignore"
3298
+ ] }).toString().trim();
3299
+ return /^[0-9a-f]{7,64}$/i.test(out) ? out : null;
3026
3300
  } catch {
3027
3301
  return null;
3028
3302
  }
3029
- const ref = lines[1] === "HEAD" ? null : lines[1];
3030
- return contextFrom(lines[0], ref);
3031
3303
  }
3032
- function detectGitContext(explicit, deps = {}) {
3033
- if (explicit) {
3034
- const declared = contextFrom(explicit.commitSha, explicit.ref);
3035
- if (declared !== null) return declared;
3036
- }
3037
- const ci = ciGitContext(deps.env ?? process.env);
3038
- if (ci !== null) return ci;
3039
- return (deps.localGit ?? localGitContext)(deps.cwd);
3304
+ const SEED_ENV_VAR = "AFTERPACK_SEED";
3305
+ function parseSeedValue(raw) {
3306
+ return /^-?\d+$/.test(raw) ? Number(raw) : raw;
3040
3307
  }
3041
-
3042
- //#endregion
3043
- //#region src/map-color.ts
3044
- const UTF8 = new TextEncoder();
3045
- const utf8Len = (s) => UTF8.encode(s).length;
3046
- const NON_ASCII = /[\u0080-\uFFFF]/;
3047
- const HIGH_SURROGATE_START = 55296;
3048
- const HIGH_SURROGATE_END = 56319;
3049
- const LOW_SURROGATE_START = 56320;
3050
- const LOW_SURROGATE_END = 57343;
3051
- function charToByteTable(line) {
3052
- const table = new Array(line.length + 1);
3053
- let bytes = 0;
3054
- let i = 0;
3055
- while (i < line.length) {
3056
- table[i] = bytes;
3057
- const code = line.charCodeAt(i);
3058
- if (code < 128) {
3059
- bytes += 1;
3060
- i += 1;
3061
- continue;
3062
- }
3063
- if (code < 2048) {
3064
- bytes += 2;
3065
- i += 1;
3066
- continue;
3067
- }
3068
- if (code >= HIGH_SURROGATE_START && code <= HIGH_SURROGATE_END && i + 1 < line.length) {
3069
- const low = line.charCodeAt(i + 1);
3070
- if (low >= LOW_SURROGATE_START && low <= LOW_SURROGATE_END) {
3071
- table[i + 1] = bytes + 3;
3072
- bytes += 4;
3073
- i += 2;
3074
- continue;
3075
- }
3076
- }
3077
- bytes += 3;
3078
- i += 1;
3308
+ const SEED_STATE = Symbol.for("afterpack.integration-utils.seed-sessions");
3309
+ function sharedSeedState() {
3310
+ const holder = globalThis;
3311
+ holder[SEED_STATE] ??= {
3312
+ sessions: new Map(),
3313
+ ownEnvExports: []
3314
+ };
3315
+ return holder[SEED_STATE];
3316
+ }
3317
+ const { sessions, ownEnvExports } = sharedSeedState();
3318
+ function isOwnEnvExport(env, value) {
3319
+ return ownEnvExports.some((e) => e.env === env && e.value === value);
3320
+ }
3321
+ function openGeneration(root, leg) {
3322
+ let session = sessions.get(root);
3323
+ if (!session) {
3324
+ session = {
3325
+ seed: void 0,
3326
+ generation: 1,
3327
+ legs: [],
3328
+ resolvedByLeg: new Map(),
3329
+ gitFallbackWarned: false
3330
+ };
3331
+ sessions.set(root, session);
3332
+ } else if (session.legs.includes(leg)) {
3333
+ session.seed = void 0;
3334
+ session.generation += 1;
3335
+ session.legs = [];
3336
+ session.resolvedByLeg.clear();
3337
+ session.gitFallbackWarned = false;
3079
3338
  }
3080
- table[line.length] = bytes;
3081
- return table;
3339
+ session.legs.push(leg);
3340
+ return session;
3082
3341
  }
3083
- var ChunkByteIndex = class {
3342
+ function resolveWithinSession(input, session, env, deps) {
3343
+ if (typeof input === "number") return {
3344
+ seed: input,
3345
+ origin: "option"
3346
+ };
3347
+ if (typeof input === "string" && input !== "git") return {
3348
+ seed: input,
3349
+ origin: "option"
3350
+ };
3351
+ if (input === "git") {
3352
+ const head = (deps.gitHead ?? gitHead)();
3353
+ if (head) return {
3354
+ seed: head,
3355
+ origin: "git"
3356
+ };
3357
+ if (!session.gitFallbackWarned) {
3358
+ session.gitFallbackWarned = true;
3359
+ (deps.warn ?? ((m) => console.warn(m)))("[afterpack] seed \"git\": no git repository / HEAD found; using a fresh random seed for this build.");
3360
+ }
3361
+ }
3362
+ const fromEnv = env[SEED_ENV_VAR];
3363
+ if (fromEnv != null && fromEnv !== "" && !isOwnEnvExport(env, fromEnv)) return {
3364
+ seed: parseSeedValue(fromEnv),
3365
+ origin: "env"
3366
+ };
3367
+ if (session.seed !== void 0) return {
3368
+ seed: session.seed,
3369
+ origin: "session"
3370
+ };
3371
+ return {
3372
+ seed: (deps.randomSeed ?? randomSeed)(),
3373
+ origin: "fresh"
3374
+ };
3375
+ }
3376
+ function resolveBuildSeed(input, scope, deps = {}) {
3377
+ const env = deps.env ?? process.env;
3378
+ const session = openGeneration(scope.root, scope.leg);
3379
+ const { seed, origin } = resolveWithinSession(input, session, env, deps);
3380
+ if (origin === "env" || origin === "fresh") session.seed = seed;
3381
+ if (origin === "fresh" && (deps.exportToEnv ?? true)) {
3382
+ const value = String(seed);
3383
+ env[SEED_ENV_VAR] = value;
3384
+ const stale = ownEnvExports.findIndex((e) => e.env === env);
3385
+ if (stale >= 0) ownEnvExports.splice(stale, 1);
3386
+ ownEnvExports.push({
3387
+ env,
3388
+ value
3389
+ });
3390
+ }
3391
+ const prior = [...session.resolvedByLeg].find(([, s]) => s !== seed);
3392
+ session.resolvedByLeg.set(scope.leg, seed);
3393
+ return {
3394
+ seed,
3395
+ origin,
3396
+ legs: [...session.legs],
3397
+ generation: session.generation,
3398
+ mismatch: prior && session.generation === 1 ? {
3399
+ leg: prior[0],
3400
+ seed: prior[1]
3401
+ } : null
3402
+ };
3403
+ }
3404
+
3405
+ //#endregion
3406
+ //#region src/telemetry.ts
3407
+ const API_URL_ENV_VAR$1 = "AFTERPACK_API_URL";
3408
+ const DEFAULT_API_URL = "https://api.afterpack.dev";
3409
+ const TELEMETRY_ENDPOINT_PATH = "/v1/telemetry/build";
3410
+ const TELEMETRY_PAYLOAD_VERSION = 1;
3411
+ const TELEMETRY_TIMEOUT_MS = 1500;
3412
+ const INSTALL_ID_ROTATION_DAYS = 30;
3413
+ const TELEMETRY_DIAGNOSTIC_LIMIT = 20;
3414
+ const TELEMETRY_STATE_FILE = join(homedir(), ".afterpack", "telemetry.json");
3415
+ const TOKEN_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
3416
+ const DATA_FIELD_WHITELIST = {
3417
+ outputUnparseable: ["parserErrorKind", "outputByteOffset"],
3418
+ parseError: ["parserErrorKind"],
3419
+ engineBug: [
3420
+ "phase",
3421
+ "transform",
3422
+ "nodeKind"
3423
+ ],
3424
+ inflationBudget: [
3425
+ "target",
3426
+ "achieved",
3427
+ "budgetRatio",
3428
+ "inflationRatio"
3429
+ ],
3430
+ configParse: [
3431
+ "category",
3432
+ "line",
3433
+ "column"
3434
+ ]
3435
+ };
3436
+ function resolveTelemetryEnabled(option, env = {}) {
3437
+ if (option !== void 0) return option;
3438
+ return !(env.NODE_ENV === "test" || env.VITEST);
3439
+ }
3440
+ const FRAMEWORK_ENTRIES = [
3441
+ {
3442
+ label: "afterpack",
3443
+ name: "cli"
3444
+ },
3445
+ {
3446
+ label: "afterpack-angular",
3447
+ name: "angular",
3448
+ pkg: "@angular/core"
3449
+ },
3450
+ {
3451
+ label: "afterpack-esbuild",
3452
+ name: "esbuild",
3453
+ pkg: "esbuild"
3454
+ },
3455
+ {
3456
+ label: "afterpack-next",
3457
+ name: "next",
3458
+ pkg: "next"
3459
+ },
3460
+ {
3461
+ label: "afterpack-rollup",
3462
+ name: "rollup",
3463
+ pkg: "rollup"
3464
+ },
3465
+ {
3466
+ label: "afterpack-vite",
3467
+ name: "vite",
3468
+ pkg: "vite"
3469
+ },
3470
+ {
3471
+ label: "afterpack-webpack",
3472
+ name: "webpack",
3473
+ pkg: "webpack"
3474
+ }
3475
+ ];
3476
+ const FRAMEWORK_BY_LABEL = new Map(FRAMEWORK_ENTRIES.map((e) => [e.label, e.name]));
3477
+ const FRAMEWORK_PACKAGE_BY_NAME = new Map(FRAMEWORK_ENTRIES.flatMap((e) => e.pkg ? [[e.name, e.pkg]] : []));
3478
+ function frameworkFromLabel(label) {
3479
+ return FRAMEWORK_BY_LABEL.get(label.split(":")[0]) ?? "unknown";
3480
+ }
3481
+ const VERSION_RANGE_PATTERN = /^[\sv0-9.\-+*xX^~><=|]{1,32}$/;
3482
+ function detectFrameworkVersion(projectRoot, framework) {
3483
+ const pkgName = FRAMEWORK_PACKAGE_BY_NAME.get(framework);
3484
+ if (!pkgName) return null;
3485
+ let deps;
3486
+ try {
3487
+ const pkg = JSON.parse(readFileSync(join(projectRoot, "package.json"), "utf8"));
3488
+ deps = {
3489
+ ...pkg.dependencies,
3490
+ ...pkg.devDependencies
3491
+ };
3492
+ } catch {
3493
+ return null;
3494
+ }
3495
+ const raw = deps[pkgName];
3496
+ if (typeof raw !== "string") return null;
3497
+ const range = raw.trim();
3498
+ return VERSION_RANGE_PATTERN.test(range) && /[0-9*xX]/.test(range) ? range : null;
3499
+ }
3500
+ function complexityLabel(preset, complexity) {
3501
+ if (preset !== void 0) return preset;
3502
+ return complexity === void 0 ? "default" : "custom";
3503
+ }
3504
+ const FILE_COUNT_BUCKETS = [
3505
+ 1,
3506
+ 5,
3507
+ 20,
3508
+ 100,
3509
+ 500,
3510
+ 2e3
3511
+ ];
3512
+ function fileCountBucket(count) {
3513
+ if (!Number.isFinite(count) || count <= 0) return "0";
3514
+ let lower = 1;
3515
+ for (const upper of FILE_COUNT_BUCKETS) {
3516
+ if (count <= upper) return lower === upper ? `${upper}` : `${lower}-${upper}`;
3517
+ lower = upper + 1;
3518
+ }
3519
+ return `${FILE_COUNT_BUCKETS[FILE_COUNT_BUCKETS.length - 1]}+`;
3520
+ }
3521
+ const DURATION_BUCKETS_MS = [
3522
+ [1e3, "<1s"],
3523
+ [5e3, "1-5s"],
3524
+ [15e3, "5-15s"],
3525
+ [6e4, "15-60s"],
3526
+ [3e5, "60-300s"]
3527
+ ];
3528
+ function durationBucket(ms) {
3529
+ if (!Number.isFinite(ms) || ms < 0) return "unknown";
3530
+ for (const [upper, label] of DURATION_BUCKETS_MS) if (ms < upper) return label;
3531
+ return "300s+";
3532
+ }
3533
+ function safeScalar(value) {
3534
+ if (typeof value === "number") return Number.isFinite(value) ? value : null;
3535
+ if (typeof value === "string") return TOKEN_PATTERN.test(value) ? value : null;
3536
+ return null;
3537
+ }
3538
+ function telemetrySafeData(data) {
3539
+ if (!data || typeof data.kind !== "string") return null;
3540
+ const kind = TOKEN_PATTERN.test(data.kind) ? data.kind : null;
3541
+ if (kind === null) return null;
3542
+ const out = { kind };
3543
+ for (const field of DATA_FIELD_WHITELIST[kind] ?? []) {
3544
+ const value = safeScalar(data[field]);
3545
+ if (value !== null) out[field] = value;
3546
+ }
3547
+ return out;
3548
+ }
3549
+ function telemetrySafeSpan(d) {
3550
+ const span = d.span;
3551
+ if (!span) return null;
3552
+ const start = safeScalar(span.startByte);
3553
+ const end = safeScalar(span.endByte);
3554
+ if (typeof start !== "number" || typeof end !== "number") return null;
3555
+ if (start < 0 || end < 0) return null;
3556
+ return {
3557
+ startByte: start,
3558
+ endByte: end
3559
+ };
3560
+ }
3561
+ function telemetrySafeDiagnostic(d, severity) {
3562
+ return {
3563
+ code: TOKEN_PATTERN.test(d.code) ? d.code : "DIAG_UNKNOWN",
3564
+ severity,
3565
+ span: telemetrySafeSpan(d),
3566
+ data: telemetrySafeData(d.data)
3567
+ };
3568
+ }
3569
+ function buildTelemetryPayload(facts, ctx) {
3570
+ let errorCount = 0;
3571
+ let criticalCount = 0;
3572
+ const alerting = [];
3573
+ for (const d of facts.diagnostics) {
3574
+ if (d.severity !== "error" && d.severity !== "critical") continue;
3575
+ if (d.severity === "critical") criticalCount += 1;
3576
+ else errorCount += 1;
3577
+ alerting.push(telemetrySafeDiagnostic(d, d.severity));
3578
+ }
3579
+ if (alerting.length === 0) return null;
3580
+ const kept = alerting.slice(-TELEMETRY_DIAGNOSTIC_LIMIT);
3581
+ const env = ctx.env ?? {};
3582
+ const runtime = ctx.runtime ?? {
3583
+ node: process.versions.node,
3584
+ platform: process.platform,
3585
+ arch: process.arch
3586
+ };
3587
+ const framework = frameworkFromLabel(facts.label);
3588
+ return {
3589
+ version: TELEMETRY_PAYLOAD_VERSION,
3590
+ installId: ctx.installId,
3591
+ framework,
3592
+ frameworkVersion: detectFrameworkVersion(facts.projectRoot, framework),
3593
+ engineVersion: safeVersion(facts.engineVersion),
3594
+ clientVersion: safeVersion(facts.clientVersion),
3595
+ nodeVersion: safeVersion(runtime.node) ?? "unknown",
3596
+ os: safeToken(runtime.platform),
3597
+ arch: safeToken(runtime.arch),
3598
+ ci: env.CI === "true",
3599
+ complexity: complexityLabel(facts.preset, facts.complexity),
3600
+ fileCountBucket: fileCountBucket(facts.fileCount),
3601
+ durationBucket: durationBucket(facts.durationMs),
3602
+ diagnostics: kept,
3603
+ errorCount,
3604
+ criticalCount,
3605
+ droppedCount: alerting.length - kept.length
3606
+ };
3607
+ }
3608
+ const VERSION_PATTERN = /^[0-9][0-9A-Za-z.\-+]{0,31}$/;
3609
+ function safeVersion(value) {
3610
+ return typeof value === "string" && VERSION_PATTERN.test(value) ? value : null;
3611
+ }
3612
+ function safeToken(value) {
3613
+ return TOKEN_PATTERN.test(value) ? value : "unknown";
3614
+ }
3615
+ const TELEMETRY_NOTICE = [
3616
+ "AfterPack: anonymous build diagnostics are ON (this notice prints once).",
3617
+ "AfterPack: A build that reports an error-level diagnostic (a refused or partial build)",
3618
+ "AfterPack: sends that diagnostic's code, severity, byte offsets and typed engine",
3619
+ "AfterPack: fields, plus engine version, integration, Node version, OS/arch, bucketed",
3620
+ "AfterPack: file counts and durations, and a random install id that rotates every 30",
3621
+ "AfterPack: days.",
3622
+ "AfterPack: It never sends your source, file names, paths, project name, diagnostic",
3623
+ "AfterPack: message text, or exact byte counts. A clean build sends nothing.",
3624
+ "AfterPack: Turn it off with AFTERPACK_telemetry_enabled=false, --telemetry.enabled=false, or",
3625
+ "AfterPack: `telemetry: { enabled: false }` in your config.",
3626
+ "AfterPack: https://www.afterpack.dev/privacy"
3627
+ ];
3628
+ const INSTALL_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
3629
+ const DAY_MS = 24 * 60 * 60 * 1e3;
3630
+ function readState(file, now) {
3631
+ try {
3632
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
3633
+ if (typeof parsed.installId === "string" && INSTALL_ID_PATTERN.test(parsed.installId) && typeof parsed.rotatedAt === "number") return {
3634
+ installId: parsed.installId,
3635
+ rotatedAt: parsed.rotatedAt,
3636
+ noticeShownAt: typeof parsed.noticeShownAt === "number" ? parsed.noticeShownAt : 0
3637
+ };
3638
+ } catch {}
3639
+ return {
3640
+ installId: randomUUID(),
3641
+ rotatedAt: now,
3642
+ noticeShownAt: 0
3643
+ };
3644
+ }
3645
+ function writeState(file, state) {
3646
+ try {
3647
+ mkdirSync(dirname(file), { recursive: true });
3648
+ writeFileSync(file, `${JSON.stringify(state)}\n`, "utf8");
3649
+ } catch {}
3650
+ }
3651
+ function telemetryUrl(env) {
3652
+ const base = (env[API_URL_ENV_VAR$1] ?? DEFAULT_API_URL).replace(/\/+$/, "");
3653
+ return `${base}${TELEMETRY_ENDPOINT_PATH}`;
3654
+ }
3655
+ const TELEMETRY_BODY_LIMIT = 64 * 1024;
3656
+ async function reportTelemetryNotices(response, logger) {
3657
+ if (!response || response.status !== 202 || typeof response.text !== "function") return;
3658
+ const declared = Number(response.headers?.get?.("content-length"));
3659
+ if (Number.isFinite(declared) && declared > TELEMETRY_BODY_LIMIT) {
3660
+ await response.body?.cancel().catch(() => {});
3661
+ return;
3662
+ }
3663
+ const text = await response.text();
3664
+ if (text.length > TELEMETRY_BODY_LIMIT) return;
3665
+ let body;
3666
+ try {
3667
+ body = JSON.parse(text);
3668
+ } catch {
3669
+ return;
3670
+ }
3671
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return;
3672
+ reportNotices(body.notices, logger);
3673
+ }
3674
+ function createTelemetryReporter(deps = {}) {
3675
+ const env = deps.env ?? process.env;
3676
+ const logger = deps.logger ?? console;
3677
+ const now = deps.now ?? Date.now;
3678
+ const stateFile = deps.stateFile ?? TELEMETRY_STATE_FILE;
3679
+ const timeoutMs = deps.timeoutMs ?? TELEMETRY_TIMEOUT_MS;
3680
+ return async (facts) => {
3681
+ try {
3682
+ const at = now();
3683
+ const state = readState(stateFile, at);
3684
+ let dirty = false;
3685
+ if (at - state.rotatedAt >= INSTALL_ID_ROTATION_DAYS * DAY_MS) {
3686
+ state.installId = randomUUID();
3687
+ state.rotatedAt = at;
3688
+ dirty = true;
3689
+ }
3690
+ if (state.noticeShownAt === 0) {
3691
+ for (const line of TELEMETRY_NOTICE) logger.log(line);
3692
+ state.noticeShownAt = at;
3693
+ dirty = true;
3694
+ }
3695
+ if (dirty) writeState(stateFile, state);
3696
+ if (facts === null) return;
3697
+ const payload = buildTelemetryPayload(facts, {
3698
+ installId: state.installId,
3699
+ env
3700
+ });
3701
+ if (payload === null) return;
3702
+ const fetchImpl = deps.fetchImpl ?? globalThis.fetch;
3703
+ if (typeof fetchImpl !== "function") return;
3704
+ const response = await fetchImpl(telemetryUrl(env), {
3705
+ method: "POST",
3706
+ headers: { "content-type": "application/json" },
3707
+ body: JSON.stringify(payload),
3708
+ signal: AbortSignal.timeout(timeoutMs)
3709
+ });
3710
+ await reportTelemetryNotices(response, logger);
3711
+ } catch {}
3712
+ };
3713
+ }
3714
+
3715
+ //#endregion
3716
+ //#region src/hash-salt.ts
3717
+ const API_URL_ENV_VAR = "AFTERPACK_API_URL";
3718
+ const VERSION_ENDPOINT_PATH = "/v1/version";
3719
+ const VERSION_PROBE_TIMEOUT_MS = 2e3;
3720
+ function canonical(value) {
3721
+ if (Array.isArray(value)) return value.map(canonical);
3722
+ if (value === null || typeof value !== "object") return value;
3723
+ const out = {};
3724
+ for (const key of Object.keys(value).sort()) {
3725
+ const item = value[key];
3726
+ if (item !== void 0) out[key] = canonical(item);
3727
+ }
3728
+ return out;
3729
+ }
3730
+ function afterpackHashSalt(input) {
3731
+ const payload = JSON.stringify(canonical({
3732
+ salt: "afterpack-output-name/1",
3733
+ seed: String(input.seed),
3734
+ engineVersion: input.engine.engineVersion,
3735
+ nonce: input.engine.nonce,
3736
+ cloud: input.engine.cloud,
3737
+ settings: input.settings
3738
+ }));
3739
+ return createHash("sha256").update(payload).digest("hex").slice(0, 32);
3740
+ }
3741
+ function isCloudBuild(env) {
3742
+ const key = env.AFTERPACK_KEY;
3743
+ return typeof key === "string" && key.trim() !== "";
3744
+ }
3745
+ function versionEndpoint(env) {
3746
+ const base = (env[API_URL_ENV_VAR] ?? DEFAULT_API_URL).replace(/\/+$/, "");
3747
+ return `${base}${VERSION_ENDPOINT_PATH}`;
3748
+ }
3749
+ async function resolveSaltEngine(env, localEngineVersion, deps = {}) {
3750
+ if (!isCloudBuild(env)) return {
3751
+ engineVersion: localEngineVersion,
3752
+ nonce: null,
3753
+ cloud: false,
3754
+ probedCloudVersion: null,
3755
+ probeFailed: false
3756
+ };
3757
+ const fetchImpl = deps.fetchImpl ?? globalThis.fetch;
3758
+ let probed = null;
3759
+ if (typeof fetchImpl === "function") try {
3760
+ const response = await fetchImpl(versionEndpoint(env), { signal: AbortSignal.timeout(deps.timeoutMs ?? VERSION_PROBE_TIMEOUT_MS) });
3761
+ if (response.ok) {
3762
+ const body = await response.json();
3763
+ if (typeof body.engineVersion === "string" && body.engineVersion !== "") probed = body.engineVersion;
3764
+ }
3765
+ } catch {
3766
+ probed = null;
3767
+ }
3768
+ if (probed === null) return {
3769
+ engineVersion: null,
3770
+ nonce: randomUUID(),
3771
+ cloud: true,
3772
+ probedCloudVersion: null,
3773
+ probeFailed: true
3774
+ };
3775
+ return {
3776
+ engineVersion: probed,
3777
+ nonce: null,
3778
+ cloud: true,
3779
+ probedCloudVersion: probed,
3780
+ probeFailed: false
3781
+ };
3782
+ }
3783
+ const PROBE_FAILED_WARNING = "could not read the cloud engine version from the API, so output file names carry a random nonce this build only. They are safe, but a pinned seed will not reproduce them. Re-run when the API is reachable to get stable names.";
3784
+ function saltSettings(settings, extra = {}) {
3785
+ const { seed: _seed, diagnostics: _diagnostics, artifactOptions, engineConfig,...rest } = settings;
3786
+ const { git: _git, telemetry: _telemetry,...output } = artifactOptions ?? {};
3787
+ const { seed: _engineSeed,...engine } = engineConfig ?? {};
3788
+ return {
3789
+ ...rest,
3790
+ engineConfig: engine,
3791
+ artifactOptions: output,
3792
+ ...extra
3793
+ };
3794
+ }
3795
+ function reportPolicySaltBits(env, artifactOptions, hasBundlerSourcemap) {
3796
+ const policy = resolveReportPolicy(env, artifactOptions ?? {}, { hasBundlerSourcemap });
3797
+ return {
3798
+ sourceMap: policy.sourceMap,
3799
+ emitSourceMappingURL: policy.emitSourceMappingURL
3800
+ };
3801
+ }
3802
+ async function prepareHashSalt(input) {
3803
+ const env = input.env ?? process.env;
3804
+ const resolvedSeed = resolveBuildSeed(input.seed, {
3805
+ root: input.root,
3806
+ leg: input.leg
3807
+ }, {
3808
+ env,
3809
+ warn: input.warn
3810
+ });
3811
+ const engine = await resolveSaltEngine(env, input.localEngineVersion, { fetchImpl: input.fetchImpl });
3812
+ if (engine.probeFailed) input.warn?.(PROBE_FAILED_WARNING);
3813
+ return {
3814
+ resolvedSeed,
3815
+ engine,
3816
+ salt: afterpackHashSalt({
3817
+ seed: resolvedSeed.seed,
3818
+ engine,
3819
+ settings: input.settings
3820
+ })
3821
+ };
3822
+ }
3823
+ async function readEngineVersion(engine) {
3824
+ try {
3825
+ return await engine.version?.() ?? null;
3826
+ } catch {
3827
+ return null;
3828
+ }
3829
+ }
3830
+ function cloudEngineMismatch(engine, batchEngineVersion) {
3831
+ if (!engine.cloud || engine.probedCloudVersion === null) return null;
3832
+ if (batchEngineVersion === null) return null;
3833
+ if (batchEngineVersion === engine.probedCloudVersion) return null;
3834
+ return `the cloud engine was version ${engine.probedCloudVersion} when output names were derived, but the build ran on ${batchEngineVersion}. Names would not match the bytes. This is a rare race during a service upgrade — re-run the build.`;
3835
+ }
3836
+
3837
+ //#endregion
3838
+ //#region src/hash-tokens.ts
3839
+ const NEXT_CHUNKS_PREFIX = "static/chunks/";
3840
+ const TURBOPACK_CHUNK_RE = /^(?:turbopack-)?([0-9a-z~._-]{13})\.(?:js|css)$/;
3841
+ const WEBPACK_CHUNK_RE = /[-.]([0-9a-f]{16})\.js$/;
3842
+ const ANGULAR_HASHED_NAME_RE = /-([A-Z0-9]{8})\.(?:js|mjs|css)$/;
3843
+ function detectNextBundler(distDir) {
3844
+ if (existsSync(join(distDir, "turbopack"))) return "turbopack";
3845
+ if (existsSync(join(distDir, "server", "webpack-runtime.js"))) return "webpack";
3846
+ return "unknown";
3847
+ }
3848
+ function nextChunkToken(bundler, chunksPrefix = NEXT_CHUNKS_PREFIX) {
3849
+ const pattern = bundler === "turbopack" ? TURBOPACK_CHUNK_RE : bundler === "webpack" ? WEBPACK_CHUNK_RE : null;
3850
+ return (relativePath) => {
3851
+ if (pattern === null || !relativePath.startsWith(chunksPrefix)) return null;
3852
+ return pattern.exec(basename(relativePath))?.[1] ?? null;
3853
+ };
3854
+ }
3855
+ function skipNextInternals(relativePath) {
3856
+ return relativePath === "cache" || relativePath.startsWith("trace");
3857
+ }
3858
+ const angularHashToken = (relativePath) => ANGULAR_HASHED_NAME_RE.exec(basename(relativePath))?.[1] ?? null;
3859
+
3860
+ //#endregion
3861
+ //#region src/hashed-names.ts
3862
+ const LOWER_HEX = "0123456789abcdef";
3863
+ const BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
3864
+ const UPPER_ALNUM = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
3865
+ const LOWER_ALNUM = "0123456789abcdefghijklmnopqrstuvwxyz";
3866
+ const ALNUM = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
3867
+ const MIN_TOKEN_LENGTH = 6;
3868
+ const BINARY_EXTENSIONS = new Set([
3869
+ ".png",
3870
+ ".jpg",
3871
+ ".jpeg",
3872
+ ".gif",
3873
+ ".webp",
3874
+ ".avif",
3875
+ ".ico",
3876
+ ".bmp",
3877
+ ".woff",
3878
+ ".woff2",
3879
+ ".ttf",
3880
+ ".otf",
3881
+ ".eot",
3882
+ ".wasm",
3883
+ ".gz",
3884
+ ".br",
3885
+ ".zst",
3886
+ ".zip",
3887
+ ".pdf",
3888
+ ".mp3",
3889
+ ".mp4",
3890
+ ".webm",
3891
+ ".ogg",
3892
+ ".wav",
3893
+ ".pack"
3894
+ ]);
3895
+ function alphabetOf(token) {
3896
+ if (/^[0-9a-f]+$/.test(token)) return LOWER_HEX;
3897
+ if (/^[A-Z2-7]+$/.test(token)) return BASE32;
3898
+ if (/^[0-9A-Z]+$/.test(token)) return UPPER_ALNUM;
3899
+ if (/^[0-9a-z~._-]+$/.test(token)) return LOWER_ALNUM;
3900
+ return ALNUM;
3901
+ }
3902
+ function inputKey(input = {}) {
3903
+ const regions = input.regions && input.regions.length > 0 ? JSON.stringify(input.regions) : "";
3904
+ return input.sourceType === void 0 ? regions : `${regions}\0${input.sourceType}`;
3905
+ }
3906
+ function deriveHashToken(token, salt, regions = "") {
3907
+ const alphabet = alphabetOf(token);
3908
+ let out = "";
3909
+ for (let round = 0; out.length < token.length; round++) {
3910
+ const bytes = createHash("sha256").update(`${salt}\0${token}\0${regions}\0${round}`).digest();
3911
+ for (const byte of bytes) {
3912
+ if (out.length === token.length) break;
3913
+ out += alphabet[byte % alphabet.length];
3914
+ }
3915
+ }
3916
+ return out;
3917
+ }
3918
+ function escapeRegExp$1(text) {
3919
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3920
+ }
3921
+ function tokenPattern(tokens) {
3922
+ const list = [...tokens].sort((a, b) => b.length - a.length || (a < b ? -1 : 1));
3923
+ if (list.length === 0) return null;
3924
+ return new RegExp(`(?<![A-Za-z0-9])(?:${list.map(escapeRegExp$1).join("|")})(?![A-Za-z0-9])`, "g");
3925
+ }
3926
+ function toPosix$1(path) {
3927
+ return sep === "/" ? path : path.split(sep).join("/");
3928
+ }
3929
+ function readText(path) {
3930
+ let bytes;
3931
+ try {
3932
+ bytes = readFileSync(path);
3933
+ } catch {
3934
+ return null;
3935
+ }
3936
+ if (bytes.subarray(0, 8192).includes(0)) return null;
3937
+ try {
3938
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
3939
+ } catch {
3940
+ return null;
3941
+ }
3942
+ }
3943
+ function listFiles(root, skip) {
3944
+ const out = [];
3945
+ const walk$1 = (dir) => {
3946
+ let entries;
3947
+ try {
3948
+ entries = readdirSync(dir, { withFileTypes: true });
3949
+ } catch {
3950
+ return;
3951
+ }
3952
+ for (const entry of entries) {
3953
+ const full = join(dir, entry.name);
3954
+ const rel = toPosix$1(relative(root, full));
3955
+ if (entry.name === AFTERPACK_DIR || entry.name === "node_modules" || skip(rel)) continue;
3956
+ if (entry.isDirectory()) walk$1(full);
3957
+ else if (entry.isFile()) out.push(full);
3958
+ }
3959
+ };
3960
+ walk$1(root);
3961
+ return out;
3962
+ }
3963
+ function isCandidate(path) {
3964
+ const name = basename(path).toLowerCase();
3965
+ if (name.endsWith(".map")) return false;
3966
+ const dot = name.lastIndexOf(".");
3967
+ return dot < 0 || !BINARY_EXTENSIONS.has(name.slice(dot));
3968
+ }
3969
+ function tokenAt(root, tokenOf, path) {
3970
+ const rel = toPosix$1(relative(root, path));
3971
+ if (rel.startsWith("..")) return null;
3972
+ const token = tokenOf(rel);
3973
+ if (token === null || token.length < MIN_TOKEN_LENGTH) return null;
3974
+ return basename(path).includes(token) ? token : null;
3975
+ }
3976
+ function unreferencedHashedFiles(options, files) {
3977
+ const owners = new Map();
3978
+ for (const file of files) {
3979
+ const token = tokenAt(options.root, options.tokenOf, file);
3980
+ if (token !== null) owners.set(token, (owners.get(token) ?? new Set()).add(file));
3981
+ }
3982
+ const pattern = tokenPattern(owners.keys());
3983
+ if (pattern === null) return [];
3984
+ const referenced = new Set();
3985
+ for (const path of listFiles(options.root, options.skip ?? (() => false))) {
3986
+ if (!isCandidate(path)) continue;
3987
+ const text = readText(path);
3988
+ if (text === null) continue;
3989
+ for (const [token] of text.matchAll(pattern)) for (const owner of owners.get(token) ?? []) if (owner !== path) referenced.add(owner);
3990
+ }
3991
+ return [...owners.values()].flatMap((set) => [...set]).filter((file) => !referenced.has(file)).sort();
3992
+ }
3993
+ const SCAN_SKIPPED_DIRS = new Set([
3994
+ "node_modules",
3995
+ ".git",
3996
+ AFTERPACK_DIR,
3997
+ ".cache",
3998
+ "cache"
3999
+ ]);
4000
+ function findHashTokenReference(paths, options, files, limits) {
4001
+ const tokens = files.map((file) => tokenAt(options.root, options.tokenOf, file)).filter((token) => token !== null);
4002
+ const pattern = tokenPattern(new Set(tokens));
4003
+ const result = {
4004
+ found: null,
4005
+ truncated: false
4006
+ };
4007
+ if (pattern === null) return result;
4008
+ let seenFiles = 0;
4009
+ let seenBytes = 0;
4010
+ const visit = (path, depth) => {
4011
+ if (result.found !== null || result.truncated || isWithinDir(options.root, path)) return;
4012
+ let stats;
4013
+ try {
4014
+ stats = statSync(path);
4015
+ } catch {
4016
+ return;
4017
+ }
4018
+ if (stats.isDirectory()) {
4019
+ if (SCAN_SKIPPED_DIRS.has(basename(path))) return;
4020
+ if (depth > limits.maxDepth) {
4021
+ result.truncated = true;
4022
+ return;
4023
+ }
4024
+ for (const entry of readdirSync(path).sort()) visit(join(path, entry), depth + 1);
4025
+ return;
4026
+ }
4027
+ if (!stats.isFile() || !isCandidate(path)) return;
4028
+ seenFiles += 1;
4029
+ seenBytes += stats.size;
4030
+ if (seenFiles > limits.maxFiles || seenBytes > limits.maxBytes) {
4031
+ result.truncated = true;
4032
+ return;
4033
+ }
4034
+ const text = readText(path);
4035
+ pattern.lastIndex = 0;
4036
+ if (text !== null && pattern.test(text)) result.found = path;
4037
+ };
4038
+ for (const path of paths) visit(path, 0);
4039
+ return result;
4040
+ }
4041
+ function writableDir(dir) {
4042
+ try {
4043
+ accessSync(dir, constants.W_OK);
4044
+ return true;
4045
+ } catch {
4046
+ return false;
4047
+ }
4048
+ }
4049
+ function planHashedNames(input) {
4050
+ const { root, tokenOf } = input.options;
4051
+ const skip = input.options.skip ?? (() => false);
4052
+ const tokens = new Map();
4053
+ const tokenOfPath = (path) => tokenAt(root, tokenOf, path);
4054
+ const addToken = (token, file) => {
4055
+ if (tokens.has(token)) return false;
4056
+ tokens.set(token, deriveHashToken(token, input.salt, inputKey(file)));
4057
+ return true;
4058
+ };
4059
+ for (const [path, file] of input.inputs) {
4060
+ const token = tokenOfPath(path);
4061
+ if (token !== null) addToken(token, file);
4062
+ }
4063
+ const others = new Map();
4064
+ if (tokens.size > 0) for (const path of listFiles(root, skip)) {
4065
+ if (input.inputs.has(path) || !isCandidate(path)) continue;
4066
+ const text = readText(path);
4067
+ if (text !== null) others.set(path, text);
4068
+ }
4069
+ const changed = new Set();
4070
+ let grew = tokens.size > 0;
4071
+ while (grew) {
4072
+ grew = false;
4073
+ const pattern$1 = tokenPattern(tokens.keys());
4074
+ if (pattern$1 === null) break;
4075
+ for (const [path, text] of others) {
4076
+ if (changed.has(path)) continue;
4077
+ pattern$1.lastIndex = 0;
4078
+ if (!pattern$1.test(text)) continue;
4079
+ changed.add(path);
4080
+ const token = tokenOfPath(path);
4081
+ if (token !== null && addToken(token)) grew = true;
4082
+ }
4083
+ }
4084
+ const pattern = tokenPattern(tokens.keys());
4085
+ const rewrite = (text) => pattern === null ? text : text.replace(pattern, (token) => tokens.get(token) ?? token);
4086
+ const renamedPath = (path) => {
4087
+ const token = tokenOfPath(path);
4088
+ if (token === null || !tokens.has(token)) return path;
4089
+ const name = basename(path);
4090
+ const at = name.lastIndexOf(token);
4091
+ return join(dirname(path), `${name.slice(0, at)}${tokens.get(token)}${name.slice(at + token.length)}`);
4092
+ };
4093
+ const renamed = new Map();
4094
+ for (const path of input.inputs.keys()) {
4095
+ const next = renamedPath(path);
4096
+ if (next !== path) renamed.set(path, next);
4097
+ }
4098
+ const writes = [];
4099
+ const rewrites = new Map();
4100
+ for (const path of changed) {
4101
+ const to = renamedPath(path);
4102
+ if (to !== path) renamed.set(path, to);
4103
+ const text = rewrite(others.get(path));
4104
+ rewrites.set(path, {
4105
+ to,
4106
+ text
4107
+ });
4108
+ writes.push({
4109
+ from: path,
4110
+ to,
4111
+ text
4112
+ });
4113
+ }
4114
+ const preflight = () => {
4115
+ const unwritable = new Set();
4116
+ for (const [from, to] of renamed) {
4117
+ if (!writableDir(dirname(from))) unwritable.add(dirname(from));
4118
+ if (!writableDir(dirname(to))) unwritable.add(dirname(to));
4119
+ }
4120
+ for (const write of writes) if (!writableDir(dirname(write.to))) unwritable.add(dirname(write.to));
4121
+ if (unwritable.size > 0) throw new Error(`cannot rename content-hashed files: these directories are not writable: ${[...unwritable].sort().join(", ")}`);
4122
+ };
4123
+ return {
4124
+ tokens,
4125
+ renamed,
4126
+ rewrites,
4127
+ rewrite,
4128
+ preflight,
4129
+ apply() {
4130
+ preflight();
4131
+ const staged = [];
4132
+ try {
4133
+ for (const write of writes) {
4134
+ writeFileSync(stagedPath(write.to), write.text);
4135
+ staged.push(stagedPath(write.to));
4136
+ }
4137
+ } catch (error) {
4138
+ for (const path of staged) rmSync(path, { force: true });
4139
+ throw error;
4140
+ }
4141
+ for (const write of writes) {
4142
+ renameSync(stagedPath(write.to), write.to);
4143
+ if (write.to !== write.from) rmSync(write.from, { force: true });
4144
+ }
4145
+ }
4146
+ };
4147
+ }
4148
+
4149
+ //#endregion
4150
+ //#region src/git.ts
4151
+ const GIT_COMMIT_SHA_PATTERN = /^[0-9a-f]{7,40}$/;
4152
+ const GIT_REF_PATTERN = /^[A-Za-z0-9._\-/+]{1,200}$/;
4153
+ function sanitizeCommitSha(value) {
4154
+ if (typeof value !== "string") return null;
4155
+ const sha = value.trim().toLowerCase();
4156
+ return GIT_COMMIT_SHA_PATTERN.test(sha) ? sha : null;
4157
+ }
4158
+ function sanitizeGitRef(value) {
4159
+ if (typeof value !== "string") return null;
4160
+ const ref = value.trim();
4161
+ return GIT_REF_PATTERN.test(ref) ? ref : null;
4162
+ }
4163
+ function contextFrom(rawSha, rawRef) {
4164
+ const commitSha = sanitizeCommitSha(rawSha);
4165
+ const ref = sanitizeGitRef(rawRef);
4166
+ if (commitSha === null && ref === null) return null;
4167
+ const context = {};
4168
+ if (commitSha !== null) context.commitSha = commitSha;
4169
+ if (ref !== null) context.ref = ref;
4170
+ return context;
4171
+ }
4172
+ const CI_SOURCES = [
4173
+ ["GITHUB_SHA", "GITHUB_REF_NAME"],
4174
+ ["CI_COMMIT_SHA", "CI_COMMIT_REF_NAME"],
4175
+ ["VERCEL_GIT_COMMIT_SHA", "VERCEL_GIT_COMMIT_REF"],
4176
+ ["CF_PAGES_COMMIT_SHA", "CF_PAGES_BRANCH"],
4177
+ ["GIT_COMMIT", "BRANCH_NAME"]
4178
+ ];
4179
+ function ciGitContext(env) {
4180
+ for (const [shaVar, refVar] of CI_SOURCES) {
4181
+ const context = contextFrom(env[shaVar], env[refVar]);
4182
+ if (context !== null) return context;
4183
+ }
4184
+ return null;
4185
+ }
4186
+ const GIT_PROBE_TIMEOUT_MS = 2e3;
4187
+ function localGitContext(cwd) {
4188
+ let lines;
4189
+ try {
4190
+ const out = execFileSync("git", [
4191
+ "rev-parse",
4192
+ "HEAD",
4193
+ "--abbrev-ref",
4194
+ "HEAD"
4195
+ ], {
4196
+ cwd,
4197
+ stdio: [
4198
+ "ignore",
4199
+ "pipe",
4200
+ "ignore"
4201
+ ],
4202
+ timeout: GIT_PROBE_TIMEOUT_MS,
4203
+ maxBuffer: 64 * 1024
4204
+ }).toString();
4205
+ lines = out.split("\n").map((line) => line.trim());
4206
+ } catch {
4207
+ return null;
4208
+ }
4209
+ const ref = lines[1] === "HEAD" ? null : lines[1];
4210
+ return contextFrom(lines[0], ref);
4211
+ }
4212
+ function detectGitContext(explicit, deps = {}) {
4213
+ if (explicit) {
4214
+ const declared = contextFrom(explicit.commitSha, explicit.ref);
4215
+ if (declared !== null) return declared;
4216
+ }
4217
+ const ci = ciGitContext(deps.env ?? process.env);
4218
+ if (ci !== null) return ci;
4219
+ return (deps.localGit ?? localGitContext)(deps.cwd);
4220
+ }
4221
+
4222
+ //#endregion
4223
+ //#region src/map-color.ts
4224
+ const UTF8 = new TextEncoder();
4225
+ const utf8Len = (s) => UTF8.encode(s).length;
4226
+ const NON_ASCII = /[\u0080-\uFFFF]/;
4227
+ const HIGH_SURROGATE_START = 55296;
4228
+ const HIGH_SURROGATE_END = 56319;
4229
+ const LOW_SURROGATE_START = 56320;
4230
+ const LOW_SURROGATE_END = 57343;
4231
+ function charToByteTable(line) {
4232
+ const table = new Array(line.length + 1);
4233
+ let bytes = 0;
4234
+ let i = 0;
4235
+ while (i < line.length) {
4236
+ table[i] = bytes;
4237
+ const code = line.charCodeAt(i);
4238
+ if (code < 128) {
4239
+ bytes += 1;
4240
+ i += 1;
4241
+ continue;
4242
+ }
4243
+ if (code < 2048) {
4244
+ bytes += 2;
4245
+ i += 1;
4246
+ continue;
4247
+ }
4248
+ if (code >= HIGH_SURROGATE_START && code <= HIGH_SURROGATE_END && i + 1 < line.length) {
4249
+ const low = line.charCodeAt(i + 1);
4250
+ if (low >= LOW_SURROGATE_START && low <= LOW_SURROGATE_END) {
4251
+ table[i + 1] = bytes + 3;
4252
+ bytes += 4;
4253
+ i += 2;
4254
+ continue;
4255
+ }
4256
+ }
4257
+ bytes += 3;
4258
+ i += 1;
4259
+ }
4260
+ table[line.length] = bytes;
4261
+ return table;
4262
+ }
4263
+ var ChunkByteIndex = class {
3084
4264
  starts;
3085
4265
  ascii;
3086
4266
  tables;
@@ -3236,16 +4416,107 @@ function coverGenerated(segments$1, start, end, index) {
3236
4416
 
3237
4417
  //#endregion
3238
4418
  //#region src/receipt.ts
3239
- const PROTECTION_RECEIPT_FILE = ".afterpack-protection.json";
4419
+ const PROTECTION_RECEIPTS_DIR = "receipts";
4420
+ const STALE_OUTPUT_RECEIPT_FILE = ".afterpack-protection.json";
3240
4421
  const PROTECTION_RECEIPT_SCHEMA = 1;
3241
4422
  function sha256OfBytes(bytes) {
3242
4423
  return createHash("sha256").update(bytes).digest("hex");
3243
4424
  }
3244
- function sha256Of(path) {
3245
- return sha256OfBytes(readFileSync(path));
4425
+ function sha256Of(path) {
4426
+ return sha256OfBytes(readFileSync(path));
4427
+ }
4428
+ function receiptPathOf(dir, file) {
4429
+ return relative(dir, file).split(sep).join("/");
4430
+ }
4431
+ const MAX_KEY_BYTES = 180;
4432
+ const HASHED_KEY_PREFIX_BYTES = 120;
4433
+ function buildDirOf(home) {
4434
+ const rel = relative(home.projectRoot, home.buildDir).split(sep).join("/");
4435
+ return rel === "" ? "." : rel;
4436
+ }
4437
+ function receiptKey(buildDir) {
4438
+ const encoded = encodeURIComponent(buildDir).replace(/\*/g, "%2A").replace(/~/g, "%7E");
4439
+ if (Buffer.byteLength(encoded) <= MAX_KEY_BYTES) return encoded;
4440
+ const prefix = encoded.slice(0, HASHED_KEY_PREFIX_BYTES).replace(/%[0-9A-F]?$/, "");
4441
+ const digest$1 = createHash("sha256").update(buildDir, "utf8").digest("hex").slice(0, 16);
4442
+ return `${prefix}~${digest$1}`;
4443
+ }
4444
+ function receiptsDirOf(home) {
4445
+ return join(home.dir, PROTECTION_RECEIPTS_DIR);
4446
+ }
4447
+ function receiptPathIn(home) {
4448
+ return join(receiptsDirOf(home), `${receiptKey(buildDirOf(home))}.json`);
4449
+ }
4450
+ function homeOf(target) {
4451
+ return typeof target === "string" ? afterpackHome(target) : target;
4452
+ }
4453
+ function buildDirKey(target) {
4454
+ return receiptKey(buildDirOf(homeOf(target)));
4455
+ }
4456
+ function protectionReceiptPath(target) {
4457
+ return receiptPathIn(homeOf(target));
4458
+ }
4459
+ function prepareProtectionReceipt(target, label) {
4460
+ const home = homeOf(target);
4461
+ const path = receiptPathIn(home);
4462
+ try {
4463
+ mkdirSync(dirname(path), { recursive: true });
4464
+ ensureAfterpackGitignore(home.dir);
4465
+ const existed = existsSync(path);
4466
+ closeSync(openSync(path, "a"));
4467
+ if (!existed) unlinkSync(path);
4468
+ } catch (error) {
4469
+ throw new AfterpackFilesError(DIAG_RECEIPT_UNWRITABLE, `[${label}] cannot write the protection receipt ${path}, so no file was rewritten: ${error}`, `Make ${dirname(path)} a writable directory, then build again.`);
4470
+ }
4471
+ return path;
4472
+ }
4473
+ function entriesOf(dir) {
4474
+ try {
4475
+ return readdirSync(dir, { withFileTypes: true });
4476
+ } catch {
4477
+ return [];
4478
+ }
4479
+ }
4480
+ function removeStaleReceipt(path, label) {
4481
+ try {
4482
+ unlinkSync(path);
4483
+ } catch (error) {
4484
+ if (error.code === "ENOENT") return;
4485
+ throw new Error(`[${label}] could not remove the stale protection receipt ${path}, refusing to ship it: ${error}`);
4486
+ }
4487
+ }
4488
+ function refuseShippedAfterpackDir(path, buildDir, label) {
4489
+ throw new AfterpackFilesError(DIAG_AFTERPACK_DIR_IN_OUTPUT, `[${label}] found ${path} inside the build output ${buildDir}. It holds AfterPack backups, receipts or Protection Maps, which must never ship.`, `Delete ${path}, then build again.`);
3246
4490
  }
3247
- function receiptPathOf(dir, file) {
3248
- return relative(dir, file).split(sep).join("/");
4491
+ function sweepDir(dir, context, recursive) {
4492
+ for (const entry of entriesOf(dir)) {
4493
+ const full = join(dir, entry.name);
4494
+ if (entry.name === STALE_OUTPUT_RECEIPT_FILE) removeStaleReceipt(full, context.label);
4495
+ else if (entry.isDirectory()) {
4496
+ if (entry.name === AFTERPACK_DIR) {
4497
+ if (context.ownHome !== null && realPath(full) === context.ownHome) continue;
4498
+ refuseShippedAfterpackDir(full, context.buildDir, context.label);
4499
+ }
4500
+ if (!recursive || entry.name === "node_modules") continue;
4501
+ sweepDir(full, context, true);
4502
+ }
4503
+ }
4504
+ }
4505
+ function sweepOutputTree(buildDir, walkedDir, label, ownHome = null) {
4506
+ const context = {
4507
+ buildDir,
4508
+ label,
4509
+ ownHome: ownHome?.strong ? realPath(ownHome.dir) : null
4510
+ };
4511
+ const walksBuildDir = walkedDir !== null && realPath(walkedDir) === realPath(buildDir);
4512
+ sweepDir(buildDir, context, walksBuildDir);
4513
+ if (walkedDir !== null && !walksBuildDir) sweepDir(walkedDir, context, true);
4514
+ }
4515
+ function keptEntries(path, replaced) {
4516
+ if (!existsSync(path)) return [];
4517
+ const previous = parseReceipt(path);
4518
+ if (previous.error !== void 0 || previous.receipt.schema !== PROTECTION_RECEIPT_SCHEMA) return [];
4519
+ return previous.receipt.files.filter((entry) => !replaced.has(entry.path));
3249
4520
  }
3250
4521
  function writeDeferredProtectionReceipt(deferred) {
3251
4522
  const survivingFiles = deferred.files.filter((file) => existsSync(file));
@@ -3266,13 +4537,22 @@ function writeProtectionReceipt(input) {
3266
4537
  seedOrigin: input.seedOrigin,
3267
4538
  bundler: input.bundler,
3268
4539
  buildId: input.buildId,
4540
+ buildDir: ".",
3269
4541
  files: input.files.map((file) => ({
3270
4542
  path: receiptPathOf(input.dir, file),
3271
4543
  sha256: sha256Of(file),
3272
4544
  transformed: transformed.has(file)
3273
4545
  })).sort((a, b) => a.path.localeCompare(b.path))
3274
4546
  };
3275
- const path = join(input.dir, PROTECTION_RECEIPT_FILE);
4547
+ const home = input.home ?? afterpackHome(input.dir);
4548
+ receipt.buildDir = buildDirOf(home);
4549
+ const path = receiptPathIn(home);
4550
+ if (input.merge) {
4551
+ const replaced = new Set(receipt.files.map((entry) => entry.path));
4552
+ receipt.files = [...keptEntries(path, replaced), ...receipt.files].sort((a, b) => a.path.localeCompare(b.path));
4553
+ }
4554
+ mkdirSync(dirname(path), { recursive: true });
4555
+ ensureAfterpackGitignore(home.dir);
3276
4556
  writeFileSync(path, `${JSON.stringify(receipt, null, 2)}\n`);
3277
4557
  return path;
3278
4558
  }
@@ -3320,8 +4600,7 @@ var UnreadableReceiptError = class extends Error {
3320
4600
  this.schema = schema;
3321
4601
  }
3322
4602
  };
3323
- function verifyProtectionReceipt(dir, expectedBuildId) {
3324
- const receiptPath = join(dir, PROTECTION_RECEIPT_FILE);
4603
+ function verifyProtectionReceipt(receiptPath, dir, expectedBuildId) {
3325
4604
  if (!existsSync(receiptPath)) return {
3326
4605
  receiptPath,
3327
4606
  receipt: null,
@@ -3353,152 +4632,93 @@ function verifyProtectionReceipt(dir, expectedBuildId) {
3353
4632
  problems
3354
4633
  };
3355
4634
  }
3356
- function findReceiptDir(startDir) {
3357
- const receiptPath = findUpward(startDir, PROTECTION_RECEIPT_FILE);
3358
- return receiptPath ? dirname(receiptPath) : null;
3359
- }
3360
- function detectAlreadyObfuscatedInputs(files, startDir, bytesByPath, prefix = (m) => m) {
3361
- const dir = findReceiptDir(startDir);
3362
- if (!dir) return null;
3363
- const receiptPath = join(dir, PROTECTION_RECEIPT_FILE);
3364
- const result = parseReceipt(receiptPath);
3365
- if (result.error !== void 0) {
3366
- const schema = result.newerSchema;
3367
- if (schema === null) return null;
3368
- 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);
3369
- }
3370
- const outputHashes = new Set(result.receipt.files.map((f) => f.sha256));
3371
- if (outputHashes.size === 0) return null;
3372
- const matches = files.filter((file) => {
3373
- const bytes = bytesByPath?.get(file);
3374
- if (bytes !== void 0) return outputHashes.has(sha256OfBytes(bytes));
3375
- return existsSync(file) && outputHashes.has(sha256Of(file));
3376
- });
3377
- return matches.length > 0 ? {
3378
- receiptPath,
3379
- files: matches
3380
- } : null;
3381
- }
3382
-
3383
- //#endregion
3384
- //#region src/seed.ts
3385
- function randomSeed() {
3386
- const b = randomBytes(8);
3387
- const hi = b.readUInt32BE(0) & 2097151;
3388
- const lo = b.readUInt32BE(4);
3389
- return hi * 4294967296 + lo;
3390
- }
3391
- function gitHead() {
3392
- try {
3393
- const out = execFileSync("git", ["rev-parse", "HEAD"], { stdio: [
3394
- "ignore",
3395
- "pipe",
3396
- "ignore"
3397
- ] }).toString().trim();
3398
- return /^[0-9a-f]{7,64}$/i.test(out) ? out : null;
3399
- } catch {
3400
- return null;
3401
- }
3402
- }
3403
- const SEED_ENV_VAR = "AFTERPACK_SEED";
3404
- function parseSeedValue(raw) {
3405
- return /^-?\d+$/.test(raw) ? Number(raw) : raw;
3406
- }
3407
- const SEED_STATE = Symbol.for("afterpack.integration-utils.seed-sessions");
3408
- function sharedSeedState() {
3409
- const holder = globalThis;
3410
- holder[SEED_STATE] ??= {
3411
- sessions: new Map(),
3412
- ownEnvExports: []
3413
- };
3414
- return holder[SEED_STATE];
3415
- }
3416
- const { sessions, ownEnvExports } = sharedSeedState();
3417
- function isOwnEnvExport(env, value) {
3418
- return ownEnvExports.some((e) => e.env === env && e.value === value);
3419
- }
3420
- function openGeneration(root, leg) {
3421
- let session = sessions.get(root);
3422
- if (!session) {
3423
- session = {
3424
- seed: void 0,
3425
- generation: 1,
3426
- legs: [],
3427
- resolvedByLeg: new Map(),
3428
- gitFallbackWarned: false
3429
- };
3430
- sessions.set(root, session);
3431
- } else if (session.legs.includes(leg)) {
3432
- session.seed = void 0;
3433
- session.generation += 1;
3434
- session.legs = [];
3435
- session.resolvedByLeg.clear();
3436
- session.gitFallbackWarned = false;
3437
- }
3438
- session.legs.push(leg);
3439
- return session;
3440
- }
3441
- function resolveWithinSession(input, session, env, deps) {
3442
- if (typeof input === "number") return {
3443
- seed: input,
3444
- origin: "option"
3445
- };
3446
- if (typeof input === "string" && input !== "git") return {
3447
- seed: input,
3448
- origin: "option"
4635
+ function receiptsIn(home) {
4636
+ const dir = receiptsDirOf(home);
4637
+ return entriesOf(dir).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => join(dir, entry.name)).sort();
4638
+ }
4639
+ function filesByName(dir) {
4640
+ const byName = new Map();
4641
+ const walk$1 = (current, rel) => {
4642
+ for (const entry of entriesOf(current)) {
4643
+ if (entry.name === "node_modules" || entry.name === AFTERPACK_DIR) continue;
4644
+ const childRel = rel === "" ? entry.name : `${rel}/${entry.name}`;
4645
+ if (entry.isDirectory()) walk$1(join(current, entry.name), childRel);
4646
+ else if (entry.isFile()) byName.set(entry.name, [...byName.get(entry.name) ?? [], childRel]);
4647
+ }
3449
4648
  };
3450
- if (input === "git") {
3451
- const head = (deps.gitHead ?? gitHead)();
3452
- if (head) return {
3453
- seed: head,
3454
- origin: "git"
3455
- };
3456
- if (!session.gitFallbackWarned) {
3457
- session.gitFallbackWarned = true;
3458
- (deps.warn ?? ((m) => console.warn(m)))("[afterpack] seed \"git\": no git repository / HEAD found; using a fresh random seed for this build.");
4649
+ walk$1(dir, "");
4650
+ return byName;
4651
+ }
4652
+ function copyMatches(dir, home, skip) {
4653
+ const receipts = receiptsIn(home).filter((path) => !skip.has(path));
4654
+ if (receipts.length === 0) return [];
4655
+ const byName = filesByName(dir);
4656
+ const matches = [];
4657
+ for (const receiptPath of receipts) {
4658
+ const parsed = parseReceipt(receiptPath);
4659
+ if (parsed.error !== void 0 || parsed.receipt.files.length === 0) continue;
4660
+ const { files, buildDir } = parsed.receipt;
4661
+ const first = files[0].path;
4662
+ for (const rel of byName.get(first.split("/").pop() ?? first) ?? []) {
4663
+ if (rel !== first && !rel.endsWith(`/${first}`)) continue;
4664
+ const prefix = rel.slice(0, rel.length - first.length);
4665
+ const copyDir = join(dir, ...prefix.split("/").filter(Boolean));
4666
+ if (!files.every((entry) => existsSync(join(copyDir, entry.path)))) continue;
4667
+ matches.push({
4668
+ receiptPath,
4669
+ dir: copyDir,
4670
+ copiedFrom: typeof buildDir === "string" ? join(home.projectRoot, buildDir) : null,
4671
+ hashesMatch: files.every((entry) => sha256Of(join(copyDir, entry.path)) === entry.sha256),
4672
+ prefix
4673
+ });
3459
4674
  }
3460
4675
  }
3461
- const fromEnv = env[SEED_ENV_VAR];
3462
- if (fromEnv != null && fromEnv !== "" && !isOwnEnvExport(env, fromEnv)) return {
3463
- seed: parseSeedValue(fromEnv),
3464
- origin: "env"
3465
- };
3466
- if (session.seed !== void 0) return {
3467
- seed: session.seed,
3468
- origin: "session"
3469
- };
3470
- return {
3471
- seed: (deps.randomSeed ?? randomSeed)(),
3472
- origin: "fresh"
4676
+ return matches.sort((a, b) => Number(b.hashesMatch) - Number(a.hashesMatch) || a.prefix.length - b.prefix.length || a.receiptPath.localeCompare(b.receiptPath));
4677
+ }
4678
+ function locateProtectionReceipt(dir, options = {}) {
4679
+ const homes = [afterpackHome(dir), afterpackHome(dir, { fileTarget: true })];
4680
+ const exact = [...new Set(homes.map(receiptPathIn))];
4681
+ const found = exact.find((path) => existsSync(path));
4682
+ if (found) return {
4683
+ receiptPath: found,
4684
+ dir,
4685
+ copiedFrom: null
3473
4686
  };
4687
+ if (options.copies === false) return null;
4688
+ const best = copyMatches(dir, homes[0], new Set(exact))[0];
4689
+ return best ? {
4690
+ receiptPath: best.receiptPath,
4691
+ dir: best.dir,
4692
+ copiedFrom: best.copiedFrom
4693
+ } : null;
3474
4694
  }
3475
- function resolveBuildSeed(input, scope, deps = {}) {
3476
- const env = deps.env ?? process.env;
3477
- const session = openGeneration(scope.root, scope.leg);
3478
- const { seed, origin } = resolveWithinSession(input, session, env, deps);
3479
- if (origin === "env" || origin === "fresh") session.seed = seed;
3480
- if (origin === "fresh" && (deps.exportToEnv ?? true)) {
3481
- const value = String(seed);
3482
- env[SEED_ENV_VAR] = value;
3483
- const stale = ownEnvExports.findIndex((e) => e.env === env);
3484
- if (stale >= 0) ownEnvExports.splice(stale, 1);
3485
- ownEnvExports.push({
3486
- env,
3487
- value
4695
+ function detectAlreadyObfuscatedInputs(files, startDir, bytesByPath, prefix = (m) => m) {
4696
+ const hashOf = (file) => {
4697
+ const bytes = bytesByPath?.get(file);
4698
+ if (bytes !== void 0) return sha256OfBytes(bytes);
4699
+ return existsSync(file) ? sha256Of(file) : null;
4700
+ };
4701
+ let hashes = null;
4702
+ for (const receiptPath of receiptsIn(homeOf(startDir))) {
4703
+ const result = parseReceipt(receiptPath);
4704
+ if (result.error !== void 0) {
4705
+ const schema = result.newerSchema;
4706
+ if (schema === null) continue;
4707
+ 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);
4708
+ }
4709
+ const outputHashes = new Set(result.receipt.files.filter((f) => f.transformed !== false).map((f) => f.sha256));
4710
+ if (outputHashes.size === 0) continue;
4711
+ hashes ??= new Map(files.map((file) => [file, hashOf(file)]));
4712
+ const matches = files.filter((file) => {
4713
+ const hash = hashes?.get(file);
4714
+ return hash != null && outputHashes.has(hash);
3488
4715
  });
4716
+ if (matches.length > 0) return {
4717
+ receiptPath,
4718
+ files: matches
4719
+ };
3489
4720
  }
3490
- const prior = [...session.resolvedByLeg].find(([, s]) => s !== seed);
3491
- session.resolvedByLeg.set(scope.leg, seed);
3492
- return {
3493
- seed,
3494
- origin,
3495
- legs: [...session.legs],
3496
- generation: session.generation,
3497
- mismatch: prior && session.generation === 1 ? {
3498
- leg: prior[0],
3499
- seed: prior[1]
3500
- } : null
3501
- };
4721
+ return null;
3502
4722
  }
3503
4723
 
3504
4724
  //#endregion
@@ -3519,312 +4739,493 @@ function formatPassSummary(input, style, colorGlyph = (glyph) => glyph) {
3519
4739
  }
3520
4740
 
3521
4741
  //#endregion
3522
- //#region src/telemetry.ts
3523
- const API_URL_ENV_VAR = "AFTERPACK_API_URL";
3524
- const DEFAULT_API_URL = "https://api.afterpack.dev";
3525
- const TELEMETRY_ENDPOINT_PATH = "/v1/telemetry/build";
3526
- const TELEMETRY_PAYLOAD_VERSION = 1;
3527
- const TELEMETRY_TIMEOUT_MS = 1500;
3528
- const INSTALL_ID_ROTATION_DAYS = 30;
3529
- const TELEMETRY_DIAGNOSTIC_LIMIT = 20;
3530
- const TELEMETRY_STATE_FILE = join(homedir(), ".afterpack", "telemetry.json");
3531
- const TOKEN_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
3532
- const DATA_FIELD_WHITELIST = {
3533
- outputUnparseable: ["parserErrorKind", "outputByteOffset"],
3534
- parseError: ["parserErrorKind"],
3535
- engineBug: [
3536
- "phase",
3537
- "transform",
3538
- "nodeKind"
3539
- ],
3540
- inflationBudget: [
3541
- "target",
3542
- "achieved",
3543
- "budgetRatio",
3544
- "inflationRatio"
3545
- ],
3546
- configParse: [
3547
- "category",
3548
- "line",
3549
- "column"
3550
- ]
4742
+ //#region src/wire.ts
4743
+ const EXTERNAL_WIRE_DIR = "_external";
4744
+ const DRIVE_PATH = /^[A-Za-z]:[\\/]/;
4745
+ const URL_SCHEME = /^[A-Za-z][A-Za-z0-9+.-]+:/;
4746
+ const FILE_URL = /^file:/i;
4747
+ const PATH_CHARS = "[^\\s\"'`|!?#()<>,;:*\\\\]";
4748
+ const EMBEDDED_PATH = new RegExp(`(^|[^A-Za-z0-9._~/\\\\-])((?:[A-Za-z]:[\\\\/]|/)(?:${PATH_CHARS}|\\\\(?!/))*)`, "g");
4749
+ const ESCAPED_PATH = new RegExp(`(^|[^A-Za-z0-9._~/\\\\-])((?:\\\\/${PATH_CHARS}+)+\\\\/?)`, "g");
4750
+ var WirePathError = class extends Error {
4751
+ constructor(message) {
4752
+ super(message);
4753
+ this.name = "WirePathError";
4754
+ }
3551
4755
  };
3552
- function resolveTelemetryEnabled(option, env = {}) {
3553
- if (option !== void 0) return option;
3554
- return !(env.NODE_ENV === "test" || env.VITEST);
4756
+ function toPosix(path) {
4757
+ return path.includes("\\") ? path.replaceAll("\\", "/") : path;
3555
4758
  }
3556
- const FRAMEWORK_ENTRIES = [
3557
- {
3558
- label: "afterpack",
3559
- name: "cli"
3560
- },
3561
- {
3562
- label: "afterpack-angular",
3563
- name: "angular",
3564
- pkg: "@angular/core"
3565
- },
3566
- {
3567
- label: "afterpack-esbuild",
3568
- name: "esbuild",
3569
- pkg: "esbuild"
3570
- },
3571
- {
3572
- label: "afterpack-next",
3573
- name: "next",
3574
- pkg: "next"
3575
- },
3576
- {
3577
- label: "afterpack-rollup",
3578
- name: "rollup",
3579
- pkg: "rollup"
3580
- },
3581
- {
3582
- label: "afterpack-vite",
3583
- name: "vite",
3584
- pkg: "vite"
3585
- },
3586
- {
3587
- label: "afterpack-webpack",
3588
- name: "webpack",
3589
- pkg: "webpack"
3590
- }
3591
- ];
3592
- const FRAMEWORK_BY_LABEL = new Map(FRAMEWORK_ENTRIES.map((e) => [e.label, e.name]));
3593
- const FRAMEWORK_PACKAGE_BY_NAME = new Map(FRAMEWORK_ENTRIES.flatMap((e) => e.pkg ? [[e.name, e.pkg]] : []));
3594
- function frameworkFromLabel(label) {
3595
- return FRAMEWORK_BY_LABEL.get(label.split(":")[0]) ?? "unknown";
4759
+ function lastSegment(path) {
4760
+ const parts = toPosix(path).split("/").filter((p) => p !== "");
4761
+ return parts[parts.length - 1] ?? "file";
3596
4762
  }
3597
- const VERSION_RANGE_PATTERN = /^[\sv0-9.\-+*xX^~><=|]{1,32}$/;
3598
- function detectFrameworkVersion(projectRoot, framework) {
3599
- const pkgName = FRAMEWORK_PACKAGE_BY_NAME.get(framework);
3600
- if (!pkgName) return null;
3601
- let deps;
4763
+ function isUnder(child, parent) {
4764
+ const rel = relative(parent, child);
4765
+ return rel === "" || !isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`);
4766
+ }
4767
+ function relativeWithin(file, baseDir) {
4768
+ const rel = relative(resolve(baseDir), resolve(file));
4769
+ if (rel === "" || isAbsolute(rel) || DRIVE_PATH.test(rel)) return null;
4770
+ if (rel === ".." || rel.startsWith(`..${sep}`)) return null;
4771
+ return toPosix(rel);
4772
+ }
4773
+ function osUsername() {
3602
4774
  try {
3603
- const pkg = JSON.parse(readFileSync(join(projectRoot, "package.json"), "utf8"));
3604
- deps = {
3605
- ...pkg.dependencies,
3606
- ...pkg.devDependencies
3607
- };
4775
+ return userInfo().username;
3608
4776
  } catch {
3609
4777
  return null;
3610
4778
  }
3611
- const raw = deps[pkgName];
3612
- if (typeof raw !== "string") return null;
3613
- const range = raw.trim();
3614
- return VERSION_RANGE_PATTERN.test(range) && /[0-9*xX]/.test(range) ? range : null;
3615
4779
  }
3616
- function complexityLabel(preset, complexity) {
3617
- if (preset !== void 0) return preset;
3618
- return complexity === void 0 ? "default" : "custom";
4780
+ function personalNames() {
4781
+ const names = new Set([basename(homedir())]);
4782
+ const user = osUsername();
4783
+ if (user) names.add(user);
4784
+ return names;
3619
4785
  }
3620
- const FILE_COUNT_BUCKETS = [
3621
- 1,
3622
- 5,
3623
- 20,
3624
- 100,
3625
- 500,
3626
- 2e3
3627
- ];
3628
- function fileCountBucket(count) {
3629
- if (!Number.isFinite(count) || count <= 0) return "0";
3630
- let lower = 1;
3631
- for (const upper of FILE_COUNT_BUCKETS) {
3632
- if (count <= upper) return lower === upper ? `${upper}` : `${lower}-${upper}`;
3633
- lower = upper + 1;
4786
+ function safeName(path) {
4787
+ const name = lastSegment(path);
4788
+ return personalNames().has(name) ? "file" : name;
4789
+ }
4790
+ function toWirePaths(files, baseDir) {
4791
+ const wire = new Map();
4792
+ const taken = new Set();
4793
+ const outside = [];
4794
+ for (const file of files) {
4795
+ if (wire.has(file)) continue;
4796
+ const rel = relativeWithin(file, baseDir);
4797
+ if (rel === null || taken.has(rel)) {
4798
+ outside.push(file);
4799
+ continue;
4800
+ }
4801
+ wire.set(file, rel);
4802
+ taken.add(rel);
4803
+ }
4804
+ let n = 0;
4805
+ for (const file of outside) {
4806
+ if (wire.has(file)) continue;
4807
+ let label;
4808
+ do {
4809
+ label = `${EXTERNAL_WIRE_DIR}/${n}/${safeName(file)}`;
4810
+ n += 1;
4811
+ } while (taken.has(label));
4812
+ wire.set(file, label);
4813
+ taken.add(label);
3634
4814
  }
3635
- return `${FILE_COUNT_BUCKETS[FILE_COUNT_BUCKETS.length - 1]}+`;
4815
+ return wire;
3636
4816
  }
3637
- const DURATION_BUCKETS_MS = [
3638
- [1e3, "<1s"],
3639
- [5e3, "1-5s"],
3640
- [15e3, "5-15s"],
3641
- [6e4, "15-60s"],
3642
- [3e5, "60-300s"]
3643
- ];
3644
- function durationBucket(ms) {
3645
- if (!Number.isFinite(ms) || ms < 0) return "unknown";
3646
- for (const [upper, label] of DURATION_BUCKETS_MS) if (ms < upper) return label;
3647
- return "300s+";
4817
+ function looksLocal(path) {
4818
+ return isUnder(path, homedir()) || isUnder(path, tmpdir()) || existsSync(path);
3648
4819
  }
3649
- function safeScalar(value) {
3650
- if (typeof value === "number") return Number.isFinite(value) ? value : null;
3651
- if (typeof value === "string") return TOKEN_PATTERN.test(value) ? value : null;
4820
+ function localPathOf(source) {
4821
+ if (DRIVE_PATH.test(source) || source.startsWith("/") || source.startsWith("\\")) return source;
4822
+ if (FILE_URL.test(source)) try {
4823
+ return fileURLToPath(source);
4824
+ } catch {
4825
+ return source.replace(FILE_URL, "").replace(/^\/\/[^/]*/, "") || "/";
4826
+ }
4827
+ const scheme = URL_SCHEME.exec(source);
4828
+ if (!scheme) return null;
4829
+ const rest = source.slice(scheme[0].length).replace(/^\/\/[^/]*/, "");
4830
+ const drive = rest.replace(/^\/+/, "");
4831
+ if (DRIVE_PATH.test(drive)) return drive;
4832
+ return rest.startsWith("/") && looksLocal(rest) ? rest : null;
4833
+ }
4834
+ function bothForms(path) {
4835
+ return [...new Set([resolve(path), realPath(path)])];
4836
+ }
4837
+ function newPlace(dir, root, labels, shipped = "") {
4838
+ return {
4839
+ dir,
4840
+ root,
4841
+ privateRoots: [...new Set([homedir(), root].flatMap(bothForms))],
4842
+ scratchRoots: bothForms(tmpdir()),
4843
+ labels,
4844
+ shipped
4845
+ };
4846
+ }
4847
+ function isPrivate(path, place) {
4848
+ if (DRIVE_PATH.test(path) && !isAbsolute(path)) return true;
4849
+ if (place.privateRoots.some((r) => isUnder(path, r))) return true;
4850
+ return place.scratchRoots.some((r) => isUnder(path, r) && resolve(path) !== resolve(r));
4851
+ }
4852
+ function inProject(path, place) {
4853
+ if (DRIVE_PATH.test(path) && !isAbsolute(path)) return null;
4854
+ const real = realPath(path);
4855
+ const mapDir = realPath(place.dir);
4856
+ const home = realPath(homedir());
4857
+ if (!isUnder(real, realPath(place.root))) return null;
4858
+ if (isUnder(real, home) && !isUnder(mapDir, home)) return null;
4859
+ const rel = relative(mapDir, real);
4860
+ if (rel === "" || isAbsolute(rel) || DRIVE_PATH.test(rel)) return null;
4861
+ return toPosix(rel);
4862
+ }
4863
+ function externalLabel(path, place) {
4864
+ const key = resolve(path);
4865
+ const known = place.labels.get(key);
4866
+ if (known !== void 0) return known;
4867
+ const label = `${EXTERNAL_WIRE_DIR}/${place.labels.size}/${safeName(path)}`;
4868
+ place.labels.set(key, label);
4869
+ return label;
4870
+ }
4871
+ function fitLength(target, candidate, slash) {
4872
+ const unit = `.${slash}`;
4873
+ const room = target - candidate.length;
4874
+ for (let a = Math.floor(Math.max(room, 0) / unit.length); a >= 0; a--) {
4875
+ const rest = room - a * unit.length;
4876
+ if (rest % slash.length !== 0) continue;
4877
+ const body = unit.repeat(a) + candidate;
4878
+ const extra = rest / slash.length;
4879
+ if (extra === 0) return body;
4880
+ const at = body.indexOf(slash);
4881
+ if (at < 0) continue;
4882
+ return body.slice(0, at) + slash.repeat(extra) + body.slice(at);
4883
+ }
3652
4884
  return null;
3653
4885
  }
3654
- function telemetrySafeData(data) {
3655
- if (!data || typeof data.kind !== "string") return null;
3656
- const kind = TOKEN_PATTERN.test(data.kind) ? data.kind : null;
3657
- if (kind === null) return null;
3658
- const out = { kind };
3659
- for (const field of DATA_FIELD_WHITELIST[kind] ?? []) {
3660
- const value = safeScalar(data[field]);
3661
- if (value !== null) out[field] = value;
4886
+ function sameLength(original, candidates, slash) {
4887
+ for (const candidate of candidates) {
4888
+ const fitted = fitLength(original.length, candidate, slash);
4889
+ if (fitted !== null) return fitted;
3662
4890
  }
3663
- return out;
4891
+ return "_".repeat(original.length);
4892
+ }
4893
+ function scrubText(text, place, keepLength) {
4894
+ if (!text.includes("/") && !text.includes("\\")) return text;
4895
+ const plain = text.replace(EMBEDDED_PATH, (whole, lead, path) => {
4896
+ if (!isPrivate(path, place) || keepLength && place.shipped.includes(path)) return whole;
4897
+ const name = inProject(path, place) ?? safeName(path);
4898
+ return `${lead}${keepLength ? sameLength(path, [name, safeName(path)], "/") : name}`;
4899
+ });
4900
+ return plain.replace(ESCAPED_PATH, (whole, lead, escaped) => {
4901
+ const path = escaped.replaceAll("\\/", "/");
4902
+ if (!isPrivate(path, place) || keepLength && place.shipped.includes(escaped)) return whole;
4903
+ const names = [inProject(path, place) ?? safeName(path), safeName(path)].map((c) => c.replaceAll("/", "\\/"));
4904
+ return `${lead}${keepLength ? sameLength(escaped, names, "\\/") : names[0]}`;
4905
+ });
3664
4906
  }
3665
- function telemetrySafeSpan(d) {
3666
- const span = d.span;
3667
- if (!span) return null;
3668
- const start = safeScalar(span.startByte);
3669
- const end = safeScalar(span.endByte);
3670
- if (typeof start !== "number" || typeof end !== "number") return null;
3671
- if (start < 0 || end < 0) return null;
4907
+ function isRecord(value) {
4908
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4909
+ }
4910
+ function joinRoot(root, source) {
4911
+ return root.endsWith("/") || root.endsWith("\\") ? `${root}${source}` : `${root}/${source}`;
4912
+ }
4913
+ function newRestore() {
3672
4914
  return {
3673
- startByte: start,
3674
- endByte: end
4915
+ sources: new Map(),
4916
+ pmPaths: new Map(),
4917
+ contents: new Map()
3675
4918
  };
3676
4919
  }
3677
- function telemetrySafeDiagnostic(d, severity) {
4920
+ function remember(table, wire, original) {
4921
+ const known = table.get(wire);
4922
+ if (known === void 0) table.set(wire, original);
4923
+ else if (known !== original) table.set(wire, null);
4924
+ }
4925
+ function wireMapObject(map, place, restore, top) {
4926
+ const out = { ...map };
4927
+ let changed = false;
4928
+ const root = typeof map.sourceRoot === "string" ? map.sourceRoot : "";
4929
+ const rootIsLocal = root !== "" && localPathOf(root) !== null;
4930
+ if (rootIsLocal) {
4931
+ delete out.sourceRoot;
4932
+ if (top) restore.sourceRoot = root;
4933
+ changed = true;
4934
+ }
4935
+ const sentRoot = rootIsLocal ? "" : root;
4936
+ const pmPath = (r, s) => r === "" ? s : joinRoot(r, s);
4937
+ const taken = new Map();
4938
+ const claim = (wired, original, local) => {
4939
+ const owner = taken.get(wired);
4940
+ if (owner === void 0 || owner === original) {
4941
+ taken.set(wired, original);
4942
+ return wired;
4943
+ }
4944
+ const label = externalLabel(local, place);
4945
+ taken.set(label, original);
4946
+ return label;
4947
+ };
4948
+ if (Array.isArray(map.sources)) out.sources = map.sources.map((source) => {
4949
+ if (typeof source !== "string") return source;
4950
+ const rooted = rootIsLocal && localPathOf(source) === null && !URL_SCHEME.test(source) ? joinRoot(root, source) : source;
4951
+ const local = localPathOf(rooted);
4952
+ let wired;
4953
+ if (local === null) {
4954
+ const scrubbed = scrubText(rooted, place, false);
4955
+ if (scrubbed === source) {
4956
+ taken.set(source, source);
4957
+ return source;
4958
+ }
4959
+ wired = claim(scrubbed, source, rooted);
4960
+ } else {
4961
+ const rel = inProject(local, place);
4962
+ wired = claim(rel ?? externalLabel(local, place), source, local);
4963
+ }
4964
+ changed = true;
4965
+ remember(restore.sources, wired, source);
4966
+ remember(restore.pmPaths, pmPath(sentRoot, wired), pmPath(root, source));
4967
+ return wired;
4968
+ });
4969
+ if (typeof map.file === "string" && localPathOf(map.file) !== null) {
4970
+ if (top) restore.file = map.file;
4971
+ out.file = safeName(map.file);
4972
+ changed = true;
4973
+ }
4974
+ if (Array.isArray(map.sourcesContent)) out.sourcesContent = map.sourcesContent.map((content) => {
4975
+ if (typeof content !== "string") return content;
4976
+ const scrubbed = scrubText(content, place, true);
4977
+ if (scrubbed === content) return content;
4978
+ changed = true;
4979
+ remember(restore.contents, scrubbed, content);
4980
+ return scrubbed;
4981
+ });
4982
+ if (Array.isArray(map.sections)) out.sections = map.sections.map((section) => {
4983
+ if (!isRecord(section) || !isRecord(section.map)) return section;
4984
+ const nested = wireMapObject(section.map, place, restore, false);
4985
+ if (!nested.changed) return section;
4986
+ changed = true;
4987
+ return {
4988
+ ...section,
4989
+ map: nested.map
4990
+ };
4991
+ });
3678
4992
  return {
3679
- code: TOKEN_PATTERN.test(d.code) ? d.code : "DIAG_UNKNOWN",
3680
- severity,
3681
- span: telemetrySafeSpan(d),
3682
- data: telemetrySafeData(d.data)
4993
+ map: out,
4994
+ changed
3683
4995
  };
3684
4996
  }
3685
- function buildTelemetryPayload(facts, ctx) {
3686
- let errorCount = 0;
3687
- let criticalCount = 0;
3688
- const alerting = [];
3689
- for (const d of facts.diagnostics) {
3690
- if (d.severity !== "error" && d.severity !== "critical") continue;
3691
- if (d.severity === "critical") criticalCount += 1;
3692
- else errorCount += 1;
3693
- alerting.push(telemetrySafeDiagnostic(d, d.severity));
4997
+ function wireSourceMapWithRestore(json, place) {
4998
+ const restore = newRestore();
4999
+ let parsed;
5000
+ try {
5001
+ parsed = JSON.parse(json);
5002
+ } catch {
5003
+ return {
5004
+ json: void 0,
5005
+ restore
5006
+ };
3694
5007
  }
3695
- if (alerting.length === 0) return null;
3696
- const kept = alerting.slice(-TELEMETRY_DIAGNOSTIC_LIMIT);
3697
- const env = ctx.env ?? {};
3698
- const runtime = ctx.runtime ?? {
3699
- node: process.versions.node,
3700
- platform: process.platform,
3701
- arch: process.arch
5008
+ if (!isRecord(parsed)) return {
5009
+ json: void 0,
5010
+ restore
3702
5011
  };
3703
- const framework = frameworkFromLabel(facts.label);
5012
+ const { map, changed } = wireMapObject(parsed, place, restore, true);
3704
5013
  return {
3705
- version: TELEMETRY_PAYLOAD_VERSION,
3706
- installId: ctx.installId,
3707
- framework,
3708
- frameworkVersion: detectFrameworkVersion(facts.projectRoot, framework),
3709
- engineVersion: safeVersion(facts.engineVersion),
3710
- clientVersion: safeVersion(facts.clientVersion),
3711
- nodeVersion: safeVersion(runtime.node) ?? "unknown",
3712
- os: safeToken(runtime.platform),
3713
- arch: safeToken(runtime.arch),
3714
- ci: env.CI === "true",
3715
- complexity: complexityLabel(facts.preset, facts.complexity),
3716
- fileCountBucket: fileCountBucket(facts.fileCount),
3717
- durationBucket: durationBucket(facts.durationMs),
3718
- diagnostics: kept,
3719
- errorCount,
3720
- criticalCount,
3721
- droppedCount: alerting.length - kept.length
5014
+ json: changed ? JSON.stringify(map) : json,
5015
+ restore
3722
5016
  };
3723
5017
  }
3724
- const VERSION_PATTERN = /^[0-9][0-9A-Za-z.\-+]{0,31}$/;
3725
- function safeVersion(value) {
3726
- return typeof value === "string" && VERSION_PATTERN.test(value) ? value : null;
3727
- }
3728
- function safeToken(value) {
3729
- return TOKEN_PATTERN.test(value) ? value : "unknown";
3730
- }
3731
- const TELEMETRY_NOTICE = [
3732
- "AfterPack: anonymous build diagnostics are ON (this notice prints once).",
3733
- "AfterPack: A build that reports an error-level diagnostic (a refused or partial build)",
3734
- "AfterPack: sends that diagnostic's code, severity, byte offsets and typed engine",
3735
- "AfterPack: fields, plus engine version, integration, Node version, OS/arch, bucketed",
3736
- "AfterPack: file counts and durations, and a random install id that rotates every 30",
3737
- "AfterPack: days.",
3738
- "AfterPack: It never sends your source, file names, paths, project name, diagnostic",
3739
- "AfterPack: message text, or exact byte counts. A clean build sends nothing.",
3740
- "AfterPack: Turn it off with AFTERPACK_telemetry_enabled=false, --telemetry.enabled=false, or",
3741
- "AfterPack: `telemetry: { enabled: false }` in your config.",
3742
- "AfterPack: https://www.afterpack.dev/privacy"
3743
- ];
3744
- const INSTALL_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
3745
- const DAY_MS = 24 * 60 * 60 * 1e3;
3746
- function readState(file, now) {
3747
- try {
3748
- const parsed = JSON.parse(readFileSync(file, "utf8"));
3749
- if (typeof parsed.installId === "string" && INSTALL_ID_PATTERN.test(parsed.installId) && typeof parsed.rotatedAt === "number") return {
3750
- installId: parsed.installId,
3751
- rotatedAt: parsed.rotatedAt,
3752
- noticeShownAt: typeof parsed.noticeShownAt === "number" ? parsed.noticeShownAt : 0
5018
+ function lookup(table, value) {
5019
+ return table.get(value) ?? value;
5020
+ }
5021
+ function restoreMapObject(map, ctx, top) {
5022
+ let changed = false;
5023
+ const out = { ...map };
5024
+ if (Array.isArray(map.sources)) out.sources = map.sources.map((entry) => {
5025
+ if (typeof entry !== "string") return entry;
5026
+ const back = entry === ctx.wire ? ctx.local : lookup(ctx.map.sources, entry);
5027
+ if (back !== entry) changed = true;
5028
+ return back;
5029
+ });
5030
+ if (Array.isArray(map.sourcesContent)) out.sourcesContent = map.sourcesContent.map((entry) => {
5031
+ if (typeof entry !== "string") return entry;
5032
+ const back = lookup(ctx.map.contents, entry);
5033
+ if (back !== entry) changed = true;
5034
+ return back;
5035
+ });
5036
+ if (top && ctx.map.sourceRoot !== void 0 && !map.sourceRoot) {
5037
+ const root = ctx.map.sourceRoot;
5038
+ const entries = Object.entries(out).filter(([key]) => key !== "sourceRoot");
5039
+ const at = "sourceRoot" in map ? Object.keys(map).indexOf("sourceRoot") : -1;
5040
+ const after = entries.findIndex(([key]) => key === "sources");
5041
+ const index = at >= 0 ? at : after >= 0 ? after + 1 : entries.length;
5042
+ entries.splice(index, 0, ["sourceRoot", root]);
5043
+ for (const key of Object.keys(out)) delete out[key];
5044
+ Object.assign(out, Object.fromEntries(entries));
5045
+ changed = true;
5046
+ }
5047
+ if (top && ctx.map.file !== void 0 && typeof map.file === "string") {
5048
+ out.file = ctx.map.file;
5049
+ changed = true;
5050
+ }
5051
+ if (Array.isArray(map.sections)) out.sections = map.sections.map((section) => {
5052
+ if (!isRecord(section) || !isRecord(section.map)) return section;
5053
+ const nested = restoreMapObject(section.map, ctx, false);
5054
+ if (!nested.changed) return section;
5055
+ changed = true;
5056
+ return {
5057
+ ...section,
5058
+ map: nested.map
3753
5059
  };
3754
- } catch {}
5060
+ });
3755
5061
  return {
3756
- installId: randomUUID(),
3757
- rotatedAt: now,
3758
- noticeShownAt: 0
5062
+ map: out,
5063
+ changed
3759
5064
  };
3760
5065
  }
3761
- function writeState(file, state) {
5066
+ function restoreSourceMap(json, ctx) {
5067
+ let parsed;
3762
5068
  try {
3763
- mkdirSync(dirname(file), { recursive: true });
3764
- writeFileSync(file, `${JSON.stringify(state)}\n`, "utf8");
3765
- } catch {}
3766
- }
3767
- function telemetryUrl(env) {
3768
- const base = (env[API_URL_ENV_VAR] ?? DEFAULT_API_URL).replace(/\/+$/, "");
3769
- return `${base}${TELEMETRY_ENDPOINT_PATH}`;
5069
+ parsed = JSON.parse(json);
5070
+ } catch {
5071
+ return json;
5072
+ }
5073
+ if (!isRecord(parsed)) return json;
5074
+ const { map, changed } = restoreMapObject(parsed, ctx, true);
5075
+ return changed ? JSON.stringify(map) : json;
5076
+ }
5077
+ function restoredSize(size, wired, original) {
5078
+ if (typeof size !== "number") return size;
5079
+ if (size === Buffer.byteLength(wired)) return Buffer.byteLength(original);
5080
+ if (size === wired.length) return original.length;
5081
+ return size;
5082
+ }
5083
+ function restoreProtectionMap(doc, ctx) {
5084
+ if (!isRecord(doc) || !Array.isArray(doc.files)) return doc;
5085
+ return {
5086
+ ...doc,
5087
+ files: doc.files.map((entry) => {
5088
+ if (!isRecord(entry) || !isRecord(entry.file)) return entry;
5089
+ const file = entry.file;
5090
+ const next = { ...file };
5091
+ if (typeof file.path === "string") next.path = file.path === ctx.wire ? ctx.local : lookup(ctx.map.pmPaths, file.path);
5092
+ if (typeof file.originalSource === "string") {
5093
+ const original = lookup(ctx.map.contents, file.originalSource);
5094
+ if (original !== file.originalSource) {
5095
+ next.originalSource = original;
5096
+ next.inputSize = restoredSize(file.inputSize, file.originalSource, original);
5097
+ }
5098
+ }
5099
+ const same = Object.keys(next).every((k) => next[k] === file[k]);
5100
+ return same ? entry : {
5101
+ ...entry,
5102
+ file: next
5103
+ };
5104
+ })
5105
+ };
3770
5106
  }
3771
- const TELEMETRY_BODY_LIMIT = 64 * 1024;
3772
- async function reportTelemetryNotices(response, logger) {
3773
- if (!response || response.status !== 202 || typeof response.text !== "function") return;
3774
- const declared = Number(response.headers?.get?.("content-length"));
3775
- if (Number.isFinite(declared) && declared > TELEMETRY_BODY_LIMIT) {
3776
- await response.body?.cancel().catch(() => {});
3777
- return;
5107
+ function wireGlob(pattern, pairs) {
5108
+ let equivalent = true;
5109
+ const matched = [];
5110
+ for (const [local, wire] of pairs) {
5111
+ const hit = matchesPath(pattern, local);
5112
+ if (hit !== matchesPath(pattern, wire)) equivalent = false;
5113
+ if (hit) matched.push(wire);
3778
5114
  }
3779
- const text = await response.text();
3780
- if (text.length > TELEMETRY_BODY_LIMIT) return;
3781
- let body;
3782
- try {
3783
- body = JSON.parse(text);
3784
- } catch {
3785
- return;
5115
+ if (!isAnchored(pattern) && equivalent && matched.length > 0) return [pattern];
5116
+ return matched.map((wire) => `/${wire}`);
5117
+ }
5118
+ function anyMatch(patterns, path) {
5119
+ return patterns.some((p) => matchesPath(p, path));
5120
+ }
5121
+ function reservedNames(entries, path) {
5122
+ const names = entries.flatMap((e) => typeof e === "string" ? [] : matchesPath(e.glob, path) ? e.names : []);
5123
+ return [...new Set(names)].sort().join("\n");
5124
+ }
5125
+ function verifyTranslation(config, out, pairs) {
5126
+ const exclude = config.paths?.exclude ?? [];
5127
+ const sentExclude = out.paths?.exclude ?? [];
5128
+ const reserved = config.identifiers?.reserved ?? [];
5129
+ const sentReserved = out.identifiers?.reserved ?? [];
5130
+ for (const [local, wire] of pairs) {
5131
+ if (anyMatch(exclude, local) !== anyMatch(sentExclude, wire)) throw new WirePathError(`could not send \`paths.exclude\` to the engine without changing which files it selects: ${wire} would be ${anyMatch(exclude, local) ? "protected" : "left unprotected"}. Rename the file or write the pattern so it does not depend on glob characters in file names.`);
5132
+ if (reservedNames(reserved, local) !== reservedNames(sentReserved, wire)) throw new WirePathError(`could not send \`identifiers.reserved\` to the engine without changing which files its globs select: ${wire} would keep a different set of names. Rename the file or write the glob so it does not depend on glob characters in file names.`);
3786
5133
  }
3787
- if (typeof body !== "object" || body === null || Array.isArray(body)) return;
3788
- reportNotices(body.notices, logger);
3789
5134
  }
3790
- function createTelemetryReporter(deps = {}) {
3791
- const env = deps.env ?? process.env;
3792
- const logger = deps.logger ?? console;
3793
- const now = deps.now ?? Date.now;
3794
- const stateFile = deps.stateFile ?? TELEMETRY_STATE_FILE;
3795
- const timeoutMs = deps.timeoutMs ?? TELEMETRY_TIMEOUT_MS;
3796
- return async (facts) => {
3797
- try {
3798
- const at = now();
3799
- const state = readState(stateFile, at);
3800
- let dirty = false;
3801
- if (at - state.rotatedAt >= INSTALL_ID_ROTATION_DAYS * DAY_MS) {
3802
- state.installId = randomUUID();
3803
- state.rotatedAt = at;
3804
- dirty = true;
3805
- }
3806
- if (state.noticeShownAt === 0) {
3807
- for (const line of TELEMETRY_NOTICE) logger.log(line);
3808
- state.noticeShownAt = at;
3809
- dirty = true;
3810
- }
3811
- if (dirty) writeState(stateFile, state);
3812
- if (facts === null) return;
3813
- const payload = buildTelemetryPayload(facts, {
3814
- installId: state.installId,
3815
- env
3816
- });
3817
- if (payload === null) return;
3818
- const fetchImpl = deps.fetchImpl ?? globalThis.fetch;
3819
- if (typeof fetchImpl !== "function") return;
3820
- const response = await fetchImpl(telemetryUrl(env), {
3821
- method: "POST",
3822
- headers: { "content-type": "application/json" },
3823
- body: JSON.stringify(payload),
3824
- signal: AbortSignal.timeout(timeoutMs)
3825
- });
3826
- await reportTelemetryNotices(response, logger);
3827
- } catch {}
5135
+ function translateConfig(config, wirePaths) {
5136
+ const exclude = config.paths?.exclude;
5137
+ const reserved = config.identifiers?.reserved;
5138
+ const origins = new Map();
5139
+ if (exclude === void 0 && reserved === void 0) return {
5140
+ config,
5141
+ origins
5142
+ };
5143
+ const pairs = [...wirePaths.entries()];
5144
+ const translate = (pattern) => {
5145
+ const patterns = wireGlob(pattern, pairs);
5146
+ for (const p of patterns) if (!origins.has(p)) origins.set(p, pattern);
5147
+ return patterns;
5148
+ };
5149
+ const out = { ...config };
5150
+ if (exclude !== void 0) out.paths = {
5151
+ ...config.paths,
5152
+ exclude: [...new Set(exclude.flatMap((pattern) => translate(pattern)))]
5153
+ };
5154
+ if (reserved !== void 0) out.identifiers = {
5155
+ ...config.identifiers,
5156
+ reserved: reserved.flatMap((entry) => typeof entry === "string" ? [entry] : translate(entry.glob).map((glob) => ({
5157
+ ...entry,
5158
+ glob
5159
+ })))
5160
+ };
5161
+ verifyTranslation(config, out, pairs);
5162
+ return {
5163
+ config: out,
5164
+ origins
5165
+ };
5166
+ }
5167
+ function escapeRegExp(text) {
5168
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5169
+ }
5170
+ function localMessage(message, wire, local, origins) {
5171
+ let out = message;
5172
+ for (const [sent, original] of origins) if (sent !== original) out = out.split(`"${sent}"`).join(`"${original}"`);
5173
+ const bounded = new RegExp(`(^|[\\s"'\`(\\[])${escapeRegExp(wire)}(?=$|[\\s"'\`)\\]:,;]|\\.(?:\\s|$))`, "g");
5174
+ return out.replace(bounded, (_m, lead) => `${lead}${local}`);
5175
+ }
5176
+ function localDiagnostics(diagnostics, localPaths, wire, local, origins) {
5177
+ if (!Array.isArray(diagnostics)) return diagnostics;
5178
+ return diagnostics.map((d) => {
5179
+ if (!isRecord(d)) return d;
5180
+ const next = { ...d };
5181
+ if (typeof d.file === "string") next.file = localPaths.get(d.file) ?? d.file;
5182
+ if (typeof d.message === "string") next.message = localMessage(d.message, wire, local, origins);
5183
+ return next.file === d.file && next.message === d.message ? d : next;
5184
+ });
5185
+ }
5186
+ function prepareWireBatch(inputs, config, baseDir, rootDir = baseDir) {
5187
+ const wirePaths = toWirePaths(inputs.map((i) => i.path), baseDir);
5188
+ const localPaths = new Map([...wirePaths].map(([local, wire]) => [wire, local]));
5189
+ const translated = translateConfig(config, wirePaths);
5190
+ const restores = new Map();
5191
+ const labels = new Map();
5192
+ const wiredInputs = inputs.map((input) => {
5193
+ const path = wirePaths.get(input.path) ?? input.path;
5194
+ const wired = {
5195
+ ...input,
5196
+ path
5197
+ };
5198
+ if (input.sourceMap !== void 0) {
5199
+ const place = newPlace(dirname(resolve(input.path)), rootDir, labels, input.source);
5200
+ const map = wireSourceMapWithRestore(input.sourceMap, place);
5201
+ restores.set(path, map.restore);
5202
+ if (map.json === void 0) delete wired.sourceMap;
5203
+ else wired.sourceMap = map.json;
5204
+ }
5205
+ return wired;
5206
+ });
5207
+ return {
5208
+ inputs: wiredInputs,
5209
+ config: translated.config,
5210
+ toLocal: (batch) => ({
5211
+ ...batch,
5212
+ files: batch.files.map((f) => {
5213
+ const local = localPaths.get(f.path);
5214
+ if (local === void 0) return f;
5215
+ const ctx = {
5216
+ map: restores.get(f.path) ?? newRestore(),
5217
+ wire: f.path,
5218
+ local
5219
+ };
5220
+ return {
5221
+ ...f,
5222
+ path: local,
5223
+ ...f.diagnostics === void 0 ? {} : { diagnostics: localDiagnostics(f.diagnostics, localPaths, f.path, local, translated.origins) },
5224
+ ...typeof f.sourceMap === "string" ? { sourceMap: restoreSourceMap(f.sourceMap, ctx) } : {},
5225
+ ...f.protectionMap == null ? {} : { protectionMap: restoreProtectionMap(f.protectionMap, ctx) }
5226
+ };
5227
+ })
5228
+ })
3828
5229
  };
3829
5230
  }
3830
5231
 
@@ -3861,12 +5262,19 @@ function fileFailure(f, source) {
3861
5262
  if (f.code === "" && source.trim() !== "") return sanitizeServerText(f.error) || "empty output";
3862
5263
  return null;
3863
5264
  }
3864
- async function readEngineVersion(engine) {
3865
- try {
3866
- return await engine.version?.() ?? null;
3867
- } catch {
3868
- return null;
5265
+ function bundlerMapsToRemove(input) {
5266
+ const { sweepDir: sweepDir$1, engineMaps, policy } = input;
5267
+ const bundlerMaps = new Set([...input.perFile].flat());
5268
+ if (sweepDir$1 != null) {
5269
+ const swept = collectSourceMaps(sweepDir$1).filter((path) => !policy.sourceMap || !path.endsWith(".css.map"));
5270
+ for (const path of containedSourceMaps(swept, sweepDir$1)) bundlerMaps.add(path);
3869
5271
  }
5272
+ return [...bundlerMaps].filter((path) => !engineMaps.has(path));
5273
+ }
5274
+ function removeBundlerSourceMaps(input) {
5275
+ const { sweepDir: sweepDir$1, policy, label } = input;
5276
+ removeSourceMaps(bundlerMapsToRemove(input), label);
5277
+ if (sweepDir$1 != null && !policy.sourceMap) stripCssSourceMappingURLs(collectStylesheets(sweepDir$1));
3870
5278
  }
3871
5279
  function describeLevel(preset, complexity) {
3872
5280
  if (complexity === void 0) return `preset "${preset ?? DEFAULT_PRESET}"`;
@@ -3876,22 +5284,30 @@ function describeLevel(preset, complexity) {
3876
5284
  async function runObfuscationPass(options) {
3877
5285
  const passStartedAt = options.startedAt ?? Date.now();
3878
5286
  const callerAnchored = options.startedAt !== void 0;
3879
- const { files, engine, label, cwd, combinedProtectionMap, artifactOptions = {}, env = process.env } = options;
5287
+ const { engine, label, cwd, combinedProtectionMap, artifactOptions = {}, env = process.env } = options;
3880
5288
  const logger = silenceSummaryLines(options.logger ?? DEFAULT_LOGGER, options.diagnostics);
3881
5289
  const prefix = (message) => `[${label}] ${message}`;
3882
5290
  const style = options.summaryStyle ?? "plugin";
3883
5291
  assertSupportedCore(options.client, prefix);
5292
+ const outsideBuildDir = options.emitToCaller ? [] : options.files.filter((f) => !options.inputs?.has(f) && !withinRealDir(dirname(f), combinedProtectionMap.buildDir));
5293
+ const files = options.files.filter((f) => !outsideBuildDir.includes(f));
5294
+ if (outsideBuildDir.length > 0) logger.warn(prefix(`left ${outsideBuildDir.length} file(s) untouched because a symlink places them outside ${combinedProtectionMap.buildDir}: ${outsideBuildDir.join(", ")}`));
3884
5295
  const onDiskFiles = options.inputs ? files.filter((f) => !options.inputs?.has(f)) : files;
3885
5296
  const onDiskBytes = new Map(await Promise.all(onDiskFiles.map(async (filePath) => [filePath, await readFile(filePath)])));
5297
+ const home = afterpackHome(combinedProtectionMap.buildDir, { fileTarget: combinedProtectionMap.fileTarget });
5298
+ const unanchored = describeUnanchoredHome(home);
5299
+ if (unanchored) logger.log(prefix(unanchored));
3886
5300
  if (!options.emitToCaller) {
3887
- const already = detectAlreadyObfuscatedInputs(onDiskFiles, combinedProtectionMap.buildDir, onDiskBytes, prefix);
5301
+ const already = detectAlreadyObfuscatedInputs(onDiskFiles, home, onDiskBytes, prefix);
3888
5302
  if (already) throw new AlreadyObfuscatedError(prefix(formatAlreadyObfuscatedMessage({
3889
5303
  files: already.files,
3890
5304
  receiptPath: already.receiptPath,
3891
5305
  dir: combinedProtectionMap.buildDir
3892
5306
  })), already.files, already.receiptPath, combinedProtectionMap.buildDir);
3893
5307
  }
3894
- const resolvedSeed = resolveBuildSeed(options.seed, {
5308
+ if (options.outputSweep !== false) sweepOutputTree(combinedProtectionMap.buildDir, options.sourceMapSweepDir ?? (options.emitToCaller ? combinedProtectionMap.buildDir : null), label, home);
5309
+ prepareProtectionReceipt(home, label);
5310
+ const resolvedSeed = options.resolvedSeed ?? resolveBuildSeed(options.seed, {
3895
5311
  root: cwd,
3896
5312
  leg: options.buildLeg ?? combinedProtectionMap.buildDir
3897
5313
  }, {
@@ -3904,6 +5320,9 @@ async function runObfuscationPass(options) {
3904
5320
  const bundledCapture = options.capturedByFile != null;
3905
5321
  const postMinifyMode = directivesEnabled && options.postMinify === true && !bundledCapture;
3906
5322
  const sourceByPath = new Map();
5323
+ const bundlerMapsByPath = new Map();
5324
+ const sweepDir$1 = options.sourceMapSweepDir ?? null;
5325
+ const sourceMapRoot = sweepDir$1 ?? combinedProtectionMap.buildDir;
3907
5326
  let coloredRegionCount = 0;
3908
5327
  let directivesNeededMap = false;
3909
5328
  let postMinifyMapsSeen = 0;
@@ -3913,6 +5332,7 @@ async function runObfuscationPass(options) {
3913
5332
  const provided = options.inputs?.get(filePath);
3914
5333
  const source = provided ? provided.source : (onDiskBytes.get(filePath) ?? readFileSync(filePath)).toString("utf8");
3915
5334
  sourceByPath.set(filePath, source);
5335
+ if (!provided && !options.emitToCaller) bundlerMapsByPath.set(filePath, bundlerSourceMapPaths(filePath, source, sourceMapRoot));
3916
5336
  const inputSourceMap = provided ? provided.sourceMap ?? null : discoverInputSourceMap(filePath, source);
3917
5337
  let regions;
3918
5338
  const modules = options.capturedByFile?.get(filePath);
@@ -3993,7 +5413,12 @@ async function runObfuscationPass(options) {
3993
5413
  cwd
3994
5414
  });
3995
5415
  const localEngineVersion = await readEngineVersion(engine);
3996
- const derivedSourceType = options.sourceType !== void 0 && coreSupportsSourceType(localEngineVersion ?? options.client?.coreVersion) ? options.sourceType : void 0;
5416
+ const gateVersion = localEngineVersion ?? options.client?.coreVersion;
5417
+ const derivedSourceType = options.sourceType !== void 0 && coreSupportsSourceType(gateVersion) ? options.sourceType : void 0;
5418
+ if (options.fileSourceTypes && options.engineConfig?.sourceType === void 0 && coreSupportsFileSourceType(gateVersion)) for (const input of inputs) {
5419
+ const sourceType = options.fileSourceTypes.get(input.path);
5420
+ if (sourceType !== void 0) input.sourceType = sourceType;
5421
+ }
3997
5422
  const engineConfig = buildEngineConfig({
3998
5423
  policy,
3999
5424
  seed,
@@ -4004,6 +5429,40 @@ async function runObfuscationPass(options) {
4004
5429
  engine: options.engineConfig,
4005
5430
  renameGlobals: capture.renameGlobals
4006
5431
  });
5432
+ const saltEngine = options.cloudEngineExpectation ?? (options.hashedNames ? await resolveSaltEngine(env, localEngineVersion) : null);
5433
+ let namesPlan = null;
5434
+ let hashSalt = null;
5435
+ if (options.hashedNames && saltEngine && !options.emitToCaller) {
5436
+ const { seed: _seed,...configWithoutSeed } = engineConfig;
5437
+ const namedInputs = new Map(inputs.map((input) => [input.path, {
5438
+ source: input.source,
5439
+ regions: input.regions,
5440
+ sourceType: input.sourceType
5441
+ }]));
5442
+ hashSalt = afterpackHashSalt({
5443
+ seed,
5444
+ engine: saltEngine,
5445
+ settings: {
5446
+ engine: configWithoutSeed,
5447
+ sourceMap: policy.sourceMap,
5448
+ emitSourceMappingURL: policy.emitSourceMappingURL
5449
+ }
5450
+ });
5451
+ namesPlan = planHashedNames({
5452
+ options: options.hashedNames,
5453
+ inputs: namedInputs,
5454
+ salt: hashSalt
5455
+ });
5456
+ namesPlan.preflight();
5457
+ for (const input of inputs) {
5458
+ const path = namesPlan.renamed.get(input.path) ?? input.path;
5459
+ const source = namesPlan.rewrite(input.source);
5460
+ sourceByPath.delete(input.path);
5461
+ sourceByPath.set(path, source);
5462
+ input.path = path;
5463
+ input.source = source;
5464
+ }
5465
+ }
4007
5466
  if (style !== "cli") logger.log(prefix(`obfuscating ${inputs.length} file(s) at ${describeLevel(options.preset, options.complexity)} ...`));
4008
5467
  const engineStartedAt = Date.now();
4009
5468
  const prepMs = engineStartedAt - passStartedAt;
@@ -4011,9 +5470,16 @@ async function runObfuscationPass(options) {
4011
5470
  clientVersion: options.client?.coreVersion,
4012
5471
  client: clientString(options.client)
4013
5472
  });
5473
+ let wire;
5474
+ try {
5475
+ wire = prepareWireBatch(inputs, engineConfig, combinedProtectionMap.buildDir, home.projectRoot);
5476
+ } catch (error) {
5477
+ if (error instanceof WirePathError) throw new Error(prefix(error.message));
5478
+ throw error;
5479
+ }
4014
5480
  let batch;
4015
5481
  try {
4016
- batch = await engine.processBatch(inputs, engineConfig, context);
5482
+ batch = wire.toLocal(await engine.processBatch(wire.inputs, wire.config, context));
4017
5483
  } catch (error) {
4018
5484
  const cloud = toCloudApiError(error, {
4019
5485
  identity: options.client,
@@ -4024,6 +5490,7 @@ async function runObfuscationPass(options) {
4024
5490
  throw cloud;
4025
5491
  }
4026
5492
  const engineEndedAt = Date.now();
5493
+ options.onBatch?.(inputs, batch);
4027
5494
  reportNotices(batch.notices, logger, prefix);
4028
5495
  const engineMs = engineEndedAt - engineStartedAt;
4029
5496
  const collected = collectDiagnostics(batch.files);
@@ -4038,6 +5505,10 @@ async function runObfuscationPass(options) {
4038
5505
  const telemetry = options.telemetry;
4039
5506
  const telemetryEnabled = telemetry != null && resolveTelemetryEnabled(artifactOptions.telemetry?.enabled, env);
4040
5507
  const engineVersion = (batch.source === "cloud" ? safeVersionString(batch.engineVersion) : null) ?? localEngineVersion;
5508
+ if (saltEngine) {
5509
+ const mismatch = cloudEngineMismatch(saltEngine, batch.source === "cloud" ? safeVersionString(batch.engineVersion) : null);
5510
+ if (mismatch) throw new Error(prefix(mismatch));
5511
+ }
4041
5512
  if (telemetry && telemetryEnabled) {
4042
5513
  const facts = {
4043
5514
  label,
@@ -4075,8 +5546,57 @@ async function runObfuscationPass(options) {
4075
5546
  source
4076
5547
  });
4077
5548
  }
5549
+ const artifactInput = (f, source) => ({
5550
+ outPath: f.path,
5551
+ code: withSourceMappingURL(f.code, null),
5552
+ sourceMapJson: f.sourceMap ?? null,
5553
+ originalSource: source,
5554
+ policy,
5555
+ mode: "framework"
5556
+ });
5557
+ if (!options.emitToCaller && options.beforeWrite) {
5558
+ const planned = new Map();
5559
+ const expectState = (path, state) => {
5560
+ const states = planned.get(path) ?? [];
5561
+ if (!states.includes(state)) states.push(state);
5562
+ planned.set(path, states);
5563
+ };
5564
+ for (const from of namesPlan?.renamed.keys() ?? []) expectState(from, null);
5565
+ const plannedEngineMaps = new Set();
5566
+ for (const { result: f, source } of verified) {
5567
+ const artifacts = planArtifactWrites(artifactInput(f, source));
5568
+ if (artifacts.mapPath) plannedEngineMaps.add(resolve(artifacts.mapPath));
5569
+ for (const write of artifacts.writes) {
5570
+ expectState(write.path, sha256Hex(write.content));
5571
+ expectState(stagedPath(write.path), null);
5572
+ }
5573
+ }
5574
+ for (const { to, text } of namesPlan?.rewrites.values() ?? []) {
5575
+ expectState(to, sha256Hex(text));
5576
+ expectState(stagedPath(to), null);
5577
+ }
5578
+ for (const map of bundlerMapsToRemove({
5579
+ perFile: bundlerMapsByPath.values(),
5580
+ sweepDir: sweepDir$1,
5581
+ engineMaps: plannedEngineMaps,
5582
+ policy
5583
+ })) expectState(map, null);
5584
+ if (sweepDir$1 != null && !policy.sourceMap) for (const css of collectStylesheets(sweepDir$1)) {
5585
+ const rewritten = namesPlan?.rewrites.get(css);
5586
+ const text = rewritten?.text ?? readFileSync(css, "utf8");
5587
+ const stripped = withoutCssSourceMappingURL(text);
5588
+ if (stripped === text) continue;
5589
+ expectState(rewritten?.to ?? css, sha256Hex(stripped));
5590
+ expectState(stagedPath(rewritten?.to ?? css), null);
5591
+ }
5592
+ options.beforeWrite({
5593
+ renamed: namesPlan?.renamed ?? new Map(),
5594
+ planned
5595
+ });
5596
+ }
4078
5597
  const writtenFiles = [];
4079
5598
  const emittedFiles = [];
5599
+ const engineMaps = new Set();
4080
5600
  for (const { result: f, source } of verified) {
4081
5601
  if (options.emitToCaller) {
4082
5602
  outputs.push({
@@ -4088,25 +5608,38 @@ async function runObfuscationPass(options) {
4088
5608
  continue;
4089
5609
  }
4090
5610
  const written = writeArtifacts({
4091
- outPath: f.path,
4092
- code: f.code,
4093
- sourceMapJson: f.sourceMap ?? null,
5611
+ ...artifactInput(f, source),
4094
5612
  protectionMapJson: null,
4095
- originalSource: source,
4096
- policy,
4097
- mode: "framework",
5613
+ afterpackDir: home.dir,
4098
5614
  logger
4099
5615
  });
4100
5616
  writtenFiles.push(written.codePath);
4101
- if (written.mapPath) sensitiveArtifactPaths.push(written.mapPath);
5617
+ if (written.mapPath) {
5618
+ sensitiveArtifactPaths.push(written.mapPath);
5619
+ engineMaps.add(resolve(written.mapPath));
5620
+ }
4102
5621
  if (written.backupPath) sensitiveArtifactPaths.push(written.backupPath);
4103
5622
  }
4104
- if (!options.emitToCaller) options.afterWrite?.();
5623
+ if (!options.emitToCaller) {
5624
+ if (namesPlan) {
5625
+ for (const [from, to] of namesPlan.renamed) if (sourceByPath.has(to)) rmSync(from, { force: true });
5626
+ namesPlan.apply();
5627
+ if (namesPlan.renamed.size > 0) logger.log(prefix(`renamed ${namesPlan.renamed.size} content-hashed file(s) so each name follows its obfuscated bytes`));
5628
+ }
5629
+ removeBundlerSourceMaps({
5630
+ perFile: bundlerMapsByPath.values(),
5631
+ sweepDir: sweepDir$1,
5632
+ engineMaps,
5633
+ policy,
5634
+ label
5635
+ });
5636
+ options.afterWrite?.(writtenFiles);
5637
+ }
4105
5638
  const protectionMapPath = writeCombinedProtectionMap({
4106
5639
  buildDir: combinedProtectionMap.buildDir,
4107
5640
  docs: protectionMapDocs,
4108
5641
  policy,
4109
- afterpackDir: combinedProtectionMap.afterpackDir,
5642
+ afterpackDir: combinedProtectionMap.subdir ? join(home.dir, combinedProtectionMap.subdir) : home.dir,
4110
5643
  fileName: combinedProtectionMap.fileName,
4111
5644
  logger
4112
5645
  });
@@ -4128,12 +5661,15 @@ async function runObfuscationPass(options) {
4128
5661
  if (options.emitToCaller) deferredReceipt = {
4129
5662
  ...receiptFields,
4130
5663
  dir: combinedProtectionMap.buildDir,
5664
+ home,
4131
5665
  files: emittedFiles
4132
5666
  };
4133
5667
  else {
4134
5668
  receiptPath = writeProtectionReceipt({
4135
5669
  ...receiptFields,
4136
5670
  dir: combinedProtectionMap.buildDir,
5671
+ home,
5672
+ merge: combinedProtectionMap.fileTarget === true,
4137
5673
  files: writtenFiles
4138
5674
  });
4139
5675
  if (style !== "cli") logger.log(prefix(`wrote protection receipt -> ${receiptPath} (afterpack verify)`));
@@ -4172,6 +5708,8 @@ async function runObfuscationPass(options) {
4172
5708
  timing,
4173
5709
  diagnostics: diagnosticsSummary,
4174
5710
  transformedFiles,
5711
+ renamed: namesPlan?.renamed ?? new Map(),
5712
+ hashSalt,
4175
5713
  ...options.emitToCaller ? { outputs } : {}
4176
5714
  };
4177
5715
  }
@@ -4351,4 +5889,4 @@ function resolvePluginConfig(input) {
4351
5889
  }
4352
5890
 
4353
5891
  //#endregion
4354
- export { AlreadyObfuscatedError, CLOUD_REFUSAL_SUMMARY, CONFIG_FILE_NAME, CONFIG_KEYS, CORE_FLOOR_SUMMARY, CloudApiError, CoreVersionError, DIAG_ALREADY_OBFUSCATED, DIAG_RECEIPT_UNREADABLE, PROTECTION_RECEIPT_FILE, SEED_ENV_VAR, UnreadableReceiptError, applyBundleOutput, applyResolvedKey, collectBundleJs, collectJsFiles, collectSourceMaps, collectStylesheets, createTelemetryReporter, decodeDataUri, discoverInputSourceMap, ensureAfterpackGitignore, extractSourceMappingURL, findUpward, getPath, installedRequiredLine, loadConfigFile, mergeConfig, normalizePluginOptions, npxAlternative, parseCliOptions, parseEnvOptions, passSettings, resolveClientIdentity, resolvePluginConfig, resolveReportPolicy, runObfuscationPass, sanitizeNotices, scanDirectives, serverAddsInfo, sha256Of, sourceTypeForBundle, sourceTypeForOutputFormat, stripBundleCssSourceMaps, toEngineConfig, toPluginOptions, validateConfig, verifyProtectionReceipt, withSourceMappingURL, withoutCssSourceMappingURL, writeArtifacts, writeDeferredProtectionReceipt, writeProtectionReceipt };
5892
+ export { AFTERPACK_DIR, AfterpackFilesError, AlreadyObfuscatedError, CLOUD_REFUSAL_SUMMARY, CONFIG_FILE_NAME, CONFIG_KEYS, CORE_FLOOR_SUMMARY, CloudApiError, CoreVersionError, DIAG_AFTERPACK_DIR_IN_OUTPUT, DIAG_ALREADY_OBFUSCATED, DIAG_RECEIPT_UNREADABLE, DIAG_RECEIPT_UNWRITABLE, NEXT_CHUNKS_PREFIX, PROTECTION_RECEIPTS_DIR, SEED_ENV_VAR, UnreadableReceiptError, afterpackHome, angularHashToken, angularServerManifestRefusal, applyBundleOutput, applyResolvedKey, buildDirKey, collectBundleJs, collectJsFiles, collectSourceMaps, collectStylesheets, createTelemetryReporter, decodeDataUri, detectNextBundler, discoverInputSourceMap, ensureAfterpackGitignore, extractSourceMappingURL, findHashTokenReference, findUpward, getPath, installedRequiredLine, isWithinDir, loadConfigFile, locateProtectionReceipt, mergeConfig, nextChunkToken, normalizePluginOptions, npxAlternative, parseCliOptions, parseEnvOptions, passSettings, planAngularIntegrity, prepareHashSalt, protectionReceiptPath, readEngineVersion, recomputeAngularIntegrity, regenerateCompressedSiblings, removeSourceMaps, reportPolicySaltBits, resolveClientIdentity, resolvePluginConfig, resolveReportPolicy, runObfuscationPass, saltSettings, sanitizeNotices, scanDirectives, serverAddsInfo, sha256Hex, sha256Of, skipNextInternals, sourceTypeForBundle, sourceTypeForOutputFormat, sriPluginRefusal, stagedPath, stripBundleCssSourceMaps, stripCssSourceMappingURLs, sweepOutputTree, toEngineConfig, toPluginOptions, unreferencedHashedFiles, unsaltedAssetsWarning, validateConfig, verifyProtectionReceipt, withSourceMappingURL, withoutCssSourceMappingURL, writeArtifacts, writeDeferredProtectionReceipt, writeFileAtomic, writeProtectionReceipt };