All files / lib/internal/streams writable.js

98.27% Statements 913/929
95.68% Branches 266/278
94.11% Functions 48/51
98.27% Lines 913/929

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 93028x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 246362x 28x 28x 28x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 84483x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 89173x 28x 106723x 106723x 106723x 106723x 106723x 106723x 28x 28x 53x 28x 28x 28x 28x 11x 11x 28x 28x 89190x 89190x 89190x 89190x 89190x 89190x 89190x 89190x 89190x 89190x 89190x 89190x 89190x 89190x 89190x 89173x 89173x 89173x 89190x 66922x 66922x 66922x 66922x 66922x 66922x 66922x 66922x 66922x 66922x 66922x 66922x 66922x 66922x 66922x 66922x 66922x 66922x 89166x 89166x 89166x 89166x 69x 69x 69x 69x 69x 69x 69x 89166x 89190x 28x 28x 28x 863x 860x 5x 863x 28x 28x 28x 28x 28x 1x 28x 28x 385630x 385630x 385630x 385630x 53347x 53347x 382042x 332283x 332283x 328658x 328658x 332283x 332283x 332283x 385630x 385630x 7x 385630x 382403x 117970x 51573x 51573x 51573x 382380x 264382x 264433x 30x 30x 51x 21x 21x 21x 382403x 385630x 385630x 385630x 23x 385630x 15x 15x 385630x 385630x 38x 38x 38x 38x 385562x 385562x 385630x 28x 28x 382301x 28x 28x 28x 39867x 28x 28x 28x 40661x 40661x 40661x 39924x 39924x 39924x 39924x 39924x 28x 28x 28x 8x 8x 8x 8x 8x 7x 7x 28x 28x 28x 28x 28x 385562x 385562x 385562x 385562x 385562x 385562x 385562x 385562x 385562x 385562x 385562x 385562x 125851x 125851x 16132x 16132x 125851x 16235x 16235x 385501x 259711x 259711x 259711x 259711x 259711x 259711x 259711x 385549x 385549x 385549x 385562x 385562x 28x 21161x 21161x 21161x 21161x 21161x 21161x 21161x 21161x 21161x 7961x 7961x 21158x 21161x 28x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 28x 280227x 280227x 280227x 280227x 280227x 280227x 6x 6x 6x 280222x 280222x 280222x 280222x 280222x 280222x 280227x 57x 57x 57x 57x 55x 55x 57x 57x 57x 57x 26x 26x 57x 57x 32x 49x 25x 25x 280227x 280164x 17652x 17652x 280164x 280164x 252009x 252009x 252009x 252009x 252009x 252009x 193721x 251782x 58288x 58288x 58288x 280164x 28155x 28155x 280164x 280227x 28x 58130x 58130x 58130x 58130x 28x 86285x 86285x 86285x 86285x 26379x 26379x 26379x 86285x 86285x 279730x 279730x 279730x 86281x 86283x 95x 95x 86283x 86283x 86285x 28x 28x 161x 161x 5x 5x 159x 161x 15x 15x 15x 15x 15x 156x 156x 160x 11x 11x 156x 156x 161x 28x 28x 57630x 57630x 57630x 57630x 57630x 13024x 13024x 57428x 57428x 57428x 57428x 57629x 23471x 23471x 57630x 57630x 57630x 57630x 57630x 13199x 13199x 13199x 12742x 70385x 70385x 13199x 13199x 13199x 13199x 13199x 13199x 13199x 13199x 13199x 13199x 36596x 7936x 7962x 7962x 7962x 7962x 7936x 7936x 7936x 4202x 7928x     3731x 3731x 3731x 7936x 36596x 57630x 28x 28x 5913x 5912x 5913x 1x 1x 28x 28x 28x 28x 28x 35044x 35044x 35044x 658x 658x 658x 34864x 1025x 1025x 1025x 35044x 35044x 35044x 35044x 3329x 3329x 2x 2x 3329x 35044x 35044x 35044x 667x 667x 667x 35042x 35044x 2x 35044x 34471x 34471x 34471x 34471x 34471x 34471x 34471x 34471x 34471x 35028x 29x 566x 86x 86x 35044x 35044x 1685x 4x 1685x 1681x 1681x 1685x 35044x 35044x 28x 28x 155170x 155170x 155170x 155170x 155170x 155170x 155170x 155170x 155170x 155170x 155170x 155170x 28x 34176x 34176x 34176x 34176x 34141x       34141x 34141x 34141x 34141x 8x 8x     8x 34141x 34111x 34111x 34111x 34111x 34111x 34111x 34111x 34111x 34141x 34176x 34176x 34176x 34176x 34176x 34176x 34176x 19x 19x 4x 4x 4x 3x 1x 1x 4x 4x 1x 1x 1x 4x 4x 19x 34176x 1x 1x 34176x 34176x 34176x 28x 37414x 37414x 34389x 34176x 34176x 34381x 213x 213x 213x 34389x 37414x 28x 120821x 120821x 37414x 37414x 216x 88x 88x 88x 71x 85x 17x 17x 88x 214x 127x 127x 127x 216x 37414x 120821x 28x 34309x 34309x 34309x 34309x 34309x 34309x 1660x 1660x 34309x 34309x 34309x 34309x 10866x 10866x 10866x 10866x 10681x 10681x 10681x 10681x 10866x 10866x 5880x 5880x 10866x 34309x 28x 28x 28x 28x 28x 206x 206x 28x 28x 28x 28x 41104x 28x 28x 2x 2x 1x 1x 2x 28x 28x 28x 28x 118598x 118598x 118598x 118598x 118598x 118598x 118598x 28x 28x 10578x 10578x 10578x 10578x 10578x 28x 28x 28x 28x 55085x 55085x 28x 28x 28x 28x 49x 49x 28x 28x 28x 28x 54x 54x 28x 28x 28x 28x 14015x 14015x 28x 28x 28x 28x 2370x 2370x 2370x 2370x 28x 28x 28x 28x 57235x 57235x 28x 28x 28x 28x 6351x 6351x 28x 28x 28x 28x 7348x 7348x 28x 28x 28x 28x 28x 2x 2x 28x 28x 28x 28x 28x 4x 4x 4x 2x 4x 4x 28x 28x 28x 28x 28x 330x 330x 330x 330x 312x 330x 9x 9x 330x 330x 330x 28x 28x 28x 28x 221x 28x 28x 28x 2x 28x 28x 28x 28x 28x           28x 28x       28x 28x 28x   28x  
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
 
