rolldown 1.0.0-beta.35 → 1.0.0-beta.36

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