rolldown-require 2.0.0 → 2.0.2

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.
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/bundler.ts
2
- import path6 from "path";
2
+ import path4 from "path";
3
3
  import { pathToFileURL as pathToFileURL2 } from "url";
4
4
  import { rolldown } from "rolldown";
5
5
 
@@ -25,299 +25,37 @@ function collectReferencedModules(bundle, fileName, allModules, analyzedModules
25
25
  }
26
26
 
27
27
  // src/externalize.ts
28
- import fs4 from "fs";
28
+ import fs3 from "fs";
29
29
  import { createRequire as createRequire3 } from "module";
30
- import path5 from "path";
31
- import { pathToFileURL } from "url";
32
-
33
- // src/config.ts
34
- var configDefaults = Object.freeze({
35
- resolve: {
36
- extensions: [".mjs", ".js", ".mts", ".ts", ".jsx", ".tsx", ".json"]
37
- }
38
- });
39
- var defaultGetOutputFile = (filepath, _format) => {
40
- return filepath;
41
- };
30
+ import path3 from "path";
31
+ import { fileURLToPath, pathToFileURL } from "url";
42
32
 
43
- // src/plugins/resolve.ts
44
- import fs3 from "fs";
45
- import path4 from "path";
46
- import { hasESMSyntax } from "mlly";
47
- import { exports, imports } from "resolve.exports";
33
+ // src/utils.ts
34
+ import { exec } from "child_process";
35
+ import fs2 from "fs";
36
+ import { builtinModules, createRequire as createRequire2 } from "module";
37
+ import path2 from "path";
38
+ import process3 from "process";
39
+ import { createFilter as _createFilter } from "@rollup/pluginutils";
48
40
 
49
41
  // src/constants.ts
50
42
  import { readFileSync } from "fs";
51
43
  var { version } = JSON.parse(
52
44
  readFileSync(new URL("../package.json", import.meta.url)).toString()
53
45
  );
54
- var DEV_PROD_CONDITION = `development|production`;
55
- var OPTIMIZABLE_ENTRY_RE = /\.[cm]?[jt]s$/;
56
- var SPECIAL_QUERY_RE = /[?&](?:worker|sharedworker|raw|url)\b/;
57
-
58
- // src/external.ts
59
- import path from "path";
60
- function canExternalizeFile(filePath) {
61
- const ext = path.extname(filePath);
62
- return !ext || ext === ".js" || ext === ".mjs" || ext === ".cjs";
63
- }
64
46
 
65
47
  // src/packages.ts
66
- import fs2 from "fs";
67
- import { createRequire as createRequire2 } from "module";
68
- import path3 from "path";
69
- import process3 from "process";
70
-
71
- // src/utils.ts
72
- import { exec } from "child_process";
73
48
  import fs from "fs";
74
- import { builtinModules, createRequire } from "module";
75
- import path2 from "path";
76
- import process2 from "process";
77
- import { createFilter as _createFilter } from "@rollup/pluginutils";
78
-
79
- // src/sharedUtils.ts
49
+ import { createRequire } from "module";
50
+ import path from "path";
80
51
  import process from "process";
