unpeek 2.0.0 → 4.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 (120) hide show
  1. package/README.md +57 -21
  2. package/README.tr.md +65 -29
  3. package/dist/adapters/esbuild.cjs +13 -0
  4. package/dist/adapters/esbuild.d.cts +13 -0
  5. package/dist/adapters/esbuild.d.ts +11 -0
  6. package/dist/adapters/esbuild.js +13 -0
  7. package/dist/adapters/next/adapter.cjs +43 -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 +43 -0
  11. package/dist/adapters/next/index.cjs +16 -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 +16 -0
  15. package/dist/adapters/rollup.cjs +13 -0
  16. package/dist/adapters/rollup.d.cts +13 -0
  17. package/dist/adapters/rollup.d.ts +11 -0
  18. package/dist/adapters/rollup.js +13 -0
  19. package/dist/adapters/rspack.cjs +13 -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 +13 -0
  23. package/dist/adapters/vite.cjs +13 -0
  24. package/dist/adapters/vite.d.cts +13 -0
  25. package/dist/adapters/vite.d.ts +11 -0
  26. package/dist/adapters/vite.js +13 -0
  27. package/dist/adapters/webpack.cjs +13 -0
  28. package/dist/adapters/webpack.d.cts +13 -0
  29. package/dist/adapters/webpack.d.ts +11 -0
  30. package/dist/adapters/webpack.js +13 -0
  31. package/dist/browser.cjs +8 -5
  32. package/dist/browser.d.cts +44 -3
  33. package/dist/browser.d.ts +44 -3
  34. package/dist/browser.js +10 -7
  35. package/dist/{chunk-5QD6FZPB.js → chunk-2JU3V7HW.js} +75 -43
  36. package/dist/chunk-3LWXEJU6.cjs +1054 -0
  37. package/dist/chunk-4FNZNIBW.js +7391 -0
  38. package/dist/chunk-7HXLHLLQ.cjs +503 -0
  39. package/dist/chunk-ADKRENAP.js +1054 -0
  40. package/dist/chunk-EN6QVR6P.js +89 -0
  41. package/dist/chunk-HHC7BUCK.js +503 -0
  42. package/dist/chunk-KLYFNMKS.cjs +7391 -0
  43. package/dist/chunk-L6BOM5VS.cjs +40 -0
  44. package/dist/{chunk-OOXSZTRV.js → chunk-LA6J3BT3.js} +26 -1
  45. package/dist/chunk-URPPSTHZ.cjs +89 -0
  46. package/dist/chunk-VG4Y26ZN.cjs +429 -0
  47. package/dist/{chunk-GZB7PFLY.js → chunk-W77DAC3H.js} +46 -64
  48. package/dist/chunk-X6EETCO6.cjs +352 -0
  49. package/dist/chunk-YCRMTXOE.js +429 -0
  50. package/dist/{chunk-GAVI2C44.cjs → chunk-ZG7BIAUI.cjs} +80 -48
  51. package/dist/cli/index.js +9861 -32
  52. package/dist/{types-BBSRUEab.d.cts → config-Y6JwVGwX.d.cts} +58 -86
  53. package/dist/{types-BBSRUEab.d.ts → config-Y6JwVGwX.d.ts} +58 -86
  54. package/dist/config.cjs +4 -16
  55. package/dist/config.d.cts +1 -12
  56. package/dist/config.d.ts +1 -12
  57. package/dist/config.js +5 -17
  58. package/dist/index-0O1WSfVP.d.ts +52 -0
  59. package/dist/index-COVHErnx.d.cts +52 -0
  60. package/dist/index.cjs +437 -9
  61. package/dist/index.d.cts +9 -17
  62. package/dist/index.d.ts +9 -17
  63. package/dist/index.js +438 -10
  64. package/dist/plugins/unplugin.cjs +21 -0
  65. package/dist/plugins/unplugin.d.cts +17 -0
  66. package/dist/plugins/unplugin.d.ts +15 -0
  67. package/dist/{bundler → plugins}/unplugin.js +6 -5
  68. package/dist/types-CMtZnV8C.d.ts +112 -0
  69. package/dist/types-D93PuOOl.d.cts +112 -0
  70. package/package.json +48 -52
  71. package/dist/ast/index.cjs +0 -17
  72. package/dist/ast/index.d.cts +0 -18
  73. package/dist/ast/index.d.ts +0 -18
  74. package/dist/ast/index.js +0 -17
  75. package/dist/bundler/unplugin.cjs +0 -20
  76. package/dist/bundler/unplugin.d.cts +0 -16
  77. package/dist/bundler/unplugin.d.ts +0 -14
  78. package/dist/chunk-24K5NDXH.cjs +0 -370
  79. package/dist/chunk-27HR647Q.js +0 -190
  80. package/dist/chunk-4TDLLEEU.cjs +0 -15
  81. package/dist/chunk-5LCMI2TL.js +0 -575
  82. package/dist/chunk-5M6Z7ZFT.cjs +0 -83
  83. package/dist/chunk-6N6S6WTQ.cjs +0 -423
  84. package/dist/chunk-7YVEHJVM.cjs +0 -575
  85. package/dist/chunk-J5CGNZDM.cjs +0 -190
  86. package/dist/chunk-KQWNFKT2.js +0 -423
  87. package/dist/chunk-LXP73HJC.cjs +0 -4532
  88. package/dist/chunk-R6EBIR3T.cjs +0 -14
  89. package/dist/chunk-S4S2WXGC.js +0 -14
  90. package/dist/chunk-UMPUYLLZ.js +0 -4532
  91. package/dist/chunk-X5MKMFMX.js +0 -83
  92. package/dist/cli/index.cjs +0 -324
  93. package/dist/cli/index.d.cts +0 -22
  94. package/dist/cli/index.d.ts +0 -22
  95. package/dist/esbuild.cjs +0 -15
  96. package/dist/esbuild.d.cts +0 -11
  97. package/dist/esbuild.d.ts +0 -11
  98. package/dist/esbuild.js +0 -13
  99. package/dist/next/adapter.cjs +0 -31
  100. package/dist/next/adapter.js +0 -31
  101. package/dist/next/index.cjs +0 -18
  102. package/dist/next/index.d.cts +0 -42
  103. package/dist/next/index.d.ts +0 -42
  104. package/dist/next/index.js +0 -18
  105. package/dist/rollup.cjs +0 -15
  106. package/dist/rollup.d.cts +0 -11
  107. package/dist/rollup.d.ts +0 -11
  108. package/dist/rollup.js +0 -13
  109. package/dist/runtime/index.cjs +0 -17
  110. package/dist/runtime/index.d.cts +0 -36
  111. package/dist/runtime/index.d.ts +0 -36
  112. package/dist/runtime/index.js +0 -17
  113. package/dist/vite.cjs +0 -15
  114. package/dist/vite.d.cts +0 -11
  115. package/dist/vite.d.ts +0 -11
  116. package/dist/vite.js +0 -13
  117. package/dist/webpack.cjs +0 -15
  118. package/dist/webpack.d.cts +0 -11
  119. package/dist/webpack.d.ts +0 -11
  120. package/dist/webpack.js +0 -13
