UNPKG

rolldown

Version:

Fast JavaScript/TypeScript bundler in Rust with Rollup-compatible API.

1,236 lines (1,211 loc) • 109 kB
"use strict"; const require_chunk = require('./chunk-qZFfknuJ.cjs'); const require_parse_ast_index = require('./parse-ast-index-C8v5UEr2.cjs'); const node_path = require_chunk.__toESM(require("node:path")); const valibot = require_chunk.__toESM(require("valibot")); const __valibot_to_json_schema = require_chunk.__toESM(require("@valibot/to-json-schema")); const node_buffer = require_chunk.__toESM(require("node:buffer")); const node_worker_threads = require_chunk.__toESM(require("node:worker_threads")); const node_os = require_chunk.__toESM(require("node:os")); //#region src/utils/define-config.ts function defineConfig(config) { return config; } //#endregion //#region src/utils/misc.ts function arraify(value) { return Array.isArray(value) ? value : [value]; } function isNullish(value) { return value === null || value === void 0; } function unimplemented(info) { if (info) throw new Error(`unimplemented: ${info}`); throw new Error("unimplemented"); } function unreachable(info) { if (info) throw new Error(`unreachable: ${info}`); throw new Error("unreachable"); } function unsupported(info) { throw new Error(`UNSUPPORTED: ${info}`); } function noop(..._args) {} //#endregion //#region src/log/logging.ts const LOG_LEVEL_SILENT = "silent"; const LOG_LEVEL_ERROR = "error"; const LOG_LEVEL_WARN = "warn"; const LOG_LEVEL_INFO = "info"; const LOG_LEVEL_DEBUG = "debug"; const logLevelPriority = { [LOG_LEVEL_DEBUG]: 0, [LOG_LEVEL_INFO]: 1, [LOG_LEVEL_WARN]: 2, [LOG_LEVEL_SILENT]: 3 }; //#endregion //#region src/log/log-handler.ts const normalizeLog = (log) => typeof log === "string" ? { message: log } : typeof log === "function" ? normalizeLog(log()) : log; function getLogHandler(level, code, logger, pluginName, logLevel) { if (logLevelPriority[level] < logLevelPriority[logLevel]) return noop; return (log, pos) => { if (pos != null) logger(LOG_LEVEL_WARN, require_parse_ast_index.logInvalidLogPosition(pluginName)); log = normalizeLog(log); if (log.code && !log.pluginCode) log.pluginCode = log.code; log.code = code; log.plugin = pluginName; logger(level, log); }; } //#endregion //#region src/utils/normalize-hook.ts function normalizeHook(hook) { if (typeof hook === "function" || typeof hook === "string") return { handler: hook, options: {}, meta: {} }; if (typeof hook === "object" && hook !== null) { const { handler, order,...options } = hook; return { handler, options, meta: { order } }; } unreachable("Invalid hook type"); } //#endregion //#region src/log/logger.ts function getLogger(plugins, onLog, logLevel) { const minimalPriority = logLevelPriority[logLevel]; const logger = (level, log, skipped = new Set()) => { const logPriority = logLevelPriority[level]; if (logPriority < minimalPriority) return; for (const plugin of getSortedPlugins("onLog", plugins)) { if (skipped.has(plugin)) continue; const { onLog: pluginOnLog } = plugin; if (pluginOnLog) { const getLogHandler$1 = (level$1) => { if (logLevelPriority[level$1] < minimalPriority) return () => {}; return (log$1) => logger(level$1, normalizeLog(log$1), new Set(skipped).add(plugin)); }; const handler = "handler" in pluginOnLog ? pluginOnLog.handler : pluginOnLog; if (handler.call({ debug: getLogHandler$1(LOG_LEVEL_DEBUG), error: (log$1) => require_parse_ast_index.error(normalizeLog(log$1)), info: getLogHandler$1(LOG_LEVEL_INFO), meta: { rollupVersion: "4.23.0", rolldownVersion: VERSION, watchMode: false }, warn: getLogHandler$1(LOG_LEVEL_WARN), pluginName: plugin.name || "unknown" }, level, log) === false) return; } } onLog(level, log); }; return logger; } const getOnLog = (config, logLevel, printLog = defaultPrintLog) => { const { onwarn, onLog } = config; const defaultOnLog = getDefaultOnLog(printLog, onwarn); if (onLog) { const minimalPriority = logLevelPriority[logLevel]; return (level, log) => onLog(level, addLogToString(log), (level$1, handledLog) => { if (level$1 === LOG_LEVEL_ERROR) return require_parse_ast_index.error(normalizeLog(handledLog)); if (logLevelPriority[level$1] >= minimalPriority) defaultOnLog(level$1, normalizeLog(handledLog)); }); } return defaultOnLog; }; const getDefaultOnLog = (printLog, onwarn) => onwarn ? (level, log) => { if (level === LOG_LEVEL_WARN) onwarn(addLogToString(log), (warning) => printLog(LOG_LEVEL_WARN, normalizeLog(warning))); else printLog(level, log); } : printLog; const addLogToString = (log) => { Object.defineProperty(log, "toString", { value: () => getExtendedLogMessage(log), writable: true }); return log; }; const defaultPrintLog = (level, log) => { const message = getExtendedLogMessage(log); switch (level) { case LOG_LEVEL_WARN: return console.warn(message); case LOG_LEVEL_DEBUG: return console.debug(message); default: return console.info(message); } }; const getExtendedLogMessage = (log) => { let prefix = ""; if (log.plugin) prefix += `(${log.plugin} plugin) `; if (log.loc) prefix += `${relativeId(log.loc.file)} (${log.loc.line}:${log.loc.column}) `; return prefix + log.message; }; function relativeId(id) { if (!node_path.default.isAbsolute(id)) return id; return node_path.default.relative(node_path.default.resolve(), id); } //#endregion //#region src/builtin-plugin/utils.ts function makeBuiltinPluginCallable(plugin) { let callablePlugin = new require_parse_ast_index.import_binding.BindingCallableBuiltinPlugin(bindingifyBuiltInPlugin(plugin)); const wrappedPlugin = plugin; for (const key in callablePlugin) wrappedPlugin[key] = function(...args) { return callablePlugin[key](...args); }; return wrappedPlugin; } function bindingifyBuiltInPlugin(plugin) { return { __name: plugin.name, options: plugin._options }; } //#endregion //#region src/builtin-plugin/constructors.ts var BuiltinPlugin = class { constructor(name, _options) { this.name = name; this._options = _options; } }; function modulePreloadPolyfillPlugin(config) { return new BuiltinPlugin("builtin:module-preload-polyfill", config); } function dynamicImportVarsPlugin() { return new BuiltinPlugin("builtin:dynamic-import-vars"); } function importGlobPlugin(config) { return new BuiltinPlugin("builtin:import-glob", config); } function manifestPlugin(config) { return new BuiltinPlugin("builtin:manifest", config); } function wasmHelperPlugin() { return new BuiltinPlugin("builtin:wasm-helper"); } function wasmFallbackPlugin() { return new BuiltinPlugin("builtin:wasm-fallback"); } function loadFallbackPlugin() { return new BuiltinPlugin("builtin:load-fallback"); } function jsonPlugin(config) { return new BuiltinPlugin("builtin:json", config); } function buildImportAnalysisPlugin(config) { return new BuiltinPlugin("builtin:build-import-analysis", config); } function viteResolvePlugin(config) { const builtinPlugin = new BuiltinPlugin("builtin:vite-resolve", { ...config, runtime: process.versions.deno ? "deno" : process.versions.bun ? "bun" : "node" }); return makeBuiltinPluginCallable(builtinPlugin); } function moduleFederationPlugin(config) { return new BuiltinPlugin("builtin:module-federation", { ...config, remotes: config.remotes && Object.entries(config.remotes).map(([name, remote]) => { if (typeof remote === "string") { const [entryGlobalName] = remote.split("@"); const entry = remote.replace(entryGlobalName + "@", ""); return { entry, name, entryGlobalName }; } return { ...remote, name: remote.name ?? name }; }), manifest: config.manifest === false ? void 0 : config.manifest === true ? {} : config.manifest }); } function isolatedDeclarationPlugin(config) { return new BuiltinPlugin("builtin:isolated-declaration", config); } //#endregion //#region src/utils/async-flatten.ts async function asyncFlatten(array) { do array = (await Promise.all(array)).flat(Infinity); while (array.some((v) => v?.then)); return array; } //#endregion //#region src/constants/plugin.ts const ENUMERATED_INPUT_PLUGIN_HOOK_NAMES = [ "options", "buildStart", "resolveId", "load", "transform", "moduleParsed", "buildEnd", "onLog", "resolveDynamicImport", "closeBundle", "closeWatcher", "watchChange" ]; const ENUMERATED_OUTPUT_PLUGIN_HOOK_NAMES = [ "augmentChunkHash", "outputOptions", "renderChunk", "renderStart", "renderError", "writeBundle", "generateBundle" ]; const ENUMERATED_PLUGIN_HOOK_NAMES = [ ...ENUMERATED_INPUT_PLUGIN_HOOK_NAMES, ...ENUMERATED_OUTPUT_PLUGIN_HOOK_NAMES, "footer", "banner", "intro", "outro" ]; const DEFINED_HOOK_NAMES = { [ENUMERATED_PLUGIN_HOOK_NAMES[0]]: ENUMERATED_PLUGIN_HOOK_NAMES[0], [ENUMERATED_PLUGIN_HOOK_NAMES[1]]: ENUMERATED_PLUGIN_HOOK_NAMES[1], [ENUMERATED_PLUGIN_HOOK_NAMES[2]]: ENUMERATED_PLUGIN_HOOK_NAMES[2], [ENUMERATED_PLUGIN_HOOK_NAMES[3]]: ENUMERATED_PLUGIN_HOOK_NAMES[3], [ENUMERATED_PLUGIN_HOOK_NAMES[4]]: ENUMERATED_PLUGIN_HOOK_NAMES[4], [ENUMERATED_PLUGIN_HOOK_NAMES[5]]: ENUMERATED_PLUGIN_HOOK_NAMES[5], [ENUMERATED_PLUGIN_HOOK_NAMES[6]]: ENUMERATED_PLUGIN_HOOK_NAMES[6], [ENUMERATED_PLUGIN_HOOK_NAMES[7]]: ENUMERATED_PLUGIN_HOOK_NAMES[7], [ENUMERATED_PLUGIN_HOOK_NAMES[8]]: ENUMERATED_PLUGIN_HOOK_NAMES[8], [ENUMERATED_PLUGIN_HOOK_NAMES[9]]: ENUMERATED_PLUGIN_HOOK_NAMES[9], [ENUMERATED_PLUGIN_HOOK_NAMES[10]]: ENUMERATED_PLUGIN_HOOK_NAMES[10], [ENUMERATED_PLUGIN_HOOK_NAMES[11]]: ENUMERATED_PLUGIN_HOOK_NAMES[11], [ENUMERATED_PLUGIN_HOOK_NAMES[12]]: ENUMERATED_PLUGIN_HOOK_NAMES[12], [ENUMERATED_PLUGIN_HOOK_NAMES[13]]: ENUMERATED_PLUGIN_HOOK_NAMES[13], [ENUMERATED_PLUGIN_HOOK_NAMES[14]]: ENUMERATED_PLUGIN_HOOK_NAMES[14], [ENUMERATED_PLUGIN_HOOK_NAMES[15]]: ENUMERATED_PLUGIN_HOOK_NAMES[15], [ENUMERATED_PLUGIN_HOOK_NAMES[16]]: ENUMERATED_PLUGIN_HOOK_NAMES[16], [ENUMERATED_PLUGIN_HOOK_NAMES[17]]: ENUMERATED_PLUGIN_HOOK_NAMES[17], [ENUMERATED_PLUGIN_HOOK_NAMES[18]]: ENUMERATED_PLUGIN_HOOK_NAMES[18], [ENUMERATED_PLUGIN_HOOK_NAMES[19]]: ENUMERATED_PLUGIN_HOOK_NAMES[19], [ENUMERATED_PLUGIN_HOOK_NAMES[20]]: ENUMERATED_PLUGIN_HOOK_NAMES[20], [ENUMERATED_PLUGIN_HOOK_NAMES[21]]: ENUMERATED_PLUGIN_HOOK_NAMES[21], [ENUMERATED_PLUGIN_HOOK_NAMES[22]]: ENUMERATED_PLUGIN_HOOK_NAMES[22] }; //#endregion //#region src/utils/normalize-plugin-option.ts const normalizePluginOption = async (plugins) => (await asyncFlatten([plugins])).filter(Boolean); function checkOutputPluginOption(plugins, onLog) { for (const plugin of plugins) for (const hook of ENUMERATED_INPUT_PLUGIN_HOOK_NAMES) if (hook in plugin) { delete plugin[hook]; onLog(LOG_LEVEL_WARN, require_parse_ast_index.logInputHookInOutputPlugin(plugin.name, hook)); } return plugins; } function normalizePlugins(plugins, anonymousPrefix) { for (const [index, plugin] of plugins.entries()) { if ("_parallel" in plugin) continue; if (plugin instanceof BuiltinPlugin) continue; if (!plugin.name) plugin.name = `${anonymousPrefix}${index + 1}`; } return plugins; } const ANONYMOUS_PLUGIN_PREFIX = "at position "; const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = "at output position "; //#endregion //#region src/plugin/plugin-driver.ts var PluginDriver = class { static async callOptionsHook(inputOptions) { const logLevel = inputOptions.logLevel || LOG_LEVEL_INFO; const plugins = getSortedPlugins("options", getObjectPlugins(await normalizePluginOption(inputOptions.plugins))); const logger = getLogger(plugins, getOnLog(inputOptions, logLevel), logLevel); for (const plugin of plugins) { const name = plugin.name || "unknown"; const options = plugin.options; if (options) { const { handler } = normalizeHook(options); const result = await handler.call({ debug: getLogHandler(LOG_LEVEL_DEBUG, "PLUGIN_LOG", logger, name, logLevel), error: (e) => require_parse_ast_index.error(require_parse_ast_index.logPluginError(normalizeLog(e), name, { hook: "onLog" })), info: getLogHandler(LOG_LEVEL_INFO, "PLUGIN_LOG", logger, name, logLevel), meta: { rollupVersion: "4.23.0", rolldownVersion: VERSION, watchMode: false }, warn: getLogHandler(LOG_LEVEL_WARN, "PLUGIN_WARNING", logger, name, logLevel), pluginName: name }, inputOptions); if (result) inputOptions = result; } } return inputOptions; } static callOutputOptionsHook(rawPlugins, outputOptions) { const sortedPlugins = getSortedPlugins("outputOptions", getObjectPlugins(rawPlugins)); for (const plugin of sortedPlugins) { const options = plugin.outputOptions; if (options) { const { handler } = normalizeHook(options); const result = handler.call(null, outputOptions); if (result) outputOptions = result; } } return outputOptions; } }; function getObjectPlugins(plugins) { return plugins.filter((plugin) => { if (!plugin) return void 0; if ("_parallel" in plugin) return void 0; if (plugin instanceof BuiltinPlugin) return void 0; return plugin; }); } function getSortedPlugins(hookName, plugins) { const pre = []; const normal = []; const post = []; for (const plugin of plugins) { const hook = plugin[hookName]; if (hook) { if (typeof hook === "object") { if (hook.order === "pre") { pre.push(plugin); continue; } if (hook.order === "post") { post.push(plugin); continue; } } normal.push(plugin); } } return [ ...pre, ...normal, ...post ]; } //#endregion //#region src/utils/validator.ts const StringOrRegExpSchema = valibot.union([valibot.string(), valibot.instance(RegExp)]); const LogLevelSchema = valibot.union([ valibot.literal("debug"), valibot.literal("info"), valibot.literal("warn") ]); const LogLevelOptionSchema = valibot.union([LogLevelSchema, valibot.literal("silent")]); const LogLevelWithErrorSchema = valibot.union([LogLevelSchema, valibot.literal("error")]); const RollupLogSchema = valibot.any(); const RollupLogWithStringSchema = valibot.union([RollupLogSchema, valibot.string()]); const InputOptionSchema = valibot.union([ valibot.string(), valibot.array(valibot.string()), valibot.record(valibot.string(), valibot.string()) ]); const ExternalSchema = valibot.union([ StringOrRegExpSchema, valibot.array(StringOrRegExpSchema), valibot.pipe(valibot.function(), valibot.args(valibot.tuple([ valibot.string(), valibot.optional(valibot.string()), valibot.boolean() ])), valibot.returns(valibot.nullish(valibot.boolean()))) ]); const ModuleTypesSchema = valibot.record(valibot.string(), valibot.union([ valibot.literal("base64"), valibot.literal("binary"), valibot.literal("css"), valibot.literal("dataurl"), valibot.literal("empty"), valibot.literal("js"), valibot.literal("json"), valibot.literal("jsx"), valibot.literal("text"), valibot.literal("ts"), valibot.literal("tsx") ])); const JsxOptionsSchema = valibot.strictObject({ development: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Development specific information")), factory: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Jsx element transformation")), fragment: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Jsx fragment transformation")), importSource: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Import the factory of element and fragment if mode is classic")), jsxImportSource: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Import the factory of element and fragment if mode is automatic")), mode: valibot.pipe(valibot.optional(valibot.union([ valibot.literal("classic"), valibot.literal("automatic"), valibot.literal("preserve") ])), valibot.description("Jsx transformation mode")), refresh: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("React refresh transformation")) }); const HelperModeSchema = valibot.union([valibot.literal("Runtime"), valibot.literal("External")]); const DecoratorOptionSchema = valibot.object({ legacy: valibot.optional(valibot.boolean()), emitDecoratorMetadata: valibot.optional(valibot.boolean()) }); const HelpersSchema = valibot.object({ mode: valibot.optional(HelperModeSchema) }); const RewriteImportExtensionsSchema = valibot.union([ valibot.literal("rewrite"), valibot.literal("remove"), valibot.boolean() ]); const TypescriptSchema = valibot.object({ jsxPragma: valibot.optional(valibot.string()), jsxPragmaFrag: valibot.optional(valibot.string()), onlyRemoveTypeImports: valibot.optional(valibot.boolean()), allowNamespaces: valibot.optional(valibot.boolean()), allowDeclareFields: valibot.optional(valibot.boolean()), declaration: valibot.optional(valibot.object({ stripInternal: valibot.optional(valibot.boolean()), sourcemap: valibot.optional(valibot.boolean()) })), rewriteImportExtensions: valibot.optional(RewriteImportExtensionsSchema) }); const AssumptionsSchema = valibot.object({ ignoreFunctionLength: valibot.optional(valibot.boolean()), noDocumentAll: valibot.optional(valibot.boolean()), objectRestNoSymbols: valibot.optional(valibot.boolean()), pureGetters: valibot.optional(valibot.boolean()), setPublicClassFields: valibot.optional(valibot.boolean()) }); const TransformOptionsSchema = valibot.object({ assumptions: valibot.optional(AssumptionsSchema), typescript: valibot.optional(TypescriptSchema), helpers: valibot.optional(HelpersSchema), decorators: valibot.optional(DecoratorOptionSchema) }); const WatchOptionsSchema = valibot.strictObject({ chokidar: valibot.optional(valibot.never(`The "watch.chokidar" option is deprecated, please use "watch.notify" instead of it`)), exclude: valibot.optional(valibot.union([StringOrRegExpSchema, valibot.array(StringOrRegExpSchema)])), include: valibot.optional(valibot.union([StringOrRegExpSchema, valibot.array(StringOrRegExpSchema)])), notify: valibot.pipe(valibot.optional(valibot.strictObject({ compareContents: valibot.optional(valibot.boolean()), pollInterval: valibot.optional(valibot.number()) })), valibot.description("Notify options")), skipWrite: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Skip the bundle.write() step")), buildDelay: valibot.pipe(valibot.optional(valibot.number()), valibot.description("Throttle watch rebuilds")) }); const ChecksOptionsSchema = valibot.strictObject({ circularDependency: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Whether to emit warning when detecting circular dependency")), eval: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Whether to emit warning when detecting eval")), missingGlobalName: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Whether to emit warning when detecting missing global name")), missingNameOptionForIifeExport: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Whether to emit warning when detecting missing name option for iife export")), mixedExport: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Whether to emit warning when detecting mixed export")), unresolvedEntry: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Whether to emit warning when detecting unresolved entry")), unresolvedImport: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Whether to emit warning when detecting unresolved import")), filenameConflict: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Whether to emit warning when detecting filename conflict")), commonJsVariableInEsm: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Whether to emit warning when detecting common js variable in esm")), importIsUndefined: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Whether to emit warning when detecting import is undefined")), configurationFieldConflict: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Whether to emit warning when detecting configuration field conflict")) }); const MinifyOptionsSchema = valibot.strictObject({ mangle: valibot.boolean(), compress: valibot.boolean(), deadCodeElimination: valibot.boolean(), removeWhitespace: valibot.boolean() }); const ResolveOptionsSchema = valibot.strictObject({ alias: valibot.optional(valibot.record(valibot.string(), valibot.union([valibot.string(), valibot.array(valibot.string())]))), aliasFields: valibot.optional(valibot.array(valibot.array(valibot.string()))), conditionNames: valibot.optional(valibot.array(valibot.string())), extensionAlias: valibot.optional(valibot.record(valibot.string(), valibot.array(valibot.string()))), exportsFields: valibot.optional(valibot.array(valibot.array(valibot.string()))), extensions: valibot.optional(valibot.array(valibot.string())), mainFields: valibot.optional(valibot.array(valibot.string())), mainFiles: valibot.optional(valibot.array(valibot.string())), modules: valibot.optional(valibot.array(valibot.string())), symlinks: valibot.optional(valibot.boolean()), tsconfigFilename: valibot.optional(valibot.string()) }); const TreeshakingOptionsSchema = valibot.union([valibot.boolean(), valibot.looseObject({ annotations: valibot.optional(valibot.boolean()), manualPureFunctions: valibot.optional(valibot.array(valibot.string())), unknownGlobalSideEffects: valibot.optional(valibot.boolean()) })]); const OnLogSchema = valibot.pipe(valibot.function(), valibot.args(valibot.tuple([ LogLevelSchema, RollupLogSchema, valibot.pipe(valibot.function(), valibot.args(valibot.tuple([LogLevelWithErrorSchema, RollupLogWithStringSchema]))) ]))); const OnwarnSchema = valibot.pipe(valibot.function(), valibot.args(valibot.tuple([RollupLogSchema, valibot.pipe(valibot.function(), valibot.args(valibot.tuple([valibot.union([RollupLogWithStringSchema, valibot.pipe(valibot.function(), valibot.returns(RollupLogWithStringSchema))])])))]))); const InputOptionsSchema = valibot.strictObject({ input: valibot.optional(InputOptionSchema), plugins: valibot.optional(valibot.custom(() => true)), external: valibot.optional(ExternalSchema), resolve: valibot.optional(ResolveOptionsSchema), cwd: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Current working directory")), platform: valibot.pipe(valibot.optional(valibot.union([ valibot.literal("browser"), valibot.literal("neutral"), valibot.literal("node") ])), valibot.description(`Platform for which the code should be generated (node, ${require_parse_ast_index.colors.underline("browser")}, neutral)`)), shimMissingExports: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Create shim variables for missing exports")), treeshake: valibot.optional(TreeshakingOptionsSchema), logLevel: valibot.pipe(valibot.optional(LogLevelOptionSchema), valibot.description(`Log level (${require_parse_ast_index.colors.dim("silent")}, ${require_parse_ast_index.colors.underline(require_parse_ast_index.colors.gray("info"))}, debug, ${require_parse_ast_index.colors.yellow("warn")})`)), onLog: valibot.optional(OnLogSchema), onwarn: valibot.optional(OnwarnSchema), moduleTypes: valibot.pipe(valibot.optional(ModuleTypesSchema), valibot.description("Module types for customized extensions")), experimental: valibot.optional(valibot.strictObject({ disableLiveBindings: valibot.optional(valibot.boolean()), enableComposingJsPlugins: valibot.optional(valibot.boolean()), resolveNewUrlToAsset: valibot.optional(valibot.boolean()), strictExecutionOrder: valibot.optional(valibot.boolean()), hmr: valibot.optional(valibot.boolean()) })), define: valibot.pipe(valibot.optional(valibot.record(valibot.string(), valibot.string())), valibot.description("Define global variables")), inject: valibot.optional(valibot.record(valibot.string(), valibot.union([valibot.string(), valibot.tuple([valibot.string(), valibot.string()])]))), profilerNames: valibot.optional(valibot.boolean()), jsx: valibot.optional(valibot.union([ valibot.boolean(), JsxOptionsSchema, valibot.string("react"), valibot.string("react-jsx"), valibot.string("preserve") ])), transform: valibot.optional(TransformOptionsSchema), watch: valibot.optional(valibot.union([WatchOptionsSchema, valibot.literal(false)])), dropLabels: valibot.pipe(valibot.optional(valibot.array(valibot.string())), valibot.description("Remove labeled statements with these label names")), checks: valibot.optional(ChecksOptionsSchema), keepNames: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Keep function/class name")) }); const InputCliOverrideSchema = valibot.strictObject({ external: valibot.pipe(valibot.optional(valibot.array(valibot.string())), valibot.description("Comma-separated list of module ids to exclude from the bundle `<module-id>,...`")), inject: valibot.pipe(valibot.optional(valibot.record(valibot.string(), valibot.string())), valibot.description("Inject import statements on demand")), treeshake: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("enable treeshaking")), jsx: valibot.pipe(valibot.optional(JsxOptionsSchema), valibot.description("enable jsx")) }); const InputCliOptionsSchema = valibot.omit(valibot.strictObject({ ...InputOptionsSchema.entries, ...InputCliOverrideSchema.entries }), [ "input", "plugins", "onwarn", "onLog", "resolve", "experimental", "profilerNames", "watch" ]); var ESTarget = /* @__PURE__ */ function(ESTarget$1) { ESTarget$1["ES6"] = "es6"; ESTarget$1["ES2015"] = "es2015"; ESTarget$1["ES2016"] = "es2016"; ESTarget$1["ES2017"] = "es2017"; ESTarget$1["ES2018"] = "es2018"; ESTarget$1["ES2019"] = "es2019"; ESTarget$1["ES2020"] = "es2020"; ESTarget$1["ES2021"] = "es2021"; ESTarget$1["ES2022"] = "es2022"; ESTarget$1["ES2023"] = "es2023"; ESTarget$1["ES2024"] = "es2024"; ESTarget$1["ESNext"] = "esnext"; return ESTarget$1; }(ESTarget || {}); const ModuleFormatSchema = valibot.union([ valibot.literal("es"), valibot.literal("cjs"), valibot.literal("esm"), valibot.literal("module"), valibot.literal("commonjs"), valibot.literal("iife"), valibot.literal("umd") ]); const AddonFunctionSchema = valibot.pipe(valibot.function(), valibot.args(valibot.tuple([valibot.custom(() => true)])), valibot.returnsAsync(valibot.unionAsync([valibot.string(), valibot.pipeAsync(valibot.promise(), valibot.awaitAsync(), valibot.string())]))); const ChunkFileNamesSchema = valibot.union([valibot.string(), valibot.pipe(valibot.function(), valibot.args(valibot.tuple([valibot.custom(() => true)])), valibot.returns(valibot.string()))]); const AssetFileNamesSchema = valibot.union([valibot.string(), valibot.pipe(valibot.function(), valibot.args(valibot.tuple([valibot.custom(() => true)])), valibot.returns(valibot.string()))]); const SanitizeFileNameSchema = valibot.union([valibot.boolean(), valibot.pipe(valibot.function(), valibot.args(valibot.tuple([valibot.string()])), valibot.returns(valibot.string()))]); const GlobalsFunctionSchema = valibot.pipe(valibot.function(), valibot.args(valibot.tuple([valibot.string()])), valibot.returns(valibot.string())); const AdvancedChunksSchema = valibot.strictObject({ minSize: valibot.optional(valibot.number()), maxSize: valibot.optional(valibot.number()), minModuleSize: valibot.optional(valibot.number()), maxModuleSize: valibot.optional(valibot.number()), minShareCount: valibot.optional(valibot.number()), groups: valibot.optional(valibot.array(valibot.strictObject({ name: valibot.string(), test: valibot.optional(valibot.union([valibot.string(), valibot.instance(RegExp)])), priority: valibot.optional(valibot.number()), minSize: valibot.optional(valibot.number()), minShareCount: valibot.optional(valibot.number()), maxSize: valibot.optional(valibot.number()), minModuleSize: valibot.optional(valibot.number()), maxModuleSize: valibot.optional(valibot.number()) }))) }); const OutputOptionsSchema = valibot.strictObject({ dir: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Output directory, defaults to `dist` if `file` is not set")), file: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Single output file")), exports: valibot.pipe(valibot.optional(valibot.union([ valibot.literal("auto"), valibot.literal("named"), valibot.literal("default"), valibot.literal("none") ])), valibot.description(`Specify a export mode (${require_parse_ast_index.colors.underline("auto")}, named, default, none)`)), hashCharacters: valibot.pipe(valibot.optional(valibot.union([ valibot.literal("base64"), valibot.literal("base36"), valibot.literal("hex") ])), valibot.description("Use the specified character set for file hashes")), format: valibot.pipe(valibot.optional(ModuleFormatSchema), valibot.description(`Output format of the generated bundle (supports ${require_parse_ast_index.colors.underline("esm")}, cjs, and iife)`)), sourcemap: valibot.pipe(valibot.optional(valibot.union([ valibot.boolean(), valibot.literal("inline"), valibot.literal("hidden") ])), valibot.description(`Generate sourcemap (\`-s inline\` for inline, or ${require_parse_ast_index.colors.bold("pass the `-s` on the last argument if you want to generate `.map` file")})`)), sourcemapDebugIds: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Inject sourcemap debug IDs")), sourcemapIgnoreList: valibot.optional(valibot.union([valibot.boolean(), valibot.custom(() => true)])), sourcemapPathTransform: valibot.optional(valibot.custom(() => true)), banner: valibot.optional(valibot.union([valibot.string(), AddonFunctionSchema])), footer: valibot.optional(valibot.union([valibot.string(), AddonFunctionSchema])), intro: valibot.optional(valibot.union([valibot.string(), AddonFunctionSchema])), outro: valibot.optional(valibot.union([valibot.string(), AddonFunctionSchema])), extend: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Extend global variable defined by name in IIFE / UMD formats")), esModule: valibot.optional(valibot.union([valibot.boolean(), valibot.literal("if-default-prop")])), assetFileNames: valibot.optional(AssetFileNamesSchema), entryFileNames: valibot.optional(ChunkFileNamesSchema), chunkFileNames: valibot.optional(ChunkFileNamesSchema), cssEntryFileNames: valibot.optional(ChunkFileNamesSchema), cssChunkFileNames: valibot.optional(ChunkFileNamesSchema), sanitizeFileName: valibot.optional(SanitizeFileNameSchema), minify: valibot.pipe(valibot.optional(valibot.union([ valibot.boolean(), valibot.string("dce-only"), MinifyOptionsSchema ])), valibot.description("Minify the bundled file")), name: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Name for UMD / IIFE format outputs")), globals: valibot.pipe(valibot.optional(valibot.union([valibot.record(valibot.string(), valibot.string()), GlobalsFunctionSchema])), valibot.description("Global variable of UMD / IIFE dependencies (syntax: `key=value`)")), externalLiveBindings: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("external live bindings")), inlineDynamicImports: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Inline dynamic imports")), advancedChunks: valibot.optional(AdvancedChunksSchema), comments: valibot.pipe(valibot.optional(valibot.union([valibot.literal("none"), valibot.literal("preserve-legal")])), valibot.description("Control comments in the output")), target: valibot.pipe(valibot.optional(valibot.enum(ESTarget)), valibot.description("The JavaScript target environment")), plugins: valibot.optional(valibot.custom(() => true)) }); const getAddonDescription = (placement, wrapper) => { return `Code to insert the ${require_parse_ast_index.colors.bold(placement)} of the bundled file (${require_parse_ast_index.colors.bold(wrapper)} the wrapper function)`; }; const OutputCliOverrideSchema = valibot.strictObject({ assetFileNames: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Name pattern for asset files")), entryFileNames: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Name pattern for emitted entry chunks")), chunkFileNames: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Name pattern for emitted secondary chunks")), cssEntryFileNames: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Name pattern for emitted css entry chunks")), cssChunkFileNames: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Name pattern for emitted css secondary chunks")), sanitizeFileName: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Sanitize file name")), banner: valibot.pipe(valibot.optional(valibot.string()), valibot.description(getAddonDescription("top", "outside"))), footer: valibot.pipe(valibot.optional(valibot.string()), valibot.description(getAddonDescription("bottom", "outside"))), intro: valibot.pipe(valibot.optional(valibot.string()), valibot.description(getAddonDescription("top", "inside"))), outro: valibot.pipe(valibot.optional(valibot.string()), valibot.description(getAddonDescription("bottom", "inside"))), esModule: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Always generate `__esModule` marks in non-ESM formats, defaults to `if-default-prop` (use `--no-esModule` to always disable)")), globals: valibot.pipe(valibot.optional(valibot.record(valibot.string(), valibot.string())), valibot.description("Global variable of UMD / IIFE dependencies (syntax: `key=value`)")), advancedChunks: valibot.pipe(valibot.optional(valibot.strictObject({ minSize: valibot.pipe(valibot.optional(valibot.number()), valibot.description("Minimum size of the chunk")), minShareCount: valibot.pipe(valibot.optional(valibot.number()), valibot.description("Minimum share count of the chunk")) })), valibot.description("Global variable of UMD / IIFE dependencies (syntax: `key=value`)")), minify: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Minify the bundled file")) }); const OutputCliOptionsSchema = valibot.omit(valibot.strictObject({ ...OutputOptionsSchema.entries, ...OutputCliOverrideSchema.entries }), [ "sourcemapIgnoreList", "sourcemapPathTransform", "plugins" ]); const CliOptionsSchema = valibot.strictObject({ config: valibot.pipe(valibot.optional(valibot.union([valibot.string(), valibot.boolean()])), valibot.description("Path to the config file (default: `rolldown.config.js`)")), help: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Show help")), version: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Show version number")), watch: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Watch files in bundle and rebuild on changes")), ...InputCliOptionsSchema.entries, ...OutputCliOptionsSchema.entries }); function validateCliOptions(options) { let parsed = valibot.safeParse(CliOptionsSchema, options); return [parsed.output, parsed.issues?.map((issue) => { const option = issue.path?.map((pathItem) => pathItem.key).join(" "); return `Invalid value for option ${option}: ${issue.message}`; })]; } const inputHelperMsgRecord = { output: { ignored: true } }; const outputHelperMsgRecord = {}; function validateOption(key, options) { if (process.env.ROLLDOWN_OPTIONS_VALIDATION === "loose") return; let parsed = valibot.safeParse(key === "input" ? InputOptionsSchema : OutputOptionsSchema, options); if (!parsed.success) { const errors = parsed.issues.map((issue) => { const issuePaths = issue.path.map((path$2) => path$2.key); let issueMsg = issue.message; if (issue.type === "union") { const subIssue = issue.issues?.find((i) => !(i.type !== issue.received && i.input === issue.input)); if (subIssue) { if (subIssue.path) issuePaths.push(subIssue.path.map((path$2) => path$2.key)); issueMsg = subIssue.message; } } const stringPath = issuePaths.join("."); const helper = key === "input" ? inputHelperMsgRecord[stringPath] : outputHelperMsgRecord[stringPath]; if (helper && helper.ignored) return ""; return `- For the "${stringPath}". ${issueMsg}. ${helper ? helper.msg : ""}`; }).filter(Boolean); if (errors.length) throw new Error(`Failed validate ${key} options.\n` + errors.join("\n")); } } function getInputCliKeys() { return valibot.keyof(InputCliOptionsSchema).options; } function getOutputCliKeys() { return valibot.keyof(OutputCliOptionsSchema).options; } function getJsonSchema() { return (0, __valibot_to_json_schema.toJsonSchema)(CliOptionsSchema); } //#endregion //#region src/utils/asset-source.ts function transformAssetSource(bindingAssetSource$1) { return bindingAssetSource$1.inner; } function bindingAssetSource(source) { return { inner: source }; } //#endregion //#region src/types/sourcemap.ts function bindingifySourcemap$1(map) { if (map == null) return; return { inner: typeof map === "string" ? map : { file: map.file ?? void 0, mappings: map.mappings, sourceRoot: "sourceRoot" in map ? map.sourceRoot ?? void 0 : void 0, sources: map.sources?.map((s) => s ?? void 0), sourcesContent: map.sourcesContent?.map((s) => s ?? void 0), names: map.names, x_google_ignoreList: map.x_google_ignoreList, debugId: "debugId" in map ? map.debugId : void 0 } }; } //#endregion //#region src/utils/error.ts function normalizeErrors(rawErrors) { const errors = rawErrors.map((e) => e instanceof Error ? e : Object.assign(new Error(), { kind: e.kind, message: e.message, stack: void 0 })); let summary = `Build failed with ${errors.length} error${errors.length < 2 ? "" : "s"}:\n`; for (let i = 0; i < errors.length; i++) { summary += "\n"; if (i >= 5) { summary += "..."; break; } summary += getErrorMessage(errors[i]); } const wrapper = new Error(summary); Object.defineProperty(wrapper, "errors", { configurable: true, enumerable: true, get: () => errors, set: (value) => Object.defineProperty(wrapper, "errors", { configurable: true, enumerable: true, value }) }); return wrapper; } function getErrorMessage(e) { if (Object.hasOwn(e, "kind")) return e.message; let s = ""; if (e.plugin) s += `[plugin ${e.plugin}]`; const id = e.id ?? e.loc?.file; if (id) { s += " " + id; if (e.loc) s += `:${e.loc.line}:${e.loc.column}`; } if (s) s += "\n"; const message = `${e.name ?? "Error"}: ${e.message}`; s += message; if (e.frame) s = joinNewLine(s, e.frame); if (e.stack) s = joinNewLine(s, e.stack.replace(message, "")); return s; } function joinNewLine(s1, s2) { return s1.replace(/\n+$/, "") + "\n" + s2.replace(/^\n+/, ""); } //#endregion //#region src/utils/transform-rendered-module.ts function transformToRenderedModule(bindingRenderedModule) { return { get code() { return bindingRenderedModule.code; }, get renderedLength() { return bindingRenderedModule.code?.length || 0; }, get renderedExports() { return bindingRenderedModule.renderedExports; } }; } //#endregion //#region src/utils/transform-rendered-chunk.ts function transformRenderedChunk(chunk) { return { get name() { return chunk.name; }, get isEntry() { return chunk.isEntry; }, get isDynamicEntry() { return chunk.isDynamicEntry; }, get facadeModuleId() { return chunk.facadeModuleId; }, get moduleIds() { return chunk.moduleIds; }, get exports() { return chunk.exports; }, get fileName() { return chunk.fileName; }, get imports() { return chunk.imports; }, get dynamicImports() { return chunk.dynamicImports; }, get modules() { return transformChunkModules(chunk.modules); } }; } function transformChunkModules(modules) { const result = {}; for (let i = 0; i < modules.values.length; i++) { let key = modules.keys[i]; const mod = modules.values[i]; result[key] = transformToRenderedModule(mod); } return result; } //#endregion //#region src/utils/transform-to-rollup-output.ts function transformToRollupSourceMap(map) { const parsed = JSON.parse(map); const obj = { ...parsed, toString() { return JSON.stringify(obj); }, toUrl() { return `data:application/json;charset=utf-8;base64,${node_buffer.Buffer.from(obj.toString(), "utf-8").toString("base64")}`; } }; return obj; } function transformToRollupOutputChunk(bindingChunk, changed) { const chunk = { type: "chunk", get code() { return bindingChunk.code; }, fileName: bindingChunk.fileName, name: bindingChunk.name, get modules() { return transformChunkModules(bindingChunk.modules); }, get imports() { return bindingChunk.imports; }, get dynamicImports() { return bindingChunk.dynamicImports; }, exports: bindingChunk.exports, isEntry: bindingChunk.isEntry, facadeModuleId: bindingChunk.facadeModuleId || null, isDynamicEntry: bindingChunk.isDynamicEntry, get moduleIds() { return bindingChunk.moduleIds; }, get map() { return bindingChunk.map ? transformToRollupSourceMap(bindingChunk.map) : null; }, sourcemapFileName: bindingChunk.sourcemapFileName || null, preliminaryFileName: bindingChunk.preliminaryFileName }; const cache = {}; return new Proxy(chunk, { get(target, p) { if (p in cache) return cache[p]; return target[p]; }, set(target, p, newValue) { cache[p] = newValue; changed?.updated.add(bindingChunk.fileName); return true; }, has(target, p) { if (p in cache) return true; return p in target; } }); } function transformToRollupOutputAsset(bindingAsset, changed) { const asset = { type: "asset", fileName: bindingAsset.fileName, originalFileName: bindingAsset.originalFileName || null, originalFileNames: bindingAsset.originalFileNames, get source() { return transformAssetSource(bindingAsset.source); }, name: bindingAsset.name ?? void 0, names: bindingAsset.names }; const cache = {}; return new Proxy(asset, { get(target, p) { if (p in cache) return cache[p]; return target[p]; }, set(target, p, newValue) { cache[p] = newValue; changed?.updated.add(bindingAsset.fileName); return true; } }); } function transformToRollupOutput(output, changed) { handleOutputErrors(output); const { chunks, assets } = output; return { output: [...chunks.map((chunk) => transformToRollupOutputChunk(chunk, changed)), ...assets.map((asset) => transformToRollupOutputAsset(asset, changed))] }; } function handleOutputErrors(output) { const rawErrors = output.errors; if (rawErrors.length > 0) throw normalizeErrors(rawErrors); } function transformToOutputBundle(output, changed) { const bundle = Object.fromEntries(transformToRollupOutput(output, changed).output.map((item) => [item.fileName, item])); return new Proxy(bundle, { deleteProperty(target, property) { if (typeof property === "string") changed.deleted.add(property); return true; } }); } function collectChangedBundle(changed, bundle) { const assets = []; const chunks = []; for (const key in bundle) { if (changed.deleted.has(key) || !changed.updated.has(key)) continue; const item = bundle[key]; if (item.type === "asset") assets.push({ filename: item.fileName, originalFileNames: item.originalFileNames, source: bindingAssetSource(item.source), names: item.names }); else chunks.push({ code: item.code, filename: item.fileName, name: item.name, isEntry: item.isEntry, exports: item.exports, modules: {}, imports: item.imports, dynamicImports: item.dynamicImports, facadeModuleId: item.facadeModuleId || void 0, isDynamicEntry: item.isDynamicEntry, moduleIds: item.moduleIds, map: bindingifySourcemap$1(item.map), sourcemapFilename: item.sourcemapFileName || void 0, preliminaryFilename: item.preliminaryFileName }); } return { assets, chunks, deleted: Array.from(changed.deleted) }; } //#endregion //#region src/utils/transform-sourcemap.ts function isEmptySourcemapFiled(array) { if (!array) return true; if (array.length === 0 || !array[0]) return true; return false; } function normalizeTransformHookSourcemap(id, originalCode, rawMap) { if (!rawMap) return; let map = typeof rawMap === "object" ? rawMap : JSON.parse(rawMap); if (isEmptySourcemapFiled(map.sourcesContent)) map.sourcesContent = [originalCode]; if (isEmptySourcemapFiled(map.sources) || map.sources && map.sources.length === 1 && map.sources[0] !== id) map.sources = [id]; return map; } //#endregion //#region src/utils/transform-module-info.ts function transformModuleInfo(info, option) { return { get ast() { return unsupported("ModuleInfo#ast"); }, get code() { return info.code; }, id: info.id, importers: info.importers, dynamicImporters: info.dynamicImporters, importedIds: info.importedIds, dynamicallyImportedIds: info.dynamicallyImportedIds, exports: info.exports, isEntry: info.isEntry, ...option }; } //#endregion //#region src/plugin/minimal-plugin-context.ts var MinimalPluginContextImpl = class { info; warn; debug; meta; constructor(onLog, logLevel, pluginName) { this.pluginName = pluginName; this.debug = getLogHandler(LOG_LEVEL_DEBUG, "PLUGIN_LOG", onLog, pluginName, logLevel); this.info = getLogHandler(LOG_LEVEL_INFO, "PLUGIN_LOG", onLog, pluginName, logLevel); this.warn = getLogHandler(LOG_LEVEL_WARN, "PLUGIN_WARNING", onLog, pluginName, logLevel); this.meta = { rollupVersion: "4.23.0", rolldownVersion: VERSION, watchMode: false }; } error(e) { return require_parse_ast_index.error(require_parse_ast_index.logPluginError(normalizeLog(e), this.pluginName)); } }; //#endregion //#region src/utils/transform-side-effects.ts function bindingifySideEffects(sideEffects) { switch (sideEffects) { case true: return require_parse_ast_index.import_binding.BindingHookSideEffects.True; case false: return require_parse_ast_index.import_binding.BindingHookSideEffects.False; case "no-treeshake": return require_parse_ast_index.import_binding.BindingHookSideEffects.NoTreeshake; case null: case void 0: return void 0; default: throw new Error(`Unexpected side effects: ${sideEffects}`); } } //#endregion //#region src/utils/resolved-external.ts function transformResolvedExternal(bindingResolvedExternal$1) { switch (bindingResolvedExternal$1.type) { case "Bool": return bindingResolvedExternal$1.field0; case "Absolute": return "absolute"; case "Relative": unreachable(`The PluginContext resolve result external couldn't be 'relative'`); } } function bindingResolvedExternal(external) { if (typeof external === "boolean") return { type: "Bool", field0: external }; if (external === "absolute") return { type: "Absolute" }; if (external === "relative") return { type: "Relative" }; } //#endregion //#region src/plugin/plugin-context.ts var PluginContextImpl = class extends MinimalPluginContextImpl { getModuleInfo; constructor(outputOptions, context, plugin, data, onLog, logLevel, currentLoadingModule) { super(onLog, logLevel, plugin.name); this.outputOptions = outputOptions; this.context = context; this.data = data; this.onLog = onLog; this.currentLoadingModule = currentLoadingModule; this.getModuleInfo = (id) => this.data.getModuleInfo(id, context); } async load(options) { const id = options.id; if (id === this.currentLoadingModule) this.onLog(LOG_LEVEL_WARN, require_parse_ast_index.logCycleLoading(this.pluginName, this.currentLoadingModule)); const moduleInfo = this.data.getModuleInfo(id, this.context); if (moduleInfo && moduleInfo.code !== null) return moduleInfo; const rawOptions = { meta: options.meta || {}, moduleSideEffects: options.moduleSideEffects || null, invalidate: false }; this.data.updateModuleOption(id, rawOptions); async function createLoadModulePromise(context, data) { const loadPromise = data.loadModulePromiseMap.get(id); if (loadPromise) return loadPromise; let resolveFn; const promise = new Promise((resolve, _) => { resolveFn = resolve; }); data.loadModulePromiseMap.set(id, promise); try { await context.load(id, bindingifySideEffects(options.moduleSideEffects), resolveFn); } finally { data.loadModulePromiseMap.delete(id); } return promise; } await createLoadModulePromise(this.context, this.data); return this.data.getModuleInfo(id, this.context); } async resolve(source, importer, options) { let receipt = void 0; if (options != null) receipt = this.data.saveResolveOptions(options); const res = await this.context.resolve(source, importer, { custom: receipt, skipSelf: options?.skipSelf }); if (receipt != null) this.data.removeSavedResolveOptions(receipt); if (res == null) return null; const info = this.data.getModuleOption(res.id) || {}; return { ...res, external: transformResolvedExternal(res.external), ...info }; } emitFile = (file) => { if (file.type === "prebuilt-chunk") return unimplemented("PluginContext.emitFile with type prebuilt-chunk"); if (file.type === "chunk") return this.context.emitChunk(file); const fnSanitizedFileName = file.fileName || typeof this.outputOptions.sanitizeFileName !== "function" ? void 0 : this.outputOptions.sanitizeFileName(file.name || "asset"); const filename = file.fileName ? void 0 : this.getAssetFileNames(file); return this.context.emitFile({ ...file, originalFileName: file.originalFileName || void 0, source: bindingAssetSource(file.source) }, filename, fnSanitizedFileName); }; getAssetFileNames(file) { if (typeof this.outputOptions.assetFileNames === "function") return this.outputOptions.assetFileNames({ names: file.name ? [file.name] : [], originalFileNames: file.originalFileName ? [file.originalFileName] : [], source: file.source, type: "asset" }); } getFileName(referenceId) { return this.context.getFileName(referenceId); } getModuleIds() { return this.data.getModuleIds(this.context); } addWatchFile(id) { this.context.addWa