unpeek 1.15.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/README.md +68 -40
  2. package/README.tr.md +74 -46
  3. package/dist/ast/index.cjs +6 -4930
  4. package/dist/ast/index.d.cts +11 -72
  5. package/dist/ast/index.d.ts +11 -72
  6. package/dist/ast/index.js +12 -4888
  7. package/dist/browser.cjs +10 -4920
  8. package/dist/browser.d.cts +2 -3
  9. package/dist/browser.d.ts +2 -3
  10. package/dist/browser.js +16 -4883
  11. package/dist/bundler/unplugin.cjs +7 -4968
  12. package/dist/bundler/unplugin.d.cts +4 -2
  13. package/dist/bundler/unplugin.d.ts +1 -1
  14. package/dist/bundler/unplugin.js +12 -4934
  15. package/dist/chunk-24K5NDXH.cjs +370 -0
  16. package/dist/chunk-27HR647Q.js +190 -0
  17. package/dist/chunk-4TDLLEEU.cjs +15 -0
  18. package/dist/chunk-5LCMI2TL.js +575 -0
  19. package/dist/chunk-5M6Z7ZFT.cjs +83 -0
  20. package/dist/chunk-5QD6FZPB.js +197 -0
  21. package/dist/chunk-6N6S6WTQ.cjs +423 -0
  22. package/dist/chunk-7YVEHJVM.cjs +575 -0
  23. package/dist/chunk-GAVI2C44.cjs +197 -0
  24. package/dist/chunk-GZB7PFLY.js +370 -0
  25. package/dist/chunk-J5CGNZDM.cjs +190 -0
  26. package/dist/chunk-KQWNFKT2.js +423 -0
  27. package/dist/{cli/protect.cjs → chunk-LXP73HJC.cjs} +301 -1473
  28. package/dist/chunk-OOXSZTRV.js +18 -0
  29. package/dist/chunk-R6EBIR3T.cjs +14 -0
  30. package/dist/chunk-S4S2WXGC.js +14 -0
  31. package/dist/{cli/protect.js → chunk-UMPUYLLZ.js} +95 -1232
  32. package/dist/chunk-X5MKMFMX.js +83 -0
  33. package/dist/cli/index.cjs +169 -5956
  34. package/dist/cli/index.d.cts +20 -1
  35. package/dist/cli/index.d.ts +20 -1
  36. package/dist/cli/index.js +163 -5911
  37. package/dist/config.cjs +21 -342
  38. package/dist/config.d.cts +2 -2
  39. package/dist/config.d.ts +2 -2
  40. package/dist/config.js +12 -291
  41. package/dist/esbuild.cjs +10 -4972
  42. package/dist/esbuild.d.cts +2 -2
  43. package/dist/esbuild.d.ts +2 -2
  44. package/dist/esbuild.js +8 -4935
  45. package/dist/index.cjs +9 -6408
  46. package/dist/index.d.cts +26 -17
  47. package/dist/index.d.ts +26 -17
  48. package/dist/index.js +20 -6359
  49. package/dist/next/adapter.cjs +16 -5823
  50. package/dist/next/adapter.d.cts +6 -4
  51. package/dist/next/adapter.d.ts +3 -3
  52. package/dist/next/adapter.js +11 -5775
  53. package/dist/next/index.cjs +9 -5856
  54. package/dist/next/index.d.cts +24 -19
  55. package/dist/next/index.d.ts +24 -19
  56. package/dist/next/index.js +13 -5824
  57. package/dist/rollup.cjs +10 -4972
  58. package/dist/rollup.d.cts +2 -2
  59. package/dist/rollup.d.ts +2 -2
  60. package/dist/rollup.js +8 -4935
  61. package/dist/runtime/index.cjs +12 -435
  62. package/dist/runtime/index.d.cts +1 -1
  63. package/dist/runtime/index.d.ts +1 -1
  64. package/dist/runtime/index.js +9 -400
  65. package/dist/{types-CQYBNQND.d.ts → types-BBSRUEab.d.cts} +3 -7
  66. package/dist/{types-CQYBNQND.d.cts → types-BBSRUEab.d.ts} +3 -7
  67. package/dist/vite.cjs +10 -4972
  68. package/dist/vite.d.cts +2 -2
  69. package/dist/vite.d.ts +2 -2
  70. package/dist/vite.js +8 -4935
  71. package/dist/webpack.cjs +10 -4972
  72. package/dist/webpack.d.cts +2 -2
  73. package/dist/webpack.d.ts +2 -2
  74. package/dist/webpack.js +8 -4935
  75. package/package.json +54 -21
  76. package/dist/ast/index.cjs.map +0 -1
  77. package/dist/ast/index.js.map +0 -1
  78. package/dist/browser.cjs.map +0 -1
  79. package/dist/browser.js.map +0 -1
  80. package/dist/bundler/detector.cjs +0 -271
  81. package/dist/bundler/detector.cjs.map +0 -1
  82. package/dist/bundler/detector.d.cts +0 -13
  83. package/dist/bundler/detector.d.ts +0 -13
  84. package/dist/bundler/detector.js +0 -232
  85. package/dist/bundler/detector.js.map +0 -1
  86. package/dist/bundler/sourcemap-vault.cjs +0 -316
  87. package/dist/bundler/sourcemap-vault.cjs.map +0 -1
  88. package/dist/bundler/sourcemap-vault.d.cts +0 -7
  89. package/dist/bundler/sourcemap-vault.d.ts +0 -7
  90. package/dist/bundler/sourcemap-vault.js +0 -280
  91. package/dist/bundler/sourcemap-vault.js.map +0 -1
  92. package/dist/bundler/unplugin.cjs.map +0 -1
  93. package/dist/bundler/unplugin.js.map +0 -1
  94. package/dist/cli/index.cjs.map +0 -1
  95. package/dist/cli/index.js.map +0 -1
  96. package/dist/cli/init.cjs +0 -342
  97. package/dist/cli/init.cjs.map +0 -1
  98. package/dist/cli/init.d.cts +0 -16
  99. package/dist/cli/init.d.ts +0 -16
  100. package/dist/cli/init.js +0 -306
  101. package/dist/cli/init.js.map +0 -1
  102. package/dist/cli/protect.cjs.map +0 -1
  103. package/dist/cli/protect.d.cts +0 -5
  104. package/dist/cli/protect.d.ts +0 -5
  105. package/dist/cli/protect.js.map +0 -1
  106. package/dist/config.cjs.map +0 -1
  107. package/dist/config.js.map +0 -1
  108. package/dist/esbuild.cjs.map +0 -1
  109. package/dist/esbuild.js.map +0 -1
  110. package/dist/index.cjs.map +0 -1
  111. package/dist/index.js.map +0 -1
  112. package/dist/next/adapter.cjs.map +0 -1
  113. package/dist/next/adapter.js.map +0 -1
  114. package/dist/next/index.cjs.map +0 -1
  115. package/dist/next/index.js.map +0 -1
  116. package/dist/next/with-unpeek.cjs +0 -5865
  117. package/dist/next/with-unpeek.cjs.map +0 -1
  118. package/dist/next/with-unpeek.d.cts +0 -2
  119. package/dist/next/with-unpeek.d.ts +0 -2
  120. package/dist/next/with-unpeek.js +0 -5829
  121. package/dist/next/with-unpeek.js.map +0 -1
  122. package/dist/rollup.cjs.map +0 -1
  123. package/dist/rollup.js.map +0 -1
  124. package/dist/runtime/index.cjs.map +0 -1
  125. package/dist/runtime/index.js.map +0 -1
  126. package/dist/vite.cjs.map +0 -1
  127. package/dist/vite.js.map +0 -1
  128. package/dist/webpack.cjs.map +0 -1
  129. package/dist/webpack.js.map +0 -1
