All files / lib/internal/webstreams adapters.js

82.37% Statements 785/953
74.5% Branches 111/149
92.31% Functions 48/52
82.37% Lines 785/953

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 26x 26x 26x 26x 26x 26x 4x 4x 4x 4x 4x 22x 26x 2x 2x 2x 2x 20x 20x 20x 26x 26x 26x 26x 26x 26x 26x 26x 26x       26x 26x 18x 1x 1x 1x 1x 18x 18x 18x 18x 18x 18x 7x 7x 7x 7x 7x 7x       7x 7x 7x 7x 11x 18x 9x 9x 9x 9x 2x 2x 26x 26x 26x 26x 26x 26x 26x 26x 11x             26x 26x 26x 2x 26x 26x 26x 9x 9x 9x 9x 9x       26x 26x 26x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 13x 13x 4x 4x 4x 4x 4x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x                                                   9x 9x 9x 8x             8x 8x 8x 8x 8x     8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 9x 9x 9x 9x 9x 9x 9x               9x 9x 9x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 7x 7x 9x 9x 9x 6x 6x 6x 6x               6x 6x 6x 6x 6x 6x 6x 6x 9x 9x 9x 9x 9x 9x 7x 7x 7x 7x 7x 9x 9x 2x 2x 2x 2x 9x 9x 9x 13x 136x 136x 136x 136x 136x 21x 21x 21x 21x 21x 21x           21x 21x 2x 2x 2x 2x 19x 19x 19x 19x 19x 19x 19x 19x 21x 21x 21x 21x 21x 21x 21x 10x 10x 10x 10x 10x 10x 10x 21x 21x 21x 21x 19x 2x 2x 2x 2x 19x 19x 19x 19x 19x 19x 19x 10x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 4x 21x 21x 21x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 9x 9x           9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x     9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x               9x 9x 9x 2x 2x 2x 2x 2x 2x 7x 9x 9x 9x 9x 9x 9x 8x 8x 8x 9x 9x 1x 1x 9x 9x 9x 9x 136x 136x 136x 136x 136x 136x 136x 136x 136x 15x 15x 15x 15x 15x 15x 15x 15x 15x     15x 15x 1x 1x 1x 1x 1x 1x 14x 14x 15x 15x 15x 15x 15x 15x 14x 14x 15x 15x 15x 15x 15x 15x 14x 14x 15x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 6x 6x 6x 6x 6x 6x 6x 6x           6x           6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x                                                   6x 6x 6x 3x             3x 3x 3x 3x 3x     3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 6x 6x 6x 4x 4x 4x 4x               4x 4x 4x 4x 4x 4x 4x 4x 6x 6x 6x 4x 4x 4x 4x 1x 4x 3x 3x 4x 4x 6x 6x 6x 6x 6x 6x 6x               6x 6x 6x 2x 2x 2x 6x 6x 2x 2x 2x 6x 6x 2x 2x 2x 2x 2x 2x 2x 2x 2x 4x 4x 6x 6x 6x 6x 6x 6x 4x 4x 4x 6x 6x 2x 2x 2x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x       6x 6x 6x 6x 136x 136x 136x 136x 136x 136x 136x 136x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x           1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x 1x 1x 1x               1x 1x 1x 136x 136x 136x 136x 136x 136x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 4x 4x 4x 4x 4x 4x 4x 2x 2x 2x 2x 2x     2x 2x 2x 2x 2x 2x 4x 4x       6x 6x 6x 6x 6x 6x 4x 6x 6x 6x 4x 4x 4x 4x       4x 4x 4x 4x 4x 4x 6x 6x 6x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x 136x  
'use strict';
 
const {
  ArrayPrototypeMap,
  PromiseAll,
  PromisePrototypeThen,
  PromisePrototypeFinally,
  PromiseResolve,
  Uint8Array,
} = primordials;
 
