rolldown 1.0.0-beta.50 → 1.0.0-beta.52

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