@ggui-ai/ui-gen 0.20.0 → 0.22.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.
Files changed (93) hide show
  1. package/dist/adapters/base.d.ts +7 -0
  2. package/dist/adapters/base.js +1 -0
  3. package/dist/adapters/base.js.map +1 -1
  4. package/dist/adapters/generation-dispatch.d.ts +17 -3
  5. package/dist/adapters/generation-dispatch.js +1078 -3464
  6. package/dist/adapters/generation-dispatch.js.map +1 -1
  7. package/dist/adapters/index.js +60 -3
  8. package/dist/adapters/index.js.map +1 -1
  9. package/dist/advanced/index.d.ts +4 -4
  10. package/dist/advanced/index.js +1346 -3557
  11. package/dist/advanced/index.js.map +1 -1
  12. package/dist/blueprint-validator.js +10 -3
  13. package/dist/blueprint-validator.js.map +1 -1
  14. package/dist/boilerplate.js +2 -2
  15. package/dist/boilerplate.js.map +1 -1
  16. package/dist/check/index.d.ts +1 -1
  17. package/dist/check/index.js.map +1 -1
  18. package/dist/{create-ui-generator-CxPvudbs.d.ts → create-ui-generator-BEkzEtNz.d.ts} +2 -2
  19. package/dist/{dispatch-N8wdNOX-.d.ts → dispatch-DJNpQ7DI.d.ts} +1 -1
  20. package/dist/evaluation/axis-checks/index.d.ts +3 -3
  21. package/dist/evaluation/axis-checks/index.js.map +1 -1
  22. package/dist/evaluation/axis-checks/registry.d.ts +1 -1
  23. package/dist/evaluation/index.d.ts +38 -6
  24. package/dist/evaluation/index.js +670 -3374
  25. package/dist/evaluation/index.js.map +1 -1
  26. package/dist/harness/check/runtime-render/index.d.ts +2 -2
  27. package/dist/harness/check/runtime-render/index.js +10 -3
  28. package/dist/harness/check/runtime-render/index.js.map +1 -1
  29. package/dist/harness/check/runtime-render/render-check-worker.js +5 -3
  30. package/dist/harness/check/runtime-render/render-check-worker.js.map +1 -1
  31. package/dist/harness/index.d.ts +2 -2
  32. package/dist/harness/index.js +587 -30
  33. package/dist/harness/index.js.map +1 -1
  34. package/dist/harness/llm-trace-sink.d.ts +7 -1
  35. package/dist/harness/llm-trace-sink.js.map +1 -1
  36. package/dist/harness/prompts.js +1 -1
  37. package/dist/harness/prompts.js.map +1 -1
  38. package/dist/harness/result-types.d.ts +15 -2
  39. package/dist/harness/result-types.js.map +1 -1
  40. package/dist/harness/runtime.d.ts +11 -2
  41. package/dist/harness/runtime.js +3 -3
  42. package/dist/harness/runtime.js.map +1 -1
  43. package/dist/harness/types-public.d.ts +1 -1
  44. package/dist/harness/types-public.js +2 -2
  45. package/dist/harness/types-public.js.map +1 -1
  46. package/dist/harness/validator-trace-sink.d.ts +1 -1
  47. package/dist/index.d.ts +23 -7
  48. package/dist/index.js +1346 -3557
  49. package/dist/index.js.map +1 -1
  50. package/dist/{llm-router-D7fjBhtr.d.ts → llm-router-DwwUK1bz.d.ts} +16 -3
  51. package/dist/patch.d.ts +1 -1
  52. package/dist/providers/index.js +5 -4
  53. package/dist/providers/index.js.map +1 -1
  54. package/dist/{render-check-WfOVO9kU.d.ts → render-check-C0CqVceF.d.ts} +17 -0
  55. package/dist/{types-public-DKR_h70H.d.ts → types-public-mM_-1Yk3.d.ts} +59 -1
  56. package/dist/validation/index.d.ts +1 -1
  57. package/dist/validation/index.js +1 -1
  58. package/dist/validation/index.js.map +1 -1
  59. package/dist/workflows.d.ts +1 -1
  60. package/package.json +16 -12
  61. package/src/adapters/base.ts +8 -0
  62. package/src/adapters/claude/claude-code-login.ts +128 -0
  63. package/src/adapters/claude/sdk.ts +9 -1
  64. package/src/adapters/generation-dispatch.ts +19 -2
  65. package/src/adapters/openai/tokens.ts +18 -0
  66. package/src/adapters/provider-router.ts +28 -0
  67. package/src/boilerplate/generate.ts +19 -4
  68. package/src/boilerplate/hard-sections.ts +1 -1
  69. package/src/boilerplate/templates/layouts/chat-mobile.tsx.tmpl +7 -3
  70. package/src/boilerplate/templates/layouts/chat-universal.tsx.tmpl +7 -3
  71. package/src/contract-context.ts +1 -1
  72. package/src/create-ui-generator.ts +49 -10
  73. package/src/evaluation/design-identity.ts +16 -5
  74. package/src/evaluation/index.ts +1 -0
  75. package/src/evaluation/llm-evaluator.ts +40 -13
  76. package/src/evaluation/types-public.ts +58 -0
  77. package/src/evaluation/visual-evaluator.ts +240 -30
  78. package/src/generator-build.ts +158 -0
  79. package/src/harness/check/runtime-render/adapter.ts +9 -0
  80. package/src/harness/check/runtime-render/render-check.ts +26 -5
  81. package/src/harness/claude-code-login-query.ts +529 -0
  82. package/src/harness/coding/assemble-result.ts +18 -2
  83. package/src/harness/coding/generate-task-runner.ts +75 -36
  84. package/src/harness/coding/run-coding-turn.ts +9 -0
  85. package/src/harness/coding/run-eval-round.ts +338 -38
  86. package/src/harness/enforced-coding.ts +20 -0
  87. package/src/harness/llm-router.ts +390 -55
  88. package/src/harness/llm-trace-sink.ts +7 -1
  89. package/src/harness/result-types.ts +14 -0
  90. package/src/harness/runtime.ts +6 -0
  91. package/src/index.ts +2 -1
  92. package/src/providers/openai.ts +31 -19
  93. package/src/validation/primitives.ts +1 -1
@@ -1,59 +1,26 @@
1
- import { readFileSync, readdirSync, statSync, mkdirSync, writeFileSync, unlinkSync, existsSync, rm, createReadStream, createWriteStream } from 'fs';
2
- import 'fs/promises';
3
- import { tmpdir } from 'os';
4
- import { resolve, dirname, join, basename } from 'path';
5
- import { Readable } from 'stream';
6
- import { pipeline } from 'stream/promises';
7
- import { createBrotliDecompress, createUnzip } from 'zlib';
8
- import { fileURLToPath } from 'url';
9
1
  import { query, createSdkMcpServer, tool } from '@anthropic-ai/claude-agent-sdk';
2
+ import { anthropicRejectsForcedToolChoice, normalizeAnthropicModelId, listContractGadgets, HOOK_NAME_RE, STDLIB_GADGETS_PACKAGE, isRecord, anthropicRejectsSamplingParams, APP_GENERATION_PROFILE_BOUNDS } from '@ggui-ai/protocol';
10
3
  import Anthropic from '@anthropic-ai/sdk';
11
4
  import { z } from 'zod';
12
5
  import { LUCIDE_ICON_NAMES, maxWidth } from '@ggui-ai/design';
13
- import { listContractGadgets, HOOK_NAME_RE, STDLIB_GADGETS_PACKAGE, APP_GENERATION_PROFILE_BOUNDS } from '@ggui-ai/protocol';
14
6
  import { createHash } from 'crypto';
15
7
  import { build } from 'esbuild';
16
8
  import { getCssTokens, composeThemeCss, fillFitRule } from '@ggui-ai/design/rendering';
9
+ import { readFileSync, readdirSync, statSync, mkdtempSync, writeFileSync, rmSync, existsSync } from 'fs';
10
+ import { resolve, relative, dirname } from 'path';
11
+ import { fileURLToPath } from 'url';
17
12
  import { createRequire } from 'module';
13
+ import { tmpdir } from 'os';
18
14
 
19
- var __create = Object.create;
20
15
  var __defProp = Object.defineProperty;
21
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
22
16
  var __getOwnPropNames = Object.getOwnPropertyNames;
23
- var __getProtoOf = Object.getPrototypeOf;
24
- var __hasOwnProp = Object.prototype.hasOwnProperty;
25
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
26
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
27
- }) : x)(function(x) {
28
- if (typeof require !== "undefined") return require.apply(this, arguments);
29
- throw Error('Dynamic require of "' + x + '" is not supported');
30
- });
31
17
  var __esm = (fn, res) => function __init() {
32
18
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
33
19
  };
34
- var __commonJS = (cb, mod) => function __require2() {
35
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
36
- };
37
20
  var __export = (target, all) => {
38
21
  for (var name in all)
39
22
  __defProp(target, name, { get: all[name], enumerable: true });
40
23
  };
41
- var __copyProps = (to, from, except, desc) => {
42
- if (from && typeof from === "object" || typeof from === "function") {
43
- for (let key of __getOwnPropNames(from))
44
- if (!__hasOwnProp.call(to, key) && key !== except)
45
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
46
- }
47
- return to;
48
- };
49
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
50
- // If the importer is in node compatibility mode or this is not an ESM
51
- // file that has been converted to a CommonJS file using a Babel-
52
- // compatible transform (i.e. "__esModule" has not been set), then set
53
- // "default" to the CommonJS "module.exports" for node compatibility.
54
- __defProp(target, "default", { value: mod, enumerable: true }) ,
55
- mod
56
- ));
57
24
 
58
25
  // src/adapters/openrouter/types.ts
59
26
  var OpenRouterError;
