Best JavaScript code snippet using wpt
pipe.ts
Source:pipe.ts
1import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';2import { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';3import { ReadableStreamReaderGenericRelease } from './generic-reader';4import {5 AcquireWritableStreamDefaultWriter,6 IsWritableStream,7 IsWritableStreamLocked,8 WritableStream,9 WritableStreamAbort,10 WritableStreamCloseQueuedOrInFlight,11 WritableStreamDefaultWriterCloseWithErrorPropagation,12 WritableStreamDefaultWriterRelease,13 WritableStreamDefaultWriterWrite14} from '../writable-stream';15import assert from '../../stub/assert';16import {17 newPromise,18 PerformPromiseThen,19 promiseResolvedWith,20 setPromiseIsHandledToTrue,21 uponFulfillment,22 uponPromise,23 uponRejection24} from '../helpers/webidl';25import { noop } from '../../utils';26import { AbortSignal, isAbortSignal } from '../abort-signal';27import { DOMException } from '../../stub/dom-exception';28export function ReadableStreamPipeTo<T>(source: ReadableStream<T>,29 dest: WritableStream<T>,30 preventClose: boolean,31 preventAbort: boolean,32 preventCancel: boolean,33 signal: AbortSignal | undefined): Promise<void> {34 assert(IsReadableStream(source));35 assert(IsWritableStream(dest));36 assert(typeof preventClose === 'boolean');37 assert(typeof preventAbort === 'boolean');38 assert(typeof preventCancel === 'boolean');39 assert(signal === undefined || isAbortSignal(signal));40 assert(!IsReadableStreamLocked(source));41 assert(!IsWritableStreamLocked(dest));42 const reader = AcquireReadableStreamDefaultReader<T>(source);43 const writer = AcquireWritableStreamDefaultWriter<T>(dest);44 source._disturbed = true;45 let shuttingDown = false;46 // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.47 let currentWrite = promiseResolvedWith<void>(undefined);48 return newPromise((resolve, reject) => {49 let abortAlgorithm: () => void;50 if (signal !== undefined) {51 abortAlgorithm = () => {52 const error = new DOMException('Aborted', 'AbortError');53 const actions: Array<() => Promise<void>> = [];54 if (!preventAbort) {55 actions.push(() => {56 if (dest._state === 'writable') {57 return WritableStreamAbort(dest, error);58 }59 return promiseResolvedWith(undefined);60 });61 }62 if (!preventCancel) {63 actions.push(() => {64 if (source._state === 'readable') {65 return ReadableStreamCancel(source, error);66 }67 return promiseResolvedWith(undefined);68 });69 }70 shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);71 };72 if (signal.aborted) {73 abortAlgorithm();74 return;75 }76 signal.addEventListener('abort', abortAlgorithm);77 }78 // Using reader and writer, read all chunks from this and write them to dest79 // - Backpressure must be enforced80 // - Shutdown must stop all activity81 function pipeLoop() {82 return newPromise<void>((resolveLoop, rejectLoop) => {83 function next(done: boolean) {84 if (done) {85 resolveLoop();86 } else {87 // Use `PerformPromiseThen` instead of `uponPromise` to avoid88 // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers89 PerformPromiseThen(pipeStep(), next, rejectLoop);90 }91 }92 next(false);93 });94 }95 function pipeStep(): Promise<boolean> {96 if (shuttingDown) {97 return promiseResolvedWith(true);98 }99 return PerformPromiseThen(writer._readyPromise, () => {100 return newPromise<boolean>((resolveRead, rejectRead) => {101 ReadableStreamDefaultReaderRead(102 reader,103 {104 _chunkSteps: chunk => {105 currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);106 resolveRead(false);107 },108 _closeSteps: () => resolveRead(true),109 _errorSteps: rejectRead110 }111 );112 });113 });114 }115 // Errors must be propagated forward116 isOrBecomesErrored(source, reader._closedPromise, storedError => {117 if (!preventAbort) {118 shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);119 } else {120 shutdown(true, storedError);121 }122 });123 // Errors must be propagated backward124 isOrBecomesErrored(dest, writer._closedPromise, storedError => {125 if (!preventCancel) {126 shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);127 } else {128 shutdown(true, storedError);129 }130 });131 // Closing must be propagated forward132 isOrBecomesClosed(source, reader._closedPromise, () => {133 if (!preventClose) {134 shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));135 } else {136 shutdown();137 }138 });139 // Closing must be propagated backward140 if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {141 const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');142 if (!preventCancel) {143 shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);144 } else {145 shutdown(true, destClosed);146 }147 }148 setPromiseIsHandledToTrue(pipeLoop());149 function waitForWritesToFinish(): Promise<void> {150 // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait151 // for that too.152 const oldCurrentWrite = currentWrite;153 return PerformPromiseThen(154 currentWrite,155 () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined156 );157 }158 function isOrBecomesErrored(stream: ReadableStream | WritableStream,159 promise: Promise<void>,160 action: (reason: any) => void) {161 if (stream._state === 'errored') {162 action(stream._storedError);163 } else {164 uponRejection(promise, action);165 }166 }167 function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise<void>, action: () => void) {168 if (stream._state === 'closed') {169 action();170 } else {171 uponFulfillment(promise, action);172 }173 }174 function shutdownWithAction(action: () => Promise<unknown>, originalIsError?: boolean, originalError?: any) {175 if (shuttingDown) {176 return;177 }178 shuttingDown = true;179 if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {180 uponFulfillment(waitForWritesToFinish(), doTheRest);181 } else {182 doTheRest();183 }184 function doTheRest() {185 uponPromise(186 action(),187 () => finalize(originalIsError, originalError),188 newError => finalize(true, newError)189 );190 }191 }192 function shutdown(isError?: boolean, error?: any) {193 if (shuttingDown) {194 return;195 }196 shuttingDown = true;197 if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {198 uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));199 } else {200 finalize(isError, error);201 }202 }203 function finalize(isError?: boolean, error?: any) {204 WritableStreamDefaultWriterRelease(writer);205 ReadableStreamReaderGenericRelease(reader);206 if (signal !== undefined) {207 signal.removeEventListener('abort', abortAlgorithm);208 }209 if (isError) {210 reject(error);211 } else {212 resolve(undefined);213 }214 }215 });...
writable_stream.ts
Source:writable_stream.ts
1// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.2import {3 AbortRequest,4 acquireWritableStreamDefaultWriter,5 Deferred,6 initializeWritableStream,7 isWritableStream,8 isWritableStreamLocked,9 makeSizeAlgorithmFromSizeFunction,10 setFunctionName,11 setUpWritableStreamDefaultControllerFromUnderlyingSink,12 writableStreamAbort,13 writableStreamClose,14 writableStreamCloseQueuedOrInFlight,15 validateAndNormalizeHighWaterMark,16} from "./internals.ts";17import * as sym from "./symbols.ts";18import { WritableStreamDefaultControllerImpl } from "./writable_stream_default_controller.ts";19import { WritableStreamDefaultWriterImpl } from "./writable_stream_default_writer.ts";20import { customInspect } from "../console.ts";21// eslint-disable-next-line @typescript-eslint/no-explicit-any22export class WritableStreamImpl<W = any> implements WritableStream<W> {23 [sym.backpressure]: boolean;24 [sym.closeRequest]?: Deferred<void>;25 [sym.inFlightWriteRequest]?: Required<Deferred<void>>;26 [sym.inFlightCloseRequest]?: Deferred<void>;27 [sym.pendingAbortRequest]?: AbortRequest;28 [sym.state]: "writable" | "closed" | "erroring" | "errored";29 // eslint-disable-next-line @typescript-eslint/no-explicit-any30 [sym.storedError]?: any;31 [sym.writableStreamController]?: WritableStreamDefaultControllerImpl<W>;32 [sym.writer]?: WritableStreamDefaultWriterImpl<W>;33 [sym.writeRequests]: Array<Required<Deferred<void>>>;34 constructor(35 underlyingSink: UnderlyingSink = {},36 strategy: QueuingStrategy = {}37 ) {38 initializeWritableStream(this);39 const size = strategy.size;40 let highWaterMark = strategy.highWaterMark ?? 1;41 const { type } = underlyingSink;42 if (type !== undefined) {43 throw new RangeError(`Sink type of "${String(type)}" not supported.`);44 }45 const sizeAlgorithm = makeSizeAlgorithmFromSizeFunction(size);46 highWaterMark = validateAndNormalizeHighWaterMark(highWaterMark);47 setUpWritableStreamDefaultControllerFromUnderlyingSink(48 this,49 underlyingSink,50 highWaterMark,51 sizeAlgorithm52 );53 }54 get locked(): boolean {55 if (!isWritableStream(this)) {56 throw new TypeError("Invalid WritableStream.");57 }58 return isWritableStreamLocked(this);59 }60 // eslint-disable-next-line @typescript-eslint/no-explicit-any61 abort(reason: any): Promise<void> {62 if (!isWritableStream(this)) {63 return Promise.reject(new TypeError("Invalid WritableStream."));64 }65 if (isWritableStreamLocked(this)) {66 return Promise.reject(67 new TypeError("Cannot abort a locked WritableStream.")68 );69 }70 return writableStreamAbort(this, reason);71 }72 close(): Promise<void> {73 if (!isWritableStream(this)) {74 return Promise.reject(new TypeError("Invalid WritableStream."));75 }76 if (isWritableStreamLocked(this)) {77 return Promise.reject(78 new TypeError("Cannot abort a locked WritableStream.")79 );80 }81 if (writableStreamCloseQueuedOrInFlight(this)) {82 return Promise.reject(83 new TypeError("Cannot close an already closing WritableStream.")84 );85 }86 return writableStreamClose(this);87 }88 getWriter(): WritableStreamDefaultWriter<W> {89 if (!isWritableStream(this)) {90 throw new TypeError("Invalid WritableStream.");91 }92 return acquireWritableStreamDefaultWriter(this);93 }94 [customInspect](): string {95 return `${this.constructor.name} { locked: ${String(this.locked)} }`;96 }97}...
Using AI Code Generation
1var rs = new ReadableStream({2 start(controller) {3 controller.enqueue('a');4 controller.enqueue('b');5 controller.close();6 }7});8var writer = rs.getWritableStreamDefaultWriter();9writer.releaseLock();10var rs = new ReadableStream({11 start(controller) {12 controller.enqueue('a');13 controller.enqueue('b');14 controller.close();15 }16});17var writer = rs.getWritableStreamDefaultWriter();18writer.releaseLock();19var rs = new ReadableStream({20 start(controller) {21 controller.enqueue('a');22 controller.enqueue('b');23 controller.close();24 }25});26var writer = rs.getWritableStreamDefaultWriter();27writer.releaseLock();28var rs = new ReadableStream({29 start(controller) {30 controller.enqueue('a');31 controller.enqueue('b');32 controller.close();33 }34});35var writer = rs.getWritableStreamDefaultWriter();36writer.releaseLock();37var rs = new ReadableStream({38 start(controller) {39 controller.enqueue('a');40 controller.enqueue('b');41 controller.close();42 }43});44var writer = rs.getWritableStreamDefaultWriter();45writer.releaseLock();
Using AI Code Generation
1import { AcquireWritableStreamDefaultWriter } from 'streams/writable-streams/default-writer.js';2export const writableStream = new WritableStream({3 write() {}4});5export const writer = AcquireWritableStreamDefaultWriter(writableStream);6### Constructor: new WritableStream(underlyingSink=, { size, highWaterMark }=)7* `underlyingSink` — An object representing the underlying sink with methods and properties that define how the constructed stream instance will behave. The following methods are the bare-minimum required: `start(controller)`, `write(chunk, controller)`. It can also contain the following optional methods: `abort(reason)`, `close(controller)`. If a `type` property is provided, it should be set to `"bytes"`. The `controller` parameter passed to some of the following methods is a8### writable.abort(reason)9### writable.close()
Using AI Code Generation
1'use strict';2const { WritableStream } = require('stream/web');3const { AcquireWritableStreamDefaultWriter } = WritableStream;4const w = new WritableStream({5 write(chunk) {6 console.log(chunk);7 }8});9const writer = AcquireWritableStreamDefaultWriter(w);10'use strict';11const { WritableStream } = require('stream/web');12const { AcquireWritableStreamDefaultWriter } = WritableStream;13const w = new WritableStream({14 write(chunk) {15 console.log(chunk);16 }17});18const writer = AcquireWritableStreamDefaultWriter(w);19'use strict';20const { WritableStream } = require('stream/web');21const { AcquireWritableStreamDefaultWriter, WritableStreamDefaultWriterGetDesiredSize } = WritableStream;22const w = new WritableStream({23 write(chunk) {24 console.log(chunk);25 }26});27const writer = AcquireWritableStreamDefaultWriter(w);28console.log(WritableStreamDefaultWriterGetDesiredSize(writer));29'use strict';30const { WritableStream } = require('stream/web');31const { AcquireWritableStreamDefaultWriter, WritableStreamDefaultWriterClose, WritableStreamDefaultWriterReleaseLock } = WritableStream;32const w = new WritableStream({33 write(chunk) {34 console.log(chunk);35 }36});37const writer = AcquireWritableStreamDefaultWriter(w);38WritableStreamDefaultWriterClose(writer).then(() => {39 console.log('closed');40 WritableStreamDefaultWriterReleaseLock(writer);41});42'use strict';43const { WritableStream } = require('stream/web');44const { AcquireWritableStreamDefaultWriter, WritableStreamDefaultWriterReleaseLock } = WritableStream;45const w = new WritableStream({46 write(chunk) {47 console.log(chunk);48 }49});50const writer = AcquireWritableStreamDefaultWriter(w);51WritableStreamDefaultWriterReleaseLock(writer);52'use strict';53const { WritableStream } = require('stream/web');54const { AcquireWritableStreamDefaultWriter, Writable
Using AI Code Generation
1var readableStream = new ReadableStream({2 start(controller) {3 controller.enqueue('a');4 controller.enqueue('b');5 controller.enqueue('c');6 }7});8var writer = readableStream.getReader();9var firstRead = writer.read();10var secondRead = writer.read();11var thirdRead = writer.read();12firstRead.then(result => {13});14secondRead.then(result => {15});16thirdRead.then(result => {17});
Using AI Code Generation
1const {WritableStream, WritableStreamDefaultWriter, AcquireWritableStreamDefaultWriter} = require('stream/web');2const {isWritableStream, isWritableStreamDefaultWriter, isWritableStreamLocked} = require('stream/web');3const writer = AcquireWritableStreamDefaultWriter(new WritableStream());4const {WritableStream, WritableStreamDefaultWriter, AcquireWritableStreamDefaultWriter} = require('stream/web');5const {isWritableStream, isWritableStreamDefaultWriter, isWritableStreamLocked} = require('stream/web');6const writer = AcquireWritableStreamDefaultWriter(new WritableStream());7const {WritableStream, WritableStreamDefaultWriter, AcquireWritableStreamDefaultWriter} = require('stream/web');8const {isWritableStream, isWritableStreamDefaultWriter, isWritableStreamLocked} = require('stream/web');9const writer = AcquireWritableStreamDefaultWriter(new WritableStream());10const {11} = primordials;12const {13 codes: {14 },15} = require('internal/errors');16const { Buffer } = require('buffer');17const { isArrayBufferView } = require('internal/util/types');18const { isUint8Array } = require('internal/util/types');19const { MathFloor, MathMax } = primordials;20const { getOptionValue } = require('internal/options');21const {22} = require('internal/util');23const { validateAbortSignal } = require('internal/validators');24const {25} = require('internal/util');26const {
Using AI Code Generation
1var writer = AcquireWritableStreamDefaultWriter(stream);2assert_throws(new TypeError(), function() {3 AcquireWritableStreamDefaultWriter(stream);4}, 'AcquireWritableStreamDefaultWriter should throw a TypeError when stream is not a WritableStream');5var writer = AcquireWritableStreamDefaultWriter(stream);6assert_equals(writer.constructor.name, "WritableStreamDefaultWriter", "AcquireWritableStreamDefaultWriter should return a WritableStreamDefaultWriter object");7var writer = AcquireWritableStreamDefaultWriter(stream);8assert_equals(writer.stream, stream, "AcquireWritableStreamDefaultWriter should return a WritableStreamDefaultWriter object whose stream property is the stream argument");9var writer = AcquireWritableStreamDefaultWriter(stream);10assert_equals(writer.closed, stream.closed, "AcquireWritableStreamDefaultWriter should return a WritableStreamDefaultWriter object whose closed promise property is the closed promise of the stream argument");11var writer = AcquireWritableStreamDefaultWriter(stream);12assert_equals(writer.ready, stream.ready, "AcquireWritableStreamDefaultWriter should return a WritableStreamDefaultWriter object whose ready promise property is the ready promise of the stream argument");13var writer = AcquireWritableStreamDefaultWriter(stream);14assert_equals(writer.desiredSize, stream.desiredSize, "AcquireWritableStreamDefaultWriter should return a WritableStreamDefaultWriter object whose desiredSize property is the desiredSize property of the stream argument");15var writer = AcquireWritableStreamDefaultWriter(stream);16assert_equals(writer.state, stream.state, "AcquireWritableStreamDefaultWriter should return a WritableStreamDefault
Using AI Code Generation
1var writer = stream.AcquireWritableStreamDefaultWriter();2writer.WriteWithLock("hello world");3const writer = stream.AcquireWritableStreamDefaultWriter();4writer.WriteWithLock(chunk);5writer.CloseWithLock();6writer.AbortWithLock(reason);7writer.ReleaseLock();8const reader = stream.AcquireReadableStreamDefaultReader();9const result = reader.ReadWithLock();10reader.CancelWithLock(reason);11reader.ReleaseLock();12const controller = stream.AcquireTransformStreamDefaultController();13controller.EnqueueWithLock(chunk);14controller.ErrorWithLock(error);15controller.TerminateWithLock();16controller.ReleaseLock();17const strategy = new ByteLengthQueuingStrategy({18});19const strategy = new CountQueuingStrategy({20});21const controller = stream.AcquireWritableStreamDefaultController();22controller.ErrorWithLock(error);23controller.TerminateWithLock();24controller.ReleaseLock();25const controller = stream.AcquireReadableStreamDefaultController();26controller.EnqueueWithLock(chunk);
Using AI Code Generation
1const file = new File(["foo"], "foo.txt", {type: "text/plain"});2const writer = file.stream().getWriter();3writer.write("bar");4writer.close();5`const reader = stream.AcquireReadableStreamDefaultReader();`6const file = new File(["foo"], "foo.txt", {type: "text/plain"});7const reader = file.stream().getReader();8reader.read().then(result => console.log(result));9`const reader = stream.AcquireReadableStreamBYOBReader();`10const file = new File(["foo"], "foo.txt", {type: "text/plain"});11const reader = file.stream().getReader({mode: "byob"});12const buffer = new ArrayBuffer(1);13reader.read(buffer).then(result => console.log(result));
Using AI Code Generation
1const writer = writable.getWriter();2writer.write("a");3writer.close();4writer.closed.then(() => console.log("closed!"));5### WritableStreamDefaultWriter.releaseLock()6const writer = writable.getWriter();7writer.releaseLock();8### WritableStreamDefaultWriter.write(chunk)9const writer = writable.getWriter();10const writePromise = writer.write("a");11writePromise.then(() => console.log("The first write completed."));12writer.write("b");13writer.write("c");14`const reader = stream.AcquireReadableStreamDefaultReader();`15const file = new File(["foo"], "foo.txt", {type: "text/plain"});16const reader = file.stream().getReader();17reader.read().then(result => console.log(result));18`const reader = stream.AcquireReadableStreamBYOBReader();`19const file = new File(["foo"], "foo.txt", {type: "text/plain"});20const reader = file.stream().getReader({mode: "byob"});21const buffer = new ArrayBuffer(1);22reader.read(buffer).then(result => console.log(result));
Using AI Code Generation
1const writer = writable.getWriter();2writer.write("a");3writer.close();4writer.closed.then(() => console.log("closed!"));5### WritableStreamDefaultWriter.releaseLock()6const writer = writable.getWriter();7writer.releaseLock();8### WritableStreamDefaultWriter.write(chunk)9const writer = writable.getWriter();10const writePromise = writer.write("a");11writePromise.then(() => console.log("The first write completed."));12writer.write("b");13writer.write("c");
Using AI Code Generation
1const writer = writable.getWriter();2writer.write("a");3writer.close();4writer.closed.then(() => console.log("closed!"));5### WritableStreamDefaultWriter.releaseLock()6const writer = writable.getWriter();7writer.releaseLock();8### WritableStreamDefaultWriter.write(chunk)9const writer = writable.getWriter();10const writePromise = writer.write("a");11writePromise.then(() => console.log("The first write completed."));12writer.write("b");13writer.write("c");14controller.ErrorWithLock(error);15controller.TerminateWithLock();16controller.ReleaseLock();17const controller = stream.AcquireReadableStreamDefaultController();18controller.EnqueueWithLock(chunk);
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!!