@rolldown/browser 1.0.0-beta.9-commit.0ec9e7d → 1.0.0-rc.2

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 (73) hide show
  1. package/dist/cli-setup.mjs +16 -0
  2. package/dist/cli.mjs +1084 -1281
  3. package/dist/config.d.mts +1 -3
  4. package/dist/config.mjs +7 -5
  5. package/dist/constructors-B8gqcrFr.js +61 -0
  6. package/dist/experimental-index.browser.mjs +225 -50
  7. package/dist/experimental-index.d.mts +164 -76
  8. package/dist/experimental-index.mjs +220 -60
  9. package/dist/experimental-runtime-types.d.ts +98 -0
  10. package/dist/filter-index.d.mts +104 -2
  11. package/dist/filter-index.mjs +123 -3
  12. package/dist/get-log-filter.d.mts +7 -0
  13. package/dist/get-log-filter.mjs +48 -0
  14. package/dist/index.browser.mjs +242 -2
  15. package/dist/index.d.mts +4 -3
  16. package/dist/index.mjs +54 -5
  17. package/dist/{shared/parse-ast-index-BHaE0ECV.cjs → normalize-string-or-regex-CL-PJZI7.js} +70 -137
  18. package/dist/parallel-plugin-worker.mjs +26 -33
  19. package/dist/parallel-plugin.d.mts +7 -7
  20. package/dist/parse-ast-index.d.mts +5 -6
  21. package/dist/parse-ast-index.mjs +1 -2
  22. package/dist/plugins-index.browser.mjs +39 -0
  23. package/dist/plugins-index.d.mts +30 -0
  24. package/dist/plugins-index.mjs +39 -0
  25. package/dist/rolldown-binding.wasi-browser.js +41 -24
  26. package/dist/rolldown-binding.wasi.cjs +62 -24
  27. package/dist/rolldown-binding.wasm32-wasi.wasm +0 -0
  28. package/dist/rolldown-build-BntP6Bjl.js +5063 -0
  29. package/dist/shared/bindingify-input-options-CObJx_Uj.mjs +2236 -0
  30. package/dist/shared/composable-filters-CIxSuZSM.mjs +227 -0
  31. package/dist/shared/constructors-5bt5oBhE.d.mts +28 -0
  32. package/dist/shared/constructors-BTW-c3jX.mjs +61 -0
  33. package/dist/shared/define-config-C-sO_cLw.d.mts +3679 -0
  34. package/dist/shared/define-config-Dlptvz3X.mjs +7 -0
  35. package/dist/shared/{load-config-D7UduHRZ.mjs → load-config-hx3WBhLe.mjs} +23 -33
  36. package/dist/shared/logging-RB67zQ4N.d.mts +50 -0
  37. package/dist/shared/{parse-ast-index-vu376yZ1.mjs → logs-B2CASPcx.mjs} +21 -116
  38. package/dist/shared/normalize-string-or-regex-DIwprzLy.mjs +60 -0
  39. package/dist/shared/parse-ast-index-BQpfNG1v.mjs +98 -0
  40. package/dist/shared/{prompt-CxjDC0Gn.cjs → prompt-CYPmuhh-.mjs} +301 -308
  41. package/dist/shared/rolldown-D2E0YTeB.mjs +42 -0
  42. package/dist/shared/rolldown-build-Do6WlRGM.mjs +2371 -0
  43. package/dist/shared/types-CIhJMr1h.d.mts +1300 -0
  44. package/dist/shared/utils-CqMTwlsR.d.mts +22 -0
  45. package/dist/shared/watch-BsneBCNP.mjs +378 -0
  46. package/package.json +33 -38
  47. package/dist/cli.cjs +0 -1748
  48. package/dist/config.cjs +0 -12
  49. package/dist/config.d.cts +0 -11
  50. package/dist/experimental-index.cjs +0 -129
  51. package/dist/experimental-index.d.cts +0 -96
  52. package/dist/filter-index.cjs +0 -53
  53. package/dist/filter-index.d.cts +0 -3
  54. package/dist/index.cjs +0 -9
  55. package/dist/index.d.cts +0 -3
  56. package/dist/parallel-plugin-worker.cjs +0 -33
  57. package/dist/parallel-plugin-worker.d.cts +0 -1
  58. package/dist/parallel-plugin.cjs +0 -8
  59. package/dist/parallel-plugin.d.cts +0 -14
  60. package/dist/parse-ast-index.cjs +0 -4
  61. package/dist/parse-ast-index.d.cts +0 -9
  62. package/dist/shared/chunk-DDkG_k5U.cjs +0 -39
  63. package/dist/shared/chunk-DSsiIF1Z.mjs +0 -30
  64. package/dist/shared/define-config.d-D4lKXE9V.d.cts +0 -1165
  65. package/dist/shared/define-config.d-Dm9iNdt9.d.mts +0 -1165
  66. package/dist/shared/dist-BMVjvV-v.cjs +0 -249
  67. package/dist/shared/dist-CAn6dxW6.mjs +0 -153
  68. package/dist/shared/load-config-CtKjQ8Mn.cjs +0 -125
  69. package/dist/shared/prompt-GFYxfPw7.mjs +0 -854
  70. package/dist/shared/src-D0nc44MQ.mjs +0 -4691
  71. package/dist/shared/src-s89s870G.cjs +0 -4647
  72. package/dist/src-CeWghjQt.js +0 -4329
  73. /package/dist/{cli.d.cts → cli-setup.d.mts} +0 -0