@@ -132,3287 +99,38 @@ var init_client = __esm({
132
99
  if (!response.ok) {
133
100
  const errorBody = await response.json().catch(() => ({ error: { message: response.statusText } }));
134
101
  const message = errorBody.error?.message ?? response.statusText;
135
- throw new OpenRouterError(message, response.status, void 0, response.headers);
136
- }
137
- if (!response.body) {
138
- throw new OpenRouterError("No response body for streaming request", 500);
139
- }
140
- const reader = response.body.getReader();
141
- const decoder = new TextDecoder();
142
- let buffer = "";
143
- try {
144
- while (true) {
145
- const { done, value } = await reader.read();
146
- if (done) break;
147
- buffer += decoder.decode(value, { stream: true });
148
- const lines = buffer.split("\n");
149
- buffer = lines.pop() ?? "";
150
- for (const line of lines) {
151
- const trimmed = line.trim();
152
- if (!trimmed || trimmed.startsWith(":")) continue;
153
- if (trimmed === "data: [DONE]") return;
154
- if (!trimmed.startsWith("data: ")) continue;
155
- const json = trimmed.slice("data: ".length);
156
- try {
157
- yield JSON.parse(json);
158
- } catch {
159
- }
160
- }
161
- }
162
- } finally {
163
- reader.releaseLock();
164
- }
165
- }
166
- };
167
- }
168
- });
169
-
170
- // ../../node_modules/events-universal/default.js
171
- var require_default = __commonJS({
172
- "../../node_modules/events-universal/default.js"(exports, module) {
173
- module.exports = __require("events");
174
- }
175
- });
176
-
177
- // ../../node_modules/fast-fifo/fixed-size.js
178
- var require_fixed_size = __commonJS({
179
- "../../node_modules/fast-fifo/fixed-size.js"(exports, module) {
180
- module.exports = class FixedFIFO {
181
- constructor(hwm) {
182
- if (!(hwm > 0) || (hwm - 1 & hwm) !== 0) throw new Error("Max size for a FixedFIFO should be a power of two");
183
- this.buffer = new Array(hwm);
184
- this.mask = hwm - 1;
185
- this.top = 0;
186
- this.btm = 0;
187
- this.next = null;
188
- }
189
- clear() {
190
- this.top = this.btm = 0;
191
- this.next = null;
192
- this.buffer.fill(void 0);
193
- }
194
- push(data) {
195
- if (this.buffer[this.top] !== void 0) return false;
196
- this.buffer[this.top] = data;
197
- this.top = this.top + 1 & this.mask;
198
- return true;
199
- }
200
- shift() {
201
- const last = this.buffer[this.btm];
202
- if (last === void 0) return void 0;
203
- this.buffer[this.btm] = void 0;
204
- this.btm = this.btm + 1 & this.mask;
205
- return last;
206
- }
207
- peek() {
208
- return this.buffer[this.btm];
209
- }
210
- isEmpty() {
211
- return this.buffer[this.btm] === void 0;
212
- }
213
- };
214
- }
215
- });
216
-
217
- // ../../node_modules/fast-fifo/index.js
218
- var require_fast_fifo = __commonJS({
219
- "../../node_modules/fast-fifo/index.js"(exports, module) {
220
- var FixedFIFO = require_fixed_size();
221
- module.exports = class FastFIFO {
222
- constructor(hwm) {
223
- this.hwm = hwm || 16;
224
- this.head = new FixedFIFO(this.hwm);
225
- this.tail = this.head;
226
- this.length = 0;
227
- }
228
- clear() {
229
- this.head = this.tail;
230
- this.head.clear();
231
- this.length = 0;
232
- }
233
- push(val) {
234
- this.length++;
235
- if (!this.head.push(val)) {
236
- const prev = this.head;
237
- this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length);
238
- this.head.push(val);
239
- }
240
- }
241
- shift() {
242
- if (this.length !== 0) this.length--;
243
- const val = this.tail.shift();
244
- if (val === void 0 && this.tail.next) {
245
- const next = this.tail.next;
246
- this.tail.next = null;
247
- this.tail = next;
248
- return this.tail.shift();
249
- }
250
- return val;
251
- }
252
- peek() {
253
- const val = this.tail.peek();
254
- if (val === void 0 && this.tail.next) return this.tail.next.peek();
255
- return val;
256
- }
257
- isEmpty() {
258
- return this.length === 0;
259
- }
260
- };
261
- }
262
- });
263
-
264
- // ../../node_modules/b4a/index.js
265
- var require_b4a = __commonJS({
266
- "../../node_modules/b4a/index.js"(exports, module) {
267
- function isBuffer(value) {
268
- return Buffer.isBuffer(value) || value instanceof Uint8Array;
269
- }
270
- function isEncoding(encoding) {
271
- return Buffer.isEncoding(encoding);
272
- }
273
- function alloc(size, fill2, encoding) {
274
- return Buffer.alloc(size, fill2, encoding);
275
- }
276
- function allocUnsafe(size) {
277
- return Buffer.allocUnsafe(size);
278
- }
279
- function allocUnsafeSlow(size) {
280
- return Buffer.allocUnsafeSlow(size);
281
- }
282
- function byteLength(string, encoding) {
283
- return Buffer.byteLength(string, encoding);
284
- }
285
- function compare(a, b) {
286
- return Buffer.compare(a, b);
287
- }
288
- function concat(buffers, totalLength) {
289
- return Buffer.concat(buffers, totalLength);
290
- }
291
- function copy(source, target, targetStart, start, end) {
292
- return toBuffer(source).copy(target, targetStart, start, end);
293
- }
294
- function equals(a, b) {
295
- return toBuffer(a).equals(b);
296
- }
297
- function fill(buffer, value, offset, end, encoding) {
298
- return toBuffer(buffer).fill(value, offset, end, encoding);
299
- }
300
- function from(value, encodingOrOffset, length) {
301
- return Buffer.from(value, encodingOrOffset, length);
302
- }
303
- function includes(buffer, value, byteOffset, encoding) {
304
- return toBuffer(buffer).includes(value, byteOffset, encoding);
305
- }
306
- function indexOf(buffer, value, byfeOffset, encoding) {
307
- return toBuffer(buffer).indexOf(value, byfeOffset, encoding);
308
- }
309
- function lastIndexOf(buffer, value, byteOffset, encoding) {
310
- return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding);
311
- }
312
- function swap16(buffer) {
313
- return toBuffer(buffer).swap16();
314
- }
315
- function swap32(buffer) {
316
- return toBuffer(buffer).swap32();
317
- }
318
- function swap64(buffer) {
319
- return toBuffer(buffer).swap64();
320
- }
321
- function toBuffer(buffer) {
322
- if (Buffer.isBuffer(buffer)) return buffer;
323
- return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength);
324
- }
325
- function toString(buffer, encoding, start, end) {
326
- return toBuffer(buffer).toString(encoding, start, end);
327
- }
328
- function write(buffer, string, offset, length, encoding) {
329
- return toBuffer(buffer).write(string, offset, length, encoding);
330
- }
331
- function readDoubleBE(buffer, offset) {
332
- return toBuffer(buffer).readDoubleBE(offset);
333
- }
334
- function readDoubleLE(buffer, offset) {
335
- return toBuffer(buffer).readDoubleLE(offset);
336
- }
337
- function readFloatBE(buffer, offset) {
338
- return toBuffer(buffer).readFloatBE(offset);
339
- }
340
- function readFloatLE(buffer, offset) {
341
- return toBuffer(buffer).readFloatLE(offset);
342
- }
343
- function readInt32BE(buffer, offset) {
344
- return toBuffer(buffer).readInt32BE(offset);
345
- }
346
- function readInt32LE(buffer, offset) {
347
- return toBuffer(buffer).readInt32LE(offset);
348
- }
349
- function readUInt32BE(buffer, offset) {
350
- return toBuffer(buffer).readUInt32BE(offset);
351
- }
352
- function readUInt32LE(buffer, offset) {
353
- return toBuffer(buffer).readUInt32LE(offset);
354
- }
355
- function writeDoubleBE(buffer, value, offset) {
356
- return toBuffer(buffer).writeDoubleBE(value, offset);
357
- }
358
- function writeDoubleLE(buffer, value, offset) {
359
- return toBuffer(buffer).writeDoubleLE(value, offset);
360
- }
361
- function writeFloatBE(buffer, value, offset) {
362
- return toBuffer(buffer).writeFloatBE(value, offset);
363
- }
364
- function writeFloatLE(buffer, value, offset) {
365
- return toBuffer(buffer).writeFloatLE(value, offset);
366
- }
367
- function writeInt32BE(buffer, value, offset) {
368
- return toBuffer(buffer).writeInt32BE(value, offset);
369
- }
370
- function writeInt32LE(buffer, value, offset) {
371
- return toBuffer(buffer).writeInt32LE(value, offset);
372
- }
373
- function writeUInt32BE(buffer, value, offset) {
374
- return toBuffer(buffer).writeUInt32BE(value, offset);
375
- }
376
- function writeUInt32LE(buffer, value, offset) {
377
- return toBuffer(buffer).writeUInt32LE(value, offset);
378
- }
379
- module.exports = {
380
- isBuffer,
381
- isEncoding,
382
- alloc,
383
- allocUnsafe,
384
- allocUnsafeSlow,
385
- byteLength,
386
- compare,
387
- concat,
388
- copy,
389
- equals,
390
- fill,
391
- from,
392
- includes,
393
- indexOf,
394
- lastIndexOf,
395
- swap16,
396
- swap32,
397
- swap64,
398
- toBuffer,
399
- toString,
400
- write,
401
- readDoubleBE,
402
- readDoubleLE,
403
- readFloatBE,
404
- readFloatLE,
405
- readInt32BE,
406
- readInt32LE,
407
- readUInt32BE,
408
- readUInt32LE,
409
- writeDoubleBE,
410
- writeDoubleLE,
411
- writeFloatBE,
412
- writeFloatLE,
413
- writeInt32BE,
414
- writeInt32LE,
415
- writeUInt32BE,
416
- writeUInt32LE
417
- };
418
- }
419
- });
420
-
421
- // ../../node_modules/text-decoder/lib/pass-through-decoder.js
422
- var require_pass_through_decoder = __commonJS({
423
- "../../node_modules/text-decoder/lib/pass-through-decoder.js"(exports, module) {
424
- var b4a = require_b4a();
425
- module.exports = class PassThroughDecoder {
426
- constructor(encoding) {
427
- this.encoding = encoding;
428
- }
429
- get remaining() {
430
- return 0;
431
- }
432
- decode(data) {
433
- return b4a.toString(data, this.encoding);
434
- }
435
- flush() {
436
- return "";
437
- }
438
- };
439
- }
440
- });
441
-
442
- // ../../node_modules/text-decoder/lib/utf8-decoder.js
443
- var require_utf8_decoder = __commonJS({
444
- "../../node_modules/text-decoder/lib/utf8-decoder.js"(exports, module) {
445
- var b4a = require_b4a();
446
- module.exports = class UTF8Decoder {
447
- constructor() {
448
- this._reset();
449
- }
450
- get remaining() {
451
- return this.bytesSeen;
452
- }
453
- decode(data) {
454
- if (data.byteLength === 0) return "";
455
- if (this.bytesNeeded === 0 && trailingIncomplete(data, 0) === 0) {
456
- this.bytesSeen = trailingBytesSeen(data);
457
- return b4a.toString(data, "utf8");
458
- }
459
- let result = "";
460
- let start = 0;
461
- if (this.bytesNeeded > 0) {
462
- while (start < data.byteLength) {
463
- const byte = data[start];
464
- if (byte < this.lowerBoundary || byte > this.upperBoundary) {
465
- result += "\uFFFD";
466
- this._reset();
467
- break;
468
- }
469
- this.lowerBoundary = 128;
470
- this.upperBoundary = 191;
471
- this.codePoint = this.codePoint << 6 | byte & 63;
472
- this.bytesSeen++;
473
- start++;
474
- if (this.bytesSeen === this.bytesNeeded) {
475
- result += String.fromCodePoint(this.codePoint);
476
- this._reset();
477
- break;
478
- }
479
- }
480
- if (this.bytesNeeded > 0) return result;
481
- }
482
- const trailing = trailingIncomplete(data, start);
483
- const end = data.byteLength - trailing;
484
- if (end > start) result += b4a.toString(data, "utf8", start, end);
485
- for (let i = end; i < data.byteLength; i++) {
486
- const byte = data[i];
487
- if (this.bytesNeeded === 0) {
488
- if (byte <= 127) {
489
- this.bytesSeen = 0;
490
- result += String.fromCharCode(byte);
491
- } else if (byte >= 194 && byte <= 223) {
492
- this.bytesNeeded = 2;
493
- this.bytesSeen = 1;
494
- this.codePoint = byte & 31;
495
- } else if (byte >= 224 && byte <= 239) {
496
- if (byte === 224) this.lowerBoundary = 160;
497
- else if (byte === 237) this.upperBoundary = 159;
498
- this.bytesNeeded = 3;
499
- this.bytesSeen = 1;
500
- this.codePoint = byte & 15;
501
- } else if (byte >= 240 && byte <= 244) {
502
- if (byte === 240) this.lowerBoundary = 144;
503
- else if (byte === 244) this.upperBoundary = 143;
504
- this.bytesNeeded = 4;
505
- this.bytesSeen = 1;
506
- this.codePoint = byte & 7;
507
- } else {
508
- this.bytesSeen = 1;
509
- result += "\uFFFD";
510
- }
511
- continue;
512
- }
513
- if (byte < this.lowerBoundary || byte > this.upperBoundary) {
514
- result += "\uFFFD";
515
- i--;
516
- this._reset();
517
- continue;
518
- }
519
- this.lowerBoundary = 128;
520
- this.upperBoundary = 191;
521
- this.codePoint = this.codePoint << 6 | byte & 63;
522
- this.bytesSeen++;
523
- if (this.bytesSeen === this.bytesNeeded) {
524
- result += String.fromCodePoint(this.codePoint);
525
- this._reset();
526
- }
527
- }
528
- return result;
529
- }
530
- flush() {
531
- const result = this.bytesNeeded > 0 ? "\uFFFD" : "";
532
- this._reset();
533
- return result;
534
- }
535
- _reset() {
536
- this.codePoint = 0;
537
- this.bytesNeeded = 0;
538
- this.bytesSeen = 0;
539
- this.lowerBoundary = 128;
540
- this.upperBoundary = 191;
541
- }
542
- };
543
- function trailingIncomplete(data, start) {
544
- const len = data.byteLength;
545
- if (len <= start) return 0;
546
- const limit = Math.max(start, len - 4);
547
- let i = len - 1;
548
- while (i > limit && (data[i] & 192) === 128) i--;
549
- if (i < start) return 0;
550
- const byte = data[i];
551
- let needed;
552
- if (byte <= 127) return 0;
553
- if (byte >= 194 && byte <= 223) needed = 2;
554
- else if (byte >= 224 && byte <= 239) needed = 3;
555
- else if (byte >= 240 && byte <= 244) needed = 4;
556
- else return 0;
557
- const available = len - i;
558
- return available < needed ? available : 0;
559
- }
560
- function trailingBytesSeen(data) {
561
- const len = data.byteLength;
562
- if (len === 0) return 0;
563
- const last = data[len - 1];
564
- if (last <= 127) return 0;
565
- if ((last & 192) !== 128) return 1;
566
- const limit = Math.max(0, len - 4);
567
- let i = len - 2;
568
- while (i >= limit && (data[i] & 192) === 128) i--;
569
- if (i < 0) return 1;
570
- const first = data[i];
571
- let needed;
572
- if (first >= 194 && first <= 223) needed = 2;
573
- else if (first >= 224 && first <= 239) needed = 3;
574
- else if (first >= 240 && first <= 244) needed = 4;
575
- else return 1;
576
- if (len - i !== needed) return 1;
577
- if (needed >= 3) {
578
- const second = data[i + 1];
579
- if (first === 224 && second < 160) return 1;
580
- if (first === 237 && second > 159) return 1;
581
- if (first === 240 && second < 144) return 1;
582
- if (first === 244 && second > 143) return 1;
583
- }
584
- return 0;
585
- }
586
- }
587
- });
588
-
589
- // ../../node_modules/text-decoder/index.js
590
- var require_text_decoder = __commonJS({
591
- "../../node_modules/text-decoder/index.js"(exports, module) {
592
- var PassThroughDecoder = require_pass_through_decoder();
593
- var UTF8Decoder = require_utf8_decoder();
594
- module.exports = class TextDecoder {
595
- constructor(encoding = "utf8") {
596
- this.encoding = normalizeEncoding(encoding);
597
- switch (this.encoding) {
598
- case "utf8":
599
- this.decoder = new UTF8Decoder();
600
- break;
601
- case "utf16le":
602
- case "base64":
603
- throw new Error("Unsupported encoding: " + this.encoding);
604
- default:
605
- this.decoder = new PassThroughDecoder(this.encoding);
606
- }
607
- }
608
- get remaining() {
609
- return this.decoder.remaining;
610
- }
611
- push(data) {
612
- if (typeof data === "string") return data;
613
- return this.decoder.decode(data);
614
- }
615
- // For Node.js compatibility
616
- write(data) {
617
- return this.push(data);
618
- }
619
- end(data) {
620
- let result = "";
621
- if (data) result = this.push(data);
622
- result += this.decoder.flush();
623
- return result;
624
- }
625
- };
626
- function normalizeEncoding(encoding) {
627
- encoding = encoding.toLowerCase();
628
- switch (encoding) {
629
- case "utf8":
630
- case "utf-8":
631
- return "utf8";
632
- case "ucs2":
633
- case "ucs-2":
634
- case "utf16le":
635
- case "utf-16le":
636
- return "utf16le";
637
- case "latin1":
638
- case "binary":
639
- return "latin1";
640
- case "base64":
641
- case "ascii":
642
- case "hex":
643
- return encoding;
644
- default:
645
- throw new Error("Unknown encoding: " + encoding);
646
- }
647
- }
648
- }
649
- });
650
-
651
- // ../../node_modules/streamx/lib/errors.js
652
- var require_errors = __commonJS({
653
- "../../node_modules/streamx/lib/errors.js"(exports, module) {
654
- module.exports = class StreamError extends Error {
655
- constructor(msg, code, fn = StreamError) {
656
- super(msg);
657
- this.code = code;
658
- if (Error.captureStackTrace) {
659
- Error.captureStackTrace(this, fn);
660
- }
661
- }
662
- static isStreamDestroyed(err) {
663
- return err && err.code === "STREAM_DESTROYED";
664
- }
665
- static isPrematureClose(err) {
666
- return err && err.code === "PREMATURE_CLOSE";
667
- }
668
- static isAborted(err) {
669
- return err && err.code === "ABORTED";
670
- }
671
- static isBadArgument(err) {
672
- return err && err.code === "BAD_ARGUMENT";
673
- }
674
- get name() {
675
- return "StreamError";
676
- }
677
- static STREAM_DESTROYED() {
678
- return new StreamError("Stream was destroyed", "STREAM_DESTROYED", StreamError.STREAM_DESTROYED);
679
- }
680
- static PREMATURE_CLOSE(msg = "Premature close") {
681
- return new StreamError(msg, "PREMATURE_CLOSE", StreamError.PREMATURE_CLOSE);
682
- }
683
- static ABORTED() {
684
- return new StreamError("Stream aborted", "ABORTED", StreamError.ABORTED);
685
- }
686
- static BAD_ARGUMENT(msg = "Bad argument") {
687
- return new StreamError(msg, "BAD_ARGUMENT", StreamError.BAD_ARGUMENT);
688
- }
689
- };
690
- }
691
- });
692
-
693
- // ../../node_modules/streamx/index.js
694
- var require_streamx = __commonJS({
695
- "../../node_modules/streamx/index.js"(exports, module) {
696
- var { EventEmitter } = require_default();
697
- var FIFO = require_fast_fifo();
698
- var TextDecoder2 = require_text_decoder();
699
- var StreamError = require_errors();
700
- var qmt = typeof queueMicrotask === "undefined" ? (fn) => global.process.nextTick(fn) : queueMicrotask;
701
- var MAX = (1 << 29) - 1;
702
- var OPENING = 1;
703
- var PREDESTROYING = 2;
704
- var DESTROYING = 4;
705
- var DESTROYED = 8;
706
- var NOT_OPENING = MAX ^ OPENING;
707
- var NOT_PREDESTROYING = MAX ^ PREDESTROYING;
708
- var READ_ACTIVE = 1 << 4;
709
- var READ_UPDATING = 2 << 4;
710
- var READ_PRIMARY = 4 << 4;
711
- var READ_QUEUED = 8 << 4;
712
- var READ_RESUMED = 16 << 4;
713
- var READ_PIPE_DRAINED = 32 << 4;
714
- var READ_ENDING = 64 << 4;
715
- var READ_EMIT_DATA = 128 << 4;
716
- var READ_EMIT_READABLE = 256 << 4;
717
- var READ_EMITTED_READABLE = 512 << 4;
718
- var READ_DONE = 1024 << 4;
719
- var READ_NEXT_TICK = 2048 << 4;
720
- var READ_NEEDS_PUSH = 4096 << 4;
721
- var READ_READ_AHEAD = 8192 << 4;
722
- var READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED;
723
- var READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH;
724
- var READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE;
725
- var READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED;
726
- var READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD;
727
- var READ_NOT_ACTIVE = MAX ^ READ_ACTIVE;
728
- var READ_NON_PRIMARY = MAX ^ READ_PRIMARY;
729
- var READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH);
730
- var READ_PUSHED = MAX ^ READ_NEEDS_PUSH;
731
- var READ_PAUSED = MAX ^ READ_RESUMED;
732
- var READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE);
733
- var READ_NOT_ENDING = MAX ^ READ_ENDING;
734
- var READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING;
735
- var READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK;
736
- var READ_NOT_UPDATING = MAX ^ READ_UPDATING;
737
- var READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD;
738
- var READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD;
739
- var WRITE_ACTIVE = 1 << 18;
740
- var WRITE_UPDATING = 2 << 18;
741
- var WRITE_PRIMARY = 4 << 18;
742
- var WRITE_QUEUED = 8 << 18;
743
- var WRITE_UNDRAINED = 16 << 18;
744
- var WRITE_DONE = 32 << 18;
745
- var WRITE_EMIT_DRAIN = 64 << 18;
746
- var WRITE_NEXT_TICK = 128 << 18;
747
- var WRITE_WRITING = 256 << 18;
748
- var WRITE_FINISHING = 512 << 18;
749
- var WRITE_CORKED = 1024 << 18;
750
- var WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING);
751
- var WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY;
752
- var WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING);
753
- var WRITE_DRAINED = MAX ^ WRITE_UNDRAINED;
754
- var WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED;
755
- var WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK;
756
- var WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING;
757
- var WRITE_NOT_CORKED = MAX ^ WRITE_CORKED;
758
- var ACTIVE = READ_ACTIVE | WRITE_ACTIVE;
759
- var NOT_ACTIVE = MAX ^ ACTIVE;
760
- var DONE = READ_DONE | WRITE_DONE;
761
- var DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING;
762
- var OPEN_STATUS = DESTROY_STATUS | OPENING;
763
- var AUTO_DESTROY = DESTROY_STATUS | DONE;
764
- var NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY;
765
- var ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK;
766
- var TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE;
767
- var IS_OPENING = OPEN_STATUS | TICKING;
768
- var READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE;
769
- var READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED;
770
- var READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED;
771
- var READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE;
772
- var SHOULD_NOT_READ = OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD;
773
- var READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE;
774
- var READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY;
775
- var READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING;
776
- var WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE;
777
- var WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED;
778
- var WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE;
779
- var WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE;
780
- var WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED;
781
- var WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE;
782
- var WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING;
783
- var WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE;
784
- var WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE;
785
- var WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY;
786
- var WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS;
787
- var asyncIterator = Symbol.asyncIterator || /* @__PURE__ */ Symbol("asyncIterator");
788
- var WritableState = class {
789
- constructor(stream, { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}) {
790
- this.stream = stream;
791
- this.queue = new FIFO();
792
- this.highWaterMark = highWaterMark;
793
- this.buffered = 0;
794
- this.error = null;
795
- this.pipeline = null;
796
- this.drains = null;
797
- this.byteLength = byteLengthWritable || byteLength || defaultByteLength;
798
- this.map = mapWritable || map;
799
- this.afterWrite = afterWrite.bind(this);
800
- this.afterUpdateNextTick = updateWriteNT.bind(this);
801
- }
802
- get ending() {
803
- return (this.stream._duplexState & WRITE_FINISHING) !== 0;
804
- }
805
- get ended() {
806
- return (this.stream._duplexState & WRITE_DONE) !== 0;
807
- }
808
- push(data) {
809
- if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false;
810
- if (this.map !== null) data = this.map(data);
811
- this.buffered += this.byteLength(data);
812
- this.queue.push(data);
813
- if (this.buffered < this.highWaterMark) {
814
- this.stream._duplexState |= WRITE_QUEUED;
815
- return true;
816
- }
817
- this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED;
818
- return false;
819
- }
820
- shift() {
821
- const data = this.queue.shift();
822
- this.buffered -= this.byteLength(data);
823
- if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED;
824
- return data;
825
- }
826
- end(data) {
827
- if (typeof data === "function") {
828
- this.stream.once("finish", data);
829
- } else if (data !== void 0 && data !== null) {
830
- this.push(data);
831
- }
832
- this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY;
833
- }
834
- autoBatch(data, cb) {
835
- const buffer = [];
836
- const stream = this.stream;
837
- buffer.push(data);
838
- while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) {
839
- buffer.push(stream._writableState.shift());
840
- }
841
- if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null);
842
- stream._writev(buffer, cb);
843
- }
844
- update() {
845
- const stream = this.stream;
846
- stream._duplexState |= WRITE_UPDATING;
847
- do {
848
- while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) {
849
- const data = this.shift();
850
- stream._duplexState |= WRITE_ACTIVE_AND_WRITING;
851
- stream._write(data, this.afterWrite);
852
- }
853
- if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary();
854
- } while (this.continueUpdate() === true);
855
- stream._duplexState &= WRITE_NOT_UPDATING;
856
- }
857
- updateNonPrimary() {
858
- const stream = this.stream;
859
- if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) {
860
- stream._duplexState = stream._duplexState | WRITE_ACTIVE;
861
- stream._final(afterFinal.bind(this));
862
- return;
863
- }
864
- if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
865
- if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
866
- stream._duplexState |= ACTIVE;
867
- stream._destroy(afterDestroy.bind(this));
868
- }
869
- return;
870
- }
871
- if ((stream._duplexState & IS_OPENING) === OPENING) {
872
- stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING;
873
- stream._open(afterOpen.bind(this));
874
- }
875
- }
876
- continueUpdate() {
877
- if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false;
878
- this.stream._duplexState &= WRITE_NOT_NEXT_TICK;
879
- return true;
880
- }
881
- updateCallback() {
882
- if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) {
883
- this.update();
884
- } else {
885
- this.updateNextTick();
886
- }
887
- }
888
- updateNextTick() {
889
- if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return;
890
- this.stream._duplexState |= WRITE_NEXT_TICK;
891
- if ((this.stream._duplexState & WRITE_UPDATING) === 0) qmt(this.afterUpdateNextTick);
892
- }
893
- };
894
- var ReadableState = class {
895
- constructor(stream, { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}) {
896
- this.stream = stream;
897
- this.queue = new FIFO();
898
- this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark;
899
- this.buffered = 0;
900
- this.readAhead = highWaterMark > 0;
901
- this.error = null;
902
- this.pipeline = null;
903
- this.byteLength = byteLengthReadable || byteLength || defaultByteLength;
904
- this.map = mapReadable || map;
905
- this.pipeTo = null;
906
- this.afterRead = afterRead.bind(this);
907
- this.afterUpdateNextTick = updateReadNT.bind(this);
908
- }
909
- get ending() {
910
- return (this.stream._duplexState & READ_ENDING) !== 0;
911
- }
912
- get ended() {
913
- return (this.stream._duplexState & READ_DONE) !== 0;
914
- }
915
- pipe(pipeTo, cb) {
916
- if (this.pipeTo !== null) throw StreamError.BAD_ARGUMENT("Can only pipe to one destination");
917
- if (typeof cb !== "function") cb = null;
918
- this.stream._duplexState |= READ_PIPE_DRAINED;
919
- this.pipeTo = pipeTo;
920
- this.pipeline = new Pipeline(this.stream, pipeTo, cb);
921
- if (cb) this.stream.on("error", noop);
922
- if (isStreamx(pipeTo)) {
923
- pipeTo._writableState.pipeline = this.pipeline;
924
- if (cb) pipeTo.on("error", noop);
925
- pipeTo.on("finish", this.pipeline.finished.bind(this.pipeline));
926
- } else {
927
- const onerror = this.pipeline.done.bind(this.pipeline, pipeTo);
928
- const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null);
929
- pipeTo.on("error", onerror);
930
- pipeTo.on("close", onclose);
931
- pipeTo.on("finish", this.pipeline.finished.bind(this.pipeline));
932
- }
933
- pipeTo.on("drain", afterDrain.bind(this));
934
- this.stream.emit("piping", pipeTo);
935
- pipeTo.emit("pipe", this.stream);
936
- }
937
- push(data) {
938
- const stream = this.stream;
939
- if (data === null) {
940
- this.highWaterMark = 0;
941
- stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED;
942
- return false;
943
- }
944
- if (this.map !== null) {
945
- data = this.map(data);
946
- if (data === null) {
947
- stream._duplexState &= READ_PUSHED;
948
- return this.buffered < this.highWaterMark;
949
- }
950
- }
951
- this.buffered += this.byteLength(data);
952
- this.queue.push(data);
953
- stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED;
954
- return this.buffered < this.highWaterMark;
955
- }
956
- shift() {
957
- const data = this.queue.shift();
958
- this.buffered -= this.byteLength(data);
959
- if (this.buffered === 0) {
960
- this.stream._duplexState &= READ_NOT_QUEUED;
961
- }
962
- return data;
963
- }
964
- unshift(data) {
965
- const pending = [this.map !== null ? this.map(data) : data];
966
- while (this.buffered > 0) pending.push(this.shift());
967
- for (let i = 0; i < pending.length - 1; i++) {
968
- const data2 = pending[i];
969
- this.buffered += this.byteLength(data2);
970
- this.queue.push(data2);
971
- }
972
- this.push(pending[pending.length - 1]);
973
- }
974
- read() {
975
- const stream = this.stream;
976
- if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {
977
- const data = this.shift();
978
- if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
979
- stream._duplexState &= READ_PIPE_NOT_DRAINED;
980
- }
981
- if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
982
- stream.emit("data", data);
983
- }
984
- return data;
985
- }
986
- if (this.readAhead === false) {
987
- stream._duplexState |= READ_READ_AHEAD;
988
- this.updateNextTick();
989
- }
990
- return null;
991
- }
992
- drain() {
993
- const stream = this.stream;
994
- while ((stream._duplexState & READ_STATUS) === READ_QUEUED && (stream._duplexState & READ_FLOWING) !== 0) {
995
- const data = this.shift();
996
- if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
997
- stream._duplexState &= READ_PIPE_NOT_DRAINED;
998
- }
999
- if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
1000
- stream.emit("data", data);
1001
- }
1002
- }
1003
- }
1004
- update() {
1005
- const stream = this.stream;
1006
- stream._duplexState |= READ_UPDATING;
1007
- do {
1008
- this.drain();
1009
- while (this.buffered < this.highWaterMark && (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD) {
1010
- stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH;
1011
- stream._read(this.afterRead);
1012
- this.drain();
1013
- }
1014
- if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) {
1015
- stream._duplexState |= READ_EMITTED_READABLE;
1016
- stream.emit("readable");
1017
- }
1018
- if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) {
1019
- this.updateNonPrimary();
1020
- }
1021
- } while (this.continueUpdate() === true);
1022
- stream._duplexState &= READ_NOT_UPDATING;
1023
- }
1024
- updateNonPrimary() {
1025
- const stream = this.stream;
1026
- if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) {
1027
- stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING;
1028
- stream.emit("end");
1029
- if ((stream._duplexState & AUTO_DESTROY) === DONE) {
1030
- stream._duplexState |= DESTROYING;
1031
- }
1032
- if (this.pipeTo !== null) {
1033
- this.pipeTo.end();
1034
- }
1035
- }
1036
- if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
1037
- if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
1038
- stream._duplexState |= ACTIVE;
1039
- stream._destroy(afterDestroy.bind(this));
1040
- }
1041
- return;
1042
- }
1043
- if ((stream._duplexState & IS_OPENING) === OPENING) {
1044
- stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING;
1045
- stream._open(afterOpen.bind(this));
1046
- }
1047
- }
1048
- continueUpdate() {
1049
- if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false;
1050
- this.stream._duplexState &= READ_NOT_NEXT_TICK;
1051
- return true;
1052
- }
1053
- updateCallback() {
1054
- if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) {
1055
- this.update();
1056
- } else {
1057
- this.updateNextTick();
1058
- }
1059
- }
1060
- updateNextTickIfOpen() {
1061
- if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return;
1062
- this.stream._duplexState |= READ_NEXT_TICK;
1063
- if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick);
1064
- }
1065
- updateNextTick() {
1066
- if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return;
1067
- this.stream._duplexState |= READ_NEXT_TICK;
1068
- if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick);
1069
- }
1070
- };
1071
- var TransformState = class {
1072
- constructor(stream) {
1073
- this.data = null;
1074
- this.afterTransform = afterTransform.bind(stream);
1075
- this.afterFinal = null;
1076
- }
1077
- };
1078
- var Pipeline = class {
1079
- constructor(src, dst, cb) {
1080
- this.from = src;
1081
- this.to = dst;
1082
- this.afterPipe = cb;
1083
- this.error = null;
1084
- this.pipeToFinished = false;
1085
- }
1086
- finished() {
1087
- this.pipeToFinished = true;
1088
- }
1089
- done(stream, err) {
1090
- if (err) this.error = err;
1091
- if (stream === this.to) {
1092
- this.to = null;
1093
- if (this.from !== null) {
1094
- if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) {
1095
- this.from.destroy(this.error || StreamError.PREMATURE_CLOSE("Writable stream closed"));
1096
- }
1097
- return;
1098
- }
1099
- }
1100
- if (stream === this.from) {
1101
- this.from = null;
1102
- if (this.to !== null) {
1103
- if ((stream._duplexState & READ_DONE) === 0) {
1104
- this.to.destroy(this.error || StreamError.PREMATURE_CLOSE("Readable stream closed"));
1105
- }
1106
- return;
1107
- }
1108
- }
1109
- if (this.afterPipe !== null) this.afterPipe(this.error);
1110
- this.to = this.from = this.afterPipe = null;
1111
- }
1112
- };
1113
- function afterDrain() {
1114
- this.stream._duplexState |= READ_PIPE_DRAINED;
1115
- this.updateCallback();
1116
- }
1117
- function afterFinal(err) {
1118
- const stream = this.stream;
1119
- if (err) stream.destroy(err);
1120
- if ((stream._duplexState & DESTROY_STATUS) === 0) {
1121
- stream._duplexState |= WRITE_DONE;
1122
- stream.emit("finish");
1123
- }
1124
- if ((stream._duplexState & AUTO_DESTROY) === DONE) {
1125
- stream._duplexState |= DESTROYING;
1126
- }
1127
- stream._duplexState &= WRITE_NOT_FINISHING;
1128
- if ((stream._duplexState & WRITE_UPDATING) === 0) {
1129
- this.update();
1130
- } else {
1131
- this.updateNextTick();
1132
- }
1133
- }
1134
- function afterDestroy(err) {
1135
- const stream = this.stream;
1136
- if (!err && !StreamError.isStreamDestroyed(this.error)) err = this.error;
1137
- if (err) stream.emit("error", err);
1138
- stream._duplexState |= DESTROYED;
1139
- stream.emit("close");
1140
- const rs = stream._readableState;
1141
- const ws = stream._writableState;
1142
- if (rs !== null && rs.pipeline !== null) {
1143
- rs.pipeline.done(stream, err);
1144
- }
1145
- if (ws !== null) {
1146
- while (ws.drains !== null && ws.drains.length > 0) {
1147
- ws.drains.shift().resolve(false);
1148
- }
1149
- if (ws.pipeline !== null) {
1150
- ws.pipeline.done(stream, err);
1151
- }
1152
- }
1153
- }
1154
- function afterWrite(err) {
1155
- const stream = this.stream;
1156
- if (err) stream.destroy(err);
1157
- stream._duplexState &= WRITE_NOT_ACTIVE;
1158
- if (this.drains !== null) tickDrains(this.drains);
1159
- if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) {
1160
- stream._duplexState &= WRITE_DRAINED;
1161
- if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) {
1162
- stream.emit("drain");
1163
- }
1164
- }
1165
- this.updateCallback();
1166
- }
1167
- function afterRead(err) {
1168
- if (err) this.stream.destroy(err);
1169
- this.stream._duplexState &= READ_NOT_ACTIVE;
1170
- if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0) {
1171
- this.stream._duplexState &= READ_NO_READ_AHEAD;
1172
- }
1173
- this.updateCallback();
1174
- }
1175
- function updateReadNT() {
1176
- if ((this.stream._duplexState & READ_UPDATING) === 0) {
1177
- this.stream._duplexState &= READ_NOT_NEXT_TICK;
1178
- this.update();
1179
- }
1180
- }
1181
- function updateWriteNT() {
1182
- if ((this.stream._duplexState & WRITE_UPDATING) === 0) {
1183
- this.stream._duplexState &= WRITE_NOT_NEXT_TICK;
1184
- this.update();
1185
- }
1186
- }
1187
- function tickDrains(drains) {
1188
- for (let i = 0; i < drains.length; i++) {
1189
- if (--drains[i].writes === 0) {
1190
- drains.shift().resolve(true);
1191
- i--;
1192
- }
1193
- }
1194
- }
1195
- function afterOpen(err) {
1196
- const stream = this.stream;
1197
- if (err) stream.destroy(err);
1198
- if ((stream._duplexState & DESTROYING) === 0) {
1199
- if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) {
1200
- stream._duplexState |= READ_PRIMARY;
1201
- }
1202
- if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) {
1203
- stream._duplexState |= WRITE_PRIMARY;
1204
- }
1205
- stream.emit("open");
1206
- }
1207
- stream._duplexState &= NOT_ACTIVE;
1208
- if (stream._writableState !== null) {
1209
- stream._writableState.updateCallback();
1210
- }
1211
- if (stream._readableState !== null) {
1212
- stream._readableState.updateCallback();
1213
- }
1214
- }
1215
- function afterTransform(err, data) {
1216
- if (data !== void 0 && data !== null) this.push(data);
1217
- this._writableState.afterWrite(err);
1218
- }
1219
- function newListener(name) {
1220
- if (this._readableState !== null) {
1221
- if (name === "data") {
1222
- this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD;
1223
- this._readableState.updateNextTick();
1224
- }
1225
- if (name === "readable") {
1226
- this._duplexState |= READ_EMIT_READABLE;
1227
- this._readableState.updateNextTick();
1228
- }
1229
- }
1230
- if (this._writableState !== null) {
1231
- if (name === "drain") {
1232
- this._duplexState |= WRITE_EMIT_DRAIN;
1233
- this._writableState.updateNextTick();
1234
- }
1235
- }
1236
- }
1237
- var Stream = class extends EventEmitter {
1238
- constructor(opts) {
1239
- super();
1240
- this._duplexState = 0;
1241
- this._readableState = null;
1242
- this._writableState = null;
1243
- if (opts) {
1244
- if (opts.open) this._open = opts.open;
1245
- if (opts.destroy) this._destroy = opts.destroy;
1246
- if (opts.predestroy) this._predestroy = opts.predestroy;
1247
- if (opts.signal) opts.signal.addEventListener("abort", abort.bind(this));
1248
- }
1249
- this.on("newListener", newListener);
1250
- }
1251
- _open(cb) {
1252
- cb(null);
1253
- }
1254
- _destroy(cb) {
1255
- cb(null);
1256
- }
1257
- _predestroy() {
1258
- }
1259
- get readable() {
1260
- return this._readableState !== null ? true : void 0;
1261
- }
1262
- get writable() {
1263
- return this._writableState !== null ? true : void 0;
1264
- }
1265
- get destroyed() {
1266
- return (this._duplexState & DESTROYED) !== 0;
1267
- }
1268
- get destroying() {
1269
- return (this._duplexState & DESTROY_STATUS) !== 0;
1270
- }
1271
- destroy(err) {
1272
- if ((this._duplexState & DESTROY_STATUS) === 0) {
1273
- if (!err) err = StreamError.STREAM_DESTROYED();
1274
- this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY;
1275
- if (this._readableState !== null) {
1276
- this._readableState.highWaterMark = 0;
1277
- this._readableState.error = err;
1278
- }
1279
- if (this._writableState !== null) {
1280
- this._writableState.highWaterMark = 0;
1281
- this._writableState.error = err;
1282
- }
1283
- this._duplexState |= PREDESTROYING;
1284
- this._predestroy();
1285
- this._duplexState &= NOT_PREDESTROYING;
1286
- if (this._readableState !== null) {
1287
- this._readableState.updateNextTick();
1288
- }
1289
- if (this._writableState !== null) {
1290
- this._writableState.updateNextTick();
1291
- }
1292
- }
1293
- }
1294
- };
1295
- var Readable2 = class _Readable extends Stream {
1296
- constructor(opts) {
1297
- super(opts);
1298
- this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD;
1299
- this._readableState = new ReadableState(this, opts);
1300
- if (opts) {
1301
- if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD;
1302
- if (opts.read) this._read = opts.read;
1303
- if (opts.eagerOpen) this._readableState.updateNextTick();
1304
- if (opts.encoding) this.setEncoding(opts.encoding);
1305
- }
1306
- }
1307
- static deferred(fn, opts) {
1308
- const out = new PassThrough(opts);
1309
- fn().then((src) => {
1310
- if (src === null) return out.end();
1311
- if (out.destroying) return;
1312
- pipeline2(src, out, noop);
1313
- }).catch((err) => out.destroy(err));
1314
- return out;
1315
- }
1316
- setEncoding(encoding) {
1317
- const dec = new TextDecoder2(encoding);
1318
- const map = this._readableState.map || echo;
1319
- this._readableState.map = mapOrSkip;
1320
- return this;
1321
- function mapOrSkip(data) {
1322
- const next = dec.push(data);
1323
- return next === "" && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next);
1324
- }
1325
- }
1326
- _read(cb) {
1327
- cb(null);
1328
- }
1329
- pipe(dest, cb) {
1330
- this._readableState.updateNextTick();
1331
- this._readableState.pipe(dest, cb);
1332
- return dest;
1333
- }
1334
- read() {
1335
- this._readableState.updateNextTick();
1336
- return this._readableState.read();
1337
- }
1338
- push(data) {
1339
- this._readableState.updateNextTickIfOpen();
1340
- return this._readableState.push(data);
1341
- }
1342
- unshift(data) {
1343
- this._readableState.updateNextTickIfOpen();
1344
- return this._readableState.unshift(data);
1345
- }
1346
- resume() {
1347
- this._duplexState |= READ_RESUMED_READ_AHEAD;
1348
- this._readableState.updateNextTick();
1349
- return this;
1350
- }
1351
- pause() {
1352
- this._duplexState &= this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED;
1353
- return this;
1354
- }
1355
- static _fromAsyncIterator(ite, opts) {
1356
- let destroy;
1357
- const rs = new _Readable({
1358
- ...opts,
1359
- read(cb) {
1360
- ite.next().then(push).then(cb.bind(null, null)).catch(cb);
1361
- },
1362
- predestroy() {
1363
- destroy = ite.return();
1364
- },
1365
- destroy(cb) {
1366
- if (!destroy) return cb(null);
1367
- destroy.then(cb.bind(null, null)).catch(cb);
1368
- }
1369
- });
1370
- return rs;
1371
- function push(data) {
1372
- if (data.done) rs.push(null);
1373
- else rs.push(data.value);
1374
- }
1375
- }
1376
- static from(data, opts) {
1377
- if (isReadStreamx(data)) return data;
1378
- if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts);
1379
- if (!Array.isArray(data)) data = data === void 0 ? [] : [data];
1380
- let i = 0;
1381
- return new _Readable({
1382
- ...opts,
1383
- read(cb) {
1384
- this.push(i === data.length ? null : data[i++]);
1385
- cb(null);
1386
- }
1387
- });
1388
- }
1389
- static isBackpressured(rs) {
1390
- return (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 || rs._readableState.buffered >= rs._readableState.highWaterMark;
1391
- }
1392
- static isPaused(rs) {
1393
- return (rs._duplexState & READ_RESUMED) === 0;
1394
- }
1395
- [asyncIterator]() {
1396
- const stream = this;
1397
- let error = null;
1398
- let promiseResolve = null;
1399
- let promiseReject = null;
1400
- this.on("error", (err) => {
1401
- error = err;
1402
- });
1403
- this.on("readable", onreadable);
1404
- this.on("close", onclose);
1405
- return {
1406
- [asyncIterator]() {
1407
- return this;
1408
- },
1409
- next() {
1410
- return new Promise(function(resolve3, reject) {
1411
- promiseResolve = resolve3;
1412
- promiseReject = reject;
1413
- const data = stream.read();
1414
- if (data !== null) ondata(data);
1415
- else if ((stream._duplexState & DESTROYED) !== 0) ondata(null);
1416
- });
1417
- },
1418
- return() {
1419
- return destroy(null);
1420
- },
1421
- throw(err) {
1422
- return destroy(err);
1423
- }
1424
- };
1425
- function onreadable() {
1426
- if (promiseResolve !== null) ondata(stream.read());
1427
- }
1428
- function onclose() {
1429
- if (promiseResolve !== null) ondata(null);
1430
- }
1431
- function ondata(data) {
1432
- if (promiseReject === null) return;
1433
- if (error) {
1434
- promiseReject(error);
1435
- } else if (data === null && (stream._duplexState & READ_DONE) === 0) {
1436
- promiseReject(StreamError.STREAM_DESTROYED());
1437
- } else {
1438
- promiseResolve({ value: data, done: data === null });
1439
- }
1440
- promiseReject = promiseResolve = null;
1441
- }
1442
- function destroy(err) {
1443
- stream.destroy(err);
1444
- return new Promise((resolve3, reject) => {
1445
- if (stream._duplexState & DESTROYED) return resolve3({ value: void 0, done: true });
1446
- stream.once("close", function() {
1447
- if (err) reject(err);
1448
- else resolve3({ value: void 0, done: true });
1449
- });
1450
- });
1451
- }
1452
- }
1453
- };
1454
- var Writable = class extends Stream {
1455
- constructor(opts) {
1456
- super(opts);
1457
- this._duplexState |= OPENING | READ_DONE;
1458
- this._writableState = new WritableState(this, opts);
1459
- if (opts) {
1460
- if (opts.writev) this._writev = opts.writev;
1461
- if (opts.write) this._write = opts.write;
1462
- if (opts.final) this._final = opts.final;
1463
- if (opts.eagerOpen) this._writableState.updateNextTick();
1464
- }
1465
- }
1466
- cork() {
1467
- this._duplexState |= WRITE_CORKED;
1468
- }
1469
- uncork() {
1470
- this._duplexState &= WRITE_NOT_CORKED;
1471
- this._writableState.updateNextTick();
1472
- }
1473
- _writev(batch, cb) {
1474
- cb(null);
1475
- }
1476
- _write(data, cb) {
1477
- this._writableState.autoBatch(data, cb);
1478
- }
1479
- _final(cb) {
1480
- cb(null);
1481
- }
1482
- static isBackpressured(ws) {
1483
- return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0;
1484
- }
1485
- static drained(ws) {
1486
- if (ws.destroyed) return Promise.resolve(false);
1487
- const state = ws._writableState;
1488
- const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length;
1489
- const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0);
1490
- if (writes === 0) return Promise.resolve(true);
1491
- if (state.drains === null) state.drains = [];
1492
- return new Promise((resolve3) => {
1493
- state.drains.push({ writes, resolve: resolve3 });
1494
- });
1495
- }
1496
- write(data) {
1497
- this._writableState.updateNextTick();
1498
- return this._writableState.push(data);
1499
- }
1500
- end(data) {
1501
- this._writableState.updateNextTick();
1502
- this._writableState.end(data);
1503
- return this;
1504
- }
1505
- };
1506
- var Duplex = class extends Readable2 {
1507
- // and Writable
1508
- constructor(opts) {
1509
- super(opts);
1510
- this._duplexState = OPENING | this._duplexState & READ_READ_AHEAD;
1511
- this._writableState = new WritableState(this, opts);
1512
- if (opts) {
1513
- if (opts.writev) this._writev = opts.writev;
1514
- if (opts.write) this._write = opts.write;
1515
- if (opts.final) this._final = opts.final;
1516
- }
1517
- }
1518
- cork() {
1519
- this._duplexState |= WRITE_CORKED;
1520
- }
1521
- uncork() {
1522
- this._duplexState &= WRITE_NOT_CORKED;
1523
- this._writableState.updateNextTick();
1524
- }
1525
- _writev(batch, cb) {
1526
- cb(null);
1527
- }
1528
- _write(data, cb) {
1529
- this._writableState.autoBatch(data, cb);
1530
- }
1531
- _final(cb) {
1532
- cb(null);
1533
- }
1534
- write(data) {
1535
- this._writableState.updateNextTick();
1536
- return this._writableState.push(data);
1537
- }
1538
- end(data) {
1539
- this._writableState.updateNextTick();
1540
- this._writableState.end(data);
1541
- return this;
1542
- }
1543
- };
1544
- var Transform = class extends Duplex {
1545
- constructor(opts) {
1546
- super(opts);
1547
- this._transformState = new TransformState(this);
1548
- if (opts) {
1549
- if (opts.transform) this._transform = opts.transform;
1550
- if (opts.flush) this._flush = opts.flush;
1551
- }
1552
- }
1553
- _write(data, cb) {
1554
- if (this._readableState.buffered >= this._readableState.highWaterMark) {
1555
- this._transformState.data = data;
1556
- } else {
1557
- this._transform(data, this._transformState.afterTransform);
1558
- }
1559
- }
1560
- _read(cb) {
1561
- if (this._transformState.data !== null) {
1562
- const data = this._transformState.data;
1563
- this._transformState.data = null;
1564
- cb(null);
1565
- this._transform(data, this._transformState.afterTransform);
1566
- } else {
1567
- cb(null);
1568
- }
1569
- }
1570
- destroy(err) {
1571
- super.destroy(err);
1572
- if (this._transformState.data !== null) {
1573
- this._transformState.data = null;
1574
- this._transformState.afterTransform();
1575
- }
1576
- }
1577
- _transform(data, cb) {
1578
- cb(null, data);
1579
- }
1580
- _flush(cb) {
1581
- cb(null);
1582
- }
1583
- _final(cb) {
1584
- this._transformState.afterFinal = cb;
1585
- this._flush(transformAfterFlush.bind(this));
1586
- }
1587
- };
1588
- var PassThrough = class extends Transform {
1589
- };
1590
- function transformAfterFlush(err, data) {
1591
- const cb = this._transformState.afterFinal;
1592
- if (err) return cb(err);
1593
- if (data !== null && data !== void 0) this.push(data);
1594
- this.push(null);
1595
- cb(null);
1596
- }
1597
- function pipelinePromise(...streams) {
1598
- return new Promise((resolve3, reject) => {
1599
- return pipeline2(...streams, (err) => {
1600
- if (err) return reject(err);
1601
- resolve3();
1602
- });
1603
- });
1604
- }
1605
- function pipeline2(stream, ...streams) {
1606
- const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams];
1607
- const done = all.length && typeof all[all.length - 1] === "function" ? all.pop() : null;
1608
- if (all.length < 2) throw StreamError.BAD_ARGUMENT("Pipeline requires at least 2 streams");
1609
- let src = all[0];
1610
- let dest = null;
1611
- let error = null;
1612
- for (let i = 1; i < all.length; i++) {
1613
- dest = all[i];
1614
- if (isStreamx(src)) {
1615
- src.pipe(dest, onerror);
1616
- } else {
1617
- errorHandle(src, true, i > 1, onerror);
1618
- src.pipe(dest);
1619
- }
1620
- src = dest;
1621
- }
1622
- if (done) {
1623
- let fin = false;
1624
- const autoDestroy = isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy);
1625
- dest.on("error", (err) => {
1626
- if (error === null) error = err;
1627
- });
1628
- dest.on("finish", () => {
1629
- fin = true;
1630
- if (!autoDestroy) done(error);
1631
- });
1632
- if (autoDestroy) {
1633
- dest.on("close", () => done(error || (fin ? null : StreamError.PREMATURE_CLOSE())));
1634
- }
1635
- }
1636
- return dest;
1637
- function errorHandle(s, rd, wr, onerror2) {
1638
- s.on("error", onerror2);
1639
- s.on("close", onclose);
1640
- function onclose() {
1641
- if (s._readableState && !s._readableState.ended) {
1642
- return onerror2(StreamError.PREMATURE_CLOSE());
1643
- }
1644
- if (wr && s._writableState && !s._writableState.ended) {
1645
- return onerror2(StreamError.PREMATURE_CLOSE());
1646
- }
1647
- }
1648
- }
1649
- function onerror(err) {
1650
- if (!err || error) return;
1651
- error = err;
1652
- for (const s of all) {
1653
- s.destroy(err);
1654
- }
1655
- }
1656
- }
1657
- function echo(s) {
1658
- return s;
1659
- }
1660
- function isStream(stream) {
1661
- return !!stream._readableState || !!stream._writableState;
1662
- }
1663
- function isStreamx(stream) {
1664
- return typeof stream._duplexState === "number" && isStream(stream);
1665
- }
1666
- function isEnding(stream) {
1667
- return !!stream._readableState && stream._readableState.ending;
1668
- }
1669
- function isEnded(stream) {
1670
- return !!stream._readableState && stream._readableState.ended;
1671
- }
1672
- function isFinishing(stream) {
1673
- return !!stream._writableState && stream._writableState.ending;
1674
- }
1675
- function isFinished(stream) {
1676
- return !!stream._writableState && stream._writableState.ended;
1677
- }
1678
- function getStreamError(stream, opts = {}) {
1679
- const err = stream._readableState && stream._readableState.error || stream._writableState && stream._writableState.error;
1680
- return !opts.all && StreamError.isStreamDestroyed(err) ? null : err;
1681
- }
1682
- function isReadStreamx(stream) {
1683
- return isStreamx(stream) && stream.readable;
1684
- }
1685
- function isDisturbed(stream) {
1686
- return (stream._duplexState & OPENING) !== OPENING || (stream._duplexState & DESTROYING) === DESTROYING || (stream._duplexState & ACTIVE_OR_TICKING) !== 0;
1687
- }
1688
- function isTypedArray(data) {
1689
- return typeof data === "object" && data !== null && typeof data.byteLength === "number";
1690
- }
1691
- function defaultByteLength(data) {
1692
- return isTypedArray(data) ? data.byteLength : 1024;
1693
- }
1694
- function noop() {
1695
- }
1696
- function abort() {
1697
- this.destroy(StreamError.ABORTED());
1698
- }
1699
- function isWritev(s) {
1700
- return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev;
1701
- }
1702
- module.exports = {
1703
- pipeline: pipeline2,
1704
- pipelinePromise,
1705
- isStream,
1706
- isStreamx,
1707
- isEnding,
1708
- isEnded,
1709
- isFinishing,
1710
- isFinished,
1711
- isDisturbed,
1712
- getStreamError,
1713
- Stream,
1714
- Writable,
1715
- Readable: Readable2,
1716
- Duplex,
1717
- Transform,
1718
- // Export PassThrough for compatibility with Node.js core's stream module
1719
- PassThrough
1720
- };
1721
- }
1722
- });
1723
-
1724
- // ../../node_modules/@sparticuz/chromium/node_modules/tar-stream/headers.js
1725
- var require_headers = __commonJS({
1726
- "../../node_modules/@sparticuz/chromium/node_modules/tar-stream/headers.js"(exports) {
1727
- var b4a = require_b4a();
1728
- var ZEROS = "0000000000000000000";
1729
- var SEVENS = "7777777777777777777";
1730
- var ZERO_OFFSET = "0".charCodeAt(0);
1731
- var USTAR_MAGIC = b4a.from([117, 115, 116, 97, 114, 0]);
1732
- var USTAR_VER = b4a.from([ZERO_OFFSET, ZERO_OFFSET]);
1733
- var GNU_MAGIC = b4a.from([117, 115, 116, 97, 114, 32]);
1734
- var GNU_VER = b4a.from([32, 0]);
1735
- var MASK = 4095;
1736
- var MAGIC_OFFSET = 257;
1737
- var VERSION_OFFSET = 263;
1738
- exports.decodeLongPath = function decodeLongPath(buf, encoding) {
1739
- return decodeStr(buf, 0, buf.length, encoding);
1740
- };
1741
- exports.encodePax = function encodePax(opts) {
1742
- let result = "";
1743
- if (opts.name) result += addLength(" path=" + opts.name + "\n");
1744
- if (opts.linkname) result += addLength(" linkpath=" + opts.linkname + "\n");
1745
- const pax = opts.pax;
1746
- if (pax) {
1747
- for (const key in pax) {
1748
- result += addLength(" " + key + "=" + pax[key] + "\n");
1749
- }
1750
- }
1751
- return b4a.from(result);
1752
- };
1753
- exports.decodePax = function decodePax(buf) {
1754
- const result = {};
1755
- while (buf.length) {
1756
- let i = 0;
1757
- while (i < buf.length && buf[i] !== 32) i++;
1758
- const len = parseInt(b4a.toString(buf.subarray(0, i)), 10);
1759
- if (!len) return result;
1760
- const b = b4a.toString(buf.subarray(i + 1, len - 1));
1761
- const keyIndex = b.indexOf("=");
1762
- if (keyIndex === -1) return result;
1763
- result[b.slice(0, keyIndex)] = b.slice(keyIndex + 1);
1764
- buf = buf.subarray(len);
1765
- }
1766
- return result;
1767
- };
1768
- exports.encode = function encode(opts) {
1769
- const buf = b4a.alloc(512);
1770
- let name = opts.name;
1771
- let prefix = "";
1772
- if (opts.typeflag === 5 && name[name.length - 1] !== "/") name += "/";
1773
- if (b4a.byteLength(name) !== name.length) return null;
1774
- while (b4a.byteLength(name) > 100) {
1775
- const i = name.indexOf("/");
1776
- if (i === -1) return null;
1777
- prefix += prefix ? "/" + name.slice(0, i) : name.slice(0, i);
1778
- name = name.slice(i + 1);
1779
- }
1780
- if (b4a.byteLength(name) > 100 || b4a.byteLength(prefix) > 155) return null;
1781
- if (opts.linkname && b4a.byteLength(opts.linkname) > 100) return null;
1782
- b4a.write(buf, name);
1783
- b4a.write(buf, encodeOct(opts.mode & MASK, 6), 100);
1784
- b4a.write(buf, encodeOct(opts.uid, 6), 108);
1785
- b4a.write(buf, encodeOct(opts.gid, 6), 116);
1786
- encodeSize(opts.size, buf, 124);
1787
- b4a.write(buf, encodeOct(opts.mtime.getTime() / 1e3 | 0, 11), 136);
1788
- buf[156] = ZERO_OFFSET + toTypeflag(opts.type);
1789
- if (opts.linkname) b4a.write(buf, opts.linkname, 157);
1790
- b4a.copy(USTAR_MAGIC, buf, MAGIC_OFFSET);
1791
- b4a.copy(USTAR_VER, buf, VERSION_OFFSET);
1792
- if (opts.uname) b4a.write(buf, opts.uname, 265);
1793
- if (opts.gname) b4a.write(buf, opts.gname, 297);
1794
- b4a.write(buf, encodeOct(opts.devmajor || 0, 6), 329);
1795
- b4a.write(buf, encodeOct(opts.devminor || 0, 6), 337);
1796
- if (prefix) b4a.write(buf, prefix, 345);
1797
- b4a.write(buf, encodeOct(cksum(buf), 6), 148);
1798
- return buf;
1799
- };
1800
- exports.decode = function decode(buf, filenameEncoding, allowUnknownFormat) {
1801
- let typeflag = buf[156] === 0 ? 0 : buf[156] - ZERO_OFFSET;
1802
- let name = decodeStr(buf, 0, 100, filenameEncoding);
1803
- const mode = decodeOct(buf, 100, 8);
1804
- const uid = decodeOct(buf, 108, 8);
1805
- const gid = decodeOct(buf, 116, 8);
1806
- const size = decodeOct(buf, 124, 12);
1807
- const mtime = decodeOct(buf, 136, 12);
1808
- const type = toType(typeflag);
1809
- const linkname = buf[157] === 0 ? null : decodeStr(buf, 157, 100, filenameEncoding);
1810
- const uname = decodeStr(buf, 265, 32);
1811
- const gname = decodeStr(buf, 297, 32);
1812
- const devmajor = decodeOct(buf, 329, 8);
1813
- const devminor = decodeOct(buf, 337, 8);
1814
- const c = cksum(buf);
1815
- if (c === 8 * 32) return null;
1816
- if (c !== decodeOct(buf, 148, 8)) throw new Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");
1817
- if (isUSTAR(buf)) {
1818
- if (buf[345]) name = decodeStr(buf, 345, 155, filenameEncoding) + "/" + name;
1819
- } else if (isGNU(buf)) ; else {
1820
- if (!allowUnknownFormat) {
1821
- throw new Error("Invalid tar header: unknown format.");
1822
- }
1823
- }
1824
- if (typeflag === 0 && name && name[name.length - 1] === "/") typeflag = 5;
1825
- return {
1826
- name,
1827
- mode,
1828
- uid,
1829
- gid,
1830
- size,
1831
- mtime: new Date(1e3 * mtime),
1832
- type,
1833
- linkname,
1834
- uname,
1835
- gname,
1836
- devmajor,
1837
- devminor,
1838
- pax: null
1839
- };
1840
- };
1841
- function isUSTAR(buf) {
1842
- return b4a.equals(USTAR_MAGIC, buf.subarray(MAGIC_OFFSET, MAGIC_OFFSET + 6));
1843
- }
1844
- function isGNU(buf) {
1845
- return b4a.equals(GNU_MAGIC, buf.subarray(MAGIC_OFFSET, MAGIC_OFFSET + 6)) && b4a.equals(GNU_VER, buf.subarray(VERSION_OFFSET, VERSION_OFFSET + 2));
1846
- }
1847
- function clamp(index, len, defaultValue) {
1848
- if (typeof index !== "number") return defaultValue;
1849
- index = ~~index;
1850
- if (index >= len) return len;
1851
- if (index >= 0) return index;
1852
- index += len;
1853
- if (index >= 0) return index;
1854
- return 0;
1855
- }
1856
- function toType(flag) {
1857
- switch (flag) {
1858
- case 0:
1859
- return "file";
1860
- case 1:
1861
- return "link";
1862
- case 2:
1863
- return "symlink";
1864
- case 3:
1865
- return "character-device";
1866
- case 4:
1867
- return "block-device";
1868
- case 5:
1869
- return "directory";
1870
- case 6:
1871
- return "fifo";
1872
- case 7:
1873
- return "contiguous-file";
1874
- case 72:
1875
- return "pax-header";
1876
- case 55:
1877
- return "pax-global-header";
1878
- case 27:
1879
- return "gnu-long-link-path";
1880
- case 28:
1881
- case 30:
1882
- return "gnu-long-path";
1883
- }
1884
- return null;
1885
- }
1886
- function toTypeflag(flag) {
1887
- switch (flag) {
1888
- case "file":
1889
- return 0;
1890
- case "link":
1891
- return 1;
1892
- case "symlink":
1893
- return 2;
1894
- case "character-device":
1895
- return 3;
1896
- case "block-device":
1897
- return 4;
1898
- case "directory":
1899
- return 5;
1900
- case "fifo":
1901
- return 6;
1902
- case "contiguous-file":
1903
- return 7;
1904
- case "pax-header":
1905
- return 72;
1906
- }
1907
- return 0;
1908
- }
1909
- function indexOf(block, num, offset, end) {
1910
- for (; offset < end; offset++) {
1911
- if (block[offset] === num) return offset;
1912
- }
1913
- return end;
1914
- }
1915
- function cksum(block) {
1916
- let sum = 8 * 32;
1917
- for (let i = 0; i < 148; i++) sum += block[i];
1918
- for (let j = 156; j < 512; j++) sum += block[j];
1919
- return sum;
1920
- }
1921
- function encodeOct(val, n) {
1922
- val = val.toString(8);
1923
- if (val.length > n) return SEVENS.slice(0, n) + " ";
1924
- return ZEROS.slice(0, n - val.length) + val + " ";
1925
- }
1926
- function encodeSizeBin(num, buf, off) {
1927
- buf[off] = 128;
1928
- for (let i = 11; i > 0; i--) {
1929
- buf[off + i] = num & 255;
1930
- num = Math.floor(num / 256);
1931
- }
1932
- }
1933
- function encodeSize(num, buf, off) {
1934
- if (num.toString(8).length > 11) {
1935
- encodeSizeBin(num, buf, off);
1936
- } else {
1937
- b4a.write(buf, encodeOct(num, 11), off);
1938
- }
1939
- }
1940
- function parse256(buf) {
1941
- let positive;
1942
- if (buf[0] === 128) positive = true;
1943
- else if (buf[0] === 255) positive = false;
1944
- else return null;
1945
- const tuple = [];
1946
- let i;
1947
- for (i = buf.length - 1; i > 0; i--) {
1948
- const byte = buf[i];
1949
- if (positive) tuple.push(byte);
1950
- else tuple.push(255 - byte);
1951
- }
1952
- let sum = 0;
1953
- const l = tuple.length;
1954
- for (i = 0; i < l; i++) {
1955
- sum += tuple[i] * Math.pow(256, i);
1956
- }
1957
- return positive ? sum : -1 * sum;
1958
- }
1959
- function decodeOct(val, offset, length) {
1960
- val = val.subarray(offset, offset + length);
1961
- offset = 0;
1962
- if (val[offset] & 128) {
1963
- return parse256(val);
1964
- } else {
1965
- while (offset < val.length && val[offset] === 32) offset++;
1966
- const end = clamp(indexOf(val, 32, offset, val.length), val.length, val.length);
1967
- while (offset < end && val[offset] === 0) offset++;
1968
- if (end === offset) return 0;
1969
- return parseInt(b4a.toString(val.subarray(offset, end)), 8);
1970
- }
1971
- }
1972
- function decodeStr(val, offset, length, encoding) {
1973
- return b4a.toString(val.subarray(offset, indexOf(val, 0, offset, offset + length)), encoding);
1974
- }
1975
- function addLength(str) {
1976
- const len = b4a.byteLength(str);
1977
- let digits = Math.floor(Math.log(len) / Math.log(10)) + 1;
1978
- if (len + digits >= Math.pow(10, digits)) digits++;
1979
- return len + digits + str;
1980
- }
1981
- }
1982
- });
1983
-
1984
- // ../../node_modules/@sparticuz/chromium/node_modules/tar-stream/extract.js
1985
- var require_extract = __commonJS({
1986
- "../../node_modules/@sparticuz/chromium/node_modules/tar-stream/extract.js"(exports, module) {
1987
- var { Writable, Readable: Readable2, getStreamError } = require_streamx();
1988
- var FIFO = require_fast_fifo();
1989
- var b4a = require_b4a();
1990
- var headers = require_headers();
1991
- var EMPTY = b4a.alloc(0);
1992
- var BufferList = class {
1993
- constructor() {
1994
- this.buffered = 0;
1995
- this.shifted = 0;
1996
- this.queue = new FIFO();
1997
- this._offset = 0;
1998
- }
1999
- push(buffer) {
2000
- this.buffered += buffer.byteLength;
2001
- this.queue.push(buffer);
2002
- }
2003
- shiftFirst(size) {
2004
- return this._buffered === 0 ? null : this._next(size);
2005
- }
2006
- shift(size) {
2007
- if (size > this.buffered) return null;
2008
- if (size === 0) return EMPTY;
2009
- let chunk = this._next(size);
2010
- if (size === chunk.byteLength) return chunk;
2011
- const chunks = [chunk];
2012
- while ((size -= chunk.byteLength) > 0) {
2013
- chunk = this._next(size);
2014
- chunks.push(chunk);
2015
- }
2016
- return b4a.concat(chunks);
2017
- }
2018
- _next(size) {
2019
- const buf = this.queue.peek();
2020
- const rem = buf.byteLength - this._offset;
2021
- if (size >= rem) {
2022
- const sub = this._offset ? buf.subarray(this._offset, buf.byteLength) : buf;
2023
- this.queue.shift();
2024
- this._offset = 0;
2025
- this.buffered -= rem;
2026
- this.shifted += rem;
2027
- return sub;
2028
- }
2029
- this.buffered -= size;
2030
- this.shifted += size;
2031
- return buf.subarray(this._offset, this._offset += size);
2032
- }
2033
- };
2034
- var Source = class extends Readable2 {
2035
- constructor(self, header, offset) {
2036
- super();
2037
- this.header = header;
2038
- this.offset = offset;
2039
- this._parent = self;
2040
- }
2041
- _read(cb) {
2042
- if (this.header.size === 0) {
2043
- this.push(null);
2044
- }
2045
- if (this._parent._stream === this) {
2046
- this._parent._update();
2047
- }
2048
- cb(null);
2049
- }
2050
- _predestroy() {
2051
- this._parent.destroy(getStreamError(this));
2052
- }
2053
- _detach() {
2054
- if (this._parent._stream === this) {
2055
- this._parent._stream = null;
2056
- this._parent._missing = overflow(this.header.size);
2057
- this._parent._update();
2058
- }
2059
- }
2060
- _destroy(cb) {
2061
- this._detach();
2062
- cb(null);
2063
- }
2064
- };
2065
- var Extract = class extends Writable {
2066
- constructor(opts) {
2067
- super(opts);
2068
- if (!opts) opts = {};
2069
- this._buffer = new BufferList();
2070
- this._offset = 0;
2071
- this._header = null;
2072
- this._stream = null;
2073
- this._missing = 0;
2074
- this._longHeader = false;
2075
- this._callback = noop;
2076
- this._locked = false;
2077
- this._finished = false;
2078
- this._pax = null;
2079
- this._paxGlobal = null;
2080
- this._gnuLongPath = null;
2081
- this._gnuLongLinkPath = null;
2082
- this._filenameEncoding = opts.filenameEncoding || "utf-8";
2083
- this._allowUnknownFormat = !!opts.allowUnknownFormat;
2084
- this._unlockBound = this._unlock.bind(this);
2085
- }
2086
- _unlock(err) {
2087
- this._locked = false;
2088
- if (err) {
2089
- this.destroy(err);
2090
- this._continueWrite(err);
2091
- return;
2092
- }
2093
- this._update();
2094
- }
2095
- _consumeHeader() {
2096
- if (this._locked) return false;
2097
- this._offset = this._buffer.shifted;
2098
- try {
2099
- this._header = headers.decode(this._buffer.shift(512), this._filenameEncoding, this._allowUnknownFormat);
2100
- } catch (err) {
2101
- this._continueWrite(err);
2102
- return false;
2103
- }
2104
- if (!this._header) return true;
2105
- switch (this._header.type) {
2106
- case "gnu-long-path":
2107
- case "gnu-long-link-path":
2108
- case "pax-global-header":
2109
- case "pax-header":
2110
- this._longHeader = true;
2111
- this._missing = this._header.size;
2112
- return true;
2113
- }
2114
- this._locked = true;
2115
- this._applyLongHeaders();
2116
- if (this._header.size === 0 || this._header.type === "directory") {
2117
- this.emit("entry", this._header, this._createStream(), this._unlockBound);
2118
- return true;
2119
- }
2120
- this._stream = this._createStream();
2121
- this._missing = this._header.size;
2122
- this.emit("entry", this._header, this._stream, this._unlockBound);
2123
- return true;
2124
- }
2125
- _applyLongHeaders() {
2126
- if (this._gnuLongPath) {
2127
- this._header.name = this._gnuLongPath;
2128
- this._gnuLongPath = null;
2129
- }
2130
- if (this._gnuLongLinkPath) {
2131
- this._header.linkname = this._gnuLongLinkPath;
2132
- this._gnuLongLinkPath = null;
2133
- }
2134
- if (this._pax) {
2135
- if (this._pax.path) this._header.name = this._pax.path;
2136
- if (this._pax.linkpath) this._header.linkname = this._pax.linkpath;
2137
- if (this._pax.size) this._header.size = parseInt(this._pax.size, 10);
2138
- this._header.pax = this._pax;
2139
- this._pax = null;
2140
- }
2141
- }
2142
- _decodeLongHeader(buf) {
2143
- switch (this._header.type) {
2144
- case "gnu-long-path":
2145
- this._gnuLongPath = headers.decodeLongPath(buf, this._filenameEncoding);
2146
- break;
2147
- case "gnu-long-link-path":
2148
- this._gnuLongLinkPath = headers.decodeLongPath(buf, this._filenameEncoding);
2149
- break;
2150
- case "pax-global-header":
2151
- this._paxGlobal = headers.decodePax(buf);
2152
- break;
2153
- case "pax-header":
2154
- this._pax = this._paxGlobal === null ? headers.decodePax(buf) : Object.assign({}, this._paxGlobal, headers.decodePax(buf));
2155
- break;
2156
- }
2157
- }
2158
- _consumeLongHeader() {
2159
- this._longHeader = false;
2160
- this._missing = overflow(this._header.size);
2161
- const buf = this._buffer.shift(this._header.size);
2162
- try {
2163
- this._decodeLongHeader(buf);
2164
- } catch (err) {
2165
- this._continueWrite(err);
2166
- return false;
2167
- }
2168
- return true;
2169
- }
2170
- _consumeStream() {
2171
- const buf = this._buffer.shiftFirst(this._missing);
2172
- if (buf === null) return false;
2173
- this._missing -= buf.byteLength;
2174
- const drained = this._stream.push(buf);
2175
- if (this._missing === 0) {
2176
- this._stream.push(null);
2177
- if (drained) this._stream._detach();
2178
- return drained && this._locked === false;
2179
- }
2180
- return drained;
2181
- }
2182
- _createStream() {
2183
- return new Source(this, this._header, this._offset);
2184
- }
2185
- _update() {
2186
- while (this._buffer.buffered > 0 && !this.destroying) {
2187
- if (this._missing > 0) {
2188
- if (this._stream !== null) {
2189
- if (this._consumeStream() === false) return;
2190
- continue;
2191
- }
2192
- if (this._longHeader === true) {
2193
- if (this._missing > this._buffer.buffered) break;
2194
- if (this._consumeLongHeader() === false) return false;
2195
- continue;
2196
- }
2197
- const ignore = this._buffer.shiftFirst(this._missing);
2198
- if (ignore !== null) this._missing -= ignore.byteLength;
2199
- continue;
2200
- }
2201
- if (this._buffer.buffered < 512) break;
2202
- if (this._stream !== null || this._consumeHeader() === false) return;
2203
- }
2204
- this._continueWrite(null);
2205
- }
2206
- _continueWrite(err) {
2207
- const cb = this._callback;
2208
- this._callback = noop;
2209
- cb(err);
2210
- }
2211
- _write(data, cb) {
2212
- this._callback = cb;
2213
- this._buffer.push(data);
2214
- this._update();
2215
- }
2216
- _final(cb) {
2217
- this._finished = this._missing === 0 && this._buffer.buffered === 0;
2218
- cb(this._finished ? null : new Error("Unexpected end of data"));
2219
- }
2220
- _predestroy() {
2221
- this._continueWrite(null);
2222
- }
2223
- _destroy(cb) {
2224
- if (this._stream) this._stream.destroy(getStreamError(this));
2225
- cb(null);
2226
- }
2227
- [Symbol.asyncIterator]() {
2228
- let error = null;
2229
- let promiseResolve = null;
2230
- let promiseReject = null;
2231
- let entryStream = null;
2232
- let entryCallback = null;
2233
- const extract3 = this;
2234
- this.on("entry", onentry);
2235
- this.on("error", (err) => {
2236
- error = err;
2237
- });
2238
- this.on("close", onclose);
2239
- return {
2240
- [Symbol.asyncIterator]() {
2241
- return this;
2242
- },
2243
- next() {
2244
- return new Promise(onnext);
2245
- },
2246
- return() {
2247
- return destroy(null);
2248
- },
2249
- throw(err) {
2250
- return destroy(err);
2251
- }
2252
- };
2253
- function consumeCallback(err) {
2254
- if (!entryCallback) return;
2255
- const cb = entryCallback;
2256
- entryCallback = null;
2257
- cb(err);
2258
- }
2259
- function onnext(resolve3, reject) {
2260
- if (error) {
2261
- return reject(error);
2262
- }
2263
- if (entryStream) {
2264
- resolve3({ value: entryStream, done: false });
2265
- entryStream = null;
2266
- return;
2267
- }
2268
- promiseResolve = resolve3;
2269
- promiseReject = reject;
2270
- consumeCallback(null);
2271
- if (extract3._finished && promiseResolve) {
2272
- promiseResolve({ value: void 0, done: true });
2273
- promiseResolve = promiseReject = null;
2274
- }
2275
- }
2276
- function onentry(header, stream, callback) {
2277
- entryCallback = callback;
2278
- stream.on("error", noop);
2279
- if (promiseResolve) {
2280
- promiseResolve({ value: stream, done: false });
2281
- promiseResolve = promiseReject = null;
2282
- } else {
2283
- entryStream = stream;
2284
- }
2285
- }
2286
- function onclose() {
2287
- consumeCallback(error);
2288
- if (!promiseResolve) return;
2289
- if (error) promiseReject(error);
2290
- else promiseResolve({ value: void 0, done: true });
2291
- promiseResolve = promiseReject = null;
2292
- }
2293
- function destroy(err) {
2294
- extract3.destroy(err);
2295
- consumeCallback(err);
2296
- return new Promise((resolve3, reject) => {
2297
- if (extract3.destroyed) return resolve3({ value: void 0, done: true });
2298
- extract3.once("close", function() {
2299
- if (err) reject(err);
2300
- else resolve3({ value: void 0, done: true });
2301
- });
2302
- });
2303
- }
2304
- }
2305
- };
2306
- module.exports = function extract3(opts) {
2307
- return new Extract(opts);
2308
- };
2309
- function noop() {
2310
- }
2311
- function overflow(size) {
2312
- size &= 511;
2313
- return size && 512 - size;
2314
- }
2315
- }
2316
- });
2317
-
2318
- // ../../node_modules/@sparticuz/chromium/node_modules/tar-stream/constants.js
2319
- var require_constants = __commonJS({
2320
- "../../node_modules/@sparticuz/chromium/node_modules/tar-stream/constants.js"(exports, module) {
2321
- var constants = {
2322
- // just for envs without fs
2323
- S_IFMT: 61440,
2324
- S_IFDIR: 16384,
2325
- S_IFCHR: 8192,
2326
- S_IFBLK: 24576,
2327
- S_IFIFO: 4096,
2328
- S_IFLNK: 40960
2329
- };
2330
- try {
2331
- module.exports = __require("fs").constants || constants;
2332
- } catch {
2333
- module.exports = constants;
2334
- }
2335
- }
2336
- });
2337
-
2338
- // ../../node_modules/@sparticuz/chromium/node_modules/tar-stream/pack.js
2339
- var require_pack = __commonJS({
2340
- "../../node_modules/@sparticuz/chromium/node_modules/tar-stream/pack.js"(exports, module) {
2341
- var { Readable: Readable2, Writable, getStreamError } = require_streamx();
2342
- var b4a = require_b4a();
2343
- var constants = require_constants();
2344
- var headers = require_headers();
2345
- var DMODE = 493;
2346
- var FMODE = 420;
2347
- var END_OF_TAR = b4a.alloc(1024);
2348
- var Sink = class extends Writable {
2349
- constructor(pack, header, callback) {
2350
- super({ mapWritable, eagerOpen: true });
2351
- this.written = 0;
2352
- this.header = header;
2353
- this._callback = callback;
2354
- this._linkname = null;
2355
- this._isLinkname = header.type === "symlink" && !header.linkname;
2356
- this._isVoid = header.type !== "file" && header.type !== "contiguous-file";
2357
- this._finished = false;
2358
- this._pack = pack;
2359
- this._openCallback = null;
2360
- if (this._pack._stream === null) this._pack._stream = this;
2361
- else this._pack._pending.push(this);
2362
- }
2363
- _open(cb) {
2364
- this._openCallback = cb;
2365
- if (this._pack._stream === this) this._continueOpen();
2366
- }
2367
- _continuePack(err) {
2368
- if (this._callback === null) return;
2369
- const callback = this._callback;
2370
- this._callback = null;
2371
- callback(err);
2372
- }
2373
- _continueOpen() {
2374
- if (this._pack._stream === null) this._pack._stream = this;
2375
- const cb = this._openCallback;
2376
- this._openCallback = null;
2377
- if (cb === null) return;
2378
- if (this._pack.destroying) return cb(new Error("pack stream destroyed"));
2379
- if (this._pack._finalized) return cb(new Error("pack stream is already finalized"));
2380
- this._pack._stream = this;
2381
- if (!this._isLinkname) {
2382
- this._pack._encode(this.header);
2383
- }
2384
- if (this._isVoid) {
2385
- this._finish();
2386
- this._continuePack(null);
2387
- }
2388
- cb(null);
2389
- }
2390
- _write(data, cb) {
2391
- if (this._isLinkname) {
2392
- this._linkname = this._linkname ? b4a.concat([this._linkname, data]) : data;
2393
- return cb(null);
2394
- }
2395
- if (this._isVoid) {
2396
- if (data.byteLength > 0) {
2397
- return cb(new Error("No body allowed for this entry"));
2398
- }
2399
- return cb();
2400
- }
2401
- this.written += data.byteLength;
2402
- if (this._pack.push(data)) return cb();
2403
- this._pack._drain = cb;
2404
- }
2405
- _finish() {
2406
- if (this._finished) return;
2407
- this._finished = true;
2408
- if (this._isLinkname) {
2409
- this.header.linkname = this._linkname ? b4a.toString(this._linkname, "utf-8") : "";
2410
- this._pack._encode(this.header);
2411
- }
2412
- overflow(this._pack, this.header.size);
2413
- this._pack._done(this);
2414
- }
2415
- _final(cb) {
2416
- if (this.written !== this.header.size) {
2417
- return cb(new Error("Size mismatch"));
2418
- }
2419
- this._finish();
2420
- cb(null);
2421
- }
2422
- _getError() {
2423
- return getStreamError(this) || new Error("tar entry destroyed");
2424
- }
2425
- _predestroy() {
2426
- this._pack.destroy(this._getError());
2427
- }
2428
- _destroy(cb) {
2429
- this._pack._done(this);
2430
- this._continuePack(this._finished ? null : this._getError());
2431
- cb();
2432
- }
2433
- };
2434
- var Pack = class extends Readable2 {
2435
- constructor(opts) {
2436
- super(opts);
2437
- this._drain = noop;
2438
- this._finalized = false;
2439
- this._finalizing = false;
2440
- this._pending = [];
2441
- this._stream = null;
2442
- }
2443
- entry(header, buffer, callback) {
2444
- if (this._finalized || this.destroying) throw new Error("already finalized or destroyed");
2445
- if (typeof buffer === "function") {
2446
- callback = buffer;
2447
- buffer = null;
2448
- }
2449
- if (!callback) callback = noop;
2450
- if (!header.size || header.type === "symlink") header.size = 0;
2451
- if (!header.type) header.type = modeToType(header.mode);
2452
- if (!header.mode) header.mode = header.type === "directory" ? DMODE : FMODE;
2453
- if (!header.uid) header.uid = 0;
2454
- if (!header.gid) header.gid = 0;
2455
- if (!header.mtime) header.mtime = /* @__PURE__ */ new Date();
2456
- if (typeof buffer === "string") buffer = b4a.from(buffer);
2457
- const sink = new Sink(this, header, callback);
2458
- if (b4a.isBuffer(buffer)) {
2459
- header.size = buffer.byteLength;
2460
- sink.write(buffer);
2461
- sink.end();
2462
- return sink;
2463
- }
2464
- if (sink._isVoid) {
2465
- return sink;
2466
- }
2467
- return sink;
2468
- }
2469
- finalize() {
2470
- if (this._stream || this._pending.length > 0) {
2471
- this._finalizing = true;
2472
- return;
2473
- }
2474
- if (this._finalized) return;
2475
- this._finalized = true;
2476
- this.push(END_OF_TAR);
2477
- this.push(null);
2478
- }
2479
- _done(stream) {
2480
- if (stream !== this._stream) return;
2481
- this._stream = null;
2482
- if (this._finalizing) this.finalize();
2483
- if (this._pending.length) this._pending.shift()._continueOpen();
2484
- }
2485
- _encode(header) {
2486
- if (!header.pax) {
2487
- const buf = headers.encode(header);
2488
- if (buf) {
2489
- this.push(buf);
2490
- return;
2491
- }
2492
- }
2493
- this._encodePax(header);
2494
- }
2495
- _encodePax(header) {
2496
- const paxHeader = headers.encodePax({
2497
- name: header.name,
2498
- linkname: header.linkname,
2499
- pax: header.pax
2500
- });
2501
- const newHeader = {
2502
- name: "PaxHeader",
2503
- mode: header.mode,
2504
- uid: header.uid,
2505
- gid: header.gid,
2506
- size: paxHeader.byteLength,
2507
- mtime: header.mtime,
2508
- type: "pax-header",
2509
- linkname: header.linkname && "PaxHeader",
2510
- uname: header.uname,
2511
- gname: header.gname,
2512
- devmajor: header.devmajor,
2513
- devminor: header.devminor
2514
- };
2515
- this.push(headers.encode(newHeader));
2516
- this.push(paxHeader);
2517
- overflow(this, paxHeader.byteLength);
2518
- newHeader.size = header.size;
2519
- newHeader.type = header.type;
2520
- this.push(headers.encode(newHeader));
2521
- }
2522
- _doDrain() {
2523
- const drain = this._drain;
2524
- this._drain = noop;
2525
- drain();
2526
- }
2527
- _predestroy() {
2528
- const err = getStreamError(this);
2529
- if (this._stream) this._stream.destroy(err);
2530
- while (this._pending.length) {
2531
- const stream = this._pending.shift();
2532
- stream.destroy(err);
2533
- stream._continueOpen();
2534
- }
2535
- this._doDrain();
2536
- }
2537
- _read(cb) {
2538
- this._doDrain();
2539
- cb();
2540
- }
2541
- };
2542
- module.exports = function pack(opts) {
2543
- return new Pack(opts);
2544
- };
2545
- function modeToType(mode) {
2546
- switch (mode & constants.S_IFMT) {
2547
- case constants.S_IFBLK:
2548
- return "block-device";
2549
- case constants.S_IFCHR:
2550
- return "character-device";
2551
- case constants.S_IFDIR:
2552
- return "directory";
2553
- case constants.S_IFIFO:
2554
- return "fifo";
2555
- case constants.S_IFLNK:
2556
- return "symlink";
2557
- }
2558
- return "file";
2559
- }
2560
- function noop() {
2561
- }
2562
- function overflow(self, size) {
2563
- size &= 511;
2564
- if (size) self.push(END_OF_TAR.subarray(0, 512 - size));
2565
- }
2566
- function mapWritable(buf) {
2567
- return b4a.isBuffer(buf) ? buf : b4a.from(buf);
2568
- }
2569
- }
2570
- });
2571
-
2572
- // ../../node_modules/@sparticuz/chromium/node_modules/tar-stream/index.js
2573
- var require_tar_stream = __commonJS({
2574
- "../../node_modules/@sparticuz/chromium/node_modules/tar-stream/index.js"(exports) {
2575
- exports.extract = require_extract();
2576
- exports.pack = require_pack();
2577
- }
2578
- });
2579
-
2580
- // ../../node_modules/wrappy/wrappy.js
2581
- var require_wrappy = __commonJS({
2582
- "../../node_modules/wrappy/wrappy.js"(exports, module) {
2583
- module.exports = wrappy;
2584
- function wrappy(fn, cb) {
2585
- if (fn && cb) return wrappy(fn)(cb);
2586
- if (typeof fn !== "function")
2587
- throw new TypeError("need wrapper function");
2588
- Object.keys(fn).forEach(function(k) {
2589
- wrapper[k] = fn[k];
2590
- });
2591
- return wrapper;
2592
- function wrapper() {
2593
- var args = new Array(arguments.length);
2594
- for (var i = 0; i < args.length; i++) {
2595
- args[i] = arguments[i];
2596
- }
2597
- var ret = fn.apply(this, args);
2598
- var cb2 = args[args.length - 1];
2599
- if (typeof ret === "function" && ret !== cb2) {
2600
- Object.keys(cb2).forEach(function(k) {
2601
- ret[k] = cb2[k];
2602
- });
2603
- }
2604
- return ret;
2605
- }
2606
- }
2607
- }
2608
- });
2609
-
2610
- // ../../node_modules/once/once.js
2611
- var require_once = __commonJS({
2612
- "../../node_modules/once/once.js"(exports, module) {
2613
- var wrappy = require_wrappy();
2614
- module.exports = wrappy(once);
2615
- module.exports.strict = wrappy(onceStrict);
2616
- once.proto = once(function() {
2617
- Object.defineProperty(Function.prototype, "once", {
2618
- value: function() {
2619
- return once(this);
2620
- },
2621
- configurable: true
2622
- });
2623
- Object.defineProperty(Function.prototype, "onceStrict", {
2624
- value: function() {
2625
- return onceStrict(this);
2626
- },
2627
- configurable: true
2628
- });
2629
- });
2630
- function once(fn) {
2631
- var f = function() {
2632
- if (f.called) return f.value;
2633
- f.called = true;
2634
- return f.value = fn.apply(this, arguments);
2635
- };
2636
- f.called = false;
2637
- return f;
2638
- }
2639
- function onceStrict(fn) {
2640
- var f = function() {
2641
- if (f.called)
2642
- throw new Error(f.onceError);
2643
- f.called = true;
2644
- return f.value = fn.apply(this, arguments);
2645
- };
2646
- var name = fn.name || "Function wrapped with `once`";
2647
- f.onceError = name + " shouldn't be called more than once";
2648
- f.called = false;
2649
- return f;
2650
- }
2651
- }
2652
- });
2653
-
2654
- // ../../node_modules/end-of-stream/index.js
2655
- var require_end_of_stream = __commonJS({
2656
- "../../node_modules/end-of-stream/index.js"(exports, module) {
2657
- var once = require_once();
2658
- var noop = function() {
2659
- };
2660
- var qnt = global.Bare ? queueMicrotask : process.nextTick.bind(process);
2661
- var isRequest = function(stream) {
2662
- return stream.setHeader && typeof stream.abort === "function";
2663
- };
2664
- var isChildProcess = function(stream) {
2665
- return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3;
2666
- };
2667
- var eos = function(stream, opts, callback) {
2668
- if (typeof opts === "function") return eos(stream, null, opts);
2669
- if (!opts) opts = {};
2670
- callback = once(callback || noop);
2671
- var ws = stream._writableState;
2672
- var rs = stream._readableState;
2673
- var readable = opts.readable || opts.readable !== false && stream.readable;
2674
- var writable = opts.writable || opts.writable !== false && stream.writable;
2675
- var cancelled = false;
2676
- var onlegacyfinish = function() {
2677
- if (!stream.writable) onfinish();
2678
- };
2679
- var onfinish = function() {
2680
- writable = false;
2681
- if (!readable) callback.call(stream);
2682
- };
2683
- var onend = function() {
2684
- readable = false;
2685
- if (!writable) callback.call(stream);
2686
- };
2687
- var onexit = function(exitCode) {
2688
- callback.call(stream, exitCode ? new Error("exited with error code: " + exitCode) : null);
2689
- };
2690
- var onerror = function(err) {
2691
- callback.call(stream, err);
2692
- };
2693
- var onclose = function() {
2694
- qnt(onclosenexttick);
2695
- };
2696
- var onclosenexttick = function() {
2697
- if (cancelled) return;
2698
- if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error("premature close"));
2699
- if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error("premature close"));
2700
- };
2701
- var onrequest = function() {
2702
- stream.req.on("finish", onfinish);
2703
- };
2704
- if (isRequest(stream)) {
2705
- stream.on("complete", onfinish);
2706
- stream.on("abort", onclose);
2707
- if (stream.req) onrequest();
2708
- else stream.on("request", onrequest);
2709
- } else if (writable && !ws) {
2710
- stream.on("end", onlegacyfinish);
2711
- stream.on("close", onlegacyfinish);
2712
- }
2713
- if (isChildProcess(stream)) stream.on("exit", onexit);
2714
- stream.on("end", onend);
2715
- stream.on("finish", onfinish);
2716
- if (opts.error !== false) stream.on("error", onerror);
2717
- stream.on("close", onclose);
2718
- return function() {
2719
- cancelled = true;
2720
- stream.removeListener("complete", onfinish);
2721
- stream.removeListener("abort", onclose);
2722
- stream.removeListener("request", onrequest);
2723
- if (stream.req) stream.req.removeListener("finish", onfinish);
2724
- stream.removeListener("end", onlegacyfinish);
2725
- stream.removeListener("close", onlegacyfinish);
2726
- stream.removeListener("finish", onfinish);
2727
- stream.removeListener("exit", onexit);
2728
- stream.removeListener("end", onend);
2729
- stream.removeListener("error", onerror);
2730
- stream.removeListener("close", onclose);
2731
- };
2732
- };
2733
- module.exports = eos;
2734
- }
2735
- });
2736
-
2737
- // ../../node_modules/pump/index.js
2738
- var require_pump = __commonJS({
2739
- "../../node_modules/pump/index.js"(exports, module) {
2740
- var once = require_once();
2741
- var eos = require_end_of_stream();
2742
- var fs;
2743
- try {
2744
- fs = __require("fs");
2745
- } catch (e) {
2746
- }
2747
- var noop = function() {
2748
- };
2749
- var ancient = typeof process === "undefined" ? false : /^v?\.0/.test(process.version);
2750
- var isFn = function(fn) {
2751
- return typeof fn === "function";
2752
- };
2753
- var isFS = function(stream) {
2754
- if (!ancient) return false;
2755
- if (!fs) return false;
2756
- return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close);
2757
- };
2758
- var isRequest = function(stream) {
2759
- return stream.setHeader && isFn(stream.abort);
2760
- };
2761
- var destroyer = function(stream, reading, writing, callback) {
2762
- callback = once(callback);
2763
- var closed = false;
2764
- stream.on("close", function() {
2765
- closed = true;
2766
- });
2767
- eos(stream, { readable: reading, writable: writing }, function(err) {
2768
- if (err) return callback(err);
2769
- closed = true;
2770
- callback();
2771
- });
2772
- var destroyed = false;
2773
- return function(err) {
2774
- if (closed) return;
2775
- if (destroyed) return;
2776
- destroyed = true;
2777
- if (isFS(stream)) return stream.close(noop);
2778
- if (isRequest(stream)) return stream.abort();
2779
- if (isFn(stream.destroy)) return stream.destroy();
2780
- callback(err || new Error("stream was destroyed"));
2781
- };
2782
- };
2783
- var call = function(fn) {
2784
- fn();
2785
- };
2786
- var pipe = function(from, to) {
2787
- return from.pipe(to);
2788
- };
2789
- var pump = function() {
2790
- var streams = Array.prototype.slice.call(arguments);
2791
- var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop;
2792
- if (Array.isArray(streams[0])) streams = streams[0];
2793
- if (streams.length < 2) throw new Error("pump requires two streams per minimum");
2794
- var error;
2795
- var destroys = streams.map(function(stream, i) {
2796
- var reading = i < streams.length - 1;
2797
- var writing = i > 0;
2798
- return destroyer(stream, reading, writing, function(err) {
2799
- if (!error) error = err;
2800
- if (err) destroys.forEach(call);
2801
- if (reading) return;
2802
- destroys.forEach(call);
2803
- callback(error);
2804
- });
2805
- });
2806
- return streams.reduce(pipe);
2807
- };
2808
- module.exports = pump;
2809
- }
2810
- });
2811
-
2812
- // ../../node_modules/@sparticuz/chromium/node_modules/tar-fs/index.js
2813
- var require_tar_fs = __commonJS({
2814
- "../../node_modules/@sparticuz/chromium/node_modules/tar-fs/index.js"(exports) {
2815
- var tar = require_tar_stream();
2816
- var pump = require_pump();
2817
- var fs = __require("fs");
2818
- var path = __require("path");
2819
- var win32 = (global.Bare ? global.Bare.platform : process.platform) === "win32";
2820
- exports.pack = function pack(cwd, opts) {
2821
- if (!cwd) cwd = ".";
2822
- if (!opts) opts = {};
2823
- const xfs = opts.fs || fs;
2824
- const ignore = opts.ignore || opts.filter || noop;
2825
- const mapStream = opts.mapStream || echo;
2826
- const statNext = statAll(xfs, opts.dereference ? xfs.stat : xfs.lstat, cwd, ignore, opts.entries, opts.sort);
2827
- const strict = opts.strict !== false;
2828
- const umask = typeof opts.umask === "number" ? ~opts.umask : ~processUmask();
2829
- const pack2 = opts.pack || tar.pack();
2830
- const finish = opts.finish || noop;
2831
- let map = opts.map || noop;
2832
- let dmode = typeof opts.dmode === "number" ? opts.dmode : 0;
2833
- let fmode = typeof opts.fmode === "number" ? opts.fmode : 0;
2834
- if (opts.strip) map = strip(map, opts.strip);
2835
- if (opts.readable) {
2836
- dmode |= parseInt(555, 8);
2837
- fmode |= parseInt(444, 8);
2838
- }
2839
- if (opts.writable) {
2840
- dmode |= parseInt(333, 8);
2841
- fmode |= parseInt(222, 8);
2842
- }
2843
- onnextentry();
2844
- function onsymlink(filename, header) {
2845
- xfs.readlink(path.join(cwd, filename), function(err, linkname) {
2846
- if (err) return pack2.destroy(err);
2847
- header.linkname = normalize(linkname);
2848
- pack2.entry(header, onnextentry);
2849
- });
2850
- }
2851
- function onstat(err, filename, stat) {
2852
- if (pack2.destroyed) return;
2853
- if (err) return pack2.destroy(err);
2854
- if (!filename) {
2855
- if (opts.finalize !== false) pack2.finalize();
2856
- return finish(pack2);
2857
- }
2858
- if (stat.isSocket()) return onnextentry();
2859
- let header = {
2860
- name: normalize(filename),
2861
- mode: (stat.mode | (stat.isDirectory() ? dmode : fmode)) & umask,
2862
- mtime: stat.mtime,
2863
- size: stat.size,
2864
- type: "file",
2865
- uid: stat.uid,
2866
- gid: stat.gid
2867
- };
2868
- if (stat.isDirectory()) {
2869
- header.size = 0;
2870
- header.type = "directory";
2871
- header = map(header) || header;
2872
- return pack2.entry(header, onnextentry);
2873
- }
2874
- if (stat.isSymbolicLink()) {
2875
- header.size = 0;
2876
- header.type = "symlink";
2877
- header = map(header) || header;
2878
- return onsymlink(filename, header);
2879
- }
2880
- header = map(header) || header;
2881
- if (!stat.isFile()) {
2882
- if (strict) return pack2.destroy(new Error("unsupported type for " + filename));
2883
- return onnextentry();
2884
- }
2885
- const entry = pack2.entry(header, onnextentry);
2886
- const rs = mapStream(xfs.createReadStream(path.join(cwd, filename), { start: 0, end: header.size > 0 ? header.size - 1 : header.size }), header);
2887
- rs.on("error", function(err2) {
2888
- entry.destroy(err2);
2889
- });
2890
- pump(rs, entry);
2891
- }
2892
- function onnextentry(err) {
2893
- if (err) return pack2.destroy(err);
2894
- statNext(onstat);
2895
- }
2896
- return pack2;
2897
- };
2898
- function head(list) {
2899
- return list.length ? list[list.length - 1] : null;
2900
- }
2901
- function processGetuid() {
2902
- return !global.Bare && process.getuid ? process.getuid() : -1;
2903
- }
2904
- function processUmask() {
2905
- return !global.Bare && process.umask ? process.umask() : 0;
2906
- }
2907
- exports.extract = function extract3(cwd, opts) {
2908
- if (!cwd) cwd = ".";
2909
- if (!opts) opts = {};
2910
- cwd = path.resolve(cwd);
2911
- const xfs = opts.fs || fs;
2912
- const ignore = opts.ignore || opts.filter || noop;
2913
- const mapStream = opts.mapStream || echo;
2914
- const own = opts.chown !== false && !win32 && processGetuid() === 0;
2915
- const extract4 = opts.extract || tar.extract();
2916
- const stack = [];
2917
- const now = /* @__PURE__ */ new Date();
2918
- const umask = typeof opts.umask === "number" ? ~opts.umask : ~processUmask();
2919
- const strict = opts.strict !== false;
2920
- const validateSymLinks = opts.validateSymlinks !== false;
2921
- let map = opts.map || noop;
2922
- let dmode = typeof opts.dmode === "number" ? opts.dmode : 0;
2923
- let fmode = typeof opts.fmode === "number" ? opts.fmode : 0;
2924
- if (opts.strip) map = strip(map, opts.strip);
2925
- if (opts.readable) {
2926
- dmode |= parseInt(555, 8);
2927
- fmode |= parseInt(444, 8);
2928
- }
2929
- if (opts.writable) {
2930
- dmode |= parseInt(333, 8);
2931
- fmode |= parseInt(222, 8);
2932
- }
2933
- extract4.on("entry", onentry);
2934
- if (opts.finish) extract4.on("finish", opts.finish);
2935
- return extract4;
2936
- function onentry(header, stream, next) {
2937
- header = map(header) || header;
2938
- header.name = normalize(header.name);
2939
- const name = path.join(cwd, path.join("/", header.name));
2940
- if (ignore(name, header)) {
2941
- stream.resume();
2942
- return next();
2943
- }
2944
- const dir = path.join(name, ".") === path.join(cwd, ".") ? cwd : path.dirname(name);
2945
- validate(xfs, dir, path.join(cwd, "."), function(err, valid) {
2946
- if (err) return next(err);
2947
- if (!valid) return next(new Error(dir + " is not a valid path"));
2948
- if (header.type === "directory") {
2949
- stack.push([name, header.mtime]);
2950
- return mkdirfix(name, {
2951
- uid: header.uid,
2952
- gid: header.gid,
2953
- mode: header.mode
2954
- }, stat);
2955
- }
2956
- mkdirfix(dir, {
2957
- uid: header.uid,
2958
- gid: header.gid,
2959
- // normally, the folders with rights and owner should be part of the TAR file
2960
- // if this is not the case, create folder for same user as file and with
2961
- // standard permissions of 0o755 (rwxr-xr-x)
2962
- mode: 493
2963
- }, function(err2) {
2964
- if (err2) return next(err2);
2965
- switch (header.type) {
2966
- case "file":
2967
- return onfile();
2968
- case "link":
2969
- return onlink();
2970
- case "symlink":
2971
- return onsymlink();
2972
- }
2973
- if (strict) return next(new Error("unsupported type for " + name + " (" + header.type + ")"));
2974
- stream.resume();
2975
- next();
2976
- });
2977
- });
2978
- function stat(err) {
2979
- if (err) return next(err);
2980
- if (path.join(name, ".") === path.join(cwd, ".")) return next();
2981
- utimes(name, header, function(err2) {
2982
- if (err2) return next(err2);
2983
- if (win32) return next();
2984
- chperm(name, header, next);
2985
- });
2986
- }
2987
- function onsymlink() {
2988
- if (win32) return next();
2989
- xfs.unlink(name, function() {
2990
- const dst = path.resolve(path.dirname(name), header.linkname);
2991
- if (!inCwd(dst) && (validateSymLinks || opts.strip)) return next(new Error(name + " is not a valid symlink"));
2992
- validateNotSymlink(xfs, dst, path.join(cwd, "."), function(err, valid) {
2993
- if (err) return next(err);
2994
- if (!valid && validateSymLinks) return next(new Error(name + " is not a valid symlink"));
2995
- xfs.symlink(header.linkname, name, stat);
2996
- });
2997
- });
2998
- }
2999
- function onlink() {
3000
- if (win32) return next();
3001
- xfs.unlink(name, function() {
3002
- const link = path.join(cwd, path.join("/", header.linkname));
3003
- xfs.realpath(link, function(err, dst) {
3004
- if (err || !inCwd(dst)) return next(new Error(name + " is not a valid hardlink"));
3005
- xfs.link(dst, name, function(err2) {
3006
- if (err2 && err2.code === "EPERM" && opts.hardlinkAsFilesFallback) {
3007
- stream = xfs.createReadStream(dst);
3008
- return onfile();
3009
- }
3010
- stat(err2);
3011
- });
3012
- });
3013
- });
3014
- }
3015
- function inCwd(dst) {
3016
- return dst === cwd || dst.startsWith(cwd + path.sep);
3017
- }
3018
- function onfile() {
3019
- xfs.lstat(name, function(err, st) {
3020
- if (!err && st.isSymbolicLink()) return xfs.unlink(name, onwrite);
3021
- onwrite();
3022
- });
3023
- function onwrite(err) {
3024
- if (err) return next(err);
3025
- const ws = xfs.createWriteStream(name);
3026
- const rs = mapStream(stream, header);
3027
- ws.on("error", function(err2) {
3028
- rs.destroy(err2);
3029
- });
3030
- pump(rs, ws, function(err2) {
3031
- if (err2) return next(err2);
3032
- ws.on("close", stat);
3033
- });
3034
- }
3035
- }
3036
- }
3037
- function utimesParent(name, cb) {
3038
- let top;
3039
- while ((top = head(stack)) && name.slice(0, top[0].length) !== top[0]) stack.pop();
3040
- if (!top) return cb();
3041
- xfs.utimes(top[0], now, top[1], cb);
3042
- }
3043
- function utimes(name, header, cb) {
3044
- if (opts.utimes === false) return cb();
3045
- if (header.type === "directory") return xfs.utimes(name, now, header.mtime, cb);
3046
- if (header.type === "symlink") return utimesParent(name, cb);
3047
- xfs.utimes(name, now, header.mtime, function(err) {
3048
- if (err) return cb(err);
3049
- utimesParent(name, cb);
3050
- });
3051
- }
3052
- function chperm(name, header, cb) {
3053
- const link = header.type === "symlink";
3054
- const chmod = link ? xfs.lchmod : xfs.chmod;
3055
- const chown = link ? xfs.lchown : xfs.chown;
3056
- if (!chmod) return cb();
3057
- const mode = (header.mode | (header.type === "directory" ? dmode : fmode)) & umask & 511;
3058
- if (chown && own) chown.call(xfs, name, header.uid, header.gid, onchown);
3059
- else onchown(null);
3060
- function onchown(err) {
3061
- if (err) return cb(err);
3062
- if (!chmod) return cb();
3063
- chmod.call(xfs, name, mode, cb);
3064
- }
3065
- }
3066
- function mkdirfix(name, opts2, cb) {
3067
- xfs.stat(name, function(err) {
3068
- if (!err) return cb(null);
3069
- if (err.code !== "ENOENT") return cb(err);
3070
- xfs.mkdir(name, { mode: opts2.mode, recursive: true }, function(err2, made) {
3071
- if (err2) return cb(err2);
3072
- chperm(name, opts2, cb);
3073
- });
3074
- });
3075
- }
3076
- };
3077
- function validateNotSymlink(fs2, name, root, cb) {
3078
- if (name === root) return cb(null, true);
3079
- if (!name.startsWith(root + path.sep)) return cb(null, false);
3080
- fs2.lstat(name, function(err, st) {
3081
- if (err && err.code !== "ENOENT" && err.code !== "EPERM") return cb(err);
3082
- if (err || !st.isSymbolicLink()) return validateNotSymlink(fs2, path.join(name, ".."), root, cb);
3083
- cb(null, false);
3084
- });
3085
- }
3086
- function validate(fs2, name, root, cb) {
3087
- if (name === root) return cb(null, true);
3088
- fs2.lstat(name, function(err, st) {
3089
- if (err && err.code !== "ENOENT" && err.code !== "EPERM") return cb(err);
3090
- if (err || st.isDirectory()) return validate(fs2, path.join(name, ".."), root, cb);
3091
- cb(null, false);
3092
- });
3093
- }
3094
- function inside(root, name) {
3095
- return name === root || name.startsWith(root + path.sep);
3096
- }
3097
- function noop() {
3098
- }
3099
- function echo(name) {
3100
- return name;
3101
- }
3102
- function normalize(name) {
3103
- return win32 ? name.replace(/\\/g, "/").replace(/[:?<>|]/g, "_") : name;
3104
- }
3105
- function statAll(fs2, stat, cwd, ignore, entries, sort) {
3106
- if (!entries) entries = ["."];
3107
- const queue = entries.slice(0);
3108
- const root = path.resolve(cwd);
3109
- return function loop(callback) {
3110
- if (!queue.length) return callback(null);
3111
- const next = queue.shift();
3112
- const nextAbs = path.join(cwd, next);
3113
- if (!inside(root, path.resolve(cwd, next))) return callback(new Error(next + " is not a valid path"));
3114
- stat.call(fs2, nextAbs, function(err, stat2) {
3115
- if (err) return callback(entries.indexOf(next) === -1 && err.code === "ENOENT" ? null : err);
3116
- if (!stat2.isDirectory()) return callback(null, next, stat2);
3117
- fs2.readdir(nextAbs, function(err2, files) {
3118
- if (err2) return callback(err2);
3119
- if (sort) files.sort();
3120
- for (let i = 0; i < files.length; i++) {
3121
- if (!ignore(path.join(cwd, next, files[i]))) queue.push(path.join(next, files[i]));
3122
- }
3123
- callback(null, next, stat2);
3124
- });
3125
- });
3126
- };
3127
- }
3128
- function strip(map, level) {
3129
- return function(header) {
3130
- header.name = header.name.split("/").slice(level).join("/");
3131
- const linkname = header.linkname;
3132
- if (linkname && (header.type === "link" || path.isAbsolute(linkname))) {
3133
- header.linkname = linkname.split("/").slice(level).join("/");
3134
- }
3135
- return map(header);
3136
- };
3137
- }
3138
- }
3139
- });
3140
- var import_tar_fs, setupLambdaEnvironment, isValidUrl, isRunningInAmazonLinux2023, downloadAndExtract;
3141
- var init_helper = __esm({
3142
- "../../node_modules/@sparticuz/chromium/build/helper.js"() {
3143
- import_tar_fs = __toESM(require_tar_fs());
3144
- setupLambdaEnvironment = (baseLibPath) => {
3145
- process.env["FONTCONFIG_PATH"] ??= join(tmpdir(), "fonts");
3146
- process.env["HOME"] ??= tmpdir();
3147
- if (process.env["LD_LIBRARY_PATH"] === void 0) {
3148
- process.env["LD_LIBRARY_PATH"] = baseLibPath;
3149
- } else if (!process.env["LD_LIBRARY_PATH"].startsWith(baseLibPath)) {
3150
- process.env["LD_LIBRARY_PATH"] = [
3151
- baseLibPath,
3152
- ...new Set(process.env["LD_LIBRARY_PATH"].split(":"))
3153
- ].join(":");
3154
- }
3155
- };
3156
- isValidUrl = (input) => {
3157
- try {
3158
- const url = new URL(input);
3159
- if (url.protocol === "https:")
3160
- return true;
3161
- if (url.protocol === "http:" && (url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]")) {
3162
- return true;
3163
- }
3164
- return false;
3165
- } catch {
3166
- return false;
3167
- }
3168
- };
3169
- isRunningInAmazonLinux2023 = (nodeMajorVersion2) => {
3170
- const awsExecEnv = process.env["AWS_EXECUTION_ENV"] ?? "";
3171
- const awsLambdaJsRuntime = process.env["AWS_LAMBDA_JS_RUNTIME"] ?? "";
3172
- const codebuildImage = process.env["CODEBUILD_BUILD_IMAGE"] ?? "";
3173
- if (awsExecEnv.includes("20.x") || awsExecEnv.includes("22.x") || awsExecEnv.includes("24.x") || awsLambdaJsRuntime.includes("20.x") || awsLambdaJsRuntime.includes("22.x") || awsLambdaJsRuntime.includes("24.x") || codebuildImage.includes("nodejs20") || codebuildImage.includes("nodejs22") || codebuildImage.includes("nodejs24")) {
3174
- return true;
3175
- }
3176
- if (process.env["VERCEL"] && nodeMajorVersion2 >= 20) {
3177
- return true;
3178
- }
3179
- return false;
3180
- };
3181
- downloadAndExtract = async (url) => {
3182
- const destDir = join(tmpdir(), "chromium-pack");
3183
- const response = await fetch(url, {
3184
- redirect: "follow",
3185
- signal: AbortSignal.timeout(3e5)
3186
- });
3187
- if (!response.ok) {
3188
- throw new Error(`Unexpected status code: ${String(response.status)}.`);
3189
- }
3190
- if (!response.body) {
3191
- throw new Error("Response body is empty.");
3192
- }
3193
- try {
3194
- await pipeline(Readable.fromWeb(response.body), (0, import_tar_fs.extract)(destDir));
3195
- } catch (error) {
3196
- await new Promise((resolve3) => {
3197
- rm(destDir, { force: true, recursive: true }, () => {
3198
- resolve3();
3199
- });
3200
- });
3201
- throw error;
3202
- }
3203
- return destDir;
3204
- };
3205
- }
3206
- });
3207
- var import_tar_fs2, ARCHIVE_EXTENSION_REGEX, TAR_EXTENSION_REGEX, BROTLI_EXTENSION_REGEX, GZIP_EXTENSION_REGEX, inflate;
3208
- var init_lambdafs = __esm({
3209
- "../../node_modules/@sparticuz/chromium/build/lambdafs.js"() {
3210
- import_tar_fs2 = __toESM(require_tar_fs());
3211
- ARCHIVE_EXTENSION_REGEX = /\.(?:t(?:ar(?:\.(?:br|gz))?|br|gz)|br|gz)$/i;
3212
- TAR_EXTENSION_REGEX = /\.t(?:ar(?:\.(?:br|gz))?|br|gz)$/i;
3213
- BROTLI_EXTENSION_REGEX = /br$/i;
3214
- GZIP_EXTENSION_REGEX = /gz$/i;
3215
- inflate = (filePath) => {
3216
- const output = filePath.includes("swiftshader") ? tmpdir() : join(tmpdir(), basename(filePath).replace(ARCHIVE_EXTENSION_REGEX, ""));
3217
- return new Promise((resolve3, reject) => {
3218
- if (filePath.includes("swiftshader")) {
3219
- if (existsSync(`${output}/libGLESv2.so`)) {
3220
- resolve3(output);
3221
- return;
3222
- }
3223
- } else if (existsSync(output)) {
3224
- resolve3(output);
3225
- return;
3226
- }
3227
- const isBrotli = BROTLI_EXTENSION_REGEX.test(filePath);
3228
- const isGzip = GZIP_EXTENSION_REGEX.test(filePath);
3229
- const isTar = TAR_EXTENSION_REGEX.test(filePath);
3230
- const highWaterMark = 2 ** 22;
3231
- const source = createReadStream(filePath, { highWaterMark });
3232
- let target;
3233
- const handleError = (error) => {
3234
- reject(error);
3235
- };
3236
- source.once("error", handleError);
3237
- if (isTar) {
3238
- target = (0, import_tar_fs2.extract)(output);
3239
- target.once("finish", () => {
3240
- resolve3(output);
3241
- });
3242
- } else {
3243
- target = createWriteStream(output, { mode: 448 });
3244
- target.once("close", () => {
3245
- resolve3(output);
3246
- });
3247
- }
3248
- target.once("error", handleError);
3249
- if (isBrotli || isGzip) {
3250
- const decompressor = isBrotli ? createBrotliDecompress({ chunkSize: 2 ** 21 }) : createUnzip({ chunkSize: 2 ** 21 });
3251
- decompressor.once("error", handleError);
3252
- source.pipe(decompressor).pipe(target);
3253
- } else {
3254
- source.pipe(target);
3255
- }
3256
- });
3257
- };
3258
- }
3259
- });
3260
- function getBinPath() {
3261
- return join(dirname(fileURLToPath(import.meta.url)), "..", "bin");
3262
- }
3263
- var init_paths = __esm({
3264
- "../../node_modules/@sparticuz/chromium/build/paths.js"() {
3265
- }
3266
- });
3267
-
3268
- // ../../node_modules/@sparticuz/chromium/build/index.js
3269
- var build_exports = {};
3270
- __export(build_exports, {
3271
- default: () => build_default,
3272
- inflate: () => inflate,
3273
- setupLambdaEnvironment: () => setupLambdaEnvironment
3274
- });
3275
- var nodeMajorVersion, Chromium, build_default;
3276
- var init_build = __esm({
3277
- "../../node_modules/@sparticuz/chromium/build/index.js"() {
3278
- init_helper();
3279
- init_lambdafs();
3280
- init_paths();
3281
- init_helper();
3282
- init_lambdafs();
3283
- nodeMajorVersion = Number.parseInt(process.versions.node.split(".")[0] ?? "");
3284
- if (isRunningInAmazonLinux2023(nodeMajorVersion)) {
3285
- setupLambdaEnvironment(join(tmpdir(), "al2023", "lib"));
3286
- }
3287
- Chromium = class {
3288
- /**
3289
- * Returns a list of additional Chromium flags recommended for serverless environments.
3290
- * The canonical list of flags can be found on https://peter.sh/experiments/chromium-command-line-switches/.
3291
- * Most of below can be found here: https://github.com/GoogleChrome/chrome-launcher/blob/main/docs/chrome-flags-for-tools.md
3292
- */
3293
- static get args() {
3294
- const chromiumFlags = [
3295
- "--ash-no-nudges",
3296
- // Avoids blue bubble "user education" nudges (eg., "… give your browser a new look", Memory Saver)
3297
- "--disable-domain-reliability",
3298
- // Disables Domain Reliability Monitoring, which tracks whether the browser has difficulty contacting Google-owned sites and uploads reports to Google.
3299
- "--disable-print-preview",
3300
- // https://source.chromium.org/search?q=lang:cpp+symbol:kDisablePrintPreview&ss=chromium
3301
- "--disk-cache-size=33554432",
3302
- // https://source.chromium.org/search?q=lang:cpp+symbol:kDiskCacheSize&ss=chromium Forces the maximum disk space to be used by the disk cache, in bytes.
3303
- "--no-default-browser-check",
3304
- // Disable the default browser check, do not prompt to set it as such. (This is already set by Playwright, but not Puppeteer)
3305
- "--no-pings",
3306
- // Don't send hyperlink auditing pings
3307
- "--single-process",
3308
- // Runs the renderer and plugins in the same process as the browser. NOTES: Needs to be single-process to avoid `prctl(PR_SET_NO_NEW_PRIVS) failed` error
3309
- "--font-render-hinting=none"
3310
- // https://github.com/puppeteer/puppeteer/issues/2410#issuecomment-560573612
3311
- ];
3312
- const chromiumDisableFeatures = [
3313
- "AudioServiceOutOfProcess",
3314
- "IsolateOrigins",
3315
- "site-per-process"
3316
- // Disables OOPIF. https://www.chromium.org/Home/chromium-security/site-isolation
3317
- ];
3318
- const chromiumEnableFeatures = ["SharedArrayBuffer"];
3319
- const graphicsFlags = [
3320
- "--ignore-gpu-blocklist",
3321
- // https://source.chromium.org/search?q=lang:cpp+symbol:kIgnoreGpuBlocklist&ss=chromium
3322
- "--in-process-gpu"
3323
- // Saves some memory by moving GPU process into a browser process thread
3324
- ];
3325
- if (this.graphics) {
3326
- graphicsFlags.push(
3327
- // As the unsafe WebGL fallback, SwANGLE (ANGLE + SwiftShader Vulkan)
3328
- "--use-gl=angle",
3329
- "--use-angle=swiftshader",
3330
- "--enable-unsafe-swiftshader"
3331
- );
3332
- } else {
3333
- graphicsFlags.push("--disable-webgl");
3334
- }
3335
- const insecureFlags = [
3336
- "--allow-running-insecure-content",
3337
- // https://source.chromium.org/search?q=lang:cpp+symbol:kAllowRunningInsecureContent&ss=chromium
3338
- "--disable-setuid-sandbox",
3339
- // Lambda runs as root, so this is required to allow Chromium to run as root
3340
- "--disable-site-isolation-trials",
3341
- // https://source.chromium.org/search?q=lang:cpp+symbol:kDisableSiteIsolation&ss=chromium
3342
- "--disable-web-security"
3343
- // https://source.chromium.org/search?q=lang:cpp+symbol:kDisableWebSecurity&ss=chromium
3344
- ];
3345
- const headlessFlags = [
3346
- "--headless='shell'",
3347
- // We only support running chrome-headless-shell
3348
- "--no-sandbox",
3349
- // https://source.chromium.org/search?q=lang:cpp+symbol:kNoSandbox&ss=chromium
3350
- "--no-zygote"
3351
- // https://source.chromium.org/search?q=lang:cpp+symbol:kNoZygote&ss=chromium
3352
- ];
3353
- return [
3354
- ...chromiumFlags,
3355
- `--disable-features=${[...chromiumDisableFeatures].join(",")}`,
3356
- `--enable-features=${[...chromiumEnableFeatures].join(",")}`,
3357
- ...graphicsFlags,
3358
- ...insecureFlags,
3359
- ...headlessFlags
3360
- ];
3361
- }
3362
- /**
3363
- * Returns whether the graphics stack is enabled or disabled
3364
- * @returns boolean
3365
- */
3366
- static get graphics() {
3367
- return this.graphicsMode;
3368
- }
3369
- /**
3370
- * Sets whether the graphics stack is enabled or disabled.
3371
- * @param true means the stack is enabled. WebGL will work.
3372
- * @param false means that the stack is disabled. WebGL will not work.
3373
- * @default true
3374
- */
3375
- static set setGraphicsMode(value) {
3376
- if (typeof value !== "boolean") {
3377
- throw new TypeError(`Graphics mode must be a boolean, you entered '${String(value)}'`);
3378
- }
3379
- this.graphicsMode = value;
3380
- }
3381
- /**
3382
- * If true, the graphics stack and webgl is enabled,
3383
- * If false, webgl will be disabled.
3384
- * (If false, the swiftshader.tar.br file will also not extract)
3385
- */
3386
- static graphicsMode = true;
3387
- /**
3388
- * Inflates the included version of Chromium
3389
- * @param input The location of the `bin` folder
3390
- * @returns The path to the `chromium` binary
3391
- */
3392
- static async executablePath(input) {
3393
- if (existsSync(join(tmpdir(), "chromium"))) {
3394
- return join(tmpdir(), "chromium");
3395
- }
3396
- if (input && isValidUrl(input)) {
3397
- return this.executablePath(await downloadAndExtract(input));
102
+ throw new OpenRouterError(message, response.status, void 0, response.headers);
3398
103
  }
3399
- input ??= getBinPath();
3400
- if (!existsSync(input)) {
3401
- throw new Error(`The input directory "${input}" does not exist. If you are using a bundler (esbuild, webpack, etc.), you must externalize @sparticuz/chromium so it is not relocated. See: https://github.com/Sparticuz/chromium#bundler-configuration`);
104
+ if (!response.body) {
105
+ throw new OpenRouterError("No response body for streaming request", 500);
3402
106
  }
3403
- const promises = [
3404
- inflate(join(input, "chromium.br")),
3405
- inflate(join(input, "fonts.tar.br")),
3406
- inflate(join(input, "swiftshader.tar.br"))
3407
- ];
3408
- if (isRunningInAmazonLinux2023(nodeMajorVersion)) {
3409
- promises.push(inflate(join(input, "al2023.tar.br")));
107
+ const reader = response.body.getReader();
108
+ const decoder = new TextDecoder();
109
+ let buffer = "";
110
+ try {
111
+ while (true) {
112
+ const { done, value } = await reader.read();
113
+ if (done) break;
114
+ buffer += decoder.decode(value, { stream: true });
115
+ const lines = buffer.split("\n");
116
+ buffer = lines.pop() ?? "";
117
+ for (const line of lines) {
118
+ const trimmed = line.trim();
119
+ if (!trimmed || trimmed.startsWith(":")) continue;
120
+ if (trimmed === "data: [DONE]") return;
121
+ if (!trimmed.startsWith("data: ")) continue;
122
+ const json = trimmed.slice("data: ".length);
123
+ try {
124
+ yield JSON.parse(json);
125
+ } catch {
126
+ }
127
+ }
128
+ }
129
+ } finally {
130
+ reader.releaseLock();
3410
131
  }
3411
- const result = await Promise.all(promises);
3412
- return result.shift();
3413
132
  }
3414
133
  };
3415
- build_default = Chromium;
3416
134
  }
3417
135
  });
3418
136
 
@@ -3708,6 +426,50 @@ function createAnthropicClient(rawKey) {
3708
426
  });
3709
427
  }