// A bit simpler than readable streams.
// Implement an async ._write(chunk, encoding, cb), and it'll handle all
// the drain event emission and buffering.
 
'use strict';
 
const {
  ArrayPrototypeSlice,
  Error,
  FunctionPrototypeSymbolHasInstance,
  ObjectDefineProperty,
  ObjectDefineProperties,
  ObjectSetPrototypeOf,
  StringPrototypeToLowerCase,
  Symbol,
  SymbolHasInstance,
} = primordials;
 
module.exports = Writable;
Writable.WritableState = WritableState;
 
const EE = require('events');
const Stream = require('internal/streams/legacy').Stream;
const { Buffer } = require('buffer');
const destroyImpl = require('internal/streams/destroy');
 
const {
  addAbortSignal,
} = require('internal/streams/add-abort-signal');
 
const {
  getHighWaterMark,
  getDefaultHighWaterMark
} = require('internal/streams/state');
const {
  ERR_INVALID_ARG_TYPE,
  ERR_METHOD_NOT_IMPLEMENTED,
  ERR_MULTIPLE_CALLBACK,
  ERR_STREAM_CANNOT_PIPE,
  ERR_STREAM_DESTROYED,
  ERR_STREAM_ALREADY_FINISHED,
  ERR_STREAM_NULL_VALUES,
  ERR_STREAM_WRITE_AFTER_END,
  ERR_UNKNOWN_ENCODING
} = require('internal/errors').codes;
 
