@afterpack/integration-utils 0.2.1 → 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,418 +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
- const CSS_SOURCE_MAPPING_URL_RE = /[ \t]*\/\*[#@]\s*sourceMappingURL=[^\s*]+\s*\*\/\s*$/;
482
- function withSourceMappingURL(code, url) {
483
- const stripped = code.replace(SOURCE_MAPPING_URL_LINE_RE, "");
484
- if (url == null) return stripped;
485
- const separator = stripped.length > 0 && !stripped.endsWith("\n") ? "\n" : "";
486
- return `${stripped}${separator}//# sourceMappingURL=${url}\n`;
487
- }
488
- function withoutCssSourceMappingURL(css) {
489
- return css.replace(CSS_SOURCE_MAPPING_URL_RE, "");
490
- }
491
- function extractSourceMappingURL(code) {
492
- let last = null;
493
- for (const match of code.matchAll(SOURCE_MAPPING_URL_RE)) last = match[1];
494
- return last;
495
- }
496
- function isRemoteSourceMappingURL(url) {
497
- return /^https?:\/\//i.test(url) || url.startsWith("//");
498
- }
499
- function decodeDataUri(url) {
500
- if (!url.startsWith("data:")) return null;
501
- const comma = url.indexOf(",");
502
- if (comma === -1) return null;
503
- const meta = url.slice(5, comma);
504
- const payload = url.slice(comma + 1);
505
- try {
506
- if (/;base64/i.test(meta)) return Buffer.from(payload, "base64").toString("utf8");
507
- return decodeURIComponent(payload);
508
- } catch {
509
- return null;
510
- }
511
- }
512
- function discoverInputSourceMap(jsPath, code) {
513
- const adjacent = `${jsPath}.map`;
514
- if (existsSync(adjacent)) try {
515
- return readFileSync(adjacent, "utf8");
516
- } catch {}
517
- let source = code;
518
- if (source == null) try {
519
- source = readFileSync(jsPath, "utf8");
520
- } catch {
521
- return null;
522
- }
523
- const url = extractSourceMappingURL(source);
524
- if (url == null) return null;
525
- if (url.startsWith("data:")) return decodeDataUri(url);
526
- if (isRemoteSourceMappingURL(url)) return null;
527
- let mapPath;
528
- try {
529
- mapPath = isAbsolute(url) ? url : resolve(dirname(jsPath), decodeURIComponent(url));
530
- } catch {
531
- return null;
532
- }
533
- if (!existsSync(mapPath)) return null;
534
- try {
535
- return readFileSync(mapPath, "utf8");
536
- } catch {
537
- return null;
538
- }
539
- }
540
-
541
- //#endregion
542
- //#region src/bundle.ts
543
- const BUNDLE_JS_RE = /\.[cm]?js$/;
544
- const CSS_MAP_RE = /\.css\.map$/;
545
- function collectBundleJs(bundle, outDir) {
546
- const files = [];
547
- const inputs = new Map();
548
- const entries = new Map();
549
- for (const [fileName, entry] of Object.entries(bundle)) {
550
- if (!BUNDLE_JS_RE.test(fileName)) continue;
551
- const source = entry.type === "chunk" ? entry.code : typeof entry.source === "string" ? entry.source : void 0;
552
- if (source === void 0) continue;
553
- const filePath = resolve(outDir, fileName);
554
- files.push(filePath);
555
- entries.set(filePath, entry);
556
- inputs.set(filePath, {
557
- source,
558
- sourceMap: entry.map ? entry.map.toString() : null
559
- });
560
- }
561
- return {
562
- files,
563
- inputs,
564
- entries
565
- };
566
- }
567
- function dataUri(json) {
568
- return `data:application/json;charset=utf-8;base64,${Buffer.from(json, "utf8").toString("base64")}`;
569
- }
570
- function applyBundleOutput(bundle, entry, out, policy) {
571
- if (entry.type !== "chunk") {
572
- entry.source = out.code;
573
- return;
574
- }
575
- const mapName = entry.sourcemapFileName ?? null;
576
- const inlineMap = mapName == null && entry.map != null;
577
- const emitMap = policy.sourceMap && out.sourceMap != null;
578
- let url = null;
579
- if (emitMap && out.sourceMap != null) {
580
- if (mapName != null && bundle[mapName]) {
581
- bundle[mapName].source = out.sourceMap;
582
- url = basename(mapName);
583
- } else if (inlineMap) url = dataUri(out.sourceMap);
584
- } else {
585
- if (mapName != null) delete bundle[mapName];
586
- entry.map = null;
587
- }
588
- entry.code = withSourceMappingURL(out.code, policy.emitSourceMappingURL ? url : null);
589
- }
590
- function stripBundleCssSourceMaps(bundle) {
591
- for (const [fileName, entry] of Object.entries(bundle)) {
592
- if (CSS_MAP_RE.test(fileName)) {
593
- delete bundle[fileName];
594
- continue;
595
- }
596
- if (entry.type !== "asset" || !fileName.endsWith(".css") || entry.source === void 0) continue;
597
- const css = typeof entry.source === "string" ? entry.source : Buffer.from(entry.source).toString("utf8");
598
- const stripped = withoutCssSourceMappingURL(css);
599
- if (stripped !== css) entry.source = stripped;
600
- }
601
- }
602
-
603
- //#endregion
604
- //#region src/glob.ts
605
- function normalize(value) {
606
- return value.includes("\\") ? value.replaceAll("\\", "/") : value;
607
- }
608
- function segments(value) {
609
- return value.split("/").filter((part) => part !== "");
610
- }
611
- function isAnchored(pattern) {
612
- if (pattern.startsWith("/")) return true;
613
- return pattern.length >= 2 && pattern[1] === ":" && /^[A-Za-z]$/.test(pattern[0]);
614
- }
615
- function segmentMatches(pattern, seg) {
616
- if (!pattern.includes("*") && !pattern.includes("?")) return pattern === seg;
617
- const p = [...pattern];
618
- const s = [...seg];
619
- let pi = 0;
620
- let si = 0;
621
- let star = -1;
622
- let starSi = 0;
623
- while (si < s.length) if (pi < p.length && p[pi] === "*") {
624
- star = pi;
625
- starSi = si;
626
- pi += 1;
627
- } else if (pi < p.length && (p[pi] === "?" || p[pi] === s[si])) {
628
- pi += 1;
629
- si += 1;
630
- } else if (star >= 0) {
631
- pi = star + 1;
632
- starSi += 1;
633
- si = starSi;
634
- } else return false;
635
- return p.slice(pi).every((c) => c === "*");
636
- }
637
- function segmentsMatch(pattern, path) {
638
- let pi = 0;
639
- let si = 0;
640
- let star = -1;
641
- let starSi = 0;
642
- while (si < path.length) if (pi < pattern.length && pattern[pi] === "**") {
643
- star = pi;
644
- starSi = si;
645
- pi += 1;
646
- } else if (pi < pattern.length && segmentMatches(pattern[pi], path[si])) {
647
- pi += 1;
648
- si += 1;
649
- } else if (star >= 0) {
650
- pi = star + 1;
651
- starSi += 1;
652
- si = starSi;
653
- } else return false;
654
- return pattern.slice(pi).every((s) => s === "**");
655
- }
656
- function matchesPath(pattern, path) {
657
- const pat = normalize(pattern);
658
- const parts = segments(pat);
659
- if (parts.length === 0) return false;
660
- const segs = segments(normalize(path));
661
- if (isAnchored(pat)) return segmentsMatch(parts, segs);
662
- for (let i = 0; i <= segs.length; i++) if (segmentsMatch(parts, segs.slice(i))) return true;
663
- return false;
664
- }
665
- function reachesInto(pattern, dir) {
666
- const pat = normalize(pattern);
667
- const parts = segments(pat);
668
- if (parts.length === 0) return false;
669
- if (!isAnchored(pat)) return true;
670
- for (let k = 1; k <= parts.length; k++) if (matchesPath(`/${parts.slice(0, k).join("/")}`, dir)) return true;
671
- return false;
672
- }
673
-
674
- //#endregion
675
- //#region src/collect.ts
676
- const BACKUP_RE = /\.backup\.[0-9a-f]{8}\.[cm]?js$/;
677
- const NODE_MODULES = "node_modules";
678
- function isCollectableJs(name) {
679
- if (BACKUP_RE.test(name)) return false;
680
- return name.endsWith(".js") || name.endsWith(".mjs") || name.endsWith(".cjs");
681
- }
682
- function statOrNull(path) {
683
- try {
684
- return statSync(path);
685
- } catch {
686
- return null;
687
- }
688
- }
689
- function collectJsFiles(target, options = {}) {
690
- const stat = statOrNull(target);
691
- if (!stat) return [];
692
- if (!stat.isDirectory()) return isCollectableJs(basename(target)) ? [target] : [];
693
- return walkJs(target, options.include ?? [], false, options.onNestedProject);
694
- }
695
- function entriesOf(dir) {
696
- try {
697
- return readdirSync(dir, { withFileTypes: true });
698
- } catch {
699
- return [];
700
- }
701
- }
702
- function kindOf(entry, full) {
703
- if (entry.isDirectory()) return "dir";
704
- if (entry.isFile()) return "file";
705
- const stat = statOrNull(full);
706
- if (!stat) return null;
707
- return stat.isDirectory() ? "dir" : "file";
708
- }
709
- function isNestedProject(dir) {
710
- return existsSync(join(dir, "package.json"));
711
- }
712
- function walkJs(dir, include, readmitted, onNestedProject) {
713
- const out = [];
714
- for (const entry of entriesOf(dir)) {
715
- const name = entry.name;
716
- const full = join(dir, name);
717
- const kind = kindOf(entry, full);
718
- if (kind === null) continue;
719
- if (kind === "dir") {
720
- const skipped = name === NODE_MODULES;
721
- if (!skipped && !readmitted && isNestedProject(full)) {
722
- onNestedProject?.(full);
723
- continue;
724
- }
725
- if (skipped && !include.some((pattern) => reachesInto(pattern, full))) continue;
726
- out.push(...walkJs(full, include, readmitted || skipped, onNestedProject));
727
- } else if (isCollectableJs(name)) {
728
- if (readmitted && !include.some((pattern) => matchesPath(pattern, full))) continue;
729
- out.push(full);
730
- }
731
- }
732
- return out;
733
- }
734
- const SOURCE_MAP_RE = /\.(?:[cm]?js|css)\.map$/;
735
- function collectFiles(dir, accept) {
736
- if (!existsSync(dir)) return [];
737
- const out = [];
738
- for (const entry of entriesOf(dir)) {
739
- const name = entry.name;
740
- const full = join(dir, name);
741
- const kind = kindOf(entry, full);
742
- if (kind === null) continue;
743
- if (kind === "dir") out.push(...collectFiles(full, accept));
744
- else if (accept(name)) out.push(full);
745
- }
746
- return out;
747
- }
748
- function collectSourceMaps(dir) {
749
- return collectFiles(dir, (name) => SOURCE_MAP_RE.test(name));
750
- }
751
- function collectStylesheets(dir) {
752
- return collectFiles(dir, (name) => name.endsWith(".css"));
753
- }
754
-
755
- //#endregion
756
- //#region src/notices.ts
757
- const NOTICE_MESSAGE_LIMIT = 500;
758
- const NOTICE_LIMIT = 5;
759
- const NOTICE_CODE_LIMIT = 64;
760
- const NOTICE_HOSTS = new Set(["afterpack.dev", "www.afterpack.dev"]);
761
- const ESC = 27;
762
- const BEL = 7;
763
- const C1_CSI = 155;
764
- const C1_OSC = 157;
765
- function isControl(code) {
766
- return code < 32 || code >= 127 && code <= 159;
767
- }
768
- function isInvisibleFormat(code) {
769
- return code === 1564 || code >= 8203 && code <= 8207 || code >= 8234 && code <= 8238 || code >= 8288 && code <= 8297 || code === 65279;
770
- }
771
- function skipCsi(text, from) {
772
- let i = from;
773
- while (i < text.length) {
774
- const c = text.charCodeAt(i);
775
- i += 1;
776
- if (c >= 64 && c <= 126) return i;
777
- }
778
- return i;
779
- }
780
- function skipOsc(text, from) {
781
- let i = from;
782
- while (i < text.length) {
783
- const c = text.charCodeAt(i);
784
- if (c === BEL) return i + 1;
785
- if (c === ESC) return text.charCodeAt(i + 1) === 92 ? i + 2 : i + 1;
786
- if (c === 156) return i + 1;
787
- i += 1;
788
- }
789
- return i;
790
- }
791
- function stripTerminalControls(text) {
792
- let out = "";
793
- let i = 0;
794
- while (i < text.length) {
795
- const c = text.charCodeAt(i);
796
- if (c === ESC) {
797
- const next = text.charCodeAt(i + 1);
798
- if (next === 91) i = skipCsi(text, i + 2);
799
- else if (next === 93) i = skipOsc(text, i + 2);
800
- else i += Number.isNaN(next) ? 1 : 2;
801
- continue;
802
- }
803
- if (c === C1_CSI) {
804
- i = skipCsi(text, i + 1);
805
- continue;
806
- }
807
- if (c === C1_OSC) {
808
- i = skipOsc(text, i + 1);
809
- continue;
810
- }
811
- if (isControl(c)) {
812
- out += c === 9 || c === 10 || c === 13 ? " " : "";
813
- i += 1;
814
- continue;
815
- }
816
- if (c === 8232 || c === 8233) {
817
- out += " ";
818
- i += 1;
819
- continue;
820
- }
821
- if (isInvisibleFormat(c)) {
822
- i += 1;
823
- continue;
824
- }
825
- out += text[i];
826
- i += 1;
827
- }
828
- return out;
829
- }
830
- function sanitizeServerText(value, limit = NOTICE_MESSAGE_LIMIT) {
831
- if (typeof value !== "string") return "";
832
- const clean = stripTerminalControls(value).replace(/\s+/g, " ").trim();
833
- if (clean.length <= limit) return clean;
834
- const chars = Array.from(clean);
835
- return chars.length > limit ? chars.slice(0, limit).join("") : clean;
836
- }
837
- function sanitizeNoticeUrl(value) {
838
- if (typeof value !== "string") return null;
839
- let url;
840
- try {
841
- url = new URL(value.trim());
842
- } catch {
843
- return null;
844
- }
845
- if (url.protocol !== "https:") return null;
846
- if (!NOTICE_HOSTS.has(url.hostname) || url.port !== "") return null;
847
- if (url.username !== "" || url.password !== "") return null;
848
- const href = url.href;
849
- return href.length <= NOTICE_MESSAGE_LIMIT ? href : null;
850
- }
851
- function noticeSeverity(value) {
852
- if (value === "info") return "info";
853
- if (value === "error" || value === "critical") return "error";
854
- return "warning";
855
- }
856
- function sanitizeNotices(raw) {
857
- if (!Array.isArray(raw)) return [];
858
- const out = [];
859
- for (const entry of raw) {
860
- if (out.length >= NOTICE_LIMIT) break;
861
- if (typeof entry !== "object" || entry === null) continue;
862
- const n = entry;
863
- const message = sanitizeServerText(n.message);
864
- if (message === "") continue;
865
- out.push({
866
- severity: noticeSeverity(n.severity),
867
- code: sanitizeServerText(n.code, NOTICE_CODE_LIMIT),
868
- message,
869
- url: sanitizeNoticeUrl(n.url)
870
- });
871
- }
872
- return out;
873
- }
874
- function formatNotice(notice) {
875
- const head = notice.severity === "info" ? "AfterPack notice" : `AfterPack ${notice.severity}`;
876
- const tail = notice.url ? ` ${notice.url}` : "";
877
- return `${head}: ${notice.message}${tail}`;
878
- }
879
- function reportNotices(raw, logger, prefix = (m) => m) {
880
- const notices = sanitizeNotices(raw);
881
- for (const notice of notices) {
882
- const line = prefix(formatNotice(notice));
883
- if (notice.severity === "info" || !logger.warn) logger.log(line);
884
- else logger.warn(line);
885
- }
886
- return notices;
887
- }
888
-
889
477
  //#endregion
890
478
  //#region src/registry.ts
891
479
  const PRESET_VALUES = [
@@ -895,6 +483,20 @@ const PRESET_VALUES = [
895
483
  "hard",
896
484
  "extreme"
897
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
+ }
898
500
  const TRANSFORM_KIND_VALUES = [
899
501
  "stringEncoding",
900
502
  "controlFlowFlatten",
@@ -944,6 +546,18 @@ const CONFIG_KEYS = [
944
546
  },
945
547
  default: "light"
946
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
+ },
947
561
  {
948
562
  path: "complexity",
949
563
  shape: "scalar",
@@ -1247,438 +861,855 @@ const CONFIG_KEYS = [
1247
861
  },
1248
862
  default: "detected from the environment"
1249
863
  },
1250
- {
1251
- path: "directives.enabled",
1252
- shape: "scalar",
1253
- scope: "program",
1254
- tier: "free",
1255
- surface: "build",
1256
- item: { kind: "boolean" },
1257
- default: "true"
864
+ {
865
+ path: "directives.enabled",
866
+ shape: "scalar",
867
+ scope: "program",
868
+ tier: "free",
869
+ surface: "build",
870
+ item: { kind: "boolean" },
871
+ default: "true"
872
+ },
873
+ {
874
+ path: "diagnostics.level",
875
+ shape: "scalar",
876
+ scope: "program",
877
+ tier: "free",
878
+ surface: "build",
879
+ item: {
880
+ kind: "enum",
881
+ values: [
882
+ "summary",
883
+ "all",
884
+ "none"
885
+ ]
886
+ },
887
+ default: "summary"
888
+ },
889
+ {
890
+ path: "diagnostics.format",
891
+ shape: "scalar",
892
+ scope: "program",
893
+ tier: "free",
894
+ surface: "cli",
895
+ item: {
896
+ kind: "enum",
897
+ values: ["text", "json"]
898
+ },
899
+ default: "text"
900
+ },
901
+ {
902
+ path: "telemetry.enabled",
903
+ shape: "scalar",
904
+ scope: "program",
905
+ tier: "free",
906
+ surface: "build",
907
+ item: { kind: "boolean" },
908
+ default: "true"
909
+ },
910
+ {
911
+ path: "allowUnobfuscated",
912
+ shape: "scalar",
913
+ scope: "program",
914
+ tier: "free",
915
+ surface: "build",
916
+ item: { kind: "boolean" },
917
+ default: "false"
918
+ },
919
+ {
920
+ path: "key",
921
+ shape: "scalar",
922
+ scope: "program",
923
+ tier: "pro",
924
+ surface: "build",
925
+ item: { kind: "string" },
926
+ default: "unset; builds run locally with basic protection"
927
+ }
928
+ ];
929
+ const EMPTY_CONFIG = {};
930
+ const CONFIG_BY_PATH = new Map(CONFIG_KEYS.map((k) => [k.path, k]));
931
+ const CONFIG_PREFIXES = new Set(CONFIG_KEYS.flatMap((k) => {
932
+ const parts = k.path.split(".");
933
+ return parts.slice(0, -1).map((_, i) => parts.slice(0, i + 1).join("."));
934
+ }));
935
+ const CONFIG_CHILDREN = new Map([...CONFIG_PREFIXES].map((prefix) => [prefix, CONFIG_KEYS.filter((k) => k.path.startsWith(`${prefix}.`)).map((k) => k.path)]));
936
+ const BY_NORMALIZED = new Map(CONFIG_KEYS.map((k) => [normalizeKey(k.path), k]));
937
+ const CHILDREN_BY_NORMALIZED = new Map([...CONFIG_CHILDREN].map(([prefix, children]) => [normalizeKey(prefix), children]));
938
+ const PREFIX_BY_NORMALIZED = new Map([...CONFIG_PREFIXES].map((prefix) => [normalizeKey(prefix), prefix]));
939
+ function normalizeKey(key) {
940
+ return key.replace(/[-_.]/g, "").toLowerCase();
941
+ }
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"
1258
1043
  },
1259
- {
1260
- path: "diagnostics.level",
1261
- shape: "scalar",
1262
- scope: "program",
1263
- tier: "free",
1264
- surface: "build",
1265
- item: {
1266
- kind: "enum",
1267
- values: [
1268
- "summary",
1269
- "all",
1270
- "none"
1271
- ]
1272
- },
1273
- default: "summary"
1044
+ complexity: {
1045
+ is: isNonNegative,
1046
+ want: "a number >= 0"
1274
1047
  },
1275
- {
1276
- path: "diagnostics.format",
1277
- shape: "scalar",
1278
- scope: "program",
1279
- tier: "free",
1280
- surface: "cli",
1281
- item: {
1282
- kind: "enum",
1283
- values: ["text", "json"]
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
1284
1060
  },
1285
- default: "text"
1286
- },
1287
- {
1288
- path: "telemetry.enabled",
1289
- shape: "scalar",
1290
- scope: "program",
1291
- tier: "free",
1292
- surface: "build",
1293
- item: { kind: "boolean" },
1294
- default: "true"
1295
- },
1296
- {
1297
- path: "allowUnobfuscated",
1298
- shape: "scalar",
1299
- scope: "program",
1300
- tier: "free",
1301
- surface: "build",
1302
- item: { kind: "boolean" },
1303
- default: "false"
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"
1304
1076
  },
1305
- {
1306
- path: "key",
1307
- shape: "scalar",
1308
- scope: "program",
1309
- tier: "pro",
1310
- surface: "build",
1311
- item: { kind: "string" },
1312
- default: "unset; builds run locally with basic protection"
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
+ });
1313
1211
  }