const {
  ReadableStream,
  isReadableStream,
} = require('internal/webstreams/readablestream');
 
const {
  WritableStream,
  isWritableStream,
} = require('internal/webstreams/writablestream');
 
const {
  CountQueuingStrategy,
} = require('internal/webstreams/queuingstrategies');
 
const {
  Writable,
  Readable,
  Duplex,
  destroy,
} = require('stream');
 
const {
  isDestroyed,
  isReadable,
  isReadableEnded,
  isWritable,
  isWritableEnded,
} = require('internal/streams/utils');
 
const {
  Buffer,
} = require('buffer');
 
const {
  errnoException,
  codes: {
    ERR_INVALID_ARG_TYPE,
    ERR_INVALID_ARG_VALUE,
    ERR_INVALID_STATE,
    ERR_STREAM_PREMATURE_CLOSE,
  },
  AbortError,
} = require('internal/errors');
 
const {
  createDeferredPromise,
} = require('internal/util');
 
const {
  validateBoolean,
  validateObject,
} = require('internal/validators');
 
const {
  WriteWrap,
  ShutdownWrap,
  kReadBytesOrError,
  kLastWriteWasAsync,
  streamBaseState,
} = internalBinding('stream_wrap');
 
const finished = require('internal/streams/end-of-stream');
 
const { UV_EOF } = internalBinding('uv');
 
/**
 * @typedef {import('../../stream').Writable} Writable
 * @typedef {import('../../stream').Readable} Readable
 * @typedef {import('./writablestream').WritableStream} WritableStream
 * @typedef {import('./readablestream').ReadableStream} ReadableStream
 *
 * @typedef {import('../abort_controller').AbortSignal} AbortSignal
 */
 
/**
 * @param {Writable} streamWritable
 * @returns {WritableStream}
 */
function newWritableStreamFromStreamWritable(streamWritable) {
  // Not using the internal/streams/utils isWritableNodeStream utility
  // here because it will return false if streamWritable is a Duplex
  // whose writable option is false. For a Duplex that is not writable,
  // we want it to pass this check but return a closed WritableStream.
  if (typeof streamWritable?._writableState !== 'object') {
    throw new ERR_INVALID_ARG_TYPE(
      'streamWritable',
      'stream.Writable',
      streamWritable);
  }
 
  if (isDestroyed(streamWritable) || !isWritable(streamWritable)) {
    const writable = new WritableStream();
    writable.close();
    return writable;
  }
 
  const highWaterMark = streamWritable.writableHighWaterMark;
  const strategy =
    streamWritable.writableObjectMode ?
      new CountQueuingStrategy({ highWaterMark }) :
      { highWaterMark };
 
  let controller;
  let backpressurePromise;
  let closed;
 
  function onDrain() {
    if (backpressurePromise !== undefined)
      backpressurePromise.resolve();
  }
 
  const cleanup = finished(streamWritable, (error) => {
    if (error?.code === 'ERR_STREAM_PREMATURE_CLOSE') {
      const err = new AbortError();
      err.cause = error;
      error = err;
    }
 
    cleanup();
    // This is a protection against non-standard, legacy streams
    // that happen to emit an error event again after finished is called.
    streamWritable.on('error', () => {});
    if (error != null) {
      if (backpressurePromise !== undefined)
        backpressurePromise.reject(error);
      // If closed is not undefined, the error is happening
      // after the WritableStream close has already started.
      // We need to reject it here.
      if (closed !== undefined) {
        closed.reject(error);
        closed = undefined;
      }
      controller.error(error);
      controller = undefined;
      return;
    }
 
    if (closed !== undefined) {
      closed.resolve();
      closed = undefined;
      return;
    }
    controller.error(new AbortError());
    controller = undefined;
  });
 
  streamWritable.on('drain', onDrain);
 
  return new WritableStream({
    start(c) { controller = c; },
 
    async write(chunk) {
      if (streamWritable.writableNeedDrain || !streamWritable.write(chunk)) {
        backpressurePromise = createDeferredPromise();
        return PromisePrototypeFinally(
          backpressurePromise.promise, () => {
            backpressurePromise = undefined;
          });
      }
    },
 
    abort(reason) {
      destroy(streamWritable, reason);
    },
 
    close() {
      if (closed === undefined && !isWritableEnded(streamWritable)) {
        closed = createDeferredPromise();
        streamWritable.end();
        return closed.promise;
      }

      controller = undefined;
      return PromiseResolve();
    },
  }, strategy);
}
 
