unpeek 2.0.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/README.md +30 -8
  2. package/README.tr.md +30 -8
  3. package/dist/adapters/esbuild.cjs +13 -0
  4. package/dist/{esbuild.d.cts → adapters/esbuild.d.cts} +2 -2
  5. package/dist/{esbuild.d.ts → adapters/esbuild.d.ts} +2 -2
  6. package/dist/adapters/esbuild.js +11 -0
  7. package/dist/adapters/next/adapter.cjs +42 -0
  8. package/dist/{next → adapters/next}/adapter.d.cts +4 -4
  9. package/dist/{next → adapters/next}/adapter.d.ts +4 -4
  10. package/dist/adapters/next/adapter.js +42 -0
  11. package/dist/adapters/next/index.cjs +15 -0
  12. package/dist/adapters/next/index.d.cts +53 -0
  13. package/dist/adapters/next/index.d.ts +53 -0
  14. package/dist/adapters/next/index.js +15 -0
  15. package/dist/adapters/rollup.cjs +13 -0
  16. package/dist/{rollup.d.cts → adapters/rollup.d.cts} +2 -2
  17. package/dist/{rollup.d.ts → adapters/rollup.d.ts} +2 -2
  18. package/dist/adapters/rollup.js +11 -0
  19. package/dist/adapters/rspack.cjs +12 -0
  20. package/dist/adapters/rspack.d.cts +13 -0
  21. package/dist/adapters/rspack.d.ts +11 -0
  22. package/dist/adapters/rspack.js +12 -0
  23. package/dist/adapters/vite.cjs +13 -0
  24. package/dist/{vite.d.cts → adapters/vite.d.cts} +2 -2
  25. package/dist/{vite.d.ts → adapters/vite.d.ts} +2 -2
  26. package/dist/adapters/vite.js +11 -0
  27. package/dist/adapters/webpack.cjs +13 -0
  28. package/dist/{webpack.d.cts → adapters/webpack.d.cts} +2 -2
  29. package/dist/{webpack.d.ts → adapters/webpack.d.ts} +2 -2
  30. package/dist/adapters/webpack.js +11 -0
  31. package/dist/browser.cjs +8 -5
  32. package/dist/browser.d.cts +41 -3
  33. package/dist/browser.d.ts +41 -3
  34. package/dist/browser.js +10 -7
  35. package/dist/{chunk-GAVI2C44.cjs → chunk-6TDCSIRZ.cjs} +76 -47
  36. package/dist/{chunk-5LCMI2TL.js → chunk-APWMNVAZ.js} +221 -32
  37. package/dist/{chunk-5QD6FZPB.js → chunk-BPRSCRUZ.js} +71 -42
  38. package/dist/{chunk-X5MKMFMX.js → chunk-DUK2SECY.js} +7 -7
  39. package/dist/chunk-FCF2EGPM.js +80 -0
  40. package/dist/{chunk-7YVEHJVM.cjs → chunk-I6GXEHFR.cjs} +241 -52
  41. package/dist/{chunk-LXP73HJC.cjs → chunk-IAD5DV3D.cjs} +1048 -213
  42. package/dist/chunk-IEBVL5BT.cjs +80 -0
  43. package/dist/{chunk-GZB7PFLY.js → chunk-IICVBTR2.js} +25 -62
  44. package/dist/{chunk-UMPUYLLZ.js → chunk-IZIWDJRF.js} +936 -101
  45. package/dist/chunk-L6BOM5VS.cjs +40 -0
  46. package/dist/{chunk-OOXSZTRV.js → chunk-LA6J3BT3.js} +26 -1
  47. package/dist/{chunk-24K5NDXH.cjs → chunk-ONM2CSTU.cjs} +45 -82
  48. package/dist/{chunk-5M6Z7ZFT.cjs → chunk-RXUY3MPH.cjs} +10 -10
  49. package/dist/cli/index.js +7309 -32
  50. package/dist/{types-BBSRUEab.d.cts → config-CfXY_iDD.d.cts} +44 -86
  51. package/dist/{types-BBSRUEab.d.ts → config-CfXY_iDD.d.ts} +44 -86
  52. package/dist/config.cjs +4 -16
  53. package/dist/config.d.cts +1 -12
  54. package/dist/config.d.ts +1 -12
  55. package/dist/config.js +5 -17
  56. package/dist/index-CjRTNPlj.d.cts +46 -0
  57. package/dist/index-Cm1IloVm.d.ts +46 -0
  58. package/dist/index.cjs +636 -9
  59. package/dist/index.d.cts +9 -17
  60. package/dist/index.d.ts +9 -17
  61. package/dist/index.js +638 -11
  62. package/dist/plugins/unplugin.cjs +20 -0
  63. package/dist/plugins/unplugin.d.cts +17 -0
  64. package/dist/plugins/unplugin.d.ts +15 -0
  65. package/dist/{bundler → plugins}/unplugin.js +5 -5
  66. package/dist/types-DYQIzGf6.d.cts +112 -0
  67. package/dist/types-ZHAFdOd3.d.ts +112 -0
  68. package/package.json +48 -52
  69. package/dist/ast/index.cjs +0 -17
  70. package/dist/ast/index.d.cts +0 -18
  71. package/dist/ast/index.d.ts +0 -18
  72. package/dist/ast/index.js +0 -17
  73. package/dist/bundler/unplugin.cjs +0 -20
  74. package/dist/bundler/unplugin.d.cts +0 -16
  75. package/dist/bundler/unplugin.d.ts +0 -14
  76. package/dist/chunk-27HR647Q.js +0 -190
  77. package/dist/chunk-4TDLLEEU.cjs +0 -15
  78. package/dist/chunk-6N6S6WTQ.cjs +0 -423
  79. package/dist/chunk-J5CGNZDM.cjs +0 -190
  80. package/dist/chunk-KQWNFKT2.js +0 -423
  81. package/dist/chunk-R6EBIR3T.cjs +0 -14
  82. package/dist/chunk-S4S2WXGC.js +0 -14
  83. package/dist/cli/index.cjs +0 -324
  84. package/dist/cli/index.d.cts +0 -22
  85. package/dist/cli/index.d.ts +0 -22
  86. package/dist/esbuild.cjs +0 -15
  87. package/dist/esbuild.js +0 -13
  88. package/dist/next/adapter.cjs +0 -31
  89. package/dist/next/adapter.js +0 -31
  90. package/dist/next/index.cjs +0 -18
  91. package/dist/next/index.d.cts +0 -42
  92. package/dist/next/index.d.ts +0 -42
  93. package/dist/next/index.js +0 -18
  94. package/dist/rollup.cjs +0 -15
  95. package/dist/rollup.js +0 -13
  96. package/dist/runtime/index.cjs +0 -17
  97. package/dist/runtime/index.d.cts +0 -36
  98. package/dist/runtime/index.d.ts +0 -36
  99. package/dist/runtime/index.js +0 -17
  100. package/dist/vite.cjs +0 -15
  101. package/dist/vite.js +0 -13
  102. package/dist/webpack.cjs +0 -15
  103. package/dist/webpack.js +0 -13
