rolldown-require 1.0.3 → 1.0.5

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/README.md CHANGED
@@ -15,7 +15,6 @@ Previously, [vite](https://vitejs.dev/) introduced the [bundle-require](https://
15
15
  ## How it works
16
16
 
17
17
  - Bundles your file using `rolldown`, excluding `node_modules` (since bundling those can cause problems)
18
-
19
18
  - `__filename`, `__dirname`, and `import.meta.url` are replaced with the source file’s value rather than the temporary output file’s value.
20
19
 
21
20
  - Outputs the file in `esm` format if possible (for `.ts` and `.js` inputs).
@@ -24,7 +23,7 @@ Previously, [vite](https://vitejs.dev/) introduced the [bundle-require](https://
24
23
 
25
24
  ## Install
26
25
 
27
- ```bash
26
+ ```sh
28
27
  npm i rolldown-require rolldown
29
28
  ```
30
29
 
package/dist/index.cjs CHANGED
@@ -5,7 +5,7 @@
5
5
  throw Error('Dynamic require of "' + x + '" is not supported');
6
6
  });
7
7
 
8
- // ../../node_modules/.pnpm/tsup@8.5.0_@swc+core@1.13.4_jiti@2.5.1_postcss@8.5.6_tsx@4.20.5_typescript@5.9.2_yaml@2.8.1/node_modules/tsup/assets/cjs_shims.js
8
+ // ../../node_modules/.pnpm/tsup@8.5.0_@swc+core@1.14.0_jiti@2.6.1_postcss@8.5.6_tsx@4.20.6_typescript@5.9.3_yaml@2.8.1/node_modules/tsup/assets/cjs_shims.js
9
9
  var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href;
10
10
  var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
11
11
 
@@ -28,8 +28,6 @@ var _rolldown = require('rolldown');
28
28
 
29
29
  // src/utils.ts
30
30
  var _child_process = require('child_process');
31
- var _crypto = require('crypto'); var _crypto2 = _interopRequireDefault(_crypto);
32
-
33
31
 
34
32
 
35
33
 
@@ -60,12 +58,8 @@ function splitFileAndPostfix(path6) {
60
58
  const file = cleanUrl(path6);
61
59
  return { file, postfix: path6.slice(file.length) };
62
60
  }
63
- var AsyncFunction = async function() {
64
- }.constructor;
65
61
 
66
62
  // src/utils.ts
67
-
68
- var _filter = require('rolldown/filter');
69
63
  var createFilter = _pluginutils.createFilter;
70
64
  var NODE_BUILTIN_NAMESPACE = "node:";
71
65
  var NPM_BUILTIN_NAMESPACE = "npm:";
@@ -113,16 +107,6 @@ function isOptimizable(id, optimizeDeps) {
113
107
  }
114
108
  var bareImportRE = /^(?![a-z]:)[\w@](?!.*:\/\/)/i;
115
109
  var deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\//;
116
- var _require = _module.createRequire.call(void 0, importMetaUrl);
117
- var _dirname = _path2.default.dirname(_url.fileURLToPath.call(void 0, importMetaUrl));
118
- var urlCanParse = _nullishCoalesce(_url.URL.canParse, () => ( ((path6, base) => {
119
- try {
120
- new (0, _url.URL)(path6, base);
121
- return true;
122
- } catch (e2) {
123
- return false;
124
- }
125
- })));
126
110
  function normalizePath(id) {
127
111
  return _path2.default.posix.normalize(isWindows ? slash(id) : id);
128
112
  }
@@ -140,7 +124,7 @@ function isObject(value) {
140
124
  function tryStatSync(file) {
141
125
  try {
142
126
  return _fs2.default.statSync(file, { throwIfNoEntry: false });
143
- } catch (e3) {
127
+ } catch (e2) {
144
128
  }
145
129
  }
146
130
  function isFilePathESM(filePath, packageCache) {
@@ -152,12 +136,15 @@ function isFilePathESM(filePath, packageCache) {
152
136
  try {
153
137
  const pkg = findNearestPackageData(_path2.default.dirname(filePath), packageCache);
154
138
  return _optionalChain([pkg, 'optionalAccess', _3 => _3.data, 'access', _4 => _4.type]) === "module";
155
- } catch (e4) {
139
+ } catch (e3) {
156
140
  return false;
157
141
  }
158
142
  }
159
143
  }
160
- var safeRealpathSync = isWindows ? windowsSafeRealPathSync : _fs2.default.realpathSync.native;
144
+ var currentSafeRealpathSync = isWindows ? windowsSafeRealPathSync : _fs2.default.realpathSync.native;
145
+ function safeRealpathSync(filePath) {
146
+ return currentSafeRealpathSync(filePath);
147
+ }
161
148
  var windowsNetworkMap = /* @__PURE__ */ new Map();
162
149
  function windowsMappedRealpathSync(path6) {
163
150
  const realPath = _fs2.default.realpathSync.native(path6);
@@ -182,14 +169,14 @@ function windowsSafeRealPathSync(path6) {
182
169
  function optimizeSafeRealPathSync() {
183
170
  const nodeVersion = _process2.default.versions.node.split(".").map(Number);
184
171
  if (nodeVersion[0] < 18 || nodeVersion[0] === 18 && nodeVersion[1] < 10) {
185
- safeRealpathSync = _fs2.default.realpathSync;
172
+ currentSafeRealpathSync = _fs2.default.realpathSync;
186
173
  return;
187
174
  }
188
175
  try {
189
176
  _fs2.default.realpathSync.native(_path2.default.resolve("./"));
190
177
  } catch (error) {
191
178
  if (error.message.includes("EISDIR: illegal operation on a directory")) {
192
- safeRealpathSync = _fs2.default.realpathSync;
179
+ currentSafeRealpathSync = _fs2.default.realpathSync;
193
180
  return;
194
181
  }
195
182
  }
@@ -204,14 +191,9 @@ function optimizeSafeRealPathSync() {
204
191
  windowsNetworkMap.set(m[2], m[1]);
205
192
  }
206
193
  }
207
- if (windowsNetworkMap.size === 0) {
208
- safeRealpathSync = _fs2.default.realpathSync.native;
209
- } else {
210
- safeRealpathSync = windowsMappedRealpathSync;
211
- }
194
+ currentSafeRealpathSync = windowsNetworkMap.size === 0 ? _fs2.default.realpathSync.native : windowsMappedRealpathSync;
212
195
  });
213
196
  }
214
- var hash = _nullishCoalesce(_crypto2.default.hash, () => ( ((algorithm, data, outputEncoding) => _crypto2.default.createHash(algorithm).update(data).digest(outputEncoding))));
215
197
  function stripBomTag(content) {
216
198
  if (content.charCodeAt(0) === 65279) {
217
199
  return content.slice(1);
@@ -230,7 +212,7 @@ function getNpmPackageName(importPath) {
230
212
  }
231
213
  }
232
214
  var dynamicImport = async (id, { format }) => {
233
- const fn = format === "esm" ? (file) => Promise.resolve().then(() => _interopRequireWildcard(require(file))) : false ? _module.createRequire.call(void 0, importMetaUrl) : __require;
215
+ const fn = format === "esm" ? (file) => Promise.resolve().then(() => _interopRequireWildcard(require(file))) : false ? createRequire(importMetaUrl) : __require;
234
216
  return fn(id);
235
217
  };
236
218
 
@@ -239,7 +221,7 @@ var pnp;
239
221
  if (_process2.default.versions.pnp) {
240
222
  try {
241
223
  pnp = _module.createRequire.call(void 0, importMetaUrl)("pnpapi");
242
- } catch (e5) {
224
+ } catch (e4) {
243
225
  }
244
226
  }
245
227
  function resolvePackageData(pkgName, basedir, preserveSymlinks = false, packageCache) {
@@ -258,7 +240,7 @@ function resolvePackageData(pkgName, basedir, preserveSymlinks = false, packageC
258
240
  const pkgData = loadPackageData(_path2.default.join(pkg, "package.json"));
259
241
  _optionalChain([packageCache, 'optionalAccess', _7 => _7.set, 'call', _8 => _8(cacheKey, pkgData)]);
260
242
  return pkgData;
261
- } catch (e6) {
243
+ } catch (e5) {
262
244
  return null;
263
245
  }
264
246
  }
@@ -293,7 +275,7 @@ function resolvePackageData(pkgName, basedir, preserveSymlinks = false, packageC
293
275
  }
294
276
  return pkgData;
295
277
  }
296
- } catch (e7) {
278
+ } catch (e6) {
297
279
  }
298
280
  const nextBasedir = _path2.default.dirname(basedir);
299
281
  if (nextBasedir === basedir) {
@@ -320,7 +302,7 @@ function findNearestPackageData(basedir, packageCache) {
320
302
  setFnpdCache(packageCache, pkgData, basedir, originalBasedir);
321
303
  }
322
304
  return pkgData;
323
- } catch (e8) {
305
+ } catch (e7) {
324
306
  }
325
307
  }
326
308
  const nextBasedir = _path2.default.dirname(basedir);
@@ -854,144 +836,114 @@ var configDefaults = Object.freeze({
854
836
  var defaultGetOutputFile = (filepath, _format) => {
855
837
  return filepath;
856
838
  };
857
- function collectAllModules(bundle, fileName, allModules, analyzedModules = /* @__PURE__ */ new Set()) {
839
+ var cachedModuleSyncCondition;
840
+ var moduleSyncConditionPromise;
841
+ async function getModuleSyncConditionEnabled() {
842
+ if (cachedModuleSyncCondition !== void 0) {
843
+ return cachedModuleSyncCondition;
844
+ }
845
+ if (!moduleSyncConditionPromise) {
846
+ moduleSyncConditionPromise = Promise.resolve().then(() => _interopRequireWildcard(require(
847
+ // @ts-ignore
848
+ "#module-sync-enabled"
849
+ ))).then((mod) => Boolean(_optionalChain([mod, 'optionalAccess', _38 => _38.default]))).catch(() => false).then((result) => {
850
+ cachedModuleSyncCondition = result;
851
+ return result;
852
+ }).finally(() => {
853
+ moduleSyncConditionPromise = void 0;
854
+ });
855
+ }
856
+ return moduleSyncConditionPromise;
857
+ }
858
+ function collectReferencedModules(bundle, fileName, allModules, analyzedModules = /* @__PURE__ */ new Set()) {
858
859
  if (analyzedModules.has(fileName)) {
859
860
  return;
860
861
  }
861
862
  analyzedModules.add(fileName);
862
863
  const chunk = bundle[fileName];
864
+ if (!chunk) {
865
+ return;
866
+ }
863
867
  for (const mod of chunk.moduleIds) {
864
868
  allModules.add(mod);
865
869
  }
866
- for (const i of chunk.imports) {
867
- analyzedModules.add(i);
868
- collectAllModules(bundle, i, allModules, analyzedModules);
870
+ for (const imported of chunk.imports) {
871
+ collectReferencedModules(bundle, imported, allModules, analyzedModules);
869
872
  }
870
- for (const i of chunk.dynamicImports) {
871
- analyzedModules.add(i);
872
- collectAllModules(bundle, i, allModules, analyzedModules);
873
+ for (const imported of chunk.dynamicImports) {
874
+ collectReferencedModules(bundle, imported, allModules, analyzedModules);
873
875
  }
874
876
  }
875
877
  async function bundleFile(fileName, options) {
876
878
  const { isESM } = options;
877
- const isModuleSyncConditionEnabled = (await Promise.resolve().then(() => _interopRequireWildcard(require(
878
- // @ts-ignore
879
- "#module-sync-enabled"
880
- )))).default;
879
+ const moduleSyncEnabled = await getModuleSyncConditionEnabled();
881
880
  const dirnameVarName = "__vite_injected_original_dirname";
882
881
  const filenameVarName = "__vite_injected_original_filename";
883
882
  const importMetaUrlVarName = "__vite_injected_original_import_meta_url";
884
- const rolldownInputOptions = _optionalChain([options, 'optionalAccess', _38 => _38.rolldownOptions, 'optionalAccess', _39 => _39.input]) || {};
885
- const bundle = await _rolldown.rolldown.call(void 0, {
886
- ...rolldownInputOptions,
887
- input: fileName,
888
- // target: [`node${process.versions.node}`],
889
- platform: "node",
890
- resolve: {
891
- mainFields: ["main"],
892
- tsconfigFilename: options.tsconfig
893
- },
894
- define: {
895
- "__dirname": dirnameVarName,
896
- "__filename": filenameVarName,
897
- "import.meta.url": importMetaUrlVarName,
898
- "import.meta.dirname": dirnameVarName,
899
- "import.meta.filename": filenameVarName
900
- },
901
- // disable treeshake to include files that is not sideeffectful to `moduleIds`
902
- treeshake: false,
903
- plugins: [
904
- /* @__PURE__ */ (() => {
905
- const packageCache = /* @__PURE__ */ new Map();
906
- const resolveByViteResolver = (id, importer, isRequire) => {
907
- return _optionalChain([tryNodeResolve, 'call', _40 => _40(id, importer, {
908
- root: _path2.default.dirname(fileName),
909
- isBuild: true,
910
- isProduction: true,
911
- preferRelative: false,
912
- tryIndex: true,
913
- mainFields: [],
914
- conditions: [
915
- "node",
916
- ...isModuleSyncConditionEnabled ? ["module-sync"] : []
917
- ],
918
- externalConditions: [],
919
- external: [],
920
- noExternal: [],
921
- dedupe: [],
922
- extensions: configDefaults.resolve.extensions,
923
- preserveSymlinks: false,
924
- packageCache,
925
- isRequire,
926
- builtins: nodeLikeBuiltins
927
- }), 'optionalAccess', _41 => _41.id]);
928
- };
929
- return {
930
- name: "externalize-deps",
931
- resolveId: {
932
- filter: { id: /^[^.#].*/ },
933
- async handler(id, importer, { kind }) {
934
- if (!importer || _path2.default.isAbsolute(id) || isNodeBuiltin(id)) {
935
- return;
936
- }
937
- if (isNodeLikeBuiltin(id)) {
938
- return { id, external: true };
939
- }
940
- const isImport = isESM || kind === "dynamic-import";
941
- let idFsPath;
942
- try {
943
- idFsPath = resolveByViteResolver(id, importer, !isImport);
944
- } catch (e) {
945
- if (!isImport) {
946
- let canResolveWithImport = false;
947
- try {
948
- canResolveWithImport = !!resolveByViteResolver(
949
- id,
950
- importer,
951
- false
952
- );
953
- } catch (e9) {
954
- }
955
- if (canResolveWithImport) {
956
- throw new Error(
957
- `Failed to resolve ${JSON.stringify(
958
- id
959
- )}. 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.`
960
- );
961
- }
962
- }
963
- throw e;
964
- }
965
- if (!idFsPath) {
966
- return;
967
- }
968
- if (idFsPath.endsWith(".json")) {
969
- return idFsPath;
970
- }
971
- if (idFsPath && isImport) {
972
- idFsPath = _url.pathToFileURL.call(void 0, idFsPath).href;
973
- }
974
- return { id: idFsPath, external: true };
975
- }
976
- }
977
- };
978
- })(),
979
- {
980
- name: "inject-file-scope-variables",
981
- transform: {
982
- filter: { id: /\.[cm]?[jt]s$/ },
983
- async handler(code, id) {
984
- const injectValues = `const ${dirnameVarName} = ${JSON.stringify(_path2.default.dirname(id))};const ${filenameVarName} = ${JSON.stringify(id)};const ${importMetaUrlVarName} = ${JSON.stringify(
985
- _url.pathToFileURL.call(void 0, id).href
986
- )};`;
987
- return { code: injectValues + code, map: null };
988
- }
989
- }
990
- }
991
- ],
992
- external: options.external
993
- // preserveEntrySignatures: 'exports-only'
994
- });
883
+ const rolldownInputOptions = _optionalChain([options, 'optionalAccess', _39 => _39.rolldownOptions, 'optionalAccess', _40 => _40.input]) || {};
884
+ const {
885
+ transform: userTransform,
886
+ resolve: userResolve,
887
+ ...restRolldownInputOptions
888
+ } = rolldownInputOptions;
889
+ const transformDefine = {
890
+ ..._nullishCoalesce(_optionalChain([userTransform, 'optionalAccess', _41 => _41.define]), () => ( {})),
891
+ "__dirname": dirnameVarName,
892
+ "__filename": filenameVarName,
893
+ "import.meta.url": importMetaUrlVarName,
894
+ "import.meta.dirname": dirnameVarName,
895
+ "import.meta.filename": filenameVarName
896
+ };
897
+ const transformOptions = {
898
+ ..._nullishCoalesce(userTransform, () => ( {})),
899
+ define: transformDefine
900
+ };
901
+ const resolveOptions = {
902
+ ..._nullishCoalesce(userResolve, () => ( {})),
903
+ mainFields: ["main"],
904
+ tsconfigFilename: options.tsconfig
905
+ };
906
+ const originalConsoleWarn = console.warn;
907
+ console.warn = (...args) => {
908
+ const message = typeof args[0] === "string" ? args[0] : "";
909
+ if (message.includes("resolve.tsconfigFilename") || message.includes("Invalid input options") || message.includes('top-level "define" option is deprecated')) {
910
+ return;
911
+ }
912
+ originalConsoleWarn(...args);
913
+ };
914
+ let bundle;
915
+ try {
916
+ bundle = await _rolldown.rolldown.call(void 0, {
917
+ ...restRolldownInputOptions,
918
+ input: fileName,
919
+ // target: [`node${process.versions.node}`],
920
+ platform: "node",
921
+ resolve: resolveOptions,
922
+ define: transformDefine,
923
+ transform: transformOptions,
924
+ // disable treeshake to include files that is not sideeffectful to `moduleIds`
925
+ treeshake: false,
926
+ plugins: [
927
+ createExternalizeDepsPlugin({
928
+ entryFile: fileName,
929
+ isESM,
930
+ moduleSyncEnabled
931
+ }),
932
+ createFileScopeVariablesPlugin({
933
+ dirnameVarName,
934
+ filenameVarName,
935
+ importMetaUrlVarName
936
+ })
937
+ ],
938
+ external: options.external
939
+ // preserveEntrySignatures: 'exports-only'
940
+ });
941
+ } finally {
942
+ console.warn = originalConsoleWarn;
943
+ }
944
+ if (!bundle) {
945
+ throw new Error("Failed to initialize bundler");
946
+ }
995
947
  const rolldownOutputOptions = _optionalChain([options, 'optionalAccess', _42 => _42.rolldownOptions, 'optionalAccess', _43 => _43.output]) || {};
996
948
  const result = await bundle.generate({
997
949
  ...rolldownOutputOptions,
@@ -1011,14 +963,14 @@ async function bundleFile(fileName, options) {
1011
963
  result.output.flatMap((c) => c.type === "chunk" ? [[c.fileName, c]] : [])
1012
964
  );
1013
965
  const allModules = /* @__PURE__ */ new Set();
1014
- collectAllModules(bundleChunks, entryChunk.fileName, allModules);
966
+ collectReferencedModules(bundleChunks, entryChunk.fileName, allModules);
1015
967
  allModules.delete(fileName);
1016
968
  return {
1017
969
  code: entryChunk.code,
1018
970
  dependencies: [...allModules]
1019
971
  };
1020
972
  }
1021
- var _require2 = _module.createRequire.call(void 0, importMetaUrl);
973
+ var _require = _module.createRequire.call(void 0, importMetaUrl);
1022
974
  async function loadFromBundledFile(fileName, bundledCode, options) {
1023
975
  const { isESM } = options;
1024
976
  if (isESM) {
@@ -1036,11 +988,11 @@ async function loadFromBundledFile(fileName, bundledCode, options) {
1036
988
  }
1037
989
  }
1038
990
  }
1039
- const hash2 = `timestamp-${Date.now()}-${Math.random().toString(16).slice(2)}`;
991
+ const hash = `timestamp-${Date.now()}-${Math.random().toString(16).slice(2)}`;
1040
992
  const tempFileName = nodeModulesDir ? _path2.default.resolve(
1041
993
  nodeModulesDir,
1042
- `.vite-temp/${_path2.default.basename(fileName)}.${hash2}.${isESM ? "mjs" : "cjs"}`
1043
- ) : `${fileName}.${hash2}.mjs`;
994
+ `.vite-temp/${_path2.default.basename(fileName)}.${hash}.${isESM ? "mjs" : "cjs"}`
995
+ ) : `${fileName}.${hash}.mjs`;
1044
996
  const getOutputFile = options.getOutputFile || defaultGetOutputFile;
1045
997
  const outfile = getOutputFile(tempFileName, options.format);
1046
998
  await _promises2.default.writeFile(outfile, bundledCode);
@@ -1061,9 +1013,9 @@ async function loadFromBundledFile(fileName, bundledCode, options) {
1061
1013
  } else {
1062
1014
  const extension = _path2.default.extname(fileName);
1063
1015
  const realFileName = await promisifiedRealpath(fileName);
1064
- const loaderExt = extension in _require2.extensions ? extension : ".js";
1065
- const defaultLoader = _require2.extensions[loaderExt];
1066
- _require2.extensions[loaderExt] = (module, filename) => {
1016
+ const loaderExt = extension in _require.extensions ? extension : ".js";
1017
+ const defaultLoader = _require.extensions[loaderExt];
1018
+ const compileLoader = (module, filename) => {
1067
1019
  if (filename === realFileName) {
1068
1020
  ;
1069
1021
  module._compile(bundledCode, filename);
@@ -1071,29 +1023,20 @@ async function loadFromBundledFile(fileName, bundledCode, options) {
1071
1023
  defaultLoader(module, filename);
1072
1024
  }
1073
1025
  };
1074
- delete _require2.cache[_require2.resolve(fileName)];
1075
- const raw = _require2(fileName);
1076
- _require2.extensions[loaderExt] = defaultLoader;
1077
- return raw.__esModule ? raw.default : raw;
1026
+ try {
1027
+ _require.extensions[loaderExt] = compileLoader;
1028
+ delete _require.cache[_require.resolve(fileName)];
1029
+ const raw = _require(fileName);
1030
+ return raw.__esModule ? raw.default : raw;
1031
+ } finally {
1032
+ _require.extensions[loaderExt] = defaultLoader;
1033
+ }
1078
1034
  }
1079
1035
  }
1080
1036
  async function bundleRequire(options) {
1081
- const resolvedPath = _path2.default.isAbsolute(options.filepath) ? options.filepath : _path2.default.resolve(options.cwd || _process2.default.cwd(), options.filepath);
1082
- const isESM = typeof _process2.default.versions.deno === "string" || isFilePathESM(resolvedPath);
1083
- if (options.tsconfig !== false) {
1084
- options.tsconfig = _nullishCoalesce(_nullishCoalesce(options.tsconfig, () => ( _optionalChain([_gettsconfig.getTsconfig.call(void 0, options.cwd, "tsconfig.json"), 'optionalAccess', _45 => _45.path]))), () => ( void 0));
1085
- } else {
1086
- options.tsconfig = void 0;
1087
- }
1088
- if (!options.format) {
1089
- options.format = isESM ? "esm" : "cjs";
1090
- }
1091
- const internalOptions = {
1092
- ...options,
1093
- isESM,
1094
- format: options.format,
1095
- tsconfig: options.tsconfig
1096
- };
1037
+ const resolvedPath = resolveEntryFilepath(options);
1038
+ const isESM = detectModuleType(resolvedPath);
1039
+ const internalOptions = createInternalOptions(options, isESM);
1097
1040
  const bundled = await bundleFile(
1098
1041
  resolvedPath,
1099
1042
  internalOptions
@@ -1108,6 +1051,137 @@ async function bundleRequire(options) {
1108
1051
  dependencies: bundled.dependencies
1109
1052
  };
1110
1053
  }
1054
+ function createExternalizeDepsPlugin({
1055
+ entryFile,
1056
+ isESM,
1057
+ moduleSyncEnabled
1058
+ }) {
1059
+ const packageCache = /* @__PURE__ */ new Map();
1060
+ const resolveByViteResolver = (id, importer, isRequire) => {
1061
+ return _optionalChain([tryNodeResolve, 'call', _45 => _45(id, importer, {
1062
+ root: _path2.default.dirname(entryFile),
1063
+ isBuild: true,
1064
+ isProduction: true,
1065
+ preferRelative: false,
1066
+ tryIndex: true,
1067
+ mainFields: [],
1068
+ conditions: [
1069
+ "node",
1070
+ ...moduleSyncEnabled ? ["module-sync"] : []
1071
+ ],
1072
+ externalConditions: [],
1073
+ external: [],
1074
+ noExternal: [],
1075
+ dedupe: [],
1076
+ extensions: configDefaults.resolve.extensions,
1077
+ preserveSymlinks: false,
1078
+ packageCache,
1079
+ isRequire,
1080
+ builtins: nodeLikeBuiltins
1081
+ }), 'optionalAccess', _46 => _46.id]);
1082
+ };
1083
+ return {
1084
+ name: "externalize-deps",
1085
+ resolveId: {
1086
+ filter: { id: /^[^.#].*/ },
1087
+ async handler(id, importer, { kind }) {
1088
+ if (!importer || _path2.default.isAbsolute(id) || isNodeBuiltin(id)) {
1089
+ return;
1090
+ }
1091
+ if (isNodeLikeBuiltin(id)) {
1092
+ return { id, external: true };
1093
+ }
1094
+ const isImport = isESM || kind === "dynamic-import";
1095
+ let idFsPath;
1096
+ try {
1097
+ idFsPath = resolveByViteResolver(id, importer, !isImport);
1098
+ } catch (e) {
1099
+ if (!isImport) {
1100
+ let canResolveWithImport = false;
1101
+ try {
1102
+ canResolveWithImport = !!resolveByViteResolver(
1103
+ id,
1104
+ importer,
1105
+ false
1106
+ );
1107
+ } catch (e8) {
1108
+ }
1109
+ if (canResolveWithImport) {
1110
+ throw new Error(
1111
+ `Failed to resolve ${JSON.stringify(
1112
+ id
1113
+ )}. 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.`
1114
+ );
1115
+ }
1116
+ }
1117
+ throw e;
1118
+ }
1119
+ if (!idFsPath) {
1120
+ return;
1121
+ }
1122
+ if (idFsPath.endsWith(".json")) {
1123
+ return idFsPath;
1124
+ }
1125
+ if (idFsPath && isImport) {
1126
+ idFsPath = _url.pathToFileURL.call(void 0, idFsPath).href;
1127
+ }
1128
+ return { id: idFsPath, external: true };
1129
+ }
1130
+ }
1131
+ };
1132
+ }
1133
+ function createFileScopeVariablesPlugin({
1134
+ dirnameVarName,
1135
+ filenameVarName,
1136
+ importMetaUrlVarName
1137
+ }) {
1138
+ return {
1139
+ name: "inject-file-scope-variables",
1140
+ transform: {
1141
+ filter: { id: /\.[cm]?[jt]s$/ },
1142
+ async handler(code, id) {
1143
+ const injectValues = `const ${dirnameVarName} = ${JSON.stringify(_path2.default.dirname(id))};const ${filenameVarName} = ${JSON.stringify(id)};const ${importMetaUrlVarName} = ${JSON.stringify(
1144
+ _url.pathToFileURL.call(void 0, id).href
1145
+ )};`;
1146
+ return { code: injectValues + code, map: null };
1147
+ }
1148
+ }
1149
+ };
1150
+ }
1151
+ function resolveEntryFilepath(options) {
1152
+ if (_path2.default.isAbsolute(options.filepath)) {
1153
+ return options.filepath;
1154
+ }
1155
+ const cwd = options.cwd ? _path2.default.resolve(options.cwd) : _process2.default.cwd();
1156
+ return _path2.default.resolve(cwd, options.filepath);
1157
+ }
1158
+ function detectModuleType(resolvedPath) {
1159
+ return typeof _process2.default.versions.deno === "string" || isFilePathESM(resolvedPath);
1160
+ }
1161
+ function createInternalOptions(userOptions, isESM) {
1162
+ const {
1163
+ filepath: _filepath,
1164
+ cwd: _cwd,
1165
+ ...rest
1166
+ } = userOptions;
1167
+ const tsconfig = resolveTsconfigPath(userOptions);
1168
+ const format = _nullishCoalesce(userOptions.format, () => ( (isESM ? "esm" : "cjs")));
1169
+ return {
1170
+ ...rest,
1171
+ isESM,
1172
+ format,
1173
+ tsconfig
1174
+ };
1175
+ }
1176
+ function resolveTsconfigPath(options) {
1177
+ if (options.tsconfig === false) {
1178
+ return void 0;
1179
+ }
1180
+ if (typeof options.tsconfig === "string") {
1181
+ return options.tsconfig;
1182
+ }
1183
+ return _nullishCoalesce(_optionalChain([_gettsconfig.getTsconfig.call(void 0, options.cwd, "tsconfig.json"), 'optionalAccess', _47 => _47.path]), () => ( void 0));
1184
+ }
1111
1185
 
1112
1186
 
1113
1187
 
package/dist/index.mjs CHANGED
@@ -17,12 +17,10 @@ import process3 from "process";
17
17
 
18
18
  // src/utils.ts
19
19
  import { exec } from "child_process";
20
- import crypto from "crypto";
21
20
  import fs from "fs";
22
21
  import { builtinModules, createRequire } from "module";
23
22
  import path from "path";
24
23
  import process2 from "process";
25
- import { fileURLToPath, URL as URL2 } from "url";
26
24
  import { createFilter as _createFilter } from "@rollup/pluginutils";
27
25
 
28
26
  // src/constants.ts
@@ -49,12 +47,8 @@ function splitFileAndPostfix(path6) {
49
47
  const file = cleanUrl(path6);
50
48
  return { file, postfix: path6.slice(file.length) };
51
49
  }
52
- var AsyncFunction = async function() {
53
- }.constructor;
54
50
 
55
51
  // src/utils.ts
56
- import { VERSION } from "rolldown";
57
- import { withFilter } from "rolldown/filter";
58
52
  var createFilter = _createFilter;
59
53
  var NODE_BUILTIN_NAMESPACE = "node:";
60
54
  var NPM_BUILTIN_NAMESPACE = "npm:";
@@ -102,16 +96,6 @@ function isOptimizable(id, optimizeDeps) {
102
96
  }
103
97
  var bareImportRE = /^(?![a-z]:)[\w@](?!.*:\/\/)/i;
104
98
  var deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\//;
105
- var _require = createRequire(import.meta.url);
106
- var _dirname = path.dirname(fileURLToPath(import.meta.url));
107
- var urlCanParse = URL2.canParse ?? ((path6, base) => {
108
- try {
109
- new URL2(path6, base);
110
- return true;
111
- } catch {
112
- return false;
113
- }
114
- });
115
99
  function normalizePath(id) {
116
100
  return path.posix.normalize(isWindows ? slash(id) : id);
117
101
  }
@@ -146,7 +130,10 @@ function isFilePathESM(filePath, packageCache) {
146
130
  }
147
131
  }
148
132
  }
149
- var safeRealpathSync = isWindows ? windowsSafeRealPathSync : fs.realpathSync.native;
133
+ var currentSafeRealpathSync = isWindows ? windowsSafeRealPathSync : fs.realpathSync.native;
134
+ function safeRealpathSync(filePath) {
135
+ return currentSafeRealpathSync(filePath);
136
+ }
150
137
  var windowsNetworkMap = /* @__PURE__ */ new Map();
151
138
  function windowsMappedRealpathSync(path6) {
152
139
  const realPath = fs.realpathSync.native(path6);
@@ -171,14 +158,14 @@ function windowsSafeRealPathSync(path6) {
171
158
  function optimizeSafeRealPathSync() {
172
159
  const nodeVersion = process2.versions.node.split(".").map(Number);
173
160
  if (nodeVersion[0] < 18 || nodeVersion[0] === 18 && nodeVersion[1] < 10) {
174
- safeRealpathSync = fs.realpathSync;
161
+ currentSafeRealpathSync = fs.realpathSync;
175
162
  return;
176
163
  }
177
164
  try {
178
165
  fs.realpathSync.native(path.resolve("./"));
179
166
  } catch (error) {
180
167
  if (error.message.includes("EISDIR: illegal operation on a directory")) {
181
- safeRealpathSync = fs.realpathSync;
168
+ currentSafeRealpathSync = fs.realpathSync;
182
169
  return;
183
170
  }
184
171
  }
@@ -193,14 +180,9 @@ function optimizeSafeRealPathSync() {
193
180
  windowsNetworkMap.set(m[2], m[1]);
194
181
  }
195
182
  }
196
- if (windowsNetworkMap.size === 0) {
197
- safeRealpathSync = fs.realpathSync.native;
198
- } else {
199
- safeRealpathSync = windowsMappedRealpathSync;
200
- }
183
+ currentSafeRealpathSync = windowsNetworkMap.size === 0 ? fs.realpathSync.native : windowsMappedRealpathSync;
201
184
  });
202
185
  }
203
- var hash = crypto.hash ?? ((algorithm, data, outputEncoding) => crypto.createHash(algorithm).update(data).digest(outputEncoding));
204
186
  function stripBomTag(content) {
205
187
  if (content.charCodeAt(0) === 65279) {
206
188
  return content.slice(1);
@@ -843,144 +825,114 @@ var configDefaults = Object.freeze({
843
825
  var defaultGetOutputFile = (filepath, _format) => {
844
826
  return filepath;
845
827
  };
846
- function collectAllModules(bundle, fileName, allModules, analyzedModules = /* @__PURE__ */ new Set()) {
828
+ var cachedModuleSyncCondition;
829
+ var moduleSyncConditionPromise;
830
+ async function getModuleSyncConditionEnabled() {
831
+ if (cachedModuleSyncCondition !== void 0) {
832
+ return cachedModuleSyncCondition;
833
+ }
834
+ if (!moduleSyncConditionPromise) {
835
+ moduleSyncConditionPromise = import(
836
+ // @ts-ignore
837
+ "#module-sync-enabled"
838
+ ).then((mod) => Boolean(mod?.default)).catch(() => false).then((result) => {
839
+ cachedModuleSyncCondition = result;
840
+ return result;
841
+ }).finally(() => {
842
+ moduleSyncConditionPromise = void 0;
843
+ });
844
+ }
845
+ return moduleSyncConditionPromise;
846
+ }
847
+ function collectReferencedModules(bundle, fileName, allModules, analyzedModules = /* @__PURE__ */ new Set()) {
847
848
  if (analyzedModules.has(fileName)) {
848
849
  return;
849
850
  }
850
851
  analyzedModules.add(fileName);
851
852
  const chunk = bundle[fileName];
853
+ if (!chunk) {
854
+ return;
855
+ }
852
856
  for (const mod of chunk.moduleIds) {
853
857
  allModules.add(mod);
854
858
  }
855
- for (const i of chunk.imports) {
856
- analyzedModules.add(i);
857
- collectAllModules(bundle, i, allModules, analyzedModules);
859
+ for (const imported of chunk.imports) {
860
+ collectReferencedModules(bundle, imported, allModules, analyzedModules);
858
861
  }
859
- for (const i of chunk.dynamicImports) {
860
- analyzedModules.add(i);
861
- collectAllModules(bundle, i, allModules, analyzedModules);
862
+ for (const imported of chunk.dynamicImports) {
863
+ collectReferencedModules(bundle, imported, allModules, analyzedModules);
862
864
  }
863
865
  }
864
866
  async function bundleFile(fileName, options) {
865
867
  const { isESM } = options;
866
- const isModuleSyncConditionEnabled = (await import(
867
- // @ts-ignore
868
- "#module-sync-enabled"
869
- )).default;
868
+ const moduleSyncEnabled = await getModuleSyncConditionEnabled();
870
869
  const dirnameVarName = "__vite_injected_original_dirname";
871
870
  const filenameVarName = "__vite_injected_original_filename";
872
871
  const importMetaUrlVarName = "__vite_injected_original_import_meta_url";
873
872
  const rolldownInputOptions = options?.rolldownOptions?.input || {};
874
- const bundle = await rolldown({
875
- ...rolldownInputOptions,
876
- input: fileName,
877
- // target: [`node${process.versions.node}`],
878
- platform: "node",
879
- resolve: {
880
- mainFields: ["main"],
881
- tsconfigFilename: options.tsconfig
882
- },
883
- define: {
884
- "__dirname": dirnameVarName,
885
- "__filename": filenameVarName,
886
- "import.meta.url": importMetaUrlVarName,
887
- "import.meta.dirname": dirnameVarName,
888
- "import.meta.filename": filenameVarName
889
- },
890
- // disable treeshake to include files that is not sideeffectful to `moduleIds`
891
- treeshake: false,
892
- plugins: [
893
- /* @__PURE__ */ (() => {
894
- const packageCache = /* @__PURE__ */ new Map();
895
- const resolveByViteResolver = (id, importer, isRequire) => {
896
- return tryNodeResolve(id, importer, {
897
- root: path5.dirname(fileName),
898
- isBuild: true,
899
- isProduction: true,
900
- preferRelative: false,
901
- tryIndex: true,
902
- mainFields: [],
903
- conditions: [
904
- "node",
905
- ...isModuleSyncConditionEnabled ? ["module-sync"] : []
906
- ],
907
- externalConditions: [],
908
- external: [],
909
- noExternal: [],
910
- dedupe: [],
911
- extensions: configDefaults.resolve.extensions,
912
- preserveSymlinks: false,
913
- packageCache,
914
- isRequire,
915
- builtins: nodeLikeBuiltins
916
- })?.id;
917
- };
918
- return {
919
- name: "externalize-deps",
920
- resolveId: {
921
- filter: { id: /^[^.#].*/ },
922
- async handler(id, importer, { kind }) {
923
- if (!importer || path5.isAbsolute(id) || isNodeBuiltin(id)) {
924
- return;
925
- }
926
- if (isNodeLikeBuiltin(id)) {
927
- return { id, external: true };
928
- }
929
- const isImport = isESM || kind === "dynamic-import";
930
- let idFsPath;
931
- try {
932
- idFsPath = resolveByViteResolver(id, importer, !isImport);
933
- } catch (e) {
934
- if (!isImport) {
935
- let canResolveWithImport = false;
936
- try {
937
- canResolveWithImport = !!resolveByViteResolver(
938
- id,
939
- importer,
940
- false
941
- );
942
- } catch {
943
- }
944
- if (canResolveWithImport) {
945
- throw new Error(
946
- `Failed to resolve ${JSON.stringify(
947
- id
948
- )}. 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.`
949
- );
950
- }
951
- }
952
- throw e;
953
- }
954
- if (!idFsPath) {
955
- return;
956
- }
957
- if (idFsPath.endsWith(".json")) {
958
- return idFsPath;
959
- }
960
- if (idFsPath && isImport) {
961
- idFsPath = pathToFileURL(idFsPath).href;
962
- }
963
- return { id: idFsPath, external: true };
964
- }
965
- }
966
- };
967
- })(),
968
- {
969
- name: "inject-file-scope-variables",
970
- transform: {
971
- filter: { id: /\.[cm]?[jt]s$/ },
972
- async handler(code, id) {
973
- const injectValues = `const ${dirnameVarName} = ${JSON.stringify(path5.dirname(id))};const ${filenameVarName} = ${JSON.stringify(id)};const ${importMetaUrlVarName} = ${JSON.stringify(
974
- pathToFileURL(id).href
975
- )};`;
976
- return { code: injectValues + code, map: null };
977
- }
978
- }
979
- }
980
- ],
981
- external: options.external
982
- // preserveEntrySignatures: 'exports-only'
983
- });
873
+ const {
874
+ transform: userTransform,
875
+ resolve: userResolve,
876
+ ...restRolldownInputOptions
877
+ } = rolldownInputOptions;
878
+ const transformDefine = {
879
+ ...userTransform?.define ?? {},
880
+ "__dirname": dirnameVarName,
881
+ "__filename": filenameVarName,
882
+ "import.meta.url": importMetaUrlVarName,
883
+ "import.meta.dirname": dirnameVarName,
884
+ "import.meta.filename": filenameVarName
885
+ };
886
+ const transformOptions = {
887
+ ...userTransform ?? {},
888
+ define: transformDefine
889
+ };
890
+ const resolveOptions = {
891
+ ...userResolve ?? {},
892
+ mainFields: ["main"],
893
+ tsconfigFilename: options.tsconfig
894
+ };
895
+ const originalConsoleWarn = console.warn;
896
+ console.warn = (...args) => {
897
+ const message = typeof args[0] === "string" ? args[0] : "";
898
+ if (message.includes("resolve.tsconfigFilename") || message.includes("Invalid input options") || message.includes('top-level "define" option is deprecated')) {
899
+ return;
900
+ }
901
+ originalConsoleWarn(...args);
902
+ };
903
+ let bundle;
904
+ try {
905
+ bundle = await rolldown({
906
+ ...restRolldownInputOptions,
907
+ input: fileName,
908
+ // target: [`node${process.versions.node}`],
909
+ platform: "node",
910
+ resolve: resolveOptions,
911
+ define: transformDefine,
912
+ transform: transformOptions,
913
+ // disable treeshake to include files that is not sideeffectful to `moduleIds`
914
+ treeshake: false,
915
+ plugins: [
916
+ createExternalizeDepsPlugin({
917
+ entryFile: fileName,
918
+ isESM,
919
+ moduleSyncEnabled
920
+ }),
921
+ createFileScopeVariablesPlugin({
922
+ dirnameVarName,
923
+ filenameVarName,
924
+ importMetaUrlVarName
925
+ })
926
+ ],
927
+ external: options.external
928
+ // preserveEntrySignatures: 'exports-only'
929
+ });
930
+ } finally {
931
+ console.warn = originalConsoleWarn;
932
+ }
933
+ if (!bundle) {
934
+ throw new Error("Failed to initialize bundler");
935
+ }
984
936
  const rolldownOutputOptions = options?.rolldownOptions?.output || {};
985
937
  const result = await bundle.generate({
986
938
  ...rolldownOutputOptions,
@@ -1000,14 +952,14 @@ async function bundleFile(fileName, options) {
1000
952
  result.output.flatMap((c) => c.type === "chunk" ? [[c.fileName, c]] : [])
1001
953
  );
1002
954
  const allModules = /* @__PURE__ */ new Set();
1003
- collectAllModules(bundleChunks, entryChunk.fileName, allModules);
955
+ collectReferencedModules(bundleChunks, entryChunk.fileName, allModules);
1004
956
  allModules.delete(fileName);
1005
957
  return {
1006
958
  code: entryChunk.code,
1007
959
  dependencies: [...allModules]
1008
960
  };
1009
961
  }
1010
- var _require2 = createRequire3(import.meta.url);
962
+ var _require = createRequire3(import.meta.url);
1011
963
  async function loadFromBundledFile(fileName, bundledCode, options) {
1012
964
  const { isESM } = options;
1013
965
  if (isESM) {
@@ -1025,11 +977,11 @@ async function loadFromBundledFile(fileName, bundledCode, options) {
1025
977
  }
1026
978
  }
1027
979
  }
1028
- const hash2 = `timestamp-${Date.now()}-${Math.random().toString(16).slice(2)}`;
980
+ const hash = `timestamp-${Date.now()}-${Math.random().toString(16).slice(2)}`;
1029
981
  const tempFileName = nodeModulesDir ? path5.resolve(
1030
982
  nodeModulesDir,
1031
- `.vite-temp/${path5.basename(fileName)}.${hash2}.${isESM ? "mjs" : "cjs"}`
1032
- ) : `${fileName}.${hash2}.mjs`;
983
+ `.vite-temp/${path5.basename(fileName)}.${hash}.${isESM ? "mjs" : "cjs"}`
984
+ ) : `${fileName}.${hash}.mjs`;
1033
985
  const getOutputFile = options.getOutputFile || defaultGetOutputFile;
1034
986
  const outfile = getOutputFile(tempFileName, options.format);
1035
987
  await fsp.writeFile(outfile, bundledCode);
@@ -1050,9 +1002,9 @@ async function loadFromBundledFile(fileName, bundledCode, options) {
1050
1002
  } else {
1051
1003
  const extension = path5.extname(fileName);
1052
1004
  const realFileName = await promisifiedRealpath(fileName);
1053
- const loaderExt = extension in _require2.extensions ? extension : ".js";
1054
- const defaultLoader = _require2.extensions[loaderExt];
1055
- _require2.extensions[loaderExt] = (module, filename) => {
1005
+ const loaderExt = extension in _require.extensions ? extension : ".js";
1006
+ const defaultLoader = _require.extensions[loaderExt];
1007
+ const compileLoader = (module, filename) => {
1056
1008
  if (filename === realFileName) {
1057
1009
  ;
1058
1010
  module._compile(bundledCode, filename);
@@ -1060,29 +1012,20 @@ async function loadFromBundledFile(fileName, bundledCode, options) {
1060
1012
  defaultLoader(module, filename);
1061
1013
  }
1062
1014
  };
1063
- delete _require2.cache[_require2.resolve(fileName)];
1064
- const raw = _require2(fileName);
1065
- _require2.extensions[loaderExt] = defaultLoader;
1066
- return raw.__esModule ? raw.default : raw;
1015
+ try {
1016
+ _require.extensions[loaderExt] = compileLoader;
1017
+ delete _require.cache[_require.resolve(fileName)];
1018
+ const raw = _require(fileName);
1019
+ return raw.__esModule ? raw.default : raw;
1020
+ } finally {
1021
+ _require.extensions[loaderExt] = defaultLoader;
1022
+ }
1067
1023
  }
1068
1024
  }
1069
1025
  async function bundleRequire(options) {
1070
- const resolvedPath = path5.isAbsolute(options.filepath) ? options.filepath : path5.resolve(options.cwd || process4.cwd(), options.filepath);
1071
- const isESM = typeof process4.versions.deno === "string" || isFilePathESM(resolvedPath);
1072
- if (options.tsconfig !== false) {
1073
- options.tsconfig = options.tsconfig ?? getTsconfig(options.cwd, "tsconfig.json")?.path ?? void 0;
1074
- } else {
1075
- options.tsconfig = void 0;
1076
- }
1077
- if (!options.format) {
1078
- options.format = isESM ? "esm" : "cjs";
1079
- }
1080
- const internalOptions = {
1081
- ...options,
1082
- isESM,
1083
- format: options.format,
1084
- tsconfig: options.tsconfig
1085
- };
1026
+ const resolvedPath = resolveEntryFilepath(options);
1027
+ const isESM = detectModuleType(resolvedPath);
1028
+ const internalOptions = createInternalOptions(options, isESM);
1086
1029
  const bundled = await bundleFile(
1087
1030
  resolvedPath,
1088
1031
  internalOptions
@@ -1097,6 +1040,137 @@ async function bundleRequire(options) {
1097
1040
  dependencies: bundled.dependencies
1098
1041
  };
1099
1042
  }
1043
+ function createExternalizeDepsPlugin({
1044
+ entryFile,
1045
+ isESM,
1046
+ moduleSyncEnabled
1047
+ }) {
1048
+ const packageCache = /* @__PURE__ */ new Map();
1049
+ const resolveByViteResolver = (id, importer, isRequire) => {
1050
+ return tryNodeResolve(id, importer, {
1051
+ root: path5.dirname(entryFile),
1052
+ isBuild: true,
1053
+ isProduction: true,
1054
+ preferRelative: false,
1055
+ tryIndex: true,
1056
+ mainFields: [],
1057
+ conditions: [
1058
+ "node",
1059
+ ...moduleSyncEnabled ? ["module-sync"] : []
1060
+ ],
1061
+ externalConditions: [],
1062
+ external: [],
1063
+ noExternal: [],
1064
+ dedupe: [],
1065
+ extensions: configDefaults.resolve.extensions,
1066
+ preserveSymlinks: false,
1067
+ packageCache,
1068
+ isRequire,
1069
+ builtins: nodeLikeBuiltins
1070
+ })?.id;
1071
+ };
1072
+ return {
1073
+ name: "externalize-deps",
1074
+ resolveId: {
1075
+ filter: { id: /^[^.#].*/ },
1076
+ async handler(id, importer, { kind }) {
1077
+ if (!importer || path5.isAbsolute(id) || isNodeBuiltin(id)) {
1078
+ return;
1079
+ }
1080
+ if (isNodeLikeBuiltin(id)) {
1081
+ return { id, external: true };
1082
+ }
1083
+ const isImport = isESM || kind === "dynamic-import";
1084
+ let idFsPath;
1085
+ try {
1086
+ idFsPath = resolveByViteResolver(id, importer, !isImport);
1087
+ } catch (e) {
1088
+ if (!isImport) {
1089
+ let canResolveWithImport = false;
1090
+ try {
1091
+ canResolveWithImport = !!resolveByViteResolver(
1092
+ id,
1093
+ importer,
1094
+ false
1095
+ );
1096
+ } catch {
1097
+ }
1098
+ if (canResolveWithImport) {
1099
+ throw new Error(
1100
+ `Failed to resolve ${JSON.stringify(
1101
+ id
1102
+ )}. 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.`
1103
+ );
1104
+ }
1105
+ }
1106
+ throw e;
1107
+ }
1108
+ if (!idFsPath) {
1109
+ return;
1110
+ }
1111
+ if (idFsPath.endsWith(".json")) {
1112
+ return idFsPath;
1113
+ }
1114
+ if (idFsPath && isImport) {
1115
+ idFsPath = pathToFileURL(idFsPath).href;
1116
+ }
1117
+ return { id: idFsPath, external: true };
1118
+ }
1119
+ }
1120
+ };
1121
+ }
1122
+ function createFileScopeVariablesPlugin({
1123
+ dirnameVarName,
1124
+ filenameVarName,
1125
+ importMetaUrlVarName
1126
+ }) {
1127
+ return {
1128
+ name: "inject-file-scope-variables",
1129
+ transform: {
1130
+ filter: { id: /\.[cm]?[jt]s$/ },
1131
+ async handler(code, id) {
1132
+ const injectValues = `const ${dirnameVarName} = ${JSON.stringify(path5.dirname(id))};const ${filenameVarName} = ${JSON.stringify(id)};const ${importMetaUrlVarName} = ${JSON.stringify(
1133
+ pathToFileURL(id).href
1134
+ )};`;
1135
+ return { code: injectValues + code, map: null };
1136
+ }
1137
+ }
1138
+ };
1139
+ }
1140
+ function resolveEntryFilepath(options) {
1141
+ if (path5.isAbsolute(options.filepath)) {
1142
+ return options.filepath;
1143
+ }
1144
+ const cwd = options.cwd ? path5.resolve(options.cwd) : process4.cwd();
1145
+ return path5.resolve(cwd, options.filepath);
1146
+ }
1147
+ function detectModuleType(resolvedPath) {
1148
+ return typeof process4.versions.deno === "string" || isFilePathESM(resolvedPath);
1149
+ }
1150
+ function createInternalOptions(userOptions, isESM) {
1151
+ const {
1152
+ filepath: _filepath,
1153
+ cwd: _cwd,
1154
+ ...rest
1155
+ } = userOptions;
1156
+ const tsconfig = resolveTsconfigPath(userOptions);
1157
+ const format = userOptions.format ?? (isESM ? "esm" : "cjs");
1158
+ return {
1159
+ ...rest,
1160
+ isESM,
1161
+ format,
1162
+ tsconfig
1163
+ };
1164
+ }
1165
+ function resolveTsconfigPath(options) {
1166
+ if (options.tsconfig === false) {
1167
+ return void 0;
1168
+ }
1169
+ if (typeof options.tsconfig === "string") {
1170
+ return options.tsconfig;
1171
+ }
1172
+ return getTsconfig(options.cwd, "tsconfig.json")?.path ?? void 0;
1173
+ }
1100
1174
  export {
1101
1175
  bundleFile,
1102
1176
  bundleRequire,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "rolldown-require",
3
3
  "type": "module",
4
- "version": "1.0.3",
4
+ "version": "1.0.5",
5
5
  "description": "bundle and require a file using rolldown!",
6
6
  "author": "ice breaker <1324318532@qq.com>",
7
7
  "license": "MIT",
@@ -51,8 +51,8 @@
51
51
  "rolldown": ">=1.0.0-beta.33"
52
52
  },
53
53
  "dependencies": {
54
- "@rollup/pluginutils": "^5.2.0",
55
- "get-tsconfig": "^4.10.1",
54
+ "@rollup/pluginutils": "^5.3.0",
55
+ "get-tsconfig": "^4.13.0",
56
56
  "mlly": "^1.8.0",
57
57
  "resolve.exports": "^2.0.3"
58
58
  },