3710
428
 
429
+ // src/adapters/claude/claude-code-login.ts
430
+ var LOGIN_CHILD_ENV_NAMES = [
431
+ "PATH",
432
+ "HOME",
433
+ "USER",
434
+ "LOGNAME",
435
+ "SHELL",
436
+ "TMPDIR",
437
+ "TMP",
438
+ "TEMP",
439
+ "TERM",
440
+ "TZ",
441
+ "LANG",
442
+ "CLAUDE_CONFIG_DIR",
443
+ "CLAUDE_CODE_OAUTH_TOKEN",
444
+ "XDG_CONFIG_HOME",
445
+ "XDG_DATA_HOME",
446
+ "XDG_CACHE_HOME",
447
+ "XDG_STATE_HOME",
448
+ "XDG_RUNTIME_DIR",
449
+ "HTTPS_PROXY",
450
+ "https_proxy",
451
+ "HTTP_PROXY",
452
+ "http_proxy",
453
+ "NO_PROXY",
454
+ "no_proxy",
455
+ "ALL_PROXY",
456
+ "all_proxy",
457
+ "NODE_EXTRA_CA_CERTS",
458
+ "SSL_CERT_FILE",
459
+ "SSL_CERT_DIR"
460
+ ];
461
+ var LOGIN_CHILD_ENV = new Set(LOGIN_CHILD_ENV_NAMES);
462
+ function loginChildEnv(env) {
463
+ const out = {};
464
+ for (const [k, v] of Object.entries(env)) {
465
+ if (v !== void 0 && (LOGIN_CHILD_ENV.has(k) || k.startsWith("LC_"))) out[k] = v;
466
+ }
467
+ return out;
468
+ }
469
+ function claudeCodeLoginQueryOptions() {
470
+ return { tools: [], settingSources: [] };
471
+ }
472
+
3711
473
  // src/adapters/provider-router.ts