/**
 * @param {WritableStream} writableStream
 * @param {{
 *   decodeStrings? : boolean,
 *   highWaterMark? : number,
 *   objectMode? : boolean,
 *   signal? : AbortSignal,
 * }} [options]
 * @returns {Writable}
 */
function newStreamWritableFromWritableStream(writableStream, options = {}) {
  if (!isWritableStream(writableStream)) {
    throw new ERR_INVALID_ARG_TYPE(
      'writableStream',
      'WritableStream',
      writableStream);
  }
 
  validateObject(options, 'options');
  const {
    highWaterMark,
    decodeStrings = true,
    objectMode = false,
    signal,
  } = options;
 
  validateBoolean(objectMode, 'options.objectMode');
  validateBoolean(decodeStrings, 'options.decodeStrings');
 
  const writer = writableStream.getWriter();
  let closed = false;
 
  const writable = new Writable({
    highWaterMark,
    objectMode,
    decodeStrings,
    signal,
 
    writev(chunks, callback) {
      function done(error) {
        try {
          callback(error);
        } catch (error) {
          // In a next tick because this is happening within
          // a promise context, and if there are any errors
          // thrown we don't want those to cause an unhandled
          // rejection. Let's just escape the promise and
          // handle it separately.
          process.nextTick(() => destroy(writable, error));
        }
      }

      PromisePrototypeThen(
        writer.ready,
        () => {
          return PromisePrototypeThen(
            PromiseAll(
              ArrayPrototypeMap(
                chunks,
                (chunk) => writer.write(chunk))),
            done,
            done);
        },
        done);
    },
 
    write(chunk, encoding, callback) {
      if (typeof chunk === 'string' && decodeStrings && !objectMode) {
        chunk = Buffer.from(chunk, encoding);
        chunk = new Uint8Array(
          chunk.buffer,
          chunk.byteOffset,
          chunk.byteLength);
      }
 
      function done(error) {
        try {
          callback(error);
        } catch (error) {
          destroy(writable, error);
        }
      }
 
      PromisePrototypeThen(
        writer.ready,
        () => {
          return PromisePrototypeThen(
            writer.write(chunk),
            done,
            done);
        },
        done);
    },
 
    destroy(error, callback) {
      function done() {
        try {
          callback(error);
        } catch (error) {
          // In a next tick because this is happening within
          // a promise context, and if there are any errors
          // thrown we don't want those to cause an unhandled
          // rejection. Let's just escape the promise and
          // handle it separately.
          process.nextTick(() => { throw error; });
        }
      }
 
      if (!closed) {
        if (error != null) {
          PromisePrototypeThen(
            writer.abort(error),
            done,
            done);
        } else {
          PromisePrototypeThen(
            writer.close(),
            done,
            done);
        }
        return;
      }
 
      done();
    },
 
    final(callback) {
      function done(error) {
        try {
          callback(error);
        } catch (error) {
          // In a next tick because this is happening within
          // a promise context, and if there are any errors
          // thrown we don't want those to cause an unhandled
          // rejection. Let's just escape the promise and
          // handle it separately.
          process.nextTick(() => destroy(writable, error));
        }
      }
 
      if (!closed) {
        PromisePrototypeThen(
          writer.close(),
          done,
          done);
      }
    },
  });
 
  PromisePrototypeThen(
    writer.closed,
    () => {
      // If the WritableStream closes before the stream.Writable has been
      // ended, we signal an error on the stream.Writable.
      closed = true;
      if (!isWritableEnded(writable))
        destroy(writable, new ERR_STREAM_PREMATURE_CLOSE());
    },
    (error) => {
      // If the WritableStream errors before the stream.Writable has been
      // destroyed, signal an error on the stream.Writable.
      closed = true;
      destroy(writable, error);
    });
 
  return writable;
}
 