const { errorOrDestroy } = destroyImpl;
 
ObjectSetPrototypeOf(Writable.prototype, Stream.prototype);
ObjectSetPrototypeOf(Writable, Stream);
 
function nop() {}
 
const kOnFinished = Symbol('kOnFinished');
 
function WritableState(options, stream, isDuplex) {
  // Duplex streams are both readable and writable, but share
  // the same options object.
  // However, some cases require setting options to different
  // values for the readable and the writable sides of the duplex stream,
  // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
  if (typeof isDuplex !== 'boolean')
    isDuplex = stream instanceof Stream.Duplex;
 
  // Object stream flag to indicate whether or not this stream
  // contains buffers or objects.
  this.objectMode = !!(options && options.objectMode);
 
  if (isDuplex)
    this.objectMode = this.objectMode ||
      !!(options && options.writableObjectMode);
 
  // The point at which write() starts returning false
  // Note: 0 is a valid value, means that we always return false if
  // the entire buffer is not flushed immediately on write().
  this.highWaterMark = options ?
    getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex) :
    getDefaultHighWaterMark(false);
 
  // if _final has been called.
  this.finalCalled = false;
 
  // drain event flag.
  this.needDrain = false;
  // At the start of calling end()
  this.ending = false;
  // When end() has been called, and returned.
  this.ended = false;
  // When 'finish' is emitted.
  this.finished = false;
 
  // Has it been destroyed
  this.destroyed = false;
 
  // Should we decode strings into buffers before passing to _write?
  // this is here so that some node-core streams can optimize string
  // handling at a lower level.
  const noDecode = !!(options && options.decodeStrings === false);
  this.decodeStrings = !noDecode;
 
  // Crypto is kind of old and crusty.  Historically, its default string
  // encoding is 'binary' so we have to make this configurable.
  // Everything else in the universe uses 'utf8', though.
  this.defaultEncoding = (options && options.defaultEncoding) || 'utf8';
 
  // Not an actual buffer we keep track of, but a measurement
  // of how much we're waiting to get pushed to some underlying
  // socket or file.
  this.length = 0;
 
  // A flag to see when we're in the middle of a write.
  this.writing = false;
 
  // When true all writes will be buffered until .uncork() call.
  this.corked = 0;
 
  // A flag to be able to tell if the onwrite cb is called immediately,
  // or on a later tick.  We set this to true at first, because any
  // actions that shouldn't happen until "later" should generally also
  // not happen before the first write call.
  this.sync = true;
 
  // A flag to know if we're processing previously buffered items, which
  // may call the _write() callback in the same tick, so that we don't
  // end up in an overlapped onwrite situation.
  this.bufferProcessing = false;
 
  // The callback that's passed to _write(chunk, cb).
  this.onwrite = onwrite.bind(undefined, stream);
 
  // The callback that the user supplies to write(chunk, encoding, cb).
  this.writecb = null;
 
  // The amount that is being written when _write is called.
  this.writelen = 0;
 
  // Storage for data passed to the afterWrite() callback in case of
  // synchronous _write() completion.
  this.afterWriteTickInfo = null;
 
  resetBuffer(this);
 
  // Number of pending user-supplied write callbacks
  // this must be 0 before 'finish' can be emitted.
  this.pendingcb = 0;
 
  // Stream is still being constructed and cannot be
  // destroyed until construction finished or failed.
  // Async construction is opt in, therefore we start as
  // constructed.
  this.constructed = true;
 
  // Emit prefinish if the only thing we're waiting for is _write cbs
  // This is relevant for synchronous Transform streams.
  this.prefinished = false;
 
  // True if the error was already emitted and should not be thrown again.
  this.errorEmitted = false;
 
  // Should close be emitted on destroy. Defaults to true.
  this.emitClose = !options || options.emitClose !== false;
 
  // Should .destroy() be called after 'finish' (and potentially 'end').
  this.autoDestroy = !options || options.autoDestroy !== false;
 
  // Indicates whether the stream has errored. When true all write() calls
  // should return false. This is needed since when autoDestroy
  // is disabled we need a way to tell whether the stream has failed.
  this.errored = null;
 
  // Indicates whether the stream has finished destroying.
  this.closed = false;
 
  // True if close has been emitted or would have been emitted
  // depending on emitClose.
  this.closeEmitted = false;
 
  this[kOnFinished] = [];
}
 
