@afterpack/integration-utils 0.2.2 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -27,10 +27,10 @@ const node_module = __toESM(require("node:module"));
27
27
  const node_zlib = __toESM(require("node:zlib"));
28
28
  const node_crypto = __toESM(require("node:crypto"));
29
29
  const node_url = __toESM(require("node:url"));
30
- const node_fs_promises = __toESM(require("node:fs/promises"));
31
30
  const node_child_process = __toESM(require("node:child_process"));
32
- const __jridgewell_sourcemap_codec = __toESM(require("@jridgewell/sourcemap-codec"));
33
31
  const node_os = __toESM(require("node:os"));
32
+ const node_fs_promises = __toESM(require("node:fs/promises"));
33
+ const __jridgewell_sourcemap_codec = __toESM(require("@jridgewell/sourcemap-codec"));
34
34
 
35
35
  //#region ../protection-map/codec.mjs
36
36
  const COMPACT_SCHEMA_VERSION = 5;
@@ -297,6 +297,91 @@ function renderProtectionMapHtml(raw, { template, includeLineage = true } = {})
297
297
  };
298
298
  }
299
299
 
300
+ //#endregion
301
+ //#region src/home.ts
302
+ const AFTERPACK_DIR = ".afterpack";
303
+ const STRONG_MARKERS = [
304
+ "afterpack.json",
305
+ ".git",
306
+ "package-lock.json",
307
+ "npm-shrinkwrap.json",
308
+ "pnpm-lock.yaml",
309
+ "yarn.lock",
310
+ "bun.lock",
311
+ "bun.lockb"
312
+ ];
313
+ const WEAK_MARKERS = ["package.json"];
314
+ const DIAG_AFTERPACK_DIR_IN_OUTPUT = "DIAG_AFTERPACK_DIR_IN_OUTPUT";
315
+ const DIAG_RECEIPT_UNWRITABLE = "DIAG_RECEIPT_UNWRITABLE";
316
+ var AfterpackFilesError = class extends Error {
317
+ code;
318
+ summary;
319
+ fix;
320
+ constructor(code, summary, fix) {
321
+ super(`${summary} ${fix}`);
322
+ this.name = "AfterpackFilesError";
323
+ this.code = code;
324
+ this.summary = summary;
325
+ this.fix = fix;
326
+ }
327
+ };
328
+ function realPath(path) {
329
+ const resolved = (0, node_path.resolve)(path);
330
+ try {
331
+ return node_fs.realpathSync.native(resolved);
332
+ } catch {
333
+ const parent = (0, node_path.dirname)(resolved);
334
+ return parent === resolved ? resolved : (0, node_path.join)(realPath(parent), (0, node_path.basename)(resolved));
335
+ }
336
+ }
337
+ function isWithinDir(dir, path) {
338
+ const rel = (0, node_path.relative)(dir, path);
339
+ return rel === "" || !rel.startsWith("..") && !(0, node_path.isAbsolute)(rel);
340
+ }
341
+ function markerIn(dir, markers) {
342
+ return markers.find((name) => (0, node_fs.existsSync)((0, node_path.join)(dir, name))) ?? null;
343
+ }
344
+ function nearestMarker(start, markers) {
345
+ for (let current = start;;) {
346
+ const marker = markerIn(current, markers);
347
+ if (marker) return {
348
+ root: current,
349
+ marker
350
+ };
351
+ const parent = (0, node_path.dirname)(current);
352
+ if (parent === current) return null;
353
+ current = parent;
354
+ }
355
+ }
356
+ function afterpackHome(buildDir, options = {}) {
357
+ const realBuildDir = realPath(buildDir);
358
+ const ownMarker = options.fileTarget ? markerIn(realBuildDir, STRONG_MARKERS) : null;
359
+ if (ownMarker !== null) return {
360
+ dir: (0, node_path.join)(realBuildDir, AFTERPACK_DIR),
361
+ projectRoot: realBuildDir,
362
+ marker: ownMarker,
363
+ strong: true,
364
+ buildDir: realBuildDir
365
+ };
366
+ const start = (0, node_path.dirname)(realBuildDir);
367
+ const strong = nearestMarker(start, STRONG_MARKERS);
368
+ const found = strong ?? nearestMarker(start, WEAK_MARKERS);
369
+ const projectRoot = found?.root ?? start;
370
+ const dir = (0, node_path.join)(projectRoot, AFTERPACK_DIR);
371
+ 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.");
372
+ return {
373
+ dir,
374
+ projectRoot,
375
+ marker: found?.marker ?? null,
376
+ strong: strong !== null,
377
+ buildDir: realBuildDir
378
+ };
379
+ }
380
+ function describeUnanchoredHome(home) {
381
+ if (home.marker !== null) return null;
382
+ return `no lockfile, afterpack.json, .git or package.json above ${home.buildDir}, so AfterPack keeps its files beside it, in ${home.dir}`;
383
+ }
384
+
300
385
  //#endregion
301
386
  //#region src/paths.ts
302
387
  const COMBINED_PROTECTION_MAP_NAME = "protectionMap.html";