/**
 * @param {Readable} streamReadable
 * @returns {ReadableStream}
 */
function newReadableStreamFromStreamReadable(streamReadable) {
  // Not using the internal/streams/utils isReadableNodeStream utility
  // here because it will return false if streamReadable is a Duplex
  // whose readable option is false. For a Duplex that is not readable,
  // we want it to pass this check but return a closed ReadableStream.
  if (typeof streamReadable?._readableState !== 'object') {
    throw new ERR_INVALID_ARG_TYPE(
      'streamReadable',
      'stream.Readable',
      streamReadable);
  }
 
  if (isDestroyed(streamReadable) || !isReadable(streamReadable)) {
    const readable = new ReadableStream();
    readable.cancel();
    return readable;
  }
 
  const objectMode = streamReadable.readableObjectMode;
  const highWaterMark = streamReadable.readableHighWaterMark;
  // When not running in objectMode explicitly, we just fall
  // back to a minimal strategy that just specifies the highWaterMark
  // and no size algorithm. Using a ByteLengthQueuingStrategy here
  // is unnecessary.
  const strategy =
    objectMode ?
      new CountQueuingStrategy({ highWaterMark }) :
      { highWaterMark };
 
  let controller;
 
  function onData(chunk) {
    // Copy the Buffer to detach it from the pool.
    if (Buffer.isBuffer(chunk) && !objectMode)
      chunk = new Uint8Array(chunk);
    controller.enqueue(chunk);
    if (controller.desiredSize <= 0)
      streamReadable.pause();
  }
 
  streamReadable.pause();
 
  const cleanup = finished(streamReadable, (error) => {
    if (error?.code === 'ERR_STREAM_PREMATURE_CLOSE') {
      const err = new AbortError();
      err.cause = error;
      error = err;
    }
 
    cleanup();
    // This is a protection against non-standard, legacy streams
    // that happen to emit an error event again after finished is called.
    streamReadable.on('error', () => {});
    if (error)
      return controller.error(error);
    controller.close();
  });
 
  streamReadable.on('data', onData);
 
  return new ReadableStream({
    start(c) { controller = c; },
 
    pull() { streamReadable.resume(); },
 
    cancel(reason) {
      destroy(streamReadable, reason);
    },
  }, strategy);
}
 
/**
 * @param {ReadableStream} readableStream
 * @param {{
 *   highWaterMark? : number,
 *   encoding? : string,
 *   objectMode? : boolean,
 *   signal? : AbortSignal,
 * }} [options]
 * @returns {Readable}
 */
