unpeek 1.7.2 → 1.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/ast/index.cjs +2278 -386
  2. package/dist/ast/index.cjs.map +1 -1
  3. package/dist/ast/index.d.cts +69 -1
  4. package/dist/ast/index.d.ts +69 -1
  5. package/dist/ast/index.js +2266 -385
  6. package/dist/ast/index.js.map +1 -1
  7. package/dist/browser.cjs +2265 -393
  8. package/dist/browser.cjs.map +1 -1
  9. package/dist/browser.d.cts +2 -1
  10. package/dist/browser.d.ts +2 -1
  11. package/dist/browser.js +2260 -388
  12. package/dist/browser.js.map +1 -1
  13. package/dist/bundler/unplugin.cjs +2259 -385
  14. package/dist/bundler/unplugin.cjs.map +1 -1
  15. package/dist/bundler/unplugin.js +2258 -384
  16. package/dist/bundler/unplugin.js.map +1 -1
  17. package/dist/cli/index.cjs +2292 -396
  18. package/dist/cli/index.cjs.map +1 -1
  19. package/dist/cli/index.js +2292 -396
  20. package/dist/cli/index.js.map +1 -1
  21. package/dist/cli/protect.cjs +2284 -391
  22. package/dist/cli/protect.cjs.map +1 -1
  23. package/dist/cli/protect.js +2285 -392
  24. package/dist/cli/protect.js.map +1 -1
  25. package/dist/esbuild.cjs +2259 -385
  26. package/dist/esbuild.cjs.map +1 -1
  27. package/dist/esbuild.d.cts +1 -1
  28. package/dist/esbuild.d.ts +1 -1
  29. package/dist/esbuild.js +2258 -384
  30. package/dist/esbuild.js.map +1 -1
  31. package/dist/index.cjs +2309 -411
  32. package/dist/index.cjs.map +1 -1
  33. package/dist/index.d.cts +2 -1
  34. package/dist/index.d.ts +2 -1
  35. package/dist/index.js +2296 -398
  36. package/dist/index.js.map +1 -1
  37. package/dist/rollup.cjs +2259 -385
  38. package/dist/rollup.cjs.map +1 -1
  39. package/dist/rollup.d.cts +1 -1
  40. package/dist/rollup.d.ts +1 -1
  41. package/dist/rollup.js +2258 -384
  42. package/dist/rollup.js.map +1 -1
  43. package/dist/runtime/index.cjs +366 -8
  44. package/dist/runtime/index.cjs.map +1 -1
  45. package/dist/runtime/index.d.cts +11 -3
  46. package/dist/runtime/index.d.ts +11 -3
  47. package/dist/runtime/index.js +364 -8
  48. package/dist/runtime/index.js.map +1 -1
  49. package/dist/{types-D-lVfaDU.d.cts → types-CQHprSVk.d.cts} +10 -0
  50. package/dist/{types-D-lVfaDU.d.ts → types-CQHprSVk.d.ts} +10 -0
  51. package/dist/vite.cjs +2259 -385
  52. package/dist/vite.cjs.map +1 -1
  53. package/dist/vite.d.cts +1 -1
  54. package/dist/vite.d.ts +1 -1
  55. package/dist/vite.js +2258 -384
  56. package/dist/vite.js.map +1 -1
  57. package/dist/webpack.cjs +2259 -385
  58. package/dist/webpack.cjs.map +1 -1
  59. package/dist/webpack.d.cts +1 -1
  60. package/dist/webpack.d.ts +1 -1
  61. package/dist/webpack.js +2258 -384
  62. package/dist/webpack.js.map +1 -1
  63. package/package.json +1 -1
@@ -109,7 +109,7 @@ function scanClientBundles(outDir) {
109
109
  return [];
110
110
  }
111
111
  const results = [];
112
- function walk5(currentDir) {
112
+ function walk7(currentDir) {
113
113
  if (hasNextServerSegment(currentDir, resolvedOutDir)) {
114
114
  return;
115
115
  }
@@ -128,7 +128,7 @@ function scanClientBundles(outDir) {
128
128
  if (hasNextServerSegment(fullPath, resolvedOutDir)) {
129
129
  continue;
130
130
  }
131
- walk5(fullPath);
131
+ walk7(fullPath);
132
132
  } else if (entry.isFile()) {
133
133
  if (hasNextServerSegment(fullPath, resolvedOutDir)) {
134
134
  continue;
@@ -139,7 +139,7 @@ function scanClientBundles(outDir) {
139
139
  }
140
140
  }
141
141
  }
142
- walk5(resolvedOutDir);
142
+ walk7(resolvedOutDir);
143
143
  return results.sort();
144
144
  }
145
145
 
@@ -256,9 +256,6 @@ function relocateSourceMaps(outDir, cwd, keepPrivateMaps = true, privateMapsDir
256
256
  };
257
257
  }
258
258
 
259
- // src/ast/index.ts
260
- import { generate } from "astring";
261
-
262
259
  // src/ast/hot-path-detector.ts
263
260
  import * as acorn from "acorn";
264
261
  import * as walk from "acorn-walk";
@@ -273,7 +270,12 @@ var ARRAY_HOF_METHODS = /* @__PURE__ */ new Set([
273
270
  "some",
274
271
  "every"
275
272
  ]);
