rolldown 1.0.0-beta.7-commit.25f3c61 → 1.0.0-beta.7-commit.170d158

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/bin/cli.mjs +2 -0
  2. package/dist/{cjs/cli.cjs → cli.cjs} +4 -5
  3. package/dist/cli.mjs +1829 -0
  4. package/dist/{cjs/experimental-index.cjs → experimental-index.cjs} +3 -3
  5. package/dist/{esm/experimental-index.mjs → experimental-index.mjs} +13 -2
  6. package/dist/{cjs/index.cjs → index.cjs} +2 -2
  7. package/dist/index.mjs +5 -0
  8. package/dist/{cjs/parallel-plugin-worker.cjs → parallel-plugin-worker.cjs} +3 -4
  9. package/dist/parallel-plugin-worker.mjs +47 -0
  10. package/dist/parse-ast-index.cjs +4 -0
  11. package/dist/parse-ast-index.mjs +4 -0
  12. package/dist/shared/chunk-DUYDk_2O.mjs +33 -0
  13. package/dist/shared/{parse-ast-index-DNOUVcBy.mjs → parse-ast-index-5U4JtZBO.mjs} +108 -110
  14. package/dist/shared/{parse-ast-index-0ei4fTjl.cjs → parse-ast-index-BfKb9n4T.cjs} +1 -1
  15. package/dist/shared/prompt-W5YHe0v6.mjs +854 -0
  16. package/dist/shared/{src-BPcsb-4N.cjs → src-B0nHUJsv.cjs} +26 -7
  17. package/dist/shared/src-kyIoH7SP.mjs +4319 -0
  18. package/dist/tsconfig.tsbuildinfo +1 -1
  19. package/dist/types/api/rolldown/rolldown-build.d.ts +1 -0
  20. package/dist/types/binding.d.ts +8 -2
  21. package/dist/types/options/input-options.d.ts +5 -1
  22. package/package.json +32 -31
  23. package/bin/cli.js +0 -2
  24. package/dist/cjs/parse-ast-index.cjs +0 -4
  25. package/dist/esm/cli.mjs +0 -1755
  26. package/dist/esm/index.mjs +0 -4
  27. package/dist/esm/parallel-plugin-worker.mjs +0 -41
  28. package/dist/esm/parse-ast-index.mjs +0 -3
  29. package/dist/shared/prompt-C6jWWCza.mjs +0 -852
  30. package/dist/shared/src-DllTyFDp.mjs +0 -2888
  31. /package/dist/{cjs/parallel-plugin.cjs → parallel-plugin.cjs} +0 -0
  32. /package/dist/{esm/parallel-plugin.mjs → parallel-plugin.mjs} +0 -0