1314
- ];
1315
- const EMPTY_CONFIG = {};
1316
- const CONFIG_BY_PATH = new Map(CONFIG_KEYS.map((k) => [k.path, k]));
1317
- const CONFIG_PREFIXES = new Set(CONFIG_KEYS.flatMap((k) => {
1318
- const parts = k.path.split(".");
1319
- return parts.slice(0, -1).map((_, i) => parts.slice(0, i + 1).join("."));
1320
- }));
1321
- const CONFIG_CHILDREN = new Map([...CONFIG_PREFIXES].map((prefix) => [prefix, CONFIG_KEYS.filter((k) => k.path.startsWith(`${prefix}.`)).map((k) => k.path)]));
1322
- const BY_NORMALIZED = new Map(CONFIG_KEYS.map((k) => [normalizeKey(k.path), k]));
1323
- const CHILDREN_BY_NORMALIZED = new Map([...CONFIG_CHILDREN].map(([prefix, children]) => [normalizeKey(prefix), children]));
1324
- const PREFIX_BY_NORMALIZED = new Map([...CONFIG_PREFIXES].map((prefix) => [normalizeKey(prefix), prefix]));
1325
- function normalizeKey(key) {
1326
- return key.replace(/[-_.]/g, "").toLowerCase();
1327
- }
1328
- function groupBooleanKey(path) {
1329
- if (!CONFIG_PREFIXES.has(path)) return void 0;
1330
- return CONFIG_BY_PATH.get(`${path}.enabled`);
1331
1212
  }