function resetBuffer(state) {
  state.buffered = [];
  state.bufferedIndex = 0;
  state.allBuffers = true;
  state.allNoop = true;
}
 
WritableState.prototype.getBuffer = function getBuffer() {
  return ArrayPrototypeSlice(this.buffered, this.bufferedIndex);
};
 
ObjectDefineProperty(WritableState.prototype, 'bufferedRequestCount', {
  get() {
    return this.buffered.length - this.bufferedIndex;
  }
});
 
function Writable(options) {
  // Writable ctor is applied to Duplexes, too.
  // `realHasInstance` is necessary because using plain `instanceof`
  // would return false, as no `_writableState` property is attached.
 
  // Trying to use the custom `instanceof` for Writable here will also break the
  // Node.js LazyTransform implementation, which has a non-trivial getter for
  // `_writableState` that would lead to infinite recursion.
 
  // Checking for a Stream.Duplex instance is faster here instead of inside
  // the WritableState constructor, at least with V8 6.5.
  const isDuplex = (this instanceof Stream.Duplex);
 
  if (!isDuplex && !FunctionPrototypeSymbolHasInstance(Writable, this))
    return new Writable(options);
 
  this._writableState = new WritableState(options, this, isDuplex);
 
  if (options) {
    if (typeof options.write === 'function')
      this._write = options.write;
 
    if (typeof options.writev === 'function')
      this._writev = options.writev;
 
    if (typeof options.destroy === 'function')
      this._destroy = options.destroy;
 
    if (typeof options.final === 'function')
      this._final = options.final;
 
    if (typeof options.construct === 'function')
      this._construct = options.construct;
 
    if (options.signal)
      addAbortSignal(options.signal, this);
  }
 
  Stream.call(this, options);
 
  destroyImpl.construct(this, () => {
    const state = this._writableState;
 
    if (!state.writing) {
      clearBuffer(this, state);
    }
 
    finishMaybe(this, state);
  });
}
 
ObjectDefineProperty(Writable, SymbolHasInstance, {
  value: function(object) {
    if (FunctionPrototypeSymbolHasInstance(this, object)) return true;
    if (this !== Writable) return false;
 
    return object && object._writableState instanceof WritableState;
  },
});
 
// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function() {
  errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
};
 
function _write(stream, chunk, encoding, cb) {
  const state = stream._writableState;
 
  if (typeof encoding === 'function') {
    cb = encoding;
    encoding = state.defaultEncoding;
  } else {
    if (!encoding)
      encoding = state.defaultEncoding;
    else if (encoding !== 'buffer' && !Buffer.isEncoding(encoding))
      throw new ERR_UNKNOWN_ENCODING(encoding);
    if (typeof cb !== 'function')
      cb = nop;
  }
 
  if (chunk === null) {
    throw new ERR_STREAM_NULL_VALUES();
  } else if (!state.objectMode) {
    if (typeof chunk === 'string') {
      if (state.decodeStrings !== false) {
        chunk = Buffer.from(chunk, encoding);
        encoding = 'buffer';
      }
    } else if (chunk instanceof Buffer) {
      encoding = 'buffer';
    } else if (Stream._isUint8Array(chunk)) {
      chunk = Stream._uint8ArrayToBuffer(chunk);
      encoding = 'buffer';
    } else {
      throw new ERR_INVALID_ARG_TYPE(
        'chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
    }
  }
 
  let err;
  if (state.ending) {
    err = new ERR_STREAM_WRITE_AFTER_END();
  } else if (state.destroyed) {
    err = new ERR_STREAM_DESTROYED('write');
  }
 
  if (err) {
    process.nextTick(cb, err);
    errorOrDestroy(stream, err, true);
    return err;
  }
  state.pendingcb++;
  return writeOrBuffer(stream, state, chunk, encoding, cb);
}
 
Writable.prototype.write = function(chunk, encoding, cb) {
  return _write(this, chunk, encoding, cb) === true;
};
 
Writable.prototype.cork = function() {
  this._writableState.corked++;
};
 
Writable.prototype.uncork = function() {
  const state = this._writableState;
 
  if (state.corked) {
    state.corked--;
 
    if (!state.writing)
      clearBuffer(this, state);
  }
};
 
Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
  // node::ParseEncoding() requires lower case.
  if (typeof encoding === 'string')
    encoding = StringPrototypeToLowerCase(encoding);
  if (!Buffer.isEncoding(encoding))
    throw new ERR_UNKNOWN_ENCODING(encoding);
  this._writableState.defaultEncoding = encoding;
  return this;
};
 
