nitro-nightly 3.0.1-20260119-145349-d0c4950f → 3.0.1-20260120-020848-6786d069

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 (70) hide show
  1. package/dist/_build/rolldown.mjs +13 -8
  2. package/dist/_build/vite.build.mjs +1 -1
  3. package/dist/_chunks/dev.mjs +5 -3
  4. package/dist/_chunks/nitro.mjs +24 -1183
  5. package/dist/_chunks/nitro2.mjs +248 -91
  6. package/dist/_chunks/nitro3.mjs +2696 -0
  7. package/dist/_chunks/nitro4.mjs +176 -0
  8. package/dist/_chunks/nitro5.mjs +733 -0
  9. package/dist/_chunks/nitro6.mjs +1458 -0
  10. package/dist/_chunks/nitro7.mjs +7561 -0
  11. package/dist/_chunks/nitro8.mjs +3524 -0
  12. package/dist/_chunks/nitro9.mjs +1729 -0
  13. package/dist/_libs/_.mjs +3 -0
  14. package/dist/_libs/_2.mjs +3 -0
  15. package/dist/_libs/_3.mjs +4 -0
  16. package/dist/_libs/_4.mjs +6 -0
  17. package/dist/_libs/_5.mjs +3 -0
  18. package/dist/_libs/_6.mjs +3 -0
  19. package/dist/_libs/acorn+confbox+js-tokens+magic-string+mlly+pkg-types+sourcemap-codec+strip-literal+unimport.mjs +8900 -0
  20. package/dist/_libs/{c12.mjs → c12+dotenv+rc9.mjs} +12 -105
  21. package/dist/_libs/{chokidar.mjs → chokidar+readdirp.mjs} +2 -9
  22. package/dist/_libs/confbox+exsolve+pkg-types.mjs +1249 -0
  23. package/dist/_libs/confbox.mjs +70 -2488
  24. package/dist/_libs/confbox2.mjs +786 -0
  25. package/dist/_libs/confbox3.mjs +404 -0
  26. package/dist/_libs/confbox4.mjs +3 -0
  27. package/dist/_libs/estree-walker+unimport.mjs +378 -0
  28. package/dist/_libs/fdir+picomatch+tinyglobby.mjs +2471 -0
  29. package/dist/_libs/gen-mapping+remapping+resolve-uri+trace-mapping+unimport+unplugin+unplugin-utils+webpack-virtual-modules.mjs +2150 -0
  30. package/dist/_libs/giget+node-fetch-native.mjs +2692 -0
  31. package/dist/_libs/httpxy.mjs +1 -6
  32. package/dist/_libs/local-pkg+quansync+unimport.mjs +1526 -0
  33. package/dist/_libs/nypm+tinyexec.mjs +858 -0
  34. package/dist/_libs/pathe.mjs +164 -0
  35. package/dist/_libs/perfect-debounce.mjs +89 -0
  36. package/dist/_libs/{@rollup/plugin-inject.mjs → plugin-alias+plugin-inject.mjs} +65 -2
  37. package/dist/_libs/std-env.mjs +158 -0
  38. package/dist/_libs/unimport.mjs +5 -1781
  39. package/dist/_libs/vite-plugin-fullstack.mjs +26 -0
  40. package/dist/_presets.mjs +8 -3
  41. package/dist/builder.mjs +8 -6
  42. package/dist/cli/_chunks/build.mjs +1 -1
  43. package/dist/cli/_chunks/dev.mjs +3 -2
  44. package/dist/cli/_chunks/list.mjs +1 -1
  45. package/dist/cli/_chunks/prepare.mjs +1 -1
  46. package/dist/cli/_chunks/run.mjs +1 -1
  47. package/dist/cli/index.mjs +1 -1
  48. package/dist/types/index.d.mts +2410 -1174
  49. package/dist/vite.d.mts +13 -13
  50. package/dist/vite.mjs +640 -16
  51. package/package.json +9 -9
  52. package/dist/_build/common.mjs +0 -24931
  53. package/dist/_build/rollup.mjs +0 -201
  54. package/dist/_chunks/utils.mjs +0 -254
  55. package/dist/_common.mjs +0 -45
  56. package/dist/_libs/@hiogawa/vite-plugin-fullstack.mjs +0 -652
  57. package/dist/_libs/@jridgewell/gen-mapping.mjs +0 -448
  58. package/dist/_libs/@jridgewell/remapping.mjs +0 -117
  59. package/dist/_libs/@rollup/plugin-alias.mjs +0 -64
  60. package/dist/_libs/@rollup/plugin-commonjs.mjs +0 -1300
  61. package/dist/_libs/@rollup/plugin-json.mjs +0 -36
  62. package/dist/_libs/@rollup/plugin-node-resolve.mjs +0 -1972
  63. package/dist/_libs/escape-string-regexp.mjs +0 -8
  64. package/dist/_libs/estree-walker.mjs +0 -187
  65. package/dist/_libs/giget.mjs +0 -3550
  66. package/dist/_libs/klona.mjs +0 -38
  67. package/dist/_libs/rou3.mjs +0 -322
  68. package/dist/_libs/tsconfck.mjs +0 -832
  69. package/dist/_libs/ultrahtml.mjs +0 -138
  70. package/dist/cli/_chunks/task.mjs +0 -16
