unpeek 4.2.0 → 4.3.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 (34) hide show
  1. package/README.md +2 -2
  2. package/README.tr.md +2 -2
  3. package/dist/adapters/esbuild.cjs +5 -5
  4. package/dist/adapters/esbuild.js +3 -3
  5. package/dist/adapters/next/adapter.cjs +5 -5
  6. package/dist/adapters/next/adapter.js +4 -4
  7. package/dist/adapters/next/index.cjs +5 -5
  8. package/dist/adapters/next/index.js +4 -4
  9. package/dist/adapters/rollup.cjs +5 -5
  10. package/dist/adapters/rollup.js +3 -3
  11. package/dist/adapters/rspack.cjs +5 -5
  12. package/dist/adapters/rspack.js +3 -3
  13. package/dist/adapters/vite.cjs +5 -5
  14. package/dist/adapters/vite.js +3 -3
  15. package/dist/adapters/webpack.cjs +5 -5
  16. package/dist/adapters/webpack.js +3 -3
  17. package/dist/browser.cjs +2 -2
  18. package/dist/browser.js +1 -1
  19. package/dist/{chunk-UUJLTW7O.cjs → chunk-4IRIMLT3.cjs} +16 -16
  20. package/dist/{chunk-AD6UFBPA.cjs → chunk-4XSFPX2Z.cjs} +367 -8
  21. package/dist/{chunk-KIAYVIC5.cjs → chunk-7F75S3GQ.cjs} +60 -36
  22. package/dist/{chunk-K77WRITN.js → chunk-EASD7C2B.js} +3 -3
  23. package/dist/{chunk-APQOBFRO.js → chunk-GKWTP4Z5.js} +30 -6
  24. package/dist/{chunk-MSECP2P4.cjs → chunk-OR5M3SN2.cjs} +1199 -428
  25. package/dist/{chunk-32GLSJAW.js → chunk-RDP4MTHK.js} +359 -0
  26. package/dist/{chunk-BL2UXZGD.js → chunk-RM3V7KJA.js} +1040 -269
  27. package/dist/{chunk-SJK45WAU.cjs → chunk-SBRU7GSX.cjs} +8 -8
  28. package/dist/{chunk-GCWXTWTN.js → chunk-XEYMZUP5.js} +2 -2
  29. package/dist/cli/index.js +1425 -274
  30. package/dist/index.cjs +21 -21
  31. package/dist/index.js +3 -3
  32. package/dist/plugins/unplugin.cjs +4 -4
  33. package/dist/plugins/unplugin.js +3 -3
  34. package/package.json +1 -1
package/dist/cli/index.js CHANGED
@@ -11,10 +11,18 @@ import path2 from "path";
11
11
  import fs from "fs";
12
12
  import path from "path";
13
13
  var SUPPORTED_EXTENSIONS = /* @__PURE__ */ new Set([".js", ".mjs", ".cjs"]);
14
+ var MAX_HTML_FILES = 64;
15
+ var MAX_SCAN_BYTES = 512 * 1024;
16
+ var MAX_JS_GRAPH_FILES = 1024;
14
17
  var EXCLUDED_DIR_NAMES = /* @__PURE__ */ new Set([
15
18
  "node_modules",
16
19
  ".unpeek-maps"
17
20
  ]);
21
+ var HTML_WALK_EXCLUDED_DIR_NAMES = /* @__PURE__ */ new Set([
22
+ "node_modules",
23
+ ".unpeek-maps",
24
+ ".git"
25
+ ]);
18
26
  var WORKER_OR_SW_BASENAME_REGEX = /^(?:sw|service-worker|workbox-[^/]+)\.(?:js|mjs|cjs)$|\.worker(?:[.-][^/]+)*\.(?:js|mjs|cjs)$/i;