81
- var isWindows = typeof process !== "undefined" && process.platform === "win32";
82
- var windowsSlashRE = /\\/g;
83
- function slash(p) {
84
- return p.replace(windowsSlashRE, "/");
85
- }
86
- var postfixRE = /[?#].*$/;
87
- function cleanUrl(url) {
88
- return url.replace(postfixRE, "");
89
- }
90
- function splitFileAndPostfix(path11) {
91
- const file = cleanUrl(path11);
92
- return { file, postfix: path11.slice(file.length) };
93
- }
94
-
95
- // src/utils.ts
96
- var createFilter = _createFilter;
97
- var NODE_BUILTIN_NAMESPACE = "node:";
98
- var NPM_BUILTIN_NAMESPACE = "npm:";
99
- var BUN_BUILTIN_NAMESPACE = "bun:";
100
- var nodeBuiltins = builtinModules.filter((id) => !id.includes(":"));
101
- var isBuiltinCache = /* @__PURE__ */ new WeakMap();
102
- function isBuiltin(builtins, id) {
103
- let isBuiltin2 = isBuiltinCache.get(builtins);
104
- if (!isBuiltin2) {
105
- isBuiltin2 = createIsBuiltin(builtins);
106
- isBuiltinCache.set(builtins, isBuiltin2);
107
- }
108
- return isBuiltin2(id);
109
- }
110
- function createIsBuiltin(builtins) {
111
- const plainBuiltinsSet = new Set(
112
- builtins.filter((builtin) => typeof builtin === "string")
113
- );
114
- const regexBuiltins = builtins.filter(
115
- (builtin) => typeof builtin !== "string"
116
- );
117
- return (id) => plainBuiltinsSet.has(id) || regexBuiltins.some((regexp) => regexp.test(id));
118
- }
119
- var nodeLikeBuiltins = [
120
- ...nodeBuiltins,
121
- new RegExp(`^${NODE_BUILTIN_NAMESPACE}`),
122
- new RegExp(`^${NPM_BUILTIN_NAMESPACE}`),
123
- new RegExp(`^${BUN_BUILTIN_NAMESPACE}`)
124
- ];
125
- function isNodeLikeBuiltin(id) {
126
- return isBuiltin(nodeLikeBuiltins, id);
127
- }
128
- function isNodeBuiltin(id) {
129
- if (id.startsWith(NODE_BUILTIN_NAMESPACE)) {
130
- return true;
131
- }
132
- return nodeBuiltins.includes(id);
133
- }
134
- function isInNodeModules(id) {
135
- return id.includes("node_modules");
136
- }
137
- function isOptimizable(id, optimizeDeps) {
138
- const { extensions } = optimizeDeps;
139
- return OPTIMIZABLE_ENTRY_RE.test(id) || (extensions?.some((ext) => id.endsWith(ext)) ?? false);
140
- }
141
- var bareImportRE = /^(?![a-z]:)[\w@](?!.*:\/\/)/i;
142
- var deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\//;
143
- function normalizePath(id) {
144
- return path2.posix.normalize(isWindows ? slash(id) : id);
145
- }
146
- function injectQuery(url, queryToInject) {
147
- const { file, postfix } = splitFileAndPostfix(url);
148
- const normalizedFile = isWindows ? slash(file) : file;
149
- return `${normalizedFile}?${queryToInject}${postfix[0] === "?" ? `&${postfix.slice(1)}` : (
150
- /* hash only */
151
- postfix
152
- )}`;
153
- }
154
- function isObject(value) {
155
- return Object.prototype.toString.call(value) === "[object Object]";
156
- }
157
- function tryStatSync(file) {
158
- try {
159
- return fs.statSync(file, { throwIfNoEntry: false });
160
- } catch {
161
- }
162
- }
163
- function isFilePathESM(filePath, packageCache) {
164
- if (/\.m[jt]s$/.test(filePath)) {
165
- return true;
166
- } else if (/\.c[jt]s$/.test(filePath)) {
167
- return false;
168
- } else {
169
- try {
170
- const pkg = findNearestPackageData(path2.dirname(filePath), packageCache);
171
- return pkg?.data.type === "module";
172
- } catch {
173
- return false;
174
- }
175
- }
176
- }
177
- var currentSafeRealpathSync = isWindows ? windowsSafeRealPathSync : fs.realpathSync.native;
178
- function safeRealpathSync(filePath) {
179
- return currentSafeRealpathSync(filePath);
180
- }
181
- var windowsNetworkMap = /* @__PURE__ */ new Map();
182
- function windowsMappedRealpathSync(path11) {
183
- const realPath = fs.realpathSync.native(path11);
184
- if (realPath.startsWith("\\\\")) {
185
- for (const [network, volume] of windowsNetworkMap) {
186
- if (realPath.startsWith(network)) {
187
- return realPath.replace(network, volume);
188
- }
189
- }
190
- }
191
- return realPath;
192
- }
193
- var parseNetUseRE = /^\w* +(\w:) +([^ ]+)\s/;
194
- var firstSafeRealPathSyncRun = false;
195
- function windowsSafeRealPathSync(path11) {
196
- if (!firstSafeRealPathSyncRun) {
197
- optimizeSafeRealPathSync();
198
- firstSafeRealPathSyncRun = true;
199
- }
200
- return fs.realpathSync(path11);
201
- }
202
- function optimizeSafeRealPathSync() {
203
- const nodeVersion = process2.versions.node.split(".").map(Number);
204
- if (nodeVersion[0] < 18 || nodeVersion[0] === 18 && nodeVersion[1] < 10) {
205
- currentSafeRealpathSync = fs.realpathSync;
206
- return;
207
- }
208
- try {
209
- fs.realpathSync.native(path2.resolve("./"));
210
- } catch (error) {
211
- if (error.message.includes("EISDIR: illegal operation on a directory")) {
212
- currentSafeRealpathSync = fs.realpathSync;
213
- return;
214
- }
215
- }
216
- exec("net use", (error, stdout) => {
217
- if (error) {
218
- return;
219
- }
220
- const lines = stdout.split("\n");
221
- for (const line of lines) {
222
- const m = parseNetUseRE.exec(line);
223
- if (m) {
224
- windowsNetworkMap.set(m[2], m[1]);
225
- }
226
- }
227
- currentSafeRealpathSync = windowsNetworkMap.size === 0 ? fs.realpathSync.native : windowsMappedRealpathSync;
228
- });
229
- }
230
- function stripBomTag(content) {
231
- if (content.charCodeAt(0) === 65279) {
232
- return content.slice(1);
233
- }
234
- return content;
235
- }
236
- function getNpmPackageName(importPath) {
237
- const parts = importPath.split("/");
238
- if (parts[0][0] === "@") {
239
- if (!parts[1]) {
240
- return null;
241
- }
242
- return `${parts[0]}/${parts[1]}`;
243
- } else {
244
- return parts[0];
245
- }
246
- }
247
- var dynamicImport = async (id, { format }) => {
248
- const fn = format === "esm" ? (file) => import(file) : true ? createRequire(import.meta.url) : __require;
249
- return fn(id);
250
- };
251
-
252
- // src/packages.ts
253
52
  var pnp;
254
- if (process3.versions.pnp) {
53
+ if (process.versions.pnp) {
255
54
  try {
256
- pnp = createRequire2(import.meta.url)("pnpapi");
55
+ pnp = createRequire(import.meta.url)("pnpapi");
257
56
  } catch {
258
57
  }
259
58
  }
260
- function resolvePackageData(pkgName, basedir, preserveSymlinks = false, packageCache) {
261
- if (pnp) {
262
- const cacheKey = getRpdCacheKey(pkgName, basedir, preserveSymlinks);
263
- if (packageCache?.has(cacheKey)) {
264
- return packageCache.get(cacheKey);
265
- }
266
- try {
267
- const pkg = pnp.resolveToUnqualified(pkgName, basedir, {
268
- considerBuiltins: false
269
- });
270
- if (!pkg) {
271
- return null;
272
- }
273
- const pkgData = loadPackageData(path3.join(pkg, "package.json"));
274
- packageCache?.set(cacheKey, pkgData);
275
- return pkgData;
276
- } catch {
277
- return null;
278
- }
279
- }
280
- const originalBasedir = basedir;
281
- while (basedir) {
282
- if (packageCache) {
283
- const cached = getRpdCache(
284
- packageCache,
285
- pkgName,
286
- basedir,
287
- originalBasedir,
288
- preserveSymlinks
289
- );
290
- if (cached) {
291
- return cached;
292
- }
293
- }
294
- const pkg = path3.join(basedir, "node_modules", pkgName, "package.json");
295
- try {
296
- if (fs2.existsSync(pkg)) {
297
- const pkgPath = preserveSymlinks ? pkg : safeRealpathSync(pkg);
298
- const pkgData = loadPackageData(pkgPath);
299
- if (packageCache) {
300
- setRpdCache(
301
- packageCache,
302
- pkgData,
303
- pkgName,
304
- basedir,
305
- originalBasedir,
306
- preserveSymlinks
307
- );
308
- }
309
- return pkgData;
310
- }
311
- } catch {
312
- }
313
- const nextBasedir = path3.dirname(basedir);
314
- if (nextBasedir === basedir) {
315
- break;
316
- }
317
- basedir = nextBasedir;
318
- }
319
- return null;
320
- }
321
59
  function findNearestPackageData(basedir, packageCache) {
322
60
  const originalBasedir = basedir;
323
61
  while (basedir) {
@@ -327,7 +65,7 @@ function findNearestPackageData(basedir, packageCache) {
327
65
  return cached;
328
66
  }
329
67
  }
330
- const pkgPath = path3.join(basedir, "package.json");
68
+ const pkgPath = path.join(basedir, "package.json");
331
69
  if (tryStatSync(pkgPath)?.isFile()) {
332
70
  try {
333
71
  const pkgData = loadPackageData(pkgPath);
@@ -338,7 +76,7 @@ function findNearestPackageData(basedir, packageCache) {
338
76
  } catch {
339
77
  }
340
78
  }
341
- const nextBasedir = path3.dirname(basedir);
79
+ const nextBasedir = path.dirname(basedir);
342
80
  if (nextBasedir === basedir) {
343
81
  break;
344
82
  }
@@ -346,16 +84,9 @@ function findNearestPackageData(basedir, packageCache) {
346
84
  }
347
85
  return null;
348
86
  }
349
- function findNearestMainPackageData(basedir, packageCache) {
350
- const nearestPackage = findNearestPackageData(basedir, packageCache);
351
- return nearestPackage && (nearestPackage.data.name ? nearestPackage : findNearestMainPackageData(
352
- path3.dirname(nearestPackage.dir),
353
- packageCache
354
- ));
355
- }
356
87
  function loadPackageData(pkgPath) {
357
- const data = JSON.parse(stripBomTag(fs2.readFileSync(pkgPath, "utf-8")));
358
- const pkgDir = normalizePath(path3.dirname(pkgPath));
88
+ const data = JSON.parse(stripBomTag(fs.readFileSync(pkgPath, "utf-8")));
89
+ const pkgDir = normalizePath(path.dirname(pkgPath));
359
90
  const { sideEffects } = data;
360
91
  let hasSideEffects;
361
92
  if (typeof sideEffects === "boolean") {
@@ -402,11 +133,11 @@ function getResolveCacheKey(key, options) {
402
133
  }
403
134
  function findNearestNodeModules(basedir) {
404
135
  while (basedir) {
405
- const pkgPath = path3.join(basedir, "node_modules");
136
+ const pkgPath = path.join(basedir, "node_modules");
406
137
  if (tryStatSync(pkgPath)?.isDirectory()) {
407
138
  return pkgPath;
408
139
  }
409
- const nextBasedir = path3.dirname(basedir);
140
+ const nextBasedir = path.dirname(basedir);
410
141
  if (nextBasedir === basedir) {
411
142
  break;
412
143
  }
@@ -414,25 +145,6 @@ function findNearestNodeModules(basedir) {
414
145
  }
415
146
  return null;
416
147
  }
417
- function getRpdCache(packageCache, pkgName, basedir, originalBasedir, preserveSymlinks) {
418
- const cacheKey = getRpdCacheKey(pkgName, basedir, preserveSymlinks);
419
- const pkgData = packageCache.get(cacheKey);
420
- if (pkgData) {
421
- traverseBetweenDirs(originalBasedir, basedir, (dir) => {
422
- packageCache.set(getRpdCacheKey(pkgName, dir, preserveSymlinks), pkgData);
423
- });
424
- return pkgData;
425
- }
426
- }
427
- function setRpdCache(packageCache, pkgData, pkgName, basedir, originalBasedir, preserveSymlinks) {
428
- packageCache.set(getRpdCacheKey(pkgName, basedir, preserveSymlinks), pkgData);
429
- traverseBetweenDirs(originalBasedir, basedir, (dir) => {
430
- packageCache.set(getRpdCacheKey(pkgName, dir, preserveSymlinks), pkgData);
431
- });
432
- }
433
- function getRpdCacheKey(pkgName, basedir, preserveSymlinks) {
434
- return `rpd_${pkgName}_${basedir}_${preserveSymlinks}`;
435
- }
436
148
  function getFnpdCache(packageCache, basedir, originalBasedir) {
437
149
  const cacheKey = getFnpdCacheKey(basedir);
438
150
  const pkgData = packageCache.get(cacheKey);
@@ -455,502 +167,235 @@ function getFnpdCacheKey(basedir) {
455
167
  function traverseBetweenDirs(longerDir, shorterDir, cb) {
456
168
  while (longerDir !== shorterDir) {
457
169
  cb(longerDir);
458
- longerDir = path3.dirname(longerDir);
170
+ longerDir = path.dirname(longerDir);
459
171
  }
460
172
  }
461
173
 
462
- // src/plugins/resolve.ts
463
- var ERR_RESOLVE_PACKAGE_ENTRY_FAIL = "ERR_RESOLVE_PACKAGE_ENTRY_FAIL";
464
- var browserExternalId = "__vite-browser-external";
465
- var optionalPeerDepId = "__vite-optional-peer-dep";
466
- function tryFsResolve(fsPath, options, tryIndex = true, skipPackageJson = false) {
467
- const hashIndex = fsPath.indexOf("#");
468
- if (hashIndex >= 0 && isInNodeModules(fsPath)) {
469
- const queryIndex = fsPath.indexOf("?");
470
- if (queryIndex < 0 || queryIndex > hashIndex) {
471
- const file2 = queryIndex > hashIndex ? fsPath.slice(0, queryIndex) : fsPath;
472
- const res2 = tryCleanFsResolve(file2, options, tryIndex, skipPackageJson);
473
- if (res2) {
474
- return res2 + fsPath.slice(file2.length);
475
- }
476
- }
477
- }
478
- const { file, postfix } = splitFileAndPostfix(fsPath);
479
- const res = tryCleanFsResolve(file, options, tryIndex, skipPackageJson);
480
- if (res) {
481
- return res + postfix;
482
- }
483
- }
484
- var knownTsOutputRE = /\.(?:js|mjs|cjs|jsx)$/;
485
- var isPossibleTsOutput = (url) => knownTsOutputRE.test(url);
486
- function tryCleanFsResolve(file, options, tryIndex = true, skipPackageJson = false) {
487
- const { tryPrefix, extensions, preserveSymlinks } = options;
488
- const fileResult = tryResolveRealFileOrType(file, options.preserveSymlinks);
489
- if (fileResult?.path) {
490
- return fileResult.path;
491
- }
492
- let res;
493
- const possibleJsToTs = isPossibleTsOutput(file);
494
- if (possibleJsToTs || options.extensions.length || tryPrefix) {
495
- const dirPath = path4.dirname(file);
496
- if (isDirectory(dirPath)) {
497
- if (possibleJsToTs) {
498
- const fileExt = path4.extname(file);
499
- const fileName = file.slice(0, -fileExt.length);
500
- if (res = tryResolveRealFile(
501
- fileName + fileExt.replace("js", "ts"),
502
- preserveSymlinks
503
- )) {
504
- return res;
505
- }
506
- if (fileExt === ".js" && (res = tryResolveRealFile(`${fileName}.tsx`, preserveSymlinks))) {
507
- return res;
508
- }
509
- }
510
- if (res = tryResolveRealFileWithExtensions(
511
- file,
512
- extensions,
513
- preserveSymlinks
514
- )) {
515
- return res;
516
- }
517
- if (tryPrefix) {
518
- const prefixed = `${dirPath}/${options.tryPrefix}${path4.basename(file)}`;
519
- if (res = tryResolveRealFile(prefixed, preserveSymlinks)) {
520
- return res;
521
- }
522
- if (res = tryResolveRealFileWithExtensions(
523
- prefixed,
524
- extensions,
525
- preserveSymlinks
526
- )) {
527
- return res;
528
- }
529
- }
530
- }
531
- }
532
- if (tryIndex && fileResult?.type === "directory") {
533
- const dirPath = file;
534
- if (!skipPackageJson) {
535
- let pkgPath = `${dirPath}/package.json`;
536
- try {
537
- if (fs3.existsSync(pkgPath)) {
538
- if (!options.preserveSymlinks) {
539
- pkgPath = safeRealpathSync(pkgPath);
540
- }
541
- const pkg = loadPackageData(pkgPath);
542
- return resolvePackageEntry(dirPath, pkg, options);
543
- }
544
- } catch (e) {
545
- if (e.code !== ERR_RESOLVE_PACKAGE_ENTRY_FAIL && e.code !== "ENOENT") {
546
- throw e;
547
- }
548
- }
549
- }
550
- if (res = tryResolveRealFileWithExtensions(
551
- `${dirPath}/index`,
552
- extensions,
553
- preserveSymlinks
554
- )) {
555
- return res;
556
- }
557
- if (tryPrefix) {
558
- if (res = tryResolveRealFileWithExtensions(
559
- `${dirPath}/${options.tryPrefix}index`,
560
- extensions,
561
- preserveSymlinks
562
- )) {
563
- return res;
564
- }
565
- }
566
- }
567
- }
568
- function tryNodeResolve(id, importer, options, depsOptimizer, externalize) {
569
- const { root, dedupe, isBuild, preserveSymlinks, packageCache } = options;
570
- const deepMatch = deepImportRE.exec(id);
571
- const pkgId = deepMatch ? deepMatch[1] || deepMatch[2] : cleanUrl(id);
572
- let basedir;
573
- if (dedupe.includes(pkgId)) {
574
- basedir = root;
575
- } else if (importer && path4.isAbsolute(importer) && (importer.endsWith("*") || fs3.existsSync(cleanUrl(importer)))) {
576
- basedir = path4.dirname(importer);
577
- } else {
578
- basedir = root;
579
- }
580
- const isModuleBuiltin = (id2) => isBuiltin(options.builtins, id2);
581
- let selfPkg = null;
582
- if (!isModuleBuiltin(id) && !id.includes("\0") && bareImportRE.test(id)) {
583
- const selfPackageData = findNearestPackageData(basedir, packageCache);
584
- selfPkg = selfPackageData?.data.exports && selfPackageData.data.name === pkgId ? selfPackageData : null;
585
- }
586
- const pkg = selfPkg || resolvePackageData(pkgId, basedir, preserveSymlinks, packageCache);
587
- if (!pkg) {
588
- if (basedir !== root && !isModuleBuiltin(id) && !id.includes("\0") && bareImportRE.test(id)) {
589
- const mainPkg = findNearestMainPackageData(basedir, packageCache)?.data;
590
- if (mainPkg) {
591
- const pkgName = getNpmPackageName(id);
592
- if (pkgName != null && mainPkg.peerDependencies?.[pkgName] && mainPkg.peerDependenciesMeta?.[pkgName]?.optional) {
593
- return {
594
- id: `${optionalPeerDepId}:${id}:${mainPkg.name}`
595
- };
596
- }
597
- }
598
- }
599
- return;
600
- }
601
- const resolveId = deepMatch ? resolveDeepImport : resolvePackageEntry;
602
- const unresolvedId = deepMatch ? `.${id.slice(pkgId.length)}` : id;
603
- let resolved = resolveId(unresolvedId, pkg, options);
604
- if (!resolved) {
605
- return;
606
- }
607
- const processResult = (resolved2) => {
608
- if (!externalize) {
609
- return resolved2;
610
- }
611
- if (!canExternalizeFile(resolved2.id)) {
612
- return resolved2;
613
- }
614
- let resolvedId = id;
615
- if (deepMatch && !pkg.data.exports && path4.extname(id) !== path4.extname(resolved2.id)) {
616
- const index = resolved2.id.indexOf(id);
617
- if (index > -1) {
618
- resolvedId = resolved2.id.slice(index);
619
- }
620
- }
621
- return { ...resolved2, id: resolvedId, external: true };
622
- };
623
- if (!options.idOnly && (!options.scan && isBuild || externalize)) {
624
- return processResult({
625
- id: resolved,
626
- moduleSideEffects: pkg.hasSideEffects(resolved)
627
- });
628
- }
629
- if (!isInNodeModules(resolved) || !depsOptimizer || options.scan) {
630
- return { id: resolved };
631
- }
632
- const isJsType = isOptimizable(resolved, depsOptimizer.options);
633
- const exclude = depsOptimizer.options.exclude;
634
- const skipOptimization = depsOptimizer.options.noDiscovery || !isJsType || importer && isInNodeModules(importer) || exclude?.includes(pkgId) || exclude?.includes(id) || SPECIAL_QUERY_RE.test(resolved);
635
- if (skipOptimization) {
636
- const versionHash = depsOptimizer.metadata.browserHash;
637
- if (versionHash && isJsType) {
638
- resolved = injectQuery(resolved, `v=${versionHash}`);
639
- }
640
- } else {
641
- const optimizedInfo = depsOptimizer.registerMissingImport(id, resolved);
642
- resolved = depsOptimizer.getOptimizedDepId(optimizedInfo);
643
- }
644
- return { id: resolved };
174
+ // src/sharedUtils.ts
175
+ import process2 from "process";
176
+ var isWindows = typeof process2 !== "undefined" && process2.platform === "win32";
177
+ var windowsSlashRE = /\\/g;
178
+ function slash(p) {
179
+ return p.replace(windowsSlashRE, "/");
645
180
  }
646
- function resolvePackageEntry(id, { dir, data, setResolvedCache, getResolvedCache }, options) {
647
- const { postfix } = splitFileAndPostfix(id);
648
- const cached = getResolvedCache(".", options);
649
- if (cached) {
650
- return cached + postfix;
651
- }
652
- try {
653
- let entryPoint;
654
- if (data.exports) {
655
- entryPoint = resolveExportsOrImports(data, ".", options, "exports");
656
- }
657
- if (!entryPoint) {
658
- for (const field of options.mainFields) {
659
- if (field === "browser") {
660
- entryPoint = tryResolveBrowserEntry(dir, data, options);
661
- if (entryPoint) {
662
- break;
663
- }
664
- } else if (typeof data[field] === "string") {
665
- entryPoint = data[field];
666
- break;
667
- }
668
- }
669
- }
670
- entryPoint ||= data.main;
671
- const entryPoints = entryPoint ? [entryPoint] : ["index.js", "index.json", "index.node"];
672
- for (let entry of entryPoints) {
673
- let skipPackageJson = false;
674
- if (options.mainFields[0] === "sass" && !options.extensions.includes(path4.extname(entry))) {
675
- entry = "";
676
- skipPackageJson = true;
677
- } else {
678
- const { browser: browserField } = data;
679
- if (options.mainFields.includes("browser") && isObject(browserField)) {
680
- entry = mapWithBrowserField(entry, browserField) || entry;
681
- }
682
- }
683
- const entryPointPath = path4.join(dir, entry);
684
- const resolvedEntryPoint = tryFsResolve(
685
- entryPointPath,
686
- options,
687
- true,
688
- skipPackageJson
689
- );
690
- if (resolvedEntryPoint) {
691
- setResolvedCache(".", resolvedEntryPoint, options);
692
- return resolvedEntryPoint + postfix;
693
- }
694
- }
695
- } catch (e) {
696
- packageEntryFailure(
697
- id,
698
- // @ts-ignore
699
- e.message
700
- );
181
+
182
+ // src/utils.ts
183
+ var createFilter = _createFilter;
184
+ var NODE_BUILTIN_NAMESPACE = "node:";
185
+ var NPM_BUILTIN_NAMESPACE = "npm:";
186
+ var BUN_BUILTIN_NAMESPACE = "bun:";
187
+ var nodeBuiltins = builtinModules.filter((id) => !id.includes(":"));
188
+ var isBuiltinCache = /* @__PURE__ */ new WeakMap();
189
+ function isBuiltin(builtins, id) {
190
+ let isBuiltin2 = isBuiltinCache.get(builtins);
191
+ if (!isBuiltin2) {
192
+ isBuiltin2 = createIsBuiltin(builtins);
193
+ isBuiltinCache.set(builtins, isBuiltin2);
701
194
  }
702
- packageEntryFailure(id);
195
+ return isBuiltin2(id);
703
196
  }
704
- function packageEntryFailure(id, details) {
705
- const err = new Error(
706
- `Failed to resolve entry for package "${id}". The package may have incorrect main/module/exports specified in its package.json${details ? `: ${details}` : "."}`
197
+ function createIsBuiltin(builtins) {
198
+ const plainBuiltinsSet = new Set(
199
+ builtins.filter((builtin) => typeof builtin === "string")
200
+ );
201
+ const regexBuiltins = builtins.filter(
202
+ (builtin) => typeof builtin !== "string"
707
203
  );
708
- err.code = ERR_RESOLVE_PACKAGE_ENTRY_FAIL;
709
- throw err;
204
+ return (id) => plainBuiltinsSet.has(id) || regexBuiltins.some((regexp) => regexp.test(id));
710
205
  }
711
- function getConditions(conditions, isProduction, isRequire) {
712
- const resolvedConditions = conditions.map((condition) => {
713
- if (condition === DEV_PROD_CONDITION) {
714
- return isProduction ? "production" : "development";
715
- }
716
- return condition;
717
- });
718
- if (isRequire) {
719
- resolvedConditions.push("require");
720
- } else {
721
- resolvedConditions.push("import");
206
+ var nodeLikeBuiltins = [
207
+ ...nodeBuiltins,
208
+ new RegExp(`^${NODE_BUILTIN_NAMESPACE}`),
209
+ new RegExp(`^${NPM_BUILTIN_NAMESPACE}`),
210
+ new RegExp(`^${BUN_BUILTIN_NAMESPACE}`)
211
+ ];
212
+ function isNodeLikeBuiltin(id) {
213
+ return isBuiltin(nodeLikeBuiltins, id);
214
+ }
215
+ function isNodeBuiltin(id) {
216
+ if (id.startsWith(NODE_BUILTIN_NAMESPACE)) {
217
+ return true;
722
218
  }
723
- return resolvedConditions;
219
+ return nodeBuiltins.includes(id);
724
220
  }
725
- function resolveExportsOrImports(pkg, key, options, type) {
726
- const conditions = getConditions(
727
- options.conditions,
728
- options.isProduction,
729
- options.isRequire
730
- );
731
- const fn = type === "imports" ? imports : exports;
732
- const result = fn(pkg, key, { conditions, unsafe: true });
733
- return result ? result[0] : void 0;
221
+ function normalizePath(id) {
222
+ return path2.posix.normalize(isWindows ? slash(id) : id);
734
223
  }
735
- function resolveDeepImport(id, { setResolvedCache, getResolvedCache, dir, data }, options) {
736
- const cache = getResolvedCache(id, options);
737
- if (cache) {
738
- return cache;
739
- }
740
- let relativeId = id;
741
- const { exports: exportsField, browser: browserField } = data;
742
- if (exportsField) {
743
- if (isObject(exportsField) && !Array.isArray(exportsField)) {
744
- const { file, postfix } = splitFileAndPostfix(relativeId);
745
- const exportsId = resolveExportsOrImports(data, file, options, "exports");
746
- if (exportsId !== void 0) {
747
- relativeId = exportsId + postfix;
748
- } else {
749
- relativeId = void 0;
750
- }
751
- } else {
752
- relativeId = void 0;
753
- }
754
- if (!relativeId) {
755
- throw new Error(
756
- `Package subpath '${relativeId}' is not defined by "exports" in ${path4.join(dir, "package.json")}.`
757
- );
758
- }
759
- } else if (options.mainFields.includes("browser") && isObject(browserField)) {
760
- const { file, postfix } = splitFileAndPostfix(relativeId);
761
- const mapped = mapWithBrowserField(file, browserField);
762
- if (mapped) {
763
- relativeId = mapped + postfix;
764
- } else if (mapped === false) {
765
- setResolvedCache(id, browserExternalId, options);
766
- return browserExternalId;
767
- }
224
+ function tryStatSync(file) {
225
+ try {
226
+ return fs2.statSync(file, { throwIfNoEntry: false });
227
+ } catch {
768
228
  }
769
- if (relativeId) {
770
- const resolved = tryFsResolve(
771
- path4.join(dir, relativeId),
772
- options,
773
- !exportsField
774
- // try index only if no exports field
775
- );
776
- if (resolved) {
777
- setResolvedCache(id, resolved, options);
778
- return resolved;
229
+ }
230
+ function isFilePathESM(filePath, packageCache) {
231
+ if (/\.m[jt]s$/.test(filePath)) {
232
+ return true;
233
+ } else if (/\.c[jt]s$/.test(filePath)) {
234
+ return false;
235
+ } else {
236
+ try {
237
+ const pkg = findNearestPackageData(path2.dirname(filePath), packageCache);
238
+ return pkg?.data.type === "module";
239
+ } catch {
240
+ return false;
779
241
  }
780
242
  }
781
243
  }
782
- function tryResolveBrowserEntry(dir, data, options) {
783
- const browserEntry = typeof data.browser === "string" ? data.browser : isObject(data.browser) && data.browser["."];
784
- if (browserEntry) {
785
- if (!options.isRequire && options.mainFields.includes("module") && typeof data.module === "string" && data.module !== browserEntry) {
786
- const resolvedBrowserEntry = tryFsResolve(
787
- path4.join(dir, browserEntry),
788
- options
789
- );
790
- if (resolvedBrowserEntry) {
791
- const content = fs3.readFileSync(resolvedBrowserEntry, "utf-8");
792
- if (hasESMSyntax(content)) {
793
- return browserEntry;
794
- } else {
795
- return data.module;
796
- }
244
+ var currentSafeRealpathSync = isWindows ? windowsSafeRealPathSync : fs2.realpathSync.native;
245
+ var windowsNetworkMap = /* @__PURE__ */ new Map();
246
+ function windowsMappedRealpathSync(path9) {
247
+ const realPath = fs2.realpathSync.native(path9);
248
+ if (realPath.startsWith("\\\\")) {
249
+ for (const [network, volume] of windowsNetworkMap) {
250
+ if (realPath.startsWith(network)) {
251
+ return realPath.replace(network, volume);
797
252
  }
798
- } else {
799
- return browserEntry;
800
253
  }
801
254
  }
255
+ return realPath;
802
256
  }
803
- function mapWithBrowserField(relativePathInPkgDir, map) {
804
- const normalizedPath = path4.posix.normalize(relativePathInPkgDir);
805
- for (const key in map) {
806
- const normalizedKey = path4.posix.normalize(key);
807
- if (normalizedPath === normalizedKey || equalWithoutSuffix(normalizedPath, normalizedKey, ".js") || equalWithoutSuffix(normalizedPath, normalizedKey, "/index.js")) {
808
- return map[key];
809
- }
257
+ var parseNetUseRE = /^\w* +(\w:) +([^ ]+)\s/;
258
+ var firstSafeRealPathSyncRun = false;
259
+ function windowsSafeRealPathSync(path9) {
260
+ if (!firstSafeRealPathSyncRun) {
261
+ optimizeSafeRealPathSync();
262
+ firstSafeRealPathSyncRun = true;
810
263
  }
264
+ return fs2.realpathSync(path9);
811
265
  }
812
- function equalWithoutSuffix(path11, key, suffix) {
813
- return key.endsWith(suffix) && key.slice(0, -suffix.length) === path11;
814
- }
815
- function tryResolveRealFile(file, preserveSymlinks) {
816
- const stat = tryStatSync(file);
817
- if (stat?.isFile()) {
818
- return getRealPath(file, preserveSymlinks);
266
+ function optimizeSafeRealPathSync() {
267
+ const nodeVersion = process3.versions.node.split(".").map(Number);
268
+ if (nodeVersion[0] < 18 || nodeVersion[0] === 18 && nodeVersion[1] < 10) {
269
+ currentSafeRealpathSync = fs2.realpathSync;
270
+ return;
819
271
  }
820
- }
821
- function tryResolveRealFileWithExtensions(filePath, extensions, preserveSymlinks) {
822
- for (const ext of extensions) {
823
- const res = tryResolveRealFile(filePath + ext, preserveSymlinks);
824
- if (res) {
825
- return res;
272
+ try {
273
+ fs2.realpathSync.native(path2.resolve("./"));
274
+ } catch (error) {
275
+ if (error.message.includes("EISDIR: illegal operation on a directory")) {
276
+ currentSafeRealpathSync = fs2.realpathSync;
277
+ return;
826
278
  }
827
279
  }
280
+ exec("net use", (error, stdout) => {
281
+ if (error) {
282
+ return;
283
+ }
284
+ const lines = stdout.split("\n");
285
+ for (const line of lines) {
286
+ const m = parseNetUseRE.exec(line);
287
+ if (m) {
288
+ windowsNetworkMap.set(m[2], m[1]);
289
+ }
290
+ }
291
+ currentSafeRealpathSync = windowsNetworkMap.size === 0 ? fs2.realpathSync.native : windowsMappedRealpathSync;
292
+ });
828
293
  }
829
- function tryResolveRealFileOrType(file, preserveSymlinks) {
830
- const fileStat = tryStatSync(file);
831
- if (fileStat?.isFile()) {
832
- return { path: getRealPath(file, preserveSymlinks), type: "file" };
833
- }
834
- if (fileStat?.isDirectory()) {
835
- return { type: "directory" };
836
- }
837
- }
838
- function getRealPath(resolved, preserveSymlinks) {
839
- if (!preserveSymlinks) {
840
- resolved = safeRealpathSync(resolved);
294
+ function stripBomTag(content) {
295
+ if (content.charCodeAt(0) === 65279) {
296
+ return content.slice(1);
841
297
  }
842
- return normalizePath(resolved);
843
- }
844
- function isDirectory(path11) {
845
- const stat = tryStatSync(path11);
846
- return stat?.isDirectory() ?? false;
298
+ return content;
847
299
  }
300
+ var dynamicImport = async (id, { format }) => {
301
+ const fn = format === "esm" ? (file) => import(file) : true ? createRequire2(import.meta.url) : __require;
302
+ return fn(id);
303
+ };
848
304
 
849
305
  // src/externalize.ts
850
306
  function createExternalizeDepsPlugin({
851
307
  entryFile,
852
- isESM,
853
- moduleSyncEnabled
308
+ isESM
854
309
  }) {
855
- const entryDir = path5.dirname(entryFile);
856
- const packageCache = /* @__PURE__ */ new Map();
857
- const resolveByViteResolver = (id, importer, isRequire) => {
858
- return tryNodeResolve(id, importer, {
859
- root: path5.dirname(entryFile),
860
- isBuild: true,
861
- isProduction: true,
862
- preferRelative: false,
863
- tryIndex: true,
864
- mainFields: [],
865
- conditions: [
866
- "node",
867
- ...moduleSyncEnabled ? ["module-sync"] : []
868
- ],
869
- externalConditions: [],
870
- external: [],
871
- noExternal: [],
872
- dedupe: [],
873
- extensions: configDefaults.resolve.extensions,
874
- preserveSymlinks: false,
875
- packageCache,
876
- isRequire,
877
- builtins: nodeLikeBuiltins
878
- })?.id;
879
- };
310
+ const entryDir = path3.dirname(entryFile);
311
+ const externalizeCache = /* @__PURE__ */ new Map();
312
+ const entryResolveCache = /* @__PURE__ */ new Map();
880
313
  return {
881
314
  name: "externalize-deps",
882
315
  resolveId: {
883
316
  filter: { id: /^[^.#].*/ },
884
- async handler(id, importer, { kind }) {
885
- if (!importer || path5.isAbsolute(id) || isNodeBuiltin(id)) {
317
+ async handler(id, importer, options) {
318
+ const { kind } = options;
319
+ if (!importer || path3.isAbsolute(id) || isNodeBuiltin(id)) {
886
320
  return;
887
321
  }
888
322
  if (isNodeLikeBuiltin(id)) {
889
323
  return { id, external: true };
890
324
  }
325
+ const cacheKey = `${importer}::${kind}::${id}`;
326
+ const cached = externalizeCache.get(cacheKey);
327
+ if (cached !== void 0) {
328
+ return cached ?? void 0;
329
+ }
891
330
  const isImport = isESM || kind === "dynamic-import";
892
- let idFsPath;
893
- try {
894
- idFsPath = resolveByViteResolver(id, importer, !isImport);
895
- } catch (e) {
896
- if (!isImport) {
897
- let canResolveWithImport = false;
898
- try {
899
- canResolveWithImport = !!resolveByViteResolver(
900
- id,
901
- importer,
902
- false
903
- );
904
- } catch {
905
- }
906
- if (canResolveWithImport) {
907
- throw new Error(
908
- `Failed to resolve ${JSON.stringify(
909
- id
910
- )}. This package is ESM only but it was tried to load by \`require\`. See https://vite.dev/guide/troubleshooting.html#this-package-is-esm-only for more details.`
911
- );
912
- }
913
- }
914
- throw e;
331
+ const resolved = await resolveWithRolldown(this, id, importer, kind);
332
+ if (!resolved?.id) {
333
+ externalizeCache.set(cacheKey, null);
334
+ return;
335
+ }
336
+ if (resolved.external) {
337
+ const external = resolved.external === "absolute" ? "absolute" : true;
338
+ const result2 = {
339
+ id: resolved.id,
340
+ external
341
+ };
342
+ externalizeCache.set(cacheKey, result2);
343
+ return result2;
915
344
  }
916
- if (!idFsPath) {
345
+ const { cleanId, query } = splitIdAndQuery(resolved.id);
346
+ const resolvedPath = toFilePath(cleanId);
347
+ if (!resolvedPath) {
348
+ externalizeCache.set(cacheKey, null);
917
349
  return;
918
350
  }
919
- if (idFsPath.endsWith(".json")) {
920
- return idFsPath;
351
+ if (!path3.isAbsolute(resolvedPath)) {
352
+ externalizeCache.set(cacheKey, null);
353
+ return;
354
+ }
355
+ if (resolvedPath.endsWith(".json")) {
356
+ const idWithQuery = resolvedPath + query;
357
+ externalizeCache.set(cacheKey, idWithQuery);
358
+ return idWithQuery;
921
359
  }
922
- const shouldExternalize = shouldExternalizeBareImport(id, importer, entryDir);
923
- if (idFsPath && isImport && shouldExternalize) {
924
- idFsPath = pathToFileURL(idFsPath).href;
360
+ const shouldExternalize = shouldExternalizeBareImport(
361
+ id,
362
+ importer,
363
+ entryDir,
364
+ resolvedPath,
365
+ entryResolveCache
366
+ );
367
+ let idOut = resolvedPath + query;
368
+ if (isImport && shouldExternalize) {
369
+ idOut = pathToFileURL(resolvedPath).href + query;
925
370
  }
926
- return { id: idFsPath, external: shouldExternalize };
371
+ const result = { id: idOut, external: shouldExternalize };
372
+ externalizeCache.set(cacheKey, result);
373
+ return result;
927
374
  }
928
375
  }
929
376
  };
930
377
  }
931
- function shouldExternalizeBareImport(specifier, importer, entryDir) {
932
- if (!specifier || specifier.startsWith(".") || path5.isAbsolute(specifier)) {
378
+ function shouldExternalizeBareImport(specifier, importer, entryDir, resolvedPath, canResolveCache) {
379
+ if (!specifier || specifier.startsWith(".") || path3.isAbsolute(specifier)) {
933
380
  return false;
934
381
  }
935
382
  if (isNodeLikeBuiltin(specifier)) {
936
383
  return true;
937
384
  }
938
385
  const importerPath = normalizeImporterPath(importer, entryDir);
939
- try {
940
- const containingNodeModules = findContainingNodeModules(
941
- createRequire3(importerPath).resolve(specifier)
942
- );
386
+ const resolvedFromImporter = resolvedPath ?? resolveSpecifierFromImporter(specifier, importerPath);
387
+ if (resolvedFromImporter) {
388
+ const containingNodeModules = findContainingNodeModules(resolvedFromImporter);
943
389
  if (containingNodeModules) {
944
- const ownerDir = path5.dirname(containingNodeModules);
390
+ const ownerDir = path3.dirname(containingNodeModules);
945
391
  const ownerInsideEntry = isPathWithinDirectory(entryDir, ownerDir);
946
392
  const entryInsideOwner = isPathWithinDirectory(ownerDir, entryDir);
947
393
  if (ownerInsideEntry && !entryInsideOwner) {
948
394
  return false;
949
395
  }
950
396
  }
951
- } catch {
952
397
  }
953
- if (!canResolveFromEntry(specifier, entryDir)) {
398
+ if (!canResolveFromEntry(specifier, entryDir, canResolveCache)) {
954
399
  return false;
955
400
  }
956
401
  return true;
@@ -963,21 +408,21 @@ function normalizeImporterPath(importer, fallback) {
963
408
  return withoutQuery || fallback;
964
409
  }
965
410
  function findContainingNodeModules(filePath) {
966
- let current = path5.dirname(filePath);
967
- const { root } = path5.parse(current);
411
+ let current = path3.dirname(filePath);
412
+ const { root } = path3.parse(current);
968
413
  while (true) {
969
- if (path5.basename(current) === "node_modules") {
414
+ if (path3.basename(current) === "node_modules") {
970
415
  return current;
971
416
  }
972
417
  if (current === root) {
973
418
  break;
974
419
  }
975
- current = path5.dirname(current);
420
+ current = path3.dirname(current);
976
421
  }
977
422
  }
978
423
  function isPathWithinDirectory(parent, child) {
979
- const relative = path5.relative(parent, child);
980
- return relative === "" || !relative.startsWith("..") && !path5.isAbsolute(relative);
424
+ const relative = path3.relative(parent, child);
425
+ return relative === "" || !relative.startsWith("..") && !path3.isAbsolute(relative);
981
426
  }
982
427
  function getPackageName(specifier) {
983
428
  if (!specifier) {
@@ -993,24 +438,52 @@ function getPackageName(specifier) {
993
438
  const [name] = specifier.split("/");
994
439
  return name || void 0;
995
440
  }
996
- function canResolveFromEntry(specifier, entryDir) {
441
+ function canResolveFromEntry(specifier, entryDir, cache) {
997
442
  const packageName = getPackageName(specifier);
998
443
  if (!packageName) {
999
444
  return false;
1000
445
  }
446
+ if (cache?.has(packageName)) {
447
+ return cache.get(packageName);
448
+ }
1001
449
  let currentDir = entryDir;
1002
450
  while (true) {
1003
- if (fs4.existsSync(path5.join(currentDir, "node_modules", packageName))) {
451
+ if (fs3.existsSync(path3.join(currentDir, "node_modules", packageName))) {
452
+ cache?.set(packageName, true);
1004
453
  return true;
1005
454
  }
1006
- const parentDir = path5.dirname(currentDir);
455
+ const parentDir = path3.dirname(currentDir);
1007
456
  if (parentDir === currentDir) {
1008
457
  break;
1009
458
  }
1010
459
  currentDir = parentDir;
1011
460
  }
461
+ cache?.set(packageName, false);
1012
462
  return false;
1013
463
  }
464
+ function resolveWithRolldown(ctx, id, importer, kind) {
465
+ return ctx.resolve(id, importer, { kind, skipSelf: true });
466
+ }
467
+ function splitIdAndQuery(id) {
468
+ const [cleanId, rawQuery] = id.split("?");
469
+ return { cleanId, query: rawQuery ? `?${rawQuery}` : "" };
470
+ }
471
+ function toFilePath(id) {
472
+ if (!id) {
473
+ return null;
474
+ }
475
+ if (id.startsWith("file://")) {
476
+ return fileURLToPath(id);
477
+ }
478
+ return id;
479
+ }
480
+ function resolveSpecifierFromImporter(specifier, importerPath) {
481
+ try {
482
+ return createRequire3(importerPath).resolve(specifier);
483
+ } catch {
484
+ return void 0;
485
+ }
486
+ }
1014
487
 
1015
488
  // src/module-sync.ts
1016
489
  var cachedModuleSyncCondition;
@@ -1036,7 +509,6 @@ async function getModuleSyncConditionEnabled() {
1036
509
  // src/bundler.ts
1037
510
  async function bundleFile(fileName, options) {
1038
511
  const { isESM } = options;
1039
- const moduleSyncEnabled = await getModuleSyncConditionEnabled();
1040
512
  const dirnameVarName = "__vite_injected_original_dirname";
1041
513
  const filenameVarName = "__vite_injected_original_filename";
1042
514
  const importMetaUrlVarName = "__vite_injected_original_import_meta_url";
@@ -1058,10 +530,17 @@ async function bundleFile(fileName, options) {
1058
530
  ...userTransform ?? {},
1059
531
  define: transformDefine
1060
532
  };
533
+ const moduleSyncEnabled = await getModuleSyncConditionEnabled();
534
+ const userConditionNames = userResolve?.conditionNames;
535
+ const conditionNames = [...userConditionNames ?? []];
536
+ if (moduleSyncEnabled && !conditionNames.includes("module-sync")) {
537
+ conditionNames.push("module-sync");
538
+ }
1061
539
  const resolveOptions = {
1062
540
  ...userResolve ?? {},
1063
541
  mainFields: ["main"],
1064
- tsconfigFilename: options.tsconfig
542
+ ...typeof options.tsconfig === "string" ? { tsconfigFilename: options.tsconfig } : {},
543
+ ...conditionNames.length ? { conditionNames } : {}
1065
544
  };
1066
545
  const originalConsoleWarn = console.warn;
1067
546
  console.warn = (...args) => {
@@ -1077,6 +556,7 @@ async function bundleFile(fileName, options) {
1077
556
  ...restRolldownInputOptions,
1078
557
  input: fileName,
1079
558
  platform: "node",
559
+ ...options.tsconfig !== void 0 ? { tsconfig: options.tsconfig } : {},
1080
560
  resolve: resolveOptions,
1081
561
  // @ts-ignore
1082
562
  define: transformDefine,
@@ -1086,8 +566,7 @@ async function bundleFile(fileName, options) {
1086
566
  plugins: [
1087
567
  createExternalizeDepsPlugin({
1088
568
  entryFile: fileName,
1089
- isESM,
1090
- moduleSyncEnabled
569
+ isESM
1091
570
  }),
1092
571
  createFileScopeVariablesPlugin({
1093
572
  dirnameVarName,
@@ -1104,11 +583,12 @@ async function bundleFile(fileName, options) {
1104
583
  throw new Error("Failed to initialize bundler");
1105
584
  }
1106
585
  const rolldownOutputOptions = options?.rolldownOptions?.output || {};
586
+ const { codeSplitting: _codeSplitting, ...normalizedOutputOptions } = rolldownOutputOptions;
1107
587
  const result = await bundle.generate({
1108
- ...rolldownOutputOptions,
588
+ ...normalizedOutputOptions,
1109
589
  format: options.format,
1110
- sourcemap: false,
1111
- inlineDynamicImports: true
590
+ sourcemap: resolveSourcemapOutput(normalizedOutputOptions.sourcemap, options.sourcemap),
591
+ codeSplitting: false
1112
592
  });
1113
593
  await bundle.close();
1114
594
  const entryChunk = result.output.find(
@@ -1125,6 +605,15 @@ async function bundleFile(fileName, options) {
1125
605
  dependencies: [...allModules]
1126
606
  };
1127
607
  }
608
+ function resolveSourcemapOutput(outputSourcemap, requested) {
609
+ if (outputSourcemap !== void 0) {
610
+ return outputSourcemap;
611
+ }
612
+ if (requested === true) {
613
+ return "inline";
614
+ }
615
+ return requested ?? false;
616
+ }
1128
617
  function createFileScopeVariablesPlugin({
1129
618
  dirnameVarName,
1130
619
  filenameVarName,
@@ -1135,7 +624,7 @@ function createFileScopeVariablesPlugin({
1135
624
  transform: {
1136
625
  filter: { id: /\.[cm]?[jt]s$/ },
1137
626
  async handler(code, id) {
1138
- const injectValues = `const ${dirnameVarName} = ${JSON.stringify(path6.dirname(id))};const ${filenameVarName} = ${JSON.stringify(id)};const ${importMetaUrlVarName} = ${JSON.stringify(
627
+ const injectValues = `const ${dirnameVarName} = ${JSON.stringify(path4.dirname(id))};const ${filenameVarName} = ${JSON.stringify(id)};const ${importMetaUrlVarName} = ${JSON.stringify(
1139
628
  pathToFileURL2(id).href
1140
629
  )};`;
1141
630
  return { code: injectValues + code, map: null };
@@ -1144,19 +633,13 @@ function createFileScopeVariablesPlugin({
1144
633
  };
1145
634
  }
1146
635
 
1147
- // src/loader.ts
1148
- import fs6 from "fs";
1149
- import { createRequire as createRequire5 } from "module";
1150
- import path9 from "path";
1151
- import { promisify } from "util";
1152
-
1153
636
  // src/cache.ts
1154
637
  import crypto from "crypto";
1155
- import fs5 from "fs";
638
+ import fs4 from "fs";
1156
639
  import fsp from "fs/promises";
1157
640
  import { createRequire as createRequire4 } from "module";
1158
641
  import os from "os";
1159
- import path7 from "path";
642
+ import path5 from "path";
1160
643
  import process4 from "process";
1161
644
  import { pathToFileURL as pathToFileURL3 } from "url";
1162
645
  var _require = createRequire4(import.meta.url);
@@ -1195,7 +678,7 @@ function resolveCacheOptions(fileName, options) {
1195
678
  const hash = crypto.createHash("sha1");
1196
679
  hash.update(
1197
680
  JSON.stringify({
1198
- entry: path7.resolve(fileName),
681
+ entry: path5.resolve(fileName),
1199
682
  mtimeMs: stat.mtimeMs,
1200
683
  size: stat.size,
1201
684
  format: options.format,
@@ -1210,22 +693,22 @@ function resolveCacheOptions(fileName, options) {
1210
693
  key: hash.digest("hex"),
1211
694
  dir,
1212
695
  reset,
1213
- entryPath: path7.resolve(fileName),
696
+ entryPath: path5.resolve(fileName),
1214
697
  memory,
1215
698
  onEvent
1216
699
  };
1217
700
  }
1218
701
  function resolveDefaultCacheDir(fileName) {
1219
702
  if (typeof process4.versions.deno !== "string") {
1220
- const nearest = findNearestNodeModules(path7.dirname(fileName));
703
+ const nearest = findNearestNodeModules(path5.dirname(fileName));
1221
704
  if (nearest) {
1222
- return path7.resolve(nearest, ".rolldown-require-cache");
705
+ return path5.resolve(nearest, ".rolldown-require-cache");
1223
706
  }
1224
707
  }
1225
- return path7.join(os.tmpdir(), "rolldown-require-cache");
708
+ return path5.join(os.tmpdir(), "rolldown-require-cache");
1226
709
  }
1227
710
  async function maybeReadCache(cache, options) {
1228
- const metaPath = path7.join(cache.dir, `${cache.key}.meta.json`);
711
+ const metaPath = path5.join(cache.dir, `${cache.key}.meta.json`);
1229
712
  const mem = cache.memory ? memoryCache.get(cache.key) : void 0;
1230
713
  if (mem?.meta) {
1231
714
  const valid2 = validateMeta(mem.meta, options);
@@ -1269,11 +752,11 @@ async function importCachedCode(cached, options) {
1269
752
  async function storeCacheOutput(cache, code, options, dependencies) {
1270
753
  await fsp.mkdir(cache.dir, { recursive: true });
1271
754
  const ext = options.format === "cjs" ? "cjs" : "mjs";
1272
- const codePath = path7.join(cache.dir, `${cache.key}.code.${ext}`);
755
+ const codePath = path5.join(cache.dir, `${cache.key}.code.${ext}`);
1273
756
  if (cache.reset) {
1274
757
  await Promise.allSettled([
1275
758
  fsp.rm(codePath, { force: true }),
1276
- fsp.rm(path7.join(cache.dir, `${cache.key}.meta.json`), { force: true })
759
+ fsp.rm(path5.join(cache.dir, `${cache.key}.meta.json`), { force: true })
1277
760
  ]);
1278
761
  }
1279
762
  await fsp.writeFile(codePath, code);
@@ -1295,7 +778,7 @@ async function storeCacheOutput(cache, code, options, dependencies) {
1295
778
  async function writeCacheMeta(cache, meta) {
1296
779
  await fsp.mkdir(cache.dir, { recursive: true });
1297
780
  await fsp.writeFile(
1298
- path7.join(cache.dir, `${cache.key}.meta.json`),
781
+ path5.join(cache.dir, `${cache.key}.meta.json`),
1299
782
  JSON.stringify(meta)
1300
783
  );
1301
784
  if (cache.memory) {
@@ -1313,7 +796,7 @@ function collectFileStats(files) {
1313
796
  const stat = tryStatSync(file);
1314
797
  if (stat?.isFile()) {
1315
798
  stats.push({
1316
- path: path7.resolve(file),
799
+ path: path5.resolve(file),
1317
800
  mtimeMs: stat.mtimeMs,
1318
801
  size: stat.size
1319
802
  });
@@ -1339,7 +822,7 @@ function validateMeta(meta, options) {
1339
822
  if (meta.format !== options.format) {
1340
823
  return "format-mismatch";
1341
824
  }
1342
- if (!meta.codePath || !fs5.existsSync(meta.codePath)) {
825
+ if (!meta.codePath || !fs4.existsSync(meta.codePath)) {
1343
826
  return "missing-code";
1344
827
  }
1345
828
  for (const file of meta.files ?? []) {
@@ -1364,11 +847,27 @@ function hashRolldownOptions(options) {
1364
847
  ).digest("hex");
1365
848
  }
1366
849
 
850
+ // src/config.ts
851
+ var configDefaults = Object.freeze({
852
+ resolve: {
853
+ extensions: [".mjs", ".js", ".mts", ".ts", ".jsx", ".tsx", ".json"]
854
+ }
855
+ });
856
+ var defaultGetOutputFile = (filepath, _format) => {
857
+ return filepath;
858
+ };
859
+
860
+ // src/loader.ts
861
+ import fs5 from "fs";
862
+ import { createRequire as createRequire5 } from "module";
863
+ import path7 from "path";
864
+ import { promisify } from "util";
865
+
1367
866
  // src/temp-output.ts
1368
867
  import { Buffer as Buffer2 } from "buffer";
1369
868
  import fsp2 from "fs/promises";
1370
869
  import os2 from "os";
1371
- import path8 from "path";
870
+ import path6 from "path";
1372
871
  import process5 from "process";
1373
872
  import { pathToFileURL as pathToFileURL4 } from "url";
1374
873
  function sanitizeFilename(name) {
@@ -1376,22 +875,22 @@ function sanitizeFilename(name) {
1376
875
  }
1377
876
  async function resolveTempOutputFile(sourceFile, code, options) {
1378
877
  const getOutputFile = options.getOutputFile || defaultGetOutputFile;
1379
- const filenameHint = sanitizeFilename(path8.basename(sourceFile));
878
+ const filenameHint = sanitizeFilename(path6.basename(sourceFile));
1380
879
  const hash = `timestamp-${Date.now()}-${Math.random().toString(16).slice(2)}`;
1381
880
  const extension = options.format === "cjs" ? "cjs" : "mjs";
1382
881
  const fileName = `${filenameHint}.${hash}.${extension}`;
1383
882
  const candidates = [];
1384
883
  if (typeof process5.versions.deno !== "string") {
1385
- const nearest = findNearestNodeModules(path8.dirname(sourceFile));
884
+ const nearest = findNearestNodeModules(path6.dirname(sourceFile));
1386
885
  if (nearest) {
1387
- candidates.push(path8.resolve(nearest, ".rolldown-require"));
886
+ candidates.push(path6.resolve(nearest, ".rolldown-require"));
1388
887
  }
1389
888
  }
1390
- candidates.push(path8.join(os2.tmpdir(), "rolldown-require"));
889
+ candidates.push(path6.join(os2.tmpdir(), "rolldown-require"));
1391
890
  for (const base of candidates) {
1392
- const target = getOutputFile(path8.join(base, fileName), options.format);
891
+ const target = getOutputFile(path6.join(base, fileName), options.format);
1393
892
  try {
1394
- await fsp2.mkdir(path8.dirname(target), { recursive: true });
893
+ await fsp2.mkdir(path6.dirname(target), { recursive: true });
1395
894
  await fsp2.writeFile(target, code);
1396
895
  const cleanup = async () => {
1397
896
  if (options.preserveTemporaryFile) {
@@ -1422,7 +921,7 @@ async function resolveTempOutputFile(sourceFile, code, options) {
1422
921
 
1423
922
  // src/loader.ts
1424
923
  var _require2 = createRequire5(import.meta.url);
1425
- var promisifiedRealpath = promisify(fs6.realpath);
924
+ var promisifiedRealpath = promisify(fs5.realpath);
1426
925
  async function loadFromBundledFile(fileName, bundledCode, options, dependencies) {
1427
926
  const cacheConfig = resolveCacheOptions(fileName, options);
1428
927
  if (cacheConfig.enabled) {
@@ -1456,7 +955,7 @@ async function loadFromBundledFile(fileName, bundledCode, options, dependencies)
1456
955
  }
1457
956
  }
1458
957
  } else {
1459
- const extension = path9.extname(fileName);
958
+ const extension = path7.extname(fileName);
1460
959
  const realFileName = await promisifiedRealpath(fileName);
1461
960
  const loaderExt = extension in _require2.extensions ? extension : ".js";
1462
961
  const defaultLoader = _require2.extensions[loaderExt];
@@ -1496,15 +995,15 @@ async function loadFromBundledFile(fileName, bundledCode, options, dependencies)
1496
995
  }
1497
996
 
1498
997
  // src/options.ts
1499
- import path10 from "path";
998
+ import path8 from "path";
1500
999
  import process6 from "process";
1501
1000
  import { getTsconfig } from "get-tsconfig";
1502
1001
  function resolveEntryFilepath(options) {
1503
- if (path10.isAbsolute(options.filepath)) {
1002
+ if (path8.isAbsolute(options.filepath)) {
1504
1003
  return options.filepath;
1505
1004
  }
1506
- const cwd = options.cwd ? path10.resolve(options.cwd) : process6.cwd();
1507
- return path10.resolve(cwd, options.filepath);
1005
+ const cwd = options.cwd ? path8.resolve(options.cwd) : process6.cwd();
1006
+ return path8.resolve(cwd, options.filepath);
1508
1007
  }
1509
1008
  function detectModuleType(resolvedPath) {
1510
1009
  return typeof process6.versions.deno === "string" || isFilePathESM(resolvedPath);
@@ -1515,13 +1014,15 @@ function createInternalOptions(userOptions, isESM) {
1515
1014
  cwd: _cwd,
1516
1015
  ...rest
1517
1016
  } = userOptions;
1518
- const tsconfig = resolveTsconfigPath(userOptions);
1017
+ const tsconfig = userOptions.tsconfig === false ? false : resolveTsconfigPath(userOptions);
1519
1018
  const format = userOptions.format ?? (isESM ? "esm" : "cjs");
1019
+ const sourcemap = resolveSourcemapOption(userOptions);
1520
1020
  return {
1521
1021
  ...rest,
1522
1022
  isESM,
1523
1023
  format,
1524
- tsconfig
1024
+ tsconfig,
1025
+ sourcemap
1525
1026
  };
1526
1027
  }
1527
1028
  function resolveTsconfigPath(options) {
@@ -1533,12 +1034,46 @@ function resolveTsconfigPath(options) {
1533
1034
  }
1534
1035
  return getTsconfig(options.cwd, "tsconfig.json")?.path ?? void 0;
1535
1036
  }
1037
+ function resolveSourcemapOption(options) {
1038
+ if (options.sourcemap !== void 0) {
1039
+ return options.sourcemap;
1040
+ }
1041
+ if (shouldEnableSourcemapFromEnv()) {
1042
+ return "inline";
1043
+ }
1044
+ return void 0;
1045
+ }
1046
+ function shouldEnableSourcemapFromEnv() {
1047
+ const nodeOptions = process6.env.NODE_OPTIONS ?? "";
1048
+ if (nodeOptions.includes("--inspect")) {
1049
+ return true;
1050
+ }
1051
+ if (process6.env.VSCODE_INSPECTOR_OPTIONS) {
1052
+ return true;
1053
+ }
1054
+ if (process6.env.DEBUG) {
1055
+ return true;
1056
+ }
1057
+ return false;
1058
+ }
1536
1059
 
1537
1060
  // src/index.ts
1538
1061
  async function bundleRequire(options) {
1539
1062
  const resolvedPath = resolveEntryFilepath(options);
1540
1063
  const isESM = detectModuleType(resolvedPath);
1541
1064
  const internalOptions = createInternalOptions(options, isESM);
1065
+ const cacheConfig = resolveCacheOptions(resolvedPath, internalOptions);
1066
+ if (cacheConfig.enabled) {
1067
+ const cached = await maybeReadCache(cacheConfig, internalOptions);
1068
+ if (cached) {
1069
+ const mod2 = await importCachedCode(cached, internalOptions);
1070
+ if (cacheConfig.memory && cached.meta) {
1071
+ writeMemoryCache(cacheConfig, mod2, cached.meta);
1072
+ }
1073
+ const dependencies = cached.meta?.files?.map((file) => file.path).filter((file) => file !== cacheConfig.entryPath) ?? [];
1074
+ return { mod: mod2, dependencies };
1075
+ }
1076
+ }
1542
1077
  const bundled = await bundleFile(
1543
1078
  resolvedPath,
1544
1079
  internalOptions