@@ -1,1300 +0,0 @@
1
- import { i as __toESM, r as __require, t as __commonJSMin } from "../../_common.mjs";
2
- import { c as createFilter, d as makeLegalIdentifier, f as walk, ot as Builder, q as MagicString, s as attachScopes, u as extractAssignedNames } from "../../_build/common.mjs";
3
- import { existsSync, readFileSync, statSync } from "fs";
4
- import { basename, dirname, extname, join, relative, resolve, sep } from "path";
5
-
6
- //#region node_modules/.pnpm/commondir@1.0.1/node_modules/commondir/index.js
7
- var require_commondir = /* @__PURE__ */ __commonJSMin(((exports, module) => {
8
- var path$1 = __require("path");
9
- module.exports = function(basedir, relfiles) {
10
- if (relfiles) var files = relfiles.map(function(r) {
11
- return path$1.resolve(basedir, r);
12
- });
13
- else var files = basedir;
14
- var res = files.slice(1).reduce(function(ps, file) {
15
- if (!file.match(/^([A-Za-z]:)?\/|\\/)) throw new Error("relative path without a basedir");
16
- var xs = file.split(/\/+|\\+/);
17
- for (var i = 0; ps[i] === xs[i] && i < Math.min(ps.length, xs.length); i++);
18
- return ps.slice(0, i);
19
- }, files[0].split(/\/+|\\+/));
20
- return res.length > 1 ? res.join("/") : "/";
21
- };
22
- }));
23
-
24
- //#endregion
25
- //#region node_modules/.pnpm/is-reference@1.2.1/node_modules/is-reference/dist/is-reference.js
26
- var require_is_reference = /* @__PURE__ */ __commonJSMin(((exports, module) => {
27
- (function(global, factory) {
28
- typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() : typeof define === "function" && define.amd ? define(factory) : (global = global || self, global.isReference = factory());
29
- })(exports, (function() {
30
- "use strict";
31
- function isReference$1(node, parent) {
32
- if (node.type === "MemberExpression") return !node.computed && isReference$1(node.object, node);
33
- if (node.type === "Identifier") {
34
- if (!parent) return true;
35
- switch (parent.type) {
36
- case "MemberExpression": return parent.computed || node === parent.object;
37
- case "MethodDefinition": return parent.computed;
38
- case "FieldDefinition": return parent.computed || node === parent.value;
39
- case "Property": return parent.computed || node === parent.value;
40
- case "ExportSpecifier":
41
- case "ImportSpecifier": return node === parent.local;
42
- case "LabeledStatement":
43
- case "BreakStatement":
44
- case "ContinueStatement": return false;
45
- default: return true;
46
- }
47
- }
48
- return false;
49
- }
50
- return isReference$1;
51
- }));
52
- }));
53
-
54
- //#endregion
55
- //#region node_modules/.pnpm/@rollup+plugin-commonjs@29.0.0_rollup@4.55.2/node_modules/@rollup/plugin-commonjs/dist/es/index.js
56
- var import_commondir = /* @__PURE__ */ __toESM(require_commondir(), 1);
57
- var import_is_reference = /* @__PURE__ */ __toESM(require_is_reference(), 1);
58
- var version = "29.0.0";
59
- var peerDependencies = { rollup: "^2.68.0||^3.0.0||^4.0.0" };
60
- function tryParse(parse, code, id) {
61
- try {
62
- return parse(code, { allowReturnOutsideFunction: true });
63
- } catch (err) {
64
- err.message += ` in ${id}`;
65
- throw err;
66
- }
67
- }
68
- const firstpassGlobal = /\b(?:require|module|exports|global)\b/;
69
- const firstpassNoGlobal = /\b(?:require|module|exports)\b/;
70
- function hasCjsKeywords(code, ignoreGlobal) {
71
- return (ignoreGlobal ? firstpassNoGlobal : firstpassGlobal).test(code);
72
- }
73
- function analyzeTopLevelStatements(parse, code, id) {
74
- const ast = tryParse(parse, code, id);
75
- let isEsModule = false;
76
- let hasDefaultExport = false;
77
- let hasNamedExports = false;
78
- for (const node of ast.body) switch (node.type) {
79
- case "ExportDefaultDeclaration":
80
- isEsModule = true;
81
- hasDefaultExport = true;
82
- break;
83
- case "ExportNamedDeclaration":
84
- isEsModule = true;
85
- if (node.declaration) hasNamedExports = true;
86
- else for (const specifier of node.specifiers) if (specifier.exported.name === "default") hasDefaultExport = true;
87
- else hasNamedExports = true;
88
- break;
89
- case "ExportAllDeclaration":
90
- isEsModule = true;
91
- if (node.exported && node.exported.name === "default") hasDefaultExport = true;
92
- else hasNamedExports = true;
93
- break;
94
- case "ImportDeclaration":
95
- isEsModule = true;
96
- break;
97
- }
98
- return {
99
- isEsModule,
100
- hasDefaultExport,
101
- hasNamedExports,
102
- ast
103
- };
104
- }
105
- function deconflict(scopes, globals, identifier) {
106
- let i = 1;
107
- let deconflicted = makeLegalIdentifier(identifier);
108
- const hasConflicts = () => scopes.some((scope) => scope.contains(deconflicted)) || globals.has(deconflicted);
109
- while (hasConflicts()) {
110
- deconflicted = makeLegalIdentifier(`${identifier}_${i}`);
111
- i += 1;
112
- }
113
- for (const scope of scopes) scope.declarations[deconflicted] = true;
114
- return deconflicted;
115
- }
116
- function getName(id) {
117
- const name = makeLegalIdentifier(basename(id, extname(id)));
118
- if (name !== "index") return name;
119
- return makeLegalIdentifier(basename(dirname(id)));
120
- }
121
- function normalizePathSlashes(path$2) {
122
- return path$2.replace(/\\/g, "/");
123
- }
124
- const getVirtualPathForDynamicRequirePath = (path$2, commonDir) => `/${normalizePathSlashes(relative(commonDir, path$2))}`;
125
- function capitalize(name) {
126
- return name[0].toUpperCase() + name.slice(1);
127
- }
128
- function getStrictRequiresFilter({ strictRequires }) {
129
- switch (strictRequires) {
130
- case void 0:
131
- case true: return {
132
- strictRequiresFilter: () => true,
133
- detectCyclesAndConditional: false
134
- };
135
- case "auto":
136
- case "debug":
137
- case null: return {
138
- strictRequiresFilter: () => false,
139
- detectCyclesAndConditional: true
140
- };
141
- case false: return {
142
- strictRequiresFilter: () => false,
143
- detectCyclesAndConditional: false
144
- };
145
- default:
146
- if (typeof strictRequires === "string" || Array.isArray(strictRequires)) return {
147
- strictRequiresFilter: createFilter(strictRequires),
148
- detectCyclesAndConditional: false
149
- };
150
- throw new Error("Unexpected value for \"strictRequires\" option.");
151
- }
152
- }
153
- function getPackageEntryPoint(dirPath) {
154
- let entryPoint = "index.js";
155
- try {
156
- if (existsSync(join(dirPath, "package.json"))) entryPoint = JSON.parse(readFileSync(join(dirPath, "package.json"), { encoding: "utf8" })).main || entryPoint;
157
- } catch (ignored) {}
158
- return entryPoint;
159
- }
160
- function isDirectory(path$2) {
161
- try {
162
- if (statSync(path$2).isDirectory()) return true;
163
- } catch (ignored) {}
164
- return false;
165
- }
166
- function getDynamicRequireModules(patterns, dynamicRequireRoot) {
167
- const dynamicRequireModules = /* @__PURE__ */ new Map();
168
- const dirNames = /* @__PURE__ */ new Set();
169
- for (const pattern of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) {
170
- const isNegated = pattern.startsWith("!");
171
- const modifyMap = (targetPath, resolvedPath) => isNegated ? dynamicRequireModules.delete(targetPath) : dynamicRequireModules.set(targetPath, resolvedPath);
172
- for (const path$2 of new Builder().withBasePath().withDirs().glob(isNegated ? pattern.substr(1) : pattern).crawl(relative(".", dynamicRequireRoot)).sync().sort((a, b) => a.localeCompare(b, "en"))) {
173
- const resolvedPath = resolve(path$2);
174
- const requirePath = normalizePathSlashes(resolvedPath);
175
- if (isDirectory(resolvedPath)) {
176
- dirNames.add(resolvedPath);
177
- const modulePath = resolve(join(resolvedPath, getPackageEntryPoint(path$2)));
178
- modifyMap(requirePath, modulePath);
179
- modifyMap(normalizePathSlashes(modulePath), modulePath);
180
- } else {
181
- dirNames.add(dirname(resolvedPath));
182
- modifyMap(requirePath, resolvedPath);
183
- }
184
- }
185
- }
186
- return {
187
- commonDir: dirNames.size ? (0, import_commondir.default)([...dirNames, dynamicRequireRoot]) : null,
188
- dynamicRequireModules
189
- };
190
- }
191
- const FAILED_REQUIRE_ERROR = `throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');`;
192
- const COMMONJS_REQUIRE_EXPORT = "commonjsRequire";
193
- const CREATE_COMMONJS_REQUIRE_EXPORT = "createCommonjsRequire";
194
- function getDynamicModuleRegistry(isDynamicRequireModulesEnabled, dynamicRequireModules, commonDir, ignoreDynamicRequires) {
195
- if (!isDynamicRequireModulesEnabled) return `export function ${COMMONJS_REQUIRE_EXPORT}(path) {
196
- ${FAILED_REQUIRE_ERROR}
197
- }`;
198
- return `${[...dynamicRequireModules.values()].map((id, index) => `import ${id.endsWith(".json") ? `json${index}` : `{ __require as require${index} }`} from ${JSON.stringify(id)};`).join("\n")}
199
-
200
- var dynamicModules;
201
-
202
- function getDynamicModules() {
203
- return dynamicModules || (dynamicModules = {
204
- ${[...dynamicRequireModules.keys()].map((id, index) => `\t\t${JSON.stringify(getVirtualPathForDynamicRequirePath(id, commonDir))}: ${id.endsWith(".json") ? `function () { return json${index}; }` : `require${index}`}`).join(",\n")}
205
- });
206
- }
207
-
208
- export function ${CREATE_COMMONJS_REQUIRE_EXPORT}(originalModuleDir) {
209
- function handleRequire(path) {
210
- var resolvedPath = commonjsResolve(path, originalModuleDir);
211
- if (resolvedPath !== null) {
212
- return getDynamicModules()[resolvedPath]();
213
- }
214
- ${ignoreDynamicRequires ? "return require(path);" : FAILED_REQUIRE_ERROR}
215
- }
216
- handleRequire.resolve = function (path) {
217
- var resolvedPath = commonjsResolve(path, originalModuleDir);
218
- if (resolvedPath !== null) {
219
- return resolvedPath;
220
- }
221
- return require.resolve(path);
222
- }
223
- return handleRequire;
224
- }
225
-
226
- function commonjsResolve (path, originalModuleDir) {
227
- var shouldTryNodeModules = isPossibleNodeModulesPath(path);
228
- path = normalize(path);
229
- var relPath;
230
- if (path[0] === '/') {
231
- originalModuleDir = '';
232
- }
233
- var modules = getDynamicModules();
234
- var checkedExtensions = ['', '.js', '.json'];
235
- while (true) {
236
- if (!shouldTryNodeModules) {
237
- relPath = normalize(originalModuleDir + '/' + path);
238
- } else {
239
- relPath = normalize(originalModuleDir + '/node_modules/' + path);
240
- }
241
-
242
- if (relPath.endsWith('/..')) {
243
- break; // Travelled too far up, avoid infinite loop
244
- }
245
-
246
- for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {
247
- var resolvedPath = relPath + checkedExtensions[extensionIndex];
248
- if (modules[resolvedPath]) {
249
- return resolvedPath;
250
- }
251
- }
252
- if (!shouldTryNodeModules) break;
253
- var nextDir = normalize(originalModuleDir + '/..');
254
- if (nextDir === originalModuleDir) break;
255
- originalModuleDir = nextDir;
256
- }
257
- return null;
258
- }
259
-
260
- function isPossibleNodeModulesPath (modulePath) {
261
- var c0 = modulePath[0];
262
- if (c0 === '/' || c0 === '\\\\') return false;
263
- var c1 = modulePath[1], c2 = modulePath[2];
264
- if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||
265
- (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;
266
- if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;
267
- return true;
268
- }
269
-
270
- function normalize (path) {
271
- path = path.replace(/\\\\/g, '/');
272
- var parts = path.split('/');
273
- var slashed = parts[0] === '';
274
- for (var i = 1; i < parts.length; i++) {
275
- if (parts[i] === '.' || parts[i] === '') {
276
- parts.splice(i--, 1);
277
- }
278
- }
279
- for (var i = 1; i < parts.length; i++) {
280
- if (parts[i] !== '..') continue;
281
- if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {
282
- parts.splice(--i, 2);
283
- i--;
284
- }
285
- }
286
- path = parts.join('/');
287
- if (slashed && path[0] !== '/') path = '/' + path;
288
- else if (path.length === 0) path = '.';
289
- return path;
290
- }`;
291
- }
292
- const isWrappedId = (id, suffix) => id.endsWith(suffix);
293
- const wrapId = (id, suffix) => `\0${id}${suffix}`;
294
- const unwrapId = (wrappedId, suffix) => wrappedId.slice(1, -suffix.length);
295
- const PROXY_SUFFIX = "?commonjs-proxy";
296
- const WRAPPED_SUFFIX = "?commonjs-wrapped";
297
- const EXTERNAL_SUFFIX = "?commonjs-external";
298
- const EXPORTS_SUFFIX = "?commonjs-exports";
299
- const MODULE_SUFFIX = "?commonjs-module";
300
- const ENTRY_SUFFIX = "?commonjs-entry";
301
- const ES_IMPORT_SUFFIX = "?commonjs-es-import";
302
- const DYNAMIC_MODULES_ID = "\0commonjs-dynamic-modules";
303
- const HELPERS_ID = "\0commonjsHelpers.js";
304
- const IS_WRAPPED_COMMONJS = "withRequireFunction";
305
- const HELPERS = `
306
- export var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
307
-
308
- export function getDefaultExportFromCjs (x) {
309
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
310
- }
311
-
312
- export function getDefaultExportFromNamespaceIfPresent (n) {
313
- return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n;
314
- }
315
-
316
- export function getDefaultExportFromNamespaceIfNotNamed (n) {
317
- return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n;
318
- }
319
-
320
- export function getAugmentedNamespace(n) {
321
- if (Object.prototype.hasOwnProperty.call(n, '__esModule')) return n;
322
- var f = n.default;
323
- if (typeof f == "function") {
324
- var a = function a () {
325
- var isInstance = false;
326
- try {
327
- isInstance = this instanceof a;
328
- } catch {}
329
- if (isInstance) {
330
- return Reflect.construct(f, arguments, this.constructor);
331
- }
332
- return f.apply(this, arguments);
333
- };
334
- a.prototype = f.prototype;
335
- } else a = {};
336
- Object.defineProperty(a, '__esModule', {value: true});
337
- Object.keys(n).forEach(function (k) {
338
- var d = Object.getOwnPropertyDescriptor(n, k);
339
- Object.defineProperty(a, k, d.get ? d : {
340
- enumerable: true,
341
- get: function () {
342
- return n[k];
343
- }
344
- });
345
- });
346
- return a;
347
- }
348
- `;
349
- function getHelpersModule() {
350
- return HELPERS;
351
- }
352
- function getUnknownRequireProxy(id, requireReturnsDefault) {
353
- if (requireReturnsDefault === true || id.endsWith(".json")) return `export { default } from ${JSON.stringify(id)};`;
354
- const name = getName(id);
355
- const exported = requireReturnsDefault === "auto" ? `import { getDefaultExportFromNamespaceIfNotNamed } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name});` : requireReturnsDefault === "preferred" ? `import { getDefaultExportFromNamespaceIfPresent } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name});` : !requireReturnsDefault ? `import { getAugmentedNamespace } from "${HELPERS_ID}"; export default /*@__PURE__*/getAugmentedNamespace(${name});` : `export default ${name};`;
356
- return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`;
357
- }
358
- async function getStaticRequireProxy(id, requireReturnsDefault, loadModule) {
359
- const name = getName(id);
360
- const { meta: { commonjs: commonjsMeta } } = await loadModule({ id });
361
- if (!commonjsMeta) return getUnknownRequireProxy(id, requireReturnsDefault);
362
- if (commonjsMeta.isCommonJS) return `export { __moduleExports as default } from ${JSON.stringify(id)};`;
363
- if (!requireReturnsDefault) return `import { getAugmentedNamespace } from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify(id)}; export default /*@__PURE__*/getAugmentedNamespace(${name});`;
364
- if (requireReturnsDefault !== true && (requireReturnsDefault === "namespace" || !commonjsMeta.hasDefaultExport || requireReturnsDefault === "auto" && commonjsMeta.hasNamedExports)) return `import * as ${name} from ${JSON.stringify(id)}; export default ${name};`;
365
- return `export { default } from ${JSON.stringify(id)};`;
366
- }
367
- function getEntryProxy(id, defaultIsModuleExports, getModuleInfo, shebang) {
368
- const { meta: { commonjs: commonjsMeta }, hasDefaultExport } = getModuleInfo(id);
369
- if (!commonjsMeta || commonjsMeta.isCommonJS !== IS_WRAPPED_COMMONJS) {
370
- const stringifiedId = JSON.stringify(id);
371
- let code = `export * from ${stringifiedId};`;
372
- if (hasDefaultExport) code += `export { default } from ${stringifiedId};`;
373
- return shebang + code;
374
- }
375
- const result = getEsImportProxy(id, defaultIsModuleExports, true);
376
- return {
377
- ...result,
378
- code: shebang + result.code
379
- };
380
- }
381
- function getEsImportProxy(id, defaultIsModuleExports, moduleSideEffects) {
382
- const name = getName(id);
383
- const exportsName = `${name}Exports`;
384
- const requireModule = `require${capitalize(name)}`;
385
- let code = `import { getDefaultExportFromCjs } from "${HELPERS_ID}";\nimport { __require as ${requireModule} } from ${JSON.stringify(id)};\nvar ${exportsName} = ${moduleSideEffects ? "" : "/*@__PURE__*/ "}${requireModule}();\nexport { ${exportsName} as __moduleExports };`;
386
- if (defaultIsModuleExports === true) code += `\nexport { ${exportsName} as default };`;
387
- else if (defaultIsModuleExports === false) code += `\nexport default ${exportsName}.default;`;
388
- else code += `\nexport default /*@__PURE__*/getDefaultExportFromCjs(${exportsName});`;
389
- return {
390
- code,
391
- syntheticNamedExports: "__moduleExports"
392
- };
393
- }
394
- function getExternalBuiltinRequireProxy(id) {
395
- return `import { createRequire } from 'node:module';
396
- const require = createRequire(import.meta.url);
397
- export function __require() { return require(${JSON.stringify(id)}); }`;
398
- }
399
- function getCandidatesForExtension(resolved, extension) {
400
- return [resolved + extension, `${resolved}${sep}index${extension}`];
401
- }
402
- function getCandidates(resolved, extensions) {
403
- return extensions.reduce((paths, extension) => paths.concat(getCandidatesForExtension(resolved, extension)), [resolved]);
404
- }
405
- function resolveExtensions(importee, importer, extensions) {
406
- if (importee[0] !== "." || !importer) return void 0;
407
- const candidates = getCandidates(resolve(dirname(importer), importee), extensions);
408
- for (let i = 0; i < candidates.length; i += 1) try {
409
- if (statSync(candidates[i]).isFile()) return { id: candidates[i] };
410
- } catch (err) {}
411
- }
412
- function getResolveId(extensions, isPossibleCjsId) {
413
- const currentlyResolving = /* @__PURE__ */ new Map();
414
- return {
415
- currentlyResolving,
416
- async resolveId(importee, importer, resolveOptions) {
417
- if (resolveOptions.custom?.["node-resolve"]?.isRequire) return null;
418
- const currentlyResolvingForParent = currentlyResolving.get(importer);
419
- if (currentlyResolvingForParent && currentlyResolvingForParent.has(importee)) {
420
- this.warn({
421
- code: "THIS_RESOLVE_WITHOUT_OPTIONS",
422
- message: "It appears a plugin has implemented a \"resolveId\" hook that uses \"this.resolve\" without forwarding the third \"options\" parameter of \"resolveId\". This is problematic as it can lead to wrong module resolutions especially for the node-resolve plugin and in certain cases cause early exit errors for the commonjs plugin.\nIn rare cases, this warning can appear if the same file is both imported and required from the same mixed ES/CommonJS module, in which case it can be ignored.",
423
- url: "https://rollupjs.org/guide/en/#resolveid"
424
- });
425
- return null;
426
- }
427
- if (isWrappedId(importee, WRAPPED_SUFFIX)) return unwrapId(importee, WRAPPED_SUFFIX);
428
- if (importee.endsWith(ENTRY_SUFFIX) || isWrappedId(importee, MODULE_SUFFIX) || isWrappedId(importee, EXPORTS_SUFFIX) || isWrappedId(importee, PROXY_SUFFIX) || isWrappedId(importee, ES_IMPORT_SUFFIX) || isWrappedId(importee, EXTERNAL_SUFFIX) || importee.startsWith(HELPERS_ID) || importee === DYNAMIC_MODULES_ID) return importee;
429
- if (importer) {
430
- if (importer === DYNAMIC_MODULES_ID || isWrappedId(importer, PROXY_SUFFIX) || isWrappedId(importer, ES_IMPORT_SUFFIX) || importer.endsWith(ENTRY_SUFFIX)) return importee;
431
- if (isWrappedId(importer, EXTERNAL_SUFFIX)) {
432
- if (!await this.resolve(importee, importer, Object.assign({ skipSelf: true }, resolveOptions))) return null;
433
- return {
434
- id: importee,
435
- external: true
436
- };
437
- }
438
- }
439
- if (importee.startsWith("\0")) return null;
440
- const resolved = await this.resolve(importee, importer, Object.assign({ skipSelf: true }, resolveOptions)) || resolveExtensions(importee, importer, extensions);
441
- if (!resolved || resolved.external || resolved.id.endsWith(ENTRY_SUFFIX) || isWrappedId(resolved.id, ES_IMPORT_SUFFIX) || !isPossibleCjsId(resolved.id)) return resolved;
442
- const moduleInfo = await this.load(resolved);
443
- const { meta: { commonjs: commonjsMeta } } = moduleInfo;
444
- if (commonjsMeta) {
445
- const { isCommonJS } = commonjsMeta;
446
- if (isCommonJS) {
447
- if (resolveOptions.isEntry) {
448
- moduleInfo.moduleSideEffects = true;
449
- return resolved.id + ENTRY_SUFFIX;
450
- }
451
- if (isCommonJS === IS_WRAPPED_COMMONJS) return {
452
- id: wrapId(resolved.id, ES_IMPORT_SUFFIX),
453
- meta: { commonjs: { resolved } }
454
- };
455
- }
456
- }
457
- return resolved;
458
- }
459
- };
460
- }
461
- function getRequireResolver(extensions, detectCyclesAndConditional, currentlyResolving, requireNodeBuiltins) {
462
- const knownCjsModuleTypes = Object.create(null);
463
- const requiredIds = Object.create(null);
464
- const unconditionallyRequiredIds = Object.create(null);
465
- const dependencies = Object.create(null);
466
- const getDependencies = (id) => dependencies[id] || (dependencies[id] = /* @__PURE__ */ new Set());
467
- const isCyclic = (id) => {
468
- const dependenciesToCheck = new Set(getDependencies(id));
469
- for (const dependency of dependenciesToCheck) {
470
- if (dependency === id) return true;
471
- for (const childDependency of getDependencies(dependency)) dependenciesToCheck.add(childDependency);
472
- }
473
- return false;
474
- };
475
- const fullyAnalyzedModules = Object.create(null);
476
- const getTypeForFullyAnalyzedModule = (id) => {
477
- const knownType = knownCjsModuleTypes[id];
478
- if (knownType !== true || !detectCyclesAndConditional || fullyAnalyzedModules[id]) return knownType;
479
- if (isCyclic(id)) return knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS;
480
- return knownType;
481
- };
482
- const setInitialParentType = (id, initialCommonJSType) => {
483
- if (fullyAnalyzedModules[id]) return;
484
- knownCjsModuleTypes[id] = initialCommonJSType;
485
- if (detectCyclesAndConditional && knownCjsModuleTypes[id] === true && requiredIds[id] && !unconditionallyRequiredIds[id]) knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS;
486
- };
487
- const analyzeRequiredModule = async (parentId, resolved, isConditional, loadModule) => {
488
- const childId = resolved.id;
489
- requiredIds[childId] = true;
490
- if (!(isConditional || knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS)) unconditionallyRequiredIds[childId] = true;
491
- getDependencies(parentId).add(childId);
492
- if (!isCyclic(childId)) await loadModule(resolved);
493
- };
494
- const getTypeForImportedModule = async (resolved, loadModule) => {
495
- if (resolved.id in knownCjsModuleTypes) return knownCjsModuleTypes[resolved.id];
496
- const { meta: { commonjs: commonjs$1 } } = await loadModule(resolved);
497
- return commonjs$1 && commonjs$1.isCommonJS || false;
498
- };
499
- return {
500
- getWrappedIds: () => Object.keys(knownCjsModuleTypes).filter((id) => knownCjsModuleTypes[id] === IS_WRAPPED_COMMONJS),
501
- isRequiredId: (id) => requiredIds[id],
502
- async shouldTransformCachedModule({ id: parentId, resolvedSources, meta: { commonjs: parentMeta } }) {
503
- if (!(parentMeta && parentMeta.isCommonJS)) knownCjsModuleTypes[parentId] = false;
504
- if (isWrappedId(parentId, ES_IMPORT_SUFFIX)) return false;
505
- const parentRequires = parentMeta && parentMeta.requires;
506
- if (parentRequires) {
507
- setInitialParentType(parentId, parentMeta.initialCommonJSType);
508
- await Promise.all(parentRequires.map(({ resolved, isConditional }) => analyzeRequiredModule(parentId, resolved, isConditional, this.load)));
509
- if (getTypeForFullyAnalyzedModule(parentId) !== parentMeta.isCommonJS) return true;
510
- for (const { resolved: { id } } of parentRequires) if (getTypeForFullyAnalyzedModule(id) !== parentMeta.isRequiredCommonJS[id]) return true;
511
- fullyAnalyzedModules[parentId] = true;
512
- for (const { resolved: { id } } of parentRequires) fullyAnalyzedModules[id] = true;
513
- }
514
- const parentRequireSet = new Set((parentRequires || []).map(({ resolved: { id } }) => id));
515
- return (await Promise.all(Object.keys(resolvedSources).map((source) => resolvedSources[source]).filter(({ id, external }) => !(external || parentRequireSet.has(id))).map(async (resolved) => {
516
- if (isWrappedId(resolved.id, ES_IMPORT_SUFFIX)) return await getTypeForImportedModule((await this.load(resolved)).meta.commonjs.resolved, this.load) !== IS_WRAPPED_COMMONJS;
517
- return await getTypeForImportedModule(resolved, this.load) === IS_WRAPPED_COMMONJS;
518
- }))).some((shouldTransform) => shouldTransform);
519
- },
520
- resolveRequireSourcesAndUpdateMeta: (rollupContext) => async (parentId, isParentCommonJS, parentMeta, sources) => {
521
- parentMeta.initialCommonJSType = isParentCommonJS;
522
- parentMeta.requires = [];
523
- parentMeta.isRequiredCommonJS = Object.create(null);
524
- setInitialParentType(parentId, isParentCommonJS);
525
- const currentlyResolvingForParent = currentlyResolving.get(parentId) || /* @__PURE__ */ new Set();
526
- currentlyResolving.set(parentId, currentlyResolvingForParent);
527
- const requireTargets = await Promise.all(sources.map(async ({ source, isConditional }) => {
528
- if (source.startsWith("\0")) return {
529
- id: source,
530
- allowProxy: false
531
- };
532
- currentlyResolvingForParent.add(source);
533
- const resolved = await rollupContext.resolve(source, parentId, {
534
- skipSelf: false,
535
- custom: { "node-resolve": { isRequire: true } }
536
- }) || resolveExtensions(source, parentId, extensions);
537
- currentlyResolvingForParent.delete(source);
538
- if (!resolved) return {
539
- id: wrapId(source, EXTERNAL_SUFFIX),
540
- allowProxy: false
541
- };
542
- const childId = resolved.id;
543
- if (resolved.external) return {
544
- id: wrapId(childId, EXTERNAL_SUFFIX),
545
- allowProxy: false
546
- };
547
- parentMeta.requires.push({
548
- resolved,
549
- isConditional
550
- });
551
- await analyzeRequiredModule(parentId, resolved, isConditional, rollupContext.load);
552
- return {
553
- id: childId,
554
- allowProxy: true
555
- };
556
- }));
557
- parentMeta.isCommonJS = getTypeForFullyAnalyzedModule(parentId);
558
- fullyAnalyzedModules[parentId] = true;
559
- return requireTargets.map(({ id: dependencyId, allowProxy }, index) => {
560
- let isCommonJS = parentMeta.isRequiredCommonJS[dependencyId] = getTypeForFullyAnalyzedModule(dependencyId);
561
- const isExternalWrapped = isWrappedId(dependencyId, EXTERNAL_SUFFIX);
562
- let resolvedDependencyId = dependencyId;
563
- if (requireNodeBuiltins === true) {
564
- if (parentMeta.isCommonJS === IS_WRAPPED_COMMONJS && !allowProxy && isExternalWrapped) {
565
- if (unwrapId(dependencyId, EXTERNAL_SUFFIX).startsWith("node:")) {
566
- isCommonJS = IS_WRAPPED_COMMONJS;
567
- parentMeta.isRequiredCommonJS[dependencyId] = isCommonJS;
568
- }
569
- } else if (isExternalWrapped && !allowProxy) {
570
- const actualExternalId = unwrapId(dependencyId, EXTERNAL_SUFFIX);
571
- if (actualExternalId.startsWith("node:")) resolvedDependencyId = actualExternalId;
572
- }
573
- }
574
- const isWrappedCommonJS = isCommonJS === IS_WRAPPED_COMMONJS;
575
- fullyAnalyzedModules[dependencyId] = true;
576
- const moduleInfo = isWrappedCommonJS && !isExternalWrapped ? rollupContext.getModuleInfo(dependencyId) : null;
577
- return {
578
- wrappedModuleSideEffects: !isWrappedCommonJS ? false : moduleInfo?.moduleSideEffects ?? true,
579
- source: sources[index].source,
580
- id: allowProxy ? wrapId(resolvedDependencyId, isWrappedCommonJS ? WRAPPED_SUFFIX : PROXY_SUFFIX) : resolvedDependencyId,
581
- isCommonJS
582
- };
583
- });
584
- },
585
- isCurrentlyResolving(source, parentId) {
586
- const currentlyResolvingForParent = currentlyResolving.get(parentId);
587
- return currentlyResolvingForParent && currentlyResolvingForParent.has(source);
588
- }
589
- };
590
- }
591
- function validateVersion(actualVersion, peerDependencyVersion, name) {
592
- const versionRegexp = /\^(\d+\.\d+\.\d+)/g;
593
- let minMajor = Infinity;
594
- let minMinor = Infinity;
595
- let minPatch = Infinity;
596
- let foundVersion;
597
- while (foundVersion = versionRegexp.exec(peerDependencyVersion)) {
598
- const [foundMajor, foundMinor, foundPatch] = foundVersion[1].split(".").map(Number);
599
- if (foundMajor < minMajor) {
600
- minMajor = foundMajor;
601
- minMinor = foundMinor;
602
- minPatch = foundPatch;
603
- }
604
- }
605
- if (!actualVersion) throw new Error(`Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch}.`);
606
- const [major, minor, patch] = actualVersion.split(".").map(Number);
607
- if (major < minMajor || major === minMajor && (minor < minMinor || minor === minMinor && patch < minPatch)) throw new Error(`Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch} but found ${name}@${actualVersion}.`);
608
- }
609
- const operators = {
610
- "==": (x) => equals(x.left, x.right, false),
611
- "!=": (x) => not(operators["=="](x)),
612
- "===": (x) => equals(x.left, x.right, true),
613
- "!==": (x) => not(operators["==="](x)),
614
- "!": (x) => isFalsy(x.argument),
615
- "&&": (x) => isTruthy(x.left) && isTruthy(x.right),
616
- "||": (x) => isTruthy(x.left) || isTruthy(x.right)
617
- };
618
- function not(value) {
619
- return value === null ? value : !value;
620
- }
621
- function equals(a, b, strict) {
622
- if (a.type !== b.type) return null;
623
- if (a.type === "Literal") return strict ? a.value === b.value : a.value == b.value;
624
- return null;
625
- }
626
- function isTruthy(node) {
627
- if (!node) return false;
628
- if (node.type === "Literal") return !!node.value;
629
- if (node.type === "ParenthesizedExpression") return isTruthy(node.expression);
630
- if (node.operator in operators) return operators[node.operator](node);
631
- return null;
632
- }
633
- function isFalsy(node) {
634
- return not(isTruthy(node));
635
- }
636
- function getKeypath(node) {
637
- const parts = [];
638
- while (node.type === "MemberExpression") {
639
- if (node.computed) return null;
640
- parts.unshift(node.property.name);
641
- node = node.object;
642
- }
643
- if (node.type !== "Identifier") return null;
644
- const { name } = node;
645
- parts.unshift(name);
646
- return {
647
- name,
648
- keypath: parts.join(".")
649
- };
650
- }
651
- const KEY_COMPILED_ESM = "__esModule";
652
- function getDefineCompiledEsmType(node) {
653
- const definedPropertyWithExports = getDefinePropertyCallName(node, "exports");
654
- const definedProperty = definedPropertyWithExports || getDefinePropertyCallName(node, "module.exports");
655
- if (definedProperty && definedProperty.key === KEY_COMPILED_ESM) return isTruthy(definedProperty.value) ? definedPropertyWithExports ? "exports" : "module" : false;
656
- return false;
657
- }
658
- function getDefinePropertyCallName(node, targetName) {
659
- const { callee: { object, property } } = node;
660
- if (!object || object.type !== "Identifier" || object.name !== "Object") return;
661
- if (!property || property.type !== "Identifier" || property.name !== "defineProperty") return;
662
- if (node.arguments.length !== 3) return;
663
- const targetNames = targetName.split(".");
664
- const [target, key, value] = node.arguments;
665
- if (targetNames.length === 1) {
666
- if (target.type !== "Identifier" || target.name !== targetNames[0]) return;
667
- }
668
- if (targetNames.length === 2) {
669
- if (target.type !== "MemberExpression" || target.object.name !== targetNames[0] || target.property.name !== targetNames[1]) return;
670
- }
671
- if (value.type !== "ObjectExpression" || !value.properties) return;
672
- const valueProperty = value.properties.find((p) => p.key && p.key.name === "value");
673
- if (!valueProperty || !valueProperty.value) return;
674
- return {
675
- key: key.value,
676
- value: valueProperty.value
677
- };
678
- }
679
- function isShorthandProperty(parent) {
680
- return parent && parent.type === "Property" && parent.shorthand;
681
- }
682
- function wrapCode(magicString, uses, moduleName, exportsName, indentExclusionRanges) {
683
- const args = [];
684
- const passedArgs = [];
685
- if (uses.module) {
686
- args.push("module");
687
- passedArgs.push(moduleName);
688
- }
689
- if (uses.exports) {
690
- args.push("exports");
691
- passedArgs.push(uses.module ? `${moduleName}.exports` : exportsName);
692
- }
693
- magicString.trim().indent(" ", { exclude: indentExclusionRanges }).prepend(`(function (${args.join(", ")}) {\n`).append(` \n} (${passedArgs.join(", ")}));`);
694
- }
695
- function rewriteExportsAndGetExportsBlock(magicString, moduleName, exportsName, exportedExportsName, wrapped, moduleExportsAssignments, firstTopLevelModuleExportsAssignment, exportsAssignmentsByName, topLevelAssignments, defineCompiledEsmExpressions, deconflictedExportNames, code, HELPERS_NAME, exportMode, defaultIsModuleExports, usesRequireWrapper, requireName) {
696
- const exports$1 = [];
697
- const exportDeclarations = [];
698
- if (usesRequireWrapper) getExportsWhenUsingRequireWrapper(magicString, wrapped, exportMode, exports$1, moduleExportsAssignments, exportsAssignmentsByName, moduleName, exportsName, requireName, defineCompiledEsmExpressions);
699
- else if (exportMode === "replace") getExportsForReplacedModuleExports(magicString, exports$1, exportDeclarations, moduleExportsAssignments, firstTopLevelModuleExportsAssignment, exportsName, defaultIsModuleExports, HELPERS_NAME);
700
- else {
701
- if (exportMode === "module") {
702
- exportDeclarations.push(`var ${exportedExportsName} = ${moduleName}.exports`);
703
- exports$1.push(`${exportedExportsName} as __moduleExports`);
704
- } else exports$1.push(`${exportsName} as __moduleExports`);
705
- if (wrapped) exportDeclarations.push(getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME));
706
- else getExports(magicString, exports$1, exportDeclarations, moduleExportsAssignments, exportsAssignmentsByName, deconflictedExportNames, topLevelAssignments, moduleName, exportsName, exportedExportsName, defineCompiledEsmExpressions, HELPERS_NAME, defaultIsModuleExports, exportMode);
707
- }
708
- if (exports$1.length) exportDeclarations.push(`export { ${exports$1.join(", ")} }`);
709
- return `\n\n${exportDeclarations.join(";\n")};`;
710
- }
711
- function getExportsWhenUsingRequireWrapper(magicString, wrapped, exportMode, exports$1, moduleExportsAssignments, exportsAssignmentsByName, moduleName, exportsName, requireName, defineCompiledEsmExpressions) {
712
- exports$1.push(`${requireName} as __require`);
713
- if (wrapped) return;
714
- if (exportMode === "replace") rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, exportsName);
715
- else {
716
- rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, `${moduleName}.exports`);
717
- for (const [exportName, { nodes }] of exportsAssignmentsByName) for (const { node, type } of nodes) magicString.overwrite(node.start, node.left.end, `${exportMode === "module" && type === "module" ? `${moduleName}.exports` : exportsName}.${exportName}`);
718
- replaceDefineCompiledEsmExpressionsAndGetIfRestorable(defineCompiledEsmExpressions, magicString, exportMode, moduleName, exportsName);
719
- }
720
- }
721
- function getExportsForReplacedModuleExports(magicString, exports$1, exportDeclarations, moduleExportsAssignments, firstTopLevelModuleExportsAssignment, exportsName, defaultIsModuleExports, HELPERS_NAME) {
722
- for (const { left } of moduleExportsAssignments) magicString.overwrite(left.start, left.end, exportsName);
723
- magicString.prependRight(firstTopLevelModuleExportsAssignment.left.start, "var ");
724
- exports$1.push(`${exportsName} as __moduleExports`);
725
- exportDeclarations.push(getDefaultExportDeclaration(exportsName, defaultIsModuleExports, HELPERS_NAME));
726
- }
727
- function getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME) {
728
- return `export default ${defaultIsModuleExports === true ? exportedExportsName : defaultIsModuleExports === false ? `${exportedExportsName}.default` : `/*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportedExportsName})`}`;
729
- }
730
- function getExports(magicString, exports$1, exportDeclarations, moduleExportsAssignments, exportsAssignmentsByName, deconflictedExportNames, topLevelAssignments, moduleName, exportsName, exportedExportsName, defineCompiledEsmExpressions, HELPERS_NAME, defaultIsModuleExports, exportMode) {
731
- let deconflictedDefaultExportName;
732
- for (const { left } of moduleExportsAssignments) magicString.overwrite(left.start, left.end, `${moduleName}.exports`);
733
- for (const [exportName, { nodes }] of exportsAssignmentsByName) {
734
- const deconflicted = deconflictedExportNames[exportName];
735
- let needsDeclaration = true;
736
- for (const { node, type } of nodes) {
737
- let replacement = `${deconflicted} = ${exportMode === "module" && type === "module" ? `${moduleName}.exports` : exportsName}.${exportName}`;
738
- if (needsDeclaration && topLevelAssignments.has(node)) {
739
- replacement = `var ${replacement}`;
740
- needsDeclaration = false;
741
- }
742
- magicString.overwrite(node.start, node.left.end, replacement);
743
- }
744
- if (needsDeclaration) magicString.prepend(`var ${deconflicted};\n`);
745
- if (exportName === "default") deconflictedDefaultExportName = deconflicted;
746
- else exports$1.push(exportName === deconflicted ? exportName : `${deconflicted} as ${exportName}`);
747
- }
748
- const isRestorableCompiledEsm = replaceDefineCompiledEsmExpressionsAndGetIfRestorable(defineCompiledEsmExpressions, magicString, exportMode, moduleName, exportsName);
749
- if (defaultIsModuleExports === false || defaultIsModuleExports === "auto" && isRestorableCompiledEsm && moduleExportsAssignments.length === 0) exports$1.push(`${deconflictedDefaultExportName || exportedExportsName} as default`);
750
- else if (defaultIsModuleExports === true || !isRestorableCompiledEsm && moduleExportsAssignments.length === 0) exports$1.push(`${exportedExportsName} as default`);
751
- else exportDeclarations.push(getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME));
752
- }
753
- function rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, exportsName) {
754
- for (const { left } of moduleExportsAssignments) magicString.overwrite(left.start, left.end, exportsName);
755
- }
756
- function replaceDefineCompiledEsmExpressionsAndGetIfRestorable(defineCompiledEsmExpressions, magicString, exportMode, moduleName, exportsName) {
757
- let isRestorableCompiledEsm = false;
758
- for (const { node, type } of defineCompiledEsmExpressions) {
759
- isRestorableCompiledEsm = true;
760
- const moduleExportsExpression = node.type === "CallExpression" ? node.arguments[0] : node.left.object;
761
- magicString.overwrite(moduleExportsExpression.start, moduleExportsExpression.end, exportMode === "module" && type === "module" ? `${moduleName}.exports` : exportsName);
762
- }
763
- return isRestorableCompiledEsm;
764
- }
765
- function isRequireExpression(node, scope) {
766
- if (!node) return false;
767
- if (node.type !== "CallExpression") return false;
768
- if (node.arguments.length === 0) return false;
769
- return isRequire(node.callee, scope);
770
- }
771
- function isRequire(node, scope) {
772
- return node.type === "Identifier" && node.name === "require" && !scope.contains("require") || node.type === "MemberExpression" && isModuleRequire(node, scope);
773
- }
774
- function isModuleRequire({ object, property }, scope) {
775
- return object.type === "Identifier" && object.name === "module" && property.type === "Identifier" && property.name === "require" && !scope.contains("module");
776
- }
777
- function hasDynamicArguments(node) {
778
- return node.arguments.length > 1 || node.arguments[0].type !== "Literal" && (node.arguments[0].type !== "TemplateLiteral" || node.arguments[0].expressions.length > 0);
779
- }
780
- const reservedMethod = {
781
- resolve: true,
782
- cache: true,
783
- main: true
784
- };
785
- function isNodeRequirePropertyAccess(parent) {
786
- return parent && parent.property && reservedMethod[parent.property.name];
787
- }
788
- function getRequireStringArg(node) {
789
- return node.arguments[0].type === "Literal" ? node.arguments[0].value : node.arguments[0].quasis[0].value.cooked;
790
- }
791
- function getRequireHandlers() {
792
- const requireExpressions = [];
793
- function addRequireExpression(sourceId, node, scope, usesReturnValue, isInsideTryBlock, isInsideConditional, toBeRemoved) {
794
- requireExpressions.push({
795
- sourceId,
796
- node,
797
- scope,
798
- usesReturnValue,
799
- isInsideTryBlock,
800
- isInsideConditional,
801
- toBeRemoved
802
- });
803
- }
804
- async function rewriteRequireExpressionsAndGetImportBlock(magicString, topLevelDeclarations, reassignedNames, helpersName, dynamicRequireName, moduleName, exportsName, id, exportMode, resolveRequireSourcesAndUpdateMeta, needsRequireWrapper, isEsModule, isDynamicRequireModulesEnabled, getIgnoreTryCatchRequireStatementMode, commonjsMeta) {
805
- const imports = [];
806
- imports.push(`import * as ${helpersName} from "${HELPERS_ID}"`);
807
- if (dynamicRequireName) imports.push(`import { ${isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT} as ${dynamicRequireName} } from "${DYNAMIC_MODULES_ID}"`);
808
- if (exportMode === "module") imports.push(`import { __module as ${moduleName} } from ${JSON.stringify(wrapId(id, MODULE_SUFFIX))}`, `var ${exportsName} = ${moduleName}.exports`);
809
- else if (exportMode === "exports") imports.push(`import { __exports as ${exportsName} } from ${JSON.stringify(wrapId(id, EXPORTS_SUFFIX))}`);
810
- const requiresBySource = collectSources(requireExpressions);
811
- processRequireExpressions(imports, await resolveRequireSourcesAndUpdateMeta(id, needsRequireWrapper ? IS_WRAPPED_COMMONJS : !isEsModule, commonjsMeta, Object.keys(requiresBySource).map((source) => {
812
- return {
813
- source,
814
- isConditional: requiresBySource[source].every((require$1) => require$1.isInsideConditional)
815
- };
816
- })), requiresBySource, getIgnoreTryCatchRequireStatementMode, magicString);
817
- return imports.length ? `${imports.join(";\n")};\n\n` : "";
818
- }
819
- return {
820
- addRequireExpression,
821
- rewriteRequireExpressionsAndGetImportBlock
822
- };
823
- }
824
- function collectSources(requireExpressions) {
825
- const requiresBySource = Object.create(null);
826
- for (const requireExpression of requireExpressions) {
827
- const { sourceId } = requireExpression;
828
- if (!requiresBySource[sourceId]) requiresBySource[sourceId] = [];
829
- requiresBySource[sourceId].push(requireExpression);
830
- }
831
- return requiresBySource;
832
- }
833
- function processRequireExpressions(imports, requireTargets, requiresBySource, getIgnoreTryCatchRequireStatementMode, magicString) {
834
- const generateRequireName = getGenerateRequireName();
835
- for (const { source, id: resolvedId, isCommonJS, wrappedModuleSideEffects } of requireTargets) {
836
- const requires = requiresBySource[source];
837
- const name = generateRequireName(requires);
838
- let usesRequired = false;
839
- let needsImport = false;
840
- for (const { node, usesReturnValue, toBeRemoved, isInsideTryBlock } of requires) {
841
- const { canConvertRequire, shouldRemoveRequire } = isInsideTryBlock && isWrappedId(resolvedId, EXTERNAL_SUFFIX) ? getIgnoreTryCatchRequireStatementMode(source) : {
842
- canConvertRequire: true,
843
- shouldRemoveRequire: false
844
- };
845
- if (shouldRemoveRequire) if (usesReturnValue) magicString.overwrite(node.start, node.end, "undefined");
846
- else magicString.remove(toBeRemoved.start, toBeRemoved.end);
847
- else if (canConvertRequire) {
848
- needsImport = true;
849
- if (isCommonJS === IS_WRAPPED_COMMONJS) magicString.overwrite(node.start, node.end, `${wrappedModuleSideEffects ? "" : "/*@__PURE__*/ "}${name}()`);
850
- else if (usesReturnValue) {
851
- usesRequired = true;
852
- magicString.overwrite(node.start, node.end, name);
853
- } else magicString.remove(toBeRemoved.start, toBeRemoved.end);
854
- }
855
- }
856
- if (needsImport) if (isCommonJS === IS_WRAPPED_COMMONJS) imports.push(`import { __require as ${name} } from ${JSON.stringify(resolvedId)}`);
857
- else imports.push(`import ${usesRequired ? `${name} from ` : ""}${JSON.stringify(resolvedId)}`);
858
- }
859
- }
860
- function getGenerateRequireName() {
861
- let uid = 0;
862
- return (requires) => {
863
- let name;
864
- const hasNameConflict = ({ scope }) => scope.contains(name);
865
- do {
866
- name = `require$$${uid}`;
867
- uid += 1;
868
- } while (requires.some(hasNameConflict));
869
- return name;
870
- };
871
- }
872
- const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/;
873
- const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/;
874
- async function transformCommonjs(parse, code, id, isEsModule, ignoreGlobal, ignoreRequire, ignoreDynamicRequires, getIgnoreTryCatchRequireStatementMode, sourceMap, isDynamicRequireModulesEnabled, dynamicRequireModules, commonDir, astCache, defaultIsModuleExports, needsRequireWrapper, resolveRequireSourcesAndUpdateMeta, isRequired, checkDynamicRequire, commonjsMeta) {
875
- const ast = astCache || tryParse(parse, code, id);
876
- const magicString = new MagicString(code);
877
- const uses = {
878
- module: false,
879
- exports: false,
880
- global: false,
881
- require: false
882
- };
883
- const virtualDynamicRequirePath = isDynamicRequireModulesEnabled && getVirtualPathForDynamicRequirePath(dirname(id), commonDir);
884
- let scope = attachScopes(ast, "scope");
885
- let lexicalDepth = 0;
886
- let programDepth = 0;
887
- let classBodyDepth = 0;
888
- let currentTryBlockEnd = null;
889
- let shouldWrap = false;
890
- const globals = /* @__PURE__ */ new Set();
891
- let currentConditionalNodeEnd = null;
892
- const conditionalNodes = /* @__PURE__ */ new Set();
893
- const { addRequireExpression, rewriteRequireExpressionsAndGetImportBlock } = getRequireHandlers();
894
- const reassignedNames = /* @__PURE__ */ new Set();
895
- const topLevelDeclarations = [];
896
- const skippedNodes = /* @__PURE__ */ new Set();
897
- const moduleAccessScopes = new Set([scope]);
898
- const exportsAccessScopes = new Set([scope]);
899
- const moduleExportsAssignments = [];
900
- let firstTopLevelModuleExportsAssignment = null;
901
- const exportsAssignmentsByName = /* @__PURE__ */ new Map();
902
- const topLevelAssignments = /* @__PURE__ */ new Set();
903
- const topLevelDefineCompiledEsmExpressions = [];
904
- const replacedGlobal = [];
905
- const replacedThis = [];
906
- const replacedDynamicRequires = [];
907
- const importedVariables = /* @__PURE__ */ new Set();
908
- const indentExclusionRanges = [];
909
- walk(ast, {
910
- enter(node, parent) {
911
- if (skippedNodes.has(node)) {
912
- this.skip();
913
- return;
914
- }
915
- if (currentTryBlockEnd !== null && node.start > currentTryBlockEnd) currentTryBlockEnd = null;
916
- if (currentConditionalNodeEnd !== null && node.start > currentConditionalNodeEnd) currentConditionalNodeEnd = null;
917
- if (currentConditionalNodeEnd === null && conditionalNodes.has(node)) currentConditionalNodeEnd = node.end;
918
- programDepth += 1;
919
- if (node.scope) ({scope} = node);
920
- if (functionType.test(node.type)) lexicalDepth += 1;
921
- if (sourceMap) {
922
- magicString.addSourcemapLocation(node.start);
923
- magicString.addSourcemapLocation(node.end);
924
- }
925
- switch (node.type) {
926
- case "AssignmentExpression":
927
- if (node.left.type === "MemberExpression") {
928
- const flattened = getKeypath(node.left);
929
- if (!flattened || scope.contains(flattened.name)) return;
930
- const exportsPatternMatch = exportsPattern.exec(flattened.keypath);
931
- if (!exportsPatternMatch || flattened.keypath === "exports") return;
932
- const [, exportName] = exportsPatternMatch;
933
- uses[flattened.name] = true;
934
- if (flattened.keypath === "module.exports") {
935
- moduleExportsAssignments.push(node);
936
- if (programDepth > 3) moduleAccessScopes.add(scope);
937
- else if (!firstTopLevelModuleExportsAssignment) firstTopLevelModuleExportsAssignment = node;
938
- } else if (exportName === KEY_COMPILED_ESM) if (programDepth > 3) shouldWrap = true;
939
- else topLevelDefineCompiledEsmExpressions.push({
940
- node,
941
- type: flattened.name
942
- });
943
- else {
944
- const exportsAssignments = exportsAssignmentsByName.get(exportName) || {
945
- nodes: [],
946
- scopes: /* @__PURE__ */ new Set()
947
- };
948
- exportsAssignments.nodes.push({
949
- node,
950
- type: flattened.name
951
- });
952
- exportsAssignments.scopes.add(scope);
953
- exportsAccessScopes.add(scope);
954
- exportsAssignmentsByName.set(exportName, exportsAssignments);
955
- if (programDepth <= 3) topLevelAssignments.add(node);
956
- }
957
- skippedNodes.add(node.left);
958
- } else for (const name of extractAssignedNames(node.left)) reassignedNames.add(name);
959
- return;
960
- case "CallExpression": {
961
- const defineCompiledEsmType = getDefineCompiledEsmType(node);
962
- if (defineCompiledEsmType) {
963
- if (programDepth === 3 && parent.type === "ExpressionStatement") {
964
- skippedNodes.add(node.arguments[0]);
965
- topLevelDefineCompiledEsmExpressions.push({
966
- node,
967
- type: defineCompiledEsmType
968
- });
969
- } else shouldWrap = true;
970
- return;
971
- }
972
- if (isDynamicRequireModulesEnabled && node.callee.object && isRequire(node.callee.object, scope) && node.callee.property.name === "resolve") {
973
- checkDynamicRequire(node.start);
974
- uses.require = true;
975
- const requireNode = node.callee.object;
976
- replacedDynamicRequires.push(requireNode);
977
- skippedNodes.add(node.callee);
978
- return;
979
- }
980
- if (!isRequireExpression(node, scope)) {
981
- const keypath = getKeypath(node.callee);
982
- if (keypath && importedVariables.has(keypath.name)) currentConditionalNodeEnd = Infinity;
983
- return;
984
- }
985
- skippedNodes.add(node.callee);
986
- uses.require = true;
987
- if (hasDynamicArguments(node)) {
988
- if (isDynamicRequireModulesEnabled) checkDynamicRequire(node.start);
989
- if (!ignoreDynamicRequires) replacedDynamicRequires.push(node.callee);
990
- return;
991
- }
992
- const requireStringArg = getRequireStringArg(node);
993
- if (!ignoreRequire(requireStringArg)) {
994
- const usesReturnValue = parent.type !== "ExpressionStatement";
995
- const toBeRemoved = parent.type === "ExpressionStatement" && (!currentConditionalNodeEnd || currentTryBlockEnd !== null && currentTryBlockEnd < currentConditionalNodeEnd) ? parent : node;
996
- addRequireExpression(requireStringArg, node, scope, usesReturnValue, currentTryBlockEnd !== null, currentConditionalNodeEnd !== null, toBeRemoved);
997
- if (parent.type === "VariableDeclarator" && parent.id.type === "Identifier") for (const name of extractAssignedNames(parent.id)) importedVariables.add(name);
998
- }
999
- return;
1000
- }
1001
- case "ClassBody":
1002
- classBodyDepth += 1;
1003
- return;
1004
- case "ConditionalExpression":
1005
- case "IfStatement":
1006
- if (isFalsy(node.test)) skippedNodes.add(node.consequent);
1007
- else if (isTruthy(node.test)) {
1008
- if (node.alternate) skippedNodes.add(node.alternate);
1009
- } else {
1010
- conditionalNodes.add(node.consequent);
1011
- if (node.alternate) conditionalNodes.add(node.alternate);
1012
- }
1013
- return;
1014
- case "ArrowFunctionExpression":
1015
- case "FunctionDeclaration":
1016
- case "FunctionExpression":
1017
- if (currentConditionalNodeEnd === null && !(parent.type === "CallExpression" && parent.callee === node)) currentConditionalNodeEnd = node.end;
1018
- return;
1019
- case "Identifier": {
1020
- const { name } = node;
1021
- if (!(0, import_is_reference.default)(node, parent) || scope.contains(name) || parent.type === "PropertyDefinition" && parent.key === node) return;
1022
- switch (name) {
1023
- case "require":
1024
- uses.require = true;
1025
- if (isNodeRequirePropertyAccess(parent)) return;
1026
- if (!ignoreDynamicRequires) {
1027
- if (isShorthandProperty(parent)) {
1028
- skippedNodes.add(parent.value);
1029
- magicString.prependRight(node.start, "require: ");
1030
- }
1031
- replacedDynamicRequires.push(node);
1032
- }
1033
- return;
1034
- case "module":
1035
- case "exports":
1036
- shouldWrap = true;
1037
- uses[name] = true;
1038
- return;
1039
- case "global":
1040
- uses.global = true;
1041
- if (!ignoreGlobal) replacedGlobal.push(node);
1042
- return;
1043
- case "define":
1044
- magicString.overwrite(node.start, node.end, "undefined", { storeName: true });
1045
- return;
1046
- default:
1047
- globals.add(name);
1048
- return;
1049
- }
1050
- }
1051
- case "LogicalExpression":
1052
- if (node.operator === "&&") {
1053
- if (isFalsy(node.left)) skippedNodes.add(node.right);
1054
- else if (!isTruthy(node.left)) conditionalNodes.add(node.right);
1055
- } else if (node.operator === "||") {
1056
- if (isTruthy(node.left)) skippedNodes.add(node.right);
1057
- else if (!isFalsy(node.left)) conditionalNodes.add(node.right);
1058
- }
1059
- return;
1060
- case "MemberExpression":
1061
- if (!isDynamicRequireModulesEnabled && isModuleRequire(node, scope)) {
1062
- uses.require = true;
1063
- replacedDynamicRequires.push(node);
1064
- skippedNodes.add(node.object);
1065
- skippedNodes.add(node.property);
1066
- }
1067
- return;
1068
- case "ReturnStatement":
1069
- if (lexicalDepth === 0) shouldWrap = true;
1070
- return;
1071
- case "ThisExpression":
1072
- if (lexicalDepth === 0 && !classBodyDepth) {
1073
- uses.global = true;
1074
- if (!ignoreGlobal) replacedThis.push(node);
1075
- }
1076
- return;
1077
- case "TryStatement":
1078
- if (currentTryBlockEnd === null) currentTryBlockEnd = node.block.end;
1079
- if (currentConditionalNodeEnd === null) currentConditionalNodeEnd = node.end;
1080
- return;
1081
- case "UnaryExpression":
1082
- if (node.operator === "typeof") {
1083
- const flattened = getKeypath(node.argument);
1084
- if (!flattened) return;
1085
- if (scope.contains(flattened.name)) return;
1086
- if (!isEsModule && (flattened.keypath === "module.exports" || flattened.keypath === "module" || flattened.keypath === "exports")) magicString.overwrite(node.start, node.end, `'object'`, { storeName: false });
1087
- }
1088
- return;
1089
- case "VariableDeclaration":
1090
- if (!scope.parent) topLevelDeclarations.push(node);
1091
- return;
1092
- case "TemplateElement": if (node.value.raw.includes("\n")) indentExclusionRanges.push([node.start, node.end]);
1093
- }
1094
- },
1095
- leave(node) {
1096
- programDepth -= 1;
1097
- if (node.scope) scope = scope.parent;
1098
- if (functionType.test(node.type)) lexicalDepth -= 1;
1099
- if (node.type === "ClassBody") classBodyDepth -= 1;
1100
- }
1101
- });
1102
- const nameBase = getName(id);
1103
- const exportsName = deconflict([...exportsAccessScopes], globals, nameBase);
1104
- const moduleName = deconflict([...moduleAccessScopes], globals, `${nameBase}Module`);
1105
- const requireName = deconflict([scope], globals, `require${capitalize(nameBase)}`);
1106
- const isRequiredName = deconflict([scope], globals, `hasRequired${capitalize(nameBase)}`);
1107
- const helpersName = deconflict([scope], globals, "commonjsHelpers");
1108
- const dynamicRequireName = replacedDynamicRequires.length > 0 && deconflict([scope], globals, isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT);
1109
- const deconflictedExportNames = Object.create(null);
1110
- for (const [exportName, { scopes }] of exportsAssignmentsByName) deconflictedExportNames[exportName] = deconflict([...scopes], globals, exportName);
1111
- for (const node of replacedGlobal) magicString.overwrite(node.start, node.end, `${helpersName}.commonjsGlobal`, { storeName: true });
1112
- for (const node of replacedThis) magicString.overwrite(node.start, node.end, exportsName, { storeName: true });
1113
- for (const node of replacedDynamicRequires) magicString.overwrite(node.start, node.end, isDynamicRequireModulesEnabled ? `${dynamicRequireName}(${JSON.stringify(virtualDynamicRequirePath)})` : dynamicRequireName, {
1114
- contentOnly: true,
1115
- storeName: true
1116
- });
1117
- shouldWrap = !isEsModule && (shouldWrap || uses.exports && moduleExportsAssignments.length > 0);
1118
- if (!(shouldWrap || isRequired || needsRequireWrapper || uses.module || uses.exports || uses.require || topLevelDefineCompiledEsmExpressions.length > 0) && (ignoreGlobal || !uses.global)) return { meta: { commonjs: { isCommonJS: false } } };
1119
- let leadingComment = "";
1120
- if (code.startsWith("/*")) {
1121
- const commentEnd = code.indexOf("*/", 2) + 2;
1122
- leadingComment = `${code.slice(0, commentEnd)}\n`;
1123
- magicString.remove(0, commentEnd).trim();
1124
- }
1125
- let shebang = "";
1126
- if (code.startsWith("#!")) {
1127
- const shebangEndPosition = code.indexOf("\n") + 1;
1128
- shebang = code.slice(0, shebangEndPosition);
1129
- magicString.remove(0, shebangEndPosition).trim();
1130
- }
1131
- const exportMode = isEsModule ? "none" : shouldWrap ? uses.module ? "module" : "exports" : firstTopLevelModuleExportsAssignment ? exportsAssignmentsByName.size === 0 && topLevelDefineCompiledEsmExpressions.length === 0 ? "replace" : "module" : moduleExportsAssignments.length === 0 ? "exports" : "module";
1132
- const exportedExportsName = exportMode === "module" ? deconflict([], globals, `${nameBase}Exports`) : exportsName;
1133
- const importBlock = await rewriteRequireExpressionsAndGetImportBlock(magicString, topLevelDeclarations, reassignedNames, helpersName, dynamicRequireName, moduleName, exportsName, id, exportMode, resolveRequireSourcesAndUpdateMeta, needsRequireWrapper, isEsModule, isDynamicRequireModulesEnabled, getIgnoreTryCatchRequireStatementMode, commonjsMeta);
1134
- const usesRequireWrapper = commonjsMeta.isCommonJS === IS_WRAPPED_COMMONJS;
1135
- const exportBlock = isEsModule ? "" : rewriteExportsAndGetExportsBlock(magicString, moduleName, exportsName, exportedExportsName, shouldWrap, moduleExportsAssignments, firstTopLevelModuleExportsAssignment, exportsAssignmentsByName, topLevelAssignments, topLevelDefineCompiledEsmExpressions, deconflictedExportNames, code, helpersName, exportMode, defaultIsModuleExports, usesRequireWrapper, requireName);
1136
- if (shouldWrap) wrapCode(magicString, uses, moduleName, exportsName, indentExclusionRanges);
1137
- if (usesRequireWrapper) {
1138
- magicString.trim().indent(" ", { exclude: indentExclusionRanges });
1139
- const exported = exportMode === "module" ? `${moduleName}.exports` : exportsName;
1140
- magicString.prepend(`var ${isRequiredName};
1141
-
1142
- function ${requireName} () {
1143
- \tif (${isRequiredName}) return ${exported};
1144
- \t${isRequiredName} = 1;
1145
- `).append(`
1146
- \treturn ${exported};
1147
- }`);
1148
- if (exportMode === "replace") magicString.prepend(`var ${exportsName};\n`);
1149
- }
1150
- magicString.trim().prepend(shebang + leadingComment + importBlock).append(exportBlock);
1151
- return {
1152
- code: magicString.toString(),
1153
- map: sourceMap ? magicString.generateMap() : null,
1154
- syntheticNamedExports: isEsModule || usesRequireWrapper ? false : "__moduleExports",
1155
- meta: { commonjs: {
1156
- ...commonjsMeta,
1157
- shebang
1158
- } }
1159
- };
1160
- }
1161
- const PLUGIN_NAME = "commonjs";
1162
- function commonjs(options = {}) {
1163
- const { ignoreGlobal, ignoreDynamicRequires, requireReturnsDefault: requireReturnsDefaultOption, defaultIsModuleExports: defaultIsModuleExportsOption, esmExternals, requireNodeBuiltins = false } = options;
1164
- const extensions = options.extensions || [".js"];
1165
- const filter = createFilter(options.include, options.exclude);
1166
- const isPossibleCjsId = (id) => {
1167
- const extName = extname(id);
1168
- return extName === ".cjs" || extensions.includes(extName) && filter(id);
1169
- };
1170
- const { strictRequiresFilter, detectCyclesAndConditional } = getStrictRequiresFilter(options);
1171
- const getRequireReturnsDefault = typeof requireReturnsDefaultOption === "function" ? requireReturnsDefaultOption : () => requireReturnsDefaultOption;
1172
- let esmExternalIds;
1173
- const isEsmExternal = typeof esmExternals === "function" ? esmExternals : Array.isArray(esmExternals) ? (esmExternalIds = new Set(esmExternals), (id) => esmExternalIds.has(id)) : () => esmExternals;
1174
- const getDefaultIsModuleExports = typeof defaultIsModuleExportsOption === "function" ? defaultIsModuleExportsOption : () => typeof defaultIsModuleExportsOption === "boolean" ? defaultIsModuleExportsOption : "auto";
1175
- const dynamicRequireRoot = typeof options.dynamicRequireRoot === "string" ? resolve(options.dynamicRequireRoot) : process.cwd();
1176
- const { commonDir, dynamicRequireModules } = getDynamicRequireModules(options.dynamicRequireTargets, dynamicRequireRoot);
1177
- const isDynamicRequireModulesEnabled = dynamicRequireModules.size > 0;
1178
- const ignoreRequire = typeof options.ignore === "function" ? options.ignore : Array.isArray(options.ignore) ? (id) => options.ignore.includes(id) : () => false;
1179
- const getIgnoreTryCatchRequireStatementMode = (id) => {
1180
- const mode = typeof options.ignoreTryCatch === "function" ? options.ignoreTryCatch(id) : Array.isArray(options.ignoreTryCatch) ? options.ignoreTryCatch.includes(id) : typeof options.ignoreTryCatch !== "undefined" ? options.ignoreTryCatch : true;
1181
- return {
1182
- canConvertRequire: mode !== "remove" && mode !== true,
1183
- shouldRemoveRequire: mode === "remove"
1184
- };
1185
- };
1186
- const { currentlyResolving, resolveId } = getResolveId(extensions, isPossibleCjsId);
1187
- const sourceMap = options.sourceMap !== false;
1188
- let requireResolver;
1189
- function transformAndCheckExports(code, id) {
1190
- const normalizedId = normalizePathSlashes(id);
1191
- const { isEsModule, hasDefaultExport, hasNamedExports, ast } = analyzeTopLevelStatements(this.parse, code, id);
1192
- const commonjsMeta = this.getModuleInfo(id).meta.commonjs || {};
1193
- if (hasDefaultExport) commonjsMeta.hasDefaultExport = true;
1194
- if (hasNamedExports) commonjsMeta.hasNamedExports = true;
1195
- if (!dynamicRequireModules.has(normalizedId) && (!(hasCjsKeywords(code, ignoreGlobal) || requireResolver.isRequiredId(id)) || isEsModule && !options.transformMixedEsModules)) {
1196
- commonjsMeta.isCommonJS = false;
1197
- return { meta: { commonjs: commonjsMeta } };
1198
- }
1199
- const needsRequireWrapper = !isEsModule && (dynamicRequireModules.has(normalizedId) || strictRequiresFilter(id));
1200
- const checkDynamicRequire = (position) => {
1201
- const normalizedDynamicRequireRoot = normalizePathSlashes(dynamicRequireRoot);
1202
- if (normalizedId.indexOf(normalizedDynamicRequireRoot) !== 0) this.error({
1203
- code: "DYNAMIC_REQUIRE_OUTSIDE_ROOT",
1204
- normalizedId,
1205
- normalizedDynamicRequireRoot,
1206
- message: `"${normalizedId}" contains dynamic require statements but it is not within the current dynamicRequireRoot "${normalizedDynamicRequireRoot}". You should set dynamicRequireRoot to "${dirname(normalizedId)}" or one of its parent directories.`
1207
- }, position);
1208
- };
1209
- return transformCommonjs(this.parse, code, id, isEsModule, ignoreGlobal || isEsModule, ignoreRequire, ignoreDynamicRequires && !isDynamicRequireModulesEnabled, getIgnoreTryCatchRequireStatementMode, sourceMap, isDynamicRequireModulesEnabled, dynamicRequireModules, commonDir, ast, getDefaultIsModuleExports(id), needsRequireWrapper, requireResolver.resolveRequireSourcesAndUpdateMeta(this), requireResolver.isRequiredId(id), checkDynamicRequire, commonjsMeta);
1210
- }
1211
- return {
1212
- name: PLUGIN_NAME,
1213
- version,
1214
- options(rawOptions) {
1215
- const plugins = Array.isArray(rawOptions.plugins) ? [...rawOptions.plugins] : rawOptions.plugins ? [rawOptions.plugins] : [];
1216
- plugins.unshift({
1217
- name: "commonjs--resolver",
1218
- resolveId
1219
- });
1220
- return {
1221
- ...rawOptions,
1222
- plugins
1223
- };
1224
- },
1225
- buildStart({ plugins }) {
1226
- validateVersion(this.meta.rollupVersion, peerDependencies.rollup, "rollup");
1227
- const nodeResolve = plugins.find(({ name }) => name === "node-resolve");
1228
- if (nodeResolve) validateVersion(nodeResolve.version, "^13.0.6", "@rollup/plugin-node-resolve");
1229
- if (options.namedExports != null) this.warn("The namedExports option from \"@rollup/plugin-commonjs\" is deprecated. Named exports are now handled automatically.");
1230
- requireResolver = getRequireResolver(extensions, detectCyclesAndConditional, currentlyResolving, requireNodeBuiltins);
1231
- },
1232
- buildEnd() {
1233
- if (options.strictRequires === "debug") {
1234
- const wrappedIds = requireResolver.getWrappedIds();
1235
- if (wrappedIds.length) this.warn({
1236
- code: "WRAPPED_IDS",
1237
- ids: wrappedIds,
1238
- message: `The commonjs plugin automatically wrapped the following files:\n[\n${wrappedIds.map((id) => `\t${JSON.stringify(relative(process.cwd(), id))}`).join(",\n")}\n]`
1239
- });
1240
- else this.warn({
1241
- code: "WRAPPED_IDS",
1242
- ids: wrappedIds,
1243
- message: "The commonjs plugin did not wrap any files."
1244
- });
1245
- }
1246
- },
1247
- async load(id) {
1248
- if (id === HELPERS_ID) return getHelpersModule();
1249
- if (isWrappedId(id, MODULE_SUFFIX)) {
1250
- const name = getName(unwrapId(id, MODULE_SUFFIX));
1251
- return {
1252
- code: `var ${name} = {exports: {}}; export {${name} as __module}`,
1253
- meta: { commonjs: { isCommonJS: false } }
1254
- };
1255
- }
1256
- if (isWrappedId(id, EXPORTS_SUFFIX)) {
1257
- const name = getName(unwrapId(id, EXPORTS_SUFFIX));
1258
- return {
1259
- code: `var ${name} = {}; export {${name} as __exports}`,
1260
- meta: { commonjs: { isCommonJS: false } }
1261
- };
1262
- }
1263
- if (isWrappedId(id, EXTERNAL_SUFFIX)) {
1264
- const actualId = unwrapId(id, EXTERNAL_SUFFIX);
1265
- if (requireNodeBuiltins === true && actualId.startsWith("node:")) return getExternalBuiltinRequireProxy(actualId);
1266
- return getUnknownRequireProxy(actualId, isEsmExternal(actualId) ? getRequireReturnsDefault(actualId) : true);
1267
- }
1268
- if (id.endsWith(ENTRY_SUFFIX)) {
1269
- const acutalId = id.slice(0, -15);
1270
- const { meta: { commonjs: commonjsMeta } } = this.getModuleInfo(acutalId);
1271
- const shebang = commonjsMeta?.shebang ?? "";
1272
- return getEntryProxy(acutalId, getDefaultIsModuleExports(acutalId), this.getModuleInfo, shebang);
1273
- }
1274
- if (isWrappedId(id, ES_IMPORT_SUFFIX)) {
1275
- const actualId = unwrapId(id, ES_IMPORT_SUFFIX);
1276
- return getEsImportProxy(actualId, getDefaultIsModuleExports(actualId), (await this.load({ id: actualId })).moduleSideEffects);
1277
- }
1278
- if (id === DYNAMIC_MODULES_ID) return getDynamicModuleRegistry(isDynamicRequireModulesEnabled, dynamicRequireModules, commonDir, ignoreDynamicRequires);
1279
- if (isWrappedId(id, PROXY_SUFFIX)) {
1280
- const actualId = unwrapId(id, PROXY_SUFFIX);
1281
- return getStaticRequireProxy(actualId, getRequireReturnsDefault(actualId), this.load);
1282
- }
1283
- return null;
1284
- },
1285
- shouldTransformCachedModule(...args) {
1286
- return requireResolver.shouldTransformCachedModule.call(this, ...args);
1287
- },
1288
- transform(code, id) {
1289
- if (!isPossibleCjsId(id)) return null;
1290
- try {
1291
- return transformAndCheckExports.call(this, code, id);
1292
- } catch (err) {
1293
- return this.error(err, err.pos);
1294
- }
1295
- }
1296
- };
1297
- }
1298
-
1299
- //#endregion
1300
- export { commonjs as t };