@@ -329,7 +414,6 @@ function findUpward(startDir, fileName, options = {}) {
329
414
 
330
415
  //#endregion
331
416
  //#region src/artifacts.ts
332
- const AFTERPACK_DIR = ".afterpack";
333
417
  const AFTERPACK_GITIGNORE_CONTENT = "*\n";
334
418
  const PUBLIC_SEGMENTS = new Set([
335
419
  "public",
@@ -355,7 +439,7 @@ function appendSourceMappingURL(code, mapPath) {
355
439
  function writeArtifacts(input) {
356
440
  const { outPath, code, sourceMapJson, protectionMapJson, originalSource, policy } = input;
357
441
  const mode = input.mode ?? "single";
358
- const afterpackDir = input.afterpackDir ?? AFTERPACK_DIR;
442
+ const afterpackDir = input.afterpackDir;
359
443
  const logger = input.logger ?? DEFAULT_LOGGER;
360
444
  const hash = policy.backup && originalSource != null ? shortHash(originalSource) : void 0;
361
445
  const paths = resolveArtifactPaths(outPath, mode, hash);
@@ -713,7 +797,7 @@ function buildProjectFileTree(files) {
713
797
  }
714
798
  function writeCombinedProtectionMap(input) {
715
799
  const { buildDir, docs, policy } = input;
716
- const afterpackDir = input.afterpackDir ?? AFTERPACK_DIR;
800
+ const afterpackDir = input.afterpackDir;
717
801
  const logger = input.logger ?? DEFAULT_LOGGER;
718
802
  if (!policy.protectionMap || docs.length === 0) return null;
719
803
  (0, node_fs.mkdirSync)(afterpackDir, { recursive: true });
@@ -991,7 +1075,7 @@ const CONFIG_KEYS = [
991
1075
  tier: "free",
992
1076
  surface: "engine",
993
1077
  item: { kind: "boolean" },
994
- default: "true in development when an input map exists; false in production"
1078
+ default: "false; true in development mode when an input map exists"
995
1079
  },
996
1080
  {
997
1081
  path: "sourceMap.sourcesContent",
@@ -1000,7 +1084,7 @@ const CONFIG_KEYS = [
1000
1084
  tier: "free",
1001
1085
  surface: "engine",
1002
1086
  item: { kind: "boolean" },
1003
- default: "true in development; false in production"
1087
+ default: "false; true in development mode"
1004
1088
  },
1005
1089
  {
1006
1090
  path: "sourceMap.emitUrl",
@@ -1009,7 +1093,7 @@ const CONFIG_KEYS = [
1009
1093
  tier: "free",
1010
1094
  surface: "build",
1011
1095
  item: { kind: "boolean" },
1012
- default: "true in development; false in production"
1096
+ default: "false; true in development mode"
1013
1097
  },
1014
1098
  {
1015
1099
  path: "protectionMap.enabled",
@@ -1148,7 +1232,7 @@ const CONFIG_KEYS = [
1148
1232
  kind: "enum",
1149
1233
  values: BUILD_MODE_VALUES
1150
1234
  },
1151
- default: "detected from the environment"
1235
+ default: "production, unless NODE_ENV is development"
1152
1236
  },
1153
1237
  {
1154
1238
  path: "directives.enabled",
@@ -1196,15 +1280,6 @@ const CONFIG_KEYS = [
1196
1280
  item: { kind: "boolean" },
1197
1281
  default: "true"
1198
1282
  },
1199
- {
1200
- path: "allowUnobfuscated",
1201
- shape: "scalar",
1202
- scope: "program",
1203
- tier: "free",
1204
- surface: "build",
1205
- item: { kind: "boolean" },
1206
- default: "false"
1207
- },
1208
1283
  {
1209
1284
  path: "key",
1210
1285
  shape: "scalar",
@@ -1278,8 +1353,8 @@ function unknownKeyMessage(path, surface) {
1278
1353
  if (group$1 && group$1.length > 0) {
1279
1354
  const list = group$1.map((child) => `\`${child}\``).join(", ");
1280
1355
  const tail$1 = group$1.length === 1 ? `did you mean ${list}?` : `its keys are ${list}`;
1281
- const canonical = PREFIX_BY_NORMALIZED.get(normalizeKey(path));
1282
- const enabled = canonical ? groupBooleanKey(canonical) : void 0;
1356
+ const canonical$1 = PREFIX_BY_NORMALIZED.get(normalizeKey(path));
1357
+ const enabled = canonical$1 ? groupBooleanKey(canonical$1) : void 0;
1283
1358
  const rule = enabled ? `; a boolean here means \`${enabled.path}\`` : "";
1284
1359
  return `\`${path}\` is a group of configuration keys, not a key itself (${surface}) — ${tail$1}${rule}`;
1285
1360
  }
@@ -1558,7 +1633,6 @@ function toPluginOptions(config) {
1558
1633
  backup: read("build.backup"),
1559
1634
  mode: read("build.mode")
1560
1635
  }),
1561
- allowUnobfuscated: read("allowUnobfuscated"),
1562
1636
  telemetry: set({ enabled: read("telemetry.enabled") })
1563
1637
  },
1564
1638
  seed: read("seed"),
@@ -1614,6 +1688,15 @@ function decodeDataUri(url) {
1614
1688
  return null;
1615
1689
  }
1616
1690
  }
1691
+ function localSourceMapPath(jsPath, url) {
1692
+ if (url.startsWith("data:") || isRemoteSourceMappingURL(url)) return null;
1693
+ const path = url.replace(/[?#].*$/, "");
1694
+ try {
1695
+ return (0, node_path.isAbsolute)(path) ? path : (0, node_path.resolve)((0, node_path.dirname)(jsPath), decodeURIComponent(path));
1696
+ } catch {
1697
+ return null;
1698
+ }
1699
+ }
1617
1700
  function discoverInputSourceMap(jsPath, code) {
1618
1701
  const adjacent = `${jsPath}.map`;
1619
1702
  if ((0, node_fs.existsSync)(adjacent)) try {
@@ -1628,20 +1711,81 @@ function discoverInputSourceMap(jsPath, code) {
1628
1711
  const url = extractSourceMappingURL(source);
1629
1712
  if (url == null) return null;
1630
1713
  if (url.startsWith("data:")) return decodeDataUri(url);
1631
- if (isRemoteSourceMappingURL(url)) return null;
1632
- let mapPath;
1714
+ const mapPath = localSourceMapPath(jsPath, url);
1715
+ if (mapPath == null || !(0, node_fs.existsSync)(mapPath)) return null;
1633
1716
  try {
1634
- mapPath = (0, node_path.isAbsolute)(url) ? url : (0, node_path.resolve)((0, node_path.dirname)(jsPath), decodeURIComponent(url));
1717
+ return (0, node_fs.readFileSync)(mapPath, "utf8");
1635
1718
  } catch {
1636
1719
  return null;
1637
1720
  }
1638
- if (!(0, node_fs.existsSync)(mapPath)) return null;
1721
+ }
1722
+ function bundlerSourceMapPaths(jsPath, code, root) {
1723
+ const candidates = [`${jsPath}.map`];
1724
+ for (const match of code.matchAll(SOURCE_MAPPING_URL_RE)) {
1725
+ const url = match[1];
1726
+ const local = localSourceMapPath(jsPath, url);
1727
+ if (local != null) candidates.push(local);
1728
+ if (url.startsWith("/") && !url.startsWith("//")) try {
1729
+ candidates.push((0, node_path.resolve)(root, `.${decodeURIComponent(url.replace(/[?#].*$/, ""))}`));
1730
+ } catch {}
1731
+ }
1732
+ return containedSourceMaps(candidates, root);
1733
+ }
1734
+ function realpathOrNull(path) {
1639
1735
  try {
1640
- return (0, node_fs.readFileSync)(mapPath, "utf8");
1736
+ return (0, node_fs.realpathSync)(path);
1641
1737
  } catch {
1642
1738
  return null;
1643
1739
  }
1644
1740
  }
1741
+ function withinRealDir(dir, root) {
1742
+ const rootReal = realpathOrNull(root);
1743
+ const real = realpathOrNull(dir);
1744
+ if (rootReal == null || real == null) return false;
1745
+ if (real === rootReal) return true;
1746
+ return real.startsWith(rootReal.endsWith(node_path.sep) ? rootReal : `${rootReal}${node_path.sep}`);
1747
+ }
1748
+ function containedSourceMaps(paths, root) {
1749
+ const found = new Set();
1750
+ for (const path of paths) {
1751
+ if (!path.endsWith(".map")) continue;
1752
+ const lexical = (0, node_path.resolve)(path);
1753
+ if (!withinRealDir((0, node_path.dirname)(lexical), root)) continue;
1754
+ try {
1755
+ const stat = (0, node_fs.lstatSync)(lexical);
1756
+ if (stat.isFile() || stat.isSymbolicLink()) found.add(lexical);
1757
+ } catch {}
1758
+ }
1759
+ return [...found];
1760
+ }
1761
+ function removeSourceMaps(paths, label) {
1762
+ let removed = 0;
1763
+ for (const path of paths) try {
1764
+ (0, node_fs.unlinkSync)(path);
1765
+ removed++;
1766
+ } catch (error) {
1767
+ if (error.code === "ENOENT") continue;
1768
+ throw new Error(`[${label}] could not remove the source map ${path}, refusing to ship it: ${error}`);
1769
+ }
1770
+ return removed;
1771
+ }
1772
+ function stripCssSourceMappingURLs(paths) {
1773
+ let stripped = 0;
1774
+ for (const path of paths) {
1775
+ let css;
1776
+ try {
1777
+ css = (0, node_fs.readFileSync)(path, "utf8");
1778
+ } catch (error) {
1779
+ if (error.code === "ENOENT") continue;
1780
+ throw error;
1781
+ }
1782
+ const without = withoutCssSourceMappingURL(css);
1783
+ if (without === css) continue;
1784
+ (0, node_fs.writeFileSync)(path, without);
1785
+ stripped++;
1786
+ }
1787
+ return stripped;
1788
+ }
1645
1789
 
1646
1790
  //#endregion
1647
1791
  //#region src/bundle.ts
@@ -1673,6 +1817,39 @@ function sourceTypeForBundle(format, entries) {
1673
1817
  for (const entry of entries) if (entry.type !== "chunk") return void 0;
1674
1818
  return sourceTypeForOutputFormat(format);
1675
1819
  }
1820
+ const COMPRESSED_SIBLING = /\.(gz|br|zst|zz|deflate)$/;
1821
+ function entryBytes(entry) {
1822
+ if (entry.type === "chunk") return entry.code === void 0 ? null : Buffer.from(entry.code);
1823
+ if (typeof entry.source === "string") return Buffer.from(entry.source);
1824
+ if (entry.source !== void 0) return Buffer.from(entry.source);
1825
+ return null;
1826
+ }
1827
+ function regenerateCompressedSiblings(bundle, obfuscated, label) {
1828
+ for (const [name, entry] of Object.entries(bundle)) {
1829
+ const match = COMPRESSED_SIBLING.exec(name);
1830
+ if (match === null) continue;
1831
+ const base = name.slice(0, -match[0].length);
1832
+ if (!obfuscated.has(base)) continue;
1833
+ const bytes = entryBytes(bundle[base]);
1834
+ if (bytes === null) continue;
1835
+ if (match[1] === "gz") entry.source = (0, node_zlib.gzipSync)(bytes);
1836
+ else if (match[1] === "br") entry.source = (0, node_zlib.brotliCompressSync)(bytes);
1837
+ 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.`);
1838
+ }
1839
+ }
1840
+ const SRI_PLUGIN_NAME = /subresource|integrity|(?:^|[^a-z])sri(?:[^a-z]|$)/i;
1841
+ function sriPluginRefusal(plugins, label) {
1842
+ const found = (plugins ?? []).find((plugin) => SRI_PLUGIN_NAME.test(plugin?.name ?? ""));
1843
+ if (!found) return null;
1844
+ 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.`;
1845
+ }
1846
+ function unsaltedAssetsWarning(entries, salted) {
1847
+ const fileNames = [];
1848
+ for (const entry of entries.values()) if (entry.type !== "chunk" && !salted.has(entry.fileName)) fileNames.push(entry.fileName);
1849
+ fileNames.sort();
1850
+ if (fileNames.length === 0) return null;
1851
+ 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.`;
1852
+ }
1676
1853
  function dataUri(json) {
1677
1854
  return `data:application/json;charset=utf-8;base64,${Buffer.from(json, "utf8").toString("base64")}`;
1678
1855
  }
@@ -1801,7 +1978,7 @@ function collectJsFiles(target, options = {}) {
1801
1978
  if (!stat.isDirectory()) return isCollectableJs((0, node_path.basename)(target)) ? [target] : [];
1802
1979
  return walkJs(target, options.include ?? [], false, options.onNestedProject);
1803
1980
  }
1804
- function entriesOf(dir) {
1981
+ function entriesOf$1(dir) {
1805
1982
  try {
1806
1983
  return (0, node_fs.readdirSync)(dir, { withFileTypes: true });
1807
1984
  } catch {
@@ -1820,12 +1997,13 @@ function isNestedProject(dir) {
1820
1997
  }
1821
1998
  function walkJs(dir, include, readmitted, onNestedProject) {
1822
1999
  const out = [];
1823
- for (const entry of entriesOf(dir)) {
2000
+ for (const entry of entriesOf$1(dir)) {
1824
2001
  const name = entry.name;
1825
2002
  const full = (0, node_path.join)(dir, name);
1826
2003
  const kind = kindOf(entry, full);
1827
2004
  if (kind === null) continue;
1828
2005
  if (kind === "dir") {
2006
+ if (name === AFTERPACK_DIR) continue;
1829
2007
  const skipped = name === NODE_MODULES;
1830
2008
  if (!skipped && !readmitted && isNestedProject(full)) {
1831
2009
  onNestedProject?.(full);
@@ -1844,13 +2022,15 @@ const SOURCE_MAP_RE = /\.(?:[cm]?js|css)\.map$/;
1844
2022
  function collectFiles(dir, accept) {
1845
2023
  if (!(0, node_fs.existsSync)(dir)) return [];
1846
2024
  const out = [];
1847
- for (const entry of entriesOf(dir)) {
2025
+ for (const entry of entriesOf$1(dir)) {
1848
2026
  const name = entry.name;
1849
2027
  const full = (0, node_path.join)(dir, name);
1850
2028
  const kind = kindOf(entry, full);
1851
2029
  if (kind === null) continue;
1852
- if (kind === "dir") out.push(...collectFiles(full, accept));
1853
- else if (accept(name)) out.push(full);
2030
+ if (kind === "dir") {
2031
+ if (name === NODE_MODULES || name === AFTERPACK_DIR || isNestedProject(full)) continue;
2032
+ out.push(...collectFiles(full, accept));
2033
+ } else if (accept(name)) out.push(full);
1854
2034
  }
1855
2035
  return out;
1856
2036
  }
@@ -2357,10 +2537,10 @@ function spaceFormIssue(path, raw, surface) {
2357
2537
  }
2358
2538
  function kebabIssue(key, surface) {
2359
2539
  const suggestion = suggestKey(key);
2360
- const canonical = suggestion ? ` — the canonical form is \`${spellKey(suggestion, surface)}\`` : " — keys are dot-delimited camelCase";
2540
+ const canonical$1 = suggestion ? ` — the canonical form is \`${spellKey(suggestion, surface)}\`` : " — keys are dot-delimited camelCase";
2361
2541
  return {
2362
2542
  path: key,
2363
- message: `kebab-case is not a configuration key (\`${spellKey(key, surface)}\`)${canonical}`
2543
+ message: `kebab-case is not a configuration key (\`${spellKey(key, surface)}\`)${canonical$1}`
2364
2544
  };
2365
2545
  }
2366
2546
  function parseAssignment(key, raw, surface) {
@@ -2699,7 +2879,7 @@ function reportDiagnostics(input) {
2699
2879
  //#region src/policy.ts
2700
2880
  function detectProduction(env = {}, opts = {}) {
2701
2881
  if (opts.build?.mode !== void 0) return opts.build.mode === "production";
2702
- return env.NODE_ENV === "production" || env.CI === "true";
2882
+ return env.NODE_ENV !== "development";
2703
2883
  }
2704
2884
  function resolveReportPolicy(env = {}, userOpts = {}, signals = {}) {
2705
2885
  const isProduction = detectProduction(env, userOpts);
@@ -3266,123 +3446,883 @@ function captureDirectiveRegions(inputs, handAuthored, enabled = true) {
3266
3446
  }
3267
3447
 
3268
3448
  //#endregion
3269
- //#region src/git.ts
3270
- const GIT_COMMIT_SHA_PATTERN = /^[0-9a-f]{7,40}$/;
3271
- const GIT_REF_PATTERN = /^[A-Za-z0-9._\-/+]{1,200}$/;
3272
- function sanitizeCommitSha(value) {
3273
- if (typeof value !== "string") return null;
3274
- const sha = value.trim().toLowerCase();
3275
- return GIT_COMMIT_SHA_PATTERN.test(sha) ? sha : null;
3276
- }
3277
- function sanitizeGitRef(value) {
3278
- if (typeof value !== "string") return null;
3279
- const ref = value.trim();
3280
- return GIT_REF_PATTERN.test(ref) ? ref : null;
3281
- }
3282
- function contextFrom(rawSha, rawRef) {
3283
- const commitSha = sanitizeCommitSha(rawSha);
3284
- const ref = sanitizeGitRef(rawRef);
3285
- if (commitSha === null && ref === null) return null;
3286
- const context = {};
3287
- if (commitSha !== null) context.commitSha = commitSha;
3288
- if (ref !== null) context.ref = ref;
3289
- return context;
3290
- }
3291
- const CI_SOURCES = [
3292
- ["GITHUB_SHA", "GITHUB_REF_NAME"],
3293
- ["CI_COMMIT_SHA", "CI_COMMIT_REF_NAME"],
3294
- ["VERCEL_GIT_COMMIT_SHA", "VERCEL_GIT_COMMIT_REF"],
3295
- ["CF_PAGES_COMMIT_SHA", "CF_PAGES_BRANCH"],
3296
- ["GIT_COMMIT", "BRANCH_NAME"]
3297
- ];
3298
- function ciGitContext(env) {
3299
- for (const [shaVar, refVar] of CI_SOURCES) {
3300
- const context = contextFrom(env[shaVar], env[refVar]);
3301
- if (context !== null) return context;
3302
- }
3303
- return null;
3449
+ //#region src/seed.ts
3450
+ function randomSeed() {
3451
+ const b = (0, node_crypto.randomBytes)(8);
3452
+ const hi = b.readUInt32BE(0) & 2097151;
3453
+ const lo = b.readUInt32BE(4);
3454
+ return hi * 4294967296 + lo;
3304
3455
  }
3305
- const GIT_PROBE_TIMEOUT_MS = 2e3;
3306
- function localGitContext(cwd) {
3307
- let lines;
3456
+ function gitHead() {
3308
3457
  try {
3309
- const out = (0, node_child_process.execFileSync)("git", [
3310
- "rev-parse",
3311
- "HEAD",
3312
- "--abbrev-ref",
3313
- "HEAD"
3314
- ], {
3315
- cwd,
3316
- stdio: [
3317
- "ignore",
3318
- "pipe",
3319
- "ignore"
3320
- ],
3321
- timeout: GIT_PROBE_TIMEOUT_MS,
3322
- maxBuffer: 64 * 1024
3323
- }).toString();
3324
- lines = out.split("\n").map((line) => line.trim());
3458
+ const out = (0, node_child_process.execFileSync)("git", ["rev-parse", "HEAD"], { stdio: [
3459
+ "ignore",
3460
+ "pipe",
3461
+ "ignore"
3462
+ ] }).toString().trim();
3463
+ return /^[0-9a-f]{7,64}$/i.test(out) ? out : null;
3325
3464
  } catch {
3326
3465
  return null;
3327
3466
  }
3328
- const ref = lines[1] === "HEAD" ? null : lines[1];
3329
- return contextFrom(lines[0], ref);
3330
3467
  }
3331
- function detectGitContext(explicit, deps = {}) {
3332
- if (explicit) {
3333
- const declared = contextFrom(explicit.commitSha, explicit.ref);
3334
- if (declared !== null) return declared;
3468
+ const SEED_ENV_VAR = "AFTERPACK_SEED";
3469
+ function parseSeedValue(raw) {
3470
+ return /^-?\d+$/.test(raw) ? Number(raw) : raw;
3471
+ }
3472
+ const SEED_STATE = Symbol.for("afterpack.integration-utils.seed-sessions");
3473
+ function sharedSeedState() {
3474
+ const holder = globalThis;
3475
+ holder[SEED_STATE] ??= {
3476
+ sessions: new Map(),
3477
+ ownEnvExports: []
3478
+ };
3479
+ return holder[SEED_STATE];
3480
+ }
3481
+ const { sessions, ownEnvExports } = sharedSeedState();
3482
+ function isOwnEnvExport(env, value) {
3483
+ return ownEnvExports.some((e) => e.env === env && e.value === value);
3484
+ }
3485
+ function openGeneration(root, leg) {
3486
+ let session = sessions.get(root);
3487
+ if (!session) {
3488
+ session = {
3489
+ seed: void 0,
3490
+ generation: 1,
3491
+ legs: [],
3492
+ resolvedByLeg: new Map(),
3493
+ gitFallbackWarned: false
3494
+ };
3495
+ sessions.set(root, session);
3496
+ } else if (session.legs.includes(leg)) {
3497
+ session.seed = void 0;
3498
+ session.generation += 1;
3499
+ session.legs = [];
3500
+ session.resolvedByLeg.clear();
3501
+ session.gitFallbackWarned = false;
3335
3502
  }
3336
- const ci = ciGitContext(deps.env ?? process.env);
3337
- if (ci !== null) return ci;
3338
- return (deps.localGit ?? localGitContext)(deps.cwd);
3503
+ session.legs.push(leg);
3504
+ return session;
3339
3505
  }
3340
-
3341
- //#endregion
3342
- //#region src/map-color.ts
3343
- const UTF8 = new TextEncoder();
3344
- const utf8Len = (s) => UTF8.encode(s).length;
3345
- const NON_ASCII = /[\u0080-\uFFFF]/;
3346
- const HIGH_SURROGATE_START = 55296;
3347
- const HIGH_SURROGATE_END = 56319;
3348
- const LOW_SURROGATE_START = 56320;
3349
- const LOW_SURROGATE_END = 57343;
3350
- function charToByteTable(line) {
3351
- const table = new Array(line.length + 1);
3352
- let bytes = 0;
3353
- let i = 0;
3354
- while (i < line.length) {
3355
- table[i] = bytes;
3356
- const code = line.charCodeAt(i);
3357
- if (code < 128) {
3358
- bytes += 1;
3359
- i += 1;
3360
- continue;
3361
- }
3362
- if (code < 2048) {
3363
- bytes += 2;
3364
- i += 1;
3365
- continue;
3366
- }
3367
- if (code >= HIGH_SURROGATE_START && code <= HIGH_SURROGATE_END && i + 1 < line.length) {
3368
- const low = line.charCodeAt(i + 1);
3369
- if (low >= LOW_SURROGATE_START && low <= LOW_SURROGATE_END) {
3370
- table[i + 1] = bytes + 3;
3371
- bytes += 4;
3372
- i += 2;
3373
- continue;
3374
- }
3506
+ function resolveWithinSession(input, session, env, deps) {
3507
+ if (typeof input === "number") return {
3508
+ seed: input,
3509
+ origin: "option"
3510
+ };
3511
+ if (typeof input === "string" && input !== "git") return {
3512
+ seed: input,
3513
+ origin: "option"
3514
+ };
3515
+ if (input === "git") {
3516
+ const head = (deps.gitHead ?? gitHead)();
3517
+ if (head) return {
3518
+ seed: head,
3519
+ origin: "git"
3520
+ };
3521
+ if (!session.gitFallbackWarned) {
3522
+ session.gitFallbackWarned = true;
3523
+ (deps.warn ?? ((m) => console.warn(m)))("[afterpack] seed \"git\": no git repository / HEAD found; using a fresh random seed for this build.");
3375
3524
  }
3376
- bytes += 3;
3377
- i += 1;
3378
3525
  }
3379
- table[line.length] = bytes;
3380
- return table;
3526
+ const fromEnv = env[SEED_ENV_VAR];
3527
+ if (fromEnv != null && fromEnv !== "" && !isOwnEnvExport(env, fromEnv)) return {
3528
+ seed: parseSeedValue(fromEnv),
3529
+ origin: "env"
3530
+ };
3531
+ if (session.seed !== void 0) return {
3532
+ seed: session.seed,
3533
+ origin: "session"
3534
+ };
3535
+ return {
3536
+ seed: (deps.randomSeed ?? randomSeed)(),
3537
+ origin: "fresh"
3538
+ };
3381
3539
  }
3382
- var ChunkByteIndex = class {
3383
- starts;
3384
- ascii;
3385
- tables;
3540
+ function resolveBuildSeed(input, scope, deps = {}) {
3541
+ const env = deps.env ?? process.env;
3542
+ const session = openGeneration(scope.root, scope.leg);
3543
+ const { seed, origin } = resolveWithinSession(input, session, env, deps);
3544
+ if (origin === "env" || origin === "fresh") session.seed = seed;
3545
+ if (origin === "fresh" && (deps.exportToEnv ?? true)) {
3546
+ const value = String(seed);
3547
+ env[SEED_ENV_VAR] = value;
3548
+ const stale = ownEnvExports.findIndex((e) => e.env === env);
3549
+ if (stale >= 0) ownEnvExports.splice(stale, 1);
3550
+ ownEnvExports.push({
3551
+ env,
3552
+ value
3553
+ });
3554
+ }
3555
+ const prior = [...session.resolvedByLeg].find(([, s]) => s !== seed);
3556
+ session.resolvedByLeg.set(scope.leg, seed);
3557
+ return {
3558
+ seed,
3559
+ origin,
3560
+ legs: [...session.legs],
3561
+ generation: session.generation,
3562
+ mismatch: prior && session.generation === 1 ? {
3563
+ leg: prior[0],
3564
+ seed: prior[1]
3565
+ } : null
3566
+ };
3567
+ }
3568
+
3569
+ //#endregion
3570
+ //#region src/telemetry.ts
3571
+ const API_URL_ENV_VAR$1 = "AFTERPACK_API_URL";
3572
+ const DEFAULT_API_URL = "https://api.afterpack.dev";
3573
+ const TELEMETRY_ENDPOINT_PATH = "/v1/telemetry/build";
3574
+ const TELEMETRY_PAYLOAD_VERSION = 1;
3575
+ const TELEMETRY_TIMEOUT_MS = 1500;
3576
+ const INSTALL_ID_ROTATION_DAYS = 30;
3577
+ const TELEMETRY_DIAGNOSTIC_LIMIT = 20;
3578
+ const TELEMETRY_STATE_FILE = (0, node_path.join)((0, node_os.homedir)(), ".afterpack", "telemetry.json");
3579
+ const TOKEN_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
3580
+ const DATA_FIELD_WHITELIST = {
3581
+ outputUnparseable: ["parserErrorKind", "outputByteOffset"],
3582
+ parseError: ["parserErrorKind"],
3583
+ engineBug: [
3584
+ "phase",
3585
+ "transform",
3586
+ "nodeKind"
3587
+ ],
3588
+ inflationBudget: [
3589
+ "target",
3590
+ "achieved",
3591
+ "budgetRatio",
3592
+ "inflationRatio"
3593
+ ],
3594
+ configParse: [
3595
+ "category",
3596
+ "line",
3597
+ "column"
3598
+ ]
3599
+ };
3600
+ function resolveTelemetryEnabled(option, env = {}) {
3601
+ if (option !== void 0) return option;
3602
+ return !(env.NODE_ENV === "test" || env.VITEST);
3603
+ }
3604
+ const FRAMEWORK_ENTRIES = [
3605
+ {
3606
+ label: "afterpack",
3607
+ name: "cli"
3608
+ },
3609
+ {
3610
+ label: "afterpack-angular",
3611
+ name: "angular",
3612
+ pkg: "@angular/core"
3613
+ },
3614
+ {
3615
+ label: "afterpack-esbuild",
3616
+ name: "esbuild",
3617
+ pkg: "esbuild"
3618
+ },
3619
+ {
3620
+ label: "afterpack-next",
3621
+ name: "next",
3622
+ pkg: "next"
3623
+ },
3624
+ {
3625
+ label: "afterpack-rollup",
3626
+ name: "rollup",
3627
+ pkg: "rollup"
3628
+ },
3629
+ {
3630
+ label: "afterpack-vite",
3631
+ name: "vite",
3632
+ pkg: "vite"
3633
+ },
3634
+ {
3635
+ label: "afterpack-webpack",
3636
+ name: "webpack",
3637
+ pkg: "webpack"
3638
+ }
3639
+ ];
3640
+ const FRAMEWORK_BY_LABEL = new Map(FRAMEWORK_ENTRIES.map((e) => [e.label, e.name]));
3641
+ const FRAMEWORK_PACKAGE_BY_NAME = new Map(FRAMEWORK_ENTRIES.flatMap((e) => e.pkg ? [[e.name, e.pkg]] : []));
3642
+ function frameworkFromLabel(label) {
3643
+ return FRAMEWORK_BY_LABEL.get(label.split(":")[0]) ?? "unknown";
3644
+ }
3645
+ const VERSION_RANGE_PATTERN = /^[\sv0-9.\-+*xX^~><=|]{1,32}$/;
3646
+ function detectFrameworkVersion(projectRoot, framework) {
3647
+ const pkgName = FRAMEWORK_PACKAGE_BY_NAME.get(framework);
3648
+ if (!pkgName) return null;
3649
+ let deps;
3650
+ try {
3651
+ const pkg = JSON.parse((0, node_fs.readFileSync)((0, node_path.join)(projectRoot, "package.json"), "utf8"));
3652
+ deps = {
3653
+ ...pkg.dependencies,
3654
+ ...pkg.devDependencies
3655
+ };
3656
+ } catch {
3657
+ return null;
3658
+ }
3659
+ const raw = deps[pkgName];
3660
+ if (typeof raw !== "string") return null;
3661
+ const range = raw.trim();
3662
+ return VERSION_RANGE_PATTERN.test(range) && /[0-9*xX]/.test(range) ? range : null;
3663
+ }
3664
+ function complexityLabel(preset, complexity) {
3665
+ if (preset !== void 0) return preset;
3666
+ return complexity === void 0 ? "default" : "custom";
3667
+ }
3668
+ const FILE_COUNT_BUCKETS = [
3669
+ 1,
3670
+ 5,
3671
+ 20,
3672
+ 100,
3673
+ 500,
3674
+ 2e3
3675
+ ];
3676
+ function fileCountBucket(count) {
3677
+ if (!Number.isFinite(count) || count <= 0) return "0";
3678
+ let lower = 1;
3679
+ for (const upper of FILE_COUNT_BUCKETS) {
3680
+ if (count <= upper) return lower === upper ? `${upper}` : `${lower}-${upper}`;
3681
+ lower = upper + 1;
3682
+ }
3683
+ return `${FILE_COUNT_BUCKETS[FILE_COUNT_BUCKETS.length - 1]}+`;
3684
+ }
3685
+ const DURATION_BUCKETS_MS = [
3686
+ [1e3, "<1s"],
3687
+ [5e3, "1-5s"],
3688
+ [15e3, "5-15s"],
3689
+ [6e4, "15-60s"],
3690
+ [3e5, "60-300s"]
3691
+ ];
3692
+ function durationBucket(ms) {
3693
+ if (!Number.isFinite(ms) || ms < 0) return "unknown";
3694
+ for (const [upper, label] of DURATION_BUCKETS_MS) if (ms < upper) return label;
3695
+ return "300s+";
3696
+ }
3697
+ function safeScalar(value) {
3698
+ if (typeof value === "number") return Number.isFinite(value) ? value : null;
3699
+ if (typeof value === "string") return TOKEN_PATTERN.test(value) ? value : null;
3700
+ return null;
3701
+ }
3702
+ function telemetrySafeData(data) {
3703
+ if (!data || typeof data.kind !== "string") return null;
3704
+ const kind = TOKEN_PATTERN.test(data.kind) ? data.kind : null;
3705
+ if (kind === null) return null;
3706
+ const out = { kind };
3707
+ for (const field of DATA_FIELD_WHITELIST[kind] ?? []) {
3708
+ const value = safeScalar(data[field]);
3709
+ if (value !== null) out[field] = value;
3710
+ }
3711
+ return out;
3712
+ }
3713
+ function telemetrySafeSpan(d) {
3714
+ const span = d.span;
3715
+ if (!span) return null;
3716
+ const start = safeScalar(span.startByte);
3717
+ const end = safeScalar(span.endByte);
3718
+ if (typeof start !== "number" || typeof end !== "number") return null;
3719
+ if (start < 0 || end < 0) return null;
3720
+ return {
3721
+ startByte: start,
3722
+ endByte: end
3723
+ };
3724
+ }
3725
+ function telemetrySafeDiagnostic(d, severity) {
3726
+ return {
3727
+ code: TOKEN_PATTERN.test(d.code) ? d.code : "DIAG_UNKNOWN",
3728
+ severity,
3729
+ span: telemetrySafeSpan(d),
3730
+ data: telemetrySafeData(d.data)
3731
+ };
3732
+ }
3733
+ function buildTelemetryPayload(facts, ctx) {
3734
+ let errorCount = 0;
3735
+ let criticalCount = 0;
3736
+ const alerting = [];
3737
+ for (const d of facts.diagnostics) {
3738
+ if (d.severity !== "error" && d.severity !== "critical") continue;
3739
+ if (d.severity === "critical") criticalCount += 1;
3740
+ else errorCount += 1;
3741
+ alerting.push(telemetrySafeDiagnostic(d, d.severity));
3742
+ }
3743
+ if (alerting.length === 0) return null;
3744
+ const kept = alerting.slice(-TELEMETRY_DIAGNOSTIC_LIMIT);
3745
+ const env = ctx.env ?? {};
3746
+ const runtime = ctx.runtime ?? {
3747
+ node: process.versions.node,
3748
+ platform: process.platform,
3749
+ arch: process.arch
3750
+ };
3751
+ const framework = frameworkFromLabel(facts.label);
3752
+ return {
3753
+ version: TELEMETRY_PAYLOAD_VERSION,
3754
+ installId: ctx.installId,
3755
+ framework,
3756
+ frameworkVersion: detectFrameworkVersion(facts.projectRoot, framework),
3757
+ engineVersion: safeVersion(facts.engineVersion),
3758
+ clientVersion: safeVersion(facts.clientVersion),
3759
+ nodeVersion: safeVersion(runtime.node) ?? "unknown",
3760
+ os: safeToken(runtime.platform),
3761
+ arch: safeToken(runtime.arch),
3762
+ ci: env.CI === "true",
3763
+ complexity: complexityLabel(facts.preset, facts.complexity),
3764
+ fileCountBucket: fileCountBucket(facts.fileCount),
3765
+ durationBucket: durationBucket(facts.durationMs),
3766
+ diagnostics: kept,
3767
+ errorCount,
3768
+ criticalCount,
3769
+ droppedCount: alerting.length - kept.length
3770
+ };
3771
+ }
3772
+ const VERSION_PATTERN = /^[0-9][0-9A-Za-z.\-+]{0,31}$/;
3773
+ function safeVersion(value) {
3774
+ return typeof value === "string" && VERSION_PATTERN.test(value) ? value : null;
3775
+ }
3776
+ function safeToken(value) {
3777
+ return TOKEN_PATTERN.test(value) ? value : "unknown";
3778
+ }
3779
+ const TELEMETRY_NOTICE = [
3780
+ "AfterPack: anonymous build diagnostics are ON (this notice prints once).",
3781
+ "AfterPack: A build that reports an error-level diagnostic (a refused or partial build)",
3782
+ "AfterPack: sends that diagnostic's code, severity, byte offsets and typed engine",
3783
+ "AfterPack: fields, plus engine version, integration, Node version, OS/arch, bucketed",
3784
+ "AfterPack: file counts and durations, and a random install id that rotates every 30",
3785
+ "AfterPack: days.",
3786
+ "AfterPack: It never sends your source, file names, paths, project name, diagnostic",
3787
+ "AfterPack: message text, or exact byte counts. A clean build sends nothing.",
3788
+ "AfterPack: Turn it off with AFTERPACK_telemetry_enabled=false, --telemetry.enabled=false, or",
3789
+ "AfterPack: `telemetry: { enabled: false }` in your config.",
3790
+ "AfterPack: https://www.afterpack.dev/privacy"
3791
+ ];
3792
+ const INSTALL_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
3793
+ const DAY_MS = 24 * 60 * 60 * 1e3;
3794
+ function readState(file, now) {
3795
+ try {
3796
+ const parsed = JSON.parse((0, node_fs.readFileSync)(file, "utf8"));
3797
+ if (typeof parsed.installId === "string" && INSTALL_ID_PATTERN.test(parsed.installId) && typeof parsed.rotatedAt === "number") return {
3798
+ installId: parsed.installId,
3799
+ rotatedAt: parsed.rotatedAt,
3800
+ noticeShownAt: typeof parsed.noticeShownAt === "number" ? parsed.noticeShownAt : 0
3801
+ };
3802
+ } catch {}
3803
+ return {
3804
+ installId: (0, node_crypto.randomUUID)(),
3805
+ rotatedAt: now,
3806
+ noticeShownAt: 0
3807
+ };
3808
+ }
3809
+ function writeState(file, state) {
3810
+ try {
3811
+ (0, node_fs.mkdirSync)((0, node_path.dirname)(file), { recursive: true });
3812
+ (0, node_fs.writeFileSync)(file, `${JSON.stringify(state)}\n`, "utf8");
3813
+ } catch {}
3814
+ }
3815
+ function telemetryUrl(env) {
3816
+ const base = (env[API_URL_ENV_VAR$1] ?? DEFAULT_API_URL).replace(/\/+$/, "");
3817
+ return `${base}${TELEMETRY_ENDPOINT_PATH}`;
3818
+ }
3819
+ const TELEMETRY_BODY_LIMIT = 64 * 1024;
3820
+ async function reportTelemetryNotices(response, logger) {
3821
+ if (!response || response.status !== 202 || typeof response.text !== "function") return;
3822
+ const declared = Number(response.headers?.get?.("content-length"));
3823
+ if (Number.isFinite(declared) && declared > TELEMETRY_BODY_LIMIT) {
3824
+ await response.body?.cancel().catch(() => {});
3825
+ return;
3826
+ }
3827
+ const text = await response.text();
3828
+ if (text.length > TELEMETRY_BODY_LIMIT) return;
3829
+ let body;
3830
+ try {
3831
+ body = JSON.parse(text);
3832
+ } catch {
3833
+ return;
3834
+ }
3835
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return;
3836
+ reportNotices(body.notices, logger);
3837
+ }
3838
+ function createTelemetryReporter(deps = {}) {
3839
+ const env = deps.env ?? process.env;
3840
+ const logger = deps.logger ?? console;
3841
+ const now = deps.now ?? Date.now;
3842
+ const stateFile = deps.stateFile ?? TELEMETRY_STATE_FILE;
3843
+ const timeoutMs = deps.timeoutMs ?? TELEMETRY_TIMEOUT_MS;
3844
+ return async (facts) => {
3845
+ try {
3846
+ const at = now();
3847
+ const state = readState(stateFile, at);
3848
+ let dirty = false;
3849
+ if (at - state.rotatedAt >= INSTALL_ID_ROTATION_DAYS * DAY_MS) {
3850
+ state.installId = (0, node_crypto.randomUUID)();
3851
+ state.rotatedAt = at;
3852
+ dirty = true;
3853
+ }
3854
+ if (state.noticeShownAt === 0) {
3855
+ for (const line of TELEMETRY_NOTICE) logger.log(line);
3856
+ state.noticeShownAt = at;
3857
+ dirty = true;
3858
+ }
3859
+ if (dirty) writeState(stateFile, state);
3860
+ if (facts === null) return;
3861
+ const payload = buildTelemetryPayload(facts, {
3862
+ installId: state.installId,
3863
+ env
3864
+ });
3865
+ if (payload === null) return;
3866
+ const fetchImpl = deps.fetchImpl ?? globalThis.fetch;
3867
+ if (typeof fetchImpl !== "function") return;
3868
+ const response = await fetchImpl(telemetryUrl(env), {
3869
+ method: "POST",
3870
+ headers: { "content-type": "application/json" },
3871
+ body: JSON.stringify(payload),
3872
+ signal: AbortSignal.timeout(timeoutMs)
3873
+ });
3874
+ await reportTelemetryNotices(response, logger);
3875
+ } catch {}
3876
+ };
3877
+ }
3878
+
3879
+ //#endregion
3880
+ //#region src/hash-salt.ts
3881
+ const API_URL_ENV_VAR = "AFTERPACK_API_URL";
3882
+ const VERSION_ENDPOINT_PATH = "/v1/version";
3883
+ const VERSION_PROBE_TIMEOUT_MS = 2e3;
3884
+ function canonical(value) {
3885
+ if (Array.isArray(value)) return value.map(canonical);
3886
+ if (value === null || typeof value !== "object") return value;
3887
+ const out = {};
3888
+ for (const key of Object.keys(value).sort()) {
3889
+ const item = value[key];
3890
+ if (item !== void 0) out[key] = canonical(item);
3891
+ }
3892
+ return out;
3893
+ }
3894
+ function afterpackHashSalt(input) {
3895
+ const payload = JSON.stringify(canonical({
3896
+ salt: "afterpack-output-name/1",
3897
+ seed: String(input.seed),
3898
+ engineVersion: input.engine.engineVersion,
3899
+ nonce: input.engine.nonce,
3900
+ cloud: input.engine.cloud,
3901
+ settings: input.settings
3902
+ }));
3903
+ return (0, node_crypto.createHash)("sha256").update(payload).digest("hex").slice(0, 32);
3904
+ }
3905
+ function isCloudBuild(env) {
3906
+ const key = env.AFTERPACK_KEY;
3907
+ return typeof key === "string" && key.trim() !== "";
3908
+ }
3909
+ function versionEndpoint(env) {
3910
+ const base = (env[API_URL_ENV_VAR] ?? DEFAULT_API_URL).replace(/\/+$/, "");
3911
+ return `${base}${VERSION_ENDPOINT_PATH}`;
3912
+ }
3913
+ async function resolveSaltEngine(env, localEngineVersion, deps = {}) {
3914
+ if (!isCloudBuild(env)) return {
3915
+ engineVersion: localEngineVersion,
3916
+ nonce: null,
3917
+ cloud: false,
3918
+ probedCloudVersion: null,
3919
+ probeFailed: false
3920
+ };
3921
+ const fetchImpl = deps.fetchImpl ?? globalThis.fetch;
3922
+ let probed = null;
3923
+ if (typeof fetchImpl === "function") try {
3924
+ const response = await fetchImpl(versionEndpoint(env), { signal: AbortSignal.timeout(deps.timeoutMs ?? VERSION_PROBE_TIMEOUT_MS) });
3925
+ if (response.ok) {
3926
+ const body = await response.json();
3927
+ if (typeof body.engineVersion === "string" && body.engineVersion !== "") probed = body.engineVersion;
3928
+ }
3929
+ } catch {
3930
+ probed = null;
3931
+ }
3932
+ if (probed === null) return {
3933
+ engineVersion: null,
3934
+ nonce: (0, node_crypto.randomUUID)(),
3935
+ cloud: true,
3936
+ probedCloudVersion: null,
3937
+ probeFailed: true
3938
+ };
3939
+ return {
3940
+ engineVersion: probed,
3941
+ nonce: null,
3942
+ cloud: true,
3943
+ probedCloudVersion: probed,
3944
+ probeFailed: false
3945
+ };
3946
+ }
3947
+ 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.";
3948
+ function saltSettings(settings, extra = {}) {
3949
+ const { seed: _seed, diagnostics: _diagnostics, artifactOptions, engineConfig,...rest } = settings;
3950
+ const { git: _git, telemetry: _telemetry,...output } = artifactOptions ?? {};
3951
+ const { seed: _engineSeed,...engine } = engineConfig ?? {};
3952
+ return {
3953
+ ...rest,
3954
+ engineConfig: engine,
3955
+ artifactOptions: output,
3956
+ ...extra
3957
+ };
3958
+ }
3959
+ function reportPolicySaltBits(env, artifactOptions, hasBundlerSourcemap) {
3960
+ const policy = resolveReportPolicy(env, artifactOptions ?? {}, { hasBundlerSourcemap });
3961
+ return {
3962
+ sourceMap: policy.sourceMap,
3963
+ emitSourceMappingURL: policy.emitSourceMappingURL
3964
+ };
3965
+ }
3966
+ async function prepareHashSalt(input) {
3967
+ const env = input.env ?? process.env;
3968
+ const resolvedSeed = resolveBuildSeed(input.seed, {
3969
+ root: input.root,
3970
+ leg: input.leg
3971
+ }, {
3972
+ env,
3973
+ warn: input.warn
3974
+ });
3975
+ const engine = await resolveSaltEngine(env, input.localEngineVersion, { fetchImpl: input.fetchImpl });
3976
+ if (engine.probeFailed) input.warn?.(PROBE_FAILED_WARNING);
3977
+ return {
3978
+ resolvedSeed,
3979
+ engine,
3980
+ salt: afterpackHashSalt({
3981
+ seed: resolvedSeed.seed,
3982
+ engine,
3983
+ settings: input.settings
3984
+ })
3985
+ };
3986
+ }
3987
+ async function readEngineVersion(engine) {
3988
+ try {
3989
+ return await engine.version?.() ?? null;
3990
+ } catch {
3991
+ return null;
3992
+ }
3993
+ }
3994
+ function cloudEngineMismatch(engine, batchEngineVersion) {
3995
+ if (!engine.cloud || engine.probedCloudVersion === null) return null;
3996
+ if (batchEngineVersion === null) return null;
3997
+ if (batchEngineVersion === engine.probedCloudVersion) return null;
3998
+ 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.`;
3999
+ }
4000
+
4001
+ //#endregion
4002
+ //#region src/git.ts
4003
+ const GIT_COMMIT_SHA_PATTERN = /^[0-9a-f]{7,40}$/;
4004
+ const GIT_REF_PATTERN = /^[A-Za-z0-9._\-/+]{1,200}$/;
4005
+ function sanitizeCommitSha(value) {
4006
+ if (typeof value !== "string") return null;
4007
+ const sha = value.trim().toLowerCase();
4008
+ return GIT_COMMIT_SHA_PATTERN.test(sha) ? sha : null;
4009
+ }
4010
+ function sanitizeGitRef(value) {
4011
+ if (typeof value !== "string") return null;
4012
+ const ref = value.trim();
4013
+ return GIT_REF_PATTERN.test(ref) ? ref : null;
4014
+ }
4015
+ function contextFrom(rawSha, rawRef) {
4016
+ const commitSha = sanitizeCommitSha(rawSha);
4017
+ const ref = sanitizeGitRef(rawRef);
4018
+ if (commitSha === null && ref === null) return null;
4019
+ const context = {};
4020
+ if (commitSha !== null) context.commitSha = commitSha;
4021
+ if (ref !== null) context.ref = ref;
4022
+ return context;
4023
+ }
4024
+ const CI_SOURCES = [
4025
+ ["GITHUB_SHA", "GITHUB_REF_NAME"],
4026
+ ["CI_COMMIT_SHA", "CI_COMMIT_REF_NAME"],
4027
+ ["VERCEL_GIT_COMMIT_SHA", "VERCEL_GIT_COMMIT_REF"],
4028
+ ["CF_PAGES_COMMIT_SHA", "CF_PAGES_BRANCH"],
4029
+ ["GIT_COMMIT", "BRANCH_NAME"]
4030
+ ];
4031
+ function ciGitContext(env) {
4032
+ for (const [shaVar, refVar] of CI_SOURCES) {
4033
+ const context = contextFrom(env[shaVar], env[refVar]);
4034
+ if (context !== null) return context;
4035
+ }
4036
+ return null;
4037
+ }
4038
+ const GIT_PROBE_TIMEOUT_MS = 2e3;
4039
+ function localGitContext(cwd) {
4040
+ let lines;
4041
+ try {
4042
+ const out = (0, node_child_process.execFileSync)("git", [
4043
+ "rev-parse",
4044
+ "HEAD",
4045
+ "--abbrev-ref",
4046
+ "HEAD"
4047
+ ], {
4048
+ cwd,
4049
+ stdio: [
4050
+ "ignore",
4051
+ "pipe",
4052
+ "ignore"
4053
+ ],
4054
+ timeout: GIT_PROBE_TIMEOUT_MS,
4055
+ maxBuffer: 64 * 1024
4056
+ }).toString();
4057
+ lines = out.split("\n").map((line) => line.trim());
4058
+ } catch {
4059
+ return null;
4060
+ }
4061
+ const ref = lines[1] === "HEAD" ? null : lines[1];
4062
+ return contextFrom(lines[0], ref);
4063
+ }
4064
+ function detectGitContext(explicit, deps = {}) {
4065
+ if (explicit) {
4066
+ const declared = contextFrom(explicit.commitSha, explicit.ref);
4067
+ if (declared !== null) return declared;
4068
+ }
4069
+ const ci = ciGitContext(deps.env ?? process.env);
4070
+ if (ci !== null) return ci;
4071
+ return (deps.localGit ?? localGitContext)(deps.cwd);
4072
+ }
4073
+
4074
+ //#endregion
4075
+ //#region src/hashed-names.ts
4076
+ const LOWER_HEX = "0123456789abcdef";
4077
+ const BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
4078
+ const UPPER_ALNUM = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
4079
+ const LOWER_ALNUM = "0123456789abcdefghijklmnopqrstuvwxyz";
4080
+ const ALNUM = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
4081
+ const MIN_TOKEN_LENGTH = 6;
4082
+ const BINARY_EXTENSIONS = new Set([
4083
+ ".png",
4084
+ ".jpg",
4085
+ ".jpeg",
4086
+ ".gif",
4087
+ ".webp",
4088
+ ".avif",
4089
+ ".ico",
4090
+ ".bmp",
4091
+ ".woff",
4092
+ ".woff2",
4093
+ ".ttf",
4094
+ ".otf",
4095
+ ".eot",
4096
+ ".wasm",
4097
+ ".gz",
4098
+ ".br",
4099
+ ".zst",
4100
+ ".zip",
4101
+ ".pdf",
4102
+ ".mp3",
4103
+ ".mp4",
4104
+ ".webm",
4105
+ ".ogg",
4106
+ ".wav",
4107
+ ".pack"
4108
+ ]);
4109
+ function alphabetOf(token) {
4110
+ if (/^[0-9a-f]+$/.test(token)) return LOWER_HEX;
4111
+ if (/^[A-Z2-7]+$/.test(token)) return BASE32;
4112
+ if (/^[0-9A-Z]+$/.test(token)) return UPPER_ALNUM;
4113
+ if (/^[0-9a-z~._-]+$/.test(token)) return LOWER_ALNUM;
4114
+ return ALNUM;
4115
+ }
4116
+ function regionsKey(regions) {
4117
+ return regions && regions.length > 0 ? JSON.stringify(regions) : "";
4118
+ }
4119
+ function deriveHashToken(token, salt, regions = "") {
4120
+ const alphabet = alphabetOf(token);
4121
+ let out = "";
4122
+ for (let round = 0; out.length < token.length; round++) {
4123
+ const bytes = (0, node_crypto.createHash)("sha256").update(`${salt}\0${token}\0${regions}\0${round}`).digest();
4124
+ for (const byte of bytes) {
4125
+ if (out.length === token.length) break;
4126
+ out += alphabet[byte % alphabet.length];
4127
+ }
4128
+ }
4129
+ return out;
4130
+ }
4131
+ function escapeRegExp$1(text) {
4132
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4133
+ }
4134
+ function tokenPattern(tokens) {
4135
+ const list = [...tokens].sort((a, b) => b.length - a.length || (a < b ? -1 : 1));
4136
+ if (list.length === 0) return null;
4137
+ return new RegExp(`(?<![A-Za-z0-9])(?:${list.map(escapeRegExp$1).join("|")})(?![A-Za-z0-9])`, "g");
4138
+ }
4139
+ function toPosix$1(path) {
4140
+ return node_path.sep === "/" ? path : path.split(node_path.sep).join("/");
4141
+ }
4142
+ function readText(path) {
4143
+ let bytes;
4144
+ try {
4145
+ bytes = (0, node_fs.readFileSync)(path);
4146
+ } catch {
4147
+ return null;
4148
+ }
4149
+ if (bytes.subarray(0, 8192).includes(0)) return null;
4150
+ try {
4151
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
4152
+ } catch {
4153
+ return null;
4154
+ }
4155
+ }
4156
+ function listFiles(root, skip) {
4157
+ const out = [];
4158
+ const walk$1 = (dir) => {
4159
+ let entries;
4160
+ try {
4161
+ entries = (0, node_fs.readdirSync)(dir, { withFileTypes: true });
4162
+ } catch {
4163
+ return;
4164
+ }
4165
+ for (const entry of entries) {
4166
+ const full = (0, node_path.join)(dir, entry.name);
4167
+ const rel = toPosix$1((0, node_path.relative)(root, full));
4168
+ if (entry.name === AFTERPACK_DIR || entry.name === "node_modules" || skip(rel)) continue;
4169
+ if (entry.isDirectory()) walk$1(full);
4170
+ else if (entry.isFile()) out.push(full);
4171
+ }
4172
+ };
4173
+ walk$1(root);
4174
+ return out;
4175
+ }
4176
+ function isCandidate(path) {
4177
+ const name = (0, node_path.basename)(path).toLowerCase();
4178
+ if (name.endsWith(".map")) return false;
4179
+ const dot = name.lastIndexOf(".");
4180
+ return dot < 0 || !BINARY_EXTENSIONS.has(name.slice(dot));
4181
+ }
4182
+ function writableDir(dir) {
4183
+ try {
4184
+ (0, node_fs.accessSync)(dir, node_fs.constants.W_OK);
4185
+ return true;
4186
+ } catch {
4187
+ return false;
4188
+ }
4189
+ }
4190
+ function planHashedNames(input) {
4191
+ const { root, tokenOf } = input.options;
4192
+ const skip = input.options.skip ?? (() => false);
4193
+ const tokens = new Map();
4194
+ const tokenOfPath = (path) => {
4195
+ const rel = toPosix$1((0, node_path.relative)(root, path));
4196
+ if (rel.startsWith("..")) return null;
4197
+ const token = tokenOf(rel);
4198
+ if (token === null || token.length < MIN_TOKEN_LENGTH) return null;
4199
+ return (0, node_path.basename)(path).includes(token) ? token : null;
4200
+ };
4201
+ const addToken = (token, regions) => {
4202
+ if (tokens.has(token)) return false;
4203
+ tokens.set(token, deriveHashToken(token, input.salt, regionsKey(regions)));
4204
+ return true;
4205
+ };
4206
+ for (const [path, { regions }] of input.inputs) {
4207
+ const token = tokenOfPath(path);
4208
+ if (token !== null) addToken(token, regions);
4209
+ }
4210
+ const others = new Map();
4211
+ if (tokens.size > 0) for (const path of listFiles(root, skip)) {
4212
+ if (input.inputs.has(path) || !isCandidate(path)) continue;
4213
+ const text = readText(path);
4214
+ if (text !== null) others.set(path, text);
4215
+ }
4216
+ const changed = new Set();
4217
+ let grew = tokens.size > 0;
4218
+ while (grew) {
4219
+ grew = false;
4220
+ const pattern$1 = tokenPattern(tokens.keys());
4221
+ if (pattern$1 === null) break;
4222
+ for (const [path, text] of others) {
4223
+ if (changed.has(path)) continue;
4224
+ pattern$1.lastIndex = 0;
4225
+ if (!pattern$1.test(text)) continue;
4226
+ changed.add(path);
4227
+ const token = tokenOfPath(path);
4228
+ if (token !== null && addToken(token)) grew = true;
4229
+ }
4230
+ }
4231
+ const pattern = tokenPattern(tokens.keys());
4232
+ const rewrite = (text) => pattern === null ? text : text.replace(pattern, (token) => tokens.get(token) ?? token);
4233
+ const renamedPath = (path) => {
4234
+ const token = tokenOfPath(path);
4235
+ if (token === null || !tokens.has(token)) return path;
4236
+ const name = (0, node_path.basename)(path);
4237
+ const at = name.lastIndexOf(token);
4238
+ return (0, node_path.join)((0, node_path.dirname)(path), `${name.slice(0, at)}${tokens.get(token)}${name.slice(at + token.length)}`);
4239
+ };
4240
+ const renamed = new Map();
4241
+ for (const path of input.inputs.keys()) {
4242
+ const next = renamedPath(path);
4243
+ if (next !== path) renamed.set(path, next);
4244
+ }
4245
+ const writes = [];
4246
+ for (const path of changed) {
4247
+ const to = renamedPath(path);
4248
+ if (to !== path) renamed.set(path, to);
4249
+ writes.push({
4250
+ from: path,
4251
+ to,
4252
+ text: rewrite(others.get(path))
4253
+ });
4254
+ }
4255
+ const preflight = () => {
4256
+ const unwritable = new Set();
4257
+ for (const [from, to] of renamed) {
4258
+ if (!writableDir((0, node_path.dirname)(from))) unwritable.add((0, node_path.dirname)(from));
4259
+ if (!writableDir((0, node_path.dirname)(to))) unwritable.add((0, node_path.dirname)(to));
4260
+ }
4261
+ for (const write of writes) if (!writableDir((0, node_path.dirname)(write.to))) unwritable.add((0, node_path.dirname)(write.to));
4262
+ if (unwritable.size > 0) throw new Error(`cannot rename content-hashed files: these directories are not writable: ${[...unwritable].sort().join(", ")}`);
4263
+ };
4264
+ return {
4265
+ tokens,
4266
+ renamed,
4267
+ rewrite,
4268
+ preflight,
4269
+ apply() {
4270
+ preflight();
4271
+ for (const write of writes) {
4272
+ const tmp = `${write.to}.afterpack-tmp`;
4273
+ (0, node_fs.writeFileSync)(tmp, write.text);
4274
+ (0, node_fs.renameSync)(tmp, write.to);
4275
+ if (write.to !== write.from) (0, node_fs.rmSync)(write.from, { force: true });
4276
+ }
4277
+ }
4278
+ };
4279
+ }
4280
+
4281
+ //#endregion
4282
+ //#region src/map-color.ts
4283
+ const UTF8 = new TextEncoder();
4284
+ const utf8Len = (s) => UTF8.encode(s).length;
4285
+ const NON_ASCII = /[\u0080-\uFFFF]/;
4286
+ const HIGH_SURROGATE_START = 55296;
4287
+ const HIGH_SURROGATE_END = 56319;
4288
+ const LOW_SURROGATE_START = 56320;
4289
+ const LOW_SURROGATE_END = 57343;
4290
+ function charToByteTable(line) {
4291
+ const table = new Array(line.length + 1);
4292
+ let bytes = 0;
4293
+ let i = 0;
4294
+ while (i < line.length) {
4295
+ table[i] = bytes;
4296
+ const code = line.charCodeAt(i);
4297
+ if (code < 128) {
4298
+ bytes += 1;
4299
+ i += 1;
4300
+ continue;
4301
+ }
4302
+ if (code < 2048) {
4303
+ bytes += 2;
4304
+ i += 1;
4305
+ continue;
4306
+ }
4307
+ if (code >= HIGH_SURROGATE_START && code <= HIGH_SURROGATE_END && i + 1 < line.length) {
4308
+ const low = line.charCodeAt(i + 1);
4309
+ if (low >= LOW_SURROGATE_START && low <= LOW_SURROGATE_END) {
4310
+ table[i + 1] = bytes + 3;
4311
+ bytes += 4;
4312
+ i += 2;
4313
+ continue;
4314
+ }
4315
+ }
4316
+ bytes += 3;
4317
+ i += 1;
4318
+ }
4319
+ table[line.length] = bytes;
4320
+ return table;
4321
+ }
4322
+ var ChunkByteIndex = class {
4323
+ starts;
4324
+ ascii;
4325
+ tables;
3386
4326
  totalBytes;
3387
4327
  constructor(lines) {
3388
4328
  this.lines = lines;
@@ -3535,7 +4475,8 @@ function coverGenerated(segments$1, start, end, index) {
3535
4475
 
3536
4476
  //#endregion
3537
4477
  //#region src/receipt.ts
3538
- const PROTECTION_RECEIPT_FILE = ".afterpack-protection.json";
4478
+ const PROTECTION_RECEIPTS_DIR = "receipts";
4479
+ const STALE_OUTPUT_RECEIPT_FILE = ".afterpack-protection.json";
3539
4480
  const PROTECTION_RECEIPT_SCHEMA = 1;
3540
4481
  function sha256OfBytes(bytes) {
3541
4482
  return (0, node_crypto.createHash)("sha256").update(bytes).digest("hex");
@@ -3546,6 +4487,93 @@ function sha256Of(path) {
3546
4487
  function receiptPathOf(dir, file) {
3547
4488
  return (0, node_path.relative)(dir, file).split(node_path.sep).join("/");
3548
4489
  }
4490
+ const MAX_KEY_BYTES = 180;
4491
+ const HASHED_KEY_PREFIX_BYTES = 120;
4492
+ function buildDirOf(home) {
4493
+ const rel = (0, node_path.relative)(home.projectRoot, home.buildDir).split(node_path.sep).join("/");
4494
+ return rel === "" ? "." : rel;
4495
+ }
4496
+ function receiptKey(buildDir) {
4497
+ const encoded = encodeURIComponent(buildDir).replace(/\*/g, "%2A").replace(/~/g, "%7E");
4498
+ if (Buffer.byteLength(encoded) <= MAX_KEY_BYTES) return encoded;
4499
+ const prefix = encoded.slice(0, HASHED_KEY_PREFIX_BYTES).replace(/%[0-9A-F]?$/, "");
4500
+ const digest = (0, node_crypto.createHash)("sha256").update(buildDir, "utf8").digest("hex").slice(0, 16);
4501
+ return `${prefix}~${digest}`;
4502
+ }
4503
+ function receiptsDirOf(home) {
4504
+ return (0, node_path.join)(home.dir, PROTECTION_RECEIPTS_DIR);
4505
+ }
4506
+ function receiptPathIn(home) {
4507
+ return (0, node_path.join)(receiptsDirOf(home), `${receiptKey(buildDirOf(home))}.json`);
4508
+ }
4509
+ function homeOf(target) {
4510
+ return typeof target === "string" ? afterpackHome(target) : target;
4511
+ }
4512
+ function protectionReceiptPath(target) {
4513
+ return receiptPathIn(homeOf(target));
4514
+ }
4515
+ function prepareProtectionReceipt(target, label) {
4516
+ const home = homeOf(target);
4517
+ const path = receiptPathIn(home);
4518
+ try {
4519
+ (0, node_fs.mkdirSync)((0, node_path.dirname)(path), { recursive: true });
4520
+ ensureAfterpackGitignore(home.dir);
4521
+ const existed = (0, node_fs.existsSync)(path);
4522
+ (0, node_fs.closeSync)((0, node_fs.openSync)(path, "a"));
4523
+ if (!existed) (0, node_fs.unlinkSync)(path);
4524
+ } catch (error) {
4525
+ throw new AfterpackFilesError(DIAG_RECEIPT_UNWRITABLE, `[${label}] cannot write the protection receipt ${path}, so no file was rewritten: ${error}`, `Make ${(0, node_path.dirname)(path)} a writable directory, then build again.`);
4526
+ }
4527
+ return path;
4528
+ }
4529
+ function entriesOf(dir) {
4530
+ try {
4531
+ return (0, node_fs.readdirSync)(dir, { withFileTypes: true });
4532
+ } catch {
4533
+ return [];
4534
+ }
4535
+ }
4536
+ function removeStaleReceipt(path, label) {
4537
+ try {
4538
+ (0, node_fs.unlinkSync)(path);
4539
+ } catch (error) {
4540
+ if (error.code === "ENOENT") return;
4541
+ throw new Error(`[${label}] could not remove the stale protection receipt ${path}, refusing to ship it: ${error}`);
4542
+ }
4543
+ }
4544
+ function refuseShippedAfterpackDir(path, buildDir, label) {
4545
+ 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.`);
4546
+ }
4547
+ function sweepDir(dir, context, recursive) {
4548
+ for (const entry of entriesOf(dir)) {
4549
+ const full = (0, node_path.join)(dir, entry.name);
4550
+ if (entry.name === STALE_OUTPUT_RECEIPT_FILE) removeStaleReceipt(full, context.label);
4551
+ else if (entry.isDirectory()) {
4552
+ if (entry.name === AFTERPACK_DIR) {
4553
+ if (context.ownHome !== null && realPath(full) === context.ownHome) continue;
4554
+ refuseShippedAfterpackDir(full, context.buildDir, context.label);
4555
+ }
4556
+ if (!recursive || entry.name === "node_modules") continue;
4557
+ sweepDir(full, context, true);
4558
+ }
4559
+ }
4560
+ }
4561
+ function sweepOutputTree(buildDir, walkedDir, label, ownHome = null) {
4562
+ const context = {
4563
+ buildDir,
4564
+ label,
4565
+ ownHome: ownHome?.strong ? realPath(ownHome.dir) : null
4566
+ };
4567
+ const walksBuildDir = walkedDir !== null && realPath(walkedDir) === realPath(buildDir);
4568
+ sweepDir(buildDir, context, walksBuildDir);
4569
+ if (walkedDir !== null && !walksBuildDir) sweepDir(walkedDir, context, true);
4570
+ }
4571
+ function keptEntries(path, replaced) {
4572
+ if (!(0, node_fs.existsSync)(path)) return [];
4573
+ const previous = parseReceipt(path);
4574
+ if (previous.error !== void 0 || previous.receipt.schema !== PROTECTION_RECEIPT_SCHEMA) return [];
4575
+ return previous.receipt.files.filter((entry) => !replaced.has(entry.path));
4576
+ }
3549
4577
  function writeDeferredProtectionReceipt(deferred) {
3550
4578
  const survivingFiles = deferred.files.filter((file) => (0, node_fs.existsSync)(file));
3551
4579
  if (survivingFiles.length === 0) return null;
@@ -3565,13 +4593,22 @@ function writeProtectionReceipt(input) {
3565
4593
  seedOrigin: input.seedOrigin,
3566
4594
  bundler: input.bundler,
3567
4595
  buildId: input.buildId,
4596
+ buildDir: ".",
3568
4597
  files: input.files.map((file) => ({
3569
4598
  path: receiptPathOf(input.dir, file),
3570
4599
  sha256: sha256Of(file),
3571
4600
  transformed: transformed.has(file)
3572
4601
  })).sort((a, b) => a.path.localeCompare(b.path))
3573
4602
  };
3574
- const path = (0, node_path.join)(input.dir, PROTECTION_RECEIPT_FILE);
4603
+ const home = input.home ?? afterpackHome(input.dir);
4604
+ receipt.buildDir = buildDirOf(home);
4605
+ const path = receiptPathIn(home);
4606
+ if (input.merge) {
4607
+ const replaced = new Set(receipt.files.map((entry) => entry.path));
4608
+ receipt.files = [...keptEntries(path, replaced), ...receipt.files].sort((a, b) => a.path.localeCompare(b.path));
4609
+ }
4610
+ (0, node_fs.mkdirSync)((0, node_path.dirname)(path), { recursive: true });
4611
+ ensureAfterpackGitignore(home.dir);
3575
4612
  (0, node_fs.writeFileSync)(path, `${JSON.stringify(receipt, null, 2)}\n`);
3576
4613
  return path;
3577
4614
  }
@@ -3619,8 +4656,7 @@ var UnreadableReceiptError = class extends Error {
3619
4656
  this.schema = schema;
3620
4657
  }
3621
4658
  };
3622
- function verifyProtectionReceipt(dir, expectedBuildId) {
3623
- const receiptPath = (0, node_path.join)(dir, PROTECTION_RECEIPT_FILE);
4659
+ function verifyProtectionReceipt(receiptPath, dir, expectedBuildId) {
3624
4660
  if (!(0, node_fs.existsSync)(receiptPath)) return {
3625
4661
  receiptPath,
3626
4662
  receipt: null,
@@ -3652,152 +4688,93 @@ function verifyProtectionReceipt(dir, expectedBuildId) {
3652
4688
  problems
3653
4689
  };
3654
4690
  }
3655
- function findReceiptDir(startDir) {
3656
- const receiptPath = findUpward(startDir, PROTECTION_RECEIPT_FILE);
3657
- return receiptPath ? (0, node_path.dirname)(receiptPath) : null;
3658
- }
3659
- function detectAlreadyObfuscatedInputs(files, startDir, bytesByPath, prefix = (m) => m) {
3660
- const dir = findReceiptDir(startDir);
3661
- if (!dir) return null;
3662
- const receiptPath = (0, node_path.join)(dir, PROTECTION_RECEIPT_FILE);
3663
- const result = parseReceipt(receiptPath);
3664
- if (result.error !== void 0) {
3665
- const schema = result.newerSchema;
3666
- if (schema === null) return null;
3667
- 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);
3668
- }
3669
- const outputHashes = new Set(result.receipt.files.map((f) => f.sha256));
3670
- if (outputHashes.size === 0) return null;
3671
- const matches = files.filter((file) => {
3672
- const bytes = bytesByPath?.get(file);
3673
- if (bytes !== void 0) return outputHashes.has(sha256OfBytes(bytes));
3674
- return (0, node_fs.existsSync)(file) && outputHashes.has(sha256Of(file));
3675
- });
3676
- return matches.length > 0 ? {
3677
- receiptPath,
3678
- files: matches
3679
- } : null;
3680
- }
3681
-
3682
- //#endregion
3683
- //#region src/seed.ts
3684
- function randomSeed() {
3685
- const b = (0, node_crypto.randomBytes)(8);
3686
- const hi = b.readUInt32BE(0) & 2097151;
3687
- const lo = b.readUInt32BE(4);
3688
- return hi * 4294967296 + lo;
3689
- }
3690
- function gitHead() {
3691
- try {
3692
- const out = (0, node_child_process.execFileSync)("git", ["rev-parse", "HEAD"], { stdio: [
3693
- "ignore",
3694
- "pipe",
3695
- "ignore"
3696
- ] }).toString().trim();
3697
- return /^[0-9a-f]{7,64}$/i.test(out) ? out : null;
3698
- } catch {
3699
- return null;
3700
- }
3701
- }
3702
- const SEED_ENV_VAR = "AFTERPACK_SEED";
3703
- function parseSeedValue(raw) {
3704
- return /^-?\d+$/.test(raw) ? Number(raw) : raw;
3705
- }
3706
- const SEED_STATE = Symbol.for("afterpack.integration-utils.seed-sessions");
3707
- function sharedSeedState() {
3708
- const holder = globalThis;
3709
- holder[SEED_STATE] ??= {
3710
- sessions: new Map(),
3711
- ownEnvExports: []
4691
+ function receiptsIn(home) {
4692
+ const dir = receiptsDirOf(home);
4693
+ return entriesOf(dir).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => (0, node_path.join)(dir, entry.name)).sort();
4694
+ }
4695
+ function filesByName(dir) {
4696
+ const byName = new Map();
4697
+ const walk$1 = (current, rel) => {
4698
+ for (const entry of entriesOf(current)) {
4699
+ if (entry.name === "node_modules" || entry.name === AFTERPACK_DIR) continue;
4700
+ const childRel = rel === "" ? entry.name : `${rel}/${entry.name}`;
4701
+ if (entry.isDirectory()) walk$1((0, node_path.join)(current, entry.name), childRel);
4702
+ else if (entry.isFile()) byName.set(entry.name, [...byName.get(entry.name) ?? [], childRel]);
4703
+ }
3712
4704
  };
3713
- return holder[SEED_STATE];
3714
- }
3715
- const { sessions, ownEnvExports } = sharedSeedState();
3716
- function isOwnEnvExport(env, value) {
3717
- return ownEnvExports.some((e) => e.env === env && e.value === value);
3718
- }
3719
- function openGeneration(root, leg) {
3720
- let session = sessions.get(root);
3721
- if (!session) {
3722
- session = {
3723
- seed: void 0,
3724
- generation: 1,
3725
- legs: [],
3726
- resolvedByLeg: new Map(),
3727
- gitFallbackWarned: false
3728
- };
3729
- sessions.set(root, session);
3730
- } else if (session.legs.includes(leg)) {
3731
- session.seed = void 0;
3732
- session.generation += 1;
3733
- session.legs = [];
3734
- session.resolvedByLeg.clear();
3735
- session.gitFallbackWarned = false;
4705
+ walk$1(dir, "");
4706
+ return byName;
4707
+ }
4708
+ function copyMatches(dir, home, skip) {
4709
+ const receipts = receiptsIn(home).filter((path) => !skip.has(path));
4710
+ if (receipts.length === 0) return [];
4711
+ const byName = filesByName(dir);
4712
+ const matches = [];
4713
+ for (const receiptPath of receipts) {
4714
+ const parsed = parseReceipt(receiptPath);
4715
+ if (parsed.error !== void 0 || parsed.receipt.files.length === 0) continue;
4716
+ const { files, buildDir } = parsed.receipt;
4717
+ const first = files[0].path;
4718
+ for (const rel of byName.get(first.split("/").pop() ?? first) ?? []) {
4719
+ if (rel !== first && !rel.endsWith(`/${first}`)) continue;
4720
+ const prefix = rel.slice(0, rel.length - first.length);
4721
+ const copyDir = (0, node_path.join)(dir, ...prefix.split("/").filter(Boolean));
4722
+ if (!files.every((entry) => (0, node_fs.existsSync)((0, node_path.join)(copyDir, entry.path)))) continue;
4723
+ matches.push({
4724
+ receiptPath,
4725
+ dir: copyDir,
4726
+ copiedFrom: typeof buildDir === "string" ? (0, node_path.join)(home.projectRoot, buildDir) : null,
4727
+ hashesMatch: files.every((entry) => sha256Of((0, node_path.join)(copyDir, entry.path)) === entry.sha256),
4728
+ prefix
4729
+ });
4730
+ }
3736
4731
  }
3737
- session.legs.push(leg);
3738
- return session;
4732
+ return matches.sort((a, b) => Number(b.hashesMatch) - Number(a.hashesMatch) || a.prefix.length - b.prefix.length || a.receiptPath.localeCompare(b.receiptPath));
3739
4733
  }
3740
- function resolveWithinSession(input, session, env, deps) {
3741
- if (typeof input === "number") return {
3742
- seed: input,
3743
- origin: "option"
4734
+ function locateProtectionReceipt(dir, options = {}) {
4735
+ const homes = [afterpackHome(dir), afterpackHome(dir, { fileTarget: true })];
4736
+ const exact = [...new Set(homes.map(receiptPathIn))];
4737
+ const found = exact.find((path) => (0, node_fs.existsSync)(path));
4738
+ if (found) return {
4739
+ receiptPath: found,
4740
+ dir,
4741
+ copiedFrom: null
3744
4742
  };
3745
- if (typeof input === "string" && input !== "git") return {
3746
- seed: input,
3747
- origin: "option"
4743
+ if (options.copies === false) return null;
4744
+ const best = copyMatches(dir, homes[0], new Set(exact))[0];
4745
+ return best ? {
4746
+ receiptPath: best.receiptPath,
4747
+ dir: best.dir,
4748
+ copiedFrom: best.copiedFrom
4749
+ } : null;
4750
+ }
4751
+ function detectAlreadyObfuscatedInputs(files, startDir, bytesByPath, prefix = (m) => m) {
4752
+ const hashOf = (file) => {
4753
+ const bytes = bytesByPath?.get(file);
4754
+ if (bytes !== void 0) return sha256OfBytes(bytes);
4755
+ return (0, node_fs.existsSync)(file) ? sha256Of(file) : null;
3748
4756
  };
3749
- if (input === "git") {
3750
- const head = (deps.gitHead ?? gitHead)();
3751
- if (head) return {
3752
- seed: head,
3753
- origin: "git"
3754
- };
3755
- if (!session.gitFallbackWarned) {
3756
- session.gitFallbackWarned = true;
3757
- (deps.warn ?? ((m) => console.warn(m)))("[afterpack] seed \"git\": no git repository / HEAD found; using a fresh random seed for this build.");
4757
+ let hashes = null;
4758
+ for (const receiptPath of receiptsIn(homeOf(startDir))) {
4759
+ const result = parseReceipt(receiptPath);
4760
+ if (result.error !== void 0) {
4761
+ const schema = result.newerSchema;
4762
+ if (schema === null) continue;
4763
+ 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);
3758
4764
  }
3759
- }
3760
- const fromEnv = env[SEED_ENV_VAR];
3761
- if (fromEnv != null && fromEnv !== "" && !isOwnEnvExport(env, fromEnv)) return {
3762
- seed: parseSeedValue(fromEnv),
3763
- origin: "env"
3764
- };
3765
- if (session.seed !== void 0) return {
3766
- seed: session.seed,
3767
- origin: "session"
3768
- };
3769
- return {
3770
- seed: (deps.randomSeed ?? randomSeed)(),
3771
- origin: "fresh"
3772
- };
3773
- }
3774
- function resolveBuildSeed(input, scope, deps = {}) {
3775
- const env = deps.env ?? process.env;
3776
- const session = openGeneration(scope.root, scope.leg);
3777
- const { seed, origin } = resolveWithinSession(input, session, env, deps);
3778
- if (origin === "env" || origin === "fresh") session.seed = seed;
3779
- if (origin === "fresh" && (deps.exportToEnv ?? true)) {
3780
- const value = String(seed);
3781
- env[SEED_ENV_VAR] = value;
3782
- const stale = ownEnvExports.findIndex((e) => e.env === env);
3783
- if (stale >= 0) ownEnvExports.splice(stale, 1);
3784
- ownEnvExports.push({
3785
- env,
3786
- value
4765
+ const outputHashes = new Set(result.receipt.files.filter((f) => f.transformed !== false).map((f) => f.sha256));
4766
+ if (outputHashes.size === 0) continue;
4767
+ hashes ??= new Map(files.map((file) => [file, hashOf(file)]));
4768
+ const matches = files.filter((file) => {
4769
+ const hash = hashes?.get(file);
4770
+ return hash != null && outputHashes.has(hash);
3787
4771
  });
4772
+ if (matches.length > 0) return {
4773
+ receiptPath,
4774
+ files: matches
4775
+ };
3788
4776
  }
3789
- const prior = [...session.resolvedByLeg].find(([, s]) => s !== seed);
3790
- session.resolvedByLeg.set(scope.leg, seed);
3791
- return {
3792
- seed,
3793
- origin,
3794
- legs: [...session.legs],
3795
- generation: session.generation,
3796
- mismatch: prior && session.generation === 1 ? {
3797
- leg: prior[0],
3798
- seed: prior[1]
3799
- } : null
3800
- };
4777
+ return null;
3801
4778
  }
3802
4779
 
3803
4780
  //#endregion
@@ -3813,317 +4790,498 @@ function fmtElapsed(ms) {
3813
4790
  function formatPassSummary(input, style, colorGlyph = (glyph) => glyph) {
3814
4791
  const head = style === "cli" ? colorGlyph("✓") : `[${input.label}]`;
3815
4792
  const files = input.fileCount === 1 ? "file" : "files";
3816
- const tail = (input.unobfuscatedCount > 0 ? ` · ${input.unobfuscatedCount} shipped UNOBFUSCATED (fallback, cleartext)` : "") + (input.noOpCount > 0 ? ` · ${input.noOpCount} no-op (unchanged)` : "");
4793
+ const tail = input.noOpCount > 0 ? ` · ${input.noOpCount} no-op (unchanged)` : "";
3817
4794
  return `${head} Protected ${input.fileCount} ${files} · ${fmtBytes(input.inputBytes)} → ${fmtBytes(input.outputBytes)}${tail} · ${fmtElapsed(input.elapsedMs)}`;
3818
4795
  }
3819
4796
 
3820
4797
  //#endregion
3821
- //#region src/telemetry.ts
3822
- const API_URL_ENV_VAR = "AFTERPACK_API_URL";
3823
- const DEFAULT_API_URL = "https://api.afterpack.dev";
3824
- const TELEMETRY_ENDPOINT_PATH = "/v1/telemetry/build";
3825
- const TELEMETRY_PAYLOAD_VERSION = 1;
3826
- const TELEMETRY_TIMEOUT_MS = 1500;
3827
- const INSTALL_ID_ROTATION_DAYS = 30;
3828
- const TELEMETRY_DIAGNOSTIC_LIMIT = 20;
3829
- const TELEMETRY_STATE_FILE = (0, node_path.join)((0, node_os.homedir)(), ".afterpack", "telemetry.json");
3830
- const TOKEN_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
3831
- const DATA_FIELD_WHITELIST = {
3832
- outputUnparseable: ["parserErrorKind", "outputByteOffset"],
3833
- parseError: ["parserErrorKind"],
3834
- engineBug: [
3835
- "phase",
3836
- "transform",
3837
- "nodeKind"
3838
- ],
3839
- inflationBudget: [
3840
- "target",
3841
- "achieved",
3842
- "budgetRatio",
3843
- "inflationRatio"
3844
- ],
3845
- configParse: [
3846
- "category",
3847
- "line",
3848
- "column"
3849
- ]
4798
+ //#region src/wire.ts
4799
+ const EXTERNAL_WIRE_DIR = "_external";
4800
+ const DRIVE_PATH = /^[A-Za-z]:[\\/]/;
4801
+ const URL_SCHEME = /^[A-Za-z][A-Za-z0-9+.-]+:/;
4802
+ const FILE_URL = /^file:/i;
4803
+ const PATH_CHARS = "[^\\s\"'`|!?#()<>,;:*\\\\]";
4804
+ const EMBEDDED_PATH = new RegExp(`(^|[^A-Za-z0-9._~/\\\\-])((?:[A-Za-z]:[\\\\/]|/)(?:${PATH_CHARS}|\\\\(?!/))*)`, "g");
4805
+ const ESCAPED_PATH = new RegExp(`(^|[^A-Za-z0-9._~/\\\\-])((?:\\\\/${PATH_CHARS}+)+\\\\/?)`, "g");
4806
+ var WirePathError = class extends Error {
4807
+ constructor(message) {
4808
+ super(message);
4809
+ this.name = "WirePathError";
4810
+ }
3850
4811
  };
3851
- function resolveTelemetryEnabled(option, env = {}) {
3852
- if (option !== void 0) return option;
3853
- return !(env.NODE_ENV === "test" || env.VITEST);
4812
+ function toPosix(path) {
4813
+ return path.includes("\\") ? path.replaceAll("\\", "/") : path;
3854
4814
  }
3855
- const FRAMEWORK_ENTRIES = [
3856
- {
3857
- label: "afterpack",
3858
- name: "cli"
3859
- },
3860
- {
3861
- label: "afterpack-angular",
3862
- name: "angular",
3863
- pkg: "@angular/core"
3864
- },
3865
- {
3866
- label: "afterpack-esbuild",
3867
- name: "esbuild",
3868
- pkg: "esbuild"
3869
- },
3870
- {
3871
- label: "afterpack-next",
3872
- name: "next",
3873
- pkg: "next"
3874
- },
3875
- {
3876
- label: "afterpack-rollup",
3877
- name: "rollup",
3878
- pkg: "rollup"
3879
- },
3880
- {
3881
- label: "afterpack-vite",
3882
- name: "vite",
3883
- pkg: "vite"
3884
- },
3885
- {
3886
- label: "afterpack-webpack",
3887
- name: "webpack",
3888
- pkg: "webpack"
3889
- }
3890
- ];
3891
- const FRAMEWORK_BY_LABEL = new Map(FRAMEWORK_ENTRIES.map((e) => [e.label, e.name]));
3892
- const FRAMEWORK_PACKAGE_BY_NAME = new Map(FRAMEWORK_ENTRIES.flatMap((e) => e.pkg ? [[e.name, e.pkg]] : []));
3893
- function frameworkFromLabel(label) {
3894
- return FRAMEWORK_BY_LABEL.get(label.split(":")[0]) ?? "unknown";
4815
+ function lastSegment(path) {
4816
+ const parts = toPosix(path).split("/").filter((p) => p !== "");
4817
+ return parts[parts.length - 1] ?? "file";
3895
4818
  }
3896
- const VERSION_RANGE_PATTERN = /^[\sv0-9.\-+*xX^~><=|]{1,32}$/;
3897
- function detectFrameworkVersion(projectRoot, framework) {
3898
- const pkgName = FRAMEWORK_PACKAGE_BY_NAME.get(framework);
3899
- if (!pkgName) return null;
3900
- let deps;
4819
+ function isUnder(child, parent) {
4820
+ const rel = (0, node_path.relative)(parent, child);
4821
+ return rel === "" || !(0, node_path.isAbsolute)(rel) && rel !== ".." && !rel.startsWith(`..${node_path.sep}`);
4822
+ }
4823
+ function relativeWithin(file, baseDir) {
4824
+ const rel = (0, node_path.relative)((0, node_path.resolve)(baseDir), (0, node_path.resolve)(file));
4825
+ if (rel === "" || (0, node_path.isAbsolute)(rel) || DRIVE_PATH.test(rel)) return null;
4826
+ if (rel === ".." || rel.startsWith(`..${node_path.sep}`)) return null;
4827
+ return toPosix(rel);
4828
+ }
4829
+ function osUsername() {
3901
4830
  try {
3902
- const pkg = JSON.parse((0, node_fs.readFileSync)((0, node_path.join)(projectRoot, "package.json"), "utf8"));
3903
- deps = {
3904
- ...pkg.dependencies,
3905
- ...pkg.devDependencies
3906
- };
4831
+ return (0, node_os.userInfo)().username;
3907
4832
  } catch {
3908
4833
  return null;
3909
4834
  }
3910
- const raw = deps[pkgName];
3911
- if (typeof raw !== "string") return null;
3912
- const range = raw.trim();
3913
- return VERSION_RANGE_PATTERN.test(range) && /[0-9*xX]/.test(range) ? range : null;
3914
- }
3915
- function complexityLabel(preset, complexity) {
3916
- if (preset !== void 0) return preset;
3917
- return complexity === void 0 ? "default" : "custom";
3918
4835
  }
3919
- const FILE_COUNT_BUCKETS = [
3920
- 1,
3921
- 5,
3922
- 20,
3923
- 100,
3924
- 500,
3925
- 2e3
3926
- ];
3927
- function fileCountBucket(count) {
3928
- if (!Number.isFinite(count) || count <= 0) return "0";
3929
- let lower = 1;
3930
- for (const upper of FILE_COUNT_BUCKETS) {
3931
- if (count <= upper) return lower === upper ? `${upper}` : `${lower}-${upper}`;
3932
- lower = upper + 1;
4836
+ function personalNames() {
4837
+ const names = new Set([(0, node_path.basename)((0, node_os.homedir)())]);
4838
+ const user = osUsername();
4839
+ if (user) names.add(user);
4840
+ return names;
4841
+ }
4842
+ function safeName(path) {
4843
+ const name = lastSegment(path);
4844
+ return personalNames().has(name) ? "file" : name;
4845
+ }
4846
+ function toWirePaths(files, baseDir) {
4847
+ const wire = new Map();
4848
+ const taken = new Set();
4849
+ const outside = [];
4850
+ for (const file of files) {
4851
+ if (wire.has(file)) continue;
4852
+ const rel = relativeWithin(file, baseDir);
4853
+ if (rel === null || taken.has(rel)) {
4854
+ outside.push(file);
4855
+ continue;
4856
+ }
4857
+ wire.set(file, rel);
4858
+ taken.add(rel);
4859
+ }
4860
+ let n = 0;
4861
+ for (const file of outside) {
4862
+ if (wire.has(file)) continue;
4863
+ let label;
4864
+ do {
4865
+ label = `${EXTERNAL_WIRE_DIR}/${n}/${safeName(file)}`;
4866
+ n += 1;
4867
+ } while (taken.has(label));
4868
+ wire.set(file, label);
4869
+ taken.add(label);
4870
+ }
4871
+ return wire;
4872
+ }
4873
+ function looksLocal(path) {
4874
+ return isUnder(path, (0, node_os.homedir)()) || isUnder(path, (0, node_os.tmpdir)()) || (0, node_fs.existsSync)(path);
4875
+ }
4876
+ function localPathOf(source) {
4877
+ if (DRIVE_PATH.test(source) || source.startsWith("/") || source.startsWith("\\")) return source;
4878
+ if (FILE_URL.test(source)) try {
4879
+ return (0, node_url.fileURLToPath)(source);
4880
+ } catch {
4881
+ return source.replace(FILE_URL, "").replace(/^\/\/[^/]*/, "") || "/";
3933
4882
  }
3934
- return `${FILE_COUNT_BUCKETS[FILE_COUNT_BUCKETS.length - 1]}+`;
4883
+ const scheme = URL_SCHEME.exec(source);
4884
+ if (!scheme) return null;
4885
+ const rest = source.slice(scheme[0].length).replace(/^\/\/[^/]*/, "");
4886
+ const drive = rest.replace(/^\/+/, "");
4887
+ if (DRIVE_PATH.test(drive)) return drive;
4888
+ return rest.startsWith("/") && looksLocal(rest) ? rest : null;
3935
4889
  }
3936
- const DURATION_BUCKETS_MS = [
3937
- [1e3, "<1s"],
3938
- [5e3, "1-5s"],
3939
- [15e3, "5-15s"],
3940
- [6e4, "15-60s"],
3941
- [3e5, "60-300s"]
3942
- ];
3943
- function durationBucket(ms) {
3944
- if (!Number.isFinite(ms) || ms < 0) return "unknown";
3945
- for (const [upper, label] of DURATION_BUCKETS_MS) if (ms < upper) return label;
3946
- return "300s+";
4890
+ function bothForms(path) {
4891
+ return [...new Set([(0, node_path.resolve)(path), realPath(path)])];
3947
4892
  }
3948
- function safeScalar(value) {
3949
- if (typeof value === "number") return Number.isFinite(value) ? value : null;
3950
- if (typeof value === "string") return TOKEN_PATTERN.test(value) ? value : null;
4893
+ function newPlace(dir, root, labels, shipped = "") {
4894
+ return {
4895
+ dir,
4896
+ root,
4897
+ privateRoots: [...new Set([(0, node_os.homedir)(), root].flatMap(bothForms))],
4898
+ scratchRoots: bothForms((0, node_os.tmpdir)()),
4899
+ labels,
4900
+ shipped
4901
+ };
4902
+ }
4903
+ function isPrivate(path, place) {
4904
+ if (DRIVE_PATH.test(path) && !(0, node_path.isAbsolute)(path)) return true;
4905
+ if (place.privateRoots.some((r) => isUnder(path, r))) return true;
4906
+ return place.scratchRoots.some((r) => isUnder(path, r) && (0, node_path.resolve)(path) !== (0, node_path.resolve)(r));
4907
+ }
4908
+ function inProject(path, place) {
4909
+ if (DRIVE_PATH.test(path) && !(0, node_path.isAbsolute)(path)) return null;
4910
+ const real = realPath(path);
4911
+ const mapDir = realPath(place.dir);
4912
+ const home = realPath((0, node_os.homedir)());
4913
+ if (!isUnder(real, realPath(place.root))) return null;
4914
+ if (isUnder(real, home) && !isUnder(mapDir, home)) return null;
4915
+ const rel = (0, node_path.relative)(mapDir, real);
4916
+ if (rel === "" || (0, node_path.isAbsolute)(rel) || DRIVE_PATH.test(rel)) return null;
4917
+ return toPosix(rel);
4918
+ }
4919
+ function externalLabel(path, place) {
4920
+ const key = (0, node_path.resolve)(path);
4921
+ const known = place.labels.get(key);
4922
+ if (known !== void 0) return known;
4923
+ const label = `${EXTERNAL_WIRE_DIR}/${place.labels.size}/${safeName(path)}`;
4924
+ place.labels.set(key, label);
4925
+ return label;
4926
+ }
4927
+ function fitLength(target, candidate, slash) {
4928
+ const unit = `.${slash}`;
4929
+ const room = target - candidate.length;
4930
+ for (let a = Math.floor(Math.max(room, 0) / unit.length); a >= 0; a--) {
4931
+ const rest = room - a * unit.length;
4932
+ if (rest % slash.length !== 0) continue;
4933
+ const body = unit.repeat(a) + candidate;
4934
+ const extra = rest / slash.length;
4935
+ if (extra === 0) return body;
4936
+ const at = body.indexOf(slash);
4937
+ if (at < 0) continue;
4938
+ return body.slice(0, at) + slash.repeat(extra) + body.slice(at);
4939
+ }
3951
4940
  return null;
3952
4941
  }
3953
- function telemetrySafeData(data) {
3954
- if (!data || typeof data.kind !== "string") return null;
3955
- const kind = TOKEN_PATTERN.test(data.kind) ? data.kind : null;
3956
- if (kind === null) return null;
3957
- const out = { kind };
3958
- for (const field of DATA_FIELD_WHITELIST[kind] ?? []) {
3959
- const value = safeScalar(data[field]);
3960
- if (value !== null) out[field] = value;
4942
+ function sameLength(original, candidates, slash) {
4943
+ for (const candidate of candidates) {
4944
+ const fitted = fitLength(original.length, candidate, slash);
4945
+ if (fitted !== null) return fitted;
3961
4946
  }
3962
- return out;
4947
+ return "_".repeat(original.length);
3963
4948
  }
3964
- function telemetrySafeSpan(d) {
3965
- const span = d.span;
3966
- if (!span) return null;
3967
- const start = safeScalar(span.startByte);
3968
- const end = safeScalar(span.endByte);
3969
- if (typeof start !== "number" || typeof end !== "number") return null;
3970
- if (start < 0 || end < 0) return null;
4949
+ function scrubText(text, place, keepLength) {
4950
+ if (!text.includes("/") && !text.includes("\\")) return text;
4951
+ const plain = text.replace(EMBEDDED_PATH, (whole, lead, path) => {
4952
+ if (!isPrivate(path, place) || keepLength && place.shipped.includes(path)) return whole;
4953
+ const name = inProject(path, place) ?? safeName(path);
4954
+ return `${lead}${keepLength ? sameLength(path, [name, safeName(path)], "/") : name}`;
4955
+ });
4956
+ return plain.replace(ESCAPED_PATH, (whole, lead, escaped) => {
4957
+ const path = escaped.replaceAll("\\/", "/");
4958
+ if (!isPrivate(path, place) || keepLength && place.shipped.includes(escaped)) return whole;
4959
+ const names = [inProject(path, place) ?? safeName(path), safeName(path)].map((c) => c.replaceAll("/", "\\/"));
4960
+ return `${lead}${keepLength ? sameLength(escaped, names, "\\/") : names[0]}`;
4961
+ });
4962
+ }
4963
+ function isRecord(value) {
4964
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4965
+ }
4966
+ function joinRoot(root, source) {
4967
+ return root.endsWith("/") || root.endsWith("\\") ? `${root}${source}` : `${root}/${source}`;
4968
+ }
4969
+ function newRestore() {
3971
4970
  return {
3972
- startByte: start,
3973
- endByte: end
4971
+ sources: new Map(),
4972
+ pmPaths: new Map(),
4973
+ contents: new Map()
3974
4974
  };
3975
4975
  }
3976
- function telemetrySafeDiagnostic(d, severity) {
4976
+ function remember(table, wire, original) {
4977
+ const known = table.get(wire);
4978
+ if (known === void 0) table.set(wire, original);
4979
+ else if (known !== original) table.set(wire, null);
4980
+ }
4981
+ function wireMapObject(map, place, restore, top) {
4982
+ const out = { ...map };
4983
+ let changed = false;
4984
+ const root = typeof map.sourceRoot === "string" ? map.sourceRoot : "";
4985
+ const rootIsLocal = root !== "" && localPathOf(root) !== null;
4986
+ if (rootIsLocal) {
4987
+ delete out.sourceRoot;
4988
+ if (top) restore.sourceRoot = root;
4989
+ changed = true;
4990
+ }
4991
+ const sentRoot = rootIsLocal ? "" : root;
4992
+ const pmPath = (r, s) => r === "" ? s : joinRoot(r, s);
4993
+ const taken = new Map();
4994
+ const claim = (wired, original, local) => {
4995
+ const owner = taken.get(wired);
4996
+ if (owner === void 0 || owner === original) {
4997
+ taken.set(wired, original);
4998
+ return wired;
4999
+ }
5000
+ const label = externalLabel(local, place);
5001
+ taken.set(label, original);
5002
+ return label;
5003
+ };
5004
+ if (Array.isArray(map.sources)) out.sources = map.sources.map((source) => {
5005
+ if (typeof source !== "string") return source;
5006
+ const rooted = rootIsLocal && localPathOf(source) === null && !URL_SCHEME.test(source) ? joinRoot(root, source) : source;
5007
+ const local = localPathOf(rooted);
5008
+ let wired;
5009
+ if (local === null) {
5010
+ const scrubbed = scrubText(rooted, place, false);
5011
+ if (scrubbed === source) {
5012
+ taken.set(source, source);
5013
+ return source;
5014
+ }
5015
+ wired = claim(scrubbed, source, rooted);
5016
+ } else {
5017
+ const rel = inProject(local, place);
5018
+ wired = claim(rel ?? externalLabel(local, place), source, local);
5019
+ }
5020
+ changed = true;
5021
+ remember(restore.sources, wired, source);
5022
+ remember(restore.pmPaths, pmPath(sentRoot, wired), pmPath(root, source));
5023
+ return wired;
5024
+ });
5025
+ if (typeof map.file === "string" && localPathOf(map.file) !== null) {
5026
+ if (top) restore.file = map.file;
5027
+ out.file = safeName(map.file);
5028
+ changed = true;
5029
+ }
5030
+ if (Array.isArray(map.sourcesContent)) out.sourcesContent = map.sourcesContent.map((content) => {
5031
+ if (typeof content !== "string") return content;
5032
+ const scrubbed = scrubText(content, place, true);
5033
+ if (scrubbed === content) return content;
5034
+ changed = true;
5035
+ remember(restore.contents, scrubbed, content);
5036
+ return scrubbed;
5037
+ });
5038
+ if (Array.isArray(map.sections)) out.sections = map.sections.map((section) => {
5039
+ if (!isRecord(section) || !isRecord(section.map)) return section;
5040
+ const nested = wireMapObject(section.map, place, restore, false);
5041
+ if (!nested.changed) return section;
5042
+ changed = true;
5043
+ return {
5044
+ ...section,
5045
+ map: nested.map
5046
+ };
5047
+ });
3977
5048
  return {
3978
- code: TOKEN_PATTERN.test(d.code) ? d.code : "DIAG_UNKNOWN",
3979
- severity,
3980
- span: telemetrySafeSpan(d),
3981
- data: telemetrySafeData(d.data)
5049
+ map: out,
5050
+ changed
3982
5051
  };
3983
5052
  }
3984
- function buildTelemetryPayload(facts, ctx) {
3985
- let errorCount = 0;
3986
- let criticalCount = 0;
3987
- const alerting = [];
3988
- for (const d of facts.diagnostics) {
3989
- if (d.severity !== "error" && d.severity !== "critical") continue;
3990
- if (d.severity === "critical") criticalCount += 1;
3991
- else errorCount += 1;
3992
- alerting.push(telemetrySafeDiagnostic(d, d.severity));
5053
+ function wireSourceMapWithRestore(json, place) {
5054
+ const restore = newRestore();
5055
+ let parsed;
5056
+ try {
5057
+ parsed = JSON.parse(json);
5058
+ } catch {
5059
+ return {
5060
+ json: void 0,
5061
+ restore
5062
+ };
3993
5063
  }
3994
- if (alerting.length === 0) return null;
3995
- const kept = alerting.slice(-TELEMETRY_DIAGNOSTIC_LIMIT);
3996
- const env = ctx.env ?? {};
3997
- const runtime = ctx.runtime ?? {
3998
- node: process.versions.node,
3999
- platform: process.platform,
4000
- arch: process.arch
5064
+ if (!isRecord(parsed)) return {
5065
+ json: void 0,
5066
+ restore
4001
5067
  };
4002
- const framework = frameworkFromLabel(facts.label);
5068
+ const { map, changed } = wireMapObject(parsed, place, restore, true);
4003
5069
  return {
4004
- version: TELEMETRY_PAYLOAD_VERSION,
4005
- installId: ctx.installId,
4006
- framework,
4007
- frameworkVersion: detectFrameworkVersion(facts.projectRoot, framework),
4008
- engineVersion: safeVersion(facts.engineVersion),
4009
- clientVersion: safeVersion(facts.clientVersion),
4010
- nodeVersion: safeVersion(runtime.node) ?? "unknown",
4011
- os: safeToken(runtime.platform),
4012
- arch: safeToken(runtime.arch),
4013
- ci: env.CI === "true",
4014
- complexity: complexityLabel(facts.preset, facts.complexity),
4015
- fileCountBucket: fileCountBucket(facts.fileCount),
4016
- durationBucket: durationBucket(facts.durationMs),
4017
- diagnostics: kept,
4018
- errorCount,
4019
- criticalCount,
4020
- droppedCount: alerting.length - kept.length
5070
+ json: changed ? JSON.stringify(map) : json,
5071
+ restore
4021
5072
  };
4022
5073
  }
4023
- const VERSION_PATTERN = /^[0-9][0-9A-Za-z.\-+]{0,31}$/;
4024
- function safeVersion(value) {
4025
- return typeof value === "string" && VERSION_PATTERN.test(value) ? value : null;
4026
- }
4027
- function safeToken(value) {
4028
- return TOKEN_PATTERN.test(value) ? value : "unknown";
4029
- }
4030
- const TELEMETRY_NOTICE = [
4031
- "AfterPack: anonymous build diagnostics are ON (this notice prints once).",
4032
- "AfterPack: A build that reports an error-level diagnostic (a refused or partial build)",
4033
- "AfterPack: sends that diagnostic's code, severity, byte offsets and typed engine",
4034
- "AfterPack: fields, plus engine version, integration, Node version, OS/arch, bucketed",
4035
- "AfterPack: file counts and durations, and a random install id that rotates every 30",
4036
- "AfterPack: days.",
4037
- "AfterPack: It never sends your source, file names, paths, project name, diagnostic",
4038
- "AfterPack: message text, or exact byte counts. A clean build sends nothing.",
4039
- "AfterPack: Turn it off with AFTERPACK_telemetry_enabled=false, --telemetry.enabled=false, or",
4040
- "AfterPack: `telemetry: { enabled: false }` in your config.",
4041
- "AfterPack: https://www.afterpack.dev/privacy"
4042
- ];
4043
- const INSTALL_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
4044
- const DAY_MS = 24 * 60 * 60 * 1e3;
4045
- function readState(file, now) {
4046
- try {
4047
- const parsed = JSON.parse((0, node_fs.readFileSync)(file, "utf8"));
4048
- if (typeof parsed.installId === "string" && INSTALL_ID_PATTERN.test(parsed.installId) && typeof parsed.rotatedAt === "number") return {
4049
- installId: parsed.installId,
4050
- rotatedAt: parsed.rotatedAt,
4051
- noticeShownAt: typeof parsed.noticeShownAt === "number" ? parsed.noticeShownAt : 0
5074
+ function lookup(table, value) {
5075
+ return table.get(value) ?? value;
5076
+ }
5077
+ function restoreMapObject(map, ctx, top) {
5078
+ let changed = false;
5079
+ const out = { ...map };
5080
+ if (Array.isArray(map.sources)) out.sources = map.sources.map((entry) => {
5081
+ if (typeof entry !== "string") return entry;
5082
+ const back = entry === ctx.wire ? ctx.local : lookup(ctx.map.sources, entry);
5083
+ if (back !== entry) changed = true;
5084
+ return back;
5085
+ });
5086
+ if (Array.isArray(map.sourcesContent)) out.sourcesContent = map.sourcesContent.map((entry) => {
5087
+ if (typeof entry !== "string") return entry;
5088
+ const back = lookup(ctx.map.contents, entry);
5089
+ if (back !== entry) changed = true;
5090
+ return back;
5091
+ });
5092
+ if (top && ctx.map.sourceRoot !== void 0 && !map.sourceRoot) {
5093
+ const root = ctx.map.sourceRoot;
5094
+ const entries = Object.entries(out).filter(([key]) => key !== "sourceRoot");
5095
+ const at = "sourceRoot" in map ? Object.keys(map).indexOf("sourceRoot") : -1;
5096
+ const after = entries.findIndex(([key]) => key === "sources");
5097
+ const index = at >= 0 ? at : after >= 0 ? after + 1 : entries.length;
5098
+ entries.splice(index, 0, ["sourceRoot", root]);
5099
+ for (const key of Object.keys(out)) delete out[key];
5100
+ Object.assign(out, Object.fromEntries(entries));
5101
+ changed = true;
5102
+ }
5103
+ if (top && ctx.map.file !== void 0 && typeof map.file === "string") {
5104
+ out.file = ctx.map.file;
5105
+ changed = true;
5106
+ }
5107
+ if (Array.isArray(map.sections)) out.sections = map.sections.map((section) => {
5108
+ if (!isRecord(section) || !isRecord(section.map)) return section;
5109
+ const nested = restoreMapObject(section.map, ctx, false);
5110
+ if (!nested.changed) return section;
5111
+ changed = true;
5112
+ return {
5113
+ ...section,
5114
+ map: nested.map
4052
5115
  };
4053
- } catch {}
5116
+ });
4054
5117
  return {
4055
- installId: (0, node_crypto.randomUUID)(),
4056
- rotatedAt: now,
4057
- noticeShownAt: 0
5118
+ map: out,
5119
+ changed
4058
5120
  };
4059
5121
  }
4060
- function writeState(file, state) {
4061
- try {
4062
- (0, node_fs.mkdirSync)((0, node_path.dirname)(file), { recursive: true });
4063
- (0, node_fs.writeFileSync)(file, `${JSON.stringify(state)}\n`, "utf8");
4064
- } catch {}
4065
- }
4066
- function telemetryUrl(env) {
4067
- const base = (env[API_URL_ENV_VAR] ?? DEFAULT_API_URL).replace(/\/+$/, "");
4068
- return `${base}${TELEMETRY_ENDPOINT_PATH}`;
4069
- }
4070
- const TELEMETRY_BODY_LIMIT = 64 * 1024;
4071
- async function reportTelemetryNotices(response, logger) {
4072
- if (!response || response.status !== 202 || typeof response.text !== "function") return;
4073
- const declared = Number(response.headers?.get?.("content-length"));
4074
- if (Number.isFinite(declared) && declared > TELEMETRY_BODY_LIMIT) {
4075
- await response.body?.cancel().catch(() => {});
4076
- return;
4077
- }
4078
- const text = await response.text();
4079
- if (text.length > TELEMETRY_BODY_LIMIT) return;
4080
- let body;
5122
+ function restoreSourceMap(json, ctx) {
5123
+ let parsed;
4081
5124
  try {
4082
- body = JSON.parse(text);
5125
+ parsed = JSON.parse(json);
4083
5126
  } catch {
4084
- return;
5127
+ return json;
4085
5128
  }
4086
- if (typeof body !== "object" || body === null || Array.isArray(body)) return;
4087
- reportNotices(body.notices, logger);
5129
+ if (!isRecord(parsed)) return json;
5130
+ const { map, changed } = restoreMapObject(parsed, ctx, true);
5131
+ return changed ? JSON.stringify(map) : json;
4088
5132
  }
4089
- function createTelemetryReporter(deps = {}) {
4090
- const env = deps.env ?? process.env;
4091
- const logger = deps.logger ?? console;
4092
- const now = deps.now ?? Date.now;
4093
- const stateFile = deps.stateFile ?? TELEMETRY_STATE_FILE;
4094
- const timeoutMs = deps.timeoutMs ?? TELEMETRY_TIMEOUT_MS;
4095
- return async (facts) => {
4096
- try {
4097
- const at = now();
4098
- const state = readState(stateFile, at);
4099
- let dirty = false;
4100
- if (at - state.rotatedAt >= INSTALL_ID_ROTATION_DAYS * DAY_MS) {
4101
- state.installId = (0, node_crypto.randomUUID)();
4102
- state.rotatedAt = at;
4103
- dirty = true;
4104
- }
4105
- if (state.noticeShownAt === 0) {
4106
- for (const line of TELEMETRY_NOTICE) logger.log(line);
4107
- state.noticeShownAt = at;
4108
- dirty = true;
5133
+ function restoredSize(size, wired, original) {
5134
+ if (typeof size !== "number") return size;
5135
+ if (size === Buffer.byteLength(wired)) return Buffer.byteLength(original);
5136
+ if (size === wired.length) return original.length;
5137
+ return size;
5138
+ }
5139
+ function restoreProtectionMap(doc, ctx) {
5140
+ if (!isRecord(doc) || !Array.isArray(doc.files)) return doc;
5141
+ return {
5142
+ ...doc,
5143
+ files: doc.files.map((entry) => {
5144
+ if (!isRecord(entry) || !isRecord(entry.file)) return entry;
5145
+ const file = entry.file;
5146
+ const next = { ...file };
5147
+ if (typeof file.path === "string") next.path = file.path === ctx.wire ? ctx.local : lookup(ctx.map.pmPaths, file.path);
5148
+ if (typeof file.originalSource === "string") {
5149
+ const original = lookup(ctx.map.contents, file.originalSource);
5150
+ if (original !== file.originalSource) {
5151
+ next.originalSource = original;
5152
+ next.inputSize = restoredSize(file.inputSize, file.originalSource, original);
5153
+ }
4109
5154
  }
4110
- if (dirty) writeState(stateFile, state);
4111
- if (facts === null) return;
4112
- const payload = buildTelemetryPayload(facts, {
4113
- installId: state.installId,
4114
- env
4115
- });
4116
- if (payload === null) return;
4117
- const fetchImpl = deps.fetchImpl ?? globalThis.fetch;
4118
- if (typeof fetchImpl !== "function") return;
4119
- const response = await fetchImpl(telemetryUrl(env), {
4120
- method: "POST",
4121
- headers: { "content-type": "application/json" },
4122
- body: JSON.stringify(payload),
4123
- signal: AbortSignal.timeout(timeoutMs)
4124
- });
4125
- await reportTelemetryNotices(response, logger);
4126
- } catch {}
5155
+ const same = Object.keys(next).every((k) => next[k] === file[k]);
5156
+ return same ? entry : {
5157
+ ...entry,
5158
+ file: next
5159
+ };
5160
+ })
5161
+ };
5162
+ }
5163
+ function wireGlob(pattern, pairs) {
5164
+ let equivalent = true;
5165
+ const matched = [];
5166
+ for (const [local, wire] of pairs) {
5167
+ const hit = matchesPath(pattern, local);
5168
+ if (hit !== matchesPath(pattern, wire)) equivalent = false;
5169
+ if (hit) matched.push(wire);
5170
+ }
5171
+ if (!isAnchored(pattern) && equivalent && matched.length > 0) return [pattern];
5172
+ return matched.map((wire) => `/${wire}`);
5173
+ }
5174
+ function anyMatch(patterns, path) {
5175
+ return patterns.some((p) => matchesPath(p, path));
5176
+ }
5177
+ function reservedNames(entries, path) {
5178
+ const names = entries.flatMap((e) => typeof e === "string" ? [] : matchesPath(e.glob, path) ? e.names : []);
5179
+ return [...new Set(names)].sort().join("\n");
5180
+ }
5181
+ function verifyTranslation(config, out, pairs) {
5182
+ const exclude = config.paths?.exclude ?? [];
5183
+ const sentExclude = out.paths?.exclude ?? [];
5184
+ const reserved = config.identifiers?.reserved ?? [];
5185
+ const sentReserved = out.identifiers?.reserved ?? [];
5186
+ for (const [local, wire] of pairs) {
5187
+ 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.`);
5188
+ 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.`);
5189
+ }
5190
+ }
5191
+ function translateConfig(config, wirePaths) {
5192
+ const exclude = config.paths?.exclude;
5193
+ const reserved = config.identifiers?.reserved;
5194
+ const origins = new Map();
5195
+ if (exclude === void 0 && reserved === void 0) return {
5196
+ config,
5197
+ origins
5198
+ };
5199
+ const pairs = [...wirePaths.entries()];
5200
+ const translate = (pattern) => {
5201
+ const patterns = wireGlob(pattern, pairs);
5202
+ for (const p of patterns) if (!origins.has(p)) origins.set(p, pattern);
5203
+ return patterns;
5204
+ };
5205
+ const out = { ...config };
5206
+ if (exclude !== void 0) out.paths = {
5207
+ ...config.paths,
5208
+ exclude: [...new Set(exclude.flatMap((pattern) => translate(pattern)))]
5209
+ };
5210
+ if (reserved !== void 0) out.identifiers = {
5211
+ ...config.identifiers,
5212
+ reserved: reserved.flatMap((entry) => typeof entry === "string" ? [entry] : translate(entry.glob).map((glob) => ({
5213
+ ...entry,
5214
+ glob
5215
+ })))
5216
+ };
5217
+ verifyTranslation(config, out, pairs);
5218
+ return {
5219
+ config: out,
5220
+ origins
5221
+ };
5222
+ }
5223
+ function escapeRegExp(text) {
5224
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5225
+ }
5226
+ function localMessage(message, wire, local, origins) {
5227
+ let out = message;
5228
+ for (const [sent, original] of origins) if (sent !== original) out = out.split(`"${sent}"`).join(`"${original}"`);
5229
+ const bounded = new RegExp(`(^|[\\s"'\`(\\[])${escapeRegExp(wire)}(?=$|[\\s"'\`)\\]:,;]|\\.(?:\\s|$))`, "g");
5230
+ return out.replace(bounded, (_m, lead) => `${lead}${local}`);
5231
+ }
5232
+ function localDiagnostics(diagnostics, localPaths, wire, local, origins) {
5233
+ if (!Array.isArray(diagnostics)) return diagnostics;
5234
+ return diagnostics.map((d) => {
5235
+ if (!isRecord(d)) return d;
5236
+ const next = { ...d };
5237
+ if (typeof d.file === "string") next.file = localPaths.get(d.file) ?? d.file;
5238
+ if (typeof d.message === "string") next.message = localMessage(d.message, wire, local, origins);
5239
+ return next.file === d.file && next.message === d.message ? d : next;
5240
+ });
5241
+ }
5242
+ function prepareWireBatch(inputs, config, baseDir, rootDir = baseDir) {
5243
+ const wirePaths = toWirePaths(inputs.map((i) => i.path), baseDir);
5244
+ const localPaths = new Map([...wirePaths].map(([local, wire]) => [wire, local]));
5245
+ const translated = translateConfig(config, wirePaths);
5246
+ const restores = new Map();
5247
+ const labels = new Map();
5248
+ const wiredInputs = inputs.map((input) => {
5249
+ const path = wirePaths.get(input.path) ?? input.path;
5250
+ const wired = {
5251
+ ...input,
5252
+ path
5253
+ };
5254
+ if (input.sourceMap !== void 0) {
5255
+ const place = newPlace((0, node_path.dirname)((0, node_path.resolve)(input.path)), rootDir, labels, input.source);
5256
+ const map = wireSourceMapWithRestore(input.sourceMap, place);
5257
+ restores.set(path, map.restore);
5258
+ if (map.json === void 0) delete wired.sourceMap;
5259
+ else wired.sourceMap = map.json;
5260
+ }
5261
+ return wired;
5262
+ });
5263
+ return {
5264
+ inputs: wiredInputs,
5265
+ config: translated.config,
5266
+ toLocal: (batch) => ({
5267
+ ...batch,
5268
+ files: batch.files.map((f) => {
5269
+ const local = localPaths.get(f.path);
5270
+ if (local === void 0) return f;
5271
+ const ctx = {
5272
+ map: restores.get(f.path) ?? newRestore(),
5273
+ wire: f.path,
5274
+ local
5275
+ };
5276
+ return {
5277
+ ...f,
5278
+ path: local,
5279
+ ...f.diagnostics === void 0 ? {} : { diagnostics: localDiagnostics(f.diagnostics, localPaths, f.path, local, translated.origins) },
5280
+ ...typeof f.sourceMap === "string" ? { sourceMap: restoreSourceMap(f.sourceMap, ctx) } : {},
5281
+ ...f.protectionMap == null ? {} : { protectionMap: restoreProtectionMap(f.protectionMap, ctx) }
5282
+ };
5283
+ })
5284
+ })
4127
5285
  };
4128
5286
  }
4129
5287
 
@@ -4156,16 +5314,19 @@ function fileFailure(f, source) {
4156
5314
  if (reason) return reason;
4157
5315
  return f.status === "failure" ? "empty output" : `the engine reported status "${sanitizeServerText(f.status, 32)}"`;
4158
5316
  }
4159
- if (typeof f.unobfuscated !== "boolean") return "the engine result does not say whether the file was obfuscated";
5317
+ if (f.unobfuscated === true) return "the engine could not obfuscate it and returned the original source — update @afterpack/core";
4160
5318
  if (f.code === "" && source.trim() !== "") return sanitizeServerText(f.error) || "empty output";
4161
5319
  return null;
4162
5320
  }
4163
- async function readEngineVersion(engine) {
4164
- try {
4165
- return await engine.version?.() ?? null;
4166
- } catch {
4167
- return null;
5321
+ function removeBundlerSourceMaps(input) {
5322
+ const { sweepDir: sweepDir$1, engineMaps, policy, label } = input;
5323
+ const bundlerMaps = new Set([...input.perFile].flat());
5324
+ if (sweepDir$1 != null) {
5325
+ const swept = collectSourceMaps(sweepDir$1).filter((path) => !policy.sourceMap || !path.endsWith(".css.map"));
5326
+ for (const path of containedSourceMaps(swept, sweepDir$1)) bundlerMaps.add(path);
4168
5327
  }
5328
+ removeSourceMaps([...bundlerMaps].filter((path) => !engineMaps.has(path)), label);
5329
+ if (sweepDir$1 != null && !policy.sourceMap) stripCssSourceMappingURLs(collectStylesheets(sweepDir$1));
4169
5330
  }
4170
5331
  function describeLevel(preset, complexity) {
4171
5332
  if (complexity === void 0) return `preset "${preset ?? DEFAULT_PRESET}"`;
@@ -4175,22 +5336,30 @@ function describeLevel(preset, complexity) {
4175
5336
  async function runObfuscationPass(options) {
4176
5337
  const passStartedAt = options.startedAt ?? Date.now();
4177
5338
  const callerAnchored = options.startedAt !== void 0;
4178
- const { files, engine, label, cwd, combinedProtectionMap, artifactOptions = {}, env = process.env } = options;
5339
+ const { engine, label, cwd, combinedProtectionMap, artifactOptions = {}, env = process.env } = options;
4179
5340
  const logger = silenceSummaryLines(options.logger ?? DEFAULT_LOGGER, options.diagnostics);
4180
5341
  const prefix = (message) => `[${label}] ${message}`;
4181
5342
  const style = options.summaryStyle ?? "plugin";
4182
5343
  assertSupportedCore(options.client, prefix);
5344
+ const outsideBuildDir = options.emitToCaller ? [] : options.files.filter((f) => !options.inputs?.has(f) && !withinRealDir((0, node_path.dirname)(f), combinedProtectionMap.buildDir));
5345
+ const files = options.files.filter((f) => !outsideBuildDir.includes(f));
5346
+ if (outsideBuildDir.length > 0) logger.warn(prefix(`left ${outsideBuildDir.length} file(s) untouched because a symlink places them outside ${combinedProtectionMap.buildDir}: ${outsideBuildDir.join(", ")}`));
4183
5347
  const onDiskFiles = options.inputs ? files.filter((f) => !options.inputs?.has(f)) : files;
4184
5348
  const onDiskBytes = new Map(await Promise.all(onDiskFiles.map(async (filePath) => [filePath, await (0, node_fs_promises.readFile)(filePath)])));
5349
+ const home = afterpackHome(combinedProtectionMap.buildDir, { fileTarget: combinedProtectionMap.fileTarget });
5350
+ const unanchored = describeUnanchoredHome(home);
5351
+ if (unanchored) logger.log(prefix(unanchored));
4185
5352
  if (!options.emitToCaller) {
4186
- const already = detectAlreadyObfuscatedInputs(onDiskFiles, combinedProtectionMap.buildDir, onDiskBytes, prefix);
5353
+ const already = detectAlreadyObfuscatedInputs(onDiskFiles, home, onDiskBytes, prefix);
4187
5354
  if (already) throw new AlreadyObfuscatedError(prefix(formatAlreadyObfuscatedMessage({
4188
5355
  files: already.files,
4189
5356
  receiptPath: already.receiptPath,
4190
5357
  dir: combinedProtectionMap.buildDir
4191
5358
  })), already.files, already.receiptPath, combinedProtectionMap.buildDir);
4192
5359
  }
4193
- const resolvedSeed = resolveBuildSeed(options.seed, {
5360
+ if (options.outputSweep !== false) sweepOutputTree(combinedProtectionMap.buildDir, options.sourceMapSweepDir ?? (options.emitToCaller ? combinedProtectionMap.buildDir : null), label, home);
5361
+ prepareProtectionReceipt(home, label);
5362
+ const resolvedSeed = options.resolvedSeed ?? resolveBuildSeed(options.seed, {
4194
5363
  root: cwd,
4195
5364
  leg: options.buildLeg ?? combinedProtectionMap.buildDir
4196
5365
  }, {
@@ -4203,6 +5372,9 @@ async function runObfuscationPass(options) {
4203
5372
  const bundledCapture = options.capturedByFile != null;
4204
5373
  const postMinifyMode = directivesEnabled && options.postMinify === true && !bundledCapture;
4205
5374
  const sourceByPath = new Map();
5375
+ const bundlerMapsByPath = new Map();
5376
+ const sweepDir$1 = options.sourceMapSweepDir ?? null;
5377
+ const sourceMapRoot = sweepDir$1 ?? combinedProtectionMap.buildDir;
4206
5378
  let coloredRegionCount = 0;
4207
5379
  let directivesNeededMap = false;
4208
5380
  let postMinifyMapsSeen = 0;
@@ -4212,6 +5384,7 @@ async function runObfuscationPass(options) {
4212
5384
  const provided = options.inputs?.get(filePath);
4213
5385
  const source = provided ? provided.source : (onDiskBytes.get(filePath) ?? (0, node_fs.readFileSync)(filePath)).toString("utf8");
4214
5386
  sourceByPath.set(filePath, source);
5387
+ if (!provided && !options.emitToCaller) bundlerMapsByPath.set(filePath, bundlerSourceMapPaths(filePath, source, sourceMapRoot));
4215
5388
  const inputSourceMap = provided ? provided.sourceMap ?? null : discoverInputSourceMap(filePath, source);
4216
5389
  let regions;
4217
5390
  const modules = options.capturedByFile?.get(filePath);
@@ -4303,6 +5476,39 @@ async function runObfuscationPass(options) {
4303
5476
  engine: options.engineConfig,
4304
5477
  renameGlobals: capture.renameGlobals
4305
5478
  });
5479
+ const saltEngine = options.cloudEngineExpectation ?? (options.hashedNames ? await resolveSaltEngine(env, localEngineVersion) : null);
5480
+ let namesPlan = null;
5481
+ let hashSalt = null;
5482
+ if (options.hashedNames && saltEngine && !options.emitToCaller) {
5483
+ const { seed: _seed,...configWithoutSeed } = engineConfig;
5484
+ const namedInputs = new Map(inputs.map((input) => [input.path, {
5485
+ source: input.source,
5486
+ regions: input.regions
5487
+ }]));
5488
+ hashSalt = afterpackHashSalt({
5489
+ seed,
5490
+ engine: saltEngine,
5491
+ settings: {
5492
+ engine: configWithoutSeed,
5493
+ sourceMap: policy.sourceMap,
5494
+ emitSourceMappingURL: policy.emitSourceMappingURL
5495
+ }
5496
+ });
5497
+ namesPlan = planHashedNames({
5498
+ options: options.hashedNames,
5499
+ inputs: namedInputs,
5500
+ salt: hashSalt
5501
+ });
5502
+ namesPlan.preflight();
5503
+ for (const input of inputs) {
5504
+ const path = namesPlan.renamed.get(input.path) ?? input.path;
5505
+ const source = namesPlan.rewrite(input.source);
5506
+ sourceByPath.delete(input.path);
5507
+ sourceByPath.set(path, source);
5508
+ input.path = path;
5509
+ input.source = source;
5510
+ }
5511
+ }
4306
5512
  if (style !== "cli") logger.log(prefix(`obfuscating ${inputs.length} file(s) at ${describeLevel(options.preset, options.complexity)} ...`));
4307
5513
  const engineStartedAt = Date.now();
4308
5514
  const prepMs = engineStartedAt - passStartedAt;
@@ -4310,9 +5516,16 @@ async function runObfuscationPass(options) {
4310
5516
  clientVersion: options.client?.coreVersion,
4311
5517
  client: clientString(options.client)
4312
5518
  });
5519
+ let wire;
5520
+ try {
5521
+ wire = prepareWireBatch(inputs, engineConfig, combinedProtectionMap.buildDir, home.projectRoot);
5522
+ } catch (error) {
5523
+ if (error instanceof WirePathError) throw new Error(prefix(error.message));
5524
+ throw error;
5525
+ }
4313
5526
  let batch;
4314
5527
  try {
4315
- batch = await engine.processBatch(inputs, engineConfig, context);
5528
+ batch = wire.toLocal(await engine.processBatch(wire.inputs, wire.config, context));
4316
5529
  } catch (error) {
4317
5530
  const cloud = toCloudApiError(error, {
4318
5531
  identity: options.client,
@@ -4323,6 +5536,7 @@ async function runObfuscationPass(options) {
4323
5536
  throw cloud;
4324
5537
  }
4325
5538
  const engineEndedAt = Date.now();
5539
+ options.onBatch?.(inputs, batch);
4326
5540
  reportNotices(batch.notices, logger, prefix);
4327
5541
  const engineMs = engineEndedAt - engineStartedAt;
4328
5542
  const collected = collectDiagnostics(batch.files);
@@ -4337,6 +5551,10 @@ async function runObfuscationPass(options) {
4337
5551
  const telemetry = options.telemetry;
4338
5552
  const telemetryEnabled = telemetry != null && resolveTelemetryEnabled(artifactOptions.telemetry?.enabled, env);
4339
5553
  const engineVersion = (batch.source === "cloud" ? safeVersionString(batch.engineVersion) : null) ?? localEngineVersion;
5554
+ if (saltEngine) {
5555
+ const mismatch = cloudEngineMismatch(saltEngine, batch.source === "cloud" ? safeVersionString(batch.engineVersion) : null);
5556
+ if (mismatch) throw new Error(prefix(mismatch));
5557
+ }
4340
5558
  if (telemetry && telemetryEnabled) {
4341
5559
  const facts = {
4342
5560
  label,
@@ -4356,7 +5574,6 @@ async function runObfuscationPass(options) {
4356
5574
  const outputs = [];
4357
5575
  let inputBytes = 0;
4358
5576
  let outputBytes = 0;
4359
- const unobfuscatedFiles = [];
4360
5577
  let noOp = 0;
4361
5578
  const transformedFiles = [];
4362
5579
  const verified = [];
@@ -4367,8 +5584,7 @@ async function runObfuscationPass(options) {
4367
5584
  if (failure !== null) throw new Error(prefix(`failed to obfuscate ${f.path}: ${failure}`));
4368
5585
  inputBytes += Buffer.byteLength(source);
4369
5586
  outputBytes += Buffer.byteLength(f.code);
4370
- if (f.unobfuscated === true) unobfuscatedFiles.push((0, node_path.basename)(f.path));
4371
- else if (f.code === source) noOp += 1;
5587
+ if (f.code === source) noOp += 1;
4372
5588
  else transformedFiles.push(f.path);
4373
5589
  if (policy.protectionMap && f.protectionMap != null) protectionMapDocs.push(f.protectionMap);
4374
5590
  verified.push({
@@ -4376,10 +5592,9 @@ async function runObfuscationPass(options) {
4376
5592
  source
4377
5593
  });
4378
5594
  }
4379
- if (unobfuscatedFiles.length > 0) if (artifactOptions.allowUnobfuscated === true) for (const name of unobfuscatedFiles) logger.warn(prefix(`${name} could not be obfuscated and SHIPPED AS CLEARTEXT (allowUnobfuscated:true). This is an engine bug — please report it.`));
4380
- else throw new Error(prefix(`${unobfuscatedFiles.length} file(s) could not be obfuscated and would ship as cleartext: ${unobfuscatedFiles.join(", ")} — fix the engine or set allowUnobfuscated:true`));
4381
5595
  const writtenFiles = [];
4382
5596
  const emittedFiles = [];
5597
+ const engineMaps = new Set();
4383
5598
  for (const { result: f, source } of verified) {
4384
5599
  if (options.emitToCaller) {
4385
5600
  outputs.push({
@@ -4392,24 +5607,42 @@ async function runObfuscationPass(options) {
4392
5607
  }
4393
5608
  const written = writeArtifacts({
4394
5609
  outPath: f.path,
4395
- code: f.code,
5610
+ code: withSourceMappingURL(f.code, null),
4396
5611
  sourceMapJson: f.sourceMap ?? null,
4397
5612
  protectionMapJson: null,
4398
5613
  originalSource: source,
4399
5614
  policy,
4400
5615
  mode: "framework",
5616
+ afterpackDir: home.dir,
4401
5617
  logger
4402
5618
  });
4403
5619
  writtenFiles.push(written.codePath);
4404
- if (written.mapPath) sensitiveArtifactPaths.push(written.mapPath);
5620
+ if (written.mapPath) {
5621
+ sensitiveArtifactPaths.push(written.mapPath);
5622
+ engineMaps.add((0, node_path.resolve)(written.mapPath));
5623
+ }
4405
5624
  if (written.backupPath) sensitiveArtifactPaths.push(written.backupPath);
4406
5625
  }
4407
- if (!options.emitToCaller) options.afterWrite?.();
5626
+ if (!options.emitToCaller) {
5627
+ if (namesPlan) {
5628
+ for (const [from, to] of namesPlan.renamed) if (sourceByPath.has(to)) (0, node_fs.rmSync)(from, { force: true });
5629
+ namesPlan.apply();
5630
+ if (namesPlan.renamed.size > 0) logger.log(prefix(`renamed ${namesPlan.renamed.size} content-hashed file(s) so each name follows its obfuscated bytes`));
5631
+ }
5632
+ removeBundlerSourceMaps({
5633
+ perFile: bundlerMapsByPath.values(),
5634
+ sweepDir: sweepDir$1,
5635
+ engineMaps,
5636
+ policy,
5637
+ label
5638
+ });
5639
+ options.afterWrite?.(writtenFiles);
5640
+ }
4408
5641
  const protectionMapPath = writeCombinedProtectionMap({
4409
5642
  buildDir: combinedProtectionMap.buildDir,
4410
5643
  docs: protectionMapDocs,
4411
5644
  policy,
4412
- afterpackDir: combinedProtectionMap.afterpackDir,
5645
+ afterpackDir: combinedProtectionMap.subdir ? (0, node_path.join)(home.dir, combinedProtectionMap.subdir) : home.dir,
4413
5646
  fileName: combinedProtectionMap.fileName,
4414
5647
  logger
4415
5648
  });
@@ -4431,12 +5664,15 @@ async function runObfuscationPass(options) {
4431
5664
  if (options.emitToCaller) deferredReceipt = {
4432
5665
  ...receiptFields,
4433
5666
  dir: combinedProtectionMap.buildDir,
5667
+ home,
4434
5668
  files: emittedFiles
4435
5669
  };
4436
5670
  else {
4437
5671
  receiptPath = writeProtectionReceipt({
4438
5672
  ...receiptFields,
4439
5673
  dir: combinedProtectionMap.buildDir,
5674
+ home,
5675
+ merge: combinedProtectionMap.fileTarget === true,
4440
5676
  files: writtenFiles
4441
5677
  });
4442
5678
  if (style !== "cli") logger.log(prefix(`wrote protection receipt -> ${receiptPath} (afterpack verify)`));
@@ -4461,7 +5697,6 @@ async function runObfuscationPass(options) {
4461
5697
  fileCount: files.length,
4462
5698
  inputBytes,
4463
5699
  outputBytes,
4464
- unobfuscatedCount: unobfuscatedFiles.length,
4465
5700
  noOpCount: noOp,
4466
5701
  elapsedMs: totalMs
4467
5702
  }, style, options.colorGlyph) + seedSuffix);
@@ -4476,6 +5711,8 @@ async function runObfuscationPass(options) {
4476
5711
  timing,
4477
5712
  diagnostics: diagnosticsSummary,
4478
5713
  transformedFiles,
5714
+ renamed: namesPlan?.renamed ?? new Map(),
5715
+ hashSalt,
4479
5716
  ...options.emitToCaller ? { outputs } : {}
4480
5717
  };
4481
5718
  }
@@ -4655,6 +5892,8 @@ function resolvePluginConfig(input) {
4655
5892
  }
4656
5893
 
4657
5894
  //#endregion
5895
+ exports.AFTERPACK_DIR = AFTERPACK_DIR;
5896
+ exports.AfterpackFilesError = AfterpackFilesError;
4658
5897
  exports.AlreadyObfuscatedError = AlreadyObfuscatedError;
4659
5898
  exports.CLOUD_REFUSAL_SUMMARY = CLOUD_REFUSAL_SUMMARY;
4660
5899
  exports.CONFIG_FILE_NAME = CONFIG_FILE_NAME;
@@ -4662,11 +5901,14 @@ exports.CONFIG_KEYS = CONFIG_KEYS;
4662
5901
  exports.CORE_FLOOR_SUMMARY = CORE_FLOOR_SUMMARY;
4663
5902
  exports.CloudApiError = CloudApiError;
4664
5903
  exports.CoreVersionError = CoreVersionError;
5904
+ exports.DIAG_AFTERPACK_DIR_IN_OUTPUT = DIAG_AFTERPACK_DIR_IN_OUTPUT;
4665
5905
  exports.DIAG_ALREADY_OBFUSCATED = DIAG_ALREADY_OBFUSCATED;
4666
5906
  exports.DIAG_RECEIPT_UNREADABLE = DIAG_RECEIPT_UNREADABLE;
4667
- exports.PROTECTION_RECEIPT_FILE = PROTECTION_RECEIPT_FILE;
5907
+ exports.DIAG_RECEIPT_UNWRITABLE = DIAG_RECEIPT_UNWRITABLE;
5908
+ exports.PROTECTION_RECEIPTS_DIR = PROTECTION_RECEIPTS_DIR;
4668
5909
  exports.SEED_ENV_VAR = SEED_ENV_VAR;
4669
5910
  exports.UnreadableReceiptError = UnreadableReceiptError;
5911
+ exports.afterpackHome = afterpackHome;
4670
5912
  exports.applyBundleOutput = applyBundleOutput;
4671
5913
  exports.applyResolvedKey = applyResolvedKey;
4672
5914
  exports.collectBundleJs = collectBundleJs;
@@ -4682,25 +5924,37 @@ exports.findUpward = findUpward;
4682
5924
  exports.getPath = getPath;
4683
5925
  exports.installedRequiredLine = installedRequiredLine;
4684
5926
  exports.loadConfigFile = loadConfigFile;
5927
+ exports.locateProtectionReceipt = locateProtectionReceipt;
4685
5928
  exports.mergeConfig = mergeConfig;
4686
5929
  exports.normalizePluginOptions = normalizePluginOptions;
4687
5930
  exports.npxAlternative = npxAlternative;
4688
5931
  exports.parseCliOptions = parseCliOptions;
4689
5932
  exports.parseEnvOptions = parseEnvOptions;
4690
5933
  exports.passSettings = passSettings;
5934
+ exports.prepareHashSalt = prepareHashSalt;
5935
+ exports.protectionReceiptPath = protectionReceiptPath;
5936
+ exports.readEngineVersion = readEngineVersion;
5937
+ exports.regenerateCompressedSiblings = regenerateCompressedSiblings;
5938
+ exports.removeSourceMaps = removeSourceMaps;
5939
+ exports.reportPolicySaltBits = reportPolicySaltBits;
4691
5940
  exports.resolveClientIdentity = resolveClientIdentity;
4692
5941
  exports.resolvePluginConfig = resolvePluginConfig;
4693
5942
  exports.resolveReportPolicy = resolveReportPolicy;
4694
5943
  exports.runObfuscationPass = runObfuscationPass;
5944
+ exports.saltSettings = saltSettings;
4695
5945
  exports.sanitizeNotices = sanitizeNotices;
4696
5946
  exports.scanDirectives = scanDirectives;
4697
5947
  exports.serverAddsInfo = serverAddsInfo;
4698
5948
  exports.sha256Of = sha256Of;
4699
5949
  exports.sourceTypeForBundle = sourceTypeForBundle;
4700
5950
  exports.sourceTypeForOutputFormat = sourceTypeForOutputFormat;
5951
+ exports.sriPluginRefusal = sriPluginRefusal;
4701
5952
  exports.stripBundleCssSourceMaps = stripBundleCssSourceMaps;
5953
+ exports.stripCssSourceMappingURLs = stripCssSourceMappingURLs;
5954
+ exports.sweepOutputTree = sweepOutputTree;
4702
5955
  exports.toEngineConfig = toEngineConfig;
4703
5956
  exports.toPluginOptions = toPluginOptions;
5957
+ exports.unsaltedAssetsWarning = unsaltedAssetsWarning;
4704
5958
  exports.validateConfig = validateConfig;
4705
5959
  exports.verifyProtectionReceipt = verifyProtectionReceipt;
4706
5960
  exports.withSourceMappingURL = withSourceMappingURL;