// If we're already writing something, then just put this
// in the queue, and wait our turn.  Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, chunk, encoding, callback) {
  const len = state.objectMode ? 1 : chunk.length;
 
  state.length += len;
 
  // stream._write resets state.length
  const ret = state.length < state.highWaterMark;
  // We must ensure that previous needDrain will not be reset to false.
  if (!ret)
    state.needDrain = true;
 
  if (state.writing || state.corked || state.errored || !state.constructed) {
    state.buffered.push({ chunk, encoding, callback });
    if (state.allBuffers && encoding !== 'buffer') {
      state.allBuffers = false;
    }
    if (state.allNoop && callback !== nop) {
      state.allNoop = false;
    }
  } else {
    state.writelen = len;
    state.writecb = callback;
    state.writing = true;
    state.sync = true;
    stream._write(chunk, encoding, state.onwrite);
    state.sync = false;
  }
 
  // Return false if errored or destroyed in order to break
  // any synchronous while(stream.write(data)) loops.
  return ret && !state.errored && !state.destroyed;
}
 
function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  state.writelen = len;
  state.writecb = cb;
  state.writing = true;
  state.sync = true;
  if (state.destroyed)
    state.onwrite(new ERR_STREAM_DESTROYED('write'));
  else if (writev)
    stream._writev(chunk, state.onwrite);
  else
    stream._write(chunk, encoding, state.onwrite);
  state.sync = false;
}
 
function onwriteError(stream, state, er, cb) {
  --state.pendingcb;
 
  cb(er);
  // Ensure callbacks are invoked even when autoDestroy is
  // not enabled. Passing `er` here doesn't make sense since
  // it's related to one specific write, not to the buffered
  // writes.
  errorBuffer(state);
  // This can emit error, but error must always follow cb.
  errorOrDestroy(stream, er);
}
 
function onwrite(stream, er) {
  const state = stream._writableState;
  const sync = state.sync;
  const cb = state.writecb;
 
  if (typeof cb !== 'function') {
    errorOrDestroy(stream, new ERR_MULTIPLE_CALLBACK());
    return;
  }
 
  state.writing = false;
  state.writecb = null;
  state.length -= state.writelen;
  state.writelen = 0;
 
  if (er) {
    // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364
    er.stack; // eslint-disable-line no-unused-expressions
 
    if (!state.errored) {
      state.errored = er;
    }
 
    // In case of duplex streams we need to notify the readable side of the
    // error.
    if (stream._readableState && !stream._readableState.errored) {
      stream._readableState.errored = er;
    }
 
    if (sync) {
      process.nextTick(onwriteError, stream, state, er, cb);
    } else {
      onwriteError(stream, state, er, cb);
    }
  } else {
    if (state.buffered.length > state.bufferedIndex) {
      clearBuffer(stream, state);
    }
 
    if (sync) {
      // It is a common case that the callback passed to .write() is always
      // the same. In that case, we do not schedule a new nextTick(), but
      // rather just increase a counter, to improve performance and avoid
      // memory allocations.
      if (state.afterWriteTickInfo !== null &&
          state.afterWriteTickInfo.cb === cb) {
        state.afterWriteTickInfo.count++;
      } else {
        state.afterWriteTickInfo = { count: 1, cb, stream, state };
        process.nextTick(afterWriteTick, state.afterWriteTickInfo);
      }
    } else {
      afterWrite(stream, state, 1, cb);
    }
  }
}
 