@@ -1,24 +1,78 @@
1
1
  import {
2
2
  loadUnpeekConfig
3
- } from "./chunk-GZB7PFLY.js";
4
- import {
5
- transformJavaScript
6
- } from "./chunk-UMPUYLLZ.js";
3
+ } from "./chunk-IICVBTR2.js";
7
4
  import {
8
5
  computeFnv1aHash,
9
6
  deriveWindowKeySymbol,
10
- generateRuntimeShield
11
- } from "./chunk-KQWNFKT2.js";
7
+ generateRuntimeShield,
8
+ transformJavaScript
9
+ } from "./chunk-IZIWDJRF.js";
12
10
  import {
13
11
  UnpeekError
14
- } from "./chunk-S4S2WXGC.js";
12
+ } from "./chunk-LA6J3BT3.js";
13
+
14
+ // src/internal/next.ts
15
+ function isNext16OrAbove(versionStr) {
16
+ if (!versionStr) return false;
17
+ const clean = versionStr.replace(/^[^\d]*/, "");
18
+ const match = clean.match(/^(\d+)\.(\d+)/);
19
+ if (!match) return false;
20
+ const major = parseInt(match[1], 10);
21
+ const minor = parseInt(match[2], 10);
22
+ if (major > 16) return true;
23
+ if (major === 16 && minor >= 2) return true;
24
+ return false;
25
+ }
26
+ function isSerializedRegExp(val) {
27
+ if (typeof val !== "object" || val === null) return false;
28
+ const record = val;
29
+ return record.__unpeekRegExp === true && typeof record.source === "string" && typeof record.flags === "string";
30
+ }
31
+ function serializeNextOptions(options) {
32
+ return JSON.stringify(options, (_key, value) => {
33
+ if (value instanceof RegExp) {
34
+ return {
35
+ __unpeekRegExp: true,
36
+ source: value.source,
37
+ flags: value.flags
38
+ };
39
+ }
40
+ return value;
41
+ });
42
+ }
43
+ function parseNextOptions(raw) {
44
+ return JSON.parse(raw, (_key, value) => {
45
+ if (isSerializedRegExp(value)) {
46
+ try {
47
+ return new RegExp(value.source, value.flags);
48
+ } catch {
49
+ return void 0;
50
+ }
51
+ }
52
+ return value;
53
+ });
54
+ }
55
+ function readUnpeekNextOptionsFromEnv() {
56
+ const raw = process.env.UNPEEK_NEXT_OPTIONS;
57
+ if (!raw) {
58
+ return void 0;
59
+ }
60
+ try {
61
+ const parsed = parseNextOptions(raw);
62
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
63
+ return parsed;
64
+ }
65
+ } catch {
66
+ }
67
+ return void 0;
68
+ }
15
69
 
16
70
  // src/core/protect.ts
17
71
  import fs3 from "fs";
18
72
  import path3 from "path";
19
73
  import zlib from "zlib";
20
74
 
21
- // src/bundler/detector.ts
75
+ // src/core/detector.ts
22
76
  import fs from "fs";
