unpeek 4.0.0 → 4.1.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 (64) hide show
  1. package/README.md +21 -12
  2. package/README.tr.md +20 -11
  3. package/dist/adapters/esbuild.cjs +5 -5
  4. package/dist/adapters/esbuild.d.cts +1 -1
  5. package/dist/adapters/esbuild.d.ts +1 -1
  6. package/dist/adapters/esbuild.js +3 -3
  7. package/dist/adapters/next/adapter.cjs +6 -6
  8. package/dist/adapters/next/adapter.d.cts +1 -1
  9. package/dist/adapters/next/adapter.d.ts +1 -1
  10. package/dist/adapters/next/adapter.js +5 -5
  11. package/dist/adapters/next/index.cjs +6 -6
  12. package/dist/adapters/next/index.js +5 -5
  13. package/dist/adapters/rollup.cjs +5 -5
  14. package/dist/adapters/rollup.d.cts +1 -1
  15. package/dist/adapters/rollup.d.ts +1 -1
  16. package/dist/adapters/rollup.js +3 -3
  17. package/dist/adapters/rspack.cjs +5 -5
  18. package/dist/adapters/rspack.d.cts +1 -1
  19. package/dist/adapters/rspack.d.ts +1 -1
  20. package/dist/adapters/rspack.js +3 -3
  21. package/dist/adapters/vite.cjs +5 -5
  22. package/dist/adapters/vite.d.cts +1 -1
  23. package/dist/adapters/vite.d.ts +1 -1
  24. package/dist/adapters/vite.js +3 -3
  25. package/dist/adapters/webpack.cjs +5 -5
  26. package/dist/adapters/webpack.d.cts +1 -1
  27. package/dist/adapters/webpack.d.ts +1 -1
  28. package/dist/adapters/webpack.js +3 -3
  29. package/dist/browser.cjs +2 -2
  30. package/dist/browser.d.cts +4 -4
  31. package/dist/browser.d.ts +4 -4
  32. package/dist/browser.js +1 -1
  33. package/dist/chunk-32GLSJAW.js +614 -0
  34. package/dist/{chunk-W77DAC3H.js → chunk-6EWFL4LQ.js} +16 -0
  35. package/dist/{chunk-4FNZNIBW.js → chunk-6KLUNEKE.js} +2538 -547
  36. package/dist/chunk-AD6UFBPA.cjs +614 -0
  37. package/dist/{chunk-X6EETCO6.cjs → chunk-BQ2O6HM5.cjs} +16 -0
  38. package/dist/{chunk-ZG7BIAUI.cjs → chunk-FLZ4FSP5.cjs} +58 -17
  39. package/dist/{chunk-2JU3V7HW.js → chunk-HV47WJIR.js} +52 -11
  40. package/dist/{chunk-VG4Y26ZN.cjs → chunk-Q4DFRMAV.cjs} +53 -36
  41. package/dist/{chunk-HHC7BUCK.js → chunk-STTUFUDC.js} +114 -16
  42. package/dist/{chunk-YCRMTXOE.js → chunk-TOUYQ4N5.js} +30 -13
  43. package/dist/{chunk-KLYFNMKS.cjs → chunk-VLL4THTG.cjs} +2727 -736
  44. package/dist/{chunk-7HXLHLLQ.cjs → chunk-WYW5UOBE.cjs} +136 -38
  45. package/dist/cli/index.js +2240 -572
  46. package/dist/{config-Y6JwVGwX.d.cts → config-BFAZrfjQ.d.cts} +2 -0
  47. package/dist/{config-Y6JwVGwX.d.ts → config-BFAZrfjQ.d.ts} +2 -0
  48. package/dist/config.cjs +2 -2
  49. package/dist/config.d.cts +1 -1
  50. package/dist/config.d.ts +1 -1
  51. package/dist/config.js +1 -1
  52. package/dist/{index-COVHErnx.d.cts → index-Bo4S_VVM.d.cts} +1 -1
  53. package/dist/{index-0O1WSfVP.d.ts → index-CKdYVt_L.d.ts} +1 -1
  54. package/dist/index.cjs +186 -47
  55. package/dist/index.d.cts +6 -6
  56. package/dist/index.d.ts +6 -6
  57. package/dist/index.js +174 -35
  58. package/dist/plugins/unplugin.cjs +4 -4
  59. package/dist/plugins/unplugin.js +3 -3
  60. package/dist/{types-CMtZnV8C.d.ts → types-BZqvBhBI.d.ts} +4 -2
  61. package/dist/{types-D93PuOOl.d.cts → types-E4ugA4Oz.d.cts} +4 -2
  62. package/package.json +1 -1
  63. package/dist/chunk-3LWXEJU6.cjs +0 -1054
  64. package/dist/chunk-ADKRENAP.js +0 -1054
