@flairjs/webpack-loader 0.0.1-beta.1

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.
@@ -0,0 +1,4148 @@
1
+ import module$1 from "node:module";
2
+ import { existsSync, watch } from "node:fs";
3
+ import { mkdir, rm, writeFile } from "node:fs/promises";
4
+ import path, { dirname } from "node:path";
5
+ import { existsSync as existsSync$1 } from "fs";
6
+ import path$1 from "path";
7
+ import { fileURLToPath } from "node:url";
8
+ import { pathToFileURL } from "url";
9
+
10
+ //#region rolldown:runtime
11
+ var __create = Object.create;
12
+ var __defProp$1 = Object.defineProperty;
13
+ var __getOwnPropDesc$1 = Object.getOwnPropertyDescriptor;
14
+ var __getOwnPropNames$1 = Object.getOwnPropertyNames;
15
+ var __getProtoOf = Object.getPrototypeOf;
16
+ var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
17
+ var __commonJS = (cb, mod) => function() {
18
+ return mod || (0, cb[__getOwnPropNames$1(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
19
+ };
20
+ var __copyProps$1 = (to, from, except, desc) => {
21
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames$1(from), i = 0, n = keys.length, key; i < n; i++) {
22
+ key = keys[i];
23
+ if (!__hasOwnProp$1.call(to, key) && key !== except) __defProp$1(to, key, {
24
+ get: ((k) => from[k]).bind(null, key),
25
+ enumerable: !(desc = __getOwnPropDesc$1(from, key)) || desc.enumerable
26
+ });
27
+ }
28
+ return to;
29
+ };
30
+ var __reExport = (target, mod, secondTarget) => (__copyProps$1(target, mod, "default"), secondTarget && __copyProps$1(secondTarget, mod, "default"));
31
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps$1(isNodeMode || !mod || !mod.__esModule ? __defProp$1(target, "default", {
32
+ value: mod,
33
+ enumerable: true
34
+ }) : target, mod));
35
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { get: (a, b) => (typeof require !== "undefined" ? require : a)[b] }) : x)(function(x) {
36
+ if (typeof require !== "undefined") return require.apply(this, arguments);
37
+ throw Error("Calling `require` for \"" + x + "\" in an environment that doesn't expose the `require` function.");
38
+ });
39
+
40
+ //#endregion
41
+ //#region ../../node_modules/.pnpm/@rollup+plugin-typescript@12.1.4_rollup@4.50.0_tslib@2.8.1_typescript@5.9.2/node_modules/tslib/tslib.es6.js
42
+ function __awaiter(thisArg, _arguments, P, generator) {
43
+ function adopt(value) {
44
+ return value instanceof P ? value : new P(function(resolve) {
45
+ resolve(value);
46
+ });
47
+ }
48
+ return new (P || (P = Promise))(function(resolve, reject) {
49
+ function fulfilled(value) {
50
+ try {
51
+ step(generator.next(value));
52
+ } catch (e) {
53
+ reject(e);
54
+ }
55
+ }
56
+ function rejected(value) {
57
+ try {
58
+ step(generator["throw"](value));
59
+ } catch (e) {
60
+ reject(e);
61
+ }
62
+ }
63
+ function step(result) {
64
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
65
+ }
66
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
67
+ });
68
+ }
69
+ function __generator(thisArg, body) {
70
+ var _ = {
71
+ label: 0,
72
+ sent: function() {
73
+ if (t[0] & 1) throw t[1];
74
+ return t[1];
75
+ },
76
+ trys: [],
77
+ ops: []
78
+ }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
79
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
80
+ return this;
81
+ }), g;
82
+ function verb(n) {
83
+ return function(v) {
84
+ return step([n, v]);
85
+ };
86
+ }
87
+ function step(op) {
88
+ if (f) throw new TypeError("Generator is already executing.");
89
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
90
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
91
+ if (y = 0, t) op = [op[0] & 2, t.value];
92
+ switch (op[0]) {
93
+ case 0:
94
+ case 1:
95
+ t = op;
96
+ break;
97
+ case 4:
98
+ _.label++;
99
+ return {
100
+ value: op[1],
101
+ done: false
102
+ };
103
+ case 5:
104
+ _.label++;
105
+ y = op[1];
106
+ op = [0];
107
+ continue;
108
+ case 7:
109
+ op = _.ops.pop();
110
+ _.trys.pop();
111
+ continue;
112
+ default:
113
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
114
+ _ = 0;
115
+ continue;
116
+ }
117
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
118
+ _.label = op[1];
119
+ break;
120
+ }
121
+ if (op[0] === 6 && _.label < t[1]) {
122
+ _.label = t[1];
123
+ t = op;
124
+ break;
125
+ }
126
+ if (t && _.label < t[2]) {
127
+ _.label = t[2];
128
+ _.ops.push(op);
129
+ break;
130
+ }
131
+ if (t[2]) _.ops.pop();
132
+ _.trys.pop();
133
+ continue;
134
+ }
135
+ op = body.call(thisArg, _);
136
+ } catch (e) {
137
+ op = [6, e];
138
+ y = 0;
139
+ } finally {
140
+ f = t = 0;
141
+ }
142
+ if (op[0] & 5) throw op[1];
143
+ return {
144
+ value: op[0] ? op[1] : void 0,
145
+ done: true
146
+ };
147
+ }
148
+ }
149
+
150
+ //#endregion
151
+ //#region ../../node_modules/.pnpm/esbuild@0.25.10/node_modules/esbuild/lib/main.js
152
+ var require_main = /* @__PURE__ */ __commonJS({ "../../node_modules/.pnpm/esbuild@0.25.10/node_modules/esbuild/lib/main.js": ((exports, module) => {
153
+ var __defProp = Object.defineProperty;
154
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
155
+ var __getOwnPropNames = Object.getOwnPropertyNames;
156
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
157
+ var __export = (target, all) => {
158
+ for (var name in all) __defProp(target, name, {
159
+ get: all[name],
160
+ enumerable: true
161
+ });
162
+ };
163
+ var __copyProps = (to, from, except, desc) => {
164
+ if (from && typeof from === "object" || typeof from === "function") {
165
+ for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
166
+ get: () => from[key],
167
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
168
+ });
169
+ }
170
+ return to;
171
+ };
172
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
173
+ var node_exports = {};
174
+ __export(node_exports, {
175
+ analyzeMetafile: () => analyzeMetafile,
176
+ analyzeMetafileSync: () => analyzeMetafileSync,
177
+ build: () => build,
178
+ buildSync: () => buildSync,
179
+ context: () => context,
180
+ default: () => node_default,
181
+ formatMessages: () => formatMessages,
182
+ formatMessagesSync: () => formatMessagesSync,
183
+ initialize: () => initialize,
184
+ stop: () => stop,
185
+ transform: () => transform,
186
+ transformSync: () => transformSync,
187
+ version: () => version
188
+ });
189
+ module.exports = __toCommonJS(node_exports);
190
+ function encodePacket(packet) {
191
+ let visit = (value) => {
192
+ if (value === null) bb.write8(0);
193
+ else if (typeof value === "boolean") {
194
+ bb.write8(1);
195
+ bb.write8(+value);
196
+ } else if (typeof value === "number") {
197
+ bb.write8(2);
198
+ bb.write32(value | 0);
199
+ } else if (typeof value === "string") {
200
+ bb.write8(3);
201
+ bb.write(encodeUTF8(value));
202
+ } else if (value instanceof Uint8Array) {
203
+ bb.write8(4);
204
+ bb.write(value);
205
+ } else if (value instanceof Array) {
206
+ bb.write8(5);
207
+ bb.write32(value.length);
208
+ for (let item of value) visit(item);
209
+ } else {
210
+ let keys = Object.keys(value);
211
+ bb.write8(6);
212
+ bb.write32(keys.length);
213
+ for (let key of keys) {
214
+ bb.write(encodeUTF8(key));
215
+ visit(value[key]);
216
+ }
217
+ }
218
+ };
219
+ let bb = new ByteBuffer();
220
+ bb.write32(0);
221
+ bb.write32(packet.id << 1 | +!packet.isRequest);
222
+ visit(packet.value);
223
+ writeUInt32LE(bb.buf, bb.len - 4, 0);
224
+ return bb.buf.subarray(0, bb.len);
225
+ }
226
+ function decodePacket(bytes) {
227
+ let visit = () => {
228
+ switch (bb.read8()) {
229
+ case 0: return null;
230
+ case 1: return !!bb.read8();
231
+ case 2: return bb.read32();
232
+ case 3: return decodeUTF8(bb.read());
233
+ case 4: return bb.read();
234
+ case 5: {
235
+ let count = bb.read32();
236
+ let value2 = [];
237
+ for (let i = 0; i < count; i++) value2.push(visit());
238
+ return value2;
239
+ }
240
+ case 6: {
241
+ let count = bb.read32();
242
+ let value2 = {};
243
+ for (let i = 0; i < count; i++) value2[decodeUTF8(bb.read())] = visit();
244
+ return value2;
245
+ }
246
+ default: throw new Error("Invalid packet");
247
+ }
248
+ };
249
+ let bb = new ByteBuffer(bytes);
250
+ let id = bb.read32();
251
+ let isRequest = (id & 1) === 0;
252
+ id >>>= 1;
253
+ let value = visit();
254
+ if (bb.ptr !== bytes.length) throw new Error("Invalid packet");
255
+ return {
256
+ id,
257
+ isRequest,
258
+ value
259
+ };
260
+ }
261
+ var ByteBuffer = class {
262
+ constructor(buf = new Uint8Array(1024)) {
263
+ this.buf = buf;
264
+ this.len = 0;
265
+ this.ptr = 0;
266
+ }
267
+ _write(delta) {
268
+ if (this.len + delta > this.buf.length) {
269
+ let clone = new Uint8Array((this.len + delta) * 2);
270
+ clone.set(this.buf);
271
+ this.buf = clone;
272
+ }
273
+ this.len += delta;
274
+ return this.len - delta;
275
+ }
276
+ write8(value) {
277
+ let offset = this._write(1);
278
+ this.buf[offset] = value;
279
+ }
280
+ write32(value) {
281
+ let offset = this._write(4);
282
+ writeUInt32LE(this.buf, value, offset);
283
+ }
284
+ write(bytes) {
285
+ let offset = this._write(4 + bytes.length);
286
+ writeUInt32LE(this.buf, bytes.length, offset);
287
+ this.buf.set(bytes, offset + 4);
288
+ }
289
+ _read(delta) {
290
+ if (this.ptr + delta > this.buf.length) throw new Error("Invalid packet");
291
+ this.ptr += delta;
292
+ return this.ptr - delta;
293
+ }
294
+ read8() {
295
+ return this.buf[this._read(1)];
296
+ }
297
+ read32() {
298
+ return readUInt32LE(this.buf, this._read(4));
299
+ }
300
+ read() {
301
+ let length = this.read32();
302
+ let bytes = new Uint8Array(length);
303
+ let ptr = this._read(bytes.length);
304
+ bytes.set(this.buf.subarray(ptr, ptr + length));
305
+ return bytes;
306
+ }
307
+ };
308
+ var encodeUTF8;
309
+ var decodeUTF8;
310
+ var encodeInvariant;
311
+ if (typeof TextEncoder !== "undefined" && typeof TextDecoder !== "undefined") {
312
+ let encoder = new TextEncoder();
313
+ let decoder = new TextDecoder();
314
+ encodeUTF8 = (text) => encoder.encode(text);
315
+ decodeUTF8 = (bytes) => decoder.decode(bytes);
316
+ encodeInvariant = "new TextEncoder().encode(\"\")";
317
+ } else if (typeof Buffer !== "undefined") {
318
+ encodeUTF8 = (text) => Buffer.from(text);
319
+ decodeUTF8 = (bytes) => {
320
+ let { buffer, byteOffset, byteLength } = bytes;
321
+ return Buffer.from(buffer, byteOffset, byteLength).toString();
322
+ };
323
+ encodeInvariant = "Buffer.from(\"\")";
324
+ } else throw new Error("No UTF-8 codec found");
325
+ if (!(encodeUTF8("") instanceof Uint8Array)) throw new Error(`Invariant violation: "${encodeInvariant} instanceof Uint8Array" is incorrectly false
326
+
327
+ This indicates that your JavaScript environment is broken. You cannot use
328
+ esbuild in this environment because esbuild relies on this invariant. This
329
+ is not a problem with esbuild. You need to fix your environment instead.
330
+ `);
331
+ function readUInt32LE(buffer, offset) {
332
+ return buffer[offset++] | buffer[offset++] << 8 | buffer[offset++] << 16 | buffer[offset++] << 24;
333
+ }
334
+ function writeUInt32LE(buffer, value, offset) {
335
+ buffer[offset++] = value;
336
+ buffer[offset++] = value >> 8;
337
+ buffer[offset++] = value >> 16;
338
+ buffer[offset++] = value >> 24;
339
+ }
340
+ var quote = JSON.stringify;
341
+ var buildLogLevelDefault = "warning";
342
+ var transformLogLevelDefault = "silent";
343
+ function validateAndJoinStringArray(values, what) {
344
+ const toJoin = [];
345
+ for (const value of values) {
346
+ validateStringValue(value, what);
347
+ if (value.indexOf(",") >= 0) throw new Error(`Invalid ${what}: ${value}`);
348
+ toJoin.push(value);
349
+ }
350
+ return toJoin.join(",");
351
+ }
352
+ var canBeAnything = () => null;
353
+ var mustBeBoolean = (value) => typeof value === "boolean" ? null : "a boolean";
354
+ var mustBeString = (value) => typeof value === "string" ? null : "a string";
355
+ var mustBeRegExp = (value) => value instanceof RegExp ? null : "a RegExp object";
356
+ var mustBeInteger = (value) => typeof value === "number" && value === (value | 0) ? null : "an integer";
357
+ var mustBeValidPortNumber = (value) => typeof value === "number" && value === (value | 0) && value >= 0 && value <= 65535 ? null : "a valid port number";
358
+ var mustBeFunction = (value) => typeof value === "function" ? null : "a function";
359
+ var mustBeArray = (value) => Array.isArray(value) ? null : "an array";
360
+ var mustBeArrayOfStrings = (value) => Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "an array of strings";
361
+ var mustBeObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? null : "an object";
362
+ var mustBeEntryPoints = (value) => typeof value === "object" && value !== null ? null : "an array or an object";
363
+ var mustBeWebAssemblyModule = (value) => value instanceof WebAssembly.Module ? null : "a WebAssembly.Module";
364
+ var mustBeObjectOrNull = (value) => typeof value === "object" && !Array.isArray(value) ? null : "an object or null";
365
+ var mustBeStringOrBoolean = (value) => typeof value === "string" || typeof value === "boolean" ? null : "a string or a boolean";
366
+ var mustBeStringOrObject = (value) => typeof value === "string" || typeof value === "object" && value !== null && !Array.isArray(value) ? null : "a string or an object";
367
+ var mustBeStringOrArrayOfStrings = (value) => typeof value === "string" || Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "a string or an array of strings";
368
+ var mustBeStringOrUint8Array = (value) => typeof value === "string" || value instanceof Uint8Array ? null : "a string or a Uint8Array";
369
+ var mustBeStringOrURL = (value) => typeof value === "string" || value instanceof URL ? null : "a string or a URL";
370
+ function getFlag(object, keys, key, mustBeFn) {
371
+ let value = object[key];
372
+ keys[key + ""] = true;
373
+ if (value === void 0) return void 0;
374
+ let mustBe = mustBeFn(value);
375
+ if (mustBe !== null) throw new Error(`${quote(key)} must be ${mustBe}`);
376
+ return value;
377
+ }
378
+ function checkForInvalidFlags(object, keys, where) {
379
+ for (let key in object) if (!(key in keys)) throw new Error(`Invalid option ${where}: ${quote(key)}`);
380
+ }
381
+ function validateInitializeOptions(options) {
382
+ let keys = /* @__PURE__ */ Object.create(null);
383
+ let wasmURL = getFlag(options, keys, "wasmURL", mustBeStringOrURL);
384
+ let wasmModule = getFlag(options, keys, "wasmModule", mustBeWebAssemblyModule);
385
+ let worker = getFlag(options, keys, "worker", mustBeBoolean);
386
+ checkForInvalidFlags(options, keys, "in initialize() call");
387
+ return {
388
+ wasmURL,
389
+ wasmModule,
390
+ worker
391
+ };
392
+ }
393
+ function validateMangleCache(mangleCache) {
394
+ let validated;
395
+ if (mangleCache !== void 0) {
396
+ validated = /* @__PURE__ */ Object.create(null);
397
+ for (let key in mangleCache) {
398
+ let value = mangleCache[key];
399
+ if (typeof value === "string" || value === false) validated[key] = value;
400
+ else throw new Error(`Expected ${quote(key)} in mangle cache to map to either a string or false`);
401
+ }
402
+ }
403
+ return validated;
404
+ }
405
+ function pushLogFlags(flags, options, keys, isTTY2, logLevelDefault) {
406
+ let color = getFlag(options, keys, "color", mustBeBoolean);
407
+ let logLevel = getFlag(options, keys, "logLevel", mustBeString);
408
+ let logLimit = getFlag(options, keys, "logLimit", mustBeInteger);
409
+ if (color !== void 0) flags.push(`--color=${color}`);
410
+ else if (isTTY2) flags.push(`--color=true`);
411
+ flags.push(`--log-level=${logLevel || logLevelDefault}`);
412
+ flags.push(`--log-limit=${logLimit || 0}`);
413
+ }
414
+ function validateStringValue(value, what, key) {
415
+ if (typeof value !== "string") throw new Error(`Expected value for ${what}${key !== void 0 ? " " + quote(key) : ""} to be a string, got ${typeof value} instead`);
416
+ return value;
417
+ }
418
+ function pushCommonFlags(flags, options, keys) {
419
+ let legalComments = getFlag(options, keys, "legalComments", mustBeString);
420
+ let sourceRoot = getFlag(options, keys, "sourceRoot", mustBeString);
421
+ let sourcesContent = getFlag(options, keys, "sourcesContent", mustBeBoolean);
422
+ let target = getFlag(options, keys, "target", mustBeStringOrArrayOfStrings);
423
+ let format = getFlag(options, keys, "format", mustBeString);
424
+ let globalName = getFlag(options, keys, "globalName", mustBeString);
425
+ let mangleProps = getFlag(options, keys, "mangleProps", mustBeRegExp);
426
+ let reserveProps = getFlag(options, keys, "reserveProps", mustBeRegExp);
427
+ let mangleQuoted = getFlag(options, keys, "mangleQuoted", mustBeBoolean);
428
+ let minify = getFlag(options, keys, "minify", mustBeBoolean);
429
+ let minifySyntax = getFlag(options, keys, "minifySyntax", mustBeBoolean);
430
+ let minifyWhitespace = getFlag(options, keys, "minifyWhitespace", mustBeBoolean);
431
+ let minifyIdentifiers = getFlag(options, keys, "minifyIdentifiers", mustBeBoolean);
432
+ let lineLimit = getFlag(options, keys, "lineLimit", mustBeInteger);
433
+ let drop = getFlag(options, keys, "drop", mustBeArrayOfStrings);
434
+ let dropLabels = getFlag(options, keys, "dropLabels", mustBeArrayOfStrings);
435
+ let charset = getFlag(options, keys, "charset", mustBeString);
436
+ let treeShaking = getFlag(options, keys, "treeShaking", mustBeBoolean);
437
+ let ignoreAnnotations = getFlag(options, keys, "ignoreAnnotations", mustBeBoolean);
438
+ let jsx = getFlag(options, keys, "jsx", mustBeString);
439
+ let jsxFactory = getFlag(options, keys, "jsxFactory", mustBeString);
440
+ let jsxFragment = getFlag(options, keys, "jsxFragment", mustBeString);
441
+ let jsxImportSource = getFlag(options, keys, "jsxImportSource", mustBeString);
442
+ let jsxDev = getFlag(options, keys, "jsxDev", mustBeBoolean);
443
+ let jsxSideEffects = getFlag(options, keys, "jsxSideEffects", mustBeBoolean);
444
+ let define = getFlag(options, keys, "define", mustBeObject);
445
+ let logOverride = getFlag(options, keys, "logOverride", mustBeObject);
446
+ let supported = getFlag(options, keys, "supported", mustBeObject);
447
+ let pure = getFlag(options, keys, "pure", mustBeArrayOfStrings);
448
+ let keepNames = getFlag(options, keys, "keepNames", mustBeBoolean);
449
+ let platform = getFlag(options, keys, "platform", mustBeString);
450
+ let tsconfigRaw = getFlag(options, keys, "tsconfigRaw", mustBeStringOrObject);
451
+ let absPaths = getFlag(options, keys, "absPaths", mustBeArrayOfStrings);
452
+ if (legalComments) flags.push(`--legal-comments=${legalComments}`);
453
+ if (sourceRoot !== void 0) flags.push(`--source-root=${sourceRoot}`);
454
+ if (sourcesContent !== void 0) flags.push(`--sources-content=${sourcesContent}`);
455
+ if (target) flags.push(`--target=${validateAndJoinStringArray(Array.isArray(target) ? target : [target], "target")}`);
456
+ if (format) flags.push(`--format=${format}`);
457
+ if (globalName) flags.push(`--global-name=${globalName}`);
458
+ if (platform) flags.push(`--platform=${platform}`);
459
+ if (tsconfigRaw) flags.push(`--tsconfig-raw=${typeof tsconfigRaw === "string" ? tsconfigRaw : JSON.stringify(tsconfigRaw)}`);
460
+ if (minify) flags.push("--minify");
461
+ if (minifySyntax) flags.push("--minify-syntax");
462
+ if (minifyWhitespace) flags.push("--minify-whitespace");
463
+ if (minifyIdentifiers) flags.push("--minify-identifiers");
464
+ if (lineLimit) flags.push(`--line-limit=${lineLimit}`);
465
+ if (charset) flags.push(`--charset=${charset}`);
466
+ if (treeShaking !== void 0) flags.push(`--tree-shaking=${treeShaking}`);
467
+ if (ignoreAnnotations) flags.push(`--ignore-annotations`);
468
+ if (drop) for (let what of drop) flags.push(`--drop:${validateStringValue(what, "drop")}`);
469
+ if (dropLabels) flags.push(`--drop-labels=${validateAndJoinStringArray(dropLabels, "drop label")}`);
470
+ if (absPaths) flags.push(`--abs-paths=${validateAndJoinStringArray(absPaths, "abs paths")}`);
471
+ if (mangleProps) flags.push(`--mangle-props=${jsRegExpToGoRegExp(mangleProps)}`);
472
+ if (reserveProps) flags.push(`--reserve-props=${jsRegExpToGoRegExp(reserveProps)}`);
473
+ if (mangleQuoted !== void 0) flags.push(`--mangle-quoted=${mangleQuoted}`);
474
+ if (jsx) flags.push(`--jsx=${jsx}`);
475
+ if (jsxFactory) flags.push(`--jsx-factory=${jsxFactory}`);
476
+ if (jsxFragment) flags.push(`--jsx-fragment=${jsxFragment}`);
477
+ if (jsxImportSource) flags.push(`--jsx-import-source=${jsxImportSource}`);
478
+ if (jsxDev) flags.push(`--jsx-dev`);
479
+ if (jsxSideEffects) flags.push(`--jsx-side-effects`);
480
+ if (define) for (let key in define) {
481
+ if (key.indexOf("=") >= 0) throw new Error(`Invalid define: ${key}`);
482
+ flags.push(`--define:${key}=${validateStringValue(define[key], "define", key)}`);
483
+ }
484
+ if (logOverride) for (let key in logOverride) {
485
+ if (key.indexOf("=") >= 0) throw new Error(`Invalid log override: ${key}`);
486
+ flags.push(`--log-override:${key}=${validateStringValue(logOverride[key], "log override", key)}`);
487
+ }
488
+ if (supported) for (let key in supported) {
489
+ if (key.indexOf("=") >= 0) throw new Error(`Invalid supported: ${key}`);
490
+ const value = supported[key];
491
+ if (typeof value !== "boolean") throw new Error(`Expected value for supported ${quote(key)} to be a boolean, got ${typeof value} instead`);
492
+ flags.push(`--supported:${key}=${value}`);
493
+ }
494
+ if (pure) for (let fn of pure) flags.push(`--pure:${validateStringValue(fn, "pure")}`);
495
+ if (keepNames) flags.push(`--keep-names`);
496
+ }
497
+ function flagsForBuildOptions(callName, options, isTTY2, logLevelDefault, writeDefault) {
498
+ var _a2;
499
+ let flags = [];
500
+ let entries = [];
501
+ let keys = /* @__PURE__ */ Object.create(null);
502
+ let stdinContents = null;
503
+ let stdinResolveDir = null;
504
+ pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
505
+ pushCommonFlags(flags, options, keys);
506
+ let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
507
+ let bundle = getFlag(options, keys, "bundle", mustBeBoolean);
508
+ let splitting = getFlag(options, keys, "splitting", mustBeBoolean);
509
+ let preserveSymlinks = getFlag(options, keys, "preserveSymlinks", mustBeBoolean);
510
+ let metafile = getFlag(options, keys, "metafile", mustBeBoolean);
511
+ let outfile = getFlag(options, keys, "outfile", mustBeString);
512
+ let outdir = getFlag(options, keys, "outdir", mustBeString);
513
+ let outbase = getFlag(options, keys, "outbase", mustBeString);
514
+ let tsconfig = getFlag(options, keys, "tsconfig", mustBeString);
515
+ let resolveExtensions = getFlag(options, keys, "resolveExtensions", mustBeArrayOfStrings);
516
+ let nodePathsInput = getFlag(options, keys, "nodePaths", mustBeArrayOfStrings);
517
+ let mainFields = getFlag(options, keys, "mainFields", mustBeArrayOfStrings);
518
+ let conditions = getFlag(options, keys, "conditions", mustBeArrayOfStrings);
519
+ let external = getFlag(options, keys, "external", mustBeArrayOfStrings);
520
+ let packages = getFlag(options, keys, "packages", mustBeString);
521
+ let alias = getFlag(options, keys, "alias", mustBeObject);
522
+ let loader = getFlag(options, keys, "loader", mustBeObject);
523
+ let outExtension = getFlag(options, keys, "outExtension", mustBeObject);
524
+ let publicPath = getFlag(options, keys, "publicPath", mustBeString);
525
+ let entryNames = getFlag(options, keys, "entryNames", mustBeString);
526
+ let chunkNames = getFlag(options, keys, "chunkNames", mustBeString);
527
+ let assetNames = getFlag(options, keys, "assetNames", mustBeString);
528
+ let inject = getFlag(options, keys, "inject", mustBeArrayOfStrings);
529
+ let banner = getFlag(options, keys, "banner", mustBeObject);
530
+ let footer = getFlag(options, keys, "footer", mustBeObject);
531
+ let entryPoints = getFlag(options, keys, "entryPoints", mustBeEntryPoints);
532
+ let absWorkingDir = getFlag(options, keys, "absWorkingDir", mustBeString);
533
+ let stdin = getFlag(options, keys, "stdin", mustBeObject);
534
+ let write = (_a2 = getFlag(options, keys, "write", mustBeBoolean)) != null ? _a2 : writeDefault;
535
+ let allowOverwrite = getFlag(options, keys, "allowOverwrite", mustBeBoolean);
536
+ let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
537
+ keys.plugins = true;
538
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
539
+ if (sourcemap) flags.push(`--sourcemap${sourcemap === true ? "" : `=${sourcemap}`}`);
540
+ if (bundle) flags.push("--bundle");
541
+ if (allowOverwrite) flags.push("--allow-overwrite");
542
+ if (splitting) flags.push("--splitting");
543
+ if (preserveSymlinks) flags.push("--preserve-symlinks");
544
+ if (metafile) flags.push(`--metafile`);
545
+ if (outfile) flags.push(`--outfile=${outfile}`);
546
+ if (outdir) flags.push(`--outdir=${outdir}`);
547
+ if (outbase) flags.push(`--outbase=${outbase}`);
548
+ if (tsconfig) flags.push(`--tsconfig=${tsconfig}`);
549
+ if (packages) flags.push(`--packages=${packages}`);
550
+ if (resolveExtensions) flags.push(`--resolve-extensions=${validateAndJoinStringArray(resolveExtensions, "resolve extension")}`);
551
+ if (publicPath) flags.push(`--public-path=${publicPath}`);
552
+ if (entryNames) flags.push(`--entry-names=${entryNames}`);
553
+ if (chunkNames) flags.push(`--chunk-names=${chunkNames}`);
554
+ if (assetNames) flags.push(`--asset-names=${assetNames}`);
555
+ if (mainFields) flags.push(`--main-fields=${validateAndJoinStringArray(mainFields, "main field")}`);
556
+ if (conditions) flags.push(`--conditions=${validateAndJoinStringArray(conditions, "condition")}`);
557
+ if (external) for (let name of external) flags.push(`--external:${validateStringValue(name, "external")}`);
558
+ if (alias) for (let old in alias) {
559
+ if (old.indexOf("=") >= 0) throw new Error(`Invalid package name in alias: ${old}`);
560
+ flags.push(`--alias:${old}=${validateStringValue(alias[old], "alias", old)}`);
561
+ }
562
+ if (banner) for (let type in banner) {
563
+ if (type.indexOf("=") >= 0) throw new Error(`Invalid banner file type: ${type}`);
564
+ flags.push(`--banner:${type}=${validateStringValue(banner[type], "banner", type)}`);
565
+ }
566
+ if (footer) for (let type in footer) {
567
+ if (type.indexOf("=") >= 0) throw new Error(`Invalid footer file type: ${type}`);
568
+ flags.push(`--footer:${type}=${validateStringValue(footer[type], "footer", type)}`);
569
+ }
570
+ if (inject) for (let path3 of inject) flags.push(`--inject:${validateStringValue(path3, "inject")}`);
571
+ if (loader) for (let ext in loader) {
572
+ if (ext.indexOf("=") >= 0) throw new Error(`Invalid loader extension: ${ext}`);
573
+ flags.push(`--loader:${ext}=${validateStringValue(loader[ext], "loader", ext)}`);
574
+ }
575
+ if (outExtension) for (let ext in outExtension) {
576
+ if (ext.indexOf("=") >= 0) throw new Error(`Invalid out extension: ${ext}`);
577
+ flags.push(`--out-extension:${ext}=${validateStringValue(outExtension[ext], "out extension", ext)}`);
578
+ }
579
+ if (entryPoints) if (Array.isArray(entryPoints)) for (let i = 0, n = entryPoints.length; i < n; i++) {
580
+ let entryPoint = entryPoints[i];
581
+ if (typeof entryPoint === "object" && entryPoint !== null) {
582
+ let entryPointKeys = /* @__PURE__ */ Object.create(null);
583
+ let input = getFlag(entryPoint, entryPointKeys, "in", mustBeString);
584
+ let output = getFlag(entryPoint, entryPointKeys, "out", mustBeString);
585
+ checkForInvalidFlags(entryPoint, entryPointKeys, "in entry point at index " + i);
586
+ if (input === void 0) throw new Error("Missing property \"in\" for entry point at index " + i);
587
+ if (output === void 0) throw new Error("Missing property \"out\" for entry point at index " + i);
588
+ entries.push([output, input]);
589
+ } else entries.push(["", validateStringValue(entryPoint, "entry point at index " + i)]);
590
+ }
591
+ else for (let key in entryPoints) entries.push([key, validateStringValue(entryPoints[key], "entry point", key)]);
592
+ if (stdin) {
593
+ let stdinKeys = /* @__PURE__ */ Object.create(null);
594
+ let contents = getFlag(stdin, stdinKeys, "contents", mustBeStringOrUint8Array);
595
+ let resolveDir = getFlag(stdin, stdinKeys, "resolveDir", mustBeString);
596
+ let sourcefile = getFlag(stdin, stdinKeys, "sourcefile", mustBeString);
597
+ let loader2 = getFlag(stdin, stdinKeys, "loader", mustBeString);
598
+ checkForInvalidFlags(stdin, stdinKeys, "in \"stdin\" object");
599
+ if (sourcefile) flags.push(`--sourcefile=${sourcefile}`);
600
+ if (loader2) flags.push(`--loader=${loader2}`);
601
+ if (resolveDir) stdinResolveDir = resolveDir;
602
+ if (typeof contents === "string") stdinContents = encodeUTF8(contents);
603
+ else if (contents instanceof Uint8Array) stdinContents = contents;
604
+ }
605
+ let nodePaths = [];
606
+ if (nodePathsInput) for (let value of nodePathsInput) {
607
+ value += "";
608
+ nodePaths.push(value);
609
+ }
610
+ return {
611
+ entries,
612
+ flags,
613
+ write,
614
+ stdinContents,
615
+ stdinResolveDir,
616
+ absWorkingDir,
617
+ nodePaths,
618
+ mangleCache: validateMangleCache(mangleCache)
619
+ };
620
+ }
621
+ function flagsForTransformOptions(callName, options, isTTY2, logLevelDefault) {
622
+ let flags = [];
623
+ let keys = /* @__PURE__ */ Object.create(null);
624
+ pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
625
+ pushCommonFlags(flags, options, keys);
626
+ let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
627
+ let sourcefile = getFlag(options, keys, "sourcefile", mustBeString);
628
+ let loader = getFlag(options, keys, "loader", mustBeString);
629
+ let banner = getFlag(options, keys, "banner", mustBeString);
630
+ let footer = getFlag(options, keys, "footer", mustBeString);
631
+ let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
632
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
633
+ if (sourcemap) flags.push(`--sourcemap=${sourcemap === true ? "external" : sourcemap}`);
634
+ if (sourcefile) flags.push(`--sourcefile=${sourcefile}`);
635
+ if (loader) flags.push(`--loader=${loader}`);
636
+ if (banner) flags.push(`--banner=${banner}`);
637
+ if (footer) flags.push(`--footer=${footer}`);
638
+ return {
639
+ flags,
640
+ mangleCache: validateMangleCache(mangleCache)
641
+ };
642
+ }
643
+ function createChannel(streamIn) {
644
+ const requestCallbacksByKey = {};
645
+ const closeData = {
646
+ didClose: false,
647
+ reason: ""
648
+ };
649
+ let responseCallbacks = {};
650
+ let nextRequestID = 0;
651
+ let nextBuildKey = 0;
652
+ let stdout = new Uint8Array(16 * 1024);
653
+ let stdoutUsed = 0;
654
+ let readFromStdout = (chunk) => {
655
+ let limit = stdoutUsed + chunk.length;
656
+ if (limit > stdout.length) {
657
+ let swap = new Uint8Array(limit * 2);
658
+ swap.set(stdout);
659
+ stdout = swap;
660
+ }
661
+ stdout.set(chunk, stdoutUsed);
662
+ stdoutUsed += chunk.length;
663
+ let offset = 0;
664
+ while (offset + 4 <= stdoutUsed) {
665
+ let length = readUInt32LE(stdout, offset);
666
+ if (offset + 4 + length > stdoutUsed) break;
667
+ offset += 4;
668
+ handleIncomingPacket(stdout.subarray(offset, offset + length));
669
+ offset += length;
670
+ }
671
+ if (offset > 0) {
672
+ stdout.copyWithin(0, offset, stdoutUsed);
673
+ stdoutUsed -= offset;
674
+ }
675
+ };
676
+ let afterClose = (error) => {
677
+ closeData.didClose = true;
678
+ if (error) closeData.reason = ": " + (error.message || error);
679
+ const text = "The service was stopped" + closeData.reason;
680
+ for (let id in responseCallbacks) responseCallbacks[id](text, null);
681
+ responseCallbacks = {};
682
+ };
683
+ let sendRequest = (refs, value, callback) => {
684
+ if (closeData.didClose) return callback("The service is no longer running" + closeData.reason, null);
685
+ let id = nextRequestID++;
686
+ responseCallbacks[id] = (error, response) => {
687
+ try {
688
+ callback(error, response);
689
+ } finally {
690
+ if (refs) refs.unref();
691
+ }
692
+ };
693
+ if (refs) refs.ref();
694
+ streamIn.writeToStdin(encodePacket({
695
+ id,
696
+ isRequest: true,
697
+ value
698
+ }));
699
+ };
700
+ let sendResponse = (id, value) => {
701
+ if (closeData.didClose) throw new Error("The service is no longer running" + closeData.reason);
702
+ streamIn.writeToStdin(encodePacket({
703
+ id,
704
+ isRequest: false,
705
+ value
706
+ }));
707
+ };
708
+ let handleRequest = async (id, request) => {
709
+ try {
710
+ if (request.command === "ping") {
711
+ sendResponse(id, {});
712
+ return;
713
+ }
714
+ if (typeof request.key === "number") {
715
+ const requestCallbacks = requestCallbacksByKey[request.key];
716
+ if (!requestCallbacks) return;
717
+ const callback = requestCallbacks[request.command];
718
+ if (callback) {
719
+ await callback(id, request);
720
+ return;
721
+ }
722
+ }
723
+ throw new Error(`Invalid command: ` + request.command);
724
+ } catch (e) {
725
+ const errors = [extractErrorMessageV8(e, streamIn, null, void 0, "")];
726
+ try {
727
+ sendResponse(id, { errors });
728
+ } catch {}
729
+ }
730
+ };
731
+ let isFirstPacket = true;
732
+ let handleIncomingPacket = (bytes) => {
733
+ if (isFirstPacket) {
734
+ isFirstPacket = false;
735
+ let binaryVersion = String.fromCharCode(...bytes);
736
+ if (binaryVersion !== "0.25.10") throw new Error(`Cannot start service: Host version "0.25.10" does not match binary version ${quote(binaryVersion)}`);
737
+ return;
738
+ }
739
+ let packet = decodePacket(bytes);
740
+ if (packet.isRequest) handleRequest(packet.id, packet.value);
741
+ else {
742
+ let callback = responseCallbacks[packet.id];
743
+ delete responseCallbacks[packet.id];
744
+ if (packet.value.error) callback(packet.value.error, {});
745
+ else callback(null, packet.value);
746
+ }
747
+ };
748
+ let buildOrContext = ({ callName, refs, options, isTTY: isTTY2, defaultWD: defaultWD2, callback }) => {
749
+ let refCount = 0;
750
+ const buildKey = nextBuildKey++;
751
+ const requestCallbacks = {};
752
+ const buildRefs = {
753
+ ref() {
754
+ if (++refCount === 1) {
755
+ if (refs) refs.ref();
756
+ }
757
+ },
758
+ unref() {
759
+ if (--refCount === 0) {
760
+ delete requestCallbacksByKey[buildKey];
761
+ if (refs) refs.unref();
762
+ }
763
+ }
764
+ };
765
+ requestCallbacksByKey[buildKey] = requestCallbacks;
766
+ buildRefs.ref();
767
+ buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, buildRefs, streamIn, requestCallbacks, options, isTTY2, defaultWD2, (err, res) => {
768
+ try {
769
+ callback(err, res);
770
+ } finally {
771
+ buildRefs.unref();
772
+ }
773
+ });
774
+ };
775
+ let transform2 = ({ callName, refs, input, options, isTTY: isTTY2, fs: fs3, callback }) => {
776
+ const details = createObjectStash();
777
+ let start = (inputPath) => {
778
+ try {
779
+ if (typeof input !== "string" && !(input instanceof Uint8Array)) throw new Error("The input to \"transform\" must be a string or a Uint8Array");
780
+ let { flags, mangleCache } = flagsForTransformOptions(callName, options, isTTY2, transformLogLevelDefault);
781
+ let request = {
782
+ command: "transform",
783
+ flags,
784
+ inputFS: inputPath !== null,
785
+ input: inputPath !== null ? encodeUTF8(inputPath) : typeof input === "string" ? encodeUTF8(input) : input
786
+ };
787
+ if (mangleCache) request.mangleCache = mangleCache;
788
+ sendRequest(refs, request, (error, response) => {
789
+ if (error) return callback(new Error(error), null);
790
+ let errors = replaceDetailsInMessages(response.errors, details);
791
+ let warnings = replaceDetailsInMessages(response.warnings, details);
792
+ let outstanding = 1;
793
+ let next = () => {
794
+ if (--outstanding === 0) {
795
+ let result = {
796
+ warnings,
797
+ code: response.code,
798
+ map: response.map,
799
+ mangleCache: void 0,
800
+ legalComments: void 0
801
+ };
802
+ if ("legalComments" in response) result.legalComments = response == null ? void 0 : response.legalComments;
803
+ if (response.mangleCache) result.mangleCache = response == null ? void 0 : response.mangleCache;
804
+ callback(null, result);
805
+ }
806
+ };
807
+ if (errors.length > 0) return callback(failureErrorWithLog("Transform failed", errors, warnings), null);
808
+ if (response.codeFS) {
809
+ outstanding++;
810
+ fs3.readFile(response.code, (err, contents) => {
811
+ if (err !== null) callback(err, null);
812
+ else {
813
+ response.code = contents;
814
+ next();
815
+ }
816
+ });
817
+ }
818
+ if (response.mapFS) {
819
+ outstanding++;
820
+ fs3.readFile(response.map, (err, contents) => {
821
+ if (err !== null) callback(err, null);
822
+ else {
823
+ response.map = contents;
824
+ next();
825
+ }
826
+ });
827
+ }
828
+ next();
829
+ });
830
+ } catch (e) {
831
+ let flags = [];
832
+ try {
833
+ pushLogFlags(flags, options, {}, isTTY2, transformLogLevelDefault);
834
+ } catch {}
835
+ const error = extractErrorMessageV8(e, streamIn, details, void 0, "");
836
+ sendRequest(refs, {
837
+ command: "error",
838
+ flags,
839
+ error
840
+ }, () => {
841
+ error.detail = details.load(error.detail);
842
+ callback(failureErrorWithLog("Transform failed", [error], []), null);
843
+ });
844
+ }
845
+ };
846
+ if ((typeof input === "string" || input instanceof Uint8Array) && input.length > 1024 * 1024) {
847
+ let next = start;
848
+ start = () => fs3.writeFile(input, next);
849
+ }
850
+ start(null);
851
+ };
852
+ let formatMessages2 = ({ callName, refs, messages, options, callback }) => {
853
+ if (!options) throw new Error(`Missing second argument in ${callName}() call`);
854
+ let keys = {};
855
+ let kind = getFlag(options, keys, "kind", mustBeString);
856
+ let color = getFlag(options, keys, "color", mustBeBoolean);
857
+ let terminalWidth = getFlag(options, keys, "terminalWidth", mustBeInteger);
858
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
859
+ if (kind === void 0) throw new Error(`Missing "kind" in ${callName}() call`);
860
+ if (kind !== "error" && kind !== "warning") throw new Error(`Expected "kind" to be "error" or "warning" in ${callName}() call`);
861
+ let request = {
862
+ command: "format-msgs",
863
+ messages: sanitizeMessages(messages, "messages", null, "", terminalWidth),
864
+ isWarning: kind === "warning"
865
+ };
866
+ if (color !== void 0) request.color = color;
867
+ if (terminalWidth !== void 0) request.terminalWidth = terminalWidth;
868
+ sendRequest(refs, request, (error, response) => {
869
+ if (error) return callback(new Error(error), null);
870
+ callback(null, response.messages);
871
+ });
872
+ };
873
+ let analyzeMetafile2 = ({ callName, refs, metafile, options, callback }) => {
874
+ if (options === void 0) options = {};
875
+ let keys = {};
876
+ let color = getFlag(options, keys, "color", mustBeBoolean);
877
+ let verbose = getFlag(options, keys, "verbose", mustBeBoolean);
878
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
879
+ let request = {
880
+ command: "analyze-metafile",
881
+ metafile
882
+ };
883
+ if (color !== void 0) request.color = color;
884
+ if (verbose !== void 0) request.verbose = verbose;
885
+ sendRequest(refs, request, (error, response) => {
886
+ if (error) return callback(new Error(error), null);
887
+ callback(null, response.result);
888
+ });
889
+ };
890
+ return {
891
+ readFromStdout,
892
+ afterClose,
893
+ service: {
894
+ buildOrContext,
895
+ transform: transform2,
896
+ formatMessages: formatMessages2,
897
+ analyzeMetafile: analyzeMetafile2
898
+ }
899
+ };
900
+ }
901
+ function buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, isTTY2, defaultWD2, callback) {
902
+ const details = createObjectStash();
903
+ const isContext = callName === "context";
904
+ const handleError = (e, pluginName) => {
905
+ const flags = [];
906
+ try {
907
+ pushLogFlags(flags, options, {}, isTTY2, buildLogLevelDefault);
908
+ } catch {}
909
+ const message = extractErrorMessageV8(e, streamIn, details, void 0, pluginName);
910
+ sendRequest(refs, {
911
+ command: "error",
912
+ flags,
913
+ error: message
914
+ }, () => {
915
+ message.detail = details.load(message.detail);
916
+ callback(failureErrorWithLog(isContext ? "Context failed" : "Build failed", [message], []), null);
917
+ });
918
+ };
919
+ let plugins;
920
+ if (typeof options === "object") {
921
+ const value = options.plugins;
922
+ if (value !== void 0) {
923
+ if (!Array.isArray(value)) return handleError(/* @__PURE__ */ new Error(`"plugins" must be an array`), "");
924
+ plugins = value;
925
+ }
926
+ }
927
+ if (plugins && plugins.length > 0) {
928
+ if (streamIn.isSync) return handleError(/* @__PURE__ */ new Error("Cannot use plugins in synchronous API calls"), "");
929
+ handlePlugins(buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, plugins, details).then((result) => {
930
+ if (!result.ok) return handleError(result.error, result.pluginName);
931
+ try {
932
+ buildOrContextContinue(result.requestPlugins, result.runOnEndCallbacks, result.scheduleOnDisposeCallbacks);
933
+ } catch (e) {
934
+ handleError(e, "");
935
+ }
936
+ }, (e) => handleError(e, ""));
937
+ return;
938
+ }
939
+ try {
940
+ buildOrContextContinue(null, (result, done) => done([], []), () => {});
941
+ } catch (e) {
942
+ handleError(e, "");
943
+ }
944
+ function buildOrContextContinue(requestPlugins, runOnEndCallbacks, scheduleOnDisposeCallbacks) {
945
+ const writeDefault = streamIn.hasFS;
946
+ const { entries, flags, write, stdinContents, stdinResolveDir, absWorkingDir, nodePaths, mangleCache } = flagsForBuildOptions(callName, options, isTTY2, buildLogLevelDefault, writeDefault);
947
+ if (write && !streamIn.hasFS) throw new Error(`The "write" option is unavailable in this environment`);
948
+ const request = {
949
+ command: "build",
950
+ key: buildKey,
951
+ entries,
952
+ flags,
953
+ write,
954
+ stdinContents,
955
+ stdinResolveDir,
956
+ absWorkingDir: absWorkingDir || defaultWD2,
957
+ nodePaths,
958
+ context: isContext
959
+ };
960
+ if (requestPlugins) request.plugins = requestPlugins;
961
+ if (mangleCache) request.mangleCache = mangleCache;
962
+ const buildResponseToResult = (response, callback2) => {
963
+ const result = {
964
+ errors: replaceDetailsInMessages(response.errors, details),
965
+ warnings: replaceDetailsInMessages(response.warnings, details),
966
+ outputFiles: void 0,
967
+ metafile: void 0,
968
+ mangleCache: void 0
969
+ };
970
+ const originalErrors = result.errors.slice();
971
+ const originalWarnings = result.warnings.slice();
972
+ if (response.outputFiles) result.outputFiles = response.outputFiles.map(convertOutputFiles);
973
+ if (response.metafile) result.metafile = JSON.parse(response.metafile);
974
+ if (response.mangleCache) result.mangleCache = response.mangleCache;
975
+ if (response.writeToStdout !== void 0) console.log(decodeUTF8(response.writeToStdout).replace(/\n$/, ""));
976
+ runOnEndCallbacks(result, (onEndErrors, onEndWarnings) => {
977
+ if (originalErrors.length > 0 || onEndErrors.length > 0) {
978
+ const error = failureErrorWithLog("Build failed", originalErrors.concat(onEndErrors), originalWarnings.concat(onEndWarnings));
979
+ return callback2(error, null, onEndErrors, onEndWarnings);
980
+ }
981
+ callback2(null, result, onEndErrors, onEndWarnings);
982
+ });
983
+ };
984
+ let latestResultPromise;
985
+ let provideLatestResult;
986
+ if (isContext) requestCallbacks["on-end"] = (id, request2) => new Promise((resolve) => {
987
+ buildResponseToResult(request2, (err, result, onEndErrors, onEndWarnings) => {
988
+ const response = {
989
+ errors: onEndErrors,
990
+ warnings: onEndWarnings
991
+ };
992
+ if (provideLatestResult) provideLatestResult(err, result);
993
+ latestResultPromise = void 0;
994
+ provideLatestResult = void 0;
995
+ sendResponse(id, response);
996
+ resolve();
997
+ });
998
+ });
999
+ sendRequest(refs, request, (error, response) => {
1000
+ if (error) return callback(new Error(error), null);
1001
+ if (!isContext) return buildResponseToResult(response, (err, res) => {
1002
+ scheduleOnDisposeCallbacks();
1003
+ return callback(err, res);
1004
+ });
1005
+ if (response.errors.length > 0) return callback(failureErrorWithLog("Context failed", response.errors, response.warnings), null);
1006
+ let didDispose = false;
1007
+ const result = {
1008
+ rebuild: () => {
1009
+ if (!latestResultPromise) latestResultPromise = new Promise((resolve, reject) => {
1010
+ let settlePromise;
1011
+ provideLatestResult = (err, result2) => {
1012
+ if (!settlePromise) settlePromise = () => err ? reject(err) : resolve(result2);
1013
+ };
1014
+ const triggerAnotherBuild = () => {
1015
+ sendRequest(refs, {
1016
+ command: "rebuild",
1017
+ key: buildKey
1018
+ }, (error2, response2) => {
1019
+ if (error2) reject(new Error(error2));
1020
+ else if (settlePromise) settlePromise();
1021
+ else triggerAnotherBuild();
1022
+ });
1023
+ };
1024
+ triggerAnotherBuild();
1025
+ });
1026
+ return latestResultPromise;
1027
+ },
1028
+ watch: (options2 = {}) => new Promise((resolve, reject) => {
1029
+ if (!streamIn.hasFS) throw new Error(`Cannot use the "watch" API in this environment`);
1030
+ const keys = {};
1031
+ const delay = getFlag(options2, keys, "delay", mustBeInteger);
1032
+ checkForInvalidFlags(options2, keys, `in watch() call`);
1033
+ const request2 = {
1034
+ command: "watch",
1035
+ key: buildKey
1036
+ };
1037
+ if (delay) request2.delay = delay;
1038
+ sendRequest(refs, request2, (error2) => {
1039
+ if (error2) reject(new Error(error2));
1040
+ else resolve(void 0);
1041
+ });
1042
+ }),
1043
+ serve: (options2 = {}) => new Promise((resolve, reject) => {
1044
+ if (!streamIn.hasFS) throw new Error(`Cannot use the "serve" API in this environment`);
1045
+ const keys = {};
1046
+ const port = getFlag(options2, keys, "port", mustBeValidPortNumber);
1047
+ const host = getFlag(options2, keys, "host", mustBeString);
1048
+ const servedir = getFlag(options2, keys, "servedir", mustBeString);
1049
+ const keyfile = getFlag(options2, keys, "keyfile", mustBeString);
1050
+ const certfile = getFlag(options2, keys, "certfile", mustBeString);
1051
+ const fallback = getFlag(options2, keys, "fallback", mustBeString);
1052
+ const cors = getFlag(options2, keys, "cors", mustBeObject);
1053
+ const onRequest = getFlag(options2, keys, "onRequest", mustBeFunction);
1054
+ checkForInvalidFlags(options2, keys, `in serve() call`);
1055
+ const request2 = {
1056
+ command: "serve",
1057
+ key: buildKey,
1058
+ onRequest: !!onRequest
1059
+ };
1060
+ if (port !== void 0) request2.port = port;
1061
+ if (host !== void 0) request2.host = host;
1062
+ if (servedir !== void 0) request2.servedir = servedir;
1063
+ if (keyfile !== void 0) request2.keyfile = keyfile;
1064
+ if (certfile !== void 0) request2.certfile = certfile;
1065
+ if (fallback !== void 0) request2.fallback = fallback;
1066
+ if (cors) {
1067
+ const corsKeys = {};
1068
+ const origin = getFlag(cors, corsKeys, "origin", mustBeStringOrArrayOfStrings);
1069
+ checkForInvalidFlags(cors, corsKeys, `on "cors" object`);
1070
+ if (Array.isArray(origin)) request2.corsOrigin = origin;
1071
+ else if (origin !== void 0) request2.corsOrigin = [origin];
1072
+ }
1073
+ sendRequest(refs, request2, (error2, response2) => {
1074
+ if (error2) return reject(new Error(error2));
1075
+ if (onRequest) requestCallbacks["serve-request"] = (id, request3) => {
1076
+ onRequest(request3.args);
1077
+ sendResponse(id, {});
1078
+ };
1079
+ resolve(response2);
1080
+ });
1081
+ }),
1082
+ cancel: () => new Promise((resolve) => {
1083
+ if (didDispose) return resolve();
1084
+ sendRequest(refs, {
1085
+ command: "cancel",
1086
+ key: buildKey
1087
+ }, () => {
1088
+ resolve();
1089
+ });
1090
+ }),
1091
+ dispose: () => new Promise((resolve) => {
1092
+ if (didDispose) return resolve();
1093
+ didDispose = true;
1094
+ sendRequest(refs, {
1095
+ command: "dispose",
1096
+ key: buildKey
1097
+ }, () => {
1098
+ resolve();
1099
+ scheduleOnDisposeCallbacks();
1100
+ refs.unref();
1101
+ });
1102
+ })
1103
+ };
1104
+ refs.ref();
1105
+ callback(null, result);
1106
+ });
1107
+ }
1108
+ }
1109
+ var handlePlugins = async (buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, initialOptions, plugins, details) => {
1110
+ let onStartCallbacks = [];
1111
+ let onEndCallbacks = [];
1112
+ let onResolveCallbacks = {};
1113
+ let onLoadCallbacks = {};
1114
+ let onDisposeCallbacks = [];
1115
+ let nextCallbackID = 0;
1116
+ let i = 0;
1117
+ let requestPlugins = [];
1118
+ let isSetupDone = false;
1119
+ plugins = [...plugins];
1120
+ for (let item of plugins) {
1121
+ let keys = {};
1122
+ if (typeof item !== "object") throw new Error(`Plugin at index ${i} must be an object`);
1123
+ const name = getFlag(item, keys, "name", mustBeString);
1124
+ if (typeof name !== "string" || name === "") throw new Error(`Plugin at index ${i} is missing a name`);
1125
+ try {
1126
+ let setup = getFlag(item, keys, "setup", mustBeFunction);
1127
+ if (typeof setup !== "function") throw new Error(`Plugin is missing a setup function`);
1128
+ checkForInvalidFlags(item, keys, `on plugin ${quote(name)}`);
1129
+ let plugin = {
1130
+ name,
1131
+ onStart: false,
1132
+ onEnd: false,
1133
+ onResolve: [],
1134
+ onLoad: []
1135
+ };
1136
+ i++;
1137
+ let resolve = (path3, options = {}) => {
1138
+ if (!isSetupDone) throw new Error("Cannot call \"resolve\" before plugin setup has completed");
1139
+ if (typeof path3 !== "string") throw new Error(`The path to resolve must be a string`);
1140
+ let keys2 = /* @__PURE__ */ Object.create(null);
1141
+ let pluginName = getFlag(options, keys2, "pluginName", mustBeString);
1142
+ let importer = getFlag(options, keys2, "importer", mustBeString);
1143
+ let namespace = getFlag(options, keys2, "namespace", mustBeString);
1144
+ let resolveDir = getFlag(options, keys2, "resolveDir", mustBeString);
1145
+ let kind = getFlag(options, keys2, "kind", mustBeString);
1146
+ let pluginData = getFlag(options, keys2, "pluginData", canBeAnything);
1147
+ let importAttributes = getFlag(options, keys2, "with", mustBeObject);
1148
+ checkForInvalidFlags(options, keys2, "in resolve() call");
1149
+ return new Promise((resolve2, reject) => {
1150
+ const request = {
1151
+ command: "resolve",
1152
+ path: path3,
1153
+ key: buildKey,
1154
+ pluginName: name
1155
+ };
1156
+ if (pluginName != null) request.pluginName = pluginName;
1157
+ if (importer != null) request.importer = importer;
1158
+ if (namespace != null) request.namespace = namespace;
1159
+ if (resolveDir != null) request.resolveDir = resolveDir;
1160
+ if (kind != null) request.kind = kind;
1161
+ else throw new Error(`Must specify "kind" when calling "resolve"`);
1162
+ if (pluginData != null) request.pluginData = details.store(pluginData);
1163
+ if (importAttributes != null) request.with = sanitizeStringMap(importAttributes, "with");
1164
+ sendRequest(refs, request, (error, response) => {
1165
+ if (error !== null) reject(new Error(error));
1166
+ else resolve2({
1167
+ errors: replaceDetailsInMessages(response.errors, details),
1168
+ warnings: replaceDetailsInMessages(response.warnings, details),
1169
+ path: response.path,
1170
+ external: response.external,
1171
+ sideEffects: response.sideEffects,
1172
+ namespace: response.namespace,
1173
+ suffix: response.suffix,
1174
+ pluginData: details.load(response.pluginData)
1175
+ });
1176
+ });
1177
+ });
1178
+ };
1179
+ let promise = setup({
1180
+ initialOptions,
1181
+ resolve,
1182
+ onStart(callback) {
1183
+ let registeredNote = extractCallerV8(new Error(`This error came from the "onStart" callback registered here:`), streamIn, "onStart");
1184
+ onStartCallbacks.push({
1185
+ name,
1186
+ callback,
1187
+ note: registeredNote
1188
+ });
1189
+ plugin.onStart = true;
1190
+ },
1191
+ onEnd(callback) {
1192
+ let registeredNote = extractCallerV8(new Error(`This error came from the "onEnd" callback registered here:`), streamIn, "onEnd");
1193
+ onEndCallbacks.push({
1194
+ name,
1195
+ callback,
1196
+ note: registeredNote
1197
+ });
1198
+ plugin.onEnd = true;
1199
+ },
1200
+ onResolve(options, callback) {
1201
+ let registeredNote = extractCallerV8(new Error(`This error came from the "onResolve" callback registered here:`), streamIn, "onResolve");
1202
+ let keys2 = {};
1203
+ let filter = getFlag(options, keys2, "filter", mustBeRegExp);
1204
+ let namespace = getFlag(options, keys2, "namespace", mustBeString);
1205
+ checkForInvalidFlags(options, keys2, `in onResolve() call for plugin ${quote(name)}`);
1206
+ if (filter == null) throw new Error(`onResolve() call is missing a filter`);
1207
+ let id = nextCallbackID++;
1208
+ onResolveCallbacks[id] = {
1209
+ name,
1210
+ callback,
1211
+ note: registeredNote
1212
+ };
1213
+ plugin.onResolve.push({
1214
+ id,
1215
+ filter: jsRegExpToGoRegExp(filter),
1216
+ namespace: namespace || ""
1217
+ });
1218
+ },
1219
+ onLoad(options, callback) {
1220
+ let registeredNote = extractCallerV8(new Error(`This error came from the "onLoad" callback registered here:`), streamIn, "onLoad");
1221
+ let keys2 = {};
1222
+ let filter = getFlag(options, keys2, "filter", mustBeRegExp);
1223
+ let namespace = getFlag(options, keys2, "namespace", mustBeString);
1224
+ checkForInvalidFlags(options, keys2, `in onLoad() call for plugin ${quote(name)}`);
1225
+ if (filter == null) throw new Error(`onLoad() call is missing a filter`);
1226
+ let id = nextCallbackID++;
1227
+ onLoadCallbacks[id] = {
1228
+ name,
1229
+ callback,
1230
+ note: registeredNote
1231
+ };
1232
+ plugin.onLoad.push({
1233
+ id,
1234
+ filter: jsRegExpToGoRegExp(filter),
1235
+ namespace: namespace || ""
1236
+ });
1237
+ },
1238
+ onDispose(callback) {
1239
+ onDisposeCallbacks.push(callback);
1240
+ },
1241
+ esbuild: streamIn.esbuild
1242
+ });
1243
+ if (promise) await promise;
1244
+ requestPlugins.push(plugin);
1245
+ } catch (e) {
1246
+ return {
1247
+ ok: false,
1248
+ error: e,
1249
+ pluginName: name
1250
+ };
1251
+ }
1252
+ }
1253
+ requestCallbacks["on-start"] = async (id, request) => {
1254
+ details.clear();
1255
+ let response = {
1256
+ errors: [],
1257
+ warnings: []
1258
+ };
1259
+ await Promise.all(onStartCallbacks.map(async ({ name, callback, note }) => {
1260
+ try {
1261
+ let result = await callback();
1262
+ if (result != null) {
1263
+ if (typeof result !== "object") throw new Error(`Expected onStart() callback in plugin ${quote(name)} to return an object`);
1264
+ let keys = {};
1265
+ let errors = getFlag(result, keys, "errors", mustBeArray);
1266
+ let warnings = getFlag(result, keys, "warnings", mustBeArray);
1267
+ checkForInvalidFlags(result, keys, `from onStart() callback in plugin ${quote(name)}`);
1268
+ if (errors != null) response.errors.push(...sanitizeMessages(errors, "errors", details, name, void 0));
1269
+ if (warnings != null) response.warnings.push(...sanitizeMessages(warnings, "warnings", details, name, void 0));
1270
+ }
1271
+ } catch (e) {
1272
+ response.errors.push(extractErrorMessageV8(e, streamIn, details, note && note(), name));
1273
+ }
1274
+ }));
1275
+ sendResponse(id, response);
1276
+ };
1277
+ requestCallbacks["on-resolve"] = async (id, request) => {
1278
+ let response = {}, name = "", callback, note;
1279
+ for (let id2 of request.ids) try {
1280
+ ({name, callback, note} = onResolveCallbacks[id2]);
1281
+ let result = await callback({
1282
+ path: request.path,
1283
+ importer: request.importer,
1284
+ namespace: request.namespace,
1285
+ resolveDir: request.resolveDir,
1286
+ kind: request.kind,
1287
+ pluginData: details.load(request.pluginData),
1288
+ with: request.with
1289
+ });
1290
+ if (result != null) {
1291
+ if (typeof result !== "object") throw new Error(`Expected onResolve() callback in plugin ${quote(name)} to return an object`);
1292
+ let keys = {};
1293
+ let pluginName = getFlag(result, keys, "pluginName", mustBeString);
1294
+ let path3 = getFlag(result, keys, "path", mustBeString);
1295
+ let namespace = getFlag(result, keys, "namespace", mustBeString);
1296
+ let suffix = getFlag(result, keys, "suffix", mustBeString);
1297
+ let external = getFlag(result, keys, "external", mustBeBoolean);
1298
+ let sideEffects = getFlag(result, keys, "sideEffects", mustBeBoolean);
1299
+ let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
1300
+ let errors = getFlag(result, keys, "errors", mustBeArray);
1301
+ let warnings = getFlag(result, keys, "warnings", mustBeArray);
1302
+ let watchFiles = getFlag(result, keys, "watchFiles", mustBeArrayOfStrings);
1303
+ let watchDirs = getFlag(result, keys, "watchDirs", mustBeArrayOfStrings);
1304
+ checkForInvalidFlags(result, keys, `from onResolve() callback in plugin ${quote(name)}`);
1305
+ response.id = id2;
1306
+ if (pluginName != null) response.pluginName = pluginName;
1307
+ if (path3 != null) response.path = path3;
1308
+ if (namespace != null) response.namespace = namespace;
1309
+ if (suffix != null) response.suffix = suffix;
1310
+ if (external != null) response.external = external;
1311
+ if (sideEffects != null) response.sideEffects = sideEffects;
1312
+ if (pluginData != null) response.pluginData = details.store(pluginData);
1313
+ if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0);
1314
+ if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
1315
+ if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
1316
+ if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
1317
+ break;
1318
+ }
1319
+ } catch (e) {
1320
+ response = {
1321
+ id: id2,
1322
+ errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)]
1323
+ };
1324
+ break;
1325
+ }
1326
+ sendResponse(id, response);
1327
+ };
1328
+ requestCallbacks["on-load"] = async (id, request) => {
1329
+ let response = {}, name = "", callback, note;
1330
+ for (let id2 of request.ids) try {
1331
+ ({name, callback, note} = onLoadCallbacks[id2]);
1332
+ let result = await callback({
1333
+ path: request.path,
1334
+ namespace: request.namespace,
1335
+ suffix: request.suffix,
1336
+ pluginData: details.load(request.pluginData),
1337
+ with: request.with
1338
+ });
1339
+ if (result != null) {
1340
+ if (typeof result !== "object") throw new Error(`Expected onLoad() callback in plugin ${quote(name)} to return an object`);
1341
+ let keys = {};
1342
+ let pluginName = getFlag(result, keys, "pluginName", mustBeString);
1343
+ let contents = getFlag(result, keys, "contents", mustBeStringOrUint8Array);
1344
+ let resolveDir = getFlag(result, keys, "resolveDir", mustBeString);
1345
+ let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
1346
+ let loader = getFlag(result, keys, "loader", mustBeString);
1347
+ let errors = getFlag(result, keys, "errors", mustBeArray);
1348
+ let warnings = getFlag(result, keys, "warnings", mustBeArray);
1349
+ let watchFiles = getFlag(result, keys, "watchFiles", mustBeArrayOfStrings);
1350
+ let watchDirs = getFlag(result, keys, "watchDirs", mustBeArrayOfStrings);
1351
+ checkForInvalidFlags(result, keys, `from onLoad() callback in plugin ${quote(name)}`);
1352
+ response.id = id2;
1353
+ if (pluginName != null) response.pluginName = pluginName;
1354
+ if (contents instanceof Uint8Array) response.contents = contents;
1355
+ else if (contents != null) response.contents = encodeUTF8(contents);
1356
+ if (resolveDir != null) response.resolveDir = resolveDir;
1357
+ if (pluginData != null) response.pluginData = details.store(pluginData);
1358
+ if (loader != null) response.loader = loader;
1359
+ if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0);
1360
+ if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
1361
+ if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
1362
+ if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
1363
+ break;
1364
+ }
1365
+ } catch (e) {
1366
+ response = {
1367
+ id: id2,
1368
+ errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)]
1369
+ };
1370
+ break;
1371
+ }
1372
+ sendResponse(id, response);
1373
+ };
1374
+ let runOnEndCallbacks = (result, done) => done([], []);
1375
+ if (onEndCallbacks.length > 0) runOnEndCallbacks = (result, done) => {
1376
+ (async () => {
1377
+ const onEndErrors = [];
1378
+ const onEndWarnings = [];
1379
+ for (const { name, callback, note } of onEndCallbacks) {
1380
+ let newErrors;
1381
+ let newWarnings;
1382
+ try {
1383
+ const value = await callback(result);
1384
+ if (value != null) {
1385
+ if (typeof value !== "object") throw new Error(`Expected onEnd() callback in plugin ${quote(name)} to return an object`);
1386
+ let keys = {};
1387
+ let errors = getFlag(value, keys, "errors", mustBeArray);
1388
+ let warnings = getFlag(value, keys, "warnings", mustBeArray);
1389
+ checkForInvalidFlags(value, keys, `from onEnd() callback in plugin ${quote(name)}`);
1390
+ if (errors != null) newErrors = sanitizeMessages(errors, "errors", details, name, void 0);
1391
+ if (warnings != null) newWarnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
1392
+ }
1393
+ } catch (e) {
1394
+ newErrors = [extractErrorMessageV8(e, streamIn, details, note && note(), name)];
1395
+ }
1396
+ if (newErrors) {
1397
+ onEndErrors.push(...newErrors);
1398
+ try {
1399
+ result.errors.push(...newErrors);
1400
+ } catch {}
1401
+ }
1402
+ if (newWarnings) {
1403
+ onEndWarnings.push(...newWarnings);
1404
+ try {
1405
+ result.warnings.push(...newWarnings);
1406
+ } catch {}
1407
+ }
1408
+ }
1409
+ done(onEndErrors, onEndWarnings);
1410
+ })();
1411
+ };
1412
+ let scheduleOnDisposeCallbacks = () => {
1413
+ for (const cb of onDisposeCallbacks) setTimeout(() => cb(), 0);
1414
+ };
1415
+ isSetupDone = true;
1416
+ return {
1417
+ ok: true,
1418
+ requestPlugins,
1419
+ runOnEndCallbacks,
1420
+ scheduleOnDisposeCallbacks
1421
+ };
1422
+ };
1423
+ function createObjectStash() {
1424
+ const map = /* @__PURE__ */ new Map();
1425
+ let nextID = 0;
1426
+ return {
1427
+ clear() {
1428
+ map.clear();
1429
+ },
1430
+ load(id) {
1431
+ return map.get(id);
1432
+ },
1433
+ store(value) {
1434
+ if (value === void 0) return -1;
1435
+ const id = nextID++;
1436
+ map.set(id, value);
1437
+ return id;
1438
+ }
1439
+ };
1440
+ }
1441
+ function extractCallerV8(e, streamIn, ident) {
1442
+ let note;
1443
+ let tried = false;
1444
+ return () => {
1445
+ if (tried) return note;
1446
+ tried = true;
1447
+ try {
1448
+ let lines = (e.stack + "").split("\n");
1449
+ lines.splice(1, 1);
1450
+ let location = parseStackLinesV8(streamIn, lines, ident);
1451
+ if (location) {
1452
+ note = {
1453
+ text: e.message,
1454
+ location
1455
+ };
1456
+ return note;
1457
+ }
1458
+ } catch {}
1459
+ };
1460
+ }
1461
+ function extractErrorMessageV8(e, streamIn, stash, note, pluginName) {
1462
+ let text = "Internal error";
1463
+ let location = null;
1464
+ try {
1465
+ text = (e && e.message || e) + "";
1466
+ } catch {}
1467
+ try {
1468
+ location = parseStackLinesV8(streamIn, (e.stack + "").split("\n"), "");
1469
+ } catch {}
1470
+ return {
1471
+ id: "",
1472
+ pluginName,
1473
+ text,
1474
+ location,
1475
+ notes: note ? [note] : [],
1476
+ detail: stash ? stash.store(e) : -1
1477
+ };
1478
+ }
1479
+ function parseStackLinesV8(streamIn, lines, ident) {
1480
+ let at = " at ";
1481
+ if (streamIn.readFileSync && !lines[0].startsWith(at) && lines[1].startsWith(at)) for (let i = 1; i < lines.length; i++) {
1482
+ let line = lines[i];
1483
+ if (!line.startsWith(at)) continue;
1484
+ line = line.slice(7);
1485
+ while (true) {
1486
+ let match = /^(?:new |async )?\S+ \((.*)\)$/.exec(line);
1487
+ if (match) {
1488
+ line = match[1];
1489
+ continue;
1490
+ }
1491
+ match = /^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(line);
1492
+ if (match) {
1493
+ line = match[1];
1494
+ continue;
1495
+ }
1496
+ match = /^(\S+):(\d+):(\d+)$/.exec(line);
1497
+ if (match) {
1498
+ let contents;
1499
+ try {
1500
+ contents = streamIn.readFileSync(match[1], "utf8");
1501
+ } catch {
1502
+ break;
1503
+ }
1504
+ let lineText = contents.split(/\r\n|\r|\n|\u2028|\u2029/)[+match[2] - 1] || "";
1505
+ let column = +match[3] - 1;
1506
+ let length = lineText.slice(column, column + ident.length) === ident ? ident.length : 0;
1507
+ return {
1508
+ file: match[1],
1509
+ namespace: "file",
1510
+ line: +match[2],
1511
+ column: encodeUTF8(lineText.slice(0, column)).length,
1512
+ length: encodeUTF8(lineText.slice(column, column + length)).length,
1513
+ lineText: lineText + "\n" + lines.slice(1).join("\n"),
1514
+ suggestion: ""
1515
+ };
1516
+ }
1517
+ break;
1518
+ }
1519
+ }
1520
+ return null;
1521
+ }
1522
+ function failureErrorWithLog(text, errors, warnings) {
1523
+ let limit = 5;
1524
+ text += errors.length < 1 ? "" : ` with ${errors.length} error${errors.length < 2 ? "" : "s"}:` + errors.slice(0, limit + 1).map((e, i) => {
1525
+ if (i === limit) return "\n...";
1526
+ if (!e.location) return `
1527
+ error: ${e.text}`;
1528
+ let { file, line, column } = e.location;
1529
+ let pluginText = e.pluginName ? `[plugin: ${e.pluginName}] ` : "";
1530
+ return `
1531
+ ${file}:${line}:${column}: ERROR: ${pluginText}${e.text}`;
1532
+ }).join("");
1533
+ let error = new Error(text);
1534
+ for (const [key, value] of [["errors", errors], ["warnings", warnings]]) Object.defineProperty(error, key, {
1535
+ configurable: true,
1536
+ enumerable: true,
1537
+ get: () => value,
1538
+ set: (value2) => Object.defineProperty(error, key, {
1539
+ configurable: true,
1540
+ enumerable: true,
1541
+ value: value2
1542
+ })
1543
+ });
1544
+ return error;
1545
+ }
1546
+ function replaceDetailsInMessages(messages, stash) {
1547
+ for (const message of messages) message.detail = stash.load(message.detail);
1548
+ return messages;
1549
+ }
1550
+ function sanitizeLocation(location, where, terminalWidth) {
1551
+ if (location == null) return null;
1552
+ let keys = {};
1553
+ let file = getFlag(location, keys, "file", mustBeString);
1554
+ let namespace = getFlag(location, keys, "namespace", mustBeString);
1555
+ let line = getFlag(location, keys, "line", mustBeInteger);
1556
+ let column = getFlag(location, keys, "column", mustBeInteger);
1557
+ let length = getFlag(location, keys, "length", mustBeInteger);
1558
+ let lineText = getFlag(location, keys, "lineText", mustBeString);
1559
+ let suggestion = getFlag(location, keys, "suggestion", mustBeString);
1560
+ checkForInvalidFlags(location, keys, where);
1561
+ if (lineText) {
1562
+ const relevantASCII = lineText.slice(0, (column && column > 0 ? column : 0) + (length && length > 0 ? length : 0) + (terminalWidth && terminalWidth > 0 ? terminalWidth : 80));
1563
+ if (!/[\x7F-\uFFFF]/.test(relevantASCII) && !/\n/.test(lineText)) lineText = relevantASCII;
1564
+ }
1565
+ return {
1566
+ file: file || "",
1567
+ namespace: namespace || "",
1568
+ line: line || 0,
1569
+ column: column || 0,
1570
+ length: length || 0,
1571
+ lineText: lineText || "",
1572
+ suggestion: suggestion || ""
1573
+ };
1574
+ }
1575
+ function sanitizeMessages(messages, property, stash, fallbackPluginName, terminalWidth) {
1576
+ let messagesClone = [];
1577
+ let index = 0;
1578
+ for (const message of messages) {
1579
+ let keys = {};
1580
+ let id = getFlag(message, keys, "id", mustBeString);
1581
+ let pluginName = getFlag(message, keys, "pluginName", mustBeString);
1582
+ let text = getFlag(message, keys, "text", mustBeString);
1583
+ let location = getFlag(message, keys, "location", mustBeObjectOrNull);
1584
+ let notes = getFlag(message, keys, "notes", mustBeArray);
1585
+ let detail = getFlag(message, keys, "detail", canBeAnything);
1586
+ let where = `in element ${index} of "${property}"`;
1587
+ checkForInvalidFlags(message, keys, where);
1588
+ let notesClone = [];
1589
+ if (notes) for (const note of notes) {
1590
+ let noteKeys = {};
1591
+ let noteText = getFlag(note, noteKeys, "text", mustBeString);
1592
+ let noteLocation = getFlag(note, noteKeys, "location", mustBeObjectOrNull);
1593
+ checkForInvalidFlags(note, noteKeys, where);
1594
+ notesClone.push({
1595
+ text: noteText || "",
1596
+ location: sanitizeLocation(noteLocation, where, terminalWidth)
1597
+ });
1598
+ }
1599
+ messagesClone.push({
1600
+ id: id || "",
1601
+ pluginName: pluginName || fallbackPluginName,
1602
+ text: text || "",
1603
+ location: sanitizeLocation(location, where, terminalWidth),
1604
+ notes: notesClone,
1605
+ detail: stash ? stash.store(detail) : -1
1606
+ });
1607
+ index++;
1608
+ }
1609
+ return messagesClone;
1610
+ }
1611
+ function sanitizeStringArray(values, property) {
1612
+ const result = [];
1613
+ for (const value of values) {
1614
+ if (typeof value !== "string") throw new Error(`${quote(property)} must be an array of strings`);
1615
+ result.push(value);
1616
+ }
1617
+ return result;
1618
+ }
1619
+ function sanitizeStringMap(map, property) {
1620
+ const result = /* @__PURE__ */ Object.create(null);
1621
+ for (const key in map) {
1622
+ const value = map[key];
1623
+ if (typeof value !== "string") throw new Error(`key ${quote(key)} in object ${quote(property)} must be a string`);
1624
+ result[key] = value;
1625
+ }
1626
+ return result;
1627
+ }
1628
+ function convertOutputFiles({ path: path3, contents, hash }) {
1629
+ let text = null;
1630
+ return {
1631
+ path: path3,
1632
+ contents,
1633
+ hash,
1634
+ get text() {
1635
+ const binary = this.contents;
1636
+ if (text === null || binary !== contents) {
1637
+ contents = binary;
1638
+ text = decodeUTF8(binary);
1639
+ }
1640
+ return text;
1641
+ }
1642
+ };
1643
+ }
1644
+ function jsRegExpToGoRegExp(regexp) {
1645
+ let result = regexp.source;
1646
+ if (regexp.flags) result = `(?${regexp.flags})${result}`;
1647
+ return result;
1648
+ }
1649
+ var fs = __require("fs");
1650
+ var os = __require("os");
1651
+ var path$2 = __require("path");
1652
+ var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH;
1653
+ var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild";
1654
+ var packageDarwin_arm64 = "@esbuild/darwin-arm64";
1655
+ var packageDarwin_x64 = "@esbuild/darwin-x64";
1656
+ var knownWindowsPackages = {
1657
+ "win32 arm64 LE": "@esbuild/win32-arm64",
1658
+ "win32 ia32 LE": "@esbuild/win32-ia32",
1659
+ "win32 x64 LE": "@esbuild/win32-x64"
1660
+ };
1661
+ var knownUnixlikePackages = {
1662
+ "aix ppc64 BE": "@esbuild/aix-ppc64",
1663
+ "android arm64 LE": "@esbuild/android-arm64",
1664
+ "darwin arm64 LE": "@esbuild/darwin-arm64",
1665
+ "darwin x64 LE": "@esbuild/darwin-x64",
1666
+ "freebsd arm64 LE": "@esbuild/freebsd-arm64",
1667
+ "freebsd x64 LE": "@esbuild/freebsd-x64",
1668
+ "linux arm LE": "@esbuild/linux-arm",
1669
+ "linux arm64 LE": "@esbuild/linux-arm64",
1670
+ "linux ia32 LE": "@esbuild/linux-ia32",
1671
+ "linux mips64el LE": "@esbuild/linux-mips64el",
1672
+ "linux ppc64 LE": "@esbuild/linux-ppc64",
1673
+ "linux riscv64 LE": "@esbuild/linux-riscv64",
1674
+ "linux s390x BE": "@esbuild/linux-s390x",
1675
+ "linux x64 LE": "@esbuild/linux-x64",
1676
+ "linux loong64 LE": "@esbuild/linux-loong64",
1677
+ "netbsd arm64 LE": "@esbuild/netbsd-arm64",
1678
+ "netbsd x64 LE": "@esbuild/netbsd-x64",
1679
+ "openbsd arm64 LE": "@esbuild/openbsd-arm64",
1680
+ "openbsd x64 LE": "@esbuild/openbsd-x64",
1681
+ "sunos x64 LE": "@esbuild/sunos-x64"
1682
+ };
1683
+ var knownWebAssemblyFallbackPackages = {
1684
+ "android arm LE": "@esbuild/android-arm",
1685
+ "android x64 LE": "@esbuild/android-x64",
1686
+ "openharmony arm64 LE": "@esbuild/openharmony-arm64"
1687
+ };
1688
+ function pkgAndSubpathForCurrentPlatform() {
1689
+ let pkg;
1690
+ let subpath;
1691
+ let isWASM = false;
1692
+ let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`;
1693
+ if (platformKey in knownWindowsPackages) {
1694
+ pkg = knownWindowsPackages[platformKey];
1695
+ subpath = "esbuild.exe";
1696
+ } else if (platformKey in knownUnixlikePackages) {
1697
+ pkg = knownUnixlikePackages[platformKey];
1698
+ subpath = "bin/esbuild";
1699
+ } else if (platformKey in knownWebAssemblyFallbackPackages) {
1700
+ pkg = knownWebAssemblyFallbackPackages[platformKey];
1701
+ subpath = "bin/esbuild";
1702
+ isWASM = true;
1703
+ } else throw new Error(`Unsupported platform: ${platformKey}`);
1704
+ return {
1705
+ pkg,
1706
+ subpath,
1707
+ isWASM
1708
+ };
1709
+ }
1710
+ function pkgForSomeOtherPlatform() {
1711
+ const libMainJS = __require.resolve("esbuild");
1712
+ const nodeModulesDirectory = path$2.dirname(path$2.dirname(path$2.dirname(libMainJS)));
1713
+ if (path$2.basename(nodeModulesDirectory) === "node_modules") {
1714
+ for (const unixKey in knownUnixlikePackages) try {
1715
+ const pkg = knownUnixlikePackages[unixKey];
1716
+ if (fs.existsSync(path$2.join(nodeModulesDirectory, pkg))) return pkg;
1717
+ } catch {}
1718
+ for (const windowsKey in knownWindowsPackages) try {
1719
+ const pkg = knownWindowsPackages[windowsKey];
1720
+ if (fs.existsSync(path$2.join(nodeModulesDirectory, pkg))) return pkg;
1721
+ } catch {}
1722
+ }
1723
+ return null;
1724
+ }
1725
+ function downloadedBinPath(pkg, subpath) {
1726
+ const esbuildLibDir = path$2.dirname(__require.resolve("esbuild"));
1727
+ return path$2.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path$2.basename(subpath)}`);
1728
+ }
1729
+ function generateBinPath() {
1730
+ if (isValidBinaryPath(ESBUILD_BINARY_PATH)) if (!fs.existsSync(ESBUILD_BINARY_PATH)) console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`);
1731
+ else return {
1732
+ binPath: ESBUILD_BINARY_PATH,
1733
+ isWASM: false
1734
+ };
1735
+ const { pkg, subpath, isWASM } = pkgAndSubpathForCurrentPlatform();
1736
+ let binPath;
1737
+ try {
1738
+ binPath = __require.resolve(`${pkg}/${subpath}`);
1739
+ } catch (e) {
1740
+ binPath = downloadedBinPath(pkg, subpath);
1741
+ if (!fs.existsSync(binPath)) {
1742
+ try {
1743
+ __require.resolve(pkg);
1744
+ } catch {
1745
+ const otherPkg = pkgForSomeOtherPlatform();
1746
+ if (otherPkg) {
1747
+ let suggestions = `
1748
+ Specifically the "${otherPkg}" package is present but this platform
1749
+ needs the "${pkg}" package instead. People often get into this
1750
+ situation by installing esbuild on Windows or macOS and copying "node_modules"
1751
+ into a Docker image that runs Linux, or by copying "node_modules" between
1752
+ Windows and WSL environments.
1753
+
1754
+ If you are installing with npm, you can try not copying the "node_modules"
1755
+ directory when you copy the files over, and running "npm ci" or "npm install"
1756
+ on the destination platform after the copy. Or you could consider using yarn
1757
+ instead of npm which has built-in support for installing a package on multiple
1758
+ platforms simultaneously.
1759
+
1760
+ If you are installing with yarn, you can try listing both this platform and the
1761
+ other platform in your ".yarnrc.yml" file using the "supportedArchitectures"
1762
+ feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
1763
+ Keep in mind that this means multiple copies of esbuild will be present.
1764
+ `;
1765
+ if (pkg === packageDarwin_x64 && otherPkg === packageDarwin_arm64 || pkg === packageDarwin_arm64 && otherPkg === packageDarwin_x64) suggestions = `
1766
+ Specifically the "${otherPkg}" package is present but this platform
1767
+ needs the "${pkg}" package instead. People often get into this
1768
+ situation by installing esbuild with npm running inside of Rosetta 2 and then
1769
+ trying to use it with node running outside of Rosetta 2, or vice versa (Rosetta
1770
+ 2 is Apple's on-the-fly x86_64-to-arm64 translation service).
1771
+
1772
+ If you are installing with npm, you can try ensuring that both npm and node are
1773
+ not running under Rosetta 2 and then reinstalling esbuild. This likely involves
1774
+ changing how you installed npm and/or node. For example, installing node with
1775
+ the universal installer here should work: https://nodejs.org/en/download/. Or
1776
+ you could consider using yarn instead of npm which has built-in support for
1777
+ installing a package on multiple platforms simultaneously.
1778
+
1779
+ If you are installing with yarn, you can try listing both "arm64" and "x64"
1780
+ in your ".yarnrc.yml" file using the "supportedArchitectures" feature:
1781
+ https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
1782
+ Keep in mind that this means multiple copies of esbuild will be present.
1783
+ `;
1784
+ throw new Error(`
1785
+ You installed esbuild for another platform than the one you're currently using.
1786
+ This won't work because esbuild is written with native code and needs to
1787
+ install a platform-specific binary executable.
1788
+ ${suggestions}
1789
+ Another alternative is to use the "esbuild-wasm" package instead, which works
1790
+ the same way on all platforms. But it comes with a heavy performance cost and
1791
+ can sometimes be 10x slower than the "esbuild" package, so you may also not
1792
+ want to do that.
1793
+ `);
1794
+ }
1795
+ throw new Error(`The package "${pkg}" could not be found, and is needed by esbuild.
1796
+
1797
+ If you are installing esbuild with npm, make sure that you don't specify the
1798
+ "--no-optional" or "--omit=optional" flags. The "optionalDependencies" feature
1799
+ of "package.json" is used by esbuild to install the correct binary executable
1800
+ for your current platform.`);
1801
+ }
1802
+ throw e;
1803
+ }
1804
+ }
1805
+ if (/\.zip\//.test(binPath)) {
1806
+ let pnpapi;
1807
+ try {
1808
+ pnpapi = __require("pnpapi");
1809
+ } catch (e) {}
1810
+ if (pnpapi) {
1811
+ const root = pnpapi.getPackageInformation(pnpapi.topLevel).packageLocation;
1812
+ const binTargetPath = path$2.join(root, "node_modules", ".cache", "esbuild", `pnpapi-${pkg.replace("/", "-")}-0.25.10-${path$2.basename(subpath)}`);
1813
+ if (!fs.existsSync(binTargetPath)) {
1814
+ fs.mkdirSync(path$2.dirname(binTargetPath), { recursive: true });
1815
+ fs.copyFileSync(binPath, binTargetPath);
1816
+ fs.chmodSync(binTargetPath, 493);
1817
+ }
1818
+ return {
1819
+ binPath: binTargetPath,
1820
+ isWASM
1821
+ };
1822
+ }
1823
+ }
1824
+ return {
1825
+ binPath,
1826
+ isWASM
1827
+ };
1828
+ }
1829
+ var child_process = __require("child_process");
1830
+ var crypto = __require("crypto");
1831
+ var path2 = __require("path");
1832
+ var fs2 = __require("fs");
1833
+ var os2 = __require("os");
1834
+ var tty = __require("tty");
1835
+ var worker_threads;
1836
+ if (process.env.ESBUILD_WORKER_THREADS !== "0") {
1837
+ try {
1838
+ worker_threads = __require("worker_threads");
1839
+ } catch {}
1840
+ let [major, minor] = process.versions.node.split(".");
1841
+ if (+major < 12 || +major === 12 && +minor < 17 || +major === 13 && +minor < 13) worker_threads = void 0;
1842
+ }
1843
+ var _a;
1844
+ var isInternalWorkerThread = ((_a = worker_threads == null ? void 0 : worker_threads.workerData) == null ? void 0 : _a.esbuildVersion) === "0.25.10";
1845
+ var esbuildCommandAndArgs = () => {
1846
+ if ((!ESBUILD_BINARY_PATH || false) && (path2.basename(__filename) !== "main.js" || path2.basename(__dirname) !== "lib")) throw new Error(`The esbuild JavaScript API cannot be bundled. Please mark the "esbuild" package as external so it's not included in the bundle.
1847
+
1848
+ More information: The file containing the code for esbuild's JavaScript API (${__filename}) does not appear to be inside the esbuild package on the file system, which usually means that the esbuild package was bundled into another file. This is problematic because the API needs to run a binary executable inside the esbuild package which is located using a relative path from the API code to the executable. If the esbuild package is bundled, the relative path will be incorrect and the executable won't be found.`);
1849
+ {
1850
+ const { binPath, isWASM } = generateBinPath();
1851
+ if (isWASM) return ["node", [binPath]];
1852
+ else return [binPath, []];
1853
+ }
1854
+ };
1855
+ var isTTY = () => tty.isatty(2);
1856
+ var fsSync = {
1857
+ readFile(tempFile, callback) {
1858
+ try {
1859
+ let contents = fs2.readFileSync(tempFile, "utf8");
1860
+ try {
1861
+ fs2.unlinkSync(tempFile);
1862
+ } catch {}
1863
+ callback(null, contents);
1864
+ } catch (err) {
1865
+ callback(err, null);
1866
+ }
1867
+ },
1868
+ writeFile(contents, callback) {
1869
+ try {
1870
+ let tempFile = randomFileName();
1871
+ fs2.writeFileSync(tempFile, contents);
1872
+ callback(tempFile);
1873
+ } catch {
1874
+ callback(null);
1875
+ }
1876
+ }
1877
+ };
1878
+ var fsAsync = {
1879
+ readFile(tempFile, callback) {
1880
+ try {
1881
+ fs2.readFile(tempFile, "utf8", (err, contents) => {
1882
+ try {
1883
+ fs2.unlink(tempFile, () => callback(err, contents));
1884
+ } catch {
1885
+ callback(err, contents);
1886
+ }
1887
+ });
1888
+ } catch (err) {
1889
+ callback(err, null);
1890
+ }
1891
+ },
1892
+ writeFile(contents, callback) {
1893
+ try {
1894
+ let tempFile = randomFileName();
1895
+ fs2.writeFile(tempFile, contents, (err) => err !== null ? callback(null) : callback(tempFile));
1896
+ } catch {
1897
+ callback(null);
1898
+ }
1899
+ }
1900
+ };
1901
+ var version = "0.25.10";
1902
+ var build = (options) => ensureServiceIsRunning().build(options);
1903
+ var context = (buildOptions) => ensureServiceIsRunning().context(buildOptions);
1904
+ var transform = (input, options) => ensureServiceIsRunning().transform(input, options);
1905
+ var formatMessages = (messages, options) => ensureServiceIsRunning().formatMessages(messages, options);
1906
+ var analyzeMetafile = (messages, options) => ensureServiceIsRunning().analyzeMetafile(messages, options);
1907
+ var buildSync = (options) => {
1908
+ if (worker_threads && !isInternalWorkerThread) {
1909
+ if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
1910
+ return workerThreadService.buildSync(options);
1911
+ }
1912
+ let result;
1913
+ runServiceSync((service) => service.buildOrContext({
1914
+ callName: "buildSync",
1915
+ refs: null,
1916
+ options,
1917
+ isTTY: isTTY(),
1918
+ defaultWD,
1919
+ callback: (err, res) => {
1920
+ if (err) throw err;
1921
+ result = res;
1922
+ }
1923
+ }));
1924
+ return result;
1925
+ };
1926
+ var transformSync = (input, options) => {
1927
+ if (worker_threads && !isInternalWorkerThread) {
1928
+ if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
1929
+ return workerThreadService.transformSync(input, options);
1930
+ }
1931
+ let result;
1932
+ runServiceSync((service) => service.transform({
1933
+ callName: "transformSync",
1934
+ refs: null,
1935
+ input,
1936
+ options: options || {},
1937
+ isTTY: isTTY(),
1938
+ fs: fsSync,
1939
+ callback: (err, res) => {
1940
+ if (err) throw err;
1941
+ result = res;
1942
+ }
1943
+ }));
1944
+ return result;
1945
+ };
1946
+ var formatMessagesSync = (messages, options) => {
1947
+ if (worker_threads && !isInternalWorkerThread) {
1948
+ if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
1949
+ return workerThreadService.formatMessagesSync(messages, options);
1950
+ }
1951
+ let result;
1952
+ runServiceSync((service) => service.formatMessages({
1953
+ callName: "formatMessagesSync",
1954
+ refs: null,
1955
+ messages,
1956
+ options,
1957
+ callback: (err, res) => {
1958
+ if (err) throw err;
1959
+ result = res;
1960
+ }
1961
+ }));
1962
+ return result;
1963
+ };
1964
+ var analyzeMetafileSync = (metafile, options) => {
1965
+ if (worker_threads && !isInternalWorkerThread) {
1966
+ if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
1967
+ return workerThreadService.analyzeMetafileSync(metafile, options);
1968
+ }
1969
+ let result;
1970
+ runServiceSync((service) => service.analyzeMetafile({
1971
+ callName: "analyzeMetafileSync",
1972
+ refs: null,
1973
+ metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
1974
+ options,
1975
+ callback: (err, res) => {
1976
+ if (err) throw err;
1977
+ result = res;
1978
+ }
1979
+ }));
1980
+ return result;
1981
+ };
1982
+ var stop = () => {
1983
+ if (stopService) stopService();
1984
+ if (workerThreadService) workerThreadService.stop();
1985
+ return Promise.resolve();
1986
+ };
1987
+ var initializeWasCalled = false;
1988
+ var initialize = (options) => {
1989
+ options = validateInitializeOptions(options || {});
1990
+ if (options.wasmURL) throw new Error(`The "wasmURL" option only works in the browser`);
1991
+ if (options.wasmModule) throw new Error(`The "wasmModule" option only works in the browser`);
1992
+ if (options.worker) throw new Error(`The "worker" option only works in the browser`);
1993
+ if (initializeWasCalled) throw new Error("Cannot call \"initialize\" more than once");
1994
+ ensureServiceIsRunning();
1995
+ initializeWasCalled = true;
1996
+ return Promise.resolve();
1997
+ };
1998
+ var defaultWD = process.cwd();
1999
+ var longLivedService;
2000
+ var stopService;
2001
+ var ensureServiceIsRunning = () => {
2002
+ if (longLivedService) return longLivedService;
2003
+ let [command, args] = esbuildCommandAndArgs();
2004
+ let child = child_process.spawn(command, args.concat(`--service=0.25.10`, "--ping"), {
2005
+ windowsHide: true,
2006
+ stdio: [
2007
+ "pipe",
2008
+ "pipe",
2009
+ "inherit"
2010
+ ],
2011
+ cwd: defaultWD
2012
+ });
2013
+ let { readFromStdout, afterClose, service } = createChannel({
2014
+ writeToStdin(bytes) {
2015
+ child.stdin.write(bytes, (err) => {
2016
+ if (err) afterClose(err);
2017
+ });
2018
+ },
2019
+ readFileSync: fs2.readFileSync,
2020
+ isSync: false,
2021
+ hasFS: true,
2022
+ esbuild: node_exports
2023
+ });
2024
+ child.stdin.on("error", afterClose);
2025
+ child.on("error", afterClose);
2026
+ const stdin = child.stdin;
2027
+ const stdout = child.stdout;
2028
+ stdout.on("data", readFromStdout);
2029
+ stdout.on("end", afterClose);
2030
+ stopService = () => {
2031
+ stdin.destroy();
2032
+ stdout.destroy();
2033
+ child.kill();
2034
+ initializeWasCalled = false;
2035
+ longLivedService = void 0;
2036
+ stopService = void 0;
2037
+ };
2038
+ let refCount = 0;
2039
+ child.unref();
2040
+ if (stdin.unref) stdin.unref();
2041
+ if (stdout.unref) stdout.unref();
2042
+ const refs = {
2043
+ ref() {
2044
+ if (++refCount === 1) child.ref();
2045
+ },
2046
+ unref() {
2047
+ if (--refCount === 0) child.unref();
2048
+ }
2049
+ };
2050
+ longLivedService = {
2051
+ build: (options) => new Promise((resolve, reject) => {
2052
+ service.buildOrContext({
2053
+ callName: "build",
2054
+ refs,
2055
+ options,
2056
+ isTTY: isTTY(),
2057
+ defaultWD,
2058
+ callback: (err, res) => err ? reject(err) : resolve(res)
2059
+ });
2060
+ }),
2061
+ context: (options) => new Promise((resolve, reject) => service.buildOrContext({
2062
+ callName: "context",
2063
+ refs,
2064
+ options,
2065
+ isTTY: isTTY(),
2066
+ defaultWD,
2067
+ callback: (err, res) => err ? reject(err) : resolve(res)
2068
+ })),
2069
+ transform: (input, options) => new Promise((resolve, reject) => service.transform({
2070
+ callName: "transform",
2071
+ refs,
2072
+ input,
2073
+ options: options || {},
2074
+ isTTY: isTTY(),
2075
+ fs: fsAsync,
2076
+ callback: (err, res) => err ? reject(err) : resolve(res)
2077
+ })),
2078
+ formatMessages: (messages, options) => new Promise((resolve, reject) => service.formatMessages({
2079
+ callName: "formatMessages",
2080
+ refs,
2081
+ messages,
2082
+ options,
2083
+ callback: (err, res) => err ? reject(err) : resolve(res)
2084
+ })),
2085
+ analyzeMetafile: (metafile, options) => new Promise((resolve, reject) => service.analyzeMetafile({
2086
+ callName: "analyzeMetafile",
2087
+ refs,
2088
+ metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
2089
+ options,
2090
+ callback: (err, res) => err ? reject(err) : resolve(res)
2091
+ }))
2092
+ };
2093
+ return longLivedService;
2094
+ };
2095
+ var runServiceSync = (callback) => {
2096
+ let [command, args] = esbuildCommandAndArgs();
2097
+ let stdin = new Uint8Array();
2098
+ let { readFromStdout, afterClose, service } = createChannel({
2099
+ writeToStdin(bytes) {
2100
+ if (stdin.length !== 0) throw new Error("Must run at most one command");
2101
+ stdin = bytes;
2102
+ },
2103
+ isSync: true,
2104
+ hasFS: true,
2105
+ esbuild: node_exports
2106
+ });
2107
+ callback(service);
2108
+ let stdout = child_process.execFileSync(command, args.concat(`--service=0.25.10`), {
2109
+ cwd: defaultWD,
2110
+ windowsHide: true,
2111
+ input: stdin,
2112
+ maxBuffer: +process.env.ESBUILD_MAX_BUFFER || 16 * 1024 * 1024
2113
+ });
2114
+ readFromStdout(stdout);
2115
+ afterClose(null);
2116
+ };
2117
+ var randomFileName = () => {
2118
+ return path2.join(os2.tmpdir(), `esbuild-${crypto.randomBytes(32).toString("hex")}`);
2119
+ };
2120
+ var workerThreadService = null;
2121
+ var startWorkerThreadService = (worker_threads2) => {
2122
+ let { port1: mainPort, port2: workerPort } = new worker_threads2.MessageChannel();
2123
+ let worker = new worker_threads2.Worker(__filename, {
2124
+ workerData: {
2125
+ workerPort,
2126
+ defaultWD,
2127
+ esbuildVersion: "0.25.10"
2128
+ },
2129
+ transferList: [workerPort],
2130
+ execArgv: []
2131
+ });
2132
+ let nextID = 0;
2133
+ let fakeBuildError = (text) => {
2134
+ let error = /* @__PURE__ */ new Error(`Build failed with 1 error:
2135
+ error: ${text}`);
2136
+ error.errors = [{
2137
+ id: "",
2138
+ pluginName: "",
2139
+ text,
2140
+ location: null,
2141
+ notes: [],
2142
+ detail: void 0
2143
+ }];
2144
+ error.warnings = [];
2145
+ return error;
2146
+ };
2147
+ let validateBuildSyncOptions = (options) => {
2148
+ if (!options) return;
2149
+ let plugins = options.plugins;
2150
+ if (plugins && plugins.length > 0) throw fakeBuildError(`Cannot use plugins in synchronous API calls`);
2151
+ };
2152
+ let applyProperties = (object, properties) => {
2153
+ for (let key in properties) object[key] = properties[key];
2154
+ };
2155
+ let runCallSync = (command, args) => {
2156
+ let id = nextID++;
2157
+ let sharedBuffer = new SharedArrayBuffer(8);
2158
+ let sharedBufferView = new Int32Array(sharedBuffer);
2159
+ let msg = {
2160
+ sharedBuffer,
2161
+ id,
2162
+ command,
2163
+ args
2164
+ };
2165
+ worker.postMessage(msg);
2166
+ let status = Atomics.wait(sharedBufferView, 0, 0);
2167
+ if (status !== "ok" && status !== "not-equal") throw new Error("Internal error: Atomics.wait() failed: " + status);
2168
+ let { message: { id: id2, resolve, reject, properties } } = worker_threads2.receiveMessageOnPort(mainPort);
2169
+ if (id !== id2) throw new Error(`Internal error: Expected id ${id} but got id ${id2}`);
2170
+ if (reject) {
2171
+ applyProperties(reject, properties);
2172
+ throw reject;
2173
+ }
2174
+ return resolve;
2175
+ };
2176
+ worker.unref();
2177
+ return {
2178
+ buildSync(options) {
2179
+ validateBuildSyncOptions(options);
2180
+ return runCallSync("build", [options]);
2181
+ },
2182
+ transformSync(input, options) {
2183
+ return runCallSync("transform", [input, options]);
2184
+ },
2185
+ formatMessagesSync(messages, options) {
2186
+ return runCallSync("formatMessages", [messages, options]);
2187
+ },
2188
+ analyzeMetafileSync(metafile, options) {
2189
+ return runCallSync("analyzeMetafile", [metafile, options]);
2190
+ },
2191
+ stop() {
2192
+ worker.terminate();
2193
+ workerThreadService = null;
2194
+ }
2195
+ };
2196
+ };
2197
+ var startSyncServiceWorker = () => {
2198
+ let workerPort = worker_threads.workerData.workerPort;
2199
+ let parentPort = worker_threads.parentPort;
2200
+ let extractProperties = (object) => {
2201
+ let properties = {};
2202
+ if (object && typeof object === "object") for (let key in object) properties[key] = object[key];
2203
+ return properties;
2204
+ };
2205
+ try {
2206
+ let service = ensureServiceIsRunning();
2207
+ defaultWD = worker_threads.workerData.defaultWD;
2208
+ parentPort.on("message", (msg) => {
2209
+ (async () => {
2210
+ let { sharedBuffer, id, command, args } = msg;
2211
+ let sharedBufferView = new Int32Array(sharedBuffer);
2212
+ try {
2213
+ switch (command) {
2214
+ case "build":
2215
+ workerPort.postMessage({
2216
+ id,
2217
+ resolve: await service.build(args[0])
2218
+ });
2219
+ break;
2220
+ case "transform":
2221
+ workerPort.postMessage({
2222
+ id,
2223
+ resolve: await service.transform(args[0], args[1])
2224
+ });
2225
+ break;
2226
+ case "formatMessages":
2227
+ workerPort.postMessage({
2228
+ id,
2229
+ resolve: await service.formatMessages(args[0], args[1])
2230
+ });
2231
+ break;
2232
+ case "analyzeMetafile":
2233
+ workerPort.postMessage({
2234
+ id,
2235
+ resolve: await service.analyzeMetafile(args[0], args[1])
2236
+ });
2237
+ break;
2238
+ default: throw new Error(`Invalid command: ${command}`);
2239
+ }
2240
+ } catch (reject) {
2241
+ workerPort.postMessage({
2242
+ id,
2243
+ reject,
2244
+ properties: extractProperties(reject)
2245
+ });
2246
+ }
2247
+ Atomics.add(sharedBufferView, 0, 1);
2248
+ Atomics.notify(sharedBufferView, 0, Infinity);
2249
+ })();
2250
+ });
2251
+ } catch (reject) {
2252
+ parentPort.on("message", (msg) => {
2253
+ let { sharedBuffer, id } = msg;
2254
+ let sharedBufferView = new Int32Array(sharedBuffer);
2255
+ workerPort.postMessage({
2256
+ id,
2257
+ reject,
2258
+ properties: extractProperties(reject)
2259
+ });
2260
+ Atomics.add(sharedBufferView, 0, 1);
2261
+ Atomics.notify(sharedBufferView, 0, Infinity);
2262
+ });
2263
+ }
2264
+ };
2265
+ if (isInternalWorkerThread) startSyncServiceWorker();
2266
+ var node_default = node_exports;
2267
+ }) });
2268
+
2269
+ //#endregion
2270
+ //#region ../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/constants.js
2271
+ var require_constants = /* @__PURE__ */ __commonJS({ "../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/constants.js": ((exports, module) => {
2272
+ const WIN_SLASH = "\\\\/";
2273
+ const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
2274
+ /**
2275
+ * Posix glob regex
2276
+ */
2277
+ const DOT_LITERAL = "\\.";
2278
+ const PLUS_LITERAL = "\\+";
2279
+ const QMARK_LITERAL = "\\?";
2280
+ const SLASH_LITERAL = "\\/";
2281
+ const ONE_CHAR = "(?=.)";
2282
+ const QMARK = "[^/]";
2283
+ const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
2284
+ const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
2285
+ const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
2286
+ const NO_DOT = `(?!${DOT_LITERAL})`;
2287
+ const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
2288
+ const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
2289
+ const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
2290
+ const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
2291
+ const STAR = `${QMARK}*?`;
2292
+ const POSIX_CHARS = {
2293
+ DOT_LITERAL,
2294
+ PLUS_LITERAL,
2295
+ QMARK_LITERAL,
2296
+ SLASH_LITERAL,
2297
+ ONE_CHAR,
2298
+ QMARK,
2299
+ END_ANCHOR,
2300
+ DOTS_SLASH,
2301
+ NO_DOT,
2302
+ NO_DOTS,
2303
+ NO_DOT_SLASH,
2304
+ NO_DOTS_SLASH,
2305
+ QMARK_NO_DOT,
2306
+ STAR,
2307
+ START_ANCHOR,
2308
+ SEP: "/"
2309
+ };
2310
+ /**
2311
+ * Windows glob regex
2312
+ */
2313
+ const WINDOWS_CHARS = {
2314
+ ...POSIX_CHARS,
2315
+ SLASH_LITERAL: `[${WIN_SLASH}]`,
2316
+ QMARK: WIN_NO_SLASH,
2317
+ STAR: `${WIN_NO_SLASH}*?`,
2318
+ DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
2319
+ NO_DOT: `(?!${DOT_LITERAL})`,
2320
+ NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
2321
+ NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
2322
+ NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
2323
+ QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
2324
+ START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
2325
+ END_ANCHOR: `(?:[${WIN_SLASH}]|$)`,
2326
+ SEP: "\\"
2327
+ };
2328
+ /**
2329
+ * POSIX Bracket Regex
2330
+ */
2331
+ const POSIX_REGEX_SOURCE$1 = {
2332
+ alnum: "a-zA-Z0-9",
2333
+ alpha: "a-zA-Z",
2334
+ ascii: "\\x00-\\x7F",
2335
+ blank: " \\t",
2336
+ cntrl: "\\x00-\\x1F\\x7F",
2337
+ digit: "0-9",
2338
+ graph: "\\x21-\\x7E",
2339
+ lower: "a-z",
2340
+ print: "\\x20-\\x7E ",
2341
+ punct: "\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",
2342
+ space: " \\t\\r\\n\\v\\f",
2343
+ upper: "A-Z",
2344
+ word: "A-Za-z0-9_",
2345
+ xdigit: "A-Fa-f0-9"
2346
+ };
2347
+ module.exports = {
2348
+ MAX_LENGTH: 1024 * 64,
2349
+ POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
2350
+ REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
2351
+ REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
2352
+ REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
2353
+ REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
2354
+ REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
2355
+ REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
2356
+ REPLACEMENTS: {
2357
+ __proto__: null,
2358
+ "***": "*",
2359
+ "**/**": "**",
2360
+ "**/**/**": "**"
2361
+ },
2362
+ CHAR_0: 48,
2363
+ CHAR_9: 57,
2364
+ CHAR_UPPERCASE_A: 65,
2365
+ CHAR_LOWERCASE_A: 97,
2366
+ CHAR_UPPERCASE_Z: 90,
2367
+ CHAR_LOWERCASE_Z: 122,
2368
+ CHAR_LEFT_PARENTHESES: 40,
2369
+ CHAR_RIGHT_PARENTHESES: 41,
2370
+ CHAR_ASTERISK: 42,
2371
+ CHAR_AMPERSAND: 38,
2372
+ CHAR_AT: 64,
2373
+ CHAR_BACKWARD_SLASH: 92,
2374
+ CHAR_CARRIAGE_RETURN: 13,
2375
+ CHAR_CIRCUMFLEX_ACCENT: 94,
2376
+ CHAR_COLON: 58,
2377
+ CHAR_COMMA: 44,
2378
+ CHAR_DOT: 46,
2379
+ CHAR_DOUBLE_QUOTE: 34,
2380
+ CHAR_EQUAL: 61,
2381
+ CHAR_EXCLAMATION_MARK: 33,
2382
+ CHAR_FORM_FEED: 12,
2383
+ CHAR_FORWARD_SLASH: 47,
2384
+ CHAR_GRAVE_ACCENT: 96,
2385
+ CHAR_HASH: 35,
2386
+ CHAR_HYPHEN_MINUS: 45,
2387
+ CHAR_LEFT_ANGLE_BRACKET: 60,
2388
+ CHAR_LEFT_CURLY_BRACE: 123,
2389
+ CHAR_LEFT_SQUARE_BRACKET: 91,
2390
+ CHAR_LINE_FEED: 10,
2391
+ CHAR_NO_BREAK_SPACE: 160,
2392
+ CHAR_PERCENT: 37,
2393
+ CHAR_PLUS: 43,
2394
+ CHAR_QUESTION_MARK: 63,
2395
+ CHAR_RIGHT_ANGLE_BRACKET: 62,
2396
+ CHAR_RIGHT_CURLY_BRACE: 125,
2397
+ CHAR_RIGHT_SQUARE_BRACKET: 93,
2398
+ CHAR_SEMICOLON: 59,
2399
+ CHAR_SINGLE_QUOTE: 39,
2400
+ CHAR_SPACE: 32,
2401
+ CHAR_TAB: 9,
2402
+ CHAR_UNDERSCORE: 95,
2403
+ CHAR_VERTICAL_LINE: 124,
2404
+ CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
2405
+ extglobChars(chars) {
2406
+ return {
2407
+ "!": {
2408
+ type: "negate",
2409
+ open: "(?:(?!(?:",
2410
+ close: `))${chars.STAR})`
2411
+ },
2412
+ "?": {
2413
+ type: "qmark",
2414
+ open: "(?:",
2415
+ close: ")?"
2416
+ },
2417
+ "+": {
2418
+ type: "plus",
2419
+ open: "(?:",
2420
+ close: ")+"
2421
+ },
2422
+ "*": {
2423
+ type: "star",
2424
+ open: "(?:",
2425
+ close: ")*"
2426
+ },
2427
+ "@": {
2428
+ type: "at",
2429
+ open: "(?:",
2430
+ close: ")"
2431
+ }
2432
+ };
2433
+ },
2434
+ globChars(win32) {
2435
+ return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
2436
+ }
2437
+ };
2438
+ }) });
2439
+
2440
+ //#endregion
2441
+ //#region ../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/utils.js
2442
+ var require_utils = /* @__PURE__ */ __commonJS({ "../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/utils.js": ((exports) => {
2443
+ const { REGEX_BACKSLASH, REGEX_REMOVE_BACKSLASH, REGEX_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_GLOBAL } = require_constants();
2444
+ exports.isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val);
2445
+ exports.hasRegexChars = (str) => REGEX_SPECIAL_CHARS.test(str);
2446
+ exports.isRegexChar = (str) => str.length === 1 && exports.hasRegexChars(str);
2447
+ exports.escapeRegex = (str) => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, "\\$1");
2448
+ exports.toPosixSlashes = (str) => str.replace(REGEX_BACKSLASH, "/");
2449
+ exports.isWindows = () => {
2450
+ if (typeof navigator !== "undefined" && navigator.platform) {
2451
+ const platform = navigator.platform.toLowerCase();
2452
+ return platform === "win32" || platform === "windows";
2453
+ }
2454
+ if (typeof process !== "undefined" && process.platform) return process.platform === "win32";
2455
+ return false;
2456
+ };
2457
+ exports.removeBackslashes = (str) => {
2458
+ return str.replace(REGEX_REMOVE_BACKSLASH, (match) => {
2459
+ return match === "\\" ? "" : match;
2460
+ });
2461
+ };
2462
+ exports.escapeLast = (input, char, lastIdx) => {
2463
+ const idx = input.lastIndexOf(char, lastIdx);
2464
+ if (idx === -1) return input;
2465
+ if (input[idx - 1] === "\\") return exports.escapeLast(input, char, idx - 1);
2466
+ return `${input.slice(0, idx)}\\${input.slice(idx)}`;
2467
+ };
2468
+ exports.removePrefix = (input, state = {}) => {
2469
+ let output = input;
2470
+ if (output.startsWith("./")) {
2471
+ output = output.slice(2);
2472
+ state.prefix = "./";
2473
+ }
2474
+ return output;
2475
+ };
2476
+ exports.wrapOutput = (input, state = {}, options = {}) => {
2477
+ const prepend = options.contains ? "" : "^";
2478
+ const append = options.contains ? "" : "$";
2479
+ let output = `${prepend}(?:${input})${append}`;
2480
+ if (state.negated === true) output = `(?:^(?!${output}).*$)`;
2481
+ return output;
2482
+ };
2483
+ exports.basename = (path$3, { windows } = {}) => {
2484
+ const segs = path$3.split(windows ? /[\\/]/ : "/");
2485
+ const last = segs[segs.length - 1];
2486
+ if (last === "") return segs[segs.length - 2];
2487
+ return last;
2488
+ };
2489
+ }) });
2490
+
2491
+ //#endregion
2492
+ //#region ../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/scan.js
2493
+ var require_scan = /* @__PURE__ */ __commonJS({ "../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/scan.js": ((exports, module) => {
2494
+ const utils$3 = require_utils();
2495
+ const { CHAR_ASTERISK, CHAR_AT, CHAR_BACKWARD_SLASH, CHAR_COMMA, CHAR_DOT, CHAR_EXCLAMATION_MARK, CHAR_FORWARD_SLASH, CHAR_LEFT_CURLY_BRACE, CHAR_LEFT_PARENTHESES, CHAR_LEFT_SQUARE_BRACKET, CHAR_PLUS, CHAR_QUESTION_MARK, CHAR_RIGHT_CURLY_BRACE, CHAR_RIGHT_PARENTHESES, CHAR_RIGHT_SQUARE_BRACKET } = require_constants();
2496
+ const isPathSeparator = (code) => {
2497
+ return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
2498
+ };
2499
+ const depth = (token) => {
2500
+ if (token.isPrefix !== true) token.depth = token.isGlobstar ? Infinity : 1;
2501
+ };
2502
+ /**
2503
+ * Quickly scans a glob pattern and returns an object with a handful of
2504
+ * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
2505
+ * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
2506
+ * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
2507
+ *
2508
+ * ```js
2509
+ * const pm = require('picomatch');
2510
+ * console.log(pm.scan('foo/bar/*.js'));
2511
+ * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
2512
+ * ```
2513
+ * @param {String} `str`
2514
+ * @param {Object} `options`
2515
+ * @return {Object} Returns an object with tokens and regex source string.
2516
+ * @api public
2517
+ */
2518
+ const scan$1 = (input, options) => {
2519
+ const opts = options || {};
2520
+ const length = input.length - 1;
2521
+ const scanToEnd = opts.parts === true || opts.scanToEnd === true;
2522
+ const slashes = [];
2523
+ const tokens = [];
2524
+ const parts = [];
2525
+ let str = input;
2526
+ let index = -1;
2527
+ let start = 0;
2528
+ let lastIndex = 0;
2529
+ let isBrace = false;
2530
+ let isBracket = false;
2531
+ let isGlob = false;
2532
+ let isExtglob = false;
2533
+ let isGlobstar = false;
2534
+ let braceEscaped = false;
2535
+ let backslashes = false;
2536
+ let negated = false;
2537
+ let negatedExtglob = false;
2538
+ let finished = false;
2539
+ let braces = 0;
2540
+ let prev;
2541
+ let code;
2542
+ let token = {
2543
+ value: "",
2544
+ depth: 0,
2545
+ isGlob: false
2546
+ };
2547
+ const eos = () => index >= length;
2548
+ const peek = () => str.charCodeAt(index + 1);
2549
+ const advance = () => {
2550
+ prev = code;
2551
+ return str.charCodeAt(++index);
2552
+ };
2553
+ while (index < length) {
2554
+ code = advance();
2555
+ let next;
2556
+ if (code === CHAR_BACKWARD_SLASH) {
2557
+ backslashes = token.backslashes = true;
2558
+ code = advance();
2559
+ if (code === CHAR_LEFT_CURLY_BRACE) braceEscaped = true;
2560
+ continue;
2561
+ }
2562
+ if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
2563
+ braces++;
2564
+ while (eos() !== true && (code = advance())) {
2565
+ if (code === CHAR_BACKWARD_SLASH) {
2566
+ backslashes = token.backslashes = true;
2567
+ advance();
2568
+ continue;
2569
+ }
2570
+ if (code === CHAR_LEFT_CURLY_BRACE) {
2571
+ braces++;
2572
+ continue;
2573
+ }
2574
+ if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
2575
+ isBrace = token.isBrace = true;
2576
+ isGlob = token.isGlob = true;
2577
+ finished = true;
2578
+ if (scanToEnd === true) continue;
2579
+ break;
2580
+ }
2581
+ if (braceEscaped !== true && code === CHAR_COMMA) {
2582
+ isBrace = token.isBrace = true;
2583
+ isGlob = token.isGlob = true;
2584
+ finished = true;
2585
+ if (scanToEnd === true) continue;
2586
+ break;
2587
+ }
2588
+ if (code === CHAR_RIGHT_CURLY_BRACE) {
2589
+ braces--;
2590
+ if (braces === 0) {
2591
+ braceEscaped = false;
2592
+ isBrace = token.isBrace = true;
2593
+ finished = true;
2594
+ break;
2595
+ }
2596
+ }
2597
+ }
2598
+ if (scanToEnd === true) continue;
2599
+ break;
2600
+ }
2601
+ if (code === CHAR_FORWARD_SLASH) {
2602
+ slashes.push(index);
2603
+ tokens.push(token);
2604
+ token = {
2605
+ value: "",
2606
+ depth: 0,
2607
+ isGlob: false
2608
+ };
2609
+ if (finished === true) continue;
2610
+ if (prev === CHAR_DOT && index === start + 1) {
2611
+ start += 2;
2612
+ continue;
2613
+ }
2614
+ lastIndex = index + 1;
2615
+ continue;
2616
+ }
2617
+ if (opts.noext !== true) {
2618
+ if ((code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK) === true && peek() === CHAR_LEFT_PARENTHESES) {
2619
+ isGlob = token.isGlob = true;
2620
+ isExtglob = token.isExtglob = true;
2621
+ finished = true;
2622
+ if (code === CHAR_EXCLAMATION_MARK && index === start) negatedExtglob = true;
2623
+ if (scanToEnd === true) {
2624
+ while (eos() !== true && (code = advance())) {
2625
+ if (code === CHAR_BACKWARD_SLASH) {
2626
+ backslashes = token.backslashes = true;
2627
+ code = advance();
2628
+ continue;
2629
+ }
2630
+ if (code === CHAR_RIGHT_PARENTHESES) {
2631
+ isGlob = token.isGlob = true;
2632
+ finished = true;
2633
+ break;
2634
+ }
2635
+ }
2636
+ continue;
2637
+ }
2638
+ break;
2639
+ }
2640
+ }
2641
+ if (code === CHAR_ASTERISK) {
2642
+ if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
2643
+ isGlob = token.isGlob = true;
2644
+ finished = true;
2645
+ if (scanToEnd === true) continue;
2646
+ break;
2647
+ }
2648
+ if (code === CHAR_QUESTION_MARK) {
2649
+ isGlob = token.isGlob = true;
2650
+ finished = true;
2651
+ if (scanToEnd === true) continue;
2652
+ break;
2653
+ }
2654
+ if (code === CHAR_LEFT_SQUARE_BRACKET) {
2655
+ while (eos() !== true && (next = advance())) {
2656
+ if (next === CHAR_BACKWARD_SLASH) {
2657
+ backslashes = token.backslashes = true;
2658
+ advance();
2659
+ continue;
2660
+ }
2661
+ if (next === CHAR_RIGHT_SQUARE_BRACKET) {
2662
+ isBracket = token.isBracket = true;
2663
+ isGlob = token.isGlob = true;
2664
+ finished = true;
2665
+ break;
2666
+ }
2667
+ }
2668
+ if (scanToEnd === true) continue;
2669
+ break;
2670
+ }
2671
+ if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
2672
+ negated = token.negated = true;
2673
+ start++;
2674
+ continue;
2675
+ }
2676
+ if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
2677
+ isGlob = token.isGlob = true;
2678
+ if (scanToEnd === true) {
2679
+ while (eos() !== true && (code = advance())) {
2680
+ if (code === CHAR_LEFT_PARENTHESES) {
2681
+ backslashes = token.backslashes = true;
2682
+ code = advance();
2683
+ continue;
2684
+ }
2685
+ if (code === CHAR_RIGHT_PARENTHESES) {
2686
+ finished = true;
2687
+ break;
2688
+ }
2689
+ }
2690
+ continue;
2691
+ }
2692
+ break;
2693
+ }
2694
+ if (isGlob === true) {
2695
+ finished = true;
2696
+ if (scanToEnd === true) continue;
2697
+ break;
2698
+ }
2699
+ }
2700
+ if (opts.noext === true) {
2701
+ isExtglob = false;
2702
+ isGlob = false;
2703
+ }
2704
+ let base = str;
2705
+ let prefix = "";
2706
+ let glob = "";
2707
+ if (start > 0) {
2708
+ prefix = str.slice(0, start);
2709
+ str = str.slice(start);
2710
+ lastIndex -= start;
2711
+ }
2712
+ if (base && isGlob === true && lastIndex > 0) {
2713
+ base = str.slice(0, lastIndex);
2714
+ glob = str.slice(lastIndex);
2715
+ } else if (isGlob === true) {
2716
+ base = "";
2717
+ glob = str;
2718
+ } else base = str;
2719
+ if (base && base !== "" && base !== "/" && base !== str) {
2720
+ if (isPathSeparator(base.charCodeAt(base.length - 1))) base = base.slice(0, -1);
2721
+ }
2722
+ if (opts.unescape === true) {
2723
+ if (glob) glob = utils$3.removeBackslashes(glob);
2724
+ if (base && backslashes === true) base = utils$3.removeBackslashes(base);
2725
+ }
2726
+ const state = {
2727
+ prefix,
2728
+ input,
2729
+ start,
2730
+ base,
2731
+ glob,
2732
+ isBrace,
2733
+ isBracket,
2734
+ isGlob,
2735
+ isExtglob,
2736
+ isGlobstar,
2737
+ negated,
2738
+ negatedExtglob
2739
+ };
2740
+ if (opts.tokens === true) {
2741
+ state.maxDepth = 0;
2742
+ if (!isPathSeparator(code)) tokens.push(token);
2743
+ state.tokens = tokens;
2744
+ }
2745
+ if (opts.parts === true || opts.tokens === true) {
2746
+ let prevIndex;
2747
+ for (let idx = 0; idx < slashes.length; idx++) {
2748
+ const n = prevIndex ? prevIndex + 1 : start;
2749
+ const i = slashes[idx];
2750
+ const value = input.slice(n, i);
2751
+ if (opts.tokens) {
2752
+ if (idx === 0 && start !== 0) {
2753
+ tokens[idx].isPrefix = true;
2754
+ tokens[idx].value = prefix;
2755
+ } else tokens[idx].value = value;
2756
+ depth(tokens[idx]);
2757
+ state.maxDepth += tokens[idx].depth;
2758
+ }
2759
+ if (idx !== 0 || value !== "") parts.push(value);
2760
+ prevIndex = i;
2761
+ }
2762
+ if (prevIndex && prevIndex + 1 < input.length) {
2763
+ const value = input.slice(prevIndex + 1);
2764
+ parts.push(value);
2765
+ if (opts.tokens) {
2766
+ tokens[tokens.length - 1].value = value;
2767
+ depth(tokens[tokens.length - 1]);
2768
+ state.maxDepth += tokens[tokens.length - 1].depth;
2769
+ }
2770
+ }
2771
+ state.slashes = slashes;
2772
+ state.parts = parts;
2773
+ }
2774
+ return state;
2775
+ };
2776
+ module.exports = scan$1;
2777
+ }) });
2778
+
2779
+ //#endregion
2780
+ //#region ../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/parse.js
2781
+ var require_parse = /* @__PURE__ */ __commonJS({ "../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/parse.js": ((exports, module) => {
2782
+ const constants$1 = require_constants();
2783
+ const utils$2 = require_utils();
2784
+ /**
2785
+ * Constants
2786
+ */
2787
+ const { MAX_LENGTH, POSIX_REGEX_SOURCE, REGEX_NON_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_BACKREF, REPLACEMENTS } = constants$1;
2788
+ /**
2789
+ * Helpers
2790
+ */
2791
+ const expandRange = (args, options) => {
2792
+ if (typeof options.expandRange === "function") return options.expandRange(...args, options);
2793
+ args.sort();
2794
+ const value = `[${args.join("-")}]`;
2795
+ try {
2796
+ new RegExp(value);
2797
+ } catch (ex) {
2798
+ return args.map((v) => utils$2.escapeRegex(v)).join("..");
2799
+ }
2800
+ return value;
2801
+ };
2802
+ /**
2803
+ * Create the message for a syntax error
2804
+ */
2805
+ const syntaxError = (type, char) => {
2806
+ return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
2807
+ };
2808
+ /**
2809
+ * Parse the given input string.
2810
+ * @param {String} input
2811
+ * @param {Object} options
2812
+ * @return {Object}
2813
+ */
2814
+ const parse$1 = (input, options) => {
2815
+ if (typeof input !== "string") throw new TypeError("Expected a string");
2816
+ input = REPLACEMENTS[input] || input;
2817
+ const opts = { ...options };
2818
+ const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
2819
+ let len = input.length;
2820
+ if (len > max) throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
2821
+ const bos = {
2822
+ type: "bos",
2823
+ value: "",
2824
+ output: opts.prepend || ""
2825
+ };
2826
+ const tokens = [bos];
2827
+ const capture = opts.capture ? "" : "?:";
2828
+ const PLATFORM_CHARS = constants$1.globChars(opts.windows);
2829
+ const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);
2830
+ const { DOT_LITERAL: DOT_LITERAL$1, PLUS_LITERAL: PLUS_LITERAL$1, SLASH_LITERAL: SLASH_LITERAL$1, ONE_CHAR: ONE_CHAR$1, DOTS_SLASH: DOTS_SLASH$1, NO_DOT: NO_DOT$1, NO_DOT_SLASH: NO_DOT_SLASH$1, NO_DOTS_SLASH: NO_DOTS_SLASH$1, QMARK: QMARK$1, QMARK_NO_DOT: QMARK_NO_DOT$1, STAR: STAR$1, START_ANCHOR: START_ANCHOR$1 } = PLATFORM_CHARS;
2831
+ const globstar = (opts$1) => {
2832
+ return `(${capture}(?:(?!${START_ANCHOR$1}${opts$1.dot ? DOTS_SLASH$1 : DOT_LITERAL$1}).)*?)`;
2833
+ };
2834
+ const nodot = opts.dot ? "" : NO_DOT$1;
2835
+ const qmarkNoDot = opts.dot ? QMARK$1 : QMARK_NO_DOT$1;
2836
+ let star = opts.bash === true ? globstar(opts) : STAR$1;
2837
+ if (opts.capture) star = `(${star})`;
2838
+ if (typeof opts.noext === "boolean") opts.noextglob = opts.noext;
2839
+ const state = {
2840
+ input,
2841
+ index: -1,
2842
+ start: 0,
2843
+ dot: opts.dot === true,
2844
+ consumed: "",
2845
+ output: "",
2846
+ prefix: "",
2847
+ backtrack: false,
2848
+ negated: false,
2849
+ brackets: 0,
2850
+ braces: 0,
2851
+ parens: 0,
2852
+ quotes: 0,
2853
+ globstar: false,
2854
+ tokens
2855
+ };
2856
+ input = utils$2.removePrefix(input, state);
2857
+ len = input.length;
2858
+ const extglobs = [];
2859
+ const braces = [];
2860
+ const stack = [];
2861
+ let prev = bos;
2862
+ let value;
2863
+ /**
2864
+ * Tokenizing helpers
2865
+ */
2866
+ const eos = () => state.index === len - 1;
2867
+ const peek = state.peek = (n = 1) => input[state.index + n];
2868
+ const advance = state.advance = () => input[++state.index] || "";
2869
+ const remaining = () => input.slice(state.index + 1);
2870
+ const consume = (value$1 = "", num = 0) => {
2871
+ state.consumed += value$1;
2872
+ state.index += num;
2873
+ };
2874
+ const append = (token) => {
2875
+ state.output += token.output != null ? token.output : token.value;
2876
+ consume(token.value);
2877
+ };
2878
+ const negate = () => {
2879
+ let count = 1;
2880
+ while (peek() === "!" && (peek(2) !== "(" || peek(3) === "?")) {
2881
+ advance();
2882
+ state.start++;
2883
+ count++;
2884
+ }
2885
+ if (count % 2 === 0) return false;
2886
+ state.negated = true;
2887
+ state.start++;
2888
+ return true;
2889
+ };
2890
+ const increment = (type) => {
2891
+ state[type]++;
2892
+ stack.push(type);
2893
+ };
2894
+ const decrement = (type) => {
2895
+ state[type]--;
2896
+ stack.pop();
2897
+ };
2898
+ /**
2899
+ * Push tokens onto the tokens array. This helper speeds up
2900
+ * tokenizing by 1) helping us avoid backtracking as much as possible,
2901
+ * and 2) helping us avoid creating extra tokens when consecutive
2902
+ * characters are plain text. This improves performance and simplifies
2903
+ * lookbehinds.
2904
+ */
2905
+ const push = (tok) => {
2906
+ if (prev.type === "globstar") {
2907
+ const isBrace = state.braces > 0 && (tok.type === "comma" || tok.type === "brace");
2908
+ const isExtglob = tok.extglob === true || extglobs.length && (tok.type === "pipe" || tok.type === "paren");
2909
+ if (tok.type !== "slash" && tok.type !== "paren" && !isBrace && !isExtglob) {
2910
+ state.output = state.output.slice(0, -prev.output.length);
2911
+ prev.type = "star";
2912
+ prev.value = "*";
2913
+ prev.output = star;
2914
+ state.output += prev.output;
2915
+ }
2916
+ }
2917
+ if (extglobs.length && tok.type !== "paren") extglobs[extglobs.length - 1].inner += tok.value;
2918
+ if (tok.value || tok.output) append(tok);
2919
+ if (prev && prev.type === "text" && tok.type === "text") {
2920
+ prev.output = (prev.output || prev.value) + tok.value;
2921
+ prev.value += tok.value;
2922
+ return;
2923
+ }
2924
+ tok.prev = prev;
2925
+ tokens.push(tok);
2926
+ prev = tok;
2927
+ };
2928
+ const extglobOpen = (type, value$1) => {
2929
+ const token = {
2930
+ ...EXTGLOB_CHARS[value$1],
2931
+ conditions: 1,
2932
+ inner: ""
2933
+ };
2934
+ token.prev = prev;
2935
+ token.parens = state.parens;
2936
+ token.output = state.output;
2937
+ const output = (opts.capture ? "(" : "") + token.open;
2938
+ increment("parens");
2939
+ push({
2940
+ type,
2941
+ value: value$1,
2942
+ output: state.output ? "" : ONE_CHAR$1
2943
+ });
2944
+ push({
2945
+ type: "paren",
2946
+ extglob: true,
2947
+ value: advance(),
2948
+ output
2949
+ });
2950
+ extglobs.push(token);
2951
+ };
2952
+ const extglobClose = (token) => {
2953
+ let output = token.close + (opts.capture ? ")" : "");
2954
+ let rest;
2955
+ if (token.type === "negate") {
2956
+ let extglobStar = star;
2957
+ if (token.inner && token.inner.length > 1 && token.inner.includes("/")) extglobStar = globstar(opts);
2958
+ if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) output = token.close = `)$))${extglobStar}`;
2959
+ if (token.inner.includes("*") && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) output = token.close = `)${parse$1(rest, {
2960
+ ...options,
2961
+ fastpaths: false
2962
+ }).output})${extglobStar})`;
2963
+ if (token.prev.type === "bos") state.negatedExtglob = true;
2964
+ }
2965
+ push({
2966
+ type: "paren",
2967
+ extglob: true,
2968
+ value,
2969
+ output
2970
+ });
2971
+ decrement("parens");
2972
+ };
2973
+ /**
2974
+ * Fast paths
2975
+ */
2976
+ if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
2977
+ let backslashes = false;
2978
+ let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
2979
+ if (first === "\\") {
2980
+ backslashes = true;
2981
+ return m;
2982
+ }
2983
+ if (first === "?") {
2984
+ if (esc) return esc + first + (rest ? QMARK$1.repeat(rest.length) : "");
2985
+ if (index === 0) return qmarkNoDot + (rest ? QMARK$1.repeat(rest.length) : "");
2986
+ return QMARK$1.repeat(chars.length);
2987
+ }
2988
+ if (first === ".") return DOT_LITERAL$1.repeat(chars.length);
2989
+ if (first === "*") {
2990
+ if (esc) return esc + first + (rest ? star : "");
2991
+ return star;
2992
+ }
2993
+ return esc ? m : `\\${m}`;
2994
+ });
2995
+ if (backslashes === true) if (opts.unescape === true) output = output.replace(/\\/g, "");
2996
+ else output = output.replace(/\\+/g, (m) => {
2997
+ return m.length % 2 === 0 ? "\\\\" : m ? "\\" : "";
2998
+ });
2999
+ if (output === input && opts.contains === true) {
3000
+ state.output = input;
3001
+ return state;
3002
+ }
3003
+ state.output = utils$2.wrapOutput(output, state, options);
3004
+ return state;
3005
+ }
3006
+ /**
3007
+ * Tokenize input until we reach end-of-string
3008
+ */
3009
+ while (!eos()) {
3010
+ value = advance();
3011
+ if (value === "\0") continue;
3012
+ /**
3013
+ * Escaped characters
3014
+ */
3015
+ if (value === "\\") {
3016
+ const next = peek();
3017
+ if (next === "/" && opts.bash !== true) continue;
3018
+ if (next === "." || next === ";") continue;
3019
+ if (!next) {
3020
+ value += "\\";
3021
+ push({
3022
+ type: "text",
3023
+ value
3024
+ });
3025
+ continue;
3026
+ }
3027
+ const match = /^\\+/.exec(remaining());
3028
+ let slashes = 0;
3029
+ if (match && match[0].length > 2) {
3030
+ slashes = match[0].length;
3031
+ state.index += slashes;
3032
+ if (slashes % 2 !== 0) value += "\\";
3033
+ }
3034
+ if (opts.unescape === true) value = advance();
3035
+ else value += advance();
3036
+ if (state.brackets === 0) {
3037
+ push({
3038
+ type: "text",
3039
+ value
3040
+ });
3041
+ continue;
3042
+ }
3043
+ }
3044
+ /**
3045
+ * If we're inside a regex character class, continue
3046
+ * until we reach the closing bracket.
3047
+ */
3048
+ if (state.brackets > 0 && (value !== "]" || prev.value === "[" || prev.value === "[^")) {
3049
+ if (opts.posix !== false && value === ":") {
3050
+ const inner = prev.value.slice(1);
3051
+ if (inner.includes("[")) {
3052
+ prev.posix = true;
3053
+ if (inner.includes(":")) {
3054
+ const idx = prev.value.lastIndexOf("[");
3055
+ const pre = prev.value.slice(0, idx);
3056
+ const rest$1 = prev.value.slice(idx + 2);
3057
+ const posix = POSIX_REGEX_SOURCE[rest$1];
3058
+ if (posix) {
3059
+ prev.value = pre + posix;
3060
+ state.backtrack = true;
3061
+ advance();
3062
+ if (!bos.output && tokens.indexOf(prev) === 1) bos.output = ONE_CHAR$1;
3063
+ continue;
3064
+ }
3065
+ }
3066
+ }
3067
+ }
3068
+ if (value === "[" && peek() !== ":" || value === "-" && peek() === "]") value = `\\${value}`;
3069
+ if (value === "]" && (prev.value === "[" || prev.value === "[^")) value = `\\${value}`;
3070
+ if (opts.posix === true && value === "!" && prev.value === "[") value = "^";
3071
+ prev.value += value;
3072
+ append({ value });
3073
+ continue;
3074
+ }
3075
+ /**
3076
+ * If we're inside a quoted string, continue
3077
+ * until we reach the closing double quote.
3078
+ */
3079
+ if (state.quotes === 1 && value !== "\"") {
3080
+ value = utils$2.escapeRegex(value);
3081
+ prev.value += value;
3082
+ append({ value });
3083
+ continue;
3084
+ }
3085
+ /**
3086
+ * Double quotes
3087
+ */
3088
+ if (value === "\"") {
3089
+ state.quotes = state.quotes === 1 ? 0 : 1;
3090
+ if (opts.keepQuotes === true) push({
3091
+ type: "text",
3092
+ value
3093
+ });
3094
+ continue;
3095
+ }
3096
+ /**
3097
+ * Parentheses
3098
+ */
3099
+ if (value === "(") {
3100
+ increment("parens");
3101
+ push({
3102
+ type: "paren",
3103
+ value
3104
+ });
3105
+ continue;
3106
+ }
3107
+ if (value === ")") {
3108
+ if (state.parens === 0 && opts.strictBrackets === true) throw new SyntaxError(syntaxError("opening", "("));
3109
+ const extglob = extglobs[extglobs.length - 1];
3110
+ if (extglob && state.parens === extglob.parens + 1) {
3111
+ extglobClose(extglobs.pop());
3112
+ continue;
3113
+ }
3114
+ push({
3115
+ type: "paren",
3116
+ value,
3117
+ output: state.parens ? ")" : "\\)"
3118
+ });
3119
+ decrement("parens");
3120
+ continue;
3121
+ }
3122
+ /**
3123
+ * Square brackets
3124
+ */
3125
+ if (value === "[") {
3126
+ if (opts.nobracket === true || !remaining().includes("]")) {
3127
+ if (opts.nobracket !== true && opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", "]"));
3128
+ value = `\\${value}`;
3129
+ } else increment("brackets");
3130
+ push({
3131
+ type: "bracket",
3132
+ value
3133
+ });
3134
+ continue;
3135
+ }
3136
+ if (value === "]") {
3137
+ if (opts.nobracket === true || prev && prev.type === "bracket" && prev.value.length === 1) {
3138
+ push({
3139
+ type: "text",
3140
+ value,
3141
+ output: `\\${value}`
3142
+ });
3143
+ continue;
3144
+ }
3145
+ if (state.brackets === 0) {
3146
+ if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("opening", "["));
3147
+ push({
3148
+ type: "text",
3149
+ value,
3150
+ output: `\\${value}`
3151
+ });
3152
+ continue;
3153
+ }
3154
+ decrement("brackets");
3155
+ const prevValue = prev.value.slice(1);
3156
+ if (prev.posix !== true && prevValue[0] === "^" && !prevValue.includes("/")) value = `/${value}`;
3157
+ prev.value += value;
3158
+ append({ value });
3159
+ if (opts.literalBrackets === false || utils$2.hasRegexChars(prevValue)) continue;
3160
+ const escaped = utils$2.escapeRegex(prev.value);
3161
+ state.output = state.output.slice(0, -prev.value.length);
3162
+ if (opts.literalBrackets === true) {
3163
+ state.output += escaped;
3164
+ prev.value = escaped;
3165
+ continue;
3166
+ }
3167
+ prev.value = `(${capture}${escaped}|${prev.value})`;
3168
+ state.output += prev.value;
3169
+ continue;
3170
+ }
3171
+ /**
3172
+ * Braces
3173
+ */
3174
+ if (value === "{" && opts.nobrace !== true) {
3175
+ increment("braces");
3176
+ const open = {
3177
+ type: "brace",
3178
+ value,
3179
+ output: "(",
3180
+ outputIndex: state.output.length,
3181
+ tokensIndex: state.tokens.length
3182
+ };
3183
+ braces.push(open);
3184
+ push(open);
3185
+ continue;
3186
+ }
3187
+ if (value === "}") {
3188
+ const brace = braces[braces.length - 1];
3189
+ if (opts.nobrace === true || !brace) {
3190
+ push({
3191
+ type: "text",
3192
+ value,
3193
+ output: value
3194
+ });
3195
+ continue;
3196
+ }
3197
+ let output = ")";
3198
+ if (brace.dots === true) {
3199
+ const arr = tokens.slice();
3200
+ const range = [];
3201
+ for (let i = arr.length - 1; i >= 0; i--) {
3202
+ tokens.pop();
3203
+ if (arr[i].type === "brace") break;
3204
+ if (arr[i].type !== "dots") range.unshift(arr[i].value);
3205
+ }
3206
+ output = expandRange(range, opts);
3207
+ state.backtrack = true;
3208
+ }
3209
+ if (brace.comma !== true && brace.dots !== true) {
3210
+ const out = state.output.slice(0, brace.outputIndex);
3211
+ const toks = state.tokens.slice(brace.tokensIndex);
3212
+ brace.value = brace.output = "\\{";
3213
+ value = output = "\\}";
3214
+ state.output = out;
3215
+ for (const t of toks) state.output += t.output || t.value;
3216
+ }
3217
+ push({
3218
+ type: "brace",
3219
+ value,
3220
+ output
3221
+ });
3222
+ decrement("braces");
3223
+ braces.pop();
3224
+ continue;
3225
+ }
3226
+ /**
3227
+ * Pipes
3228
+ */
3229
+ if (value === "|") {
3230
+ if (extglobs.length > 0) extglobs[extglobs.length - 1].conditions++;
3231
+ push({
3232
+ type: "text",
3233
+ value
3234
+ });
3235
+ continue;
3236
+ }
3237
+ /**
3238
+ * Commas
3239
+ */
3240
+ if (value === ",") {
3241
+ let output = value;
3242
+ const brace = braces[braces.length - 1];
3243
+ if (brace && stack[stack.length - 1] === "braces") {
3244
+ brace.comma = true;
3245
+ output = "|";
3246
+ }
3247
+ push({
3248
+ type: "comma",
3249
+ value,
3250
+ output
3251
+ });
3252
+ continue;
3253
+ }
3254
+ /**
3255
+ * Slashes
3256
+ */
3257
+ if (value === "/") {
3258
+ if (prev.type === "dot" && state.index === state.start + 1) {
3259
+ state.start = state.index + 1;
3260
+ state.consumed = "";
3261
+ state.output = "";
3262
+ tokens.pop();
3263
+ prev = bos;
3264
+ continue;
3265
+ }
3266
+ push({
3267
+ type: "slash",
3268
+ value,
3269
+ output: SLASH_LITERAL$1
3270
+ });
3271
+ continue;
3272
+ }
3273
+ /**
3274
+ * Dots
3275
+ */
3276
+ if (value === ".") {
3277
+ if (state.braces > 0 && prev.type === "dot") {
3278
+ if (prev.value === ".") prev.output = DOT_LITERAL$1;
3279
+ const brace = braces[braces.length - 1];
3280
+ prev.type = "dots";
3281
+ prev.output += value;
3282
+ prev.value += value;
3283
+ brace.dots = true;
3284
+ continue;
3285
+ }
3286
+ if (state.braces + state.parens === 0 && prev.type !== "bos" && prev.type !== "slash") {
3287
+ push({
3288
+ type: "text",
3289
+ value,
3290
+ output: DOT_LITERAL$1
3291
+ });
3292
+ continue;
3293
+ }
3294
+ push({
3295
+ type: "dot",
3296
+ value,
3297
+ output: DOT_LITERAL$1
3298
+ });
3299
+ continue;
3300
+ }
3301
+ /**
3302
+ * Question marks
3303
+ */
3304
+ if (value === "?") {
3305
+ if (!(prev && prev.value === "(") && opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
3306
+ extglobOpen("qmark", value);
3307
+ continue;
3308
+ }
3309
+ if (prev && prev.type === "paren") {
3310
+ const next = peek();
3311
+ let output = value;
3312
+ if (prev.value === "(" && !/[!=<:]/.test(next) || next === "<" && !/<([!=]|\w+>)/.test(remaining())) output = `\\${value}`;
3313
+ push({
3314
+ type: "text",
3315
+ value,
3316
+ output
3317
+ });
3318
+ continue;
3319
+ }
3320
+ if (opts.dot !== true && (prev.type === "slash" || prev.type === "bos")) {
3321
+ push({
3322
+ type: "qmark",
3323
+ value,
3324
+ output: QMARK_NO_DOT$1
3325
+ });
3326
+ continue;
3327
+ }
3328
+ push({
3329
+ type: "qmark",
3330
+ value,
3331
+ output: QMARK$1
3332
+ });
3333
+ continue;
3334
+ }
3335
+ /**
3336
+ * Exclamation
3337
+ */
3338
+ if (value === "!") {
3339
+ if (opts.noextglob !== true && peek() === "(") {
3340
+ if (peek(2) !== "?" || !/[!=<:]/.test(peek(3))) {
3341
+ extglobOpen("negate", value);
3342
+ continue;
3343
+ }
3344
+ }
3345
+ if (opts.nonegate !== true && state.index === 0) {
3346
+ negate();
3347
+ continue;
3348
+ }
3349
+ }
3350
+ /**
3351
+ * Plus
3352
+ */
3353
+ if (value === "+") {
3354
+ if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
3355
+ extglobOpen("plus", value);
3356
+ continue;
3357
+ }
3358
+ if (prev && prev.value === "(" || opts.regex === false) {
3359
+ push({
3360
+ type: "plus",
3361
+ value,
3362
+ output: PLUS_LITERAL$1
3363
+ });
3364
+ continue;
3365
+ }
3366
+ if (prev && (prev.type === "bracket" || prev.type === "paren" || prev.type === "brace") || state.parens > 0) {
3367
+ push({
3368
+ type: "plus",
3369
+ value
3370
+ });
3371
+ continue;
3372
+ }
3373
+ push({
3374
+ type: "plus",
3375
+ value: PLUS_LITERAL$1
3376
+ });
3377
+ continue;
3378
+ }
3379
+ /**
3380
+ * Plain text
3381
+ */
3382
+ if (value === "@") {
3383
+ if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
3384
+ push({
3385
+ type: "at",
3386
+ extglob: true,
3387
+ value,
3388
+ output: ""
3389
+ });
3390
+ continue;
3391
+ }
3392
+ push({
3393
+ type: "text",
3394
+ value
3395
+ });
3396
+ continue;
3397
+ }
3398
+ /**
3399
+ * Plain text
3400
+ */
3401
+ if (value !== "*") {
3402
+ if (value === "$" || value === "^") value = `\\${value}`;
3403
+ const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
3404
+ if (match) {
3405
+ value += match[0];
3406
+ state.index += match[0].length;
3407
+ }
3408
+ push({
3409
+ type: "text",
3410
+ value
3411
+ });
3412
+ continue;
3413
+ }
3414
+ /**
3415
+ * Stars
3416
+ */
3417
+ if (prev && (prev.type === "globstar" || prev.star === true)) {
3418
+ prev.type = "star";
3419
+ prev.star = true;
3420
+ prev.value += value;
3421
+ prev.output = star;
3422
+ state.backtrack = true;
3423
+ state.globstar = true;
3424
+ consume(value);
3425
+ continue;
3426
+ }
3427
+ let rest = remaining();
3428
+ if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
3429
+ extglobOpen("star", value);
3430
+ continue;
3431
+ }
3432
+ if (prev.type === "star") {
3433
+ if (opts.noglobstar === true) {
3434
+ consume(value);
3435
+ continue;
3436
+ }
3437
+ const prior = prev.prev;
3438
+ const before = prior.prev;
3439
+ const isStart = prior.type === "slash" || prior.type === "bos";
3440
+ const afterStar = before && (before.type === "star" || before.type === "globstar");
3441
+ if (opts.bash === true && (!isStart || rest[0] && rest[0] !== "/")) {
3442
+ push({
3443
+ type: "star",
3444
+ value,
3445
+ output: ""
3446
+ });
3447
+ continue;
3448
+ }
3449
+ const isBrace = state.braces > 0 && (prior.type === "comma" || prior.type === "brace");
3450
+ const isExtglob = extglobs.length && (prior.type === "pipe" || prior.type === "paren");
3451
+ if (!isStart && prior.type !== "paren" && !isBrace && !isExtglob) {
3452
+ push({
3453
+ type: "star",
3454
+ value,
3455
+ output: ""
3456
+ });
3457
+ continue;
3458
+ }
3459
+ while (rest.slice(0, 3) === "/**") {
3460
+ const after = input[state.index + 4];
3461
+ if (after && after !== "/") break;
3462
+ rest = rest.slice(3);
3463
+ consume("/**", 3);
3464
+ }
3465
+ if (prior.type === "bos" && eos()) {
3466
+ prev.type = "globstar";
3467
+ prev.value += value;
3468
+ prev.output = globstar(opts);
3469
+ state.output = prev.output;
3470
+ state.globstar = true;
3471
+ consume(value);
3472
+ continue;
3473
+ }
3474
+ if (prior.type === "slash" && prior.prev.type !== "bos" && !afterStar && eos()) {
3475
+ state.output = state.output.slice(0, -(prior.output + prev.output).length);
3476
+ prior.output = `(?:${prior.output}`;
3477
+ prev.type = "globstar";
3478
+ prev.output = globstar(opts) + (opts.strictSlashes ? ")" : "|$)");
3479
+ prev.value += value;
3480
+ state.globstar = true;
3481
+ state.output += prior.output + prev.output;
3482
+ consume(value);
3483
+ continue;
3484
+ }
3485
+ if (prior.type === "slash" && prior.prev.type !== "bos" && rest[0] === "/") {
3486
+ const end = rest[1] !== void 0 ? "|$" : "";
3487
+ state.output = state.output.slice(0, -(prior.output + prev.output).length);
3488
+ prior.output = `(?:${prior.output}`;
3489
+ prev.type = "globstar";
3490
+ prev.output = `${globstar(opts)}${SLASH_LITERAL$1}|${SLASH_LITERAL$1}${end})`;
3491
+ prev.value += value;
3492
+ state.output += prior.output + prev.output;
3493
+ state.globstar = true;
3494
+ consume(value + advance());
3495
+ push({
3496
+ type: "slash",
3497
+ value: "/",
3498
+ output: ""
3499
+ });
3500
+ continue;
3501
+ }
3502
+ if (prior.type === "bos" && rest[0] === "/") {
3503
+ prev.type = "globstar";
3504
+ prev.value += value;
3505
+ prev.output = `(?:^|${SLASH_LITERAL$1}|${globstar(opts)}${SLASH_LITERAL$1})`;
3506
+ state.output = prev.output;
3507
+ state.globstar = true;
3508
+ consume(value + advance());
3509
+ push({
3510
+ type: "slash",
3511
+ value: "/",
3512
+ output: ""
3513
+ });
3514
+ continue;
3515
+ }
3516
+ state.output = state.output.slice(0, -prev.output.length);
3517
+ prev.type = "globstar";
3518
+ prev.output = globstar(opts);
3519
+ prev.value += value;
3520
+ state.output += prev.output;
3521
+ state.globstar = true;
3522
+ consume(value);
3523
+ continue;
3524
+ }
3525
+ const token = {
3526
+ type: "star",
3527
+ value,
3528
+ output: star
3529
+ };
3530
+ if (opts.bash === true) {
3531
+ token.output = ".*?";
3532
+ if (prev.type === "bos" || prev.type === "slash") token.output = nodot + token.output;
3533
+ push(token);
3534
+ continue;
3535
+ }
3536
+ if (prev && (prev.type === "bracket" || prev.type === "paren") && opts.regex === true) {
3537
+ token.output = value;
3538
+ push(token);
3539
+ continue;
3540
+ }
3541
+ if (state.index === state.start || prev.type === "slash" || prev.type === "dot") {
3542
+ if (prev.type === "dot") {
3543
+ state.output += NO_DOT_SLASH$1;
3544
+ prev.output += NO_DOT_SLASH$1;
3545
+ } else if (opts.dot === true) {
3546
+ state.output += NO_DOTS_SLASH$1;
3547
+ prev.output += NO_DOTS_SLASH$1;
3548
+ } else {
3549
+ state.output += nodot;
3550
+ prev.output += nodot;
3551
+ }
3552
+ if (peek() !== "*") {
3553
+ state.output += ONE_CHAR$1;
3554
+ prev.output += ONE_CHAR$1;
3555
+ }
3556
+ }
3557
+ push(token);
3558
+ }
3559
+ while (state.brackets > 0) {
3560
+ if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", "]"));
3561
+ state.output = utils$2.escapeLast(state.output, "[");
3562
+ decrement("brackets");
3563
+ }
3564
+ while (state.parens > 0) {
3565
+ if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", ")"));
3566
+ state.output = utils$2.escapeLast(state.output, "(");
3567
+ decrement("parens");
3568
+ }
3569
+ while (state.braces > 0) {
3570
+ if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", "}"));
3571
+ state.output = utils$2.escapeLast(state.output, "{");
3572
+ decrement("braces");
3573
+ }
3574
+ if (opts.strictSlashes !== true && (prev.type === "star" || prev.type === "bracket")) push({
3575
+ type: "maybe_slash",
3576
+ value: "",
3577
+ output: `${SLASH_LITERAL$1}?`
3578
+ });
3579
+ if (state.backtrack === true) {
3580
+ state.output = "";
3581
+ for (const token of state.tokens) {
3582
+ state.output += token.output != null ? token.output : token.value;
3583
+ if (token.suffix) state.output += token.suffix;
3584
+ }
3585
+ }
3586
+ return state;
3587
+ };
3588
+ /**
3589
+ * Fast paths for creating regular expressions for common glob patterns.
3590
+ * This can significantly speed up processing and has very little downside
3591
+ * impact when none of the fast paths match.
3592
+ */
3593
+ parse$1.fastpaths = (input, options) => {
3594
+ const opts = { ...options };
3595
+ const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
3596
+ const len = input.length;
3597
+ if (len > max) throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
3598
+ input = REPLACEMENTS[input] || input;
3599
+ const { DOT_LITERAL: DOT_LITERAL$1, SLASH_LITERAL: SLASH_LITERAL$1, ONE_CHAR: ONE_CHAR$1, DOTS_SLASH: DOTS_SLASH$1, NO_DOT: NO_DOT$1, NO_DOTS: NO_DOTS$1, NO_DOTS_SLASH: NO_DOTS_SLASH$1, STAR: STAR$1, START_ANCHOR: START_ANCHOR$1 } = constants$1.globChars(opts.windows);
3600
+ const nodot = opts.dot ? NO_DOTS$1 : NO_DOT$1;
3601
+ const slashDot = opts.dot ? NO_DOTS_SLASH$1 : NO_DOT$1;
3602
+ const capture = opts.capture ? "" : "?:";
3603
+ const state = {
3604
+ negated: false,
3605
+ prefix: ""
3606
+ };
3607
+ let star = opts.bash === true ? ".*?" : STAR$1;
3608
+ if (opts.capture) star = `(${star})`;
3609
+ const globstar = (opts$1) => {
3610
+ if (opts$1.noglobstar === true) return star;
3611
+ return `(${capture}(?:(?!${START_ANCHOR$1}${opts$1.dot ? DOTS_SLASH$1 : DOT_LITERAL$1}).)*?)`;
3612
+ };
3613
+ const create = (str) => {
3614
+ switch (str) {
3615
+ case "*": return `${nodot}${ONE_CHAR$1}${star}`;
3616
+ case ".*": return `${DOT_LITERAL$1}${ONE_CHAR$1}${star}`;
3617
+ case "*.*": return `${nodot}${star}${DOT_LITERAL$1}${ONE_CHAR$1}${star}`;
3618
+ case "*/*": return `${nodot}${star}${SLASH_LITERAL$1}${ONE_CHAR$1}${slashDot}${star}`;
3619
+ case "**": return nodot + globstar(opts);
3620
+ case "**/*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL$1})?${slashDot}${ONE_CHAR$1}${star}`;
3621
+ case "**/*.*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL$1})?${slashDot}${star}${DOT_LITERAL$1}${ONE_CHAR$1}${star}`;
3622
+ case "**/.*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL$1})?${DOT_LITERAL$1}${ONE_CHAR$1}${star}`;
3623
+ default: {
3624
+ const match = /^(.*?)\.(\w+)$/.exec(str);
3625
+ if (!match) return;
3626
+ const source$1 = create(match[1]);
3627
+ if (!source$1) return;
3628
+ return source$1 + DOT_LITERAL$1 + match[2];
3629
+ }
3630
+ }
3631
+ };
3632
+ const output = utils$2.removePrefix(input, state);
3633
+ let source = create(output);
3634
+ if (source && opts.strictSlashes !== true) source += `${SLASH_LITERAL$1}?`;
3635
+ return source;
3636
+ };
3637
+ module.exports = parse$1;
3638
+ }) });
3639
+
3640
+ //#endregion
3641
+ //#region ../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/picomatch.js
3642
+ var require_picomatch$1 = /* @__PURE__ */ __commonJS({ "../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/picomatch.js": ((exports, module) => {
3643
+ const scan = require_scan();
3644
+ const parse = require_parse();
3645
+ const utils$1 = require_utils();
3646
+ const constants = require_constants();
3647
+ const isObject = (val) => val && typeof val === "object" && !Array.isArray(val);
3648
+ /**
3649
+ * Creates a matcher function from one or more glob patterns. The
3650
+ * returned function takes a string to match as its first argument,
3651
+ * and returns true if the string is a match. The returned matcher
3652
+ * function also takes a boolean as the second argument that, when true,
3653
+ * returns an object with additional information.
3654
+ *
3655
+ * ```js
3656
+ * const picomatch = require('picomatch');
3657
+ * // picomatch(glob[, options]);
3658
+ *
3659
+ * const isMatch = picomatch('*.!(*a)');
3660
+ * console.log(isMatch('a.a')); //=> false
3661
+ * console.log(isMatch('a.b')); //=> true
3662
+ * ```
3663
+ * @name picomatch
3664
+ * @param {String|Array} `globs` One or more glob patterns.
3665
+ * @param {Object=} `options`
3666
+ * @return {Function=} Returns a matcher function.
3667
+ * @api public
3668
+ */
3669
+ const picomatch$2 = (glob, options, returnState = false) => {
3670
+ if (Array.isArray(glob)) {
3671
+ const fns = glob.map((input) => picomatch$2(input, options, returnState));
3672
+ const arrayMatcher = (str) => {
3673
+ for (const isMatch of fns) {
3674
+ const state$1 = isMatch(str);
3675
+ if (state$1) return state$1;
3676
+ }
3677
+ return false;
3678
+ };
3679
+ return arrayMatcher;
3680
+ }
3681
+ const isState = isObject(glob) && glob.tokens && glob.input;
3682
+ if (glob === "" || typeof glob !== "string" && !isState) throw new TypeError("Expected pattern to be a non-empty string");
3683
+ const opts = options || {};
3684
+ const posix = opts.windows;
3685
+ const regex = isState ? picomatch$2.compileRe(glob, options) : picomatch$2.makeRe(glob, options, false, true);
3686
+ const state = regex.state;
3687
+ delete regex.state;
3688
+ let isIgnored = () => false;
3689
+ if (opts.ignore) {
3690
+ const ignoreOpts = {
3691
+ ...options,
3692
+ ignore: null,
3693
+ onMatch: null,
3694
+ onResult: null
3695
+ };
3696
+ isIgnored = picomatch$2(opts.ignore, ignoreOpts, returnState);
3697
+ }
3698
+ const matcher = (input, returnObject = false) => {
3699
+ const { isMatch, match, output } = picomatch$2.test(input, regex, options, {
3700
+ glob,
3701
+ posix
3702
+ });
3703
+ const result = {
3704
+ glob,
3705
+ state,
3706
+ regex,
3707
+ posix,
3708
+ input,
3709
+ output,
3710
+ match,
3711
+ isMatch
3712
+ };
3713
+ if (typeof opts.onResult === "function") opts.onResult(result);
3714
+ if (isMatch === false) {
3715
+ result.isMatch = false;
3716
+ return returnObject ? result : false;
3717
+ }
3718
+ if (isIgnored(input)) {
3719
+ if (typeof opts.onIgnore === "function") opts.onIgnore(result);
3720
+ result.isMatch = false;
3721
+ return returnObject ? result : false;
3722
+ }
3723
+ if (typeof opts.onMatch === "function") opts.onMatch(result);
3724
+ return returnObject ? result : true;
3725
+ };
3726
+ if (returnState) matcher.state = state;
3727
+ return matcher;
3728
+ };
3729
+ /**
3730
+ * Test `input` with the given `regex`. This is used by the main
3731
+ * `picomatch()` function to test the input string.
3732
+ *
3733
+ * ```js
3734
+ * const picomatch = require('picomatch');
3735
+ * // picomatch.test(input, regex[, options]);
3736
+ *
3737
+ * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
3738
+ * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
3739
+ * ```
3740
+ * @param {String} `input` String to test.
3741
+ * @param {RegExp} `regex`
3742
+ * @return {Object} Returns an object with matching info.
3743
+ * @api public
3744
+ */
3745
+ picomatch$2.test = (input, regex, options, { glob, posix } = {}) => {
3746
+ if (typeof input !== "string") throw new TypeError("Expected input to be a string");
3747
+ if (input === "") return {
3748
+ isMatch: false,
3749
+ output: ""
3750
+ };
3751
+ const opts = options || {};
3752
+ const format = opts.format || (posix ? utils$1.toPosixSlashes : null);
3753
+ let match = input === glob;
3754
+ let output = match && format ? format(input) : input;
3755
+ if (match === false) {
3756
+ output = format ? format(input) : input;
3757
+ match = output === glob;
3758
+ }
3759
+ if (match === false || opts.capture === true) if (opts.matchBase === true || opts.basename === true) match = picomatch$2.matchBase(input, regex, options, posix);
3760
+ else match = regex.exec(output);
3761
+ return {
3762
+ isMatch: Boolean(match),
3763
+ match,
3764
+ output
3765
+ };
3766
+ };
3767
+ /**
3768
+ * Match the basename of a filepath.
3769
+ *
3770
+ * ```js
3771
+ * const picomatch = require('picomatch');
3772
+ * // picomatch.matchBase(input, glob[, options]);
3773
+ * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
3774
+ * ```
3775
+ * @param {String} `input` String to test.
3776
+ * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
3777
+ * @return {Boolean}
3778
+ * @api public
3779
+ */
3780
+ picomatch$2.matchBase = (input, glob, options) => {
3781
+ return (glob instanceof RegExp ? glob : picomatch$2.makeRe(glob, options)).test(utils$1.basename(input));
3782
+ };
3783
+ /**
3784
+ * Returns true if **any** of the given glob `patterns` match the specified `string`.
3785
+ *
3786
+ * ```js
3787
+ * const picomatch = require('picomatch');
3788
+ * // picomatch.isMatch(string, patterns[, options]);
3789
+ *
3790
+ * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
3791
+ * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
3792
+ * ```
3793
+ * @param {String|Array} str The string to test.
3794
+ * @param {String|Array} patterns One or more glob patterns to use for matching.
3795
+ * @param {Object} [options] See available [options](#options).
3796
+ * @return {Boolean} Returns true if any patterns match `str`
3797
+ * @api public
3798
+ */
3799
+ picomatch$2.isMatch = (str, patterns, options) => picomatch$2(patterns, options)(str);
3800
+ /**
3801
+ * Parse a glob pattern to create the source string for a regular
3802
+ * expression.
3803
+ *
3804
+ * ```js
3805
+ * const picomatch = require('picomatch');
3806
+ * const result = picomatch.parse(pattern[, options]);
3807
+ * ```
3808
+ * @param {String} `pattern`
3809
+ * @param {Object} `options`
3810
+ * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
3811
+ * @api public
3812
+ */
3813
+ picomatch$2.parse = (pattern, options) => {
3814
+ if (Array.isArray(pattern)) return pattern.map((p) => picomatch$2.parse(p, options));
3815
+ return parse(pattern, {
3816
+ ...options,
3817
+ fastpaths: false
3818
+ });
3819
+ };
3820
+ /**
3821
+ * Scan a glob pattern to separate the pattern into segments.
3822
+ *
3823
+ * ```js
3824
+ * const picomatch = require('picomatch');
3825
+ * // picomatch.scan(input[, options]);
3826
+ *
3827
+ * const result = picomatch.scan('!./foo/*.js');
3828
+ * console.log(result);
3829
+ * { prefix: '!./',
3830
+ * input: '!./foo/*.js',
3831
+ * start: 3,
3832
+ * base: 'foo',
3833
+ * glob: '*.js',
3834
+ * isBrace: false,
3835
+ * isBracket: false,
3836
+ * isGlob: true,
3837
+ * isExtglob: false,
3838
+ * isGlobstar: false,
3839
+ * negated: true }
3840
+ * ```
3841
+ * @param {String} `input` Glob pattern to scan.
3842
+ * @param {Object} `options`
3843
+ * @return {Object} Returns an object with
3844
+ * @api public
3845
+ */
3846
+ picomatch$2.scan = (input, options) => scan(input, options);
3847
+ /**
3848
+ * Compile a regular expression from the `state` object returned by the
3849
+ * [parse()](#parse) method.
3850
+ *
3851
+ * @param {Object} `state`
3852
+ * @param {Object} `options`
3853
+ * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
3854
+ * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
3855
+ * @return {RegExp}
3856
+ * @api public
3857
+ */
3858
+ picomatch$2.compileRe = (state, options, returnOutput = false, returnState = false) => {
3859
+ if (returnOutput === true) return state.output;
3860
+ const opts = options || {};
3861
+ const prepend = opts.contains ? "" : "^";
3862
+ const append = opts.contains ? "" : "$";
3863
+ let source = `${prepend}(?:${state.output})${append}`;
3864
+ if (state && state.negated === true) source = `^(?!${source}).*$`;
3865
+ const regex = picomatch$2.toRegex(source, options);
3866
+ if (returnState === true) regex.state = state;
3867
+ return regex;
3868
+ };
3869
+ /**
3870
+ * Create a regular expression from a parsed glob pattern.
3871
+ *
3872
+ * ```js
3873
+ * const picomatch = require('picomatch');
3874
+ * const state = picomatch.parse('*.js');
3875
+ * // picomatch.compileRe(state[, options]);
3876
+ *
3877
+ * console.log(picomatch.compileRe(state));
3878
+ * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
3879
+ * ```
3880
+ * @param {String} `state` The object returned from the `.parse` method.
3881
+ * @param {Object} `options`
3882
+ * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
3883
+ * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
3884
+ * @return {RegExp} Returns a regex created from the given pattern.
3885
+ * @api public
3886
+ */
3887
+ picomatch$2.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
3888
+ if (!input || typeof input !== "string") throw new TypeError("Expected a non-empty string");
3889
+ let parsed = {
3890
+ negated: false,
3891
+ fastpaths: true
3892
+ };
3893
+ if (options.fastpaths !== false && (input[0] === "." || input[0] === "*")) parsed.output = parse.fastpaths(input, options);
3894
+ if (!parsed.output) parsed = parse(input, options);
3895
+ return picomatch$2.compileRe(parsed, options, returnOutput, returnState);
3896
+ };
3897
+ /**
3898
+ * Create a regular expression from the given regex source string.
3899
+ *
3900
+ * ```js
3901
+ * const picomatch = require('picomatch');
3902
+ * // picomatch.toRegex(source[, options]);
3903
+ *
3904
+ * const { output } = picomatch.parse('*.js');
3905
+ * console.log(picomatch.toRegex(output));
3906
+ * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
3907
+ * ```
3908
+ * @param {String} `source` Regular expression source string.
3909
+ * @param {Object} `options`
3910
+ * @return {RegExp}
3911
+ * @api public
3912
+ */
3913
+ picomatch$2.toRegex = (source, options) => {
3914
+ try {
3915
+ const opts = options || {};
3916
+ return new RegExp(source, opts.flags || (opts.nocase ? "i" : ""));
3917
+ } catch (err) {
3918
+ if (options && options.debug === true) throw err;
3919
+ return /$^/;
3920
+ }
3921
+ };
3922
+ /**
3923
+ * Picomatch constants.
3924
+ * @return {Object}
3925
+ */
3926
+ picomatch$2.constants = constants;
3927
+ /**
3928
+ * Expose "picomatch"
3929
+ */
3930
+ module.exports = picomatch$2;
3931
+ }) });
3932
+
3933
+ //#endregion
3934
+ //#region ../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/index.js
3935
+ var require_picomatch = /* @__PURE__ */ __commonJS({ "../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/index.js": ((exports, module) => {
3936
+ const pico = require_picomatch$1();
3937
+ const utils = require_utils();
3938
+ function picomatch$1(glob, options, returnState = false) {
3939
+ if (options && (options.windows === null || options.windows === void 0)) options = {
3940
+ ...options,
3941
+ windows: utils.isWindows()
3942
+ };
3943
+ return pico(glob, options, returnState);
3944
+ }
3945
+ Object.assign(picomatch$1, pico);
3946
+ module.exports = picomatch$1;
3947
+ }) });
3948
+
3949
+ //#endregion
3950
+ //#region ../core/browser.js
3951
+ var import_picomatch = /* @__PURE__ */ __toESM(require_picomatch(), 1);
3952
+ var import_main = /* @__PURE__ */ __toESM(require_main(), 1);
3953
+ var browser_exports = {};
3954
+ import * as import___flairjs_core_wasm32_wasi from "@flairjs/core-wasm32-wasi";
3955
+ __reExport(browser_exports, import___flairjs_core_wasm32_wasi);
3956
+
3957
+ //#endregion
3958
+ //#region ../shared/dist/esm/index.js
3959
+ String.raw;
3960
+ const buildThemeTokens = (theme, themeName) => {
3961
+ let css$1 = "";
3962
+ const { tokens, selector } = theme;
3963
+ if (typeof selector === "string") css$1 += `${selector} {\n`;
3964
+ css$1 += tokensToCSSVars(tokens, theme.prefix ? [theme.prefix] : []);
3965
+ if (typeof selector === "string") css$1 += `}\n`;
3966
+ else css$1 = selector(css$1, themeName);
3967
+ Object.entries(theme.themes ?? {}).forEach(([name, themeConfig]) => {
3968
+ css$1 += buildThemeTokens({
3969
+ prefix: theme.prefix,
3970
+ selector: theme.selector,
3971
+ ...themeConfig
3972
+ }, name);
3973
+ });
3974
+ return css$1;
3975
+ };
3976
+ function tokensToCSSVars(tokens, prefix = []) {
3977
+ let css$1 = "";
3978
+ for (const [key, value] of Object.entries(tokens)) {
3979
+ const newPrefix = [...prefix, key];
3980
+ if (typeof value === "string" || typeof value === "number") css$1 += `--${newPrefix.join("-")}: ${value};\n`;
3981
+ else if (typeof value === "object" && value !== null) css$1 += tokensToCSSVars(value, newPrefix);
3982
+ }
3983
+ return css$1;
3984
+ }
3985
+ const __dirname$1 = dirname(fileURLToPath(import.meta.url));
3986
+ const getUserTheme = async () => {
3987
+ try {
3988
+ let userThemeFilePath = path$1.resolve(process.cwd(), "flair.theme.ts");
3989
+ if (!existsSync$1(userThemeFilePath)) userThemeFilePath = path$1.resolve(process.cwd(), "flair.theme.js");
3990
+ if (!existsSync$1(userThemeFilePath)) return null;
3991
+ const outFile = path$1.resolve(__dirname$1, `flair.theme.js`);
3992
+ await import_main.build({
3993
+ entryPoints: [userThemeFilePath],
3994
+ outfile: outFile,
3995
+ platform: "node",
3996
+ bundle: true,
3997
+ format: "esm",
3998
+ external: ["*"]
3999
+ });
4000
+ const cacheBuster = Date.now();
4001
+ const userTheme = await import(`${pathToFileURL(outFile).href}?update=${cacheBuster}`);
4002
+ if (userTheme.default) return {
4003
+ theme: userTheme.default,
4004
+ originalPath: userThemeFilePath
4005
+ };
4006
+ return null;
4007
+ } catch (error) {
4008
+ console.error("Error loading user theme:", error);
4009
+ return null;
4010
+ }
4011
+ };
4012
+ const require$1 = module$1.createRequire(import.meta.url);
4013
+ /**
4014
+ * Initialize the shared plugin context
4015
+ */
4016
+ async function initializeSharedContext(options = {}) {
4017
+ const { buildThemeFile } = options;
4018
+ const fileNameToGeneratedCssNameMap = /* @__PURE__ */ new Map();
4019
+ const flairThemeFile = require$1.resolve("@flairjs/client/theme.css");
4020
+ const flairGeneratedCssDir = path.resolve(flairThemeFile, "../generated-css");
4021
+ if (!existsSync(flairGeneratedCssDir)) await mkdir(flairGeneratedCssDir);
4022
+ else {
4023
+ await rm(flairGeneratedCssDir, {
4024
+ recursive: true,
4025
+ force: true
4026
+ });
4027
+ await mkdir(flairGeneratedCssDir);
4028
+ }
4029
+ let userTheme = await getUserTheme();
4030
+ const buildThemeCSS = buildThemeFile ?? buildThemeTokens;
4031
+ if (userTheme) {
4032
+ const themeCSS = buildThemeCSS(userTheme.theme);
4033
+ await writeFile(flairThemeFile, themeCSS, "utf-8");
4034
+ watch(userTheme.originalPath, async () => {
4035
+ userTheme = await getUserTheme();
4036
+ if (!userTheme) return;
4037
+ const themeCSS$1 = buildThemeCSS(userTheme.theme);
4038
+ await writeFile(flairThemeFile, themeCSS$1, "utf-8");
4039
+ });
4040
+ }
4041
+ const refreshCssFile = (filePath) => {
4042
+ if (fileNameToGeneratedCssNameMap.has(filePath)) {
4043
+ const previousGeneratedCssName = fileNameToGeneratedCssNameMap.get(filePath);
4044
+ setTimeout(() => {
4045
+ rm(path.join(flairGeneratedCssDir, previousGeneratedCssName));
4046
+ }, 2e3);
4047
+ }
4048
+ };
4049
+ return {
4050
+ flairThemeFile,
4051
+ flairGeneratedCssDir,
4052
+ userTheme,
4053
+ buildThemeCSS,
4054
+ refreshCssFile
4055
+ };
4056
+ }
4057
+ function shouldProcessFile(id, include, exclude) {
4058
+ const isIncluded = (0, import_picomatch.default)(include || ["**/*.{js,ts,jsx,tsx}"]);
4059
+ const isExcluded = (0, import_picomatch.default)(exclude || ["node_modules/**"]);
4060
+ if (!isIncluded(id)) return false;
4061
+ if (isExcluded(id)) return false;
4062
+ return true;
4063
+ }
4064
+ const colors = {
4065
+ reset: "\x1B[0m",
4066
+ fg: {
4067
+ red: "\x1B[31m",
4068
+ yellow: "\x1B[33m",
4069
+ blue: "\x1B[34m",
4070
+ white: "\x1B[37m"
4071
+ },
4072
+ bg: {
4073
+ red: "\x1B[41m",
4074
+ yellow: "\x1B[43m",
4075
+ blue: "\x1B[44m"
4076
+ }
4077
+ };
4078
+ const logger = {
4079
+ error: (msg) => {
4080
+ console.log(`${colors.bg.red}${colors.fg.white}[flairjs/Error]${colors.reset} ${colors.fg.red}${msg}${colors.reset}`);
4081
+ },
4082
+ warn: (msg) => {
4083
+ console.log(`${colors.bg.yellow}${colors.fg.white}[flairjs/Warning]${colors.reset} ${msg}${colors.reset}`);
4084
+ },
4085
+ info: (msg) => {
4086
+ console.log(`${colors.bg.blue}${colors.fg.white}[flairjs/Info]${colors.reset} ${msg}${colors.reset}`);
4087
+ }
4088
+ };
4089
+ const transformCode = (code, filePath, options) => {
4090
+ const result = (0, browser_exports.transformCode)(code, filePath, {
4091
+ cssOutDir: options.cssOutDir,
4092
+ classNameList: options.classNameList,
4093
+ useTheme: options.useTheme,
4094
+ theme: options.theme,
4095
+ appendTimestampToCssFile: options.appendTimestampToCssFile
4096
+ }, options.cssPreprocessor);
4097
+ (result?.logs ?? []).forEach((log) => {
4098
+ if (logger[log.level]) logger[log.level](log.message);
4099
+ });
4100
+ return result;
4101
+ };
4102
+
4103
+ //#endregion
4104
+ //#region src/index.ts
4105
+ function flairJsLoader(source, sourceMap) {
4106
+ return __awaiter(this, void 0, void 0, function() {
4107
+ var callback, options, context$1, fileName, result;
4108
+ var _a$1, _b;
4109
+ return __generator(this, function(_c) {
4110
+ switch (_c.label) {
4111
+ case 0:
4112
+ callback = this.async();
4113
+ if (!callback) {
4114
+ console.error("@flairjs/webpack-loader requires async support");
4115
+ return [2];
4116
+ }
4117
+ options = this.getOptions() || {};
4118
+ return [4, initializeSharedContext(options)];
4119
+ case 1:
4120
+ context$1 = _c.sent();
4121
+ fileName = this.resourcePath;
4122
+ if (!shouldProcessFile(fileName, options === null || options === void 0 ? void 0 : options.include, options === null || options === void 0 ? void 0 : options.exclude)) return [2, callback(null, source, sourceMap)];
4123
+ try {
4124
+ result = transformCode(source, fileName, {
4125
+ appendTimestampToCssFile: true,
4126
+ classNameList: options === null || options === void 0 ? void 0 : options.classNameList,
4127
+ cssPreprocessor: (options === null || options === void 0 ? void 0 : options.cssPreprocessor) ? function(css) {
4128
+ return options.cssPreprocessor(css, fileName);
4129
+ } : void 0,
4130
+ theme: (_a$1 = context$1.userTheme) === null || _a$1 === void 0 ? void 0 : _a$1.theme,
4131
+ useTheme: !!context$1.userTheme,
4132
+ cssOutDir: context$1.flairGeneratedCssDir
4133
+ });
4134
+ if (!result) return [2, callback(null, source, sourceMap)];
4135
+ if (result.generatedCssName) context$1.refreshCssFile(result.generatedCssName);
4136
+ callback(null, result.code, result.sourcemap ? JSON.parse((_b = result.sourcemap) !== null && _b !== void 0 ? _b : "{}") : sourceMap);
4137
+ } catch (error) {
4138
+ console.error("[@flairjs/webpack-loader]", error);
4139
+ callback(error, source, sourceMap);
4140
+ }
4141
+ return [2];
4142
+ }
4143
+ });
4144
+ });
4145
+ }
4146
+
4147
+ //#endregion
4148
+ export { flairJsLoader as default };