aipeek 0.1.5 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3732 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
8
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
9
+ }) : x)(function(x) {
10
+ if (typeof require !== "undefined") return require.apply(this, arguments);
11
+ throw Error('Dynamic require of "' + x + '" is not supported');
12
+ });
13
+ var __commonJS = (cb, mod) => function __require2() {
14
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
15
+ };
16
+ var __copyProps = (to, from, except, desc) => {
17
+ if (from && typeof from === "object" || typeof from === "function") {
18
+ for (let key of __getOwnPropNames(from))
19
+ if (!__hasOwnProp.call(to, key) && key !== except)
20
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
21
+ }
22
+ return to;
23
+ };
24
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
25
+ // If the importer is in node compatibility mode or this is not an ESM
26
+ // file that has been converted to a CommonJS file using a Babel-
27
+ // compatible transform (i.e. "__esModule" has not been set), then set
28
+ // "default" to the CommonJS "module.exports" for node compatibility.
29
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
30
+ mod
31
+ ));
32
+
33
+ // node_modules/esbuild/lib/main.js
34
+ var require_main = __commonJS({
35
+ "node_modules/esbuild/lib/main.js"(exports, module) {
36
+ "use strict";
37
+ var __defProp2 = Object.defineProperty;
38
+ var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
39
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
40
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
41
+ var __export = (target, all) => {
42
+ for (var name in all)
43
+ __defProp2(target, name, { get: all[name], enumerable: true });
44
+ };
45
+ var __copyProps2 = (to, from, except, desc) => {
46
+ if (from && typeof from === "object" || typeof from === "function") {
47
+ for (let key of __getOwnPropNames2(from))
48
+ if (!__hasOwnProp2.call(to, key) && key !== except)
49
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
50
+ }
51
+ return to;
52
+ };
53
+ var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
54
+ var node_exports = {};
55
+ __export(node_exports, {
56
+ analyzeMetafile: () => analyzeMetafile,
57
+ analyzeMetafileSync: () => analyzeMetafileSync,
58
+ build: () => build,
59
+ buildSync: () => buildSync,
60
+ context: () => context,
61
+ default: () => node_default,
62
+ formatMessages: () => formatMessages,
63
+ formatMessagesSync: () => formatMessagesSync,
64
+ initialize: () => initialize,
65
+ stop: () => stop,
66
+ transform: () => transform,
67
+ transformSync: () => transformSync2,
68
+ version: () => version
69
+ });
70
+ module.exports = __toCommonJS(node_exports);
71
+ function encodePacket(packet) {
72
+ let visit = (value) => {
73
+ if (value === null) {
74
+ bb.write8(0);
75
+ } else if (typeof value === "boolean") {
76
+ bb.write8(1);
77
+ bb.write8(+value);
78
+ } else if (typeof value === "number") {
79
+ bb.write8(2);
80
+ bb.write32(value | 0);
81
+ } else if (typeof value === "string") {
82
+ bb.write8(3);
83
+ bb.write(encodeUTF8(value));
84
+ } else if (value instanceof Uint8Array) {
85
+ bb.write8(4);
86
+ bb.write(value);
87
+ } else if (value instanceof Array) {
88
+ bb.write8(5);
89
+ bb.write32(value.length);
90
+ for (let item of value) {
91
+ visit(item);
92
+ }
93
+ } else {
94
+ let keys = Object.keys(value);
95
+ bb.write8(6);
96
+ bb.write32(keys.length);
97
+ for (let key of keys) {
98
+ bb.write(encodeUTF8(key));
99
+ visit(value[key]);
100
+ }
101
+ }
102
+ };
103
+ let bb = new ByteBuffer();
104
+ bb.write32(0);
105
+ bb.write32(packet.id << 1 | +!packet.isRequest);
106
+ visit(packet.value);
107
+ writeUInt32LE(bb.buf, bb.len - 4, 0);
108
+ return bb.buf.subarray(0, bb.len);
109
+ }
110
+ function decodePacket(bytes) {
111
+ let visit = () => {
112
+ switch (bb.read8()) {
113
+ case 0:
114
+ return null;
115
+ case 1:
116
+ return !!bb.read8();
117
+ case 2:
118
+ return bb.read32();
119
+ case 3:
120
+ return decodeUTF8(bb.read());
121
+ case 4:
122
+ return bb.read();
123
+ case 5: {
124
+ let count = bb.read32();
125
+ let value2 = [];
126
+ for (let i = 0; i < count; i++) {
127
+ value2.push(visit());
128
+ }
129
+ return value2;
130
+ }
131
+ case 6: {
132
+ let count = bb.read32();
133
+ let value2 = {};
134
+ for (let i = 0; i < count; i++) {
135
+ value2[decodeUTF8(bb.read())] = visit();
136
+ }
137
+ return value2;
138
+ }
139
+ default:
140
+ throw new Error("Invalid packet");
141
+ }
142
+ };
143
+ let bb = new ByteBuffer(bytes);
144
+ let id = bb.read32();
145
+ let isRequest = (id & 1) === 0;
146
+ id >>>= 1;
147
+ let value = visit();
148
+ if (bb.ptr !== bytes.length) {
149
+ throw new Error("Invalid packet");
150
+ }
151
+ return { id, isRequest, value };
152
+ }
153
+ var ByteBuffer = class {
154
+ constructor(buf = new Uint8Array(1024)) {
155
+ this.buf = buf;
156
+ this.len = 0;
157
+ this.ptr = 0;
158
+ }
159
+ _write(delta) {
160
+ if (this.len + delta > this.buf.length) {
161
+ let clone = new Uint8Array((this.len + delta) * 2);
162
+ clone.set(this.buf);
163
+ this.buf = clone;
164
+ }
165
+ this.len += delta;
166
+ return this.len - delta;
167
+ }
168
+ write8(value) {
169
+ let offset = this._write(1);
170
+ this.buf[offset] = value;
171
+ }
172
+ write32(value) {
173
+ let offset = this._write(4);
174
+ writeUInt32LE(this.buf, value, offset);
175
+ }
176
+ write(bytes) {
177
+ let offset = this._write(4 + bytes.length);
178
+ writeUInt32LE(this.buf, bytes.length, offset);
179
+ this.buf.set(bytes, offset + 4);
180
+ }
181
+ _read(delta) {
182
+ if (this.ptr + delta > this.buf.length) {
183
+ throw new Error("Invalid packet");
184
+ }
185
+ this.ptr += delta;
186
+ return this.ptr - delta;
187
+ }
188
+ read8() {
189
+ return this.buf[this._read(1)];
190
+ }
191
+ read32() {
192
+ return readUInt32LE(this.buf, this._read(4));
193
+ }
194
+ read() {
195
+ let length = this.read32();
196
+ let bytes = new Uint8Array(length);
197
+ let ptr = this._read(bytes.length);
198
+ bytes.set(this.buf.subarray(ptr, ptr + length));
199
+ return bytes;
200
+ }
201
+ };
202
+ var encodeUTF8;
203
+ var decodeUTF8;
204
+ var encodeInvariant;
205
+ if (typeof TextEncoder !== "undefined" && typeof TextDecoder !== "undefined") {
206
+ let encoder = new TextEncoder();
207
+ let decoder = new TextDecoder();
208
+ encodeUTF8 = (text) => encoder.encode(text);
209
+ decodeUTF8 = (bytes) => decoder.decode(bytes);
210
+ encodeInvariant = 'new TextEncoder().encode("")';
211
+ } else if (typeof Buffer !== "undefined") {
212
+ encodeUTF8 = (text) => Buffer.from(text);
213
+ decodeUTF8 = (bytes) => {
214
+ let { buffer, byteOffset, byteLength } = bytes;
215
+ return Buffer.from(buffer, byteOffset, byteLength).toString();
216
+ };
217
+ encodeInvariant = 'Buffer.from("")';
218
+ } else {
219
+ throw new Error("No UTF-8 codec found");
220
+ }
221
+ if (!(encodeUTF8("") instanceof Uint8Array))
222
+ throw new Error(`Invariant violation: "${encodeInvariant} instanceof Uint8Array" is incorrectly false
223
+
224
+ This indicates that your JavaScript environment is broken. You cannot use
225
+ esbuild in this environment because esbuild relies on this invariant. This
226
+ is not a problem with esbuild. You need to fix your environment instead.
227
+ `);
228
+ function readUInt32LE(buffer, offset) {
229
+ return (buffer[offset++] | buffer[offset++] << 8 | buffer[offset++] << 16 | buffer[offset++] << 24) >>> 0;
230
+ }
231
+ function writeUInt32LE(buffer, value, offset) {
232
+ buffer[offset++] = value;
233
+ buffer[offset++] = value >> 8;
234
+ buffer[offset++] = value >> 16;
235
+ buffer[offset++] = value >> 24;
236
+ }
237
+ var fromCharCode = String.fromCharCode;
238
+ function throwSyntaxError(bytes, index, message) {
239
+ const c = bytes[index];
240
+ let line = 1;
241
+ let column = 0;
242
+ for (let i = 0; i < index; i++) {
243
+ if (bytes[i] === 10) {
244
+ line++;
245
+ column = 0;
246
+ } else {
247
+ column++;
248
+ }
249
+ }
250
+ throw new SyntaxError(
251
+ message ? message : index === bytes.length ? "Unexpected end of input while parsing JSON" : c >= 32 && c <= 126 ? `Unexpected character ${fromCharCode(c)} in JSON at position ${index} (line ${line}, column ${column})` : `Unexpected byte 0x${c.toString(16)} in JSON at position ${index} (line ${line}, column ${column})`
252
+ );
253
+ }
254
+ function JSON_parse(bytes) {
255
+ if (!(bytes instanceof Uint8Array)) {
256
+ throw new Error(`JSON input must be a Uint8Array`);
257
+ }
258
+ const propertyStack = [];
259
+ const objectStack = [];
260
+ const stateStack = [];
261
+ const length = bytes.length;
262
+ let property = null;
263
+ let state = 0;
264
+ let object;
265
+ let i = 0;
266
+ while (i < length) {
267
+ let c = bytes[i++];
268
+ if (c <= 32) {
269
+ continue;
270
+ }
271
+ let value;
272
+ if (state === 2 && property === null && c !== 34 && c !== 125) {
273
+ throwSyntaxError(bytes, --i);
274
+ }
275
+ switch (c) {
276
+ // True
277
+ case 116: {
278
+ if (bytes[i++] !== 114 || bytes[i++] !== 117 || bytes[i++] !== 101) {
279
+ throwSyntaxError(bytes, --i);
280
+ }
281
+ value = true;
282
+ break;
283
+ }
284
+ // False
285
+ case 102: {
286
+ if (bytes[i++] !== 97 || bytes[i++] !== 108 || bytes[i++] !== 115 || bytes[i++] !== 101) {
287
+ throwSyntaxError(bytes, --i);
288
+ }
289
+ value = false;
290
+ break;
291
+ }
292
+ // Null
293
+ case 110: {
294
+ if (bytes[i++] !== 117 || bytes[i++] !== 108 || bytes[i++] !== 108) {
295
+ throwSyntaxError(bytes, --i);
296
+ }
297
+ value = null;
298
+ break;
299
+ }
300
+ // Number begin
301
+ case 45:
302
+ case 46:
303
+ case 48:
304
+ case 49:
305
+ case 50:
306
+ case 51:
307
+ case 52:
308
+ case 53:
309
+ case 54:
310
+ case 55:
311
+ case 56:
312
+ case 57: {
313
+ let index = i;
314
+ value = fromCharCode(c);
315
+ c = bytes[i];
316
+ while (true) {
317
+ switch (c) {
318
+ case 43:
319
+ case 45:
320
+ case 46:
321
+ case 48:
322
+ case 49:
323
+ case 50:
324
+ case 51:
325
+ case 52:
326
+ case 53:
327
+ case 54:
328
+ case 55:
329
+ case 56:
330
+ case 57:
331
+ case 101:
332
+ case 69: {
333
+ value += fromCharCode(c);
334
+ c = bytes[++i];
335
+ continue;
336
+ }
337
+ }
338
+ break;
339
+ }
340
+ value = +value;
341
+ if (isNaN(value)) {
342
+ throwSyntaxError(bytes, --index, "Invalid number");
343
+ }
344
+ break;
345
+ }
346
+ // String begin
347
+ case 34: {
348
+ value = "";
349
+ while (true) {
350
+ if (i >= length) {
351
+ throwSyntaxError(bytes, length);
352
+ }
353
+ c = bytes[i++];
354
+ if (c === 34) {
355
+ break;
356
+ } else if (c === 92) {
357
+ switch (bytes[i++]) {
358
+ // Normal escape sequence
359
+ case 34:
360
+ value += '"';
361
+ break;
362
+ case 47:
363
+ value += "/";
364
+ break;
365
+ case 92:
366
+ value += "\\";
367
+ break;
368
+ case 98:
369
+ value += "\b";
370
+ break;
371
+ case 102:
372
+ value += "\f";
373
+ break;
374
+ case 110:
375
+ value += "\n";
376
+ break;
377
+ case 114:
378
+ value += "\r";
379
+ break;
380
+ case 116:
381
+ value += " ";
382
+ break;
383
+ // Unicode escape sequence
384
+ case 117: {
385
+ let code = 0;
386
+ for (let j = 0; j < 4; j++) {
387
+ c = bytes[i++];
388
+ code <<= 4;
389
+ if (c >= 48 && c <= 57) code |= c - 48;
390
+ else if (c >= 97 && c <= 102) code |= c + (10 - 97);
391
+ else if (c >= 65 && c <= 70) code |= c + (10 - 65);
392
+ else throwSyntaxError(bytes, --i);
393
+ }
394
+ value += fromCharCode(code);
395
+ break;
396
+ }
397
+ // Invalid escape sequence
398
+ default:
399
+ throwSyntaxError(bytes, --i);
400
+ break;
401
+ }
402
+ } else if (c <= 127) {
403
+ value += fromCharCode(c);
404
+ } else if ((c & 224) === 192) {
405
+ value += fromCharCode((c & 31) << 6 | bytes[i++] & 63);
406
+ } else if ((c & 240) === 224) {
407
+ value += fromCharCode((c & 15) << 12 | (bytes[i++] & 63) << 6 | bytes[i++] & 63);
408
+ } else if ((c & 248) == 240) {
409
+ let codePoint = (c & 7) << 18 | (bytes[i++] & 63) << 12 | (bytes[i++] & 63) << 6 | bytes[i++] & 63;
410
+ if (codePoint > 65535) {
411
+ codePoint -= 65536;
412
+ value += fromCharCode(codePoint >> 10 & 1023 | 55296);
413
+ codePoint = 56320 | codePoint & 1023;
414
+ }
415
+ value += fromCharCode(codePoint);
416
+ }
417
+ }
418
+ value[0];
419
+ break;
420
+ }
421
+ // Array begin
422
+ case 91: {
423
+ value = [];
424
+ propertyStack.push(property);
425
+ objectStack.push(object);
426
+ stateStack.push(state);
427
+ property = null;
428
+ object = value;
429
+ state = 1;
430
+ continue;
431
+ }
432
+ // Object begin
433
+ case 123: {
434
+ value = {};
435
+ propertyStack.push(property);
436
+ objectStack.push(object);
437
+ stateStack.push(state);
438
+ property = null;
439
+ object = value;
440
+ state = 2;
441
+ continue;
442
+ }
443
+ // Array end
444
+ case 93: {
445
+ if (state !== 1) {
446
+ throwSyntaxError(bytes, --i);
447
+ }
448
+ value = object;
449
+ property = propertyStack.pop();
450
+ object = objectStack.pop();
451
+ state = stateStack.pop();
452
+ break;
453
+ }
454
+ // Object end
455
+ case 125: {
456
+ if (state !== 2) {
457
+ throwSyntaxError(bytes, --i);
458
+ }
459
+ value = object;
460
+ property = propertyStack.pop();
461
+ object = objectStack.pop();
462
+ state = stateStack.pop();
463
+ break;
464
+ }
465
+ default: {
466
+ throwSyntaxError(bytes, --i);
467
+ }
468
+ }
469
+ c = bytes[i];
470
+ while (c <= 32) {
471
+ c = bytes[++i];
472
+ }
473
+ switch (state) {
474
+ case 0: {
475
+ if (i === length) {
476
+ return value;
477
+ }
478
+ break;
479
+ }
480
+ case 1: {
481
+ object.push(value);
482
+ if (c === 44) {
483
+ i++;
484
+ continue;
485
+ }
486
+ if (c === 93) {
487
+ continue;
488
+ }
489
+ break;
490
+ }
491
+ case 2: {
492
+ if (property === null) {
493
+ property = value;
494
+ if (c === 58) {
495
+ i++;
496
+ continue;
497
+ }
498
+ } else {
499
+ object[property] = value;
500
+ property = null;
501
+ if (c === 44) {
502
+ i++;
503
+ continue;
504
+ }
505
+ if (c === 125) {
506
+ continue;
507
+ }
508
+ }
509
+ break;
510
+ }
511
+ }
512
+ break;
513
+ }
514
+ throwSyntaxError(bytes, i);
515
+ }
516
+ var quote = JSON.stringify;
517
+ var buildLogLevelDefault = "warning";
518
+ var transformLogLevelDefault = "silent";
519
+ function validateAndJoinStringArray(values, what) {
520
+ const toJoin = [];
521
+ for (const value of values) {
522
+ validateStringValue(value, what);
523
+ if (value.indexOf(",") >= 0) throw new Error(`Invalid ${what}: ${value}`);
524
+ toJoin.push(value);
525
+ }
526
+ return toJoin.join(",");
527
+ }
528
+ var canBeAnything = () => null;
529
+ var mustBeBoolean = (value) => typeof value === "boolean" ? null : "a boolean";
530
+ var mustBeString = (value) => typeof value === "string" ? null : "a string";
531
+ var mustBeRegExp = (value) => value instanceof RegExp ? null : "a RegExp object";
532
+ var mustBeInteger = (value) => typeof value === "number" && value === (value | 0) ? null : "an integer";
533
+ var mustBeValidPortNumber = (value) => typeof value === "number" && value === (value | 0) && value >= 0 && value <= 65535 ? null : "a valid port number";
534
+ var mustBeFunction = (value) => typeof value === "function" ? null : "a function";
535
+ var mustBeArray = (value) => Array.isArray(value) ? null : "an array";
536
+ var mustBeArrayOfStrings = (value) => Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "an array of strings";
537
+ var mustBeObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? null : "an object";
538
+ var mustBeEntryPoints = (value) => typeof value === "object" && value !== null ? null : "an array or an object";
539
+ var mustBeWebAssemblyModule = (value) => value instanceof WebAssembly.Module ? null : "a WebAssembly.Module";
540
+ var mustBeObjectOrNull = (value) => typeof value === "object" && !Array.isArray(value) ? null : "an object or null";
541
+ var mustBeStringOrBoolean = (value) => typeof value === "string" || typeof value === "boolean" ? null : "a string or a boolean";
542
+ var mustBeStringOrObject = (value) => typeof value === "string" || typeof value === "object" && value !== null && !Array.isArray(value) ? null : "a string or an object";
543
+ var mustBeStringOrArrayOfStrings = (value) => typeof value === "string" || Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "a string or an array of strings";
544
+ var mustBeStringOrUint8Array = (value) => typeof value === "string" || value instanceof Uint8Array ? null : "a string or a Uint8Array";
545
+ var mustBeStringOrURL = (value) => typeof value === "string" || value instanceof URL ? null : "a string or a URL";
546
+ function getFlag(object, keys, key, mustBeFn) {
547
+ let value = object[key];
548
+ keys[key + ""] = true;
549
+ if (value === void 0) return void 0;
550
+ let mustBe = mustBeFn(value);
551
+ if (mustBe !== null) throw new Error(`${quote(key)} must be ${mustBe}`);
552
+ return value;
553
+ }
554
+ function checkForInvalidFlags(object, keys, where) {
555
+ for (let key in object) {
556
+ if (!(key in keys)) {
557
+ throw new Error(`Invalid option ${where}: ${quote(key)}`);
558
+ }
559
+ }
560
+ }
561
+ function validateInitializeOptions(options) {
562
+ let keys = /* @__PURE__ */ Object.create(null);
563
+ let wasmURL = getFlag(options, keys, "wasmURL", mustBeStringOrURL);
564
+ let wasmModule = getFlag(options, keys, "wasmModule", mustBeWebAssemblyModule);
565
+ let worker = getFlag(options, keys, "worker", mustBeBoolean);
566
+ checkForInvalidFlags(options, keys, "in initialize() call");
567
+ return {
568
+ wasmURL,
569
+ wasmModule,
570
+ worker
571
+ };
572
+ }
573
+ function validateMangleCache(mangleCache) {
574
+ let validated;
575
+ if (mangleCache !== void 0) {
576
+ validated = /* @__PURE__ */ Object.create(null);
577
+ for (let key in mangleCache) {
578
+ let value = mangleCache[key];
579
+ if (typeof value === "string" || value === false) {
580
+ validated[key] = value;
581
+ } else {
582
+ throw new Error(`Expected ${quote(key)} in mangle cache to map to either a string or false`);
583
+ }
584
+ }
585
+ }
586
+ return validated;
587
+ }
588
+ function pushLogFlags(flags, options, keys, isTTY2, logLevelDefault) {
589
+ let color = getFlag(options, keys, "color", mustBeBoolean);
590
+ let logLevel = getFlag(options, keys, "logLevel", mustBeString);
591
+ let logLimit = getFlag(options, keys, "logLimit", mustBeInteger);
592
+ if (color !== void 0) flags.push(`--color=${color}`);
593
+ else if (isTTY2) flags.push(`--color=true`);
594
+ flags.push(`--log-level=${logLevel || logLevelDefault}`);
595
+ flags.push(`--log-limit=${logLimit || 0}`);
596
+ }
597
+ function validateStringValue(value, what, key) {
598
+ if (typeof value !== "string") {
599
+ throw new Error(`Expected value for ${what}${key !== void 0 ? " " + quote(key) : ""} to be a string, got ${typeof value} instead`);
600
+ }
601
+ return value;
602
+ }
603
+ function pushCommonFlags(flags, options, keys) {
604
+ let legalComments = getFlag(options, keys, "legalComments", mustBeString);
605
+ let sourceRoot = getFlag(options, keys, "sourceRoot", mustBeString);
606
+ let sourcesContent = getFlag(options, keys, "sourcesContent", mustBeBoolean);
607
+ let target = getFlag(options, keys, "target", mustBeStringOrArrayOfStrings);
608
+ let format = getFlag(options, keys, "format", mustBeString);
609
+ let globalName = getFlag(options, keys, "globalName", mustBeString);
610
+ let mangleProps = getFlag(options, keys, "mangleProps", mustBeRegExp);
611
+ let reserveProps = getFlag(options, keys, "reserveProps", mustBeRegExp);
612
+ let mangleQuoted = getFlag(options, keys, "mangleQuoted", mustBeBoolean);
613
+ let minify = getFlag(options, keys, "minify", mustBeBoolean);
614
+ let minifySyntax = getFlag(options, keys, "minifySyntax", mustBeBoolean);
615
+ let minifyWhitespace = getFlag(options, keys, "minifyWhitespace", mustBeBoolean);
616
+ let minifyIdentifiers = getFlag(options, keys, "minifyIdentifiers", mustBeBoolean);
617
+ let lineLimit = getFlag(options, keys, "lineLimit", mustBeInteger);
618
+ let drop = getFlag(options, keys, "drop", mustBeArrayOfStrings);
619
+ let dropLabels = getFlag(options, keys, "dropLabels", mustBeArrayOfStrings);
620
+ let charset = getFlag(options, keys, "charset", mustBeString);
621
+ let treeShaking = getFlag(options, keys, "treeShaking", mustBeBoolean);
622
+ let ignoreAnnotations = getFlag(options, keys, "ignoreAnnotations", mustBeBoolean);
623
+ let jsx = getFlag(options, keys, "jsx", mustBeString);
624
+ let jsxFactory = getFlag(options, keys, "jsxFactory", mustBeString);
625
+ let jsxFragment = getFlag(options, keys, "jsxFragment", mustBeString);
626
+ let jsxImportSource = getFlag(options, keys, "jsxImportSource", mustBeString);
627
+ let jsxDev = getFlag(options, keys, "jsxDev", mustBeBoolean);
628
+ let jsxSideEffects = getFlag(options, keys, "jsxSideEffects", mustBeBoolean);
629
+ let define = getFlag(options, keys, "define", mustBeObject);
630
+ let logOverride = getFlag(options, keys, "logOverride", mustBeObject);
631
+ let supported = getFlag(options, keys, "supported", mustBeObject);
632
+ let pure = getFlag(options, keys, "pure", mustBeArrayOfStrings);
633
+ let keepNames = getFlag(options, keys, "keepNames", mustBeBoolean);
634
+ let platform = getFlag(options, keys, "platform", mustBeString);
635
+ let tsconfigRaw = getFlag(options, keys, "tsconfigRaw", mustBeStringOrObject);
636
+ let absPaths = getFlag(options, keys, "absPaths", mustBeArrayOfStrings);
637
+ if (legalComments) flags.push(`--legal-comments=${legalComments}`);
638
+ if (sourceRoot !== void 0) flags.push(`--source-root=${sourceRoot}`);
639
+ if (sourcesContent !== void 0) flags.push(`--sources-content=${sourcesContent}`);
640
+ if (target) flags.push(`--target=${validateAndJoinStringArray(Array.isArray(target) ? target : [target], "target")}`);
641
+ if (format) flags.push(`--format=${format}`);
642
+ if (globalName) flags.push(`--global-name=${globalName}`);
643
+ if (platform) flags.push(`--platform=${platform}`);
644
+ if (tsconfigRaw) flags.push(`--tsconfig-raw=${typeof tsconfigRaw === "string" ? tsconfigRaw : JSON.stringify(tsconfigRaw)}`);
645
+ if (minify) flags.push("--minify");
646
+ if (minifySyntax) flags.push("--minify-syntax");
647
+ if (minifyWhitespace) flags.push("--minify-whitespace");
648
+ if (minifyIdentifiers) flags.push("--minify-identifiers");
649
+ if (lineLimit) flags.push(`--line-limit=${lineLimit}`);
650
+ if (charset) flags.push(`--charset=${charset}`);
651
+ if (treeShaking !== void 0) flags.push(`--tree-shaking=${treeShaking}`);
652
+ if (ignoreAnnotations) flags.push(`--ignore-annotations`);
653
+ if (drop) for (let what of drop) flags.push(`--drop:${validateStringValue(what, "drop")}`);
654
+ if (dropLabels) flags.push(`--drop-labels=${validateAndJoinStringArray(dropLabels, "drop label")}`);
655
+ if (absPaths) flags.push(`--abs-paths=${validateAndJoinStringArray(absPaths, "abs paths")}`);
656
+ if (mangleProps) flags.push(`--mangle-props=${jsRegExpToGoRegExp(mangleProps)}`);
657
+ if (reserveProps) flags.push(`--reserve-props=${jsRegExpToGoRegExp(reserveProps)}`);
658
+ if (mangleQuoted !== void 0) flags.push(`--mangle-quoted=${mangleQuoted}`);
659
+ if (jsx) flags.push(`--jsx=${jsx}`);
660
+ if (jsxFactory) flags.push(`--jsx-factory=${jsxFactory}`);
661
+ if (jsxFragment) flags.push(`--jsx-fragment=${jsxFragment}`);
662
+ if (jsxImportSource) flags.push(`--jsx-import-source=${jsxImportSource}`);
663
+ if (jsxDev) flags.push(`--jsx-dev`);
664
+ if (jsxSideEffects) flags.push(`--jsx-side-effects`);
665
+ if (define) {
666
+ for (let key in define) {
667
+ if (key.indexOf("=") >= 0) throw new Error(`Invalid define: ${key}`);
668
+ flags.push(`--define:${key}=${validateStringValue(define[key], "define", key)}`);
669
+ }
670
+ }
671
+ if (logOverride) {
672
+ for (let key in logOverride) {
673
+ if (key.indexOf("=") >= 0) throw new Error(`Invalid log override: ${key}`);
674
+ flags.push(`--log-override:${key}=${validateStringValue(logOverride[key], "log override", key)}`);
675
+ }
676
+ }
677
+ if (supported) {
678
+ for (let key in supported) {
679
+ if (key.indexOf("=") >= 0) throw new Error(`Invalid supported: ${key}`);
680
+ const value = supported[key];
681
+ if (typeof value !== "boolean") throw new Error(`Expected value for supported ${quote(key)} to be a boolean, got ${typeof value} instead`);
682
+ flags.push(`--supported:${key}=${value}`);
683
+ }
684
+ }
685
+ if (pure) for (let fn of pure) flags.push(`--pure:${validateStringValue(fn, "pure")}`);
686
+ if (keepNames) flags.push(`--keep-names`);
687
+ }
688
+ function flagsForBuildOptions(callName, options, isTTY2, logLevelDefault, writeDefault) {
689
+ var _a2;
690
+ let flags = [];
691
+ let entries = [];
692
+ let keys = /* @__PURE__ */ Object.create(null);
693
+ let stdinContents = null;
694
+ let stdinResolveDir = null;
695
+ pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
696
+ pushCommonFlags(flags, options, keys);
697
+ let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
698
+ let bundle = getFlag(options, keys, "bundle", mustBeBoolean);
699
+ let splitting = getFlag(options, keys, "splitting", mustBeBoolean);
700
+ let preserveSymlinks = getFlag(options, keys, "preserveSymlinks", mustBeBoolean);
701
+ let metafile = getFlag(options, keys, "metafile", mustBeBoolean);
702
+ let outfile = getFlag(options, keys, "outfile", mustBeString);
703
+ let outdir = getFlag(options, keys, "outdir", mustBeString);
704
+ let outbase = getFlag(options, keys, "outbase", mustBeString);
705
+ let tsconfig = getFlag(options, keys, "tsconfig", mustBeString);
706
+ let resolveExtensions = getFlag(options, keys, "resolveExtensions", mustBeArrayOfStrings);
707
+ let nodePathsInput = getFlag(options, keys, "nodePaths", mustBeArrayOfStrings);
708
+ let mainFields = getFlag(options, keys, "mainFields", mustBeArrayOfStrings);
709
+ let conditions = getFlag(options, keys, "conditions", mustBeArrayOfStrings);
710
+ let external = getFlag(options, keys, "external", mustBeArrayOfStrings);
711
+ let packages = getFlag(options, keys, "packages", mustBeString);
712
+ let alias = getFlag(options, keys, "alias", mustBeObject);
713
+ let loader = getFlag(options, keys, "loader", mustBeObject);
714
+ let outExtension = getFlag(options, keys, "outExtension", mustBeObject);
715
+ let publicPath = getFlag(options, keys, "publicPath", mustBeString);
716
+ let entryNames = getFlag(options, keys, "entryNames", mustBeString);
717
+ let chunkNames = getFlag(options, keys, "chunkNames", mustBeString);
718
+ let assetNames = getFlag(options, keys, "assetNames", mustBeString);
719
+ let inject = getFlag(options, keys, "inject", mustBeArrayOfStrings);
720
+ let banner = getFlag(options, keys, "banner", mustBeObject);
721
+ let footer = getFlag(options, keys, "footer", mustBeObject);
722
+ let entryPoints = getFlag(options, keys, "entryPoints", mustBeEntryPoints);
723
+ let absWorkingDir = getFlag(options, keys, "absWorkingDir", mustBeString);
724
+ let stdin = getFlag(options, keys, "stdin", mustBeObject);
725
+ let write = (_a2 = getFlag(options, keys, "write", mustBeBoolean)) != null ? _a2 : writeDefault;
726
+ let allowOverwrite = getFlag(options, keys, "allowOverwrite", mustBeBoolean);
727
+ let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
728
+ keys.plugins = true;
729
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
730
+ if (sourcemap) flags.push(`--sourcemap${sourcemap === true ? "" : `=${sourcemap}`}`);
731
+ if (bundle) flags.push("--bundle");
732
+ if (allowOverwrite) flags.push("--allow-overwrite");
733
+ if (splitting) flags.push("--splitting");
734
+ if (preserveSymlinks) flags.push("--preserve-symlinks");
735
+ if (metafile) flags.push(`--metafile`);
736
+ if (outfile) flags.push(`--outfile=${outfile}`);
737
+ if (outdir) flags.push(`--outdir=${outdir}`);
738
+ if (outbase) flags.push(`--outbase=${outbase}`);
739
+ if (tsconfig) flags.push(`--tsconfig=${tsconfig}`);
740
+ if (packages) flags.push(`--packages=${packages}`);
741
+ if (resolveExtensions) flags.push(`--resolve-extensions=${validateAndJoinStringArray(resolveExtensions, "resolve extension")}`);
742
+ if (publicPath) flags.push(`--public-path=${publicPath}`);
743
+ if (entryNames) flags.push(`--entry-names=${entryNames}`);
744
+ if (chunkNames) flags.push(`--chunk-names=${chunkNames}`);
745
+ if (assetNames) flags.push(`--asset-names=${assetNames}`);
746
+ if (mainFields) flags.push(`--main-fields=${validateAndJoinStringArray(mainFields, "main field")}`);
747
+ if (conditions) flags.push(`--conditions=${validateAndJoinStringArray(conditions, "condition")}`);
748
+ if (external) for (let name of external) flags.push(`--external:${validateStringValue(name, "external")}`);
749
+ if (alias) {
750
+ for (let old in alias) {
751
+ if (old.indexOf("=") >= 0) throw new Error(`Invalid package name in alias: ${old}`);
752
+ flags.push(`--alias:${old}=${validateStringValue(alias[old], "alias", old)}`);
753
+ }
754
+ }
755
+ if (banner) {
756
+ for (let type in banner) {
757
+ if (type.indexOf("=") >= 0) throw new Error(`Invalid banner file type: ${type}`);
758
+ flags.push(`--banner:${type}=${validateStringValue(banner[type], "banner", type)}`);
759
+ }
760
+ }
761
+ if (footer) {
762
+ for (let type in footer) {
763
+ if (type.indexOf("=") >= 0) throw new Error(`Invalid footer file type: ${type}`);
764
+ flags.push(`--footer:${type}=${validateStringValue(footer[type], "footer", type)}`);
765
+ }
766
+ }
767
+ if (inject) for (let path3 of inject) flags.push(`--inject:${validateStringValue(path3, "inject")}`);
768
+ if (loader) {
769
+ for (let ext in loader) {
770
+ if (ext.indexOf("=") >= 0) throw new Error(`Invalid loader extension: ${ext}`);
771
+ flags.push(`--loader:${ext}=${validateStringValue(loader[ext], "loader", ext)}`);
772
+ }
773
+ }
774
+ if (outExtension) {
775
+ for (let ext in outExtension) {
776
+ if (ext.indexOf("=") >= 0) throw new Error(`Invalid out extension: ${ext}`);
777
+ flags.push(`--out-extension:${ext}=${validateStringValue(outExtension[ext], "out extension", ext)}`);
778
+ }
779
+ }
780
+ if (entryPoints) {
781
+ if (Array.isArray(entryPoints)) {
782
+ for (let i = 0, n = entryPoints.length; i < n; i++) {
783
+ let entryPoint = entryPoints[i];
784
+ if (typeof entryPoint === "object" && entryPoint !== null) {
785
+ let entryPointKeys = /* @__PURE__ */ Object.create(null);
786
+ let input = getFlag(entryPoint, entryPointKeys, "in", mustBeString);
787
+ let output = getFlag(entryPoint, entryPointKeys, "out", mustBeString);
788
+ checkForInvalidFlags(entryPoint, entryPointKeys, "in entry point at index " + i);
789
+ if (input === void 0) throw new Error('Missing property "in" for entry point at index ' + i);
790
+ if (output === void 0) throw new Error('Missing property "out" for entry point at index ' + i);
791
+ entries.push([output, input]);
792
+ } else {
793
+ entries.push(["", validateStringValue(entryPoint, "entry point at index " + i)]);
794
+ }
795
+ }
796
+ } else {
797
+ for (let key in entryPoints) {
798
+ entries.push([key, validateStringValue(entryPoints[key], "entry point", key)]);
799
+ }
800
+ }
801
+ }
802
+ if (stdin) {
803
+ let stdinKeys = /* @__PURE__ */ Object.create(null);
804
+ let contents = getFlag(stdin, stdinKeys, "contents", mustBeStringOrUint8Array);
805
+ let resolveDir = getFlag(stdin, stdinKeys, "resolveDir", mustBeString);
806
+ let sourcefile = getFlag(stdin, stdinKeys, "sourcefile", mustBeString);
807
+ let loader2 = getFlag(stdin, stdinKeys, "loader", mustBeString);
808
+ checkForInvalidFlags(stdin, stdinKeys, 'in "stdin" object');
809
+ if (sourcefile) flags.push(`--sourcefile=${sourcefile}`);
810
+ if (loader2) flags.push(`--loader=${loader2}`);
811
+ if (resolveDir) stdinResolveDir = resolveDir;
812
+ if (typeof contents === "string") stdinContents = encodeUTF8(contents);
813
+ else if (contents instanceof Uint8Array) stdinContents = contents;
814
+ }
815
+ let nodePaths = [];
816
+ if (nodePathsInput) {
817
+ for (let value of nodePathsInput) {
818
+ value += "";
819
+ nodePaths.push(value);
820
+ }
821
+ }
822
+ return {
823
+ entries,
824
+ flags,
825
+ write,
826
+ stdinContents,
827
+ stdinResolveDir,
828
+ absWorkingDir,
829
+ nodePaths,
830
+ mangleCache: validateMangleCache(mangleCache)
831
+ };
832
+ }
833
+ function flagsForTransformOptions(callName, options, isTTY2, logLevelDefault) {
834
+ let flags = [];
835
+ let keys = /* @__PURE__ */ Object.create(null);
836
+ pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
837
+ pushCommonFlags(flags, options, keys);
838
+ let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
839
+ let sourcefile = getFlag(options, keys, "sourcefile", mustBeString);
840
+ let loader = getFlag(options, keys, "loader", mustBeString);
841
+ let banner = getFlag(options, keys, "banner", mustBeString);
842
+ let footer = getFlag(options, keys, "footer", mustBeString);
843
+ let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
844
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
845
+ if (sourcemap) flags.push(`--sourcemap=${sourcemap === true ? "external" : sourcemap}`);
846
+ if (sourcefile) flags.push(`--sourcefile=${sourcefile}`);
847
+ if (loader) flags.push(`--loader=${loader}`);
848
+ if (banner) flags.push(`--banner=${banner}`);
849
+ if (footer) flags.push(`--footer=${footer}`);
850
+ return {
851
+ flags,
852
+ mangleCache: validateMangleCache(mangleCache)
853
+ };
854
+ }
855
+ function createChannel(streamIn) {
856
+ const requestCallbacksByKey = {};
857
+ const closeData = { didClose: false, reason: "" };
858
+ let responseCallbacks = {};
859
+ let nextRequestID = 0;
860
+ let nextBuildKey = 0;
861
+ let stdout = new Uint8Array(16 * 1024);
862
+ let stdoutUsed = 0;
863
+ let readFromStdout = (chunk) => {
864
+ let limit = stdoutUsed + chunk.length;
865
+ if (limit > stdout.length) {
866
+ let swap = new Uint8Array(limit * 2);
867
+ swap.set(stdout);
868
+ stdout = swap;
869
+ }
870
+ stdout.set(chunk, stdoutUsed);
871
+ stdoutUsed += chunk.length;
872
+ let offset = 0;
873
+ while (offset + 4 <= stdoutUsed) {
874
+ let length = readUInt32LE(stdout, offset);
875
+ if (offset + 4 + length > stdoutUsed) {
876
+ break;
877
+ }
878
+ offset += 4;
879
+ handleIncomingPacket(stdout.subarray(offset, offset + length));
880
+ offset += length;
881
+ }
882
+ if (offset > 0) {
883
+ stdout.copyWithin(0, offset, stdoutUsed);
884
+ stdoutUsed -= offset;
885
+ }
886
+ };
887
+ let afterClose = (error) => {
888
+ closeData.didClose = true;
889
+ if (error) closeData.reason = ": " + (error.message || error);
890
+ const text = "The service was stopped" + closeData.reason;
891
+ for (let id in responseCallbacks) {
892
+ responseCallbacks[id](text, null);
893
+ }
894
+ responseCallbacks = {};
895
+ };
896
+ let sendRequest = (refs, value, callback) => {
897
+ if (closeData.didClose) return callback("The service is no longer running" + closeData.reason, null);
898
+ let id = nextRequestID++;
899
+ responseCallbacks[id] = (error, response) => {
900
+ try {
901
+ callback(error, response);
902
+ } finally {
903
+ if (refs) refs.unref();
904
+ }
905
+ };
906
+ if (refs) refs.ref();
907
+ streamIn.writeToStdin(encodePacket({ id, isRequest: true, value }));
908
+ };
909
+ let sendResponse = (id, value) => {
910
+ if (closeData.didClose) throw new Error("The service is no longer running" + closeData.reason);
911
+ streamIn.writeToStdin(encodePacket({ id, isRequest: false, value }));
912
+ };
913
+ let handleRequest = async (id, request) => {
914
+ try {
915
+ if (request.command === "ping") {
916
+ sendResponse(id, {});
917
+ return;
918
+ }
919
+ if (typeof request.key === "number") {
920
+ const requestCallbacks = requestCallbacksByKey[request.key];
921
+ if (!requestCallbacks) {
922
+ return;
923
+ }
924
+ const callback = requestCallbacks[request.command];
925
+ if (callback) {
926
+ await callback(id, request);
927
+ return;
928
+ }
929
+ }
930
+ throw new Error(`Invalid command: ` + request.command);
931
+ } catch (e) {
932
+ const errors = [extractErrorMessageV8(e, streamIn, null, void 0, "")];
933
+ try {
934
+ sendResponse(id, { errors });
935
+ } catch (e2) {
936
+ }
937
+ }
938
+ };
939
+ let isFirstPacket = true;
940
+ let handleIncomingPacket = (bytes) => {
941
+ if (isFirstPacket) {
942
+ isFirstPacket = false;
943
+ let binaryVersion = String.fromCharCode(...bytes);
944
+ if (binaryVersion !== "0.27.7") {
945
+ throw new Error(`Cannot start service: Host version "${"0.27.7"}" does not match binary version ${quote(binaryVersion)}`);
946
+ }
947
+ return;
948
+ }
949
+ let packet = decodePacket(bytes);
950
+ if (packet.isRequest) {
951
+ handleRequest(packet.id, packet.value);
952
+ } else {
953
+ let callback = responseCallbacks[packet.id];
954
+ delete responseCallbacks[packet.id];
955
+ if (packet.value.error) callback(packet.value.error, {});
956
+ else callback(null, packet.value);
957
+ }
958
+ };
959
+ let buildOrContext = ({ callName, refs, options, isTTY: isTTY2, defaultWD: defaultWD2, callback }) => {
960
+ let refCount = 0;
961
+ const buildKey = nextBuildKey++;
962
+ const requestCallbacks = {};
963
+ const buildRefs = {
964
+ ref() {
965
+ if (++refCount === 1) {
966
+ if (refs) refs.ref();
967
+ }
968
+ },
969
+ unref() {
970
+ if (--refCount === 0) {
971
+ delete requestCallbacksByKey[buildKey];
972
+ if (refs) refs.unref();
973
+ }
974
+ }
975
+ };
976
+ requestCallbacksByKey[buildKey] = requestCallbacks;
977
+ buildRefs.ref();
978
+ buildOrContextImpl(
979
+ callName,
980
+ buildKey,
981
+ sendRequest,
982
+ sendResponse,
983
+ buildRefs,
984
+ streamIn,
985
+ requestCallbacks,
986
+ options,
987
+ isTTY2,
988
+ defaultWD2,
989
+ (err, res) => {
990
+ try {
991
+ callback(err, res);
992
+ } finally {
993
+ buildRefs.unref();
994
+ }
995
+ }
996
+ );
997
+ };
998
+ let transform2 = ({ callName, refs, input, options, isTTY: isTTY2, fs: fs3, callback }) => {
999
+ const details = createObjectStash();
1000
+ let start = (inputPath) => {
1001
+ try {
1002
+ if (typeof input !== "string" && !(input instanceof Uint8Array))
1003
+ throw new Error('The input to "transform" must be a string or a Uint8Array');
1004
+ let {
1005
+ flags,
1006
+ mangleCache
1007
+ } = flagsForTransformOptions(callName, options, isTTY2, transformLogLevelDefault);
1008
+ let request = {
1009
+ command: "transform",
1010
+ flags,
1011
+ inputFS: inputPath !== null,
1012
+ input: inputPath !== null ? encodeUTF8(inputPath) : typeof input === "string" ? encodeUTF8(input) : input
1013
+ };
1014
+ if (mangleCache) request.mangleCache = mangleCache;
1015
+ sendRequest(refs, request, (error, response) => {
1016
+ if (error) return callback(new Error(error), null);
1017
+ let errors = replaceDetailsInMessages(response.errors, details);
1018
+ let warnings = replaceDetailsInMessages(response.warnings, details);
1019
+ let outstanding = 1;
1020
+ let next = () => {
1021
+ if (--outstanding === 0) {
1022
+ let result = {
1023
+ warnings,
1024
+ code: response.code,
1025
+ map: response.map,
1026
+ mangleCache: void 0,
1027
+ legalComments: void 0
1028
+ };
1029
+ if ("legalComments" in response) result.legalComments = response == null ? void 0 : response.legalComments;
1030
+ if (response.mangleCache) result.mangleCache = response == null ? void 0 : response.mangleCache;
1031
+ callback(null, result);
1032
+ }
1033
+ };
1034
+ if (errors.length > 0) return callback(failureErrorWithLog("Transform failed", errors, warnings), null);
1035
+ if (response.codeFS) {
1036
+ outstanding++;
1037
+ fs3.readFile(response.code, (err, contents) => {
1038
+ if (err !== null) {
1039
+ callback(err, null);
1040
+ } else {
1041
+ response.code = contents;
1042
+ next();
1043
+ }
1044
+ });
1045
+ }
1046
+ if (response.mapFS) {
1047
+ outstanding++;
1048
+ fs3.readFile(response.map, (err, contents) => {
1049
+ if (err !== null) {
1050
+ callback(err, null);
1051
+ } else {
1052
+ response.map = contents;
1053
+ next();
1054
+ }
1055
+ });
1056
+ }
1057
+ next();
1058
+ });
1059
+ } catch (e) {
1060
+ let flags = [];
1061
+ try {
1062
+ pushLogFlags(flags, options, {}, isTTY2, transformLogLevelDefault);
1063
+ } catch (e3) {
1064
+ }
1065
+ const error = extractErrorMessageV8(e, streamIn, details, void 0, "");
1066
+ sendRequest(refs, { command: "error", flags, error }, () => {
1067
+ error.detail = details.load(error.detail);
1068
+ callback(failureErrorWithLog("Transform failed", [error], []), null);
1069
+ });
1070
+ }
1071
+ };
1072
+ if ((typeof input === "string" || input instanceof Uint8Array) && input.length > 1024 * 1024) {
1073
+ let next = start;
1074
+ start = () => fs3.writeFile(input, next);
1075
+ }
1076
+ start(null);
1077
+ };
1078
+ let formatMessages2 = ({ callName, refs, messages, options, callback }) => {
1079
+ if (!options) throw new Error(`Missing second argument in ${callName}() call`);
1080
+ let keys = {};
1081
+ let kind = getFlag(options, keys, "kind", mustBeString);
1082
+ let color = getFlag(options, keys, "color", mustBeBoolean);
1083
+ let terminalWidth = getFlag(options, keys, "terminalWidth", mustBeInteger);
1084
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
1085
+ if (kind === void 0) throw new Error(`Missing "kind" in ${callName}() call`);
1086
+ if (kind !== "error" && kind !== "warning") throw new Error(`Expected "kind" to be "error" or "warning" in ${callName}() call`);
1087
+ let request = {
1088
+ command: "format-msgs",
1089
+ messages: sanitizeMessages(messages, "messages", null, "", terminalWidth),
1090
+ isWarning: kind === "warning"
1091
+ };
1092
+ if (color !== void 0) request.color = color;
1093
+ if (terminalWidth !== void 0) request.terminalWidth = terminalWidth;
1094
+ sendRequest(refs, request, (error, response) => {
1095
+ if (error) return callback(new Error(error), null);
1096
+ callback(null, response.messages);
1097
+ });
1098
+ };
1099
+ let analyzeMetafile2 = ({ callName, refs, metafile, options, callback }) => {
1100
+ if (options === void 0) options = {};
1101
+ let keys = {};
1102
+ let color = getFlag(options, keys, "color", mustBeBoolean);
1103
+ let verbose = getFlag(options, keys, "verbose", mustBeBoolean);
1104
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
1105
+ let request = {
1106
+ command: "analyze-metafile",
1107
+ metafile
1108
+ };
1109
+ if (color !== void 0) request.color = color;
1110
+ if (verbose !== void 0) request.verbose = verbose;
1111
+ sendRequest(refs, request, (error, response) => {
1112
+ if (error) return callback(new Error(error), null);
1113
+ callback(null, response.result);
1114
+ });
1115
+ };
1116
+ return {
1117
+ readFromStdout,
1118
+ afterClose,
1119
+ service: {
1120
+ buildOrContext,
1121
+ transform: transform2,
1122
+ formatMessages: formatMessages2,
1123
+ analyzeMetafile: analyzeMetafile2
1124
+ }
1125
+ };
1126
+ }
1127
+ function buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, isTTY2, defaultWD2, callback) {
1128
+ const details = createObjectStash();
1129
+ const isContext = callName === "context";
1130
+ const handleError = (e, pluginName) => {
1131
+ const flags = [];
1132
+ try {
1133
+ pushLogFlags(flags, options, {}, isTTY2, buildLogLevelDefault);
1134
+ } catch (e4) {
1135
+ }
1136
+ const message = extractErrorMessageV8(e, streamIn, details, void 0, pluginName);
1137
+ sendRequest(refs, { command: "error", flags, error: message }, () => {
1138
+ message.detail = details.load(message.detail);
1139
+ callback(failureErrorWithLog(isContext ? "Context failed" : "Build failed", [message], []), null);
1140
+ });
1141
+ };
1142
+ let plugins;
1143
+ if (typeof options === "object") {
1144
+ const value = options.plugins;
1145
+ if (value !== void 0) {
1146
+ if (!Array.isArray(value)) return handleError(new Error(`"plugins" must be an array`), "");
1147
+ plugins = value;
1148
+ }
1149
+ }
1150
+ if (plugins && plugins.length > 0) {
1151
+ if (streamIn.isSync) return handleError(new Error("Cannot use plugins in synchronous API calls"), "");
1152
+ handlePlugins(
1153
+ buildKey,
1154
+ sendRequest,
1155
+ sendResponse,
1156
+ refs,
1157
+ streamIn,
1158
+ requestCallbacks,
1159
+ options,
1160
+ plugins,
1161
+ details
1162
+ ).then(
1163
+ (result) => {
1164
+ if (!result.ok) return handleError(result.error, result.pluginName);
1165
+ try {
1166
+ buildOrContextContinue(result.requestPlugins, result.runOnEndCallbacks, result.scheduleOnDisposeCallbacks);
1167
+ } catch (e) {
1168
+ handleError(e, "");
1169
+ }
1170
+ },
1171
+ (e) => handleError(e, "")
1172
+ );
1173
+ return;
1174
+ }
1175
+ try {
1176
+ buildOrContextContinue(null, (result, done) => done([], []), () => {
1177
+ });
1178
+ } catch (e) {
1179
+ handleError(e, "");
1180
+ }
1181
+ function buildOrContextContinue(requestPlugins, runOnEndCallbacks, scheduleOnDisposeCallbacks) {
1182
+ const writeDefault = streamIn.hasFS;
1183
+ const {
1184
+ entries,
1185
+ flags,
1186
+ write,
1187
+ stdinContents,
1188
+ stdinResolveDir,
1189
+ absWorkingDir,
1190
+ nodePaths,
1191
+ mangleCache
1192
+ } = flagsForBuildOptions(callName, options, isTTY2, buildLogLevelDefault, writeDefault);
1193
+ if (write && !streamIn.hasFS) throw new Error(`The "write" option is unavailable in this environment`);
1194
+ const request = {
1195
+ command: "build",
1196
+ key: buildKey,
1197
+ entries,
1198
+ flags,
1199
+ write,
1200
+ stdinContents,
1201
+ stdinResolveDir,
1202
+ absWorkingDir: absWorkingDir || defaultWD2,
1203
+ nodePaths,
1204
+ context: isContext
1205
+ };
1206
+ if (requestPlugins) request.plugins = requestPlugins;
1207
+ if (mangleCache) request.mangleCache = mangleCache;
1208
+ const buildResponseToResult = (response, callback2) => {
1209
+ const result = {
1210
+ errors: replaceDetailsInMessages(response.errors, details),
1211
+ warnings: replaceDetailsInMessages(response.warnings, details),
1212
+ outputFiles: void 0,
1213
+ metafile: void 0,
1214
+ mangleCache: void 0
1215
+ };
1216
+ const originalErrors = result.errors.slice();
1217
+ const originalWarnings = result.warnings.slice();
1218
+ if (response.outputFiles) result.outputFiles = response.outputFiles.map(convertOutputFiles);
1219
+ if (response.metafile && response.metafile.length) result.metafile = parseJSON(response.metafile);
1220
+ if (response.mangleCache) result.mangleCache = response.mangleCache;
1221
+ if (response.writeToStdout !== void 0) console.log(decodeUTF8(response.writeToStdout).replace(/\n$/, ""));
1222
+ runOnEndCallbacks(result, (onEndErrors, onEndWarnings) => {
1223
+ if (originalErrors.length > 0 || onEndErrors.length > 0) {
1224
+ const error = failureErrorWithLog("Build failed", originalErrors.concat(onEndErrors), originalWarnings.concat(onEndWarnings));
1225
+ return callback2(error, null, onEndErrors, onEndWarnings);
1226
+ }
1227
+ callback2(null, result, onEndErrors, onEndWarnings);
1228
+ });
1229
+ };
1230
+ let latestResultPromise;
1231
+ let provideLatestResult;
1232
+ if (isContext)
1233
+ requestCallbacks["on-end"] = (id, request2) => new Promise((resolve2) => {
1234
+ buildResponseToResult(request2, (err, result, onEndErrors, onEndWarnings) => {
1235
+ const response = {
1236
+ errors: onEndErrors,
1237
+ warnings: onEndWarnings
1238
+ };
1239
+ if (provideLatestResult) provideLatestResult(err, result);
1240
+ latestResultPromise = void 0;
1241
+ provideLatestResult = void 0;
1242
+ sendResponse(id, response);
1243
+ resolve2();
1244
+ });
1245
+ });
1246
+ sendRequest(refs, request, (error, response) => {
1247
+ if (error) return callback(new Error(error), null);
1248
+ if (!isContext) {
1249
+ return buildResponseToResult(response, (err, res) => {
1250
+ scheduleOnDisposeCallbacks();
1251
+ return callback(err, res);
1252
+ });
1253
+ }
1254
+ if (response.errors.length > 0) {
1255
+ return callback(failureErrorWithLog("Context failed", response.errors, response.warnings), null);
1256
+ }
1257
+ let didDispose = false;
1258
+ const result = {
1259
+ rebuild: () => {
1260
+ if (!latestResultPromise) latestResultPromise = new Promise((resolve2, reject) => {
1261
+ let settlePromise;
1262
+ provideLatestResult = (err, result2) => {
1263
+ if (!settlePromise) settlePromise = () => err ? reject(err) : resolve2(result2);
1264
+ };
1265
+ const triggerAnotherBuild = () => {
1266
+ const request2 = {
1267
+ command: "rebuild",
1268
+ key: buildKey
1269
+ };
1270
+ sendRequest(refs, request2, (error2, response2) => {
1271
+ if (error2) {
1272
+ reject(new Error(error2));
1273
+ } else if (settlePromise) {
1274
+ settlePromise();
1275
+ } else {
1276
+ triggerAnotherBuild();
1277
+ }
1278
+ });
1279
+ };
1280
+ triggerAnotherBuild();
1281
+ });
1282
+ return latestResultPromise;
1283
+ },
1284
+ watch: (options2 = {}) => new Promise((resolve2, reject) => {
1285
+ if (!streamIn.hasFS) throw new Error(`Cannot use the "watch" API in this environment`);
1286
+ const keys = {};
1287
+ const delay = getFlag(options2, keys, "delay", mustBeInteger);
1288
+ checkForInvalidFlags(options2, keys, `in watch() call`);
1289
+ const request2 = {
1290
+ command: "watch",
1291
+ key: buildKey
1292
+ };
1293
+ if (delay) request2.delay = delay;
1294
+ sendRequest(refs, request2, (error2) => {
1295
+ if (error2) reject(new Error(error2));
1296
+ else resolve2(void 0);
1297
+ });
1298
+ }),
1299
+ serve: (options2 = {}) => new Promise((resolve2, reject) => {
1300
+ if (!streamIn.hasFS) throw new Error(`Cannot use the "serve" API in this environment`);
1301
+ const keys = {};
1302
+ const port = getFlag(options2, keys, "port", mustBeValidPortNumber);
1303
+ const host = getFlag(options2, keys, "host", mustBeString);
1304
+ const servedir = getFlag(options2, keys, "servedir", mustBeString);
1305
+ const keyfile = getFlag(options2, keys, "keyfile", mustBeString);
1306
+ const certfile = getFlag(options2, keys, "certfile", mustBeString);
1307
+ const fallback = getFlag(options2, keys, "fallback", mustBeString);
1308
+ const cors = getFlag(options2, keys, "cors", mustBeObject);
1309
+ const onRequest = getFlag(options2, keys, "onRequest", mustBeFunction);
1310
+ checkForInvalidFlags(options2, keys, `in serve() call`);
1311
+ const request2 = {
1312
+ command: "serve",
1313
+ key: buildKey,
1314
+ onRequest: !!onRequest
1315
+ };
1316
+ if (port !== void 0) request2.port = port;
1317
+ if (host !== void 0) request2.host = host;
1318
+ if (servedir !== void 0) request2.servedir = servedir;
1319
+ if (keyfile !== void 0) request2.keyfile = keyfile;
1320
+ if (certfile !== void 0) request2.certfile = certfile;
1321
+ if (fallback !== void 0) request2.fallback = fallback;
1322
+ if (cors) {
1323
+ const corsKeys = {};
1324
+ const origin = getFlag(cors, corsKeys, "origin", mustBeStringOrArrayOfStrings);
1325
+ checkForInvalidFlags(cors, corsKeys, `on "cors" object`);
1326
+ if (Array.isArray(origin)) request2.corsOrigin = origin;
1327
+ else if (origin !== void 0) request2.corsOrigin = [origin];
1328
+ }
1329
+ sendRequest(refs, request2, (error2, response2) => {
1330
+ if (error2) return reject(new Error(error2));
1331
+ if (onRequest) {
1332
+ requestCallbacks["serve-request"] = (id, request3) => {
1333
+ onRequest(request3.args);
1334
+ sendResponse(id, {});
1335
+ };
1336
+ }
1337
+ resolve2(response2);
1338
+ });
1339
+ }),
1340
+ cancel: () => new Promise((resolve2) => {
1341
+ if (didDispose) return resolve2();
1342
+ const request2 = {
1343
+ command: "cancel",
1344
+ key: buildKey
1345
+ };
1346
+ sendRequest(refs, request2, () => {
1347
+ resolve2();
1348
+ });
1349
+ }),
1350
+ dispose: () => new Promise((resolve2) => {
1351
+ if (didDispose) return resolve2();
1352
+ didDispose = true;
1353
+ const request2 = {
1354
+ command: "dispose",
1355
+ key: buildKey
1356
+ };
1357
+ sendRequest(refs, request2, () => {
1358
+ resolve2();
1359
+ scheduleOnDisposeCallbacks();
1360
+ refs.unref();
1361
+ });
1362
+ })
1363
+ };
1364
+ refs.ref();
1365
+ callback(null, result);
1366
+ });
1367
+ }
1368
+ }
1369
+ var handlePlugins = async (buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, initialOptions, plugins, details) => {
1370
+ let onStartCallbacks = [];
1371
+ let onEndCallbacks = [];
1372
+ let onResolveCallbacks = {};
1373
+ let onLoadCallbacks = {};
1374
+ let onDisposeCallbacks = [];
1375
+ let nextCallbackID = 0;
1376
+ let i = 0;
1377
+ let requestPlugins = [];
1378
+ let isSetupDone = false;
1379
+ plugins = [...plugins];
1380
+ for (let item of plugins) {
1381
+ let keys = {};
1382
+ if (typeof item !== "object") throw new Error(`Plugin at index ${i} must be an object`);
1383
+ const name = getFlag(item, keys, "name", mustBeString);
1384
+ if (typeof name !== "string" || name === "") throw new Error(`Plugin at index ${i} is missing a name`);
1385
+ try {
1386
+ let setup = getFlag(item, keys, "setup", mustBeFunction);
1387
+ if (typeof setup !== "function") throw new Error(`Plugin is missing a setup function`);
1388
+ checkForInvalidFlags(item, keys, `on plugin ${quote(name)}`);
1389
+ let plugin = {
1390
+ name,
1391
+ onStart: false,
1392
+ onEnd: false,
1393
+ onResolve: [],
1394
+ onLoad: []
1395
+ };
1396
+ i++;
1397
+ let resolve2 = (path3, options = {}) => {
1398
+ if (!isSetupDone) throw new Error('Cannot call "resolve" before plugin setup has completed');
1399
+ if (typeof path3 !== "string") throw new Error(`The path to resolve must be a string`);
1400
+ let keys2 = /* @__PURE__ */ Object.create(null);
1401
+ let pluginName = getFlag(options, keys2, "pluginName", mustBeString);
1402
+ let importer = getFlag(options, keys2, "importer", mustBeString);
1403
+ let namespace = getFlag(options, keys2, "namespace", mustBeString);
1404
+ let resolveDir = getFlag(options, keys2, "resolveDir", mustBeString);
1405
+ let kind = getFlag(options, keys2, "kind", mustBeString);
1406
+ let pluginData = getFlag(options, keys2, "pluginData", canBeAnything);
1407
+ let importAttributes = getFlag(options, keys2, "with", mustBeObject);
1408
+ checkForInvalidFlags(options, keys2, "in resolve() call");
1409
+ return new Promise((resolve22, reject) => {
1410
+ const request = {
1411
+ command: "resolve",
1412
+ path: path3,
1413
+ key: buildKey,
1414
+ pluginName: name
1415
+ };
1416
+ if (pluginName != null) request.pluginName = pluginName;
1417
+ if (importer != null) request.importer = importer;
1418
+ if (namespace != null) request.namespace = namespace;
1419
+ if (resolveDir != null) request.resolveDir = resolveDir;
1420
+ if (kind != null) request.kind = kind;
1421
+ else throw new Error(`Must specify "kind" when calling "resolve"`);
1422
+ if (pluginData != null) request.pluginData = details.store(pluginData);
1423
+ if (importAttributes != null) request.with = sanitizeStringMap(importAttributes, "with");
1424
+ sendRequest(refs, request, (error, response) => {
1425
+ if (error !== null) reject(new Error(error));
1426
+ else resolve22({
1427
+ errors: replaceDetailsInMessages(response.errors, details),
1428
+ warnings: replaceDetailsInMessages(response.warnings, details),
1429
+ path: response.path,
1430
+ external: response.external,
1431
+ sideEffects: response.sideEffects,
1432
+ namespace: response.namespace,
1433
+ suffix: response.suffix,
1434
+ pluginData: details.load(response.pluginData)
1435
+ });
1436
+ });
1437
+ });
1438
+ };
1439
+ let promise = setup({
1440
+ initialOptions,
1441
+ resolve: resolve2,
1442
+ onStart(callback) {
1443
+ let registeredText = `This error came from the "onStart" callback registered here:`;
1444
+ let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onStart");
1445
+ onStartCallbacks.push({ name, callback, note: registeredNote });
1446
+ plugin.onStart = true;
1447
+ },
1448
+ onEnd(callback) {
1449
+ let registeredText = `This error came from the "onEnd" callback registered here:`;
1450
+ let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onEnd");
1451
+ onEndCallbacks.push({ name, callback, note: registeredNote });
1452
+ plugin.onEnd = true;
1453
+ },
1454
+ onResolve(options, callback) {
1455
+ let registeredText = `This error came from the "onResolve" callback registered here:`;
1456
+ let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onResolve");
1457
+ let keys2 = {};
1458
+ let filter = getFlag(options, keys2, "filter", mustBeRegExp);
1459
+ let namespace = getFlag(options, keys2, "namespace", mustBeString);
1460
+ checkForInvalidFlags(options, keys2, `in onResolve() call for plugin ${quote(name)}`);
1461
+ if (filter == null) throw new Error(`onResolve() call is missing a filter`);
1462
+ let id = nextCallbackID++;
1463
+ onResolveCallbacks[id] = { name, callback, note: registeredNote };
1464
+ plugin.onResolve.push({ id, filter: jsRegExpToGoRegExp(filter), namespace: namespace || "" });
1465
+ },
1466
+ onLoad(options, callback) {
1467
+ let registeredText = `This error came from the "onLoad" callback registered here:`;
1468
+ let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onLoad");
1469
+ let keys2 = {};
1470
+ let filter = getFlag(options, keys2, "filter", mustBeRegExp);
1471
+ let namespace = getFlag(options, keys2, "namespace", mustBeString);
1472
+ checkForInvalidFlags(options, keys2, `in onLoad() call for plugin ${quote(name)}`);
1473
+ if (filter == null) throw new Error(`onLoad() call is missing a filter`);
1474
+ let id = nextCallbackID++;
1475
+ onLoadCallbacks[id] = { name, callback, note: registeredNote };
1476
+ plugin.onLoad.push({ id, filter: jsRegExpToGoRegExp(filter), namespace: namespace || "" });
1477
+ },
1478
+ onDispose(callback) {
1479
+ onDisposeCallbacks.push(callback);
1480
+ },
1481
+ esbuild: streamIn.esbuild
1482
+ });
1483
+ if (promise) await promise;
1484
+ requestPlugins.push(plugin);
1485
+ } catch (e) {
1486
+ return { ok: false, error: e, pluginName: name };
1487
+ }
1488
+ }
1489
+ requestCallbacks["on-start"] = async (id, request) => {
1490
+ details.clear();
1491
+ let response = { errors: [], warnings: [] };
1492
+ await Promise.all(onStartCallbacks.map(async ({ name, callback, note }) => {
1493
+ try {
1494
+ let result = await callback();
1495
+ if (result != null) {
1496
+ if (typeof result !== "object") throw new Error(`Expected onStart() callback in plugin ${quote(name)} to return an object`);
1497
+ let keys = {};
1498
+ let errors = getFlag(result, keys, "errors", mustBeArray);
1499
+ let warnings = getFlag(result, keys, "warnings", mustBeArray);
1500
+ checkForInvalidFlags(result, keys, `from onStart() callback in plugin ${quote(name)}`);
1501
+ if (errors != null) response.errors.push(...sanitizeMessages(errors, "errors", details, name, void 0));
1502
+ if (warnings != null) response.warnings.push(...sanitizeMessages(warnings, "warnings", details, name, void 0));
1503
+ }
1504
+ } catch (e) {
1505
+ response.errors.push(extractErrorMessageV8(e, streamIn, details, note && note(), name));
1506
+ }
1507
+ }));
1508
+ sendResponse(id, response);
1509
+ };
1510
+ requestCallbacks["on-resolve"] = async (id, request) => {
1511
+ let response = {}, name = "", callback, note;
1512
+ for (let id2 of request.ids) {
1513
+ try {
1514
+ ({ name, callback, note } = onResolveCallbacks[id2]);
1515
+ let result = await callback({
1516
+ path: request.path,
1517
+ importer: request.importer,
1518
+ namespace: request.namespace,
1519
+ resolveDir: request.resolveDir,
1520
+ kind: request.kind,
1521
+ pluginData: details.load(request.pluginData),
1522
+ with: request.with
1523
+ });
1524
+ if (result != null) {
1525
+ if (typeof result !== "object") throw new Error(`Expected onResolve() callback in plugin ${quote(name)} to return an object`);
1526
+ let keys = {};
1527
+ let pluginName = getFlag(result, keys, "pluginName", mustBeString);
1528
+ let path3 = getFlag(result, keys, "path", mustBeString);
1529
+ let namespace = getFlag(result, keys, "namespace", mustBeString);
1530
+ let suffix = getFlag(result, keys, "suffix", mustBeString);
1531
+ let external = getFlag(result, keys, "external", mustBeBoolean);
1532
+ let sideEffects = getFlag(result, keys, "sideEffects", mustBeBoolean);
1533
+ let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
1534
+ let errors = getFlag(result, keys, "errors", mustBeArray);
1535
+ let warnings = getFlag(result, keys, "warnings", mustBeArray);
1536
+ let watchFiles = getFlag(result, keys, "watchFiles", mustBeArrayOfStrings);
1537
+ let watchDirs = getFlag(result, keys, "watchDirs", mustBeArrayOfStrings);
1538
+ checkForInvalidFlags(result, keys, `from onResolve() callback in plugin ${quote(name)}`);
1539
+ response.id = id2;
1540
+ if (pluginName != null) response.pluginName = pluginName;
1541
+ if (path3 != null) response.path = path3;
1542
+ if (namespace != null) response.namespace = namespace;
1543
+ if (suffix != null) response.suffix = suffix;
1544
+ if (external != null) response.external = external;
1545
+ if (sideEffects != null) response.sideEffects = sideEffects;
1546
+ if (pluginData != null) response.pluginData = details.store(pluginData);
1547
+ if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0);
1548
+ if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
1549
+ if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
1550
+ if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
1551
+ break;
1552
+ }
1553
+ } catch (e) {
1554
+ response = { id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] };
1555
+ break;
1556
+ }
1557
+ }
1558
+ sendResponse(id, response);
1559
+ };
1560
+ requestCallbacks["on-load"] = async (id, request) => {
1561
+ let response = {}, name = "", callback, note;
1562
+ for (let id2 of request.ids) {
1563
+ try {
1564
+ ({ name, callback, note } = onLoadCallbacks[id2]);
1565
+ let result = await callback({
1566
+ path: request.path,
1567
+ namespace: request.namespace,
1568
+ suffix: request.suffix,
1569
+ pluginData: details.load(request.pluginData),
1570
+ with: request.with
1571
+ });
1572
+ if (result != null) {
1573
+ if (typeof result !== "object") throw new Error(`Expected onLoad() callback in plugin ${quote(name)} to return an object`);
1574
+ let keys = {};
1575
+ let pluginName = getFlag(result, keys, "pluginName", mustBeString);
1576
+ let contents = getFlag(result, keys, "contents", mustBeStringOrUint8Array);
1577
+ let resolveDir = getFlag(result, keys, "resolveDir", mustBeString);
1578
+ let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
1579
+ let loader = getFlag(result, keys, "loader", mustBeString);
1580
+ let errors = getFlag(result, keys, "errors", mustBeArray);
1581
+ let warnings = getFlag(result, keys, "warnings", mustBeArray);
1582
+ let watchFiles = getFlag(result, keys, "watchFiles", mustBeArrayOfStrings);
1583
+ let watchDirs = getFlag(result, keys, "watchDirs", mustBeArrayOfStrings);
1584
+ checkForInvalidFlags(result, keys, `from onLoad() callback in plugin ${quote(name)}`);
1585
+ response.id = id2;
1586
+ if (pluginName != null) response.pluginName = pluginName;
1587
+ if (contents instanceof Uint8Array) response.contents = contents;
1588
+ else if (contents != null) response.contents = encodeUTF8(contents);
1589
+ if (resolveDir != null) response.resolveDir = resolveDir;
1590
+ if (pluginData != null) response.pluginData = details.store(pluginData);
1591
+ if (loader != null) response.loader = loader;
1592
+ if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0);
1593
+ if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
1594
+ if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
1595
+ if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
1596
+ break;
1597
+ }
1598
+ } catch (e) {
1599
+ response = { id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] };
1600
+ break;
1601
+ }
1602
+ }
1603
+ sendResponse(id, response);
1604
+ };
1605
+ let runOnEndCallbacks = (result, done) => done([], []);
1606
+ if (onEndCallbacks.length > 0) {
1607
+ runOnEndCallbacks = (result, done) => {
1608
+ (async () => {
1609
+ const onEndErrors = [];
1610
+ const onEndWarnings = [];
1611
+ for (const { name, callback, note } of onEndCallbacks) {
1612
+ let newErrors;
1613
+ let newWarnings;
1614
+ try {
1615
+ const value = await callback(result);
1616
+ if (value != null) {
1617
+ if (typeof value !== "object") throw new Error(`Expected onEnd() callback in plugin ${quote(name)} to return an object`);
1618
+ let keys = {};
1619
+ let errors = getFlag(value, keys, "errors", mustBeArray);
1620
+ let warnings = getFlag(value, keys, "warnings", mustBeArray);
1621
+ checkForInvalidFlags(value, keys, `from onEnd() callback in plugin ${quote(name)}`);
1622
+ if (errors != null) newErrors = sanitizeMessages(errors, "errors", details, name, void 0);
1623
+ if (warnings != null) newWarnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
1624
+ }
1625
+ } catch (e) {
1626
+ newErrors = [extractErrorMessageV8(e, streamIn, details, note && note(), name)];
1627
+ }
1628
+ if (newErrors) {
1629
+ onEndErrors.push(...newErrors);
1630
+ try {
1631
+ result.errors.push(...newErrors);
1632
+ } catch (e5) {
1633
+ }
1634
+ }
1635
+ if (newWarnings) {
1636
+ onEndWarnings.push(...newWarnings);
1637
+ try {
1638
+ result.warnings.push(...newWarnings);
1639
+ } catch (e6) {
1640
+ }
1641
+ }
1642
+ }
1643
+ done(onEndErrors, onEndWarnings);
1644
+ })();
1645
+ };
1646
+ }
1647
+ let scheduleOnDisposeCallbacks = () => {
1648
+ for (const cb of onDisposeCallbacks) {
1649
+ setTimeout(() => cb(), 0);
1650
+ }
1651
+ };
1652
+ isSetupDone = true;
1653
+ return {
1654
+ ok: true,
1655
+ requestPlugins,
1656
+ runOnEndCallbacks,
1657
+ scheduleOnDisposeCallbacks
1658
+ };
1659
+ };
1660
+ function createObjectStash() {
1661
+ const map = /* @__PURE__ */ new Map();
1662
+ let nextID = 0;
1663
+ return {
1664
+ clear() {
1665
+ map.clear();
1666
+ },
1667
+ load(id) {
1668
+ return map.get(id);
1669
+ },
1670
+ store(value) {
1671
+ if (value === void 0) return -1;
1672
+ const id = nextID++;
1673
+ map.set(id, value);
1674
+ return id;
1675
+ }
1676
+ };
1677
+ }
1678
+ function extractCallerV8(e, streamIn, ident) {
1679
+ let note;
1680
+ let tried = false;
1681
+ return () => {
1682
+ if (tried) return note;
1683
+ tried = true;
1684
+ try {
1685
+ let lines = (e.stack + "").split("\n");
1686
+ lines.splice(1, 1);
1687
+ let location2 = parseStackLinesV8(streamIn, lines, ident);
1688
+ if (location2) {
1689
+ note = { text: e.message, location: location2 };
1690
+ return note;
1691
+ }
1692
+ } catch (e7) {
1693
+ }
1694
+ };
1695
+ }
1696
+ function extractErrorMessageV8(e, streamIn, stash, note, pluginName) {
1697
+ let text = "Internal error";
1698
+ let location2 = null;
1699
+ try {
1700
+ text = (e && e.message || e) + "";
1701
+ } catch (e8) {
1702
+ }
1703
+ try {
1704
+ location2 = parseStackLinesV8(streamIn, (e.stack + "").split("\n"), "");
1705
+ } catch (e9) {
1706
+ }
1707
+ return { id: "", pluginName, text, location: location2, notes: note ? [note] : [], detail: stash ? stash.store(e) : -1 };
1708
+ }
1709
+ function parseStackLinesV8(streamIn, lines, ident) {
1710
+ let at = " at ";
1711
+ if (streamIn.readFileSync && !lines[0].startsWith(at) && lines[1].startsWith(at)) {
1712
+ for (let i = 1; i < lines.length; i++) {
1713
+ let line = lines[i];
1714
+ if (!line.startsWith(at)) continue;
1715
+ line = line.slice(at.length);
1716
+ while (true) {
1717
+ let match = /^(?:new |async )?\S+ \((.*)\)$/.exec(line);
1718
+ if (match) {
1719
+ line = match[1];
1720
+ continue;
1721
+ }
1722
+ match = /^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(line);
1723
+ if (match) {
1724
+ line = match[1];
1725
+ continue;
1726
+ }
1727
+ match = /^(\S+):(\d+):(\d+)$/.exec(line);
1728
+ if (match) {
1729
+ let contents;
1730
+ try {
1731
+ contents = streamIn.readFileSync(match[1], "utf8");
1732
+ } catch (e10) {
1733
+ break;
1734
+ }
1735
+ let lineText = contents.split(/\r\n|\r|\n|\u2028|\u2029/)[+match[2] - 1] || "";
1736
+ let column = +match[3] - 1;
1737
+ let length = lineText.slice(column, column + ident.length) === ident ? ident.length : 0;
1738
+ return {
1739
+ file: match[1],
1740
+ namespace: "file",
1741
+ line: +match[2],
1742
+ column: encodeUTF8(lineText.slice(0, column)).length,
1743
+ length: encodeUTF8(lineText.slice(column, column + length)).length,
1744
+ lineText: lineText + "\n" + lines.slice(1).join("\n"),
1745
+ suggestion: ""
1746
+ };
1747
+ }
1748
+ break;
1749
+ }
1750
+ }
1751
+ }
1752
+ return null;
1753
+ }
1754
+ function failureErrorWithLog(text, errors, warnings) {
1755
+ let limit = 5;
1756
+ text += errors.length < 1 ? "" : ` with ${errors.length} error${errors.length < 2 ? "" : "s"}:` + errors.slice(0, limit + 1).map((e, i) => {
1757
+ if (i === limit) return "\n...";
1758
+ if (!e.location) return `
1759
+ error: ${e.text}`;
1760
+ let { file, line, column } = e.location;
1761
+ let pluginText = e.pluginName ? `[plugin: ${e.pluginName}] ` : "";
1762
+ return `
1763
+ ${file}:${line}:${column}: ERROR: ${pluginText}${e.text}`;
1764
+ }).join("");
1765
+ let error = new Error(text);
1766
+ for (const [key, value] of [["errors", errors], ["warnings", warnings]]) {
1767
+ Object.defineProperty(error, key, {
1768
+ configurable: true,
1769
+ enumerable: true,
1770
+ get: () => value,
1771
+ set: (value2) => Object.defineProperty(error, key, {
1772
+ configurable: true,
1773
+ enumerable: true,
1774
+ value: value2
1775
+ })
1776
+ });
1777
+ }
1778
+ return error;
1779
+ }
1780
+ function replaceDetailsInMessages(messages, stash) {
1781
+ for (const message of messages) {
1782
+ message.detail = stash.load(message.detail);
1783
+ }
1784
+ return messages;
1785
+ }
1786
+ function sanitizeLocation(location2, where, terminalWidth) {
1787
+ if (location2 == null) return null;
1788
+ let keys = {};
1789
+ let file = getFlag(location2, keys, "file", mustBeString);
1790
+ let namespace = getFlag(location2, keys, "namespace", mustBeString);
1791
+ let line = getFlag(location2, keys, "line", mustBeInteger);
1792
+ let column = getFlag(location2, keys, "column", mustBeInteger);
1793
+ let length = getFlag(location2, keys, "length", mustBeInteger);
1794
+ let lineText = getFlag(location2, keys, "lineText", mustBeString);
1795
+ let suggestion = getFlag(location2, keys, "suggestion", mustBeString);
1796
+ checkForInvalidFlags(location2, keys, where);
1797
+ if (lineText) {
1798
+ const relevantASCII = lineText.slice(
1799
+ 0,
1800
+ (column && column > 0 ? column : 0) + (length && length > 0 ? length : 0) + (terminalWidth && terminalWidth > 0 ? terminalWidth : 80)
1801
+ );
1802
+ if (!/[\x7F-\uFFFF]/.test(relevantASCII) && !/\n/.test(lineText)) {
1803
+ lineText = relevantASCII;
1804
+ }
1805
+ }
1806
+ return {
1807
+ file: file || "",
1808
+ namespace: namespace || "",
1809
+ line: line || 0,
1810
+ column: column || 0,
1811
+ length: length || 0,
1812
+ lineText: lineText || "",
1813
+ suggestion: suggestion || ""
1814
+ };
1815
+ }
1816
+ function sanitizeMessages(messages, property, stash, fallbackPluginName, terminalWidth) {
1817
+ let messagesClone = [];
1818
+ let index = 0;
1819
+ for (const message of messages) {
1820
+ let keys = {};
1821
+ let id = getFlag(message, keys, "id", mustBeString);
1822
+ let pluginName = getFlag(message, keys, "pluginName", mustBeString);
1823
+ let text = getFlag(message, keys, "text", mustBeString);
1824
+ let location2 = getFlag(message, keys, "location", mustBeObjectOrNull);
1825
+ let notes = getFlag(message, keys, "notes", mustBeArray);
1826
+ let detail2 = getFlag(message, keys, "detail", canBeAnything);
1827
+ let where = `in element ${index} of "${property}"`;
1828
+ checkForInvalidFlags(message, keys, where);
1829
+ let notesClone = [];
1830
+ if (notes) {
1831
+ for (const note of notes) {
1832
+ let noteKeys = {};
1833
+ let noteText = getFlag(note, noteKeys, "text", mustBeString);
1834
+ let noteLocation = getFlag(note, noteKeys, "location", mustBeObjectOrNull);
1835
+ checkForInvalidFlags(note, noteKeys, where);
1836
+ notesClone.push({
1837
+ text: noteText || "",
1838
+ location: sanitizeLocation(noteLocation, where, terminalWidth)
1839
+ });
1840
+ }
1841
+ }
1842
+ messagesClone.push({
1843
+ id: id || "",
1844
+ pluginName: pluginName || fallbackPluginName,
1845
+ text: text || "",
1846
+ location: sanitizeLocation(location2, where, terminalWidth),
1847
+ notes: notesClone,
1848
+ detail: stash ? stash.store(detail2) : -1
1849
+ });
1850
+ index++;
1851
+ }
1852
+ return messagesClone;
1853
+ }
1854
+ function sanitizeStringArray(values, property) {
1855
+ const result = [];
1856
+ for (const value of values) {
1857
+ if (typeof value !== "string") throw new Error(`${quote(property)} must be an array of strings`);
1858
+ result.push(value);
1859
+ }
1860
+ return result;
1861
+ }
1862
+ function sanitizeStringMap(map, property) {
1863
+ const result = /* @__PURE__ */ Object.create(null);
1864
+ for (const key in map) {
1865
+ const value = map[key];
1866
+ if (typeof value !== "string") throw new Error(`key ${quote(key)} in object ${quote(property)} must be a string`);
1867
+ result[key] = value;
1868
+ }
1869
+ return result;
1870
+ }
1871
+ function convertOutputFiles({ path: path3, contents, hash }) {
1872
+ let text = null;
1873
+ return {
1874
+ path: path3,
1875
+ contents,
1876
+ hash,
1877
+ get text() {
1878
+ const binary = this.contents;
1879
+ if (text === null || binary !== contents) {
1880
+ contents = binary;
1881
+ text = decodeUTF8(binary);
1882
+ }
1883
+ return text;
1884
+ }
1885
+ };
1886
+ }
1887
+ function jsRegExpToGoRegExp(regexp) {
1888
+ let result = regexp.source;
1889
+ if (regexp.flags) result = `(?${regexp.flags})${result}`;
1890
+ return result;
1891
+ }
1892
+ function parseJSON(bytes) {
1893
+ let text;
1894
+ try {
1895
+ text = decodeUTF8(bytes);
1896
+ } catch (e11) {
1897
+ return JSON_parse(bytes);
1898
+ }
1899
+ return JSON.parse(text);
1900
+ }
1901
+ var fs = __require("fs");
1902
+ var os = __require("os");
1903
+ var path = __require("path");
1904
+ var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH;
1905
+ var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild";
1906
+ var packageDarwin_arm64 = "@esbuild/darwin-arm64";
1907
+ var packageDarwin_x64 = "@esbuild/darwin-x64";
1908
+ var knownWindowsPackages = {
1909
+ "win32 arm64 LE": "@esbuild/win32-arm64",
1910
+ "win32 ia32 LE": "@esbuild/win32-ia32",
1911
+ "win32 x64 LE": "@esbuild/win32-x64"
1912
+ };
1913
+ var knownUnixlikePackages = {
1914
+ "aix ppc64 BE": "@esbuild/aix-ppc64",
1915
+ "android arm64 LE": "@esbuild/android-arm64",
1916
+ "darwin arm64 LE": "@esbuild/darwin-arm64",
1917
+ "darwin x64 LE": "@esbuild/darwin-x64",
1918
+ "freebsd arm64 LE": "@esbuild/freebsd-arm64",
1919
+ "freebsd x64 LE": "@esbuild/freebsd-x64",
1920
+ "linux arm LE": "@esbuild/linux-arm",
1921
+ "linux arm64 LE": "@esbuild/linux-arm64",
1922
+ "linux ia32 LE": "@esbuild/linux-ia32",
1923
+ "linux mips64el LE": "@esbuild/linux-mips64el",
1924
+ "linux ppc64 LE": "@esbuild/linux-ppc64",
1925
+ "linux riscv64 LE": "@esbuild/linux-riscv64",
1926
+ "linux s390x BE": "@esbuild/linux-s390x",
1927
+ "linux x64 LE": "@esbuild/linux-x64",
1928
+ "linux loong64 LE": "@esbuild/linux-loong64",
1929
+ "netbsd arm64 LE": "@esbuild/netbsd-arm64",
1930
+ "netbsd x64 LE": "@esbuild/netbsd-x64",
1931
+ "openbsd arm64 LE": "@esbuild/openbsd-arm64",
1932
+ "openbsd x64 LE": "@esbuild/openbsd-x64",
1933
+ "sunos x64 LE": "@esbuild/sunos-x64"
1934
+ };
1935
+ var knownWebAssemblyFallbackPackages = {
1936
+ "android arm LE": "@esbuild/android-arm",
1937
+ "android x64 LE": "@esbuild/android-x64",
1938
+ "openharmony arm64 LE": "@esbuild/openharmony-arm64"
1939
+ };
1940
+ function pkgAndSubpathForCurrentPlatform() {
1941
+ let pkg;
1942
+ let subpath;
1943
+ let isWASM = false;
1944
+ let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`;
1945
+ if (platformKey in knownWindowsPackages) {
1946
+ pkg = knownWindowsPackages[platformKey];
1947
+ subpath = "esbuild.exe";
1948
+ } else if (platformKey in knownUnixlikePackages) {
1949
+ pkg = knownUnixlikePackages[platformKey];
1950
+ subpath = "bin/esbuild";
1951
+ } else if (platformKey in knownWebAssemblyFallbackPackages) {
1952
+ pkg = knownWebAssemblyFallbackPackages[platformKey];
1953
+ subpath = "bin/esbuild";
1954
+ isWASM = true;
1955
+ } else {
1956
+ throw new Error(`Unsupported platform: ${platformKey}`);
1957
+ }
1958
+ return { pkg, subpath, isWASM };
1959
+ }
1960
+ function pkgForSomeOtherPlatform() {
1961
+ const libMainJS = __require.resolve("esbuild");
1962
+ const nodeModulesDirectory = path.dirname(path.dirname(path.dirname(libMainJS)));
1963
+ if (path.basename(nodeModulesDirectory) === "node_modules") {
1964
+ for (const unixKey in knownUnixlikePackages) {
1965
+ try {
1966
+ const pkg = knownUnixlikePackages[unixKey];
1967
+ if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg;
1968
+ } catch (e12) {
1969
+ }
1970
+ }
1971
+ for (const windowsKey in knownWindowsPackages) {
1972
+ try {
1973
+ const pkg = knownWindowsPackages[windowsKey];
1974
+ if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg;
1975
+ } catch (e13) {
1976
+ }
1977
+ }
1978
+ }
1979
+ return null;
1980
+ }
1981
+ function downloadedBinPath(pkg, subpath) {
1982
+ const esbuildLibDir = path.dirname(__require.resolve("esbuild"));
1983
+ return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`);
1984
+ }
1985
+ function generateBinPath() {
1986
+ if (isValidBinaryPath(ESBUILD_BINARY_PATH)) {
1987
+ if (!fs.existsSync(ESBUILD_BINARY_PATH)) {
1988
+ console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`);
1989
+ } else {
1990
+ return { binPath: ESBUILD_BINARY_PATH, isWASM: false };
1991
+ }
1992
+ }
1993
+ const { pkg, subpath, isWASM } = pkgAndSubpathForCurrentPlatform();
1994
+ let binPath;
1995
+ try {
1996
+ binPath = __require.resolve(`${pkg}/${subpath}`);
1997
+ } catch (e) {
1998
+ binPath = downloadedBinPath(pkg, subpath);
1999
+ if (!fs.existsSync(binPath)) {
2000
+ try {
2001
+ __require.resolve(pkg);
2002
+ } catch (e14) {
2003
+ const otherPkg = pkgForSomeOtherPlatform();
2004
+ if (otherPkg) {
2005
+ let suggestions = `
2006
+ Specifically the "${otherPkg}" package is present but this platform
2007
+ needs the "${pkg}" package instead. People often get into this
2008
+ situation by installing esbuild on Windows or macOS and copying "node_modules"
2009
+ into a Docker image that runs Linux, or by copying "node_modules" between
2010
+ Windows and WSL environments.
2011
+
2012
+ If you are installing with npm, you can try not copying the "node_modules"
2013
+ directory when you copy the files over, and running "npm ci" or "npm install"
2014
+ on the destination platform after the copy. Or you could consider using yarn
2015
+ instead of npm which has built-in support for installing a package on multiple
2016
+ platforms simultaneously.
2017
+
2018
+ If you are installing with yarn, you can try listing both this platform and the
2019
+ other platform in your ".yarnrc.yml" file using the "supportedArchitectures"
2020
+ feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
2021
+ Keep in mind that this means multiple copies of esbuild will be present.
2022
+ `;
2023
+ if (pkg === packageDarwin_x64 && otherPkg === packageDarwin_arm64 || pkg === packageDarwin_arm64 && otherPkg === packageDarwin_x64) {
2024
+ suggestions = `
2025
+ Specifically the "${otherPkg}" package is present but this platform
2026
+ needs the "${pkg}" package instead. People often get into this
2027
+ situation by installing esbuild with npm running inside of Rosetta 2 and then
2028
+ trying to use it with node running outside of Rosetta 2, or vice versa (Rosetta
2029
+ 2 is Apple's on-the-fly x86_64-to-arm64 translation service).
2030
+
2031
+ If you are installing with npm, you can try ensuring that both npm and node are
2032
+ not running under Rosetta 2 and then reinstalling esbuild. This likely involves
2033
+ changing how you installed npm and/or node. For example, installing node with
2034
+ the universal installer here should work: https://nodejs.org/en/download/. Or
2035
+ you could consider using yarn instead of npm which has built-in support for
2036
+ installing a package on multiple platforms simultaneously.
2037
+
2038
+ If you are installing with yarn, you can try listing both "arm64" and "x64"
2039
+ in your ".yarnrc.yml" file using the "supportedArchitectures" feature:
2040
+ https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
2041
+ Keep in mind that this means multiple copies of esbuild will be present.
2042
+ `;
2043
+ }
2044
+ throw new Error(`
2045
+ You installed esbuild for another platform than the one you're currently using.
2046
+ This won't work because esbuild is written with native code and needs to
2047
+ install a platform-specific binary executable.
2048
+ ${suggestions}
2049
+ Another alternative is to use the "esbuild-wasm" package instead, which works
2050
+ the same way on all platforms. But it comes with a heavy performance cost and
2051
+ can sometimes be 10x slower than the "esbuild" package, so you may also not
2052
+ want to do that.
2053
+ `);
2054
+ }
2055
+ throw new Error(`The package "${pkg}" could not be found, and is needed by esbuild.
2056
+
2057
+ If you are installing esbuild with npm, make sure that you don't specify the
2058
+ "--no-optional" or "--omit=optional" flags. The "optionalDependencies" feature
2059
+ of "package.json" is used by esbuild to install the correct binary executable
2060
+ for your current platform.`);
2061
+ }
2062
+ throw e;
2063
+ }
2064
+ }
2065
+ if (/\.zip\//.test(binPath)) {
2066
+ let pnpapi;
2067
+ try {
2068
+ pnpapi = __require("pnpapi");
2069
+ } catch (e) {
2070
+ }
2071
+ if (pnpapi) {
2072
+ const root = pnpapi.getPackageInformation(pnpapi.topLevel).packageLocation;
2073
+ const binTargetPath = path.join(
2074
+ root,
2075
+ "node_modules",
2076
+ ".cache",
2077
+ "esbuild",
2078
+ `pnpapi-${pkg.replace("/", "-")}-${"0.27.7"}-${path.basename(subpath)}`
2079
+ );
2080
+ if (!fs.existsSync(binTargetPath)) {
2081
+ fs.mkdirSync(path.dirname(binTargetPath), { recursive: true });
2082
+ fs.copyFileSync(binPath, binTargetPath);
2083
+ fs.chmodSync(binTargetPath, 493);
2084
+ }
2085
+ return { binPath: binTargetPath, isWASM };
2086
+ }
2087
+ }
2088
+ return { binPath, isWASM };
2089
+ }
2090
+ var child_process = __require("child_process");
2091
+ var crypto = __require("crypto");
2092
+ var path2 = __require("path");
2093
+ var fs2 = __require("fs");
2094
+ var os2 = __require("os");
2095
+ var tty = __require("tty");
2096
+ var worker_threads;
2097
+ if (process.env.ESBUILD_WORKER_THREADS !== "0") {
2098
+ try {
2099
+ worker_threads = __require("worker_threads");
2100
+ } catch (e15) {
2101
+ }
2102
+ let [major, minor] = process.versions.node.split(".");
2103
+ if (
2104
+ // <v12.17.0 does not work
2105
+ +major < 12 || +major === 12 && +minor < 17 || +major === 13 && +minor < 13
2106
+ ) {
2107
+ worker_threads = void 0;
2108
+ }
2109
+ }
2110
+ var _a;
2111
+ var isInternalWorkerThread = ((_a = worker_threads == null ? void 0 : worker_threads.workerData) == null ? void 0 : _a.esbuildVersion) === "0.27.7";
2112
+ var esbuildCommandAndArgs = () => {
2113
+ if ((!ESBUILD_BINARY_PATH || false) && (path2.basename(__filename) !== "main.js" || path2.basename(__dirname) !== "lib")) {
2114
+ throw new Error(
2115
+ `The esbuild JavaScript API cannot be bundled. Please mark the "esbuild" package as external so it's not included in the bundle.
2116
+
2117
+ 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.`
2118
+ );
2119
+ }
2120
+ if (false) {
2121
+ return ["node", [path2.join(__dirname, "..", "bin", "esbuild")]];
2122
+ } else {
2123
+ const { binPath, isWASM } = generateBinPath();
2124
+ if (isWASM) {
2125
+ return ["node", [binPath]];
2126
+ } else {
2127
+ return [binPath, []];
2128
+ }
2129
+ }
2130
+ };
2131
+ var isTTY = () => tty.isatty(2);
2132
+ var fsSync = {
2133
+ readFile(tempFile, callback) {
2134
+ try {
2135
+ let contents = fs2.readFileSync(tempFile, "utf8");
2136
+ try {
2137
+ fs2.unlinkSync(tempFile);
2138
+ } catch (e16) {
2139
+ }
2140
+ callback(null, contents);
2141
+ } catch (err) {
2142
+ callback(err, null);
2143
+ }
2144
+ },
2145
+ writeFile(contents, callback) {
2146
+ try {
2147
+ let tempFile = randomFileName();
2148
+ fs2.writeFileSync(tempFile, contents);
2149
+ callback(tempFile);
2150
+ } catch (e17) {
2151
+ callback(null);
2152
+ }
2153
+ }
2154
+ };
2155
+ var fsAsync = {
2156
+ readFile(tempFile, callback) {
2157
+ try {
2158
+ fs2.readFile(tempFile, "utf8", (err, contents) => {
2159
+ try {
2160
+ fs2.unlink(tempFile, () => callback(err, contents));
2161
+ } catch (e18) {
2162
+ callback(err, contents);
2163
+ }
2164
+ });
2165
+ } catch (err) {
2166
+ callback(err, null);
2167
+ }
2168
+ },
2169
+ writeFile(contents, callback) {
2170
+ try {
2171
+ let tempFile = randomFileName();
2172
+ fs2.writeFile(tempFile, contents, (err) => err !== null ? callback(null) : callback(tempFile));
2173
+ } catch (e19) {
2174
+ callback(null);
2175
+ }
2176
+ }
2177
+ };
2178
+ var version = "0.27.7";
2179
+ var build = (options) => ensureServiceIsRunning().build(options);
2180
+ var context = (buildOptions) => ensureServiceIsRunning().context(buildOptions);
2181
+ var transform = (input, options) => ensureServiceIsRunning().transform(input, options);
2182
+ var formatMessages = (messages, options) => ensureServiceIsRunning().formatMessages(messages, options);
2183
+ var analyzeMetafile = (messages, options) => ensureServiceIsRunning().analyzeMetafile(messages, options);
2184
+ var buildSync = (options) => {
2185
+ if (worker_threads && !isInternalWorkerThread) {
2186
+ if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
2187
+ return workerThreadService.buildSync(options);
2188
+ }
2189
+ let result;
2190
+ runServiceSync((service) => service.buildOrContext({
2191
+ callName: "buildSync",
2192
+ refs: null,
2193
+ options,
2194
+ isTTY: isTTY(),
2195
+ defaultWD,
2196
+ callback: (err, res) => {
2197
+ if (err) throw err;
2198
+ result = res;
2199
+ }
2200
+ }));
2201
+ return result;
2202
+ };
2203
+ var transformSync2 = (input, options) => {
2204
+ if (worker_threads && !isInternalWorkerThread) {
2205
+ if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
2206
+ return workerThreadService.transformSync(input, options);
2207
+ }
2208
+ let result;
2209
+ runServiceSync((service) => service.transform({
2210
+ callName: "transformSync",
2211
+ refs: null,
2212
+ input,
2213
+ options: options || {},
2214
+ isTTY: isTTY(),
2215
+ fs: fsSync,
2216
+ callback: (err, res) => {
2217
+ if (err) throw err;
2218
+ result = res;
2219
+ }
2220
+ }));
2221
+ return result;
2222
+ };
2223
+ var formatMessagesSync = (messages, options) => {
2224
+ if (worker_threads && !isInternalWorkerThread) {
2225
+ if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
2226
+ return workerThreadService.formatMessagesSync(messages, options);
2227
+ }
2228
+ let result;
2229
+ runServiceSync((service) => service.formatMessages({
2230
+ callName: "formatMessagesSync",
2231
+ refs: null,
2232
+ messages,
2233
+ options,
2234
+ callback: (err, res) => {
2235
+ if (err) throw err;
2236
+ result = res;
2237
+ }
2238
+ }));
2239
+ return result;
2240
+ };
2241
+ var analyzeMetafileSync = (metafile, options) => {
2242
+ if (worker_threads && !isInternalWorkerThread) {
2243
+ if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
2244
+ return workerThreadService.analyzeMetafileSync(metafile, options);
2245
+ }
2246
+ let result;
2247
+ runServiceSync((service) => service.analyzeMetafile({
2248
+ callName: "analyzeMetafileSync",
2249
+ refs: null,
2250
+ metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
2251
+ options,
2252
+ callback: (err, res) => {
2253
+ if (err) throw err;
2254
+ result = res;
2255
+ }
2256
+ }));
2257
+ return result;
2258
+ };
2259
+ var stop = () => {
2260
+ if (stopService) stopService();
2261
+ if (workerThreadService) workerThreadService.stop();
2262
+ return Promise.resolve();
2263
+ };
2264
+ var initializeWasCalled = false;
2265
+ var initialize = (options) => {
2266
+ options = validateInitializeOptions(options || {});
2267
+ if (options.wasmURL) throw new Error(`The "wasmURL" option only works in the browser`);
2268
+ if (options.wasmModule) throw new Error(`The "wasmModule" option only works in the browser`);
2269
+ if (options.worker) throw new Error(`The "worker" option only works in the browser`);
2270
+ if (initializeWasCalled) throw new Error('Cannot call "initialize" more than once');
2271
+ ensureServiceIsRunning();
2272
+ initializeWasCalled = true;
2273
+ return Promise.resolve();
2274
+ };
2275
+ var defaultWD = process.cwd();
2276
+ var longLivedService;
2277
+ var stopService;
2278
+ var ensureServiceIsRunning = () => {
2279
+ if (longLivedService) return longLivedService;
2280
+ let [command, args] = esbuildCommandAndArgs();
2281
+ let child = child_process.spawn(command, args.concat(`--service=${"0.27.7"}`, "--ping"), {
2282
+ windowsHide: true,
2283
+ stdio: ["pipe", "pipe", "inherit"],
2284
+ cwd: defaultWD
2285
+ });
2286
+ let { readFromStdout, afterClose, service } = createChannel({
2287
+ writeToStdin(bytes) {
2288
+ child.stdin.write(bytes, (err) => {
2289
+ if (err) afterClose(err);
2290
+ });
2291
+ },
2292
+ readFileSync: fs2.readFileSync,
2293
+ isSync: false,
2294
+ hasFS: true,
2295
+ esbuild: node_exports
2296
+ });
2297
+ child.stdin.on("error", afterClose);
2298
+ child.on("error", afterClose);
2299
+ const stdin = child.stdin;
2300
+ const stdout = child.stdout;
2301
+ stdout.on("data", readFromStdout);
2302
+ stdout.on("end", afterClose);
2303
+ stopService = () => {
2304
+ stdin.destroy();
2305
+ stdout.destroy();
2306
+ child.kill();
2307
+ initializeWasCalled = false;
2308
+ longLivedService = void 0;
2309
+ stopService = void 0;
2310
+ };
2311
+ let refCount = 0;
2312
+ child.unref();
2313
+ if (stdin.unref) {
2314
+ stdin.unref();
2315
+ }
2316
+ if (stdout.unref) {
2317
+ stdout.unref();
2318
+ }
2319
+ const refs = {
2320
+ ref() {
2321
+ if (++refCount === 1) child.ref();
2322
+ },
2323
+ unref() {
2324
+ if (--refCount === 0) child.unref();
2325
+ }
2326
+ };
2327
+ longLivedService = {
2328
+ build: (options) => new Promise((resolve2, reject) => {
2329
+ service.buildOrContext({
2330
+ callName: "build",
2331
+ refs,
2332
+ options,
2333
+ isTTY: isTTY(),
2334
+ defaultWD,
2335
+ callback: (err, res) => err ? reject(err) : resolve2(res)
2336
+ });
2337
+ }),
2338
+ context: (options) => new Promise((resolve2, reject) => service.buildOrContext({
2339
+ callName: "context",
2340
+ refs,
2341
+ options,
2342
+ isTTY: isTTY(),
2343
+ defaultWD,
2344
+ callback: (err, res) => err ? reject(err) : resolve2(res)
2345
+ })),
2346
+ transform: (input, options) => new Promise((resolve2, reject) => service.transform({
2347
+ callName: "transform",
2348
+ refs,
2349
+ input,
2350
+ options: options || {},
2351
+ isTTY: isTTY(),
2352
+ fs: fsAsync,
2353
+ callback: (err, res) => err ? reject(err) : resolve2(res)
2354
+ })),
2355
+ formatMessages: (messages, options) => new Promise((resolve2, reject) => service.formatMessages({
2356
+ callName: "formatMessages",
2357
+ refs,
2358
+ messages,
2359
+ options,
2360
+ callback: (err, res) => err ? reject(err) : resolve2(res)
2361
+ })),
2362
+ analyzeMetafile: (metafile, options) => new Promise((resolve2, reject) => service.analyzeMetafile({
2363
+ callName: "analyzeMetafile",
2364
+ refs,
2365
+ metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
2366
+ options,
2367
+ callback: (err, res) => err ? reject(err) : resolve2(res)
2368
+ }))
2369
+ };
2370
+ return longLivedService;
2371
+ };
2372
+ var runServiceSync = (callback) => {
2373
+ let [command, args] = esbuildCommandAndArgs();
2374
+ let stdin = new Uint8Array();
2375
+ let { readFromStdout, afterClose, service } = createChannel({
2376
+ writeToStdin(bytes) {
2377
+ if (stdin.length !== 0) throw new Error("Must run at most one command");
2378
+ stdin = bytes;
2379
+ },
2380
+ isSync: true,
2381
+ hasFS: true,
2382
+ esbuild: node_exports
2383
+ });
2384
+ callback(service);
2385
+ let stdout = child_process.execFileSync(command, args.concat(`--service=${"0.27.7"}`), {
2386
+ cwd: defaultWD,
2387
+ windowsHide: true,
2388
+ input: stdin,
2389
+ // We don't know how large the output could be. If it's too large, the
2390
+ // command will fail with ENOBUFS. Reserve 16mb for now since that feels
2391
+ // like it should be enough. Also allow overriding this with an environment
2392
+ // variable.
2393
+ maxBuffer: +process.env.ESBUILD_MAX_BUFFER || 16 * 1024 * 1024
2394
+ });
2395
+ readFromStdout(stdout);
2396
+ afterClose(null);
2397
+ };
2398
+ var randomFileName = () => {
2399
+ return path2.join(os2.tmpdir(), `esbuild-${crypto.randomBytes(32).toString("hex")}`);
2400
+ };
2401
+ var workerThreadService = null;
2402
+ var startWorkerThreadService = (worker_threads2) => {
2403
+ let { port1: mainPort, port2: workerPort } = new worker_threads2.MessageChannel();
2404
+ let worker = new worker_threads2.Worker(__filename, {
2405
+ workerData: { workerPort, defaultWD, esbuildVersion: "0.27.7" },
2406
+ transferList: [workerPort],
2407
+ // From node's documentation: https://nodejs.org/api/worker_threads.html
2408
+ //
2409
+ // Take care when launching worker threads from preload scripts (scripts loaded
2410
+ // and run using the `-r` command line flag). Unless the `execArgv` option is
2411
+ // explicitly set, new Worker threads automatically inherit the command line flags
2412
+ // from the running process and will preload the same preload scripts as the main
2413
+ // thread. If the preload script unconditionally launches a worker thread, every
2414
+ // thread spawned will spawn another until the application crashes.
2415
+ //
2416
+ execArgv: []
2417
+ });
2418
+ let nextID = 0;
2419
+ let fakeBuildError = (text) => {
2420
+ let error = new Error(`Build failed with 1 error:
2421
+ error: ${text}`);
2422
+ let errors = [{ id: "", pluginName: "", text, location: null, notes: [], detail: void 0 }];
2423
+ error.errors = errors;
2424
+ error.warnings = [];
2425
+ return error;
2426
+ };
2427
+ let validateBuildSyncOptions = (options) => {
2428
+ if (!options) return;
2429
+ let plugins = options.plugins;
2430
+ if (plugins && plugins.length > 0) throw fakeBuildError(`Cannot use plugins in synchronous API calls`);
2431
+ };
2432
+ let applyProperties = (object, properties) => {
2433
+ for (let key in properties) {
2434
+ object[key] = properties[key];
2435
+ }
2436
+ };
2437
+ let runCallSync = (command, args) => {
2438
+ let id = nextID++;
2439
+ let sharedBuffer = new SharedArrayBuffer(8);
2440
+ let sharedBufferView = new Int32Array(sharedBuffer);
2441
+ let msg = { sharedBuffer, id, command, args };
2442
+ worker.postMessage(msg);
2443
+ let status = Atomics.wait(sharedBufferView, 0, 0);
2444
+ if (status !== "ok" && status !== "not-equal") throw new Error("Internal error: Atomics.wait() failed: " + status);
2445
+ let { message: { id: id2, resolve: resolve2, reject, properties } } = worker_threads2.receiveMessageOnPort(mainPort);
2446
+ if (id !== id2) throw new Error(`Internal error: Expected id ${id} but got id ${id2}`);
2447
+ if (reject) {
2448
+ applyProperties(reject, properties);
2449
+ throw reject;
2450
+ }
2451
+ return resolve2;
2452
+ };
2453
+ worker.unref();
2454
+ return {
2455
+ buildSync(options) {
2456
+ validateBuildSyncOptions(options);
2457
+ return runCallSync("build", [options]);
2458
+ },
2459
+ transformSync(input, options) {
2460
+ return runCallSync("transform", [input, options]);
2461
+ },
2462
+ formatMessagesSync(messages, options) {
2463
+ return runCallSync("formatMessages", [messages, options]);
2464
+ },
2465
+ analyzeMetafileSync(metafile, options) {
2466
+ return runCallSync("analyzeMetafile", [metafile, options]);
2467
+ },
2468
+ stop() {
2469
+ worker.terminate();
2470
+ workerThreadService = null;
2471
+ }
2472
+ };
2473
+ };
2474
+ var startSyncServiceWorker = () => {
2475
+ let workerPort = worker_threads.workerData.workerPort;
2476
+ let parentPort = worker_threads.parentPort;
2477
+ let extractProperties = (object) => {
2478
+ let properties = {};
2479
+ if (object && typeof object === "object") {
2480
+ for (let key in object) {
2481
+ properties[key] = object[key];
2482
+ }
2483
+ }
2484
+ return properties;
2485
+ };
2486
+ try {
2487
+ let service = ensureServiceIsRunning();
2488
+ defaultWD = worker_threads.workerData.defaultWD;
2489
+ parentPort.on("message", (msg) => {
2490
+ (async () => {
2491
+ let { sharedBuffer, id, command, args } = msg;
2492
+ let sharedBufferView = new Int32Array(sharedBuffer);
2493
+ try {
2494
+ switch (command) {
2495
+ case "build":
2496
+ workerPort.postMessage({ id, resolve: await service.build(args[0]) });
2497
+ break;
2498
+ case "transform":
2499
+ workerPort.postMessage({ id, resolve: await service.transform(args[0], args[1]) });
2500
+ break;
2501
+ case "formatMessages":
2502
+ workerPort.postMessage({ id, resolve: await service.formatMessages(args[0], args[1]) });
2503
+ break;
2504
+ case "analyzeMetafile":
2505
+ workerPort.postMessage({ id, resolve: await service.analyzeMetafile(args[0], args[1]) });
2506
+ break;
2507
+ default:
2508
+ throw new Error(`Invalid command: ${command}`);
2509
+ }
2510
+ } catch (reject) {
2511
+ workerPort.postMessage({ id, reject, properties: extractProperties(reject) });
2512
+ }
2513
+ Atomics.add(sharedBufferView, 0, 1);
2514
+ Atomics.notify(sharedBufferView, 0, Infinity);
2515
+ })();
2516
+ });
2517
+ } catch (reject) {
2518
+ parentPort.on("message", (msg) => {
2519
+ let { sharedBuffer, id } = msg;
2520
+ let sharedBufferView = new Int32Array(sharedBuffer);
2521
+ workerPort.postMessage({ id, reject, properties: extractProperties(reject) });
2522
+ Atomics.add(sharedBufferView, 0, 1);
2523
+ Atomics.notify(sharedBufferView, 0, Infinity);
2524
+ });
2525
+ }
2526
+ };
2527
+ if (isInternalWorkerThread) {
2528
+ startSyncServiceWorker();
2529
+ }
2530
+ var node_default = node_exports;
2531
+ }
2532
+ });
2533
+
2534
+ // src/server/plugin.ts
2535
+ var import_esbuild = __toESM(require_main(), 1);
2536
+ var _buffer = require('buffer');
2537
+ var _fs = require('fs');
2538
+ var _path = require('path');
2539
+ var _url = require('url');
2540
+
2541
+ // src/core/action.ts
2542
+ var TYPES = ["click", "fill", "press", "wait", "screenshot"];
2543
+ function resolveAction(type, args) {
2544
+ if (!TYPES.includes(type))
2545
+ return { valid: false, error: `unknown action: ${type}` };
2546
+ const hasTarget = !!(args.sel || args.text);
2547
+ switch (type) {
2548
+ case "click":
2549
+ return hasTarget ? { valid: true } : { valid: false, error: "click needs sel= or text=" };
2550
+ case "fill":
2551
+ if (!hasTarget)
2552
+ return { valid: false, error: "fill needs sel= or text=" };
2553
+ if (args.value === void 0)
2554
+ return { valid: false, error: "fill needs value=" };
2555
+ return { valid: true };
2556
+ case "press":
2557
+ return args.key ? { valid: true } : { valid: false, error: "press needs key=" };
2558
+ case "wait":
2559
+ return hasTarget ? { valid: true } : { valid: false, error: "wait needs sel= or text=" };
2560
+ case "screenshot":
2561
+ return { valid: true };
2562
+ default:
2563
+ return { valid: false, error: `unknown action: ${type}` };
2564
+ }
2565
+ }
2566
+
2567
+ // src/core/check.ts
2568
+ function check(raw) {
2569
+ const consoleErrors = raw.console.filter((l) => l.level === "error");
2570
+ const failedRequests = raw.network.filter((r) => r.status >= 400 || r.failed);
2571
+ const assertions = [
2572
+ {
2573
+ name: "no-console-errors",
2574
+ pass: consoleErrors.length === 0,
2575
+ ...consoleErrors.length && { detail: consoleErrors[0].text }
2576
+ },
2577
+ {
2578
+ name: "no-uncaught-errors",
2579
+ pass: raw.errors.length === 0,
2580
+ ...raw.errors.length && { detail: raw.errors[0].message }
2581
+ },
2582
+ {
2583
+ name: "no-failed-requests",
2584
+ pass: failedRequests.length === 0,
2585
+ ...failedRequests.length && { detail: `${failedRequests[0].method} ${failedRequests[0].url} ${failedRequests[0].status}` }
2586
+ },
2587
+ {
2588
+ name: "ui-not-empty",
2589
+ pass: raw.ui.trim().length > 0,
2590
+ ...!raw.ui.trim().length && { detail: "UI tree is empty" }
2591
+ }
2592
+ ];
2593
+ return {
2594
+ pass: assertions.every((a) => a.pass),
2595
+ assertions
2596
+ };
2597
+ }
2598
+
2599
+ // src/core/util.ts
2600
+ function truncate(s, max) {
2601
+ return s.length > max ? `${s.slice(0, max)}\u2026` : s;
2602
+ }
2603
+ function compactUrl(url, search) {
2604
+ try {
2605
+ const u = new URL(url);
2606
+ if (search && u.search)
2607
+ return `${u.pathname}?${truncate(u.search.slice(1), search)}`;
2608
+ return u.pathname;
2609
+ } catch (e20) {
2610
+ return truncate(url, 80);
2611
+ }
2612
+ }
2613
+
2614
+ // src/core/compact.ts
2615
+ var SLOW_THRESHOLD = 1e3;
2616
+ var MAX_UI_DEPTH = 6;
2617
+ var UI_PRIMITIVES = /* @__PURE__ */ new Set([
2618
+ "Button",
2619
+ "Input",
2620
+ "Label",
2621
+ "Badge",
2622
+ "Checkbox",
2623
+ "Skeleton",
2624
+ "Spinner",
2625
+ "Switch",
2626
+ "Tabs",
2627
+ "Tooltip",
2628
+ "Popover",
2629
+ "Dialog",
2630
+ "Select",
2631
+ "Card",
2632
+ "Table",
2633
+ "Slider",
2634
+ "Progress",
2635
+ "RadioGroup",
2636
+ "HoverCard",
2637
+ "DropdownMenu",
2638
+ "ContextMenu",
2639
+ "Command",
2640
+ "Form",
2641
+ "Alert",
2642
+ "Pagination",
2643
+ "Textarea",
2644
+ "TooltipProvider",
2645
+ "DialogPortal",
2646
+ "Router",
2647
+ "RenderErrorBoundary",
2648
+ "RouterProvider",
2649
+ "RouterProvider2",
2650
+ "PanelGroup",
2651
+ "Panel"
2652
+ ]);
2653
+ function nameOf(line) {
2654
+ let end = 0;
2655
+ while (end < line.length) {
2656
+ const c = line[end];
2657
+ if (c === " " || c === " " || c === "[" || c === "\u2014")
2658
+ break;
2659
+ end++;
2660
+ }
2661
+ return line.slice(0, end);
2662
+ }
2663
+ function compactUI(tree) {
2664
+ if (!tree)
2665
+ return "";
2666
+ const lines = tree.split("\n");
2667
+ const result = [];
2668
+ const repeatTracker = /* @__PURE__ */ new Map();
2669
+ for (let i = 0; i < lines.length; i++) {
2670
+ const line = lines[i];
2671
+ const trimmed = line.trimStart();
2672
+ if (!trimmed)
2673
+ continue;
2674
+ const indent = line.length - trimmed.length;
2675
+ const depth = Math.floor(indent / 2);
2676
+ if (depth > MAX_UI_DEPTH)
2677
+ continue;
2678
+ const componentName = nameOf(trimmed);
2679
+ if (UI_PRIMITIVES.has(componentName))
2680
+ continue;
2681
+ const key = `${depth}:${componentName}`;
2682
+ const tracker = repeatTracker.get(key);
2683
+ if (tracker && i - tracker.lastIndex <= 2) {
2684
+ tracker.count++;
2685
+ tracker.lastIndex = i;
2686
+ continue;
2687
+ }
2688
+ for (const [k, t] of repeatTracker) {
2689
+ if (t.count > 1) {
2690
+ const d = Number.parseInt(k.split(":")[0]);
2691
+ const name = k.split(":").slice(1).join(":");
2692
+ result.push(`${" ".repeat(d)}${name} \xD7${t.count}`);
2693
+ }
2694
+ if (t.count > 1 || i - t.lastIndex > 2) {
2695
+ repeatTracker.delete(k);
2696
+ }
2697
+ }
2698
+ repeatTracker.set(key, { count: 1, lastIndex: i });
2699
+ result.push(line);
2700
+ }
2701
+ for (const [k, t] of repeatTracker) {
2702
+ if (t.count > 1) {
2703
+ const d = Number.parseInt(k.split(":")[0]);
2704
+ const name = k.split(":").slice(1).join(":");
2705
+ result.push(`${" ".repeat(d)}${name} \xD7${t.count}`);
2706
+ }
2707
+ }
2708
+ return result.join("\n");
2709
+ }
2710
+ var NOISE_SUBSTRINGS = [
2711
+ "[hmr]",
2712
+ "[vite]",
2713
+ "hot module",
2714
+ "react-devtools",
2715
+ "download the react devtools",
2716
+ "warning: react does not recognize",
2717
+ "source map",
2718
+ "favicon.ico",
2719
+ "webpack"
2720
+ ];
2721
+ function compactConsole(logs) {
2722
+ if (!logs.length)
2723
+ return "";
2724
+ const filtered = logs.filter((l) => {
2725
+ const lower = l.text.toLowerCase();
2726
+ return !NOISE_SUBSTRINGS.some((s) => lower.includes(s));
2727
+ });
2728
+ if (!filtered.length)
2729
+ return "";
2730
+ const deduped = [];
2731
+ for (const log of filtered) {
2732
+ const last = deduped[deduped.length - 1];
2733
+ if (last && last.entry.text === log.text && last.entry.level === log.level) {
2734
+ last.count++;
2735
+ } else {
2736
+ deduped.push({ entry: log, count: 1 });
2737
+ }
2738
+ }
2739
+ const errors = deduped.filter((d) => d.entry.level === "error");
2740
+ const warns = deduped.filter((d) => d.entry.level === "warn");
2741
+ const rest = deduped.filter((d) => d.entry.level !== "error" && d.entry.level !== "warn");
2742
+ const recentRest = rest.slice(-10);
2743
+ const lines = [];
2744
+ for (const group of [...errors, ...warns, ...recentRest]) {
2745
+ const prefix = `[${group.entry.level}]`;
2746
+ const count = group.count > 1 ? ` \xD7${group.count}` : "";
2747
+ const source = group.entry.source ? ` (${group.entry.source})` : "";
2748
+ const text = truncate(group.entry.text, 200);
2749
+ lines.push(`${prefix}${count} ${text}${source}`);
2750
+ }
2751
+ return lines.join("\n");
2752
+ }
2753
+ function compactNetwork(requests) {
2754
+ if (!requests.length)
2755
+ return "";
2756
+ const relevant = requests.filter(
2757
+ (r) => r.resourceType === "fetch" || r.resourceType === "xhr" || r.resourceType === "websocket" || r.resourceType === "eventsource" || isApiUrl(r.url)
2758
+ );
2759
+ if (!relevant.length)
2760
+ return "";
2761
+ const lines = [];
2762
+ for (const req of relevant) {
2763
+ const duration = req.duration > 0 ? ` ${formatDuration(req.duration)}` : "";
2764
+ const slow = req.duration >= SLOW_THRESHOLD ? " [SLOW]" : "";
2765
+ const url = compactUrl(req.url, 50);
2766
+ const headers = diagnosticHeaders(req);
2767
+ if (req.failed || req.status >= 400) {
2768
+ const body = req.responseBody ? ` "${truncate(req.responseBody, 100)}"` : "";
2769
+ const failure = req.failureText ? ` (${req.failureText})` : "";
2770
+ lines.push(`${req.method} ${url} ${req.status}${failure}${body}${headers}${duration}${slow}`);
2771
+ } else {
2772
+ lines.push(`${req.method} ${url} ${req.status}${headers}${duration}${slow}`);
2773
+ }
2774
+ }
2775
+ return lines.join("\n");
2776
+ }
2777
+ function isApiUrl(url) {
2778
+ try {
2779
+ const u = new URL(url);
2780
+ return u.pathname.startsWith("/api") || u.pathname.includes("/graphql");
2781
+ } catch (e21) {
2782
+ return false;
2783
+ }
2784
+ }
2785
+ var DIAGNOSTIC_HEADERS = ["content-type", "x-error", "www-authenticate", "access-control-allow-origin"];
2786
+ function diagnosticHeaders(req) {
2787
+ const h = req.responseHeaders;
2788
+ if (!h)
2789
+ return "";
2790
+ const parts = [];
2791
+ for (const key of DIAGNOSTIC_HEADERS) {
2792
+ const val = h[key];
2793
+ if (!val)
2794
+ continue;
2795
+ if (key === "content-type" && req.status < 400 && val.includes("application/json"))
2796
+ continue;
2797
+ parts.push(`${key}: ${truncate(val, 60)}`);
2798
+ }
2799
+ if (!parts.length)
2800
+ return "";
2801
+ return ` [${parts.join(", ")}]`;
2802
+ }
2803
+ function formatDuration(ms) {
2804
+ return ms >= 1e3 ? `${(ms / 1e3).toFixed(1)}s` : `${Math.round(ms)}ms`;
2805
+ }
2806
+ function compactErrors(errors) {
2807
+ if (!errors.length)
2808
+ return "";
2809
+ const seen = /* @__PURE__ */ new Map();
2810
+ for (const err of errors) {
2811
+ if (!seen.has(err.message)) {
2812
+ seen.set(err.message, err);
2813
+ }
2814
+ }
2815
+ const lines = [];
2816
+ for (const err of seen.values()) {
2817
+ lines.push(err.message);
2818
+ if (err.stack) {
2819
+ const frames = filterStack(err.stack);
2820
+ for (const frame of frames) {
2821
+ lines.push(` at ${frame}`);
2822
+ }
2823
+ }
2824
+ }
2825
+ return lines.join("\n");
2826
+ }
2827
+ function filterStack(stack) {
2828
+ return stack.split("\n").map((l) => l.trim()).filter((l) => l.startsWith("at ")).map((l) => l.slice(3)).filter((l) => !l.includes("node_modules") && !l.includes("<anonymous>")).slice(0, 5);
2829
+ }
2830
+ function compactState(state) {
2831
+ if (!state || !Object.keys(state).length)
2832
+ return "";
2833
+ const lines = [];
2834
+ for (const [name, value] of Object.entries(state)) {
2835
+ lines.push(`${name}:`);
2836
+ if (typeof value === "object" && value !== null) {
2837
+ for (const [k, v] of Object.entries(value)) {
2838
+ lines.push(` ${k}: ${formatValue(v)}`);
2839
+ }
2840
+ } else {
2841
+ lines.push(` ${String(value)}`);
2842
+ }
2843
+ }
2844
+ return lines.join("\n");
2845
+ }
2846
+ function formatValue(v) {
2847
+ if (v === null || v === void 0)
2848
+ return String(v);
2849
+ if (typeof v === "string")
2850
+ return v;
2851
+ if (typeof v === "number" || typeof v === "boolean")
2852
+ return String(v);
2853
+ if (typeof v === "object") {
2854
+ const s = JSON.stringify(v);
2855
+ return s.length > 120 ? `${s.slice(0, 120)}\u2026` : s;
2856
+ }
2857
+ return String(v);
2858
+ }
2859
+ function compact(raw) {
2860
+ return {
2861
+ url: raw.url,
2862
+ ui: compactUI(raw.ui),
2863
+ console: compactConsole(raw.console),
2864
+ network: compactNetwork(raw.network),
2865
+ errors: compactErrors(raw.errors),
2866
+ state: compactState(raw.state),
2867
+ timestamp: raw.timestamp,
2868
+ counts: {
2869
+ console: raw.console.length,
2870
+ network: raw.network.length,
2871
+ errors: raw.errors.length,
2872
+ state: Object.keys(raw.state).length
2873
+ }
2874
+ };
2875
+ }
2876
+
2877
+ // src/core/detail.ts
2878
+ function detail(raw, section, index, full) {
2879
+ switch (section) {
2880
+ case "ui":
2881
+ return full ? raw.ui || null : compactUI(raw.ui) || null;
2882
+ case "console":
2883
+ return detailConsole(raw.console, index, full);
2884
+ case "network":
2885
+ return detailNetwork(raw.network, index, full);
2886
+ case "errors":
2887
+ return detailError(raw.errors, index, full);
2888
+ case "state":
2889
+ return detailState(raw.state, index, full);
2890
+ default:
2891
+ return null;
2892
+ }
2893
+ }
2894
+ function detailConsole(logs, index, full) {
2895
+ if (index === void 0) {
2896
+ if (!logs.length)
2897
+ return "(empty)";
2898
+ return logs.map((log2, i2) => `[${i2}] [${log2.level}] ${truncate(log2.text, 120)}`).join("\n");
2899
+ }
2900
+ const i = Number.parseInt(index);
2901
+ if (Number.isNaN(i) || i < 0 || i >= logs.length)
2902
+ return null;
2903
+ const log = logs[i];
2904
+ if (full) {
2905
+ const parts = [`[${log.level}] ${log.text}`];
2906
+ if (log.timestamp)
2907
+ parts.push(`timestamp: ${new Date(log.timestamp).toISOString()}`);
2908
+ if (log.source)
2909
+ parts.push(`source: ${log.source}`);
2910
+ return parts.join("\n");
2911
+ }
2912
+ return `[${log.level}] ${truncate(log.text, 200)}`;
2913
+ }
2914
+ function detailNetwork(requests, index, full) {
2915
+ if (index === void 0) {
2916
+ if (!requests.length)
2917
+ return "(empty)";
2918
+ return requests.map((req2, i2) => `[${i2}] ${req2.method} ${req2.status} ${truncate(req2.url, 80)} ${req2.duration}ms${req2.failed ? " FAILED" : ""}`).join("\n");
2919
+ }
2920
+ const i = Number.parseInt(index);
2921
+ if (Number.isNaN(i) || i < 0 || i >= requests.length)
2922
+ return null;
2923
+ const req = requests[i];
2924
+ const lines = [
2925
+ `${req.method} ${req.url}`,
2926
+ `status: ${req.status}`,
2927
+ `duration: ${req.duration}ms`,
2928
+ `type: ${req.resourceType}`
2929
+ ];
2930
+ if (req.failed)
2931
+ lines.push(`failed: ${req.failureText || "true"}`);
2932
+ if (full) {
2933
+ if (req.requestHeaders && Object.keys(req.requestHeaders).length) {
2934
+ lines.push("request-headers:");
2935
+ for (const [k, v] of Object.entries(req.requestHeaders)) lines.push(` ${k}: ${v}`);
2936
+ }
2937
+ if (req.requestBody)
2938
+ lines.push(`request-body:
2939
+ ${req.requestBody}`);
2940
+ if (req.responseHeaders && Object.keys(req.responseHeaders).length) {
2941
+ lines.push("response-headers:");
2942
+ for (const [k, v] of Object.entries(req.responseHeaders)) lines.push(` ${k}: ${v}`);
2943
+ }
2944
+ if (req.responseBody)
2945
+ lines.push(`response-body:
2946
+ ${req.responseBody}`);
2947
+ } else {
2948
+ if (req.requestBody) {
2949
+ lines.push(`request-body: ${byteSize(req.requestBody)}`);
2950
+ if (req.requestSample) {
2951
+ const schema = jsonSchema(req.requestSample);
2952
+ if (schema)
2953
+ lines.push(schema);
2954
+ }
2955
+ }
2956
+ if (req.responseBody) {
2957
+ if (req.status >= 400) {
2958
+ lines.push(`response-body: ${byteSize(req.responseBody)} "${truncate(req.responseBody, 100)}"`);
2959
+ } else {
2960
+ if (req.responseSample) {
2961
+ lines.push(`response-body: ${byteSize(req.responseBody)}`);
2962
+ const schema = jsonSchema(req.responseSample);
2963
+ if (schema)
2964
+ lines.push(schema);
2965
+ } else {
2966
+ lines.push(`response-body: ${byteSize(req.responseBody)} ${truncate(req.responseBody, 100)}`);
2967
+ }
2968
+ }
2969
+ }
2970
+ }
2971
+ return lines.join("\n");
2972
+ }
2973
+ function detailError(errors, index, full) {
2974
+ if (index === void 0) {
2975
+ if (!errors.length)
2976
+ return "(empty)";
2977
+ return errors.map((err2, i2) => `[${i2}] ${truncate(err2.message, 120)}`).join("\n");
2978
+ }
2979
+ const i = Number.parseInt(index);
2980
+ if (Number.isNaN(i) || i < 0 || i >= errors.length)
2981
+ return null;
2982
+ const err = errors[i];
2983
+ if (full) {
2984
+ const lines2 = [err.message];
2985
+ if (err.stack)
2986
+ lines2.push(err.stack);
2987
+ if (err.source)
2988
+ lines2.push(`source: ${err.source}`);
2989
+ if (err.line != null)
2990
+ lines2.push(`location: ${err.source || ""}:${err.line}:${_nullishCoalesce(err.column, () => ( 0))}`);
2991
+ return lines2.join("\n");
2992
+ }
2993
+ const lines = [err.message];
2994
+ if (err.stack) {
2995
+ const appFrames = err.stack.split("\n").map((l) => l.trim()).filter((l) => l.startsWith("at ") && !l.includes("node_modules")).slice(0, 3);
2996
+ if (appFrames.length)
2997
+ lines.push(...appFrames);
2998
+ const totalApp = err.stack.split("\n").filter((l) => l.trim().startsWith("at ") && !l.includes("node_modules")).length;
2999
+ if (totalApp > 3)
3000
+ lines.push(` ... ${totalApp - 3} more app frames`);
3001
+ }
3002
+ if (err.line != null)
3003
+ lines.push(`location: ${err.source || ""}:${err.line}:${_nullishCoalesce(err.column, () => ( 0))}`);
3004
+ return lines.join("\n");
3005
+ }
3006
+ function detailState(state, name, full) {
3007
+ if (!name) {
3008
+ const keys = Object.keys(state);
3009
+ if (!keys.length)
3010
+ return "(empty)";
3011
+ return keys.map((k) => `${k}: ${formatSummaryValue(state[k])}`).join("\n");
3012
+ }
3013
+ if (!(name in state))
3014
+ return null;
3015
+ const value = state[name];
3016
+ if (full) {
3017
+ try {
3018
+ return JSON.stringify(value, null, 2);
3019
+ } catch (e22) {
3020
+ return String(value);
3021
+ }
3022
+ }
3023
+ if (typeof value !== "object" || value === null)
3024
+ return `${name}: ${typeof value}`;
3025
+ const lines = [];
3026
+ for (const [k, v] of Object.entries(value)) {
3027
+ lines.push(`${k}: ${formatSummaryValue(v)}`);
3028
+ }
3029
+ return lines.join("\n");
3030
+ }
3031
+ function isArraySentinel(v) {
3032
+ if (!v.startsWith("Array(") || !v.endsWith(")"))
3033
+ return false;
3034
+ const digits = v.slice(6, -1);
3035
+ return digits.length > 0 && [...digits].every((c) => c >= "0" && c <= "9");
3036
+ }
3037
+ function formatSummaryValue(v) {
3038
+ if (v === null || v === void 0)
3039
+ return String(v);
3040
+ if (typeof v === "string") {
3041
+ if (isArraySentinel(v))
3042
+ return v;
3043
+ return v.length > 80 ? `${v.slice(0, 80)}\u2026` : v;
3044
+ }
3045
+ if (typeof v === "number" || typeof v === "boolean")
3046
+ return String(v);
3047
+ if (typeof v === "object") {
3048
+ const s = JSON.stringify(v);
3049
+ return s.length > 80 ? `${s.slice(0, 80)}\u2026` : s;
3050
+ }
3051
+ return String(v);
3052
+ }
3053
+ function jsonSchema(sample) {
3054
+ try {
3055
+ return schemaOf(JSON.parse(sample), 0);
3056
+ } catch (e23) {
3057
+ return null;
3058
+ }
3059
+ }
3060
+ function schemaOf(v, d) {
3061
+ if (v === null)
3062
+ return "null";
3063
+ if (typeof v === "string")
3064
+ return "string";
3065
+ if (typeof v === "number")
3066
+ return "number";
3067
+ if (typeof v === "boolean")
3068
+ return "boolean";
3069
+ if (Array.isArray(v)) {
3070
+ if (!v.length)
3071
+ return "[]";
3072
+ if (d >= 3)
3073
+ return "[\u2026]";
3074
+ return `${schemaOf(v[0], d + 1)}[]`;
3075
+ }
3076
+ if (typeof v === "object") {
3077
+ if (d >= 3)
3078
+ return "{\u2026}";
3079
+ const entries = Object.entries(v);
3080
+ if (!entries.length)
3081
+ return "{}";
3082
+ const max = d === 0 ? 12 : 6;
3083
+ const fields = entries.slice(0, max).map(([k, val]) => `${k}: ${schemaOf(val, d + 1)}`);
3084
+ if (entries.length > max)
3085
+ fields.push(`\u2026 ${entries.length - max} more`);
3086
+ return `{ ${fields.join(", ")} }`;
3087
+ }
3088
+ return typeof v;
3089
+ }
3090
+ function byteSize(s) {
3091
+ const bytes = new TextEncoder().encode(s).length;
3092
+ if (bytes < 1024)
3093
+ return `${bytes}B`;
3094
+ if (bytes < 1024 * 1024)
3095
+ return `${(bytes / 1024).toFixed(1)}KB`;
3096
+ return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
3097
+ }
3098
+
3099
+ // src/core/diff.ts
3100
+ function diffState(prev, curr) {
3101
+ if (!prev) {
3102
+ return {
3103
+ newErrors: curr.console.filter((l) => l.level === "error"),
3104
+ newExceptions: [...curr.errors],
3105
+ newFailedRequests: curr.network.filter((r) => r.status >= 400 || r.failed),
3106
+ uiGone: false,
3107
+ clean: curr.console.filter((l) => l.level === "error").length === 0 && curr.errors.length === 0 && curr.network.filter((r) => r.status >= 400 || r.failed).length === 0
3108
+ };
3109
+ }
3110
+ const prevErrorTexts = new Set(prev.console.filter((l) => l.level === "error").map((l) => l.text));
3111
+ const newErrors = curr.console.filter((l) => l.level === "error" && !prevErrorTexts.has(l.text));
3112
+ const prevExceptionMsgs = new Set(prev.errors.map((e) => e.message));
3113
+ const newExceptions = curr.errors.filter((e) => !prevExceptionMsgs.has(e.message));
3114
+ const prevFailedKeys = new Set(
3115
+ prev.network.filter((r) => r.status >= 400 || r.failed).map((r) => `${r.method}|${r.url}|${r.status}`)
3116
+ );
3117
+ const newFailedRequests = curr.network.filter((r) => r.status >= 400 || r.failed).filter((r) => !prevFailedKeys.has(`${r.method}|${r.url}|${r.status}`));
3118
+ const uiGone = prev.ui.trim().length > 0 && curr.ui.trim().length === 0;
3119
+ return {
3120
+ newErrors,
3121
+ newExceptions,
3122
+ newFailedRequests,
3123
+ uiGone,
3124
+ clean: newErrors.length === 0 && newExceptions.length === 0 && newFailedRequests.length === 0 && !uiGone
3125
+ };
3126
+ }
3127
+
3128
+ // src/core/emit.ts
3129
+ var _picocolors = require('picocolors'); var _picocolors2 = _interopRequireDefault(_picocolors);
3130
+ var SECTIONS = ["ui", "console", "network", "errors", "state"];
3131
+ var COUNTED_SECTIONS = {
3132
+ console: "console",
3133
+ network: "network",
3134
+ errors: "errors",
3135
+ state: "state"
3136
+ };
3137
+ function emit(state) {
3138
+ const sections = [];
3139
+ for (const key of SECTIONS) {
3140
+ if (state[key]) {
3141
+ const countKey = COUNTED_SECTIONS[key];
3142
+ const count = countKey ? _nullishCoalesce(_optionalChain([state, 'access', _ => _.counts, 'optionalAccess', _2 => _2[countKey]]), () => ( 0)) : 0;
3143
+ const attr = count ? ` count="${count}"` : "";
3144
+ sections.push(`<${key}${attr}>
3145
+ ${state[key]}
3146
+ </${key}>`);
3147
+ }
3148
+ }
3149
+ if (!sections.length) {
3150
+ sections.push("<empty/>");
3151
+ }
3152
+ return `<aipeek url="${state.url}">
3153
+
3154
+ ${sections.join("\n\n")}
3155
+
3156
+ </aipeek>
3157
+
3158
+ detail: GET /__aipeek/{section}/{index}?full`;
3159
+ }
3160
+ function emitSummary(raw) {
3161
+ const consoleErrors = raw.console.filter((l) => l.level === "error");
3162
+ const consoleWarns = raw.console.filter((l) => l.level === "warn");
3163
+ const failedReqs = raw.network.filter((r) => r.status >= 400 || r.failed);
3164
+ const hasIssues = consoleErrors.length > 0 || raw.errors.length > 0 || failedReqs.length > 0;
3165
+ const lines = [];
3166
+ if (raw.ui.trim()) {
3167
+ lines.push(`ui: ${summarizeUI(raw.ui)}`);
3168
+ }
3169
+ if (raw.console.length) {
3170
+ if (consoleErrors.length || consoleWarns.length) {
3171
+ const parts = [];
3172
+ for (const e of consoleErrors) parts.push(` [error] ${truncate(e.text, 150)}`);
3173
+ for (const w of consoleWarns) parts.push(` [warn] ${truncate(w.text, 150)}`);
3174
+ const rest = raw.console.length - consoleErrors.length - consoleWarns.length;
3175
+ if (rest > 0)
3176
+ parts.push(` \u2026 ${rest} more`);
3177
+ lines.push(`console (${raw.console.length}):`);
3178
+ lines.push(...parts);
3179
+ } else {
3180
+ lines.push(`console: ${raw.console.length} logs`);
3181
+ }
3182
+ }
3183
+ if (raw.network.length) {
3184
+ if (failedReqs.length) {
3185
+ lines.push(`network (${raw.network.length}):`);
3186
+ for (const r of failedReqs) {
3187
+ const body = r.responseBody ? ` "${truncate(r.responseBody, 80)}"` : "";
3188
+ lines.push(` ${r.method} ${compactUrl(r.url)} ${r.status}${body}`);
3189
+ }
3190
+ const ok = raw.network.length - failedReqs.length;
3191
+ if (ok > 0)
3192
+ lines.push(` \u2026 ${ok} ok`);
3193
+ } else {
3194
+ lines.push(`network: ${raw.network.length} ok`);
3195
+ }
3196
+ }
3197
+ if (raw.errors.length) {
3198
+ lines.push(`errors (${raw.errors.length}):`);
3199
+ for (const e of raw.errors) lines.push(` ${truncate(e.message, 150)}`);
3200
+ }
3201
+ const storeNames = Object.keys(raw.state);
3202
+ if (storeNames.length) {
3203
+ const parts = storeNames.map((n) => {
3204
+ const v = raw.state[n];
3205
+ const keys = typeof v === "object" && v !== null ? Object.keys(v).length : 0;
3206
+ return keys > 0 ? `${n}(${keys})` : n;
3207
+ });
3208
+ lines.push(`state: ${parts.join(", ")}`);
3209
+ }
3210
+ if (!lines.length)
3211
+ return "<aipeek>empty</aipeek>";
3212
+ const status = hasIssues ? `${consoleErrors.length + raw.errors.length + failedReqs.length} issues` : "ok";
3213
+ return `<aipeek url="${raw.url}" status="${status}">
3214
+ ${lines.join("\n")}
3215
+ </aipeek>${hasIssues ? "\n\ndetail: GET /__aipeek/{section}/{index}" : ""}`;
3216
+ }
3217
+ function summarizeUI(tree) {
3218
+ const components = [];
3219
+ const counts = /* @__PURE__ */ new Map();
3220
+ for (const line of tree.split("\n")) {
3221
+ const trimmed = line.trimStart();
3222
+ if (!trimmed)
3223
+ continue;
3224
+ const indent = line.length - trimmed.length;
3225
+ if (indent > 2)
3226
+ continue;
3227
+ const name = nameOf(trimmed);
3228
+ if (!name)
3229
+ continue;
3230
+ const focused = trimmed.includes("[focused]");
3231
+ const generating = trimmed.includes("[generating]");
3232
+ const loading = trimmed.includes("[loading]");
3233
+ const existing = counts.get(name) || 0;
3234
+ if (existing > 0) {
3235
+ counts.set(name, existing + 1);
3236
+ continue;
3237
+ }
3238
+ counts.set(name, 1);
3239
+ let label = name;
3240
+ if (focused)
3241
+ label += "[focused]";
3242
+ if (generating)
3243
+ label += "[generating]";
3244
+ if (loading)
3245
+ label += "[loading]";
3246
+ components.push(label);
3247
+ }
3248
+ const result = components.map((c) => {
3249
+ const name = c.split("[")[0];
3250
+ const count = counts.get(name) || 1;
3251
+ return count > 1 ? `${c}(\xD7${count})` : c;
3252
+ });
3253
+ return result.join(", ") || "empty";
3254
+ }
3255
+ function emitCheck(result) {
3256
+ const lines = result.assertions.map(
3257
+ (a) => a.pass ? `\u2713 ${a.name}` : `\u2717 ${a.name}${a.detail ? `: ${a.detail}` : ""}`
3258
+ );
3259
+ return `<aipeek-check pass="${result.pass}">
3260
+ ${lines.join("\n")}
3261
+ </aipeek-check>`;
3262
+ }
3263
+ function emitDiff(diff) {
3264
+ const issues = [];
3265
+ for (const e of diff.newErrors) issues.push(_picocolors2.default.red(` [error] ${e.text}`));
3266
+ for (const e of diff.newExceptions) issues.push(_picocolors2.default.red(` [exception] ${e.message}`));
3267
+ for (const r of diff.newFailedRequests) issues.push(_picocolors2.default.yellow(` [network] ${r.method} ${r.url} ${r.status}`));
3268
+ if (diff.uiGone)
3269
+ issues.push(_picocolors2.default.magenta(" [ui] component tree disappeared"));
3270
+ if (!issues.length)
3271
+ return "";
3272
+ const count = issues.length;
3273
+ return `${_picocolors2.default.bold("[aipeek]")} ${_picocolors2.default.red(`\u2717 ${count} issue${count > 1 ? "s" : ""} after HMR`)}
3274
+ ${issues.join("\n")}`;
3275
+ }
3276
+
3277
+ // src/server/plugin.ts
3278
+ function readBody(req) {
3279
+ return new Promise((resolve2) => {
3280
+ let s = "";
3281
+ req.on("data", (c) => s += c);
3282
+ req.on("end", () => resolve2(s));
3283
+ });
3284
+ }
3285
+ var __dirname2 = _path.dirname.call(void 0, _url.fileURLToPath.call(void 0, import.meta.url));
3286
+ var clientPath = _path.resolve.call(void 0, __dirname2, "../client/client.ts");
3287
+ var patchPath = _path.resolve.call(void 0, __dirname2, "../client/client-patch.ts");
3288
+ function compilePatch() {
3289
+ const source = _fs.readFileSync.call(void 0, patchPath, "utf-8");
3290
+ const result = (0, import_esbuild.transformSync)(source, {
3291
+ loader: "ts",
3292
+ target: "es2020",
3293
+ format: "iife",
3294
+ minify: false
3295
+ });
3296
+ return result.code;
3297
+ }
3298
+ function aipeekSnippet(port) {
3299
+ const base = `http://localhost:${port}/__aipeek`;
3300
+ return `
3301
+ # aipeek \u2014 Runtime Browser Inspector
3302
+
3303
+ IMPORTANT: Before debugging any UI issue, visual bug, or runtime error, ALWAYS fetch the live app state first. Do NOT guess \u2014 look at the actual browser state.
3304
+
3305
+ ## Read state \u2014 cheapest first
3306
+
3307
+ \`\`\`bash
3308
+ curl ${base}/screen # state-machine projection {view, modal, focus, knobs} \u2014 START HERE
3309
+ curl ${base}/ui # React component tree \u2014 deep-dive when /screen isn't enough
3310
+ curl '${base}/dom?scope=ChatInput' # semantic DOM scoped to a component \u2014 UI as text, src locations
3311
+ curl ${base} # high-density summary (ok sections \u2192 1 line, issues \u2192 expanded)
3312
+ curl ${base}?full # full dump: UI tree + console + network + errors + state
3313
+ curl ${base}/check # pass/fail health check \u2014 use after code changes
3314
+ curl ${base}/console # console logs (errors, warnings, info)
3315
+ curl ${base}/network # fetch/XHR requests with status and timing
3316
+ curl ${base}/errors # uncaught errors and unhandled rejections
3317
+ curl ${base}/state # registered store snapshots
3318
+ \`\`\`
3319
+
3320
+ \`/screen\` projects the whole UI to a few state variables \u2014 start there, not \`/ui\`. Append
3321
+ \`?full\` for untruncated output. Append \`/{index}\` for a specific item's detail.
3322
+
3323
+ To inspect or edit a component, work top-down \u2014 the full DOM is huge, a scoped view is
3324
+ accurate: \`/screen\` or \`/ui\` to find the component, then \`/dom?scope=<Name>\` (matches the
3325
+ source path) or \`/dom?sel=<css>\` for just that subtree. Each line carries its source
3326
+ location (\`@File.tsx:line\`), so the DOM view tells you exactly where to edit.
3327
+
3328
+ ## Drive the page (acts on the currently-open tab \u2014 no separate browser)
3329
+
3330
+ \`\`\`bash
3331
+ curl '${base}/click?text=New' # click by visible text (or sel= for CSS)
3332
+ curl '${base}/fill?sel=textarea&value=hi' # set an input/textarea/select value
3333
+ curl '${base}/press?key=Enter' # key on focused element (e.g. Control+a)
3334
+ curl '${base}/wait?text=Done&timeout=8000' # poll until text/sel appears (add gone=1 to wait until it disappears)
3335
+ curl '${base}/screenshot?out=shot.png' # DOM\u2192PNG into .aipeek/ (html-to-image; lossy)
3336
+ \`\`\`
3337
+
3338
+ \`click\`/\`fill\`/\`press\` settle the DOM and append the resulting UI tree (\`--- ui after ---\`)
3339
+ to the response \u2014 no follow-up read needed. On a miss, the response lists the reachable
3340
+ clickable elements so you can re-target. URL-encode any \`sel=\` with non-ASCII or quotes:
3341
+ \`curl -G ${base}/click --data-urlencode 'sel=button[title="\u77E5\u8BC6\u5E93"]'\`.
3342
+
3343
+ **Chain \u2014 a whole interaction in one round-trip.** POST a JSON array; runs in sequence,
3344
+ each step settles before the next, stops on first failure:
3345
+
3346
+ \`\`\`bash
3347
+ curl -X POST ${base}/chain -d '[
3348
+ {"type":"click","sel":"button[title=\\"\u77E5\u8BC6\u5E93\\"]"},
3349
+ {"type":"wait","text":"Done"},
3350
+ {"type":"fill","sel":"textarea","value":"hi"},
3351
+ {"type":"press","key":"Enter"}
3352
+ ]'
3353
+ \`\`\`
3354
+
3355
+ **Escape hatch.** \`curl '${base}/eval?code=...'\` (or POST the code as the body) runs arbitrary
3356
+ JS in the page and returns the result \u2014 for anything the typed endpoints can't do.
3357
+
3358
+ aipeek auto-detects errors after HMR and prints them to the terminal \u2014 watch for \`[aipeek]\` messages.
3359
+ `;
3360
+ }
3361
+ function norm(line) {
3362
+ const t = line.trim();
3363
+ const i = t.indexOf("localhost:");
3364
+ if (i === -1)
3365
+ return t;
3366
+ let j = i + "localhost:".length;
3367
+ while (j < t.length && t[j] >= "0" && t[j] <= "9") j++;
3368
+ return `${t.slice(0, i)}localhost:PORT${t.slice(j)}`;
3369
+ }
3370
+ function stripBlocks(content, snippet) {
3371
+ const known = new Set(snippet.split("\n").map(norm).filter((l) => l.length > 3));
3372
+ const lines = content.split("\n");
3373
+ const keep = [];
3374
+ let inside = false;
3375
+ let buf = [];
3376
+ let hits = 0;
3377
+ const flush = () => {
3378
+ if (buf.length && hits / buf.length <= 0.5)
3379
+ keep.push(...buf);
3380
+ buf = [];
3381
+ hits = 0;
3382
+ inside = false;
3383
+ };
3384
+ for (const line of lines) {
3385
+ const isKnown = known.has(norm(line));
3386
+ if (!inside) {
3387
+ if (isKnown) {
3388
+ inside = true;
3389
+ buf = [line];
3390
+ hits = 1;
3391
+ } else {
3392
+ keep.push(line);
3393
+ }
3394
+ continue;
3395
+ }
3396
+ buf.push(line);
3397
+ if (isKnown)
3398
+ hits++;
3399
+ else if (buf.slice(-3).every((l) => !known.has(norm(l))))
3400
+ flush();
3401
+ }
3402
+ flush();
3403
+ return keep.join("\n");
3404
+ }
3405
+ function injectClaudeMd(root, port) {
3406
+ const path = _path.resolve.call(void 0, root, "CLAUDE.md");
3407
+ const snippet = aipeekSnippet(port);
3408
+ try {
3409
+ if (!_fs.existsSync.call(void 0, path)) {
3410
+ _fs.writeFileSync.call(void 0, path, snippet.trimStart());
3411
+ return;
3412
+ }
3413
+ const stripped = stripBlocks(_fs.readFileSync.call(void 0, path, "utf-8"), snippet).trimEnd();
3414
+ _fs.writeFileSync.call(void 0, path, `${stripped}
3415
+ ${snippet}`);
3416
+ } catch (e24) {
3417
+ }
3418
+ }
3419
+ function aipeekPlugin() {
3420
+ let pendingResolve = null;
3421
+ let server;
3422
+ let lastRaw = null;
3423
+ let pushTimer;
3424
+ const pendingActions = /* @__PURE__ */ new Map();
3425
+ let actionId = 0;
3426
+ let pendingDom = null;
3427
+ let pendingScreen = null;
3428
+ const pendingEvals = /* @__PURE__ */ new Map();
3429
+ let evalId = 0;
3430
+ const VISIBLE_MS = 400;
3431
+ function twoPhase(event, payload, arm, fullMs = 3e3) {
3432
+ return new Promise((resolve2, reject) => {
3433
+ let settled = false;
3434
+ const clear = arm((v) => {
3435
+ settled = true;
3436
+ resolve2(v);
3437
+ });
3438
+ server.hot.send(event, { ...payload, requireVisible: true });
3439
+ setTimeout(() => {
3440
+ if (settled)
3441
+ return;
3442
+ server.hot.send(event, { ...payload, requireVisible: false });
3443
+ setTimeout(() => {
3444
+ if (settled)
3445
+ return;
3446
+ clear();
3447
+ reject(new Error(`timeout: no client response within ${VISIBLE_MS + fullMs}ms`));
3448
+ }, fullMs);
3449
+ }, VISIBLE_MS);
3450
+ });
3451
+ }
3452
+ function collectFromClient() {
3453
+ return twoPhase("aipeek:collect", {}, (resolve2) => {
3454
+ pendingResolve = resolve2;
3455
+ return () => {
3456
+ pendingResolve = null;
3457
+ };
3458
+ });
3459
+ }
3460
+ function collectDomFromClient(scope, sel) {
3461
+ return twoPhase("aipeek:collect-dom", { scope, sel }, (resolve2) => {
3462
+ pendingDom = resolve2;
3463
+ return () => {
3464
+ pendingDom = null;
3465
+ };
3466
+ });
3467
+ }
3468
+ function collectScreenFromClient() {
3469
+ return twoPhase("aipeek:collect-screen", {}, (resolve2) => {
3470
+ pendingScreen = resolve2;
3471
+ return () => {
3472
+ pendingScreen = null;
3473
+ };
3474
+ });
3475
+ }
3476
+ function sendAction(type, args) {
3477
+ const id = ++actionId;
3478
+ const fullMs = Math.max(_nullishCoalesce(args.timeout, () => ( 0)), 3e3) + 2e3;
3479
+ return twoPhase("aipeek:action", { id, type, args }, (resolve2) => {
3480
+ pendingActions.set(id, resolve2);
3481
+ return () => {
3482
+ pendingActions.delete(id);
3483
+ };
3484
+ }, fullMs);
3485
+ }
3486
+ function evalInClient(code) {
3487
+ const id = ++evalId;
3488
+ return twoPhase("aipeek:eval", { id, code }, (resolve2) => {
3489
+ pendingEvals.set(id, resolve2);
3490
+ return () => {
3491
+ pendingEvals.delete(id);
3492
+ };
3493
+ }, 8e3);
3494
+ }
3495
+ return {
3496
+ name: "aipeek",
3497
+ apply: "serve",
3498
+ transformIndexHtml() {
3499
+ const patchCode = compilePatch();
3500
+ return [
3501
+ // Synchronous inline script — patches console/fetch/XHR/errors
3502
+ // BEFORE any ES modules execute
3503
+ {
3504
+ tag: "script",
3505
+ children: patchCode,
3506
+ injectTo: "head-prepend"
3507
+ },
3508
+ // Module script — collectors + HMR channel (can be deferred)
3509
+ {
3510
+ tag: "script",
3511
+ attrs: { type: "module" },
3512
+ children: `import '/@fs/${clientPath}'`,
3513
+ injectTo: "body"
3514
+ }
3515
+ ];
3516
+ },
3517
+ configureServer(_server) {
3518
+ server = _server;
3519
+ injectClaudeMd(server.config.root, server.config.server.port || 5173);
3520
+ server.hot.on("aipeek:state", (data) => {
3521
+ if (pendingResolve) {
3522
+ pendingResolve(data);
3523
+ pendingResolve = null;
3524
+ }
3525
+ });
3526
+ server.hot.on("aipeek:result", (data) => {
3527
+ const resolve2 = pendingActions.get(data.id);
3528
+ if (resolve2) {
3529
+ pendingActions.delete(data.id);
3530
+ resolve2(data);
3531
+ }
3532
+ });
3533
+ server.hot.on("aipeek:eval-result", (data) => {
3534
+ const resolve2 = pendingEvals.get(data.id);
3535
+ if (resolve2) {
3536
+ pendingEvals.delete(data.id);
3537
+ resolve2(data);
3538
+ }
3539
+ });
3540
+ server.hot.on("aipeek:dom", (data) => {
3541
+ if (pendingDom) {
3542
+ pendingDom(data.dom);
3543
+ pendingDom = null;
3544
+ }
3545
+ });
3546
+ server.hot.on("aipeek:screen", (data) => {
3547
+ if (pendingScreen) {
3548
+ pendingScreen(data.screen);
3549
+ pendingScreen = null;
3550
+ }
3551
+ });
3552
+ server.hot.on("vite:afterUpdate", () => {
3553
+ clearTimeout(pushTimer);
3554
+ pushTimer = setTimeout(async () => {
3555
+ try {
3556
+ const raw = await collectFromClient();
3557
+ const diff = diffState(lastRaw, raw);
3558
+ lastRaw = raw;
3559
+ if (!diff.clean) {
3560
+ const msg = emitDiff(diff);
3561
+ if (msg)
3562
+ server.config.logger.warn(msg);
3563
+ }
3564
+ } catch (e25) {
3565
+ }
3566
+ }, 500);
3567
+ });
3568
+ server.middlewares.use("/__aipeek", async (req, res) => {
3569
+ const url = new URL(req.url || "/", "http://localhost");
3570
+ const parts = url.pathname.split("/").filter(Boolean);
3571
+ const full = url.searchParams.has("full");
3572
+ try {
3573
+ if (parts[0] === "eval") {
3574
+ let code = url.searchParams.get("code") || "";
3575
+ if (!code && req.method === "POST")
3576
+ code = await readBody(req);
3577
+ if (!code) {
3578
+ res.writeHead(400, { "Content-Type": "text/plain; charset=utf-8" });
3579
+ res.end("eval needs ?code= or a POST body");
3580
+ return;
3581
+ }
3582
+ const r = await evalInClient(code);
3583
+ res.writeHead(r.ok ? 200 : 422, { "Content-Type": "text/plain; charset=utf-8" });
3584
+ res.end(r.ok ? _nullishCoalesce(r.value, () => ( "undefined")) : `error: ${r.error}`);
3585
+ return;
3586
+ }
3587
+ if (parts[0] === "dom") {
3588
+ const dom = await collectDomFromClient(
3589
+ url.searchParams.get("scope") || void 0,
3590
+ url.searchParams.get("sel") || void 0
3591
+ );
3592
+ res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
3593
+ res.end(dom || "(empty)");
3594
+ return;
3595
+ }
3596
+ if (parts[0] === "screen") {
3597
+ const screen = await collectScreenFromClient();
3598
+ res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
3599
+ res.end(screen || "(empty)");
3600
+ return;
3601
+ }
3602
+ if (parts[0] === "chain") {
3603
+ const body = await readBody(req);
3604
+ let steps;
3605
+ try {
3606
+ steps = JSON.parse(body);
3607
+ if (!Array.isArray(steps))
3608
+ throw new Error("body must be a JSON array");
3609
+ } catch (e) {
3610
+ res.writeHead(400, { "Content-Type": "text/plain; charset=utf-8" });
3611
+ res.end(`invalid chain body: ${e instanceof Error ? e.message : String(e)}`);
3612
+ return;
3613
+ }
3614
+ lastRaw = null;
3615
+ const lines = [];
3616
+ let lastUi = "";
3617
+ let allOk = true;
3618
+ for (let i = 0; i < steps.length; i++) {
3619
+ const { type, ...args } = steps[i];
3620
+ const check2 = resolveAction(type, args);
3621
+ if (!check2.valid) {
3622
+ lines.push(`[${i}] \u2717 ${type}: ${check2.error}`);
3623
+ allOk = false;
3624
+ break;
3625
+ }
3626
+ const r = await sendAction(type, args);
3627
+ lines.push(`[${i}] ${r.ok ? "\u2713" : "\u2717"} ${type}: ${r.ok ? r.detail || "ok" : r.error}`);
3628
+ if (r.screen)
3629
+ lines.push(r.screen.split("\n").map((l) => ` ${l}`).join("\n"));
3630
+ if (r.ui)
3631
+ lastUi = r.ui;
3632
+ if (!r.ok) {
3633
+ allOk = false;
3634
+ break;
3635
+ }
3636
+ }
3637
+ res.writeHead(allOk ? 200 : 422, { "Content-Type": "text/plain; charset=utf-8" });
3638
+ res.end(lastUi ? `${lines.join("\n")}
3639
+
3640
+ --- ui after ---
3641
+ ${lastUi}` : lines.join("\n"));
3642
+ return;
3643
+ }
3644
+ if (["click", "fill", "press", "wait", "screenshot"].includes(parts[0])) {
3645
+ const q = url.searchParams;
3646
+ const args = {
3647
+ sel: q.get("sel") || void 0,
3648
+ text: q.get("text") || void 0,
3649
+ value: q.has("value") ? q.get("value") : void 0,
3650
+ key: q.get("key") || void 0,
3651
+ timeout: q.has("timeout") ? Number(q.get("timeout")) : void 0,
3652
+ gone: q.has("gone") ? q.get("gone") !== "false" : void 0
3653
+ };
3654
+ const check2 = resolveAction(parts[0], args);
3655
+ if (!check2.valid) {
3656
+ res.writeHead(400, { "Content-Type": "text/plain; charset=utf-8" });
3657
+ res.end(check2.error);
3658
+ return;
3659
+ }
3660
+ const result = await sendAction(parts[0], args);
3661
+ lastRaw = null;
3662
+ if (parts[0] === "screenshot" && result.dataUrl) {
3663
+ const dir = _path.resolve.call(void 0, server.config.root, ".aipeek");
3664
+ _fs.mkdirSync.call(void 0, dir, { recursive: true });
3665
+ const name = q.get("out") || `shot-${result.dataUrl.length}.png`;
3666
+ const file = _path.resolve.call(void 0, dir, name);
3667
+ _fs.writeFileSync.call(void 0, file, _buffer.Buffer.from(result.dataUrl.split(",")[1], "base64"));
3668
+ res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
3669
+ res.end(`saved: ${file}`);
3670
+ return;
3671
+ }
3672
+ res.writeHead(result.ok ? 200 : 422, { "Content-Type": "text/plain; charset=utf-8" });
3673
+ const head = result.ok ? result.detail || "ok" : `${result.error}${result.detail ? `
3674
+
3675
+ clickable: ${result.detail}` : ""}`;
3676
+ res.end(result.ui ? `${head}
3677
+
3678
+ --- ui after ---
3679
+ ${result.ui}` : head);
3680
+ return;
3681
+ }
3682
+ if (parts[0] === "check") {
3683
+ const raw2 = await collectFromClient();
3684
+ lastRaw = raw2;
3685
+ const result = check(raw2);
3686
+ const output = emitCheck(result);
3687
+ res.writeHead(result.pass ? 200 : 417, { "Content-Type": "text/plain; charset=utf-8" });
3688
+ res.end(output);
3689
+ return;
3690
+ }
3691
+ if (parts.length >= 1) {
3692
+ if (!lastRaw)
3693
+ lastRaw = await collectFromClient();
3694
+ const result = detail(lastRaw, parts[0], parts[1], full);
3695
+ if (result !== null) {
3696
+ res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
3697
+ res.end(result);
3698
+ return;
3699
+ }
3700
+ res.writeHead(404, { "Content-Type": "text/plain" });
3701
+ res.end(`not found: ${parts.join("/")}`);
3702
+ return;
3703
+ }
3704
+ const raw = await collectFromClient();
3705
+ lastRaw = raw;
3706
+ if (full) {
3707
+ const compacted = compact(raw);
3708
+ const output = emit(compacted);
3709
+ res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
3710
+ res.end(output);
3711
+ } else {
3712
+ const output = emitSummary(raw);
3713
+ res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
3714
+ res.end(output);
3715
+ }
3716
+ } catch (err) {
3717
+ res.writeHead(504, { "Content-Type": "text/plain" });
3718
+ res.end(err instanceof Error ? err.message : "unknown error");
3719
+ }
3720
+ });
3721
+ }
3722
+ };
3723
+ }
3724
+
3725
+
3726
+
3727
+
3728
+
3729
+
3730
+
3731
+
3732
+ exports.check = check; exports.diffState = diffState; exports.emitSummary = emitSummary; exports.emitCheck = emitCheck; exports.emitDiff = emitDiff; exports.aipeekPlugin = aipeekPlugin;