1332
- function nearestName(name, candidates) {
1333
- const target = normalizeKey(name);
1334
- let best;
1335
- for (const candidate of candidates) {
1336
- const distance = editDistance(target, normalizeKey(candidate));
1337
- if (distance > Math.max(2, Math.floor(target.length / 4))) continue;
1338
- if (!best || distance < best.distance) best = {
1339
- name: candidate,
1340
- distance
1341
- };
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;
1342
1219
  }
1343
- return best?.name;
1344
- }
1345
- function suggestKey(key) {
1346
- const exact = BY_NORMALIZED.get(normalizeKey(key));
1347
- if (exact) return exact.path;
1348
- const near = nearestName(key, CONFIG_KEYS.map((k) => k.path));
1349
- if (near) return near;
1350
- const tail = normalizeKey(key);
1351
- const owners = CONFIG_KEYS.filter((k) => normalizeKey(k.path.slice(k.path.lastIndexOf(".") + 1)) === tail);
1352
- return owners.length === 1 ? owners[0].path : void 0;
1220
+ return out;
1353
1221
  }
1354
- function canonicalSpelling(name) {
1355
- const norm$1 = normalizeKey(name);
1356
- const key = BY_NORMALIZED.get(norm$1);
1357
- if (key) return { key: key.path };
1358
- const group$1 = CHILDREN_BY_NORMALIZED.get(norm$1);
1359
- return group$1 && group$1.length > 0 ? { group: group$1 } : void 0;
1222
+ function mergeInto(base, override) {
1223
+ return deepMerge(base, override);
1360
1224
  }
1361
- function editDistance(a, b) {
1362
- const prev = new Array(b.length + 1);
1363
- const next = new Array(b.length + 1);
1364
- for (let j = 0; j <= b.length; j++) prev[j] = j;
1365
- for (let i = 1; i <= a.length; i++) {
1366
- next[0] = i;
1367
- 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));
1368
- for (let j = 0; j <= b.length; j++) prev[j] = next[j];
1369
- }
1370
- return prev[b.length];
1225
+ function mergeConfig(base, override) {
1226
+ return deepMerge(base, override);
1371
1227
  }