@@ -1,27 +1,27 @@
1
1
  import {
2
2
  loadUnpeekConfig
3
- } from "./chunk-W77DAC3H.js";
3
+ } from "./chunk-6EWFL4LQ.js";
4
4
  import {
5
- chainSourceMaps,
6
- computeDeterministicDebugId,
7
5
  detectTargetFramework,
8
6
  extractDebugId,
9
- flattenSourceMapSections,
10
7
  isWorkerOrServiceWorkerFile,
11
8
  relocateSourceMaps,
12
9
  replaceOrAppendDebugId,
13
- safeDecodeURIComponent,
14
10
  scanClientBundles,
15
- shiftSourceMapLines,
16
11
  stripDebugIdComments,
17
12
  stripSourceMapComments
18
- } from "./chunk-ADKRENAP.js";
13
+ } from "./chunk-32GLSJAW.js";
19
14
  import {
15
+ chainSourceMaps,
16
+ computeDeterministicDebugId,
20
17
  computeFnv1aHash,
21
18
  deriveWindowKeySymbol,
19
+ flattenSourceMapSections,
22
20
  generateRuntimeShield,
21
+ safeDecodeURIComponent,
22
+ shiftSourceMapLines,
23
23
  transformJavaScript
24
- } from "./chunk-4FNZNIBW.js";
24
+ } from "./chunk-6KLUNEKE.js";
25
25
  import {
26
26
  UnpeekError
27
27
  } from "./chunk-LA6J3BT3.js";