function newStreamReadableFromReadableStream(readableStream, options = {}) {
  if (!isReadableStream(readableStream)) {
    throw new ERR_INVALID_ARG_TYPE(
      'readableStream',
      'ReadableStream',
      readableStream);
  }
 
  validateObject(options, 'options');
  const {
    highWaterMark,
    encoding,
    objectMode = false,
    signal,
  } = options;
 
  if (encoding !== undefined && !Buffer.isEncoding(encoding))
    throw new ERR_INVALID_ARG_VALUE(encoding, 'options.encoding');
  validateBoolean(objectMode, 'options.objectMode');
 
  const reader = readableStream.getReader();
  let closed = false;
 
  const readable = new Readable({
    objectMode,
    highWaterMark,
    encoding,
    signal,
 
    read() {
      PromisePrototypeThen(
        reader.read(),
        (chunk) => {
          if (chunk.done) {
            // Value should always be undefined here.
            readable.push(null);
          } else {
            readable.push(chunk.value);
          }
        },
        (error) => destroy(readable, error));
    },
 
    destroy(error, callback) {
      function done() {
        try {
          callback(error);
        } catch (error) {
          // In a next tick because this is happening within
          // a promise context, and if there are any errors
          // thrown we don't want those to cause an unhandled
          // rejection. Let's just escape the promise and
          // handle it separately.
          process.nextTick(() => { throw error; });
        }
      }
 
      if (!closed) {
        PromisePrototypeThen(
          reader.cancel(error),
          done,
          done);
        return;
      }
      done();
    },
  });
 
  PromisePrototypeThen(
    reader.closed,
    () => {
      closed = true;
      if (!isReadableEnded(readable))
        readable.push(null);
    },
    (error) => {
      closed = true;
      destroy(readable, error);
    });
 
  return readable;
}
 
/**
 * @typedef {import('./readablestream').ReadableWritablePair
 * } ReadableWritablePair
 * @typedef {import('../../stream').Duplex} Duplex
 *
 * @param {Duplex} duplex
 * @returns {ReadableWritablePair}
 */
function newReadableWritablePairFromDuplex(duplex) {
  // Not using the internal/streams/utils isWritableNodeStream and
  // isReadableNodestream utilities here because they will return false
  // if the duplex was created with writable or readable options set to
  // false. Instead, we'll check the readable and writable state after
  // and return closed WritableStream or closed ReadableStream as
  // necessary.
  if (typeof duplex?._writableState !== 'object' ||
      typeof duplex?._readableState !== 'object') {
    throw new ERR_INVALID_ARG_TYPE('duplex', 'stream.Duplex', duplex);
  }
 
  if (isDestroyed(duplex)) {
    const writable = new WritableStream();
    const readable = new ReadableStream();
    writable.close();
    readable.cancel();
    return { readable, writable };
  }
 
  const writable =
    isWritable(duplex) ?
      newWritableStreamFromStreamWritable(duplex) :
      new WritableStream();
 
  if (!isWritable(duplex))
    writable.close();
 
  const readable =
    isReadable(duplex) ?
      newReadableStreamFromStreamReadable(duplex) :
      new ReadableStream();
 
  if (!isReadable(duplex))
    readable.cancel();
 
  return { writable, readable };
}
 
/**
 * @param {ReadableWritablePair} pair
 * @param {{
 *   allowHalfOpen? : boolean,
 *   decodeStrings? : boolean,
 *   encoding? : string,
 *   highWaterMark? : number,
 *   objectMode? : boolean,
 *   signal? : AbortSignal,
 * }} [options]
 * @returns
 */
