UNPKG

rolldown

Version:

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

1,460 lines (1,459 loc) 141 kB
import { a as RolldownLog, i as RolldownError, n as LogLevelOption, o as RolldownLogWithString, r as LogOrStringHandler, t as LogLevel } from "./logging-BSNejiLS.mjs"; import { A as ExternalMemoryStatus, N as JsxOptions, P as MinifyOptions$1, R as ParserOptions, U as TransformOptions$1, c as BindingHookResolveIdExtraArgs, d as BindingPluginContextResolveOptions, h as BindingTransformHookExtraArgs, k as BindingWatcherBundler, p as BindingRenderedChunk, t as BindingBuiltinPluginName, u as BindingMagicString, z as PreRenderedChunk } from "./binding-DktDDYoY.mjs"; import { TopLevelFilterExpression } from "@rolldown/pluginutils"; import { Program } from "@oxc-project/types"; //#region src/types/misc.d.ts /** @inline */ type SourcemapPathTransformOption = (relativeSourcePath: string, sourcemapPath: string) => string; /** @inline */ type SourcemapIgnoreListOption = (relativeSourcePath: string, sourcemapPath: string) => boolean; //#endregion //#region src/types/module-info.d.ts /** @category Plugin APIs */ interface ModuleInfo extends ModuleOptions { /** * @hidden Not supported by Rolldown */ ast: any; /** * The source code of the module. * * `null` if external or not yet available. */ code: string | null; /** * The id of the module for convenience */ id: string; /** * The ids of all modules that statically import this module. */ importers: string[]; /** * The ids of all modules that dynamically import this module. */ dynamicImporters: string[]; /** * The module ids statically imported by this module. */ importedIds: string[]; /** * The module ids dynamically imported by this module. */ dynamicallyImportedIds: string[]; /** * All exported variables */ exports: string[]; /** * Whether this module is a user- or plugin-defined entry point. */ isEntry: boolean; /** * The detected format of the module, based on both its syntax and module definition * metadata (such as `package.json` `type` and file extensions like `.mjs`/`.cjs`/`.mts`/`.cts`). * - "esm" for ES modules (has `import`/`export` statements or is defined as ESM by module metadata) * - "cjs" for CommonJS modules (uses `module.exports`, `exports`, top-level `return`, or is defined as CommonJS by module metadata) * - "unknown" when the format could not be determined from either syntax or module definition metadata * * @experimental */ inputFormat: "es" | "cjs" | "unknown"; } //#endregion //#region src/utils/asset-source.d.ts /** @inline */ type AssetSource = string | Uint8Array; //#endregion //#region src/types/external-memory-handle.d.ts declare const symbolForExternalMemoryHandle: "__rolldown_external_memory_handle__"; /** * Interface for objects that hold external memory that can be explicitly freed. */ interface ExternalMemoryHandle { /** * Frees the external memory held by this object. * @param keepDataAlive - If true, evaluates all lazy fields before freeing memory. * This will take time but prevents errors when accessing properties after freeing. * @returns Status object with `freed` boolean and optional `reason` string. * @internal */ [symbolForExternalMemoryHandle]: (keepDataAlive?: boolean) => ExternalMemoryStatus; } /** * Frees the external memory held by the given handle. * * This is useful when you want to manually release memory held by Rust objects * (like `OutputChunk` or `OutputAsset`) before they are garbage collected. * * @param handle - The object with external memory to free * @param keepDataAlive - If true, evaluates all lazy fields before freeing memory (default: false). * This will take time to copy data from Rust to JavaScript, but prevents errors * when accessing properties after the memory is freed. * @returns Status object with `freed` boolean and optional `reason` string. * - `{ freed: true }` if memory was successfully freed * - `{ freed: false, reason: "..." }` if memory couldn't be freed (e.g., already freed or other references exist) * * @example * ```typescript * import { freeExternalMemory } from 'rolldown/experimental'; * * const output = await bundle.generate(); * const chunk = output.output[0]; * * // Use the chunk... * * // Manually free the memory (fast, but accessing properties after will throw) * const status = freeExternalMemory(chunk); // { freed: true } * const statusAgain = freeExternalMemory(chunk); // { freed: false, reason: "Memory has already been freed" } * * // Keep data alive before freeing (slower, but data remains accessible) * freeExternalMemory(chunk, true); // Evaluates all lazy fields first * console.log(chunk.code); // OK - data was copied to JavaScript before freeing * * // Without keepDataAlive, accessing chunk properties after freeing will throw an error * ``` */ declare function freeExternalMemory(handle: ExternalMemoryHandle, keepDataAlive?: boolean): ExternalMemoryStatus; //#endregion //#region src/types/rolldown-output.d.ts /** * The information about an asset in the generated bundle. * * @category Plugin APIs */ interface OutputAsset extends ExternalMemoryHandle { type: "asset"; /** The file name of this asset. */ fileName: string; /** @deprecated Use {@linkcode originalFileNames} instead. */ originalFileName: string | null; /** The list of the absolute paths to the original file of this asset. */ originalFileNames: string[]; /** The content of this asset. */ source: AssetSource; /** @deprecated Use {@linkcode names} instead. */ name: string | undefined; names: string[]; } /** @category Plugin APIs */ interface SourceMap { file: string; mappings: string; names: string[]; sources: string[]; sourcesContent: string[]; version: number; debugId?: string; x_google_ignoreList?: number[]; toString(): string; toUrl(): string; } /** @category Plugin APIs */ interface RenderedModule { /** * The rendered code of this module. * * The unused variables and functions are removed. */ readonly code: string | null; /** * The length of the rendered code of this module. */ renderedLength: number; /** * The list of exported names from this module. * * The names that are not used are not included. */ renderedExports: string[]; } /** * The information about the chunk being rendered. * * Unlike {@link OutputChunk}, `code` and `map` are not set as the chunk has not been rendered yet. * All referenced chunk file names in each property that would contain hashes will contain hash placeholders instead. * * @category Plugin APIs */ interface RenderedChunk extends Omit<BindingRenderedChunk, "modules"> { type: "chunk"; /** Information about the modules included in this chunk. */ modules: { [id: string]: RenderedModule; }; /** The name of this chunk, which is used in naming patterns. */ name: string; /** Whether this chunk is a static entry point. */ isEntry: boolean; /** Whether this chunk is a dynamic entry point. */ isDynamicEntry: boolean; /** The id of a module that this chunk corresponds to. */ facadeModuleId: string | null; /** The list of ids of modules included in this chunk. */ moduleIds: Array<string>; /** Exported variable names from this chunk. */ exports: Array<string>; /** The preliminary file name of this chunk with hash placeholders. */ fileName: string; /** External modules imported statically by this chunk. */ imports: Array<string>; /** External modules imported dynamically by this chunk. */ dynamicImports: Array<string>; } /** * The information about a chunk in the generated bundle. * * @category Plugin APIs */ interface OutputChunk extends ExternalMemoryHandle { type: "chunk"; /** The generated code of this chunk. */ code: string; /** The name of this chunk, which is used in naming patterns. */ name: string; /** Whether this chunk is a static entry point. */ isEntry: boolean; /** Exported variable names from this chunk. */ exports: string[]; /** The file name of this chunk. */ fileName: string; /** Information about the modules included in this chunk. */ modules: { [id: string]: RenderedModule; }; /** External modules imported statically by this chunk. */ imports: string[]; /** External modules imported dynamically by this chunk. */ dynamicImports: string[]; /** The id of a module that this chunk corresponds to. */ facadeModuleId: string | null; /** Whether this chunk is a dynamic entry point. */ isDynamicEntry: boolean; moduleIds: string[]; /** The source map of this chunk if present. */ map: SourceMap | null; sourcemapFileName: string | null; /** The preliminary file name of this chunk with hash placeholders. */ preliminaryFileName: string; } /** * The generated bundle output. * * @category Programmatic APIs */ interface RolldownOutput extends ExternalMemoryHandle { /** * The list of chunks and assets in the generated bundle. * * This includes at least one {@linkcode OutputChunk}. It may also include more * {@linkcode OutputChunk} and/or {@linkcode OutputAsset}s. */ output: [OutputChunk, ...(OutputChunk | OutputAsset)[]]; } //#endregion //#region src/types/utils.d.ts type MaybePromise<T> = T | Promise<T>; /** @inline */ type NullValue<T = void> = T | undefined | null | void; type PartialNull<T> = { [P in keyof T]: T[P] | null }; type MakeAsync<Function_> = Function_ extends ((this: infer This, ...parameters: infer Arguments) => infer Return) ? (this: This, ...parameters: Arguments) => Return | Promise<Return> : never; type MaybeArray<T> = T | T[]; /** @inline */ type StringOrRegExp = string | RegExp; //#endregion //#region src/options/output-options.d.ts type GeneratedCodePreset = "es5" | "es2015"; interface GeneratedCodeOptions { /** * Whether to use Symbol.toStringTag for namespace objects. * @default false */ symbols?: boolean; /** * Allows choosing one of the presets listed above while overriding some options. * * ```js * export default { * output: { * generatedCode: { * preset: 'es2015', * symbols: false * } * } * }; * ``` * * @default 'es2015' */ preset?: GeneratedCodePreset; /** * Whether to add readable names to internal variables for profiling purposes. * * When enabled, generated code will use descriptive variable names that correspond * to the original module names, making it easier to profile and debug the bundled code. * * @default false * * */ profilerNames?: boolean; } /** @inline */ type ModuleFormat = "es" | "cjs" | "esm" | "module" | "commonjs" | "iife" | "umd"; /** @inline */ type AddonFunction = (chunk: RenderedChunk) => string | Promise<string>; /** @inline */ type ChunkFileNamesFunction = (chunkInfo: PreRenderedChunk) => string; /** @inline */ type SanitizeFileNameFunction = (name: string) => string; /** @category Plugin APIs */ interface PreRenderedAsset { type: "asset"; /** @deprecated Use {@linkcode names} instead. */ name?: string; names: string[]; /** @deprecated Use {@linkcode originalFileNames} instead. */ originalFileName?: string; /** The list of the absolute paths to the original file of this asset. */ originalFileNames: string[]; /** The content of this asset. */ source: AssetSource; } /** @inline */ type AssetFileNamesFunction = (chunkInfo: PreRenderedAsset) => string; /** @inline */ type PathsFunction$1 = (id: string) => string; /** @inline */ type ManualChunksFunction = (moduleId: string, meta: { getModuleInfo: (moduleId: string) => ModuleInfo | null; }) => string | NullValue; /** @inline */ type GlobalsFunction = (name: string) => string; /** @category Plugin APIs */ type CodeSplittingNameFunction = (moduleId: string, ctx: ChunkingContext) => string | NullValue; /** @inline */ type CodeSplittingTestFunction = (id: string) => boolean | undefined | void; type MinifyOptions = Omit<MinifyOptions$1, "module" | "sourcemap">; interface CommentsOptions { /** * Comments that contain `@license`, `@preserve` or start with `//!` or `/*!` */ legal?: boolean; /** * Comments that contain `@__PURE__`, `@__NO_SIDE_EFFECTS__` or `@vite-ignore` */ annotation?: boolean; /** * JSDoc comments */ jsdoc?: boolean; } /** @inline */ interface ChunkingContext { getModuleInfo(moduleId: string): ModuleInfo | null; } interface OutputOptions { /** * The directory in which all generated chunks are placed. * * The {@linkcode file | output.file} option can be used instead if only a single chunk is generated. * * * * @default 'dist' */ dir?: string; /** * The file path for the single generated chunk. * * The {@linkcode dir | output.dir} option should be used instead if multiple chunks are generated. */ file?: string; /** * Which exports mode to use. * * * * @default 'auto' */ exports?: "auto" | "named" | "default" | "none"; /** * Specify the character set that Rolldown is allowed to use in file hashes. * * - `'base64'`: Uses url-safe base64 characters (0-9, a-z, A-Z, -, _). This will produce the shortest hashes. * - `'base36'`: Uses alphanumeric characters (0-9, a-z) * - `'hex'`: Uses hexadecimal characters (0-9, a-f) * * @default 'base64' */ hashCharacters?: "base64" | "base36" | "hex"; /** * Expected format of generated code. * * - `'es'`, `'esm'` and `'module'` are the same format, all stand for ES module. * - `'cjs'` and `'commonjs'` are the same format, all stand for CommonJS module. * - `'iife'` stands for [Immediately Invoked Function Expression](https://developer.mozilla.org/en-US/docs/Glossary/IIFE). * - `'umd'` stands for [Universal Module Definition](https://github.com/umdjs/umd). * * @default 'es' * * */ format?: ModuleFormat; /** * Whether to generate sourcemaps. * * - `false`: No sourcemap will be generated. * - `true`: A separate sourcemap file will be generated. * - `'inline'`: The sourcemap will be appended to the output file as a data URL. * - `'hidden'`: A separate sourcemap file will be generated, but the link to the sourcemap (`//# sourceMappingURL` comment) will not be included in the output file. * * @default false */ sourcemap?: boolean | "inline" | "hidden"; /** * The base URL for the links to the sourcemap file in the output file. * * By default, relative URLs are generated. If this option is set, an absolute URL with that base URL will be generated. This is useful when deploying source maps to a different location than your code, such as a CDN or separate debugging server. */ sourcemapBaseUrl?: string; /** * Whether to include [debug IDs](https://github.com/tc39/ecma426/blob/main/proposals/debug-id.md) in the sourcemap. * * When `true`, a unique debug ID will be emitted in source and sourcemaps which streamlines identifying sourcemaps across different builds. * * @default false */ sourcemapDebugIds?: boolean; /** * Control which source files are included in the sourcemap ignore list. * * Files in the ignore list are excluded from debugger stepping and error stack traces. * * - `false`: Include no source files in the ignore list * - `true`: Include all source files in the ignore list * - `string`: Files containing this string in their path will be included in the ignore list * - `RegExp`: Files matching this regular expression will be included in the ignore list * - `function`: Custom function to determine if a source should be ignored * * :::tip Performance * Using static values (`boolean`, `string`, or `RegExp`) is significantly more performant than functions. * Calling JavaScript functions from Rust has extremely high overhead, so prefer static patterns when possible. * ::: * * @example * ```js * // ✅ Preferred: Use RegExp for better performance * sourcemapIgnoreList: /node_modules/ * * // ✅ Preferred: Use string pattern for better performance * sourcemapIgnoreList: "vendor" * * // ! Use sparingly: Function calls have high overhead * sourcemapIgnoreList: (source, sourcemapPath) => { * return source.includes('node_modules') || source.includes('.min.'); * } * ``` * * @default /node_modules/ */ sourcemapIgnoreList?: boolean | SourcemapIgnoreListOption | StringOrRegExp; /** * A transformation to apply to each path in a sourcemap. * * @example * ```js * export default defineConfig({ * output: { * sourcemap: true, * sourcemapPathTransform: (source, sourcemapPath) => { * // Remove 'src/' prefix from all source paths * return source.replace(/^src\//, ''); * }, * }, * }); * ``` */ sourcemapPathTransform?: SourcemapPathTransformOption; /** * Whether to exclude the original source code from sourcemaps. * * When `true`, the `sourcesContent` field is omitted from the generated sourcemap, * reducing the sourcemap file size. The sourcemap will still contain source file paths * and mappings, so debugging works if the original files are available. * * @default false */ sourcemapExcludeSources?: boolean; /** * A string to prepend to the bundle before {@linkcode Plugin.renderChunk | renderChunk} hook. * * See {@linkcode intro | output.intro}, {@linkcode postBanner | output.postBanner} as well. * * */ banner?: string | AddonFunction; /** * A string to append to the bundle before {@linkcode Plugin.renderChunk | renderChunk} hook. * * See {@linkcode outro | output.outro}, {@linkcode postFooter | output.postFooter} as well. * * */ footer?: string | AddonFunction; /** * A string to prepend to the bundle after {@linkcode Plugin.renderChunk | renderChunk} hook and minification. * * See {@linkcode banner | output.banner}, {@linkcode intro | output.intro} as well. * * */ postBanner?: string | AddonFunction; /** * A string to append to the bundle after {@linkcode Plugin.renderChunk | renderChunk} hook and minification. * * See {@linkcode footer | output.footer}, {@linkcode outro | output.outro} as well. * * */ postFooter?: string | AddonFunction; /** * A string to prepend inside any {@link OutputOptions.format | format}-specific wrapper. * * See {@linkcode banner | output.banner}, {@linkcode postBanner | output.postBanner} as well. * * */ intro?: string | AddonFunction; /** * A string to append inside any {@link OutputOptions.format | format}-specific wrapper. * * See {@linkcode footer | output.footer}, {@linkcode postFooter | output.postFooter} as well. * * */ outro?: string | AddonFunction; /** * Whether to extend the global variable defined by the {@linkcode OutputOptions.name | name} option in `umd` or `iife` {@link OutputOptions.format | formats}. * * When `true`, the global variable will be defined as `global.name = global.name || {}`. * When `false`, the global defined by name will be overwritten like `global.name = {}`. * * @default false */ extend?: boolean; /** * Whether to add a `__esModule: true` property when generating exports for non-ES {@link OutputOptions.format | formats}. * * This property signifies that the exported value is the namespace of an ES module and that the default export of this module corresponds to the `.default` property of the exported object. * * - `true`: Always add the property when using {@link OutputOptions.exports | named exports mode}, which is similar to what other tools do. * - `"if-default-prop"`: Only add the property when using {@link OutputOptions.exports | named exports mode} and there also is a default export. The subtle difference is that if there is no default export, consumers of the CommonJS version of your library will get all named exports as default export instead of an error or `undefined`. * - `false`: Never add the property even if the default export would become a property `.default`. * * @default 'if-default-prop' * * */ esModule?: boolean | "if-default-prop"; /** * The pattern to use for naming custom emitted assets to include in the build output, or a function that is called per asset with {@linkcode PreRenderedAsset} to return such a pattern. * * Patterns support the following placeholders: * - `[extname]`: The file extension of the asset including a leading dot, e.g. `.css`. * - `[ext]`: The file extension without a leading dot, e.g. css. * - `[hash]`: A hash based on the content of the asset. You can also set a specific hash length via e.g. `[hash:10]`. By default, it will create a base-64 hash. If you need a reduced character set, see {@linkcode hashCharacters | output.hashCharacters}. * - `[name]`: The file name of the asset excluding any extension. * * Forward slashes (`/`) can be used to place files in sub-directories. * * See also {@linkcode chunkFileNames | output.chunkFileNames}, {@linkcode entryFileNames | output.entryFileNames}. * * @default 'assets/[name]-[hash][extname]' */ assetFileNames?: string | AssetFileNamesFunction; /** * The pattern to use for chunks created from entry points, or a function that is called per entry chunk with {@linkcode PreRenderedChunk} to return such a pattern. * * Patterns support the following placeholders: * - `[format]`: The rendering format defined in the output options. The value is any of {@linkcode InternalModuleFormat}. * - `[hash]`: A hash based only on the content of the final generated chunk, including transformations in `renderChunk` and any referenced file hashes. You can also set a specific hash length via e.g. `[hash:10]`. By default, it will create a base-64 hash. If you need a reduced character set, see {@linkcode hashCharacters | output.hashCharacters}. * - `[name]`: The file name (without extension) of the entry point, unless the object form of input was used to define a different name. * * Forward slashes (`/`) can be used to place files in sub-directories. This pattern will also be used for every file when setting the {@linkcode preserveModules | output.preserveModules} option. * * See also {@linkcode assetFileNames | output.assetFileNames}, {@linkcode chunkFileNames | output.chunkFileNames}. * * @default '[name].js' */ entryFileNames?: string | ChunkFileNamesFunction; /** * The pattern to use for naming shared chunks created when code-splitting, or a function that is called per chunk with {@linkcode PreRenderedChunk} to return such a pattern. * * Patterns support the following placeholders: * - `[format]`: The rendering format defined in the output options. The value is any of {@linkcode InternalModuleFormat}. * - `[hash]`: A hash based only on the content of the final generated chunk, including transformations in `renderChunk` and any referenced file hashes. You can also set a specific hash length via e.g. `[hash:10]`. By default, it will create a base-64 hash. If you need a reduced character set, see {@linkcode hashCharacters | output.hashCharacters}. * - `[name]`: The name of the chunk. This can be explicitly set via the {@linkcode codeSplitting | output.codeSplitting} option or when the chunk is created by a plugin via `this.emitFile`. Otherwise, it will be derived from the chunk contents. * * Forward slashes (`/`) can be used to place files in sub-directories. * * See also {@linkcode assetFileNames | output.assetFileNames}, {@linkcode entryFileNames | output.entryFileNames}. * * @default '[name]-[hash].js' */ chunkFileNames?: string | ChunkFileNamesFunction; /** * Whether to enable chunk name sanitization (removal of non-URL-safe characters like `\0`, `?` and `*`). * * Set `false` to disable the sanitization. You can also provide a custom sanitization function. * * @default true */ sanitizeFileName?: boolean | SanitizeFileNameFunction; /** * Control code minification * * Rolldown uses Oxc Minifier under the hood. See Oxc's [minification documentation](https://oxc.rs/docs/guide/usage/minifier#features) for more details. * * - `true`: Enable full minification including code compression and dead code elimination * - `false`: Disable minification * - `'dce-only'`: Only perform dead code elimination without code compression (default) * - `MinifyOptions`: Fine-grained control over minification settings * * @default 'dce-only' */ minify?: boolean | "dce-only" | MinifyOptions; /** * Specifies the global variable name that contains the exports of `umd` / `iife` {@link OutputOptions.format | formats}. * * @example * ```js * export default defineConfig({ * output: { * format: 'iife', * name: 'MyBundle', * } * }); * ``` * ```js * // output * var MyBundle = (function () { * // ... * })(); * ``` * * */ name?: string; /** * Specifies `id: variableName` pairs necessary for {@link InputOptions.external | external} imports in `umd` / `iife` {@link OutputOptions.format | formats}. * * @example * ```js * export default defineConfig({ * external: ['jquery'], * output: { * format: 'iife', * name: 'MyBundle', * globals: { * jquery: '$', * } * } * }); * ``` * ```js * // input * import $ from 'jquery'; * ``` * ```js * // output * var MyBundle = (function ($) { * // ... * })($); * ``` */ globals?: Record<string, string> | GlobalsFunction; /** * Maps {@link InputOptions.external | external} module IDs to paths. * * Allows customizing the path used when importing external dependencies. * This is particularly useful for loading dependencies from CDNs or custom locations. * * - Object form: Maps module IDs to their replacement paths * - Function form: Takes a module ID and returns its replacement path * * @example * ```js * { * paths: { * 'd3': 'https://cdn.jsdelivr.net/npm/d3@7' * } * } * ``` * * @example * ```js * { * paths: (id) => { * if (id.startsWith('lodash')) { * return `https://cdn.jsdelivr.net/npm/${id}` * } * return id * } * } * ``` */ paths?: Record<string, string> | PathsFunction$1; /** * Which language features Rolldown can safely use in generated code. * * This will not transpile any user code but only change the code Rolldown uses in wrappers and helpers. */ generatedCode?: Partial<GeneratedCodeOptions>; /** * Whether to generate code to support live bindings for {@link InputOptions.external | external} imports. * * With the default value of `true`, Rolldown will generate code to support live bindings for external imports. * * When set to `false`, Rolldown will assume that exports from external modules do not change. This will allow Rolldown to generate smaller code. Note that this can cause issues when there are circular dependencies involving an external dependency. * * @default true * * */ externalLiveBindings?: boolean; /** * @deprecated Please use `codeSplitting: false` instead. * * Whether to inline dynamic imports instead of creating new chunks to create a single bundle. * * This option can be used only when a single input is provided. * * @default false */ inlineDynamicImports?: boolean; /** * Whether to keep external dynamic imports as `import(...)` expressions in CommonJS output. * * If set to `false`, external dynamic imports will be rewritten to use `require(...)` calls. * This may be necessary to support environments that do not support dynamic `import()` in CommonJS modules like old Node.js versions. * * @default true */ dynamicImportInCjs?: boolean; /** * Allows you to do manual chunking. Provided for Rollup compatibility. * * You could use this option for migration purpose. Under the hood, * * ```js * { * manualChunks: (moduleId, meta) => { * if (moduleId.includes('node_modules')) { * return 'vendor'; * } * return null; * } * } * ``` * * will be transformed to * * ```js * { * codeSplitting: { * groups: [ * { * name(moduleId) { * if (moduleId.includes('node_modules')) { * return 'vendor'; * } * return null; * }, * }, * ], * } * } * * ``` * * Note that unlike Rollup, object form is not supported. * * @deprecated * Please use {@linkcode codeSplitting | output.codeSplitting} instead. * * :::warning * If `manualChunks` and `codeSplitting` are both specified, `manualChunks` option will be ignored. * ::: */ manualChunks?: ManualChunksFunction; /** * Controls how code splitting is performed. * * - `true`: Default behavior, automatic code splitting. **(default)** * - `false`: Inline all dynamic imports into a single bundle (equivalent to deprecated `inlineDynamicImports: true`). * - `object`: Advanced manual code splitting configuration. * * For deeper understanding, please refer to the in-depth [documentation](https://rolldown.rs/in-depth/manual-code-splitting). * * * * @example * **Basic vendor chunk** * ```js * export default defineConfig({ * output: { * codeSplitting: { * minSize: 20000, * groups: [ * { * name: 'vendor', * test: /node_modules/, * }, * ], * }, * }, * }); * ``` * * * @default true */ codeSplitting?: boolean | CodeSplittingOptions; /** * @deprecated Please use {@linkcode codeSplitting | output.codeSplitting} instead. * * Allows you to do manual chunking. * * :::warning * If `advancedChunks` and `codeSplitting` are both specified, `advancedChunks` option will be ignored. * ::: */ advancedChunks?: { includeDependenciesRecursively?: boolean; minSize?: number; maxSize?: number; maxModuleSize?: number; minModuleSize?: number; minShareCount?: number; groups?: CodeSplittingGroup[]; }; /** * Controls how legal comments are preserved in the output. * * - `none`: no legal comments * - `inline`: preserve legal comments that contain `@license`, `@preserve` or starts with `//!` `/*!` * * @deprecated Use `comments.legal` instead. When both `legalComments` and `comments.legal` are set, `comments.legal` takes priority. */ legalComments?: "none" | "inline"; /** * Control which comments are preserved in the output. * * - `true`: Preserve legal, annotation, and JSDoc comments (default) * - `false`: Strip all comments * - Object: Granular control over comment categories * * Note: Regular line and block comments without these markers * are always removed regardless of this option. * * When both `legalComments` and `comments.legal` are set, `comments.legal` takes priority. * * @default true */ comments?: boolean | CommentsOptions; /** * The list of plugins to use only for this output. * * @see {@linkcode InputOptions.plugins | plugins} */ plugins?: RolldownOutputPluginOption; /** * Whether to add a polyfill for `require()` function in non-CommonJS formats. * * This option is useful when you want to inject your own `require` implementation. * * @default true */ polyfillRequire?: boolean; /** * This option is not implemented yet. * @hidden */ hoistTransitiveImports?: false; /** * Whether to use preserve modules mode. * * * * @default false */ preserveModules?: boolean; /** * Specifies the directory name for "virtual" files that might be emitted by plugins when using {@link OutputOptions.preserveModules | preserve modules mode}. * * @default '_virtual' */ virtualDirname?: string; /** * A directory path to input modules that should be stripped away from {@linkcode dir | output.dir} when using {@link OutputOptions.preserveModules | preserve modules mode}. * * */ preserveModulesRoot?: string; /** * Whether to convert top-level `let` and `const` declarations into `var` declarations. * * Enabling this option can improve runtime performance of the generated code in * certain environments by avoiding Temporal Dead Zone (TDZ) checks. Only declarations * in the module's top-level scope are rewritten — declarations inside nested scopes * (functions, blocks, etc.) are left as-is. * * Note: * - Top-level `class X {}` declarations are always emitted as `var X = class {}` so * rolldown can hoist them alongside other top-level bindings; this transform is * independent of `topLevelVar`. * - Top-level `function` declarations are never rewritten. * * @default false * * */ topLevelVar?: boolean; /** * Whether to minify internal exports as single letter variables to allow for better minification. * * @default * `true` for format `es` or if `output.minify` is `true` or object, `false` otherwise * * */ minifyInternalExports?: boolean; /** * Clean output directory ({@linkcode dir | output.dir}) before emitting output. * * @default false * * */ cleanDir?: boolean; /** * Keep `name` property of functions and classes after bundling. * * When enabled, the bundler will preserve the original `name` property value of functions and * classes in the output. This is useful for debugging and some frameworks that rely on it for * registration and binding purposes. * * * * @default false */ keepNames?: boolean; /** * Lets modules be executed in the order they are declared. * * This is done by injecting runtime helpers to ensure that modules are executed in the order they are imported. External modules won't be affected. * * > [!WARNING] * > Enabling this option may negatively increase bundle size. It is recommended to use this option only when absolutely necessary. * @default false */ strictExecutionOrder?: boolean; /** * Whether to always output `"use strict"` directive in non-ES module outputs. * * - `true` - Always emit `"use strict"` at the top of the output (not applicable for ESM format since ESM is always strict). * - `false` - Never emit `"use strict"` in the output. * - `'auto'` - Respect the `"use strict"` directives from the source code. * * See [In-depth directive guide](https://rolldown.rs/in-depth/directives) for more details. * * @default 'auto' */ strict?: boolean | "auto"; } /** * Built-in module tag names computed by rolldown. * * - `'$initial'` — the module is statically imported by at least one user-defined entry point, or is part of its static dependency chain. */ type BuiltinModuleTag = "$initial"; type CodeSplittingGroup = { /** * Name of the group. It will be also used as the name of the chunk and replace the `[name]` placeholder in the {@linkcode OutputOptions.chunkFileNames | output.chunkFileNames} option. * * For example, * * ```js * import { defineConfig } from 'rolldown'; * * export default defineConfig({ * output: { * codeSplitting: { * groups: [ * { * name: 'libs', * test: /node_modules/, * }, * ], * }, * }, * }); * ``` * will create a chunk named `libs-[hash].js` in the end. * * It's ok to have the same name for different groups. Rolldown will deduplicate the chunk names if necessary. * * #### Dynamic `name()` * * If `name` is a function, it will be called with the module id as the argument. The function should return a string or `null`. If it returns `null`, the module will be ignored by this group. * * Notice, each returned new name will be treated as a separate group. * * For example, * * ```js * import { defineConfig } from 'rolldown'; * * export default defineConfig({ * output: { * codeSplitting: { * groups: [ * { * name: (moduleId) => moduleId.includes('node_modules') ? 'libs' : 'app', * minSize: 100 * 1024, * }, * ], * }, * }, * }); * ``` * * :::warning * Constraints like `minSize`, `maxSize`, etc. are applied separately for different names returned by the function. * ::: */ name: string | CodeSplittingNameFunction; /** * Controls which modules are captured in this group. * * - If `test` is a string, the module whose id contains the string will be captured. * - If `test` is a regular expression, the module whose id matches the regular expression will be captured. * - If `test` is a function, modules for which `test(id)` returns `true` will be captured. * - If `test` is empty, any module will be considered as matched. * * :::warning * When using regular expression, it's recommended to use `[\\/]` to match the path separator instead of `/` to avoid potential issues on Windows. * - ✅ Recommended: `/node_modules[\\/]react/` * - ❌ Not recommended: `/node_modules/react/` * ::: */ test?: StringOrRegExp | CodeSplittingTestFunction; /** * Priority of the group. Group with higher priority will be chosen first to match modules and create chunks. When converting the group to a chunk, modules of that group will be removed from other groups. * * If two groups have the same priority, the group whose index is smaller will be chosen. * * @example * ```js * import { defineConfig } from 'rolldown'; * * export default defineConfig({ * output: { * codeSplitting: { * groups: [ * { * name: 'react', * test: /node_modules[\\/]react/, * priority: 2, * }, * { * name: 'other-libs', * test: /node_modules/, * priority: 1, * }, * ], * }, * }, * }); * ``` * * @default 0 */ priority?: number; /** * Minimum size in bytes of the desired chunk. If the accumulated size of the captured modules by this group is smaller than this value, it will be ignored. Modules in this group will fall back to the `automatic chunking` if they are not captured by any other group. * * @default 0 */ minSize?: number; /** * Controls if a module should be captured based on how many entry chunks reference it. * * @default 1 */ minShareCount?: number; /** * If the accumulated size in bytes of the captured modules by this group is larger than this value, this group will be split into multiple groups that each has size close to this value. * * @default Infinity */ maxSize?: number; /** * Controls whether a module can only be captured if its size in bytes is smaller than or equal to this value. * * @default Infinity */ maxModuleSize?: number; /** * Controls whether a module can only be captured if its size in bytes is larger than or equal to this value. * * @default 0 */ minModuleSize?: number; /** * When `false` (default), all matching modules are merged into a single chunk. * Every entry that uses any of these modules must load the entire chunk — even * modules it doesn't need. * * When `true`, matching modules are grouped by which entries actually import them. * Modules shared by the same set of entries go into the same chunk, while modules * shared by a different set go into a separate chunk. This way, each entry only * loads the code it actually uses. * * Example: entries A, B, C all match a `"vendor"` group. * - `moduleX` is used by A, B, C * - `moduleY` is used by A, B only * * With `entriesAware: false` → one `vendor.js` chunk with both modules; C loads `moduleY` unnecessarily. * With `entriesAware: true` → `vendor.js` (moduleX, loaded by all) + `vendor2.js` (moduleY, loaded by A and B only). * * @default false */ entriesAware?: boolean; /** * Size threshold in bytes for merging small `entriesAware` subgroups into the * closest neighboring subgroup. * * This option only works when {@linkcode CodeSplittingGroup.entriesAware | entriesAware} * is `true`. Set to `0` to disable subgroup merging. * * @default 0 */ entriesAwareMergeThreshold?: number; /** * Filter modules by tags. Only modules that have **all** specified tags * are captured by this group. Combines with `test` and other filters — * a module must match all criteria. * * Built-in tags: `'$initial'` (module is statically imported by a user-defined entry or part of its dependency chain). * * @see {@link https://rolldown.rs/in-depth/manual-code-splitting | Manual Code Splitting} * * @example * ```js * { name: 'initial-deps', tags: ['$initial'], maxSize: 1048576 } * ``` */ tags?: BuiltinModuleTag[]; }; /** * Alias for {@linkcode CodeSplittingGroup}. Use this type for the `codeSplitting.groups` option. * * @deprecated Please use {@linkcode CodeSplittingGroup} instead. */ type AdvancedChunksGroup = CodeSplittingGroup; /** * Configuration options for advanced code splitting. */ type CodeSplittingOptions = { /** * By default, each group will also include captured modules' dependencies. This reduces the chance of generating circular chunks. * * If you want to disable this behavior, it's recommended to both set * - {@linkcode InputOptions.preserveEntrySignatures | preserveEntrySignatures}: `false | 'allow-extension'` * - {@linkcode OutputOptions.strictExecutionOrder | strictExecutionOrder}: `true` * * to avoid generating invalid chunks. * * @default true */ includeDependenciesRecursively?: boolean; /** * Global fallback of {@linkcode CodeSplittingGroup.minSize | group.minSize}, if it's not specified in the group. */ minSize?: number; /** * Global fallback of {@linkcode CodeSplittingGroup.maxSize | group.maxSize}, if it's not specified in the group. */ maxSize?: number; /** * Global fallback of {@linkcode CodeSplittingGroup.maxModuleSize | group.maxModuleSize}, if it's not specified in the group. */ maxModuleSize?: number; /** * Global fallback of {@linkcode CodeSplittingGroup.minModuleSize | group.minModuleSize}, if it's not specified in the group. */ minModuleSize?: number; /** * Global fallback of {@linkcode CodeSplittingGroup.minShareCount | group.minShareCount}, if it's not specified in the group. */ minShareCount?: number; /** * Groups to be used for code splitting. */ groups?: CodeSplittingGroup[]; }; /** * Alias for {@linkcode CodeSplittingOptions}. Use this type for the `codeSplitting` option. * * @deprecated Please use {@linkcode CodeSplittingOptions} instead. */ type AdvancedChunksOptions = CodeSplittingOptions; //#endregion //#region src/api/build.d.ts /** * The options for {@linkcode build} function. * * @experimental * @category Programmatic APIs */ type BuildOptions = InputOptions & { /** * Write the output to the file system * * @default true */ write?: boolean; output?: OutputOptions; }; /** * Build a single output. * * @param options The build options. * @returns A Promise that resolves to the build output. */ declare function build(options: BuildOptions): Promise<RolldownOutput>; /** * Build multiple outputs __sequentially__. * * @param options The build options. * @returns A Promise that resolves to the build outputs for each option. */ declare function build(options: BuildOptions[]): Promise<RolldownOutput[]>; //#endregion //#region src/api/rolldown/rolldown-build.d.ts /** * The bundle object returned by {@linkcode rolldown} function. * * @category Programmatic APIs */ declare class RolldownBuild { #private; /** @internal */ static asyncRuntimeShutdown: boolean; /** @hidden should not be used directly */ constructor(inputOptions: InputOptions); /** * Whether the bundle has been closed. * * If the bundle is closed, calling other methods will throw an error. */ get closed(): boolean; /** * Generate bundles in-memory. * * If you directly want to write bundles to disk, use the {@linkcode write} method instead. * * @param outputOptions The output options. * @returns The generated bundle. * @throws {@linkcode BundleError} When an error occurs during the build. */ generate(outputOptions?: OutputOptions): Promise<RolldownOutput>; /** * Generate and write bundles to disk. * * If you want to generate bundles in-memory, use the {@linkcode generate} method instead. * * @param outputOptions The output options. * @returns The generated bundle. * @throws {@linkcode BundleError} When an error occurs during the build. */ write(outputOptions?: OutputOptions): Promise<RolldownOutput>; /** * Close the bundle and free resources. * * This method is called automatically when using `using` syntax. * * @example * ```js * import { rolldown } from 'rolldown'; * * { * using bundle = await rolldown({ input: 'src/main.js' }); * const output = await bundle.generate({ format: 'esm' }); * console.log(output); * // bundle.close() is called automatically here * } * ``` */ close(): Promise<void>; /** @hidden documented in close method */ [Symbol.asyncDispose](): Promise<void>; /** * @experimental * @hidden not ready for public usage yet */ get watchFiles(): Promise<string[]>; } //#endregion //#region src/api/rolldown/index.d.ts /** * The API compatible with Rollup's `rollup` function. * * Unlike Rollup, the module graph is not built until the methods of the bundle object are called. * * @param input The input options object. * @returns A Promise that resolves to a bundle object. * * @example * ```js * import { rolldown } from 'rolldown'; * * let bundle, failed = false; * try { * bundle = await rolldown({ * input: 'src/main.js', * }); * await bundle.write({ * format: 'esm', * }); * } catch (e) { * console.error(e); * failed = true; * } * if (bundle) { * await bundle.close(); * } * process.exitCode = failed ? 1 : 0; * ``` * * @category Programmatic APIs */ declare const rolldown: (input: InputOptions) => Promise<RolldownBuild>; //#endregion //#region src/options/watch-options.d.ts /** @category Programmatic APIs */ interface WatchOptions extends InputOptions { output?: OutputOptions | OutputOptions[]; } //#endregion //#region src/api/watch/watch-emitter.d.ts type ChangeEvent$1 = "create" | "update" | "delete"; type RolldownWatchBuild = BindingWatcherBundler; /** * - `START`: the watcher is (re)starting * - `BUNDLE_START`: building an individual bundle * - `BUNDLE_END`: finished building a bundle * - `duration`: the build duration in milliseconds * - `output`: an array of the {@linkcode OutputOptions.file | file} or {@linkcode OutputOptions.dir | dir} option values of the generated outputs * - `result`: the bundle object that can be used to generate additional outputs. This is especially important when the watch.skipWrite option is used. You should call `event.result.close()` once you are done generating outputs, or if you do not generate outputs. This will allow plugins to clean up resources via the `closeBundle` hook. * - `END`: finished building all bundles * - `ERROR`: encountered an error while bundling * - `error`: the error that was thrown * - `result`: the bundle object * * @category Programmatic APIs */ type RolldownWatcherEvent = { code: "START"; } | { code: "BUNDLE_START"; } | { code: "BUNDLE_END"; duration: number; output: readonly string[]; result: RolldownWatchBuild; } | { code: "END"; } | { code: "ERROR"; error: Error; result: RolldownWatchBuild; }; /** * * @category Programmatic APIs */ type RolldownWatcherWatcherEventMap = { event: [data: RolldownWatcherEvent]; /** a file was modified */ change: [id: string, change: { event: ChangeEvent$1; }]; /** a new run was triggered */ restart: []; /** the watcher was closed */ close: []; }; /** * @category Programmatic APIs */ interface RolldownWatcher { /** * Register a listener for events defined in {@linkcode RolldownWatcherWatcherEventMap}. */ on<E extends keyof RolldownWatcherWatcherEventMap>(event: E, listener: (...args: RolldownWatcherWatcherEventMap[E]) => MaybePromise<void>): this; /** * Unregister a listener for events defined in {@linkcode RolldownWatcherWatcherEventMap}. */ off<E extends keyof RolldownWatcherWatcherEventMap>(event: E, listener: (...args: RolldownWatcherWatcherEventMap[E]) => MaybePromise<void>): this; /** * Unregister all listeners for a specific event defined in {@linkcode RolldownWatcherWatcherEventMap}. */ clear<E extends keyof RolldownWatcherWatcherEventMap>(event: E): void; /** * Close the watcher and stop listening for file changes. */ close(): Promise<void>; } //#endregion //#region src/api/watch/index.d.ts /** * The API compatible with Rollup's `watch` function. * * This function will rebuild the bundle when it detects that the individual modules have changed on disk. * * Note that when using this function, it is your responsibility to call `event.result.close()` in response to the `BUNDLE_END` event to avoid resource leaks. * * @param input The watch options object or the list of them. * @returns A watcher object. * * @example * ```js * import { watch } from 'rolldown'; * * const watcher = watch({ /* ... *\/ }); * watcher.on('event', (event) => { * if (event.code === 'BUNDLE_END') { * console.log(event.duration); * event.result.close(); * } * }); * * // Stop watching * watcher.close(); * ``` * * @experimental * @category Programmatic APIs */ declare function watch(input: WatchOptions | WatchOptions[]): RolldownWatcher; //#endregion //#region src/binding-magic-string.d.ts interface RolldownMagicString extends BindingMagicString { readonly isRolldownMagicString: true; /** Accepts a string or RegExp pattern. RegExp supports `$&`, `$$`, and `$N` substitutions. */ replace(from: string | RegExp, to: string): this; /** Accepts a string or RegExp pattern. RegExp must have the global (`g`) flag. */ replaceAll(from: string | RegExp, to: string): this; } type RolldownMagicStringConstructor = Omit<