3712
474
  function getBedrockModelId(model) {
3713
475
  const BEDROCK_MAP = {
@@ -3757,6 +519,26 @@ function toJsonValue(value, path) {
3757
519
  `Tool-call arguments contain a non-JSON value at '${path}' (${typeof value})`
3758
520
  );
3759
521
  }
522
+
523
+ // src/adapters/openai/tokens.ts
524
+ function splitOpenAiUsage(inputTokensInclCached, outputTokens, cachedTokens) {
525
+ return splitCacheInclusiveUsage(inputTokensInclCached, outputTokens, cachedTokens);
526
+ }
527
+ function splitCacheInclusiveUsage(inputTokensInclCached, outputTokens, cachedTokens) {
528
+ const cacheRead = Math.min(
529
+ Math.max(cachedTokens, 0),
530
+ Math.max(inputTokensInclCached, 0)
531
+ );
532
+ const nonCachedInput = Math.max(inputTokensInclCached, 0) - cacheRead;
533
+ return {
534
+ tokens: {
535
+ input: nonCachedInput,
536
+ output: outputTokens,
537
+ total: nonCachedInput + cacheRead + outputTokens
538
+ },
539
+ cacheReadTokens: cacheRead
540
+ };
541
+ }
3760
542
  function emitLlmTraceEvent(event) {
3761
543
  return;
3762
544
  }
@@ -3767,6 +549,271 @@ function newLlmTraceId() {
3767
549
  return Date.now().toString(36) + Math.random().toString(36).slice(2, 10);
3768
550
  }
3769
551
 
552
+ // src/adapters/claude/tool-bridge.ts
553
+ var MCP_SERVER_NAME = "ggui";
554
+
555
+ // src/harness/claude-code-login-query.ts
556
+ var MCP_TOOL_PREFIX = `mcp__${MCP_SERVER_NAME}__`;
557
+ function stripMcpToolPrefix(name) {
558
+ return name.startsWith(MCP_TOOL_PREFIX) ? name.slice(MCP_TOOL_PREFIX.length) : name;
559
+ }
560
+ var LOGIN_API_KEY_SOURCE = "none";
561
+ var ClaudeCodeLoginAuthError = class extends Error {
562
+ apiKeySource;
563
+ constructor(apiKeySource) {
564
+ super(
565
+ `claude-code-login: the Claude Code binary authenticated from apiKeySource=${apiKeySource}, not from its login \u2014 a provider key reached the spawned process; the run was stopped before it spent a turn`
566
+ );
567
+ this.name = "ClaudeCodeLoginAuthError";
568
+ this.apiKeySource = apiKeySource;
569
+ }
570
+ };
571
+ var ClaudeCodeLoginResultError = class extends Error {
572
+ subtype;
573
+ errors;
574
+ status;
575
+ constructor(subtype, errors, status) {
576
+ super(
577
+ `claude-code-login: query() ended with ${subtype}` + (status !== void 0 ? ` (api status ${status})` : "") + `: ${errors.length > 0 ? errors.join("; ") : "no detail from the binary"}`
578
+ );
579
+ this.name = "ClaudeCodeLoginResultError";
580
+ this.subtype = subtype;
581
+ this.errors = errors;
582
+ this.status = status;
583
+ }
584
+ };
585
+ function createDenyingIntercept(intercepted) {
586
+ return async (toolName, input) => {
587
+ intercepted.push({ name: toolName, input });
588
+ return {
589
+ behavior: "deny",
590
+ message: "ggui executes tools in its harness; the binary only proposes them."
591
+ };
592
+ };
593
+ }
594
+ async function* imageUserMessage(text, image) {
595
+ const message = {
596
+ role: "user",
597
+ content: [
598
+ {
599
+ type: "image",
600
+ source: { type: "base64", media_type: image.mediaType, data: image.base64 }
601
+ },
602
+ { type: "text", text }
603
+ ]
604
+ };
605
+ yield { type: "user", message, parent_tool_use_id: null };
606
+ }
607
+ function buildLoginQueryOptions(params) {
608
+ return {
609
+ model: params.model,
610
+ systemPrompt: params.systemPrompt,
611
+ maxTurns: 1,
612
+ thinking: { type: "disabled" },
613
+ env: loginChildEnv(params.env ?? process.env),
614
+ ...claudeCodeLoginQueryOptions(),
615
+ ...params.tools !== void 0 ? {
616
+ mcpServers: { [MCP_SERVER_NAME]: params.tools.server },
617
+ canUseTool: params.tools.canUseTool
618
+ } : {}
619
+ };
620
+ }
621
+ var JSON_SCHEMA_TYPES = [
622
+ "object",
623
+ "array",
624
+ "string",
625
+ "number",
626
+ "boolean",
627
+ "null",
628
+ "integer"
629
+ ];
630
+ function isJsonSchemaType(value) {
631
+ return typeof value === "string" && JSON_SCHEMA_TYPES.includes(value);
632
+ }
633
+ function isJsonObject(value) {
634
+ return typeof value === "object" && value !== null && !Array.isArray(value);
635
+ }
636
+ function schemaAt(value, path) {
637
+ if (typeof value === "boolean") return value;
638
+ if (!isJsonObject(value)) {
639
+ throw new Error(
640
+ `claude-code-login: ${path} must be a JSON-Schema object or boolean, got ${JSON.stringify(value)}`
641
+ );
642
+ }
643
+ return toZodJsonSchema(value, path);
644
+ }
645
+ function toZodJsonSchema(parameters, path = "parameters") {
646
+ const out = {};
647
+ for (const [key, value] of Object.entries(parameters)) {
648
+ if (value === void 0) continue;
649
+ switch (key) {
650
+ case "type": {
651
+ if (!isJsonSchemaType(value)) {
652
+ throw new Error(
653
+ `claude-code-login: ${path}.type must be one of ${JSON_SCHEMA_TYPES.join("|")}, got ${JSON.stringify(value)}`
654
+ );
655
+ }
656
+ out.type = value;
657
+ break;
658
+ }
659
+ case "properties":
660
+ case "patternProperties":
661
+ case "$defs": {
662
+ if (!isJsonObject(value))
663
+ throw new Error(`claude-code-login: ${path}.${key} must be an object`);
664
+ const record = {};
665
+ for (const [name, sub] of Object.entries(value)) {
666
+ if (sub === void 0) continue;
667
+ record[name] = schemaAt(sub, `${path}.${key}.${name}`);
668
+ }
669
+ if (key === "$defs") {
670
+ const defs = {};
671
+ for (const [name, sub] of Object.entries(record)) {
672
+ if (typeof sub === "boolean")
673
+ throw new Error(`claude-code-login: ${path}.$defs.${name} must be an object`);
674
+ defs[name] = sub;
675
+ }
676
+ out.$defs = defs;
677
+ } else {
678
+ out[key] = record;
679
+ }
680
+ break;
681
+ }
682
+ case "items": {
683
+ out.items = Array.isArray(value) ? value.map((sub, i) => schemaAt(sub, `${path}.items[${i}]`)) : schemaAt(value, `${path}.items`);
684
+ break;
685
+ }
686
+ case "additionalProperties":
687
+ case "not": {
688
+ out[key] = schemaAt(value, `${path}.${key}`);
689
+ break;
690
+ }
691
+ case "anyOf":
692
+ case "oneOf":
693
+ case "allOf": {
694
+ if (!Array.isArray(value))
695
+ throw new Error(`claude-code-login: ${path}.${key} must be an array`);
696
+ out[key] = value.map((sub, i) => {
697
+ const s = schemaAt(sub, `${path}.${key}[${i}]`);
698
+ if (typeof s === "boolean")
699
+ throw new Error(`claude-code-login: ${path}.${key}[${i}] must be an object`);
700
+ return s;
701
+ });
702
+ break;
703
+ }
704
+ case "required": {
705
+ if (!Array.isArray(value) || !value.every((v) => typeof v === "string")) {
706
+ throw new Error(`claude-code-login: ${path}.required must be an array of strings`);
707
+ }
708
+ out.required = value;
709
+ break;
710
+ }
711
+ case "enum": {
712
+ if (!Array.isArray(value) || !value.every(
713
+ (v) => v === null || typeof v === "string" || typeof v === "number" || typeof v === "boolean"
714
+ )) {
715
+ throw new Error(`claude-code-login: ${path}.enum must be an array of primitives`);
716
+ }
717
+ out.enum = value;
718
+ break;
719
+ }
720
+ default:
721
+ out[key] = value;
722
+ }
723
+ }
724
+ return out;
725
+ }
726
+ function createLoginToolServer(sdk, tools) {
727
+ const sdkTools = tools.map((def) => {
728
+ const schema = z.fromJSONSchema(toZodJsonSchema(def.parameters, `${def.name}.parameters`));
729
+ if (!(schema instanceof z.ZodObject)) {
730
+ throw new Error(
731
+ `claude-code-login: tool ${def.name}'s parameters must be a JSON-Schema object`
732
+ );
733
+ }
734
+ return sdk.tool(def.name, def.description, schema.shape, async () => {
735
+ throw new Error(
736
+ `claude-code-login: the binary tried to execute ${def.name} \u2014 ggui's tools are proposed to the harness and never run in the binary (the intercept denies every call)`
737
+ );
738
+ });
739
+ });
740
+ return sdk.createSdkMcpServer({ name: MCP_SERVER_NAME, version: "1.0.0", tools: sdkTools });
741
+ }
742
+ var LOGIN_REQUIRED_TOOL_INSTRUCTION = "Respond only with tool calls: do not write any text before, between or after them. Text outside a tool call is not read.";
743
+ function describeCalls(calls) {
744
+ return JSON.stringify(calls.map((c) => ({ name: stripMcpToolPrefix(c.name), input: c.input })));
745
+ }
746
+ async function collectLoginTurn(stream, opts) {
747
+ let init;
748
+ const toolCalls = [];
749
+ let text = "";
750
+ let thinkingBlocks = 0;
751
+ let result;
752
+ try {
753
+ for await (const msg of stream) {
754
+ if (msg.type === "system" && msg.subtype === "init") {
755
+ const measured = msg;
756
+ init = measured;
757
+ opts.log(
758
+ `[claude-code-login] apiKeySource=${measured.apiKeySource} claude_code_version=${measured.claude_code_version} model=${measured.model}`
759
+ );
760
+ if (measured.apiKeySource !== LOGIN_API_KEY_SOURCE) {
761
+ throw new ClaudeCodeLoginAuthError(measured.apiKeySource);
762
+ }
763
+ } else if (msg.type === "assistant") {
764
+ for (const block of msg.message.content) {
765
+ if (block.type === "tool_use") {
766
+ toolCalls.push({
767
+ id: block.id,
768
+ name: stripMcpToolPrefix(block.name),
769
+ input: isRecord(block.input) ? toolArgsToJsonObject(block.input) : {}
770
+ });
771
+ } else if (block.type === "text") {
772
+ text += block.text;
773
+ } else if (block.type === "thinking" || block.type === "redacted_thinking") {
774
+ thinkingBlocks += 1;
775
+ }
776
+ }
777
+ } else if (msg.type === "result") {
778
+ result = msg;
779
+ }
780
+ }
781
+ } catch (e) {
782
+ if (result === void 0) throw e;
783
+ opts.log(
784
+ `[claude-code-login] query() threw after its result message \u2014 the result decides (${e instanceof Error ? e.message : String(e)})`
785
+ );
786
+ }
787
+ if (result === void 0) {
788
+ throw new Error("claude-code-login: query() ended without a result message");
789
+ }
790
+ const usage = result.usage;
791
+ const thinkingTokens = usage.output_tokens_details?.thinking_tokens ?? 0;
792
+ opts.log(
793
+ `[claude-code-login] usage kind=${opts.kind} input=${usage.input_tokens} output=${usage.output_tokens} cacheRead=${usage.cache_read_input_tokens} cacheCreated=${usage.cache_creation_input_tokens} thinking=${thinkingTokens} thinkingBlocks=${thinkingBlocks} textChars=${text.length} toolCalls=${toolCalls.length} stop=${result.stop_reason ?? "none"} choice=${opts.choice}`
794
+ );
795
+ const streamSaw = describeCalls(toolCalls);
796
+ const interceptSaw = describeCalls(opts.intercepted);
797
+ if (streamSaw !== interceptSaw) {
798
+ opts.warn(
799
+ `[claude-code-login] intercept/stream disagreement \u2014 the stream's blocks win. intercepted=${interceptSaw} stream=${streamSaw}`
800
+ );
801
+ }
802
+ if (result.subtype === "success") {
803
+ if (result.is_error) {
804
+ throw new ClaudeCodeLoginResultError(
805
+ "success",
806
+ [result.result],
807
+ result.api_error_status ?? void 0
808
+ );
809
+ }
810
+ } else if (result.subtype !== "error_max_turns") {
811
+ const failed = result;
812
+ throw new ClaudeCodeLoginResultError(failed.subtype, failed.errors, void 0);
813
+ }
814
+ return { init, toolCalls, text, result };
815
+ }
816
+
3770
817
  // src/harness/llm-router.ts
3771
818
  function addStrictSchemaConstraints(schema) {
3772
819
  const result = { ...schema };
@@ -3961,17 +1008,6 @@ var LLMAgent = class {
3961
1008
  }
3962
1009
  }
3963
1010
  };
