@rolldown/browser 1.0.0-beta.7-commit.a0a7d95

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 (121) hide show
  1. package/LICENSE +25 -0
  2. package/bin/cli.mjs +2 -0
  3. package/dist/browser-bundler.mjs +3514 -0
  4. package/dist/browser.js +4626 -0
  5. package/dist/cli.cjs +1759 -0
  6. package/dist/cli.mjs +1828 -0
  7. package/dist/experimental-index.cjs +87 -0
  8. package/dist/experimental-index.mjs +67 -0
  9. package/dist/index.cjs +9 -0
  10. package/dist/index.mjs +5 -0
  11. package/dist/parallel-plugin-worker.cjs +43 -0
  12. package/dist/parallel-plugin-worker.mjs +48 -0
  13. package/dist/parallel-plugin.cjs +9 -0
  14. package/dist/parallel-plugin.mjs +8 -0
  15. package/dist/parse-ast-index.cjs +4 -0
  16. package/dist/parse-ast-index.mjs +4 -0
  17. package/dist/rolldown-binding.wasi-browser.js +102 -0
  18. package/dist/rolldown-binding.wasi.cjs +127 -0
  19. package/dist/rolldown-binding.wasm32-wasi.wasm +0 -0
  20. package/dist/shared/chunk-BuCFLigr.mjs +12 -0
  21. package/dist/shared/chunk-Dc32QXFI.cjs +31 -0
  22. package/dist/shared/parse-ast-index-C29iO6Jv.cjs +316 -0
  23. package/dist/shared/parse-ast-index-GcZLh6_d.mjs +273 -0
  24. package/dist/shared/prompt-B3VJLbs9.mjs +854 -0
  25. package/dist/shared/prompt-wpCBKCzA.cjs +855 -0
  26. package/dist/shared/src-6_rb-jCl.cjs +3147 -0
  27. package/dist/shared/src-QrPvO0Ec.mjs +4375 -0
  28. package/dist/types/api/build.d.ts +18 -0
  29. package/dist/types/api/experimental.d.ts +7 -0
  30. package/dist/types/api/rolldown/index.d.ts +3 -0
  31. package/dist/types/api/rolldown/rolldown-build.d.ts +15 -0
  32. package/dist/types/api/watch/index.d.ts +3 -0
  33. package/dist/types/api/watch/watch-emitter.d.ts +31 -0
  34. package/dist/types/api/watch/watcher.d.ts +13 -0
  35. package/dist/types/binding.d.ts +1504 -0
  36. package/dist/types/builtin-plugin/alias-plugin.d.ts +10 -0
  37. package/dist/types/builtin-plugin/constructors.d.ts +22 -0
  38. package/dist/types/builtin-plugin/replace-plugin.d.ts +27 -0
  39. package/dist/types/builtin-plugin/transform-plugin.d.ts +9 -0
  40. package/dist/types/builtin-plugin/utils.d.ts +8 -0
  41. package/dist/types/cli/arguments/alias.d.ts +16 -0
  42. package/dist/types/cli/arguments/index.d.ts +15 -0
  43. package/dist/types/cli/arguments/normalize.d.ts +16 -0
  44. package/dist/types/cli/arguments/utils.d.ts +8 -0
  45. package/dist/types/cli/commands/bundle.d.ts +3 -0
  46. package/dist/types/cli/commands/help.d.ts +1 -0
  47. package/dist/types/cli/index.d.ts +1 -0
  48. package/dist/types/cli/load-config.d.ts +5 -0
  49. package/dist/types/cli/logger.d.ts +5 -0
  50. package/dist/types/constants/plugin-context.d.ts +7 -0
  51. package/dist/types/constants/plugin.d.ts +45 -0
  52. package/dist/types/experimental-index.d.ts +9 -0
  53. package/dist/types/index.d.ts +31 -0
  54. package/dist/types/log/log-handler.d.ts +4 -0
  55. package/dist/types/log/logger.d.ts +6 -0
  56. package/dist/types/log/logging.d.ts +12 -0
  57. package/dist/types/log/logs.d.ts +18 -0
  58. package/dist/types/options/generated/checks-options.d.ts +57 -0
  59. package/dist/types/options/input-options.d.ts +185 -0
  60. package/dist/types/options/normalized-input-options.d.ts +18 -0
  61. package/dist/types/options/normalized-output-options.d.ts +70 -0
  62. package/dist/types/options/output-options.d.ts +182 -0
  63. package/dist/types/options/watch-options.d.ts +5 -0
  64. package/dist/types/parallel-plugin-worker.d.ts +1 -0
  65. package/dist/types/parallel-plugin.d.ts +1 -0
  66. package/dist/types/parse-ast-index.d.ts +5 -0
  67. package/dist/types/plugin/bindingify-build-hooks.d.ts +10 -0
  68. package/dist/types/plugin/bindingify-hook-filter.d.ts +7 -0
  69. package/dist/types/plugin/bindingify-output-hooks.d.ts +14 -0
  70. package/dist/types/plugin/bindingify-plugin-hook-meta.d.ts +8 -0
  71. package/dist/types/plugin/bindingify-plugin.d.ts +17 -0
  72. package/dist/types/plugin/bindingify-watch-hooks.d.ts +5 -0
  73. package/dist/types/plugin/hook-filter.d.ts +49 -0
  74. package/dist/types/plugin/index.d.ts +141 -0
  75. package/dist/types/plugin/minimal-plugin-context.d.ts +24 -0
  76. package/dist/types/plugin/parallel-plugin-implementation.d.ts +10 -0
  77. package/dist/types/plugin/parallel-plugin.d.ts +9 -0
  78. package/dist/types/plugin/plugin-context-data.d.ts +21 -0
  79. package/dist/types/plugin/plugin-context.d.ts +67 -0
  80. package/dist/types/plugin/plugin-driver.d.ts +10 -0
  81. package/dist/types/plugin/transform-plugin-context.d.ts +28 -0
  82. package/dist/types/plugin/with-filter.d.ts +10 -0
  83. package/dist/types/types/assert.d.ts +14 -0
  84. package/dist/types/types/config-export.d.ts +5 -0
  85. package/dist/types/types/misc.d.ts +40 -0
  86. package/dist/types/types/module-info.d.ts +15 -0
  87. package/dist/types/types/module-side-effects.d.ts +12 -0
  88. package/dist/types/types/output-bundle.d.ts +4 -0
  89. package/dist/types/types/rolldown-options.d.ts +5 -0
  90. package/dist/types/types/rolldown-output.d.ts +66 -0
  91. package/dist/types/types/schema.d.ts +33 -0
  92. package/dist/types/types/sourcemap.d.ts +14 -0
  93. package/dist/types/types/utils.d.ts +13 -0
  94. package/dist/types/types.d.ts +7 -0
  95. package/dist/types/utils/asset-source.d.ts +4 -0
  96. package/dist/types/utils/async-flatten.d.ts +1 -0
  97. package/dist/types/utils/bindingify-input-options.d.ts +7 -0
  98. package/dist/types/utils/bindingify-output-options.d.ts +5 -0
  99. package/dist/types/utils/code-frame.d.ts +1 -0
  100. package/dist/types/utils/compose-js-plugins.d.ts +2 -0
  101. package/dist/types/utils/create-bundler-option.d.ts +11 -0
  102. package/dist/types/utils/create-bundler.d.ts +9 -0
  103. package/dist/types/utils/define-config.d.ts +5 -0
  104. package/dist/types/utils/error.d.ts +2 -0
  105. package/dist/types/utils/initialize-parallel-plugins.d.ts +17 -0
  106. package/dist/types/utils/misc.d.ts +7 -0
  107. package/dist/types/utils/normalize-hook.d.ts +7 -0
  108. package/dist/types/utils/normalize-plugin-option.d.ts +13 -0
  109. package/dist/types/utils/normalize-string-or-regex.d.ts +2 -0
  110. package/dist/types/utils/plugin/index.d.ts +2 -0
  111. package/dist/types/utils/resolved-external.d.ts +4 -0
  112. package/dist/types/utils/transform-module-info.d.ts +4 -0
  113. package/dist/types/utils/transform-rendered-chunk.d.ts +4 -0
  114. package/dist/types/utils/transform-rendered-module.d.ts +3 -0
  115. package/dist/types/utils/transform-side-effects.d.ts +3 -0
  116. package/dist/types/utils/transform-sourcemap.d.ts +3 -0
  117. package/dist/types/utils/transform-to-rollup-output.d.ts +11 -0
  118. package/dist/types/utils/validator.d.ts +6 -0
  119. package/dist/wasi-worker-browser.mjs +39 -0
  120. package/dist/wasi-worker.mjs +63 -0
  121. package/package.json +85 -0
