unpeek 4.0.0 → 4.1.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 (64) hide show
  1. package/README.md +21 -12
  2. package/README.tr.md +20 -11
  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 +4 -4
  31. package/dist/browser.d.ts +4 -4
  32. package/dist/browser.js +1 -1
  33. package/dist/chunk-32GLSJAW.js +614 -0
  34. package/dist/{chunk-W77DAC3H.js → chunk-6EWFL4LQ.js} +16 -0
  35. package/dist/{chunk-4FNZNIBW.js → chunk-6KLUNEKE.js} +2538 -547
  36. package/dist/chunk-AD6UFBPA.cjs +614 -0
  37. package/dist/{chunk-X6EETCO6.cjs → chunk-BQ2O6HM5.cjs} +16 -0
  38. package/dist/{chunk-ZG7BIAUI.cjs → chunk-FLZ4FSP5.cjs} +58 -17
  39. package/dist/{chunk-2JU3V7HW.js → chunk-HV47WJIR.js} +52 -11
  40. package/dist/{chunk-VG4Y26ZN.cjs → chunk-Q4DFRMAV.cjs} +53 -36
  41. package/dist/{chunk-HHC7BUCK.js → chunk-STTUFUDC.js} +114 -16
  42. package/dist/{chunk-YCRMTXOE.js → chunk-TOUYQ4N5.js} +30 -13
  43. package/dist/{chunk-KLYFNMKS.cjs → chunk-VLL4THTG.cjs} +2727 -736
  44. package/dist/{chunk-7HXLHLLQ.cjs → chunk-WYW5UOBE.cjs} +136 -38
  45. package/dist/cli/index.js +2240 -572
  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 +186 -47
  55. package/dist/index.d.cts +6 -6
  56. package/dist/index.d.ts +6 -6
  57. package/dist/index.js +174 -35
  58. package/dist/plugins/unplugin.cjs +4 -4
  59. package/dist/plugins/unplugin.js +3 -3
  60. package/dist/{types-CMtZnV8C.d.ts → types-BZqvBhBI.d.ts} +4 -2
  61. package/dist/{types-D93PuOOl.d.cts → types-E4ugA4Oz.d.cts} +4 -2
  62. package/package.json +1 -1
  63. package/dist/chunk-3LWXEJU6.cjs +0 -1054
  64. package/dist/chunk-ADKRENAP.js +0 -1054
@@ -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",
@@ -97,7 +946,19 @@ var DEFAULT_HOC_WRAPPERS = /* @__PURE__ */ new Set([
97
946
  "connect"
98
947
  ]);
99
948
  var DEFAULT_EVENT_HANDLER_REGEX = /^(?:on|handle)(?!Tick|Render|Update|Frame|Animate|Physics)[A-Z]/;
949
+ var CRITICAL_COLD_HANDLER_REGEX = /^(?:onSubmit|handleSubmit|submit[A-Z0-9_]*|validate[A-Z0-9_]*|login|signIn|register|checkout)$/i;
950
+ var CRITICAL_COLD_CALLEE_REGEX = /^(?:onSubmit|handleSubmit|submit[A-Z0-9_]*|validate[A-Z0-9_]*|login|signIn|register|checkout|createServerReference|fetch)$/i;
100
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
+ ]);
101
962
  var REACT_HOOK_OR_RENDER_CALLS = /* @__PURE__ */ new Set([
102
963
  "useState",
103
964
  "useEffect",
@@ -112,7 +973,10 @@ var REACT_HOOK_OR_RENDER_CALLS = /* @__PURE__ */ new Set([
112
973
  "jsxs",
113
974
  "_jsx",
114
975
  "_jsxs",
115
- "createElement"
976
+ "jsxDEV",
977
+ "_jsxDEV",
978
+ "createElement",
979
+ "cloneElement"
116
980
  ]);
117
981
  var FUNCTION_NODE_TYPES = /* @__PURE__ */ new Set([
118
982
  "FunctionDeclaration",
@@ -154,9 +1018,16 @@ function parseJavaScriptAst(code, comments, opts) {
154
1018
  }
155
1019
  return ast;
156
1020
  }
157
- function isHocCall(callNode, hocWrappers) {
158
- if (!callNode || callNode.type !== "CallExpression") return false;
159
- 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);
160
1031
  if (!callee) return false;
161
1032
  const wrappers = hocWrappers ?? DEFAULT_HOC_WRAPPERS;
162
1033
  if (callee.type === "Identifier") {
@@ -169,6 +1040,9 @@ function isHocCall(callNode, hocWrappers) {
169
1040
  if (wrappers.has(full2)) return true;
170
1041
  }
171
1042
  }
1043
+ if (callee.type === "CallExpression") {
1044
+ return isHocCall(callee, wrappers, depth + 1);
1045
+ }
172
1046
  return false;
173
1047
  }
174
1048
  function getFunctionLabel(node, ancestors, hocWrappers) {
@@ -218,8 +1092,73 @@ function getFunctionLabel(node, ancestors, hocWrappers) {
218
1092
  }
219
1093
  return `anonymous_${node.start}`;
220
1094
  }
221
- function isPascalCaseComponent(name) {
222
- 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
+ );
223
1162
  }
224
1163
  function isEventHandlerName(name, regex = DEFAULT_EVENT_HANDLER_REGEX) {
225
1164
  return regex.test(name);
@@ -298,7 +1237,7 @@ function containsLoopOrAnimation(fnNode, animationCalls = ANIMATION_FRAME_CALLS)
298
1237
  });
299
1238
  return found;
300
1239
  }
301
- function analyzeAstHotPaths(ast, config) {
1240
+ function analyzeAstHotPaths(ast, config, originalSourceMap) {
302
1241
  const hotFunctionNodes = /* @__PURE__ */ new WeakSet();
303
1242
  const coldFunctionNodes = /* @__PURE__ */ new WeakSet();
304
1243
  const hotExemptNodes = /* @__PURE__ */ new WeakSet();
@@ -440,9 +1379,50 @@ function analyzeAstHotPaths(ast, config) {
440
1379
  }
441
1380
  return anchorStart;
442
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
+ }
443
1418
  function registerFunctionNode(node, ancestors) {
444
1419
  const name = getFunctionLabel(node, ancestors, hocWrappers);
445
- 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
+ });
446
1426
  fnByName.set(name, node);
447
1427
  const paramSet = /* @__PURE__ */ new Set();
448
1428
  for (const p of node.params || []) {
@@ -491,7 +1471,8 @@ function analyzeAstHotPaths(ast, config) {
491
1471
  }
492
1472
  }
493
1473
  fnScopeChain.set(node, chain);
494
- if (isPascalCaseComponent(name) && !excludedComponents.has(name)) {
1474
+ if (isPascalCaseComponent(name, node, ancestors, hocWrappers, isHookName) && !excludedComponents.has(name)) {
1475
+ node._unpeekIsComponent = true;
495
1476
  shallowComponentNodes.add(node);
496
1477
  hotFunctionNodes.add(node);
497
1478
  directHotNodes.add(node);
@@ -603,7 +1584,7 @@ function analyzeAstHotPaths(ast, config) {
603
1584
  }
604
1585
  },
605
1586
  CallExpression(node, _state, ancestors) {
606
- const callee = node.callee;
1587
+ const callee = unwrapCallee(node.callee);
607
1588
  let calleeName = "";
608
1589
  let memberProp = "";
609
1590
  let qualifiedCall = "";
@@ -734,6 +1715,9 @@ function analyzeAstHotPaths(ast, config) {
734
1715
  }
735
1716
  if (REACT_HOOK_OR_RENDER_CALLS.has(calleeName) || REACT_HOOK_OR_RENDER_CALLS.has(memberProp) || isHookName(calleeName) || isHookName(memberProp)) {
736
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
+ }
737
1721
  shallowComponentNodes.add(enclosingFn);
738
1722
  hotFunctionNodes.add(enclosingFn);
739
1723
  directHotNodes.add(enclosingFn);
@@ -882,56 +1866,36 @@ function analyzeAstHotPaths(ast, config) {
882
1866
  }
883
1867
  }
884
1868
  }
885
- const calleeToCallers = /* @__PURE__ */ new Map();
886
- for (const [callerNode, calleeNames] of callerToCallees.entries()) {
887
- for (const cName of calleeNames) {
888
- const targetNode = resolveCalleeNode(callerNode, cName);
889
- if (targetNode) {
890
- let set = calleeToCallers.get(targetNode);
891
- if (!set) {
892
- set = /* @__PURE__ */ new Set();
893
- calleeToCallers.set(targetNode, set);
894
- }
895
- set.add(callerNode);
896
- }
897
- }
898
- }
899
- let changed = true;
900
- while (changed) {
901
- changed = false;
902
- for (const [callerNode, calleeNames] of callerToCallees.entries()) {
903
- if (hotFunctionNodes.has(callerNode) || shallowComponentNodes.has(callerNode) || coldForcedNodes.has(callerNode)) {
904
- continue;
905
- }
906
- for (const cName of calleeNames) {
907
- const targetNode = resolveCalleeNode(callerNode, cName);
908
- if (targetNode && trueHotNodes.has(targetNode)) {
909
- const callers = calleeToCallers.get(targetNode);
910
- const isDedicatedPipeline = callers && callers.size <= maxPipelineCallers;
911
- if (isDedicatedPipeline) {
912
- trueHotNodes.add(callerNode);
913
- hotFunctionNodes.add(callerNode);
914
- hotExemptNodes.add(callerNode);
915
- changed = true;
916
- break;
1869
+ for (const fn of allFunctions) {
1870
+ if (!serializedWorkerNodes.has(fn.node) && !trueHotNodes.has(fn.node) && !shallowComponentNodes.has(fn.node) && !containsLoopOrAnimation(fn.node, animationCalls)) {
1871
+ let isCriticalHandler = CRITICAL_COLD_HANDLER_REGEX.test(fn.name);
1872
+ if (!isCriticalHandler) {
1873
+ const callees = callerToCallees.get(fn.node);
1874
+ if (callees) {
1875
+ for (const cName of callees) {
1876
+ const bare = cName.includes(".") ? cName.split(".").pop() : cName;
1877
+ if (CRITICAL_COLD_CALLEE_REGEX.test(bare)) {
1878
+ isCriticalHandler = true;
1879
+ break;
1880
+ }
917
1881
  }
918
1882
  }
919
1883
  }
1884
+ if (isCriticalHandler) {
1885
+ coldForcedNodes.add(fn.node);
1886
+ }
920
1887
  }
921
1888
  }
922
- for (const node of coldForcedNodes) {
923
- hotFunctionNodes.delete(node);
924
- hotExemptNodes.delete(node);
925
- }
1889
+ const criticalAnnotation = typeof config?.critical?.annotation === "string" && config.critical.annotation.length > 0 ? config.critical.annotation : "@unpeek-critical";
926
1890
  const astComments = ast?.__unpeekComments ?? ast?.comments ?? [];
927
1891
  const criticalComments = astComments.filter(
928
- (c) => typeof c?.value === "string" && c.value.includes("@unpeek-critical")
1892
+ (c) => typeof c?.value === "string" && c.value.includes(criticalAnnotation)
929
1893
  );
930
1894
  const criticalCommentNodes = /* @__PURE__ */ new Set();
931
1895
  if (criticalComments.length > 0 && allFunctions.length > 0) {
932
1896
  const stmtRanges = [];
933
1897
  walk.full(ast, (n) => {
934
- 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")) {
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")) {
935
1899
  stmtRanges.push({ start: n.start, end: n.end });
936
1900
  }
937
1901
  });
@@ -939,18 +1903,41 @@ function analyzeAstHotPaths(ast, config) {
939
1903
  (a, b) => (a.node.start ?? 0) - (b.node.start ?? 0)
940
1904
  );
941
1905
  for (const c of criticalComments) {
1906
+ const cStart = typeof c.start === "number" ? c.start : 0;
942
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
+ }
943
1916
  const target = sortedFns.find(
944
1917
  (fn) => typeof fn.node.start === "number" && fn.node.start >= cEnd
945
1918
  );
946
- if (!target) continue;
947
- const fnStart = target.node.start;
948
- const fnEnd = target.node.end;
949
- const blockedByStmt = stmtRanges.some(
950
- (s) => !(s.start <= fnStart && fnEnd <= s.end) && s.end > cEnd && s.end <= target.anchorStart
951
- );
952
- if (!blockedByStmt) {
953
- criticalCommentNodes.add(target.node);
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
+ }
954
1941
  }
955
1942
  }
956
1943
  }
@@ -969,6 +1956,71 @@ function analyzeAstHotPaths(ast, config) {
969
1956
  }
970
1957
  }
971
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
+ }
1982
+ const calleeToCallers = /* @__PURE__ */ new Map();
1983
+ for (const [callerNode, calleeNames] of callerToCallees.entries()) {
1984
+ for (const cName of calleeNames) {
1985
+ const targetNode = resolveCalleeNode(callerNode, cName);
1986
+ if (targetNode) {
1987
+ let set = calleeToCallers.get(targetNode);
1988
+ if (!set) {
1989
+ set = /* @__PURE__ */ new Set();
1990
+ calleeToCallers.set(targetNode, set);
1991
+ }
1992
+ set.add(callerNode);
1993
+ }
1994
+ }
1995
+ }
1996
+ let changed = true;
1997
+ while (changed) {
1998
+ changed = false;
1999
+ for (const [callerNode, calleeNames] of callerToCallees.entries()) {
2000
+ if (hotFunctionNodes.has(callerNode) || shallowComponentNodes.has(callerNode) || coldForcedNodes.has(callerNode)) {
2001
+ continue;
2002
+ }
2003
+ for (const cName of calleeNames) {
2004
+ const targetNode = resolveCalleeNode(callerNode, cName);
2005
+ if (targetNode && trueHotNodes.has(targetNode)) {
2006
+ const callers = calleeToCallers.get(targetNode);
2007
+ const isDedicatedPipeline = callers && callers.size <= maxPipelineCallers;
2008
+ if (isDedicatedPipeline) {
2009
+ trueHotNodes.add(callerNode);
2010
+ hotFunctionNodes.add(callerNode);
2011
+ hotExemptNodes.add(callerNode);
2012
+ changed = true;
2013
+ break;
2014
+ }
2015
+ }
2016
+ }
2017
+ }
2018
+ }
2019
+ for (const node of coldForcedNodes) {
2020
+ shallowComponentNodes.delete(node);
2021
+ hotFunctionNodes.delete(node);
2022
+ hotExemptNodes.delete(node);
2023
+ }
972
2024
  const hotFunctionsSkipped = [];
973
2025
  const coldFunctionsProtected = [];
974
2026
  for (const fn of allFunctions) {
@@ -977,7 +2029,7 @@ function analyzeAstHotPaths(ast, config) {
977
2029
  } else {
978
2030
  coldFunctionNodes.add(fn.node);
979
2031
  coldFunctionsProtected.push(fn.name);
980
- 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)) {
981
2033
  criticalFunctionNodes.add(fn.node);
982
2034
  }
983
2035
  }
@@ -1021,30 +2073,167 @@ function computeNormalizedIntegrityHash(source, seed = 0) {
1021
2073
  (FNV_OFFSET_BASIS ^ seed >>> 0) >>> 0
1022
2074
  );
1023
2075
  }
1024
- function isNativeDescriptorIntact() {
1025
- if (typeof Reflect === "undefined" || typeof Reflect.apply !== "function") {
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*\}$/;
2080
+ function hasTamperedDescriptor(obj, key) {
2081
+ try {
2082
+ let cur = obj ?? null;
2083
+ while (cur) {
2084
+ const desc = Object.getOwnPropertyDescriptor(cur, key);
2085
+ if (desc && (desc.set || !desc.writable)) {
2086
+ return true;
2087
+ }
2088
+ cur = Object.getPrototypeOf(cur);
2089
+ }
2090
+ return false;
2091
+ } catch {
2092
+ return true;
2093
+ }
2094
+ }
2095
+ function isNativeBuiltinSignature(fn, expectedName, expectedLength, toStr) {
2096
+ if (typeof fn !== "function" || Reflect.has(fn, "prototype") || fn.name !== expectedName || fn.length !== expectedLength) {
1026
2097
  return false;
1027
2098
  }
1028
2099
  try {
1029
- Reflect.apply(Object.getOwnPropertyDescriptor, null, []);
2100
+ const direct = Reflect.apply(toStr, fn, []);
2101
+ const nested = Reflect.apply(Reflect.apply, null, [toStr, fn, []]);
2102
+ if (typeof direct !== "string" || direct !== nested) {
2103
+ return false;
2104
+ }
2105
+ const match = NATIVE_BUILTIN_RE.exec(direct);
2106
+ return !!match && match[1] === expectedName;
2107
+ } catch {
1030
2108
  return false;
1031
- } catch (err) {
1032
- if (!(err instanceof TypeError)) {
2109
+ }
2110
+ }
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;
2116
+ try {
2117
+ if (prevPrepare !== void 0) {
2118
+ if (typeof process === "undefined") {
2119
+ return false;
2120
+ }
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);
1033
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
+ }
1034
2175
  }
1035
2176
  }
2177
+ return ok && !restoreFailed;
2178
+ }
2179
+ function isNativeDescriptorIntact() {
2180
+ if (typeof Reflect === "undefined" || typeof Reflect.apply !== "function") {
2181
+ return false;
2182
+ }
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) {
2188
+ return false;
2189
+ }
1036
2190
  const toStr = Function.prototype.toString;
1037
- if (typeof toStr !== "function" || Reflect.has(toStr, "prototype") || toStr.name !== "toString" || toStr.length !== 0) {
2191
+ const reflectApply = Reflect.apply;
2192
+ const fnCall = Function.prototype.call;
2193
+ if (!isNativeBuiltinSignature(reflectApply, "apply", 3, toStr) || !isNativeBuiltinSignature(toStr, "toString", 0, toStr) || !isNativeBuiltinSignature(fnCall, "call", 1, toStr)) {
1038
2194
  return false;
1039
2195
  }
1040
- try {
1041
- Reflect.apply(toStr, { toString() {
1042
- } }, []);
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)) {
1043
2226
  return false;
1044
- } catch (err) {
1045
- if (!(err instanceof TypeError)) {
2227
+ }
2228
+ try {
2229
+ const probeFn = function() {
2230
+ };
2231
+ const expectedProbe = reflectApply(toStr, probeFn, []);
2232
+ if (toStr.call(probeFn) !== expectedProbe || fnCall.call(toStr, probeFn) !== expectedProbe) {
1046
2233
  return false;
1047
2234
  }
2235
+ } catch {
2236
+ return false;
1048
2237
  }
1049
2238
  return true;
1050
2239
  }
