rolldown-require
Version:
bundle and require a file using rolldown!
1,106 lines (1,095 loc) • 35.4 kB
JavaScript
// src/index.ts
import fs4 from "fs";
import fsp from "fs/promises";
import { createRequire as createRequire3 } from "module";
import path5 from "path";
import process4 from "process";
import { pathToFileURL } from "url";
import { promisify } from "util";
import { getTsconfig } from "get-tsconfig";
import { rolldown } from "rolldown";
// src/packages.ts
import fs2 from "fs";
import { createRequire as createRequire2 } from "module";
import path2 from "path";
import process3 from "process";
// src/utils.ts
import { exec } from "child_process";
import crypto from "crypto";
import fs from "fs";
import { builtinModules, createRequire } from "module";
import path from "path";
import process2 from "process";
import { fileURLToPath, URL as URL2 } from "url";
import { createFilter as _createFilter } from "@rollup/pluginutils";
// src/constants.ts
import { readFileSync } from "fs";
var { version } = JSON.parse(
readFileSync(new URL("../package.json", import.meta.url)).toString()
);
var DEV_PROD_CONDITION = `development|production`;
var OPTIMIZABLE_ENTRY_RE = /\.[cm]?[jt]s$/;
var SPECIAL_QUERY_RE = /[?&](?:worker|sharedworker|raw|url)\b/;
// src/sharedUtils.ts
import process from "process";
var isWindows = typeof process !== "undefined" && process.platform === "win32";
var windowsSlashRE = /\\/g;
function slash(p) {
return p.replace(windowsSlashRE, "/");
}
var postfixRE = /[?#].*$/;
function cleanUrl(url) {
return url.replace(postfixRE, "");
}
function splitFileAndPostfix(path6) {
const file = cleanUrl(path6);
return { file, postfix: path6.slice(file.length) };
}
var AsyncFunction = async function() {
}.constructor;
// src/utils.ts
import { VERSION } from "rolldown";
import { withFilter } from "rolldown/filter";
var createFilter = _createFilter;
var NODE_BUILTIN_NAMESPACE = "node:";
var NPM_BUILTIN_NAMESPACE = "npm:";
var BUN_BUILTIN_NAMESPACE = "bun:";
var nodeBuiltins = builtinModules.filter((id) => !id.includes(":"));
var isBuiltinCache = /* @__PURE__ */ new WeakMap();
function isBuiltin(builtins, id) {
let isBuiltin2 = isBuiltinCache.get(builtins);
if (!isBuiltin2) {
isBuiltin2 = createIsBuiltin(builtins);
isBuiltinCache.set(builtins, isBuiltin2);
}
return isBuiltin2(id);
}
function createIsBuiltin(builtins) {
const plainBuiltinsSet = new Set(
builtins.filter((builtin) => typeof builtin === "string")
);
const regexBuiltins = builtins.filter(
(builtin) => typeof builtin !== "string"
);
return (id) => plainBuiltinsSet.has(id) || regexBuiltins.some((regexp) => regexp.test(id));
}
var nodeLikeBuiltins = [
...nodeBuiltins,
new RegExp(`^${NODE_BUILTIN_NAMESPACE}`),
new RegExp(`^${NPM_BUILTIN_NAMESPACE}`),
new RegExp(`^${BUN_BUILTIN_NAMESPACE}`)
];
function isNodeLikeBuiltin(id) {
return isBuiltin(nodeLikeBuiltins, id);
}
function isNodeBuiltin(id) {
if (id.startsWith(NODE_BUILTIN_NAMESPACE)) {
return true;
}
return nodeBuiltins.includes(id);
}
function isInNodeModules(id) {
return id.includes("node_modules");
}
function isOptimizable(id, optimizeDeps) {
const { extensions } = optimizeDeps;
return OPTIMIZABLE_ENTRY_RE.test(id) || (extensions?.some((ext) => id.endsWith(ext)) ?? false);
}
var bareImportRE = /^(?![a-z]:)[\w@](?!.*:\/\/)/i;
var deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\//;
var _require = createRequire(import.meta.url);
var _dirname = path.dirname(fileURLToPath(import.meta.url));
var urlCanParse = URL2.canParse ?? ((path6, base) => {
try {
new URL2(path6, base);
return true;
} catch {
return false;
}
});
function normalizePath(id) {
return path.posix.normalize(isWindows ? slash(id) : id);
}
function injectQuery(url, queryToInject) {
const { file, postfix } = splitFileAndPostfix(url);
const normalizedFile = isWindows ? slash(file) : file;
return `${normalizedFile}?${queryToInject}${postfix[0] === "?" ? `&${postfix.slice(1)}` : (
/* hash only */
postfix
)}`;
}
function isObject(value) {
return Object.prototype.toString.call(value) === "[object Object]";
}
function tryStatSync(file) {
try {
return fs.statSync(file, { throwIfNoEntry: false });
} catch {
}
}
function isFilePathESM(filePath, packageCache) {
if (/\.m[jt]s$/.test(filePath)) {
return true;
} else if (/\.c[jt]s$/.test(filePath)) {
return false;
} else {
try {
const pkg = findNearestPackageData(path.dirname(filePath), packageCache);
return pkg?.data.type === "module";
} catch {
return false;
}
}
}
var safeRealpathSync = isWindows ? windowsSafeRealPathSync : fs.realpathSync.native;
var windowsNetworkMap = /* @__PURE__ */ new Map();
function windowsMappedRealpathSync(path6) {
const realPath = fs.realpathSync.native(path6);
if (realPath.startsWith("\\\\")) {
for (const [network, volume] of windowsNetworkMap) {
if (realPath.startsWith(network)) {
return realPath.replace(network, volume);
}
}
}
return realPath;
}
var parseNetUseRE = /^\w* +(\w:) +([^ ]+)\s/;
var firstSafeRealPathSyncRun = false;
function windowsSafeRealPathSync(path6) {
if (!firstSafeRealPathSyncRun) {
optimizeSafeRealPathSync();
firstSafeRealPathSyncRun = true;
}
return fs.realpathSync(path6);
}
function optimizeSafeRealPathSync() {
const nodeVersion = process2.versions.node.split(".").map(Number);
if (nodeVersion[0] < 18 || nodeVersion[0] === 18 && nodeVersion[1] < 10) {
safeRealpathSync = fs.realpathSync;
return;
}
try {
fs.realpathSync.native(path.resolve("./"));
} catch (error) {
if (error.message.includes("EISDIR: illegal operation on a directory")) {
safeRealpathSync = fs.realpathSync;
return;
}
}
exec("net use", (error, stdout) => {
if (error) {
return;
}
const lines = stdout.split("\n");
for (const line of lines) {
const m = parseNetUseRE.exec(line);
if (m) {
windowsNetworkMap.set(m[2], m[1]);
}
}
if (windowsNetworkMap.size === 0) {
safeRealpathSync = fs.realpathSync.native;
} else {
safeRealpathSync = windowsMappedRealpathSync;
}
});
}
var hash = crypto.hash ?? ((algorithm, data, outputEncoding) => crypto.createHash(algorithm).update(data).digest(outputEncoding));
function stripBomTag(content) {
if (content.charCodeAt(0) === 65279) {
return content.slice(1);
}
return content;
}
function getNpmPackageName(importPath) {
const parts = importPath.split("/");
if (parts[0][0] === "@") {
if (!parts[1]) {
return null;
}
return `${parts[0]}/${parts[1]}`;
} else {
return parts[0];
}
}
var dynamicImport = async (id, { format }) => {
const fn = format === "esm" ? (file) => import(file) : true ? createRequire(import.meta.url) : __require;
return fn(id);
};
// src/packages.ts
var pnp;
if (process3.versions.pnp) {
try {
pnp = createRequire2(import.meta.url)("pnpapi");
} catch {
}
}
function resolvePackageData(pkgName, basedir, preserveSymlinks = false, packageCache) {
if (pnp) {
const cacheKey = getRpdCacheKey(pkgName, basedir, preserveSymlinks);
if (packageCache?.has(cacheKey)) {
return packageCache.get(cacheKey);
}
try {
const pkg = pnp.resolveToUnqualified(pkgName, basedir, {
considerBuiltins: false
});
if (!pkg) {
return null;
}
const pkgData = loadPackageData(path2.join(pkg, "package.json"));
packageCache?.set(cacheKey, pkgData);
return pkgData;
} catch {
return null;
}
}
const originalBasedir = basedir;
while (basedir) {
if (packageCache) {
const cached = getRpdCache(
packageCache,
pkgName,
basedir,
originalBasedir,
preserveSymlinks
);
if (cached) {
return cached;
}
}
const pkg = path2.join(basedir, "node_modules", pkgName, "package.json");
try {
if (fs2.existsSync(pkg)) {
const pkgPath = preserveSymlinks ? pkg : safeRealpathSync(pkg);
const pkgData = loadPackageData(pkgPath);
if (packageCache) {
setRpdCache(
packageCache,
pkgData,
pkgName,
basedir,
originalBasedir,
preserveSymlinks
);
}
return pkgData;
}
} catch {
}
const nextBasedir = path2.dirname(basedir);
if (nextBasedir === basedir) {
break;
}
basedir = nextBasedir;
}
return null;
}
function findNearestPackageData(basedir, packageCache) {
const originalBasedir = basedir;
while (basedir) {
if (packageCache) {
const cached = getFnpdCache(packageCache, basedir, originalBasedir);
if (cached) {
return cached;
}
}
const pkgPath = path2.join(basedir, "package.json");
if (tryStatSync(pkgPath)?.isFile()) {
try {
const pkgData = loadPackageData(pkgPath);
if (packageCache) {
setFnpdCache(packageCache, pkgData, basedir, originalBasedir);
}
return pkgData;
} catch {
}
}
const nextBasedir = path2.dirname(basedir);
if (nextBasedir === basedir) {
break;
}
basedir = nextBasedir;
}
return null;
}
function findNearestMainPackageData(basedir, packageCache) {
const nearestPackage = findNearestPackageData(basedir, packageCache);
return nearestPackage && (nearestPackage.data.name ? nearestPackage : findNearestMainPackageData(
path2.dirname(nearestPackage.dir),
packageCache
));
}
function loadPackageData(pkgPath) {
const data = JSON.parse(stripBomTag(fs2.readFileSync(pkgPath, "utf-8")));
const pkgDir = normalizePath(path2.dirname(pkgPath));
const { sideEffects } = data;
let hasSideEffects;
if (typeof sideEffects === "boolean") {
hasSideEffects = () => sideEffects;
} else if (Array.isArray(sideEffects)) {
if (sideEffects.length <= 0) {
hasSideEffects = () => false;
} else {
const finalPackageSideEffects = sideEffects.map((sideEffect) => {
if (sideEffect.includes("/")) {
return sideEffect;
}
return `**/${sideEffect}`;
});
hasSideEffects = createFilter(finalPackageSideEffects, null, {
resolve: pkgDir
});
}
} else {
hasSideEffects = () => null;
}
const resolvedCache = {};
const pkg = {
dir: pkgDir,
data,
hasSideEffects,
setResolvedCache(key, entry, options) {
resolvedCache[getResolveCacheKey(key, options)] = entry;
},
getResolvedCache(key, options) {
return resolvedCache[getResolveCacheKey(key, options)];
}
};
return pkg;
}
function getResolveCacheKey(key, options) {
return [
key,
options.isRequire ? "1" : "0",
options.conditions.join("_"),
options.extensions.join("_"),
options.mainFields.join("_")
].join("|");
}
function findNearestNodeModules(basedir) {
while (basedir) {
const pkgPath = path2.join(basedir, "node_modules");
if (tryStatSync(pkgPath)?.isDirectory()) {
return pkgPath;
}
const nextBasedir = path2.dirname(basedir);
if (nextBasedir === basedir) {
break;
}
basedir = nextBasedir;
}
return null;
}
function getRpdCache(packageCache, pkgName, basedir, originalBasedir, preserveSymlinks) {
const cacheKey = getRpdCacheKey(pkgName, basedir, preserveSymlinks);
const pkgData = packageCache.get(cacheKey);
if (pkgData) {
traverseBetweenDirs(originalBasedir, basedir, (dir) => {
packageCache.set(getRpdCacheKey(pkgName, dir, preserveSymlinks), pkgData);
});
return pkgData;
}
}
function setRpdCache(packageCache, pkgData, pkgName, basedir, originalBasedir, preserveSymlinks) {
packageCache.set(getRpdCacheKey(pkgName, basedir, preserveSymlinks), pkgData);
traverseBetweenDirs(originalBasedir, basedir, (dir) => {
packageCache.set(getRpdCacheKey(pkgName, dir, preserveSymlinks), pkgData);
});
}
function getRpdCacheKey(pkgName, basedir, preserveSymlinks) {
return `rpd_${pkgName}_${basedir}_${preserveSymlinks}`;
}
function getFnpdCache(packageCache, basedir, originalBasedir) {
const cacheKey = getFnpdCacheKey(basedir);
const pkgData = packageCache.get(cacheKey);
if (pkgData) {
traverseBetweenDirs(originalBasedir, basedir, (dir) => {
packageCache.set(getFnpdCacheKey(dir), pkgData);
});
return pkgData;
}
}
function setFnpdCache(packageCache, pkgData, basedir, originalBasedir) {
packageCache.set(getFnpdCacheKey(basedir), pkgData);
traverseBetweenDirs(originalBasedir, basedir, (dir) => {
packageCache.set(getFnpdCacheKey(dir), pkgData);
});
}
function getFnpdCacheKey(basedir) {
return `fnpd_${basedir}`;
}
function traverseBetweenDirs(longerDir, shorterDir, cb) {
while (longerDir !== shorterDir) {
cb(longerDir);
longerDir = path2.dirname(longerDir);
}
}
// src/plugins/resolve.ts
import fs3 from "fs";
import path4 from "path";
import { hasESMSyntax } from "mlly";
import { exports, imports } from "resolve.exports";
// src/external.ts
import path3 from "path";
function canExternalizeFile(filePath) {
const ext = path3.extname(filePath);
return !ext || ext === ".js" || ext === ".mjs" || ext === ".cjs";
}
// src/plugins/resolve.ts
var ERR_RESOLVE_PACKAGE_ENTRY_FAIL = "ERR_RESOLVE_PACKAGE_ENTRY_FAIL";
var browserExternalId = "__vite-browser-external";
var optionalPeerDepId = "__vite-optional-peer-dep";
function tryFsResolve(fsPath, options, tryIndex = true, skipPackageJson = false) {
const hashIndex = fsPath.indexOf("#");
if (hashIndex >= 0 && isInNodeModules(fsPath)) {
const queryIndex = fsPath.indexOf("?");
if (queryIndex < 0 || queryIndex > hashIndex) {
const file2 = queryIndex > hashIndex ? fsPath.slice(0, queryIndex) : fsPath;
const res2 = tryCleanFsResolve(file2, options, tryIndex, skipPackageJson);
if (res2) {
return res2 + fsPath.slice(file2.length);
}
}
}
const { file, postfix } = splitFileAndPostfix(fsPath);
const res = tryCleanFsResolve(file, options, tryIndex, skipPackageJson);
if (res) {
return res + postfix;
}
}
var knownTsOutputRE = /\.(?:js|mjs|cjs|jsx)$/;
var isPossibleTsOutput = (url) => knownTsOutputRE.test(url);
function tryCleanFsResolve(file, options, tryIndex = true, skipPackageJson = false) {
const { tryPrefix, extensions, preserveSymlinks } = options;
const fileResult = tryResolveRealFileOrType(file, options.preserveSymlinks);
if (fileResult?.path) {
return fileResult.path;
}
let res;
const possibleJsToTs = isPossibleTsOutput(file);
if (possibleJsToTs || options.extensions.length || tryPrefix) {
const dirPath = path4.dirname(file);
if (isDirectory(dirPath)) {
if (possibleJsToTs) {
const fileExt = path4.extname(file);
const fileName = file.slice(0, -fileExt.length);
if (res = tryResolveRealFile(
fileName + fileExt.replace("js", "ts"),
preserveSymlinks
)) {
return res;
}
if (fileExt === ".js" && (res = tryResolveRealFile(`${fileName}.tsx`, preserveSymlinks))) {
return res;
}
}
if (res = tryResolveRealFileWithExtensions(
file,
extensions,
preserveSymlinks
)) {
return res;
}
if (tryPrefix) {
const prefixed = `${dirPath}/${options.tryPrefix}${path4.basename(file)}`;
if (res = tryResolveRealFile(prefixed, preserveSymlinks)) {
return res;
}
if (res = tryResolveRealFileWithExtensions(
prefixed,
extensions,
preserveSymlinks
)) {
return res;
}
}
}
}
if (tryIndex && fileResult?.type === "directory") {
const dirPath = file;
if (!skipPackageJson) {
let pkgPath = `${dirPath}/package.json`;
try {
if (fs3.existsSync(pkgPath)) {
if (!options.preserveSymlinks) {
pkgPath = safeRealpathSync(pkgPath);
}
const pkg = loadPackageData(pkgPath);
return resolvePackageEntry(dirPath, pkg, options);
}
} catch (e) {
if (e.code !== ERR_RESOLVE_PACKAGE_ENTRY_FAIL && e.code !== "ENOENT") {
throw e;
}
}
}
if (res = tryResolveRealFileWithExtensions(
`${dirPath}/index`,
extensions,
preserveSymlinks
)) {
return res;
}
if (tryPrefix) {
if (res = tryResolveRealFileWithExtensions(
`${dirPath}/${options.tryPrefix}index`,
extensions,
preserveSymlinks
)) {
return res;
}
}
}
}
function tryNodeResolve(id, importer, options, depsOptimizer, externalize) {
const { root, dedupe, isBuild, preserveSymlinks, packageCache } = options;
const deepMatch = deepImportRE.exec(id);
const pkgId = deepMatch ? deepMatch[1] || deepMatch[2] : cleanUrl(id);
let basedir;
if (dedupe.includes(pkgId)) {
basedir = root;
} else if (importer && path4.isAbsolute(importer) && (importer.endsWith("*") || fs3.existsSync(cleanUrl(importer)))) {
basedir = path4.dirname(importer);
} else {
basedir = root;
}
const isModuleBuiltin = (id2) => isBuiltin(options.builtins, id2);
let selfPkg = null;
if (!isModuleBuiltin(id) && !id.includes("\0") && bareImportRE.test(id)) {
const selfPackageData = findNearestPackageData(basedir, packageCache);
selfPkg = selfPackageData?.data.exports && selfPackageData.data.name === pkgId ? selfPackageData : null;
}
const pkg = selfPkg || resolvePackageData(pkgId, basedir, preserveSymlinks, packageCache);
if (!pkg) {
if (basedir !== root && !isModuleBuiltin(id) && !id.includes("\0") && bareImportRE.test(id)) {
const mainPkg = findNearestMainPackageData(basedir, packageCache)?.data;
if (mainPkg) {
const pkgName = getNpmPackageName(id);
if (pkgName != null && mainPkg.peerDependencies?.[pkgName] && mainPkg.peerDependenciesMeta?.[pkgName]?.optional) {
return {
id: `${optionalPeerDepId}:${id}:${mainPkg.name}`
};
}
}
}
return;
}
const resolveId = deepMatch ? resolveDeepImport : resolvePackageEntry;
const unresolvedId = deepMatch ? `.${id.slice(pkgId.length)}` : id;
let resolved = resolveId(unresolvedId, pkg, options);
if (!resolved) {
return;
}
const processResult = (resolved2) => {
if (!externalize) {
return resolved2;
}
if (!canExternalizeFile(resolved2.id)) {
return resolved2;
}
let resolvedId = id;
if (deepMatch && !pkg.data.exports && path4.extname(id) !== path4.extname(resolved2.id)) {
const index = resolved2.id.indexOf(id);
if (index > -1) {
resolvedId = resolved2.id.slice(index);
}
}
return { ...resolved2, id: resolvedId, external: true };
};
if (!options.idOnly && (!options.scan && isBuild || externalize)) {
return processResult({
id: resolved,
moduleSideEffects: pkg.hasSideEffects(resolved)
});
}
if (!isInNodeModules(resolved) || !depsOptimizer || options.scan) {
return { id: resolved };
}
const isJsType = isOptimizable(resolved, depsOptimizer.options);
const exclude = depsOptimizer.options.exclude;
const skipOptimization = depsOptimizer.options.noDiscovery || !isJsType || importer && isInNodeModules(importer) || exclude?.includes(pkgId) || exclude?.includes(id) || SPECIAL_QUERY_RE.test(resolved);
if (skipOptimization) {
const versionHash = depsOptimizer.metadata.browserHash;
if (versionHash && isJsType) {
resolved = injectQuery(resolved, `v=${versionHash}`);
}
} else {
const optimizedInfo = depsOptimizer.registerMissingImport(id, resolved);
resolved = depsOptimizer.getOptimizedDepId(optimizedInfo);
}
return { id: resolved };
}
function resolvePackageEntry(id, { dir, data, setResolvedCache, getResolvedCache }, options) {
const { postfix } = splitFileAndPostfix(id);
const cached = getResolvedCache(".", options);
if (cached) {
return cached + postfix;
}
try {
let entryPoint;
if (data.exports) {
entryPoint = resolveExportsOrImports(data, ".", options, "exports");
}
if (!entryPoint) {
for (const field of options.mainFields) {
if (field === "browser") {
entryPoint = tryResolveBrowserEntry(dir, data, options);
if (entryPoint) {
break;
}
} else if (typeof data[field] === "string") {
entryPoint = data[field];
break;
}
}
}
entryPoint ||= data.main;
const entryPoints = entryPoint ? [entryPoint] : ["index.js", "index.json", "index.node"];
for (let entry of entryPoints) {
let skipPackageJson = false;
if (options.mainFields[0] === "sass" && !options.extensions.includes(path4.extname(entry))) {
entry = "";
skipPackageJson = true;
} else {
const { browser: browserField } = data;
if (options.mainFields.includes("browser") && isObject(browserField)) {
entry = mapWithBrowserField(entry, browserField) || entry;
}
}
const entryPointPath = path4.join(dir, entry);
const resolvedEntryPoint = tryFsResolve(
entryPointPath,
options,
true,
skipPackageJson
);
if (resolvedEntryPoint) {
setResolvedCache(".", resolvedEntryPoint, options);
return resolvedEntryPoint + postfix;
}
}
} catch (e) {
packageEntryFailure(
id,
// @ts-ignore
e.message
);
}
packageEntryFailure(id);
}
function packageEntryFailure(id, details) {
const err = new Error(
`Failed to resolve entry for package "${id}". The package may have incorrect main/module/exports specified in its package.json${details ? `: ${details}` : "."}`
);
err.code = ERR_RESOLVE_PACKAGE_ENTRY_FAIL;
throw err;
}
function getConditions(conditions, isProduction, isRequire) {
const resolvedConditions = conditions.map((condition) => {
if (condition === DEV_PROD_CONDITION) {
return isProduction ? "production" : "development";
}
return condition;
});
if (isRequire) {
resolvedConditions.push("require");
} else {
resolvedConditions.push("import");
}
return resolvedConditions;
}
function resolveExportsOrImports(pkg, key, options, type) {
const conditions = getConditions(
options.conditions,
options.isProduction,
options.isRequire
);
const fn = type === "imports" ? imports : exports;
const result = fn(pkg, key, { conditions, unsafe: true });
return result ? result[0] : void 0;
}
function resolveDeepImport(id, { setResolvedCache, getResolvedCache, dir, data }, options) {
const cache = getResolvedCache(id, options);
if (cache) {
return cache;
}
let relativeId = id;
const { exports: exportsField, browser: browserField } = data;
if (exportsField) {
if (isObject(exportsField) && !Array.isArray(exportsField)) {
const { file, postfix } = splitFileAndPostfix(relativeId);
const exportsId = resolveExportsOrImports(data, file, options, "exports");
if (exportsId !== void 0) {
relativeId = exportsId + postfix;
} else {
relativeId = void 0;
}
} else {
relativeId = void 0;
}
if (!relativeId) {
throw new Error(
`Package subpath '${relativeId}' is not defined by "exports" in ${path4.join(dir, "package.json")}.`
);
}
} else if (options.mainFields.includes("browser") && isObject(browserField)) {
const { file, postfix } = splitFileAndPostfix(relativeId);
const mapped = mapWithBrowserField(file, browserField);
if (mapped) {
relativeId = mapped + postfix;
} else if (mapped === false) {
setResolvedCache(id, browserExternalId, options);
return browserExternalId;
}
}
if (relativeId) {
const resolved = tryFsResolve(
path4.join(dir, relativeId),
options,
!exportsField
// try index only if no exports field
);
if (resolved) {
setResolvedCache(id, resolved, options);
return resolved;
}
}
}
function tryResolveBrowserEntry(dir, data, options) {
const browserEntry = typeof data.browser === "string" ? data.browser : isObject(data.browser) && data.browser["."];
if (browserEntry) {
if (!options.isRequire && options.mainFields.includes("module") && typeof data.module === "string" && data.module !== browserEntry) {
const resolvedBrowserEntry = tryFsResolve(
path4.join(dir, browserEntry),
options
);
if (resolvedBrowserEntry) {
const content = fs3.readFileSync(resolvedBrowserEntry, "utf-8");
if (hasESMSyntax(content)) {
return browserEntry;
} else {
return data.module;
}
}
} else {
return browserEntry;
}
}
}
function mapWithBrowserField(relativePathInPkgDir, map) {
const normalizedPath = path4.posix.normalize(relativePathInPkgDir);
for (const key in map) {
const normalizedKey = path4.posix.normalize(key);
if (normalizedPath === normalizedKey || equalWithoutSuffix(normalizedPath, normalizedKey, ".js") || equalWithoutSuffix(normalizedPath, normalizedKey, "/index.js")) {
return map[key];
}
}
}
function equalWithoutSuffix(path6, key, suffix) {
return key.endsWith(suffix) && key.slice(0, -suffix.length) === path6;
}
function tryResolveRealFile(file, preserveSymlinks) {
const stat = tryStatSync(file);
if (stat?.isFile()) {
return getRealPath(file, preserveSymlinks);
}
}
function tryResolveRealFileWithExtensions(filePath, extensions, preserveSymlinks) {
for (const ext of extensions) {
const res = tryResolveRealFile(filePath + ext, preserveSymlinks);
if (res) {
return res;
}
}
}
function tryResolveRealFileOrType(file, preserveSymlinks) {
const fileStat = tryStatSync(file);
if (fileStat?.isFile()) {
return { path: getRealPath(file, preserveSymlinks), type: "file" };
}
if (fileStat?.isDirectory()) {
return { type: "directory" };
}
}
function getRealPath(resolved, preserveSymlinks) {
if (!preserveSymlinks) {
resolved = safeRealpathSync(resolved);
}
return normalizePath(resolved);
}
function isDirectory(path6) {
const stat = tryStatSync(path6);
return stat?.isDirectory() ?? false;
}
// src/index.ts
var promisifiedRealpath = promisify(fs4.realpath);
var configDefaults = Object.freeze({
resolve: {
extensions: [".mjs", ".js", ".mts", ".ts", ".jsx", ".tsx", ".json"]
}
});
var defaultGetOutputFile = (filepath, _format) => {
return filepath;
};
function collectAllModules(bundle, fileName, allModules, analyzedModules = /* @__PURE__ */ new Set()) {
if (analyzedModules.has(fileName)) {
return;
}
analyzedModules.add(fileName);
const chunk = bundle[fileName];
for (const mod of chunk.moduleIds) {
allModules.add(mod);
}
for (const i of chunk.imports) {
analyzedModules.add(i);
collectAllModules(bundle, i, allModules, analyzedModules);
}
for (const i of chunk.dynamicImports) {
analyzedModules.add(i);
collectAllModules(bundle, i, allModules, analyzedModules);
}
}
async function bundleFile(fileName, options) {
const { isESM } = options;
const isModuleSyncConditionEnabled = (await import(
// @ts-ignore
"#module-sync-enabled"
)).default;
const dirnameVarName = "__vite_injected_original_dirname";
const filenameVarName = "__vite_injected_original_filename";
const importMetaUrlVarName = "__vite_injected_original_import_meta_url";
const rolldownInputOptions = options?.rolldownOptions?.input || {};
const bundle = await rolldown({
...rolldownInputOptions,
input: fileName,
// target: [`node${process.versions.node}`],
platform: "node",
resolve: {
mainFields: ["main"],
tsconfigFilename: options.tsconfig
},
define: {
"__dirname": dirnameVarName,
"__filename": filenameVarName,
"import.meta.url": importMetaUrlVarName,
"import.meta.dirname": dirnameVarName,
"import.meta.filename": filenameVarName
},
// disable treeshake to include files that is not sideeffectful to `moduleIds`
treeshake: false,
plugins: [
/* @__PURE__ */ (() => {
const packageCache = /* @__PURE__ */ new Map();
const resolveByViteResolver = (id, importer, isRequire) => {
return tryNodeResolve(id, importer, {
root: path5.dirname(fileName),
isBuild: true,
isProduction: true,
preferRelative: false,
tryIndex: true,
mainFields: [],
conditions: [
"node",
...isModuleSyncConditionEnabled ? ["module-sync"] : []
],
externalConditions: [],
external: [],
noExternal: [],
dedupe: [],
extensions: configDefaults.resolve.extensions,
preserveSymlinks: false,
packageCache,
isRequire,
builtins: nodeLikeBuiltins
})?.id;
};
return {
name: "externalize-deps",
resolveId: {
filter: { id: /^[^.#].*/ },
async handler(id, importer, { kind }) {
if (!importer || path5.isAbsolute(id) || isNodeBuiltin(id)) {
return;
}
if (isNodeLikeBuiltin(id)) {
return { id, external: true };
}
const isImport = isESM || kind === "dynamic-import";
let idFsPath;
try {
idFsPath = resolveByViteResolver(id, importer, !isImport);
} catch (e) {
if (!isImport) {
let canResolveWithImport = false;
try {
canResolveWithImport = !!resolveByViteResolver(
id,
importer,
false
);
} catch {
}
if (canResolveWithImport) {
throw new Error(
`Failed to resolve ${JSON.stringify(
id
)}. 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.`
);
}
}
throw e;
}
if (!idFsPath) {
return;
}
if (idFsPath.endsWith(".json")) {
return idFsPath;
}
if (idFsPath && isImport) {
idFsPath = pathToFileURL(idFsPath).href;
}
return { id: idFsPath, external: true };
}
}
};
})(),
{
name: "inject-file-scope-variables",
transform: {
filter: { id: /\.[cm]?[jt]s$/ },
async handler(code, id) {
const injectValues = `const ${dirnameVarName} = ${JSON.stringify(path5.dirname(id))};const ${filenameVarName} = ${JSON.stringify(id)};const ${importMetaUrlVarName} = ${JSON.stringify(
pathToFileURL(id).href
)};`;
return { code: injectValues + code, map: null };
}
}
}
],
external: options.external
// preserveEntrySignatures: 'exports-only'
});
const rolldownOutputOptions = options?.rolldownOptions?.output || {};
const result = await bundle.generate({
...rolldownOutputOptions,
format: options.format,
sourcemap: false,
// sourcemapPathTransform(relative) {
// return path.resolve(fileName, relative)
// },
// we want to generate a single chunk like esbuild does with `splitting: false`
inlineDynamicImports: true
});
await bundle.close();
const entryChunk = result.output.find(
(chunk) => chunk.type === "chunk" && chunk.isEntry
);
const bundleChunks = Object.fromEntries(
result.output.flatMap((c) => c.type === "chunk" ? [[c.fileName, c]] : [])
);
const allModules = /* @__PURE__ */ new Set();
collectAllModules(bundleChunks, entryChunk.fileName, allModules);
allModules.delete(fileName);
return {
code: entryChunk.code,
dependencies: [...allModules]
};
}
var _require2 = createRequire3(import.meta.url);
async function loadFromBundledFile(fileName, bundledCode, options) {
const { isESM } = options;
if (isESM) {
let nodeModulesDir = typeof process4.versions.deno === "string" ? void 0 : findNearestNodeModules(path5.dirname(fileName));
if (nodeModulesDir) {
try {
await fsp.mkdir(path5.resolve(nodeModulesDir, ".vite-temp/"), {
recursive: true
});
} catch (e) {
if (e.code === "EACCES") {
nodeModulesDir = void 0;
} else {
throw e;
}
}
}
const hash2 = `timestamp-${Date.now()}-${Math.random().toString(16).slice(2)}`;
const tempFileName = nodeModulesDir ? path5.resolve(
nodeModulesDir,
`.vite-temp/${path5.basename(fileName)}.${hash2}.${isESM ? "mjs" : "cjs"}`
) : `${fileName}.${hash2}.mjs`;
const getOutputFile = options.getOutputFile || defaultGetOutputFile;
const outfile = getOutputFile(tempFileName, options.format);
await fsp.writeFile(outfile, bundledCode);
let mod;
const req = options.require || dynamicImport;
try {
mod = await req(
options.format === "esm" ? pathToFileURL(outfile).href : outfile,
{ format: options.format }
);
return mod;
} finally {
if (!options?.preserveTemporaryFile) {
fs4.unlink(outfile, () => {
});
}
}
} else {
const extension = path5.extname(fileName);
const realFileName = await promisifiedRealpath(fileName);
const loaderExt = extension in _require2.extensions ? extension : ".js";
const defaultLoader = _require2.extensions[loaderExt];
_require2.extensions[loaderExt] = (module, filename) => {
if (filename === realFileName) {
;
module._compile(bundledCode, filename);
} else {
defaultLoader(module, filename);
}
};
delete _require2.cache[_require2.resolve(fileName)];
const raw = _require2(fileName);
_require2.extensions[loaderExt] = defaultLoader;
return raw.__esModule ? raw.default : raw;
}
}
async function bundleRequire(options) {
const resolvedPath = path5.isAbsolute(options.filepath) ? options.filepath : path5.resolve(options.cwd || process4.cwd(), options.filepath);
const isESM = typeof process4.versions.deno === "string" || isFilePathESM(resolvedPath);
if (options.tsconfig !== false) {
options.tsconfig = options.tsconfig ?? getTsconfig(options.cwd, "tsconfig.json")?.path ?? void 0;
} else {
options.tsconfig = void 0;
}
if (!options.format) {
options.format = isESM ? "esm" : "cjs";
}
const internalOptions = {
...options,
isESM,
format: options.format,
tsconfig: options.tsconfig
};
const bundled = await bundleFile(
resolvedPath,
internalOptions
);
const mod = await loadFromBundledFile(
resolvedPath,
bundled.code,
internalOptions
);
return {
mod,
dependencies: bundled.dependencies
};
}
export {
bundleFile,
bundleRequire,
configDefaults,
loadFromBundledFile
};