function afterWriteTick({ stream, state, count, cb }) {
  state.afterWriteTickInfo = null;
  return afterWrite(stream, state, count, cb);
}
 
function afterWrite(stream, state, count, cb) {
  const needDrain = !state.ending && !stream.destroyed && state.length === 0 &&
    state.needDrain;
  if (needDrain) {
    state.needDrain = false;
    stream.emit('drain');
  }
 
  while (count-- > 0) {
    state.pendingcb--;
    cb();
  }
 
  if (state.destroyed) {
    errorBuffer(state);
  }
 
  finishMaybe(stream, state);
}
 
// If there's something in the buffer waiting, then invoke callbacks.
function errorBuffer(state) {
  if (state.writing) {
    return;
  }
 
  for (let n = state.bufferedIndex; n < state.buffered.length; ++n) {
    const { chunk, callback } = state.buffered[n];
    const len = state.objectMode ? 1 : chunk.length;
    state.length -= len;
    callback(state.errored ?? new ERR_STREAM_DESTROYED('write'));
  }
 
  const onfinishCallbacks = state[kOnFinished].splice(0);
  for (let i = 0; i < onfinishCallbacks.length; i++) {
    onfinishCallbacks[i](state.errored ?? new ERR_STREAM_DESTROYED('end'));
  }
 
  resetBuffer(state);
}
 
// If there's something in the buffer waiting, then process it.
function clearBuffer(stream, state) {
  if (state.corked ||
      state.bufferProcessing ||
      state.destroyed ||
      !state.constructed) {
    return;
  }
 
  const { buffered, bufferedIndex, objectMode } = state;
  const bufferedLength = buffered.length - bufferedIndex;
 
  if (!bufferedLength) {
    return;
  }
 
  let i = bufferedIndex;
 
  state.bufferProcessing = true;
  if (bufferedLength > 1 && stream._writev) {
    state.pendingcb -= bufferedLength - 1;
 
    const callback = state.allNoop ? nop : (err) => {
      for (let n = i; n < buffered.length; ++n) {
        buffered[n].callback(err);
      }
    };
    // Make a copy of `buffered` if it's going to be used by `callback` above,
    // since `doWrite` will mutate the array.
    const chunks = state.allNoop && i === 0 ?
      buffered : ArrayPrototypeSlice(buffered, i);
    chunks.allBuffers = state.allBuffers;
 
    doWrite(stream, state, true, state.length, chunks, '', callback);
 
    resetBuffer(state);
  } else {
    do {
      const { chunk, encoding, callback } = buffered[i];
      buffered[i++] = null;
      const len = objectMode ? 1 : chunk.length;
      doWrite(stream, state, false, len, chunk, encoding, callback);
    } while (i < buffered.length && !state.writing);
 
    if (i === buffered.length) {
      resetBuffer(state);
    } else if (i > 256) {
      buffered.splice(0, i);
      state.bufferedIndex = 0;
    } else {
      state.bufferedIndex = i;
    }
  }
  state.bufferProcessing = false;
}
 
Writable.prototype._write = function(chunk, encoding, cb) {
  if (this._writev) {
    this._writev([{ chunk, encoding }], cb);
  } else {
    throw new ERR_METHOD_NOT_IMPLEMENTED('_write()');
  }
};
 
Writable.prototype._writev = null;
 