3964
- function normalizeAnthropicModelId(model) {
3965
- return model.replace(/^anthropic\//, "").replace(/^(?:[a-z]{2}\.)?anthropic\./, "");
3966
- }
3967
- function anthropicRejectsSamplingParams(model) {
3968
- return /^claude-(?:opus-4-7|opus-5|sonnet-5|fable-5)(?:-|$)/.test(
3969
- normalizeAnthropicModelId(model)
3970
- );
3971
- }
3972
- function anthropicRejectsForcedToolChoice(model) {
3973
- return /^claude-fable-5-1(?:-|$)/.test(normalizeAnthropicModelId(model));
3974
- }
3975
1011
  function resolveAnthropicSampling(model, temperature) {
3976
1012
  if (temperature === void 0) {
3977
1013
  return { request: {}, applied: { temperature: "provider-default" } };
@@ -4307,6 +1343,170 @@ var AnthropicAgent = class extends LLMAgent {
4307
1343
  }
4308
1344
  }
4309
1345
  };
1346
+ var ClaudeCodeLoginAgent = class extends LLMAgent {
1347
+ provider = "anthropic";
1348
+ resolveModel(model) {
1349
+ return model.startsWith("anthropic/") ? model.slice("anthropic/".length) : model;
1350
+ }
1351
+ async createClient() {
1352
+ const { query: query2, tool: tool2, createSdkMcpServer: createSdkMcpServer2 } = await import('@anthropic-ai/claude-agent-sdk');
1353
+ return { query: query2, tool: tool2, createSdkMcpServer: createSdkMcpServer2 };
1354
+ }
1355
+ async callText(model, systemPrompt, userPrompt, _maxTokens, _temperature) {
1356
+ const sdk = await this.getClient();
1357
+ const traceId = newLlmTraceId();
1358
+ const startedAt = Date.now();
1359
+ const resolvedModel = this.resolveModel(model);
1360
+ try {
1361
+ const turn = await this.apiCall(
1362
+ () => collectLoginTurn(
1363
+ sdk.query({
1364
+ prompt: userPrompt,
1365
+ options: buildLoginQueryOptions({ model: resolvedModel, systemPrompt })
1366
+ }),
1367
+ { intercepted: [], kind: "callText", choice: "none", log: console.log, warn: console.warn }
1368
+ )
1369
+ );
1370
+ const usage = turn.result.usage;
1371
+ const endedAt = Date.now();
1372
+ emitLlmTraceEvent({
1373
+ id: traceId,
1374
+ at: startedAt,
1375
+ endedAt,
1376
+ durationMs: endedAt - startedAt,
1377
+ provider: "claude-code-login",
1378
+ model: resolvedModel,
1379
+ kind: "callText",
1380
+ systemPrompt,
1381
+ userPrompt,
1382
+ result: {
1383
+ inputTokens: usage.input_tokens,
1384
+ outputTokens: usage.output_tokens,
1385
+ cacheCreated: usage.cache_creation_input_tokens,
1386
+ cacheRead: usage.cache_read_input_tokens,
1387
+ text: turn.text
1388
+ }
1389
+ });
1390
+ return { text: turn.text, inputTokens: usage.input_tokens, outputTokens: usage.output_tokens };
1391
+ } catch (e) {
1392
+ emitLlmTraceEvent({
1393
+ error: { message: e instanceof Error ? e.message : String(e) }
1394
+ });
1395
+ throw e;
1396
+ }
1397
+ }
1398
+ async callVision(model, systemPrompt, userPrompt, image, _maxTokens) {
1399
+ const sdk = await this.getClient();
1400
+ const traceId = newLlmTraceId();
1401
+ const startedAt = Date.now();
1402
+ const resolvedModel = this.resolveModel(model);
1403
+ try {
1404
+ const turn = await this.apiCall(
1405
+ () => collectLoginTurn(
1406
+ sdk.query({
1407
+ prompt: imageUserMessage(userPrompt, image),
1408
+ options: buildLoginQueryOptions({ model: resolvedModel, systemPrompt })
1409
+ }),
1410
+ { intercepted: [], kind: "callVision", choice: "none", log: console.log, warn: console.warn }
1411
+ )
1412
+ );
1413
+ const usage = turn.result.usage;
1414
+ const endedAt = Date.now();
1415
+ emitLlmTraceEvent({
1416
+ id: traceId,
1417
+ at: startedAt,
1418
+ endedAt,
1419
+ durationMs: endedAt - startedAt,
1420
+ provider: "claude-code-login",
1421
+ model: resolvedModel,
1422
+ kind: "callVision",
1423
+ systemPrompt,
1424
+ userPrompt,
1425
+ result: { inputTokens: usage.input_tokens, outputTokens: usage.output_tokens, text: turn.text }
1426
+ });
1427
+ return { text: turn.text, inputTokens: usage.input_tokens, outputTokens: usage.output_tokens };
1428
+ } catch (e) {
1429
+ emitLlmTraceEvent({
1430
+ error: { message: e instanceof Error ? e.message : String(e) }
1431
+ });
1432
+ throw e;
1433
+ }
1434
+ }
1435
+ async callTools(model, systemPrompt, userPrompt, tools, toolChoice = "required", _scopedTools) {
1436
+ const sdk = await this.getClient();
1437
+ const traceId = newLlmTraceId();
1438
+ const startedAt = Date.now();
1439
+ const resolvedModel = this.resolveModel(model);
1440
+ const sentUserPrompt = toolChoice === "required" ? `${userPrompt}
1441
+
1442
+ ${LOGIN_REQUIRED_TOOL_INSTRUCTION}` : userPrompt;
1443
+ try {
1444
+ const turn = await this.apiCall(() => {
1445
+ const intercepted = [];
1446
+ const server = createLoginToolServer(sdk, tools);
1447
+ return collectLoginTurn(
1448
+ sdk.query({
1449
+ prompt: sentUserPrompt,
1450
+ options: buildLoginQueryOptions({
1451
+ model: resolvedModel,
1452
+ systemPrompt,
1453
+ tools: { server, canUseTool: createDenyingIntercept(intercepted) }
1454
+ })
1455
+ }),
1456
+ { intercepted, kind: "callTools", choice: toolChoice === "required" ? "required:instructed" : "auto", log: console.log, warn: console.warn }
1457
+ );
1458
+ });
1459
+ const usage = turn.result.usage;
1460
+ const cacheCreated = usage.cache_creation_input_tokens;
1461
+ const cacheRead = usage.cache_read_input_tokens;
1462
+ if (cacheCreated || cacheRead) {
1463
+ console.log(
1464
+ `[claude-code-login] callTools cache: created=${cacheCreated} read=${cacheRead} input=${usage.input_tokens} output=${usage.output_tokens}`
1465
+ );
1466
+ }
1467
+ const toolCalls = turn.toolCalls.map((c) => ({ id: c.id, name: c.name, input: c.input }));
1468
+ const endedAt = Date.now();
1469
+ emitLlmTraceEvent({
1470
+ id: traceId,
1471
+ at: startedAt,
1472
+ endedAt,
1473
+ durationMs: endedAt - startedAt,
1474
+ provider: "claude-code-login",
1475
+ model: resolvedModel,
1476
+ kind: "callTools",
1477
+ systemPrompt,
1478
+ userPrompt: sentUserPrompt,
1479
+ tools: summarizeTools(tools),
1480
+ result: {
1481
+ inputTokens: usage.input_tokens,
1482
+ outputTokens: usage.output_tokens,
1483
+ cacheCreated,
1484
+ cacheRead,
1485
+ toolCalls: toolCalls.map((c) => ({ name: c.name, input: c.input }))
1486
+ }
1487
+ });
1488
+ return {
1489
+ toolCalls,
1490
+ inputTokens: usage.input_tokens,
1491
+ outputTokens: usage.output_tokens,
1492
+ cacheReadTokens: cacheRead,
1493
+ cacheCreationTokens: cacheCreated,
1494
+ appliedToolChoice: "auto"
1495
+ };
1496
+ } catch (e) {
1497
+ emitLlmTraceEvent({
1498
+ tools: summarizeTools(tools),
1499
+ error: { message: e instanceof Error ? e.message : String(e) }
1500
+ });
1501
+ throw e;
1502
+ }
1503
+ }
1504
+ async callWithTools() {
1505
+ throw new Error(
1506
+ "claude-code-login: callWithTools (an in-client agentic loop) is not part of the login client \u2014 ggui's harness runs the loop through callTools"
1507
+ );
1508
+ }
1509
+ };
4310
1510
  var OpenAIAgent = class extends LLMAgent {
4311
1511
  provider = "openai";
4312
1512
  resolveModel(model) {
@@ -4335,10 +1535,15 @@ var OpenAIAgent = class extends LLMAgent {
4335
1535
  }
4336
1536
  }
4337
1537
  }
1538
+ const textUsage = splitOpenAiUsage(
1539
+ response.usage?.input_tokens ?? 0,
1540
+ response.usage?.output_tokens ?? 0,
1541
+ response.usage?.input_tokens_details?.cached_tokens ?? 0
1542
+ );
4338
1543
  return {
4339
1544
  text,
4340
- inputTokens: response.usage?.input_tokens ?? 0,
4341
- outputTokens: response.usage?.output_tokens ?? 0,
1545
+ inputTokens: textUsage.tokens.input,
1546
+ outputTokens: textUsage.tokens.output,
4342
1547
  sampling: { temperature: temperature ?? "provider-default" }
4343
1548
  };
4344
1549
  }