1372
- const DOCS_URL = "https://www.afterpack.dev/docs/config";
1373
- function unknownKeyMessage(path, surface) {
1374
- const group$1 = CHILDREN_BY_NORMALIZED.get(normalizeKey(path));
1375
- if (group$1 && group$1.length > 0) {
1376
- const list = group$1.map((child) => `\`${child}\``).join(", ");
1377
- const tail$1 = group$1.length === 1 ? `did you mean ${list}?` : `its keys are ${list}`;
1378
- const canonical = PREFIX_BY_NORMALIZED.get(normalizeKey(path));
1379
- const enabled = canonical ? groupBooleanKey(canonical) : void 0;
1380
- const rule = enabled ? `; a boolean here means \`${enabled.path}\`` : "";
1381
- return `\`${path}\` is a group of configuration keys, not a key itself (${surface}) — ${tail$1}${rule}`;
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];
1382
1233
  }
1383
- const suggestion = suggestKey(path);
1384
- const tail = suggestion ? ` — did you mean \`${suggestion}\`?` : ` — see ${DOCS_URL}`;
1385
- return `unknown configuration key \`${path}\` (${surface})${tail}`;
1234
+ return current;
1386
1235
  }
1387
- function isPlainObject(value) {
1388
- return typeof value === "object" && value !== null && !Array.isArray(value);
1236
+ function nest(path, value) {
1237
+ return path.split(".").reduceRight((inner, segment) => ({ [segment]: inner }), value);
1389
1238
  }
1390
- function describe(item) {
1391
- switch (item.kind) {
1392
- case "boolean": return "true or false";
1393
- case "number": return item.integer ? `an integer >= ${item.min}` : `a number >= ${item.min}`;
1394
- case "unbounded": return `a number >= ${item.min}, or the string "${item.unlimited}"`;
1395
- case "string": return "a string";
1396
- case "enum": return `one of: ${item.values.join(", ")}`;
1397
- case "seed": return "a number, any string, or \"git\"";
1398
- case "reserved": return "a name, or { \"glob\": \"…\", \"names\": [\"…\"] }";
1399
- case "region": return "an object with numeric `start` and `end`";
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];
1400
1245
  }
1246
+ node[parts[parts.length - 1]] = value;
1401
1247
  }
