rolldown 1.0.0-beta.4-commit.d3748b6 → 1.0.0-beta.40

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