function newStreamDuplexFromReadableWritablePair(pair = {}, options = {}) {
  validateObject(pair, 'pair');
  const {
    readable: readableStream,
    writable: writableStream,
  } = pair;
 
  if (!isReadableStream(readableStream)) {
    throw new ERR_INVALID_ARG_TYPE(
      'pair.readable',
      'ReadableStream',
      readableStream);
  }
  if (!isWritableStream(writableStream)) {
    throw new ERR_INVALID_ARG_TYPE(
      'pair.writable',
      'WritableStream',
      writableStream);
  }
 
  validateObject(options, 'options');
  const {
    allowHalfOpen = false,
    objectMode = false,
    encoding,
    decodeStrings = true,
    highWaterMark,
    signal,
  } = options;
 
  validateBoolean(objectMode, 'options.objectMode');
  if (encoding !== undefined && !Buffer.isEncoding(encoding))
    throw new ERR_INVALID_ARG_VALUE(encoding, 'options.encoding');
 
  const writer = writableStream.getWriter();
  const reader = readableStream.getReader();
  let writableClosed = false;
  let readableClosed = false;
 
  const duplex = new Duplex({
    allowHalfOpen,
    highWaterMark,
    objectMode,
    encoding,
    decodeStrings,
    signal,
 
    writev(chunks, callback) {
      function done(error) {
        try {
          callback(error);
        } catch (error) {
          // In a next tick because this is happening within
          // a promise context, and if there are any errors
          // thrown we don't want those to cause an unhandled
          // rejection. Let's just escape the promise and
          // handle it separately.
          process.nextTick(() => destroy(duplex, error));
        }
      }

      PromisePrototypeThen(
        writer.ready,
        () => {
          return PromisePrototypeThen(
            PromiseAll(
              ArrayPrototypeMap(
                chunks,
                (chunk) => writer.write(chunk))),
            done,
            done);
        },
        done);
    },
 
    write(chunk, encoding, callback) {
      if (typeof chunk === 'string' && decodeStrings && !objectMode) {
        chunk = Buffer.from(chunk, encoding);
        chunk = new Uint8Array(
          chunk.buffer,
          chunk.byteOffset,
          chunk.byteLength);
      }
 
      function done(error) {
        try {
          callback(error);
        } catch (error) {
          destroy(duplex, error);
        }
      }
 
      PromisePrototypeThen(
        writer.ready,
        () => {
          return PromisePrototypeThen(
            writer.write(chunk),
            done,
            done);
        },
        done);
    },
 
    final(callback) {
      function done(error) {
        try {
          callback(error);
        } catch (error) {
          // In a next tick because this is happening within
          // a promise context, and if there are any errors
          // thrown we don't want those to cause an unhandled
          // rejection. Let's just escape the promise and
          // handle it separately.
          process.nextTick(() => destroy(duplex, error));
        }
      }
 
      if (!writableClosed) {
        PromisePrototypeThen(
          writer.close(),
          done,
          done);
      }
    },
 
    read() {
      PromisePrototypeThen(
        reader.read(),
        (chunk) => {
          if (chunk.done) {
            duplex.push(null);
          } else {
            duplex.push(chunk.value);
          }
        },
        (error) => destroy(duplex, error));
    },
 
    destroy(error, callback) {
      function done() {
        try {
          callback(error);
        } catch (error) {
          // In a next tick because this is happening within
          // a promise context, and if there are any errors
          // thrown we don't want those to cause an unhandled
          // rejection. Let's just escape the promise and
          // handle it separately.
          process.nextTick(() => { throw error; });
        }
      }
 
      async function closeWriter() {
        if (!writableClosed)
          await writer.abort(error);
      }
 
      async function closeReader() {
        if (!readableClosed)
          await reader.cancel(error);
      }
 
      if (!writableClosed || !readableClosed) {
        PromisePrototypeThen(
          PromiseAll([
            closeWriter(),
            closeReader(),
          ]),
          done,
          done);
        return;
      }
 
      done();
    },
  });
 
  PromisePrototypeThen(
    writer.closed,
    () => {
      writableClosed = true;
      if (!isWritableEnded(duplex))
        destroy(duplex, new ERR_STREAM_PREMATURE_CLOSE());
    },
    (error) => {
      writableClosed = true;
      readableClosed = true;
      destroy(duplex, error);
    });
 
  PromisePrototypeThen(
    reader.closed,
    () => {
      readableClosed = true;
      if (!isReadableEnded(duplex))
        duplex.push(null);
    },
    (error) => {
      writableClosed = true;
      readableClosed = true;
      destroy(duplex, error);
    });
 
  return duplex;
}
 
/**
 * @typedef {import('./queuingstrategies').QueuingStrategy} QueuingStrategy
 * @typedef {{}} StreamBase
 * @param {StreamBase} streamBase
 * @param {QueuingStrategy} strategy
 * @returns {WritableStream}
 */