@@ -4377,14 +1582,20 @@ var OpenAIAgent = class extends LLMAgent {
4377
1582
  const functionCalls = response.output.filter(
4378
1583
  (o) => o.type === "function_call"
4379
1584
  );
1585
+ const toolsUsage = splitOpenAiUsage(
1586
+ response.usage?.input_tokens ?? 0,
1587
+ response.usage?.output_tokens ?? 0,
1588
+ response.usage?.input_tokens_details?.cached_tokens ?? 0
1589
+ );
4380
1590
  return {
4381
1591
  toolCalls: functionCalls.map((fc) => ({
4382
1592
  id: fc.call_id,
4383
1593
  name: fc.name,
4384
1594
  input: JSON.parse(fc.arguments ?? "{}")
4385
1595
  })),
4386
- inputTokens: response.usage?.input_tokens ?? 0,
4387
- outputTokens: response.usage?.output_tokens ?? 0
1596
+ inputTokens: toolsUsage.tokens.input,
1597
+ outputTokens: toolsUsage.tokens.output,
1598
+ cacheReadTokens: toolsUsage.cacheReadTokens
4388
1599
  };
4389
1600
  }
4390
1601
  // Pending tool results — stored by sendToolResult, consumed by next callTools
@@ -4411,6 +1622,7 @@ var OpenAIAgent = class extends LLMAgent {
4411
1622
  ];