@@ -1,4329 +0,0 @@
1
- import { BindingCallableBuiltinPlugin, BindingHookSideEffects, BindingJsx, BindingLogLevel, BindingPluginOrder, BindingWatcher, Bundler, parseSync, shutdownAsyncRuntime, startAsyncRuntime } from "./rolldown-binding.wasi-browser.js";
2
- import path from "pathe";
3
- import colors from "ansis";
4
-
5
- //#region package.json
6
- var version = "1.0.0-beta.9-commit.0ec9e7d";
7
-
8
- //#endregion
9
- //#region src/builtin-plugin/utils.ts
10
- function makeBuiltinPluginCallable(plugin) {
11
- let callablePlugin = new BindingCallableBuiltinPlugin(bindingifyBuiltInPlugin(plugin));
12
- const wrappedPlugin = plugin;
13
- for (const key in callablePlugin) wrappedPlugin[key] = function(...args$1) {
14
- return callablePlugin[key](...args$1);
15
- };
16
- return wrappedPlugin;
17
- }
18
- function bindingifyBuiltInPlugin(plugin) {
19
- return {
20
- __name: plugin.name,
21
- options: plugin._options
22
- };
23
- }
24
-
25
- //#endregion
26
- //#region src/builtin-plugin/constructors.ts
27
- var BuiltinPlugin = class {
28
- constructor(name, _options) {
29
- this.name = name;
30
- this._options = _options;
31
- }
32
- };
33
- function modulePreloadPolyfillPlugin() {
34
- return new BuiltinPlugin("builtin:module-preload-polyfill");
35
- }
36
- function dynamicImportVarsPlugin(config) {
37
- return new BuiltinPlugin("builtin:dynamic-import-vars", config);
38
- }
39
- function importGlobPlugin(config) {
40
- return new BuiltinPlugin("builtin:import-glob", config);
41
- }
42
- function reporterPlugin(config) {
43
- return new BuiltinPlugin("builtin:reporter", config);
44
- }
45
- function manifestPlugin(config) {
46
- return new BuiltinPlugin("builtin:manifest", config);
47
- }
48
- function wasmHelperPlugin() {
49
- return new BuiltinPlugin("builtin:wasm-helper");
50
- }
51
- function wasmFallbackPlugin() {
52
- return new BuiltinPlugin("builtin:wasm-fallback");
53
- }
54
- function loadFallbackPlugin() {
55
- return new BuiltinPlugin("builtin:load-fallback");
56
- }
57
- function jsonPlugin(config) {
58
- return new BuiltinPlugin("builtin:json", config);
59
- }
60
- function buildImportAnalysisPlugin(config) {
61
- return new BuiltinPlugin("builtin:build-import-analysis", config);
62
- }
63
- function viteResolvePlugin(config) {
64
- const builtinPlugin = new BuiltinPlugin("builtin:vite-resolve", config);
65
- return makeBuiltinPluginCallable(builtinPlugin);
66
- }
67
- function moduleFederationPlugin(config) {
68
- return new BuiltinPlugin("builtin:module-federation", {
69
- ...config,
70
- remotes: config.remotes && Object.entries(config.remotes).map(([name, remote]) => {
71
- if (typeof remote === "string") {
72
- const [entryGlobalName] = remote.split("@");
73
- const entry = remote.replace(entryGlobalName + "@", "");
74
- return {
75
- entry,
76
- name,
77
- entryGlobalName
78
- };
79
- }
80
- return {
81
- ...remote,
82
- name: remote.name ?? name
83
- };
84
- }),
85
- manifest: config.manifest === false ? void 0 : config.manifest === true ? {} : config.manifest
86
- });
87
- }
88
- function isolatedDeclarationPlugin(config) {
89
- return new BuiltinPlugin("builtin:isolated-declaration", config);
90
- }
91
- function assetPlugin(config) {
92
- return new BuiltinPlugin("builtin:asset", config);
93
- }
94
- function webWorkerPostPlugin() {
95
- return new BuiltinPlugin("builtin:web-worker-post");
96
- }
97
-
98
- //#endregion
99
- //#region src/utils/misc.ts
100
- function arraify(value) {
101
- return Array.isArray(value) ? value : [value];
102
- }
103
- function isNullish(value) {
104
- return value === null || value === void 0;
105
- }
106
- function unimplemented(info) {
107
- if (info) throw new Error(`unimplemented: ${info}`);
108
- throw new Error("unimplemented");
109
- }
110
- function unreachable(info) {
111
- if (info) throw new Error(`unreachable: ${info}`);
112
- throw new Error("unreachable");
113
- }
114
- function unsupported(info) {
115
- throw new Error(`UNSUPPORTED: ${info}`);
116
- }
117
- function noop(..._args) {}
118
-
119
- //#endregion
120
- //#region src/log/logging.ts
121
- const LOG_LEVEL_SILENT = "silent";
122
- const LOG_LEVEL_ERROR = "error";
123
- const LOG_LEVEL_WARN = "warn";
124
- const LOG_LEVEL_INFO = "info";
125
- const LOG_LEVEL_DEBUG = "debug";
126
- const logLevelPriority = {
127
- [LOG_LEVEL_DEBUG]: 0,
128
- [LOG_LEVEL_INFO]: 1,
129
- [LOG_LEVEL_WARN]: 2,
130
- [LOG_LEVEL_SILENT]: 3
131
- };
132
-
133
- //#endregion
134
- //#region src/utils/code-frame.ts
135
- function spaces(index) {
136
- let result = "";
137
- while (index--) result += " ";
138
- return result;
139
- }
140
- function tabsToSpaces(value) {
141
- return value.replace(/^\t+/, (match) => match.split(" ").join(" "));
142
- }
143
- const LINE_TRUNCATE_LENGTH = 120;
144
- const MIN_CHARACTERS_SHOWN_AFTER_LOCATION = 10;
145
- const ELLIPSIS = "...";
146
- function getCodeFrame(source, line, column) {
147
- let lines = source.split("\n");
148
- if (line > lines.length) return "";
149
- const maxLineLength = Math.max(tabsToSpaces(lines[line - 1].slice(0, column)).length + MIN_CHARACTERS_SHOWN_AFTER_LOCATION + ELLIPSIS.length, LINE_TRUNCATE_LENGTH);
150
- const frameStart = Math.max(0, line - 3);
151
- let frameEnd = Math.min(line + 2, lines.length);
152
- lines = lines.slice(frameStart, frameEnd);
153
- while (!/\S/.test(lines[lines.length - 1])) {
154
- lines.pop();
155
- frameEnd -= 1;
156
- }
157
- const digits = String(frameEnd).length;
158
- return lines.map((sourceLine, index) => {
159
- const isErrorLine = frameStart + index + 1 === line;
160
- let lineNumber = String(index + frameStart + 1);
161
- while (lineNumber.length < digits) lineNumber = ` ${lineNumber}`;
162
- let displayedLine = tabsToSpaces(sourceLine);
163
- if (displayedLine.length > maxLineLength) displayedLine = `${displayedLine.slice(0, maxLineLength - ELLIPSIS.length)}${ELLIPSIS}`;
164
- if (isErrorLine) {
165
- const indicator = spaces(digits + 2 + tabsToSpaces(sourceLine.slice(0, column)).length) + "^";
166
- return `${lineNumber}: ${displayedLine}\n${indicator}`;
167
- }
168
- return `${lineNumber}: ${displayedLine}`;
169
- }).join("\n");
170
- }
171
-
172
- //#endregion
173
- //#region src/log/locate-character/index.js
174
- /** @typedef {import('./types').Location} Location */
175
- /**
176
- * @param {import('./types').Range} range
177
- * @param {number} index
178
- */
179
- function rangeContains(range, index) {
180
- return range.start <= index && index < range.end;
181
- }
182
- /**
183
- * @param {string} source
184
- * @param {import('./types').Options} [options]
185
- */
186
- function getLocator(source, options = {}) {
187
- const { offsetLine = 0, offsetColumn = 0 } = options;
188
- let start = 0;
189
- const ranges = source.split("\n").map((line, i$2) => {
190
- const end = start + line.length + 1;
191
- /** @type {import('./types').Range} */
192
- const range = {
193
- start,
194
- end,
195
- line: i$2
196
- };
197
- start = end;
198
- return range;
199
- });
200
- let i$1 = 0;
201
- /**
202
- * @param {string | number} search
203
- * @param {number} [index]
204
- * @returns {Location | undefined}
205
- */
206
- function locator(search, index) {
207
- if (typeof search === "string") search = source.indexOf(search, index ?? 0);
208
- if (search === -1) return void 0;
209
- let range = ranges[i$1];
210
- const d$1 = search >= range.end ? 1 : -1;
211
- while (range) {
212
- if (rangeContains(range, search)) return {
213
- line: offsetLine + range.line,
214
- column: offsetColumn + search - range.start,
215
- character: search
216
- };
217
- i$1 += d$1;
218
- range = ranges[i$1];
219
- }
220
- }
221
- return locator;
222
- }
223
- /**
224
- * @param {string} source
225
- * @param {string | number} search
226
- * @param {import('./types').Options} [options]
227
- * @returns {Location | undefined}
228
- */
229
- function locate(source, search, options) {
230
- return getLocator(source, options)(search, options && options.startIndex);
231
- }
232
-
233
- //#endregion
234
- //#region src/log/logs.ts
235
- const INVALID_LOG_POSITION = "INVALID_LOG_POSITION", PLUGIN_ERROR = "PLUGIN_ERROR", INPUT_HOOK_IN_OUTPUT_PLUGIN = "INPUT_HOOK_IN_OUTPUT_PLUGIN", CYCLE_LOADING = "CYCLE_LOADING", MULTIPLY_NOTIFY_OPTION = "MULTIPLY_NOTIFY_OPTION", PARSE_ERROR = "PARSE_ERROR";
236
- function logParseError(message) {
237
- return {
238
- code: PARSE_ERROR,
239
- message
240
- };
241
- }
242
- function logInvalidLogPosition(pluginName) {
243
- return {
244
- code: INVALID_LOG_POSITION,
245
- message: `Plugin "${pluginName}" tried to add a file position to a log or warning. This is only supported in the "transform" hook at the moment and will be ignored.`
246
- };
247
- }
248
- function logInputHookInOutputPlugin(pluginName, hookName) {
249
- return {
250
- code: INPUT_HOOK_IN_OUTPUT_PLUGIN,
251
- message: `The "${hookName}" hook used by the output plugin ${pluginName} is a build time hook and will not be run for that plugin. Either this plugin cannot be used as an output plugin, or it should have an option to configure it as an output plugin.`
252
- };
253
- }
254
- function logCycleLoading(pluginName, moduleId) {
255
- return {
256
- code: CYCLE_LOADING,
257
- message: `Found the module "${moduleId}" cycle loading at ${pluginName} plugin, it maybe blocking fetching modules.`
258
- };
259
- }
260
- function logMultiplyNotifyOption() {
261
- return {
262
- code: MULTIPLY_NOTIFY_OPTION,
263
- message: `Found multiply notify option at watch options, using first one to start notify watcher.`
264
- };
265
- }
266
- function logPluginError(error$1, plugin, { hook, id: id$1 } = {}) {
267
- try {
268
- const code$1 = error$1.code;
269
- if (!error$1.pluginCode && code$1 != null && (typeof code$1 !== "string" || !code$1.startsWith("PLUGIN_"))) error$1.pluginCode = code$1;
270
- error$1.code = PLUGIN_ERROR;
271
- error$1.plugin = plugin;
272
- if (hook) error$1.hook = hook;
273
- if (id$1) error$1.id = id$1;
274
- } catch (_) {} finally {
275
- return error$1;
276
- }
277
- }
278
- function error(base) {
279
- if (!(base instanceof Error)) {
280
- base = Object.assign(new Error(base.message), base);
281
- Object.defineProperty(base, "name", {
282
- value: "RollupError",
283
- writable: true
284
- });
285
- }
286
- throw base;
287
- }
288
- function augmentCodeLocation(properties, pos, source, id$1) {
289
- if (typeof pos === "object") {
290
- const { line, column } = pos;
291
- properties.loc = {
292
- column,
293
- file: id$1,
294
- line
295
- };
296
- } else {
297
- properties.pos = pos;
298
- const location = locate(source, pos, { offsetLine: 1 });
299
- if (!location) return;
300
- const { line, column } = location;
301
- properties.loc = {
302
- column,
303
- file: id$1,
304
- line
305
- };
306
- }
307
- if (properties.frame === void 0) {
308
- const { line, column } = properties.loc;
309
- properties.frame = getCodeFrame(source, line, column);
310
- }
311
- }
312
-
313
- //#endregion
314
- //#region src/log/log-handler.ts
315
- const normalizeLog = (log) => typeof log === "string" ? { message: log } : typeof log === "function" ? normalizeLog(log()) : log;
316
- function getLogHandler(level, code$1, logger, pluginName, logLevel) {
317
- if (logLevelPriority[level] < logLevelPriority[logLevel]) return noop;
318
- return (log, pos) => {
319
- if (pos != null) logger(LOG_LEVEL_WARN, logInvalidLogPosition(pluginName));
320
- log = normalizeLog(log);
321
- if (log.code && !log.pluginCode) log.pluginCode = log.code;
322
- log.code = code$1;
323
- log.plugin = pluginName;
324
- logger(level, log);
325
- };
326
- }
327
-
328
- //#endregion
329
- //#region src/log/logger.ts
330
- function getLogger(plugins, onLog, logLevel, watchMode) {
331
- const minimalPriority = logLevelPriority[logLevel];
332
- const logger = (level, log, skipped = new Set()) => {
333
- const logPriority = logLevelPriority[level];
334
- if (logPriority < minimalPriority) return;
335
- for (const plugin of getSortedPlugins("onLog", plugins)) {
336
- if (skipped.has(plugin)) continue;
337
- const { onLog: pluginOnLog } = plugin;
338
- if (pluginOnLog) {
339
- const getLogHandler$1 = (level$1) => {
340
- if (logLevelPriority[level$1] < minimalPriority) return () => {};
341
- return (log$1) => logger(level$1, normalizeLog(log$1), new Set(skipped).add(plugin));
342
- };
343
- const handler = "handler" in pluginOnLog ? pluginOnLog.handler : pluginOnLog;
344
- if (handler.call({
345
- debug: getLogHandler$1(LOG_LEVEL_DEBUG),
346
- error: (log$1) => error(normalizeLog(log$1)),
347
- info: getLogHandler$1(LOG_LEVEL_INFO),
348
- meta: {
349
- rollupVersion: "4.23.0",
350
- rolldownVersion: VERSION,
351
- watchMode
352
- },
353
- warn: getLogHandler$1(LOG_LEVEL_WARN),
354
- pluginName: plugin.name || "unknown"
355
- }, level, log) === false) return;
356
- }
357
- }
358
- onLog(level, log);
359
- };
360
- return logger;
361
- }
362
- const getOnLog = (config, logLevel, printLog = defaultPrintLog) => {
363
- const { onwarn, onLog } = config;
364
- const defaultOnLog = getDefaultOnLog(printLog, onwarn);
365
- if (onLog) {
366
- const minimalPriority = logLevelPriority[logLevel];
367
- return (level, log) => onLog(level, addLogToString(log), (level$1, handledLog) => {
368
- if (level$1 === LOG_LEVEL_ERROR) return error(normalizeLog(handledLog));
369
- if (logLevelPriority[level$1] >= minimalPriority) defaultOnLog(level$1, normalizeLog(handledLog));
370
- });
371
- }
372
- return defaultOnLog;
373
- };
374
- const getDefaultOnLog = (printLog, onwarn) => onwarn ? (level, log) => {
375
- if (level === LOG_LEVEL_WARN) onwarn(addLogToString(log), (warning) => printLog(LOG_LEVEL_WARN, normalizeLog(warning)));
376
- else printLog(level, log);
377
- } : printLog;
378
- const addLogToString = (log) => {
379
- Object.defineProperty(log, "toString", {
380
- value: () => getExtendedLogMessage(log),
381
- writable: true
382
- });
383
- return log;
384
- };
385
- const defaultPrintLog = (level, log) => {
386
- const message = getExtendedLogMessage(log);
387
- switch (level) {
388
- case LOG_LEVEL_WARN: return console.warn(message);
389
- case LOG_LEVEL_DEBUG: return console.debug(message);
390
- default: return console.info(message);
391
- }
392
- };
393
- const getExtendedLogMessage = (log) => {
394
- let prefix = "";
395
- if (log.plugin) prefix += `(${log.plugin} plugin) `;
396
- if (log.loc) prefix += `${relativeId(log.loc.file)} (${log.loc.line}:${log.loc.column}) `;
397
- return prefix + log.message;
398
- };
399
- function relativeId(id$1) {
400
- if (!path.isAbsolute(id$1)) return id$1;
401
- return path.relative(path.resolve(), id$1);
402
- }
403
-
404
- //#endregion
405
- //#region src/utils/normalize-hook.ts
406
- function normalizeHook(hook) {
407
- if (typeof hook === "function" || typeof hook === "string") return {
408
- handler: hook,
409
- options: {},
410
- meta: {}
411
- };
412
- if (typeof hook === "object" && hook !== null) {
413
- const { handler, order,...options } = hook;
414
- return {
415
- handler,
416
- options,
417
- meta: { order }
418
- };
419
- }
420
- unreachable("Invalid hook type");
421
- }
422
-
423
- //#endregion
424
- //#region src/constants/plugin.ts
425
- const ENUMERATED_INPUT_PLUGIN_HOOK_NAMES = [
426
- "options",
427
- "buildStart",
428
- "resolveId",
429
- "load",
430
- "transform",
431
- "moduleParsed",
432
- "buildEnd",
433
- "onLog",
434
- "resolveDynamicImport",
435
- "closeBundle",
436
- "closeWatcher",
437
- "watchChange"
438
- ];
439
- const ENUMERATED_OUTPUT_PLUGIN_HOOK_NAMES = [
440
- "augmentChunkHash",
441
- "outputOptions",
442
- "renderChunk",
443
- "renderStart",
444
- "renderError",
445
- "writeBundle",
446
- "generateBundle"
447
- ];
448
- const ENUMERATED_PLUGIN_HOOK_NAMES = [
449
- ...ENUMERATED_INPUT_PLUGIN_HOOK_NAMES,
450
- ...ENUMERATED_OUTPUT_PLUGIN_HOOK_NAMES,
451
- "footer",
452
- "banner",
453
- "intro",
454
- "outro"
455
- ];
456
- /**
457
- * Names of all defined hooks. It's like
458
- * ```js
459
- * const DEFINED_HOOK_NAMES ={
460
- * options: 'options',
461
- * buildStart: 'buildStart',
462
- * ...
463
- * }
464
- * ```
465
- */
466
- const DEFINED_HOOK_NAMES = {
467
- [ENUMERATED_PLUGIN_HOOK_NAMES[0]]: ENUMERATED_PLUGIN_HOOK_NAMES[0],
468
- [ENUMERATED_PLUGIN_HOOK_NAMES[1]]: ENUMERATED_PLUGIN_HOOK_NAMES[1],
469
- [ENUMERATED_PLUGIN_HOOK_NAMES[2]]: ENUMERATED_PLUGIN_HOOK_NAMES[2],
470
- [ENUMERATED_PLUGIN_HOOK_NAMES[3]]: ENUMERATED_PLUGIN_HOOK_NAMES[3],
471
- [ENUMERATED_PLUGIN_HOOK_NAMES[4]]: ENUMERATED_PLUGIN_HOOK_NAMES[4],
472
- [ENUMERATED_PLUGIN_HOOK_NAMES[5]]: ENUMERATED_PLUGIN_HOOK_NAMES[5],
473
- [ENUMERATED_PLUGIN_HOOK_NAMES[6]]: ENUMERATED_PLUGIN_HOOK_NAMES[6],
474
- [ENUMERATED_PLUGIN_HOOK_NAMES[7]]: ENUMERATED_PLUGIN_HOOK_NAMES[7],
475
- [ENUMERATED_PLUGIN_HOOK_NAMES[8]]: ENUMERATED_PLUGIN_HOOK_NAMES[8],
476
- [ENUMERATED_PLUGIN_HOOK_NAMES[9]]: ENUMERATED_PLUGIN_HOOK_NAMES[9],
477
- [ENUMERATED_PLUGIN_HOOK_NAMES[10]]: ENUMERATED_PLUGIN_HOOK_NAMES[10],
478
- [ENUMERATED_PLUGIN_HOOK_NAMES[11]]: ENUMERATED_PLUGIN_HOOK_NAMES[11],
479
- [ENUMERATED_PLUGIN_HOOK_NAMES[12]]: ENUMERATED_PLUGIN_HOOK_NAMES[12],
480
- [ENUMERATED_PLUGIN_HOOK_NAMES[13]]: ENUMERATED_PLUGIN_HOOK_NAMES[13],
481
- [ENUMERATED_PLUGIN_HOOK_NAMES[14]]: ENUMERATED_PLUGIN_HOOK_NAMES[14],
482
- [ENUMERATED_PLUGIN_HOOK_NAMES[15]]: ENUMERATED_PLUGIN_HOOK_NAMES[15],
483
- [ENUMERATED_PLUGIN_HOOK_NAMES[16]]: ENUMERATED_PLUGIN_HOOK_NAMES[16],
484
- [ENUMERATED_PLUGIN_HOOK_NAMES[17]]: ENUMERATED_PLUGIN_HOOK_NAMES[17],
485
- [ENUMERATED_PLUGIN_HOOK_NAMES[18]]: ENUMERATED_PLUGIN_HOOK_NAMES[18],
486
- [ENUMERATED_PLUGIN_HOOK_NAMES[19]]: ENUMERATED_PLUGIN_HOOK_NAMES[19],
487
- [ENUMERATED_PLUGIN_HOOK_NAMES[20]]: ENUMERATED_PLUGIN_HOOK_NAMES[20],
488
- [ENUMERATED_PLUGIN_HOOK_NAMES[21]]: ENUMERATED_PLUGIN_HOOK_NAMES[21],
489
- [ENUMERATED_PLUGIN_HOOK_NAMES[22]]: ENUMERATED_PLUGIN_HOOK_NAMES[22]
490
- };
491
-
492
- //#endregion
493
- //#region src/utils/async-flatten.ts
494
- async function asyncFlatten(array$1) {
495
- do
496
- array$1 = (await Promise.all(array$1)).flat(Infinity);
497
- while (array$1.some((v) => v?.then));
498
- return array$1;
499
- }
500
-
501
- //#endregion
502
- //#region src/utils/normalize-plugin-option.ts
503
- const normalizePluginOption = async (plugins) => (await asyncFlatten([plugins])).filter(Boolean);
504
- function checkOutputPluginOption(plugins, onLog) {
505
- for (const plugin of plugins) for (const hook of ENUMERATED_INPUT_PLUGIN_HOOK_NAMES) if (hook in plugin) {
506
- delete plugin[hook];
507
- onLog(LOG_LEVEL_WARN, logInputHookInOutputPlugin(plugin.name, hook));
508
- }
509
- return plugins;
510
- }
511
- function normalizePlugins(plugins, anonymousPrefix) {
512
- for (const [index, plugin] of plugins.entries()) {
513
- if ("_parallel" in plugin) continue;
514
- if (plugin instanceof BuiltinPlugin) continue;
515
- if (!plugin.name) plugin.name = `${anonymousPrefix}${index + 1}`;
516
- }
517
- return plugins;
518
- }
519
- const ANONYMOUS_PLUGIN_PREFIX = "at position ";
520
- const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = "at output position ";
521
- const BUILTIN_PLUGINS = [];
522
-
523
- //#endregion
524
- //#region src/plugin/minimal-plugin-context.ts
525
- var MinimalPluginContextImpl = class {
526
- info;
527
- warn;
528
- debug;
529
- meta;
530
- constructor(onLog, logLevel, pluginName, watchMode, hookName) {
531
- this.pluginName = pluginName;
532
- this.hookName = hookName;
533
- this.debug = getLogHandler(LOG_LEVEL_DEBUG, "PLUGIN_LOG", onLog, pluginName, logLevel);
534
- this.info = getLogHandler(LOG_LEVEL_INFO, "PLUGIN_LOG", onLog, pluginName, logLevel);
535
- this.warn = getLogHandler(LOG_LEVEL_WARN, "PLUGIN_WARNING", onLog, pluginName, logLevel);
536
- this.meta = {
537
- rollupVersion: "4.23.0",
538
- rolldownVersion: VERSION,
539
- watchMode
540
- };
541
- }
542
- error(e) {
543
- return error(logPluginError(normalizeLog(e), this.pluginName, { hook: this.hookName }));
544
- }
545
- };
546
-
547
- //#endregion
548
- //#region src/plugin/plugin-driver.ts
549
- var PluginDriver = class {
550
- static async callOptionsHook(inputOptions, watchMode = false) {
551
- const logLevel = inputOptions.logLevel || LOG_LEVEL_INFO;
552
- const plugins = getSortedPlugins("options", getObjectPlugins(await normalizePluginOption(inputOptions.plugins)));
553
- const logger = getLogger(plugins, getOnLog(inputOptions, logLevel), logLevel, watchMode);
554
- for (const plugin of plugins) {
555
- const name = plugin.name || "unknown";
556
- const options = plugin.options;
557
- if (options) {
558
- const { handler } = normalizeHook(options);
559
- const result = await handler.call(new MinimalPluginContextImpl(logger, logLevel, name, watchMode, "onLog"), inputOptions);
560
- if (result) inputOptions = result;
561
- }
562
- }
563
- return inputOptions;
564
- }
565
- static callOutputOptionsHook(rawPlugins, outputOptions, onLog, logLevel, watchMode) {
566
- const sortedPlugins = getSortedPlugins("outputOptions", getObjectPlugins(rawPlugins));
567
- for (const plugin of sortedPlugins) {
568
- const name = plugin.name || "unknown";
569
- const options = plugin.outputOptions;
570
- if (options) {
571
- const { handler } = normalizeHook(options);
572
- const result = handler.call(new MinimalPluginContextImpl(onLog, logLevel, name, watchMode), outputOptions);
573
- if (result) outputOptions = result;
574
- }
575
- }
576
- return outputOptions;
577
- }
578
- };
579
- function getObjectPlugins(plugins) {
580
- return plugins.filter((plugin) => {
581
- if (!plugin) return void 0;
582
- if ("_parallel" in plugin) return void 0;
583
- if (plugin instanceof BuiltinPlugin) return void 0;
584
- return plugin;
585
- });
586
- }
587
- function getSortedPlugins(hookName, plugins) {
588
- const pre = [];
589
- const normal = [];
590
- const post = [];
591
- for (const plugin of plugins) {
592
- const hook = plugin[hookName];
593
- if (hook) {
594
- if (typeof hook === "object") {
595
- if (hook.order === "pre") {
596
- pre.push(plugin);
597
- continue;
598
- }
599
- if (hook.order === "post") {
600
- post.push(plugin);
601
- continue;
602
- }
603
- }
604
- normal.push(plugin);
605
- }
606
- }
607
- return [
608
- ...pre,
609
- ...normal,
610
- ...post
611
- ];
612
- }
613
-
614
- //#endregion
615
- //#region ../../node_modules/.pnpm/valibot@1.1.0_typescript@5.8.3/node_modules/valibot/dist/index.js
616
- var store;
617
- /* @__NO_SIDE_EFFECTS__ */
618
- function getGlobalConfig(config2) {
619
- return {
620
- lang: config2?.lang ?? store?.lang,
621
- message: config2?.message,
622
- abortEarly: config2?.abortEarly ?? store?.abortEarly,
623
- abortPipeEarly: config2?.abortPipeEarly ?? store?.abortPipeEarly
624
- };
625
- }
626
- var store2;
627
- /* @__NO_SIDE_EFFECTS__ */
628
- function getGlobalMessage(lang) {
629
- return store2?.get(lang);
630
- }
631
- var store3;
632
- /* @__NO_SIDE_EFFECTS__ */
633
- function getSchemaMessage(lang) {
634
- return store3?.get(lang);
635
- }
636
- var store4;
637
- /* @__NO_SIDE_EFFECTS__ */
638
- function getSpecificMessage(reference, lang) {
639
- return store4?.get(reference)?.get(lang);
640
- }
641
- /* @__NO_SIDE_EFFECTS__ */
642
- function _stringify(input) {
643
- const type = typeof input;
644
- if (type === "string") return `"${input}"`;
645
- if (type === "number" || type === "bigint" || type === "boolean") return `${input}`;
646
- if (type === "object" || type === "function") return (input && Object.getPrototypeOf(input)?.constructor?.name) ?? "null";
647
- return type;
648
- }
649
- function _addIssue(context, label, dataset, config2, other) {
650
- const input = other && "input" in other ? other.input : dataset.value;
651
- const expected = other?.expected ?? context.expects ?? null;
652
- const received = other?.received ?? /* @__PURE__ */ _stringify(input);
653
- const issue = {
654
- kind: context.kind,
655
- type: context.type,
656
- input,
657
- expected,
658
- received,
659
- message: `Invalid ${label}: ${expected ? `Expected ${expected} but r` : "R"}eceived ${received}`,
660
- requirement: context.requirement,
661
- path: other?.path,
662
- issues: other?.issues,
663
- lang: config2.lang,
664
- abortEarly: config2.abortEarly,
665
- abortPipeEarly: config2.abortPipeEarly
666
- };
667
- const isSchema = context.kind === "schema";
668
- const message2 = other?.message ?? context.message ?? /* @__PURE__ */ getSpecificMessage(context.reference, issue.lang) ?? (isSchema ? /* @__PURE__ */ getSchemaMessage(issue.lang) : null) ?? config2.message ?? /* @__PURE__ */ getGlobalMessage(issue.lang);
669
- if (message2 !== void 0) issue.message = typeof message2 === "function" ? message2(issue) : message2;
670
- if (isSchema) dataset.typed = false;
671
- if (dataset.issues) dataset.issues.push(issue);
672
- else dataset.issues = [issue];
673
- }
674
- /* @__NO_SIDE_EFFECTS__ */
675
- function _getStandardProps(context) {
676
- return {
677
- version: 1,
678
- vendor: "valibot",
679
- validate(value2) {
680
- return context["~run"]({ value: value2 }, /* @__PURE__ */ getGlobalConfig());
681
- }
682
- };
683
- }
684
- /* @__NO_SIDE_EFFECTS__ */
685
- function _isValidObjectKey(object2, key) {
686
- return Object.hasOwn(object2, key) && key !== "__proto__" && key !== "prototype" && key !== "constructor";
687
- }
688
- /* @__NO_SIDE_EFFECTS__ */
689
- function _joinExpects(values2, separator) {
690
- const list = [...new Set(values2)];
691
- if (list.length > 1) return `(${list.join(` ${separator} `)})`;
692
- return list[0] ?? "never";
693
- }
694
- var ValiError = class extends Error {
695
- /**
696
- * Creates a Valibot error with useful information.
697
- *
698
- * @param issues The error issues.
699
- */
700
- constructor(issues) {
701
- super(issues[0].message);
702
- this.name = "ValiError";
703
- this.issues = issues;
704
- }
705
- };
706
- /* @__NO_SIDE_EFFECTS__ */
707
- function args(schema) {
708
- return {
709
- kind: "transformation",
710
- type: "args",
711
- reference: args,
712
- async: false,
713
- schema,
714
- "~run"(dataset, config2) {
715
- const func = dataset.value;
716
- dataset.value = (...args_) => {
717
- const argsDataset = this.schema["~run"]({ value: args_ }, config2);
718
- if (argsDataset.issues) throw new ValiError(argsDataset.issues);
719
- return func(...argsDataset.value);
720
- };
721
- return dataset;
722
- }
723
- };
724
- }
725
- /* @__NO_SIDE_EFFECTS__ */
726
- function awaitAsync() {
727
- return {
728
- kind: "transformation",
729
- type: "await",
730
- reference: awaitAsync,
731
- async: true,
732
- async "~run"(dataset) {
733
- dataset.value = await dataset.value;
734
- return dataset;
735
- }
736
- };
737
- }
738
- /* @__NO_SIDE_EFFECTS__ */
739
- function description(description_) {
740
- return {
741
- kind: "metadata",
742
- type: "description",
743
- reference: description,
744
- description: description_
745
- };
746
- }
747
- /* @__NO_SIDE_EFFECTS__ */
748
- function returns(schema) {
749
- return {
750
- kind: "transformation",
751
- type: "returns",
752
- reference: returns,
753
- async: false,
754
- schema,
755
- "~run"(dataset, config2) {
756
- const func = dataset.value;
757
- dataset.value = (...args_) => {
758
- const returnsDataset = this.schema["~run"]({ value: func(...args_) }, config2);
759
- if (returnsDataset.issues) throw new ValiError(returnsDataset.issues);
760
- return returnsDataset.value;
761
- };
762
- return dataset;
763
- }
764
- };
765
- }
766
- /* @__NO_SIDE_EFFECTS__ */
767
- function returnsAsync(schema) {
768
- return {
769
- kind: "transformation",
770
- type: "returns",
771
- reference: returnsAsync,
772
- async: false,
773
- schema,
774
- "~run"(dataset, config2) {
775
- const func = dataset.value;
776
- dataset.value = async (...args_) => {
777
- const returnsDataset = await this.schema["~run"]({ value: await func(...args_) }, config2);
778
- if (returnsDataset.issues) throw new ValiError(returnsDataset.issues);
779
- return returnsDataset.value;
780
- };
781
- return dataset;
782
- }
783
- };
784
- }
785
- /* @__NO_SIDE_EFFECTS__ */
786
- function getFallback(schema, dataset, config2) {
787
- return typeof schema.fallback === "function" ? schema.fallback(dataset, config2) : schema.fallback;
788
- }
789
- /* @__NO_SIDE_EFFECTS__ */
790
- function getDefault(schema, dataset, config2) {
791
- return typeof schema.default === "function" ? schema.default(dataset, config2) : schema.default;
792
- }
793
- /* @__NO_SIDE_EFFECTS__ */
794
- function any() {
795
- return {
796
- kind: "schema",
797
- type: "any",
798
- reference: any,
799
- expects: "any",
800
- async: false,
801
- get "~standard"() {
802
- return /* @__PURE__ */ _getStandardProps(this);
803
- },
804
- "~run"(dataset) {
805
- dataset.typed = true;
806
- return dataset;
807
- }
808
- };
809
- }
810
- /* @__NO_SIDE_EFFECTS__ */
811
- function array(item, message2) {
812
- return {
813
- kind: "schema",
814
- type: "array",
815
- reference: array,
816
- expects: "Array",
817
- async: false,
818
- item,
819
- message: message2,
820
- get "~standard"() {
821
- return /* @__PURE__ */ _getStandardProps(this);
822
- },
823
- "~run"(dataset, config2) {
824
- const input = dataset.value;
825
- if (Array.isArray(input)) {
826
- dataset.typed = true;
827
- dataset.value = [];
828
- for (let key = 0; key < input.length; key++) {
829
- const value2 = input[key];
830
- const itemDataset = this.item["~run"]({ value: value2 }, config2);
831
- if (itemDataset.issues) {
832
- const pathItem = {
833
- type: "array",
834
- origin: "value",
835
- input,
836
- key,
837
- value: value2
838
- };
839
- for (const issue of itemDataset.issues) {
840
- if (issue.path) issue.path.unshift(pathItem);
841
- else issue.path = [pathItem];
842
- dataset.issues?.push(issue);
843
- }
844
- if (!dataset.issues) dataset.issues = itemDataset.issues;
845
- if (config2.abortEarly) {
846
- dataset.typed = false;
847
- break;
848
- }
849
- }
850
- if (!itemDataset.typed) dataset.typed = false;
851
- dataset.value.push(itemDataset.value);
852
- }
853
- } else _addIssue(this, "type", dataset, config2);
854
- return dataset;
855
- }
856
- };
857
- }
858
- /* @__NO_SIDE_EFFECTS__ */
859
- function boolean(message2) {
860
- return {
861
- kind: "schema",
862
- type: "boolean",
863
- reference: boolean,
864
- expects: "boolean",
865
- async: false,
866
- message: message2,
867
- get "~standard"() {
868
- return /* @__PURE__ */ _getStandardProps(this);
869
- },
870
- "~run"(dataset, config2) {
871
- if (typeof dataset.value === "boolean") dataset.typed = true;
872
- else _addIssue(this, "type", dataset, config2);
873
- return dataset;
874
- }
875
- };
876
- }
877
- /* @__NO_SIDE_EFFECTS__ */
878
- function custom(check2, message2) {
879
- return {
880
- kind: "schema",
881
- type: "custom",
882
- reference: custom,
883
- expects: "unknown",
884
- async: false,
885
- check: check2,
886
- message: message2,
887
- get "~standard"() {
888
- return /* @__PURE__ */ _getStandardProps(this);
889
- },
890
- "~run"(dataset, config2) {
891
- if (this.check(dataset.value)) dataset.typed = true;
892
- else _addIssue(this, "type", dataset, config2);
893
- return dataset;
894
- }
895
- };
896
- }
897
- /* @__NO_SIDE_EFFECTS__ */
898
- function function_(message2) {
899
- return {
900
- kind: "schema",
901
- type: "function",
902
- reference: function_,
903
- expects: "Function",
904
- async: false,
905
- message: message2,
906
- get "~standard"() {
907
- return /* @__PURE__ */ _getStandardProps(this);
908
- },
909
- "~run"(dataset, config2) {
910
- if (typeof dataset.value === "function") dataset.typed = true;
911
- else _addIssue(this, "type", dataset, config2);
912
- return dataset;
913
- }
914
- };
915
- }
916
- /* @__NO_SIDE_EFFECTS__ */
917
- function instance(class_, message2) {
918
- return {
919
- kind: "schema",
920
- type: "instance",
921
- reference: instance,
922
- expects: class_.name,
923
- async: false,
924
- class: class_,
925
- message: message2,
926
- get "~standard"() {
927
- return /* @__PURE__ */ _getStandardProps(this);
928
- },
929
- "~run"(dataset, config2) {
930
- if (dataset.value instanceof this.class) dataset.typed = true;
931
- else _addIssue(this, "type", dataset, config2);
932
- return dataset;
933
- }
934
- };
935
- }
936
- /* @__NO_SIDE_EFFECTS__ */
937
- function literal(literal_, message2) {
938
- return {
939
- kind: "schema",
940
- type: "literal",
941
- reference: literal,
942
- expects: /* @__PURE__ */ _stringify(literal_),
943
- async: false,
944
- literal: literal_,
945
- message: message2,
946
- get "~standard"() {
947
- return /* @__PURE__ */ _getStandardProps(this);
948
- },
949
- "~run"(dataset, config2) {
950
- if (dataset.value === this.literal) dataset.typed = true;
951
- else _addIssue(this, "type", dataset, config2);
952
- return dataset;
953
- }
954
- };
955
- }
956
- /* @__NO_SIDE_EFFECTS__ */
957
- function looseObject(entries2, message2) {
958
- return {
959
- kind: "schema",
960
- type: "loose_object",
961
- reference: looseObject,
962
- expects: "Object",
963
- async: false,
964
- entries: entries2,
965
- message: message2,
966
- get "~standard"() {
967
- return /* @__PURE__ */ _getStandardProps(this);
968
- },
969
- "~run"(dataset, config2) {
970
- const input = dataset.value;
971
- if (input && typeof input === "object") {
972
- dataset.typed = true;
973
- dataset.value = {};
974
- for (const key in this.entries) {
975
- const valueSchema = this.entries[key];
976
- if (key in input || (valueSchema.type === "exact_optional" || valueSchema.type === "optional" || valueSchema.type === "nullish") && valueSchema.default !== void 0) {
977
- const value2 = key in input ? input[key] : /* @__PURE__ */ getDefault(valueSchema);
978
- const valueDataset = valueSchema["~run"]({ value: value2 }, config2);
979
- if (valueDataset.issues) {
980
- const pathItem = {
981
- type: "object",
982
- origin: "value",
983
- input,
984
- key,
985
- value: value2
986
- };
987
- for (const issue of valueDataset.issues) {
988
- if (issue.path) issue.path.unshift(pathItem);
989
- else issue.path = [pathItem];
990
- dataset.issues?.push(issue);
991
- }
992
- if (!dataset.issues) dataset.issues = valueDataset.issues;
993
- if (config2.abortEarly) {
994
- dataset.typed = false;
995
- break;
996
- }
997
- }
998
- if (!valueDataset.typed) dataset.typed = false;
999
- dataset.value[key] = valueDataset.value;
1000
- } else if (valueSchema.fallback !== void 0) dataset.value[key] = /* @__PURE__ */ getFallback(valueSchema);
1001
- else if (valueSchema.type !== "exact_optional" && valueSchema.type !== "optional" && valueSchema.type !== "nullish") {
1002
- _addIssue(this, "key", dataset, config2, {
1003
- input: void 0,
1004
- expected: `"${key}"`,
1005
- path: [{
1006
- type: "object",
1007
- origin: "key",
1008
- input,
1009
- key,
1010
- value: input[key]
1011
- }]
1012
- });
1013
- if (config2.abortEarly) break;
1014
- }
1015
- }
1016
- if (!dataset.issues || !config2.abortEarly) {
1017
- for (const key in input) if (/* @__PURE__ */ _isValidObjectKey(input, key) && !(key in this.entries)) dataset.value[key] = input[key];
1018
- }
1019
- } else _addIssue(this, "type", dataset, config2);
1020
- return dataset;
1021
- }
1022
- };
1023
- }
1024
- /* @__NO_SIDE_EFFECTS__ */
1025
- function never(message2) {
1026
- return {
1027
- kind: "schema",
1028
- type: "never",
1029
- reference: never,
1030
- expects: "never",
1031
- async: false,
1032
- message: message2,
1033
- get "~standard"() {
1034
- return /* @__PURE__ */ _getStandardProps(this);
1035
- },
1036
- "~run"(dataset, config2) {
1037
- _addIssue(this, "type", dataset, config2);
1038
- return dataset;
1039
- }
1040
- };
1041
- }
1042
- /* @__NO_SIDE_EFFECTS__ */
1043
- function nullish(wrapped, default_) {
1044
- return {
1045
- kind: "schema",
1046
- type: "nullish",
1047
- reference: nullish,
1048
- expects: `(${wrapped.expects} | null | undefined)`,
1049
- async: false,
1050
- wrapped,
1051
- default: default_,
1052
- get "~standard"() {
1053
- return /* @__PURE__ */ _getStandardProps(this);
1054
- },
1055
- "~run"(dataset, config2) {
1056
- if (dataset.value === null || dataset.value === void 0) {
1057
- if (this.default !== void 0) dataset.value = /* @__PURE__ */ getDefault(this, dataset, config2);
1058
- if (dataset.value === null || dataset.value === void 0) {
1059
- dataset.typed = true;
1060
- return dataset;
1061
- }
1062
- }
1063
- return this.wrapped["~run"](dataset, config2);
1064
- }
1065
- };
1066
- }
1067
- /* @__NO_SIDE_EFFECTS__ */
1068
- function number(message2) {
1069
- return {
1070
- kind: "schema",
1071
- type: "number",
1072
- reference: number,
1073
- expects: "number",
1074
- async: false,
1075
- message: message2,
1076
- get "~standard"() {
1077
- return /* @__PURE__ */ _getStandardProps(this);
1078
- },
1079
- "~run"(dataset, config2) {
1080
- if (typeof dataset.value === "number" && !isNaN(dataset.value)) dataset.typed = true;
1081
- else _addIssue(this, "type", dataset, config2);
1082
- return dataset;
1083
- }
1084
- };
1085
- }
1086
- /* @__NO_SIDE_EFFECTS__ */
1087
- function object(entries2, message2) {
1088
- return {
1089
- kind: "schema",
1090
- type: "object",
1091
- reference: object,
1092
- expects: "Object",
1093
- async: false,
1094
- entries: entries2,
1095
- message: message2,
1096
- get "~standard"() {
1097
- return /* @__PURE__ */ _getStandardProps(this);
1098
- },
1099
- "~run"(dataset, config2) {
1100
- const input = dataset.value;
1101
- if (input && typeof input === "object") {
1102
- dataset.typed = true;
1103
- dataset.value = {};
1104
- for (const key in this.entries) {
1105
- const valueSchema = this.entries[key];
1106
- if (key in input || (valueSchema.type === "exact_optional" || valueSchema.type === "optional" || valueSchema.type === "nullish") && valueSchema.default !== void 0) {
1107
- const value2 = key in input ? input[key] : /* @__PURE__ */ getDefault(valueSchema);
1108
- const valueDataset = valueSchema["~run"]({ value: value2 }, config2);
1109
- if (valueDataset.issues) {
1110
- const pathItem = {
1111
- type: "object",
1112
- origin: "value",
1113
- input,
1114
- key,
1115
- value: value2
1116
- };
1117
- for (const issue of valueDataset.issues) {
1118
- if (issue.path) issue.path.unshift(pathItem);
1119
- else issue.path = [pathItem];
1120
- dataset.issues?.push(issue);
1121
- }
1122
- if (!dataset.issues) dataset.issues = valueDataset.issues;
1123
- if (config2.abortEarly) {
1124
- dataset.typed = false;
1125
- break;
1126
- }
1127
- }
1128
- if (!valueDataset.typed) dataset.typed = false;
1129
- dataset.value[key] = valueDataset.value;
1130
- } else if (valueSchema.fallback !== void 0) dataset.value[key] = /* @__PURE__ */ getFallback(valueSchema);
1131
- else if (valueSchema.type !== "exact_optional" && valueSchema.type !== "optional" && valueSchema.type !== "nullish") {
1132
- _addIssue(this, "key", dataset, config2, {
1133
- input: void 0,
1134
- expected: `"${key}"`,
1135
- path: [{
1136
- type: "object",
1137
- origin: "key",
1138
- input,
1139
- key,
1140
- value: input[key]
1141
- }]
1142
- });
1143
- if (config2.abortEarly) break;
1144
- }
1145
- }
1146
- } else _addIssue(this, "type", dataset, config2);
1147
- return dataset;
1148
- }
1149
- };
1150
- }
1151
- /* @__NO_SIDE_EFFECTS__ */
1152
- function optional(wrapped, default_) {
1153
- return {
1154
- kind: "schema",
1155
- type: "optional",
1156
- reference: optional,
1157
- expects: `(${wrapped.expects} | undefined)`,
1158
- async: false,
1159
- wrapped,
1160
- default: default_,
1161
- get "~standard"() {
1162
- return /* @__PURE__ */ _getStandardProps(this);
1163
- },
1164
- "~run"(dataset, config2) {
1165
- if (dataset.value === void 0) {
1166
- if (this.default !== void 0) dataset.value = /* @__PURE__ */ getDefault(this, dataset, config2);
1167
- if (dataset.value === void 0) {
1168
- dataset.typed = true;
1169
- return dataset;
1170
- }
1171
- }
1172
- return this.wrapped["~run"](dataset, config2);
1173
- }
1174
- };
1175
- }
1176
- /* @__NO_SIDE_EFFECTS__ */
1177
- function promise(message2) {
1178
- return {
1179
- kind: "schema",
1180
- type: "promise",
1181
- reference: promise,
1182
- expects: "Promise",
1183
- async: false,
1184
- message: message2,
1185
- get "~standard"() {
1186
- return /* @__PURE__ */ _getStandardProps(this);
1187
- },
1188
- "~run"(dataset, config2) {
1189
- if (dataset.value instanceof Promise) dataset.typed = true;
1190
- else _addIssue(this, "type", dataset, config2);
1191
- return dataset;
1192
- }
1193
- };
1194
- }
1195
- /* @__NO_SIDE_EFFECTS__ */
1196
- function record(key, value2, message2) {
1197
- return {
1198
- kind: "schema",
1199
- type: "record",
1200
- reference: record,
1201
- expects: "Object",
1202
- async: false,
1203
- key,
1204
- value: value2,
1205
- message: message2,
1206
- get "~standard"() {
1207
- return /* @__PURE__ */ _getStandardProps(this);
1208
- },
1209
- "~run"(dataset, config2) {
1210
- const input = dataset.value;
1211
- if (input && typeof input === "object") {
1212
- dataset.typed = true;
1213
- dataset.value = {};
1214
- for (const entryKey in input) if (/* @__PURE__ */ _isValidObjectKey(input, entryKey)) {
1215
- const entryValue = input[entryKey];
1216
- const keyDataset = this.key["~run"]({ value: entryKey }, config2);
1217
- if (keyDataset.issues) {
1218
- const pathItem = {
1219
- type: "object",
1220
- origin: "key",
1221
- input,
1222
- key: entryKey,
1223
- value: entryValue
1224
- };
1225
- for (const issue of keyDataset.issues) {
1226
- issue.path = [pathItem];
1227
- dataset.issues?.push(issue);
1228
- }
1229
- if (!dataset.issues) dataset.issues = keyDataset.issues;
1230
- if (config2.abortEarly) {
1231
- dataset.typed = false;
1232
- break;
1233
- }
1234
- }
1235
- const valueDataset = this.value["~run"]({ value: entryValue }, config2);
1236
- if (valueDataset.issues) {
1237
- const pathItem = {
1238
- type: "object",
1239
- origin: "value",
1240
- input,
1241
- key: entryKey,
1242
- value: entryValue
1243
- };
1244
- for (const issue of valueDataset.issues) {
1245
- if (issue.path) issue.path.unshift(pathItem);
1246
- else issue.path = [pathItem];
1247
- dataset.issues?.push(issue);
1248
- }
1249
- if (!dataset.issues) dataset.issues = valueDataset.issues;
1250
- if (config2.abortEarly) {
1251
- dataset.typed = false;
1252
- break;
1253
- }
1254
- }
1255
- if (!keyDataset.typed || !valueDataset.typed) dataset.typed = false;
1256
- if (keyDataset.typed) dataset.value[keyDataset.value] = valueDataset.value;
1257
- }
1258
- } else _addIssue(this, "type", dataset, config2);
1259
- return dataset;
1260
- }
1261
- };
1262
- }
1263
- /* @__NO_SIDE_EFFECTS__ */
1264
- function strictObject(entries2, message2) {
1265
- return {
1266
- kind: "schema",
1267
- type: "strict_object",
1268
- reference: strictObject,
1269
- expects: "Object",
1270
- async: false,
1271
- entries: entries2,
1272
- message: message2,
1273
- get "~standard"() {
1274
- return /* @__PURE__ */ _getStandardProps(this);
1275
- },
1276
- "~run"(dataset, config2) {
1277
- const input = dataset.value;
1278
- if (input && typeof input === "object") {
1279
- dataset.typed = true;
1280
- dataset.value = {};
1281
- for (const key in this.entries) {
1282
- const valueSchema = this.entries[key];
1283
- if (key in input || (valueSchema.type === "exact_optional" || valueSchema.type === "optional" || valueSchema.type === "nullish") && valueSchema.default !== void 0) {
1284
- const value2 = key in input ? input[key] : /* @__PURE__ */ getDefault(valueSchema);
1285
- const valueDataset = valueSchema["~run"]({ value: value2 }, config2);
1286
- if (valueDataset.issues) {
1287
- const pathItem = {
1288
- type: "object",
1289
- origin: "value",
1290
- input,
1291
- key,
1292
- value: value2
1293
- };
1294
- for (const issue of valueDataset.issues) {
1295
- if (issue.path) issue.path.unshift(pathItem);
1296
- else issue.path = [pathItem];
1297
- dataset.issues?.push(issue);
1298
- }
1299
- if (!dataset.issues) dataset.issues = valueDataset.issues;
1300
- if (config2.abortEarly) {
1301
- dataset.typed = false;
1302
- break;
1303
- }
1304
- }
1305
- if (!valueDataset.typed) dataset.typed = false;
1306
- dataset.value[key] = valueDataset.value;
1307
- } else if (valueSchema.fallback !== void 0) dataset.value[key] = /* @__PURE__ */ getFallback(valueSchema);
1308
- else if (valueSchema.type !== "exact_optional" && valueSchema.type !== "optional" && valueSchema.type !== "nullish") {
1309
- _addIssue(this, "key", dataset, config2, {
1310
- input: void 0,
1311
- expected: `"${key}"`,
1312
- path: [{
1313
- type: "object",
1314
- origin: "key",
1315
- input,
1316
- key,
1317
- value: input[key]
1318
- }]
1319
- });
1320
- if (config2.abortEarly) break;
1321
- }
1322
- }
1323
- if (!dataset.issues || !config2.abortEarly) {
1324
- for (const key in input) if (!(key in this.entries)) {
1325
- _addIssue(this, "key", dataset, config2, {
1326
- input: key,
1327
- expected: "never",
1328
- path: [{
1329
- type: "object",
1330
- origin: "key",
1331
- input,
1332
- key,
1333
- value: input[key]
1334
- }]
1335
- });
1336
- break;
1337
- }
1338
- }
1339
- } else _addIssue(this, "type", dataset, config2);
1340
- return dataset;
1341
- }
1342
- };
1343
- }
1344
- /* @__NO_SIDE_EFFECTS__ */
1345
- function string(message2) {
1346
- return {
1347
- kind: "schema",
1348
- type: "string",
1349
- reference: string,
1350
- expects: "string",
1351
- async: false,
1352
- message: message2,
1353
- get "~standard"() {
1354
- return /* @__PURE__ */ _getStandardProps(this);
1355
- },
1356
- "~run"(dataset, config2) {
1357
- if (typeof dataset.value === "string") dataset.typed = true;
1358
- else _addIssue(this, "type", dataset, config2);
1359
- return dataset;
1360
- }
1361
- };
1362
- }
1363
- /* @__NO_SIDE_EFFECTS__ */
1364
- function tuple(items, message2) {
1365
- return {
1366
- kind: "schema",
1367
- type: "tuple",
1368
- reference: tuple,
1369
- expects: "Array",
1370
- async: false,
1371
- items,
1372
- message: message2,
1373
- get "~standard"() {
1374
- return /* @__PURE__ */ _getStandardProps(this);
1375
- },
1376
- "~run"(dataset, config2) {
1377
- const input = dataset.value;
1378
- if (Array.isArray(input)) {
1379
- dataset.typed = true;
1380
- dataset.value = [];
1381
- for (let key = 0; key < this.items.length; key++) {
1382
- const value2 = input[key];
1383
- const itemDataset = this.items[key]["~run"]({ value: value2 }, config2);
1384
- if (itemDataset.issues) {
1385
- const pathItem = {
1386
- type: "array",
1387
- origin: "value",
1388
- input,
1389
- key,
1390
- value: value2
1391
- };
1392
- for (const issue of itemDataset.issues) {
1393
- if (issue.path) issue.path.unshift(pathItem);
1394
- else issue.path = [pathItem];
1395
- dataset.issues?.push(issue);
1396
- }
1397
- if (!dataset.issues) dataset.issues = itemDataset.issues;
1398
- if (config2.abortEarly) {
1399
- dataset.typed = false;
1400
- break;
1401
- }
1402
- }
1403
- if (!itemDataset.typed) dataset.typed = false;
1404
- dataset.value.push(itemDataset.value);
1405
- }
1406
- } else _addIssue(this, "type", dataset, config2);
1407
- return dataset;
1408
- }
1409
- };
1410
- }
1411
- /* @__NO_SIDE_EFFECTS__ */
1412
- function _subIssues(datasets) {
1413
- let issues;
1414
- if (datasets) for (const dataset of datasets) if (issues) issues.push(...dataset.issues);
1415
- else issues = dataset.issues;
1416
- return issues;
1417
- }
1418
- /* @__NO_SIDE_EFFECTS__ */
1419
- function union(options, message2) {
1420
- return {
1421
- kind: "schema",
1422
- type: "union",
1423
- reference: union,
1424
- expects: /* @__PURE__ */ _joinExpects(options.map((option) => option.expects), "|"),
1425
- async: false,
1426
- options,
1427
- message: message2,
1428
- get "~standard"() {
1429
- return /* @__PURE__ */ _getStandardProps(this);
1430
- },
1431
- "~run"(dataset, config2) {
1432
- let validDataset;
1433
- let typedDatasets;
1434
- let untypedDatasets;
1435
- for (const schema of this.options) {
1436
- const optionDataset = schema["~run"]({ value: dataset.value }, config2);
1437
- if (optionDataset.typed) if (optionDataset.issues) if (typedDatasets) typedDatasets.push(optionDataset);
1438
- else typedDatasets = [optionDataset];
1439
- else {
1440
- validDataset = optionDataset;
1441
- break;
1442
- }
1443
- else if (untypedDatasets) untypedDatasets.push(optionDataset);
1444
- else untypedDatasets = [optionDataset];
1445
- }
1446
- if (validDataset) return validDataset;
1447
- if (typedDatasets) {
1448
- if (typedDatasets.length === 1) return typedDatasets[0];
1449
- _addIssue(this, "type", dataset, config2, { issues: /* @__PURE__ */ _subIssues(typedDatasets) });
1450
- dataset.typed = true;
1451
- } else if (untypedDatasets?.length === 1) return untypedDatasets[0];
1452
- else _addIssue(this, "type", dataset, config2, { issues: /* @__PURE__ */ _subIssues(untypedDatasets) });
1453
- return dataset;
1454
- }
1455
- };
1456
- }
1457
- /* @__NO_SIDE_EFFECTS__ */
1458
- function unionAsync(options, message2) {
1459
- return {
1460
- kind: "schema",
1461
- type: "union",
1462
- reference: unionAsync,
1463
- expects: /* @__PURE__ */ _joinExpects(options.map((option) => option.expects), "|"),
1464
- async: true,
1465
- options,
1466
- message: message2,
1467
- get "~standard"() {
1468
- return /* @__PURE__ */ _getStandardProps(this);
1469
- },
1470
- async "~run"(dataset, config2) {
1471
- let validDataset;
1472
- let typedDatasets;
1473
- let untypedDatasets;
1474
- for (const schema of this.options) {
1475
- const optionDataset = await schema["~run"]({ value: dataset.value }, config2);
1476
- if (optionDataset.typed) if (optionDataset.issues) if (typedDatasets) typedDatasets.push(optionDataset);
1477
- else typedDatasets = [optionDataset];
1478
- else {
1479
- validDataset = optionDataset;
1480
- break;
1481
- }
1482
- else if (untypedDatasets) untypedDatasets.push(optionDataset);
1483
- else untypedDatasets = [optionDataset];
1484
- }
1485
- if (validDataset) return validDataset;
1486
- if (typedDatasets) {
1487
- if (typedDatasets.length === 1) return typedDatasets[0];
1488
- _addIssue(this, "type", dataset, config2, { issues: /* @__PURE__ */ _subIssues(typedDatasets) });
1489
- dataset.typed = true;
1490
- } else if (untypedDatasets?.length === 1) return untypedDatasets[0];
1491
- else _addIssue(this, "type", dataset, config2, { issues: /* @__PURE__ */ _subIssues(untypedDatasets) });
1492
- return dataset;
1493
- }
1494
- };
1495
- }
1496
- /* @__NO_SIDE_EFFECTS__ */
1497
- function omit(schema, keys) {
1498
- const entries2 = { ...schema.entries };
1499
- for (const key of keys) delete entries2[key];
1500
- return {
1501
- ...schema,
1502
- entries: entries2,
1503
- get "~standard"() {
1504
- return /* @__PURE__ */ _getStandardProps(this);
1505
- }
1506
- };
1507
- }
1508
- /* @__NO_SIDE_EFFECTS__ */
1509
- function pipe(...pipe2) {
1510
- return {
1511
- ...pipe2[0],
1512
- pipe: pipe2,
1513
- get "~standard"() {
1514
- return /* @__PURE__ */ _getStandardProps(this);
1515
- },
1516
- "~run"(dataset, config2) {
1517
- for (const item of pipe2) if (item.kind !== "metadata") {
1518
- if (dataset.issues && (item.kind === "schema" || item.kind === "transformation")) {
1519
- dataset.typed = false;
1520
- break;
1521
- }
1522
- if (!dataset.issues || !config2.abortEarly && !config2.abortPipeEarly) dataset = item["~run"](dataset, config2);
1523
- }
1524
- return dataset;
1525
- }
1526
- };
1527
- }
1528
- /* @__NO_SIDE_EFFECTS__ */
1529
- function pipeAsync(...pipe2) {
1530
- return {
1531
- ...pipe2[0],
1532
- pipe: pipe2,
1533
- async: true,
1534
- get "~standard"() {
1535
- return /* @__PURE__ */ _getStandardProps(this);
1536
- },
1537
- async "~run"(dataset, config2) {
1538
- for (const item of pipe2) if (item.kind !== "metadata") {
1539
- if (dataset.issues && (item.kind === "schema" || item.kind === "transformation")) {
1540
- dataset.typed = false;
1541
- break;
1542
- }
1543
- if (!dataset.issues || !config2.abortEarly && !config2.abortPipeEarly) dataset = await item["~run"](dataset, config2);
1544
- }
1545
- return dataset;
1546
- }
1547
- };
1548
- }
1549
- /* @__NO_SIDE_EFFECTS__ */
1550
- function safeParse(schema, input, config2) {
1551
- const dataset = schema["~run"]({ value: input }, /* @__PURE__ */ getGlobalConfig(config2));
1552
- return {
1553
- typed: dataset.typed,
1554
- success: !dataset.issues,
1555
- output: dataset.value,
1556
- issues: dataset.issues
1557
- };
1558
- }
1559
-
1560
- //#endregion
1561
- //#region src/utils/validator.ts
1562
- const StringOrRegExpSchema = union([string(), instance(RegExp)]);
1563
- const LogLevelSchema = union([
1564
- literal("debug"),
1565
- literal("info"),
1566
- literal("warn")
1567
- ]);
1568
- const LogLevelOptionSchema = union([LogLevelSchema, literal("silent")]);
1569
- const LogLevelWithErrorSchema = union([LogLevelSchema, literal("error")]);
1570
- const RollupLogSchema = any();
1571
- const RollupLogWithStringSchema = union([RollupLogSchema, string()]);
1572
- const InputOptionSchema = union([
1573
- string(),
1574
- array(string()),
1575
- record(string(), string())
1576
- ]);
1577
- const ExternalSchema = union([
1578
- StringOrRegExpSchema,
1579
- array(StringOrRegExpSchema),
1580
- pipe(function_(), args(tuple([
1581
- string(),
1582
- optional(string()),
1583
- boolean()
1584
- ])), returns(nullish(boolean())))
1585
- ]);
1586
- const ModuleTypesSchema = record(string(), union([
1587
- literal("asset"),
1588
- literal("base64"),
1589
- literal("binary"),
1590
- literal("css"),
1591
- literal("dataurl"),
1592
- literal("empty"),
1593
- literal("js"),
1594
- literal("json"),
1595
- literal("jsx"),
1596
- literal("text"),
1597
- literal("ts"),
1598
- literal("tsx")
1599
- ]));
1600
- const JsxOptionsSchema = strictObject({
1601
- runtime: pipe(optional(union([literal("classic"), literal("automatic")])), description("Which runtime to use")),
1602
- development: pipe(optional(boolean()), description("Development specific information")),
1603
- throwIfNamespace: pipe(optional(string()), description("Toggles whether to throw an error when a tag name uses an XML namespace")),
1604
- importSource: pipe(optional(string()), description("Import the factory of element and fragment if mode is classic")),
1605
- pragma: pipe(optional(string()), description("Jsx element transformation")),
1606
- pragmaFlag: pipe(optional(string()), description("Jsx fragment transformation")),
1607
- refresh: pipe(optional(boolean()), description("Enable react fast refresh"))
1608
- });
1609
- const HelperModeSchema = union([literal("Runtime"), literal("External")]);
1610
- const DecoratorOptionSchema = object({
1611
- legacy: optional(boolean()),
1612
- emitDecoratorMetadata: optional(boolean())
1613
- });
1614
- const HelpersSchema = object({ mode: optional(HelperModeSchema) });
1615
- const RewriteImportExtensionsSchema = union([
1616
- literal("rewrite"),
1617
- literal("remove"),
1618
- boolean()
1619
- ]);
1620
- const TypescriptSchema = object({
1621
- jsxPragma: optional(string()),
1622
- jsxPragmaFrag: optional(string()),
1623
- onlyRemoveTypeImports: optional(boolean()),
1624
- allowNamespaces: optional(boolean()),
1625
- allowDeclareFields: optional(boolean()),
1626
- declaration: optional(object({
1627
- stripInternal: optional(boolean()),
1628
- sourcemap: optional(boolean())
1629
- })),
1630
- rewriteImportExtensions: optional(RewriteImportExtensionsSchema)
1631
- });
1632
- const AssumptionsSchema = object({
1633
- ignoreFunctionLength: optional(boolean()),
1634
- noDocumentAll: optional(boolean()),
1635
- objectRestNoSymbols: optional(boolean()),
1636
- pureGetters: optional(boolean()),
1637
- setPublicClassFields: optional(boolean())
1638
- });
1639
- const TransformOptionsSchema = object({
1640
- assumptions: optional(AssumptionsSchema),
1641
- typescript: optional(TypescriptSchema),
1642
- helpers: optional(HelpersSchema),
1643
- decorators: optional(DecoratorOptionSchema),
1644
- jsx: optional(JsxOptionsSchema),
1645
- target: pipe(optional(union([string(), array(string())])), description("The JavaScript target environment"))
1646
- });
1647
- const WatchOptionsSchema = strictObject({
1648
- chokidar: optional(never(`The "watch.chokidar" option is deprecated, please use "watch.notify" instead of it`)),
1649
- exclude: optional(union([StringOrRegExpSchema, array(StringOrRegExpSchema)])),
1650
- include: optional(union([StringOrRegExpSchema, array(StringOrRegExpSchema)])),
1651
- notify: pipe(optional(strictObject({
1652
- compareContents: optional(boolean()),
1653
- pollInterval: optional(number())
1654
- })), description("Notify options")),
1655
- skipWrite: pipe(optional(boolean()), description("Skip the bundle.write() step")),
1656
- buildDelay: pipe(optional(number()), description("Throttle watch rebuilds"))
1657
- });
1658
- const ChecksOptionsSchema = strictObject({
1659
- circularDependency: pipe(optional(boolean()), description("Whether to emit warning when detecting circular dependency")),
1660
- eval: pipe(optional(boolean()), description("Whether to emit warning when detecting eval")),
1661
- missingGlobalName: pipe(optional(boolean()), description("Whether to emit warning when detecting missing global name")),
1662
- missingNameOptionForIifeExport: pipe(optional(boolean()), description("Whether to emit warning when detecting missing name option for iife export")),
1663
- mixedExport: pipe(optional(boolean()), description("Whether to emit warning when detecting mixed export")),
1664
- unresolvedEntry: pipe(optional(boolean()), description("Whether to emit warning when detecting unresolved entry")),
1665
- unresolvedImport: pipe(optional(boolean()), description("Whether to emit warning when detecting unresolved import")),
1666
- filenameConflict: pipe(optional(boolean()), description("Whether to emit warning when detecting filename conflict")),
1667
- commonJsVariableInEsm: pipe(optional(boolean()), description("Whether to emit warning when detecting common js variable in esm")),
1668
- importIsUndefined: pipe(optional(boolean()), description("Whether to emit warning when detecting import is undefined")),
1669
- configurationFieldConflict: pipe(optional(boolean()), description("Whether to emit warning when detecting configuration field conflict"))
1670
- });
1671
- const MinifyOptionsSchema = strictObject({
1672
- mangle: optional(boolean()),
1673
- compress: optional(boolean()),
1674
- removeWhitespace: optional(boolean())
1675
- });
1676
- const ResolveOptionsSchema = strictObject({
1677
- alias: optional(record(string(), union([string(), array(string())]))),
1678
- aliasFields: optional(array(array(string()))),
1679
- conditionNames: optional(array(string())),
1680
- extensionAlias: optional(record(string(), array(string()))),
1681
- exportsFields: optional(array(array(string()))),
1682
- extensions: optional(array(string())),
1683
- mainFields: optional(array(string())),
1684
- mainFiles: optional(array(string())),
1685
- modules: optional(array(string())),
1686
- symlinks: optional(boolean()),
1687
- tsconfigFilename: optional(string())
1688
- });
1689
- const TreeshakingOptionsSchema = union([boolean(), looseObject({
1690
- annotations: optional(boolean()),
1691
- manualPureFunctions: optional(array(string())),
1692
- unknownGlobalSideEffects: optional(boolean())
1693
- })]);
1694
- const OnLogSchema = pipe(function_(), args(tuple([
1695
- LogLevelSchema,
1696
- RollupLogSchema,
1697
- pipe(function_(), args(tuple([LogLevelWithErrorSchema, RollupLogWithStringSchema])))
1698
- ])));
1699
- const OnwarnSchema = pipe(function_(), args(tuple([RollupLogSchema, pipe(function_(), args(tuple([union([RollupLogWithStringSchema, pipe(function_(), returns(RollupLogWithStringSchema))])])))])));
1700
- const HmrSchema = union([boolean(), strictObject({
1701
- port: optional(number()),
1702
- host: optional(string()),
1703
- implement: optional(string())
1704
- })]);
1705
- const InputOptionsSchema = strictObject({
1706
- input: optional(InputOptionSchema),
1707
- plugins: optional(custom(() => true)),
1708
- external: optional(ExternalSchema),
1709
- resolve: optional(ResolveOptionsSchema),
1710
- cwd: pipe(optional(string()), description("Current working directory")),
1711
- platform: pipe(optional(union([
1712
- literal("browser"),
1713
- literal("neutral"),
1714
- literal("node")
1715
- ])), description(`Platform for which the code should be generated (node, ${colors.underline("browser")}, neutral)`)),
1716
- shimMissingExports: pipe(optional(boolean()), description("Create shim variables for missing exports")),
1717
- treeshake: optional(TreeshakingOptionsSchema),
1718
- logLevel: pipe(optional(LogLevelOptionSchema), description(`Log level (${colors.dim("silent")}, ${colors.underline(colors.gray("info"))}, debug, ${colors.yellow("warn")})`)),
1719
- onLog: optional(OnLogSchema),
1720
- onwarn: optional(OnwarnSchema),
1721
- moduleTypes: pipe(optional(ModuleTypesSchema), description("Module types for customized extensions")),
1722
- experimental: optional(strictObject({
1723
- disableLiveBindings: optional(boolean()),
1724
- enableComposingJsPlugins: optional(boolean()),
1725
- resolveNewUrlToAsset: optional(boolean()),
1726
- strictExecutionOrder: optional(boolean()),
1727
- hmr: optional(HmrSchema),
1728
- attachDebugInfo: optional(boolean())
1729
- })),
1730
- define: pipe(optional(record(string(), string())), description("Define global variables")),
1731
- inject: optional(record(string(), union([string(), tuple([string(), string()])]))),
1732
- profilerNames: optional(boolean()),
1733
- jsx: pipe(optional(union([
1734
- literal(false),
1735
- literal("react"),
1736
- literal("react-jsx"),
1737
- literal("preserve")
1738
- ])), description("Jsx options preset")),
1739
- transform: optional(TransformOptionsSchema),
1740
- watch: optional(union([WatchOptionsSchema, literal(false)])),
1741
- dropLabels: pipe(optional(array(string())), description("Remove labeled statements with these label names")),
1742
- checks: optional(ChecksOptionsSchema),
1743
- keepNames: pipe(optional(boolean()), description("Keep function/class name")),
1744
- debug: pipe(optional(object({ sessionId: pipe(optional(string()), description("Used to name the build.")) })), description("Enable debug mode. Emit debug information to disk. This might slow down the build process significantly."))
1745
- });
1746
- const InputCliOverrideSchema = strictObject({
1747
- input: pipe(optional(array(string())), description("Entry file")),
1748
- external: pipe(optional(array(string())), description("Comma-separated list of module ids to exclude from the bundle `<module-id>,...`")),
1749
- inject: pipe(optional(record(string(), string())), description("Inject import statements on demand")),
1750
- treeshake: pipe(optional(boolean()), description("enable treeshaking"))
1751
- });
1752
- const InputCliOptionsSchema = omit(strictObject({
1753
- ...InputOptionsSchema.entries,
1754
- ...InputCliOverrideSchema.entries
1755
- }), [
1756
- "plugins",
1757
- "onwarn",
1758
- "onLog",
1759
- "resolve",
1760
- "experimental",
1761
- "profilerNames",
1762
- "watch"
1763
- ]);
1764
- const ModuleFormatSchema = union([
1765
- literal("es"),
1766
- literal("cjs"),
1767
- literal("esm"),
1768
- literal("module"),
1769
- literal("commonjs"),
1770
- literal("iife"),
1771
- literal("umd")
1772
- ]);
1773
- const AddonFunctionSchema = pipe(function_(), args(tuple([custom(() => true)])), returnsAsync(unionAsync([string(), pipeAsync(promise(), awaitAsync(), string())])));
1774
- const ChunkFileNamesSchema = union([string(), pipe(function_(), args(tuple([custom(() => true)])), returns(string()))]);
1775
- const AssetFileNamesSchema = union([string(), pipe(function_(), args(tuple([custom(() => true)])), returns(string()))]);
1776
- const SanitizeFileNameSchema = union([boolean(), pipe(function_(), args(tuple([string()])), returns(string()))]);
1777
- const GlobalsFunctionSchema = pipe(function_(), args(tuple([string()])), returns(string()));
1778
- const AdvancedChunksSchema = strictObject({
1779
- minSize: optional(number()),
1780
- maxSize: optional(number()),
1781
- minModuleSize: optional(number()),
1782
- maxModuleSize: optional(number()),
1783
- minShareCount: optional(number()),
1784
- groups: optional(array(strictObject({
1785
- name: string(),
1786
- test: optional(union([string(), instance(RegExp)])),
1787
- priority: optional(number()),
1788
- minSize: optional(number()),
1789
- minShareCount: optional(number()),
1790
- maxSize: optional(number()),
1791
- minModuleSize: optional(number()),
1792
- maxModuleSize: optional(number())
1793
- })))
1794
- });
1795
- const OutputOptionsSchema = strictObject({
1796
- dir: pipe(optional(string()), description("Output directory, defaults to `dist` if `file` is not set")),
1797
- file: pipe(optional(string()), description("Single output file")),
1798
- exports: pipe(optional(union([
1799
- literal("auto"),
1800
- literal("named"),
1801
- literal("default"),
1802
- literal("none")
1803
- ])), description(`Specify a export mode (${colors.underline("auto")}, named, default, none)`)),
1804
- hashCharacters: pipe(optional(union([
1805
- literal("base64"),
1806
- literal("base36"),
1807
- literal("hex")
1808
- ])), description("Use the specified character set for file hashes")),
1809
- format: pipe(optional(ModuleFormatSchema), description(`Output format of the generated bundle (supports ${colors.underline("esm")}, cjs, and iife)`)),
1810
- sourcemap: pipe(optional(union([
1811
- boolean(),
1812
- literal("inline"),
1813
- literal("hidden")
1814
- ])), description(`Generate sourcemap (\`-s inline\` for inline, or ${colors.bold("pass the `-s` on the last argument if you want to generate `.map` file")})`)),
1815
- sourcemapDebugIds: pipe(optional(boolean()), description("Inject sourcemap debug IDs")),
1816
- sourcemapIgnoreList: optional(union([boolean(), custom(() => true)])),
1817
- sourcemapPathTransform: optional(custom(() => true)),
1818
- banner: optional(union([string(), AddonFunctionSchema])),
1819
- footer: optional(union([string(), AddonFunctionSchema])),
1820
- intro: optional(union([string(), AddonFunctionSchema])),
1821
- outro: optional(union([string(), AddonFunctionSchema])),
1822
- extend: pipe(optional(boolean()), description("Extend global variable defined by name in IIFE / UMD formats")),
1823
- esModule: optional(union([boolean(), literal("if-default-prop")])),
1824
- assetFileNames: optional(AssetFileNamesSchema),
1825
- entryFileNames: optional(ChunkFileNamesSchema),
1826
- chunkFileNames: optional(ChunkFileNamesSchema),
1827
- cssEntryFileNames: optional(ChunkFileNamesSchema),
1828
- cssChunkFileNames: optional(ChunkFileNamesSchema),
1829
- sanitizeFileName: optional(SanitizeFileNameSchema),
1830
- minify: pipe(optional(union([
1831
- boolean(),
1832
- string("dce-only"),
1833
- MinifyOptionsSchema
1834
- ])), description("Minify the bundled file")),
1835
- name: pipe(optional(string()), description("Name for UMD / IIFE format outputs")),
1836
- globals: pipe(optional(union([record(string(), string()), GlobalsFunctionSchema])), description("Global variable of UMD / IIFE dependencies (syntax: `key=value`)")),
1837
- externalLiveBindings: pipe(optional(boolean()), description("external live bindings")),
1838
- inlineDynamicImports: pipe(optional(boolean()), description("Inline dynamic imports")),
1839
- manualChunks: optional(never("manualChunks is not supported. Please use advancedChunks instead")),
1840
- advancedChunks: optional(AdvancedChunksSchema),
1841
- legalComments: pipe(optional(union([literal("none"), literal("inline")])), description("Control comments in the output")),
1842
- plugins: optional(custom(() => true)),
1843
- polyfillRequire: pipe(optional(boolean()), description("Disable require polyfill injection")),
1844
- hoistTransitiveImports: optional(custom((input) => {
1845
- if (input) return false;
1846
- return true;
1847
- }, () => `The 'true' value is not supported`)),
1848
- preserveModules: pipe(optional(boolean()), description("Preserve module structure")),
1849
- preserveModulesRoot: pipe(optional(string()), description("Put preserved modules under this path at root level")),
1850
- virtualDirname: optional(string())
1851
- });
1852
- const getAddonDescription = (placement, wrapper) => {
1853
- return `Code to insert the ${colors.bold(placement)} of the bundled file (${colors.bold(wrapper)} the wrapper function)`;
1854
- };
1855
- const OutputCliOverrideSchema = strictObject({
1856
- assetFileNames: pipe(optional(string()), description("Name pattern for asset files")),
1857
- entryFileNames: pipe(optional(string()), description("Name pattern for emitted entry chunks")),
1858
- chunkFileNames: pipe(optional(string()), description("Name pattern for emitted secondary chunks")),
1859
- cssEntryFileNames: pipe(optional(string()), description("Name pattern for emitted css entry chunks")),
1860
- cssChunkFileNames: pipe(optional(string()), description("Name pattern for emitted css secondary chunks")),
1861
- sanitizeFileName: pipe(optional(boolean()), description("Sanitize file name")),
1862
- banner: pipe(optional(string()), description(getAddonDescription("top", "outside"))),
1863
- footer: pipe(optional(string()), description(getAddonDescription("bottom", "outside"))),
1864
- intro: pipe(optional(string()), description(getAddonDescription("top", "inside"))),
1865
- outro: pipe(optional(string()), description(getAddonDescription("bottom", "inside"))),
1866
- esModule: pipe(optional(boolean()), description("Always generate `__esModule` marks in non-ESM formats, defaults to `if-default-prop` (use `--no-esModule` to always disable)")),
1867
- globals: pipe(optional(record(string(), string())), description("Global variable of UMD / IIFE dependencies (syntax: `key=value`)")),
1868
- advancedChunks: pipe(optional(strictObject({
1869
- minSize: pipe(optional(number()), description("Minimum size of the chunk")),
1870
- minShareCount: pipe(optional(number()), description("Minimum share count of the chunk"))
1871
- })), description("Global variable of UMD / IIFE dependencies (syntax: `key=value`)")),
1872
- minify: pipe(optional(boolean()), description("Minify the bundled file"))
1873
- });
1874
- const OutputCliOptionsSchema = omit(strictObject({
1875
- ...OutputOptionsSchema.entries,
1876
- ...OutputCliOverrideSchema.entries
1877
- }), [
1878
- "sourcemapIgnoreList",
1879
- "sourcemapPathTransform",
1880
- "plugins",
1881
- "hoistTransitiveImports"
1882
- ]);
1883
- const CliOptionsSchema = strictObject({
1884
- config: pipe(optional(union([string(), boolean()])), description("Path to the config file (default: `rolldown.config.js`)")),
1885
- help: pipe(optional(boolean()), description("Show help")),
1886
- version: pipe(optional(boolean()), description("Show version number")),
1887
- watch: pipe(optional(boolean()), description("Watch files in bundle and rebuild on changes")),
1888
- ...InputCliOptionsSchema.entries,
1889
- ...OutputCliOptionsSchema.entries
1890
- });
1891
- const inputHelperMsgRecord = { output: { ignored: true } };
1892
- const outputHelperMsgRecord = {};
1893
- function validateOption(key, options) {
1894
- if (globalThis.process?.env?.ROLLUP_TEST) return;
1895
- let parsed = safeParse(key === "input" ? InputOptionsSchema : OutputOptionsSchema, options);
1896
- if (!parsed.success) {
1897
- const errors = parsed.issues.map((issue) => {
1898
- const issuePaths = issue.path.map((path$1) => path$1.key);
1899
- let issueMsg = issue.message;
1900
- if (issue.type === "union") {
1901
- const subIssue = issue.issues?.find((i$1) => !(i$1.type !== issue.received && i$1.input === issue.input));
1902
- if (subIssue) {
1903
- if (subIssue.path) issuePaths.push(subIssue.path.map((path$1) => path$1.key));
1904
- issueMsg = subIssue.message;
1905
- }
1906
- }
1907
- const stringPath = issuePaths.join(".");
1908
- const helper = key === "input" ? inputHelperMsgRecord[stringPath] : outputHelperMsgRecord[stringPath];
1909
- if (helper && helper.ignored) return "";
1910
- return `- For the "${stringPath}". ${issueMsg}. ${helper ? helper.msg : ""}`;
1911
- }).filter(Boolean);
1912
- if (errors.length) console.warn(`Warning validate ${key} options.\n` + errors.join("\n"));
1913
- }
1914
- }
1915
-
1916
- //#endregion
1917
- //#region src/constants/plugin-context.ts
1918
- /**
1919
- * If Composed plugins call `this.resolve` with `skipSelf: true`, the composed plugins will be skipped as a whole.
1920
- * To prevent that, we use this symbol to store the actual caller of `this.resolve` with `skipSelf: true`. And we
1921
- * will modify the skipSelf option to `false` and use this symbol to skip the caller itself in the composed plugins
1922
- * internally.
1923
- */
1924
- const SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF = Symbol("plugin-context-resolve-caller");
1925
-
1926
- //#endregion
1927
- //#region src/options/normalized-input-options.ts
1928
- var NormalizedInputOptionsImpl = class {
1929
- inner;
1930
- constructor(inner, onLog) {
1931
- this.onLog = onLog;
1932
- this.inner = inner;
1933
- }
1934
- get shimMissingExports() {
1935
- return this.inner.shimMissingExports;
1936
- }
1937
- get input() {
1938
- return this.inner.input;
1939
- }
1940
- get cwd() {
1941
- return this.inner.cwd ?? void 0;
1942
- }
1943
- get platform() {
1944
- return this.inner.platform;
1945
- }
1946
- };
1947
-
1948
- //#endregion
1949
- //#region src/types/sourcemap.ts
1950
- function bindingifySourcemap(map) {
1951
- if (map == null) return;
1952
- return { inner: typeof map === "string" ? map : {
1953
- file: map.file ?? void 0,
1954
- mappings: map.mappings,
1955
- sourceRoot: "sourceRoot" in map ? map.sourceRoot ?? void 0 : void 0,
1956
- sources: map.sources?.map((s) => s ?? void 0),
1957
- sourcesContent: map.sourcesContent?.map((s) => s ?? void 0),
1958
- names: map.names,
1959
- x_google_ignoreList: map.x_google_ignoreList,
1960
- debugId: "debugId" in map ? map.debugId : void 0
1961
- } };
1962
- }
1963
-
1964
- //#endregion
1965
- //#region src/utils/error.ts
1966
- function normalizeErrors(rawErrors) {
1967
- const errors = rawErrors.map((e) => e instanceof Error ? e : Object.assign(new Error(), {
1968
- kind: e.kind,
1969
- message: e.message,
1970
- stack: void 0
1971
- }));
1972
- let summary = `Build failed with ${errors.length} error${errors.length < 2 ? "" : "s"}:\n`;
1973
- for (let i$1 = 0; i$1 < errors.length; i$1++) {
1974
- summary += "\n";
1975
- if (i$1 >= 5) {
1976
- summary += "...";
1977
- break;
1978
- }
1979
- summary += getErrorMessage(errors[i$1]);
1980
- }
1981
- const wrapper = new Error(summary);
1982
- Object.defineProperty(wrapper, "errors", {
1983
- configurable: true,
1984
- enumerable: true,
1985
- get: () => errors,
1986
- set: (value) => Object.defineProperty(wrapper, "errors", {
1987
- configurable: true,
1988
- enumerable: true,
1989
- value
1990
- })
1991
- });
1992
- return wrapper;
1993
- }
1994
- function getErrorMessage(e) {
1995
- if (Object.hasOwn(e, "kind")) return e.message;
1996
- let s = "";
1997
- if (e.plugin) s += `[plugin ${e.plugin}]`;
1998
- const id$1 = e.id ?? e.loc?.file;
1999
- if (id$1) {
2000
- s += " " + id$1;
2001
- if (e.loc) s += `:${e.loc.line}:${e.loc.column}`;
2002
- }
2003
- if (s) s += "\n";
2004
- const message = `${e.name ?? "Error"}: ${e.message}`;
2005
- s += message;
2006
- if (e.frame) s = joinNewLine(s, e.frame);
2007
- if (e.stack) s = joinNewLine(s, e.stack.replace(message, ""));
2008
- return s;
2009
- }
2010
- function joinNewLine(s1, s2) {
2011
- return s1.replace(/\n+$/, "") + "\n" + s2.replace(/^\n+/, "");
2012
- }
2013
-
2014
- //#endregion
2015
- //#region src/utils/transform-module-info.ts
2016
- function transformModuleInfo(info, option) {
2017
- return {
2018
- get ast() {
2019
- return unsupported("ModuleInfo#ast");
2020
- },
2021
- get code() {
2022
- return info.code;
2023
- },
2024
- id: info.id,
2025
- importers: info.importers,
2026
- dynamicImporters: info.dynamicImporters,
2027
- importedIds: info.importedIds,
2028
- dynamicallyImportedIds: info.dynamicallyImportedIds,
2029
- exports: info.exports,
2030
- isEntry: info.isEntry,
2031
- ...option
2032
- };
2033
- }
2034
-
2035
- //#endregion
2036
- //#region src/utils/transform-side-effects.ts
2037
- function bindingifySideEffects(sideEffects) {
2038
- switch (sideEffects) {
2039
- case true: return BindingHookSideEffects.True;
2040
- case false: return BindingHookSideEffects.False;
2041
- case "no-treeshake": return BindingHookSideEffects.NoTreeshake;
2042
- case null:
2043
- case void 0: return void 0;
2044
- default: throw new Error(`Unexpected side effects: ${sideEffects}`);
2045
- }
2046
- }
2047
-
2048
- //#endregion
2049
- //#region src/utils/transform-sourcemap.ts
2050
- function isEmptySourcemapFiled(array$1) {
2051
- if (!array$1) return true;
2052
- if (array$1.length === 0 || !array$1[0]) return true;
2053
- return false;
2054
- }
2055
- function normalizeTransformHookSourcemap(id$1, originalCode, rawMap) {
2056
- if (!rawMap) return;
2057
- let map = typeof rawMap === "object" ? rawMap : JSON.parse(rawMap);
2058
- if (isEmptySourcemapFiled(map.sourcesContent)) map.sourcesContent = [originalCode];
2059
- if (isEmptySourcemapFiled(map.sources) || map.sources && map.sources.length === 1 && map.sources[0] !== id$1) map.sources = [id$1];
2060
- return map;
2061
- }
2062
-
2063
- //#endregion
2064
- //#region ../pluginutils/dist/index.js
2065
- var And = class {
2066
- kind;
2067
- args;
2068
- constructor(...args$1) {
2069
- if (args$1.length === 0) throw new Error("`And` expects at least one operand");
2070
- this.args = args$1;
2071
- this.kind = "and";
2072
- }
2073
- };
2074
- var Or = class {
2075
- kind;
2076
- args;
2077
- constructor(...args$1) {
2078
- if (args$1.length === 0) throw new Error("`Or` expects at least one operand");
2079
- this.args = args$1;
2080
- this.kind = "or";
2081
- }
2082
- };
2083
- var Id = class {
2084
- kind;
2085
- pattern;
2086
- params;
2087
- constructor(pattern, params) {
2088
- this.pattern = pattern;
2089
- this.kind = "id";
2090
- this.params = params ?? { cleanUrl: false };
2091
- }
2092
- };
2093
- var ModuleType = class {
2094
- kind;
2095
- pattern;
2096
- constructor(pattern) {
2097
- this.pattern = pattern;
2098
- this.kind = "moduleType";
2099
- }
2100
- };
2101
- var Code = class {
2102
- kind;
2103
- pattern;
2104
- constructor(expr) {
2105
- this.pattern = expr;
2106
- this.kind = "code";
2107
- }
2108
- };
2109
- var Include = class {
2110
- kind;
2111
- expr;
2112
- constructor(expr) {
2113
- this.expr = expr;
2114
- this.kind = "include";
2115
- }
2116
- };
2117
- var Exclude = class {
2118
- kind;
2119
- expr;
2120
- constructor(expr) {
2121
- this.expr = expr;
2122
- this.kind = "exclude";
2123
- }
2124
- };
2125
- function and(...args$1) {
2126
- return new And(...args$1);
2127
- }
2128
- function or(...args$1) {
2129
- return new Or(...args$1);
2130
- }
2131
- function id(pattern, params) {
2132
- return new Id(pattern, params);
2133
- }
2134
- function moduleType(pattern) {
2135
- return new ModuleType(pattern);
2136
- }
2137
- function code(pattern) {
2138
- return new Code(pattern);
2139
- }
2140
- function include(expr) {
2141
- return new Include(expr);
2142
- }
2143
- function exclude(expr) {
2144
- return new Exclude(expr);
2145
- }
2146
-
2147
- //#endregion
2148
- //#region ../../node_modules/.pnpm/remeda@2.21.6/node_modules/remeda/dist/chunk-D6FCK2GA.js
2149
- function u$1(o, n, a) {
2150
- let t$1 = (r) => o(r, ...n);
2151
- return a === void 0 ? t$1 : Object.assign(t$1, {
2152
- lazy: a,
2153
- lazyArgs: n
2154
- });
2155
- }
2156
-
2157
- //#endregion
2158
- //#region ../../node_modules/.pnpm/remeda@2.21.6/node_modules/remeda/dist/chunk-WIMGWYZL.js
2159
- function u(r, n, o) {
2160
- let a = r.length - n.length;
2161
- if (a === 0) return r(...n);
2162
- if (a === 1) return u$1(r, n, o);
2163
- throw new Error("Wrong number of arguments");
2164
- }
2165
-
2166
- //#endregion
2167
- //#region ../../node_modules/.pnpm/remeda@2.21.6/node_modules/remeda/dist/chunk-3IFJP4R5.js
2168
- function d(...r) {
2169
- return u(i, r);
2170
- }
2171
- var i = (r, t$1) => {
2172
- let a = [[], []];
2173
- for (let [o, e] of r.entries()) t$1(e, o, r) ? a[0].push(e) : a[1].push(e);
2174
- return a;
2175
- };
2176
-
2177
- //#endregion
2178
- //#region ../../node_modules/.pnpm/remeda@2.21.6/node_modules/remeda/dist/chunk-5NQBDF4H.js
2179
- function t(...n) {
2180
- return u(Object.keys, n);
2181
- }
2182
-
2183
- //#endregion
2184
- //#region src/plugin/bindingify-hook-filter.ts
2185
- function generalHookFilterMatcherToFilterExprs(matcher, stringKind) {
2186
- if (typeof matcher === "string" || matcher instanceof RegExp) return [include(generateAtomMatcher(stringKind, matcher))];
2187
- if (Array.isArray(matcher)) return matcher.map((m) => include(generateAtomMatcher(stringKind, m)));
2188
- let ret = [];
2189
- if (matcher.exclude) ret.push(...arraify(matcher.exclude).map((m) => exclude(generateAtomMatcher(stringKind, m))));
2190
- if (matcher.include) ret.push(...arraify(matcher.include).map((m) => include(generateAtomMatcher(stringKind, m))));
2191
- return ret;
2192
- }
2193
- function generateAtomMatcher(kind, matcher) {
2194
- return kind === "code" ? code(matcher) : id(matcher);
2195
- }
2196
- function transformFilterMatcherToFilterExprs(filterOption) {
2197
- if (!filterOption) return void 0;
2198
- if (Array.isArray(filterOption)) return filterOption;
2199
- const { id: id$1, code: code$1, moduleType: moduleType$1 } = filterOption;
2200
- let ret = [];
2201
- let idIncludes = [];
2202
- let idExcludes = [];
2203
- let codeIncludes = [];
2204
- let codeExcludes = [];
2205
- if (id$1) [idIncludes, idExcludes] = d(generalHookFilterMatcherToFilterExprs(id$1, "id") ?? [], (m) => m.kind === "include");
2206
- if (code$1) [codeIncludes, codeExcludes] = d(generalHookFilterMatcherToFilterExprs(code$1, "code") ?? [], (m) => m.kind === "include");
2207
- ret.push(...idExcludes);
2208
- ret.push(...codeExcludes);
2209
- let andExprList = [];
2210
- if (moduleType$1) {
2211
- let moduleTypes = Array.isArray(moduleType$1) ? moduleType$1 : moduleType$1.include ?? [];
2212
- andExprList.push(or(...moduleTypes.map((m) => moduleType(m))));
2213
- }
2214
- if (idIncludes.length) andExprList.push(or(...idIncludes.map((item) => item.expr)));
2215
- if (codeIncludes.length) andExprList.push(or(...codeIncludes.map((item) => item.expr)));
2216
- if (andExprList.length) ret.push(include(and(...andExprList)));
2217
- return ret;
2218
- }
2219
- function bindingifyGeneralHookFilter(stringKind, pattern) {
2220
- let filterExprs = generalHookFilterMatcherToFilterExprs(pattern, stringKind);
2221
- let ret = [];
2222
- if (filterExprs) ret = filterExprs.map(bindingifyFilterExpr);
2223
- return ret.length > 0 ? { value: ret } : void 0;
2224
- }
2225
- function bindingifyFilterExpr(expr) {
2226
- let list = [];
2227
- bindingifyFilterExprImpl(expr, list);
2228
- return list;
2229
- }
2230
- function bindingifyFilterExprImpl(expr, list) {
2231
- switch (expr.kind) {
2232
- case "and": {
2233
- let args$1 = expr.args;
2234
- for (let i$1 = args$1.length - 1; i$1 >= 0; i$1--) bindingifyFilterExprImpl(args$1[i$1], list);
2235
- list.push({
2236
- kind: "And",
2237
- payload: args$1.length
2238
- });
2239
- break;
2240
- }
2241
- case "or": {
2242
- let args$1 = expr.args;
2243
- for (let i$1 = args$1.length - 1; i$1 >= 0; i$1--) bindingifyFilterExprImpl(args$1[i$1], list);
2244
- list.push({
2245
- kind: "Or",
2246
- payload: args$1.length
2247
- });
2248
- break;
2249
- }
2250
- case "not": {
2251
- bindingifyFilterExprImpl(expr.expr, list);
2252
- list.push({ kind: "Not" });
2253
- break;
2254
- }
2255
- case "id": {
2256
- list.push({
2257
- kind: "Id",
2258
- payload: expr.pattern
2259
- });
2260
- if (expr.params.cleanUrl) list.push({ kind: "CleanUrl" });
2261
- break;
2262
- }
2263
- case "moduleType": {
2264
- list.push({
2265
- kind: "ModuleType",
2266
- payload: expr.pattern
2267
- });
2268
- break;
2269
- }
2270
- case "code": {
2271
- list.push({
2272
- kind: "Code",
2273
- payload: expr.pattern
2274
- });
2275
- break;
2276
- }
2277
- case "include": {
2278
- bindingifyFilterExprImpl(expr.expr, list);
2279
- list.push({ kind: "Include" });
2280
- break;
2281
- }
2282
- case "exclude": {
2283
- bindingifyFilterExprImpl(expr.expr, list);
2284
- list.push({ kind: "Exclude" });
2285
- break;
2286
- }
2287
- case "query": {
2288
- list.push({
2289
- kind: "QueryKey",
2290
- payload: expr.key
2291
- });
2292
- list.push({
2293
- kind: "QueryValue",
2294
- payload: expr.pattern
2295
- });
2296
- break;
2297
- }
2298
- default: throw new Error(`Unknown filter expression: ${expr}`);
2299
- }
2300
- }
2301
- function bindingifyResolveIdFilter(filterOption) {
2302
- if (!filterOption) return void 0;
2303
- if (Array.isArray(filterOption)) return { value: filterOption.map(bindingifyFilterExpr) };
2304
- return filterOption.id ? bindingifyGeneralHookFilter("id", filterOption.id) : void 0;
2305
- }
2306
- function bindingifyLoadFilter(filterOption) {
2307
- if (!filterOption) return void 0;
2308
- if (Array.isArray(filterOption)) return { value: filterOption.map(bindingifyFilterExpr) };
2309
- return filterOption.id ? bindingifyGeneralHookFilter("id", filterOption.id) : void 0;
2310
- }
2311
- function bindingifyTransformFilter(filterOption) {
2312
- if (!filterOption) return void 0;
2313
- let filterExprs = transformFilterMatcherToFilterExprs(filterOption);
2314
- let ret = [];
2315
- if (filterExprs) ret = filterExprs.map(bindingifyFilterExpr);
2316
- return { value: ret.length > 0 ? ret : void 0 };
2317
- }
2318
- function bindingifyRenderChunkFilter(filterOption) {
2319
- if (!filterOption) return void 0;
2320
- if (Array.isArray(filterOption)) return { value: filterOption.map(bindingifyFilterExpr) };
2321
- return filterOption.code ? bindingifyGeneralHookFilter("code", filterOption.code) : void 0;
2322
- }
2323
-
2324
- //#endregion
2325
- //#region src/plugin/bindingify-plugin-hook-meta.ts
2326
- function bindingifyPluginHookMeta(options) {
2327
- return { order: bindingPluginOrder(options.order) };
2328
- }
2329
- function bindingPluginOrder(order) {
2330
- switch (order) {
2331
- case "post": return BindingPluginOrder.Post;
2332
- case "pre": return BindingPluginOrder.Pre;
2333
- case null:
2334
- case void 0: return void 0;
2335
- default: throw new Error(`Unknown plugin order: ${order}`);
2336
- }
2337
- }
2338
-
2339
- //#endregion
2340
- //#region ../../node_modules/.pnpm/oxc-parser@0.72.0/node_modules/oxc-parser/wrap.mjs
2341
- function wrap$1(result) {
2342
- let program, module, comments, errors;
2343
- return {
2344
- get program() {
2345
- if (!program) program = jsonParseAst(result.program);
2346
- return program;
2347
- },
2348
- get module() {
2349
- if (!module) module = result.module;
2350
- return module;
2351
- },
2352
- get comments() {
2353
- if (!comments) comments = result.comments;
2354
- return comments;
2355
- },
2356
- get errors() {
2357
- if (!errors) errors = result.errors;
2358
- return errors;
2359
- }
2360
- };
2361
- }
2362
- function jsonParseAst(programJson) {
2363
- const { node: program, fixes } = JSON.parse(programJson);
2364
- for (const fixPath of fixes) applyFix(program, fixPath);
2365
- return program;
2366
- }
2367
- function applyFix(program, fixPath) {
2368
- let node = program;
2369
- for (const key of fixPath) node = node[key];
2370
- if (node.bigint) node.value = BigInt(node.bigint);
2371
- else try {
2372
- node.value = RegExp(node.regex.pattern, node.regex.flags);
2373
- } catch (_err) {}
2374
- }
2375
-
2376
- //#endregion
2377
- //#region src/parse-ast-index.ts
2378
- function wrap(result, sourceText) {
2379
- result = wrap$1(result);
2380
- if (result.errors.length > 0) return normalizeParseError(sourceText, result.errors);
2381
- return result.program;
2382
- }
2383
- function normalizeParseError(sourceText, errors) {
2384
- let message = `Parse failed with ${errors.length} error${errors.length < 2 ? "" : "s"}:\n`;
2385
- for (let i$1 = 0; i$1 < errors.length; i$1++) {
2386
- if (i$1 >= 5) {
2387
- message += "\n...";
2388
- break;
2389
- }
2390
- const e = errors[i$1];
2391
- message += e.message + "\n" + e.labels.map((label) => {
2392
- const location = locate(sourceText, label.start, { offsetLine: 1 });
2393
- if (!location) return;
2394
- return getCodeFrame(sourceText, location.line, location.column);
2395
- }).filter(Boolean).join("\n");
2396
- }
2397
- return error(logParseError(message));
2398
- }
2399
- const defaultParserOptions = {
2400
- lang: "js",
2401
- preserveParens: false
2402
- };
2403
- function parseAst(sourceText, options, filename) {
2404
- return wrap(parseSync(filename ?? "file.js", sourceText, {
2405
- ...defaultParserOptions,
2406
- ...options
2407
- }), sourceText);
2408
- }
2409
-
2410
- //#endregion
2411
- //#region src/utils/asset-source.ts
2412
- function transformAssetSource(bindingAssetSource$1) {
2413
- return bindingAssetSource$1.inner;
2414
- }
2415
- function bindingAssetSource(source) {
2416
- return { inner: source };
2417
- }
2418
-
2419
- //#endregion
2420
- //#region src/plugin/plugin-context.ts
2421
- var PluginContextImpl = class extends MinimalPluginContextImpl {
2422
- getModuleInfo;
2423
- constructor(outputOptions, context, plugin, data, onLog, logLevel, watchMode, currentLoadingModule) {
2424
- super(onLog, logLevel, plugin.name, watchMode);
2425
- this.outputOptions = outputOptions;
2426
- this.context = context;
2427
- this.data = data;
2428
- this.onLog = onLog;
2429
- this.currentLoadingModule = currentLoadingModule;
2430
- this.getModuleInfo = (id$1) => this.data.getModuleInfo(id$1, context);
2431
- }
2432
- async load(options) {
2433
- const id$1 = options.id;
2434
- if (id$1 === this.currentLoadingModule) this.onLog(LOG_LEVEL_WARN, logCycleLoading(this.pluginName, this.currentLoadingModule));
2435
- const moduleInfo = this.data.getModuleInfo(id$1, this.context);
2436
- if (moduleInfo && moduleInfo.code !== null) return moduleInfo;
2437
- const rawOptions = {
2438
- meta: options.meta || {},
2439
- moduleSideEffects: options.moduleSideEffects || null,
2440
- invalidate: false
2441
- };
2442
- this.data.updateModuleOption(id$1, rawOptions);
2443
- async function createLoadModulePromise(context, data) {
2444
- const loadPromise = data.loadModulePromiseMap.get(id$1);
2445
- if (loadPromise) return loadPromise;
2446
- const promise$1 = new Promise((resolve, _) => {
2447
- data.loadModulePromiseResolveFnMap.set(id$1, resolve);
2448
- });
2449
- data.loadModulePromiseMap.set(id$1, promise$1);
2450
- try {
2451
- await context.load(id$1, bindingifySideEffects(options.moduleSideEffects));
2452
- } catch (e) {
2453
- data.loadModulePromiseMap.delete(id$1);
2454
- data.loadModulePromiseResolveFnMap.delete(id$1);
2455
- throw e;
2456
- }
2457
- return promise$1;
2458
- }
2459
- await createLoadModulePromise(this.context, this.data);
2460
- return this.data.getModuleInfo(id$1, this.context);
2461
- }
2462
- async resolve(source, importer, options) {
2463
- let receipt = void 0;
2464
- if (options != null) receipt = this.data.saveResolveOptions(options);
2465
- const res = await this.context.resolve(source, importer, {
2466
- custom: receipt,
2467
- skipSelf: options?.skipSelf
2468
- });
2469
- if (receipt != null) this.data.removeSavedResolveOptions(receipt);
2470
- if (res == null) return null;
2471
- const info = this.data.getModuleOption(res.id) || {};
2472
- return {
2473
- ...res,
2474
- external: res.external === "relative" ? unreachable(`The PluginContext resolve result external couldn't be 'relative'`) : res.external,
2475
- ...info
2476
- };
2477
- }
2478
- emitFile = (file) => {
2479
- if (file.type === "prebuilt-chunk") return unimplemented("PluginContext.emitFile with type prebuilt-chunk");
2480
- if (file.type === "chunk") return this.context.emitChunk(file);
2481
- const fnSanitizedFileName = file.fileName || typeof this.outputOptions.sanitizeFileName !== "function" ? void 0 : this.outputOptions.sanitizeFileName(file.name || "asset");
2482
- const filename = file.fileName ? void 0 : this.getAssetFileNames(file);
2483
- return this.context.emitFile({
2484
- ...file,
2485
- originalFileName: file.originalFileName || void 0,
2486
- source: bindingAssetSource(file.source)
2487
- }, filename, fnSanitizedFileName);
2488
- };
2489
- getAssetFileNames(file) {
2490
- if (typeof this.outputOptions.assetFileNames === "function") return this.outputOptions.assetFileNames({
2491
- names: file.name ? [file.name] : [],
2492
- originalFileNames: file.originalFileName ? [file.originalFileName] : [],
2493
- source: file.source,
2494
- type: "asset"
2495
- });
2496
- }
2497
- getFileName(referenceId) {
2498
- return this.context.getFileName(referenceId);
2499
- }
2500
- getModuleIds() {
2501
- return this.data.getModuleIds(this.context);
2502
- }
2503
- addWatchFile(id$1) {
2504
- this.context.addWatchFile(id$1);
2505
- }
2506
- parse(input, options) {
2507
- return parseAst(input, options);
2508
- }
2509
- };
2510
-
2511
- //#endregion
2512
- //#region src/plugin/transform-plugin-context.ts
2513
- var TransformPluginContextImpl = class extends PluginContextImpl {
2514
- constructor(outputOptions, context, plugin, data, inner, moduleId, moduleSource, onLog, LogLevelOption, watchMode) {
2515
- super(outputOptions, context, plugin, data, onLog, LogLevelOption, watchMode, moduleId);
2516
- this.inner = inner;
2517
- this.moduleId = moduleId;
2518
- this.moduleSource = moduleSource;
2519
- const getLogHandler$1 = (handler) => (log, pos) => {
2520
- log = normalizeLog(log);
2521
- if (pos) augmentCodeLocation(log, pos, moduleSource, moduleId);
2522
- log.id = moduleId;
2523
- log.hook = "transform";
2524
- handler(log);
2525
- };
2526
- this.debug = getLogHandler$1(this.debug);
2527
- this.warn = getLogHandler$1(this.warn);
2528
- this.info = getLogHandler$1(this.info);
2529
- }
2530
- error(e, pos) {
2531
- if (typeof e === "string") e = { message: e };
2532
- if (pos) augmentCodeLocation(e, pos, this.moduleSource, this.moduleId);
2533
- e.id = this.moduleId;
2534
- e.hook = "transform";
2535
- return error(logPluginError(normalizeLog(e), this.pluginName));
2536
- }
2537
- getCombinedSourcemap() {
2538
- return JSON.parse(this.inner.getCombinedSourcemap());
2539
- }
2540
- };
2541
-
2542
- //#endregion
2543
- //#region src/plugin/bindingify-build-hooks.ts
2544
- function bindingifyBuildStart(args$1) {
2545
- const hook = args$1.plugin.buildStart;
2546
- if (!hook) return {};
2547
- const { handler, meta } = normalizeHook(hook);
2548
- return {
2549
- plugin: async (ctx, opts) => {
2550
- await handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode), new NormalizedInputOptionsImpl(opts, args$1.onLog));
2551
- },
2552
- meta: bindingifyPluginHookMeta(meta)
2553
- };
2554
- }
2555
- function bindingifyBuildEnd(args$1) {
2556
- const hook = args$1.plugin.buildEnd;
2557
- if (!hook) return {};
2558
- const { handler, meta } = normalizeHook(hook);
2559
- return {
2560
- plugin: async (ctx, err) => {
2561
- await handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode), err ? normalizeErrors(err) : void 0);
2562
- },
2563
- meta: bindingifyPluginHookMeta(meta)
2564
- };
2565
- }
2566
- function bindingifyResolveId(args$1) {
2567
- const hook = args$1.plugin.resolveId;
2568
- if (!hook) return {};
2569
- const { handler, meta, options } = normalizeHook(hook);
2570
- return {
2571
- plugin: async (ctx, specifier, importer, extraOptions) => {
2572
- const contextResolveOptions = extraOptions.custom != null ? args$1.pluginContextData.getSavedResolveOptions(extraOptions.custom) : void 0;
2573
- const newExtraOptions = {
2574
- ...extraOptions,
2575
- custom: contextResolveOptions?.custom,
2576
- [SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF]: contextResolveOptions?.[SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF]
2577
- };
2578
- const ret = await handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode), specifier, importer ?? void 0, newExtraOptions);
2579
- if (ret == null) return;
2580
- if (ret === false) return {
2581
- id: specifier,
2582
- external: true,
2583
- normalizeExternalId: true
2584
- };
2585
- if (typeof ret === "string") return {
2586
- id: ret,
2587
- normalizeExternalId: true
2588
- };
2589
- let exist = args$1.pluginContextData.updateModuleOption(ret.id, {
2590
- meta: ret.meta || {},
2591
- moduleSideEffects: ret.moduleSideEffects ?? null,
2592
- invalidate: false
2593
- });
2594
- return {
2595
- id: ret.id,
2596
- external: ret.external,
2597
- normalizeExternalId: false,
2598
- sideEffects: bindingifySideEffects(exist.moduleSideEffects)
2599
- };
2600
- },
2601
- meta: bindingifyPluginHookMeta(meta),
2602
- filter: bindingifyResolveIdFilter(options.filter)
2603
- };
2604
- }
2605
- function bindingifyResolveDynamicImport(args$1) {
2606
- const hook = args$1.plugin.resolveDynamicImport;
2607
- if (!hook) return {};
2608
- const { handler, meta } = normalizeHook(hook);
2609
- return {
2610
- plugin: async (ctx, specifier, importer) => {
2611
- const ret = await handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode), specifier, importer ?? void 0);
2612
- if (ret == null) return;
2613
- if (ret === false) return {
2614
- id: specifier,
2615
- external: true
2616
- };
2617
- if (typeof ret === "string") return { id: ret };
2618
- const result = {
2619
- id: ret.id,
2620
- external: ret.external
2621
- };
2622
- if (ret.moduleSideEffects !== null) result.sideEffects = bindingifySideEffects(ret.moduleSideEffects);
2623
- args$1.pluginContextData.updateModuleOption(ret.id, {
2624
- meta: ret.meta || {},
2625
- moduleSideEffects: ret.moduleSideEffects || null,
2626
- invalidate: false
2627
- });
2628
- return result;
2629
- },
2630
- meta: bindingifyPluginHookMeta(meta)
2631
- };
2632
- }
2633
- function bindingifyTransform(args$1) {
2634
- const hook = args$1.plugin.transform;
2635
- if (!hook) return {};
2636
- const { handler, meta, options } = normalizeHook(hook);
2637
- return {
2638
- plugin: async (ctx, code$1, id$1, meta$1) => {
2639
- const ret = await handler.call(new TransformPluginContextImpl(args$1.outputOptions, ctx.inner(), args$1.plugin, args$1.pluginContextData, ctx, id$1, code$1, args$1.onLog, args$1.logLevel, args$1.watchMode), code$1, id$1, meta$1);
2640
- if (ret == null) return void 0;
2641
- if (typeof ret === "string") return { code: ret };
2642
- let moduleOption = args$1.pluginContextData.updateModuleOption(id$1, {
2643
- meta: ret.meta ?? {},
2644
- moduleSideEffects: ret.moduleSideEffects ?? null,
2645
- invalidate: false
2646
- });
2647
- return {
2648
- code: ret.code,
2649
- map: bindingifySourcemap(normalizeTransformHookSourcemap(id$1, code$1, ret.map)),
2650
- sideEffects: bindingifySideEffects(moduleOption.moduleSideEffects),
2651
- moduleType: ret.moduleType
2652
- };
2653
- },
2654
- meta: bindingifyPluginHookMeta(meta),
2655
- filter: bindingifyTransformFilter(options.filter)
2656
- };
2657
- }
2658
- function bindingifyLoad(args$1) {
2659
- const hook = args$1.plugin.load;
2660
- if (!hook) return {};
2661
- const { handler, meta, options } = normalizeHook(hook);
2662
- return {
2663
- plugin: async (ctx, id$1) => {
2664
- const ret = await handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode, id$1), id$1);
2665
- if (ret == null) return;
2666
- if (typeof ret === "string") return { code: ret };
2667
- let moduleOption = args$1.pluginContextData.updateModuleOption(id$1, {
2668
- meta: ret.meta || {},
2669
- moduleSideEffects: ret.moduleSideEffects ?? null,
2670
- invalidate: false
2671
- });
2672
- let map = preProcessSourceMap(ret, id$1);
2673
- return {
2674
- code: ret.code,
2675
- map: bindingifySourcemap(map),
2676
- moduleType: ret.moduleType,
2677
- sideEffects: bindingifySideEffects(moduleOption.moduleSideEffects)
2678
- };
2679
- },
2680
- meta: bindingifyPluginHookMeta(meta),
2681
- filter: bindingifyLoadFilter(options.filter)
2682
- };
2683
- }
2684
- function preProcessSourceMap(ret, id$1) {
2685
- if (!ret.map) return;
2686
- let map = typeof ret.map === "object" ? ret.map : JSON.parse(ret.map);
2687
- if (!isEmptySourcemapFiled(map.sources)) {
2688
- const directory = path.dirname(id$1) || ".";
2689
- const sourceRoot = map.sourceRoot || ".";
2690
- map.sources = map.sources.map((source) => path.resolve(directory, sourceRoot, source));
2691
- }
2692
- return map;
2693
- }
2694
- function bindingifyModuleParsed(args$1) {
2695
- const hook = args$1.plugin.moduleParsed;
2696
- if (!hook) return {};
2697
- const { handler, meta } = normalizeHook(hook);
2698
- return {
2699
- plugin: async (ctx, moduleInfo) => {
2700
- await handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode), transformModuleInfo(moduleInfo, args$1.pluginContextData.getModuleOption(moduleInfo.id)));
2701
- },
2702
- meta: bindingifyPluginHookMeta(meta)
2703
- };
2704
- }
2705
-
2706
- //#endregion
2707
- //#region src/utils/transform-rendered-module.ts
2708
- function transformToRenderedModule(bindingRenderedModule) {
2709
- return {
2710
- get code() {
2711
- return bindingRenderedModule.code;
2712
- },
2713
- get renderedLength() {
2714
- return bindingRenderedModule.code?.length || 0;
2715
- },
2716
- get renderedExports() {
2717
- return bindingRenderedModule.renderedExports;
2718
- }
2719
- };
2720
- }
2721
-
2722
- //#endregion
2723
- //#region src/utils/transform-rendered-chunk.ts
2724
- function transformRenderedChunk(chunk) {
2725
- let modules = null;
2726
- return {
2727
- type: "chunk",
2728
- get name() {
2729
- return chunk.name;
2730
- },
2731
- get isEntry() {
2732
- return chunk.isEntry;
2733
- },
2734
- get isDynamicEntry() {
2735
- return chunk.isDynamicEntry;
2736
- },
2737
- get facadeModuleId() {
2738
- return chunk.facadeModuleId;
2739
- },
2740
- get moduleIds() {
2741
- return chunk.moduleIds;
2742
- },
2743
- get exports() {
2744
- return chunk.exports;
2745
- },
2746
- get fileName() {
2747
- return chunk.fileName;
2748
- },
2749
- get imports() {
2750
- return chunk.imports;
2751
- },
2752
- get dynamicImports() {
2753
- return chunk.dynamicImports;
2754
- },
2755
- get modules() {
2756
- if (!modules) modules = transformChunkModules(chunk.modules);
2757
- return modules;
2758
- }
2759
- };
2760
- }
2761
- function transformChunkModules(modules) {
2762
- const result = {};
2763
- for (let i$1 = 0; i$1 < modules.values.length; i$1++) {
2764
- let key = modules.keys[i$1];
2765
- const mod = modules.values[i$1];
2766
- result[key] = transformToRenderedModule(mod);
2767
- }
2768
- return result;
2769
- }
2770
-
2771
- //#endregion
2772
- //#region src/utils/bindingify-output-options.ts
2773
- function bindingifyOutputOptions(outputOptions) {
2774
- const { dir, format, exports, hashCharacters, sourcemap, sourcemapDebugIds, sourcemapIgnoreList, sourcemapPathTransform, name, assetFileNames, entryFileNames, chunkFileNames, cssEntryFileNames, cssChunkFileNames, banner, footer, intro, outro, esModule, globals, file, sanitizeFileName, preserveModules, virtualDirname, legalComments, preserveModulesRoot } = outputOptions;
2775
- return {
2776
- dir,
2777
- file: file == null ? void 0 : file,
2778
- format: bindingifyFormat(format),
2779
- exports,
2780
- hashCharacters,
2781
- sourcemap: bindingifySourcemap$1(sourcemap),
2782
- sourcemapDebugIds,
2783
- sourcemapIgnoreList: bindingifySourcemapIgnoreList(sourcemapIgnoreList),
2784
- sourcemapPathTransform,
2785
- banner: bindingifyAddon(banner),
2786
- footer: bindingifyAddon(footer),
2787
- intro: bindingifyAddon(intro),
2788
- outro: bindingifyAddon(outro),
2789
- extend: outputOptions.extend,
2790
- globals,
2791
- esModule,
2792
- name,
2793
- assetFileNames: bindingifyAssetFilenames(assetFileNames),
2794
- entryFileNames,
2795
- chunkFileNames,
2796
- cssEntryFileNames,
2797
- cssChunkFileNames,
2798
- plugins: [],
2799
- minify: outputOptions.minify,
2800
- externalLiveBindings: outputOptions.externalLiveBindings,
2801
- inlineDynamicImports: outputOptions.inlineDynamicImports,
2802
- advancedChunks: outputOptions.advancedChunks,
2803
- polyfillRequire: outputOptions.polyfillRequire,
2804
- sanitizeFileName,
2805
- preserveModules,
2806
- virtualDirname,
2807
- legalComments,
2808
- preserveModulesRoot
2809
- };
2810
- }
2811
- function bindingifyAddon(configAddon) {
2812
- return async (chunk) => {
2813
- if (typeof configAddon === "function") return configAddon(transformRenderedChunk(chunk));
2814
- return configAddon || "";
2815
- };
2816
- }
2817
- function bindingifyFormat(format) {
2818
- switch (format) {
2819
- case void 0:
2820
- case "es":
2821
- case "esm":
2822
- case "module": return "es";
2823
- case "cjs":
2824
- case "commonjs": return "cjs";
2825
- case "iife": return "iife";
2826
- case "umd": return "umd";
2827
- case "experimental-app": return "app";
2828
- default: unimplemented(`output.format: ${format}`);
2829
- }
2830
- }
2831
- function bindingifySourcemap$1(sourcemap) {
2832
- switch (sourcemap) {
2833
- case true: return "file";
2834
- case "inline": return "inline";
2835
- case false:
2836
- case void 0: return void 0;
2837
- case "hidden": return "hidden";
2838
- default: throw new Error(`unknown sourcemap: ${sourcemap}`);
2839
- }
2840
- }
2841
- function bindingifySourcemapIgnoreList(sourcemapIgnoreList) {
2842
- return typeof sourcemapIgnoreList === "function" ? sourcemapIgnoreList : sourcemapIgnoreList === false ? () => false : (relativeSourcePath, _sourcemapPath) => relativeSourcePath.includes("node_modules");
2843
- }
2844
- function bindingifyAssetFilenames(assetFileNames) {
2845
- if (typeof assetFileNames === "function") return (asset) => {
2846
- return assetFileNames({
2847
- names: asset.names,
2848
- originalFileNames: asset.originalFileNames,
2849
- source: transformAssetSource(asset.source),
2850
- type: "asset"
2851
- });
2852
- };
2853
- return assetFileNames;
2854
- }
2855
-
2856
- //#endregion
2857
- //#region src/options/normalized-output-options.ts
2858
- var NormalizedOutputOptionsImpl = class {
2859
- constructor(inner, outputOptions, normalizedOutputPlugins) {
2860
- this.inner = inner;
2861
- this.outputOptions = outputOptions;
2862
- this.normalizedOutputPlugins = normalizedOutputPlugins;
2863
- }
2864
- get dir() {
2865
- return this.inner.dir ?? void 0;
2866
- }
2867
- get entryFileNames() {
2868
- return this.inner.entryFilenames || this.outputOptions.entryFileNames;
2869
- }
2870
- get chunkFileNames() {
2871
- return this.inner.chunkFilenames || this.outputOptions.chunkFileNames;
2872
- }
2873
- get assetFileNames() {
2874
- return this.inner.assetFilenames || this.outputOptions.assetFileNames;
2875
- }
2876
- get format() {
2877
- return this.inner.format;
2878
- }
2879
- get exports() {
2880
- return this.inner.exports;
2881
- }
2882
- get sourcemap() {
2883
- return this.inner.sourcemap;
2884
- }
2885
- get cssEntryFileNames() {
2886
- return this.inner.cssEntryFilenames || this.outputOptions.cssEntryFileNames;
2887
- }
2888
- get cssChunkFileNames() {
2889
- return this.inner.cssChunkFilenames || this.outputOptions.cssChunkFileNames;
2890
- }
2891
- get shimMissingExports() {
2892
- return this.inner.shimMissingExports;
2893
- }
2894
- get name() {
2895
- return this.inner.name ?? void 0;
2896
- }
2897
- get file() {
2898
- return this.inner.file ?? void 0;
2899
- }
2900
- get inlineDynamicImports() {
2901
- return this.inner.inlineDynamicImports;
2902
- }
2903
- get externalLiveBindings() {
2904
- return this.inner.externalLiveBindings;
2905
- }
2906
- get banner() {
2907
- return normalizeAddon(this.outputOptions.banner);
2908
- }
2909
- get footer() {
2910
- return normalizeAddon(this.outputOptions.footer);
2911
- }
2912
- get intro() {
2913
- return normalizeAddon(this.outputOptions.intro);
2914
- }
2915
- get outro() {
2916
- return normalizeAddon(this.outputOptions.outro);
2917
- }
2918
- get esModule() {
2919
- return this.inner.esModule;
2920
- }
2921
- get extend() {
2922
- return this.inner.extend;
2923
- }
2924
- get globals() {
2925
- return this.inner.globals || this.outputOptions.globals;
2926
- }
2927
- get hashCharacters() {
2928
- return this.inner.hashCharacters;
2929
- }
2930
- get sourcemapDebugIds() {
2931
- return this.inner.sourcemapDebugIds;
2932
- }
2933
- get sourcemapIgnoreList() {
2934
- return bindingifySourcemapIgnoreList(this.outputOptions.sourcemapIgnoreList);
2935
- }
2936
- get sourcemapPathTransform() {
2937
- return this.outputOptions.sourcemapPathTransform;
2938
- }
2939
- get minify() {
2940
- return this.inner.minify;
2941
- }
2942
- get legalComments() {
2943
- return this.inner.legalComments;
2944
- }
2945
- get polyfillRequire() {
2946
- return this.inner.polyfillRequire;
2947
- }
2948
- get plugins() {
2949
- return this.normalizedOutputPlugins;
2950
- }
2951
- get preserveModules() {
2952
- return this.preserveModules;
2953
- }
2954
- get preserveModulesRoot() {
2955
- return this.preserveModulesRoot;
2956
- }
2957
- get virtualDirname() {
2958
- return this.virtualDirname;
2959
- }
2960
- };
2961
- function normalizeAddon(value) {
2962
- if (typeof value === "function") return value;
2963
- return () => value || "";
2964
- }
2965
-
2966
- //#endregion
2967
- //#region src/utils/transform-to-rollup-output.ts
2968
- function transformToRollupSourceMap(map) {
2969
- const parsed = JSON.parse(map);
2970
- const obj = {
2971
- ...parsed,
2972
- toString() {
2973
- return JSON.stringify(obj);
2974
- },
2975
- toUrl() {
2976
- return `data:application/json;charset=utf-8;base64,${Buffer.from(obj.toString(), "utf-8").toString("base64")}`;
2977
- }
2978
- };
2979
- return obj;
2980
- }
2981
- function transformToRollupOutputChunk(bindingChunk, changed) {
2982
- const chunk = {
2983
- type: "chunk",
2984
- get code() {
2985
- return bindingChunk.code;
2986
- },
2987
- fileName: bindingChunk.fileName,
2988
- name: bindingChunk.name,
2989
- get modules() {
2990
- return transformChunkModules(bindingChunk.modules);
2991
- },
2992
- get imports() {
2993
- return bindingChunk.imports;
2994
- },
2995
- get dynamicImports() {
2996
- return bindingChunk.dynamicImports;
2997
- },
2998
- exports: bindingChunk.exports,
2999
- isEntry: bindingChunk.isEntry,
3000
- facadeModuleId: bindingChunk.facadeModuleId || null,
3001
- isDynamicEntry: bindingChunk.isDynamicEntry,
3002
- get moduleIds() {
3003
- return bindingChunk.moduleIds;
3004
- },
3005
- get map() {
3006
- return bindingChunk.map ? transformToRollupSourceMap(bindingChunk.map) : null;
3007
- },
3008
- sourcemapFileName: bindingChunk.sourcemapFileName || null,
3009
- preliminaryFileName: bindingChunk.preliminaryFileName
3010
- };
3011
- const cache = {};
3012
- return new Proxy(chunk, {
3013
- get(target, p) {
3014
- if (p in cache) return cache[p];
3015
- const value = target[p];
3016
- cache[p] = value;
3017
- return value;
3018
- },
3019
- set(target, p, newValue) {
3020
- cache[p] = newValue;
3021
- changed?.updated.add(bindingChunk.fileName);
3022
- return true;
3023
- },
3024
- has(target, p) {
3025
- if (p in cache) return true;
3026
- return p in target;
3027
- }
3028
- });
3029
- }
3030
- function transformToRollupOutputAsset(bindingAsset, changed) {
3031
- const asset = {
3032
- type: "asset",
3033
- fileName: bindingAsset.fileName,
3034
- originalFileName: bindingAsset.originalFileName || null,
3035
- originalFileNames: bindingAsset.originalFileNames,
3036
- get source() {
3037
- return transformAssetSource(bindingAsset.source);
3038
- },
3039
- name: bindingAsset.name ?? void 0,
3040
- names: bindingAsset.names
3041
- };
3042
- const cache = {};
3043
- return new Proxy(asset, {
3044
- get(target, p) {
3045
- if (p in cache) return cache[p];
3046
- const value = target[p];
3047
- cache[p] = value;
3048
- return value;
3049
- },
3050
- set(target, p, newValue) {
3051
- cache[p] = newValue;
3052
- changed?.updated.add(bindingAsset.fileName);
3053
- return true;
3054
- }
3055
- });
3056
- }
3057
- function transformToRollupOutput(output, changed) {
3058
- handleOutputErrors(output);
3059
- const { chunks, assets } = output;
3060
- return { output: [...chunks.map((chunk) => transformToRollupOutputChunk(chunk, changed)), ...assets.map((asset) => transformToRollupOutputAsset(asset, changed))] };
3061
- }
3062
- function handleOutputErrors(output) {
3063
- const rawErrors = output.errors;
3064
- if (rawErrors.length > 0) throw normalizeErrors(rawErrors);
3065
- }
3066
- function transformToOutputBundle(output, changed) {
3067
- const bundle = Object.fromEntries(transformToRollupOutput(output, changed).output.map((item) => [item.fileName, item]));
3068
- return new Proxy(bundle, { deleteProperty(target, property) {
3069
- if (typeof property === "string") changed.deleted.add(property);
3070
- return true;
3071
- } });
3072
- }
3073
- function collectChangedBundle(changed, bundle) {
3074
- const assets = [];
3075
- const chunks = [];
3076
- for (const key in bundle) {
3077
- if (changed.deleted.has(key) || !changed.updated.has(key)) continue;
3078
- const item = bundle[key];
3079
- if (item.type === "asset") assets.push({
3080
- filename: item.fileName,
3081
- originalFileNames: item.originalFileNames,
3082
- source: bindingAssetSource(item.source),
3083
- names: item.names
3084
- });
3085
- else chunks.push({
3086
- code: item.code,
3087
- filename: item.fileName,
3088
- name: item.name,
3089
- isEntry: item.isEntry,
3090
- exports: item.exports,
3091
- modules: {},
3092
- imports: item.imports,
3093
- dynamicImports: item.dynamicImports,
3094
- facadeModuleId: item.facadeModuleId || void 0,
3095
- isDynamicEntry: item.isDynamicEntry,
3096
- moduleIds: item.moduleIds,
3097
- map: bindingifySourcemap(item.map),
3098
- sourcemapFilename: item.sourcemapFileName || void 0,
3099
- preliminaryFilename: item.preliminaryFileName
3100
- });
3101
- }
3102
- return {
3103
- assets,
3104
- chunks,
3105
- deleted: Array.from(changed.deleted)
3106
- };
3107
- }
3108
-
3109
- //#endregion
3110
- //#region src/plugin/bindingify-output-hooks.ts
3111
- function bindingifyRenderStart(args$1) {
3112
- const hook = args$1.plugin.renderStart;
3113
- if (!hook) return {};
3114
- const { handler, meta } = normalizeHook(hook);
3115
- return {
3116
- plugin: async (ctx, opts) => {
3117
- handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode), new NormalizedOutputOptionsImpl(opts, args$1.outputOptions, args$1.normalizedOutputPlugins), new NormalizedInputOptionsImpl(opts, args$1.onLog));
3118
- },
3119
- meta: bindingifyPluginHookMeta(meta)
3120
- };
3121
- }
3122
- function bindingifyRenderChunk(args$1) {
3123
- const hook = args$1.plugin.renderChunk;
3124
- if (!hook) return {};
3125
- const { handler, meta, options } = normalizeHook(hook);
3126
- return {
3127
- plugin: async (ctx, code$1, chunk, opts, meta$1) => {
3128
- if (args$1.pluginContextData.getRenderChunkMeta() == null) args$1.pluginContextData.setRenderChunkMeta({ chunks: Object.fromEntries(Object.entries(meta$1.chunks).map(([key, value]) => [key, transformRenderedChunk(value)])) });
3129
- const ret = await handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode), code$1, transformRenderedChunk(chunk), new NormalizedOutputOptionsImpl(opts, args$1.outputOptions, args$1.normalizedOutputPlugins), args$1.pluginContextData.getRenderChunkMeta());
3130
- if (ret == null) return;
3131
- if (typeof ret === "string") return { code: ret };
3132
- if (!ret.map) return { code: ret.code };
3133
- return {
3134
- code: ret.code,
3135
- map: bindingifySourcemap(ret.map)
3136
- };
3137
- },
3138
- meta: bindingifyPluginHookMeta(meta),
3139
- filter: bindingifyRenderChunkFilter(options.filter)
3140
- };
3141
- }
3142
- function bindingifyAugmentChunkHash(args$1) {
3143
- const hook = args$1.plugin.augmentChunkHash;
3144
- if (!hook) return {};
3145
- const { handler, meta } = normalizeHook(hook);
3146
- return {
3147
- plugin: async (ctx, chunk) => {
3148
- return await handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode), transformRenderedChunk(chunk));
3149
- },
3150
- meta: bindingifyPluginHookMeta(meta)
3151
- };
3152
- }
3153
- function bindingifyRenderError(args$1) {
3154
- const hook = args$1.plugin.renderError;
3155
- if (!hook) return {};
3156
- const { handler, meta } = normalizeHook(hook);
3157
- return {
3158
- plugin: async (ctx, err) => {
3159
- handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode), normalizeErrors(err));
3160
- },
3161
- meta: bindingifyPluginHookMeta(meta)
3162
- };
3163
- }
3164
- function bindingifyGenerateBundle(args$1) {
3165
- const hook = args$1.plugin.generateBundle;
3166
- if (!hook) return {};
3167
- const { handler, meta } = normalizeHook(hook);
3168
- return {
3169
- plugin: async (ctx, bundle, isWrite, opts) => {
3170
- const changed = {
3171
- updated: new Set(),
3172
- deleted: new Set()
3173
- };
3174
- const output = transformToOutputBundle(bundle, changed);
3175
- await handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode), new NormalizedOutputOptionsImpl(opts, args$1.outputOptions, args$1.normalizedOutputPlugins), output, isWrite);
3176
- return collectChangedBundle(changed, output);
3177
- },
3178
- meta: bindingifyPluginHookMeta(meta)
3179
- };
3180
- }
3181
- function bindingifyWriteBundle(args$1) {
3182
- const hook = args$1.plugin.writeBundle;
3183
- if (!hook) return {};
3184
- const { handler, meta } = normalizeHook(hook);
3185
- return {
3186
- plugin: async (ctx, bundle, opts) => {
3187
- const changed = {
3188
- updated: new Set(),
3189
- deleted: new Set()
3190
- };
3191
- const output = transformToOutputBundle(bundle, changed);
3192
- await handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode), new NormalizedOutputOptionsImpl(opts, args$1.outputOptions, args$1.normalizedOutputPlugins), output);
3193
- return collectChangedBundle(changed, output);
3194
- },
3195
- meta: bindingifyPluginHookMeta(meta)
3196
- };
3197
- }
3198
- function bindingifyCloseBundle(args$1) {
3199
- const hook = args$1.plugin.closeBundle;
3200
- if (!hook) return {};
3201
- const { handler, meta } = normalizeHook(hook);
3202
- return {
3203
- plugin: async (ctx) => {
3204
- await handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode));
3205
- },
3206
- meta: bindingifyPluginHookMeta(meta)
3207
- };
3208
- }
3209
- function bindingifyBanner(args$1) {
3210
- const hook = args$1.plugin.banner;
3211
- if (!hook) return {};
3212
- const { handler, meta } = normalizeHook(hook);
3213
- return {
3214
- plugin: async (ctx, chunk) => {
3215
- if (typeof handler === "string") return handler;
3216
- return handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode), transformRenderedChunk(chunk));
3217
- },
3218
- meta: bindingifyPluginHookMeta(meta)
3219
- };
3220
- }
3221
- function bindingifyFooter(args$1) {
3222
- const hook = args$1.plugin.footer;
3223
- if (!hook) return {};
3224
- const { handler, meta } = normalizeHook(hook);
3225
- return {
3226
- plugin: async (ctx, chunk) => {
3227
- if (typeof handler === "string") return handler;
3228
- return handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode), transformRenderedChunk(chunk));
3229
- },
3230
- meta: bindingifyPluginHookMeta(meta)
3231
- };
3232
- }
3233
- function bindingifyIntro(args$1) {
3234
- const hook = args$1.plugin.intro;
3235
- if (!hook) return {};
3236
- const { handler, meta } = normalizeHook(hook);
3237
- return {
3238
- plugin: async (ctx, chunk) => {
3239
- if (typeof handler === "string") return handler;
3240
- return handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode), transformRenderedChunk(chunk));
3241
- },
3242
- meta: bindingifyPluginHookMeta(meta)
3243
- };
3244
- }
3245
- function bindingifyOutro(args$1) {
3246
- const hook = args$1.plugin.outro;
3247
- if (!hook) return {};
3248
- const { handler, meta } = normalizeHook(hook);
3249
- return {
3250
- plugin: async (ctx, chunk) => {
3251
- if (typeof handler === "string") return handler;
3252
- return handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode), transformRenderedChunk(chunk));
3253
- },
3254
- meta: bindingifyPluginHookMeta(meta)
3255
- };
3256
- }
3257
-
3258
- //#endregion
3259
- //#region src/plugin/bindingify-watch-hooks.ts
3260
- function bindingifyWatchChange(args$1) {
3261
- const hook = args$1.plugin.watchChange;
3262
- if (!hook) return {};
3263
- const { handler, meta } = normalizeHook(hook);
3264
- return {
3265
- plugin: async (ctx, id$1, event) => {
3266
- await handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode), id$1, { event });
3267
- },
3268
- meta: bindingifyPluginHookMeta(meta)
3269
- };
3270
- }
3271
- function bindingifyCloseWatcher(args$1) {
3272
- const hook = args$1.plugin.closeWatcher;
3273
- if (!hook) return {};
3274
- const { handler, meta } = normalizeHook(hook);
3275
- return {
3276
- plugin: async (ctx) => {
3277
- await handler.call(new PluginContextImpl(args$1.outputOptions, ctx, args$1.plugin, args$1.pluginContextData, args$1.onLog, args$1.logLevel, args$1.watchMode));
3278
- },
3279
- meta: bindingifyPluginHookMeta(meta)
3280
- };
3281
- }
3282
-
3283
- //#endregion
3284
- //#region src/plugin/generated/hook-usage.ts
3285
- let HookUsageKind = /* @__PURE__ */ function(HookUsageKind$1) {
3286
- HookUsageKind$1[HookUsageKind$1["buildStart"] = 1] = "buildStart";
3287
- HookUsageKind$1[HookUsageKind$1["resolveId"] = 2] = "resolveId";
3288
- HookUsageKind$1[HookUsageKind$1["resolveDynamicImport"] = 4] = "resolveDynamicImport";
3289
- HookUsageKind$1[HookUsageKind$1["load"] = 8] = "load";
3290
- HookUsageKind$1[HookUsageKind$1["transform"] = 16] = "transform";
3291
- HookUsageKind$1[HookUsageKind$1["moduleParsed"] = 32] = "moduleParsed";
3292
- HookUsageKind$1[HookUsageKind$1["buildEnd"] = 64] = "buildEnd";
3293
- HookUsageKind$1[HookUsageKind$1["renderStart"] = 128] = "renderStart";
3294
- HookUsageKind$1[HookUsageKind$1["renderError"] = 256] = "renderError";
3295
- HookUsageKind$1[HookUsageKind$1["renderChunk"] = 512] = "renderChunk";
3296
- HookUsageKind$1[HookUsageKind$1["augmentChunkHash"] = 1024] = "augmentChunkHash";
3297
- HookUsageKind$1[HookUsageKind$1["generateBundle"] = 2048] = "generateBundle";
3298
- HookUsageKind$1[HookUsageKind$1["writeBundle"] = 4096] = "writeBundle";
3299
- HookUsageKind$1[HookUsageKind$1["closeBundle"] = 8192] = "closeBundle";
3300
- HookUsageKind$1[HookUsageKind$1["watchChange"] = 16384] = "watchChange";
3301
- HookUsageKind$1[HookUsageKind$1["closeWatcher"] = 32768] = "closeWatcher";
3302
- HookUsageKind$1[HookUsageKind$1["transformAst"] = 65536] = "transformAst";
3303
- HookUsageKind$1[HookUsageKind$1["banner"] = 131072] = "banner";
3304
- HookUsageKind$1[HookUsageKind$1["footer"] = 262144] = "footer";
3305
- HookUsageKind$1[HookUsageKind$1["intro"] = 524288] = "intro";
3306
- HookUsageKind$1[HookUsageKind$1["outro"] = 1048576] = "outro";
3307
- return HookUsageKind$1;
3308
- }({});
3309
- var HookUsage = class {
3310
- bitflag = BigInt(0);
3311
- constructor() {}
3312
- union(kind) {
3313
- this.bitflag |= BigInt(kind);
3314
- }
3315
- inner() {
3316
- return Number(this.bitflag);
3317
- }
3318
- };
3319
- function extractHookUsage(plugin) {
3320
- let hookUsage = new HookUsage();
3321
- if (plugin.buildStart) hookUsage.union(HookUsageKind.buildStart);
3322
- if (plugin.resolveId) hookUsage.union(HookUsageKind.resolveId);
3323
- if (plugin.resolveDynamicImport) hookUsage.union(HookUsageKind.resolveDynamicImport);
3324
- if (plugin.load) hookUsage.union(HookUsageKind.load);
3325
- if (plugin.transform) hookUsage.union(HookUsageKind.transform);
3326
- if (plugin.moduleParsed) hookUsage.union(HookUsageKind.moduleParsed);
3327
- if (plugin.buildEnd) hookUsage.union(HookUsageKind.buildEnd);
3328
- if (plugin.renderStart) hookUsage.union(HookUsageKind.renderStart);
3329
- if (plugin.renderError) hookUsage.union(HookUsageKind.renderError);
3330
- if (plugin.renderChunk) hookUsage.union(HookUsageKind.renderChunk);
3331
- if (plugin.augmentChunkHash) hookUsage.union(HookUsageKind.augmentChunkHash);
3332
- if (plugin.generateBundle) hookUsage.union(HookUsageKind.generateBundle);
3333
- if (plugin.writeBundle) hookUsage.union(HookUsageKind.writeBundle);
3334
- if (plugin.closeBundle) hookUsage.union(HookUsageKind.closeBundle);
3335
- if (plugin.watchChange) hookUsage.union(HookUsageKind.watchChange);
3336
- if (plugin.closeWatcher) hookUsage.union(HookUsageKind.closeWatcher);
3337
- if (plugin.banner) hookUsage.union(HookUsageKind.banner);
3338
- if (plugin.footer) hookUsage.union(HookUsageKind.footer);
3339
- if (plugin.intro) hookUsage.union(HookUsageKind.intro);
3340
- if (plugin.outro) hookUsage.union(HookUsageKind.outro);
3341
- return hookUsage;
3342
- }
3343
-
3344
- //#endregion
3345
- //#region src/plugin/bindingify-plugin.ts
3346
- function bindingifyPlugin(plugin, options, outputOptions, pluginContextData, normalizedOutputPlugins, onLog, logLevel, watchMode) {
3347
- const args$1 = {
3348
- plugin,
3349
- options,
3350
- outputOptions,
3351
- pluginContextData,
3352
- onLog,
3353
- logLevel,
3354
- watchMode,
3355
- normalizedOutputPlugins
3356
- };
3357
- const { plugin: buildStart, meta: buildStartMeta } = bindingifyBuildStart(args$1);
3358
- const { plugin: resolveId, meta: resolveIdMeta, filter: resolveIdFilter } = bindingifyResolveId(args$1);
3359
- const { plugin: resolveDynamicImport, meta: resolveDynamicImportMeta } = bindingifyResolveDynamicImport(args$1);
3360
- const { plugin: buildEnd, meta: buildEndMeta } = bindingifyBuildEnd(args$1);
3361
- const { plugin: transform, meta: transformMeta, filter: transformFilter } = bindingifyTransform(args$1);
3362
- const { plugin: moduleParsed, meta: moduleParsedMeta } = bindingifyModuleParsed(args$1);
3363
- const { plugin: load, meta: loadMeta, filter: loadFilter } = bindingifyLoad(args$1);
3364
- const { plugin: renderChunk, meta: renderChunkMeta, filter: renderChunkFilter } = bindingifyRenderChunk(args$1);
3365
- const { plugin: augmentChunkHash, meta: augmentChunkHashMeta } = bindingifyAugmentChunkHash(args$1);
3366
- const { plugin: renderStart, meta: renderStartMeta } = bindingifyRenderStart(args$1);
3367
- const { plugin: renderError, meta: renderErrorMeta } = bindingifyRenderError(args$1);
3368
- const { plugin: generateBundle, meta: generateBundleMeta } = bindingifyGenerateBundle(args$1);
3369
- const { plugin: writeBundle, meta: writeBundleMeta } = bindingifyWriteBundle(args$1);
3370
- const { plugin: closeBundle, meta: closeBundleMeta } = bindingifyCloseBundle(args$1);
3371
- const { plugin: banner, meta: bannerMeta } = bindingifyBanner(args$1);
3372
- const { plugin: footer, meta: footerMeta } = bindingifyFooter(args$1);
3373
- const { plugin: intro, meta: introMeta } = bindingifyIntro(args$1);
3374
- const { plugin: outro, meta: outroMeta } = bindingifyOutro(args$1);
3375
- const { plugin: watchChange, meta: watchChangeMeta } = bindingifyWatchChange(args$1);
3376
- const { plugin: closeWatcher, meta: closeWatcherMeta } = bindingifyCloseWatcher(args$1);
3377
- let hookUsage = extractHookUsage(plugin).inner();
3378
- const result = {
3379
- name: plugin.name,
3380
- buildStart,
3381
- buildStartMeta,
3382
- resolveId,
3383
- resolveIdMeta,
3384
- resolveIdFilter,
3385
- resolveDynamicImport,
3386
- resolveDynamicImportMeta,
3387
- buildEnd,
3388
- buildEndMeta,
3389
- transform,
3390
- transformMeta,
3391
- transformFilter,
3392
- moduleParsed,
3393
- moduleParsedMeta,
3394
- load,
3395
- loadMeta,
3396
- loadFilter,
3397
- renderChunk,
3398
- renderChunkMeta,
3399
- renderChunkFilter,
3400
- augmentChunkHash,
3401
- augmentChunkHashMeta,
3402
- renderStart,
3403
- renderStartMeta,
3404
- renderError,
3405
- renderErrorMeta,
3406
- generateBundle,
3407
- generateBundleMeta,
3408
- writeBundle,
3409
- writeBundleMeta,
3410
- closeBundle,
3411
- closeBundleMeta,
3412
- banner,
3413
- bannerMeta,
3414
- footer,
3415
- footerMeta,
3416
- intro,
3417
- introMeta,
3418
- outro,
3419
- outroMeta,
3420
- watchChange,
3421
- watchChangeMeta,
3422
- closeWatcher,
3423
- closeWatcherMeta,
3424
- hookUsage
3425
- };
3426
- return wrapHandlers(result);
3427
- }
3428
- function wrapHandlers(plugin) {
3429
- for (const hookName of [
3430
- "buildStart",
3431
- "resolveId",
3432
- "resolveDynamicImport",
3433
- "buildEnd",
3434
- "transform",
3435
- "moduleParsed",
3436
- "load",
3437
- "renderChunk",
3438
- "augmentChunkHash",
3439
- "renderStart",
3440
- "renderError",
3441
- "generateBundle",
3442
- "writeBundle",
3443
- "closeBundle",
3444
- "banner",
3445
- "footer",
3446
- "intro",
3447
- "outro",
3448
- "watchChange",
3449
- "closeWatcher"
3450
- ]) {
3451
- const handler = plugin[hookName];
3452
- if (handler) plugin[hookName] = async (...args$1) => {
3453
- try {
3454
- return await handler(...args$1);
3455
- } catch (e) {
3456
- return error(logPluginError(e, plugin.name, {
3457
- hook: hookName,
3458
- id: hookName === "transform" ? args$1[2] : void 0
3459
- }));
3460
- }
3461
- };
3462
- }
3463
- return plugin;
3464
- }
3465
-
3466
- //#endregion
3467
- //#region src/plugin/plugin-context-data.ts
3468
- var PluginContextData = class {
3469
- moduleOptionMap = new Map();
3470
- resolveOptionsMap = new Map();
3471
- loadModulePromiseMap = new Map();
3472
- loadModulePromiseResolveFnMap = new Map();
3473
- renderedChunkMeta = null;
3474
- updateModuleOption(id$1, option) {
3475
- const existing = this.moduleOptionMap.get(id$1);
3476
- if (existing) {
3477
- if (option.moduleSideEffects != null) existing.moduleSideEffects = option.moduleSideEffects;
3478
- if (option.meta != null) Object.assign(existing.meta, option.meta);
3479
- if (option.invalidate != null) existing.invalidate = option.invalidate;
3480
- } else {
3481
- this.moduleOptionMap.set(id$1, option);
3482
- return option;
3483
- }
3484
- return existing;
3485
- }
3486
- getModuleOption(id$1) {
3487
- const option = this.moduleOptionMap.get(id$1);
3488
- if (!option) {
3489
- const raw = {
3490
- moduleSideEffects: null,
3491
- meta: {}
3492
- };
3493
- this.moduleOptionMap.set(id$1, raw);
3494
- return raw;
3495
- }
3496
- return option;
3497
- }
3498
- getModuleInfo(id$1, context) {
3499
- const bindingInfo = context.getModuleInfo(id$1);
3500
- if (bindingInfo) {
3501
- const info = transformModuleInfo(bindingInfo, this.getModuleOption(id$1));
3502
- return this.proxyModuleInfo(id$1, info);
3503
- }
3504
- return null;
3505
- }
3506
- proxyModuleInfo(id$1, info) {
3507
- let moduleSideEffects = info.moduleSideEffects;
3508
- Object.defineProperty(info, "moduleSideEffects", {
3509
- get() {
3510
- return moduleSideEffects;
3511
- },
3512
- set: (v) => {
3513
- this.updateModuleOption(id$1, {
3514
- moduleSideEffects: v,
3515
- meta: info.meta,
3516
- invalidate: true
3517
- });
3518
- moduleSideEffects = v;
3519
- }
3520
- });
3521
- return info;
3522
- }
3523
- getModuleIds(context) {
3524
- const moduleIds = context.getModuleIds();
3525
- return moduleIds.values();
3526
- }
3527
- saveResolveOptions(options) {
3528
- const index = this.resolveOptionsMap.size;
3529
- this.resolveOptionsMap.set(index, options);
3530
- return index;
3531
- }
3532
- getSavedResolveOptions(receipt) {
3533
- return this.resolveOptionsMap.get(receipt);
3534
- }
3535
- removeSavedResolveOptions(receipt) {
3536
- this.resolveOptionsMap.delete(receipt);
3537
- }
3538
- setRenderChunkMeta(meta) {
3539
- this.renderedChunkMeta = meta;
3540
- }
3541
- getRenderChunkMeta() {
3542
- return this.renderedChunkMeta;
3543
- }
3544
- markModuleLoaded(id$1, _success) {
3545
- const resolve = this.loadModulePromiseResolveFnMap.get(id$1);
3546
- if (resolve) resolve();
3547
- }
3548
- clear() {
3549
- this.renderedChunkMeta = null;
3550
- this.loadModulePromiseMap.clear();
3551
- this.loadModulePromiseResolveFnMap.clear();
3552
- }
3553
- };
3554
-
3555
- //#endregion
3556
- //#region src/utils/normalize-string-or-regex.ts
3557
- function normalizedStringOrRegex(pattern) {
3558
- if (!pattern) return void 0;
3559
- if (!isReadonlyArray(pattern)) return [pattern];
3560
- return pattern;
3561
- }
3562
- function isReadonlyArray(input) {
3563
- return Array.isArray(input);
3564
- }
3565
-
3566
- //#endregion
3567
- //#region src/utils/bindingify-input-options.ts
3568
- function bindingifyInputOptions(rawPlugins, inputOptions, outputOptions, normalizedOutputPlugins, onLog, logLevel, watchMode) {
3569
- const pluginContextData = new PluginContextData();
3570
- const plugins = rawPlugins.map((plugin) => {
3571
- if ("_parallel" in plugin) return void 0;
3572
- if (plugin instanceof BuiltinPlugin) return bindingifyBuiltInPlugin(plugin);
3573
- return bindingifyPlugin(plugin, inputOptions, outputOptions, pluginContextData, normalizedOutputPlugins, onLog, logLevel, watchMode);
3574
- });
3575
- return {
3576
- input: bindingifyInput(inputOptions.input),
3577
- plugins,
3578
- cwd: inputOptions.cwd ?? process.cwd(),
3579
- external: bindingifyExternal(inputOptions.external),
3580
- resolve: bindingifyResolve(inputOptions.resolve),
3581
- platform: inputOptions.platform,
3582
- shimMissingExports: inputOptions.shimMissingExports,
3583
- logLevel: bindingifyLogLevel(logLevel),
3584
- onLog,
3585
- treeshake: bindingifyTreeshakeOptions(inputOptions.treeshake),
3586
- moduleTypes: inputOptions.moduleTypes,
3587
- define: inputOptions.define ? Object.entries(inputOptions.define) : void 0,
3588
- inject: bindingifyInject(inputOptions.inject),
3589
- experimental: {
3590
- strictExecutionOrder: inputOptions.experimental?.strictExecutionOrder,
3591
- disableLiveBindings: inputOptions.experimental?.disableLiveBindings,
3592
- viteMode: inputOptions.experimental?.viteMode,
3593
- resolveNewUrlToAsset: inputOptions.experimental?.resolveNewUrlToAsset,
3594
- hmr: bindingifyHmr(inputOptions.experimental?.hmr),
3595
- attachDebugInfo: inputOptions.experimental?.attachDebugInfo
3596
- },
3597
- profilerNames: inputOptions?.profilerNames,
3598
- jsx: bindingifyJsx(inputOptions.jsx),
3599
- transform: inputOptions.transform,
3600
- watch: bindingifyWatch(inputOptions.watch),
3601
- dropLabels: inputOptions.dropLabels,
3602
- keepNames: inputOptions.keepNames,
3603
- checks: inputOptions.checks,
3604
- deferSyncScanData: () => {
3605
- let ret = [];
3606
- pluginContextData.moduleOptionMap.forEach((value, key) => {
3607
- if (value.invalidate) ret.push({
3608
- id: key,
3609
- sideEffects: bindingifySideEffects(value.moduleSideEffects)
3610
- });
3611
- });
3612
- return ret;
3613
- },
3614
- makeAbsoluteExternalsRelative: bindingifyMakeAbsoluteExternalsRelative(inputOptions.makeAbsoluteExternalsRelative),
3615
- debug: inputOptions.debug,
3616
- invalidateJsSideCache: pluginContextData.clear.bind(pluginContextData),
3617
- markModuleLoaded: pluginContextData.markModuleLoaded.bind(pluginContextData)
3618
- };
3619
- }
3620
- function bindingifyHmr(hmr) {
3621
- if (hmr) {
3622
- if (typeof hmr === "boolean") return hmr ? {} : void 0;
3623
- return hmr;
3624
- }
3625
- }
3626
- function bindingifyExternal(external) {
3627
- if (external) {
3628
- if (typeof external === "function") return (id$1, importer, isResolved) => {
3629
- if (id$1.startsWith("\0")) return false;
3630
- return external(id$1, importer, isResolved) ?? false;
3631
- };
3632
- const externalArr = arraify(external);
3633
- return (id$1, _importer, _isResolved) => {
3634
- return externalArr.some((pat) => {
3635
- if (pat instanceof RegExp) return pat.test(id$1);
3636
- return id$1 === pat;
3637
- });
3638
- };
3639
- }
3640
- }
3641
- function bindingifyResolve(resolve) {
3642
- if (resolve) {
3643
- const { alias, extensionAlias,...rest } = resolve;
3644
- return {
3645
- alias: alias ? Object.entries(alias).map(([name, replacement]) => ({
3646
- find: name,
3647
- replacements: arraify(replacement)
3648
- })) : void 0,
3649
- extensionAlias: extensionAlias ? Object.entries(extensionAlias).map(([name, value]) => ({
3650
- target: name,
3651
- replacements: value
3652
- })) : void 0,
3653
- ...rest
3654
- };
3655
- }
3656
- }
3657
- function bindingifyInject(inject) {
3658
- if (inject) return Object.entries(inject).map(([alias, item]) => {
3659
- if (Array.isArray(item)) {
3660
- if (item[1] === "*") return {
3661
- tagNamespace: true,
3662
- alias,
3663
- from: item[0]
3664
- };
3665
- return {
3666
- tagNamed: true,
3667
- alias,
3668
- from: item[0],
3669
- imported: item[1]
3670
- };
3671
- } else return {
3672
- tagNamed: true,
3673
- imported: "default",
3674
- alias,
3675
- from: item
3676
- };
3677
- });
3678
- }
3679
- function bindingifyLogLevel(logLevel) {
3680
- switch (logLevel) {
3681
- case "silent": return BindingLogLevel.Silent;
3682
- case "debug": return BindingLogLevel.Debug;
3683
- case "warn": return BindingLogLevel.Warn;
3684
- case "info": return BindingLogLevel.Info;
3685
- default: throw new Error(`Unexpected log level: ${logLevel}`);
3686
- }
3687
- }
3688
- function bindingifyInput(input) {
3689
- if (input === void 0) return [];
3690
- if (typeof input === "string") return [{ import: input }];
3691
- if (Array.isArray(input)) return input.map((src) => ({ import: src }));
3692
- return Object.entries(input).map(([name, import_path]) => {
3693
- return {
3694
- name,
3695
- import: import_path
3696
- };
3697
- });
3698
- }
3699
- function bindingifyJsx(input) {
3700
- switch (input) {
3701
- case false: return BindingJsx.Disable;
3702
- case "react": return BindingJsx.React;
3703
- case "react-jsx": return BindingJsx.ReactJsx;
3704
- case "preserve": return BindingJsx.Preserve;
3705
- default: return void 0;
3706
- }
3707
- }
3708
- function bindingifyWatch(watch$1) {
3709
- if (watch$1) return {
3710
- buildDelay: watch$1.buildDelay,
3711
- skipWrite: watch$1.skipWrite,
3712
- include: normalizedStringOrRegex(watch$1.include),
3713
- exclude: normalizedStringOrRegex(watch$1.exclude)
3714
- };
3715
- }
3716
- function bindingifyTreeshakeOptions(config) {
3717
- if (config === false) return void 0;
3718
- if (config === true || config === void 0) return { moduleSideEffects: true };
3719
- let normalizedConfig = {
3720
- moduleSideEffects: true,
3721
- annotations: config.annotations,
3722
- manualPureFunctions: config.manualPureFunctions,
3723
- unknownGlobalSideEffects: config.unknownGlobalSideEffects
3724
- };
3725
- if (config.moduleSideEffects === void 0) normalizedConfig.moduleSideEffects = true;
3726
- else if (config.moduleSideEffects === "no-external") normalizedConfig.moduleSideEffects = [{
3727
- external: true,
3728
- sideEffects: false
3729
- }, {
3730
- external: false,
3731
- sideEffects: true
3732
- }];
3733
- else normalizedConfig.moduleSideEffects = config.moduleSideEffects;
3734
- return normalizedConfig;
3735
- }
3736
- function bindingifyMakeAbsoluteExternalsRelative(makeAbsoluteExternalsRelative) {
3737
- if (makeAbsoluteExternalsRelative === "ifRelativeSource") return { type: "IfRelativeSource" };
3738
- if (typeof makeAbsoluteExternalsRelative === "boolean") return {
3739
- type: "Bool",
3740
- field0: makeAbsoluteExternalsRelative
3741
- };
3742
- }
3743
-
3744
- //#endregion
3745
- //#region src/utils/plugin/index.ts
3746
- const isPluginHookName = function() {
3747
- const PLUGIN_HOOK_NAMES_SET = new Set(ENUMERATED_PLUGIN_HOOK_NAMES);
3748
- return function isPluginHookName$1(hookName) {
3749
- return PLUGIN_HOOK_NAMES_SET.has(hookName);
3750
- };
3751
- }();
3752
-
3753
- //#endregion
3754
- //#region src/utils/compose-js-plugins.ts
3755
- const unsupportedHookName = [
3756
- "augmentChunkHash",
3757
- "generateBundle",
3758
- "moduleParsed",
3759
- "onLog",
3760
- "options",
3761
- "outputOptions",
3762
- "renderError",
3763
- "renderStart",
3764
- "resolveDynamicImport",
3765
- "writeBundle"
3766
- ];
3767
- const unsupportedHooks = new Set(unsupportedHookName);
3768
- function isUnsupportedHooks(hookName) {
3769
- return unsupportedHooks.has(hookName);
3770
- }
3771
- function createComposedPlugin(plugins) {
3772
- const names = [];
3773
- const batchedHooks = {};
3774
- plugins.forEach((plugin, index) => {
3775
- const pluginName = plugin.name || `Anonymous(index: ${index})`;
3776
- names.push(pluginName);
3777
- t(plugin).forEach((pluginProp) => {
3778
- if (isUnsupportedHooks(pluginProp)) throw new Error(`Failed to compose js plugins. Plugin ${pluginName} has an unsupported hook: ${pluginProp}`);
3779
- if (!isPluginHookName(pluginProp)) return;
3780
- switch (pluginProp) {
3781
- case "buildStart": {
3782
- const handlers = batchedHooks.buildStart ?? [];
3783
- batchedHooks.buildStart = handlers;
3784
- if (plugin.buildStart) handlers.push([plugin.buildStart, plugin]);
3785
- break;
3786
- }
3787
- case "load": {
3788
- const handlers = batchedHooks.load ?? [];
3789
- batchedHooks.load = handlers;
3790
- if (plugin.load) handlers.push([plugin.load, plugin]);
3791
- break;
3792
- }
3793
- case "transform": {
3794
- const handlers = batchedHooks.transform ?? [];
3795
- batchedHooks.transform = handlers;
3796
- if (plugin.transform) handlers.push([plugin.transform, plugin]);
3797
- break;
3798
- }
3799
- case "resolveId": {
3800
- const handlers = batchedHooks.resolveId ?? [];
3801
- batchedHooks.resolveId = handlers;
3802
- if (plugin.resolveId) handlers.push([plugin.resolveId, plugin]);
3803
- break;
3804
- }
3805
- case "buildEnd": {
3806
- const handlers = batchedHooks.buildEnd ?? [];
3807
- batchedHooks.buildEnd = handlers;
3808
- if (plugin.buildEnd) handlers.push([plugin.buildEnd, plugin]);
3809
- break;
3810
- }
3811
- case "renderChunk": {
3812
- const handlers = batchedHooks.renderChunk ?? [];
3813
- batchedHooks.renderChunk = handlers;
3814
- if (plugin.renderChunk) handlers.push([plugin.renderChunk, plugin]);
3815
- break;
3816
- }
3817
- case "banner":
3818
- case "footer":
3819
- case "intro":
3820
- case "outro": {
3821
- const hook = plugin[pluginProp];
3822
- if (hook) (batchedHooks[pluginProp] ??= []).push([hook, plugin]);
3823
- break;
3824
- }
3825
- case "closeBundle": {
3826
- const handlers = batchedHooks.closeBundle ?? [];
3827
- batchedHooks.closeBundle = handlers;
3828
- if (plugin.closeBundle) handlers.push([plugin.closeBundle, plugin]);
3829
- break;
3830
- }
3831
- case "watchChange": {
3832
- const handlers = batchedHooks.watchChange ?? [];
3833
- batchedHooks.watchChange = handlers;
3834
- if (plugin.watchChange) handlers.push([plugin.watchChange, plugin]);
3835
- break;
3836
- }
3837
- case "closeWatcher": {
3838
- const handlers = batchedHooks.closeWatcher ?? [];
3839
- batchedHooks.closeWatcher = handlers;
3840
- if (plugin.closeWatcher) handlers.push([plugin.closeWatcher, plugin]);
3841
- break;
3842
- }
3843
- default: {}
3844
- }
3845
- });
3846
- });
3847
- const composed = { name: `Composed(${names.join(", ")})` };
3848
- const createFixedPluginResolveFnMap = new Map();
3849
- function applyFixedPluginResolveFn(ctx, plugin) {
3850
- const createFixedPluginResolveFn = createFixedPluginResolveFnMap.get(plugin);
3851
- if (createFixedPluginResolveFn) ctx.resolve = createFixedPluginResolveFn(ctx, ctx.resolve.bind(ctx));
3852
- return ctx;
3853
- }
3854
- if (batchedHooks.resolveId) {
3855
- const batchedHandlers = batchedHooks.resolveId;
3856
- const handlerSymbols = batchedHandlers.map(([_handler, plugin]) => Symbol(plugin.name ?? `Anonymous`));
3857
- for (let handlerIdx = 0; handlerIdx < batchedHandlers.length; handlerIdx++) {
3858
- const [_handler, plugin] = batchedHandlers[handlerIdx];
3859
- const handlerSymbol = handlerSymbols[handlerIdx];
3860
- const createFixedPluginResolveFn = (ctx, resolve) => {
3861
- return (source, importer, rawContextResolveOptions) => {
3862
- const contextResolveOptions = rawContextResolveOptions ?? {};
3863
- if (contextResolveOptions.skipSelf) {
3864
- contextResolveOptions[SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF] = handlerSymbol;
3865
- contextResolveOptions.skipSelf = false;
3866
- }
3867
- return resolve(source, importer, contextResolveOptions);
3868
- };
3869
- };
3870
- createFixedPluginResolveFnMap.set(plugin, createFixedPluginResolveFn);
3871
- }
3872
- composed.resolveId = async function(source, importer, rawHookResolveIdOptions) {
3873
- const hookResolveIdOptions = rawHookResolveIdOptions;
3874
- const symbolForCallerThatSkipSelf = hookResolveIdOptions?.[SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF];
3875
- for (let handlerIdx = 0; handlerIdx < batchedHandlers.length; handlerIdx++) {
3876
- const [handler, plugin] = batchedHandlers[handlerIdx];
3877
- const handlerSymbol = handlerSymbols[handlerIdx];
3878
- if (symbolForCallerThatSkipSelf === handlerSymbol) continue;
3879
- const { handler: handlerFn } = normalizeHook(handler);
3880
- const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), source, importer, rawHookResolveIdOptions);
3881
- if (!isNullish(result)) return result;
3882
- }
3883
- };
3884
- }
3885
- t(batchedHooks).forEach((hookName) => {
3886
- switch (hookName) {
3887
- case "resolveId": break;
3888
- case "buildStart": {
3889
- if (batchedHooks.buildStart) {
3890
- const batchedHandlers = batchedHooks.buildStart;
3891
- composed.buildStart = async function(options) {
3892
- await Promise.all(batchedHandlers.map(([handler, plugin]) => {
3893
- const { handler: handlerFn } = normalizeHook(handler);
3894
- return handlerFn.call(applyFixedPluginResolveFn(this, plugin), options);
3895
- }));
3896
- };
3897
- }
3898
- break;
3899
- }
3900
- case "load": {
3901
- if (batchedHooks.load) {
3902
- const batchedHandlers = batchedHooks.load;
3903
- composed.load = async function(id$1) {
3904
- for (const [handler, plugin] of batchedHandlers) {
3905
- const { handler: handlerFn } = normalizeHook(handler);
3906
- const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), id$1);
3907
- if (!isNullish(result)) return result;
3908
- }
3909
- };
3910
- }
3911
- break;
3912
- }
3913
- case "transform": {
3914
- if (batchedHooks.transform) {
3915
- const batchedHandlers = batchedHooks.transform;
3916
- composed.transform = async function(initialCode, id$1, moduleType$1) {
3917
- let code$1 = initialCode;
3918
- let moduleSideEffects = void 0;
3919
- function updateOutput(newCode, newModuleSideEffects) {
3920
- code$1 = newCode;
3921
- moduleSideEffects = newModuleSideEffects ?? void 0;
3922
- }
3923
- for (const [handler, plugin] of batchedHandlers) {
3924
- const { handler: handlerFn } = normalizeHook(handler);
3925
- this.getCombinedSourcemap = () => {
3926
- throw new Error(`The getCombinedSourcemap is not implement in transform hook at composedJsPlugins`);
3927
- };
3928
- const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), code$1, id$1, moduleType$1);
3929
- if (!isNullish(result)) {
3930
- if (typeof result === "string") updateOutput(result);
3931
- else if (result.code) updateOutput(result.code, result.moduleSideEffects);
3932
- }
3933
- }
3934
- return {
3935
- code: code$1,
3936
- moduleSideEffects
3937
- };
3938
- };
3939
- }
3940
- break;
3941
- }
3942
- case "buildEnd": {
3943
- if (batchedHooks.buildEnd) {
3944
- const batchedHandlers = batchedHooks.buildEnd;
3945
- composed.buildEnd = async function(err) {
3946
- await Promise.all(batchedHandlers.map(([handler, plugin]) => {
3947
- const { handler: handlerFn } = normalizeHook(handler);
3948
- return handlerFn.call(applyFixedPluginResolveFn(this, plugin), err);
3949
- }));
3950
- };
3951
- }
3952
- break;
3953
- }
3954
- case "renderChunk": {
3955
- if (batchedHooks.renderChunk) {
3956
- const batchedHandlers = batchedHooks.renderChunk;
3957
- composed.renderChunk = async function(code$1, chunk, options, meta) {
3958
- for (const [handler, plugin] of batchedHandlers) {
3959
- const { handler: handlerFn } = normalizeHook(handler);
3960
- const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), code$1, chunk, options, meta);
3961
- if (!isNullish(result)) return result;
3962
- }
3963
- };
3964
- }
3965
- break;
3966
- }
3967
- case "banner":
3968
- case "footer":
3969
- case "intro":
3970
- case "outro": {
3971
- const hooks = batchedHooks[hookName];
3972
- if (hooks?.length) composed[hookName] = async function(chunk) {
3973
- const ret = [];
3974
- for (const [hook, plugin] of hooks) {
3975
- const { handler } = normalizeHook(hook);
3976
- ret.push(typeof handler === "string" ? handler : await handler.call(applyFixedPluginResolveFn(this, plugin), chunk));
3977
- }
3978
- return ret.join("\n");
3979
- };
3980
- break;
3981
- }
3982
- case "closeBundle": {
3983
- if (batchedHooks.closeBundle) {
3984
- const batchedHandlers = batchedHooks.closeBundle;
3985
- composed.closeBundle = async function() {
3986
- await Promise.all(batchedHandlers.map(([handler, plugin]) => {
3987
- const { handler: handlerFn } = normalizeHook(handler);
3988
- return handlerFn.call(applyFixedPluginResolveFn(this, plugin));
3989
- }));
3990
- };
3991
- }
3992
- break;
3993
- }
3994
- case "watchChange": {
3995
- if (batchedHooks.watchChange) {
3996
- const batchedHandlers = batchedHooks.watchChange;
3997
- composed.watchChange = async function(id$1, event) {
3998
- await Promise.all(batchedHandlers.map(([handler, plugin]) => {
3999
- const { handler: handlerFn } = normalizeHook(handler);
4000
- return handlerFn.call(applyFixedPluginResolveFn(this, plugin), id$1, event);
4001
- }));
4002
- };
4003
- }
4004
- break;
4005
- }
4006
- case "closeWatcher": {
4007
- if (batchedHooks.closeWatcher) {
4008
- const batchedHandlers = batchedHooks.closeWatcher;
4009
- composed.closeWatcher = async function() {
4010
- await Promise.all(batchedHandlers.map(([handler, plugin]) => {
4011
- const { handler: handlerFn } = normalizeHook(handler);
4012
- return handlerFn.call(applyFixedPluginResolveFn(this, plugin));
4013
- }));
4014
- };
4015
- }
4016
- break;
4017
- }
4018
- default: {}
4019
- }
4020
- });
4021
- return composed;
4022
- }
4023
- function isComposablePlugin(plugin) {
4024
- if (plugin instanceof BuiltinPlugin) return false;
4025
- if ("_parallel" in plugin) return false;
4026
- const hasNotComposablePattern = t(plugin).some((hookName) => {
4027
- if (!isPluginHookName(hookName)) return false;
4028
- const OK_TO_COMPOSE = false;
4029
- if (isUnsupportedHooks(hookName)) return !OK_TO_COMPOSE;
4030
- if (plugin[hookName]) {
4031
- const { meta } = normalizeHook(plugin[hookName]);
4032
- if (meta.order === "pre" || meta.order === "post") return !OK_TO_COMPOSE;
4033
- }
4034
- return OK_TO_COMPOSE;
4035
- });
4036
- if (hasNotComposablePattern) return false;
4037
- return true;
4038
- }
4039
- function composeJsPlugins(plugins) {
4040
- const newPlugins = [];
4041
- const toBeComposed = [];
4042
- plugins.forEach((plugin) => {
4043
- if (isComposablePlugin(plugin)) toBeComposed.push(plugin);
4044
- else {
4045
- if (toBeComposed.length > 0) {
4046
- if (toBeComposed.length > 1) newPlugins.push(createComposedPlugin(toBeComposed));
4047
- else newPlugins.push(toBeComposed[0]);
4048
- toBeComposed.length = 0;
4049
- }
4050
- newPlugins.push(plugin);
4051
- }
4052
- });
4053
- if (toBeComposed.length > 0) {
4054
- if (toBeComposed.length > 1) newPlugins.push(createComposedPlugin(toBeComposed));
4055
- else newPlugins.push(toBeComposed[0]);
4056
- toBeComposed.length = 0;
4057
- }
4058
- return newPlugins;
4059
- }
4060
-
4061
- //#endregion
4062
- //#region src/utils/create-bundler-option.ts
4063
- async function createBundlerOptions(inputOptions, outputOptions, watchMode, isClose) {
4064
- const inputPlugins = await normalizePluginOption(inputOptions.plugins);
4065
- const outputPlugins = await normalizePluginOption(outputOptions.plugins);
4066
- const logLevel = inputOptions.logLevel || LOG_LEVEL_INFO;
4067
- const onLog = getLogger(getObjectPlugins(inputPlugins), getOnLog(inputOptions, logLevel), logLevel, watchMode);
4068
- if (!isClose) outputOptions = PluginDriver.callOutputOptionsHook([...inputPlugins, ...outputPlugins], outputOptions, onLog, logLevel, watchMode);
4069
- const normalizedOutputPlugins = await normalizePluginOption(outputOptions.plugins);
4070
- let plugins = [
4071
- ...BUILTIN_PLUGINS,
4072
- ...normalizePlugins(inputPlugins, ANONYMOUS_PLUGIN_PREFIX),
4073
- ...checkOutputPluginOption(normalizePlugins(normalizedOutputPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX), onLog)
4074
- ];
4075
- if (inputOptions.experimental?.enableComposingJsPlugins ?? false) plugins = composeJsPlugins(plugins);
4076
- const parallelPluginInitResult = void 0;
4077
- try {
4078
- const bindingInputOptions = bindingifyInputOptions(plugins, inputOptions, outputOptions, normalizedOutputPlugins, onLog, logLevel, watchMode);
4079
- const bindingOutputOptions = bindingifyOutputOptions(outputOptions);
4080
- return {
4081
- bundlerOptions: {
4082
- inputOptions: bindingInputOptions,
4083
- outputOptions: bindingOutputOptions,
4084
- parallelPluginsRegistry: parallelPluginInitResult?.registry
4085
- },
4086
- inputOptions,
4087
- onLog,
4088
- stopWorkers: parallelPluginInitResult?.stopWorkers
4089
- };
4090
- } catch (e) {
4091
- await parallelPluginInitResult?.stopWorkers();
4092
- throw e;
4093
- }
4094
- }
4095
-
4096
- //#endregion
4097
- //#region src/utils/create-bundler.ts
4098
- let asyncRuntimeShutdown = false;
4099
- async function createBundler(inputOptions, outputOptions, isClose) {
4100
- const option = await createBundlerOptions(inputOptions, outputOptions, false, isClose);
4101
- if (asyncRuntimeShutdown) startAsyncRuntime();
4102
- try {
4103
- return {
4104
- bundler: new Bundler(option.bundlerOptions),
4105
- stopWorkers: option.stopWorkers,
4106
- shutdown: () => {
4107
- shutdownAsyncRuntime();
4108
- asyncRuntimeShutdown = true;
4109
- }
4110
- };
4111
- } catch (e) {
4112
- await option.stopWorkers?.();
4113
- throw e;
4114
- }
4115
- }
4116
-
4117
- //#endregion
4118
- //#region src/api/rolldown/rolldown-build.ts
4119
- Symbol.asyncDispose ??= Symbol("Symbol.asyncDispose");
4120
- var RolldownBuild = class {
4121
- #inputOptions;
4122
- #bundler;
4123
- constructor(inputOptions) {
4124
- this.#inputOptions = inputOptions;
4125
- }
4126
- get closed() {
4127
- return this.#bundler?.bundler.closed ?? false;
4128
- }
4129
- async #getBundlerWithStopWorker(outputOptions, isClose) {
4130
- if (this.#bundler) await this.#bundler.stopWorkers?.();
4131
- return this.#bundler = await createBundler(this.#inputOptions, outputOptions, isClose);
4132
- }
4133
- async generate(outputOptions = {}) {
4134
- validateOption("output", outputOptions);
4135
- const { bundler } = await this.#getBundlerWithStopWorker(outputOptions);
4136
- const output = await bundler.generate();
4137
- return transformToRollupOutput(output);
4138
- }
4139
- async write(outputOptions = {}) {
4140
- validateOption("output", outputOptions);
4141
- const { bundler } = await this.#getBundlerWithStopWorker(outputOptions);
4142
- const output = await bundler.write();
4143
- return transformToRollupOutput(output);
4144
- }
4145
- async close() {
4146
- const { bundler, stopWorkers, shutdown } = await this.#getBundlerWithStopWorker({}, true);
4147
- await stopWorkers?.();
4148
- await bundler.close();
4149
- shutdown();
4150
- }
4151
- async [Symbol.asyncDispose]() {
4152
- await this.close();
4153
- }
4154
- async generateHmrPatch(changedFiles) {
4155
- return this.#bundler?.bundler.generateHmrPatch(changedFiles);
4156
- }
4157
- async hmrInvalidate(file, firstInvalidatedBy) {
4158
- return this.#bundler?.bundler.hmrInvalidate(file, firstInvalidatedBy);
4159
- }
4160
- get watchFiles() {
4161
- return this.#bundler?.bundler.getWatchFiles() ?? Promise.resolve([]);
4162
- }
4163
- };
4164
-
4165
- //#endregion
4166
- //#region src/api/rolldown/index.ts
4167
- const rolldown = async (input) => {
4168
- validateOption("input", input);
4169
- const inputOptions = await PluginDriver.callOptionsHook(input);
4170
- return new RolldownBuild(inputOptions);
4171
- };
4172
-
4173
- //#endregion
4174
- //#region src/api/build.ts
4175
- async function build(options) {
4176
- if (Array.isArray(options)) return Promise.all(options.map((opts) => build(opts)));
4177
- else {
4178
- const { output, write = true,...inputOptions } = options;
4179
- const build$1 = await rolldown(inputOptions);
4180
- try {
4181
- if (write) return await build$1.write(output);
4182
- else return await build$1.generate(output);
4183
- } finally {
4184
- await build$1.close();
4185
- }
4186
- }
4187
- }
4188
-
4189
- //#endregion
4190
- //#region src/api/watch/watch-emitter.ts
4191
- var WatcherEmitter = class {
4192
- listeners = new Map();
4193
- timer;
4194
- constructor() {
4195
- this.timer = setInterval(() => {}, 1e9);
4196
- }
4197
- on(event, listener) {
4198
- const listeners = this.listeners.get(event);
4199
- if (listeners) listeners.push(listener);
4200
- else this.listeners.set(event, [listener]);
4201
- return this;
4202
- }
4203
- off(event, listener) {
4204
- const listeners = this.listeners.get(event);
4205
- if (listeners) {
4206
- const index = listeners.indexOf(listener);
4207
- if (index !== -1) listeners.splice(index, 1);
4208
- }
4209
- return this;
4210
- }
4211
- async onEvent(event) {
4212
- const listeners = this.listeners.get(event.eventKind());
4213
- if (listeners) switch (event.eventKind()) {
4214
- case "close":
4215
- case "restart":
4216
- for (const listener of listeners) await listener();
4217
- break;
4218
- case "event":
4219
- for (const listener of listeners) {
4220
- const code$1 = event.bundleEventKind();
4221
- switch (code$1) {
4222
- case "BUNDLE_END":
4223
- const { duration, output, result } = event.bundleEndData();
4224
- await listener({
4225
- code: "BUNDLE_END",
4226
- duration,
4227
- output: [output],
4228
- result
4229
- });
4230
- break;
4231
- case "ERROR":
4232
- const data = event.bundleErrorData();
4233
- await listener({
4234
- code: "ERROR",
4235
- error: normalizeErrors(data.error),
4236
- result: data.result
4237
- });
4238
- break;
4239
- default:
4240
- await listener({ code: code$1 });
4241
- break;
4242
- }
4243
- }
4244
- break;
4245
- case "change":
4246
- for (const listener of listeners) {
4247
- const { path: path$1, kind } = event.watchChangeData();
4248
- await listener(path$1, { event: kind });
4249
- }
4250
- break;
4251
- default: throw new Error(`Unknown event: ${event}`);
4252
- }
4253
- }
4254
- async close() {
4255
- clearInterval(this.timer);
4256
- }
4257
- };
4258
-
4259
- //#endregion
4260
- //#region src/api/watch/watcher.ts
4261
- var Watcher = class {
4262
- closed;
4263
- inner;
4264
- emitter;
4265
- stopWorkers;
4266
- constructor(emitter, inner, stopWorkers) {
4267
- this.closed = false;
4268
- this.inner = inner;
4269
- this.emitter = emitter;
4270
- const originClose = emitter.close.bind(emitter);
4271
- emitter.close = async () => {
4272
- await this.close();
4273
- originClose();
4274
- };
4275
- this.stopWorkers = stopWorkers;
4276
- }
4277
- async close() {
4278
- if (this.closed) return;
4279
- this.closed = true;
4280
- for (const stop of this.stopWorkers) await stop?.();
4281
- await this.inner.close();
4282
- shutdownAsyncRuntime();
4283
- }
4284
- start() {
4285
- process.nextTick(() => this.inner.start(this.emitter.onEvent.bind(this.emitter)));
4286
- }
4287
- };
4288
- async function createWatcher(emitter, input) {
4289
- const options = arraify(input);
4290
- const bundlerOptions = await Promise.all(options.map((option) => arraify(option.output || {}).map(async (output) => {
4291
- const inputOptions = await PluginDriver.callOptionsHook(option, true);
4292
- return createBundlerOptions(inputOptions, output, true);
4293
- })).flat());
4294
- const notifyOptions = getValidNotifyOption(bundlerOptions);
4295
- const bindingWatcher = new BindingWatcher(bundlerOptions.map((option) => option.bundlerOptions), notifyOptions);
4296
- const watcher = new Watcher(emitter, bindingWatcher, bundlerOptions.map((option) => option.stopWorkers));
4297
- watcher.start();
4298
- }
4299
- function getValidNotifyOption(bundlerOptions) {
4300
- let result;
4301
- for (const option of bundlerOptions) if (option.inputOptions.watch) {
4302
- const notifyOption = option.inputOptions.watch.notify;
4303
- if (notifyOption) if (result) {
4304
- option.onLog(LOG_LEVEL_WARN, logMultiplyNotifyOption());
4305
- return result;
4306
- } else result = notifyOption;
4307
- }
4308
- }
4309
-
4310
- //#endregion
4311
- //#region src/api/watch/index.ts
4312
- const watch = (input) => {
4313
- const emitter = new WatcherEmitter();
4314
- createWatcher(emitter, input);
4315
- return emitter;
4316
- };
4317
-
4318
- //#endregion
4319
- //#region src/utils/define-config.ts
4320
- function defineConfig(config) {
4321
- return config;
4322
- }
4323
-
4324
- //#endregion
4325
- //#region src/index.ts
4326
- const VERSION = version;
4327
-
4328
- //#endregion
4329
- export { BuiltinPlugin, VERSION, assetPlugin, build, buildImportAnalysisPlugin, composeJsPlugins, createBundler, defineConfig, dynamicImportVarsPlugin, handleOutputErrors, importGlobPlugin, isolatedDeclarationPlugin, jsonPlugin, loadFallbackPlugin, manifestPlugin, moduleFederationPlugin, modulePreloadPolyfillPlugin, normalizedStringOrRegex, reporterPlugin, rolldown, viteResolvePlugin, wasmFallbackPlugin, wasmHelperPlugin, watch, webWorkerPostPlugin };