23
77
  import path from "path";
24
78
  var SUPPORTED_EXTENSIONS = /* @__PURE__ */ new Set([".js", ".mjs", ".cjs"]);
@@ -243,10 +297,28 @@ function scanClientBundles(outDir, config) {
243
297
  return results.sort();
244
298
  }
245
299
 
246
- // src/bundler/sourcemap-vault.ts
300
+ // src/core/sourcemap-vault.ts
247
301
  import fs2 from "fs";
248
302
  import path2 from "path";
249
303
  var SOURCE_MAP_COMMENT_REGEX = /(?:^\s*\/\/[#@]\s*sourceMappingURL=.*$|\/\*[#@]\s*sourceMappingURL=[\s\S]*?\*\/)\s*/gm;
304
+ var DEBUG_ID_COMMENT_REGEX = /(?:\/\/[#@]\s*debugId=([^\s*]+)|\/\*[#@]\s*debugId=([^\s*]+)\s*\*\/)/;
305
+ function extractDebugId(code) {
306
+ const match = code.match(DEBUG_ID_COMMENT_REGEX);
307
+ const id = match?.[1] ?? match?.[2];
308
+ return id ? id.trim() : void 0;
309
+ }
310
+ function stripSourceMapComments(code) {
311
+ const debugId = extractDebugId(code);
312
+ SOURCE_MAP_COMMENT_REGEX.lastIndex = 0;
313
+ let next = code.replace(SOURCE_MAP_COMMENT_REGEX, "");
314
+ const stripped = next !== code;
315
+ if (debugId && !DEBUG_ID_COMMENT_REGEX.test(next)) {
316
+ const suffix = next.length > 0 && !next.endsWith("\n") ? "\n" : "";
317
+ next = `${next}${suffix}//# debugId=${debugId}
318
+ `;
319
+ }
320
+ return { code: next, stripped, debugId };
321
+ }
250
322
  function ensureIgnoreEntry(dir, fileName, entryName) {
251
323
  const filePath = path2.join(path2.resolve(dir), fileName);
252
324
  if (!fs2.existsSync(filePath)) {
@@ -325,6 +397,7 @@ function relocateSourceMaps(outDir, cwd, keepPrivateMaps = true, privateMapsDir
325
397
  const effectiveKeepPrivate = config?.sourcemaps?.keepPrivate ?? keepPrivateMaps;
326
398
  const effectiveStripComments = config?.sourcemaps?.stripComments ?? stripComments;
327
399
  const updateIgnoreFiles = typeof options === "boolean" ? options : options?.updateIgnoreFiles ?? true;
400
+ const dryRun = typeof options === "object" && options !== null ? options.dryRun ?? false : false;
328
401
  const vaultDir = path2.resolve(resolvedCwd, effectiveVaultDirName);
329
402
  const publicDirsToCheck = /* @__PURE__ */ new Set();
330
403
  if (config?.publicDirs && config.publicDirs.length > 0) {
@@ -396,11 +469,13 @@ function relocateSourceMaps(outDir, cwd, keepPrivateMaps = true, privateMapsDir
396
469
  if (effectiveKeepPrivate !== false) {
397
470
  const relPath = path2.relative(resolvedOutDir, fullPath);
398
471
  const targetPath = path2.join(vaultDir, relPath);
399
- fs2.mkdirSync(path2.dirname(targetPath), { recursive: true });
400
- fs2.copyFileSync(fullPath, targetPath);
401
- fs2.unlinkSync(fullPath);
472
+ if (!dryRun) {
473
+ fs2.mkdirSync(path2.dirname(targetPath), { recursive: true });
474
+ fs2.copyFileSync(fullPath, targetPath);
475
+ fs2.unlinkSync(fullPath);
476
+ }
402
477
  movedFiles.push(targetPath);
403
- } else {
478
+ } else if (!dryRun) {
404
479
  fs2.unlinkSync(fullPath);
405
480
  }
406
481
  movedMapsCount++;
@@ -408,7 +483,7 @@ function relocateSourceMaps(outDir, cwd, keepPrivateMaps = true, privateMapsDir
408
483
  }
409
484
  }
410
485
  walkForMaps(resolvedOutDir);
411
- if (updateIgnoreFiles && effectiveKeepPrivate !== false && movedMapsCount > 0) {
486
+ if (!dryRun && updateIgnoreFiles && effectiveKeepPrivate !== false && movedMapsCount > 0) {
412
487
  updateAllIgnoreFiles(resolvedCwd, vaultDir);
413
488
  }
414
489
  if (effectiveStripComments) {
@@ -416,9 +491,11 @@ function relocateSourceMaps(outDir, cwd, keepPrivateMaps = true, privateMapsDir
416
491
  for (const filePath of clientFiles) {
417
492
  const original = fs2.readFileSync(filePath, "utf8");
418
493
  if (original.includes("sourceMappingURL=")) {
419
- const stripped = original.replace(SOURCE_MAP_COMMENT_REGEX, "");
420
- if (stripped !== original) {
421
- fs2.writeFileSync(filePath, stripped, "utf8");
494
+ const { code: strippedCode, stripped } = stripSourceMapComments(original);
495
+ if (stripped) {
496
+ if (!dryRun) {
497
+ fs2.writeFileSync(filePath, strippedCode, "utf8");
498
+ }
422
499
  strippedFilesCount++;
423
500
  }
424
501
  }
@@ -453,16 +530,20 @@ function isEntryChunk(relPath, index, allRelPaths) {
453
530
  async function protectProject(options = {}) {
454
531
  const startTime = performance.now();
455
532
  const cwd = path3.resolve(options.cwd ?? process.cwd());
456
- const config = await loadUnpeekConfig(cwd, options.config);
533
+ const effectiveConfigInput = options.profile ? { ...options.config ?? {}, profile: options.profile } : options.config;
534
+ const config = await loadUnpeekConfig(cwd, effectiveConfigInput);
535
+ const effectiveProfile = options.profile ?? config.profile ?? "recommended";
457
536
  const { framework, outDir } = detectTargetFramework(cwd, options.outDir, config);
458
537
  const seed = typeof options.seed === "number" ? options.seed : Math.floor(Math.random() * 2147483647) || 1597463007;
538
+ const dryRun = Boolean(options.dryRun);
459
539
  const keepPrivateMaps = options.keepPrivateMaps ?? config.sourcemaps?.keepPrivate ?? true;
460
540
  const privateMapsDir = options.privateMapsDir ?? config.sourcemaps?.vaultDir ?? ".unpeek-maps";
461
541
  const deterrentMode = options.deterrentMode ?? config.shield?.deterrentMode ?? "passive";
462
542
  const detectHeadless = options.detectHeadless ?? config.shield?.detectHeadless ?? false;
463
- const injectRuntimeShield = options.injectRuntimeShield ?? true;
543
+ const injectRuntimeShield = options.injectRuntimeShield ?? (effectiveProfile === "minimal" ? false : true);
464
544
  const minStringLength = options.minStringLength ?? config.vault?.minStringLength ?? 4;
465
- const aggressive = options.aggressive ?? false;
545
+ const aggressive = options.aggressive ?? (effectiveProfile === "strict" ? true : false);
546
+ const scrubPaths = options.scrubPaths ?? config.scrubPaths ?? (effectiveProfile === "strict" ? true : false);
466
547
  const masterSym = deriveWindowKeySymbol(seed);
467
548
  const masterShield = injectRuntimeShield ? generateRuntimeShield({
468
549
  seed,
@@ -470,7 +551,10 @@ async function protectProject(options = {}) {
470
551
  detectHeadless,
471
552
  windowKeySymbol: masterSym
472
553
  }) : void 0;
473
- const vaultResult = relocateSourceMaps(outDir, cwd, keepPrivateMaps, privateMapsDir, false, config);
554
+ const deferVaultWrites = dryRun || typeof options.maxGzipDelta === "number";
555
+ const vaultResult = relocateSourceMaps(outDir, cwd, keepPrivateMaps, privateMapsDir, false, config, {
556
+ dryRun: deferVaultWrites
557
+ });
474
558
  const clientFiles = scanClientBundles(outDir, config);
475
559
  const allRelPaths = clientFiles.map((f) => path3.relative(outDir, f).replace(/\\/g, "/"));
476
560
  let originalBytes = 0;
@@ -480,16 +564,34 @@ async function protectProject(options = {}) {
480
564
  let totalEncryptedStrings = 0;
481
565
  let totalMangledSymbols = 0;
482
566
  let processedFiles = 0;
567
+ let debugIdsPreserved = 0;
568
+ const diagnostics = [];
569
+ if (vaultResult.dockerIgnoreMissing) {
570
+ diagnostics.push({
571
+ code: "DOCKERIGNORE_MISSING",
572
+ severity: "warning",
573
+ message: ".dockerignore is missing .unpeek-maps/. Private maps may leak into Docker image during 'COPY . .'."
574
+ });
575
+ }
483
576
  const allOrigBufs = [];
484
577
  const allProtBufs = [];
485
578
  const stagedFiles = [];
579
+ const pendingDebugIds = [];
580
+ let originalGzipBytes = 0;
581
+ let protectedGzipBytes = 0;
582
+ let gzipDeltaPercent = 0;
583
+ let budgetExceeded = false;
486
584
  try {
487
585
  for (let i = 0; i < clientFiles.length; i++) {
488
586
  const filePath = clientFiles[i];
489
587
  let codeToTransform = fs3.readFileSync(filePath, "utf8");
588
+ const fileDebugId = extractDebugId(codeToTransform);
490
589
  if (codeToTransform.includes("sourceMappingURL=")) {
491
- codeToTransform = codeToTransform.replace(SOURCE_MAP_COMMENT_REGEX, "");
492
- vaultResult.strippedFilesCount++;
590
+ const strippedRes = stripSourceMapComments(codeToTransform);
591
+ codeToTransform = strippedRes.code;
592
+ if (strippedRes.stripped) {
593
+ vaultResult.strippedFilesCount++;
594
+ }
493
595
  }
494
596
  const origBuf = Buffer.from(codeToTransform, "utf8");
495
597
  originalBytes += origBuf.byteLength;
@@ -510,17 +612,54 @@ async function protectProject(options = {}) {
510
612
  deterrentMode,
511
613
  detectHeadless,
512
614
  aggressive,
615
+ scrubPaths,
513
616
  config
514
617
  };
515
618
  const result = transformJavaScript(codeToTransform, transformOptions);
619
+ if (result.skippedReason === "parse-error") {
620
+ diagnostics.push({
621
+ code: "PARSE_FALLBACK",
622
+ severity: "warning",
623
+ message: `Skipped AST transform due to parse error in "${relPath}".`,
624
+ file: relPath
625
+ });
626
+ } else if (result.skippedReason === "already-protected") {
627
+ diagnostics.push({
628
+ code: "ALREADY_PROTECTED",
629
+ severity: "info",
630
+ message: `File "${relPath}" is already protected.`,
631
+ file: relPath
632
+ });
633
+ } else if (result.skippedReason === "empty") {
634
+ diagnostics.push({
635
+ code: "EMPTY_INPUT",
636
+ severity: "info",
637
+ message: `File "${relPath}" is empty.`,
638
+ file: relPath
639
+ });
640
+ }
516
641
  let finalCode = result.code;
517
642
  if (shouldInjectShield && masterShield?.preambleCode && !finalCode.includes("__unpeek_tampered") && !finalCode.includes(masterShield.integrityCheckFnName) && !finalCode.startsWith(masterShield.preambleCode)) {
518
643
  finalCode = `${masterShield.preambleCode}
519
644
  ${finalCode}`;
520
645
  }
521
- const tmpPath = `${filePath}.unpeek.tmp`;
522
- fs3.writeFileSync(tmpPath, finalCode, "utf8");
523
- stagedFiles.push({ tmpPath, finalPath: filePath });
646
+ const effectiveDebugId = result.debugId ?? fileDebugId;
647
+ if (effectiveDebugId) {
648
+ if (!DEBUG_ID_COMMENT_REGEX.test(finalCode)) {
649
+ const suffix = finalCode.length > 0 && !finalCode.endsWith("\n") ? "\n" : "";
650
+ finalCode = `${finalCode}${suffix}//# debugId=${effectiveDebugId}
651
+ `;
652
+ }
653
+ debugIdsPreserved++;
654
+ if (!dryRun && keepPrivateMaps) {
655
+ pendingDebugIds.push({ relPath, debugId: effectiveDebugId });
656
+ }
657
+ }
658
+ if (!dryRun) {
659
+ const tmpPath = `${filePath}.unpeek.tmp`;
660
+ fs3.writeFileSync(tmpPath, finalCode, "utf8");
661
+ stagedFiles.push({ tmpPath, finalPath: filePath });
662
+ }
524
663
  const protBuf = Buffer.from(finalCode, "utf8");
525
664
  protectedBytes += protBuf.byteLength;
526
665
  allProtBufs.push(protBuf);
@@ -530,8 +669,48 @@ ${finalCode}`;
530
669
  totalMangledSymbols += result.mangledSymbolsCount;
531
670
  processedFiles++;
532
671
  }
533
- for (const { tmpPath, finalPath } of stagedFiles) {
534
- fs3.renameSync(tmpPath, finalPath);
672
+ originalGzipBytes = allOrigBufs.length > 0 ? zlib.gzipSync(Buffer.concat(allOrigBufs)).byteLength : 0;
673
+ protectedGzipBytes = allProtBufs.length > 0 ? zlib.gzipSync(Buffer.concat(allProtBufs)).byteLength : 0;
674
+ gzipDeltaPercent = originalGzipBytes > 0 ? Number(((protectedGzipBytes - originalGzipBytes) / originalGzipBytes * 100).toFixed(2)) : 0;
675
+ budgetExceeded = typeof options.maxGzipDelta === "number" && gzipDeltaPercent > options.maxGzipDelta;
676
+ if (budgetExceeded && !dryRun) {
677
+ throw new UnpeekError(
678
+ "ERR_BUDGET_EXCEEDED",
679
+ `Protected bundle Gzip delta (${gzipDeltaPercent}%) exceeded maxGzipDelta (${options.maxGzipDelta}%).`
680
+ );
681
+ }
682
+ if (!dryRun) {
683
+ if (deferVaultWrites) {
684
+ const finalVaultResult = relocateSourceMaps(
685
+ outDir,
686
+ cwd,
687
+ keepPrivateMaps,
688
+ privateMapsDir,
689
+ false,
690
+ config,
691
+ { dryRun: false }
692
+ );
693
+ vaultResult.movedMapsCount = finalVaultResult.movedMapsCount;
694
+ vaultResult.vaultDir = finalVaultResult.vaultDir;
695
+ vaultResult.movedFiles = finalVaultResult.movedFiles;
696
+ vaultResult.dockerIgnoreMissing = finalVaultResult.dockerIgnoreMissing;
697
+ }
698
+ for (const { relPath, debugId } of pendingDebugIds) {
699
+ const vaultedMapPath = path3.join(vaultResult.vaultDir, `${relPath}.map`);
700
+ if (fs3.existsSync(vaultedMapPath)) {
701
+ try {
702
+ const mapJson = JSON.parse(fs3.readFileSync(vaultedMapPath, "utf8"));
703
+ if (!mapJson.debugId) {
704
+ mapJson.debugId = debugId;
705
+ fs3.writeFileSync(vaultedMapPath, JSON.stringify(mapJson), "utf8");
706
+ }
707
+ } catch {
708
+ }
709
+ }
710
+ }
711
+ for (const { tmpPath, finalPath } of stagedFiles) {
712
+ fs3.renameSync(tmpPath, finalPath);
713
+ }
535
714
  }
536
715
  } catch (error) {
537
716
  for (const { tmpPath } of stagedFiles) {
@@ -544,9 +723,6 @@ ${finalCode}`;
544
723
  }
545
724
  throw error;
546
725
  }
547
- const originalGzipBytes = allOrigBufs.length > 0 ? zlib.gzipSync(Buffer.concat(allOrigBufs)).byteLength : 0;
548
- const protectedGzipBytes = allProtBufs.length > 0 ? zlib.gzipSync(Buffer.concat(allProtBufs)).byteLength : 0;
549
- const gzipDeltaPercent = originalGzipBytes > 0 ? Number(((protectedGzipBytes - originalGzipBytes) / originalGzipBytes * 100).toFixed(2)) : 0;
550
726
  const elapsedMs = Math.max(1, Math.round(performance.now() - startTime));
551
727
  return {
552
728
  framework,
@@ -563,13 +739,26 @@ ${finalCode}`;
563
739
  totalEncryptedStrings,
564
740
  totalMangledSymbols,
565
741
  elapsedMs,
742
+ seed,
566
743
  tier: aggressive ? "Tier 2" : "Tier 1",
567
744
  aggressive,
568
- dockerIgnoreMissing: vaultResult.dockerIgnoreMissing
745
+ dockerIgnoreMissing: vaultResult.dockerIgnoreMissing,
746
+ dryRun,
747
+ profile: effectiveProfile,
748
+ budgetExceeded,
749
+ debugIdsPreserved,
750
+ diagnostics
569
751
  };
570
752
  }
571
753
 
572
754
  export {
755
+ hasNextServerSegment,
573
756
  detectTargetFramework,
757
+ scanClientBundles,
758
+ isNext16OrAbove,
759
+ serializeNextOptions,
760
+ readUnpeekNextOptionsFromEnv,
761
+ SOURCE_MAP_COMMENT_REGEX,
762
+ findMonorepoRoots,
574
763
  protectProject
575
764
  };
@@ -1,20 +1,23 @@
1
1
  import {
2
- protectProject
3
- } from "./chunk-5LCMI2TL.js";
2
+ protectProject,
3
+ serializeNextOptions
4
+ } from "./chunk-APWMNVAZ.js";
4
5
  import {
5
6
  computeFnv1aHash
6
- } from "./chunk-KQWNFKT2.js";
7
+ } from "./chunk-IZIWDJRF.js";
7
8
  import {
9
+ UnpeekError,
8
10
  __dirname,
9
11
  __require
10
- } from "./chunk-OOXSZTRV.js";
12
+ } from "./chunk-LA6J3BT3.js";
11
13
 
12
- // src/next/index.ts
14
+ // src/adapters/next/index.ts
13
15
  import fs from "fs";
14
16
  import path from "path";
15
17
  import crypto from "crypto";
16
18
  import { fileURLToPath, pathToFileURL } from "url";
17
19
  import { createRequire } from "module";
20
+ var MAX_NEXT_OPTIONS_ENV_BYTES = 32767;
18
21
  async function loadUpstreamAdapter(adapterPath) {
19
22
  const resolved = path.isAbsolute(adapterPath) ? adapterPath : path.resolve(process.cwd(), adapterPath);
20
23
  try {
@@ -31,11 +34,31 @@ function recomputeHash(content, existingHash) {
31
34
  const algo = len === 64 ? "sha256" : len === 40 ? "sha1" : len === 32 ? "md5" : "sha256";
32
35
  return crypto.createHash(algo).update(content).digest("hex");
33
36
  }
37
+ function isNonProductionPhase(phase) {
38
+ return phase !== void 0 && phase !== "phase-production-build" && phase !== "phase-export";
39
+ }
40
+ async function delegateToUpstreamOnBuildComplete(upstreamPath, context) {
41
+ if (!upstreamPath) return;
42
+ try {
43
+ const upstream = await loadUpstreamAdapter(upstreamPath);
44
+ if (upstream && typeof upstream !== "function" && typeof upstream.onBuildComplete === "function") {
45
+ await upstream.onBuildComplete(context);
46
+ } else if (typeof upstream === "function") {
47
+ await upstream(context);
48
+ }
49
+ } catch (err) {
50
+ console.warn("[unpeek:next] Failed to delegate to upstream adapter onBuildComplete:", err);
51
+ }
52
+ }
34
53
  function createUnpeekNextAdapter(options = {}) {
35
54
  const upstreamPath = options.upstreamAdapterPath || process.env.UNPEEK_UPSTREAM_ADAPTER_PATH || process.env.NEXT_ADAPTER_PATH;
55
+ let recordedPhase;
36
56
  return {
37
57
  name: "unpeek",
38
58
  async modifyConfig(config, context) {
59
+ if (context && typeof context.phase === "string") {
60
+ recordedPhase = context.phase;
61
+ }
39
62
  if (upstreamPath) {
40
63
  try {
41
64
  const upstream = await loadUpstreamAdapter(upstreamPath);
@@ -53,6 +76,26 @@ function createUnpeekNextAdapter(options = {}) {
53
76
  const distDir = path.resolve(cwd, context.distDir || ".next");
54
77
  const staticDir = path.join(distDir, "static");
55
78
  const targetDir = fs.existsSync(staticDir) ? staticDir : distDir;
79
+ const phase = context.phase ?? recordedPhase;
80
+ if (isNonProductionPhase(phase)) {
81
+ await delegateToUpstreamOnBuildComplete(upstreamPath, context);
82
+ return {
83
+ framework: "nextjs",
84
+ outDir: targetDir,
85
+ processedFiles: 0,
86
+ movedSourceMaps: 0,
87
+ originalBytes: 0,
88
+ protectedBytes: 0,
89
+ originalGzipBytes: 0,
90
+ protectedGzipBytes: 0,
91
+ gzipDeltaPercent: 0,
92
+ totalHotFunctionsSkipped: 0,
93
+ totalColdFunctionsProtected: 0,
94
+ totalEncryptedStrings: 0,
95
+ totalMangledSymbols: 0,
96
+ elapsedMs: 0
97
+ };
98
+ }
56
99
  const deterministicSeed = typeof options.seed === "number" ? options.seed : context.buildId ? computeFnv1aHash(context.buildId, 1597463007) : 1597463007;
57
100
  const summary = await protectProject({
58
101
  ...options,
@@ -98,18 +141,7 @@ function createUnpeekNextAdapter(options = {}) {
98
141
  }
99
142
  }
100
143
  }
101
- if (upstreamPath) {
102
- try {
103
- const upstream = await loadUpstreamAdapter(upstreamPath);
104
- if (upstream && typeof upstream !== "function" && typeof upstream.onBuildComplete === "function") {
105
- await upstream.onBuildComplete(context);
106
- } else if (typeof upstream === "function") {
107
- await upstream(context);
108
- }
109
- } catch (err) {
110
- console.warn("[unpeek:next] Failed to delegate to upstream adapter onBuildComplete:", err);
111
- }
112
- }
144
+ await delegateToUpstreamOnBuildComplete(upstreamPath, context);
113
145
  return summary;
114
146
  }
115
147
  };
@@ -127,14 +159,14 @@ function getUnpeekAdapterPath() {
127
159
  const isCjs = typeof __dirname !== "undefined";
128
160
  const currentDir = isCjs ? __dirname : path.dirname(fileURLToPath(import.meta.url));
129
161
  const candidates = [
130
- path.resolve(currentDir, isCjs ? "next/adapter.cjs" : "next/adapter.js"),
131
- path.resolve(currentDir, isCjs ? "next/adapter.js" : "next/adapter.cjs"),
162
+ path.resolve(currentDir, isCjs ? "adapters/next/adapter.cjs" : "adapters/next/adapter.js"),
163
+ path.resolve(currentDir, isCjs ? "adapters/next/adapter.js" : "adapters/next/adapter.cjs"),
132
164
  path.resolve(currentDir, isCjs ? "adapter.cjs" : "adapter.js"),
133
165
  path.resolve(currentDir, isCjs ? "adapter.js" : "adapter.cjs"),
134
- path.resolve(currentDir, "../dist/next/adapter.cjs"),
135
- path.resolve(currentDir, "../dist/next/adapter.js"),
136
- path.resolve(process.cwd(), "node_modules/unpeek/dist/next/adapter.cjs"),
137
- path.resolve(process.cwd(), "node_modules/unpeek/dist/next/adapter.js")
166
+ path.resolve(currentDir, "../dist/adapters/next/adapter.cjs"),
167
+ path.resolve(currentDir, "../dist/adapters/next/adapter.js"),
168
+ path.resolve(process.cwd(), "node_modules/unpeek/dist/adapters/next/adapter.cjs"),
169
+ path.resolve(process.cwd(), "node_modules/unpeek/dist/adapters/next/adapter.js")
138
170
  ];
139
171
  for (const cand of candidates) {
140
172
  if (fs.existsSync(cand)) {
@@ -143,23 +175,9 @@ function getUnpeekAdapterPath() {
143
175
  }
144
176
  return candidates[0];
145
177
  } catch {
146
- return path.resolve(process.cwd(), "node_modules/unpeek/dist/next/adapter.js");
178
+ return path.resolve(process.cwd(), "node_modules/unpeek/dist/adapters/next/adapter.js");
147
179
  }
148
180
  }
149
- function readUnpeekNextOptionsFromEnv() {
150
- const raw = process.env.UNPEEK_NEXT_OPTIONS;
151
- if (!raw) {
152
- return void 0;
153
- }
154
- try {
155
- const parsed = JSON.parse(raw);
156
- if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
157
- return parsed;
158
- }
159
- } catch {
160
- }
161
- return void 0;
162
- }
163
181
  function applyWithUnpeek(config = {}, options) {
164
182
  const existingAdapter = config.adapterPath || process.env.NEXT_ADAPTER_PATH;
165
183
  if (existingAdapter && !process.env.UNPEEK_UPSTREAM_ADAPTER_PATH) {
@@ -169,7 +187,15 @@ function applyWithUnpeek(config = {}, options) {
169
187
  process.env.UNPEEK_UPSTREAM_ADAPTER_PATH = options.upstreamAdapterPath;
170
188
  }
171
189
  if (options) {
172
- process.env.UNPEEK_NEXT_OPTIONS = JSON.stringify(options);
190
+ const serialized = serializeNextOptions(options);
191
+ const byteLength = Buffer.byteLength(serialized, "utf8");
192
+ if (byteLength > MAX_NEXT_OPTIONS_ENV_BYTES) {
193
+ throw new UnpeekError(
194
+ "ERR_NEXT_ADAPTER",
195
+ `Serialized UNPEEK_NEXT_OPTIONS (${byteLength} bytes) exceeds the ${MAX_NEXT_OPTIONS_ENV_BYTES}-byte process.env limit.`
196
+ );
197
+ }
198
+ process.env.UNPEEK_NEXT_OPTIONS = serialized;
173
199
  } else {
174
200
  delete process.env.UNPEEK_NEXT_OPTIONS;
175
201
  }
@@ -181,10 +207,14 @@ function applyWithUnpeek(config = {}, options) {
181
207
  }
182
208
  function withUnpeek(nextConfig = {}, options) {
183
209
  if (typeof nextConfig === "function") {
184
- return (async (...args) => {
210
+ return async (...args) => {
185
211
  const resolved = await nextConfig(...args);
212
+ const phase = typeof args[0] === "string" ? args[0] : void 0;
213
+ if (isNonProductionPhase(phase)) {
214
+ return resolved;
215
+ }
186
216
  return applyWithUnpeek(resolved, options);
187
- });
217
+ };
188
218
  }
189
219
  return applyWithUnpeek(nextConfig, options);
190
220
  }
@@ -192,6 +222,5 @@ function withUnpeek(nextConfig = {}, options) {
192
222
  export {
193
223
  createUnpeekNextAdapter,
194
224
  getUnpeekAdapterPath,
195
- readUnpeekNextOptionsFromEnv,
196
225
  withUnpeek
197
226
  };
@@ -1,17 +1,15 @@
1
- import {
2
- transformJavaScript
3
- } from "./chunk-UMPUYLLZ.js";
4
1
  import {
5
2
  computeFnv1aHash,
6
3
  deriveWindowKeySymbol,
7
- generateRuntimeShield
8
- } from "./chunk-KQWNFKT2.js";
4
+ generateRuntimeShield,
5
+ transformJavaScript
6
+ } from "./chunk-IZIWDJRF.js";
9
7
 
10
- // src/bundler/unplugin.ts
8
+ // src/plugins/unplugin.ts
11
9
  import { createUnplugin } from "unplugin";
12
10
  var ENTRY_CHUNK_PATTERN = /(?:^|\/)(?:webpack|main|index|runtime|turbopack|pages\/_app|pages\/index)(?:[-._/]|$)/i;
13
11
  var unpeekPlugin = createUnplugin((options = {}) => {
14
- const config = options.config ?? ("framework" in options || "target" in options || "vault" in options || "hotPath" in options || "mangler" in options || "shield" in options || "sourcemaps" in options ? options : void 0);
12
+ const config = options.config;
15
13
  const baseSeed = typeof options.seed === "number" ? options.seed : Math.floor(Math.random() * 2147483647) || 322420463;
16
14
  const deterrentMode = options.deterrentMode ?? config?.shield?.deterrentMode ?? "passive";
17
15
  const detectHeadless = options.detectHeadless ?? config?.shield?.detectHeadless ?? false;
@@ -71,6 +69,7 @@ var vitePlugin = unpeekPlugin.vite;
71
69
  var webpackPlugin = unpeekPlugin.webpack;
72
70
  var rollupPlugin = unpeekPlugin.rollup;
73
71
  var esbuildPlugin = unpeekPlugin.esbuild;
72
+ var rspackPlugin = unpeekPlugin.rspack;
74
73
  var unplugin_default = unpeekPlugin;
75
74
 
76
75
  export {
@@ -79,5 +78,6 @@ export {
79
78
  webpackPlugin,
80
79
  rollupPlugin,
81
80
  esbuildPlugin,
81
+ rspackPlugin,
82
82
  unplugin_default
83
83
  };