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