@@ -1060,7 +2249,8 @@ function verifyCodeIntegrity(fnOrSource, expectedHash, seed = 0, normalized = fa
1060
2249
  try {
1061
2250
  const toStr = Function.prototype.toString;
1062
2251
  const selfStr = Reflect.apply(toStr, toStr, []);
1063
- if (typeof selfStr !== "string" || selfStr.indexOf("[native code]") < 0) {
2252
+ const match = typeof selfStr === "string" ? NATIVE_BUILTIN_RE.exec(selfStr) : null;
2253
+ if (!match || match[1] !== "toString") {
1064
2254
  return false;
1065
2255
  }
1066
2256
  raw = Reflect.apply(toStr, fnOrSource, []);
@@ -1112,24 +2302,25 @@ var DISALLOWED_IDENTS = /* @__PURE__ */ new Set([
1112
2302
  function derivePolymorphicIdent(seed, role) {
1113
2303
  let h = (2166136261 ^ seed >>> 0) >>> 0;
1114
2304
  for (let i = 0; i < role.length; i++) {
1115
- h ^= role.charCodeAt(i);
2305
+ h = (h ^ role.charCodeAt(i)) >>> 0;
1116
2306
  h = Math.imul(h, 16777619) >>> 0;
1117
2307
  }
1118
- h ^= h >>> 16;
2308
+ h = (h ^ h >>> 16) >>> 0;
1119
2309
  h = Math.imul(h, 2246822507) >>> 0;
1120
- h ^= h >>> 13;
2310
+ h = (h ^ h >>> 13) >>> 0;
1121
2311
  h = Math.imul(h, 3266489909) >>> 0;
1122
- h ^= h >>> 16;
2312
+ h = (h ^ h >>> 16) >>> 0;
1123
2313
  for (let attempt = 0; attempt < 32; attempt++) {
1124
- const c0 = IDENT_START_CHARS[h % IDENT_START_CHARS.length];
1125
- const c1 = IDENT_CONT_CHARS[(h >>> 6) % IDENT_CONT_CHARS.length];
1126
- const c2 = IDENT_CONT_CHARS[(h >>> 12) % IDENT_CONT_CHARS.length];
1127
- const c3 = IDENT_CONT_CHARS[(h >>> 18) % IDENT_CONT_CHARS.length];
2314
+ const u = h >>> 0;
2315
+ const c0 = IDENT_START_CHARS[u % IDENT_START_CHARS.length];
2316
+ const c1 = IDENT_CONT_CHARS[(u >>> 6) % IDENT_CONT_CHARS.length];
2317
+ const c2 = IDENT_CONT_CHARS[(u >>> 12) % IDENT_CONT_CHARS.length];
2318
+ const c3 = IDENT_CONT_CHARS[(u >>> 18) % IDENT_CONT_CHARS.length];
1128
2319
  const ident = `${c0}${c1}${c2}${c3}`;
1129
2320
  if (!DISALLOWED_IDENTS.has(ident) && !ident.startsWith("__") && !ident.startsWith("_u") && !ident.startsWith("_0")) {
1130
2321
  return ident;
1131
2322
  }
1132
- h = Math.imul(h ^ 2654435769 + attempt, 2246822507) >>> 0;
2323
+ h = Math.imul(u ^ 2654435769 + attempt, 2246822507) >>> 0;
1133
2324
  }
1134
2325
  return `_${(h >>> 0).toString(36).slice(0, 3).padStart(3, "0")}`;
1135
2326
  }
@@ -1627,7 +2818,7 @@ var compactGenerator = Object.assign({}, baseGenerator, {
1627
2818
  }
1628
2819
  });
1629
2820
  var VLQ_BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1630
- function encodeVlq(value) {
2821
+ function encodeVlq2(value) {
1631
2822
  let vlq = value < 0 ? (-value << 1) + 1 : value << 1;
1632
2823
  let encoded = "";
1633
2824
  do {
@@ -1728,13 +2919,13 @@ function generateCompactJsWithMap(ast, fileName) {
1728
2919
  let prevGenCol = 0;
1729
2920
  const encodedSegs = [];
1730
2921
  for (const seg of segs) {
1731
- 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);
1732
2923
  prevGenCol = seg.genCol;
1733
2924
  prevSrcIdx = seg.srcIdx;
1734
2925
  prevOrigLine = seg.origLine;
1735
2926
  prevOrigCol = seg.origCol;
1736
2927
  if (seg.nameIdx !== void 0) {
1737
- s += encodeVlq(seg.nameIdx - prevNameIdx);
2928
+ s += encodeVlq2(seg.nameIdx - prevNameIdx);
1738
2929
  prevNameIdx = seg.nameIdx;
1739
2930
  }
1740
2931
  encodedSegs.push(s);
@@ -1762,13 +2953,12 @@ function createDeterrentSnippet(config) {
1762
2953
  const detectHeadless = config.detectHeadless ?? false;
1763
2954
  const fnName = deriveIntegrityFnName(seed);
1764
2955
  const sym = config.windowKeySymbol ?? deriveWindowKeySymbol(seed);
1765
- const consoleSilence = deterrentMode === "gradual" ? "for(var k in console)console[k]=function(){return 0;};" : "";
2956
+ const consoleSilence = deterrentMode === "gradual" ? "for(var k in console)console[k]=()=>0;" : "";
1766
2957
  const symLit = JSON.stringify(sym);
1767
- const stateLit = JSON.stringify(`${sym}_s`);
1768
2958
  const headlessDecl = detectHeadless ? ",n=w.navigator||0" : "";
1769
2959
  const headlessCond = detectHeadless ? "||n.webdriver||/HeadlessChrome/.test(n.userAgent)" : "";
1770
2960
  const k1Mul = (seed | 1) >>> 0;
1771
- return `(function ${fnName}(w){var G=typeof globalThis<'u'?globalThis:w;if(w){var O=Object,P=O.getOwnPropertyDescriptor,GP=O.getPrototypeOf,R=typeof Reflect<'u'&&Reflect.apply,SP=String.prototype,Q='__unpeek_',y=${symLit},z=${stateLit},U='__unpeek_tampered',T=function(o,k){try{while(o){var r=P&&P(o,k);if(r&&(r.set||!r.writable))return 1;o=GP?GP(o):0;}}catch(e){return 1;}},B=function(k,v,c){try{if(!c||!T(G,k))G[k]=v;}catch(e){}try{if(!c||!T(w,k))w[k]=v;}catch(e){}},s=Function.prototype.toString${headlessDecl},src='',t=0;if((G[z]||w[z]||0)[0]==2)t=1;try{if(typeof R!='function')t=1;else{var E=function(f,a,b){try{R(f,a,b);t=1;}catch(e){t|=!e||(!(e instanceof TypeError)&&e.name!='TypeError');}};E(P,null,[]);E(s,{toString(){}},[]);src=R(s,${fnName},[]);if(typeof s!='function'||'prototype'in s||s.name!='toString'||s.length!=0||R(s,s,[]).indexOf('[native code]')<0||/\\n/.test(src)${headlessCond})t=1;}}catch(e){t=1;}for(var j in K=[y,z,U])if(T(w,K[j])||T(G,K[j]))t=1;if(T(SP,'_u'))t=1;for(var h=0x811c9dc5,i=0;i<src.length;i++)h=Math.imul(h^src.charCodeAt(i),0x01000193)>>>0;var d=h&65535,k0=(h^${seed})>>>0,k1=(h^${k1Mul})>>>0,nc=(d^(h>>>16))>>>0;B(z,[t?2:1,k0^t,k1^t,1,nc],t);if(t){var pd=(d^((h>>>16^0x5a5b)||1))&65535;B(y,pd,1);B(y+'_t',!0);B(Q+'delta',pd);try{SP._u=14;}catch(e){}B(Q+'seed',((w.__unpeek_seed||${seed})^1)>>>0);B(U,!0);try{${consoleSilence}w.dispatchEvent&&w.dispatchEvent(new CustomEvent('unpeek:tamper'));}catch(e){}}else B(y,d);}})(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);`;
1772
2962
  }
1773
2963
 
1774
2964
  // src/runtime/index.ts
@@ -1787,13 +2977,15 @@ function generateRuntimeShield(config) {
1787
2977
  const computedHash = computeIntegrityHash(fnDecl, 0);
1788
2978
  const expectedHash = config.expectedIntegrityHash !== void 0 ? config.expectedIntegrityHash >>> 0 : computedHash;
1789
2979
  const expectedDelta = config.expectedDelta !== void 0 ? config.expectedDelta & 65535 : computedHash >>> 0 & 65535;
2980
+ const expectedStateHash = computedHash ^ seed | 0;
1790
2981
  const payload = {
1791
2982
  preambleCode,
1792
2983
  integrityCheckFnName,
1793
2984
  expectedHash,
1794
2985
  windowKeySymbol,
1795
2986
  expectedDelta,
1796
- stateKeySymbol: `${windowKeySymbol}_s`
2987
+ stateKeySymbol: `${windowKeySymbol}_s`,
2988
+ expectedStateHash
1797
2989
  };
1798
2990
  return payload;
1799
2991
  }
@@ -1865,10 +3057,13 @@ function deriveWasmHostParams(seed) {
1865
3057
  const rA1 = computeFnv1aHash("wasm-ra1", seed) | 1;
1866
3058
  const rA2 = computeFnv1aHash("wasm-ra2", seed) & ~1;
1867
3059
  const rA3 = computeFnv1aHash("wasm-ra3", seed) & ~1;
1868
- 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 };
1869
3063
  }
1870
3064
  function generateWasmKdfBinary(seed) {
1871
3065
  const { sVal, c1, c2, k0, r1, r2 } = deriveKdfParams(seed);
3066
+ const { gMask, pcMask } = deriveWasmHostParams(seed);
1872
3067
  const memBase = (seed >>> 0 & 127) * 4;
1873
3068
  const r0 = computeFnv1aHash("wasm-r0", seed) | 0;
1874
3069
  const rotAmt = (seed >>> 0) % 27 + 3;
@@ -1882,6 +3077,8 @@ function generateWasmKdfBinary(seed) {
1882
3077
  const w2 = c1 ^ (w0 + w1 | 0) | 0;
1883
3078
  const w3 = c2 - Math.imul(w1 | 1, w2 | 1) | 0;
1884
3079
  const w4 = k0 ^ rotl32(w2, 11) ^ w3 | 0;
3080
+ const w5 = gMask ^ rotl32(w3, 7) ^ w0 | 0;
3081
+ const w6 = pcMask ^ rotl32(w4, 13) ^ w1 | 0;
1885
3082
  const kdfInstructions = [
1886
3083
  65,
1887
3084
  ...encodeSignedLeb128(memA),
@@ -1988,9 +3185,68 @@ function generateWasmKdfBinary(seed) {
1988
3185
  115,
1989
3186
  // i32.xor
1990
3187
  33,
1991
- 9,
1992
- // local.set 9 (c1)
1993
- // Reconstruct k0 -> local 10
3188
+ 9,
3189
+ // local.set 9 (c1)
3190
+ // Reconstruct k0 -> local 10
3191
+ 32,
3192
+ 3,
3193
+ // local.get 3 (ptr)
3194
+ 40,
3195
+ 2,
3196
+ 16,
3197
+ // i32.load align=2 offset=16 (w4)
3198
+ 32,
3199
+ 6,
3200
+ // local.get 6 (w2)
3201
+ 65,
3202
+ 11,
3203
+ // i32.const 11
3204
+ 119,
3205
+ // i32.rotl
3206
+ 115,
3207
+ // i32.xor
3208
+ 32,
3209
+ 7,
3210
+ // local.get 7 (w3)
3211
+ 115,
3212
+ // i32.xor
3213
+ 33,
3214
+ 10,
3215
+ // local.set 10 (k0)
3216
+ // Reconstruct gMask -> local 12
3217
+ 32,
3218
+ 3,
3219
+ // local.get 3 (ptr)
3220
+ 40,
3221
+ 2,
3222
+ 20,
3223
+ // i32.load align=2 offset=20 (w5)
3224
+ 32,
3225
+ 7,
3226
+ // local.get 7 (w3)
3227
+ 65,
3228
+ 7,
3229
+ // i32.const 7
3230
+ 119,
3231
+ // i32.rotl
3232
+ 115,
3233
+ // i32.xor
3234
+ 32,
3235
+ 4,
3236
+ // local.get 4 (w0)
3237
+ 115,
3238
+ // i32.xor
3239
+ 33,
3240
+ 12,
3241
+ // local.set 12 (gMask)
3242
+ // Reconstruct pcMask -> local 13
3243
+ 32,
3244
+ 3,
3245
+ // local.get 3 (ptr)
3246
+ 40,
3247
+ 2,
3248
+ 24,
3249
+ // i32.load align=2 offset=24 (w6)
1994
3250
  32,
1995
3251
  3,
1996
3252
  // local.get 3 (ptr)
@@ -1998,25 +3254,22 @@ function generateWasmKdfBinary(seed) {
1998
3254
  2,
1999
3255
  16,
2000
3256
  // i32.load align=2 offset=16 (w4)
2001
- 32,
2002
- 6,
2003
- // local.get 6 (w2)
2004
3257
  65,
2005
- 11,
2006
- // i32.const 11
3258
+ 13,
3259
+ // i32.const 13
2007
3260
  119,
2008
3261
  // i32.rotl
2009
3262
  115,
2010
3263
  // i32.xor
2011
3264
  32,
2012
- 7,
2013
- // local.get 7 (w3)
3265
+ 5,
3266
+ // local.get 5 (w1)
2014
3267
  115,
2015
3268
  // i32.xor
2016
3269
  33,
2017
- 10,
2018
- // local.set 10 (k0)
2019
- // x = f ^ sVal ^ k0 ^ env.g(0)
3270
+ 13,
3271
+ // local.set 13 (pcMask)
3272
+ // x = f ^ sVal ^ k0 ^ (env.g(0) ^ gMask)
2020
3273
  32,
2021
3274
  0,
2022
3275
  // local.get 0 (fnId)
@@ -2036,6 +3289,11 @@ function generateWasmKdfBinary(seed) {
2036
3289
  16,
2037
3290
  0,
2038
3291
  // call 0 (env.g(0))
3292
+ 32,
3293
+ 12,
3294
+ // local.get 12 (gMask)
3295
+ 115,
3296
+ // i32.xor
2039
3297
  115,
2040
3298
  // i32.xor
2041
3299
  34,
@@ -2069,14 +3327,19 @@ function generateWasmKdfBinary(seed) {
2069
3327
  // i32.const r1
2070
3328
  119,
2071
3329
  // i32.rotl
2072
- // x = env.m(x, shieldHash)
3330
+ // x = env.m(x, shieldHash ^ pcMask)
2073
3331
  32,
2074
3332
  2,
2075
3333
  // local.get 2 (shieldHash)
3334
+ 32,
3335
+ 13,
3336
+ // local.get 13 (pcMask)
3337
+ 115,
3338
+ // i32.xor
2076
3339
  16,
2077
3340
  1,
2078
- // call 1 (env.m(x, shieldHash))
2079
- // x = imul(x ^ h ^ sVal ^ env.g(1), c2)
3341
+ // call 1 (env.m(x, maskedPc))
3342
+ // x = imul(x ^ h ^ sVal ^ (env.g(1) ^ gMask), c2)
2080
3343
  32,
2081
3344
  2,
2082
3345
  // local.get 2 (shieldHash)
@@ -2093,6 +3356,11 @@ function generateWasmKdfBinary(seed) {
2093
3356
  16,
2094
3357
  0,
2095
3358
  // call 0 (env.g(1))
3359
+ 32,
3360
+ 12,
3361
+ // local.get 12 (gMask)
3362
+ 115,
3363
+ // i32.xor
2096
3364
  115,
2097
3365
  // i32.xor
2098
3366
  32,
@@ -2229,6 +3497,11 @@ function generateWasmKdfBinary(seed) {
2229
3497
  16,
2230
3498
  0,
2231
3499
  // call 0 (env.g)
3500
+ 65,
3501
+ ...encodeSignedLeb128(gMask),
3502
+ // i32.const gMask
3503
+ 115,
3504
+ // i32.xor
2232
3505
  106,
2233
3506
  // i32.add
2234
3507
  16,
@@ -2280,7 +3553,7 @@ function generateWasmKdfBinary(seed) {
2280
3553
  11
2281
3554
  // end func
2282
3555
  ];
2283
- const kdfBody = [1, 9, 127, ...kdfInstructions];
3556
+ const kdfBody = [1, 11, 127, ...kdfInstructions];
2284
3557
  const kdfBodyWithLen = [...encodeUnsignedLeb128(kdfBody.length), ...kdfBody];
2285
3558
  const bulkBody = [1, 2, 127, ...bulkMixInstructions];
2286
3559
  const bulkBodyWithLen = [...encodeUnsignedLeb128(bulkBody.length), ...bulkBody];
@@ -2393,7 +3666,9 @@ function generateWasmKdfBinary(seed) {
2393
3666
  ...writeI32LE(w1),
2394
3667
  ...writeI32LE(w2),
2395
3668
  ...writeI32LE(w3),
2396
- ...writeI32LE(w4)
3669
+ ...writeI32LE(w4),
3670
+ ...writeI32LE(w5),
3671
+ ...writeI32LE(w6)
2397
3672
  ];
2398
3673
  const dataPayload = [
2399
3674
  1,
@@ -2426,20 +3701,22 @@ function generateWasmKdfBinary(seed) {
2426
3701
  }
2427
3702
  function fallbackKdf(fnId, callSiteSalt, shieldHash, seed) {
2428
3703
  const { sVal, c1, c2, k0, r1, r2 } = deriveKdfParams(seed);
2429
- const { gArr, sOff, rA0, rA1, rA2, rA3 } = deriveWasmHostParams(seed);
3704
+ const { gArr, sOff, rA0, rA1, rA2, rA3, gMask, pcMask } = deriveWasmHostParams(seed);
3705
+ const envG = (slot) => gArr[slot & 3] ^ gMask | 0;
2430
3706
  const envM = (acc, pc) => {
2431
3707
  const sb0 = Math.imul(167, acc & 255) + sOff & 255;
2432
3708
  const sb1 = Math.imul(167, acc >>> 8 & 255) + sOff & 255;
2433
3709
  const sb = sb0 ^ sb1 << 8;
2434
- const riv = evalRivestPoly32(acc ^ sb ^ pc | 0, rA0, rA1, rA2, rA3) | 0;
3710
+ const unmaskedPc = pc ^ pcMask | 0;
3711
+ const riv = evalRivestPoly32(acc ^ sb ^ unmaskedPc | 0, rA0, rA1, rA2, rA3) | 0;
2435
3712
  return riv ^ gArr[2] | 0;
2436
3713
  };
2437
- let x = fnId ^ sVal ^ k0 ^ gArr[0] | 0;
3714
+ let x = fnId ^ sVal ^ k0 ^ (envG(0) ^ gMask) | 0;
2438
3715
  x = x ^ x >>> 16 | 0;
2439
3716
  x = Math.imul(x, c1);
2440
3717
  x = rotl32(x ^ callSiteSalt | 0, r1);
2441
- x = envM(x, shieldHash | 0);
2442
- x = Math.imul(x ^ shieldHash ^ sVal ^ gArr[1] | 0, c2);
3718
+ x = envM(x, shieldHash ^ pcMask | 0);
3719
+ x = Math.imul(x ^ shieldHash ^ sVal ^ (envG(1) ^ gMask) | 0, c2);
2443
3720
  x = x ^ x >>> 15 | 0;
2444
3721
  x = x + rotl32(callSiteSalt ^ k0 | 0, r2) | 0;
2445
3722
  x = Math.imul(x, c1);
@@ -2478,7 +3755,7 @@ function injectWasmVault(ast, seed = 2654435769) {
2478
3755
  const wasmBytes = generateWasmKdfBinary(seed);
2479
3756
  const byteArrayLiteral = Array.from(wasmBytes).join(",");
2480
3757
  const { sVal, c1, c2, k0, r1, r2 } = deriveKdfParams(seed);
2481
- const { gArr, sOff, rA0, rA1, rA2, rA3 } = deriveWasmHostParams(seed);
3758
+ const { gArr, sOff, rA0, rA1, rA2, rA3, gMask, pcMask } = deriveWasmHostParams(seed);
2482
3759
  const targets = [c1, c2, sVal, k0, r1, r2];
2483
3760
  const rivEncodedTargets = targets.map(
2484
3761
  (t, j) => invertRivestPoly32((t ^ gArr[j & 3]) >>> 0, rA0, rA1, rA2, rA3) | 0
@@ -2503,11 +3780,11 @@ function injectWasmVault(ast, seed = 2654435769) {
2503
3780
  var _tk = ['__','unp','eek_t','ampered'].join('');
2504
3781
  var _eG = function(sl) {
2505
3782
  var tp = (_G && _G[_tk] === !0) ? 0x5a5b : 0;
2506
- return (_g[sl & 3] ^ tp) | 0;
3783
+ return (_g[sl & 3] ^ ${gMask} ^ tp) | 0;
2507
3784
  };
2508
3785
  var _eM = function(acc, pc) {
2509
3786
  var sb = _sb(acc) ^ (_sb(acc >>> 8) << 8);
2510
- return (_evR((acc ^ sb ^ pc) | 0) ^ _g[2]) | 0;
3787
+ return (_evR((acc ^ sb ^ (pc ^ ${pcMask})) | 0) ^ _g[2]) | 0;
2511
3788
  };
2512
3789
  try {
2513
3790
  var ${wasmVarName} = new Uint8Array([${byteArrayLiteral}]);
@@ -2527,13 +3804,13 @@ function injectWasmVault(ast, seed = 2654435769) {
2527
3804
  }
2528
3805
  var _m = Math[_p];
2529
3806
  ${kdfFnName} = function(f, s, h) {
2530
- var _x = (f ^ _k[2] ^ _k[3] ^ _eG(0)) | 0;
3807
+ var _x = (f ^ _k[2] ^ _k[3] ^ (_eG(0) ^ ${gMask})) | 0;
2531
3808
  _x = (_x ^ (_x >>> 16)) | 0;
2532
3809
  _x = _m(_x, _k[0]);
2533
3810
  var _t0 = _x ^ s, _r1 = _k[4];
2534
3811
  _x = (_t0 << _r1) | (_t0 >>> (32 - _r1));
2535
- _x = _eM(_x, h | 0);
2536
- _x = _m(_x ^ h ^ _k[2] ^ _eG(1), _k[1]);
3812
+ _x = _eM(_x, (h ^ ${pcMask}) | 0);
3813
+ _x = _m(_x ^ h ^ _k[2] ^ (_eG(1) ^ ${gMask}), _k[1]);
2537
3814
  _x = (_x ^ (_x >>> 15)) | 0;
2538
3815
  var _u0 = s ^ _k[3], _r2 = _k[5];
2539
3816
  _x = (_x + ((_u0 << _r2) | (_u0 >>> (32 - _r2)))) | 0;
@@ -2600,6 +3877,43 @@ function exemptWebpackPushArg(arg, exemptSubtreeRoots) {
2600
3877
  }
2601
3878
  exemptSubtreeRoots.add(arg);
2602
3879
  }
3880
+ function exemptTurbopackPropertyKeys(objNode, exemptSubtreeRoots) {
3881
+ if (!Array.isArray(objNode?.properties)) return;
3882
+ for (const prop of objNode.properties) {
3883
+ if (prop?.type === "Property" && prop.key && typeof prop.key === "object") {
3884
+ exemptSubtreeRoots.add(prop.key);
3885
+ }
3886
+ }
3887
+ }
3888
+ function exemptTurbopackPushArg(arg, exemptSubtreeRoots) {
3889
+ if (!arg || typeof arg !== "object") return;
3890
+ if (arg.type === "ArrayExpression" && Array.isArray(arg.elements)) {
3891
+ for (let i = 0; i < arg.elements.length; i++) {
3892
+ const el = arg.elements[i];
3893
+ if (!el || typeof el !== "object") continue;
3894
+ if (i === 0) {
3895
+ exemptSubtreeRoots.add(el);
3896
+ continue;
3897
+ }
3898
+ if (el.type === "Literal") {
3899
+ exemptSubtreeRoots.add(el);
3900
+ } else if (el.type === "ObjectExpression") {
3901
+ exemptTurbopackPropertyKeys(el, exemptSubtreeRoots);
3902
+ } else if (el.type === "FunctionExpression" || el.type === "ArrowFunctionExpression") {
3903
+ continue;
3904
+ }
3905
+ }
3906
+ return;
3907
+ }
3908
+ if (arg.type === "ObjectExpression") {
3909
+ exemptTurbopackPropertyKeys(arg, exemptSubtreeRoots);
3910
+ return;
3911
+ }
3912
+ if (arg.type === "FunctionExpression" || arg.type === "ArrowFunctionExpression") {
3913
+ return;
3914
+ }
3915
+ exemptSubtreeRoots.add(arg);
3916
+ }
2603
3917
  function isHostMember(node, matcher) {
2604
3918
  if (!node) return false;
2605
3919
  if (node.type === "Identifier" && matchesPropName(node.name, matcher)) {
@@ -2658,12 +3972,13 @@ function classifyChunkBoundary(ast) {
2658
3972
  }
2659
3973
  } else if (unwrapAssignedHostMember(callee.object, "TURBOPACK")) {
2660
3974
  hasEntryBootstrap = true;
2661
- exemptSubtreeRoots.add(node);
3975
+ exemptSubtreeRoots.add(callee);
3976
+ if (callee.object && typeof callee.object === "object") {
3977
+ exemptSubtreeRoots.add(callee.object);
3978
+ }
2662
3979
  if (Array.isArray(node.arguments)) {
2663
3980
  for (const arg of node.arguments) {
2664
- if (arg && typeof arg === "object") {
2665
- exemptSubtreeRoots.add(arg);
2666
- }
3981
+ exemptTurbopackPushArg(arg, exemptSubtreeRoots);
2667
3982
  }
2668
3983
  }
2669
3984
  } else if (unwrapAssignedHostMember(callee.object, isWebpackOrRspackChunkName)) {
@@ -2761,6 +4076,7 @@ function computeCallSiteSalt(seed, idx) {
2761
4076
  const [lo, hi] = computeCallSiteSalt64(seed >>> 0, idx >>> 0, seed >>> 0);
2762
4077
  return ((lo ^ hi) & 2147483647 | 1) >>> 0;
2763
4078
  }
4079
+ 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');`;
2764
4080
  function buildRivestDeltaExpr(seed, expectedDelta, varName = "_ed") {
2765
4081
  const s = seed >>> 0;
2766
4082
  const rA0 = computeFnv1aHash(`riv-a0:${s}`, s) | 0;
@@ -2786,7 +4102,10 @@ function createSaltedDecryptorFnAst(seed, pChars, expectedDelta, windowKeySymbol
2786
4102
  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}";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;var tm=(G&&(G[_tk]===!0||G${flagAccess}===!0))||(w&&(w[_tk]===!0||w${flagAccess}===!0))||((""._u||a._u||0)!==0);if(!tm&&(i in m))return m[i];var d=tm?(((Math.imul(i+1,0x9e3779b1)^0x5a5b)&65535)|1):0;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)m[i]=o;return o;};`;
2787
4103
  } else {
2788
4104
  const edInit = buildRivestDeltaExpr(seed, expectedDelta, "_ed");
2789
- 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;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)||(sv!==void 0&&sv!==_ed);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;};`;
4105
+ const hasWindowKey = Boolean(windowKeySymbol);
4106
+ const brDecl = hasWindowKey ? NARROWED_ASYNC_BR_DECL : "";
4107
+ const svCheck = hasWindowKey ? `(sv===void 0?!_br:sv!==_ed)` : `(sv!==void 0&&sv!==_ed)`;
4108
+ 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;};`;
2790
4109
  }
2791
4110
  return acorn3.parse(`(function f(a){${fBody}})`, {
2792
4111
  ecmaVersion: "latest",
@@ -2835,7 +4154,7 @@ function isAstAlreadySalted(ast) {
2835
4154
  if (!ast || !Array.isArray(ast.body)) return false;
2836
4155
  return ast.body.some((stmt) => {
2837
4156
  if (stmt.type === "VariableDeclaration" && stmt.declarations?.some(
2838
- (d) => d.id?.type === "Identifier" && typeof d.id.name === "string" && d.id.name.startsWith("_uP")
4157
+ (d) => d.id?.type === "Identifier" && typeof d.id.name === "string" && (d.id.name.startsWith("_uP") || d.init?.type === "CallExpression" && d.init.callee?.type === "FunctionExpression" && d.init.callee?.id?.name === "f" && d.init.arguments?.[0]?.type === "ArrayExpression")
2839
4158
  )) {
2840
4159
  return true;
2841
4160
  }
@@ -2866,7 +4185,8 @@ function applySaltedStringVault(ast, seed = 2654435769, minStringLength = 4, hot
2866
4185
  encryptedStringsCount: 0,
2867
4186
  integrityToken: computeFnv1aHash("already-salted", seed),
2868
4187
  vaultVarName: "",
2869
- decryptFnName: ""
4188
+ decryptFnName: "",
4189
+ shaderBuffersCount: 0
2870
4190
  };
2871
4191
  }
2872
4192
  const minLen = config?.vault?.minStringLength ?? minStringLength;
@@ -2879,74 +4199,124 @@ function applySaltedStringVault(ast, seed = 2654435769, minStringLength = 4, hot
2879
4199
  const customReserved = config?.vault?.reservedProps ? new Set(config.vault.reservedProps) : void 0;
2880
4200
  const targetsToReplace = [];
2881
4201
  const encryptedPayloads = [];
4202
+ const shaderToIndex = /* @__PURE__ */ new Map();
4203
+ const shaderPayloads = [];
4204
+ const shaderTargets = [];
4205
+ function processSaltedCandidate(val, node, parent, ancestors) {
4206
+ if (isNodeInExemptSubtree(ancestors, exemptSubtreeRoots)) {
4207
+ return;
4208
+ }
4209
+ if (parent.type === "ExpressionStatement" && (Boolean(parent.directive) || activeDirectives.has(val))) {
4210
+ return;
4211
+ }
4212
+ for (let i = ancestors.length - 2; i >= 0; i--) {
4213
+ if (ancestors[i].type === "ExpressionStatement" && Boolean(ancestors[i].directive)) {
4214
+ return;
4215
+ }
4216
+ }
4217
+ let isHotExempt = false;
4218
+ if (hotExemptNodes) {
4219
+ for (let i = ancestors.length - 2; i >= 0; i--) {
4220
+ if (hotExemptNodes.has(ancestors[i])) {
4221
+ isHotExempt = true;
4222
+ break;
4223
+ }
4224
+ }
4225
+ }
4226
+ if (isShaderPayload(
4227
+ val,
4228
+ node,
4229
+ parent,
4230
+ ancestors,
4231
+ seed,
4232
+ isHotExempt,
4233
+ customReserved
4234
+ )) {
4235
+ let idx = shaderToIndex.get(val);
4236
+ if (idx === void 0) {
4237
+ idx = shaderPayloads.length;
4238
+ shaderToIndex.set(val, idx);
4239
+ shaderPayloads.push(val);
4240
+ }
4241
+ shaderTargets.push({ node, parent, idx });
4242
+ return;
4243
+ }
4244
+ if (isHotExempt) {
4245
+ return;
4246
+ }
4247
+ if (!shouldEncryptString(
4248
+ val,
4249
+ minLen,
4250
+ parent,
4251
+ activeDirectives,
4252
+ customReserved
4253
+ )) {
4254
+ return;
4255
+ }
4256
+ const callSiteIdx = targetsToReplace.length;
4257
+ const [saltLo, saltHi] = computeCallSiteSalt64(
4258
+ seed >>> 0,
4259
+ callSiteIdx >>> 0,
4260
+ seed >>> 0
4261
+ );
4262
+ const localSalt = ((saltLo ^ saltHi) & 2147483647 | 1) >>> 0;
4263
+ targetsToReplace.push({
4264
+ node,
4265
+ parent,
4266
+ callSiteIdx,
4267
+ localSalt,
4268
+ rawString: val
4269
+ });
4270
+ }
2882
4271
  walk3.ancestor(ast, {
2883
4272
  Literal(node, ancestors) {
2884
4273
  if (typeof node.value !== "string") return;
2885
- if (node.value.length < minLen) return;
2886
- if (activeDirectives.has(node.value)) return;
4274
+ const val = node.value;
4275
+ if (activeDirectives.has(val)) return;
2887
4276
  const parent = ancestors[ancestors.length - 2];
2888
4277
  if (!parent) return;
2889
- if (isNodeInExemptSubtree(ancestors, exemptSubtreeRoots)) {
4278
+ if ((parent.type === "ImportDeclaration" || parent.type === "ExportNamedDeclaration" || parent.type === "ExportAllDeclaration" || parent.type === "ImportExpression") && parent.source === node) {
2890
4279
  return;
2891
4280
  }
2892
- if (parent.type === "ExpressionStatement" && (Boolean(parent.directive) || activeDirectives.has(node.value))) {
4281
+ if (parent.type === "Property" && parent.key === node && !parent.computed) {
2893
4282
  return;
2894
4283
  }
2895
- for (let i = ancestors.length - 2; i >= 0; i--) {
2896
- if (ancestors[i].type === "ExpressionStatement" && Boolean(ancestors[i].directive)) {
2897
- return;
2898
- }
2899
- }
2900
- if ((parent.type === "ImportDeclaration" || parent.type === "ExportNamedDeclaration" || parent.type === "ExportAllDeclaration" || parent.type === "ImportExpression") && parent.source === node) {
4284
+ if ((parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") && parent.key === node && !parent.computed) {
2901
4285
  return;
2902
4286
  }
2903
- if (parent.type === "Property" && parent.key === node && !parent.computed) {
4287
+ if (parent.type === "ImportAttribute" || parent.type === "ImportSpecifier" || parent.type === "ExportSpecifier") {
2904
4288
  return;
2905
4289
  }
2906
- if ((parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") && parent.key === node && !parent.computed) {
4290
+ processSaltedCandidate(val, node, parent, ancestors);
4291
+ },
4292
+ TemplateLiteral(node, ancestors) {
4293
+ if (!node.quasis || node.quasis.length !== 1) return;
4294
+ if (node.expressions && node.expressions.length !== 0) return;
4295
+ const val = node.quasis[0].value.cooked ?? node.quasis[0].value.raw;
4296
+ if (typeof val !== "string" || activeDirectives.has(val)) return;
4297
+ const parent = ancestors[ancestors.length - 2];
4298
+ if (!parent) return;
4299
+ if (parent.type === "TaggedTemplateExpression" && parent.quasi === node) {
2907
4300
  return;
2908
4301
  }
2909
- if (hotExemptNodes) {
2910
- for (let i = ancestors.length - 1; i >= 0; i--) {
2911
- if (hotExemptNodes.has(ancestors[i])) {
2912
- return;
2913
- }
2914
- }
4302
+ if (parent.type === "ImportExpression" && parent.source === node) {
4303
+ return;
2915
4304
  }
2916
- if (isReservedProp(node.value, customReserved)) return;
2917
- if (isTailwindNoise(node.value)) return;
2918
- if (isSvgPathString(node.value, parent)) return;
2919
- const callSiteIdx = targetsToReplace.length;
2920
- const [saltLo, saltHi] = computeCallSiteSalt64(
2921
- seed >>> 0,
2922
- callSiteIdx >>> 0,
2923
- seed >>> 0
2924
- );
2925
- const localSalt = ((saltLo ^ saltHi) & 2147483647 | 1) >>> 0;
2926
- targetsToReplace.push({
2927
- node,
2928
- parent,
2929
- callSiteIdx,
2930
- localSalt,
2931
- rawString: node.value
2932
- });
4305
+ processSaltedCandidate(val, node, parent, ancestors);
2933
4306
  }
2934
4307
  });
2935
- if (targetsToReplace.length === 0) {
4308
+ if (targetsToReplace.length === 0 && shaderTargets.length === 0) {
2936
4309
  return {
2937
4310
  encryptedStringsCount: 0,
2938
4311
  integrityToken: computeFnv1aHash("empty-salted", seed),
2939
4312
  vaultVarName: "",
2940
- decryptFnName: ""
4313
+ decryptFnName: "",
4314
+ shaderBuffersCount: 0
2941
4315
  };
2942
4316
  }
2943
- const wasmResult = injectWasmVault(ast, seed);
2944
- const kdfFnName = wasmResult.kdfFnName;
2945
- const suffix = computeFnv1aHash(`salted:${seed}`, seed).toString(36);
2946
- const vaultVarName = `_uP${suffix}`;
2947
- const cacheVarName = `_uCache${suffix}`;
2948
- const dCacheVarName = `_uDc${suffix}`;
2949
- const decryptFnName = `_uD${suffix}`;
4317
+ let vaultVarName = "";
4318
+ let decryptFnName = "";
4319
+ let integrityToken = computeFnv1aHash("empty-salted", seed);
2950
4320
  const sym = windowKeySymbol ?? deriveWindowKeySymbol(seed);
2951
4321
  let expDelta = expectedDelta;
2952
4322
  if (shieldCoupled && expDelta === void 0) {
@@ -2958,75 +4328,113 @@ function applySaltedStringVault(ast, seed = 2654435769, minStringLength = 4, hot
2958
4328
  });
2959
4329
  expDelta = shield.expectedDelta ?? 0;
2960
4330
  }
2961
- const propAccess = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(sym) ? `.${sym}` : `[${JSON.stringify(sym)}]`;
2962
- const stateSym = `${sym}_s`;
2963
- const stateAccess = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(stateSym) ? `.${stateSym}` : `[${JSON.stringify(stateSym)}]`;
2964
- const flagSym = `${sym}_t`;
2965
- const flagAccess = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(flagSym) ? `.${flagSym}` : `[${JSON.stringify(flagSym)}]`;
2966
- const tkExpr = `['__','unp','eek_t','ampered'].join('')`;
2967
- const dkExpr = `['__','unp','eek_d','elta'].join('')`;
2968
- let helperFnSnippet;
2969
- if (!shieldCoupled) {
2970
- 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};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))||((""._u||0)!==0)||(dv!==0);if(!tm&&${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;}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)${cacheVarName}[i]=o;return o;}`;
2971
- } else {
2972
- const edInit = buildRivestDeltaExpr(seed, (expDelta ?? 0) & 65535, "_ed");
2973
- 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}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)||(sv!==void 0&&sv!==_ed);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;}`;
2974
- }
2975
- const parsedFn = acorn3.parse(helperFnSnippet, {
2976
- ecmaVersion: "latest",
2977
- sourceType: "script"
2978
- });
2979
- const fnDeclAst = parsedFn.body[0];
2980
- const selfHash = computeFnv1aHash(generateCompactJs(fnDeclAst)) | 0;
2981
- const buildD = shieldCoupled ? selfHash ^ (expDelta ?? 0) & 65535 | 0 : selfHash | 0;
2982
- for (const target of targetsToReplace) {
2983
- const k = fallbackKdf(target.callSiteIdx, target.localSalt, buildD, seed);
2984
- encryptedPayloads.push(encodeSaltedString(target.rawString, k));
2985
- const callExpr = {
2986
- type: "CallExpression",
2987
- callee: {
2988
- type: "Identifier",
2989
- name: decryptFnName
2990
- },
2991
- arguments: [
2992
- {
2993
- type: "Literal",
2994
- value: target.callSiteIdx,
2995
- raw: String(target.callSiteIdx)
4331
+ if (targetsToReplace.length > 0) {
4332
+ const wasmResult = injectWasmVault(ast, seed);
4333
+ const kdfFnName = wasmResult.kdfFnName;
4334
+ const suffix = computeFnv1aHash(`salted:${seed}`, seed).toString(36);
4335
+ vaultVarName = `_uP${suffix}`;
4336
+ const cacheVarName = `_uCache${suffix}`;
4337
+ const dCacheVarName = `_uDc${suffix}`;
4338
+ decryptFnName = `_uD${suffix}`;
4339
+ const propAccess = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(sym) ? `.${sym}` : `[${JSON.stringify(sym)}]`;
4340
+ const stateSym = `${sym}_s`;
4341
+ const stateAccess = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(stateSym) ? `.${stateSym}` : `[${JSON.stringify(stateSym)}]`;
4342
+ const flagSym = `${sym}_t`;
4343
+ const flagAccess = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(flagSym) ? `.${flagSym}` : `[${JSON.stringify(flagSym)}]`;
4344
+ const tkExpr = `['__','unp','eek_t','ampered'].join('')`;
4345
+ const dkExpr = `['__','unp','eek_d','elta'].join('')`;
4346
+ let helperFnSnippet;
4347
+ if (!shieldCoupled) {
4348
+ 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};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))||((""._u||0)!==0)||(dv!==0);if(!tm&&${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;}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)${cacheVarName}[i]=o;return o;}`;
4349
+ } else {
4350
+ const edInit = buildRivestDeltaExpr(seed, (expDelta ?? 0) & 65535, "_ed");
4351
+ const hasWindowKey = Boolean(sym);
4352
+ const brDecl = hasWindowKey ? NARROWED_ASYNC_BR_DECL : "";
4353
+ const svCheck = hasWindowKey ? `(sv===void 0?!_br:sv!==_ed)` : `(sv!==void 0&&sv!==_ed)`;
4354
+ 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;}`;
4355
+ }
4356
+ const parsedFn = acorn3.parse(helperFnSnippet, {
4357
+ ecmaVersion: "latest",
4358
+ sourceType: "script"
4359
+ });
4360
+ const fnDeclAst = parsedFn.body[0];
4361
+ const selfHash = computeFnv1aHash(generateCompactJs(fnDeclAst)) | 0;
4362
+ const buildD = shieldCoupled ? selfHash ^ (expDelta ?? 0) & 65535 | 0 : selfHash | 0;
4363
+ for (const target of targetsToReplace) {
4364
+ const k = fallbackKdf(target.callSiteIdx, target.localSalt, buildD, seed);
4365
+ encryptedPayloads.push(encodeSaltedString(target.rawString, k));
4366
+ const callExpr = {
4367
+ type: "CallExpression",
4368
+ callee: {
4369
+ type: "Identifier",
4370
+ name: decryptFnName
2996
4371
  },
2997
- {
2998
- type: "Literal",
2999
- value: target.localSalt,
3000
- raw: String(target.localSalt)
3001
- }
3002
- ],
3003
- optional: false
3004
- };
3005
- replaceNodeInParent(target.parent, target.node, callExpr);
4372
+ arguments: [
4373
+ {
4374
+ type: "Literal",
4375
+ value: target.callSiteIdx,
4376
+ raw: String(target.callSiteIdx)
4377
+ },
4378
+ {
4379
+ type: "Literal",
4380
+ value: target.localSalt,
4381
+ raw: String(target.localSalt)
4382
+ }
4383
+ ],
4384
+ optional: false
4385
+ };
4386
+ replaceNodeInParent(target.parent, target.node, callExpr);
4387
+ }
4388
+ const serializedTable = JSON.stringify(encryptedPayloads);
4389
+ integrityToken = computeFnv1aHash(serializedTable, seed);
4390
+ const varsSnippet = `var ${vaultVarName}=${serializedTable};var ${cacheVarName}=[];var ${dCacheVarName};`;
4391
+ const parsedVars = acorn3.parse(varsSnippet, {
4392
+ ecmaVersion: "latest",
4393
+ sourceType: "script"
4394
+ });
4395
+ const insertIdx = findVaultInsertIndex(ast, activeDirectives);
4396
+ ast.body.splice(insertIdx, 0, ...parsedVars.body, fnDeclAst);
3006
4397
  }
3007
- const serializedTable = JSON.stringify(encryptedPayloads);
3008
- const integrityToken = computeFnv1aHash(serializedTable, seed);
3009
- const varsSnippet = `var ${vaultVarName}=${serializedTable};var ${cacheVarName}=[];var ${dCacheVarName};`;
3010
- const parsedVars = acorn3.parse(varsSnippet, {
3011
- ecmaVersion: "latest",
3012
- sourceType: "script"
3013
- });
3014
- let insertIdx = 0;
3015
- while (insertIdx < ast.body.length) {
3016
- const stmt = ast.body[insertIdx];
3017
- const isDirective = stmt.type === "ExpressionStatement" && (Boolean(stmt.directive) || stmt.expression?.type === "Literal" && typeof stmt.expression.value === "string" && (activeDirectives.has(stmt.expression.value) || /^(?:use\s+[a-zA-Z0-9_-]+)/.test(stmt.expression.value.trim())));
3018
- if (isDirective || stmt.type === "ImportDeclaration") {
3019
- insertIdx++;
3020
- } else {
3021
- break;
4398
+ if (shaderPayloads.length > 0) {
4399
+ const shaderVarName = derivePolymorphicIdent(seed, "shader");
4400
+ for (const target of shaderTargets) {
4401
+ const callExpr = {
4402
+ type: "CallExpression",
4403
+ callee: {
4404
+ type: "Identifier",
4405
+ name: shaderVarName
4406
+ },
4407
+ arguments: [
4408
+ {
4409
+ type: "Literal",
4410
+ value: target.idx,
4411
+ raw: String(target.idx)
4412
+ }
4413
+ ],
4414
+ optional: false
4415
+ };
4416
+ replaceNodeInParent(target.parent, target.node, callExpr);
4417
+ }
4418
+ const shaderHelperStmt = createShaderVaultAst(
4419
+ shaderVarName,
4420
+ shaderPayloads,
4421
+ seed,
4422
+ sym,
4423
+ expDelta,
4424
+ shieldCoupled
4425
+ );
4426
+ const shaderInsertIdx = findVaultInsertIndex(ast, activeDirectives);
4427
+ ast.body.splice(shaderInsertIdx, 0, shaderHelperStmt);
4428
+ if (targetsToReplace.length === 0) {
4429
+ integrityToken = computeFnv1aHash(JSON.stringify(shaderPayloads), seed);
3022
4430
  }
3023
4431
  }
3024
- ast.body.splice(insertIdx, 0, ...parsedVars.body, fnDeclAst);
3025
4432
  return {
3026
4433
  encryptedStringsCount: targetsToReplace.length,
3027
4434
  integrityToken,
3028
4435
  vaultVarName,
3029
- decryptFnName
4436
+ decryptFnName,
4437
+ shaderBuffersCount: shaderPayloads.length
3030
4438
  };
3031
4439
  }
3032
4440
 
@@ -3175,6 +4583,7 @@ function isAdversaryDecoy(val, seed) {
3175
4583
  }
3176
4584
  function isEligibleHotLiteral(val, node, parent, ancestors, minLen, seed = 2654435769, customReserved, activeDirectives = DIRECTIVE_STRINGS, semanticAnchorPatterns, excludeUiClasses = true) {
3177
4585
  if (val.length < minLen || activeDirectives.has(val)) return false;
4586
+ if (isBinaryOrBase64Payload(val)) return false;
3178
4587
  if (isReactDomSpecialProp(val, node, parent, customReserved)) return false;
3179
4588
  if (isTailwindNoise(val)) return false;
3180
4589
  if (isSvgPathString(val, parent)) return false;
@@ -3202,11 +4611,7 @@ function isEligibleHotLiteral(val, node, parent, ancestors, minLen, seed = 26544
3202
4611
  for (let i = ancestors.length - 2; i >= 0; i--) {
3203
4612
  const a = ancestors[i];
3204
4613
  if (a.type === "FunctionDeclaration" || a.type === "FunctionExpression" || a.type === "ArrowFunctionExpression") {
3205
- if (a.id?.name && /^[A-Z]/.test(a.id.name)) {
3206
- isInsideRender = true;
3207
- break;
3208
- }
3209
- if (a._unpeekIsComponent) {
4614
+ if (Boolean(a._unpeekIsComponent)) {
3210
4615
  isInsideRender = true;
3211
4616
  break;
3212
4617
  }
@@ -3229,9 +4634,58 @@ function isEligibleHotLiteral(val, node, parent, ancestors, minLen, seed = 26544
3229
4634
  }
3230
4635
  return true;
3231
4636
  }
3232
- var SHADER_SIG_RE = /@group|@binding|@vertex|@fragment|@compute|vec4f|gl_Position|uniform/;
4637
+ var SHADER_SIG_RE = /@group|@binding|@vertex|@fragment|@compute|@builtin|@location|@workgroup_size|\bstruct\s+[A-Za-z_]\w*\s*\{|\b[iub]?vec[234][fhiu]?\b|\bmat[234](?:x[234])?[fhi]?\b|\buniform\b|\bvar<(?:uniform|storage)|\bgl_(?:Position|FragColor|FragCoord|VertexID|InstanceID)\b|\bfn\s+main\b|\bvoid\s+main\s*\(|\bprecision\s+(?:lowp|mediump|highp)\s+float\b/;
4638
+ function isInsideLoopOrSerialized(ancestors) {
4639
+ for (let i = ancestors.length - 2; i >= 0; i--) {
4640
+ const anc = ancestors[i];
4641
+ if (LOOP_NODE_TYPES.has(anc.type) || Boolean(anc._unpeekSerialized)) {
4642
+ return true;
4643
+ }
4644
+ }
4645
+ return false;
4646
+ }
4647
+ var BINARY_DATA_URI_RE = /^data:(?:application\/(?:wasm|octet-stream|pdf|zip|gzip|font-[a-z0-9-]+)|image\/|font\/|audio\/|video\/)/i;
4648
+ var PURE_BASE64_RE = /^[A-Za-z0-9+/]+={0,2}$/;
4649
+ function isBinaryOrBase64Payload(val) {
4650
+ if (val.startsWith("AGFzbQE")) return true;
4651
+ if (BINARY_DATA_URI_RE.test(val)) return true;
4652
+ if (val.length >= 4096 && !/\s/.test(val) && PURE_BASE64_RE.test(val)) {
4653
+ return true;
4654
+ }
4655
+ return false;
4656
+ }
4657
+ function isShaderPayload(val, node, parent, ancestors, seed, isHotExempt, customReserved) {
4658
+ if (isBinaryOrBase64Payload(val)) return false;
4659
+ if (isInsideLoopOrSerialized(ancestors)) return false;
4660
+ if (parent?.type === "Property" && parent.key === node && !parent.computed) return false;
4661
+ if (isReservedProp(val, customReserved)) return false;
4662
+ if (isTailwindNoise(val)) return false;
4663
+ if (isSvgPathString(val, parent)) return false;
4664
+ if (isAdversaryDecoy(val, seed)) return false;
4665
+ if (val.startsWith("HOT_")) return false;
4666
+ const matchesSig = SHADER_SIG_RE.test(val);
4667
+ if (!matchesSig) {
4668
+ if (val.length < 256) return false;
4669
+ if (isHotExempt && isUiClassName(val, parent)) return false;
4670
+ }
4671
+ return true;
4672
+ }
4673
+ function findVaultInsertIndex(ast, activeDirectives = DIRECTIVE_STRINGS) {
4674
+ let insertIdx = 0;
4675
+ while (insertIdx < ast.body.length) {
4676
+ const stmt = ast.body[insertIdx];
4677
+ const isDirective = stmt.type === "ExpressionStatement" && (Boolean(stmt.directive) || stmt.expression?.type === "Literal" && typeof stmt.expression.value === "string" && (activeDirectives.has(stmt.expression.value) || /^(?:use\s+[a-zA-Z0-9_-]+)/.test(stmt.expression.value.trim())));
4678
+ if (isDirective || stmt.type === "ImportDeclaration") {
4679
+ insertIdx++;
4680
+ } else {
4681
+ break;
4682
+ }
4683
+ }
4684
+ return insertIdx;
4685
+ }
3233
4686
  function shouldEncryptString(val, minLen, parent, activeDirectives = DIRECTIVE_STRINGS, customReserved) {
3234
4687
  if (val.length < minLen || activeDirectives.has(val)) return false;
4688
+ if (isBinaryOrBase64Payload(val)) return false;
3235
4689
  if (isReservedProp(val, customReserved)) return false;
3236
4690
  if (isSvgPathString(val, parent)) return false;
3237
4691
  if (isTailwindNoise(val)) return false;
@@ -3299,9 +4753,31 @@ function uint8ArrayToBase64(bytes) {
3299
4753
  }
3300
4754
  throw new Error("No base64 encoder available in this environment");
3301
4755
  }
3302
- function createShaderVaultAst(shaderVarName, shaderPayloads, seed) {
4756
+ function createShaderVaultAst(shaderVarName, shaderPayloads, seed, windowKeySymbol, expectedDelta, shieldCoupled = false) {
3303
4757
  const sSeed = seed >>> 0;
3304
- 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);}};})`;
4758
+ let fnCode;
4759
+ let ed = 0;
4760
+ if (!shieldCoupled) {
4761
+ 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);}};})`;
4762
+ } else {
4763
+ const sym = windowKeySymbol ?? deriveWindowKeySymbol(sSeed);
4764
+ let expDelta = expectedDelta;
4765
+ if (expDelta === void 0) {
4766
+ expDelta = generateRuntimeShield({
4767
+ seed: sSeed,
4768
+ windowKeySymbol: sym
4769
+ }).expectedDelta ?? 0;
4770
+ }
4771
+ ed = expDelta & 65535;
4772
+ const edInit = buildRivestDeltaExpr(sSeed, ed, "_ed");
4773
+ const propAccess = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(sym) ? `.${sym}` : `[${JSON.stringify(sym)}]`;
4774
+ const stateSym = `${sym}_s`;
4775
+ const stateAccess = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(stateSym) ? `.${stateSym}` : `[${JSON.stringify(stateSym)}]`;
4776
+ const flagSym = `${sym}_t`;
4777
+ const flagAccess = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(flagSym) ? `.${flagSym}` : `[${JSON.stringify(flagSym)}]`;
4778
+ const tkExpr = `['__','unp','eek_t','ampered'].join('')`;
4779
+ 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);}};})`;
4780
+ }
3305
4781
  const parsedProgram = acorn4.parse(fnCode, {
3306
4782
  ecmaVersion: "latest",
3307
4783
  sourceType: "script"
@@ -3309,7 +4785,7 @@ function createShaderVaultAst(shaderVarName, shaderPayloads, seed) {
3309
4785
  const firstStmt = parsedProgram.body[0];
3310
4786
  const fnAst = firstStmt.expression;
3311
4787
  const buildH = computeIntegrityHash(generateCompactJs(fnAst), 0);
3312
- const S = (buildH ^ sSeed) >>> 0;
4788
+ const S = (buildH ^ sSeed ^ (shieldCoupled ? ed : 0)) >>> 0;
3313
4789
  const textEncoder = new TextEncoder();
3314
4790
  const b64List = [];
3315
4791
  for (let idx = 0; idx < shaderPayloads.length; idx++) {
@@ -3380,7 +4856,7 @@ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExempt
3380
4856
  }
3381
4857
  const alreadyVaulted = ast.body.some(
3382
4858
  (stmt) => stmt.type === "VariableDeclaration" && stmt.declarations?.some(
3383
- (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")
4859
+ (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")
3384
4860
  )
3385
4861
  );
3386
4862
  if (alreadyVaulted) {
@@ -3417,35 +4893,105 @@ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExempt
3417
4893
  if (node.value) c(node.value, st);
3418
4894
  }
3419
4895
  };
4896
+ function processVaultCandidate(val, node, parent, ancestors) {
4897
+ if (isNodeInExemptSubtree(ancestors, exemptSubtreeRoots)) {
4898
+ return;
4899
+ }
4900
+ if (parent.type === "ExpressionStatement" && (Boolean(parent.directive) || activeDirectives.has(val))) {
4901
+ return;
4902
+ }
4903
+ for (let i = ancestors.length - 2; i >= 0; i--) {
4904
+ if (ancestors[i].type === "ExpressionStatement" && Boolean(ancestors[i].directive)) {
4905
+ return;
4906
+ }
4907
+ }
4908
+ let isHotExempt = false;
4909
+ if (hotExemptNodes) {
4910
+ for (let i = ancestors.length - 2; i >= 0; i--) {
4911
+ if (hotExemptNodes.has(ancestors[i])) {
4912
+ isHotExempt = true;
4913
+ break;
4914
+ }
4915
+ }
4916
+ }
4917
+ if (isShaderPayload(
4918
+ val,
4919
+ node,
4920
+ parent,
4921
+ ancestors,
4922
+ seed,
4923
+ isHotExempt,
4924
+ customReserved
4925
+ )) {
4926
+ let idx2 = shaderToIndex.get(val);
4927
+ if (idx2 === void 0) {
4928
+ idx2 = shaderPayloads.length;
4929
+ shaderToIndex.set(val, idx2);
4930
+ shaderPayloads.push(val);
4931
+ }
4932
+ targetsToReplace.push({
4933
+ type: "shader",
4934
+ node,
4935
+ parent,
4936
+ idx: idx2,
4937
+ scopeChain: extractScopeChain(ast, ancestors)
4938
+ });
4939
+ return;
4940
+ }
4941
+ if (isHotExempt) {
4942
+ if (isEligibleHotLiteral(
4943
+ val,
4944
+ node,
4945
+ parent,
4946
+ ancestors,
4947
+ minLen,
4948
+ seed,
4949
+ customReserved,
4950
+ activeDirectives,
4951
+ semanticPatterns,
4952
+ excludeUi
4953
+ )) {
4954
+ hotTargetsToReplace.push({
4955
+ node,
4956
+ parent,
4957
+ val,
4958
+ idx: hotTargetsToReplace.length
4959
+ });
4960
+ }
4961
+ return;
4962
+ }
4963
+ if (!shouldEncryptString(
4964
+ val,
4965
+ minLen,
4966
+ parent,
4967
+ activeDirectives,
4968
+ customReserved
4969
+ )) {
4970
+ return;
4971
+ }
4972
+ let idx = stringToIndex.get(val);
4973
+ if (idx === void 0) {
4974
+ idx = uniqueStrings.length;
4975
+ stringToIndex.set(val, idx);
4976
+ uniqueStrings.push(val);
4977
+ }
4978
+ targetsToReplace.push({
4979
+ type: "string",
4980
+ node,
4981
+ parent,
4982
+ idx,
4983
+ scopeChain: extractScopeChain(ast, ancestors)
4984
+ });
4985
+ }
3420
4986
  walk4.ancestor(
3421
4987
  ast,
3422
4988
  {
3423
4989
  Literal(node, _state, ancestors) {
3424
- if (typeof node.value !== "string") return;
3425
- const val = node.value;
3426
- if (activeDirectives.has(val)) return;
3427
- let isHotExempt = false;
3428
- if (hotExemptNodes) {
3429
- for (let i = ancestors.length - 2; i >= 0; i--) {
3430
- if (hotExemptNodes.has(ancestors[i])) {
3431
- isHotExempt = true;
3432
- break;
3433
- }
3434
- }
3435
- }
4990
+ if (typeof node.value !== "string") return;
4991
+ const val = node.value;
4992
+ if (activeDirectives.has(val)) return;
3436
4993
  const parent = ancestors[ancestors.length - 2];
3437
4994
  if (!parent) return;
3438
- if (isNodeInExemptSubtree(ancestors, exemptSubtreeRoots)) {
3439
- return;
3440
- }
3441
- if (parent.type === "ExpressionStatement" && (Boolean(parent.directive) || activeDirectives.has(val))) {
3442
- return;
3443
- }
3444
- for (let i = ancestors.length - 2; i >= 0; i--) {
3445
- if (ancestors[i].type === "ExpressionStatement" && Boolean(ancestors[i].directive)) {
3446
- return;
3447
- }
3448
- }
3449
4995
  if (parent.type === "ImportDeclaration" || parent.type === "ExportNamedDeclaration" || parent.type === "ExportAllDeclaration" || parent.type === "ImportExpression") {
3450
4996
  if (parent.source === node) return;
3451
4997
  }
@@ -3455,154 +5001,22 @@ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExempt
3455
5001
  if (parent.type === "ImportAttribute" || parent.type === "ImportSpecifier" || parent.type === "ExportSpecifier") {
3456
5002
  return;
3457
5003
  }
3458
- if (isHotExempt) {
3459
- if (isEligibleHotLiteral(
3460
- val,
3461
- node,
3462
- parent,
3463
- ancestors,
3464
- minLen,
3465
- seed,
3466
- customReserved,
3467
- activeDirectives,
3468
- semanticPatterns,
3469
- excludeUi
3470
- )) {
3471
- hotTargetsToReplace.push({
3472
- node,
3473
- parent,
3474
- val,
3475
- idx: hotTargetsToReplace.length
3476
- });
3477
- }
3478
- return;
3479
- }
3480
- if (parent.type === "Property" && parent.key === node && !parent.computed) {
3481
- if (isReservedProp(val, customReserved)) {
3482
- return;
3483
- }
3484
- }
3485
- if (isReservedProp(val, customReserved)) return;
3486
- if (isTailwindNoise(val)) return;
3487
- if (isSvgPathString(val, parent)) return;
3488
- const isShader = val.length >= 256 || SHADER_SIG_RE.test(val);
3489
- if (isShader) {
3490
- let idx = shaderToIndex.get(val);
3491
- if (idx === void 0) {
3492
- idx = shaderPayloads.length;
3493
- shaderToIndex.set(val, idx);
3494
- shaderPayloads.push(val);
3495
- }
3496
- targetsToReplace.push({
3497
- type: "shader",
3498
- node,
3499
- parent,
3500
- idx,
3501
- scopeChain: extractScopeChain(ast, ancestors)
3502
- });
3503
- } else {
3504
- if (!shouldEncryptString(val, minLen, parent, activeDirectives, customReserved)) return;
3505
- let idx = stringToIndex.get(val);
3506
- if (idx === void 0) {
3507
- idx = uniqueStrings.length;
3508
- stringToIndex.set(val, idx);
3509
- uniqueStrings.push(val);
3510
- }
3511
- targetsToReplace.push({
3512
- type: "string",
3513
- node,
3514
- parent,
3515
- idx,
3516
- scopeChain: extractScopeChain(ast, ancestors)
3517
- });
3518
- }
5004
+ processVaultCandidate(val, node, parent, ancestors);
3519
5005
  },
3520
5006
  TemplateLiteral(node, _state, ancestors) {
3521
5007
  if (!node.quasis || node.quasis.length !== 1) return;
3522
5008
  if (node.expressions && node.expressions.length !== 0) return;
3523
5009
  const val = node.quasis[0].value.cooked ?? node.quasis[0].value.raw;
3524
5010
  if (typeof val !== "string" || activeDirectives.has(val)) return;
3525
- if (isNodeInExemptSubtree(ancestors, exemptSubtreeRoots)) {
3526
- return;
3527
- }
3528
- let isHotExempt = false;
3529
- if (hotExemptNodes) {
3530
- for (let i = ancestors.length - 2; i >= 0; i--) {
3531
- if (hotExemptNodes.has(ancestors[i])) {
3532
- isHotExempt = true;
3533
- break;
3534
- }
3535
- }
3536
- }
3537
5011
  const parent = ancestors[ancestors.length - 2];
3538
5012
  if (!parent) return;
3539
- if (isNodeInExemptSubtree(ancestors, exemptSubtreeRoots)) {
3540
- return;
3541
- }
3542
- if (parent.type === "ExpressionStatement" && (Boolean(parent.directive) || activeDirectives.has(val))) {
5013
+ if (parent.type === "TaggedTemplateExpression" && parent.quasi === node) {
3543
5014
  return;
3544
5015
  }
3545
- for (let i = ancestors.length - 2; i >= 0; i--) {
3546
- if (ancestors[i].type === "ExpressionStatement" && Boolean(ancestors[i].directive)) {
3547
- return;
3548
- }
3549
- }
3550
- if (isHotExempt) {
3551
- if (isEligibleHotLiteral(
3552
- val,
3553
- node,
3554
- parent,
3555
- ancestors,
3556
- minLen,
3557
- seed,
3558
- customReserved,
3559
- activeDirectives,
3560
- semanticPatterns,
3561
- excludeUi
3562
- )) {
3563
- hotTargetsToReplace.push({
3564
- node,
3565
- parent,
3566
- val,
3567
- idx: hotTargetsToReplace.length
3568
- });
3569
- }
5016
+ if (parent.type === "ImportExpression" && parent.source === node) {
3570
5017
  return;
3571
5018
  }
3572
- if (isReservedProp(val, customReserved)) return;
3573
- if (isTailwindNoise(val)) return;
3574
- if (isSvgPathString(val, parent)) return;
3575
- const isShader = val.length >= 256 || SHADER_SIG_RE.test(val);
3576
- if (isShader) {
3577
- let idx = shaderToIndex.get(val);
3578
- if (idx === void 0) {
3579
- idx = shaderPayloads.length;
3580
- shaderToIndex.set(val, idx);
3581
- shaderPayloads.push(val);
3582
- }
3583
- targetsToReplace.push({
3584
- type: "shader",
3585
- node,
3586
- parent,
3587
- idx,
3588
- scopeChain: extractScopeChain(ast, ancestors)
3589
- });
3590
- } else {
3591
- if (!shouldEncryptString(val, minLen, parent, activeDirectives, customReserved)) return;
3592
- let idx = stringToIndex.get(val);
3593
- if (idx === void 0) {
3594
- idx = uniqueStrings.length;
3595
- stringToIndex.set(val, idx);
3596
- uniqueStrings.push(val);
3597
- }
3598
- targetsToReplace.push({
3599
- type: "string",
3600
- node,
3601
- parent,
3602
- idx,
3603
- scopeChain: extractScopeChain(ast, ancestors)
3604
- });
3605
- }
5019
+ processVaultCandidate(val, node, parent, ancestors);
3606
5020
  }
3607
5021
  },
3608
5022
  customWalkBase
@@ -3646,16 +5060,7 @@ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExempt
3646
5060
  delete node.quasis;
3647
5061
  delete node.expressions;
3648
5062
  }
3649
- let insertIdx = 0;
3650
- while (insertIdx < ast.body.length) {
3651
- const stmt = ast.body[insertIdx];
3652
- const isDirective = stmt.type === "ExpressionStatement" && (Boolean(stmt.directive) || stmt.expression?.type === "Literal" && typeof stmt.expression.value === "string" && (activeDirectives.has(stmt.expression.value) || /^(?:use\s+[a-zA-Z0-9_-]+)/.test(stmt.expression.value.trim())));
3653
- if (isDirective || stmt.type === "ImportDeclaration") {
3654
- insertIdx++;
3655
- } else {
3656
- break;
3657
- }
3658
- }
5063
+ let insertIdx = findVaultInsertIndex(ast, activeDirectives);
3659
5064
  const wantFragmented = Boolean(config?.vault?.fragmented);
3660
5065
  let fragCount = Math.max(2, Math.min(8, Math.floor(config?.vault?.fragmentCount ?? 3)));
3661
5066
  while (fragCount > 2 && Math.floor(uniqueStrings.length / fragCount) < 4) {
@@ -3831,7 +5236,10 @@ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExempt
3831
5236
  const shaderHelperStmt = createShaderVaultAst(
3832
5237
  shaderVarName,
3833
5238
  shaderPayloads,
3834
- seed
5239
+ seed,
5240
+ sym,
5241
+ expDelta,
5242
+ shieldCoupled
3835
5243
  );
3836
5244
  ast.body.splice(insertIdx++, 0, shaderHelperStmt);
3837
5245
  }
@@ -4876,6 +6284,19 @@ function extractParamNames(paramNode, out = []) {
4876
6284
  }
4877
6285
  return out;
4878
6286
  }
6287
+ function makeSafeNumericParam(name) {
6288
+ return {
6289
+ type: "ConditionalExpression",
6290
+ test: {
6291
+ type: "BinaryExpression",
6292
+ operator: "===",
6293
+ left: makeUnary("typeof", { type: "Identifier", name }),
6294
+ right: makeLiteral("number")
6295
+ },
6296
+ consequent: makeBinary("|", { type: "Identifier", name }, makeLiteral(0)),
6297
+ alternate: makeLiteral(0)
6298
+ };
6299
+ }
4879
6300
  function buildLiveVariables4(seed, fnIndex, paramNode, isArrowFn = false, ctxOpts) {
4880
6301
  const candidates = [];
4881
6302
  const seenNames = /* @__PURE__ */ new Set();
@@ -4883,7 +6304,7 @@ function buildLiveVariables4(seed, fnIndex, paramNode, isArrowFn = false, ctxOpt
4883
6304
  for (const name of names) {
4884
6305
  if (name && name !== "arguments" && name !== "eval" && !seenNames.has(name)) {
4885
6306
  seenNames.add(name);
4886
- candidates.push(makeBinary("|", { type: "Identifier", name }, makeLiteral(0)));
6307
+ candidates.push(makeSafeNumericParam(name));
4887
6308
  }
4888
6309
  }
4889
6310
  if (ctxOpts?.aliasIdentA && ctxOpts?.aliasIdentB) {
@@ -4930,13 +6351,151 @@ function buildLiveVariables4(seed, fnIndex, paramNode, isArrowFn = false, ctxOpt
4930
6351
  }
4931
6352
  return [candidates[0], candidates[1], candidates[2], candidates[3]];
4932
6353
  }
6354
+ var QNR_RESIDUE_FAMILIES = [
6355
+ // LHS in {1, 2}: > 2 is false; ((v ^ (v >> 1)) & 1) === 1
6356
+ { add: 1, mask: 3, target: 3, outBoundOp: ">", outBoundVal: 2, bitKind: "xor1", expectedBit: 1 },
6357
+ // LHS in {3, 4, 7}: < 3 is false; ((v | (v >> 2)) & 1) === 1
6358
+ { add: 3, mask: 7, target: 6, outBoundOp: "<", outBoundVal: 3, bitKind: "or2", expectedBit: 1 },
6359
+ // LHS in {1, 5, 6}: > 6 is false; ((v ^ (v >> 1)) & 1) === 1
6360
+ { add: 5, mask: 7, target: 3, outBoundOp: ">", outBoundVal: 6, bitKind: "xor1", expectedBit: 1 },
6361
+ // LHS in {0, 7, 8, 11}: > 11 is false; ((v ^ (v >> 1)) & 1) === 0
6362
+ { add: 7, mask: 15, target: 13, outBoundOp: ">", outBoundVal: 11, bitKind: "xor1", expectedBit: 0 }
6363
+ ];
6364
+ function makeTypeofGlobalLen() {
6365
+ return {
6366
+ type: "MemberExpression",
6367
+ computed: false,
6368
+ object: makeUnary("typeof", { type: "Identifier", name: "globalThis" }),
6369
+ property: { type: "Identifier", name: "length" }
6370
+ };
6371
+ }
6372
+ function makePropAccess(objExpr, propName) {
6373
+ if (/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(propName)) {
6374
+ return {
6375
+ type: "MemberExpression",
6376
+ computed: false,
6377
+ object: objExpr,
6378
+ property: { type: "Identifier", name: propName }
6379
+ };
6380
+ }
6381
+ return {
6382
+ type: "MemberExpression",
6383
+ computed: true,
6384
+ object: objExpr,
6385
+ property: makeLiteral(propName)
6386
+ };
6387
+ }
6388
+ function buildQnrBitExpr(qnrValRef, bitKind) {
6389
+ const shiftAmt = bitKind === "xor1" ? 1 : 2;
6390
+ const combOp = bitKind === "xor1" ? "^" : "|";
6391
+ return makeBinary(
6392
+ "&",
6393
+ makeBinary(
6394
+ combOp,
6395
+ cloneNode(qnrValRef),
6396
+ makeBinary(">>", cloneNode(qnrValRef), makeLiteral(shiftAmt))
6397
+ ),
6398
+ makeLiteral(1)
6399
+ );
6400
+ }
4933
6401
  function createSotaMbaPredicate(seed, fnIndex = 0, paramNode, decoyIdent, isArrowFn = false, ctxOpts) {
4934
6402
  const domain = ctxOpts?.returnDomain ?? "object";
4935
6403
  const [x1, x2, x3, x4] = buildLiveVariables4(seed, fnIndex, paramNode, isArrowFn, ctxOpts);
4936
6404
  const mba4 = buildMba4Ast(seed, fnIndex, x1, x2, x3, x4);
6405
+ const qnrFamilyIdx = ((seed ^ Math.imul(fnIndex + 1, 2654435761)) >>> 0) % QNR_RESIDUE_FAMILIES.length;
6406
+ const qnrFamily = QNR_RESIDUE_FAMILIES[qnrFamilyIdx];
6407
+ const slotA = fnIndex + (seed & 3) & 3;
6408
+ const slotB = slotA + 1 + (seed >>> 2 & 1) & 3;
6409
+ const hasAlias = Boolean(ctxOpts?.aliasIdentA);
6410
+ const aliasReadIdent = ctxOpts?.aliasIdentB ?? ctxOpts?.aliasIdentA ?? "";
4937
6411
  let qnrLeft;
6412
+ let qnrValForForm0;
4938
6413
  let zRefForDecoy;
4939
- if (ctxOpts?.scratchVarIdent) {
6414
+ let aliasInvZero = null;
6415
+ if (ctxOpts?.mxIdent && ctxOpts?.scratchVarIdent && hasAlias) {
6416
+ const scratchId = { type: "Identifier", name: ctxOpts.scratchVarIdent };
6417
+ const names = [...ctxOpts?.liveVars ?? [], ...extractParamNames(paramNode)];
6418
+ const uniqueNames = [];
6419
+ for (const n of names) {
6420
+ if (n && n !== "arguments" && n !== "eval" && !uniqueNames.includes(n)) {
6421
+ uniqueNames.push(n);
6422
+ }
6423
+ }
6424
+ const arg0 = uniqueNames.length >= 1 ? makeSafeNumericParam(uniqueNames[0]) : !isArrowFn ? {
6425
+ type: "MemberExpression",
6426
+ computed: false,
6427
+ object: { type: "Identifier", name: "arguments" },
6428
+ property: { type: "Identifier", name: "length" }
6429
+ } : makeTypeofGlobalLen();
6430
+ const arg1 = uniqueNames.length >= 2 ? makeSafeNumericParam(uniqueNames[1]) : uniqueNames.length === 1 && !isArrowFn ? {
6431
+ type: "MemberExpression",
6432
+ computed: false,
6433
+ object: { type: "Identifier", name: "arguments" },
6434
+ property: { type: "Identifier", name: "length" }
6435
+ } : makeTypeofGlobalLen();
6436
+ const a0 = mixSeed32(seed, fnIndex * 13 + 3);
6437
+ const a1 = mixSeed32(seed, fnIndex * 13 + 5) | 1;
6438
+ const a2 = mixSeed32(seed, fnIndex * 13 + 7) & ~1;
6439
+ const a3 = mixSeed32(seed, fnIndex * 13 + 9) & ~1;
6440
+ const maskConst = mixSeed32(seed, fnIndex + 97) | 1;
6441
+ const r0 = mixSeed32(seed, fnIndex * 17 + 1);
6442
+ const r1 = mixSeed32(seed, fnIndex * 17 + 3) | 1;
6443
+ const seqExprs = [
6444
+ {
6445
+ type: "AssignmentExpression",
6446
+ operator: "=",
6447
+ left: cloneNode(scratchId),
6448
+ right: {
6449
+ type: "CallExpression",
6450
+ callee: { type: "Identifier", name: ctxOpts.mxIdent },
6451
+ arguments: [
6452
+ arg0,
6453
+ arg1,
6454
+ makeLiteral(slotA),
6455
+ makeLiteral(slotB),
6456
+ makeInt32Literal(maskConst),
6457
+ makeInt32Literal(a0),
6458
+ makeInt32Literal(a1),
6459
+ makeInt32Literal(a2),
6460
+ makeInt32Literal(a3)
6461
+ ],
6462
+ optional: false
6463
+ }
6464
+ },
6465
+ {
6466
+ type: "AssignmentExpression",
6467
+ operator: "=",
6468
+ left: cloneNode(scratchId),
6469
+ right: makeBinary(
6470
+ "|",
6471
+ makeBinary("+", makeInt32Literal(r0), makeImul(cloneNode(scratchId), makeInt32Literal(r1))),
6472
+ makeLiteral(0)
6473
+ )
6474
+ }
6475
+ ];
6476
+ const qnrCore = makeBinary(
6477
+ "&",
6478
+ makeBinary("+", makeImul(cloneNode(scratchId), cloneNode(scratchId)), makeLiteral(qnrFamily.add)),
6479
+ makeLiteral(qnrFamily.mask)
6480
+ );
6481
+ qnrLeft = {
6482
+ type: "SequenceExpression",
6483
+ expressions: [...seqExprs, qnrCore]
6484
+ };
6485
+ qnrValForForm0 = {
6486
+ type: "SequenceExpression",
6487
+ expressions: [
6488
+ {
6489
+ type: "AssignmentExpression",
6490
+ operator: "=",
6491
+ left: cloneNode(scratchId),
6492
+ right: cloneNode(qnrCore)
6493
+ },
6494
+ buildQnrBitExpr(scratchId, qnrFamily.bitKind)
6495
+ ]
6496
+ };
6497
+ zRefForDecoy = cloneNode(scratchId);
6498
+ } else if (ctxOpts?.scratchVarIdent) {
4940
6499
  const scratchId = { type: "Identifier", name: ctxOpts.scratchVarIdent };
4941
6500
  const rivestOnScratch = buildRivestPermAst(seed, fnIndex, scratchId);
4942
6501
  const seqExprs = [
@@ -4961,25 +6520,62 @@ function createSotaMbaPredicate(seed, fnIndex = 0, paramNode, decoyIdent, isArro
4961
6520
  right: buildSboxMixAst(ctxOpts.sboxIdent, ctxOpts.scratchVarIdent)
4962
6521
  });
4963
6522
  }
4964
- seqExprs.push(
4965
- makeBinary(
4966
- "&",
4967
- makeBinary("+", makeImul(cloneNode(scratchId), cloneNode(scratchId)), makeLiteral(1)),
4968
- makeLiteral(3)
4969
- )
6523
+ if (hasAlias) {
6524
+ const aliasWriteMemA = makeMemberIndex(ctxOpts.aliasIdentA, makeLiteral(slotA));
6525
+ const maskConst = mixSeed32(seed, fnIndex + 97) | 1;
6526
+ const updateMask = makeBinary(
6527
+ "^",
6528
+ makeBinary("<<", cloneNode(scratchId), makeLiteral(3)),
6529
+ makeInt32Literal(maskConst)
6530
+ );
6531
+ seqExprs.push({
6532
+ type: "AssignmentExpression",
6533
+ operator: "=",
6534
+ left: cloneNode(aliasWriteMemA),
6535
+ right: makeBinary("|", makeBinary("^", cloneNode(aliasWriteMemA), cloneNode(updateMask)), makeLiteral(0))
6536
+ });
6537
+ aliasInvZero = makeBinary(
6538
+ "^",
6539
+ makeBinary("|", makeBinary("^", cloneNode(aliasWriteMemA), cloneNode(updateMask)), makeLiteral(0)),
6540
+ {
6541
+ type: "AssignmentExpression",
6542
+ operator: "=",
6543
+ left: cloneNode(aliasWriteMemA),
6544
+ right: makeBinary("|", makeBinary("^", cloneNode(aliasWriteMemA), cloneNode(updateMask)), makeLiteral(0))
6545
+ }
6546
+ );
6547
+ }
6548
+ const qnrCore = makeBinary(
6549
+ "&",
6550
+ makeBinary("+", makeImul(cloneNode(scratchId), cloneNode(scratchId)), makeLiteral(qnrFamily.add)),
6551
+ makeLiteral(qnrFamily.mask)
4970
6552
  );
4971
6553
  qnrLeft = {
4972
6554
  type: "SequenceExpression",
4973
- expressions: seqExprs
6555
+ expressions: [...seqExprs, qnrCore]
6556
+ };
6557
+ qnrValForForm0 = {
6558
+ type: "SequenceExpression",
6559
+ expressions: [
6560
+ {
6561
+ type: "AssignmentExpression",
6562
+ operator: "=",
6563
+ left: cloneNode(scratchId),
6564
+ right: cloneNode(qnrCore)
6565
+ },
6566
+ buildQnrBitExpr(scratchId, qnrFamily.bitKind)
6567
+ ]
4974
6568
  };
4975
6569
  zRefForDecoy = cloneNode(scratchId);
4976
6570
  } else {
4977
6571
  const zExpr = buildRivestPermAst(seed, fnIndex, mba4);
4978
- qnrLeft = makeBinary(
6572
+ const qnrCore = makeBinary(
4979
6573
  "&",
4980
- makeBinary("+", makeImul(cloneNode(zExpr), cloneNode(zExpr)), makeLiteral(1)),
4981
- makeLiteral(3)
6574
+ makeBinary("+", makeImul(cloneNode(zExpr), cloneNode(zExpr)), makeLiteral(qnrFamily.add)),
6575
+ makeLiteral(qnrFamily.mask)
4982
6576
  );
6577
+ qnrLeft = qnrCore;
6578
+ qnrValForForm0 = buildQnrBitExpr(qnrCore, qnrFamily.bitKind);
4983
6579
  zRefForDecoy = zExpr;
4984
6580
  }
4985
6581
  const consequent = createContextualDecoyConsequent(
@@ -4989,14 +6585,94 @@ function createSotaMbaPredicate(seed, fnIndex = 0, paramNode, decoyIdent, isArro
4989
6585
  decoyIdent,
4990
6586
  zRefForDecoy
4991
6587
  );
6588
+ const hasShieldCoupling = Boolean(ctxOpts?.shieldCoupled && ctxOpts?.windowKeySymbol);
6589
+ const predForm = fnIndex + (hasShieldCoupling ? 1 : seed >>> 2 & 3) & 3;
6590
+ let testExpr;
6591
+ if (predForm === 0) {
6592
+ let pathACore = qnrValForForm0;
6593
+ if (aliasInvZero) {
6594
+ pathACore = makeBinary("^", aliasInvZero, qnrValForForm0);
6595
+ }
6596
+ if (hasAlias) {
6597
+ pathACore = makeBinary(
6598
+ "^",
6599
+ pathACore,
6600
+ makeBinary("&", makeMemberIndex(aliasReadIdent, makeLiteral(slotB)), makeLiteral(1))
6601
+ );
6602
+ }
6603
+ const pathA = ctxOpts?.scratchVarIdent ? {
6604
+ type: "SequenceExpression",
6605
+ expressions: [...qnrLeft.expressions.slice(0, -1), pathACore]
6606
+ } : pathACore;
6607
+ const pathB = hasAlias ? makeBinary(
6608
+ "^",
6609
+ makeLiteral(qnrFamily.expectedBit),
6610
+ makeBinary("&", makeMemberIndex(ctxOpts.aliasIdentA, makeLiteral(slotB)), makeLiteral(1))
6611
+ ) : makeLiteral(qnrFamily.expectedBit);
6612
+ testExpr = makeBinary("!==", makeBinary("^", pathA, pathB), makeLiteral(0));
6613
+ } else if (predForm === 1) {
6614
+ const qnrLhs = aliasInvZero ? makeBinary("+", qnrLeft, makeBinary("&", aliasInvZero, makeLiteral(1))) : qnrLeft;
6615
+ const qnrFail = makeBinary(qnrFamily.outBoundOp, qnrLhs, makeLiteral(qnrFamily.outBoundVal));
6616
+ const hasGlobal = makeBinary(
6617
+ "<",
6618
+ makeUnary("typeof", { type: "Identifier", name: "globalThis" }),
6619
+ makeLiteral("u")
6620
+ );
6621
+ const tamperCheck = hasShieldCoupling ? {
6622
+ type: "LogicalExpression",
6623
+ operator: "&&",
6624
+ left: hasGlobal,
6625
+ right: {
6626
+ type: "LogicalExpression",
6627
+ operator: "&&",
6628
+ left: makePropAccess({ type: "Identifier", name: "globalThis" }, `${ctxOpts.windowKeySymbol}_s`),
6629
+ right: makeBinary(
6630
+ "===",
6631
+ {
6632
+ type: "MemberExpression",
6633
+ computed: true,
6634
+ object: makePropAccess({ type: "Identifier", name: "globalThis" }, `${ctxOpts.windowKeySymbol}_s`),
6635
+ property: makeLiteral(0)
6636
+ },
6637
+ makeLiteral(2)
6638
+ )
6639
+ }
6640
+ } : {
6641
+ type: "LogicalExpression",
6642
+ operator: "&&",
6643
+ left: hasGlobal,
6644
+ right: makeBinary(
6645
+ "===",
6646
+ makePropAccess({ type: "Identifier", name: "globalThis" }, "__unpeek_tampered"),
6647
+ makeUnary("!", makeLiteral(0))
6648
+ )
6649
+ };
6650
+ testExpr = {
6651
+ type: "LogicalExpression",
6652
+ operator: "||",
6653
+ left: qnrFail,
6654
+ right: tamperCheck
6655
+ };
6656
+ } else if (predForm === 2) {
6657
+ const slotReadB = hasAlias ? makeBinary("&", makeMemberIndex(aliasReadIdent, makeLiteral(slotB)), makeLiteral(7)) : makeBinary("&", makeTypeofGlobalLen(), makeLiteral(7));
6658
+ const slotWriteB = hasAlias ? makeBinary("&", makeMemberIndex(ctxOpts.aliasIdentA, makeLiteral(slotB)), makeLiteral(7)) : makeBinary("&", makeTypeofGlobalLen(), makeLiteral(7));
6659
+ let lhsExpr = makeBinary("+", qnrLeft, slotReadB);
6660
+ if (aliasInvZero) {
6661
+ lhsExpr = makeBinary("+", lhsExpr, makeBinary("&", aliasInvZero, makeLiteral(3)));
6662
+ }
6663
+ const rhsExpr = makeBinary("+", makeLiteral(qnrFamily.outBoundVal), slotWriteB);
6664
+ testExpr = makeBinary(qnrFamily.outBoundOp, lhsExpr, rhsExpr);
6665
+ } else {
6666
+ const tagLhs = hasAlias ? makeBinary("&", makeMemberIndex(ctxOpts.aliasIdentA, makeLiteral(slotB)), makeLiteral(240)) : makeBinary("&", makeBinary("<<", makeTypeofGlobalLen(), makeLiteral(4)), makeLiteral(240));
6667
+ const tagRhsBase = hasAlias ? makeBinary("&", makeMemberIndex(aliasReadIdent, makeLiteral(slotB)), makeLiteral(240)) : makeBinary("&", makeBinary("<<", makeTypeofGlobalLen(), makeLiteral(4)), makeLiteral(240));
6668
+ const tagRhs = aliasInvZero ? makeBinary("^", tagRhsBase, makeBinary("&", aliasInvZero, makeLiteral(15))) : tagRhsBase;
6669
+ const lhsExpr = makeBinary("|", makeBinary("^", qnrLeft, tagLhs), makeLiteral(0));
6670
+ const rhsExpr = makeBinary("|", makeBinary("^", makeLiteral(qnrFamily.target), tagRhs), makeLiteral(0));
6671
+ testExpr = makeBinary("===", lhsExpr, rhsExpr);
6672
+ }
4992
6673
  return {
4993
6674
  type: "IfStatement",
4994
- test: {
4995
- type: "BinaryExpression",
4996
- operator: "===",
4997
- left: qnrLeft,
4998
- right: makeLiteral(3)
4999
- },
6675
+ test: testExpr,
5000
6676
  consequent,
5001
6677
  alternate: null
5002
6678
  };
@@ -5055,7 +6731,7 @@ function inferFunctionReturnDomain(fnNode) {
5055
6731
  if (seenString && !seenNumber && !seenBoolean) return "string";
5056
6732
  return "object";
5057
6733
  }
5058
- function createSboxAndAliasDeclarations(sboxIdent, aliasIdentA, aliasIdentB, scratchVarIdent, seed) {
6734
+ function createSboxAndAliasDeclarations(sboxIdent, aliasIdentA, aliasIdentB, scratchVarIdent, seed, mxIdent) {
5059
6735
  const sboxInit = acorn5.parseExpressionAt(
5060
6736
  `(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;})()`,
5061
6737
  0,
@@ -5067,48 +6743,188 @@ function createSboxAndAliasDeclarations(sboxIdent, aliasIdentA, aliasIdentB, scr
5067
6743
  mixSeed32(seed, 107),
5068
6744
  mixSeed32(seed, 109)
5069
6745
  ];
6746
+ const declarations = [
6747
+ {
6748
+ type: "VariableDeclarator",
6749
+ id: { type: "Identifier", name: sboxIdent },
6750
+ init: sboxInit
6751
+ },
6752
+ {
6753
+ type: "VariableDeclarator",
6754
+ id: { type: "Identifier", name: aliasIdentA },
6755
+ init: {
6756
+ type: "ArrayExpression",
6757
+ elements: stateVals.map((v) => makeInt32Literal(v))
6758
+ }
6759
+ },
6760
+ {
6761
+ type: "VariableDeclarator",
6762
+ id: { type: "Identifier", name: aliasIdentB },
6763
+ init: { type: "Identifier", name: aliasIdentA }
6764
+ },
6765
+ {
6766
+ type: "VariableDeclarator",
6767
+ id: { type: "Identifier", name: scratchVarIdent },
6768
+ init: makeLiteral(0)
6769
+ }
6770
+ ];
6771
+ if (mxIdent) {
6772
+ const mbaAst = buildMba4Ast(
6773
+ seed,
6774
+ 0,
6775
+ { type: "Identifier", name: "$u" },
6776
+ { type: "Identifier", name: "$v" },
6777
+ { type: "Identifier", name: "$p" },
6778
+ { type: "Identifier", name: "$q" }
6779
+ );
6780
+ const mxFn = {
6781
+ type: "FunctionExpression",
6782
+ id: null,
6783
+ params: [
6784
+ { type: "Identifier", name: "$a" },
6785
+ { type: "Identifier", name: "$b" },
6786
+ { type: "Identifier", name: "$c" },
6787
+ { type: "Identifier", name: "$d" },
6788
+ { type: "Identifier", name: "$e" },
6789
+ { type: "Identifier", name: "$f" },
6790
+ { type: "Identifier", name: "$g" },
6791
+ { type: "Identifier", name: "$h" },
6792
+ { type: "Identifier", name: "$i" }
6793
+ ],
6794
+ body: {
6795
+ type: "BlockStatement",
6796
+ body: [
6797
+ {
6798
+ type: "VariableDeclaration",
6799
+ kind: "var",
6800
+ declarations: [
6801
+ { type: "VariableDeclarator", id: { type: "Identifier", name: "$u" }, init: makeBinary("|", { type: "Identifier", name: "$a" }, makeLiteral(0)) },
6802
+ { type: "VariableDeclarator", id: { type: "Identifier", name: "$v" }, init: makeBinary("|", { type: "Identifier", name: "$b" }, makeLiteral(0)) },
6803
+ { type: "VariableDeclarator", id: { type: "Identifier", name: "$p" }, init: makeBinary("|", makeMemberIndex(aliasIdentA, { type: "Identifier", name: "$c" }), makeLiteral(0)) },
6804
+ { type: "VariableDeclarator", id: { type: "Identifier", name: "$q" }, init: makeBinary("|", makeMemberIndex(aliasIdentB, { type: "Identifier", name: "$d" }), makeLiteral(0)) },
6805
+ { type: "VariableDeclarator", id: { type: "Identifier", name: "$z" }, init: mbaAst }
6806
+ ]
6807
+ },
6808
+ {
6809
+ type: "ExpressionStatement",
6810
+ expression: {
6811
+ type: "AssignmentExpression",
6812
+ operator: "=",
6813
+ left: { type: "Identifier", name: "$z" },
6814
+ right: makeBinary(
6815
+ "|",
6816
+ makeBinary(
6817
+ "+",
6818
+ { type: "Identifier", name: "$f" },
6819
+ makeImul(
6820
+ { type: "Identifier", name: "$z" },
6821
+ makeBinary(
6822
+ "+",
6823
+ { type: "Identifier", name: "$g" },
6824
+ makeImul(
6825
+ { type: "Identifier", name: "$z" },
6826
+ makeBinary(
6827
+ "+",
6828
+ { type: "Identifier", name: "$h" },
6829
+ makeImul({ type: "Identifier", name: "$z" }, { type: "Identifier", name: "$i" })
6830
+ )
6831
+ )
6832
+ )
6833
+ )
6834
+ ),
6835
+ makeLiteral(0)
6836
+ )
6837
+ }
6838
+ },
6839
+ {
6840
+ type: "ExpressionStatement",
6841
+ expression: {
6842
+ type: "AssignmentExpression",
6843
+ operator: "=",
6844
+ left: { type: "Identifier", name: "$z" },
6845
+ right: buildSboxMixAst(sboxIdent, "$z")
6846
+ }
6847
+ },
6848
+ {
6849
+ type: "VariableDeclaration",
6850
+ kind: "var",
6851
+ declarations: [
6852
+ {
6853
+ type: "VariableDeclarator",
6854
+ id: { type: "Identifier", name: "$m" },
6855
+ init: makeBinary("^", makeBinary("<<", { type: "Identifier", name: "$z" }, makeLiteral(3)), { type: "Identifier", name: "$e" })
6856
+ }
6857
+ ]
6858
+ },
6859
+ {
6860
+ type: "ExpressionStatement",
6861
+ expression: {
6862
+ type: "AssignmentExpression",
6863
+ operator: "=",
6864
+ left: makeMemberIndex(aliasIdentA, { type: "Identifier", name: "$c" }),
6865
+ right: makeBinary("|", makeBinary("^", makeMemberIndex(aliasIdentA, { type: "Identifier", name: "$c" }), { type: "Identifier", name: "$m" }), makeLiteral(0))
6866
+ }
6867
+ },
6868
+ {
6869
+ type: "VariableDeclaration",
6870
+ kind: "var",
6871
+ declarations: [
6872
+ {
6873
+ type: "VariableDeclarator",
6874
+ id: { type: "Identifier", name: "$w" },
6875
+ init: makeBinary(
6876
+ "^",
6877
+ makeBinary("|", makeBinary("^", makeMemberIndex(aliasIdentA, { type: "Identifier", name: "$c" }), { type: "Identifier", name: "$m" }), makeLiteral(0)),
6878
+ {
6879
+ type: "AssignmentExpression",
6880
+ operator: "=",
6881
+ left: makeMemberIndex(aliasIdentA, { type: "Identifier", name: "$c" }),
6882
+ right: makeBinary("|", makeBinary("^", makeMemberIndex(aliasIdentA, { type: "Identifier", name: "$c" }), { type: "Identifier", name: "$m" }), makeLiteral(0))
6883
+ }
6884
+ )
6885
+ }
6886
+ ]
6887
+ },
6888
+ {
6889
+ type: "ReturnStatement",
6890
+ argument: {
6891
+ type: "AssignmentExpression",
6892
+ operator: "=",
6893
+ left: { type: "Identifier", name: scratchVarIdent },
6894
+ right: makeBinary("|", makeBinary("^", { type: "Identifier", name: "$z" }, { type: "Identifier", name: "$w" }), makeLiteral(0))
6895
+ }
6896
+ }
6897
+ ]
6898
+ },
6899
+ generator: false,
6900
+ async: false,
6901
+ expression: false
6902
+ };
6903
+ declarations.push({
6904
+ type: "VariableDeclarator",
6905
+ id: { type: "Identifier", name: mxIdent },
6906
+ init: mxFn
6907
+ });
6908
+ }
5070
6909
  return {
5071
6910
  type: "VariableDeclaration",
5072
6911
  kind: "var",
5073
- declarations: [
5074
- {
5075
- type: "VariableDeclarator",
5076
- id: { type: "Identifier", name: sboxIdent },
5077
- init: sboxInit
5078
- },
5079
- {
5080
- type: "VariableDeclarator",
5081
- id: { type: "Identifier", name: aliasIdentA },
5082
- init: {
5083
- type: "ArrayExpression",
5084
- elements: stateVals.map((v) => makeInt32Literal(v))
5085
- }
5086
- },
5087
- {
5088
- type: "VariableDeclarator",
5089
- id: { type: "Identifier", name: aliasIdentB },
5090
- init: { type: "Identifier", name: aliasIdentA }
5091
- },
5092
- {
5093
- type: "VariableDeclarator",
5094
- id: { type: "Identifier", name: scratchVarIdent },
5095
- init: makeLiteral(0)
5096
- }
5097
- ]
6912
+ declarations
5098
6913
  };
5099
6914
  }
5100
6915
  var MAX_COLD_GUARDS_PER_CHUNK = 12;
5101
- function applyColdFlowGuard(ast, coldFunctionNodes, seed = 2654435769, hotExemptNodes) {
5102
- const decoyIdent = "_d";
6916
+ function applyColdFlowGuard(ast, coldFunctionNodes, seed = 2654435769, hotExemptNodes, windowKeySymbol, expectedDelta, shieldCoupled = false) {
5103
6917
  const sfx = (seed >>> 0).toString(36).slice(0, 4);
6918
+ const decoyIdent = `_uDec${sfx}`;
5104
6919
  const sboxIdent = `_uSb${sfx}`;
5105
6920
  const aliasIdentA = `_uAl${sfx}`;
5106
6921
  const aliasIdentB = `_uAm${sfx}`;
5107
6922
  const scratchVarIdent = `_uZt${sfx}`;
6923
+ const mxIdent = `_uMx${sfx}`;
5108
6924
  if (Array.isArray(ast.body)) {
5109
6925
  const alreadyGuarded = ast.body.some(
5110
6926
  (stmt) => stmt.type === "VariableDeclaration" && stmt.declarations?.some(
5111
- (d) => d.id?.type === "Identifier" && (d.id.name === decoyIdent || d.id.name === sboxIdent)
6927
+ (d) => d.id?.type === "Identifier" && (d.id.name === decoyIdent || d.id.name === sboxIdent || d.id.name === mxIdent)
5112
6928
  )
5113
6929
  );
5114
6930
  if (alreadyGuarded) return 0;
@@ -5118,6 +6934,7 @@ function applyColdFlowGuard(ast, coldFunctionNodes, seed = 2654435769, hotExempt
5118
6934
  if (guardedCount >= MAX_COLD_GUARDS_PER_CHUNK) return;
5119
6935
  if (!coldFunctionNodes.has(node)) return;
5120
6936
  if (hotExemptNodes?.has(node) || node._unpeekSerialized) return;
6937
+ if (node._unpeekVirtualized === true) return;
5121
6938
  if (!node.body || node.body.type !== "BlockStatement") return;
5122
6939
  const paramNames = [];
5123
6940
  for (const p of node.params || []) {
@@ -5138,7 +6955,11 @@ function applyColdFlowGuard(ast, coldFunctionNodes, seed = 2654435769, hotExempt
5138
6955
  aliasIdentA,
5139
6956
  aliasIdentB,
5140
6957
  scratchVarIdent,
5141
- returnDomain
6958
+ mxIdent,
6959
+ returnDomain,
6960
+ windowKeySymbol,
6961
+ expectedDelta,
6962
+ shieldCoupled
5142
6963
  }
5143
6964
  );
5144
6965
  guardedCount++;
@@ -5168,11 +6989,17 @@ function applyColdFlowGuard(ast, coldFunctionNodes, seed = 2654435769, hotExempt
5168
6989
  aliasIdentA,
5169
6990
  aliasIdentB,
5170
6991
  scratchVarIdent,
5171
- seed
6992
+ seed,
6993
+ mxIdent
5172
6994
  );
5173
6995
  if (hotExemptNodes) {
5174
6996
  hotExemptNodes.add(sharedDecoyDecl);
5175
6997
  hotExemptNodes.add(sboxAliasDecl);
6998
+ for (const decl of sboxAliasDecl.declarations || []) {
6999
+ if (decl.init?.type === "FunctionExpression") {
7000
+ hotExemptNodes.add(decl.init);
7001
+ }
7002
+ }
5176
7003
  for (const decl of sharedDecoyDecl.declarations || []) {
5177
7004
  if (decl.init?.type === "ArrayExpression" && decl.init.elements) {
5178
7005
  for (const el of decl.init.elements) {
@@ -5271,7 +7098,7 @@ function mixOpSeed(seed, salt) {
5271
7098
  h ^= h >>> 13;
5272
7099
  return h | 0;
5273
7100
  }
5274
- function encryptBytecodeStream(plainBytecode, fnSalt, vmKey, stateSlots, accSlots) {
7101
+ function encryptBytecodeStream(plainBytecode, fnSalt, vmKey, stateSlots, accSlots, jumpTargets) {
5275
7102
  const len = plainBytecode.length;
5276
7103
  const enc = new Array(len);
5277
7104
  const stateBefore = new Array(len + 1);
@@ -5302,14 +7129,14 @@ function encryptBytecodeStream(plainBytecode, fnSalt, vmKey, stateSlots, accSlot
5302
7129
  accBefore[len] = ac;
5303
7130
  if (stateSlots) {
5304
7131
  for (const slot of stateSlots) {
5305
- const targetPc = plainBytecode[slot - 1];
7132
+ const targetPc = jumpTargets?.get(slot - 1) ?? plainBytecode[slot - 1];
5306
7133
  const sBefore = stAtSlot.get(slot) ?? 0;
5307
7134
  enc[slot] = stateBefore[targetPc] ^ sBefore | 0;
5308
7135
  }
5309
7136
  }
5310
7137
  if (accSlots) {
5311
7138
  for (const slot of accSlots) {
5312
- const targetPc = plainBytecode[slot - 2];
7139
+ const targetPc = jumpTargets?.get(slot - 2) ?? plainBytecode[slot - 2];
5313
7140
  const aBefore = acAtSlot.get(slot) ?? 0;
5314
7141
  enc[slot] = accBefore[targetPc] ^ aBefore | 0;
5315
7142
  }
@@ -5334,36 +7161,39 @@ function generateOpcodeMap(seed, count = OPCODE_COUNT) {
5334
7161
  }
5335
7162
  return pool.slice(0, count);
5336
7163
  }
5337
- function makeHandlerMbaZeroExpr(seed, op) {
7164
+ function computeHandlerBias(seed, op) {
7165
+ const mixed = Math.abs(mixOpSeed(seed, op * 19 + 7)) % 31;
7166
+ return mixed + 1;
7167
+ }
7168
+ function makeHandlerMbaOffsetExpr(seed, op, bias) {
5338
7169
  const variant = Math.abs(mixOpSeed(seed, op * 11 + 3)) % 4;
5339
7170
  const c1 = mixOpSeed(seed, op * 11 + 5);
5340
7171
  const c2 = mixOpSeed(seed, op * 11 + 7);
5341
7172
  if (variant === 0) {
5342
- const cSum = c1 + c2 | 0;
7173
+ const cSum = c1 + c2 - bias | 0;
5343
7174
  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`;
5344
7175
  }
5345
7176
  if (variant === 1) {
5346
- const cSum = c1 + c2 | 0;
7177
+ const cSum = c1 + c2 + bias | 0;
5347
7178
  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`;
5348
7179
  }
5349
7180
  if (variant === 2) {
5350
- const cFold = 1 - c1 - c2 | 0;
5351
- return `(((~$f.ac|${c1})+(~$f.ac&${c1}))+(($f.ac|${c2})+($f.ac&${c2}))+${cFold})|0`;
7181
+ const cFold2 = 1 + bias - c1 - c2 | 0;
7182
+ return `(((~$f.ac|${c1})+(~$f.ac&${c1}))+(($f.ac|$f.p)-(~$f.ac&$f.p))+(($f.p&${c2})+(~$f.p&${c2}))+${cFold2})|0`;
5352
7183
  }
5353
- return `((($f.ac|$f.p)-(~$f.ac&$f.p))^((($f.ac&${c1})+($f.ac&~${c1}))))|0`;
7184
+ const cFold = c1 - bias | 0;
7185
+ 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`;
5354
7186
  }
5355
7187
  function wrapHandlerWithMba(seed, op, coreBody, isTerminal = false) {
5356
- const zExpr = makeHandlerMbaZeroExpr(seed, op);
7188
+ const bias = computeHandlerBias(seed, op);
7189
+ const zExpr = makeHandlerMbaOffsetExpr(seed, op, bias);
5357
7190
  const shape = Math.abs(mixOpSeed(seed, op * 17 + 1)) % 3;
5358
7191
  const zVar = shape === 0 ? "$z0" : shape === 1 ? "$m0" : "$k0";
5359
7192
  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);";
5360
- const adjustedBody = coreBody.replace(/\$Z/g, zVar);
5361
- if (coreBody.includes("$Z")) {
5362
- return `function($f){var ${zVar}=${zExpr};${adjustedBody}${tail}}`;
5363
- }
5364
- return `function($f){var ${zVar}=${zExpr};$f.r=($f.r+${zVar})|0;${adjustedBody}${tail}}`;
7193
+ const adjustedBody = coreBody.replace(/\$Z/g, zVar).replace(/\$B/g, String(bias));
7194
+ return `function($f){var ${zVar}=${zExpr};${adjustedBody}${tail}}`;
5365
7195
  }
5366
- function createInterpreterSource(vmHelperName, opMap, seed = 2654435769, windowKeySymbol, expectedDelta) {
7196
+ function createInterpreterSource(vmHelperName, opMap, seed = 2654435769, windowKeySymbol, expectedDelta, expectedStateHash) {
5367
7197
  const opCount = opMap.length;
5368
7198
  const slotMap = shuffleRange(opCount, (seed ^ 1367130551) >>> 0);
5369
7199
  const pairOrder = shuffleRange(opCount, (seed ^ 1013904242) >>> 0);
@@ -5378,69 +7208,82 @@ function createInterpreterSource(vmHelperName, opMap, seed = 2654435769, windowK
5378
7208
  const andImpl = Math.abs(mixOpSeed(seed, OP_AND)) % 2 === 0 ? "~(~$a|~$b)" : "$a&$b";
5379
7209
  const orImpl = Math.abs(mixOpSeed(seed, OP_OR)) % 2 === 0 ? "(($a^$b)+($a&$b))|0" : "$a|$b";
5380
7210
  const coreHandlers = {
5381
- [OP_LDC]: { body: "$f.q[($f.r++)+$Z]=$f.k[$rd($f)];" },
5382
- [OP_LDV]: { body: "$f.q[($f.r++)+$Z]=$f.s[$rd($f)];" },
5383
- [OP_STV]: { body: "$f.s[$rd($f)]=$f.q[(--$f.r)+$Z];" },
5384
- [OP_LDG]: { body: "$f.q[($f.r++)+$Z]=$G[$f.k[$rd($f)]];" },
5385
- [OP_GETP]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a[$b];" },
5386
- [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);" },
5387
- [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);" },
5388
- [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);" },
5389
- [OP_ADD]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a+$b;" },
5390
- [OP_SUB]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a-$b;" },
5391
- [OP_MUL]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a*$b;" },
5392
- [OP_XOR]: { body: `var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=${xorImpl};` },
5393
- [OP_AND]: { body: `var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=${andImpl};` },
5394
- [OP_OR]: { body: `var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=${orImpl};` },
5395
- [OP_SEQ]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a===$b;" },
5396
- [OP_LT]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a<$b;" },
5397
- [OP_NOT]: { body: "$f.q[($f.r-1)+$Z]=!$f.q[$f.r-1];" },
5398
- [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;" },
5399
- [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;}" },
5400
- [OP_RET]: { body: "$f.d=1;$f.v=$f.q[(--$f.r)+$Z];", terminal: true },
5401
- [OP_THROW]: { body: "throw $f.q[(--$f.r)+$Z];" },
7211
+ [OP_LDC]: { body: "$f.q[$f.r++]=$f.k[($rd($f)-$Z)&0xffff];" },
7212
+ [OP_LDV]: { body: "$f.q[$f.r++]=$f.s[($rd($f)-$Z)&0xffff];" },
7213
+ [OP_STV]: { body: "$f.s[($rd($f)-$Z)&0xffff]=$f.q[--$f.r];" },
7214
+ [OP_LDG]: { body: "$f.q[$f.r++]=$G[$f.k[($rd($f)-$Z)&0xffff]];" },
7215
+ [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;" },
7216
+ [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;" },
7217
+ [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);" },
7218
+ [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);" },
7219
+ [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;" },
7220
+ [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;" },
7221
+ [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;" },
7222
+ [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;` },
7223
+ [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;` },
7224
+ [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;` },
7225
+ [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;" },
7226
+ [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;" },
7227
+ [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;" },
7228
+ [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;" },
7229
+ [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;}" },
7230
+ [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 },
7231
+ [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;" },
5402
7232
  [OP_AWAIT]: {
5403
- 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;});",
7233
+ 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;});",
5404
7234
  terminal: true
5405
7235
  },
5406
- [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;" },
5407
- [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;" },
5408
- [OP_LDU]: { body: "$f.q[($f.r++)+$Z]=$f.u[$rd($f)][0]();" },
5409
- [OP_STU]: { body: "$f.u[$rd($f)][1]($f.q[(--$f.r)+$Z]);" },
5410
- [OP_DIV]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a/$b;" },
5411
- [OP_MOD]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a%$b;" },
5412
- [OP_SHL]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a<<$b;" },
5413
- [OP_SHR]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a>>$b;" },
5414
- [OP_USHR]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a>>>$b;" },
5415
- [OP_POW]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a**$b;" },
5416
- [OP_EQ]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a==$b;" },
5417
- [OP_TYPEOF]: { body: "$f.q[($f.r-1)+$Z]=typeof $f.q[$f.r-1];" },
5418
- [OP_IN]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a in $b;" },
5419
- [OP_INSTOF]: { body: "var $b=$f.q[--$f.r],$a=$f.q[(--$f.r)+$Z];$f.q[$f.r++]=$a instanceof $b;" },
5420
- [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);" },
5421
- [OP_THIS]: { body: "$f.q[($f.r++)+$Z]=$f.t;" },
5422
- [OP_POP]: { body: "--$f.r;$f.r+=$Z;" },
5423
- [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});" },
5424
- [OP_ENDTRY]: { body: "$f.e.pop();$f.r+=$Z;" },
5425
- [OP_NULLISH]: { body: "var $v=$f.q[($f.r-1)+$Z];$f.q[$f.r-1]=($v===null||$v===void 0);" },
5426
- [OP_DUP]: { body: "var $top=$f.q[($f.r-1)+$Z];$f.q[$f.r++]=$top;" }
7236
+ [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;" },
7237
+ [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;" },
7238
+ [OP_LDU]: { body: "$f.q[$f.r++]=$f.u[($rd($f)-$Z)&0xffff][0]();" },
7239
+ [OP_STU]: { body: "$f.u[($rd($f)-$Z)&0xffff][1]($f.q[--$f.r]);" },
7240
+ [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;" },
7241
+ [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;" },
7242
+ [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;" },
7243
+ [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;" },
7244
+ [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;" },
7245
+ [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;" },
7246
+ [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;" },
7247
+ [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;" },
7248
+ [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;" },
7249
+ [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;" },
7250
+ [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);" },
7251
+ [OP_THIS]: { body: "$f.r=($f.r+$Z)|0;$f.q[($f.r++)-$B]=$f.t;$f.r=($f.r-$B)|0;" },
7252
+ [OP_POP]: { body: "$f.r=($f.r+$Z)|0;$f.r=($f.r-(1+$B))|0;" },
7253
+ [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});" },
7254
+ [OP_ENDTRY]: { body: "$f.r=($f.r+$Z)|0;$f.e.pop();$f.r=($f.r-$B)|0;" },
7255
+ [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;" },
7256
+ [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;" }
5427
7257
  };
5428
7258
  const handlers = new Array(opCount);
5429
7259
  for (let op = 0; op < opCount; op++) {
5430
7260
  const spec = coreHandlers[op];
5431
7261
  handlers[slotMap[op]] = wrapHandlerWithMba(seed, op, spec.body, Boolean(spec.terminal));
5432
7262
  }
5433
- const hasSym = Boolean(windowKeySymbol && expectedDelta !== void 0);
7263
+ const hasSym = Boolean(windowKeySymbol);
7264
+ const hasExpDelta = Boolean(hasSym && expectedDelta !== void 0);
7265
+ const hasExpHash = Boolean(hasSym && expectedStateHash !== void 0);
7266
+ const hasDigest = hasExpDelta || hasExpHash;
5434
7267
  const symPropAccess = hasSym ? /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(windowKeySymbol) ? `.${windowKeySymbol}` : `[${JSON.stringify(windowKeySymbol)}]` : "";
5435
7268
  const symTamperPropAccess = hasSym ? /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(`${windowKeySymbol}_t`) ? `.${windowKeySymbol}_t` : `[${JSON.stringify(`${windowKeySymbol}_t`)}]` : "";
5436
- const expD = hasSym ? expectedDelta & 65535 : 0;
7269
+ const symStatePropAccess = hasSym ? /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(`${windowKeySymbol}_s`) ? `.${windowKeySymbol}_s` : `[${JSON.stringify(`${windowKeySymbol}_s`)}]` : "";
7270
+ const expD = hasExpDelta ? expectedDelta & 65535 : 0;
7271
+ const expH = hasExpHash ? expectedStateHash | 0 : 0;
5437
7272
  const seed32 = seed | 0;
5438
- const expDigest = hasSym ? Math.imul(expD ^ seed32 | 0, 2654435761) ^ (expD << 16 | seed32 >>> 16) ^ 2246822507 | 0 : 0;
5439
- const tamperCheckExpr = hasSym ? `var $bad=$G[$tk]===!0||$G${symTamperPropAccess}===!0,$sv=$G${symPropAccess};if(!$bad&&$sv!==void 0){if(Array.isArray($sv)){if($sv[0]===2)$bad=true;}else{var $sh=(Math.imul(($sv^$S)|0,0x9e3779b1)^(($sv<<16)|($S>>>16))^0x85ebca6b)|0;if($sh!==$D)$bad=true;}}` : `var $bad=$G[$tk]===!0;`;
5440
- const paramsList = hasSym ? "$P,$A,$B,$C,$S,$D" : "$P,$A,$B,$C,$S";
5441
- const factoryRaw = `(function $I(${paramsList}){var $G=typeof globalThis<"u"?globalThis:(typeof window<"u"?window:this);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(
7273
+ const seedU32 = seed >>> 0;
7274
+ const scopeKey = hasSym ? computeFnv1aHash(
7275
+ `${windowKeySymbol}:${hasExpDelta ? expD : ""}${hasExpHash ? `:${expH}` : ""}`,
7276
+ seed
7277
+ ) >>> 0 : 0;
7278
+ 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;
7279
+ const selfPrettyCheck = "$pp||/\\n/.test(Function.prototype.toString.call($vm))";
7280
+ 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(''));";
7281
+ 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;}" : ""}`;
7282
+ 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);`;
7283
+ const paramsList = hasDigest ? "$P,$A,$B,$C,$S,$D" : "$P,$A,$B,$C,$S";
7284
+ 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(
5442
7285
  ","
5443
- )}];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;}return 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});};})`;
7286
+ )}];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;})`;
5444
7287
  const parsedFactory = acorn6.parse(factoryRaw, {
5445
7288
  ecmaVersion: "latest",
5446
7289
  sourceType: "script"
@@ -5449,7 +7292,7 @@ function createInterpreterSource(vmHelperName, opMap, seed = 2654435769, windowK
5449
7292
  const argA = opMask & 255;
5450
7293
  const argB = slotMask & 255;
5451
7294
  const argC = vmKey | 0;
5452
- return `var ${vmHelperName}=(${compactFactory})([${pairs.join(",")}],${argA},${argB},${argC},${seed32}${hasSym ? `,${expDigest}` : ""});`;
7295
+ return `var ${vmHelperName}=(${compactFactory})([${pairs.join(",")}],${argA},${argB},${argC},${seed32}${hasDigest ? `,${expDigest}` : ""});`;
5453
7296
  }
5454
7297
  function walkWithParent(node, parent, visitor) {
5455
7298
  if (!node || typeof node !== "object") return;
@@ -5659,11 +7502,40 @@ function prepareLoweredFunction(fnNode, enclosingBindings) {
5659
7502
  }
5660
7503
  return { loweredFn: clone, wrapperParams, paramPassExprs };
5661
7504
  }
5662
- function compileFunctionToBytecode(fnNode, opMap, enclosingBindings) {
7505
+ function definitelyTerminates(stmt) {
7506
+ if (!stmt) return false;
7507
+ switch (stmt.type) {
7508
+ case "ReturnStatement":
7509
+ case "ThrowStatement":
7510
+ return true;
7511
+ case "BlockStatement": {
7512
+ const stmts = stmt.body || [];
7513
+ for (const s of stmts) {
7514
+ if (definitelyTerminates(s)) return true;
7515
+ }
7516
+ return false;
7517
+ }
7518
+ case "IfStatement":
7519
+ return Boolean(
7520
+ stmt.alternate && definitelyTerminates(stmt.consequent) && definitelyTerminates(stmt.alternate)
7521
+ );
7522
+ case "TryStatement": {
7523
+ if (stmt.finalizer && definitelyTerminates(stmt.finalizer)) return true;
7524
+ if (!definitelyTerminates(stmt.block)) return false;
7525
+ if (stmt.handler && !definitelyTerminates(stmt.handler.body)) return false;
7526
+ return true;
7527
+ }
7528
+ default:
7529
+ return false;
7530
+ }
7531
+ }
7532
+ function compileFunctionToBytecode(fnNode, opMap, enclosingBindings, seed = 2654435769) {
5663
7533
  const bytecode = [];
5664
7534
  const consts = [];
5665
7535
  const stateSlots = /* @__PURE__ */ new Set();
5666
7536
  const accSlots = /* @__PURE__ */ new Set();
7537
+ const jumpTargets = /* @__PURE__ */ new Map();
7538
+ const jumpOps = /* @__PURE__ */ new Map();
5667
7539
  const fnScope = /* @__PURE__ */ new Map();
5668
7540
  const scopeStack = [fnScope];
5669
7541
  const upvalues = [];
@@ -5792,17 +7664,24 @@ function compileFunctionToBytecode(fnNode, opMap, enclosingBindings) {
5792
7664
  }
5793
7665
  function emit(op, ...args) {
5794
7666
  bytecode.push(opMap[op]);
5795
- for (const a of args) bytecode.push(a);
7667
+ if (args.length === 1) {
7668
+ bytecode.push(args[0] + computeHandlerBias(seed, op) & 65535);
7669
+ } else {
7670
+ for (const a of args) bytecode.push(a);
7671
+ }
5796
7672
  }
5797
7673
  function emitJumpPlaceholder(op) {
5798
7674
  const pos = bytecode.length;
5799
7675
  emit(op, 0, 0, 0);
7676
+ jumpOps.set(pos, op);
5800
7677
  stateSlots.add(pos + 2);
5801
7678
  accSlots.add(pos + 3);
5802
7679
  return pos;
5803
7680
  }
5804
7681
  function patchJump(pos, targetPc) {
5805
- bytecode[pos + 1] = targetPc;
7682
+ const op = jumpOps.get(pos) ?? OP_JMP;
7683
+ jumpTargets.set(pos + 1, targetPc);
7684
+ bytecode[pos + 1] = targetPc + computeHandlerBias(seed, op) & 65535;
5806
7685
  }
5807
7686
  function compilePatternAssignFromSlot(pattern, sourceSlot) {
5808
7687
  if (!pattern) return false;
@@ -6374,10 +8253,15 @@ function compileFunctionToBytecode(fnNode, opMap, enclosingBindings) {
6374
8253
  const jzPos = emitJumpPlaceholder(OP_JZ);
6375
8254
  if (!compileStmt(stmt.consequent, false)) return false;
6376
8255
  if (stmt.alternate) {
6377
- const jmpPos = emitJumpPlaceholder(OP_JMP);
8256
+ let jmpPos = -1;
8257
+ if (!definitelyTerminates(stmt.consequent)) {
8258
+ jmpPos = emitJumpPlaceholder(OP_JMP);
8259
+ }
6378
8260
  patchJump(jzPos, bytecode.length);
6379
8261
  if (!compileStmt(stmt.alternate, false)) return false;
6380
- patchJump(jmpPos, bytecode.length);
8262
+ if (jmpPos !== -1) {
8263
+ patchJump(jmpPos, bytecode.length);
8264
+ }
6381
8265
  } else {
6382
8266
  patchJump(jzPos, bytecode.length);
6383
8267
  }
@@ -6647,15 +8531,20 @@ function compileFunctionToBytecode(fnNode, opMap, enclosingBindings) {
6647
8531
  return false;
6648
8532
  }
6649
8533
  }
8534
+ let endsWithTermination = false;
6650
8535
  if (fnNode.body.type === "BlockStatement") {
6651
8536
  if (!compileStmt(fnNode.body, true)) return null;
8537
+ endsWithTermination = definitelyTerminates(fnNode.body);
6652
8538
  } else {
6653
8539
  if (!compileExpr(fnNode.body, true)) return null;
6654
8540
  emit(OP_RET);
8541
+ endsWithTermination = true;
8542
+ }
8543
+ if (!endsWithTermination) {
8544
+ emit(OP_LDC, addConst(void 0));
8545
+ emit(OP_RET);
6655
8546
  }
6656
- emit(OP_LDC, addConst(void 0));
6657
- emit(OP_RET);
6658
- return { bytecode, consts, localCount, stateSlots, accSlots, upvalues };
8547
+ return { bytecode, consts, localCount, stateSlots, accSlots, jumpTargets, upvalues };
6659
8548
  }
6660
8549
  function findInjectedVmHelperName(ast) {
6661
8550
  if (!ast || !Array.isArray(ast.body)) return null;
@@ -6673,6 +8562,80 @@ function findInjectedVmHelperName(ast) {
6673
8562
  }
6674
8563
  return null;
6675
8564
  }
8565
+ var PRIORITY_HANDLER_NAME_RE = /^(?:onSubmit|handleSubmit|submit[A-Za-z0-9_]*|validate[A-Za-z0-9_]*|login(?:[A-Z0-9_].*)?|signIn(?:[A-Z0-9_].*)?|register(?:[A-Z0-9_].*)?|checkout(?:[A-Z0-9_].*)?)$/i;
8566
+ var PRIORITY_CALL_NAME_RE = /^(?:onSubmit|handleSubmit|submit[A-Za-z0-9_]*|validate[A-Za-z0-9_]*|login(?:[A-Z0-9_].*)?|signIn(?:[A-Z0-9_].*)?|register(?:[A-Z0-9_].*)?|checkout(?:[A-Z0-9_].*)?|createServerReference|fetch)$/i;
8567
+ function getVmCandidateName(fn, ancestors) {
8568
+ if (fn.id?.type === "Identifier" && typeof fn.id.name === "string") {
8569
+ return fn.id.name;
8570
+ }
8571
+ const parent = ancestors.length >= 2 ? ancestors[ancestors.length - 2] : null;
8572
+ if (!parent) return "";
8573
+ if (parent.type === "VariableDeclarator" && parent.id?.type === "Identifier") {
8574
+ return parent.id.name;
8575
+ }
8576
+ if (parent.type === "Property") {
8577
+ if (parent.key?.type === "Identifier") return parent.key.name;
8578
+ if (parent.key?.type === "Literal" && typeof parent.key.value === "string") {
8579
+ return parent.key.value;
8580
+ }
8581
+ }
8582
+ if (parent.type === "MethodDefinition" && parent.key?.type === "Identifier") {
8583
+ return parent.key.name;
8584
+ }
8585
+ if (parent.type === "AssignmentExpression") {
8586
+ if (parent.left?.type === "Identifier") return parent.left.name;
8587
+ if (parent.left?.type === "MemberExpression" && !parent.left.computed && parent.left.property?.type === "Identifier") {
8588
+ return parent.left.property.name;
8589
+ }
8590
+ }
8591
+ return "";
8592
+ }
8593
+ function bodyHasPrioritySignal(fnNode) {
8594
+ let matched = false;
8595
+ walkWithParent(fnNode.body, fnNode, (n, parent) => {
8596
+ if (matched) return false;
8597
+ if (n !== fnNode && FUNCTION_NODE_TYPES2.has(n.type)) return false;
8598
+ if (n.type === "CallExpression") {
8599
+ const callee = n.callee;
8600
+ if (callee?.type === "Identifier" && PRIORITY_CALL_NAME_RE.test(callee.name)) {
8601
+ matched = true;
8602
+ return false;
8603
+ }
8604
+ if (callee?.type === "MemberExpression" && !callee.computed && callee.property?.type === "Identifier" && PRIORITY_CALL_NAME_RE.test(callee.property.name)) {
8605
+ matched = true;
8606
+ return false;
8607
+ }
8608
+ }
8609
+ if (n.type === "Identifier" && PRIORITY_CALL_NAME_RE.test(n.name)) {
8610
+ if (parent && parent.type === "MemberExpression" && !parent.computed && parent.property === n) {
8611
+ return;
8612
+ }
8613
+ if (parent && parent.type === "Property" && !parent.computed && parent.key === n && !parent.shorthand) {
8614
+ return;
8615
+ }
8616
+ matched = true;
8617
+ return false;
8618
+ }
8619
+ });
8620
+ return matched;
8621
+ }
8622
+ function scoreVmCandidate(fn, ancestors, criticalSet) {
8623
+ let score = 0;
8624
+ if (criticalSet?.has(fn)) {
8625
+ score += 1e3;
8626
+ }
8627
+ const candName = getVmCandidateName(fn, ancestors);
8628
+ if (candName && PRIORITY_HANDLER_NAME_RE.test(candName) || bodyHasPrioritySignal(fn)) {
8629
+ score += 500;
8630
+ }
8631
+ if (fn.body?.type === "BlockStatement" && Array.isArray(fn.body.body)) {
8632
+ const stmtCount = fn.body.body.length;
8633
+ if (stmtCount >= 2) {
8634
+ score += Math.min(200, 10 + (stmtCount - 2) * 15);
8635
+ }
8636
+ }
8637
+ return score;
8638
+ }
6676
8639
  function applyMicroVm(ast, coldFunctionNodes, serializedFunctionNodes, seed = 2654435769, windowKeySymbol, expectedDelta, extraOpts) {
6677
8640
  const suffix = computeFnv1aHash(`micro-vm:${seed}`, seed).toString(36);
6678
8641
  const vmHelperName = `_uVm${suffix}`;
@@ -6791,10 +8754,11 @@ function applyMicroVm(ast, coldFunctionNodes, serializedFunctionNodes, seed = 26
6791
8754
  }
6792
8755
  }
6793
8756
  });
6794
- const candidates = criticalSet ? [
6795
- ...rawCandidates.filter((c) => criticalSet.has(c.fn)),
6796
- ...rawCandidates.filter((c) => !criticalSet.has(c.fn))
6797
- ] : rawCandidates;
8757
+ const candidates = rawCandidates.map((c, idx) => ({
8758
+ ...c,
8759
+ score: scoreVmCandidate(c.fn, c.ancestors, criticalSet),
8760
+ idx
8761
+ })).sort((a, b) => b.score !== a.score ? b.score - a.score : a.idx - b.idx);
6798
8762
  let virtualizedCount = 0;
6799
8763
  for (const { fn, ancestors } of candidates) {
6800
8764
  if (virtualizedCount >= maxFunctions) break;
@@ -6837,7 +8801,7 @@ function applyMicroVm(ast, coldFunctionNodes, serializedFunctionNodes, seed = 26
6837
8801
  if (!lowered) {
6838
8802
  continue;
6839
8803
  }
6840
- const compiled = compileFunctionToBytecode(lowered.loweredFn, opMap, enclosingBindings);
8804
+ const compiled = compileFunctionToBytecode(lowered.loweredFn, opMap, enclosingBindings, seed);
6841
8805
  if (!compiled) {
6842
8806
  continue;
6843
8807
  }
@@ -6847,7 +8811,8 @@ function applyMicroVm(ast, coldFunctionNodes, serializedFunctionNodes, seed = 26
6847
8811
  fnSalt,
6848
8812
  vmKey,
6849
8813
  compiled.stateSlots,
6850
- compiled.accSlots
8814
+ compiled.accSlots,
8815
+ compiled.jumpTargets
6851
8816
  );
6852
8817
  const constElements = compiled.consts.map((c) => {
6853
8818
  if (c === void 0) {
@@ -6958,6 +8923,7 @@ function applyMicroVm(ast, coldFunctionNodes, serializedFunctionNodes, seed = 26
6958
8923
  } else {
6959
8924
  fn.body = callExpr;
6960
8925
  }
8926
+ fn._unpeekVirtualized = true;
6961
8927
  virtualizedCount++;
6962
8928
  }
6963
8929
  if (virtualizedCount > 0) {
@@ -6966,7 +8932,8 @@ function applyMicroVm(ast, coldFunctionNodes, serializedFunctionNodes, seed = 26
6966
8932
  opMap,
6967
8933
  seed,
6968
8934
  windowKeySymbol,
6969
- expectedDelta
8935
+ expectedDelta,
8936
+ extraOpts?.expectedStateHash
6970
8937
  );
6971
8938
  const parsedHelper = acorn6.parse(interpreterSource, {
6972
8939
  ecmaVersion: "latest",
@@ -7134,7 +9101,7 @@ function isAstAlreadyProtected(ast) {
7134
9101
  for (const d of stmt.declarations) {
7135
9102
  const name = d.id?.type === "Identifier" ? d.id.name : void 0;
7136
9103
  if (typeof name === "string") {
7137
- 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_")) {
9104
+ 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_")) {
7138
9105
  return true;
7139
9106
  }
7140
9107
  }
@@ -7142,7 +9109,7 @@ function isAstAlreadyProtected(ast) {
7142
9109
  }
7143
9110
  if (stmt.type === "FunctionDeclaration" && stmt.id?.type === "Identifier") {
7144
9111
  const fnName = stmt.id.name;
7145
- if (typeof fnName === "string" && (fnName.startsWith("_uD") || fnName.startsWith("_uVm") || fnName.startsWith("_wKdf") || fnName.startsWith("_hX"))) {
9112
+ if (typeof fnName === "string" && (fnName.startsWith("_uD") || fnName.startsWith("_uVm") || fnName.startsWith("_wKdf") || fnName === "_hX")) {
7146
9113
  return true;
7147
9114
  }
7148
9115
  }
@@ -7150,7 +9117,7 @@ function isAstAlreadyProtected(ast) {
7150
9117
  const callee = stmt.expression.callee;
7151
9118
  if (callee?.type === "FunctionExpression") {
7152
9119
  const name = callee.id?.name;
7153
- if (typeof name === "string" && (name.startsWith("_u$") || name.startsWith("_$") || name.startsWith("_s") || name.startsWith("$b") || containsUnpeekShieldMarker(callee.body))) {
9120
+ if (typeof name === "string" && name.startsWith("_u$") || containsUnpeekShieldMarker(callee.body)) {
7154
9121
  return true;
7155
9122
  }
7156
9123
  }
@@ -7227,7 +9194,8 @@ function transformJavaScript(code, options = {}) {
7227
9194
  attachMagicComments(boundary.importExpressions, comments);
7228
9195
  const effectiveConfig = options.critical ? { ...options.config ?? {}, critical: options.critical } : options.config;
7229
9196
  const effectiveProfile = options.profile ?? effectiveConfig?.profile;
7230
- const hotRes = analyzeAstHotPaths(ast, effectiveConfig);
9197
+ const originalSourceMap = internalOptions.originalSourceMap;
9198
+ const hotRes = analyzeAstHotPaths(ast, effectiveConfig, originalSourceMap);
7231
9199
  const {
7232
9200
  report: hotPathReport,
7233
9201
  coldFunctionNodes,
@@ -7252,20 +9220,27 @@ function transformJavaScript(code, options = {}) {
7252
9220
  const detectHeadless = internalOptions.detectHeadless ?? effectiveConfig?.shield?.detectHeadless ?? false;
7253
9221
  const sym = shieldCoupled ? internalOptions.windowKeySymbol ?? deriveWindowKeySymbol(seed) : void 0;
7254
9222
  let shieldDelta = shieldCoupled ? internalOptions.expectedDelta : void 0;
7255
- if (shieldCoupled && shieldDelta === void 0) {
9223
+ let expectedStateHash = shieldCoupled ? internalOptions.expectedStateHash : void 0;
9224
+ if (shieldCoupled && (shieldDelta === void 0 || expectedStateHash === void 0)) {
7256
9225
  const shieldInfo = generateRuntimeShield({
7257
9226
  seed,
7258
9227
  windowKeySymbol: sym,
7259
9228
  deterrentMode,
7260
9229
  detectHeadless
7261
9230
  });
7262
- shieldDelta = shieldInfo.expectedDelta ?? 0;
9231
+ if (shieldDelta === void 0) {
9232
+ shieldDelta = shieldInfo.expectedDelta ?? 0;
9233
+ }
9234
+ if (expectedStateHash === void 0) {
9235
+ expectedStateHash = shieldInfo.expectedStateHash;
9236
+ }
7263
9237
  }
7264
9238
  let virtualizedFunctionsCount = 0;
7265
9239
  if (isAggressive) {
7266
- const extraVmOpts = criticalFunctionNodes || effectiveConfig?.critical?.maxFunctionsPerChunk !== void 0 ? {
9240
+ const extraVmOpts = criticalFunctionNodes || effectiveConfig?.critical?.maxFunctionsPerChunk !== void 0 || expectedStateHash !== void 0 ? {
7267
9241
  ...criticalFunctionNodes ? { criticalFunctionNodes } : {},
7268
- ...effectiveConfig?.critical?.maxFunctionsPerChunk !== void 0 ? { maxFunctionsPerChunk: effectiveConfig.critical.maxFunctionsPerChunk } : {}
9242
+ ...effectiveConfig?.critical?.maxFunctionsPerChunk !== void 0 ? { maxFunctionsPerChunk: effectiveConfig.critical.maxFunctionsPerChunk } : {},
9243
+ ...expectedStateHash !== void 0 ? { expectedStateHash } : {}
7269
9244
  } : void 0;
7270
9245
  const vmRes = extraVmOpts ? applyMicroVm(
7271
9246
  ast,
@@ -7286,7 +9261,15 @@ function transformJavaScript(code, options = {}) {
7286
9261
  virtualizedFunctionsCount = vmRes.virtualizedCount;
7287
9262
  }
7288
9263
  if (effectiveProfile !== "minimal" && effectiveConfig?.coldFlow !== false) {
7289
- applyColdFlowGuard(ast, coldFunctionNodes, seed, hotExemptNodes);
9264
+ applyColdFlowGuard(
9265
+ ast,
9266
+ coldFunctionNodes,
9267
+ seed,
9268
+ hotExemptNodes,
9269
+ sym,
9270
+ shieldDelta,
9271
+ shieldCoupled
9272
+ );
7290
9273
  }
7291
9274
  const mangledSymbolsCount = applyPolymorphicMangler(
7292
9275
  ast,
@@ -7313,6 +9296,7 @@ function transformJavaScript(code, options = {}) {
7313
9296
  );
7314
9297
  encryptedStringsCount = saltedRes.encryptedStringsCount;
7315
9298
  integrityToken = saltedRes.integrityToken;
9299
+ shaderBuffersCount = saltedRes.shaderBuffersCount ?? 0;
7316
9300
  } else {
7317
9301
  const vaultRes = applyStringVault(
7318
9302
  ast,
@@ -7381,6 +9365,13 @@ ${finalCode}`;
7381
9365
 
7382
9366
  export {
7383
9367
  computeFnv1aHash,
9368
+ flattenSourceMapSections,
9369
+ shiftSourceMapLines,
9370
+ computeDeterministicDebugId,
9371
+ chainSourceMaps,
9372
+ resolvePosition,
9373
+ safeDecodeURIComponent,
9374
+ symbolicateStackTrace,
7384
9375
  detectHotPaths,
7385
9376
  computeIntegrityHash,
7386
9377
  verifyCodeIntegrity,