{“ast”:null,“code”:“// Copyright Joyent, Inc. and other Node contributors.n//n// Permission is hereby granted, free of charge, to any person obtaining an// copy of this software and associated documentation files (then// "Software"), to deal in the Software without restriction, includingn// without limitation the rights to use, copy, modify, merge, publish,n// distribute, sublicense, and/or sell copies of the Software, and to permitn// persons to whom the Software is furnished to do so, subject to then// following conditions:n//n// The above copyright notice and this permission notice shall be includedn// in all copies or substantial portions of the Software.n//n// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESSn// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OFn// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. INn// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT ORn// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THEn// USE OR OTHER DEALINGS IN THE SOFTWARE.n// A bit simpler than readable streams.n// Implement an async ._write(chunk, encoding, cb), and it'll handle alln// the drain event emission and buffering.n'use strict';n/*<replacement>*/nnvar pna = require('process-nextick-args');n/*</replacement>*/nnnmodule.exports = Writable;n/* <replacement> */nnfunction WriteReq(chunk, encoding, cb) {n this.chunk = chunk;n this.encoding = encoding;n this.callback = cb;n this.next = null;n} // It seems a linked list but it is notn// there will be only 2 of these for each streamnnnfunction CorkedRequest(state) {n var _this = this;nn this.next = null;n this.entry = null;nn this.finish = function () {n onCorkedFinish(_this, state);n };n}n/* </replacement> */nn/*<replacement>*/nnnvar asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;n/*</replacement>*/nn/*<replacement>*/nnvar Duplex;n/*</replacement>*/nnWritable.WritableState = WritableState;n/*<replacement>*/nnvar util = require('core-util-is');nnutil.inherits = require('inherits');n/*</replacement>*/nn/*<replacement>*/nnvar internalUtil = {n deprecate: require('util-deprecate')n};n/*</replacement>*/nn/*<replacement>*/nnvar Stream = require('./internal/streams/stream');n/*</replacement>*/nn/*<replacement>*/nnnvar Buffer = require('safe-buffer').Buffer;nnvar OurUint8Array = global.Uint8Array || function () {};nnfunction _uint8ArrayToBuffer(chunk) {n return Buffer.from(chunk);n}nnfunction _isUint8Array(obj) {n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;n}n/*</replacement>*/nnnvar destroyImpl = require('./internal/streams/destroy');nnutil.inherits(Writable, Stream);nnfunction nop() {}nnfunction WritableState(options, stream) {n Duplex = Duplex || require('./_stream_duplex');n options = options || {}; // Duplex streams are both readable and writable, but sharen // the same options object.n // However, some cases require setting options to differentn // values for the readable and the writable sides of the duplex stream.n // These options can be provided separately as readableXXX and writableXXX.nn var isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this streamn // contains buffers or objects.nn this.objectMode = !!options.objectMode;n if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning falsen // Note: 0 is a valid value, means that we always return false ifn // the entire buffer is not flushed immediately on write()nn var hwm = options.highWaterMark;n var writableHwm = options.writableHighWaterMark;n var defaultHwm = this.objectMode ? 16 : 16 * 1024;n if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; // cast to ints.nn this.highWaterMark = Math.floor(this.highWaterMark); // if _final has been callednn this.finalCalled = false; // drain event flag.nn this.needDrain = false; // at the start of calling end()nn this.ending = false; // when end() has been called, and returnednn this.ended = false; // when 'finish' is emittednn this.finished = false; // has it been destroyednn this.destroyed = false; // should we decode strings into buffers before passing to _write?n // this is here so that some node-core streams can optimize stringn // handling at a lower level.nn var noDecode = options.decodeStrings === false;n this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default stringn // encoding is 'binary' so we have to make this configurable.n // Everything else in the universe uses 'utf8', though.nn this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurementn // of how much we're waiting to get pushed to some underlyingn // socket or file.nn this.length = 0; // a flag to see when we're in the middle of a write.nn this.writing = false; // when true all writes will be buffered until .uncork() callnn this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,n // or on a later tick. We set this to true at first, because anyn // actions that shouldn't happen until "later" should generally alson // not happen before the first write call.nn this.sync = true; // a flag to know if we're processing previously buffered items, whichn // may call the _write() callback in the same tick, so that we don'tn // end up in an overlapped onwrite situation.nn this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)nn this.onwrite = function (er) {n onwrite(stream, er);n }; // the callback that the user supplies to write(chunk,encoding,cb)nnn this.writecb = null; // the amount that is being written when _write is called.nn this.writelen = 0;n this.bufferedRequest = null;n this.lastBufferedRequest = null; // number of pending user-supplied write callbacksn // this must be 0 before 'finish' can be emittednn this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbsn // This is relevant for synchronous Transform streamsnn this.prefinished = false; // True if the error was already emitted and should not be thrown againnn this.errorEmitted = false; // count buffered requestsnn this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is alwaysn // one allocated and free to use, and we maintain at most twonn this.corkedRequestsFree = new CorkedRequest(this);n}nnWritableState.prototype.getBuffer = function getBuffer() {n var current = this.bufferedRequest;n var out = [];nn while (current) {n out.push(current);n current = current.next;n }nn return out;n};nn(function () {n try {n Object.defineProperty(WritableState.prototype, 'buffer', {n get: internalUtil.deprecate(function () {n return this.getBuffer();n }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')n });n } catch (_) {}n})(); // Test _writableState for inheritance to account for Duplex streams,n// whose prototype chain only points to Readable.nnnvar realHasInstance;nnif (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype === 'function') {n realHasInstance = Function.prototype;n Object.defineProperty(Writable, Symbol.hasInstance, {n value: function value(object) {n if (realHasInstance.call(this, object)) return true;n if (this !== Writable) return false;n return object && object._writableState instanceof WritableState;n }n });n} else {n realHasInstance = function realHasInstance(object) {n return object instanceof this;n };n}nnfunction Writable(options) {n Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too.n // `realHasInstance` is necessary because using plain `instanceof`n // would return false, as no `_writableState` property is attached.n // Trying to use the custom `instanceof` for Writable here will also break then // Node.js LazyTransform implementation, which has a non-trivial getter forn // `_writableState` that would lead to infinite recursion.nn if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {n return new Writable(options);n }nn this._writableState = new WritableState(options, this); // legacy.nn this.writable = true;nn if (options) {n if (typeof options.write === 'function') this._write = options.write;n if (typeof options.writev === 'function') this._writev = options.writev;n if (typeof options.destroy === 'function') this._destroy = options.destroy;n if (typeof options === 'function') this._final = options;n }nn Stream.call(this);n} // Otherwise people can pipe Writable streams, which is just wrong.nnnWritable.prototype.pipe = function () {n this.emit('error', new Error('Cannot pipe, not readable'));n};nnfunction writeAfterEnd(stream, cb) {n var er = new Error('write after end'); // TODO: defer error events consistently everywhere, not just the cbnn stream.emit('error', er);n pna.nextTick(cb, er);n} // Checks that a user-supplied chunk is valid, especially for the particularn// mode the stream is in. Currently this means that `null` is never acceptedn// and undefined/non-string values are only allowed in object mode.nnnfunction validChunk(stream, state, chunk, cb) {n var valid = true;n var er = false;nn if (chunk === null) {n er = new TypeError('May not write null values to stream');n } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {n er = new TypeError('Invalid non-string/buffer chunk');n }nn if (er) {n stream.emit('error', er);n pna.nextTick(cb, er);n valid = false;n }nn return valid;n}nnWritable.prototype.write = function (chunk, encoding, cb) {n var state = this._writableState;n var ret = false;nn var isBuf = !state.objectMode && _isUint8Array(chunk);nn if (isBuf && !Buffer.isBuffer(chunk)) {n chunk = _uint8ArrayToBuffer(chunk);n }nn if (typeof encoding === 'function') {n cb = encoding;n encoding = null;n }nn if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;n if (typeof cb !== 'function') cb = nop;n if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {n state.pendingcb++;n ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);n }n return ret;n};nnWritable.prototype.cork = function () {n var state = this._writableState;n state.corked++;n};nnWritable.prototype.uncork = function () {n var state = this._writableState;nn if (state.corked) {n state.corked–;n if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);n }n};nnWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {n // node::ParseEncoding() requires lower case.n if (typeof encoding === 'string') encoding = encoding.toLowerCase();n if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);n this._writableState.defaultEncoding = encoding;n return this;n};nnfunction decodeChunk(state, chunk, encoding) {n if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {n chunk = Buffer.from(chunk, encoding);n }nn return chunk;n}nnObject.defineProperty(Writable.prototype, 'writableHighWaterMark', {n // making it explicit this property is not enumerablen // because otherwise some prototype manipulation inn // userland will failn enumerable: false,n get: function get() {n return this._writableState.highWaterMark;n }n}); // if we're already writing something, then just put thisn// in the queue, and wait our turn. Otherwise, call _writen// If we return false, then we need a drain event, so set that flag.nnfunction writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {n if (!isBuf) {n var newChunk = decodeChunk(state, chunk, encoding);nn if (chunk !== newChunk) {n isBuf = true;n encoding = 'buffer';n chunk = newChunk;n }n }nn var len = state.objectMode ? 1 : chunk.length;n state.length += len;n var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.nn if (!ret) state.needDrain = true;nn if (state.writing || state.corked) {n var last = state.lastBufferedRequest;n state.lastBufferedRequest = {n chunk: chunk,n encoding: encoding,n isBuf: isBuf,n callback: cb,n next: nulln };nn if (last) {n last.next = state.lastBufferedRequest;n } else {n state.bufferedRequest = state.lastBufferedRequest;n }nn state.bufferedRequestCount += 1;n } else {n doWrite(stream, state, false, len, chunk, encoding, cb);n }nn return ret;n}nnfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {n state.writelen = len;n state.writecb = cb;n state.writing = true;n state.sync = true;n if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);n state.sync = false;n}nnfunction onwriteError(stream, state, sync, er, cb) {n –state.pendingcb;nn if (sync) {n // defer the callback if we are being called synchronouslyn // to avoid piling up things on the stackn pna.nextTick(cb, er); // this can emit finish, and it will always happenn // after errornn pna.nextTick(finishMaybe, stream, state);n stream._writableState.errorEmitted = true;n stream.emit('error', er);n } else {n // the caller expect this to happen before ifn // it is asyncn cb(er);n stream._writableState.errorEmitted = true;n stream.emit('error', er); // this can emit finish, but finish mustn // always follow errornn finishMaybe(stream, state);n }n}nnfunction onwriteStateUpdate(state) {n state.writing = false;n state.writecb = null;n state.length -= state.writelen;n state.writelen = 0;n}nnfunction onwrite(stream, er) {n var state = stream._writableState;n var sync = state.sync;n var cb = state.writecb;n onwriteStateUpdate(state);n if (er) onwriteError(stream, state, sync, er, cb);else {n // Check if we're actually ready to finish, but don't emit yetn var finished = needFinish(state);nn if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {n clearBuffer(stream, state);n }nn if (sync) {n /*<replacement>*/n asyncWrite(afterWrite, stream, state, finished, cb);n /*</replacement>*/n } else {n afterWrite(stream, state, finished, cb);n }n }n}nnfunction afterWrite(stream, state, finished, cb) {n if (!finished) onwriteDrain(stream, state);n state.pendingcb–;n cb();n finishMaybe(stream, state);n} // Must force callback to be called on nextTick, so that we don'tn// emit 'drain' before the write() consumer gets the 'false' returnn// value, and has a chance to attach a 'drain' listener.nnnfunction onwriteDrain(stream, state) {n if (state.length === 0 && state.needDrain) {n state.needDrain = false;n stream.emit('drain');n }n} // if there's something in the buffer waiting, then process itnnnfunction clearBuffer(stream, state) {n state.bufferProcessing = true;n var entry = state.bufferedRequest;nn if (stream._writev && entry && entry.next) {n // Fast case, write everything using _writev()n var l = state.bufferedRequestCount;n var buffer = new Array(l);n var holder = state.corkedRequestsFree;n holder.entry = entry;n var count = 0;n var allBuffers = true;nn while (entry) {n buffer = entry;n if (!entry.isBuf) allBuffers = false;n entry = entry.next;n count += 1;n }nn buffer.allBuffers = allBuffers;n doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of timen // as the hot path ends with doWritenn state.pendingcb++;n state.lastBufferedRequest = null;nn if (holder.next) {n state.corkedRequestsFree = holder.next;n holder.next = null;n } else {n state.corkedRequestsFree = new CorkedRequest(state);n }nn state.bufferedRequestCount = 0;n } else {n // Slow case, write chunks one-by-onen while (entry) {n var chunk = entry.chunk;n var encoding = entry.encoding;n var cb = entry.callback;n var len = state.objectMode ? 1 : chunk.length;n doWrite(stream, state, false, len, chunk, encoding, cb);n entry = entry.next;n state.bufferedRequestCount–; // if we didn't call the onwrite immediately, thenn // it means that we need to wait until it does.n // also, that means that the chunk and cb are currentlyn // being processed, so move the buffer counter past them.nn if (state.writing) {n break;n }n }nn if (entry === null) state.lastBufferedRequest = null;n }nn state.bufferedRequest = entry;n state.bufferProcessing = false;n}nnWritable.prototype._write = function (chunk, encoding, cb) {n cb(new Error('_write() is not implemented'));n};nnWritable.prototype._writev = null;nnWritable.prototype.end = function (chunk, encoding, cb) {n var state = this._writableState;nn if (typeof chunk === 'function') {n cb = chunk;n chunk = null;n encoding = null;n } else if (typeof encoding === 'function') {n cb = encoding;n encoding = null;n }nn if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorksnn if (state.corked) {n state.corked = 1;n this.uncork();n } // ignore unnecessary end() calls.nnn if (!state.ending && !state.finished) endWritable(this, state, cb);n};nnfunction needFinish(state) {n return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;n}nnfunction callFinal(stream, state) {n stream._final(function (err) {n state.pendingcb–;nn if (err) {n stream.emit('error', err);n }nn state.prefinished = true;n stream.emit('prefinish');n finishMaybe(stream, state);n });n}nnfunction prefinish(stream, state) {n if (!state.prefinished && !state.finalCalled) {n if (typeof stream._final === 'function') {n state.pendingcb++;n state.finalCalled = true;n pna.nextTick(callFinal, stream, state);n } else {n state.prefinished = true;n stream.emit('prefinish');n }n }n}nnfunction finishMaybe(stream, state) {n var need = needFinish(state);nn if (need) {n prefinish(stream, state);nn if (state.pendingcb === 0) {n state.finished = true;n stream.emit('finish');n }n }nn return need;n}nnfunction endWritable(stream, state, cb) {n state.ending = true;n finishMaybe(stream, state);nn if (cb) {n if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);n }nn state.ended = true;n stream.writable = false;n}nnfunction onCorkedFinish(corkReq, state, err) {n var entry = corkReq.entry;n corkReq.entry = null;nn while (entry) {n var cb = entry.callback;n state.pendingcb–;n cb(err);n entry = entry.next;n }nn if (state.corkedRequestsFree) {n state.corkedRequestsFree.next = corkReq;n } else {n state.corkedRequestsFree = corkReq;n }n}nnObject.defineProperty(Writable.prototype, 'destroyed', {n get: function get() {n if (this._writableState === undefined) {n return false;n }nn return this._writableState.destroyed;n },n set: function set(value) {n // we ignore the value if the streamn // has not been initialized yetn if (!this._writableState) {n return;n } // backward compatibility, the user is explicitlyn // managing destroyednnn this._writableState.destroyed = value;n }n});nWritable.prototype.destroy = destroyImpl.destroy;nWritable.prototype._undestroy = destroyImpl.undestroy;nnWritable.prototype._destroy = function (err, cb) {n this.end();n cb(err);n};”,“map”:null,“metadata”:{},“sourceType”:“module”}