19
27
  function isWorkerOrServiceWorkerFile(filePath, rootDir) {
20
28
  const normalized = filePath.replace(/\\/g, "/").split("?")[0];
@@ -377,6 +385,356 @@ function scanClientBundles(outDir, config) {
377
385
  walk9(resolvedOutDir);
378
386
  return results.sort();
379
387
  }
388
+ var SCRIPT_TAG_REGEX = /<script\b([^>]*)>([\s\S]*?)<\/script>/gi;
389
+ var LINK_TAG_REGEX = /<link\b([^>]*)>/gi;
390
+ var HTML_COMMENT_REGEX = /<!--[\s\S]*?-->/g;
391
+ var ATTR_SRC_REGEX = /\bsrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i;
392
+ var ATTR_HREF_REGEX = /\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i;
393
+ var ATTR_REL_REGEX = /\brel\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i;
394
+ var ATTR_AS_REGEX = /\bas\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i;
395
+ var ATTR_TYPE_REGEX = /\btype\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i;
396
+ var STATIC_FROM_IMPORT_REGEX = /\bfrom\s*(['"`])([^'"`\r\n${}]+)\1/g;
397
+ var SIDE_EFFECT_IMPORT_REGEX = /(?:^|[;}\n])\s*import\s*(['"`])([^'"`\r\n${}]+)\1/g;
398
+ var DYNAMIC_IMPORT_REGEX = /\bimport\s*\(\s*(?:\/\*[^*]{0,120}\*\/\s*)?(['"`])([^'"`\r\n${}]+)\1/g;
399
+ var WORKER_META_URL_REGEX = /\bnew\s+(?:(?:window|self|globalThis)\s*\.\s*)?(?:Shared)?Worker\s*\(\s*new\s+URL\s*\(\s*(['"`])([^'"`\r\n${}]+)\1\s*,\s*import\.meta\.url\s*\)/g;
400
+ var WORKER_DIRECT_URL_REGEX = /\bnew\s+(?:(?:window|self|globalThis)\s*\.\s*)?(?:Shared)?Worker\s*\(\s*(['"`])([^'"`\r\n${}]+)\1/g;
401
+ function getHtmlAttr(attrs, regex) {
402
+ const match = attrs.match(regex);
403
+ if (!match) return void 0;
404
+ return (match[1] ?? match[2] ?? match[3] ?? "").trim();
405
+ }
406
+ function readBoundedText(filePath, maxBytes) {
407
+ let fd;
408
+ try {
409
+ fd = fs.openSync(filePath, "r");
410
+ const stat = fs.fstatSync(fd);
411
+ const toRead = Math.min(stat.size, maxBytes);
412
+ if (toRead <= 0) return "";
413
+ const buf = Buffer.allocUnsafe(toRead);
414
+ let offset = 0;
415
+ while (offset < toRead) {
416
+ const bytesRead = fs.readSync(fd, buf, offset, toRead - offset, offset);
417
+ if (bytesRead <= 0) break;
418
+ offset += bytesRead;
419
+ }
420
+ return buf.subarray(0, offset).toString("utf8");
421
+ } catch {
422
+ return "";
423
+ } finally {
424
+ if (fd !== void 0) {
425
+ try {
426
+ fs.closeSync(fd);
427
+ } catch {
428
+ }
429
+ }
430
+ }
431
+ }
432
+ function buildServerDirPrefixes(config) {
433
+ const prefixes = [];
434
+ if (config?.next?.distDir) {
435
+ prefixes.push(
436
+ path.join(config.next.distDir, "server"),
437
+ path.join(config.next.distDir, "ssr")
438
+ );
439
+ }
440
+ if (config?.vite?.outDir) {
441
+ prefixes.push(path.join(config.vite.outDir, "server"));
442
+ }
443
+ return prefixes;
444
+ }
445
+ function getAllowedExtensions(config) {
446
+ return config?.extensions && config.extensions.length > 0 ? new Set(
447
+ config.extensions.map((e) => e.startsWith(".") ? e.toLowerCase() : `.${e.toLowerCase()}`)
448
+ ) : SUPPORTED_EXTENSIONS;
449
+ }
450
+ function isExcludedPathSegment(fullPath) {
451
+ const normalized = fullPath.replace(/\\/g, "/");
452
+ return normalized.includes("/.git/") || normalized.endsWith("/.git") || normalized.includes("/node_modules/") || normalized.endsWith("/node_modules") || normalized.includes("/.unpeek-maps/") || normalized.endsWith("/.unpeek-maps");
453
+ }
454
+ function resolveOutDirJsTarget(rawSpecifier, baseDir, resolvedOutDir, allowedExtensions, serverDirPrefixes, fallbackRootDir) {
455
+ const trimmed = rawSpecifier.trim();
456
+ if (!trimmed || trimmed.startsWith("#") || /^(?:https?:|data:|blob:|javascript:|mailto:|\/\/)/i.test(trimmed)) {
457
+ return void 0;
458
+ }
459
+ const withoutQuery = trimmed.split("?")[0].split("#")[0];
460
+ let cleanSpec = withoutQuery;
461
+ try {
462
+ cleanSpec = decodeURIComponent(withoutQuery);
463
+ } catch {
464
+ }
465
+ if (!cleanSpec) return void 0;
466
+ const candidates = [];
467
+ if (cleanSpec.startsWith("/")) {
468
+ const stripped = cleanSpec.replace(/^\/+/, "");
469
+ candidates.push(path.resolve(resolvedOutDir, stripped));
470
+ if (fallbackRootDir && fallbackRootDir !== resolvedOutDir) {
471
+ candidates.push(path.resolve(fallbackRootDir, stripped));
472
+ }
473
+ } else {
474
+ candidates.push(path.resolve(baseDir, cleanSpec));
475
+ }
476
+ for (const baseCandidate of candidates) {
477
+ const ext = path.extname(baseCandidate).toLowerCase();
478
+ const withExts = ext ? [baseCandidate] : Array.from(allowedExtensions).map((e) => `${baseCandidate}${e}`);
479
+ for (const candidate of withExts) {
480
+ const candExt = path.extname(candidate).toLowerCase();
481
+ if (!allowedExtensions.has(candExt)) continue;
482
+ if (isExcludedPathSegment(candidate)) continue;
483
+ if (hasNextServerSegment(candidate, resolvedOutDir, serverDirPrefixes)) continue;
484
+ const rel = path.relative(resolvedOutDir, candidate).replace(/\\/g, "/");
485
+ if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) continue;
486
+ try {
487
+ if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {
488
+ return { absPath: candidate, relPath: rel };
489
+ }
490
+ } catch {
491
+ }
492
+ }
493
+ }
494
+ return void 0;
495
+ }
496
+ function extractRelativeSpecifiers(jsText, allowBareRelativeFromRoot) {
497
+ const imports = [];
498
+ const workers = [];
499
+ const collectMatches = (regex, target, requireDotPrefix) => {
500
+ regex.lastIndex = 0;
501
+ let m;
502
+ while ((m = regex.exec(jsText)) !== null) {
503
+ const spec = m[2];
504
+ if (!spec) continue;
505
+ if (spec.startsWith("./") || spec.startsWith("../") || !requireDotPrefix && !/^(?:https?:|data:|blob:)/i.test(spec)) {
506
+ target.push(spec);
507
+ }
508
+ }
509
+ };
510
+ collectMatches(STATIC_FROM_IMPORT_REGEX, imports, true);
511
+ collectMatches(SIDE_EFFECT_IMPORT_REGEX, imports, true);
512
+ collectMatches(DYNAMIC_IMPORT_REGEX, imports, true);
513
+ collectMatches(WORKER_META_URL_REGEX, workers, !allowBareRelativeFromRoot);
514
+ collectMatches(WORKER_DIRECT_URL_REGEX, workers, true);
515
+ return { imports, workers };
516
+ }
517
+ function discoverHtmlEntryGraph(outDir, config, extraHtmlDirs = []) {
518
+ const htmlEntryFiles = /* @__PURE__ */ new Set();
519
+ const preloadedFiles = /* @__PURE__ */ new Set();
520
+ const workerEntryFiles = /* @__PURE__ */ new Set();
521
+ const reachableFiles = /* @__PURE__ */ new Set();
522
+ const emptyResult = () => ({
523
+ htmlEntryFiles,
524
+ preloadedFiles,
525
+ workerEntryFiles,
526
+ reachableFiles,
527
+ entryFiles: /* @__PURE__ */ new Set(),
528
+ scannedHtmlFiles: 0,
529
+ scannedJsFiles: 0
530
+ });
531
+ const resolvedOutDir = path.resolve(outDir);
532
+ if (!fs.existsSync(resolvedOutDir)) {
533
+ return emptyResult();
534
+ }
535
+ const serverDirPrefixes = buildServerDirPrefixes(config);
536
+ const allowedExtensions = getAllowedExtensions(config);
537
+ const htmlFiles = [];
538
+ function walkHtml(currentDir) {
539
+ if (htmlFiles.length >= MAX_HTML_FILES) return;
540
+ if (hasNextServerSegment(currentDir, resolvedOutDir, serverDirPrefixes)) return;
541
+ let entries;
542
+ try {
543
+ entries = fs.readdirSync(currentDir, { withFileTypes: true });
544
+ } catch {
545
+ return;
546
+ }
547
+ entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
548
+ for (const entry of entries) {
549
+ if (htmlFiles.length >= MAX_HTML_FILES) break;
550
+ const fullPath = path.join(currentDir, entry.name);
551
+ if (entry.isDirectory()) {
552
+ if (HTML_WALK_EXCLUDED_DIR_NAMES.has(entry.name.toLowerCase())) continue;
553
+ if (hasNextServerSegment(fullPath, resolvedOutDir, serverDirPrefixes)) continue;
554
+ walkHtml(fullPath);
555
+ } else if (entry.isFile()) {
556
+ if (hasNextServerSegment(fullPath, resolvedOutDir, serverDirPrefixes)) continue;
557
+ if (path.extname(entry.name).toLowerCase() === ".html") {
558
+ htmlFiles.push({ filePath: fullPath, rootDir: resolvedOutDir });
559
+ }
560
+ }
561
+ }
562
+ }
563
+ walkHtml(resolvedOutDir);
564
+ if (htmlFiles.length === 0 && extraHtmlDirs.length > 0) {
565
+ for (const extraDir of extraHtmlDirs) {
566
+ if (htmlFiles.length >= MAX_HTML_FILES) break;
567
+ const resolvedExtra = path.resolve(extraDir);
568
+ if (!fs.existsSync(resolvedExtra) || isExcludedPathSegment(resolvedExtra) || hasNextServerSegment(resolvedExtra, resolvedExtra, serverDirPrefixes)) {
569
+ continue;
570
+ }
571
+ let entries;
572
+ try {
573
+ entries = fs.readdirSync(resolvedExtra, { withFileTypes: true });
574
+ } catch {
575
+ continue;
576
+ }
577
+ entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
578
+ for (const entry of entries) {
579
+ if (htmlFiles.length >= MAX_HTML_FILES) break;
580
+ if (entry.isFile() && path.extname(entry.name).toLowerCase() === ".html") {
581
+ htmlFiles.push({ filePath: path.join(resolvedExtra, entry.name), rootDir: resolvedExtra });
582
+ }
583
+ }
584
+ }
585
+ }
586
+ const jsQueue = [];
587
+ const queuedOrVisitedJs = /* @__PURE__ */ new Set();
588
+ const enqueueJs = (resolved) => {
589
+ if (!resolved) return;
590
+ reachableFiles.add(resolved.relPath);
591
+ if (!queuedOrVisitedJs.has(resolved.relPath) && queuedOrVisitedJs.size < MAX_JS_GRAPH_FILES) {
592
+ queuedOrVisitedJs.add(resolved.relPath);
593
+ jsQueue.push(resolved);
594
+ }
595
+ };
596
+ for (const { filePath: htmlPath, rootDir: htmlRootDir } of htmlFiles) {
597
+ const rawHtml = readBoundedText(htmlPath, MAX_SCAN_BYTES);
598
+ if (!rawHtml) continue;
599
+ const htmlText = rawHtml.replace(HTML_COMMENT_REGEX, "");
600
+ const htmlDir = path.dirname(htmlPath);
601
+ SCRIPT_TAG_REGEX.lastIndex = 0;
602
+ let scriptMatch;
603
+ while ((scriptMatch = SCRIPT_TAG_REGEX.exec(htmlText)) !== null) {
604
+ const attrs = scriptMatch[1] ?? "";
605
+ const body = scriptMatch[2] ?? "";
606
+ const scriptType = (getHtmlAttr(attrs, ATTR_TYPE_REGEX) ?? "").toLowerCase();
607
+ const isJsScript = !scriptType || scriptType === "module" || scriptType.includes("javascript") || scriptType.includes("ecmascript");
608
+ if (!isJsScript) continue;
609
+ const src = getHtmlAttr(attrs, ATTR_SRC_REGEX);
610
+ if (src) {
611
+ const resolved = resolveOutDirJsTarget(
612
+ src,
613
+ htmlDir,
614
+ resolvedOutDir,
615
+ allowedExtensions,
616
+ serverDirPrefixes,
617
+ htmlRootDir
618
+ );
619
+ if (resolved) {
620
+ htmlEntryFiles.add(resolved.relPath);
621
+ enqueueJs(resolved);
622
+ }
623
+ } else if (body.trim()) {
624
+ const { imports, workers } = extractRelativeSpecifiers(body, false);
625
+ for (const imp of imports) {
626
+ const resolved = resolveOutDirJsTarget(
627
+ imp,
628
+ htmlDir,
629
+ resolvedOutDir,
630
+ allowedExtensions,
631
+ serverDirPrefixes,
632
+ htmlRootDir
633
+ );
634
+ if (resolved) {
635
+ htmlEntryFiles.add(resolved.relPath);
636
+ enqueueJs(resolved);
637
+ }
638
+ }
639
+ for (const workerSpec of workers) {
640
+ const resolved = resolveOutDirJsTarget(
641
+ workerSpec,
642
+ htmlDir,
643
+ resolvedOutDir,
644
+ allowedExtensions,
645
+ serverDirPrefixes,
646
+ htmlRootDir
647
+ );
648
+ if (resolved) {
649
+ workerEntryFiles.add(resolved.relPath);
650
+ enqueueJs(resolved);
651
+ }
652
+ }
653
+ }
654
+ }
655
+ LINK_TAG_REGEX.lastIndex = 0;
656
+ let linkMatch;
657
+ while ((linkMatch = LINK_TAG_REGEX.exec(htmlText)) !== null) {
658
+ const attrs = linkMatch[1] ?? "";
659
+ const relAttr = (getHtmlAttr(attrs, ATTR_REL_REGEX) ?? "").toLowerCase();
660
+ if (!relAttr) continue;
661
+ const relTokens = relAttr.split(/\s+/);
662
+ const isModulePreload = relTokens.includes("modulepreload");
663
+ const isPreload = relTokens.includes("preload");
664
+ if (!isModulePreload && !isPreload) continue;
665
+ if (isPreload && !isModulePreload) {
666
+ const asAttr = (getHtmlAttr(attrs, ATTR_AS_REGEX) ?? "").toLowerCase();
667
+ if (asAttr && asAttr !== "script" && asAttr !== "worker") {
668
+ continue;
669
+ }
670
+ }
671
+ const href = getHtmlAttr(attrs, ATTR_HREF_REGEX);
672
+ if (!href) continue;
673
+ const resolved = resolveOutDirJsTarget(
674
+ href,
675
+ htmlDir,
676
+ resolvedOutDir,
677
+ allowedExtensions,
678
+ serverDirPrefixes,
679
+ htmlRootDir
680
+ );
681
+ if (resolved) {
682
+ preloadedFiles.add(resolved.relPath);
683
+ enqueueJs(resolved);
684
+ }
685
+ }
686
+ }
687
+ let scannedJsFiles = 0;
688
+ let head = 0;
689
+ while (head < jsQueue.length && scannedJsFiles < MAX_JS_GRAPH_FILES) {
690
+ const current = jsQueue[head++];
691
+ const jsText = readBoundedText(current.absPath, MAX_SCAN_BYTES);
692
+ scannedJsFiles++;
693
+ if (!jsText) continue;
694
+ const currentDir = path.dirname(current.absPath);
695
+ const { imports, workers } = extractRelativeSpecifiers(jsText, true);
696
+ for (const imp of imports) {
697
+ const resolved = resolveOutDirJsTarget(
698
+ imp,
699
+ currentDir,
700
+ resolvedOutDir,
701
+ allowedExtensions,
702
+ serverDirPrefixes
703
+ );
704
+ if (resolved) {
705
+ enqueueJs(resolved);
706
+ }
707
+ }
708
+ for (const workerSpec of workers) {
709
+ const resolved = resolveOutDirJsTarget(
710
+ workerSpec,
711
+ currentDir,
712
+ resolvedOutDir,
713
+ allowedExtensions,
714
+ serverDirPrefixes
715
+ );
716
+ if (resolved) {
717
+ workerEntryFiles.add(resolved.relPath);
718
+ enqueueJs(resolved);
719
+ }
720
+ }
721
+ }
722
+ const entryFiles = /* @__PURE__ */ new Set([...htmlEntryFiles, ...workerEntryFiles]);
723
+ if (htmlEntryFiles.size === 0 && preloadedFiles.size > 0) {
724
+ for (const preloaded of preloadedFiles) {
725
+ entryFiles.add(preloaded);
726
+ }
727
+ }
728
+ return {
729
+ htmlEntryFiles,
730
+ preloadedFiles,
731
+ workerEntryFiles,
732
+ reachableFiles,
733
+ entryFiles,
734
+ scannedHtmlFiles: htmlFiles.length,
735
+ scannedJsFiles
736
+ };
737
+ }
380
738
 
381
739
  // src/shared/errors.ts
382
740
  var UNPEEK_ERROR_BRAND = /* @__PURE__ */ Symbol.for("unpeek.UnpeekError");
@@ -3844,8 +4202,119 @@ var compactGenerator = Object.assign({}, baseGenerator, {
3844
4202
  this[node.options.type](node.options, state);
3845
4203
  }
3846
4204
  state.write(")");
4205
+ },
4206
+ ImportSpecifier(node, state) {
4207
+ writeModuleBindingName(this, node.imported, state);
4208
+ const sameIdent = node.imported?.type === "Identifier" && node.local?.type === "Identifier" && node.imported.name === node.local.name;
4209
+ if (!sameIdent && node.local?.name) {
4210
+ state.write(" as " + node.local.name);
4211
+ }
4212
+ },
4213
+ ExportSpecifier(node, state) {
4214
+ writeModuleBindingName(this, node.local, state);
4215
+ const sameIdent = node.local?.type === "Identifier" && node.exported?.type === "Identifier" && node.local.name === node.exported.name;
4216
+ if (!sameIdent && node.exported) {
4217
+ state.write(" as ");
4218
+ writeModuleBindingName(this, node.exported, state);
4219
+ }
4220
+ },
4221
+ ImportDeclaration(node, state) {
4222
+ state.write("import ");
4223
+ const specifiers = node.specifiers || [];
4224
+ const len = specifiers.length;
4225
+ let i = 0;
4226
+ if (len > 0) {
4227
+ while (i < len) {
4228
+ if (i > 0) state.write(", ");
4229
+ const spec = specifiers[i];
4230
+ const tag = spec.type[6];
4231
+ if (tag === "D") {
4232
+ state.write(spec.local.name, spec);
4233
+ i++;
4234
+ } else if (tag === "N") {
4235
+ state.write("* as " + spec.local.name, spec);
4236
+ i++;
4237
+ } else {
4238
+ break;
4239
+ }
4240
+ }
4241
+ if (i < len) {
4242
+ state.write("{");
4243
+ for (; ; ) {
4244
+ this.ImportSpecifier(specifiers[i], state);
4245
+ if (++i < len) {
4246
+ state.write(", ");
4247
+ } else {
4248
+ break;
4249
+ }
4250
+ }
4251
+ state.write("}");
4252
+ }
4253
+ state.write(" from ");
4254
+ }
4255
+ this.Literal(node.source, state);
4256
+ writeImportAttributes(this, node.attributes, state);
4257
+ state.write(";");
4258
+ },
4259
+ ExportNamedDeclaration(node, state) {
4260
+ state.write("export ");
4261
+ if (node.declaration) {
4262
+ this[node.declaration.type](node.declaration, state);
4263
+ return;
4264
+ }
4265
+ state.write("{");
4266
+ const specifiers = node.specifiers || [];
4267
+ const len = specifiers.length;
4268
+ if (len > 0) {
4269
+ for (let i = 0; ; ) {
4270
+ this.ExportSpecifier(specifiers[i], state);
4271
+ if (++i < len) {
4272
+ state.write(", ");
4273
+ } else {
4274
+ break;
4275
+ }
4276
+ }
4277
+ }
4278
+ state.write("}");
4279
+ if (node.source) {
4280
+ state.write(" from ");
4281
+ this.Literal(node.source, state);
4282
+ }
4283
+ writeImportAttributes(this, node.attributes, state);
4284
+ state.write(";");
4285
+ },
4286
+ ExportAllDeclaration(node, state) {
4287
+ if (node.exported == null) {
4288
+ state.write("export * from ");
4289
+ } else {
4290
+ state.write("export * as ");
4291
+ writeModuleBindingName(this, node.exported, state);
4292
+ state.write(" from ");
4293
+ }
4294
+ this.Literal(node.source, state);
4295
+ writeImportAttributes(this, node.attributes, state);
4296
+ state.write(";");
3847
4297
  }
3848
4298
  });
4299
+ function writeModuleBindingName(generator, node, state) {
4300
+ if (!node) return;
4301
+ if (node.type === "Literal") {
4302
+ generator.Literal(node, state);
4303
+ } else {
4304
+ state.write(node.name, node);
4305
+ }
4306
+ }
4307
+ function writeImportAttributes(generator, attributes, state) {
4308
+ if (!attributes || attributes.length === 0) return;
4309
+ state.write(" with { ");
4310
+ for (let i = 0; i < attributes.length; i++) {
4311
+ generator.ImportAttribute(attributes[i], state);
4312
+ if (i < attributes.length - 1) {
4313
+ state.write(", ");
4314
+ }
4315
+ }
4316
+ state.write(" }");
4317
+ }
3849
4318
  var VLQ_BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
3850
4319
  function encodeVlq2(value) {
3851
4320
  let vlq = value < 0 ? (-value << 1) + 1 : value << 1;
@@ -4859,7 +5328,8 @@ function injectWasmVault(ast, seed = 2654435769) {
4859
5328
  const mChars = [105 ^ strKey, 109 ^ strKey, 117 ^ strKey, 108 ^ strKey].join(",");
4860
5329
  const helperSnippet = `var ${kdfFnName};
4861
5330
  (function(){
4862
- var _G = typeof globalThis < 'u' ? globalThis : typeof self < 'u' ? self : 0;
5331
+ var _G = typeof globalThis < 'u' ? globalThis : typeof self < 'u' ? self : typeof window < 'u' ? window : 0;
5332
+ var _M = (_G && _G.Math) || Math;
4863
5333
  var _reg = _G ? (_G.__unpeek_wasm_kdf || (_G.__unpeek_wasm_kdf = {})) : 0;
4864
5334
  if (_reg && _reg['${suffix}']) {
4865
5335
  ${kdfFnName} = _reg['${suffix}'];
@@ -4867,10 +5337,10 @@ function injectWasmVault(ast, seed = 2654435769) {
4867
5337
  }
4868
5338
  var _g = [${gArr.join(",")}];
4869
5339
  var _evR = function(x) {
4870
- return (${rA0} + Math.imul(x, (${rA1} + Math.imul(x, (${rA2} + Math.imul(${rA3}, x)) | 0)) | 0)) | 0;
5340
+ return (${rA0} + _M.imul(x, (${rA1} + _M.imul(x, (${rA2} + _M.imul(${rA3}, x)) | 0)) | 0)) | 0;
4871
5341
  };
4872
5342
  var _sb = function(b) {
4873
- return (Math.imul(167, b & 255) + ${sOff}) & 255;
5343
+ return (_M.imul(167, b & 255) + ${sOff}) & 255;
4874
5344
  };
4875
5345
  var _tk = ['__','unp','eek_t','ampered'].join('');
4876
5346
  var _eG = function(sl) {
@@ -4897,7 +5367,7 @@ function injectWasmVault(ast, seed = 2654435769) {
4897
5367
  for (var _i = 0; _i < _c.length; _i++) {
4898
5368
  _p += String.fromCharCode(_c[_i] ^ ${strKey});
4899
5369
  }
4900
- var _m = Math[_p];
5370
+ var _m = _M[_p];
4901
5371
  ${kdfFnName} = function(f, s, h) {
4902
5372
  var _x = (f ^ _k[2] ^ _k[3] ^ (_eG(0) ^ ${gMask})) | 0;
4903
5373
  _x = (_x ^ (_x >>> 16)) | 0;
@@ -5044,6 +5514,61 @@ function unwrapAssignedHostMember(node, matcher, depth = 0) {
5044
5514
  return false;
5045
5515
  }
5046
5516
  }
5517
+ function isImportMetaMember(node, propName) {
5518
+ if (!node || node.type !== "MemberExpression") return false;
5519
+ const obj = node.object;
5520
+ if (obj?.type !== "MetaProperty" || obj.meta?.type !== "Identifier" || obj.meta.name !== "import" || obj.property?.type !== "Identifier" || obj.property.name !== "meta") {
5521
+ return false;
5522
+ }
5523
+ if (!node.computed && node.property?.type === "Identifier") {
5524
+ return node.property.name === propName;
5525
+ }
5526
+ return node.computed && node.property?.type === "Literal" && node.property.value === propName;
5527
+ }
5528
+ function isRequireResolveCallee(callee) {
5529
+ if (!callee || callee.type !== "MemberExpression") return false;
5530
+ if (callee.object?.type !== "Identifier" || callee.object.name !== "require") {
5531
+ return false;
5532
+ }
5533
+ if (!callee.computed && callee.property?.type === "Identifier") {
5534
+ return callee.property.name === "resolve";
5535
+ }
5536
+ return callee.computed && callee.property?.type === "Literal" && callee.property.value === "resolve";
5537
+ }
5538
+ function isStaticModuleOrAssetPosition(node, parent) {
5539
+ if (!node || !parent) return false;
5540
+ if (parent.type === "ImportDeclaration" || parent.type === "ExportNamedDeclaration") {
5541
+ return parent.source === node;
5542
+ }
5543
+ if (parent.type === "ExportAllDeclaration") {
5544
+ return parent.source === node || parent.exported === node;
5545
+ }
5546
+ if (parent.type === "ImportExpression") {
5547
+ return parent.source === node;
5548
+ }
5549
+ if (parent.type === "ImportSpecifier") {
5550
+ return parent.imported === node;
5551
+ }
5552
+ if (parent.type === "ExportSpecifier") {
5553
+ return parent.local === node || parent.exported === node;
5554
+ }
5555
+ if (parent.type === "ImportAttribute") {
5556
+ return true;
5557
+ }
5558
+ if (parent.type === "NewExpression") {
5559
+ return parent.callee?.type === "Identifier" && parent.callee.name === "URL" && Array.isArray(parent.arguments) && parent.arguments.length >= 2 && parent.arguments[0] === node && isImportMetaMember(parent.arguments[1], "url");
5560
+ }
5561
+ if (parent.type === "CallExpression") {
5562
+ if (!Array.isArray(parent.arguments) || parent.arguments[0] !== node) {
5563
+ return false;
5564
+ }
5565
+ const callee = parent.callee;
5566
+ if (isImportMetaMember(callee, "resolve")) return true;
5567
+ if (isRequireResolveCallee(callee)) return true;
5568
+ if (callee?.type === "Identifier" && callee.name === "require") return true;
5569
+ }
5570
+ return false;
5571
+ }
5047
5572
  function classifyChunkBoundary(ast) {
5048
5573
  const exemptSubtreeRoots = /* @__PURE__ */ new WeakSet();
5049
5574
  const importSourceNodes = /* @__PURE__ */ new WeakSet();
@@ -5053,6 +5578,10 @@ function classifyChunkBoundary(ast) {
5053
5578
  let hasPreloadManifest = false;
5054
5579
  walk2.simple(ast, {
5055
5580
  CallExpression(node) {
5581
+ const firstArg = Array.isArray(node.arguments) ? node.arguments[0] : void 0;
5582
+ if (firstArg && (firstArg.type === "Literal" || firstArg.type === "TemplateLiteral") && isStaticModuleOrAssetPosition(firstArg, node)) {
5583
+ exemptSubtreeRoots.add(firstArg);
5584
+ }
5056
5585
  const callee = node.callee;
5057
5586
  const isPushCall = callee?.type === "MemberExpression" && (!callee.computed && callee.property?.type === "Identifier" && callee.property.name === "push" || callee.computed && callee.property?.type === "Literal" && callee.property.value === "push");
5058
5587
  if (isPushCall) {
@@ -5116,6 +5645,49 @@ function classifyChunkBoundary(ast) {
5116
5645
  exemptSubtreeRoots.add(node);
5117
5646
  }
5118
5647
  },
5648
+ NewExpression(node) {
5649
+ const firstArg = Array.isArray(node.arguments) ? node.arguments[0] : void 0;
5650
+ if (firstArg && (firstArg.type === "Literal" || firstArg.type === "TemplateLiteral") && isStaticModuleOrAssetPosition(firstArg, node)) {
5651
+ exemptSubtreeRoots.add(firstArg);
5652
+ }
5653
+ },
5654
+ ImportDeclaration(node) {
5655
+ if (node.source && typeof node.source === "object") {
5656
+ exemptSubtreeRoots.add(node.source);
5657
+ }
5658
+ if (Array.isArray(node.specifiers)) {
5659
+ for (const spec of node.specifiers) {
5660
+ if (spec?.type === "ImportSpecifier" && spec.imported?.type === "Literal") {
5661
+ exemptSubtreeRoots.add(spec.imported);
5662
+ }
5663
+ }
5664
+ }
5665
+ },
5666
+ ExportNamedDeclaration(node) {
5667
+ if (node.source && typeof node.source === "object") {
5668
+ exemptSubtreeRoots.add(node.source);
5669
+ }
5670
+ if (Array.isArray(node.specifiers)) {
5671
+ for (const spec of node.specifiers) {
5672
+ if (spec?.type === "ExportSpecifier") {
5673
+ if (spec.local?.type === "Literal") {
5674
+ exemptSubtreeRoots.add(spec.local);
5675
+ }
5676
+ if (spec.exported?.type === "Literal") {
5677
+ exemptSubtreeRoots.add(spec.exported);
5678
+ }
5679
+ }
5680
+ }
5681
+ }
5682
+ },
5683
+ ExportAllDeclaration(node) {
5684
+ if (node.source && typeof node.source === "object") {
5685
+ exemptSubtreeRoots.add(node.source);
5686
+ }
5687
+ if (node.exported && typeof node.exported === "object") {
5688
+ exemptSubtreeRoots.add(node.exported);
5689
+ }
5690
+ },
5119
5691
  ImportExpression(node) {
5120
5692
  importExpressions.push(node);
5121
5693
  if (node.source && typeof node.source === "object") {
@@ -5185,22 +5757,36 @@ function buildRivestDeltaExpr(seed, expectedDelta, varName = "_ed") {
5185
5757
  const xMasked = xEnc ^ xMask | 0;
5186
5758
  return `var _rx=(${xMasked}^${xMask | 0})|0,${varName}=(${rA0}+Math.imul(_rx,(${rA1}+Math.imul(_rx,(${rA2}+Math.imul(${rA3},_rx))|0))|0))&65535;`;
5187
5759
  }
5188
- function createSaltedDecryptorFnAst(seed, pChars, expectedDelta, windowKeySymbol, safeAlpha = SAFE_ALPHA, shieldCoupled = true, _browserOnly = false) {
5760
+ function buildLatchInitSnippet(seed, latchCoupling) {
5761
+ if (!latchCoupling || typeof latchCoupling.latchFnName !== "string" || !/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(latchCoupling.latchFnName)) {
5762
+ return { hasLatch: false, latchDecl: "" };
5763
+ }
5764
+ const tamperByte = seed >>> 8 & 127 | 53;
5765
+ const expectedLatch = latchCoupling.expectedLatchByte & 255;
5766
+ return {
5767
+ hasLatch: true,
5768
+ latchDecl: `var _ld=typeof ${latchCoupling.latchFnName}==="function"?((${latchCoupling.latchFnName}()^${expectedLatch})&255):${tamperByte};`
5769
+ };
5770
+ }
5771
+ function createSaltedDecryptorFnAst(seed, pChars, expectedDelta, windowKeySymbol, safeAlpha = SAFE_ALPHA, shieldCoupled = true, _browserOnly = false, latchCoupling) {
5189
5772
  const propAccess = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(windowKeySymbol) ? `.${windowKeySymbol}` : `[${JSON.stringify(windowKeySymbol)}]`;
5190
5773
  const stateSym = `${windowKeySymbol}_s`;
5191
5774
  const stateAccess = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(stateSym) ? `.${stateSym}` : `[${JSON.stringify(stateSym)}]`;
5192
5775
  const flagSym = `${windowKeySymbol}_t`;
5193
5776
  const flagAccess = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(flagSym) ? `.${flagSym}` : `[${JSON.stringify(flagSym)}]`;
5194
5777
  const tkExpr = `['__','unp','eek_t','ampered'].join('')`;
5778
+ const { hasLatch, latchDecl } = buildLatchInitSnippet(seed, latchCoupling);
5779
+ const charEmit = hasLatch ? `o+=String.fromCharCode((k<0?ch:A[(A.indexOf(P[(k-(t&65535)%92+92)%92])-(t>>>16)%92+92)%92]).charCodeAt(0)^_ld);` : `o+=k<0?ch:A[(A.indexOf(P[(k-(t&65535)%92+92)%92])-(t>>>16)%92+92)%92];`;
5780
+ const cacheGuardSuffix = hasLatch ? "&&!_ld" : "";
5195
5781
  let fBody;
5196
5782
  if (!shieldCoupled) {
5197
- 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;};`;
5783
+ 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];` + latchDecl + `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);` + charEmit + `}if(!tm${cacheGuardSuffix})m[i]=o;return o;};`;
5198
5784
  } else {
5199
5785
  const edInit = buildRivestDeltaExpr(seed, expectedDelta, "_ed");
5200
5786
  const hasWindowKey = Boolean(windowKeySymbol);
5201
5787
  const brDecl = hasWindowKey ? NARROWED_ASYNC_BR_DECL : "";
5202
5788
  const svCheck = hasWindowKey ? `(sv===void 0?!_br:sv!==_ed)` : `(sv!==void 0&&sv!==_ed)`;
5203
- 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;};`;
5789
+ 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];` + latchDecl + `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);` + charEmit + `}if(!tm&&sv===_ed${cacheGuardSuffix})m[i]=o;return o;};`;
5204
5790
  }
5205
5791
  return acorn3.parse(`(function f(a){${fBody}})`, {
5206
5792
  ecmaVersion: "latest",
@@ -5274,7 +5860,7 @@ function replaceNodeInParent(parent, oldNode, newNode) {
5274
5860
  }
5275
5861
  return false;
5276
5862
  }
5277
- function applySaltedStringVault(ast, seed = 2654435769, minStringLength = 4, hotExemptNodes, config, windowKeySymbol, expectedDelta, deterrentMode, shieldCoupled = true, detectHeadless = false, exemptSubtreeRoots) {
5863
+ function applySaltedStringVault(ast, seed = 2654435769, minStringLength = 4, hotExemptNodes, config, windowKeySymbol, expectedDelta, deterrentMode, shieldCoupled = true, detectHeadless = false, exemptSubtreeRoots, latchCoupling) {
5278
5864
  if (isAstAlreadySalted(ast)) {
5279
5865
  return {
5280
5866
  encryptedStringsCount: 0,
@@ -5374,86 +5960,89 @@ function applySaltedStringVault(ast, seed = 2654435769, minStringLength = 4, hot
5374
5960
  pushSaltedTarget(val, node, parent, onReplace ? { onReplace } : void 0);
5375
5961
  return true;
5376
5962
  }
5377
- walk3.ancestor(ast, {
5378
- Literal(node, ancestors) {
5379
- if (node.regex) {
5380
- if (isEligibleSecretRegExp(
5381
- node,
5382
- ancestors,
5383
- hotExemptNodes,
5384
- exemptSubtreeRoots,
5385
- getRegExpShadowedScopes
5386
- )) {
5387
- pushSaltedTarget(
5388
- node.regex.pattern,
5963
+ walk3.ancestor(
5964
+ ast,
5965
+ {
5966
+ Literal(node, _state, ancestors) {
5967
+ if (node.regex) {
5968
+ if (isEligibleSecretRegExp(
5389
5969
  node,
5390
- ancestors[ancestors.length - 2],
5391
- {
5392
- replaceMode: "regexp",
5393
- flags: node.regex.flags ?? ""
5970
+ ancestors,
5971
+ hotExemptNodes,
5972
+ exemptSubtreeRoots,
5973
+ getRegExpShadowedScopes
5974
+ )) {
5975
+ pushSaltedTarget(
5976
+ node.regex.pattern,
5977
+ node,
5978
+ ancestors[ancestors.length - 2],
5979
+ {
5980
+ replaceMode: "regexp",
5981
+ flags: node.regex.flags ?? ""
5982
+ }
5983
+ );
5984
+ }
5985
+ return;
5986
+ }
5987
+ if (typeof node.value !== "string") return;
5988
+ const val = node.value;
5989
+ if (activeDirectives.has(val)) return;
5990
+ const parent = ancestors[ancestors.length - 2];
5991
+ if (!parent) return;
5992
+ if (isStaticModuleOrAssetPosition(node, parent)) {
5993
+ return;
5994
+ }
5995
+ if (parent.type === "Property" && parent.key === node && !parent.computed) {
5996
+ if (!isEligibleObjectPropertyKey(val, node, parent, ancestors)) {
5997
+ return;
5998
+ }
5999
+ }
6000
+ if ((parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") && parent.key === node && !parent.computed) {
6001
+ return;
6002
+ }
6003
+ processSaltedCandidate(val, node, parent, ancestors);
6004
+ },
6005
+ TemplateLiteral(node, _state, ancestors) {
6006
+ if (!Array.isArray(node.quasis) || node.quasis.length === 0) return;
6007
+ const parent = ancestors[ancestors.length - 2];
6008
+ if (isExemptTemplateLiteral(node, parent)) return;
6009
+ const exprCount = Array.isArray(node.expressions) ? node.expressions.length : 0;
6010
+ if (exprCount === 0) {
6011
+ if (node.quasis.length !== 1) return;
6012
+ const val = node.quasis[0].value.cooked ?? node.quasis[0].value.raw;
6013
+ if (typeof val !== "string" || activeDirectives.has(val)) return;
6014
+ processSaltedCandidate(val, node, parent, ancestors);
6015
+ return;
6016
+ }
6017
+ if (node.quasis.length !== exprCount + 1) return;
6018
+ if (node.quasis.some((q) => typeof q?.value?.cooked !== "string")) {
6019
+ return;
6020
+ }
6021
+ const replacements = /* @__PURE__ */ new Map();
6022
+ let queuedCount = 0;
6023
+ for (let qIdx = 0; qIdx < node.quasis.length; qIdx++) {
6024
+ const val = node.quasis[qIdx].value.cooked;
6025
+ if (activeDirectives.has(val)) continue;
6026
+ const queued = processSaltedCandidate(
6027
+ val,
6028
+ node,
6029
+ parent,
6030
+ ancestors,
6031
+ (exprAst) => {
6032
+ replacements.set(qIdx, exprAst);
5394
6033
  }
5395
6034
  );
6035
+ if (queued) {
6036
+ queuedCount++;
6037
+ }
6038
+ }
6039
+ if (queuedCount > 0) {
6040
+ interpolatedTemplates.push({ node, replacements });
5396
6041
  }
5397
- return;
5398
6042
  }
5399
- if (typeof node.value !== "string") return;
5400
- const val = node.value;
5401
- if (activeDirectives.has(val)) return;
5402
- const parent = ancestors[ancestors.length - 2];
5403
- if (!parent) return;
5404
- if ((parent.type === "ImportDeclaration" || parent.type === "ExportNamedDeclaration" || parent.type === "ExportAllDeclaration" || parent.type === "ImportExpression") && parent.source === node) {
5405
- return;
5406
- }
5407
- if (parent.type === "Property" && parent.key === node && !parent.computed) {
5408
- return;
5409
- }
5410
- if ((parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") && parent.key === node && !parent.computed) {
5411
- return;
5412
- }
5413
- if (parent.type === "ImportAttribute" || parent.type === "ImportSpecifier" || parent.type === "ExportSpecifier") {
5414
- return;
5415
- }
5416
- processSaltedCandidate(val, node, parent, ancestors);
5417
6043
  },
5418
- TemplateLiteral(node, ancestors) {
5419
- if (!Array.isArray(node.quasis) || node.quasis.length === 0) return;
5420
- const parent = ancestors[ancestors.length - 2];
5421
- if (isExemptTemplateLiteral(node, parent)) return;
5422
- const exprCount = Array.isArray(node.expressions) ? node.expressions.length : 0;
5423
- if (exprCount === 0) {
5424
- if (node.quasis.length !== 1) return;
5425
- const val = node.quasis[0].value.cooked ?? node.quasis[0].value.raw;
5426
- if (typeof val !== "string" || activeDirectives.has(val)) return;
5427
- processSaltedCandidate(val, node, parent, ancestors);
5428
- return;
5429
- }
5430
- if (node.quasis.length !== exprCount + 1) return;
5431
- if (node.quasis.some((q) => typeof q?.value?.cooked !== "string")) {
5432
- return;
5433
- }
5434
- const replacements = /* @__PURE__ */ new Map();
5435
- let queuedCount = 0;
5436
- for (let qIdx = 0; qIdx < node.quasis.length; qIdx++) {
5437
- const val = node.quasis[qIdx].value.cooked;
5438
- if (activeDirectives.has(val)) continue;
5439
- const queued = processSaltedCandidate(
5440
- val,
5441
- node,
5442
- parent,
5443
- ancestors,
5444
- (exprAst) => {
5445
- replacements.set(qIdx, exprAst);
5446
- }
5447
- );
5448
- if (queued) {
5449
- queuedCount++;
5450
- }
5451
- }
5452
- if (queuedCount > 0) {
5453
- interpolatedTemplates.push({ node, replacements });
5454
- }
5455
- }
5456
- });
6044
+ VAULT_WALK_BASE
6045
+ );
5457
6046
  if (targetsToReplace.length === 0 && shaderTargets.length === 0) {
5458
6047
  return {
5459
6048
  encryptedStringsCount: 0,
@@ -5492,15 +6081,18 @@ function applySaltedStringVault(ast, seed = 2654435769, minStringLength = 4, hot
5492
6081
  const flagAccess = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(flagSym) ? `.${flagSym}` : `[${JSON.stringify(flagSym)}]`;
5493
6082
  const tkExpr = `['__','unp','eek_t','ampered'].join('')`;
5494
6083
  const dkExpr = `['__','unp','eek_d','elta'].join('')`;
6084
+ const { hasLatch, latchDecl } = buildLatchInitSnippet(seed, latchCoupling);
6085
+ const charMaskXor = hasLatch ? "^_ld" : "";
6086
+ const cacheGuardSuffix = hasLatch ? "&&!_ld" : "";
5495
6087
  let helperFnSnippet;
5496
6088
  if (!shieldCoupled) {
5497
- 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;}`;
6089
+ 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];` + latchDecl + `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)${charMaskXor});}if(!tm${cacheGuardSuffix})${cacheVarName}[i]=o;return o;}`;
5498
6090
  } else {
5499
6091
  const edInit = buildRivestDeltaExpr(seed, (expDelta ?? 0) & 65535, "_ed");
5500
6092
  const hasWindowKey = Boolean(sym);
5501
6093
  const brDecl = hasWindowKey ? NARROWED_ASYNC_BR_DECL : "";
5502
6094
  const svCheck = hasWindowKey ? `(sv===void 0?!_br:sv!==_ed)` : `(sv!==void 0&&sv!==_ed)`;
5503
- 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;}`;
6095
+ 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];` + latchDecl + `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)${charMaskXor});}if(!tm&&sv===_ed${cacheGuardSuffix})${cacheVarName}[i]=o;return o;}`;
5504
6096
  }
5505
6097
  const parsedFn = acorn3.parse(helperFnSnippet, {
5506
6098
  ecmaVersion: "latest",
@@ -5541,6 +6133,9 @@ function applySaltedStringVault(ast, seed = 2654435769, minStringLength = 4, hot
5541
6133
  createNewRegExpAst(callExpr, target.flags ?? "")
5542
6134
  );
5543
6135
  } else {
6136
+ if (target.parent?.type === "Property" && target.parent.key === target.node) {
6137
+ target.parent.computed = true;
6138
+ }
5544
6139
  replaceNodeInParent(target.parent, target.node, callExpr);
5545
6140
  }
5546
6141
  }
@@ -5913,13 +6508,10 @@ function isEligibleHotLiteral(val, node, parent, ancestors, minLen, seed = 26544
5913
6508
  return false;
5914
6509
  }
5915
6510
  if (parent) {
5916
- if (parent.type === "ImportDeclaration" || parent.type === "ExportNamedDeclaration" || parent.type === "ExportAllDeclaration" || parent.type === "ImportExpression") {
5917
- if (parent.source === node) return false;
5918
- }
5919
- if ((parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") && parent.key === node && !parent.computed) {
6511
+ if (isStaticModuleOrAssetPosition(node, parent)) {
5920
6512
  return false;
5921
6513
  }
5922
- if (parent.type === "ImportAttribute" || parent.type === "ImportSpecifier" || parent.type === "ExportSpecifier") {
6514
+ if ((parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") && parent.key === node && !parent.computed) {
5923
6515
  return false;
5924
6516
  }
5925
6517
  }
@@ -5982,6 +6574,68 @@ function shouldEncryptString(val, minLen, parent, activeDirectives = DIRECTIVE_S
5982
6574
  if (isTailwindNoise(val)) return false;
5983
6575
  return true;
5984
6576
  }
6577
+ var VAULT_WALK_BASE = {
6578
+ ...walk4.base,
6579
+ Property(node, st, c) {
6580
+ c(node.key, st);
6581
+ if (node.value) c(node.value, st);
6582
+ }
6583
+ };
6584
+ function isCjsExportsTarget(lhs) {
6585
+ if (!lhs || typeof lhs !== "object") return false;
6586
+ if (lhs.type === "ParenthesizedExpression") {
6587
+ return isCjsExportsTarget(lhs.expression);
6588
+ }
6589
+ if (lhs.type === "Identifier") {
6590
+ return lhs.name === "exports";
6591
+ }
6592
+ if (lhs.type === "MemberExpression") {
6593
+ if (lhs.object?.type === "Identifier" && lhs.object.name === "module" && (!lhs.computed && lhs.property?.type === "Identifier" && lhs.property.name === "exports" || lhs.computed && lhs.property?.type === "Literal" && lhs.property.value === "exports")) {
6594
+ return true;
6595
+ }
6596
+ return isCjsExportsTarget(lhs.object);
6597
+ }
6598
+ return false;
6599
+ }
6600
+ function isInsideCjsExportsObject(ancestors, objIdx) {
6601
+ if (objIdx < 1) return false;
6602
+ let cur = ancestors[objIdx];
6603
+ for (let i = objIdx - 1; i >= 0; i--) {
6604
+ const anc = ancestors[i];
6605
+ if (!anc) break;
6606
+ if (anc.type === "ParenthesizedExpression") {
6607
+ cur = anc;
6608
+ continue;
6609
+ }
6610
+ if (anc.type === "AssignmentExpression" && anc.right === cur) {
6611
+ if (isCjsExportsTarget(anc.left)) {
6612
+ return true;
6613
+ }
6614
+ cur = anc;
6615
+ continue;
6616
+ }
6617
+ if (anc.type === "CallExpression" && anc.callee?.type === "MemberExpression" && !anc.callee.computed && anc.callee.object?.type === "Identifier" && anc.callee.object.name === "Object" && anc.callee.property?.type === "Identifier" && anc.callee.property.name === "assign" && Array.isArray(anc.arguments) && anc.arguments.slice(1).includes(cur) && isCjsExportsTarget(anc.arguments[0])) {
6618
+ return true;
6619
+ }
6620
+ break;
6621
+ }
6622
+ return false;
6623
+ }
6624
+ function isEligibleObjectPropertyKey(val, node, parent, ancestors) {
6625
+ if (!parent || parent.type !== "Property" || parent.key !== node || parent.computed) {
6626
+ return false;
6627
+ }
6628
+ if (val === "__proto__") return false;
6629
+ if (parent.kind !== "init" || parent.shorthand) return false;
6630
+ if (!isLikelySecretLiteral(val)) return false;
6631
+ const containerIdx = ancestors.length - 3;
6632
+ const container = containerIdx >= 0 ? ancestors[containerIdx] : void 0;
6633
+ if (!container || container.type === "ObjectPattern") return false;
6634
+ if (container.type === "ObjectExpression" && isInsideCjsExportsObject(ancestors, containerIdx)) {
6635
+ return false;
6636
+ }
6637
+ return true;
6638
+ }
5985
6639
  function createPermutationTable(seed) {
5986
6640
  let s = (seed || 305419896) >>> 0;
5987
6641
  function xorshift() {
@@ -6121,7 +6775,7 @@ function isExemptTemplateLiteral(node, parent) {
6121
6775
  if (parent.type === "TaggedTemplateExpression" && parent.quasi === node) {
6122
6776
  return true;
6123
6777
  }
6124
- if (parent.type === "ImportExpression" && parent.source === node) {
6778
+ if (isStaticModuleOrAssetPosition(node, parent)) {
6125
6779
  return true;
6126
6780
  }
6127
6781
  return false;
@@ -6332,7 +6986,7 @@ function isEligibleSecretRegExp(node, ancestors, hotExemptNodes, exemptSubtreeRo
6332
6986
  }
6333
6987
  return true;
6334
6988
  }
6335
- function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExemptNodes, windowKeySymbol, expectedDelta, deterrentMode, config, shieldCoupled = true, detectHeadless = false, exemptSubtreeRoots) {
6989
+ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExemptNodes, windowKeySymbol, expectedDelta, deterrentMode, config, shieldCoupled = true, detectHeadless = false, exemptSubtreeRoots, latchCoupling) {
6336
6990
  const minLen = config?.vault?.minStringLength ?? minStringLength;
6337
6991
  const activeDirectives = new Set(DIRECTIVE_STRINGS);
6338
6992
  if (config?.vault?.customDirectives) {
@@ -6381,7 +7035,8 @@ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExempt
6381
7035
  sym,
6382
7036
  SAFE_ALPHA,
6383
7037
  shieldCoupled,
6384
- browserOnly
7038
+ browserOnly,
7039
+ latchCoupling
6385
7040
  );
6386
7041
  const compactFnStr = generateCompactJs(fnAst);
6387
7042
  const buildH = computeIntegrityHash(compactFnStr, 0);
@@ -6399,13 +7054,6 @@ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExempt
6399
7054
  regExpShadowedScopes ??= collectIdentifierShadowedScopes(ast, "RegExp");
6400
7055
  return regExpShadowedScopes;
6401
7056
  };
6402
- const customWalkBase = {
6403
- ...walk4.base,
6404
- Property(node, st, c) {
6405
- c(node.key, st);
6406
- if (node.value) c(node.value, st);
6407
- }
6408
- };
6409
7057
  function processVaultCandidate(val, node, parent, ancestors, onReplace) {
6410
7058
  if (isNodeInExemptSubtree(ancestors, exemptSubtreeRoots)) {
6411
7059
  return false;
@@ -6539,14 +7187,16 @@ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExempt
6539
7187
  if (activeDirectives.has(val)) return;
6540
7188
  const parent = ancestors[ancestors.length - 2];
6541
7189
  if (!parent) return;
6542
- if (parent.type === "ImportDeclaration" || parent.type === "ExportNamedDeclaration" || parent.type === "ExportAllDeclaration" || parent.type === "ImportExpression") {
6543
- if (parent.source === node) return;
7190
+ if (isStaticModuleOrAssetPosition(node, parent)) {
7191
+ return;
6544
7192
  }
6545
7193
  if ((parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") && parent.key === node && !parent.computed) {
6546
7194
  return;
6547
7195
  }
6548
- if (parent.type === "ImportAttribute" || parent.type === "ImportSpecifier" || parent.type === "ExportSpecifier") {
6549
- return;
7196
+ if (parent.type === "Property" && parent.key === node && !parent.computed) {
7197
+ if (!isEligibleObjectPropertyKey(val, node, parent, ancestors)) {
7198
+ return;
7199
+ }
6550
7200
  }
6551
7201
  processVaultCandidate(val, node, parent, ancestors);
6552
7202
  },
@@ -6589,7 +7239,7 @@ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExempt
6589
7239
  }
6590
7240
  }
6591
7241
  },
6592
- customWalkBase
7242
+ VAULT_WALK_BASE
6593
7243
  );
6594
7244
  if (targetsToReplace.length === 0 && hotTargetsToReplace.length === 0) {
6595
7245
  return {
@@ -6741,7 +7391,8 @@ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExempt
6741
7391
  sym,
6742
7392
  SAFE_ALPHA,
6743
7393
  shieldCoupled,
6744
- browserOnly
7394
+ browserOnly,
7395
+ latchCoupling
6745
7396
  );
6746
7397
  const buildHF = computeIntegrityHash(generateCompactJs(fnAstF), 0);
6747
7398
  const expectedKeyF = (buildHF ^ 0 ^ (shieldCoupled ? (expDelta ?? 0) & 65535 : 0)) >>> 0;
@@ -7035,14 +7686,55 @@ function applyPolymorphicMangler(ast, seed = 2654435769, serializedFunctionNodes
7035
7686
  }
7036
7687
  const manglerConfig = config?.mangler;
7037
7688
  const scopeRecords = /* @__PURE__ */ new Map();
7689
+ const protectedScopeNodes = /* @__PURE__ */ new Set();
7038
7690
  const barrierOrFreeIds = /* @__PURE__ */ new Set();
7039
7691
  const renamedTargetNodes = /* @__PURE__ */ new WeakSet();
7040
7692
  let counter = 0;
7693
+ function hasStrictDirective(stmts) {
7694
+ if (!Array.isArray(stmts)) return false;
7695
+ for (const stmt of stmts) {
7696
+ if (stmt?.type !== "ExpressionStatement") break;
7697
+ const isStrLit = stmt.expression?.type === "Literal" && typeof stmt.expression.value === "string";
7698
+ if (!stmt.directive && !isStrLit) break;
7699
+ if (stmt.directive === "use strict" || stmt.expression?.value === "use strict") {
7700
+ return true;
7701
+ }
7702
+ }
7703
+ return false;
7704
+ }
7705
+ function isSloppyFunctionNode(fnNode, ancestors) {
7706
+ if (fnNode.type === "ArrowFunctionExpression") return false;
7707
+ if (ast.sourceType === "module") return false;
7708
+ const parent = ancestors.length >= 2 ? ancestors[ancestors.length - 2] : null;
7709
+ if (parent && (parent.type === "MethodDefinition" || parent.type === "Property" && (parent.method || parent.kind === "get" || parent.kind === "set"))) {
7710
+ return false;
7711
+ }
7712
+ for (let i = 0; i < ancestors.length - 1; i++) {
7713
+ const anc = ancestors[i];
7714
+ if (anc.type === "ClassDeclaration" || anc.type === "ClassExpression") {
7715
+ return false;
7716
+ }
7717
+ if (anc.type === "Program" && hasStrictDirective(anc.body)) {
7718
+ return false;
7719
+ }
7720
+ if (FUNCTION_TYPES.has(anc.type) && anc.body?.type === "BlockStatement" && hasStrictDirective(anc.body.body)) {
7721
+ return false;
7722
+ }
7723
+ }
7724
+ if (fnNode.body?.type === "BlockStatement" && hasStrictDirective(fnNode.body.body)) {
7725
+ return false;
7726
+ }
7727
+ return true;
7728
+ }
7041
7729
  function ensureScopeChain(ancestors) {
7730
+ const insideWith = ancestors.some((a) => a.type === "WithStatement");
7042
7731
  let prevScope = null;
7043
7732
  for (let i = 0; i < ancestors.length; i++) {
7044
7733
  const node = ancestors[i];
7045
7734
  if (!LEXICAL_SCOPE_TYPES.has(node.type)) continue;
7735
+ if (insideWith) {
7736
+ protectedScopeNodes.add(node);
7737
+ }
7046
7738
  let record = scopeRecords.get(node);
7047
7739
  if (!record) {
7048
7740
  const isFn = FUNCTION_TYPES.has(node.type);
@@ -7129,16 +7821,45 @@ function applyPolymorphicMangler(ast, seed = 2654435769, serializedFunctionNodes
7129
7821
  }
7130
7822
  function registerFunctionParams(fnNode, ancestors) {
7131
7823
  ensureScopeChain(ancestors);
7132
- for (const param of fnNode.params || []) {
7824
+ const params = fnNode.params || [];
7825
+ const duplicateParamNames = /* @__PURE__ */ new Set();
7826
+ const allSimpleParams = params.every((p) => p?.type === "Identifier");
7827
+ if (allSimpleParams && params.length > 1 && isSloppyFunctionNode(fnNode, ancestors)) {
7828
+ const seen = /* @__PURE__ */ new Set();
7829
+ for (const p of params) {
7830
+ if (seen.has(p.name)) {
7831
+ duplicateParamNames.add(p.name);
7832
+ }
7833
+ seen.add(p.name);
7834
+ }
7835
+ }
7836
+ for (const param of params) {
7133
7837
  const targets = [];
7134
7838
  collectPatternTargets(param, targets);
7135
7839
  for (const target of targets) {
7136
- registerBindingTarget(fnNode, target, true, fnNode);
7840
+ const allowMangle = !duplicateParamNames.has(target.idNode.name);
7841
+ registerBindingTarget(fnNode, target, allowMangle, fnNode);
7137
7842
  }
7138
7843
  }
7139
7844
  }
7140
7845
  ensureScopeChain([ast]);
7141
7846
  walk5.ancestor(ast, {
7847
+ CallExpression(node, _state, ancestors) {
7848
+ if (!node.optional && node.callee?.type === "Identifier" && node.callee.name === "eval") {
7849
+ for (const anc of ancestors) {
7850
+ if (LEXICAL_SCOPE_TYPES.has(anc.type)) {
7851
+ protectedScopeNodes.add(anc);
7852
+ }
7853
+ }
7854
+ }
7855
+ },
7856
+ WithStatement(_node, _state, ancestors) {
7857
+ for (const anc of ancestors) {
7858
+ if (LEXICAL_SCOPE_TYPES.has(anc.type)) {
7859
+ protectedScopeNodes.add(anc);
7860
+ }
7861
+ }
7862
+ },
7142
7863
  BlockStatement(_node, _state, ancestors) {
7143
7864
  ensureScopeChain(ancestors);
7144
7865
  },
@@ -7251,6 +7972,14 @@ function applyPolymorphicMangler(ast, seed = 2654435769, serializedFunctionNodes
7251
7972
  }
7252
7973
  }
7253
7974
  });
7975
+ for (const scopeNode of protectedScopeNodes) {
7976
+ const scope = scopeRecords.get(scopeNode);
7977
+ if (!scope) continue;
7978
+ for (const entry of scope.bindings.values()) {
7979
+ entry.shouldMangle = false;
7980
+ barrierOrFreeIds.add(entry.origName);
7981
+ }
7982
+ }
7254
7983
  function resolveBinding(name, ancestors) {
7255
7984
  for (let i = ancestors.length - 1; i >= 0; i--) {
7256
7985
  const scope = scopeRecords.get(ancestors[i]);
@@ -7417,6 +8146,35 @@ function applyPolymorphicMangler(ast, seed = 2654435769, serializedFunctionNodes
7417
8146
  // src/ast/cold-flow-guard.ts
7418
8147
  import * as acorn5 from "acorn";
7419
8148
  import * as walk6 from "acorn-walk";
8149
+ function deriveColdFlowSuffix(seed) {
8150
+ return (seed >>> 0).toString(36).slice(0, 4);
8151
+ }
8152
+ function deriveColdAliasInitWords(seed) {
8153
+ const words = [
8154
+ mixSeed32(seed, 101),
8155
+ mixSeed32(seed, 103),
8156
+ mixSeed32(seed, 107),
8157
+ mixSeed32(seed, 109),
8158
+ mixSeed32(seed, 113),
8159
+ mixSeed32(seed, 127),
8160
+ mixSeed32(seed, 131),
8161
+ mixSeed32(seed, 137)
8162
+ ];
8163
+ const latchByte = (words[0] ^ words[1]) & 255;
8164
+ if (latchByte === 0 || latchByte === 255) {
8165
+ words[1] = words[1] ^ 90 | 0;
8166
+ }
8167
+ return words;
8168
+ }
8169
+ function deriveColdLatchCoupling(seed) {
8170
+ const sfx = deriveColdFlowSuffix(seed);
8171
+ const initWords = deriveColdAliasInitWords(seed);
8172
+ const expectedLatchByte = (initWords[0] ^ initWords[1]) & 255;
8173
+ return {
8174
+ latchFnName: `_uLr${sfx}`,
8175
+ expectedLatchByte
8176
+ };
8177
+ }
7420
8178
  var NEUTRAL_DECOY_KEYS = [
7421
8179
  "telemetryOk",
7422
8180
  "retryBudget",
@@ -8007,6 +8765,14 @@ function makePropAccess(objExpr, propName) {
8007
8765
  property: makeLiteral(propName)
8008
8766
  };
8009
8767
  }
8768
+ function makeSafeAliasRead(aliasIdent, slot) {
8769
+ return {
8770
+ type: "ConditionalExpression",
8771
+ test: makeBinary("<", makeUnary("typeof", { type: "Identifier", name: aliasIdent }), makeLiteral("u")),
8772
+ consequent: makeMemberIndex(aliasIdent, makeLiteral(slot)),
8773
+ alternate: makeLiteral(0)
8774
+ };
8775
+ }
8010
8776
  function buildQnrBitExpr(qnrValRef, bitKind) {
8011
8777
  const shiftAmt = bitKind === "xor1" ? 1 : 2;
8012
8778
  const combOp = bitKind === "xor1" ? "^" : "|";
@@ -8026,8 +8792,8 @@ function createSotaMbaPredicate(seed, fnIndex = 0, paramNode, decoyIdent, isArro
8026
8792
  const mba4 = buildMba4Ast(seed, fnIndex, x1, x2, x3, x4);
8027
8793
  const qnrFamilyIdx = ((seed ^ Math.imul(fnIndex + 1, 2654435761)) >>> 0) % QNR_RESIDUE_FAMILIES.length;
8028
8794
  const qnrFamily = QNR_RESIDUE_FAMILIES[qnrFamilyIdx];
8029
- const slotA = fnIndex + (seed & 3) & 3;
8030
- const slotB = slotA + 1 + (seed >>> 2 & 1) & 3;
8795
+ const slotA = 2 + (fnIndex + (seed & 1) & 1);
8796
+ const slotB = slotA ^ 1;
8031
8797
  const hasAlias = Boolean(ctxOpts?.aliasIdentA);
8032
8798
  const aliasReadIdent = ctxOpts?.aliasIdentB ?? ctxOpts?.aliasIdentA ?? "";
8033
8799
  let qnrLeft;
@@ -8220,7 +8986,7 @@ function createSotaMbaPredicate(seed, fnIndex = 0, paramNode, decoyIdent, isArro
8220
8986
  pathACore = makeBinary(
8221
8987
  "^",
8222
8988
  pathACore,
8223
- makeBinary("&", makeMemberIndex(aliasReadIdent, makeLiteral(slotB)), makeLiteral(1))
8989
+ makeBinary("&", makeSafeAliasRead(aliasReadIdent, slotB), makeLiteral(1))
8224
8990
  );
8225
8991
  }
8226
8992
  const pathA = ctxOpts?.scratchVarIdent ? {
@@ -8230,7 +8996,7 @@ function createSotaMbaPredicate(seed, fnIndex = 0, paramNode, decoyIdent, isArro
8230
8996
  const pathB = hasAlias ? makeBinary(
8231
8997
  "^",
8232
8998
  makeLiteral(qnrFamily.expectedBit),
8233
- makeBinary("&", makeMemberIndex(ctxOpts.aliasIdentA, makeLiteral(slotB)), makeLiteral(1))
8999
+ makeBinary("&", makeSafeAliasRead(ctxOpts.aliasIdentA, slotB), makeLiteral(1))
8234
9000
  ) : makeLiteral(qnrFamily.expectedBit);
8235
9001
  testExpr = makeBinary("!==", makeBinary("^", pathA, pathB), makeLiteral(0));
8236
9002
  } else if (predForm === 1) {
@@ -8277,8 +9043,8 @@ function createSotaMbaPredicate(seed, fnIndex = 0, paramNode, decoyIdent, isArro
8277
9043
  right: tamperCheck
8278
9044
  };
8279
9045
  } else if (predForm === 2) {
8280
- const slotReadB = hasAlias ? makeBinary("&", makeMemberIndex(aliasReadIdent, makeLiteral(slotB)), makeLiteral(7)) : makeBinary("&", makeTypeofGlobalLen(), makeLiteral(7));
8281
- const slotWriteB = hasAlias ? makeBinary("&", makeMemberIndex(ctxOpts.aliasIdentA, makeLiteral(slotB)), makeLiteral(7)) : makeBinary("&", makeTypeofGlobalLen(), makeLiteral(7));
9046
+ const slotReadB = hasAlias ? makeBinary("&", makeSafeAliasRead(aliasReadIdent, slotB), makeLiteral(7)) : makeBinary("&", makeTypeofGlobalLen(), makeLiteral(7));
9047
+ const slotWriteB = hasAlias ? makeBinary("&", makeSafeAliasRead(ctxOpts.aliasIdentA, slotB), makeLiteral(7)) : makeBinary("&", makeTypeofGlobalLen(), makeLiteral(7));
8282
9048
  let lhsExpr = makeBinary("+", qnrLeft, slotReadB);
8283
9049
  if (aliasInvZero) {
8284
9050
  lhsExpr = makeBinary("+", lhsExpr, makeBinary("&", aliasInvZero, makeLiteral(3)));
@@ -8286,8 +9052,8 @@ function createSotaMbaPredicate(seed, fnIndex = 0, paramNode, decoyIdent, isArro
8286
9052
  const rhsExpr = makeBinary("+", makeLiteral(qnrFamily.outBoundVal), slotWriteB);
8287
9053
  testExpr = makeBinary(qnrFamily.outBoundOp, lhsExpr, rhsExpr);
8288
9054
  } else if (predForm === 3) {
8289
- const tagLhs = hasAlias ? makeBinary("&", makeMemberIndex(ctxOpts.aliasIdentA, makeLiteral(slotB)), makeLiteral(240)) : makeBinary("&", makeBinary("<<", makeTypeofGlobalLen(), makeLiteral(4)), makeLiteral(240));
8290
- const tagRhsBase = hasAlias ? makeBinary("&", makeMemberIndex(aliasReadIdent, makeLiteral(slotB)), makeLiteral(240)) : makeBinary("&", makeBinary("<<", makeTypeofGlobalLen(), makeLiteral(4)), makeLiteral(240));
9055
+ const tagLhs = hasAlias ? makeBinary("&", makeSafeAliasRead(ctxOpts.aliasIdentA, slotB), makeLiteral(240)) : makeBinary("&", makeBinary("<<", makeTypeofGlobalLen(), makeLiteral(4)), makeLiteral(240));
9056
+ const tagRhsBase = hasAlias ? makeBinary("&", makeSafeAliasRead(aliasReadIdent, slotB), makeLiteral(240)) : makeBinary("&", makeBinary("<<", makeTypeofGlobalLen(), makeLiteral(4)), makeLiteral(240));
8291
9057
  const tagRhs = aliasInvZero ? makeBinary("^", tagRhsBase, makeBinary("&", aliasInvZero, makeLiteral(15))) : tagRhsBase;
8292
9058
  const lhsExpr = makeBinary("|", makeBinary("^", qnrLeft, tagLhs), makeLiteral(0));
8293
9059
  const rhsExpr = makeBinary("|", makeBinary("^", makeLiteral(qnrFamily.target), tagRhs), makeLiteral(0));
@@ -8425,18 +9191,25 @@ function inferFunctionReturnDomain(fnNode) {
8425
9191
  if (seenString && !seenNumber && !seenBoolean) return "string";
8426
9192
  return "object";
8427
9193
  }
8428
- function createSboxAndAliasDeclarations(sboxIdent, aliasIdentA, aliasIdentB, scratchVarIdent, seed, mxIdent) {
8429
- const sboxInit = acorn5.parseExpressionAt(
9194
+ function buildSboxInitExpression(seed) {
9195
+ return acorn5.parseExpressionAt(
8430
9196
  `(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;})()`,
8431
9197
  0,
8432
9198
  { ecmaVersion: "latest" }
8433
9199
  );
8434
- const stateVals = [
8435
- mixSeed32(seed, 101),
8436
- mixSeed32(seed, 103),
8437
- mixSeed32(seed, 107),
8438
- mixSeed32(seed, 109)
8439
- ];
9200
+ }
9201
+ function createColdFlowRuntimeDeclarations(sboxIdent, aliasIdentA, aliasIdentB, scratchVarIdent, seed, latchFnName, mxIdent) {
9202
+ const sboxInit = buildSboxInitExpression(seed);
9203
+ const initWords = deriveColdAliasInitWords(seed);
9204
+ const wordsArrayExpr = {
9205
+ type: "ArrayExpression",
9206
+ elements: initWords.map((v) => makeInt32Literal(v))
9207
+ };
9208
+ const newArrayBuffer32 = {
9209
+ type: "NewExpression",
9210
+ callee: { type: "Identifier", name: "ArrayBuffer" },
9211
+ arguments: [makeLiteral(32)]
9212
+ };
8440
9213
  const declarations = [
8441
9214
  {
8442
9215
  type: "VariableDeclarator",
@@ -8447,14 +9220,26 @@ function createSboxAndAliasDeclarations(sboxIdent, aliasIdentA, aliasIdentB, scr
8447
9220
  type: "VariableDeclarator",
8448
9221
  id: { type: "Identifier", name: aliasIdentA },
8449
9222
  init: {
8450
- type: "ArrayExpression",
8451
- elements: stateVals.map((v) => makeInt32Literal(v))
9223
+ type: "NewExpression",
9224
+ callee: { type: "Identifier", name: "Uint32Array" },
9225
+ arguments: [newArrayBuffer32]
8452
9226
  }
8453
9227
  },
8454
9228
  {
8455
9229
  type: "VariableDeclarator",
8456
9230
  id: { type: "Identifier", name: aliasIdentB },
8457
- init: { type: "Identifier", name: aliasIdentA }
9231
+ init: {
9232
+ type: "NewExpression",
9233
+ callee: { type: "Identifier", name: "Int32Array" },
9234
+ arguments: [
9235
+ {
9236
+ type: "MemberExpression",
9237
+ computed: false,
9238
+ object: { type: "Identifier", name: aliasIdentA },
9239
+ property: { type: "Identifier", name: "buffer" }
9240
+ }
9241
+ ]
9242
+ }
8458
9243
  },
8459
9244
  {
8460
9245
  type: "VariableDeclarator",
@@ -8462,6 +9247,32 @@ function createSboxAndAliasDeclarations(sboxIdent, aliasIdentA, aliasIdentB, scr
8462
9247
  init: makeLiteral(0)
8463
9248
  }
8464
9249
  ];
9250
+ const varDecl = {
9251
+ type: "VariableDeclaration",
9252
+ kind: "var",
9253
+ declarations
9254
+ };
9255
+ const aliasInitStmt = {
9256
+ type: "ExpressionStatement",
9257
+ expression: {
9258
+ type: "CallExpression",
9259
+ callee: {
9260
+ type: "MemberExpression",
9261
+ computed: false,
9262
+ object: { type: "Identifier", name: aliasIdentB },
9263
+ property: { type: "Identifier", name: "set" }
9264
+ },
9265
+ arguments: [cloneNode(wordsArrayExpr)],
9266
+ optional: false
9267
+ }
9268
+ };
9269
+ const wordsList = initWords.map((w) => w | 0).join(",");
9270
+ const latchFnParsed = acorn5.parse(
9271
+ `function ${latchFnName}(){try{return(${aliasIdentA}!==void 0&&${aliasIdentB}!==void 0)||(${aliasIdentA}=new Uint32Array(new ArrayBuffer(32)),${aliasIdentB}=new Int32Array(${aliasIdentA}.buffer),${aliasIdentB}.set([${wordsList}])),((${aliasIdentA}[0]^${aliasIdentB}[1])&255)}catch(e){return -1}}`,
9272
+ { ecmaVersion: "latest", sourceType: "script" }
9273
+ );
9274
+ const latchFnDecl = latchFnParsed.body[0];
9275
+ let mxFnDecl;
8465
9276
  if (mxIdent) {
8466
9277
  const mbaAst = buildMba4Ast(
8467
9278
  seed,
@@ -8471,9 +9282,48 @@ function createSboxAndAliasDeclarations(sboxIdent, aliasIdentA, aliasIdentB, scr
8471
9282
  { type: "Identifier", name: "$p" },
8472
9283
  { type: "Identifier", name: "$q" }
8473
9284
  );
8474
- const mxFn = {
8475
- type: "FunctionExpression",
8476
- id: null,
9285
+ const slotExpr = makeBinary("+", makeLiteral(2), makeBinary("&", { type: "Identifier", name: "$c" }, makeLiteral(1)));
9286
+ const lazyAliasGuard = {
9287
+ type: "ExpressionStatement",
9288
+ expression: {
9289
+ type: "LogicalExpression",
9290
+ operator: "||",
9291
+ left: {
9292
+ type: "LogicalExpression",
9293
+ operator: "&&",
9294
+ left: makeBinary("!==", { type: "Identifier", name: aliasIdentA }, makeUnary("void", makeLiteral(0))),
9295
+ right: makeBinary("!==", { type: "Identifier", name: aliasIdentB }, makeUnary("void", makeLiteral(0)))
9296
+ },
9297
+ right: {
9298
+ type: "LogicalExpression",
9299
+ operator: "||",
9300
+ left: makeBinary("!==", makeUnary("typeof", { type: "Identifier", name: latchFnName }), makeLiteral("function")),
9301
+ right: {
9302
+ type: "CallExpression",
9303
+ callee: { type: "Identifier", name: latchFnName },
9304
+ arguments: [],
9305
+ optional: false
9306
+ }
9307
+ }
9308
+ }
9309
+ };
9310
+ const lazySboxGuard = {
9311
+ type: "ExpressionStatement",
9312
+ expression: {
9313
+ type: "LogicalExpression",
9314
+ operator: "||",
9315
+ left: { type: "Identifier", name: sboxIdent },
9316
+ right: {
9317
+ type: "AssignmentExpression",
9318
+ operator: "=",
9319
+ left: { type: "Identifier", name: sboxIdent },
9320
+ right: buildSboxInitExpression(seed)
9321
+ }
9322
+ }
9323
+ };
9324
+ mxFnDecl = {
9325
+ type: "FunctionDeclaration",
9326
+ id: { type: "Identifier", name: mxIdent },
8477
9327
  params: [
8478
9328
  { type: "Identifier", name: "$a" },
8479
9329
  { type: "Identifier", name: "$b" },
@@ -8489,104 +9339,124 @@ function createSboxAndAliasDeclarations(sboxIdent, aliasIdentA, aliasIdentB, scr
8489
9339
  type: "BlockStatement",
8490
9340
  body: [
8491
9341
  {
8492
- type: "VariableDeclaration",
8493
- kind: "var",
8494
- declarations: [
8495
- { type: "VariableDeclarator", id: { type: "Identifier", name: "$u" }, init: makeBinary("|", { type: "Identifier", name: "$a" }, makeLiteral(0)) },
8496
- { type: "VariableDeclarator", id: { type: "Identifier", name: "$v" }, init: makeBinary("|", { type: "Identifier", name: "$b" }, makeLiteral(0)) },
8497
- { type: "VariableDeclarator", id: { type: "Identifier", name: "$p" }, init: makeBinary("|", makeMemberIndex(aliasIdentA, { type: "Identifier", name: "$c" }), makeLiteral(0)) },
8498
- { type: "VariableDeclarator", id: { type: "Identifier", name: "$q" }, init: makeBinary("|", makeMemberIndex(aliasIdentB, { type: "Identifier", name: "$d" }), makeLiteral(0)) },
8499
- { type: "VariableDeclarator", id: { type: "Identifier", name: "$z" }, init: mbaAst }
8500
- ]
8501
- },
8502
- {
8503
- type: "ExpressionStatement",
8504
- expression: {
8505
- type: "AssignmentExpression",
8506
- operator: "=",
8507
- left: { type: "Identifier", name: "$z" },
8508
- right: makeBinary(
8509
- "|",
8510
- makeBinary(
8511
- "+",
8512
- { type: "Identifier", name: "$f" },
8513
- makeImul(
8514
- { type: "Identifier", name: "$z" },
8515
- makeBinary(
8516
- "+",
8517
- { type: "Identifier", name: "$g" },
8518
- makeImul(
8519
- { type: "Identifier", name: "$z" },
8520
- makeBinary(
8521
- "+",
8522
- { type: "Identifier", name: "$h" },
8523
- makeImul({ type: "Identifier", name: "$z" }, { type: "Identifier", name: "$i" })
9342
+ type: "TryStatement",
9343
+ block: {
9344
+ type: "BlockStatement",
9345
+ body: [
9346
+ lazyAliasGuard,
9347
+ lazySboxGuard,
9348
+ {
9349
+ type: "VariableDeclaration",
9350
+ kind: "var",
9351
+ declarations: [
9352
+ { type: "VariableDeclarator", id: { type: "Identifier", name: "$s" }, init: slotExpr },
9353
+ { type: "VariableDeclarator", id: { type: "Identifier", name: "$u" }, init: makeBinary("|", { type: "Identifier", name: "$a" }, makeLiteral(0)) },
9354
+ { type: "VariableDeclarator", id: { type: "Identifier", name: "$v" }, init: makeBinary("|", { type: "Identifier", name: "$b" }, makeLiteral(0)) },
9355
+ { type: "VariableDeclarator", id: { type: "Identifier", name: "$p" }, init: makeBinary("|", makeMemberIndex(aliasIdentA, { type: "Identifier", name: "$s" }), makeLiteral(0)) },
9356
+ { type: "VariableDeclarator", id: { type: "Identifier", name: "$q" }, init: makeBinary("|", makeMemberIndex(aliasIdentB, { type: "Identifier", name: "$d" }), makeLiteral(0)) },
9357
+ { type: "VariableDeclarator", id: { type: "Identifier", name: "$z" }, init: mbaAst }
9358
+ ]
9359
+ },
9360
+ {
9361
+ type: "ExpressionStatement",
9362
+ expression: {
9363
+ type: "AssignmentExpression",
9364
+ operator: "=",
9365
+ left: { type: "Identifier", name: "$z" },
9366
+ right: makeBinary(
9367
+ "|",
9368
+ makeBinary(
9369
+ "+",
9370
+ { type: "Identifier", name: "$f" },
9371
+ makeImul(
9372
+ { type: "Identifier", name: "$z" },
9373
+ makeBinary(
9374
+ "+",
9375
+ { type: "Identifier", name: "$g" },
9376
+ makeImul(
9377
+ { type: "Identifier", name: "$z" },
9378
+ makeBinary(
9379
+ "+",
9380
+ { type: "Identifier", name: "$h" },
9381
+ makeImul({ type: "Identifier", name: "$z" }, { type: "Identifier", name: "$i" })
9382
+ )
9383
+ )
9384
+ )
8524
9385
  )
8525
- )
9386
+ ),
9387
+ makeLiteral(0)
8526
9388
  )
8527
- )
8528
- ),
8529
- makeLiteral(0)
8530
- )
8531
- }
8532
- },
8533
- {
8534
- type: "ExpressionStatement",
8535
- expression: {
8536
- type: "AssignmentExpression",
8537
- operator: "=",
8538
- left: { type: "Identifier", name: "$z" },
8539
- right: buildSboxMixAst(sboxIdent, "$z")
8540
- }
8541
- },
8542
- {
8543
- type: "VariableDeclaration",
8544
- kind: "var",
8545
- declarations: [
8546
- {
8547
- type: "VariableDeclarator",
8548
- id: { type: "Identifier", name: "$m" },
8549
- init: makeBinary("^", makeBinary("<<", { type: "Identifier", name: "$z" }, makeLiteral(3)), { type: "Identifier", name: "$e" })
8550
- }
8551
- ]
8552
- },
8553
- {
8554
- type: "ExpressionStatement",
8555
- expression: {
8556
- type: "AssignmentExpression",
8557
- operator: "=",
8558
- left: makeMemberIndex(aliasIdentA, { type: "Identifier", name: "$c" }),
8559
- right: makeBinary("|", makeBinary("^", makeMemberIndex(aliasIdentA, { type: "Identifier", name: "$c" }), { type: "Identifier", name: "$m" }), makeLiteral(0))
8560
- }
8561
- },
8562
- {
8563
- type: "VariableDeclaration",
8564
- kind: "var",
8565
- declarations: [
8566
- {
8567
- type: "VariableDeclarator",
8568
- id: { type: "Identifier", name: "$w" },
8569
- init: makeBinary(
8570
- "^",
8571
- makeBinary("|", makeBinary("^", makeMemberIndex(aliasIdentA, { type: "Identifier", name: "$c" }), { type: "Identifier", name: "$m" }), makeLiteral(0)),
8572
- {
9389
+ }
9390
+ },
9391
+ {
9392
+ type: "ExpressionStatement",
9393
+ expression: {
9394
+ type: "AssignmentExpression",
9395
+ operator: "=",
9396
+ left: { type: "Identifier", name: "$z" },
9397
+ right: buildSboxMixAst(sboxIdent, "$z")
9398
+ }
9399
+ },
9400
+ {
9401
+ type: "VariableDeclaration",
9402
+ kind: "var",
9403
+ declarations: [
9404
+ {
9405
+ type: "VariableDeclarator",
9406
+ id: { type: "Identifier", name: "$m" },
9407
+ init: makeBinary("^", makeBinary("<<", { type: "Identifier", name: "$z" }, makeLiteral(3)), { type: "Identifier", name: "$e" })
9408
+ }
9409
+ ]
9410
+ },
9411
+ {
9412
+ type: "ExpressionStatement",
9413
+ expression: {
8573
9414
  type: "AssignmentExpression",
8574
9415
  operator: "=",
8575
- left: makeMemberIndex(aliasIdentA, { type: "Identifier", name: "$c" }),
8576
- right: makeBinary("|", makeBinary("^", makeMemberIndex(aliasIdentA, { type: "Identifier", name: "$c" }), { type: "Identifier", name: "$m" }), makeLiteral(0))
9416
+ left: makeMemberIndex(aliasIdentA, { type: "Identifier", name: "$s" }),
9417
+ right: makeBinary("|", makeBinary("^", makeMemberIndex(aliasIdentA, { type: "Identifier", name: "$s" }), { type: "Identifier", name: "$m" }), makeLiteral(0))
8577
9418
  }
8578
- )
9419
+ },
9420
+ {
9421
+ type: "VariableDeclaration",
9422
+ kind: "var",
9423
+ declarations: [
9424
+ {
9425
+ type: "VariableDeclarator",
9426
+ id: { type: "Identifier", name: "$w" },
9427
+ init: makeBinary(
9428
+ "^",
9429
+ makeBinary("|", makeBinary("^", makeMemberIndex(aliasIdentA, { type: "Identifier", name: "$s" }), { type: "Identifier", name: "$m" }), makeLiteral(0)),
9430
+ {
9431
+ type: "AssignmentExpression",
9432
+ operator: "=",
9433
+ left: makeMemberIndex(aliasIdentA, { type: "Identifier", name: "$s" }),
9434
+ right: makeBinary("|", makeBinary("^", makeMemberIndex(aliasIdentA, { type: "Identifier", name: "$s" }), { type: "Identifier", name: "$m" }), makeLiteral(0))
9435
+ }
9436
+ )
9437
+ }
9438
+ ]
9439
+ },
9440
+ {
9441
+ type: "ReturnStatement",
9442
+ argument: {
9443
+ type: "AssignmentExpression",
9444
+ operator: "=",
9445
+ left: { type: "Identifier", name: scratchVarIdent },
9446
+ right: makeBinary("|", makeBinary("^", { type: "Identifier", name: "$z" }, { type: "Identifier", name: "$w" }), makeLiteral(0))
9447
+ }
9448
+ }
9449
+ ]
9450
+ },
9451
+ handler: {
9452
+ type: "CatchClause",
9453
+ param: { type: "Identifier", name: "$e" },
9454
+ body: {
9455
+ type: "BlockStatement",
9456
+ body: [{ type: "ReturnStatement", argument: makeLiteral(0) }]
8579
9457
  }
8580
- ]
8581
- },
8582
- {
8583
- type: "ReturnStatement",
8584
- argument: {
8585
- type: "AssignmentExpression",
8586
- operator: "=",
8587
- left: { type: "Identifier", name: scratchVarIdent },
8588
- right: makeBinary("|", makeBinary("^", { type: "Identifier", name: "$z" }, { type: "Identifier", name: "$w" }), makeLiteral(0))
8589
- }
9458
+ },
9459
+ finalizer: null
8590
9460
  }
8591
9461
  ]
8592
9462
  },
@@ -8594,16 +9464,12 @@ function createSboxAndAliasDeclarations(sboxIdent, aliasIdentA, aliasIdentB, scr
8594
9464
  async: false,
8595
9465
  expression: false
8596
9466
  };
8597
- declarations.push({
8598
- type: "VariableDeclarator",
8599
- id: { type: "Identifier", name: mxIdent },
8600
- init: mxFn
8601
- });
8602
9467
  }
8603
9468
  return {
8604
- type: "VariableDeclaration",
8605
- kind: "var",
8606
- declarations
9469
+ varDecl,
9470
+ aliasInitStmt,
9471
+ latchFnDecl,
9472
+ ...mxFnDecl ? { mxFnDecl } : {}
8607
9473
  };
8608
9474
  }
8609
9475
  var MAX_COLD_GUARDS_PER_CHUNK = 12;
@@ -8962,96 +9828,345 @@ function applyColdBitwiseMba(ast, coldFunctionNodes, seed = 2654435769, hotExemp
8962
9828
  }, false);
8963
9829
  return mbaCount;
8964
9830
  }
9831
+ var UNSAFE_EXPRESSION_NODE_TYPES = /* @__PURE__ */ new Set(["Super", "WithStatement"]);
9832
+ var UNSAFE_IF_NODE_TYPES = /* @__PURE__ */ new Set([
9833
+ "Super",
9834
+ "WithStatement",
9835
+ "FunctionDeclaration",
9836
+ "ClassDeclaration"
9837
+ ]);
9838
+ function containsAstNodeType(node, types) {
9839
+ if (!node || typeof node !== "object") return false;
9840
+ if (Array.isArray(node)) {
9841
+ for (const item of node) {
9842
+ if (containsAstNodeType(item, types)) return true;
9843
+ }
9844
+ return false;
9845
+ }
9846
+ if (typeof node.type === "string" && types.has(node.type)) {
9847
+ return true;
9848
+ }
9849
+ for (const key of Object.keys(node)) {
9850
+ if (key === "loc" || key === "range" || key === "start" || key === "end" || key === "comments" || key === "tokens") {
9851
+ continue;
9852
+ }
9853
+ const val = node[key];
9854
+ if (val && typeof val === "object" && containsAstNodeType(val, types)) {
9855
+ return true;
9856
+ }
9857
+ }
9858
+ return false;
9859
+ }
9860
+ function collectMathUnsafeScopes(ast) {
9861
+ const unsafe = /* @__PURE__ */ new WeakSet();
9862
+ const findEnclosing = (ancestors) => {
9863
+ for (let i = ancestors.length - 1; i >= 0; i--) {
9864
+ if (BITWISE_LEXICAL_SCOPE_TYPES.has(ancestors[i].type)) {
9865
+ return ancestors[i];
9866
+ }
9867
+ }
9868
+ return ast;
9869
+ };
9870
+ const markScopeAndEnclosingFn = (ancestors, scopeNode) => {
9871
+ unsafe.add(scopeNode);
9872
+ const parent = ancestors.length >= 2 ? ancestors[ancestors.length - 2] : null;
9873
+ if (parent && BITWISE_FUNCTION_TYPES.has(parent.type) && parent.body === scopeNode) {
9874
+ unsafe.add(parent);
9875
+ }
9876
+ };
9877
+ const patternHasMath = (pat) => {
9878
+ const names = [];
9879
+ collectBoundPatternNames(pat, names);
9880
+ return names.includes("Math");
9881
+ };
9882
+ walk6.ancestor(ast, {
9883
+ WithStatement(node, _st, ancestors) {
9884
+ unsafe.add(node);
9885
+ for (let i = ancestors.length - 2; i >= 0; i--) {
9886
+ const a = ancestors[i];
9887
+ if (BITWISE_FUNCTION_TYPES.has(a.type)) {
9888
+ unsafe.add(a);
9889
+ break;
9890
+ }
9891
+ if (a.type === "Program") break;
9892
+ }
9893
+ },
9894
+ ImportSpecifier(node) {
9895
+ if (node.local?.name === "Math") unsafe.add(ast);
9896
+ },
9897
+ ImportDefaultSpecifier(node) {
9898
+ if (node.local?.name === "Math") unsafe.add(ast);
9899
+ },
9900
+ ImportNamespaceSpecifier(node) {
9901
+ if (node.local?.name === "Math") unsafe.add(ast);
9902
+ },
9903
+ FunctionDeclaration(node, _st, ancestors) {
9904
+ if (node.id?.name === "Math") {
9905
+ const prefix = ancestors.slice(0, -1);
9906
+ markScopeAndEnclosingFn(prefix, findEnclosing(prefix));
9907
+ unsafe.add(node);
9908
+ }
9909
+ if (Array.isArray(node.params) && node.params.some(patternHasMath)) {
9910
+ unsafe.add(node);
9911
+ }
9912
+ },
9913
+ FunctionExpression(node) {
9914
+ if (node.id?.name === "Math" || Array.isArray(node.params) && node.params.some(patternHasMath)) {
9915
+ unsafe.add(node);
9916
+ }
9917
+ },
9918
+ ArrowFunctionExpression(node) {
9919
+ if (Array.isArray(node.params) && node.params.some(patternHasMath)) {
9920
+ unsafe.add(node);
9921
+ }
9922
+ },
9923
+ ClassDeclaration(node, _st, ancestors) {
9924
+ if (node.id?.name === "Math") {
9925
+ const prefix = ancestors.slice(0, -1);
9926
+ markScopeAndEnclosingFn(prefix, findEnclosing(prefix));
9927
+ unsafe.add(node);
9928
+ }
9929
+ },
9930
+ ClassExpression(node) {
9931
+ if (node.id?.name === "Math") {
9932
+ unsafe.add(node);
9933
+ }
9934
+ },
9935
+ CatchClause(node) {
9936
+ if (node.param && patternHasMath(node.param)) {
9937
+ unsafe.add(node);
9938
+ }
9939
+ },
9940
+ VariableDeclaration(node, _st, ancestors) {
9941
+ if (!Array.isArray(node.declarations) || !node.declarations.some((d) => patternHasMath(d?.id))) {
9942
+ return;
9943
+ }
9944
+ if (node.kind === "var") {
9945
+ for (let i = ancestors.length - 1; i >= 0; i--) {
9946
+ const a = ancestors[i];
9947
+ if (BITWISE_FUNCTION_TYPES.has(a.type) || a.type === "StaticBlock" || a.type === "Program") {
9948
+ unsafe.add(a);
9949
+ break;
9950
+ }
9951
+ }
9952
+ } else {
9953
+ const prefix = ancestors.slice(0, -1);
9954
+ markScopeAndEnclosingFn(prefix, findEnclosing(prefix));
9955
+ }
9956
+ }
9957
+ });
9958
+ return unsafe;
9959
+ }
9960
+ function isAnyAncestorInSet(ancestors, set) {
9961
+ if (!set) return false;
9962
+ for (let i = ancestors.length - 1; i >= 0; i--) {
9963
+ if (set.has(ancestors[i])) return true;
9964
+ }
9965
+ return false;
9966
+ }
9967
+ function isDirectiveStatement(stmt) {
9968
+ if (!stmt || stmt.type !== "ExpressionStatement") return false;
9969
+ if (stmt.directive) return true;
9970
+ return stmt.expression?.type === "Literal" && typeof stmt.expression.value === "string" && /^(?:use\s+[a-zA-Z0-9_-]+)/.test(stmt.expression.value.trim());
9971
+ }
9972
+ function isSafeC9Statement(stmt, hotExemptNodes) {
9973
+ if (!stmt || typeof stmt !== "object") return false;
9974
+ if (stmt._unpeekGuardSubtree === true) return false;
9975
+ if (hotExemptNodes?.has(stmt)) return false;
9976
+ if (stmt.type === "ExpressionStatement") {
9977
+ if (isDirectiveStatement(stmt)) return false;
9978
+ return !containsAstNodeType(stmt, UNSAFE_EXPRESSION_NODE_TYPES);
9979
+ }
9980
+ if (stmt.type === "IfStatement") {
9981
+ return !containsAstNodeType(stmt, UNSAFE_IF_NODE_TYPES);
9982
+ }
9983
+ return false;
9984
+ }
8965
9985
  function applyColdFlowGuard(ast, coldFunctionNodes, seed = 2654435769, hotExemptNodes, windowKeySymbol, expectedDelta, shieldCoupled = false, options) {
8966
- const sfx = (seed >>> 0).toString(36).slice(0, 4);
9986
+ const sfx = deriveColdFlowSuffix(seed);
8967
9987
  const decoyIdent = `_uDec${sfx}`;
8968
9988
  const sboxIdent = `_uSb${sfx}`;
8969
9989
  const aliasIdentA = `_uAl${sfx}`;
8970
9990
  const aliasIdentB = `_uAm${sfx}`;
8971
9991
  const scratchVarIdent = `_uZt${sfx}`;
8972
9992
  const mxIdent = `_uMx${sfx}`;
9993
+ const latchFnName = `_uLr${sfx}`;
8973
9994
  if (Array.isArray(ast.body)) {
8974
9995
  const alreadyGuarded = ast.body.some(
8975
9996
  (stmt) => stmt.type === "VariableDeclaration" && stmt.declarations?.some(
8976
9997
  (d) => d.id?.type === "Identifier" && (d.id.name === decoyIdent || d.id.name === sboxIdent || d.id.name === mxIdent)
8977
- )
9998
+ ) || stmt.type === "FunctionDeclaration" && stmt.id?.type === "Identifier" && (stmt.id.name === mxIdent || stmt.id.name === latchFnName)
8978
9999
  );
8979
10000
  if (alreadyGuarded) return 0;
8980
10001
  }
8981
10002
  if (options?.enableBitwiseMba) {
8982
10003
  applyColdBitwiseMba(ast, coldFunctionNodes, seed, hotExemptNodes);
8983
10004
  }
8984
- let guardedCount = 0;
8985
- function maybeInjectGuard(node) {
8986
- if (guardedCount >= MAX_COLD_GUARDS_PER_CHUNK) return;
10005
+ const mathUnsafeScopes = collectMathUnsafeScopes(ast);
10006
+ const C9_RESERVED_SLOTS = 4;
10007
+ const eligibleColdFns = [];
10008
+ function collectEligibleColdFn(node, _state, ancestors) {
10009
+ if (eligibleColdFns.length >= MAX_COLD_GUARDS_PER_CHUNK) return;
8987
10010
  if (!coldFunctionNodes.has(node)) return;
8988
- if (hotExemptNodes?.has(node) || node._unpeekSerialized) return;
10011
+ if (isAnyAncestorInSet(ancestors, hotExemptNodes)) return;
10012
+ if (isAnyAncestorInSet(ancestors, mathUnsafeScopes)) return;
10013
+ if (node._unpeekSerialized) return;
8989
10014
  if (node._unpeekVirtualized === true) return;
8990
10015
  if (!node.body || node.body.type !== "BlockStatement") return;
8991
10016
  const paramNames = [];
8992
10017
  for (const p of node.params || []) {
8993
10018
  extractParamNames(p, paramNames);
8994
10019
  }
8995
- const firstParam = node.params?.[0];
8996
- const isArrow = node.type === "ArrowFunctionExpression";
8997
- const returnDomain = inferFunctionReturnDomain(node);
10020
+ eligibleColdFns.push({
10021
+ node,
10022
+ paramNames,
10023
+ firstParam: node.params?.[0],
10024
+ isArrow: node.type === "ArrowFunctionExpression",
10025
+ returnDomain: inferFunctionReturnDomain(node)
10026
+ });
10027
+ }
10028
+ walk6.ancestor(ast, {
10029
+ FunctionDeclaration: collectEligibleColdFn,
10030
+ FunctionExpression: collectEligibleColdFn,
10031
+ ArrowFunctionExpression: collectEligibleColdFn
10032
+ });
10033
+ let availableC9Slots = 0;
10034
+ for (const fnInfo of eligibleColdFns) {
10035
+ if (availableC9Slots >= C9_RESERVED_SLOTS) break;
10036
+ const bodyStmts = fnInfo.node.body.body;
10037
+ let idx = 0;
10038
+ while (idx < bodyStmts.length && isDirectiveStatement(bodyStmts[idx])) {
10039
+ idx++;
10040
+ }
10041
+ for (; idx < bodyStmts.length; idx++) {
10042
+ if (isSafeC9Statement(bodyStmts[idx], hotExemptNodes)) {
10043
+ availableC9Slots++;
10044
+ if (availableC9Slots >= C9_RESERVED_SLOTS) break;
10045
+ }
10046
+ }
10047
+ }
10048
+ const opaqueFalseLimit = MAX_COLD_GUARDS_PER_CHUNK - availableC9Slots;
10049
+ let opaqueFalseCount = 0;
10050
+ for (let i = 0; i < eligibleColdFns.length && opaqueFalseCount < opaqueFalseLimit; i++) {
10051
+ const fnInfo = eligibleColdFns[i];
8998
10052
  const guardStmt = createSotaMbaPredicate(
8999
10053
  seed,
9000
- guardedCount,
9001
- firstParam,
10054
+ opaqueFalseCount,
10055
+ fnInfo.firstParam,
9002
10056
  decoyIdent,
9003
- isArrow,
10057
+ fnInfo.isArrow,
9004
10058
  {
9005
- liveVars: paramNames,
10059
+ liveVars: fnInfo.paramNames,
9006
10060
  sboxIdent,
9007
10061
  aliasIdentA,
9008
10062
  aliasIdentB,
9009
10063
  scratchVarIdent,
9010
10064
  mxIdent,
9011
- returnDomain,
10065
+ returnDomain: fnInfo.returnDomain,
9012
10066
  windowKeySymbol,
9013
10067
  expectedDelta,
9014
10068
  shieldCoupled
9015
10069
  }
9016
10070
  );
9017
- guardedCount++;
10071
+ opaqueFalseCount++;
9018
10072
  guardStmt._unpeekGuardSubtree = true;
9019
10073
  if (hotExemptNodes) {
9020
10074
  hotExemptNodes.add(guardStmt);
9021
10075
  hotExemptNodes.add(guardStmt.consequent);
9022
10076
  }
9023
10077
  let insertIdx = 0;
9024
- while (insertIdx < node.body.body.length && node.body.body[insertIdx].type === "ExpressionStatement" && node.body.body[insertIdx].directive) {
10078
+ while (insertIdx < fnInfo.node.body.body.length && isDirectiveStatement(fnInfo.node.body.body[insertIdx])) {
9025
10079
  insertIdx++;
9026
10080
  }
9027
- node.body.body.splice(insertIdx, 0, guardStmt);
10081
+ fnInfo.node.body.body.splice(insertIdx, 0, guardStmt);
9028
10082
  }
9029
- walk6.simple(ast, {
9030
- FunctionDeclaration: maybeInjectGuard,
9031
- FunctionExpression: maybeInjectGuard,
9032
- ArrowFunctionExpression: maybeInjectGuard
9033
- });
9034
- if (guardedCount > 0 && Array.isArray(ast.body)) {
10083
+ let c9WrappedCount = 0;
10084
+ if (eligibleColdFns.length > 0 && opaqueFalseCount < MAX_COLD_GUARDS_PER_CHUNK) {
10085
+ const fnCursors = eligibleColdFns.map((fnInfo) => {
10086
+ const bodyStmts = fnInfo.node.body.body;
10087
+ let startIdx = 0;
10088
+ while (startIdx < bodyStmts.length && isDirectiveStatement(bodyStmts[startIdx])) {
10089
+ startIdx++;
10090
+ }
10091
+ return { fnInfo, bodyStmts, idx: startIdx };
10092
+ });
10093
+ let progress = true;
10094
+ while (progress && opaqueFalseCount + c9WrappedCount < MAX_COLD_GUARDS_PER_CHUNK) {
10095
+ progress = false;
10096
+ for (const cursor of fnCursors) {
10097
+ if (opaqueFalseCount + c9WrappedCount >= MAX_COLD_GUARDS_PER_CHUNK) break;
10098
+ const { fnInfo, bodyStmts } = cursor;
10099
+ while (cursor.idx < bodyStmts.length) {
10100
+ const stmt = bodyStmts[cursor.idx];
10101
+ const curIdx = cursor.idx++;
10102
+ if (!isSafeC9Statement(stmt, hotExemptNodes)) continue;
10103
+ const pred = createSotaMbaPredicate(
10104
+ seed,
10105
+ opaqueFalseCount + c9WrappedCount,
10106
+ fnInfo.firstParam,
10107
+ decoyIdent,
10108
+ fnInfo.isArrow,
10109
+ {
10110
+ liveVars: fnInfo.paramNames,
10111
+ sboxIdent,
10112
+ aliasIdentA,
10113
+ aliasIdentB,
10114
+ scratchVarIdent,
10115
+ mxIdent,
10116
+ returnDomain: "void",
10117
+ windowKeySymbol,
10118
+ expectedDelta,
10119
+ shieldCoupled
10120
+ }
10121
+ );
10122
+ const negatedTest = makeUnary("!", pred.test);
10123
+ negatedTest._unpeekGuardSubtree = true;
10124
+ if (hotExemptNodes) {
10125
+ hotExemptNodes.add(negatedTest);
10126
+ }
10127
+ bodyStmts[curIdx] = {
10128
+ type: "IfStatement",
10129
+ test: negatedTest,
10130
+ consequent: {
10131
+ type: "BlockStatement",
10132
+ body: [stmt]
10133
+ },
10134
+ alternate: null
10135
+ };
10136
+ c9WrappedCount++;
10137
+ progress = true;
10138
+ break;
10139
+ }
10140
+ }
10141
+ }
10142
+ }
10143
+ if ((opaqueFalseCount > 0 || c9WrappedCount > 0) && Array.isArray(ast.body)) {
9035
10144
  const sharedDecoyDecl = createSharedDecoyDeclaration(
9036
10145
  decoyIdent,
9037
- guardedCount,
10146
+ Math.max(1, opaqueFalseCount),
9038
10147
  seed
9039
10148
  );
9040
- const sboxAliasDecl = createSboxAndAliasDeclarations(
10149
+ const { varDecl, aliasInitStmt, latchFnDecl, mxFnDecl } = createColdFlowRuntimeDeclarations(
9041
10150
  sboxIdent,
9042
10151
  aliasIdentA,
9043
10152
  aliasIdentB,
9044
10153
  scratchVarIdent,
9045
10154
  seed,
10155
+ latchFnName,
9046
10156
  mxIdent
9047
10157
  );
10158
+ aliasInitStmt._unpeekGuardSubtree = true;
10159
+ latchFnDecl._unpeekGuardSubtree = true;
10160
+ if (mxFnDecl) {
10161
+ mxFnDecl._unpeekGuardSubtree = true;
10162
+ }
9048
10163
  if (hotExemptNodes) {
9049
10164
  hotExemptNodes.add(sharedDecoyDecl);
9050
- hotExemptNodes.add(sboxAliasDecl);
9051
- for (const decl of sboxAliasDecl.declarations || []) {
9052
- if (decl.init?.type === "FunctionExpression") {
9053
- hotExemptNodes.add(decl.init);
9054
- }
10165
+ hotExemptNodes.add(varDecl);
10166
+ hotExemptNodes.add(aliasInitStmt);
10167
+ hotExemptNodes.add(latchFnDecl);
10168
+ if (mxFnDecl) {
10169
+ hotExemptNodes.add(mxFnDecl);
9055
10170
  }
9056
10171
  for (const decl of sharedDecoyDecl.declarations || []) {
9057
10172
  if (decl.init?.type === "ArrayExpression" && decl.init.elements) {
@@ -9071,9 +10186,16 @@ function applyColdFlowGuard(ast, coldFunctionNodes, seed = 2654435769, hotExempt
9071
10186
  break;
9072
10187
  }
9073
10188
  }
9074
- ast.body.splice(insertIdx, 0, sboxAliasDecl, sharedDecoyDecl);
10189
+ const injectedDecls = [
10190
+ varDecl,
10191
+ aliasInitStmt,
10192
+ latchFnDecl,
10193
+ ...mxFnDecl ? [mxFnDecl] : [],
10194
+ sharedDecoyDecl
10195
+ ];
10196
+ ast.body.splice(insertIdx, 0, ...injectedDecls);
9075
10197
  }
9076
- return guardedCount;
10198
+ return opaqueFalseCount;
9077
10199
  }
9078
10200
 
9079
10201
  // src/ast/micro-vm.ts
@@ -9122,7 +10244,8 @@ var OP_TRY = 39;
9122
10244
  var OP_ENDTRY = 40;
9123
10245
  var OP_NULLISH = 41;
9124
10246
  var OP_DUP = 42;
9125
- var OPCODE_COUNT = 43;
10247
+ var OP_TOSTR = 43;
10248
+ var OPCODE_COUNT = 44;
9126
10249
  function shuffleRange(n, seed) {
9127
10250
  const arr = [];
9128
10251
  for (let i = 0; i < n; i++) arr.push(i);
@@ -9306,7 +10429,8 @@ function createInterpreterSource(vmHelperName, opMap, seed = 2654435769, windowK
9306
10429
  [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});" },
9307
10430
  [OP_ENDTRY]: { body: "$f.r=($f.r+$Z)|0;$f.e.pop();$f.r=($f.r-$B)|0;" },
9308
10431
  [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;" },
9309
- [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;" }
10432
+ [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;" },
10433
+ [OP_TOSTR]: { body: "$f.r=($f.r+$Z)|0;var $v=$f.q[$f.r-(1+$B)];$f.r=($f.r-$B)|0;$f.q[$f.r-1]=`${$v}`;" }
9310
10434
  };
9311
10435
  const handlers = new Array(opCount);
9312
10436
  for (let op = 0; op < opCount; op++) {
@@ -9913,6 +11037,7 @@ function compileFunctionToBytecode(fnNode, opMap, enclosingBindings, seed = 2654
9913
11037
  emit(OP_LDC, addConst(quasis[0]?.value?.cooked ?? quasis[0]?.value?.raw ?? ""));
9914
11038
  for (let i = 0; i < exprs.length; i++) {
9915
11039
  if (!compileExpr(exprs[i], true)) return false;
11040
+ emit(OP_TOSTR);
9916
11041
  emit(OP_ADD);
9917
11042
  const qStr = quasis[i + 1]?.value?.cooked ?? quasis[i + 1]?.value?.raw ?? "";
9918
11043
  if (qStr.length > 0) {
@@ -11085,7 +12210,7 @@ function scrubResidualPaths(ast, options = {}, hotExemptNodes, exemptSubtreeRoot
11085
12210
  if (exemptSet?.has(val)) return;
11086
12211
  const parent = ancestors[ancestors.length - 2];
11087
12212
  if (!parent) return;
11088
- if ((parent.type === "ImportDeclaration" || parent.type === "ExportNamedDeclaration" || parent.type === "ExportAllDeclaration" || parent.type === "ImportExpression") && parent.source === node) {
12213
+ if (isStaticModuleOrAssetPosition(node, parent)) {
11089
12214
  return;
11090
12215
  }
11091
12216
  if (parent.type === "ExpressionStatement" && Boolean(parent.directive)) {
@@ -11107,7 +12232,7 @@ function scrubResidualPaths(ast, options = {}, hotExemptNodes, exemptSubtreeRoot
11107
12232
  return;
11108
12233
  }
11109
12234
  const parent = ancestors[ancestors.length - 2];
11110
- if (parent?.type === "ImportExpression" && parent.source === node) {
12235
+ if (isStaticModuleOrAssetPosition(node, parent)) {
11111
12236
  return;
11112
12237
  }
11113
12238
  for (const quasi of node.quasis) {
@@ -11162,7 +12287,7 @@ function isAstAlreadyProtected(ast) {
11162
12287
  }
11163
12288
  if (stmt.type === "FunctionDeclaration" && stmt.id?.type === "Identifier") {
11164
12289
  const fnName = stmt.id.name;
11165
- if (typeof fnName === "string" && (fnName.startsWith("_uD") || fnName.startsWith("_uVm") || fnName.startsWith("_wKdf") || fnName === "_hX")) {
12290
+ if (typeof fnName === "string" && (fnName.startsWith("_uD") || fnName.startsWith("_uVm") || fnName.startsWith("_wKdf") || fnName.startsWith("_uLr") || fnName.startsWith("_uMx") || fnName === "_hX")) {
11166
12291
  return true;
11167
12292
  }
11168
12293
  }
@@ -11313,8 +12438,9 @@ function transformJavaScript(code, options = {}) {
11313
12438
  );
11314
12439
  virtualizedFunctionsCount = vmRes.virtualizedCount;
11315
12440
  }
12441
+ let coldFlowGuardedCount = 0;
11316
12442
  if (effectiveProfile !== "minimal" && effectiveConfig?.coldFlow !== false) {
11317
- applyColdFlowGuard(
12443
+ coldFlowGuardedCount = applyColdFlowGuard(
11318
12444
  ast,
11319
12445
  coldFunctionNodes,
11320
12446
  seed,
@@ -11325,6 +12451,7 @@ function transformJavaScript(code, options = {}) {
11325
12451
  { enableBitwiseMba: isAggressive || effectiveProfile === "strict" }
11326
12452
  );
11327
12453
  }
12454
+ const latchCoupling = coldFlowGuardedCount > 0 ? deriveColdLatchCoupling(seed) : void 0;
11328
12455
  const mangledSymbolsCount = applyPolymorphicMangler(
11329
12456
  ast,
11330
12457
  seed,
@@ -11346,7 +12473,8 @@ function transformJavaScript(code, options = {}) {
11346
12473
  deterrentMode,
11347
12474
  shieldCoupled,
11348
12475
  detectHeadless,
11349
- boundary.exemptSubtreeRoots
12476
+ boundary.exemptSubtreeRoots,
12477
+ latchCoupling
11350
12478
  );
11351
12479
  encryptedStringsCount = saltedRes.encryptedStringsCount;
11352
12480
  integrityToken = saltedRes.integrityToken;
@@ -11363,7 +12491,8 @@ function transformJavaScript(code, options = {}) {
11363
12491
  effectiveConfig,
11364
12492
  shieldCoupled,
11365
12493
  detectHeadless,
11366
- boundary.exemptSubtreeRoots
12494
+ boundary.exemptSubtreeRoots,
12495
+ latchCoupling
11367
12496
  );
11368
12497
  encryptedStringsCount = vaultRes.encryptedStringsCount;
11369
12498
  integrityToken = vaultRes.integrityToken;
@@ -11526,21 +12655,29 @@ function matchesManifestEntry(relPath, manifestEntries) {
11526
12655
  }
11527
12656
  return false;
11528
12657
  }
11529
- function isEntryChunk(relPath, index, allRelPaths, manifestEntries, isWorkerTarget) {
12658
+ function isEntryChunk(relPath, index, allRelPaths, manifestEntries, isWorkerTarget, htmlGraph) {
11530
12659
  const norm = relPath.replace(/\\/g, "/");
11531
12660
  const base2 = path5.basename(norm);
11532
12661
  if (isWorkerTarget && isWorkerOrServiceWorkerFile(norm)) {
11533
12662
  return true;
11534
12663
  }
12664
+ if (htmlGraph?.workerEntryFiles.has(norm)) {
12665
+ return true;
12666
+ }
11535
12667
  if (matchesManifestEntry(norm, manifestEntries)) {
11536
12668
  return true;
11537
12669
  }
12670
+ const hasKnownManifestEntry = manifestEntries.size > 0 && allRelPaths.some((p) => matchesManifestEntry(p.replace(/\\/g, "/"), manifestEntries));
12671
+ const hasKnownHtmlEntry = manifestEntries.size === 0 && Boolean(htmlGraph && allRelPaths.some((p) => htmlGraph.entryFiles.has(p.replace(/\\/g, "/"))));
12672
+ if (hasKnownHtmlEntry) {
12673
+ return htmlGraph.entryFiles.has(norm);
12674
+ }
11538
12675
  if (ENTRY_PATTERN.test(norm) || ENTRY_PATTERN.test(base2)) {
11539
12676
  return true;
11540
12677
  }
11541
- const hasAnyKnownEntry = allRelPaths.some((p) => {
12678
+ const hasAnyKnownEntry = hasKnownManifestEntry || allRelPaths.some((p) => {
11542
12679
  const n = p.replace(/\\/g, "/");
11543
- return matchesManifestEntry(n, manifestEntries) || ENTRY_PATTERN.test(n) || ENTRY_PATTERN.test(path5.basename(n));
12680
+ return ENTRY_PATTERN.test(n) || ENTRY_PATTERN.test(path5.basename(n));
11544
12681
  });
11545
12682
  if (!hasAnyKnownEntry && index === 0) {
11546
12683
  return true;
@@ -11639,6 +12776,13 @@ async function protectProject(options = {}) {
11639
12776
  const allRelPaths = clientFiles.map((f) => path5.relative(outDir, f).replace(/\\/g, "/"));
11640
12777
  const manifestEntries = collectManifestEntryFiles(outDir, cwd, config);
11641
12778
  const isWorkerTarget = config.target === "worker";
12779
+ const extraHtmlDirs = [];
12780
+ const parentOutDir = path5.dirname(outDir);
12781
+ const relParent = path5.relative(cwd, parentOutDir);
12782
+ if (relParent && !relParent.startsWith("..") && !path5.isAbsolute(relParent) && !hasNextServerSegment(parentOutDir, cwd)) {
12783
+ extraHtmlDirs.push(parentOutDir);
12784
+ }
12785
+ const htmlGraph = discoverHtmlEntryGraph(outDir, config, extraHtmlDirs);
11642
12786
  let originalBytes = 0;
11643
12787
  let protectedBytes = 0;
11644
12788
  let totalHotFunctionsSkipped = 0;
@@ -11694,7 +12838,14 @@ async function protectProject(options = {}) {
11694
12838
  const relPath = allRelPaths[i];
11695
12839
  const originalMap = keepPrivateMaps ? readOriginalSourceMapForFile(filePath, relPath, vaultResult.vaultDir, deferVaultWrites) : void 0;
11696
12840
  const preExistingHits = countPreExistingEvalCalls(codeToTransform);
11697
- const isEntry = isEntryChunk(relPath, i, allRelPaths, manifestEntries, isWorkerTarget);
12841
+ const isEntry = isEntryChunk(
12842
+ relPath,
12843
+ i,
12844
+ allRelPaths,
12845
+ manifestEntries,
12846
+ isWorkerTarget,
12847
+ htmlGraph
12848
+ );
11698
12849
  const shouldInjectShield = injectRuntimeShield && isEntry;
11699
12850
  const fileSeed = computeFnv1aHash(`${relPath}:${i}`, seed);
11700
12851
  const transformOptions = {
@@ -12444,7 +13595,7 @@ async function checkProject(options = {}) {
12444
13595
  }
12445
13596
 
12446
13597
  // src/cli/index.ts
12447
- var VERSION = "4.2.0";
13598
+ var VERSION = "4.3.0";
12448
13599
  var cachedPackageVersion;
12449
13600
  function getPackageVersion() {
12450
13601
  if (cachedPackageVersion !== void 0) {