1402
- function misdirectedHint(key, value, spell) {
1403
- const other = misdirectedTo(key, value);
1404
- if (!other) return "";
1405
- const written = spell(other.path, String(value));
1406
- return ` — \`${String(value)}\` is a \`${other.path}\` value; write \`${written}\` instead`;
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;
1407
1257
  }
1408
- const isFiniteNumber = (v) => typeof v === "number" && Number.isFinite(v);
1409
- const isTransformKinds = (v) => Array.isArray(v) && v.every((k) => TRANSFORM_KIND_VALUES.includes(k));
1410
- const KINDS = `a list of: ${TRANSFORM_KIND_VALUES.join(", ")}`;
1411
- const isNonNegative = (v) => isFiniteNumber(v) && v >= 0;
1412
- function group(fields) {
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;
1413
1261
  return {
1414
- is: isPlainObject,
1415
- want: "an object",
1416
- fields
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")
1417
1290
  };
1418
1291
  }
1419
- const REGION_FIELDS = {
1420
- start: {
1421
- required: true,
1422
- is: isFiniteNumber,
1423
- want: "a number"
1424
- },
1425
- end: {
1426
- required: true,
1427
- is: isFiniteNumber,
1428
- want: "a number"
1429
- },
1430
- complexity: {
1431
- is: isNonNegative,
1432
- want: "a number >= 0"
1433
- },
1434
- inflation: group({ max: {
1435
- is: isNonNegative,
1436
- want: "a number >= 0"
1437
- } }),
1438
- strings: group({ encode: {
1439
- is: (v) => typeof v === "boolean",
1440
- want: "true or false"
1441
- } }),
1442
- transforms: group({
1443
- only: {
1444
- is: isTransformKinds,
1445
- want: KINDS
1446
- },
1447
- deny: {
1448
- is: isTransformKinds,
1449
- want: KINDS
1450
- }
1451
- }),
1452
- label: {
1453
- is: (v) => typeof v === "string",
1454
- want: "a string"
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;
1326
+ }
1327
+ }
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;
1455
1354
  }
