unpeek 4.0.1 → 4.2.0

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.
Files changed (62) hide show
  1. package/README.md +21 -13
  2. package/README.tr.md +21 -13
  3. package/dist/adapters/esbuild.cjs +5 -5
  4. package/dist/adapters/esbuild.d.cts +1 -1
  5. package/dist/adapters/esbuild.d.ts +1 -1
  6. package/dist/adapters/esbuild.js +3 -3
  7. package/dist/adapters/next/adapter.cjs +6 -6
  8. package/dist/adapters/next/adapter.d.cts +1 -1
  9. package/dist/adapters/next/adapter.d.ts +1 -1
  10. package/dist/adapters/next/adapter.js +5 -5
  11. package/dist/adapters/next/index.cjs +6 -6
  12. package/dist/adapters/next/index.js +5 -5
  13. package/dist/adapters/rollup.cjs +5 -5
  14. package/dist/adapters/rollup.d.cts +1 -1
  15. package/dist/adapters/rollup.d.ts +1 -1
  16. package/dist/adapters/rollup.js +3 -3
  17. package/dist/adapters/rspack.cjs +5 -5
  18. package/dist/adapters/rspack.d.cts +1 -1
  19. package/dist/adapters/rspack.d.ts +1 -1
  20. package/dist/adapters/rspack.js +3 -3
  21. package/dist/adapters/vite.cjs +5 -5
  22. package/dist/adapters/vite.d.cts +1 -1
  23. package/dist/adapters/vite.d.ts +1 -1
  24. package/dist/adapters/vite.js +3 -3
  25. package/dist/adapters/webpack.cjs +5 -5
  26. package/dist/adapters/webpack.d.cts +1 -1
  27. package/dist/adapters/webpack.d.ts +1 -1
  28. package/dist/adapters/webpack.js +3 -3
  29. package/dist/browser.cjs +2 -2
  30. package/dist/browser.d.cts +7 -6
  31. package/dist/browser.d.ts +7 -6
  32. package/dist/browser.js +1 -1
  33. package/dist/{chunk-TYL32LUK.js → chunk-32GLSJAW.js} +91 -569
  34. package/dist/{chunk-W77DAC3H.js → chunk-6EWFL4LQ.js} +16 -0
  35. package/dist/{chunk-3GDHYBVH.cjs → chunk-AD6UFBPA.cjs} +96 -574
  36. package/dist/{chunk-XYN5NYSD.js → chunk-APQOBFRO.js} +21 -15
  37. package/dist/{chunk-LGTXAAZH.js → chunk-BL2UXZGD.js} +3155 -481
  38. package/dist/{chunk-X6EETCO6.cjs → chunk-BQ2O6HM5.cjs} +16 -0
  39. package/dist/{chunk-4G2HCME5.js → chunk-GCWXTWTN.js} +30 -13
  40. package/dist/{chunk-4SOS3LRV.js → chunk-K77WRITN.js} +6 -6
  41. package/dist/{chunk-7ZEVJ4OR.cjs → chunk-KIAYVIC5.cjs} +40 -34
  42. package/dist/{chunk-M46SFJE7.cjs → chunk-MSECP2P4.cjs} +3351 -677
  43. package/dist/{chunk-NNAAPDUS.cjs → chunk-SJK45WAU.cjs} +8 -8
  44. package/dist/{chunk-OTA75YI6.cjs → chunk-UUJLTW7O.cjs} +53 -36
  45. package/dist/cli/index.js +2808 -528
  46. package/dist/{config-Y6JwVGwX.d.cts → config-BFAZrfjQ.d.cts} +2 -0
  47. package/dist/{config-Y6JwVGwX.d.ts → config-BFAZrfjQ.d.ts} +2 -0
  48. package/dist/config.cjs +2 -2
  49. package/dist/config.d.cts +1 -1
  50. package/dist/config.d.ts +1 -1
  51. package/dist/config.js +1 -1
  52. package/dist/{index-COVHErnx.d.cts → index-Bo4S_VVM.d.cts} +1 -1
  53. package/dist/{index-0O1WSfVP.d.ts → index-CKdYVt_L.d.ts} +1 -1
  54. package/dist/index.cjs +171 -31
  55. package/dist/index.d.cts +6 -6
  56. package/dist/index.d.ts +6 -6
  57. package/dist/index.js +156 -16
  58. package/dist/plugins/unplugin.cjs +4 -4
  59. package/dist/plugins/unplugin.js +3 -3
  60. package/dist/{types-CMtZnV8C.d.ts → types-BDpFfokR.d.ts} +6 -3
  61. package/dist/{types-D93PuOOl.d.cts → types-WIoud53X.d.cts} +6 -3
  62. package/package.json +1 -1
@@ -57,9 +57,858 @@ function invertRivestPoly32(y, a0, a1Odd, a2Even, a3Even) {
57
57
  return x >>> 0;
58
58
  }
59
59
 