function newWritableStreamFromStreamBase(streamBase, strategy) {
  validateObject(streamBase, 'streamBase');
 
  let current;
 
  function createWriteWrap(controller, promise) {
    const req = new WriteWrap();
    req.handle = streamBase;
    req.oncomplete = onWriteComplete;
    req.async = false;
    req.bytes = 0;
    req.buffer = null;
    req.controller = controller;
    req.promise = promise;
    return req;
  }
 
  function onWriteComplete(status) {
    if (status < 0) {
      const error = errnoException(status, 'write', this.error);
      this.promise.reject(error);
      this.controller.error(error);
      return;
    }
    this.promise.resolve();
  }
 
  function doWrite(chunk, controller) {
    const promise = createDeferredPromise();
    let ret;
    let req;
    try {
      req = createWriteWrap(controller, promise);
      ret = streamBase.writeBuffer(req, chunk);
      if (streamBaseState[kLastWriteWasAsync])
        req.buffer = chunk;
      req.async = !!streamBaseState[kLastWriteWasAsync];
    } catch (error) {
      promise.reject(error);
    }
 
    if (ret !== 0)
      promise.reject(errnoException(ret, 'write', req));
    else if (!req.async)
      promise.resolve();
 
    return promise.promise;
  }
 
  return new WritableStream({
    write(chunk, controller) {
      current = current !== undefined ?
        PromisePrototypeThen(
          current,
          () => doWrite(chunk, controller),
          (error) => controller.error(error)) :
        doWrite(chunk, controller);
      return current;
    },
 
    close() {
      const promise = createDeferredPromise();
      const req = new ShutdownWrap();
      req.oncomplete = () => promise.resolve();
      const err = streamBase.shutdown(req);
      if (err === 1)
        promise.resolve();
      return promise.promise;
    },
  }, strategy);
}
 
/**
 * @param {StreamBase} streamBase
 * @param {QueuingStrategy} strategy
 * @returns {ReadableStream}
 */
function newReadableStreamFromStreamBase(streamBase, strategy, options = {}) {
  validateObject(streamBase, 'streamBase');
  validateObject(options, 'options');
 
  const {
    ondone = () => {},
  } = options;
 
  if (typeof streamBase.onread === 'function')
    throw new ERR_INVALID_STATE('StreamBase already has a consumer');
 
  if (typeof ondone !== 'function')
    throw new ERR_INVALID_ARG_TYPE('options.ondone', 'Function', ondone);
 
  let controller;
 
  streamBase.onread = (arrayBuffer) => {
    const nread = streamBaseState[kReadBytesOrError];
 
    if (nread === 0)
      return;
 
    try {
      if (nread === UV_EOF) {
        controller.close();
        streamBase.readStop();
        try {
          ondone();
        } catch (error) {
          controller.error(error);
        }
        return;
      }
 
      controller.enqueue(arrayBuffer);
 
      if (controller.desiredSize <= 0)
        streamBase.readStop();
    } catch (error) {
      controller.error(error);
      streamBase.readStop();
    }
  };
 
  return new ReadableStream({
    start(c) { controller = c; },
 
    pull() {
      streamBase.readStart();
    },
 
    cancel() {
      const promise = createDeferredPromise();
      try {
        ondone();
      } catch (error) {
        promise.reject(error);
        return promise.promise;
      }
      const req = new ShutdownWrap();
      req.oncomplete = () => promise.resolve();
      const err = streamBase.shutdown(req);
      if (err === 1)
        promise.resolve();
      return promise.promise;
    },
  }, strategy);
}
 
module.exports = {
  newWritableStreamFromStreamWritable,
  newReadableStreamFromStreamReadable,
  newStreamWritableFromWritableStream,
  newStreamReadableFromReadableStream,
  newReadableWritablePairFromDuplex,
  newStreamDuplexFromReadableWritablePair,
  newWritableStreamFromStreamBase,
  newReadableStreamFromStreamBase,
};