1456
- };
1457
- const RESERVED_FIELDS = {
1458
- glob: {
1459
- required: true,
1460
- is: (v) => typeof v === "string",
1461
- want: "a string"
1462
- },
1463
- names: {
1464
- required: true,
1465
- is: (v) => Array.isArray(v) && v.every((n) => typeof n === "string"),
1466
- want: "a list of names"
1355
+ }
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
+ });
1467
1376
  }
1468
- };
1469
- function leafNames(spec, prefix) {
1470
- return Object.entries(spec).flatMap(([name, field]) => field.fields ? leafNames(field.fields, `${prefix}${name}.`) : [prefix + name]);
1377
+ return {
1378
+ files,
1379
+ inputs,
1380
+ entries
1381
+ };
1471
1382
  }
1472
- function checkFields(spec, value, prefix = "") {
1473
- for (const name of Object.keys(value)) {
1474
- if (name in spec) continue;
1475
- const near = nearestName(prefix + name, Object.keys(spec).map((n) => prefix + n));
1476
- return `item has an unknown field \`${prefix}${name}\`` + (near ? ` — did you mean \`${near}\`?` : "") + ` (allowed: ${leafNames(spec, prefix).join(", ")})`;
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;
1477
1394
  }
1478
- for (const [name, field] of Object.entries(spec)) {
1479
- const present = value[name];
1480
- if (present === void 0) {
1481
- if (field.required) return `item is missing \`${prefix}${name}\` (${field.want})`;
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;
1407
+ }
1408
+ entry.code = withSourceMappingURL(out.code, policy.emitSourceMappingURL ? url : null);
1409
+ }
1410
+ function stripBundleCssSourceMaps(bundle) {
1411
+ for (const [fileName, entry] of Object.entries(bundle)) {
1412
+ if (CSS_MAP_RE.test(fileName)) {
1413
+ delete bundle[fileName];
1482
1414
  continue;
1483
1415
  }
1484
- if (!field.is(present)) return `item's \`${prefix}${name}\` must be ${field.want}, got ${JSON.stringify(present)}`;
1485
- if (field.fields) {
1486
- const nested = checkFields(field.fields, present, `${prefix}${name}.`);
1487
- if (nested) return nested;
1488
- }
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;
1489
1420
  }
1490
- return void 0;
1491
1421
  }
1492
- function expected(item, value) {
1493
- 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;
1494
1427
  }
1495
- function checkItem(item, value) {
1496
- switch (item.kind) {
1497
- case "boolean": return typeof value === "boolean" ? void 0 : expected(item, value);
1498
- case "number": {
1499
- if (typeof value !== "number" || !Number.isFinite(value)) return expected(item, value);
1500
- if (value < item.min) return expected(item, value);
1501
- if (item.integer && !Number.isInteger(value)) return expected(item, value);
1502
- return void 0;
1503
- }
1504
- case "unbounded": {
1505
- if (value === item.unlimited) return void 0;
1506
- if (typeof value === "number" && Number.isFinite(value) && value >= item.min) return void 0;
1507
- return `${expected(item, value)} — there is no \`Infinity\` in JSON; write "${item.unlimited}"`;
1508
- }
1509
- case "string": return typeof value === "string" ? void 0 : expected(item, value);
1510
- case "enum": return typeof value === "string" && item.values.includes(value) ? void 0 : expected(item, value);
1511
- case "seed": return typeof value === "number" || typeof value === "string" ? void 0 : expected(item, value);
1512
- case "reserved": {
1513
- if (typeof value === "string") return void 0;
1514
- if (!isPlainObject(value)) return expected(item, value);
1515
- return checkFields(RESERVED_FIELDS, value);
1516
- }
1517
- case "region": {
1518
- if (!isPlainObject(value)) return expected(item, value);
1519
- return checkFields(REGION_FIELDS, value);
1520
- }
1521
- }
1428
+ function segments(value) {
1429
+ return value.split("/").filter((part) => part !== "");
1522
1430
  }
1523
- function checkValue(key, value) {
1524
- if (key.shape === "scalar") {
1525
- const failure = checkItem(key.item, value);
1526
- return failure ? `\`${key.path}\`: ${failure}` : void 0;
1527
- }
1528
- if (!Array.isArray(value)) return `\`${key.path}\`: expected a list of values, got ${JSON.stringify(value)}`;
1529
- for (const entry of value) {
1530
- const failure = checkItem(key.item, entry);
1531
- 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;
1532
1507
  }
1533
- return void 0;
1534
1508
  }
1535
- function misdirectedTo(key, value) {
1536
- if (key.namedValuesOf === void 0 || typeof value !== "string") return void 0;
1537
- const other = CONFIG_BY_PATH.get(key.namedValuesOf);
1538
- if (!other || other.shape !== "scalar") return void 0;
1539
- 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);
1540
1514
  }
1541
- function validateConfig(input, surface) {
1542
- const issues = [];
1543
- const config = {};
1544
- if (input === void 0 || input === null) return {
1545
- config,
1546
- issues
1547
- };
1548
- if (!isPlainObject(input)) {
1549
- issues.push({
1550
- path: "",
1551
- message: `configuration (${surface}) must be an object`
1552
- });
1553
- return {
1554
- config,
1555
- issues
1556
- };
1515
+ function entriesOf(dir) {
1516
+ try {
1517
+ return readdirSync(dir, { withFileTypes: true });
1518
+ } catch {
1519
+ return [];
1557
1520
  }
1558
- walk(input, "", config, issues, surface);
1559
- return {
1560
- config,
1561
- issues
1562
- };
1563
1521
  }
1564
- function walk(source, prefix, target, issues, surface) {
1565
- for (const [name, value] of Object.entries(source)) {
1566
- if (value === void 0) continue;
1567
- const path = prefix ? `${prefix}.${name}` : name;
1568
- const key = CONFIG_BY_PATH.get(path);
1569
- if (key) {
1570
- const failure = checkValue(key, value);
1571
- if (failure) {
1572
- const hint = misdirectedHint(key, value, (p, v) => `"${p}": ${JSON.stringify(v)}`);
1573
- issues.push({
1574
- path,
1575
- message: `${failure} (${surface})${hint}`
1576
- });
1577
- } else target[name] = value;
1578
- continue;
1579
- }
1580
- if (CONFIG_PREFIXES.has(path)) {
1581
- if (isPlainObject(value)) {
1582
- const nested = {};
1583
- walk(value, path, nested, issues, surface);
1584
- if (Object.keys(nested).length > 0) target[name] = nested;
1585
- continue;
1586
- }
1587
- const enabled = groupBooleanKey(path);
1588
- if (enabled && typeof value === "boolean") {
1589
- 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);
1590
1543
  continue;
1591
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);
1592
1550
  }
1593
- issues.push({
1594
- path,
1595
- message: unknownKeyMessage(path, surface)
1596
- });
1597
1551
  }
1552
+ return out;
1598
1553
  }
1599
- function deepMerge(base, override) {
1600
- const out = { ...base };
1601
- for (const [name, value] of Object.entries(override)) {
1602
- if (value === void 0) continue;
1603
- const existing = out[name];
1604
- 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);
1605
1565
  }
1606
1566
  return out;
1607
1567
  }
1608
- function mergeInto(base, override) {
1609
- return deepMerge(base, override);
1568
+ function collectSourceMaps(dir) {
1569
+ return collectFiles(dir, (name) => SOURCE_MAP_RE.test(name));
1610
1570
  }
1611
- function mergeConfig(base, override) {
1612
- return deepMerge(base, override);
1571
+ function collectStylesheets(dir) {
1572
+ return collectFiles(dir, (name) => name.endsWith(".css"));
1613
1573
  }
1614
- function getPath(config, path) {
1615
- let current = config;
1616
- for (const part of path.split(".")) {
1617
- if (!isPlainObject(current)) return void 0;
1618
- 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;
1619
1597
  }
1620
- return current;
1598
+ return i;
1621
1599
  }
1622
- function nest(path, value) {
1623
- 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;
1624
1610
  }
1625
- function setPath(target, path, value) {
1626
- const parts = path.split(".");
1627
- let node = target;
1628
- for (const part of parts.slice(0, -1)) {
1629
- if (!isPlainObject(node[part])) node[part] = {};
1630
- 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;
1631
1647
  }
1632
- node[parts[parts.length - 1]] = value;
1648
+ return out;
1633
1649
  }
1634
- function toEngineConfig(config) {
1635
- const out = {};
1636
- for (const key of CONFIG_KEYS) {
1637
- if (key.surface !== "engine") continue;
1638
- const value = getPath(config, key.path);
1639
- if (value === void 0) continue;
1640
- 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
+ });
1641
1691
  }
1642
1692
  return out;
1643
1693
  }
1644
- function toPluginOptions(config) {
1645
- const read = (path) => getPath(config, path);
1646
- const set = (container) => Object.values(container).some((v) => v !== void 0) ? container : void 0;
1647
- return {
1648
- artifactOptions: {
1649
- protectionMap: set({ enabled: read("protectionMap.enabled") }),
1650
- sourceMap: set({
1651
- enabled: read("sourceMap.enabled"),
1652
- emitUrl: read("sourceMap.emitUrl")
1653
- }),
1654
- build: set({
1655
- backup: read("build.backup"),
1656
- mode: read("build.mode")
1657
- }),
1658
- allowUnobfuscated: read("allowUnobfuscated"),
1659
- telemetry: set({ enabled: read("telemetry.enabled") })
1660
- },
1661
- seed: read("seed"),
1662
- preset: read("preset"),
1663
- complexity: read("complexity"),
1664
- regions: read("regions"),
1665
- directives: {
1666
- enabled: read("directives.enabled") ?? DIRECTIVES_ENABLED_DEFAULT,
1667
- explicit: read("directives.enabled") !== void 0
1668
- },
1669
- build: set({ autorun: read("build.autorun") }),
1670
- diagnostics: set({
1671
- level: read("diagnostics.level"),
1672
- format: read("diagnostics.format")
1673
- }),
1674
- paths: set({ include: read("paths.include") }),
1675
- key: read("key")
1676
- };
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;
1677
1707
  }
1678
1708
 
1679
1709
  //#endregion
1680
1710
  //#region src/compat.ts
1681
1711
  const MIN_CORE_VERSION = "0.2.0";
1712
+ const SOURCE_TYPE_MIN_CORE_VERSION = "0.2.3";
1682
1713
  const CORE_PACKAGE = "@afterpack/core";
1683
1714
  const VERSION_PATTERN$1 = /^\d{1,9}\.\d{1,9}\.\d{1,9}(?:[-+][0-9A-Za-z.+-]{1,64})?$/;
1684
1715
  const PACKAGE_NAME_PATTERN = /^(?:@[a-z0-9][a-z0-9._-]{0,63}\/)?[a-z0-9][a-z0-9._-]{0,63}$/;
@@ -1750,6 +1781,9 @@ function isBelowVersion(version, minimum) {
1750
1781
  for (let i = 0; i < 3; i++) if (have[i] !== need[i]) return have[i] < need[i];
1751
1782
  return false;
1752
1783
  }
1784
+ function coreSupportsSourceType(coreVersion) {
1785
+ return releaseTriple(coreVersion) !== null && !isBelowVersion(coreVersion, SOURCE_TYPE_MIN_CORE_VERSION);
1786
+ }
1753
1787
  const CLI_PACKAGE = "afterpack";
1754
1788
  function updateCommand(identity, minVersion) {
1755
1789
  const core = `${CORE_PACKAGE}@${safeVersionString(minVersion) ?? "latest"}`;
@@ -2426,6 +2460,7 @@ function buildEngineConfig(options) {
2426
2460
  if (options.complexity !== void 0) defaults.complexity = options.complexity;
2427
2461
  if (options.preset !== void 0) defaults.preset = options.preset;
2428
2462
  else if (options.complexity === void 0) defaults.preset = DEFAULT_PRESET;
2463
+ if (options.sourceType !== void 0) defaults.sourceType = options.sourceType;
2429
2464
  const config = mergeInto({
2430
2465
  ...defaults,
2431
2466
  sourceMap,
@@ -3967,11 +4002,14 @@ async function runObfuscationPass(options) {
3967
4002
  env,
3968
4003
  cwd
3969
4004
  });
4005
+ const localEngineVersion = await readEngineVersion(engine);
4006
+ const derivedSourceType = options.sourceType !== void 0 && coreSupportsSourceType(localEngineVersion ?? options.client?.coreVersion) ? options.sourceType : void 0;
3970
4007
  const engineConfig = buildEngineConfig({
3971
4008
  policy,
3972
4009
  seed,
3973
4010
  preset: options.preset,
3974
4011
  complexity: options.complexity,
4012
+ sourceType: derivedSourceType,
3975
4013
  regions: capture.regions,
3976
4014
  engine: options.engineConfig,
3977
4015
  renameGlobals: capture.renameGlobals
@@ -4009,7 +4047,7 @@ async function runObfuscationPass(options) {
4009
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."));
4010
4048
  const telemetry = options.telemetry;
4011
4049
  const telemetryEnabled = telemetry != null && resolveTelemetryEnabled(artifactOptions.telemetry?.enabled, env);
4012
- const engineVersion = (batch.source === "cloud" ? safeVersionString(batch.engineVersion) : null) ?? await readEngineVersion(engine);
4050
+ const engineVersion = (batch.source === "cloud" ? safeVersionString(batch.engineVersion) : null) ?? localEngineVersion;
4013
4051
  if (telemetry && telemetryEnabled) {
4014
4052
  const facts = {
4015
4053
  label,
@@ -4328,4 +4366,4 @@ function resolvePluginConfig(input) {
4328
4366
  }
4329
4367
 
4330
4368
  //#endregion
4331
- 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, stripBundleCssSourceMaps, toEngineConfig, toPluginOptions, validateConfig, verifyProtectionReceipt, withSourceMappingURL, withoutCssSourceMappingURL, 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 };