@afterpack/integration-utils 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -474,397 +474,6 @@ function warnIfPublicPath(artifactPath, logger = DEFAULT_LOGGER) {
474
474
  return true;
475
475
  }
476
476
 
477
- //#endregion
478
- //#region src/source-map.ts
479
- const SOURCE_MAPPING_URL_RE = /\/\/[#@]\s*sourceMappingURL=(\S+)\s*$/gm;
480
- const SOURCE_MAPPING_URL_LINE_RE = /^[ \t]*\/\/[#@]\s*sourceMappingURL=\S+[ \t]*\r?\n?/gm;
481
- function withSourceMappingURL(code, url) {
482
- const stripped = code.replace(SOURCE_MAPPING_URL_LINE_RE, "");
483
- if (url == null) return stripped;
484
- const separator = stripped.length > 0 && !stripped.endsWith("\n") ? "\n" : "";
485
- return `${stripped}${separator}//# sourceMappingURL=${url}\n`;
486
- }
487
- function extractSourceMappingURL(code) {
488
- let last = null;
489
- for (const match of code.matchAll(SOURCE_MAPPING_URL_RE)) last = match[1];
490
- return last;
491
- }
492
- function isRemoteSourceMappingURL(url) {
493
- return /^https?:\/\//i.test(url) || url.startsWith("//");
494
- }
495
- function decodeDataUri(url) {
496
- if (!url.startsWith("data:")) return null;
497
- const comma = url.indexOf(",");
498
- if (comma === -1) return null;
499
- const meta = url.slice(5, comma);
500
- const payload = url.slice(comma + 1);
501
- try {
502
- if (/;base64/i.test(meta)) return Buffer.from(payload, "base64").toString("utf8");
503
- return decodeURIComponent(payload);
504
- } catch {
505
- return null;
506
- }
507
- }
508
- function discoverInputSourceMap(jsPath, code) {
509
- const adjacent = `${jsPath}.map`;
510
- if (existsSync(adjacent)) try {
511
- return readFileSync(adjacent, "utf8");
512
- } catch {}
513
- let source = code;
514
- if (source == null) try {
515
- source = readFileSync(jsPath, "utf8");
516
- } catch {
517
- return null;
518
- }
519
- const url = extractSourceMappingURL(source);
520
- if (url == null) return null;
521
- if (url.startsWith("data:")) return decodeDataUri(url);
522
- if (isRemoteSourceMappingURL(url)) return null;
523
- let mapPath;
524
- try {
525
- mapPath = isAbsolute(url) ? url : resolve(dirname(jsPath), decodeURIComponent(url));
526
- } catch {
527
- return null;
528
- }
529
- if (!existsSync(mapPath)) return null;
530
- try {
531
- return readFileSync(mapPath, "utf8");
532
- } catch {
533
- return null;
534
- }
535
- }
536
-
537
- //#endregion
538
- //#region src/bundle.ts
539
- const BUNDLE_JS_RE = /\.[cm]?js$/;
540
- function collectBundleJs(bundle, outDir) {
541
- const files = [];
542
- const inputs = new Map();
543
- const entries = new Map();
544
- for (const [fileName, entry] of Object.entries(bundle)) {
545
- if (!BUNDLE_JS_RE.test(fileName)) continue;
546
- const source = entry.type === "chunk" ? entry.code : typeof entry.source === "string" ? entry.source : void 0;
547
- if (source === void 0) continue;
548
- const filePath = resolve(outDir, fileName);
549
- files.push(filePath);
550
- entries.set(filePath, entry);
551
- inputs.set(filePath, {
552
- source,
553
- sourceMap: entry.map ? entry.map.toString() : null
554
- });
555
- }
556
- return {
557
- files,
558
- inputs,
559
- entries
560
- };
561
- }
562
- function dataUri(json) {
563
- return `data:application/json;charset=utf-8;base64,${Buffer.from(json, "utf8").toString("base64")}`;
564
- }
565
- function applyBundleOutput(bundle, entry, out, policy) {
566
- if (entry.type !== "chunk") {
567
- entry.source = out.code;
568
- return;
569
- }
570
- const mapName = entry.sourcemapFileName ?? null;
571
- const inlineMap = mapName == null && entry.map != null;
572
- const emitMap = policy.sourceMap && out.sourceMap != null;
573
- let url = null;
574
- if (emitMap && out.sourceMap != null) {
575
- if (mapName != null && bundle[mapName]) {
576
- bundle[mapName].source = out.sourceMap;
577
- url = basename(mapName);
578
- } else if (inlineMap) url = dataUri(out.sourceMap);
579
- } else {
580
- if (mapName != null) delete bundle[mapName];
581
- entry.map = null;
582
- }
583
- entry.code = withSourceMappingURL(out.code, policy.emitSourceMappingURL ? url : null);
584
- }
585
-
586
- //#endregion
587
- //#region src/glob.ts
588
- function normalize(value) {
589
- return value.includes("\\") ? value.replaceAll("\\", "/") : value;
590
- }
591
- function segments(value) {
592
- return value.split("/").filter((part) => part !== "");
593
- }
594
- function isAnchored(pattern) {
595
- if (pattern.startsWith("/")) return true;
596
- return pattern.length >= 2 && pattern[1] === ":" && /^[A-Za-z]$/.test(pattern[0]);
597
- }
598
- function segmentMatches(pattern, seg) {
599
- if (!pattern.includes("*") && !pattern.includes("?")) return pattern === seg;
600
- const p = [...pattern];
601
- const s = [...seg];
602
- let pi = 0;
603
- let si = 0;
604
- let star = -1;
605
- let starSi = 0;
606
- while (si < s.length) if (pi < p.length && p[pi] === "*") {
607
- star = pi;
608
- starSi = si;
609
- pi += 1;
610
- } else if (pi < p.length && (p[pi] === "?" || p[pi] === s[si])) {
611
- pi += 1;
612
- si += 1;
613
- } else if (star >= 0) {
614
- pi = star + 1;
615
- starSi += 1;
616
- si = starSi;
617
- } else return false;
618
- return p.slice(pi).every((c) => c === "*");
619
- }
620
- function segmentsMatch(pattern, path) {
621
- let pi = 0;
622
- let si = 0;
623
- let star = -1;
624
- let starSi = 0;
625
- while (si < path.length) if (pi < pattern.length && pattern[pi] === "**") {
626
- star = pi;
627
- starSi = si;
628
- pi += 1;
629
- } else if (pi < pattern.length && segmentMatches(pattern[pi], path[si])) {
630
- pi += 1;
631
- si += 1;
632
- } else if (star >= 0) {
633
- pi = star + 1;
634
- starSi += 1;
635
- si = starSi;
636
- } else return false;
637
- return pattern.slice(pi).every((s) => s === "**");
638
- }
639
- function matchesPath(pattern, path) {
640
- const pat = normalize(pattern);
641
- const parts = segments(pat);
642
- if (parts.length === 0) return false;
643
- const segs = segments(normalize(path));
644
- if (isAnchored(pat)) return segmentsMatch(parts, segs);
645
- for (let i = 0; i <= segs.length; i++) if (segmentsMatch(parts, segs.slice(i))) return true;
646
- return false;
647
- }
648
- function reachesInto(pattern, dir) {
649
- const pat = normalize(pattern);
650
- const parts = segments(pat);
651
- if (parts.length === 0) return false;
652
- if (!isAnchored(pat)) return true;
653
- for (let k = 1; k <= parts.length; k++) if (matchesPath(`/${parts.slice(0, k).join("/")}`, dir)) return true;
654
- return false;
655
- }
656
-
657
- //#endregion
658
- //#region src/collect.ts
659
- const BACKUP_RE = /\.backup\.[0-9a-f]{8}\.[cm]?js$/;
660
- const NODE_MODULES = "node_modules";
661
- function isCollectableJs(name) {
662
- if (BACKUP_RE.test(name)) return false;
663
- return name.endsWith(".js") || name.endsWith(".mjs") || name.endsWith(".cjs");
664
- }
665
- function statOrNull(path) {
666
- try {
667
- return statSync(path);
668
- } catch {
669
- return null;
670
- }
671
- }
672
- function collectJsFiles(target, options = {}) {
673
- const stat = statOrNull(target);
674
- if (!stat) return [];
675
- if (!stat.isDirectory()) return isCollectableJs(basename(target)) ? [target] : [];
676
- return walkJs(target, options.include ?? [], false, options.onNestedProject);
677
- }
678
- function entriesOf(dir) {
679
- try {
680
- return readdirSync(dir, { withFileTypes: true });
681
- } catch {
682
- return [];
683
- }
684
- }
685
- function kindOf(entry, full) {
686
- if (entry.isDirectory()) return "dir";
687
- if (entry.isFile()) return "file";
688
- const stat = statOrNull(full);
689
- if (!stat) return null;
690
- return stat.isDirectory() ? "dir" : "file";
691
- }
692
- function isNestedProject(dir) {
693
- return existsSync(join(dir, "package.json"));
694
- }
695
- function walkJs(dir, include, readmitted, onNestedProject) {
696
- const out = [];
697
- for (const entry of entriesOf(dir)) {
698
- const name = entry.name;
699
- const full = join(dir, name);
700
- const kind = kindOf(entry, full);
701
- if (kind === null) continue;
702
- if (kind === "dir") {
703
- const skipped = name === NODE_MODULES;
704
- if (!skipped && !readmitted && isNestedProject(full)) {
705
- onNestedProject?.(full);
706
- continue;
707
- }
708
- if (skipped && !include.some((pattern) => reachesInto(pattern, full))) continue;
709
- out.push(...walkJs(full, include, readmitted || skipped, onNestedProject));
710
- } else if (isCollectableJs(name)) {
711
- if (readmitted && !include.some((pattern) => matchesPath(pattern, full))) continue;
712
- out.push(full);
713
- }
714
- }
715
- return out;
716
- }
717
- function isSourceMap(name) {
718
- return name.endsWith(".js.map") || name.endsWith(".mjs.map") || name.endsWith(".cjs.map");
719
- }
720
- function collectSourceMaps(dir) {
721
- if (!existsSync(dir)) return [];
722
- const out = [];
723
- for (const entry of entriesOf(dir)) {
724
- const name = entry.name;
725
- const full = join(dir, name);
726
- const kind = kindOf(entry, full);
727
- if (kind === null) continue;
728
- if (kind === "dir") out.push(...collectSourceMaps(full));
729
- else if (isSourceMap(name)) out.push(full);
730
- }
731
- return out;
732
- }
733
-
734
- //#endregion
735
- //#region src/notices.ts
736
- const NOTICE_MESSAGE_LIMIT = 500;
737
- const NOTICE_LIMIT = 5;
738
- const NOTICE_CODE_LIMIT = 64;
739
- const NOTICE_HOSTS = new Set(["afterpack.dev", "www.afterpack.dev"]);
740
- const ESC = 27;
741
- const BEL = 7;
742
- const C1_CSI = 155;
743
- const C1_OSC = 157;
744
- function isControl(code) {
745
- return code < 32 || code >= 127 && code <= 159;
746
- }
747
- function isInvisibleFormat(code) {
748
- return code === 1564 || code >= 8203 && code <= 8207 || code >= 8234 && code <= 8238 || code >= 8288 && code <= 8297 || code === 65279;
749
- }
750
- function skipCsi(text, from) {
751
- let i = from;
752
- while (i < text.length) {
753
- const c = text.charCodeAt(i);
754
- i += 1;
755
- if (c >= 64 && c <= 126) return i;
756
- }
757
- return i;
758
- }
759
- function skipOsc(text, from) {
760
- let i = from;
761
- while (i < text.length) {
762
- const c = text.charCodeAt(i);
763
- if (c === BEL) return i + 1;
764
- if (c === ESC) return text.charCodeAt(i + 1) === 92 ? i + 2 : i + 1;
765
- if (c === 156) return i + 1;
766
- i += 1;
767
- }
768
- return i;
769
- }
770
- function stripTerminalControls(text) {
771
- let out = "";
772
- let i = 0;
773
- while (i < text.length) {
774
- const c = text.charCodeAt(i);
775
- if (c === ESC) {
776
- const next = text.charCodeAt(i + 1);
777
- if (next === 91) i = skipCsi(text, i + 2);
778
- else if (next === 93) i = skipOsc(text, i + 2);
779
- else i += Number.isNaN(next) ? 1 : 2;
780
- continue;
781
- }
782
- if (c === C1_CSI) {
783
- i = skipCsi(text, i + 1);
784
- continue;
785
- }
786
- if (c === C1_OSC) {
787
- i = skipOsc(text, i + 1);
788
- continue;
789
- }
790
- if (isControl(c)) {
791
- out += c === 9 || c === 10 || c === 13 ? " " : "";
792
- i += 1;
793
- continue;
794
- }
795
- if (c === 8232 || c === 8233) {
796
- out += " ";
797
- i += 1;
798
- continue;
799
- }
800
- if (isInvisibleFormat(c)) {
801
- i += 1;
802
- continue;
803
- }
804
- out += text[i];
805
- i += 1;
806
- }
807
- return out;
808
- }
809
- function sanitizeServerText(value, limit = NOTICE_MESSAGE_LIMIT) {
810
- if (typeof value !== "string") return "";
811
- const clean = stripTerminalControls(value).replace(/\s+/g, " ").trim();
812
- if (clean.length <= limit) return clean;
813
- const chars = Array.from(clean);
814
- return chars.length > limit ? chars.slice(0, limit).join("") : clean;
815
- }
816
- function sanitizeNoticeUrl(value) {
817
- if (typeof value !== "string") return null;
818
- let url;
819
- try {
820
- url = new URL(value.trim());
821
- } catch {
822
- return null;
823
- }
824
- if (url.protocol !== "https:") return null;
825
- if (!NOTICE_HOSTS.has(url.hostname) || url.port !== "") return null;
826
- if (url.username !== "" || url.password !== "") return null;
827
- const href = url.href;
828
- return href.length <= NOTICE_MESSAGE_LIMIT ? href : null;
829
- }
830
- function noticeSeverity(value) {
831
- if (value === "info") return "info";
832
- if (value === "error" || value === "critical") return "error";
833
- return "warning";
834
- }
835
- function sanitizeNotices(raw) {
836
- if (!Array.isArray(raw)) return [];
837
- const out = [];
838
- for (const entry of raw) {
839
- if (out.length >= NOTICE_LIMIT) break;
840
- if (typeof entry !== "object" || entry === null) continue;
841
- const n = entry;
842
- const message = sanitizeServerText(n.message);
843
- if (message === "") continue;
844
- out.push({
845
- severity: noticeSeverity(n.severity),
846
- code: sanitizeServerText(n.code, NOTICE_CODE_LIMIT),
847
- message,
848
- url: sanitizeNoticeUrl(n.url)
849
- });
850
- }
851
- return out;
852
- }
853
- function formatNotice(notice) {
854
- const head = notice.severity === "info" ? "AfterPack notice" : `AfterPack ${notice.severity}`;
855
- const tail = notice.url ? ` ${notice.url}` : "";
856
- return `${head}: ${notice.message}${tail}`;
857
- }
858
- function reportNotices(raw, logger, prefix = (m) => m) {
859
- const notices = sanitizeNotices(raw);
860
- for (const notice of notices) {
861
- const line = prefix(formatNotice(notice));
862
- if (notice.severity === "info" || !logger.warn) logger.log(line);
863
- else logger.warn(line);
864
- }
865
- return notices;
866
- }
867
-
868
477
  //#endregion
869
478
  //#region src/registry.ts
870
479
  const PRESET_VALUES = [
@@ -874,6 +483,20 @@ const PRESET_VALUES = [
874
483
  "hard",
875
484
  "extreme"
876
485
  ];
486
+ const SOURCE_TYPE_VALUES = [
487
+ "auto",
488
+ "module",
489
+ "script"
490
+ ];
491
+ const MODULE_OUTPUT_FORMATS = new Set([
492
+ "es",
493
+ "esm",
494
+ "esmodule",
495
+ "module"
496
+ ]);
497
+ function sourceTypeForOutputFormat(format) {
498
+ return typeof format === "string" && MODULE_OUTPUT_FORMATS.has(format.toLowerCase()) ? "module" : void 0;
499
+ }
877
500
  const TRANSFORM_KIND_VALUES = [
878
501
  "stringEncoding",
879
502
  "controlFlowFlatten",
@@ -923,6 +546,18 @@ const CONFIG_KEYS = [
923
546
  },
924
547
  default: "light"
925
548
  },
549
+ {
550
+ path: "sourceType",
551
+ shape: "scalar",
552
+ scope: "program",
553
+ tier: "free",
554
+ surface: "engine",
555
+ item: {
556
+ kind: "enum",
557
+ values: SOURCE_TYPE_VALUES
558
+ },
559
+ default: "auto"
560
+ },
926
561
  {
927
562
  path: "complexity",
928
563
  shape: "scalar",
@@ -1094,7 +729,7 @@ const CONFIG_KEYS = [
1094
729
  tier: "free",
1095
730
  surface: "engine",
1096
731
  item: { kind: "boolean" },
1097
- default: "true when the bundler emitted a source map"
732
+ default: "true when the bundler emitted a source map, outside CI"
1098
733
  },
1099
734
  {
1100
735
  path: "protectionMap.detailed",
@@ -1304,360 +939,777 @@ const PREFIX_BY_NORMALIZED = new Map([...CONFIG_PREFIXES].map((prefix) => [norma
1304
939
  function normalizeKey(key) {
1305
940
  return key.replace(/[-_.]/g, "").toLowerCase();
1306
941
  }
1307
- function groupBooleanKey(path) {
1308
- if (!CONFIG_PREFIXES.has(path)) return void 0;
1309
- return CONFIG_BY_PATH.get(`${path}.enabled`);
942
+ function groupBooleanKey(path) {
943
+ if (!CONFIG_PREFIXES.has(path)) return void 0;
944
+ return CONFIG_BY_PATH.get(`${path}.enabled`);
945
+ }
946
+ function nearestName(name, candidates) {
947
+ const target = normalizeKey(name);
948
+ let best;
949
+ for (const candidate of candidates) {
950
+ const distance = editDistance(target, normalizeKey(candidate));
951
+ if (distance > Math.max(2, Math.floor(target.length / 4))) continue;
952
+ if (!best || distance < best.distance) best = {
953
+ name: candidate,
954
+ distance
955
+ };
956
+ }
957
+ return best?.name;
958
+ }
959
+ function suggestKey(key) {
960
+ const exact = BY_NORMALIZED.get(normalizeKey(key));
961
+ if (exact) return exact.path;
962
+ const near = nearestName(key, CONFIG_KEYS.map((k) => k.path));
963
+ if (near) return near;
964
+ const tail = normalizeKey(key);
965
+ const owners = CONFIG_KEYS.filter((k) => normalizeKey(k.path.slice(k.path.lastIndexOf(".") + 1)) === tail);
966
+ return owners.length === 1 ? owners[0].path : void 0;
967
+ }
968
+ function canonicalSpelling(name) {
969
+ const norm$1 = normalizeKey(name);
970
+ const key = BY_NORMALIZED.get(norm$1);
971
+ if (key) return { key: key.path };
972
+ const group$1 = CHILDREN_BY_NORMALIZED.get(norm$1);
973
+ return group$1 && group$1.length > 0 ? { group: group$1 } : void 0;
974
+ }
975
+ function editDistance(a, b) {
976
+ const prev = new Array(b.length + 1);
977
+ const next = new Array(b.length + 1);
978
+ for (let j = 0; j <= b.length; j++) prev[j] = j;
979
+ for (let i = 1; i <= a.length; i++) {
980
+ next[0] = i;
981
+ for (let j = 1; j <= b.length; j++) next[j] = Math.min(prev[j] + 1, next[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
982
+ for (let j = 0; j <= b.length; j++) prev[j] = next[j];
983
+ }
984
+ return prev[b.length];
985
+ }
986
+ const DOCS_URL = "https://www.afterpack.dev/docs/config";
987
+ function unknownKeyMessage(path, surface) {
988
+ const group$1 = CHILDREN_BY_NORMALIZED.get(normalizeKey(path));
989
+ if (group$1 && group$1.length > 0) {
990
+ const list = group$1.map((child) => `\`${child}\``).join(", ");
991
+ const tail$1 = group$1.length === 1 ? `did you mean ${list}?` : `its keys are ${list}`;
992
+ const canonical = PREFIX_BY_NORMALIZED.get(normalizeKey(path));
993
+ const enabled = canonical ? groupBooleanKey(canonical) : void 0;
994
+ const rule = enabled ? `; a boolean here means \`${enabled.path}\`` : "";
995
+ return `\`${path}\` is a group of configuration keys, not a key itself (${surface}) — ${tail$1}${rule}`;
996
+ }
997
+ const suggestion = suggestKey(path);
998
+ const tail = suggestion ? ` — did you mean \`${suggestion}\`?` : ` — see ${DOCS_URL}`;
999
+ return `unknown configuration key \`${path}\` (${surface})${tail}`;
1000
+ }
1001
+ function isPlainObject(value) {
1002
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1003
+ }
1004
+ function describe(item) {
1005
+ switch (item.kind) {
1006
+ case "boolean": return "true or false";
1007
+ case "number": return item.integer ? `an integer >= ${item.min}` : `a number >= ${item.min}`;
1008
+ case "unbounded": return `a number >= ${item.min}, or the string "${item.unlimited}"`;
1009
+ case "string": return "a string";
1010
+ case "enum": return `one of: ${item.values.join(", ")}`;
1011
+ case "seed": return "a number, any string, or \"git\"";
1012
+ case "reserved": return "a name, or { \"glob\": \"…\", \"names\": [\"…\"] }";
1013
+ case "region": return "an object with numeric `start` and `end`";
1014
+ }
1015
+ }
1016
+ function misdirectedHint(key, value, spell) {
1017
+ const other = misdirectedTo(key, value);
1018
+ if (!other) return "";
1019
+ const written = spell(other.path, String(value));
1020
+ return ` — \`${String(value)}\` is a \`${other.path}\` value; write \`${written}\` instead`;
1021
+ }
1022
+ const isFiniteNumber = (v) => typeof v === "number" && Number.isFinite(v);
1023
+ const isTransformKinds = (v) => Array.isArray(v) && v.every((k) => TRANSFORM_KIND_VALUES.includes(k));
1024
+ const KINDS = `a list of: ${TRANSFORM_KIND_VALUES.join(", ")}`;
1025
+ const isNonNegative = (v) => isFiniteNumber(v) && v >= 0;
1026
+ function group(fields) {
1027
+ return {
1028
+ is: isPlainObject,
1029
+ want: "an object",
1030
+ fields
1031
+ };
1032
+ }
1033
+ const REGION_FIELDS = {
1034
+ start: {
1035
+ required: true,
1036
+ is: isFiniteNumber,
1037
+ want: "a number"
1038
+ },
1039
+ end: {
1040
+ required: true,
1041
+ is: isFiniteNumber,
1042
+ want: "a number"
1043
+ },
1044
+ complexity: {
1045
+ is: isNonNegative,
1046
+ want: "a number >= 0"
1047
+ },
1048
+ inflation: group({ max: {
1049
+ is: isNonNegative,
1050
+ want: "a number >= 0"
1051
+ } }),
1052
+ strings: group({ encode: {
1053
+ is: (v) => typeof v === "boolean",
1054
+ want: "true or false"
1055
+ } }),
1056
+ transforms: group({
1057
+ only: {
1058
+ is: isTransformKinds,
1059
+ want: KINDS
1060
+ },
1061
+ deny: {
1062
+ is: isTransformKinds,
1063
+ want: KINDS
1064
+ }
1065
+ }),
1066
+ label: {
1067
+ is: (v) => typeof v === "string",
1068
+ want: "a string"
1069
+ }
1070
+ };
1071
+ const RESERVED_FIELDS = {
1072
+ glob: {
1073
+ required: true,
1074
+ is: (v) => typeof v === "string",
1075
+ want: "a string"
1076
+ },
1077
+ names: {
1078
+ required: true,
1079
+ is: (v) => Array.isArray(v) && v.every((n) => typeof n === "string"),
1080
+ want: "a list of names"
1081
+ }
1082
+ };
1083
+ function leafNames(spec, prefix) {
1084
+ return Object.entries(spec).flatMap(([name, field]) => field.fields ? leafNames(field.fields, `${prefix}${name}.`) : [prefix + name]);
1085
+ }
1086
+ function checkFields(spec, value, prefix = "") {
1087
+ for (const name of Object.keys(value)) {
1088
+ if (name in spec) continue;
1089
+ const near = nearestName(prefix + name, Object.keys(spec).map((n) => prefix + n));
1090
+ return `item has an unknown field \`${prefix}${name}\`` + (near ? ` — did you mean \`${near}\`?` : "") + ` (allowed: ${leafNames(spec, prefix).join(", ")})`;
1091
+ }
1092
+ for (const [name, field] of Object.entries(spec)) {
1093
+ const present = value[name];
1094
+ if (present === void 0) {
1095
+ if (field.required) return `item is missing \`${prefix}${name}\` (${field.want})`;
1096
+ continue;
1097
+ }
1098
+ if (!field.is(present)) return `item's \`${prefix}${name}\` must be ${field.want}, got ${JSON.stringify(present)}`;
1099
+ if (field.fields) {
1100
+ const nested = checkFields(field.fields, present, `${prefix}${name}.`);
1101
+ if (nested) return nested;
1102
+ }
1103
+ }
1104
+ return void 0;
1105
+ }
1106
+ function expected(item, value) {
1107
+ return `expected ${describe(item)}, got ${JSON.stringify(value)}`;
1108
+ }
1109
+ function checkItem(item, value) {
1110
+ switch (item.kind) {
1111
+ case "boolean": return typeof value === "boolean" ? void 0 : expected(item, value);
1112
+ case "number": {
1113
+ if (typeof value !== "number" || !Number.isFinite(value)) return expected(item, value);
1114
+ if (value < item.min) return expected(item, value);
1115
+ if (item.integer && !Number.isInteger(value)) return expected(item, value);
1116
+ return void 0;
1117
+ }
1118
+ case "unbounded": {
1119
+ if (value === item.unlimited) return void 0;
1120
+ if (typeof value === "number" && Number.isFinite(value) && value >= item.min) return void 0;
1121
+ return `${expected(item, value)} — there is no \`Infinity\` in JSON; write "${item.unlimited}"`;
1122
+ }
1123
+ case "string": return typeof value === "string" ? void 0 : expected(item, value);
1124
+ case "enum": return typeof value === "string" && item.values.includes(value) ? void 0 : expected(item, value);
1125
+ case "seed": return typeof value === "number" || typeof value === "string" ? void 0 : expected(item, value);
1126
+ case "reserved": {
1127
+ if (typeof value === "string") return void 0;
1128
+ if (!isPlainObject(value)) return expected(item, value);
1129
+ return checkFields(RESERVED_FIELDS, value);
1130
+ }
1131
+ case "region": {
1132
+ if (!isPlainObject(value)) return expected(item, value);
1133
+ return checkFields(REGION_FIELDS, value);
1134
+ }
1135
+ }
1136
+ }
1137
+ function checkValue(key, value) {
1138
+ if (key.shape === "scalar") {
1139
+ const failure = checkItem(key.item, value);
1140
+ return failure ? `\`${key.path}\`: ${failure}` : void 0;
1141
+ }
1142
+ if (!Array.isArray(value)) return `\`${key.path}\`: expected a list of values, got ${JSON.stringify(value)}`;
1143
+ for (const entry of value) {
1144
+ const failure = checkItem(key.item, entry);
1145
+ if (failure) return `\`${key.path}\`: ${failure}`;
1146
+ }
1147
+ return void 0;
1148
+ }
1149
+ function misdirectedTo(key, value) {
1150
+ if (key.namedValuesOf === void 0 || typeof value !== "string") return void 0;
1151
+ const other = CONFIG_BY_PATH.get(key.namedValuesOf);
1152
+ if (!other || other.shape !== "scalar") return void 0;
1153
+ return checkItem(other.item, value) === void 0 ? other : void 0;
1154
+ }
1155
+ function validateConfig(input, surface) {
1156
+ const issues = [];
1157
+ const config = {};
1158
+ if (input === void 0 || input === null) return {
1159
+ config,
1160
+ issues
1161
+ };
1162
+ if (!isPlainObject(input)) {
1163
+ issues.push({
1164
+ path: "",
1165
+ message: `configuration (${surface}) must be an object`
1166
+ });
1167
+ return {
1168
+ config,
1169
+ issues
1170
+ };
1171
+ }
1172
+ walk(input, "", config, issues, surface);
1173
+ return {
1174
+ config,
1175
+ issues
1176
+ };
1177
+ }
1178
+ function walk(source, prefix, target, issues, surface) {
1179
+ for (const [name, value] of Object.entries(source)) {
1180
+ if (value === void 0) continue;
1181
+ const path = prefix ? `${prefix}.${name}` : name;
1182
+ const key = CONFIG_BY_PATH.get(path);
1183
+ if (key) {
1184
+ const failure = checkValue(key, value);
1185
+ if (failure) {
1186
+ const hint = misdirectedHint(key, value, (p, v) => `"${p}": ${JSON.stringify(v)}`);
1187
+ issues.push({
1188
+ path,
1189
+ message: `${failure} (${surface})${hint}`
1190
+ });
1191
+ } else target[name] = value;
1192
+ continue;
1193
+ }
1194
+ if (CONFIG_PREFIXES.has(path)) {
1195
+ if (isPlainObject(value)) {
1196
+ const nested = {};
1197
+ walk(value, path, nested, issues, surface);
1198
+ if (Object.keys(nested).length > 0) target[name] = nested;
1199
+ continue;
1200
+ }
1201
+ const enabled = groupBooleanKey(path);
1202
+ if (enabled && typeof value === "boolean") {
1203
+ target[name] = { enabled: value };
1204
+ continue;
1205
+ }
1206
+ }
1207
+ issues.push({
1208
+ path,
1209
+ message: unknownKeyMessage(path, surface)
1210
+ });
1211
+ }
1310
1212
  }
1311
- function nearestName(name, candidates) {
1312
- const target = normalizeKey(name);
1313
- let best;
1314
- for (const candidate of candidates) {
1315
- const distance = editDistance(target, normalizeKey(candidate));
1316
- if (distance > Math.max(2, Math.floor(target.length / 4))) continue;
1317
- if (!best || distance < best.distance) best = {
1318
- name: candidate,
1319
- distance
1320
- };
1213
+ function deepMerge(base, override) {
1214
+ const out = { ...base };
1215
+ for (const [name, value] of Object.entries(override)) {
1216
+ if (value === void 0) continue;
1217
+ const existing = out[name];
1218
+ out[name] = isPlainObject(value) && isPlainObject(existing) ? deepMerge(existing, value) : value;
1321
1219
  }
1322
- return best?.name;
1220
+ return out;
1323
1221
  }
1324
- function suggestKey(key) {
1325
- const exact = BY_NORMALIZED.get(normalizeKey(key));
1326
- if (exact) return exact.path;
1327
- const near = nearestName(key, CONFIG_KEYS.map((k) => k.path));
1328
- if (near) return near;
1329
- const tail = normalizeKey(key);
1330
- const owners = CONFIG_KEYS.filter((k) => normalizeKey(k.path.slice(k.path.lastIndexOf(".") + 1)) === tail);
1331
- return owners.length === 1 ? owners[0].path : void 0;
1222
+ function mergeInto(base, override) {
1223
+ return deepMerge(base, override);
1332
1224
  }
1333
- function canonicalSpelling(name) {
1334
- const norm$1 = normalizeKey(name);
1335
- const key = BY_NORMALIZED.get(norm$1);
1336
- if (key) return { key: key.path };
1337
- const group$1 = CHILDREN_BY_NORMALIZED.get(norm$1);
1338
- return group$1 && group$1.length > 0 ? { group: group$1 } : void 0;
1225
+ function mergeConfig(base, override) {
1226
+ return deepMerge(base, override);
1339
1227
  }
1340
- function editDistance(a, b) {
1341
- const prev = new Array(b.length + 1);
1342
- const next = new Array(b.length + 1);
1343
- for (let j = 0; j <= b.length; j++) prev[j] = j;
1344
- for (let i = 1; i <= a.length; i++) {
1345
- next[0] = i;
1346
- for (let j = 1; j <= b.length; j++) next[j] = Math.min(prev[j] + 1, next[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
1347
- for (let j = 0; j <= b.length; j++) prev[j] = next[j];
1228
+ function getPath(config, path) {
1229
+ let current = config;
1230
+ for (const part of path.split(".")) {
1231
+ if (!isPlainObject(current)) return void 0;
1232
+ current = current[part];
1348
1233
  }
1349
- return prev[b.length];
1234
+ return current;
1350
1235
  }
1351
- const DOCS_URL = "https://www.afterpack.dev/docs/config";
1352
- function unknownKeyMessage(path, surface) {
1353
- const group$1 = CHILDREN_BY_NORMALIZED.get(normalizeKey(path));
1354
- if (group$1 && group$1.length > 0) {
1355
- const list = group$1.map((child) => `\`${child}\``).join(", ");
1356
- const tail$1 = group$1.length === 1 ? `did you mean ${list}?` : `its keys are ${list}`;
1357
- const canonical = PREFIX_BY_NORMALIZED.get(normalizeKey(path));
1358
- const enabled = canonical ? groupBooleanKey(canonical) : void 0;
1359
- const rule = enabled ? `; a boolean here means \`${enabled.path}\`` : "";
1360
- return `\`${path}\` is a group of configuration keys, not a key itself (${surface}) — ${tail$1}${rule}`;
1236
+ function nest(path, value) {
1237
+ return path.split(".").reduceRight((inner, segment) => ({ [segment]: inner }), value);
1238
+ }
1239
+ function setPath(target, path, value) {
1240
+ const parts = path.split(".");
1241
+ let node = target;
1242
+ for (const part of parts.slice(0, -1)) {
1243
+ if (!isPlainObject(node[part])) node[part] = {};
1244
+ node = node[part];
1361
1245
  }
1362
- const suggestion = suggestKey(path);
1363
- const tail = suggestion ? ` — did you mean \`${suggestion}\`?` : ` — see ${DOCS_URL}`;
1364
- return `unknown configuration key \`${path}\` (${surface})${tail}`;
1246
+ node[parts[parts.length - 1]] = value;
1365
1247
  }
1366
- function isPlainObject(value) {
1367
- return typeof value === "object" && value !== null && !Array.isArray(value);
1248
+ function toEngineConfig(config) {
1249
+ const out = {};
1250
+ for (const key of CONFIG_KEYS) {
1251
+ if (key.surface !== "engine") continue;
1252
+ const value = getPath(config, key.path);
1253
+ if (value === void 0) continue;
1254
+ setPath(out, key.path, value);
1255
+ }
1256
+ return out;
1368
1257
  }
1369
- function describe(item) {
1370
- switch (item.kind) {
1371
- case "boolean": return "true or false";
1372
- case "number": return item.integer ? `an integer >= ${item.min}` : `a number >= ${item.min}`;
1373
- case "unbounded": return `a number >= ${item.min}, or the string "${item.unlimited}"`;
1374
- case "string": return "a string";
1375
- case "enum": return `one of: ${item.values.join(", ")}`;
1376
- case "seed": return "a number, any string, or \"git\"";
1377
- case "reserved": return "a name, or { \"glob\": \"…\", \"names\": [\"…\"] }";
1378
- case "region": return "an object with numeric `start` and `end`";
1258
+ function toPluginOptions(config) {
1259
+ const read = (path) => getPath(config, path);
1260
+ const set = (container) => Object.values(container).some((v) => v !== void 0) ? container : void 0;
1261
+ return {
1262
+ artifactOptions: {
1263
+ protectionMap: set({ enabled: read("protectionMap.enabled") }),
1264
+ sourceMap: set({
1265
+ enabled: read("sourceMap.enabled"),
1266
+ emitUrl: read("sourceMap.emitUrl")
1267
+ }),
1268
+ build: set({
1269
+ backup: read("build.backup"),
1270
+ mode: read("build.mode")
1271
+ }),
1272
+ allowUnobfuscated: read("allowUnobfuscated"),
1273
+ telemetry: set({ enabled: read("telemetry.enabled") })
1274
+ },
1275
+ seed: read("seed"),
1276
+ preset: read("preset"),
1277
+ complexity: read("complexity"),
1278
+ regions: read("regions"),
1279
+ directives: {
1280
+ enabled: read("directives.enabled") ?? DIRECTIVES_ENABLED_DEFAULT,
1281
+ explicit: read("directives.enabled") !== void 0
1282
+ },
1283
+ build: set({ autorun: read("build.autorun") }),
1284
+ diagnostics: set({
1285
+ level: read("diagnostics.level"),
1286
+ format: read("diagnostics.format")
1287
+ }),
1288
+ paths: set({ include: read("paths.include") }),
1289
+ key: read("key")
1290
+ };
1291
+ }
1292
+
1293
+ //#endregion
1294
+ //#region src/source-map.ts
1295
+ const SOURCE_MAPPING_URL_RE = /\/\/[#@]\s*sourceMappingURL=(\S+)\s*$/gm;
1296
+ const SOURCE_MAPPING_URL_LINE_RE = /^[ \t]*\/\/[#@]\s*sourceMappingURL=\S+[ \t]*\r?\n?/gm;
1297
+ const CSS_SOURCE_MAPPING_URL_RE = /[ \t]*\/\*[#@]\s*sourceMappingURL=[^\s*]+\s*\*\/\s*$/;
1298
+ function withSourceMappingURL(code, url) {
1299
+ const stripped = code.replace(SOURCE_MAPPING_URL_LINE_RE, "");
1300
+ if (url == null) return stripped;
1301
+ const separator = stripped.length > 0 && !stripped.endsWith("\n") ? "\n" : "";
1302
+ return `${stripped}${separator}//# sourceMappingURL=${url}\n`;
1303
+ }
1304
+ function withoutCssSourceMappingURL(css) {
1305
+ return css.replace(CSS_SOURCE_MAPPING_URL_RE, "");
1306
+ }
1307
+ function extractSourceMappingURL(code) {
1308
+ let last = null;
1309
+ for (const match of code.matchAll(SOURCE_MAPPING_URL_RE)) last = match[1];
1310
+ return last;
1311
+ }
1312
+ function isRemoteSourceMappingURL(url) {
1313
+ return /^https?:\/\//i.test(url) || url.startsWith("//");
1314
+ }
1315
+ function decodeDataUri(url) {
1316
+ if (!url.startsWith("data:")) return null;
1317
+ const comma = url.indexOf(",");
1318
+ if (comma === -1) return null;
1319
+ const meta = url.slice(5, comma);
1320
+ const payload = url.slice(comma + 1);
1321
+ try {
1322
+ if (/;base64/i.test(meta)) return Buffer.from(payload, "base64").toString("utf8");
1323
+ return decodeURIComponent(payload);
1324
+ } catch {
1325
+ return null;
1379
1326
  }
1380
1327
  }
1381
- function misdirectedHint(key, value, spell) {
1382
- const other = misdirectedTo(key, value);
1383
- if (!other) return "";
1384
- const written = spell(other.path, String(value));
1385
- return ` — \`${String(value)}\` is a \`${other.path}\` value; write \`${written}\` instead`;
1328
+ function discoverInputSourceMap(jsPath, code) {
1329
+ const adjacent = `${jsPath}.map`;
1330
+ if (existsSync(adjacent)) try {
1331
+ return readFileSync(adjacent, "utf8");
1332
+ } catch {}
1333
+ let source = code;
1334
+ if (source == null) try {
1335
+ source = readFileSync(jsPath, "utf8");
1336
+ } catch {
1337
+ return null;
1338
+ }
1339
+ const url = extractSourceMappingURL(source);
1340
+ if (url == null) return null;
1341
+ if (url.startsWith("data:")) return decodeDataUri(url);
1342
+ if (isRemoteSourceMappingURL(url)) return null;
1343
+ let mapPath;
1344
+ try {
1345
+ mapPath = isAbsolute(url) ? url : resolve(dirname(jsPath), decodeURIComponent(url));
1346
+ } catch {
1347
+ return null;
1348
+ }
1349
+ if (!existsSync(mapPath)) return null;
1350
+ try {
1351
+ return readFileSync(mapPath, "utf8");
1352
+ } catch {
1353
+ return null;
1354
+ }
1386
1355
  }
1387
- const isFiniteNumber = (v) => typeof v === "number" && Number.isFinite(v);
1388
- const isTransformKinds = (v) => Array.isArray(v) && v.every((k) => TRANSFORM_KIND_VALUES.includes(k));
1389
- const KINDS = `a list of: ${TRANSFORM_KIND_VALUES.join(", ")}`;
1390
- const isNonNegative = (v) => isFiniteNumber(v) && v >= 0;
1391
- function group(fields) {
1356
+
1357
+ //#endregion
1358
+ //#region src/bundle.ts
1359
+ const BUNDLE_JS_RE = /\.[cm]?js$/;
1360
+ const CSS_MAP_RE = /\.css\.map$/;
1361
+ function collectBundleJs(bundle, outDir) {
1362
+ const files = [];
1363
+ const inputs = new Map();
1364
+ const entries = new Map();
1365
+ for (const [fileName, entry] of Object.entries(bundle)) {
1366
+ if (!BUNDLE_JS_RE.test(fileName)) continue;
1367
+ const source = entry.type === "chunk" ? entry.code : typeof entry.source === "string" ? entry.source : void 0;
1368
+ if (source === void 0) continue;
1369
+ const filePath = resolve(outDir, fileName);
1370
+ files.push(filePath);
1371
+ entries.set(filePath, entry);
1372
+ inputs.set(filePath, {
1373
+ source,
1374
+ sourceMap: entry.map ? entry.map.toString() : null
1375
+ });
1376
+ }
1392
1377
  return {
1393
- is: isPlainObject,
1394
- want: "an object",
1395
- fields
1378
+ files,
1379
+ inputs,
1380
+ entries
1396
1381
  };
1397
1382
  }
1398
- const REGION_FIELDS = {
1399
- start: {
1400
- required: true,
1401
- is: isFiniteNumber,
1402
- want: "a number"
1403
- },
1404
- end: {
1405
- required: true,
1406
- is: isFiniteNumber,
1407
- want: "a number"
1408
- },
1409
- complexity: {
1410
- is: isNonNegative,
1411
- want: "a number >= 0"
1412
- },
1413
- inflation: group({ max: {
1414
- is: isNonNegative,
1415
- want: "a number >= 0"
1416
- } }),
1417
- strings: group({ encode: {
1418
- is: (v) => typeof v === "boolean",
1419
- want: "true or false"
1420
- } }),
1421
- transforms: group({
1422
- only: {
1423
- is: isTransformKinds,
1424
- want: KINDS
1425
- },
1426
- deny: {
1427
- is: isTransformKinds,
1428
- want: KINDS
1429
- }
1430
- }),
1431
- label: {
1432
- is: (v) => typeof v === "string",
1433
- want: "a string"
1383
+ function sourceTypeForBundle(format, entries) {
1384
+ for (const entry of entries) if (entry.type !== "chunk") return void 0;
1385
+ return sourceTypeForOutputFormat(format);
1386
+ }
1387
+ function dataUri(json) {
1388
+ return `data:application/json;charset=utf-8;base64,${Buffer.from(json, "utf8").toString("base64")}`;
1389
+ }
1390
+ function applyBundleOutput(bundle, entry, out, policy) {
1391
+ if (entry.type !== "chunk") {
1392
+ entry.source = out.code;
1393
+ return;
1434
1394
  }
1435
- };
1436
- const RESERVED_FIELDS = {
1437
- glob: {
1438
- required: true,
1439
- is: (v) => typeof v === "string",
1440
- want: "a string"
1441
- },
1442
- names: {
1443
- required: true,
1444
- is: (v) => Array.isArray(v) && v.every((n) => typeof n === "string"),
1445
- want: "a list of names"
1395
+ const mapName = entry.sourcemapFileName ?? null;
1396
+ const inlineMap = mapName == null && entry.map != null;
1397
+ const emitMap = policy.sourceMap && out.sourceMap != null;
1398
+ let url = null;
1399
+ if (emitMap && out.sourceMap != null) {
1400
+ if (mapName != null && bundle[mapName]) {
1401
+ bundle[mapName].source = out.sourceMap;
1402
+ url = basename(mapName);
1403
+ } else if (inlineMap) url = dataUri(out.sourceMap);
1404
+ } else {
1405
+ if (mapName != null) delete bundle[mapName];
1406
+ entry.map = null;
1446
1407
  }
1447
- };
1448
- function leafNames(spec, prefix) {
1449
- return Object.entries(spec).flatMap(([name, field]) => field.fields ? leafNames(field.fields, `${prefix}${name}.`) : [prefix + name]);
1408
+ entry.code = withSourceMappingURL(out.code, policy.emitSourceMappingURL ? url : null);
1450
1409
  }
1451
- function checkFields(spec, value, prefix = "") {
1452
- for (const name of Object.keys(value)) {
1453
- if (name in spec) continue;
1454
- const near = nearestName(prefix + name, Object.keys(spec).map((n) => prefix + n));
1455
- return `item has an unknown field \`${prefix}${name}\`` + (near ? ` — did you mean \`${near}\`?` : "") + ` (allowed: ${leafNames(spec, prefix).join(", ")})`;
1456
- }
1457
- for (const [name, field] of Object.entries(spec)) {
1458
- const present = value[name];
1459
- if (present === void 0) {
1460
- if (field.required) return `item is missing \`${prefix}${name}\` (${field.want})`;
1410
+ function stripBundleCssSourceMaps(bundle) {
1411
+ for (const [fileName, entry] of Object.entries(bundle)) {
1412
+ if (CSS_MAP_RE.test(fileName)) {
1413
+ delete bundle[fileName];
1461
1414
  continue;
1462
1415
  }
1463
- if (!field.is(present)) return `item's \`${prefix}${name}\` must be ${field.want}, got ${JSON.stringify(present)}`;
1464
- if (field.fields) {
1465
- const nested = checkFields(field.fields, present, `${prefix}${name}.`);
1466
- if (nested) return nested;
1467
- }
1416
+ if (entry.type !== "asset" || !fileName.endsWith(".css") || entry.source === void 0) continue;
1417
+ const css = typeof entry.source === "string" ? entry.source : Buffer.from(entry.source).toString("utf8");
1418
+ const stripped = withoutCssSourceMappingURL(css);
1419
+ if (stripped !== css) entry.source = stripped;
1468
1420
  }
1469
- return void 0;
1470
1421
  }
1471
- function expected(item, value) {
1472
- return `expected ${describe(item)}, got ${JSON.stringify(value)}`;
1422
+
1423
+ //#endregion
1424
+ //#region src/glob.ts
1425
+ function normalize(value) {
1426
+ return value.includes("\\") ? value.replaceAll("\\", "/") : value;
1473
1427
  }
1474
- function checkItem(item, value) {
1475
- switch (item.kind) {
1476
- case "boolean": return typeof value === "boolean" ? void 0 : expected(item, value);
1477
- case "number": {
1478
- if (typeof value !== "number" || !Number.isFinite(value)) return expected(item, value);
1479
- if (value < item.min) return expected(item, value);
1480
- if (item.integer && !Number.isInteger(value)) return expected(item, value);
1481
- return void 0;
1482
- }
1483
- case "unbounded": {
1484
- if (value === item.unlimited) return void 0;
1485
- if (typeof value === "number" && Number.isFinite(value) && value >= item.min) return void 0;
1486
- return `${expected(item, value)} — there is no \`Infinity\` in JSON; write "${item.unlimited}"`;
1487
- }
1488
- case "string": return typeof value === "string" ? void 0 : expected(item, value);
1489
- case "enum": return typeof value === "string" && item.values.includes(value) ? void 0 : expected(item, value);
1490
- case "seed": return typeof value === "number" || typeof value === "string" ? void 0 : expected(item, value);
1491
- case "reserved": {
1492
- if (typeof value === "string") return void 0;
1493
- if (!isPlainObject(value)) return expected(item, value);
1494
- return checkFields(RESERVED_FIELDS, value);
1495
- }
1496
- case "region": {
1497
- if (!isPlainObject(value)) return expected(item, value);
1498
- return checkFields(REGION_FIELDS, value);
1499
- }
1500
- }
1428
+ function segments(value) {
1429
+ return value.split("/").filter((part) => part !== "");
1501
1430
  }
1502
- function checkValue(key, value) {
1503
- if (key.shape === "scalar") {
1504
- const failure = checkItem(key.item, value);
1505
- return failure ? `\`${key.path}\`: ${failure}` : void 0;
1506
- }
1507
- if (!Array.isArray(value)) return `\`${key.path}\`: expected a list of values, got ${JSON.stringify(value)}`;
1508
- for (const entry of value) {
1509
- const failure = checkItem(key.item, entry);
1510
- if (failure) return `\`${key.path}\`: ${failure}`;
1431
+ function isAnchored(pattern) {
1432
+ if (pattern.startsWith("/")) return true;
1433
+ return pattern.length >= 2 && pattern[1] === ":" && /^[A-Za-z]$/.test(pattern[0]);
1434
+ }
1435
+ function segmentMatches(pattern, seg) {
1436
+ if (!pattern.includes("*") && !pattern.includes("?")) return pattern === seg;
1437
+ const p = [...pattern];
1438
+ const s = [...seg];
1439
+ let pi = 0;
1440
+ let si = 0;
1441
+ let star = -1;
1442
+ let starSi = 0;
1443
+ while (si < s.length) if (pi < p.length && p[pi] === "*") {
1444
+ star = pi;
1445
+ starSi = si;
1446
+ pi += 1;
1447
+ } else if (pi < p.length && (p[pi] === "?" || p[pi] === s[si])) {
1448
+ pi += 1;
1449
+ si += 1;
1450
+ } else if (star >= 0) {
1451
+ pi = star + 1;
1452
+ starSi += 1;
1453
+ si = starSi;
1454
+ } else return false;
1455
+ return p.slice(pi).every((c) => c === "*");
1456
+ }
1457
+ function segmentsMatch(pattern, path) {
1458
+ let pi = 0;
1459
+ let si = 0;
1460
+ let star = -1;
1461
+ let starSi = 0;
1462
+ while (si < path.length) if (pi < pattern.length && pattern[pi] === "**") {
1463
+ star = pi;
1464
+ starSi = si;
1465
+ pi += 1;
1466
+ } else if (pi < pattern.length && segmentMatches(pattern[pi], path[si])) {
1467
+ pi += 1;
1468
+ si += 1;
1469
+ } else if (star >= 0) {
1470
+ pi = star + 1;
1471
+ starSi += 1;
1472
+ si = starSi;
1473
+ } else return false;
1474
+ return pattern.slice(pi).every((s) => s === "**");
1475
+ }
1476
+ function matchesPath(pattern, path) {
1477
+ const pat = normalize(pattern);
1478
+ const parts = segments(pat);
1479
+ if (parts.length === 0) return false;
1480
+ const segs = segments(normalize(path));
1481
+ if (isAnchored(pat)) return segmentsMatch(parts, segs);
1482
+ for (let i = 0; i <= segs.length; i++) if (segmentsMatch(parts, segs.slice(i))) return true;
1483
+ return false;
1484
+ }
1485
+ function reachesInto(pattern, dir) {
1486
+ const pat = normalize(pattern);
1487
+ const parts = segments(pat);
1488
+ if (parts.length === 0) return false;
1489
+ if (!isAnchored(pat)) return true;
1490
+ for (let k = 1; k <= parts.length; k++) if (matchesPath(`/${parts.slice(0, k).join("/")}`, dir)) return true;
1491
+ return false;
1492
+ }
1493
+
1494
+ //#endregion
1495
+ //#region src/collect.ts
1496
+ const BACKUP_RE = /\.backup\.[0-9a-f]{8}\.[cm]?js$/;
1497
+ const NODE_MODULES = "node_modules";
1498
+ function isCollectableJs(name) {
1499
+ if (BACKUP_RE.test(name)) return false;
1500
+ return name.endsWith(".js") || name.endsWith(".mjs") || name.endsWith(".cjs");
1501
+ }
1502
+ function statOrNull(path) {
1503
+ try {
1504
+ return statSync(path);
1505
+ } catch {
1506
+ return null;
1511
1507
  }
1512
- return void 0;
1513
1508
  }
1514
- function misdirectedTo(key, value) {
1515
- if (key.namedValuesOf === void 0 || typeof value !== "string") return void 0;
1516
- const other = CONFIG_BY_PATH.get(key.namedValuesOf);
1517
- if (!other || other.shape !== "scalar") return void 0;
1518
- return checkItem(other.item, value) === void 0 ? other : void 0;
1509
+ function collectJsFiles(target, options = {}) {
1510
+ const stat = statOrNull(target);
1511
+ if (!stat) return [];
1512
+ if (!stat.isDirectory()) return isCollectableJs(basename(target)) ? [target] : [];
1513
+ return walkJs(target, options.include ?? [], false, options.onNestedProject);
1519
1514
  }
1520
- function validateConfig(input, surface) {
1521
- const issues = [];
1522
- const config = {};
1523
- if (input === void 0 || input === null) return {
1524
- config,
1525
- issues
1526
- };
1527
- if (!isPlainObject(input)) {
1528
- issues.push({
1529
- path: "",
1530
- message: `configuration (${surface}) must be an object`
1531
- });
1532
- return {
1533
- config,
1534
- issues
1535
- };
1515
+ function entriesOf(dir) {
1516
+ try {
1517
+ return readdirSync(dir, { withFileTypes: true });
1518
+ } catch {
1519
+ return [];
1536
1520
  }
1537
- walk(input, "", config, issues, surface);
1538
- return {
1539
- config,
1540
- issues
1541
- };
1542
1521
  }
1543
- function walk(source, prefix, target, issues, surface) {
1544
- for (const [name, value] of Object.entries(source)) {
1545
- if (value === void 0) continue;
1546
- const path = prefix ? `${prefix}.${name}` : name;
1547
- const key = CONFIG_BY_PATH.get(path);
1548
- if (key) {
1549
- const failure = checkValue(key, value);
1550
- if (failure) {
1551
- const hint = misdirectedHint(key, value, (p, v) => `"${p}": ${JSON.stringify(v)}`);
1552
- issues.push({
1553
- path,
1554
- message: `${failure} (${surface})${hint}`
1555
- });
1556
- } else target[name] = value;
1557
- continue;
1558
- }
1559
- if (CONFIG_PREFIXES.has(path)) {
1560
- if (isPlainObject(value)) {
1561
- const nested = {};
1562
- walk(value, path, nested, issues, surface);
1563
- if (Object.keys(nested).length > 0) target[name] = nested;
1564
- continue;
1565
- }
1566
- const enabled = groupBooleanKey(path);
1567
- if (enabled && typeof value === "boolean") {
1568
- target[name] = { enabled: value };
1522
+ function kindOf(entry, full) {
1523
+ if (entry.isDirectory()) return "dir";
1524
+ if (entry.isFile()) return "file";
1525
+ const stat = statOrNull(full);
1526
+ if (!stat) return null;
1527
+ return stat.isDirectory() ? "dir" : "file";
1528
+ }
1529
+ function isNestedProject(dir) {
1530
+ return existsSync(join(dir, "package.json"));
1531
+ }
1532
+ function walkJs(dir, include, readmitted, onNestedProject) {
1533
+ const out = [];
1534
+ for (const entry of entriesOf(dir)) {
1535
+ const name = entry.name;
1536
+ const full = join(dir, name);
1537
+ const kind = kindOf(entry, full);
1538
+ if (kind === null) continue;
1539
+ if (kind === "dir") {
1540
+ const skipped = name === NODE_MODULES;
1541
+ if (!skipped && !readmitted && isNestedProject(full)) {
1542
+ onNestedProject?.(full);
1569
1543
  continue;
1570
1544
  }
1545
+ if (skipped && !include.some((pattern) => reachesInto(pattern, full))) continue;
1546
+ out.push(...walkJs(full, include, readmitted || skipped, onNestedProject));
1547
+ } else if (isCollectableJs(name)) {
1548
+ if (readmitted && !include.some((pattern) => matchesPath(pattern, full))) continue;
1549
+ out.push(full);
1571
1550
  }
1572
- issues.push({
1573
- path,
1574
- message: unknownKeyMessage(path, surface)
1575
- });
1576
1551
  }
1552
+ return out;
1577
1553
  }
1578
- function deepMerge(base, override) {
1579
- const out = { ...base };
1580
- for (const [name, value] of Object.entries(override)) {
1581
- if (value === void 0) continue;
1582
- const existing = out[name];
1583
- out[name] = isPlainObject(value) && isPlainObject(existing) ? deepMerge(existing, value) : value;
1554
+ const SOURCE_MAP_RE = /\.(?:[cm]?js|css)\.map$/;
1555
+ function collectFiles(dir, accept) {
1556
+ if (!existsSync(dir)) return [];
1557
+ const out = [];
1558
+ for (const entry of entriesOf(dir)) {
1559
+ const name = entry.name;
1560
+ const full = join(dir, name);
1561
+ const kind = kindOf(entry, full);
1562
+ if (kind === null) continue;
1563
+ if (kind === "dir") out.push(...collectFiles(full, accept));
1564
+ else if (accept(name)) out.push(full);
1584
1565
  }
1585
1566
  return out;
1586
1567
  }
1587
- function mergeInto(base, override) {
1588
- return deepMerge(base, override);
1568
+ function collectSourceMaps(dir) {
1569
+ return collectFiles(dir, (name) => SOURCE_MAP_RE.test(name));
1589
1570
  }
1590
- function mergeConfig(base, override) {
1591
- return deepMerge(base, override);
1571
+ function collectStylesheets(dir) {
1572
+ return collectFiles(dir, (name) => name.endsWith(".css"));
1592
1573
  }
1593
- function getPath(config, path) {
1594
- let current = config;
1595
- for (const part of path.split(".")) {
1596
- if (!isPlainObject(current)) return void 0;
1597
- current = current[part];
1574
+
1575
+ //#endregion
1576
+ //#region src/notices.ts
1577
+ const NOTICE_MESSAGE_LIMIT = 500;
1578
+ const NOTICE_LIMIT = 5;
1579
+ const NOTICE_CODE_LIMIT = 64;
1580
+ const NOTICE_HOSTS = new Set(["afterpack.dev", "www.afterpack.dev"]);
1581
+ const ESC = 27;
1582
+ const BEL = 7;
1583
+ const C1_CSI = 155;
1584
+ const C1_OSC = 157;
1585
+ function isControl(code) {
1586
+ return code < 32 || code >= 127 && code <= 159;
1587
+ }
1588
+ function isInvisibleFormat(code) {
1589
+ return code === 1564 || code >= 8203 && code <= 8207 || code >= 8234 && code <= 8238 || code >= 8288 && code <= 8297 || code === 65279;
1590
+ }
1591
+ function skipCsi(text, from) {
1592
+ let i = from;
1593
+ while (i < text.length) {
1594
+ const c = text.charCodeAt(i);
1595
+ i += 1;
1596
+ if (c >= 64 && c <= 126) return i;
1598
1597
  }
1599
- return current;
1598
+ return i;
1600
1599
  }
1601
- function nest(path, value) {
1602
- return path.split(".").reduceRight((inner, segment) => ({ [segment]: inner }), value);
1600
+ function skipOsc(text, from) {
1601
+ let i = from;
1602
+ while (i < text.length) {
1603
+ const c = text.charCodeAt(i);
1604
+ if (c === BEL) return i + 1;
1605
+ if (c === ESC) return text.charCodeAt(i + 1) === 92 ? i + 2 : i + 1;
1606
+ if (c === 156) return i + 1;
1607
+ i += 1;
1608
+ }
1609
+ return i;
1603
1610
  }
1604
- function setPath(target, path, value) {
1605
- const parts = path.split(".");
1606
- let node = target;
1607
- for (const part of parts.slice(0, -1)) {
1608
- if (!isPlainObject(node[part])) node[part] = {};
1609
- node = node[part];
1611
+ function stripTerminalControls(text) {
1612
+ let out = "";
1613
+ let i = 0;
1614
+ while (i < text.length) {
1615
+ const c = text.charCodeAt(i);
1616
+ if (c === ESC) {
1617
+ const next = text.charCodeAt(i + 1);
1618
+ if (next === 91) i = skipCsi(text, i + 2);
1619
+ else if (next === 93) i = skipOsc(text, i + 2);
1620
+ else i += Number.isNaN(next) ? 1 : 2;
1621
+ continue;
1622
+ }
1623
+ if (c === C1_CSI) {
1624
+ i = skipCsi(text, i + 1);
1625
+ continue;
1626
+ }
1627
+ if (c === C1_OSC) {
1628
+ i = skipOsc(text, i + 1);
1629
+ continue;
1630
+ }
1631
+ if (isControl(c)) {
1632
+ out += c === 9 || c === 10 || c === 13 ? " " : "";
1633
+ i += 1;
1634
+ continue;
1635
+ }
1636
+ if (c === 8232 || c === 8233) {
1637
+ out += " ";
1638
+ i += 1;
1639
+ continue;
1640
+ }
1641
+ if (isInvisibleFormat(c)) {
1642
+ i += 1;
1643
+ continue;
1644
+ }
1645
+ out += text[i];
1646
+ i += 1;
1610
1647
  }
1611
- node[parts[parts.length - 1]] = value;
1648
+ return out;
1612
1649
  }
1613
- function toEngineConfig(config) {
1614
- const out = {};
1615
- for (const key of CONFIG_KEYS) {
1616
- if (key.surface !== "engine") continue;
1617
- const value = getPath(config, key.path);
1618
- if (value === void 0) continue;
1619
- setPath(out, key.path, value);
1650
+ function sanitizeServerText(value, limit = NOTICE_MESSAGE_LIMIT) {
1651
+ if (typeof value !== "string") return "";
1652
+ const clean = stripTerminalControls(value).replace(/\s+/g, " ").trim();
1653
+ if (clean.length <= limit) return clean;
1654
+ const chars = Array.from(clean);
1655
+ return chars.length > limit ? chars.slice(0, limit).join("") : clean;
1656
+ }
1657
+ function sanitizeNoticeUrl(value) {
1658
+ if (typeof value !== "string") return null;
1659
+ let url;
1660
+ try {
1661
+ url = new URL(value.trim());
1662
+ } catch {
1663
+ return null;
1664
+ }
1665
+ if (url.protocol !== "https:") return null;
1666
+ if (!NOTICE_HOSTS.has(url.hostname) || url.port !== "") return null;
1667
+ if (url.username !== "" || url.password !== "") return null;
1668
+ const href = url.href;
1669
+ return href.length <= NOTICE_MESSAGE_LIMIT ? href : null;
1670
+ }
1671
+ function noticeSeverity(value) {
1672
+ if (value === "info") return "info";
1673
+ if (value === "error" || value === "critical") return "error";
1674
+ return "warning";
1675
+ }
1676
+ function sanitizeNotices(raw) {
1677
+ if (!Array.isArray(raw)) return [];
1678
+ const out = [];
1679
+ for (const entry of raw) {
1680
+ if (out.length >= NOTICE_LIMIT) break;
1681
+ if (typeof entry !== "object" || entry === null) continue;
1682
+ const n = entry;
1683
+ const message = sanitizeServerText(n.message);
1684
+ if (message === "") continue;
1685
+ out.push({
1686
+ severity: noticeSeverity(n.severity),
1687
+ code: sanitizeServerText(n.code, NOTICE_CODE_LIMIT),
1688
+ message,
1689
+ url: sanitizeNoticeUrl(n.url)
1690
+ });
1620
1691
  }
1621
1692
  return out;
1622
1693
  }
1623
- function toPluginOptions(config) {
1624
- const read = (path) => getPath(config, path);
1625
- const set = (container) => Object.values(container).some((v) => v !== void 0) ? container : void 0;
1626
- return {
1627
- artifactOptions: {
1628
- protectionMap: set({ enabled: read("protectionMap.enabled") }),
1629
- sourceMap: set({
1630
- enabled: read("sourceMap.enabled"),
1631
- emitUrl: read("sourceMap.emitUrl")
1632
- }),
1633
- build: set({
1634
- backup: read("build.backup"),
1635
- mode: read("build.mode")
1636
- }),
1637
- allowUnobfuscated: read("allowUnobfuscated"),
1638
- telemetry: set({ enabled: read("telemetry.enabled") })
1639
- },
1640
- seed: read("seed"),
1641
- preset: read("preset"),
1642
- complexity: read("complexity"),
1643
- regions: read("regions"),
1644
- directives: {
1645
- enabled: read("directives.enabled") ?? DIRECTIVES_ENABLED_DEFAULT,
1646
- explicit: read("directives.enabled") !== void 0
1647
- },
1648
- build: set({ autorun: read("build.autorun") }),
1649
- diagnostics: set({
1650
- level: read("diagnostics.level"),
1651
- format: read("diagnostics.format")
1652
- }),
1653
- paths: set({ include: read("paths.include") }),
1654
- key: read("key")
1655
- };
1694
+ function formatNotice(notice) {
1695
+ const head = notice.severity === "info" ? "AfterPack notice" : `AfterPack ${notice.severity}`;
1696
+ const tail = notice.url ? ` ${notice.url}` : "";
1697
+ return `${head}: ${notice.message}${tail}`;
1698
+ }
1699
+ function reportNotices(raw, logger, prefix = (m) => m) {
1700
+ const notices = sanitizeNotices(raw);
1701
+ for (const notice of notices) {
1702
+ const line = prefix(formatNotice(notice));
1703
+ if (notice.severity === "info" || !logger.warn) logger.log(line);
1704
+ else logger.warn(line);
1705
+ }
1706
+ return notices;
1656
1707
  }
1657
1708
 
1658
1709
  //#endregion
1659
1710
  //#region src/compat.ts
1660
1711
  const MIN_CORE_VERSION = "0.2.0";
1712
+ const SOURCE_TYPE_MIN_CORE_VERSION = "0.2.3";
1661
1713
  const CORE_PACKAGE = "@afterpack/core";
1662
1714
  const VERSION_PATTERN$1 = /^\d{1,9}\.\d{1,9}\.\d{1,9}(?:[-+][0-9A-Za-z.+-]{1,64})?$/;
1663
1715
  const PACKAGE_NAME_PATTERN = /^(?:@[a-z0-9][a-z0-9._-]{0,63}\/)?[a-z0-9][a-z0-9._-]{0,63}$/;
@@ -1729,6 +1781,9 @@ function isBelowVersion(version, minimum) {
1729
1781
  for (let i = 0; i < 3; i++) if (have[i] !== need[i]) return have[i] < need[i];
1730
1782
  return false;
1731
1783
  }
1784
+ function coreSupportsSourceType(coreVersion) {
1785
+ return releaseTriple(coreVersion) !== null && !isBelowVersion(coreVersion, SOURCE_TYPE_MIN_CORE_VERSION);
1786
+ }
1732
1787
  const CLI_PACKAGE = "afterpack";
1733
1788
  function updateCommand(identity, minVersion) {
1734
1789
  const core = `${CORE_PACKAGE}@${safeVersionString(minVersion) ?? "latest"}`;
@@ -2405,6 +2460,7 @@ function buildEngineConfig(options) {
2405
2460
  if (options.complexity !== void 0) defaults.complexity = options.complexity;
2406
2461
  if (options.preset !== void 0) defaults.preset = options.preset;
2407
2462
  else if (options.complexity === void 0) defaults.preset = DEFAULT_PRESET;
2463
+ if (options.sourceType !== void 0) defaults.sourceType = options.sourceType;
2408
2464
  const config = mergeInto({
2409
2465
  ...defaults,
2410
2466
  sourceMap,
@@ -3946,11 +4002,14 @@ async function runObfuscationPass(options) {
3946
4002
  env,
3947
4003
  cwd
3948
4004
  });
4005
+ const localEngineVersion = await readEngineVersion(engine);
4006
+ const derivedSourceType = options.sourceType !== void 0 && coreSupportsSourceType(localEngineVersion ?? options.client?.coreVersion) ? options.sourceType : void 0;
3949
4007
  const engineConfig = buildEngineConfig({
3950
4008
  policy,
3951
4009
  seed,
3952
4010
  preset: options.preset,
3953
4011
  complexity: options.complexity,
4012
+ sourceType: derivedSourceType,
3954
4013
  regions: capture.regions,
3955
4014
  engine: options.engineConfig,
3956
4015
  renameGlobals: capture.renameGlobals
@@ -3988,7 +4047,7 @@ async function runObfuscationPass(options) {
3988
4047
  if (collected.unknownFiles > 0 && batch.source === "cloud") logger.warn(prefix("engine diagnostics are not returned on the Pro Cloud path — this build's diagnostics were recorded server-side."));
3989
4048
  const telemetry = options.telemetry;
3990
4049
  const telemetryEnabled = telemetry != null && resolveTelemetryEnabled(artifactOptions.telemetry?.enabled, env);
3991
- const engineVersion = (batch.source === "cloud" ? safeVersionString(batch.engineVersion) : null) ?? await readEngineVersion(engine);
4050
+ const engineVersion = (batch.source === "cloud" ? safeVersionString(batch.engineVersion) : null) ?? localEngineVersion;
3992
4051
  if (telemetry && telemetryEnabled) {
3993
4052
  const facts = {
3994
4053
  label,
@@ -4307,4 +4366,4 @@ function resolvePluginConfig(input) {
4307
4366
  }
4308
4367
 
4309
4368
  //#endregion
4310
- export { AlreadyObfuscatedError, CLOUD_REFUSAL_SUMMARY, CONFIG_FILE_NAME, CONFIG_KEYS, CORE_FLOOR_SUMMARY, CloudApiError, CoreVersionError, DIAG_ALREADY_OBFUSCATED, DIAG_RECEIPT_UNREADABLE, PROTECTION_RECEIPT_FILE, SEED_ENV_VAR, UnreadableReceiptError, applyBundleOutput, applyResolvedKey, collectBundleJs, collectJsFiles, collectSourceMaps, createTelemetryReporter, decodeDataUri, discoverInputSourceMap, ensureAfterpackGitignore, extractSourceMappingURL, findUpward, getPath, installedRequiredLine, loadConfigFile, mergeConfig, normalizePluginOptions, npxAlternative, parseCliOptions, parseEnvOptions, passSettings, resolveClientIdentity, resolvePluginConfig, resolveReportPolicy, runObfuscationPass, sanitizeNotices, scanDirectives, serverAddsInfo, sha256Of, toEngineConfig, toPluginOptions, validateConfig, verifyProtectionReceipt, withSourceMappingURL, writeArtifacts, writeDeferredProtectionReceipt, writeProtectionReceipt };
4369
+ export { AlreadyObfuscatedError, CLOUD_REFUSAL_SUMMARY, CONFIG_FILE_NAME, CONFIG_KEYS, CORE_FLOOR_SUMMARY, CloudApiError, CoreVersionError, DIAG_ALREADY_OBFUSCATED, DIAG_RECEIPT_UNREADABLE, PROTECTION_RECEIPT_FILE, SEED_ENV_VAR, UnreadableReceiptError, applyBundleOutput, applyResolvedKey, collectBundleJs, collectJsFiles, collectSourceMaps, collectStylesheets, createTelemetryReporter, decodeDataUri, discoverInputSourceMap, ensureAfterpackGitignore, extractSourceMappingURL, findUpward, getPath, installedRequiredLine, loadConfigFile, mergeConfig, normalizePluginOptions, npxAlternative, parseCliOptions, parseEnvOptions, passSettings, resolveClientIdentity, resolvePluginConfig, resolveReportPolicy, runObfuscationPass, sanitizeNotices, scanDirectives, serverAddsInfo, sha256Of, sourceTypeForBundle, sourceTypeForOutputFormat, stripBundleCssSourceMaps, toEngineConfig, toPluginOptions, validateConfig, verifyProtectionReceipt, withSourceMappingURL, withoutCssSourceMappingURL, writeArtifacts, writeDeferredProtectionReceipt, writeProtectionReceipt };