276
- var UI_HOOK_OR_RENDER_CALLS = /* @__PURE__ */ new Set([
273
+ var ANIMATION_FRAME_CALLS = /* @__PURE__ */ new Set([
274
+ "requestAnimationFrame",
275
+ "cancelAnimationFrame",
276
+ "useFrame"
277
+ ]);
278
+ var REACT_HOOK_OR_RENDER_CALLS = /* @__PURE__ */ new Set([
277
279
  "useState",
278
280
  "useEffect",
279
281
  "useMemo",
@@ -284,9 +286,7 @@ var UI_HOOK_OR_RENDER_CALLS = /* @__PURE__ */ new Set([
284
286
  "jsxs",
285
287
  "_jsx",
286
288
  "_jsxs",
287
- "createElement",
288
- "requestAnimationFrame",
289
- "cancelAnimationFrame"
289
+ "createElement"
290
290
  ]);
291
291
  var FUNCTION_NODE_TYPES = /* @__PURE__ */ new Set([
292
292
  "FunctionDeclaration",
@@ -321,8 +321,13 @@ function getFunctionLabel(node, ancestors) {
321
321
  if (parent.type === "VariableDeclarator" && parent.id?.type === "Identifier") {
322
322
  return parent.id.name;
323
323
  }
324
- if (parent.type === "Property" && parent.key?.type === "Identifier") {
325
- return parent.key.name;
324
+ if (parent.type === "Property") {
325
+ if (parent.key?.type === "Identifier") {
326
+ return parent.key.name;
327
+ }
328
+ if (parent.key?.type === "Literal" && typeof parent.key.value === "string") {
329
+ return parent.key.value;
330
+ }
326
331
  }
327
332
  if (parent.type === "MethodDefinition" && parent.key?.type === "Identifier") {
328
333
  return parent.key.name;
@@ -336,6 +341,9 @@ function getFunctionLabel(node, ancestors) {
336
341
  function isPascalCaseComponent(name) {
337
342
  return /^[A-Z][a-zA-Z0-9]*$/.test(name);
338
343
  }
344
+ function isEventHandlerName(name) {
345
+ return /^(?:on|handle)[A-Z]/.test(name);
346
+ }
339
347
  function findEnclosingScopeNode(ancestors, selfNode) {
340
348
  for (let i = ancestors.length - 1; i >= 0; i--) {
341
349
  const anc = ancestors[i];
@@ -345,12 +353,80 @@ function findEnclosingScopeNode(ancestors, selfNode) {
345
353
  }
346
354
  return ancestors[0];
347
355
  }
356
+ function findEnclosingFunction(ancestors, selfNode) {
357
+ for (let i = ancestors.length - 1; i >= 0; i--) {
358
+ if (ancestors[i] !== selfNode && FUNCTION_NODE_TYPES.has(ancestors[i].type)) {
359
+ return ancestors[i];
360
+ }
361
+ }
362
+ return null;
363
+ }
364
+ function findOutermostModuleFunction(ancestors) {
365
+ const fnList = [];
366
+ for (let i = 0; i < ancestors.length; i++) {
367
+ if (FUNCTION_NODE_TYPES.has(ancestors[i].type)) {
368
+ fnList.push(ancestors[i]);
369
+ }
370
+ }
371
+ if (fnList.length === 0) return null;
372
+ if (fnList.length === 1) return fnList[0];
373
+ return fnList[1];
374
+ }
375
+ function isZeroArgIifeFactoryFunction(node) {
376
+ if (!node || node.params && node.params.length > 0) return false;
377
+ if (!node.body || node.body.type !== "BlockStatement") return false;
378
+ const stmts = (node.body.body || []).filter(
379
+ (s) => !(s.type === "ExpressionStatement" && s.directive)
380
+ );
381
+ if (stmts.length !== 1 || stmts[0].type !== "ReturnStatement") return false;
382
+ const retArg = stmts[0].argument;
383
+ if (!retArg || retArg.type !== "CallExpression") return false;
384
+ const callee = retArg.callee;
385
+ return callee && (callee.type === "FunctionExpression" || callee.type === "ArrowFunctionExpression") && callee.body?.type === "BlockStatement";
386
+ }
387
+ function containsLoopOrAnimation(fnNode) {
388
+ let found = false;
389
+ walk.simple(fnNode, {
390
+ ForStatement() {
391
+ found = true;
392
+ },
393
+ ForInStatement() {
394
+ found = true;
395
+ },
396
+ ForOfStatement() {
397
+ found = true;
398
+ },
399
+ WhileStatement() {
400
+ found = true;
401
+ },
402
+ DoWhileStatement() {
403
+ found = true;
404
+ },
405
+ CallExpression(callNode) {
406
+ let cName = "";
407
+ let mProp = "";
408
+ if (callNode.callee?.type === "Identifier") {
409
+ cName = callNode.callee.name;
410
+ } else if (callNode.callee?.type === "MemberExpression" && !callNode.callee.computed && callNode.callee.property?.type === "Identifier") {
411
+ mProp = callNode.callee.property.name;
412
+ }
413
+ if (ANIMATION_FRAME_CALLS.has(cName) || ANIMATION_FRAME_CALLS.has(mProp)) {
414
+ found = true;
415
+ }
416
+ }
417
+ });
418
+ return found;
419
+ }
348
420
  function analyzeAstHotPaths(ast) {
349
421
  const hotFunctionNodes = /* @__PURE__ */ new WeakSet();
350
422
  const coldFunctionNodes = /* @__PURE__ */ new WeakSet();
351
423
  const hotExemptNodes = /* @__PURE__ */ new WeakSet();
424
+ const serializedFunctionNodes = /* @__PURE__ */ new WeakSet();
425
+ const serializedWorkerNodes = /* @__PURE__ */ new Set();
426
+ const trueHotNodes = /* @__PURE__ */ new Set();
427
+ const shallowComponentNodes = /* @__PURE__ */ new Set();
428
+ const coldForcedNodes = /* @__PURE__ */ new Set();
352
429
  const directHotNodes = /* @__PURE__ */ new Set();
353
- const serializedFunctionNodes = /* @__PURE__ */ new Set();
354
430
  const serializerHelperNodes = /* @__PURE__ */ new Set();
355
431
  const allFunctions = [];
356
432
  const fnByName = /* @__PURE__ */ new Map();
@@ -395,42 +471,12 @@ function analyzeAstHotPaths(ast) {
395
471
  return cur;
396
472
  }
397
473
  function markSerializedFunction(node) {
474
+ serializedWorkerNodes.add(node);
398
475
  serializedFunctionNodes.add(node);
399
476
  hotFunctionNodes.add(node);
400
477
  directHotNodes.add(node);
401
478
  hotExemptNodes.add(node);
402
479
  }
403
- function findEnclosingFunction(ancestors, selfNode) {
404
- for (let i = ancestors.length - 1; i >= 0; i--) {
405
- if (ancestors[i] !== selfNode && FUNCTION_NODE_TYPES.has(ancestors[i].type)) {
406
- return ancestors[i];
407
- }
408
- }
409
- return null;
410
- }
411
- function findOutermostModuleFunction(ancestors) {
412
- const fnList = [];
413
- for (let i = 0; i < ancestors.length; i++) {
414
- if (FUNCTION_NODE_TYPES.has(ancestors[i].type)) {
415
- fnList.push(ancestors[i]);
416
- }
417
- }
418
- if (fnList.length === 0) return null;
419
- if (fnList.length === 1) return fnList[0];
420
- return fnList[1];
421
- }
422
- function isZeroArgIifeFactoryFunction(node) {
423
- if (!node || node.params && node.params.length > 0) return false;
424
- if (!node.body || node.body.type !== "BlockStatement") return false;
425
- const stmts = (node.body.body || []).filter(
426
- (s) => !(s.type === "ExpressionStatement" && s.directive)
427
- );
428
- if (stmts.length !== 1 || stmts[0].type !== "ReturnStatement") return false;
429
- const retArg = stmts[0].argument;
430
- if (!retArg || retArg.type !== "CallExpression") return false;
431
- const callee = retArg.callee;
432
- return callee && (callee.type === "FunctionExpression" || callee.type === "ArrowFunctionExpression") && callee.body?.type === "BlockStatement";
433
- }
434
480
  function registerFunctionNode(node, ancestors) {
435
481
  const name = getFunctionLabel(node, ancestors);
436
482
  allFunctions.push({ node, name });
@@ -483,6 +529,7 @@ function analyzeAstHotPaths(ast) {
483
529
  }
484
530
  fnScopeChain.set(node, chain);
485
531
  if (isPascalCaseComponent(name)) {
532
+ shallowComponentNodes.add(node);
486
533
  hotFunctionNodes.add(node);
487
534
  directHotNodes.add(node);
488
535
  }
@@ -652,9 +699,15 @@ function analyzeAstHotPaths(ast) {
652
699
  const outerFn = findOutermostModuleFunction(ancestors);
653
700
  if (outerFn) markSerializedFunction(outerFn);
654
701
  }
655
- if (ARRAY_HOF_METHODS.has(memberProp) || calleeName === "requestAnimationFrame" || memberProp === "requestAnimationFrame" || calleeName === "cancelAnimationFrame" || memberProp === "cancelAnimationFrame") {
702
+ if (ANIMATION_FRAME_CALLS.has(calleeName) || ANIMATION_FRAME_CALLS.has(memberProp)) {
703
+ if (enclosingFn) {
704
+ trueHotNodes.add(enclosingFn);
705
+ hotFunctionNodes.add(enclosingFn);
706
+ directHotNodes.add(enclosingFn);
707
+ }
656
708
  for (const arg of node.arguments || []) {
657
709
  if (FUNCTION_NODE_TYPES.has(arg.type)) {
710
+ trueHotNodes.add(arg);
658
711
  hotFunctionNodes.add(arg);
659
712
  directHotNodes.add(arg);
660
713
  hotExemptNodes.add(arg);
@@ -667,8 +720,48 @@ function analyzeAstHotPaths(ast) {
667
720
  }
668
721
  }
669
722
  }
670
- if (UI_HOOK_OR_RENDER_CALLS.has(calleeName) || UI_HOOK_OR_RENDER_CALLS.has(memberProp)) {
723
+ if (ARRAY_HOF_METHODS.has(memberProp)) {
724
+ if (enclosingFn !== null) {
725
+ for (const arg of node.arguments || []) {
726
+ if (FUNCTION_NODE_TYPES.has(arg.type)) {
727
+ trueHotNodes.add(arg);
728
+ hotFunctionNodes.add(arg);
729
+ directHotNodes.add(arg);
730
+ hotExemptNodes.add(arg);
731
+ } else if (arg?.type === "Identifier") {
732
+ allCallSites.push({
733
+ scopeNode: currentScope,
734
+ calleeKey: arg.name,
735
+ args: [arg]
736
+ });
737
+ }
738
+ }
739
+ } else {
740
+ for (const arg of node.arguments || []) {
741
+ if (FUNCTION_NODE_TYPES.has(arg.type)) {
742
+ coldForcedNodes.add(arg);
743
+ }
744
+ }
745
+ }
746
+ }
747
+ if (calleeName === "useEffect" || memberProp === "useEffect" || calleeName === "useLayoutEffect" || memberProp === "useLayoutEffect") {
748
+ const effectArg = node.arguments?.[0];
749
+ if (effectArg && FUNCTION_NODE_TYPES.has(effectArg.type)) {
750
+ if (!containsLoopOrAnimation(effectArg)) {
751
+ coldForcedNodes.add(effectArg);
752
+ if (effectArg.body?.type === "BlockStatement") {
753
+ for (const s of effectArg.body.body || []) {
754
+ if (s.type === "ReturnStatement" && s.argument && FUNCTION_NODE_TYPES.has(s.argument.type) && !containsLoopOrAnimation(s.argument)) {
755
+ coldForcedNodes.add(s.argument);
756
+ }
757
+ }
758
+ }
759
+ }
760
+ }
761
+ }
762
+ if (REACT_HOOK_OR_RENDER_CALLS.has(calleeName) || REACT_HOOK_OR_RENDER_CALLS.has(memberProp)) {
671
763
  if (enclosingFn) {
764
+ shallowComponentNodes.add(enclosingFn);
672
765
  hotFunctionNodes.add(enclosingFn);
673
766
  directHotNodes.add(enclosingFn);
674
767
  }
@@ -676,23 +769,48 @@ function analyzeAstHotPaths(ast) {
676
769
  },
677
770
  ForStatement(node, _state, ancestors) {
678
771
  hotExemptNodes.add(node);
679
- markEnclosingFunctionHot(ancestors, hotFunctionNodes, directHotNodes);
772
+ const enc = findEnclosingFunction(ancestors);
773
+ if (enc) {
774
+ trueHotNodes.add(enc);
775
+ hotFunctionNodes.add(enc);
776
+ directHotNodes.add(enc);
777
+ }
680
778
  },
681
779
  ForInStatement(node, _state, ancestors) {
682
780
  hotExemptNodes.add(node);
683
- markEnclosingFunctionHot(ancestors, hotFunctionNodes, directHotNodes);
781
+ const enc = findEnclosingFunction(ancestors);
782
+ if (enc) {
783
+ trueHotNodes.add(enc);
784
+ hotFunctionNodes.add(enc);
785
+ directHotNodes.add(enc);
786
+ }
684
787
  },
685
788
  ForOfStatement(node, _state, ancestors) {
686
789
  hotExemptNodes.add(node);
687
- markEnclosingFunctionHot(ancestors, hotFunctionNodes, directHotNodes);
790
+ const enc = findEnclosingFunction(ancestors);
791
+ if (enc) {
792
+ trueHotNodes.add(enc);
793
+ hotFunctionNodes.add(enc);
794
+ directHotNodes.add(enc);
795
+ }
688
796
  },
689
797
  WhileStatement(node, _state, ancestors) {
690
798
  hotExemptNodes.add(node);
691
- markEnclosingFunctionHot(ancestors, hotFunctionNodes, directHotNodes);
799
+ const enc = findEnclosingFunction(ancestors);
800
+ if (enc) {
801
+ trueHotNodes.add(enc);
802
+ hotFunctionNodes.add(enc);
803
+ directHotNodes.add(enc);
804
+ }
692
805
  },
693
806
  DoWhileStatement(node, _state, ancestors) {
694
807
  hotExemptNodes.add(node);
695
- markEnclosingFunctionHot(ancestors, hotFunctionNodes, directHotNodes);
808
+ const enc = findEnclosingFunction(ancestors);
809
+ if (enc) {
810
+ trueHotNodes.add(enc);
811
+ hotFunctionNodes.add(enc);
812
+ directHotNodes.add(enc);
813
+ }
696
814
  }
697
815
  });
698
816
  for (const callSite of allCallSites) {
@@ -709,59 +827,113 @@ function analyzeAstHotPaths(ast) {
709
827
  markSerializedFunction(targetNode);
710
828
  }
711
829
  }
712
- const forwardHotSet = new Set(directHotNodes);
830
+ for (const fn of allFunctions) {
831
+ if (!trueHotNodes.has(fn.node) && !containsLoopOrAnimation(fn.node)) {
832
+ if (fn.node.async === true || isEventHandlerName(fn.name)) {
833
+ coldForcedNodes.add(fn.node);
834
+ }
835
+ }
836
+ }
713
837
  let forwardChanged = true;
714
838
  while (forwardChanged) {
715
839
  forwardChanged = false;
716
840
  for (const fn of allFunctions) {
717
- if (forwardHotSet.has(fn.node)) continue;
841
+ if (coldForcedNodes.has(fn.node)) continue;
718
842
  const chain = fnScopeChain.get(fn.node);
719
843
  if (!chain) continue;
720
844
  for (const anc of chain) {
721
- if (anc !== fn.node && (serializedFunctionNodes.has(anc) || forwardHotSet.has(anc))) {
722
- forwardHotSet.add(fn.node);
723
- hotFunctionNodes.add(fn.node);
724
- hotExemptNodes.add(fn.node);
725
- if (serializedFunctionNodes.has(anc)) {
845
+ if (anc === fn.node) continue;
846
+ if (serializedWorkerNodes.has(anc)) {
847
+ if (!serializedWorkerNodes.has(fn.node)) {
848
+ serializedWorkerNodes.add(fn.node);
726
849
  serializedFunctionNodes.add(fn.node);
850
+ hotFunctionNodes.add(fn.node);
851
+ hotExemptNodes.add(fn.node);
852
+ forwardChanged = true;
853
+ }
854
+ break;
855
+ }
856
+ const isModuleContainer = (fnScopeChain.get(anc)?.length ?? 0) <= 1;
857
+ if (trueHotNodes.has(anc) && !shallowComponentNodes.has(anc) && !isModuleContainer) {
858
+ if (!trueHotNodes.has(fn.node)) {
859
+ trueHotNodes.add(fn.node);
860
+ hotFunctionNodes.add(fn.node);
861
+ hotExemptNodes.add(fn.node);
862
+ forwardChanged = true;
727
863
  }
728
- forwardChanged = true;
729
864
  break;
730
865
  }
731
866
  }
732
867
  }
733
- for (const callerNode of Array.from(forwardHotSet)) {
868
+ for (const callerNode of Array.from(serializedWorkerNodes)) {
734
869
  const calleeNames = callerToCallees.get(callerNode);
735
870
  if (!calleeNames) continue;
736
871
  for (const cName of calleeNames) {
737
872
  const targetNode = resolveCalleeNode(callerNode, cName);
738
- if (targetNode && !forwardHotSet.has(targetNode)) {
739
- forwardHotSet.add(targetNode);
873
+ if (targetNode && !serializedWorkerNodes.has(targetNode) && !coldForcedNodes.has(targetNode)) {
874
+ serializedWorkerNodes.add(targetNode);
875
+ serializedFunctionNodes.add(targetNode);
876
+ hotFunctionNodes.add(targetNode);
877
+ hotExemptNodes.add(targetNode);
878
+ forwardChanged = true;
879
+ }
880
+ }
881
+ }
882
+ for (const callerNode of Array.from(trueHotNodes)) {
883
+ const calleeNames = callerToCallees.get(callerNode);
884
+ if (!calleeNames) continue;
885
+ for (const cName of calleeNames) {
886
+ const targetNode = resolveCalleeNode(callerNode, cName);
887
+ if (targetNode && !trueHotNodes.has(targetNode) && !coldForcedNodes.has(targetNode)) {
888
+ trueHotNodes.add(targetNode);
740
889
  hotFunctionNodes.add(targetNode);
741
890
  hotExemptNodes.add(targetNode);
742
- if (serializedFunctionNodes.has(callerNode)) {
743
- serializedFunctionNodes.add(targetNode);
744
- }
745
891
  forwardChanged = true;
746
892
  }
747
893
  }
748
894
  }
749
895
  }
896
+ const calleeToCallers = /* @__PURE__ */ new Map();
897
+ for (const [callerNode, calleeNames] of callerToCallees.entries()) {
898
+ for (const cName of calleeNames) {
899
+ const targetNode = resolveCalleeNode(callerNode, cName);
900
+ if (targetNode) {
901
+ let set = calleeToCallers.get(targetNode);
902
+ if (!set) {
903
+ set = /* @__PURE__ */ new Set();
904
+ calleeToCallers.set(targetNode, set);
905
+ }
906
+ set.add(callerNode);
907
+ }
908
+ }
909
+ }
750
910
  let changed = true;
751
911
  while (changed) {
752
912
  changed = false;
753
913
  for (const [callerNode, calleeNames] of callerToCallees.entries()) {
754
- if (hotFunctionNodes.has(callerNode)) continue;
914
+ if (hotFunctionNodes.has(callerNode) || shallowComponentNodes.has(callerNode) || coldForcedNodes.has(callerNode)) {
915
+ continue;
916
+ }
755
917
  for (const cName of calleeNames) {
756
918
  const targetNode = resolveCalleeNode(callerNode, cName);
757
- if (targetNode && hotFunctionNodes.has(targetNode)) {
758
- hotFunctionNodes.add(callerNode);
759
- changed = true;
760
- break;
919
+ if (targetNode && trueHotNodes.has(targetNode)) {
920
+ const callers = calleeToCallers.get(targetNode);
921
+ const isDedicatedPipeline = callers && callers.size <= 2;
922
+ if (isDedicatedPipeline) {
923
+ trueHotNodes.add(callerNode);
924
+ hotFunctionNodes.add(callerNode);
925
+ hotExemptNodes.add(callerNode);
926
+ changed = true;
927
+ break;
928
+ }
761
929
  }
762
930
  }
763
931
  }
764
932
  }
933
+ for (const node of coldForcedNodes) {
934
+ hotFunctionNodes.delete(node);
935
+ hotExemptNodes.delete(node);
936
+ }
765
937
  const hotFunctionsSkipped = [];
766
938
  const coldFunctionsProtected = [];
767
939
  for (const fn of allFunctions) {
@@ -780,56 +952,454 @@ function analyzeAstHotPaths(ast) {
780
952
  },
781
953
  hotFunctionNodes,
782
954
  coldFunctionNodes,
783
- hotExemptNodes
955
+ hotExemptNodes,
956
+ serializedFunctionNodes
784
957
  };
785
958
  }
786
- function markEnclosingFunctionHot(ancestors, hotSet, directHotSet) {
787
- for (let i = ancestors.length - 1; i >= 0; i--) {
788
- if (FUNCTION_NODE_TYPES.has(ancestors[i].type)) {
789
- hotSet.add(ancestors[i]);
790
- if (directHotSet) {
791
- directHotSet.add(ancestors[i]);
959
+
960
+ // src/ast/string-vault.ts
961
+ import * as acorn2 from "acorn";
962
+ import * as walk2 from "acorn-walk";
963
+
964
+ // src/ast/codegen.ts
965
+ import { generate, baseGenerator } from "astring";
966
+ function derivePolymorphicIdent(seed, role) {
967
+ let h = (2166136261 ^ seed >>> 0) >>> 0;
968
+ for (let i = 0; i < role.length; i++) {
969
+ h ^= role.charCodeAt(i);
970
+ h = Math.imul(h, 16777619) >>> 0;
971
+ }
972
+ const rolePrefixes = {
973
+ vault: "_a",
974
+ shield: "$b",
975
+ decoy: "_d",
976
+ shader: "_s",
977
+ vm: "_m",
978
+ wasm: "_w",
979
+ salted: "_k",
980
+ windowKey: "_z"
981
+ };
982
+ const prefix = rolePrefixes[role] ?? `_${String.fromCharCode(97 + h % 26)}`;
983
+ const suffix = ((h >>> 4) % 1296).toString(36).padStart(2, "0");
984
+ return `${prefix}${suffix}`;
985
+ }
986
+ var OPERATOR_PRECEDENCE = {
987
+ "||": 2,
988
+ "??": 3,
989
+ "&&": 4,
990
+ "|": 5,
991
+ "^": 6,
992
+ "&": 7,
993
+ "==": 8,
994
+ "!=": 8,
995
+ "===": 8,
996
+ "!==": 8,
997
+ "<": 9,
998
+ ">": 9,
999
+ "<=": 9,
1000
+ ">=": 9,
1001
+ "in": 9,
1002
+ "instanceof": 9,
1003
+ "<<": 10,
1004
+ ">>": 10,
1005
+ ">>>": 10,
1006
+ "+": 11,
1007
+ "-": 11,
1008
+ "*": 12,
1009
+ "%": 12,
1010
+ "/": 12,
1011
+ "**": 13
1012
+ };
1013
+ var NEEDS_PARENTHESES = 17;
1014
+ function expressionNeedsParenthesis(state, node, parentNode, isRightHand) {
1015
+ const nodePrecedence = state.expressionsPrecedence[node.type];
1016
+ if (nodePrecedence === NEEDS_PARENTHESES) {
1017
+ return true;
1018
+ }
1019
+ const parentNodePrecedence = state.expressionsPrecedence[parentNode.type];
1020
+ if (nodePrecedence !== parentNodePrecedence) {
1021
+ return !isRightHand && nodePrecedence === 15 && parentNodePrecedence === 14 && parentNode.operator === "**" || nodePrecedence < parentNodePrecedence;
1022
+ }
1023
+ if (nodePrecedence !== 13 && nodePrecedence !== 14) {
1024
+ return false;
1025
+ }
1026
+ if (node.operator === "**" && parentNode.operator === "**") {
1027
+ return !isRightHand;
1028
+ }
1029
+ if (nodePrecedence === 13 && parentNodePrecedence === 13 && (node.operator === "??" || parentNode.operator === "??")) {
1030
+ return true;
1031
+ }
1032
+ if (isRightHand) {
1033
+ return OPERATOR_PRECEDENCE[node.operator] <= OPERATOR_PRECEDENCE[parentNode.operator];
1034
+ }
1035
+ return OPERATOR_PRECEDENCE[node.operator] < OPERATOR_PRECEDENCE[parentNode.operator];
1036
+ }
1037
+ function formatExpression(state, node, parentNode, isRightHand) {
1038
+ const generator = state.generator;
1039
+ if (expressionNeedsParenthesis(state, node, parentNode, isRightHand)) {
1040
+ state.write("(");
1041
+ generator[node.type](node, state);
1042
+ state.write(")");
1043
+ } else {
1044
+ generator[node.type](node, state);
1045
+ }
1046
+ }
1047
+ function formatSequence(state, expressions) {
1048
+ const length = expressions.length;
1049
+ if (length > 0) {
1050
+ state.write("(");
1051
+ state.generator[expressions[0].type](expressions[0], state);
1052
+ for (let i = 1; i < length; i++) {
1053
+ state.write(",");
1054
+ state.generator[expressions[i].type](expressions[i], state);
1055
+ }
1056
+ state.write(")");
1057
+ } else {
1058
+ state.write("()");
1059
+ }
1060
+ }
1061
+ function expressionStartsWith(node, char) {
1062
+ if (!node) return false;
1063
+ if (node.type === "UnaryExpression" && node.prefix) {
1064
+ return node.operator === char;
1065
+ }
1066
+ if (node.type === "UpdateExpression" && node.prefix) {
1067
+ return node.operator[0] === char;
1068
+ }
1069
+ return false;
1070
+ }
1071
+ function expressionEndsWith(node, char) {
1072
+ if (!node) return false;
1073
+ if (node.type === "UpdateExpression" && !node.prefix) {
1074
+ return node.operator[0] === char;
1075
+ }
1076
+ return false;
1077
+ }
1078
+ function isRegExp(node) {
1079
+ return node && (node.type === "Literal" && !!node.regex || node.type === "RegExpLiteral");
1080
+ }
1081
+ var compactGenerator = Object.assign({}, baseGenerator, {
1082
+ BinaryExpression(node, state) {
1083
+ const isIn = node.operator === "in";
1084
+ if (isIn) {
1085
+ state.write("(");
1086
+ }
1087
+ formatExpression(state, node.left, node, false);
1088
+ const op = node.operator;
1089
+ let spaceBefore = false;
1090
+ let spaceAfter = false;
1091
+ if (op === "in" || op === "instanceof") {
1092
+ spaceBefore = true;
1093
+ spaceAfter = true;
1094
+ } else {
1095
+ if ((op === "+" || op === "-") && expressionEndsWith(node.left, op) && !expressionNeedsParenthesis(state, node.left, node, false)) {
1096
+ spaceBefore = true;
1097
+ }
1098
+ if ((op === "+" || op === "-") && expressionStartsWith(node.right, op) && !expressionNeedsParenthesis(state, node.right, node, true) || op === "/" && isRegExp(node.right)) {
1099
+ spaceAfter = true;
1100
+ }
1101
+ }
1102
+ if (spaceBefore) state.write(" ");
1103
+ state.write(op);
1104
+ if (spaceAfter) state.write(" ");
1105
+ formatExpression(state, node.right, node, true);
1106
+ if (isIn) {
1107
+ state.write(")");
1108
+ }
1109
+ },
1110
+ LogicalExpression(node, state) {
1111
+ formatExpression(state, node.left, node, false);
1112
+ state.write(node.operator);
1113
+ formatExpression(state, node.right, node, true);
1114
+ },
1115
+ AssignmentExpression(node, state) {
1116
+ this[node.left.type](node.left, state);
1117
+ const op = node.operator;
1118
+ if (op.endsWith("+") && expressionStartsWith(node.right, "+") || op.endsWith("-") && expressionStartsWith(node.right, "-") || op.endsWith("/") && isRegExp(node.right)) {
1119
+ state.write(op + " ");
1120
+ } else {
1121
+ state.write(op);
1122
+ }
1123
+ this[node.right.type](node.right, state);
1124
+ },
1125
+ ConditionalExpression(node, state) {
1126
+ const test = node.test;
1127
+ const precedence = state.expressionsPrecedence[test.type];
1128
+ if (precedence === NEEDS_PARENTHESES || precedence <= state.expressionsPrecedence.ConditionalExpression) {
1129
+ state.write("(");
1130
+ this[test.type](test, state);
1131
+ state.write(")");
1132
+ } else {
1133
+ this[test.type](test, state);
1134
+ }
1135
+ state.write("?");
1136
+ this[node.consequent.type](node.consequent, state);
1137
+ state.write(":");
1138
+ this[node.alternate.type](node.alternate, state);
1139
+ },
1140
+ ArrayExpression(node, state) {
1141
+ state.write("[");
1142
+ const elements = node.elements;
1143
+ const length = elements.length;
1144
+ for (let i = 0; i < length; i++) {
1145
+ const element = elements[i];
1146
+ if (element != null) {
1147
+ this[element.type](element, state);
1148
+ }
1149
+ if (i + 1 < length) {
1150
+ state.write(",");
1151
+ }
1152
+ }
1153
+ state.write("]");
1154
+ },
1155
+ ObjectExpression(node, state) {
1156
+ state.write("{");
1157
+ const properties = node.properties;
1158
+ const length = properties.length;
1159
+ for (let i = 0; i < length; i++) {
1160
+ const property = properties[i];
1161
+ this[property.type](property, state);
1162
+ if (i + 1 < length) {
1163
+ state.write(",");
1164
+ }
1165
+ }
1166
+ state.write("}");
1167
+ },
1168
+ Property(node, state) {
1169
+ if (node.method || node.kind[0] !== "i") {
1170
+ this.MethodDefinition(node, state);
1171
+ } else {
1172
+ if (!node.shorthand) {
1173
+ if (node.computed) {
1174
+ state.write("[");
1175
+ this[node.key.type](node.key, state);
1176
+ state.write("]");
1177
+ } else {
1178
+ this[node.key.type](node.key, state);
1179
+ }
1180
+ state.write(":");
1181
+ }
1182
+ this[node.value.type](node.value, state);
1183
+ }
1184
+ },
1185
+ CallExpression(node, state) {
1186
+ formatExpression(state, node.callee, node, false);
1187
+ if (node.optional) {
1188
+ state.write("?.");
1189
+ }
1190
+ formatSequence(state, node.arguments);
1191
+ },
1192
+ SequenceExpression(node, state) {
1193
+ formatSequence(state, node.expressions);
1194
+ },
1195
+ FunctionDeclaration(node, state) {
1196
+ state.write(
1197
+ (node.async ? "async " : "") + (node.generator ? "function* " : "function ") + (node.id ? node.id.name : ""),
1198
+ node
1199
+ );
1200
+ formatSequence(state, node.params);
1201
+ this[node.body.type](node.body, state);
1202
+ },
1203
+ FunctionExpression(node, state) {
1204
+ compactGenerator.FunctionDeclaration.call(this, node, state);
1205
+ },
1206
+ ArrowFunctionExpression(node, state) {
1207
+ state.write(node.async ? "async " : "", node);
1208
+ const params = node.params;
1209
+ if (params != null) {
1210
+ if (params.length === 0) {
1211
+ state.write("()");
1212
+ } else if (params.length === 1 && params[0].type === "Identifier") {
1213
+ state.write(params[0].name, params[0]);
1214
+ } else {
1215
+ formatSequence(state, node.params);
1216
+ }
1217
+ } else {
1218
+ state.write("()");
1219
+ }
1220
+ state.write("=>");
1221
+ if (node.body.type[0] === "O") {
1222
+ state.write("(");
1223
+ this.ObjectExpression(node.body, state);
1224
+ state.write(")");
1225
+ } else {
1226
+ this[node.body.type](node.body, state);
1227
+ }
1228
+ },
1229
+ ForStatement(node, state) {
1230
+ state.write("for(");
1231
+ if (node.init != null) {
1232
+ const init = node.init;
1233
+ if (init.type[0] === "V") {
1234
+ this.VariableDeclaration(init, state);
1235
+ } else {
1236
+ this[init.type](init, state);
1237
+ state.write(";");
1238
+ }
1239
+ } else {
1240
+ state.write(";");
1241
+ }
1242
+ if (node.test) {
1243
+ this[node.test.type](node.test, state);
1244
+ }
1245
+ state.write(";");
1246
+ if (node.update) {
1247
+ this[node.update.type](node.update, state);
1248
+ }
1249
+ state.write(")");
1250
+ this[node.body.type](node.body, state);
1251
+ },
1252
+ IfStatement(node, state) {
1253
+ state.write("if(");
1254
+ this[node.test.type](node.test, state);
1255
+ state.write(")");
1256
+ this[node.consequent.type](node.consequent, state);
1257
+ if (node.alternate != null) {
1258
+ if (node.consequent.type === "BlockStatement") {
1259
+ state.write("else");
1260
+ } else {
1261
+ state.write(" else");
1262
+ }
1263
+ if (node.alternate.type === "BlockStatement") {
1264
+ this[node.alternate.type](node.alternate, state);
1265
+ } else if (node.alternate.type === "IfStatement") {
1266
+ state.write(" ");
1267
+ this[node.alternate.type](node.alternate, state);
1268
+ } else {
1269
+ state.write(" ");
1270
+ this[node.alternate.type](node.alternate, state);
1271
+ }
1272
+ }
1273
+ },
1274
+ VariableDeclaration(node, state) {
1275
+ state.write(node.kind + " ");
1276
+ const declarations = node.declarations;
1277
+ const length = declarations.length;
1278
+ for (let i = 0; i < length; i++) {
1279
+ this.VariableDeclarator(declarations[i], state);
1280
+ if (i + 1 < length) {
1281
+ state.write(",");
792
1282
  }
793
- break;
794
1283
  }
1284
+ state.write(";");
1285
+ },
1286
+ VariableDeclarator(node, state) {
1287
+ this[node.id.type](node.id, state);
1288
+ if (node.init != null) {
1289
+ state.write("=");
1290
+ this[node.init.type](node.init, state);
1291
+ }
1292
+ },
1293
+ ReturnStatement(node, state) {
1294
+ state.write("return");
1295
+ if (node.argument) {
1296
+ state.write(" ");
1297
+ this[node.argument.type](node.argument, state);
1298
+ }
1299
+ state.write(";");
1300
+ }
1301
+ });
1302
+ function generateCompactJs(ast) {
1303
+ return generate(ast, {
1304
+ generator: compactGenerator,
1305
+ indent: "",
1306
+ lineEnd: ""
1307
+ });
1308
+ }
1309
+
1310
+ // src/runtime/integrity-guard.ts
1311
+ var FNV_OFFSET_BASIS = 2166136261;
1312
+ var FNV_PRIME = 16777619;
1313
+ function computeIntegrityHash(source, seed = 0) {
1314
+ let hash = (FNV_OFFSET_BASIS ^ seed >>> 0) >>> 0;
1315
+ for (let i = 0; i < source.length; i++) {
1316
+ hash ^= source.charCodeAt(i);
1317
+ hash = Math.imul(hash, FNV_PRIME) >>> 0;
795
1318
  }
1319
+ return hash >>> 0;
1320
+ }
1321
+
1322
+ // src/runtime/devtools-deterrent.ts
1323
+ function deriveIntegrityFnName(seed) {
1324
+ return derivePolymorphicIdent(seed, "shield");
1325
+ }
1326
+ function deriveWindowKeySymbol(seed) {
1327
+ return derivePolymorphicIdent(seed, "windowKey");
1328
+ }
1329
+ function createDeterrentSnippet(config) {
1330
+ const seed = config.seed >>> 0;
1331
+ const deterrentMode = config.deterrentMode ?? "passive";
1332
+ const fnName = deriveIntegrityFnName(seed);
1333
+ const sym = config.windowKeySymbol ?? deriveWindowKeySymbol(seed);
1334
+ const consoleSilence = deterrentMode === "gradual" ? "for(var k in console)console[k]=function(){return 0;};" : "";
1335
+ return `(function ${fnName}(w){if(w){try{var s=Function.prototype.toString,n=w.navigator||0,src=s.call(${fnName}),t=s.call(s).indexOf('[native code]')<0||/\\n/.test(src)||n.webdriver||/HeadlessChrome/.test(n.userAgent);for(var h=0x811c9dc5,i=0;i<src.length;i++)h=Math.imul(h^src.charCodeAt(i),0x01000193)>>>0;var d=(h&31);if(t){w.__unpeek_tampered=!0;w.__unpeek_seed=((w.__unpeek_seed||${seed})^1)>>>0;String.prototype._u=14;w['${sym}']=d^29;try{${consoleSilence}w.dispatchEvent(new CustomEvent('unpeek:tamper'));}catch(e){}}else{w['${sym}']=d;}}catch(e){}}})(typeof window!=='undefined'&&window);`;
1336
+ }
1337
+
1338
+ // src/runtime/index.ts
1339
+ function generateRuntimeShield(config) {
1340
+ const seed = config.seed >>> 0;
1341
+ const windowKeySymbol = config.windowKeySymbol ?? deriveWindowKeySymbol(seed);
1342
+ const integrityCheckFnName = deriveIntegrityFnName(seed);
1343
+ const preambleCode = createDeterrentSnippet({
1344
+ ...config,
1345
+ windowKeySymbol
1346
+ });
1347
+ const fnStart = preambleCode.indexOf("function");
1348
+ const fnEnd = preambleCode.lastIndexOf("(") - 1;
1349
+ const fnDecl = preambleCode.slice(fnStart, fnEnd);
1350
+ const computedHash = computeIntegrityHash(fnDecl, 0);
1351
+ const expectedHash = config.expectedIntegrityHash !== void 0 ? config.expectedIntegrityHash >>> 0 : computedHash;
1352
+ const expectedDelta = config.expectedDelta !== void 0 ? config.expectedDelta & 31 : computedHash >>> 0 & 31;
1353
+ return {
1354
+ preambleCode,
1355
+ integrityCheckFnName,
1356
+ expectedHash,
1357
+ windowKeySymbol,
1358
+ expectedDelta
1359
+ };
796
1360
  }
797
1361
 
798
1362
  // src/ast/string-vault.ts
799
- import * as acorn2 from "acorn";
800
- import * as walk2 from "acorn-walk";
1363
+ var SAFE_ALPHA = " !#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_abcdefghijklmnopqrstuvwxyz{|}~";
801
1364
  var DIRECTIVE_STRINGS = /* @__PURE__ */ new Set([
802
1365
  "use strict",
803
1366
  "use client",
804
1367
  "use server",
805
1368
  "use asm"
806
1369
  ]);
807
- var HELPER_TEMPLATE = acorn2.parse(
808
- `var _ = (function f(a){return a.map(function(s){var o="";for(var j=0;j<s.length;j++)o+=String.fromCharCode(s.charCodeAt(j)^(((0^((a._u||/\\n/.test(f)*14)|((j&1)*0)))&30)|1));return o;});})([]);`,
809
- { ecmaVersion: "latest", sourceType: "script" }
810
- ).body[0];
811
- function createVaultHelperAst(cacheVarName, encryptedPayloads, mask, step) {
812
- const node = structuredClone(HELPER_TEMPLATE);
813
- node.declarations[0].id.name = cacheVarName;
814
- node.declarations[0].init.arguments[0].elements = encryptedPayloads.map(
815
- (str) => ({
816
- type: "Literal",
817
- value: str,
818
- raw: JSON.stringify(str)
819
- })
820
- );
821
- const outerFn = node.declarations[0].init.callee;
822
- const returnStmt = outerFn.body.body[0];
823
- const innerFn = returnStmt.argument.arguments[0];
824
- const forStmt = innerFn.body.body[1];
825
- const expr = forStmt.body.type === "BlockStatement" ? forStmt.body.body[0].expression : forStmt.body.expression;
826
- const binaryXor = expr.right.arguments[0];
827
- const innerLeft = binaryXor.right.left.left;
828
- innerLeft.left.value = mask;
829
- innerLeft.left.raw = String(mask);
830
- innerLeft.right.right.right.value = step;
831
- innerLeft.right.right.right.raw = String(step);
832
- return node;
1370
+ var STANDARD_PROP_KEYS = /* @__PURE__ */ new Set([
1371
+ "id",
1372
+ "type",
1373
+ "key",
1374
+ "ref",
1375
+ "className",
1376
+ "style",
1377
+ "name",
1378
+ "value",
1379
+ "children",
1380
+ "src",
1381
+ "href",
1382
+ "alt",
1383
+ "role",
1384
+ "tabIndex"
1385
+ ]);
1386
+ var TAILWIND_TOKEN_RE = /^(?:flex|grid|block|inline|hidden|relative|absolute|fixed|w-|h-|min-|max-|p[xytrbl]?-|m[xytrbl]?-|space-[xy]-|text-|font-|bg-|border|rounded|shadow|ring|outline|transition|duration|opacity|cursor|pointer-events|select-|items-|justify-|gap-|overflow-|z-|inset-|top-|left-|right-|bottom-|hover:|focus:|focus-visible:|disabled:|dark:|data-\[|aria-|\[&_)/;
1387
+ var SVG_PATH_RE = /^[Mm]\s*-?\d+(?:\.\d+)?[\s,]+-?\d+/;
1388
+ var SHADER_SIG_RE = /@group|@binding|@vertex|@fragment|@compute|vec4f|gl_Position|uniform/;
1389
+ function shouldEncryptString(val, minLen) {
1390
+ if (val.length < minLen || DIRECTIVE_STRINGS.has(val)) return false;
1391
+ if (SVG_PATH_RE.test(val)) return false;
1392
+ if (val.includes(" ")) {
1393
+ const tokens = val.trim().split(/\s+/);
1394
+ if (tokens.length >= 3) {
1395
+ let twHits = 0;
1396
+ for (const t of tokens) {
1397
+ if (TAILWIND_TOKEN_RE.test(t)) twHits++;
1398
+ }
1399
+ if (twHits / tokens.length >= 0.5) return false;
1400
+ }
1401
+ }
1402
+ return true;
833
1403
  }
834
1404
  function computeFnv1aHash(input, seed = 2166136261) {
835
1405
  let hash = seed >>> 0;
@@ -839,31 +1409,127 @@ function computeFnv1aHash(input, seed = 2166136261) {
839
1409
  }
840
1410
  return hash >>> 0;
841
1411
  }
842
- function encodeStringWithSeed(str, mask, step) {
1412
+ function createPermutationTable(seed) {
1413
+ let s = (seed || 305419896) >>> 0;
1414
+ function xorshift() {
1415
+ s ^= s << 13;
1416
+ s ^= s >>> 17;
1417
+ s ^= s << 5;
1418
+ return s >>> 0;
1419
+ }
1420
+ const indices = [];
1421
+ for (let i = 0; i < 92; i++) indices.push(i);
1422
+ for (let i = 91; i > 0; i--) {
1423
+ const j = xorshift() % (i + 1);
1424
+ const tmp = indices[i];
1425
+ indices[i] = indices[j];
1426
+ indices[j] = tmp;
1427
+ }
1428
+ const B = new Array(92);
1429
+ for (let i = 0; i < 46; i++) {
1430
+ const a = indices[2 * i];
1431
+ const b = indices[2 * i + 1];
1432
+ B[a] = b;
1433
+ B[b] = a;
1434
+ }
1435
+ let P_CHARS = "";
1436
+ for (let i = 0; i < 92; i++) {
1437
+ P_CHARS += SAFE_ALPHA[B[i]];
1438
+ }
1439
+ return P_CHARS;
1440
+ }
1441
+ function encodeStringWithSeed(str, P_CHARS, expectedRot) {
843
1442
  let out = "";
844
1443
  for (let i = 0; i < str.length; i++) {
845
- const code = str.charCodeAt(i);
846
- const k = (mask ^ (i & 1) * step) & 30 | 1;
847
- out += String.fromCharCode(code ^ k);
1444
+ const c = str.charAt(i);
1445
+ const k = SAFE_ALPHA.indexOf(c);
1446
+ if (k < 0) {
1447
+ out += c;
1448
+ } else {
1449
+ const y = (k + expectedRot) % 92;
1450
+ const z = SAFE_ALPHA.indexOf(P_CHARS.charAt(y));
1451
+ out += SAFE_ALPHA.charAt((z - expectedRot + 92) % 92);
1452
+ }
848
1453
  }
849
1454
  return out;
850
1455
  }
851
- function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExemptNodes) {
1456
+ function createVaultHelperAst(cacheVarName, encryptedPayloads, fnAst) {
1457
+ return {
1458
+ type: "VariableDeclaration",
1459
+ kind: "var",
1460
+ declarations: [
1461
+ {
1462
+ type: "VariableDeclarator",
1463
+ id: { type: "Identifier", name: cacheVarName },
1464
+ init: {
1465
+ type: "CallExpression",
1466
+ callee: fnAst,
1467
+ arguments: [
1468
+ {
1469
+ type: "ArrayExpression",
1470
+ elements: encryptedPayloads.map((str) => ({
1471
+ type: "Literal",
1472
+ value: str,
1473
+ raw: JSON.stringify(str)
1474
+ }))
1475
+ }
1476
+ ],
1477
+ optional: false
1478
+ }
1479
+ }
1480
+ ]
1481
+ };
1482
+ }
1483
+ function createShaderVaultAst(shaderVarName, shaderPayloads, seed) {
1484
+ const b64List = [];
1485
+ const key = seed >>> 0 & 255 ^ 90;
1486
+ for (let idx = 0; idx < shaderPayloads.length; idx++) {
1487
+ const str = shaderPayloads[idx];
1488
+ const buf = Buffer.from(str, "utf8");
1489
+ for (let i = 0; i < buf.length; i++) {
1490
+ buf[i] ^= key;
1491
+ }
1492
+ b64List.push(buf.toString("base64"));
1493
+ }
1494
+ const shaderCode = `var ${shaderVarName} = (function(){var B=${JSON.stringify(
1495
+ b64List
1496
+ )};var k=${key};var b=B.map(function(s){var bin=typeof atob==='function'?atob(s):(typeof Buffer!=='undefined'?Buffer.from(s,'base64').toString('binary'):'');var u=new Uint8Array(bin.length);for(var i=0;i<bin.length;i++)u[i]=bin.charCodeAt(i);return u;});var d=typeof TextDecoder!=='undefined'?new TextDecoder():null;return function(i){var u=b[i];for(var j=0;j<u.length;j++)u[j]^=k;try{return d?d.decode(u):String.fromCharCode.apply(null,u);}finally{for(var j=0;j<u.length;j++)u[j]^=k;}};})();`;
1497
+ return acorn2.parse(shaderCode, { ecmaVersion: "latest", sourceType: "script" }).body[0];
1498
+ }
1499
+ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExemptNodes, windowKeySymbol, expectedDelta) {
1500
+ const cacheVarName = derivePolymorphicIdent(seed, "vault");
1501
+ const shaderVarName = derivePolymorphicIdent(seed, "shader");
1502
+ const sym = windowKeySymbol ?? deriveWindowKeySymbol(seed);
1503
+ let expDelta = expectedDelta;
1504
+ if (expDelta === void 0) {
1505
+ const shield = generateRuntimeShield({ seed, windowKeySymbol: sym });
1506
+ expDelta = shield.expectedDelta ?? 0;
1507
+ }
852
1508
  const alreadyVaulted = ast.body.some(
853
1509
  (stmt) => stmt.type === "VariableDeclaration" && stmt.declarations?.some(
854
- (d) => d.id?.type === "Identifier" && typeof d.id.name === "string" && d.id.name.startsWith("_uC")
1510
+ (d) => d.id?.type === "Identifier" && typeof d.id.name === "string" && (d.id.name.startsWith("_uC") || d.id.name === cacheVarName || d.init?.type === "CallExpression" && d.init.callee?.type === "FunctionExpression" && d.init.callee?.id?.name === "f" && d.init.arguments?.[0]?.type === "ArrayExpression")
855
1511
  )
856
1512
  );
857
1513
  if (alreadyVaulted) {
858
1514
  return {
859
1515
  encryptedStringsCount: 0,
860
- integrityToken: computeFnv1aHash("already-vaulted", seed)
1516
+ integrityToken: computeFnv1aHash("already-vaulted", seed),
1517
+ shaderBuffersCount: 0
861
1518
  };
862
1519
  }
863
- const mask = seed >>> 0 & 30 | 3;
864
- const step = 1;
1520
+ const P_CHARS = createPermutationTable(seed);
1521
+ const fBody = `var s=Function.prototype.toString,w=typeof window!=='undefined'&&window,src=s.call(f);for(var h=0x811c9dc5,i=0;i<src.length;i++)h=Math.imul(h^src.charCodeAt(i),0x01000193)>>>0;var rot=(h^(a._u||0)^(w&&w['${sym}']!=null?w['${sym}']:${expDelta}))&31;var A="${SAFE_ALPHA}";var P="${P_CHARS}";return a.map(function(s){var o="";for(var j=0;j<s.length;j++){var c=s.charAt(j),k=A.indexOf(c);if(k<0){o+=c;}else{var y=(k+rot)%92;var z=A.indexOf(P.charAt(y));o+=A.charAt((z-rot+92)%92);}}return o;});`;
1522
+ const fnAst = acorn2.parse(`(function f(a){${fBody}})`, {
1523
+ ecmaVersion: "latest",
1524
+ sourceType: "script"
1525
+ }).body[0].expression;
1526
+ const compactFnStr = generateCompactJs(fnAst);
1527
+ const buildH = computeIntegrityHash(compactFnStr, 0);
1528
+ const expectedRot = (buildH ^ 0 ^ expDelta) & 31;
865
1529
  const stringToIndex = /* @__PURE__ */ new Map();
866
1530
  const encryptedPayloads = [];
1531
+ const shaderToIndex = /* @__PURE__ */ new Map();
1532
+ const shaderPayloads = [];
867
1533
  const targetsToReplace = [];
868
1534
  const customWalkBase = {
869
1535
  ...walk2.base,
@@ -878,7 +1544,6 @@ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExempt
878
1544
  Literal(node, _state, ancestors) {
879
1545
  if (typeof node.value !== "string") return;
880
1546
  const val = node.value;
881
- if (val.length < minStringLength) return;
882
1547
  if (DIRECTIVE_STRINGS.has(val)) return;
883
1548
  if (hotExemptNodes) {
884
1549
  for (let i = ancestors.length - 2; i >= 0; i--) {
@@ -896,59 +1561,125 @@ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExempt
896
1561
  if ((parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") && parent.key === node && !parent.computed) {
897
1562
  return;
898
1563
  }
899
- if (parent.type === "Property" && parent.key === node) {
900
- parent.computed = true;
901
- }
902
1564
  if (parent.type === "ImportAttribute" || parent.type === "ImportSpecifier" || parent.type === "ExportSpecifier") {
903
1565
  return;
904
1566
  }
905
- let idx = stringToIndex.get(val);
906
- if (idx === void 0) {
907
- idx = encryptedPayloads.length;
908
- stringToIndex.set(val, idx);
909
- encryptedPayloads.push(encodeStringWithSeed(val, mask, step));
1567
+ if (parent.type === "Property" && parent.key === node && !parent.computed) {
1568
+ if (STANDARD_PROP_KEYS.has(val)) {
1569
+ return;
1570
+ }
1571
+ }
1572
+ const isShader = val.length >= 256 || SHADER_SIG_RE.test(val);
1573
+ if (isShader) {
1574
+ let idx = shaderToIndex.get(val);
1575
+ if (idx === void 0) {
1576
+ idx = shaderPayloads.length;
1577
+ shaderToIndex.set(val, idx);
1578
+ shaderPayloads.push(val);
1579
+ }
1580
+ targetsToReplace.push({ type: "shader", node, parent, idx });
1581
+ } else {
1582
+ if (!shouldEncryptString(val, minStringLength)) return;
1583
+ let idx = stringToIndex.get(val);
1584
+ if (idx === void 0) {
1585
+ idx = encryptedPayloads.length;
1586
+ stringToIndex.set(val, idx);
1587
+ encryptedPayloads.push(
1588
+ encodeStringWithSeed(val, P_CHARS, expectedRot)
1589
+ );
1590
+ }
1591
+ targetsToReplace.push({ type: "string", node, parent, idx });
1592
+ }
1593
+ },
1594
+ TemplateLiteral(node, _state, ancestors) {
1595
+ if (!node.quasis || node.quasis.length !== 1) return;
1596
+ if (node.expressions && node.expressions.length !== 0) return;
1597
+ if (hotExemptNodes) {
1598
+ for (let i = ancestors.length - 2; i >= 0; i--) {
1599
+ if (hotExemptNodes.has(ancestors[i])) {
1600
+ return;
1601
+ }
1602
+ }
1603
+ }
1604
+ const parent = ancestors[ancestors.length - 2];
1605
+ if (!parent) return;
1606
+ const val = node.quasis[0].value.cooked ?? node.quasis[0].value.raw;
1607
+ if (typeof val !== "string" || DIRECTIVE_STRINGS.has(val)) return;
1608
+ const isShader = val.length >= 256 || SHADER_SIG_RE.test(val);
1609
+ if (isShader) {
1610
+ let idx = shaderToIndex.get(val);
1611
+ if (idx === void 0) {
1612
+ idx = shaderPayloads.length;
1613
+ shaderToIndex.set(val, idx);
1614
+ shaderPayloads.push(val);
1615
+ }
1616
+ targetsToReplace.push({ type: "shader", node, parent, idx });
1617
+ } else {
1618
+ if (!shouldEncryptString(val, minStringLength)) return;
1619
+ let idx = stringToIndex.get(val);
1620
+ if (idx === void 0) {
1621
+ idx = encryptedPayloads.length;
1622
+ stringToIndex.set(val, idx);
1623
+ encryptedPayloads.push(
1624
+ encodeStringWithSeed(val, P_CHARS, expectedRot)
1625
+ );
1626
+ }
1627
+ targetsToReplace.push({ type: "string", node, parent, idx });
910
1628
  }
911
- targetsToReplace.push({ node, parent });
912
1629
  }
913
1630
  },
914
1631
  customWalkBase
915
1632
  );
916
- if (targetsToReplace.length === 0 || encryptedPayloads.length === 0) {
1633
+ if (targetsToReplace.length === 0) {
917
1634
  return {
918
1635
  encryptedStringsCount: 0,
919
- integrityToken: computeFnv1aHash("empty", seed)
1636
+ integrityToken: computeFnv1aHash("empty", seed),
1637
+ shaderBuffersCount: 0
920
1638
  };
921
1639
  }
922
1640
  const serializedTable = JSON.stringify(encryptedPayloads);
923
1641
  const integrityToken = computeFnv1aHash(serializedTable, seed);
924
- const suffix = computeFnv1aHash(`vault:${seed}`, integrityToken).toString(36);
925
- const cacheVarName = `_uC${suffix}`;
926
- for (const { node, parent } of targetsToReplace) {
1642
+ for (const { type, node, parent, idx } of targetsToReplace) {
927
1643
  if (parent?.type === "Property" && parent.key === node) {
928
1644
  parent.computed = true;
929
1645
  }
930
- const idx = stringToIndex.get(node.value);
931
- node.type = "MemberExpression";
932
- node.object = {
933
- type: "Identifier",
934
- name: cacheVarName
935
- };
936
- node.property = {
937
- type: "Literal",
938
- value: idx,
939
- raw: String(idx)
940
- };
941
- node.computed = true;
942
- node.optional = false;
943
- delete node.value;
944
- delete node.raw;
945
- }
946
- const helperStmt = createVaultHelperAst(
947
- cacheVarName,
948
- encryptedPayloads,
949
- mask,
950
- step
951
- );
1646
+ if (type === "shader") {
1647
+ node.type = "CallExpression";
1648
+ node.callee = {
1649
+ type: "Identifier",
1650
+ name: shaderVarName
1651
+ };
1652
+ node.arguments = [
1653
+ {
1654
+ type: "Literal",
1655
+ value: idx,
1656
+ raw: String(idx)
1657
+ }
1658
+ ];
1659
+ node.optional = false;
1660
+ delete node.value;
1661
+ delete node.raw;
1662
+ delete node.quasis;
1663
+ delete node.expressions;
1664
+ } else {
1665
+ node.type = "MemberExpression";
1666
+ node.object = {
1667
+ type: "Identifier",
1668
+ name: cacheVarName
1669
+ };
1670
+ node.property = {
1671
+ type: "Literal",
1672
+ value: idx,
1673
+ raw: String(idx)
1674
+ };
1675
+ node.computed = true;
1676
+ node.optional = false;
1677
+ delete node.value;
1678
+ delete node.raw;
1679
+ delete node.quasis;
1680
+ delete node.expressions;
1681
+ }
1682
+ }
952
1683
  let insertIdx = 0;
953
1684
  while (insertIdx < ast.body.length) {
954
1685
  const stmt = ast.body[insertIdx];
@@ -959,10 +1690,26 @@ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExempt
959
1690
  break;
960
1691
  }
961
1692
  }
962
- ast.body.splice(insertIdx, 0, helperStmt);
1693
+ if (encryptedPayloads.length > 0) {
1694
+ const vaultHelperStmt = createVaultHelperAst(
1695
+ cacheVarName,
1696
+ encryptedPayloads,
1697
+ fnAst
1698
+ );
1699
+ ast.body.splice(insertIdx++, 0, vaultHelperStmt);
1700
+ }
1701
+ if (shaderPayloads.length > 0) {
1702
+ const shaderHelperStmt = createShaderVaultAst(
1703
+ shaderVarName,
1704
+ shaderPayloads,
1705
+ seed
1706
+ );
1707
+ ast.body.splice(insertIdx++, 0, shaderHelperStmt);
1708
+ }
963
1709
  return {
964
1710
  encryptedStringsCount: encryptedPayloads.length,
965
- integrityToken
1711
+ integrityToken,
1712
+ shaderBuffersCount: shaderPayloads.length
966
1713
  };
967
1714
  }
968
1715
 
@@ -1061,9 +1808,9 @@ function collectPatternTargets(pattern, out, shorthandProp) {
1061
1808
  }
1062
1809
  }
1063
1810
  function isMangleableName(origName) {
1064
- return !RESERVED_IDENTIFIERS.has(origName) && !origName.startsWith("_u") && !origName.startsWith("_0x");
1811
+ return origName.length > 2 && !RESERVED_IDENTIFIERS.has(origName) && !origName.startsWith("_u") && !origName.startsWith("_0x") && !origName.startsWith("$$");
1065
1812
  }
1066
- function applyPolymorphicMangler(ast, seed = 2654435769) {
1813
+ function applyPolymorphicMangler(ast, seed = 2654435769, serializedFunctionNodes) {
1067
1814
  const scopeRecords = /* @__PURE__ */ new Map();
1068
1815
  const existingIdentifiers = /* @__PURE__ */ new Set();
1069
1816
  let counter = 0;
@@ -1109,11 +1856,16 @@ function applyPolymorphicMangler(ast, seed = 2654435769) {
1109
1856
  }
1110
1857
  return ancestors[0];
1111
1858
  }
1112
- function registerBindingTarget(scopeNode, target, shouldMangle) {
1859
+ function registerBindingTarget(scopeNode, target, shouldMangle, fnScope) {
1113
1860
  const scope = scopeRecords.get(scopeNode);
1114
1861
  if (!scope) return;
1115
1862
  const origName = target.idNode.name;
1116
- const canMangle = shouldMangle && isMangleableName(origName);
1863
+ let canMangle = shouldMangle && isMangleableName(origName);
1864
+ if (canMangle && fnScope) {
1865
+ if (serializedFunctionNodes && serializedFunctionNodes.has(fnScope)) {
1866
+ canMangle = false;
1867
+ }
1868
+ }
1117
1869
  let entry = scope.bindings.get(origName);
1118
1870
  if (!entry) {
1119
1871
  entry = {
@@ -1152,7 +1904,7 @@ function applyPolymorphicMangler(ast, seed = 2654435769) {
1152
1904
  const targets = [];
1153
1905
  collectPatternTargets(param, targets);
1154
1906
  for (const target of targets) {
1155
- registerBindingTarget(fnNode, target, true);
1907
+ registerBindingTarget(fnNode, target, true, fnNode);
1156
1908
  }
1157
1909
  }
1158
1910
  }
@@ -1222,10 +1974,11 @@ function applyPolymorphicMangler(ast, seed = 2654435769) {
1222
1974
  CatchClause(node, _state, ancestors) {
1223
1975
  ensureScopeChain(ancestors);
1224
1976
  if (node.param) {
1977
+ const fnScope = findEnclosingFunctionNode(ancestors);
1225
1978
  const targets = [];
1226
1979
  collectPatternTargets(node.param, targets);
1227
1980
  for (const target of targets) {
1228
- registerBindingTarget(node, target, true);
1981
+ registerBindingTarget(node, target, true, fnScope);
1229
1982
  }
1230
1983
  }
1231
1984
  },
@@ -1260,7 +2013,7 @@ function applyPolymorphicMangler(ast, seed = 2654435769) {
1260
2013
  }
1261
2014
  }
1262
2015
  }
1263
- registerBindingTarget(targetScopeNode, target, true);
2016
+ registerBindingTarget(targetScopeNode, target, true, fnScope);
1264
2017
  }
1265
2018
  }
1266
2019
  }
@@ -1276,12 +2029,16 @@ function applyPolymorphicMangler(ast, seed = 2654435769) {
1276
2029
  }
1277
2030
  return false;
1278
2031
  }
2032
+ const ALPHABET = "abcdefghijklmnopqrstuvwxyz";
1279
2033
  function makeScopedMangledName(scope, localIndex) {
1280
2034
  counter++;
1281
2035
  let salt = 0;
1282
2036
  while (true) {
1283
2037
  const h = computeFnv1aHash(`s${scope.depth}:i${localIndex}:${salt}`, seed);
1284
- const candidate = `_0x${((h & 31) + localIndex + salt).toString(36)}`;
2038
+ const prefix = (h & 1) === 0 ? "_" : "$";
2039
+ const ch = ALPHABET[((h >>> 1) + localIndex) % ALPHABET.length];
2040
+ const num = (localIndex + salt).toString(36);
2041
+ const candidate = `${prefix}${ch}${num}`;
1285
2042
  if (!isNameUsedInScopeOrAncestors(candidate, scope)) {
1286
2043
  return candidate;
1287
2044
  }
@@ -1391,227 +2148,420 @@ function applyPolymorphicMangler(ast, seed = 2654435769) {
1391
2148
 
1392
2149
  // src/ast/cold-flow-guard.ts
1393
2150
  import * as walk4 from "acorn-walk";
1394
- function createDecoyConsequent(fnIndex) {
1395
- const model = Math.abs(fnIndex) % 3;
1396
- if (model === 0) {
2151
+ function createDecoyObjectExpression(model) {
2152
+ const m = Math.abs(model) % 3;
2153
+ if (m === 0) {
1397
2154
  return {
1398
- type: "BlockStatement",
1399
- body: [
2155
+ type: "ObjectExpression",
2156
+ properties: [
1400
2157
  {
1401
- type: "ReturnStatement",
1402
- argument: {
1403
- type: "ObjectExpression",
1404
- properties: [
1405
- {
1406
- type: "Property",
1407
- key: { type: "Identifier", name: "endpoint" },
1408
- value: {
1409
- type: "Literal",
1410
- value: "/api/v2/auth/admin-bypass",
1411
- raw: '"/api/v2/auth/admin-bypass"'
1412
- },
1413
- kind: "init",
1414
- computed: false,
1415
- method: false,
1416
- shorthand: false
1417
- },
1418
- {
1419
- type: "Property",
1420
- key: { type: "Identifier", name: "superadmin_token" },
1421
- value: { type: "Literal", value: 1, raw: "1" },
1422
- kind: "init",
1423
- computed: false,
1424
- method: false,
1425
- shorthand: false
1426
- },
1427
- {
1428
- type: "Property",
1429
- key: { type: "Identifier", name: "elevate" },
1430
- value: { type: "Literal", value: 1, raw: "1" },
1431
- kind: "init",
1432
- computed: false,
1433
- method: false,
1434
- shorthand: false
1435
- }
1436
- ]
1437
- }
1438
- }
2158
+ type: "Property",
2159
+ key: { type: "Identifier", name: "endpoint" },
2160
+ value: {
2161
+ type: "Literal",
2162
+ value: "/api/v2/auth/admin-bypass",
2163
+ raw: '"/api/v2/auth/admin-bypass"'
2164
+ },
2165
+ kind: "init",
2166
+ computed: false,
2167
+ method: false,
2168
+ shorthand: false
2169
+ },
2170
+ {
2171
+ type: "Property",
2172
+ key: { type: "Identifier", name: "superadmin_token" },
2173
+ value: { type: "Literal", value: 1, raw: "1" },
2174
+ kind: "init",
2175
+ computed: false,
2176
+ method: false,
2177
+ shorthand: false
2178
+ },
2179
+ {
2180
+ type: "Property",
2181
+ key: { type: "Identifier", name: "elevate" },
2182
+ value: { type: "Literal", value: 1, raw: "1" },
2183
+ kind: "init",
2184
+ computed: false,
2185
+ method: false,
2186
+ shorthand: false
2187
+ }
1439
2188
  ]
1440
2189
  };
1441
2190
  }
1442
- if (model === 1) {
2191
+ if (m === 1) {
1443
2192
  return {
1444
- type: "BlockStatement",
1445
- body: [
2193
+ type: "ObjectExpression",
2194
+ properties: [
1446
2195
  {
1447
- type: "ReturnStatement",
1448
- argument: {
1449
- type: "ObjectExpression",
1450
- properties: [
1451
- {
1452
- type: "Property",
1453
- key: { type: "Identifier", name: "endpoint" },
1454
- value: {
1455
- type: "Literal",
1456
- value: "/api/v2/auth/verify-master",
1457
- raw: '"/api/v2/auth/verify-master"'
1458
- },
1459
- kind: "init",
1460
- computed: false,
1461
- method: false,
1462
- shorthand: false
1463
- },
1464
- {
1465
- type: "Property",
1466
- key: { type: "Identifier", name: "_verifyMasterToken" },
1467
- value: { type: "Literal", value: true, raw: "true" },
1468
- kind: "init",
1469
- computed: false,
1470
- method: false,
1471
- shorthand: false
1472
- },
1473
- {
1474
- type: "Property",
1475
- key: { type: "Identifier", name: "_bypassToken" },
1476
- value: {
1477
- type: "Literal",
1478
- value: "mock_jwt_bypass_signature",
1479
- raw: '"mock_jwt_bypass_signature"'
1480
- },
1481
- kind: "init",
1482
- computed: false,
1483
- method: false,
1484
- shorthand: false
1485
- },
1486
- {
1487
- type: "Property",
1488
- key: { type: "Identifier", name: "authorized" },
1489
- value: { type: "Literal", value: true, raw: "true" },
1490
- kind: "init",
1491
- computed: false,
1492
- method: false,
1493
- shorthand: false
1494
- }
1495
- ]
1496
- }
2196
+ type: "Property",
2197
+ key: { type: "Identifier", name: "endpoint" },
2198
+ value: {
2199
+ type: "Literal",
2200
+ value: "/api/v2/auth/verify-master",
2201
+ raw: '"/api/v2/auth/verify-master"'
2202
+ },
2203
+ kind: "init",
2204
+ computed: false,
2205
+ method: false,
2206
+ shorthand: false
2207
+ },
2208
+ {
2209
+ type: "Property",
2210
+ key: { type: "Identifier", name: "_verifyMasterToken" },
2211
+ value: { type: "Literal", value: true, raw: "true" },
2212
+ kind: "init",
2213
+ computed: false,
2214
+ method: false,
2215
+ shorthand: false
2216
+ },
2217
+ {
2218
+ type: "Property",
2219
+ key: { type: "Identifier", name: "_bypassToken" },
2220
+ value: {
2221
+ type: "Literal",
2222
+ value: "mock_jwt_bypass_signature",
2223
+ raw: '"mock_jwt_bypass_signature"'
2224
+ },
2225
+ kind: "init",
2226
+ computed: false,
2227
+ method: false,
2228
+ shorthand: false
2229
+ },
2230
+ {
2231
+ type: "Property",
2232
+ key: { type: "Identifier", name: "authorized" },
2233
+ value: { type: "Literal", value: true, raw: "true" },
2234
+ kind: "init",
2235
+ computed: false,
2236
+ method: false,
2237
+ shorthand: false
1497
2238
  }
1498
2239
  ]
1499
2240
  };
1500
2241
  }
2242
+ return {
2243
+ type: "ObjectExpression",
2244
+ properties: [
2245
+ {
2246
+ type: "Property",
2247
+ key: { type: "Identifier", name: "endpoint" },
2248
+ value: {
2249
+ type: "Literal",
2250
+ value: "/api/v2/auth/debug-telemetry",
2251
+ raw: '"/api/v2/auth/debug-telemetry"'
2252
+ },
2253
+ kind: "init",
2254
+ computed: false,
2255
+ method: false,
2256
+ shorthand: false
2257
+ },
2258
+ {
2259
+ type: "Property",
2260
+ key: { type: "Identifier", name: "debug_supervisor_override" },
2261
+ value: { type: "Literal", value: true, raw: "true" },
2262
+ kind: "init",
2263
+ computed: false,
2264
+ method: false,
2265
+ shorthand: false
2266
+ },
2267
+ {
2268
+ type: "Property",
2269
+ key: { type: "Identifier", name: "_bypassToken" },
2270
+ value: {
2271
+ type: "Literal",
2272
+ value: "superadmin_token",
2273
+ raw: '"superadmin_token"'
2274
+ },
2275
+ kind: "init",
2276
+ computed: false,
2277
+ method: false,
2278
+ shorthand: false
2279
+ },
2280
+ {
2281
+ type: "Property",
2282
+ key: { type: "Identifier", name: "mfa_bypassed" },
2283
+ value: { type: "Literal", value: true, raw: "true" },
2284
+ kind: "init",
2285
+ computed: false,
2286
+ method: false,
2287
+ shorthand: false
2288
+ }
2289
+ ]
2290
+ };
2291
+ }
2292
+ function createDecoyConsequent(fnIndex) {
2293
+ return {
2294
+ type: "BlockStatement",
2295
+ body: [
2296
+ {
2297
+ type: "ReturnStatement",
2298
+ argument: createDecoyObjectExpression(fnIndex)
2299
+ }
2300
+ ]
2301
+ };
2302
+ }
2303
+ function createSharedDecoyConsequent(decoyIdent, fnIndex) {
2304
+ const model = Math.abs(fnIndex) % 3;
1501
2305
  return {
1502
2306
  type: "BlockStatement",
1503
2307
  body: [
1504
2308
  {
1505
2309
  type: "ReturnStatement",
1506
2310
  argument: {
1507
- type: "ObjectExpression",
1508
- properties: [
1509
- {
1510
- type: "Property",
1511
- key: { type: "Identifier", name: "endpoint" },
1512
- value: {
1513
- type: "Literal",
1514
- value: "/api/v2/auth/debug-telemetry",
1515
- raw: '"/api/v2/auth/debug-telemetry"'
1516
- },
1517
- kind: "init",
1518
- computed: false,
1519
- method: false,
1520
- shorthand: false
1521
- },
1522
- {
1523
- type: "Property",
1524
- key: { type: "Identifier", name: "debug_supervisor_override" },
1525
- value: { type: "Literal", value: true, raw: "true" },
1526
- kind: "init",
1527
- computed: false,
1528
- method: false,
1529
- shorthand: false
1530
- },
1531
- {
1532
- type: "Property",
1533
- key: { type: "Identifier", name: "_bypassToken" },
1534
- value: {
1535
- type: "Literal",
1536
- value: "superadmin_token",
1537
- raw: '"superadmin_token"'
1538
- },
1539
- kind: "init",
1540
- computed: false,
1541
- method: false,
1542
- shorthand: false
1543
- },
1544
- {
1545
- type: "Property",
1546
- key: { type: "Identifier", name: "mfa_bypassed" },
1547
- value: { type: "Literal", value: true, raw: "true" },
1548
- kind: "init",
1549
- computed: false,
1550
- method: false,
1551
- shorthand: false
2311
+ type: "CallExpression",
2312
+ callee: {
2313
+ type: "MemberExpression",
2314
+ computed: true,
2315
+ object: { type: "Identifier", name: decoyIdent },
2316
+ property: {
2317
+ type: "Literal",
2318
+ value: model,
2319
+ raw: String(model)
1552
2320
  }
1553
- ]
2321
+ },
2322
+ arguments: []
1554
2323
  }
1555
2324
  }
1556
2325
  ]
1557
2326
  };
1558
2327
  }
1559
- function createSotaMbaPredicate(seed, fnIndex = 0) {
1560
- const x = (seed >>> 0) + Math.imul(fnIndex + 1, 73244475) | 0;
1561
- const y = x ^ 1515870810 | 0;
2328
+ function createSharedDecoyDeclaration(decoyIdent = "_d") {
2329
+ return {
2330
+ type: "VariableDeclaration",
2331
+ kind: "var",
2332
+ declarations: [
2333
+ {
2334
+ type: "VariableDeclarator",
2335
+ id: { type: "Identifier", name: decoyIdent },
2336
+ init: {
2337
+ type: "ArrayExpression",
2338
+ elements: [0, 1, 2].map((m) => ({
2339
+ type: "ArrowFunctionExpression",
2340
+ id: null,
2341
+ params: [],
2342
+ body: createDecoyObjectExpression(m),
2343
+ generator: false,
2344
+ async: false,
2345
+ expression: true
2346
+ }))
2347
+ }
2348
+ }
2349
+ ]
2350
+ };
2351
+ }
2352
+ function cloneNode(node) {
2353
+ return JSON.parse(JSON.stringify(node));
2354
+ }
2355
+ function createSotaMbaPredicate(seed, fnIndex = 0, paramNode, decoyIdent, isArrowFn = false) {
2356
+ const family = Math.abs(seed + fnIndex & 3);
2357
+ const c1 = (seed >>> 0) + Math.imul(family + 1, 73244475) | 0;
2358
+ const c2 = c1 ^ 1515870810 | 0;
2359
+ const target = (seed ^ Math.imul(family + 1, 2654435761)) & 8388607 | 1;
2360
+ let paramName = null;
2361
+ if (typeof paramNode === "string") {
2362
+ paramName = paramNode;
2363
+ } else if (paramNode?.type === "Identifier") {
2364
+ paramName = paramNode.name;
2365
+ } else if (paramNode?.type === "AssignmentPattern" && paramNode.left?.type === "Identifier") {
2366
+ paramName = paramNode.left.name;
2367
+ }
2368
+ const zNode = {
2369
+ type: "UnaryExpression",
2370
+ operator: "+",
2371
+ prefix: true,
2372
+ argument: {
2373
+ type: "UnaryExpression",
2374
+ operator: "!",
2375
+ prefix: true,
2376
+ argument: { type: "Identifier", name: "String" }
2377
+ }
2378
+ };
2379
+ const vNode = {
2380
+ type: "BinaryExpression",
2381
+ operator: "|",
2382
+ left: zNode,
2383
+ right: { type: "Literal", value: c1, raw: String(c1) }
2384
+ };
2385
+ const kNode = {
2386
+ type: "BinaryExpression",
2387
+ operator: "|",
2388
+ left: { type: "Literal", value: c2, raw: String(c2) },
2389
+ right: {
2390
+ type: "UnaryExpression",
2391
+ operator: "!",
2392
+ prefix: true,
2393
+ argument: { type: "Identifier", name: "String" }
2394
+ }
2395
+ };
2396
+ let mbaExpr;
2397
+ if (family === 0) {
2398
+ const vXorK = {
2399
+ type: "BinaryExpression",
2400
+ operator: "^",
2401
+ left: cloneNode(vNode),
2402
+ right: cloneNode(kNode)
2403
+ };
2404
+ const vAndK = {
2405
+ type: "BinaryExpression",
2406
+ operator: "&",
2407
+ left: cloneNode(vNode),
2408
+ right: cloneNode(kNode)
2409
+ };
2410
+ const shift = {
2411
+ type: "BinaryExpression",
2412
+ operator: "<<",
2413
+ left: vAndK,
2414
+ right: { type: "Literal", value: 1, raw: "1" }
2415
+ };
2416
+ const addLeft = {
2417
+ type: "BinaryExpression",
2418
+ operator: "+",
2419
+ left: vXorK,
2420
+ right: shift
2421
+ };
2422
+ const vPlusK = {
2423
+ type: "BinaryExpression",
2424
+ operator: "+",
2425
+ left: cloneNode(vNode),
2426
+ right: cloneNode(kNode)
2427
+ };
2428
+ mbaExpr = {
2429
+ type: "BinaryExpression",
2430
+ operator: "-",
2431
+ left: addLeft,
2432
+ right: vPlusK
2433
+ };
2434
+ } else if (family === 1) {
2435
+ const vOrK = {
2436
+ type: "BinaryExpression",
2437
+ operator: "|",
2438
+ left: cloneNode(vNode),
2439
+ right: cloneNode(kNode)
2440
+ };
2441
+ const vAndK = {
2442
+ type: "BinaryExpression",
2443
+ operator: "&",
2444
+ left: cloneNode(vNode),
2445
+ right: cloneNode(kNode)
2446
+ };
2447
+ const addLeft = {
2448
+ type: "BinaryExpression",
2449
+ operator: "+",
2450
+ left: vOrK,
2451
+ right: vAndK
2452
+ };
2453
+ const vPlusK = {
2454
+ type: "BinaryExpression",
2455
+ operator: "+",
2456
+ left: cloneNode(vNode),
2457
+ right: cloneNode(kNode)
2458
+ };
2459
+ mbaExpr = {
2460
+ type: "BinaryExpression",
2461
+ operator: "^",
2462
+ left: addLeft,
2463
+ right: vPlusK
2464
+ };
2465
+ } else if (family === 2) {
2466
+ const notK = {
2467
+ type: "UnaryExpression",
2468
+ operator: "~",
2469
+ prefix: true,
2470
+ argument: cloneNode(kNode)
2471
+ };
2472
+ const vOrNotK = {
2473
+ type: "BinaryExpression",
2474
+ operator: "|",
2475
+ left: cloneNode(vNode),
2476
+ right: cloneNode(notK)
2477
+ };
2478
+ const subLeft = {
2479
+ type: "BinaryExpression",
2480
+ operator: "-",
2481
+ left: vOrNotK,
2482
+ right: cloneNode(notK)
2483
+ };
2484
+ const vAndK = {
2485
+ type: "BinaryExpression",
2486
+ operator: "&",
2487
+ left: cloneNode(vNode),
2488
+ right: cloneNode(kNode)
2489
+ };
2490
+ mbaExpr = {
2491
+ type: "BinaryExpression",
2492
+ operator: "^",
2493
+ left: subLeft,
2494
+ right: vAndK
2495
+ };
2496
+ } else {
2497
+ const notK = {
2498
+ type: "UnaryExpression",
2499
+ operator: "~",
2500
+ prefix: true,
2501
+ argument: cloneNode(kNode)
2502
+ };
2503
+ const vAndNotK = {
2504
+ type: "BinaryExpression",
2505
+ operator: "&",
2506
+ left: cloneNode(vNode),
2507
+ right: cloneNode(notK)
2508
+ };
2509
+ const vAndK = {
2510
+ type: "BinaryExpression",
2511
+ operator: "&",
2512
+ left: cloneNode(vNode),
2513
+ right: cloneNode(kNode)
2514
+ };
2515
+ const addLeft = {
2516
+ type: "BinaryExpression",
2517
+ operator: "+",
2518
+ left: vAndNotK,
2519
+ right: vAndK
2520
+ };
2521
+ mbaExpr = {
2522
+ type: "BinaryExpression",
2523
+ operator: "^",
2524
+ left: addLeft,
2525
+ right: cloneNode(vNode)
2526
+ };
2527
+ }
2528
+ const decoyIdx = Math.abs(fnIndex) % 3;
2529
+ const consequent = decoyIdent ? createSharedDecoyConsequent(decoyIdent, decoyIdx) : createDecoyConsequent(decoyIdx);
1562
2530
  return {
1563
2531
  type: "IfStatement",
1564
2532
  test: {
1565
2533
  type: "BinaryExpression",
1566
2534
  operator: "===",
1567
- left: {
1568
- type: "BinaryExpression",
1569
- operator: "|",
1570
- left: {
1571
- type: "BinaryExpression",
1572
- operator: "^",
1573
- left: {
1574
- type: "BinaryExpression",
1575
- operator: "+",
1576
- left: {
1577
- type: "BinaryExpression",
1578
- operator: "|",
1579
- left: { type: "Literal", value: x, raw: String(x) },
1580
- right: { type: "Literal", value: y, raw: String(y) }
1581
- },
1582
- right: {
1583
- type: "BinaryExpression",
1584
- operator: "&",
1585
- left: { type: "Literal", value: x, raw: String(x) },
1586
- right: { type: "Literal", value: y, raw: String(y) }
1587
- }
1588
- },
1589
- right: {
1590
- type: "BinaryExpression",
1591
- operator: "+",
1592
- left: { type: "Literal", value: x, raw: String(x) },
1593
- right: { type: "Literal", value: y, raw: String(y) }
1594
- }
1595
- },
1596
- right: {
1597
- type: "UnaryExpression",
1598
- operator: "!",
1599
- prefix: true,
1600
- argument: { type: "Identifier", name: "String" }
1601
- }
1602
- },
1603
- right: { type: "Literal", value: 2147483647, raw: "0x7fffffff" }
2535
+ left: mbaExpr,
2536
+ right: { type: "Literal", value: target, raw: String(target) }
1604
2537
  },
1605
- consequent: createDecoyConsequent(fnIndex),
2538
+ consequent,
1606
2539
  alternate: null
1607
2540
  };
1608
2541
  }
1609
2542
  function applyColdFlowGuard(ast, coldFunctionNodes, seed = 2654435769, hotExemptNodes) {
2543
+ const decoyIdent = "_d";
2544
+ if (Array.isArray(ast.body)) {
2545
+ const alreadyGuarded = ast.body.some(
2546
+ (stmt) => stmt.type === "VariableDeclaration" && stmt.declarations?.some(
2547
+ (d) => d.id?.type === "Identifier" && d.id.name === decoyIdent
2548
+ )
2549
+ );
2550
+ if (alreadyGuarded) return 0;
2551
+ }
1610
2552
  let guardedCount = 0;
1611
2553
  function maybeInjectGuard(node) {
1612
2554
  if (!coldFunctionNodes.has(node)) return;
1613
2555
  if (!node.body || node.body.type !== "BlockStatement") return;
1614
- const guardStmt = createSotaMbaPredicate(seed, 0);
2556
+ const firstParam = node.params?.[0];
2557
+ const isArrow = node.type === "ArrowFunctionExpression";
2558
+ const guardStmt = createSotaMbaPredicate(
2559
+ seed,
2560
+ guardedCount,
2561
+ firstParam,
2562
+ decoyIdent,
2563
+ isArrow
2564
+ );
1615
2565
  guardedCount++;
1616
2566
  if (hotExemptNodes) {
1617
2567
  hotExemptNodes.add(guardStmt);
@@ -1628,64 +2578,946 @@ function applyColdFlowGuard(ast, coldFunctionNodes, seed = 2654435769, hotExempt
1628
2578
  FunctionExpression: maybeInjectGuard,
1629
2579
  ArrowFunctionExpression: maybeInjectGuard
1630
2580
  });
2581
+ if (guardedCount > 0 && Array.isArray(ast.body)) {
2582
+ const sharedDecoyDecl = createSharedDecoyDeclaration(decoyIdent);
2583
+ if (hotExemptNodes) {
2584
+ hotExemptNodes.add(sharedDecoyDecl);
2585
+ for (const decl of sharedDecoyDecl.declarations || []) {
2586
+ if (decl.init?.elements) {
2587
+ for (const el of decl.init.elements) {
2588
+ hotExemptNodes.add(el);
2589
+ }
2590
+ }
2591
+ }
2592
+ }
2593
+ let insertIdx = 0;
2594
+ while (insertIdx < ast.body.length && ast.body[insertIdx].type === "ExpressionStatement" && ast.body[insertIdx].directive) {
2595
+ insertIdx++;
2596
+ }
2597
+ ast.body.splice(insertIdx, 0, sharedDecoyDecl);
2598
+ }
1631
2599
  return guardedCount;
1632
2600
  }
1633
2601
 
1634
- // src/runtime/integrity-guard.ts
1635
- var FNV_OFFSET_BASIS = 2166136261;
1636
- var FNV_PRIME = 16777619;
1637
- function computeIntegrityHash(source, seed = 0) {
1638
- let hash = (FNV_OFFSET_BASIS ^ seed >>> 0) >>> 0;
1639
- for (let i = 0; i < source.length; i++) {
1640
- hash ^= source.charCodeAt(i);
1641
- hash = Math.imul(hash, FNV_PRIME) >>> 0;
2602
+ // src/ast/micro-vm.ts
2603
+ import * as acorn3 from "acorn";
2604
+ import * as walk5 from "acorn-walk";
2605
+ var OP_LDC = 0;
2606
+ var OP_LDV = 1;
2607
+ var OP_STV = 2;
2608
+ var OP_LDG = 3;
2609
+ var OP_GETP = 4;
2610
+ var OP_SETP = 5;
2611
+ var OP_CALL = 6;
2612
+ var OP_MCALL = 7;
2613
+ var OP_ADD = 8;
2614
+ var OP_SUB = 9;
2615
+ var OP_MUL = 10;
2616
+ var OP_XOR = 11;
2617
+ var OP_AND = 12;
2618
+ var OP_OR = 13;
2619
+ var OP_SEQ = 14;
2620
+ var OP_LT = 15;
2621
+ var OP_NOT = 16;
2622
+ var OP_JMP = 17;
2623
+ var OP_JZ = 18;
2624
+ var OP_RET = 19;
2625
+ var OP_THROW = 20;
2626
+ var OP_AWAIT = 21;
2627
+ var OP_OBJ = 22;
2628
+ var OP_ARR = 23;
2629
+ function generateOpcodeMap(seed) {
2630
+ const pool = [];
2631
+ for (let i = 0; i < 256; i++) pool.push(i);
2632
+ let s = (seed ^ 2779096485) >>> 0;
2633
+ function rand() {
2634
+ s ^= s << 13;
2635
+ s ^= s >>> 17;
2636
+ s ^= s << 5;
2637
+ return (s >>> 0) / 4294967296;
1642
2638
  }
1643
- return hash >>> 0;
2639
+ for (let i = pool.length - 1; i > 0; i--) {
2640
+ const j = Math.floor(rand() * (i + 1));
2641
+ const tmp = pool[i];
2642
+ pool[i] = pool[j];
2643
+ pool[j] = tmp;
2644
+ }
2645
+ return pool.slice(0, 24);
1644
2646
  }
1645
-
1646
- // src/runtime/devtools-deterrent.ts
1647
- function deriveIntegrityFnName(seed) {
1648
- const hash = computeIntegrityHash(`unpeek:fn:${seed}`, seed);
1649
- return `_u$${hash.toString(36)}`;
2647
+ function createInterpreterSource(vmHelperName, opMap) {
2648
+ return `function ${vmHelperName}(c, k, s, t) {
2649
+ var p = 0, r = 0, q = [];
2650
+ var G = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : this);
2651
+ function x() {
2652
+ while (p < c.length) {
2653
+ var o = c[p++];
2654
+ switch (o) {
2655
+ case ${opMap[OP_LDC]}: q[r++] = k[c[p++]]; break;
2656
+ case ${opMap[OP_LDV]}: q[r++] = s[c[p++]]; break;
2657
+ case ${opMap[OP_STV]}: s[c[p++]] = q[--r]; break;
2658
+ case ${opMap[OP_LDG]}: q[r++] = G[k[c[p++]]]; break;
2659
+ case ${opMap[OP_GETP]}: { var b = q[--r], a = q[--r]; q[r++] = a[b]; break; }
2660
+ case ${opMap[OP_SETP]}: { var v = q[--r], b = q[--r], a = q[--r]; q[r++] = (a[b] = v); break; }
2661
+ case ${opMap[OP_CALL]}: {
2662
+ var n = c[p++], g = [];
2663
+ for (var i = n - 1; i >= 0; i--) g[i] = q[--r];
2664
+ var f = q[--r]; q[r++] = f.apply(null, g); break;
2665
+ }
2666
+ case ${opMap[OP_MCALL]}: {
2667
+ var n = c[p++], g = [];
2668
+ for (var i = n - 1; i >= 0; i--) g[i] = q[--r];
2669
+ var b = q[--r], a = q[--r]; q[r++] = a[b].apply(a, g); break;
2670
+ }
2671
+ case ${opMap[OP_ADD]}: { var b = q[--r], a = q[--r]; q[r++] = a + b; break; }
2672
+ case ${opMap[OP_SUB]}: { var b = q[--r], a = q[--r]; q[r++] = a - b; break; }
2673
+ case ${opMap[OP_MUL]}: { var b = q[--r], a = q[--r]; q[r++] = a * b; break; }
2674
+ case ${opMap[OP_XOR]}: { var b = q[--r], a = q[--r]; q[r++] = a ^ b; break; }
2675
+ case ${opMap[OP_AND]}: { var b = q[--r], a = q[--r]; q[r++] = a & b; break; }
2676
+ case ${opMap[OP_OR]}: { var b = q[--r], a = q[--r]; q[r++] = a | b; break; }
2677
+ case ${opMap[OP_SEQ]}: { var b = q[--r], a = q[--r]; q[r++] = a === b; break; }
2678
+ case ${opMap[OP_LT]}: { var b = q[--r], a = q[--r]; q[r++] = a < b; break; }
2679
+ case ${opMap[OP_NOT]}: { q[r - 1] = !q[r - 1]; break; }
2680
+ case ${opMap[OP_JMP]}: { p = c[p]; break; }
2681
+ case ${opMap[OP_JZ]}: { var j = c[p++]; if (!q[--r]) p = j; break; }
2682
+ case ${opMap[OP_RET]}: return q[--r];
2683
+ case ${opMap[OP_THROW]}: throw q[--r];
2684
+ case ${opMap[OP_AWAIT]}: {
2685
+ var v = q[--r];
2686
+ return Promise.resolve(v).then(function(w) { q[r++] = w; return x(); });
2687
+ }
2688
+ case ${opMap[OP_OBJ]}: {
2689
+ var n = c[p++], o = {}, e = [];
2690
+ for (var i = 0; i < n; i++) { var v = q[--r], k0 = q[--r]; e.push([k0, v]); }
2691
+ for (var i = e.length - 1; i >= 0; i--) { o[e[i][0]] = e[i][1]; }
2692
+ q[r++] = o;
2693
+ break;
2694
+ }
2695
+ case ${opMap[OP_ARR]}: {
2696
+ var n = c[p++], a = [];
2697
+ for (var i = n - 1; i >= 0; i--) a[i] = q[--r];
2698
+ q[r++] = a;
2699
+ break;
2700
+ }
2701
+ }
2702
+ }
2703
+ }
2704
+ return x();
2705
+ }`;
1650
2706
  }
1651
- function createDeterrentSnippet(config) {
1652
- const seed = config.seed >>> 0;
1653
- const deterrentMode = config.deterrentMode ?? "passive";
1654
- const fnName = deriveIntegrityFnName(seed);
1655
- const consoleSilence = deterrentMode === "gradual" ? "for(var k in console)console[k]=f=>0;" : "";
1656
- return `(function ${fnName}(w){if(w){try{(w.queueMicrotask||w.requestIdleCallback||(f=>f()))(function f(a){var s=Function.prototype.toString,n=w.navigator||0,t=s.call(s).indexOf('[native code]')<0||/\\n/.test(s.call(${fnName}))||n.webdriver||/HeadlessChrome/.test(n.userAgent);if(t){w.__unpeek_tampered=!0,w.__unpeek_seed=((w.__unpeek_seed||${seed})^1)>>>0,String.prototype._u=14;try{${consoleSilence}w.dispatchEvent(new CustomEvent('unpeek:tamper'));}catch(e){}}});}catch(e){}}})(typeof window!=='undefined'&&window);`;
2707
+ function countAstNodes(node) {
2708
+ let count = 0;
2709
+ walk5.full(node, () => {
2710
+ count++;
2711
+ });
2712
+ return count;
2713
+ }
2714
+ function hasForbiddenConstructs(fnNode) {
2715
+ let forbidden = false;
2716
+ walk5.full(fnNode, (node) => {
2717
+ if (forbidden) return;
2718
+ const type = node.type;
2719
+ if (type === "JSXElement" || type === "JSXFragment" || type === "Super" || type === "YieldExpression") {
2720
+ forbidden = true;
2721
+ return;
2722
+ }
2723
+ if (type === "Identifier" && node.name === "arguments") {
2724
+ forbidden = true;
2725
+ return;
2726
+ }
2727
+ if (type === "MetaProperty" && node.meta?.name === "new" && node.property?.name === "target") {
2728
+ forbidden = true;
2729
+ return;
2730
+ }
2731
+ });
2732
+ return forbidden;
2733
+ }
2734
+ function compileFunctionToBytecode(fnNode, opMap) {
2735
+ const bytecode = [];
2736
+ const consts = [];
2737
+ const localMap = /* @__PURE__ */ new Map();
2738
+ let localCount = 0;
2739
+ for (const param of fnNode.params) {
2740
+ if (param.type !== "Identifier") return null;
2741
+ localMap.set(param.name, localCount++);
2742
+ }
2743
+ const bodyNodes = fnNode.body.type === "BlockStatement" ? fnNode.body.body : [fnNode.body];
2744
+ for (const stmt of bodyNodes) {
2745
+ if (stmt.type === "VariableDeclaration") {
2746
+ for (const decl of stmt.declarations) {
2747
+ if (decl.id.type === "Identifier") {
2748
+ if (!localMap.has(decl.id.name)) {
2749
+ localMap.set(decl.id.name, localCount++);
2750
+ }
2751
+ } else {
2752
+ return null;
2753
+ }
2754
+ }
2755
+ }
2756
+ }
2757
+ function addConst(val) {
2758
+ for (let i = 0; i < consts.length; i++) {
2759
+ if (consts[i] === val) return i;
2760
+ }
2761
+ const idx = consts.length;
2762
+ consts.push(val);
2763
+ return idx;
2764
+ }
2765
+ function emit(op, ...args) {
2766
+ bytecode.push(opMap[op]);
2767
+ for (const a of args) bytecode.push(a);
2768
+ }
2769
+ function compileExpr(node) {
2770
+ if (!node) return false;
2771
+ switch (node.type) {
2772
+ case "Literal": {
2773
+ const idx = addConst(node.value);
2774
+ emit(OP_LDC, idx);
2775
+ return true;
2776
+ }
2777
+ case "Identifier": {
2778
+ if (node.name === "undefined") {
2779
+ const idx = addConst(void 0);
2780
+ emit(OP_LDC, idx);
2781
+ } else if (localMap.has(node.name)) {
2782
+ emit(OP_LDV, localMap.get(node.name));
2783
+ } else {
2784
+ const idx = addConst(node.name);
2785
+ emit(OP_LDG, idx);
2786
+ }
2787
+ return true;
2788
+ }
2789
+ case "BinaryExpression": {
2790
+ if (node.operator === ">") {
2791
+ if (!compileExpr(node.right)) return false;
2792
+ if (!compileExpr(node.left)) return false;
2793
+ emit(OP_LT);
2794
+ return true;
2795
+ }
2796
+ if (node.operator === "<=") {
2797
+ if (!compileExpr(node.right)) return false;
2798
+ if (!compileExpr(node.left)) return false;
2799
+ emit(OP_LT);
2800
+ emit(OP_NOT);
2801
+ return true;
2802
+ }
2803
+ if (node.operator === ">=") {
2804
+ if (!compileExpr(node.left)) return false;
2805
+ if (!compileExpr(node.right)) return false;
2806
+ emit(OP_LT);
2807
+ emit(OP_NOT);
2808
+ return true;
2809
+ }
2810
+ if (!compileExpr(node.left)) return false;
2811
+ if (!compileExpr(node.right)) return false;
2812
+ switch (node.operator) {
2813
+ case "+":
2814
+ emit(OP_ADD);
2815
+ break;
2816
+ case "-":
2817
+ emit(OP_SUB);
2818
+ break;
2819
+ case "*":
2820
+ emit(OP_MUL);
2821
+ break;
2822
+ case "^":
2823
+ emit(OP_XOR);
2824
+ break;
2825
+ case "&":
2826
+ emit(OP_AND);
2827
+ break;
2828
+ case "|":
2829
+ emit(OP_OR);
2830
+ break;
2831
+ case "==":
2832
+ case "===":
2833
+ emit(OP_SEQ);
2834
+ break;
2835
+ case "!=":
2836
+ case "!==":
2837
+ emit(OP_SEQ);
2838
+ emit(OP_NOT);
2839
+ break;
2840
+ case "<":
2841
+ emit(OP_LT);
2842
+ break;
2843
+ default:
2844
+ return false;
2845
+ }
2846
+ return true;
2847
+ }
2848
+ case "UnaryExpression": {
2849
+ if (!compileExpr(node.argument)) return false;
2850
+ switch (node.operator) {
2851
+ case "!":
2852
+ emit(OP_NOT);
2853
+ break;
2854
+ case "-": {
2855
+ const neg1Idx = addConst(-1);
2856
+ emit(OP_LDC, neg1Idx);
2857
+ emit(OP_MUL);
2858
+ break;
2859
+ }
2860
+ case "+": {
2861
+ const zeroIdx = addConst(0);
2862
+ emit(OP_LDC, zeroIdx);
2863
+ emit(OP_ADD);
2864
+ break;
2865
+ }
2866
+ case "~": {
2867
+ const neg1Idx = addConst(-1);
2868
+ emit(OP_LDC, neg1Idx);
2869
+ emit(OP_XOR);
2870
+ break;
2871
+ }
2872
+ case "void": {
2873
+ const undefIdx2 = addConst(void 0);
2874
+ emit(OP_LDC, undefIdx2);
2875
+ break;
2876
+ }
2877
+ default:
2878
+ return false;
2879
+ }
2880
+ return true;
2881
+ }
2882
+ case "MemberExpression": {
2883
+ if (!compileExpr(node.object)) return false;
2884
+ if (node.computed) {
2885
+ if (!compileExpr(node.property)) return false;
2886
+ } else {
2887
+ const idx = addConst(node.property.name);
2888
+ emit(OP_LDC, idx);
2889
+ }
2890
+ emit(OP_GETP);
2891
+ return true;
2892
+ }
2893
+ case "CallExpression": {
2894
+ if (node.callee.type === "MemberExpression") {
2895
+ if (!compileExpr(node.callee.object)) return false;
2896
+ if (node.callee.computed) {
2897
+ if (!compileExpr(node.callee.property)) return false;
2898
+ } else {
2899
+ const idx = addConst(node.callee.property.name);
2900
+ emit(OP_LDC, idx);
2901
+ }
2902
+ for (const arg of node.arguments) {
2903
+ if (!compileExpr(arg)) return false;
2904
+ }
2905
+ emit(OP_MCALL, node.arguments.length);
2906
+ } else {
2907
+ if (!compileExpr(node.callee)) return false;
2908
+ for (const arg of node.arguments) {
2909
+ if (!compileExpr(arg)) return false;
2910
+ }
2911
+ emit(OP_CALL, node.arguments.length);
2912
+ }
2913
+ return true;
2914
+ }
2915
+ case "AssignmentExpression": {
2916
+ if (node.operator !== "=") return false;
2917
+ if (node.left.type === "Identifier") {
2918
+ if (!localMap.has(node.left.name)) return false;
2919
+ if (!compileExpr(node.right)) return false;
2920
+ emit(OP_STV, localMap.get(node.left.name));
2921
+ return true;
2922
+ }
2923
+ if (node.left.type === "MemberExpression") {
2924
+ if (!compileExpr(node.left.object)) return false;
2925
+ if (node.left.computed) {
2926
+ if (!compileExpr(node.left.property)) return false;
2927
+ } else {
2928
+ const idx = addConst(node.left.property.name);
2929
+ emit(OP_LDC, idx);
2930
+ }
2931
+ if (!compileExpr(node.right)) return false;
2932
+ emit(OP_SETP);
2933
+ return true;
2934
+ }
2935
+ return false;
2936
+ }
2937
+ case "ObjectExpression": {
2938
+ for (const prop of node.properties) {
2939
+ if (prop.type !== "Property") return false;
2940
+ if (prop.computed) {
2941
+ if (!compileExpr(prop.key)) return false;
2942
+ } else {
2943
+ const keyName = prop.key.name ?? prop.key.value;
2944
+ const idx = addConst(keyName);
2945
+ emit(OP_LDC, idx);
2946
+ }
2947
+ if (!compileExpr(prop.value)) return false;
2948
+ }
2949
+ emit(OP_OBJ, node.properties.length);
2950
+ return true;
2951
+ }
2952
+ case "ArrayExpression": {
2953
+ for (const elem of node.elements) {
2954
+ if (!compileExpr(elem)) return false;
2955
+ }
2956
+ emit(OP_ARR, node.elements.length);
2957
+ return true;
2958
+ }
2959
+ case "AwaitExpression": {
2960
+ if (!compileExpr(node.argument)) return false;
2961
+ emit(OP_AWAIT);
2962
+ return true;
2963
+ }
2964
+ default:
2965
+ return false;
2966
+ }
2967
+ }
2968
+ function compileStmt(stmt) {
2969
+ if (!stmt) return false;
2970
+ switch (stmt.type) {
2971
+ case "ReturnStatement": {
2972
+ if (stmt.argument) {
2973
+ if (!compileExpr(stmt.argument)) return false;
2974
+ } else {
2975
+ const idx = addConst(void 0);
2976
+ emit(OP_LDC, idx);
2977
+ }
2978
+ emit(OP_RET);
2979
+ return true;
2980
+ }
2981
+ case "ExpressionStatement": {
2982
+ if (!compileExpr(stmt.expression)) return false;
2983
+ return true;
2984
+ }
2985
+ case "VariableDeclaration": {
2986
+ for (const decl of stmt.declarations) {
2987
+ if (decl.init) {
2988
+ if (!compileExpr(decl.init)) return false;
2989
+ emit(OP_STV, localMap.get(decl.id.name));
2990
+ }
2991
+ }
2992
+ return true;
2993
+ }
2994
+ case "IfStatement": {
2995
+ if (!compileExpr(stmt.test)) return false;
2996
+ const jzPos = bytecode.length;
2997
+ emit(OP_JZ, 0);
2998
+ if (!compileStmt(stmt.consequent)) return false;
2999
+ if (stmt.alternate) {
3000
+ const jmpPos = bytecode.length;
3001
+ emit(OP_JMP, 0);
3002
+ bytecode[jzPos + 1] = bytecode.length;
3003
+ if (!compileStmt(stmt.alternate)) return false;
3004
+ bytecode[jmpPos + 1] = bytecode.length;
3005
+ } else {
3006
+ bytecode[jzPos + 1] = bytecode.length;
3007
+ }
3008
+ return true;
3009
+ }
3010
+ case "BlockStatement": {
3011
+ for (const s of stmt.body) {
3012
+ if (!compileStmt(s)) return false;
3013
+ }
3014
+ return true;
3015
+ }
3016
+ default:
3017
+ return false;
3018
+ }
3019
+ }
3020
+ if (fnNode.body.type === "BlockStatement") {
3021
+ if (!compileStmt(fnNode.body)) return null;
3022
+ } else {
3023
+ if (!compileExpr(fnNode.body)) return null;
3024
+ emit(OP_RET);
3025
+ }
3026
+ const undefIdx = addConst(void 0);
3027
+ emit(OP_LDC, undefIdx);
3028
+ emit(OP_RET);
3029
+ return { bytecode, consts, localCount };
3030
+ }
3031
+ function isMicroVmAlreadyInjected(ast) {
3032
+ if (!ast || !Array.isArray(ast.body)) return false;
3033
+ return ast.body.some((stmt) => {
3034
+ if (stmt.type === "FunctionDeclaration" && typeof stmt.id?.name === "string" && stmt.id.name.startsWith("_uVm")) {
3035
+ return true;
3036
+ }
3037
+ return false;
3038
+ });
3039
+ }
3040
+ function applyMicroVm(ast, coldFunctionNodes, serializedFunctionNodes, seed = 2654435769) {
3041
+ const suffix = computeFnv1aHash(`micro-vm:${seed}`, seed).toString(36);
3042
+ const vmHelperName = `_uVm${suffix}`;
3043
+ if (isMicroVmAlreadyInjected(ast)) {
3044
+ const existing = ast.body.find(
3045
+ (stmt) => stmt.type === "FunctionDeclaration" && typeof stmt.id?.name === "string" && stmt.id.name.startsWith("_uVm")
3046
+ );
3047
+ return {
3048
+ virtualizedCount: 0,
3049
+ vmHelperName: existing?.id?.name ?? vmHelperName
3050
+ };
3051
+ }
3052
+ const opMap = generateOpcodeMap(seed);
3053
+ const candidates = [];
3054
+ walk5.simple(ast, {
3055
+ FunctionDeclaration(node) {
3056
+ candidates.push(node);
3057
+ },
3058
+ FunctionExpression(node) {
3059
+ candidates.push(node);
3060
+ },
3061
+ ArrowFunctionExpression(node) {
3062
+ candidates.push(node);
3063
+ }
3064
+ });
3065
+ let virtualizedCount = 0;
3066
+ for (const fn of candidates) {
3067
+ if (virtualizedCount >= 10) break;
3068
+ if (coldFunctionNodes && !coldFunctionNodes.has(fn)) {
3069
+ continue;
3070
+ }
3071
+ if (serializedFunctionNodes && serializedFunctionNodes.has(fn)) {
3072
+ continue;
3073
+ }
3074
+ if (fn.generator) {
3075
+ continue;
3076
+ }
3077
+ if (hasForbiddenConstructs(fn)) {
3078
+ continue;
3079
+ }
3080
+ const nodeCount = countAstNodes(fn);
3081
+ if (nodeCount < 15 || nodeCount > 80) {
3082
+ continue;
3083
+ }
3084
+ const compiled = compileFunctionToBytecode(fn, opMap);
3085
+ if (!compiled) {
3086
+ continue;
3087
+ }
3088
+ const paramArgs = fn.params.map((p) => ({
3089
+ type: "Identifier",
3090
+ name: p.name
3091
+ }));
3092
+ const callExpr = {
3093
+ type: "CallExpression",
3094
+ callee: {
3095
+ type: "Identifier",
3096
+ name: vmHelperName
3097
+ },
3098
+ arguments: [
3099
+ {
3100
+ type: "ArrayExpression",
3101
+ elements: compiled.bytecode.map((b) => ({
3102
+ type: "Literal",
3103
+ value: b,
3104
+ raw: String(b)
3105
+ }))
3106
+ },
3107
+ {
3108
+ type: "ArrayExpression",
3109
+ elements: compiled.consts.map((c) => ({
3110
+ type: "Literal",
3111
+ value: c,
3112
+ raw: c === void 0 ? "void 0" : JSON.stringify(c)
3113
+ }))
3114
+ },
3115
+ {
3116
+ type: "ArrayExpression",
3117
+ elements: paramArgs
3118
+ },
3119
+ {
3120
+ type: "ThisExpression"
3121
+ }
3122
+ ],
3123
+ optional: false
3124
+ };
3125
+ if (fn.body.type === "BlockStatement") {
3126
+ fn.body.body = [
3127
+ {
3128
+ type: "ReturnStatement",
3129
+ argument: callExpr
3130
+ }
3131
+ ];
3132
+ } else {
3133
+ fn.body = callExpr;
3134
+ }
3135
+ virtualizedCount++;
3136
+ }
3137
+ if (virtualizedCount > 0) {
3138
+ const interpreterSource = createInterpreterSource(vmHelperName, opMap);
3139
+ const parsedHelper = acorn3.parse(interpreterSource, {
3140
+ ecmaVersion: "latest",
3141
+ sourceType: "script"
3142
+ });
3143
+ ast.body.unshift(...parsedHelper.body);
3144
+ }
3145
+ return {
3146
+ virtualizedCount,
3147
+ vmHelperName
3148
+ };
1657
3149
  }
1658
3150
 
1659
- // src/runtime/index.ts
1660
- function generateRuntimeShield(config) {
1661
- const preambleCode = createDeterrentSnippet(config);
1662
- const integrityCheckFnName = deriveIntegrityFnName(config.seed);
1663
- const expectedHash = config.expectedIntegrityHash !== void 0 ? config.expectedIntegrityHash >>> 0 : computeIntegrityHash(preambleCode, config.seed);
3151
+ // src/ast/wasm-vault.ts
3152
+ import * as acorn4 from "acorn";
3153
+ function encodeSignedLeb128(value) {
3154
+ const bytes = [];
3155
+ let val = value | 0;
3156
+ let more = true;
3157
+ while (more) {
3158
+ let byte = val & 127;
3159
+ val >>= 7;
3160
+ if (val === 0 && (byte & 64) === 0 || val === -1 && (byte & 64) !== 0) {
3161
+ more = false;
3162
+ } else {
3163
+ byte |= 128;
3164
+ }
3165
+ bytes.push(byte);
3166
+ }
3167
+ return bytes;
3168
+ }
3169
+ function encodeUnsignedLeb128(value) {
3170
+ const bytes = [];
3171
+ let val = value >>> 0;
3172
+ do {
3173
+ let byte = val & 127;
3174
+ val >>>= 7;
3175
+ if (val !== 0) {
3176
+ byte |= 128;
3177
+ }
3178
+ bytes.push(byte);
3179
+ } while (val !== 0);
3180
+ return bytes;
3181
+ }
3182
+ function generateWasmKdfBinary(seed) {
3183
+ const instructions = [
3184
+ 32,
3185
+ 0,
3186
+ // local.get 0
3187
+ 65,
3188
+ ...encodeSignedLeb128(seed),
3189
+ // i32.const seed
3190
+ 115,
3191
+ // i32.xor
3192
+ 65,
3193
+ ...encodeSignedLeb128(16777619),
3194
+ // i32.const 0x01000193
3195
+ 108,
3196
+ // i32.mul
3197
+ 32,
3198
+ 1,
3199
+ // local.get 1
3200
+ 32,
3201
+ 2,
3202
+ // local.get 2
3203
+ 106,
3204
+ // i32.add
3205
+ 65,
3206
+ ...encodeSignedLeb128(73244475),
3207
+ // i32.const 0x45d9f3b
3208
+ 108,
3209
+ // i32.mul
3210
+ 115,
3211
+ // i32.xor
3212
+ 11
3213
+ // end
3214
+ ];
3215
+ const funcBody = [0, ...instructions];
3216
+ const funcBodyWithLen = [...encodeUnsignedLeb128(funcBody.length), ...funcBody];
3217
+ const codeSectionPayload = [1, ...funcBodyWithLen];
3218
+ const codeSection = [
3219
+ 10,
3220
+ ...encodeUnsignedLeb128(codeSectionPayload.length),
3221
+ ...codeSectionPayload
3222
+ ];
3223
+ const typePayload = [
3224
+ 1,
3225
+ // 1 type
3226
+ 96,
3227
+ // func
3228
+ 3,
3229
+ 127,
3230
+ 127,
3231
+ 127,
3232
+ // 3 params of type i32
3233
+ 1,
3234
+ 127
3235
+ // 1 result of type i32
3236
+ ];
3237
+ const typeSection = [
3238
+ 1,
3239
+ ...encodeUnsignedLeb128(typePayload.length),
3240
+ ...typePayload
3241
+ ];
3242
+ const funcPayload = [
3243
+ 1,
3244
+ // 1 function
3245
+ 0
3246
+ // type index 0
3247
+ ];
3248
+ const funcSection = [
3249
+ 3,
3250
+ ...encodeUnsignedLeb128(funcPayload.length),
3251
+ ...funcPayload
3252
+ ];
3253
+ const exportName = [3, 107, 100, 102];
3254
+ const exportPayload = [
3255
+ 1,
3256
+ // 1 export
3257
+ ...exportName,
3258
+ 0,
3259
+ // function export
3260
+ 0
3261
+ // function index 0
3262
+ ];
3263
+ const exportSection = [
3264
+ 7,
3265
+ ...encodeUnsignedLeb128(exportPayload.length),
3266
+ ...exportPayload
3267
+ ];
3268
+ const header = [0, 97, 115, 109, 1, 0, 0, 0];
3269
+ return new Uint8Array([
3270
+ ...header,
3271
+ ...typeSection,
3272
+ ...funcSection,
3273
+ ...exportSection,
3274
+ ...codeSection
3275
+ ]);
3276
+ }
3277
+ function fallbackKdf(fnId, callSiteSalt, shieldHash, seed) {
3278
+ return Math.imul(fnId ^ seed | 0, 16777619) ^ Math.imul(callSiteSalt + shieldHash | 0, 73244475) | 0;
3279
+ }
3280
+ function isWasmVaultAlreadyInjected(ast) {
3281
+ if (!ast || !Array.isArray(ast.body)) return false;
3282
+ return ast.body.some((stmt) => {
3283
+ if (stmt.type === "VariableDeclaration" && stmt.declarations?.some(
3284
+ (d) => d.id?.type === "Identifier" && typeof d.id.name === "string" && d.id.name.startsWith("_wKdf")
3285
+ )) {
3286
+ return true;
3287
+ }
3288
+ return false;
3289
+ });
3290
+ }
3291
+ function injectWasmVault(ast, seed = 2654435769) {
3292
+ const suffix = computeFnv1aHash(`wasm:${seed}`, seed).toString(36);
3293
+ const kdfFnName = `_wKdf${suffix}`;
3294
+ const wasmVarName = `_wb${suffix}`;
3295
+ if (isWasmVaultAlreadyInjected(ast)) {
3296
+ const existing = ast.body.find(
3297
+ (stmt) => stmt.type === "VariableDeclaration" && stmt.declarations?.some(
3298
+ (d) => d.id?.type === "Identifier" && typeof d.id.name === "string" && d.id.name.startsWith("_wKdf")
3299
+ )
3300
+ );
3301
+ const id = existing?.declarations[0]?.id?.name ?? kdfFnName;
3302
+ return {
3303
+ kdfFnName: id,
3304
+ wasmBytes: generateWasmKdfBinary(seed),
3305
+ wasmVarName
3306
+ };
3307
+ }
3308
+ const wasmBytes = generateWasmKdfBinary(seed);
3309
+ const byteArrayLiteral = Array.from(wasmBytes).join(",");
3310
+ const helperSnippet = `var ${kdfFnName};
3311
+ try {
3312
+ var ${wasmVarName} = new Uint8Array([${byteArrayLiteral}]);
3313
+ var _wm${suffix} = new WebAssembly.Module(${wasmVarName});
3314
+ var _wi${suffix} = new WebAssembly.Instance(_wm${suffix});
3315
+ ${kdfFnName} = _wi${suffix}.exports.kdf;
3316
+ } catch (e) {
3317
+ ${kdfFnName} = function(f, s, h) {
3318
+ return (Math.imul((f ^ ${seed | 0}) | 0, 16777619) ^ Math.imul(((s + h) | 0), 73244475)) | 0;
3319
+ };
3320
+ }`;
3321
+ const parsedHelper = acorn4.parse(helperSnippet, {
3322
+ ecmaVersion: "latest",
3323
+ sourceType: "script"
3324
+ });
3325
+ ast.body.unshift(...parsedHelper.body);
1664
3326
  return {
1665
- preambleCode,
1666
- integrityCheckFnName,
1667
- expectedHash
3327
+ kdfFnName,
3328
+ wasmBytes,
3329
+ wasmVarName
1668
3330
  };
1669
3331
  }
1670
3332
 
1671
- // src/ast/index.ts
1672
- function isAstAlreadyProtected(ast) {
3333
+ // src/ast/salted-vault.ts
3334
+ import * as acorn5 from "acorn";
3335
+ import * as walk6 from "acorn-walk";
3336
+ var DIRECTIVE_STRINGS2 = /* @__PURE__ */ new Set([
3337
+ "use strict",
3338
+ "use client",
3339
+ "use server",
3340
+ "use asm"
3341
+ ]);
3342
+ function encodeSaltedString(str, k) {
3343
+ let out = "";
3344
+ for (let j = 0; j < str.length; j++) {
3345
+ const code = str.charCodeAt(j);
3346
+ const mask = k >>> j % 24 & 127 | 1;
3347
+ out += String.fromCharCode(code ^ mask);
3348
+ }
3349
+ return out;
3350
+ }
3351
+ function isAstAlreadySalted(ast) {
1673
3352
  if (!ast || !Array.isArray(ast.body)) return false;
1674
3353
  return ast.body.some((stmt) => {
1675
3354
  if (stmt.type === "VariableDeclaration" && stmt.declarations?.some(
1676
- (d) => d.id?.type === "Identifier" && typeof d.id.name === "string" && d.id.name.startsWith("_uC")
3355
+ (d) => d.id?.type === "Identifier" && typeof d.id.name === "string" && d.id.name.startsWith("_uP")
1677
3356
  )) {
1678
3357
  return true;
1679
3358
  }
1680
- if (stmt.type === "ExpressionStatement" && stmt.expression?.type === "CallExpression" && stmt.expression.callee?.type === "FunctionExpression" && typeof stmt.expression.callee.id?.name === "string" && stmt.expression.callee.id.name.startsWith("_u$")) {
3359
+ return false;
3360
+ });
3361
+ }
3362
+ function replaceNodeInParent(parent, oldNode, newNode) {
3363
+ if (!parent) return false;
3364
+ for (const key of Object.keys(parent)) {
3365
+ const val = parent[key];
3366
+ if (val === oldNode) {
3367
+ parent[key] = newNode;
1681
3368
  return true;
1682
3369
  }
3370
+ if (Array.isArray(val)) {
3371
+ const idx = val.indexOf(oldNode);
3372
+ if (idx !== -1) {
3373
+ val[idx] = newNode;
3374
+ return true;
3375
+ }
3376
+ }
3377
+ }
3378
+ return false;
3379
+ }
3380
+ function applySaltedStringVault(ast, seed = 2654435769, minStringLength = 4, hotExemptNodes) {
3381
+ if (isAstAlreadySalted(ast)) {
3382
+ return {
3383
+ encryptedStringsCount: 0,
3384
+ integrityToken: computeFnv1aHash("already-salted", seed),
3385
+ vaultVarName: "",
3386
+ decryptFnName: ""
3387
+ };
3388
+ }
3389
+ const targetsToReplace = [];
3390
+ const encryptedPayloads = [];
3391
+ walk6.ancestor(ast, {
3392
+ Literal(node, ancestors) {
3393
+ if (typeof node.value !== "string") return;
3394
+ if (node.value.length < minStringLength) return;
3395
+ if (DIRECTIVE_STRINGS2.has(node.value)) return;
3396
+ const parent = ancestors[ancestors.length - 2];
3397
+ if (!parent) return;
3398
+ if ((parent.type === "ImportDeclaration" || parent.type === "ExportNamedDeclaration" || parent.type === "ExportAllDeclaration") && parent.source === node) {
3399
+ return;
3400
+ }
3401
+ if (parent.type === "Property" && parent.key === node && !parent.computed) {
3402
+ return;
3403
+ }
3404
+ if ((parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") && parent.key === node && !parent.computed) {
3405
+ return;
3406
+ }
3407
+ if (hotExemptNodes) {
3408
+ for (let i = ancestors.length - 1; i >= 0; i--) {
3409
+ if (hotExemptNodes.has(ancestors[i])) {
3410
+ return;
3411
+ }
3412
+ }
3413
+ }
3414
+ const callSiteIdx = targetsToReplace.length;
3415
+ const localSalt = computeFnv1aHash(`salt:${seed}:${callSiteIdx}`, seed) & 2147483647 | 1;
3416
+ targetsToReplace.push({
3417
+ node,
3418
+ parent,
3419
+ callSiteIdx,
3420
+ localSalt,
3421
+ rawString: node.value
3422
+ });
3423
+ }
3424
+ });
3425
+ if (targetsToReplace.length === 0) {
3426
+ return {
3427
+ encryptedStringsCount: 0,
3428
+ integrityToken: computeFnv1aHash("empty-salted", seed),
3429
+ vaultVarName: "",
3430
+ decryptFnName: ""
3431
+ };
3432
+ }
3433
+ const wasmResult = injectWasmVault(ast, seed);
3434
+ const kdfFnName = wasmResult.kdfFnName;
3435
+ const suffix = computeFnv1aHash(`salted:${seed}`, seed).toString(36);
3436
+ const vaultVarName = `_uP${suffix}`;
3437
+ const cacheVarName = `_uCache${suffix}`;
3438
+ const decryptFnName = `_uD${suffix}`;
3439
+ for (const target of targetsToReplace) {
3440
+ const k = fallbackKdf(target.callSiteIdx, target.localSalt, 0, seed);
3441
+ encryptedPayloads.push(encodeSaltedString(target.rawString, k));
3442
+ const callExpr = {
3443
+ type: "CallExpression",
3444
+ callee: {
3445
+ type: "Identifier",
3446
+ name: decryptFnName
3447
+ },
3448
+ arguments: [
3449
+ {
3450
+ type: "Literal",
3451
+ value: target.callSiteIdx,
3452
+ raw: String(target.callSiteIdx)
3453
+ },
3454
+ {
3455
+ type: "Literal",
3456
+ value: target.localSalt,
3457
+ raw: String(target.localSalt)
3458
+ }
3459
+ ],
3460
+ optional: false
3461
+ };
3462
+ replaceNodeInParent(target.parent, target.node, callExpr);
3463
+ }
3464
+ const serializedTable = JSON.stringify(encryptedPayloads);
3465
+ const integrityToken = computeFnv1aHash(serializedTable, seed);
3466
+ const helperSnippet = `var ${vaultVarName} = ${serializedTable};
3467
+ var ${cacheVarName} = [];
3468
+ function ${decryptFnName}(i, s) {
3469
+ if (${cacheVarName}[i] !== void 0) return ${cacheVarName}[i];
3470
+ var d = typeof window !== 'undefined' && window.__unpeek_delta != null ? window.__unpeek_delta : 0;
3471
+ var k = ${kdfFnName}(i, s, d);
3472
+ var p = ${vaultVarName}[i], o = '';
3473
+ for (var j = 0; j < p.length; j++) {
3474
+ o += String.fromCharCode(p.charCodeAt(j) ^ (((k >>> (j % 24)) & 127) | 1));
3475
+ }
3476
+ return (${cacheVarName}[i] = o);
3477
+ }`;
3478
+ const parsedHelper = acorn5.parse(helperSnippet, {
3479
+ ecmaVersion: "latest",
3480
+ sourceType: "script"
3481
+ });
3482
+ ast.body.unshift(...parsedHelper.body);
3483
+ return {
3484
+ encryptedStringsCount: targetsToReplace.length,
3485
+ integrityToken,
3486
+ vaultVarName,
3487
+ decryptFnName
3488
+ };
3489
+ }
3490
+
3491
+ // src/ast/index.ts
3492
+ function isAstAlreadyProtected(ast) {
3493
+ if (!ast || !Array.isArray(ast.body)) return false;
3494
+ return ast.body.some((stmt) => {
3495
+ if (stmt.type === "VariableDeclaration" && Array.isArray(stmt.declarations)) {
3496
+ for (const d of stmt.declarations) {
3497
+ const name = d.id?.name;
3498
+ if (typeof name === "string") {
3499
+ if (name === "_d" || name.startsWith("_uC") || name.startsWith("_uD") || name.startsWith("_uS") || name.startsWith("_uVm") || name.startsWith("_wKdf") || name.startsWith("_m") || name.startsWith("_w") || name.startsWith("_k") || name.startsWith("_a") && d.init?.type === "CallExpression" && d.init.callee?.type === "FunctionExpression" && d.init.callee?.id?.name === "f") {
3500
+ return true;
3501
+ }
3502
+ }
3503
+ }
3504
+ }
3505
+ if (stmt.type === "ExpressionStatement" && stmt.expression?.type === "CallExpression") {
3506
+ const callee = stmt.expression.callee;
3507
+ if (callee?.type === "FunctionExpression") {
3508
+ const name = callee.id?.name;
3509
+ if (typeof name === "string" && (name.startsWith("_u$") || name.startsWith("_$") || name.startsWith("_s") || name.startsWith("$b"))) {
3510
+ return true;
3511
+ }
3512
+ }
3513
+ }
1683
3514
  return false;
1684
3515
  });
1685
3516
  }
1686
3517
  function transformJavaScript(code, options = {}) {
1687
3518
  const seed = options.seed ?? 2654435769;
1688
3519
  const minStringLength = options.minStringLength ?? 4;
3520
+ const isAggressive = options.aggressive ?? false;
1689
3521
  if (!code || !code.trim()) {
1690
3522
  return {
1691
3523
  code,
@@ -1696,7 +3528,9 @@ function transformJavaScript(code, options = {}) {
1696
3528
  hotFunctionsSkipped: [],
1697
3529
  coldFunctionsProtected: []
1698
3530
  },
1699
- integrityToken: computeFnv1aHash("", seed)
3531
+ integrityToken: computeFnv1aHash("", seed),
3532
+ virtualizedFunctionsCount: 0,
3533
+ shaderBuffersCount: 0
1700
3534
  };
1701
3535
  }
1702
3536
  const ast = parseJavaScriptAst(code);
@@ -1710,23 +3544,59 @@ function transformJavaScript(code, options = {}) {
1710
3544
  hotFunctionsSkipped: [],
1711
3545
  coldFunctionsProtected: []
1712
3546
  },
1713
- integrityToken: computeFnv1aHash(code, seed)
3547
+ integrityToken: computeFnv1aHash(code, seed),
3548
+ virtualizedFunctionsCount: 0,
3549
+ shaderBuffersCount: 0
1714
3550
  };
1715
3551
  }
1716
3552
  const {
1717
3553
  report: hotPathReport,
1718
3554
  coldFunctionNodes,
1719
- hotExemptNodes
3555
+ hotFunctionNodes,
3556
+ hotExemptNodes,
3557
+ serializedFunctionNodes
1720
3558
  } = analyzeAstHotPaths(ast);
3559
+ let virtualizedFunctionsCount = 0;
3560
+ if (isAggressive) {
3561
+ const vmRes = applyMicroVm(
3562
+ ast,
3563
+ coldFunctionNodes,
3564
+ serializedFunctionNodes,
3565
+ seed
3566
+ );
3567
+ virtualizedFunctionsCount = vmRes.virtualizedCount;
3568
+ }
1721
3569
  applyColdFlowGuard(ast, coldFunctionNodes, seed, hotExemptNodes);
1722
- const mangledSymbolsCount = applyPolymorphicMangler(ast, seed);
1723
- const { encryptedStringsCount, integrityToken } = applyStringVault(
3570
+ const mangledSymbolsCount = applyPolymorphicMangler(
1724
3571
  ast,
1725
3572
  seed,
1726
- minStringLength,
1727
- hotExemptNodes
3573
+ serializedFunctionNodes
1728
3574
  );
1729
- const outputCode = generate(ast, { indent: "", lineEnd: "" });
3575
+ let encryptedStringsCount = 0;
3576
+ let integrityToken = 0;
3577
+ let shaderBuffersCount = 0;
3578
+ if (isAggressive) {
3579
+ injectWasmVault(ast, seed);
3580
+ const saltedRes = applySaltedStringVault(
3581
+ ast,
3582
+ seed,
3583
+ minStringLength,
3584
+ hotExemptNodes
3585
+ );
3586
+ encryptedStringsCount = saltedRes.encryptedStringsCount;
3587
+ integrityToken = saltedRes.integrityToken;
3588
+ } else {
3589
+ const vaultRes = applyStringVault(
3590
+ ast,
3591
+ seed,
3592
+ minStringLength,
3593
+ hotExemptNodes
3594
+ );
3595
+ encryptedStringsCount = vaultRes.encryptedStringsCount;
3596
+ integrityToken = vaultRes.integrityToken;
3597
+ shaderBuffersCount = vaultRes.shaderBuffersCount ?? 0;
3598
+ }
3599
+ const outputCode = generateCompactJs(ast);
1730
3600
  let finalCode = outputCode;
1731
3601
  if (options.injectRuntimeShield) {
1732
3602
  const shield = generateRuntimeShield({
@@ -1744,11 +3614,29 @@ ${finalCode}`;
1744
3614
  encryptedStringsCount,
1745
3615
  mangledSymbolsCount,
1746
3616
  hotPathReport,
1747
- integrityToken
3617
+ integrityToken,
3618
+ virtualizedFunctionsCount,
3619
+ shaderBuffersCount
1748
3620
  };
1749
3621
  }
1750
3622
 
1751
3623
  // src/cli/protect.ts
3624
+ var ENTRY_PATTERN = /^(?:main|index|turbopack|webpack|runtime|app\/layout|app\/page|pages\/_app|pages\/index)[-._/]/i;
3625
+ function isEntryChunk(relPath, index, allRelPaths) {
3626
+ const norm = relPath.replace(/\\/g, "/");
3627
+ const base2 = path3.basename(norm);
3628
+ if (ENTRY_PATTERN.test(norm) || ENTRY_PATTERN.test(base2)) {
3629
+ return true;
3630
+ }
3631
+ const hasAnyPatternMatch = allRelPaths.some((p) => {
3632
+ const n = p.replace(/\\/g, "/");
3633
+ return ENTRY_PATTERN.test(n) || ENTRY_PATTERN.test(path3.basename(n));
3634
+ });
3635
+ if (!hasAnyPatternMatch && index === 0) {
3636
+ return true;
3637
+ }
3638
+ return false;
3639
+ }
1752
3640
  async function protectProject(options = {}) {
1753
3641
  const startTime = performance.now();
1754
3642
  const cwd = path3.resolve(options.cwd ?? process.cwd());
@@ -1759,8 +3647,10 @@ async function protectProject(options = {}) {
1759
3647
  const deterrentMode = options.deterrentMode ?? "passive";
1760
3648
  const injectRuntimeShield = options.injectRuntimeShield ?? true;
1761
3649
  const minStringLength = options.minStringLength ?? 4;
3650
+ const aggressive = options.aggressive ?? false;
1762
3651
  const vaultResult = relocateSourceMaps(outDir, cwd, keepPrivateMaps, privateMapsDir, false);
1763
3652
  const clientFiles = scanClientBundles(outDir);
3653
+ const allRelPaths = clientFiles.map((f) => path3.relative(outDir, f).replace(/\\/g, "/"));
1764
3654
  let originalBytes = 0;
1765
3655
  let protectedBytes = 0;
1766
3656
  let totalHotFunctionsSkipped = 0;
@@ -1782,23 +3672,26 @@ async function protectProject(options = {}) {
1782
3672
  const origBuf = Buffer.from(codeToTransform, "utf8");
1783
3673
  originalBytes += origBuf.byteLength;
1784
3674
  allOrigBufs.push(origBuf);
1785
- const relPath = path3.relative(outDir, filePath).replace(/\\/g, "/");
3675
+ const relPath = allRelPaths[i];
3676
+ const isEntry = isEntryChunk(relPath, i, allRelPaths);
3677
+ const shouldInjectShield = injectRuntimeShield && isEntry;
1786
3678
  const fileSeed = computeFnv1aHash(`${relPath}:${i}`, seed);
1787
3679
  const result = transformJavaScript(codeToTransform, {
1788
3680
  seed: fileSeed,
1789
3681
  minStringLength,
1790
3682
  filename: path3.basename(filePath),
1791
- injectRuntimeShield,
1792
- deterrentMode
3683
+ injectRuntimeShield: shouldInjectShield,
3684
+ deterrentMode,
3685
+ aggressive
1793
3686
  });
1794
3687
  let finalCode = result.code;
1795
- if (injectRuntimeShield) {
3688
+ if (shouldInjectShield && !finalCode.includes("__unpeek_tampered")) {
1796
3689
  const shield = generateRuntimeShield({
1797
3690
  seed: fileSeed,
1798
3691
  deterrentMode,
1799
3692
  expectedIntegrityHash: result.integrityToken
1800
3693
  });
1801
- if (shield.preambleCode && !finalCode.includes("(function _u$") && !finalCode.includes(shield.integrityCheckFnName) && !finalCode.startsWith(shield.preambleCode)) {
3694
+ if (shield.preambleCode && !finalCode.includes(shield.integrityCheckFnName) && !finalCode.startsWith(shield.preambleCode)) {
1802
3695
  finalCode = `${shield.preambleCode}
1803
3696
  ${finalCode}`;
1804
3697
  }