package/dist/rollup.js CHANGED
@@ -1,4940 +1,13 @@
1
- // src/bundler/unplugin.ts
2
- import { createUnplugin } from "unplugin";
3
-
4
- // src/ast/hot-path-detector.ts
5
- import * as acorn from "acorn";
6
- import * as walk from "acorn-walk";
7
- var ARRAY_HOF_METHODS = /* @__PURE__ */ new Set([
8
- "map",
9
- "filter",
10
- "reduce",
11
- "forEach",
12
- "flatMap",
13
- "find",
14
- "findIndex",
15
- "some",
16
- "every"
17
- ]);
18
- var ANIMATION_FRAME_CALLS = /* @__PURE__ */ new Set([
19
- "requestAnimationFrame",
20
- "cancelAnimationFrame",
21
- "useFrame",
22
- "useLenis",
23
- "setAnimationLoop",
24
- "onBeforeRender",
25
- "updateMatrixWorld",
26
- "raf"
27
- ]);
28
- var DEFAULT_IMPORT_SOURCES = {
29
- "@react-three/fiber": ["useFrame"],
30
- lenis: ["useLenis", "raf"],
31
- "lenis/react": ["useLenis"],
32
- three: ["onBeforeRender", "updateMatrixWorld", "useFrame"],
33
- gsap: ["ticker"]
34
- };
35
- var DEFAULT_HOC_WRAPPERS = /* @__PURE__ */ new Set([
36
- "memo",
37
- "forwardRef",
38
- "React.memo",
39
- "React.forwardRef",
40
- "observer",
41
- "connect"
42
- ]);
43
- var DEFAULT_EVENT_HANDLER_REGEX = /^(?:on|handle)(?!Tick|Render|Update|Frame|Animate|Physics)[A-Z]/;
44
- var DEFAULT_HOOK_REGEX = /^use[A-Z0-9]/;
45
- var REACT_HOOK_OR_RENDER_CALLS = /* @__PURE__ */ new Set([
46
- "useState",
47
- "useEffect",
48
- "useMemo",
49
- "useCallback",
50
- "useRef",
51
- "useLayoutEffect",
52
- "useActionState",
53
- "useFormStatus",
54
- "useOptimistic",
55
- "jsx",
56
- "jsxs",
57
- "_jsx",
58
- "_jsxs",
59
- "createElement"
60
- ]);
61
- var FUNCTION_NODE_TYPES = /* @__PURE__ */ new Set([
62
- "FunctionDeclaration",
63
- "FunctionExpression",
64
- "ArrowFunctionExpression"
65
- ]);
66
- function parseJavaScriptAst(code) {
67
- try {
68
- return acorn.parse(code, {
69
- ecmaVersion: "latest",
70
- sourceType: "module",
71
- allowReturnOutsideFunction: true
72
- });
73
- } catch {
74
- try {
75
- return acorn.parse(code, {
76
- ecmaVersion: "latest",
77
- sourceType: "script",
78
- allowReturnOutsideFunction: true
79
- });
80
- } catch {
81
- return null;
82
- }
83
- }
84
- }
85
- function isHocCall(callNode, hocWrappers) {
86
- if (!callNode || callNode.type !== "CallExpression") return false;
87
- const callee = callNode.callee;
88
- if (!callee) return false;
89
- const wrappers = hocWrappers ?? DEFAULT_HOC_WRAPPERS;
90
- if (callee.type === "Identifier") {
91
- return wrappers.has(callee.name);
92
- }
93
- if (callee.type === "MemberExpression" && !callee.computed && callee.property?.type === "Identifier") {
94
- if (wrappers.has(callee.property.name)) return true;
95
- if (callee.object?.type === "Identifier") {
96
- const full2 = `${callee.object.name}.${callee.property.name}`;
97
- if (wrappers.has(full2)) return true;
98
- }
99
- }
100
- return false;
101
- }
102
- function getFunctionLabel(node, ancestors, hocWrappers) {
103
- if (node.id && typeof node.id.name === "string") {
104
- return node.id.name;
105
- }
106
- const parent = ancestors[ancestors.length - 2];
107
- if (parent) {
108
- if (parent.type === "VariableDeclarator" && parent.id?.type === "Identifier") {
109
- return parent.id.name;
110
- }
111
- if (parent.type === "Property") {
112
- if (parent.key?.type === "Identifier") {
113
- return parent.key.name;
114
- }
115
- if (parent.key?.type === "Literal" && typeof parent.key.value === "string") {
116
- return parent.key.value;
117
- }
118
- }
119
- if (parent.type === "MethodDefinition" && parent.key?.type === "Identifier") {
120
- return parent.key.name;
121
- }
122
- if (parent.type === "AssignmentExpression" && parent.left?.type === "Identifier") {
123
- return parent.left.name;
124
- }
125
- if (parent.type === "CallExpression") {
126
- let idx = ancestors.length - 2;
127
- let matchedHoc = false;
128
- while (idx >= 0 && ancestors[idx].type === "CallExpression") {
129
- if (isHocCall(ancestors[idx], hocWrappers)) {
130
- matchedHoc = true;
131
- idx--;
132
- } else {
133
- break;
134
- }
135
- }
136
- if (matchedHoc && idx >= 0) {
137
- const outer = ancestors[idx];
138
- if (outer.type === "VariableDeclarator" && outer.id?.type === "Identifier") {
139
- return outer.id.name;
140
- }
141
- if (outer.type === "AssignmentExpression" && outer.left?.type === "Identifier") {
142
- return outer.left.name;
143
- }
144
- }
145
- }
146
- }
147
- return `anonymous_${node.start}`;
148
- }
149
- function isPascalCaseComponent(name) {
150
- return /^[A-Z][a-zA-Z0-9]*$/.test(name);
151
- }
152
- function isEventHandlerName(name, regex = DEFAULT_EVENT_HANDLER_REGEX) {
153
- return regex.test(name);
154
- }
155
- function findEnclosingScopeNode(ancestors, selfNode) {
156
- for (let i = ancestors.length - 1; i >= 0; i--) {
157
- const anc = ancestors[i];
158
- if (anc !== selfNode && (FUNCTION_NODE_TYPES.has(anc.type) || anc.type === "Program")) {
159
- return anc;
160
- }
161
- }
162
- return ancestors[0];
163
- }
164
- function findEnclosingFunction(ancestors, selfNode) {
165
- for (let i = ancestors.length - 1; i >= 0; i--) {
166
- if (ancestors[i] !== selfNode && FUNCTION_NODE_TYPES.has(ancestors[i].type)) {
167
- return ancestors[i];
168
- }
169
- }
170
- return null;
171
- }
172
- function findOutermostModuleFunction(ancestors) {
173
- const fnList = [];
174
- for (let i = 0; i < ancestors.length; i++) {
175
- if (FUNCTION_NODE_TYPES.has(ancestors[i].type)) {
176
- fnList.push(ancestors[i]);
177
- }
178
- }
179
- if (fnList.length === 0) return null;
180
- if (fnList.length === 1) return fnList[0];
181
- return fnList[1];
182
- }
183
- function isZeroArgIifeFactoryFunction(node) {
184
- if (!node || node.params && node.params.length > 0) return false;
185
- if (!node.body || node.body.type !== "BlockStatement") return false;
186
- const stmts = (node.body.body || []).filter(
187
- (s) => !(s.type === "ExpressionStatement" && s.directive)
188
- );
189
- if (stmts.length !== 1 || stmts[0].type !== "ReturnStatement") return false;
190
- const retArg = stmts[0].argument;
191
- if (!retArg || retArg.type !== "CallExpression") return false;
192
- const callee = retArg.callee;
193
- return callee && (callee.type === "FunctionExpression" || callee.type === "ArrowFunctionExpression") && callee.body?.type === "BlockStatement";
194
- }
195
- function containsLoopOrAnimation(fnNode, animationCalls = ANIMATION_FRAME_CALLS) {
196
- let found = false;
197
- walk.simple(fnNode, {
198
- ForStatement() {
199
- found = true;
200
- },
201
- ForInStatement() {
202
- found = true;
203
- },
204
- ForOfStatement() {
205
- found = true;
206
- },
207
- WhileStatement() {
208
- found = true;
209
- },
210
- DoWhileStatement() {
211
- found = true;
212
- },
213
- CallExpression(callNode) {
214
- let cName = "";
215
- let mProp = "";
216
- if (callNode.callee?.type === "Identifier") {
217
- cName = callNode.callee.name;
218
- } else if (callNode.callee?.type === "MemberExpression" && !callNode.callee.computed && callNode.callee.property?.type === "Identifier") {
219
- mProp = callNode.callee.property.name;
220
- }
221
- const isTickerAdd = mProp === "add" && (callNode.callee?.object?.name === "ticker" || callNode.callee?.object?.property?.name === "ticker");
222
- if (animationCalls.has(cName) || animationCalls.has(mProp) || isTickerAdd) {
223
- found = true;
224
- }
225
- }
226
- });
227
- return found;
228
- }
229
- function analyzeAstHotPaths(ast, config) {
230
- const hotFunctionNodes = /* @__PURE__ */ new WeakSet();
231
- const coldFunctionNodes = /* @__PURE__ */ new WeakSet();
232
- const hotExemptNodes = /* @__PURE__ */ new WeakSet();
233
- const serializedFunctionNodes = /* @__PURE__ */ new WeakSet();
234
- const serializedWorkerNodes = /* @__PURE__ */ new Set();
235
- const trueHotNodes = /* @__PURE__ */ new Set();
236
- const shallowComponentNodes = /* @__PURE__ */ new Set();
237
- const coldForcedNodes = /* @__PURE__ */ new Set();
238
- const directHotNodes = /* @__PURE__ */ new Set();
239
- const serializerHelperNodes = /* @__PURE__ */ new Set();
240
- const allFunctions = [];
241
- const fnByName = /* @__PURE__ */ new Map();
242
- const scopeFunctions = /* @__PURE__ */ new Map();
243
- const fnScopeChain = /* @__PURE__ */ new Map();
244
- const fnParams = /* @__PURE__ */ new Map();
245
- const fnVarAliases = /* @__PURE__ */ new Map();
246
- const callerToCallees = /* @__PURE__ */ new Map();
247
- const pendingSerializedRefs = [];
248
- const pendingHotRefs = [];
249
- const allCallSites = [];
250
- const animationCalls = new Set(ANIMATION_FRAME_CALLS);
251
- if (config?.hotPath?.customAnimationCalls) {
252
- for (const c of config.hotPath.customAnimationCalls) {
253
- animationCalls.add(c);
254
- }
255
- }
256
- const mergedImportSources = {
257
- ...DEFAULT_IMPORT_SOURCES,
258
- ...config?.hotPath?.importSources ?? {}
259
- };
260
- if (ast && Array.isArray(ast.body)) {
261
- for (const stmt of ast.body) {
262
- if (stmt.type === "ImportDeclaration" && stmt.source?.value) {
263
- const sourcePkg = String(stmt.source.value);
264
- const sourceMethods = mergedImportSources[sourcePkg];
265
- for (const spec of stmt.specifiers || []) {
266
- if (spec.type === "ImportSpecifier") {
267
- const importedName = spec.imported?.name ?? spec.imported?.value;
268
- const localName = spec.local?.name;
269
- if (localName && importedName) {
270
- const isKnownSource = sourceMethods !== void 0;
271
- const isListedMethod = sourceMethods && (sourceMethods.includes(importedName) || sourceMethods.includes("*"));
272
- const isKnownAnimCall = ANIMATION_FRAME_CALLS.has(importedName);
273
- if (isKnownSource && isListedMethod || isKnownAnimCall) {
274
- animationCalls.add(localName);
275
- }
276
- }
277
- }
278
- }
279
- }
280
- }
281
- }
282
- const hocWrappers = new Set(DEFAULT_HOC_WRAPPERS);
283
- if (config?.hotPath?.hocWrappers) {
284
- for (const h of config.hotPath.hocWrappers) {
285
- hocWrappers.add(h);
286
- }
287
- }
288
- const arrayHofMethods = new Set(ARRAY_HOF_METHODS);
289
- if (config?.hotPath?.arrayHofMethods) {
290
- for (const m of config.hotPath.arrayHofMethods) {
291
- arrayHofMethods.add(m);
292
- }
293
- }
294
- const eventHandlerRegex = config?.hotPath?.eventHandlerRegex ?? DEFAULT_EVENT_HANDLER_REGEX;
295
- const hookRegex = config?.hotPath?.hookPattern ?? DEFAULT_HOOK_REGEX;
296
- const customHooksSet = new Set(config?.hotPath?.customHooks ?? []);
297
- function isHookName(name) {
298
- if (!name) return false;
299
- return customHooksSet.has(name) || hookRegex.test(name);
300
- }
301
- const excludedComponents = new Set(config?.hotPath?.excludeComponents ?? []);
302
- const maxPipelineCallers = config?.hotPath?.maxPipelineCallers ?? 2;
303
- function ensureFnParams(fnNode) {
304
- let paramSet = fnParams.get(fnNode);
305
- if (!paramSet) {
306
- paramSet = /* @__PURE__ */ new Set();
307
- for (const p of fnNode.params || []) {
308
- if (p?.type === "Identifier") {
309
- paramSet.add(p.name);
310
- } else if (p?.type === "AssignmentPattern" && p.left?.type === "Identifier") {
311
- paramSet.add(p.left.name);
312
- }
313
- }
314
- fnParams.set(fnNode, paramSet);
315
- }
316
- return paramSet;
317
- }
318
- function recordVarAlias(scopeNode, varName, rhsName) {
319
- let map = fnVarAliases.get(scopeNode);
320
- if (!map) {
321
- map = /* @__PURE__ */ new Map();
322
- fnVarAliases.set(scopeNode, map);
323
- }
324
- map.set(varName, rhsName);
325
- }
326
- function resolveAliasTarget(scopeNode, identName) {
327
- const map = fnVarAliases.get(scopeNode);
328
- let cur = identName;
329
- const seen = /* @__PURE__ */ new Set();
330
- while (map && map.has(cur) && !seen.has(cur)) {
331
- seen.add(cur);
332
- cur = map.get(cur);
333
- }
334
- return cur;
335
- }
336
- function markSerializedFunction(node) {
337
- node._unpeekSerialized = true;
338
- serializedWorkerNodes.add(node);
339
- serializedFunctionNodes.add(node);
340
- hotFunctionNodes.add(node);
341
- directHotNodes.add(node);
342
- hotExemptNodes.add(node);
343
- }
344
- function registerFunctionNode(node, ancestors) {
345
- const name = getFunctionLabel(node, ancestors, hocWrappers);
346
- allFunctions.push({ node, name });
347
- fnByName.set(name, node);
348
- const paramSet = /* @__PURE__ */ new Set();
349
- for (const p of node.params || []) {
350
- if (p?.type === "Identifier") {
351
- paramSet.add(p.name);
352
- } else if (p?.type === "AssignmentPattern" && p.left?.type === "Identifier") {
353
- paramSet.add(p.left.name);
354
- }
355
- }
356
- fnParams.set(node, paramSet);
357
- const enclosingScope = findEnclosingScopeNode(ancestors, node);
358
- let localMap = scopeFunctions.get(enclosingScope);
359
- if (!localMap) {
360
- localMap = /* @__PURE__ */ new Map();
361
- scopeFunctions.set(enclosingScope, localMap);
362
- }
363
- localMap.set(name, node);
364
- const parent = ancestors[ancestors.length - 2];
365
- if (parent?.type === "VariableDeclarator" && parent.id?.type === "Identifier") {
366
- fnByName.set(parent.id.name, node);
367
- localMap.set(parent.id.name, node);
368
- } else if (parent?.type === "AssignmentExpression" && parent.left?.type === "Identifier") {
369
- fnByName.set(parent.left.name, node);
370
- localMap.set(parent.left.name, node);
371
- } else if (parent?.type === "AssignmentExpression" && parent.left?.type === "MemberExpression" && !parent.left.computed && parent.left.property?.type === "Identifier") {
372
- const propName = parent.left.property.name;
373
- fnByName.set(propName, node);
374
- localMap.set(propName, node);
375
- if (parent.left.object?.type === "Identifier") {
376
- const qual = `${parent.left.object.name}.${propName}`;
377
- fnByName.set(qual, node);
378
- localMap.set(qual, node);
379
- }
380
- }
381
- const grandParent = ancestors[ancestors.length - 3];
382
- const greatGrandParent = ancestors[ancestors.length - 4];
383
- if (parent?.type === "Property" && parent.key?.type === "Identifier" && grandParent?.type === "ObjectExpression" && greatGrandParent?.type === "VariableDeclarator" && greatGrandParent.id?.type === "Identifier") {
384
- const qualified = `${greatGrandParent.id.name}.${parent.key.name}`;
385
- fnByName.set(qualified, node);
386
- localMap.set(qualified, node);
387
- }
388
- const chain = [];
389
- for (let i = ancestors.length - 1; i >= 0; i--) {
390
- if (ancestors[i] !== node && (FUNCTION_NODE_TYPES.has(ancestors[i].type) || ancestors[i].type === "Program")) {
391
- chain.push(ancestors[i]);
392
- }
393
- }
394
- fnScopeChain.set(node, chain);
395
- if (isPascalCaseComponent(name) && !excludedComponents.has(name)) {
396
- shallowComponentNodes.add(node);
397
- hotFunctionNodes.add(node);
398
- directHotNodes.add(node);
399
- hotExemptNodes.add(node);
400
- }
401
- if (isHookName(name)) {
402
- shallowComponentNodes.add(node);
403
- hotFunctionNodes.add(node);
404
- directHotNodes.add(node);
405
- hotExemptNodes.add(node);
406
- }
407
- if (isZeroArgIifeFactoryFunction(node)) {
408
- markSerializedFunction(node);
409
- }
410
- }
411
- function resolveCalleeNode(callerNode, calleeKey) {
412
- const directLocal = scopeFunctions.get(callerNode)?.get(calleeKey);
413
- if (directLocal) return directLocal;
414
- const chain = fnScopeChain.get(callerNode);
415
- if (chain) {
416
- for (const scopeNode of chain) {
417
- const localMap = scopeFunctions.get(scopeNode);
418
- const found = localMap?.get(calleeKey);
419
- if (found) return found;
420
- }
421
- }
422
- return fnByName.get(calleeKey);
423
- }
424
- function queueSerializedTarget(target, enclosingScope) {
425
- if (!target) return;
426
- if (FUNCTION_NODE_TYPES.has(target.type)) {
427
- markSerializedFunction(target);
428
- } else if (target.type === "Identifier") {
429
- pendingSerializedRefs.push({ scopeNode: enclosingScope, name: target.name });
430
- } else if (target.type === "MemberExpression" && !target.computed && target.property?.type === "Identifier") {
431
- pendingSerializedRefs.push({
432
- scopeNode: enclosingScope,
433
- name: target.property.name
434
- });
435
- if (target.object?.type === "Identifier") {
436
- pendingSerializedRefs.push({
437
- scopeNode: enclosingScope,
438
- name: `${target.object.name}.${target.property.name}`
439
- });
440
- }
441
- }
442
- }
443
- walk.ancestor(ast, {
444
- FunctionDeclaration(node, _state, ancestors) {
445
- registerFunctionNode(node, ancestors);
446
- },
447
- FunctionExpression(node, _state, ancestors) {
448
- registerFunctionNode(node, ancestors);
449
- },
450
- ArrowFunctionExpression(node, _state, ancestors) {
451
- registerFunctionNode(node, ancestors);
452
- },
453
- VariableDeclarator(node, _state, ancestors) {
454
- if (node.id?.type === "Identifier" && node.init?.type === "Identifier") {
455
- const scopeNode = findEnclosingFunction(ancestors) ?? ast;
456
- recordVarAlias(scopeNode, node.id.name, node.init.name);
457
- }
458
- },
459
- AssignmentExpression(node, _state, ancestors) {
460
- const left = node.left;
461
- if (left?.type === "Identifier" && node.right?.type === "Identifier") {
462
- const scopeNode = findEnclosingFunction(ancestors) ?? ast;
463
- recordVarAlias(scopeNode, left.name, node.right.name);
464
- }
465
- const isBareOnMessage = left?.type === "Identifier" && left.name === "onmessage";
466
- const isSelfOnMessage = left?.type === "MemberExpression" && !left.computed && left.object?.type === "Identifier" && left.object.name === "self" && left.property?.type === "Identifier" && left.property.name === "onmessage";
467
- if (isBareOnMessage || isSelfOnMessage) {
468
- const enclosingFn = findEnclosingFunction(ancestors);
469
- if (enclosingFn) {
470
- markSerializedFunction(enclosingFn);
471
- }
472
- const outerFn = findOutermostModuleFunction(ancestors);
473
- if (outerFn) {
474
- markSerializedFunction(outerFn);
475
- }
476
- const scopeNode = enclosingFn ?? ast;
477
- queueSerializedTarget(node.right, scopeNode);
478
- }
479
- },
480
- ObjectExpression(node, _state, ancestors) {
481
- const props = node.properties || [];
482
- const propMap = /* @__PURE__ */ new Map();
483
- for (const p of props) {
484
- if (p?.type === "Property" && !p.computed) {
485
- const keyName = p.key?.type === "Identifier" ? p.key.name : p.key?.type === "Literal" ? String(p.key.value) : "";
486
- if (keyName) {
487
- propMap.set(keyName, p.value);
488
- }
489
- }
490
- }
491
- const hasWorkerDescriptorShape = propMap.has("init") && propMap.has("dependencies") || propMap.has("isWorkerModule") || propMap.has("getTransferables") && (propMap.has("init") || propMap.has("dependencies"));
492
- if (hasWorkerDescriptorShape) {
493
- const scopeNode = findEnclosingFunction(ancestors) ?? ast;
494
- for (const key of ["init", "getTransferables", "worker"]) {
495
- const val = propMap.get(key);
496
- if (val) queueSerializedTarget(val, scopeNode);
497
- }
498
- const deps = propMap.get("dependencies");
499
- if (deps?.type === "ArrayExpression") {
500
- for (const el of deps.elements || []) {
501
- if (el) queueSerializedTarget(el, scopeNode);
502
- }
503
- }
504
- }
505
- },
506
- CallExpression(node, _state, ancestors) {
507
- const callee = node.callee;
508
- let calleeName = "";
509
- let memberProp = "";
510
- let qualifiedCall = "";
511
- if (callee?.type === "Identifier") {
512
- calleeName = callee.name;
513
- qualifiedCall = calleeName;
514
- } else if (callee?.type === "MemberExpression" && !callee.computed && callee.property?.type === "Identifier") {
515
- memberProp = callee.property.name;
516
- if (callee.object?.type === "Identifier") {
517
- qualifiedCall = `${callee.object.name}.${memberProp}`;
518
- } else if (callee.object?.type === "ThisExpression") {
519
- qualifiedCall = memberProp;
520
- }
521
- }
522
- const enclosingFn = findEnclosingFunction(ancestors);
523
- const currentScope = enclosingFn ?? ast;
524
- if (qualifiedCall || memberProp) {
525
- allCallSites.push({
526
- scopeNode: currentScope,
527
- calleeKey: qualifiedCall || memberProp,
528
- args: node.arguments || []
529
- });
530
- if (enclosingFn) {
531
- let set = callerToCallees.get(enclosingFn);
532
- if (!set) {
533
- set = /* @__PURE__ */ new Set();
534
- callerToCallees.set(enclosingFn, set);
535
- }
536
- if (qualifiedCall) set.add(qualifiedCall);
537
- if (memberProp && !arrayHofMethods.has(memberProp)) {
538
- set.add(memberProp);
539
- }
540
- }
541
- }
542
- if (memberProp === "toString" && (!node.arguments || node.arguments.length === 0) && callee?.type === "MemberExpression") {
543
- const targetObj = callee.object;
544
- queueSerializedTarget(targetObj, currentScope);
545
- if (targetObj?.type === "Identifier" && enclosingFn) {
546
- const resolvedName = resolveAliasTarget(enclosingFn, targetObj.name);
547
- if (ensureFnParams(enclosingFn).has(resolvedName)) {
548
- serializerHelperNodes.add(enclosingFn);
549
- }
550
- if (resolvedName !== targetObj.name) {
551
- queueSerializedTarget({ type: "Identifier", name: resolvedName }, currentScope);
552
- }
553
- }
554
- }
555
- if ((memberProp === "call" || memberProp === "apply") && callee?.type === "MemberExpression" && callee.object?.type === "MemberExpression" && callee.object.property?.type === "Identifier" && callee.object.property.name === "toString" && node.arguments?.length > 0) {
556
- const firstArg = node.arguments[0];
557
- queueSerializedTarget(firstArg, currentScope);
558
- if (firstArg?.type === "Identifier" && enclosingFn) {
559
- const resolvedName = resolveAliasTarget(enclosingFn, firstArg.name);
560
- if (ensureFnParams(enclosingFn).has(resolvedName)) {
561
- serializerHelperNodes.add(enclosingFn);
562
- }
563
- if (resolvedName !== firstArg.name) {
564
- queueSerializedTarget({ type: "Identifier", name: resolvedName }, currentScope);
565
- }
566
- }
567
- }
568
- if (calleeName === "importScripts" || memberProp === "importScripts" && callee?.object?.type === "Identifier" && callee.object.name === "self") {
569
- if (enclosingFn) markSerializedFunction(enclosingFn);
570
- const outerFn = findOutermostModuleFunction(ancestors);
571
- if (outerFn) markSerializedFunction(outerFn);
572
- }
573
- const isTickerAdd = memberProp === "add" && (callee?.object?.name === "ticker" || callee?.object?.property?.name === "ticker");
574
- if (animationCalls.has(calleeName) || animationCalls.has(memberProp) || isTickerAdd) {
575
- if (enclosingFn) {
576
- trueHotNodes.add(enclosingFn);
577
- hotFunctionNodes.add(enclosingFn);
578
- directHotNodes.add(enclosingFn);
579
- }
580
- for (const arg of node.arguments || []) {
581
- if (FUNCTION_NODE_TYPES.has(arg.type)) {
582
- trueHotNodes.add(arg);
583
- hotFunctionNodes.add(arg);
584
- directHotNodes.add(arg);
585
- hotExemptNodes.add(arg);
586
- } else if (arg?.type === "Identifier") {
587
- pendingHotRefs.push({ scopeNode: currentScope, name: arg.name });
588
- allCallSites.push({
589
- scopeNode: currentScope,
590
- calleeKey: arg.name,
591
- args: [arg]
592
- });
593
- }
594
- }
595
- }
596
- if (arrayHofMethods.has(memberProp)) {
597
- if (enclosingFn !== null) {
598
- for (const arg of node.arguments || []) {
599
- if (FUNCTION_NODE_TYPES.has(arg.type)) {
600
- trueHotNodes.add(arg);
601
- hotFunctionNodes.add(arg);
602
- directHotNodes.add(arg);
603
- hotExemptNodes.add(arg);
604
- } else if (arg?.type === "Identifier") {
605
- allCallSites.push({
606
- scopeNode: currentScope,
607
- calleeKey: arg.name,
608
- args: [arg]
609
- });
610
- }
611
- }
612
- } else {
613
- for (const arg of node.arguments || []) {
614
- const isAnonymousFunction = arg.type === "FunctionExpression" && !arg.id || arg.type === "ArrowFunctionExpression";
615
- if (isAnonymousFunction) {
616
- coldForcedNodes.add(arg);
617
- }
618
- }
619
- }
620
- }
621
- if (calleeName === "useEffect" || memberProp === "useEffect" || calleeName === "useLayoutEffect" || memberProp === "useLayoutEffect") {
622
- const effectArg = node.arguments?.[0];
623
- if (effectArg && FUNCTION_NODE_TYPES.has(effectArg.type)) {
624
- if (!containsLoopOrAnimation(effectArg, animationCalls)) {
625
- coldForcedNodes.add(effectArg);
626
- if (effectArg.body?.type === "BlockStatement") {
627
- for (const s of effectArg.body.body || []) {
628
- if (s.type === "ReturnStatement" && s.argument && FUNCTION_NODE_TYPES.has(s.argument.type) && !containsLoopOrAnimation(s.argument, animationCalls)) {
629
- coldForcedNodes.add(s.argument);
630
- }
631
- }
632
- }
633
- }
634
- }
635
- }
636
- if (REACT_HOOK_OR_RENDER_CALLS.has(calleeName) || REACT_HOOK_OR_RENDER_CALLS.has(memberProp) || isHookName(calleeName) || isHookName(memberProp)) {
637
- if (enclosingFn) {
638
- shallowComponentNodes.add(enclosingFn);
639
- hotFunctionNodes.add(enclosingFn);
640
- directHotNodes.add(enclosingFn);
641
- hotExemptNodes.add(enclosingFn);
642
- }
643
- }
644
- },
645
- ForStatement(node, _state, ancestors) {
646
- hotExemptNodes.add(node);
647
- const enc = findEnclosingFunction(ancestors);
648
- if (enc) {
649
- trueHotNodes.add(enc);
650
- hotFunctionNodes.add(enc);
651
- directHotNodes.add(enc);
652
- }
653
- },
654
- ForInStatement(node, _state, ancestors) {
655
- hotExemptNodes.add(node);
656
- const enc = findEnclosingFunction(ancestors);
657
- if (enc) {
658
- trueHotNodes.add(enc);
659
- hotFunctionNodes.add(enc);
660
- directHotNodes.add(enc);
661
- }
662
- },
663
- ForOfStatement(node, _state, ancestors) {
664
- hotExemptNodes.add(node);
665
- const enc = findEnclosingFunction(ancestors);
666
- if (enc) {
667
- trueHotNodes.add(enc);
668
- hotFunctionNodes.add(enc);
669
- directHotNodes.add(enc);
670
- }
671
- },
672
- WhileStatement(node, _state, ancestors) {
673
- hotExemptNodes.add(node);
674
- const enc = findEnclosingFunction(ancestors);
675
- if (enc) {
676
- trueHotNodes.add(enc);
677
- hotFunctionNodes.add(enc);
678
- directHotNodes.add(enc);
679
- }
680
- },
681
- DoWhileStatement(node, _state, ancestors) {
682
- hotExemptNodes.add(node);
683
- const enc = findEnclosingFunction(ancestors);
684
- if (enc) {
685
- trueHotNodes.add(enc);
686
- hotFunctionNodes.add(enc);
687
- directHotNodes.add(enc);
688
- }
689
- }
690
- });
691
- for (const callSite of allCallSites) {
692
- const resolvedCallee = resolveCalleeNode(callSite.scopeNode, callSite.calleeKey);
693
- if (resolvedCallee && serializerHelperNodes.has(resolvedCallee)) {
694
- for (const arg of callSite.args) {
695
- queueSerializedTarget(arg, callSite.scopeNode);
696
- }
697
- }
698
- }
699
- for (const ref of pendingSerializedRefs) {
700
- const targetNode = resolveCalleeNode(ref.scopeNode, ref.name);
701
- if (targetNode) {
702
- markSerializedFunction(targetNode);
703
- }
704
- }
705
- for (const ref of pendingHotRefs) {
706
- const targetNode = resolveCalleeNode(ref.scopeNode, ref.name);
707
- if (targetNode) {
708
- trueHotNodes.add(targetNode);
709
- hotFunctionNodes.add(targetNode);
710
- directHotNodes.add(targetNode);
711
- hotExemptNodes.add(targetNode);
712
- }
713
- }
714
- for (const fn of allFunctions) {
715
- if (!trueHotNodes.has(fn.node) && !containsLoopOrAnimation(fn.node, animationCalls)) {
716
- if (!shallowComponentNodes.has(fn.node)) {
717
- if (fn.node.async === true || isEventHandlerName(fn.name, eventHandlerRegex)) {
718
- coldForcedNodes.add(fn.node);
719
- }
720
- }
721
- }
722
- }
723
- let forwardChanged = true;
724
- while (forwardChanged) {
725
- forwardChanged = false;
726
- for (const fn of allFunctions) {
727
- if (coldForcedNodes.has(fn.node)) continue;
728
- const chain = fnScopeChain.get(fn.node);
729
- if (!chain) continue;
730
- for (const anc of chain) {
731
- if (anc === fn.node) continue;
732
- if (serializedWorkerNodes.has(anc)) {
733
- if (!serializedWorkerNodes.has(fn.node)) {
734
- fn.node._unpeekSerialized = true;
735
- serializedWorkerNodes.add(fn.node);
736
- serializedFunctionNodes.add(fn.node);
737
- hotFunctionNodes.add(fn.node);
738
- hotExemptNodes.add(fn.node);
739
- forwardChanged = true;
740
- }
741
- break;
742
- }
743
- const isModuleContainer = (fnScopeChain.get(anc)?.length ?? 0) <= 1;
744
- if (trueHotNodes.has(anc) && !shallowComponentNodes.has(anc) && !isModuleContainer) {
745
- if (!trueHotNodes.has(fn.node)) {
746
- trueHotNodes.add(fn.node);
747
- hotFunctionNodes.add(fn.node);
748
- hotExemptNodes.add(fn.node);
749
- forwardChanged = true;
750
- }
751
- break;
752
- }
753
- }
754
- }
755
- for (const callerNode of Array.from(serializedWorkerNodes)) {
756
- const calleeNames = callerToCallees.get(callerNode);
757
- if (!calleeNames) continue;
758
- for (const cName of calleeNames) {
759
- const targetNode = resolveCalleeNode(callerNode, cName);
760
- if (targetNode && !serializedWorkerNodes.has(targetNode) && !coldForcedNodes.has(targetNode)) {
761
- targetNode._unpeekSerialized = true;
762
- serializedWorkerNodes.add(targetNode);
763
- serializedFunctionNodes.add(targetNode);
764
- hotFunctionNodes.add(targetNode);
765
- hotExemptNodes.add(targetNode);
766
- forwardChanged = true;
767
- }
768
- }
769
- }
770
- for (const callerNode of Array.from(trueHotNodes)) {
771
- const calleeNames = callerToCallees.get(callerNode);
772
- if (!calleeNames) continue;
773
- for (const cName of calleeNames) {
774
- const targetNode = resolveCalleeNode(callerNode, cName);
775
- if (targetNode && !trueHotNodes.has(targetNode) && !coldForcedNodes.has(targetNode)) {
776
- trueHotNodes.add(targetNode);
777
- hotFunctionNodes.add(targetNode);
778
- hotExemptNodes.add(targetNode);
779
- forwardChanged = true;
780
- }
781
- }
782
- }
783
- }
784
- const calleeToCallers = /* @__PURE__ */ new Map();
785
- for (const [callerNode, calleeNames] of callerToCallees.entries()) {
786
- for (const cName of calleeNames) {
787
- const targetNode = resolveCalleeNode(callerNode, cName);
788
- if (targetNode) {
789
- let set = calleeToCallers.get(targetNode);
790
- if (!set) {
791
- set = /* @__PURE__ */ new Set();
792
- calleeToCallers.set(targetNode, set);
793
- }
794
- set.add(callerNode);
795
- }
796
- }
797
- }
798
- let changed = true;
799
- while (changed) {
800
- changed = false;
801
- for (const [callerNode, calleeNames] of callerToCallees.entries()) {
802
- if (hotFunctionNodes.has(callerNode) || shallowComponentNodes.has(callerNode) || coldForcedNodes.has(callerNode)) {
803
- continue;
804
- }
805
- for (const cName of calleeNames) {
806
- const targetNode = resolveCalleeNode(callerNode, cName);
807
- if (targetNode && trueHotNodes.has(targetNode)) {
808
- const callers = calleeToCallers.get(targetNode);
809
- const isDedicatedPipeline = callers && callers.size <= maxPipelineCallers;
810
- if (isDedicatedPipeline) {
811
- trueHotNodes.add(callerNode);
812
- hotFunctionNodes.add(callerNode);
813
- hotExemptNodes.add(callerNode);
814
- changed = true;
815
- break;
816
- }
817
- }
818
- }
819
- }
820
- }
821
- for (const node of coldForcedNodes) {
822
- hotFunctionNodes.delete(node);
823
- hotExemptNodes.delete(node);
824
- }
825
- const hotFunctionsSkipped = [];
826
- const coldFunctionsProtected = [];
827
- for (const fn of allFunctions) {
828
- if (hotFunctionNodes.has(fn.node)) {
829
- hotFunctionsSkipped.push(fn.name);
830
- } else {
831
- coldFunctionNodes.add(fn.node);
832
- coldFunctionsProtected.push(fn.name);
833
- }
834
- }
835
- return {
836
- report: {
837
- totalFunctions: allFunctions.length,
838
- hotFunctionsSkipped,
839
- coldFunctionsProtected
840
- },
841
- hotFunctionNodes,
842
- coldFunctionNodes,
843
- hotExemptNodes,
844
- serializedFunctionNodes
845
- };
846
- }
847
-
848
- // src/ast/string-vault.ts
849
- import * as acorn4 from "acorn";
850
- import * as walk3 from "acorn-walk";
851
-
852
- // src/ast/codegen.ts
853
- import { generate, baseGenerator } from "astring";
854
- function derivePolymorphicIdent(seed, role) {
855
- let h = (2166136261 ^ seed >>> 0) >>> 0;
856
- for (let i = 0; i < role.length; i++) {
857
- h ^= role.charCodeAt(i);
858
- h = Math.imul(h, 16777619) >>> 0;
859
- }
860
- const rolePrefixes = {
861
- vault: "_a",
862
- shield: "$b",
863
- decoy: "_d",
864
- shader: "_s",
865
- vm: "_m",
866
- wasm: "_w",
867
- salted: "_k",
868
- windowKey: "_z"
869
- };
870
- const prefix = rolePrefixes[role] ?? `_${String.fromCharCode(97 + h % 26)}`;
871
- const suffix = ((h >>> 4) % 1296).toString(36).padStart(2, "0");
872
- return `${prefix}${suffix}`;
873
- }
874
- var OPERATOR_PRECEDENCE = {
875
- "||": 2,
876
- "??": 3,
877
- "&&": 4,
878
- "|": 5,
879
- "^": 6,
880
- "&": 7,
881
- "==": 8,
882
- "!=": 8,
883
- "===": 8,
884
- "!==": 8,
885
- "<": 9,
886
- ">": 9,
887
- "<=": 9,
888
- ">=": 9,
889
- "in": 9,
890
- "instanceof": 9,
891
- "<<": 10,
892
- ">>": 10,
893
- ">>>": 10,
894
- "+": 11,
895
- "-": 11,
896
- "*": 12,
897
- "%": 12,
898
- "/": 12,
899
- "**": 13
900
- };
901
- var NEEDS_PARENTHESES = 17;
902
- function expressionNeedsParenthesis(state, node, parentNode, isRightHand) {
903
- const nodePrecedence = state.expressionsPrecedence[node.type];
904
- if (nodePrecedence === NEEDS_PARENTHESES) {
905
- return true;
906
- }
907
- const parentNodePrecedence = state.expressionsPrecedence[parentNode.type];
908
- if (nodePrecedence !== parentNodePrecedence) {
909
- return !isRightHand && nodePrecedence === 15 && parentNodePrecedence === 14 && parentNode.operator === "**" || nodePrecedence < parentNodePrecedence;
910
- }
911
- if (nodePrecedence !== 13 && nodePrecedence !== 14) {
912
- return false;
913
- }
914
- if (node.operator === "**" && parentNode.operator === "**") {
915
- return !isRightHand;
916
- }
917
- if (nodePrecedence === 13 && parentNodePrecedence === 13 && (node.operator === "??" || parentNode.operator === "??")) {
918
- return true;
919
- }
920
- if (isRightHand) {
921
- return OPERATOR_PRECEDENCE[node.operator] <= OPERATOR_PRECEDENCE[parentNode.operator];
922
- }
923
- return OPERATOR_PRECEDENCE[node.operator] < OPERATOR_PRECEDENCE[parentNode.operator];
924
- }
925
- function formatExpression(state, node, parentNode, isRightHand) {
926
- const generator = state.generator;
927
- if (expressionNeedsParenthesis(state, node, parentNode, isRightHand)) {
928
- state.write("(");
929
- generator[node.type](node, state);
930
- state.write(")");
931
- } else {
932
- generator[node.type](node, state);
933
- }
934
- }
935
- function formatSequence(state, expressions) {
936
- const length = expressions.length;
937
- if (length > 0) {
938
- state.write("(");
939
- state.generator[expressions[0].type](expressions[0], state);
940
- for (let i = 1; i < length; i++) {
941
- state.write(",");
942
- state.generator[expressions[i].type](expressions[i], state);
943
- }
944
- state.write(")");
945
- } else {
946
- state.write("()");
947
- }
948
- }
949
- function expressionStartsWith(node, char) {
950
- if (!node) return false;
951
- if (node.type === "UnaryExpression" && node.prefix) {
952
- return node.operator === char;
953
- }
954
- if (node.type === "UpdateExpression" && node.prefix) {
955
- return node.operator[0] === char;
956
- }
957
- return false;
958
- }
959
- function expressionEndsWith(node, char) {
960
- if (!node) return false;
961
- if (node.type === "UpdateExpression" && !node.prefix) {
962
- return node.operator[0] === char;
963
- }
964
- return false;
965
- }
966
- function isRegExp(node) {
967
- return node && (node.type === "Literal" && !!node.regex || node.type === "RegExpLiteral");
968
- }
969
- var compactGenerator = Object.assign({}, baseGenerator, {
970
- BinaryExpression(node, state) {
971
- const isIn = node.operator === "in";
972
- if (isIn) {
973
- state.write("(");
974
- }
975
- formatExpression(state, node.left, node, false);
976
- const op = node.operator;
977
- let spaceBefore = false;
978
- let spaceAfter = false;
979
- if (op === "in" || op === "instanceof") {
980
- spaceBefore = true;
981
- spaceAfter = true;
982
- } else {
983
- if ((op === "+" || op === "-") && expressionEndsWith(node.left, op) && !expressionNeedsParenthesis(state, node.left, node, false)) {
984
- spaceBefore = true;
985
- }
986
- if ((op === "+" || op === "-") && expressionStartsWith(node.right, op) && !expressionNeedsParenthesis(state, node.right, node, true) || op === "/" && isRegExp(node.right)) {
987
- spaceAfter = true;
988
- }
989
- }
990
- if (spaceBefore) state.write(" ");
991
- state.write(op);
992
- if (spaceAfter) state.write(" ");
993
- formatExpression(state, node.right, node, true);
994
- if (isIn) {
995
- state.write(")");
996
- }
997
- },
998
- LogicalExpression(node, state) {
999
- formatExpression(state, node.left, node, false);
1000
- state.write(node.operator);
1001
- formatExpression(state, node.right, node, true);
1002
- },
1003
- AssignmentExpression(node, state) {
1004
- this[node.left.type](node.left, state);
1005
- const op = node.operator;
1006
- if (op.endsWith("+") && expressionStartsWith(node.right, "+") || op.endsWith("-") && expressionStartsWith(node.right, "-") || op.endsWith("/") && isRegExp(node.right)) {
1007
- state.write(op + " ");
1008
- } else {
1009
- state.write(op);
1010
- }
1011
- this[node.right.type](node.right, state);
1012
- },
1013
- ConditionalExpression(node, state) {
1014
- const test = node.test;
1015
- const precedence = state.expressionsPrecedence[test.type];
1016
- if (precedence === NEEDS_PARENTHESES || precedence <= state.expressionsPrecedence.ConditionalExpression) {
1017
- state.write("(");
1018
- this[test.type](test, state);
1019
- state.write(")");
1020
- } else {
1021
- this[test.type](test, state);
1022
- }
1023
- state.write("?");
1024
- this[node.consequent.type](node.consequent, state);
1025
- state.write(":");
1026
- this[node.alternate.type](node.alternate, state);
1027
- },
1028
- ArrayExpression(node, state) {
1029
- state.write("[");
1030
- const elements = node.elements;
1031
- const length = elements.length;
1032
- for (let i = 0; i < length; i++) {
1033
- const element = elements[i];
1034
- if (element != null) {
1035
- this[element.type](element, state);
1036
- }
1037
- if (i + 1 < length) {
1038
- state.write(",");
1039
- }
1040
- }
1041
- state.write("]");
1042
- },
1043
- ObjectExpression(node, state) {
1044
- state.write("{");
1045
- const properties = node.properties;
1046
- const length = properties.length;
1047
- for (let i = 0; i < length; i++) {
1048
- const property = properties[i];
1049
- this[property.type](property, state);
1050
- if (i + 1 < length) {
1051
- state.write(",");
1052
- }
1053
- }
1054
- state.write("}");
1055
- },
1056
- Property(node, state) {
1057
- if (node.method || node.kind[0] !== "i") {
1058
- this.MethodDefinition(node, state);
1059
- } else {
1060
- if (!node.shorthand) {
1061
- if (node.computed) {
1062
- state.write("[");
1063
- this[node.key.type](node.key, state);
1064
- state.write("]");
1065
- } else {
1066
- this[node.key.type](node.key, state);
1067
- }
1068
- state.write(":");
1069
- }
1070
- this[node.value.type](node.value, state);
1071
- }
1072
- },
1073
- CallExpression(node, state) {
1074
- formatExpression(state, node.callee, node, false);
1075
- if (node.optional) {
1076
- state.write("?.");
1077
- }
1078
- formatSequence(state, node.arguments);
1079
- },
1080
- SequenceExpression(node, state) {
1081
- formatSequence(state, node.expressions);
1082
- },
1083
- FunctionDeclaration(node, state) {
1084
- state.write(
1085
- (node.async ? "async " : "") + (node.generator ? "function* " : "function ") + (node.id ? node.id.name : ""),
1086
- node
1087
- );
1088
- formatSequence(state, node.params);
1089
- this[node.body.type](node.body, state);
1090
- },
1091
- FunctionExpression(node, state) {
1092
- compactGenerator.FunctionDeclaration.call(this, node, state);
1093
- },
1094
- ArrowFunctionExpression(node, state) {
1095
- state.write(node.async ? "async " : "", node);
1096
- const params = node.params;
1097
- if (params != null) {
1098
- if (params.length === 0) {
1099
- state.write("()");
1100
- } else if (params.length === 1 && params[0].type === "Identifier") {
1101
- state.write(params[0].name, params[0]);
1102
- } else {
1103
- formatSequence(state, node.params);
1104
- }
1105
- } else {
1106
- state.write("()");
1107
- }
1108
- state.write("=>");
1109
- if (node.body.type[0] === "O") {
1110
- state.write("(");
1111
- this.ObjectExpression(node.body, state);
1112
- state.write(")");
1113
- } else {
1114
- this[node.body.type](node.body, state);
1115
- }
1116
- },
1117
- ForStatement(node, state) {
1118
- state.write("for(");
1119
- if (node.init != null) {
1120
- const init = node.init;
1121
- if (init.type[0] === "V") {
1122
- this.VariableDeclaration(init, state);
1123
- } else {
1124
- this[init.type](init, state);
1125
- state.write(";");
1126
- }
1127
- } else {
1128
- state.write(";");
1129
- }
1130
- if (node.test) {
1131
- this[node.test.type](node.test, state);
1132
- }
1133
- state.write(";");
1134
- if (node.update) {
1135
- this[node.update.type](node.update, state);
1136
- }
1137
- state.write(")");
1138
- this[node.body.type](node.body, state);
1139
- },
1140
- IfStatement(node, state) {
1141
- state.write("if(");
1142
- this[node.test.type](node.test, state);
1143
- state.write(")");
1144
- this[node.consequent.type](node.consequent, state);
1145
- if (node.alternate != null) {
1146
- if (node.consequent.type === "BlockStatement") {
1147
- state.write("else");
1148
- } else {
1149
- state.write(" else");
1150
- }
1151
- if (node.alternate.type === "BlockStatement") {
1152
- this[node.alternate.type](node.alternate, state);
1153
- } else if (node.alternate.type === "IfStatement") {
1154
- state.write(" ");
1155
- this[node.alternate.type](node.alternate, state);
1156
- } else {
1157
- state.write(" ");
1158
- this[node.alternate.type](node.alternate, state);
1159
- }
1160
- }
1161
- },
1162
- VariableDeclaration(node, state) {
1163
- state.write(node.kind + " ");
1164
- const declarations = node.declarations;
1165
- const length = declarations.length;
1166
- for (let i = 0; i < length; i++) {
1167
- this.VariableDeclarator(declarations[i], state);
1168
- if (i + 1 < length) {
1169
- state.write(",");
1170
- }
1171
- }
1172
- state.write(";");
1173
- },
1174
- VariableDeclarator(node, state) {
1175
- this[node.id.type](node.id, state);
1176
- if (node.init != null) {
1177
- state.write("=");
1178
- this[node.init.type](node.init, state);
1179
- }
1180
- },
1181
- ReturnStatement(node, state) {
1182
- state.write("return");
1183
- if (node.argument) {
1184
- state.write(" ");
1185
- this[node.argument.type](node.argument, state);
1186
- }
1187
- state.write(";");
1188
- }
1189
- });
1190
- function generateCompactJs(ast) {
1191
- return generate(ast, {
1192
- generator: compactGenerator,
1193
- indent: "",
1194
- lineEnd: ""
1195
- });
1196
- }
1197
-
1198
- // src/runtime/integrity-guard.ts
1199
- var FNV_OFFSET_BASIS = 2166136261;
1200
- var FNV_PRIME = 16777619;
1201
- function computeIntegrityHash(source, seed = 0) {
1202
- let hash = (FNV_OFFSET_BASIS ^ seed >>> 0) >>> 0;
1203
- for (let i = 0; i < source.length; i++) {
1204
- hash ^= source.charCodeAt(i);
1205
- hash = Math.imul(hash, FNV_PRIME) >>> 0;
1206
- }
1207
- return hash >>> 0;
1208
- }
1209
-
1210
- // src/runtime/devtools-deterrent.ts
1211
- function deriveIntegrityFnName(seed) {
1212
- return derivePolymorphicIdent(seed, "shield");
1213
- }
1214
- function deriveWindowKeySymbol(seed) {
1215
- return derivePolymorphicIdent(seed, "windowKey");
1216
- }
1217
- function createDeterrentSnippet(config) {
1218
- const seed = config.seed >>> 0;
1219
- const deterrentMode = config.deterrentMode ?? "passive";
1220
- const detectHeadless = config.detectHeadless ?? false;
1221
- const fnName = deriveIntegrityFnName(seed);
1222
- const sym = config.windowKeySymbol ?? deriveWindowKeySymbol(seed);
1223
- const consoleSilence = deterrentMode === "gradual" ? "for(var k in console)console[k]=function(){return 0;};" : "";
1224
- const symLit = JSON.stringify(sym);
1225
- const headlessDecl = detectHeadless ? ",n=w.navigator||0" : "";
1226
- const headlessCond = detectHeadless ? "||n.webdriver||/HeadlessChrome/.test(n.userAgent)" : "";
1227
- return `(function ${fnName}(w){var G=typeof globalThis!=='undefined'?globalThis:w;if(w){var O=Object,P=O.getOwnPropertyDescriptor,GP=O.getPrototypeOf,T=function(o,k){try{while(o){var r=P&&P(o,k);if(r&&(r.set||!r.writable))return 1;o=GP?GP(o):0;}}catch(e){return 1;}},S=function(o,k,v){try{o[k]=v;}catch(e){}},s=Function.prototype.toString${headlessDecl},src='',t=0;try{src=s.call(${fnName});if('prototype' in s||s.name!=='toString'||s.length!==0||s.call(s).indexOf('[native code]')<0||/\\n/.test(src)${headlessCond})t=1;}catch(e){t=1;}try{s.call(0);t=1;}catch(e){}if(T(w,${symLit})||T(G,${symLit})||T(G,'__unpeek_tampered')||T(w,'__unpeek_tampered')||T(String.prototype,'_u'))t=1;for(var h=0x811c9dc5,i=0;i<src.length;i++)h=Math.imul(h^src.charCodeAt(i),0x01000193)>>>0;var d=h&0xffff;if(t){var pd=(d^(((h>>>16)^0x5a5b)||1))&0xffff;if(!T(G,${symLit}))S(G,${symLit},pd);if(!T(w,${symLit}))S(w,${symLit},pd);S(G,'__unpeek_delta',pd);S(w,'__unpeek_delta',pd);try{String.prototype._u=14;}catch(e){}var ns=((w.__unpeek_seed||${seed})^1)>>>0;S(G,'__unpeek_seed',ns);S(w,'__unpeek_seed',ns);S(G,'__unpeek_tampered',!0);S(w,'__unpeek_tampered',!0);try{${consoleSilence}if(w.dispatchEvent)w.dispatchEvent(new CustomEvent('unpeek:tamper'));}catch(e){}}else{S(G,${symLit},d);S(w,${symLit},d);}}})(typeof window!=='undefined'?window:(typeof self!=='undefined'?self:0));`;
1228
- }
1229
-
1230
- // src/runtime/index.ts
1231
- function generateRuntimeShield(config) {
1232
- const seed = config.seed >>> 0;
1233
- const windowKeySymbol = config.windowKeySymbol ?? deriveWindowKeySymbol(seed);
1234
- const integrityCheckFnName = deriveIntegrityFnName(seed);
1235
- const preambleCode = createDeterrentSnippet({
1236
- ...config,
1237
- windowKeySymbol
1238
- });
1239
- const fnStart = preambleCode.indexOf("function");
1240
- const endMarker = preambleCode.lastIndexOf("})(");
1241
- const fnEnd = endMarker !== -1 ? endMarker + 1 : preambleCode.lastIndexOf("(") - 1;
1242
- const fnDecl = preambleCode.slice(fnStart, fnEnd);
1243
- const computedHash = computeIntegrityHash(fnDecl, 0);
1244
- const expectedHash = config.expectedIntegrityHash !== void 0 ? config.expectedIntegrityHash >>> 0 : computedHash;
1245
- const expectedDelta = config.expectedDelta !== void 0 ? config.expectedDelta & 65535 : computedHash >>> 0 & 65535;
1246
- return {
1247
- preambleCode,
1248
- integrityCheckFnName,
1249
- expectedHash,
1250
- windowKeySymbol,
1251
- expectedDelta
1252
- };
1253
- }
1254
-
1255
- // src/ast/salted-vault.ts
1256
- import * as acorn3 from "acorn";
1257
- import * as walk2 from "acorn-walk";
1258
-
1259
- // src/ast/wasm-vault.ts
1260
- import * as acorn2 from "acorn";
1261
- function encodeSignedLeb128(value) {
1262
- const bytes = [];
1263
- let val = value | 0;
1264
- let more = true;
1265
- while (more) {
1266
- let byte = val & 127;
1267
- val >>= 7;
1268
- if (val === 0 && (byte & 64) === 0 || val === -1 && (byte & 64) !== 0) {
1269
- more = false;
1270
- } else {
1271
- byte |= 128;
1272
- }
1273
- bytes.push(byte);
1274
- }
1275
- return bytes;
1276
- }
1277
- function encodeUnsignedLeb128(value) {
1278
- const bytes = [];
1279
- let val = value >>> 0;
1280
- do {
1281
- let byte = val & 127;
1282
- val >>>= 7;
1283
- if (val !== 0) {
1284
- byte |= 128;
1285
- }
1286
- bytes.push(byte);
1287
- } while (val !== 0);
1288
- return bytes;
1289
- }
1290
- function rotl32(value, bits) {
1291
- return value << bits | value >>> 32 - bits | 0;
1292
- }
1293
- function writeI32LE(value) {
1294
- const v = value | 0;
1295
- return [v & 255, v >>> 8 & 255, v >>> 16 & 255, v >>> 24 & 255];
1296
- }
1297
- function deriveKdfParams(seed) {
1298
- const sVal = seed | 0;
1299
- const c1 = computeFnv1aHash("wasm-c1", seed) ^ 2246822507 | 1;
1300
- const c2 = computeFnv1aHash("wasm-c2", seed) ^ 3266489909 | 1;
1301
- const k0 = computeFnv1aHash("wasm-k0", seed) | 0;
1302
- const r1 = (seed >>> 0) % 19 + 7;
1303
- const r2 = (seed >>> 5) % 17 + 5;
1304
- return { sVal, c1, c2, k0, r1, r2 };
1305
- }
1306
- function generateWasmKdfBinary(seed) {
1307
- const { sVal, c1, c2, k0, r1, r2 } = deriveKdfParams(seed);
1308
- const memBase = (seed >>> 0 & 127) * 4;
1309
- const r0 = computeFnv1aHash("wasm-r0", seed) | 0;
1310
- const rotAmt = (seed >>> 0) % 27 + 3;
1311
- const kMul = computeFnv1aHash("wasm-kmul", seed) | 1;
1312
- const kA = kMul >>> 16 & 65535;
1313
- const kB = kMul & 65535;
1314
- const memMask = computeFnv1aHash("wasm-mem", seed) & 1023 | 1;
1315
- const memA = memBase ^ memMask;
1316
- const w0 = r0;
1317
- const w1 = sVal ^ rotl32(r0, rotAmt) ^ Math.imul(r0 | 1, kMul) | 0;
1318
- const w2 = c1 ^ (w0 + w1 | 0) | 0;
1319
- const w3 = c2 - Math.imul(w1 | 1, w2 | 1) | 0;
1320
- const w4 = k0 ^ rotl32(w2, 11) ^ w3 | 0;
1321
- const instructions = [
1322
- 65,
1323
- ...encodeSignedLeb128(memA),
1324
- // i32.const memA
1325
- 65,
1326
- ...encodeSignedLeb128(memMask),
1327
- // i32.const memMask
1328
- 115,
1329
- // i32.xor
1330
- 34,
1331
- 3,
1332
- // local.tee 3 (ptr)
1333
- 40,
1334
- 2,
1335
- 0,
1336
- // i32.load align=2 offset=0
1337
- 33,
1338
- 4,
1339
- // local.set 4 (w0)
1340
- 32,
1341
- 3,
1342
- // local.get 3
1343
- 40,
1344
- 2,
1345
- 4,
1346
- // i32.load align=2 offset=4
1347
- 33,
1348
- 5,
1349
- // local.set 5 (w1)
1350
- 32,
1351
- 3,
1352
- // local.get 3
1353
- 40,
1354
- 2,
1355
- 8,
1356
- // i32.load align=2 offset=8
1357
- 33,
1358
- 6,
1359
- // local.set 6 (w2)
1360
- 32,
1361
- 3,
1362
- // local.get 3
1363
- 40,
1364
- 2,
1365
- 12,
1366
- // i32.load align=2 offset=12
1367
- 33,
1368
- 7,
1369
- // local.set 7 (w3)
1370
- // Reconstruct sVal -> local 8
1371
- 32,
1372
- 5,
1373
- // local.get 5 (w1)
1374
- 32,
1375
- 4,
1376
- // local.get 4 (w0)
1377
- 65,
1378
- ...encodeSignedLeb128(rotAmt),
1379
- // i32.const rotAmt
1380
- 119,
1381
- // i32.rotl
1382
- 115,
1383
- // i32.xor
1384
- 32,
1385
- 4,
1386
- // local.get 4 (w0)
1387
- 65,
1388
- 1,
1389
- // i32.const 1
1390
- 114,
1391
- // i32.or
1392
- 65,
1393
- ...encodeSignedLeb128(kA),
1394
- // i32.const kA
1395
- 65,
1396
- 16,
1397
- // i32.const 16
1398
- 116,
1399
- // i32.shl
1400
- 65,
1401
- ...encodeSignedLeb128(kB),
1402
- // i32.const kB
1403
- 114,
1404
- // i32.or
1405
- 108,
1406
- // i32.mul
1407
- 115,
1408
- // i32.xor
1409
- 33,
1410
- 8,
1411
- // local.set 8 (sVal)
1412
- // Reconstruct c1 -> local 9
1413
- 32,
1414
- 6,
1415
- // local.get 6 (w2)
1416
- 32,
1417
- 4,
1418
- // local.get 4 (w0)
1419
- 32,
1420
- 5,
1421
- // local.get 5 (w1)
1422
- 106,
1423
- // i32.add
1424
- 115,
1425
- // i32.xor
1426
- 33,
1427
- 9,
1428
- // local.set 9 (c1)
1429
- // Reconstruct k0 -> local 10
1430
- 32,
1431
- 3,
1432
- // local.get 3 (ptr)
1433
- 40,
1434
- 2,
1435
- 16,
1436
- // i32.load align=2 offset=16 (w4)
1437
- 32,
1438
- 6,
1439
- // local.get 6 (w2)
1440
- 65,
1441
- 11,
1442
- // i32.const 11
1443
- 119,
1444
- // i32.rotl
1445
- 115,
1446
- // i32.xor
1447
- 32,
1448
- 7,
1449
- // local.get 7 (w3)
1450
- 115,
1451
- // i32.xor
1452
- 33,
1453
- 10,
1454
- // local.set 10 (k0)
1455
- // x = f ^ sVal ^ k0
1456
- 32,
1457
- 0,
1458
- // local.get 0 (fnId)
1459
- 32,
1460
- 8,
1461
- // local.get 8 (sVal)
1462
- 115,
1463
- // i32.xor
1464
- 32,
1465
- 10,
1466
- // local.get 10 (k0)
1467
- 115,
1468
- // i32.xor
1469
- 34,
1470
- 11,
1471
- // local.tee 11 (x)
1472
- // x ^= x >>> 16
1473
- 32,
1474
- 11,
1475
- // local.get 11
1476
- 65,
1477
- 16,
1478
- // i32.const 16
1479
- 118,
1480
- // i32.shr_u
1481
- 115,
1482
- // i32.xor
1483
- // x = imul(x, c1)
1484
- 32,
1485
- 9,
1486
- // local.get 9 (c1)
1487
- 108,
1488
- // i32.mul
1489
- // x = rotl(x ^ s, r1)
1490
- 32,
1491
- 1,
1492
- // local.get 1 (callSiteSalt)
1493
- 115,
1494
- // i32.xor
1495
- 65,
1496
- ...encodeSignedLeb128(r1),
1497
- // i32.const r1
1498
- 119,
1499
- // i32.rotl
1500
- // x = imul(x ^ h ^ sVal, c2)
1501
- 32,
1502
- 2,
1503
- // local.get 2 (shieldHash)
1504
- 115,
1505
- // i32.xor
1506
- 32,
1507
- 8,
1508
- // local.get 8 (sVal)
1509
- 115,
1510
- // i32.xor
1511
- 32,
1512
- 7,
1513
- // local.get 7 (w3)
1514
- 32,
1515
- 5,
1516
- // local.get 5 (w1)
1517
- 65,
1518
- 1,
1519
- // i32.const 1
1520
- 114,
1521
- // i32.or
1522
- 32,
1523
- 6,
1524
- // local.get 6 (w2)
1525
- 65,
1526
- 1,
1527
- // i32.const 1
1528
- 114,
1529
- // i32.or
1530
- 108,
1531
- // i32.mul
1532
- 106,
1533
- // i32.add (c2)
1534
- 108,
1535
- // i32.mul
1536
- 34,
1537
- 11,
1538
- // local.tee 11 (x)
1539
- // x ^= x >>> 15
1540
- 32,
1541
- 11,
1542
- // local.get 11
1543
- 65,
1544
- 15,
1545
- // i32.const 15
1546
- 118,
1547
- // i32.shr_u
1548
- 115,
1549
- // i32.xor
1550
- // x = (x + rotl(s ^ k0, r2))
1551
- 32,
1552
- 1,
1553
- // local.get 1 (callSiteSalt)
1554
- 32,
1555
- 10,
1556
- // local.get 10 (k0)
1557
- 115,
1558
- // i32.xor
1559
- 65,
1560
- ...encodeSignedLeb128(r2),
1561
- // i32.const r2
1562
- 119,
1563
- // i32.rotl
1564
- 106,
1565
- // i32.add
1566
- // x = imul(x, c1)
1567
- 32,
1568
- 9,
1569
- // local.get 9 (c1)
1570
- 108,
1571
- // i32.mul
1572
- 34,
1573
- 11,
1574
- // local.tee 11 (x)
1575
- // x ^= x >>> 16
1576
- 32,
1577
- 11,
1578
- // local.get 11
1579
- 65,
1580
- 16,
1581
- // i32.const 16
1582
- 118,
1583
- // i32.shr_u
1584
- 115,
1585
- // i32.xor
1586
- 11
1587
- // end
1588
- ];
1589
- const funcBody = [1, 9, 127, ...instructions];
1590
- const funcBodyWithLen = [...encodeUnsignedLeb128(funcBody.length), ...funcBody];
1591
- const codeSectionPayload = [1, ...funcBodyWithLen];
1592
- const codeSection = [
1593
- 10,
1594
- ...encodeUnsignedLeb128(codeSectionPayload.length),
1595
- ...codeSectionPayload
1596
- ];
1597
- const typePayload = [
1598
- 1,
1599
- // 1 type
1600
- 96,
1601
- // func
1602
- 3,
1603
- 127,
1604
- 127,
1605
- 127,
1606
- // 3 params of type i32
1607
- 1,
1608
- 127
1609
- // 1 result of type i32
1610
- ];
1611
- const typeSection = [
1612
- 1,
1613
- ...encodeUnsignedLeb128(typePayload.length),
1614
- ...typePayload
1615
- ];
1616
- const funcPayload = [
1617
- 1,
1618
- // 1 function
1619
- 0
1620
- // type index 0
1621
- ];
1622
- const funcSection = [
1623
- 3,
1624
- ...encodeUnsignedLeb128(funcPayload.length),
1625
- ...funcPayload
1626
- ];
1627
- const memSection = [5, 3, 1, 0, 1];
1628
- const exportName = [3, 107, 100, 102];
1629
- const exportPayload = [
1630
- 1,
1631
- // 1 export
1632
- ...exportName,
1633
- 0,
1634
- // function export
1635
- 0
1636
- // function index 0
1637
- ];
1638
- const exportSection = [
1639
- 7,
1640
- ...encodeUnsignedLeb128(exportPayload.length),
1641
- ...exportPayload
1642
- ];
1643
- const dataWords = [
1644
- ...writeI32LE(w0),
1645
- ...writeI32LE(w1),
1646
- ...writeI32LE(w2),
1647
- ...writeI32LE(w3),
1648
- ...writeI32LE(w4)
1649
- ];
1650
- const dataPayload = [
1651
- 1,
1652
- // 1 active segment
1653
- 0,
1654
- // memory index 0
1655
- 65,
1656
- ...encodeSignedLeb128(memBase),
1657
- 11,
1658
- // i32.const memBase; end
1659
- ...encodeUnsignedLeb128(dataWords.length),
1660
- ...dataWords
1661
- ];
1662
- const dataSection = [
1663
- 11,
1664
- ...encodeUnsignedLeb128(dataPayload.length),
1665
- ...dataPayload
1666
- ];
1667
- const header = [0, 97, 115, 109, 1, 0, 0, 0];
1668
- return new Uint8Array([
1669
- ...header,
1670
- ...typeSection,
1671
- ...funcSection,
1672
- ...memSection,
1673
- ...exportSection,
1674
- ...codeSection,
1675
- ...dataSection
1676
- ]);
1677
- }
1678
- function fallbackKdf(fnId, callSiteSalt, shieldHash, seed) {
1679
- const { sVal, c1, c2, k0, r1, r2 } = deriveKdfParams(seed);
1680
- let x = fnId ^ sVal ^ k0 | 0;
1681
- x = x ^ x >>> 16 | 0;
1682
- x = Math.imul(x, c1);
1683
- x = rotl32(x ^ callSiteSalt | 0, r1);
1684
- x = Math.imul(x ^ shieldHash ^ sVal | 0, c2);
1685
- x = x ^ x >>> 15 | 0;
1686
- x = x + rotl32(callSiteSalt ^ k0 | 0, r2) | 0;
1687
- x = Math.imul(x, c1);
1688
- x = x ^ x >>> 16 | 0;
1689
- return x | 0;
1690
- }
1691
- function isWasmVaultAlreadyInjected(ast) {
1692
- if (!ast || !Array.isArray(ast.body)) return false;
1693
- return ast.body.some((stmt) => {
1694
- if (stmt.type === "VariableDeclaration" && stmt.declarations?.some(
1695
- (d) => d.id?.type === "Identifier" && typeof d.id.name === "string" && d.id.name.startsWith("_wKdf")
1696
- )) {
1697
- return true;
1698
- }
1699
- return false;
1700
- });
1701
- }
1702
- function injectWasmVault(ast, seed = 2654435769) {
1703
- const suffix = computeFnv1aHash(`wasm:${seed}`, seed).toString(36);
1704
- const kdfFnName = `_wKdf${suffix}`;
1705
- const wasmVarName = `_wb${suffix}`;
1706
- if (isWasmVaultAlreadyInjected(ast)) {
1707
- const existing = ast.body.find(
1708
- (stmt) => stmt.type === "VariableDeclaration" && stmt.declarations?.some(
1709
- (d) => d.id?.type === "Identifier" && typeof d.id.name === "string" && d.id.name.startsWith("_wKdf")
1710
- )
1711
- );
1712
- const id = existing?.declarations[0]?.id?.name ?? kdfFnName;
1713
- return {
1714
- kdfFnName: id,
1715
- wasmBytes: generateWasmKdfBinary(seed),
1716
- wasmVarName
1717
- };
1718
- }
1719
- const wasmBytes = generateWasmKdfBinary(seed);
1720
- const byteArrayLiteral = Array.from(wasmBytes).join(",");
1721
- const { sVal, c1, c2, k0, r1, r2 } = deriveKdfParams(seed);
1722
- const targets = [c1, c2, sVal, k0, r1, r2];
1723
- const aArr = [];
1724
- const bArr = [];
1725
- const mArr = [];
1726
- for (let i = 0; i < targets.length; i++) {
1727
- const aVal = computeFnv1aHash(`mba-a:${i}`, seed) | 0;
1728
- const mVal = computeFnv1aHash(`mba-m:${i}`, seed) | 0;
1729
- const bVal = (targets[i] ^ mVal) - aVal | 0;
1730
- aArr.push(aVal);
1731
- bArr.push(bVal);
1732
- mArr.push(mVal);
1733
- }
1734
- const strKey = seed & 127 ^ 61 | 0;
1735
- const mChars = [105 ^ strKey, 109 ^ strKey, 117 ^ strKey, 108 ^ strKey].join(",");
1736
- const helperSnippet = `var ${kdfFnName};
1737
- try {
1738
- var ${wasmVarName} = new Uint8Array([${byteArrayLiteral}]);
1739
- var _wm${suffix} = new WebAssembly.Module(${wasmVarName});
1740
- var _wi${suffix} = new WebAssembly.Instance(_wm${suffix});
1741
- ${kdfFnName} = _wi${suffix}.exports.kdf;
1742
- } catch (e) {
1743
- ${kdfFnName} = (function() {
1744
- var _z = +!String;
1745
- var _a = [${aArr.join(",")}];
1746
- var _b = [${bArr.join(",")}];
1747
- var _m0 = [${mArr.join(",")}];
1748
- var _k = [];
1749
- for (var _j = 0; _j < ${targets.length}; _j++) {
1750
- var _u = _a[_j] | _z, _v = _b[_j];
1751
- var _t = ((_u | _v) + (_u & _v)) | 0;
1752
- _k[_j] = ((_t + _m0[_j]) - ((_t & _m0[_j]) << 1)) | 0;
1753
- }
1754
- var _p = '';
1755
- var _c = [${mChars}];
1756
- for (var _i = 0; _i < _c.length; _i++) {
1757
- _p += String.fromCharCode(_c[_i] ^ ${strKey});
1758
- }
1759
- var _m = Math[_p];
1760
- return function(f, s, h) {
1761
- var _x = (f ^ _k[2] ^ _k[3]) | 0;
1762
- _x = (_x ^ (_x >>> 16)) | 0;
1763
- _x = _m(_x, _k[0]);
1764
- var _t0 = _x ^ s, _r1 = _k[4];
1765
- _x = (_t0 << _r1) | (_t0 >>> (32 - _r1));
1766
- _x = _m(_x ^ h ^ _k[2], _k[1]);
1767
- _x = (_x ^ (_x >>> 15)) | 0;
1768
- var _u0 = s ^ _k[3], _r2 = _k[5];
1769
- _x = (_x + ((_u0 << _r2) | (_u0 >>> (32 - _r2)))) | 0;
1770
- _x = _m(_x, _k[0]);
1771
- return (_x ^ (_x >>> 16)) | 0;
1772
- };
1773
- })();
1774
- }`;
1775
- const parsedHelper = acorn2.parse(helperSnippet, {
1776
- ecmaVersion: "latest",
1777
- sourceType: "script"
1778
- });
1779
- let insertIdx = 0;
1780
- while (insertIdx < ast.body.length) {
1781
- const stmt = ast.body[insertIdx];
1782
- const isDirective = stmt.type === "ExpressionStatement" && (Boolean(stmt.directive) || stmt.expression?.type === "Literal" && typeof stmt.expression.value === "string" && /^(?:use\s+[a-zA-Z0-9_-]+)/.test(stmt.expression.value.trim()));
1783
- if (isDirective || stmt.type === "ImportDeclaration") {
1784
- insertIdx++;
1785
- } else {
1786
- break;
1787
- }
1788
- }
1789
- ast.body.splice(insertIdx, 0, ...parsedHelper.body);
1790
- return {
1791
- kdfFnName,
1792
- wasmBytes,
1793
- wasmVarName
1794
- };
1795
- }
1796
-
1797
- // src/ast/salted-vault.ts
1798
- function computeCallSiteSalt(seed, idx) {
1799
- return ((Math.imul((seed ^ idx) >>> 0, 2654435761) ^ Math.imul(idx + 1 >>> 0, 73244475)) & 31) >>> 0;
1800
- }
1801
- function createSaltedDecryptorFnAst(seed, pChars, expectedDelta, windowKeySymbol, safeAlpha = SAFE_ALPHA, shieldCoupled = true, browserOnly = false) {
1802
- const propAccess = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(windowKeySymbol) ? `.${windowKeySymbol}` : `[${JSON.stringify(windowKeySymbol)}]`;
1803
- let fBody;
1804
- if (!shieldCoupled) {
1805
- fBody = `var m=[],c=Function.prototype.toString.call(f);for(var h=0x811c9dc5,j=0;j<c.length;j++)h=Math.imul(h^c.charCodeAt(j),0x01000193)>>>0;var q=(h^(""._u||a._u||0))>>>0,A="${safeAlpha}",P="${pChars}";return function(i,s){if(i in m)return m[i];var p=a[i],o="";if(p)for(var t=q^s^Math.imul(i+1,0x01000193),j=0;j<p.length;j++){t=Math.imul(t^j+1,0x01000193)^0x811c9dc5;var c=p[j],k=A.indexOf(c);o+=k<0?c:A[(A.indexOf(P[(k-(t&65535)%92+92)%92])-(t>>>16)%92+92)%92];}return m[i]=o;};`;
1806
- } else if (browserOnly) {
1807
- fBody = `var m=[],c=Function.prototype.toString.call(f);for(var h=0x811c9dc5,j=0;j<c.length;j++)h=Math.imul(h^c.charCodeAt(j),0x01000193)>>>0;var q,A="${safeAlpha}",P="${pChars}";return function(i,s){if(q===void 0){var w=typeof window<"u"?window:typeof self<"u"?self:0,G=typeof globalThis<"u"?globalThis:w||this,d=G&&G${propAccess}!=null?G${propAccess}:w&&w${propAccess}!=null?w${propAccess}:w?-1:0;q=(h^(""._u||a._u||0)^d)>>>0;}if(i in m)return m[i];var p=a[i],o="";if(p)for(var t=q^s^Math.imul(i+1,0x01000193),j=0;j<p.length;j++){t=Math.imul(t^j+1,0x01000193)^0x811c9dc5;var c=p[j],k=A.indexOf(c);o+=k<0?c:A[(A.indexOf(P[(k-(t&65535)%92+92)%92])-(t>>>16)%92+92)%92];}return m[i]=o;};`;
1808
- } else {
1809
- const maskA = computeFnv1aHash("delta-a", seed) & 65535 | 1;
1810
- const maskB = (expectedDelta & 65535 ^ maskA) & 65535;
1811
- fBody = `var m=[],c=Function.prototype.toString.call(f);for(var h=0x811c9dc5,j=0;j<c.length;j++)h=Math.imul(h^c.charCodeAt(j),0x01000193)>>>0;var q,A="${safeAlpha}",P="${pChars}";return function(i,s){if(q===void 0){var w=typeof window<"u"?window:typeof self<"u"?self:0,G=typeof globalThis<"u"?globalThis:w||this,d=G&&G${propAccess}!=null?G${propAccess}:w&&w${propAccess}!=null?w${propAccess}:w?-1:(${maskA}^${maskB});q=(h^(""._u||a._u||0)^d)>>>0;}if(i in m)return m[i];var p=a[i],o="";if(p)for(var t=q^s^Math.imul(i+1,0x01000193),j=0;j<p.length;j++){t=Math.imul(t^j+1,0x01000193)^0x811c9dc5;var c=p[j],k=A.indexOf(c);o+=k<0?c:A[(A.indexOf(P[(k-(t&65535)%92+92)%92])-(t>>>16)%92+92)%92];}return m[i]=o;};`;
1812
- }
1813
- return acorn3.parse(`(function f(a){${fBody}})`, {
1814
- ecmaVersion: "latest",
1815
- sourceType: "script"
1816
- }).body[0].expression;
1817
- }
1818
- function createSaltedVaultHelperAst(decryptFnName, encryptedPayloads, fnAst) {
1819
- return {
1820
- type: "VariableDeclaration",
1821
- kind: "var",
1822
- declarations: [
1823
- {
1824
- type: "VariableDeclarator",
1825
- id: { type: "Identifier", name: decryptFnName },
1826
- init: {
1827
- type: "CallExpression",
1828
- callee: fnAst,
1829
- arguments: [
1830
- {
1831
- type: "ArrayExpression",
1832
- elements: encryptedPayloads.map((str) => ({
1833
- type: "Literal",
1834
- value: str,
1835
- raw: JSON.stringify(str)
1836
- }))
1837
- }
1838
- ],
1839
- optional: false
1840
- }
1841
- }
1842
- ]
1843
- };
1844
- }
1845
- function encodeSaltedString(str, k) {
1846
- let out = "";
1847
- let rk = k | 0;
1848
- for (let j = 0; j < str.length; j++) {
1849
- rk = Math.imul(rk ^ j + 1, 73244475) + 2654435769 | 0;
1850
- const code = str.charCodeAt(j);
1851
- const mask = rk >>> 16 & 127 | 1;
1852
- out += String.fromCharCode(code ^ mask);
1853
- }
1854
- return out;
1855
- }
1856
- function isAstAlreadySalted(ast) {
1857
- if (!ast || !Array.isArray(ast.body)) return false;
1858
- return ast.body.some((stmt) => {
1859
- if (stmt.type === "VariableDeclaration" && stmt.declarations?.some(
1860
- (d) => d.id?.type === "Identifier" && typeof d.id.name === "string" && d.id.name.startsWith("_uP")
1861
- )) {
1862
- return true;
1863
- }
1864
- return false;
1865
- });
1866
- }
1867
- function replaceNodeInParent(parent, oldNode, newNode) {
1868
- if (!parent) return false;
1869
- for (const key of Object.keys(parent)) {
1870
- const val = parent[key];
1871
- if (val === oldNode) {
1872
- parent[key] = newNode;
1873
- return true;
1874
- }
1875
- if (Array.isArray(val)) {
1876
- const idx = val.indexOf(oldNode);
1877
- if (idx !== -1) {
1878
- val[idx] = newNode;
1879
- return true;
1880
- }
1881
- }
1882
- }
1883
- return false;
1884
- }
1885
- function applySaltedStringVault(ast, seed = 2654435769, minStringLength = 4, hotExemptNodes, config, windowKeySymbol, expectedDelta, deterrentMode, shieldCoupled = true, detectHeadless = false) {
1886
- if (isAstAlreadySalted(ast)) {
1887
- return {
1888
- encryptedStringsCount: 0,
1889
- integrityToken: computeFnv1aHash("already-salted", seed),
1890
- vaultVarName: "",
1891
- decryptFnName: ""
1892
- };
1893
- }
1894
- const minLen = config?.vault?.minStringLength ?? minStringLength;
1895
- const activeDirectives = new Set(DIRECTIVE_STRINGS);
1896
- if (config?.vault?.customDirectives) {
1897
- for (const dir of config.vault.customDirectives) {
1898
- activeDirectives.add(dir);
1899
- }
1900
- }
1901
- const customReserved = config?.vault?.reservedProps ? new Set(config.vault.reservedProps) : void 0;
1902
- const targetsToReplace = [];
1903
- const encryptedPayloads = [];
1904
- walk2.ancestor(ast, {
1905
- Literal(node, ancestors) {
1906
- if (typeof node.value !== "string") return;
1907
- if (node.value.length < minLen) return;
1908
- if (activeDirectives.has(node.value)) return;
1909
- const parent = ancestors[ancestors.length - 2];
1910
- if (!parent) return;
1911
- if (parent.type === "ExpressionStatement" && (Boolean(parent.directive) || activeDirectives.has(node.value))) {
1912
- return;
1913
- }
1914
- for (let i = ancestors.length - 2; i >= 0; i--) {
1915
- if (ancestors[i].type === "ExpressionStatement" && Boolean(ancestors[i].directive)) {
1916
- return;
1917
- }
1918
- }
1919
- if ((parent.type === "ImportDeclaration" || parent.type === "ExportNamedDeclaration" || parent.type === "ExportAllDeclaration" || parent.type === "ImportExpression") && parent.source === node) {
1920
- return;
1921
- }
1922
- if (parent.type === "Property" && parent.key === node && !parent.computed) {
1923
- return;
1924
- }
1925
- if ((parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") && parent.key === node && !parent.computed) {
1926
- return;
1927
- }
1928
- if (hotExemptNodes) {
1929
- for (let i = ancestors.length - 1; i >= 0; i--) {
1930
- if (hotExemptNodes.has(ancestors[i])) {
1931
- return;
1932
- }
1933
- }
1934
- }
1935
- if (isReservedProp(node.value, customReserved)) return;
1936
- if (isTailwindNoise(node.value)) return;
1937
- if (isSvgPathString(node.value, parent)) return;
1938
- const callSiteIdx = targetsToReplace.length;
1939
- const localSalt = computeFnv1aHash(`salt:${seed}:${callSiteIdx}`, seed) & 2147483647 | 1;
1940
- targetsToReplace.push({
1941
- node,
1942
- parent,
1943
- callSiteIdx,
1944
- localSalt,
1945
- rawString: node.value
1946
- });
1947
- }
1948
- });
1949
- if (targetsToReplace.length === 0) {
1950
- return {
1951
- encryptedStringsCount: 0,
1952
- integrityToken: computeFnv1aHash("empty-salted", seed),
1953
- vaultVarName: "",
1954
- decryptFnName: ""
1955
- };
1956
- }
1957
- const wasmResult = injectWasmVault(ast, seed);
1958
- const kdfFnName = wasmResult.kdfFnName;
1959
- const suffix = computeFnv1aHash(`salted:${seed}`, seed).toString(36);
1960
- const vaultVarName = `_uP${suffix}`;
1961
- const cacheVarName = `_uCache${suffix}`;
1962
- const dCacheVarName = `_uDc${suffix}`;
1963
- const decryptFnName = `_uD${suffix}`;
1964
- const sym = windowKeySymbol ?? deriveWindowKeySymbol(seed);
1965
- const browserOnly = config?.target === "browser";
1966
- let expDelta = expectedDelta;
1967
- if (shieldCoupled && expDelta === void 0) {
1968
- const shield = generateRuntimeShield({
1969
- seed,
1970
- windowKeySymbol: sym,
1971
- deterrentMode: deterrentMode ?? "passive",
1972
- detectHeadless
1973
- });
1974
- expDelta = shield.expectedDelta ?? 0;
1975
- }
1976
- const propAccess = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(sym) ? `.${sym}` : `[${JSON.stringify(sym)}]`;
1977
- let shieldDeltaExpr;
1978
- if (!shieldCoupled) {
1979
- shieldDeltaExpr = `var dv=(G&&G.__unpeek_delta!=null?G.__unpeek_delta:0)|0;${dCacheVarName}=((h|0)^dv)|0;`;
1980
- } else {
1981
- const fallbackExpr = browserOnly ? "0" : `(${computeFnv1aHash("salted-a", seed) & 65535 | 1}^${((expDelta ?? 0) & 65535 ^ (computeFnv1aHash("salted-a", seed) & 65535 | 1)) & 65535})`;
1982
- shieldDeltaExpr = `var w=typeof window<"u"?window:typeof self<"u"?self:0;var sv=G&&G${propAccess}!=null?G${propAccess}:w&&w${propAccess}!=null?w${propAccess}:w?-1:${fallbackExpr};var dv=(G&&G.__unpeek_delta!=null?G.__unpeek_delta:w&&w.__unpeek_delta!=null?w.__unpeek_delta:0)|0;${dCacheVarName}=((h|0)^(sv|0)^dv)|0;`;
1983
- }
1984
- const helperFnSnippet = `function ${decryptFnName}(i,s){if(${cacheVarName}[i]!==void 0)return ${cacheVarName}[i];if(${dCacheVarName}===void 0){var G=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof self<"u"?self:this;var c=Function.prototype.toString.call(${decryptFnName}),h=0x811c9dc5;for(var l=0;l<c.length;l++)h=Math.imul(h^c.charCodeAt(l),0x01000193)>>>0;${shieldDeltaExpr}}var k=${kdfFnName}(i,s,${dCacheVarName});var p=${vaultVarName}[i],o="",rk=k|0;for(var j=0;j<p.length;j++){rk=(Math.imul(rk^(j+1),0x45d9f3b)+0x9e3779b9)|0;o+=String.fromCharCode(p.charCodeAt(j)^(((rk>>>16)&127)|1));}return (${cacheVarName}[i]=o);}`;
1985
- const parsedFn = acorn3.parse(helperFnSnippet, {
1986
- ecmaVersion: "latest",
1987
- sourceType: "script"
1988
- });
1989
- const fnDeclAst = parsedFn.body[0];
1990
- const selfHash = computeFnv1aHash(generateCompactJs(fnDeclAst)) | 0;
1991
- const buildD = shieldCoupled ? selfHash ^ (expDelta ?? 0) & 65535 | 0 : selfHash | 0;
1992
- for (const target of targetsToReplace) {
1993
- const k = fallbackKdf(target.callSiteIdx, target.localSalt, buildD, seed);
1994
- encryptedPayloads.push(encodeSaltedString(target.rawString, k));
1995
- const callExpr = {
1996
- type: "CallExpression",
1997
- callee: {
1998
- type: "Identifier",
1999
- name: decryptFnName
2000
- },
2001
- arguments: [
2002
- {
2003
- type: "Literal",
2004
- value: target.callSiteIdx,
2005
- raw: String(target.callSiteIdx)
2006
- },
2007
- {
2008
- type: "Literal",
2009
- value: target.localSalt,
2010
- raw: String(target.localSalt)
2011
- }
2012
- ],
2013
- optional: false
2014
- };
2015
- replaceNodeInParent(target.parent, target.node, callExpr);
2016
- }
2017
- const serializedTable = JSON.stringify(encryptedPayloads);
2018
- const integrityToken = computeFnv1aHash(serializedTable, seed);
2019
- const varsSnippet = `var ${vaultVarName}=${serializedTable};var ${cacheVarName}=[];var ${dCacheVarName};`;
2020
- const parsedVars = acorn3.parse(varsSnippet, {
2021
- ecmaVersion: "latest",
2022
- sourceType: "script"
2023
- });
2024
- let insertIdx = 0;
2025
- while (insertIdx < ast.body.length) {
2026
- const stmt = ast.body[insertIdx];
2027
- const isDirective = stmt.type === "ExpressionStatement" && (Boolean(stmt.directive) || stmt.expression?.type === "Literal" && typeof stmt.expression.value === "string" && (activeDirectives.has(stmt.expression.value) || /^(?:use\s+[a-zA-Z0-9_-]+)/.test(stmt.expression.value.trim())));
2028
- if (isDirective || stmt.type === "ImportDeclaration") {
2029
- insertIdx++;
2030
- } else {
2031
- break;
2032
- }
2033
- }
2034
- ast.body.splice(insertIdx, 0, ...parsedVars.body, fnDeclAst);
2035
- return {
2036
- encryptedStringsCount: targetsToReplace.length,
2037
- integrityToken,
2038
- vaultVarName,
2039
- decryptFnName
2040
- };
2041
- }
2042
-
2043
- // src/ast/string-vault.ts
2044
- var SAFE_ALPHA = " !#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_abcdefghijklmnopqrstuvwxyz{|}~";
2045
- var DIRECTIVE_STRINGS = /* @__PURE__ */ new Set([
2046
- "use strict",
2047
- "use client",
2048
- "use server",
2049
- "use asm",
2050
- "use cache",
2051
- "use worklet",
2052
- "use worker",
2053
- "use memo"
2054
- ]);
2055
- var STANDARD_PROP_KEYS = /* @__PURE__ */ new Set([
2056
- "id",
2057
- "type",
2058
- "key",
2059
- "ref",
2060
- "className",
2061
- "style",
2062
- "name",
2063
- "value",
2064
- "children",
2065
- "src",
2066
- "href",
2067
- "alt",
2068
- "role",
2069
- "tabIndex",
2070
- "class",
2071
- "part",
2072
- "slot",
2073
- "is",
2074
- "innerHTML",
2075
- "disabled",
2076
- "title"
2077
- ]);
2078
- var STANDARD_PROP_PREFIX_RE = /^(?:data-|aria-|on[A-Z]|v-|bind:)/;
2079
- function isReservedProp(propName, customReserved) {
2080
- if (STANDARD_PROP_KEYS.has(propName)) return true;
2081
- if (customReserved && customReserved.has(propName)) return true;
2082
- if (STANDARD_PROP_PREFIX_RE.test(propName)) return true;
2083
- return false;
2084
- }
2085
- var LOOP_NODE_TYPES = /* @__PURE__ */ new Set([
2086
- "ForStatement",
2087
- "ForInStatement",
2088
- "ForOfStatement",
2089
- "WhileStatement",
2090
- "DoWhileStatement"
2091
- ]);
2092
- function isReactDomSpecialProp(val, node, parent, customReserved) {
2093
- if (isReservedProp(val, customReserved)) return true;
2094
- if (!parent) return false;
2095
- if (parent.type === "Property") {
2096
- if (parent.key === node && !parent.computed) {
2097
- return true;
2098
- }
2099
- const keyName = parent.key?.type === "Identifier" ? parent.key.name : parent.key?.type === "Literal" ? String(parent.key.value) : "";
2100
- if (keyName && isReservedProp(keyName, customReserved)) {
2101
- return true;
2102
- }
2103
- }
2104
- return false;
2105
- }
2106
- 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-|\[&_)/;
2107
- var TAILWIND_VARIANT_PREFIX_RE = /^(?:[a-zA-Z0-9_@-]+:)+/;
2108
- function stripTailwindVariants(token) {
2109
- return token.replace(TAILWIND_VARIANT_PREFIX_RE, "");
2110
- }
2111
- function isTailwindNoise(val) {
2112
- const trimmed = val.trim();
2113
- if (!trimmed) return false;
2114
- const isMatch = (t) => {
2115
- const stripped = stripTailwindVariants(t);
2116
- return TAILWIND_TOKEN_RE.test(stripped) || stripped.startsWith("btn") || stripped.startsWith("p-") || stripped.startsWith("m-");
2117
- };
2118
- if (trimmed.includes(" ")) {
2119
- const tokens = trimmed.split(/\s+/);
2120
- let twHits = 0;
2121
- for (const t of tokens) {
2122
- if (isMatch(t)) {
2123
- twHits++;
2124
- }
2125
- }
2126
- if (twHits / tokens.length >= 0.5) return true;
2127
- } else {
2128
- if (isMatch(trimmed)) return true;
2129
- }
2130
- return false;
2131
- }
2132
- function isParentSvgPathProperty(parent) {
2133
- if (!parent) return false;
2134
- if (parent.type === "Property") {
2135
- const keyName = parent.key?.type === "Identifier" ? parent.key.name : parent.key?.type === "Literal" ? String(parent.key.value) : "";
2136
- if (keyName === "d" || keyName === "path") return true;
2137
- }
2138
- if (parent.type === "JSXAttribute") {
2139
- const attrName = parent.name?.name;
2140
- if (attrName === "d" || attrName === "path") return true;
2141
- }
2142
- return false;
2143
- }
2144
- function isSvgPathString(val, parent) {
2145
- if (typeof val !== "string" || val.length < 4) return false;
2146
- const trimmed = val.trim();
2147
- if (!/^[Mm]\s*[-+]?(?:\d*\.\d+|\d+)/.test(trimmed)) {
2148
- return false;
2149
- }
2150
- if (parent && isParentSvgPathProperty(parent)) {
2151
- return true;
2152
- }
2153
- return /[zZ]$/.test(trimmed) || /[Mm]\s*[-+]?\d.*[a-df-zA-DF-Z]\s*[-+]?\d/.test(trimmed) || /^[Mm]\s*[-+]?\d+(?:\.\d+)?[\s,]+-?\d+(?:\.\d+)?(?:\s+[a-zA-Z][-+]?\d+.*)?$/.test(
2154
- trimmed
2155
- );
2156
- }
2157
- var DEFAULT_SEMANTIC_ANCHOR_RE = /(?:\bapi\/|\bcheckout\b|\badmin\b|\bauth\b|\btoken\b|\bcredential\b|\bsecret\b|\bpassword\b|\bbearer\b)/i;
2158
- function isUiClassName(val, parent) {
2159
- if (parent) {
2160
- if (parent.type === "Property") {
2161
- const k = parent.key?.type === "Identifier" ? parent.key.name : parent.key?.type === "Literal" ? String(parent.key.value) : "";
2162
- if (k === "className" || k === "class" || k === "classList") return true;
2163
- }
2164
- if (parent.type === "JSXAttribute") {
2165
- const name = parent.name?.name;
2166
- if (name === "className" || name === "class") return true;
2167
- }
2168
- }
2169
- if (isTailwindNoise(val)) return true;
2170
- if (/^[a-z0-9_-]+(?:\s+[a-z0-9_-]+)+$/i.test(val.trim())) {
2171
- return true;
2172
- }
2173
- return false;
2174
- }
2175
- function isAdversaryDecoy(val, seed) {
2176
- if (val.startsWith("/api/v2/auth/") || val === "superadmin_token" || val === "elevate" || val === "_verifyMasterToken" || val === "mock_jwt_bypass_signature" || val === "debug_supervisor_override" || val.startsWith("_decoy_") || val.startsWith("_auth_bypass_")) {
2177
- return true;
2178
- }
2179
- const s = (seed >>> 0 & 65535).toString(36);
2180
- if (val.includes(s) && (val.includes("auth") || val.includes("token") || val.includes("decoy") || val.includes("elevate"))) {
2181
- return true;
2182
- }
2183
- return false;
2184
- }
2185
- function isEligibleHotLiteral(val, node, parent, ancestors, minLen, seed = 2654435769, customReserved, activeDirectives = DIRECTIVE_STRINGS, semanticAnchorPatterns, excludeUiClasses = true) {
2186
- if (val.length < minLen || activeDirectives.has(val)) return false;
2187
- if (isReactDomSpecialProp(val, node, parent, customReserved)) return false;
2188
- if (isTailwindNoise(val)) return false;
2189
- if (isSvgPathString(val, parent)) return false;
2190
- for (let i = ancestors.length - 2; i >= 0; i--) {
2191
- if (LOOP_NODE_TYPES.has(ancestors[i].type)) {
2192
- return false;
2193
- }
2194
- }
2195
- for (let i = ancestors.length - 2; i >= 0; i--) {
2196
- if (ancestors[i]._unpeekSerialized) {
2197
- return false;
2198
- }
2199
- }
2200
- if (val.startsWith("HOT_")) return false;
2201
- let isSemanticAnchor = false;
2202
- if (semanticAnchorPatterns && semanticAnchorPatterns.length > 0) {
2203
- isSemanticAnchor = semanticAnchorPatterns.some((re) => re.test(val));
2204
- } else {
2205
- isSemanticAnchor = DEFAULT_SEMANTIC_ANCHOR_RE.test(val);
2206
- }
2207
- if (isSemanticAnchor && excludeUiClasses && isUiClassName(val, parent)) {
2208
- isSemanticAnchor = false;
2209
- }
2210
- let isInsideRender = false;
2211
- for (let i = ancestors.length - 2; i >= 0; i--) {
2212
- const a = ancestors[i];
2213
- if (a.type === "FunctionDeclaration" || a.type === "FunctionExpression" || a.type === "ArrowFunctionExpression") {
2214
- if (a.id?.name && /^[A-Z]/.test(a.id.name)) {
2215
- isInsideRender = true;
2216
- break;
2217
- }
2218
- if (a._unpeekIsComponent) {
2219
- isInsideRender = true;
2220
- break;
2221
- }
2222
- }
2223
- }
2224
- if (!isSemanticAnchor && !isInsideRender) return false;
2225
- if (isAdversaryDecoy(val, seed)) {
2226
- return false;
2227
- }
2228
- if (parent) {
2229
- if (parent.type === "ImportDeclaration" || parent.type === "ExportNamedDeclaration" || parent.type === "ExportAllDeclaration" || parent.type === "ImportExpression") {
2230
- if (parent.source === node) return false;
2231
- }
2232
- if ((parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") && parent.key === node && !parent.computed) {
2233
- return false;
2234
- }
2235
- if (parent.type === "ImportAttribute" || parent.type === "ImportSpecifier" || parent.type === "ExportSpecifier") {
2236
- return false;
2237
- }
2238
- }
2239
- return true;
2240
- }
2241
- var SHADER_SIG_RE = /@group|@binding|@vertex|@fragment|@compute|vec4f|gl_Position|uniform/;
2242
- function shouldEncryptString(val, minLen, parent, activeDirectives = DIRECTIVE_STRINGS, customReserved) {
2243
- if (val.length < minLen || activeDirectives.has(val)) return false;
2244
- if (isReservedProp(val, customReserved)) return false;
2245
- if (isSvgPathString(val, parent)) return false;
2246
- if (isTailwindNoise(val)) return false;
2247
- return true;
2248
- }
2249
- function computeFnv1aHash(input, seed = 2166136261) {
2250
- let hash = seed >>> 0;
2251
- for (let i = 0; i < input.length; i++) {
2252
- hash ^= input.charCodeAt(i);
2253
- hash = Math.imul(hash, 16777619) >>> 0;
2254
- }
2255
- return hash >>> 0;
2256
- }
2257
- function createPermutationTable(seed) {
2258
- let s = (seed || 305419896) >>> 0;
2259
- function xorshift() {
2260
- s ^= s << 13;
2261
- s ^= s >>> 17;
2262
- s ^= s << 5;
2263
- return s >>> 0;
2264
- }
2265
- const indices = [];
2266
- for (let i = 0; i < 92; i++) indices.push(i);
2267
- for (let i = 91; i > 0; i--) {
2268
- const j = xorshift() % (i + 1);
2269
- const tmp = indices[i];
2270
- indices[i] = indices[j];
2271
- indices[j] = tmp;
2272
- }
2273
- const B = new Array(92);
2274
- for (let i = 0; i < 46; i++) {
2275
- const a = indices[2 * i];
2276
- const b = indices[2 * i + 1];
2277
- B[a] = b;
2278
- B[b] = a;
2279
- }
2280
- let P_CHARS = "";
2281
- for (let i = 0; i < 92; i++) {
2282
- P_CHARS += SAFE_ALPHA[B[i]];
2283
- }
2284
- return P_CHARS;
2285
- }
2286
- function encodeStringWithSeed(str, P_CHARS, expectedKey, salt = 0, idx = 0) {
2287
- let out = "";
2288
- let st = (expectedKey >>> 0 ^ salt >>> 0 ^ Math.imul(idx + 1, 16777619)) >>> 0;
2289
- for (let j = 0; j < str.length; j++) {
2290
- st = Math.imul(st ^ j + 1, 16777619) ^ 2166136261 | 0;
2291
- const r1 = (st >>> 16) % 92;
2292
- const r2 = (st & 65535) % 92;
2293
- const c = str.charAt(j);
2294
- const k = SAFE_ALPHA.indexOf(c);
2295
- if (k < 0) {
2296
- out += c;
2297
- } else {
2298
- const y = (k + r1) % 92;
2299
- const z = SAFE_ALPHA.indexOf(P_CHARS.charAt(y));
2300
- out += SAFE_ALPHA.charAt((z + r2) % 92);
2301
- }
2302
- }
2303
- return out;
2304
- }
2305
- function createShaderVaultAst(shaderVarName, shaderPayloads, seed) {
2306
- const sSeed = seed >>> 0;
2307
- const fnCode = `(function f(B){var c=Function.prototype.toString.call(f),h=0x811c9dc5;for(var i=0;i<c.length;i++)h=Math.imul(h^c.charCodeAt(i),0x01000193)>>>0;var S=h^${sSeed},b=B.map(function(s){var n=typeof atob=="function"?atob(s):typeof Buffer<"u"?Buffer.from(s,"base64").toString("binary"):"",u=new Uint8Array(n.length);for(var i=0;i<n.length;i++)u[i]=n.charCodeAt(i);return u;}),d=typeof TextDecoder<"u"?new TextDecoder():null;function x(u,i){for(var r=(S^Math.imul(i+1,0x9e3779b1))|0,j=0;j<u.length;j++){r=(Math.imul(r^(j+1),0x45d9f3b)+0x85ebca6b)|0;u[j]^=(r>>>16)&255;}}return function(i){var u=b[i];x(u,i);try{return d?d.decode(u):String.fromCharCode.apply(null,u);}finally{x(u,i);}};})`;
2308
- const fnAst = acorn4.parse(fnCode, { ecmaVersion: "latest", sourceType: "script" }).body[0].expression;
2309
- const buildH = computeIntegrityHash(generateCompactJs(fnAst), 0);
2310
- const S = (buildH ^ sSeed) >>> 0;
2311
- const b64List = [];
2312
- for (let idx = 0; idx < shaderPayloads.length; idx++) {
2313
- const str = shaderPayloads[idx];
2314
- const buf = Buffer.from(str, "utf8");
2315
- let r = S ^ Math.imul(idx + 1, 2654435761) | 0;
2316
- for (let j = 0; j < buf.length; j++) {
2317
- r = Math.imul(r ^ j + 1, 73244475) + 2246822507 | 0;
2318
- buf[j] ^= r >>> 16 & 255;
2319
- }
2320
- b64List.push(buf.toString("base64"));
2321
- }
2322
- return createSaltedVaultHelperAst(shaderVarName, b64List, fnAst);
2323
- }
2324
- function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExemptNodes, windowKeySymbol, expectedDelta, deterrentMode, config, shieldCoupled = true, detectHeadless = false) {
2325
- const minLen = config?.vault?.minStringLength ?? minStringLength;
2326
- const activeDirectives = new Set(DIRECTIVE_STRINGS);
2327
- if (config?.vault?.customDirectives) {
2328
- for (const dir of config.vault.customDirectives) {
2329
- activeDirectives.add(dir);
2330
- }
2331
- }
2332
- const customReserved = config?.vault?.reservedProps ? new Set(config.vault.reservedProps) : void 0;
2333
- const semanticPatterns = config?.vault?.semanticAnchors?.patterns;
2334
- const excludeUi = config?.vault?.semanticAnchors?.excludeUiClasses !== false;
2335
- const suffix = (seed >>> 0 & 65535).toString(36);
2336
- const decryptFnName = `_uD${suffix}`;
2337
- const cacheVarName = derivePolymorphicIdent(seed, "vault");
2338
- const shaderVarName = derivePolymorphicIdent(seed, "shader");
2339
- const sym = windowKeySymbol ?? deriveWindowKeySymbol(seed);
2340
- const browserOnly = config?.target === "browser";
2341
- let expDelta = shieldCoupled ? expectedDelta : 0;
2342
- if (shieldCoupled && expDelta === void 0) {
2343
- const shield = generateRuntimeShield({
2344
- seed,
2345
- windowKeySymbol: sym,
2346
- deterrentMode: deterrentMode ?? "passive",
2347
- detectHeadless
2348
- });
2349
- expDelta = shield.expectedDelta ?? 0;
2350
- }
2351
- const alreadyVaulted = ast.body.some(
2352
- (stmt) => stmt.type === "VariableDeclaration" && stmt.declarations?.some(
2353
- (d) => d.id?.type === "Identifier" && typeof d.id.name === "string" && (d.id.name.startsWith("_uC") || d.id.name.startsWith("_uD") || d.id.name === decryptFnName || d.id.name === cacheVarName || d.init?.type === "CallExpression" && d.init.callee?.type === "FunctionExpression" && d.init.callee?.id?.name === "f" && d.init.arguments?.[0]?.type === "ArrayExpression")
2354
- )
2355
- );
2356
- if (alreadyVaulted) {
2357
- return {
2358
- encryptedStringsCount: 0,
2359
- integrityToken: computeFnv1aHash("already-vaulted", seed),
2360
- shaderBuffersCount: 0
2361
- };
2362
- }
2363
- const P_CHARS = createPermutationTable(seed);
2364
- const fnAst = createSaltedDecryptorFnAst(
2365
- seed,
2366
- P_CHARS,
2367
- expDelta ?? 0,
2368
- sym,
2369
- SAFE_ALPHA,
2370
- shieldCoupled,
2371
- browserOnly
2372
- );
2373
- const compactFnStr = generateCompactJs(fnAst);
2374
- const buildH = computeIntegrityHash(compactFnStr, 0);
2375
- const expectedKey = (buildH ^ 0 ^ (shieldCoupled ? (expDelta ?? 0) & 65535 : 0)) >>> 0;
2376
- const stringToIndex = /* @__PURE__ */ new Map();
2377
- const encryptedPayloads = [];
2378
- const shaderToIndex = /* @__PURE__ */ new Map();
2379
- const shaderPayloads = [];
2380
- const targetsToReplace = [];
2381
- const hotTargetsToReplace = [];
2382
- const customWalkBase = {
2383
- ...walk3.base,
2384
- Property(node, st, c) {
2385
- c(node.key, st);
2386
- if (node.value) c(node.value, st);
2387
- }
2388
- };
2389
- walk3.ancestor(
2390
- ast,
2391
- {
2392
- Literal(node, _state, ancestors) {
2393
- if (typeof node.value !== "string") return;
2394
- const val = node.value;
2395
- if (activeDirectives.has(val)) return;
2396
- let isHotExempt = false;
2397
- if (hotExemptNodes) {
2398
- for (let i = ancestors.length - 2; i >= 0; i--) {
2399
- if (hotExemptNodes.has(ancestors[i])) {
2400
- isHotExempt = true;
2401
- break;
2402
- }
2403
- }
2404
- }
2405
- const parent = ancestors[ancestors.length - 2];
2406
- if (!parent) return;
2407
- if (parent.type === "ExpressionStatement" && (Boolean(parent.directive) || activeDirectives.has(val))) {
2408
- return;
2409
- }
2410
- for (let i = ancestors.length - 2; i >= 0; i--) {
2411
- if (ancestors[i].type === "ExpressionStatement" && Boolean(ancestors[i].directive)) {
2412
- return;
2413
- }
2414
- }
2415
- if (parent.type === "ImportDeclaration" || parent.type === "ExportNamedDeclaration" || parent.type === "ExportAllDeclaration" || parent.type === "ImportExpression") {
2416
- if (parent.source === node) return;
2417
- }
2418
- if ((parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") && parent.key === node && !parent.computed) {
2419
- return;
2420
- }
2421
- if (parent.type === "ImportAttribute" || parent.type === "ImportSpecifier" || parent.type === "ExportSpecifier") {
2422
- return;
2423
- }
2424
- if (isHotExempt) {
2425
- if (isEligibleHotLiteral(
2426
- val,
2427
- node,
2428
- parent,
2429
- ancestors,
2430
- minLen,
2431
- seed,
2432
- customReserved,
2433
- activeDirectives,
2434
- semanticPatterns,
2435
- excludeUi
2436
- )) {
2437
- hotTargetsToReplace.push({
2438
- node,
2439
- parent,
2440
- val,
2441
- idx: hotTargetsToReplace.length
2442
- });
2443
- }
2444
- return;
2445
- }
2446
- if (parent.type === "Property" && parent.key === node && !parent.computed) {
2447
- if (isReservedProp(val, customReserved)) {
2448
- return;
2449
- }
2450
- }
2451
- if (isReservedProp(val, customReserved)) return;
2452
- if (isTailwindNoise(val)) return;
2453
- if (isSvgPathString(val, parent)) return;
2454
- const isShader = val.length >= 256 || SHADER_SIG_RE.test(val);
2455
- if (isShader) {
2456
- let idx = shaderToIndex.get(val);
2457
- if (idx === void 0) {
2458
- idx = shaderPayloads.length;
2459
- shaderToIndex.set(val, idx);
2460
- shaderPayloads.push(val);
2461
- }
2462
- targetsToReplace.push({ type: "shader", node, parent, idx });
2463
- } else {
2464
- if (!shouldEncryptString(val, minLen, parent, activeDirectives, customReserved)) return;
2465
- let idx = stringToIndex.get(val);
2466
- if (idx === void 0) {
2467
- idx = encryptedPayloads.length;
2468
- stringToIndex.set(val, idx);
2469
- const salt = computeCallSiteSalt(seed, idx);
2470
- encryptedPayloads.push(
2471
- encodeStringWithSeed(val, P_CHARS, expectedKey, salt, idx)
2472
- );
2473
- }
2474
- targetsToReplace.push({ type: "string", node, parent, idx });
2475
- }
2476
- },
2477
- TemplateLiteral(node, _state, ancestors) {
2478
- if (!node.quasis || node.quasis.length !== 1) return;
2479
- if (node.expressions && node.expressions.length !== 0) return;
2480
- const val = node.quasis[0].value.cooked ?? node.quasis[0].value.raw;
2481
- if (typeof val !== "string" || activeDirectives.has(val)) return;
2482
- let isHotExempt = false;
2483
- if (hotExemptNodes) {
2484
- for (let i = ancestors.length - 2; i >= 0; i--) {
2485
- if (hotExemptNodes.has(ancestors[i])) {
2486
- isHotExempt = true;
2487
- break;
2488
- }
2489
- }
2490
- }
2491
- const parent = ancestors[ancestors.length - 2];
2492
- if (!parent) return;
2493
- if (parent.type === "ExpressionStatement" && (Boolean(parent.directive) || activeDirectives.has(val))) {
2494
- return;
2495
- }
2496
- for (let i = ancestors.length - 2; i >= 0; i--) {
2497
- if (ancestors[i].type === "ExpressionStatement" && Boolean(ancestors[i].directive)) {
2498
- return;
2499
- }
2500
- }
2501
- if (isHotExempt) {
2502
- if (isEligibleHotLiteral(
2503
- val,
2504
- node,
2505
- parent,
2506
- ancestors,
2507
- minLen,
2508
- seed,
2509
- customReserved,
2510
- activeDirectives,
2511
- semanticPatterns,
2512
- excludeUi
2513
- )) {
2514
- hotTargetsToReplace.push({
2515
- node,
2516
- parent,
2517
- val,
2518
- idx: hotTargetsToReplace.length
2519
- });
2520
- }
2521
- return;
2522
- }
2523
- if (isReservedProp(val, customReserved)) return;
2524
- if (isTailwindNoise(val)) return;
2525
- if (isSvgPathString(val, parent)) return;
2526
- const isShader = val.length >= 256 || SHADER_SIG_RE.test(val);
2527
- if (isShader) {
2528
- let idx = shaderToIndex.get(val);
2529
- if (idx === void 0) {
2530
- idx = shaderPayloads.length;
2531
- shaderToIndex.set(val, idx);
2532
- shaderPayloads.push(val);
2533
- }
2534
- targetsToReplace.push({ type: "shader", node, parent, idx });
2535
- } else {
2536
- if (!shouldEncryptString(val, minLen, parent, activeDirectives, customReserved)) return;
2537
- let idx = stringToIndex.get(val);
2538
- if (idx === void 0) {
2539
- idx = encryptedPayloads.length;
2540
- stringToIndex.set(val, idx);
2541
- const salt = computeCallSiteSalt(seed, idx);
2542
- encryptedPayloads.push(
2543
- encodeStringWithSeed(val, P_CHARS, expectedKey, salt, idx)
2544
- );
2545
- }
2546
- targetsToReplace.push({ type: "string", node, parent, idx });
2547
- }
2548
- }
2549
- },
2550
- customWalkBase
2551
- );
2552
- if (targetsToReplace.length === 0 && hotTargetsToReplace.length === 0) {
2553
- return {
2554
- encryptedStringsCount: 0,
2555
- integrityToken: computeFnv1aHash("empty", seed),
2556
- shaderBuffersCount: 0
2557
- };
2558
- }
2559
- for (const { node, parent, val, idx } of hotTargetsToReplace) {
2560
- const key = idx % 3 + 1;
2561
- let encodedStr = "";
2562
- for (let i = 0; i < val.length; i++) {
2563
- encodedStr += String.fromCharCode(val.charCodeAt(i) ^ key);
2564
- }
2565
- if (parent?.type === "Property" && parent.key === node) {
2566
- parent.computed = true;
2567
- }
2568
- node.type = "CallExpression";
2569
- node.callee = {
2570
- type: "Identifier",
2571
- name: "_hX"
2572
- };
2573
- node.arguments = [
2574
- {
2575
- type: "Literal",
2576
- value: encodedStr,
2577
- raw: JSON.stringify(encodedStr)
2578
- },
2579
- {
2580
- type: "Literal",
2581
- value: key,
2582
- raw: String(key)
2583
- }
2584
- ];
2585
- node.optional = false;
2586
- delete node.value;
2587
- delete node.raw;
2588
- delete node.quasis;
2589
- delete node.expressions;
2590
- }
2591
- const serializedTable = JSON.stringify(encryptedPayloads);
2592
- const integrityToken = computeFnv1aHash(serializedTable, seed);
2593
- for (const { type, node, parent, idx } of targetsToReplace) {
2594
- if (parent?.type === "Property" && parent.key === node) {
2595
- parent.computed = true;
2596
- }
2597
- if (type === "shader") {
2598
- node.type = "CallExpression";
2599
- node.callee = {
2600
- type: "Identifier",
2601
- name: shaderVarName
2602
- };
2603
- node.arguments = [
2604
- {
2605
- type: "Literal",
2606
- value: idx,
2607
- raw: String(idx)
2608
- }
2609
- ];
2610
- node.optional = false;
2611
- delete node.value;
2612
- delete node.raw;
2613
- delete node.quasis;
2614
- delete node.expressions;
2615
- } else {
2616
- const salt = computeCallSiteSalt(seed, idx);
2617
- node.type = "CallExpression";
2618
- node.callee = {
2619
- type: "Identifier",
2620
- name: decryptFnName
2621
- };
2622
- node.arguments = [
2623
- {
2624
- type: "Literal",
2625
- value: idx,
2626
- raw: String(idx)
2627
- },
2628
- {
2629
- type: "Literal",
2630
- value: salt,
2631
- raw: String(salt)
2632
- }
2633
- ];
2634
- node.optional = false;
2635
- delete node.value;
2636
- delete node.raw;
2637
- delete node.quasis;
2638
- delete node.expressions;
2639
- }
2640
- }
2641
- let insertIdx = 0;
2642
- while (insertIdx < ast.body.length) {
2643
- const stmt = ast.body[insertIdx];
2644
- const isDirective = stmt.type === "ExpressionStatement" && (Boolean(stmt.directive) || stmt.expression?.type === "Literal" && typeof stmt.expression.value === "string" && (activeDirectives.has(stmt.expression.value) || /^(?:use\s+[a-zA-Z0-9_-]+)/.test(stmt.expression.value.trim())));
2645
- if (isDirective || stmt.type === "ImportDeclaration") {
2646
- insertIdx++;
2647
- } else {
2648
- break;
2649
- }
2650
- }
2651
- if (hotTargetsToReplace.length > 0) {
2652
- const alreadyHasHx = ast.body.some(
2653
- (stmt) => stmt.type === "FunctionDeclaration" && stmt.id?.name === "_hX"
2654
- );
2655
- if (!alreadyHasHx) {
2656
- const hxAst = acorn4.parse(
2657
- 'function _hX(s,k){var o="";for(var i=0;i<s.length;i++)o+=String.fromCharCode(s.charCodeAt(i)^k);return o;}',
2658
- { ecmaVersion: "latest", sourceType: "script" }
2659
- );
2660
- ast.body.splice(insertIdx++, 0, hxAst.body[0]);
2661
- }
2662
- }
2663
- if (encryptedPayloads.length > 0) {
2664
- const vaultHelperStmt = createSaltedVaultHelperAst(
2665
- decryptFnName,
2666
- encryptedPayloads,
2667
- fnAst
2668
- );
2669
- ast.body.splice(insertIdx++, 0, vaultHelperStmt);
2670
- }
2671
- if (shaderPayloads.length > 0) {
2672
- const shaderHelperStmt = createShaderVaultAst(
2673
- shaderVarName,
2674
- shaderPayloads,
2675
- seed
2676
- );
2677
- ast.body.splice(insertIdx++, 0, shaderHelperStmt);
2678
- }
2679
- return {
2680
- encryptedStringsCount: encryptedPayloads.length + hotTargetsToReplace.length,
2681
- integrityToken,
2682
- shaderBuffersCount: shaderPayloads.length
2683
- };
2684
- }
2685
-
2686
- // src/ast/polymorphic-mangler.ts
2687
- import * as walk4 from "acorn-walk";
2688
- var RESERVED_IDENTIFIERS = /* @__PURE__ */ new Set([
2689
- "arguments",
2690
- "undefined",
2691
- "NaN",
2692
- "Infinity",
2693
- "window",
2694
- "document",
2695
- "globalThis",
2696
- "self",
2697
- "console",
2698
- "Math",
2699
- "JSON",
2700
- "Object",
2701
- "Array",
2702
- "String",
2703
- "Number",
2704
- "Boolean",
2705
- "Symbol",
2706
- "BigInt",
2707
- "Promise",
2708
- "Map",
2709
- "Set",
2710
- "WeakMap",
2711
- "WeakSet",
2712
- "Error",
2713
- "TypeError",
2714
- "RangeError",
2715
- "SyntaxError",
2716
- "RegExp",
2717
- "Date",
2718
- "Reflect",
2719
- "Proxy",
2720
- "Intl",
2721
- "eval",
2722
- "process",
2723
- "Buffer",
2724
- "require",
2725
- "module",
2726
- "exports",
2727
- "React",
2728
- "navigator",
2729
- "crypto",
2730
- "location",
2731
- "history",
2732
- "indexedDB",
2733
- "fetch",
2734
- "WebSocket",
2735
- "Worker",
2736
- "AudioContext",
2737
- "performance"
2738
- ]);
2739
- var JS_KEYWORDS = /* @__PURE__ */ new Set([
2740
- "as",
2741
- "await",
2742
- "break",
2743
- "case",
2744
- "catch",
2745
- "class",
2746
- "const",
2747
- "continue",
2748
- "debugger",
2749
- "default",
2750
- "delete",
2751
- "do",
2752
- "else",
2753
- "enum",
2754
- "export",
2755
- "extends",
2756
- "false",
2757
- "finally",
2758
- "for",
2759
- "function",
2760
- "if",
2761
- "implements",
2762
- "import",
2763
- "in",
2764
- "instanceof",
2765
- "interface",
2766
- "let",
2767
- "new",
2768
- "null",
2769
- "of",
2770
- "package",
2771
- "private",
2772
- "protected",
2773
- "public",
2774
- "return",
2775
- "static",
2776
- "super",
2777
- "switch",
2778
- "this",
2779
- "throw",
2780
- "true",
2781
- "try",
2782
- "typeof",
2783
- "var",
2784
- "void",
2785
- "while",
2786
- "with",
2787
- "yield"
2788
- ]);
2789
- var FUNCTION_TYPES = /* @__PURE__ */ new Set([
2790
- "FunctionDeclaration",
2791
- "FunctionExpression",
2792
- "ArrowFunctionExpression"
2793
- ]);
2794
- var LEXICAL_SCOPE_TYPES = /* @__PURE__ */ new Set([
2795
- "Program",
2796
- "FunctionDeclaration",
2797
- "FunctionExpression",
2798
- "ArrowFunctionExpression",
2799
- "BlockStatement",
2800
- "ForStatement",
2801
- "ForInStatement",
2802
- "ForOfStatement",
2803
- "SwitchStatement",
2804
- "CatchClause",
2805
- "ClassDeclaration",
2806
- "ClassExpression"
2807
- ]);
2808
- function collectPatternTargets(pattern, out, shorthandProp) {
2809
- if (!pattern) return;
2810
- switch (pattern.type) {
2811
- case "Identifier":
2812
- out.push({ idNode: pattern, shorthandProp });
2813
- break;
2814
- case "AssignmentPattern":
2815
- collectPatternTargets(pattern.left, out, shorthandProp);
2816
- break;
2817
- case "RestElement":
2818
- collectPatternTargets(pattern.argument, out);
2819
- break;
2820
- case "ArrayPattern":
2821
- for (const el of pattern.elements || []) {
2822
- if (el) collectPatternTargets(el, out);
2823
- }
2824
- break;
2825
- case "ObjectPattern":
2826
- for (const prop of pattern.properties || []) {
2827
- if (prop.type === "Property") {
2828
- collectPatternTargets(
2829
- prop.value,
2830
- out,
2831
- prop.shorthand ? prop : void 0
2832
- );
2833
- } else if (prop.type === "RestElement") {
2834
- collectPatternTargets(prop.argument, out);
2835
- }
2836
- }
2837
- break;
2838
- }
2839
- }
2840
- function isMangleableName(origName, reservedSet = RESERVED_IDENTIFIERS, manglerConfig) {
2841
- const minLength = manglerConfig?.minLength ?? 3;
2842
- return origName.length >= minLength && !reservedSet.has(origName) && !JS_KEYWORDS.has(origName) && !origName.startsWith("$") && !origName.startsWith("__") && !origName.startsWith("_u") && !origName.startsWith("_0x") && (!manglerConfig?.excludePrefixes || !manglerConfig.excludePrefixes.some((p) => origName.startsWith(p))) && (!manglerConfig?.excludePatterns || !manglerConfig.excludePatterns.some((re) => re.test(origName)));
2843
- }
2844
- function shuffleAlphabet(chars, seed) {
2845
- const arr = chars.split("");
2846
- let s = (seed || 324478056) >>> 0;
2847
- for (let i = arr.length - 1; i > 0; i--) {
2848
- s ^= s << 13;
2849
- s ^= s >>> 17;
2850
- s ^= s << 5;
2851
- const j = (s >>> 0) % (i + 1);
2852
- const tmp = arr[i];
2853
- arr[i] = arr[j];
2854
- arr[j] = tmp;
2855
- }
2856
- return arr;
2857
- }
2858
- function applyPolymorphicMangler(ast, seed = 2654435769, serializedFunctionNodes, config) {
2859
- const activeReserved = new Set(RESERVED_IDENTIFIERS);
2860
- if (config?.mangler?.reservedIdentifiers) {
2861
- for (const id of config.mangler.reservedIdentifiers) {
2862
- activeReserved.add(id);
2863
- }
2864
- }
2865
- const manglerConfig = config?.mangler;
2866
- const scopeRecords = /* @__PURE__ */ new Map();
2867
- const barrierOrFreeIds = /* @__PURE__ */ new Set();
2868
- const renamedTargetNodes = /* @__PURE__ */ new WeakSet();
2869
- let counter = 0;
2870
- function ensureScopeChain(ancestors) {
2871
- let prevScope = null;
2872
- for (let i = 0; i < ancestors.length; i++) {
2873
- const node = ancestors[i];
2874
- if (!LEXICAL_SCOPE_TYPES.has(node.type)) continue;
2875
- let record = scopeRecords.get(node);
2876
- if (!record) {
2877
- const isFn = FUNCTION_TYPES.has(node.type);
2878
- const depth = prevScope ? prevScope.depth + (isFn ? 1 : 0) : 0;
2879
- record = {
2880
- node,
2881
- parent: prevScope,
2882
- children: [],
2883
- depth: Math.max(1, depth),
2884
- bindings: /* @__PURE__ */ new Map(),
2885
- usedNames: /* @__PURE__ */ new Set()
2886
- };
2887
- scopeRecords.set(node, record);
2888
- if (prevScope) {
2889
- prevScope.children.push(record);
2890
- }
2891
- }
2892
- prevScope = record;
2893
- }
2894
- return prevScope;
2895
- }
2896
- function findEnclosingFunctionNode(ancestors) {
2897
- for (let i = ancestors.length - 1; i >= 0; i--) {
2898
- if (FUNCTION_TYPES.has(ancestors[i].type)) {
2899
- return ancestors[i];
2900
- }
2901
- }
2902
- return null;
2903
- }
2904
- function findEnclosingLexicalNode(ancestors) {
2905
- for (let i = ancestors.length - 1; i >= 0; i--) {
2906
- if (LEXICAL_SCOPE_TYPES.has(ancestors[i].type)) {
2907
- return ancestors[i];
2908
- }
2909
- }
2910
- return ancestors[0];
2911
- }
2912
- function registerBindingTarget(scopeNode, target, shouldMangle, fnScope) {
2913
- const scope = scopeRecords.get(scopeNode);
2914
- if (!scope) return;
2915
- const origName = target.idNode.name;
2916
- let canMangle = shouldMangle && isMangleableName(origName, activeReserved, manglerConfig);
2917
- if (canMangle && fnScope) {
2918
- if (serializedFunctionNodes && serializedFunctionNodes.has(fnScope)) {
2919
- canMangle = false;
2920
- }
2921
- }
2922
- renamedTargetNodes.add(target.idNode);
2923
- let entry = scope.bindings.get(origName);
2924
- if (!entry) {
2925
- entry = {
2926
- origName,
2927
- shouldMangle: canMangle,
2928
- targets: [target],
2929
- mangledName: origName
2930
- };
2931
- scope.bindings.set(origName, entry);
2932
- } else {
2933
- if (!canMangle) {
2934
- entry.shouldMangle = false;
2935
- }
2936
- entry.targets.push(target);
2937
- }
2938
- if (!entry.shouldMangle) {
2939
- barrierOrFreeIds.add(origName);
2940
- }
2941
- }
2942
- function registerBarrierName(scopeNode, origName) {
2943
- barrierOrFreeIds.add(origName);
2944
- const scope = scopeRecords.get(scopeNode);
2945
- if (!scope) return;
2946
- let entry = scope.bindings.get(origName);
2947
- if (!entry) {
2948
- entry = {
2949
- origName,
2950
- shouldMangle: false,
2951
- targets: [],
2952
- mangledName: origName
2953
- };
2954
- scope.bindings.set(origName, entry);
2955
- } else {
2956
- entry.shouldMangle = false;
2957
- }
2958
- }
2959
- function registerFunctionParams(fnNode, ancestors) {
2960
- ensureScopeChain(ancestors);
2961
- for (const param of fnNode.params || []) {
2962
- const targets = [];
2963
- collectPatternTargets(param, targets);
2964
- for (const target of targets) {
2965
- registerBindingTarget(fnNode, target, true, fnNode);
2966
- }
2967
- }
2968
- }
2969
- ensureScopeChain([ast]);
2970
- walk4.ancestor(ast, {
2971
- BlockStatement(_node, _state, ancestors) {
2972
- ensureScopeChain(ancestors);
2973
- },
2974
- ForStatement(_node, _state, ancestors) {
2975
- ensureScopeChain(ancestors);
2976
- },
2977
- ForInStatement(_node, _state, ancestors) {
2978
- ensureScopeChain(ancestors);
2979
- },
2980
- ForOfStatement(_node, _state, ancestors) {
2981
- ensureScopeChain(ancestors);
2982
- },
2983
- SwitchStatement(_node, _state, ancestors) {
2984
- ensureScopeChain(ancestors);
2985
- },
2986
- ImportSpecifier(node) {
2987
- if (node.local?.name) barrierOrFreeIds.add(node.local.name);
2988
- },
2989
- ImportDefaultSpecifier(node) {
2990
- if (node.local?.name) barrierOrFreeIds.add(node.local.name);
2991
- },
2992
- ImportNamespaceSpecifier(node) {
2993
- if (node.local?.name) barrierOrFreeIds.add(node.local.name);
2994
- },
2995
- FunctionDeclaration(node, _state, ancestors) {
2996
- registerFunctionParams(node, ancestors);
2997
- if (node.id?.type === "Identifier") {
2998
- const parentAncestors = ancestors.slice(0, -1);
2999
- const lexNode = findEnclosingLexicalNode(parentAncestors);
3000
- const fnNode = findEnclosingFunctionNode(parentAncestors) ?? ast;
3001
- registerBarrierName(lexNode, node.id.name);
3002
- if (lexNode === fnNode.body || fnNode === ast) {
3003
- registerBarrierName(fnNode, node.id.name);
3004
- }
3005
- if (!scopeRecords.get(node)?.bindings.has(node.id.name)) {
3006
- registerBarrierName(node, node.id.name);
3007
- }
3008
- }
3009
- },
3010
- FunctionExpression(node, _state, ancestors) {
3011
- registerFunctionParams(node, ancestors);
3012
- if (node.id?.type === "Identifier") {
3013
- if (!scopeRecords.get(node)?.bindings.has(node.id.name)) {
3014
- registerBarrierName(node, node.id.name);
3015
- }
3016
- }
3017
- },
3018
- ArrowFunctionExpression(node, _state, ancestors) {
3019
- registerFunctionParams(node, ancestors);
3020
- },
3021
- ClassDeclaration(node, _state, ancestors) {
3022
- ensureScopeChain(ancestors);
3023
- if (node.id?.type === "Identifier") {
3024
- const parentAncestors = ancestors.slice(0, -1);
3025
- const lexNode = findEnclosingLexicalNode(parentAncestors);
3026
- registerBarrierName(lexNode, node.id.name);
3027
- registerBarrierName(node, node.id.name);
3028
- }
3029
- },
3030
- ClassExpression(node, _state, ancestors) {
3031
- ensureScopeChain(ancestors);
3032
- if (node.id?.type === "Identifier") {
3033
- registerBarrierName(node, node.id.name);
3034
- }
3035
- },
3036
- CatchClause(node, _state, ancestors) {
3037
- ensureScopeChain(ancestors);
3038
- if (node.param) {
3039
- const fnScope = findEnclosingFunctionNode(ancestors);
3040
- const targets = [];
3041
- collectPatternTargets(node.param, targets);
3042
- for (const target of targets) {
3043
- registerBindingTarget(node, target, true, fnScope);
3044
- }
3045
- }
3046
- },
3047
- VariableDeclaration(node, _state, ancestors) {
3048
- ensureScopeChain(ancestors);
3049
- const fnScope = findEnclosingFunctionNode(ancestors);
3050
- if (!fnScope) {
3051
- for (const decl of node.declarations || []) {
3052
- const targets = [];
3053
- collectPatternTargets(decl.id, targets);
3054
- for (const target of targets) {
3055
- registerBarrierName(ast, target.idNode.name);
3056
- }
3057
- }
3058
- return;
3059
- }
3060
- const targetScopeNode = node.kind === "var" ? fnScope : findEnclosingLexicalNode(ancestors);
3061
- for (const decl of node.declarations || []) {
3062
- const targets = [];
3063
- collectPatternTargets(decl.id, targets);
3064
- for (const target of targets) {
3065
- const origName = target.idNode.name;
3066
- if (node.kind === "var") {
3067
- for (let i = ancestors.length - 1; i >= 0; i--) {
3068
- if (ancestors[i] === fnScope) break;
3069
- if (ancestors[i].type === "CatchClause") {
3070
- const catchScope = scopeRecords.get(ancestors[i]);
3071
- if (catchScope?.bindings.has(origName)) {
3072
- registerBarrierName(ancestors[i], origName);
3073
- registerBarrierName(fnScope, origName);
3074
- }
3075
- }
3076
- }
3077
- }
3078
- registerBindingTarget(targetScopeNode, target, true, fnScope);
3079
- }
3080
- }
3081
- }
3082
- });
3083
- function resolveBinding(name, ancestors) {
3084
- for (let i = ancestors.length - 1; i >= 0; i--) {
3085
- const scope = scopeRecords.get(ancestors[i]);
3086
- if (scope && scope.bindings.has(name)) {
3087
- return scope.bindings.get(name);
3088
- }
3089
- }
3090
- return null;
3091
- }
3092
- function isNonVarIdentifierPosition(node, parent) {
3093
- if (!parent) return true;
3094
- if ((parent.type === "FunctionDeclaration" || parent.type === "FunctionExpression" || parent.type === "ClassDeclaration" || parent.type === "ClassExpression") && parent.id === node) {
3095
- return true;
3096
- }
3097
- if (parent.type === "MemberExpression" && parent.property === node && !parent.computed) {
3098
- return true;
3099
- }
3100
- if ((parent.type === "Property" || parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") && parent.key === node && !parent.computed) {
3101
- return true;
3102
- }
3103
- if (parent.type === "LabeledStatement" || parent.type === "BreakStatement" || parent.type === "ContinueStatement" || parent.type === "ImportSpecifier" || parent.type === "ImportDefaultSpecifier" || parent.type === "ImportNamespaceSpecifier" || parent.type === "ExportSpecifier" || parent.type === "MetaProperty") {
3104
- return true;
3105
- }
3106
- return false;
3107
- }
3108
- walk4.ancestor(ast, {
3109
- Identifier(node, _state, ancestors) {
3110
- if (renamedTargetNodes.has(node)) return;
3111
- const parent = ancestors[ancestors.length - 2];
3112
- if (isNonVarIdentifierPosition(node, parent)) return;
3113
- const entry = resolveBinding(node.name, ancestors);
3114
- if (!entry || !entry.shouldMangle) {
3115
- barrierOrFreeIds.add(node.name);
3116
- }
3117
- }
3118
- });
3119
- function isNameUsedInScopeOrAncestors(candidate, scope) {
3120
- if (JS_KEYWORDS.has(candidate) || activeReserved.has(candidate) || barrierOrFreeIds.has(candidate)) {
3121
- return true;
3122
- }
3123
- let curr = scope;
3124
- while (curr) {
3125
- if (curr.usedNames.has(candidate)) {
3126
- return true;
3127
- }
3128
- curr = curr.parent;
3129
- }
3130
- return false;
3131
- }
3132
- const p1 = shuffleAlphabet("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", seed);
3133
- const p2a = shuffleAlphabet(
3134
- "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
3135
- (seed ^ 1367130551) >>> 0
3136
- );
3137
- const p2b = shuffleAlphabet(
3138
- "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_",
3139
- (seed ^ 2654435769) >>> 0
3140
- );
3141
- function candidateAtSlot(slot) {
3142
- if (slot < p1.length) {
3143
- return p1[slot];
3144
- }
3145
- const rem = slot - p1.length;
3146
- const twoCharSpace = p2a.length * p2b.length;
3147
- if (rem < twoCharSpace) {
3148
- return `${p2a[rem % p2a.length]}${p2b[Math.floor(rem / p2a.length)]}`;
3149
- }
3150
- const rem3 = rem - twoCharSpace;
3151
- return `${p2a[rem3 % p2a.length]}${p2b[Math.floor(rem3 / p2a.length) % p2b.length]}${p2b[Math.floor(rem3 / twoCharSpace) % p2b.length]}`;
3152
- }
3153
- function makeScopedMangledName(scope, origName) {
3154
- let slot = 0;
3155
- while (true) {
3156
- const candidate = candidateAtSlot(slot);
3157
- slot++;
3158
- if (candidate === origName) continue;
3159
- if (!isNameUsedInScopeOrAncestors(candidate, scope)) {
3160
- return candidate;
3161
- }
3162
- }
3163
- }
3164
- function assignScopeNamesTopDown(scope) {
3165
- for (const entry of scope.bindings.values()) {
3166
- if (!entry.shouldMangle) {
3167
- entry.mangledName = entry.origName;
3168
- scope.usedNames.add(entry.origName);
3169
- continue;
3170
- }
3171
- const mangled = makeScopedMangledName(scope, entry.origName);
3172
- counter++;
3173
- entry.mangledName = mangled;
3174
- scope.usedNames.add(mangled);
3175
- for (const target of entry.targets) {
3176
- if (target.shorthandProp && target.shorthandProp.shorthand) {
3177
- target.shorthandProp.shorthand = false;
3178
- target.shorthandProp.key = {
3179
- type: "Identifier",
3180
- name: entry.origName
3181
- };
3182
- }
3183
- target.idNode.name = mangled;
3184
- }
3185
- }
3186
- for (const child of scope.children) {
3187
- assignScopeNamesTopDown(child);
3188
- }
3189
- }
3190
- const rootScope = scopeRecords.get(ast);
3191
- if (rootScope) {
3192
- assignScopeNamesTopDown(rootScope);
3193
- }
3194
- if (counter === 0) return 0;
3195
- function renamePatternTargetsInScope(pattern, ancestors) {
3196
- const targets = [];
3197
- collectPatternTargets(pattern, targets);
3198
- for (const target of targets) {
3199
- if (renamedTargetNodes.has(target.idNode)) continue;
3200
- const origName = target.idNode.name;
3201
- const entry = resolveBinding(origName, ancestors);
3202
- if (entry && entry.shouldMangle && entry.mangledName !== origName) {
3203
- if (target.shorthandProp && target.shorthandProp.shorthand) {
3204
- target.shorthandProp.shorthand = false;
3205
- target.shorthandProp.key = {
3206
- type: "Identifier",
3207
- name: origName
3208
- };
3209
- }
3210
- target.idNode.name = entry.mangledName;
3211
- renamedTargetNodes.add(target.idNode);
3212
- }
3213
- }
3214
- }
3215
- walk4.ancestor(ast, {
3216
- AssignmentExpression(node, _state, ancestors) {
3217
- renamePatternTargetsInScope(node.left, ancestors);
3218
- },
3219
- ForInStatement(node, _state, ancestors) {
3220
- if (node.left && node.left.type !== "VariableDeclaration") {
3221
- renamePatternTargetsInScope(node.left, ancestors);
3222
- }
3223
- },
3224
- ForOfStatement(node, _state, ancestors) {
3225
- if (node.left && node.left.type !== "VariableDeclaration") {
3226
- renamePatternTargetsInScope(node.left, ancestors);
3227
- }
3228
- },
3229
- Identifier(node, _state, ancestors) {
3230
- if (renamedTargetNodes.has(node)) return;
3231
- const parent = ancestors[ancestors.length - 2];
3232
- if (isNonVarIdentifierPosition(node, parent)) return;
3233
- const entry = resolveBinding(node.name, ancestors);
3234
- if (entry && entry.shouldMangle && entry.mangledName !== node.name) {
3235
- if (parent.type === "Property" && parent.shorthand && parent.value === node) {
3236
- parent.shorthand = false;
3237
- parent.key = { type: "Identifier", name: node.name };
3238
- }
3239
- node.name = entry.mangledName;
3240
- }
3241
- }
3242
- });
3243
- return counter;
3244
- }
3245
-
3246
- // src/ast/cold-flow-guard.ts
3247
- import * as walk5 from "acorn-walk";
3248
- function createDecoyObjectExpression(model) {
3249
- const m = Math.abs(model) % 3;
3250
- if (m === 0) {
3251
- return {
3252
- type: "ObjectExpression",
3253
- properties: [
3254
- {
3255
- type: "Property",
3256
- key: { type: "Identifier", name: "endpoint" },
3257
- value: {
3258
- type: "Literal",
3259
- value: "/api/v2/auth/admin-bypass",
3260
- raw: '"/api/v2/auth/admin-bypass"'
3261
- },
3262
- kind: "init",
3263
- computed: false,
3264
- method: false,
3265
- shorthand: false
3266
- },
3267
- {
3268
- type: "Property",
3269
- key: { type: "Identifier", name: "superadmin_token" },
3270
- value: { type: "Literal", value: 1, raw: "1" },
3271
- kind: "init",
3272
- computed: false,
3273
- method: false,
3274
- shorthand: false
3275
- },
3276
- {
3277
- type: "Property",
3278
- key: { type: "Identifier", name: "elevate" },
3279
- value: { type: "Literal", value: 1, raw: "1" },
3280
- kind: "init",
3281
- computed: false,
3282
- method: false,
3283
- shorthand: false
3284
- }
3285
- ]
3286
- };
3287
- }
3288
- if (m === 1) {
3289
- return {
3290
- type: "ObjectExpression",
3291
- properties: [
3292
- {
3293
- type: "Property",
3294
- key: { type: "Identifier", name: "endpoint" },
3295
- value: {
3296
- type: "Literal",
3297
- value: "/api/v2/auth/verify-master",
3298
- raw: '"/api/v2/auth/verify-master"'
3299
- },
3300
- kind: "init",
3301
- computed: false,
3302
- method: false,
3303
- shorthand: false
3304
- },
3305
- {
3306
- type: "Property",
3307
- key: { type: "Identifier", name: "_verifyMasterToken" },
3308
- value: { type: "Literal", value: true, raw: "true" },
3309
- kind: "init",
3310
- computed: false,
3311
- method: false,
3312
- shorthand: false
3313
- },
3314
- {
3315
- type: "Property",
3316
- key: { type: "Identifier", name: "_bypassToken" },
3317
- value: {
3318
- type: "Literal",
3319
- value: "mock_jwt_bypass_signature",
3320
- raw: '"mock_jwt_bypass_signature"'
3321
- },
3322
- kind: "init",
3323
- computed: false,
3324
- method: false,
3325
- shorthand: false
3326
- },
3327
- {
3328
- type: "Property",
3329
- key: { type: "Identifier", name: "authorized" },
3330
- value: { type: "Literal", value: true, raw: "true" },
3331
- kind: "init",
3332
- computed: false,
3333
- method: false,
3334
- shorthand: false
3335
- }
3336
- ]
3337
- };
3338
- }
3339
- return {
3340
- type: "ObjectExpression",
3341
- properties: [
3342
- {
3343
- type: "Property",
3344
- key: { type: "Identifier", name: "endpoint" },
3345
- value: {
3346
- type: "Literal",
3347
- value: "/api/v2/auth/debug-telemetry",
3348
- raw: '"/api/v2/auth/debug-telemetry"'
3349
- },
3350
- kind: "init",
3351
- computed: false,
3352
- method: false,
3353
- shorthand: false
3354
- },
3355
- {
3356
- type: "Property",
3357
- key: { type: "Identifier", name: "debug_supervisor_override" },
3358
- value: { type: "Literal", value: true, raw: "true" },
3359
- kind: "init",
3360
- computed: false,
3361
- method: false,
3362
- shorthand: false
3363
- },
3364
- {
3365
- type: "Property",
3366
- key: { type: "Identifier", name: "_bypassToken" },
3367
- value: {
3368
- type: "Literal",
3369
- value: "superadmin_token",
3370
- raw: '"superadmin_token"'
3371
- },
3372
- kind: "init",
3373
- computed: false,
3374
- method: false,
3375
- shorthand: false
3376
- },
3377
- {
3378
- type: "Property",
3379
- key: { type: "Identifier", name: "mfa_bypassed" },
3380
- value: { type: "Literal", value: true, raw: "true" },
3381
- kind: "init",
3382
- computed: false,
3383
- method: false,
3384
- shorthand: false
3385
- }
3386
- ]
3387
- };
3388
- }
3389
- function createDecoyConsequent(fnIndex) {
3390
- return {
3391
- type: "BlockStatement",
3392
- body: [
3393
- {
3394
- type: "ReturnStatement",
3395
- argument: createDecoyObjectExpression(fnIndex)
3396
- }
3397
- ]
3398
- };
3399
- }
3400
- function createSharedDecoyConsequent(decoyIdent, fnIndex) {
3401
- const model = Math.abs(fnIndex) % 3;
3402
- return {
3403
- type: "BlockStatement",
3404
- body: [
3405
- {
3406
- type: "ReturnStatement",
3407
- argument: {
3408
- type: "CallExpression",
3409
- callee: {
3410
- type: "MemberExpression",
3411
- computed: true,
3412
- object: { type: "Identifier", name: decoyIdent },
3413
- property: {
3414
- type: "Literal",
3415
- value: model,
3416
- raw: String(model)
3417
- }
3418
- },
3419
- arguments: []
3420
- }
3421
- }
3422
- ]
3423
- };
3424
- }
3425
- function createSharedDecoyDeclaration(decoyIdent = "_d", maxModels = 3) {
3426
- const count = Math.max(1, Math.min(3, maxModels));
3427
- const indices = [];
3428
- for (let i = 0; i < count; i++) indices.push(i);
3429
- return {
3430
- type: "VariableDeclaration",
3431
- kind: "var",
3432
- declarations: [
3433
- {
3434
- type: "VariableDeclarator",
3435
- id: { type: "Identifier", name: decoyIdent },
3436
- init: {
3437
- type: "ArrayExpression",
3438
- elements: indices.map((m) => ({
3439
- type: "ArrowFunctionExpression",
3440
- id: null,
3441
- params: [],
3442
- body: createDecoyObjectExpression(m),
3443
- generator: false,
3444
- async: false,
3445
- expression: true
3446
- }))
3447
- }
3448
- }
3449
- ]
3450
- };
3451
- }
3452
- function cloneNode(node) {
3453
- return JSON.parse(JSON.stringify(node));
3454
- }
3455
- function makeImul(left, right) {
3456
- return {
3457
- type: "CallExpression",
3458
- callee: {
3459
- type: "MemberExpression",
3460
- computed: false,
3461
- object: { type: "Identifier", name: "Math" },
3462
- property: { type: "Identifier", name: "imul" }
3463
- },
3464
- arguments: [left, right]
3465
- };
3466
- }
3467
- function makeBinary(operator, left, right) {
3468
- return {
3469
- type: "BinaryExpression",
3470
- operator,
3471
- left,
3472
- right
3473
- };
3474
- }
3475
- function makeUnary(operator, argument) {
3476
- return {
3477
- type: "UnaryExpression",
3478
- operator,
3479
- prefix: true,
3480
- argument
3481
- };
3482
- }
3483
- function makeLiteral(value) {
3484
- return {
3485
- type: "Literal",
3486
- value,
3487
- raw: String(value)
3488
- };
3489
- }
3490
- function createSotaMbaPredicate(seed, fnIndex = 0, paramNode, decoyIdent, isArrowFn = false) {
3491
- const family = Math.abs((seed + fnIndex) % 5);
3492
- const c1 = (seed >>> 1) + Math.imul(family + 1, 22912827) & 32767;
3493
- const c2 = (c1 ^ 173477) & 32767;
3494
- const target = (seed ^ Math.imul(family + 1, 2654435761)) & 65535 | 1;
3495
- let paramName = null;
3496
- if (typeof paramNode === "string") {
3497
- paramName = paramNode;
3498
- } else if (paramNode?.type === "Identifier") {
3499
- paramName = paramNode.name;
3500
- } else if (paramNode?.type === "AssignmentPattern" && paramNode.left?.type === "Identifier") {
3501
- paramName = paramNode.left.name;
3502
- } else if (paramNode?.type === "RestElement" && paramNode.argument?.type === "Identifier") {
3503
- paramName = paramNode.argument.name;
3504
- }
3505
- let vBitNode;
3506
- let vIntNode;
3507
- if (paramName && paramName !== "arguments" && paramName !== "eval") {
3508
- vBitNode = { type: "Identifier", name: paramName };
3509
- vIntNode = makeBinary("|", { type: "Identifier", name: paramName }, makeLiteral(0));
3510
- } else if (!isArrowFn) {
3511
- vBitNode = {
3512
- type: "MemberExpression",
3513
- computed: false,
3514
- object: { type: "Identifier", name: "arguments" },
3515
- property: { type: "Identifier", name: "length" }
3516
- };
3517
- vIntNode = cloneNode(vBitNode);
3518
- } else {
3519
- vBitNode = {
3520
- type: "MemberExpression",
3521
- computed: false,
3522
- object: makeUnary("typeof", { type: "Identifier", name: "globalThis" }),
3523
- property: { type: "Identifier", name: "length" }
3524
- };
3525
- vIntNode = cloneNode(vBitNode);
3526
- }
3527
- const kLit = makeLiteral(c2);
3528
- let mbaExpr;
3529
- if (family === 0) {
3530
- const term1 = makeImul(cloneNode(vIntNode), cloneNode(kLit));
3531
- const vAndK = makeBinary("&", cloneNode(vBitNode), cloneNode(kLit));
3532
- const vOrK = makeBinary("|", cloneNode(vBitNode), cloneNode(kLit));
3533
- const notK = makeUnary("~", cloneNode(kLit));
3534
- const notV = makeUnary("~", cloneNode(vBitNode));
3535
- const vAndNotK = makeBinary("&", cloneNode(vBitNode), notK);
3536
- const notVAndK = makeBinary("&", notV, cloneNode(kLit));
3537
- const term2 = makeImul(vAndK, vOrK);
3538
- const term3 = makeImul(vAndNotK, notVAndK);
3539
- const sumTerms = makeBinary("+", term2, term3);
3540
- mbaExpr = makeBinary("|", makeBinary("-", term1, sumTerms), makeLiteral(0));
3541
- } else if (family === 1) {
3542
- const vXorK1 = makeBinary("^", cloneNode(vBitNode), cloneNode(kLit));
3543
- const vXorK2 = makeBinary("^", cloneNode(vBitNode), cloneNode(kLit));
3544
- const term1 = makeImul(vXorK1, vXorK2);
3545
- const vSubK1 = makeBinary("-", cloneNode(vIntNode), cloneNode(kLit));
3546
- const vSubK2 = makeBinary("-", cloneNode(vIntNode), cloneNode(kLit));
3547
- const term2 = makeImul(vSubK1, vSubK2);
3548
- const notK = makeUnary("~", cloneNode(kLit));
3549
- const notV = makeUnary("~", cloneNode(vBitNode));
3550
- const vAndNotK = makeBinary("&", cloneNode(vBitNode), notK);
3551
- const notVAndK = makeBinary("&", notV, cloneNode(kLit));
3552
- const term3 = makeImul(vAndNotK, notVAndK);
3553
- const shiftTerm = makeBinary("<<", term3, makeLiteral(2));
3554
- const sumTerms = makeBinary("+", term2, shiftTerm);
3555
- mbaExpr = makeBinary("|", makeBinary("-", term1, sumTerms), makeLiteral(0));
3556
- } else if (family === 2) {
3557
- const vAddK1 = makeBinary("+", cloneNode(vIntNode), cloneNode(kLit));
3558
- const vAddK2 = makeBinary("+", cloneNode(vIntNode), cloneNode(kLit));
3559
- const term1 = makeImul(vAddK1, vAddK2);
3560
- const vAndK = makeBinary("&", cloneNode(vBitNode), cloneNode(kLit));
3561
- const vOrK = makeBinary("|", cloneNode(vBitNode), cloneNode(kLit));
3562
- const term2 = makeImul(vAndK, vOrK);
3563
- const shiftTerm = makeBinary("<<", term2, makeLiteral(2));
3564
- const vXorK1 = makeBinary("^", cloneNode(vBitNode), cloneNode(kLit));
3565
- const vXorK2 = makeBinary("^", cloneNode(vBitNode), cloneNode(kLit));
3566
- const term3 = makeImul(vXorK1, vXorK2);
3567
- const sumTerms = makeBinary("+", shiftTerm, term3);
3568
- mbaExpr = makeBinary("|", makeBinary("-", term1, sumTerms), makeLiteral(0));
3569
- } else if (family === 3) {
3570
- const vOrK1 = makeBinary("|", cloneNode(vBitNode), cloneNode(kLit));
3571
- const vOrK2 = makeBinary("|", cloneNode(vBitNode), cloneNode(kLit));
3572
- const term1 = makeImul(vOrK1, vOrK2);
3573
- const vAndK1 = makeBinary("&", cloneNode(vBitNode), cloneNode(kLit));
3574
- const vAndK2 = makeBinary("&", cloneNode(vBitNode), cloneNode(kLit));
3575
- const term2 = makeImul(vAndK1, vAndK2);
3576
- const vXorK = makeBinary("^", cloneNode(vBitNode), cloneNode(kLit));
3577
- const vAddK = makeBinary("+", cloneNode(vIntNode), cloneNode(kLit));
3578
- const term3 = makeImul(vXorK, vAddK);
3579
- const sumTerms = makeBinary("+", term2, term3);
3580
- mbaExpr = makeBinary("|", makeBinary("-", term1, sumTerms), makeLiteral(0));
3581
- } else {
3582
- const vk = makeBinary("^", cloneNode(vBitNode), cloneNode(kLit));
3583
- const vkSq = makeImul(vk, cloneNode(vk));
3584
- const sevenVkSqSub1 = makeBinary("-", makeImul(makeLiteral(7), vkSq), makeLiteral(1));
3585
- const vSq = makeImul(cloneNode(vBitNode), cloneNode(vBitNode));
3586
- const quadDiff = makeBinary("^", makeBinary("&", makeBinary("^", sevenVkSqSub1, vSq), makeLiteral(2)), makeLiteral(2));
3587
- const parityTerm = makeBinary("&", makeBinary("+", makeImul(cloneNode(vBitNode), cloneNode(vBitNode)), cloneNode(vIntNode)), makeLiteral(1));
3588
- mbaExpr = makeBinary("|", quadDiff, parityTerm);
3589
- }
3590
- const decoyIdx = Math.abs(fnIndex) % 3;
3591
- const consequent = decoyIdent ? createSharedDecoyConsequent(decoyIdent, decoyIdx) : createDecoyConsequent(decoyIdx);
3592
- return {
3593
- type: "IfStatement",
3594
- test: {
3595
- type: "BinaryExpression",
3596
- operator: "===",
3597
- left: mbaExpr,
3598
- right: { type: "Literal", value: target, raw: String(target) }
3599
- },
3600
- consequent,
3601
- alternate: null
3602
- };
3603
- }
3604
- var MAX_COLD_GUARDS_PER_CHUNK = 12;
3605
- function applyColdFlowGuard(ast, coldFunctionNodes, seed = 2654435769, hotExemptNodes) {
3606
- const decoyIdent = "_d";
3607
- if (Array.isArray(ast.body)) {
3608
- const alreadyGuarded = ast.body.some(
3609
- (stmt) => stmt.type === "VariableDeclaration" && stmt.declarations?.some(
3610
- (d) => d.id?.type === "Identifier" && d.id.name === decoyIdent
3611
- )
3612
- );
3613
- if (alreadyGuarded) return 0;
3614
- }
3615
- let guardedCount = 0;
3616
- function maybeInjectGuard(node) {
3617
- if (guardedCount >= MAX_COLD_GUARDS_PER_CHUNK) return;
3618
- if (!coldFunctionNodes.has(node)) return;
3619
- if (!node.body || node.body.type !== "BlockStatement") return;
3620
- const firstParam = node.params?.[0];
3621
- const isArrow = node.type === "ArrowFunctionExpression";
3622
- const guardStmt = createSotaMbaPredicate(
3623
- seed,
3624
- guardedCount,
3625
- firstParam,
3626
- decoyIdent,
3627
- isArrow
3628
- );
3629
- guardedCount++;
3630
- if (hotExemptNodes) {
3631
- hotExemptNodes.add(guardStmt);
3632
- hotExemptNodes.add(guardStmt.consequent);
3633
- }
3634
- let insertIdx = 0;
3635
- while (insertIdx < node.body.body.length && node.body.body[insertIdx].type === "ExpressionStatement" && node.body.body[insertIdx].directive) {
3636
- insertIdx++;
3637
- }
3638
- node.body.body.splice(insertIdx, 0, guardStmt);
3639
- }
3640
- walk5.simple(ast, {
3641
- FunctionDeclaration: maybeInjectGuard,
3642
- FunctionExpression: maybeInjectGuard,
3643
- ArrowFunctionExpression: maybeInjectGuard
3644
- });
3645
- if (guardedCount > 0 && Array.isArray(ast.body)) {
3646
- const sharedDecoyDecl = createSharedDecoyDeclaration(decoyIdent, guardedCount);
3647
- if (hotExemptNodes) {
3648
- hotExemptNodes.add(sharedDecoyDecl);
3649
- for (const decl of sharedDecoyDecl.declarations || []) {
3650
- if (decl.init?.elements) {
3651
- for (const el of decl.init.elements) {
3652
- hotExemptNodes.add(el);
3653
- }
3654
- }
3655
- }
3656
- }
3657
- let insertIdx = 0;
3658
- while (insertIdx < ast.body.length && ast.body[insertIdx].type === "ExpressionStatement" && ast.body[insertIdx].directive) {
3659
- insertIdx++;
3660
- }
3661
- ast.body.splice(insertIdx, 0, sharedDecoyDecl);
3662
- }
3663
- return guardedCount;
3664
- }
3665
-
3666
- // src/ast/micro-vm.ts
3667
- import * as acorn5 from "acorn";
3668
- import * as walk6 from "acorn-walk";
3669
- var OP_LDC = 0;
3670
- var OP_LDV = 1;
3671
- var OP_STV = 2;
3672
- var OP_LDG = 3;
3673
- var OP_GETP = 4;
3674
- var OP_SETP = 5;
3675
- var OP_CALL = 6;
3676
- var OP_MCALL = 7;
3677
- var OP_ADD = 8;
3678
- var OP_SUB = 9;
3679
- var OP_MUL = 10;
3680
- var OP_XOR = 11;
3681
- var OP_AND = 12;
3682
- var OP_OR = 13;
3683
- var OP_SEQ = 14;
3684
- var OP_LT = 15;
3685
- var OP_NOT = 16;
3686
- var OP_JMP = 17;
3687
- var OP_JZ = 18;
3688
- var OP_RET = 19;
3689
- var OP_THROW = 20;
3690
- var OP_AWAIT = 21;
3691
- var OP_OBJ = 22;
3692
- var OP_ARR = 23;
3693
- var OP_LDU = 24;
3694
- var OP_STU = 25;
3695
- var OPCODE_COUNT = 26;
3696
- function shuffleRange(n, seed) {
3697
- const arr = [];
3698
- for (let i = 0; i < n; i++) arr.push(i);
3699
- let s = (seed || 324478056) >>> 0;
3700
- function rand() {
3701
- s ^= s << 13;
3702
- s ^= s >>> 17;
3703
- s ^= s << 5;
3704
- return (s >>> 0) / 4294967296;
3705
- }
3706
- for (let i = arr.length - 1; i > 0; i--) {
3707
- const j = Math.floor(rand() * (i + 1));
3708
- const tmp = arr[i];
3709
- arr[i] = arr[j];
3710
- arr[j] = tmp;
3711
- }
3712
- return arr;
3713
- }
3714
- function deriveVmKey(seed) {
3715
- return computeFnv1aHash("vm-key", seed) | 0;
3716
- }
3717
- function encryptBytecodeStream(plainBytecode, fnSalt, vmKey, stateSlots) {
3718
- const len = plainBytecode.length;
3719
- const enc = new Array(len);
3720
- const stateBefore = new Array(len + 1);
3721
- const stAtSlot = /* @__PURE__ */ new Map();
3722
- let st = vmKey ^ fnSalt | 0;
3723
- for (let p = 0; p < len; p++) {
3724
- stateBefore[p] = st;
3725
- if (stateSlots && stateSlots.has(p)) {
3726
- stAtSlot.set(p, st);
3727
- enc[p] = 0;
3728
- } else {
3729
- st = Math.imul(st ^ p + 1, 73244475) + 2654435769 | 0;
3730
- const raw = plainBytecode[p] ^ st >>> 16 & 65535;
3731
- enc[p] = raw;
3732
- st = st ^ Math.imul(raw + 1, 2246822507) | 0;
3733
- }
3734
- }
3735
- stateBefore[len] = st;
3736
- if (stateSlots) {
3737
- for (const slot of stateSlots) {
3738
- const targetPc = plainBytecode[slot - 1];
3739
- const sBefore = stAtSlot.get(slot) ?? 0;
3740
- enc[slot] = stateBefore[targetPc] ^ sBefore | 0;
3741
- }
3742
- }
3743
- return enc;
3744
- }
3745
- function generateOpcodeMap(seed, count = OPCODE_COUNT) {
3746
- const pool = [];
3747
- for (let i = 0; i < 256; i++) pool.push(i);
3748
- let s = (seed ^ 2779096485) >>> 0;
3749
- function rand() {
3750
- s ^= s << 13;
3751
- s ^= s >>> 17;
3752
- s ^= s << 5;
3753
- return (s >>> 0) / 4294967296;
3754
- }
3755
- for (let i = pool.length - 1; i > 0; i--) {
3756
- const j = Math.floor(rand() * (i + 1));
3757
- const tmp = pool[i];
3758
- pool[i] = pool[j];
3759
- pool[j] = tmp;
3760
- }
3761
- return pool.slice(0, count);
3762
- }
3763
- function createInterpreterSource(vmHelperName, opMap, seed = 2654435769, windowKeySymbol, expectedDelta) {
3764
- const opCount = opMap.length;
3765
- const slotMap = shuffleRange(opCount, (seed ^ 1367130551) >>> 0);
3766
- const pairOrder = shuffleRange(opCount, (seed ^ 1013904242) >>> 0);
3767
- const opMask = computeFnv1aHash("vm-opmask", seed) & 255 | 1;
3768
- const slotMask = computeFnv1aHash("vm-slotmask", seed) & 127 | 32;
3769
- const vmKey = deriveVmKey(seed);
3770
- const pairs = [];
3771
- for (const op of pairOrder) {
3772
- pairs.push(opMap[op] ^ opMask, slotMap[op] ^ slotMask);
3773
- }
3774
- const handlerMap = {
3775
- [OP_LDC]: "function($f){$f.q[$f.r++]=$f.k[$rd($f)];}",
3776
- [OP_LDV]: "function($f){$f.q[$f.r++]=$f.s[$rd($f)];}",
3777
- [OP_STV]: "function($f){$f.s[$rd($f)]=$f.q[--$f.r];}",
3778
- [OP_LDG]: "function($f){$f.q[$f.r++]=$G[$f.k[$rd($f)]];}",
3779
- [OP_GETP]: "function($f){var $b=$f.q[--$f.r],$a=$f.q[--$f.r];$f.q[$f.r++]=$a[$b];}",
3780
- [OP_SETP]: "function($f){var $v=$f.q[--$f.r],$b=$f.q[--$f.r],$a=$f.q[--$f.r];$f.q[$f.r++]=($a[$b]=$v);}",
3781
- [OP_CALL]: "function($f){var $n=$rd($f),$g=[];for(var $i=$n-1;$i>=0;$i--)$g[$i]=$f.q[--$f.r];var $fn=$f.q[--$f.r];$f.q[$f.r++]=$fn.apply(void 0,$g);}",
3782
- [OP_MCALL]: "function($f){var $n=$rd($f),$g=[];for(var $i=$n-1;$i>=0;$i--)$g[$i]=$f.q[--$f.r];var $b=$f.q[--$f.r],$a=$f.q[--$f.r];$f.q[$f.r++]=$a[$b].apply($a,$g);}",
3783
- [OP_ADD]: "function($f){var $b=$f.q[--$f.r],$a=$f.q[--$f.r];$f.q[$f.r++]=$a+$b;}",
3784
- [OP_SUB]: "function($f){var $b=$f.q[--$f.r],$a=$f.q[--$f.r];$f.q[$f.r++]=$a-$b;}",
3785
- [OP_MUL]: "function($f){var $b=$f.q[--$f.r],$a=$f.q[--$f.r];$f.q[$f.r++]=$a*$b;}",
3786
- [OP_XOR]: "function($f){var $b=$f.q[--$f.r],$a=$f.q[--$f.r];$f.q[$f.r++]=$a^$b;}",
3787
- [OP_AND]: "function($f){var $b=$f.q[--$f.r],$a=$f.q[--$f.r];$f.q[$f.r++]=$a&$b;}",
3788
- [OP_OR]: "function($f){var $b=$f.q[--$f.r],$a=$f.q[--$f.r];$f.q[$f.r++]=$a|$b;}",
3789
- [OP_SEQ]: "function($f){var $b=$f.q[--$f.r],$a=$f.q[--$f.r];$f.q[$f.r++]=$a===$b;}",
3790
- [OP_LT]: "function($f){var $b=$f.q[--$f.r],$a=$f.q[--$f.r];$f.q[$f.r++]=$a<$b;}",
3791
- [OP_NOT]: "function($f){$f.q[$f.r-1]=!$f.q[$f.r-1];}",
3792
- [OP_JMP]: "function($f){var $j=$rd($f),$ts=$f.c[$f.p++]^$f.st;$f.p=$j;$f.st=$ts;}",
3793
- [OP_JZ]: "function($f){var $j=$rd($f),$ts=$f.c[$f.p++]^$f.st;if(!$f.q[--$f.r]){$f.p=$j;$f.st=$ts;}}",
3794
- [OP_RET]: "function($f){$f.d=1;$f.v=$f.q[--$f.r];}",
3795
- [OP_THROW]: "function($f){throw $f.q[--$f.r];}",
3796
- [OP_AWAIT]: "function($f){var $v=$f.q[--$f.r];$f.d=2;$f.v=Promise.resolve($v).then(function($w){$f.d=0;$f.q[$f.r++]=$w;return $x($f);});}",
3797
- [OP_OBJ]: "function($f){var $n=$rd($f),$o={},$e=[];for(var $i=0;$i<$n;$i++){var $v=$f.q[--$f.r],$k0=$f.q[--$f.r];$e.push([$k0,$v]);}for(var $i=$e.length-1;$i>=0;$i--){$o[$e[$i][0]]=$e[$i][1];}$f.q[$f.r++]=$o;}",
3798
- [OP_ARR]: "function($f){var $n=$rd($f),$a=[];for(var $i=$n-1;$i>=0;$i--)$a[$i]=$f.q[--$f.r];$f.q[$f.r++]=$a;}",
3799
- [OP_LDU]: "function($f){$f.q[$f.r++]=$f.u[$rd($f)][0]();}",
3800
- [OP_STU]: "function($f){$f.u[$rd($f)][1]($f.q[--$f.r]);}"
3801
- };
3802
- const handlers = new Array(opCount);
3803
- for (let op = 0; op < opCount; op++) {
3804
- handlers[slotMap[op]] = handlerMap[op];
3805
- }
3806
- const hasSym = Boolean(windowKeySymbol && expectedDelta !== void 0);
3807
- const symPropAccess = hasSym ? /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(windowKeySymbol) ? `.${windowKeySymbol}` : `[${JSON.stringify(windowKeySymbol)}]` : "";
3808
- const dDecl = hasSym ? `var $d=$G${symPropAccess}!=null?$G${symPropAccess}:($W?-1:(($h^$D)&0xffff));` : "";
3809
- const okExpr = hasSym ? `(($h&255)^$A^($d&255))&255` : `(($h&255)^$A)&255`;
3810
- const skExpr = hasSym ? `((($h>>>8)&255)^$B^(($d>>>8)&255))&255` : `((($h>>>8)&255)^$B)&255`;
3811
- const vkExpr = hasSym ? `($h^$C^Math.imul($d|0,0x9e3779b1))|0` : `($h^$C)|0`;
3812
- const paramsList = hasSym ? "$P,$A,$B,$C,$D" : "$P,$A,$B,$C";
3813
- const factoryRaw = `(function $I(${paramsList}){var $G=typeof globalThis<"u"?globalThis:(typeof window<"u"?window:this);${hasSym ? 'var $W=typeof window<"u"||typeof self<"u";' : ""}var $ts=Function.prototype.toString,$s=$ts.call($I);for(var $h=0x811c9dc5,$i=0;$i<$s.length;$i++)$h=Math.imul($h^$s.charCodeAt($i),0x01000193)>>>0;try{$ts.call(0);$h^=1;}catch($e){}var $M,$ok,$sk,$vk,$in=0;function $init(){$in=1;${dDecl}$ok=${okExpr};$sk=${skExpr};$vk=${vkExpr};$M=[];for(var $j=0;$j<$P.length;$j+=2)$M[$P[$j]]=$P[$j+1];}function $rd($f){var $p=$f.p++;var $x0=$f.st=(Math.imul($f.st^($p+1),0x45d9f3b)+0x9e3779b9)|0;var $w=$f.c[$p],$v=$w^(($x0>>>16)&0xffff);$f.st=($f.st^Math.imul($w+1,0x85ebca6b))|0;return $v;}var $H;function $x($f){while($f.p<$f.c.length){var $o=$rd($f),$m=$M[$o^$ok];if($m!==void 0){var $h0=$H[$m^$sk];if($h0)$h0($f);}if($f.d)return $f.v;}}$H=[${handlers.join(
3814
- ","
3815
- )}];return function($c,$k,$s0,$t,$a,$u){if(!$in)$init();return $x({c:$c,k:$k,s:$s0,t:$t,u:$u||[],q:[],r:0,p:0,st:($vk^$a)|0,d:0,v:void 0});};})`;
3816
- const parsedFactory = acorn5.parse(factoryRaw, {
3817
- ecmaVersion: "latest",
3818
- sourceType: "script"
3819
- });
3820
- const factoryExpr = parsedFactory.body[0].expression;
3821
- const compactFactory = generateCompactJs(factoryExpr);
3822
- const buildH = computeFnv1aHash(compactFactory);
3823
- const expD = hasSym ? expectedDelta & 65535 : 0;
3824
- const argA = (opMask ^ buildH & 255 ^ expD & 255) & 255;
3825
- const argB = (slotMask ^ buildH >>> 8 & 255 ^ expD >>> 8 & 255) & 255;
3826
- const argC = vmKey ^ buildH ^ (hasSym ? Math.imul(expD | 0, 2654435761) : 0) | 0;
3827
- const argD = hasSym ? (buildH ^ expD) & 65535 : 0;
3828
- return `var ${vmHelperName}=(${compactFactory})([${pairs.join(",")}],${argA},${argB},${argC}${hasSym ? `,${argD}` : ""});`;
3829
- }
3830
- function countAstNodes(node) {
3831
- let count = 0;
3832
- walk6.full(node, () => {
3833
- count++;
3834
- });
3835
- return count;
3836
- }
3837
- function hasForbiddenConstructs(fnNode) {
3838
- let forbidden = false;
3839
- walk6.full(fnNode, (node) => {
3840
- if (forbidden) return;
3841
- const type = node.type;
3842
- if (type === "JSXElement" || type === "JSXFragment" || type === "Super" || type === "YieldExpression" || type === "WithStatement") {
3843
- forbidden = true;
3844
- return;
3845
- }
3846
- if (type === "Identifier" && (node.name === "arguments" || node.name === "eval")) {
3847
- forbidden = true;
3848
- return;
3849
- }
3850
- if (type === "MetaProperty") {
3851
- forbidden = true;
3852
- return;
3853
- }
3854
- });
3855
- return forbidden;
3856
- }
3857
- var FUNCTION_NODE_TYPES2 = /* @__PURE__ */ new Set([
3858
- "FunctionDeclaration",
3859
- "FunctionExpression",
3860
- "ArrowFunctionExpression"
3861
- ]);
3862
- var LEXICAL_SCOPE_TYPES2 = /* @__PURE__ */ new Set([
3863
- "Program",
3864
- "FunctionDeclaration",
3865
- "FunctionExpression",
3866
- "ArrowFunctionExpression",
3867
- "BlockStatement",
3868
- "ForStatement",
3869
- "ForInStatement",
3870
- "ForOfStatement",
3871
- "SwitchStatement",
3872
- "CatchClause",
3873
- "ClassDeclaration",
3874
- "ClassExpression"
3875
- ]);
3876
- function collectPatternNames(pattern, out) {
3877
- if (!pattern) return;
3878
- switch (pattern.type) {
3879
- case "Identifier":
3880
- out.add(pattern.name);
3881
- break;
3882
- case "AssignmentPattern":
3883
- collectPatternNames(pattern.left, out);
3884
- break;
3885
- case "RestElement":
3886
- collectPatternNames(pattern.argument, out);
3887
- break;
3888
- case "ArrayPattern":
3889
- for (const el of pattern.elements || []) {
3890
- if (el) collectPatternNames(el, out);
3891
- }
3892
- break;
3893
- case "ObjectPattern":
3894
- for (const prop of pattern.properties || []) {
3895
- if (prop.type === "Property") {
3896
- collectPatternNames(prop.value, out);
3897
- } else if (prop.type === "RestElement") {
3898
- collectPatternNames(prop.argument, out);
3899
- }
3900
- }
3901
- break;
3902
- }
3903
- }
3904
- function compileFunctionToBytecode(fnNode, opMap, enclosingBindings) {
3905
- const bytecode = [];
3906
- const consts = [];
3907
- const stateSlots = /* @__PURE__ */ new Set();
3908
- const fnScope = /* @__PURE__ */ new Map();
3909
- const scopeStack = [fnScope];
3910
- const upvalues = [];
3911
- const upvalueMap = /* @__PURE__ */ new Map();
3912
- let localCount = 0;
3913
- for (const param of fnNode.params) {
3914
- if (param.type !== "Identifier") return null;
3915
- if (fnScope.has(param.name)) return null;
3916
- fnScope.set(param.name, localCount++);
3917
- }
3918
- let invalidDecl = false;
3919
- function scanVarDecls(node, isTopBody) {
3920
- if (!node || invalidDecl) return;
3921
- if (Array.isArray(node)) {
3922
- for (const item of node) scanVarDecls(item, isTopBody);
3923
- return;
3924
- }
3925
- if (typeof node !== "object" || !node.type) return;
3926
- if (FUNCTION_NODE_TYPES2.has(node.type)) return;
3927
- if (node.type === "VariableDeclaration") {
3928
- const isVar = node.kind === "var";
3929
- if (isVar || isTopBody) {
3930
- for (const decl of node.declarations || []) {
3931
- if (decl.id?.type !== "Identifier") {
3932
- invalidDecl = true;
3933
- return;
3934
- }
3935
- if (!fnScope.has(decl.id.name)) {
3936
- fnScope.set(decl.id.name, localCount++);
3937
- }
3938
- }
3939
- }
3940
- return;
3941
- }
3942
- if (node.type === "BlockStatement") {
3943
- for (const s of node.body || []) {
3944
- scanVarDecls(s, false);
3945
- }
3946
- return;
3947
- }
3948
- if (node.type === "IfStatement") {
3949
- scanVarDecls(node.consequent, false);
3950
- if (node.alternate) scanVarDecls(node.alternate, false);
3951
- }
3952
- }
3953
- if (fnNode.body.type === "BlockStatement") {
3954
- for (const stmt of fnNode.body.body || []) {
3955
- scanVarDecls(stmt, true);
3956
- if (invalidDecl) return null;
3957
- }
3958
- }
3959
- function resolveLocal(name) {
3960
- for (let i = scopeStack.length - 1; i >= 0; i--) {
3961
- const slot = scopeStack[i].get(name);
3962
- if (slot !== void 0) return slot;
3963
- }
3964
- return void 0;
3965
- }
3966
- function getOrCreateUpvalue(name, isWritten) {
3967
- let idx = upvalueMap.get(name);
3968
- if (idx === void 0) {
3969
- idx = upvalues.length;
3970
- upvalueMap.set(name, idx);
3971
- upvalues.push({ name, isWritten });
3972
- } else if (isWritten) {
3973
- upvalues[idx].isWritten = true;
3974
- }
3975
- return idx;
3976
- }
3977
- function emitLoadVar(name) {
3978
- const localSlot = resolveLocal(name);
3979
- if (localSlot !== void 0) {
3980
- emit(OP_LDV, localSlot);
3981
- return;
3982
- }
3983
- if (enclosingBindings && enclosingBindings.has(name)) {
3984
- emit(OP_LDU, getOrCreateUpvalue(name, false));
3985
- return;
3986
- }
3987
- const idx = addConst(name);
3988
- emit(OP_LDG, idx);
3989
- }
3990
- function canWriteVar(name) {
3991
- if (resolveLocal(name) !== void 0) return true;
3992
- return Boolean(enclosingBindings && enclosingBindings.has(name));
3993
- }
3994
- function emitStoreVar(name) {
3995
- const localSlot = resolveLocal(name);
3996
- if (localSlot !== void 0) {
3997
- emit(OP_STV, localSlot);
3998
- return true;
3999
- }
4000
- if (enclosingBindings && enclosingBindings.has(name)) {
4001
- emit(OP_STU, getOrCreateUpvalue(name, true));
4002
- return true;
4003
- }
4004
- return false;
4005
- }
4006
- function addConst(val) {
4007
- for (let i = 0; i < consts.length; i++) {
4008
- if (Object.is(consts[i], val)) return i;
4009
- }
4010
- const idx = consts.length;
4011
- consts.push(val);
4012
- return idx;
4013
- }
4014
- function emit(op, ...args) {
4015
- bytecode.push(opMap[op]);
4016
- for (const a of args) bytecode.push(a);
4017
- }
4018
- function compileExpr(node, inValuePos = true) {
4019
- if (!node) return false;
4020
- switch (node.type) {
4021
- case "Literal": {
4022
- if (node.regex || typeof node.value === "bigint") return false;
4023
- const idx = addConst(node.value);
4024
- emit(OP_LDC, idx);
4025
- return true;
4026
- }
4027
- case "Identifier": {
4028
- if (node.name === "undefined") {
4029
- const localSlot = resolveLocal("undefined");
4030
- if (localSlot !== void 0) {
4031
- emit(OP_LDV, localSlot);
4032
- } else if (enclosingBindings && enclosingBindings.has("undefined")) {
4033
- emit(OP_LDU, getOrCreateUpvalue("undefined", false));
4034
- } else {
4035
- const idx = addConst(void 0);
4036
- emit(OP_LDC, idx);
4037
- }
4038
- return true;
4039
- }
4040
- emitLoadVar(node.name);
4041
- return true;
4042
- }
4043
- case "BinaryExpression": {
4044
- if (node.operator === ">") {
4045
- if (!compileExpr(node.right, true)) return false;
4046
- if (!compileExpr(node.left, true)) return false;
4047
- emit(OP_LT);
4048
- return true;
4049
- }
4050
- if (node.operator === "<=") {
4051
- if (!compileExpr(node.right, true)) return false;
4052
- if (!compileExpr(node.left, true)) return false;
4053
- emit(OP_LT);
4054
- emit(OP_NOT);
4055
- return true;
4056
- }
4057
- if (node.operator === ">=") {
4058
- if (!compileExpr(node.left, true)) return false;
4059
- if (!compileExpr(node.right, true)) return false;
4060
- emit(OP_LT);
4061
- emit(OP_NOT);
4062
- return true;
4063
- }
4064
- if (!compileExpr(node.left, true)) return false;
4065
- if (!compileExpr(node.right, true)) return false;
4066
- switch (node.operator) {
4067
- case "+":
4068
- emit(OP_ADD);
4069
- break;
4070
- case "-":
4071
- emit(OP_SUB);
4072
- break;
4073
- case "*":
4074
- emit(OP_MUL);
4075
- break;
4076
- case "^":
4077
- emit(OP_XOR);
4078
- break;
4079
- case "&":
4080
- emit(OP_AND);
4081
- break;
4082
- case "|":
4083
- emit(OP_OR);
4084
- break;
4085
- case "==":
4086
- case "===":
4087
- emit(OP_SEQ);
4088
- break;
4089
- case "!=":
4090
- case "!==":
4091
- emit(OP_SEQ);
4092
- emit(OP_NOT);
4093
- break;
4094
- case "<":
4095
- emit(OP_LT);
4096
- break;
4097
- default:
4098
- return false;
4099
- }
4100
- return true;
4101
- }
4102
- case "UnaryExpression": {
4103
- if (node.operator === "void") {
4104
- if (node.argument?.type !== "Literal" || node.argument.regex) return false;
4105
- const undefIdx2 = addConst(void 0);
4106
- emit(OP_LDC, undefIdx2);
4107
- return true;
4108
- }
4109
- if (!compileExpr(node.argument, true)) return false;
4110
- switch (node.operator) {
4111
- case "!":
4112
- emit(OP_NOT);
4113
- break;
4114
- case "-": {
4115
- const neg1Idx = addConst(-1);
4116
- emit(OP_LDC, neg1Idx);
4117
- emit(OP_MUL);
4118
- break;
4119
- }
4120
- case "+": {
4121
- const zeroIdx = addConst(0);
4122
- emit(OP_LDC, zeroIdx);
4123
- emit(OP_ADD);
4124
- break;
4125
- }
4126
- case "~": {
4127
- const neg1Idx = addConst(-1);
4128
- emit(OP_LDC, neg1Idx);
4129
- emit(OP_XOR);
4130
- break;
4131
- }
4132
- default:
4133
- return false;
4134
- }
4135
- return true;
4136
- }
4137
- case "MemberExpression": {
4138
- if (node.optional) return false;
4139
- if (!compileExpr(node.object, true)) return false;
4140
- if (node.computed) {
4141
- if (!compileExpr(node.property, true)) return false;
4142
- } else {
4143
- if (node.property?.type !== "Identifier") return false;
4144
- const idx = addConst(node.property.name);
4145
- emit(OP_LDC, idx);
4146
- }
4147
- emit(OP_GETP);
4148
- return true;
4149
- }
4150
- case "CallExpression": {
4151
- if (node.optional) return false;
4152
- if (node.callee.type === "MemberExpression") {
4153
- if (node.callee.optional) return false;
4154
- if (!compileExpr(node.callee.object, true)) return false;
4155
- if (node.callee.computed) {
4156
- if (!compileExpr(node.callee.property, true)) return false;
4157
- } else {
4158
- if (node.callee.property?.type !== "Identifier") return false;
4159
- const idx = addConst(node.callee.property.name);
4160
- emit(OP_LDC, idx);
4161
- }
4162
- for (const arg of node.arguments) {
4163
- if (!compileExpr(arg, true)) return false;
4164
- }
4165
- emit(OP_MCALL, node.arguments.length);
4166
- } else {
4167
- if (!compileExpr(node.callee, true)) return false;
4168
- for (const arg of node.arguments) {
4169
- if (!compileExpr(arg, true)) return false;
4170
- }
4171
- emit(OP_CALL, node.arguments.length);
4172
- }
4173
- return true;
4174
- }
4175
- case "AssignmentExpression": {
4176
- if (node.left.type === "Identifier") {
4177
- const name = node.left.name;
4178
- if (!canWriteVar(name)) return false;
4179
- if (node.operator === "=") {
4180
- if (!compileExpr(node.right, true)) return false;
4181
- } else {
4182
- let binOp = null;
4183
- switch (node.operator) {
4184
- case "+=":
4185
- binOp = OP_ADD;
4186
- break;
4187
- case "-=":
4188
- binOp = OP_SUB;
4189
- break;
4190
- case "*=":
4191
- binOp = OP_MUL;
4192
- break;
4193
- case "^=":
4194
- binOp = OP_XOR;
4195
- break;
4196
- case "&=":
4197
- binOp = OP_AND;
4198
- break;
4199
- case "|=":
4200
- binOp = OP_OR;
4201
- break;
4202
- default:
4203
- return false;
4204
- }
4205
- emitLoadVar(name);
4206
- if (!compileExpr(node.right, true)) return false;
4207
- emit(binOp);
4208
- }
4209
- if (!emitStoreVar(name)) return false;
4210
- if (inValuePos) {
4211
- emitLoadVar(name);
4212
- }
4213
- return true;
4214
- }
4215
- if (node.left.type === "MemberExpression") {
4216
- if (node.operator !== "=" || node.left.optional) return false;
4217
- if (!compileExpr(node.left.object, true)) return false;
4218
- if (node.left.computed) {
4219
- if (!compileExpr(node.left.property, true)) return false;
4220
- } else {
4221
- if (node.left.property?.type !== "Identifier") return false;
4222
- const idx = addConst(node.left.property.name);
4223
- emit(OP_LDC, idx);
4224
- }
4225
- if (!compileExpr(node.right, true)) return false;
4226
- emit(OP_SETP);
4227
- return true;
4228
- }
4229
- return false;
4230
- }
4231
- case "UpdateExpression": {
4232
- if (node.argument?.type !== "Identifier") return false;
4233
- const name = node.argument.name;
4234
- if (!canWriteVar(name)) return false;
4235
- const oneIdx = addConst(1);
4236
- const stepOp = node.operator === "++" ? OP_ADD : OP_SUB;
4237
- if (node.prefix) {
4238
- emitLoadVar(name);
4239
- emit(OP_LDC, oneIdx);
4240
- emit(OP_MUL);
4241
- emit(OP_LDC, oneIdx);
4242
- emit(stepOp);
4243
- if (!emitStoreVar(name)) return false;
4244
- if (inValuePos) {
4245
- emitLoadVar(name);
4246
- }
4247
- } else {
4248
- if (inValuePos) {
4249
- emitLoadVar(name);
4250
- emit(OP_LDC, oneIdx);
4251
- emit(OP_MUL);
4252
- }
4253
- emitLoadVar(name);
4254
- emit(OP_LDC, oneIdx);
4255
- emit(OP_MUL);
4256
- emit(OP_LDC, oneIdx);
4257
- emit(stepOp);
4258
- if (!emitStoreVar(name)) return false;
4259
- }
4260
- return true;
4261
- }
4262
- case "ObjectExpression": {
4263
- for (const prop of node.properties) {
4264
- if (prop.type !== "Property" || prop.kind !== "init") return false;
4265
- if (prop.computed) {
4266
- if (!compileExpr(prop.key, true)) return false;
4267
- } else {
4268
- const keyName = prop.key?.name ?? prop.key?.value;
4269
- if (keyName === void 0) return false;
4270
- const idx = addConst(keyName);
4271
- emit(OP_LDC, idx);
4272
- }
4273
- if (!compileExpr(prop.value, true)) return false;
4274
- }
4275
- emit(OP_OBJ, node.properties.length);
4276
- return true;
4277
- }
4278
- case "ArrayExpression": {
4279
- for (const elem of node.elements) {
4280
- if (!elem || !compileExpr(elem, true)) return false;
4281
- }
4282
- emit(OP_ARR, node.elements.length);
4283
- return true;
4284
- }
4285
- case "AwaitExpression": {
4286
- if (!compileExpr(node.argument, true)) return false;
4287
- emit(OP_AWAIT);
4288
- return true;
4289
- }
4290
- default:
4291
- return false;
4292
- }
4293
- }
4294
- function compileStmt(stmt, isFnBody = false) {
4295
- if (!stmt) return false;
4296
- switch (stmt.type) {
4297
- case "ReturnStatement": {
4298
- if (stmt.argument) {
4299
- if (!compileExpr(stmt.argument, true)) return false;
4300
- } else {
4301
- const idx = addConst(void 0);
4302
- emit(OP_LDC, idx);
4303
- }
4304
- emit(OP_RET);
4305
- return true;
4306
- }
4307
- case "ExpressionStatement": {
4308
- if (!compileExpr(stmt.expression, false)) return false;
4309
- return true;
4310
- }
4311
- case "VariableDeclaration": {
4312
- for (const decl of stmt.declarations) {
4313
- if (decl.id?.type !== "Identifier") return false;
4314
- const slot = resolveLocal(decl.id.name);
4315
- if (slot === void 0) return false;
4316
- if (decl.init) {
4317
- if (!compileExpr(decl.init, true)) return false;
4318
- emit(OP_STV, slot);
4319
- }
4320
- }
4321
- return true;
4322
- }
4323
- case "IfStatement": {
4324
- if (!compileExpr(stmt.test, true)) return false;
4325
- const jzPos = bytecode.length;
4326
- emit(OP_JZ, 0, 0);
4327
- stateSlots.add(jzPos + 2);
4328
- if (!compileStmt(stmt.consequent, false)) return false;
4329
- if (stmt.alternate) {
4330
- const jmpPos = bytecode.length;
4331
- emit(OP_JMP, 0, 0);
4332
- stateSlots.add(jmpPos + 2);
4333
- bytecode[jzPos + 1] = bytecode.length;
4334
- if (!compileStmt(stmt.alternate, false)) return false;
4335
- bytecode[jmpPos + 1] = bytecode.length;
4336
- } else {
4337
- bytecode[jzPos + 1] = bytecode.length;
4338
- }
4339
- return true;
4340
- }
4341
- case "BlockStatement": {
4342
- let pushedBlock = false;
4343
- if (!isFnBody) {
4344
- const blockScope = /* @__PURE__ */ new Map();
4345
- for (const s of stmt.body || []) {
4346
- if (s.type === "VariableDeclaration" && s.kind !== "var") {
4347
- for (const decl of s.declarations || []) {
4348
- if (decl.id?.type !== "Identifier") return false;
4349
- if (!blockScope.has(decl.id.name)) {
4350
- blockScope.set(decl.id.name, localCount++);
4351
- }
4352
- }
4353
- }
4354
- }
4355
- if (blockScope.size > 0) {
4356
- scopeStack.push(blockScope);
4357
- pushedBlock = true;
4358
- }
4359
- }
4360
- for (const s of stmt.body) {
4361
- if (!compileStmt(s, false)) {
4362
- if (pushedBlock) scopeStack.pop();
4363
- return false;
4364
- }
4365
- }
4366
- if (pushedBlock) scopeStack.pop();
4367
- return true;
4368
- }
4369
- default:
4370
- return false;
4371
- }
4372
- }
4373
- if (fnNode.body.type === "BlockStatement") {
4374
- if (!compileStmt(fnNode.body, true)) return null;
4375
- } else {
4376
- if (!compileExpr(fnNode.body, true)) return null;
4377
- emit(OP_RET);
4378
- }
4379
- const undefIdx = addConst(void 0);
4380
- emit(OP_LDC, undefIdx);
4381
- emit(OP_RET);
4382
- return { bytecode, consts, localCount, stateSlots, upvalues };
4383
- }
4384
- function findInjectedVmHelperName(ast) {
4385
- if (!ast || !Array.isArray(ast.body)) return null;
4386
- for (const stmt of ast.body) {
4387
- if (stmt.type === "FunctionDeclaration" && typeof stmt.id?.name === "string" && stmt.id.name.startsWith("_uVm")) {
4388
- return stmt.id.name;
4389
- }
4390
- if (stmt.type === "VariableDeclaration" && Array.isArray(stmt.declarations)) {
4391
- for (const d of stmt.declarations) {
4392
- if (d.id?.type === "Identifier" && typeof d.id.name === "string" && d.id.name.startsWith("_uVm")) {
4393
- return d.id.name;
4394
- }
4395
- }
4396
- }
4397
- }
4398
- return null;
4399
- }
4400
- function applyMicroVm(ast, coldFunctionNodes, serializedFunctionNodes, seed = 2654435769, windowKeySymbol, expectedDelta) {
4401
- const suffix = computeFnv1aHash(`micro-vm:${seed}`, seed).toString(36);
4402
- const vmHelperName = `_uVm${suffix}`;
4403
- const existingName = findInjectedVmHelperName(ast);
4404
- if (existingName) {
4405
- return {
4406
- virtualizedCount: 0,
4407
- vmHelperName: existingName
4408
- };
4409
- }
4410
- const opMap = generateOpcodeMap(seed, OPCODE_COUNT);
4411
- const vmKey = deriveVmKey(seed);
4412
- const scopeBindings = /* @__PURE__ */ new Map();
4413
- function addScopeBinding(scopeNode, name) {
4414
- if (!scopeNode || !name) return;
4415
- let set = scopeBindings.get(scopeNode);
4416
- if (!set) {
4417
- set = /* @__PURE__ */ new Set();
4418
- scopeBindings.set(scopeNode, set);
4419
- }
4420
- set.add(name);
4421
- }
4422
- function findNearestFunctionOrProgram(ancestors) {
4423
- for (let i = ancestors.length - 1; i >= 0; i--) {
4424
- if (FUNCTION_NODE_TYPES2.has(ancestors[i].type) || ancestors[i].type === "Program") {
4425
- return ancestors[i];
4426
- }
4427
- }
4428
- return ast;
4429
- }
4430
- function findNearestLexicalScope(ancestors) {
4431
- for (let i = ancestors.length - 1; i >= 0; i--) {
4432
- if (LEXICAL_SCOPE_TYPES2.has(ancestors[i].type)) {
4433
- return ancestors[i];
4434
- }
4435
- }
4436
- return ast;
4437
- }
4438
- const candidates = [];
4439
- walk6.ancestor(ast, {
4440
- ImportDeclaration(node) {
4441
- for (const spec of node.specifiers || []) {
4442
- if (spec.local?.type === "Identifier") {
4443
- addScopeBinding(ast, spec.local.name);
4444
- }
4445
- }
4446
- },
4447
- VariableDeclaration(node, _state, ancestors) {
4448
- const targetScope = node.kind === "var" ? findNearestFunctionOrProgram(ancestors) : findNearestLexicalScope(ancestors);
4449
- const names = /* @__PURE__ */ new Set();
4450
- for (const decl of node.declarations || []) {
4451
- collectPatternNames(decl.id, names);
4452
- }
4453
- for (const name of names) {
4454
- addScopeBinding(targetScope, name);
4455
- }
4456
- },
4457
- FunctionDeclaration(node, _state, ancestors) {
4458
- const parentAncestors = ancestors.slice(0, -1);
4459
- if (node.id?.type === "Identifier") {
4460
- addScopeBinding(findNearestLexicalScope(parentAncestors), node.id.name);
4461
- addScopeBinding(findNearestFunctionOrProgram(parentAncestors), node.id.name);
4462
- }
4463
- const paramNames = /* @__PURE__ */ new Set();
4464
- for (const p of node.params || []) {
4465
- collectPatternNames(p, paramNames);
4466
- }
4467
- for (const name of paramNames) {
4468
- addScopeBinding(node, name);
4469
- }
4470
- candidates.push({ fn: node, ancestors: ancestors.slice() });
4471
- },
4472
- FunctionExpression(node, _state, ancestors) {
4473
- if (node.id?.type === "Identifier") {
4474
- addScopeBinding(node, node.id.name);
4475
- }
4476
- const paramNames = /* @__PURE__ */ new Set();
4477
- for (const p of node.params || []) {
4478
- collectPatternNames(p, paramNames);
4479
- }
4480
- for (const name of paramNames) {
4481
- addScopeBinding(node, name);
4482
- }
4483
- candidates.push({ fn: node, ancestors: ancestors.slice() });
4484
- },
4485
- ArrowFunctionExpression(node, _state, ancestors) {
4486
- const paramNames = /* @__PURE__ */ new Set();
4487
- for (const p of node.params || []) {
4488
- collectPatternNames(p, paramNames);
4489
- }
4490
- for (const name of paramNames) {
4491
- addScopeBinding(node, name);
4492
- }
4493
- candidates.push({ fn: node, ancestors: ancestors.slice() });
4494
- },
4495
- ClassDeclaration(node, _state, ancestors) {
4496
- if (node.id?.type === "Identifier") {
4497
- addScopeBinding(findNearestLexicalScope(ancestors.slice(0, -1)), node.id.name);
4498
- addScopeBinding(node, node.id.name);
4499
- }
4500
- },
4501
- ClassExpression(node) {
4502
- if (node.id?.type === "Identifier") {
4503
- addScopeBinding(node, node.id.name);
4504
- }
4505
- },
4506
- CatchClause(node) {
4507
- if (node.param) {
4508
- const names = /* @__PURE__ */ new Set();
4509
- collectPatternNames(node.param, names);
4510
- for (const name of names) {
4511
- addScopeBinding(node, name);
4512
- }
4513
- }
4514
- }
4515
- });
4516
- let virtualizedCount = 0;
4517
- for (const { fn, ancestors } of candidates) {
4518
- if (virtualizedCount >= 5) break;
4519
- if (coldFunctionNodes && !coldFunctionNodes.has(fn)) {
4520
- continue;
4521
- }
4522
- if (serializedFunctionNodes && serializedFunctionNodes.has(fn)) {
4523
- continue;
4524
- }
4525
- if (fn.generator) {
4526
- continue;
4527
- }
4528
- const parentNode = ancestors.length >= 2 ? ancestors[ancestors.length - 2] : null;
4529
- if (parentNode?.type === "MethodDefinition" && parentNode.kind === "constructor") {
4530
- continue;
4531
- }
4532
- if (ancestors.some((a) => a.type === "WithStatement")) {
4533
- continue;
4534
- }
4535
- if (hasForbiddenConstructs(fn)) {
4536
- continue;
4537
- }
4538
- const nodeCount = countAstNodes(fn);
4539
- if (nodeCount < 15 || nodeCount > 80) {
4540
- continue;
4541
- }
4542
- const enclosingBindings = /* @__PURE__ */ new Set();
4543
- for (let i = 0; i < ancestors.length - 1; i++) {
4544
- const bound = scopeBindings.get(ancestors[i]);
4545
- if (bound) {
4546
- for (const name of bound) {
4547
- enclosingBindings.add(name);
4548
- }
4549
- }
4550
- }
4551
- if (fn.type === "FunctionExpression" && fn.id?.type === "Identifier") {
4552
- enclosingBindings.add(fn.id.name);
4553
- }
4554
- const compiled = compileFunctionToBytecode(fn, opMap, enclosingBindings);
4555
- if (!compiled) {
4556
- continue;
4557
- }
4558
- const fnSalt = computeFnv1aHash(`vm-fn:${virtualizedCount}`, seed) >>> 0;
4559
- const encBytecode = encryptBytecodeStream(
4560
- compiled.bytecode,
4561
- fnSalt,
4562
- vmKey,
4563
- compiled.stateSlots
4564
- );
4565
- const paramArgs = fn.params.map((p) => ({
4566
- type: "Identifier",
4567
- name: p.name
4568
- }));
4569
- const constElements = compiled.consts.map((c) => {
4570
- if (c === void 0) {
4571
- return {
4572
- type: "UnaryExpression",
4573
- operator: "void",
4574
- prefix: true,
4575
- argument: { type: "Literal", value: 0, raw: "0" }
4576
- };
4577
- }
4578
- return {
4579
- type: "Literal",
4580
- value: c,
4581
- raw: JSON.stringify(c)
4582
- };
4583
- });
4584
- const callArgs = [
4585
- {
4586
- type: "ArrayExpression",
4587
- elements: encBytecode.map((b) => ({
4588
- type: "Literal",
4589
- value: b >>> 0,
4590
- raw: String(b >>> 0)
4591
- }))
4592
- },
4593
- {
4594
- type: "ArrayExpression",
4595
- elements: constElements
4596
- },
4597
- {
4598
- type: "ArrayExpression",
4599
- elements: paramArgs
4600
- },
4601
- {
4602
- type: "ThisExpression"
4603
- },
4604
- {
4605
- type: "Literal",
4606
- value: fnSalt,
4607
- raw: String(fnSalt)
4608
- }
4609
- ];
4610
- if (compiled.upvalues && compiled.upvalues.length > 0) {
4611
- const usedParamNames = new Set(enclosingBindings);
4612
- const upvalueElements = compiled.upvalues.map((uv, uIdx) => {
4613
- const getterFn = {
4614
- type: "ArrowFunctionExpression",
4615
- id: null,
4616
- params: [],
4617
- body: { type: "Identifier", name: uv.name },
4618
- generator: false,
4619
- async: false,
4620
- expression: true
4621
- };
4622
- if (!uv.isWritten) {
4623
- return {
4624
- type: "ArrayExpression",
4625
- elements: [getterFn]
4626
- };
4627
- }
4628
- let paramName = `_uv${uIdx}`;
4629
- let suffixIdx = 0;
4630
- while (usedParamNames.has(paramName) || paramName === uv.name) {
4631
- paramName = `_uv${uIdx}_${suffixIdx++}`;
4632
- }
4633
- usedParamNames.add(paramName);
4634
- const setterFn = {
4635
- type: "ArrowFunctionExpression",
4636
- id: null,
4637
- params: [{ type: "Identifier", name: paramName }],
4638
- body: {
4639
- type: "AssignmentExpression",
4640
- operator: "=",
4641
- left: { type: "Identifier", name: uv.name },
4642
- right: { type: "Identifier", name: paramName }
4643
- },
4644
- generator: false,
4645
- async: false,
4646
- expression: true
4647
- };
4648
- return {
4649
- type: "ArrayExpression",
4650
- elements: [getterFn, setterFn]
4651
- };
4652
- });
4653
- callArgs.push({
4654
- type: "ArrayExpression",
4655
- elements: upvalueElements
4656
- });
4657
- }
4658
- const callExpr = {
4659
- type: "CallExpression",
4660
- callee: {
4661
- type: "Identifier",
4662
- name: vmHelperName
4663
- },
4664
- arguments: callArgs,
4665
- optional: false
4666
- };
4667
- if (fn.body.type === "BlockStatement") {
4668
- fn.body.body = [
4669
- {
4670
- type: "ReturnStatement",
4671
- argument: callExpr
4672
- }
4673
- ];
4674
- } else {
4675
- fn.body = callExpr;
4676
- }
4677
- virtualizedCount++;
4678
- }
4679
- if (virtualizedCount > 0) {
4680
- const interpreterSource = createInterpreterSource(
4681
- vmHelperName,
4682
- opMap,
4683
- seed,
4684
- windowKeySymbol,
4685
- expectedDelta
4686
- );
4687
- const parsedHelper = acorn5.parse(interpreterSource, {
4688
- ecmaVersion: "latest",
4689
- sourceType: "script"
4690
- });
4691
- let insertIdx = 0;
4692
- while (insertIdx < ast.body.length) {
4693
- const stmt = ast.body[insertIdx];
4694
- const isDirective = stmt.type === "ExpressionStatement" && (Boolean(stmt.directive) || stmt.expression?.type === "Literal" && typeof stmt.expression.value === "string" && /^(?:use\s+[a-zA-Z0-9_-]+)/.test(stmt.expression.value.trim()));
4695
- if (isDirective || stmt.type === "ImportDeclaration") {
4696
- insertIdx++;
4697
- } else {
4698
- break;
4699
- }
4700
- }
4701
- ast.body.splice(insertIdx, 0, ...parsedHelper.body);
4702
- }
4703
- return {
4704
- virtualizedCount,
4705
- vmHelperName
4706
- };
4707
- }
4708
-
4709
- // src/ast/index.ts
4710
- function isAstAlreadyProtected(ast) {
4711
- if (!ast || !Array.isArray(ast.body)) return false;
4712
- return ast.body.some((stmt) => {
4713
- if (stmt.type === "VariableDeclaration" && Array.isArray(stmt.declarations)) {
4714
- for (const d of stmt.declarations) {
4715
- const name = d.id?.name;
4716
- if (typeof name === "string") {
4717
- 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") {
4718
- return true;
4719
- }
4720
- }
4721
- }
4722
- }
4723
- if (stmt.type === "ExpressionStatement" && stmt.expression?.type === "CallExpression") {
4724
- const callee = stmt.expression.callee;
4725
- if (callee?.type === "FunctionExpression") {
4726
- const name = callee.id?.name;
4727
- if (typeof name === "string" && (name.startsWith("_u$") || name.startsWith("_$") || name.startsWith("_s") || name.startsWith("$b"))) {
4728
- return true;
4729
- }
4730
- }
4731
- }
4732
- return false;
4733
- });
4734
- }
4735
- function transformJavaScript(code, options = {}) {
4736
- const seed = options.seed ?? 2654435769;
4737
- const minStringLength = options.minStringLength ?? options.config?.vault?.minStringLength ?? 4;
4738
- const isAggressive = options.aggressive ?? false;
4739
- if (!code || !code.trim()) {
4740
- return {
4741
- code,
4742
- encryptedStringsCount: 0,
4743
- mangledSymbolsCount: 0,
4744
- hotPathReport: {
4745
- totalFunctions: 0,
4746
- hotFunctionsSkipped: [],
4747
- coldFunctionsProtected: []
4748
- },
4749
- integrityToken: computeFnv1aHash("", seed),
4750
- virtualizedFunctionsCount: 0,
4751
- shaderBuffersCount: 0
4752
- };
4753
- }
4754
- const ast = parseJavaScriptAst(code);
4755
- if (!ast || isAstAlreadyProtected(ast)) {
4756
- return {
4757
- code,
4758
- encryptedStringsCount: 0,
4759
- mangledSymbolsCount: 0,
4760
- hotPathReport: {
4761
- totalFunctions: 0,
4762
- hotFunctionsSkipped: [],
4763
- coldFunctionsProtected: []
4764
- },
4765
- integrityToken: computeFnv1aHash(code, seed),
4766
- virtualizedFunctionsCount: 0,
4767
- shaderBuffersCount: 0
4768
- };
4769
- }
4770
- const {
4771
- report: hotPathReport,
4772
- coldFunctionNodes,
4773
- hotFunctionNodes,
4774
- hotExemptNodes,
4775
- serializedFunctionNodes
4776
- } = analyzeAstHotPaths(ast, options.config);
4777
- const shieldCoupled = options.shieldCoupled ?? Boolean(options.injectRuntimeShield);
4778
- const deterrentMode = options.deterrentMode ?? options.config?.shield?.deterrentMode ?? "passive";
4779
- const detectHeadless = options.detectHeadless ?? options.config?.shield?.detectHeadless ?? false;
4780
- const sym = shieldCoupled ? options.windowKeySymbol ?? deriveWindowKeySymbol(seed) : void 0;
4781
- let shieldDelta = shieldCoupled ? options.expectedDelta : void 0;
4782
- if (shieldCoupled && shieldDelta === void 0) {
4783
- const shieldInfo = generateRuntimeShield({
4784
- seed,
4785
- windowKeySymbol: sym,
4786
- deterrentMode,
4787
- detectHeadless
4788
- });
4789
- shieldDelta = shieldInfo.expectedDelta ?? 0;
4790
- }
4791
- let virtualizedFunctionsCount = 0;
4792
- if (isAggressive) {
4793
- const vmRes = applyMicroVm(
4794
- ast,
4795
- coldFunctionNodes,
4796
- serializedFunctionNodes,
4797
- seed,
4798
- sym,
4799
- shieldDelta
4800
- );
4801
- virtualizedFunctionsCount = vmRes.virtualizedCount;
4802
- }
4803
- applyColdFlowGuard(ast, coldFunctionNodes, seed, hotExemptNodes);
4804
- const mangledSymbolsCount = applyPolymorphicMangler(
4805
- ast,
4806
- seed,
4807
- serializedFunctionNodes,
4808
- options.config
4809
- );
4810
- let encryptedStringsCount = 0;
4811
- let integrityToken = 0;
4812
- let shaderBuffersCount = 0;
4813
- if (isAggressive) {
4814
- const saltedRes = applySaltedStringVault(
4815
- ast,
4816
- seed,
4817
- minStringLength,
4818
- hotExemptNodes,
4819
- options.config,
4820
- sym,
4821
- shieldDelta,
4822
- deterrentMode,
4823
- shieldCoupled,
4824
- detectHeadless
4825
- );
4826
- encryptedStringsCount = saltedRes.encryptedStringsCount;
4827
- integrityToken = saltedRes.integrityToken;
4828
- } else {
4829
- const vaultRes = applyStringVault(
4830
- ast,
4831
- seed,
4832
- minStringLength,
4833
- hotExemptNodes,
4834
- sym,
4835
- shieldDelta,
4836
- deterrentMode,
4837
- options.config,
4838
- shieldCoupled,
4839
- detectHeadless
4840
- );
4841
- encryptedStringsCount = vaultRes.encryptedStringsCount;
4842
- integrityToken = vaultRes.integrityToken;
4843
- shaderBuffersCount = vaultRes.shaderBuffersCount ?? 0;
4844
- }
4845
- const outputCode = generateCompactJs(ast);
4846
- let finalCode = outputCode;
4847
- if (options.injectRuntimeShield && !options.skipShieldPreamble) {
4848
- const shield = generateRuntimeShield({
4849
- seed,
4850
- windowKeySymbol: sym,
4851
- expectedDelta: shieldDelta,
4852
- deterrentMode,
4853
- detectHeadless,
4854
- expectedIntegrityHash: integrityToken
4855
- });
4856
- if (shield.preambleCode) {
4857
- finalCode = `${shield.preambleCode}
4858
- ${finalCode}`;
4859
- }
4860
- }
4861
- return {
4862
- code: finalCode,
4863
- encryptedStringsCount,
4864
- mangledSymbolsCount,
4865
- hotPathReport,
4866
- integrityToken,
4867
- virtualizedFunctionsCount,
4868
- shaderBuffersCount
4869
- };
4870
- }
4871
-
4872
- // src/bundler/unplugin.ts
4873
- var ENTRY_CHUNK_PATTERN = /(?:^|\/)(?:webpack|main|index|runtime|turbopack|pages\/_app|pages\/index)(?:[-._/]|$)/i;
4874
- var unpeekPlugin = createUnplugin((options = {}) => {
4875
- const config = options.config ?? ("framework" in options || "target" in options || "vault" in options || "hotPath" in options || "mangler" in options || "shield" in options || "sourcemaps" in options ? options : void 0);
4876
- const baseSeed = typeof options.seed === "number" ? options.seed : Math.floor(Math.random() * 2147483647) || 322420463;
4877
- const deterrentMode = options.deterrentMode ?? config?.shield?.deterrentMode ?? "passive";
4878
- const detectHeadless = options.detectHeadless ?? config?.shield?.detectHeadless ?? false;
4879
- const injectRuntimeShield = options.injectRuntimeShield ?? true;
4880
- const minStringLength = options.minStringLength ?? config?.vault?.minStringLength ?? 4;
4881
- const aggressive = options.aggressive ?? false;
4882
- const masterSym = deriveWindowKeySymbol(baseSeed);
4883
- const masterShield = injectRuntimeShield ? generateRuntimeShield({
4884
- seed: baseSeed,
4885
- deterrentMode,
4886
- detectHeadless,
4887
- windowKeySymbol: masterSym
4888
- }) : void 0;
4889
- return {
4890
- name: "unpeek",
4891
- enforce: "post",
4892
- renderChunk(code, chunk) {
4893
- const normalizedFileName = chunk.fileName.replace(/\\/g, "/");
4894
- if (!normalizedFileName.endsWith(".js") && !normalizedFileName.endsWith(".mjs") && !normalizedFileName.endsWith(".cjs")) {
4895
- return null;
4896
- }
4897
- if (normalizedFileName.includes("server/") || normalizedFileName.includes("ssr/") || normalizedFileName.includes("node_modules/")) {
4898
- return null;
4899
- }
4900
- const isEntry = chunk.isEntry !== void 0 ? chunk.isEntry : ENTRY_CHUNK_PATTERN.test(normalizedFileName);
4901
- const shouldInjectShield = injectRuntimeShield && isEntry;
4902
- const chunkSeed = computeFnv1aHash(chunk.fileName, baseSeed);
4903
- const result = transformJavaScript(code, {
4904
- seed: chunkSeed,
4905
- minStringLength,
4906
- filename: chunk.fileName,
4907
- injectRuntimeShield: shouldInjectShield,
4908
- skipShieldPreamble: true,
4909
- shieldCoupled: injectRuntimeShield,
4910
- windowKeySymbol: masterSym,
4911
- expectedDelta: masterShield?.expectedDelta,
4912
- deterrentMode,
4913
- detectHeadless,
4914
- aggressive,
4915
- config
4916
- });
4917
- let finalCode = result.code;
4918
- if (shouldInjectShield && masterShield?.preambleCode && !finalCode.includes("__unpeek_tampered") && !finalCode.includes("(function _u$") && !finalCode.includes(masterShield.integrityCheckFnName) && !finalCode.startsWith(masterShield.preambleCode)) {
4919
- finalCode = `${masterShield.preambleCode}
4920
- ${finalCode}`;
4921
- }
4922
- return {
4923
- code: finalCode,
4924
- map: null
4925
- };
4926
- }
4927
- };
4928
- });
4929
- var vitePlugin = unpeekPlugin.vite;
4930
- var webpackPlugin = unpeekPlugin.webpack;
4931
- var rollupPlugin = unpeekPlugin.rollup;
4932
- var esbuildPlugin = unpeekPlugin.esbuild;
1
+ import {
2
+ rollupPlugin
3
+ } from "./chunk-X5MKMFMX.js";
4
+ import "./chunk-UMPUYLLZ.js";
5
+ import "./chunk-KQWNFKT2.js";
6
+ import "./chunk-S4S2WXGC.js";
7
+ import "./chunk-OOXSZTRV.js";
4933
8
 
4934
9
  // src/rollup.ts
4935
10
  var rollup_default = rollupPlugin;
4936
11
  export {
4937
- rollup_default as default,
4938
- rollupPlugin
12
+ rollup_default as default
4939
13
  };
4940
- //# sourceMappingURL=rollup.js.map