@@ -0,0 +1,429 @@
1
+ import {
2
+ chainSourceMaps,
3
+ computeDeterministicDebugId,
4
+ extractDebugId,
5
+ flattenSourceMapSections,
6
+ replaceOrAppendDebugId,
7
+ shiftSourceMapLines,
8
+ stripDebugIdComments,
9
+ stripSourceMapComments
10
+ } from "./chunk-ADKRENAP.js";
11
+ import {
12
+ computeFnv1aHash,
13
+ deriveWindowKeySymbol,
14
+ generateRuntimeShield,
15
+ transformJavaScript
16
+ } from "./chunk-4FNZNIBW.js";
17
+
18
+ // src/plugins/unplugin.ts
19
+ import fs from "fs";
20
+ import path from "path";
21
+ import { createUnplugin } from "unplugin";
22
+ var ENTRY_CHUNK_PATTERN = /(?:^|\/)(?:webpack|main|index|runtime|turbopack|pages\/_app|pages\/index)(?:[-._/]|$)/i;
23
+ var SW_OR_WORKBOX_PATTERN = /(?:^|\/)(?:sw|service-worker|workbox-[^/]+)\.(?:js|mjs|cjs)$|\.worker\.min\.(?:js|mjs|cjs)$/i;
24
+ function isSupportedJsAsset(fileName) {
25
+ const clean = fileName.replace(/\\/g, "/").split("?")[0].split("#")[0].toLowerCase();
26
+ return clean.endsWith(".js") || clean.endsWith(".mjs") || clean.endsWith(".cjs");
27
+ }
28
+ function isExcludedClientAsset(fileName, config) {
29
+ const norm = fileName.replace(/\\/g, "/").split("?")[0].split("#")[0];
30
+ if (norm.includes("server/") || norm.includes("ssr/") || norm.includes("node_modules/")) {
31
+ return true;
32
+ }
33
+ if (config?.target !== "worker" && SW_OR_WORKBOX_PATTERN.test(norm)) {
34
+ return true;
35
+ }
36
+ return false;
37
+ }
38
+ function createWebpackRawSource(sources, content) {
39
+ if (sources && typeof sources.RawSource === "function") {
40
+ return new sources.RawSource(content);
41
+ }
42
+ return {
43
+ source: () => content,
44
+ buffer: () => Buffer.from(content, "utf8"),
45
+ size: () => Buffer.byteLength(content, "utf8"),
46
+ map: () => null,
47
+ sourceAndMap: () => ({ source: content, map: null }),
48
+ updateHash: (hash) => {
49
+ hash.update(content);
50
+ }
51
+ };
52
+ }
53
+ var unpeekPlugin = createUnplugin((options = {}) => {
54
+ const config = options.config;
55
+ const baseSeed = typeof options.seed === "number" ? options.seed : Math.floor(Math.random() * 2147483647) || 322420463;
56
+ const deterrentMode = options.deterrentMode ?? config?.shield?.deterrentMode ?? "passive";
57
+ const detectHeadless = options.detectHeadless ?? config?.shield?.detectHeadless ?? false;
58
+ const injectRuntimeShield = options.injectRuntimeShield ?? true;
59
+ const minStringLength = options.minStringLength ?? config?.vault?.minStringLength ?? 4;
60
+ const aggressive = options.aggressive ?? false;
61
+ const masterSym = deriveWindowKeySymbol(baseSeed);
62
+ const masterShield = injectRuntimeShield ? generateRuntimeShield({
63
+ seed: baseSeed,
64
+ deterrentMode,
65
+ detectHeadless,
66
+ windowKeySymbol: masterSym
67
+ }) : void 0;
68
+ const transformChunk = (rawCode, fileName, isEntry, inputMap, requestMap = false) => {
69
+ const normalizedFileName = fileName.replace(/\\/g, "/").split("?")[0].split("#")[0];
70
+ if (!isSupportedJsAsset(normalizedFileName) || isExcludedClientAsset(normalizedFileName, config)) {
71
+ return null;
72
+ }
73
+ const fileDebugId = extractDebugId(rawCode);
74
+ const shouldStripComments = config?.sourcemaps?.stripComments !== false;
75
+ let codeToTransform = rawCode;
76
+ if (shouldStripComments && rawCode.includes("sourceMappingURL=")) {
77
+ codeToTransform = stripSourceMapComments(rawCode).code;
78
+ }
79
+ const shouldInjectShield = injectRuntimeShield && isEntry;
80
+ const chunkSeed = computeFnv1aHash(fileName, baseSeed);
81
+ const transformOptions = {
82
+ seed: chunkSeed,
83
+ minStringLength,
84
+ filename: fileName,
85
+ injectRuntimeShield: shouldInjectShield,
86
+ skipShieldPreamble: true,
87
+ shieldCoupled: injectRuntimeShield,
88
+ windowKeySymbol: masterSym,
89
+ expectedDelta: masterShield?.expectedDelta,
90
+ deterrentMode,
91
+ detectHeadless,
92
+ aggressive,
93
+ config
94
+ };
95
+ transformOptions.generateMap = requestMap || Boolean(inputMap);
96
+ transformOptions.rootDir = process.cwd();
97
+ const result = transformJavaScript(codeToTransform, transformOptions);
98
+ let finalCode = result.code;
99
+ let preambleLineOffset = 0;
100
+ const integrityCheckFnName = masterShield && "integrityCheckFnName" in masterShield ? masterShield.integrityCheckFnName : void 0;
101
+ if (shouldInjectShield && masterShield?.preambleCode && !finalCode.includes("(function _u$") && (!integrityCheckFnName || !finalCode.includes(integrityCheckFnName)) && !finalCode.startsWith(masterShield.preambleCode)) {
102
+ const prefix = `${masterShield.preambleCode}
103
+ `;
104
+ preambleLineOffset = (prefix.match(/\n/g) ?? []).length;
105
+ finalCode = `${prefix}${finalCode}`;
106
+ }
107
+ const rawTransformMap = result.sourceMap;
108
+ const shiftedTransformMap = rawTransformMap ? shiftSourceMapLines(rawTransformMap, preambleLineOffset) : void 0;
109
+ let composedMap = null;
110
+ if (shiftedTransformMap && inputMap) {
111
+ composedMap = chainSourceMaps(shiftedTransformMap, inputMap);
112
+ } else if (shiftedTransformMap) {
113
+ composedMap = shiftedTransformMap;
114
+ } else if (inputMap) {
115
+ composedMap = flattenSourceMapSections(inputMap);
116
+ }
117
+ const inputMapDebugId = inputMap?.debugId ?? inputMap?.debug_id;
118
+ const hadDebugId = Boolean(fileDebugId || inputMapDebugId || result.debugId);
119
+ if (hadDebugId) {
120
+ const codeWithoutDebugId = stripDebugIdComments(finalCode);
121
+ const mintedDebugId = computeDeterministicDebugId(
122
+ codeWithoutDebugId,
123
+ composedMap?.mappings ?? ""
124
+ );
125
+ finalCode = replaceOrAppendDebugId(codeWithoutDebugId, mintedDebugId);
126
+ if (composedMap) {
127
+ composedMap.debugId = mintedDebugId;
128
+ delete composedMap.debug_id;
129
+ }
130
+ }
131
+ if (composedMap) {
132
+ if (!Object.prototype.hasOwnProperty.call(composedMap, "toString")) {
133
+ Object.defineProperty(composedMap, "toString", {
134
+ enumerable: false,
135
+ configurable: true,
136
+ value() {
137
+ return JSON.stringify(this);
138
+ }
139
+ });
140
+ }
141
+ }
142
+ return {
143
+ code: finalCode,
144
+ map: composedMap
145
+ };
146
+ };
147
+ const renderChunkHandler = (code, chunk) => {
148
+ const normalizedFileName = chunk.fileName.replace(/\\/g, "/").split("?")[0].split("#")[0];
149
+ const isEntry = chunk.isEntry !== void 0 ? chunk.isEntry : ENTRY_CHUNK_PATTERN.test(normalizedFileName);
150
+ const res = transformChunk(code, chunk.fileName, isEntry, void 0, true);
151
+ if (!res) {
152
+ return null;
153
+ }
154
+ return {
155
+ code: res.code,
156
+ map: res.map ?? null
157
+ };
158
+ };
159
+ const attachWebpackLikeProcessAssets = (compiler, framework) => {
160
+ compiler.hooks.thisCompilation.tap("unpeek", (compilation) => {
161
+ const stage = (framework === "rspack" ? compiler.rspack?.Compilation?.PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE : compiler.webpack?.Compilation?.PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE) ?? 700;
162
+ compilation.hooks.processAssets.tap(
163
+ { name: "unpeek", stage },
164
+ (assets) => {
165
+ const entryFiles = /* @__PURE__ */ new Set();
166
+ if (compilation.entrypoints && typeof compilation.entrypoints.values === "function") {
167
+ for (const ep of compilation.entrypoints.values()) {
168
+ if (ep && typeof ep.getFiles === "function") {
169
+ for (const f of ep.getFiles()) {
170
+ entryFiles.add(String(f).replace(/\\/g, "/").split("?")[0]);
171
+ }
172
+ }
173
+ }
174
+ }
175
+ if (compilation.chunks) {
176
+ for (const chunk of compilation.chunks) {
177
+ const chunkIsEntry = typeof chunk.hasRuntime === "function" && chunk.hasRuntime() || typeof chunk.canBeInitial === "function" && chunk.canBeInitial();
178
+ if (chunkIsEntry && chunk.files) {
179
+ for (const f of chunk.files) {
180
+ entryFiles.add(String(f).replace(/\\/g, "/").split("?")[0]);
181
+ }
182
+ }
183
+ }
184
+ }
185
+ const sources = (framework === "rspack" ? compiler.rspack?.sources : compiler.webpack?.sources) ?? compiler.webpack?.sources ?? compiler.rspack?.sources;
186
+ for (const assetName of Object.keys(assets)) {
187
+ const normalizedName = assetName.replace(/\\/g, "/").split("?")[0];
188
+ if (!isSupportedJsAsset(normalizedName) || isExcludedClientAsset(normalizedName, config)) {
189
+ continue;
190
+ }
191
+ const existingAsset = typeof compilation.getAsset === "function" ? compilation.getAsset(assetName) : { source: assets[assetName] };
192
+ const sourceObj = existingAsset?.source ?? assets[assetName];
193
+ if (!sourceObj) continue;
194
+ const rawContent = typeof sourceObj.source === "function" ? sourceObj.source() : sourceObj;
195
+ const code = Buffer.isBuffer(rawContent) ? rawContent.toString("utf8") : String(rawContent);
196
+ const mapAssetName = `${assetName}.map`;
197
+ const mapSourceObj = assets[mapAssetName];
198
+ let inputMap;
199
+ if (mapSourceObj) {
200
+ try {
201
+ const rawMap = typeof mapSourceObj.source === "function" ? mapSourceObj.source() : mapSourceObj;
202
+ const mapStr = Buffer.isBuffer(rawMap) ? rawMap.toString("utf8") : String(rawMap);
203
+ inputMap = JSON.parse(mapStr);
204
+ } catch {
205
+ }
206
+ } else if (typeof sourceObj.map === "function") {
207
+ try {
208
+ const m = sourceObj.map();
209
+ if (m && typeof m === "object") {
210
+ inputMap = m;
211
+ }
212
+ } catch {
213
+ }
214
+ }
215
+ const isEntry = entryFiles.size > 0 ? entryFiles.has(normalizedName) || ENTRY_CHUNK_PATTERN.test(normalizedName) : ENTRY_CHUNK_PATTERN.test(normalizedName);
216
+ const res = transformChunk(code, assetName, isEntry, inputMap, Boolean(inputMap));
217
+ if (!res) continue;
218
+ const newSource = createWebpackRawSource(sources, res.code);
219
+ if (typeof compilation.updateAsset === "function") {
220
+ compilation.updateAsset(assetName, newSource);
221
+ } else {
222
+ assets[assetName] = newSource;
223
+ }
224
+ if (res.map && mapSourceObj) {
225
+ const newMapSource = createWebpackRawSource(sources, JSON.stringify(res.map));
226
+ if (typeof compilation.updateAsset === "function") {
227
+ compilation.updateAsset(mapAssetName, newMapSource);
228
+ } else {
229
+ assets[mapAssetName] = newMapSource;
230
+ }
231
+ }
232
+ }
233
+ }
234
+ );
235
+ });
236
+ };
237
+ return {
238
+ name: "unpeek",
239
+ enforce: "post",
240
+ // Preserved at top-level for direct unpeekPlugin.raw() unit test compatibility and Rollup
241
+ renderChunk: renderChunkHandler,
242
+ rollup: {
243
+ renderChunk: renderChunkHandler
244
+ },
245
+ vite: {
246
+ enforce: "post",
247
+ apply: "build",
248
+ renderChunk: void 0,
249
+ config(userConfig) {
250
+ if (config?.target === "worker") {
251
+ return void 0;
252
+ }
253
+ const existingWorkerPlugins = userConfig?.worker?.plugins;
254
+ return {
255
+ worker: {
256
+ plugins: () => {
257
+ const resolved = typeof existingWorkerPlugins === "function" ? existingWorkerPlugins() : Array.isArray(existingWorkerPlugins) ? existingWorkerPlugins : [];
258
+ const flat = (Array.isArray(resolved) ? resolved : [resolved]).flat(Infinity).filter(Boolean);
259
+ if (flat.some((p) => p && p.name === "unpeek")) {
260
+ return flat;
261
+ }
262
+ return [
263
+ ...flat,
264
+ vitePlugin({
265
+ ...options,
266
+ seed: baseSeed,
267
+ config: {
268
+ ...config ?? {},
269
+ target: "worker"
270
+ }
271
+ })
272
+ ];
273
+ }
274
+ }
275
+ };
276
+ },
277
+ generateBundle(_outputOptions, bundle) {
278
+ for (const [fileName, item] of Object.entries(bundle)) {
279
+ if (!item || item.type !== "chunk") continue;
280
+ const normalizedFileName = fileName.replace(/\\/g, "/").split("?")[0].split("#")[0];
281
+ if (!isSupportedJsAsset(normalizedFileName) || isExcludedClientAsset(normalizedFileName, config)) {
282
+ continue;
283
+ }
284
+ const mapAssetKey = `${fileName}.map`;
285
+ const mapAsset = bundle[mapAssetKey];
286
+ let inputMap = item.map && typeof item.map === "object" ? item.map : void 0;
287
+ if (!inputMap && mapAsset && mapAsset.type === "asset") {
288
+ try {
289
+ const rawMapStr = typeof mapAsset.source === "string" ? mapAsset.source : Buffer.from(mapAsset.source).toString("utf8");
290
+ inputMap = JSON.parse(rawMapStr);
291
+ } catch {
292
+ }
293
+ }
294
+ const isEntry = typeof item.isEntry === "boolean" ? item.isEntry : ENTRY_CHUNK_PATTERN.test(normalizedFileName);
295
+ const res = transformChunk(item.code, fileName, isEntry, inputMap, Boolean(inputMap));
296
+ if (!res) continue;
297
+ item.code = res.code;
298
+ if (res.map) {
299
+ item.map = res.map;
300
+ if (mapAsset && mapAsset.type === "asset") {
301
+ mapAsset.source = JSON.stringify(res.map);
302
+ }
303
+ }
304
+ }
305
+ }
306
+ },
307
+ webpack(compiler) {
308
+ attachWebpackLikeProcessAssets(compiler, "webpack");
309
+ },
310
+ rspack(compiler) {
311
+ attachWebpackLikeProcessAssets(compiler, "rspack");
312
+ },
313
+ esbuild: {
314
+ config(buildOptions) {
315
+ buildOptions.metafile = true;
316
+ },
317
+ setup(build) {
318
+ build.onEnd(async (result) => {
319
+ const workDir = build.initialOptions.absWorkingDir ?? process.cwd();
320
+ const entryOutputs = /* @__PURE__ */ new Set();
321
+ if (result.metafile?.outputs) {
322
+ for (const [outKey, meta] of Object.entries(result.metafile.outputs)) {
323
+ if (meta && meta.entryPoint) {
324
+ entryOutputs.add(path.resolve(workDir, outKey));
325
+ entryOutputs.add(outKey.replace(/\\/g, "/"));
326
+ }
327
+ }
328
+ }
329
+ if (Array.isArray(result.outputFiles) && result.outputFiles.length > 0) {
330
+ const mapFilesByPath = /* @__PURE__ */ new Map();
331
+ for (const outFile of result.outputFiles) {
332
+ if (outFile.path.endsWith(".map")) {
333
+ mapFilesByPath.set(outFile.path, outFile);
334
+ }
335
+ }
336
+ const jsOutCount = result.outputFiles.filter((f) => isSupportedJsAsset(f.path)).length;
337
+ for (const outFile of result.outputFiles) {
338
+ const normPath = outFile.path.replace(/\\/g, "/");
339
+ if (!isSupportedJsAsset(normPath) || isExcludedClientAsset(normPath, config)) {
340
+ continue;
341
+ }
342
+ const mapFile = mapFilesByPath.get(`${outFile.path}.map`);
343
+ let inputMap;
344
+ if (mapFile) {
345
+ try {
346
+ inputMap = JSON.parse(mapFile.text);
347
+ } catch {
348
+ }
349
+ }
350
+ const relFromWork = path.relative(workDir, outFile.path).replace(/\\/g, "/");
351
+ 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
+ const res = transformChunk(
353
+ outFile.text,
354
+ relFromWork || path.basename(outFile.path),
355
+ isEntry,
356
+ inputMap,
357
+ Boolean(inputMap)
358
+ );
359
+ if (!res) continue;
360
+ outFile.contents = Buffer.from(res.code, "utf8");
361
+ if (res.map && mapFile) {
362
+ mapFile.contents = Buffer.from(JSON.stringify(res.map), "utf8");
363
+ }
364
+ }
365
+ return;
366
+ }
367
+ const diskOutputs = /* @__PURE__ */ new Set();
368
+ if (result.metafile?.outputs) {
369
+ for (const outKey of Object.keys(result.metafile.outputs)) {
370
+ const abs = path.resolve(workDir, outKey);
371
+ if (isSupportedJsAsset(abs)) {
372
+ diskOutputs.add(abs);
373
+ }
374
+ }
375
+ } else if (build.initialOptions.outfile) {
376
+ const abs = path.resolve(workDir, build.initialOptions.outfile);
377
+ if (isSupportedJsAsset(abs)) {
378
+ diskOutputs.add(abs);
379
+ }
380
+ }
381
+ const diskArr = Array.from(diskOutputs);
382
+ for (const absPath of diskArr) {
383
+ const relFromWork = path.relative(workDir, absPath).replace(/\\/g, "/");
384
+ if (isExcludedClientAsset(relFromWork, config)) continue;
385
+ if (!fs.existsSync(absPath)) continue;
386
+ const code = fs.readFileSync(absPath, "utf8");
387
+ const mapPath = `${absPath}.map`;
388
+ let inputMap;
389
+ if (fs.existsSync(mapPath)) {
390
+ try {
391
+ inputMap = JSON.parse(fs.readFileSync(mapPath, "utf8"));
392
+ } catch {
393
+ }
394
+ }
395
+ const isEntry = entryOutputs.size > 0 ? entryOutputs.has(absPath) || entryOutputs.has(relFromWork) || ENTRY_CHUNK_PATTERN.test(relFromWork) : ENTRY_CHUNK_PATTERN.test(relFromWork) || diskArr.length === 1;
396
+ const res = transformChunk(
397
+ code,
398
+ relFromWork || path.basename(absPath),
399
+ isEntry,
400
+ inputMap,
401
+ Boolean(inputMap)
402
+ );
403
+ if (!res) continue;
404
+ fs.writeFileSync(absPath, res.code, "utf8");
405
+ if (res.map && fs.existsSync(mapPath)) {
406
+ fs.writeFileSync(mapPath, JSON.stringify(res.map), "utf8");
407
+ }
408
+ }
409
+ });
410
+ }
411
+ }
412
+ };
413
+ });
414
+ var vitePlugin = unpeekPlugin.vite;
415
+ var webpackPlugin = unpeekPlugin.webpack;
416
+ var rollupPlugin = unpeekPlugin.rollup;
417
+ var esbuildPlugin = unpeekPlugin.esbuild;
418
+ var rspackPlugin = unpeekPlugin.rspack;
419
+ var unplugin_default = unpeekPlugin;
420
+
421
+ export {
422
+ unpeekPlugin,
423
+ vitePlugin,
424
+ webpackPlugin,
425
+ rollupPlugin,
426
+ esbuildPlugin,
427
+ rspackPlugin,
428
+ unplugin_default
429
+ };
@@ -1,27 +1,33 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
2
 
