unpeek 1.0.1 → 1.2.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 (102) hide show
  1. package/README.md +131 -60
  2. package/README.tr.md +317 -0
  3. package/dist/ast/index.cjs +802 -0
  4. package/dist/ast/index.cjs.map +1 -0
  5. package/dist/ast/index.d.cts +9 -0
  6. package/dist/ast/index.d.ts +9 -4
  7. package/dist/ast/index.js +762 -52
  8. package/dist/ast/index.js.map +1 -0
  9. package/dist/browser.cjs +816 -0
  10. package/dist/browser.cjs.map +1 -0
  11. package/dist/browser.d.cts +3 -0
  12. package/dist/browser.d.ts +3 -0
  13. package/dist/browser.js +773 -0
  14. package/dist/browser.js.map +1 -0
  15. package/dist/bundler/detector.cjs +180 -0
  16. package/dist/bundler/detector.cjs.map +1 -0
  17. package/dist/bundler/detector.d.cts +9 -0
  18. package/dist/bundler/detector.d.ts +6 -3
  19. package/dist/bundler/detector.js +130 -135
  20. package/dist/bundler/detector.js.map +1 -0
  21. package/dist/bundler/sourcemap-vault.cjs +210 -0
  22. package/dist/bundler/sourcemap-vault.cjs.map +1 -0
  23. package/dist/bundler/sourcemap-vault.d.cts +6 -0
  24. package/dist/bundler/sourcemap-vault.d.ts +6 -2
  25. package/dist/bundler/sourcemap-vault.js +161 -85
  26. package/dist/bundler/sourcemap-vault.js.map +1 -0
  27. package/dist/bundler/unplugin.cjs +848 -0
  28. package/dist/bundler/unplugin.cjs.map +1 -0
  29. package/dist/bundler/unplugin.d.cts +14 -0
  30. package/dist/bundler/unplugin.d.ts +14 -7
  31. package/dist/bundler/unplugin.js +805 -51
  32. package/dist/bundler/unplugin.js.map +1 -0
  33. package/dist/cli/index.cjs +1361 -0
  34. package/dist/cli/index.cjs.map +1 -0
  35. package/dist/cli/index.d.cts +3 -0
  36. package/dist/cli/index.d.ts +3 -1
  37. package/dist/cli/index.js +1309 -94
  38. package/dist/cli/index.js.map +1 -0
  39. package/dist/cli/init.cjs +200 -0
  40. package/dist/cli/init.cjs.map +1 -0
  41. package/dist/cli/init.d.cts +13 -0
  42. package/dist/cli/init.d.ts +10 -2
  43. package/dist/cli/init.js +162 -46
  44. package/dist/cli/init.js.map +1 -0
  45. package/dist/cli/protect.cjs +1147 -0
  46. package/dist/cli/protect.cjs.map +1 -0
  47. package/dist/cli/protect.d.cts +5 -0
  48. package/dist/cli/protect.d.ts +5 -2
  49. package/dist/cli/protect.js +1107 -83
  50. package/dist/cli/protect.js.map +1 -0
  51. package/dist/esbuild.cjs +844 -0
  52. package/dist/esbuild.cjs.map +1 -0
  53. package/dist/esbuild.d.cts +11 -0
  54. package/dist/esbuild.d.ts +11 -0
  55. package/dist/esbuild.js +807 -0
  56. package/dist/esbuild.js.map +1 -0
  57. package/dist/index.cjs +1453 -0
  58. package/dist/index.cjs.map +1 -0
  59. package/dist/index.d.cts +14 -0
  60. package/dist/index.d.ts +9 -4
  61. package/dist/index.js +1395 -8
  62. package/dist/index.js.map +1 -0
  63. package/dist/rollup.cjs +844 -0
  64. package/dist/rollup.cjs.map +1 -0
  65. package/dist/rollup.d.cts +11 -0
  66. package/dist/rollup.d.ts +11 -0
  67. package/dist/rollup.js +807 -0
  68. package/dist/rollup.js.map +1 -0
  69. package/dist/runtime/index.cjs +88 -0
  70. package/dist/runtime/index.cjs.map +1 -0
  71. package/dist/runtime/index.d.cts +23 -0
  72. package/dist/runtime/index.d.ts +23 -4
  73. package/dist/runtime/index.js +57 -15
  74. package/dist/runtime/index.js.map +1 -0
  75. package/dist/{types.d.ts → types-BTMkXmVE.d.cts} +14 -12
  76. package/dist/types-BTMkXmVE.d.ts +73 -0
  77. package/dist/vite.cjs +844 -0
  78. package/dist/vite.cjs.map +1 -0
  79. package/dist/vite.d.cts +11 -0
  80. package/dist/vite.d.ts +11 -0
  81. package/dist/vite.js +807 -0
  82. package/dist/vite.js.map +1 -0
  83. package/dist/webpack.cjs +844 -0
  84. package/dist/webpack.cjs.map +1 -0
  85. package/dist/webpack.d.cts +11 -0
  86. package/dist/webpack.d.ts +11 -0
  87. package/dist/webpack.js +807 -0
  88. package/dist/webpack.js.map +1 -0
  89. package/package.json +104 -7
  90. package/dist/ast/cold-flow-guard.d.ts +0 -2
  91. package/dist/ast/cold-flow-guard.js +0 -39
  92. package/dist/ast/hot-path-detector.d.ts +0 -10
  93. package/dist/ast/hot-path-detector.js +0 -235
  94. package/dist/ast/polymorphic-mangler.d.ts +0 -2
  95. package/dist/ast/polymorphic-mangler.js +0 -270
  96. package/dist/ast/string-vault.d.ts +0 -7
  97. package/dist/ast/string-vault.js +0 -139
  98. package/dist/runtime/devtools-deterrent.d.ts +0 -7
  99. package/dist/runtime/devtools-deterrent.js +0 -27
  100. package/dist/runtime/integrity-guard.d.ts +0 -11
  101. package/dist/runtime/integrity-guard.js +0 -25
  102. package/dist/types.js +0 -1
