Diffinery

homeflare/celldpublic

celld/crates/celld/js/node_stream.js
5520 lines · 163.9 KBRaw History
1// node:stream for celld. Copyright Joyent, Inc., Node.js contributors, and
2// the Deno authors (MIT) — [email protected] (MIT, Node.js contributors),
3// via the esbuild bundle Deno ships as ext/node/polyfills/_stream.mjs (MIT,
4// the Deno authors). Workerd's node:stream at commit
5// 191a27f941300dd8956f2afeb66c10a651108c0b is the same Readable/Writable/
6// Duplex/Transform/PassThrough port; the bundle form is terser to embed, so
7// it is vendored verbatim between the "esm.sh bundle" markers below, with
8// the bundle's external imports (process, buffer, events, string_decoder,
9// util helpers, node error classes) mapped onto Cells' own seams in the
10// header. Comment-only lines were rewrapped to 80 columns; the single code
11// change (Duplex.prototype.destroy, matching Workerd) is marked inline.
12//
13// Also defines stream/promises, stream/web (re-exporting the global web
14// stream classes lazily, so importing node:stream alone does not force
15// them), and stream/consumers.
16//
17// Injected lazily into the generated stub module, so an isolate that never
18// imports node:stream pays nothing.
19(() => {
20 "use strict";
21 const { Buffer } = globalThis; // lazy global; forces node_buffer
22 const EE = process.getBuiltinModule("node:events");
23 const nextTick = process.nextTick;
24 const __process$ = process;
25 const __buffer$ = { Buffer };
26
27 // ---- node:string_decoder (subset the bundle reaches for) ----------------
28 // utf8/utf16le decode statefully through TextDecoder; base64 keeps the
29 // 3-byte remainder; hex/latin1/ascii are alignment-free.
30 class StringDecoder {
31 constructor(encoding = "utf8") {
32 this.encoding = normalizeEncoding(encoding);
33 if (this.encoding === undefined)
34 throw new ERR_UNKNOWN_ENCODING(encoding);
35 if (this.encoding === "utf8" || this.encoding === "utf16le") {
36 this.__td = new TextDecoder(
37 this.encoding === "utf8" ? "utf-8" : "utf-16le");
38 } else if (this.encoding.startsWith("base64")) {
39 this.__rem = null;
40 }
41 }
42 write(buf) {
43 if (typeof buf === "string") return buf;
44 const u8 = buf instanceof Uint8Array
45 ? buf : new Uint8Array(buf.buffer ?? buf);
46 if (this.__td) return this.__td.decode(u8, { stream: true });
47 let bytes = u8;
48 if (this.__rem !== undefined) {
49 const joined = this.__rem
50 ? Buffer.concat([this.__rem, u8]) : Buffer.from(u8);
51 const keep = joined.length % 3;
52 this.__rem = keep ? joined.slice(joined.length - keep) : null;
53 bytes = joined.slice(0, joined.length - keep);
54 }
55 return Buffer.from(
56 bytes.buffer, bytes.byteOffset, bytes.byteLength,
57 ).toString(this.encoding);
58 }
59 end(buf) {
60 let out = buf !== undefined && buf.length ? this.write(buf) : "";
61 if (this.__td) out += this.__td.decode();
62 else if (this.__rem) {
63 out += this.__rem.toString(this.encoding);
64 this.__rem = null;
65 }
66 return out;
67 }
68 text(buf, offset) { return this.write(buf.slice(offset)); }
69 }
70
71 // ---- internal/util helpers ----------------------------------------------
72 const createDeferredPromise = () => {
73 let resolve, reject;
74 const promise = new Promise((res, rej) => { resolve = res; reject = rej; });
75 return { promise, resolve, reject };
76 };
77 const kEmptyObject = Object.freeze({ __proto__: null });
78 const normalizeEncoding = (enc) => {
79 if (enc == null || enc === "utf8" || enc === "utf-8") return "utf8";
80 switch (String(enc).toLowerCase()) {
81 case "utf8": case "utf-8": return "utf8";
82 case "ucs2": case "ucs-2": case "utf16le": case "utf-16le":
83 return "utf16le";
84 case "latin1": case "binary": return "latin1";
85 case "base64": return "base64";
86 case "base64url": return "base64url";
87 case "hex": return "hex";
88 case "ascii": return "ascii";
89 default: return undefined;
90 }
91 };
92 const once = (callback) => {
93 let called = false;
94 return function (...args) {
95 if (called) return;
96 called = true;
97 callback.apply(this, args);
98 };
99 };
100 // Only used as a property key: `pipeline[promisify]` / `eos[promisify]`
101 // must be the custom-promisify slot node:util's promisify honors.
102 const promisify = Symbol.for("nodejs.util.promisify.custom");
103 const isArrayBufferView = (v) => ArrayBuffer.isView(v);
104 const isAsyncFunction = (v) =>
105 Object.prototype.toString.call(v) === "[object AsyncFunction]";
106 const debuglog = () => () => {};
107 const inspect = (v) => {
108 if (typeof v === "string") return `'${v}'`;
109 try { return JSON.stringify(v) ?? String(v); }
110 catch { return String(v); }
111 };
112
113 // ---- node error classes (internal/errors subset) ------------------------
114 // Factories rather than classes: the bundle constructs some with `new` and
115 // calls others bare, and a function returning the error object serves both.
116 const E = (code, Base, message) => {
117 function factory(...args) {
118 const error = new Base(
119 typeof message === "function" ? message(...args) : message);
120 error.code = code;
121 return error;
122 }
123 return factory;
124 };
125 const received = (value) => {
126 if (value == null) return `. Received ${value}`;
127 if (typeof value === "function")
128 return `. Received function ${value.name || "anonymous"}`;
129 if (typeof value === "object")
130 return `. Received an instance of ${
131 value.constructor?.name ?? "Object"}`;
132 let repr = inspect(value);
133 if (repr.length > 27) repr = `${repr.slice(0, 25)}...`;
134 return `. Received type ${typeof value} (${repr})`;
135 };
136 const oneOf = (expected) =>
137 (Array.isArray(expected) ? expected : [expected]).join(" or ");
138 const ERR_INVALID_ARG_TYPE = E(
139 "ERR_INVALID_ARG_TYPE", TypeError,
140 (name, expected, actual) =>
141 `The ${name.includes(".") ? `"${name}" property` :
142 `"${name}" argument`} must be of type ${
143 oneOf(expected)}${received(actual)}`);
144 const ERR_INVALID_ARG_VALUE = E(
145 "ERR_INVALID_ARG_VALUE", TypeError,
146 (name, value, reason = "is invalid") =>
147 `The argument '${name}' ${reason}. Received ${inspect(value)}`);
148 const ERR_OUT_OF_RANGE = E(
149 "ERR_OUT_OF_RANGE", RangeError,
150 (name, range, actual) =>
151 `The value of "${name}" is out of range. It must be ${range}. ` +
152 `Received ${actual}`);
153 const ERR_INVALID_RETURN_VALUE = E(
154 "ERR_INVALID_RETURN_VALUE", TypeError,
155 (expected, name, value) =>
156 `Expected ${expected} to be returned from the "${name}" function` +
157 ` but got ${typeof value}.`);
158 const ERR_METHOD_NOT_IMPLEMENTED = E(
159 "ERR_METHOD_NOT_IMPLEMENTED", Error,
160 (name) => `The ${name} method is not implemented`);
161 const ERR_MISSING_ARGS = E(
162 "ERR_MISSING_ARGS", TypeError,
163 (...args) => {
164 const names = args.map((a) => `"${a}"`).join(" or ");
165 return `The ${names} argument${args.length > 1 ? "s" : ""} ` +
166 `must be specified`;
167 });
168 const ERR_MULTIPLE_CALLBACK =
169 E("ERR_MULTIPLE_CALLBACK", Error, "Callback called multiple times");
170 const ERR_SOCKET_BAD_PORT = E(
171 "ERR_SOCKET_BAD_PORT", RangeError,
172 (name, port, allowZero = true) =>
173 `${name} should be >${allowZero ? "=" : ""} 0 and < 65536. ` +
174 `Received ${port}.`);
175 const ERR_STREAM_ALREADY_FINISHED = E(
176 "ERR_STREAM_ALREADY_FINISHED", Error,
177 (name) => `Cannot call ${name} after a stream was finished`);
178 const ERR_STREAM_CANNOT_PIPE =
179 E("ERR_STREAM_CANNOT_PIPE", Error, "Cannot pipe, not readable");
180 const ERR_STREAM_DESTROYED = E(
181 "ERR_STREAM_DESTROYED", Error,
182 (name) => `Cannot call ${name} after a stream was destroyed`);
183 const ERR_STREAM_NULL_VALUES = E(
184 "ERR_STREAM_NULL_VALUES", TypeError,
185 "May not write null values to stream");
186 const ERR_STREAM_PREMATURE_CLOSE =
187 E("ERR_STREAM_PREMATURE_CLOSE", Error, "Premature close");
188 const ERR_STREAM_PUSH_AFTER_EOF =
189 E("ERR_STREAM_PUSH_AFTER_EOF", Error, "stream.push() after EOF");
190 const ERR_STREAM_UNSHIFT_AFTER_END_EVENT = E(
191 "ERR_STREAM_UNSHIFT_AFTER_END_EVENT", Error,
192 "stream.unshift() after end event");
193 const ERR_STREAM_WRITE_AFTER_END =
194 E("ERR_STREAM_WRITE_AFTER_END", Error, "write after end");
195 const ERR_UNKNOWN_ENCODING = E(
196 "ERR_UNKNOWN_ENCODING", TypeError,
197 (enc) => `Unknown encoding: ${enc}`);
198 const ERR_UNKNOWN_SIGNAL = E(
199 "ERR_UNKNOWN_SIGNAL", TypeError,
200 (signal) => `Unknown signal: ${signal}`);
201 const ERR_ILLEGAL_CONSTRUCTOR =
202 E("ERR_ILLEGAL_CONSTRUCTOR", TypeError, "Illegal constructor");
203 function AbortError(message = "The operation was aborted", options) {
204 const error = new Error(message);
205 error.name = "AbortError";
206 error.code = "ABORT_ERR";
207 if (options?.cause !== undefined) error.cause = options.cause;
208 return error;
209 }
210 const aggregateTwoErrors = (inner, outer) => {
211 if (inner && outer && inner !== outer) {
212 if (Array.isArray(outer.errors)) {
213 outer.errors.push(inner);
214 return outer;
215 }
216 const error = new AggregateError([outer, inner], outer.message);
217 error.code = outer.code;
218 return error;
219 }
220 return inner || outer;
221 };
222 const hideStackFrames = (fn) => fn;
223
224 /* esm.sh bundle: [email protected], vendored verbatim */
225var __getOwnPropNames = Object.getOwnPropertyNames;
226var __commonJS = (cb, mod) =>
227 function __require() {
228 return mod ||
229 (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod),
230 mod.exports;
231 };
232
233// node_modules/buffer/index.js
234var require_buffer = () => {
235 return __buffer$;
236};
237
238// lib/ours/errors.js
239var require_primordials = __commonJS({
240 "lib/ours/primordials.js"(exports2, module2) {
241 "use strict";
242 module2.exports = {
243 ArrayIsArray(self2) {
244 return Array.isArray(self2);
245 },
246 ArrayPrototypeIncludes(self2, el) {
247 return self2.includes(el);
248 },
249 ArrayPrototypeIndexOf(self2, el) {
250 return self2.indexOf(el);
251 },
252 ArrayPrototypeJoin(self2, sep) {
253 return self2.join(sep);
254 },
255 ArrayPrototypeMap(self2, fn) {
256 return self2.map(fn);
257 },
258 ArrayPrototypePop(self2, el) {
259 return self2.pop(el);
260 },
261 ArrayPrototypePush(self2, el) {
262 return self2.push(el);
263 },
264 ArrayPrototypeSlice(self2, start, end) {
265 return self2.slice(start, end);
266 },
267 Error,
268 FunctionPrototypeCall(fn, thisArgs, ...args) {
269 return fn.call(thisArgs, ...args);
270 },
271 FunctionPrototypeSymbolHasInstance(self2, instance) {
272 return Function.prototype[Symbol.hasInstance].call(self2, instance);
273 },
274 MathFloor: Math.floor,
275 Number,
276 NumberIsInteger: Number.isInteger,
277 NumberIsNaN: Number.isNaN,
278 NumberMAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER,
279 NumberMIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER,
280 NumberParseInt: Number.parseInt,
281 ObjectDefineProperties(self2, props) {
282 return Object.defineProperties(self2, props);
283 },
284 ObjectDefineProperty(self2, name, prop) {
285 return Object.defineProperty(self2, name, prop);
286 },
287 ObjectGetOwnPropertyDescriptor(self2, name) {
288 return Object.getOwnPropertyDescriptor(self2, name);
289 },
290 ObjectKeys(obj) {
291 return Object.keys(obj);
292 },
293 ObjectSetPrototypeOf(target, proto) {
294 return Object.setPrototypeOf(target, proto);
295 },
296 Promise,
297 PromisePrototypeCatch(self2, fn) {
298 return self2.catch(fn);
299 },
300 PromisePrototypeThen(self2, thenFn, catchFn) {
301 return self2.then(thenFn, catchFn);
302 },
303 PromiseReject(err) {
304 return Promise.reject(err);
305 },
306 ReflectApply: Reflect.apply,
307 RegExpPrototypeTest(self2, value) {
308 return self2.test(value);
309 },
310 SafeSet: Set,
311 String,
312 StringPrototypeSlice(self2, start, end) {
313 return self2.slice(start, end);
314 },
315 StringPrototypeToLowerCase(self2) {
316 return self2.toLowerCase();
317 },
318 StringPrototypeToUpperCase(self2) {
319 return self2.toUpperCase();
320 },
321 StringPrototypeTrim(self2) {
322 return self2.trim();
323 },
324 Symbol,
325 SymbolAsyncIterator: Symbol.asyncIterator,
326 SymbolHasInstance: Symbol.hasInstance,
327 SymbolIterator: Symbol.iterator,
328 TypedArrayPrototypeSet(self2, buf, len) {
329 return self2.set(buf, len);
330 },
331 Uint8Array,
332 };
333 },
334});
335
336// lib/internal/validators.js
337var require_validators = __commonJS({
338 "lib/internal/validators.js"(exports, module) {
339 "use strict";
340 var {
341 ArrayIsArray,
342 ArrayPrototypeIncludes,
343 ArrayPrototypeJoin,
344 ArrayPrototypeMap,
345 NumberIsInteger,
346 NumberIsNaN,
347 NumberMAX_SAFE_INTEGER,
348 NumberMIN_SAFE_INTEGER,
349 NumberParseInt,
350 ObjectPrototypeHasOwnProperty,
351 RegExpPrototypeExec,
352 String: String2,
353 StringPrototypeToUpperCase,
354 StringPrototypeTrim,
355 } = require_primordials();
356 var signals = {};
357 function isInt32(value) {
358 return value === (value | 0);
359 }
360 function isUint32(value) {
361 return value === value >>> 0;
362 }
363 var octalReg = /^[0-7]+$/;
364 var modeDesc = "must be a 32-bit unsigned integer or an octal string";
365 function parseFileMode(value, name, def) {
366 if (typeof value === "undefined") {
367 value = def;
368 }
369 if (typeof value === "string") {
370 if (RegExpPrototypeExec(octalReg, value) === null) {
371 throw new ERR_INVALID_ARG_VALUE(name, value, modeDesc);
372 }
373 value = NumberParseInt(value, 8);
374 }
375 validateUint32(value, name);
376 return value;
377 }
378 var validateInteger = hideStackFrames(
379 (
380 value,
381 name,
382 min = NumberMIN_SAFE_INTEGER,
383 max = NumberMAX_SAFE_INTEGER,
384 ) => {
385 if (typeof value !== "number") {
386 throw new ERR_INVALID_ARG_TYPE(name, "number", value);
387 }
388 if (!NumberIsInteger(value)) {
389 throw new ERR_OUT_OF_RANGE(name, "an integer", value);
390 }
391 if (value < min || value > max) {
392 throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value);
393 }
394 },
395 );
396 var validateInt32 = hideStackFrames(
397 (value, name, min = -2147483648, max = 2147483647) => {
398 if (typeof value !== "number") {
399 throw new ERR_INVALID_ARG_TYPE(name, "number", value);
400 }
401 if (!NumberIsInteger(value)) {
402 throw new ERR_OUT_OF_RANGE(name, "an integer", value);
403 }
404 if (value < min || value > max) {
405 throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value);
406 }
407 },
408 );
409 var validateUint32 = hideStackFrames((value, name, positive = false) => {
410 if (typeof value !== "number") {
411 throw new ERR_INVALID_ARG_TYPE(name, "number", value);
412 }
413 if (!NumberIsInteger(value)) {
414 throw new ERR_OUT_OF_RANGE(name, "an integer", value);
415 }
416 const min = positive ? 1 : 0;
417 const max = 4294967295;
418 if (value < min || value > max) {
419 throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value);
420 }
421 });
422 function validateString(value, name) {
423 if (typeof value !== "string") {
424 throw new ERR_INVALID_ARG_TYPE(name, "string", value);
425 }
426 }
427 function validateNumber(value, name, min = void 0, max) {
428 if (typeof value !== "number") {
429 throw new ERR_INVALID_ARG_TYPE(name, "number", value);
430 }
431 if (
432 min != null && value < min || max != null && value > max ||
433 (min != null || max != null) && NumberIsNaN(value)
434 ) {
435 throw new ERR_OUT_OF_RANGE(
436 name,
437 `${min != null ? `>= ${min}` : ""}${
438 min != null && max != null ? " && " : ""
439 }${max != null ? `<= ${max}` : ""}`,
440 value,
441 );
442 }
443 }
444 var validateOneOf = hideStackFrames((value, name, oneOf) => {
445 if (!ArrayPrototypeIncludes(oneOf, value)) {
446 const allowed = ArrayPrototypeJoin(
447 ArrayPrototypeMap(
448 oneOf,
449 (v) => typeof v === "string" ? `'${v}'` : String2(v),
450 ),
451 ", ",
452 );
453 const reason = "must be one of: " + allowed;
454 throw new ERR_INVALID_ARG_VALUE(name, value, reason);
455 }
456 });
457 function validateBoolean(value, name) {
458 if (typeof value !== "boolean") {
459 throw new ERR_INVALID_ARG_TYPE(name, "boolean", value);
460 }
461 }
462 function getOwnPropertyValueOrDefault(options, key, defaultValue) {
463 return options == null || !ObjectPrototypeHasOwnProperty(options, key)
464 ? defaultValue
465 : options[key];
466 }
467 var validateObject = hideStackFrames((value, name, options = null) => {
468 const allowArray = getOwnPropertyValueOrDefault(
469 options,
470 "allowArray",
471 false,
472 );
473 const allowFunction = getOwnPropertyValueOrDefault(
474 options,
475 "allowFunction",
476 false,
477 );
478 const nullable = getOwnPropertyValueOrDefault(options, "nullable", false);
479 if (
480 !nullable && value === null || !allowArray && ArrayIsArray(value) ||
481 typeof value !== "object" &&
482 (!allowFunction || typeof value !== "function")
483 ) {
484 throw new ERR_INVALID_ARG_TYPE(name, "Object", value);
485 }
486 });
487 var validateArray = hideStackFrames((value, name, minLength = 0) => {
488 if (!ArrayIsArray(value)) {
489 throw new ERR_INVALID_ARG_TYPE(name, "Array", value);
490 }
491 if (value.length < minLength) {
492 const reason = `must be longer than ${minLength}`;
493 throw new ERR_INVALID_ARG_VALUE(name, value, reason);
494 }
495 });
496 function validateSignalName(signal, name = "signal") {
497 validateString(signal, name);
498 if (signals[signal] === void 0) {
499 if (signals[StringPrototypeToUpperCase(signal)] !== void 0) {
500 throw new ERR_UNKNOWN_SIGNAL(
501 signal + " (signals must use all capital letters)",
502 );
503 }
504 throw new ERR_UNKNOWN_SIGNAL(signal);
505 }
506 }
507 var validateBuffer = hideStackFrames((buffer, name = "buffer") => {
508 if (!isArrayBufferView(buffer)) {
509 throw new ERR_INVALID_ARG_TYPE(name, [
510 "Buffer",
511 "TypedArray",
512 "DataView",
513 ], buffer);
514 }
515 });
516 function validateEncoding(data, encoding) {
517 const normalizedEncoding = normalizeEncoding(encoding);
518 const length = data.length;
519 if (normalizedEncoding === "hex" && length % 2 !== 0) {
520 throw new ERR_INVALID_ARG_VALUE(
521 "encoding",
522 encoding,
523 `is invalid for data of length ${length}`,
524 );
525 }
526 }
527 function validatePort(port, name = "Port", allowZero = true) {
528 if (
529 typeof port !== "number" && typeof port !== "string" ||
530 typeof port === "string" && StringPrototypeTrim(port).length === 0 ||
531 +port !== +port >>> 0 || port > 65535 || port === 0 && !allowZero
532 ) {
533 throw new ERR_SOCKET_BAD_PORT(name, port, allowZero);
534 }
535 return port | 0;
536 }
537 var validateAbortSignal = hideStackFrames((signal, name) => {
538 if (
539 signal !== void 0 &&
540 (signal === null || typeof signal !== "object" ||
541 !("aborted" in signal))
542 ) {
543 throw new ERR_INVALID_ARG_TYPE(name, "AbortSignal", signal);
544 }
545 });
546 var validateFunction = hideStackFrames((value, name) => {
547 if (typeof value !== "function") {
548 throw new ERR_INVALID_ARG_TYPE(name, "Function", value);
549 }
550 });
551 var validatePlainFunction = hideStackFrames((value, name) => {
552 if (typeof value !== "function" || isAsyncFunction(value)) {
553 throw new ERR_INVALID_ARG_TYPE(name, "Function", value);
554 }
555 });
556 var validateUndefined = hideStackFrames((value, name) => {
557 if (value !== void 0) {
558 throw new ERR_INVALID_ARG_TYPE(name, "undefined", value);
559 }
560 });
561 function validateUnion(value, name, union) {
562 if (!ArrayPrototypeIncludes(union, value)) {
563 throw new ERR_INVALID_ARG_TYPE(
564 name,
565 `('${ArrayPrototypeJoin(union, "|")}')`,
566 value,
567 );
568 }
569 }
570 module.exports = {
571 isInt32,
572 isUint32,
573 parseFileMode,
574 validateArray,
575 validateBoolean,
576 validateBuffer,
577 validateEncoding,
578 validateFunction,
579 validateInt32,
580 validateInteger,
581 validateNumber,
582 validateObject,
583 validateOneOf,
584 validatePlainFunction,
585 validatePort,
586 validateSignalName,
587 validateString,
588 validateUint32,
589 validateUndefined,
590 validateUnion,
591 validateAbortSignal,
592 };
593 },
594});
595
596// node_modules/process/browser.js
597var require_browser2 = () => {
598 return __process$;
599};
600
601// lib/internal/streams/utils.js
602var require_utils = __commonJS({
603 "lib/internal/streams/utils.js"(exports, module) {
604 "use strict";
605 var { Symbol: Symbol2, SymbolAsyncIterator, SymbolIterator } =
606 require_primordials();
607 var kDestroyed = Symbol2("kDestroyed");
608 var kIsErrored = Symbol2("kIsErrored");
609 var kIsReadable = Symbol2("kIsReadable");
610 var kIsDisturbed = Symbol2("kIsDisturbed");
611 function isReadableNodeStream(obj, strict = false) {
612 var _obj$_readableState;
613 return !!(obj && typeof obj.pipe === "function" &&
614 typeof obj.on === "function" &&
615 (!strict ||
616 typeof obj.pause === "function" &&
617 typeof obj.resume === "function") &&
618 (!obj._writableState ||
619 ((_obj$_readableState = obj._readableState) === null ||
620 _obj$_readableState === void 0
621 ? void 0
622 : _obj$_readableState.readable) !== false) && // Duplex
623 (!obj._writableState || obj._readableState));
624 }
625 function isWritableNodeStream(obj) {
626 var _obj$_writableState;
627 return !!(obj && typeof obj.write === "function" &&
628 typeof obj.on === "function" &&
629 (!obj._readableState ||
630 ((_obj$_writableState = obj._writableState) === null ||
631 _obj$_writableState === void 0
632 ? void 0
633 : _obj$_writableState.writable) !== false));
634 }
635 function isDuplexNodeStream(obj) {
636 return !!(obj && typeof obj.pipe === "function" && obj._readableState &&
637 typeof obj.on === "function" && typeof obj.write === "function");
638 }
639 function isNodeStream(obj) {
640 return obj &&
641 (obj._readableState || obj._writableState ||
642 typeof obj.write === "function" && typeof obj.on === "function" ||
643 typeof obj.pipe === "function" && typeof obj.on === "function");
644 }
645 function isIterable(obj, isAsync) {
646 if (obj == null) {
647 return false;
648 }
649 if (isAsync === true) {
650 return typeof obj[SymbolAsyncIterator] === "function";
651 }
652 if (isAsync === false) {
653 return typeof obj[SymbolIterator] === "function";
654 }
655 return typeof obj[SymbolAsyncIterator] === "function" ||
656 typeof obj[SymbolIterator] === "function";
657 }
658 function isDestroyed(stream) {
659 if (!isNodeStream(stream)) {
660 return null;
661 }
662 const wState = stream._writableState;
663 const rState = stream._readableState;
664 const state = wState || rState;
665 return !!(stream.destroyed || stream[kDestroyed] ||
666 state !== null && state !== void 0 && state.destroyed);
667 }
668 function isWritableEnded(stream) {
669 if (!isWritableNodeStream(stream)) {
670 return null;
671 }
672 if (stream.writableEnded === true) {
673 return true;
674 }
675 const wState = stream._writableState;
676 if (wState !== null && wState !== void 0 && wState.errored) {
677 return false;
678 }
679 if (
680 typeof (wState === null || wState === void 0
681 ? void 0
682 : wState.ended) !== "boolean"
683 ) {
684 return null;
685 }
686 return wState.ended;
687 }
688 function isWritableFinished(stream, strict) {
689 if (!isWritableNodeStream(stream)) {
690 return null;
691 }
692 if (stream.writableFinished === true) {
693 return true;
694 }
695 const wState = stream._writableState;
696 if (wState !== null && wState !== void 0 && wState.errored) {
697 return false;
698 }
699 if (
700 typeof (wState === null || wState === void 0
701 ? void 0
702 : wState.finished) !== "boolean"
703 ) {
704 return null;
705 }
706 return !!(wState.finished ||
707 strict === false && wState.ended === true && wState.length === 0);
708 }
709 function isReadableEnded(stream) {
710 if (!isReadableNodeStream(stream)) {
711 return null;
712 }
713 if (stream.readableEnded === true) {
714 return true;
715 }
716 const rState = stream._readableState;
717 if (!rState || rState.errored) {
718 return false;
719 }
720 if (
721 typeof (rState === null || rState === void 0
722 ? void 0
723 : rState.ended) !== "boolean"
724 ) {
725 return null;
726 }
727 return rState.ended;
728 }
729 function isReadableFinished(stream, strict) {
730 if (!isReadableNodeStream(stream)) {
731 return null;
732 }
733 const rState = stream._readableState;
734 if (rState !== null && rState !== void 0 && rState.errored) {
735 return false;
736 }
737 if (
738 typeof (rState === null || rState === void 0
739 ? void 0
740 : rState.endEmitted) !== "boolean"
741 ) {
742 return null;
743 }
744 return !!(rState.endEmitted ||
745 strict === false && rState.ended === true && rState.length === 0);
746 }
747 function isReadable(stream) {
748 if (stream && stream[kIsReadable] != null) {
749 return stream[kIsReadable];
750 }
751 if (
752 typeof (stream === null || stream === void 0
753 ? void 0
754 : stream.readable) !== "boolean"
755 ) {
756 return null;
757 }
758 if (isDestroyed(stream)) {
759 return false;
760 }
761 return isReadableNodeStream(stream) && stream.readable &&
762 !isReadableFinished(stream);
763 }
764 function isWritable(stream) {
765 if (
766 typeof (stream === null || stream === void 0
767 ? void 0
768 : stream.writable) !== "boolean"
769 ) {
770 return null;
771 }
772 if (isDestroyed(stream)) {
773 return false;
774 }
775 return isWritableNodeStream(stream) && stream.writable &&
776 !isWritableEnded(stream);
777 }
778 function isFinished(stream, opts) {
779 if (!isNodeStream(stream)) {
780 return null;
781 }
782 if (isDestroyed(stream)) {
783 return true;
784 }
785 if (
786 (opts === null || opts === void 0 ? void 0 : opts.readable) !== false &&
787 isReadable(stream)
788 ) {
789 return false;
790 }
791 if (
792 (opts === null || opts === void 0 ? void 0 : opts.writable) !== false &&
793 isWritable(stream)
794 ) {
795 return false;
796 }
797 return true;
798 }
799 function isWritableErrored(stream) {
800 var _stream$_writableStat, _stream$_writableStat2;
801 if (!isNodeStream(stream)) {
802 return null;
803 }
804 if (stream.writableErrored) {
805 return stream.writableErrored;
806 }
807 return (_stream$_writableStat =
808 (_stream$_writableStat2 = stream._writableState) === null ||
809 _stream$_writableStat2 === void 0
810 ? void 0
811 : _stream$_writableStat2.errored) !== null &&
812 _stream$_writableStat !== void 0
813 ? _stream$_writableStat
814 : null;
815 }
816 function isReadableErrored(stream) {
817 var _stream$_readableStat, _stream$_readableStat2;
818 if (!isNodeStream(stream)) {
819 return null;
820 }
821 if (stream.readableErrored) {
822 return stream.readableErrored;
823 }
824 return (_stream$_readableStat =
825 (_stream$_readableStat2 = stream._readableState) === null ||
826 _stream$_readableStat2 === void 0
827 ? void 0
828 : _stream$_readableStat2.errored) !== null &&
829 _stream$_readableStat !== void 0
830 ? _stream$_readableStat
831 : null;
832 }
833 function isClosed(stream) {
834 if (!isNodeStream(stream)) {
835 return null;
836 }
837 if (typeof stream.closed === "boolean") {
838 return stream.closed;
839 }
840 const wState = stream._writableState;
841 const rState = stream._readableState;
842 if (
843 typeof (wState === null || wState === void 0
844 ? void 0
845 : wState.closed) === "boolean" ||
846 typeof (rState === null || rState === void 0
847 ? void 0
848 : rState.closed) === "boolean"
849 ) {
850 return (wState === null || wState === void 0
851 ? void 0
852 : wState.closed) ||
853 (rState === null || rState === void 0 ? void 0 : rState.closed);
854 }
855 if (typeof stream._closed === "boolean" && isOutgoingMessage(stream)) {
856 return stream._closed;
857 }
858 return null;
859 }
860 function isOutgoingMessage(stream) {
861 return typeof stream._closed === "boolean" &&
862 typeof stream._defaultKeepAlive === "boolean" &&
863 typeof stream._removedConnection === "boolean" &&
864 typeof stream._removedContLen === "boolean";
865 }
866 function isServerResponse(stream) {
867 return typeof stream._sent100 === "boolean" && isOutgoingMessage(stream);
868 }
869 function isServerRequest(stream) {
870 var _stream$req;
871 return typeof stream._consuming === "boolean" &&
872 typeof stream._dumped === "boolean" &&
873 ((_stream$req = stream.req) === null || _stream$req === void 0
874 ? void 0
875 : _stream$req.upgradeOrConnect) === void 0;
876 }
877 function willEmitClose(stream) {
878 if (!isNodeStream(stream)) {
879 return null;
880 }
881 const wState = stream._writableState;
882 const rState = stream._readableState;
883 const state = wState || rState;
884 return !state && isServerResponse(stream) ||
885 !!(state && state.autoDestroy && state.emitClose &&
886 state.closed === false);
887 }
888 function isDisturbed(stream) {
889 var _stream$kIsDisturbed;
890 return !!(stream &&
891 ((_stream$kIsDisturbed = stream[kIsDisturbed]) !== null &&
892 _stream$kIsDisturbed !== void 0
893 ? _stream$kIsDisturbed
894 : stream.readableDidRead || stream.readableAborted));
895 }
896 function isErrored(stream) {
897 var _ref,
898 _ref2,
899 _ref3,
900 _ref4,
901 _ref5,
902 _stream$kIsErrored,
903 _stream$_readableStat3,
904 _stream$_writableStat3,
905 _stream$_readableStat4,
906 _stream$_writableStat4;
907 return !!(stream &&
908 ((_ref =
909 (_ref2 =
910 (_ref3 =
911 (_ref4 =
912 (_ref5 =
913 (_stream$kIsErrored =
914 stream[kIsErrored]) !== null &&
915 _stream$kIsErrored !== void 0
916 ? _stream$kIsErrored
917 : stream.readableErrored) !== null &&
918 _ref5 !== void 0
919 ? _ref5
920 : stream.writableErrored) !== null &&
921 _ref4 !== void 0
922 ? _ref4
923 : (_stream$_readableStat3 =
924 stream._readableState) === null ||
925 _stream$_readableStat3 === void 0
926 ? void 0
927 : _stream$_readableStat3.errorEmitted) !== null &&
928 _ref3 !== void 0
929 ? _ref3
930 : (_stream$_writableStat3 = stream._writableState) ===
931 null || _stream$_writableStat3 === void 0
932 ? void 0
933 : _stream$_writableStat3.errorEmitted) !== null &&
934 _ref2 !== void 0
935 ? _ref2
936 : (_stream$_readableStat4 = stream._readableState) === null ||
937 _stream$_readableStat4 === void 0
938 ? void 0
939 : _stream$_readableStat4.errored) !== null && _ref !== void 0
940 ? _ref
941 : (_stream$_writableStat4 = stream._writableState) === null ||
942 _stream$_writableStat4 === void 0
943 ? void 0
944 : _stream$_writableStat4.errored));
945 }
946 module.exports = {
947 kDestroyed,
948 isDisturbed,
949 kIsDisturbed,
950 isErrored,
951 kIsErrored,
952 isReadable,
953 kIsReadable,
954 isClosed,
955 isDestroyed,
956 isDuplexNodeStream,
957 isFinished,
958 isIterable,
959 isReadableNodeStream,
960 isReadableEnded,
961 isReadableFinished,
962 isReadableErrored,
963 isNodeStream,
964 isWritable,
965 isWritableNodeStream,
966 isWritableEnded,
967 isWritableFinished,
968 isWritableErrored,
969 isServerRequest,
970 isServerResponse,
971 willEmitClose,
972 };
973 },
974});
975
976// lib/internal/streams/end-of-stream.js
977var require_end_of_stream = __commonJS({
978 "lib/internal/streams/end-of-stream.js"(exports, module) {
979 var process = require_browser2();
980 var { validateAbortSignal, validateFunction, validateObject } =
981 require_validators();
982 var { Promise: Promise2 } = require_primordials();
983 var {
984 isClosed,
985 isReadable,
986 isReadableNodeStream,
987 isReadableFinished,
988 isReadableErrored,
989 isWritable,
990 isWritableNodeStream,
991 isWritableFinished,
992 isWritableErrored,
993 isNodeStream,
994 willEmitClose: _willEmitClose,
995 } = require_utils();
996 function isRequest(stream) {
997 return stream.setHeader && typeof stream.abort === "function";
998 }
999 var nop = () => {
1000 };
1001 function eos(stream, options, callback) {
1002 var _options$readable, _options$writable;
1003 if (arguments.length === 2) {
1004 callback = options;
1005 options = kEmptyObject;
1006 } else if (options == null) {
1007 options = kEmptyObject;
1008 } else {
1009 validateObject(options, "options");
1010 }
1011 validateFunction(callback, "callback");
1012 validateAbortSignal(options.signal, "options.signal");
1013 callback = once(callback);
1014 const readable = (_options$readable = options.readable) !== null &&
1015 _options$readable !== void 0
1016 ? _options$readable
1017 : isReadableNodeStream(stream);
1018 const writable = (_options$writable = options.writable) !== null &&
1019 _options$writable !== void 0
1020 ? _options$writable
1021 : isWritableNodeStream(stream);
1022 if (!isNodeStream(stream)) {
1023 throw new ERR_INVALID_ARG_TYPE("stream", "Stream", stream);
1024 }
1025 const wState = stream._writableState;
1026 const rState = stream._readableState;
1027 const onlegacyfinish = () => {
1028 if (!stream.writable) {
1029 onfinish();
1030 }
1031 };
1032 let willEmitClose = _willEmitClose(stream) &&
1033 isReadableNodeStream(stream) === readable &&
1034 isWritableNodeStream(stream) === writable;
1035 let writableFinished = isWritableFinished(stream, false);
1036 const onfinish = () => {
1037 writableFinished = true;
1038 if (stream.destroyed) {
1039 willEmitClose = false;
1040 }
1041 if (willEmitClose && (!stream.readable || readable)) {
1042 return;
1043 }
1044 if (!readable || readableFinished) {
1045 callback.call(stream);
1046 }
1047 };
1048 let readableFinished = isReadableFinished(stream, false);
1049 const onend = () => {
1050 readableFinished = true;
1051 if (stream.destroyed) {
1052 willEmitClose = false;
1053 }
1054 if (willEmitClose && (!stream.writable || writable)) {
1055 return;
1056 }
1057 if (!writable || writableFinished) {
1058 callback.call(stream);
1059 }
1060 };
1061 const onerror = (err) => {
1062 callback.call(stream, err);
1063 };
1064 let closed = isClosed(stream);
1065 const onclose = () => {
1066 closed = true;
1067 const errored = isWritableErrored(stream) || isReadableErrored(stream);
1068 if (errored && typeof errored !== "boolean") {
1069 return callback.call(stream, errored);
1070 }
1071 if (
1072 readable && !readableFinished && isReadableNodeStream(stream, true)
1073 ) {
1074 if (!isReadableFinished(stream, false)) {
1075 return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE());
1076 }
1077 }
1078 if (writable && !writableFinished) {
1079 if (!isWritableFinished(stream, false)) {
1080 return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE());
1081 }
1082 }
1083 callback.call(stream);
1084 };
1085 const onrequest = () => {
1086 stream.req.on("finish", onfinish);
1087 };
1088 if (isRequest(stream)) {
1089 stream.on("complete", onfinish);
1090 if (!willEmitClose) {
1091 stream.on("abort", onclose);
1092 }
1093 if (stream.req) {
1094 onrequest();
1095 } else {
1096 stream.on("request", onrequest);
1097 }
1098 } else if (writable && !wState) {
1099 stream.on("end", onlegacyfinish);
1100 stream.on("close", onlegacyfinish);
1101 }
1102 if (!willEmitClose && typeof stream.aborted === "boolean") {
1103 stream.on("aborted", onclose);
1104 }
1105 stream.on("end", onend);
1106 stream.on("finish", onfinish);
1107 if (options.error !== false) {
1108 stream.on("error", onerror);
1109 }
1110 stream.on("close", onclose);
1111 if (closed) {
1112 process.nextTick(onclose);
1113 } else if (
1114 wState !== null && wState !== void 0 && wState.errorEmitted ||
1115 rState !== null && rState !== void 0 && rState.errorEmitted
1116 ) {
1117 if (!willEmitClose) {
1118 process.nextTick(onclose);
1119 }
1120 } else if (
1121 !readable && (!willEmitClose || isReadable(stream)) &&
1122 (writableFinished || isWritable(stream) === false)
1123 ) {
1124 process.nextTick(onclose);
1125 } else if (
1126 !writable && (!willEmitClose || isWritable(stream)) &&
1127 (readableFinished || isReadable(stream) === false)
1128 ) {
1129 process.nextTick(onclose);
1130 } else if (rState && stream.req && stream.aborted) {
1131 process.nextTick(onclose);
1132 }
1133 const cleanup = () => {
1134 callback = nop;
1135 stream.removeListener("aborted", onclose);
1136 stream.removeListener("complete", onfinish);
1137 stream.removeListener("abort", onclose);
1138 stream.removeListener("request", onrequest);
1139 if (stream.req) {
1140 stream.req.removeListener("finish", onfinish);
1141 }
1142 stream.removeListener("end", onlegacyfinish);
1143 stream.removeListener("close", onlegacyfinish);
1144 stream.removeListener("finish", onfinish);
1145 stream.removeListener("end", onend);
1146 stream.removeListener("error", onerror);
1147 stream.removeListener("close", onclose);
1148 };
1149 if (options.signal && !closed) {
1150 const abort = () => {
1151 const endCallback = callback;
1152 cleanup();
1153 endCallback.call(
1154 stream,
1155 new AbortError(void 0, {
1156 cause: options.signal.reason,
1157 }),
1158 );
1159 };
1160 if (options.signal.aborted) {
1161 process.nextTick(abort);
1162 } else {
1163 const originalCallback = callback;
1164 callback = once((...args) => {
1165 options.signal.removeEventListener("abort", abort);
1166 originalCallback.apply(stream, args);
1167 });
1168 options.signal.addEventListener("abort", abort);
1169 }
1170 }
1171 return cleanup;
1172 }
1173 function finished(stream, opts) {
1174 return new Promise2((resolve, reject) => {
1175 eos(stream, opts, (err) => {
1176 if (err) {
1177 reject(err);
1178 } else {
1179 resolve();
1180 }
1181 });
1182 });
1183 }
1184 module.exports = eos;
1185 module.exports.finished = finished;
1186 },
1187});
1188
1189// lib/internal/streams/operators.js
1190var require_operators = __commonJS({
1191 "lib/internal/streams/operators.js"(exports, module) {
1192 "use strict";
1193 var { validateAbortSignal, validateInteger, validateObject } =
1194 require_validators();
1195 var kWeakHandler = require_primordials().Symbol("kWeak");
1196 var { finished } = require_end_of_stream();
1197 var {
1198 ArrayPrototypePush,
1199 MathFloor,
1200 Number: Number2,
1201 NumberIsNaN,
1202 Promise: Promise2,
1203 PromiseReject,
1204 PromisePrototypeThen,
1205 Symbol: Symbol2,
1206 } = require_primordials();
1207 var kEmpty = Symbol2("kEmpty");
1208 var kEof = Symbol2("kEof");
1209 function map(fn, options) {
1210 if (typeof fn !== "function") {
1211 throw new ERR_INVALID_ARG_TYPE("fn", ["Function", "AsyncFunction"], fn);
1212 }
1213 if (options != null) {
1214 validateObject(options, "options");
1215 }
1216 if (
1217 (options === null || options === void 0 ? void 0 : options.signal) !=
1218 null
1219 ) {
1220 validateAbortSignal(options.signal, "options.signal");
1221 }
1222 let concurrency = 1;
1223 if (
1224 (options === null || options === void 0
1225 ? void 0
1226 : options.concurrency) != null
1227 ) {
1228 concurrency = MathFloor(options.concurrency);
1229 }
1230 validateInteger(concurrency, "concurrency", 1);
1231 return async function* map2() {
1232 var _options$signal, _options$signal2;
1233 const ac = new AbortController();
1234 const stream = this;
1235 const queue = [];
1236 const signal = ac.signal;
1237 const signalOpt = {
1238 signal,
1239 };
1240 const abort = () => ac.abort();
1241 if (
1242 options !== null && options !== void 0 &&
1243 (_options$signal = options.signal) !== null &&
1244 _options$signal !== void 0 && _options$signal.aborted
1245 ) {
1246 abort();
1247 }
1248 options === null || options === void 0
1249 ? void 0
1250 : (_options$signal2 = options.signal) === null ||
1251 _options$signal2 === void 0
1252 ? void 0
1253 : _options$signal2.addEventListener("abort", abort);
1254 let next;
1255 let resume;
1256 let done = false;
1257 function onDone() {
1258 done = true;
1259 }
1260 async function pump() {
1261 try {
1262 for await (let val of stream) {
1263 var _val;
1264 if (done) {
1265 return;
1266 }
1267 if (signal.aborted) {
1268 throw new AbortError();
1269 }
1270 try {
1271 val = fn(val, signalOpt);
1272 } catch (err) {
1273 val = PromiseReject(err);
1274 }
1275 if (val === kEmpty) {
1276 continue;
1277 }
1278 if (
1279 typeof ((_val = val) === null || _val === void 0
1280 ? void 0
1281 : _val.catch) === "function"
1282 ) {
1283 val.catch(onDone);
1284 }
1285 queue.push(val);
1286 if (next) {
1287 next();
1288 next = null;
1289 }
1290 if (!done && queue.length && queue.length >= concurrency) {
1291 await new Promise2((resolve) => {
1292 resume = resolve;
1293 });
1294 }
1295 }
1296 queue.push(kEof);
1297 } catch (err) {
1298 const val = PromiseReject(err);
1299 PromisePrototypeThen(val, void 0, onDone);
1300 queue.push(val);
1301 } finally {
1302 var _options$signal3;
1303 done = true;
1304 if (next) {
1305 next();
1306 next = null;
1307 }
1308 options === null || options === void 0
1309 ? void 0
1310 : (_options$signal3 = options.signal) === null ||
1311 _options$signal3 === void 0
1312 ? void 0
1313 : _options$signal3.removeEventListener("abort", abort);
1314 }
1315 }
1316 pump();
1317 try {
1318 while (true) {
1319 while (queue.length > 0) {
1320 const val = await queue[0];
1321 if (val === kEof) {
1322 return;
1323 }
1324 if (signal.aborted) {
1325 throw new AbortError();
1326 }
1327 if (val !== kEmpty) {
1328 yield val;
1329 }
1330 queue.shift();
1331 if (resume) {
1332 resume();
1333 resume = null;
1334 }
1335 }
1336 await new Promise2((resolve) => {
1337 next = resolve;
1338 });
1339 }
1340 } finally {
1341 ac.abort();
1342 done = true;
1343 if (resume) {
1344 resume();
1345 resume = null;
1346 }
1347 }
1348 }.call(this);
1349 }
1350 function asIndexedPairs(options = void 0) {
1351 if (options != null) {
1352 validateObject(options, "options");
1353 }
1354 if (
1355 (options === null || options === void 0 ? void 0 : options.signal) !=
1356 null
1357 ) {
1358 validateAbortSignal(options.signal, "options.signal");
1359 }
1360 return async function* asIndexedPairs2() {
1361 let index = 0;
1362 for await (const val of this) {
1363 var _options$signal4;
1364 if (
1365 options !== null && options !== void 0 &&
1366 (_options$signal4 = options.signal) !== null &&
1367 _options$signal4 !== void 0 && _options$signal4.aborted
1368 ) {
1369 throw new AbortError({
1370 cause: options.signal.reason,
1371 });
1372 }
1373 yield [index++, val];
1374 }
1375 }.call(this);
1376 }
1377 async function some(fn, options = void 0) {
1378 for await (const unused of filter.call(this, fn, options)) {
1379 return true;
1380 }
1381 return false;
1382 }
1383 async function every(fn, options = void 0) {
1384 if (typeof fn !== "function") {
1385 throw new ERR_INVALID_ARG_TYPE("fn", ["Function", "AsyncFunction"], fn);
1386 }
1387 return !await some.call(
1388 this,
1389 async (...args) => {
1390 return !await fn(...args);
1391 },
1392 options,
1393 );
1394 }
1395 async function find(fn, options) {
1396 for await (const result of filter.call(this, fn, options)) {
1397 return result;
1398 }
1399 return void 0;
1400 }
1401 async function forEach(fn, options) {
1402 if (typeof fn !== "function") {
1403 throw new ERR_INVALID_ARG_TYPE("fn", ["Function", "AsyncFunction"], fn);
1404 }
1405 async function forEachFn(value, options2) {
1406 await fn(value, options2);
1407 return kEmpty;
1408 }
1409 for await (const unused of map.call(this, forEachFn, options));
1410 }
1411 function filter(fn, options) {
1412 if (typeof fn !== "function") {
1413 throw new ERR_INVALID_ARG_TYPE("fn", ["Function", "AsyncFunction"], fn);
1414 }
1415 async function filterFn(value, options2) {
1416 if (await fn(value, options2)) {
1417 return value;
1418 }
1419 return kEmpty;
1420 }
1421 return map.call(this, filterFn, options);
1422 }
1423 var ReduceAwareErrMissingArgs = class extends ERR_MISSING_ARGS {
1424 constructor() {
1425 super("reduce");
1426 this.message = "Reduce of an empty stream requires an initial value";
1427 }
1428 };
1429 async function reduce(reducer, initialValue, options) {
1430 var _options$signal5;
1431 if (typeof reducer !== "function") {
1432 throw new ERR_INVALID_ARG_TYPE(
1433 "reducer",
1434 ["Function", "AsyncFunction"],
1435 reducer,
1436 );
1437 }
1438 if (options != null) {
1439 validateObject(options, "options");
1440 }
1441 if (
1442 (options === null || options === void 0 ? void 0 : options.signal) !=
1443 null
1444 ) {
1445 validateAbortSignal(options.signal, "options.signal");
1446 }
1447 let hasInitialValue = arguments.length > 1;
1448 if (
1449 options !== null && options !== void 0 &&
1450 (_options$signal5 = options.signal) !== null &&
1451 _options$signal5 !== void 0 && _options$signal5.aborted
1452 ) {
1453 const err = new AbortError(void 0, {
1454 cause: options.signal.reason,
1455 });
1456 this.once("error", () => {
1457 });
1458 await finished(this.destroy(err));
1459 throw err;
1460 }
1461 const ac = new AbortController();
1462 const signal = ac.signal;
1463 if (options !== null && options !== void 0 && options.signal) {
1464 const opts = {
1465 once: true,
1466 [kWeakHandler]: this,
1467 };
1468 options.signal.addEventListener("abort", () => ac.abort(), opts);
1469 }
1470 let gotAnyItemFromStream = false;
1471 try {
1472 for await (const value of this) {
1473 var _options$signal6;
1474 gotAnyItemFromStream = true;
1475 if (
1476 options !== null && options !== void 0 &&
1477 (_options$signal6 = options.signal) !== null &&
1478 _options$signal6 !== void 0 && _options$signal6.aborted
1479 ) {
1480 throw new AbortError();
1481 }
1482 if (!hasInitialValue) {
1483 initialValue = value;
1484 hasInitialValue = true;
1485 } else {
1486 initialValue = await reducer(initialValue, value, {
1487 signal,
1488 });
1489 }
1490 }
1491 if (!gotAnyItemFromStream && !hasInitialValue) {
1492 throw new ReduceAwareErrMissingArgs();
1493 }
1494 } finally {
1495 ac.abort();
1496 }
1497 return initialValue;
1498 }
1499 async function toArray(options) {
1500 if (options != null) {
1501 validateObject(options, "options");
1502 }
1503 if (
1504 (options === null || options === void 0 ? void 0 : options.signal) !=
1505 null
1506 ) {
1507 validateAbortSignal(options.signal, "options.signal");
1508 }
1509 const result = [];
1510 for await (const val of this) {
1511 var _options$signal7;
1512 if (
1513 options !== null && options !== void 0 &&
1514 (_options$signal7 = options.signal) !== null &&
1515 _options$signal7 !== void 0 && _options$signal7.aborted
1516 ) {
1517 throw new AbortError(void 0, {
1518 cause: options.signal.reason,
1519 });
1520 }
1521 ArrayPrototypePush(result, val);
1522 }
1523 return result;
1524 }
1525 function flatMap(fn, options) {
1526 const values = map.call(this, fn, options);
1527 return async function* flatMap2() {
1528 for await (const val of values) {
1529 yield* val;
1530 }
1531 }.call(this);
1532 }
1533 function toIntegerOrInfinity(number) {
1534 number = Number2(number);
1535 if (NumberIsNaN(number)) {
1536 return 0;
1537 }
1538 if (number < 0) {
1539 throw new ERR_OUT_OF_RANGE("number", ">= 0", number);
1540 }
1541 return number;
1542 }
1543 function drop(number, options = void 0) {
1544 if (options != null) {
1545 validateObject(options, "options");
1546 }
1547 if (
1548 (options === null || options === void 0 ? void 0 : options.signal) !=
1549 null
1550 ) {
1551 validateAbortSignal(options.signal, "options.signal");
1552 }
1553 number = toIntegerOrInfinity(number);
1554 return async function* drop2() {
1555 var _options$signal8;
1556 if (
1557 options !== null && options !== void 0 &&
1558 (_options$signal8 = options.signal) !== null &&
1559 _options$signal8 !== void 0 && _options$signal8.aborted
1560 ) {
1561 throw new AbortError();
1562 }
1563 for await (const val of this) {
1564 var _options$signal9;
1565 if (
1566 options !== null && options !== void 0 &&
1567 (_options$signal9 = options.signal) !== null &&
1568 _options$signal9 !== void 0 && _options$signal9.aborted
1569 ) {
1570 throw new AbortError();
1571 }
1572 if (number-- <= 0) {
1573 yield val;
1574 }
1575 }
1576 }.call(this);
1577 }
1578 function take(number, options = void 0) {
1579 if (options != null) {
1580 validateObject(options, "options");
1581 }
1582 if (
1583 (options === null || options === void 0 ? void 0 : options.signal) !=
1584 null
1585 ) {
1586 validateAbortSignal(options.signal, "options.signal");
1587 }
1588 number = toIntegerOrInfinity(number);
1589 return async function* take2() {
1590 var _options$signal10;
1591 if (
1592 options !== null && options !== void 0 &&
1593 (_options$signal10 = options.signal) !== null &&
1594 _options$signal10 !== void 0 && _options$signal10.aborted
1595 ) {
1596 throw new AbortError();
1597 }
1598 for await (const val of this) {
1599 var _options$signal11;
1600 if (
1601 options !== null && options !== void 0 &&
1602 (_options$signal11 = options.signal) !== null &&
1603 _options$signal11 !== void 0 && _options$signal11.aborted
1604 ) {
1605 throw new AbortError();
1606 }
1607 if (number-- > 0) {
1608 yield val;
1609 } else {
1610 return;
1611 }
1612 }
1613 }.call(this);
1614 }
1615 module.exports.streamReturningOperators = {
1616 asIndexedPairs,
1617 drop,
1618 filter,
1619 flatMap,
1620 map,
1621 take,
1622 };
1623 module.exports.promiseReturningOperators = {
1624 every,
1625 forEach,
1626 reduce,
1627 toArray,
1628 some,
1629 find,
1630 };
1631 },
1632});
1633
1634// lib/internal/streams/destroy.js
1635var require_destroy = __commonJS({
1636 "lib/internal/streams/destroy.js"(exports, module) {
1637 "use strict";
1638 var process = require_browser2();
1639 var { Symbol: Symbol2 } = require_primordials();
1640 var { kDestroyed, isDestroyed, isFinished, isServerRequest } =
1641 require_utils();
1642 var kDestroy = Symbol2("kDestroy");
1643 var kConstruct = Symbol2("kConstruct");
1644 function checkError(err, w, r) {
1645 if (err) {
1646 err.stack;
1647 if (w && !w.errored) {
1648 w.errored = err;
1649 }
1650 if (r && !r.errored) {
1651 r.errored = err;
1652 }
1653 }
1654 }
1655 function destroy(err, cb) {
1656 const r = this._readableState;
1657 const w = this._writableState;
1658 const s = w || r;
1659 if (w && w.destroyed || r && r.destroyed) {
1660 if (typeof cb === "function") {
1661 cb();
1662 }
1663 return this;
1664 }
1665 checkError(err, w, r);
1666 if (w) {
1667 w.destroyed = true;
1668 }
1669 if (r) {
1670 r.destroyed = true;
1671 }
1672 if (!s.constructed) {
1673 this.once(kDestroy, function (er) {
1674 _destroy(this, aggregateTwoErrors(er, err), cb);
1675 });
1676 } else {
1677 _destroy(this, err, cb);
1678 }
1679 return this;
1680 }
1681 function _destroy(self2, err, cb) {
1682 let called = false;
1683 function onDestroy(err2) {
1684 if (called) {
1685 return;
1686 }
1687 called = true;
1688 const r = self2._readableState;
1689 const w = self2._writableState;
1690 checkError(err2, w, r);
1691 if (w) {
1692 w.closed = true;
1693 }
1694 if (r) {
1695 r.closed = true;
1696 }
1697 if (typeof cb === "function") {
1698 cb(err2);
1699 }
1700 if (err2) {
1701 process.nextTick(emitErrorCloseNT, self2, err2);
1702 } else {
1703 process.nextTick(emitCloseNT, self2);
1704 }
1705 }
1706 try {
1707 self2._destroy(err || null, onDestroy);
1708 } catch (err2) {
1709 onDestroy(err2);
1710 }
1711 }
1712 function emitErrorCloseNT(self2, err) {
1713 emitErrorNT(self2, err);
1714 emitCloseNT(self2);
1715 }
1716 function emitCloseNT(self2) {
1717 const r = self2._readableState;
1718 const w = self2._writableState;
1719 if (w) {
1720 w.closeEmitted = true;
1721 }
1722 if (r) {
1723 r.closeEmitted = true;
1724 }
1725 if (w && w.emitClose || r && r.emitClose) {
1726 self2.emit("close");
1727 }
1728 }
1729 function emitErrorNT(self2, err) {
1730 const r = self2._readableState;
1731 const w = self2._writableState;
1732 if (w && w.errorEmitted || r && r.errorEmitted) {
1733 return;
1734 }
1735 if (w) {
1736 w.errorEmitted = true;
1737 }
1738 if (r) {
1739 r.errorEmitted = true;
1740 }
1741 self2.emit("error", err);
1742 }
1743 function undestroy() {
1744 const r = this._readableState;
1745 const w = this._writableState;
1746 if (r) {
1747 r.constructed = true;
1748 r.closed = false;
1749 r.closeEmitted = false;
1750 r.destroyed = false;
1751 r.errored = null;
1752 r.errorEmitted = false;
1753 r.reading = false;
1754 r.ended = r.readable === false;
1755 r.endEmitted = r.readable === false;
1756 }
1757 if (w) {
1758 w.constructed = true;
1759 w.destroyed = false;
1760 w.closed = false;
1761 w.closeEmitted = false;
1762 w.errored = null;
1763 w.errorEmitted = false;
1764 w.finalCalled = false;
1765 w.prefinished = false;
1766 w.ended = w.writable === false;
1767 w.ending = w.writable === false;
1768 w.finished = w.writable === false;
1769 }
1770 }
1771 function errorOrDestroy(stream, err, sync) {
1772 const r = stream._readableState;
1773 const w = stream._writableState;
1774 if (w && w.destroyed || r && r.destroyed) {
1775 return this;
1776 }
1777 if (r && r.autoDestroy || w && w.autoDestroy) {
1778 stream.destroy(err);
1779 } else if (err) {
1780 err.stack;
1781 if (w && !w.errored) {
1782 w.errored = err;
1783 }
1784 if (r && !r.errored) {
1785 r.errored = err;
1786 }
1787 if (sync) {
1788 process.nextTick(emitErrorNT, stream, err);
1789 } else {
1790 emitErrorNT(stream, err);
1791 }
1792 }
1793 }
1794 function construct(stream, cb) {
1795 if (typeof stream._construct !== "function") {
1796 return;
1797 }
1798 const r = stream._readableState;
1799 const w = stream._writableState;
1800 if (r) {
1801 r.constructed = false;
1802 }
1803 if (w) {
1804 w.constructed = false;
1805 }
1806 stream.once(kConstruct, cb);
1807 if (stream.listenerCount(kConstruct) > 1) {
1808 return;
1809 }
1810 process.nextTick(constructNT, stream);
1811 }
1812 function constructNT(stream) {
1813 let called = false;
1814 function onConstruct(err) {
1815 if (called) {
1816 errorOrDestroy(
1817 stream,
1818 err !== null && err !== void 0 ? err : new ERR_MULTIPLE_CALLBACK(),
1819 );
1820 return;
1821 }
1822 called = true;
1823 const r = stream._readableState;
1824 const w = stream._writableState;
1825 const s = w || r;
1826 if (r) {
1827 r.constructed = true;
1828 }
1829 if (w) {
1830 w.constructed = true;
1831 }
1832 if (s.destroyed) {
1833 stream.emit(kDestroy, err);
1834 } else if (err) {
1835 errorOrDestroy(stream, err, true);
1836 } else {
1837 stream.emit(kConstruct);
1838 }
1839 }
1840 try {
1841 stream._construct((err) => {
1842 nextTick(onConstruct, err);
1843 });
1844 } catch (err) {
1845 nextTick(onConstruct, err);
1846 }
1847 }
1848 function isRequest(stream) {
1849 return stream && stream.setHeader && typeof stream.abort === "function";
1850 }
1851 function emitCloseLegacy(stream) {
1852 stream.emit("close");
1853 }
1854 function emitErrorCloseLegacy(stream, err) {
1855 stream.emit("error", err);
1856 process.nextTick(emitCloseLegacy, stream);
1857 }
1858 function destroyer(stream, err) {
1859 if (!stream || isDestroyed(stream)) {
1860 return;
1861 }
1862 if (!err && !isFinished(stream)) {
1863 err = new AbortError();
1864 }
1865 if (isServerRequest(stream)) {
1866 stream.socket = null;
1867 stream.destroy(err);
1868 } else if (isRequest(stream)) {
1869 stream.abort();
1870 } else if (isRequest(stream.req)) {
1871 stream.req.abort();
1872 } else if (typeof stream.destroy === "function") {
1873 stream.destroy(err);
1874 } else if (typeof stream.close === "function") {
1875 stream.close();
1876 } else if (err) {
1877 process.nextTick(emitErrorCloseLegacy, stream, err);
1878 } else {
1879 process.nextTick(emitCloseLegacy, stream);
1880 }
1881 if (!stream.destroyed) {
1882 stream[kDestroyed] = true;
1883 }
1884 }
1885 module.exports = {
1886 construct,
1887 destroyer,
1888 destroy,
1889 undestroy,
1890 errorOrDestroy,
1891 };
1892 },
1893});
1894
1895// lib/internal/streams/legacy.js
1896var require_legacy = __commonJS({
1897 "lib/internal/streams/legacy.js"(exports, module) {
1898 "use strict";
1899 var { ArrayIsArray, ObjectSetPrototypeOf } = require_primordials();
1900 function Stream(opts) {
1901 EE.call(this, opts);
1902 }
1903 ObjectSetPrototypeOf(Stream.prototype, EE.prototype);
1904 ObjectSetPrototypeOf(Stream, EE);
1905 Stream.prototype.pipe = function (dest, options) {
1906 const source = this;
1907 function ondata(chunk) {
1908 if (dest.writable && dest.write(chunk) === false && source.pause) {
1909 source.pause();
1910 }
1911 }
1912 source.on("data", ondata);
1913 function ondrain() {
1914 if (source.readable && source.resume) {
1915 source.resume();
1916 }
1917 }
1918 dest.on("drain", ondrain);
1919 if (!dest._isStdio && (!options || options.end !== false)) {
1920 source.on("end", onend);
1921 source.on("close", onclose);
1922 }
1923 let didOnEnd = false;
1924 function onend() {
1925 if (didOnEnd) {
1926 return;
1927 }
1928 didOnEnd = true;
1929 dest.end();
1930 }
1931 function onclose() {
1932 if (didOnEnd) {
1933 return;
1934 }
1935 didOnEnd = true;
1936 if (typeof dest.destroy === "function") {
1937 dest.destroy();
1938 }
1939 }
1940 function onerror(er) {
1941 cleanup();
1942 if (EE.listenerCount(this, "error") === 0) {
1943 this.emit("error", er);
1944 }
1945 }
1946 prependListener(source, "error", onerror);
1947 prependListener(dest, "error", onerror);
1948 function cleanup() {
1949 source.removeListener("data", ondata);
1950 dest.removeListener("drain", ondrain);
1951 source.removeListener("end", onend);
1952 source.removeListener("close", onclose);
1953 source.removeListener("error", onerror);
1954 dest.removeListener("error", onerror);
1955 source.removeListener("end", cleanup);
1956 source.removeListener("close", cleanup);
1957 dest.removeListener("close", cleanup);
1958 }
1959 source.on("end", cleanup);
1960 source.on("close", cleanup);
1961 dest.on("close", cleanup);
1962 dest.emit("pipe", source);
1963 return dest;
1964 };
1965 function prependListener(emitter, event, fn) {
1966 if (typeof emitter.prependListener === "function") {
1967 return emitter.prependListener(event, fn);
1968 }
1969 if (!emitter._events || !emitter._events[event]) {
1970 emitter.on(event, fn);
1971 } else if (ArrayIsArray(emitter._events[event])) {
1972 emitter._events[event].unshift(fn);
1973 } else {
1974 emitter._events[event] = [fn, emitter._events[event]];
1975 }
1976 }
1977 module.exports = {
1978 Stream,
1979 prependListener,
1980 };
1981 },
1982});
1983
1984// lib/internal/streams/add-abort-signal.js
1985var require_add_abort_signal = __commonJS({
1986 "lib/internal/streams/add-abort-signal.js"(exports, module) {
1987 "use strict";
1988 var eos = require_end_of_stream();
1989 var validateAbortSignal = (signal, name) => {
1990 if (typeof signal !== "object" || !("aborted" in signal)) {
1991 throw new ERR_INVALID_ARG_TYPE(name, "AbortSignal", signal);
1992 }
1993 };
1994 function isNodeStream(obj) {
1995 return !!(obj && typeof obj.pipe === "function");
1996 }
1997 module.exports.addAbortSignal = function addAbortSignal(signal, stream) {
1998 validateAbortSignal(signal, "signal");
1999 if (!isNodeStream(stream)) {
2000 throw new ERR_INVALID_ARG_TYPE("stream", "stream.Stream", stream);
2001 }
2002 return module.exports.addAbortSignalNoValidate(signal, stream);
2003 };
2004 module.exports.addAbortSignalNoValidate = function (signal, stream) {
2005 if (typeof signal !== "object" || !("aborted" in signal)) {
2006 return stream;
2007 }
2008 const onAbort = () => {
2009 stream.destroy(
2010 new AbortError(void 0, {
2011 cause: signal.reason,
2012 }),
2013 );
2014 };
2015 if (signal.aborted) {
2016 onAbort();
2017 } else {
2018 signal.addEventListener("abort", onAbort);
2019 eos(stream, () => signal.removeEventListener("abort", onAbort));
2020 }
2021 return stream;
2022 };
2023 },
2024});
2025
2026// lib/internal/streams/buffer_list.js
2027var require_buffer_list = __commonJS({
2028 "lib/internal/streams/buffer_list.js"(exports, module) {
2029 "use strict";
2030 var {
2031 StringPrototypeSlice,
2032 SymbolIterator,
2033 TypedArrayPrototypeSet,
2034 Uint8Array: Uint8Array2,
2035 } = require_primordials();
2036 var { Buffer: Buffer2 } = require_buffer();
2037 module.exports = class BufferList {
2038 constructor() {
2039 this.head = null;
2040 this.tail = null;
2041 this.length = 0;
2042 }
2043 push(v) {
2044 const entry = {
2045 data: v,
2046 next: null,
2047 };
2048 if (this.length > 0) {
2049 this.tail.next = entry;
2050 } else {
2051 this.head = entry;
2052 }
2053 this.tail = entry;
2054 ++this.length;
2055 }
2056 unshift(v) {
2057 const entry = {
2058 data: v,
2059 next: this.head,
2060 };
2061 if (this.length === 0) {
2062 this.tail = entry;
2063 }
2064 this.head = entry;
2065 ++this.length;
2066 }
2067 shift() {
2068 if (this.length === 0) {
2069 return;
2070 }
2071 const ret = this.head.data;
2072 if (this.length === 1) {
2073 this.head = this.tail = null;
2074 } else {
2075 this.head = this.head.next;
2076 }
2077 --this.length;
2078 return ret;
2079 }
2080 clear() {
2081 this.head = this.tail = null;
2082 this.length = 0;
2083 }
2084 join(s) {
2085 if (this.length === 0) {
2086 return "";
2087 }
2088 let p = this.head;
2089 let ret = "" + p.data;
2090 while ((p = p.next) !== null) {
2091 ret += s + p.data;
2092 }
2093 return ret;
2094 }
2095 concat(n) {
2096 if (this.length === 0) {
2097 return Buffer2.alloc(0);
2098 }
2099 const ret = Buffer2.allocUnsafe(n >>> 0);
2100 let p = this.head;
2101 let i = 0;
2102 while (p) {
2103 TypedArrayPrototypeSet(ret, p.data, i);
2104 i += p.data.length;
2105 p = p.next;
2106 }
2107 return ret;
2108 }
2109 // Consumes a specified amount of bytes or characters from the
2110 // buffered data.
2111 consume(n, hasStrings) {
2112 const data = this.head.data;
2113 if (n < data.length) {
2114 const slice = data.slice(0, n);
2115 this.head.data = data.slice(n);
2116 return slice;
2117 }
2118 if (n === data.length) {
2119 return this.shift();
2120 }
2121 return hasStrings ? this._getString(n) : this._getBuffer(n);
2122 }
2123 first() {
2124 return this.head.data;
2125 }
2126 *[SymbolIterator]() {
2127 for (let p = this.head; p; p = p.next) {
2128 yield p.data;
2129 }
2130 }
2131 // Consumes a specified amount of characters from the buffered data.
2132 _getString(n) {
2133 let ret = "";
2134 let p = this.head;
2135 let c = 0;
2136 do {
2137 const str = p.data;
2138 if (n > str.length) {
2139 ret += str;
2140 n -= str.length;
2141 } else {
2142 if (n === str.length) {
2143 ret += str;
2144 ++c;
2145 if (p.next) {
2146 this.head = p.next;
2147 } else {
2148 this.head = this.tail = null;
2149 }
2150 } else {
2151 ret += StringPrototypeSlice(str, 0, n);
2152 this.head = p;
2153 p.data = StringPrototypeSlice(str, n);
2154 }
2155 break;
2156 }
2157 ++c;
2158 } while ((p = p.next) !== null);
2159 this.length -= c;
2160 return ret;
2161 }
2162 // Consumes a specified amount of bytes from the buffered data.
2163 _getBuffer(n) {
2164 const ret = Buffer2.allocUnsafe(n);
2165 const retLen = n;
2166 let p = this.head;
2167 let c = 0;
2168 do {
2169 const buf = p.data;
2170 if (n > buf.length) {
2171 TypedArrayPrototypeSet(ret, buf, retLen - n);
2172 n -= buf.length;
2173 } else {
2174 if (n === buf.length) {
2175 TypedArrayPrototypeSet(ret, buf, retLen - n);
2176 ++c;
2177 if (p.next) {
2178 this.head = p.next;
2179 } else {
2180 this.head = this.tail = null;
2181 }
2182 } else {
2183 TypedArrayPrototypeSet(
2184 ret,
2185 new Uint8Array2(buf.buffer, buf.byteOffset, n),
2186 retLen - n,
2187 );
2188 this.head = p;
2189 p.data = buf.slice(n);
2190 }
2191 break;
2192 }
2193 ++c;
2194 } while ((p = p.next) !== null);
2195 this.length -= c;
2196 return ret;
2197 }
2198 // Make sure the linked list only shows the minimal necessary information.
2199 [Symbol.for("nodejs.util.inspect.custom")](_, options) {
2200 return inspect(this, {
2201 ...options,
2202 // Only inspect one level.
2203 depth: 0,
2204 // It should not recurse.
2205 customInspect: false,
2206 });
2207 }
2208 };
2209 },
2210});
2211
2212// lib/internal/streams/state.js
2213var require_state = __commonJS({
2214 "lib/internal/streams/state.js"(exports, module) {
2215 "use strict";
2216 var { MathFloor, NumberIsInteger } = require_primordials();
2217 function highWaterMarkFrom(options, isDuplex, duplexKey) {
2218 return options.highWaterMark != null
2219 ? options.highWaterMark
2220 : isDuplex
2221 ? options[duplexKey]
2222 : null;
2223 }
2224 function getDefaultHighWaterMark(objectMode) {
2225 return objectMode ? 16 : 16 * 1024;
2226 }
2227 function getHighWaterMark(state, options, duplexKey, isDuplex) {
2228 const hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
2229 if (hwm != null) {
2230 if (!NumberIsInteger(hwm) || hwm < 0) {
2231 const name = isDuplex
2232 ? `options.${duplexKey}`
2233 : "options.highWaterMark";
2234 throw new ERR_INVALID_ARG_VALUE(name, hwm);
2235 }
2236 return MathFloor(hwm);
2237 }
2238 return getDefaultHighWaterMark(state.objectMode);
2239 }
2240 module.exports = {
2241 getHighWaterMark,
2242 getDefaultHighWaterMark,
2243 };
2244 },
2245});
2246
2247// node_modules/safe-buffer/index.js
2248var require_safe_buffer = __commonJS({
2249 "node_modules/safe-buffer/index.js"(exports, module) {
2250 var buffer = require_buffer();
2251 var Buffer2 = buffer.Buffer;
2252 function copyProps(src, dst) {
2253 for (var key in src) {
2254 dst[key] = src[key];
2255 }
2256 }
2257 if (
2258 Buffer2.from && Buffer2.alloc && Buffer2.allocUnsafe &&
2259 Buffer2.allocUnsafeSlow
2260 ) {
2261 module.exports = buffer;
2262 } else {
2263 copyProps(buffer, exports);
2264 exports.Buffer = SafeBuffer;
2265 }
2266 function SafeBuffer(arg, encodingOrOffset, length) {
2267 return Buffer2(arg, encodingOrOffset, length);
2268 }
2269 SafeBuffer.prototype = Object.create(Buffer2.prototype);
2270 copyProps(Buffer2, SafeBuffer);
2271 SafeBuffer.from = function (arg, encodingOrOffset, length) {
2272 if (typeof arg === "number") {
2273 throw new TypeError("Argument must not be a number");
2274 }
2275 return Buffer2(arg, encodingOrOffset, length);
2276 };
2277 SafeBuffer.alloc = function (size, fill, encoding) {
2278 if (typeof size !== "number") {
2279 throw new TypeError("Argument must be a number");
2280 }
2281 var buf = Buffer2(size);
2282 if (fill !== void 0) {
2283 if (typeof encoding === "string") {
2284 buf.fill(fill, encoding);
2285 } else {
2286 buf.fill(fill);
2287 }
2288 } else {
2289 buf.fill(0);
2290 }
2291 return buf;
2292 };
2293 SafeBuffer.allocUnsafe = function (size) {
2294 if (typeof size !== "number") {
2295 throw new TypeError("Argument must be a number");
2296 }
2297 return Buffer2(size);
2298 };
2299 SafeBuffer.allocUnsafeSlow = function (size) {
2300 if (typeof size !== "number") {
2301 throw new TypeError("Argument must be a number");
2302 }
2303 return buffer.SlowBuffer(size);
2304 };
2305 },
2306});
2307
2308// lib/internal/streams/from.js
2309var require_from = __commonJS({
2310 "lib/internal/streams/from.js"(exports, module) {
2311 "use strict";
2312 var process = require_browser2();
2313 var { PromisePrototypeThen, SymbolAsyncIterator, SymbolIterator } =
2314 require_primordials();
2315 var { Buffer: Buffer2 } = require_buffer();
2316 function from(Readable, iterable, opts) {
2317 let iterator;
2318 if (typeof iterable === "string" || iterable instanceof Buffer2) {
2319 return new Readable({
2320 objectMode: true,
2321 ...opts,
2322 read() {
2323 this.push(iterable);
2324 this.push(null);
2325 },
2326 });
2327 }
2328 let isAsync;
2329 if (iterable && iterable[SymbolAsyncIterator]) {
2330 isAsync = true;
2331 iterator = iterable[SymbolAsyncIterator]();
2332 } else if (iterable && iterable[SymbolIterator]) {
2333 isAsync = false;
2334 iterator = iterable[SymbolIterator]();
2335 } else {
2336 throw new ERR_INVALID_ARG_TYPE("iterable", ["Iterable"], iterable);
2337 }
2338 const readable = new Readable({
2339 objectMode: true,
2340 highWaterMark: 1,
2341 // TODO(ronag): What options should be allowed?
2342 ...opts,
2343 });
2344 let reading = false;
2345 readable._read = function () {
2346 if (!reading) {
2347 reading = true;
2348 next();
2349 }
2350 };
2351 readable._destroy = function (error, cb) {
2352 PromisePrototypeThen(
2353 close(error),
2354 () => process.nextTick(cb, error),
2355 // nextTick is here in case cb throws
2356 (e) => process.nextTick(cb, e || error),
2357 );
2358 };
2359 async function close(error) {
2360 const hadError = error !== void 0 && error !== null;
2361 const hasThrow = typeof iterator.throw === "function";
2362 if (hadError && hasThrow) {
2363 const { value, done } = await iterator.throw(error);
2364 await value;
2365 if (done) {
2366 return;
2367 }
2368 }
2369 if (typeof iterator.return === "function") {
2370 const { value } = await iterator.return();
2371 await value;
2372 }
2373 }
2374 async function next() {
2375 for (;;) {
2376 try {
2377 const { value, done } = isAsync
2378 ? await iterator.next()
2379 : iterator.next();
2380 if (done) {
2381 readable.push(null);
2382 } else {
2383 const res = value && typeof value.then === "function"
2384 ? await value
2385 : value;
2386 if (res === null) {
2387 reading = false;
2388 throw new ERR_STREAM_NULL_VALUES();
2389 } else if (readable.push(res)) {
2390 continue;
2391 } else {
2392 reading = false;
2393 }
2394 }
2395 } catch (err) {
2396 readable.destroy(err);
2397 }
2398 break;
2399 }
2400 }
2401 return readable;
2402 }
2403 module.exports = from;
2404 },
2405});
2406
2407// lib/internal/streams/readable.js
2408var require_readable = __commonJS({
2409 "lib/internal/streams/readable.js"(exports, module) {
2410 var process = require_browser2();
2411 var {
2412 ArrayPrototypeIndexOf,
2413 NumberIsInteger,
2414 NumberIsNaN,
2415 NumberParseInt,
2416 ObjectDefineProperties,
2417 ObjectKeys,
2418 ObjectSetPrototypeOf,
2419 Promise: Promise2,
2420 SafeSet,
2421 SymbolAsyncIterator,
2422 Symbol: Symbol2,
2423 } = require_primordials();
2424 module.exports = Readable;
2425 Readable.ReadableState = ReadableState;
2426 var { Stream, prependListener } = require_legacy();
2427 var { Buffer: Buffer2 } = require_buffer();
2428 var { addAbortSignal } = require_add_abort_signal();
2429 var eos = require_end_of_stream();
2430 var debug = debuglog("stream", (fn) => {
2431 debug = fn;
2432 });
2433 var BufferList = require_buffer_list();
2434 var destroyImpl = require_destroy();
2435 var { getHighWaterMark, getDefaultHighWaterMark } = require_state();
2436 var { validateObject } = require_validators();
2437 var kPaused = Symbol2("kPaused");
2438 var from = require_from();
2439 ObjectSetPrototypeOf(Readable.prototype, Stream.prototype);
2440 ObjectSetPrototypeOf(Readable, Stream);
2441 var nop = () => {
2442 };
2443 var { errorOrDestroy } = destroyImpl;
2444 function ReadableState(options, stream, isDuplex) {
2445 if (typeof isDuplex !== "boolean") {
2446 isDuplex = stream instanceof require_duplex();
2447 }
2448 this.objectMode = !!(options && options.objectMode);
2449 if (isDuplex) {
2450 this.objectMode = this.objectMode ||
2451 !!(options && options.readableObjectMode);
2452 }
2453 this.highWaterMark = options
2454 ? getHighWaterMark(this, options, "readableHighWaterMark", isDuplex)
2455 : getDefaultHighWaterMark(false);
2456 this.buffer = new BufferList();
2457 this.length = 0;
2458 this.pipes = [];
2459 this.flowing = null;
2460 this.ended = false;
2461 this.endEmitted = false;
2462 this.reading = false;
2463 this.constructed = true;
2464 this.sync = true;
2465 this.needReadable = false;
2466 this.emittedReadable = false;
2467 this.readableListening = false;
2468 this.resumeScheduled = false;
2469 this[kPaused] = null;
2470 this.errorEmitted = false;
2471 this.emitClose = !options || options.emitClose !== false;
2472 this.autoDestroy = !options || options.autoDestroy !== false;
2473 this.destroyed = false;
2474 this.errored = null;
2475 this.closed = false;
2476 this.closeEmitted = false;
2477 this.defaultEncoding = options && options.defaultEncoding || "utf8";
2478 this.awaitDrainWriters = null;
2479 this.multiAwaitDrain = false;
2480 this.readingMore = false;
2481 this.dataEmitted = false;
2482 this.decoder = null;
2483 this.encoding = null;
2484 if (options && options.encoding) {
2485 this.decoder = new StringDecoder(options.encoding);
2486 this.encoding = options.encoding;
2487 }
2488 }
2489 function Readable(options) {
2490 if (!(this instanceof Readable)) {
2491 return new Readable(options);
2492 }
2493 const isDuplex = this instanceof require_duplex();
2494 this._readableState = new ReadableState(options, this, isDuplex);
2495 if (options) {
2496 if (typeof options.read === "function") {
2497 this._read = options.read;
2498 }
2499 if (typeof options.destroy === "function") {
2500 this._destroy = options.destroy;
2501 }
2502 if (typeof options.construct === "function") {
2503 this._construct = options.construct;
2504 }
2505 if (options.signal && !isDuplex) {
2506 addAbortSignal(options.signal, this);
2507 }
2508 }
2509 Stream.call(this, options);
2510 destroyImpl.construct(this, () => {
2511 if (this._readableState.needReadable) {
2512 maybeReadMore(this, this._readableState);
2513 }
2514 });
2515 }
2516 Readable.prototype.destroy = destroyImpl.destroy;
2517 Readable.prototype._undestroy = destroyImpl.undestroy;
2518 Readable.prototype._destroy = function (err, cb) {
2519 cb(err);
2520 };
2521 Readable.prototype[EE.captureRejectionSymbol] = function (err) {
2522 this.destroy(err);
2523 };
2524 Readable.prototype.push = function (chunk, encoding) {
2525 return readableAddChunk(this, chunk, encoding, false);
2526 };
2527 Readable.prototype.unshift = function (chunk, encoding) {
2528 return readableAddChunk(this, chunk, encoding, true);
2529 };
2530 function readableAddChunk(stream, chunk, encoding, addToFront) {
2531 debug("readableAddChunk", chunk);
2532 const state = stream._readableState;
2533 let err;
2534 if (!state.objectMode) {
2535 if (typeof chunk === "string") {
2536 encoding = encoding || state.defaultEncoding;
2537 if (state.encoding !== encoding) {
2538 if (addToFront && state.encoding) {
2539 chunk = Buffer2.from(chunk, encoding).toString(state.encoding);
2540 } else {
2541 chunk = Buffer2.from(chunk, encoding);
2542 encoding = "";
2543 }
2544 }
2545 } else if (chunk instanceof Buffer2) {
2546 encoding = "";
2547 } else if (Stream._isUint8Array(chunk)) {
2548 chunk = Stream._uint8ArrayToBuffer(chunk);
2549 encoding = "";
2550 } else if (chunk != null) {
2551 err = new ERR_INVALID_ARG_TYPE("chunk", [
2552 "string",
2553 "Buffer",
2554 "Uint8Array",
2555 ], chunk);
2556 }
2557 }
2558 if (err) {
2559 errorOrDestroy(stream, err);
2560 } else if (chunk === null) {
2561 state.reading = false;
2562 onEofChunk(stream, state);
2563 } else if (state.objectMode || chunk && chunk.length > 0) {
2564 if (addToFront) {
2565 if (state.endEmitted) {
2566 errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());
2567 } else if (state.destroyed || state.errored) {
2568 return false;
2569 } else {
2570 addChunk(stream, state, chunk, true);
2571 }
2572 } else if (state.ended) {
2573 errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());
2574 } else if (state.destroyed || state.errored) {
2575 return false;
2576 } else {
2577 state.reading = false;
2578 if (state.decoder && !encoding) {
2579 chunk = state.decoder.write(chunk);
2580 if (state.objectMode || chunk.length !== 0) {
2581 addChunk(stream, state, chunk, false);
2582 } else {
2583 maybeReadMore(stream, state);
2584 }
2585 } else {
2586 addChunk(stream, state, chunk, false);
2587 }
2588 }
2589 } else if (!addToFront) {
2590 state.reading = false;
2591 maybeReadMore(stream, state);
2592 }
2593 return !state.ended &&
2594 (state.length < state.highWaterMark || state.length === 0);
2595 }
2596 function addChunk(stream, state, chunk, addToFront) {
2597 if (
2598 state.flowing && state.length === 0 && !state.sync &&
2599 stream.listenerCount("data") > 0
2600 ) {
2601 if (state.multiAwaitDrain) {
2602 state.awaitDrainWriters.clear();
2603 } else {
2604 state.awaitDrainWriters = null;
2605 }
2606 state.dataEmitted = true;
2607 stream.emit("data", chunk);
2608 } else {
2609 state.length += state.objectMode ? 1 : chunk.length;
2610 if (addToFront) {
2611 state.buffer.unshift(chunk);
2612 } else {
2613 state.buffer.push(chunk);
2614 }
2615 if (state.needReadable) {
2616 emitReadable(stream);
2617 }
2618 }
2619 maybeReadMore(stream, state);
2620 }
2621 Readable.prototype.isPaused = function () {
2622 const state = this._readableState;
2623 return state[kPaused] === true || state.flowing === false;
2624 };
2625 Readable.prototype.setEncoding = function (enc) {
2626 const decoder = new StringDecoder(enc);
2627 this._readableState.decoder = decoder;
2628 this._readableState.encoding = this._readableState.decoder.encoding;
2629 const buffer = this._readableState.buffer;
2630 let content = "";
2631 for (const data of buffer) {
2632 content += decoder.write(data);
2633 }
2634 buffer.clear();
2635 if (content !== "") {
2636 buffer.push(content);
2637 }
2638 this._readableState.length = content.length;
2639 return this;
2640 };
2641 var MAX_HWM = 1073741824;
2642 function computeNewHighWaterMark(n) {
2643 if (n > MAX_HWM) {
2644 throw new ERR_OUT_OF_RANGE("size", "<= 1GiB", n);
2645 } else {
2646 n--;
2647 n |= n >>> 1;
2648 n |= n >>> 2;
2649 n |= n >>> 4;
2650 n |= n >>> 8;
2651 n |= n >>> 16;
2652 n++;
2653 }
2654 return n;
2655 }
2656 function howMuchToRead(n, state) {
2657 if (n <= 0 || state.length === 0 && state.ended) {
2658 return 0;
2659 }
2660 if (state.objectMode) {
2661 return 1;
2662 }
2663 if (NumberIsNaN(n)) {
2664 if (state.flowing && state.length) {
2665 return state.buffer.first().length;
2666 }
2667 return state.length;
2668 }
2669 if (n <= state.length) {
2670 return n;
2671 }
2672 return state.ended ? state.length : 0;
2673 }
2674 Readable.prototype.read = function (n) {
2675 debug("read", n);
2676 if (n === void 0) {
2677 n = NaN;
2678 } else if (!NumberIsInteger(n)) {
2679 n = NumberParseInt(n, 10);
2680 }
2681 const state = this._readableState;
2682 const nOrig = n;
2683 if (n > state.highWaterMark) {
2684 state.highWaterMark = computeNewHighWaterMark(n);
2685 }
2686 if (n !== 0) {
2687 state.emittedReadable = false;
2688 }
2689 if (
2690 n === 0 && state.needReadable &&
2691 ((state.highWaterMark !== 0
2692 ? state.length >= state.highWaterMark
2693 : state.length > 0) || state.ended)
2694 ) {
2695 debug("read: emitReadable", state.length, state.ended);
2696 if (state.length === 0 && state.ended) {
2697 endReadable(this);
2698 } else {
2699 emitReadable(this);
2700 }
2701 return null;
2702 }
2703 n = howMuchToRead(n, state);
2704 if (n === 0 && state.ended) {
2705 if (state.length === 0) {
2706 endReadable(this);
2707 }
2708 return null;
2709 }
2710 let doRead = state.needReadable;
2711 debug("need readable", doRead);
2712 if (state.length === 0 || state.length - n < state.highWaterMark) {
2713 doRead = true;
2714 debug("length less than watermark", doRead);
2715 }
2716 if (
2717 state.ended || state.reading || state.destroyed || state.errored ||
2718 !state.constructed
2719 ) {
2720 doRead = false;
2721 debug("reading, ended or constructing", doRead);
2722 } else if (doRead) {
2723 debug("do read");
2724 state.reading = true;
2725 state.sync = true;
2726 if (state.length === 0) {
2727 state.needReadable = true;
2728 }
2729 try {
2730 this._read(state.highWaterMark);
2731 } catch (err) {
2732 errorOrDestroy(this, err);
2733 }
2734 state.sync = false;
2735 if (!state.reading) {
2736 n = howMuchToRead(nOrig, state);
2737 }
2738 }
2739 let ret;
2740 if (n > 0) {
2741 ret = fromList(n, state);
2742 } else {
2743 ret = null;
2744 }
2745 if (ret === null) {
2746 state.needReadable = state.length <= state.highWaterMark;
2747 n = 0;
2748 } else {
2749 state.length -= n;
2750 if (state.multiAwaitDrain) {
2751 state.awaitDrainWriters.clear();
2752 } else {
2753 state.awaitDrainWriters = null;
2754 }
2755 }
2756 if (state.length === 0) {
2757 if (!state.ended) {
2758 state.needReadable = true;
2759 }
2760 if (nOrig !== n && state.ended) {
2761 endReadable(this);
2762 }
2763 }
2764 if (ret !== null && !state.errorEmitted && !state.closeEmitted) {
2765 state.dataEmitted = true;
2766 this.emit("data", ret);
2767 }
2768 return ret;
2769 };
2770 function onEofChunk(stream, state) {
2771 debug("onEofChunk");
2772 if (state.ended) {
2773 return;
2774 }
2775 if (state.decoder) {
2776 const chunk = state.decoder.end();
2777 if (chunk && chunk.length) {
2778 state.buffer.push(chunk);
2779 state.length += state.objectMode ? 1 : chunk.length;
2780 }
2781 }
2782 state.ended = true;
2783 if (state.sync) {
2784 emitReadable(stream);
2785 } else {
2786 state.needReadable = false;
2787 state.emittedReadable = true;
2788 emitReadable_(stream);
2789 }
2790 }
2791 function emitReadable(stream) {
2792 const state = stream._readableState;
2793 debug("emitReadable", state.needReadable, state.emittedReadable);
2794 state.needReadable = false;
2795 if (!state.emittedReadable) {
2796 debug("emitReadable", state.flowing);
2797 state.emittedReadable = true;
2798 process.nextTick(emitReadable_, stream);
2799 }
2800 }
2801 function emitReadable_(stream) {
2802 const state = stream._readableState;
2803 debug("emitReadable_", state.destroyed, state.length, state.ended);
2804 if (!state.destroyed && !state.errored && (state.length || state.ended)) {
2805 stream.emit("readable");
2806 state.emittedReadable = false;
2807 }
2808 state.needReadable = !state.flowing && !state.ended &&
2809 state.length <= state.highWaterMark;
2810 flow(stream);
2811 }
2812 function maybeReadMore(stream, state) {
2813 if (!state.readingMore && state.constructed) {
2814 state.readingMore = true;
2815 process.nextTick(maybeReadMore_, stream, state);
2816 }
2817 }
2818 function maybeReadMore_(stream, state) {
2819 while (
2820 !state.reading && !state.ended &&
2821 (state.length < state.highWaterMark ||
2822 state.flowing && state.length === 0)
2823 ) {
2824 const len = state.length;
2825 debug("maybeReadMore read 0");
2826 stream.read(0);
2827 if (len === state.length) {
2828 break;
2829 }
2830 }
2831 state.readingMore = false;
2832 }
2833 Readable.prototype._read = function (n) {
2834 throw new ERR_METHOD_NOT_IMPLEMENTED("_read()");
2835 };
2836 Readable.prototype.pipe = function (dest, pipeOpts) {
2837 const src = this;
2838 const state = this._readableState;
2839 if (state.pipes.length === 1) {
2840 if (!state.multiAwaitDrain) {
2841 state.multiAwaitDrain = true;
2842 state.awaitDrainWriters = new SafeSet(
2843 state.awaitDrainWriters ? [state.awaitDrainWriters] : [],
2844 );
2845 }
2846 }
2847 state.pipes.push(dest);
2848 debug("pipe count=%d opts=%j", state.pipes.length, pipeOpts);
2849 const doEnd = (!pipeOpts || pipeOpts.end !== false) &&
2850 dest !== process.stdout && dest !== process.stderr;
2851 const endFn = doEnd ? onend : unpipe;
2852 if (state.endEmitted) {
2853 process.nextTick(endFn);
2854 } else {
2855 src.once("end", endFn);
2856 }
2857 dest.on("unpipe", onunpipe);
2858 function onunpipe(readable, unpipeInfo) {
2859 debug("onunpipe");
2860 if (readable === src) {
2861 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
2862 unpipeInfo.hasUnpiped = true;
2863 cleanup();
2864 }
2865 }
2866 }
2867 function onend() {
2868 debug("onend");
2869 dest.end();
2870 }
2871 let ondrain;
2872 let cleanedUp = false;
2873 function cleanup() {
2874 debug("cleanup");
2875 dest.removeListener("close", onclose);
2876 dest.removeListener("finish", onfinish);
2877 if (ondrain) {
2878 dest.removeListener("drain", ondrain);
2879 }
2880 dest.removeListener("error", onerror);
2881 dest.removeListener("unpipe", onunpipe);
2882 src.removeListener("end", onend);
2883 src.removeListener("end", unpipe);
2884 src.removeListener("data", ondata);
2885 cleanedUp = true;
2886 if (
2887 ondrain && state.awaitDrainWriters &&
2888 (!dest._writableState || dest._writableState.needDrain)
2889 ) {
2890 ondrain();
2891 }
2892 }
2893 function pause() {
2894 if (!cleanedUp) {
2895 if (state.pipes.length === 1 && state.pipes[0] === dest) {
2896 debug("false write response, pause", 0);
2897 state.awaitDrainWriters = dest;
2898 state.multiAwaitDrain = false;
2899 } else if (state.pipes.length > 1 && state.pipes.includes(dest)) {
2900 debug("false write response, pause", state.awaitDrainWriters.size);
2901 state.awaitDrainWriters.add(dest);
2902 }
2903 src.pause();
2904 }
2905 if (!ondrain) {
2906 ondrain = pipeOnDrain(src, dest);
2907 dest.on("drain", ondrain);
2908 }
2909 }
2910 src.on("data", ondata);
2911 function ondata(chunk) {
2912 debug("ondata");
2913 const ret = dest.write(chunk);
2914 debug("dest.write", ret);
2915 if (ret === false) {
2916 pause();
2917 }
2918 }
2919 function onerror(er) {
2920 debug("onerror", er);
2921 unpipe();
2922 dest.removeListener("error", onerror);
2923 if (dest.listenerCount("error") === 0) {
2924 const s = dest._writableState || dest._readableState;
2925 if (s && !s.errorEmitted) {
2926 errorOrDestroy(dest, er);
2927 } else {
2928 dest.emit("error", er);
2929 }
2930 }
2931 }
2932 prependListener(dest, "error", onerror);
2933 function onclose() {
2934 dest.removeListener("finish", onfinish);
2935 unpipe();
2936 }
2937 dest.once("close", onclose);
2938 function onfinish() {
2939 debug("onfinish");
2940 dest.removeListener("close", onclose);
2941 unpipe();
2942 }
2943 dest.once("finish", onfinish);
2944 function unpipe() {
2945 debug("unpipe");
2946 src.unpipe(dest);
2947 }
2948 dest.emit("pipe", src);
2949 if (dest.writableNeedDrain === true) {
2950 if (state.flowing) {
2951 pause();
2952 }
2953 } else if (!state.flowing) {
2954 debug("pipe resume");
2955 src.resume();
2956 }
2957 return dest;
2958 };
2959 function pipeOnDrain(src, dest) {
2960 return function pipeOnDrainFunctionResult() {
2961 const state = src._readableState;
2962 if (state.awaitDrainWriters === dest) {
2963 debug("pipeOnDrain", 1);
2964 state.awaitDrainWriters = null;
2965 } else if (state.multiAwaitDrain) {
2966 debug("pipeOnDrain", state.awaitDrainWriters.size);
2967 state.awaitDrainWriters.delete(dest);
2968 }
2969 if (
2970 (!state.awaitDrainWriters || state.awaitDrainWriters.size === 0) &&
2971 src.listenerCount("data")
2972 ) {
2973 src.resume();
2974 }
2975 };
2976 }
2977 Readable.prototype.unpipe = function (dest) {
2978 const state = this._readableState;
2979 const unpipeInfo = {
2980 hasUnpiped: false,
2981 };
2982 if (state.pipes.length === 0) {
2983 return this;
2984 }
2985 if (!dest) {
2986 const dests = state.pipes;
2987 state.pipes = [];
2988 this.pause();
2989 for (let i = 0; i < dests.length; i++) {
2990 dests[i].emit("unpipe", this, {
2991 hasUnpiped: false,
2992 });
2993 }
2994 return this;
2995 }
2996 const index = ArrayPrototypeIndexOf(state.pipes, dest);
2997 if (index === -1) {
2998 return this;
2999 }
3000 state.pipes.splice(index, 1);
3001 if (state.pipes.length === 0) {
3002 this.pause();
3003 }
3004 dest.emit("unpipe", this, unpipeInfo);
3005 return this;
3006 };
3007 Readable.prototype.on = function (ev, fn) {
3008 const res = Stream.prototype.on.call(this, ev, fn);
3009 const state = this._readableState;
3010 if (ev === "data") {
3011 state.readableListening = this.listenerCount("readable") > 0;
3012 if (state.flowing !== false) {
3013 this.resume();
3014 }
3015 } else if (ev === "readable") {
3016 if (!state.endEmitted && !state.readableListening) {
3017 state.readableListening = state.needReadable = true;
3018 state.flowing = false;
3019 state.emittedReadable = false;
3020 debug("on readable", state.length, state.reading);
3021 if (state.length) {
3022 emitReadable(this);
3023 } else if (!state.reading) {
3024 process.nextTick(nReadingNextTick, this);
3025 }
3026 }
3027 }
3028 return res;
3029 };
3030 Readable.prototype.addListener = Readable.prototype.on;
3031 Readable.prototype.removeListener = function (ev, fn) {
3032 const res = Stream.prototype.removeListener.call(this, ev, fn);
3033 if (ev === "readable") {
3034 process.nextTick(updateReadableListening, this);
3035 }
3036 return res;
3037 };
3038 Readable.prototype.off = Readable.prototype.removeListener;
3039 Readable.prototype.removeAllListeners = function (ev) {
3040 const res = Stream.prototype.removeAllListeners.apply(this, arguments);
3041 if (ev === "readable" || ev === void 0) {
3042 process.nextTick(updateReadableListening, this);
3043 }
3044 return res;
3045 };
3046 function updateReadableListening(self2) {
3047 const state = self2._readableState;
3048 state.readableListening = self2.listenerCount("readable") > 0;
3049 if (state.resumeScheduled && state[kPaused] === false) {
3050 state.flowing = true;
3051 } else if (self2.listenerCount("data") > 0) {
3052 self2.resume();
3053 } else if (!state.readableListening) {
3054 state.flowing = null;
3055 }
3056 }
3057 function nReadingNextTick(self2) {
3058 debug("readable nexttick read 0");
3059 self2.read(0);
3060 }
3061 Readable.prototype.resume = function () {
3062 const state = this._readableState;
3063 if (!state.flowing) {
3064 debug("resume");
3065 state.flowing = !state.readableListening;
3066 resume(this, state);
3067 }
3068 state[kPaused] = false;
3069 return this;
3070 };
3071 function resume(stream, state) {
3072 if (!state.resumeScheduled) {
3073 state.resumeScheduled = true;
3074 process.nextTick(resume_, stream, state);
3075 }
3076 }
3077 function resume_(stream, state) {
3078 debug("resume", state.reading);
3079 if (!state.reading) {
3080 stream.read(0);
3081 }
3082 state.resumeScheduled = false;
3083 stream.emit("resume");
3084 flow(stream);
3085 if (state.flowing && !state.reading) {
3086 stream.read(0);
3087 }
3088 }
3089 Readable.prototype.pause = function () {
3090 debug("call pause flowing=%j", this._readableState.flowing);
3091 if (this._readableState.flowing !== false) {
3092 debug("pause");
3093 this._readableState.flowing = false;
3094 this.emit("pause");
3095 }
3096 this._readableState[kPaused] = true;
3097 return this;
3098 };
3099 function flow(stream) {
3100 const state = stream._readableState;
3101 debug("flow", state.flowing);
3102 while (state.flowing && stream.read() !== null);
3103 }
3104 Readable.prototype.wrap = function (stream) {
3105 let paused = false;
3106 stream.on("data", (chunk) => {
3107 if (!this.push(chunk) && stream.pause) {
3108 paused = true;
3109 stream.pause();
3110 }
3111 });
3112 stream.on("end", () => {
3113 this.push(null);
3114 });
3115 stream.on("error", (err) => {
3116 errorOrDestroy(this, err);
3117 });
3118 stream.on("close", () => {
3119 this.destroy();
3120 });
3121 stream.on("destroy", () => {
3122 this.destroy();
3123 });
3124 this._read = () => {
3125 if (paused && stream.resume) {
3126 paused = false;
3127 stream.resume();
3128 }
3129 };
3130 const streamKeys = ObjectKeys(stream);
3131 for (let j = 1; j < streamKeys.length; j++) {
3132 const i = streamKeys[j];
3133 if (this[i] === void 0 && typeof stream[i] === "function") {
3134 this[i] = stream[i].bind(stream);
3135 }
3136 }
3137 return this;
3138 };
3139 Readable.prototype[SymbolAsyncIterator] = function () {
3140 return streamToAsyncIterator(this);
3141 };
3142 Readable.prototype.iterator = function (options) {
3143 if (options !== void 0) {
3144 validateObject(options, "options");
3145 }
3146 return streamToAsyncIterator(this, options);
3147 };
3148 function streamToAsyncIterator(stream, options) {
3149 if (typeof stream.read !== "function") {
3150 stream = Readable.wrap(stream, {
3151 objectMode: true,
3152 });
3153 }
3154 const iter = createAsyncIterator(stream, options);
3155 iter.stream = stream;
3156 return iter;
3157 }
3158 async function* createAsyncIterator(stream, options) {
3159 let callback = nop;
3160 function next(resolve) {
3161 if (this === stream) {
3162 callback();
3163 callback = nop;
3164 } else {
3165 callback = resolve;
3166 }
3167 }
3168 stream.on("readable", next);
3169 let error;
3170 const cleanup = eos(
3171 stream,
3172 {
3173 writable: false,
3174 },
3175 (err) => {
3176 error = err ? aggregateTwoErrors(error, err) : null;
3177 callback();
3178 callback = nop;
3179 },
3180 );
3181 try {
3182 while (true) {
3183 const chunk = stream.destroyed ? null : stream.read();
3184 if (chunk !== null) {
3185 yield chunk;
3186 } else if (error) {
3187 throw error;
3188 } else if (error === null) {
3189 return;
3190 } else {
3191 await new Promise2(next);
3192 }
3193 }
3194 } catch (err) {
3195 error = aggregateTwoErrors(error, err);
3196 throw error;
3197 } finally {
3198 if (
3199 (error ||
3200 (options === null || options === void 0
3201 ? void 0
3202 : options.destroyOnReturn) !== false) &&
3203 (error === void 0 || stream._readableState.autoDestroy)
3204 ) {
3205 destroyImpl.destroyer(stream, null);
3206 } else {
3207 stream.off("readable", next);
3208 cleanup();
3209 }
3210 }
3211 }
3212 ObjectDefineProperties(Readable.prototype, {
3213 readable: {
3214 __proto__: null,
3215 get() {
3216 const r = this._readableState;
3217 return !!r && r.readable !== false && !r.destroyed &&
3218 !r.errorEmitted && !r.endEmitted;
3219 },
3220 set(val) {
3221 if (this._readableState) {
3222 this._readableState.readable = !!val;
3223 }
3224 },
3225 },
3226 readableDidRead: {
3227 __proto__: null,
3228 enumerable: false,
3229 get: function () {
3230 return this._readableState.dataEmitted;
3231 },
3232 },
3233 readableAborted: {
3234 __proto__: null,
3235 enumerable: false,
3236 get: function () {
3237 return !!(this._readableState.readable !== false &&
3238 (this._readableState.destroyed || this._readableState.errored) &&
3239 !this._readableState.endEmitted);
3240 },
3241 },
3242 readableHighWaterMark: {
3243 __proto__: null,
3244 enumerable: false,
3245 get: function () {
3246 return this._readableState.highWaterMark;
3247 },
3248 },
3249 readableBuffer: {
3250 __proto__: null,
3251 enumerable: false,
3252 get: function () {
3253 return this._readableState && this._readableState.buffer;
3254 },
3255 },
3256 readableFlowing: {
3257 __proto__: null,
3258 enumerable: false,
3259 get: function () {
3260 return this._readableState.flowing;
3261 },
3262 set: function (state) {
3263 if (this._readableState) {
3264 this._readableState.flowing = state;
3265 }
3266 },
3267 },
3268 readableLength: {
3269 __proto__: null,
3270 enumerable: false,
3271 get() {
3272 return this._readableState.length;
3273 },
3274 },
3275 readableObjectMode: {
3276 __proto__: null,
3277 enumerable: false,
3278 get() {
3279 return this._readableState ? this._readableState.objectMode : false;
3280 },
3281 },
3282 readableEncoding: {
3283 __proto__: null,
3284 enumerable: false,
3285 get() {
3286 return this._readableState ? this._readableState.encoding : null;
3287 },
3288 },
3289 errored: {
3290 __proto__: null,
3291 enumerable: false,
3292 get() {
3293 return this._readableState ? this._readableState.errored : null;
3294 },
3295 },
3296 closed: {
3297 __proto__: null,
3298 get() {
3299 return this._readableState ? this._readableState.closed : false;
3300 },
3301 },
3302 destroyed: {
3303 __proto__: null,
3304 enumerable: false,
3305 get() {
3306 return this._readableState ? this._readableState.destroyed : false;
3307 },
3308 set(value) {
3309 if (!this._readableState) {
3310 return;
3311 }
3312 this._readableState.destroyed = value;
3313 },
3314 },
3315 readableEnded: {
3316 __proto__: null,
3317 enumerable: false,
3318 get() {
3319 return this._readableState ? this._readableState.endEmitted : false;
3320 },
3321 },
3322 });
3323 ObjectDefineProperties(ReadableState.prototype, {
3324 // Legacy getter for `pipesCount`.
3325 pipesCount: {
3326 __proto__: null,
3327 get() {
3328 return this.pipes.length;
3329 },
3330 },
3331 // Legacy property for `paused`.
3332 paused: {
3333 __proto__: null,
3334 get() {
3335 return this[kPaused] !== false;
3336 },
3337 set(value) {
3338 this[kPaused] = !!value;
3339 },
3340 },
3341 });
3342 Readable._fromList = fromList;
3343 function fromList(n, state) {
3344 if (state.length === 0) {
3345 return null;
3346 }
3347 let ret;
3348 if (state.objectMode) {
3349 ret = state.buffer.shift();
3350 } else if (!n || n >= state.length) {
3351 if (state.decoder) {
3352 ret = state.buffer.join("");
3353 } else if (state.buffer.length === 1) {
3354 ret = state.buffer.first();
3355 } else {
3356 ret = state.buffer.concat(state.length);
3357 }
3358 state.buffer.clear();
3359 } else {
3360 ret = state.buffer.consume(n, state.decoder);
3361 }
3362 return ret;
3363 }
3364 function endReadable(stream) {
3365 const state = stream._readableState;
3366 debug("endReadable", state.endEmitted);
3367 if (!state.endEmitted) {
3368 state.ended = true;
3369 process.nextTick(endReadableNT, state, stream);
3370 }
3371 }
3372 function endReadableNT(state, stream) {
3373 debug("endReadableNT", state.endEmitted, state.length);
3374 if (
3375 !state.errored && !state.closeEmitted && !state.endEmitted &&
3376 state.length === 0
3377 ) {
3378 state.endEmitted = true;
3379 stream.emit("end");
3380 if (stream.writable && stream.allowHalfOpen === false) {
3381 process.nextTick(endWritableNT, stream);
3382 } else if (state.autoDestroy) {
3383 const wState = stream._writableState;
3384 // We don't expect the writable to ever 'finish' if writable is
3385 // explicitly set to false.
3386 const autoDestroy = !wState || wState.autoDestroy &&
3387 (wState.finished || wState.writable === false);
3388 if (autoDestroy) {
3389 stream.destroy();
3390 }
3391 }
3392 }
3393 }
3394 function endWritableNT(stream) {
3395 const writable = stream.writable && !stream.writableEnded &&
3396 !stream.destroyed;
3397 if (writable) {
3398 stream.end();
3399 }
3400 }
3401 Readable.from = function (iterable, opts) {
3402 return from(Readable, iterable, opts);
3403 };
3404 var webStreamsAdapters;
3405 function lazyWebStreams() {
3406 if (webStreamsAdapters === void 0) {
3407 webStreamsAdapters = {};
3408 }
3409 return webStreamsAdapters;
3410 }
3411 Readable.fromWeb = function (readableStream, options) {
3412 return lazyWebStreams().newStreamReadableFromReadableStream(
3413 readableStream,
3414 options,
3415 );
3416 };
3417 Readable.toWeb = function (streamReadable, options) {
3418 return lazyWebStreams().newReadableStreamFromStreamReadable(
3419 streamReadable,
3420 options,
3421 );
3422 };
3423 Readable.wrap = function (src, options) {
3424 var _ref, _src$readableObjectMo;
3425 return new Readable({
3426 objectMode:
3427 (_ref = (_src$readableObjectMo = src.readableObjectMode) !== null &&
3428 _src$readableObjectMo !== void 0
3429 ? _src$readableObjectMo
3430 : src.objectMode) !== null && _ref !== void 0
3431 ? _ref
3432 : true,
3433 ...options,
3434 destroy(err, callback) {
3435 destroyImpl.destroyer(src, err);
3436 callback(err);
3437 },
3438 }).wrap(src);
3439 };
3440 },
3441});
3442
3443// lib/internal/streams/writable.js
3444var require_writable = __commonJS({
3445 "lib/internal/streams/writable.js"(exports, module) {
3446 var process = require_browser2();
3447 var {
3448 ArrayPrototypeSlice,
3449 Error: Error2,
3450 FunctionPrototypeSymbolHasInstance,
3451 ObjectDefineProperty,
3452 ObjectDefineProperties,
3453 ObjectSetPrototypeOf,
3454 StringPrototypeToLowerCase,
3455 Symbol: Symbol2,
3456 SymbolHasInstance,
3457 } = require_primordials();
3458 module.exports = Writable;
3459 Writable.WritableState = WritableState;
3460 var Stream = require_legacy().Stream;
3461 var { Buffer: Buffer2 } = require_buffer();
3462 var destroyImpl = require_destroy();
3463 var { addAbortSignal } = require_add_abort_signal();
3464 var { getHighWaterMark, getDefaultHighWaterMark } = require_state();
3465 var { errorOrDestroy } = destroyImpl;
3466 ObjectSetPrototypeOf(Writable.prototype, Stream.prototype);
3467 ObjectSetPrototypeOf(Writable, Stream);
3468 function nop() {
3469 }
3470 var kOnFinished = Symbol2("kOnFinished");
3471 function WritableState(options, stream, isDuplex) {
3472 if (typeof isDuplex !== "boolean") {
3473 isDuplex = stream instanceof require_duplex();
3474 }
3475 this.objectMode = !!(options && options.objectMode);
3476 if (isDuplex) {
3477 this.objectMode = this.objectMode ||
3478 !!(options && options.writableObjectMode);
3479 }
3480 this.highWaterMark = options
3481 ? getHighWaterMark(this, options, "writableHighWaterMark", isDuplex)
3482 : getDefaultHighWaterMark(false);
3483 this.finalCalled = false;
3484 this.needDrain = false;
3485 this.ending = false;
3486 this.ended = false;
3487 this.finished = false;
3488 this.destroyed = false;
3489 const noDecode = !!(options && options.decodeStrings === false);
3490 this.decodeStrings = !noDecode;
3491 const defaultEncoding = options?.defaultEncoding;
3492 if (defaultEncoding == null) {
3493 this.defaultEncoding = 'utf8';
3494 } else if (Buffer2.isEncoding(defaultEncoding)) {
3495 this.defaultEncoding = defaultEncoding;
3496 } else {
3497 throw new ERR_UNKNOWN_ENCODING(defaultEncoding);
3498 }
3499 this.length = 0;
3500 this.writing = false;
3501 this.corked = 0;
3502 this.sync = true;
3503 this.bufferProcessing = false;
3504 this.onwrite = onwrite.bind(void 0, stream);
3505 this.writecb = null;
3506 this.writelen = 0;
3507 this.afterWriteTickInfo = null;
3508 resetBuffer(this);
3509 this.pendingcb = 0;
3510 this.constructed = true;
3511 this.prefinished = false;
3512 this.errorEmitted = false;
3513 this.emitClose = !options || options.emitClose !== false;
3514 this.autoDestroy = !options || options.autoDestroy !== false;
3515 this.errored = null;
3516 this.closed = false;
3517 this.closeEmitted = false;
3518 this[kOnFinished] = [];
3519 }
3520 function resetBuffer(state) {
3521 state.buffered = [];
3522 state.bufferedIndex = 0;
3523 state.allBuffers = true;
3524 state.allNoop = true;
3525 }
3526 WritableState.prototype.getBuffer = function getBuffer() {
3527 return ArrayPrototypeSlice(this.buffered, this.bufferedIndex);
3528 };
3529 ObjectDefineProperty(WritableState.prototype, "bufferedRequestCount", {
3530 __proto__: null,
3531 get() {
3532 return this.buffered.length - this.bufferedIndex;
3533 },
3534 });
3535 function Writable(options) {
3536 const isDuplex = this instanceof require_duplex();
3537 if (!isDuplex && !FunctionPrototypeSymbolHasInstance(Writable, this)) {
3538 return new Writable(options);
3539 }
3540 this._writableState = new WritableState(options, this, isDuplex);
3541 if (options) {
3542 if (typeof options.write === "function") {
3543 this._write = options.write;
3544 }
3545 if (typeof options.writev === "function") {
3546 this._writev = options.writev;
3547 }
3548 if (typeof options.destroy === "function") {
3549 this._destroy = options.destroy;
3550 }
3551 if (typeof options.final === "function") {
3552 this._final = options.final;
3553 }
3554 if (typeof options.construct === "function") {
3555 this._construct = options.construct;
3556 }
3557 if (options.signal) {
3558 addAbortSignal(options.signal, this);
3559 }
3560 }
3561 Stream.call(this, options);
3562 destroyImpl.construct(this, () => {
3563 const state = this._writableState;
3564 if (!state.writing) {
3565 clearBuffer(this, state);
3566 }
3567 finishMaybe(this, state);
3568 });
3569 }
3570 ObjectDefineProperty(Writable, SymbolHasInstance, {
3571 __proto__: null,
3572 value: function (object) {
3573 if (FunctionPrototypeSymbolHasInstance(this, object)) {
3574 return true;
3575 }
3576 if (this !== Writable) {
3577 return false;
3578 }
3579 return object && object._writableState instanceof WritableState;
3580 },
3581 });
3582 Writable.prototype.pipe = function () {
3583 errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
3584 };
3585 function _write(stream, chunk, encoding, cb) {
3586 const state = stream._writableState;
3587 if (typeof encoding === "function") {
3588 cb = encoding;
3589 // Simulates nodejs/node commit
3590 // dbed0319ac438dcbd6e92483f3280b1dc6767e00
3591 encoding = state.objectMode ? undefined : state.defaultEncoding;
3592 } else {
3593 if (!encoding) {
3594 // Simulates nodejs/node commit
3595 // dbed0319ac438dcbd6e92483f3280b1dc6767e00
3596 encoding = state.objectMode ? undefined : state.defaultEncoding;
3597 } else if (encoding !== "buffer" && !Buffer2.isEncoding(encoding)) {
3598 throw new ERR_UNKNOWN_ENCODING(encoding);
3599 }
3600 if (typeof cb !== "function") {
3601 cb = nop;
3602 }
3603 }
3604 if (chunk === null) {
3605 throw new ERR_STREAM_NULL_VALUES();
3606 } else if (!state.objectMode) {
3607 if (typeof chunk === "string") {
3608 if (state.decodeStrings !== false) {
3609 chunk = Buffer2.from(chunk, encoding);
3610 encoding = "buffer";
3611 }
3612 } else if (chunk instanceof Buffer2) {
3613 encoding = "buffer";
3614 } else if (Stream._isUint8Array(chunk)) {
3615 chunk = Stream._uint8ArrayToBuffer(chunk);
3616 encoding = "buffer";
3617 } else {
3618 throw new ERR_INVALID_ARG_TYPE("chunk", [
3619 "string",
3620 "Buffer",
3621 "Uint8Array",
3622 ], chunk);
3623 }
3624 }
3625 let err;
3626 if (state.ending) {
3627 err = new ERR_STREAM_WRITE_AFTER_END();
3628 } else if (state.destroyed) {
3629 err = new ERR_STREAM_DESTROYED("write");
3630 }
3631 if (err) {
3632 process.nextTick(cb, err);
3633 errorOrDestroy(stream, err, true);
3634 return err;
3635 }
3636 state.pendingcb++;
3637 return writeOrBuffer(stream, state, chunk, encoding, cb);
3638 }
3639 Writable.prototype.write = function (chunk, encoding, cb) {
3640 return _write(this, chunk, encoding, cb) === true;
3641 };
3642 Writable.prototype.cork = function () {
3643 this._writableState.corked++;
3644 };
3645 Writable.prototype.uncork = function () {
3646 const state = this._writableState;
3647 if (state.corked) {
3648 state.corked--;
3649 if (!state.writing) {
3650 clearBuffer(this, state);
3651 }
3652 }
3653 };
3654 Writable.prototype.setDefaultEncoding = function setDefaultEncoding(
3655 encoding,
3656 ) {
3657 if (typeof encoding === "string") {
3658 encoding = StringPrototypeToLowerCase(encoding);
3659 }
3660 if (!Buffer2.isEncoding(encoding)) {
3661 throw new ERR_UNKNOWN_ENCODING(encoding);
3662 }
3663 this._writableState.defaultEncoding = encoding;
3664 return this;
3665 };
3666 function writeOrBuffer(stream, state, chunk, encoding, callback) {
3667 const len = state.objectMode ? 1 : chunk.length;
3668 state.length += len;
3669 const ret = state.length < state.highWaterMark;
3670 if (!ret) {
3671 state.needDrain = true;
3672 }
3673 if (
3674 state.writing || state.corked || state.errored || !state.constructed
3675 ) {
3676 state.buffered.push({
3677 chunk,
3678 encoding,
3679 callback,
3680 });
3681 if (state.allBuffers && encoding !== "buffer") {
3682 state.allBuffers = false;
3683 }
3684 if (state.allNoop && callback !== nop) {
3685 state.allNoop = false;
3686 }
3687 } else {
3688 state.writelen = len;
3689 state.writecb = callback;
3690 state.writing = true;
3691 state.sync = true;
3692 stream._write(chunk, encoding, state.onwrite);
3693 state.sync = false;
3694 }
3695 return ret && !state.errored && !state.destroyed;
3696 }
3697 function doWrite(stream, state, writev, len, chunk, encoding, cb) {
3698 state.writelen = len;
3699 state.writecb = cb;
3700 state.writing = true;
3701 state.sync = true;
3702 if (state.destroyed) {
3703 state.onwrite(new ERR_STREAM_DESTROYED("write"));
3704 } else if (writev) {
3705 stream._writev(chunk, state.onwrite);
3706 } else {
3707 stream._write(chunk, encoding, state.onwrite);
3708 }
3709 state.sync = false;
3710 }
3711 function onwriteError(stream, state, er, cb) {
3712 --state.pendingcb;
3713 cb(er);
3714 errorBuffer(state);
3715 errorOrDestroy(stream, er);
3716 }
3717 function onwrite(stream, er) {
3718 const state = stream._writableState;
3719 const sync = state.sync;
3720 const cb = state.writecb;
3721 if (typeof cb !== "function") {
3722 errorOrDestroy(stream, new ERR_MULTIPLE_CALLBACK());
3723 return;
3724 }
3725 state.writing = false;
3726 state.writecb = null;
3727 state.length -= state.writelen;
3728 state.writelen = 0;
3729 if (er) {
3730 er.stack;
3731 if (!state.errored) {
3732 state.errored = er;
3733 }
3734 if (stream._readableState && !stream._readableState.errored) {
3735 stream._readableState.errored = er;
3736 }
3737 if (sync) {
3738 process.nextTick(onwriteError, stream, state, er, cb);
3739 } else {
3740 onwriteError(stream, state, er, cb);
3741 }
3742 } else {
3743 if (state.buffered.length > state.bufferedIndex) {
3744 clearBuffer(stream, state);
3745 }
3746 if (sync) {
3747 if (
3748 state.afterWriteTickInfo !== null &&
3749 state.afterWriteTickInfo.cb === cb
3750 ) {
3751 state.afterWriteTickInfo.count++;
3752 } else {
3753 state.afterWriteTickInfo = {
3754 count: 1,
3755 cb,
3756 stream,
3757 state,
3758 };
3759 process.nextTick(afterWriteTick, state.afterWriteTickInfo);
3760 }
3761 } else {
3762 afterWrite(stream, state, 1, cb);
3763 }
3764 }
3765 }
3766 function afterWriteTick({ stream, state, count, cb }) {
3767 state.afterWriteTickInfo = null;
3768 return afterWrite(stream, state, count, cb);
3769 }
3770 function afterWrite(stream, state, count, cb) {
3771 const needDrain = !state.ending && !stream.destroyed &&
3772 state.length === 0 && state.needDrain;
3773 if (needDrain) {
3774 state.needDrain = false;
3775 stream.emit("drain");
3776 }
3777 while (count-- > 0) {
3778 state.pendingcb--;
3779 cb(null);
3780 }
3781 if (state.destroyed) {
3782 errorBuffer(state);
3783 }
3784 finishMaybe(stream, state);
3785 }
3786 function errorBuffer(state) {
3787 if (state.writing) {
3788 return;
3789 }
3790 for (let n = state.bufferedIndex; n < state.buffered.length; ++n) {
3791 var _state$errored;
3792 const { chunk, callback } = state.buffered[n];
3793 const len = state.objectMode ? 1 : chunk.length;
3794 state.length -= len;
3795 callback(
3796 (_state$errored = state.errored) !== null && _state$errored !== void 0
3797 ? _state$errored
3798 : new ERR_STREAM_DESTROYED("write"),
3799 );
3800 }
3801 const onfinishCallbacks = state[kOnFinished].splice(0);
3802 for (let i = 0; i < onfinishCallbacks.length; i++) {
3803 var _state$errored2;
3804 onfinishCallbacks[i](
3805 (_state$errored2 = state.errored) !== null &&
3806 _state$errored2 !== void 0
3807 ? _state$errored2
3808 : new ERR_STREAM_DESTROYED("end"),
3809 );
3810 }
3811 resetBuffer(state);
3812 }
3813 function clearBuffer(stream, state) {
3814 if (
3815 state.corked || state.bufferProcessing || state.destroyed ||
3816 !state.constructed
3817 ) {
3818 return;
3819 }
3820 const { buffered, bufferedIndex, objectMode } = state;
3821 const bufferedLength = buffered.length - bufferedIndex;
3822 if (!bufferedLength) {
3823 return;
3824 }
3825 let i = bufferedIndex;
3826 state.bufferProcessing = true;
3827 if (bufferedLength > 1 && stream._writev) {
3828 state.pendingcb -= bufferedLength - 1;
3829 const callback = state.allNoop ? nop : (err) => {
3830 for (let n = i; n < buffered.length; ++n) {
3831 buffered[n].callback(err);
3832 }
3833 };
3834 const chunks = state.allNoop && i === 0
3835 ? buffered
3836 : ArrayPrototypeSlice(buffered, i);
3837 chunks.allBuffers = state.allBuffers;
3838 doWrite(stream, state, true, state.length, chunks, "", callback);
3839 resetBuffer(state);
3840 } else {
3841 do {
3842 const { chunk, encoding, callback } = buffered[i];
3843 buffered[i++] = null;
3844 const len = objectMode ? 1 : chunk.length;
3845 doWrite(stream, state, false, len, chunk, encoding, callback);
3846 } while (i < buffered.length && !state.writing);
3847 if (i === buffered.length) {
3848 resetBuffer(state);
3849 } else if (i > 256) {
3850 buffered.splice(0, i);
3851 state.bufferedIndex = 0;
3852 } else {
3853 state.bufferedIndex = i;
3854 }
3855 }
3856 state.bufferProcessing = false;
3857 }
3858 Writable.prototype._write = function (chunk, encoding, cb) {
3859 if (this._writev) {
3860 this._writev(
3861 [
3862 {
3863 chunk,
3864 encoding,
3865 },
3866 ],
3867 cb,
3868 );
3869 } else {
3870 throw new ERR_METHOD_NOT_IMPLEMENTED("_write()");
3871 }
3872 };
3873 Writable.prototype._writev = null;
3874 Writable.prototype.end = function (chunk, encoding, cb) {
3875 const state = this._writableState;
3876 if (typeof chunk === "function") {
3877 cb = chunk;
3878 chunk = null;
3879 encoding = null;
3880 } else if (typeof encoding === "function") {
3881 cb = encoding;
3882 encoding = null;
3883 }
3884 let err;
3885 if (chunk !== null && chunk !== void 0) {
3886 const ret = _write(this, chunk, encoding);
3887 if (ret instanceof Error2) {
3888 err = ret;
3889 }
3890 }
3891 if (state.corked) {
3892 state.corked = 1;
3893 this.uncork();
3894 }
3895 if (err) {
3896 } else if (!state.errored && !state.ending) {
3897 state.ending = true;
3898 finishMaybe(this, state, true);
3899 state.ended = true;
3900 } else if (state.finished) {
3901 err = new ERR_STREAM_ALREADY_FINISHED("end");
3902 } else if (state.destroyed) {
3903 err = new ERR_STREAM_DESTROYED("end");
3904 }
3905 if (typeof cb === "function") {
3906 if (err) {
3907 process.nextTick(cb, err);
3908 } else if (state.finished) {
3909 process.nextTick(cb, null);
3910 } else {
3911 state[kOnFinished].push(cb);
3912 }
3913 }
3914 return this;
3915 };
3916 function needFinish(state) {
3917 return state.ending && !state.destroyed && state.constructed &&
3918 state.length === 0 && !state.errored && state.buffered.length === 0 &&
3919 !state.finished && !state.writing && !state.errorEmitted &&
3920 !state.closeEmitted;
3921 }
3922 function callFinal(stream, state) {
3923 let called = false;
3924 function onFinish(err) {
3925 if (called) {
3926 errorOrDestroy(
3927 stream,
3928 err !== null && err !== void 0 ? err : ERR_MULTIPLE_CALLBACK(),
3929 );
3930 return;
3931 }
3932 called = true;
3933 state.pendingcb--;
3934 if (err) {
3935 const onfinishCallbacks = state[kOnFinished].splice(0);
3936 for (let i = 0; i < onfinishCallbacks.length; i++) {
3937 onfinishCallbacks[i](err);
3938 }
3939 errorOrDestroy(stream, err, state.sync);
3940 } else if (needFinish(state)) {
3941 state.prefinished = true;
3942 stream.emit("prefinish");
3943 state.pendingcb++;
3944 process.nextTick(finish, stream, state);
3945 }
3946 }
3947 state.sync = true;
3948 state.pendingcb++;
3949 try {
3950 stream._final(onFinish);
3951 } catch (err) {
3952 onFinish(err);
3953 }
3954 state.sync = false;
3955 }
3956 function prefinish(stream, state) {
3957 if (!state.prefinished && !state.finalCalled) {
3958 if (typeof stream._final === "function" && !state.destroyed) {
3959 state.finalCalled = true;
3960 callFinal(stream, state);
3961 } else {
3962 state.prefinished = true;
3963 stream.emit("prefinish");
3964 }
3965 }
3966 }
3967 function finishMaybe(stream, state, sync) {
3968 if (needFinish(state)) {
3969 prefinish(stream, state);
3970 if (state.pendingcb === 0) {
3971 if (sync) {
3972 state.pendingcb++;
3973 process.nextTick(
3974 (stream2, state2) => {
3975 if (needFinish(state2)) {
3976 finish(stream2, state2);
3977 } else {
3978 state2.pendingcb--;
3979 }
3980 },
3981 stream,
3982 state,
3983 );
3984 } else if (needFinish(state)) {
3985 state.pendingcb++;
3986 finish(stream, state);
3987 }
3988 }
3989 }
3990 }
3991 function finish(stream, state) {
3992 state.pendingcb--;
3993 state.finished = true;
3994 const onfinishCallbacks = state[kOnFinished].splice(0);
3995 for (let i = 0; i < onfinishCallbacks.length; i++) {
3996 onfinishCallbacks[i](null);
3997 }
3998 stream.emit("finish");
3999 if (state.autoDestroy) {
4000 const rState = stream._readableState;
4001 // We don't expect the readable to ever 'end' if readable is
4002 // explicitly set to false.
4003 const autoDestroy = !rState || rState.autoDestroy &&
4004 (rState.endEmitted || rState.readable === false);
4005 if (autoDestroy) {
4006 stream.destroy();
4007 }
4008 }
4009 }
4010 ObjectDefineProperties(Writable.prototype, {
4011 closed: {
4012 __proto__: null,
4013 get() {
4014 return this._writableState ? this._writableState.closed : false;
4015 },
4016 },
4017 destroyed: {
4018 __proto__: null,
4019 get() {
4020 return this._writableState ? this._writableState.destroyed : false;
4021 },
4022 set(value) {
4023 if (this._writableState) {
4024 this._writableState.destroyed = value;
4025 }
4026 },
4027 },
4028 writable: {
4029 __proto__: null,
4030 get() {
4031 const w = this._writableState;
4032 return !!w && w.writable !== false && !w.destroyed && !w.errored &&
4033 !w.ending && !w.ended;
4034 },
4035 set(val) {
4036 if (this._writableState) {
4037 this._writableState.writable = !!val;
4038 }
4039 },
4040 },
4041 writableFinished: {
4042 __proto__: null,
4043 get() {
4044 return this._writableState ? this._writableState.finished : false;
4045 },
4046 },
4047 writableObjectMode: {
4048 __proto__: null,
4049 get() {
4050 return this._writableState ? this._writableState.objectMode : false;
4051 },
4052 },
4053 writableBuffer: {
4054 __proto__: null,
4055 get() {
4056 return this._writableState && this._writableState.getBuffer();
4057 },
4058 },
4059 writableEnded: {
4060 __proto__: null,
4061 get() {
4062 return this._writableState ? this._writableState.ending : false;
4063 },
4064 },
4065 writableNeedDrain: {
4066 __proto__: null,
4067 get() {
4068 const wState = this._writableState;
4069 if (!wState) {
4070 return false;
4071 }
4072 return !wState.destroyed && !wState.ending && wState.needDrain;
4073 },
4074 },
4075 writableHighWaterMark: {
4076 __proto__: null,
4077 get() {
4078 return this._writableState && this._writableState.highWaterMark;
4079 },
4080 },
4081 writableCorked: {
4082 __proto__: null,
4083 get() {
4084 return this._writableState ? this._writableState.corked : 0;
4085 },
4086 },
4087 writableLength: {
4088 __proto__: null,
4089 get() {
4090 return this._writableState && this._writableState.length;
4091 },
4092 },
4093 errored: {
4094 __proto__: null,
4095 enumerable: false,
4096 get() {
4097 return this._writableState ? this._writableState.errored : null;
4098 },
4099 },
4100 writableAborted: {
4101 __proto__: null,
4102 enumerable: false,
4103 get: function () {
4104 return !!(this._writableState.writable !== false &&
4105 (this._writableState.destroyed || this._writableState.errored) &&
4106 !this._writableState.finished);
4107 },
4108 },
4109 });
4110 var destroy = destroyImpl.destroy;
4111 Writable.prototype.destroy = function (err, cb) {
4112 const state = this._writableState;
4113 if (
4114 !state.destroyed &&
4115 (state.bufferedIndex < state.buffered.length ||
4116 state[kOnFinished].length)
4117 ) {
4118 process.nextTick(errorBuffer, state);
4119 }
4120 destroy.call(this, err, cb);
4121 return this;
4122 };
4123 Writable.prototype._undestroy = destroyImpl.undestroy;
4124 Writable.prototype._destroy = function (err, cb) {
4125 cb(err);
4126 };
4127 Writable.prototype[EE.captureRejectionSymbol] = function (err) {
4128 this.destroy(err);
4129 };
4130 var webStreamsAdapters;
4131 function lazyWebStreams() {
4132 if (webStreamsAdapters === void 0) {
4133 webStreamsAdapters = {};
4134 }
4135 return webStreamsAdapters;
4136 }
4137 Writable.fromWeb = function (writableStream, options) {
4138 return lazyWebStreams().newStreamWritableFromWritableStream(
4139 writableStream,
4140 options,
4141 );
4142 };
4143 Writable.toWeb = function (streamWritable) {
4144 return lazyWebStreams().newWritableStreamFromStreamWritable(
4145 streamWritable,
4146 );
4147 };
4148 },
4149});
4150
4151// lib/internal/streams/duplexify.js
4152var require_duplexify = __commonJS({
4153 "lib/internal/streams/duplexify.js"(exports, module) {
4154 var process = require_browser2();
4155 var bufferModule = require_buffer();
4156 var {
4157 isReadable,
4158 isWritable,
4159 isIterable,
4160 isNodeStream,
4161 isReadableNodeStream,
4162 isWritableNodeStream,
4163 isDuplexNodeStream,
4164 } = require_utils();
4165 var eos = require_end_of_stream();
4166 var { destroyer } = require_destroy();
4167 var Duplex = require_duplex();
4168 var Readable = require_readable();
4169 var from = require_from();
4170 var isBlob = typeof Blob !== "undefined"
4171 ? function isBlob2(b) {
4172 return b instanceof Blob;
4173 }
4174 : function isBlob2(b) {
4175 return false;
4176 };
4177 var { FunctionPrototypeCall } = require_primordials();
4178 var Duplexify = class extends Duplex {
4179 constructor(options) {
4180 super(options);
4181 if (
4182 (options === null || options === void 0
4183 ? void 0
4184 : options.readable) === false
4185 ) {
4186 this._readableState.readable = false;
4187 this._readableState.ended = true;
4188 this._readableState.endEmitted = true;
4189 }
4190 if (
4191 (options === null || options === void 0
4192 ? void 0
4193 : options.writable) === false
4194 ) {
4195 this._writableState.writable = false;
4196 this._writableState.ending = true;
4197 this._writableState.ended = true;
4198 this._writableState.finished = true;
4199 }
4200 }
4201 };
4202 module.exports = function duplexify(body, name) {
4203 if (isDuplexNodeStream(body)) {
4204 return body;
4205 }
4206 if (isReadableNodeStream(body)) {
4207 return _duplexify({
4208 readable: body,
4209 });
4210 }
4211 if (isWritableNodeStream(body)) {
4212 return _duplexify({
4213 writable: body,
4214 });
4215 }
4216 if (isNodeStream(body)) {
4217 return _duplexify({
4218 writable: false,
4219 readable: false,
4220 });
4221 }
4222
4223 if (typeof body === "function") {
4224 const { value, write, final, destroy } = fromAsyncGen(body);
4225 if (isIterable(value)) {
4226 return from(Duplexify, value, {
4227 // TODO (ronag): highWaterMark?
4228 objectMode: true,
4229 write,
4230 final,
4231 destroy,
4232 });
4233 }
4234 const then2 = value === null || value === void 0 ? void 0 : value.then;
4235 if (typeof then2 === "function") {
4236 let d;
4237 const promise = FunctionPrototypeCall(
4238 then2,
4239 value,
4240 (val) => {
4241 if (val != null) {
4242 throw new ERR_INVALID_RETURN_VALUE("nully", "body", val);
4243 }
4244 },
4245 (err) => {
4246 destroyer(d, err);
4247 },
4248 );
4249 return d = new Duplexify({
4250 // TODO (ronag): highWaterMark?
4251 objectMode: true,
4252 readable: false,
4253 write,
4254 final(cb) {
4255 final(async () => {
4256 try {
4257 await promise;
4258 process.nextTick(cb, null);
4259 } catch (err) {
4260 process.nextTick(cb, err);
4261 }
4262 });
4263 },
4264 destroy,
4265 });
4266 }
4267 throw new ERR_INVALID_RETURN_VALUE(
4268 "Iterable, AsyncIterable or AsyncFunction",
4269 name,
4270 value,
4271 );
4272 }
4273 if (isBlob(body)) {
4274 return duplexify(body.arrayBuffer());
4275 }
4276 if (isIterable(body)) {
4277 return from(Duplexify, body, {
4278 // TODO (ronag): highWaterMark?
4279 objectMode: true,
4280 writable: false,
4281 });
4282 }
4283 if (
4284 typeof (body === null || body === void 0 ? void 0 : body.writable) ===
4285 "object" ||
4286 typeof (body === null || body === void 0 ? void 0 : body.readable) ===
4287 "object"
4288 ) {
4289 const readable = body !== null && body !== void 0 && body.readable
4290 ? isReadableNodeStream(
4291 body === null || body === void 0 ? void 0 : body.readable,
4292 )
4293 ? body === null || body === void 0 ? void 0 : body.readable
4294 : duplexify(body.readable)
4295 : void 0;
4296 const writable = body !== null && body !== void 0 && body.writable
4297 ? isWritableNodeStream(
4298 body === null || body === void 0 ? void 0 : body.writable,
4299 )
4300 ? body === null || body === void 0 ? void 0 : body.writable
4301 : duplexify(body.writable)
4302 : void 0;
4303 return _duplexify({
4304 readable,
4305 writable,
4306 });
4307 }
4308 const then = body === null || body === void 0 ? void 0 : body.then;
4309 if (typeof then === "function") {
4310 let d;
4311 FunctionPrototypeCall(
4312 then,
4313 body,
4314 (val) => {
4315 if (val != null) {
4316 d.push(val);
4317 }
4318 d.push(null);
4319 },
4320 (err) => {
4321 destroyer(d, err);
4322 },
4323 );
4324 return d = new Duplexify({
4325 objectMode: true,
4326 writable: false,
4327 read() {
4328 },
4329 });
4330 }
4331 throw new ERR_INVALID_ARG_TYPE(
4332 name,
4333 [
4334 "Blob",
4335 "ReadableStream",
4336 "WritableStream",
4337 "Stream",
4338 "Iterable",
4339 "AsyncIterable",
4340 "Function",
4341 "{ readable, writable } pair",
4342 "Promise",
4343 ],
4344 body,
4345 );
4346 };
4347 function fromAsyncGen(fn) {
4348 let { promise, resolve } = createDeferredPromise();
4349 const ac = new AbortController();
4350 const signal = ac.signal;
4351 const value = fn(
4352 async function* () {
4353 while (true) {
4354 const _promise = promise;
4355 promise = null;
4356 const { chunk, done, cb } = await _promise;
4357 process.nextTick(cb);
4358 if (done) {
4359 return;
4360 }
4361 if (signal.aborted) {
4362 throw new AbortError(void 0, {
4363 cause: signal.reason,
4364 });
4365 }
4366 ({ promise, resolve } = createDeferredPromise());
4367 yield chunk;
4368 }
4369 }(),
4370 {
4371 signal,
4372 },
4373 );
4374 return {
4375 value,
4376 write(chunk, encoding, cb) {
4377 const _resolve = resolve;
4378 resolve = null;
4379 _resolve({
4380 chunk,
4381 done: false,
4382 cb,
4383 });
4384 },
4385 final(cb) {
4386 const _resolve = resolve;
4387 resolve = null;
4388 _resolve({
4389 done: true,
4390 cb,
4391 });
4392 },
4393 destroy(err, cb) {
4394 ac.abort();
4395 cb(err);
4396 },
4397 };
4398 }
4399 function _duplexify(pair) {
4400 const r = pair.readable && typeof pair.readable.read !== "function"
4401 ? Readable.wrap(pair.readable)
4402 : pair.readable;
4403 const w = pair.writable;
4404 let readable = !!isReadable(r);
4405 let writable = !!isWritable(w);
4406 let ondrain;
4407 let onfinish;
4408 let onreadable;
4409 let onclose;
4410 let d;
4411 function onfinished(err) {
4412 const cb = onclose;
4413 onclose = null;
4414 if (cb) {
4415 cb(err);
4416 } else if (err) {
4417 d.destroy(err);
4418 }
4419 }
4420 d = new Duplexify({
4421 // TODO (ronag): highWaterMark?
4422 readableObjectMode:
4423 !!(r !== null && r !== void 0 && r.readableObjectMode),
4424 writableObjectMode:
4425 !!(w !== null && w !== void 0 && w.writableObjectMode),
4426 readable,
4427 writable,
4428 });
4429 if (writable) {
4430 eos(w, (err) => {
4431 writable = false;
4432 if (err) {
4433 destroyer(r, err);
4434 }
4435 onfinished(err);
4436 });
4437 d._write = function (chunk, encoding, callback) {
4438 if (w.write(chunk, encoding)) {
4439 callback();
4440 } else {
4441 ondrain = callback;
4442 }
4443 };
4444 d._final = function (callback) {
4445 w.end();
4446 onfinish = callback;
4447 };
4448 w.on("drain", function () {
4449 if (ondrain) {
4450 const cb = ondrain;
4451 ondrain = null;
4452 cb();
4453 }
4454 });
4455 w.on("finish", function () {
4456 if (onfinish) {
4457 const cb = onfinish;
4458 onfinish = null;
4459 cb();
4460 }
4461 });
4462 }
4463 if (readable) {
4464 eos(r, (err) => {
4465 readable = false;
4466 if (err) {
4467 destroyer(r, err);
4468 }
4469 onfinished(err);
4470 });
4471 r.on("readable", function () {
4472 if (onreadable) {
4473 const cb = onreadable;
4474 onreadable = null;
4475 cb();
4476 }
4477 });
4478 r.on("end", function () {
4479 d.push(null);
4480 });
4481 d._read = function () {
4482 while (true) {
4483 const buf = r.read();
4484 if (buf === null) {
4485 onreadable = d._read;
4486 return;
4487 }
4488 if (!d.push(buf)) {
4489 return;
4490 }
4491 }
4492 };
4493 }
4494 d._destroy = function (err, callback) {
4495 if (!err && onclose !== null) {
4496 err = new AbortError();
4497 }
4498 onreadable = null;
4499 ondrain = null;
4500 onfinish = null;
4501 if (onclose === null) {
4502 callback(err);
4503 } else {
4504 onclose = callback;
4505 destroyer(w, err);
4506 destroyer(r, err);
4507 }
4508 };
4509 return d;
4510 }
4511 },
4512});
4513
4514// lib/internal/streams/duplex.js
4515var require_duplex = __commonJS({
4516 "lib/internal/streams/duplex.js"(exports, module) {
4517 "use strict";
4518 var {
4519 ObjectDefineProperties,
4520 ObjectGetOwnPropertyDescriptor,
4521 ObjectKeys,
4522 ObjectSetPrototypeOf,
4523 } = require_primordials();
4524 module.exports = Duplex;
4525 var Readable = require_readable();
4526 var Writable = require_writable();
4527 ObjectSetPrototypeOf(Duplex.prototype, Readable.prototype);
4528 ObjectSetPrototypeOf(Duplex, Readable);
4529 {
4530 const keys = ObjectKeys(Writable.prototype);
4531 for (let i = 0; i < keys.length; i++) {
4532 const method = keys[i];
4533 if (!Duplex.prototype[method]) {
4534 Duplex.prototype[method] = Writable.prototype[method];
4535 }
4536 }
4537 }
4538 // Cells fix, matching Workerd's streams_duplex: the loop above keeps
4539 // Readable's bare destroyImpl.destroy, so a destroyed Duplex would
4540 // never error buffered write callbacks. Writable's override does.
4541 Duplex.prototype.destroy = Writable.prototype.destroy;
4542 function Duplex(options) {
4543 if (!(this instanceof Duplex)) {
4544 return new Duplex(options);
4545 }
4546 Readable.call(this, options);
4547 Writable.call(this, options);
4548 if (options) {
4549 this.allowHalfOpen = options.allowHalfOpen !== false;
4550 if (options.readable === false) {
4551 this._readableState.readable = false;
4552 this._readableState.ended = true;
4553 this._readableState.endEmitted = true;
4554 }
4555 if (options.writable === false) {
4556 this._writableState.writable = false;
4557 this._writableState.ending = true;
4558 this._writableState.ended = true;
4559 this._writableState.finished = true;
4560 }
4561 } else {
4562 this.allowHalfOpen = true;
4563 }
4564 }
4565 ObjectDefineProperties(Duplex.prototype, {
4566 writable: {
4567 __proto__: null,
4568 ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writable"),
4569 },
4570 writableHighWaterMark: {
4571 __proto__: null,
4572 ...ObjectGetOwnPropertyDescriptor(
4573 Writable.prototype,
4574 "writableHighWaterMark",
4575 ),
4576 },
4577 writableObjectMode: {
4578 __proto__: null,
4579 ...ObjectGetOwnPropertyDescriptor(
4580 Writable.prototype,
4581 "writableObjectMode",
4582 ),
4583 },
4584 writableBuffer: {
4585 __proto__: null,
4586 ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableBuffer"),
4587 },
4588 writableLength: {
4589 __proto__: null,
4590 ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableLength"),
4591 },
4592 writableFinished: {
4593 __proto__: null,
4594 ...ObjectGetOwnPropertyDescriptor(
4595 Writable.prototype,
4596 "writableFinished",
4597 ),
4598 },
4599 writableCorked: {
4600 __proto__: null,
4601 ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableCorked"),
4602 },
4603 writableEnded: {
4604 __proto__: null,
4605 ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableEnded"),
4606 },
4607 writableNeedDrain: {
4608 __proto__: null,
4609 ...ObjectGetOwnPropertyDescriptor(
4610 Writable.prototype,
4611 "writableNeedDrain",
4612 ),
4613 },
4614 destroyed: {
4615 __proto__: null,
4616 get() {
4617 if (
4618 this._readableState === void 0 || this._writableState === void 0
4619 ) {
4620 return false;
4621 }
4622 return this._readableState.destroyed && this._writableState.destroyed;
4623 },
4624 set(value) {
4625 if (this._readableState && this._writableState) {
4626 this._readableState.destroyed = value;
4627 this._writableState.destroyed = value;
4628 }
4629 },
4630 },
4631 });
4632 var webStreamsAdapters;
4633 function lazyWebStreams() {
4634 if (webStreamsAdapters === void 0) {
4635 webStreamsAdapters = {};
4636 }
4637 return webStreamsAdapters;
4638 }
4639 Duplex.fromWeb = function (pair, options) {
4640 return lazyWebStreams().newStreamDuplexFromReadableWritablePair(
4641 pair,
4642 options,
4643 );
4644 };
4645 Duplex.toWeb = function (duplex) {
4646 return lazyWebStreams().newReadableWritablePairFromDuplex(duplex);
4647 };
4648 var duplexify;
4649 Duplex.from = function (body) {
4650 if (!duplexify) {
4651 duplexify = require_duplexify();
4652 }
4653 return duplexify(body, "body");
4654 };
4655 },
4656});
4657
4658// lib/internal/streams/transform.js
4659var require_transform = __commonJS({
4660 "lib/internal/streams/transform.js"(exports, module) {
4661 "use strict";
4662 var { ObjectSetPrototypeOf, Symbol: Symbol2 } = require_primordials();
4663 module.exports = Transform;
4664 var Duplex = require_duplex();
4665 var { getHighWaterMark } = require_state();
4666 ObjectSetPrototypeOf(Transform.prototype, Duplex.prototype);
4667 ObjectSetPrototypeOf(Transform, Duplex);
4668 var kCallback = Symbol2("kCallback");
4669 function Transform(options) {
4670 if (!(this instanceof Transform)) {
4671 return new Transform(options);
4672 }
4673 const readableHighWaterMark = options
4674 ? getHighWaterMark(this, options, "readableHighWaterMark", true)
4675 : null;
4676 if (readableHighWaterMark === 0) {
4677 options = {
4678 ...options,
4679 highWaterMark: null,
4680 readableHighWaterMark,
4681 // TODO (ronag): 0 is not optimal since we have
4682 // a "bug" where we check needDrain before calling _write and
4683 // not after.
4684 // Refs: https://github.com/nodejs/node/pull/32887
4685 // Refs: https://github.com/nodejs/node/pull/35941
4686 writableHighWaterMark: options.writableHighWaterMark || 0,
4687 };
4688 }
4689 Duplex.call(this, options);
4690 this._readableState.sync = false;
4691 this[kCallback] = null;
4692 if (options) {
4693 if (typeof options.transform === "function") {
4694 this._transform = options.transform;
4695 }
4696 if (typeof options.flush === "function") {
4697 this._flush = options.flush;
4698 }
4699 }
4700 this.on("prefinish", prefinish);
4701 }
4702 function final(cb) {
4703 if (typeof this._flush === "function" && !this.destroyed) {
4704 this._flush((er, data) => {
4705 if (er) {
4706 if (cb) {
4707 cb(er);
4708 } else {
4709 this.destroy(er);
4710 }
4711 return;
4712 }
4713 if (data != null) {
4714 this.push(data);
4715 }
4716 this.push(null);
4717 if (cb) {
4718 cb();
4719 }
4720 });
4721 } else {
4722 this.push(null);
4723 if (cb) {
4724 cb();
4725 }
4726 }
4727 }
4728 function prefinish() {
4729 if (this._final !== final) {
4730 final.call(this);
4731 }
4732 }
4733 Transform.prototype._final = final;
4734 Transform.prototype._transform = function (chunk, encoding, callback) {
4735 throw new ERR_METHOD_NOT_IMPLEMENTED("_transform()");
4736 };
4737 Transform.prototype._write = function (chunk, encoding, callback) {
4738 const rState = this._readableState;
4739 const wState = this._writableState;
4740 const length = rState.length;
4741 this._transform(chunk, encoding, (err, val) => {
4742 if (err) {
4743 callback(err);
4744 return;
4745 }
4746 if (val != null) {
4747 this.push(val);
4748 }
4749 if (
4750 wState.ended || // Backwards compat.
4751 length === rState.length || // Backwards compat.
4752 rState.length < rState.highWaterMark
4753 ) {
4754 callback();
4755 } else {
4756 this[kCallback] = callback;
4757 }
4758 });
4759 };
4760 Transform.prototype._read = function () {
4761 if (this[kCallback]) {
4762 const callback = this[kCallback];
4763 this[kCallback] = null;
4764 callback();
4765 }
4766 };
4767 },
4768});
4769
4770// lib/internal/streams/passthrough.js
4771var require_passthrough = __commonJS({
4772 "lib/internal/streams/passthrough.js"(exports, module) {
4773 "use strict";
4774 var { ObjectSetPrototypeOf } = require_primordials();
4775 module.exports = PassThrough;
4776 var Transform = require_transform();
4777 ObjectSetPrototypeOf(PassThrough.prototype, Transform.prototype);
4778 ObjectSetPrototypeOf(PassThrough, Transform);
4779 function PassThrough(options) {
4780 if (!(this instanceof PassThrough)) {
4781 return new PassThrough(options);
4782 }
4783 Transform.call(this, options);
4784 }
4785 PassThrough.prototype._transform = function (chunk, encoding, cb) {
4786 cb(null, chunk);
4787 };
4788 },
4789});
4790
4791// lib/internal/streams/pipeline.js
4792var require_pipeline = __commonJS({
4793 "lib/internal/streams/pipeline.js"(exports, module) {
4794 var process = require_browser2();
4795 var { ArrayIsArray, Promise: Promise2, SymbolAsyncIterator } =
4796 require_primordials();
4797 var eos = require_end_of_stream();
4798 var destroyImpl = require_destroy();
4799 var Duplex = require_duplex();
4800 var { validateFunction, validateAbortSignal } = require_validators();
4801 var { isIterable, isReadable, isReadableNodeStream, isNodeStream } =
4802 require_utils();
4803 var PassThrough;
4804 var Readable;
4805 function destroyer(stream, reading, writing) {
4806 let finished = false;
4807 stream.on("close", () => {
4808 finished = true;
4809 });
4810 const cleanup = eos(
4811 stream,
4812 {
4813 readable: reading,
4814 writable: writing,
4815 },
4816 (err) => {
4817 finished = !err;
4818 },
4819 );
4820 return {
4821 destroy: (err) => {
4822 if (finished) {
4823 return;
4824 }
4825 finished = true;
4826 destroyImpl.destroyer(
4827 stream,
4828 err || new ERR_STREAM_DESTROYED("pipe"),
4829 );
4830 },
4831 cleanup,
4832 };
4833 }
4834 function popCallback(streams) {
4835 validateFunction(
4836 streams[streams.length - 1],
4837 "streams[stream.length - 1]",
4838 );
4839 return streams.pop();
4840 }
4841 function makeAsyncIterable(val) {
4842 if (isIterable(val)) {
4843 return val;
4844 } else if (isReadableNodeStream(val)) {
4845 return fromReadable(val);
4846 }
4847 throw new ERR_INVALID_ARG_TYPE("val", [
4848 "Readable",
4849 "Iterable",
4850 "AsyncIterable",
4851 ], val);
4852 }
4853 async function* fromReadable(val) {
4854 if (!Readable) {
4855 Readable = require_readable();
4856 }
4857 yield* Readable.prototype[SymbolAsyncIterator].call(val);
4858 }
4859 async function pump(iterable, writable, finish, { end }) {
4860 let error;
4861 let onresolve = null;
4862 const resume = (err) => {
4863 if (err) {
4864 error = err;
4865 }
4866 if (onresolve) {
4867 const callback = onresolve;
4868 onresolve = null;
4869 callback();
4870 }
4871 };
4872 const wait = () =>
4873 new Promise2((resolve, reject) => {
4874 if (error) {
4875 reject(error);
4876 } else {
4877 onresolve = () => {
4878 if (error) {
4879 reject(error);
4880 } else {
4881 resolve();
4882 }
4883 };
4884 }
4885 });
4886 writable.on("drain", resume);
4887 const cleanup = eos(
4888 writable,
4889 {
4890 readable: false,
4891 },
4892 resume,
4893 );
4894 try {
4895 if (writable.writableNeedDrain) {
4896 await wait();
4897 }
4898 for await (const chunk of iterable) {
4899 if (!writable.write(chunk)) {
4900 await wait();
4901 }
4902 }
4903 if (end) {
4904 writable.end();
4905 }
4906 await wait();
4907 finish();
4908 } catch (err) {
4909 finish(error !== err ? aggregateTwoErrors(error, err) : err);
4910 } finally {
4911 cleanup();
4912 writable.off("drain", resume);
4913 }
4914 }
4915 function pipeline(...streams) {
4916 return pipelineImpl(streams, once(popCallback(streams)));
4917 }
4918 function pipelineImpl(streams, callback, opts) {
4919 if (streams.length === 1 && ArrayIsArray(streams[0])) {
4920 streams = streams[0];
4921 }
4922 if (streams.length < 2) {
4923 throw new ERR_MISSING_ARGS("streams");
4924 }
4925 const ac = new AbortController();
4926 const signal = ac.signal;
4927 const outerSignal = opts === null || opts === void 0
4928 ? void 0
4929 : opts.signal;
4930 const lastStreamCleanup = [];
4931 validateAbortSignal(outerSignal, "options.signal");
4932 function abort() {
4933 finishImpl(new AbortError());
4934 }
4935 outerSignal === null || outerSignal === void 0
4936 ? void 0
4937 : outerSignal.addEventListener("abort", abort);
4938 let error;
4939 let value;
4940 const destroys = [];
4941 let finishCount = 0;
4942 function finish(err) {
4943 finishImpl(err, --finishCount === 0);
4944 }
4945 function finishImpl(err, final) {
4946 if (err && (!error || error.code === "ERR_STREAM_PREMATURE_CLOSE")) {
4947 error = err;
4948 }
4949 if (!error && !final) {
4950 return;
4951 }
4952 while (destroys.length) {
4953 destroys.shift()(error);
4954 }
4955 outerSignal === null || outerSignal === void 0
4956 ? void 0
4957 : outerSignal.removeEventListener("abort", abort);
4958 ac.abort();
4959 if (final) {
4960 if (!error) {
4961 lastStreamCleanup.forEach((fn) => fn());
4962 }
4963 process.nextTick(callback, error, value);
4964 }
4965 }
4966 let ret;
4967 for (let i = 0; i < streams.length; i++) {
4968 const stream = streams[i];
4969 const reading = i < streams.length - 1;
4970 const writing = i > 0;
4971 const end = reading ||
4972 (opts === null || opts === void 0 ? void 0 : opts.end) !== false;
4973 const isLastStream = i === streams.length - 1;
4974 if (isNodeStream(stream)) {
4975 let onError2 = function (err) {
4976 if (
4977 err && err.name !== "AbortError" &&
4978 err.code !== "ERR_STREAM_PREMATURE_CLOSE"
4979 ) {
4980 finish(err);
4981 }
4982 };
4983 var onError = onError2;
4984 if (end) {
4985 const { destroy, cleanup } = destroyer(stream, reading, writing);
4986 destroys.push(destroy);
4987 if (isReadable(stream) && isLastStream) {
4988 lastStreamCleanup.push(cleanup);
4989 }
4990 }
4991 stream.on("error", onError2);
4992 if (isReadable(stream) && isLastStream) {
4993 lastStreamCleanup.push(() => {
4994 stream.removeListener("error", onError2);
4995 });
4996 }
4997 }
4998 if (i === 0) {
4999 if (typeof stream === "function") {
5000 ret = stream({
5001 signal,
5002 });
5003 if (!isIterable(ret)) {
5004 throw new ERR_INVALID_RETURN_VALUE(
5005 "Iterable, AsyncIterable or Stream",
5006 "source",
5007 ret,
5008 );
5009 }
5010 } else if (isIterable(stream) || isReadableNodeStream(stream)) {
5011 ret = stream;
5012 } else {
5013 ret = Duplex.from(stream);
5014 }
5015 } else if (typeof stream === "function") {
5016 ret = makeAsyncIterable(ret);
5017 ret = stream(ret, {
5018 signal,
5019 });
5020 if (reading) {
5021 if (!isIterable(ret, true)) {
5022 throw new ERR_INVALID_RETURN_VALUE(
5023 "AsyncIterable",
5024 `transform[${i - 1}]`,
5025 ret,
5026 );
5027 }
5028 } else {
5029 var _ret;
5030 if (!PassThrough) {
5031 PassThrough = require_passthrough();
5032 }
5033 const pt = new PassThrough({
5034 objectMode: true,
5035 });
5036 const then = (_ret = ret) === null || _ret === void 0
5037 ? void 0
5038 : _ret.then;
5039 if (typeof then === "function") {
5040 finishCount++;
5041 then.call(
5042 ret,
5043 (val) => {
5044 value = val;
5045 if (val != null) {
5046 pt.write(val);
5047 }
5048 if (end) {
5049 pt.end();
5050 }
5051 process.nextTick(finish);
5052 },
5053 (err) => {
5054 pt.destroy(err);
5055 process.nextTick(finish, err);
5056 },
5057 );
5058 } else if (isIterable(ret, true)) {
5059 finishCount++;
5060 pump(ret, pt, finish, {
5061 end,
5062 });
5063 } else {
5064 throw new ERR_INVALID_RETURN_VALUE(
5065 "AsyncIterable or Promise",
5066 "destination",
5067 ret,
5068 );
5069 }
5070 ret = pt;
5071 const { destroy, cleanup } = destroyer(ret, false, true);
5072 destroys.push(destroy);
5073 if (isLastStream) {
5074 lastStreamCleanup.push(cleanup);
5075 }
5076 }
5077 } else if (isNodeStream(stream)) {
5078 if (isReadableNodeStream(ret)) {
5079 finishCount += 2;
5080 const cleanup = pipe(ret, stream, finish, {
5081 end,
5082 });
5083 if (isReadable(stream) && isLastStream) {
5084 lastStreamCleanup.push(cleanup);
5085 }
5086 } else if (isIterable(ret)) {
5087 finishCount++;
5088 pump(ret, stream, finish, {
5089 end,
5090 });
5091 } else {
5092 throw new ERR_INVALID_ARG_TYPE("val", [
5093 "Readable",
5094 "Iterable",
5095 "AsyncIterable",
5096 ], ret);
5097 }
5098 ret = stream;
5099 } else {
5100 ret = Duplex.from(stream);
5101 }
5102 }
5103 if (
5104 signal !== null && signal !== void 0 && signal.aborted ||
5105 outerSignal !== null && outerSignal !== void 0 && outerSignal.aborted
5106 ) {
5107 process.nextTick(abort);
5108 }
5109 return ret;
5110 }
5111 function pipe(src, dst, finish, { end }) {
5112 let ended = false;
5113 dst.on("close", () => {
5114 if (!ended) {
5115 finish(new ERR_STREAM_PREMATURE_CLOSE());
5116 }
5117 });
5118 src.pipe(dst, {
5119 end,
5120 });
5121 if (end) {
5122 src.once("end", () => {
5123 ended = true;
5124 dst.end();
5125 });
5126 } else {
5127 finish();
5128 }
5129 eos(
5130 src,
5131 {
5132 readable: true,
5133 writable: false,
5134 },
5135 (err) => {
5136 const rState = src._readableState;
5137 if (
5138 err && err.code === "ERR_STREAM_PREMATURE_CLOSE" && rState &&
5139 rState.ended && !rState.errored && !rState.errorEmitted
5140 ) {
5141 src.once("end", finish).once("error", finish);
5142 } else {
5143 finish(err);
5144 }
5145 },
5146 );
5147 return eos(
5148 dst,
5149 {
5150 readable: false,
5151 writable: true,
5152 },
5153 finish,
5154 );
5155 }
5156 module.exports = {
5157 pipelineImpl,
5158 pipeline,
5159 };
5160 },
5161});
5162
5163// lib/internal/streams/compose.js
5164var require_compose = __commonJS({
5165 "lib/internal/streams/compose.js"(exports, module) {
5166 "use strict";
5167 var { pipeline } = require_pipeline();
5168 var Duplex = require_duplex();
5169 var { destroyer } = require_destroy();
5170 var { isNodeStream, isReadable, isWritable } = require_utils();
5171 module.exports = function compose(...streams) {
5172 if (streams.length === 0) {
5173 throw new ERR_MISSING_ARGS("streams");
5174 }
5175 if (streams.length === 1) {
5176 return Duplex.from(streams[0]);
5177 }
5178 const orgStreams = [...streams];
5179 if (typeof streams[0] === "function") {
5180 streams[0] = Duplex.from(streams[0]);
5181 }
5182 if (typeof streams[streams.length - 1] === "function") {
5183 const idx = streams.length - 1;
5184 streams[idx] = Duplex.from(streams[idx]);
5185 }
5186 for (let n = 0; n < streams.length; ++n) {
5187 if (!isNodeStream(streams[n])) {
5188 continue;
5189 }
5190 if (n < streams.length - 1 && !isReadable(streams[n])) {
5191 throw new ERR_INVALID_ARG_VALUE(
5192 `streams[${n}]`,
5193 orgStreams[n],
5194 "must be readable",
5195 );
5196 }
5197 if (n > 0 && !isWritable(streams[n])) {
5198 throw new ERR_INVALID_ARG_VALUE(
5199 `streams[${n}]`,
5200 orgStreams[n],
5201 "must be writable",
5202 );
5203 }
5204 }
5205 let ondrain;
5206 let onfinish;
5207 let onreadable;
5208 let onclose;
5209 let d;
5210 function onfinished(err) {
5211 const cb = onclose;
5212 onclose = null;
5213 if (cb) {
5214 cb(err);
5215 } else if (err) {
5216 d.destroy(err);
5217 } else if (!readable && !writable) {
5218 d.destroy();
5219 }
5220 }
5221 const head = streams[0];
5222 const tail = pipeline(streams, onfinished);
5223 const writable = !!isWritable(head);
5224 const readable = !!isReadable(tail);
5225 d = new Duplex({
5226 // TODO (ronag): highWaterMark?
5227 writableObjectMode:
5228 !!(head !== null && head !== void 0 && head.writableObjectMode),
5229 readableObjectMode:
5230 !!(tail !== null && tail !== void 0 && tail.writableObjectMode),
5231 writable,
5232 readable,
5233 });
5234 if (writable) {
5235 d._write = function (chunk, encoding, callback) {
5236 if (head.write(chunk, encoding)) {
5237 callback();
5238 } else {
5239 ondrain = callback;
5240 }
5241 };
5242 d._final = function (callback) {
5243 head.end();
5244 onfinish = callback;
5245 };
5246 head.on("drain", function () {
5247 if (ondrain) {
5248 const cb = ondrain;
5249 ondrain = null;
5250 cb();
5251 }
5252 });
5253 tail.on("finish", function () {
5254 if (onfinish) {
5255 const cb = onfinish;
5256 onfinish = null;
5257 cb();
5258 }
5259 });
5260 }
5261 if (readable) {
5262 tail.on("readable", function () {
5263 if (onreadable) {
5264 const cb = onreadable;
5265 onreadable = null;
5266 cb();
5267 }
5268 });
5269 tail.on("end", function () {
5270 d.push(null);
5271 });
5272 d._read = function () {
5273 while (true) {
5274 const buf = tail.read();
5275 if (buf === null) {
5276 onreadable = d._read;
5277 return;
5278 }
5279 if (!d.push(buf)) {
5280 return;
5281 }
5282 }
5283 };
5284 }
5285 d._destroy = function (err, callback) {
5286 if (!err && onclose !== null) {
5287 err = new AbortError();
5288 }
5289 onreadable = null;
5290 ondrain = null;
5291 onfinish = null;
5292 if (onclose === null) {
5293 callback(err);
5294 } else {
5295 onclose = callback;
5296 destroyer(tail, err);
5297 }
5298 };
5299 return d;
5300 };
5301 },
5302});
5303
5304// lib/stream/promises.js
5305var require_promises = __commonJS({
5306 "lib/stream/promises.js"(exports, module) {
5307 "use strict";
5308 var { ArrayPrototypePop, Promise: Promise2 } = require_primordials();
5309 var { isIterable, isNodeStream } = require_utils();
5310 var { pipelineImpl: pl } = require_pipeline();
5311 var { finished } = require_end_of_stream();
5312 function pipeline(...streams) {
5313 return new Promise2((resolve, reject) => {
5314 let signal;
5315 let end;
5316 const lastArg = streams[streams.length - 1];
5317 if (
5318 lastArg && typeof lastArg === "object" && !isNodeStream(lastArg) &&
5319 !isIterable(lastArg)
5320 ) {
5321 const options = ArrayPrototypePop(streams);
5322 signal = options.signal;
5323 end = options.end;
5324 }
5325 pl(
5326 streams,
5327 (err, value) => {
5328 if (err) {
5329 reject(err);
5330 } else {
5331 resolve(value);
5332 }
5333 },
5334 {
5335 signal,
5336 end,
5337 },
5338 );
5339 });
5340 }
5341 module.exports = {
5342 finished,
5343 pipeline,
5344 };
5345 },
5346});
5347
5348// lib/stream.js
5349var require_stream = __commonJS({
5350 "lib/stream.js"(exports, module) {
5351 var { Buffer: Buffer2 } = require_buffer();
5352 var { ObjectDefineProperty, ObjectKeys, ReflectApply } =
5353 require_primordials();
5354 var { streamReturningOperators, promiseReturningOperators } =
5355 require_operators();
5356 var compose = require_compose();
5357 var { pipeline } = require_pipeline();
5358 var { destroyer } = require_destroy();
5359 var eos = require_end_of_stream();
5360 var promises = require_promises();
5361 var utils = require_utils();
5362 var Stream = module.exports = require_legacy().Stream;
5363 Stream.isDisturbed = utils.isDisturbed;
5364 Stream.isErrored = utils.isErrored;
5365 Stream.isReadable = utils.isReadable;
5366 Stream.Readable = require_readable();
5367 for (const key of ObjectKeys(streamReturningOperators)) {
5368 let fn2 = function (...args) {
5369 if (new.target) {
5370 throw ERR_ILLEGAL_CONSTRUCTOR();
5371 }
5372 return Stream.Readable.from(ReflectApply(op, this, args));
5373 };
5374 fn = fn2;
5375 const op = streamReturningOperators[key];
5376 ObjectDefineProperty(fn2, "name", {
5377 __proto__: null,
5378 value: op.name,
5379 });
5380 ObjectDefineProperty(fn2, "length", {
5381 __proto__: null,
5382 value: op.length,
5383 });
5384 ObjectDefineProperty(Stream.Readable.prototype, key, {
5385 __proto__: null,
5386 value: fn2,
5387 enumerable: false,
5388 configurable: true,
5389 writable: true,
5390 });
5391 }
5392 var fn;
5393 for (const key of ObjectKeys(promiseReturningOperators)) {
5394 let fn2 = function (...args) {
5395 if (new.target) {
5396 throw ERR_ILLEGAL_CONSTRUCTOR();
5397 }
5398 return ReflectApply(op, this, args);
5399 };
5400 fn = fn2;
5401 const op = promiseReturningOperators[key];
5402 ObjectDefineProperty(fn2, "name", {
5403 __proto__: null,
5404 value: op.name,
5405 });
5406 ObjectDefineProperty(fn2, "length", {
5407 __proto__: null,
5408 value: op.length,
5409 });
5410 ObjectDefineProperty(Stream.Readable.prototype, key, {
5411 __proto__: null,
5412 value: fn2,
5413 enumerable: false,
5414 configurable: true,
5415 writable: true,
5416 });
5417 }
5418 var fn;
5419 Stream.Writable = require_writable();
5420 Stream.Duplex = require_duplex();
5421 Stream.Transform = require_transform();
5422 Stream.PassThrough = require_passthrough();
5423 Stream.pipeline = pipeline;
5424 var { addAbortSignal } = require_add_abort_signal();
5425 Stream.addAbortSignal = addAbortSignal;
5426 Stream.finished = eos;
5427 Stream.destroy = destroyer;
5428 Stream.compose = compose;
5429 ObjectDefineProperty(Stream, "promises", {
5430 __proto__: null,
5431 configurable: true,
5432 enumerable: true,
5433 get() {
5434 return promises;
5435 },
5436 });
5437 ObjectDefineProperty(pipeline, promisify, {
5438 __proto__: null,
5439 enumerable: true,
5440 get() {
5441 return promises.pipeline;
5442 },
5443 });
5444 ObjectDefineProperty(eos, promisify, {
5445 __proto__: null,
5446 enumerable: true,
5447 get() {
5448 return promises.finished;
5449 },
5450 });
5451 Stream.Stream = Stream;
5452 Stream._isUint8Array = function isUint8Array(value) {
5453 return value instanceof Uint8Array;
5454 };
5455 Stream._uint8ArrayToBuffer = function _uint8ArrayToBuffer(chunk) {
5456 return Buffer2.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
5457 };
5458 Stream._isArrayBufferView = isArrayBufferView;
5459 },
5460});
5461 /* End esm.sh bundle */
5462
5463 const Stream = require_stream();
5464
5465 // stream/web: the global web-stream classes, behind getters so importing
5466 // node:stream alone does not materialize the lazy byte-stream/compression
5467 // globals.
5468 const web = {};
5469 for (const name of [
5470 "ReadableStream", "ReadableStreamDefaultReader",
5471 "ReadableStreamBYOBReader", "ReadableStreamBYOBRequest",
5472 "ReadableByteStreamController", "ReadableStreamDefaultController",
5473 "TransformStream", "TransformStreamDefaultController",
5474 "WritableStream", "WritableStreamDefaultWriter",
5475 "WritableStreamDefaultController", "ByteLengthQueuingStrategy",
5476 "CountQueuingStrategy", "TextEncoderStream", "TextDecoderStream",
5477 "CompressionStream", "DecompressionStream",
5478 ]) {
5479 Object.defineProperty(web, name, {
5480 enumerable: true, configurable: true,
5481 get: () => globalThis[name],
5482 });
5483 }
5484
5485 // stream/consumers over anything async-iterable (node streams and Cells'
5486 // web ReadableStream both are).
5487 const consumers = {
5488 async arrayBuffer(stream) {
5489 const buf = await consumers.buffer(stream);
5490 return buf.buffer.slice(
5491 buf.byteOffset, buf.byteOffset + buf.byteLength);
5492 },
5493 async blob(stream) {
5494 const parts = [];
5495 for await (const chunk of stream) parts.push(chunk);
5496 return new Blob(parts);
5497 },
5498 async buffer(stream) {
5499 const parts = [];
5500 for await (const chunk of stream)
5501 parts.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
5502 return Buffer.concat(parts);
5503 },
5504 async json(stream) { return JSON.parse(await consumers.text(stream)); },
5505 async text(stream) {
5506 let out = "";
5507 const decoder = new TextDecoder();
5508 for await (const chunk of stream) {
5509 out += typeof chunk === "string"
5510 ? chunk : decoder.decode(chunk, { stream: true });
5511 }
5512 return out + decoder.decode();
5513 },
5514 };
5515
5516 globalThis.__streamModule = Stream;
5517 globalThis.__streamPromises = Stream.promises;
5518 globalThis.__streamWeb = web;
5519 globalThis.__streamConsumers = consumers;
5520})();