3
- var _chunk7YVEHJVMcjs = require('./chunk-7YVEHJVM.cjs');
4
3
 
4
+ var _chunk7HXLHLLQcjs = require('./chunk-7HXLHLLQ.cjs');
5
5
 
6
- var _chunk6N6S6WTQcjs = require('./chunk-6N6S6WTQ.cjs');
7
6
 
7
+ var _chunk3LWXEJU6cjs = require('./chunk-3LWXEJU6.cjs');
8
8
 
9
9
 
10
- var _chunk4TDLLEEUcjs = require('./chunk-4TDLLEEU.cjs');
10
+ var _chunkKLYFNMKScjs = require('./chunk-KLYFNMKS.cjs');
11
11
 
12
- // src/next/index.ts
12
+
13
+
14
+
15
+ var _chunkL6BOM5VScjs = require('./chunk-L6BOM5VS.cjs');
16
+
17
+ // src/adapters/next/index.ts
13
18
  var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);
14
19
  var _path = require('path'); var _path2 = _interopRequireDefault(_path);
15
20
  var _crypto = require('crypto'); var _crypto2 = _interopRequireDefault(_crypto);
16
21
  var _url = require('url');
17
22
  var _module = require('module');
23
+ var MAX_NEXT_OPTIONS_ENV_BYTES = 32767;
18
24
  async function loadUpstreamAdapter(adapterPath) {
19
25
  const resolved = _path2.default.isAbsolute(adapterPath) ? adapterPath : _path2.default.resolve(process.cwd(), adapterPath);
20
26
  try {
21
27
  const mod = await Promise.resolve().then(() => _interopRequireWildcard(require(_url.pathToFileURL.call(void 0, resolved).href)));
22
28
  return _nullishCoalesce(mod.default, () => ( mod));
23
29
  } catch (e) {
24
- const req = _module.createRequire.call(void 0, _chunk4TDLLEEUcjs.importMetaUrl);
30
+ const req = _module.createRequire.call(void 0, _chunkL6BOM5VScjs.importMetaUrl);
25
31
  const mod = req(resolved);
26
32
  return _nullishCoalesce(mod.default, () => ( mod));
27
33
  }
@@ -31,11 +37,31 @@ function recomputeHash(content, existingHash) {
31
37
  const algo = len === 64 ? "sha256" : len === 40 ? "sha1" : len === 32 ? "md5" : "sha256";
32
38
  return _crypto2.default.createHash(algo).update(content).digest("hex");
33
39
  }
40
+ function isNonProductionPhase(phase) {
41
+ return phase !== void 0 && phase !== "phase-production-build" && phase !== "phase-export";
42
+ }
43
+ async function delegateToUpstreamOnBuildComplete(upstreamPath, context) {
44
+ if (!upstreamPath) return;
45
+ try {
46
+ const upstream = await loadUpstreamAdapter(upstreamPath);
47
+ if (upstream && typeof upstream !== "function" && typeof upstream.onBuildComplete === "function") {
48
+ await upstream.onBuildComplete(context);
49
+ } else if (typeof upstream === "function") {
50
+ await upstream(context);
51
+ }
52
+ } catch (err) {
53
+ console.warn("[unpeek:next] Failed to delegate to upstream adapter onBuildComplete:", err);
54
+ }
55
+ }
34
56
  function createUnpeekNextAdapter(options = {}) {
35
57
  const upstreamPath = options.upstreamAdapterPath || process.env.UNPEEK_UPSTREAM_ADAPTER_PATH || process.env.NEXT_ADAPTER_PATH;
58
+ let recordedPhase;
36
59
  return {
37
60
  name: "unpeek",
38
61
  async modifyConfig(config, context) {
62
+ if (context && typeof context.phase === "string") {
63
+ recordedPhase = context.phase;
64
+ }
39
65
  if (upstreamPath) {
40
66
  try {
41
67
  const upstream = await loadUpstreamAdapter(upstreamPath);
@@ -53,8 +79,28 @@ function createUnpeekNextAdapter(options = {}) {
53
79
  const distDir = _path2.default.resolve(cwd, context.distDir || ".next");
54
80
  const staticDir = _path2.default.join(distDir, "static");
55
81
  const targetDir = _fs2.default.existsSync(staticDir) ? staticDir : distDir;
56
- const deterministicSeed = typeof options.seed === "number" ? options.seed : context.buildId ? _chunk6N6S6WTQcjs.computeFnv1aHash.call(void 0, context.buildId, 1597463007) : 1597463007;
57
- const summary = await _chunk7YVEHJVMcjs.protectProject.call(void 0, {
82
+ const phase = _nullishCoalesce(context.phase, () => ( recordedPhase));
83
+ if (isNonProductionPhase(phase)) {
84
+ await delegateToUpstreamOnBuildComplete(upstreamPath, context);
85
+ return {
86
+ framework: "nextjs",
87
+ outDir: targetDir,
88
+ processedFiles: 0,
89
+ movedSourceMaps: 0,
90
+ originalBytes: 0,
91
+ protectedBytes: 0,
92
+ originalGzipBytes: 0,
93
+ protectedGzipBytes: 0,
94
+ gzipDeltaPercent: 0,
95
+ totalHotFunctionsSkipped: 0,
96
+ totalColdFunctionsProtected: 0,
97
+ totalEncryptedStrings: 0,
98
+ totalMangledSymbols: 0,
99
+ elapsedMs: 0
100
+ };
101
+ }
102
+ const deterministicSeed = typeof options.seed === "number" ? options.seed : context.buildId ? _chunkKLYFNMKScjs.computeFnv1aHash.call(void 0, context.buildId, 1597463007) : 1597463007;
103
+ const summary = await _chunk7HXLHLLQcjs.protectProject.call(void 0, {
58
104
  ...options,
59
105
  cwd,
60
106
  outDir: targetDir,
@@ -69,7 +115,7 @@ function createUnpeekNextAdapter(options = {}) {
69
115
  if (!rawFilePath) continue;
70
116
  let absPath = _path2.default.isAbsolute(rawFilePath) ? rawFilePath : _path2.default.resolve(cwd, rawFilePath);
71
117
  if (!_fs2.default.existsSync(absPath)) {
72
- const relClean = rawFilePath.replace(/\\/g, "/").replace(/^\/?(?:_next\/|\.next\/)/, "");
118
+ const relClean = _chunk3LWXEJU6cjs.safeDecodeURIComponent.call(void 0, rawFilePath).replace(/\\/g, "/").replace(/^\/?(?:_next\/|\.next\/)/, "");
73
119
  const fromDist = _path2.default.resolve(distDir, relClean);
74
120
  if (_fs2.default.existsSync(fromDist)) {
75
121
  absPath = fromDist;
@@ -98,25 +144,14 @@ function createUnpeekNextAdapter(options = {}) {
98
144
  }
99
145
  }
100
146
  }
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
- }
147
+ await delegateToUpstreamOnBuildComplete(upstreamPath, context);
113
148
  return summary;
114
149
  }
115
150
  };
116
151
  }
117
152
  function getUnpeekAdapterPath() {
118
153
  try {
119
- const req = typeof _chunk4TDLLEEUcjs.__require !== "undefined" ? _chunk4TDLLEEUcjs.__require : _module.createRequire.call(void 0, _chunk4TDLLEEUcjs.importMetaUrl);
154
+ const req = typeof _chunkL6BOM5VScjs.__require !== "undefined" ? _chunkL6BOM5VScjs.__require : _module.createRequire.call(void 0, _chunkL6BOM5VScjs.importMetaUrl);
120
155
  try {
121
156
  const resolved = req.resolve("unpeek/next/adapter");
122
157
  if (_fs2.default.existsSync(resolved)) {
@@ -125,16 +160,16 @@ function getUnpeekAdapterPath() {
125
160
  } catch (e3) {
126
161
  }
127
162
  const isCjs = typeof __dirname !== "undefined";
128
- const currentDir = isCjs ? __dirname : _path2.default.dirname(_url.fileURLToPath.call(void 0, _chunk4TDLLEEUcjs.importMetaUrl));
163
+ const currentDir = isCjs ? __dirname : _path2.default.dirname(_url.fileURLToPath.call(void 0, _chunkL6BOM5VScjs.importMetaUrl));
129
164
  const candidates = [
130
- _path2.default.resolve(currentDir, isCjs ? "next/adapter.cjs" : "next/adapter.js"),
131
- _path2.default.resolve(currentDir, isCjs ? "next/adapter.js" : "next/adapter.cjs"),
165
+ _path2.default.resolve(currentDir, isCjs ? "adapters/next/adapter.cjs" : "adapters/next/adapter.js"),
166
+ _path2.default.resolve(currentDir, isCjs ? "adapters/next/adapter.js" : "adapters/next/adapter.cjs"),
132
167
  _path2.default.resolve(currentDir, isCjs ? "adapter.cjs" : "adapter.js"),
133
168
  _path2.default.resolve(currentDir, isCjs ? "adapter.js" : "adapter.cjs"),
134
- _path2.default.resolve(currentDir, "../dist/next/adapter.cjs"),
135
- _path2.default.resolve(currentDir, "../dist/next/adapter.js"),
136
- _path2.default.resolve(process.cwd(), "node_modules/unpeek/dist/next/adapter.cjs"),
137
- _path2.default.resolve(process.cwd(), "node_modules/unpeek/dist/next/adapter.js")
169
+ _path2.default.resolve(currentDir, "../dist/adapters/next/adapter.cjs"),
170
+ _path2.default.resolve(currentDir, "../dist/adapters/next/adapter.js"),
171
+ _path2.default.resolve(process.cwd(), "node_modules/unpeek/dist/adapters/next/adapter.cjs"),
172
+ _path2.default.resolve(process.cwd(), "node_modules/unpeek/dist/adapters/next/adapter.js")
138
173
  ];
139
174
  for (const cand of candidates) {
140
175
  if (_fs2.default.existsSync(cand)) {
@@ -143,23 +178,9 @@ function getUnpeekAdapterPath() {
143
178
  }
144
179
  return candidates[0];
145
180
  } catch (e4) {
146
- return _path2.default.resolve(process.cwd(), "node_modules/unpeek/dist/next/adapter.js");
181
+ return _path2.default.resolve(process.cwd(), "node_modules/unpeek/dist/adapters/next/adapter.js");
147
182
  }
148
183
  }
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 (e5) {
160
- }
161
- return void 0;
162
- }
163
184
  function applyWithUnpeek(config = {}, options) {
164
185
  const existingAdapter = config.adapterPath || process.env.NEXT_ADAPTER_PATH;
165
186
  if (existingAdapter && !process.env.UNPEEK_UPSTREAM_ADAPTER_PATH) {
@@ -169,7 +190,15 @@ function applyWithUnpeek(config = {}, options) {
169
190
  process.env.UNPEEK_UPSTREAM_ADAPTER_PATH = options.upstreamAdapterPath;
170
191
  }
171
192
  if (options) {
172
- process.env.UNPEEK_NEXT_OPTIONS = JSON.stringify(options);
193
+ const serialized = _chunk7HXLHLLQcjs.serializeNextOptions.call(void 0, options);
194
+ const byteLength = Buffer.byteLength(serialized, "utf8");
195
+ if (byteLength > MAX_NEXT_OPTIONS_ENV_BYTES) {
196
+ throw new (0, _chunkL6BOM5VScjs.UnpeekError)(
197
+ "ERR_NEXT_ADAPTER",
198
+ `Serialized UNPEEK_NEXT_OPTIONS (${byteLength} bytes) exceeds the ${MAX_NEXT_OPTIONS_ENV_BYTES}-byte process.env limit.`
199
+ );
200
+ }
201
+ process.env.UNPEEK_NEXT_OPTIONS = serialized;
173
202
  } else {
174
203
  delete process.env.UNPEEK_NEXT_OPTIONS;
175
204
  }
@@ -181,10 +210,14 @@ function applyWithUnpeek(config = {}, options) {
181
210
  }
182
211
  function withUnpeek(nextConfig = {}, options) {
183
212
  if (typeof nextConfig === "function") {
184
- return (async (...args) => {
213
+ return async (...args) => {
185
214
  const resolved = await nextConfig(...args);
215
+ const phase = typeof args[0] === "string" ? args[0] : void 0;
216
+ if (isNonProductionPhase(phase)) {
217
+ return resolved;
218
+ }
186
219
  return applyWithUnpeek(resolved, options);
187
- });
220
+ };
188
221
  }
189
222
  return applyWithUnpeek(nextConfig, options);
190
223
  }
@@ -193,5 +226,4 @@ function withUnpeek(nextConfig = {}, options) {
193
226
 
194
227
 
195
228
 
196
-
197
- exports.createUnpeekNextAdapter = createUnpeekNextAdapter; exports.getUnpeekAdapterPath = getUnpeekAdapterPath; exports.readUnpeekNextOptionsFromEnv = readUnpeekNextOptionsFromEnv; exports.withUnpeek = withUnpeek;
229
+ exports.createUnpeekNextAdapter = createUnpeekNextAdapter; exports.getUnpeekAdapterPath = getUnpeekAdapterPath; exports.withUnpeek = withUnpeek;