Writable.prototype.end = function(chunk, encoding, cb) {
  const state = this._writableState;
 
  if (typeof chunk === 'function') {
    cb = chunk;
    chunk = null;
    encoding = null;
  } else if (typeof encoding === 'function') {
    cb = encoding;
    encoding = null;
  }
 
  let err;
 
  if (chunk !== null && chunk !== undefined) {
    const ret = _write(this, chunk, encoding);
    if (ret instanceof Error) {
      err = ret;
    }
  }
 
  // .end() fully uncorks.
  if (state.corked) {
    state.corked = 1;
    this.uncork();
  }
 
  if (err) {
    // Do nothing...
  } else if (!state.errored && !state.ending) {
    // This is forgiving in terms of unnecessary calls to end() and can hide
    // logic errors. However, usually such errors are harmless and causing a
    // hard error can be disproportionately destructive. It is not always
    // trivial for the user to determine whether end() needs to be called
    // or not.
 
    state.ending = true;
    finishMaybe(this, state, true);
    state.ended = true;
  } else if (state.finished) {
    err = new ERR_STREAM_ALREADY_FINISHED('end');
  } else if (state.destroyed) {
    err = new ERR_STREAM_DESTROYED('end');
  }
 
  if (typeof cb === 'function') {
    if (err || state.finished) {
      process.nextTick(cb, err);
    } else {
      state[kOnFinished].push(cb);
    }
  }
 
  return this;
};
 
function needFinish(state) {
  return (state.ending &&
          !state.destroyed &&
          state.constructed &&
          state.length === 0 &&
          !state.errored &&
          state.buffered.length === 0 &&
          !state.finished &&
          !state.writing &&
          !state.errorEmitted &&
          !state.closeEmitted);
}
 
function callFinal(stream, state) {
  let called = false;
 
  function onFinish(err) {
    if (called) {
      errorOrDestroy(stream, err ?? ERR_MULTIPLE_CALLBACK());
      return;
    }
    called = true;
 
    state.pendingcb--;
    if (err) {
      const onfinishCallbacks = state[kOnFinished].splice(0);
      for (let i = 0; i < onfinishCallbacks.length; i++) {
        onfinishCallbacks[i](err);
      }
      errorOrDestroy(stream, err, state.sync);
    } else if (needFinish(state)) {
      state.prefinished = true;
      stream.emit('prefinish');
      // Backwards compat. Don't check state.sync here.
      // Some streams assume 'finish' will be emitted
      // asynchronously relative to _final callback.
      state.pendingcb++;
      process.nextTick(finish, stream, state);
    }
  }
 
  state.sync = true;
  state.pendingcb++;
 
  try {
    const result = stream._final(onFinish);
    if (result != null) {
      const then = result.then;
      if (typeof then === 'function') {
        then.call(
          result,
          function() {
            if (!called) {
              process.nextTick(onFinish, null);
            }
          },
          function(err) {
            if (!called) {
              process.nextTick(onFinish, err);
            }
          });
      }
    }
  } catch (err) {
    onFinish(err);
  }
 
  state.sync = false;
}
 
function prefinish(stream, state) {
  if (!state.prefinished && !state.finalCalled) {
    if (typeof stream._final === 'function' && !state.destroyed) {
      state.finalCalled = true;
      callFinal(stream, state);
    } else {
      state.prefinished = true;
      stream.emit('prefinish');
    }
  }
}
 
function finishMaybe(stream, state, sync) {
  if (needFinish(state)) {
    prefinish(stream, state);
    if (state.pendingcb === 0) {
      if (sync) {
        state.pendingcb++;
        process.nextTick((stream, state) => {
          if (needFinish(state)) {
            finish(stream, state);
          } else {
            state.pendingcb--;
          }
        }, stream, state);
      } else if (needFinish(state)) {
        state.pendingcb++;
        finish(stream, state);
      }
    }
  }
}
 
