experimental-index.mjs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. import { n as __toESM, t as require_binding } from "./shared/binding-B4m_2rFW.mjs";
  2. import { n as BuiltinPlugin, t as normalizedStringOrRegex } from "./shared/normalize-string-or-regex-xyy0kCQR.mjs";
  3. import { u as transformToRollupOutput } from "./shared/bindingify-input-options-DCTviPFW.mjs";
  4. import { l as PluginDriver, s as validateOption, t as createBundlerOptions } from "./shared/create-bundler-option-DLv8UpsD.mjs";
  5. import { i as unwrapBindingResult, r as normalizeBindingResult } from "./shared/error-Bj1xBdEY.mjs";
  6. import { n as parseSync$1, t as parse$1 } from "./shared/parse-D5aRkQ8y.mjs";
  7. import { a as viteDynamicImportVarsPlugin, c as viteLoadFallbackPlugin, d as viteReporterPlugin, f as viteResolvePlugin, i as viteBuildImportAnalysisPlugin, l as viteModulePreloadPolyfillPlugin, n as isolatedDeclarationPlugin, o as viteImportGlobPlugin, p as viteWebWorkerPostPlugin, r as oxcRuntimePlugin, s as viteJsonPlugin, u as viteReactRefreshWrapperPlugin } from "./shared/constructors-DDRbtWM1.mjs";
  8. import { a as minify$1, i as transformSync$1, n as resolveTsconfig, o as minifySync$1, r as transform$1, t as TsconfigCache$1 } from "./shared/resolve-tsconfig-DRWFAQ3v.mjs";
  9. import { pathToFileURL } from "node:url";
  10. //#region src/api/dev/dev-engine.ts
  11. var import_binding = /* @__PURE__ */ __toESM(require_binding(), 1);
  12. /** Read-only view over the engine's module graph, kept current across rebuilds. */
  13. var DevEngineModuleGraph = class {
  14. #inner;
  15. constructor(inner) {
  16. this.#inner = inner;
  17. }
  18. /**
  19. * Get additional information about the module in question.
  20. *
  21. * @returns Module information for that module. `null` if the module could not be found.
  22. */
  23. getModuleInfo(moduleId) {
  24. return this.#inner.getModuleInfo(moduleId) ?? null;
  25. }
  26. /**
  27. * Get all module ids in the current module graph.
  28. *
  29. * @returns An array of module ids.
  30. */
  31. getModuleIds() {
  32. return this.#inner.getModuleIds();
  33. }
  34. };
  35. var DevEngine = class DevEngine {
  36. #inner;
  37. #cachedBuildFinishPromise = null;
  38. #asyncRuntimeReleased = false;
  39. moduleGraph;
  40. static async create(inputOptions, outputOptions = {}, devOptions = {}) {
  41. inputOptions = await PluginDriver.callOptionsHook(inputOptions);
  42. const options = await createBundlerOptions(inputOptions, outputOptions, false);
  43. const userOnHmrUpdates = devOptions.onHmrUpdates;
  44. const bindingOnHmrUpdates = userOnHmrUpdates ? function(rawResult) {
  45. const result = normalizeBindingResult(rawResult);
  46. if (result instanceof Error) {
  47. userOnHmrUpdates(result);
  48. return;
  49. }
  50. const [updates, changedFiles] = result;
  51. userOnHmrUpdates({
  52. updates,
  53. changedFiles
  54. });
  55. } : void 0;
  56. const userOnOutput = devOptions.onOutput;
  57. const bindingOnOutput = userOnOutput ? function(rawResult) {
  58. const result = normalizeBindingResult(rawResult);
  59. if (result instanceof Error) {
  60. userOnOutput(result);
  61. return;
  62. }
  63. userOnOutput(transformToRollupOutput(result));
  64. } : void 0;
  65. const userOnAdditionalAssets = devOptions.onAdditionalAssets;
  66. const bindingDevOptions = {
  67. onHmrUpdates: bindingOnHmrUpdates,
  68. onOutput: bindingOnOutput,
  69. onAdditionalAssets: userOnAdditionalAssets ? function(output) {
  70. userOnAdditionalAssets(transformToRollupOutput(output));
  71. } : void 0,
  72. rebuildStrategy: devOptions.rebuildStrategy ? devOptions.rebuildStrategy === "always" ? import_binding.BindingRebuildStrategy.Always : import_binding.BindingRebuildStrategy.Never : void 0,
  73. watch: devOptions.watch && {
  74. enabled: devOptions.watch.enabled,
  75. skipWrite: devOptions.watch.skipWrite,
  76. usePolling: devOptions.watch.usePolling,
  77. pollInterval: devOptions.watch.pollInterval,
  78. useDebounce: devOptions.watch.useDebounce,
  79. debounceDuration: devOptions.watch.debounceDuration,
  80. compareContentsForPolling: devOptions.watch.compareContentsForPolling,
  81. debounceTickRate: devOptions.watch.debounceTickRate,
  82. include: normalizedStringOrRegex(devOptions.watch.include),
  83. exclude: normalizedStringOrRegex(devOptions.watch.exclude)
  84. },
  85. hotUpdate: devOptions.hotUpdate
  86. };
  87. const inner = new import_binding.BindingDevEngine(options.bundlerOptions, bindingDevOptions);
  88. (0, import_binding.startAsyncRuntime)();
  89. return new DevEngine(inner);
  90. }
  91. constructor(inner) {
  92. this.#inner = inner;
  93. this.moduleGraph = new DevEngineModuleGraph(inner);
  94. }
  95. async run() {
  96. await this.#inner.run();
  97. }
  98. async ensureCurrentBuildFinish() {
  99. if (this.#cachedBuildFinishPromise) return this.#cachedBuildFinishPromise;
  100. const promise = this.#inner.ensureCurrentBuildFinish().then(() => {
  101. this.#cachedBuildFinishPromise = null;
  102. });
  103. this.#cachedBuildFinishPromise = promise;
  104. return promise;
  105. }
  106. async getBundleState() {
  107. return this.#inner.getBundleState();
  108. }
  109. async ensureLatestBuildOutput() {
  110. unwrapBindingResult(await this.#inner.ensureLatestBuildOutput());
  111. }
  112. triggerFullBuild() {
  113. this.#inner.triggerFullBuild();
  114. }
  115. /**
  116. * Client-connect signal (the clientId hello): creates the per-client session
  117. * with an empty ship map. Reconnects arrive as fresh clientIds.
  118. */
  119. async registerClient(clientId) {
  120. await this.#inner.registerClient(clientId);
  121. }
  122. /**
  123. * Delivery notification for the payload `filename`. Call it when the client
  124. * reports that it ran the payload (Vite appends a
  125. * `__rolldown_runtime__.payloadDelivered(filename)` statement to every patch
  126. * and lazy chunk). A completed HTTP response is not enough: the bytes may not
  127. * have evaluated yet. Records the payload's modules as shipped to that client.
  128. */
  129. async notifyPayloadDelivered(filename) {
  130. await this.#inner.notifyPayloadDelivered(filename);
  131. }
  132. async removeClient(clientId) {
  133. await this.#inner.removeClient(clientId);
  134. }
  135. async close() {
  136. const shouldRelease = !this.#asyncRuntimeReleased;
  137. this.#asyncRuntimeReleased = true;
  138. try {
  139. await this.#inner.close();
  140. } finally {
  141. if (shouldRelease) (0, import_binding.shutdownAsyncRuntime)();
  142. }
  143. }
  144. /**
  145. * Compile a lazy entry module and return HMR-style patch code.
  146. *
  147. * This is called when a dynamically imported module is first requested at runtime.
  148. * The module was previously stubbed with a proxy, and now we need to compile the
  149. * actual module and its dependencies.
  150. *
  151. * @param moduleId - The absolute file path of the module to compile
  152. * @param clientId - The client ID requesting this compilation
  153. * @returns The compiled chunk: its code plus the filename whose delivery the
  154. * dev server reports via {@link notifyPayloadDelivered}
  155. */
  156. async compileEntry(moduleId, clientId) {
  157. return this.#inner.compileEntry(moduleId, clientId);
  158. }
  159. };
  160. //#endregion
  161. //#region src/api/dev/index.ts
  162. const dev = (...args) => DevEngine.create(...args);
  163. //#endregion
  164. //#region src/types/external-memory-handle.ts
  165. const symbolForExternalMemoryHandle = "__rolldown_external_memory_handle__";
  166. /**
  167. * Frees the external memory held by the given handle.
  168. *
  169. * This is useful when you want to manually release memory held by Rust objects
  170. * (like `OutputChunk` or `OutputAsset`) before they are garbage collected.
  171. *
  172. * @param handle - The object with external memory to free
  173. * @param keepDataAlive - If true, evaluates all lazy fields before freeing memory (default: false).
  174. * This will take time to copy data from Rust to JavaScript, but prevents errors
  175. * when accessing properties after the memory is freed.
  176. * @returns Status object with `freed` boolean and optional `reason` string.
  177. * - `{ freed: true }` if memory was successfully freed
  178. * - `{ freed: false, reason: "..." }` if memory couldn't be freed (e.g., already freed or other references exist)
  179. *
  180. * @example
  181. * ```typescript
  182. * import { freeExternalMemory } from 'rolldown/experimental';
  183. *
  184. * const output = await bundle.generate();
  185. * const chunk = output.output[0];
  186. *
  187. * // Use the chunk...
  188. *
  189. * // Manually free the memory (fast, but accessing properties after will throw)
  190. * const status = freeExternalMemory(chunk); // { freed: true }
  191. * const statusAgain = freeExternalMemory(chunk); // { freed: false, reason: "Memory has already been freed" }
  192. *
  193. * // Keep data alive before freeing (slower, but data remains accessible)
  194. * freeExternalMemory(chunk, true); // Evaluates all lazy fields first
  195. * console.log(chunk.code); // OK - data was copied to JavaScript before freeing
  196. *
  197. * // Without keepDataAlive, accessing chunk properties after freeing will throw an error
  198. * ```
  199. */
  200. function freeExternalMemory(handle, keepDataAlive = false) {
  201. return handle[symbolForExternalMemoryHandle](keepDataAlive);
  202. }
  203. //#endregion
  204. //#region src/api/experimental.ts
  205. /**
  206. * This is an experimental API. Its behavior may change in the future.
  207. *
  208. * - Calling this API will only execute the `scan/build` stage of rolldown.
  209. * - `scan` will clean up all resources automatically, but if you want to ensure timely cleanup, you need to wait for the returned promise to resolve.
  210. *
  211. * @example To ensure cleanup of resources, use the returned promise to wait for the scan to complete.
  212. * ```ts
  213. * import { scan } from 'rolldown/api/experimental';
  214. *
  215. * const cleanupPromise = await scan(...);
  216. * await cleanupPromise;
  217. * // Now all resources have been cleaned up.
  218. * ```
  219. */
  220. const scan = async (rawInputOptions, rawOutputOptions = {}) => {
  221. validateOption("input", rawInputOptions);
  222. validateOption("output", rawOutputOptions);
  223. const inputOptions = await PluginDriver.callOptionsHook(rawInputOptions);
  224. const ret = await createBundlerOptions(inputOptions, rawOutputOptions, false);
  225. const bundler = new import_binding.BindingBundler();
  226. (0, import_binding.startAsyncRuntime)();
  227. let cleanedUp = false;
  228. async function cleanup() {
  229. if (cleanedUp) return;
  230. cleanedUp = true;
  231. try {
  232. await bundler.close();
  233. await ret.stopWorkers?.();
  234. } finally {
  235. (0, import_binding.shutdownAsyncRuntime)();
  236. }
  237. }
  238. let cleanupPromise = Promise.resolve();
  239. try {
  240. const result = await bundler.scan(ret.bundlerOptions);
  241. unwrapBindingResult(result);
  242. } catch (err) {
  243. await cleanup();
  244. throw err;
  245. } finally {
  246. cleanupPromise = cleanup();
  247. }
  248. return cleanupPromise;
  249. };
  250. //#endregion
  251. //#region src/plugin/parallel-plugin.ts
  252. function defineParallelPlugin(pluginPath) {
  253. return (options) => {
  254. return { _parallel: {
  255. fileUrl: pathToFileURL(pluginPath).href,
  256. options
  257. } };
  258. };
  259. }
  260. //#endregion
  261. //#region src/builtin-plugin/alias-plugin.ts
  262. function viteAliasPlugin(config) {
  263. return new BuiltinPlugin("builtin:vite-alias", config);
  264. }
  265. //#endregion
  266. //#region src/builtin-plugin/bundle-analyzer-plugin.ts
  267. /**
  268. * A plugin that analyzes bundle composition and generates detailed reports.
  269. *
  270. * The plugin outputs a file containing detailed information about:
  271. * - All chunks and their relationships
  272. * - Modules bundled in each chunk
  273. * - Import dependencies between chunks
  274. * - Reachable modules from each entry point
  275. *
  276. * @example
  277. * ```js
  278. * import { bundleAnalyzerPlugin } from 'rolldown/experimental';
  279. *
  280. * export default {
  281. * plugins: [
  282. * bundleAnalyzerPlugin()
  283. * ]
  284. * }
  285. * ```
  286. *
  287. * @example
  288. * **Custom filename**
  289. * ```js
  290. * import { bundleAnalyzerPlugin } from 'rolldown/experimental';
  291. *
  292. * export default {
  293. * plugins: [
  294. * bundleAnalyzerPlugin({
  295. * fileName: 'bundle-analysis.json'
  296. * })
  297. * ]
  298. * }
  299. * ```
  300. *
  301. * @example
  302. * **LLM-friendly markdown output**
  303. * ```js
  304. * import { bundleAnalyzerPlugin } from 'rolldown/experimental';
  305. *
  306. * export default {
  307. * plugins: [
  308. * bundleAnalyzerPlugin({
  309. * format: 'md'
  310. * })
  311. * ]
  312. * }
  313. * ```
  314. */
  315. function bundleAnalyzerPlugin(config) {
  316. return new BuiltinPlugin("builtin:bundle-analyzer", config);
  317. }
  318. //#endregion
  319. //#region src/builtin-plugin/transform-plugin.ts
  320. function viteTransformPlugin(config) {
  321. return new BuiltinPlugin("builtin:vite-transform", {
  322. ...config,
  323. include: normalizedStringOrRegex(config.include),
  324. exclude: normalizedStringOrRegex(config.exclude),
  325. jsxRefreshInclude: normalizedStringOrRegex(config.jsxRefreshInclude),
  326. jsxRefreshExclude: normalizedStringOrRegex(config.jsxRefreshExclude),
  327. yarnPnp: typeof process === "object" && !!process.versions?.pnp
  328. });
  329. }
  330. //#endregion
  331. //#region src/builtin-plugin/vite-manifest-plugin.ts
  332. function viteManifestPlugin(config) {
  333. return new BuiltinPlugin("builtin:vite-manifest", config);
  334. }
  335. //#endregion
  336. //#region src/experimental-index.ts
  337. /**
  338. * In-memory file system for browser builds.
  339. *
  340. * This is a re-export of the {@link https://github.com/streamich/memfs | memfs} package used by the WASI runtime.
  341. * It allows you to read and write files to a virtual filesystem when using rolldown in browser environments.
  342. *
  343. * - `fs`: A Node.js-compatible filesystem API (`IFs` from memfs)
  344. * - `volume`: The underlying `Volume` instance that stores the filesystem state
  345. *
  346. * Returns `undefined` in Node.js builds (only available in browser builds via `@rolldown/browser`).
  347. *
  348. * @example
  349. * ```typescript
  350. * import { memfs } from 'rolldown/experimental';
  351. *
  352. * // Write files to virtual filesystem before bundling
  353. * memfs?.volume.fromJSON({
  354. * '/src/index.js': 'export const foo = 42;',
  355. * '/package.json': '{"name": "my-app"}'
  356. * });
  357. *
  358. * // Read files from the virtual filesystem
  359. * const content = memfs?.fs.readFileSync('/src/index.js', 'utf8');
  360. * ```
  361. *
  362. * @see {@link https://github.com/streamich/memfs} for more information on the memfs API.
  363. */
  364. const memfs = void 0;
  365. /** @deprecated Use from `rolldown/utils` instead. */
  366. const parse = parse$1;
  367. /** @deprecated Use from `rolldown/utils` instead. */
  368. const parseSync = parseSync$1;
  369. /** @deprecated Use from `rolldown/utils` instead. */
  370. const minify = minify$1;
  371. /** @deprecated Use from `rolldown/utils` instead. */
  372. const minifySync = minifySync$1;
  373. /** @deprecated Use from `rolldown/utils` instead. */
  374. const transform = transform$1;
  375. /** @deprecated Use from `rolldown/utils` instead. */
  376. const transformSync = transformSync$1;
  377. /** @deprecated Use from `rolldown/utils` instead. */
  378. const TsconfigCache = TsconfigCache$1;
  379. //#endregion
  380. var BindingRebuildStrategy = import_binding.BindingRebuildStrategy;
  381. var ResolverFactory = import_binding.ResolverFactory;
  382. var getNativeMemoryStats = import_binding.getNativeMemoryStats;
  383. var isolatedDeclaration = import_binding.isolatedDeclaration;
  384. var isolatedDeclarationSync = import_binding.isolatedDeclarationSync;
  385. var moduleRunnerTransform = import_binding.moduleRunnerTransform;
  386. var resetNativeMemoryStats = import_binding.resetNativeMemoryStats;
  387. export { BindingRebuildStrategy, DevEngine, ResolverFactory, TsconfigCache, bundleAnalyzerPlugin, defineParallelPlugin, dev, viteDynamicImportVarsPlugin as dynamicImportVarsPlugin, viteDynamicImportVarsPlugin, freeExternalMemory, getNativeMemoryStats, viteImportGlobPlugin as importGlobPlugin, viteImportGlobPlugin, isolatedDeclaration, isolatedDeclarationPlugin, isolatedDeclarationSync, memfs, minify, minifySync, moduleRunnerTransform, oxcRuntimePlugin, parse, parseSync, resetNativeMemoryStats, resolveTsconfig, scan, transform, transformSync, viteAliasPlugin, viteBuildImportAnalysisPlugin, viteJsonPlugin, viteLoadFallbackPlugin, viteManifestPlugin, viteModulePreloadPolyfillPlugin, viteReactRefreshWrapperPlugin, viteReporterPlugin, viteResolvePlugin, viteTransformPlugin, viteWebWorkerPostPlugin };