4412
1623
  let totalIn = 0;
4413
1624
  let totalOut = 0;
1625
+ let totalCacheRead = 0;
4414
1626
  let allText = "";
4415
1627
  for (let turn = 0; turn < maxTurns; turn++) {
4416
1628
  const response = await this.apiCall(
@@ -4421,8 +1633,14 @@ var OpenAIAgent = class extends LLMAgent {
4421
1633
  tools: openaiTools
4422
1634
  })
4423
1635
  );
4424
- totalIn += response.usage?.input_tokens ?? 0;
4425
- totalOut += response.usage?.output_tokens ?? 0;
1636
+ const turnUsage = splitOpenAiUsage(
1637
+ response.usage?.input_tokens ?? 0,
1638
+ response.usage?.output_tokens ?? 0,
1639
+ response.usage?.input_tokens_details?.cached_tokens ?? 0
1640
+ );
1641
+ totalIn += turnUsage.tokens.input;
1642
+ totalOut += turnUsage.tokens.output;
1643
+ totalCacheRead += turnUsage.cacheReadTokens;
4426
1644
  const functionCalls = response.output.filter(
4427
1645
  (o) => o.type === "function_call"
4428
1646
  );
@@ -4453,6 +1671,7 @@ var OpenAIAgent = class extends LLMAgent {
4453
1671
  text: allText,
4454
1672
  inputTokens: totalIn,
4455
1673
  outputTokens: totalOut,
1674
+ cacheReadTokens: totalCacheRead,
4456
1675
  turnsUsed: input.length
4457
1676
  };
4458
1677
  }
