@shaper.org/vite-react-plugin 1.0.7 → 1.0.9

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