@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.cjs CHANGED
@@ -763,397 +763,6 @@ function warnIfPublicPath(artifactPath, logger = DEFAULT_LOGGER) {
763
763
  return true;
764
764
  }
765
765
 
766
- //#endregion
767
- //#region src/source-map.ts
768
- const SOURCE_MAPPING_URL_RE = /\/\/[#@]\s*sourceMappingURL=(\S+)\s*$/gm;
769
- const SOURCE_MAPPING_URL_LINE_RE = /^[ \t]*\/\/[#@]\s*sourceMappingURL=\S+[ \t]*\r?\n?/gm;
770
- function withSourceMappingURL(code, url) {
771
- const stripped = code.replace(SOURCE_MAPPING_URL_LINE_RE, "");
772
- if (url == null) return stripped;
773
- const separator = stripped.length > 0 && !stripped.endsWith("\n") ? "\n" : "";
774
- return `${stripped}${separator}//# sourceMappingURL=${url}\n`;
775
- }
776
- function extractSourceMappingURL(code) {
777
- let last = null;
778
- for (const match of code.matchAll(SOURCE_MAPPING_URL_RE)) last = match[1];
779
- return last;
780
- }
781
- function isRemoteSourceMappingURL(url) {
782
- return /^https?:\/\//i.test(url) || url.startsWith("//");
783
- }
784
- function decodeDataUri(url) {
785
- if (!url.startsWith("data:")) return null;
786
- const comma = url.indexOf(",");
787
- if (comma === -1) return null;
788
- const meta = url.slice(5, comma);
789
- const payload = url.slice(comma + 1);
790
- try {
791
- if (/;base64/i.test(meta)) return Buffer.from(payload, "base64").toString("utf8");
792
- return decodeURIComponent(payload);
793
- } catch {
794
- return null;
795
- }
796
- }
797
- function discoverInputSourceMap(jsPath, code) {
798
- const adjacent = `${jsPath}.map`;
799
- if ((0, node_fs.existsSync)(adjacent)) try {
800
- return (0, node_fs.readFileSync)(adjacent, "utf8");
801
- } catch {}
802
- let source = code;
803
- if (source == null) try {
804
- source = (0, node_fs.readFileSync)(jsPath, "utf8");
805
- } catch {
806
- return null;
807
- }
808
- const url = extractSourceMappingURL(source);
809
- if (url == null) return null;
810
- if (url.startsWith("data:")) return decodeDataUri(url);
811
- if (isRemoteSourceMappingURL(url)) return null;
812
- let mapPath;
813
- try {
814
- mapPath = (0, node_path.isAbsolute)(url) ? url : (0, node_path.resolve)((0, node_path.dirname)(jsPath), decodeURIComponent(url));
815
- } catch {
816
- return null;
817
- }
818
- if (!(0, node_fs.existsSync)(mapPath)) return null;
819
- try {
820
- return (0, node_fs.readFileSync)(mapPath, "utf8");
821
- } catch {
822
- return null;
823
- }
824
- }
825
-
826
- //#endregion
827
- //#region src/bundle.ts
828
- const BUNDLE_JS_RE = /\.[cm]?js$/;
829
- function collectBundleJs(bundle, outDir) {
830
- const files = [];
831
- const inputs = new Map();
832
- const entries = new Map();
833
- for (const [fileName, entry] of Object.entries(bundle)) {
834
- if (!BUNDLE_JS_RE.test(fileName)) continue;
835
- const source = entry.type === "chunk" ? entry.code : typeof entry.source === "string" ? entry.source : void 0;
836
- if (source === void 0) continue;
837
- const filePath = (0, node_path.resolve)(outDir, fileName);
838
- files.push(filePath);
839
- entries.set(filePath, entry);
840
- inputs.set(filePath, {
841
- source,
842
- sourceMap: entry.map ? entry.map.toString() : null
843
- });
844
- }
845
- return {
846
- files,
847
- inputs,
848
- entries
849
- };
850
- }
851
- function dataUri(json) {
852
- return `data:application/json;charset=utf-8;base64,${Buffer.from(json, "utf8").toString("base64")}`;
853
- }
854
- function applyBundleOutput(bundle, entry, out, policy) {
855
- if (entry.type !== "chunk") {
856
- entry.source = out.code;
857
- return;
858
- }
859
- const mapName = entry.sourcemapFileName ?? null;
860
- const inlineMap = mapName == null && entry.map != null;
861
- const emitMap = policy.sourceMap && out.sourceMap != null;
862
- let url = null;
863
- if (emitMap && out.sourceMap != null) {
864
- if (mapName != null && bundle[mapName]) {
865
- bundle[mapName].source = out.sourceMap;
866
- url = (0, node_path.basename)(mapName);
867
- } else if (inlineMap) url = dataUri(out.sourceMap);
868
- } else {
869
- if (mapName != null) delete bundle[mapName];
870
- entry.map = null;
871
- }
872
- entry.code = withSourceMappingURL(out.code, policy.emitSourceMappingURL ? url : null);
873
- }
874
-
875
- //#endregion
876
- //#region src/glob.ts
877
- function normalize(value) {
878
- return value.includes("\\") ? value.replaceAll("\\", "/") : value;
879
- }
880
- function segments(value) {
881
- return value.split("/").filter((part) => part !== "");
882
- }
883
- function isAnchored(pattern) {
884
- if (pattern.startsWith("/")) return true;
885
- return pattern.length >= 2 && pattern[1] === ":" && /^[A-Za-z]$/.test(pattern[0]);
886
- }
887
- function segmentMatches(pattern, seg) {
888
- if (!pattern.includes("*") && !pattern.includes("?")) return pattern === seg;
889
- const p = [...pattern];
890
- const s = [...seg];
891
- let pi = 0;
892
- let si = 0;
893
- let star = -1;
894
- let starSi = 0;
895
- while (si < s.length) if (pi < p.length && p[pi] === "*") {
896
- star = pi;
897
- starSi = si;
898
- pi += 1;
899
- } else if (pi < p.length && (p[pi] === "?" || p[pi] === s[si])) {
900
- pi += 1;
901
- si += 1;
902
- } else if (star >= 0) {
903
- pi = star + 1;
904
- starSi += 1;
905
- si = starSi;
906
- } else return false;
907
- return p.slice(pi).every((c) => c === "*");
908
- }
909
- function segmentsMatch(pattern, path) {
910
- let pi = 0;
911
- let si = 0;
912
- let star = -1;
913
- let starSi = 0;
914
- while (si < path.length) if (pi < pattern.length && pattern[pi] === "**") {
915
- star = pi;
916
- starSi = si;
917
- pi += 1;
918
- } else if (pi < pattern.length && segmentMatches(pattern[pi], path[si])) {
919
- pi += 1;
920
- si += 1;
921
- } else if (star >= 0) {
922
- pi = star + 1;
923
- starSi += 1;
924
- si = starSi;
925
- } else return false;
926
- return pattern.slice(pi).every((s) => s === "**");
927
- }
928
- function matchesPath(pattern, path) {
929
- const pat = normalize(pattern);
930
- const parts = segments(pat);
931
- if (parts.length === 0) return false;
932
- const segs = segments(normalize(path));
933
- if (isAnchored(pat)) return segmentsMatch(parts, segs);
934
- for (let i = 0; i <= segs.length; i++) if (segmentsMatch(parts, segs.slice(i))) return true;
935
- return false;
936
- }
937
- function reachesInto(pattern, dir) {
938
- const pat = normalize(pattern);
939
- const parts = segments(pat);
940
- if (parts.length === 0) return false;
941
- if (!isAnchored(pat)) return true;
942
- for (let k = 1; k <= parts.length; k++) if (matchesPath(`/${parts.slice(0, k).join("/")}`, dir)) return true;
943
- return false;
944
- }
945
-
946
- //#endregion
947
- //#region src/collect.ts
948
- const BACKUP_RE = /\.backup\.[0-9a-f]{8}\.[cm]?js$/;
949
- const NODE_MODULES = "node_modules";
950
- function isCollectableJs(name) {
951
- if (BACKUP_RE.test(name)) return false;
952
- return name.endsWith(".js") || name.endsWith(".mjs") || name.endsWith(".cjs");
953
- }
954
- function statOrNull(path) {
955
- try {
956
- return (0, node_fs.statSync)(path);
957
- } catch {
958
- return null;
959
- }
960
- }
961
- function collectJsFiles(target, options = {}) {
962
- const stat = statOrNull(target);
963
- if (!stat) return [];
964
- if (!stat.isDirectory()) return isCollectableJs((0, node_path.basename)(target)) ? [target] : [];
965
- return walkJs(target, options.include ?? [], false, options.onNestedProject);
966
- }
967
- function entriesOf(dir) {
968
- try {
969
- return (0, node_fs.readdirSync)(dir, { withFileTypes: true });
970
- } catch {
971
- return [];
972
- }
973
- }
974
- function kindOf(entry, full) {
975
- if (entry.isDirectory()) return "dir";
976
- if (entry.isFile()) return "file";
977
- const stat = statOrNull(full);
978
- if (!stat) return null;
979
- return stat.isDirectory() ? "dir" : "file";
980
- }
981
- function isNestedProject(dir) {
982
- return (0, node_fs.existsSync)((0, node_path.join)(dir, "package.json"));
983
- }
984
- function walkJs(dir, include, readmitted, onNestedProject) {
985
- const out = [];
986
- for (const entry of entriesOf(dir)) {
987
- const name = entry.name;
988
- const full = (0, node_path.join)(dir, name);
989
- const kind = kindOf(entry, full);
990
- if (kind === null) continue;
991
- if (kind === "dir") {
992
- const skipped = name === NODE_MODULES;
993
- if (!skipped && !readmitted && isNestedProject(full)) {
994
- onNestedProject?.(full);
995
- continue;
996
- }
997
- if (skipped && !include.some((pattern) => reachesInto(pattern, full))) continue;
998
- out.push(...walkJs(full, include, readmitted || skipped, onNestedProject));
999
- } else if (isCollectableJs(name)) {
1000
- if (readmitted && !include.some((pattern) => matchesPath(pattern, full))) continue;
1001
- out.push(full);
1002
- }
1003
- }
1004
- return out;
1005
- }
1006
- function isSourceMap(name) {
1007
- return name.endsWith(".js.map") || name.endsWith(".mjs.map") || name.endsWith(".cjs.map");
1008
- }
1009
- function collectSourceMaps(dir) {
1010
- if (!(0, node_fs.existsSync)(dir)) return [];
1011
- const out = [];
1012
- for (const entry of entriesOf(dir)) {
1013
- const name = entry.name;
1014
- const full = (0, node_path.join)(dir, name);
1015
- const kind = kindOf(entry, full);
1016
- if (kind === null) continue;
1017
- if (kind === "dir") out.push(...collectSourceMaps(full));
1018
- else if (isSourceMap(name)) out.push(full);
1019
- }
1020
- return out;
1021
- }
1022
-
1023
- //#endregion
1024
- //#region src/notices.ts
1025
- const NOTICE_MESSAGE_LIMIT = 500;
1026
- const NOTICE_LIMIT = 5;
1027
- const NOTICE_CODE_LIMIT = 64;
1028
- const NOTICE_HOSTS = new Set(["afterpack.dev", "www.afterpack.dev"]);
1029
- const ESC = 27;
1030
- const BEL = 7;
1031
- const C1_CSI = 155;
1032
- const C1_OSC = 157;
1033
- function isControl(code) {
1034
- return code < 32 || code >= 127 && code <= 159;
1035
- }
1036
- function isInvisibleFormat(code) {
1037
- return code === 1564 || code >= 8203 && code <= 8207 || code >= 8234 && code <= 8238 || code >= 8288 && code <= 8297 || code === 65279;
1038
- }
1039
- function skipCsi(text, from) {
1040
- let i = from;
1041
- while (i < text.length) {
1042
- const c = text.charCodeAt(i);
1043
- i += 1;
1044
- if (c >= 64 && c <= 126) return i;
1045
- }
1046
- return i;
1047
- }
1048
- function skipOsc(text, from) {
1049
- let i = from;
1050
- while (i < text.length) {
1051
- const c = text.charCodeAt(i);
1052
- if (c === BEL) return i + 1;
1053
- if (c === ESC) return text.charCodeAt(i + 1) === 92 ? i + 2 : i + 1;
1054
- if (c === 156) return i + 1;
1055
- i += 1;
1056
- }
1057
- return i;
1058
- }
1059
- function stripTerminalControls(text) {
1060
- let out = "";
1061
- let i = 0;
1062
- while (i < text.length) {
1063
- const c = text.charCodeAt(i);
1064
- if (c === ESC) {
1065
- const next = text.charCodeAt(i + 1);
1066
- if (next === 91) i = skipCsi(text, i + 2);
1067
- else if (next === 93) i = skipOsc(text, i + 2);
1068
- else i += Number.isNaN(next) ? 1 : 2;
1069
- continue;
1070
- }
1071
- if (c === C1_CSI) {
1072
- i = skipCsi(text, i + 1);
1073
- continue;
1074
- }
1075
- if (c === C1_OSC) {
1076
- i = skipOsc(text, i + 1);
1077
- continue;
1078
- }
1079
- if (isControl(c)) {
1080
- out += c === 9 || c === 10 || c === 13 ? " " : "";
1081
- i += 1;
1082
- continue;
1083
- }
1084
- if (c === 8232 || c === 8233) {
1085
- out += " ";
1086
- i += 1;
1087
- continue;
1088
- }
1089
- if (isInvisibleFormat(c)) {
1090
- i += 1;
1091
- continue;
1092
- }
1093
- out += text[i];
1094
- i += 1;
1095
- }
1096
- return out;
1097
- }
1098
- function sanitizeServerText(value, limit = NOTICE_MESSAGE_LIMIT) {
1099
- if (typeof value !== "string") return "";
1100
- const clean = stripTerminalControls(value).replace(/\s+/g, " ").trim();
1101
- if (clean.length <= limit) return clean;
1102
- const chars = Array.from(clean);
1103
- return chars.length > limit ? chars.slice(0, limit).join("") : clean;
1104
- }
1105
- function sanitizeNoticeUrl(value) {
1106
- if (typeof value !== "string") return null;
1107
- let url;
1108
- try {
1109
- url = new URL(value.trim());
1110
- } catch {
1111
- return null;
1112
- }
1113
- if (url.protocol !== "https:") return null;
1114
- if (!NOTICE_HOSTS.has(url.hostname) || url.port !== "") return null;
1115
- if (url.username !== "" || url.password !== "") return null;
1116
- const href = url.href;
1117
- return href.length <= NOTICE_MESSAGE_LIMIT ? href : null;
1118
- }
1119
- function noticeSeverity(value) {
1120
- if (value === "info") return "info";
1121
- if (value === "error" || value === "critical") return "error";
1122
- return "warning";
1123
- }
1124
- function sanitizeNotices(raw) {
1125
- if (!Array.isArray(raw)) return [];
1126
- const out = [];
1127
- for (const entry of raw) {
1128
- if (out.length >= NOTICE_LIMIT) break;
1129
- if (typeof entry !== "object" || entry === null) continue;
1130
- const n = entry;
1131
- const message = sanitizeServerText(n.message);
1132
- if (message === "") continue;
1133
- out.push({
1134
- severity: noticeSeverity(n.severity),
1135
- code: sanitizeServerText(n.code, NOTICE_CODE_LIMIT),
1136
- message,
1137
- url: sanitizeNoticeUrl(n.url)
1138
- });
1139
- }
1140
- return out;
1141
- }
1142
- function formatNotice(notice) {
1143
- const head = notice.severity === "info" ? "AfterPack notice" : `AfterPack ${notice.severity}`;
1144
- const tail = notice.url ? ` ${notice.url}` : "";
1145
- return `${head}: ${notice.message}${tail}`;
1146
- }
1147
- function reportNotices(raw, logger, prefix = (m) => m) {
1148
- const notices = sanitizeNotices(raw);
1149
- for (const notice of notices) {
1150
- const line = prefix(formatNotice(notice));
1151
- if (notice.severity === "info" || !logger.warn) logger.log(line);
1152
- else logger.warn(line);
1153
- }
1154
- return notices;
1155
- }
1156
-
1157
766
  //#endregion
1158
767
  //#region src/registry.ts
1159
768
  const PRESET_VALUES = [
@@ -1163,6 +772,20 @@ const PRESET_VALUES = [
1163
772
  "hard",
1164
773
  "extreme"
1165
774
  ];
775
+ const SOURCE_TYPE_VALUES = [
776
+ "auto",
777
+ "module",
778
+ "script"
779
+ ];
780
+ const MODULE_OUTPUT_FORMATS = new Set([
781
+ "es",
782
+ "esm",
783
+ "esmodule",
784
+ "module"
785
+ ]);
786
+ function sourceTypeForOutputFormat(format) {
787
+ return typeof format === "string" && MODULE_OUTPUT_FORMATS.has(format.toLowerCase()) ? "module" : void 0;
788
+ }
1166
789
  const TRANSFORM_KIND_VALUES = [
1167
790
  "stringEncoding",
1168
791
  "controlFlowFlatten",
@@ -1212,6 +835,18 @@ const CONFIG_KEYS = [
1212
835
  },
1213
836
  default: "light"
1214
837
  },
838
+ {
839
+ path: "sourceType",
840
+ shape: "scalar",
841
+ scope: "program",
842
+ tier: "free",
843
+ surface: "engine",
844
+ item: {
845
+ kind: "enum",
846
+ values: SOURCE_TYPE_VALUES
847
+ },
848
+ default: "auto"
849
+ },
1215
850
  {
1216
851
  path: "complexity",
1217
852
  shape: "scalar",
@@ -1383,7 +1018,7 @@ const CONFIG_KEYS = [
1383
1018
  tier: "free",
1384
1019
  surface: "engine",
1385
1020
  item: { kind: "boolean" },
1386
- default: "true when the bundler emitted a source map"
1021
+ default: "true when the bundler emitted a source map, outside CI"
1387
1022
  },
1388
1023
  {
1389
1024
  path: "protectionMap.detailed",
@@ -1593,360 +1228,777 @@ const PREFIX_BY_NORMALIZED = new Map([...CONFIG_PREFIXES].map((prefix) => [norma
1593
1228
  function normalizeKey(key) {
1594
1229
  return key.replace(/[-_.]/g, "").toLowerCase();
1595
1230
  }
1596
- function groupBooleanKey(path) {
1597
- if (!CONFIG_PREFIXES.has(path)) return void 0;
1598
- return CONFIG_BY_PATH.get(`${path}.enabled`);
1231
+ function groupBooleanKey(path) {
1232
+ if (!CONFIG_PREFIXES.has(path)) return void 0;
1233
+ return CONFIG_BY_PATH.get(`${path}.enabled`);
1234
+ }
1235
+ function nearestName(name, candidates) {
1236
+ const target = normalizeKey(name);
1237
+ let best;
1238
+ for (const candidate of candidates) {
1239
+ const distance = editDistance(target, normalizeKey(candidate));
1240
+ if (distance > Math.max(2, Math.floor(target.length / 4))) continue;
1241
+ if (!best || distance < best.distance) best = {
1242
+ name: candidate,
1243
+ distance
1244
+ };
1245
+ }
1246
+ return best?.name;
1247
+ }
1248
+ function suggestKey(key) {
1249
+ const exact = BY_NORMALIZED.get(normalizeKey(key));
1250
+ if (exact) return exact.path;
1251
+ const near = nearestName(key, CONFIG_KEYS.map((k) => k.path));
1252
+ if (near) return near;
1253
+ const tail = normalizeKey(key);
1254
+ const owners = CONFIG_KEYS.filter((k) => normalizeKey(k.path.slice(k.path.lastIndexOf(".") + 1)) === tail);
1255
+ return owners.length === 1 ? owners[0].path : void 0;
1256
+ }
1257
+ function canonicalSpelling(name) {
1258
+ const norm$1 = normalizeKey(name);
1259
+ const key = BY_NORMALIZED.get(norm$1);
1260
+ if (key) return { key: key.path };
1261
+ const group$1 = CHILDREN_BY_NORMALIZED.get(norm$1);
1262
+ return group$1 && group$1.length > 0 ? { group: group$1 } : void 0;
1263
+ }
1264
+ function editDistance(a, b) {
1265
+ const prev = new Array(b.length + 1);
1266
+ const next = new Array(b.length + 1);
1267
+ for (let j = 0; j <= b.length; j++) prev[j] = j;
1268
+ for (let i = 1; i <= a.length; i++) {
1269
+ next[0] = i;
1270
+ 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));
1271
+ for (let j = 0; j <= b.length; j++) prev[j] = next[j];
1272
+ }
1273
+ return prev[b.length];
1274
+ }
1275
+ const DOCS_URL = "https://www.afterpack.dev/docs/config";
1276
+ function unknownKeyMessage(path, surface) {
1277
+ const group$1 = CHILDREN_BY_NORMALIZED.get(normalizeKey(path));
1278
+ if (group$1 && group$1.length > 0) {
1279
+ const list = group$1.map((child) => `\`${child}\``).join(", ");
1280
+ const tail$1 = group$1.length === 1 ? `did you mean ${list}?` : `its keys are ${list}`;
1281
+ const canonical = PREFIX_BY_NORMALIZED.get(normalizeKey(path));
1282
+ const enabled = canonical ? groupBooleanKey(canonical) : void 0;
1283
+ const rule = enabled ? `; a boolean here means \`${enabled.path}\`` : "";
1284
+ return `\`${path}\` is a group of configuration keys, not a key itself (${surface}) — ${tail$1}${rule}`;
1285
+ }
1286
+ const suggestion = suggestKey(path);
1287
+ const tail = suggestion ? ` — did you mean \`${suggestion}\`?` : ` — see ${DOCS_URL}`;
1288
+ return `unknown configuration key \`${path}\` (${surface})${tail}`;
1289
+ }
1290
+ function isPlainObject(value) {
1291
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1292
+ }
1293
+ function describe(item) {
1294
+ switch (item.kind) {
1295
+ case "boolean": return "true or false";
1296
+ case "number": return item.integer ? `an integer >= ${item.min}` : `a number >= ${item.min}`;
1297
+ case "unbounded": return `a number >= ${item.min}, or the string "${item.unlimited}"`;
1298
+ case "string": return "a string";
1299
+ case "enum": return `one of: ${item.values.join(", ")}`;
1300
+ case "seed": return "a number, any string, or \"git\"";
1301
+ case "reserved": return "a name, or { \"glob\": \"…\", \"names\": [\"…\"] }";
1302
+ case "region": return "an object with numeric `start` and `end`";
1303
+ }
1304
+ }
1305
+ function misdirectedHint(key, value, spell) {
1306
+ const other = misdirectedTo(key, value);
1307
+ if (!other) return "";
1308
+ const written = spell(other.path, String(value));
1309
+ return ` — \`${String(value)}\` is a \`${other.path}\` value; write \`${written}\` instead`;
1310
+ }
1311
+ const isFiniteNumber = (v) => typeof v === "number" && Number.isFinite(v);
1312
+ const isTransformKinds = (v) => Array.isArray(v) && v.every((k) => TRANSFORM_KIND_VALUES.includes(k));
1313
+ const KINDS = `a list of: ${TRANSFORM_KIND_VALUES.join(", ")}`;
1314
+ const isNonNegative = (v) => isFiniteNumber(v) && v >= 0;
1315
+ function group(fields) {
1316
+ return {
1317
+ is: isPlainObject,
1318
+ want: "an object",
1319
+ fields
1320
+ };
1321
+ }
1322
+ const REGION_FIELDS = {
1323
+ start: {
1324
+ required: true,
1325
+ is: isFiniteNumber,
1326
+ want: "a number"
1327
+ },
1328
+ end: {
1329
+ required: true,
1330
+ is: isFiniteNumber,
1331
+ want: "a number"
1332
+ },
1333
+ complexity: {
1334
+ is: isNonNegative,
1335
+ want: "a number >= 0"
1336
+ },
1337
+ inflation: group({ max: {
1338
+ is: isNonNegative,
1339
+ want: "a number >= 0"
1340
+ } }),
1341
+ strings: group({ encode: {
1342
+ is: (v) => typeof v === "boolean",
1343
+ want: "true or false"
1344
+ } }),
1345
+ transforms: group({
1346
+ only: {
1347
+ is: isTransformKinds,
1348
+ want: KINDS
1349
+ },
1350
+ deny: {
1351
+ is: isTransformKinds,
1352
+ want: KINDS
1353
+ }
1354
+ }),
1355
+ label: {
1356
+ is: (v) => typeof v === "string",
1357
+ want: "a string"
1358
+ }
1359
+ };
1360
+ const RESERVED_FIELDS = {
1361
+ glob: {
1362
+ required: true,
1363
+ is: (v) => typeof v === "string",
1364
+ want: "a string"
1365
+ },
1366
+ names: {
1367
+ required: true,
1368
+ is: (v) => Array.isArray(v) && v.every((n) => typeof n === "string"),
1369
+ want: "a list of names"
1370
+ }
1371
+ };
1372
+ function leafNames(spec, prefix) {
1373
+ return Object.entries(spec).flatMap(([name, field]) => field.fields ? leafNames(field.fields, `${prefix}${name}.`) : [prefix + name]);
1374
+ }
1375
+ function checkFields(spec, value, prefix = "") {
1376
+ for (const name of Object.keys(value)) {
1377
+ if (name in spec) continue;
1378
+ const near = nearestName(prefix + name, Object.keys(spec).map((n) => prefix + n));
1379
+ return `item has an unknown field \`${prefix}${name}\`` + (near ? ` — did you mean \`${near}\`?` : "") + ` (allowed: ${leafNames(spec, prefix).join(", ")})`;
1380
+ }
1381
+ for (const [name, field] of Object.entries(spec)) {
1382
+ const present = value[name];
1383
+ if (present === void 0) {
1384
+ if (field.required) return `item is missing \`${prefix}${name}\` (${field.want})`;
1385
+ continue;
1386
+ }
1387
+ if (!field.is(present)) return `item's \`${prefix}${name}\` must be ${field.want}, got ${JSON.stringify(present)}`;
1388
+ if (field.fields) {
1389
+ const nested = checkFields(field.fields, present, `${prefix}${name}.`);
1390
+ if (nested) return nested;
1391
+ }
1392
+ }
1393
+ return void 0;
1394
+ }
1395
+ function expected(item, value) {
1396
+ return `expected ${describe(item)}, got ${JSON.stringify(value)}`;
1397
+ }
1398
+ function checkItem(item, value) {
1399
+ switch (item.kind) {
1400
+ case "boolean": return typeof value === "boolean" ? void 0 : expected(item, value);
1401
+ case "number": {
1402
+ if (typeof value !== "number" || !Number.isFinite(value)) return expected(item, value);
1403
+ if (value < item.min) return expected(item, value);
1404
+ if (item.integer && !Number.isInteger(value)) return expected(item, value);
1405
+ return void 0;
1406
+ }
1407
+ case "unbounded": {
1408
+ if (value === item.unlimited) return void 0;
1409
+ if (typeof value === "number" && Number.isFinite(value) && value >= item.min) return void 0;
1410
+ return `${expected(item, value)} — there is no \`Infinity\` in JSON; write "${item.unlimited}"`;
1411
+ }
1412
+ case "string": return typeof value === "string" ? void 0 : expected(item, value);
1413
+ case "enum": return typeof value === "string" && item.values.includes(value) ? void 0 : expected(item, value);
1414
+ case "seed": return typeof value === "number" || typeof value === "string" ? void 0 : expected(item, value);
1415
+ case "reserved": {
1416
+ if (typeof value === "string") return void 0;
1417
+ if (!isPlainObject(value)) return expected(item, value);
1418
+ return checkFields(RESERVED_FIELDS, value);
1419
+ }
1420
+ case "region": {
1421
+ if (!isPlainObject(value)) return expected(item, value);
1422
+ return checkFields(REGION_FIELDS, value);
1423
+ }
1424
+ }
1425
+ }
1426
+ function checkValue(key, value) {
1427
+ if (key.shape === "scalar") {
1428
+ const failure = checkItem(key.item, value);
1429
+ return failure ? `\`${key.path}\`: ${failure}` : void 0;
1430
+ }
1431
+ if (!Array.isArray(value)) return `\`${key.path}\`: expected a list of values, got ${JSON.stringify(value)}`;
1432
+ for (const entry of value) {
1433
+ const failure = checkItem(key.item, entry);
1434
+ if (failure) return `\`${key.path}\`: ${failure}`;
1435
+ }
1436
+ return void 0;
1437
+ }
1438
+ function misdirectedTo(key, value) {
1439
+ if (key.namedValuesOf === void 0 || typeof value !== "string") return void 0;
1440
+ const other = CONFIG_BY_PATH.get(key.namedValuesOf);
1441
+ if (!other || other.shape !== "scalar") return void 0;
1442
+ return checkItem(other.item, value) === void 0 ? other : void 0;
1443
+ }
1444
+ function validateConfig(input, surface) {
1445
+ const issues = [];
1446
+ const config = {};
1447
+ if (input === void 0 || input === null) return {
1448
+ config,
1449
+ issues
1450
+ };
1451
+ if (!isPlainObject(input)) {
1452
+ issues.push({
1453
+ path: "",
1454
+ message: `configuration (${surface}) must be an object`
1455
+ });
1456
+ return {
1457
+ config,
1458
+ issues
1459
+ };
1460
+ }
1461
+ walk(input, "", config, issues, surface);
1462
+ return {
1463
+ config,
1464
+ issues
1465
+ };
1466
+ }
1467
+ function walk(source, prefix, target, issues, surface) {
1468
+ for (const [name, value] of Object.entries(source)) {
1469
+ if (value === void 0) continue;
1470
+ const path = prefix ? `${prefix}.${name}` : name;
1471
+ const key = CONFIG_BY_PATH.get(path);
1472
+ if (key) {
1473
+ const failure = checkValue(key, value);
1474
+ if (failure) {
1475
+ const hint = misdirectedHint(key, value, (p, v) => `"${p}": ${JSON.stringify(v)}`);
1476
+ issues.push({
1477
+ path,
1478
+ message: `${failure} (${surface})${hint}`
1479
+ });
1480
+ } else target[name] = value;
1481
+ continue;
1482
+ }
1483
+ if (CONFIG_PREFIXES.has(path)) {
1484
+ if (isPlainObject(value)) {
1485
+ const nested = {};
1486
+ walk(value, path, nested, issues, surface);
1487
+ if (Object.keys(nested).length > 0) target[name] = nested;
1488
+ continue;
1489
+ }
1490
+ const enabled = groupBooleanKey(path);
1491
+ if (enabled && typeof value === "boolean") {
1492
+ target[name] = { enabled: value };
1493
+ continue;
1494
+ }
1495
+ }
1496
+ issues.push({
1497
+ path,
1498
+ message: unknownKeyMessage(path, surface)
1499
+ });
1500
+ }
1599
1501
  }
1600
- function nearestName(name, candidates) {
1601
- const target = normalizeKey(name);
1602
- let best;
1603
- for (const candidate of candidates) {
1604
- const distance = editDistance(target, normalizeKey(candidate));
1605
- if (distance > Math.max(2, Math.floor(target.length / 4))) continue;
1606
- if (!best || distance < best.distance) best = {
1607
- name: candidate,
1608
- distance
1609
- };
1502
+ function deepMerge(base, override) {
1503
+ const out = { ...base };
1504
+ for (const [name, value] of Object.entries(override)) {
1505
+ if (value === void 0) continue;
1506
+ const existing = out[name];
1507
+ out[name] = isPlainObject(value) && isPlainObject(existing) ? deepMerge(existing, value) : value;
1610
1508
  }
1611
- return best?.name;
1509
+ return out;
1612
1510
  }
1613
- function suggestKey(key) {
1614
- const exact = BY_NORMALIZED.get(normalizeKey(key));
1615
- if (exact) return exact.path;
1616
- const near = nearestName(key, CONFIG_KEYS.map((k) => k.path));
1617
- if (near) return near;
1618
- const tail = normalizeKey(key);
1619
- const owners = CONFIG_KEYS.filter((k) => normalizeKey(k.path.slice(k.path.lastIndexOf(".") + 1)) === tail);
1620
- return owners.length === 1 ? owners[0].path : void 0;
1511
+ function mergeInto(base, override) {
1512
+ return deepMerge(base, override);
1621
1513
  }
1622
- function canonicalSpelling(name) {
1623
- const norm$1 = normalizeKey(name);
1624
- const key = BY_NORMALIZED.get(norm$1);
1625
- if (key) return { key: key.path };
1626
- const group$1 = CHILDREN_BY_NORMALIZED.get(norm$1);
1627
- return group$1 && group$1.length > 0 ? { group: group$1 } : void 0;
1514
+ function mergeConfig(base, override) {
1515
+ return deepMerge(base, override);
1628
1516
  }
1629
- function editDistance(a, b) {
1630
- const prev = new Array(b.length + 1);
1631
- const next = new Array(b.length + 1);
1632
- for (let j = 0; j <= b.length; j++) prev[j] = j;
1633
- for (let i = 1; i <= a.length; i++) {
1634
- next[0] = i;
1635
- 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));
1636
- for (let j = 0; j <= b.length; j++) prev[j] = next[j];
1517
+ function getPath(config, path) {
1518
+ let current = config;
1519
+ for (const part of path.split(".")) {
1520
+ if (!isPlainObject(current)) return void 0;
1521
+ current = current[part];
1637
1522
  }
1638
- return prev[b.length];
1523
+ return current;
1639
1524
  }
1640
- const DOCS_URL = "https://www.afterpack.dev/docs/config";
1641
- function unknownKeyMessage(path, surface) {
1642
- const group$1 = CHILDREN_BY_NORMALIZED.get(normalizeKey(path));
1643
- if (group$1 && group$1.length > 0) {
1644
- const list = group$1.map((child) => `\`${child}\``).join(", ");
1645
- const tail$1 = group$1.length === 1 ? `did you mean ${list}?` : `its keys are ${list}`;
1646
- const canonical = PREFIX_BY_NORMALIZED.get(normalizeKey(path));
1647
- const enabled = canonical ? groupBooleanKey(canonical) : void 0;
1648
- const rule = enabled ? `; a boolean here means \`${enabled.path}\`` : "";
1649
- return `\`${path}\` is a group of configuration keys, not a key itself (${surface}) — ${tail$1}${rule}`;
1525
+ function nest(path, value) {
1526
+ return path.split(".").reduceRight((inner, segment) => ({ [segment]: inner }), value);
1527
+ }
1528
+ function setPath(target, path, value) {
1529
+ const parts = path.split(".");
1530
+ let node = target;
1531
+ for (const part of parts.slice(0, -1)) {
1532
+ if (!isPlainObject(node[part])) node[part] = {};
1533
+ node = node[part];
1650
1534
  }
1651
- const suggestion = suggestKey(path);
1652
- const tail = suggestion ? ` — did you mean \`${suggestion}\`?` : ` — see ${DOCS_URL}`;
1653
- return `unknown configuration key \`${path}\` (${surface})${tail}`;
1535
+ node[parts[parts.length - 1]] = value;
1654
1536
  }
1655
- function isPlainObject(value) {
1656
- return typeof value === "object" && value !== null && !Array.isArray(value);
1537
+ function toEngineConfig(config) {
1538
+ const out = {};
1539
+ for (const key of CONFIG_KEYS) {
1540
+ if (key.surface !== "engine") continue;
1541
+ const value = getPath(config, key.path);
1542
+ if (value === void 0) continue;
1543
+ setPath(out, key.path, value);
1544
+ }
1545
+ return out;
1657
1546
  }
1658
- function describe(item) {
1659
- switch (item.kind) {
1660
- case "boolean": return "true or false";
1661
- case "number": return item.integer ? `an integer >= ${item.min}` : `a number >= ${item.min}`;
1662
- case "unbounded": return `a number >= ${item.min}, or the string "${item.unlimited}"`;
1663
- case "string": return "a string";
1664
- case "enum": return `one of: ${item.values.join(", ")}`;
1665
- case "seed": return "a number, any string, or \"git\"";
1666
- case "reserved": return "a name, or { \"glob\": \"…\", \"names\": [\"…\"] }";
1667
- case "region": return "an object with numeric `start` and `end`";
1547
+ function toPluginOptions(config) {
1548
+ const read = (path) => getPath(config, path);
1549
+ const set = (container) => Object.values(container).some((v) => v !== void 0) ? container : void 0;
1550
+ return {
1551
+ artifactOptions: {
1552
+ protectionMap: set({ enabled: read("protectionMap.enabled") }),
1553
+ sourceMap: set({
1554
+ enabled: read("sourceMap.enabled"),
1555
+ emitUrl: read("sourceMap.emitUrl")
1556
+ }),
1557
+ build: set({
1558
+ backup: read("build.backup"),
1559
+ mode: read("build.mode")
1560
+ }),
1561
+ allowUnobfuscated: read("allowUnobfuscated"),
1562
+ telemetry: set({ enabled: read("telemetry.enabled") })
1563
+ },
1564
+ seed: read("seed"),
1565
+ preset: read("preset"),
1566
+ complexity: read("complexity"),
1567
+ regions: read("regions"),
1568
+ directives: {
1569
+ enabled: read("directives.enabled") ?? DIRECTIVES_ENABLED_DEFAULT,
1570
+ explicit: read("directives.enabled") !== void 0
1571
+ },
1572
+ build: set({ autorun: read("build.autorun") }),
1573
+ diagnostics: set({
1574
+ level: read("diagnostics.level"),
1575
+ format: read("diagnostics.format")
1576
+ }),
1577
+ paths: set({ include: read("paths.include") }),
1578
+ key: read("key")
1579
+ };
1580
+ }
1581
+
1582
+ //#endregion
1583
+ //#region src/source-map.ts
1584
+ const SOURCE_MAPPING_URL_RE = /\/\/[#@]\s*sourceMappingURL=(\S+)\s*$/gm;
1585
+ const SOURCE_MAPPING_URL_LINE_RE = /^[ \t]*\/\/[#@]\s*sourceMappingURL=\S+[ \t]*\r?\n?/gm;
1586
+ const CSS_SOURCE_MAPPING_URL_RE = /[ \t]*\/\*[#@]\s*sourceMappingURL=[^\s*]+\s*\*\/\s*$/;
1587
+ function withSourceMappingURL(code, url) {
1588
+ const stripped = code.replace(SOURCE_MAPPING_URL_LINE_RE, "");
1589
+ if (url == null) return stripped;
1590
+ const separator = stripped.length > 0 && !stripped.endsWith("\n") ? "\n" : "";
1591
+ return `${stripped}${separator}//# sourceMappingURL=${url}\n`;
1592
+ }
1593
+ function withoutCssSourceMappingURL(css) {
1594
+ return css.replace(CSS_SOURCE_MAPPING_URL_RE, "");
1595
+ }
1596
+ function extractSourceMappingURL(code) {
1597
+ let last = null;
1598
+ for (const match of code.matchAll(SOURCE_MAPPING_URL_RE)) last = match[1];
1599
+ return last;
1600
+ }
1601
+ function isRemoteSourceMappingURL(url) {
1602
+ return /^https?:\/\//i.test(url) || url.startsWith("//");
1603
+ }
1604
+ function decodeDataUri(url) {
1605
+ if (!url.startsWith("data:")) return null;
1606
+ const comma = url.indexOf(",");
1607
+ if (comma === -1) return null;
1608
+ const meta = url.slice(5, comma);
1609
+ const payload = url.slice(comma + 1);
1610
+ try {
1611
+ if (/;base64/i.test(meta)) return Buffer.from(payload, "base64").toString("utf8");
1612
+ return decodeURIComponent(payload);
1613
+ } catch {
1614
+ return null;
1668
1615
  }
1669
1616
  }
1670
- function misdirectedHint(key, value, spell) {
1671
- const other = misdirectedTo(key, value);
1672
- if (!other) return "";
1673
- const written = spell(other.path, String(value));
1674
- return ` — \`${String(value)}\` is a \`${other.path}\` value; write \`${written}\` instead`;
1617
+ function discoverInputSourceMap(jsPath, code) {
1618
+ const adjacent = `${jsPath}.map`;
1619
+ if ((0, node_fs.existsSync)(adjacent)) try {
1620
+ return (0, node_fs.readFileSync)(adjacent, "utf8");
1621
+ } catch {}
1622
+ let source = code;
1623
+ if (source == null) try {
1624
+ source = (0, node_fs.readFileSync)(jsPath, "utf8");
1625
+ } catch {
1626
+ return null;
1627
+ }
1628
+ const url = extractSourceMappingURL(source);
1629
+ if (url == null) return null;
1630
+ if (url.startsWith("data:")) return decodeDataUri(url);
1631
+ if (isRemoteSourceMappingURL(url)) return null;
1632
+ let mapPath;
1633
+ try {
1634
+ mapPath = (0, node_path.isAbsolute)(url) ? url : (0, node_path.resolve)((0, node_path.dirname)(jsPath), decodeURIComponent(url));
1635
+ } catch {
1636
+ return null;
1637
+ }
1638
+ if (!(0, node_fs.existsSync)(mapPath)) return null;
1639
+ try {
1640
+ return (0, node_fs.readFileSync)(mapPath, "utf8");
1641
+ } catch {
1642
+ return null;
1643
+ }
1675
1644
  }
1676
- const isFiniteNumber = (v) => typeof v === "number" && Number.isFinite(v);
1677
- const isTransformKinds = (v) => Array.isArray(v) && v.every((k) => TRANSFORM_KIND_VALUES.includes(k));
1678
- const KINDS = `a list of: ${TRANSFORM_KIND_VALUES.join(", ")}`;
1679
- const isNonNegative = (v) => isFiniteNumber(v) && v >= 0;
1680
- function group(fields) {
1645
+
1646
+ //#endregion
1647
+ //#region src/bundle.ts
1648
+ const BUNDLE_JS_RE = /\.[cm]?js$/;
1649
+ const CSS_MAP_RE = /\.css\.map$/;
1650
+ function collectBundleJs(bundle, outDir) {
1651
+ const files = [];
1652
+ const inputs = new Map();
1653
+ const entries = new Map();
1654
+ for (const [fileName, entry] of Object.entries(bundle)) {
1655
+ if (!BUNDLE_JS_RE.test(fileName)) continue;
1656
+ const source = entry.type === "chunk" ? entry.code : typeof entry.source === "string" ? entry.source : void 0;
1657
+ if (source === void 0) continue;
1658
+ const filePath = (0, node_path.resolve)(outDir, fileName);
1659
+ files.push(filePath);
1660
+ entries.set(filePath, entry);
1661
+ inputs.set(filePath, {
1662
+ source,
1663
+ sourceMap: entry.map ? entry.map.toString() : null
1664
+ });
1665
+ }
1681
1666
  return {
1682
- is: isPlainObject,
1683
- want: "an object",
1684
- fields
1667
+ files,
1668
+ inputs,
1669
+ entries
1685
1670
  };
1686
1671
  }
1687
- const REGION_FIELDS = {
1688
- start: {
1689
- required: true,
1690
- is: isFiniteNumber,
1691
- want: "a number"
1692
- },
1693
- end: {
1694
- required: true,
1695
- is: isFiniteNumber,
1696
- want: "a number"
1697
- },
1698
- complexity: {
1699
- is: isNonNegative,
1700
- want: "a number >= 0"
1701
- },
1702
- inflation: group({ max: {
1703
- is: isNonNegative,
1704
- want: "a number >= 0"
1705
- } }),
1706
- strings: group({ encode: {
1707
- is: (v) => typeof v === "boolean",
1708
- want: "true or false"
1709
- } }),
1710
- transforms: group({
1711
- only: {
1712
- is: isTransformKinds,
1713
- want: KINDS
1714
- },
1715
- deny: {
1716
- is: isTransformKinds,
1717
- want: KINDS
1718
- }
1719
- }),
1720
- label: {
1721
- is: (v) => typeof v === "string",
1722
- want: "a string"
1672
+ function sourceTypeForBundle(format, entries) {
1673
+ for (const entry of entries) if (entry.type !== "chunk") return void 0;
1674
+ return sourceTypeForOutputFormat(format);
1675
+ }
1676
+ function dataUri(json) {
1677
+ return `data:application/json;charset=utf-8;base64,${Buffer.from(json, "utf8").toString("base64")}`;
1678
+ }
1679
+ function applyBundleOutput(bundle, entry, out, policy) {
1680
+ if (entry.type !== "chunk") {
1681
+ entry.source = out.code;
1682
+ return;
1723
1683
  }
1724
- };
1725
- const RESERVED_FIELDS = {
1726
- glob: {
1727
- required: true,
1728
- is: (v) => typeof v === "string",
1729
- want: "a string"
1730
- },
1731
- names: {
1732
- required: true,
1733
- is: (v) => Array.isArray(v) && v.every((n) => typeof n === "string"),
1734
- want: "a list of names"
1684
+ const mapName = entry.sourcemapFileName ?? null;
1685
+ const inlineMap = mapName == null && entry.map != null;
1686
+ const emitMap = policy.sourceMap && out.sourceMap != null;
1687
+ let url = null;
1688
+ if (emitMap && out.sourceMap != null) {
1689
+ if (mapName != null && bundle[mapName]) {
1690
+ bundle[mapName].source = out.sourceMap;
1691
+ url = (0, node_path.basename)(mapName);
1692
+ } else if (inlineMap) url = dataUri(out.sourceMap);
1693
+ } else {
1694
+ if (mapName != null) delete bundle[mapName];
1695
+ entry.map = null;
1735
1696
  }
1736
- };
1737
- function leafNames(spec, prefix) {
1738
- return Object.entries(spec).flatMap(([name, field]) => field.fields ? leafNames(field.fields, `${prefix}${name}.`) : [prefix + name]);
1697
+ entry.code = withSourceMappingURL(out.code, policy.emitSourceMappingURL ? url : null);
1739
1698
  }
1740
- function checkFields(spec, value, prefix = "") {
1741
- for (const name of Object.keys(value)) {
1742
- if (name in spec) continue;
1743
- const near = nearestName(prefix + name, Object.keys(spec).map((n) => prefix + n));
1744
- return `item has an unknown field \`${prefix}${name}\`` + (near ? ` — did you mean \`${near}\`?` : "") + ` (allowed: ${leafNames(spec, prefix).join(", ")})`;
1745
- }
1746
- for (const [name, field] of Object.entries(spec)) {
1747
- const present = value[name];
1748
- if (present === void 0) {
1749
- if (field.required) return `item is missing \`${prefix}${name}\` (${field.want})`;
1699
+ function stripBundleCssSourceMaps(bundle) {
1700
+ for (const [fileName, entry] of Object.entries(bundle)) {
1701
+ if (CSS_MAP_RE.test(fileName)) {
1702
+ delete bundle[fileName];
1750
1703
  continue;
1751
1704
  }
1752
- if (!field.is(present)) return `item's \`${prefix}${name}\` must be ${field.want}, got ${JSON.stringify(present)}`;
1753
- if (field.fields) {
1754
- const nested = checkFields(field.fields, present, `${prefix}${name}.`);
1755
- if (nested) return nested;
1756
- }
1705
+ if (entry.type !== "asset" || !fileName.endsWith(".css") || entry.source === void 0) continue;
1706
+ const css = typeof entry.source === "string" ? entry.source : Buffer.from(entry.source).toString("utf8");
1707
+ const stripped = withoutCssSourceMappingURL(css);
1708
+ if (stripped !== css) entry.source = stripped;
1757
1709
  }
1758
- return void 0;
1759
1710
  }
1760
- function expected(item, value) {
1761
- return `expected ${describe(item)}, got ${JSON.stringify(value)}`;
1711
+
1712
+ //#endregion
1713
+ //#region src/glob.ts
1714
+ function normalize(value) {
1715
+ return value.includes("\\") ? value.replaceAll("\\", "/") : value;
1762
1716
  }
1763
- function checkItem(item, value) {
1764
- switch (item.kind) {
1765
- case "boolean": return typeof value === "boolean" ? void 0 : expected(item, value);
1766
- case "number": {
1767
- if (typeof value !== "number" || !Number.isFinite(value)) return expected(item, value);
1768
- if (value < item.min) return expected(item, value);
1769
- if (item.integer && !Number.isInteger(value)) return expected(item, value);
1770
- return void 0;
1771
- }
1772
- case "unbounded": {
1773
- if (value === item.unlimited) return void 0;
1774
- if (typeof value === "number" && Number.isFinite(value) && value >= item.min) return void 0;
1775
- return `${expected(item, value)} — there is no \`Infinity\` in JSON; write "${item.unlimited}"`;
1776
- }
1777
- case "string": return typeof value === "string" ? void 0 : expected(item, value);
1778
- case "enum": return typeof value === "string" && item.values.includes(value) ? void 0 : expected(item, value);
1779
- case "seed": return typeof value === "number" || typeof value === "string" ? void 0 : expected(item, value);
1780
- case "reserved": {
1781
- if (typeof value === "string") return void 0;
1782
- if (!isPlainObject(value)) return expected(item, value);
1783
- return checkFields(RESERVED_FIELDS, value);
1784
- }
1785
- case "region": {
1786
- if (!isPlainObject(value)) return expected(item, value);
1787
- return checkFields(REGION_FIELDS, value);
1788
- }
1789
- }
1717
+ function segments(value) {
1718
+ return value.split("/").filter((part) => part !== "");
1790
1719
  }
1791
- function checkValue(key, value) {
1792
- if (key.shape === "scalar") {
1793
- const failure = checkItem(key.item, value);
1794
- return failure ? `\`${key.path}\`: ${failure}` : void 0;
1795
- }
1796
- if (!Array.isArray(value)) return `\`${key.path}\`: expected a list of values, got ${JSON.stringify(value)}`;
1797
- for (const entry of value) {
1798
- const failure = checkItem(key.item, entry);
1799
- if (failure) return `\`${key.path}\`: ${failure}`;
1720
+ function isAnchored(pattern) {
1721
+ if (pattern.startsWith("/")) return true;
1722
+ return pattern.length >= 2 && pattern[1] === ":" && /^[A-Za-z]$/.test(pattern[0]);
1723
+ }
1724
+ function segmentMatches(pattern, seg) {
1725
+ if (!pattern.includes("*") && !pattern.includes("?")) return pattern === seg;
1726
+ const p = [...pattern];
1727
+ const s = [...seg];
1728
+ let pi = 0;
1729
+ let si = 0;
1730
+ let star = -1;
1731
+ let starSi = 0;
1732
+ while (si < s.length) if (pi < p.length && p[pi] === "*") {
1733
+ star = pi;
1734
+ starSi = si;
1735
+ pi += 1;
1736
+ } else if (pi < p.length && (p[pi] === "?" || p[pi] === s[si])) {
1737
+ pi += 1;
1738
+ si += 1;
1739
+ } else if (star >= 0) {
1740
+ pi = star + 1;
1741
+ starSi += 1;
1742
+ si = starSi;
1743
+ } else return false;
1744
+ return p.slice(pi).every((c) => c === "*");
1745
+ }
1746
+ function segmentsMatch(pattern, path) {
1747
+ let pi = 0;
1748
+ let si = 0;
1749
+ let star = -1;
1750
+ let starSi = 0;
1751
+ while (si < path.length) if (pi < pattern.length && pattern[pi] === "**") {
1752
+ star = pi;
1753
+ starSi = si;
1754
+ pi += 1;
1755
+ } else if (pi < pattern.length && segmentMatches(pattern[pi], path[si])) {
1756
+ pi += 1;
1757
+ si += 1;
1758
+ } else if (star >= 0) {
1759
+ pi = star + 1;
1760
+ starSi += 1;
1761
+ si = starSi;
1762
+ } else return false;
1763
+ return pattern.slice(pi).every((s) => s === "**");
1764
+ }
1765
+ function matchesPath(pattern, path) {
1766
+ const pat = normalize(pattern);
1767
+ const parts = segments(pat);
1768
+ if (parts.length === 0) return false;
1769
+ const segs = segments(normalize(path));
1770
+ if (isAnchored(pat)) return segmentsMatch(parts, segs);
1771
+ for (let i = 0; i <= segs.length; i++) if (segmentsMatch(parts, segs.slice(i))) return true;
1772
+ return false;
1773
+ }
1774
+ function reachesInto(pattern, dir) {
1775
+ const pat = normalize(pattern);
1776
+ const parts = segments(pat);
1777
+ if (parts.length === 0) return false;
1778
+ if (!isAnchored(pat)) return true;
1779
+ for (let k = 1; k <= parts.length; k++) if (matchesPath(`/${parts.slice(0, k).join("/")}`, dir)) return true;
1780
+ return false;
1781
+ }
1782
+
1783
+ //#endregion
1784
+ //#region src/collect.ts
1785
+ const BACKUP_RE = /\.backup\.[0-9a-f]{8}\.[cm]?js$/;
1786
+ const NODE_MODULES = "node_modules";
1787
+ function isCollectableJs(name) {
1788
+ if (BACKUP_RE.test(name)) return false;
1789
+ return name.endsWith(".js") || name.endsWith(".mjs") || name.endsWith(".cjs");
1790
+ }
1791
+ function statOrNull(path) {
1792
+ try {
1793
+ return (0, node_fs.statSync)(path);
1794
+ } catch {
1795
+ return null;
1800
1796
  }
1801
- return void 0;
1802
1797
  }
1803
- function misdirectedTo(key, value) {
1804
- if (key.namedValuesOf === void 0 || typeof value !== "string") return void 0;
1805
- const other = CONFIG_BY_PATH.get(key.namedValuesOf);
1806
- if (!other || other.shape !== "scalar") return void 0;
1807
- return checkItem(other.item, value) === void 0 ? other : void 0;
1798
+ function collectJsFiles(target, options = {}) {
1799
+ const stat = statOrNull(target);
1800
+ if (!stat) return [];
1801
+ if (!stat.isDirectory()) return isCollectableJs((0, node_path.basename)(target)) ? [target] : [];
1802
+ return walkJs(target, options.include ?? [], false, options.onNestedProject);
1808
1803
  }
1809
- function validateConfig(input, surface) {
1810
- const issues = [];
1811
- const config = {};
1812
- if (input === void 0 || input === null) return {
1813
- config,
1814
- issues
1815
- };
1816
- if (!isPlainObject(input)) {
1817
- issues.push({
1818
- path: "",
1819
- message: `configuration (${surface}) must be an object`
1820
- });
1821
- return {
1822
- config,
1823
- issues
1824
- };
1804
+ function entriesOf(dir) {
1805
+ try {
1806
+ return (0, node_fs.readdirSync)(dir, { withFileTypes: true });
1807
+ } catch {
1808
+ return [];
1825
1809
  }
1826
- walk(input, "", config, issues, surface);
1827
- return {
1828
- config,
1829
- issues
1830
- };
1831
1810
  }
1832
- function walk(source, prefix, target, issues, surface) {
1833
- for (const [name, value] of Object.entries(source)) {
1834
- if (value === void 0) continue;
1835
- const path = prefix ? `${prefix}.${name}` : name;
1836
- const key = CONFIG_BY_PATH.get(path);
1837
- if (key) {
1838
- const failure = checkValue(key, value);
1839
- if (failure) {
1840
- const hint = misdirectedHint(key, value, (p, v) => `"${p}": ${JSON.stringify(v)}`);
1841
- issues.push({
1842
- path,
1843
- message: `${failure} (${surface})${hint}`
1844
- });
1845
- } else target[name] = value;
1846
- continue;
1847
- }
1848
- if (CONFIG_PREFIXES.has(path)) {
1849
- if (isPlainObject(value)) {
1850
- const nested = {};
1851
- walk(value, path, nested, issues, surface);
1852
- if (Object.keys(nested).length > 0) target[name] = nested;
1853
- continue;
1854
- }
1855
- const enabled = groupBooleanKey(path);
1856
- if (enabled && typeof value === "boolean") {
1857
- target[name] = { enabled: value };
1811
+ function kindOf(entry, full) {
1812
+ if (entry.isDirectory()) return "dir";
1813
+ if (entry.isFile()) return "file";
1814
+ const stat = statOrNull(full);
1815
+ if (!stat) return null;
1816
+ return stat.isDirectory() ? "dir" : "file";
1817
+ }
1818
+ function isNestedProject(dir) {
1819
+ return (0, node_fs.existsSync)((0, node_path.join)(dir, "package.json"));
1820
+ }
1821
+ function walkJs(dir, include, readmitted, onNestedProject) {
1822
+ const out = [];
1823
+ for (const entry of entriesOf(dir)) {
1824
+ const name = entry.name;
1825
+ const full = (0, node_path.join)(dir, name);
1826
+ const kind = kindOf(entry, full);
1827
+ if (kind === null) continue;
1828
+ if (kind === "dir") {
1829
+ const skipped = name === NODE_MODULES;
1830
+ if (!skipped && !readmitted && isNestedProject(full)) {
1831
+ onNestedProject?.(full);
1858
1832
  continue;
1859
1833
  }
1834
+ if (skipped && !include.some((pattern) => reachesInto(pattern, full))) continue;
1835
+ out.push(...walkJs(full, include, readmitted || skipped, onNestedProject));
1836
+ } else if (isCollectableJs(name)) {
1837
+ if (readmitted && !include.some((pattern) => matchesPath(pattern, full))) continue;
1838
+ out.push(full);
1860
1839
  }
1861
- issues.push({
1862
- path,
1863
- message: unknownKeyMessage(path, surface)
1864
- });
1865
1840
  }
1841
+ return out;
1866
1842
  }
1867
- function deepMerge(base, override) {
1868
- const out = { ...base };
1869
- for (const [name, value] of Object.entries(override)) {
1870
- if (value === void 0) continue;
1871
- const existing = out[name];
1872
- out[name] = isPlainObject(value) && isPlainObject(existing) ? deepMerge(existing, value) : value;
1843
+ const SOURCE_MAP_RE = /\.(?:[cm]?js|css)\.map$/;
1844
+ function collectFiles(dir, accept) {
1845
+ if (!(0, node_fs.existsSync)(dir)) return [];
1846
+ const out = [];
1847
+ for (const entry of entriesOf(dir)) {
1848
+ const name = entry.name;
1849
+ const full = (0, node_path.join)(dir, name);
1850
+ const kind = kindOf(entry, full);
1851
+ if (kind === null) continue;
1852
+ if (kind === "dir") out.push(...collectFiles(full, accept));
1853
+ else if (accept(name)) out.push(full);
1873
1854
  }
1874
1855
  return out;
1875
1856
  }
1876
- function mergeInto(base, override) {
1877
- return deepMerge(base, override);
1857
+ function collectSourceMaps(dir) {
1858
+ return collectFiles(dir, (name) => SOURCE_MAP_RE.test(name));
1878
1859
  }
1879
- function mergeConfig(base, override) {
1880
- return deepMerge(base, override);
1860
+ function collectStylesheets(dir) {
1861
+ return collectFiles(dir, (name) => name.endsWith(".css"));
1881
1862
  }
1882
- function getPath(config, path) {
1883
- let current = config;
1884
- for (const part of path.split(".")) {
1885
- if (!isPlainObject(current)) return void 0;
1886
- current = current[part];
1863
+
1864
+ //#endregion
1865
+ //#region src/notices.ts
1866
+ const NOTICE_MESSAGE_LIMIT = 500;
1867
+ const NOTICE_LIMIT = 5;
1868
+ const NOTICE_CODE_LIMIT = 64;
1869
+ const NOTICE_HOSTS = new Set(["afterpack.dev", "www.afterpack.dev"]);
1870
+ const ESC = 27;
1871
+ const BEL = 7;
1872
+ const C1_CSI = 155;
1873
+ const C1_OSC = 157;
1874
+ function isControl(code) {
1875
+ return code < 32 || code >= 127 && code <= 159;
1876
+ }
1877
+ function isInvisibleFormat(code) {
1878
+ return code === 1564 || code >= 8203 && code <= 8207 || code >= 8234 && code <= 8238 || code >= 8288 && code <= 8297 || code === 65279;
1879
+ }
1880
+ function skipCsi(text, from) {
1881
+ let i = from;
1882
+ while (i < text.length) {
1883
+ const c = text.charCodeAt(i);
1884
+ i += 1;
1885
+ if (c >= 64 && c <= 126) return i;
1887
1886
  }
1888
- return current;
1887
+ return i;
1889
1888
  }
1890
- function nest(path, value) {
1891
- return path.split(".").reduceRight((inner, segment) => ({ [segment]: inner }), value);
1889
+ function skipOsc(text, from) {
1890
+ let i = from;
1891
+ while (i < text.length) {
1892
+ const c = text.charCodeAt(i);
1893
+ if (c === BEL) return i + 1;
1894
+ if (c === ESC) return text.charCodeAt(i + 1) === 92 ? i + 2 : i + 1;
1895
+ if (c === 156) return i + 1;
1896
+ i += 1;
1897
+ }
1898
+ return i;
1892
1899
  }
1893
- function setPath(target, path, value) {
1894
- const parts = path.split(".");
1895
- let node = target;
1896
- for (const part of parts.slice(0, -1)) {
1897
- if (!isPlainObject(node[part])) node[part] = {};
1898
- node = node[part];
1900
+ function stripTerminalControls(text) {
1901
+ let out = "";
1902
+ let i = 0;
1903
+ while (i < text.length) {
1904
+ const c = text.charCodeAt(i);
1905
+ if (c === ESC) {
1906
+ const next = text.charCodeAt(i + 1);
1907
+ if (next === 91) i = skipCsi(text, i + 2);
1908
+ else if (next === 93) i = skipOsc(text, i + 2);
1909
+ else i += Number.isNaN(next) ? 1 : 2;
1910
+ continue;
1911
+ }
1912
+ if (c === C1_CSI) {
1913
+ i = skipCsi(text, i + 1);
1914
+ continue;
1915
+ }
1916
+ if (c === C1_OSC) {
1917
+ i = skipOsc(text, i + 1);
1918
+ continue;
1919
+ }
1920
+ if (isControl(c)) {
1921
+ out += c === 9 || c === 10 || c === 13 ? " " : "";
1922
+ i += 1;
1923
+ continue;
1924
+ }
1925
+ if (c === 8232 || c === 8233) {
1926
+ out += " ";
1927
+ i += 1;
1928
+ continue;
1929
+ }
1930
+ if (isInvisibleFormat(c)) {
1931
+ i += 1;
1932
+ continue;
1933
+ }
1934
+ out += text[i];
1935
+ i += 1;
1899
1936
  }
1900
- node[parts[parts.length - 1]] = value;
1937
+ return out;
1901
1938
  }
1902
- function toEngineConfig(config) {
1903
- const out = {};
1904
- for (const key of CONFIG_KEYS) {
1905
- if (key.surface !== "engine") continue;
1906
- const value = getPath(config, key.path);
1907
- if (value === void 0) continue;
1908
- setPath(out, key.path, value);
1939
+ function sanitizeServerText(value, limit = NOTICE_MESSAGE_LIMIT) {
1940
+ if (typeof value !== "string") return "";
1941
+ const clean = stripTerminalControls(value).replace(/\s+/g, " ").trim();
1942
+ if (clean.length <= limit) return clean;
1943
+ const chars = Array.from(clean);
1944
+ return chars.length > limit ? chars.slice(0, limit).join("") : clean;
1945
+ }
1946
+ function sanitizeNoticeUrl(value) {
1947
+ if (typeof value !== "string") return null;
1948
+ let url;
1949
+ try {
1950
+ url = new URL(value.trim());
1951
+ } catch {
1952
+ return null;
1953
+ }
1954
+ if (url.protocol !== "https:") return null;
1955
+ if (!NOTICE_HOSTS.has(url.hostname) || url.port !== "") return null;
1956
+ if (url.username !== "" || url.password !== "") return null;
1957
+ const href = url.href;
1958
+ return href.length <= NOTICE_MESSAGE_LIMIT ? href : null;
1959
+ }
1960
+ function noticeSeverity(value) {
1961
+ if (value === "info") return "info";
1962
+ if (value === "error" || value === "critical") return "error";
1963
+ return "warning";
1964
+ }
1965
+ function sanitizeNotices(raw) {
1966
+ if (!Array.isArray(raw)) return [];
1967
+ const out = [];
1968
+ for (const entry of raw) {
1969
+ if (out.length >= NOTICE_LIMIT) break;
1970
+ if (typeof entry !== "object" || entry === null) continue;
1971
+ const n = entry;
1972
+ const message = sanitizeServerText(n.message);
1973
+ if (message === "") continue;
1974
+ out.push({
1975
+ severity: noticeSeverity(n.severity),
1976
+ code: sanitizeServerText(n.code, NOTICE_CODE_LIMIT),
1977
+ message,
1978
+ url: sanitizeNoticeUrl(n.url)
1979
+ });
1909
1980
  }
1910
1981
  return out;
1911
1982
  }
1912
- function toPluginOptions(config) {
1913
- const read = (path) => getPath(config, path);
1914
- const set = (container) => Object.values(container).some((v) => v !== void 0) ? container : void 0;
1915
- return {
1916
- artifactOptions: {
1917
- protectionMap: set({ enabled: read("protectionMap.enabled") }),
1918
- sourceMap: set({
1919
- enabled: read("sourceMap.enabled"),
1920
- emitUrl: read("sourceMap.emitUrl")
1921
- }),
1922
- build: set({
1923
- backup: read("build.backup"),
1924
- mode: read("build.mode")
1925
- }),
1926
- allowUnobfuscated: read("allowUnobfuscated"),
1927
- telemetry: set({ enabled: read("telemetry.enabled") })
1928
- },
1929
- seed: read("seed"),
1930
- preset: read("preset"),
1931
- complexity: read("complexity"),
1932
- regions: read("regions"),
1933
- directives: {
1934
- enabled: read("directives.enabled") ?? DIRECTIVES_ENABLED_DEFAULT,
1935
- explicit: read("directives.enabled") !== void 0
1936
- },
1937
- build: set({ autorun: read("build.autorun") }),
1938
- diagnostics: set({
1939
- level: read("diagnostics.level"),
1940
- format: read("diagnostics.format")
1941
- }),
1942
- paths: set({ include: read("paths.include") }),
1943
- key: read("key")
1944
- };
1983
+ function formatNotice(notice) {
1984
+ const head = notice.severity === "info" ? "AfterPack notice" : `AfterPack ${notice.severity}`;
1985
+ const tail = notice.url ? ` ${notice.url}` : "";
1986
+ return `${head}: ${notice.message}${tail}`;
1987
+ }
1988
+ function reportNotices(raw, logger, prefix = (m) => m) {
1989
+ const notices = sanitizeNotices(raw);
1990
+ for (const notice of notices) {
1991
+ const line = prefix(formatNotice(notice));
1992
+ if (notice.severity === "info" || !logger.warn) logger.log(line);
1993
+ else logger.warn(line);
1994
+ }
1995
+ return notices;
1945
1996
  }
1946
1997
 
1947
1998
  //#endregion
1948
1999
  //#region src/compat.ts
1949
2000
  const MIN_CORE_VERSION = "0.2.0";
2001
+ const SOURCE_TYPE_MIN_CORE_VERSION = "0.2.3";
1950
2002
  const CORE_PACKAGE = "@afterpack/core";
1951
2003
  const VERSION_PATTERN$1 = /^\d{1,9}\.\d{1,9}\.\d{1,9}(?:[-+][0-9A-Za-z.+-]{1,64})?$/;
1952
2004
  const PACKAGE_NAME_PATTERN = /^(?:@[a-z0-9][a-z0-9._-]{0,63}\/)?[a-z0-9][a-z0-9._-]{0,63}$/;
@@ -2018,6 +2070,9 @@ function isBelowVersion(version, minimum) {
2018
2070
  for (let i = 0; i < 3; i++) if (have[i] !== need[i]) return have[i] < need[i];
2019
2071
  return false;
2020
2072
  }
2073
+ function coreSupportsSourceType(coreVersion) {
2074
+ return releaseTriple(coreVersion) !== null && !isBelowVersion(coreVersion, SOURCE_TYPE_MIN_CORE_VERSION);
2075
+ }
2021
2076
  const CLI_PACKAGE = "afterpack";
2022
2077
  function updateCommand(identity, minVersion) {
2023
2078
  const core = `${CORE_PACKAGE}@${safeVersionString(minVersion) ?? "latest"}`;
@@ -2694,6 +2749,7 @@ function buildEngineConfig(options) {
2694
2749
  if (options.complexity !== void 0) defaults.complexity = options.complexity;
2695
2750
  if (options.preset !== void 0) defaults.preset = options.preset;
2696
2751
  else if (options.complexity === void 0) defaults.preset = DEFAULT_PRESET;
2752
+ if (options.sourceType !== void 0) defaults.sourceType = options.sourceType;
2697
2753
  const config = mergeInto({
2698
2754
  ...defaults,
2699
2755
  sourceMap,
@@ -4235,11 +4291,14 @@ async function runObfuscationPass(options) {
4235
4291
  env,
4236
4292
  cwd
4237
4293
  });
4294
+ const localEngineVersion = await readEngineVersion(engine);
4295
+ const derivedSourceType = options.sourceType !== void 0 && coreSupportsSourceType(localEngineVersion ?? options.client?.coreVersion) ? options.sourceType : void 0;
4238
4296
  const engineConfig = buildEngineConfig({
4239
4297
  policy,
4240
4298
  seed,
4241
4299
  preset: options.preset,
4242
4300
  complexity: options.complexity,
4301
+ sourceType: derivedSourceType,
4243
4302
  regions: capture.regions,
4244
4303
  engine: options.engineConfig,
4245
4304
  renameGlobals: capture.renameGlobals
@@ -4277,7 +4336,7 @@ async function runObfuscationPass(options) {
4277
4336
  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."));
4278
4337
  const telemetry = options.telemetry;
4279
4338
  const telemetryEnabled = telemetry != null && resolveTelemetryEnabled(artifactOptions.telemetry?.enabled, env);
4280
- const engineVersion = (batch.source === "cloud" ? safeVersionString(batch.engineVersion) : null) ?? await readEngineVersion(engine);
4339
+ const engineVersion = (batch.source === "cloud" ? safeVersionString(batch.engineVersion) : null) ?? localEngineVersion;
4281
4340
  if (telemetry && telemetryEnabled) {
4282
4341
  const facts = {
4283
4342
  label,
@@ -4613,6 +4672,7 @@ exports.applyResolvedKey = applyResolvedKey;
4613
4672
  exports.collectBundleJs = collectBundleJs;
4614
4673
  exports.collectJsFiles = collectJsFiles;
4615
4674
  exports.collectSourceMaps = collectSourceMaps;
4675
+ exports.collectStylesheets = collectStylesheets;
4616
4676
  exports.createTelemetryReporter = createTelemetryReporter;
4617
4677
  exports.decodeDataUri = decodeDataUri;
4618
4678
  exports.discoverInputSourceMap = discoverInputSourceMap;
@@ -4636,11 +4696,15 @@ exports.sanitizeNotices = sanitizeNotices;
4636
4696
  exports.scanDirectives = scanDirectives;
4637
4697
  exports.serverAddsInfo = serverAddsInfo;
4638
4698
  exports.sha256Of = sha256Of;
4699
+ exports.sourceTypeForBundle = sourceTypeForBundle;
4700
+ exports.sourceTypeForOutputFormat = sourceTypeForOutputFormat;
4701
+ exports.stripBundleCssSourceMaps = stripBundleCssSourceMaps;
4639
4702
  exports.toEngineConfig = toEngineConfig;
4640
4703
  exports.toPluginOptions = toPluginOptions;
4641
4704
  exports.validateConfig = validateConfig;
4642
4705
  exports.verifyProtectionReceipt = verifyProtectionReceipt;
4643
4706
  exports.withSourceMappingURL = withSourceMappingURL;
4707
+ exports.withoutCssSourceMappingURL = withoutCssSourceMappingURL;
4644
4708
  exports.writeArtifacts = writeArtifacts;
4645
4709
  exports.writeDeferredProtectionReceipt = writeDeferredProtectionReceipt;
4646
4710
  exports.writeProtectionReceipt = writeProtectionReceipt;