Best JavaScript code snippet using wpt
writable-stream.ts
Source:writable-stream.ts
...412 } else {413 assert(state === 'errored');414 const storedError = stream._storedError;415 defaultWriterReadyPromiseInitializeAsRejected(this, storedError);416 defaultWriterClosedPromiseInitializeAsRejected(this, storedError);417 }418 }419 get closed(): Promise<void> {420 if (IsWritableStreamDefaultWriter(this) === false) {421 return Promise.reject(defaultWriterBrandCheckException('closed'));422 }423 return this._closedPromise;424 }425 get desiredSize(): number | null {426 if (IsWritableStreamDefaultWriter(this) === false) {427 throw defaultWriterBrandCheckException('desiredSize');428 }429 if (this._ownerWritableStream === undefined) {430 throw defaultWriterLockException('desiredSize');431 }432 return WritableStreamDefaultWriterGetDesiredSize(this);433 }434 get ready(): Promise<void> {435 if (IsWritableStreamDefaultWriter(this) === false) {436 return Promise.reject(defaultWriterBrandCheckException('ready'));437 }438 return this._readyPromise;439 }440 abort(reason: any): Promise<void> {441 if (IsWritableStreamDefaultWriter(this) === false) {442 return Promise.reject(defaultWriterBrandCheckException('abort'));443 }444 if (this._ownerWritableStream === undefined) {445 return Promise.reject(defaultWriterLockException('abort'));446 }447 return WritableStreamDefaultWriterAbort(this, reason);448 }449 close(): Promise<void> {450 if (IsWritableStreamDefaultWriter(this) === false) {451 return Promise.reject(defaultWriterBrandCheckException('close'));452 }453 const stream = this._ownerWritableStream;454 if (stream === undefined) {455 return Promise.reject(defaultWriterLockException('close'));456 }457 if (WritableStreamCloseQueuedOrInFlight(stream) === true) {458 return Promise.reject(new TypeError('cannot close an already-closing stream'));459 }460 return WritableStreamDefaultWriterClose(this);461 }462 releaseLock(): void {463 if (IsWritableStreamDefaultWriter(this) === false) {464 throw defaultWriterBrandCheckException('releaseLock');465 }466 const stream = this._ownerWritableStream;467 if (stream === undefined) {468 return;469 }470 assert(stream._writer !== undefined);471 WritableStreamDefaultWriterRelease(this);472 }473 write(chunk: W): Promise<void> {474 if (IsWritableStreamDefaultWriter(this) === false) {475 return Promise.reject(defaultWriterBrandCheckException('write'));476 }477 if (this._ownerWritableStream === undefined) {478 return Promise.reject(defaultWriterLockException('write to'));479 }480 return WritableStreamDefaultWriterWrite(this, chunk);481 }482}483// Abstract operations for the WritableStreamDefaultWriter.484function IsWritableStreamDefaultWriter<W>(x: any): x is WritableStreamDefaultWriter<W> {485 if (!typeIsObject(x)) {486 return false;487 }488 if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {489 return false;490 }491 return true;492}493// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.494function WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter<any>, reason: any) {495 const stream = writer._ownerWritableStream;496 assert(stream !== undefined);497 return WritableStreamAbort(stream, reason);498}499function WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter<any>): Promise<void> {500 const stream = writer._ownerWritableStream;501 assert(stream !== undefined);502 const state = stream._state;503 if (state === 'closed' || state === 'errored') {504 return Promise.reject(new TypeError(505 `The stream (in ${state} state) is not in the writable state and cannot be closed`));506 }507 assert(state === 'writable' || state === 'erroring');508 assert(WritableStreamCloseQueuedOrInFlight(stream) === false);509 const promise = new Promise<void>((resolve, reject) => {510 const closeRequest: CloseRequest = {511 _resolve: resolve,512 _reject: reject513 };514 stream._closeRequest = closeRequest;515 });516 if (stream._backpressure === true && state === 'writable') {517 defaultWriterReadyPromiseResolve(writer);518 }519 WritableStreamDefaultControllerClose(stream._writableStreamController);520 return promise;521}522function WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter<any>): Promise<void> {523 const stream = writer._ownerWritableStream;524 assert(stream !== undefined);525 const state = stream._state;526 if (WritableStreamCloseQueuedOrInFlight(stream) === true || state === 'closed') {527 return Promise.resolve();528 }529 if (state === 'errored') {530 return Promise.reject(stream._storedError);531 }532 assert(state === 'writable' || state === 'erroring');533 return WritableStreamDefaultWriterClose(writer);534}535function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter<any>, error: any) {536 if (writer._closedPromiseState === 'pending') {537 defaultWriterClosedPromiseReject(writer, error);538 } else {539 defaultWriterClosedPromiseResetToRejected(writer, error);540 }541}542function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter<any>, error: any) {543 if (writer._readyPromiseState === 'pending') {544 defaultWriterReadyPromiseReject(writer, error);545 } else {546 defaultWriterReadyPromiseResetToRejected(writer, error);547 }548}549function WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter<any>): number | null {550 const stream = writer._ownerWritableStream;551 const state = stream._state;552 if (state === 'errored' || state === 'erroring') {553 return null;554 }555 if (state === 'closed') {556 return 0;557 }558 return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);559}560function WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter<any>) {561 const stream = writer._ownerWritableStream;562 assert(stream !== undefined);563 assert(stream._writer === writer);564 const releasedError = new TypeError(565 'Writer was released and can no longer be used to monitor the stream\'s closedness');566 WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);567 // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not568 // rejected until afterwards. This means that simply testing state will not work.569 WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);570 stream._writer = undefined;571 writer._ownerWritableStream = undefined!;572}573function WritableStreamDefaultWriterWrite<W>(writer: WritableStreamDefaultWriter<W>, chunk: W): Promise<void> {574 const stream = writer._ownerWritableStream;575 assert(stream !== undefined);576 const controller = stream._writableStreamController;577 const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);578 if (stream !== writer._ownerWritableStream) {579 return Promise.reject(defaultWriterLockException('write to'));580 }581 const state = stream._state;582 if (state === 'errored') {583 return Promise.reject(stream._storedError);584 }585 if (WritableStreamCloseQueuedOrInFlight(stream) === true || state === 'closed') {586 return Promise.reject(new TypeError('The stream is closing or closed and cannot be written to'));587 }588 if (state === 'erroring') {589 return Promise.reject(stream._storedError);590 }591 assert(state === 'writable');592 const promise = WritableStreamAddWriteRequest(stream);593 WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);594 return promise;595}596interface WriteRecord<W> {597 chunk: W;598}599type QueueRecord<W> = WriteRecord<W> | 'close';600export type WritableStreamDefaultControllerType = WritableStreamDefaultController<any>;601class WritableStreamDefaultController<W = any> {602 /** @internal */603 _controlledWritableStream!: WritableStream<W>;604 /** @internal */605 _queue!: SimpleQueue<QueuePair<QueueRecord<W>>>;606 /** @internal */607 _queueTotalSize!: number;608 /** @internal */609 _started!: boolean;610 /** @internal */611 _strategySizeAlgorithm!: QueuingStrategySizeCallback<W>;612 /** @internal */613 _strategyHWM!: number;614 /** @internal */615 _writeAlgorithm!: (chunk: W) => Promise<void>;616 /** @internal */617 _closeAlgorithm!: () => Promise<void>;618 /** @internal */619 _abortAlgorithm!: (reason: any) => Promise<void>;620 /** @internal */621 constructor() {622 throw new TypeError('WritableStreamDefaultController cannot be constructed explicitly');623 }624 error(e: any) {625 if (IsWritableStreamDefaultController(this) === false) {626 throw new TypeError(627 'WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController');628 }629 const state = this._controlledWritableStream._state;630 if (state !== 'writable') {631 // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so632 // just treat it as a no-op.633 return;634 }635 WritableStreamDefaultControllerError(this, e);636 }637 /** @internal */638 [AbortSteps](reason: any) {639 const result = this._abortAlgorithm(reason);640 WritableStreamDefaultControllerClearAlgorithms(this);641 return result;642 }643 /** @internal */644 [ErrorSteps]() {645 ResetQueue(this);646 }647}648// Abstract operations implementing interface required by the WritableStream.649function IsWritableStreamDefaultController<W>(x: any): x is WritableStreamDefaultController<W> {650 if (!typeIsObject(x)) {651 return false;652 }653 if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {654 return false;655 }656 return true;657}658function SetUpWritableStreamDefaultController<W>(stream: WritableStream<W>,659 controller: WritableStreamDefaultController<W>,660 startAlgorithm: () => void | PromiseLike<void>,661 writeAlgorithm: (chunk: W) => Promise<void>,662 closeAlgorithm: () => Promise<void>,663 abortAlgorithm: (reason: any) => Promise<void>,664 highWaterMark: number,665 sizeAlgorithm: QueuingStrategySizeCallback<W>) {666 assert(IsWritableStream(stream) === true);667 assert(stream._writableStreamController === undefined);668 controller._controlledWritableStream = stream;669 stream._writableStreamController = controller;670 // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.671 controller._queue = undefined!;672 controller._queueTotalSize = undefined!;673 ResetQueue(controller);674 controller._started = false;675 controller._strategySizeAlgorithm = sizeAlgorithm;676 controller._strategyHWM = highWaterMark;677 controller._writeAlgorithm = writeAlgorithm;678 controller._closeAlgorithm = closeAlgorithm;679 controller._abortAlgorithm = abortAlgorithm;680 const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);681 WritableStreamUpdateBackpressure(stream, backpressure);682 const startResult = startAlgorithm();683 const startPromise = Promise.resolve(startResult);684 startPromise.then(685 () => {686 assert(stream._state === 'writable' || stream._state === 'erroring');687 controller._started = true;688 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);689 },690 r => {691 assert(stream._state === 'writable' || stream._state === 'erroring');692 controller._started = true;693 WritableStreamDealWithRejection(stream, r);694 }695 ).catch(rethrowAssertionErrorRejection);696}697function SetUpWritableStreamDefaultControllerFromUnderlyingSink<W>(stream: WritableStream<W>,698 underlyingSink: UnderlyingSink<W>,699 highWaterMark: number,700 sizeAlgorithm: QueuingStrategySizeCallback<W>) {701 assert(underlyingSink !== undefined);702 const controller = Object.create(WritableStreamDefaultController.prototype);703 function startAlgorithm() {704 return InvokeOrNoop<typeof underlyingSink, 'start'>(underlyingSink, 'start', [controller]);705 }706 const writeAlgorithm = CreateAlgorithmFromUnderlyingMethod<typeof underlyingSink, 'write'>(707 underlyingSink, 'write', 1, [controller]708 );709 const closeAlgorithm = CreateAlgorithmFromUnderlyingMethod<typeof underlyingSink, 'close'>(710 underlyingSink, 'close', 0, []711 );712 const abortAlgorithm = CreateAlgorithmFromUnderlyingMethod<typeof underlyingSink, 'abort'>(713 underlyingSink, 'abort', 1, []714 );715 SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,716 abortAlgorithm, highWaterMark, sizeAlgorithm);717}718// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.719function WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController<any>) {720 controller._writeAlgorithm = undefined!;721 controller._closeAlgorithm = undefined!;722 controller._abortAlgorithm = undefined!;723 controller._strategySizeAlgorithm = undefined!;724}725function WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController<any>) {726 EnqueueValueWithSize(controller, 'close', 0);727 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);728}729function WritableStreamDefaultControllerGetChunkSize<W>(controller: WritableStreamDefaultController<W>,730 chunk: W): number {731 try {732 return controller._strategySizeAlgorithm(chunk);733 } catch (chunkSizeE) {734 WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);735 return 1;736 }737}738function WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController<any>): number {739 return controller._strategyHWM - controller._queueTotalSize;740}741function WritableStreamDefaultControllerWrite<W>(controller: WritableStreamDefaultController<W>,742 chunk: W,743 chunkSize: number) {744 const writeRecord = { chunk };745 try {746 EnqueueValueWithSize(controller, writeRecord, chunkSize);747 } catch (enqueueE) {748 WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);749 return;750 }751 const stream = controller._controlledWritableStream;752 if (WritableStreamCloseQueuedOrInFlight(stream) === false && stream._state === 'writable') {753 const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);754 WritableStreamUpdateBackpressure(stream, backpressure);755 }756 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);757}758// Abstract operations for the WritableStreamDefaultController.759function WritableStreamDefaultControllerAdvanceQueueIfNeeded<W>(controller: WritableStreamDefaultController<W>) {760 const stream = controller._controlledWritableStream;761 if (controller._started === false) {762 return;763 }764 if (stream._inFlightWriteRequest !== undefined) {765 return;766 }767 const state = stream._state;768 assert(state !== 'closed' && state !== 'errored');769 if (state === 'erroring') {770 WritableStreamFinishErroring(stream);771 return;772 }773 if (controller._queue.length === 0) {774 return;775 }776 const writeRecord = PeekQueueValue(controller);777 if (writeRecord === 'close') {778 WritableStreamDefaultControllerProcessClose(controller);779 } else {780 WritableStreamDefaultControllerProcessWrite(controller, writeRecord.chunk);781 }782}783function WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController<any>, error: any) {784 if (controller._controlledWritableStream._state === 'writable') {785 WritableStreamDefaultControllerError(controller, error);786 }787}788function WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController<any>) {789 const stream = controller._controlledWritableStream;790 WritableStreamMarkCloseRequestInFlight(stream);791 DequeueValue(controller);792 assert(controller._queue.length === 0);793 const sinkClosePromise = controller._closeAlgorithm();794 WritableStreamDefaultControllerClearAlgorithms(controller);795 sinkClosePromise.then(796 () => {797 WritableStreamFinishInFlightClose(stream);798 },799 reason => {800 WritableStreamFinishInFlightCloseWithError(stream, reason);801 }802 ).catch(rethrowAssertionErrorRejection);803}804function WritableStreamDefaultControllerProcessWrite<W>(controller: WritableStreamDefaultController<W>, chunk: W) {805 const stream = controller._controlledWritableStream;806 WritableStreamMarkFirstWriteRequestInFlight(stream);807 const sinkWritePromise = controller._writeAlgorithm(chunk);808 sinkWritePromise.then(809 () => {810 WritableStreamFinishInFlightWrite(stream);811 const state = stream._state;812 assert(state === 'writable' || state === 'erroring');813 DequeueValue(controller);814 if (WritableStreamCloseQueuedOrInFlight(stream) === false && state === 'writable') {815 const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);816 WritableStreamUpdateBackpressure(stream, backpressure);817 }818 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);819 },820 reason => {821 if (stream._state === 'writable') {822 WritableStreamDefaultControllerClearAlgorithms(controller);823 }824 WritableStreamFinishInFlightWriteWithError(stream, reason);825 }826 ).catch(rethrowAssertionErrorRejection);827}828function WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController<any>): boolean {829 const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);830 return desiredSize <= 0;831}832// A client of WritableStreamDefaultController may use these functions directly to bypass state check.833function WritableStreamDefaultControllerError(controller: WritableStreamDefaultController<any>, error: any) {834 const stream = controller._controlledWritableStream;835 assert(stream._state === 'writable');836 WritableStreamDefaultControllerClearAlgorithms(controller);837 WritableStreamStartErroring(stream, error);838}839// Helper functions for the WritableStream.840function streamBrandCheckException(name: string): TypeError {841 return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);842}843// Helper functions for the WritableStreamDefaultWriter.844function defaultWriterBrandCheckException(name: string): TypeError {845 return new TypeError(846 `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);847}848function defaultWriterLockException(name: string): TypeError {849 return new TypeError('Cannot ' + name + ' a stream using a released writer');850}851function defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter<any>) {852 writer._closedPromise = new Promise((resolve, reject) => {853 writer._closedPromise_resolve = resolve;854 writer._closedPromise_reject = reject;855 writer._closedPromiseState = 'pending';856 });857}858function defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter<any>, reason: any) {859 defaultWriterClosedPromiseInitialize(writer);860 defaultWriterClosedPromiseReject(writer, reason);861}862function defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter<any>) {863 defaultWriterClosedPromiseInitialize(writer);864 defaultWriterClosedPromiseResolve(writer);865}866function defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter<any>, reason: any) {867 assert(writer._closedPromise_resolve !== undefined);868 assert(writer._closedPromise_reject !== undefined);869 assert(writer._closedPromiseState === 'pending');870 writer._closedPromise.catch(() => {});871 writer._closedPromise_reject!(reason);872 writer._closedPromise_resolve = undefined;873 writer._closedPromise_reject = undefined;874 writer._closedPromiseState = 'rejected';875}876function defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter<any>, reason: any) {877 assert(writer._closedPromise_resolve === undefined);878 assert(writer._closedPromise_reject === undefined);879 assert(writer._closedPromiseState !== 'pending');880 defaultWriterClosedPromiseInitializeAsRejected(writer, reason);881}882function defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter<any>) {883 assert(writer._closedPromise_resolve !== undefined);884 assert(writer._closedPromise_reject !== undefined);885 assert(writer._closedPromiseState === 'pending');886 writer._closedPromise_resolve!(undefined);887 writer._closedPromise_resolve = undefined;888 writer._closedPromise_reject = undefined;889 writer._closedPromiseState = 'resolved';890}891function defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter<any>) {892 writer._readyPromise = new Promise((resolve, reject) => {893 writer._readyPromise_resolve = resolve;894 writer._readyPromise_reject = reject;...
writable-stream.js
Source:writable-stream.js
...164 } else if (state === 'closed') {165 defaultWriterClosedPromiseInitializeAsResolved(this);166 } else {167 assert(state === 'errored', 'state must be errored');168 defaultWriterClosedPromiseInitializeAsRejected(this, stream._storedError);169 this._closedPromise.catch(() => {});170 }171 if (state === 'writable' &&172 WritableStreamDefaultControllerGetBackpressure(stream._writableStreamController) === true) {173 defaultWriterReadyPromiseInitialize(this);174 } else {175 defaultWriterReadyPromiseInitializeAsResolved(this, undefined);176 }177 }178 get closed() {179 if (IsWritableStreamDefaultWriter(this) === false) {180 return Promise.reject(defaultWriterBrandCheckException('closed'));181 }182 return this._closedPromise;183 }184 get desiredSize() {185 if (IsWritableStreamDefaultWriter(this) === false) {186 throw defaultWriterBrandCheckException('desiredSize');187 }188 if (this._ownerWritableStream === undefined) {189 throw defaultWriterLockException('desiredSize');190 }191 return WritableStreamDefaultWriterGetDesiredSize(this);192 }193 get ready() {194 if (IsWritableStreamDefaultWriter(this) === false) {195 return Promise.reject(defaultWriterBrandCheckException('ready'));196 }197 return this._readyPromise;198 }199 abort(reason) {200 if (IsWritableStreamDefaultWriter(this) === false) {201 return Promise.reject(defaultWriterBrandCheckException('abort'));202 }203 if (this._ownerWritableStream === undefined) {204 return Promise.reject(defaultWriterLockException('abort'));205 }206 return WritableStreamDefaultWriterAbort(this, reason);207 }208 close() {209 if (IsWritableStreamDefaultWriter(this) === false) {210 return Promise.reject(defaultWriterBrandCheckException('close'));211 }212 const stream = this._ownerWritableStream;213 if (stream === undefined) {214 return Promise.reject(defaultWriterLockException('close'));215 }216 if (stream._state === 'closing') {217 return Promise.reject(new TypeError('cannot close an already-closing stream'));218 }219 return WritableStreamDefaultWriterClose(this);220 }221 releaseLock() {222 if (IsWritableStreamDefaultWriter(this) === false) {223 throw defaultWriterBrandCheckException('releaseLock');224 }225 const stream = this._ownerWritableStream;226 if (stream === undefined) {227 return;228 }229 assert(stream._writer !== undefined);230 WritableStreamDefaultWriterRelease(this);231 }232 write(chunk) {233 if (IsWritableStreamDefaultWriter(this) === false) {234 return Promise.reject(defaultWriterBrandCheckException('write'));235 }236 const stream = this._ownerWritableStream;237 if (stream === undefined) {238 return Promise.reject(defaultWriterLockException('write to'));239 }240 if (stream._state === 'closing') {241 return Promise.reject(new TypeError('Cannot write to an already-closed stream'));242 }243 return WritableStreamDefaultWriterWrite(this, chunk);244 }245}246// Abstract operations for the WritableStreamDefaultWriter.247function IsWritableStreamDefaultWriter(x) {248 if (!typeIsObject(x)) {249 return false;250 }251 if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {252 return false;253 }254 return true;255}256// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.257function WritableStreamDefaultWriterAbort(writer, reason) {258 const stream = writer._ownerWritableStream;259 assert(stream !== undefined);260 return WritableStreamAbort(stream, reason);261}262function WritableStreamDefaultWriterClose(writer) {263 const stream = writer._ownerWritableStream;264 assert(stream !== undefined);265 const state = stream._state;266 if (state === 'closed' || state === 'errored') {267 return Promise.reject(new TypeError(268 `The stream (in ${state} state) is not in the writable state and cannot be closed`));269 }270 assert(state === 'writable');271 const promise = WritableStreamAddWriteRequest(stream);272 if (WritableStreamDefaultControllerGetBackpressure(stream._writableStreamController) === true) {273 defaultWriterReadyPromiseResolve(writer);274 }275 stream._state = 'closing';276 WritableStreamDefaultControllerClose(stream._writableStreamController);277 return promise;278}279function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) {280 const stream = writer._ownerWritableStream;281 assert(stream !== undefined);282 const state = stream._state;283 if (state === 'closing' || state === 'closed') {284 return Promise.resolve();285 }286 if (state === 'errored') {287 return Promise.reject(stream._storedError);288 }289 assert(state === 'writable');290 return WritableStreamDefaultWriterClose(writer);291}292function WritableStreamDefaultWriterGetDesiredSize(writer) {293 const stream = writer._ownerWritableStream;294 const state = stream._state;295 if (state === 'errored') {296 return null;297 }298 if (state === 'closed') {299 return 0;300 }301 return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);302}303function WritableStreamDefaultWriterRelease(writer) {304 const stream = writer._ownerWritableStream;305 assert(stream !== undefined);306 assert(stream._writer === writer);307 const releasedError = new TypeError(308 'Writer was released and can no longer be used to monitor the stream\'s closedness');309 const state = stream._state;310 if (state === 'writable' || state === 'closing') {311 defaultWriterClosedPromiseReject(writer, releasedError);312 } else {313 defaultWriterClosedPromiseResetToRejected(writer, releasedError);314 }315 writer._closedPromise.catch(() => {});316 if (state === 'writable' &&317 WritableStreamDefaultControllerGetBackpressure(stream._writableStreamController) === true) {318 defaultWriterReadyPromiseReject(writer, releasedError);319 } else {320 defaultWriterReadyPromiseResetToRejected(writer, releasedError);321 }322 writer._readyPromise.catch(() => {});323 stream._writer = undefined;324 writer._ownerWritableStream = undefined;325}326function WritableStreamDefaultWriterWrite(writer, chunk) {327 const stream = writer._ownerWritableStream;328 assert(stream !== undefined);329 const state = stream._state;330 if (state === 'closed' || state === 'errored') {331 return Promise.reject(new TypeError(332 `The stream (in ${state} state) is not in the writable state and cannot be written to`));333 }334 assert(state === 'writable');335 const promise = WritableStreamAddWriteRequest(stream);336 WritableStreamDefaultControllerWrite(stream._writableStreamController, chunk);337 return promise;338}339class WritableStreamDefaultController {340 constructor(stream, underlyingSink, size, highWaterMark) {341 if (IsWritableStream(stream) === false) {342 throw new TypeError('WritableStreamDefaultController can only be constructed with a WritableStream instance');343 }344 if (stream._writableStreamController !== undefined) {345 throw new TypeError(346 'WritableStreamDefaultController instances can only be created by the WritableStream constructor');347 }348 this._controlledWritableStream = stream;349 this._underlyingSink = underlyingSink;350 this._queue = [];351 this._started = false;352 this._writing = false;353 const normalizedStrategy = ValidateAndNormalizeQueuingStrategy(size, highWaterMark);354 this._strategySize = normalizedStrategy.size;355 this._strategyHWM = normalizedStrategy.highWaterMark;356 const backpressure = WritableStreamDefaultControllerGetBackpressure(this);357 if (backpressure === true) {358 WritableStreamUpdateBackpressure(stream, backpressure);359 }360 const controller = this;361 const startResult = InvokeOrNoop(underlyingSink, 'start', [this]);362 Promise.resolve(startResult).then(363 () => {364 controller._started = true;365 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);366 },367 r => {368 WritableStreamDefaultControllerErrorIfNeeded(controller, r);369 }370 )371 .catch(rethrowAssertionErrorRejection);372 }373 error(e) {374 if (IsWritableStreamDefaultController(this) === false) {375 throw new TypeError(376 'WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController');377 }378 const state = this._controlledWritableStream._state;379 if (state === 'closed' || state === 'errored') {380 throw new TypeError(`The stream is ${state} and so cannot be errored`);381 }382 WritableStreamDefaultControllerError(this, e);383 }384}385// Abstract operations implementing interface required by the WritableStream.386function WritableStreamDefaultControllerAbort(controller, reason) {387 controller._queue = [];388 const sinkAbortPromise = PromiseInvokeOrFallbackOrNoop(controller._underlyingSink, 'abort', [reason],389 'close', [controller]);390 return sinkAbortPromise.then(() => undefined);391}392function WritableStreamDefaultControllerClose(controller) {393 EnqueueValueWithSize(controller._queue, 'close', 0);394 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);395}396function WritableStreamDefaultControllerGetDesiredSize(controller) {397 const queueSize = GetTotalQueueSize(controller._queue);398 return controller._strategyHWM - queueSize;399}400function WritableStreamDefaultControllerWrite(controller, chunk) {401 const stream = controller._controlledWritableStream;402 assert(stream._state === 'writable');403 let chunkSize = 1;404 if (controller._strategySize !== undefined) {405 try {406 chunkSize = controller._strategySize(chunk);407 } catch (chunkSizeE) {408 // TODO: Should we notify the sink of this error?409 WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);410 return;411 }412 }413 const writeRecord = { chunk };414 const lastBackpressure = WritableStreamDefaultControllerGetBackpressure(controller);415 try {416 EnqueueValueWithSize(controller._queue, writeRecord, chunkSize);417 } catch (enqueueE) {418 WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);419 return;420 }421 if (stream._state === 'writable') {422 const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);423 if (lastBackpressure !== backpressure) {424 WritableStreamUpdateBackpressure(stream, backpressure);425 }426 }427 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);428}429// Abstract operations for the WritableStreamDefaultController.430function IsWritableStreamDefaultController(x) {431 if (!typeIsObject(x)) {432 return false;433 }434 if (!Object.prototype.hasOwnProperty.call(x, '_underlyingSink')) {435 return false;436 }437 return true;438}439function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) {440 if (controller._controlledWritableStream._state === 'closed' ||441 controller._controlledWritableStream._state === 'errored') {442 return;443 }444 if (controller._started === false) {445 return;446 }447 if (controller._writing === true) {448 return;449 }450 if (controller._queue.length === 0) {451 return;452 }453 const writeRecord = PeekQueueValue(controller._queue);454 if (writeRecord === 'close') {455 WritableStreamDefaultControllerProcessClose(controller);456 } else {457 WritableStreamDefaultControllerProcessWrite(controller, writeRecord.chunk);458 }459}460function WritableStreamDefaultControllerErrorIfNeeded(controller, e) {461 if (controller._controlledWritableStream._state === 'writable' ||462 controller._controlledWritableStream._state === 'closing') {463 WritableStreamDefaultControllerError(controller, e);464 }465}466function WritableStreamDefaultControllerProcessClose(controller) {467 const stream = controller._controlledWritableStream;468 assert(stream._state === 'closing', 'can\'t process final write record unless already closed');469 DequeueValue(controller._queue);470 assert(controller._queue.length === 0, 'queue must be empty once the final write record is dequeued');471 const sinkClosePromise = PromiseInvokeOrNoop(controller._underlyingSink, 'close', [controller]);472 sinkClosePromise.then(473 () => {474 if (stream._state !== 'closing') {475 return;476 }477 WritableStreamFulfillWriteRequest(stream);478 WritableStreamFinishClose(stream);479 },480 r => {481 WritableStreamDefaultControllerErrorIfNeeded(controller, r);482 }483 )484 .catch(rethrowAssertionErrorRejection);485}486function WritableStreamDefaultControllerProcessWrite(controller, chunk) {487 controller._writing = true;488 const sinkWritePromise = PromiseInvokeOrNoop(controller._underlyingSink, 'write', [chunk, controller]);489 sinkWritePromise.then(490 () => {491 const stream = controller._controlledWritableStream;492 const state = stream._state;493 if (state === 'errored' || state === 'closed') {494 return;495 }496 controller._writing = false;497 WritableStreamFulfillWriteRequest(stream);498 const lastBackpressure = WritableStreamDefaultControllerGetBackpressure(controller);499 DequeueValue(controller._queue);500 if (state !== 'closing') {501 const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);502 if (lastBackpressure !== backpressure) {503 WritableStreamUpdateBackpressure(controller._controlledWritableStream, backpressure);504 }505 }506 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);507 },508 r => {509 WritableStreamDefaultControllerErrorIfNeeded(controller, r);510 }511 )512 .catch(rethrowAssertionErrorRejection);513}514function WritableStreamDefaultControllerGetBackpressure(controller) {515 const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);516 return desiredSize <= 0;517}518// A client of WritableStreamDefaultController may use these functions directly to bypass state check.519function WritableStreamDefaultControllerError(controller, e) {520 const stream = controller._controlledWritableStream;521 assert(stream._state === 'writable' || stream._state === 'closing');522 WritableStreamError(stream, e);523 controller._queue = [];524}525// Helper functions for the WritableStream.526function streamBrandCheckException(name) {527 return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);528}529// Helper functions for the WritableStreamDefaultWriter.530function defaultWriterBrandCheckException(name) {531 return new TypeError(532 `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);533}534function defaultWriterLockException(name) {535 return new TypeError('Cannot ' + name + ' a stream using a released writer');536}537function defaultWriterClosedPromiseInitialize(writer) {538 writer._closedPromise = new Promise((resolve, reject) => {539 writer._closedPromise_resolve = resolve;540 writer._closedPromise_reject = reject;541 });542}543function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) {544 writer._closedPromise = Promise.reject(reason);545 writer._closedPromise_resolve = undefined;546 writer._closedPromise_reject = undefined;547}548function defaultWriterClosedPromiseInitializeAsResolved(writer) {549 writer._closedPromise = Promise.resolve(undefined);550 writer._closedPromise_resolve = undefined;551 writer._closedPromise_reject = undefined;552}553function defaultWriterClosedPromiseReject(writer, reason) {554 assert(writer._closedPromise_resolve !== undefined);555 assert(writer._closedPromise_reject !== undefined);556 writer._closedPromise_reject(reason);557 writer._closedPromise_resolve = undefined;...
Using AI Code Generation
1const defaultWriterClosedPromiseInitializeAsRejected = wpt.defaultWriterClosedPromiseInitializeAsRejected;2const writer = new WritableStreamDefaultWriter(stream);3defaultWriterClosedPromiseInitializeAsRejected(writer, reason);4writer.closed.then(5 () => console.log('closed fulfilled'),6 r => console.log(`closed rejected with ${r}`)7);8const defaultWriterClosedPromiseInitializeAsRejected = wpt.defaultWriterClosedPromiseInitializeAsRejected;9const writer = new WritableStreamDefaultWriter(stream);10defaultWriterClosedPromiseInitializeAsRejected(writer, reason);11writer.closed.then(12 () => console.log('closed fulfilled'),13 r => console.log(`closed rejected with ${r}`)14);15const defaultWriterClosedPromiseInitializeAsRejected = wpt.defaultWriterClosedPromiseInitializeAsRejected;16const writer = new WritableStreamDefaultWriter(stream);17defaultWriterClosedPromiseInitializeAsRejected(writer, reason);18writer.closed.then(19 () => console.log('closed fulfilled'),20 r => console.log(`closed rejected with ${r}`)21);22const defaultWriterClosedPromiseInitializeAsRejected = wpt.defaultWriterClosedPromiseInitializeAsRejected;23const writer = new WritableStreamDefaultWriter(stream);24defaultWriterClosedPromiseInitializeAsRejected(writer, reason);25writer.closed.then(26 () => console.log('closed fulfilled'),27 r => console.log(`closed rejected with ${r}`)28);29const defaultWriterClosedPromiseInitializeAsRejected = wpt.defaultWriterClosedPromiseInitializeAsRejected;30const writer = new WritableStreamDefaultWriter(stream);31defaultWriterClosedPromiseInitializeAsRejected(writer, reason);32writer.closed.then(33 () => console.log('closed fulfilled'),34 r => console.log(`closed rejected with ${r}`)35);36const defaultWriterClosedPromiseInitializeAsRejected = wpt.defaultWriterClosedPromiseInitializeAsRejected;37const writer = new WritableStreamDefaultWriter(stream);38defaultWriterClosedPromiseInitializeAsRejected(writer, reason);39writer.closed.then(40 () => console.log('closed fulfilled'),41 r => console.log(`closed rejected with ${r}`)42);
Using AI Code Generation
1import {defaultWriterClosedPromiseInitializeAsRejected} from2"../streams/writable-streams/default-writer-closed-promise-initialize-as-rejected.js";3import {createWritableStream} from "../streams/writable-streams/writable-stream.js";4import {assert_equals} from "../streams/resources/test-utils.js";5let ws = createWritableStream();6let writer = ws.getWriter();7defaultWriterClosedPromiseInitializeAsRejected(writer, new Error("rejected"));8assert_equals(writer.closed._state, "rejected");9assert_equals(writer.closed._value.message, "rejected");
Using AI Code Generation
1import * as wpt from 'web-streams-polyfill/ponyfill/es6';2wpt.defaultWriterClosedPromiseInitializeAsRejected();3import * as wpt from 'web-streams-polyfill/ponyfill/es2018';4wpt.defaultWriterClosedPromiseInitializeAsRejected();5import * as wpt from 'web-streams-polyfill/ponyfill/es2020';6wpt.defaultWriterClosedPromiseInitializeAsRejected();7import * as wpt from 'web-streams-polyfill/ponyfill/es2021';8wpt.defaultWriterClosedPromiseInitializeAsRejected();9import * as wpt from 'web-streams-polyfill/ponyfill/esnext';10wpt.defaultWriterClosedPromiseInitializeAsRejected();11import * as wpt from 'web-streams-polyfill/ponyfill';12wpt.defaultWriterClosedPromiseInitializeAsRejected();13import * as wpt from 'web-streams-polyfill';14wpt.defaultWriterClosedPromiseInitializeAsRejected();
Using AI Code Generation
1import { defaultWriterClosedPromiseInitializeAsRejected } from "./resources/wpt.js";2const writer = new WritableStream().getWriter();3defaultWriterClosedPromiseInitializeAsRejected(writer, new Error("error"));4writer.closed.then(5 () => assert_unreached("closed promise should not fulfill"),6 (e) => assert_equals(e.message, "error")7);8* [Web platform tests](
Using AI Code Generation
1defaultWriterClosedPromiseInitializeAsRejected(writer, new TypeError("error"));2writer.closed.then(() => {3 assert_unreached("writer.closed should be rejected");4}).catch(e => {5 assert_equals(e.name, "TypeError", "writer.closed should be rejected with a TypeError");6});7defaultWriterClosedPromiseInitializeAsRejected(writer, new TypeError("error"));8writer.closed.then(() => {9 assert_unreached("writer.closed should be rejected");10}).catch(e => {11 assert_equals(e.name, "TypeError", "writer.closed should be rejected with a TypeError");12});13promise_test(() => {14 return promise_rejects(t, new TypeError(), writer.closed, 'writer.closed should be rejected');15}, '...');16defaultWriterClosedPromiseInitializeAsRejected(writer, new TypeError("error"));17writer.closed.then(() => {18 assert_unreached("writer.closed should be rejected");19}).catch(e => {20 assert_equals(e.name, "TypeError", "writer.closed should be rejected with a TypeError");21});22promise_test(() => {23 return promise_rejects(t, new TypeError(), writer.closed, 'writer.closed should be rejected');24}, '...');
Using AI Code Generation
1const { defaultWriterClosedPromiseInitializeAsRejected } = require('wpt')2const w = new WritableStream()3const writer = w.getWriter()4defaultWriterClosedPromiseInitializeAsRejected(writer)5writer.closed.then(6 () => console.log('closed'),7 () => console.log('errored')8const { defaultWriterClosedPromiseInitializeAsRejectedWith } = require('wpt')9const w = new WritableStream()10const writer = w.getWriter()11defaultWriterClosedPromiseInitializeAsRejectedWith(writer, new Error('oh no'))12writer.closed.then(13 () => console.log('closed'),14 () => console.log('errored')15const { defaultWriterClosedPromiseInitializeAsResolved } = require('wpt')16const w = new WritableStream()17const writer = w.getWriter()18defaultWriterClosedPromiseInitializeAsResolved(writer)19writer.closed.then(20 () => console.log('closed'),21 () => console.log('errored')22const { defaultWriterReadyPromiseInitializeAsRejected } = require('wpt')23const w = new WritableStream()24const writer = w.getWriter()25defaultWriterReadyPromiseInitializeAsRejected(writer, new Error('oh no'))26writer.ready.then(27 () => console.log('resolved'),28 () => console.log('rejected')29const { defaultWriterReadyPromiseInitializeAsResolved } = require('wpt')30const w = new WritableStream()31const writer = w.getWriter()32defaultWriterReadyPromiseInitializeAsResolved(writer)33writer.ready.then(34 () => console.log('resolved'),35 () => console.log('rejected')
Using AI Code Generation
1'use strict';2var test = async_test(document.title);3var defaultWriterClosedPromise = new WritableStream().getWriter().closed;4test.step(function() {5 defaultWriterClosedPromise.then(test.step_func(function() {6 assert_unreached('closed promise should be rejected');7 }), test.step_func(function(reason) {8 assert_equals(reason.name, 'TypeError', 'closed promise should be rejected with a TypeError');9 })).then(test.step_func(function() {10 test.done();11 }));12});13'use strict';14var test = async_test(document.title);15var defaultWriterClosedPromise = new WritableStream().getWriter().closed;16test.step(function() {17 defaultWriterClosedPromise.then(test.step_func(function() {18 assert_unreached('closed promise should be rejected');19 }), test.step_func(function(reason) {20 assert_equals(reason.name, 'TypeError', 'closed promise should be rejected with a TypeError');21 })).then(test.step_func(function() {22 test.done();23 }));24});25'use strict';26var test = async_test(document.title);27var defaultWriterClosedPromise = new WritableStream().getWriter().closed;28test.step(function() {29 defaultWriterClosedPromise.then(test.step_func(function() {30 assert_unreached('closed promise should be rejected');31 }), test.step_func(function(reason) {32 assert_equals(reason.name, 'TypeError', 'closed promise should be rejected with a TypeError');33 })).then(test.step_func(function() {34 test.done();35 }));36});37'use strict';38var test = async_test(document.title);39var defaultWriterClosedPromise = new WritableStream().getWriter().closed;40test.step(function() {
Using AI Code Generation
1'use strict';2promise_test(() => {3 let defaultWriterClosedPromiseInitializeAsRejected = new WritableStream({4 start(c) {5 c.error();6 }7 }).getWriter().closed;8 return promise_rejects_exactly(9 new TypeError(),10 'closed promise should be rejected with the error that caused the state to become "errored"');11}, 'closed promise should be rejected when the writer is closed and the state is "writable"');
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!