@@ -0,0 +1,802 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/ast/index.ts
31
+ var ast_exports = {};
32
+ __export(ast_exports, {
33
+ computeFnv1aHash: () => computeFnv1aHash,
34
+ detectHotPaths: () => detectHotPaths,
35
+ transformJavaScript: () => transformJavaScript
36
+ });
37
+ module.exports = __toCommonJS(ast_exports);
38
+ var import_astring = require("astring");
39
+
40
+ // src/ast/hot-path-detector.ts
41
+ var acorn = __toESM(require("acorn"), 1);
42
+ var walk = __toESM(require("acorn-walk"), 1);
43
+ var ARRAY_HOF_METHODS = /* @__PURE__ */ new Set([
44
+ "map",
45
+ "filter",
46
+ "reduce",
47
+ "forEach",
48
+ "flatMap",
49
+ "find",
50
+ "some",
51
+ "every"
52
+ ]);
53
+ var UI_HOOK_OR_RENDER_CALLS = /* @__PURE__ */ new Set([
54
+ "useState",
55
+ "useEffect",
56
+ "useMemo",
57
+ "useCallback",
58
+ "useRef",
59
+ "useLayoutEffect",
60
+ "jsx",
61
+ "jsxs",
62
+ "_jsx",
63
+ "_jsxs",
64
+ "createElement",
65
+ "requestAnimationFrame"
66
+ ]);
67
+ var FUNCTION_NODE_TYPES = /* @__PURE__ */ new Set([
68
+ "FunctionDeclaration",
69
+ "FunctionExpression",
70
+ "ArrowFunctionExpression"
71
+ ]);
72
+ function parseJavaScriptAst(code) {
73
+ try {
74
+ return acorn.parse(code, {
75
+ ecmaVersion: "latest",
76
+ sourceType: "module",
77
+ allowReturnOutsideFunction: true
78
+ });
79
+ } catch {
80
+ try {
81
+ return acorn.parse(code, {
82
+ ecmaVersion: "latest",
83
+ sourceType: "script",
84
+ allowReturnOutsideFunction: true
85
+ });
86
+ } catch {
87
+ return null;
88
+ }
89
+ }
90
+ }
91
+ function getFunctionLabel(node, ancestors) {
92
+ if (node.id && typeof node.id.name === "string") {
93
+ return node.id.name;
94
+ }
95
+ const parent = ancestors[ancestors.length - 2];
96
+ if (parent) {
97
+ if (parent.type === "VariableDeclarator" && parent.id?.type === "Identifier") {
98
+ return parent.id.name;
99
+ }
100
+ if (parent.type === "Property" && parent.key?.type === "Identifier") {
101
+ return parent.key.name;
102
+ }
103
+ if (parent.type === "MethodDefinition" && parent.key?.type === "Identifier") {
104
+ return parent.key.name;
105
+ }
106
+ if (parent.type === "AssignmentExpression" && parent.left?.type === "Identifier") {
107
+ return parent.left.name;
108
+ }
109
+ }
110
+ return `anonymous_${node.start}`;
111
+ }
112
+ function isPascalCaseComponent(name) {
113
+ return /^[A-Z][a-zA-Z0-9]*$/.test(name);
114
+ }
115
+ function analyzeAstHotPaths(ast) {
116
+ const hotFunctionNodes = /* @__PURE__ */ new WeakSet();
117
+ const coldFunctionNodes = /* @__PURE__ */ new WeakSet();
118
+ const allFunctions = [];
119
+ const fnByName = /* @__PURE__ */ new Map();
120
+ const callerToCallees = /* @__PURE__ */ new Map();
121
+ walk.ancestor(ast, {
122
+ FunctionDeclaration(node, _state, ancestors) {
123
+ const name = getFunctionLabel(node, ancestors);
124
+ allFunctions.push({ node, name });
125
+ fnByName.set(name, node);
126
+ if (isPascalCaseComponent(name)) {
127
+ hotFunctionNodes.add(node);
128
+ }
129
+ },
130
+ FunctionExpression(node, _state, ancestors) {
131
+ const name = getFunctionLabel(node, ancestors);
132
+ allFunctions.push({ node, name });
133
+ fnByName.set(name, node);
134
+ if (isPascalCaseComponent(name)) {
135
+ hotFunctionNodes.add(node);
136
+ }
137
+ },
138
+ ArrowFunctionExpression(node, _state, ancestors) {
139
+ const name = getFunctionLabel(node, ancestors);
140
+ allFunctions.push({ node, name });
141
+ fnByName.set(name, node);
142
+ if (isPascalCaseComponent(name)) {
143
+ hotFunctionNodes.add(node);
144
+ }
145
+ },
146
+ CallExpression(node, _state, ancestors) {
147
+ const callee = node.callee;
148
+ let calleeName = "";
149
+ let memberProp = "";
150
+ if (callee?.type === "Identifier") {
151
+ calleeName = callee.name;
152
+ for (let i = ancestors.length - 1; i >= 0; i--) {
153
+ if (FUNCTION_NODE_TYPES.has(ancestors[i].type)) {
154
+ let set = callerToCallees.get(ancestors[i]);
155
+ if (!set) {
156
+ set = /* @__PURE__ */ new Set();
157
+ callerToCallees.set(ancestors[i], set);
158
+ }
159
+ set.add(calleeName);
160
+ break;
161
+ }
162
+ }
163
+ } else if (callee?.type === "MemberExpression" && !callee.computed && callee.property?.type === "Identifier") {
164
+ memberProp = callee.property.name;
165
+ }
166
+ if (ARRAY_HOF_METHODS.has(memberProp) || calleeName === "requestAnimationFrame" || memberProp === "requestAnimationFrame") {
167
+ for (const arg of node.arguments || []) {
168
+ if (FUNCTION_NODE_TYPES.has(arg.type)) {
169
+ hotFunctionNodes.add(arg);
170
+ }
171
+ }
172
+ }
173
+ if (UI_HOOK_OR_RENDER_CALLS.has(calleeName) || UI_HOOK_OR_RENDER_CALLS.has(memberProp)) {
174
+ for (let i = ancestors.length - 1; i >= 0; i--) {
175
+ if (FUNCTION_NODE_TYPES.has(ancestors[i].type)) {
176
+ hotFunctionNodes.add(ancestors[i]);
177
+ break;
178
+ }
179
+ }
180
+ }
181
+ },
182
+ ForStatement(_node, _state, ancestors) {
183
+ markEnclosingFunctionHot(ancestors, hotFunctionNodes);
184
+ },
185
+ ForInStatement(_node, _state, ancestors) {
186
+ markEnclosingFunctionHot(ancestors, hotFunctionNodes);
187
+ },
188
+ ForOfStatement(_node, _state, ancestors) {
189
+ markEnclosingFunctionHot(ancestors, hotFunctionNodes);
190
+ },
191
+ WhileStatement(_node, _state, ancestors) {
192
+ markEnclosingFunctionHot(ancestors, hotFunctionNodes);
193
+ },
194
+ DoWhileStatement(_node, _state, ancestors) {
195
+ markEnclosingFunctionHot(ancestors, hotFunctionNodes);
196
+ }
197
+ });
198
+ let changed = true;
199
+ while (changed) {
200
+ changed = false;
201
+ for (const [callerNode, calleeNames] of callerToCallees.entries()) {
202
+ if (hotFunctionNodes.has(callerNode)) continue;
203
+ for (const cName of calleeNames) {
204
+ const targetNode = fnByName.get(cName);
205
+ if (targetNode && hotFunctionNodes.has(targetNode)) {
206
+ hotFunctionNodes.add(callerNode);
207
+ changed = true;
208
+ break;
209
+ }
210
+ }
211
+ }
212
+ }
213
+ const hotFunctionsSkipped = [];
214
+ const coldFunctionsProtected = [];
215
+ for (const fn of allFunctions) {
216
+ if (hotFunctionNodes.has(fn.node)) {
217
+ hotFunctionsSkipped.push(fn.name);
218
+ } else {
219
+ coldFunctionNodes.add(fn.node);
220
+ coldFunctionsProtected.push(fn.name);
221
+ }
222
+ }
223
+ return {
224
+ report: {
225
+ totalFunctions: allFunctions.length,
226
+ hotFunctionsSkipped,
227
+ coldFunctionsProtected
228
+ },
229
+ hotFunctionNodes,
230
+ coldFunctionNodes
231
+ };
232
+ }
233
+ function markEnclosingFunctionHot(ancestors, hotSet) {
234
+ for (let i = ancestors.length - 1; i >= 0; i--) {
235
+ if (FUNCTION_NODE_TYPES.has(ancestors[i].type)) {
236
+ hotSet.add(ancestors[i]);
237
+ break;
238
+ }
239
+ }
240
+ }
241
+ function detectHotPaths(code) {
242
+ const ast = parseJavaScriptAst(code);
243
+ if (!ast) {
244
+ return {
245
+ totalFunctions: 0,
246
+ hotFunctionsSkipped: [],
247
+ coldFunctionsProtected: []
248
+ };
249
+ }
250
+ return analyzeAstHotPaths(ast).report;
251
+ }
252
+
253
+ // src/ast/string-vault.ts
254
+ var acorn2 = __toESM(require("acorn"), 1);
255
+ var walk2 = __toESM(require("acorn-walk"), 1);
256
+ var DIRECTIVE_STRINGS = /* @__PURE__ */ new Set([
257
+ "use strict",
258
+ "use client",
259
+ "use server",
260
+ "use asm"
261
+ ]);
262
+ var HELPER_TEMPLATE = acorn2.parse(
263
+ `const _ = [].map(function(a) {
264
+ var s = "";
265
+ for (var j = 0; j < a.length; j++) {
266
+ s += String.fromCharCode(a.charCodeAt(j) ^ (((0 ^ ((j & 1) * 0)) & 30) | 1));
267
+ }
268
+ return s;
269
+ });`,
270
+ { ecmaVersion: "latest", sourceType: "script" }
271
+ ).body[0];
272
+ function createVaultHelperAst(cacheVarName, encryptedPayloads, mask, step) {
273
+ const node = structuredClone(HELPER_TEMPLATE);
274
+ node.declarations[0].id.name = cacheVarName;
275
+ node.declarations[0].init.callee.object.elements = encryptedPayloads.map(
276
+ (str) => ({
277
+ type: "Literal",
278
+ value: str,
279
+ raw: JSON.stringify(str)
280
+ })
281
+ );
282
+ const fn = node.declarations[0].init.arguments[0];
283
+ const binaryXor = fn.body.body[1].body.body[0].expression.right.arguments[0];
284
+ const innerLeft = binaryXor.right.left.left;
285
+ innerLeft.left.value = mask;
286
+ innerLeft.left.raw = String(mask);
287
+ innerLeft.right.right.value = step;
288
+ innerLeft.right.right.raw = String(step);
289
+ return node;
290
+ }
291
+ function computeFnv1aHash(input, seed = 2166136261) {
292
+ let hash = seed >>> 0;
293
+ for (let i = 0; i < input.length; i++) {
294
+ hash ^= input.charCodeAt(i);
295
+ hash = Math.imul(hash, 16777619) >>> 0;
296
+ }
297
+ return hash >>> 0;
298
+ }
299
+ function encodeStringWithSeed(str, mask, step) {
300
+ let out = "";
301
+ for (let i = 0; i < str.length; i++) {
302
+ const code = str.charCodeAt(i);
303
+ const k = (mask ^ (i & 1) * step) & 30 | 1;
304
+ out += String.fromCharCode(code ^ k);
305
+ }
306
+ return out;
307
+ }
308
+ function applyStringVault(ast, seed = 2654435769, minStringLength = 4) {
309
+ const suffix = ((seed >>> 0) % 255).toString(36);
310
+ const cacheVarName = `_uC${suffix}`;
311
+ const mask = seed >>> 0 & 30 | 3;
312
+ const step = (seed >>> 5 & 7) * 2 + 3;
313
+ const stringToIndex = /* @__PURE__ */ new Map();
314
+ const encryptedPayloads = [];
315
+ const targetsToReplace = [];
316
+ walk2.ancestor(ast, {
317
+ Literal(node, _state, ancestors) {
318
+ if (typeof node.value !== "string") return;
319
+ const val = node.value;
320
+ if (val.length < minStringLength) return;
321
+ if (DIRECTIVE_STRINGS.has(val)) return;
322
+ const parent = ancestors[ancestors.length - 2];
323
+ if (!parent) return;
324
+ if (parent.type === "ExpressionStatement" && parent.directive) return;
325
+ if (parent.type === "ImportDeclaration" || parent.type === "ExportNamedDeclaration" || parent.type === "ExportAllDeclaration" || parent.type === "ImportExpression") {
326
+ if (parent.source === node) return;
327
+ }
328
+ if ((parent.type === "Property" || parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") && parent.key === node && !parent.computed) {
329
+ return;
330
+ }
331
+ if (parent.type === "ImportAttribute" || parent.type === "ImportSpecifier" || parent.type === "ExportSpecifier") {
332
+ return;
333
+ }
334
+ let idx = stringToIndex.get(val);
335
+ if (idx === void 0) {
336
+ idx = encryptedPayloads.length;
337
+ stringToIndex.set(val, idx);
338
+ encryptedPayloads.push(encodeStringWithSeed(val, mask, step));
339
+ }
340
+ targetsToReplace.push({ node });
341
+ }
342
+ });
343
+ if (targetsToReplace.length === 0 || encryptedPayloads.length === 0) {
344
+ return {
345
+ encryptedStringsCount: 0,
346
+ integrityToken: computeFnv1aHash("empty", seed)
347
+ };
348
+ }
349
+ for (const { node } of targetsToReplace) {
350
+ const idx = stringToIndex.get(node.value);
351
+ node.type = "MemberExpression";
352
+ node.object = {
353
+ type: "Identifier",
354
+ name: cacheVarName
355
+ };
356
+ node.property = {
357
+ type: "Literal",
358
+ value: idx,
359
+ raw: String(idx)
360
+ };
361
+ node.computed = true;
362
+ node.optional = false;
363
+ delete node.value;
364
+ delete node.raw;
365
+ }
366
+ const serializedTable = JSON.stringify(encryptedPayloads);
367
+ const integrityToken = computeFnv1aHash(serializedTable, seed);
368
+ const helperStmt = createVaultHelperAst(
369
+ cacheVarName,
370
+ encryptedPayloads,
371
+ mask,
372
+ step
373
+ );
374
+ let insertIdx = 0;
375
+ while (insertIdx < ast.body.length) {
376
+ const stmt = ast.body[insertIdx];
377
+ const isDirective = stmt.type === "ExpressionStatement" && (stmt.directive || stmt.expression?.type === "Literal" && typeof stmt.expression.value === "string" && DIRECTIVE_STRINGS.has(stmt.expression.value));
378
+ if (isDirective || stmt.type === "ImportDeclaration") {
379
+ insertIdx++;
380
+ } else {
381
+ break;
382
+ }
383
+ }
384
+ ast.body.splice(insertIdx, 0, helperStmt);
385
+ return {
386
+ encryptedStringsCount: encryptedPayloads.length,
387
+ integrityToken
388
+ };
389
+ }
390
+
391
+ // src/ast/polymorphic-mangler.ts
392
+ var walk3 = __toESM(require("acorn-walk"), 1);
393
+ var RESERVED_IDENTIFIERS = /* @__PURE__ */ new Set([
394
+ "arguments",
395
+ "undefined",
396
+ "NaN",
397
+ "Infinity",
398
+ "window",
399
+ "document",
400
+ "globalThis",
401
+ "self",
402
+ "console",
403
+ "Math",
404
+ "JSON",
405
+ "Object",
406
+ "Array",
407
+ "String",
408
+ "Number",
409
+ "Boolean",
410
+ "Symbol",
411
+ "BigInt",
412
+ "Promise",
413
+ "Map",
414
+ "Set",
415
+ "WeakMap",
416
+ "WeakSet",
417
+ "Error",
418
+ "TypeError",
419
+ "RangeError",
420
+ "SyntaxError",
421
+ "RegExp",
422
+ "Date",
423
+ "Reflect",
424
+ "Proxy",
425
+ "Intl",
426
+ "eval",
427
+ "process",
428
+ "Buffer",
429
+ "require",
430
+ "module",
431
+ "exports",
432
+ "React"
433
+ ]);
434
+ var FUNCTION_TYPES = /* @__PURE__ */ new Set([
435
+ "FunctionDeclaration",
436
+ "FunctionExpression",
437
+ "ArrowFunctionExpression"
438
+ ]);
439
+ function collectPatternIdentifiers(pattern, out) {
440
+ if (!pattern) return;
441
+ switch (pattern.type) {
442
+ case "Identifier":
443
+ out.push(pattern);
444
+ break;
445
+ case "AssignmentPattern":
446
+ collectPatternIdentifiers(pattern.left, out);
447
+ break;
448
+ case "RestElement":
449
+ collectPatternIdentifiers(pattern.argument, out);
450
+ break;
451
+ case "ArrayPattern":
452
+ for (const el of pattern.elements || []) {
453
+ if (el) collectPatternIdentifiers(el, out);
454
+ }
455
+ break;
456
+ case "ObjectPattern":
457
+ for (const prop of pattern.properties || []) {
458
+ if (prop.type === "Property") {
459
+ if (prop.shorthand) {
460
+ prop.shorthand = false;
461
+ prop.key = { ...prop.key };
462
+ }
463
+ collectPatternIdentifiers(prop.value, out);
464
+ } else if (prop.type === "RestElement") {
465
+ collectPatternIdentifiers(prop.argument, out);
466
+ }
467
+ }
468
+ break;
469
+ }
470
+ }
471
+ function applyPolymorphicMangler(ast, seed = 2654435769) {
472
+ const scopeMap = /* @__PURE__ */ new Map();
473
+ const scopeDepthMap = /* @__PURE__ */ new Map();
474
+ let counter = 0;
475
+ function makeScopedMangledName(scopeDepth, localIndex, usedValues) {
476
+ counter++;
477
+ let salt = 0;
478
+ while (true) {
479
+ const h = computeFnv1aHash(`s${scopeDepth}:i${localIndex}:${salt}`, seed);
480
+ const candidate = `_0x${((h & 31) + localIndex + salt).toString(36)}`;
481
+ if (!usedValues.has(candidate)) {
482
+ return candidate;
483
+ }
484
+ salt++;
485
+ }
486
+ }
487
+ function countFunctionDepth(ancestors) {
488
+ let depth = 0;
489
+ for (let i = 0; i < ancestors.length; i++) {
490
+ if (FUNCTION_TYPES.has(ancestors[i].type)) {
491
+ depth++;
492
+ }
493
+ }
494
+ return Math.max(1, depth);
495
+ }
496
+ function findEnclosingFunction(ancestors) {
497
+ for (let i = ancestors.length - 1; i >= 0; i--) {
498
+ if (FUNCTION_TYPES.has(ancestors[i].type)) {
499
+ return ancestors[i];
500
+ }
501
+ }
502
+ return null;
503
+ }
504
+ function registerBindingAndMutateDeclSite(idNode, bindings, scopeDepth) {
505
+ const origName = idNode.name;
506
+ if (RESERVED_IDENTIFIERS.has(origName) || origName.startsWith("_u") || origName.startsWith("_0x")) {
507
+ return;
508
+ }
509
+ let mangled = bindings.get(origName);
510
+ if (!mangled) {
511
+ const usedValues = new Set(bindings.values());
512
+ mangled = makeScopedMangledName(scopeDepth, bindings.size, usedValues);
513
+ bindings.set(origName, mangled);
514
+ }
515
+ idNode.name = mangled;
516
+ }
517
+ function registerFunctionParams(fnNode, ancestors) {
518
+ let bindings = scopeMap.get(fnNode);
519
+ const depth = countFunctionDepth(ancestors);
520
+ scopeDepthMap.set(fnNode, depth);
521
+ if (!bindings) {
522
+ bindings = /* @__PURE__ */ new Map();
523
+ scopeMap.set(fnNode, bindings);
524
+ }
525
+ for (const param of fnNode.params || []) {
526
+ const idNodes = [];
527
+ collectPatternIdentifiers(param, idNodes);
528
+ for (const idNode of idNodes) {
529
+ registerBindingAndMutateDeclSite(idNode, bindings, depth);
530
+ }
531
+ }
532
+ }
533
+ walk3.ancestor(ast, {
534
+ FunctionDeclaration(node, _state, ancestors) {
535
+ registerFunctionParams(node, ancestors);
536
+ },
537
+ FunctionExpression(node, _state, ancestors) {
538
+ registerFunctionParams(node, ancestors);
539
+ },
540
+ ArrowFunctionExpression(node, _state, ancestors) {
541
+ registerFunctionParams(node, ancestors);
542
+ },
543
+ VariableDeclaration(node, _state, ancestors) {
544
+ const fnScope = findEnclosingFunction(ancestors);
545
+ if (!fnScope) return;
546
+ let bindings = scopeMap.get(fnScope);
547
+ const depth = scopeDepthMap.get(fnScope) ?? countFunctionDepth(ancestors);
548
+ if (!bindings) {
549
+ bindings = /* @__PURE__ */ new Map();
550
+ scopeMap.set(fnScope, bindings);
551
+ }
552
+ for (const decl of node.declarations || []) {
553
+ const idNodes = [];
554
+ collectPatternIdentifiers(decl.id, idNodes);
555
+ for (const idNode of idNodes) {
556
+ registerBindingAndMutateDeclSite(idNode, bindings, depth);
557
+ }
558
+ }
559
+ }
560
+ });
561
+ if (counter === 0) return 0;
562
+ walk3.ancestor(ast, {
563
+ AssignmentExpression(node, _state, ancestors) {
564
+ const idNodes = [];
565
+ collectPatternIdentifiers(node.left, idNodes);
566
+ for (const idNode of idNodes) {
567
+ const resolved = resolveMangledName(idNode.name, ancestors, scopeMap);
568
+ if (resolved) {
569
+ idNode.name = resolved;
570
+ }
571
+ }
572
+ },
573
+ ForInStatement(node, _state, ancestors) {
574
+ if (node.left && node.left.type !== "VariableDeclaration") {
575
+ const idNodes = [];
576
+ collectPatternIdentifiers(node.left, idNodes);
577
+ for (const idNode of idNodes) {
578
+ const resolved = resolveMangledName(idNode.name, ancestors, scopeMap);
579
+ if (resolved) idNode.name = resolved;
580
+ }
581
+ }
582
+ },
583
+ ForOfStatement(node, _state, ancestors) {
584
+ if (node.left && node.left.type !== "VariableDeclaration") {
585
+ const idNodes = [];
586
+ collectPatternIdentifiers(node.left, idNodes);
587
+ for (const idNode of idNodes) {
588
+ const resolved = resolveMangledName(idNode.name, ancestors, scopeMap);
589
+ if (resolved) idNode.name = resolved;
590
+ }
591
+ }
592
+ },
593
+ Property(node, _state, ancestors) {
594
+ if (node.shorthand && node.value?.type === "Identifier") {
595
+ const resolved = resolveMangledName(node.value.name, ancestors, scopeMap);
596
+ if (resolved) {
597
+ node.shorthand = false;
598
+ node.key = { type: "Identifier", name: node.value.name };
599
+ }
600
+ }
601
+ },
602
+ Identifier(node, _state, ancestors) {
603
+ const parent = ancestors[ancestors.length - 2];
604
+ if (!parent) return;
605
+ if ((parent.type === "FunctionDeclaration" || parent.type === "FunctionExpression" || parent.type === "ClassDeclaration" || parent.type === "ClassExpression") && parent.id === node) {
606
+ return;
607
+ }
608
+ if (parent.type === "MemberExpression" && parent.property === node && !parent.computed) {
609
+ return;
610
+ }
611
+ if ((parent.type === "Property" || parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") && parent.key === node && !parent.computed) {
612
+ return;
613
+ }
614
+ if (parent.type === "LabeledStatement" || parent.type === "BreakStatement" || parent.type === "ContinueStatement" || parent.type === "ImportSpecifier" || parent.type === "ImportDefaultSpecifier" || parent.type === "ImportNamespaceSpecifier" || parent.type === "ExportSpecifier") {
615
+ return;
616
+ }
617
+ const resolved = resolveMangledName(node.name, ancestors, scopeMap);
618
+ if (resolved) {
619
+ node.name = resolved;
620
+ }
621
+ }
622
+ });
623
+ return counter;
624
+ }
625
+ function resolveMangledName(name, ancestors, scopeMap) {
626
+ for (let i = ancestors.length - 1; i >= 0; i--) {
627
+ const anc = ancestors[i];
628
+ const bindings = scopeMap.get(anc);
629
+ if (bindings && bindings.has(name)) {
630
+ return bindings.get(name);
631
+ }
632
+ }
633
+ return null;
634
+ }
635
+
636
+ // src/ast/cold-flow-guard.ts
637
+ var walk4 = __toESM(require("acorn-walk"), 1);
638
+ function createOpaqueGuardStatement(seed, fnIndex) {
639
+ const a = (seed >>> 0) + Math.imul(fnIndex + 1, 73244475) & 65535;
640
+ const b = (a ^ 4951) & 65535;
641
+ const wrongVal = (a ^ b) & 7 ^ 5;
642
+ return {
643
+ type: "IfStatement",
644
+ test: {
645
+ type: "BinaryExpression",
646
+ operator: "===",
647
+ left: {
648
+ type: "BinaryExpression",
649
+ operator: "&",
650
+ left: {
651
+ type: "BinaryExpression",
652
+ operator: "^",
653
+ left: { type: "Literal", value: a, raw: String(a) },
654
+ right: { type: "Literal", value: b, raw: String(b) }
655
+ },
656
+ right: { type: "Literal", value: 7, raw: "7" }
657
+ },
658
+ right: { type: "Literal", value: wrongVal, raw: String(wrongVal) }
659
+ },
660
+ consequent: {
661
+ type: "ReturnStatement",
662
+ argument: null
663
+ },
664
+ alternate: null
665
+ };
666
+ }
667
+ function applyColdFlowGuard(ast, coldFunctionNodes, seed = 2654435769) {
668
+ let guardedCount = 0;
669
+ function maybeInjectGuard(node) {
670
+ if (!coldFunctionNodes.has(node)) return;
671
+ if (!node.body || node.body.type !== "BlockStatement") return;
672
+ guardedCount++;
673
+ const guardStmt = createOpaqueGuardStatement(seed, guardedCount);
674
+ let insertIdx = 0;
675
+ while (insertIdx < node.body.body.length && node.body.body[insertIdx].type === "ExpressionStatement" && node.body.body[insertIdx].directive) {
676
+ insertIdx++;
677
+ }
678
+ node.body.body.splice(insertIdx, 0, guardStmt);
679
+ }
680
+ walk4.simple(ast, {
681
+ FunctionDeclaration: maybeInjectGuard,
682
+ FunctionExpression: maybeInjectGuard,
683
+ ArrowFunctionExpression: maybeInjectGuard
684
+ });
685
+ return guardedCount;
686
+ }
687
+
688
+ // src/runtime/integrity-guard.ts
689
+ var FNV_OFFSET_BASIS = 2166136261;
690
+ var FNV_PRIME = 16777619;
691
+ function computeIntegrityHash(source, seed = 0) {
692
+ let hash = (FNV_OFFSET_BASIS ^ seed >>> 0) >>> 0;
693
+ for (let i = 0; i < source.length; i++) {
694
+ hash ^= source.charCodeAt(i);
695
+ hash = Math.imul(hash, FNV_PRIME) >>> 0;
696
+ }
697
+ return hash >>> 0;
698
+ }
699
+
700
+ // src/runtime/devtools-deterrent.ts
701
+ function deriveIntegrityFnName(seed) {
702
+ const hash = computeIntegrityHash(`unpeek:fn:${seed}`, seed);
703
+ return `_u$${hash.toString(36)}`;
704
+ }
705
+ function deriveLocalVar(label, seed) {
706
+ const hash = computeIntegrityHash(`unpeek:var:${label}:${seed}`, seed) & 1048575;
707
+ return `_${label}${hash.toString(36)}`;
708
+ }
709
+ function createDeterrentSnippet(config) {
710
+ const seed = config.seed >>> 0;
711
+ const deterrentMode = config.deterrentMode ?? "passive";
712
+ const fnName = deriveIntegrityFnName(seed);
713
+ const strVar = deriveLocalVar("s", seed);
714
+ const tamperVar = deriveLocalVar("t", seed);
715
+ const noopVar = deriveLocalVar("n", seed);
716
+ const methodsVar = deriveLocalVar("m", seed);
717
+ const idxVar = deriveLocalVar("i", seed);
718
+ const errVar = deriveLocalVar("e", seed);
719
+ const gradualConsoleSilence = deterrentMode === "gradual" ? `if(typeof console!=='undefined'){var ${noopVar}=function(){},${methodsVar}=['log','debug','info','table','dir'];for(var ${idxVar}=0;${idxVar}<${methodsVar}.length;${idxVar}++){try{console[${methodsVar}[${idxVar}]]=${noopVar};}catch(${errVar}){}}}` : "";
720
+ const tamperDispatch = `if(typeof window.dispatchEvent==='function'&&typeof CustomEvent==='function'){try{window.dispatchEvent(new CustomEvent('unpeek:tamper'));}catch(${errVar}){}}`;
721
+ return `(function ${fnName}(){if(typeof window!=='undefined'){try{var ${strVar}=Function.prototype.toString,${tamperVar}=${strVar}.call(${strVar}).indexOf('[native code]')===-1||${strVar}.call(${fnName}).indexOf('\\n')!==-1||${strVar}.call(${fnName}).indexOf('\\r')!==-1;if(${tamperVar}){window.__unpeek_tampered=!0;${tamperDispatch}${gradualConsoleSilence}}}catch(${errVar}){}}})();`;
722
+ }
723
+
724
+ // src/runtime/index.ts
725
+ function generateRuntimeShield(config) {
726
+ const preambleCode = createDeterrentSnippet(config);
727
+ const integrityCheckFnName = deriveIntegrityFnName(config.seed);
728
+ const expectedHash = config.expectedIntegrityHash !== void 0 ? config.expectedIntegrityHash >>> 0 : computeIntegrityHash(preambleCode, config.seed);
729
+ return {
730
+ preambleCode,
731
+ integrityCheckFnName,
732
+ expectedHash
733
+ };
734
+ }
735
+
736
+ // src/ast/index.ts
737
+ function transformJavaScript(code, options = {}) {
738
+ const seed = options.seed ?? 2654435769;
739
+ const minStringLength = options.minStringLength ?? 4;
740
+ if (!code || !code.trim()) {
741
+ return {
742
+ code,
743
+ encryptedStringsCount: 0,
744
+ mangledSymbolsCount: 0,
745
+ hotPathReport: {
746
+ totalFunctions: 0,
747
+ hotFunctionsSkipped: [],
748
+ coldFunctionsProtected: []
749
+ },
750
+ integrityToken: computeFnv1aHash("", seed)
751
+ };
752
+ }
753
+ const ast = parseJavaScriptAst(code);
754
+ if (!ast) {
755
+ return {
756
+ code,
757
+ encryptedStringsCount: 0,
758
+ mangledSymbolsCount: 0,
759
+ hotPathReport: {
760
+ totalFunctions: 0,
761
+ hotFunctionsSkipped: [],
762
+ coldFunctionsProtected: []
763
+ },
764
+ integrityToken: computeFnv1aHash(code, seed)
765
+ };
766
+ }
767
+ const { report: hotPathReport, coldFunctionNodes } = analyzeAstHotPaths(ast);
768
+ applyColdFlowGuard(ast, coldFunctionNodes, seed);
769
+ const mangledSymbolsCount = applyPolymorphicMangler(ast, seed);
770
+ const { encryptedStringsCount, integrityToken } = applyStringVault(
771
+ ast,
772
+ seed,
773
+ minStringLength
774
+ );
775
+ const outputCode = (0, import_astring.generate)(ast, { indent: "", lineEnd: "" });
776
+ let finalCode = outputCode;
777
+ if (options.injectRuntimeShield) {
778
+ const shield = generateRuntimeShield({
779
+ seed,
780
+ deterrentMode: options.deterrentMode ?? "gradual",
781
+ expectedIntegrityHash: integrityToken
782
+ });
783
+ if (shield.preambleCode) {
784
+ finalCode = `${shield.preambleCode}
785
+ ${finalCode}`;
786
+ }
787
+ }
788
+ return {
789
+ code: finalCode,
790
+ encryptedStringsCount,
791
+ mangledSymbolsCount,
792
+ hotPathReport,
793
+ integrityToken
794
+ };
795
+ }
796
+ // Annotate the CommonJS export names for ESM import in node:
797
+ 0 && (module.exports = {
798
+ computeFnv1aHash,
799
+ detectHotPaths,
800
+ transformJavaScript
801
+ });
802
+ //# sourceMappingURL=index.cjs.map