function finish(stream, state) {
  state.pendingcb--;
  state.finished = true;
 
  const onfinishCallbacks = state[kOnFinished].splice(0);
  for (let i = 0; i < onfinishCallbacks.length; i++) {
    onfinishCallbacks[i]();
  }
 
  stream.emit('finish');
 
  if (state.autoDestroy) {
    // In case of duplex streams we need a way to detect
    // if the readable side is ready for autoDestroy as well.
    const rState = stream._readableState;
    const autoDestroy = !rState || (
      rState.autoDestroy &&
      // We don't expect the readable to ever 'end'
      // if readable is explicitly set to false.
      (rState.endEmitted || rState.readable === false)
    );
    if (autoDestroy) {
      stream.destroy();
    }
  }
}
 
ObjectDefineProperties(Writable.prototype, {
 
  closed: {
    get() {
      return this._writableState ? this._writableState.closed : false;
    }
  },
 
  destroyed: {
    get() {
      return this._writableState ? this._writableState.destroyed : false;
    },
    set(value) {
      // Backward compatibility, the user is explicitly managing destroyed.
      if (this._writableState) {
        this._writableState.destroyed = value;
      }
    }
  },
 
  writable: {
    get() {
      const w = this._writableState;
      // w.writable === false means that this is part of a Duplex stream
      // where the writable side was disabled upon construction.
      // Compat. The user might manually disable writable side through
      // deprecated setter.
      return !!w && w.writable !== false && !w.destroyed && !w.errored &&
        !w.ending && !w.ended;
    },
    set(val) {
      // Backwards compatible.
      if (this._writableState) {
        this._writableState.writable = !!val;
      }
    }
  },
 
  writableFinished: {
    get() {
      return this._writableState ? this._writableState.finished : false;
    }
  },
 
  writableObjectMode: {
    get() {
      return this._writableState ? this._writableState.objectMode : false;
    }
  },
 
  writableBuffer: {
    get() {
      return this._writableState && this._writableState.getBuffer();
    }
  },
 
  writableEnded: {
    get() {
      return this._writableState ? this._writableState.ending : false;
    }
  },
 
  writableNeedDrain: {
    get() {
      const wState = this._writableState;
      if (!wState) return false;
      return !wState.destroyed && !wState.ending && wState.needDrain;
    }
  },
 
  writableHighWaterMark: {
    get() {
      return this._writableState && this._writableState.highWaterMark;
    }
  },
 
  writableCorked: {
    get() {
      return this._writableState ? this._writableState.corked : 0;
    }
  },
 
  writableLength: {
    get() {
      return this._writableState && this._writableState.length;
    }
  },
 
  errored: {
    enumerable: false,
    get() {
      return this._writableState ? this._writableState.errored : null;
    }
  },
 
  writableAborted: {
    enumerable: false,
    get: function() {
      return !!(
        this._writableState.writable !== false &&
        (this._writableState.destroyed || this._writableState.errored) &&
        !this._writableState.finished
      );
    }
  },
});
 
const destroy = destroyImpl.destroy;
Writable.prototype.destroy = function(err, cb) {
  const state = this._writableState;
 
  // Invoke pending callbacks.
  if (!state.destroyed &&
    (state.bufferedIndex < state.buffered.length ||
      state[kOnFinished].length)) {
    process.nextTick(errorBuffer, state);
  }
 
  destroy.call(this, err, cb);
  return this;
};
 
Writable.prototype._undestroy = destroyImpl.undestroy;
Writable.prototype._destroy = function(err, cb) {
  cb(err);
};
 
Writable.prototype[EE.captureRejectionSymbol] = function(err) {
  this.destroy(err);
};
 
let webStreamsAdapters;
 
// Lazy to avoid circular references
function lazyWebStreams() {
  if (webStreamsAdapters === undefined)
    webStreamsAdapters = require('internal/webstreams/adapters');
  return webStreamsAdapters;
}
 
Writable.fromWeb = function(writableStream, options) {
  return lazyWebStreams().newStreamWritableFromWritableStream(
    writableStream,
    options);
};
 
Writable.toWeb = function(streamWritable) {
  return lazyWebStreams().newWritableStreamFromStreamWritable(streamWritable);
};