unpeek 1.6.0 → 1.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -128,15 +128,100 @@ function analyzeAstHotPaths(ast) {
128
128
  const coldFunctionNodes = /* @__PURE__ */ new WeakSet();
129
129
  const hotExemptNodes = /* @__PURE__ */ new WeakSet();
130
130
  const directHotNodes = /* @__PURE__ */ new Set();
131
+ const serializedFunctionNodes = /* @__PURE__ */ new Set();
132
+ const serializerHelperNodes = /* @__PURE__ */ new Set();
131
133
  const allFunctions = [];
132
134
  const fnByName = /* @__PURE__ */ new Map();
133
135
  const scopeFunctions = /* @__PURE__ */ new Map();
134
136
  const fnScopeChain = /* @__PURE__ */ new Map();
137
+ const fnParams = /* @__PURE__ */ new Map();
138
+ const fnVarAliases = /* @__PURE__ */ new Map();
135
139
  const callerToCallees = /* @__PURE__ */ new Map();
140
+ const pendingSerializedRefs = [];
141
+ const allCallSites = [];
142
+ function ensureFnParams(fnNode) {
143
+ let paramSet = fnParams.get(fnNode);
144
+ if (!paramSet) {
145
+ paramSet = /* @__PURE__ */ new Set();
146
+ for (const p of fnNode.params || []) {
147
+ if (p?.type === "Identifier") {
148
+ paramSet.add(p.name);
149
+ } else if (p?.type === "AssignmentPattern" && p.left?.type === "Identifier") {
150
+ paramSet.add(p.left.name);
151
+ }
152
+ }
153
+ fnParams.set(fnNode, paramSet);
154
+ }
155
+ return paramSet;
156
+ }
157
+ function recordVarAlias(scopeNode, varName, rhsName) {
158
+ let map = fnVarAliases.get(scopeNode);
159
+ if (!map) {
160
+ map = /* @__PURE__ */ new Map();
161
+ fnVarAliases.set(scopeNode, map);
162
+ }
163
+ map.set(varName, rhsName);
164
+ }
165
+ function resolveAliasTarget(scopeNode, identName) {
166
+ const map = fnVarAliases.get(scopeNode);
167
+ let cur = identName;
168
+ const seen = /* @__PURE__ */ new Set();
169
+ while (map && map.has(cur) && !seen.has(cur)) {
170
+ seen.add(cur);
171
+ cur = map.get(cur);
172
+ }
173
+ return cur;
174
+ }
175
+ function markSerializedFunction(node) {
176
+ serializedFunctionNodes.add(node);
177
+ hotFunctionNodes.add(node);
178
+ directHotNodes.add(node);
179
+ hotExemptNodes.add(node);
180
+ }
181
+ function findEnclosingFunction(ancestors, selfNode) {
182
+ for (let i = ancestors.length - 1; i >= 0; i--) {
183
+ if (ancestors[i] !== selfNode && FUNCTION_NODE_TYPES.has(ancestors[i].type)) {
184
+ return ancestors[i];
185
+ }
186
+ }
187
+ return null;
188
+ }
189
+ function findOutermostModuleFunction(ancestors) {
190
+ const fnList = [];
191
+ for (let i = 0; i < ancestors.length; i++) {
192
+ if (FUNCTION_NODE_TYPES.has(ancestors[i].type)) {
193
+ fnList.push(ancestors[i]);
194
+ }
195
+ }
196
+ if (fnList.length === 0) return null;
197
+ if (fnList.length === 1) return fnList[0];
198
+ return fnList[1];
199
+ }
200
+ function isZeroArgIifeFactoryFunction(node) {
201
+ if (!node || node.params && node.params.length > 0) return false;
202
+ if (!node.body || node.body.type !== "BlockStatement") return false;
203
+ const stmts = (node.body.body || []).filter(
204
+ (s) => !(s.type === "ExpressionStatement" && s.directive)
205
+ );
206
+ if (stmts.length !== 1 || stmts[0].type !== "ReturnStatement") return false;
207
+ const retArg = stmts[0].argument;
208
+ if (!retArg || retArg.type !== "CallExpression") return false;
209
+ const callee = retArg.callee;
210
+ return callee && (callee.type === "FunctionExpression" || callee.type === "ArrowFunctionExpression") && callee.body?.type === "BlockStatement";
211
+ }
136
212
  function registerFunctionNode(node, ancestors) {
137
213
  const name = getFunctionLabel(node, ancestors);
138
214
  allFunctions.push({ node, name });
139
215
  fnByName.set(name, node);
216
+ const paramSet = /* @__PURE__ */ new Set();
217
+ for (const p of node.params || []) {
218
+ if (p?.type === "Identifier") {
219
+ paramSet.add(p.name);
220
+ } else if (p?.type === "AssignmentPattern" && p.left?.type === "Identifier") {
221
+ paramSet.add(p.left.name);
222
+ }
223
+ }
224
+ fnParams.set(node, paramSet);
140
225
  const enclosingScope = findEnclosingScopeNode(ancestors, node);
141
226
  let localMap = scopeFunctions.get(enclosingScope);
142
227
  if (!localMap) {
@@ -145,6 +230,22 @@ function analyzeAstHotPaths(ast) {
145
230
  }
146
231
  localMap.set(name, node);
147
232
  const parent = ancestors[ancestors.length - 2];
233
+ if (parent?.type === "VariableDeclarator" && parent.id?.type === "Identifier") {
234
+ fnByName.set(parent.id.name, node);
235
+ localMap.set(parent.id.name, node);
236
+ } else if (parent?.type === "AssignmentExpression" && parent.left?.type === "Identifier") {
237
+ fnByName.set(parent.left.name, node);
238
+ localMap.set(parent.left.name, node);
239
+ } else if (parent?.type === "AssignmentExpression" && parent.left?.type === "MemberExpression" && !parent.left.computed && parent.left.property?.type === "Identifier") {
240
+ const propName = parent.left.property.name;
241
+ fnByName.set(propName, node);
242
+ localMap.set(propName, node);
243
+ if (parent.left.object?.type === "Identifier") {
244
+ const qual = `${parent.left.object.name}.${propName}`;
245
+ fnByName.set(qual, node);
246
+ localMap.set(qual, node);
247
+ }
248
+ }
148
249
  const grandParent = ancestors[ancestors.length - 3];
149
250
  const greatGrandParent = ancestors[ancestors.length - 4];
150
251
  if (parent?.type === "Property" && parent.key?.type === "Identifier" && grandParent?.type === "ObjectExpression" && greatGrandParent?.type === "VariableDeclarator" && greatGrandParent.id?.type === "Identifier") {
@@ -154,7 +255,7 @@ function analyzeAstHotPaths(ast) {
154
255
  }
155
256
  const chain = [];
156
257
  for (let i = ancestors.length - 1; i >= 0; i--) {
157
- if (FUNCTION_NODE_TYPES.has(ancestors[i].type) || ancestors[i].type === "Program") {
258
+ if (ancestors[i] !== node && (FUNCTION_NODE_TYPES.has(ancestors[i].type) || ancestors[i].type === "Program")) {
158
259
  chain.push(ancestors[i]);
159
260
  }
160
261
  }
@@ -163,8 +264,13 @@ function analyzeAstHotPaths(ast) {
163
264
  hotFunctionNodes.add(node);
164
265
  directHotNodes.add(node);
165
266
  }
267
+ if (isZeroArgIifeFactoryFunction(node)) {
268
+ markSerializedFunction(node);
269
+ }
166
270
  }
167
271
  function resolveCalleeNode(callerNode, calleeKey) {
272
+ const directLocal = scopeFunctions.get(callerNode)?.get(calleeKey);
273
+ if (directLocal) return directLocal;
168
274
  const chain = fnScopeChain.get(callerNode);
169
275
  if (chain) {
170
276
  for (const scopeNode of chain) {
@@ -175,6 +281,25 @@ function analyzeAstHotPaths(ast) {
175
281
  }
176
282
  return fnByName.get(calleeKey);
177
283
  }
284
+ function queueSerializedTarget(target, enclosingScope) {
285
+ if (!target) return;
286
+ if (FUNCTION_NODE_TYPES.has(target.type)) {
287
+ markSerializedFunction(target);
288
+ } else if (target.type === "Identifier") {
289
+ pendingSerializedRefs.push({ scopeNode: enclosingScope, name: target.name });
290
+ } else if (target.type === "MemberExpression" && !target.computed && target.property?.type === "Identifier") {
291
+ pendingSerializedRefs.push({
292
+ scopeNode: enclosingScope,
293
+ name: target.property.name
294
+ });
295
+ if (target.object?.type === "Identifier") {
296
+ pendingSerializedRefs.push({
297
+ scopeNode: enclosingScope,
298
+ name: `${target.object.name}.${target.property.name}`
299
+ });
300
+ }
301
+ }
302
+ }
178
303
  walk.ancestor(ast, {
179
304
  FunctionDeclaration(node, _state, ancestors) {
180
305
  registerFunctionNode(node, ancestors);
@@ -185,6 +310,59 @@ function analyzeAstHotPaths(ast) {
185
310
  ArrowFunctionExpression(node, _state, ancestors) {
186
311
  registerFunctionNode(node, ancestors);
187
312
  },
313
+ VariableDeclarator(node, _state, ancestors) {
314
+ if (node.id?.type === "Identifier" && node.init?.type === "Identifier") {
315
+ const scopeNode = findEnclosingFunction(ancestors) ?? ast;
316
+ recordVarAlias(scopeNode, node.id.name, node.init.name);
317
+ }
318
+ },
319
+ AssignmentExpression(node, _state, ancestors) {
320
+ const left = node.left;
321
+ if (left?.type === "Identifier" && node.right?.type === "Identifier") {
322
+ const scopeNode = findEnclosingFunction(ancestors) ?? ast;
323
+ recordVarAlias(scopeNode, left.name, node.right.name);
324
+ }
325
+ const isBareOnMessage = left?.type === "Identifier" && left.name === "onmessage";
326
+ const isSelfOnMessage = left?.type === "MemberExpression" && !left.computed && left.object?.type === "Identifier" && left.object.name === "self" && left.property?.type === "Identifier" && left.property.name === "onmessage";
327
+ if (isBareOnMessage || isSelfOnMessage) {
328
+ const enclosingFn = findEnclosingFunction(ancestors);
329
+ if (enclosingFn) {
330
+ markSerializedFunction(enclosingFn);
331
+ }
332
+ const outerFn = findOutermostModuleFunction(ancestors);
333
+ if (outerFn) {
334
+ markSerializedFunction(outerFn);
335
+ }
336
+ const scopeNode = enclosingFn ?? ast;
337
+ queueSerializedTarget(node.right, scopeNode);
338
+ }
339
+ },
340
+ ObjectExpression(node, _state, ancestors) {
341
+ const props = node.properties || [];
342
+ const propMap = /* @__PURE__ */ new Map();
343
+ for (const p of props) {
344
+ if (p?.type === "Property" && !p.computed) {
345
+ const keyName = p.key?.type === "Identifier" ? p.key.name : p.key?.type === "Literal" ? String(p.key.value) : "";
346
+ if (keyName) {
347
+ propMap.set(keyName, p.value);
348
+ }
349
+ }
350
+ }
351
+ const hasWorkerDescriptorShape = propMap.has("init") && propMap.has("dependencies") || propMap.has("isWorkerModule") || propMap.has("getTransferables") && (propMap.has("init") || propMap.has("dependencies"));
352
+ if (hasWorkerDescriptorShape) {
353
+ const scopeNode = findEnclosingFunction(ancestors) ?? ast;
354
+ for (const key of ["init", "getTransferables", "worker"]) {
355
+ const val = propMap.get(key);
356
+ if (val) queueSerializedTarget(val, scopeNode);
357
+ }
358
+ const deps = propMap.get("dependencies");
359
+ if (deps?.type === "ArrayExpression") {
360
+ for (const el of deps.elements || []) {
361
+ if (el) queueSerializedTarget(el, scopeNode);
362
+ }
363
+ }
364
+ }
365
+ },
188
366
  CallExpression(node, _state, ancestors) {
189
367
  const callee = node.callee;
190
368
  let calleeName = "";
@@ -201,38 +379,76 @@ function analyzeAstHotPaths(ast) {
201
379
  qualifiedCall = memberProp;
202
380
  }
203
381
  }
382
+ const enclosingFn = findEnclosingFunction(ancestors);
383
+ const currentScope = enclosingFn ?? ast;
204
384
  if (qualifiedCall || memberProp) {
205
- for (let i = ancestors.length - 1; i >= 0; i--) {
206
- if (FUNCTION_NODE_TYPES.has(ancestors[i].type)) {
207
- let set = callerToCallees.get(ancestors[i]);
208
- if (!set) {
209
- set = /* @__PURE__ */ new Set();
210
- callerToCallees.set(ancestors[i], set);
211
- }
212
- if (qualifiedCall) set.add(qualifiedCall);
213
- if (memberProp && !ARRAY_HOF_METHODS.has(memberProp)) {
214
- set.add(memberProp);
215
- }
216
- break;
385
+ allCallSites.push({
386
+ scopeNode: currentScope,
387
+ calleeKey: qualifiedCall || memberProp,
388
+ args: node.arguments || []
389
+ });
390
+ if (enclosingFn) {
391
+ let set = callerToCallees.get(enclosingFn);
392
+ if (!set) {
393
+ set = /* @__PURE__ */ new Set();
394
+ callerToCallees.set(enclosingFn, set);
395
+ }
396
+ if (qualifiedCall) set.add(qualifiedCall);
397
+ if (memberProp && !ARRAY_HOF_METHODS.has(memberProp)) {
398
+ set.add(memberProp);
399
+ }
400
+ }
401
+ }
402
+ if (memberProp === "toString" && (!node.arguments || node.arguments.length === 0) && callee?.type === "MemberExpression") {
403
+ const targetObj = callee.object;
404
+ queueSerializedTarget(targetObj, currentScope);
405
+ if (targetObj?.type === "Identifier" && enclosingFn) {
406
+ const resolvedName = resolveAliasTarget(enclosingFn, targetObj.name);
407
+ if (ensureFnParams(enclosingFn).has(resolvedName)) {
408
+ serializerHelperNodes.add(enclosingFn);
409
+ }
410
+ if (resolvedName !== targetObj.name) {
411
+ queueSerializedTarget({ type: "Identifier", name: resolvedName }, currentScope);
412
+ }
413
+ }
414
+ }
415
+ 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) {
416
+ const firstArg = node.arguments[0];
417
+ queueSerializedTarget(firstArg, currentScope);
418
+ if (firstArg?.type === "Identifier" && enclosingFn) {
419
+ const resolvedName = resolveAliasTarget(enclosingFn, firstArg.name);
420
+ if (ensureFnParams(enclosingFn).has(resolvedName)) {
421
+ serializerHelperNodes.add(enclosingFn);
422
+ }
423
+ if (resolvedName !== firstArg.name) {
424
+ queueSerializedTarget({ type: "Identifier", name: resolvedName }, currentScope);
217
425
  }
218
426
  }
219
427
  }
428
+ if (calleeName === "importScripts" || memberProp === "importScripts" && callee?.object?.type === "Identifier" && callee.object.name === "self") {
429
+ if (enclosingFn) markSerializedFunction(enclosingFn);
430
+ const outerFn = findOutermostModuleFunction(ancestors);
431
+ if (outerFn) markSerializedFunction(outerFn);
432
+ }
220
433
  if (ARRAY_HOF_METHODS.has(memberProp) || calleeName === "requestAnimationFrame" || memberProp === "requestAnimationFrame" || calleeName === "cancelAnimationFrame" || memberProp === "cancelAnimationFrame") {
221
434
  for (const arg of node.arguments || []) {
222
435
  if (FUNCTION_NODE_TYPES.has(arg.type)) {
223
436
  hotFunctionNodes.add(arg);
224
437
  directHotNodes.add(arg);
225
438
  hotExemptNodes.add(arg);
439
+ } else if (arg?.type === "Identifier") {
440
+ allCallSites.push({
441
+ scopeNode: currentScope,
442
+ calleeKey: arg.name,
443
+ args: [arg]
444
+ });
226
445
  }
227
446
  }
228
447
  }
229
448
  if (UI_HOOK_OR_RENDER_CALLS.has(calleeName) || UI_HOOK_OR_RENDER_CALLS.has(memberProp)) {
230
- for (let i = ancestors.length - 1; i >= 0; i--) {
231
- if (FUNCTION_NODE_TYPES.has(ancestors[i].type)) {
232
- hotFunctionNodes.add(ancestors[i]);
233
- directHotNodes.add(ancestors[i]);
234
- break;
235
- }
449
+ if (enclosingFn) {
450
+ hotFunctionNodes.add(enclosingFn);
451
+ directHotNodes.add(enclosingFn);
236
452
  }
237
453
  }
238
454
  },
@@ -257,10 +473,41 @@ function analyzeAstHotPaths(ast) {
257
473
  markEnclosingFunctionHot(ancestors, hotFunctionNodes, directHotNodes);
258
474
  }
259
475
  });
476
+ for (const callSite of allCallSites) {
477
+ const resolvedCallee = resolveCalleeNode(callSite.scopeNode, callSite.calleeKey);
478
+ if (resolvedCallee && serializerHelperNodes.has(resolvedCallee)) {
479
+ for (const arg of callSite.args) {
480
+ queueSerializedTarget(arg, callSite.scopeNode);
481
+ }
482
+ }
483
+ }
484
+ for (const ref of pendingSerializedRefs) {
485
+ const targetNode = resolveCalleeNode(ref.scopeNode, ref.name);
486
+ if (targetNode) {
487
+ markSerializedFunction(targetNode);
488
+ }
489
+ }
260
490
  const forwardHotSet = new Set(directHotNodes);
261
491
  let forwardChanged = true;
262
492
  while (forwardChanged) {
263
493
  forwardChanged = false;
494
+ for (const fn of allFunctions) {
495
+ if (forwardHotSet.has(fn.node)) continue;
496
+ const chain = fnScopeChain.get(fn.node);
497
+ if (!chain) continue;
498
+ for (const anc of chain) {
499
+ if (anc !== fn.node && (serializedFunctionNodes.has(anc) || forwardHotSet.has(anc))) {
500
+ forwardHotSet.add(fn.node);
501
+ hotFunctionNodes.add(fn.node);
502
+ hotExemptNodes.add(fn.node);
503
+ if (serializedFunctionNodes.has(anc)) {
504
+ serializedFunctionNodes.add(fn.node);
505
+ }
506
+ forwardChanged = true;
507
+ break;
508
+ }
509
+ }
510
+ }
264
511
  for (const callerNode of Array.from(forwardHotSet)) {
265
512
  const calleeNames = callerToCallees.get(callerNode);
266
513
  if (!calleeNames) continue;
@@ -270,6 +517,9 @@ function analyzeAstHotPaths(ast) {
270
517
  forwardHotSet.add(targetNode);
271
518
  hotFunctionNodes.add(targetNode);
272
519
  hotExemptNodes.add(targetNode);
520
+ if (serializedFunctionNodes.has(callerNode)) {
521
+ serializedFunctionNodes.add(targetNode);
522
+ }
273
523
  forwardChanged = true;
274
524
  }
275
525
  }
@@ -344,7 +594,7 @@ var DIRECTIVE_STRINGS = /* @__PURE__ */ new Set([
344
594
  "use asm"
345
595
  ]);
346
596
  var HELPER_TEMPLATE = acorn2.parse(
347
- `const _ = [].map(function f(a) {
597
+ `var _ = [].map(function f(a) {
348
598
  var s = "";
349
599
  for (var j = 0; j < a.length; j++) {
350
600
  s += String.fromCharCode(a.charCodeAt(j) ^ (((0 ^ ((a._u || /\\n/.test(f) * 14) | ((j & 1) * 0))) & 30) | 1));
@@ -390,8 +640,17 @@ function encodeStringWithSeed(str, mask, step) {
390
640
  return out;
391
641
  }
392
642
  function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExemptNodes) {
393
- const suffix = ((seed >>> 0) % 255).toString(36);
394
- const cacheVarName = `_uC${suffix}`;
643
+ const alreadyVaulted = ast.body.some(
644
+ (stmt) => stmt.type === "VariableDeclaration" && stmt.declarations?.some(
645
+ (d) => d.id?.type === "Identifier" && typeof d.id.name === "string" && d.id.name.startsWith("_uC")
646
+ )
647
+ );
648
+ if (alreadyVaulted) {
649
+ return {
650
+ encryptedStringsCount: 0,
651
+ integrityToken: computeFnv1aHash("already-vaulted", seed)
652
+ };
653
+ }
395
654
  const mask = seed >>> 0 & 30 | 3;
396
655
  const step = (seed >>> 5 & 7) * 2 + 3;
397
656
  const stringToIndex = /* @__PURE__ */ new Map();
@@ -437,6 +696,10 @@ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExempt
437
696
  integrityToken: computeFnv1aHash("empty", seed)
438
697
  };
439
698
  }
699
+ const serializedTable = JSON.stringify(encryptedPayloads);
700
+ const integrityToken = computeFnv1aHash(serializedTable, seed);
701
+ const suffix = computeFnv1aHash(`vault:${seed}`, integrityToken).toString(36);
702
+ const cacheVarName = `_uC${suffix}`;
440
703
  for (const { node } of targetsToReplace) {
441
704
  const idx = stringToIndex.get(node.value);
442
705
  node.type = "MemberExpression";
@@ -454,8 +717,6 @@ function applyStringVault(ast, seed = 2654435769, minStringLength = 4, hotExempt
454
717
  delete node.value;
455
718
  delete node.raw;
456
719
  }
457
- const serializedTable = JSON.stringify(encryptedPayloads);
458
- const integrityToken = computeFnv1aHash(serializedTable, seed);
459
720
  const helperStmt = createVaultHelperAst(
460
721
  cacheVarName,
461
722
  encryptedPayloads,
@@ -527,167 +788,351 @@ var FUNCTION_TYPES = /* @__PURE__ */ new Set([
527
788
  "FunctionExpression",
528
789
  "ArrowFunctionExpression"
529
790
  ]);
530
- function collectPatternIdentifiers(pattern, out) {
791
+ var LEXICAL_SCOPE_TYPES = /* @__PURE__ */ new Set([
792
+ "Program",
793
+ "FunctionDeclaration",
794
+ "FunctionExpression",
795
+ "ArrowFunctionExpression",
796
+ "BlockStatement",
797
+ "ForStatement",
798
+ "ForInStatement",
799
+ "ForOfStatement",
800
+ "SwitchStatement",
801
+ "CatchClause",
802
+ "ClassDeclaration",
803
+ "ClassExpression"
804
+ ]);
805
+ function collectPatternTargets(pattern, out, shorthandProp) {
531
806
  if (!pattern) return;
532
807
  switch (pattern.type) {
533
808
  case "Identifier":
534
- out.push(pattern);
809
+ out.push({ idNode: pattern, shorthandProp });
535
810
  break;
536
811
  case "AssignmentPattern":
537
- collectPatternIdentifiers(pattern.left, out);
812
+ collectPatternTargets(pattern.left, out, shorthandProp);
538
813
  break;
539
814
  case "RestElement":
540
- collectPatternIdentifiers(pattern.argument, out);
815
+ collectPatternTargets(pattern.argument, out);
541
816
  break;
542
817
  case "ArrayPattern":
543
818
  for (const el of pattern.elements || []) {
544
- if (el) collectPatternIdentifiers(el, out);
819
+ if (el) collectPatternTargets(el, out);
545
820
  }
546
821
  break;
547
822
  case "ObjectPattern":
548
823
  for (const prop of pattern.properties || []) {
549
824
  if (prop.type === "Property") {
550
- if (prop.shorthand) {
551
- prop.shorthand = false;
552
- prop.key = { ...prop.key };
553
- }
554
- collectPatternIdentifiers(prop.value, out);
825
+ collectPatternTargets(
826
+ prop.value,
827
+ out,
828
+ prop.shorthand ? prop : void 0
829
+ );
555
830
  } else if (prop.type === "RestElement") {
556
- collectPatternIdentifiers(prop.argument, out);
831
+ collectPatternTargets(prop.argument, out);
557
832
  }
558
833
  }
559
834
  break;
560
835
  }
561
836
  }
837
+ function isMangleableName(origName) {
838
+ return !RESERVED_IDENTIFIERS.has(origName) && !origName.startsWith("_u") && !origName.startsWith("_0x");
839
+ }
562
840
  function applyPolymorphicMangler(ast, seed = 2654435769) {
563
- const scopeMap = /* @__PURE__ */ new Map();
564
- const scopeDepthMap = /* @__PURE__ */ new Map();
841
+ const scopeRecords = /* @__PURE__ */ new Map();
842
+ const existingIdentifiers = /* @__PURE__ */ new Set();
565
843
  let counter = 0;
566
- function makeScopedMangledName(scopeDepth, localIndex, usedValues) {
567
- counter++;
568
- let salt = 0;
569
- while (true) {
570
- const h = computeFnv1aHash(`s${scopeDepth}:i${localIndex}:${salt}`, seed);
571
- const candidate = `_0x${((h & 31) + localIndex + salt).toString(36)}`;
572
- if (!usedValues.has(candidate)) {
573
- return candidate;
844
+ function ensureScopeChain(ancestors) {
845
+ let prevScope = null;
846
+ for (let i = 0; i < ancestors.length; i++) {
847
+ const node = ancestors[i];
848
+ if (!LEXICAL_SCOPE_TYPES.has(node.type)) continue;
849
+ let record = scopeRecords.get(node);
850
+ if (!record) {
851
+ const isFn = FUNCTION_TYPES.has(node.type);
852
+ const depth = prevScope ? prevScope.depth + (isFn ? 1 : 0) : 0;
853
+ record = {
854
+ node,
855
+ parent: prevScope,
856
+ children: [],
857
+ depth: Math.max(1, depth),
858
+ bindings: /* @__PURE__ */ new Map(),
859
+ usedNames: /* @__PURE__ */ new Set()
860
+ };
861
+ scopeRecords.set(node, record);
862
+ if (prevScope) {
863
+ prevScope.children.push(record);
864
+ }
574
865
  }
575
- salt++;
866
+ prevScope = record;
576
867
  }
868
+ return prevScope;
577
869
  }
578
- function countFunctionDepth(ancestors) {
579
- let depth = 0;
580
- for (let i = 0; i < ancestors.length; i++) {
870
+ function findEnclosingFunctionNode(ancestors) {
871
+ for (let i = ancestors.length - 1; i >= 0; i--) {
581
872
  if (FUNCTION_TYPES.has(ancestors[i].type)) {
582
- depth++;
873
+ return ancestors[i];
583
874
  }
584
875
  }
585
- return Math.max(1, depth);
876
+ return null;
586
877
  }
587
- function findEnclosingFunction(ancestors) {
878
+ function findEnclosingLexicalNode(ancestors) {
588
879
  for (let i = ancestors.length - 1; i >= 0; i--) {
589
- if (FUNCTION_TYPES.has(ancestors[i].type)) {
880
+ if (LEXICAL_SCOPE_TYPES.has(ancestors[i].type)) {
590
881
  return ancestors[i];
591
882
  }
592
883
  }
593
- return null;
884
+ return ancestors[0];
594
885
  }
595
- function registerBindingAndMutateDeclSite(idNode, bindings, scopeDepth) {
596
- const origName = idNode.name;
597
- if (RESERVED_IDENTIFIERS.has(origName) || origName.startsWith("_u") || origName.startsWith("_0x")) {
598
- return;
886
+ function registerBindingTarget(scopeNode, target, shouldMangle) {
887
+ const scope = scopeRecords.get(scopeNode);
888
+ if (!scope) return;
889
+ const origName = target.idNode.name;
890
+ const canMangle = shouldMangle && isMangleableName(origName);
891
+ let entry = scope.bindings.get(origName);
892
+ if (!entry) {
893
+ entry = {
894
+ origName,
895
+ shouldMangle: canMangle,
896
+ targets: [target],
897
+ mangledName: origName
898
+ };
899
+ scope.bindings.set(origName, entry);
900
+ } else {
901
+ if (!canMangle) {
902
+ entry.shouldMangle = false;
903
+ }
904
+ entry.targets.push(target);
599
905
  }
600
- let mangled = bindings.get(origName);
601
- if (!mangled) {
602
- const usedValues = new Set(bindings.values());
603
- mangled = makeScopedMangledName(scopeDepth, bindings.size, usedValues);
604
- bindings.set(origName, mangled);
906
+ }
907
+ function registerBarrierName(scopeNode, origName) {
908
+ const scope = scopeRecords.get(scopeNode);
909
+ if (!scope) return;
910
+ let entry = scope.bindings.get(origName);
911
+ if (!entry) {
912
+ entry = {
913
+ origName,
914
+ shouldMangle: false,
915
+ targets: [],
916
+ mangledName: origName
917
+ };
918
+ scope.bindings.set(origName, entry);
919
+ } else {
920
+ entry.shouldMangle = false;
605
921
  }
606
- idNode.name = mangled;
607
922
  }
608
923
  function registerFunctionParams(fnNode, ancestors) {
609
- let bindings = scopeMap.get(fnNode);
610
- const depth = countFunctionDepth(ancestors);
611
- scopeDepthMap.set(fnNode, depth);
612
- if (!bindings) {
613
- bindings = /* @__PURE__ */ new Map();
614
- scopeMap.set(fnNode, bindings);
615
- }
924
+ ensureScopeChain(ancestors);
616
925
  for (const param of fnNode.params || []) {
617
- const idNodes = [];
618
- collectPatternIdentifiers(param, idNodes);
619
- for (const idNode of idNodes) {
620
- registerBindingAndMutateDeclSite(idNode, bindings, depth);
926
+ const targets = [];
927
+ collectPatternTargets(param, targets);
928
+ for (const target of targets) {
929
+ registerBindingTarget(fnNode, target, true);
621
930
  }
622
931
  }
623
932
  }
933
+ ensureScopeChain([ast]);
624
934
  walk3.ancestor(ast, {
935
+ Identifier(node) {
936
+ if (typeof node.name === "string") {
937
+ existingIdentifiers.add(node.name);
938
+ }
939
+ },
940
+ BlockStatement(_node, _state, ancestors) {
941
+ ensureScopeChain(ancestors);
942
+ },
943
+ ForStatement(_node, _state, ancestors) {
944
+ ensureScopeChain(ancestors);
945
+ },
946
+ ForInStatement(_node, _state, ancestors) {
947
+ ensureScopeChain(ancestors);
948
+ },
949
+ ForOfStatement(_node, _state, ancestors) {
950
+ ensureScopeChain(ancestors);
951
+ },
952
+ SwitchStatement(_node, _state, ancestors) {
953
+ ensureScopeChain(ancestors);
954
+ },
625
955
  FunctionDeclaration(node, _state, ancestors) {
626
956
  registerFunctionParams(node, ancestors);
957
+ if (node.id?.type === "Identifier") {
958
+ const parentAncestors = ancestors.slice(0, -1);
959
+ const lexNode = findEnclosingLexicalNode(parentAncestors);
960
+ const fnNode = findEnclosingFunctionNode(parentAncestors) ?? ast;
961
+ registerBarrierName(lexNode, node.id.name);
962
+ if (lexNode === fnNode.body || fnNode === ast) {
963
+ registerBarrierName(fnNode, node.id.name);
964
+ }
965
+ if (!scopeRecords.get(node)?.bindings.has(node.id.name)) {
966
+ registerBarrierName(node, node.id.name);
967
+ }
968
+ }
627
969
  },
628
970
  FunctionExpression(node, _state, ancestors) {
629
971
  registerFunctionParams(node, ancestors);
972
+ if (node.id?.type === "Identifier") {
973
+ if (!scopeRecords.get(node)?.bindings.has(node.id.name)) {
974
+ registerBarrierName(node, node.id.name);
975
+ }
976
+ }
630
977
  },
631
978
  ArrowFunctionExpression(node, _state, ancestors) {
632
979
  registerFunctionParams(node, ancestors);
633
980
  },
981
+ ClassDeclaration(node, _state, ancestors) {
982
+ ensureScopeChain(ancestors);
983
+ if (node.id?.type === "Identifier") {
984
+ const parentAncestors = ancestors.slice(0, -1);
985
+ const lexNode = findEnclosingLexicalNode(parentAncestors);
986
+ registerBarrierName(lexNode, node.id.name);
987
+ registerBarrierName(node, node.id.name);
988
+ }
989
+ },
990
+ ClassExpression(node, _state, ancestors) {
991
+ ensureScopeChain(ancestors);
992
+ if (node.id?.type === "Identifier") {
993
+ registerBarrierName(node, node.id.name);
994
+ }
995
+ },
996
+ CatchClause(node, _state, ancestors) {
997
+ ensureScopeChain(ancestors);
998
+ if (node.param) {
999
+ const targets = [];
1000
+ collectPatternTargets(node.param, targets);
1001
+ for (const target of targets) {
1002
+ registerBindingTarget(node, target, true);
1003
+ }
1004
+ }
1005
+ },
634
1006
  VariableDeclaration(node, _state, ancestors) {
635
- const fnScope = findEnclosingFunction(ancestors);
636
- if (!fnScope) return;
637
- let bindings = scopeMap.get(fnScope);
638
- const depth = scopeDepthMap.get(fnScope) ?? countFunctionDepth(ancestors);
639
- if (!bindings) {
640
- bindings = /* @__PURE__ */ new Map();
641
- scopeMap.set(fnScope, bindings);
1007
+ ensureScopeChain(ancestors);
1008
+ const fnScope = findEnclosingFunctionNode(ancestors);
1009
+ if (!fnScope) {
1010
+ for (const decl of node.declarations || []) {
1011
+ const targets = [];
1012
+ collectPatternTargets(decl.id, targets);
1013
+ for (const target of targets) {
1014
+ registerBarrierName(ast, target.idNode.name);
1015
+ }
1016
+ }
1017
+ return;
642
1018
  }
1019
+ const targetScopeNode = node.kind === "var" ? fnScope : findEnclosingLexicalNode(ancestors);
643
1020
  for (const decl of node.declarations || []) {
644
- const idNodes = [];
645
- collectPatternIdentifiers(decl.id, idNodes);
646
- for (const idNode of idNodes) {
647
- registerBindingAndMutateDeclSite(idNode, bindings, depth);
1021
+ const targets = [];
1022
+ collectPatternTargets(decl.id, targets);
1023
+ for (const target of targets) {
1024
+ const origName = target.idNode.name;
1025
+ if (node.kind === "var") {
1026
+ for (let i = ancestors.length - 1; i >= 0; i--) {
1027
+ if (ancestors[i] === fnScope) break;
1028
+ if (ancestors[i].type === "CatchClause") {
1029
+ const catchScope = scopeRecords.get(ancestors[i]);
1030
+ if (catchScope?.bindings.has(origName)) {
1031
+ registerBarrierName(ancestors[i], origName);
1032
+ registerBarrierName(fnScope, origName);
1033
+ }
1034
+ }
1035
+ }
1036
+ }
1037
+ registerBindingTarget(targetScopeNode, target, true);
648
1038
  }
649
1039
  }
650
1040
  }
651
1041
  });
1042
+ function isNameUsedInScopeOrAncestors(candidate, scope) {
1043
+ if (existingIdentifiers.has(candidate)) return true;
1044
+ let curr = scope;
1045
+ while (curr) {
1046
+ if (curr.usedNames.has(candidate) || curr.bindings.has(candidate)) {
1047
+ return true;
1048
+ }
1049
+ curr = curr.parent;
1050
+ }
1051
+ return false;
1052
+ }
1053
+ function makeScopedMangledName(scope, localIndex) {
1054
+ counter++;
1055
+ let salt = 0;
1056
+ while (true) {
1057
+ const h = computeFnv1aHash(`s${scope.depth}:i${localIndex}:${salt}`, seed);
1058
+ const candidate = `_0x${((h & 31) + localIndex + salt).toString(36)}`;
1059
+ if (!isNameUsedInScopeOrAncestors(candidate, scope)) {
1060
+ return candidate;
1061
+ }
1062
+ salt++;
1063
+ }
1064
+ }
1065
+ function assignScopeNamesTopDown(scope) {
1066
+ let localIndex = 0;
1067
+ for (const entry of scope.bindings.values()) {
1068
+ if (!entry.shouldMangle) {
1069
+ entry.mangledName = entry.origName;
1070
+ scope.usedNames.add(entry.origName);
1071
+ continue;
1072
+ }
1073
+ const mangled = makeScopedMangledName(scope, localIndex);
1074
+ localIndex++;
1075
+ entry.mangledName = mangled;
1076
+ scope.usedNames.add(mangled);
1077
+ for (const target of entry.targets) {
1078
+ if (target.shorthandProp && target.shorthandProp.shorthand) {
1079
+ target.shorthandProp.shorthand = false;
1080
+ target.shorthandProp.key = {
1081
+ type: "Identifier",
1082
+ name: entry.origName
1083
+ };
1084
+ }
1085
+ target.idNode.name = mangled;
1086
+ }
1087
+ }
1088
+ for (const child of scope.children) {
1089
+ assignScopeNamesTopDown(child);
1090
+ }
1091
+ }
1092
+ const rootScope = scopeRecords.get(ast);
1093
+ if (rootScope) {
1094
+ assignScopeNamesTopDown(rootScope);
1095
+ }
652
1096
  if (counter === 0) return 0;
653
- walk3.ancestor(ast, {
654
- AssignmentExpression(node, _state, ancestors) {
655
- const idNodes = [];
656
- collectPatternIdentifiers(node.left, idNodes);
657
- for (const idNode of idNodes) {
658
- const resolved = resolveMangledName(idNode.name, ancestors, scopeMap);
659
- if (resolved) {
660
- idNode.name = resolved;
1097
+ function resolveBinding(name, ancestors) {
1098
+ for (let i = ancestors.length - 1; i >= 0; i--) {
1099
+ const scope = scopeRecords.get(ancestors[i]);
1100
+ if (scope && scope.bindings.has(name)) {
1101
+ return scope.bindings.get(name);
1102
+ }
1103
+ }
1104
+ return null;
1105
+ }
1106
+ function renamePatternTargetsInScope(pattern, ancestors) {
1107
+ const targets = [];
1108
+ collectPatternTargets(pattern, targets);
1109
+ for (const target of targets) {
1110
+ const origName = target.idNode.name;
1111
+ const entry = resolveBinding(origName, ancestors);
1112
+ if (entry && entry.shouldMangle && entry.mangledName !== origName) {
1113
+ if (target.shorthandProp && target.shorthandProp.shorthand) {
1114
+ target.shorthandProp.shorthand = false;
1115
+ target.shorthandProp.key = {
1116
+ type: "Identifier",
1117
+ name: origName
1118
+ };
661
1119
  }
1120
+ target.idNode.name = entry.mangledName;
662
1121
  }
1122
+ }
1123
+ }
1124
+ walk3.ancestor(ast, {
1125
+ AssignmentExpression(node, _state, ancestors) {
1126
+ renamePatternTargetsInScope(node.left, ancestors);
663
1127
  },
664
1128
  ForInStatement(node, _state, ancestors) {
665
1129
  if (node.left && node.left.type !== "VariableDeclaration") {
666
- const idNodes = [];
667
- collectPatternIdentifiers(node.left, idNodes);
668
- for (const idNode of idNodes) {
669
- const resolved = resolveMangledName(idNode.name, ancestors, scopeMap);
670
- if (resolved) idNode.name = resolved;
671
- }
1130
+ renamePatternTargetsInScope(node.left, ancestors);
672
1131
  }
673
1132
  },
674
1133
  ForOfStatement(node, _state, ancestors) {
675
1134
  if (node.left && node.left.type !== "VariableDeclaration") {
676
- const idNodes = [];
677
- collectPatternIdentifiers(node.left, idNodes);
678
- for (const idNode of idNodes) {
679
- const resolved = resolveMangledName(idNode.name, ancestors, scopeMap);
680
- if (resolved) idNode.name = resolved;
681
- }
682
- }
683
- },
684
- Property(node, _state, ancestors) {
685
- if (node.shorthand && node.value?.type === "Identifier") {
686
- const resolved = resolveMangledName(node.value.name, ancestors, scopeMap);
687
- if (resolved) {
688
- node.shorthand = false;
689
- node.key = { type: "Identifier", name: node.value.name };
690
- }
1135
+ renamePatternTargetsInScope(node.left, ancestors);
691
1136
  }
692
1137
  },
693
1138
  Identifier(node, _state, ancestors) {
@@ -705,24 +1150,18 @@ function applyPolymorphicMangler(ast, seed = 2654435769) {
705
1150
  if (parent.type === "LabeledStatement" || parent.type === "BreakStatement" || parent.type === "ContinueStatement" || parent.type === "ImportSpecifier" || parent.type === "ImportDefaultSpecifier" || parent.type === "ImportNamespaceSpecifier" || parent.type === "ExportSpecifier") {
706
1151
  return;
707
1152
  }
708
- const resolved = resolveMangledName(node.name, ancestors, scopeMap);
709
- if (resolved) {
710
- node.name = resolved;
1153
+ const entry = resolveBinding(node.name, ancestors);
1154
+ if (entry && entry.shouldMangle && entry.mangledName !== node.name) {
1155
+ if (parent.type === "Property" && parent.shorthand && parent.value === node) {
1156
+ parent.shorthand = false;
1157
+ parent.key = { type: "Identifier", name: node.name };
1158
+ }
1159
+ node.name = entry.mangledName;
711
1160
  }
712
1161
  }
713
1162
  });
714
1163
  return counter;
715
1164
  }
716
- function resolveMangledName(name, ancestors, scopeMap) {
717
- for (let i = ancestors.length - 1; i >= 0; i--) {
718
- const anc = ancestors[i];
719
- const bindings = scopeMap.get(anc);
720
- if (bindings && bindings.has(name)) {
721
- return bindings.get(name);
722
- }
723
- }
724
- return null;
725
- }
726
1165
 
727
1166
  // src/ast/cold-flow-guard.ts
728
1167
  var walk4 = __toESM(require("acorn-walk"), 1);
@@ -759,8 +1198,13 @@ function createOpaqueGuardStatement(seed, fnIndex) {
759
1198
  right: { type: "Literal", value: wrongVal, raw: String(wrongVal) }
760
1199
  },
761
1200
  consequent: {
762
- type: "ReturnStatement",
763
- argument: null
1201
+ type: "ExpressionStatement",
1202
+ expression: {
1203
+ type: "UnaryExpression",
1204
+ operator: "void",
1205
+ prefix: true,
1206
+ argument: { type: "Literal", value: 0, raw: "0" }
1207
+ }
764
1208
  },
765
1209
  alternate: null
766
1210
  };
@@ -837,6 +1281,20 @@ function generateRuntimeShield(config) {
837
1281
  }
838
1282
 
839
1283
  // src/ast/index.ts
1284
+ function isAstAlreadyProtected(ast) {
1285
+ if (!ast || !Array.isArray(ast.body)) return false;
1286
+ return ast.body.some((stmt) => {
1287
+ if (stmt.type === "VariableDeclaration" && stmt.declarations?.some(
1288
+ (d) => d.id?.type === "Identifier" && typeof d.id.name === "string" && d.id.name.startsWith("_uC")
1289
+ )) {
1290
+ return true;
1291
+ }
1292
+ if (stmt.type === "ExpressionStatement" && stmt.expression?.type === "CallExpression" && stmt.expression.callee?.type === "FunctionExpression" && typeof stmt.expression.callee.id?.name === "string" && stmt.expression.callee.id.name.startsWith("_u$")) {
1293
+ return true;
1294
+ }
1295
+ return false;
1296
+ });
1297
+ }
840
1298
  function transformJavaScript(code, options = {}) {
841
1299
  const seed = options.seed ?? 2654435769;
842
1300
  const minStringLength = options.minStringLength ?? 4;
@@ -854,7 +1312,7 @@ function transformJavaScript(code, options = {}) {
854
1312
  };
855
1313
  }
856
1314
  const ast = parseJavaScriptAst(code);
857
- if (!ast) {
1315
+ if (!ast || isAstAlreadyProtected(ast)) {
858
1316
  return {
859
1317
  code,
860
1318
  encryptedStringsCount: 0,