@@ -1,2888 +0,0 @@
1
- import { augmentCodeLocation, colors, error, import_binding, logCycleLoading, logInputHookInOutputPlugin, logInvalidLogPosition, logMinifyWarning, logMultiplyNotifyOption, logPluginError, parseAst } from "./parse-ast-index-DNOUVcBy.mjs";
2
- import path from "node:path";
3
- import { toJsonSchema } from "@valibot/to-json-schema";
4
- import * as v from "valibot";
5
- import { Buffer } from "node:buffer";
6
- import { availableParallelism } from "node:os";
7
- import { Worker } from "node:worker_threads";
8
-
9
- //#region package.json
10
- var version = "1.0.0-beta.7-commit.25f3c61";
11
- var description = "Fast JavaScript/TypeScript bundler in Rust with Rollup-compatible API.";
12
-
13
- //#endregion
14
- //#region src/builtin-plugin/utils.ts
15
- function makeBuiltinPluginCallable(plugin) {
16
- let callablePlugin = new import_binding.BindingCallableBuiltinPlugin(bindingifyBuiltInPlugin(plugin));
17
- const wrappedPlugin = plugin;
18
- for (const key in callablePlugin) wrappedPlugin[key] = function(...args) {
19
- return callablePlugin[key](...args);
20
- };
21
- return wrappedPlugin;
22
- }
23
- function bindingifyBuiltInPlugin(plugin) {
24
- return {
25
- __name: plugin.name,
26
- options: plugin._options
27
- };
28
- }
29
-
30
- //#endregion
31
- //#region src/builtin-plugin/constructors.ts
32
- var BuiltinPlugin = class {
33
- constructor(name, _options) {
34
- this.name = name;
35
- this._options = _options;
36
- }
37
- };
38
- function modulePreloadPolyfillPlugin(config) {
39
- return new BuiltinPlugin("builtin:module-preload-polyfill", config);
40
- }
41
- function dynamicImportVarsPlugin() {
42
- return new BuiltinPlugin("builtin:dynamic-import-vars");
43
- }
44
- function importGlobPlugin(config) {
45
- return new BuiltinPlugin("builtin:import-glob", config);
46
- }
47
- function manifestPlugin(config) {
48
- return new BuiltinPlugin("builtin:manifest", config);
49
- }
50
- function wasmHelperPlugin() {
51
- return new BuiltinPlugin("builtin:wasm-helper");
52
- }
53
- function wasmFallbackPlugin() {
54
- return new BuiltinPlugin("builtin:wasm-fallback");
55
- }
56
- function loadFallbackPlugin() {
57
- return new BuiltinPlugin("builtin:load-fallback");
58
- }
59
- function jsonPlugin(config) {
60
- return new BuiltinPlugin("builtin:json", config);
61
- }
62
- function buildImportAnalysisPlugin(config) {
63
- return new BuiltinPlugin("builtin:build-import-analysis", config);
64
- }
65
- function viteResolvePlugin(config) {
66
- const builtinPlugin = new BuiltinPlugin("builtin:vite-resolve", {
67
- ...config,
68
- runtime: process.versions.deno ? "deno" : process.versions.bun ? "bun" : "node"
69
- });
70
- return makeBuiltinPluginCallable(builtinPlugin);
71
- }
72
- function moduleFederationPlugin(config) {
73
- return new BuiltinPlugin("builtin:module-federation", {
74
- ...config,
75
- remotes: config.remotes && Object.entries(config.remotes).map(([name, remote]) => {
76
- if (typeof remote === "string") {
77
- const [entryGlobalName] = remote.split("@");
78
- const entry = remote.replace(entryGlobalName + "@", "");
79
- return {
80
- entry,
81
- name,
82
- entryGlobalName
83
- };
84
- }
85
- return {
86
- ...remote,
87
- name: remote.name ?? name
88
- };
89
- }),
90
- manifest: config.manifest === false ? void 0 : config.manifest === true ? {} : config.manifest
91
- });
92
- }
93
- function isolatedDeclarationPlugin(config) {
94
- return new BuiltinPlugin("builtin:isolated-declaration", config);
95
- }
96
-
97
- //#endregion
98
- //#region src/utils/misc.ts
99
- function arraify(value) {
100
- return Array.isArray(value) ? value : [value];
101
- }
102
- function isNullish(value) {
103
- return value === null || value === void 0;
104
- }
105
- function unimplemented(info) {
106
- if (info) throw new Error(`unimplemented: ${info}`);
107
- throw new Error("unimplemented");
108
- }
109
- function unreachable(info) {
110
- if (info) throw new Error(`unreachable: ${info}`);
111
- throw new Error("unreachable");
112
- }
113
- function unsupported(info) {
114
- throw new Error(`UNSUPPORTED: ${info}`);
115
- }
116
- function noop(..._args) {}
117
-
118
- //#endregion
119
- //#region src/log/logging.ts
120
- const LOG_LEVEL_SILENT = "silent";
121
- const LOG_LEVEL_ERROR = "error";
122
- const LOG_LEVEL_WARN = "warn";
123
- const LOG_LEVEL_INFO = "info";
124
- const LOG_LEVEL_DEBUG = "debug";
125
- const logLevelPriority = {
126
- [LOG_LEVEL_DEBUG]: 0,
127
- [LOG_LEVEL_INFO]: 1,
128
- [LOG_LEVEL_WARN]: 2,
129
- [LOG_LEVEL_SILENT]: 3
130
- };
131
-
132
- //#endregion
133
- //#region src/log/log-handler.ts
134
- const normalizeLog = (log) => typeof log === "string" ? { message: log } : typeof log === "function" ? normalizeLog(log()) : log;
135
- function getLogHandler(level, code, logger, pluginName, logLevel) {
136
- if (logLevelPriority[level] < logLevelPriority[logLevel]) return noop;
137
- return (log, pos) => {
138
- if (pos != null) logger(LOG_LEVEL_WARN, logInvalidLogPosition(pluginName));
139
- log = normalizeLog(log);
140
- if (log.code && !log.pluginCode) log.pluginCode = log.code;
141
- log.code = code;
142
- log.plugin = pluginName;
143
- logger(level, log);
144
- };
145
- }
146
-
147
- //#endregion
148
- //#region src/log/logger.ts
149
- function getLogger(plugins, onLog, logLevel, watchMode) {
150
- const minimalPriority = logLevelPriority[logLevel];
151
- const logger = (level, log, skipped = new Set()) => {
152
- const logPriority = logLevelPriority[level];
153
- if (logPriority < minimalPriority) return;
154
- for (const plugin of getSortedPlugins("onLog", plugins)) {
155
- if (skipped.has(plugin)) continue;
156
- const { onLog: pluginOnLog } = plugin;
157
- if (pluginOnLog) {
158
- const getLogHandler$1 = (level$1) => {
159
- if (logLevelPriority[level$1] < minimalPriority) return () => {};
160
- return (log$1) => logger(level$1, normalizeLog(log$1), new Set(skipped).add(plugin));
161
- };
162
- const handler = "handler" in pluginOnLog ? pluginOnLog.handler : pluginOnLog;
163
- if (handler.call({
164
- debug: getLogHandler$1(LOG_LEVEL_DEBUG),
165
- error: (log$1) => error(normalizeLog(log$1)),
166
- info: getLogHandler$1(LOG_LEVEL_INFO),
167
- meta: {
168
- rollupVersion: "4.23.0",
169
- rolldownVersion: VERSION,
170
- watchMode
171
- },
172
- warn: getLogHandler$1(LOG_LEVEL_WARN),
173
- pluginName: plugin.name || "unknown"
174
- }, level, log) === false) return;
175
- }
176
- }
177
- onLog(level, log);
178
- };
179
- return logger;
180
- }
181
- const getOnLog = (config, logLevel, printLog = defaultPrintLog) => {
182
- const { onwarn, onLog } = config;
183
- const defaultOnLog = getDefaultOnLog(printLog, onwarn);
184
- if (onLog) {
185
- const minimalPriority = logLevelPriority[logLevel];
186
- return (level, log) => onLog(level, addLogToString(log), (level$1, handledLog) => {
187
- if (level$1 === LOG_LEVEL_ERROR) return error(normalizeLog(handledLog));
188
- if (logLevelPriority[level$1] >= minimalPriority) defaultOnLog(level$1, normalizeLog(handledLog));
189
- });
190
- }
191
- return defaultOnLog;
192
- };
193
- const getDefaultOnLog = (printLog, onwarn) => onwarn ? (level, log) => {
194
- if (level === LOG_LEVEL_WARN) onwarn(addLogToString(log), (warning) => printLog(LOG_LEVEL_WARN, normalizeLog(warning)));
195
- else printLog(level, log);
196
- } : printLog;
197
- const addLogToString = (log) => {
198
- Object.defineProperty(log, "toString", {
199
- value: () => getExtendedLogMessage(log),
200
- writable: true
201
- });
202
- return log;
203
- };
204
- const defaultPrintLog = (level, log) => {
205
- const message = getExtendedLogMessage(log);
206
- switch (level) {
207
- case LOG_LEVEL_WARN: return console.warn(message);
208
- case LOG_LEVEL_DEBUG: return console.debug(message);
209
- default: return console.info(message);
210
- }
211
- };
212
- const getExtendedLogMessage = (log) => {
213
- let prefix = "";
214
- if (log.plugin) prefix += `(${log.plugin} plugin) `;
215
- if (log.loc) prefix += `${relativeId(log.loc.file)} (${log.loc.line}:${log.loc.column}) `;
216
- return prefix + log.message;
217
- };
218
- function relativeId(id) {
219
- if (!path.isAbsolute(id)) return id;
220
- return path.relative(path.resolve(), id);
221
- }
222
-
223
- //#endregion
224
- //#region src/utils/normalize-hook.ts
225
- function normalizeHook(hook) {
226
- if (typeof hook === "function" || typeof hook === "string") return {
227
- handler: hook,
228
- options: {},
229
- meta: {}
230
- };
231
- if (typeof hook === "object" && hook !== null) {
232
- const { handler, order,...options } = hook;
233
- return {
234
- handler,
235
- options,
236
- meta: { order }
237
- };
238
- }
239
- unreachable("Invalid hook type");
240
- }
241
-
242
- //#endregion
243
- //#region src/constants/plugin.ts
244
- const ENUMERATED_INPUT_PLUGIN_HOOK_NAMES = [
245
- "options",
246
- "buildStart",
247
- "resolveId",
248
- "load",
249
- "transform",
250
- "moduleParsed",
251
- "buildEnd",
252
- "onLog",
253
- "resolveDynamicImport",
254
- "closeBundle",
255
- "closeWatcher",
256
- "watchChange"
257
- ];
258
- const ENUMERATED_OUTPUT_PLUGIN_HOOK_NAMES = [
259
- "augmentChunkHash",
260
- "outputOptions",
261
- "renderChunk",
262
- "renderStart",
263
- "renderError",
264
- "writeBundle",
265
- "generateBundle"
266
- ];
267
- const ENUMERATED_PLUGIN_HOOK_NAMES = [
268
- ...ENUMERATED_INPUT_PLUGIN_HOOK_NAMES,
269
- ...ENUMERATED_OUTPUT_PLUGIN_HOOK_NAMES,
270
- "footer",
271
- "banner",
272
- "intro",
273
- "outro"
274
- ];
275
- const DEFINED_HOOK_NAMES = {
276
- [ENUMERATED_PLUGIN_HOOK_NAMES[0]]: ENUMERATED_PLUGIN_HOOK_NAMES[0],
277
- [ENUMERATED_PLUGIN_HOOK_NAMES[1]]: ENUMERATED_PLUGIN_HOOK_NAMES[1],
278
- [ENUMERATED_PLUGIN_HOOK_NAMES[2]]: ENUMERATED_PLUGIN_HOOK_NAMES[2],
279
- [ENUMERATED_PLUGIN_HOOK_NAMES[3]]: ENUMERATED_PLUGIN_HOOK_NAMES[3],
280
- [ENUMERATED_PLUGIN_HOOK_NAMES[4]]: ENUMERATED_PLUGIN_HOOK_NAMES[4],
281
- [ENUMERATED_PLUGIN_HOOK_NAMES[5]]: ENUMERATED_PLUGIN_HOOK_NAMES[5],
282
- [ENUMERATED_PLUGIN_HOOK_NAMES[6]]: ENUMERATED_PLUGIN_HOOK_NAMES[6],
283
- [ENUMERATED_PLUGIN_HOOK_NAMES[7]]: ENUMERATED_PLUGIN_HOOK_NAMES[7],
284
- [ENUMERATED_PLUGIN_HOOK_NAMES[8]]: ENUMERATED_PLUGIN_HOOK_NAMES[8],
285
- [ENUMERATED_PLUGIN_HOOK_NAMES[9]]: ENUMERATED_PLUGIN_HOOK_NAMES[9],
286
- [ENUMERATED_PLUGIN_HOOK_NAMES[10]]: ENUMERATED_PLUGIN_HOOK_NAMES[10],
287
- [ENUMERATED_PLUGIN_HOOK_NAMES[11]]: ENUMERATED_PLUGIN_HOOK_NAMES[11],
288
- [ENUMERATED_PLUGIN_HOOK_NAMES[12]]: ENUMERATED_PLUGIN_HOOK_NAMES[12],
289
- [ENUMERATED_PLUGIN_HOOK_NAMES[13]]: ENUMERATED_PLUGIN_HOOK_NAMES[13],
290
- [ENUMERATED_PLUGIN_HOOK_NAMES[14]]: ENUMERATED_PLUGIN_HOOK_NAMES[14],
291
- [ENUMERATED_PLUGIN_HOOK_NAMES[15]]: ENUMERATED_PLUGIN_HOOK_NAMES[15],
292
- [ENUMERATED_PLUGIN_HOOK_NAMES[16]]: ENUMERATED_PLUGIN_HOOK_NAMES[16],
293
- [ENUMERATED_PLUGIN_HOOK_NAMES[17]]: ENUMERATED_PLUGIN_HOOK_NAMES[17],
294
- [ENUMERATED_PLUGIN_HOOK_NAMES[18]]: ENUMERATED_PLUGIN_HOOK_NAMES[18],
295
- [ENUMERATED_PLUGIN_HOOK_NAMES[19]]: ENUMERATED_PLUGIN_HOOK_NAMES[19],
296
- [ENUMERATED_PLUGIN_HOOK_NAMES[20]]: ENUMERATED_PLUGIN_HOOK_NAMES[20],
297
- [ENUMERATED_PLUGIN_HOOK_NAMES[21]]: ENUMERATED_PLUGIN_HOOK_NAMES[21],
298
- [ENUMERATED_PLUGIN_HOOK_NAMES[22]]: ENUMERATED_PLUGIN_HOOK_NAMES[22]
299
- };
300
-
301
- //#endregion
302
- //#region src/utils/async-flatten.ts
303
- async function asyncFlatten(array) {
304
- do
305
- array = (await Promise.all(array)).flat(Infinity);
306
- while (array.some((v$1) => v$1?.then));
307
- return array;
308
- }
309
-
310
- //#endregion
311
- //#region src/utils/normalize-plugin-option.ts
312
- const normalizePluginOption = async (plugins) => (await asyncFlatten([plugins])).filter(Boolean);
313
- function checkOutputPluginOption(plugins, onLog) {
314
- for (const plugin of plugins) for (const hook of ENUMERATED_INPUT_PLUGIN_HOOK_NAMES) if (hook in plugin) {
315
- delete plugin[hook];
316
- onLog(LOG_LEVEL_WARN, logInputHookInOutputPlugin(plugin.name, hook));
317
- }
318
- return plugins;
319
- }
320
- function normalizePlugins(plugins, anonymousPrefix) {
321
- for (const [index, plugin] of plugins.entries()) {
322
- if ("_parallel" in plugin) continue;
323
- if (plugin instanceof BuiltinPlugin) continue;
324
- if (!plugin.name) plugin.name = `${anonymousPrefix}${index + 1}`;
325
- }
326
- return plugins;
327
- }
328
- const ANONYMOUS_PLUGIN_PREFIX = "at position ";
329
- const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = "at output position ";
330
-
331
- //#endregion
332
- //#region src/plugin/minimal-plugin-context.ts
333
- var MinimalPluginContextImpl = class {
334
- info;
335
- warn;
336
- debug;
337
- meta;
338
- constructor(onLog, logLevel, pluginName, watchMode, hookName) {
339
- this.pluginName = pluginName;
340
- this.hookName = hookName;
341
- this.debug = getLogHandler(LOG_LEVEL_DEBUG, "PLUGIN_LOG", onLog, pluginName, logLevel);
342
- this.info = getLogHandler(LOG_LEVEL_INFO, "PLUGIN_LOG", onLog, pluginName, logLevel);
343
- this.warn = getLogHandler(LOG_LEVEL_WARN, "PLUGIN_WARNING", onLog, pluginName, logLevel);
344
- this.meta = {
345
- rollupVersion: "4.23.0",
346
- rolldownVersion: VERSION,
347
- watchMode
348
- };
349
- }
350
- error(e) {
351
- return error(logPluginError(normalizeLog(e), this.pluginName, { hook: this.hookName }));
352
- }
353
- };
354
-
355
- //#endregion
356
- //#region src/plugin/plugin-driver.ts
357
- var PluginDriver = class {
358
- static async callOptionsHook(inputOptions, watchMode = false) {
359
- const logLevel = inputOptions.logLevel || LOG_LEVEL_INFO;
360
- const plugins = getSortedPlugins("options", getObjectPlugins(await normalizePluginOption(inputOptions.plugins)));
361
- const logger = getLogger(plugins, getOnLog(inputOptions, logLevel), logLevel, watchMode);
362
- for (const plugin of plugins) {
363
- const name = plugin.name || "unknown";
364
- const options = plugin.options;
365
- if (options) {
366
- const { handler } = normalizeHook(options);
367
- const result = await handler.call(new MinimalPluginContextImpl(logger, logLevel, name, watchMode, "onLog"), inputOptions);
368
- if (result) inputOptions = result;
369
- }
370
- }
371
- return inputOptions;
372
- }
373
- static callOutputOptionsHook(rawPlugins, outputOptions, onLog, logLevel, watchMode) {
374
- const sortedPlugins = getSortedPlugins("outputOptions", getObjectPlugins(rawPlugins));
375
- for (const plugin of sortedPlugins) {
376
- const name = plugin.name || "unknown";
377
- const options = plugin.outputOptions;
378
- if (options) {
379
- const { handler } = normalizeHook(options);
380
- const result = handler.call(new MinimalPluginContextImpl(onLog, logLevel, name, watchMode), outputOptions);
381
- if (result) outputOptions = result;
382
- }
383
- }
384
- return outputOptions;
385
- }
386
- };
387
- function getObjectPlugins(plugins) {
388
- return plugins.filter((plugin) => {
389
- if (!plugin) return void 0;
390
- if ("_parallel" in plugin) return void 0;
391
- if (plugin instanceof BuiltinPlugin) return void 0;
392
- return plugin;
393
- });
394
- }
395
- function getSortedPlugins(hookName, plugins) {
396
- const pre = [];
397
- const normal = [];
398
- const post = [];
399
- for (const plugin of plugins) {
400
- const hook = plugin[hookName];
401
- if (hook) {
402
- if (typeof hook === "object") {
403
- if (hook.order === "pre") {
404
- pre.push(plugin);
405
- continue;
406
- }
407
- if (hook.order === "post") {
408
- post.push(plugin);
409
- continue;
410
- }
411
- }
412
- normal.push(plugin);
413
- }
414
- }
415
- return [
416
- ...pre,
417
- ...normal,
418
- ...post
419
- ];
420
- }
421
-
422
- //#endregion
423
- //#region src/utils/validator.ts
424
- const StringOrRegExpSchema = v.union([v.string(), v.instance(RegExp)]);
425
- const LogLevelSchema = v.union([
426
- v.literal("debug"),
427
- v.literal("info"),
428
- v.literal("warn")
429
- ]);
430
- const LogLevelOptionSchema = v.union([LogLevelSchema, v.literal("silent")]);
431
- const LogLevelWithErrorSchema = v.union([LogLevelSchema, v.literal("error")]);
432
- const RollupLogSchema = v.any();
433
- const RollupLogWithStringSchema = v.union([RollupLogSchema, v.string()]);
434
- const InputOptionSchema = v.union([
435
- v.string(),
436
- v.array(v.string()),
437
- v.record(v.string(), v.string())
438
- ]);
439
- const ExternalSchema = v.union([
440
- StringOrRegExpSchema,
441
- v.array(StringOrRegExpSchema),
442
- v.pipe(v.function(), v.args(v.tuple([
443
- v.string(),
444
- v.optional(v.string()),
445
- v.boolean()
446
- ])), v.returns(v.nullish(v.boolean())))
447
- ]);
448
- const ModuleTypesSchema = v.record(v.string(), v.union([
449
- v.literal("base64"),
450
- v.literal("binary"),
451
- v.literal("css"),
452
- v.literal("dataurl"),
453
- v.literal("empty"),
454
- v.literal("js"),
455
- v.literal("json"),
456
- v.literal("jsx"),
457
- v.literal("text"),
458
- v.literal("ts"),
459
- v.literal("tsx")
460
- ]));
461
- const JsxOptionsSchema = v.strictObject({
462
- development: v.pipe(v.optional(v.boolean()), v.description("Development specific information")),
463
- factory: v.pipe(v.optional(v.string()), v.description("Jsx element transformation")),
464
- fragment: v.pipe(v.optional(v.string()), v.description("Jsx fragment transformation")),
465
- importSource: v.pipe(v.optional(v.string()), v.description("Import the factory of element and fragment if mode is classic")),
466
- jsxImportSource: v.pipe(v.optional(v.string()), v.description("Import the factory of element and fragment if mode is automatic")),
467
- mode: v.pipe(v.optional(v.union([
468
- v.literal("classic"),
469
- v.literal("automatic"),
470
- v.literal("preserve")
471
- ])), v.description("Jsx transformation mode")),
472
- refresh: v.pipe(v.optional(v.boolean()), v.description("React refresh transformation"))
473
- });
474
- const HelperModeSchema = v.union([v.literal("Runtime"), v.literal("External")]);
475
- const DecoratorOptionSchema = v.object({
476
- legacy: v.optional(v.boolean()),
477
- emitDecoratorMetadata: v.optional(v.boolean())
478
- });
479
- const HelpersSchema = v.object({ mode: v.optional(HelperModeSchema) });
480
- const RewriteImportExtensionsSchema = v.union([
481
- v.literal("rewrite"),
482
- v.literal("remove"),
483
- v.boolean()
484
- ]);
485
- const TypescriptSchema = v.object({
486
- jsxPragma: v.optional(v.string()),
487
- jsxPragmaFrag: v.optional(v.string()),
488
- onlyRemoveTypeImports: v.optional(v.boolean()),
489
- allowNamespaces: v.optional(v.boolean()),
490
- allowDeclareFields: v.optional(v.boolean()),
491
- declaration: v.optional(v.object({
492
- stripInternal: v.optional(v.boolean()),
493
- sourcemap: v.optional(v.boolean())
494
- })),
495
- rewriteImportExtensions: v.optional(RewriteImportExtensionsSchema)
496
- });
497
- const AssumptionsSchema = v.object({
498
- ignoreFunctionLength: v.optional(v.boolean()),
499
- noDocumentAll: v.optional(v.boolean()),
500
- objectRestNoSymbols: v.optional(v.boolean()),
501
- pureGetters: v.optional(v.boolean()),
502
- setPublicClassFields: v.optional(v.boolean())
503
- });
504
- const TransformOptionsSchema = v.object({
505
- assumptions: v.optional(AssumptionsSchema),
506
- typescript: v.optional(TypescriptSchema),
507
- helpers: v.optional(HelpersSchema),
508
- decorators: v.optional(DecoratorOptionSchema)
509
- });
510
- const WatchOptionsSchema = v.strictObject({
511
- chokidar: v.optional(v.never(`The "watch.chokidar" option is deprecated, please use "watch.notify" instead of it`)),
512
- exclude: v.optional(v.union([StringOrRegExpSchema, v.array(StringOrRegExpSchema)])),
513
- include: v.optional(v.union([StringOrRegExpSchema, v.array(StringOrRegExpSchema)])),
514
- notify: v.pipe(v.optional(v.strictObject({
515
- compareContents: v.optional(v.boolean()),
516
- pollInterval: v.optional(v.number())
517
- })), v.description("Notify options")),
518
- skipWrite: v.pipe(v.optional(v.boolean()), v.description("Skip the bundle.write() step")),
519
- buildDelay: v.pipe(v.optional(v.number()), v.description("Throttle watch rebuilds"))
520
- });
521
- const ChecksOptionsSchema = v.strictObject({
522
- circularDependency: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warning when detecting circular dependency")),
523
- eval: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warning when detecting eval")),
524
- missingGlobalName: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warning when detecting missing global name")),
525
- missingNameOptionForIifeExport: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warning when detecting missing name option for iife export")),
526
- mixedExport: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warning when detecting mixed export")),
527
- unresolvedEntry: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warning when detecting unresolved entry")),
528
- unresolvedImport: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warning when detecting unresolved import")),
529
- filenameConflict: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warning when detecting filename conflict")),
530
- commonJsVariableInEsm: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warning when detecting common js variable in esm")),
531
- importIsUndefined: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warning when detecting import is undefined")),
532
- configurationFieldConflict: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warning when detecting configuration field conflict"))
533
- });
534
- const MinifyOptionsSchema = v.strictObject({
535
- mangle: v.boolean(),
536
- compress: v.boolean(),
537
- deadCodeElimination: v.boolean(),
538
- removeWhitespace: v.boolean()
539
- });
540
- const ResolveOptionsSchema = v.strictObject({
541
- alias: v.optional(v.record(v.string(), v.union([v.string(), v.array(v.string())]))),
542
- aliasFields: v.optional(v.array(v.array(v.string()))),
543
- conditionNames: v.optional(v.array(v.string())),
544
- extensionAlias: v.optional(v.record(v.string(), v.array(v.string()))),
545
- exportsFields: v.optional(v.array(v.array(v.string()))),
546
- extensions: v.optional(v.array(v.string())),
547
- mainFields: v.optional(v.array(v.string())),
548
- mainFiles: v.optional(v.array(v.string())),
549
- modules: v.optional(v.array(v.string())),
550
- symlinks: v.optional(v.boolean()),
551
- tsconfigFilename: v.optional(v.string())
552
- });
553
- const TreeshakingOptionsSchema = v.union([v.boolean(), v.looseObject({
554
- annotations: v.optional(v.boolean()),
555
- manualPureFunctions: v.optional(v.array(v.string())),
556
- unknownGlobalSideEffects: v.optional(v.boolean())
557
- })]);
558
- const OnLogSchema = v.pipe(v.function(), v.args(v.tuple([
559
- LogLevelSchema,
560
- RollupLogSchema,
561
- v.pipe(v.function(), v.args(v.tuple([LogLevelWithErrorSchema, RollupLogWithStringSchema])))
562
- ])));
563
- const OnwarnSchema = v.pipe(v.function(), v.args(v.tuple([RollupLogSchema, v.pipe(v.function(), v.args(v.tuple([v.union([RollupLogWithStringSchema, v.pipe(v.function(), v.returns(RollupLogWithStringSchema))])])))])));
564
- const InputOptionsSchema = v.strictObject({
565
- input: v.optional(InputOptionSchema),
566
- plugins: v.optional(v.custom(() => true)),
567
- external: v.optional(ExternalSchema),
568
- resolve: v.optional(ResolveOptionsSchema),
569
- cwd: v.pipe(v.optional(v.string()), v.description("Current working directory")),
570
- platform: v.pipe(v.optional(v.union([
571
- v.literal("browser"),
572
- v.literal("neutral"),
573
- v.literal("node")
574
- ])), v.description(`Platform for which the code should be generated (node, ${colors.underline("browser")}, neutral)`)),
575
- shimMissingExports: v.pipe(v.optional(v.boolean()), v.description("Create shim variables for missing exports")),
576
- treeshake: v.optional(TreeshakingOptionsSchema),
577
- logLevel: v.pipe(v.optional(LogLevelOptionSchema), v.description(`Log level (${colors.dim("silent")}, ${colors.underline(colors.gray("info"))}, debug, ${colors.yellow("warn")})`)),
578
- onLog: v.optional(OnLogSchema),
579
- onwarn: v.optional(OnwarnSchema),
580
- moduleTypes: v.pipe(v.optional(ModuleTypesSchema), v.description("Module types for customized extensions")),
581
- experimental: v.optional(v.strictObject({
582
- disableLiveBindings: v.optional(v.boolean()),
583
- enableComposingJsPlugins: v.optional(v.boolean()),
584
- resolveNewUrlToAsset: v.optional(v.boolean()),
585
- strictExecutionOrder: v.optional(v.boolean()),
586
- hmr: v.optional(v.boolean())
587
- })),
588
- define: v.pipe(v.optional(v.record(v.string(), v.string())), v.description("Define global variables")),
589
- inject: v.optional(v.record(v.string(), v.union([v.string(), v.tuple([v.string(), v.string()])]))),
590
- profilerNames: v.optional(v.boolean()),
591
- jsx: v.optional(v.union([
592
- v.boolean(),
593
- JsxOptionsSchema,
594
- v.string("react"),
595
- v.string("react-jsx"),
596
- v.string("preserve")
597
- ])),
598
- transform: v.optional(TransformOptionsSchema),
599
- watch: v.optional(v.union([WatchOptionsSchema, v.literal(false)])),
600
- dropLabels: v.pipe(v.optional(v.array(v.string())), v.description("Remove labeled statements with these label names")),
601
- checks: v.optional(ChecksOptionsSchema),
602
- keepNames: v.pipe(v.optional(v.boolean()), v.description("Keep function/class name"))
603
- });
604
- const InputCliOverrideSchema = v.strictObject({
605
- external: v.pipe(v.optional(v.array(v.string())), v.description("Comma-separated list of module ids to exclude from the bundle `<module-id>,...`")),
606
- inject: v.pipe(v.optional(v.record(v.string(), v.string())), v.description("Inject import statements on demand")),
607
- treeshake: v.pipe(v.optional(v.boolean()), v.description("enable treeshaking")),
608
- jsx: v.pipe(v.optional(JsxOptionsSchema), v.description("enable jsx"))
609
- });
610
- const InputCliOptionsSchema = v.omit(v.strictObject({
611
- ...InputOptionsSchema.entries,
612
- ...InputCliOverrideSchema.entries
613
- }), [
614
- "input",
615
- "plugins",
616
- "onwarn",
617
- "onLog",
618
- "resolve",
619
- "experimental",
620
- "profilerNames",
621
- "watch"
622
- ]);
623
- var ESTarget = /* @__PURE__ */ function(ESTarget$1) {
624
- ESTarget$1["ES6"] = "es6";
625
- ESTarget$1["ES2015"] = "es2015";
626
- ESTarget$1["ES2016"] = "es2016";
627
- ESTarget$1["ES2017"] = "es2017";
628
- ESTarget$1["ES2018"] = "es2018";
629
- ESTarget$1["ES2019"] = "es2019";
630
- ESTarget$1["ES2020"] = "es2020";
631
- ESTarget$1["ES2021"] = "es2021";
632
- ESTarget$1["ES2022"] = "es2022";
633
- ESTarget$1["ES2023"] = "es2023";
634
- ESTarget$1["ES2024"] = "es2024";
635
- ESTarget$1["ESNext"] = "esnext";
636
- return ESTarget$1;
637
- }(ESTarget || {});
638
- const ModuleFormatSchema = v.union([
639
- v.literal("es"),
640
- v.literal("cjs"),
641
- v.literal("esm"),
642
- v.literal("module"),
643
- v.literal("commonjs"),
644
- v.literal("iife"),
645
- v.literal("umd")
646
- ]);
647
- const AddonFunctionSchema = v.pipe(v.function(), v.args(v.tuple([v.custom(() => true)])), v.returnsAsync(v.unionAsync([v.string(), v.pipeAsync(v.promise(), v.awaitAsync(), v.string())])));
648
- const ChunkFileNamesSchema = v.union([v.string(), v.pipe(v.function(), v.args(v.tuple([v.custom(() => true)])), v.returns(v.string()))]);
649
- const AssetFileNamesSchema = v.union([v.string(), v.pipe(v.function(), v.args(v.tuple([v.custom(() => true)])), v.returns(v.string()))]);
650
- const SanitizeFileNameSchema = v.union([v.boolean(), v.pipe(v.function(), v.args(v.tuple([v.string()])), v.returns(v.string()))]);
651
- const GlobalsFunctionSchema = v.pipe(v.function(), v.args(v.tuple([v.string()])), v.returns(v.string()));
652
- const AdvancedChunksSchema = v.strictObject({
653
- minSize: v.optional(v.number()),
654
- maxSize: v.optional(v.number()),
655
- minModuleSize: v.optional(v.number()),
656
- maxModuleSize: v.optional(v.number()),
657
- minShareCount: v.optional(v.number()),
658
- groups: v.optional(v.array(v.strictObject({
659
- name: v.string(),
660
- test: v.optional(v.union([v.string(), v.instance(RegExp)])),
661
- priority: v.optional(v.number()),
662
- minSize: v.optional(v.number()),
663
- minShareCount: v.optional(v.number()),
664
- maxSize: v.optional(v.number()),
665
- minModuleSize: v.optional(v.number()),
666
- maxModuleSize: v.optional(v.number())
667
- })))
668
- });
669
- const OutputOptionsSchema = v.strictObject({
670
- dir: v.pipe(v.optional(v.string()), v.description("Output directory, defaults to `dist` if `file` is not set")),
671
- file: v.pipe(v.optional(v.string()), v.description("Single output file")),
672
- exports: v.pipe(v.optional(v.union([
673
- v.literal("auto"),
674
- v.literal("named"),
675
- v.literal("default"),
676
- v.literal("none")
677
- ])), v.description(`Specify a export mode (${colors.underline("auto")}, named, default, none)`)),
678
- hashCharacters: v.pipe(v.optional(v.union([
679
- v.literal("base64"),
680
- v.literal("base36"),
681
- v.literal("hex")
682
- ])), v.description("Use the specified character set for file hashes")),
683
- format: v.pipe(v.optional(ModuleFormatSchema), v.description(`Output format of the generated bundle (supports ${colors.underline("esm")}, cjs, and iife)`)),
684
- sourcemap: v.pipe(v.optional(v.union([
685
- v.boolean(),
686
- v.literal("inline"),
687
- v.literal("hidden")
688
- ])), v.description(`Generate sourcemap (\`-s inline\` for inline, or ${colors.bold("pass the `-s` on the last argument if you want to generate `.map` file")})`)),
689
- sourcemapDebugIds: v.pipe(v.optional(v.boolean()), v.description("Inject sourcemap debug IDs")),
690
- sourcemapIgnoreList: v.optional(v.union([v.boolean(), v.custom(() => true)])),
691
- sourcemapPathTransform: v.optional(v.custom(() => true)),
692
- banner: v.optional(v.union([v.string(), AddonFunctionSchema])),
693
- footer: v.optional(v.union([v.string(), AddonFunctionSchema])),
694
- intro: v.optional(v.union([v.string(), AddonFunctionSchema])),
695
- outro: v.optional(v.union([v.string(), AddonFunctionSchema])),
696
- extend: v.pipe(v.optional(v.boolean()), v.description("Extend global variable defined by name in IIFE / UMD formats")),
697
- esModule: v.optional(v.union([v.boolean(), v.literal("if-default-prop")])),
698
- assetFileNames: v.optional(AssetFileNamesSchema),
699
- entryFileNames: v.optional(ChunkFileNamesSchema),
700
- chunkFileNames: v.optional(ChunkFileNamesSchema),
701
- cssEntryFileNames: v.optional(ChunkFileNamesSchema),
702
- cssChunkFileNames: v.optional(ChunkFileNamesSchema),
703
- sanitizeFileName: v.optional(SanitizeFileNameSchema),
704
- minify: v.pipe(v.optional(v.union([
705
- v.boolean(),
706
- v.string("dce-only"),
707
- MinifyOptionsSchema
708
- ])), v.description("Minify the bundled file")),
709
- name: v.pipe(v.optional(v.string()), v.description("Name for UMD / IIFE format outputs")),
710
- globals: v.pipe(v.optional(v.union([v.record(v.string(), v.string()), GlobalsFunctionSchema])), v.description("Global variable of UMD / IIFE dependencies (syntax: `key=value`)")),
711
- externalLiveBindings: v.pipe(v.optional(v.boolean()), v.description("external live bindings")),
712
- inlineDynamicImports: v.pipe(v.optional(v.boolean()), v.description("Inline dynamic imports")),
713
- advancedChunks: v.optional(AdvancedChunksSchema),
714
- comments: v.pipe(v.optional(v.union([v.literal("none"), v.literal("preserve-legal")])), v.description("Control comments in the output")),
715
- target: v.pipe(v.optional(v.enum(ESTarget)), v.description("The JavaScript target environment")),
716
- plugins: v.optional(v.custom(() => true))
717
- });
718
- const getAddonDescription = (placement, wrapper) => {
719
- return `Code to insert the ${colors.bold(placement)} of the bundled file (${colors.bold(wrapper)} the wrapper function)`;
720
- };
721
- const OutputCliOverrideSchema = v.strictObject({
722
- assetFileNames: v.pipe(v.optional(v.string()), v.description("Name pattern for asset files")),
723
- entryFileNames: v.pipe(v.optional(v.string()), v.description("Name pattern for emitted entry chunks")),
724
- chunkFileNames: v.pipe(v.optional(v.string()), v.description("Name pattern for emitted secondary chunks")),
725
- cssEntryFileNames: v.pipe(v.optional(v.string()), v.description("Name pattern for emitted css entry chunks")),
726
- cssChunkFileNames: v.pipe(v.optional(v.string()), v.description("Name pattern for emitted css secondary chunks")),
727
- sanitizeFileName: v.pipe(v.optional(v.boolean()), v.description("Sanitize file name")),
728
- banner: v.pipe(v.optional(v.string()), v.description(getAddonDescription("top", "outside"))),
729
- footer: v.pipe(v.optional(v.string()), v.description(getAddonDescription("bottom", "outside"))),
730
- intro: v.pipe(v.optional(v.string()), v.description(getAddonDescription("top", "inside"))),
731
- outro: v.pipe(v.optional(v.string()), v.description(getAddonDescription("bottom", "inside"))),
732
- esModule: v.pipe(v.optional(v.boolean()), v.description("Always generate `__esModule` marks in non-ESM formats, defaults to `if-default-prop` (use `--no-esModule` to always disable)")),
733
- globals: v.pipe(v.optional(v.record(v.string(), v.string())), v.description("Global variable of UMD / IIFE dependencies (syntax: `key=value`)")),
734
- advancedChunks: v.pipe(v.optional(v.strictObject({
735
- minSize: v.pipe(v.optional(v.number()), v.description("Minimum size of the chunk")),
736
- minShareCount: v.pipe(v.optional(v.number()), v.description("Minimum share count of the chunk"))
737
- })), v.description("Global variable of UMD / IIFE dependencies (syntax: `key=value`)")),
738
- minify: v.pipe(v.optional(v.boolean()), v.description("Minify the bundled file"))
739
- });
740
- const OutputCliOptionsSchema = v.omit(v.strictObject({
741
- ...OutputOptionsSchema.entries,
742
- ...OutputCliOverrideSchema.entries
743
- }), [
744
- "sourcemapIgnoreList",
745
- "sourcemapPathTransform",
746
- "plugins"
747
- ]);
748
- const CliOptionsSchema = v.strictObject({
749
- config: v.pipe(v.optional(v.union([v.string(), v.boolean()])), v.description("Path to the config file (default: `rolldown.config.js`)")),
750
- help: v.pipe(v.optional(v.boolean()), v.description("Show help")),
751
- version: v.pipe(v.optional(v.boolean()), v.description("Show version number")),
752
- watch: v.pipe(v.optional(v.boolean()), v.description("Watch files in bundle and rebuild on changes")),
753
- ...InputCliOptionsSchema.entries,
754
- ...OutputCliOptionsSchema.entries
755
- });
756
- function validateCliOptions(options) {
757
- let parsed = v.safeParse(CliOptionsSchema, options);
758
- return [parsed.output, parsed.issues?.map((issue) => {
759
- const option = issue.path?.map((pathItem) => pathItem.key).join(" ");
760
- return `Invalid value for option ${option}: ${issue.message}`;
761
- })];
762
- }
763
- const inputHelperMsgRecord = { output: { ignored: true } };
764
- const outputHelperMsgRecord = {};
765
- function validateOption(key, options) {
766
- if (process.env.ROLLDOWN_OPTIONS_VALIDATION === "loose") return;
767
- let parsed = v.safeParse(key === "input" ? InputOptionsSchema : OutputOptionsSchema, options);
768
- if (!parsed.success) {
769
- const errors = parsed.issues.map((issue) => {
770
- const issuePaths = issue.path.map((path$1) => path$1.key);
771
- let issueMsg = issue.message;
772
- if (issue.type === "union") {
773
- const subIssue = issue.issues?.find((i) => !(i.type !== issue.received && i.input === issue.input));
774
- if (subIssue) {
775
- if (subIssue.path) issuePaths.push(subIssue.path.map((path$1) => path$1.key));
776
- issueMsg = subIssue.message;
777
- }
778
- }
779
- const stringPath = issuePaths.join(".");
780
- const helper = key === "input" ? inputHelperMsgRecord[stringPath] : outputHelperMsgRecord[stringPath];
781
- if (helper && helper.ignored) return "";
782
- return `- For the "${stringPath}". ${issueMsg}. ${helper ? helper.msg : ""}`;
783
- }).filter(Boolean);
784
- if (errors.length) throw new Error(`Failed validate ${key} options.\n` + errors.join("\n"));
785
- }
786
- }
787
- function getInputCliKeys() {
788
- return v.keyof(InputCliOptionsSchema).options;
789
- }
790
- function getOutputCliKeys() {
791
- return v.keyof(OutputCliOptionsSchema).options;
792
- }
793
- function getJsonSchema() {
794
- return toJsonSchema(CliOptionsSchema);
795
- }
796
-
797
- //#endregion
798
- //#region src/constants/plugin-context.ts
799
- const SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF = Symbol("plugin-context-resolve-caller");
800
-
801
- //#endregion
802
- //#region src/options/normalized-input-options.ts
803
- var NormalizedInputOptionsImpl = class {
804
- inner;
805
- constructor(inner, onLog) {
806
- this.onLog = onLog;
807
- this.inner = inner;
808
- }
809
- get shimMissingExports() {
810
- return this.inner.shimMissingExports;
811
- }
812
- get input() {
813
- return this.inner.input;
814
- }
815
- get cwd() {
816
- return this.inner.cwd ?? void 0;
817
- }
818
- get platform() {
819
- return this.inner.platform;
820
- }
821
- };
822
-
823
- //#endregion
824
- //#region src/types/sourcemap.ts
825
- function bindingifySourcemap$1(map) {
826
- if (map == null) return;
827
- return { inner: typeof map === "string" ? map : {
828
- file: map.file ?? void 0,
829
- mappings: map.mappings,
830
- sourceRoot: "sourceRoot" in map ? map.sourceRoot ?? void 0 : void 0,
831
- sources: map.sources?.map((s) => s ?? void 0),
832
- sourcesContent: map.sourcesContent?.map((s) => s ?? void 0),
833
- names: map.names,
834
- x_google_ignoreList: map.x_google_ignoreList,
835
- debugId: "debugId" in map ? map.debugId : void 0
836
- } };
837
- }
838
-
839
- //#endregion
840
- //#region src/utils/error.ts
841
- function normalizeErrors(rawErrors) {
842
- const errors = rawErrors.map((e) => e instanceof Error ? e : Object.assign(new Error(), {
843
- kind: e.kind,
844
- message: e.message,
845
- stack: void 0
846
- }));
847
- let summary = `Build failed with ${errors.length} error${errors.length < 2 ? "" : "s"}:\n`;
848
- for (let i = 0; i < errors.length; i++) {
849
- summary += "\n";
850
- if (i >= 5) {
851
- summary += "...";
852
- break;
853
- }
854
- summary += getErrorMessage(errors[i]);
855
- }
856
- const wrapper = new Error(summary);
857
- Object.defineProperty(wrapper, "errors", {
858
- configurable: true,
859
- enumerable: true,
860
- get: () => errors,
861
- set: (value) => Object.defineProperty(wrapper, "errors", {
862
- configurable: true,
863
- enumerable: true,
864
- value
865
- })
866
- });
867
- return wrapper;
868
- }
869
- function getErrorMessage(e) {
870
- if (Object.hasOwn(e, "kind")) return e.message;
871
- let s = "";
872
- if (e.plugin) s += `[plugin ${e.plugin}]`;
873
- const id = e.id ?? e.loc?.file;
874
- if (id) {
875
- s += " " + id;
876
- if (e.loc) s += `:${e.loc.line}:${e.loc.column}`;
877
- }
878
- if (s) s += "\n";
879
- const message = `${e.name ?? "Error"}: ${e.message}`;
880
- s += message;
881
- if (e.frame) s = joinNewLine(s, e.frame);
882
- if (e.stack) s = joinNewLine(s, e.stack.replace(message, ""));
883
- return s;
884
- }
885
- function joinNewLine(s1, s2) {
886
- return s1.replace(/\n+$/, "") + "\n" + s2.replace(/^\n+/, "");
887
- }
888
-
889
- //#endregion
890
- //#region src/utils/resolved-external.ts
891
- function transformResolvedExternal(bindingResolvedExternal$1) {
892
- switch (bindingResolvedExternal$1.type) {
893
- case "Bool": return bindingResolvedExternal$1.field0;
894
- case "Absolute": return "absolute";
895
- case "Relative": unreachable(`The PluginContext resolve result external couldn't be 'relative'`);
896
- }
897
- }
898
- function bindingResolvedExternal(external) {
899
- if (typeof external === "boolean") return {
900
- type: "Bool",
901
- field0: external
902
- };
903
- if (external === "absolute") return { type: "Absolute" };
904
- if (external === "relative") return { type: "Relative" };
905
- }
906
-
907
- //#endregion
908
- //#region src/utils/transform-module-info.ts
909
- function transformModuleInfo(info, option) {
910
- return {
911
- get ast() {
912
- return unsupported("ModuleInfo#ast");
913
- },
914
- get code() {
915
- return info.code;
916
- },
917
- id: info.id,
918
- importers: info.importers,
919
- dynamicImporters: info.dynamicImporters,
920
- importedIds: info.importedIds,
921
- dynamicallyImportedIds: info.dynamicallyImportedIds,
922
- exports: info.exports,
923
- isEntry: info.isEntry,
924
- ...option
925
- };
926
- }
927
-
928
- //#endregion
929
- //#region src/utils/transform-side-effects.ts
930
- function bindingifySideEffects(sideEffects) {
931
- switch (sideEffects) {
932
- case true: return import_binding.BindingHookSideEffects.True;
933
- case false: return import_binding.BindingHookSideEffects.False;
934
- case "no-treeshake": return import_binding.BindingHookSideEffects.NoTreeshake;
935
- case null:
936
- case void 0: return void 0;
937
- default: throw new Error(`Unexpected side effects: ${sideEffects}`);
938
- }
939
- }
940
-
941
- //#endregion
942
- //#region src/utils/transform-sourcemap.ts
943
- function isEmptySourcemapFiled(array) {
944
- if (!array) return true;
945
- if (array.length === 0 || !array[0]) return true;
946
- return false;
947
- }
948
- function normalizeTransformHookSourcemap(id, originalCode, rawMap) {
949
- if (!rawMap) return;
950
- let map = typeof rawMap === "object" ? rawMap : JSON.parse(rawMap);
951
- if (isEmptySourcemapFiled(map.sourcesContent)) map.sourcesContent = [originalCode];
952
- if (isEmptySourcemapFiled(map.sources) || map.sources && map.sources.length === 1 && map.sources[0] !== id) map.sources = [id];
953
- return map;
954
- }
955
-
956
- //#endregion
957
- //#region src/plugin/bindingify-hook-filter.ts
958
- function bindingifyStringFilter(matcher) {
959
- if (typeof matcher === "string" || matcher instanceof RegExp) return { include: [matcher] };
960
- if (Array.isArray(matcher)) return { include: matcher };
961
- return {
962
- include: matcher.include ? arraify(matcher.include) : void 0,
963
- exclude: matcher.exclude ? arraify(matcher.exclude) : void 0
964
- };
965
- }
966
- function bindingifyResolveIdFilter(filterOption) {
967
- return filterOption?.id ? bindingifyStringFilter(filterOption.id) : void 0;
968
- }
969
- function bindingifyLoadFilter(filterOption) {
970
- return filterOption?.id ? bindingifyStringFilter(filterOption.id) : void 0;
971
- }
972
- function bindingifyTransformFilter(filterOption) {
973
- if (!filterOption) return void 0;
974
- const { id, code, moduleType } = filterOption;
975
- let moduleTypeRet;
976
- if (moduleType) if (Array.isArray(moduleType)) moduleTypeRet = moduleType;
977
- else moduleTypeRet = moduleType.include;
978
- return {
979
- id: id ? bindingifyStringFilter(id) : void 0,
980
- code: code ? bindingifyStringFilter(code) : void 0,
981
- moduleType: moduleTypeRet
982
- };
983
- }
984
-
985
- //#endregion
986
- //#region src/plugin/bindingify-plugin-hook-meta.ts
987
- function bindingifyPluginHookMeta(options) {
988
- return { order: bindingPluginOrder(options.order) };
989
- }
990
- function bindingPluginOrder(order) {
991
- switch (order) {
992
- case "post": return import_binding.BindingPluginOrder.Post;
993
- case "pre": return import_binding.BindingPluginOrder.Pre;
994
- case null:
995
- case void 0: return void 0;
996
- default: throw new Error(`Unknown plugin order: ${order}`);
997
- }
998
- }
999
-
1000
- //#endregion
1001
- //#region src/utils/asset-source.ts
1002
- function transformAssetSource(bindingAssetSource$1) {
1003
- return bindingAssetSource$1.inner;
1004
- }
1005
- function bindingAssetSource(source) {
1006
- return { inner: source };
1007
- }
1008
-
1009
- //#endregion
1010
- //#region src/plugin/plugin-context.ts
1011
- var PluginContextImpl = class extends MinimalPluginContextImpl {
1012
- getModuleInfo;
1013
- constructor(outputOptions, context, plugin, data, onLog, logLevel, watchMode, currentLoadingModule) {
1014
- super(onLog, logLevel, plugin.name, watchMode);
1015
- this.outputOptions = outputOptions;
1016
- this.context = context;
1017
- this.data = data;
1018
- this.onLog = onLog;
1019
- this.currentLoadingModule = currentLoadingModule;
1020
- this.getModuleInfo = (id) => this.data.getModuleInfo(id, context);
1021
- }
1022
- async load(options) {
1023
- const id = options.id;
1024
- if (id === this.currentLoadingModule) this.onLog(LOG_LEVEL_WARN, logCycleLoading(this.pluginName, this.currentLoadingModule));
1025
- const moduleInfo = this.data.getModuleInfo(id, this.context);
1026
- if (moduleInfo && moduleInfo.code !== null) return moduleInfo;
1027
- const rawOptions = {
1028
- meta: options.meta || {},
1029
- moduleSideEffects: options.moduleSideEffects || null,
1030
- invalidate: false
1031
- };
1032
- this.data.updateModuleOption(id, rawOptions);
1033
- async function createLoadModulePromise(context, data) {
1034
- const loadPromise = data.loadModulePromiseMap.get(id);
1035
- if (loadPromise) return loadPromise;
1036
- let resolveFn;
1037
- const promise = new Promise((resolve, _) => {
1038
- resolveFn = resolve;
1039
- });
1040
- data.loadModulePromiseMap.set(id, promise);
1041
- try {
1042
- await context.load(id, bindingifySideEffects(options.moduleSideEffects), resolveFn);
1043
- } finally {
1044
- data.loadModulePromiseMap.delete(id);
1045
- }
1046
- return promise;
1047
- }
1048
- await createLoadModulePromise(this.context, this.data);
1049
- return this.data.getModuleInfo(id, this.context);
1050
- }
1051
- async resolve(source, importer, options) {
1052
- let receipt = void 0;
1053
- if (options != null) receipt = this.data.saveResolveOptions(options);
1054
- const res = await this.context.resolve(source, importer, {
1055
- custom: receipt,
1056
- skipSelf: options?.skipSelf
1057
- });
1058
- if (receipt != null) this.data.removeSavedResolveOptions(receipt);
1059
- if (res == null) return null;
1060
- const info = this.data.getModuleOption(res.id) || {};
1061
- return {
1062
- ...res,
1063
- external: transformResolvedExternal(res.external),
1064
- ...info
1065
- };
1066
- }
1067
- emitFile = (file) => {
1068
- if (file.type === "prebuilt-chunk") return unimplemented("PluginContext.emitFile with type prebuilt-chunk");
1069
- if (file.type === "chunk") return this.context.emitChunk(file);
1070
- const fnSanitizedFileName = file.fileName || typeof this.outputOptions.sanitizeFileName !== "function" ? void 0 : this.outputOptions.sanitizeFileName(file.name || "asset");
1071
- const filename = file.fileName ? void 0 : this.getAssetFileNames(file);
1072
- return this.context.emitFile({
1073
- ...file,
1074
- originalFileName: file.originalFileName || void 0,
1075
- source: bindingAssetSource(file.source)
1076
- }, filename, fnSanitizedFileName);
1077
- };
1078
- getAssetFileNames(file) {
1079
- if (typeof this.outputOptions.assetFileNames === "function") return this.outputOptions.assetFileNames({
1080
- names: file.name ? [file.name] : [],
1081
- originalFileNames: file.originalFileName ? [file.originalFileName] : [],
1082
- source: file.source,
1083
- type: "asset"
1084
- });
1085
- }
1086
- getFileName(referenceId) {
1087
- return this.context.getFileName(referenceId);
1088
- }
1089
- getModuleIds() {
1090
- return this.data.getModuleIds(this.context);
1091
- }
1092
- addWatchFile(id) {
1093
- this.context.addWatchFile(id);
1094
- }
1095
- parse(input, options) {
1096
- return parseAst(input, options);
1097
- }
1098
- };
1099
-
1100
- //#endregion
1101
- //#region src/plugin/transform-plugin-context.ts
1102
- var TransformPluginContextImpl = class extends PluginContextImpl {
1103
- constructor(outputOptions, context, plugin, data, inner, moduleId, moduleSource, onLog, LogLevelOption, watchMode) {
1104
- super(outputOptions, context, plugin, data, onLog, LogLevelOption, watchMode, moduleId);
1105
- this.inner = inner;
1106
- this.moduleId = moduleId;
1107
- this.moduleSource = moduleSource;
1108
- const getLogHandler$1 = (handler) => (log, pos) => {
1109
- log = normalizeLog(log);
1110
- if (pos) augmentCodeLocation(log, pos, moduleSource, moduleId);
1111
- log.id = moduleId;
1112
- log.hook = "transform";
1113
- handler(log);
1114
- };
1115
- this.debug = getLogHandler$1(this.debug);
1116
- this.warn = getLogHandler$1(this.warn);
1117
- this.info = getLogHandler$1(this.info);
1118
- }
1119
- error(e, pos) {
1120
- if (typeof e === "string") e = { message: e };
1121
- if (pos) augmentCodeLocation(e, pos, this.moduleSource, this.moduleId);
1122
- e.id = this.moduleId;
1123
- e.hook = "transform";
1124
- return error(logPluginError(normalizeLog(e), this.pluginName));
1125
- }
1126
- getCombinedSourcemap() {
1127
- return JSON.parse(this.inner.getCombinedSourcemap());
1128
- }
1129
- };
1130
-
1131
- //#endregion
1132
- //#region src/plugin/bindingify-build-hooks.ts
1133
- function bindingifyBuildStart(args) {
1134
- const hook = args.plugin.buildStart;
1135
- if (!hook) return {};
1136
- const { handler, meta } = normalizeHook(hook);
1137
- return {
1138
- plugin: async (ctx, opts) => {
1139
- await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode), new NormalizedInputOptionsImpl(opts, args.onLog));
1140
- },
1141
- meta: bindingifyPluginHookMeta(meta)
1142
- };
1143
- }
1144
- function bindingifyBuildEnd(args) {
1145
- const hook = args.plugin.buildEnd;
1146
- if (!hook) return {};
1147
- const { handler, meta } = normalizeHook(hook);
1148
- return {
1149
- plugin: async (ctx, err) => {
1150
- await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode), err ? normalizeErrors(err) : void 0);
1151
- },
1152
- meta: bindingifyPluginHookMeta(meta)
1153
- };
1154
- }
1155
- function bindingifyResolveId(args) {
1156
- const hook = args.plugin.resolveId;
1157
- if (!hook) return {};
1158
- const { handler, meta, options } = normalizeHook(hook);
1159
- return {
1160
- plugin: async (ctx, specifier, importer, extraOptions) => {
1161
- const contextResolveOptions = extraOptions.custom != null ? args.pluginContextData.getSavedResolveOptions(extraOptions.custom) : void 0;
1162
- const newExtraOptions = {
1163
- ...extraOptions,
1164
- custom: contextResolveOptions?.custom,
1165
- [SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF]: contextResolveOptions?.[SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF]
1166
- };
1167
- const ret = await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode), specifier, importer ?? void 0, newExtraOptions);
1168
- if (ret == null) return;
1169
- if (ret === false) return {
1170
- id: specifier,
1171
- external: bindingResolvedExternal(true),
1172
- normalizeExternalId: true
1173
- };
1174
- if (typeof ret === "string") return {
1175
- id: ret,
1176
- normalizeExternalId: true
1177
- };
1178
- let exist = args.pluginContextData.updateModuleOption(ret.id, {
1179
- meta: ret.meta || {},
1180
- moduleSideEffects: ret.moduleSideEffects ?? null,
1181
- invalidate: false
1182
- });
1183
- return {
1184
- id: ret.id,
1185
- external: bindingResolvedExternal(ret.external),
1186
- normalizeExternalId: false,
1187
- sideEffects: bindingifySideEffects(exist.moduleSideEffects)
1188
- };
1189
- },
1190
- meta: bindingifyPluginHookMeta(meta),
1191
- filter: bindingifyResolveIdFilter(options.filter)
1192
- };
1193
- }
1194
- function bindingifyResolveDynamicImport(args) {
1195
- const hook = args.plugin.resolveDynamicImport;
1196
- if (!hook) return {};
1197
- const { handler, meta } = normalizeHook(hook);
1198
- return {
1199
- plugin: async (ctx, specifier, importer) => {
1200
- const ret = await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode), specifier, importer ?? void 0);
1201
- if (ret == null) return;
1202
- if (ret === false) return {
1203
- id: specifier,
1204
- external: bindingResolvedExternal(true)
1205
- };
1206
- if (typeof ret === "string") return { id: ret };
1207
- const result = {
1208
- id: ret.id,
1209
- external: bindingResolvedExternal(ret.external)
1210
- };
1211
- if (ret.moduleSideEffects !== null) result.sideEffects = bindingifySideEffects(ret.moduleSideEffects);
1212
- args.pluginContextData.updateModuleOption(ret.id, {
1213
- meta: ret.meta || {},
1214
- moduleSideEffects: ret.moduleSideEffects || null,
1215
- invalidate: false
1216
- });
1217
- return result;
1218
- },
1219
- meta: bindingifyPluginHookMeta(meta)
1220
- };
1221
- }
1222
- function bindingifyTransform(args) {
1223
- const hook = args.plugin.transform;
1224
- if (!hook) return {};
1225
- const { handler, meta, options } = normalizeHook(hook);
1226
- return {
1227
- plugin: async (ctx, code, id, meta$1) => {
1228
- const ret = await handler.call(new TransformPluginContextImpl(args.outputOptions, ctx.inner(), args.plugin, args.pluginContextData, ctx, id, code, args.onLog, args.logLevel, args.watchMode), code, id, meta$1);
1229
- if (ret == null) return void 0;
1230
- if (typeof ret === "string") return { code: ret };
1231
- let moduleOption = args.pluginContextData.updateModuleOption(id, {
1232
- meta: ret.meta ?? {},
1233
- moduleSideEffects: ret.moduleSideEffects ?? null,
1234
- invalidate: false
1235
- });
1236
- return {
1237
- code: ret.code,
1238
- map: bindingifySourcemap$1(normalizeTransformHookSourcemap(id, code, ret.map)),
1239
- sideEffects: bindingifySideEffects(moduleOption.moduleSideEffects),
1240
- moduleType: ret.moduleType
1241
- };
1242
- },
1243
- meta: bindingifyPluginHookMeta(meta),
1244
- filter: bindingifyTransformFilter(options.filter)
1245
- };
1246
- }
1247
- function bindingifyLoad(args) {
1248
- const hook = args.plugin.load;
1249
- if (!hook) return {};
1250
- const { handler, meta, options } = normalizeHook(hook);
1251
- return {
1252
- plugin: async (ctx, id) => {
1253
- const ret = await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode, id), id);
1254
- if (ret == null) return;
1255
- if (typeof ret === "string") return { code: ret };
1256
- let moduleOption = args.pluginContextData.updateModuleOption(id, {
1257
- meta: ret.meta || {},
1258
- moduleSideEffects: ret.moduleSideEffects ?? null,
1259
- invalidate: false
1260
- });
1261
- let map = preProcessSourceMap(ret, id);
1262
- return {
1263
- code: ret.code,
1264
- map: bindingifySourcemap$1(map),
1265
- moduleType: ret.moduleType,
1266
- sideEffects: bindingifySideEffects(moduleOption.moduleSideEffects)
1267
- };
1268
- },
1269
- meta: bindingifyPluginHookMeta(meta),
1270
- filter: bindingifyLoadFilter(options.filter)
1271
- };
1272
- }
1273
- function preProcessSourceMap(ret, id) {
1274
- if (!ret.map) return;
1275
- let map = typeof ret.map === "object" ? ret.map : JSON.parse(ret.map);
1276
- if (!isEmptySourcemapFiled(map.sources)) {
1277
- const directory = path.dirname(id) || ".";
1278
- const sourceRoot = map.sourceRoot || ".";
1279
- map.sources = map.sources.map((source) => path.resolve(directory, sourceRoot, source));
1280
- }
1281
- return map;
1282
- }
1283
- function bindingifyModuleParsed(args) {
1284
- const hook = args.plugin.moduleParsed;
1285
- if (!hook) return {};
1286
- const { handler, meta } = normalizeHook(hook);
1287
- return {
1288
- plugin: async (ctx, moduleInfo) => {
1289
- await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode), transformModuleInfo(moduleInfo, args.pluginContextData.getModuleOption(moduleInfo.id)));
1290
- },
1291
- meta: bindingifyPluginHookMeta(meta)
1292
- };
1293
- }
1294
-
1295
- //#endregion
1296
- //#region src/utils/transform-rendered-module.ts
1297
- function transformToRenderedModule(bindingRenderedModule) {
1298
- return {
1299
- get code() {
1300
- return bindingRenderedModule.code;
1301
- },
1302
- get renderedLength() {
1303
- return bindingRenderedModule.code?.length || 0;
1304
- },
1305
- get renderedExports() {
1306
- return bindingRenderedModule.renderedExports;
1307
- }
1308
- };
1309
- }
1310
-
1311
- //#endregion
1312
- //#region src/utils/transform-rendered-chunk.ts
1313
- function transformRenderedChunk(chunk) {
1314
- let modules = null;
1315
- return {
1316
- get name() {
1317
- return chunk.name;
1318
- },
1319
- get isEntry() {
1320
- return chunk.isEntry;
1321
- },
1322
- get isDynamicEntry() {
1323
- return chunk.isDynamicEntry;
1324
- },
1325
- get facadeModuleId() {
1326
- return chunk.facadeModuleId;
1327
- },
1328
- get moduleIds() {
1329
- return chunk.moduleIds;
1330
- },
1331
- get exports() {
1332
- return chunk.exports;
1333
- },
1334
- get fileName() {
1335
- return chunk.fileName;
1336
- },
1337
- get imports() {
1338
- return chunk.imports;
1339
- },
1340
- get dynamicImports() {
1341
- return chunk.dynamicImports;
1342
- },
1343
- get modules() {
1344
- if (!modules) modules = transformChunkModules(chunk.modules);
1345
- return modules;
1346
- }
1347
- };
1348
- }
1349
- function transformChunkModules(modules) {
1350
- const result = {};
1351
- for (let i = 0; i < modules.values.length; i++) {
1352
- let key = modules.keys[i];
1353
- const mod = modules.values[i];
1354
- result[key] = transformToRenderedModule(mod);
1355
- }
1356
- return result;
1357
- }
1358
-
1359
- //#endregion
1360
- //#region src/utils/bindingify-output-options.ts
1361
- function bindingifyOutputOptions(outputOptions) {
1362
- const { dir, format, exports, hashCharacters, sourcemap, sourcemapDebugIds, sourcemapIgnoreList, sourcemapPathTransform, name, assetFileNames, entryFileNames, chunkFileNames, cssEntryFileNames, cssChunkFileNames, banner, footer, intro, outro, esModule, globals, file, sanitizeFileName } = outputOptions;
1363
- return {
1364
- dir,
1365
- file: file == null ? void 0 : file,
1366
- format: bindingifyFormat(format),
1367
- exports,
1368
- hashCharacters,
1369
- sourcemap: bindingifySourcemap(sourcemap),
1370
- sourcemapDebugIds,
1371
- sourcemapIgnoreList: bindingifySourcemapIgnoreList(sourcemapIgnoreList),
1372
- sourcemapPathTransform,
1373
- banner: bindingifyAddon(banner),
1374
- footer: bindingifyAddon(footer),
1375
- intro: bindingifyAddon(intro),
1376
- outro: bindingifyAddon(outro),
1377
- extend: outputOptions.extend,
1378
- globals,
1379
- esModule,
1380
- name,
1381
- assetFileNames: bindingifyAssetFilenames(assetFileNames),
1382
- entryFileNames,
1383
- chunkFileNames,
1384
- cssEntryFileNames,
1385
- cssChunkFileNames,
1386
- plugins: [],
1387
- minify: outputOptions.minify,
1388
- externalLiveBindings: outputOptions.externalLiveBindings,
1389
- inlineDynamicImports: outputOptions.inlineDynamicImports,
1390
- advancedChunks: outputOptions.advancedChunks,
1391
- polyfillRequire: outputOptions.polyfillRequire,
1392
- target: outputOptions.target,
1393
- sanitizeFileName
1394
- };
1395
- }
1396
- function bindingifyAddon(configAddon) {
1397
- return async (chunk) => {
1398
- if (typeof configAddon === "function") return configAddon(transformRenderedChunk(chunk));
1399
- return configAddon || "";
1400
- };
1401
- }
1402
- function bindingifyFormat(format) {
1403
- switch (format) {
1404
- case void 0:
1405
- case "es":
1406
- case "esm":
1407
- case "module": return "es";
1408
- case "cjs":
1409
- case "commonjs": return "cjs";
1410
- case "iife": return "iife";
1411
- case "umd": return "umd";
1412
- case "experimental-app": return "app";
1413
- default: unimplemented(`output.format: ${format}`);
1414
- }
1415
- }
1416
- function bindingifySourcemap(sourcemap) {
1417
- switch (sourcemap) {
1418
- case true: return "file";
1419
- case "inline": return "inline";
1420
- case false:
1421
- case void 0: return void 0;
1422
- case "hidden": return "hidden";
1423
- default: throw new Error(`unknown sourcemap: ${sourcemap}`);
1424
- }
1425
- }
1426
- function bindingifySourcemapIgnoreList(sourcemapIgnoreList) {
1427
- return typeof sourcemapIgnoreList === "function" ? sourcemapIgnoreList : sourcemapIgnoreList === false ? () => false : (relativeSourcePath, _sourcemapPath) => relativeSourcePath.includes("node_modules");
1428
- }
1429
- function bindingifyAssetFilenames(assetFileNames) {
1430
- if (typeof assetFileNames === "function") return (asset) => {
1431
- return assetFileNames({
1432
- names: asset.names,
1433
- originalFileNames: asset.originalFileNames,
1434
- source: transformAssetSource(asset.source),
1435
- type: "asset"
1436
- });
1437
- };
1438
- return assetFileNames;
1439
- }
1440
-
1441
- //#endregion
1442
- //#region src/options/normalized-output-options.ts
1443
- var NormalizedOutputOptionsImpl = class {
1444
- constructor(inner, outputOptions, normalizedOutputPlugins) {
1445
- this.inner = inner;
1446
- this.outputOptions = outputOptions;
1447
- this.normalizedOutputPlugins = normalizedOutputPlugins;
1448
- }
1449
- get dir() {
1450
- return this.inner.dir ?? void 0;
1451
- }
1452
- get entryFileNames() {
1453
- return this.inner.entryFilenames || this.outputOptions.entryFileNames;
1454
- }
1455
- get chunkFileNames() {
1456
- return this.inner.chunkFilenames || this.outputOptions.chunkFileNames;
1457
- }
1458
- get assetFileNames() {
1459
- return this.inner.assetFilenames || this.outputOptions.assetFileNames;
1460
- }
1461
- get format() {
1462
- return this.inner.format;
1463
- }
1464
- get exports() {
1465
- return this.inner.exports;
1466
- }
1467
- get sourcemap() {
1468
- return this.inner.sourcemap;
1469
- }
1470
- get cssEntryFileNames() {
1471
- return this.inner.cssEntryFilenames || this.outputOptions.cssEntryFileNames;
1472
- }
1473
- get cssChunkFileNames() {
1474
- return this.inner.cssChunkFilenames || this.outputOptions.cssChunkFileNames;
1475
- }
1476
- get shimMissingExports() {
1477
- return this.inner.shimMissingExports;
1478
- }
1479
- get name() {
1480
- return this.inner.name ?? void 0;
1481
- }
1482
- get file() {
1483
- return this.inner.file ?? void 0;
1484
- }
1485
- get inlineDynamicImports() {
1486
- return this.inner.inlineDynamicImports;
1487
- }
1488
- get externalLiveBindings() {
1489
- return this.inner.externalLiveBindings;
1490
- }
1491
- get banner() {
1492
- return normalizeAddon(this.outputOptions.banner);
1493
- }
1494
- get footer() {
1495
- return normalizeAddon(this.outputOptions.footer);
1496
- }
1497
- get intro() {
1498
- return normalizeAddon(this.outputOptions.intro);
1499
- }
1500
- get outro() {
1501
- return normalizeAddon(this.outputOptions.outro);
1502
- }
1503
- get esModule() {
1504
- return this.inner.esModule;
1505
- }
1506
- get extend() {
1507
- return this.inner.extend;
1508
- }
1509
- get globals() {
1510
- return this.inner.globals || this.outputOptions.globals;
1511
- }
1512
- get hashCharacters() {
1513
- return this.inner.hashCharacters;
1514
- }
1515
- get sourcemapDebugIds() {
1516
- return this.inner.sourcemapDebugIds;
1517
- }
1518
- get sourcemapIgnoreList() {
1519
- return bindingifySourcemapIgnoreList(this.outputOptions.sourcemapIgnoreList);
1520
- }
1521
- get sourcemapPathTransform() {
1522
- return this.outputOptions.sourcemapPathTransform;
1523
- }
1524
- get minify() {
1525
- return this.inner.minify;
1526
- }
1527
- get comments() {
1528
- return this.inner.comments;
1529
- }
1530
- get polyfillRequire() {
1531
- return this.inner.polyfillRequire;
1532
- }
1533
- get plugins() {
1534
- return this.normalizedOutputPlugins;
1535
- }
1536
- };
1537
- function normalizeAddon(value) {
1538
- if (typeof value === "function") return value;
1539
- return () => value || "";
1540
- }
1541
-
1542
- //#endregion
1543
- //#region src/utils/transform-to-rollup-output.ts
1544
- function transformToRollupSourceMap(map) {
1545
- const parsed = JSON.parse(map);
1546
- const obj = {
1547
- ...parsed,
1548
- toString() {
1549
- return JSON.stringify(obj);
1550
- },
1551
- toUrl() {
1552
- return `data:application/json;charset=utf-8;base64,${Buffer.from(obj.toString(), "utf-8").toString("base64")}`;
1553
- }
1554
- };
1555
- return obj;
1556
- }
1557
- function transformToRollupOutputChunk(bindingChunk, changed) {
1558
- const chunk = {
1559
- type: "chunk",
1560
- get code() {
1561
- return bindingChunk.code;
1562
- },
1563
- fileName: bindingChunk.fileName,
1564
- name: bindingChunk.name,
1565
- get modules() {
1566
- return transformChunkModules(bindingChunk.modules);
1567
- },
1568
- get imports() {
1569
- return bindingChunk.imports;
1570
- },
1571
- get dynamicImports() {
1572
- return bindingChunk.dynamicImports;
1573
- },
1574
- exports: bindingChunk.exports,
1575
- isEntry: bindingChunk.isEntry,
1576
- facadeModuleId: bindingChunk.facadeModuleId || null,
1577
- isDynamicEntry: bindingChunk.isDynamicEntry,
1578
- get moduleIds() {
1579
- return bindingChunk.moduleIds;
1580
- },
1581
- get map() {
1582
- return bindingChunk.map ? transformToRollupSourceMap(bindingChunk.map) : null;
1583
- },
1584
- sourcemapFileName: bindingChunk.sourcemapFileName || null,
1585
- preliminaryFileName: bindingChunk.preliminaryFileName
1586
- };
1587
- const cache = {};
1588
- return new Proxy(chunk, {
1589
- get(target, p) {
1590
- if (p in cache) return cache[p];
1591
- return target[p];
1592
- },
1593
- set(target, p, newValue) {
1594
- cache[p] = newValue;
1595
- changed?.updated.add(bindingChunk.fileName);
1596
- return true;
1597
- },
1598
- has(target, p) {
1599
- if (p in cache) return true;
1600
- return p in target;
1601
- }
1602
- });
1603
- }
1604
- function transformToRollupOutputAsset(bindingAsset, changed) {
1605
- const asset = {
1606
- type: "asset",
1607
- fileName: bindingAsset.fileName,
1608
- originalFileName: bindingAsset.originalFileName || null,
1609
- originalFileNames: bindingAsset.originalFileNames,
1610
- get source() {
1611
- return transformAssetSource(bindingAsset.source);
1612
- },
1613
- name: bindingAsset.name ?? void 0,
1614
- names: bindingAsset.names
1615
- };
1616
- const cache = {};
1617
- return new Proxy(asset, {
1618
- get(target, p) {
1619
- if (p in cache) return cache[p];
1620
- return target[p];
1621
- },
1622
- set(target, p, newValue) {
1623
- cache[p] = newValue;
1624
- changed?.updated.add(bindingAsset.fileName);
1625
- return true;
1626
- }
1627
- });
1628
- }
1629
- function transformToRollupOutput(output, changed) {
1630
- handleOutputErrors(output);
1631
- const { chunks, assets } = output;
1632
- return { output: [...chunks.map((chunk) => transformToRollupOutputChunk(chunk, changed)), ...assets.map((asset) => transformToRollupOutputAsset(asset, changed))] };
1633
- }
1634
- function handleOutputErrors(output) {
1635
- const rawErrors = output.errors;
1636
- if (rawErrors.length > 0) throw normalizeErrors(rawErrors);
1637
- }
1638
- function transformToOutputBundle(output, changed) {
1639
- const bundle = Object.fromEntries(transformToRollupOutput(output, changed).output.map((item) => [item.fileName, item]));
1640
- return new Proxy(bundle, { deleteProperty(target, property) {
1641
- if (typeof property === "string") changed.deleted.add(property);
1642
- return true;
1643
- } });
1644
- }
1645
- function collectChangedBundle(changed, bundle) {
1646
- const assets = [];
1647
- const chunks = [];
1648
- for (const key in bundle) {
1649
- if (changed.deleted.has(key) || !changed.updated.has(key)) continue;
1650
- const item = bundle[key];
1651
- if (item.type === "asset") assets.push({
1652
- filename: item.fileName,
1653
- originalFileNames: item.originalFileNames,
1654
- source: bindingAssetSource(item.source),
1655
- names: item.names
1656
- });
1657
- else chunks.push({
1658
- code: item.code,
1659
- filename: item.fileName,
1660
- name: item.name,
1661
- isEntry: item.isEntry,
1662
- exports: item.exports,
1663
- modules: {},
1664
- imports: item.imports,
1665
- dynamicImports: item.dynamicImports,
1666
- facadeModuleId: item.facadeModuleId || void 0,
1667
- isDynamicEntry: item.isDynamicEntry,
1668
- moduleIds: item.moduleIds,
1669
- map: bindingifySourcemap$1(item.map),
1670
- sourcemapFilename: item.sourcemapFileName || void 0,
1671
- preliminaryFilename: item.preliminaryFileName
1672
- });
1673
- }
1674
- return {
1675
- assets,
1676
- chunks,
1677
- deleted: Array.from(changed.deleted)
1678
- };
1679
- }
1680
-
1681
- //#endregion
1682
- //#region src/plugin/bindingify-output-hooks.ts
1683
- function bindingifyRenderStart(args) {
1684
- const hook = args.plugin.renderStart;
1685
- if (!hook) return {};
1686
- const { handler, meta } = normalizeHook(hook);
1687
- return {
1688
- plugin: async (ctx, opts) => {
1689
- handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode), new NormalizedOutputOptionsImpl(opts, args.outputOptions, args.normalizedOutputPlugins), new NormalizedInputOptionsImpl(opts, args.onLog));
1690
- },
1691
- meta: bindingifyPluginHookMeta(meta)
1692
- };
1693
- }
1694
- function bindingifyRenderChunk(args) {
1695
- const hook = args.plugin.renderChunk;
1696
- if (!hook) return {};
1697
- const { handler, meta } = normalizeHook(hook);
1698
- return {
1699
- plugin: async (ctx, code, chunk, opts, meta$1) => {
1700
- if (args.pluginContextData.getRenderChunkMeta() == null) args.pluginContextData.setRenderChunkMeta({ chunks: Object.fromEntries(Object.entries(meta$1.chunks).map(([key, value]) => [key, transformRenderedChunk(value)])) });
1701
- const ret = await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode), code, transformRenderedChunk(chunk), new NormalizedOutputOptionsImpl(opts, args.outputOptions, args.normalizedOutputPlugins), args.pluginContextData.getRenderChunkMeta());
1702
- if (ret == null) return;
1703
- if (typeof ret === "string") return { code: ret };
1704
- if (!ret.map) return { code: ret.code };
1705
- return {
1706
- code: ret.code,
1707
- map: bindingifySourcemap$1(ret.map)
1708
- };
1709
- },
1710
- meta: bindingifyPluginHookMeta(meta)
1711
- };
1712
- }
1713
- function bindingifyAugmentChunkHash(args) {
1714
- const hook = args.plugin.augmentChunkHash;
1715
- if (!hook) return {};
1716
- const { handler, meta } = normalizeHook(hook);
1717
- return {
1718
- plugin: async (ctx, chunk) => {
1719
- return await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode), transformRenderedChunk(chunk));
1720
- },
1721
- meta: bindingifyPluginHookMeta(meta)
1722
- };
1723
- }
1724
- function bindingifyRenderError(args) {
1725
- const hook = args.plugin.renderError;
1726
- if (!hook) return {};
1727
- const { handler, meta } = normalizeHook(hook);
1728
- return {
1729
- plugin: async (ctx, err) => {
1730
- handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode), normalizeErrors(err));
1731
- },
1732
- meta: bindingifyPluginHookMeta(meta)
1733
- };
1734
- }
1735
- function bindingifyGenerateBundle(args) {
1736
- const hook = args.plugin.generateBundle;
1737
- if (!hook) return {};
1738
- const { handler, meta } = normalizeHook(hook);
1739
- return {
1740
- plugin: async (ctx, bundle, isWrite, opts) => {
1741
- const changed = {
1742
- updated: new Set(),
1743
- deleted: new Set()
1744
- };
1745
- const output = transformToOutputBundle(bundle, changed);
1746
- await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode), new NormalizedOutputOptionsImpl(opts, args.outputOptions, args.normalizedOutputPlugins), output, isWrite);
1747
- return collectChangedBundle(changed, output);
1748
- },
1749
- meta: bindingifyPluginHookMeta(meta)
1750
- };
1751
- }
1752
- function bindingifyWriteBundle(args) {
1753
- const hook = args.plugin.writeBundle;
1754
- if (!hook) return {};
1755
- const { handler, meta } = normalizeHook(hook);
1756
- return {
1757
- plugin: async (ctx, bundle, opts) => {
1758
- const changed = {
1759
- updated: new Set(),
1760
- deleted: new Set()
1761
- };
1762
- const output = transformToOutputBundle(bundle, changed);
1763
- await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode), new NormalizedOutputOptionsImpl(opts, args.outputOptions, args.normalizedOutputPlugins), output);
1764
- return collectChangedBundle(changed, output);
1765
- },
1766
- meta: bindingifyPluginHookMeta(meta)
1767
- };
1768
- }
1769
- function bindingifyCloseBundle(args) {
1770
- const hook = args.plugin.closeBundle;
1771
- if (!hook) return {};
1772
- const { handler, meta } = normalizeHook(hook);
1773
- return {
1774
- plugin: async (ctx) => {
1775
- await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode));
1776
- },
1777
- meta: bindingifyPluginHookMeta(meta)
1778
- };
1779
- }
1780
- function bindingifyBanner(args) {
1781
- const hook = args.plugin.banner;
1782
- if (!hook) return {};
1783
- const { handler, meta } = normalizeHook(hook);
1784
- return {
1785
- plugin: async (ctx, chunk) => {
1786
- if (typeof handler === "string") return handler;
1787
- return handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode), transformRenderedChunk(chunk));
1788
- },
1789
- meta: bindingifyPluginHookMeta(meta)
1790
- };
1791
- }
1792
- function bindingifyFooter(args) {
1793
- const hook = args.plugin.footer;
1794
- if (!hook) return {};
1795
- const { handler, meta } = normalizeHook(hook);
1796
- return {
1797
- plugin: async (ctx, chunk) => {
1798
- if (typeof handler === "string") return handler;
1799
- return handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode), transformRenderedChunk(chunk));
1800
- },
1801
- meta: bindingifyPluginHookMeta(meta)
1802
- };
1803
- }
1804
- function bindingifyIntro(args) {
1805
- const hook = args.plugin.intro;
1806
- if (!hook) return {};
1807
- const { handler, meta } = normalizeHook(hook);
1808
- return {
1809
- plugin: async (ctx, chunk) => {
1810
- if (typeof handler === "string") return handler;
1811
- return handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode), transformRenderedChunk(chunk));
1812
- },
1813
- meta: bindingifyPluginHookMeta(meta)
1814
- };
1815
- }
1816
- function bindingifyOutro(args) {
1817
- const hook = args.plugin.outro;
1818
- if (!hook) return {};
1819
- const { handler, meta } = normalizeHook(hook);
1820
- return {
1821
- plugin: async (ctx, chunk) => {
1822
- if (typeof handler === "string") return handler;
1823
- return handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode), transformRenderedChunk(chunk));
1824
- },
1825
- meta: bindingifyPluginHookMeta(meta)
1826
- };
1827
- }
1828
-
1829
- //#endregion
1830
- //#region src/plugin/bindingify-watch-hooks.ts
1831
- function bindingifyWatchChange(args) {
1832
- const hook = args.plugin.watchChange;
1833
- if (!hook) return {};
1834
- const { handler, meta } = normalizeHook(hook);
1835
- return {
1836
- plugin: async (ctx, id, event) => {
1837
- await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode), id, { event });
1838
- },
1839
- meta: bindingifyPluginHookMeta(meta)
1840
- };
1841
- }
1842
- function bindingifyCloseWatcher(args) {
1843
- const hook = args.plugin.closeWatcher;
1844
- if (!hook) return {};
1845
- const { handler, meta } = normalizeHook(hook);
1846
- return {
1847
- plugin: async (ctx) => {
1848
- await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode));
1849
- },
1850
- meta: bindingifyPluginHookMeta(meta)
1851
- };
1852
- }
1853
-
1854
- //#endregion
1855
- //#region src/plugin/bindingify-plugin.ts
1856
- function bindingifyPlugin(plugin, options, outputOptions, pluginContextData, normalizedOutputPlugins, onLog, logLevel, watchMode) {
1857
- const args = {
1858
- plugin,
1859
- options,
1860
- outputOptions,
1861
- pluginContextData,
1862
- onLog,
1863
- logLevel,
1864
- watchMode,
1865
- normalizedOutputPlugins
1866
- };
1867
- const { plugin: buildStart, meta: buildStartMeta } = bindingifyBuildStart(args);
1868
- const { plugin: resolveId, meta: resolveIdMeta, filter: resolveIdFilter } = bindingifyResolveId(args);
1869
- const { plugin: resolveDynamicImport, meta: resolveDynamicImportMeta } = bindingifyResolveDynamicImport(args);
1870
- const { plugin: buildEnd, meta: buildEndMeta } = bindingifyBuildEnd(args);
1871
- const { plugin: transform, meta: transformMeta, filter: transformFilter } = bindingifyTransform(args);
1872
- const { plugin: moduleParsed, meta: moduleParsedMeta } = bindingifyModuleParsed(args);
1873
- const { plugin: load, meta: loadMeta, filter: loadFilter } = bindingifyLoad(args);
1874
- const { plugin: renderChunk, meta: renderChunkMeta } = bindingifyRenderChunk(args);
1875
- const { plugin: augmentChunkHash, meta: augmentChunkHashMeta } = bindingifyAugmentChunkHash(args);
1876
- const { plugin: renderStart, meta: renderStartMeta } = bindingifyRenderStart(args);
1877
- const { plugin: renderError, meta: renderErrorMeta } = bindingifyRenderError(args);
1878
- const { plugin: generateBundle, meta: generateBundleMeta } = bindingifyGenerateBundle(args);
1879
- const { plugin: writeBundle, meta: writeBundleMeta } = bindingifyWriteBundle(args);
1880
- const { plugin: closeBundle, meta: closeBundleMeta } = bindingifyCloseBundle(args);
1881
- const { plugin: banner, meta: bannerMeta } = bindingifyBanner(args);
1882
- const { plugin: footer, meta: footerMeta } = bindingifyFooter(args);
1883
- const { plugin: intro, meta: introMeta } = bindingifyIntro(args);
1884
- const { plugin: outro, meta: outroMeta } = bindingifyOutro(args);
1885
- const { plugin: watchChange, meta: watchChangeMeta } = bindingifyWatchChange(args);
1886
- const { plugin: closeWatcher, meta: closeWatcherMeta } = bindingifyCloseWatcher(args);
1887
- const result = {
1888
- name: plugin.name,
1889
- buildStart,
1890
- buildStartMeta,
1891
- resolveId,
1892
- resolveIdMeta,
1893
- resolveIdFilter,
1894
- resolveDynamicImport,
1895
- resolveDynamicImportMeta,
1896
- buildEnd,
1897
- buildEndMeta,
1898
- transform,
1899
- transformMeta,
1900
- transformFilter,
1901
- moduleParsed,
1902
- moduleParsedMeta,
1903
- load,
1904
- loadMeta,
1905
- loadFilter,
1906
- renderChunk,
1907
- renderChunkMeta,
1908
- augmentChunkHash,
1909
- augmentChunkHashMeta,
1910
- renderStart,
1911
- renderStartMeta,
1912
- renderError,
1913
- renderErrorMeta,
1914
- generateBundle,
1915
- generateBundleMeta,
1916
- writeBundle,
1917
- writeBundleMeta,
1918
- closeBundle,
1919
- closeBundleMeta,
1920
- banner,
1921
- bannerMeta,
1922
- footer,
1923
- footerMeta,
1924
- intro,
1925
- introMeta,
1926
- outro,
1927
- outroMeta,
1928
- watchChange,
1929
- watchChangeMeta,
1930
- closeWatcher,
1931
- closeWatcherMeta
1932
- };
1933
- return wrapHandlers(result);
1934
- }
1935
- function wrapHandlers(plugin) {
1936
- for (const hookName of [
1937
- "buildStart",
1938
- "resolveId",
1939
- "resolveDynamicImport",
1940
- "buildEnd",
1941
- "transform",
1942
- "moduleParsed",
1943
- "load",
1944
- "renderChunk",
1945
- "augmentChunkHash",
1946
- "renderStart",
1947
- "renderError",
1948
- "generateBundle",
1949
- "writeBundle",
1950
- "closeBundle",
1951
- "banner",
1952
- "footer",
1953
- "intro",
1954
- "outro",
1955
- "watchChange",
1956
- "closeWatcher"
1957
- ]) {
1958
- const handler = plugin[hookName];
1959
- if (handler) plugin[hookName] = async (...args) => {
1960
- try {
1961
- return await handler(...args);
1962
- } catch (e) {
1963
- return error(logPluginError(e, plugin.name, {
1964
- hook: hookName,
1965
- id: hookName === "transform" ? args[2] : void 0
1966
- }));
1967
- }
1968
- };
1969
- }
1970
- return plugin;
1971
- }
1972
-
1973
- //#endregion
1974
- //#region src/plugin/plugin-context-data.ts
1975
- var PluginContextData = class {
1976
- moduleOptionMap = new Map();
1977
- resolveOptionsMap = new Map();
1978
- loadModulePromiseMap = new Map();
1979
- meta = null;
1980
- updateModuleOption(id, option) {
1981
- const existing = this.moduleOptionMap.get(id);
1982
- if (existing) {
1983
- if (option.moduleSideEffects != null) existing.moduleSideEffects = option.moduleSideEffects;
1984
- if (option.meta != null) Object.assign(existing.meta, option.meta);
1985
- if (option.invalidate != null) existing.invalidate = option.invalidate;
1986
- } else {
1987
- this.moduleOptionMap.set(id, option);
1988
- return option;
1989
- }
1990
- return existing;
1991
- }
1992
- getModuleOption(id) {
1993
- const option = this.moduleOptionMap.get(id);
1994
- if (!option) {
1995
- const raw = {
1996
- moduleSideEffects: null,
1997
- meta: {}
1998
- };
1999
- this.moduleOptionMap.set(id, raw);
2000
- return raw;
2001
- }
2002
- return option;
2003
- }
2004
- getModuleInfo(id, context) {
2005
- const bindingInfo = context.getModuleInfo(id);
2006
- if (bindingInfo) {
2007
- const info = transformModuleInfo(bindingInfo, this.getModuleOption(id));
2008
- return this.proxyModuleInfo(id, info);
2009
- }
2010
- return null;
2011
- }
2012
- proxyModuleInfo(id, info) {
2013
- let moduleSideEffects = info.moduleSideEffects;
2014
- Object.defineProperty(info, "moduleSideEffects", {
2015
- get() {
2016
- return moduleSideEffects;
2017
- },
2018
- set: (v$1) => {
2019
- this.updateModuleOption(id, {
2020
- moduleSideEffects: v$1,
2021
- meta: info.meta,
2022
- invalidate: true
2023
- });
2024
- moduleSideEffects = v$1;
2025
- }
2026
- });
2027
- return info;
2028
- }
2029
- getModuleIds(context) {
2030
- const moduleIds = context.getModuleIds();
2031
- return moduleIds.values();
2032
- }
2033
- saveResolveOptions(options) {
2034
- const index = this.resolveOptionsMap.size;
2035
- this.resolveOptionsMap.set(index, options);
2036
- return index;
2037
- }
2038
- getSavedResolveOptions(receipt) {
2039
- return this.resolveOptionsMap.get(receipt);
2040
- }
2041
- removeSavedResolveOptions(receipt) {
2042
- this.resolveOptionsMap.delete(receipt);
2043
- }
2044
- setRenderChunkMeta(meta) {
2045
- this.meta = meta;
2046
- }
2047
- getRenderChunkMeta() {
2048
- return this.meta;
2049
- }
2050
- };
2051
-
2052
- //#endregion
2053
- //#region src/utils/normalize-string-or-regex.ts
2054
- function normalizedStringOrRegex(pattern) {
2055
- if (!pattern) return void 0;
2056
- if (!Array.isArray(pattern)) pattern = [pattern];
2057
- return pattern;
2058
- }
2059
-
2060
- //#endregion
2061
- //#region src/utils/bindingify-input-options.ts
2062
- function bindingifyInputOptions(rawPlugins, inputOptions, outputOptions, normalizedOutputPlugins, onLog, logLevel, watchMode) {
2063
- const pluginContextData = new PluginContextData();
2064
- const plugins = rawPlugins.map((plugin) => {
2065
- if ("_parallel" in plugin) return void 0;
2066
- if (plugin instanceof BuiltinPlugin) return bindingifyBuiltInPlugin(plugin);
2067
- return bindingifyPlugin(plugin, inputOptions, outputOptions, pluginContextData, normalizedOutputPlugins, onLog, logLevel, watchMode);
2068
- });
2069
- return {
2070
- input: bindingifyInput(inputOptions.input),
2071
- plugins,
2072
- cwd: inputOptions.cwd ?? process.cwd(),
2073
- external: bindingifyExternal(inputOptions.external),
2074
- resolve: bindingifyResolve(inputOptions.resolve),
2075
- platform: inputOptions.platform,
2076
- shimMissingExports: inputOptions.shimMissingExports,
2077
- logLevel: bindingifyLogLevel(logLevel),
2078
- onLog,
2079
- treeshake: bindingifyTreeshakeOptions(inputOptions.treeshake),
2080
- moduleTypes: inputOptions.moduleTypes,
2081
- define: inputOptions.define ? Object.entries(inputOptions.define) : void 0,
2082
- inject: bindingifyInject(inputOptions.inject),
2083
- experimental: {
2084
- strictExecutionOrder: inputOptions.experimental?.strictExecutionOrder,
2085
- disableLiveBindings: inputOptions.experimental?.disableLiveBindings,
2086
- viteMode: inputOptions.experimental?.viteMode,
2087
- resolveNewUrlToAsset: inputOptions.experimental?.resolveNewUrlToAsset,
2088
- hmr: inputOptions.experimental?.hmr
2089
- },
2090
- profilerNames: inputOptions?.profilerNames,
2091
- jsx: bindingifyJsx(inputOptions.jsx),
2092
- transform: inputOptions.transform,
2093
- watch: bindingifyWatch(inputOptions.watch),
2094
- dropLabels: inputOptions.dropLabels,
2095
- keepNames: inputOptions.keepNames,
2096
- checks: inputOptions.checks,
2097
- deferSyncScanData: () => {
2098
- let ret = [];
2099
- pluginContextData.moduleOptionMap.forEach((value, key) => {
2100
- if (value.invalidate) ret.push({
2101
- id: key,
2102
- sideEffects: bindingifySideEffects(value.moduleSideEffects)
2103
- });
2104
- });
2105
- return ret;
2106
- },
2107
- makeAbsoluteExternalsRelative: bindingifyMakeAbsoluteExternalsRelative(inputOptions.makeAbsoluteExternalsRelative)
2108
- };
2109
- }
2110
- function bindingifyExternal(external) {
2111
- if (external) {
2112
- if (typeof external === "function") return (id, importer, isResolved) => {
2113
- if (id.startsWith("\0")) return false;
2114
- return external(id, importer, isResolved) ?? false;
2115
- };
2116
- const externalArr = arraify(external);
2117
- return (id, _importer, _isResolved) => {
2118
- return externalArr.some((pat) => {
2119
- if (pat instanceof RegExp) return pat.test(id);
2120
- return id === pat;
2121
- });
2122
- };
2123
- }
2124
- }
2125
- function bindingifyResolve(resolve) {
2126
- if (resolve) {
2127
- const { alias, extensionAlias,...rest } = resolve;
2128
- return {
2129
- alias: alias ? Object.entries(alias).map(([name, replacement]) => ({
2130
- find: name,
2131
- replacements: arraify(replacement)
2132
- })) : void 0,
2133
- extensionAlias: extensionAlias ? Object.entries(extensionAlias).map(([name, value]) => ({
2134
- target: name,
2135
- replacements: value
2136
- })) : void 0,
2137
- ...rest
2138
- };
2139
- }
2140
- }
2141
- function bindingifyInject(inject) {
2142
- if (inject) return Object.entries(inject).map(([alias, item]) => {
2143
- if (Array.isArray(item)) {
2144
- if (item[1] === "*") return {
2145
- tagNamespace: true,
2146
- alias,
2147
- from: item[0]
2148
- };
2149
- return {
2150
- tagNamed: true,
2151
- alias,
2152
- from: item[0],
2153
- imported: item[1]
2154
- };
2155
- } else return {
2156
- tagNamed: true,
2157
- imported: "default",
2158
- alias,
2159
- from: item
2160
- };
2161
- });
2162
- }
2163
- function bindingifyLogLevel(logLevel) {
2164
- switch (logLevel) {
2165
- case "silent": return import_binding.BindingLogLevel.Silent;
2166
- case "debug": return import_binding.BindingLogLevel.Debug;
2167
- case "warn": return import_binding.BindingLogLevel.Warn;
2168
- case "info": return import_binding.BindingLogLevel.Info;
2169
- default: throw new Error(`Unexpected log level: ${logLevel}`);
2170
- }
2171
- }
2172
- function bindingifyInput(input) {
2173
- if (input === void 0) return [];
2174
- if (typeof input === "string") return [{ import: input }];
2175
- if (Array.isArray(input)) return input.map((src) => ({ import: src }));
2176
- return Object.entries(input).map(([name, import_path]) => {
2177
- return {
2178
- name,
2179
- import: import_path
2180
- };
2181
- });
2182
- }
2183
- function bindingifyJsx(input) {
2184
- switch (input) {
2185
- case false: return { type: "Disable" };
2186
- case "react": return { type: "React" };
2187
- case "react-jsx": return { type: "ReactJsx" };
2188
- case "preserve": return { type: "Preserve" };
2189
- case void 0: return void 0;
2190
- }
2191
- if (input.mode === "preserve") return { type: "Preserve" };
2192
- const mode = input.mode ?? "automatic";
2193
- return {
2194
- type: "Enable",
2195
- field0: {
2196
- runtime: mode,
2197
- importSource: mode === "classic" ? input.importSource : mode === "automatic" ? input.jsxImportSource : void 0,
2198
- pragma: input.factory,
2199
- pragmaFrag: input.fragment,
2200
- development: input.development,
2201
- refresh: input.refresh
2202
- }
2203
- };
2204
- }
2205
- function bindingifyWatch(watch$1) {
2206
- if (watch$1) return {
2207
- buildDelay: watch$1.buildDelay,
2208
- skipWrite: watch$1.skipWrite,
2209
- include: normalizedStringOrRegex(watch$1.include),
2210
- exclude: normalizedStringOrRegex(watch$1.exclude)
2211
- };
2212
- }
2213
- function bindingifyTreeshakeOptions(config) {
2214
- if (config === false) return void 0;
2215
- if (config === true || config === void 0) return { moduleSideEffects: true };
2216
- let normalizedConfig = {
2217
- moduleSideEffects: true,
2218
- annotations: config.annotations,
2219
- manualPureFunctions: config.manualPureFunctions,
2220
- unknownGlobalSideEffects: config.unknownGlobalSideEffects
2221
- };
2222
- if (config.moduleSideEffects === void 0) normalizedConfig.moduleSideEffects = true;
2223
- else if (config.moduleSideEffects === "no-external") normalizedConfig.moduleSideEffects = [{
2224
- external: true,
2225
- sideEffects: false
2226
- }, {
2227
- external: false,
2228
- sideEffects: true
2229
- }];
2230
- else normalizedConfig.moduleSideEffects = config.moduleSideEffects;
2231
- return normalizedConfig;
2232
- }
2233
- function bindingifyMakeAbsoluteExternalsRelative(makeAbsoluteExternalsRelative) {
2234
- if (makeAbsoluteExternalsRelative === "ifRelativeSource") return { type: "IfRelativeSource" };
2235
- if (typeof makeAbsoluteExternalsRelative === "boolean") return {
2236
- type: "Bool",
2237
- field0: makeAbsoluteExternalsRelative
2238
- };
2239
- }
2240
-
2241
- //#endregion
2242
- //#region ../../node_modules/.pnpm/remeda@2.21.2/node_modules/remeda/dist/chunk-D6FCK2GA.js
2243
- function u$1(o, n, a) {
2244
- let t$1 = (r) => o(r, ...n);
2245
- return a === void 0 ? t$1 : Object.assign(t$1, {
2246
- lazy: a,
2247
- lazyArgs: n
2248
- });
2249
- }
2250
-
2251
- //#endregion
2252
- //#region ../../node_modules/.pnpm/remeda@2.21.2/node_modules/remeda/dist/chunk-WIMGWYZL.js
2253
- function u(r, n, o) {
2254
- let a = r.length - n.length;
2255
- if (a === 0) return r(...n);
2256
- if (a === 1) return u$1(r, n, o);
2257
- throw new Error("Wrong number of arguments");
2258
- }
2259
-
2260
- //#endregion
2261
- //#region ../../node_modules/.pnpm/remeda@2.21.2/node_modules/remeda/dist/chunk-5NQBDF4H.js
2262
- function t(...n) {
2263
- return u(Object.keys, n);
2264
- }
2265
-
2266
- //#endregion
2267
- //#region src/utils/plugin/index.ts
2268
- const isPluginHookName = function() {
2269
- const PLUGIN_HOOK_NAMES_SET = new Set(ENUMERATED_PLUGIN_HOOK_NAMES);
2270
- return function isPluginHookName$1(hookName) {
2271
- return PLUGIN_HOOK_NAMES_SET.has(hookName);
2272
- };
2273
- }();
2274
-
2275
- //#endregion
2276
- //#region src/utils/compose-js-plugins.ts
2277
- const unsupportedHookName = [
2278
- "augmentChunkHash",
2279
- "generateBundle",
2280
- "moduleParsed",
2281
- "onLog",
2282
- "options",
2283
- "outputOptions",
2284
- "renderError",
2285
- "renderStart",
2286
- "resolveDynamicImport",
2287
- "writeBundle"
2288
- ];
2289
- const unsupportedHooks = new Set(unsupportedHookName);
2290
- function isUnsupportedHooks(hookName) {
2291
- return unsupportedHooks.has(hookName);
2292
- }
2293
- function createComposedPlugin(plugins) {
2294
- const names = [];
2295
- const batchedHooks = {};
2296
- plugins.forEach((plugin, index) => {
2297
- const pluginName = plugin.name || `Anonymous(index: ${index})`;
2298
- names.push(pluginName);
2299
- t(plugin).forEach((pluginProp) => {
2300
- if (isUnsupportedHooks(pluginProp)) throw new Error(`Failed to compose js plugins. Plugin ${pluginName} has an unsupported hook: ${pluginProp}`);
2301
- if (!isPluginHookName(pluginProp)) return;
2302
- switch (pluginProp) {
2303
- case "buildStart": {
2304
- const handlers = batchedHooks.buildStart ?? [];
2305
- batchedHooks.buildStart = handlers;
2306
- if (plugin.buildStart) handlers.push([plugin.buildStart, plugin]);
2307
- break;
2308
- }
2309
- case "load": {
2310
- const handlers = batchedHooks.load ?? [];
2311
- batchedHooks.load = handlers;
2312
- if (plugin.load) handlers.push([plugin.load, plugin]);
2313
- break;
2314
- }
2315
- case "transform": {
2316
- const handlers = batchedHooks.transform ?? [];
2317
- batchedHooks.transform = handlers;
2318
- if (plugin.transform) handlers.push([plugin.transform, plugin]);
2319
- break;
2320
- }
2321
- case "resolveId": {
2322
- const handlers = batchedHooks.resolveId ?? [];
2323
- batchedHooks.resolveId = handlers;
2324
- if (plugin.resolveId) handlers.push([plugin.resolveId, plugin]);
2325
- break;
2326
- }
2327
- case "buildEnd": {
2328
- const handlers = batchedHooks.buildEnd ?? [];
2329
- batchedHooks.buildEnd = handlers;
2330
- if (plugin.buildEnd) handlers.push([plugin.buildEnd, plugin]);
2331
- break;
2332
- }
2333
- case "renderChunk": {
2334
- const handlers = batchedHooks.renderChunk ?? [];
2335
- batchedHooks.renderChunk = handlers;
2336
- if (plugin.renderChunk) handlers.push([plugin.renderChunk, plugin]);
2337
- break;
2338
- }
2339
- case "banner":
2340
- case "footer":
2341
- case "intro":
2342
- case "outro": {
2343
- const hook = plugin[pluginProp];
2344
- if (hook) (batchedHooks[pluginProp] ??= []).push([hook, plugin]);
2345
- break;
2346
- }
2347
- case "closeBundle": {
2348
- const handlers = batchedHooks.closeBundle ?? [];
2349
- batchedHooks.closeBundle = handlers;
2350
- if (plugin.closeBundle) handlers.push([plugin.closeBundle, plugin]);
2351
- break;
2352
- }
2353
- case "watchChange": {
2354
- const handlers = batchedHooks.watchChange ?? [];
2355
- batchedHooks.watchChange = handlers;
2356
- if (plugin.watchChange) handlers.push([plugin.watchChange, plugin]);
2357
- break;
2358
- }
2359
- case "closeWatcher": {
2360
- const handlers = batchedHooks.closeWatcher ?? [];
2361
- batchedHooks.closeWatcher = handlers;
2362
- if (plugin.closeWatcher) handlers.push([plugin.closeWatcher, plugin]);
2363
- break;
2364
- }
2365
- default: {}
2366
- }
2367
- });
2368
- });
2369
- const composed = { name: `Composed(${names.join(", ")})` };
2370
- const createFixedPluginResolveFnMap = new Map();
2371
- function applyFixedPluginResolveFn(ctx, plugin) {
2372
- const createFixedPluginResolveFn = createFixedPluginResolveFnMap.get(plugin);
2373
- if (createFixedPluginResolveFn) ctx.resolve = createFixedPluginResolveFn(ctx, ctx.resolve.bind(ctx));
2374
- return ctx;
2375
- }
2376
- if (batchedHooks.resolveId) {
2377
- const batchedHandlers = batchedHooks.resolveId;
2378
- const handlerSymbols = batchedHandlers.map(([_handler, plugin]) => Symbol(plugin.name ?? `Anonymous`));
2379
- for (let handlerIdx = 0; handlerIdx < batchedHandlers.length; handlerIdx++) {
2380
- const [_handler, plugin] = batchedHandlers[handlerIdx];
2381
- const handlerSymbol = handlerSymbols[handlerIdx];
2382
- const createFixedPluginResolveFn = (ctx, resolve) => {
2383
- return (source, importer, rawContextResolveOptions) => {
2384
- const contextResolveOptions = rawContextResolveOptions ?? {};
2385
- if (contextResolveOptions.skipSelf) {
2386
- contextResolveOptions[SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF] = handlerSymbol;
2387
- contextResolveOptions.skipSelf = false;
2388
- }
2389
- return resolve(source, importer, contextResolveOptions);
2390
- };
2391
- };
2392
- createFixedPluginResolveFnMap.set(plugin, createFixedPluginResolveFn);
2393
- }
2394
- composed.resolveId = async function(source, importer, rawHookResolveIdOptions) {
2395
- const hookResolveIdOptions = rawHookResolveIdOptions;
2396
- const symbolForCallerThatSkipSelf = hookResolveIdOptions?.[SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF];
2397
- for (let handlerIdx = 0; handlerIdx < batchedHandlers.length; handlerIdx++) {
2398
- const [handler, plugin] = batchedHandlers[handlerIdx];
2399
- const handlerSymbol = handlerSymbols[handlerIdx];
2400
- if (symbolForCallerThatSkipSelf === handlerSymbol) continue;
2401
- const { handler: handlerFn } = normalizeHook(handler);
2402
- const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), source, importer, rawHookResolveIdOptions);
2403
- if (!isNullish(result)) return result;
2404
- }
2405
- };
2406
- }
2407
- t(batchedHooks).forEach((hookName) => {
2408
- switch (hookName) {
2409
- case "resolveId": break;
2410
- case "buildStart": {
2411
- if (batchedHooks.buildStart) {
2412
- const batchedHandlers = batchedHooks.buildStart;
2413
- composed.buildStart = async function(options) {
2414
- await Promise.all(batchedHandlers.map(([handler, plugin]) => {
2415
- const { handler: handlerFn } = normalizeHook(handler);
2416
- return handlerFn.call(applyFixedPluginResolveFn(this, plugin), options);
2417
- }));
2418
- };
2419
- }
2420
- break;
2421
- }
2422
- case "load": {
2423
- if (batchedHooks.load) {
2424
- const batchedHandlers = batchedHooks.load;
2425
- composed.load = async function(id) {
2426
- for (const [handler, plugin] of batchedHandlers) {
2427
- const { handler: handlerFn } = normalizeHook(handler);
2428
- const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), id);
2429
- if (!isNullish(result)) return result;
2430
- }
2431
- };
2432
- }
2433
- break;
2434
- }
2435
- case "transform": {
2436
- if (batchedHooks.transform) {
2437
- const batchedHandlers = batchedHooks.transform;
2438
- composed.transform = async function(initialCode, id, moduleType) {
2439
- let code = initialCode;
2440
- let moduleSideEffects = void 0;
2441
- function updateOutput(newCode, newModuleSideEffects) {
2442
- code = newCode;
2443
- moduleSideEffects = newModuleSideEffects ?? void 0;
2444
- }
2445
- for (const [handler, plugin] of batchedHandlers) {
2446
- const { handler: handlerFn } = normalizeHook(handler);
2447
- this.getCombinedSourcemap = () => {
2448
- throw new Error(`The getCombinedSourcemap is not implement in transform hook at composedJsPlugins`);
2449
- };
2450
- const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), code, id, moduleType);
2451
- if (!isNullish(result)) {
2452
- if (typeof result === "string") updateOutput(result);
2453
- else if (result.code) updateOutput(result.code, result.moduleSideEffects);
2454
- }
2455
- }
2456
- return {
2457
- code,
2458
- moduleSideEffects
2459
- };
2460
- };
2461
- }
2462
- break;
2463
- }
2464
- case "buildEnd": {
2465
- if (batchedHooks.buildEnd) {
2466
- const batchedHandlers = batchedHooks.buildEnd;
2467
- composed.buildEnd = async function(err) {
2468
- await Promise.all(batchedHandlers.map(([handler, plugin]) => {
2469
- const { handler: handlerFn } = normalizeHook(handler);
2470
- return handlerFn.call(applyFixedPluginResolveFn(this, plugin), err);
2471
- }));
2472
- };
2473
- }
2474
- break;
2475
- }
2476
- case "renderChunk": {
2477
- if (batchedHooks.renderChunk) {
2478
- const batchedHandlers = batchedHooks.renderChunk;
2479
- composed.renderChunk = async function(code, chunk, options, meta) {
2480
- for (const [handler, plugin] of batchedHandlers) {
2481
- const { handler: handlerFn } = normalizeHook(handler);
2482
- const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), code, chunk, options, meta);
2483
- if (!isNullish(result)) return result;
2484
- }
2485
- };
2486
- }
2487
- break;
2488
- }
2489
- case "banner":
2490
- case "footer":
2491
- case "intro":
2492
- case "outro": {
2493
- const hooks = batchedHooks[hookName];
2494
- if (hooks?.length) composed[hookName] = async function(chunk) {
2495
- const ret = [];
2496
- for (const [hook, plugin] of hooks) {
2497
- const { handler } = normalizeHook(hook);
2498
- ret.push(typeof handler === "string" ? handler : await handler.call(applyFixedPluginResolveFn(this, plugin), chunk));
2499
- }
2500
- return ret.join("\n");
2501
- };
2502
- break;
2503
- }
2504
- case "closeBundle": {
2505
- if (batchedHooks.closeBundle) {
2506
- const batchedHandlers = batchedHooks.closeBundle;
2507
- composed.closeBundle = async function() {
2508
- await Promise.all(batchedHandlers.map(([handler, plugin]) => {
2509
- const { handler: handlerFn } = normalizeHook(handler);
2510
- return handlerFn.call(applyFixedPluginResolveFn(this, plugin));
2511
- }));
2512
- };
2513
- }
2514
- break;
2515
- }
2516
- case "watchChange": {
2517
- if (batchedHooks.watchChange) {
2518
- const batchedHandlers = batchedHooks.watchChange;
2519
- composed.watchChange = async function(id, event) {
2520
- await Promise.all(batchedHandlers.map(([handler, plugin]) => {
2521
- const { handler: handlerFn } = normalizeHook(handler);
2522
- return handlerFn.call(applyFixedPluginResolveFn(this, plugin), id, event);
2523
- }));
2524
- };
2525
- }
2526
- break;
2527
- }
2528
- case "closeWatcher": {
2529
- if (batchedHooks.closeWatcher) {
2530
- const batchedHandlers = batchedHooks.closeWatcher;
2531
- composed.closeWatcher = async function() {
2532
- await Promise.all(batchedHandlers.map(([handler, plugin]) => {
2533
- const { handler: handlerFn } = normalizeHook(handler);
2534
- return handlerFn.call(applyFixedPluginResolveFn(this, plugin));
2535
- }));
2536
- };
2537
- }
2538
- break;
2539
- }
2540
- default: {}
2541
- }
2542
- });
2543
- return composed;
2544
- }
2545
- function isComposablePlugin(plugin) {
2546
- if (plugin instanceof BuiltinPlugin) return false;
2547
- if ("_parallel" in plugin) return false;
2548
- const hasNotComposablePattern = t(plugin).some((hookName) => {
2549
- if (!isPluginHookName(hookName)) return false;
2550
- const OK_TO_COMPOSE = false;
2551
- if (isUnsupportedHooks(hookName)) return !OK_TO_COMPOSE;
2552
- if (plugin[hookName]) {
2553
- const { meta } = normalizeHook(plugin[hookName]);
2554
- if (meta.order === "pre" || meta.order === "post") return !OK_TO_COMPOSE;
2555
- }
2556
- return OK_TO_COMPOSE;
2557
- });
2558
- if (hasNotComposablePattern) return false;
2559
- return true;
2560
- }
2561
- function composeJsPlugins(plugins) {
2562
- const newPlugins = [];
2563
- const toBeComposed = [];
2564
- plugins.forEach((plugin) => {
2565
- if (isComposablePlugin(plugin)) toBeComposed.push(plugin);
2566
- else {
2567
- if (toBeComposed.length > 0) {
2568
- if (toBeComposed.length > 1) newPlugins.push(createComposedPlugin(toBeComposed));
2569
- else newPlugins.push(toBeComposed[0]);
2570
- toBeComposed.length = 0;
2571
- }
2572
- newPlugins.push(plugin);
2573
- }
2574
- });
2575
- if (toBeComposed.length > 0) {
2576
- if (toBeComposed.length > 1) newPlugins.push(createComposedPlugin(toBeComposed));
2577
- else newPlugins.push(toBeComposed[0]);
2578
- toBeComposed.length = 0;
2579
- }
2580
- return newPlugins;
2581
- }
2582
-
2583
- //#endregion
2584
- //#region src/utils/initialize-parallel-plugins.ts
2585
- async function initializeParallelPlugins(plugins) {
2586
- const pluginInfos = [];
2587
- for (const [index, plugin] of plugins.entries()) if ("_parallel" in plugin) {
2588
- const { fileUrl, options } = plugin._parallel;
2589
- pluginInfos.push({
2590
- index,
2591
- fileUrl,
2592
- options
2593
- });
2594
- }
2595
- if (pluginInfos.length <= 0) return void 0;
2596
- const count = Math.min(availableParallelism(), 8);
2597
- const parallelJsPluginRegistry = new import_binding.ParallelJsPluginRegistry(count);
2598
- const registryId = parallelJsPluginRegistry.id;
2599
- const workers = await initializeWorkers(registryId, count, pluginInfos);
2600
- const stopWorkers = async () => {
2601
- await Promise.all(workers.map((worker) => worker.terminate()));
2602
- };
2603
- return {
2604
- registry: parallelJsPluginRegistry,
2605
- stopWorkers
2606
- };
2607
- }
2608
- function initializeWorkers(registryId, count, pluginInfos) {
2609
- return Promise.all(Array.from({ length: count }, (_, i) => initializeWorker(registryId, pluginInfos, i)));
2610
- }
2611
- async function initializeWorker(registryId, pluginInfos, threadNumber) {
2612
- const urlString = import.meta.resolve("#parallel-plugin-worker");
2613
- const workerData$1 = {
2614
- registryId,
2615
- pluginInfos,
2616
- threadNumber
2617
- };
2618
- let worker;
2619
- try {
2620
- worker = new Worker(new URL(urlString), { workerData: workerData$1 });
2621
- worker.unref();
2622
- await new Promise((resolve, reject) => {
2623
- worker.once("message", async (message) => {
2624
- if (message.type === "error") reject(message.error);
2625
- else resolve();
2626
- });
2627
- });
2628
- return worker;
2629
- } catch (e) {
2630
- worker?.terminate();
2631
- throw e;
2632
- }
2633
- }
2634
-
2635
- //#endregion
2636
- //#region src/utils/create-bundler-option.ts
2637
- async function createBundlerOptions(inputOptions, outputOptions, watchMode, isClose) {
2638
- const inputPlugins = await normalizePluginOption(inputOptions.plugins);
2639
- const outputPlugins = await normalizePluginOption(outputOptions.plugins);
2640
- const logLevel = inputOptions.logLevel || LOG_LEVEL_INFO;
2641
- const onLog = getLogger(getObjectPlugins(inputPlugins), getOnLog(inputOptions, logLevel), logLevel, watchMode);
2642
- if (!isClose) outputOptions = PluginDriver.callOutputOptionsHook([...inputPlugins, ...outputPlugins], outputOptions, onLog, logLevel, watchMode);
2643
- if (outputOptions.minify === true) onLog(LOG_LEVEL_WARN, logMinifyWarning());
2644
- const normalizedOutputPlugins = await normalizePluginOption(outputOptions.plugins);
2645
- let plugins = [...normalizePlugins(inputPlugins, ANONYMOUS_PLUGIN_PREFIX), ...checkOutputPluginOption(normalizePlugins(normalizedOutputPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX), onLog)];
2646
- if (inputOptions.experimental?.enableComposingJsPlugins ?? false) plugins = composeJsPlugins(plugins);
2647
- const parallelPluginInitResult = await initializeParallelPlugins(plugins);
2648
- try {
2649
- const bindingInputOptions = bindingifyInputOptions(plugins, inputOptions, outputOptions, normalizedOutputPlugins, onLog, logLevel, watchMode);
2650
- const bindingOutputOptions = bindingifyOutputOptions(outputOptions);
2651
- return {
2652
- bundlerOptions: {
2653
- inputOptions: bindingInputOptions,
2654
- outputOptions: bindingOutputOptions,
2655
- parallelPluginsRegistry: parallelPluginInitResult?.registry
2656
- },
2657
- inputOptions,
2658
- onLog,
2659
- stopWorkers: parallelPluginInitResult?.stopWorkers
2660
- };
2661
- } catch (e) {
2662
- await parallelPluginInitResult?.stopWorkers();
2663
- throw e;
2664
- }
2665
- }
2666
-
2667
- //#endregion
2668
- //#region src/utils/create-bundler.ts
2669
- let asyncRuntimeShutdown = false;
2670
- async function createBundler(inputOptions, outputOptions, isClose) {
2671
- const option = await createBundlerOptions(inputOptions, outputOptions, false, isClose);
2672
- if (asyncRuntimeShutdown) (0, import_binding.startAsyncRuntime)();
2673
- try {
2674
- return {
2675
- bundler: new import_binding.Bundler(option.bundlerOptions),
2676
- stopWorkers: option.stopWorkers,
2677
- shutdown: () => {
2678
- (0, import_binding.shutdownAsyncRuntime)();
2679
- asyncRuntimeShutdown = true;
2680
- }
2681
- };
2682
- } catch (e) {
2683
- await option.stopWorkers?.();
2684
- throw e;
2685
- }
2686
- }
2687
-
2688
- //#endregion
2689
- //#region src/api/rolldown/rolldown-build.ts
2690
- Symbol.asyncDispose ??= Symbol("Symbol.asyncDispose");
2691
- var RolldownBuild = class {
2692
- #inputOptions;
2693
- #bundler;
2694
- constructor(inputOptions) {
2695
- this.#inputOptions = inputOptions;
2696
- }
2697
- get closed() {
2698
- return this.#bundler?.bundler.closed ?? false;
2699
- }
2700
- async #getBundlerWithStopWorker(outputOptions, isClose) {
2701
- if (this.#bundler) await this.#bundler.stopWorkers?.();
2702
- return this.#bundler = await createBundler(this.#inputOptions, outputOptions, isClose);
2703
- }
2704
- async generate(outputOptions = {}) {
2705
- validateOption("output", outputOptions);
2706
- const { bundler } = await this.#getBundlerWithStopWorker(outputOptions);
2707
- const output = await bundler.generate();
2708
- return transformToRollupOutput(output);
2709
- }
2710
- async write(outputOptions = {}) {
2711
- validateOption("output", outputOptions);
2712
- const { bundler } = await this.#getBundlerWithStopWorker(outputOptions);
2713
- const output = await bundler.write();
2714
- return transformToRollupOutput(output);
2715
- }
2716
- async close() {
2717
- const { bundler, stopWorkers, shutdown } = await this.#getBundlerWithStopWorker({}, true);
2718
- await stopWorkers?.();
2719
- await bundler.close();
2720
- shutdown();
2721
- }
2722
- async [Symbol.asyncDispose]() {
2723
- await this.close();
2724
- }
2725
- async generateHmrPatch(changedFiles) {
2726
- return this.#bundler?.bundler.generateHmrPatch(changedFiles);
2727
- }
2728
- };
2729
-
2730
- //#endregion
2731
- //#region src/api/rolldown/index.ts
2732
- const rolldown = async (input) => {
2733
- validateOption("input", input);
2734
- const inputOptions = await PluginDriver.callOptionsHook(input);
2735
- return new RolldownBuild(inputOptions);
2736
- };
2737
-
2738
- //#endregion
2739
- //#region src/api/build.ts
2740
- async function build(options) {
2741
- if (Array.isArray(options)) return Promise.all(options.map((opts) => build(opts)));
2742
- else {
2743
- const { output, write = true,...inputOptions } = options;
2744
- const build$1 = await rolldown(inputOptions);
2745
- try {
2746
- if (write) return await build$1.write(output);
2747
- else return await build$1.generate(output);
2748
- } finally {
2749
- await build$1.close();
2750
- }
2751
- }
2752
- }
2753
-
2754
- //#endregion
2755
- //#region src/api/watch/watch-emitter.ts
2756
- var WatcherEmitter = class {
2757
- listeners = new Map();
2758
- timer;
2759
- constructor() {
2760
- this.timer = setInterval(
2761
- () => {},
2762
- 1e9
2763
- /* Low power usage */
2764
- );
2765
- }
2766
- on(event, listener) {
2767
- const listeners = this.listeners.get(event);
2768
- if (listeners) listeners.push(listener);
2769
- else this.listeners.set(event, [listener]);
2770
- return this;
2771
- }
2772
- async onEvent(event) {
2773
- const listeners = this.listeners.get(event.eventKind());
2774
- if (listeners) switch (event.eventKind()) {
2775
- case "close":
2776
- case "restart":
2777
- for (const listener of listeners) await listener();
2778
- break;
2779
- case "event":
2780
- for (const listener of listeners) {
2781
- const code = event.bundleEventKind();
2782
- switch (code) {
2783
- case "BUNDLE_END":
2784
- const { duration, output } = event.bundleEndData();
2785
- await listener({
2786
- code: "BUNDLE_END",
2787
- duration,
2788
- output: [output]
2789
- });
2790
- break;
2791
- case "ERROR":
2792
- const errors = event.errors();
2793
- await listener({
2794
- code: "ERROR",
2795
- error: normalizeErrors(errors)
2796
- });
2797
- break;
2798
- default:
2799
- await listener({ code });
2800
- break;
2801
- }
2802
- }
2803
- break;
2804
- case "change":
2805
- for (const listener of listeners) {
2806
- const { path: path$1, kind } = event.watchChangeData();
2807
- await listener(path$1, { event: kind });
2808
- }
2809
- break;
2810
- default: throw new Error(`Unknown event: ${event}`);
2811
- }
2812
- }
2813
- async close() {
2814
- clearInterval(this.timer);
2815
- }
2816
- };
2817
-
2818
- //#endregion
2819
- //#region src/api/watch/watcher.ts
2820
- var Watcher = class {
2821
- closed;
2822
- inner;
2823
- emitter;
2824
- stopWorkers;
2825
- constructor(emitter, inner, stopWorkers) {
2826
- this.closed = false;
2827
- this.inner = inner;
2828
- this.emitter = emitter;
2829
- const originClose = emitter.close.bind(emitter);
2830
- emitter.close = async () => {
2831
- await this.close();
2832
- originClose();
2833
- };
2834
- this.stopWorkers = stopWorkers;
2835
- }
2836
- async close() {
2837
- if (this.closed) return;
2838
- this.closed = true;
2839
- for (const stop of this.stopWorkers) await stop?.();
2840
- await this.inner.close();
2841
- (0, import_binding.shutdownAsyncRuntime)();
2842
- }
2843
- start() {
2844
- process.nextTick(() => this.inner.start(this.emitter.onEvent.bind(this.emitter)));
2845
- }
2846
- };
2847
- async function createWatcher(emitter, input) {
2848
- const options = arraify(input);
2849
- const bundlerOptions = await Promise.all(options.map((option) => arraify(option.output || {}).map(async (output) => {
2850
- const inputOptions = await PluginDriver.callOptionsHook(option, true);
2851
- return createBundlerOptions(inputOptions, output, true);
2852
- })).flat());
2853
- const notifyOptions = getValidNotifyOption(bundlerOptions);
2854
- const bindingWatcher = new import_binding.BindingWatcher(bundlerOptions.map((option) => option.bundlerOptions), notifyOptions);
2855
- const watcher = new Watcher(emitter, bindingWatcher, bundlerOptions.map((option) => option.stopWorkers));
2856
- watcher.start();
2857
- }
2858
- function getValidNotifyOption(bundlerOptions) {
2859
- let result;
2860
- for (const option of bundlerOptions) if (option.inputOptions.watch) {
2861
- const notifyOption = option.inputOptions.watch.notify;
2862
- if (notifyOption) if (result) {
2863
- option.onLog(LOG_LEVEL_WARN, logMultiplyNotifyOption());
2864
- return result;
2865
- } else result = notifyOption;
2866
- }
2867
- }
2868
-
2869
- //#endregion
2870
- //#region src/api/watch/index.ts
2871
- const watch = (input) => {
2872
- const emitter = new WatcherEmitter();
2873
- createWatcher(emitter, input);
2874
- return emitter;
2875
- };
2876
-
2877
- //#endregion
2878
- //#region src/utils/define-config.ts
2879
- function defineConfig(config) {
2880
- return config;
2881
- }
2882
-
2883
- //#endregion
2884
- //#region src/index.ts
2885
- const VERSION = version;
2886
-
2887
- //#endregion
2888
- export { BuiltinPlugin, PluginContextData, VERSION, arraify, bindingifyPlugin, build, buildImportAnalysisPlugin, composeJsPlugins, createBundler, defineConfig, description, dynamicImportVarsPlugin, getInputCliKeys, getJsonSchema, getOutputCliKeys, handleOutputErrors, importGlobPlugin, isolatedDeclarationPlugin, jsonPlugin, loadFallbackPlugin, manifestPlugin, moduleFederationPlugin, modulePreloadPolyfillPlugin, normalizedStringOrRegex, rolldown, validateCliOptions, version, viteResolvePlugin, wasmFallbackPlugin, wasmHelperPlugin, watch };