60
+ // src/core/vlq.ts
61
+ import crypto from "crypto";
62
+ import fs from "fs";
63
+ import path from "path";
64
+ var BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
65
+ var BASE64_MAP = /* @__PURE__ */ new Map();
66
+ for (let i = 0; i < BASE64_CHARS.length; i++) {
67
+ BASE64_MAP.set(BASE64_CHARS[i], i);
68
+ }
69
+ var VLQ_BASE_SHIFT = 5;
70
+ var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
71
+ var VLQ_BASE_MASK = VLQ_BASE - 1;
72
+ var VLQ_CONTINUATION_BIT = VLQ_BASE;
73
+ function encodeVlq(value) {
74
+ let vlq = value < 0 ? (-value << 1) + 1 : value << 1;
75
+ let encoded = "";
76
+ do {
77
+ let digit = vlq & VLQ_BASE_MASK;
78
+ vlq >>>= VLQ_BASE_SHIFT;
79
+ if (vlq > 0) {
80
+ digit |= VLQ_CONTINUATION_BIT;
81
+ }
82
+ encoded += BASE64_CHARS[digit];
83
+ } while (vlq > 0);
84
+ return encoded;
85
+ }
86
+ function decodeVlq(segment, startIndex) {
87
+ let result = 0;
88
+ let shift = 0;
89
+ let index = startIndex;
90
+ while (index < segment.length) {
91
+ const digit = BASE64_MAP.get(segment[index]);
92
+ if (digit === void 0) {
93
+ return null;
94
+ }
95
+ index++;
96
+ const continuation = (digit & VLQ_CONTINUATION_BIT) !== 0;
97
+ result += (digit & VLQ_BASE_MASK) << shift;
98
+ shift += VLQ_BASE_SHIFT;
99
+ if (!continuation) {
100
+ const isNegative = (result & 1) === 1;
101
+ const shifted = result >> 1;
102
+ return {
103
+ value: isNegative ? -shifted : shifted,
104
+ nextIndex: index
105
+ };
106
+ }
107
+ if (shift > 30) {
108
+ return null;
109
+ }
110
+ }
111
+ return null;
112
+ }
113
+ function decodeMappingsString(mappingsStr) {
114
+ const mappings = [];
115
+ let malformedCount = 0;
116
+ if (!mappingsStr) {
117
+ return { mappings, malformedCount };
118
+ }
119
+ let sourceIndex = 0;
120
+ let originalLine = 0;
121
+ let originalColumn = 0;
122
+ let nameIndex = 0;
123
+ const lines = mappingsStr.split(";");
124
+ for (let genLine = 0; genLine < lines.length; genLine++) {
125
+ const lineStr = lines[genLine];
126
+ if (!lineStr) continue;
127
+ let genCol = 0;
128
+ const segments = lineStr.split(",");
129
+ for (const seg of segments) {
130
+ if (!seg) continue;
131
+ const values = [];
132
+ let idx = 0;
133
+ let valid = true;
134
+ while (idx < seg.length) {
135
+ const decoded = decodeVlq(seg, idx);
136
+ if (!decoded) {
137
+ valid = false;
138
+ break;
139
+ }
140
+ values.push(decoded.value);
141
+ idx = decoded.nextIndex;
142
+ }
143
+ if (!valid || values.length !== 1 && values.length !== 4 && values.length !== 5) {
144
+ malformedCount++;
145
+ continue;
146
+ }
147
+ genCol += values[0];
148
+ if (values.length >= 4) {
149
+ sourceIndex += values[1];
150
+ originalLine += values[2];
151
+ originalColumn += values[3];
152
+ const mapping = {
153
+ generatedLine: genLine,
154
+ generatedColumn: genCol,
155
+ sourceIndex,
156
+ originalLine,
157
+ originalColumn
158
+ };
159
+ if (values.length === 5) {
160
+ nameIndex += values[4];
161
+ mapping.nameIndex = nameIndex;
162
+ }
163
+ mappings.push(mapping);
164
+ }
165
+ }
166
+ }
167
+ return { mappings, malformedCount };
168
+ }
169
+ function resolveSourceWithRoot(rawSource, sourceRoot) {
170
+ if (!sourceRoot || !rawSource || rawSource.startsWith(sourceRoot)) {
171
+ return rawSource;
172
+ }
173
+ return `${sourceRoot.replace(/\/$/, "")}/${rawSource.replace(/^\//, "")}`;
174
+ }
175
+ function flattenSourceMapSectionsWithStats(rawMap) {
176
+ if (!Array.isArray(rawMap.sections)) {
177
+ const normalized = {
178
+ version: rawMap.version ?? 3,
179
+ sources: Array.isArray(rawMap.sources) ? [...rawMap.sources] : [],
180
+ names: Array.isArray(rawMap.names) ? [...rawMap.names] : [],
181
+ mappings: typeof rawMap.mappings === "string" ? rawMap.mappings : ""
182
+ };
183
+ if (rawMap.file !== void 0) normalized.file = rawMap.file;
184
+ if (rawMap.sourceRoot !== void 0) normalized.sourceRoot = rawMap.sourceRoot;
185
+ if (Array.isArray(rawMap.sourcesContent)) {
186
+ normalized.sourcesContent = [...rawMap.sourcesContent];
187
+ }
188
+ const debugId2 = rawMap.debugId ?? rawMap.debug_id;
189
+ if (debugId2) normalized.debugId = debugId2;
190
+ return { map: normalized, malformedCount: 0 };
191
+ }
192
+ const mergedSources = [];
193
+ const mergedSourcesContent = [];
194
+ let hasAnySourcesContent = false;
195
+ const sourceIndexMap = /* @__PURE__ */ new Map();
196
+ const mergedNames = [];
197
+ const nameIndexMap = /* @__PURE__ */ new Map();
198
+ const mergedMappings = [];
199
+ let totalMalformed = 0;
200
+ const internSource = (src, content) => {
201
+ const existing = sourceIndexMap.get(src);
202
+ if (existing !== void 0) {
203
+ if (mergedSourcesContent[existing] === null && content !== void 0 && content !== null) {
204
+ mergedSourcesContent[existing] = content;
205
+ hasAnySourcesContent = true;
206
+ }
207
+ return existing;
208
+ }
209
+ const nextIdx = mergedSources.length;
210
+ mergedSources.push(src);
211
+ if (content !== void 0 && content !== null) {
212
+ hasAnySourcesContent = true;
213
+ }
214
+ mergedSourcesContent.push(content ?? null);
215
+ sourceIndexMap.set(src, nextIdx);
216
+ return nextIdx;
217
+ };
218
+ const internName = (name) => {
219
+ const existing = nameIndexMap.get(name);
220
+ if (existing !== void 0) return existing;
221
+ const nextIdx = mergedNames.length;
222
+ mergedNames.push(name);
223
+ nameIndexMap.set(name, nextIdx);
224
+ return nextIdx;
225
+ };
226
+ for (const section of rawMap.sections) {
227
+ if (!section || !section.map) continue;
228
+ const offLine = (section.offset?.line ?? 0) | 0;
229
+ const offCol = (section.offset?.column ?? 0) | 0;
230
+ const flatSecResult = flattenSourceMapSectionsWithStats(section.map);
231
+ const flatSec = flatSecResult.map;
232
+ totalMalformed += flatSecResult.malformedCount;
233
+ const decoded = decodeMappingsString(flatSec.mappings);
234
+ totalMalformed += decoded.malformedCount;
235
+ const secSources = flatSec.sources ?? [];
236
+ const secContents = flatSec.sourcesContent ?? [];
237
+ const secNames = flatSec.names ?? [];
238
+ const sourceRemap = /* @__PURE__ */ new Map();
239
+ for (let i = 0; i < secSources.length; i++) {
240
+ const fullSource = resolveSourceWithRoot(secSources[i], flatSec.sourceRoot);
241
+ sourceRemap.set(i, internSource(fullSource, secContents[i]));
242
+ }
243
+ const nameRemap = /* @__PURE__ */ new Map();
244
+ for (let i = 0; i < secNames.length; i++) {
245
+ nameRemap.set(i, internName(secNames[i]));
246
+ }
247
+ for (const m of decoded.mappings) {
248
+ const mappedSource = sourceRemap.get(m.sourceIndex);
249
+ if (mappedSource === void 0) continue;
250
+ const shifted = {
251
+ generatedLine: offLine + m.generatedLine,
252
+ generatedColumn: (m.generatedLine === 0 ? offCol : 0) + m.generatedColumn,
253
+ sourceIndex: mappedSource,
254
+ originalLine: m.originalLine,
255
+ originalColumn: m.originalColumn
256
+ };
257
+ if (m.nameIndex !== void 0) {
258
+ const mappedName = nameRemap.get(m.nameIndex);
259
+ if (mappedName !== void 0) {
260
+ shifted.nameIndex = mappedName;
261
+ }
262
+ }
263
+ mergedMappings.push(shifted);
264
+ }
265
+ }
266
+ mergedMappings.sort(
267
+ (a, b) => a.generatedLine !== b.generatedLine ? a.generatedLine - b.generatedLine : a.generatedColumn - b.generatedColumn
268
+ );
269
+ const flat = {
270
+ version: rawMap.version ?? 3,
271
+ sources: mergedSources,
272
+ names: mergedNames,
273
+ mappings: encodeMappings(mergedMappings)
274
+ };
275
+ if (rawMap.file !== void 0) flat.file = rawMap.file;
276
+ if (rawMap.sourceRoot !== void 0) flat.sourceRoot = rawMap.sourceRoot;
277
+ if (hasAnySourcesContent) flat.sourcesContent = mergedSourcesContent;
278
+ const debugId = rawMap.debugId ?? rawMap.debug_id;
279
+ if (debugId) flat.debugId = debugId;
280
+ return { map: flat, malformedCount: totalMalformed };
281
+ }
282
+ function flattenSourceMapSections(rawMap) {
283
+ return flattenSourceMapSectionsWithStats(rawMap).map;
284
+ }
285
+ function encodeMappings(decoded) {
286
+ if (decoded.length === 0) return "";
287
+ const sorted = [...decoded].sort(
288
+ (a, b) => a.generatedLine !== b.generatedLine ? a.generatedLine - b.generatedLine : a.generatedColumn - b.generatedColumn
289
+ );
290
+ const maxLine = sorted[sorted.length - 1].generatedLine;
291
+ const lineBuckets = Array.from({ length: maxLine + 1 }, () => []);
292
+ let prevSource = 0;
293
+ let prevOrigLine = 0;
294
+ let prevOrigCol = 0;
295
+ let prevName = 0;
296
+ let prevGenLine = -1;
297
+ let prevGenCol = 0;
298
+ for (const m of sorted) {
299
+ if (m.generatedLine !== prevGenLine) {
300
+ prevGenLine = m.generatedLine;
301
+ prevGenCol = 0;
302
+ }
303
+ let seg = encodeVlq(m.generatedColumn - prevGenCol) + encodeVlq(m.sourceIndex - prevSource) + encodeVlq(m.originalLine - prevOrigLine) + encodeVlq(m.originalColumn - prevOrigCol);
304
+ prevGenCol = m.generatedColumn;
305
+ prevSource = m.sourceIndex;
306
+ prevOrigLine = m.originalLine;
307
+ prevOrigCol = m.originalColumn;
308
+ if (m.nameIndex !== void 0) {
309
+ seg += encodeVlq(m.nameIndex - prevName);
310
+ prevName = m.nameIndex;
311
+ }
312
+ lineBuckets[m.generatedLine].push(seg);
313
+ }
314
+ return lineBuckets.map((segs) => segs.join(",")).join(";");
315
+ }
316
+ function ensureSortedMappings(mappings) {
317
+ for (let i = 1; i < mappings.length; i++) {
318
+ const prev = mappings[i - 1];
319
+ const curr = mappings[i];
320
+ if (curr.generatedLine < prev.generatedLine || curr.generatedLine === prev.generatedLine && curr.generatedColumn < prev.generatedColumn) {
321
+ return [...mappings].sort(
322
+ (a, b) => a.generatedLine !== b.generatedLine ? a.generatedLine - b.generatedLine : a.generatedColumn - b.generatedColumn
323
+ );
324
+ }
325
+ }
326
+ return mappings;
327
+ }
328
+ function findMappingAt(mappings, line0, col0) {
329
+ let lo = 0;
330
+ let hi = mappings.length - 1;
331
+ let best;
332
+ while (lo <= hi) {
333
+ const mid = lo + hi >> 1;
334
+ const m = mappings[mid];
335
+ if (m.generatedLine < line0 || m.generatedLine === line0 && m.generatedColumn <= col0) {
336
+ if (m.generatedLine === line0) {
337
+ best = m;
338
+ }
339
+ lo = mid + 1;
340
+ } else {
341
+ hi = mid - 1;
342
+ }
343
+ }
344
+ return best;
345
+ }
346
+ function shiftSourceMapLines(map, lineOffset) {
347
+ if (lineOffset <= 0 || !map.mappings) {
348
+ return map;
349
+ }
350
+ return {
351
+ ...map,
352
+ mappings: `${";".repeat(lineOffset)}${map.mappings}`
353
+ };
354
+ }
355
+ function computeDeterministicDebugId(code, mappings = "") {
356
+ const hash = crypto.createHash("sha256").update(code, "utf8");
357
+ if (mappings) {
358
+ hash.update("\0", "utf8").update(mappings, "utf8");
359
+ }
360
+ const bytes = hash.digest();
361
+ bytes[6] = bytes[6] & 15 | 64;
362
+ bytes[8] = bytes[8] & 63 | 128;
363
+ const hex = bytes.subarray(0, 16).toString("hex");
364
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
365
+ }
366
+ function chainSourceMaps(mapB, mapA) {
367
+ const flatB = flattenSourceMapSections(mapB);
368
+ const flatA = flattenSourceMapSections(mapA);
369
+ const decodedB = ensureSortedMappings(decodeMappingsString(flatB.mappings).mappings);
370
+ const decodedA = ensureSortedMappings(decodeMappingsString(flatA.mappings).mappings);
371
+ const chained = [];
372
+ for (const mB of decodedB) {
373
+ const mA = findMappingAt(decodedA, mB.originalLine, mB.originalColumn);
374
+ if (mA) {
375
+ chained.push({
376
+ generatedLine: mB.generatedLine,
377
+ generatedColumn: mB.generatedColumn,
378
+ sourceIndex: mA.sourceIndex,
379
+ originalLine: mA.originalLine,
380
+ originalColumn: mA.originalColumn,
381
+ nameIndex: mA.nameIndex
382
+ });
383
+ }
384
+ }
385
+ const debugId = flatA.debugId ?? flatA.debug_id ?? flatB.debugId ?? flatB.debug_id;
386
+ const result = {
387
+ version: 3,
388
+ file: flatB.file ?? flatA.file,
389
+ sourceRoot: flatA.sourceRoot,
390
+ sources: [...flatA.sources],
391
+ sourcesContent: flatA.sourcesContent ? [...flatA.sourcesContent] : void 0,
392
+ names: [...flatA.names],
393
+ mappings: encodeMappings(chained)
394
+ };
395
+ if (debugId) {
396
+ result.debugId = debugId;
397
+ }
398
+ return result;
399
+ }
400
+ function resolvePosition(map, line1Based, column1Based) {
401
+ const { map: flatMap, malformedCount: flattenMalformed } = flattenSourceMapSectionsWithStats(map);
402
+ const { mappings, malformedCount: decodeMalformed } = decodeMappingsString(flatMap.mappings);
403
+ const malformedCount = flattenMalformed + decodeMalformed;
404
+ const sortedMappings = ensureSortedMappings(mappings);
405
+ const match = findMappingAt(
406
+ sortedMappings,
407
+ Math.max(0, line1Based - 1),
408
+ Math.max(0, column1Based - 1)
409
+ );
410
+ if (!match) {
411
+ return { malformedCount };
412
+ }
413
+ const rawSource = flatMap.sources[match.sourceIndex];
414
+ const source = resolveSourceWithRoot(rawSource, flatMap.sourceRoot);
415
+ return {
416
+ source,
417
+ line: match.originalLine + 1,
418
+ column: match.originalColumn + 1,
419
+ name: match.nameIndex !== void 0 ? flatMap.names[match.nameIndex] : void 0,
420
+ malformedCount
421
+ };
422
+ }
423
+ function safeDecodeURIComponent(input) {
424
+ try {
425
+ return decodeURIComponent(input);
426
+ } catch {
427
+ return input.replace(/%[0-9A-Fa-f]{2}/g, (seq) => {
428
+ try {
429
+ return decodeURIComponent(seq);
430
+ } catch {
431
+ return seq;
432
+ }
433
+ });
434
+ }
435
+ }
436
+ function collectMapFiles(mapsDir) {
437
+ if (!fs.existsSync(mapsDir)) return [];
438
+ const results = [];
439
+ const walk9 = (dir) => {
440
+ let entries;
441
+ try {
442
+ entries = fs.readdirSync(dir, { withFileTypes: true });
443
+ } catch {
444
+ return;
445
+ }
446
+ for (const entry of entries) {
447
+ const fullPath = path.join(dir, entry.name);
448
+ if (entry.isDirectory()) {
449
+ walk9(fullPath);
450
+ } else if (entry.isFile() && entry.name.endsWith(".map")) {
451
+ results.push(fullPath);
452
+ }
453
+ }
454
+ };
455
+ walk9(mapsDir);
456
+ return results;
457
+ }
458
+ function normalizeFileRefCandidates(fileRef) {
459
+ let cleanRef = fileRef.trim();
460
+ try {
461
+ if (/^(?:https?|file):\/\//i.test(cleanRef)) {
462
+ cleanRef = new URL(cleanRef).pathname;
463
+ }
464
+ } catch {
465
+ }
466
+ cleanRef = cleanRef.split("?")[0].split("#")[0].replace(/\\/g, "/");
467
+ cleanRef = cleanRef.replace(/^\/+([A-Za-z]:\/)/, "$1").replace(/^\/+/, "");
468
+ const decodedRef = safeDecodeURIComponent(cleanRef).replace(/\\/g, "/").replace(/^\/+/, "");
469
+ const variants = /* @__PURE__ */ new Set();
470
+ for (const raw of [decodedRef, cleanRef]) {
471
+ if (!raw) continue;
472
+ variants.add(raw);
473
+ const withoutDrive = raw.replace(/^[A-Za-z]:\//, "");
474
+ variants.add(withoutDrive);
475
+ for (const v of [raw, withoutDrive]) {
476
+ const nextStripped = v.replace(
477
+ /^(?:.*\/)?(?:_next\/static\/chunks\/|_next\/static\/|_next\/|static\/chunks\/|static\/)/,
478
+ ""
479
+ );
480
+ if (nextStripped) variants.add(nextStripped);
481
+ const chunksIdx = v.indexOf("/chunks/");
482
+ if (chunksIdx !== -1) {
483
+ variants.add(v.slice(chunksIdx + "/chunks/".length));
484
+ }
485
+ }
486
+ }
487
+ return Array.from(variants).filter(Boolean);
488
+ }
489
+ function findMatchingMapFile(fileRef, mapsDir, allMaps) {
490
+ const candidates = normalizeFileRefCandidates(fileRef);
491
+ for (const cand of candidates) {
492
+ const exactCandidate = path.join(mapsDir, `${cand}.map`);
493
+ if (fs.existsSync(exactCandidate)) {
494
+ return exactCandidate;
495
+ }
496
+ }
497
+ for (const mapPath of allMaps) {
498
+ const relRaw = path.relative(mapsDir, mapPath).replace(/\\/g, "/");
499
+ const relDecoded = safeDecodeURIComponent(relRaw);
500
+ for (const rel of [relDecoded, relRaw]) {
501
+ const relNoMap = rel.slice(0, -4);
502
+ for (const cand of candidates) {
503
+ if (rel === `${cand}.map` || rel.endsWith(`/${cand}.map`) || cand.endsWith(`/${relNoMap}`) || cand === relNoMap) {
504
+ return mapPath;
505
+ }
506
+ }
507
+ }
508
+ }
509
+ const baseNames = new Set(candidates.map((c) => `${path.posix.basename(c)}.map`));
510
+ return allMaps.find((m) => {
511
+ const base2 = path.basename(m);
512
+ return baseNames.has(base2) || baseNames.has(safeDecodeURIComponent(base2));
513
+ });
514
+ }
515
+ var V8_PARENS_FRAME_REGEX = /^\s*at\s+(?:.+?\s+\()(.+):(\d+):(\d+)\)\s*$/;
516
+ var V8_BARE_FRAME_REGEX = /^\s*at\s+(.+?):(\d+):(\d+)\s*$/;
517
+ var FIREFOX_FRAME_REGEX = /^[^@]*@(.+?):(\d+):(\d+)\s*$/;
518
+ var STACK_FRAME_REGEX = /(?:at\s+(?:[^(]+\s+\()?|\@)([^\s()]+?):(\d+):(\d+)\)?/;
519
+ function parseStackFrame(rawLine) {
520
+ const match = rawLine.match(V8_PARENS_FRAME_REGEX) ?? rawLine.match(V8_BARE_FRAME_REGEX) ?? rawLine.match(FIREFOX_FRAME_REGEX) ?? rawLine.match(STACK_FRAME_REGEX);
521
+ if (!match) {
522
+ return null;
523
+ }
524
+ return {
525
+ fileRef: match[1],
526
+ lineNum: Number(match[2]),
527
+ colNum: Number(match[3])
528
+ };
529
+ }
530
+ async function symbolicateStackTrace(options) {
531
+ const cwd = path.resolve(options.cwd ?? process.cwd());
532
+ const mapsDir = path.resolve(cwd, options.mapsDir ?? ".unpeek-maps");
533
+ const allMaps = collectMapFiles(mapsDir);
534
+ const warnings = [];
535
+ const mapCache = /* @__PURE__ */ new Map();
536
+ if (allMaps.length === 0) {
537
+ warnings.push(`No .map files found in "${mapsDir}".`);
538
+ }
539
+ const lines = options.stackTrace.split(/\r?\n/);
540
+ const frames = [];
541
+ const outputLines = [];
542
+ for (const rawLine of lines) {
543
+ const parsedFrame = parseStackFrame(rawLine);
544
+ if (!parsedFrame) {
545
+ frames.push({ raw: rawLine, resolved: false });
546
+ outputLines.push(rawLine);
547
+ continue;
548
+ }
549
+ const { fileRef, lineNum, colNum } = parsedFrame;
550
+ const normalizedFrameFile = safeDecodeURIComponent(fileRef).replace(/\\/g, "/");
551
+ const mapPath = findMatchingMapFile(fileRef, mapsDir, allMaps);
552
+ if (!mapPath) {
553
+ frames.push({
554
+ raw: rawLine,
555
+ file: normalizedFrameFile,
556
+ line: lineNum,
557
+ column: colNum,
558
+ resolved: false
559
+ });
560
+ outputLines.push(rawLine);
561
+ continue;
562
+ }
563
+ let parsedMap = mapCache.get(mapPath);
564
+ if (parsedMap === void 0) {
565
+ try {
566
+ const rawJson = JSON.parse(fs.readFileSync(mapPath, "utf8"));
567
+ parsedMap = Array.isArray(rawJson?.sections) ? flattenSourceMapSections(rawJson) : rawJson;
568
+ } catch {
569
+ parsedMap = null;
570
+ warnings.push(`Failed to parse source map "${mapPath}".`);
571
+ }
572
+ mapCache.set(mapPath, parsedMap);
573
+ }
574
+ if (!parsedMap || typeof parsedMap.mappings !== "string" || !Array.isArray(parsedMap.sources)) {
575
+ frames.push({
576
+ raw: rawLine,
577
+ file: normalizedFrameFile,
578
+ line: lineNum,
579
+ column: colNum,
580
+ resolved: false
581
+ });
582
+ outputLines.push(rawLine);
583
+ continue;
584
+ }
585
+ const pos = resolvePosition(parsedMap, lineNum, colNum);
586
+ if (pos.malformedCount > 0) {
587
+ warnings.push(`Skipped ${pos.malformedCount} malformed VLQ segment(s) in "${path.basename(mapPath)}".`);
588
+ }
589
+ if (!pos.source || pos.line === void 0 || pos.column === void 0) {
590
+ frames.push({
591
+ raw: rawLine,
592
+ file: normalizedFrameFile,
593
+ line: lineNum,
594
+ column: colNum,
595
+ resolved: false
596
+ });
597
+ outputLines.push(rawLine);
598
+ continue;
599
+ }
600
+ frames.push({
601
+ raw: rawLine,
602
+ file: normalizedFrameFile,
603
+ line: lineNum,
604
+ column: colNum,
605
+ originalSource: pos.source,
606
+ originalLine: pos.line,
607
+ originalColumn: pos.column,
608
+ originalName: pos.name,
609
+ resolved: true
610
+ });
611
+ const fnPrefix = pos.name ? `${pos.name} ` : "";
612
+ outputLines.push(` at ${fnPrefix}(${pos.source}:${pos.line}:${pos.column})`);
613
+ }
614
+ return {
615
+ stackTrace: outputLines.join("\n"),
616
+ frames,
617
+ warnings: Array.from(new Set(warnings))
618
+ };
619
+ }
620
+
60
621
  // src/ast/hot-path-detector.ts
61
622
  import * as acorn from "acorn";
62
623
  import * as walk from "acorn-walk";
624
+
625
+ // src/ast/sourcemap-critical.ts
626
+ function contentMightMatchInclude(content, rawPatterns) {
627
+ for (const pat of rawPatterns) {
628
+ if (typeof pat === "string" && pat.length > 0) {
629
+ if (content.includes(pat)) return true;
630
+ try {
631
+ const stripped = pat.replace(/^\^|\$$/g, "");
632
+ if (stripped && new RegExp(stripped).test(content)) return true;
633
+ } catch {
634
+ }
635
+ } else if (pat instanceof RegExp) {
636
+ try {
637
+ const stripped = pat.source.replace(/^\^|\$$/g, "");
638
+ const flags = pat.flags.replace(/[gy]/g, "");
639
+ if (new RegExp(stripped, flags).test(content)) return true;
640
+ } catch {
641
+ return true;
642
+ }
643
+ }
644
+ }
645
+ return false;
646
+ }
647
+ function mightContainCriticalMatches(rawMap, options) {
648
+ if (!rawMap || typeof rawMap !== "object") return false;
649
+ if (Array.isArray(rawMap.sections)) {
650
+ return rawMap.sections.some(
651
+ (sec) => sec?.map && mightContainCriticalMatches(sec.map, options)
652
+ );
653
+ }
654
+ if (options.criticalIncludeMatchers.length > 0 && Array.isArray(rawMap.names) && rawMap.names.some(
655
+ (n) => typeof n === "string" && options.criticalIncludeMatchers.some((match) => match(n))
656
+ )) {
657
+ return true;
658
+ }
659
+ if (Array.isArray(rawMap.sourcesContent)) {
660
+ for (const content of rawMap.sourcesContent) {
661
+ if (typeof content !== "string" || content.length === 0) continue;
662
+ if (content.includes(options.criticalAnnotation)) return true;
663
+ if (options.rawIncludePatterns.length > 0 && contentMightMatchInclude(content, options.rawIncludePatterns)) {
664
+ return true;
665
+ }
666
+ }
667
+ }
668
+ return false;
669
+ }
670
+ function decodeMappingsByLine(mappingsStr, maxGenLine) {
671
+ const byLine = /* @__PURE__ */ new Map();
672
+ if (!mappingsStr || maxGenLine < 0) return byLine;
673
+ let sourceIndex = 0;
674
+ let originalLine = 0;
675
+ let originalColumn = 0;
676
+ let nameIndex = 0;
677
+ let genLine = 0;
678
+ let pos = 0;
679
+ const len = mappingsStr.length;
680
+ while (pos <= len && genLine <= maxGenLine) {
681
+ let semi = mappingsStr.indexOf(";", pos);
682
+ if (semi === -1) semi = len;
683
+ if (semi > pos) {
684
+ const lineStr = mappingsStr.slice(pos, semi);
685
+ let genCol = 0;
686
+ const lineSegs = [];
687
+ const segments = lineStr.split(",");
688
+ for (const seg of segments) {
689
+ if (!seg) continue;
690
+ const values = [];
691
+ let idx = 0;
692
+ let valid = true;
693
+ while (idx < seg.length) {
694
+ const decoded = decodeVlq(seg, idx);
695
+ if (!decoded) {
696
+ valid = false;
697
+ break;
698
+ }
699
+ values.push(decoded.value);
700
+ idx = decoded.nextIndex;
701
+ }
702
+ if (!valid || values.length !== 1 && values.length !== 4 && values.length !== 5) {
703
+ continue;
704
+ }
705
+ genCol += values[0];
706
+ if (values.length >= 4) {
707
+ sourceIndex += values[1];
708
+ originalLine += values[2];
709
+ originalColumn += values[3];
710
+ const mapping = {
711
+ generatedLine: genLine,
712
+ generatedColumn: genCol,
713
+ sourceIndex,
714
+ originalLine,
715
+ originalColumn
716
+ };
717
+ if (values.length === 5) {
718
+ nameIndex += values[4];
719
+ mapping.nameIndex = nameIndex;
720
+ }
721
+ lineSegs.push(mapping);
722
+ }
723
+ }
724
+ if (lineSegs.length > 0) {
725
+ for (let i = 1; i < lineSegs.length; i++) {
726
+ if (lineSegs[i].generatedColumn < lineSegs[i - 1].generatedColumn) {
727
+ lineSegs.sort((a, b) => a.generatedColumn - b.generatedColumn);
728
+ break;
729
+ }
730
+ }
731
+ byLine.set(genLine, lineSegs);
732
+ }
733
+ }
734
+ if (semi === len) break;
735
+ pos = semi + 1;
736
+ genLine++;
737
+ }
738
+ return byLine;
739
+ }
740
+ function findNearestSegmentOnLine(lineSegs, genCol, maxForwardCol) {
741
+ if (!lineSegs || lineSegs.length === 0) return void 0;
742
+ let lo = 0;
743
+ let hi = lineSegs.length - 1;
744
+ let best;
745
+ while (lo <= hi) {
746
+ const mid = lo + hi >> 1;
747
+ const m = lineSegs[mid];
748
+ if (m.generatedColumn <= genCol) {
749
+ best = m;
750
+ lo = mid + 1;
751
+ } else {
752
+ hi = mid - 1;
753
+ }
754
+ }
755
+ if (best) return best;
756
+ const first = lineSegs[0];
757
+ if (maxForwardCol === void 0 || first.generatedColumn <= maxForwardCol) {
758
+ return first;
759
+ }
760
+ return void 0;
761
+ }
762
+ function hasCriticalAnnotationNearLine(lines, origLine, annotation) {
763
+ if (origLine < 0 || origLine >= lines.length) return false;
764
+ if (lines[origLine].includes(annotation)) return true;
765
+ const minLine = Math.max(0, origLine - 5);
766
+ let inBlockComment = false;
767
+ for (let l = origLine - 1; l >= minLine; l--) {
768
+ const line = lines[l];
769
+ if (line.includes(annotation)) return true;
770
+ const trimmed = line.trim();
771
+ if (!inBlockComment && trimmed.endsWith("*/") && !trimmed.includes("/*")) {
772
+ inBlockComment = true;
773
+ continue;
774
+ }
775
+ if (inBlockComment) {
776
+ if (trimmed.includes("/*")) {
777
+ inBlockComment = false;
778
+ }
779
+ continue;
780
+ }
781
+ if (trimmed === "" || trimmed.startsWith("//") || trimmed.startsWith("/*") && trimmed.endsWith("*/")) {
782
+ continue;
783
+ }
784
+ break;
785
+ }
786
+ return false;
787
+ }
788
+ var IDENT_CHAR_RE = /[A-Za-z0-9_$]/;
789
+ var DECL_IDENT_RES = [
790
+ /\bfunction\s*\*?\s*([A-Za-z_$][A-Za-z0-9_$]*)/g,
791
+ /\b(?:const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=/g,
792
+ /([A-Za-z_$][A-Za-z0-9_$]*)\s*[:=]\s*(?:async\s+)?(?:function\b|\()/g
793
+ ];
794
+ function hasCriticalNameOnSourceLine(line, origCol, matchers) {
795
+ if (!line || matchers.length === 0) return false;
796
+ if (origCol >= 0 && origCol < line.length) {
797
+ let start = origCol;
798
+ while (start > 0 && IDENT_CHAR_RE.test(line[start - 1])) start--;
799
+ let end = origCol;
800
+ while (end < line.length && IDENT_CHAR_RE.test(line[end])) end++;
801
+ if (end > start) {
802
+ const token = line.slice(start, end);
803
+ if (matchers.some((m) => m(token))) return true;
804
+ }
805
+ }
806
+ for (const re of DECL_IDENT_RES) {
807
+ re.lastIndex = 0;
808
+ let m;
809
+ while ((m = re.exec(line)) !== null) {
810
+ if (m[1] && matchers.some((match) => match(m[1]))) {
811
+ return true;
812
+ }
813
+ }
814
+ }
815
+ return false;
816
+ }
817
+ function resolveSourceMapCriticalNodes(functions, originalSourceMap, options) {
818
+ const matched = /* @__PURE__ */ new Set();
819
+ if (!originalSourceMap || functions.length === 0) {
820
+ return matched;
821
+ }
822
+ if (!mightContainCriticalMatches(originalSourceMap, options)) {
823
+ return matched;
824
+ }
825
+ const flatMap = flattenSourceMapSections(originalSourceMap);
826
+ if (!flatMap.mappings) {
827
+ return matched;
828
+ }
829
+ let maxGenLine = -1;
830
+ for (const fn of functions) {
831
+ const nLine = fn.node.loc?.start?.line;
832
+ if (typeof nLine === "number") {
833
+ maxGenLine = Math.max(maxGenLine, nLine - 1);
834
+ }
835
+ const idLine = fn.idNode?.loc?.start?.line;
836
+ if (typeof idLine === "number") {
837
+ maxGenLine = Math.max(maxGenLine, idLine - 1);
838
+ }
839
+ }
840
+ if (maxGenLine < 0) {
841
+ return matched;
842
+ }
843
+ const lineMappings = decodeMappingsByLine(flatMap.mappings, maxGenLine);
844
+ if (lineMappings.size === 0) {
845
+ return matched;
846
+ }
847
+ const linesCache = /* @__PURE__ */ new Map();
848
+ const getSourceLines = (sourceIdx) => {
849
+ if (linesCache.has(sourceIdx)) return linesCache.get(sourceIdx);
850
+ const content = flatMap.sourcesContent?.[sourceIdx];
851
+ if (typeof content !== "string") return void 0;
852
+ const split = content.split(/\r?\n/);
853
+ linesCache.set(sourceIdx, split);
854
+ return split;
855
+ };
856
+ const segmentIsCritical = (seg) => {
857
+ if (seg.nameIndex !== void 0 && options.criticalIncludeMatchers.length > 0) {
858
+ const mappedName = flatMap.names[seg.nameIndex];
859
+ if (typeof mappedName === "string" && options.criticalIncludeMatchers.some((m) => m(mappedName))) {
860
+ return true;
861
+ }
862
+ }
863
+ const lines = getSourceLines(seg.sourceIndex);
864
+ if (!lines) return false;
865
+ if (hasCriticalAnnotationNearLine(
866
+ lines,
867
+ seg.originalLine,
868
+ options.criticalAnnotation
869
+ )) {
870
+ return true;
871
+ }
872
+ if (options.criticalIncludeMatchers.length > 0 && seg.originalLine >= 0 && seg.originalLine < lines.length && hasCriticalNameOnSourceLine(
873
+ lines[seg.originalLine],
874
+ seg.originalColumn,
875
+ options.criticalIncludeMatchers
876
+ )) {
877
+ return true;
878
+ }
879
+ return false;
880
+ };
881
+ for (const fn of functions) {
882
+ const candidates = [];
883
+ const idLoc = fn.idNode?.loc?.start;
884
+ if (idLoc) {
885
+ const seg = findNearestSegmentOnLine(
886
+ lineMappings.get(idLoc.line - 1),
887
+ idLoc.column
888
+ );
889
+ if (seg) candidates.push(seg);
890
+ }
891
+ const nodeStart = fn.node.loc?.start;
892
+ if (nodeStart) {
893
+ const nodeEnd = fn.node.loc?.end;
894
+ const maxForwardCol = nodeEnd && nodeEnd.line === nodeStart.line ? nodeEnd.column : void 0;
895
+ const seg = findNearestSegmentOnLine(
896
+ lineMappings.get(nodeStart.line - 1),
897
+ nodeStart.column,
898
+ maxForwardCol
899
+ );
900
+ if (seg && !candidates.includes(seg)) {
901
+ candidates.push(seg);
902
+ }
903
+ }
904
+ if (candidates.some(segmentIsCritical)) {
905
+ matched.add(fn.node);
906
+ }
907
+ }
908
+ return matched;
909
+ }
910
+
911
+ // src/ast/hot-path-detector.ts
63
912
  var ARRAY_HOF_METHODS = /* @__PURE__ */ new Set([
64
913
  "map",
65
914
  "filter",
@@ -100,6 +949,16 @@ var DEFAULT_EVENT_HANDLER_REGEX = /^(?:on|handle)(?!Tick|Render|Update|Frame|Ani
100
949
  var CRITICAL_COLD_HANDLER_REGEX = /^(?:onSubmit|handleSubmit|submit[A-Z0-9_]*|validate[A-Z0-9_]*|login|signIn|register|checkout)$/i;
101
950
  var CRITICAL_COLD_CALLEE_REGEX = /^(?:onSubmit|handleSubmit|submit[A-Z0-9_]*|validate[A-Z0-9_]*|login|signIn|register|checkout|createServerReference|fetch)$/i;
102
951
  var DEFAULT_HOOK_REGEX = /^use[A-Z0-9]/;
952
+ var JSX_FACTORY_CALLS = /* @__PURE__ */ new Set([
953
+ "jsx",
954
+ "jsxs",
955
+ "_jsx",
956
+ "_jsxs",
957
+ "jsxDEV",
958
+ "_jsxDEV",
959
+ "createElement",
960
+ "cloneElement"
961
+ ]);
103
962
  var REACT_HOOK_OR_RENDER_CALLS = /* @__PURE__ */ new Set([
104
963
  "useState",
105
964
  "useEffect",
@@ -114,7 +973,10 @@ var REACT_HOOK_OR_RENDER_CALLS = /* @__PURE__ */ new Set([
114
973
  "jsxs",
115
974
  "_jsx",
116
975
  "_jsxs",
117
- "createElement"
976
+ "jsxDEV",
977
+ "_jsxDEV",
978
+ "createElement",
979
+ "cloneElement"
118
980
  ]);
119
981
  var FUNCTION_NODE_TYPES = /* @__PURE__ */ new Set([
120
982
  "FunctionDeclaration",
@@ -156,9 +1018,16 @@ function parseJavaScriptAst(code, comments, opts) {
156
1018
  }
157
1019
  return ast;
158
1020
  }
159
- function isHocCall(callNode, hocWrappers) {
160
- if (!callNode || callNode.type !== "CallExpression") return false;
161
- const callee = callNode.callee;
1021
+ function unwrapCallee(callee) {
1022
+ let cur = callee;
1023
+ while (cur?.type === "SequenceExpression" && Array.isArray(cur.expressions) && cur.expressions.length > 0) {
1024
+ cur = cur.expressions[cur.expressions.length - 1];
1025
+ }
1026
+ return cur;
1027
+ }
1028
+ function isHocCall(callNode, hocWrappers, depth = 0) {
1029
+ if (!callNode || callNode.type !== "CallExpression" || depth > 4) return false;
1030
+ const callee = unwrapCallee(callNode.callee);
162
1031
  if (!callee) return false;
163
1032
  const wrappers = hocWrappers ?? DEFAULT_HOC_WRAPPERS;
164
1033
  if (callee.type === "Identifier") {
@@ -171,6 +1040,9 @@ function isHocCall(callNode, hocWrappers) {
171
1040
  if (wrappers.has(full2)) return true;
172
1041
  }
173
1042
  }
1043
+ if (callee.type === "CallExpression") {
1044
+ return isHocCall(callee, wrappers, depth + 1);
1045
+ }
174
1046
  return false;
175
1047
  }
176
1048
  function getFunctionLabel(node, ancestors, hocWrappers) {
@@ -220,8 +1092,73 @@ function getFunctionLabel(node, ancestors, hocWrappers) {
220
1092
  }
221
1093
  return `anonymous_${node.start}`;
222
1094
  }
223
- function isPascalCaseComponent(name) {
224
- return /^[A-Z][a-zA-Z0-9]*$/.test(name);
1095
+ function hasUiComponentSignal(node, ancestors, hocWrappers, isHookFn) {
1096
+ if (!node) return false;
1097
+ for (let i = ancestors.length - 2; i >= 0; i--) {
1098
+ const anc = ancestors[i];
1099
+ if (anc.type === "CallExpression") {
1100
+ if (isHocCall(anc, hocWrappers)) {
1101
+ return true;
1102
+ }
1103
+ } else {
1104
+ break;
1105
+ }
1106
+ }
1107
+ if (!node.body) return false;
1108
+ const stack = [node.body];
1109
+ while (stack.length > 0) {
1110
+ const cur = stack.pop();
1111
+ if (!cur || typeof cur !== "object") continue;
1112
+ if (cur.type === "JSXElement" || cur.type === "JSXFragment") {
1113
+ return true;
1114
+ }
1115
+ if (cur.type === "CallExpression") {
1116
+ const callee = unwrapCallee(cur.callee);
1117
+ let calleeName = "";
1118
+ let memberProp = "";
1119
+ let qualifiedCall = "";
1120
+ if (callee?.type === "Identifier") {
1121
+ calleeName = callee.name;
1122
+ qualifiedCall = calleeName;
1123
+ } else if (callee?.type === "MemberExpression" && !callee.computed && callee.property?.type === "Identifier") {
1124
+ memberProp = callee.property.name;
1125
+ if (callee.object?.type === "Identifier") {
1126
+ qualifiedCall = `${callee.object.name}.${memberProp}`;
1127
+ }
1128
+ }
1129
+ if (JSX_FACTORY_CALLS.has(calleeName) || JSX_FACTORY_CALLS.has(memberProp) || qualifiedCall === "React.createElement" || qualifiedCall === "React.cloneElement" || REACT_HOOK_OR_RENDER_CALLS.has(calleeName) || REACT_HOOK_OR_RENDER_CALLS.has(memberProp) || isHookFn(calleeName) || isHookFn(memberProp)) {
1130
+ return true;
1131
+ }
1132
+ if (calleeName === "h" && Array.isArray(cur.arguments) && (cur.arguments.length >= 2 || cur.arguments.length === 1 && cur.arguments[0]?.type === "Literal" && typeof cur.arguments[0].value === "string")) {
1133
+ return true;
1134
+ }
1135
+ }
1136
+ for (const key of Object.keys(cur)) {
1137
+ if (key === "loc" || key === "start" || key === "end") continue;
1138
+ const val = cur[key];
1139
+ if (Array.isArray(val)) {
1140
+ for (let i = val.length - 1; i >= 0; i--) {
1141
+ const item = val[i];
1142
+ if (item && typeof item === "object" && typeof item.type === "string" && !FUNCTION_NODE_TYPES.has(item.type)) {
1143
+ stack.push(item);
1144
+ }
1145
+ }
1146
+ } else if (val && typeof val === "object" && typeof val.type === "string" && !FUNCTION_NODE_TYPES.has(val.type)) {
1147
+ stack.push(val);
1148
+ }
1149
+ }
1150
+ }
1151
+ return false;
1152
+ }
1153
+ function isPascalCaseComponent(name, node, ancestors, hocWrappers, isHookFn) {
1154
+ if (!/^[A-Z][a-zA-Z0-9]*$/.test(name)) return false;
1155
+ if (!node || !ancestors) return false;
1156
+ return hasUiComponentSignal(
1157
+ node,
1158
+ ancestors,
1159
+ hocWrappers ?? DEFAULT_HOC_WRAPPERS,
1160
+ isHookFn ?? ((n) => DEFAULT_HOOK_REGEX.test(n))
1161
+ );
225
1162
  }
226
1163
  function isEventHandlerName(name, regex = DEFAULT_EVENT_HANDLER_REGEX) {
227
1164
  return regex.test(name);
@@ -300,7 +1237,7 @@ function containsLoopOrAnimation(fnNode, animationCalls = ANIMATION_FRAME_CALLS)
300
1237
  });
301
1238
  return found;
302
1239
  }
303
- function analyzeAstHotPaths(ast, config) {
1240
+ function analyzeAstHotPaths(ast, config, originalSourceMap) {
304
1241
  const hotFunctionNodes = /* @__PURE__ */ new WeakSet();
305
1242
  const coldFunctionNodes = /* @__PURE__ */ new WeakSet();
306
1243
  const hotExemptNodes = /* @__PURE__ */ new WeakSet();
@@ -442,9 +1379,50 @@ function analyzeAstHotPaths(ast, config) {
442
1379
  }
443
1380
  return anchorStart;
444
1381
  }
1382
+ function getFunctionIdNode(node, ancestors) {
1383
+ if (node.id) return node.id;
1384
+ const parent = ancestors[ancestors.length - 2];
1385
+ if (!parent) return null;
1386
+ if (parent.type === "VariableDeclarator" && parent.id?.type === "Identifier") {
1387
+ return parent.id;
1388
+ }
1389
+ if (parent.type === "AssignmentExpression" && parent.left?.type === "Identifier") {
1390
+ return parent.left;
1391
+ }
1392
+ if ((parent.type === "Property" || parent.type === "MethodDefinition") && parent.key?.type === "Identifier") {
1393
+ return parent.key;
1394
+ }
1395
+ if (parent.type === "CallExpression") {
1396
+ let idx = ancestors.length - 2;
1397
+ let matchedHoc = false;
1398
+ while (idx >= 0 && ancestors[idx].type === "CallExpression") {
1399
+ if (isHocCall(ancestors[idx], hocWrappers)) {
1400
+ matchedHoc = true;
1401
+ idx--;
1402
+ } else {
1403
+ break;
1404
+ }
1405
+ }
1406
+ if (matchedHoc && idx >= 0) {
1407
+ const outer = ancestors[idx];
1408
+ if (outer.type === "VariableDeclarator" && outer.id?.type === "Identifier") {
1409
+ return outer.id;
1410
+ }
1411
+ if (outer.type === "AssignmentExpression" && outer.left?.type === "Identifier") {
1412
+ return outer.left;
1413
+ }
1414
+ }
1415
+ }
1416
+ return null;
1417
+ }
445
1418
  function registerFunctionNode(node, ancestors) {
446
1419
  const name = getFunctionLabel(node, ancestors, hocWrappers);
447
- allFunctions.push({ node, name, anchorStart: computeFunctionAnchorStart(node, ancestors) });
1420
+ allFunctions.push({
1421
+ node,
1422
+ name,
1423
+ anchorStart: computeFunctionAnchorStart(node, ancestors),
1424
+ idNode: getFunctionIdNode(node, ancestors)
1425
+ });
448
1426
  fnByName.set(name, node);
449
1427
  const paramSet = /* @__PURE__ */ new Set();
450
1428
  for (const p of node.params || []) {
@@ -493,7 +1471,8 @@ function analyzeAstHotPaths(ast, config) {
493
1471
  }
494
1472
  }
495
1473
  fnScopeChain.set(node, chain);
496
- if (isPascalCaseComponent(name) && !excludedComponents.has(name)) {
1474
+ if (isPascalCaseComponent(name, node, ancestors, hocWrappers, isHookName) && !excludedComponents.has(name)) {
1475
+ node._unpeekIsComponent = true;
497
1476
  shallowComponentNodes.add(node);
498
1477
  hotFunctionNodes.add(node);
499
1478
  directHotNodes.add(node);
@@ -605,7 +1584,7 @@ function analyzeAstHotPaths(ast, config) {
605
1584
  }
606
1585
  },
607
1586
  CallExpression(node, _state, ancestors) {
608
- const callee = node.callee;
1587
+ const callee = unwrapCallee(node.callee);
609
1588
  let calleeName = "";
610
1589
  let memberProp = "";
611
1590
  let qualifiedCall = "";
@@ -736,6 +1715,9 @@ function analyzeAstHotPaths(ast, config) {
736
1715
  }
737
1716
  if (REACT_HOOK_OR_RENDER_CALLS.has(calleeName) || REACT_HOOK_OR_RENDER_CALLS.has(memberProp) || isHookName(calleeName) || isHookName(memberProp)) {
738
1717
  if (enclosingFn) {
1718
+ if (JSX_FACTORY_CALLS.has(calleeName) || JSX_FACTORY_CALLS.has(memberProp) || REACT_HOOK_OR_RENDER_CALLS.has(calleeName) || REACT_HOOK_OR_RENDER_CALLS.has(memberProp)) {
1719
+ enclosingFn._unpeekIsComponent = true;
1720
+ }
739
1721
  shallowComponentNodes.add(enclosingFn);
740
1722
  hotFunctionNodes.add(enclosingFn);
741
1723
  directHotNodes.add(enclosingFn);
@@ -904,6 +1886,99 @@ function analyzeAstHotPaths(ast, config) {
904
1886
  }
905
1887
  }
906
1888
  }
1889
+ const criticalAnnotation = typeof config?.critical?.annotation === "string" && config.critical.annotation.length > 0 ? config.critical.annotation : "@unpeek-critical";
1890
+ const astComments = ast?.__unpeekComments ?? ast?.comments ?? [];
1891
+ const criticalComments = astComments.filter(
1892
+ (c) => typeof c?.value === "string" && c.value.includes(criticalAnnotation)
1893
+ );
1894
+ const criticalCommentNodes = /* @__PURE__ */ new Set();
1895
+ if (criticalComments.length > 0 && allFunctions.length > 0) {
1896
+ const stmtRanges = [];
1897
+ walk.full(ast, (n) => {
1898
+ if (n && typeof n.start === "number" && typeof n.end === "number" && n.type !== "Program" && n.type !== "BlockStatement" && n.type !== "EmptyStatement" && (n.type.endsWith("Statement") || n.type === "VariableDeclaration" || n.type === "FunctionDeclaration" || n.type === "ClassDeclaration" || n.type === "ImportDeclaration" || n.type === "ExportNamedDeclaration" || n.type === "ExportDefaultDeclaration")) {
1899
+ stmtRanges.push({ start: n.start, end: n.end });
1900
+ }
1901
+ });
1902
+ const sortedFns = [...allFunctions].sort(
1903
+ (a, b) => (a.node.start ?? 0) - (b.node.start ?? 0)
1904
+ );
1905
+ for (const c of criticalComments) {
1906
+ const cStart = typeof c.start === "number" ? c.start : 0;
1907
+ const cEnd = typeof c.end === "number" ? c.end : 0;
1908
+ let enclosingFnEntry;
1909
+ for (const fn of sortedFns) {
1910
+ const s = fn.node.start;
1911
+ const e = fn.node.end;
1912
+ if (typeof s === "number" && typeof e === "number" && s <= cStart && cEnd <= e) {
1913
+ enclosingFnEntry = fn;
1914
+ }
1915
+ }
1916
+ const target = sortedFns.find(
1917
+ (fn) => typeof fn.node.start === "number" && fn.node.start >= cEnd
1918
+ );
1919
+ const enclosingEnd = enclosingFnEntry ? enclosingFnEntry.node.end : Infinity;
1920
+ if (target && target.node.end <= enclosingEnd) {
1921
+ const fnStart = target.node.start;
1922
+ const fnEnd = target.node.end;
1923
+ const blockedByStmt = stmtRanges.some(
1924
+ (s) => !(s.start <= fnStart && fnEnd <= s.end) && s.end > cEnd && s.end <= target.anchorStart
1925
+ );
1926
+ if (!blockedByStmt) {
1927
+ criticalCommentNodes.add(target.node);
1928
+ continue;
1929
+ }
1930
+ }
1931
+ if (enclosingFnEntry) {
1932
+ const body = enclosingFnEntry.node.body;
1933
+ if (body && typeof body.start === "number" && cStart >= body.start) {
1934
+ const hasPriorStmtInBody = stmtRanges.some(
1935
+ (s) => s.start >= body.start && s.end <= cStart
1936
+ );
1937
+ if (!hasPriorStmtInBody) {
1938
+ criticalCommentNodes.add(enclosingFnEntry.node);
1939
+ }
1940
+ }
1941
+ }
1942
+ }
1943
+ }
1944
+ const rawCriticalInclude = config?.critical?.include;
1945
+ const criticalIncludeList = Array.isArray(rawCriticalInclude) ? rawCriticalInclude : rawCriticalInclude !== void 0 ? [rawCriticalInclude] : [];
1946
+ const criticalIncludeMatchers = [];
1947
+ for (const pat of criticalIncludeList) {
1948
+ if (pat instanceof RegExp) {
1949
+ criticalIncludeMatchers.push((name) => pat.test(name));
1950
+ } else if (typeof pat === "string" && pat.length > 0) {
1951
+ try {
1952
+ const re = new RegExp(pat);
1953
+ criticalIncludeMatchers.push((name) => re.test(name));
1954
+ } catch {
1955
+ criticalIncludeMatchers.push((name) => name.includes(pat));
1956
+ }
1957
+ }
1958
+ }
1959
+ const sourceMapCriticalNodes = resolveSourceMapCriticalNodes(
1960
+ allFunctions,
1961
+ originalSourceMap,
1962
+ {
1963
+ criticalAnnotation,
1964
+ criticalIncludeMatchers,
1965
+ rawIncludePatterns: criticalIncludeList
1966
+ }
1967
+ );
1968
+ const matchedCriticalNodes = /* @__PURE__ */ new Set();
1969
+ for (const fn of allFunctions) {
1970
+ if (criticalCommentNodes.has(fn.node) || sourceMapCriticalNodes.has(fn.node) || criticalIncludeMatchers.some((match) => match(fn.name))) {
1971
+ matchedCriticalNodes.add(fn.node);
1972
+ if (!trueHotNodes.has(fn.node) && !serializedWorkerNodes.has(fn.node)) {
1973
+ shallowComponentNodes.delete(fn.node);
1974
+ hotFunctionNodes.delete(fn.node);
1975
+ directHotNodes.delete(fn.node);
1976
+ hotExemptNodes.delete(fn.node);
1977
+ delete fn.node._unpeekIsComponent;
1978
+ coldForcedNodes.add(fn.node);
1979
+ }
1980
+ }
1981
+ }
907
1982
  const calleeToCallers = /* @__PURE__ */ new Map();
908
1983
  for (const [callerNode, calleeNames] of callerToCallees.entries()) {
909
1984
  for (const cName of calleeNames) {
@@ -942,56 +2017,10 @@ function analyzeAstHotPaths(ast, config) {
942
2017
  }
943
2018
  }
944
2019
  for (const node of coldForcedNodes) {
2020
+ shallowComponentNodes.delete(node);
945
2021
  hotFunctionNodes.delete(node);
946
2022
  hotExemptNodes.delete(node);
947
2023
  }
948
- const criticalAnnotation = typeof config?.critical?.annotation === "string" && config.critical.annotation.length > 0 ? config.critical.annotation : "@unpeek-critical";
949
- const astComments = ast?.__unpeekComments ?? ast?.comments ?? [];
950
- const criticalComments = astComments.filter(
951
- (c) => typeof c?.value === "string" && c.value.includes(criticalAnnotation)
952
- );
953
- const criticalCommentNodes = /* @__PURE__ */ new Set();
954
- if (criticalComments.length > 0 && allFunctions.length > 0) {
955
- const stmtRanges = [];
956
- walk.full(ast, (n) => {
957
- if (n && typeof n.start === "number" && typeof n.end === "number" && n.type !== "Program" && n.type !== "BlockStatement" && (n.type.endsWith("Statement") || n.type === "VariableDeclaration" || n.type === "FunctionDeclaration" || n.type === "ClassDeclaration" || n.type === "ImportDeclaration" || n.type === "ExportNamedDeclaration" || n.type === "ExportDefaultDeclaration")) {
958
- stmtRanges.push({ start: n.start, end: n.end });
959
- }
960
- });
961
- const sortedFns = [...allFunctions].sort(
962
- (a, b) => (a.node.start ?? 0) - (b.node.start ?? 0)
963
- );
964
- for (const c of criticalComments) {
965
- const cEnd = typeof c.end === "number" ? c.end : 0;
966
- const target = sortedFns.find(
967
- (fn) => typeof fn.node.start === "number" && fn.node.start >= cEnd
968
- );
969
- if (!target) continue;
970
- const fnStart = target.node.start;
971
- const fnEnd = target.node.end;
972
- const blockedByStmt = stmtRanges.some(
973
- (s) => !(s.start <= fnStart && fnEnd <= s.end) && s.end > cEnd && s.end <= target.anchorStart
974
- );
975
- if (!blockedByStmt) {
976
- criticalCommentNodes.add(target.node);
977
- }
978
- }
979
- }
980
- const rawCriticalInclude = config?.critical?.include;
981
- const criticalIncludeList = Array.isArray(rawCriticalInclude) ? rawCriticalInclude : rawCriticalInclude !== void 0 ? [rawCriticalInclude] : [];
982
- const criticalIncludeMatchers = [];
983
- for (const pat of criticalIncludeList) {
984
- if (pat instanceof RegExp) {
985
- criticalIncludeMatchers.push((name) => pat.test(name));
986
- } else if (typeof pat === "string" && pat.length > 0) {
987
- try {
988
- const re = new RegExp(pat);
989
- criticalIncludeMatchers.push((name) => re.test(name));
990
- } catch {
991
- criticalIncludeMatchers.push((name) => name.includes(pat));
992
- }
993
- }
994
- }
995
2024
  const hotFunctionsSkipped = [];
996
2025
  const coldFunctionsProtected = [];
997
2026
  for (const fn of allFunctions) {
@@ -1000,7 +2029,7 @@ function analyzeAstHotPaths(ast, config) {
1000
2029
  } else {
1001
2030
  coldFunctionNodes.add(fn.node);
1002
2031
  coldFunctionsProtected.push(fn.name);
1003
- if (criticalCommentNodes.has(fn.node) || criticalIncludeMatchers.some((match) => match(fn.name))) {
2032
+ if (matchedCriticalNodes.has(fn.node) && !trueHotNodes.has(fn.node) && !serializedWorkerNodes.has(fn.node)) {
1004
2033
  criticalFunctionNodes.add(fn.node);
1005
2034
  }
1006
2035
  }
@@ -1045,6 +2074,9 @@ function computeNormalizedIntegrityHash(source, seed = 0) {
1045
2074
  );
1046
2075
  }
1047
2076
  var NATIVE_BUILTIN_RE = /^function (\w+)\(\)\s*\{\s*\[native code\]\s*\}$/;
2077
+ var STACK_GETTER_RE = /^function (?:get )?stack\(\)\s*\{\s*\[native code\]\s*\}$/;
2078
+ var STACK_SETTER_RE = /^function (?:set )?stack\(\)\s*\{\s*\[native code\]\s*\}$/;
2079
+ var NATIVE_ANON_OR_STACK_RE = /^function (?:(?:get )?stack)?\(\)\s*\{\s*\[native code\]\s*\}$/;
1048
2080
  function hasTamperedDescriptor(obj, key) {
1049
2081
  try {
1050
2082
  let cur = obj ?? null;
@@ -1076,36 +2108,83 @@ function isNativeBuiltinSignature(fn, expectedName, expectedLength, toStr) {
1076
2108
  return false;
1077
2109
  }
1078
2110
  }
1079
- function probeThrowsCleanTypeError(fn, thisArg, args) {
1080
- const refLine = (new Error().stack || "").split("\n")[1] || "";
1081
- const refMatch = /^\s*at\s+([^\s(]+)\s*\(/.exec(refLine);
1082
- const callerMarker = refMatch ? `
1083
- at ${refMatch[1]} (` : "";
2111
+ function probeThrowsCleanTypeError(fn, thisArg, args, toStr, stackProtoDesc) {
2112
+ const errCtor = Error;
2113
+ const prevPrepare = errCtor.prepareStackTrace;
2114
+ let ok = false;
2115
+ let restoreFailed = false;
1084
2116
  try {
1085
- Reflect.apply(fn, thisArg, args);
1086
- return false;
1087
- } catch (err) {
1088
- const isTypeError = err instanceof TypeError || err !== null && typeof err === "object" && err.name === "TypeError";
1089
- if (!isTypeError) {
1090
- return false;
1091
- }
1092
- const stack = err !== null && typeof err === "object" && typeof err.stack === "string" ? err.stack : "";
1093
- if (stack && callerMarker && stack.includes(callerMarker)) {
1094
- const head = stack.slice(0, stack.indexOf(callerMarker));
1095
- if (/(?:Object|Proxy)\.apply\b/.test(head) || /\n at (?!.* \(<anonymous>\)$)/m.test(head)) {
2117
+ if (prevPrepare !== void 0) {
2118
+ if (typeof process === "undefined") {
1096
2119
  return false;
1097
2120
  }
1098
- } else if (stack && /(?:Object|Proxy)\.apply\b/.test(stack)) {
2121
+ errCtor.prepareStackTrace = void 0;
2122
+ }
2123
+ const refOwnStackDesc = Object.getOwnPropertyDescriptor(new Error(), "stack");
2124
+ const refLine = (new Error().stack || "").split("\n")[1] || "";
2125
+ const refMatch = /^\s*at\s+([^\s(]+)\s*\(/.exec(refLine);
2126
+ const callerMarker = refMatch ? `
2127
+ at ${refMatch[1]} (` : "";
2128
+ try {
2129
+ Reflect.apply(fn, thisArg, args);
1099
2130
  return false;
2131
+ } catch (err) {
2132
+ if (errCtor.prepareStackTrace !== void 0) {
2133
+ if (typeof process === "undefined") {
2134
+ return false;
2135
+ }
2136
+ errCtor.prepareStackTrace = void 0;
2137
+ }
2138
+ const isTypeError = err instanceof TypeError || err !== null && typeof err === "object" && err.name === "TypeError";
2139
+ if (!isTypeError || err === null || typeof err !== "object") {
2140
+ return false;
2141
+ }
2142
+ const ownDesc = Object.getOwnPropertyDescriptor(err, "stack");
2143
+ if (ownDesc) {
2144
+ if ("value" in ownDesc || typeof ownDesc.get !== "function" || Reflect.has(ownDesc.get, "prototype") || !refOwnStackDesc?.get || ownDesc.get.name !== "" || ownDesc.get.length !== 0) {
2145
+ return false;
2146
+ }
2147
+ const getterSrc = Reflect.apply(toStr, ownDesc.get, []);
2148
+ if (typeof getterSrc !== "string" || !NATIVE_ANON_OR_STACK_RE.test(getterSrc)) {
2149
+ return false;
2150
+ }
2151
+ }
2152
+ const stack = stackProtoDesc?.get ? Reflect.apply(stackProtoDesc.get, err, []) : ownDesc?.get ? Reflect.apply(ownDesc.get, err, []) : err.stack;
2153
+ if (typeof stack !== "string" || stack.length === 0 || !stack.includes("\n at ")) {
2154
+ return false;
2155
+ }
2156
+ if (callerMarker && stack.includes(callerMarker)) {
2157
+ const head = stack.slice(0, stack.indexOf(callerMarker));
2158
+ if (/(?:Object|Proxy)\.apply\b/.test(head) || /\n at (?!.* \(<anonymous>\)$)/m.test(head)) {
2159
+ return false;
2160
+ }
2161
+ } else if (/(?:Object|Proxy)\.apply\b/.test(stack)) {
2162
+ return false;
2163
+ }
2164
+ ok = true;
2165
+ }
2166
+ } catch {
2167
+ return false;
2168
+ } finally {
2169
+ if (prevPrepare !== void 0) {
2170
+ try {
2171
+ errCtor.prepareStackTrace = prevPrepare;
2172
+ } catch {
2173
+ restoreFailed = true;
2174
+ }
1100
2175
  }
1101
- return true;
1102
2176
  }
2177
+ return ok && !restoreFailed;
1103
2178
  }
1104
2179
  function isNativeDescriptorIntact() {
1105
2180
  if (typeof Reflect === "undefined" || typeof Reflect.apply !== "function") {
1106
2181
  return false;
1107
2182
  }
1108
- if (hasTamperedDescriptor(Function.prototype, "toString") || hasTamperedDescriptor(Function.prototype, "call") || hasTamperedDescriptor(Reflect, "apply")) {
2183
+ const errCtor = Error;
2184
+ if (hasTamperedDescriptor(Function.prototype, "toString") || hasTamperedDescriptor(Function.prototype, "call") || hasTamperedDescriptor(Reflect, "apply") || hasTamperedDescriptor(Error, "prepareStackTrace")) {
2185
+ return false;
2186
+ }
2187
+ if (typeof process === "undefined" && errCtor.prepareStackTrace !== void 0) {
1109
2188
  return false;
1110
2189
  }
1111
2190
  const toStr = Function.prototype.toString;
@@ -1114,8 +2193,36 @@ function isNativeDescriptorIntact() {
1114
2193
  if (!isNativeBuiltinSignature(reflectApply, "apply", 3, toStr) || !isNativeBuiltinSignature(toStr, "toString", 0, toStr) || !isNativeBuiltinSignature(fnCall, "call", 1, toStr)) {
1115
2194
  return false;
1116
2195
  }
1117
- if (!probeThrowsCleanTypeError(Object.getOwnPropertyDescriptor, null, []) || !probeThrowsCleanTypeError(toStr, { toString() {
1118
- } }, []) || !probeThrowsCleanTypeError(reflectApply, toStr, [null, toStr, []])) {
2196
+ const stackProtoDesc = Object.getOwnPropertyDescriptor(Error.prototype, "stack");
2197
+ if (stackProtoDesc) {
2198
+ if (typeof stackProtoDesc.get !== "function" || Reflect.has(stackProtoDesc.get, "prototype")) {
2199
+ return false;
2200
+ }
2201
+ try {
2202
+ const getSrc = reflectApply(toStr, stackProtoDesc.get, []);
2203
+ if (typeof getSrc !== "string" || !STACK_GETTER_RE.test(getSrc)) {
2204
+ return false;
2205
+ }
2206
+ if (stackProtoDesc.set !== void 0) {
2207
+ if (typeof stackProtoDesc.set !== "function" || Reflect.has(stackProtoDesc.set, "prototype")) {
2208
+ return false;
2209
+ }
2210
+ const setSrc = reflectApply(toStr, stackProtoDesc.set, []);
2211
+ if (typeof setSrc !== "string" || !STACK_SETTER_RE.test(setSrc)) {
2212
+ return false;
2213
+ }
2214
+ }
2215
+ } catch {
2216
+ return false;
2217
+ }
2218
+ if (hasTamperedDescriptor(Object.getPrototypeOf(Error.prototype), "stack")) {
2219
+ return false;
2220
+ }
2221
+ } else if (hasTamperedDescriptor(Error.prototype, "stack")) {
2222
+ return false;
2223
+ }
2224
+ if (!probeThrowsCleanTypeError(Object.getOwnPropertyDescriptor, null, [], toStr, stackProtoDesc) || !probeThrowsCleanTypeError(toStr, { toString() {
2225
+ } }, [], toStr, stackProtoDesc) || !probeThrowsCleanTypeError(reflectApply, toStr, [null, toStr, []], toStr, stackProtoDesc)) {
1119
2226
  return false;
1120
2227
  }
1121
2228
  try {
@@ -1711,7 +2818,7 @@ var compactGenerator = Object.assign({}, baseGenerator, {
1711
2818
  }
1712
2819
  });
1713
2820
  var VLQ_BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1714
- function encodeVlq(value) {
2821
+ function encodeVlq2(value) {
1715
2822
  let vlq = value < 0 ? (-value << 1) + 1 : value << 1;
1716
2823
  let encoded = "";
1717
2824
  do {
@@ -1812,13 +2919,13 @@ function generateCompactJsWithMap(ast, fileName) {
1812
2919
  let prevGenCol = 0;
1813
2920
  const encodedSegs = [];
1814
2921
  for (const seg of segs) {
1815
- let s = encodeVlq(seg.genCol - prevGenCol) + encodeVlq(seg.srcIdx - prevSrcIdx) + encodeVlq(seg.origLine - prevOrigLine) + encodeVlq(seg.origCol - prevOrigCol);
2922
+ let s = encodeVlq2(seg.genCol - prevGenCol) + encodeVlq2(seg.srcIdx - prevSrcIdx) + encodeVlq2(seg.origLine - prevOrigLine) + encodeVlq2(seg.origCol - prevOrigCol);
1816
2923
  prevGenCol = seg.genCol;
1817
2924
  prevSrcIdx = seg.srcIdx;
1818
2925
  prevOrigLine = seg.origLine;
1819
2926
  prevOrigCol = seg.origCol;
1820
2927
  if (seg.nameIdx !== void 0) {
1821
- s += encodeVlq(seg.nameIdx - prevNameIdx);
2928
+ s += encodeVlq2(seg.nameIdx - prevNameIdx);
1822
2929
  prevNameIdx = seg.nameIdx;
1823
2930
  }
1824
2931
  encodedSegs.push(s);
@@ -1849,9 +2956,9 @@ function createDeterrentSnippet(config) {
1849
2956
  const consoleSilence = deterrentMode === "gradual" ? "for(var k in console)console[k]=()=>0;" : "";
1850
2957
  const symLit = JSON.stringify(sym);
1851
2958
  const headlessDecl = detectHeadless ? ",n=w.navigator||0" : "";
1852
- const headlessCond = detectHeadless ? "||n.webdriver||/HeadlessChrome/.test(n.userAgent)" : "";
2959
+ const headlessCond = detectHeadless ? "||n.webdriver||/HeadlessChrome/.test(n.userAgent)||['__playwright','__puppeteer_evaluation_script__','__nightmare','frida','_frida_'].some(k=>w[k]||G[k])" : "";
1853
2960
  const k1Mul = (seed | 1) >>> 0;
1854
- return `(function ${fnName}(w){var G=globalThis||w;if(w){var O=Object,P=O.getOwnPropertyDescriptor,RF=G.Reflect,R=RF&&RF.apply,FP=Function.prototype,SP=String.prototype,Q='__unpeek_',y=${symLit},z=y+'_s',U='__unpeek_tampered',K=Q+'seed',T=(o,k)=>{try{for(var r;o;o=O.getPrototypeOf(o))if((r=P(o,k))&&(r.set||!r.writable))return 1;}catch(e){return 1;}},D=k=>T(w,k)|T(G,k),B=(k,v,c,W)=>{W=o=>{try{if(!c||!T(o,k))o[k]=v;}catch(e){}};W(G);W(w);},s=FP.toString${headlessDecl},src='',t=+((G[z]||w[z])?.[0]==2);try{var ps,E=(f,a,b)=>{try{R(f,a,b);t=1;}catch(e){t|=e?.name!='TypeError'||/\\n at (?!.* \\(<anonymous>\\)$)/m.test(e?.stack?.split('\\n at E (')[0]);}},F=(f,n,l)=>typeof f!='function'||'prototype'in f||f.name!=n||f.length!=l||/^function (\\w+)\\(\\)\\s*\\x7b\\s*\\[native code\\]\\s*}$/.exec(R(R,null,[s,f,[]]))?.[1]!=n;E(P,null,[]);E(s,{toString(){}},[]);E(R,s,[null,s,[]]);src=R(s,${fnName},[]);t|=F(R,'apply',3)|F(s,'toString',0)|s.call(T)!==(ps=R(s,T,[]))|FP.call.call(s,T)!==ps|/\\n/.test(src)${headlessCond};}catch(e){t=1;}t|=D(y)|D(z)|D(U)|T(SP,'_u')|T(FP,'toString')|T(FP,'call')|T(RF,'apply');for(var h=2166136261,i=0;i<src.length;)h=Math.imul(h^src.charCodeAt(i++),16777619);var d=h&65535,pd=t?d^((h>>>16^23131)||1):d;B(z,[t+1,h^${seed}^t,h^${k1Mul}^t,1,d^h>>>16],t);B(y,pd,t);if(t){B(y+'_t',!0);B(Q+'delta',pd);try{SP._u=14;}catch(e){}B(K,((w[K]||${seed})^1)>>>0);B(U,!0);try{${consoleSilence}w.dispatchEvent?.(new CustomEvent('unpeek:tamper'));}catch(e){}}}})(typeof window!=='undefined'?window:typeof self<'u'?self:typeof globalThis<'u'?globalThis:0);`;
2961
+ return `(function ${fnName}(w){var G=globalThis||w;if(w){var O=Object,P=O.getOwnPropertyDescriptor,RF=G.Reflect,R=RF&&RF.apply,FP=Function.prototype,SP=String.prototype,ER=Error,EP=ER.prototype,Q='__unpeek_',y=${symLit},z=y+'_s',U='__unpeek_tampered',K=Q+'seed',ST='stack',PS='prepareStackTrace',A='\\n at ',T=(o,k)=>{try{for(var r;o;o=O.getPrototypeOf(o))if((r=P(o,k))&&(r.set||!r.writable))return 1;}catch(e){return 1;}},D=k=>T(w,k)|T(G,k),B=(k,v,c,W)=>{W=o=>{try{if(!c||!T(o,k))o[k]=v;}catch(e){}};W(G);W(w);},s=FP.toString${headlessDecl},src='',t=+((G[z]||w[z])?.[0]==2),sd=P(EP,ST),ep=ER[PS],M=/^function (?:get )?(\\w*)\\(\\)\\s*\\x7b\\s*\\[native code\\]\\s*\\}$/;try{var ps,rf=P(new ER(),ST),Z=()=>{if(ER[PS]!==void 0){if(typeof process>'u')t=1;ER[PS]=void 0;}},F=(f,n,l)=>typeof f!='function'||'prototype'in f||(l>=0&&(f.name!=n||f.length!=l))||M.exec(R(R,null,[s,f,[]]))?.[1]!=n,E=(f,a,b)=>{try{R(f,a,b);t=1;}catch(e){Z();var ed=P(e,ST),st=sd&&sd.get?R(sd.get,e,[]):ed&&ed.get?R(ed.get,e,[]):e[ST];if(ed&&(!rf||F(ed.get,'',0)))t=1;t|=e?.name!='TypeError'||!st||st.indexOf(A)<0||/(?:Object|Proxy)\\.apply\\b|\\n at (?!.* \\(<anonymous>\\)$)/m.test(st.split(A+'E (')[0]);}};Z();try{E(P,null,[]);E(s,{toString(){}},[]);E(R,s,[null,s,[]]);}finally{if(ep!==void 0)ER[PS]=ep;}src=R(s,${fnName},[]);t|=(sd&&F(sd.get,ST,-1))|F(R,'apply',3)|F(s,'toString',0)|s.call(T)!==(ps=R(s,T,[]))|FP.call.call(s,T)!==ps|/\\n/.test(src)${headlessCond};}catch(e){t=1;}t|=D(y)|D(z)|D(U)|T(SP,'_u')|T(FP,'toString')|T(FP,'call')|T(RF,'apply')|T(ER,PS)|(sd?T(O.getPrototypeOf(EP),ST):T(EP,ST));for(var h=2166136261,i=0;i<src.length;)h=Math.imul(h^src.charCodeAt(i++),16777619);var d=h&65535,pd=t?d^((h>>>16^23131)||1):d;B(z,[t+1,h^${seed}^t,h^${k1Mul}^t,1,d^h>>>16],t);B(y,pd,t);if(t){B(y+'_t',!0);B(Q+'delta',pd);try{SP._u=14;}catch(e){}B(K,((w[K]||${seed})^1)>>>0);B(U,!0);try{${consoleSilence}w.dispatchEvent?.(new CustomEvent('unpeek:tamper'));}catch(e){}}}})(typeof window!=='undefined'?window:typeof self<'u'?self:typeof globalThis<'u'?globalThis:0);`;
1855
2962
  }
1856
2963
 
1857
2964
  // src/runtime/index.ts
@@ -1870,13 +2977,15 @@ function generateRuntimeShield(config) {
1870
2977
  const computedHash = computeIntegrityHash(fnDecl, 0);
1871
2978
  const expectedHash = config.expectedIntegrityHash !== void 0 ? config.expectedIntegrityHash >>> 0 : computedHash;
1872
2979
  const expectedDelta = config.expectedDelta !== void 0 ? config.expectedDelta & 65535 : computedHash >>> 0 & 65535;
2980
+ const expectedStateHash = computedHash ^ seed | 0;
1873
2981
  const payload = {
1874
2982
  preambleCode,
1875
2983
  integrityCheckFnName,
1876
2984
  expectedHash,
1877
2985
  windowKeySymbol,
1878
2986
  expectedDelta,
1879
- stateKeySymbol: `${windowKeySymbol}_s`
2987
+ stateKeySymbol: `${windowKeySymbol}_s`,
2988
+ expectedStateHash
1880
2989
  };
1881
2990
  return payload;
1882
2991
  }
@@ -1948,10 +3057,94 @@ function deriveWasmHostParams(seed) {
1948
3057
  const rA1 = computeFnv1aHash("wasm-ra1", seed) | 1;
1949
3058
  const rA2 = computeFnv1aHash("wasm-ra2", seed) & ~1;
1950
3059
  const rA3 = computeFnv1aHash("wasm-ra3", seed) & ~1;
1951
- return { gArr, sOff, rA0, rA1, rA2, rA3 };
3060
+ const gMask = computeFnv1aHash("wasm-gmask", seed) | 1 | 0;
3061
+ const pcMask = computeFnv1aHash("wasm-pcmask", seed) | 1 | 0;
3062
+ return { gArr, sOff, rA0, rA1, rA2, rA3, gMask, pcMask };
3063
+ }
3064
+ var ABI_START_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_";
3065
+ var ABI_CONT_CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_";
3066
+ var FORBIDDEN_ABI_NAMES = /* @__PURE__ */ new Set([
3067
+ "env",
3068
+ "g",
3069
+ "m",
3070
+ "kdf",
3071
+ "bulkmix",
3072
+ "mem",
3073
+ "as",
3074
+ "do",
3075
+ "if",
3076
+ "in",
3077
+ "of",
3078
+ "for",
3079
+ "int",
3080
+ "let",
3081
+ "new",
3082
+ "try",
3083
+ "var",
3084
+ "nan",
3085
+ "map",
3086
+ "set",
3087
+ "url",
3088
+ "top",
3089
+ "get",
3090
+ "set"
3091
+ ]);
3092
+ function avalancheMix32(h) {
3093
+ let x = h >>> 0;
3094
+ x = Math.imul(x ^ x >>> 16, 2246822507) >>> 0;
3095
+ x = Math.imul(x ^ x >>> 13, 3266489909) >>> 0;
3096
+ return (x ^ x >>> 16) >>> 0;
3097
+ }
3098
+ function encodeWasmName(name) {
3099
+ const utf8 = new TextEncoder().encode(name);
3100
+ return [...encodeUnsignedLeb128(utf8.length), ...utf8];
3101
+ }
3102
+ function deriveWasmAbiNames(seed) {
3103
+ const s = seed >>> 0;
3104
+ const used = new Set(FORBIDDEN_ABI_NAMES);
3105
+ const pickName = (role) => {
3106
+ for (let attempt = 0; attempt < 64; attempt++) {
3107
+ const h = avalancheMix32(computeFnv1aHash(`wasm-abi:${role}:${attempt}`, s));
3108
+ const len = h >>> 18 & 1 ? 3 : 2;
3109
+ const c0 = ABI_START_CHARS[h % ABI_START_CHARS.length];
3110
+ const c1 = ABI_CONT_CHARS[(h >>> 6) % ABI_CONT_CHARS.length];
3111
+ const c2 = len === 3 ? ABI_CONT_CHARS[(h >>> 12) % ABI_CONT_CHARS.length] : "";
3112
+ const candidate = `${c0}${c1}${c2}`;
3113
+ const lower = candidate.toLowerCase();
3114
+ if (!candidate.startsWith("__") && !used.has(lower)) {
3115
+ used.add(lower);
3116
+ return candidate;
3117
+ }
3118
+ }
3119
+ const fallback = `w${s.toString(36).slice(0, 2).padStart(2, "0")}`;
3120
+ used.add(fallback.toLowerCase());
3121
+ return fallback;
3122
+ };
3123
+ const envMod = pickName("envMod");
3124
+ const gImport = pickName("gImport");
3125
+ const mImport = pickName("mImport");
3126
+ const kdfExport = pickName("kdfExport");
3127
+ const bulkMixExport = pickName("bulkMixExport");
3128
+ const memExport = pickName("memExport");
3129
+ const exportOrder = [0, 1, 2];
3130
+ const orderHash = avalancheMix32(computeFnv1aHash("wasm-abi:order", s));
3131
+ const j2 = orderHash % 3;
3132
+ [exportOrder[2], exportOrder[j2]] = [exportOrder[j2], exportOrder[2]];
3133
+ const j1 = (orderHash >>> 8) % 2;
3134
+ [exportOrder[1], exportOrder[j1]] = [exportOrder[j1], exportOrder[1]];
3135
+ return {
3136
+ envMod,
3137
+ gImport,
3138
+ mImport,
3139
+ kdfExport,
3140
+ bulkMixExport,
3141
+ memExport,
3142
+ exportOrder
3143
+ };
1952
3144
  }
1953
- function generateWasmKdfBinary(seed) {
3145
+ function generateWasmKdfBinary(seed, options) {
1954
3146
  const { sVal, c1, c2, k0, r1, r2 } = deriveKdfParams(seed);
3147
+ const { gMask, pcMask } = deriveWasmHostParams(seed);
1955
3148
  const memBase = (seed >>> 0 & 127) * 4;
1956
3149
  const r0 = computeFnv1aHash("wasm-r0", seed) | 0;
1957
3150
  const rotAmt = (seed >>> 0) % 27 + 3;
@@ -1965,6 +3158,8 @@ function generateWasmKdfBinary(seed) {
1965
3158
  const w2 = c1 ^ (w0 + w1 | 0) | 0;
1966
3159
  const w3 = c2 - Math.imul(w1 | 1, w2 | 1) | 0;
1967
3160
  const w4 = k0 ^ rotl32(w2, 11) ^ w3 | 0;
3161
+ const w5 = gMask ^ rotl32(w3, 7) ^ w0 | 0;
3162
+ const w6 = pcMask ^ rotl32(w4, 13) ^ w1 | 0;
1968
3163
  const kdfInstructions = [
1969
3164
  65,
1970
3165
  ...encodeSignedLeb128(memA),
@@ -2081,25 +3276,81 @@ function generateWasmKdfBinary(seed) {
2081
3276
  2,
2082
3277
  16,
2083
3278
  // i32.load align=2 offset=16 (w4)
2084
- 32,
2085
- 6,
2086
- // local.get 6 (w2)
3279
+ 32,
3280
+ 6,
3281
+ // local.get 6 (w2)
3282
+ 65,
3283
+ 11,
3284
+ // i32.const 11
3285
+ 119,
3286
+ // i32.rotl
3287
+ 115,
3288
+ // i32.xor
3289
+ 32,
3290
+ 7,
3291
+ // local.get 7 (w3)
3292
+ 115,
3293
+ // i32.xor
3294
+ 33,
3295
+ 10,
3296
+ // local.set 10 (k0)
3297
+ // Reconstruct gMask -> local 12
3298
+ 32,
3299
+ 3,
3300
+ // local.get 3 (ptr)
3301
+ 40,
3302
+ 2,
3303
+ 20,
3304
+ // i32.load align=2 offset=20 (w5)
3305
+ 32,
3306
+ 7,
3307
+ // local.get 7 (w3)
3308
+ 65,
3309
+ 7,
3310
+ // i32.const 7
3311
+ 119,
3312
+ // i32.rotl
3313
+ 115,
3314
+ // i32.xor
3315
+ 32,
3316
+ 4,
3317
+ // local.get 4 (w0)
3318
+ 115,
3319
+ // i32.xor
3320
+ 33,
3321
+ 12,
3322
+ // local.set 12 (gMask)
3323
+ // Reconstruct pcMask -> local 13
3324
+ 32,
3325
+ 3,
3326
+ // local.get 3 (ptr)
3327
+ 40,
3328
+ 2,
3329
+ 24,
3330
+ // i32.load align=2 offset=24 (w6)
3331
+ 32,
3332
+ 3,
3333
+ // local.get 3 (ptr)
3334
+ 40,
3335
+ 2,
3336
+ 16,
3337
+ // i32.load align=2 offset=16 (w4)
2087
3338
  65,
2088
- 11,
2089
- // i32.const 11
3339
+ 13,
3340
+ // i32.const 13
2090
3341
  119,
2091
3342
  // i32.rotl
2092
3343
  115,
2093
3344
  // i32.xor
2094
3345
  32,
2095
- 7,
2096
- // local.get 7 (w3)
3346
+ 5,
3347
+ // local.get 5 (w1)
2097
3348
  115,
2098
3349
  // i32.xor
2099
3350
  33,
2100
- 10,
2101
- // local.set 10 (k0)
2102
- // x = f ^ sVal ^ k0 ^ env.g(0)
3351
+ 13,
3352
+ // local.set 13 (pcMask)
3353
+ // x = f ^ sVal ^ k0 ^ (env.g(0) ^ gMask)
2103
3354
  32,
2104
3355
  0,
2105
3356
  // local.get 0 (fnId)
@@ -2119,6 +3370,11 @@ function generateWasmKdfBinary(seed) {
2119
3370
  16,
2120
3371
  0,
2121
3372
  // call 0 (env.g(0))
3373
+ 32,
3374
+ 12,
3375
+ // local.get 12 (gMask)
3376
+ 115,
3377
+ // i32.xor
2122
3378
  115,
2123
3379
  // i32.xor
2124
3380
  34,
@@ -2152,14 +3408,19 @@ function generateWasmKdfBinary(seed) {
2152
3408
  // i32.const r1
2153
3409
  119,
2154
3410
  // i32.rotl
2155
- // x = env.m(x, shieldHash)
3411
+ // x = env.m(x, shieldHash ^ pcMask)
2156
3412
  32,
2157
3413
  2,
2158
3414
  // local.get 2 (shieldHash)
3415
+ 32,
3416
+ 13,
3417
+ // local.get 13 (pcMask)
3418
+ 115,
3419
+ // i32.xor
2159
3420
  16,
2160
3421
  1,
2161
- // call 1 (env.m(x, shieldHash))
2162
- // x = imul(x ^ h ^ sVal ^ env.g(1), c2)
3422
+ // call 1 (env.m(x, maskedPc))
3423
+ // x = imul(x ^ h ^ sVal ^ (env.g(1) ^ gMask), c2)
2163
3424
  32,
2164
3425
  2,
2165
3426
  // local.get 2 (shieldHash)
@@ -2176,6 +3437,11 @@ function generateWasmKdfBinary(seed) {
2176
3437
  16,
2177
3438
  0,
2178
3439
  // call 0 (env.g(1))
3440
+ 32,
3441
+ 12,
3442
+ // local.get 12 (gMask)
3443
+ 115,
3444
+ // i32.xor
2179
3445
  115,
2180
3446
  // i32.xor
2181
3447
  32,
@@ -2312,6 +3578,11 @@ function generateWasmKdfBinary(seed) {
2312
3578
  16,
2313
3579
  0,
2314
3580
  // call 0 (env.g)
3581
+ 65,
3582
+ ...encodeSignedLeb128(gMask),
3583
+ // i32.const gMask
3584
+ 115,
3585
+ // i32.xor
2315
3586
  106,
2316
3587
  // i32.add
2317
3588
  16,
@@ -2363,7 +3634,7 @@ function generateWasmKdfBinary(seed) {
2363
3634
  11
2364
3635
  // end func
2365
3636
  ];
2366
- const kdfBody = [1, 9, 127, ...kdfInstructions];
3637
+ const kdfBody = [1, 11, 127, ...kdfInstructions];
2367
3638
  const kdfBodyWithLen = [...encodeUnsignedLeb128(kdfBody.length), ...kdfBody];
2368
3639
  const bulkBody = [1, 2, 127, ...bulkMixInstructions];
2369
3640
  const bulkBodyWithLen = [...encodeUnsignedLeb128(bulkBody.length), ...bulkBody];
@@ -2397,27 +3668,23 @@ function generateWasmKdfBinary(seed) {
2397
3668
  ...encodeUnsignedLeb128(typePayload.length),
2398
3669
  ...typePayload
2399
3670
  ];
3671
+ const abi = options?.polymorphicAbi ? deriveWasmAbiNames(seed) : null;
3672
+ const envModName = abi ? abi.envMod : "env";
3673
+ const gImportName = abi ? abi.gImport : "g";
3674
+ const mImportName = abi ? abi.mImport : "m";
2400
3675
  const importPayload = [
2401
3676
  2,
2402
3677
  // 2 imports
2403
- 3,
2404
- 101,
2405
- 110,
2406
- 118,
2407
- 1,
2408
- 103,
3678
+ ...encodeWasmName(envModName),
3679
+ ...encodeWasmName(gImportName),
2409
3680
  0,
2410
3681
  0,
2411
- // env.g: func type 0
2412
- 3,
2413
- 101,
2414
- 110,
2415
- 118,
2416
- 1,
2417
- 109,
3682
+ // g: func type 0
3683
+ ...encodeWasmName(envModName),
3684
+ ...encodeWasmName(mImportName),
2418
3685
  0,
2419
3686
  1
2420
- // env.m: func type 1
3687
+ // m: func type 1
2421
3688
  ];
2422
3689
  const importSection = [
2423
3690
  2,
@@ -2431,35 +3698,21 @@ function generateWasmKdfBinary(seed) {
2431
3698
  ...funcPayload
2432
3699
  ];
2433
3700
  const memSection = [5, 3, 1, 0, 1];
2434
- const exportPayload = [
2435
- 3,
2436
- // 3 exports
2437
- 3,
2438
- 107,
2439
- 100,
2440
- 102,
2441
- 0,
2442
- 2,
2443
- // "kdf" -> func 2
2444
- 7,
2445
- 98,
2446
- 117,
2447
- 108,
2448
- 107,
2449
- 77,
2450
- 105,
2451
- 120,
2452
- 0,
2453
- 3,
2454
- // "bulkMix" -> func 3
2455
- 3,
2456
- 109,
2457
- 101,
2458
- 109,
2459
- 2,
2460
- 0
2461
- // "mem" -> memory 0
3701
+ const exportSpecs = abi ? [
3702
+ [abi.kdfExport, 0, 2],
3703
+ [abi.bulkMixExport, 0, 3],
3704
+ [abi.memExport, 2, 0]
3705
+ ] : [
3706
+ ["kdf", 0, 2],
3707
+ ["bulkMix", 0, 3],
3708
+ ["mem", 2, 0]
2462
3709
  ];
3710
+ const exportOrder = abi ? abi.exportOrder : [0, 1, 2];
3711
+ const exportPayload = [3];
3712
+ for (const idx of exportOrder) {
3713
+ const [name, kind, targetIdx] = exportSpecs[idx];
3714
+ exportPayload.push(...encodeWasmName(name), kind, targetIdx);
3715
+ }
2463
3716
  const exportSection = [
2464
3717
  7,
2465
3718
  ...encodeUnsignedLeb128(exportPayload.length),
@@ -2476,7 +3729,9 @@ function generateWasmKdfBinary(seed) {
2476
3729
  ...writeI32LE(w1),
2477
3730
  ...writeI32LE(w2),
2478
3731
  ...writeI32LE(w3),
2479
- ...writeI32LE(w4)
3732
+ ...writeI32LE(w4),
3733
+ ...writeI32LE(w5),
3734
+ ...writeI32LE(w6)
2480
3735
  ];
2481
3736
  const dataPayload = [
2482
3737
  1,
@@ -2509,20 +3764,22 @@ function generateWasmKdfBinary(seed) {
2509
3764
  }
2510
3765
  function fallbackKdf(fnId, callSiteSalt, shieldHash, seed) {
2511
3766
  const { sVal, c1, c2, k0, r1, r2 } = deriveKdfParams(seed);
2512
- const { gArr, sOff, rA0, rA1, rA2, rA3 } = deriveWasmHostParams(seed);
3767
+ const { gArr, sOff, rA0, rA1, rA2, rA3, gMask, pcMask } = deriveWasmHostParams(seed);
3768
+ const envG = (slot) => gArr[slot & 3] ^ gMask | 0;
2513
3769
  const envM = (acc, pc) => {
2514
3770
  const sb0 = Math.imul(167, acc & 255) + sOff & 255;
2515
3771
  const sb1 = Math.imul(167, acc >>> 8 & 255) + sOff & 255;
2516
3772
  const sb = sb0 ^ sb1 << 8;
2517
- const riv = evalRivestPoly32(acc ^ sb ^ pc | 0, rA0, rA1, rA2, rA3) | 0;
3773
+ const unmaskedPc = pc ^ pcMask | 0;
3774
+ const riv = evalRivestPoly32(acc ^ sb ^ unmaskedPc | 0, rA0, rA1, rA2, rA3) | 0;
2518
3775
  return riv ^ gArr[2] | 0;
2519
3776
  };
2520
- let x = fnId ^ sVal ^ k0 ^ gArr[0] | 0;
3777
+ let x = fnId ^ sVal ^ k0 ^ (envG(0) ^ gMask) | 0;
2521
3778
  x = x ^ x >>> 16 | 0;
2522
3779
  x = Math.imul(x, c1);
2523
3780
  x = rotl32(x ^ callSiteSalt | 0, r1);
2524
- x = envM(x, shieldHash | 0);
2525
- x = Math.imul(x ^ shieldHash ^ sVal ^ gArr[1] | 0, c2);
3781
+ x = envM(x, shieldHash ^ pcMask | 0);
3782
+ x = Math.imul(x ^ shieldHash ^ sVal ^ (envG(1) ^ gMask) | 0, c2);
2526
3783
  x = x ^ x >>> 15 | 0;
2527
3784
  x = x + rotl32(callSiteSalt ^ k0 | 0, r2) | 0;
2528
3785
  x = Math.imul(x, c1);
@@ -2553,15 +3810,16 @@ function injectWasmVault(ast, seed = 2654435769) {
2553
3810
  const id = existing?.declarations[0]?.id?.name ?? kdfFnName;
2554
3811
  return {
2555
3812
  kdfFnName: id,
2556
- wasmBytes: generateWasmKdfBinary(seed),
3813
+ wasmBytes: generateWasmKdfBinary(seed, { polymorphicAbi: true }),
2557
3814
  wasmVarName,
2558
3815
  kdfParityVerified: true
2559
3816
  };
2560
3817
  }
2561
- const wasmBytes = generateWasmKdfBinary(seed);
3818
+ const abi = deriveWasmAbiNames(seed);
3819
+ const wasmBytes = generateWasmKdfBinary(seed, { polymorphicAbi: true });
2562
3820
  const byteArrayLiteral = Array.from(wasmBytes).join(",");
2563
3821
  const { sVal, c1, c2, k0, r1, r2 } = deriveKdfParams(seed);
2564
- const { gArr, sOff, rA0, rA1, rA2, rA3 } = deriveWasmHostParams(seed);
3822
+ const { gArr, sOff, rA0, rA1, rA2, rA3, gMask, pcMask } = deriveWasmHostParams(seed);
2565
3823
  const targets = [c1, c2, sVal, k0, r1, r2];
2566
3824
  const rivEncodedTargets = targets.map(
2567
3825
  (t, j) => invertRivestPoly32((t ^ gArr[j & 3]) >>> 0, rA0, rA1, rA2, rA3) | 0
@@ -2586,17 +3844,17 @@ function injectWasmVault(ast, seed = 2654435769) {
2586
3844
  var _tk = ['__','unp','eek_t','ampered'].join('');
2587
3845
  var _eG = function(sl) {
2588
3846
  var tp = (_G && _G[_tk] === !0) ? 0x5a5b : 0;
2589
- return (_g[sl & 3] ^ tp) | 0;
3847
+ return (_g[sl & 3] ^ ${gMask} ^ tp) | 0;
2590
3848
  };
2591
3849
  var _eM = function(acc, pc) {
2592
3850
  var sb = _sb(acc) ^ (_sb(acc >>> 8) << 8);
2593
- return (_evR((acc ^ sb ^ pc) | 0) ^ _g[2]) | 0;
3851
+ return (_evR((acc ^ sb ^ (pc ^ ${pcMask})) | 0) ^ _g[2]) | 0;
2594
3852
  };
2595
3853
  try {
2596
3854
  var ${wasmVarName} = new Uint8Array([${byteArrayLiteral}]);
2597
3855
  var _wm${suffix} = new WebAssembly.Module(${wasmVarName});
2598
- var _wi${suffix} = new WebAssembly.Instance(_wm${suffix}, { env: { g: _eG, m: _eM } });
2599
- ${kdfFnName} = _wi${suffix}.exports.kdf;
3856
+ var _wi${suffix} = new WebAssembly.Instance(_wm${suffix}, { ${abi.envMod}: { ${abi.gImport}: _eG, ${abi.mImport}: _eM } });
3857
+ ${kdfFnName} = _wi${suffix}.exports[${JSON.stringify(abi.kdfExport)}];
2600
3858
  } catch (e) {
2601
3859
  var _kx = [${rivEncodedTargets.join(",")}];
2602
3860
  var _k = [];
@@ -2610,13 +3868,13 @@ function injectWasmVault(ast, seed = 2654435769) {
2610
3868
  }
2611
3869
  var _m = Math[_p];
2612
3870
  ${kdfFnName} = function(f, s, h) {
2613
- var _x = (f ^ _k[2] ^ _k[3] ^ _eG(0)) | 0;
3871
+ var _x = (f ^ _k[2] ^ _k[3] ^ (_eG(0) ^ ${gMask})) | 0;
2614
3872
  _x = (_x ^ (_x >>> 16)) | 0;
2615
3873
  _x = _m(_x, _k[0]);
2616
3874
  var _t0 = _x ^ s, _r1 = _k[4];
2617
3875
  _x = (_t0 << _r1) | (_t0 >>> (32 - _r1));
2618
- _x = _eM(_x, h | 0);
2619
- _x = _m(_x ^ h ^ _k[2] ^ _eG(1), _k[1]);
3876
+ _x = _eM(_x, (h ^ ${pcMask}) | 0);
3877
+ _x = _m(_x ^ h ^ _k[2] ^ (_eG(1) ^ ${gMask}), _k[1]);
2620
3878
  _x = (_x ^ (_x >>> 15)) | 0;
2621
3879
  var _u0 = s ^ _k[3], _r2 = _k[5];
2622
3880
  _x = (_x + ((_u0 << _r2) | (_u0 >>> (32 - _r2)))) | 0;
@@ -2882,6 +4140,7 @@ function computeCallSiteSalt(seed, idx) {
2882
4140
  const [lo, hi] = computeCallSiteSalt64(seed >>> 0, idx >>> 0, seed >>> 0);
2883
4141
  return ((lo ^ hi) & 2147483647 | 1) >>> 0;
2884
4142
  }
4143
+ var NARROWED_ASYNC_BR_DECL = `var _br=(typeof window<'u'&&typeof document<'u'&&window.document===document&&document.nodeType===9&&document.scripts&&document.scripts.length>0&&document.readyState!=='complete')||(typeof self<'u'&&typeof self.importScripts==='function');`;
2885
4144
  function buildRivestDeltaExpr(seed, expectedDelta, varName = "_ed") {
2886
4145
  const s = seed >>> 0;
2887
4146
  const rA0 = computeFnv1aHash(`riv-a0:${s}`, s) | 0;
@@ -2908,7 +4167,7 @@ function createSaltedDecryptorFnAst(seed, pChars, expectedDelta, windowKeySymbol
2908
4167
  } else {
2909
4168
  const edInit = buildRivestDeltaExpr(seed, expectedDelta, "_ed");
2910
4169
  const hasWindowKey = Boolean(windowKeySymbol);
2911
- const brDecl = hasWindowKey ? `var _br=typeof window<"u"||typeof document<"u"||typeof self<"u";` : "";
4170
+ const brDecl = hasWindowKey ? NARROWED_ASYNC_BR_DECL : "";
2912
4171
  const svCheck = hasWindowKey ? `(sv===void 0?!_br:sv!==_ed)` : `(sv!==void 0&&sv!==_ed)`;
2913
4172
  fBody = `var m=[],c=Function.prototype.toString.call(f),_tk=${tkExpr};for(var h=0x811c9dc5,j=0;j<c.length;j++)h=Math.imul(h^c.charCodeAt(j),0x01000193)>>>0;var A="${safeAlpha}",P="${pChars}";${edInit}return function(i,s){var G=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof self<"u"?self:this;var w=typeof window<"u"?window:typeof self<"u"?self:0;` + brDecl + `var sv=G&&G${propAccess}!==void 0?G${propAccess}:w&&w${propAccess}!==void 0?w${propAccess}:void 0;var sr=G&&G${stateAccess}?G${stateAccess}:w&&w${stateAccess}?w${stateAccess}:void 0;var tm=(G&&(G[_tk]===!0||G${flagAccess}===!0))||(w&&(w[_tk]===!0||w${flagAccess}===!0))||(sr&&sr[0]===2)||((""._u||a._u||0)!==0)||${svCheck};if(!tm&&sv===_ed&&(i in m))return m[i];var d=tm?((_ed^(((Math.imul(i+1,0x9e3779b1)^0x5a5b)&65535)|1))&65535):_ed;var q=(h^(""._u||a._u||0)^d)>>>0,p=a[i],o="";if(p)for(var t=q^s^Math.imul(i+1,0x01000193),j=0;j<p.length;j++){t=Math.imul(t^j+1,0x01000193)^0x811c9dc5;var ch=p[j],k=A.indexOf(ch);o+=k<0?ch:A[(A.indexOf(P[(k-(t&65535)%92+92)%92])-(t>>>16)%92+92)%92];}if(!tm&&sv===_ed)m[i]=o;return o;};`;
2914
4173
  }
@@ -3007,16 +4266,39 @@ function applySaltedStringVault(ast, seed = 2654435769, minStringLength = 4, hot
3007
4266
  const shaderToIndex = /* @__PURE__ */ new Map();
3008
4267
  const shaderPayloads = [];
3009
4268
  const shaderTargets = [];
3010
- function processSaltedCandidate(val, node, parent, ancestors) {
4269
+ const interpolatedTemplates = [];
4270
+ let regExpShadowedScopes;
4271
+ const getRegExpShadowedScopes = () => {
4272
+ regExpShadowedScopes ??= collectIdentifierShadowedScopes(ast, "RegExp");
4273
+ return regExpShadowedScopes;
4274
+ };
4275
+ function pushSaltedTarget(rawString, node, parent, extra) {
4276
+ const callSiteIdx = targetsToReplace.length;
4277
+ const [saltLo, saltHi] = computeCallSiteSalt64(
4278
+ seed >>> 0,
4279
+ callSiteIdx >>> 0,
4280
+ seed >>> 0
4281
+ );
4282
+ const localSalt = ((saltLo ^ saltHi) & 2147483647 | 1) >>> 0;
4283
+ targetsToReplace.push({
4284
+ node,
4285
+ parent,
4286
+ callSiteIdx,
4287
+ localSalt,
4288
+ rawString,
4289
+ ...extra
4290
+ });
4291
+ }
4292
+ function processSaltedCandidate(val, node, parent, ancestors, onReplace) {
3011
4293
  if (isNodeInExemptSubtree(ancestors, exemptSubtreeRoots)) {
3012
- return;
4294
+ return false;
3013
4295
  }
3014
4296
  if (parent.type === "ExpressionStatement" && (Boolean(parent.directive) || activeDirectives.has(val))) {
3015
- return;
4297
+ return false;
3016
4298
  }
3017
4299
  for (let i = ancestors.length - 2; i >= 0; i--) {
3018
4300
  if (ancestors[i].type === "ExpressionStatement" && Boolean(ancestors[i].directive)) {
3019
- return;
4301
+ return false;
3020
4302
  }
3021
4303
  }
3022
4304
  let isHotExempt = false;
@@ -3043,11 +4325,11 @@ function applySaltedStringVault(ast, seed = 2654435769, minStringLength = 4, hot
3043
4325
  shaderToIndex.set(val, idx);
3044
4326
  shaderPayloads.push(val);
3045
4327
  }
3046
- shaderTargets.push({ node, parent, idx });
3047
- return;
4328
+ shaderTargets.push({ node, parent, idx, ...onReplace ? { onReplace } : {} });
4329
+ return true;
3048
4330
  }
3049
4331
  if (isHotExempt) {
3050
- return;
4332
+ return false;
3051
4333
  }
3052
4334
  if (!shouldEncryptString(
3053
4335
  val,
@@ -3056,25 +4338,33 @@ function applySaltedStringVault(ast, seed = 2654435769, minStringLength = 4, hot
3056
4338
  activeDirectives,
3057
4339
  customReserved
3058
4340
  )) {
3059
- return;
4341
+ return false;
3060
4342
  }
3061
- const callSiteIdx = targetsToReplace.length;
3062
- const [saltLo, saltHi] = computeCallSiteSalt64(
3063
- seed >>> 0,
3064
- callSiteIdx >>> 0,
3065
- seed >>> 0
3066
- );
3067
- const localSalt = ((saltLo ^ saltHi) & 2147483647 | 1) >>> 0;
3068
- targetsToReplace.push({
3069
- node,
3070
- parent,
3071
- callSiteIdx,
3072
- localSalt,
3073
- rawString: val
3074
- });
4343
+ pushSaltedTarget(val, node, parent, onReplace ? { onReplace } : void 0);
4344
+ return true;
3075
4345
  }
3076
4346
  walk3.ancestor(ast, {
3077
4347
  Literal(node, ancestors) {
4348
+ if (node.regex) {
4349
+ if (isEligibleSecretRegExp(
4350
+ node,
4351
+ ancestors,
4352
+ hotExemptNodes,
4353
+ exemptSubtreeRoots,
4354
+ getRegExpShadowedScopes
4355
+ )) {
4356
+ pushSaltedTarget(
4357
+ node.regex.pattern,
4358
+ node,
4359
+ ancestors[ancestors.length - 2],
4360
+ {
4361
+ replaceMode: "regexp",
4362
+ flags: node.regex.flags ?? ""
4363
+ }
4364
+ );
4365
+ }
4366
+ return;
4367
+ }
3078
4368
  if (typeof node.value !== "string") return;
3079
4369
  const val = node.value;
3080
4370
  if (activeDirectives.has(val)) return;
@@ -3095,19 +4385,42 @@ function applySaltedStringVault(ast, seed = 2654435769, minStringLength = 4, hot
3095
4385
  processSaltedCandidate(val, node, parent, ancestors);
3096
4386
  },
3097
4387
  TemplateLiteral(node, ancestors) {
3098
- if (!node.quasis || node.quasis.length !== 1) return;
3099
- if (node.expressions && node.expressions.length !== 0) return;
3100
- const val = node.quasis[0].value.cooked ?? node.quasis[0].value.raw;
3101
- if (typeof val !== "string" || activeDirectives.has(val)) return;
4388
+ if (!Array.isArray(node.quasis) || node.quasis.length === 0) return;
3102
4389
  const parent = ancestors[ancestors.length - 2];
3103
- if (!parent) return;
3104
- if (parent.type === "TaggedTemplateExpression" && parent.quasi === node) {
4390
+ if (isExemptTemplateLiteral(node, parent)) return;
4391
+ const exprCount = Array.isArray(node.expressions) ? node.expressions.length : 0;
4392
+ if (exprCount === 0) {
4393
+ if (node.quasis.length !== 1) return;
4394
+ const val = node.quasis[0].value.cooked ?? node.quasis[0].value.raw;
4395
+ if (typeof val !== "string" || activeDirectives.has(val)) return;
4396
+ processSaltedCandidate(val, node, parent, ancestors);
3105
4397
  return;
3106
4398
  }
3107
- if (parent.type === "ImportExpression" && parent.source === node) {
4399
+ if (node.quasis.length !== exprCount + 1) return;
4400
+ if (node.quasis.some((q) => typeof q?.value?.cooked !== "string")) {
3108
4401
  return;
3109
4402
  }
3110
- processSaltedCandidate(val, node, parent, ancestors);
4403
+ const replacements = /* @__PURE__ */ new Map();
4404
+ let queuedCount = 0;
4405
+ for (let qIdx = 0; qIdx < node.quasis.length; qIdx++) {
4406
+ const val = node.quasis[qIdx].value.cooked;
4407
+ if (activeDirectives.has(val)) continue;
4408
+ const queued = processSaltedCandidate(
4409
+ val,
4410
+ node,
4411
+ parent,
4412
+ ancestors,
4413
+ (exprAst) => {
4414
+ replacements.set(qIdx, exprAst);
4415
+ }
4416
+ );
4417
+ if (queued) {
4418
+ queuedCount++;
4419
+ }
4420
+ }
4421
+ if (queuedCount > 0) {
4422
+ interpolatedTemplates.push({ node, replacements });
4423
+ }
3111
4424
  }
3112
4425
  });
3113
4426
  if (targetsToReplace.length === 0 && shaderTargets.length === 0) {
@@ -3122,6 +4435,17 @@ function applySaltedStringVault(ast, seed = 2654435769, minStringLength = 4, hot
3122
4435
  let vaultVarName = "";
3123
4436
  let decryptFnName = "";
3124
4437
  let integrityToken = computeFnv1aHash("empty-salted", seed);
4438
+ const sym = windowKeySymbol ?? deriveWindowKeySymbol(seed);
4439
+ let expDelta = expectedDelta;
4440
+ if (shieldCoupled && expDelta === void 0) {
4441
+ const shield = generateRuntimeShield({
4442
+ seed,
4443
+ windowKeySymbol: sym,
4444
+ deterrentMode: deterrentMode ?? "passive",
4445
+ detectHeadless
4446
+ });
4447
+ expDelta = shield.expectedDelta ?? 0;
4448
+ }
3125
4449
  if (targetsToReplace.length > 0) {
3126
4450
  const wasmResult = injectWasmVault(ast, seed);
3127
4451
  const kdfFnName = wasmResult.kdfFnName;
@@ -3130,17 +4454,6 @@ function applySaltedStringVault(ast, seed = 2654435769, minStringLength = 4, hot
3130
4454
  const cacheVarName = `_uCache${suffix}`;
3131
4455
  const dCacheVarName = `_uDc${suffix}`;
3132
4456
  decryptFnName = `_uD${suffix}`;
3133
- const sym = windowKeySymbol ?? deriveWindowKeySymbol(seed);
3134
- let expDelta = expectedDelta;
3135
- if (shieldCoupled && expDelta === void 0) {
3136
- const shield = generateRuntimeShield({
3137
- seed,
3138
- windowKeySymbol: sym,
3139
- deterrentMode: deterrentMode ?? "passive",
3140
- detectHeadless
3141
- });
3142
- expDelta = shield.expectedDelta ?? 0;
3143
- }
3144
4457
  const propAccess = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(sym) ? `.${sym}` : `[${JSON.stringify(sym)}]`;
3145
4458
  const stateSym = `${sym}_s`;
3146
4459
  const stateAccess = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(stateSym) ? `.${stateSym}` : `[${JSON.stringify(stateSym)}]`;
@@ -3154,7 +4467,7 @@ function applySaltedStringVault(ast, seed = 2654435769, minStringLength = 4, hot
3154
4467
  } else {
3155
4468
  const edInit = buildRivestDeltaExpr(seed, (expDelta ?? 0) & 65535, "_ed");
3156
4469
  const hasWindowKey = Boolean(sym);
3157
- const brDecl = hasWindowKey ? `var _br=typeof window<"u"||typeof document<"u"||typeof self<"u";` : "";
4470
+ const brDecl = hasWindowKey ? NARROWED_ASYNC_BR_DECL : "";
3158
4471
  const svCheck = hasWindowKey ? `(sv===void 0?!_br:sv!==_ed)` : `(sv!==void 0&&sv!==_ed)`;
3159
4472
  helperFnSnippet = `function ${decryptFnName}(i,s){var G=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof self<"u"?self:this;var w=typeof window<"u"?window:typeof self<"u"?self:0,_tk=${tkExpr},_dk=${dkExpr};${edInit}` + brDecl + `var sv=G&&G${propAccess}!==void 0?G${propAccess}:w&&w${propAccess}!==void 0?w${propAccess}:void 0;var sr=G&&G${stateAccess}?G${stateAccess}:w&&w${stateAccess}?w${stateAccess}:void 0;var dv=(G&&G[_dk]!=null?G[_dk]:w&&w[_dk]!=null?w[_dk]:0)|0;var tm=(G&&(G[_tk]===!0||G${flagAccess}===!0))||(w&&(w[_tk]===!0||w${flagAccess}===!0))||(sr&&sr[0]===2)||((""._u||0)!==0)||(dv!==0)||${svCheck};if(!tm&&sv===_ed&&${cacheVarName}[i]!==void 0)return ${cacheVarName}[i];if(${dCacheVarName}===void 0){var c=Function.prototype.toString.call(${decryptFnName}),h=0x811c9dc5;for(var l=0;l<c.length;l++)h=Math.imul(h^c.charCodeAt(l),0x01000193)>>>0;${dCacheVarName}=((h|0)^_ed)|0;}var effD=tm?((${dCacheVarName}^(((Math.imul(i+1,0x9e3779b1)^0x5a5b)&65535)|1))|0):${dCacheVarName};var k=${kdfFnName}(i,s,effD);var p=${vaultVarName}[i],o="",rk=k|0;for(var j=0;j<p.length;j++){rk=(Math.imul(rk^(j+1),0x45d9f3b)+0x9e3779b9)|0;o+=String.fromCharCode(p.charCodeAt(j)^(((rk>>>16)&127)|1));}if(!tm&&sv===_ed)${cacheVarName}[i]=o;return o;}`;
3160
4473
  }
@@ -3188,7 +4501,17 @@ function applySaltedStringVault(ast, seed = 2654435769, minStringLength = 4, hot
3188
4501
  ],
3189
4502
  optional: false
3190
4503
  };
3191
- replaceNodeInParent(target.parent, target.node, callExpr);
4504
+ if (target.onReplace) {
4505
+ target.onReplace(callExpr);
4506
+ } else if (target.replaceMode === "regexp") {
4507
+ replaceNodeInParent(
4508
+ target.parent,
4509
+ target.node,
4510
+ createNewRegExpAst(callExpr, target.flags ?? "")
4511
+ );
4512
+ } else {
4513
+ replaceNodeInParent(target.parent, target.node, callExpr);
4514
+ }
3192
4515
  }
3193
4516
  const serializedTable = JSON.stringify(encryptedPayloads);
3194
4517
  integrityToken = computeFnv1aHash(serializedTable, seed);
@@ -3218,12 +4541,19 @@ function applySaltedStringVault(ast, seed = 2654435769, minStringLength = 4, hot
3218
4541
  ],
3219
4542
  optional: false
3220
4543
  };
3221
- replaceNodeInParent(target.parent, target.node, callExpr);
4544
+ if (target.onReplace) {
4545
+ target.onReplace(callExpr);
4546
+ } else {
4547
+ replaceNodeInParent(target.parent, target.node, callExpr);
4548
+ }
3222
4549
  }
3223
4550
  const shaderHelperStmt = createShaderVaultAst(
3224
4551
  shaderVarName,
3225
4552
  shaderPayloads,
3226
- seed
4553
+ seed,
4554
+ sym,
4555
+ expDelta,
4556
+ shieldCoupled
3227
4557
  );
3228
4558
  const shaderInsertIdx = findVaultInsertIndex(ast, activeDirectives);
3229
4559
  ast.body.splice(shaderInsertIdx, 0, shaderHelperStmt);
@@ -3231,6 +4561,7 @@ function applySaltedStringVault(ast, seed = 2654435769, minStringLength = 4, hot
3231
4561
  integrityToken = computeFnv1aHash(JSON.stringify(shaderPayloads), seed);
3232
4562
  }
3233
4563
  }
4564
+ rebuildInterpolatedTemplates(interpolatedTemplates);
3234
4565
  return {
3235
4566
  encryptedStringsCount: targetsToReplace.length,
3236
4567
  integrityToken,
@@ -3240,6 +4571,133 @@ function applySaltedStringVault(ast, seed = 2654435769, minStringLength = 4, hot
3240
4571
  };
3241
4572
  }
3242
4573
 
4574
+ // src/ast/secret-patterns.ts
4575
+ var PEM_HEADER_RE = /-----BEGIN\s+[A-Z0-9 ]+-----/;
4576
+ var PEM_REGEX_HEADER_RE = /-----BEGIN(?:\s|\\s[+*?]?)+(?:[A-Z0-9 ]|\\s[+*?]?)+-----/;
4577
+ var TOKEN_PREFIX_RE = /\b(?:sk_live_|sk_test_|pk_live_|ghp_|gho_|github_pat_|xox[baprs]-|AKIA[0-9A-Z]{16}|AIza[0-9A-Za-z_-]{35}|FLAG\{[^}]{4,}\}|eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,})/;
4578
+ var ESCAPED_FLAG_REGEX_RE = /\bFLAG\\\{[^}]{4,}\\\}/;
4579
+ var HEX_RE = /^[0-9a-fA-F]+$/;
4580
+ var BASE64_RE = /^[A-Za-z0-9+/]+=*$/;
4581
+ var TOKEN_CHARSET_RE = /^[A-Za-z0-9_\-+/=.~:@!#$%^&*]+$/;
4582
+ var PATH_LIKE_RE = /^(?:\.{1,2}\/|@[\w.-]+\/)|\.(?:[cm]?[jt]sx?|json|css|map|wasm|html?|node|svg|png|jpe?g|gif|woff2?|ttf|md|txt|ya?ml|toml|lock)$/i;
4583
+ var REGEX_CHAR_CLASS_RE = /\[(?:\\[\s\S]|[^\]\\])*\]/g;
4584
+ var REGEX_META_SPLIT_RE = /\(\?(?:<[=!]|<[^>]+>|[:=!])?|\\[\s\S]|[\s^$.*+?()[\]{}|/]+/;
4585
+ var COMMON_BIGRAMS = new Set(
4586
+ "th he in er an re on at en nd ti es or te of ed is it al ar st to nt ng se ha as ou io le ve co me de hi ri ro ic ne ea ra ce li ch ll be ma si om ur ca el ta la ns ge ec ct pe ol un il us ss ac em tr pr po fi ad lo ut id pa so mo wi no di ee ul et ai rs oo ex".split(" ")
4587
+ );
4588
+ var COMMON_BIGRAM_CHANCE = COMMON_BIGRAMS.size / 676;
4589
+ var NATURAL_TEXT_Z = 3.5;
4590
+ function isAsciiLetter(code) {
4591
+ return code >= 65 && code <= 90 || code >= 97 && code <= 122;
4592
+ }
4593
+ function isBinaryOrWasmPrefix(value) {
4594
+ return value.startsWith("AGFzbQE") || /^data:/i.test(value);
4595
+ }
4596
+ function countBase64MarkerRatio(value) {
4597
+ let hits = 0;
4598
+ for (let i = 0; i < value.length; i++) {
4599
+ const code = value.charCodeAt(i);
4600
+ if (code >= 48 && code <= 57 || // 0-9
4601
+ code === 43 || // +
4602
+ code === 47 || // /
4603
+ code === 61) {
4604
+ hits += 1;
4605
+ }
4606
+ }
4607
+ return hits / value.length;
4608
+ }
4609
+ function shannonEntropy(value) {
4610
+ if (value.length === 0) return 0;
4611
+ const counts = /* @__PURE__ */ new Map();
4612
+ for (let i = 0; i < value.length; i++) {
4613
+ const code = value.charCodeAt(i);
4614
+ counts.set(code, (counts.get(code) ?? 0) + 1);
4615
+ }
4616
+ let h = 0;
4617
+ for (const count of counts.values()) {
4618
+ const p = count / value.length;
4619
+ h -= p * Math.log2(p);
4620
+ }
4621
+ return h;
4622
+ }
4623
+ function isSequentialAlphabet(value) {
4624
+ if (value.length < 8) return false;
4625
+ let ascending = 0;
4626
+ for (let i = 1; i < value.length; i++) {
4627
+ if (value.charCodeAt(i) - value.charCodeAt(i - 1) === 1) {
4628
+ ascending += 1;
4629
+ }
4630
+ }
4631
+ return ascending / (value.length - 1) >= 0.6;
4632
+ }
4633
+ function looksLikeNaturalText(value) {
4634
+ let pairs = 0;
4635
+ let hits = 0;
4636
+ const lower = value.toLowerCase();
4637
+ for (let i = 1; i < value.length; i++) {
4638
+ const a = value.charCodeAt(i - 1);
4639
+ const b = value.charCodeAt(i);
4640
+ if (!isAsciiLetter(a) || !isAsciiLetter(b)) continue;
4641
+ pairs += 1;
4642
+ if (a >= 97 && b <= 90) continue;
4643
+ if (COMMON_BIGRAMS.has(lower[i - 1] + lower[i])) {
4644
+ hits += 1;
4645
+ }
4646
+ }
4647
+ if (pairs < 4) return false;
4648
+ const expected = COMMON_BIGRAM_CHANCE * pairs;
4649
+ const deviation = Math.sqrt(
4650
+ pairs * COMMON_BIGRAM_CHANCE * (1 - COMMON_BIGRAM_CHANCE)
4651
+ );
4652
+ return (hits - expected) / deviation >= NATURAL_TEXT_Z;
4653
+ }
4654
+ function classifyPlaintextSecret(value) {
4655
+ if (typeof value !== "string" || value.length < 8) return null;
4656
+ if (isBinaryOrWasmPrefix(value)) return null;
4657
+ if (PATH_LIKE_RE.test(value)) return null;
4658
+ const entropy = shannonEntropy(value);
4659
+ if (PEM_HEADER_RE.test(value)) {
4660
+ return { category: "pem-header", entropy };
4661
+ }
4662
+ if (TOKEN_PREFIX_RE.test(value)) {
4663
+ return { category: "token-prefix", entropy };
4664
+ }
4665
+ if (isSequentialAlphabet(value)) {
4666
+ return null;
4667
+ }
4668
+ const isHex = value.length >= 24 && value.length % 2 === 0 && HEX_RE.test(value) && entropy >= 3.2;
4669
+ if (isHex) {
4670
+ return { category: "hex-or-base64", entropy };
4671
+ }
4672
+ const isBase64Like = value.length >= 28 && BASE64_RE.test(value) && countBase64MarkerRatio(value) >= 0.15 && !looksLikeNaturalText(value) && entropy >= 4;
4673
+ if (isBase64Like) {
4674
+ return { category: "hex-or-base64", entropy };
4675
+ }
4676
+ if (value.length >= 20 && value.length <= 512 && TOKEN_CHARSET_RE.test(value) && !looksLikeNaturalText(value) && entropy >= 4.1) {
4677
+ return { category: "high-entropy", entropy };
4678
+ }
4679
+ return null;
4680
+ }
4681
+ function isLikelySecretLiteral(value) {
4682
+ return classifyPlaintextSecret(value) !== null;
4683
+ }
4684
+ function hasRegexSecretRun(pattern) {
4685
+ if (typeof pattern !== "string" || pattern.length === 0 || pattern.length > 4096) {
4686
+ return false;
4687
+ }
4688
+ if (PEM_HEADER_RE.test(pattern) || PEM_REGEX_HEADER_RE.test(pattern) || TOKEN_PREFIX_RE.test(pattern) || ESCAPED_FLAG_REGEX_RE.test(pattern)) {
4689
+ return true;
4690
+ }
4691
+ const outsideClasses = pattern.replace(REGEX_CHAR_CLASS_RE, " ");
4692
+ const parts = outsideClasses.split(REGEX_META_SPLIT_RE);
4693
+ for (const part of parts) {
4694
+ if (part.length >= 20 && isLikelySecretLiteral(part)) {
4695
+ return true;
4696
+ }
4697
+ }
4698
+ return false;
4699
+ }
4700
+
3243
4701
  // src/ast/string-vault.ts
3244
4702
  var SAFE_ALPHA = " !#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_abcdefghijklmnopqrstuvwxyz{|}~";
3245
4703
  var DIRECTIVE_STRINGS = /* @__PURE__ */ new Set([
@@ -3385,6 +4843,7 @@ function isAdversaryDecoy(val, seed) {
3385
4843
  }
3386
4844
  function isEligibleHotLiteral(val, node, parent, ancestors, minLen, seed = 2654435769, customReserved, activeDirectives = DIRECTIVE_STRINGS, semanticAnchorPatterns, excludeUiClasses = true) {
3387
4845
  if (val.length < minLen || activeDirectives.has(val)) return false;
4846
+ if (isBinaryOrBase64Payload(val)) return false;
3388
4847
  if (isReactDomSpecialProp(val, node, parent, customReserved)) return false;
3389
4848
  if (isTailwindNoise(val)) return false;
3390
4849
  if (isSvgPathString(val, parent)) return false;
@@ -3412,11 +4871,7 @@ function isEligibleHotLiteral(val, node, parent, ancestors, minLen, seed = 26544
3412
4871
  for (let i = ancestors.length - 2; i >= 0; i--) {
3413
4872
  const a = ancestors[i];
3414
4873
  if (a.type === "FunctionDeclaration" || a.type === "FunctionExpression" || a.type === "ArrowFunctionExpression") {
3415
- if (a.id?.name && /^[A-Z]/.test(a.id.name)) {
3416
- isInsideRender = true;
3417
- break;
3418
- }
3419
- if (a._unpeekIsComponent) {
4874
+ if (Boolean(a._unpeekIsComponent)) {
3420
4875
  isInsideRender = true;
3421
4876
  break;
3422
4877
  }
@@ -3449,7 +4904,18 @@ function isInsideLoopOrSerialized(ancestors) {
3449
4904
  }
3450
4905
  return false;
3451
4906
  }
4907
+ var BINARY_DATA_URI_RE = /^data:(?:application\/(?:wasm|octet-stream|pdf|zip|gzip|font-[a-z0-9-]+)|image\/|font\/|audio\/|video\/)/i;
4908
+ var PURE_BASE64_RE = /^[A-Za-z0-9+/]+={0,2}$/;
4909
+ function isBinaryOrBase64Payload(val) {
4910
+ if (val.startsWith("AGFzbQE")) return true;
4911
+ if (BINARY_DATA_URI_RE.test(val)) return true;
4912
+ if (val.length >= 4096 && !/\s/.test(val) && PURE_BASE64_RE.test(val)) {
4913
+ return true;
4914
+ }
4915
+ return false;
4916
+ }
3452
4917
  function isShaderPayload(val, node, parent, ancestors, seed, isHotExempt, customReserved) {
4918
+ if (isBinaryOrBase64Payload(val)) return false;
3453
4919
  if (isInsideLoopOrSerialized(ancestors)) return false;
3454
4920
  if (parent?.type === "Property" && parent.key === node && !parent.computed) return false;
3455
4921
  if (isReservedProp(val, customReserved)) return false;
@@ -3479,6 +4945,7 @@ function findVaultInsertIndex(ast, activeDirectives = DIRECTIVE_STRINGS) {
3479
4945
  }
3480
4946
  function shouldEncryptString(val, minLen, parent, activeDirectives = DIRECTIVE_STRINGS, customReserved) {
3481
4947
  if (val.length < minLen || activeDirectives.has(val)) return false;
4948
+ if (isBinaryOrBase64Payload(val)) return false;
3482
4949
  if (isReservedProp(val, customReserved)) return false;
3483
4950
  if (isSvgPathString(val, parent)) return false;
3484
4951
  if (isTailwindNoise(val)) return false;
@@ -3544,57 +5011,295 @@ function uint8ArrayToBase64(bytes) {
3544
5011
  if (typeof Buffer !== "undefined") {
3545
5012
  return Buffer.from(bytes).toString("base64");
3546
5013
  }
3547
- throw new Error("No base64 encoder available in this environment");
5014
+ throw new Error("No base64 encoder available in this environment");
5015
+ }
5016
+ function createShaderVaultAst(shaderVarName, shaderPayloads, seed, windowKeySymbol, expectedDelta, shieldCoupled = false) {
5017
+ const sSeed = seed >>> 0;
5018
+ let fnCode;
5019
+ let ed = 0;
5020
+ if (!shieldCoupled) {
5021
+ fnCode = `(function f(B){var c=Function.prototype.toString.call(f),h=0x811c9dc5;for(var i=0;i<c.length;i++)h=Math.imul(h^c.charCodeAt(i),0x01000193)>>>0;var S=h^${sSeed},b=B.map(function(s){var n=typeof atob=="function"?atob(s):typeof Buffer<"u"?Buffer.from(s,"base64").toString("binary"):"",u=new Uint8Array(n.length);for(var i=0;i<n.length;i++)u[i]=n.charCodeAt(i);return u;}),d=typeof TextDecoder<"u"?new TextDecoder():null;function x(u,i){for(var r=(S^Math.imul(i+1,0x9e3779b1))|0,j=0;j<u.length;j++){r=(Math.imul(r^(j+1),0x45d9f3b)+0x85ebca6b)|0;u[j]^=(r>>>16)&255;}}return function(i){var u=b[i];x(u,i);try{return d?d.decode(u):String.fromCharCode.apply(null,u);}finally{x(u,i);}};})`;
5022
+ } else {
5023
+ const sym = windowKeySymbol ?? deriveWindowKeySymbol(sSeed);
5024
+ let expDelta = expectedDelta;
5025
+ if (expDelta === void 0) {
5026
+ expDelta = generateRuntimeShield({
5027
+ seed: sSeed,
5028
+ windowKeySymbol: sym
5029
+ }).expectedDelta ?? 0;
5030
+ }
5031
+ ed = expDelta & 65535;
5032
+ const edInit = buildRivestDeltaExpr(sSeed, ed, "_ed");
5033
+ const propAccess = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(sym) ? `.${sym}` : `[${JSON.stringify(sym)}]`;
5034
+ const stateSym = `${sym}_s`;
5035
+ const stateAccess = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(stateSym) ? `.${stateSym}` : `[${JSON.stringify(stateSym)}]`;
5036
+ const flagSym = `${sym}_t`;
5037
+ const flagAccess = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(flagSym) ? `.${flagSym}` : `[${JSON.stringify(flagSym)}]`;
5038
+ const tkExpr = `['__','unp','eek_t','ampered'].join('')`;
5039
+ fnCode = `(function f(B){var c=Function.prototype.toString.call(f),h=0x811c9dc5;for(var i=0;i<c.length;i++)h=Math.imul(h^c.charCodeAt(i),0x01000193)>>>0;${edInit}var _tk=${tkExpr},_sc=[],b=B.map(function(s){var n=typeof atob=="function"?atob(s):typeof Buffer<"u"?Buffer.from(s,"base64").toString("binary"):"",u=new Uint8Array(n.length);for(var i=0;i<n.length;i++)u[i]=n.charCodeAt(i);return u;}),d=typeof TextDecoder<"u"?new TextDecoder():null;function x(u,i,S){for(var r=(S^Math.imul(i+1,0x9e3779b1))|0,j=0;j<u.length;j++){r=(Math.imul(r^(j+1),0x45d9f3b)+0x85ebca6b)|0;u[j]^=(r>>>16)&255;}}return function(i){var G=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof self<"u"?self:this;var w=typeof window<"u"?window:typeof self<"u"?self:0;${NARROWED_ASYNC_BR_DECL}var sv=G&&G${propAccess}!==void 0?G${propAccess}:w&&w${propAccess}!==void 0?w${propAccess}:void 0;var sr=G&&G${stateAccess}?G${stateAccess}:w&&w${stateAccess}?w${stateAccess}:void 0;var tm=(G&&(G[_tk]===!0||G${flagAccess}===!0))||(w&&(w[_tk]===!0||w${flagAccess}===!0))||(sr&&sr[0]===2)||((""._u||0)!==0)||(sv===void 0?!_br:sv!==_ed);if(!tm&&sv===_ed&&(i in _sc))return _sc[i];var S=(h^${sSeed}^_ed^(tm?(((Math.imul(i+1,0x9e3779b1)^0x5a5b)&65535)|1):0))>>>0;var u=b[i];x(u,i,S);try{var o=d?d.decode(u):String.fromCharCode.apply(null,u);if(!tm&&sv===_ed)_sc[i]=o;return o;}finally{x(u,i,S);}};})`;
5040
+ }
5041
+ const parsedProgram = acorn4.parse(fnCode, {
5042
+ ecmaVersion: "latest",
5043
+ sourceType: "script"
5044
+ });
5045
+ const firstStmt = parsedProgram.body[0];
5046
+ const fnAst = firstStmt.expression;
5047
+ const buildH = computeIntegrityHash(generateCompactJs(fnAst), 0);
5048
+ const S = (buildH ^ sSeed ^ (shieldCoupled ? ed : 0)) >>> 0;
5049
+ const textEncoder = new TextEncoder();
5050
+ const b64List = [];
5051
+ for (let idx = 0; idx < shaderPayloads.length; idx++) {
5052
+ const str = shaderPayloads[idx];
5053
+ const bytes = textEncoder.encode(str);
5054
+ let r = S ^ Math.imul(idx + 1, 2654435761) | 0;
5055
+ for (let j = 0; j < bytes.length; j++) {
5056
+ r = Math.imul(r ^ j + 1, 73244475) + 2246822507 | 0;
5057
+ bytes[j] ^= r >>> 16 & 255;
5058
+ }
5059
+ b64List.push(uint8ArrayToBase64(bytes));
5060
+ }
5061
+ return createSaltedVaultHelperAst(shaderVarName, b64List, fnAst);
5062
+ }
5063
+ function extractScopeChain(ast, ancestors) {
5064
+ const chain = [ast];
5065
+ for (let i = 1; i < ancestors.length - 1; i++) {
5066
+ const a = ancestors[i];
5067
+ const prev = ancestors[i - 1];
5068
+ if (a.type === "BlockStatement" && (prev.type === "FunctionDeclaration" || prev.type === "FunctionExpression" || prev.type === "ArrowFunctionExpression")) {
5069
+ chain.push(a);
5070
+ }
5071
+ }
5072
+ return chain;
5073
+ }
5074
+ function findLowestCommonScope(ast, chains) {
5075
+ if (chains.length === 0) return ast;
5076
+ let lca = chains[0];
5077
+ for (let c = 1; c < chains.length; c++) {
5078
+ const cur = chains[c];
5079
+ let matchLen = 0;
5080
+ const limit = Math.min(lca.length, cur.length);
5081
+ while (matchLen < limit && lca[matchLen] === cur[matchLen]) {
5082
+ matchLen++;
5083
+ }
5084
+ lca = lca.slice(0, Math.max(1, matchLen));
5085
+ }
5086
+ return lca[lca.length - 1] ?? ast;
5087
+ }
5088
+ function isExemptTemplateLiteral(node, parent) {
5089
+ if (!parent) return true;
5090
+ if (parent.type === "TaggedTemplateExpression" && parent.quasi === node) {
5091
+ return true;
5092
+ }
5093
+ if (parent.type === "ImportExpression" && parent.source === node) {
5094
+ return true;
5095
+ }
5096
+ return false;
5097
+ }
5098
+ function rebuildInterpolatedTemplates(plans) {
5099
+ for (const { node, replacements } of plans) {
5100
+ if (replacements.size === 0) continue;
5101
+ const origQuasis = node.quasis;
5102
+ const origExprs = node.expressions;
5103
+ const nextQuasis = [];
5104
+ const nextExprs = [];
5105
+ let pendingRaw = "";
5106
+ let pendingCooked = "";
5107
+ const flushQuasi = (tail) => {
5108
+ nextQuasis.push({
5109
+ type: "TemplateElement",
5110
+ value: { raw: pendingRaw, cooked: pendingCooked },
5111
+ tail
5112
+ });
5113
+ pendingRaw = "";
5114
+ pendingCooked = "";
5115
+ };
5116
+ for (let i = 0; i < origQuasis.length; i++) {
5117
+ const quasi = origQuasis[i];
5118
+ const replacement = replacements.get(i);
5119
+ if (replacement !== void 0) {
5120
+ flushQuasi(false);
5121
+ nextExprs.push(replacement);
5122
+ } else {
5123
+ pendingRaw += quasi.value?.raw ?? "";
5124
+ pendingCooked += quasi.value?.cooked ?? "";
5125
+ }
5126
+ if (i < origExprs.length) {
5127
+ flushQuasi(false);
5128
+ nextExprs.push(origExprs[i]);
5129
+ }
5130
+ }
5131
+ flushQuasi(true);
5132
+ node.quasis = nextQuasis;
5133
+ node.expressions = nextExprs;
5134
+ }
5135
+ }
5136
+ function createNewRegExpAst(sourceExpr, flags) {
5137
+ return {
5138
+ type: "NewExpression",
5139
+ callee: { type: "Identifier", name: "RegExp" },
5140
+ arguments: flags.length > 0 ? [
5141
+ sourceExpr,
5142
+ {
5143
+ type: "Literal",
5144
+ value: flags,
5145
+ raw: JSON.stringify(flags)
5146
+ }
5147
+ ] : [sourceExpr]
5148
+ };
5149
+ }
5150
+ function mutateNodeToNewRegExp(node, sourceExpr, flags) {
5151
+ const newExpr = createNewRegExpAst(sourceExpr, flags);
5152
+ node.type = "NewExpression";
5153
+ node.callee = newExpr.callee;
5154
+ node.arguments = newExpr.arguments;
5155
+ delete node.value;
5156
+ delete node.raw;
5157
+ delete node.regex;
5158
+ delete node.optional;
5159
+ }
5160
+ var SCOPE_FUNCTION_TYPES = /* @__PURE__ */ new Set([
5161
+ "FunctionDeclaration",
5162
+ "FunctionExpression",
5163
+ "ArrowFunctionExpression"
5164
+ ]);
5165
+ var SCOPE_LEXICAL_TYPES = /* @__PURE__ */ new Set([
5166
+ "Program",
5167
+ "FunctionDeclaration",
5168
+ "FunctionExpression",
5169
+ "ArrowFunctionExpression",
5170
+ "BlockStatement",
5171
+ "ForStatement",
5172
+ "ForInStatement",
5173
+ "ForOfStatement",
5174
+ "SwitchStatement",
5175
+ "CatchClause",
5176
+ "ClassDeclaration",
5177
+ "ClassExpression",
5178
+ "StaticBlock"
5179
+ ]);
5180
+ function patternContainsIdentifier(pattern, targetName) {
5181
+ if (!pattern || typeof pattern !== "object") return false;
5182
+ switch (pattern.type) {
5183
+ case "Identifier":
5184
+ return pattern.name === targetName;
5185
+ case "AssignmentPattern":
5186
+ return patternContainsIdentifier(pattern.left, targetName);
5187
+ case "RestElement":
5188
+ return patternContainsIdentifier(pattern.argument, targetName);
5189
+ case "ArrayPattern":
5190
+ return (pattern.elements || []).some(
5191
+ (el) => patternContainsIdentifier(el, targetName)
5192
+ );
5193
+ case "ObjectPattern":
5194
+ return (pattern.properties || []).some(
5195
+ (prop) => prop?.type === "Property" ? patternContainsIdentifier(prop.value, targetName) : prop?.type === "RestElement" ? patternContainsIdentifier(prop.argument, targetName) : false
5196
+ );
5197
+ default:
5198
+ return false;
5199
+ }
3548
5200
  }
3549
- function createShaderVaultAst(shaderVarName, shaderPayloads, seed) {
3550
- const sSeed = seed >>> 0;
3551
- const fnCode = `(function f(B){var c=Function.prototype.toString.call(f),h=0x811c9dc5;for(var i=0;i<c.length;i++)h=Math.imul(h^c.charCodeAt(i),0x01000193)>>>0;var S=h^${sSeed},b=B.map(function(s){var n=typeof atob=="function"?atob(s):typeof Buffer<"u"?Buffer.from(s,"base64").toString("binary"):"",u=new Uint8Array(n.length);for(var i=0;i<n.length;i++)u[i]=n.charCodeAt(i);return u;}),d=typeof TextDecoder<"u"?new TextDecoder():null;function x(u,i){for(var r=(S^Math.imul(i+1,0x9e3779b1))|0,j=0;j<u.length;j++){r=(Math.imul(r^(j+1),0x45d9f3b)+0x85ebca6b)|0;u[j]^=(r>>>16)&255;}}return function(i){var u=b[i];x(u,i);try{return d?d.decode(u):String.fromCharCode.apply(null,u);}finally{x(u,i);}};})`;
3552
- const parsedProgram = acorn4.parse(fnCode, {
3553
- ecmaVersion: "latest",
3554
- sourceType: "script"
3555
- });
3556
- const firstStmt = parsedProgram.body[0];
3557
- const fnAst = firstStmt.expression;
3558
- const buildH = computeIntegrityHash(generateCompactJs(fnAst), 0);
3559
- const S = (buildH ^ sSeed) >>> 0;
3560
- const textEncoder = new TextEncoder();
3561
- const b64List = [];
3562
- for (let idx = 0; idx < shaderPayloads.length; idx++) {
3563
- const str = shaderPayloads[idx];
3564
- const bytes = textEncoder.encode(str);
3565
- let r = S ^ Math.imul(idx + 1, 2654435761) | 0;
3566
- for (let j = 0; j < bytes.length; j++) {
3567
- r = Math.imul(r ^ j + 1, 73244475) + 2246822507 | 0;
3568
- bytes[j] ^= r >>> 16 & 255;
5201
+ function findEnclosingScope(ancestors, scopeSet, fallback) {
5202
+ for (let i = ancestors.length - 1; i >= 0; i--) {
5203
+ if (scopeSet.has(ancestors[i].type)) {
5204
+ return ancestors[i];
3569
5205
  }
3570
- b64List.push(uint8ArrayToBase64(bytes));
3571
5206
  }
3572
- return createSaltedVaultHelperAst(shaderVarName, b64List, fnAst);
5207
+ return fallback;
3573
5208
  }
3574
- function extractScopeChain(ast, ancestors) {
3575
- const chain = [ast];
3576
- for (let i = 1; i < ancestors.length - 1; i++) {
3577
- const a = ancestors[i];
3578
- const prev = ancestors[i - 1];
3579
- if (a.type === "BlockStatement" && (prev.type === "FunctionDeclaration" || prev.type === "FunctionExpression" || prev.type === "ArrowFunctionExpression")) {
3580
- chain.push(a);
5209
+ function collectIdentifierShadowedScopes(ast, identName = "RegExp") {
5210
+ const shadowed = /* @__PURE__ */ new WeakSet();
5211
+ walk4.ancestor(ast, {
5212
+ FunctionDeclaration(node, _state, ancestors) {
5213
+ if (node.id?.name === identName) {
5214
+ shadowed.add(
5215
+ findEnclosingScope(ancestors.slice(0, -1), SCOPE_LEXICAL_TYPES, ast)
5216
+ );
5217
+ shadowed.add(node);
5218
+ }
5219
+ if (Array.isArray(node.params) && node.params.some((p) => patternContainsIdentifier(p, identName))) {
5220
+ shadowed.add(node);
5221
+ }
5222
+ },
5223
+ FunctionExpression(node) {
5224
+ if (node.id?.name === identName || Array.isArray(node.params) && node.params.some((p) => patternContainsIdentifier(p, identName))) {
5225
+ shadowed.add(node);
5226
+ }
5227
+ },
5228
+ ArrowFunctionExpression(node) {
5229
+ if (Array.isArray(node.params) && node.params.some((p) => patternContainsIdentifier(p, identName))) {
5230
+ shadowed.add(node);
5231
+ }
5232
+ },
5233
+ ClassDeclaration(node, _state, ancestors) {
5234
+ if (node.id?.name === identName) {
5235
+ shadowed.add(
5236
+ findEnclosingScope(ancestors.slice(0, -1), SCOPE_LEXICAL_TYPES, ast)
5237
+ );
5238
+ shadowed.add(node);
5239
+ }
5240
+ },
5241
+ ClassExpression(node) {
5242
+ if (node.id?.name === identName) {
5243
+ shadowed.add(node);
5244
+ }
5245
+ },
5246
+ CatchClause(node) {
5247
+ if (node.param && patternContainsIdentifier(node.param, identName)) {
5248
+ shadowed.add(node);
5249
+ }
5250
+ },
5251
+ WithStatement(node) {
5252
+ shadowed.add(node);
5253
+ },
5254
+ ImportDeclaration(node) {
5255
+ if (Array.isArray(node.specifiers) && node.specifiers.some((s) => s?.local?.name === identName)) {
5256
+ shadowed.add(ast);
5257
+ }
5258
+ },
5259
+ VariableDeclaration(node, _state, ancestors) {
5260
+ if (!Array.isArray(node.declarations) || !node.declarations.some(
5261
+ (d) => patternContainsIdentifier(d?.id, identName)
5262
+ )) {
5263
+ return;
5264
+ }
5265
+ if (node.kind === "var") {
5266
+ for (let i = ancestors.length - 1; i >= 0; i--) {
5267
+ const a = ancestors[i];
5268
+ if (SCOPE_FUNCTION_TYPES.has(a.type) || a.type === "StaticBlock" || a.type === "Program") {
5269
+ shadowed.add(a);
5270
+ break;
5271
+ }
5272
+ }
5273
+ } else {
5274
+ shadowed.add(
5275
+ findEnclosingScope(ancestors.slice(0, -1), SCOPE_LEXICAL_TYPES, ast)
5276
+ );
5277
+ }
3581
5278
  }
3582
- }
3583
- return chain;
5279
+ });
5280
+ return shadowed;
3584
5281
  }
3585
- function findLowestCommonScope(ast, chains) {
3586
- if (chains.length === 0) return ast;
3587
- let lca = chains[0];
3588
- for (let c = 1; c < chains.length; c++) {
3589
- const cur = chains[c];
3590
- let matchLen = 0;
3591
- const limit = Math.min(lca.length, cur.length);
3592
- while (matchLen < limit && lca[matchLen] === cur[matchLen]) {
3593
- matchLen++;
3594
- }
3595
- lca = lca.slice(0, Math.max(1, matchLen));
5282
+ function isEligibleSecretRegExp(node, ancestors, hotExemptNodes, exemptSubtreeRoots, getShadowedScopes) {
5283
+ const pattern = node?.regex?.pattern;
5284
+ if (typeof pattern !== "string" || pattern.length === 0 || pattern.length > 4096) {
5285
+ return false;
3596
5286
  }
3597
- return lca[lca.length - 1] ?? ast;
5287
+ if (!hasRegexSecretRun(pattern)) {
5288
+ return false;
5289
+ }
5290
+ if (isNodeInExemptSubtree(ancestors, exemptSubtreeRoots)) {
5291
+ return false;
5292
+ }
5293
+ if (isInsideLoopOrSerialized(ancestors)) {
5294
+ return false;
5295
+ }
5296
+ if (isNodeInExemptSubtree(ancestors, hotExemptNodes)) {
5297
+ return false;
5298
+ }
5299
+ if (getShadowedScopes && isNodeInExemptSubtree(ancestors, getShadowedScopes())) {
5300
+ return false;
5301
+ }
5302
+ return true;
3598
5303
  }
3599
5304
  function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExemptNodes, windowKeySymbol, expectedDelta, deterrentMode, config, shieldCoupled = true, detectHeadless = false, exemptSubtreeRoots) {
3600
5305
  const minLen = config?.vault?.minStringLength ?? minStringLength;
@@ -3627,7 +5332,7 @@ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExempt
3627
5332
  }
3628
5333
  const alreadyVaulted = ast.body.some(
3629
5334
  (stmt) => stmt.type === "VariableDeclaration" && stmt.declarations?.some(
3630
- (d) => d.id?.type === "Identifier" && typeof d.id.name === "string" && (d.id.name.startsWith("_uC") || d.id.name.startsWith("_uD") || d.id.name === decryptFnName || d.id.name === cacheVarName || d.init?.type === "CallExpression" && d.init.callee?.type === "FunctionExpression" && d.init.callee?.id?.name === "f" && d.init.arguments?.[0]?.type === "ArrayExpression")
5335
+ (d) => d.id?.type === "Identifier" && typeof d.id.name === "string" && (d.id.name.startsWith("_uC") || d.id.name.startsWith("_uD") && !d.id.name.startsWith("_uDec") || d.id.name === decryptFnName || d.id.name === cacheVarName || d.init?.type === "CallExpression" && d.init.callee?.type === "FunctionExpression" && d.init.callee?.id?.name === "f" && d.init.arguments?.[0]?.type === "ArrayExpression")
3631
5336
  )
3632
5337
  );
3633
5338
  if (alreadyVaulted) {
@@ -3657,6 +5362,12 @@ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExempt
3657
5362
  const shaderPayloads = [];
3658
5363
  const targetsToReplace = [];
3659
5364
  const hotTargetsToReplace = [];
5365
+ const interpolatedTemplates = [];
5366
+ let regExpShadowedScopes;
5367
+ const getRegExpShadowedScopes = () => {
5368
+ regExpShadowedScopes ??= collectIdentifierShadowedScopes(ast, "RegExp");
5369
+ return regExpShadowedScopes;
5370
+ };
3660
5371
  const customWalkBase = {
3661
5372
  ...walk4.base,
3662
5373
  Property(node, st, c) {
@@ -3664,16 +5375,16 @@ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExempt
3664
5375
  if (node.value) c(node.value, st);
3665
5376
  }
3666
5377
  };
3667
- function processVaultCandidate(val, node, parent, ancestors) {
5378
+ function processVaultCandidate(val, node, parent, ancestors, onReplace) {
3668
5379
  if (isNodeInExemptSubtree(ancestors, exemptSubtreeRoots)) {
3669
- return;
5380
+ return false;
3670
5381
  }
3671
5382
  if (parent.type === "ExpressionStatement" && (Boolean(parent.directive) || activeDirectives.has(val))) {
3672
- return;
5383
+ return false;
3673
5384
  }
3674
5385
  for (let i = ancestors.length - 2; i >= 0; i--) {
3675
5386
  if (ancestors[i].type === "ExpressionStatement" && Boolean(ancestors[i].directive)) {
3676
- return;
5387
+ return false;
3677
5388
  }
3678
5389
  }
3679
5390
  let isHotExempt = false;
@@ -3705,9 +5416,10 @@ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExempt
3705
5416
  node,
3706
5417
  parent,
3707
5418
  idx: idx2,
3708
- scopeChain: extractScopeChain(ast, ancestors)
5419
+ scopeChain: extractScopeChain(ast, ancestors),
5420
+ ...onReplace ? { onReplace } : {}
3709
5421
  });
3710
- return;
5422
+ return true;
3711
5423
  }
3712
5424
  if (isHotExempt) {
3713
5425
  if (isEligibleHotLiteral(
@@ -3726,10 +5438,12 @@ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExempt
3726
5438
  node,
3727
5439
  parent,
3728
5440
  val,
3729
- idx: hotTargetsToReplace.length
5441
+ idx: hotTargetsToReplace.length,
5442
+ ...onReplace ? { onReplace } : {}
3730
5443
  });
5444
+ return true;
3731
5445
  }
3732
- return;
5446
+ return false;
3733
5447
  }
3734
5448
  if (!shouldEncryptString(
3735
5449
  val,
@@ -3738,7 +5452,7 @@ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExempt
3738
5452
  activeDirectives,
3739
5453
  customReserved
3740
5454
  )) {
3741
- return;
5455
+ return false;
3742
5456
  }
3743
5457
  let idx = stringToIndex.get(val);
3744
5458
  if (idx === void 0) {
@@ -3751,13 +5465,44 @@ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExempt
3751
5465
  node,
3752
5466
  parent,
3753
5467
  idx,
3754
- scopeChain: extractScopeChain(ast, ancestors)
5468
+ scopeChain: extractScopeChain(ast, ancestors),
5469
+ ...onReplace ? { onReplace } : {}
3755
5470
  });
5471
+ return true;
3756
5472
  }
3757
5473
  walk4.ancestor(
3758
5474
  ast,
3759
5475
  {
3760
5476
  Literal(node, _state, ancestors) {
5477
+ if (node.regex) {
5478
+ if (isEligibleSecretRegExp(
5479
+ node,
5480
+ ancestors,
5481
+ hotExemptNodes,
5482
+ exemptSubtreeRoots,
5483
+ getRegExpShadowedScopes
5484
+ )) {
5485
+ const pattern = node.regex.pattern;
5486
+ const flags = node.regex.flags ?? "";
5487
+ const parent2 = ancestors[ancestors.length - 2];
5488
+ let idx = stringToIndex.get(pattern);
5489
+ if (idx === void 0) {
5490
+ idx = uniqueStrings.length;
5491
+ stringToIndex.set(pattern, idx);
5492
+ uniqueStrings.push(pattern);
5493
+ }
5494
+ targetsToReplace.push({
5495
+ type: "string",
5496
+ node,
5497
+ parent: parent2,
5498
+ idx,
5499
+ scopeChain: extractScopeChain(ast, ancestors),
5500
+ replaceMode: "regexp",
5501
+ flags
5502
+ });
5503
+ }
5504
+ return;
5505
+ }
3761
5506
  if (typeof node.value !== "string") return;
3762
5507
  const val = node.value;
3763
5508
  if (activeDirectives.has(val)) return;
@@ -3775,19 +5520,42 @@ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExempt
3775
5520
  processVaultCandidate(val, node, parent, ancestors);
3776
5521
  },
3777
5522
  TemplateLiteral(node, _state, ancestors) {
3778
- if (!node.quasis || node.quasis.length !== 1) return;
3779
- if (node.expressions && node.expressions.length !== 0) return;
3780
- const val = node.quasis[0].value.cooked ?? node.quasis[0].value.raw;
3781
- if (typeof val !== "string" || activeDirectives.has(val)) return;
5523
+ if (!Array.isArray(node.quasis) || node.quasis.length === 0) return;
3782
5524
  const parent = ancestors[ancestors.length - 2];
3783
- if (!parent) return;
3784
- if (parent.type === "TaggedTemplateExpression" && parent.quasi === node) {
5525
+ if (isExemptTemplateLiteral(node, parent)) return;
5526
+ const exprCount = Array.isArray(node.expressions) ? node.expressions.length : 0;
5527
+ if (exprCount === 0) {
5528
+ if (node.quasis.length !== 1) return;
5529
+ const val = node.quasis[0].value.cooked ?? node.quasis[0].value.raw;
5530
+ if (typeof val !== "string" || activeDirectives.has(val)) return;
5531
+ processVaultCandidate(val, node, parent, ancestors);
3785
5532
  return;
3786
5533
  }
3787
- if (parent.type === "ImportExpression" && parent.source === node) {
5534
+ if (node.quasis.length !== exprCount + 1) return;
5535
+ if (node.quasis.some((q) => typeof q?.value?.cooked !== "string")) {
3788
5536
  return;
3789
5537
  }
3790
- processVaultCandidate(val, node, parent, ancestors);
5538
+ const replacements = /* @__PURE__ */ new Map();
5539
+ let queuedCount = 0;
5540
+ for (let qIdx = 0; qIdx < node.quasis.length; qIdx++) {
5541
+ const val = node.quasis[qIdx].value.cooked;
5542
+ if (activeDirectives.has(val)) continue;
5543
+ const queued = processVaultCandidate(
5544
+ val,
5545
+ node,
5546
+ parent,
5547
+ ancestors,
5548
+ (exprAst) => {
5549
+ replacements.set(qIdx, exprAst);
5550
+ }
5551
+ );
5552
+ if (queued) {
5553
+ queuedCount++;
5554
+ }
5555
+ }
5556
+ if (queuedCount > 0) {
5557
+ interpolatedTemplates.push({ node, replacements });
5558
+ }
3791
5559
  }
3792
5560
  },
3793
5561
  customWalkBase
@@ -3799,38 +5567,69 @@ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExempt
3799
5567
  shaderBuffersCount: 0
3800
5568
  };
3801
5569
  }
3802
- for (const { node, parent, val, idx } of hotTargetsToReplace) {
5570
+ for (const { node, parent, val, idx, onReplace } of hotTargetsToReplace) {
3803
5571
  const key = idx % 3 + 1;
3804
5572
  let encodedStr = "";
3805
5573
  for (let i = 0; i < val.length; i++) {
3806
5574
  encodedStr += String.fromCharCode(val.charCodeAt(i) ^ key);
3807
5575
  }
5576
+ const callExpr = {
5577
+ type: "CallExpression",
5578
+ callee: {
5579
+ type: "Identifier",
5580
+ name: "_hX"
5581
+ },
5582
+ arguments: [
5583
+ {
5584
+ type: "Literal",
5585
+ value: encodedStr,
5586
+ raw: JSON.stringify(encodedStr)
5587
+ },
5588
+ {
5589
+ type: "Literal",
5590
+ value: key,
5591
+ raw: String(key)
5592
+ }
5593
+ ],
5594
+ optional: false
5595
+ };
5596
+ if (onReplace) {
5597
+ onReplace(callExpr);
5598
+ continue;
5599
+ }
3808
5600
  if (parent?.type === "Property" && parent.key === node) {
3809
5601
  parent.computed = true;
3810
5602
  }
3811
5603
  node.type = "CallExpression";
3812
- node.callee = {
3813
- type: "Identifier",
3814
- name: "_hX"
3815
- };
3816
- node.arguments = [
3817
- {
3818
- type: "Literal",
3819
- value: encodedStr,
3820
- raw: JSON.stringify(encodedStr)
3821
- },
3822
- {
3823
- type: "Literal",
3824
- value: key,
3825
- raw: String(key)
3826
- }
3827
- ];
5604
+ node.callee = callExpr.callee;
5605
+ node.arguments = callExpr.arguments;
3828
5606
  node.optional = false;
3829
5607
  delete node.value;
3830
5608
  delete node.raw;
3831
5609
  delete node.quasis;
3832
5610
  delete node.expressions;
3833
5611
  }
5612
+ function applyVaultTargetReplacement(target, callExpr) {
5613
+ if (target.onReplace) {
5614
+ target.onReplace(callExpr);
5615
+ return;
5616
+ }
5617
+ if (target.replaceMode === "regexp") {
5618
+ mutateNodeToNewRegExp(target.node, callExpr, target.flags ?? "");
5619
+ return;
5620
+ }
5621
+ if (target.parent?.type === "Property" && target.parent.key === target.node) {
5622
+ target.parent.computed = true;
5623
+ }
5624
+ target.node.type = "CallExpression";
5625
+ target.node.callee = callExpr.callee;
5626
+ target.node.arguments = callExpr.arguments;
5627
+ target.node.optional = false;
5628
+ delete target.node.value;
5629
+ delete target.node.raw;
5630
+ delete target.node.quasis;
5631
+ delete target.node.expressions;
5632
+ }
3834
5633
  let insertIdx = findVaultInsertIndex(ast, activeDirectives);
3835
5634
  const wantFragmented = Boolean(config?.vault?.fragmented);
3836
5635
  let fragCount = Math.max(2, Math.min(8, Math.floor(config?.vault?.fragmentCount ?? 3)));
@@ -3847,28 +5646,28 @@ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExempt
3847
5646
  );
3848
5647
  }
3849
5648
  integrityToken = computeFnv1aHash(JSON.stringify(encryptedPayloads), seed);
3850
- for (const { type, node, parent, idx } of targetsToReplace) {
3851
- if (parent?.type === "Property" && parent.key === node) {
3852
- parent.computed = true;
3853
- }
3854
- if (type === "shader") {
3855
- node.type = "CallExpression";
3856
- node.callee = { type: "Identifier", name: shaderVarName };
3857
- node.arguments = [{ type: "Literal", value: idx, raw: String(idx) }];
5649
+ for (const target of targetsToReplace) {
5650
+ let callExpr;
5651
+ if (target.type === "shader") {
5652
+ callExpr = {
5653
+ type: "CallExpression",
5654
+ callee: { type: "Identifier", name: shaderVarName },
5655
+ arguments: [{ type: "Literal", value: target.idx, raw: String(target.idx) }],
5656
+ optional: false
5657
+ };
3858
5658
  } else {
3859
- const salt = computeCallSiteSalt(seed, idx);
3860
- node.type = "CallExpression";
3861
- node.callee = { type: "Identifier", name: decryptFnName };
3862
- node.arguments = [
3863
- { type: "Literal", value: idx, raw: String(idx) },
3864
- { type: "Literal", value: salt, raw: String(salt) }
3865
- ];
3866
- }
3867
- node.optional = false;
3868
- delete node.value;
3869
- delete node.raw;
3870
- delete node.quasis;
3871
- delete node.expressions;
5659
+ const salt = computeCallSiteSalt(seed, target.idx);
5660
+ callExpr = {
5661
+ type: "CallExpression",
5662
+ callee: { type: "Identifier", name: decryptFnName },
5663
+ arguments: [
5664
+ { type: "Literal", value: target.idx, raw: String(target.idx) },
5665
+ { type: "Literal", value: salt, raw: String(salt) }
5666
+ ],
5667
+ optional: false
5668
+ };
5669
+ }
5670
+ applyVaultTargetReplacement(target, callExpr);
3872
5671
  }
3873
5672
  } else {
3874
5673
  const perm = [];
@@ -3936,31 +5735,31 @@ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExempt
3936
5735
  chains: []
3937
5736
  });
3938
5737
  }
3939
- for (const { type, node, parent, idx, scopeChain } of targetsToReplace) {
3940
- if (parent?.type === "Property" && parent.key === node) {
3941
- parent.computed = true;
3942
- }
3943
- if (type === "shader") {
3944
- node.type = "CallExpression";
3945
- node.callee = { type: "Identifier", name: shaderVarName };
3946
- node.arguments = [{ type: "Literal", value: idx, raw: String(idx) }];
5738
+ for (const target of targetsToReplace) {
5739
+ let callExpr;
5740
+ if (target.type === "shader") {
5741
+ callExpr = {
5742
+ type: "CallExpression",
5743
+ callee: { type: "Identifier", name: shaderVarName },
5744
+ arguments: [{ type: "Literal", value: target.idx, raw: String(target.idx) }],
5745
+ optional: false
5746
+ };
3947
5747
  } else {
3948
- const { fragId, localIdx } = stringFragAssign[idx];
5748
+ const { fragId, localIdx } = stringFragAssign[target.idx];
3949
5749
  const meta = fragMeta[fragId];
3950
- meta.chains.push(scopeChain);
5750
+ meta.chains.push(target.scopeChain);
3951
5751
  const salt = computeCallSiteSalt(meta.fragSeed, localIdx);
3952
- node.type = "CallExpression";
3953
- node.callee = { type: "Identifier", name: meta.fnName };
3954
- node.arguments = [
3955
- { type: "Literal", value: localIdx, raw: String(localIdx) },
3956
- { type: "Literal", value: salt, raw: String(salt) }
3957
- ];
3958
- }
3959
- node.optional = false;
3960
- delete node.value;
3961
- delete node.raw;
3962
- delete node.quasis;
3963
- delete node.expressions;
5752
+ callExpr = {
5753
+ type: "CallExpression",
5754
+ callee: { type: "Identifier", name: meta.fnName },
5755
+ arguments: [
5756
+ { type: "Literal", value: localIdx, raw: String(localIdx) },
5757
+ { type: "Literal", value: salt, raw: String(salt) }
5758
+ ],
5759
+ optional: false
5760
+ };
5761
+ }
5762
+ applyVaultTargetReplacement(target, callExpr);
3964
5763
  }
3965
5764
  const allPayloads = [];
3966
5765
  for (const meta of fragMeta) {
@@ -3983,6 +5782,7 @@ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExempt
3983
5782
  }
3984
5783
  integrityToken = computeFnv1aHash(JSON.stringify(allPayloads), seed);
3985
5784
  }
5785
+ rebuildInterpolatedTemplates(interpolatedTemplates);
3986
5786
  if (hotTargetsToReplace.length > 0) {
3987
5787
  const alreadyHasHx = ast.body.some(
3988
5788
  (stmt) => stmt.type === "FunctionDeclaration" && stmt.id?.name === "_hX"
@@ -4007,7 +5807,10 @@ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExempt
4007
5807
  const shaderHelperStmt = createShaderVaultAst(
4008
5808
  shaderVarName,
4009
5809
  shaderPayloads,
4010
- seed
5810
+ seed,
5811
+ sym,
5812
+ expDelta,
5813
+ shieldCoupled
4011
5814
  );
4012
5815
  ast.body.splice(insertIdx++, 0, shaderHelperStmt);
4013
5816
  }
@@ -4606,6 +6409,26 @@ function mixSeed32(seed, salt) {
4606
6409
  h ^= h >>> 16;
4607
6410
  return h | 0;
4608
6411
  }
6412
+ function modInverseUint32(oddValue) {
6413
+ const m = (oddValue | 1) >>> 0;
6414
+ let inv = 1;
6415
+ for (let i = 0; i < 5; i++) {
6416
+ inv = Math.imul(inv, 2 - Math.imul(m, inv) | 0) >>> 0;
6417
+ }
6418
+ return inv >>> 0;
6419
+ }
6420
+ function deriveAffineMbaParams(seed, salt) {
6421
+ let m = (mixSeed32(seed, salt) | 1) >>> 0;
6422
+ if (m === 1 || m === 4294967295 || m === 2654435769) {
6423
+ m = (m ^ 1540483477 | 1) >>> 0;
6424
+ }
6425
+ const m2 = Math.imul(m, 2) >>> 0;
6426
+ const mInv = modInverseUint32(m);
6427
+ let c = mixSeed32(seed, salt + 40503) >>> 0;
6428
+ if (c === 0) c = 668265263;
6429
+ const d = -Math.imul(mInv, c) >>> 0;
6430
+ return { m, m2, mInv, c, d };
6431
+ }
4609
6432
  function cloneNode(node) {
4610
6433
  return JSON.parse(JSON.stringify(node));
4611
6434
  }
@@ -5120,20 +6943,150 @@ function buildLiveVariables4(seed, fnIndex, paramNode, isArrowFn = false, ctxOpt
5120
6943
  return [candidates[0], candidates[1], candidates[2], candidates[3]];
5121
6944
  }
5122
6945
  var QNR_RESIDUE_FAMILIES = [
5123
- { add: 1, mask: 3, target: 3 },
5124
- { add: 3, mask: 7, target: 6 },
5125
- { add: 5, mask: 7, target: 3 },
5126
- { add: 7, mask: 15, target: 13 }
6946
+ // LHS in {1, 2}: > 2 is false; ((v ^ (v >> 1)) & 1) === 1
6947
+ { add: 1, mask: 3, target: 3, outBoundOp: ">", outBoundVal: 2, bitKind: "xor1", expectedBit: 1 },
6948
+ // LHS in {3, 4, 7}: < 3 is false; ((v | (v >> 2)) & 1) === 1
6949
+ { add: 3, mask: 7, target: 6, outBoundOp: "<", outBoundVal: 3, bitKind: "or2", expectedBit: 1 },
6950
+ // LHS in {1, 5, 6}: > 6 is false; ((v ^ (v >> 1)) & 1) === 1
6951
+ { add: 5, mask: 7, target: 3, outBoundOp: ">", outBoundVal: 6, bitKind: "xor1", expectedBit: 1 },
6952
+ // LHS in {0, 7, 8, 11}: > 11 is false; ((v ^ (v >> 1)) & 1) === 0
6953
+ { add: 7, mask: 15, target: 13, outBoundOp: ">", outBoundVal: 11, bitKind: "xor1", expectedBit: 0 }
5127
6954
  ];
6955
+ function makeTypeofGlobalLen() {
6956
+ return {
6957
+ type: "MemberExpression",
6958
+ computed: false,
6959
+ object: makeUnary("typeof", { type: "Identifier", name: "globalThis" }),
6960
+ property: { type: "Identifier", name: "length" }
6961
+ };
6962
+ }
6963
+ function makePropAccess(objExpr, propName) {
6964
+ if (/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(propName)) {
6965
+ return {
6966
+ type: "MemberExpression",
6967
+ computed: false,
6968
+ object: objExpr,
6969
+ property: { type: "Identifier", name: propName }
6970
+ };
6971
+ }
6972
+ return {
6973
+ type: "MemberExpression",
6974
+ computed: true,
6975
+ object: objExpr,
6976
+ property: makeLiteral(propName)
6977
+ };
6978
+ }
6979
+ function buildQnrBitExpr(qnrValRef, bitKind) {
6980
+ const shiftAmt = bitKind === "xor1" ? 1 : 2;
6981
+ const combOp = bitKind === "xor1" ? "^" : "|";
6982
+ return makeBinary(
6983
+ "&",
6984
+ makeBinary(
6985
+ combOp,
6986
+ cloneNode(qnrValRef),
6987
+ makeBinary(">>", cloneNode(qnrValRef), makeLiteral(shiftAmt))
6988
+ ),
6989
+ makeLiteral(1)
6990
+ );
6991
+ }
5128
6992
  function createSotaMbaPredicate(seed, fnIndex = 0, paramNode, decoyIdent, isArrowFn = false, ctxOpts) {
5129
6993
  const domain = ctxOpts?.returnDomain ?? "object";
5130
6994
  const [x1, x2, x3, x4] = buildLiveVariables4(seed, fnIndex, paramNode, isArrowFn, ctxOpts);
5131
6995
  const mba4 = buildMba4Ast(seed, fnIndex, x1, x2, x3, x4);
5132
6996
  const qnrFamilyIdx = ((seed ^ Math.imul(fnIndex + 1, 2654435761)) >>> 0) % QNR_RESIDUE_FAMILIES.length;
5133
6997
  const qnrFamily = QNR_RESIDUE_FAMILIES[qnrFamilyIdx];
6998
+ const slotA = fnIndex + (seed & 3) & 3;
6999
+ const slotB = slotA + 1 + (seed >>> 2 & 1) & 3;
7000
+ const hasAlias = Boolean(ctxOpts?.aliasIdentA);
7001
+ const aliasReadIdent = ctxOpts?.aliasIdentB ?? ctxOpts?.aliasIdentA ?? "";
5134
7002
  let qnrLeft;
7003
+ let qnrValForForm0;
5135
7004
  let zRefForDecoy;
5136
- if (ctxOpts?.scratchVarIdent) {
7005
+ let aliasInvZero = null;
7006
+ if (ctxOpts?.mxIdent && ctxOpts?.scratchVarIdent && hasAlias) {
7007
+ const scratchId = { type: "Identifier", name: ctxOpts.scratchVarIdent };
7008
+ const names = [...ctxOpts?.liveVars ?? [], ...extractParamNames(paramNode)];
7009
+ const uniqueNames = [];
7010
+ for (const n of names) {
7011
+ if (n && n !== "arguments" && n !== "eval" && !uniqueNames.includes(n)) {
7012
+ uniqueNames.push(n);
7013
+ }
7014
+ }
7015
+ const arg0 = uniqueNames.length >= 1 ? makeSafeNumericParam(uniqueNames[0]) : !isArrowFn ? {
7016
+ type: "MemberExpression",
7017
+ computed: false,
7018
+ object: { type: "Identifier", name: "arguments" },
7019
+ property: { type: "Identifier", name: "length" }
7020
+ } : makeTypeofGlobalLen();
7021
+ const arg1 = uniqueNames.length >= 2 ? makeSafeNumericParam(uniqueNames[1]) : uniqueNames.length === 1 && !isArrowFn ? {
7022
+ type: "MemberExpression",
7023
+ computed: false,
7024
+ object: { type: "Identifier", name: "arguments" },
7025
+ property: { type: "Identifier", name: "length" }
7026
+ } : makeTypeofGlobalLen();
7027
+ const a0 = mixSeed32(seed, fnIndex * 13 + 3);
7028
+ const a1 = mixSeed32(seed, fnIndex * 13 + 5) | 1;
7029
+ const a2 = mixSeed32(seed, fnIndex * 13 + 7) & ~1;
7030
+ const a3 = mixSeed32(seed, fnIndex * 13 + 9) & ~1;
7031
+ const maskConst = mixSeed32(seed, fnIndex + 97) | 1;
7032
+ const r0 = mixSeed32(seed, fnIndex * 17 + 1);
7033
+ const r1 = mixSeed32(seed, fnIndex * 17 + 3) | 1;
7034
+ const seqExprs = [
7035
+ {
7036
+ type: "AssignmentExpression",
7037
+ operator: "=",
7038
+ left: cloneNode(scratchId),
7039
+ right: {
7040
+ type: "CallExpression",
7041
+ callee: { type: "Identifier", name: ctxOpts.mxIdent },
7042
+ arguments: [
7043
+ arg0,
7044
+ arg1,
7045
+ makeLiteral(slotA),
7046
+ makeLiteral(slotB),
7047
+ makeInt32Literal(maskConst),
7048
+ makeInt32Literal(a0),
7049
+ makeInt32Literal(a1),
7050
+ makeInt32Literal(a2),
7051
+ makeInt32Literal(a3)
7052
+ ],
7053
+ optional: false
7054
+ }
7055
+ },
7056
+ {
7057
+ type: "AssignmentExpression",
7058
+ operator: "=",
7059
+ left: cloneNode(scratchId),
7060
+ right: makeBinary(
7061
+ "|",
7062
+ makeBinary("+", makeInt32Literal(r0), makeImul(cloneNode(scratchId), makeInt32Literal(r1))),
7063
+ makeLiteral(0)
7064
+ )
7065
+ }
7066
+ ];
7067
+ const qnrCore = makeBinary(
7068
+ "&",
7069
+ makeBinary("+", makeImul(cloneNode(scratchId), cloneNode(scratchId)), makeLiteral(qnrFamily.add)),
7070
+ makeLiteral(qnrFamily.mask)
7071
+ );
7072
+ qnrLeft = {
7073
+ type: "SequenceExpression",
7074
+ expressions: [...seqExprs, qnrCore]
7075
+ };
7076
+ qnrValForForm0 = {
7077
+ type: "SequenceExpression",
7078
+ expressions: [
7079
+ {
7080
+ type: "AssignmentExpression",
7081
+ operator: "=",
7082
+ left: cloneNode(scratchId),
7083
+ right: cloneNode(qnrCore)
7084
+ },
7085
+ buildQnrBitExpr(scratchId, qnrFamily.bitKind)
7086
+ ]
7087
+ };
7088
+ zRefForDecoy = cloneNode(scratchId);
7089
+ } else if (ctxOpts?.scratchVarIdent) {
5137
7090
  const scratchId = { type: "Identifier", name: ctxOpts.scratchVarIdent };
5138
7091
  const rivestOnScratch = buildRivestPermAst(seed, fnIndex, scratchId);
5139
7092
  const seqExprs = [
@@ -5158,43 +7111,62 @@ function createSotaMbaPredicate(seed, fnIndex = 0, paramNode, decoyIdent, isArro
5158
7111
  right: buildSboxMixAst(ctxOpts.sboxIdent, ctxOpts.scratchVarIdent)
5159
7112
  });
5160
7113
  }
5161
- if (ctxOpts.aliasIdentA) {
5162
- const aliasSlot = fnIndex + (seed & 3) & 3;
5163
- const aliasMem = makeMemberIndex(ctxOpts.aliasIdentA, makeLiteral(aliasSlot));
7114
+ if (hasAlias) {
7115
+ const aliasWriteMemA = makeMemberIndex(ctxOpts.aliasIdentA, makeLiteral(slotA));
7116
+ const maskConst = mixSeed32(seed, fnIndex + 97) | 1;
7117
+ const updateMask = makeBinary(
7118
+ "^",
7119
+ makeBinary("<<", cloneNode(scratchId), makeLiteral(3)),
7120
+ makeInt32Literal(maskConst)
7121
+ );
5164
7122
  seqExprs.push({
5165
7123
  type: "AssignmentExpression",
5166
- operator: "=",
5167
- left: cloneNode(aliasMem),
5168
- right: makeBinary(
5169
- "|",
5170
- makeBinary(
5171
- "^",
5172
- cloneNode(aliasMem),
5173
- makeBinary("&", cloneNode(scratchId), makeLiteral(0))
5174
- ),
5175
- makeLiteral(0)
5176
- )
7124
+ operator: "=",
7125
+ left: cloneNode(aliasWriteMemA),
7126
+ right: makeBinary("|", makeBinary("^", cloneNode(aliasWriteMemA), cloneNode(updateMask)), makeLiteral(0))
5177
7127
  });
7128
+ aliasInvZero = makeBinary(
7129
+ "^",
7130
+ makeBinary("|", makeBinary("^", cloneNode(aliasWriteMemA), cloneNode(updateMask)), makeLiteral(0)),
7131
+ {
7132
+ type: "AssignmentExpression",
7133
+ operator: "=",
7134
+ left: cloneNode(aliasWriteMemA),
7135
+ right: makeBinary("|", makeBinary("^", cloneNode(aliasWriteMemA), cloneNode(updateMask)), makeLiteral(0))
7136
+ }
7137
+ );
5178
7138
  }
5179
- seqExprs.push(
5180
- makeBinary(
5181
- "&",
5182
- makeBinary("+", makeImul(cloneNode(scratchId), cloneNode(scratchId)), makeLiteral(qnrFamily.add)),
5183
- makeLiteral(qnrFamily.mask)
5184
- )
7139
+ const qnrCore = makeBinary(
7140
+ "&",
7141
+ makeBinary("+", makeImul(cloneNode(scratchId), cloneNode(scratchId)), makeLiteral(qnrFamily.add)),
7142
+ makeLiteral(qnrFamily.mask)
5185
7143
  );
5186
7144
  qnrLeft = {
5187
7145
  type: "SequenceExpression",
5188
- expressions: seqExprs
7146
+ expressions: [...seqExprs, qnrCore]
7147
+ };
7148
+ qnrValForForm0 = {
7149
+ type: "SequenceExpression",
7150
+ expressions: [
7151
+ {
7152
+ type: "AssignmentExpression",
7153
+ operator: "=",
7154
+ left: cloneNode(scratchId),
7155
+ right: cloneNode(qnrCore)
7156
+ },
7157
+ buildQnrBitExpr(scratchId, qnrFamily.bitKind)
7158
+ ]
5189
7159
  };
5190
7160
  zRefForDecoy = cloneNode(scratchId);
5191
7161
  } else {
5192
7162
  const zExpr = buildRivestPermAst(seed, fnIndex, mba4);
5193
- qnrLeft = makeBinary(
7163
+ const qnrCore = makeBinary(
5194
7164
  "&",
5195
7165
  makeBinary("+", makeImul(cloneNode(zExpr), cloneNode(zExpr)), makeLiteral(qnrFamily.add)),
5196
7166
  makeLiteral(qnrFamily.mask)
5197
7167
  );
7168
+ qnrLeft = qnrCore;
7169
+ qnrValForForm0 = buildQnrBitExpr(qnrCore, qnrFamily.bitKind);
5198
7170
  zRefForDecoy = zExpr;
5199
7171
  }
5200
7172
  const consequent = createContextualDecoyConsequent(
@@ -5204,14 +7176,166 @@ function createSotaMbaPredicate(seed, fnIndex = 0, paramNode, decoyIdent, isArro
5204
7176
  decoyIdent,
5205
7177
  zRefForDecoy
5206
7178
  );
7179
+ const hasShieldCoupling = Boolean(ctxOpts?.shieldCoupled && ctxOpts?.windowKeySymbol);
7180
+ const predOffset = hasShieldCoupling ? 1 : (seed >>> 2) % 6;
7181
+ const predForm = ((fnIndex + predOffset) % 6 + 6) % 6;
7182
+ let testExpr;
7183
+ if (predForm === 0) {
7184
+ let pathACore = qnrValForForm0;
7185
+ if (aliasInvZero) {
7186
+ pathACore = makeBinary("^", aliasInvZero, qnrValForForm0);
7187
+ }
7188
+ if (hasAlias) {
7189
+ pathACore = makeBinary(
7190
+ "^",
7191
+ pathACore,
7192
+ makeBinary("&", makeMemberIndex(aliasReadIdent, makeLiteral(slotB)), makeLiteral(1))
7193
+ );
7194
+ }
7195
+ const pathA = ctxOpts?.scratchVarIdent ? {
7196
+ type: "SequenceExpression",
7197
+ expressions: [...qnrLeft.expressions.slice(0, -1), pathACore]
7198
+ } : pathACore;
7199
+ const pathB = hasAlias ? makeBinary(
7200
+ "^",
7201
+ makeLiteral(qnrFamily.expectedBit),
7202
+ makeBinary("&", makeMemberIndex(ctxOpts.aliasIdentA, makeLiteral(slotB)), makeLiteral(1))
7203
+ ) : makeLiteral(qnrFamily.expectedBit);
7204
+ testExpr = makeBinary("!==", makeBinary("^", pathA, pathB), makeLiteral(0));
7205
+ } else if (predForm === 1) {
7206
+ const qnrLhs = aliasInvZero ? makeBinary("+", qnrLeft, makeBinary("&", aliasInvZero, makeLiteral(1))) : qnrLeft;
7207
+ const qnrFail = makeBinary(qnrFamily.outBoundOp, qnrLhs, makeLiteral(qnrFamily.outBoundVal));
7208
+ const hasGlobal = makeBinary(
7209
+ "<",
7210
+ makeUnary("typeof", { type: "Identifier", name: "globalThis" }),
7211
+ makeLiteral("u")
7212
+ );
7213
+ const tamperCheck = hasShieldCoupling ? {
7214
+ type: "LogicalExpression",
7215
+ operator: "&&",
7216
+ left: hasGlobal,
7217
+ right: {
7218
+ type: "LogicalExpression",
7219
+ operator: "&&",
7220
+ left: makePropAccess({ type: "Identifier", name: "globalThis" }, `${ctxOpts.windowKeySymbol}_s`),
7221
+ right: makeBinary(
7222
+ "===",
7223
+ {
7224
+ type: "MemberExpression",
7225
+ computed: true,
7226
+ object: makePropAccess({ type: "Identifier", name: "globalThis" }, `${ctxOpts.windowKeySymbol}_s`),
7227
+ property: makeLiteral(0)
7228
+ },
7229
+ makeLiteral(2)
7230
+ )
7231
+ }
7232
+ } : {
7233
+ type: "LogicalExpression",
7234
+ operator: "&&",
7235
+ left: hasGlobal,
7236
+ right: makeBinary(
7237
+ "===",
7238
+ makePropAccess({ type: "Identifier", name: "globalThis" }, "__unpeek_tampered"),
7239
+ makeUnary("!", makeLiteral(0))
7240
+ )
7241
+ };
7242
+ testExpr = {
7243
+ type: "LogicalExpression",
7244
+ operator: "||",
7245
+ left: qnrFail,
7246
+ right: tamperCheck
7247
+ };
7248
+ } else if (predForm === 2) {
7249
+ const slotReadB = hasAlias ? makeBinary("&", makeMemberIndex(aliasReadIdent, makeLiteral(slotB)), makeLiteral(7)) : makeBinary("&", makeTypeofGlobalLen(), makeLiteral(7));
7250
+ const slotWriteB = hasAlias ? makeBinary("&", makeMemberIndex(ctxOpts.aliasIdentA, makeLiteral(slotB)), makeLiteral(7)) : makeBinary("&", makeTypeofGlobalLen(), makeLiteral(7));
7251
+ let lhsExpr = makeBinary("+", qnrLeft, slotReadB);
7252
+ if (aliasInvZero) {
7253
+ lhsExpr = makeBinary("+", lhsExpr, makeBinary("&", aliasInvZero, makeLiteral(3)));
7254
+ }
7255
+ const rhsExpr = makeBinary("+", makeLiteral(qnrFamily.outBoundVal), slotWriteB);
7256
+ testExpr = makeBinary(qnrFamily.outBoundOp, lhsExpr, rhsExpr);
7257
+ } else if (predForm === 3) {
7258
+ const tagLhs = hasAlias ? makeBinary("&", makeMemberIndex(ctxOpts.aliasIdentA, makeLiteral(slotB)), makeLiteral(240)) : makeBinary("&", makeBinary("<<", makeTypeofGlobalLen(), makeLiteral(4)), makeLiteral(240));
7259
+ const tagRhsBase = hasAlias ? makeBinary("&", makeMemberIndex(aliasReadIdent, makeLiteral(slotB)), makeLiteral(240)) : makeBinary("&", makeBinary("<<", makeTypeofGlobalLen(), makeLiteral(4)), makeLiteral(240));
7260
+ const tagRhs = aliasInvZero ? makeBinary("^", tagRhsBase, makeBinary("&", aliasInvZero, makeLiteral(15))) : tagRhsBase;
7261
+ const lhsExpr = makeBinary("|", makeBinary("^", qnrLeft, tagLhs), makeLiteral(0));
7262
+ const rhsExpr = makeBinary("|", makeBinary("^", makeLiteral(qnrFamily.target), tagRhs), makeLiteral(0));
7263
+ testExpr = makeBinary("===", lhsExpr, rhsExpr);
7264
+ } else if (predForm === 4) {
7265
+ const k4 = mixSeed32(seed, fnIndex * 29 + 13) >>> 0 || 1;
7266
+ if (ctxOpts?.scratchVarIdent) {
7267
+ const scratchId = { type: "Identifier", name: ctxOpts.scratchVarIdent };
7268
+ const preU = aliasInvZero ? makeBinary("^", cloneNode(scratchId), aliasInvZero) : cloneNode(scratchId);
7269
+ const uAssign = {
7270
+ type: "AssignmentExpression",
7271
+ operator: "=",
7272
+ left: cloneNode(scratchId),
7273
+ right: makeBinary(">>>", makeBinary("^", preU, makeLiteral(k4)), makeLiteral(0))
7274
+ };
7275
+ const uMinus1Lhs = makeBinary(">>>", makeBinary("-", cloneNode(scratchId), makeLiteral(1)), makeLiteral(0));
7276
+ const uMinus1Rhs = makeBinary(">>>", makeBinary("-", cloneNode(scratchId), makeLiteral(1)), makeLiteral(0));
7277
+ const orU = makeBinary(">>>", makeBinary("|", cloneNode(scratchId), uMinus1Lhs), makeLiteral(0));
7278
+ const xorU = makeBinary(">>>", makeBinary("^", cloneNode(scratchId), uMinus1Rhs), makeLiteral(0));
7279
+ const lhsSeq = {
7280
+ type: "SequenceExpression",
7281
+ expressions: [...qnrLeft.expressions.slice(0, -1), uAssign, orU]
7282
+ };
7283
+ testExpr = makeBinary("<", lhsSeq, xorU);
7284
+ } else {
7285
+ const uExpr = makeBinary(">>>", makeBinary("^", cloneNode(zRefForDecoy), makeLiteral(k4)), makeLiteral(0));
7286
+ const uMinus1Lhs = makeBinary(">>>", makeBinary("-", cloneNode(uExpr), makeLiteral(1)), makeLiteral(0));
7287
+ const uMinus1Rhs = makeBinary(">>>", makeBinary("-", cloneNode(uExpr), makeLiteral(1)), makeLiteral(0));
7288
+ const orU = makeBinary(">>>", makeBinary("|", cloneNode(uExpr), uMinus1Lhs), makeLiteral(0));
7289
+ const xorU = makeBinary(">>>", makeBinary("^", cloneNode(uExpr), uMinus1Rhs), makeLiteral(0));
7290
+ testExpr = makeBinary("<", orU, xorU);
7291
+ }
7292
+ } else {
7293
+ const k5 = mixSeed32(seed, fnIndex * 31 + 17) >>> 0 || 3;
7294
+ const { m, m2, mInv, c, d } = deriveAffineMbaParams(seed, fnIndex * 37 + 23);
7295
+ const buildAffineLhs = (valNode) => {
7296
+ const inner = makeBinary(
7297
+ "|",
7298
+ makeBinary(
7299
+ "+",
7300
+ makeBinary(
7301
+ "+",
7302
+ makeImul(makeLiteral(m), makeBinary("^", cloneNode(valNode), makeLiteral(k5))),
7303
+ makeImul(makeLiteral(m2), makeBinary("&", cloneNode(valNode), makeLiteral(k5)))
7304
+ ),
7305
+ makeLiteral(c)
7306
+ ),
7307
+ makeLiteral(0)
7308
+ );
7309
+ return makeBinary(
7310
+ "|",
7311
+ makeBinary("+", makeImul(makeLiteral(mInv), inner), makeLiteral(d)),
7312
+ makeLiteral(0)
7313
+ );
7314
+ };
7315
+ const buildAffineRhs = (valNode) => makeBinary("|", makeBinary("+", cloneNode(valNode), makeLiteral(k5)), makeLiteral(0));
7316
+ if (ctxOpts?.scratchVarIdent) {
7317
+ const scratchId = { type: "Identifier", name: ctxOpts.scratchVarIdent };
7318
+ const preSeqs = [...qnrLeft.expressions.slice(0, -1)];
7319
+ if (aliasInvZero) {
7320
+ preSeqs.push({
7321
+ type: "AssignmentExpression",
7322
+ operator: "=",
7323
+ left: cloneNode(scratchId),
7324
+ right: makeBinary("|", makeBinary("^", cloneNode(scratchId), aliasInvZero), makeLiteral(0))
7325
+ });
7326
+ }
7327
+ const lhsSeq = {
7328
+ type: "SequenceExpression",
7329
+ expressions: [...preSeqs, buildAffineLhs(scratchId)]
7330
+ };
7331
+ testExpr = makeBinary("!==", lhsSeq, buildAffineRhs(scratchId));
7332
+ } else {
7333
+ testExpr = makeBinary("!==", buildAffineLhs(zRefForDecoy), buildAffineRhs(zRefForDecoy));
7334
+ }
7335
+ }
5207
7336
  return {
5208
7337
  type: "IfStatement",
5209
- test: {
5210
- type: "BinaryExpression",
5211
- operator: "===",
5212
- left: qnrLeft,
5213
- right: makeLiteral(qnrFamily.target)
5214
- },
7338
+ test: testExpr,
5215
7339
  consequent,
5216
7340
  alternate: null
5217
7341
  };
@@ -5270,7 +7394,7 @@ function inferFunctionReturnDomain(fnNode) {
5270
7394
  if (seenString && !seenNumber && !seenBoolean) return "string";
5271
7395
  return "object";
5272
7396
  }
5273
- function createSboxAndAliasDeclarations(sboxIdent, aliasIdentA, aliasIdentB, scratchVarIdent, seed) {
7397
+ function createSboxAndAliasDeclarations(sboxIdent, aliasIdentA, aliasIdentB, scratchVarIdent, seed, mxIdent) {
5274
7398
  const sboxInit = acorn5.parseExpressionAt(
5275
7399
  `(function(){var a=[],i,s=${seed | 0},j,t;for(i=0;i<256;i++)a[i]=i;for(i=255;i>0;i--){s=(Math.imul(s,1664525)+1013904223)|0;j=(s>>>0)%(i+1);t=a[i];a[i]=a[j];a[j]=t;}return a;})()`,
5276
7400
  0,
@@ -5282,52 +7406,550 @@ function createSboxAndAliasDeclarations(sboxIdent, aliasIdentA, aliasIdentB, scr
5282
7406
  mixSeed32(seed, 107),
5283
7407
  mixSeed32(seed, 109)
5284
7408
  ];
7409
+ const declarations = [
7410
+ {
7411
+ type: "VariableDeclarator",
7412
+ id: { type: "Identifier", name: sboxIdent },
7413
+ init: sboxInit
7414
+ },
7415
+ {
7416
+ type: "VariableDeclarator",
7417
+ id: { type: "Identifier", name: aliasIdentA },
7418
+ init: {
7419
+ type: "ArrayExpression",
7420
+ elements: stateVals.map((v) => makeInt32Literal(v))
7421
+ }
7422
+ },
7423
+ {
7424
+ type: "VariableDeclarator",
7425
+ id: { type: "Identifier", name: aliasIdentB },
7426
+ init: { type: "Identifier", name: aliasIdentA }
7427
+ },
7428
+ {
7429
+ type: "VariableDeclarator",
7430
+ id: { type: "Identifier", name: scratchVarIdent },
7431
+ init: makeLiteral(0)
7432
+ }
7433
+ ];
7434
+ if (mxIdent) {
7435
+ const mbaAst = buildMba4Ast(
7436
+ seed,
7437
+ 0,
7438
+ { type: "Identifier", name: "$u" },
7439
+ { type: "Identifier", name: "$v" },
7440
+ { type: "Identifier", name: "$p" },
7441
+ { type: "Identifier", name: "$q" }
7442
+ );
7443
+ const mxFn = {
7444
+ type: "FunctionExpression",
7445
+ id: null,
7446
+ params: [
7447
+ { type: "Identifier", name: "$a" },
7448
+ { type: "Identifier", name: "$b" },
7449
+ { type: "Identifier", name: "$c" },
7450
+ { type: "Identifier", name: "$d" },
7451
+ { type: "Identifier", name: "$e" },
7452
+ { type: "Identifier", name: "$f" },
7453
+ { type: "Identifier", name: "$g" },
7454
+ { type: "Identifier", name: "$h" },
7455
+ { type: "Identifier", name: "$i" }
7456
+ ],
7457
+ body: {
7458
+ type: "BlockStatement",
7459
+ body: [
7460
+ {
7461
+ type: "VariableDeclaration",
7462
+ kind: "var",
7463
+ declarations: [
7464
+ { type: "VariableDeclarator", id: { type: "Identifier", name: "$u" }, init: makeBinary("|", { type: "Identifier", name: "$a" }, makeLiteral(0)) },
7465
+ { type: "VariableDeclarator", id: { type: "Identifier", name: "$v" }, init: makeBinary("|", { type: "Identifier", name: "$b" }, makeLiteral(0)) },
7466
+ { type: "VariableDeclarator", id: { type: "Identifier", name: "$p" }, init: makeBinary("|", makeMemberIndex(aliasIdentA, { type: "Identifier", name: "$c" }), makeLiteral(0)) },
7467
+ { type: "VariableDeclarator", id: { type: "Identifier", name: "$q" }, init: makeBinary("|", makeMemberIndex(aliasIdentB, { type: "Identifier", name: "$d" }), makeLiteral(0)) },
7468
+ { type: "VariableDeclarator", id: { type: "Identifier", name: "$z" }, init: mbaAst }
7469
+ ]
7470
+ },
7471
+ {
7472
+ type: "ExpressionStatement",
7473
+ expression: {
7474
+ type: "AssignmentExpression",
7475
+ operator: "=",
7476
+ left: { type: "Identifier", name: "$z" },
7477
+ right: makeBinary(
7478
+ "|",
7479
+ makeBinary(
7480
+ "+",
7481
+ { type: "Identifier", name: "$f" },
7482
+ makeImul(
7483
+ { type: "Identifier", name: "$z" },
7484
+ makeBinary(
7485
+ "+",
7486
+ { type: "Identifier", name: "$g" },
7487
+ makeImul(
7488
+ { type: "Identifier", name: "$z" },
7489
+ makeBinary(
7490
+ "+",
7491
+ { type: "Identifier", name: "$h" },
7492
+ makeImul({ type: "Identifier", name: "$z" }, { type: "Identifier", name: "$i" })
7493
+ )
7494
+ )
7495
+ )
7496
+ )
7497
+ ),
7498
+ makeLiteral(0)
7499
+ )
7500
+ }
7501
+ },
7502
+ {
7503
+ type: "ExpressionStatement",
7504
+ expression: {
7505
+ type: "AssignmentExpression",
7506
+ operator: "=",
7507
+ left: { type: "Identifier", name: "$z" },
7508
+ right: buildSboxMixAst(sboxIdent, "$z")
7509
+ }
7510
+ },
7511
+ {
7512
+ type: "VariableDeclaration",
7513
+ kind: "var",
7514
+ declarations: [
7515
+ {
7516
+ type: "VariableDeclarator",
7517
+ id: { type: "Identifier", name: "$m" },
7518
+ init: makeBinary("^", makeBinary("<<", { type: "Identifier", name: "$z" }, makeLiteral(3)), { type: "Identifier", name: "$e" })
7519
+ }
7520
+ ]
7521
+ },
7522
+ {
7523
+ type: "ExpressionStatement",
7524
+ expression: {
7525
+ type: "AssignmentExpression",
7526
+ operator: "=",
7527
+ left: makeMemberIndex(aliasIdentA, { type: "Identifier", name: "$c" }),
7528
+ right: makeBinary("|", makeBinary("^", makeMemberIndex(aliasIdentA, { type: "Identifier", name: "$c" }), { type: "Identifier", name: "$m" }), makeLiteral(0))
7529
+ }
7530
+ },
7531
+ {
7532
+ type: "VariableDeclaration",
7533
+ kind: "var",
7534
+ declarations: [
7535
+ {
7536
+ type: "VariableDeclarator",
7537
+ id: { type: "Identifier", name: "$w" },
7538
+ init: makeBinary(
7539
+ "^",
7540
+ makeBinary("|", makeBinary("^", makeMemberIndex(aliasIdentA, { type: "Identifier", name: "$c" }), { type: "Identifier", name: "$m" }), makeLiteral(0)),
7541
+ {
7542
+ type: "AssignmentExpression",
7543
+ operator: "=",
7544
+ left: makeMemberIndex(aliasIdentA, { type: "Identifier", name: "$c" }),
7545
+ right: makeBinary("|", makeBinary("^", makeMemberIndex(aliasIdentA, { type: "Identifier", name: "$c" }), { type: "Identifier", name: "$m" }), makeLiteral(0))
7546
+ }
7547
+ )
7548
+ }
7549
+ ]
7550
+ },
7551
+ {
7552
+ type: "ReturnStatement",
7553
+ argument: {
7554
+ type: "AssignmentExpression",
7555
+ operator: "=",
7556
+ left: { type: "Identifier", name: scratchVarIdent },
7557
+ right: makeBinary("|", makeBinary("^", { type: "Identifier", name: "$z" }, { type: "Identifier", name: "$w" }), makeLiteral(0))
7558
+ }
7559
+ }
7560
+ ]
7561
+ },
7562
+ generator: false,
7563
+ async: false,
7564
+ expression: false
7565
+ };
7566
+ declarations.push({
7567
+ type: "VariableDeclarator",
7568
+ id: { type: "Identifier", name: mxIdent },
7569
+ init: mxFn
7570
+ });
7571
+ }
5285
7572
  return {
5286
7573
  type: "VariableDeclaration",
5287
7574
  kind: "var",
5288
- declarations: [
5289
- {
5290
- type: "VariableDeclarator",
5291
- id: { type: "Identifier", name: sboxIdent },
5292
- init: sboxInit
5293
- },
5294
- {
5295
- type: "VariableDeclarator",
5296
- id: { type: "Identifier", name: aliasIdentA },
5297
- init: {
5298
- type: "ArrayExpression",
5299
- elements: stateVals.map((v) => makeInt32Literal(v))
7575
+ declarations
7576
+ };
7577
+ }
7578
+ var MAX_COLD_GUARDS_PER_CHUNK = 12;
7579
+ var MAX_COLD_BITWISE_MBA_PER_CHUNK = 8;
7580
+ var BITWISE_MBA_OPS = /* @__PURE__ */ new Set(["^", "|", "&"]);
7581
+ var BITWISE_LOOP_NODE_TYPES = /* @__PURE__ */ new Set([
7582
+ "ForStatement",
7583
+ "WhileStatement",
7584
+ "DoWhileStatement",
7585
+ "ForInStatement",
7586
+ "ForOfStatement"
7587
+ ]);
7588
+ var BITWISE_FUNCTION_TYPES = /* @__PURE__ */ new Set([
7589
+ "FunctionDeclaration",
7590
+ "FunctionExpression",
7591
+ "ArrowFunctionExpression"
7592
+ ]);
7593
+ var BITWISE_LEXICAL_SCOPE_TYPES = /* @__PURE__ */ new Set([
7594
+ "Program",
7595
+ "FunctionDeclaration",
7596
+ "FunctionExpression",
7597
+ "ArrowFunctionExpression",
7598
+ "BlockStatement",
7599
+ "ForStatement",
7600
+ "ForInStatement",
7601
+ "ForOfStatement",
7602
+ "SwitchStatement",
7603
+ "CatchClause",
7604
+ "StaticBlock"
7605
+ ]);
7606
+ var FORBIDDEN_BITWISE_IDENTIFIERS = /* @__PURE__ */ new Set([
7607
+ "arguments",
7608
+ "eval",
7609
+ "undefined",
7610
+ "NaN",
7611
+ "Infinity",
7612
+ "globalThis",
7613
+ "window",
7614
+ "self",
7615
+ "Math",
7616
+ "BigInt"
7617
+ ]);
7618
+ function collectBoundPatternNames(pattern, out) {
7619
+ if (!pattern || typeof pattern !== "object") return;
7620
+ switch (pattern.type) {
7621
+ case "Identifier":
7622
+ out.push(pattern.name);
7623
+ break;
7624
+ case "AssignmentPattern":
7625
+ collectBoundPatternNames(pattern.left, out);
7626
+ break;
7627
+ case "RestElement":
7628
+ collectBoundPatternNames(pattern.argument, out);
7629
+ break;
7630
+ case "ArrayPattern":
7631
+ for (const el of pattern.elements || []) {
7632
+ if (el) collectBoundPatternNames(el, out);
7633
+ }
7634
+ break;
7635
+ case "ObjectPattern":
7636
+ for (const prop of pattern.properties || []) {
7637
+ if (prop.type === "Property") {
7638
+ collectBoundPatternNames(prop.value, out);
7639
+ } else if (prop.type === "RestElement") {
7640
+ collectBoundPatternNames(prop.argument, out);
5300
7641
  }
5301
- },
5302
- {
5303
- type: "VariableDeclarator",
5304
- id: { type: "Identifier", name: aliasIdentB },
5305
- init: { type: "Identifier", name: aliasIdentA }
5306
- },
5307
- {
5308
- type: "VariableDeclarator",
5309
- id: { type: "Identifier", name: scratchVarIdent },
5310
- init: makeLiteral(0)
5311
7642
  }
5312
- ]
7643
+ break;
7644
+ }
7645
+ }
7646
+ function analyzeBitwiseMbaScopes(ast) {
7647
+ const scopeBindings = /* @__PURE__ */ new Map();
7648
+ let unsafe = false;
7649
+ const addBinding = (scopeNode, name) => {
7650
+ if (name === "Math") {
7651
+ unsafe = true;
7652
+ return;
7653
+ }
7654
+ let set = scopeBindings.get(scopeNode);
7655
+ if (!set) {
7656
+ set = /* @__PURE__ */ new Set();
7657
+ scopeBindings.set(scopeNode, set);
7658
+ }
7659
+ set.add(name);
7660
+ };
7661
+ const scopeStack = [];
7662
+ const varTargetStack = [];
7663
+ const getNearestLexicalScope = () => scopeStack[scopeStack.length - 1] ?? ast;
7664
+ const getNearestVarScope = () => varTargetStack[varTargetStack.length - 1] ?? ast;
7665
+ function scan(node) {
7666
+ if (unsafe || !node || typeof node !== "object" || typeof node.type !== "string") {
7667
+ return;
7668
+ }
7669
+ if (node.type === "WithStatement") {
7670
+ unsafe = true;
7671
+ return;
7672
+ }
7673
+ if (node.type === "Literal" && (typeof node.value === "bigint" || typeof node.bigint === "string") || node.type === "BigIntLiteral") {
7674
+ unsafe = true;
7675
+ return;
7676
+ }
7677
+ if (node.type === "Identifier" && node.name === "BigInt") {
7678
+ unsafe = true;
7679
+ return;
7680
+ }
7681
+ if (node.type === "ImportSpecifier" || node.type === "ImportDefaultSpecifier" || node.type === "ImportNamespaceSpecifier") {
7682
+ if (node.local?.type === "Identifier") {
7683
+ addBinding(ast, node.local.name);
7684
+ }
7685
+ } else if (node.type === "FunctionDeclaration") {
7686
+ if (node.id?.type === "Identifier") {
7687
+ addBinding(getNearestLexicalScope(), node.id.name);
7688
+ addBinding(getNearestVarScope(), node.id.name);
7689
+ }
7690
+ } else if (node.type === "ClassDeclaration") {
7691
+ if (node.id?.type === "Identifier") {
7692
+ addBinding(getNearestLexicalScope(), node.id.name);
7693
+ }
7694
+ } else if (node.type === "VariableDeclaration") {
7695
+ const targetScope = node.kind === "var" ? getNearestVarScope() : getNearestLexicalScope();
7696
+ for (const decl of node.declarations || []) {
7697
+ const names = [];
7698
+ collectBoundPatternNames(decl.id, names);
7699
+ for (const name of names) {
7700
+ addBinding(targetScope, name);
7701
+ }
7702
+ }
7703
+ }
7704
+ if (unsafe) return;
7705
+ const pushesLexical = BITWISE_LEXICAL_SCOPE_TYPES.has(node.type);
7706
+ const isFn = BITWISE_FUNCTION_TYPES.has(node.type);
7707
+ const isStaticBlock = node.type === "StaticBlock";
7708
+ if (pushesLexical) {
7709
+ scopeStack.push(node);
7710
+ if (!scopeBindings.has(node)) {
7711
+ scopeBindings.set(node, /* @__PURE__ */ new Set());
7712
+ }
7713
+ }
7714
+ if (isFn) {
7715
+ if (node.id?.type === "Identifier") {
7716
+ addBinding(node, node.id.name);
7717
+ }
7718
+ for (const param of node.params || []) {
7719
+ const names = [];
7720
+ collectBoundPatternNames(param, names);
7721
+ for (const name of names) {
7722
+ addBinding(node, name);
7723
+ }
7724
+ }
7725
+ const bodyScope = node.body?.type === "BlockStatement" ? node.body : node;
7726
+ varTargetStack.push(bodyScope);
7727
+ } else if (node.type === "Program" || isStaticBlock) {
7728
+ varTargetStack.push(node);
7729
+ } else if (node.type === "CatchClause" && node.param) {
7730
+ const names = [];
7731
+ collectBoundPatternNames(node.param, names);
7732
+ for (const name of names) {
7733
+ addBinding(node, name);
7734
+ }
7735
+ } else if (node.type === "ClassExpression" && node.id?.type === "Identifier") {
7736
+ addBinding(node, node.id.name);
7737
+ }
7738
+ try {
7739
+ for (const key of Object.keys(node)) {
7740
+ if (key === "loc" || key === "range" || key === "start" || key === "end" || key === "comments" || key === "tokens") {
7741
+ continue;
7742
+ }
7743
+ const child = node[key];
7744
+ if (Array.isArray(child)) {
7745
+ for (const item of child) {
7746
+ scan(item);
7747
+ if (unsafe) return;
7748
+ }
7749
+ } else if (child && typeof child === "object") {
7750
+ scan(child);
7751
+ if (unsafe) return;
7752
+ }
7753
+ }
7754
+ } finally {
7755
+ if (isFn || node.type === "Program" || isStaticBlock) {
7756
+ varTargetStack.pop();
7757
+ }
7758
+ if (pushesLexical) {
7759
+ scopeStack.pop();
7760
+ }
7761
+ }
7762
+ }
7763
+ scan(ast);
7764
+ return { unsafe, scopeBindings };
7765
+ }
7766
+ function isSafeAtomicIntegerLiteral(node) {
7767
+ return Boolean(
7768
+ node && node.type === "Literal" && typeof node.value === "number" && Number.isInteger(node.value) && node.value >= 0 && node.value <= 4294967295
7769
+ );
7770
+ }
7771
+ function isZeroNumericLiteral(node) {
7772
+ return Boolean(node && node.type === "Literal" && typeof node.value === "number" && node.value === 0);
7773
+ }
7774
+ function isLocalBoundIdentifier(node, scopeStack, scopeBindings, programNode) {
7775
+ if (!node || node.type !== "Identifier") return false;
7776
+ if (FORBIDDEN_BITWISE_IDENTIFIERS.has(node.name)) return false;
7777
+ for (let i = scopeStack.length - 1; i >= 0; i--) {
7778
+ const scopeNode = scopeStack[i];
7779
+ if (scopeNode === programNode) return false;
7780
+ const bindings = scopeBindings.get(scopeNode);
7781
+ if (bindings && bindings.has(node.name)) {
7782
+ return true;
7783
+ }
7784
+ }
7785
+ return false;
7786
+ }
7787
+ function buildColdBitwiseConditional(op, left, right, seed, subIndex, hotExemptNodes) {
7788
+ const { m, mInv, c, d } = deriveAffineMbaParams(seed, 16640 + subIndex * 43);
7789
+ const a1 = cloneNode(left);
7790
+ const b1 = cloneNode(right);
7791
+ const a2 = cloneNode(left);
7792
+ const b2 = cloneNode(right);
7793
+ let affineComb;
7794
+ if (op === "^") {
7795
+ affineComb = makeBinary(
7796
+ "-",
7797
+ makeImul(makeLiteral(m), makeBinary("|", a1, b1)),
7798
+ makeImul(makeLiteral(m), makeBinary("&", a2, b2))
7799
+ );
7800
+ } else if (op === "|") {
7801
+ affineComb = makeBinary(
7802
+ "+",
7803
+ makeImul(makeLiteral(m), makeBinary("&", a1, b1)),
7804
+ makeImul(makeLiteral(m), makeBinary("^", a2, b2))
7805
+ );
7806
+ } else {
7807
+ affineComb = makeBinary(
7808
+ "-",
7809
+ makeImul(makeLiteral(m), makeBinary("|", a1, b1)),
7810
+ makeImul(makeLiteral(m), makeBinary("^", a2, b2))
7811
+ );
7812
+ }
7813
+ const innerWithC = makeBinary("|", makeBinary("+", affineComb, makeLiteral(c)), makeLiteral(0));
7814
+ const consequent = makeBinary(
7815
+ "|",
7816
+ makeBinary("+", makeImul(makeLiteral(mInv), innerWithC), makeLiteral(d)),
7817
+ makeLiteral(0)
7818
+ );
7819
+ const alternate = makeBinary(op, cloneNode(left), cloneNode(right));
7820
+ const exemptNodes = [];
7821
+ const uniqueIdents = [];
7822
+ const seenNames = /* @__PURE__ */ new Set();
7823
+ for (const operand of [left, right]) {
7824
+ if (operand?.type === "Identifier" && !seenNames.has(operand.name)) {
7825
+ seenNames.add(operand.name);
7826
+ uniqueIdents.push(operand);
7827
+ }
7828
+ }
7829
+ const makeIsNumberExpr = (ident) => {
7830
+ const numLit = makeLiteral("number");
7831
+ const eqNode = makeBinary("===", makeUnary("typeof", { type: "Identifier", name: ident.name }), numLit);
7832
+ exemptNodes.push(numLit, eqNode);
7833
+ return eqNode;
7834
+ };
7835
+ const testExpr = uniqueIdents.length === 2 ? {
7836
+ type: "LogicalExpression",
7837
+ operator: "&&",
7838
+ left: makeIsNumberExpr(uniqueIdents[0]),
7839
+ right: makeIsNumberExpr(uniqueIdents[1])
7840
+ } : makeIsNumberExpr(uniqueIdents[0]);
7841
+ const replacement = {
7842
+ type: "ConditionalExpression",
7843
+ test: testExpr,
7844
+ consequent,
7845
+ alternate,
7846
+ _unpeekGuardSubtree: true
5313
7847
  };
7848
+ if (hotExemptNodes) {
7849
+ hotExemptNodes.add(replacement);
7850
+ hotExemptNodes.add(testExpr);
7851
+ for (const nodeToExempt of exemptNodes) {
7852
+ hotExemptNodes.add(nodeToExempt);
7853
+ }
7854
+ }
7855
+ return replacement;
7856
+ }
7857
+ function applyColdBitwiseMba(ast, coldFunctionNodes, seed = 2654435769, hotExemptNodes, guardSubtreeNodes) {
7858
+ const { unsafe, scopeBindings } = analyzeBitwiseMbaScopes(ast);
7859
+ if (unsafe) return 0;
7860
+ let mbaCount = 0;
7861
+ const scopeStack = [];
7862
+ function walkTransform(node, setInParent, inColdFn) {
7863
+ if (mbaCount >= MAX_COLD_BITWISE_MBA_PER_CHUNK) return;
7864
+ if (!node || typeof node !== "object" || typeof node.type !== "string") return;
7865
+ if (hotExemptNodes?.has(node) || guardSubtreeNodes?.has(node)) return;
7866
+ if (node._unpeekGuardSubtree === true) return;
7867
+ if (node._unpeekSerialized || node._unpeekVirtualized === true) return;
7868
+ if (BITWISE_LOOP_NODE_TYPES.has(node.type)) return;
7869
+ const pushedScope = scopeBindings.has(node);
7870
+ if (pushedScope) scopeStack.push(node);
7871
+ try {
7872
+ const childInColdFn = BITWISE_FUNCTION_TYPES.has(node.type) ? coldFunctionNodes.has(node) : inColdFn;
7873
+ if (childInColdFn && node.type === "BinaryExpression" && BITWISE_MBA_OPS.has(node.operator)) {
7874
+ const op = node.operator;
7875
+ const { left, right } = node;
7876
+ const isCoercionOrZero = op === "|" && isZeroNumericLiteral(right);
7877
+ if (!isCoercionOrZero) {
7878
+ const leftAtomic = isSafeAtomicIntegerLiteral(left) || isLocalBoundIdentifier(left, scopeStack, scopeBindings, ast);
7879
+ const rightAtomic = isSafeAtomicIntegerLiteral(right) || isLocalBoundIdentifier(right, scopeStack, scopeBindings, ast);
7880
+ const hasIdent = left?.type === "Identifier" || right?.type === "Identifier";
7881
+ if (leftAtomic && rightAtomic && hasIdent) {
7882
+ const replacement = buildColdBitwiseConditional(
7883
+ op,
7884
+ left,
7885
+ right,
7886
+ seed,
7887
+ mbaCount,
7888
+ hotExemptNodes
7889
+ );
7890
+ mbaCount++;
7891
+ setInParent(replacement);
7892
+ return;
7893
+ }
7894
+ }
7895
+ }
7896
+ for (const key of Object.keys(node)) {
7897
+ if (mbaCount >= MAX_COLD_BITWISE_MBA_PER_CHUNK) break;
7898
+ if (key === "loc" || key === "range" || key === "start" || key === "end" || key === "comments" || key === "tokens") {
7899
+ continue;
7900
+ }
7901
+ const child = node[key];
7902
+ if (Array.isArray(child)) {
7903
+ for (let i = 0; i < child.length; i++) {
7904
+ if (mbaCount >= MAX_COLD_BITWISE_MBA_PER_CHUNK) break;
7905
+ const item = child[i];
7906
+ if (item && typeof item === "object" && typeof item.type === "string") {
7907
+ walkTransform(
7908
+ item,
7909
+ (rep) => {
7910
+ child[i] = rep;
7911
+ },
7912
+ childInColdFn
7913
+ );
7914
+ }
7915
+ }
7916
+ } else if (child && typeof child === "object" && typeof child.type === "string") {
7917
+ walkTransform(
7918
+ child,
7919
+ (rep) => {
7920
+ node[key] = rep;
7921
+ },
7922
+ childInColdFn
7923
+ );
7924
+ }
7925
+ }
7926
+ } finally {
7927
+ if (pushedScope) scopeStack.pop();
7928
+ }
7929
+ }
7930
+ walkTransform(ast, () => {
7931
+ }, false);
7932
+ return mbaCount;
5314
7933
  }
5315
- var MAX_COLD_GUARDS_PER_CHUNK = 12;
5316
- function applyColdFlowGuard(ast, coldFunctionNodes, seed = 2654435769, hotExemptNodes) {
5317
- const decoyIdent = "_d";
7934
+ function applyColdFlowGuard(ast, coldFunctionNodes, seed = 2654435769, hotExemptNodes, windowKeySymbol, expectedDelta, shieldCoupled = false, options) {
5318
7935
  const sfx = (seed >>> 0).toString(36).slice(0, 4);
7936
+ const decoyIdent = `_uDec${sfx}`;
5319
7937
  const sboxIdent = `_uSb${sfx}`;
5320
7938
  const aliasIdentA = `_uAl${sfx}`;
5321
7939
  const aliasIdentB = `_uAm${sfx}`;
5322
7940
  const scratchVarIdent = `_uZt${sfx}`;
7941
+ const mxIdent = `_uMx${sfx}`;
5323
7942
  if (Array.isArray(ast.body)) {
5324
7943
  const alreadyGuarded = ast.body.some(
5325
7944
  (stmt) => stmt.type === "VariableDeclaration" && stmt.declarations?.some(
5326
- (d) => d.id?.type === "Identifier" && (d.id.name === decoyIdent || d.id.name === sboxIdent)
7945
+ (d) => d.id?.type === "Identifier" && (d.id.name === decoyIdent || d.id.name === sboxIdent || d.id.name === mxIdent)
5327
7946
  )
5328
7947
  );
5329
7948
  if (alreadyGuarded) return 0;
5330
7949
  }
7950
+ if (options?.enableBitwiseMba) {
7951
+ applyColdBitwiseMba(ast, coldFunctionNodes, seed, hotExemptNodes);
7952
+ }
5331
7953
  let guardedCount = 0;
5332
7954
  function maybeInjectGuard(node) {
5333
7955
  if (guardedCount >= MAX_COLD_GUARDS_PER_CHUNK) return;
@@ -5354,10 +7976,15 @@ function applyColdFlowGuard(ast, coldFunctionNodes, seed = 2654435769, hotExempt
5354
7976
  aliasIdentA,
5355
7977
  aliasIdentB,
5356
7978
  scratchVarIdent,
5357
- returnDomain
7979
+ mxIdent,
7980
+ returnDomain,
7981
+ windowKeySymbol,
7982
+ expectedDelta,
7983
+ shieldCoupled
5358
7984
  }
5359
7985
  );
5360
7986
  guardedCount++;
7987
+ guardStmt._unpeekGuardSubtree = true;
5361
7988
  if (hotExemptNodes) {
5362
7989
  hotExemptNodes.add(guardStmt);
5363
7990
  hotExemptNodes.add(guardStmt.consequent);
@@ -5384,11 +8011,17 @@ function applyColdFlowGuard(ast, coldFunctionNodes, seed = 2654435769, hotExempt
5384
8011
  aliasIdentA,
5385
8012
  aliasIdentB,
5386
8013
  scratchVarIdent,
5387
- seed
8014
+ seed,
8015
+ mxIdent
5388
8016
  );
5389
8017
  if (hotExemptNodes) {
5390
8018
  hotExemptNodes.add(sharedDecoyDecl);
5391
8019
  hotExemptNodes.add(sboxAliasDecl);
8020
+ for (const decl of sboxAliasDecl.declarations || []) {
8021
+ if (decl.init?.type === "FunctionExpression") {
8022
+ hotExemptNodes.add(decl.init);
8023
+ }
8024
+ }
5392
8025
  for (const decl of sharedDecoyDecl.declarations || []) {
5393
8026
  if (decl.init?.type === "ArrayExpression" && decl.init.elements) {
5394
8027
  for (const el of decl.init.elements) {
@@ -5487,7 +8120,7 @@ function mixOpSeed(seed, salt) {
5487
8120
  h ^= h >>> 13;
5488
8121
  return h | 0;
5489
8122
  }
5490
- function encryptBytecodeStream(plainBytecode, fnSalt, vmKey, stateSlots, accSlots) {
8123
+ function encryptBytecodeStream(plainBytecode, fnSalt, vmKey, stateSlots, accSlots, jumpTargets) {
5491
8124
  const len = plainBytecode.length;
5492
8125
  const enc = new Array(len);
5493
8126
  const stateBefore = new Array(len + 1);
@@ -5518,14 +8151,14 @@ function encryptBytecodeStream(plainBytecode, fnSalt, vmKey, stateSlots, accSlot
5518
8151
  accBefore[len] = ac;
5519
8152
  if (stateSlots) {
5520
8153
  for (const slot of stateSlots) {
5521
- const targetPc = plainBytecode[slot - 1];
8154
+ const targetPc = jumpTargets?.get(slot - 1) ?? plainBytecode[slot - 1];
5522
8155
  const sBefore = stAtSlot.get(slot) ?? 0;
5523
8156
  enc[slot] = stateBefore[targetPc] ^ sBefore | 0;
5524
8157
  }
5525
8158
  }
5526
8159
  if (accSlots) {
5527
8160
  for (const slot of accSlots) {
5528
- const targetPc = plainBytecode[slot - 2];
8161
+ const targetPc = jumpTargets?.get(slot - 2) ?? plainBytecode[slot - 2];
5529
8162
  const aBefore = acAtSlot.get(slot) ?? 0;
5530
8163
  enc[slot] = accBefore[targetPc] ^ aBefore | 0;
5531
8164
  }
@@ -5550,43 +8183,39 @@ function generateOpcodeMap(seed, count = OPCODE_COUNT) {
5550
8183
  }
5551
8184
  return pool.slice(0, count);
5552
8185
  }
5553
- function computeHandlerDelta(op) {
5554
- const delta = (op + 1) * 7 & 31;
5555
- return delta === 0 ? 7 : delta;
8186
+ function computeHandlerBias(seed, op) {
8187
+ const mixed = Math.abs(mixOpSeed(seed, op * 19 + 7)) % 31;
8188
+ return mixed + 1;
5556
8189
  }
5557
- function makeHandlerMbaOffsetExpr(seed, op, deltaOp) {
8190
+ function makeHandlerMbaOffsetExpr(seed, op, bias) {
5558
8191
  const variant = Math.abs(mixOpSeed(seed, op * 11 + 3)) % 4;
5559
8192
  const c1 = mixOpSeed(seed, op * 11 + 5);
5560
8193
  const c2 = mixOpSeed(seed, op * 11 + 7);
5561
8194
  if (variant === 0) {
5562
- const cSum = c1 + c2 - deltaOp | 0;
8195
+ const cSum = c1 + c2 - bias | 0;
5563
8196
  return `(((((($f.ac|${c1})+($f.ac&${c1}))|0)|((($f.p^${c2})+(($f.p&${c2})<<1))|0))+((((($f.ac|${c1})+($f.ac&${c1}))|0)&((($f.p^${c2})+(($f.p&${c2})<<1))|0))))-(((((($f.ac^$f.p)+(($f.ac&$f.p)<<1))|0)|${cSum})+((((($f.ac^$f.p)+(($f.ac&$f.p)<<1))|0)&${cSum})))|0))|0`;
5564
8197
  }
5565
8198
  if (variant === 1) {
5566
- const cSum = c1 + c2 + deltaOp | 0;
8199
+ const cSum = c1 + c2 + bias | 0;
5567
8200
  return `((((($f.ac|$f.p)<<1)-($f.ac^$f.p))+${cSum})-((($f.ac^${c1})+(($f.ac&${c1})<<1))+(($f.p|${c2})+($f.p&${c2}))))|0`;
5568
8201
  }
5569
8202
  if (variant === 2) {
5570
- const cFold2 = 1 + deltaOp - c1 - c2 | 0;
8203
+ const cFold2 = 1 + bias - c1 - c2 | 0;
5571
8204
  return `(((~$f.ac|${c1})+(~$f.ac&${c1}))+(($f.ac|$f.p)-(~$f.ac&$f.p))+(($f.p&${c2})+(~$f.p&${c2}))+${cFold2})|0`;
5572
8205
  }
5573
- const cFold = c1 - deltaOp | 0;
8206
+ const cFold = c1 - bias | 0;
5574
8207
  return `((((($f.ac|$f.p)-(~$f.ac&$f.p))|${c1})+((($f.ac|$f.p)-(~$f.ac&$f.p))&${c1}))-(((($f.ac&${c2})+($f.ac&~${c2}))^${cFold})+(((($f.ac&${c2})+($f.ac&~${c2}))&${cFold})<<1)))|0`;
5575
8208
  }
5576
8209
  function wrapHandlerWithMba(seed, op, coreBody, isTerminal = false) {
5577
- const deltaOp = computeHandlerDelta(op);
5578
- const zExpr = makeHandlerMbaOffsetExpr(seed, op, deltaOp);
8210
+ const bias = computeHandlerBias(seed, op);
8211
+ const zExpr = makeHandlerMbaOffsetExpr(seed, op, bias);
5579
8212
  const shape = Math.abs(mixOpSeed(seed, op * 17 + 1)) % 3;
5580
8213
  const zVar = shape === 0 ? "$z0" : shape === 1 ? "$m0" : "$k0";
5581
8214
  const tail = isTerminal ? "return void 0;" : shape === 0 ? "return $step($f);" : shape === 1 ? "var $nx=$step($f);return $nx;" : "return $f.d?void 0:$step($f);";
5582
- const balancedOffset = `(${zVar}-${deltaOp})`;
5583
- const adjustedBody = coreBody.replace(/\$Z/g, balancedOffset);
5584
- if (coreBody.includes("$Z")) {
5585
- return `function($f){var ${zVar}=${zExpr};${adjustedBody}${tail}}`;
5586
- }
5587
- return `function($f){var ${zVar}=${zExpr};$f.r=($f.r+${balancedOffset})|0;${adjustedBody}${tail}}`;
8215
+ const adjustedBody = coreBody.replace(/\$Z/g, zVar).replace(/\$B/g, String(bias));
8216
+ return `function($f){var ${zVar}=${zExpr};${adjustedBody}${tail}}`;
5588
8217
  }
5589
- function createInterpreterSource(vmHelperName, opMap, seed = 2654435769, windowKeySymbol, expectedDelta) {
8218
+ function createInterpreterSource(vmHelperName, opMap, seed = 2654435769, windowKeySymbol, expectedDelta, expectedStateHash) {
5590
8219
  const opCount = opMap.length;
5591
8220
  const slotMap = shuffleRange(opCount, (seed ^ 1367130551) >>> 0);
5592
8221
  const pairOrder = shuffleRange(opCount, (seed ^ 1013904242) >>> 0);
@@ -5601,52 +8230,52 @@ function createInterpreterSource(vmHelperName, opMap, seed = 2654435769, windowK
5601
8230
  const andImpl = Math.abs(mixOpSeed(seed, OP_AND)) % 2 === 0 ? "~(~$a|~$b)" : "$a&$b";
5602
8231
  const orImpl = Math.abs(mixOpSeed(seed, OP_OR)) % 2 === 0 ? "(($a^$b)+($a&$b))|0" : "$a|$b";
5603
8232
  const coreHandlers = {
5604
- [OP_LDC]: { body: "$f.q[($f.r++)+$Z]=$f.k[$rd($f)];" },
5605
- [OP_LDV]: { body: "$f.q[($f.r++)+$Z]=$f.s[$rd($f)];" },
5606
- [OP_STV]: { body: "$f.s[$rd($f)]=$f.q[(--$f.r)+$Z];" },
5607
- [OP_LDG]: { body: "$f.q[($f.r++)+$Z]=$G[$f.k[$rd($f)]];" },
5608
- [OP_GETP]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a[$b];" },
5609
- [OP_SETP]: { body: "var $v=$f.q[--$f.r],$b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=($a[$b]=$v);" },
5610
- [OP_CALL]: { body: "var $n=$rd($f)+$Z,$g=[];for(var $i=$n-1;$i>=0;$i--)$g[$i]=$f.q[--$f.r];var $fn=$f.q[--$f.r];$f.q[$f.r++]=$fn.apply(void 0,$g);" },
5611
- [OP_MCALL]: { body: "var $n=$rd($f)+$Z,$g=[];for(var $i=$n-1;$i>=0;$i--)$g[$i]=$f.q[--$f.r];var $b=$f.q[--$f.r],$a=$f.q[--$f.r];$f.q[$f.r++]=$a[$b].apply($a,$g);" },
5612
- [OP_ADD]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a+$b;" },
5613
- [OP_SUB]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a-$b;" },
5614
- [OP_MUL]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a*$b;" },
5615
- [OP_XOR]: { body: `var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=${xorImpl};` },
5616
- [OP_AND]: { body: `var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=${andImpl};` },
5617
- [OP_OR]: { body: `var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=${orImpl};` },
5618
- [OP_SEQ]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a===$b;" },
5619
- [OP_LT]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a<$b;" },
5620
- [OP_NOT]: { body: "$f.q[($f.r-1)+$Z]=!$f.q[$f.r-1];" },
5621
- [OP_JMP]: { body: "var $j=$rd($f)+$Z,$ts=$f.c[$f.p++]^$f.st,$ta=$f.c[$f.p++]^$f.ac;$f.p=$j;$f.st=$ts;$f.ac=$ta;" },
5622
- [OP_JZ]: { body: "var $j=$rd($f)+$Z,$ts=$f.c[$f.p++]^$f.st,$ta=$f.c[$f.p++]^$f.ac;if(!$f.q[--$f.r]){$f.p=$j;$f.st=$ts;$f.ac=$ta;}" },
5623
- [OP_RET]: { body: "$f.d=1;$f.v=$f.q[(--$f.r)+$Z];", terminal: true },
5624
- [OP_THROW]: { body: "throw $f.q[(--$f.r)+$Z];" },
8233
+ [OP_LDC]: { body: "$f.q[$f.r++]=$f.k[($rd($f)-$Z)&0xffff];" },
8234
+ [OP_LDV]: { body: "$f.q[$f.r++]=$f.s[($rd($f)-$Z)&0xffff];" },
8235
+ [OP_STV]: { body: "$f.s[($rd($f)-$Z)&0xffff]=$f.q[--$f.r];" },
8236
+ [OP_LDG]: { body: "$f.q[$f.r++]=$G[$f.k[($rd($f)-$Z)&0xffff]];" },
8237
+ [OP_GETP]: { body: "$f.r=($f.r+$Z)|0;var $b=$f.q[($f.r-=1)-$B],$a=$f.q[($f.r-=1)-$B];$f.q[($f.r++)-$B]=$a[$b];$f.r=($f.r-$B)|0;" },
8238
+ [OP_SETP]: { body: "$f.r=($f.r+$Z)|0;var $v=$f.q[($f.r-=1)-$B],$b=$f.q[($f.r-=1)-$B],$a=$f.q[($f.r-=1)-$B];$f.q[($f.r++)-$B]=($a[$b]=$v);$f.r=($f.r-$B)|0;" },
8239
+ [OP_CALL]: { body: "var $n=($rd($f)-$Z)&0xffff,$g=[];for(var $i=$n-1;$i>=0;$i--)$g[$i]=$f.q[--$f.r];var $fn=$f.q[--$f.r];$f.q[$f.r++]=$fn.apply(void 0,$g);" },
8240
+ [OP_MCALL]: { body: "var $n=($rd($f)-$Z)&0xffff,$g=[];for(var $i=$n-1;$i>=0;$i--)$g[$i]=$f.q[--$f.r];var $b=$f.q[--$f.r],$a=$f.q[--$f.r];$f.q[$f.r++]=$a[$b].apply($a,$g);" },
8241
+ [OP_ADD]: { body: "$f.r=($f.r+$Z)|0;var $b=$f.q[($f.r-=1)-$B],$a=$f.q[($f.r-=1)-$B];$f.q[($f.r++)-$B]=$a+$b;$f.r=($f.r-$B)|0;" },
8242
+ [OP_SUB]: { body: "$f.r=($f.r+$Z)|0;var $b=$f.q[($f.r-=1)-$B],$a=$f.q[($f.r-=1)-$B];$f.q[($f.r++)-$B]=$a-$b;$f.r=($f.r-$B)|0;" },
8243
+ [OP_MUL]: { body: "$f.r=($f.r+$Z)|0;var $b=$f.q[($f.r-=1)-$B],$a=$f.q[($f.r-=1)-$B];$f.q[($f.r++)-$B]=$a*$b;$f.r=($f.r-$B)|0;" },
8244
+ [OP_XOR]: { body: `$f.r=($f.r+$Z)|0;var $b=$f.q[($f.r-=1)-$B],$a=$f.q[($f.r-=1)-$B];$f.q[($f.r++)-$B]=${xorImpl};$f.r=($f.r-$B)|0;` },
8245
+ [OP_AND]: { body: `$f.r=($f.r+$Z)|0;var $b=$f.q[($f.r-=1)-$B],$a=$f.q[($f.r-=1)-$B];$f.q[($f.r++)-$B]=${andImpl};$f.r=($f.r-$B)|0;` },
8246
+ [OP_OR]: { body: `$f.r=($f.r+$Z)|0;var $b=$f.q[($f.r-=1)-$B],$a=$f.q[($f.r-=1)-$B];$f.q[($f.r++)-$B]=${orImpl};$f.r=($f.r-$B)|0;` },
8247
+ [OP_SEQ]: { body: "$f.r=($f.r+$Z)|0;var $b=$f.q[($f.r-=1)-$B],$a=$f.q[($f.r-=1)-$B];$f.q[($f.r++)-$B]=$a===$b;$f.r=($f.r-$B)|0;" },
8248
+ [OP_LT]: { body: "$f.r=($f.r+$Z)|0;var $b=$f.q[($f.r-=1)-$B],$a=$f.q[($f.r-=1)-$B];$f.q[($f.r++)-$B]=$a<$b;$f.r=($f.r-$B)|0;" },
8249
+ [OP_NOT]: { body: "$f.r=($f.r+$Z)|0;$f.q[$f.r-(1+$B)]=!$f.q[$f.r-(1+$B)];$f.r=($f.r-$B)|0;" },
8250
+ [OP_JMP]: { body: "var $j=($rd($f)-$Z)&0xffff,$ts=$f.c[$f.p++]^$f.st,$ta=$f.c[$f.p++]^$f.ac;$f.p=$j;$f.st=$ts;$f.ac=$ta;" },
8251
+ [OP_JZ]: { body: "var $j=($rd($f)-$Z)&0xffff,$ts=$f.c[$f.p++]^$f.st,$ta=$f.c[$f.p++]^$f.ac;if(!$f.q[--$f.r]){$f.p=$j;$f.st=$ts;$f.ac=$ta;}" },
8252
+ [OP_RET]: { body: "$f.r=($f.r+$Z)|0;$f.d=1;$f.v=$f.q[($f.r-=1)-$B];$f.r=($f.r-$B)|0;", terminal: true },
8253
+ [OP_THROW]: { body: "$f.r=($f.r+$Z)|0;var $tv=$f.q[($f.r-=1)-$B];$f.r=($f.r-$B)|0;throw $tv;" },
5625
8254
  [OP_AWAIT]: {
5626
- body: "var $v=$f.q[(--$f.r)+$Z];$f.d=2;$f.v=Promise.resolve($v).then(function($w){$f.d=0;$f.q[$f.r++]=$w;return $x($f);},function($e){if($f.e.length>0){var $ex=$f.e.pop();$f.d=0;$f.r=$ex.r;$f.q[$f.r++]=$e;$f.p=$ex.p;$f.st=$ex.s;$f.ac=$ex.a;return $x($f);}throw $e;});",
8255
+ body: "$f.r=($f.r+$Z)|0;var $v=$f.q[($f.r-=1)-$B];$f.r=($f.r-$B)|0;$f.d=2;$f.v=Promise.resolve($v).then(function($w){$f.d=0;$f.q[$f.r++]=$w;return $x($f);},function($e){if($f.e.length>0){var $ex=$f.e.pop();$f.d=0;$f.r=$ex.r;$f.q[$f.r++]=$e;$f.p=$ex.p;$f.st=$ex.s;$f.ac=$ex.a;return $x($f);}throw $e;});",
5627
8256
  terminal: true
5628
8257
  },
5629
- [OP_OBJ]: { body: "var $n=$rd($f)+$Z,$o={},$e=[];for(var $i=0;$i<$n;$i++){var $v=$f.q[--$f.r],$k0=$f.q[--$f.r];$e.push([$k0,$v]);}for(var $i=$e.length-1;$i>=0;$i--){$o[$e[$i][0]]=$e[$i][1];}$f.q[$f.r++]=$o;" },
5630
- [OP_ARR]: { body: "var $n=$rd($f)+$Z,$a=[];for(var $i=$n-1;$i>=0;$i--)$a[$i]=$f.q[--$f.r];$f.q[$f.r++]=$a;" },
5631
- [OP_LDU]: { body: "$f.q[($f.r++)+$Z]=$f.u[$rd($f)][0]();" },
5632
- [OP_STU]: { body: "$f.u[$rd($f)][1]($f.q[(--$f.r)+$Z]);" },
5633
- [OP_DIV]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a/$b;" },
5634
- [OP_MOD]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a%$b;" },
5635
- [OP_SHL]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a<<$b;" },
5636
- [OP_SHR]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a>>$b;" },
5637
- [OP_USHR]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a>>>$b;" },
5638
- [OP_POW]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a**$b;" },
5639
- [OP_EQ]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a==$b;" },
5640
- [OP_TYPEOF]: { body: "$f.q[($f.r-1)+$Z]=typeof $f.q[$f.r-1];" },
5641
- [OP_IN]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a in $b;" },
5642
- [OP_INSTOF]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a instanceof $b;" },
5643
- [OP_NEW]: { body: "var $n=$rd($f)+$Z,$g=[];for(var $i=$n-1;$i>=0;$i--)$g[$i]=$f.q[--$f.r];var $fn=$f.q[--$f.r];$f.q[$f.r++]=new $fn(...$g);" },
5644
- [OP_THIS]: { body: "$f.q[($f.r++)+$Z]=$f.t;" },
5645
- [OP_POP]: { body: "--$f.r;$f.r+=$Z;" },
5646
- [OP_TRY]: { body: "var $cp=$rd($f)+$Z,$cs=$f.c[$f.p++]^$f.st,$ca=$f.c[$f.p++]^$f.ac;$f.e.push({p:$cp,r:$f.r,s:$cs,a:$ca});" },
5647
- [OP_ENDTRY]: { body: "$f.e.pop();$f.r+=$Z;" },
5648
- [OP_NULLISH]: { body: "var $v=$f.q[($f.r-1)+$Z];$f.q[$f.r-1]=($v===null||$v===void 0);" },
5649
- [OP_DUP]: { body: "var $top=$f.q[($f.r-1)+$Z];$f.q[$f.r++]=$top;" }
8258
+ [OP_OBJ]: { body: "var $n=($rd($f)-$Z)&0xffff,$o={},$e=[];for(var $i=0;$i<$n;$i++){var $v=$f.q[--$f.r],$ky=$f.q[--$f.r];$e.push([$ky,$v]);}for(var $i=$e.length-1;$i>=0;$i--){$o[$e[$i][0]]=$e[$i][1];}$f.q[$f.r++]=$o;" },
8259
+ [OP_ARR]: { body: "var $n=($rd($f)-$Z)&0xffff,$a=[];for(var $i=$n-1;$i>=0;$i--)$a[$i]=$f.q[--$f.r];$f.q[$f.r++]=$a;" },
8260
+ [OP_LDU]: { body: "$f.q[$f.r++]=$f.u[($rd($f)-$Z)&0xffff][0]();" },
8261
+ [OP_STU]: { body: "$f.u[($rd($f)-$Z)&0xffff][1]($f.q[--$f.r]);" },
8262
+ [OP_DIV]: { body: "$f.r=($f.r+$Z)|0;var $b=$f.q[($f.r-=1)-$B],$a=$f.q[($f.r-=1)-$B];$f.q[($f.r++)-$B]=$a/$b;$f.r=($f.r-$B)|0;" },
8263
+ [OP_MOD]: { body: "$f.r=($f.r+$Z)|0;var $b=$f.q[($f.r-=1)-$B],$a=$f.q[($f.r-=1)-$B];$f.q[($f.r++)-$B]=$a%$b;$f.r=($f.r-$B)|0;" },
8264
+ [OP_SHL]: { body: "$f.r=($f.r+$Z)|0;var $b=$f.q[($f.r-=1)-$B],$a=$f.q[($f.r-=1)-$B];$f.q[($f.r++)-$B]=$a<<$b;$f.r=($f.r-$B)|0;" },
8265
+ [OP_SHR]: { body: "$f.r=($f.r+$Z)|0;var $b=$f.q[($f.r-=1)-$B],$a=$f.q[($f.r-=1)-$B];$f.q[($f.r++)-$B]=$a>>$b;$f.r=($f.r-$B)|0;" },
8266
+ [OP_USHR]: { body: "$f.r=($f.r+$Z)|0;var $b=$f.q[($f.r-=1)-$B],$a=$f.q[($f.r-=1)-$B];$f.q[($f.r++)-$B]=$a>>>$b;$f.r=($f.r-$B)|0;" },
8267
+ [OP_POW]: { body: "$f.r=($f.r+$Z)|0;var $b=$f.q[($f.r-=1)-$B],$a=$f.q[($f.r-=1)-$B];$f.q[($f.r++)-$B]=$a**$b;$f.r=($f.r-$B)|0;" },
8268
+ [OP_EQ]: { body: "$f.r=($f.r+$Z)|0;var $b=$f.q[($f.r-=1)-$B],$a=$f.q[($f.r-=1)-$B];$f.q[($f.r++)-$B]=$a==$b;$f.r=($f.r-$B)|0;" },
8269
+ [OP_TYPEOF]: { body: "$f.r=($f.r+$Z)|0;$f.q[$f.r-(1+$B)]=typeof $f.q[$f.r-(1+$B)];$f.r=($f.r-$B)|0;" },
8270
+ [OP_IN]: { body: "$f.r=($f.r+$Z)|0;var $b=$f.q[($f.r-=1)-$B],$a=$f.q[($f.r-=1)-$B];$f.q[($f.r++)-$B]=$a in $b;$f.r=($f.r-$B)|0;" },
8271
+ [OP_INSTOF]: { body: "$f.r=($f.r+$Z)|0;var $b=$f.q[($f.r-=1)-$B],$a=$f.q[($f.r-=1)-$B];$f.q[($f.r++)-$B]=$a instanceof $b;$f.r=($f.r-$B)|0;" },
8272
+ [OP_NEW]: { body: "var $n=($rd($f)-$Z)&0xffff,$g=[];for(var $i=$n-1;$i>=0;$i--)$g[$i]=$f.q[--$f.r];var $fn=$f.q[--$f.r];$f.q[$f.r++]=new $fn(...$g);" },
8273
+ [OP_THIS]: { body: "$f.r=($f.r+$Z)|0;$f.q[($f.r++)-$B]=$f.t;$f.r=($f.r-$B)|0;" },
8274
+ [OP_POP]: { body: "$f.r=($f.r+$Z)|0;$f.r=($f.r-(1+$B))|0;" },
8275
+ [OP_TRY]: { body: "var $cp=($rd($f)-$Z)&0xffff,$cs=$f.c[$f.p++]^$f.st,$ca=$f.c[$f.p++]^$f.ac;$f.e.push({p:$cp,r:$f.r,s:$cs,a:$ca});" },
8276
+ [OP_ENDTRY]: { body: "$f.r=($f.r+$Z)|0;$f.e.pop();$f.r=($f.r-$B)|0;" },
8277
+ [OP_NULLISH]: { body: "$f.r=($f.r+$Z)|0;var $v=$f.q[$f.r-(1+$B)];$f.q[$f.r-(1+$B)]=($v===null||$v===void 0);$f.r=($f.r-$B)|0;" },
8278
+ [OP_DUP]: { body: "$f.r=($f.r+$Z)|0;var $top=$f.q[$f.r-(1+$B)];$f.q[($f.r++)-$B]=$top;$f.r=($f.r-$B)|0;" }
5650
8279
  };
5651
8280
  const handlers = new Array(opCount);
5652
8281
  for (let op = 0; op < opCount; op++) {
@@ -5655,17 +8284,25 @@ function createInterpreterSource(vmHelperName, opMap, seed = 2654435769, windowK
5655
8284
  }
5656
8285
  const hasSym = Boolean(windowKeySymbol);
5657
8286
  const hasExpDelta = Boolean(hasSym && expectedDelta !== void 0);
8287
+ const hasExpHash = Boolean(hasSym && expectedStateHash !== void 0);
8288
+ const hasDigest = hasExpDelta || hasExpHash;
5658
8289
  const symPropAccess = hasSym ? /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(windowKeySymbol) ? `.${windowKeySymbol}` : `[${JSON.stringify(windowKeySymbol)}]` : "";
5659
8290
  const symTamperPropAccess = hasSym ? /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(`${windowKeySymbol}_t`) ? `.${windowKeySymbol}_t` : `[${JSON.stringify(`${windowKeySymbol}_t`)}]` : "";
5660
8291
  const symStatePropAccess = hasSym ? /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(`${windowKeySymbol}_s`) ? `.${windowKeySymbol}_s` : `[${JSON.stringify(`${windowKeySymbol}_s`)}]` : "";
5661
8292
  const expD = hasExpDelta ? expectedDelta & 65535 : 0;
8293
+ const expH = hasExpHash ? expectedStateHash | 0 : 0;
5662
8294
  const seed32 = seed | 0;
5663
8295
  const seedU32 = seed >>> 0;
5664
- const scopeKey = hasSym ? computeFnv1aHash(`${windowKeySymbol}:${hasExpDelta ? expD : ""}`, seed) >>> 0 : 0;
5665
- const expDigest = hasExpDelta ? Math.imul(expD ^ seed32 | 0, 2654435761) ^ (expD << 16 | seed32 >>> 16) ^ 2246822507 | 0 : 0;
8296
+ const scopeKey = hasSym ? computeFnv1aHash(
8297
+ `${windowKeySymbol}:${hasExpDelta ? expD : ""}${hasExpHash ? `:${expH}` : ""}`,
8298
+ seed
8299
+ ) >>> 0 : 0;
8300
+ const expDigest = hasExpDelta ? hasExpHash ? Math.imul(expD ^ expH ^ seed32 | 0, 2654435761) ^ (expD << 16 | seed32 >>> 16) ^ (expH >>> 13 | expH << 19) ^ 2246822507 | 0 : Math.imul(expD ^ seed32 | 0, 2654435761) ^ (expD << 16 | seed32 >>> 16) ^ 2246822507 | 0 : hasExpHash ? Math.imul(expH ^ seed32 | 0, 2654435761) ^ (expH >>> 13 | expH << 19) ^ 2246822507 | 0 : 0;
5666
8301
  const selfPrettyCheck = "$pp||/\\n/.test(Function.prototype.toString.call($vm))";
5667
- const tamperCheckExpr = hasSym ? `var $bad=${selfPrettyCheck}||($G&&($G[$tk]===!0||$G${symTamperPropAccess}===!0||($G${symStatePropAccess}&&$G${symStatePropAccess}[0]===2))),$sv=$G?$G${symPropAccess}:void 0;if(!$bad){if($sv===void 0){if(typeof window>"u"&&typeof document>"u"&&typeof self>"u")$bad=!0;}else if(Array.isArray($sv)){if($sv[0]===2)$bad=!0;}${hasExpDelta ? `else if($sv!==($sv|0)){$bad=!0;}else{var $sh=(Math.imul(($sv^$S)|0,0x9e3779b1)^(($sv<<16)|($S>>>16))^0x85ebca6b)|0;if($sh!==$D)$bad=!0;}` : ""}}` : `var $bad=${selfPrettyCheck}||($G&&$G[$tk]===!0);`;
5668
- const paramsList = hasExpDelta ? "$P,$A,$B,$C,$S,$D" : "$P,$A,$B,$C,$S";
8302
+ const asyncEnvGuard = "var $br=(typeof window<'u'&&typeof document<'u'&&window.document===document&&document.nodeType===9&&document.scripts&&document.scripts.length>0&&document.readyState!==['co','mp','le','te'].join(''))||(typeof self<'u'&&typeof self.importScripts===['fu','nct','ion'].join(''));";
8303
+ const svPresentBranch = hasExpHash ? hasExpDelta ? "else if(!Array.isArray($sr)||$sr[0]!==1||$sv!==($sv|0)){$bad=!0;}else{var $s1=$sr[1]|0,$sh=(Math.imul(($sv^$s1^$S)|0,0x9e3779b1)^(($sv<<16)|($S>>>16))^(($s1>>>13)|($s1<<19))^0x85ebca6b)|0;if($sh!==$D)$bad=!0;}" : "else if(!Array.isArray($sr)||$sr[0]!==1){$bad=!0;}else{var $s1=$sr[1]|0,$sh=(Math.imul(($s1^$S)|0,0x9e3779b1)^(($s1>>>13)|($s1<<19))^0x85ebca6b)|0;if($sh!==$D)$bad=!0;}" : `else if(Array.isArray($sv)){if($sv[0]===2)$bad=!0;}${hasExpDelta ? "else if($sv!==($sv|0)){$bad=!0;}else{var $sh=(Math.imul(($sv^$S)|0,0x9e3779b1)^(($sv<<16)|($S>>>16))^0x85ebca6b)|0;if($sh!==$D)$bad=!0;}" : ""}`;
8304
+ const tamperCheckExpr = hasSym ? `var $sr=$G?$G${symStatePropAccess}:void 0,$bad=${selfPrettyCheck}||($G&&($G[$tk]===!0||$G${symTamperPropAccess}===!0||($sr&&$sr[0]===2))),$sv=$G?$G${symPropAccess}:void 0;if(!$bad){${asyncEnvGuard}if($sv===void 0){if(!$br)$bad=!0;}${svPresentBranch}}` : `var $bad=${selfPrettyCheck}||($G&&$G[$tk]===!0);`;
8305
+ const paramsList = hasDigest ? "$P,$A,$B,$C,$S,$D" : "$P,$A,$B,$C,$S";
5669
8306
  const factoryRaw = `(function $I(${paramsList}){var $G=typeof globalThis<"u"?globalThis:(typeof window<"u"?window:(typeof self<"u"?self:this));var $pp=/\\n/.test(Function.prototype.toString.call($I));var $rk=['__','unp','eek','_vm'].join('');var $rg=0,$rs=0;try{$rg=$G?($G[$rk]||($G[$rk]={})) : 0;$rs=$rg?($rg[${scopeKey}]||($rg[${scopeKey}]={})) : 0;if(!$pp&&$rs&&$rs[${seedU32}])return $rs[${seedU32}];}catch($e){}var $tk=['__','unp','eek','_ta','mpe','red'].join('');var $M=[],$ok=$A&255,$sk=$B&255,$vk=$C|0;for(var $j=0;$j<$P.length;$j+=2)$M[$P[$j]]=$P[$j+1];function $rd($f){var $p=$f.p++;var $x0=$f.st=(Math.imul($f.st^($p+1),0x45d9f3b)+(($f.ac|0x9e3779b9)+($f.ac&0x9e3779b9)))|0;var $w=$f.c[$p],$v=$w^(($x0>>>16)&0xffff);$f.st=($f.st^Math.imul($w+1,0x85ebca6b))|0;$f.ac=(Math.imul($f.ac^$v,0x27d4eb2d)^(($f.st>>>13)|($f.st<<19)))|0;return $v;}var $H=[${handlers.join(
5670
8307
  ","
5671
8308
  )}];function $step($f){if($f.d||$f.p>=$f.c.length)return void 0;var $o=$rd($f),$m=$M[$o^$ok];return $m!==void 0?$H[$m^$sk]:void 0;}function $x($f){var $fn=$step($f);while($fn!==void 0){try{$fn=$fn($f);}catch($err){if($f.e.length>0){var $ex=$f.e.pop();$f.r=$ex.r;$f.q[$f.r++]=$err;$f.p=$ex.p;$f.st=$ex.s;$f.ac=$ex.a;$fn=$step($f);}else{throw $err;}}}return $f.v;}var $vm=function($c,$k,$s0,$t,$a,$u){${tamperCheckExpr}var $flt=$bad?(Math.imul($vk^$a,0x45d9f3b)|1):0;return $x({c:$c,k:$k,s:$s0,t:$t,u:$u||[],q:[],r:0,p:0,st:($vk^$a^$flt)|0,ac:($vk^($a<<5)^0x517cc1b7^$flt)|0,e:[],d:0,v:void 0});};try{if(!$pp&&$rs)$rs[${seedU32}]=$vm;}catch($e){}return $vm;})`;
@@ -5677,7 +8314,7 @@ function createInterpreterSource(vmHelperName, opMap, seed = 2654435769, windowK
5677
8314
  const argA = opMask & 255;
5678
8315
  const argB = slotMask & 255;
5679
8316
  const argC = vmKey | 0;
5680
- return `var ${vmHelperName}=(${compactFactory})([${pairs.join(",")}],${argA},${argB},${argC},${seed32}${hasExpDelta ? `,${expDigest}` : ""});`;
8317
+ return `var ${vmHelperName}=(${compactFactory})([${pairs.join(",")}],${argA},${argB},${argC},${seed32}${hasDigest ? `,${expDigest}` : ""});`;
5681
8318
  }
5682
8319
  function walkWithParent(node, parent, visitor) {
5683
8320
  if (!node || typeof node !== "object") return;
@@ -5914,11 +8551,13 @@ function definitelyTerminates(stmt) {
5914
8551
  return false;
5915
8552
  }
5916
8553
  }
5917
- function compileFunctionToBytecode(fnNode, opMap, enclosingBindings) {
8554
+ function compileFunctionToBytecode(fnNode, opMap, enclosingBindings, seed = 2654435769) {
5918
8555
  const bytecode = [];
5919
8556
  const consts = [];
5920
8557
  const stateSlots = /* @__PURE__ */ new Set();
5921
8558
  const accSlots = /* @__PURE__ */ new Set();
8559
+ const jumpTargets = /* @__PURE__ */ new Map();
8560
+ const jumpOps = /* @__PURE__ */ new Map();
5922
8561
  const fnScope = /* @__PURE__ */ new Map();
5923
8562
  const scopeStack = [fnScope];
5924
8563
  const upvalues = [];
@@ -6047,17 +8686,24 @@ function compileFunctionToBytecode(fnNode, opMap, enclosingBindings) {
6047
8686
  }
6048
8687
  function emit(op, ...args) {
6049
8688
  bytecode.push(opMap[op]);
6050
- for (const a of args) bytecode.push(a);
8689
+ if (args.length === 1) {
8690
+ bytecode.push(args[0] + computeHandlerBias(seed, op) & 65535);
8691
+ } else {
8692
+ for (const a of args) bytecode.push(a);
8693
+ }
6051
8694
  }
6052
8695
  function emitJumpPlaceholder(op) {
6053
8696
  const pos = bytecode.length;
6054
8697
  emit(op, 0, 0, 0);
8698
+ jumpOps.set(pos, op);
6055
8699
  stateSlots.add(pos + 2);
6056
8700
  accSlots.add(pos + 3);
6057
8701
  return pos;
6058
8702
  }
6059
8703
  function patchJump(pos, targetPc) {
6060
- bytecode[pos + 1] = targetPc;
8704
+ const op = jumpOps.get(pos) ?? OP_JMP;
8705
+ jumpTargets.set(pos + 1, targetPc);
8706
+ bytecode[pos + 1] = targetPc + computeHandlerBias(seed, op) & 65535;
6061
8707
  }
6062
8708
  function compilePatternAssignFromSlot(pattern, sourceSlot) {
6063
8709
  if (!pattern) return false;
@@ -6920,7 +9566,7 @@ function compileFunctionToBytecode(fnNode, opMap, enclosingBindings) {
6920
9566
  emit(OP_LDC, addConst(void 0));
6921
9567
  emit(OP_RET);
6922
9568
  }
6923
- return { bytecode, consts, localCount, stateSlots, accSlots, upvalues };
9569
+ return { bytecode, consts, localCount, stateSlots, accSlots, jumpTargets, upvalues };
6924
9570
  }
6925
9571
  function findInjectedVmHelperName(ast) {
6926
9572
  if (!ast || !Array.isArray(ast.body)) return null;
@@ -7177,7 +9823,7 @@ function applyMicroVm(ast, coldFunctionNodes, serializedFunctionNodes, seed = 26
7177
9823
  if (!lowered) {
7178
9824
  continue;
7179
9825
  }
7180
- const compiled = compileFunctionToBytecode(lowered.loweredFn, opMap, enclosingBindings);
9826
+ const compiled = compileFunctionToBytecode(lowered.loweredFn, opMap, enclosingBindings, seed);
7181
9827
  if (!compiled) {
7182
9828
  continue;
7183
9829
  }
@@ -7187,7 +9833,8 @@ function applyMicroVm(ast, coldFunctionNodes, serializedFunctionNodes, seed = 26
7187
9833
  fnSalt,
7188
9834
  vmKey,
7189
9835
  compiled.stateSlots,
7190
- compiled.accSlots
9836
+ compiled.accSlots,
9837
+ compiled.jumpTargets
7191
9838
  );
7192
9839
  const constElements = compiled.consts.map((c) => {
7193
9840
  if (c === void 0) {
@@ -7307,7 +9954,8 @@ function applyMicroVm(ast, coldFunctionNodes, serializedFunctionNodes, seed = 26
7307
9954
  opMap,
7308
9955
  seed,
7309
9956
  windowKeySymbol,
7310
- expectedDelta
9957
+ expectedDelta,
9958
+ extraOpts?.expectedStateHash
7311
9959
  );
7312
9960
  const parsedHelper = acorn6.parse(interpreterSource, {
7313
9961
  ecmaVersion: "latest",
@@ -7475,7 +10123,7 @@ function isAstAlreadyProtected(ast) {
7475
10123
  for (const d of stmt.declarations) {
7476
10124
  const name = d.id?.type === "Identifier" ? d.id.name : void 0;
7477
10125
  if (typeof name === "string") {
7478
- if (name === "_d" || name.startsWith("_uC") || name.startsWith("_uD") || name.startsWith("_uS") || name.startsWith("_uVm") || name.startsWith("_wKdf") || name.startsWith("_uP") || name.startsWith("_uCache") || name.startsWith("_uDc") || name.startsWith("_m") || name.startsWith("_w") || name.startsWith("_k") || d.init?.type === "CallExpression" && d.init.callee?.type === "FunctionExpression" && d.init.callee?.id?.name === "f" && d.init.arguments?.[0]?.type === "ArrayExpression" || d.init?.type === "CallExpression" && d.init.callee?.type === "MemberExpression" && d.init.callee.object?.type === "Identifier" && d.init.callee.object.name === "Symbol" && d.init.callee.property?.type === "Identifier" && d.init.callee.property.name === "for" && typeof d.init.arguments?.[0]?.value === "string" && d.init.arguments[0].value.startsWith("__upk_v4_")) {
10126
+ if (name.startsWith("_uC") || name.startsWith("_uD") || name.startsWith("_uS") || name.startsWith("_uSb") || name.startsWith("_uDec") || name.startsWith("_uAl") || name.startsWith("_uAm") || name.startsWith("_uZt") || name.startsWith("_uVm") || name.startsWith("_wKdf") || name.startsWith("_uP") || name.startsWith("_uCache") || name.startsWith("_uDc") || d.init?.type === "CallExpression" && d.init.callee?.type === "FunctionExpression" && d.init.callee?.id?.name === "f" && d.init.arguments?.[0]?.type === "ArrayExpression" || d.init?.type === "CallExpression" && d.init.callee?.type === "MemberExpression" && d.init.callee.object?.type === "Identifier" && d.init.callee.object.name === "Symbol" && d.init.callee.property?.type === "Identifier" && d.init.callee.property.name === "for" && typeof d.init.arguments?.[0]?.value === "string" && d.init.arguments[0].value.startsWith("__upk_v4_")) {
7479
10127
  return true;
7480
10128
  }
7481
10129
  }
@@ -7483,7 +10131,7 @@ function isAstAlreadyProtected(ast) {
7483
10131
  }
7484
10132
  if (stmt.type === "FunctionDeclaration" && stmt.id?.type === "Identifier") {
7485
10133
  const fnName = stmt.id.name;
7486
- if (typeof fnName === "string" && (fnName.startsWith("_uD") || fnName.startsWith("_uVm") || fnName.startsWith("_wKdf") || fnName.startsWith("_hX"))) {
10134
+ if (typeof fnName === "string" && (fnName.startsWith("_uD") || fnName.startsWith("_uVm") || fnName.startsWith("_wKdf") || fnName === "_hX")) {
7487
10135
  return true;
7488
10136
  }
7489
10137
  }
@@ -7491,7 +10139,7 @@ function isAstAlreadyProtected(ast) {
7491
10139
  const callee = stmt.expression.callee;
7492
10140
  if (callee?.type === "FunctionExpression") {
7493
10141
  const name = callee.id?.name;
7494
- if (typeof name === "string" && (name.startsWith("_u$") || name.startsWith("_$") || name.startsWith("_s") || name.startsWith("$b") || containsUnpeekShieldMarker(callee.body))) {
10142
+ if (typeof name === "string" && name.startsWith("_u$") || containsUnpeekShieldMarker(callee.body)) {
7495
10143
  return true;
7496
10144
  }
7497
10145
  }
@@ -7568,7 +10216,8 @@ function transformJavaScript(code, options = {}) {
7568
10216
  attachMagicComments(boundary.importExpressions, comments);
7569
10217
  const effectiveConfig = options.critical ? { ...options.config ?? {}, critical: options.critical } : options.config;
7570
10218
  const effectiveProfile = options.profile ?? effectiveConfig?.profile;
7571
- const hotRes = analyzeAstHotPaths(ast, effectiveConfig);
10219
+ const originalSourceMap = internalOptions.originalSourceMap;
10220
+ const hotRes = analyzeAstHotPaths(ast, effectiveConfig, originalSourceMap);
7572
10221
  const {
7573
10222
  report: hotPathReport,
7574
10223
  coldFunctionNodes,
@@ -7593,20 +10242,27 @@ function transformJavaScript(code, options = {}) {
7593
10242
  const detectHeadless = internalOptions.detectHeadless ?? effectiveConfig?.shield?.detectHeadless ?? false;
7594
10243
  const sym = shieldCoupled ? internalOptions.windowKeySymbol ?? deriveWindowKeySymbol(seed) : void 0;
7595
10244
  let shieldDelta = shieldCoupled ? internalOptions.expectedDelta : void 0;
7596
- if (shieldCoupled && shieldDelta === void 0) {
10245
+ let expectedStateHash = shieldCoupled ? internalOptions.expectedStateHash : void 0;
10246
+ if (shieldCoupled && (shieldDelta === void 0 || expectedStateHash === void 0)) {
7597
10247
  const shieldInfo = generateRuntimeShield({
7598
10248
  seed,
7599
10249
  windowKeySymbol: sym,
7600
10250
  deterrentMode,
7601
10251
  detectHeadless
7602
10252
  });
7603
- shieldDelta = shieldInfo.expectedDelta ?? 0;
10253
+ if (shieldDelta === void 0) {
10254
+ shieldDelta = shieldInfo.expectedDelta ?? 0;
10255
+ }
10256
+ if (expectedStateHash === void 0) {
10257
+ expectedStateHash = shieldInfo.expectedStateHash;
10258
+ }
7604
10259
  }
7605
10260
  let virtualizedFunctionsCount = 0;
7606
10261
  if (isAggressive) {
7607
- const extraVmOpts = criticalFunctionNodes || effectiveConfig?.critical?.maxFunctionsPerChunk !== void 0 ? {
10262
+ const extraVmOpts = criticalFunctionNodes || effectiveConfig?.critical?.maxFunctionsPerChunk !== void 0 || expectedStateHash !== void 0 ? {
7608
10263
  ...criticalFunctionNodes ? { criticalFunctionNodes } : {},
7609
- ...effectiveConfig?.critical?.maxFunctionsPerChunk !== void 0 ? { maxFunctionsPerChunk: effectiveConfig.critical.maxFunctionsPerChunk } : {}
10264
+ ...effectiveConfig?.critical?.maxFunctionsPerChunk !== void 0 ? { maxFunctionsPerChunk: effectiveConfig.critical.maxFunctionsPerChunk } : {},
10265
+ ...expectedStateHash !== void 0 ? { expectedStateHash } : {}
7610
10266
  } : void 0;
7611
10267
  const vmRes = extraVmOpts ? applyMicroVm(
7612
10268
  ast,
@@ -7627,7 +10283,16 @@ function transformJavaScript(code, options = {}) {
7627
10283
  virtualizedFunctionsCount = vmRes.virtualizedCount;
7628
10284
  }
7629
10285
  if (effectiveProfile !== "minimal" && effectiveConfig?.coldFlow !== false) {
7630
- applyColdFlowGuard(ast, coldFunctionNodes, seed, hotExemptNodes);
10286
+ applyColdFlowGuard(
10287
+ ast,
10288
+ coldFunctionNodes,
10289
+ seed,
10290
+ hotExemptNodes,
10291
+ sym,
10292
+ shieldDelta,
10293
+ shieldCoupled,
10294
+ { enableBitwiseMba: isAggressive || effectiveProfile === "strict" }
10295
+ );
7631
10296
  }
7632
10297
  const mangledSymbolsCount = applyPolymorphicMangler(
7633
10298
  ast,
@@ -7723,11 +10388,20 @@ ${finalCode}`;
7723
10388
 
7724
10389
  export {
7725
10390
  computeFnv1aHash,
10391
+ flattenSourceMapSections,
10392
+ shiftSourceMapLines,
10393
+ computeDeterministicDebugId,
10394
+ chainSourceMaps,
10395
+ resolvePosition,
10396
+ safeDecodeURIComponent,
10397
+ symbolicateStackTrace,
7726
10398
  detectHotPaths,
7727
10399
  computeIntegrityHash,
7728
10400
  verifyCodeIntegrity,
7729
10401
  deriveWindowKeySymbol,
7730
10402
  createDeterrentSnippet,
7731
10403
  generateRuntimeShield,
10404
+ classifyPlaintextSecret,
10405
+ hasRegexSecretRun,
7732
10406
  transformJavaScript
7733
10407
  };