@@ -0,0 +1,3514 @@
1
+ import { BindingHookSideEffects, BindingLogLevel, BindingPluginOrder, BindingWatcher, Bundler, parseSync, shutdownAsyncRuntime, startAsyncRuntime } from "./rolldown-binding.wasi-browser.js";
2
+ import colors from "ansis";
3
+ import "@valibot/to-json-schema";
4
+ import * as v from "valibot";
5
+
6
+ //#region package.json
7
+ var version = "1.0.0-beta.7-commit.a0a7d95";
8
+
9
+ //#endregion
10
+ //#region src/builtin-plugin/utils.ts
11
+ function bindingifyBuiltInPlugin(plugin) {
12
+ return {
13
+ __name: plugin.name,
14
+ options: plugin._options
15
+ };
16
+ }
17
+
18
+ //#endregion
19
+ //#region src/builtin-plugin/constructors.ts
20
+ var BuiltinPlugin = class {
21
+ constructor(name, _options) {
22
+ this.name = name;
23
+ this._options = _options;
24
+ }
25
+ };
26
+
27
+ //#endregion
28
+ //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
29
+ let _lazyMatch = () => {
30
+ var __lib__ = (() => {
31
+ var m = Object.defineProperty, V = Object.getOwnPropertyDescriptor, G = Object.getOwnPropertyNames, T = Object.prototype.hasOwnProperty, q = (r, e) => {
32
+ for (var n in e) m(r, n, {
33
+ get: e[n],
34
+ enumerable: true
35
+ });
36
+ }, H = (r, e, n, a) => {
37
+ if (e && typeof e == "object" || typeof e == "function") for (let t$1 of G(e)) !T.call(r, t$1) && t$1 !== n && m(r, t$1, {
38
+ get: () => e[t$1],
39
+ enumerable: !(a = V(e, t$1)) || a.enumerable
40
+ });
41
+ return r;
42
+ }, J = (r) => H(m({}, "__esModule", { value: true }), r), w = {};
43
+ q(w, { default: () => re });
44
+ var A = (r) => Array.isArray(r), d = (r) => typeof r == "function", Q = (r) => r.length === 0, W = (r) => typeof r == "number", K = (r) => typeof r == "object" && r !== null, X = (r) => r instanceof RegExp, b = (r) => typeof r == "string", h = (r) => r === void 0, Y = (r) => {
45
+ const e = new Map();
46
+ return (n) => {
47
+ const a = e.get(n);
48
+ if (a) return a;
49
+ const t$1 = r(n);
50
+ return e.set(n, t$1), t$1;
51
+ };
52
+ }, rr = (r, e, n = {}) => {
53
+ const a = {
54
+ cache: {},
55
+ input: r,
56
+ index: 0,
57
+ indexMax: 0,
58
+ options: n,
59
+ output: []
60
+ };
61
+ if (v$1(e)(a) && a.index === r.length) return a.output;
62
+ throw new Error(`Failed to parse at index ${a.indexMax}`);
63
+ }, i = (r, e) => A(r) ? er(r, e) : b(r) ? ar(r, e) : nr(r, e), er = (r, e) => {
64
+ const n = {};
65
+ for (const a of r) {
66
+ if (a.length !== 1) throw new Error(`Invalid character: "${a}"`);
67
+ const t$1 = a.charCodeAt(0);
68
+ n[t$1] = true;
69
+ }
70
+ return (a) => {
71
+ const t$1 = a.index, o = a.input;
72
+ for (; a.index < o.length && o.charCodeAt(a.index) in n;) a.index += 1;
73
+ const u$2 = a.index;
74
+ if (u$2 > t$1) {
75
+ if (!h(e) && !a.options.silent) {
76
+ const s = a.input.slice(t$1, u$2), c = d(e) ? e(s, o, String(t$1)) : e;
77
+ h(c) || a.output.push(c);
78
+ }
79
+ a.indexMax = Math.max(a.indexMax, a.index);
80
+ }
81
+ return true;
82
+ };
83
+ }, nr = (r, e) => {
84
+ const n = r.source, a = r.flags.replace(/y|$/, "y"), t$1 = new RegExp(n, a);
85
+ return g((o) => {
86
+ t$1.lastIndex = o.index;
87
+ const u$2 = t$1.exec(o.input);
88
+ if (u$2) {
89
+ if (!h(e) && !o.options.silent) {
90
+ const s = d(e) ? e(...u$2, o.input, String(o.index)) : e;
91
+ h(s) || o.output.push(s);
92
+ }
93
+ return o.index += u$2[0].length, o.indexMax = Math.max(o.indexMax, o.index), true;
94
+ } else return false;
95
+ });
96
+ }, ar = (r, e) => (n) => {
97
+ if (n.input.startsWith(r, n.index)) {
98
+ if (!h(e) && !n.options.silent) {
99
+ const t$1 = d(e) ? e(r, n.input, String(n.index)) : e;
100
+ h(t$1) || n.output.push(t$1);
101
+ }
102
+ return n.index += r.length, n.indexMax = Math.max(n.indexMax, n.index), true;
103
+ } else return false;
104
+ }, C = (r, e, n, a) => {
105
+ const t$1 = v$1(r);
106
+ return g(_(M((o) => {
107
+ let u$2 = 0;
108
+ for (; u$2 < n;) {
109
+ const s = o.index;
110
+ if (!t$1(o) || (u$2 += 1, o.index === s)) break;
111
+ }
112
+ return u$2 >= e;
113
+ })));
114
+ }, tr = (r, e) => C(r, 0, 1), f = (r, e) => C(r, 0, Infinity), x = (r, e) => {
115
+ const n = r.map(v$1);
116
+ return g(_(M((a) => {
117
+ for (let t$1 = 0, o = n.length; t$1 < o; t$1++) if (!n[t$1](a)) return false;
118
+ return true;
119
+ })));
120
+ }, l = (r, e) => {
121
+ const n = r.map(v$1);
122
+ return g(_((a) => {
123
+ for (let t$1 = 0, o = n.length; t$1 < o; t$1++) if (n[t$1](a)) return true;
124
+ return false;
125
+ }));
126
+ }, M = (r, e = false) => {
127
+ const n = v$1(r);
128
+ return (a) => {
129
+ const t$1 = a.index, o = a.output.length, u$2 = n(a);
130
+ return (!u$2 || e) && (a.index = t$1, a.output.length !== o && (a.output.length = o)), u$2;
131
+ };
132
+ }, _ = (r, e) => {
133
+ const n = v$1(r);
134
+ return n;
135
+ }, g = (() => {
136
+ let r = 0;
137
+ return (e) => {
138
+ const n = v$1(e), a = r += 1;
139
+ return (t$1) => {
140
+ var o;
141
+ if (t$1.options.memoization === false) return n(t$1);
142
+ const u$2 = t$1.index, s = (o = t$1.cache)[a] || (o[a] = new Map()), c = s.get(u$2);
143
+ if (c === false) return false;
144
+ if (W(c)) return t$1.index = c, true;
145
+ if (c) return t$1.index = c.index, c.output?.length && t$1.output.push(...c.output), true;
146
+ {
147
+ const Z = t$1.output.length;
148
+ if (n(t$1)) {
149
+ const D = t$1.index, U = t$1.output.length;
150
+ if (U > Z) {
151
+ const ee = t$1.output.slice(Z, U);
152
+ s.set(u$2, {
153
+ index: D,
154
+ output: ee
155
+ });
156
+ } else s.set(u$2, D);
157
+ return true;
158
+ } else return s.set(u$2, false), false;
159
+ }
160
+ };
161
+ };
162
+ })(), E = (r) => {
163
+ let e;
164
+ return (n) => (e || (e = v$1(r())), e(n));
165
+ }, v$1 = Y((r) => {
166
+ if (d(r)) return Q(r) ? E(r) : r;
167
+ if (b(r) || X(r)) return i(r);
168
+ if (A(r)) return x(r);
169
+ if (K(r)) return l(Object.values(r));
170
+ throw new Error("Invalid rule");
171
+ }), P = "abcdefghijklmnopqrstuvwxyz", ir = (r) => {
172
+ let e = "";
173
+ for (; r > 0;) {
174
+ const n = (r - 1) % 26;
175
+ e = P[n] + e, r = Math.floor((r - 1) / 26);
176
+ }
177
+ return e;
178
+ }, O = (r) => {
179
+ let e = 0;
180
+ for (let n = 0, a = r.length; n < a; n++) e = e * 26 + P.indexOf(r[n]) + 1;
181
+ return e;
182
+ }, S = (r, e) => {
183
+ if (e < r) return S(e, r);
184
+ const n = [];
185
+ for (; r <= e;) n.push(r++);
186
+ return n;
187
+ }, or = (r, e, n) => S(r, e).map((a) => String(a).padStart(n, "0")), R = (r, e) => S(O(r), O(e)).map(ir), p = (r) => r, z = (r) => ur((e) => rr(e, r, { memoization: false }).join("")), ur = (r) => {
188
+ const e = {};
189
+ return (n) => e[n] ?? (e[n] = r(n));
190
+ }, sr = i(/^\*\*\/\*$/, ".*"), cr = i(/^\*\*\/(\*)?([ a-zA-Z0-9._-]+)$/, (r, e, n) => `.*${e ? "" : "(?:^|/)"}${n.replaceAll(".", "\\.")}`), lr = i(/^\*\*\/(\*)?([ a-zA-Z0-9._-]*)\{([ a-zA-Z0-9._-]+(?:,[ a-zA-Z0-9._-]+)*)\}$/, (r, e, n, a) => `.*${e ? "" : "(?:^|/)"}${n.replaceAll(".", "\\.")}(?:${a.replaceAll(",", "|").replaceAll(".", "\\.")})`), y = i(/\\./, p), pr = i(/[$.*+?^(){}[\]\|]/, (r) => `\\${r}`), vr = i(/./, p), hr = i(/^(?:!!)*!(.*)$/, (r, e) => `(?!^${L(e)}$).*?`), dr = i(/^(!!)+/, ""), fr = l([hr, dr]), xr = i(/\/(\*\*\/)+/, "(?:/.+/|/)"), gr = i(/^(\*\*\/)+/, "(?:^|.*/)"), mr = i(/\/(\*\*)$/, "(?:/.*|$)"), _r = i(/\*\*/, ".*"), j = l([
191
+ xr,
192
+ gr,
193
+ mr,
194
+ _r
195
+ ]), Sr = i(/\*\/(?!\*\*\/)/, "[^/]*/"), yr = i(/\*/, "[^/]*"), N = l([Sr, yr]), k = i("?", "[^/]"), $r = i("[", p), wr = i("]", p), Ar = i(/[!^]/, "^/"), br = i(/[a-z]-[a-z]|[0-9]-[0-9]/i, p), Cr = i(/[$.*+?^(){}[\|]/, (r) => `\\${r}`), Mr = i(/[^\]]/, p), Er = l([
196
+ y,
197
+ Cr,
198
+ br,
199
+ Mr
200
+ ]), B = x([
201
+ $r,
202
+ tr(Ar),
203
+ f(Er),
204
+ wr
205
+ ]), Pr = i("{", "(?:"), Or = i("}", ")"), Rr = i(/(\d+)\.\.(\d+)/, (r, e, n) => or(+e, +n, Math.min(e.length, n.length)).join("|")), zr = i(/([a-z]+)\.\.([a-z]+)/, (r, e, n) => R(e, n).join("|")), jr = i(/([A-Z]+)\.\.([A-Z]+)/, (r, e, n) => R(e.toLowerCase(), n.toLowerCase()).join("|").toUpperCase()), Nr = l([
206
+ Rr,
207
+ zr,
208
+ jr
209
+ ]), I = x([
210
+ Pr,
211
+ Nr,
212
+ Or
213
+ ]), kr = i("{", "(?:"), Br = i("}", ")"), Ir = i(",", "|"), Fr = i(/[$.*+?^(){[\]\|]/, (r) => `\\${r}`), Lr = i(/[^}]/, p), Zr = E(() => F), Dr = l([
214
+ j,
215
+ N,
216
+ k,
217
+ B,
218
+ I,
219
+ Zr,
220
+ y,
221
+ Fr,
222
+ Ir,
223
+ Lr
224
+ ]), F = x([
225
+ kr,
226
+ f(Dr),
227
+ Br
228
+ ]), Ur = f(l([
229
+ sr,
230
+ cr,
231
+ lr,
232
+ fr,
233
+ j,
234
+ N,
235
+ k,
236
+ B,
237
+ I,
238
+ F,
239
+ y,
240
+ pr,
241
+ vr
242
+ ])), Vr = Ur, Gr = z(Vr), L = Gr, Tr = i(/\\./, p), qr = i(/./, p), Hr = i(/\*\*\*+/, "*"), Jr = i(/([^/{[(!])\*\*/, (r, e) => `${e}*`), Qr = i(/(^|.)\*\*(?=[^*/)\]}])/, (r, e) => `${e}*`), Wr = f(l([
243
+ Tr,
244
+ Hr,
245
+ Jr,
246
+ Qr,
247
+ qr
248
+ ])), Kr = Wr, Xr = z(Kr), Yr = Xr, $ = (r, e) => {
249
+ const n = Array.isArray(r) ? r : [r];
250
+ if (!n.length) return false;
251
+ const a = n.map($.compile), t$1 = n.every((s) => /(\/(?:\*\*)?|\[\/\])$/.test(s)), o = e.replace(/[\\\/]+/g, "/").replace(/\/$/, t$1 ? "/" : "");
252
+ return a.some((s) => s.test(o));
253
+ };
254
+ $.compile = (r) => new RegExp(`^${L(Yr(r))}$`, "s");
255
+ var re = $;
256
+ return J(w);
257
+ })();
258
+ return __lib__.default || __lib__;
259
+ };
260
+ let _match;
261
+ const zeptomatch = (path, pattern) => {
262
+ if (!_match) {
263
+ _match = _lazyMatch();
264
+ _lazyMatch = null;
265
+ }
266
+ return _match(path, pattern);
267
+ };
268
+ const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
269
+ function normalizeWindowsPath(input = "") {
270
+ if (!input) return input;
271
+ return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
272
+ }
273
+ const _UNC_REGEX = /^[/\\]{2}/;
274
+ const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
275
+ const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
276
+ const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
277
+ const _EXTNAME_RE = /.(\.[^./]+|\.)$/;
278
+ const _PATH_ROOT_RE = /^[/\\]|^[a-zA-Z]:[/\\]/;
279
+ const sep = "/";
280
+ const normalize = function(path) {
281
+ if (path.length === 0) return ".";
282
+ path = normalizeWindowsPath(path);
283
+ const isUNCPath = path.match(_UNC_REGEX);
284
+ const isPathAbsolute = isAbsolute(path);
285
+ const trailingSeparator = path[path.length - 1] === "/";
286
+ path = normalizeString(path, !isPathAbsolute);
287
+ if (path.length === 0) {
288
+ if (isPathAbsolute) return "/";
289
+ return trailingSeparator ? "./" : ".";
290
+ }
291
+ if (trailingSeparator) path += "/";
292
+ if (_DRIVE_LETTER_RE.test(path)) path += "/";
293
+ if (isUNCPath) {
294
+ if (!isPathAbsolute) return `//./${path}`;
295
+ return `//${path}`;
296
+ }
297
+ return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path;
298
+ };
299
+ const join = function(...segments) {
300
+ let path = "";
301
+ for (const seg of segments) {
302
+ if (!seg) continue;
303
+ if (path.length > 0) {
304
+ const pathTrailing = path[path.length - 1] === "/";
305
+ const segLeading = seg[0] === "/";
306
+ const both = pathTrailing && segLeading;
307
+ if (both) path += seg.slice(1);
308
+ else path += pathTrailing || segLeading ? seg : `/${seg}`;
309
+ } else path += seg;
310
+ }
311
+ return normalize(path);
312
+ };
313
+ function cwd() {
314
+ if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
315
+ return "/";
316
+ }
317
+ const resolve = function(...arguments_) {
318
+ arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
319
+ let resolvedPath = "";
320
+ let resolvedAbsolute = false;
321
+ for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
322
+ const path = index >= 0 ? arguments_[index] : cwd();
323
+ if (!path || path.length === 0) continue;
324
+ resolvedPath = `${path}/${resolvedPath}`;
325
+ resolvedAbsolute = isAbsolute(path);
326
+ }
327
+ resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
328
+ if (resolvedAbsolute && !isAbsolute(resolvedPath)) return `/${resolvedPath}`;
329
+ return resolvedPath.length > 0 ? resolvedPath : ".";
330
+ };
331
+ function normalizeString(path, allowAboveRoot) {
332
+ let res = "";
333
+ let lastSegmentLength = 0;
334
+ let lastSlash = -1;
335
+ let dots = 0;
336
+ let char = null;
337
+ for (let index = 0; index <= path.length; ++index) {
338
+ if (index < path.length) char = path[index];
339
+ else if (char === "/") break;
340
+ else char = "/";
341
+ if (char === "/") {
342
+ if (lastSlash === index - 1 || dots === 1);
343
+ else if (dots === 2) {
344
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
345
+ if (res.length > 2) {
346
+ const lastSlashIndex = res.lastIndexOf("/");
347
+ if (lastSlashIndex === -1) {
348
+ res = "";
349
+ lastSegmentLength = 0;
350
+ } else {
351
+ res = res.slice(0, lastSlashIndex);
352
+ lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
353
+ }
354
+ lastSlash = index;
355
+ dots = 0;
356
+ continue;
357
+ } else if (res.length > 0) {
358
+ res = "";
359
+ lastSegmentLength = 0;
360
+ lastSlash = index;
361
+ dots = 0;
362
+ continue;
363
+ }
364
+ }
365
+ if (allowAboveRoot) {
366
+ res += res.length > 0 ? "/.." : "..";
367
+ lastSegmentLength = 2;
368
+ }
369
+ } else {
370
+ if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
371
+ else res = path.slice(lastSlash + 1, index);
372
+ lastSegmentLength = index - lastSlash - 1;
373
+ }
374
+ lastSlash = index;
375
+ dots = 0;
376
+ } else if (char === "." && dots !== -1) ++dots;
377
+ else dots = -1;
378
+ }
379
+ return res;
380
+ }
381
+ const isAbsolute = function(p) {
382
+ return _IS_ABSOLUTE_RE.test(p);
383
+ };
384
+ const toNamespacedPath = function(p) {
385
+ return normalizeWindowsPath(p);
386
+ };
387
+ const extname = function(p) {
388
+ if (p === "..") return "";
389
+ const match = _EXTNAME_RE.exec(normalizeWindowsPath(p));
390
+ return match && match[1] || "";
391
+ };
392
+ const relative = function(from, to) {
393
+ const _from = resolve(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
394
+ const _to = resolve(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
395
+ if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) return _to.join("/");
396
+ const _fromCopy = [..._from];
397
+ for (const segment of _fromCopy) {
398
+ if (_to[0] !== segment) break;
399
+ _from.shift();
400
+ _to.shift();
401
+ }
402
+ return [..._from.map(() => ".."), ..._to].join("/");
403
+ };
404
+ const dirname = function(p) {
405
+ const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
406
+ if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) segments[0] += "/";
407
+ return segments.join("/") || (isAbsolute(p) ? "/" : ".");
408
+ };
409
+ const format = function(p) {
410
+ const ext = p.ext ? p.ext.startsWith(".") ? p.ext : `.${p.ext}` : "";
411
+ const segments = [
412
+ p.root,
413
+ p.dir,
414
+ p.base ?? (p.name ?? "") + ext
415
+ ].filter(Boolean);
416
+ return normalizeWindowsPath(p.root ? resolve(...segments) : segments.join("/"));
417
+ };
418
+ const basename = function(p, extension) {
419
+ const segments = normalizeWindowsPath(p).split("/");
420
+ let lastSegment = "";
421
+ for (let i = segments.length - 1; i >= 0; i--) {
422
+ const val = segments[i];
423
+ if (val) {
424
+ lastSegment = val;
425
+ break;
426
+ }
427
+ }
428
+ return extension && lastSegment.endsWith(extension) ? lastSegment.slice(0, -extension.length) : lastSegment;
429
+ };
430
+ const parse = function(p) {
431
+ const root = _PATH_ROOT_RE.exec(p)?.[0]?.replace(/\\/g, "/") || "";
432
+ const base = basename(p);
433
+ const extension = extname(base);
434
+ return {
435
+ root,
436
+ dir: dirname(p),
437
+ base,
438
+ ext: extension,
439
+ name: base.slice(0, base.length - extension.length)
440
+ };
441
+ };
442
+ const matchesGlob = (path, pattern) => {
443
+ return zeptomatch(pattern, normalize(path));
444
+ };
445
+ const _path = {
446
+ __proto__: null,
447
+ basename,
448
+ dirname,
449
+ extname,
450
+ format,
451
+ isAbsolute,
452
+ join,
453
+ matchesGlob,
454
+ normalize,
455
+ normalizeString,
456
+ parse,
457
+ relative,
458
+ resolve,
459
+ sep,
460
+ toNamespacedPath
461
+ };
462
+
463
+ //#endregion
464
+ //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/index.mjs
465
+ const delimiter = /* @__PURE__ */ (() => globalThis.process?.platform === "win32" ? ";" : ":")();
466
+ const _platforms = {
467
+ posix: void 0,
468
+ win32: void 0
469
+ };
470
+ const mix = (del = delimiter) => {
471
+ return new Proxy(_path, { get(_, prop) {
472
+ if (prop === "delimiter") return del;
473
+ if (prop === "posix") return posix;
474
+ if (prop === "win32") return win32;
475
+ return _platforms[prop] || _path[prop];
476
+ } });
477
+ };
478
+ const posix = /* @__PURE__ */ mix(":");
479
+ const win32 = /* @__PURE__ */ mix(";");
480
+
481
+ //#endregion
482
+ //#region src/utils/misc.ts
483
+ function arraify(value) {
484
+ return Array.isArray(value) ? value : [value];
485
+ }
486
+ function isNullish(value) {
487
+ return value === null || value === void 0;
488
+ }
489
+ function isPromiseLike(value) {
490
+ return value && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
491
+ }
492
+ function unimplemented(info) {
493
+ if (info) throw new Error(`unimplemented: ${info}`);
494
+ throw new Error("unimplemented");
495
+ }
496
+ function unreachable(info) {
497
+ if (info) throw new Error(`unreachable: ${info}`);
498
+ throw new Error("unreachable");
499
+ }
500
+ function unsupported(info) {
501
+ throw new Error(`UNSUPPORTED: ${info}`);
502
+ }
503
+ function noop(..._args) {}
504
+
505
+ //#endregion
506
+ //#region src/log/logging.ts
507
+ const LOG_LEVEL_SILENT = "silent";
508
+ const LOG_LEVEL_ERROR = "error";
509
+ const LOG_LEVEL_WARN = "warn";
510
+ const LOG_LEVEL_INFO = "info";
511
+ const LOG_LEVEL_DEBUG = "debug";
512
+ const logLevelPriority = {
513
+ [LOG_LEVEL_DEBUG]: 0,
514
+ [LOG_LEVEL_INFO]: 1,
515
+ [LOG_LEVEL_WARN]: 2,
516
+ [LOG_LEVEL_SILENT]: 3
517
+ };
518
+
519
+ //#endregion
520
+ //#region src/utils/code-frame.ts
521
+ function spaces(index) {
522
+ let result = "";
523
+ while (index--) result += " ";
524
+ return result;
525
+ }
526
+ function tabsToSpaces(value) {
527
+ return value.replace(/^\t+/, (match) => match.split(" ").join(" "));
528
+ }
529
+ const LINE_TRUNCATE_LENGTH = 120;
530
+ const MIN_CHARACTERS_SHOWN_AFTER_LOCATION = 10;
531
+ const ELLIPSIS = "...";
532
+ function getCodeFrame(source, line, column) {
533
+ let lines = source.split("\n");
534
+ if (line > lines.length) return "";
535
+ const maxLineLength = Math.max(tabsToSpaces(lines[line - 1].slice(0, column)).length + MIN_CHARACTERS_SHOWN_AFTER_LOCATION + ELLIPSIS.length, LINE_TRUNCATE_LENGTH);
536
+ const frameStart = Math.max(0, line - 3);
537
+ let frameEnd = Math.min(line + 2, lines.length);
538
+ lines = lines.slice(frameStart, frameEnd);
539
+ while (!/\S/.test(lines[lines.length - 1])) {
540
+ lines.pop();
541
+ frameEnd -= 1;
542
+ }
543
+ const digits = String(frameEnd).length;
544
+ return lines.map((sourceLine, index) => {
545
+ const isErrorLine = frameStart + index + 1 === line;
546
+ let lineNumber = String(index + frameStart + 1);
547
+ while (lineNumber.length < digits) lineNumber = ` ${lineNumber}`;
548
+ let displayedLine = tabsToSpaces(sourceLine);
549
+ if (displayedLine.length > maxLineLength) displayedLine = `${displayedLine.slice(0, maxLineLength - ELLIPSIS.length)}${ELLIPSIS}`;
550
+ if (isErrorLine) {
551
+ const indicator = spaces(digits + 2 + tabsToSpaces(sourceLine.slice(0, column)).length) + "^";
552
+ return `${lineNumber}: ${displayedLine}\n${indicator}`;
553
+ }
554
+ return `${lineNumber}: ${displayedLine}`;
555
+ }).join("\n");
556
+ }
557
+
558
+ //#endregion
559
+ //#region src/log/locate-character/index.js
560
+ /** @typedef {import('./types').Location} Location */
561
+ /**
562
+ * @param {import('./types').Range} range
563
+ * @param {number} index
564
+ */
565
+ function rangeContains(range, index) {
566
+ return range.start <= index && index < range.end;
567
+ }
568
+ function getLocator(source, options = {}) {
569
+ const { offsetLine = 0, offsetColumn = 0 } = options;
570
+ let start = 0;
571
+ const ranges = source.split("\n").map((line, i$1) => {
572
+ const end = start + line.length + 1;
573
+ /** @type {import('./types').Range} */
574
+ const range = {
575
+ start,
576
+ end,
577
+ line: i$1
578
+ };
579
+ start = end;
580
+ return range;
581
+ });
582
+ let i = 0;
583
+ /**
584
+ * @param {string | number} search
585
+ * @param {number} [index]
586
+ * @returns {Location | undefined}
587
+ */
588
+ function locator(search, index) {
589
+ if (typeof search === "string") search = source.indexOf(search, index ?? 0);
590
+ if (search === -1) return void 0;
591
+ let range = ranges[i];
592
+ const d = search >= range.end ? 1 : -1;
593
+ while (range) {
594
+ if (rangeContains(range, search)) return {
595
+ line: offsetLine + range.line,
596
+ column: offsetColumn + search - range.start,
597
+ character: search
598
+ };
599
+ i += d;
600
+ range = ranges[i];
601
+ }
602
+ }
603
+ return locator;
604
+ }
605
+ function locate(source, search, options) {
606
+ return getLocator(source, options)(search, options && options.startIndex);
607
+ }
608
+
609
+ //#endregion
610
+ //#region src/log/logs.ts
611
+ const INVALID_LOG_POSITION = "INVALID_LOG_POSITION", PLUGIN_ERROR = "PLUGIN_ERROR", INPUT_HOOK_IN_OUTPUT_PLUGIN = "INPUT_HOOK_IN_OUTPUT_PLUGIN", CYCLE_LOADING = "CYCLE_LOADING", MULTIPLY_NOTIFY_OPTION = "MULTIPLY_NOTIFY_OPTION", MINIFY_WARNING = "MINIFY_WARNING", PARSE_ERROR = "PARSE_ERROR";
612
+ function logParseError(message) {
613
+ return {
614
+ code: PARSE_ERROR,
615
+ message
616
+ };
617
+ }
618
+ function logMinifyWarning() {
619
+ return {
620
+ code: MINIFY_WARNING,
621
+ message: colors.yellow("The built-in minifier is still under development. Setting \"minify: true\" is not recommended for production use.")
622
+ };
623
+ }
624
+ function logInvalidLogPosition(pluginName) {
625
+ return {
626
+ code: INVALID_LOG_POSITION,
627
+ message: `Plugin "${pluginName}" tried to add a file position to a log or warning. This is only supported in the "transform" hook at the moment and will be ignored.`
628
+ };
629
+ }
630
+ function logInputHookInOutputPlugin(pluginName, hookName) {
631
+ return {
632
+ code: INPUT_HOOK_IN_OUTPUT_PLUGIN,
633
+ message: `The "${hookName}" hook used by the output plugin ${pluginName} is a build time hook and will not be run for that plugin. Either this plugin cannot be used as an output plugin, or it should have an option to configure it as an output plugin.`
634
+ };
635
+ }
636
+ function logCycleLoading(pluginName, moduleId) {
637
+ return {
638
+ code: CYCLE_LOADING,
639
+ message: `Found the module "${moduleId}" cycle loading at ${pluginName} plugin, it maybe blocking fetching modules.`
640
+ };
641
+ }
642
+ function logMultiplyNotifyOption() {
643
+ return {
644
+ code: MULTIPLY_NOTIFY_OPTION,
645
+ message: `Found multiply notify option at watch options, using first one to start notify watcher.`
646
+ };
647
+ }
648
+ function logPluginError(error$1, plugin, { hook, id } = {}) {
649
+ const code = error$1.code;
650
+ if (!error$1.pluginCode && code != null && (typeof code !== "string" || !code.startsWith("PLUGIN_"))) error$1.pluginCode = code;
651
+ error$1.code = PLUGIN_ERROR;
652
+ error$1.plugin = plugin;
653
+ if (hook) error$1.hook = hook;
654
+ if (id) error$1.id = id;
655
+ return error$1;
656
+ }
657
+ function error(base) {
658
+ if (!(base instanceof Error)) {
659
+ base = Object.assign(new Error(base.message), base);
660
+ Object.defineProperty(base, "name", {
661
+ value: "RollupError",
662
+ writable: true
663
+ });
664
+ }
665
+ throw base;
666
+ }
667
+ function augmentCodeLocation(properties, pos, source, id) {
668
+ if (typeof pos === "object") {
669
+ const { line, column } = pos;
670
+ properties.loc = {
671
+ column,
672
+ file: id,
673
+ line
674
+ };
675
+ } else {
676
+ properties.pos = pos;
677
+ const location = locate(source, pos, { offsetLine: 1 });
678
+ if (!location) return;
679
+ const { line, column } = location;
680
+ properties.loc = {
681
+ column,
682
+ file: id,
683
+ line
684
+ };
685
+ }
686
+ if (properties.frame === void 0) {
687
+ const { line, column } = properties.loc;
688
+ properties.frame = getCodeFrame(source, line, column);
689
+ }
690
+ }
691
+
692
+ //#endregion
693
+ //#region src/log/log-handler.ts
694
+ const normalizeLog = (log) => typeof log === "string" ? { message: log } : typeof log === "function" ? normalizeLog(log()) : log;
695
+ function getLogHandler(level, code, logger, pluginName, logLevel) {
696
+ if (logLevelPriority[level] < logLevelPriority[logLevel]) return noop;
697
+ return (log, pos) => {
698
+ if (pos != null) logger(LOG_LEVEL_WARN, logInvalidLogPosition(pluginName));
699
+ log = normalizeLog(log);
700
+ if (log.code && !log.pluginCode) log.pluginCode = log.code;
701
+ log.code = code;
702
+ log.plugin = pluginName;
703
+ logger(level, log);
704
+ };
705
+ }
706
+
707
+ //#endregion
708
+ //#region src/log/logger.ts
709
+ function getLogger(plugins, onLog, logLevel, watchMode) {
710
+ const minimalPriority = logLevelPriority[logLevel];
711
+ const logger = (level, log, skipped = new Set()) => {
712
+ const logPriority = logLevelPriority[level];
713
+ if (logPriority < minimalPriority) return;
714
+ for (const plugin of getSortedPlugins("onLog", plugins)) {
715
+ if (skipped.has(plugin)) continue;
716
+ const { onLog: pluginOnLog } = plugin;
717
+ if (pluginOnLog) {
718
+ const getLogHandler$1 = (level$1) => {
719
+ if (logLevelPriority[level$1] < minimalPriority) return () => {};
720
+ return (log$1) => logger(level$1, normalizeLog(log$1), new Set(skipped).add(plugin));
721
+ };
722
+ const handler = "handler" in pluginOnLog ? pluginOnLog.handler : pluginOnLog;
723
+ if (handler.call({
724
+ debug: getLogHandler$1(LOG_LEVEL_DEBUG),
725
+ error: (log$1) => error(normalizeLog(log$1)),
726
+ info: getLogHandler$1(LOG_LEVEL_INFO),
727
+ meta: {
728
+ rollupVersion: "4.23.0",
729
+ rolldownVersion: VERSION,
730
+ watchMode
731
+ },
732
+ warn: getLogHandler$1(LOG_LEVEL_WARN),
733
+ pluginName: plugin.name || "unknown"
734
+ }, level, log) === false) return;
735
+ }
736
+ }
737
+ onLog(level, log);
738
+ };
739
+ return logger;
740
+ }
741
+ const getOnLog = (config, logLevel, printLog = defaultPrintLog) => {
742
+ const { onwarn, onLog } = config;
743
+ const defaultOnLog = getDefaultOnLog(printLog, onwarn);
744
+ if (onLog) {
745
+ const minimalPriority = logLevelPriority[logLevel];
746
+ return (level, log) => onLog(level, addLogToString(log), (level$1, handledLog) => {
747
+ if (level$1 === LOG_LEVEL_ERROR) return error(normalizeLog(handledLog));
748
+ if (logLevelPriority[level$1] >= minimalPriority) defaultOnLog(level$1, normalizeLog(handledLog));
749
+ });
750
+ }
751
+ return defaultOnLog;
752
+ };
753
+ const getDefaultOnLog = (printLog, onwarn) => onwarn ? (level, log) => {
754
+ if (level === LOG_LEVEL_WARN) onwarn(addLogToString(log), (warning) => printLog(LOG_LEVEL_WARN, normalizeLog(warning)));
755
+ else printLog(level, log);
756
+ } : printLog;
757
+ const addLogToString = (log) => {
758
+ Object.defineProperty(log, "toString", {
759
+ value: () => getExtendedLogMessage(log),
760
+ writable: true
761
+ });
762
+ return log;
763
+ };
764
+ const defaultPrintLog = (level, log) => {
765
+ const message = getExtendedLogMessage(log);
766
+ switch (level) {
767
+ case LOG_LEVEL_WARN: return console.warn(message);
768
+ case LOG_LEVEL_DEBUG: return console.debug(message);
769
+ default: return console.info(message);
770
+ }
771
+ };
772
+ const getExtendedLogMessage = (log) => {
773
+ let prefix = "";
774
+ if (log.plugin) prefix += `(${log.plugin} plugin) `;
775
+ if (log.loc) prefix += `${relativeId(log.loc.file)} (${log.loc.line}:${log.loc.column}) `;
776
+ return prefix + log.message;
777
+ };
778
+ function relativeId(id) {
779
+ if (!posix.isAbsolute(id)) return id;
780
+ return posix.relative(posix.resolve(), id);
781
+ }
782
+
783
+ //#endregion
784
+ //#region src/utils/normalize-hook.ts
785
+ function normalizeHook(hook) {
786
+ if (typeof hook === "function" || typeof hook === "string") return {
787
+ handler: hook,
788
+ options: {},
789
+ meta: {}
790
+ };
791
+ if (typeof hook === "object" && hook !== null) {
792
+ const { handler, order,...options } = hook;
793
+ return {
794
+ handler,
795
+ options,
796
+ meta: { order }
797
+ };
798
+ }
799
+ unreachable("Invalid hook type");
800
+ }
801
+
802
+ //#endregion
803
+ //#region src/constants/plugin.ts
804
+ const ENUMERATED_INPUT_PLUGIN_HOOK_NAMES = [
805
+ "options",
806
+ "buildStart",
807
+ "resolveId",
808
+ "load",
809
+ "transform",
810
+ "moduleParsed",
811
+ "buildEnd",
812
+ "onLog",
813
+ "resolveDynamicImport",
814
+ "closeBundle",
815
+ "closeWatcher",
816
+ "watchChange"
817
+ ];
818
+ const ENUMERATED_OUTPUT_PLUGIN_HOOK_NAMES = [
819
+ "augmentChunkHash",
820
+ "outputOptions",
821
+ "renderChunk",
822
+ "renderStart",
823
+ "renderError",
824
+ "writeBundle",
825
+ "generateBundle"
826
+ ];
827
+ const ENUMERATED_PLUGIN_HOOK_NAMES = [
828
+ ...ENUMERATED_INPUT_PLUGIN_HOOK_NAMES,
829
+ ...ENUMERATED_OUTPUT_PLUGIN_HOOK_NAMES,
830
+ "footer",
831
+ "banner",
832
+ "intro",
833
+ "outro"
834
+ ];
835
+ const DEFINED_HOOK_NAMES = {
836
+ [ENUMERATED_PLUGIN_HOOK_NAMES[0]]: ENUMERATED_PLUGIN_HOOK_NAMES[0],
837
+ [ENUMERATED_PLUGIN_HOOK_NAMES[1]]: ENUMERATED_PLUGIN_HOOK_NAMES[1],
838
+ [ENUMERATED_PLUGIN_HOOK_NAMES[2]]: ENUMERATED_PLUGIN_HOOK_NAMES[2],
839
+ [ENUMERATED_PLUGIN_HOOK_NAMES[3]]: ENUMERATED_PLUGIN_HOOK_NAMES[3],
840
+ [ENUMERATED_PLUGIN_HOOK_NAMES[4]]: ENUMERATED_PLUGIN_HOOK_NAMES[4],
841
+ [ENUMERATED_PLUGIN_HOOK_NAMES[5]]: ENUMERATED_PLUGIN_HOOK_NAMES[5],
842
+ [ENUMERATED_PLUGIN_HOOK_NAMES[6]]: ENUMERATED_PLUGIN_HOOK_NAMES[6],
843
+ [ENUMERATED_PLUGIN_HOOK_NAMES[7]]: ENUMERATED_PLUGIN_HOOK_NAMES[7],
844
+ [ENUMERATED_PLUGIN_HOOK_NAMES[8]]: ENUMERATED_PLUGIN_HOOK_NAMES[8],
845
+ [ENUMERATED_PLUGIN_HOOK_NAMES[9]]: ENUMERATED_PLUGIN_HOOK_NAMES[9],
846
+ [ENUMERATED_PLUGIN_HOOK_NAMES[10]]: ENUMERATED_PLUGIN_HOOK_NAMES[10],
847
+ [ENUMERATED_PLUGIN_HOOK_NAMES[11]]: ENUMERATED_PLUGIN_HOOK_NAMES[11],
848
+ [ENUMERATED_PLUGIN_HOOK_NAMES[12]]: ENUMERATED_PLUGIN_HOOK_NAMES[12],
849
+ [ENUMERATED_PLUGIN_HOOK_NAMES[13]]: ENUMERATED_PLUGIN_HOOK_NAMES[13],
850
+ [ENUMERATED_PLUGIN_HOOK_NAMES[14]]: ENUMERATED_PLUGIN_HOOK_NAMES[14],
851
+ [ENUMERATED_PLUGIN_HOOK_NAMES[15]]: ENUMERATED_PLUGIN_HOOK_NAMES[15],
852
+ [ENUMERATED_PLUGIN_HOOK_NAMES[16]]: ENUMERATED_PLUGIN_HOOK_NAMES[16],
853
+ [ENUMERATED_PLUGIN_HOOK_NAMES[17]]: ENUMERATED_PLUGIN_HOOK_NAMES[17],
854
+ [ENUMERATED_PLUGIN_HOOK_NAMES[18]]: ENUMERATED_PLUGIN_HOOK_NAMES[18],
855
+ [ENUMERATED_PLUGIN_HOOK_NAMES[19]]: ENUMERATED_PLUGIN_HOOK_NAMES[19],
856
+ [ENUMERATED_PLUGIN_HOOK_NAMES[20]]: ENUMERATED_PLUGIN_HOOK_NAMES[20],
857
+ [ENUMERATED_PLUGIN_HOOK_NAMES[21]]: ENUMERATED_PLUGIN_HOOK_NAMES[21],
858
+ [ENUMERATED_PLUGIN_HOOK_NAMES[22]]: ENUMERATED_PLUGIN_HOOK_NAMES[22]
859
+ };
860
+
861
+ //#endregion
862
+ //#region src/utils/async-flatten.ts
863
+ async function asyncFlatten(array) {
864
+ do
865
+ array = (await Promise.all(array)).flat(Infinity);
866
+ while (array.some((v$1) => v$1?.then));
867
+ return array;
868
+ }
869
+
870
+ //#endregion
871
+ //#region src/utils/normalize-plugin-option.ts
872
+ const normalizePluginOption = async (plugins) => (await asyncFlatten([plugins])).filter(Boolean);
873
+ function checkOutputPluginOption(plugins, onLog) {
874
+ for (const plugin of plugins) for (const hook of ENUMERATED_INPUT_PLUGIN_HOOK_NAMES) if (hook in plugin) {
875
+ delete plugin[hook];
876
+ onLog(LOG_LEVEL_WARN, logInputHookInOutputPlugin(plugin.name, hook));
877
+ }
878
+ return plugins;
879
+ }
880
+ function normalizePlugins(plugins, anonymousPrefix) {
881
+ for (const [index, plugin] of plugins.entries()) {
882
+ if ("_parallel" in plugin) continue;
883
+ if (plugin instanceof BuiltinPlugin) continue;
884
+ if (!plugin.name) plugin.name = `${anonymousPrefix}${index + 1}`;
885
+ }
886
+ return plugins;
887
+ }
888
+ const ANONYMOUS_PLUGIN_PREFIX = "at position ";
889
+ const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = "at output position ";
890
+
891
+ //#endregion
892
+ //#region src/plugin/minimal-plugin-context.ts
893
+ var MinimalPluginContextImpl = class {
894
+ info;
895
+ warn;
896
+ debug;
897
+ meta;
898
+ constructor(onLog, logLevel, pluginName, watchMode, hookName) {
899
+ this.pluginName = pluginName;
900
+ this.hookName = hookName;
901
+ this.debug = getLogHandler(LOG_LEVEL_DEBUG, "PLUGIN_LOG", onLog, pluginName, logLevel);
902
+ this.info = getLogHandler(LOG_LEVEL_INFO, "PLUGIN_LOG", onLog, pluginName, logLevel);
903
+ this.warn = getLogHandler(LOG_LEVEL_WARN, "PLUGIN_WARNING", onLog, pluginName, logLevel);
904
+ this.meta = {
905
+ rollupVersion: "4.23.0",
906
+ rolldownVersion: VERSION,
907
+ watchMode
908
+ };
909
+ }
910
+ error(e) {
911
+ return error(logPluginError(normalizeLog(e), this.pluginName, { hook: this.hookName }));
912
+ }
913
+ };
914
+
915
+ //#endregion
916
+ //#region src/plugin/plugin-driver.ts
917
+ var PluginDriver = class {
918
+ static async callOptionsHook(inputOptions, watchMode = false) {
919
+ const logLevel = inputOptions.logLevel || LOG_LEVEL_INFO;
920
+ const plugins = getSortedPlugins("options", getObjectPlugins(await normalizePluginOption(inputOptions.plugins)));
921
+ const logger = getLogger(plugins, getOnLog(inputOptions, logLevel), logLevel, watchMode);
922
+ for (const plugin of plugins) {
923
+ const name = plugin.name || "unknown";
924
+ const options = plugin.options;
925
+ if (options) {
926
+ const { handler } = normalizeHook(options);
927
+ const result = await handler.call(new MinimalPluginContextImpl(logger, logLevel, name, watchMode, "onLog"), inputOptions);
928
+ if (result) inputOptions = result;
929
+ }
930
+ }
931
+ return inputOptions;
932
+ }
933
+ static callOutputOptionsHook(rawPlugins, outputOptions, onLog, logLevel, watchMode) {
934
+ const sortedPlugins = getSortedPlugins("outputOptions", getObjectPlugins(rawPlugins));
935
+ for (const plugin of sortedPlugins) {
936
+ const name = plugin.name || "unknown";
937
+ const options = plugin.outputOptions;
938
+ if (options) {
939
+ const { handler } = normalizeHook(options);
940
+ const result = handler.call(new MinimalPluginContextImpl(onLog, logLevel, name, watchMode), outputOptions);
941
+ if (result) outputOptions = result;
942
+ }
943
+ }
944
+ return outputOptions;
945
+ }
946
+ };
947
+ function getObjectPlugins(plugins) {
948
+ return plugins.filter((plugin) => {
949
+ if (!plugin) return void 0;
950
+ if ("_parallel" in plugin) return void 0;
951
+ if (plugin instanceof BuiltinPlugin) return void 0;
952
+ return plugin;
953
+ });
954
+ }
955
+ function getSortedPlugins(hookName, plugins) {
956
+ const pre = [];
957
+ const normal = [];
958
+ const post = [];
959
+ for (const plugin of plugins) {
960
+ const hook = plugin[hookName];
961
+ if (hook) {
962
+ if (typeof hook === "object") {
963
+ if (hook.order === "pre") {
964
+ pre.push(plugin);
965
+ continue;
966
+ }
967
+ if (hook.order === "post") {
968
+ post.push(plugin);
969
+ continue;
970
+ }
971
+ }
972
+ normal.push(plugin);
973
+ }
974
+ }
975
+ return [
976
+ ...pre,
977
+ ...normal,
978
+ ...post
979
+ ];
980
+ }
981
+
982
+ //#endregion
983
+ //#region src/utils/validator.ts
984
+ const StringOrRegExpSchema = v.union([v.string(), v.instance(RegExp)]);
985
+ const LogLevelSchema = v.union([
986
+ v.literal("debug"),
987
+ v.literal("info"),
988
+ v.literal("warn")
989
+ ]);
990
+ const LogLevelOptionSchema = v.union([LogLevelSchema, v.literal("silent")]);
991
+ const LogLevelWithErrorSchema = v.union([LogLevelSchema, v.literal("error")]);
992
+ const RollupLogSchema = v.any();
993
+ const RollupLogWithStringSchema = v.union([RollupLogSchema, v.string()]);
994
+ const InputOptionSchema = v.union([
995
+ v.string(),
996
+ v.array(v.string()),
997
+ v.record(v.string(), v.string())
998
+ ]);
999
+ const ExternalSchema = v.union([
1000
+ StringOrRegExpSchema,
1001
+ v.array(StringOrRegExpSchema),
1002
+ v.pipe(v.function(), v.args(v.tuple([
1003
+ v.string(),
1004
+ v.optional(v.string()),
1005
+ v.boolean()
1006
+ ])), v.returns(v.nullish(v.boolean())))
1007
+ ]);
1008
+ const ModuleTypesSchema = v.record(v.string(), v.union([
1009
+ v.literal("base64"),
1010
+ v.literal("binary"),
1011
+ v.literal("css"),
1012
+ v.literal("dataurl"),
1013
+ v.literal("empty"),
1014
+ v.literal("js"),
1015
+ v.literal("json"),
1016
+ v.literal("jsx"),
1017
+ v.literal("text"),
1018
+ v.literal("ts"),
1019
+ v.literal("tsx")
1020
+ ]));
1021
+ const JsxOptionsSchema = v.strictObject({
1022
+ development: v.pipe(v.optional(v.boolean()), v.description("Development specific information")),
1023
+ factory: v.pipe(v.optional(v.string()), v.description("Jsx element transformation")),
1024
+ fragment: v.pipe(v.optional(v.string()), v.description("Jsx fragment transformation")),
1025
+ importSource: v.pipe(v.optional(v.string()), v.description("Import the factory of element and fragment if mode is classic")),
1026
+ jsxImportSource: v.pipe(v.optional(v.string()), v.description("Import the factory of element and fragment if mode is automatic")),
1027
+ mode: v.pipe(v.optional(v.union([
1028
+ v.literal("classic"),
1029
+ v.literal("automatic"),
1030
+ v.literal("preserve")
1031
+ ])), v.description("Jsx transformation mode")),
1032
+ refresh: v.pipe(v.optional(v.boolean()), v.description("React refresh transformation"))
1033
+ });
1034
+ const HelperModeSchema = v.union([v.literal("Runtime"), v.literal("External")]);
1035
+ const DecoratorOptionSchema = v.object({
1036
+ legacy: v.optional(v.boolean()),
1037
+ emitDecoratorMetadata: v.optional(v.boolean())
1038
+ });
1039
+ const HelpersSchema = v.object({ mode: v.optional(HelperModeSchema) });
1040
+ const RewriteImportExtensionsSchema = v.union([
1041
+ v.literal("rewrite"),
1042
+ v.literal("remove"),
1043
+ v.boolean()
1044
+ ]);
1045
+ const TypescriptSchema = v.object({
1046
+ jsxPragma: v.optional(v.string()),
1047
+ jsxPragmaFrag: v.optional(v.string()),
1048
+ onlyRemoveTypeImports: v.optional(v.boolean()),
1049
+ allowNamespaces: v.optional(v.boolean()),
1050
+ allowDeclareFields: v.optional(v.boolean()),
1051
+ declaration: v.optional(v.object({
1052
+ stripInternal: v.optional(v.boolean()),
1053
+ sourcemap: v.optional(v.boolean())
1054
+ })),
1055
+ rewriteImportExtensions: v.optional(RewriteImportExtensionsSchema)
1056
+ });
1057
+ const AssumptionsSchema = v.object({
1058
+ ignoreFunctionLength: v.optional(v.boolean()),
1059
+ noDocumentAll: v.optional(v.boolean()),
1060
+ objectRestNoSymbols: v.optional(v.boolean()),
1061
+ pureGetters: v.optional(v.boolean()),
1062
+ setPublicClassFields: v.optional(v.boolean())
1063
+ });
1064
+ const TransformOptionsSchema = v.object({
1065
+ assumptions: v.optional(AssumptionsSchema),
1066
+ typescript: v.optional(TypescriptSchema),
1067
+ helpers: v.optional(HelpersSchema),
1068
+ decorators: v.optional(DecoratorOptionSchema)
1069
+ });
1070
+ const WatchOptionsSchema = v.strictObject({
1071
+ chokidar: v.optional(v.never(`The "watch.chokidar" option is deprecated, please use "watch.notify" instead of it`)),
1072
+ exclude: v.optional(v.union([StringOrRegExpSchema, v.array(StringOrRegExpSchema)])),
1073
+ include: v.optional(v.union([StringOrRegExpSchema, v.array(StringOrRegExpSchema)])),
1074
+ notify: v.pipe(v.optional(v.strictObject({
1075
+ compareContents: v.optional(v.boolean()),
1076
+ pollInterval: v.optional(v.number())
1077
+ })), v.description("Notify options")),
1078
+ skipWrite: v.pipe(v.optional(v.boolean()), v.description("Skip the bundle.write() step")),
1079
+ buildDelay: v.pipe(v.optional(v.number()), v.description("Throttle watch rebuilds"))
1080
+ });
1081
+ const ChecksOptionsSchema = v.strictObject({
1082
+ circularDependency: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warning when detecting circular dependency")),
1083
+ eval: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warning when detecting eval")),
1084
+ missingGlobalName: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warning when detecting missing global name")),
1085
+ missingNameOptionForIifeExport: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warning when detecting missing name option for iife export")),
1086
+ mixedExport: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warning when detecting mixed export")),
1087
+ unresolvedEntry: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warning when detecting unresolved entry")),
1088
+ unresolvedImport: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warning when detecting unresolved import")),
1089
+ filenameConflict: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warning when detecting filename conflict")),
1090
+ commonJsVariableInEsm: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warning when detecting common js variable in esm")),
1091
+ importIsUndefined: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warning when detecting import is undefined")),
1092
+ configurationFieldConflict: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warning when detecting configuration field conflict"))
1093
+ });
1094
+ const MinifyOptionsSchema = v.strictObject({
1095
+ mangle: v.boolean(),
1096
+ compress: v.boolean(),
1097
+ deadCodeElimination: v.boolean(),
1098
+ removeWhitespace: v.boolean()
1099
+ });
1100
+ const ResolveOptionsSchema = v.strictObject({
1101
+ alias: v.optional(v.record(v.string(), v.union([v.string(), v.array(v.string())]))),
1102
+ aliasFields: v.optional(v.array(v.array(v.string()))),
1103
+ conditionNames: v.optional(v.array(v.string())),
1104
+ extensionAlias: v.optional(v.record(v.string(), v.array(v.string()))),
1105
+ exportsFields: v.optional(v.array(v.array(v.string()))),
1106
+ extensions: v.optional(v.array(v.string())),
1107
+ mainFields: v.optional(v.array(v.string())),
1108
+ mainFiles: v.optional(v.array(v.string())),
1109
+ modules: v.optional(v.array(v.string())),
1110
+ symlinks: v.optional(v.boolean()),
1111
+ tsconfigFilename: v.optional(v.string())
1112
+ });
1113
+ const TreeshakingOptionsSchema = v.union([v.boolean(), v.looseObject({
1114
+ annotations: v.optional(v.boolean()),
1115
+ manualPureFunctions: v.optional(v.array(v.string())),
1116
+ unknownGlobalSideEffects: v.optional(v.boolean())
1117
+ })]);
1118
+ const OnLogSchema = v.pipe(v.function(), v.args(v.tuple([
1119
+ LogLevelSchema,
1120
+ RollupLogSchema,
1121
+ v.pipe(v.function(), v.args(v.tuple([LogLevelWithErrorSchema, RollupLogWithStringSchema])))
1122
+ ])));
1123
+ const OnwarnSchema = v.pipe(v.function(), v.args(v.tuple([RollupLogSchema, v.pipe(v.function(), v.args(v.tuple([v.union([RollupLogWithStringSchema, v.pipe(v.function(), v.returns(RollupLogWithStringSchema))])])))])));
1124
+ const HmrSchema = v.union([v.boolean(), v.strictObject({
1125
+ port: v.optional(v.number()),
1126
+ host: v.optional(v.string()),
1127
+ implement: v.optional(v.string())
1128
+ })]);
1129
+ const InputOptionsSchema = v.strictObject({
1130
+ input: v.optional(InputOptionSchema),
1131
+ plugins: v.optional(v.custom(() => true)),
1132
+ external: v.optional(ExternalSchema),
1133
+ resolve: v.optional(ResolveOptionsSchema),
1134
+ cwd: v.pipe(v.optional(v.string()), v.description("Current working directory")),
1135
+ platform: v.pipe(v.optional(v.union([
1136
+ v.literal("browser"),
1137
+ v.literal("neutral"),
1138
+ v.literal("node")
1139
+ ])), v.description(`Platform for which the code should be generated (node, ${colors.underline("browser")}, neutral)`)),
1140
+ shimMissingExports: v.pipe(v.optional(v.boolean()), v.description("Create shim variables for missing exports")),
1141
+ treeshake: v.optional(TreeshakingOptionsSchema),
1142
+ logLevel: v.pipe(v.optional(LogLevelOptionSchema), v.description(`Log level (${colors.dim("silent")}, ${colors.underline(colors.gray("info"))}, debug, ${colors.yellow("warn")})`)),
1143
+ onLog: v.optional(OnLogSchema),
1144
+ onwarn: v.optional(OnwarnSchema),
1145
+ moduleTypes: v.pipe(v.optional(ModuleTypesSchema), v.description("Module types for customized extensions")),
1146
+ experimental: v.optional(v.strictObject({
1147
+ disableLiveBindings: v.optional(v.boolean()),
1148
+ enableComposingJsPlugins: v.optional(v.boolean()),
1149
+ resolveNewUrlToAsset: v.optional(v.boolean()),
1150
+ strictExecutionOrder: v.optional(v.boolean()),
1151
+ hmr: v.optional(HmrSchema)
1152
+ })),
1153
+ define: v.pipe(v.optional(v.record(v.string(), v.string())), v.description("Define global variables")),
1154
+ inject: v.optional(v.record(v.string(), v.union([v.string(), v.tuple([v.string(), v.string()])]))),
1155
+ profilerNames: v.optional(v.boolean()),
1156
+ jsx: v.optional(v.union([
1157
+ v.boolean(),
1158
+ JsxOptionsSchema,
1159
+ v.string("react"),
1160
+ v.string("react-jsx"),
1161
+ v.string("preserve")
1162
+ ])),
1163
+ transform: v.optional(TransformOptionsSchema),
1164
+ watch: v.optional(v.union([WatchOptionsSchema, v.literal(false)])),
1165
+ dropLabels: v.pipe(v.optional(v.array(v.string())), v.description("Remove labeled statements with these label names")),
1166
+ checks: v.optional(ChecksOptionsSchema),
1167
+ keepNames: v.pipe(v.optional(v.boolean()), v.description("Keep function/class name")),
1168
+ debug: v.pipe(v.optional(v.object({ buildId: v.pipe(v.optional(v.string()), v.description("Used to name the build.")) })), v.description("Enable debug mode. Emit debug information to disk. This might slow down the build process significantly."))
1169
+ });
1170
+ const InputCliOverrideSchema = v.strictObject({
1171
+ external: v.pipe(v.optional(v.array(v.string())), v.description("Comma-separated list of module ids to exclude from the bundle `<module-id>,...`")),
1172
+ inject: v.pipe(v.optional(v.record(v.string(), v.string())), v.description("Inject import statements on demand")),
1173
+ treeshake: v.pipe(v.optional(v.boolean()), v.description("enable treeshaking")),
1174
+ jsx: v.pipe(v.optional(JsxOptionsSchema), v.description("enable jsx"))
1175
+ });
1176
+ const InputCliOptionsSchema = v.omit(v.strictObject({
1177
+ ...InputOptionsSchema.entries,
1178
+ ...InputCliOverrideSchema.entries
1179
+ }), [
1180
+ "input",
1181
+ "plugins",
1182
+ "onwarn",
1183
+ "onLog",
1184
+ "resolve",
1185
+ "experimental",
1186
+ "profilerNames",
1187
+ "watch"
1188
+ ]);
1189
+ var ESTarget = /* @__PURE__ */ function(ESTarget$1) {
1190
+ ESTarget$1["ES6"] = "es6";
1191
+ ESTarget$1["ES2015"] = "es2015";
1192
+ ESTarget$1["ES2016"] = "es2016";
1193
+ ESTarget$1["ES2017"] = "es2017";
1194
+ ESTarget$1["ES2018"] = "es2018";
1195
+ ESTarget$1["ES2019"] = "es2019";
1196
+ ESTarget$1["ES2020"] = "es2020";
1197
+ ESTarget$1["ES2021"] = "es2021";
1198
+ ESTarget$1["ES2022"] = "es2022";
1199
+ ESTarget$1["ES2023"] = "es2023";
1200
+ ESTarget$1["ES2024"] = "es2024";
1201
+ ESTarget$1["ESNext"] = "esnext";
1202
+ return ESTarget$1;
1203
+ }(ESTarget || {});
1204
+ const ModuleFormatSchema = v.union([
1205
+ v.literal("es"),
1206
+ v.literal("cjs"),
1207
+ v.literal("esm"),
1208
+ v.literal("module"),
1209
+ v.literal("commonjs"),
1210
+ v.literal("iife"),
1211
+ v.literal("umd")
1212
+ ]);
1213
+ const AddonFunctionSchema = v.pipe(v.function(), v.args(v.tuple([v.custom(() => true)])), v.returnsAsync(v.unionAsync([v.string(), v.pipeAsync(v.promise(), v.awaitAsync(), v.string())])));
1214
+ const ChunkFileNamesSchema = v.union([v.string(), v.pipe(v.function(), v.args(v.tuple([v.custom(() => true)])), v.returns(v.string()))]);
1215
+ const AssetFileNamesSchema = v.union([v.string(), v.pipe(v.function(), v.args(v.tuple([v.custom(() => true)])), v.returns(v.string()))]);
1216
+ const SanitizeFileNameSchema = v.union([v.boolean(), v.pipe(v.function(), v.args(v.tuple([v.string()])), v.returns(v.string()))]);
1217
+ const GlobalsFunctionSchema = v.pipe(v.function(), v.args(v.tuple([v.string()])), v.returns(v.string()));
1218
+ const AdvancedChunksSchema = v.strictObject({
1219
+ minSize: v.optional(v.number()),
1220
+ maxSize: v.optional(v.number()),
1221
+ minModuleSize: v.optional(v.number()),
1222
+ maxModuleSize: v.optional(v.number()),
1223
+ minShareCount: v.optional(v.number()),
1224
+ groups: v.optional(v.array(v.strictObject({
1225
+ name: v.string(),
1226
+ test: v.optional(v.union([v.string(), v.instance(RegExp)])),
1227
+ priority: v.optional(v.number()),
1228
+ minSize: v.optional(v.number()),
1229
+ minShareCount: v.optional(v.number()),
1230
+ maxSize: v.optional(v.number()),
1231
+ minModuleSize: v.optional(v.number()),
1232
+ maxModuleSize: v.optional(v.number())
1233
+ })))
1234
+ });
1235
+ const OutputOptionsSchema = v.strictObject({
1236
+ dir: v.pipe(v.optional(v.string()), v.description("Output directory, defaults to `dist` if `file` is not set")),
1237
+ file: v.pipe(v.optional(v.string()), v.description("Single output file")),
1238
+ exports: v.pipe(v.optional(v.union([
1239
+ v.literal("auto"),
1240
+ v.literal("named"),
1241
+ v.literal("default"),
1242
+ v.literal("none")
1243
+ ])), v.description(`Specify a export mode (${colors.underline("auto")}, named, default, none)`)),
1244
+ hashCharacters: v.pipe(v.optional(v.union([
1245
+ v.literal("base64"),
1246
+ v.literal("base36"),
1247
+ v.literal("hex")
1248
+ ])), v.description("Use the specified character set for file hashes")),
1249
+ format: v.pipe(v.optional(ModuleFormatSchema), v.description(`Output format of the generated bundle (supports ${colors.underline("esm")}, cjs, and iife)`)),
1250
+ sourcemap: v.pipe(v.optional(v.union([
1251
+ v.boolean(),
1252
+ v.literal("inline"),
1253
+ v.literal("hidden")
1254
+ ])), v.description(`Generate sourcemap (\`-s inline\` for inline, or ${colors.bold("pass the `-s` on the last argument if you want to generate `.map` file")})`)),
1255
+ sourcemapDebugIds: v.pipe(v.optional(v.boolean()), v.description("Inject sourcemap debug IDs")),
1256
+ sourcemapIgnoreList: v.optional(v.union([v.boolean(), v.custom(() => true)])),
1257
+ sourcemapPathTransform: v.optional(v.custom(() => true)),
1258
+ banner: v.optional(v.union([v.string(), AddonFunctionSchema])),
1259
+ footer: v.optional(v.union([v.string(), AddonFunctionSchema])),
1260
+ intro: v.optional(v.union([v.string(), AddonFunctionSchema])),
1261
+ outro: v.optional(v.union([v.string(), AddonFunctionSchema])),
1262
+ extend: v.pipe(v.optional(v.boolean()), v.description("Extend global variable defined by name in IIFE / UMD formats")),
1263
+ esModule: v.optional(v.union([v.boolean(), v.literal("if-default-prop")])),
1264
+ assetFileNames: v.optional(AssetFileNamesSchema),
1265
+ entryFileNames: v.optional(ChunkFileNamesSchema),
1266
+ chunkFileNames: v.optional(ChunkFileNamesSchema),
1267
+ cssEntryFileNames: v.optional(ChunkFileNamesSchema),
1268
+ cssChunkFileNames: v.optional(ChunkFileNamesSchema),
1269
+ sanitizeFileName: v.optional(SanitizeFileNameSchema),
1270
+ minify: v.pipe(v.optional(v.union([
1271
+ v.boolean(),
1272
+ v.string("dce-only"),
1273
+ MinifyOptionsSchema
1274
+ ])), v.description("Minify the bundled file")),
1275
+ name: v.pipe(v.optional(v.string()), v.description("Name for UMD / IIFE format outputs")),
1276
+ globals: v.pipe(v.optional(v.union([v.record(v.string(), v.string()), GlobalsFunctionSchema])), v.description("Global variable of UMD / IIFE dependencies (syntax: `key=value`)")),
1277
+ externalLiveBindings: v.pipe(v.optional(v.boolean()), v.description("external live bindings")),
1278
+ inlineDynamicImports: v.pipe(v.optional(v.boolean()), v.description("Inline dynamic imports")),
1279
+ advancedChunks: v.optional(AdvancedChunksSchema),
1280
+ comments: v.pipe(v.optional(v.union([v.literal("none"), v.literal("preserve-legal")])), v.description("Control comments in the output")),
1281
+ target: v.pipe(v.optional(v.enum(ESTarget)), v.description("The JavaScript target environment")),
1282
+ plugins: v.optional(v.custom(() => true))
1283
+ });
1284
+ const getAddonDescription = (placement, wrapper) => {
1285
+ return `Code to insert the ${colors.bold(placement)} of the bundled file (${colors.bold(wrapper)} the wrapper function)`;
1286
+ };
1287
+ const OutputCliOverrideSchema = v.strictObject({
1288
+ assetFileNames: v.pipe(v.optional(v.string()), v.description("Name pattern for asset files")),
1289
+ entryFileNames: v.pipe(v.optional(v.string()), v.description("Name pattern for emitted entry chunks")),
1290
+ chunkFileNames: v.pipe(v.optional(v.string()), v.description("Name pattern for emitted secondary chunks")),
1291
+ cssEntryFileNames: v.pipe(v.optional(v.string()), v.description("Name pattern for emitted css entry chunks")),
1292
+ cssChunkFileNames: v.pipe(v.optional(v.string()), v.description("Name pattern for emitted css secondary chunks")),
1293
+ sanitizeFileName: v.pipe(v.optional(v.boolean()), v.description("Sanitize file name")),
1294
+ banner: v.pipe(v.optional(v.string()), v.description(getAddonDescription("top", "outside"))),
1295
+ footer: v.pipe(v.optional(v.string()), v.description(getAddonDescription("bottom", "outside"))),
1296
+ intro: v.pipe(v.optional(v.string()), v.description(getAddonDescription("top", "inside"))),
1297
+ outro: v.pipe(v.optional(v.string()), v.description(getAddonDescription("bottom", "inside"))),
1298
+ esModule: v.pipe(v.optional(v.boolean()), v.description("Always generate `__esModule` marks in non-ESM formats, defaults to `if-default-prop` (use `--no-esModule` to always disable)")),
1299
+ globals: v.pipe(v.optional(v.record(v.string(), v.string())), v.description("Global variable of UMD / IIFE dependencies (syntax: `key=value`)")),
1300
+ advancedChunks: v.pipe(v.optional(v.strictObject({
1301
+ minSize: v.pipe(v.optional(v.number()), v.description("Minimum size of the chunk")),
1302
+ minShareCount: v.pipe(v.optional(v.number()), v.description("Minimum share count of the chunk"))
1303
+ })), v.description("Global variable of UMD / IIFE dependencies (syntax: `key=value`)")),
1304
+ minify: v.pipe(v.optional(v.boolean()), v.description("Minify the bundled file"))
1305
+ });
1306
+ const OutputCliOptionsSchema = v.omit(v.strictObject({
1307
+ ...OutputOptionsSchema.entries,
1308
+ ...OutputCliOverrideSchema.entries
1309
+ }), [
1310
+ "sourcemapIgnoreList",
1311
+ "sourcemapPathTransform",
1312
+ "plugins"
1313
+ ]);
1314
+ const CliOptionsSchema = v.strictObject({
1315
+ config: v.pipe(v.optional(v.union([v.string(), v.boolean()])), v.description("Path to the config file (default: `rolldown.config.js`)")),
1316
+ help: v.pipe(v.optional(v.boolean()), v.description("Show help")),
1317
+ version: v.pipe(v.optional(v.boolean()), v.description("Show version number")),
1318
+ watch: v.pipe(v.optional(v.boolean()), v.description("Watch files in bundle and rebuild on changes")),
1319
+ ...InputCliOptionsSchema.entries,
1320
+ ...OutputCliOptionsSchema.entries
1321
+ });
1322
+ const inputHelperMsgRecord = { output: { ignored: true } };
1323
+ const outputHelperMsgRecord = {};
1324
+ function validateOption(key, options) {
1325
+ if (globalThis.process?.env?.ROLLDOWN_OPTIONS_VALIDATION === "loose") return;
1326
+ let parsed = v.safeParse(key === "input" ? InputOptionsSchema : OutputOptionsSchema, options);
1327
+ if (!parsed.success) {
1328
+ const errors = parsed.issues.map((issue) => {
1329
+ const issuePaths = issue.path.map((path) => path.key);
1330
+ let issueMsg = issue.message;
1331
+ if (issue.type === "union") {
1332
+ const subIssue = issue.issues?.find((i) => !(i.type !== issue.received && i.input === issue.input));
1333
+ if (subIssue) {
1334
+ if (subIssue.path) issuePaths.push(subIssue.path.map((path) => path.key));
1335
+ issueMsg = subIssue.message;
1336
+ }
1337
+ }
1338
+ const stringPath = issuePaths.join(".");
1339
+ const helper = key === "input" ? inputHelperMsgRecord[stringPath] : outputHelperMsgRecord[stringPath];
1340
+ if (helper && helper.ignored) return "";
1341
+ return `- For the "${stringPath}". ${issueMsg}. ${helper ? helper.msg : ""}`;
1342
+ }).filter(Boolean);
1343
+ if (errors.length) throw new Error(`Failed validate ${key} options.\n` + errors.join("\n"));
1344
+ }
1345
+ }
1346
+
1347
+ //#endregion
1348
+ //#region src/constants/plugin-context.ts
1349
+ const SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF = Symbol("plugin-context-resolve-caller");
1350
+
1351
+ //#endregion
1352
+ //#region src/options/normalized-input-options.ts
1353
+ var NormalizedInputOptionsImpl = class {
1354
+ inner;
1355
+ constructor(inner, onLog) {
1356
+ this.onLog = onLog;
1357
+ this.inner = inner;
1358
+ }
1359
+ get shimMissingExports() {
1360
+ return this.inner.shimMissingExports;
1361
+ }
1362
+ get input() {
1363
+ return this.inner.input;
1364
+ }
1365
+ get cwd() {
1366
+ return this.inner.cwd ?? void 0;
1367
+ }
1368
+ get platform() {
1369
+ return this.inner.platform;
1370
+ }
1371
+ };
1372
+
1373
+ //#endregion
1374
+ //#region src/types/sourcemap.ts
1375
+ function bindingifySourcemap$1(map) {
1376
+ if (map == null) return;
1377
+ return { inner: typeof map === "string" ? map : {
1378
+ file: map.file ?? void 0,
1379
+ mappings: map.mappings,
1380
+ sourceRoot: "sourceRoot" in map ? map.sourceRoot ?? void 0 : void 0,
1381
+ sources: map.sources?.map((s) => s ?? void 0),
1382
+ sourcesContent: map.sourcesContent?.map((s) => s ?? void 0),
1383
+ names: map.names,
1384
+ x_google_ignoreList: map.x_google_ignoreList,
1385
+ debugId: "debugId" in map ? map.debugId : void 0
1386
+ } };
1387
+ }
1388
+
1389
+ //#endregion
1390
+ //#region src/utils/error.ts
1391
+ function normalizeErrors(rawErrors) {
1392
+ const errors = rawErrors.map((e) => e instanceof Error ? e : Object.assign(new Error(), {
1393
+ kind: e.kind,
1394
+ message: e.message,
1395
+ stack: void 0
1396
+ }));
1397
+ let summary = `Build failed with ${errors.length} error${errors.length < 2 ? "" : "s"}:\n`;
1398
+ for (let i = 0; i < errors.length; i++) {
1399
+ summary += "\n";
1400
+ if (i >= 5) {
1401
+ summary += "...";
1402
+ break;
1403
+ }
1404
+ summary += getErrorMessage(errors[i]);
1405
+ }
1406
+ const wrapper = new Error(summary);
1407
+ Object.defineProperty(wrapper, "errors", {
1408
+ configurable: true,
1409
+ enumerable: true,
1410
+ get: () => errors,
1411
+ set: (value) => Object.defineProperty(wrapper, "errors", {
1412
+ configurable: true,
1413
+ enumerable: true,
1414
+ value
1415
+ })
1416
+ });
1417
+ return wrapper;
1418
+ }
1419
+ function getErrorMessage(e) {
1420
+ if (Object.hasOwn(e, "kind")) return e.message;
1421
+ let s = "";
1422
+ if (e.plugin) s += `[plugin ${e.plugin}]`;
1423
+ const id = e.id ?? e.loc?.file;
1424
+ if (id) {
1425
+ s += " " + id;
1426
+ if (e.loc) s += `:${e.loc.line}:${e.loc.column}`;
1427
+ }
1428
+ if (s) s += "\n";
1429
+ const message = `${e.name ?? "Error"}: ${e.message}`;
1430
+ s += message;
1431
+ if (e.frame) s = joinNewLine(s, e.frame);
1432
+ if (e.stack) s = joinNewLine(s, e.stack.replace(message, ""));
1433
+ return s;
1434
+ }
1435
+ function joinNewLine(s1, s2) {
1436
+ return s1.replace(/\n+$/, "") + "\n" + s2.replace(/^\n+/, "");
1437
+ }
1438
+
1439
+ //#endregion
1440
+ //#region src/utils/resolved-external.ts
1441
+ function transformResolvedExternal(bindingResolvedExternal$1) {
1442
+ switch (bindingResolvedExternal$1.type) {
1443
+ case "Bool": return bindingResolvedExternal$1.field0;
1444
+ case "Absolute": return "absolute";
1445
+ case "Relative": unreachable(`The PluginContext resolve result external couldn't be 'relative'`);
1446
+ }
1447
+ }
1448
+ function bindingResolvedExternal(external) {
1449
+ if (typeof external === "boolean") return {
1450
+ type: "Bool",
1451
+ field0: external
1452
+ };
1453
+ if (external === "absolute") return { type: "Absolute" };
1454
+ if (external === "relative") return { type: "Relative" };
1455
+ }
1456
+
1457
+ //#endregion
1458
+ //#region src/utils/transform-module-info.ts
1459
+ function transformModuleInfo(info, option) {
1460
+ return {
1461
+ get ast() {
1462
+ return unsupported("ModuleInfo#ast");
1463
+ },
1464
+ get code() {
1465
+ return info.code;
1466
+ },
1467
+ id: info.id,
1468
+ importers: info.importers,
1469
+ dynamicImporters: info.dynamicImporters,
1470
+ importedIds: info.importedIds,
1471
+ dynamicallyImportedIds: info.dynamicallyImportedIds,
1472
+ exports: info.exports,
1473
+ isEntry: info.isEntry,
1474
+ ...option
1475
+ };
1476
+ }
1477
+
1478
+ //#endregion
1479
+ //#region src/utils/transform-side-effects.ts
1480
+ function bindingifySideEffects(sideEffects) {
1481
+ switch (sideEffects) {
1482
+ case true: return BindingHookSideEffects.True;
1483
+ case false: return BindingHookSideEffects.False;
1484
+ case "no-treeshake": return BindingHookSideEffects.NoTreeshake;
1485
+ case null:
1486
+ case void 0: return void 0;
1487
+ default: throw new Error(`Unexpected side effects: ${sideEffects}`);
1488
+ }
1489
+ }
1490
+
1491
+ //#endregion
1492
+ //#region src/utils/transform-sourcemap.ts
1493
+ function isEmptySourcemapFiled(array) {
1494
+ if (!array) return true;
1495
+ if (array.length === 0 || !array[0]) return true;
1496
+ return false;
1497
+ }
1498
+ function normalizeTransformHookSourcemap(id, originalCode, rawMap) {
1499
+ if (!rawMap) return;
1500
+ let map = typeof rawMap === "object" ? rawMap : JSON.parse(rawMap);
1501
+ if (isEmptySourcemapFiled(map.sourcesContent)) map.sourcesContent = [originalCode];
1502
+ if (isEmptySourcemapFiled(map.sources) || map.sources && map.sources.length === 1 && map.sources[0] !== id) map.sources = [id];
1503
+ return map;
1504
+ }
1505
+
1506
+ //#endregion
1507
+ //#region src/plugin/bindingify-hook-filter.ts
1508
+ function bindingifyStringFilter(matcher) {
1509
+ if (typeof matcher === "string" || matcher instanceof RegExp) return { include: [matcher] };
1510
+ if (Array.isArray(matcher)) return { include: matcher };
1511
+ return {
1512
+ include: matcher.include ? arraify(matcher.include) : void 0,
1513
+ exclude: matcher.exclude ? arraify(matcher.exclude) : void 0
1514
+ };
1515
+ }
1516
+ function bindingifyResolveIdFilter(filterOption) {
1517
+ return filterOption?.id ? bindingifyStringFilter(filterOption.id) : void 0;
1518
+ }
1519
+ function bindingifyLoadFilter(filterOption) {
1520
+ return filterOption?.id ? bindingifyStringFilter(filterOption.id) : void 0;
1521
+ }
1522
+ function bindingifyTransformFilter(filterOption) {
1523
+ if (!filterOption) return void 0;
1524
+ const { id, code, moduleType } = filterOption;
1525
+ let moduleTypeRet;
1526
+ if (moduleType) if (Array.isArray(moduleType)) moduleTypeRet = moduleType;
1527
+ else moduleTypeRet = moduleType.include;
1528
+ return {
1529
+ id: id ? bindingifyStringFilter(id) : void 0,
1530
+ code: code ? bindingifyStringFilter(code) : void 0,
1531
+ moduleType: moduleTypeRet
1532
+ };
1533
+ }
1534
+
1535
+ //#endregion
1536
+ //#region src/plugin/bindingify-plugin-hook-meta.ts
1537
+ function bindingifyPluginHookMeta(options) {
1538
+ return { order: bindingPluginOrder(options.order) };
1539
+ }
1540
+ function bindingPluginOrder(order) {
1541
+ switch (order) {
1542
+ case "post": return BindingPluginOrder.Post;
1543
+ case "pre": return BindingPluginOrder.Pre;
1544
+ case null:
1545
+ case void 0: return void 0;
1546
+ default: throw new Error(`Unknown plugin order: ${order}`);
1547
+ }
1548
+ }
1549
+
1550
+ //#endregion
1551
+ //#region ../../node_modules/.pnpm/oxc-parser@0.63.0/node_modules/oxc-parser/wrap.mjs
1552
+ function wrap$1(result) {
1553
+ let program, module, comments, errors;
1554
+ return {
1555
+ get program() {
1556
+ if (!program) program = jsonParseAst(result.program);
1557
+ return program;
1558
+ },
1559
+ get module() {
1560
+ if (!module) module = result.module;
1561
+ return module;
1562
+ },
1563
+ get comments() {
1564
+ if (!comments) comments = result.comments;
1565
+ return comments;
1566
+ },
1567
+ get errors() {
1568
+ if (!errors) errors = result.errors;
1569
+ return errors;
1570
+ }
1571
+ };
1572
+ }
1573
+ function jsonParseAst(ast) {
1574
+ return JSON.parse(ast, function(key, value) {
1575
+ if (value === null && key === "value" && Object.hasOwn(this, "type") && this.type === "Literal") {
1576
+ if (Object.hasOwn(this, "bigint")) return BigInt(this.bigint);
1577
+ if (Object.hasOwn(this, "regex")) {
1578
+ const { regex } = this;
1579
+ try {
1580
+ return RegExp(regex.pattern, regex.flags);
1581
+ } catch (_err) {}
1582
+ }
1583
+ }
1584
+ return value;
1585
+ });
1586
+ }
1587
+
1588
+ //#endregion
1589
+ //#region src/parse-ast-index.ts
1590
+ function wrap(result, sourceText) {
1591
+ result = wrap$1(result);
1592
+ if (result.errors.length > 0) return normalizeParseError(sourceText, result.errors);
1593
+ return result.program;
1594
+ }
1595
+ function normalizeParseError(sourceText, errors) {
1596
+ let message = `Parse failed with ${errors.length} error${errors.length < 2 ? "" : "s"}:\n`;
1597
+ for (let i = 0; i < errors.length; i++) {
1598
+ if (i >= 5) {
1599
+ message += "\n...";
1600
+ break;
1601
+ }
1602
+ const e = errors[i];
1603
+ message += e.message + "\n" + e.labels.map((label) => {
1604
+ const location = locate(sourceText, label.start, { offsetLine: 1 });
1605
+ if (!location) return;
1606
+ return getCodeFrame(sourceText, location.line, location.column);
1607
+ }).filter(Boolean).join("\n");
1608
+ }
1609
+ return error(logParseError(message));
1610
+ }
1611
+ const defaultParserOptions = {
1612
+ lang: "js",
1613
+ preserveParens: false
1614
+ };
1615
+ function parseAst(sourceText, options, filename) {
1616
+ return wrap(parseSync(filename ?? "file.js", sourceText, {
1617
+ ...defaultParserOptions,
1618
+ ...options
1619
+ }), sourceText);
1620
+ }
1621
+
1622
+ //#endregion
1623
+ //#region src/utils/asset-source.ts
1624
+ function transformAssetSource(bindingAssetSource$1) {
1625
+ return bindingAssetSource$1.inner;
1626
+ }
1627
+ function bindingAssetSource(source) {
1628
+ return { inner: source };
1629
+ }
1630
+
1631
+ //#endregion
1632
+ //#region src/plugin/plugin-context.ts
1633
+ var PluginContextImpl = class extends MinimalPluginContextImpl {
1634
+ getModuleInfo;
1635
+ constructor(outputOptions, context, plugin, data, onLog, logLevel, watchMode, currentLoadingModule) {
1636
+ super(onLog, logLevel, plugin.name, watchMode);
1637
+ this.outputOptions = outputOptions;
1638
+ this.context = context;
1639
+ this.data = data;
1640
+ this.onLog = onLog;
1641
+ this.currentLoadingModule = currentLoadingModule;
1642
+ this.getModuleInfo = (id) => this.data.getModuleInfo(id, context);
1643
+ }
1644
+ async load(options) {
1645
+ const id = options.id;
1646
+ if (id === this.currentLoadingModule) this.onLog(LOG_LEVEL_WARN, logCycleLoading(this.pluginName, this.currentLoadingModule));
1647
+ const moduleInfo = this.data.getModuleInfo(id, this.context);
1648
+ if (moduleInfo && moduleInfo.code !== null) return moduleInfo;
1649
+ const rawOptions = {
1650
+ meta: options.meta || {},
1651
+ moduleSideEffects: options.moduleSideEffects || null,
1652
+ invalidate: false
1653
+ };
1654
+ this.data.updateModuleOption(id, rawOptions);
1655
+ async function createLoadModulePromise(context, data) {
1656
+ const loadPromise = data.loadModulePromiseMap.get(id);
1657
+ if (loadPromise) return loadPromise;
1658
+ let resolveFn;
1659
+ const promise = new Promise((resolve$1, _) => {
1660
+ resolveFn = resolve$1;
1661
+ });
1662
+ data.loadModulePromiseMap.set(id, promise);
1663
+ try {
1664
+ await context.load(id, bindingifySideEffects(options.moduleSideEffects), (_success) => {
1665
+ resolveFn();
1666
+ });
1667
+ } finally {
1668
+ data.loadModulePromiseMap.delete(id);
1669
+ }
1670
+ return promise;
1671
+ }
1672
+ await createLoadModulePromise(this.context, this.data);
1673
+ return this.data.getModuleInfo(id, this.context);
1674
+ }
1675
+ async resolve(source, importer, options) {
1676
+ let receipt = void 0;
1677
+ if (options != null) receipt = this.data.saveResolveOptions(options);
1678
+ const res = await this.context.resolve(source, importer, {
1679
+ custom: receipt,
1680
+ skipSelf: options?.skipSelf
1681
+ });
1682
+ if (receipt != null) this.data.removeSavedResolveOptions(receipt);
1683
+ if (res == null) return null;
1684
+ const info = this.data.getModuleOption(res.id) || {};
1685
+ return {
1686
+ ...res,
1687
+ external: transformResolvedExternal(res.external),
1688
+ ...info
1689
+ };
1690
+ }
1691
+ emitFile = (file) => {
1692
+ if (file.type === "prebuilt-chunk") return unimplemented("PluginContext.emitFile with type prebuilt-chunk");
1693
+ if (file.type === "chunk") return this.context.emitChunk(file);
1694
+ const fnSanitizedFileName = file.fileName || typeof this.outputOptions.sanitizeFileName !== "function" ? void 0 : this.outputOptions.sanitizeFileName(file.name || "asset");
1695
+ const filename = file.fileName ? void 0 : this.getAssetFileNames(file);
1696
+ return this.context.emitFile({
1697
+ ...file,
1698
+ originalFileName: file.originalFileName || void 0,
1699
+ source: bindingAssetSource(file.source)
1700
+ }, filename, fnSanitizedFileName);
1701
+ };
1702
+ getAssetFileNames(file) {
1703
+ if (typeof this.outputOptions.assetFileNames === "function") return this.outputOptions.assetFileNames({
1704
+ names: file.name ? [file.name] : [],
1705
+ originalFileNames: file.originalFileName ? [file.originalFileName] : [],
1706
+ source: file.source,
1707
+ type: "asset"
1708
+ });
1709
+ }
1710
+ getFileName(referenceId) {
1711
+ return this.context.getFileName(referenceId);
1712
+ }
1713
+ getModuleIds() {
1714
+ return this.data.getModuleIds(this.context);
1715
+ }
1716
+ addWatchFile(id) {
1717
+ this.context.addWatchFile(id);
1718
+ }
1719
+ parse(input, options) {
1720
+ return parseAst(input, options);
1721
+ }
1722
+ };
1723
+
1724
+ //#endregion
1725
+ //#region src/plugin/transform-plugin-context.ts
1726
+ var TransformPluginContextImpl = class extends PluginContextImpl {
1727
+ constructor(outputOptions, context, plugin, data, inner, moduleId, moduleSource, onLog, LogLevelOption, watchMode) {
1728
+ super(outputOptions, context, plugin, data, onLog, LogLevelOption, watchMode, moduleId);
1729
+ this.inner = inner;
1730
+ this.moduleId = moduleId;
1731
+ this.moduleSource = moduleSource;
1732
+ const getLogHandler$1 = (handler) => (log, pos) => {
1733
+ log = normalizeLog(log);
1734
+ if (pos) augmentCodeLocation(log, pos, moduleSource, moduleId);
1735
+ log.id = moduleId;
1736
+ log.hook = "transform";
1737
+ handler(log);
1738
+ };
1739
+ this.debug = getLogHandler$1(this.debug);
1740
+ this.warn = getLogHandler$1(this.warn);
1741
+ this.info = getLogHandler$1(this.info);
1742
+ }
1743
+ error(e, pos) {
1744
+ if (typeof e === "string") e = { message: e };
1745
+ if (pos) augmentCodeLocation(e, pos, this.moduleSource, this.moduleId);
1746
+ e.id = this.moduleId;
1747
+ e.hook = "transform";
1748
+ return error(logPluginError(normalizeLog(e), this.pluginName));
1749
+ }
1750
+ getCombinedSourcemap() {
1751
+ return JSON.parse(this.inner.getCombinedSourcemap());
1752
+ }
1753
+ };
1754
+
1755
+ //#endregion
1756
+ //#region src/plugin/bindingify-build-hooks.ts
1757
+ function bindingifyBuildStart(args) {
1758
+ const hook = args.plugin.buildStart;
1759
+ if (!hook) return {};
1760
+ const { handler, meta } = normalizeHook(hook);
1761
+ return {
1762
+ plugin: async (ctx, opts) => {
1763
+ await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode), new NormalizedInputOptionsImpl(opts, args.onLog));
1764
+ },
1765
+ meta: bindingifyPluginHookMeta(meta)
1766
+ };
1767
+ }
1768
+ function bindingifyBuildEnd(args) {
1769
+ const hook = args.plugin.buildEnd;
1770
+ if (!hook) return {};
1771
+ const { handler, meta } = normalizeHook(hook);
1772
+ return {
1773
+ plugin: async (ctx, err) => {
1774
+ await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode), err ? normalizeErrors(err) : void 0);
1775
+ },
1776
+ meta: bindingifyPluginHookMeta(meta)
1777
+ };
1778
+ }
1779
+ function bindingifyResolveId(args) {
1780
+ const hook = args.plugin.resolveId;
1781
+ if (!hook) return {};
1782
+ const { handler, meta, options } = normalizeHook(hook);
1783
+ return {
1784
+ plugin: async (ctx, specifier, importer, extraOptions) => {
1785
+ const contextResolveOptions = extraOptions.custom != null ? args.pluginContextData.getSavedResolveOptions(extraOptions.custom) : void 0;
1786
+ const newExtraOptions = {
1787
+ ...extraOptions,
1788
+ custom: contextResolveOptions?.custom,
1789
+ [SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF]: contextResolveOptions?.[SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF]
1790
+ };
1791
+ const ret = await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode), specifier, importer ?? void 0, newExtraOptions);
1792
+ if (ret == null) return;
1793
+ if (ret === false) return {
1794
+ id: specifier,
1795
+ external: bindingResolvedExternal(true),
1796
+ normalizeExternalId: true
1797
+ };
1798
+ if (typeof ret === "string") return {
1799
+ id: ret,
1800
+ normalizeExternalId: true
1801
+ };
1802
+ let exist = args.pluginContextData.updateModuleOption(ret.id, {
1803
+ meta: ret.meta || {},
1804
+ moduleSideEffects: ret.moduleSideEffects ?? null,
1805
+ invalidate: false
1806
+ });
1807
+ return {
1808
+ id: ret.id,
1809
+ external: bindingResolvedExternal(ret.external),
1810
+ normalizeExternalId: false,
1811
+ sideEffects: bindingifySideEffects(exist.moduleSideEffects)
1812
+ };
1813
+ },
1814
+ meta: bindingifyPluginHookMeta(meta),
1815
+ filter: bindingifyResolveIdFilter(options.filter)
1816
+ };
1817
+ }
1818
+ function bindingifyResolveDynamicImport(args) {
1819
+ const hook = args.plugin.resolveDynamicImport;
1820
+ if (!hook) return {};
1821
+ const { handler, meta } = normalizeHook(hook);
1822
+ return {
1823
+ plugin: async (ctx, specifier, importer) => {
1824
+ const ret = await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode), specifier, importer ?? void 0);
1825
+ if (ret == null) return;
1826
+ if (ret === false) return {
1827
+ id: specifier,
1828
+ external: bindingResolvedExternal(true)
1829
+ };
1830
+ if (typeof ret === "string") return { id: ret };
1831
+ const result = {
1832
+ id: ret.id,
1833
+ external: bindingResolvedExternal(ret.external)
1834
+ };
1835
+ if (ret.moduleSideEffects !== null) result.sideEffects = bindingifySideEffects(ret.moduleSideEffects);
1836
+ args.pluginContextData.updateModuleOption(ret.id, {
1837
+ meta: ret.meta || {},
1838
+ moduleSideEffects: ret.moduleSideEffects || null,
1839
+ invalidate: false
1840
+ });
1841
+ return result;
1842
+ },
1843
+ meta: bindingifyPluginHookMeta(meta)
1844
+ };
1845
+ }
1846
+ function bindingifyTransform(args) {
1847
+ const hook = args.plugin.transform;
1848
+ if (!hook) return {};
1849
+ const { handler, meta, options } = normalizeHook(hook);
1850
+ return {
1851
+ plugin: async (ctx, code, id, meta$1) => {
1852
+ const ret = await handler.call(new TransformPluginContextImpl(args.outputOptions, ctx.inner(), args.plugin, args.pluginContextData, ctx, id, code, args.onLog, args.logLevel, args.watchMode), code, id, meta$1);
1853
+ if (ret == null) return void 0;
1854
+ if (typeof ret === "string") return { code: ret };
1855
+ let moduleOption = args.pluginContextData.updateModuleOption(id, {
1856
+ meta: ret.meta ?? {},
1857
+ moduleSideEffects: ret.moduleSideEffects ?? null,
1858
+ invalidate: false
1859
+ });
1860
+ return {
1861
+ code: ret.code,
1862
+ map: bindingifySourcemap$1(normalizeTransformHookSourcemap(id, code, ret.map)),
1863
+ sideEffects: bindingifySideEffects(moduleOption.moduleSideEffects),
1864
+ moduleType: ret.moduleType
1865
+ };
1866
+ },
1867
+ meta: bindingifyPluginHookMeta(meta),
1868
+ filter: bindingifyTransformFilter(options.filter)
1869
+ };
1870
+ }
1871
+ function bindingifyLoad(args) {
1872
+ const hook = args.plugin.load;
1873
+ if (!hook) return {};
1874
+ const { handler, meta, options } = normalizeHook(hook);
1875
+ return {
1876
+ plugin: async (ctx, id) => {
1877
+ const ret = await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode, id), id);
1878
+ if (ret == null) return;
1879
+ if (typeof ret === "string") return { code: ret };
1880
+ let moduleOption = args.pluginContextData.updateModuleOption(id, {
1881
+ meta: ret.meta || {},
1882
+ moduleSideEffects: ret.moduleSideEffects ?? null,
1883
+ invalidate: false
1884
+ });
1885
+ let map = preProcessSourceMap(ret, id);
1886
+ return {
1887
+ code: ret.code,
1888
+ map: bindingifySourcemap$1(map),
1889
+ moduleType: ret.moduleType,
1890
+ sideEffects: bindingifySideEffects(moduleOption.moduleSideEffects)
1891
+ };
1892
+ },
1893
+ meta: bindingifyPluginHookMeta(meta),
1894
+ filter: bindingifyLoadFilter(options.filter)
1895
+ };
1896
+ }
1897
+ function preProcessSourceMap(ret, id) {
1898
+ if (!ret.map) return;
1899
+ let map = typeof ret.map === "object" ? ret.map : JSON.parse(ret.map);
1900
+ if (!isEmptySourcemapFiled(map.sources)) {
1901
+ const directory = posix.dirname(id) || ".";
1902
+ const sourceRoot = map.sourceRoot || ".";
1903
+ map.sources = map.sources.map((source) => posix.resolve(directory, sourceRoot, source));
1904
+ }
1905
+ return map;
1906
+ }
1907
+ function bindingifyModuleParsed(args) {
1908
+ const hook = args.plugin.moduleParsed;
1909
+ if (!hook) return {};
1910
+ const { handler, meta } = normalizeHook(hook);
1911
+ return {
1912
+ plugin: async (ctx, moduleInfo) => {
1913
+ await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode), transformModuleInfo(moduleInfo, args.pluginContextData.getModuleOption(moduleInfo.id)));
1914
+ },
1915
+ meta: bindingifyPluginHookMeta(meta)
1916
+ };
1917
+ }
1918
+
1919
+ //#endregion
1920
+ //#region src/utils/transform-rendered-module.ts
1921
+ function transformToRenderedModule(bindingRenderedModule) {
1922
+ return {
1923
+ get code() {
1924
+ return bindingRenderedModule.code;
1925
+ },
1926
+ get renderedLength() {
1927
+ return bindingRenderedModule.code?.length || 0;
1928
+ },
1929
+ get renderedExports() {
1930
+ return bindingRenderedModule.renderedExports;
1931
+ }
1932
+ };
1933
+ }
1934
+
1935
+ //#endregion
1936
+ //#region src/utils/transform-rendered-chunk.ts
1937
+ function transformRenderedChunk(chunk) {
1938
+ let modules = null;
1939
+ return {
1940
+ get name() {
1941
+ return chunk.name;
1942
+ },
1943
+ get isEntry() {
1944
+ return chunk.isEntry;
1945
+ },
1946
+ get isDynamicEntry() {
1947
+ return chunk.isDynamicEntry;
1948
+ },
1949
+ get facadeModuleId() {
1950
+ return chunk.facadeModuleId;
1951
+ },
1952
+ get moduleIds() {
1953
+ return chunk.moduleIds;
1954
+ },
1955
+ get exports() {
1956
+ return chunk.exports;
1957
+ },
1958
+ get fileName() {
1959
+ return chunk.fileName;
1960
+ },
1961
+ get imports() {
1962
+ return chunk.imports;
1963
+ },
1964
+ get dynamicImports() {
1965
+ return chunk.dynamicImports;
1966
+ },
1967
+ get modules() {
1968
+ if (!modules) modules = transformChunkModules(chunk.modules);
1969
+ return modules;
1970
+ }
1971
+ };
1972
+ }
1973
+ function transformChunkModules(modules) {
1974
+ const result = {};
1975
+ for (let i = 0; i < modules.values.length; i++) {
1976
+ let key = modules.keys[i];
1977
+ const mod = modules.values[i];
1978
+ result[key] = transformToRenderedModule(mod);
1979
+ }
1980
+ return result;
1981
+ }
1982
+
1983
+ //#endregion
1984
+ //#region src/utils/bindingify-output-options.ts
1985
+ function bindingifyOutputOptions(outputOptions) {
1986
+ const { dir, format: format$1, exports, hashCharacters, sourcemap, sourcemapDebugIds, sourcemapIgnoreList, sourcemapPathTransform, name, assetFileNames, entryFileNames, chunkFileNames, cssEntryFileNames, cssChunkFileNames, banner, footer, intro, outro, esModule, globals, file, sanitizeFileName } = outputOptions;
1987
+ return {
1988
+ dir,
1989
+ file: file == null ? void 0 : file,
1990
+ format: bindingifyFormat(format$1),
1991
+ exports,
1992
+ hashCharacters,
1993
+ sourcemap: bindingifySourcemap(sourcemap),
1994
+ sourcemapDebugIds,
1995
+ sourcemapIgnoreList: bindingifySourcemapIgnoreList(sourcemapIgnoreList),
1996
+ sourcemapPathTransform,
1997
+ banner: bindingifyAddon(banner),
1998
+ footer: bindingifyAddon(footer),
1999
+ intro: bindingifyAddon(intro),
2000
+ outro: bindingifyAddon(outro),
2001
+ extend: outputOptions.extend,
2002
+ globals,
2003
+ esModule,
2004
+ name,
2005
+ assetFileNames: bindingifyAssetFilenames(assetFileNames),
2006
+ entryFileNames,
2007
+ chunkFileNames,
2008
+ cssEntryFileNames,
2009
+ cssChunkFileNames,
2010
+ plugins: [],
2011
+ minify: outputOptions.minify,
2012
+ externalLiveBindings: outputOptions.externalLiveBindings,
2013
+ inlineDynamicImports: outputOptions.inlineDynamicImports,
2014
+ advancedChunks: outputOptions.advancedChunks,
2015
+ polyfillRequire: outputOptions.polyfillRequire,
2016
+ target: outputOptions.target,
2017
+ sanitizeFileName
2018
+ };
2019
+ }
2020
+ function bindingifyAddon(configAddon) {
2021
+ return async (chunk) => {
2022
+ if (typeof configAddon === "function") return configAddon(transformRenderedChunk(chunk));
2023
+ return configAddon || "";
2024
+ };
2025
+ }
2026
+ function bindingifyFormat(format$1) {
2027
+ switch (format$1) {
2028
+ case void 0:
2029
+ case "es":
2030
+ case "esm":
2031
+ case "module": return "es";
2032
+ case "cjs":
2033
+ case "commonjs": return "cjs";
2034
+ case "iife": return "iife";
2035
+ case "umd": return "umd";
2036
+ case "experimental-app": return "app";
2037
+ default: unimplemented(`output.format: ${format$1}`);
2038
+ }
2039
+ }
2040
+ function bindingifySourcemap(sourcemap) {
2041
+ switch (sourcemap) {
2042
+ case true: return "file";
2043
+ case "inline": return "inline";
2044
+ case false:
2045
+ case void 0: return void 0;
2046
+ case "hidden": return "hidden";
2047
+ default: throw new Error(`unknown sourcemap: ${sourcemap}`);
2048
+ }
2049
+ }
2050
+ function bindingifySourcemapIgnoreList(sourcemapIgnoreList) {
2051
+ return typeof sourcemapIgnoreList === "function" ? sourcemapIgnoreList : sourcemapIgnoreList === false ? () => false : (relativeSourcePath, _sourcemapPath) => relativeSourcePath.includes("node_modules");
2052
+ }
2053
+ function bindingifyAssetFilenames(assetFileNames) {
2054
+ if (typeof assetFileNames === "function") return (asset) => {
2055
+ return assetFileNames({
2056
+ names: asset.names,
2057
+ originalFileNames: asset.originalFileNames,
2058
+ source: transformAssetSource(asset.source),
2059
+ type: "asset"
2060
+ });
2061
+ };
2062
+ return assetFileNames;
2063
+ }
2064
+
2065
+ //#endregion
2066
+ //#region src/options/normalized-output-options.ts
2067
+ var NormalizedOutputOptionsImpl = class {
2068
+ constructor(inner, outputOptions, normalizedOutputPlugins) {
2069
+ this.inner = inner;
2070
+ this.outputOptions = outputOptions;
2071
+ this.normalizedOutputPlugins = normalizedOutputPlugins;
2072
+ }
2073
+ get dir() {
2074
+ return this.inner.dir ?? void 0;
2075
+ }
2076
+ get entryFileNames() {
2077
+ return this.inner.entryFilenames || this.outputOptions.entryFileNames;
2078
+ }
2079
+ get chunkFileNames() {
2080
+ return this.inner.chunkFilenames || this.outputOptions.chunkFileNames;
2081
+ }
2082
+ get assetFileNames() {
2083
+ return this.inner.assetFilenames || this.outputOptions.assetFileNames;
2084
+ }
2085
+ get format() {
2086
+ return this.inner.format;
2087
+ }
2088
+ get exports() {
2089
+ return this.inner.exports;
2090
+ }
2091
+ get sourcemap() {
2092
+ return this.inner.sourcemap;
2093
+ }
2094
+ get cssEntryFileNames() {
2095
+ return this.inner.cssEntryFilenames || this.outputOptions.cssEntryFileNames;
2096
+ }
2097
+ get cssChunkFileNames() {
2098
+ return this.inner.cssChunkFilenames || this.outputOptions.cssChunkFileNames;
2099
+ }
2100
+ get shimMissingExports() {
2101
+ return this.inner.shimMissingExports;
2102
+ }
2103
+ get name() {
2104
+ return this.inner.name ?? void 0;
2105
+ }
2106
+ get file() {
2107
+ return this.inner.file ?? void 0;
2108
+ }
2109
+ get inlineDynamicImports() {
2110
+ return this.inner.inlineDynamicImports;
2111
+ }
2112
+ get externalLiveBindings() {
2113
+ return this.inner.externalLiveBindings;
2114
+ }
2115
+ get banner() {
2116
+ return normalizeAddon(this.outputOptions.banner);
2117
+ }
2118
+ get footer() {
2119
+ return normalizeAddon(this.outputOptions.footer);
2120
+ }
2121
+ get intro() {
2122
+ return normalizeAddon(this.outputOptions.intro);
2123
+ }
2124
+ get outro() {
2125
+ return normalizeAddon(this.outputOptions.outro);
2126
+ }
2127
+ get esModule() {
2128
+ return this.inner.esModule;
2129
+ }
2130
+ get extend() {
2131
+ return this.inner.extend;
2132
+ }
2133
+ get globals() {
2134
+ return this.inner.globals || this.outputOptions.globals;
2135
+ }
2136
+ get hashCharacters() {
2137
+ return this.inner.hashCharacters;
2138
+ }
2139
+ get sourcemapDebugIds() {
2140
+ return this.inner.sourcemapDebugIds;
2141
+ }
2142
+ get sourcemapIgnoreList() {
2143
+ return bindingifySourcemapIgnoreList(this.outputOptions.sourcemapIgnoreList);
2144
+ }
2145
+ get sourcemapPathTransform() {
2146
+ return this.outputOptions.sourcemapPathTransform;
2147
+ }
2148
+ get minify() {
2149
+ return this.inner.minify;
2150
+ }
2151
+ get comments() {
2152
+ return this.inner.comments;
2153
+ }
2154
+ get polyfillRequire() {
2155
+ return this.inner.polyfillRequire;
2156
+ }
2157
+ get plugins() {
2158
+ return this.normalizedOutputPlugins;
2159
+ }
2160
+ };
2161
+ function normalizeAddon(value) {
2162
+ if (typeof value === "function") return value;
2163
+ return () => value || "";
2164
+ }
2165
+
2166
+ //#endregion
2167
+ //#region src/utils/transform-to-rollup-output.ts
2168
+ function transformToRollupSourceMap(map) {
2169
+ const parsed = JSON.parse(map);
2170
+ const obj = {
2171
+ ...parsed,
2172
+ toString() {
2173
+ return JSON.stringify(obj);
2174
+ },
2175
+ toUrl() {
2176
+ return `data:application/json;charset=utf-8;base64,${Buffer.from(obj.toString(), "utf-8").toString("base64")}`;
2177
+ }
2178
+ };
2179
+ return obj;
2180
+ }
2181
+ function transformToRollupOutputChunk(bindingChunk, changed) {
2182
+ const chunk = {
2183
+ type: "chunk",
2184
+ get code() {
2185
+ return bindingChunk.code;
2186
+ },
2187
+ fileName: bindingChunk.fileName,
2188
+ name: bindingChunk.name,
2189
+ get modules() {
2190
+ return transformChunkModules(bindingChunk.modules);
2191
+ },
2192
+ get imports() {
2193
+ return bindingChunk.imports;
2194
+ },
2195
+ get dynamicImports() {
2196
+ return bindingChunk.dynamicImports;
2197
+ },
2198
+ exports: bindingChunk.exports,
2199
+ isEntry: bindingChunk.isEntry,
2200
+ facadeModuleId: bindingChunk.facadeModuleId || null,
2201
+ isDynamicEntry: bindingChunk.isDynamicEntry,
2202
+ get moduleIds() {
2203
+ return bindingChunk.moduleIds;
2204
+ },
2205
+ get map() {
2206
+ return bindingChunk.map ? transformToRollupSourceMap(bindingChunk.map) : null;
2207
+ },
2208
+ sourcemapFileName: bindingChunk.sourcemapFileName || null,
2209
+ preliminaryFileName: bindingChunk.preliminaryFileName
2210
+ };
2211
+ const cache = {};
2212
+ return new Proxy(chunk, {
2213
+ get(target, p) {
2214
+ if (p in cache) return cache[p];
2215
+ const value = target[p];
2216
+ cache[p] = value;
2217
+ return value;
2218
+ },
2219
+ set(target, p, newValue) {
2220
+ cache[p] = newValue;
2221
+ changed?.updated.add(bindingChunk.fileName);
2222
+ return true;
2223
+ },
2224
+ has(target, p) {
2225
+ if (p in cache) return true;
2226
+ return p in target;
2227
+ }
2228
+ });
2229
+ }
2230
+ function transformToRollupOutputAsset(bindingAsset, changed) {
2231
+ const asset = {
2232
+ type: "asset",
2233
+ fileName: bindingAsset.fileName,
2234
+ originalFileName: bindingAsset.originalFileName || null,
2235
+ originalFileNames: bindingAsset.originalFileNames,
2236
+ get source() {
2237
+ return transformAssetSource(bindingAsset.source);
2238
+ },
2239
+ name: bindingAsset.name ?? void 0,
2240
+ names: bindingAsset.names
2241
+ };
2242
+ const cache = {};
2243
+ return new Proxy(asset, {
2244
+ get(target, p) {
2245
+ if (p in cache) return cache[p];
2246
+ const value = target[p];
2247
+ cache[p] = value;
2248
+ return value;
2249
+ },
2250
+ set(target, p, newValue) {
2251
+ cache[p] = newValue;
2252
+ changed?.updated.add(bindingAsset.fileName);
2253
+ return true;
2254
+ }
2255
+ });
2256
+ }
2257
+ function transformToRollupOutput(output, changed) {
2258
+ handleOutputErrors(output);
2259
+ const { chunks, assets } = output;
2260
+ return { output: [...chunks.map((chunk) => transformToRollupOutputChunk(chunk, changed)), ...assets.map((asset) => transformToRollupOutputAsset(asset, changed))] };
2261
+ }
2262
+ function handleOutputErrors(output) {
2263
+ const rawErrors = output.errors;
2264
+ if (rawErrors.length > 0) throw normalizeErrors(rawErrors);
2265
+ }
2266
+ function transformToOutputBundle(output, changed) {
2267
+ const bundle = Object.fromEntries(transformToRollupOutput(output, changed).output.map((item) => [item.fileName, item]));
2268
+ return new Proxy(bundle, { deleteProperty(target, property) {
2269
+ if (typeof property === "string") changed.deleted.add(property);
2270
+ return true;
2271
+ } });
2272
+ }
2273
+ function collectChangedBundle(changed, bundle) {
2274
+ const assets = [];
2275
+ const chunks = [];
2276
+ for (const key in bundle) {
2277
+ if (changed.deleted.has(key) || !changed.updated.has(key)) continue;
2278
+ const item = bundle[key];
2279
+ if (item.type === "asset") assets.push({
2280
+ filename: item.fileName,
2281
+ originalFileNames: item.originalFileNames,
2282
+ source: bindingAssetSource(item.source),
2283
+ names: item.names
2284
+ });
2285
+ else chunks.push({
2286
+ code: item.code,
2287
+ filename: item.fileName,
2288
+ name: item.name,
2289
+ isEntry: item.isEntry,
2290
+ exports: item.exports,
2291
+ modules: {},
2292
+ imports: item.imports,
2293
+ dynamicImports: item.dynamicImports,
2294
+ facadeModuleId: item.facadeModuleId || void 0,
2295
+ isDynamicEntry: item.isDynamicEntry,
2296
+ moduleIds: item.moduleIds,
2297
+ map: bindingifySourcemap$1(item.map),
2298
+ sourcemapFilename: item.sourcemapFileName || void 0,
2299
+ preliminaryFilename: item.preliminaryFileName
2300
+ });
2301
+ }
2302
+ return {
2303
+ assets,
2304
+ chunks,
2305
+ deleted: Array.from(changed.deleted)
2306
+ };
2307
+ }
2308
+
2309
+ //#endregion
2310
+ //#region src/plugin/bindingify-output-hooks.ts
2311
+ function bindingifyRenderStart(args) {
2312
+ const hook = args.plugin.renderStart;
2313
+ if (!hook) return {};
2314
+ const { handler, meta } = normalizeHook(hook);
2315
+ return {
2316
+ plugin: async (ctx, opts) => {
2317
+ handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode), new NormalizedOutputOptionsImpl(opts, args.outputOptions, args.normalizedOutputPlugins), new NormalizedInputOptionsImpl(opts, args.onLog));
2318
+ },
2319
+ meta: bindingifyPluginHookMeta(meta)
2320
+ };
2321
+ }
2322
+ function bindingifyRenderChunk(args) {
2323
+ const hook = args.plugin.renderChunk;
2324
+ if (!hook) return {};
2325
+ const { handler, meta } = normalizeHook(hook);
2326
+ return {
2327
+ plugin: async (ctx, code, chunk, opts, meta$1) => {
2328
+ if (args.pluginContextData.getRenderChunkMeta() == null) args.pluginContextData.setRenderChunkMeta({ chunks: Object.fromEntries(Object.entries(meta$1.chunks).map(([key, value]) => [key, transformRenderedChunk(value)])) });
2329
+ const ret = await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode), code, transformRenderedChunk(chunk), new NormalizedOutputOptionsImpl(opts, args.outputOptions, args.normalizedOutputPlugins), args.pluginContextData.getRenderChunkMeta());
2330
+ if (ret == null) return;
2331
+ if (typeof ret === "string") return { code: ret };
2332
+ if (!ret.map) return { code: ret.code };
2333
+ return {
2334
+ code: ret.code,
2335
+ map: bindingifySourcemap$1(ret.map)
2336
+ };
2337
+ },
2338
+ meta: bindingifyPluginHookMeta(meta)
2339
+ };
2340
+ }
2341
+ function bindingifyAugmentChunkHash(args) {
2342
+ const hook = args.plugin.augmentChunkHash;
2343
+ if (!hook) return {};
2344
+ const { handler, meta } = normalizeHook(hook);
2345
+ return {
2346
+ plugin: async (ctx, chunk) => {
2347
+ return await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode), transformRenderedChunk(chunk));
2348
+ },
2349
+ meta: bindingifyPluginHookMeta(meta)
2350
+ };
2351
+ }
2352
+ function bindingifyRenderError(args) {
2353
+ const hook = args.plugin.renderError;
2354
+ if (!hook) return {};
2355
+ const { handler, meta } = normalizeHook(hook);
2356
+ return {
2357
+ plugin: async (ctx, err) => {
2358
+ handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode), normalizeErrors(err));
2359
+ },
2360
+ meta: bindingifyPluginHookMeta(meta)
2361
+ };
2362
+ }
2363
+ function bindingifyGenerateBundle(args) {
2364
+ const hook = args.plugin.generateBundle;
2365
+ if (!hook) return {};
2366
+ const { handler, meta } = normalizeHook(hook);
2367
+ return {
2368
+ plugin: async (ctx, bundle, isWrite, opts) => {
2369
+ const changed = {
2370
+ updated: new Set(),
2371
+ deleted: new Set()
2372
+ };
2373
+ const output = transformToOutputBundle(bundle, changed);
2374
+ await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode), new NormalizedOutputOptionsImpl(opts, args.outputOptions, args.normalizedOutputPlugins), output, isWrite);
2375
+ return collectChangedBundle(changed, output);
2376
+ },
2377
+ meta: bindingifyPluginHookMeta(meta)
2378
+ };
2379
+ }
2380
+ function bindingifyWriteBundle(args) {
2381
+ const hook = args.plugin.writeBundle;
2382
+ if (!hook) return {};
2383
+ const { handler, meta } = normalizeHook(hook);
2384
+ return {
2385
+ plugin: async (ctx, bundle, opts) => {
2386
+ const changed = {
2387
+ updated: new Set(),
2388
+ deleted: new Set()
2389
+ };
2390
+ const output = transformToOutputBundle(bundle, changed);
2391
+ await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode), new NormalizedOutputOptionsImpl(opts, args.outputOptions, args.normalizedOutputPlugins), output);
2392
+ return collectChangedBundle(changed, output);
2393
+ },
2394
+ meta: bindingifyPluginHookMeta(meta)
2395
+ };
2396
+ }
2397
+ function bindingifyCloseBundle(args) {
2398
+ const hook = args.plugin.closeBundle;
2399
+ if (!hook) return {};
2400
+ const { handler, meta } = normalizeHook(hook);
2401
+ return {
2402
+ plugin: async (ctx) => {
2403
+ await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode));
2404
+ },
2405
+ meta: bindingifyPluginHookMeta(meta)
2406
+ };
2407
+ }
2408
+ function bindingifyBanner(args) {
2409
+ const hook = args.plugin.banner;
2410
+ if (!hook) return {};
2411
+ const { handler, meta } = normalizeHook(hook);
2412
+ return {
2413
+ plugin: async (ctx, chunk) => {
2414
+ if (typeof handler === "string") return handler;
2415
+ return handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode), transformRenderedChunk(chunk));
2416
+ },
2417
+ meta: bindingifyPluginHookMeta(meta)
2418
+ };
2419
+ }
2420
+ function bindingifyFooter(args) {
2421
+ const hook = args.plugin.footer;
2422
+ if (!hook) return {};
2423
+ const { handler, meta } = normalizeHook(hook);
2424
+ return {
2425
+ plugin: async (ctx, chunk) => {
2426
+ if (typeof handler === "string") return handler;
2427
+ return handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode), transformRenderedChunk(chunk));
2428
+ },
2429
+ meta: bindingifyPluginHookMeta(meta)
2430
+ };
2431
+ }
2432
+ function bindingifyIntro(args) {
2433
+ const hook = args.plugin.intro;
2434
+ if (!hook) return {};
2435
+ const { handler, meta } = normalizeHook(hook);
2436
+ return {
2437
+ plugin: async (ctx, chunk) => {
2438
+ if (typeof handler === "string") return handler;
2439
+ return handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode), transformRenderedChunk(chunk));
2440
+ },
2441
+ meta: bindingifyPluginHookMeta(meta)
2442
+ };
2443
+ }
2444
+ function bindingifyOutro(args) {
2445
+ const hook = args.plugin.outro;
2446
+ if (!hook) return {};
2447
+ const { handler, meta } = normalizeHook(hook);
2448
+ return {
2449
+ plugin: async (ctx, chunk) => {
2450
+ if (typeof handler === "string") return handler;
2451
+ return handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode), transformRenderedChunk(chunk));
2452
+ },
2453
+ meta: bindingifyPluginHookMeta(meta)
2454
+ };
2455
+ }
2456
+
2457
+ //#endregion
2458
+ //#region src/plugin/bindingify-watch-hooks.ts
2459
+ function bindingifyWatchChange(args) {
2460
+ const hook = args.plugin.watchChange;
2461
+ if (!hook) return {};
2462
+ const { handler, meta } = normalizeHook(hook);
2463
+ return {
2464
+ plugin: async (ctx, id, event) => {
2465
+ await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode), id, { event });
2466
+ },
2467
+ meta: bindingifyPluginHookMeta(meta)
2468
+ };
2469
+ }
2470
+ function bindingifyCloseWatcher(args) {
2471
+ const hook = args.plugin.closeWatcher;
2472
+ if (!hook) return {};
2473
+ const { handler, meta } = normalizeHook(hook);
2474
+ return {
2475
+ plugin: async (ctx) => {
2476
+ await handler.call(new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode));
2477
+ },
2478
+ meta: bindingifyPluginHookMeta(meta)
2479
+ };
2480
+ }
2481
+
2482
+ //#endregion
2483
+ //#region src/plugin/bindingify-plugin.ts
2484
+ function bindingifyPlugin(plugin, options, outputOptions, pluginContextData, normalizedOutputPlugins, onLog, logLevel, watchMode) {
2485
+ const args = {
2486
+ plugin,
2487
+ options,
2488
+ outputOptions,
2489
+ pluginContextData,
2490
+ onLog,
2491
+ logLevel,
2492
+ watchMode,
2493
+ normalizedOutputPlugins
2494
+ };
2495
+ const { plugin: buildStart, meta: buildStartMeta } = bindingifyBuildStart(args);
2496
+ const { plugin: resolveId, meta: resolveIdMeta, filter: resolveIdFilter } = bindingifyResolveId(args);
2497
+ const { plugin: resolveDynamicImport, meta: resolveDynamicImportMeta } = bindingifyResolveDynamicImport(args);
2498
+ const { plugin: buildEnd, meta: buildEndMeta } = bindingifyBuildEnd(args);
2499
+ const { plugin: transform, meta: transformMeta, filter: transformFilter } = bindingifyTransform(args);
2500
+ const { plugin: moduleParsed, meta: moduleParsedMeta } = bindingifyModuleParsed(args);
2501
+ const { plugin: load, meta: loadMeta, filter: loadFilter } = bindingifyLoad(args);
2502
+ const { plugin: renderChunk, meta: renderChunkMeta } = bindingifyRenderChunk(args);
2503
+ const { plugin: augmentChunkHash, meta: augmentChunkHashMeta } = bindingifyAugmentChunkHash(args);
2504
+ const { plugin: renderStart, meta: renderStartMeta } = bindingifyRenderStart(args);
2505
+ const { plugin: renderError, meta: renderErrorMeta } = bindingifyRenderError(args);
2506
+ const { plugin: generateBundle, meta: generateBundleMeta } = bindingifyGenerateBundle(args);
2507
+ const { plugin: writeBundle, meta: writeBundleMeta } = bindingifyWriteBundle(args);
2508
+ const { plugin: closeBundle, meta: closeBundleMeta } = bindingifyCloseBundle(args);
2509
+ const { plugin: banner, meta: bannerMeta } = bindingifyBanner(args);
2510
+ const { plugin: footer, meta: footerMeta } = bindingifyFooter(args);
2511
+ const { plugin: intro, meta: introMeta } = bindingifyIntro(args);
2512
+ const { plugin: outro, meta: outroMeta } = bindingifyOutro(args);
2513
+ const { plugin: watchChange, meta: watchChangeMeta } = bindingifyWatchChange(args);
2514
+ const { plugin: closeWatcher, meta: closeWatcherMeta } = bindingifyCloseWatcher(args);
2515
+ const result = {
2516
+ name: plugin.name,
2517
+ buildStart,
2518
+ buildStartMeta,
2519
+ resolveId,
2520
+ resolveIdMeta,
2521
+ resolveIdFilter,
2522
+ resolveDynamicImport,
2523
+ resolveDynamicImportMeta,
2524
+ buildEnd,
2525
+ buildEndMeta,
2526
+ transform,
2527
+ transformMeta,
2528
+ transformFilter,
2529
+ moduleParsed,
2530
+ moduleParsedMeta,
2531
+ load,
2532
+ loadMeta,
2533
+ loadFilter,
2534
+ renderChunk,
2535
+ renderChunkMeta,
2536
+ augmentChunkHash,
2537
+ augmentChunkHashMeta,
2538
+ renderStart,
2539
+ renderStartMeta,
2540
+ renderError,
2541
+ renderErrorMeta,
2542
+ generateBundle,
2543
+ generateBundleMeta,
2544
+ writeBundle,
2545
+ writeBundleMeta,
2546
+ closeBundle,
2547
+ closeBundleMeta,
2548
+ banner,
2549
+ bannerMeta,
2550
+ footer,
2551
+ footerMeta,
2552
+ intro,
2553
+ introMeta,
2554
+ outro,
2555
+ outroMeta,
2556
+ watchChange,
2557
+ watchChangeMeta,
2558
+ closeWatcher,
2559
+ closeWatcherMeta
2560
+ };
2561
+ return wrapHandlers(result);
2562
+ }
2563
+ function wrapHandlers(plugin) {
2564
+ for (const hookName of [
2565
+ "buildStart",
2566
+ "resolveId",
2567
+ "resolveDynamicImport",
2568
+ "buildEnd",
2569
+ "transform",
2570
+ "moduleParsed",
2571
+ "load",
2572
+ "renderChunk",
2573
+ "augmentChunkHash",
2574
+ "renderStart",
2575
+ "renderError",
2576
+ "generateBundle",
2577
+ "writeBundle",
2578
+ "closeBundle",
2579
+ "banner",
2580
+ "footer",
2581
+ "intro",
2582
+ "outro",
2583
+ "watchChange",
2584
+ "closeWatcher"
2585
+ ]) {
2586
+ const handler = plugin[hookName];
2587
+ if (handler) plugin[hookName] = async (...args) => {
2588
+ try {
2589
+ return await handler(...args);
2590
+ } catch (e) {
2591
+ return error(logPluginError(e, plugin.name, {
2592
+ hook: hookName,
2593
+ id: hookName === "transform" ? args[2] : void 0
2594
+ }));
2595
+ }
2596
+ };
2597
+ }
2598
+ return plugin;
2599
+ }
2600
+
2601
+ //#endregion
2602
+ //#region src/plugin/plugin-context-data.ts
2603
+ var PluginContextData = class {
2604
+ moduleOptionMap = new Map();
2605
+ resolveOptionsMap = new Map();
2606
+ loadModulePromiseMap = new Map();
2607
+ meta = null;
2608
+ updateModuleOption(id, option) {
2609
+ const existing = this.moduleOptionMap.get(id);
2610
+ if (existing) {
2611
+ if (option.moduleSideEffects != null) existing.moduleSideEffects = option.moduleSideEffects;
2612
+ if (option.meta != null) Object.assign(existing.meta, option.meta);
2613
+ if (option.invalidate != null) existing.invalidate = option.invalidate;
2614
+ } else {
2615
+ this.moduleOptionMap.set(id, option);
2616
+ return option;
2617
+ }
2618
+ return existing;
2619
+ }
2620
+ getModuleOption(id) {
2621
+ const option = this.moduleOptionMap.get(id);
2622
+ if (!option) {
2623
+ const raw = {
2624
+ moduleSideEffects: null,
2625
+ meta: {}
2626
+ };
2627
+ this.moduleOptionMap.set(id, raw);
2628
+ return raw;
2629
+ }
2630
+ return option;
2631
+ }
2632
+ getModuleInfo(id, context) {
2633
+ const bindingInfo = context.getModuleInfo(id);
2634
+ if (bindingInfo) {
2635
+ const info = transformModuleInfo(bindingInfo, this.getModuleOption(id));
2636
+ return this.proxyModuleInfo(id, info);
2637
+ }
2638
+ return null;
2639
+ }
2640
+ proxyModuleInfo(id, info) {
2641
+ let moduleSideEffects = info.moduleSideEffects;
2642
+ Object.defineProperty(info, "moduleSideEffects", {
2643
+ get() {
2644
+ return moduleSideEffects;
2645
+ },
2646
+ set: (v$1) => {
2647
+ this.updateModuleOption(id, {
2648
+ moduleSideEffects: v$1,
2649
+ meta: info.meta,
2650
+ invalidate: true
2651
+ });
2652
+ moduleSideEffects = v$1;
2653
+ }
2654
+ });
2655
+ return info;
2656
+ }
2657
+ getModuleIds(context) {
2658
+ const moduleIds = context.getModuleIds();
2659
+ return moduleIds.values();
2660
+ }
2661
+ saveResolveOptions(options) {
2662
+ const index = this.resolveOptionsMap.size;
2663
+ this.resolveOptionsMap.set(index, options);
2664
+ return index;
2665
+ }
2666
+ getSavedResolveOptions(receipt) {
2667
+ return this.resolveOptionsMap.get(receipt);
2668
+ }
2669
+ removeSavedResolveOptions(receipt) {
2670
+ this.resolveOptionsMap.delete(receipt);
2671
+ }
2672
+ setRenderChunkMeta(meta) {
2673
+ this.meta = meta;
2674
+ }
2675
+ getRenderChunkMeta() {
2676
+ return this.meta;
2677
+ }
2678
+ };
2679
+
2680
+ //#endregion
2681
+ //#region src/utils/normalize-string-or-regex.ts
2682
+ function normalizedStringOrRegex(pattern) {
2683
+ if (!pattern) return void 0;
2684
+ if (!Array.isArray(pattern)) pattern = [pattern];
2685
+ return pattern;
2686
+ }
2687
+
2688
+ //#endregion
2689
+ //#region src/utils/bindingify-input-options.ts
2690
+ function bindingifyInputOptions(rawPlugins, inputOptions, outputOptions, normalizedOutputPlugins, onLog, logLevel, watchMode) {
2691
+ const pluginContextData = new PluginContextData();
2692
+ const plugins = rawPlugins.map((plugin) => {
2693
+ if ("_parallel" in plugin) return void 0;
2694
+ if (plugin instanceof BuiltinPlugin) return bindingifyBuiltInPlugin(plugin);
2695
+ return bindingifyPlugin(plugin, inputOptions, outputOptions, pluginContextData, normalizedOutputPlugins, onLog, logLevel, watchMode);
2696
+ });
2697
+ return {
2698
+ input: bindingifyInput(inputOptions.input),
2699
+ plugins,
2700
+ cwd: inputOptions.cwd ?? process.cwd(),
2701
+ external: bindingifyExternal(inputOptions.external),
2702
+ resolve: bindingifyResolve(inputOptions.resolve),
2703
+ platform: inputOptions.platform,
2704
+ shimMissingExports: inputOptions.shimMissingExports,
2705
+ logLevel: bindingifyLogLevel(logLevel),
2706
+ onLog,
2707
+ treeshake: bindingifyTreeshakeOptions(inputOptions.treeshake),
2708
+ moduleTypes: inputOptions.moduleTypes,
2709
+ define: inputOptions.define ? Object.entries(inputOptions.define) : void 0,
2710
+ inject: bindingifyInject(inputOptions.inject),
2711
+ experimental: {
2712
+ strictExecutionOrder: inputOptions.experimental?.strictExecutionOrder,
2713
+ disableLiveBindings: inputOptions.experimental?.disableLiveBindings,
2714
+ viteMode: inputOptions.experimental?.viteMode,
2715
+ resolveNewUrlToAsset: inputOptions.experimental?.resolveNewUrlToAsset,
2716
+ hmr: bindingifyHmr(inputOptions.experimental?.hmr)
2717
+ },
2718
+ profilerNames: inputOptions?.profilerNames,
2719
+ jsx: bindingifyJsx(inputOptions.jsx),
2720
+ transform: inputOptions.transform,
2721
+ watch: bindingifyWatch(inputOptions.watch),
2722
+ dropLabels: inputOptions.dropLabels,
2723
+ keepNames: inputOptions.keepNames,
2724
+ checks: inputOptions.checks,
2725
+ deferSyncScanData: () => {
2726
+ let ret = [];
2727
+ pluginContextData.moduleOptionMap.forEach((value, key) => {
2728
+ if (value.invalidate) ret.push({
2729
+ id: key,
2730
+ sideEffects: bindingifySideEffects(value.moduleSideEffects)
2731
+ });
2732
+ });
2733
+ return ret;
2734
+ },
2735
+ makeAbsoluteExternalsRelative: bindingifyMakeAbsoluteExternalsRelative(inputOptions.makeAbsoluteExternalsRelative),
2736
+ debug: inputOptions.debug
2737
+ };
2738
+ }
2739
+ function bindingifyHmr(hmr) {
2740
+ if (hmr) {
2741
+ if (typeof hmr === "boolean") return hmr ? {} : void 0;
2742
+ return hmr;
2743
+ }
2744
+ }
2745
+ function bindingifyExternal(external) {
2746
+ if (external) {
2747
+ if (typeof external === "function") return (id, importer, isResolved) => {
2748
+ if (id.startsWith("\0")) return false;
2749
+ return external(id, importer, isResolved) ?? false;
2750
+ };
2751
+ const externalArr = arraify(external);
2752
+ return (id, _importer, _isResolved) => {
2753
+ return externalArr.some((pat) => {
2754
+ if (pat instanceof RegExp) return pat.test(id);
2755
+ return id === pat;
2756
+ });
2757
+ };
2758
+ }
2759
+ }
2760
+ function bindingifyResolve(resolve$1) {
2761
+ if (resolve$1) {
2762
+ const { alias, extensionAlias,...rest } = resolve$1;
2763
+ return {
2764
+ alias: alias ? Object.entries(alias).map(([name, replacement]) => ({
2765
+ find: name,
2766
+ replacements: arraify(replacement)
2767
+ })) : void 0,
2768
+ extensionAlias: extensionAlias ? Object.entries(extensionAlias).map(([name, value]) => ({
2769
+ target: name,
2770
+ replacements: value
2771
+ })) : void 0,
2772
+ ...rest
2773
+ };
2774
+ }
2775
+ }
2776
+ function bindingifyInject(inject) {
2777
+ if (inject) return Object.entries(inject).map(([alias, item]) => {
2778
+ if (Array.isArray(item)) {
2779
+ if (item[1] === "*") return {
2780
+ tagNamespace: true,
2781
+ alias,
2782
+ from: item[0]
2783
+ };
2784
+ return {
2785
+ tagNamed: true,
2786
+ alias,
2787
+ from: item[0],
2788
+ imported: item[1]
2789
+ };
2790
+ } else return {
2791
+ tagNamed: true,
2792
+ imported: "default",
2793
+ alias,
2794
+ from: item
2795
+ };
2796
+ });
2797
+ }
2798
+ function bindingifyLogLevel(logLevel) {
2799
+ switch (logLevel) {
2800
+ case "silent": return BindingLogLevel.Silent;
2801
+ case "debug": return BindingLogLevel.Debug;
2802
+ case "warn": return BindingLogLevel.Warn;
2803
+ case "info": return BindingLogLevel.Info;
2804
+ default: throw new Error(`Unexpected log level: ${logLevel}`);
2805
+ }
2806
+ }
2807
+ function bindingifyInput(input) {
2808
+ if (input === void 0) return [];
2809
+ if (typeof input === "string") return [{ import: input }];
2810
+ if (Array.isArray(input)) return input.map((src) => ({ import: src }));
2811
+ return Object.entries(input).map(([name, import_path]) => {
2812
+ return {
2813
+ name,
2814
+ import: import_path
2815
+ };
2816
+ });
2817
+ }
2818
+ function bindingifyJsx(input) {
2819
+ switch (input) {
2820
+ case false: return { type: "Disable" };
2821
+ case "react": return { type: "React" };
2822
+ case "react-jsx": return { type: "ReactJsx" };
2823
+ case "preserve": return { type: "Preserve" };
2824
+ case void 0: return void 0;
2825
+ }
2826
+ if (input.mode === "preserve") return { type: "Preserve" };
2827
+ const mode = input.mode ?? "automatic";
2828
+ return {
2829
+ type: "Enable",
2830
+ field0: {
2831
+ runtime: mode,
2832
+ importSource: mode === "classic" ? input.importSource : mode === "automatic" ? input.jsxImportSource : void 0,
2833
+ pragma: input.factory,
2834
+ pragmaFrag: input.fragment,
2835
+ development: input.development,
2836
+ refresh: input.refresh
2837
+ }
2838
+ };
2839
+ }
2840
+ function bindingifyWatch(watch$1) {
2841
+ if (watch$1) return {
2842
+ buildDelay: watch$1.buildDelay,
2843
+ skipWrite: watch$1.skipWrite,
2844
+ include: normalizedStringOrRegex(watch$1.include),
2845
+ exclude: normalizedStringOrRegex(watch$1.exclude)
2846
+ };
2847
+ }
2848
+ function bindingifyTreeshakeOptions(config) {
2849
+ if (config === false) return void 0;
2850
+ if (config === true || config === void 0) return { moduleSideEffects: true };
2851
+ let normalizedConfig = {
2852
+ moduleSideEffects: true,
2853
+ annotations: config.annotations,
2854
+ manualPureFunctions: config.manualPureFunctions,
2855
+ unknownGlobalSideEffects: config.unknownGlobalSideEffects
2856
+ };
2857
+ if (config.moduleSideEffects === void 0) normalizedConfig.moduleSideEffects = true;
2858
+ else if (config.moduleSideEffects === "no-external") normalizedConfig.moduleSideEffects = [{
2859
+ external: true,
2860
+ sideEffects: false
2861
+ }, {
2862
+ external: false,
2863
+ sideEffects: true
2864
+ }];
2865
+ else normalizedConfig.moduleSideEffects = config.moduleSideEffects;
2866
+ return normalizedConfig;
2867
+ }
2868
+ function bindingifyMakeAbsoluteExternalsRelative(makeAbsoluteExternalsRelative) {
2869
+ if (makeAbsoluteExternalsRelative === "ifRelativeSource") return { type: "IfRelativeSource" };
2870
+ if (typeof makeAbsoluteExternalsRelative === "boolean") return {
2871
+ type: "Bool",
2872
+ field0: makeAbsoluteExternalsRelative
2873
+ };
2874
+ }
2875
+
2876
+ //#endregion
2877
+ //#region ../../node_modules/.pnpm/remeda@2.21.2/node_modules/remeda/dist/chunk-D6FCK2GA.js
2878
+ function u$1(o, n, a) {
2879
+ let t$1 = (r) => o(r, ...n);
2880
+ return a === void 0 ? t$1 : Object.assign(t$1, {
2881
+ lazy: a,
2882
+ lazyArgs: n
2883
+ });
2884
+ }
2885
+
2886
+ //#endregion
2887
+ //#region ../../node_modules/.pnpm/remeda@2.21.2/node_modules/remeda/dist/chunk-WIMGWYZL.js
2888
+ function u(r, n, o) {
2889
+ let a = r.length - n.length;
2890
+ if (a === 0) return r(...n);
2891
+ if (a === 1) return u$1(r, n, o);
2892
+ throw new Error("Wrong number of arguments");
2893
+ }
2894
+
2895
+ //#endregion
2896
+ //#region ../../node_modules/.pnpm/remeda@2.21.2/node_modules/remeda/dist/chunk-5NQBDF4H.js
2897
+ function t(...n) {
2898
+ return u(Object.keys, n);
2899
+ }
2900
+
2901
+ //#endregion
2902
+ //#region src/utils/plugin/index.ts
2903
+ const isPluginHookName = function() {
2904
+ const PLUGIN_HOOK_NAMES_SET = new Set(ENUMERATED_PLUGIN_HOOK_NAMES);
2905
+ return function isPluginHookName$1(hookName) {
2906
+ return PLUGIN_HOOK_NAMES_SET.has(hookName);
2907
+ };
2908
+ }();
2909
+
2910
+ //#endregion
2911
+ //#region src/utils/compose-js-plugins.ts
2912
+ const unsupportedHookName = [
2913
+ "augmentChunkHash",
2914
+ "generateBundle",
2915
+ "moduleParsed",
2916
+ "onLog",
2917
+ "options",
2918
+ "outputOptions",
2919
+ "renderError",
2920
+ "renderStart",
2921
+ "resolveDynamicImport",
2922
+ "writeBundle"
2923
+ ];
2924
+ const unsupportedHooks = new Set(unsupportedHookName);
2925
+ function isUnsupportedHooks(hookName) {
2926
+ return unsupportedHooks.has(hookName);
2927
+ }
2928
+ function createComposedPlugin(plugins) {
2929
+ const names = [];
2930
+ const batchedHooks = {};
2931
+ plugins.forEach((plugin, index) => {
2932
+ const pluginName = plugin.name || `Anonymous(index: ${index})`;
2933
+ names.push(pluginName);
2934
+ t(plugin).forEach((pluginProp) => {
2935
+ if (isUnsupportedHooks(pluginProp)) throw new Error(`Failed to compose js plugins. Plugin ${pluginName} has an unsupported hook: ${pluginProp}`);
2936
+ if (!isPluginHookName(pluginProp)) return;
2937
+ switch (pluginProp) {
2938
+ case "buildStart": {
2939
+ const handlers = batchedHooks.buildStart ?? [];
2940
+ batchedHooks.buildStart = handlers;
2941
+ if (plugin.buildStart) handlers.push([plugin.buildStart, plugin]);
2942
+ break;
2943
+ }
2944
+ case "load": {
2945
+ const handlers = batchedHooks.load ?? [];
2946
+ batchedHooks.load = handlers;
2947
+ if (plugin.load) handlers.push([plugin.load, plugin]);
2948
+ break;
2949
+ }
2950
+ case "transform": {
2951
+ const handlers = batchedHooks.transform ?? [];
2952
+ batchedHooks.transform = handlers;
2953
+ if (plugin.transform) handlers.push([plugin.transform, plugin]);
2954
+ break;
2955
+ }
2956
+ case "resolveId": {
2957
+ const handlers = batchedHooks.resolveId ?? [];
2958
+ batchedHooks.resolveId = handlers;
2959
+ if (plugin.resolveId) handlers.push([plugin.resolveId, plugin]);
2960
+ break;
2961
+ }
2962
+ case "buildEnd": {
2963
+ const handlers = batchedHooks.buildEnd ?? [];
2964
+ batchedHooks.buildEnd = handlers;
2965
+ if (plugin.buildEnd) handlers.push([plugin.buildEnd, plugin]);
2966
+ break;
2967
+ }
2968
+ case "renderChunk": {
2969
+ const handlers = batchedHooks.renderChunk ?? [];
2970
+ batchedHooks.renderChunk = handlers;
2971
+ if (plugin.renderChunk) handlers.push([plugin.renderChunk, plugin]);
2972
+ break;
2973
+ }
2974
+ case "banner":
2975
+ case "footer":
2976
+ case "intro":
2977
+ case "outro": {
2978
+ const hook = plugin[pluginProp];
2979
+ if (hook) (batchedHooks[pluginProp] ??= []).push([hook, plugin]);
2980
+ break;
2981
+ }
2982
+ case "closeBundle": {
2983
+ const handlers = batchedHooks.closeBundle ?? [];
2984
+ batchedHooks.closeBundle = handlers;
2985
+ if (plugin.closeBundle) handlers.push([plugin.closeBundle, plugin]);
2986
+ break;
2987
+ }
2988
+ case "watchChange": {
2989
+ const handlers = batchedHooks.watchChange ?? [];
2990
+ batchedHooks.watchChange = handlers;
2991
+ if (plugin.watchChange) handlers.push([plugin.watchChange, plugin]);
2992
+ break;
2993
+ }
2994
+ case "closeWatcher": {
2995
+ const handlers = batchedHooks.closeWatcher ?? [];
2996
+ batchedHooks.closeWatcher = handlers;
2997
+ if (plugin.closeWatcher) handlers.push([plugin.closeWatcher, plugin]);
2998
+ break;
2999
+ }
3000
+ default: {}
3001
+ }
3002
+ });
3003
+ });
3004
+ const composed = { name: `Composed(${names.join(", ")})` };
3005
+ const createFixedPluginResolveFnMap = new Map();
3006
+ function applyFixedPluginResolveFn(ctx, plugin) {
3007
+ const createFixedPluginResolveFn = createFixedPluginResolveFnMap.get(plugin);
3008
+ if (createFixedPluginResolveFn) ctx.resolve = createFixedPluginResolveFn(ctx, ctx.resolve.bind(ctx));
3009
+ return ctx;
3010
+ }
3011
+ if (batchedHooks.resolveId) {
3012
+ const batchedHandlers = batchedHooks.resolveId;
3013
+ const handlerSymbols = batchedHandlers.map(([_handler, plugin]) => Symbol(plugin.name ?? `Anonymous`));
3014
+ for (let handlerIdx = 0; handlerIdx < batchedHandlers.length; handlerIdx++) {
3015
+ const [_handler, plugin] = batchedHandlers[handlerIdx];
3016
+ const handlerSymbol = handlerSymbols[handlerIdx];
3017
+ const createFixedPluginResolveFn = (ctx, resolve$1) => {
3018
+ return (source, importer, rawContextResolveOptions) => {
3019
+ const contextResolveOptions = rawContextResolveOptions ?? {};
3020
+ if (contextResolveOptions.skipSelf) {
3021
+ contextResolveOptions[SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF] = handlerSymbol;
3022
+ contextResolveOptions.skipSelf = false;
3023
+ }
3024
+ return resolve$1(source, importer, contextResolveOptions);
3025
+ };
3026
+ };
3027
+ createFixedPluginResolveFnMap.set(plugin, createFixedPluginResolveFn);
3028
+ }
3029
+ composed.resolveId = async function(source, importer, rawHookResolveIdOptions) {
3030
+ const hookResolveIdOptions = rawHookResolveIdOptions;
3031
+ const symbolForCallerThatSkipSelf = hookResolveIdOptions?.[SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF];
3032
+ for (let handlerIdx = 0; handlerIdx < batchedHandlers.length; handlerIdx++) {
3033
+ const [handler, plugin] = batchedHandlers[handlerIdx];
3034
+ const handlerSymbol = handlerSymbols[handlerIdx];
3035
+ if (symbolForCallerThatSkipSelf === handlerSymbol) continue;
3036
+ const { handler: handlerFn } = normalizeHook(handler);
3037
+ const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), source, importer, rawHookResolveIdOptions);
3038
+ if (!isNullish(result)) return result;
3039
+ }
3040
+ };
3041
+ }
3042
+ t(batchedHooks).forEach((hookName) => {
3043
+ switch (hookName) {
3044
+ case "resolveId": break;
3045
+ case "buildStart": {
3046
+ if (batchedHooks.buildStart) {
3047
+ const batchedHandlers = batchedHooks.buildStart;
3048
+ composed.buildStart = async function(options) {
3049
+ await Promise.all(batchedHandlers.map(([handler, plugin]) => {
3050
+ const { handler: handlerFn } = normalizeHook(handler);
3051
+ return handlerFn.call(applyFixedPluginResolveFn(this, plugin), options);
3052
+ }));
3053
+ };
3054
+ }
3055
+ break;
3056
+ }
3057
+ case "load": {
3058
+ if (batchedHooks.load) {
3059
+ const batchedHandlers = batchedHooks.load;
3060
+ composed.load = async function(id) {
3061
+ for (const [handler, plugin] of batchedHandlers) {
3062
+ const { handler: handlerFn } = normalizeHook(handler);
3063
+ const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), id);
3064
+ if (!isNullish(result)) return result;
3065
+ }
3066
+ };
3067
+ }
3068
+ break;
3069
+ }
3070
+ case "transform": {
3071
+ if (batchedHooks.transform) {
3072
+ const batchedHandlers = batchedHooks.transform;
3073
+ composed.transform = async function(initialCode, id, moduleType) {
3074
+ let code = initialCode;
3075
+ let moduleSideEffects = void 0;
3076
+ function updateOutput(newCode, newModuleSideEffects) {
3077
+ code = newCode;
3078
+ moduleSideEffects = newModuleSideEffects ?? void 0;
3079
+ }
3080
+ for (const [handler, plugin] of batchedHandlers) {
3081
+ const { handler: handlerFn } = normalizeHook(handler);
3082
+ this.getCombinedSourcemap = () => {
3083
+ throw new Error(`The getCombinedSourcemap is not implement in transform hook at composedJsPlugins`);
3084
+ };
3085
+ const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), code, id, moduleType);
3086
+ if (!isNullish(result)) {
3087
+ if (typeof result === "string") updateOutput(result);
3088
+ else if (result.code) updateOutput(result.code, result.moduleSideEffects);
3089
+ }
3090
+ }
3091
+ return {
3092
+ code,
3093
+ moduleSideEffects
3094
+ };
3095
+ };
3096
+ }
3097
+ break;
3098
+ }
3099
+ case "buildEnd": {
3100
+ if (batchedHooks.buildEnd) {
3101
+ const batchedHandlers = batchedHooks.buildEnd;
3102
+ composed.buildEnd = async function(err) {
3103
+ await Promise.all(batchedHandlers.map(([handler, plugin]) => {
3104
+ const { handler: handlerFn } = normalizeHook(handler);
3105
+ return handlerFn.call(applyFixedPluginResolveFn(this, plugin), err);
3106
+ }));
3107
+ };
3108
+ }
3109
+ break;
3110
+ }
3111
+ case "renderChunk": {
3112
+ if (batchedHooks.renderChunk) {
3113
+ const batchedHandlers = batchedHooks.renderChunk;
3114
+ composed.renderChunk = async function(code, chunk, options, meta) {
3115
+ for (const [handler, plugin] of batchedHandlers) {
3116
+ const { handler: handlerFn } = normalizeHook(handler);
3117
+ const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), code, chunk, options, meta);
3118
+ if (!isNullish(result)) return result;
3119
+ }
3120
+ };
3121
+ }
3122
+ break;
3123
+ }
3124
+ case "banner":
3125
+ case "footer":
3126
+ case "intro":
3127
+ case "outro": {
3128
+ const hooks = batchedHooks[hookName];
3129
+ if (hooks?.length) composed[hookName] = async function(chunk) {
3130
+ const ret = [];
3131
+ for (const [hook, plugin] of hooks) {
3132
+ const { handler } = normalizeHook(hook);
3133
+ ret.push(typeof handler === "string" ? handler : await handler.call(applyFixedPluginResolveFn(this, plugin), chunk));
3134
+ }
3135
+ return ret.join("\n");
3136
+ };
3137
+ break;
3138
+ }
3139
+ case "closeBundle": {
3140
+ if (batchedHooks.closeBundle) {
3141
+ const batchedHandlers = batchedHooks.closeBundle;
3142
+ composed.closeBundle = async function() {
3143
+ await Promise.all(batchedHandlers.map(([handler, plugin]) => {
3144
+ const { handler: handlerFn } = normalizeHook(handler);
3145
+ return handlerFn.call(applyFixedPluginResolveFn(this, plugin));
3146
+ }));
3147
+ };
3148
+ }
3149
+ break;
3150
+ }
3151
+ case "watchChange": {
3152
+ if (batchedHooks.watchChange) {
3153
+ const batchedHandlers = batchedHooks.watchChange;
3154
+ composed.watchChange = async function(id, event) {
3155
+ await Promise.all(batchedHandlers.map(([handler, plugin]) => {
3156
+ const { handler: handlerFn } = normalizeHook(handler);
3157
+ return handlerFn.call(applyFixedPluginResolveFn(this, plugin), id, event);
3158
+ }));
3159
+ };
3160
+ }
3161
+ break;
3162
+ }
3163
+ case "closeWatcher": {
3164
+ if (batchedHooks.closeWatcher) {
3165
+ const batchedHandlers = batchedHooks.closeWatcher;
3166
+ composed.closeWatcher = async function() {
3167
+ await Promise.all(batchedHandlers.map(([handler, plugin]) => {
3168
+ const { handler: handlerFn } = normalizeHook(handler);
3169
+ return handlerFn.call(applyFixedPluginResolveFn(this, plugin));
3170
+ }));
3171
+ };
3172
+ }
3173
+ break;
3174
+ }
3175
+ default: {}
3176
+ }
3177
+ });
3178
+ return composed;
3179
+ }
3180
+ function isComposablePlugin(plugin) {
3181
+ if (plugin instanceof BuiltinPlugin) return false;
3182
+ if ("_parallel" in plugin) return false;
3183
+ const hasNotComposablePattern = t(plugin).some((hookName) => {
3184
+ if (!isPluginHookName(hookName)) return false;
3185
+ const OK_TO_COMPOSE = false;
3186
+ if (isUnsupportedHooks(hookName)) return !OK_TO_COMPOSE;
3187
+ if (plugin[hookName]) {
3188
+ const { meta } = normalizeHook(plugin[hookName]);
3189
+ if (meta.order === "pre" || meta.order === "post") return !OK_TO_COMPOSE;
3190
+ }
3191
+ return OK_TO_COMPOSE;
3192
+ });
3193
+ if (hasNotComposablePattern) return false;
3194
+ return true;
3195
+ }
3196
+ function composeJsPlugins(plugins) {
3197
+ const newPlugins = [];
3198
+ const toBeComposed = [];
3199
+ plugins.forEach((plugin) => {
3200
+ if (isComposablePlugin(plugin)) toBeComposed.push(plugin);
3201
+ else {
3202
+ if (toBeComposed.length > 0) {
3203
+ if (toBeComposed.length > 1) newPlugins.push(createComposedPlugin(toBeComposed));
3204
+ else newPlugins.push(toBeComposed[0]);
3205
+ toBeComposed.length = 0;
3206
+ }
3207
+ newPlugins.push(plugin);
3208
+ }
3209
+ });
3210
+ if (toBeComposed.length > 0) {
3211
+ if (toBeComposed.length > 1) newPlugins.push(createComposedPlugin(toBeComposed));
3212
+ else newPlugins.push(toBeComposed[0]);
3213
+ toBeComposed.length = 0;
3214
+ }
3215
+ return newPlugins;
3216
+ }
3217
+
3218
+ //#endregion
3219
+ //#region src/utils/create-bundler-option.ts
3220
+ async function createBundlerOptions(inputOptions, outputOptions, watchMode, isClose) {
3221
+ const inputPlugins = await normalizePluginOption(inputOptions.plugins);
3222
+ const outputPlugins = await normalizePluginOption(outputOptions.plugins);
3223
+ const logLevel = inputOptions.logLevel || LOG_LEVEL_INFO;
3224
+ const onLog = getLogger(getObjectPlugins(inputPlugins), getOnLog(inputOptions, logLevel), logLevel, watchMode);
3225
+ if (!isClose) outputOptions = PluginDriver.callOutputOptionsHook([...inputPlugins, ...outputPlugins], outputOptions, onLog, logLevel, watchMode);
3226
+ if (outputOptions.minify === true) onLog(LOG_LEVEL_WARN, logMinifyWarning());
3227
+ const normalizedOutputPlugins = await normalizePluginOption(outputOptions.plugins);
3228
+ let plugins = [...normalizePlugins(inputPlugins, ANONYMOUS_PLUGIN_PREFIX), ...checkOutputPluginOption(normalizePlugins(normalizedOutputPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX), onLog)];
3229
+ if (inputOptions.experimental?.enableComposingJsPlugins ?? false) plugins = composeJsPlugins(plugins);
3230
+ const parallelPluginInitResult = void 0;
3231
+ try {
3232
+ const bindingInputOptions = bindingifyInputOptions(plugins, inputOptions, outputOptions, normalizedOutputPlugins, onLog, logLevel, watchMode);
3233
+ const bindingOutputOptions = bindingifyOutputOptions(outputOptions);
3234
+ return {
3235
+ bundlerOptions: {
3236
+ inputOptions: bindingInputOptions,
3237
+ outputOptions: bindingOutputOptions,
3238
+ parallelPluginsRegistry: parallelPluginInitResult?.registry
3239
+ },
3240
+ inputOptions,
3241
+ onLog,
3242
+ stopWorkers: parallelPluginInitResult?.stopWorkers
3243
+ };
3244
+ } catch (e) {
3245
+ await parallelPluginInitResult?.stopWorkers();
3246
+ throw e;
3247
+ }
3248
+ }
3249
+
3250
+ //#endregion
3251
+ //#region src/utils/create-bundler.ts
3252
+ let asyncRuntimeShutdown = false;
3253
+ async function createBundler(inputOptions, outputOptions, isClose) {
3254
+ const option = await createBundlerOptions(inputOptions, outputOptions, false, isClose);
3255
+ if (asyncRuntimeShutdown) startAsyncRuntime();
3256
+ try {
3257
+ return {
3258
+ bundler: new Bundler(option.bundlerOptions),
3259
+ stopWorkers: option.stopWorkers,
3260
+ shutdown: () => {
3261
+ shutdownAsyncRuntime();
3262
+ asyncRuntimeShutdown = true;
3263
+ }
3264
+ };
3265
+ } catch (e) {
3266
+ await option.stopWorkers?.();
3267
+ throw e;
3268
+ }
3269
+ }
3270
+
3271
+ //#endregion
3272
+ //#region src/api/rolldown/rolldown-build.ts
3273
+ Symbol.asyncDispose ??= Symbol("Symbol.asyncDispose");
3274
+ var RolldownBuild = class {
3275
+ #inputOptions;
3276
+ #bundler;
3277
+ constructor(inputOptions) {
3278
+ this.#inputOptions = inputOptions;
3279
+ }
3280
+ get closed() {
3281
+ return this.#bundler?.bundler.closed ?? false;
3282
+ }
3283
+ async #getBundlerWithStopWorker(outputOptions, isClose) {
3284
+ if (this.#bundler) await this.#bundler.stopWorkers?.();
3285
+ return this.#bundler = await createBundler(this.#inputOptions, outputOptions, isClose);
3286
+ }
3287
+ async generate(outputOptions = {}) {
3288
+ validateOption("output", outputOptions);
3289
+ const { bundler } = await this.#getBundlerWithStopWorker(outputOptions);
3290
+ const output = await bundler.generate();
3291
+ return transformToRollupOutput(output);
3292
+ }
3293
+ async write(outputOptions = {}) {
3294
+ validateOption("output", outputOptions);
3295
+ const { bundler } = await this.#getBundlerWithStopWorker(outputOptions);
3296
+ const output = await bundler.write();
3297
+ return transformToRollupOutput(output);
3298
+ }
3299
+ async close() {
3300
+ const { bundler, stopWorkers, shutdown } = await this.#getBundlerWithStopWorker({}, true);
3301
+ await stopWorkers?.();
3302
+ await bundler.close();
3303
+ shutdown();
3304
+ }
3305
+ async [Symbol.asyncDispose]() {
3306
+ await this.close();
3307
+ }
3308
+ async generateHmrPatch(changedFiles) {
3309
+ return this.#bundler?.bundler.generateHmrPatch(changedFiles);
3310
+ }
3311
+ get watchFiles() {
3312
+ return this.#bundler?.bundler.watchFiles ?? [];
3313
+ }
3314
+ };
3315
+
3316
+ //#endregion
3317
+ //#region src/api/rolldown/index.ts
3318
+ const rolldown = async (input) => {
3319
+ validateOption("input", input);
3320
+ const inputOptions = await PluginDriver.callOptionsHook(input);
3321
+ return new RolldownBuild(inputOptions);
3322
+ };
3323
+
3324
+ //#endregion
3325
+ //#region src/api/build.ts
3326
+ async function build(options) {
3327
+ if (Array.isArray(options)) return Promise.all(options.map((opts) => build(opts)));
3328
+ else {
3329
+ const { output, write = true,...inputOptions } = options;
3330
+ const build$1 = await rolldown(inputOptions);
3331
+ try {
3332
+ if (write) return await build$1.write(output);
3333
+ else return await build$1.generate(output);
3334
+ } finally {
3335
+ await build$1.close();
3336
+ }
3337
+ }
3338
+ }
3339
+
3340
+ //#endregion
3341
+ //#region src/api/watch/watch-emitter.ts
3342
+ var WatcherEmitter = class {
3343
+ listeners = new Map();
3344
+ timer;
3345
+ constructor() {
3346
+ this.timer = setInterval(
3347
+ () => {},
3348
+ 1e9
3349
+ /* Low power usage */
3350
+ );
3351
+ }
3352
+ on(event, listener) {
3353
+ const listeners = this.listeners.get(event);
3354
+ if (listeners) listeners.push(listener);
3355
+ else this.listeners.set(event, [listener]);
3356
+ return this;
3357
+ }
3358
+ async onEvent(event) {
3359
+ const listeners = this.listeners.get(event.eventKind());
3360
+ if (listeners) switch (event.eventKind()) {
3361
+ case "close":
3362
+ case "restart":
3363
+ for (const listener of listeners) await listener();
3364
+ break;
3365
+ case "event":
3366
+ for (const listener of listeners) {
3367
+ const code = event.bundleEventKind();
3368
+ switch (code) {
3369
+ case "BUNDLE_END":
3370
+ const { duration, output } = event.bundleEndData();
3371
+ await listener({
3372
+ code: "BUNDLE_END",
3373
+ duration,
3374
+ output: [output]
3375
+ });
3376
+ break;
3377
+ case "ERROR":
3378
+ const errors = event.errors();
3379
+ await listener({
3380
+ code: "ERROR",
3381
+ error: normalizeErrors(errors)
3382
+ });
3383
+ break;
3384
+ default:
3385
+ await listener({ code });
3386
+ break;
3387
+ }
3388
+ }
3389
+ break;
3390
+ case "change":
3391
+ for (const listener of listeners) {
3392
+ const { path, kind } = event.watchChangeData();
3393
+ await listener(path, { event: kind });
3394
+ }
3395
+ break;
3396
+ default: throw new Error(`Unknown event: ${event}`);
3397
+ }
3398
+ }
3399
+ async close() {
3400
+ clearInterval(this.timer);
3401
+ }
3402
+ };
3403
+
3404
+ //#endregion
3405
+ //#region src/api/watch/watcher.ts
3406
+ var Watcher = class {
3407
+ closed;
3408
+ inner;
3409
+ emitter;
3410
+ stopWorkers;
3411
+ constructor(emitter, inner, stopWorkers) {
3412
+ this.closed = false;
3413
+ this.inner = inner;
3414
+ this.emitter = emitter;
3415
+ const originClose = emitter.close.bind(emitter);
3416
+ emitter.close = async () => {
3417
+ await this.close();
3418
+ originClose();
3419
+ };
3420
+ this.stopWorkers = stopWorkers;
3421
+ }
3422
+ async close() {
3423
+ if (this.closed) return;
3424
+ this.closed = true;
3425
+ for (const stop of this.stopWorkers) await stop?.();
3426
+ await this.inner.close();
3427
+ shutdownAsyncRuntime();
3428
+ }
3429
+ start() {
3430
+ process.nextTick(() => this.inner.start(this.emitter.onEvent.bind(this.emitter)));
3431
+ }
3432
+ };
3433
+ async function createWatcher(emitter, input) {
3434
+ const options = arraify(input);
3435
+ const bundlerOptions = await Promise.all(options.map((option) => arraify(option.output || {}).map(async (output) => {
3436
+ const inputOptions = await PluginDriver.callOptionsHook(option, true);
3437
+ return createBundlerOptions(inputOptions, output, true);
3438
+ })).flat());
3439
+ const notifyOptions = getValidNotifyOption(bundlerOptions);
3440
+ const bindingWatcher = new BindingWatcher(bundlerOptions.map((option) => option.bundlerOptions), notifyOptions);
3441
+ const watcher = new Watcher(emitter, bindingWatcher, bundlerOptions.map((option) => option.stopWorkers));
3442
+ watcher.start();
3443
+ }
3444
+ function getValidNotifyOption(bundlerOptions) {
3445
+ let result;
3446
+ for (const option of bundlerOptions) if (option.inputOptions.watch) {
3447
+ const notifyOption = option.inputOptions.watch.notify;
3448
+ if (notifyOption) if (result) {
3449
+ option.onLog(LOG_LEVEL_WARN, logMultiplyNotifyOption());
3450
+ return result;
3451
+ } else result = notifyOption;
3452
+ }
3453
+ }
3454
+
3455
+ //#endregion
3456
+ //#region src/api/watch/index.ts
3457
+ const watch = (input) => {
3458
+ const emitter = new WatcherEmitter();
3459
+ createWatcher(emitter, input);
3460
+ return emitter;
3461
+ };
3462
+
3463
+ //#endregion
3464
+ //#region src/plugin/with-filter.ts
3465
+ function withFilterImpl(pluginOption, filterObjectList) {
3466
+ if (isPromiseLike(pluginOption)) return pluginOption.then((p) => withFilter(p, filterObjectList));
3467
+ if (pluginOption == false || pluginOption == null) return pluginOption;
3468
+ if (Array.isArray(pluginOption)) return pluginOption.map((p) => withFilter(p, filterObjectList));
3469
+ let plugin = pluginOption;
3470
+ let filterObjectIndex = findMatchedFilterObject(plugin.name, filterObjectList);
3471
+ if (filterObjectIndex === -1) return plugin;
3472
+ let filterObject = filterObjectList[filterObjectIndex];
3473
+ Object.keys(plugin).forEach((key) => {
3474
+ switch (key) {
3475
+ case "transform":
3476
+ case "resolveId":
3477
+ case "load":
3478
+ if (!plugin[key]) return;
3479
+ if (typeof plugin[key] === "object") plugin[key].filter = filterObject[key] ?? plugin[key].filter;
3480
+ else plugin[key] = {
3481
+ handler: plugin[key],
3482
+ filter: filterObject[key]
3483
+ };
3484
+ break;
3485
+ default: break;
3486
+ }
3487
+ });
3488
+ return plugin;
3489
+ }
3490
+ function withFilter(pluginOption, filterObject) {
3491
+ return withFilterImpl(pluginOption, arraify(filterObject));
3492
+ }
3493
+ function findMatchedFilterObject(pluginName, overrideFilterObjectList) {
3494
+ if (overrideFilterObjectList.length === 1 && overrideFilterObjectList[0].pluginNamePattern === void 0) return 0;
3495
+ for (let i = 0; i < overrideFilterObjectList.length; i++) for (let j = 0; j < (overrideFilterObjectList[i].pluginNamePattern ?? []).length; j++) {
3496
+ let pattern = overrideFilterObjectList[i].pluginNamePattern[j];
3497
+ if (typeof pattern === "string" && pattern === pluginName) return i;
3498
+ else if (pattern instanceof RegExp && pattern.test(pluginName)) return i;
3499
+ }
3500
+ return -1;
3501
+ }
3502
+
3503
+ //#endregion
3504
+ //#region src/utils/define-config.ts
3505
+ function defineConfig(config) {
3506
+ return config;
3507
+ }
3508
+
3509
+ //#endregion
3510
+ //#region src/index.ts
3511
+ const VERSION = version;
3512
+
3513
+ //#endregion
3514
+ export { VERSION, build, defineConfig, rolldown, watch, withFilter };