rolldown 1.0.0-beta.3-commit.e170e6e → 1.0.0-beta.30

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