@@ -4478,6 +1697,10 @@ function functionCallSteps(interaction) {
4478
1697
  function toUserInputStep(text) {
4479
1698
  return { type: "user_input", content: [{ type: "text", text }] };
4480
1699
  }
1700
+ function googleInteractionUsage(usage) {
1701
+ const split = splitCacheInclusiveUsage(usage?.total_input_tokens ?? 0, usage?.total_output_tokens ?? 0, usage?.total_cached_tokens ?? 0);
1702
+ return { inputTokens: split.tokens.input, outputTokens: split.tokens.output, cacheReadTokens: split.cacheReadTokens };
1703
+ }
4481
1704
  var GoogleAgent = class extends LLMAgent {
4482
1705
  provider = "google";
4483
1706
  resolveModel(model) {
@@ -4507,8 +1730,9 @@ var GoogleAgent = class extends LLMAgent {
4507
1730
  );
4508
1731
  return {
4509
1732
  text: interactionText(interaction),
4510
- inputTokens: interaction.usage?.total_input_tokens ?? 0,
4511
- outputTokens: interaction.usage?.total_output_tokens ?? 0,
1733
+ // ggui#1186 (third site): `total_input_tokens` INCLUDES the cached part of the prompt — report the non-cached input.
1734
+ inputTokens: googleInteractionUsage(interaction.usage).inputTokens,
1735
+ outputTokens: googleInteractionUsage(interaction.usage).outputTokens,
4512
1736
  sampling: { temperature: temperature ?? "provider-default" }
4513
1737
  };
4514
1738
  }
@@ -4540,7 +1764,8 @@ var GoogleAgent = class extends LLMAgent {
4540
1764
  const usage = response.usageMetadata;
4541
1765
  const result = {
4542
1766
  text,
4543
- inputTokens: usage?.promptTokenCount ?? 0,
1767
+ // ggui#1186 (third site): `promptTokenCount` includes `cachedContentTokenCount` — report the non-cached input.
1768
+ inputTokens: splitCacheInclusiveUsage(usage?.promptTokenCount ?? 0, usage?.candidatesTokenCount ?? 0, usage?.cachedContentTokenCount ?? 0).tokens.input,
4544
1769
  outputTokens: usage?.candidatesTokenCount ?? 0
4545
1770
  };
4546
1771
  const endedAt = Date.now();
@@ -4674,8 +1899,8 @@ var GoogleAgent = class extends LLMAgent {
4674
1899
  }));
4675
1900
  return {
4676
1901
  toolCalls,
4677
- inputTokens: interaction.usage?.total_input_tokens ?? 0,
4678
- outputTokens: interaction.usage?.total_output_tokens ?? 0
1902
+ // ggui#1186 (third site): the coding loop reads this per-turn usage — the non-cached prompt as input, the cached subset reported.
1903
+ ...googleInteractionUsage(interaction.usage)
4679
1904
  };
4680
1905
  }
4681
1906
  // Pending tool results — stored by sendToolResult, consumed by next callTools
@@ -4699,6 +1924,7 @@ var GoogleAgent = class extends LLMAgent {
4699
1924
  }));
4700
1925
  let totalIn = 0;
4701
1926
  let totalOut = 0;
1927
+ let totalCacheRead = 0;
4702
1928
  let allText = "";
4703
1929
  let turnsUsed = 0;
4704
1930
  let interaction = await this.apiCall(
@@ -4712,8 +1938,10 @@ var GoogleAgent = class extends LLMAgent {
4712
1938
  for (let turn = 0; turn < maxTurns; turn++) {
4713
1939
  turnsUsed = turn + 1;
4714
1940
  if (interaction.usage) {
4715
- totalIn += interaction.usage.total_input_tokens ?? 0;
4716
- totalOut += interaction.usage.total_output_tokens ?? 0;
1941
+ const turnUsage = googleInteractionUsage(interaction.usage);
1942
+ totalIn += turnUsage.inputTokens;
1943
+ totalOut += turnUsage.outputTokens;
1944
+ totalCacheRead += turnUsage.cacheReadTokens;
4717
1945
  }
4718
1946
  allText += interactionText(interaction);
4719
1947
  const fnCalls = functionCallSteps(interaction);
@@ -4751,6 +1979,7 @@ var GoogleAgent = class extends LLMAgent {
4751
1979
  text: allText,
4752
1980
  inputTokens: totalIn,
4753
1981
  outputTokens: totalOut,
1982
+ cacheReadTokens: totalCacheRead,
4754
1983
  turnsUsed
4755
1984
  };
4756
1985
  }
@@ -4806,12 +2035,19 @@ var OpenRouterAgent = class extends LLMAgent {
4806
2035
  this.sessionMessages.push({ role: "system", content: systemPrompt });
4807
2036
  }
4808
2037
  this.sessionMessages.push({ role: "user", content: userPrompt });
2038
+ const requested = toolChoice ?? "auto";
2039
+ const appliedToolChoice = requested === "required" && anthropicRejectsForcedToolChoice(resolved) ? "auto" : requested;
2040
+ if (appliedToolChoice !== requested) {
2041
+ console.warn(
2042
+ `[openrouter] callTools: ${resolved} rejects forced tool_choice (HTTP 400); caller's 'required' downgraded to 'auto'`
2043
+ );
2044
+ }
4809
2045
  const response = await this.apiCall(
4810
2046
  () => client.chatCompletion({
4811
2047
  model: resolved,
4812
2048
  messages: this.sessionMessages,
4813
2049
  tools: orTools,
4814
- tool_choice: toolChoice ?? "auto"
2050
+ tool_choice: appliedToolChoice
4815
2051
  })
4816
2052
  );
4817
2053
  const choice = response.choices[0];
@@ -4830,7 +2066,8 @@ var OpenRouterAgent = class extends LLMAgent {
4830
2066
  return {
4831
2067
  toolCalls,
4832
2068
  inputTokens: response.usage.prompt_tokens,
4833
- outputTokens: response.usage.completion_tokens
2069
+ outputTokens: response.usage.completion_tokens,
2070
+ appliedToolChoice
4834
2071
  };
4835
2072
  }
4836
2073
  async sendToolResult(results) {
@@ -4901,6 +2138,14 @@ function createAgent(providerOrConfig) {
4901
2138
  const provider = typeof providerOrConfig === "string" ? providerOrConfig : providerOrConfig.provider;
4902
2139
  const routeOverride = typeof providerOrConfig === "string" ? void 0 : providerOrConfig.routeOverride;
4903
2140
  const onRetry = typeof providerOrConfig === "string" ? void 0 : providerOrConfig.onRetry;
2141
+ if (routeOverride?.claudeCodeLogin === true) {
2142
+ if (provider !== "anthropic") {
2143
+ throw new Error(
2144
+ `${provider}: the claude-code-login credential authenticates the Claude Code binary only \u2014 pick an anthropic route or supply a ${provider} API key`
2145
+ );
2146
+ }
2147
+ return new ClaudeCodeLoginAgent(routeOverride, onRetry);
2148
+ }
4904
2149
  switch (provider) {
4905
2150
  case "anthropic":
4906
2151
  return new AnthropicAgent(routeOverride, onRetry);
@@ -4913,11 +2158,23 @@ function createAgent(providerOrConfig) {
4913
2158
  }
4914
2159
  }
4915
2160
  function createVisionAgent(config) {
2161
+ if (config.routeOverride?.claudeCodeLogin === true) {
2162
+ if (config.provider !== "anthropic") {
2163
+ throw new Error(
2164
+ `${config.provider}: the claude-code-login credential authenticates the Claude Code binary only \u2014 pick an anthropic route or supply a ${config.provider} API key`
2165
+ );
2166
+ }
2167
+ return new ClaudeCodeLoginAgent(config.routeOverride, config.onRetry);
2168
+ }
4916
2169
  switch (config.provider) {
4917
2170
  case "anthropic":
4918
2171
  return new AnthropicAgent(config.routeOverride, config.onRetry);
4919
2172
  case "google":
4920
2173
  return new GoogleAgent(config.routeOverride, config.onRetry);
2174
+ default: {
2175
+ const unreachable = config.provider;
2176
+ throw new Error(`createVisionAgent: provider '${String(unreachable)}' has no vision path (anthropic, google)`);
2177
+ }
4921
2178
  }
4922
2179
  }
4923
2180
 
@@ -7235,18 +4492,19 @@ function isDesignRenderingInput(relativePath) {
7235
4492
  return true;
7236
4493
  }
7237
4494
  function designTreeSha256(root) {
4495
+ const base = resolve(root);
7238
4496
  const files = [];
7239
4497
  const walk = (dir) => {
7240
4498
  for (const name of readdirSync(dir).sort()) {
7241
4499
  const full = resolve(dir, name);
7242
4500
  if (statSync(full).isDirectory()) walk(full);
7243
- else if (isDesignRenderingInput(full.slice(root.length + 1))) files.push(full);
4501
+ else if (isDesignRenderingInput(relative(base, full))) files.push(full);
7244
4502
  }
7245
4503
  };
7246
- walk(root);
4504
+ walk(base);
7247
4505
  const h = createHash("sha256");
7248
4506
  for (const f of files) {
7249
- h.update(f.slice(root.length + 1) + "\n");
4507
+ h.update(relative(base, f) + "\n");
7250
4508
  h.update(readFileSync(f));
7251
4509
  h.update("\n");
7252
4510
  }
@@ -7285,12 +4543,21 @@ var JUDGE_SCOPE_CLASS = "ggui-judge-scope";
7285
4543
  function canvasFit(canvas) {
7286
4544
  return displayModeForCanvas(canvas) === "fullscreen" ? "fill" : void 0;
7287
4545
  }
4546
+ function integerBox(viewport) {
4547
+ return { width: Math.round(viewport.width), height: Math.round(viewport.height) };
4548
+ }
4549
+ function isDeclaredViewport(canvas, viewport) {
4550
+ const classBox = CANVAS_VIEWPORTS[canvas];
4551
+ return viewport.width !== classBox.width || viewport.height !== classBox.height;
4552
+ }
7288
4553
  function canvasOverflowIssue(canvas, viewport, contentHeight, verdict) {
7289
4554
  const hidden = contentHeight - viewport.height;
4555
+ const classBox = CANVAS_VIEWPORTS[canvas];
4556
+ const box = isDeclaredViewport(canvas, viewport) ? `declared ${viewport.width}\xD7${viewport.height}; class box ${classBox.width}\xD7${classBox.height}` : `${viewport.width}\xD7${viewport.height}`;
7290
4557
  return {
7291
4558
  dimension: "canvas-overflow",
7292
4559
  severity: verdict === "fail" ? "critical" : "major",
7293
- description: `Rendered content is ${contentHeight}px tall on the ${canvas} canvas (${viewport.width}\xD7${viewport.height}) \u2014 ${hidden}px ${verdict === "fail" ? "is cut off: the inline card does not scroll" : "sits below the first screen"}.`,
4560
+ description: `Rendered content is ${contentHeight}px tall on the ${canvas} canvas (${box}) \u2014 ${hidden}px ${verdict === "fail" ? "is cut off: the inline card does not scroll" : "sits below the first screen"}.`,
7294
4561
  fix: "Fit the composition to the canvas: fewer and shorter sections, one compact row of chips, no hero taller than a third of the box, no fixed min-heights or tall paddings \u2014 measure against the canvas, not the page."
7295
4562
  };
7296
4563
  }
@@ -7331,8 +4598,7 @@ function resolveDesignPackageDir() {
7331
4598
  }
7332
4599
  }
7333
4600
  async function bundleForRendering(compiledCode, sampleProps, designSrc = resolve(resolveDesignPackageDir(), "src")) {
7334
- const tmpDir = resolve(tmpdir(), "ggui-visual-eval-" + Date.now());
7335
- mkdirSync(tmpDir, { recursive: true });
4601
+ const tmpDir = mkdtempSync(resolve(tmpdir(), "ggui-visual-eval-"));
7336
4602
  const componentFile = resolve(tmpDir, "component.tsx");
7337
4603
  const entryFile = resolve(tmpDir, "entry.tsx");
7338
4604
  const designPkgDir = resolve(designSrc, "..");
@@ -7407,14 +4673,7 @@ try {
7407
4673
  });
7408
4674
  return result.outputFiles[0]?.text ?? "";
7409
4675
  } finally {
7410
- try {
7411
- unlinkSync(entryFile);
7412
- } catch {
7413
- }
7414
- try {
7415
- unlinkSync(componentFile);
7416
- } catch {
7417
- }
4676
+ rmSync(tmpDir, { recursive: true, force: true });
7418
4677
  }
7419
4678
  }
7420
4679
  function buildRenderHTML(bundledCode, cssTokens, fit) {
@@ -7429,7 +4688,10 @@ function buildRenderHTML(bundledCode, cssTokens, fit) {
7429
4688
  *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
7430
4689
  body {
7431
4690
  font-family: var(--ggui-font-family-sans, system-ui, -apple-system, sans-serif);
7432
- background: var(--ggui-color-neutral-50, #ffffff);
4691
+ /* ggui#1083 \u2014 the host stand-in (neutral-50) under the theme's scrim (its tint at
4692
+ its opacity): the ground a frosted host puts under the card, so the judge scores
4693
+ the card where the visitor sees it. */
4694
+ background: color-mix(in oklch, var(--ggui-scrim-tint, var(--ggui-color-ground, #ffffff)) calc(var(--ggui-scrim-opacity, 0.45) * 100%), var(--ggui-color-neutral-50, #ffffff));
7433
4695
  color: var(--ggui-color-neutral-900, #111827);
7434
4696
  }
7435
4697
  .error { color: #dc2626; padding: 16px; font-family: monospace; white-space: pre-wrap; }
@@ -7457,24 +4719,25 @@ ${bundledCode}
7457
4719
  var EXECUTABLE_PATH_LAUNCH_ARGS = ["--no-sandbox", "--disable-dev-shm-usage"];
7458
4720
  var DEFAULT_SCREENSHOT_VIEWPORT = { width: 1280, height: 800 };
7459
4721
  async function loadSparticuzChromium() {
7460
- const chromium = await Promise.resolve().then(() => (init_build(), build_exports));
4722
+ const chromium = await import('@sparticuz/chromium');
7461
4723
  return chromium.default;
7462
4724
  }
7463
4725
  async function resolveLaunchOptions(viewport, deps = {}) {
7464
4726
  const env = deps.env ?? process.env;
7465
4727
  const override = env.PUPPETEER_EXECUTABLE_PATH?.trim();
4728
+ const defaultViewport = integerBox(viewport);
7466
4729
  if (override) {
7467
4730
  return {
7468
4731
  executablePath: override,
7469
4732
  args: [...EXECUTABLE_PATH_LAUNCH_ARGS],
7470
- defaultViewport: viewport,
4733
+ defaultViewport,
7471
4734
  headless: true
7472
4735
  };
7473
4736
  }
7474
4737
  const chromium = await (deps.loadChromium ?? loadSparticuzChromium)();
7475
4738
  return {
7476
4739
  args: chromium.args,
7477
- defaultViewport: viewport,
4740
+ defaultViewport,
7478
4741
  executablePath: await chromium.executablePath(),
7479
4742
  headless: true
7480
4743
  };
@@ -7583,6 +4846,20 @@ ${originalPrompt}
7583
4846
  VISUAL_JUDGE_MAX_OUTPUT_TOKENS
7584
4847
  );
7585
4848
  }
4849
+ async function frameCanvas(bundledCode, context, html, canvas, canvasViewports, deps) {
4850
+ const declaredBox = canvasViewports?.[canvas];
4851
+ const viewport = declaredBox !== void 0 ? integerBox(declaredBox) : CANVAS_VIEWPORTS[canvas];
4852
+ const policy = canvasFitPolicy(canvas);
4853
+ const fit = canvasFit(canvas);
4854
+ const canvasHtml = fit !== void 0 ? buildRenderHTML(bundledCode, context.cssTokens, fit) : html;
4855
+ const attempt = await captureScreenshotDetailed(canvasHtml, viewport, deps, policy.capture);
4856
+ return { viewport, policy, fit, declared: declaredBox !== void 0, attempt };
4857
+ }
4858
+ function fitVerdict(canvas, frame) {
4859
+ const contentHeight = frame.attempt.contentHeight;
4860
+ if (contentHeight === null || contentHeight <= frame.viewport.height || frame.policy.overflow === "none") return null;
4861
+ return canvasOverflowIssue(canvas, frame.viewport, contentHeight, frame.policy.overflow);
4862
+ }
7586
4863
  function judgeCountFor(config, canvas) {
7587
4864
  const k = Math.max(1, Math.floor(config.judgeK ?? 1));
7588
4865
  if (k === 1) return 1;
@@ -7650,11 +4927,8 @@ async function runVisualEvaluationDetailed(context, config, deps = {}) {
7650
4927
  const perCanvas = [];
7651
4928
  const perCanvasResults = [];
7652
4929
  for (const canvas of config.canvases) {
7653
- const viewport = CANVAS_VIEWPORTS[canvas];
7654
- const policy = canvasFitPolicy(canvas);
7655
- const fit = canvasFit(canvas);
7656
- const canvasHtml = fit !== void 0 ? buildRenderHTML(bundledCode, context.cssTokens, fit) : html;
7657
- const attempt2 = await captureScreenshotDetailed(canvasHtml, viewport, deps, policy.capture);
4930
+ const frame = await frameCanvas(bundledCode, context, html, canvas, config.canvasViewports, deps);
4931
+ const { viewport, policy, fit, attempt: attempt2 } = frame;
7658
4932
  const screenshot2 = attempt2.png;
7659
4933
  if (!screenshot2) {
7660
4934
  const unavailableReason = attempt2.reason ?? "no browser available";
@@ -7689,8 +4963,9 @@ async function runVisualEvaluationDetailed(context, config, deps = {}) {
7689
4963
  };
7690
4964
  const contentHeight = attempt2.contentHeight;
7691
4965
  const overflow = contentHeight !== null && contentHeight > viewport.height;
7692
- if (contentHeight !== null && contentHeight > viewport.height && policy.overflow !== "none") {
7693
- result2.issues.push(canvasOverflowIssue(canvas, viewport, contentHeight, policy.overflow));
4966
+ const fitIssue = fitVerdict(canvas, frame);
4967
+ if (fitIssue !== null) {
4968
+ result2.issues.push(fitIssue);
7694
4969
  if (policy.overflow === "fail") result2.passed = false;
7695
4970
  }
7696
4971
  perCanvasResults.push(result2);
@@ -7703,7 +4978,8 @@ async function runVisualEvaluationDetailed(context, config, deps = {}) {
7703
4978
  contentHeight,
7704
4979
  overflow,
7705
4980
  judge: judgeRecord,
7706
- ...fit !== void 0 ? { fit } : {}
4981
+ ...fit !== void 0 ? { fit } : {},
4982
+ ...frame.declared ? { declared: true } : {}
7707
4983
  });
7708
4984
  console.log(
7709
4985
  `[visual-eval] canvas=${canvas} ${viewport.width}\xD7${viewport.height} score=${result2.finalScore}${k > 1 ? ` (median of ${judgeRecord.samples.length}/${k}: ${judgeRecord.samples.join(",")} \u03C3=${judgeRecord.sigma})` : ""} ${result2.passed ? "pass" : "FAIL"} | content=${contentHeight ?? "?"}px${overflow ? ` OVERFLOW (${policy.overflow})` : ""} | in=${response2.inputTokens} out=${response2.outputTokens}`
@@ -7743,6 +5019,9 @@ async function runVisualEvaluationDetailed(context, config, deps = {}) {
7743
5019
  console.log(`[visual-eval] score=${result.finalScore} (${elapsed}ms) | in=${response.inputTokens} out=${response.outputTokens}`);
7744
5020
  return { result: stamp(result) };
7745
5021
  }
5022
+ function canvasScopedIssue(canvas, issue) {
5023
+ return { ...issue, description: `[${canvas}] ${issue.description}` };
5024
+ }
7746
5025
  function aggregateCanvasResults(perCanvas, results) {
7747
5026
  const n = results.length;
7748
5027
  const mean = (pick) => Math.round(results.reduce((sum, r) => sum + pick(r), 0) / n);
@@ -7759,7 +5038,7 @@ function aggregateCanvasResults(perCanvas, results) {
7759
5038
  let outputTokens = 0;
7760
5039
  results.forEach((r, i) => {
7761
5040
  const canvas = perCanvas[i].canvas;
7762
- for (const issue of r.issues) issues.push({ ...issue, description: `[${canvas}] ${issue.description}` });
5041
+ for (const issue of r.issues) issues.push(canvasScopedIssue(canvas, issue));
7763
5042
  if (r.critique) critiques.push(`${canvas}: ${r.critique}`);
7764
5043
  inputTokens += r.inputTokens ?? 0;
7765
5044
  outputTokens += r.outputTokens ?? 0;
@@ -7787,10 +5066,19 @@ function summarizeVisualResult(result) {
7787
5066
  judge: c.judge,
7788
5067
  ...c.fit !== void 0 ? { fit: c.fit } : {}
7789
5068
  }));
5069
+ const fitCanvas = result.canvases.find((c) => canvasFitPolicy(c.canvas).overflow === "fail" && c.contentHeight !== null);
5070
+ const fit = fitCanvas !== void 0 && fitCanvas.contentHeight !== null ? {
5071
+ canvas: fitCanvas.canvas,
5072
+ ceiling: { width: fitCanvas.viewport.width, height: fitCanvas.viewport.height },
5073
+ // Declared = the order carried a box, even one equal to the class box (the review's point).
5074
+ declared: fitCanvas.declared === true,
5075
+ overflowPx: Math.max(0, fitCanvas.contentHeight - fitCanvas.viewport.height)
5076
+ } : void 0;
7790
5077
  return {
7791
5078
  score: result.finalScore,
7792
5079
  passed: result.passed,
7793
5080
  canvases,
5081
+ ...fit !== void 0 ? { fit } : {},
7794
5082
  ...result.design !== void 0 ? { design: result.design } : {},
7795
5083
  ...result.themeMode !== void 0 ? { themeMode: result.themeMode } : {}
7796
5084
  };
@@ -7878,10 +5166,20 @@ function getDefaultVisualModel(provider) {
7878
5166
  return "gemini-3-flash-preview";
7879
5167
  }
7880
5168
  }
7881
- async function runVisualEval(context, config) {
7882
- const result = await runVisualEvaluation(context, config);
7883
- if (!result) return { issues: [] };
7884
- const issues = (result.issues || []).map((issue) => ({
5169
+ async function runVisualEval(context, config, deps = {}) {
5170
+ const detailed = await runVisualEvaluationDetailed(context, config, deps);
5171
+ const result = detailed.result;
5172
+ if (!result) {
5173
+ const reason = detailed.unavailableReason ?? "no browser available";
5174
+ return { issues: [], coverage: { status: "skipped", reason } };
5175
+ }
5176
+ const issues = (result.issues || []).map(toEvalIssue);
5177
+ const summary = summarizeVisualResult(result);
5178
+ const coverage = { status: "ran" };
5179
+ return summary === void 0 ? { issues, coverage } : { issues, summary, coverage };
5180
+ }
5181
+ function toEvalIssue(issue) {
5182
+ return {
7885
5183
  tier: 2,
7886
5184
  result: issue.severity === "critical" ? "fail" : "warn",
7887
5185
  category: "visual",
@@ -7889,9 +5187,7 @@ async function runVisualEval(context, config) {
7889
5187
  severity: issue.severity === "critical" ? "critical" : "major",
7890
5188
  description: issue.description,
7891
5189
  fix: issue.fix || ""
7892
- }));
7893
- const summary = summarizeVisualResult(result);
7894
- return summary === void 0 ? { issues } : { issues, summary };
5190
+ };
7895
5191
  }
7896
5192
  function cssTokensForAppTheme(theme, mode = "light") {
7897
5193
  if (theme === void 0) return getCssTokens(mode);