@@ -86,6 +86,8 @@ function readUnpeekNextOptionsFromEnv() {
86
86
  import fs from "fs";
87
87
  import path from "path";
88
88
  import zlib from "zlib";
89
+ import * as acorn from "acorn";
90
+ import { simple as walkSimple } from "acorn-walk";
89
91
  var ENTRY_PATTERN = /^(?:webpack|main|index|runtime|turbopack|pages\/_app|pages\/index)(?:[-._/]|$)/i;
90
92
  function normalizeManifestRel(fileRef) {
91
93
  const clean = fileRef.replace(/\\/g, "/").split("?")[0].split("#")[0].replace(/^\/+/, "");
@@ -237,6 +239,44 @@ function readOriginalSourceMapForFile(filePath, relPath, vaultDir, deferVaultWri
237
239
  }
238
240
  return void 0;
239
241
  }
242
+ function countPreExistingEvalCalls(code) {
243
+ const hits = [];
244
+ let ast;
245
+ try {
246
+ ast = acorn.parse(code, {
247
+ ecmaVersion: "latest",
248
+ sourceType: "module",
249
+ allowReturnOutsideFunction: true
250
+ });
251
+ } catch {
252
+ try {
253
+ ast = acorn.parse(code, {
254
+ ecmaVersion: "latest",
255
+ sourceType: "script",
256
+ allowReturnOutsideFunction: true
257
+ });
258
+ } catch {
259
+ return hits;
260
+ }
261
+ }
262
+ walkSimple(ast, {
263
+ CallExpression(node) {
264
+ if (node.callee.type === "Identifier") {
265
+ if (node.callee.name === "eval") {
266
+ hits.push("eval(...)");
267
+ } else if (node.callee.name === "Function") {
268
+ hits.push("Function(...)");
269
+ }
270
+ }
271
+ },
272
+ NewExpression(node) {
273
+ if (node.callee.type === "Identifier" && node.callee.name === "Function") {
274
+ hits.push("new Function(...)");
275
+ }
276
+ }
277
+ });
278
+ return hits;
279
+ }
240
280
  async function protectProject(options = {}) {
241
281
  const startTime = performance.now();
242
282
  const cwd = path.resolve(options.cwd ?? process.cwd());
@@ -244,7 +284,7 @@ async function protectProject(options = {}) {
244
284
  const config = await loadUnpeekConfig(cwd, effectiveConfigInput);
245
285
  const effectiveProfile = options.profile ?? config.profile ?? "recommended";
246
286
  const { framework, outDir } = detectTargetFramework(cwd, options.outDir, config);
247
- const seed = typeof options.seed === "number" ? options.seed : Math.floor(Math.random() * 2147483647) || 1597463007;
287
+ const seed = typeof options.seed === "number" && Number.isFinite(options.seed) ? options.seed : typeof config.seed === "number" && Number.isFinite(config.seed) ? config.seed : Math.floor(Math.random() * 2147483647) || 1597463007;
248
288
  const dryRun = Boolean(options.dryRun);
249
289
  const keepPrivateMaps = options.keepPrivateMaps ?? config.sourcemaps?.keepPrivate ?? true;
250
290
  const privateMapsDir = options.privateMapsDir ?? config.sourcemaps?.vaultDir ?? ".unpeek-maps";
@@ -289,6 +329,19 @@ async function protectProject(options = {}) {
289
329
  const allProtBufs = [];
290
330
  const stagedFiles = [];
291
331
  const pendingVaultMaps = [];
332
+ const preExistingEvalFiles = {};
333
+ let alreadyProtectedCount = 0;
334
+ const manifestPath = path.join(vaultResult.vaultDir, "manifest.json");
335
+ let existingManifest;
336
+ if (!dryRun && fs.existsSync(manifestPath)) {
337
+ try {
338
+ const parsed = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
339
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
340
+ existingManifest = parsed;
341
+ }
342
+ } catch {
343
+ }
344
+ }
292
345
  let originalGzipBytes = 0;
293
346
  let protectedGzipBytes = 0;
294
347
  let gzipDeltaPercent = 0;
@@ -309,6 +362,8 @@ async function protectProject(options = {}) {
309
362
  originalBytes += origBuf.byteLength;
310
363
  allOrigBufs.push(origBuf);
311
364
  const relPath = allRelPaths[i];
365
+ const originalMap = keepPrivateMaps ? readOriginalSourceMapForFile(filePath, relPath, vaultResult.vaultDir, deferVaultWrites) : void 0;
366
+ const preExistingHits = countPreExistingEvalCalls(codeToTransform);
312
367
  const isEntry = isEntryChunk(relPath, i, allRelPaths, manifestEntries, isWorkerTarget);
313
368
  const shouldInjectShield = injectRuntimeShield && isEntry;
314
369
  const fileSeed = computeFnv1aHash(`${relPath}:${i}`, seed);
@@ -321,14 +376,16 @@ async function protectProject(options = {}) {
321
376
  shieldCoupled: injectRuntimeShield,
322
377
  windowKeySymbol: masterSym,
323
378
  expectedDelta: masterShield?.expectedDelta,
379
+ expectedStateHash: masterShield?.expectedStateHash,
380
+ originalSourceMap: originalMap,
324
381
  deterrentMode,
325
382
  detectHeadless,
326
383
  aggressive,
327
384
  scrubPaths,
328
- config
385
+ config,
386
+ generateMap: keepPrivateMaps,
387
+ rootDir: cwd
329
388
  };
330
- transformOptions.generateMap = keepPrivateMaps;
331
- transformOptions.rootDir = cwd;
332
389
  const result = transformJavaScript(codeToTransform, transformOptions);
333
390
  if (result.skippedReason === "parse-error") {
334
391
  diagnostics.push({
@@ -338,6 +395,13 @@ async function protectProject(options = {}) {
338
395
  file: relPath
339
396
  });
340
397
  } else if (result.skippedReason === "already-protected") {
398
+ alreadyProtectedCount++;
399
+ const prevHits = existingManifest?.preExistingEvalFiles?.[relPath];
400
+ if (Array.isArray(prevHits) && prevHits.length > 0) {
401
+ preExistingEvalFiles[relPath] = prevHits;
402
+ } else if (preExistingHits.length > 0) {
403
+ preExistingEvalFiles[relPath] = preExistingHits;
404
+ }
341
405
  diagnostics.push({
342
406
  code: "ALREADY_PROTECTED",
343
407
  severity: "info",
@@ -351,6 +415,8 @@ async function protectProject(options = {}) {
351
415
  message: `File "${relPath}" is empty.`,
352
416
  file: relPath
353
417
  });
418
+ } else if (preExistingHits.length > 0) {
419
+ preExistingEvalFiles[relPath] = preExistingHits;
354
420
  }
355
421
  let finalCode = result.code;
356
422
  let preambleLineOffset = 0;
@@ -360,7 +426,6 @@ async function protectProject(options = {}) {
360
426
  preambleLineOffset = (prefix.match(/\n/g) ?? []).length;
361
427
  finalCode = `${prefix}${finalCode}`;
362
428
  }
363
- const originalMap = keepPrivateMaps ? readOriginalSourceMapForFile(filePath, relPath, vaultResult.vaultDir, deferVaultWrites) : void 0;
364
429
  const rawTransformMap = result.sourceMap;
365
430
  const shiftedTransformMap = rawTransformMap ? shiftSourceMapLines(rawTransformMap, preambleLineOffset) : void 0;
366
431
  let composedMap;
@@ -373,8 +438,9 @@ async function protectProject(options = {}) {
373
438
  }
374
439
  const originalMapDebugId = originalMap?.debugId ?? originalMap?.debug_id;
375
440
  const hadDebugId = Boolean(fileDebugId || originalMapDebugId || result.debugId);
441
+ const shouldMintDebugId = hadDebugId || keepPrivateMaps && !result.skippedReason && Boolean(composedMap || originalMap);
376
442
  let mintedDebugId;
377
- if (hadDebugId) {
443
+ if (shouldMintDebugId) {
378
444
  const codeWithoutDebugId = stripDebugIdComments(finalCode);
379
445
  mintedDebugId = computeDeterministicDebugId(
380
446
  codeWithoutDebugId,
@@ -437,8 +503,9 @@ async function protectProject(options = {}) {
437
503
  `${safeDecodeURIComponent(relPath)}.map`
438
504
  );
439
505
  const targetMapPath = fs.existsSync(vaultedMapPath) ? vaultedMapPath : fs.existsSync(decodedMapPath) ? decodedMapPath : vaultedMapPath;
440
- if (map && fs.existsSync(targetMapPath)) {
506
+ if (map) {
441
507
  try {
508
+ fs.mkdirSync(path.dirname(targetMapPath), { recursive: true });
442
509
  fs.writeFileSync(targetMapPath, JSON.stringify(map), "utf8");
443
510
  } catch {
444
511
  }
@@ -455,6 +522,34 @@ async function protectProject(options = {}) {
455
522
  for (const { tmpPath, finalPath } of stagedFiles) {
456
523
  fs.renameSync(tmpPath, finalPath);
457
524
  }
525
+ const relVault = path.relative(cwd, vaultResult.vaultDir);
526
+ const isSafeVaultDir = relVault === "" || !relVault.startsWith("..") && !path.isAbsolute(relVault);
527
+ if (isSafeVaultDir) {
528
+ const relOutDir = path.relative(cwd, outDir).replace(/\\/g, "/") || ".";
529
+ const manifestPayload = processedFiles > 0 && alreadyProtectedCount === processedFiles && existingManifest ? {
530
+ version: 1,
531
+ outDir: existingManifest.outDir ?? relOutDir,
532
+ originalGzipBytes: existingManifest.originalGzipBytes ?? originalGzipBytes,
533
+ protectedGzipBytes: existingManifest.protectedGzipBytes ?? protectedGzipBytes,
534
+ gzipDeltaPercent: existingManifest.gzipDeltaPercent ?? gzipDeltaPercent,
535
+ preExistingEvalFiles: {
536
+ ...existingManifest.preExistingEvalFiles ?? {},
537
+ ...preExistingEvalFiles
538
+ }
539
+ } : {
540
+ version: 1,
541
+ outDir: relOutDir,
542
+ originalGzipBytes,
543
+ protectedGzipBytes,
544
+ gzipDeltaPercent,
545
+ preExistingEvalFiles
546
+ };
547
+ try {
548
+ fs.mkdirSync(vaultResult.vaultDir, { recursive: true });
549
+ fs.writeFileSync(manifestPath, JSON.stringify(manifestPayload, null, 2), "utf8");
550
+ } catch {
551
+ }
552
+ }
458
553
  }
459
554
  } catch (error) {
460
555
  for (const { tmpPath } of stagedFiles) {
@@ -468,6 +563,7 @@ async function protectProject(options = {}) {
468
563
  throw error;
469
564
  }
470
565
  const elapsedMs = Math.max(1, Math.round(performance.now() - startTime));
566
+ const resolvedTier = options.tier ?? (effectiveProfile === "strict" || aggressive ? "Tier 3" : effectiveProfile === "minimal" ? "Tier 1" : config.tier ?? "Tier 2");
471
567
  return {
472
568
  framework,
473
569
  outDir,
@@ -484,8 +580,10 @@ async function protectProject(options = {}) {
484
580
  totalMangledSymbols,
485
581
  elapsedMs,
486
582
  seed,
487
- tier: aggressive ? "Tier 2" : "Tier 1",
583
+ tier: resolvedTier,
488
584
  aggressive,
585
+ deterrentMode,
586
+ detectHeadless,
489
587
  dockerIgnoreMissing: vaultResult.dockerIgnoreMissing,
490
588
  dryRun,
491
589
  profile: effectiveProfile,
@@ -1,19 +1,20 @@
1
1
  import {
2
- chainSourceMaps,
3
- computeDeterministicDebugId,
4
2
  extractDebugId,
5
- flattenSourceMapSections,
3
+ matchesGlobPattern,
6
4
  replaceOrAppendDebugId,
7
- shiftSourceMapLines,
8
5
  stripDebugIdComments,
9
6
  stripSourceMapComments
10
- } from "./chunk-ADKRENAP.js";
7
+ } from "./chunk-32GLSJAW.js";
11
8
  import {
9
+ chainSourceMaps,
10
+ computeDeterministicDebugId,
12
11
  computeFnv1aHash,
13
12
  deriveWindowKeySymbol,
13
+ flattenSourceMapSections,
14
14
  generateRuntimeShield,
15
+ shiftSourceMapLines,
15
16
  transformJavaScript
16
- } from "./chunk-4FNZNIBW.js";
17
+ } from "./chunk-6KLUNEKE.js";
17
18
 
18
19
  // src/plugins/unplugin.ts
19
20
  import fs from "fs";
@@ -33,6 +34,17 @@ function isExcludedClientAsset(fileName, config) {
33
34
  if (config?.target !== "worker" && SW_OR_WORKBOX_PATTERN.test(norm)) {
34
35
  return true;
35
36
  }
37
+ const cleanRel = norm.replace(/^\/+/, "");
38
+ if (config?.filter?.include && config.filter.include.length > 0) {
39
+ if (!config.filter.include.some((pattern) => matchesGlobPattern(cleanRel, pattern))) {
40
+ return true;
41
+ }
42
+ }
43
+ if (config?.filter?.exclude && config.filter.exclude.length > 0) {
44
+ if (config.filter.exclude.some((pattern) => matchesGlobPattern(cleanRel, pattern))) {
45
+ return true;
46
+ }
47
+ }
36
48
  return false;
37
49
  }
38
50
  function createWebpackRawSource(sources, content) {
@@ -52,7 +64,7 @@ function createWebpackRawSource(sources, content) {
52
64
  }
53
65
  var unpeekPlugin = createUnplugin((options = {}) => {
54
66
  const config = options.config;
55
- const baseSeed = typeof options.seed === "number" ? options.seed : Math.floor(Math.random() * 2147483647) || 322420463;
67
+ const baseSeed = typeof options.seed === "number" && Number.isFinite(options.seed) ? options.seed : typeof config?.seed === "number" && Number.isFinite(config.seed) ? config.seed : Math.floor(Math.random() * 2147483647) || 322420463;
56
68
  const deterrentMode = options.deterrentMode ?? config?.shield?.deterrentMode ?? "passive";
57
69
  const detectHeadless = options.detectHeadless ?? config?.shield?.detectHeadless ?? false;
58
70
  const injectRuntimeShield = options.injectRuntimeShield ?? true;
@@ -77,6 +89,7 @@ var unpeekPlugin = createUnplugin((options = {}) => {
77
89
  codeToTransform = stripSourceMapComments(rawCode).code;
78
90
  }
79
91
  const shouldInjectShield = injectRuntimeShield && isEntry;
92
+ const shouldGenerateMap = requestMap || Boolean(inputMap);
80
93
  const chunkSeed = computeFnv1aHash(fileName, baseSeed);
81
94
  const transformOptions = {
82
95
  seed: chunkSeed,
@@ -87,13 +100,15 @@ var unpeekPlugin = createUnplugin((options = {}) => {
87
100
  shieldCoupled: injectRuntimeShield,
88
101
  windowKeySymbol: masterSym,
89
102
  expectedDelta: masterShield?.expectedDelta,
103
+ expectedStateHash: masterShield?.expectedStateHash,
104
+ originalSourceMap: inputMap,
90
105
  deterrentMode,
91
106
  detectHeadless,
92
107
  aggressive,
93
- config
108
+ config,
109
+ generateMap: shouldGenerateMap,
110
+ rootDir: process.cwd()
94
111
  };
95
- transformOptions.generateMap = requestMap || Boolean(inputMap);
96
- transformOptions.rootDir = process.cwd();
97
112
  const result = transformJavaScript(codeToTransform, transformOptions);
98
113
  let finalCode = result.code;
99
114
  let preambleLineOffset = 0;
@@ -116,7 +131,8 @@ var unpeekPlugin = createUnplugin((options = {}) => {
116
131
  }
117
132
  const inputMapDebugId = inputMap?.debugId ?? inputMap?.debug_id;
118
133
  const hadDebugId = Boolean(fileDebugId || inputMapDebugId || result.debugId);
119
- if (hadDebugId) {
134
+ const shouldMintDebugId = hadDebugId || shouldGenerateMap && !result.skippedReason && Boolean(composedMap || inputMap);
135
+ if (shouldMintDebugId) {
120
136
  const codeWithoutDebugId = stripDebugIdComments(finalCode);
121
137
  const mintedDebugId = computeDeterministicDebugId(
122
138
  codeWithoutDebugId,
@@ -336,7 +352,9 @@ var unpeekPlugin = createUnplugin((options = {}) => {
336
352
  const jsOutCount = result.outputFiles.filter((f) => isSupportedJsAsset(f.path)).length;
337
353
  for (const outFile of result.outputFiles) {
338
354
  const normPath = outFile.path.replace(/\\/g, "/");
339
- if (!isSupportedJsAsset(normPath) || isExcludedClientAsset(normPath, config)) {
355
+ const relFromWork = path.relative(workDir, outFile.path).replace(/\\/g, "/");
356
+ const filterPath = relFromWork && !relFromWork.startsWith("..") && !path.isAbsolute(relFromWork) ? relFromWork : normPath;
357
+ if (!isSupportedJsAsset(normPath) || isExcludedClientAsset(filterPath, config)) {
340
358
  continue;
341
359
  }
342
360
  const mapFile = mapFilesByPath.get(`${outFile.path}.map`);
@@ -347,7 +365,6 @@ var unpeekPlugin = createUnplugin((options = {}) => {
347
365
  } catch {
348
366
  }
349
367
  }
350
- const relFromWork = path.relative(workDir, outFile.path).replace(/\\/g, "/");
351
368
  const isEntry = entryOutputs.size > 0 ? entryOutputs.has(outFile.path) || entryOutputs.has(relFromWork) || ENTRY_CHUNK_PATTERN.test(relFromWork) : ENTRY_CHUNK_PATTERN.test(relFromWork) || jsOutCount === 1;
352
369
  const res = transformChunk(
353
370
  outFile.text,