Best JavaScript code snippet using wpt
22_body.js
Source:22_body.js
1// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.2// @ts-check3/// <reference path="../webidl/internal.d.ts" />4/// <reference path="../url/internal.d.ts" />5/// <reference path="../url/lib.deno_url.d.ts" />6/// <reference path="../web/internal.d.ts" />7/// <reference path="../file/internal.d.ts" />8/// <reference path="../file/lib.deno_file.d.ts" />9/// <reference path="./internal.d.ts" />10/// <reference path="./11_streams_types.d.ts" />11/// <reference path="./lib.deno_fetch.d.ts" />12/// <reference lib="esnext" />13"use strict";14((window) => {15 const core = window.Deno.core;16 const webidl = globalThis.__bootstrap.webidl;17 const { parseUrlEncoded } = globalThis.__bootstrap.url;18 const { parseFormData, formDataFromEntries, encodeFormData } =19 globalThis.__bootstrap.formData;20 const mimesniff = globalThis.__bootstrap.mimesniff;21 const { isReadableStreamDisturbed, errorReadableStream } =22 globalThis.__bootstrap.streams;23 class InnerBody {24 /** @type {ReadableStream<Uint8Array> | { body: Uint8Array, consumed: boolean }} */25 streamOrStatic;26 /** @type {null | Uint8Array | Blob | FormData} */27 source = null;28 /** @type {null | number} */29 length = null;30 /**31 * @param {ReadableStream<Uint8Array> | { body: Uint8Array, consumed: boolean }} stream32 */33 constructor(stream) {34 this.streamOrStatic = stream ??35 { body: new Uint8Array(), consumed: false };36 }37 get stream() {38 if (!(this.streamOrStatic instanceof ReadableStream)) {39 const { body, consumed } = this.streamOrStatic;40 this.streamOrStatic = new ReadableStream({41 start(controller) {42 controller.enqueue(body);43 controller.close();44 },45 });46 if (consumed) {47 this.streamOrStatic.cancel();48 }49 }50 return this.streamOrStatic;51 }52 /**53 * https://fetch.spec.whatwg.org/#body-unusable54 * @returns {boolean}55 */56 unusable() {57 if (this.streamOrStatic instanceof ReadableStream) {58 return this.streamOrStatic.locked ||59 isReadableStreamDisturbed(this.streamOrStatic);60 }61 return this.streamOrStatic.consumed;62 }63 /**64 * @returns {boolean}65 */66 consumed() {67 if (this.streamOrStatic instanceof ReadableStream) {68 return isReadableStreamDisturbed(this.streamOrStatic);69 }70 return this.streamOrStatic.consumed;71 }72 /**73 * https://fetch.spec.whatwg.org/#concept-body-consume-body74 * @returns {Promise<Uint8Array>}75 */76 async consume() {77 if (this.unusable()) throw new TypeError("Body already consumed.");78 if (this.streamOrStatic instanceof ReadableStream) {79 const reader = this.stream.getReader();80 /** @type {Uint8Array[]} */81 const chunks = [];82 let totalLength = 0;83 while (true) {84 const { value: chunk, done } = await reader.read();85 if (done) break;86 chunks.push(chunk);87 totalLength += chunk.byteLength;88 }89 const finalBuffer = new Uint8Array(totalLength);90 let i = 0;91 for (const chunk of chunks) {92 finalBuffer.set(chunk, i);93 i += chunk.byteLength;94 }95 return finalBuffer;96 } else {97 this.streamOrStatic.consumed = true;98 return this.streamOrStatic.body;99 }100 }101 cancel(error) {102 if (this.streamOrStatic instanceof ReadableStream) {103 this.streamOrStatic.cancel(error);104 } else {105 this.streamOrStatic.consumed = true;106 }107 }108 error(error) {109 if (this.streamOrStatic instanceof ReadableStream) {110 errorReadableStream(this.streamOrStatic, error);111 } else {112 this.streamOrStatic.consumed = true;113 }114 }115 /**116 * @returns {InnerBody}117 */118 clone() {119 const [out1, out2] = this.stream.tee();120 this.streamOrStatic = out1;121 const second = new InnerBody(out2);122 second.source = core.deserialize(core.serialize(this.source));123 second.length = this.length;124 return second;125 }126 }127 /**128 * @param {any} prototype129 * @param {symbol} bodySymbol130 * @param {symbol} mimeTypeSymbol131 * @returns {void}132 */133 function mixinBody(prototype, bodySymbol, mimeTypeSymbol) {134 function consumeBody(object) {135 if (object[bodySymbol] !== null) {136 return object[bodySymbol].consume();137 }138 return Promise.resolve(new Uint8Array());139 }140 /** @type {PropertyDescriptorMap} */141 const mixin = {142 body: {143 /**144 * @returns {ReadableStream<Uint8Array> | null}145 */146 get() {147 webidl.assertBranded(this, prototype);148 if (this[bodySymbol] === null) {149 return null;150 } else {151 return this[bodySymbol].stream;152 }153 },154 configurable: true,155 enumerable: true,156 },157 bodyUsed: {158 /**159 * @returns {boolean}160 */161 get() {162 webidl.assertBranded(this, prototype);163 if (this[bodySymbol] !== null) {164 return this[bodySymbol].consumed();165 }166 return false;167 },168 configurable: true,169 enumerable: true,170 },171 arrayBuffer: {172 /** @returns {Promise<ArrayBuffer>} */173 value: async function arrayBuffer() {174 webidl.assertBranded(this, prototype);175 const body = await consumeBody(this);176 return packageData(body, "ArrayBuffer");177 },178 writable: true,179 configurable: true,180 enumerable: true,181 },182 blob: {183 /** @returns {Promise<Blob>} */184 value: async function blob() {185 webidl.assertBranded(this, prototype);186 const body = await consumeBody(this);187 return packageData(body, "Blob", this[mimeTypeSymbol]);188 },189 writable: true,190 configurable: true,191 enumerable: true,192 },193 formData: {194 /** @returns {Promise<FormData>} */195 value: async function formData() {196 webidl.assertBranded(this, prototype);197 const body = await consumeBody(this);198 return packageData(body, "FormData", this[mimeTypeSymbol]);199 },200 writable: true,201 configurable: true,202 enumerable: true,203 },204 json: {205 /** @returns {Promise<any>} */206 value: async function json() {207 webidl.assertBranded(this, prototype);208 const body = await consumeBody(this);209 return packageData(body, "JSON");210 },211 writable: true,212 configurable: true,213 enumerable: true,214 },215 text: {216 /** @returns {Promise<string>} */217 value: async function text() {218 webidl.assertBranded(this, prototype);219 const body = await consumeBody(this);220 return packageData(body, "text");221 },222 writable: true,223 configurable: true,224 enumerable: true,225 },226 };227 return Object.defineProperties(prototype.prototype, mixin);228 }229 /**230 * https://fetch.spec.whatwg.org/#concept-body-package-data231 * @param {Uint8Array} bytes232 * @param {"ArrayBuffer" | "Blob" | "FormData" | "JSON" | "text"} type233 * @param {MimeType | null} [mimeType]234 */235 function packageData(bytes, type, mimeType) {236 switch (type) {237 case "ArrayBuffer":238 return bytes.buffer;239 case "Blob":240 return new Blob([bytes], {241 type: mimeType !== null ? mimesniff.serializeMimeType(mimeType) : "",242 });243 case "FormData": {244 if (mimeType !== null) {245 if (mimeType !== null) {246 const essence = mimesniff.essence(mimeType);247 if (essence === "multipart/form-data") {248 const boundary = mimeType.parameters.get("boundary");249 if (boundary === null) {250 throw new TypeError(251 "Missing boundary parameter in mime type of multipart formdata.",252 );253 }254 return parseFormData(bytes, boundary);255 } else if (essence === "application/x-www-form-urlencoded") {256 const entries = parseUrlEncoded(bytes);257 return formDataFromEntries(258 entries.map((x) => ({ name: x[0], value: x[1] })),259 );260 }261 }262 throw new TypeError("Invalid form data");263 }264 throw new TypeError("Missing content type");265 }266 case "JSON":267 return JSON.parse(core.decode(bytes));268 case "text":269 return core.decode(bytes);270 }271 }272 /**273 * @param {BodyInit} object274 * @returns {{body: InnerBody, contentType: string | null}}275 */276 function extractBody(object) {277 /** @type {ReadableStream<Uint8Array> | { body: Uint8Array, consumed: boolean }} */278 let stream;279 let source = null;280 let length = null;281 let contentType = null;282 if (object instanceof Blob) {283 stream = object.stream();284 source = object;285 length = object.size;286 if (object.type.length !== 0) {287 contentType = object.type;288 }289 } else if (ArrayBuffer.isView(object) || object instanceof ArrayBuffer) {290 const u8 = ArrayBuffer.isView(object)291 ? new Uint8Array(292 object.buffer,293 object.byteOffset,294 object.byteLength,295 )296 : new Uint8Array(object);297 const copy = u8.slice(0, u8.byteLength);298 source = copy;299 } else if (object instanceof FormData) {300 const res = encodeFormData(object);301 stream = { body: res.body, consumed: false };302 source = object;303 length = res.body.byteLength;304 contentType = res.contentType;305 } else if (object instanceof URLSearchParams) {306 source = core.encode(object.toString());307 contentType = "application/x-www-form-urlencoded;charset=UTF-8";308 } else if (typeof object === "string") {309 source = core.encode(object);310 contentType = "text/plain;charset=UTF-8";311 } else if (object instanceof ReadableStream) {312 stream = object;313 if (object.locked || isReadableStreamDisturbed(object)) {314 throw new TypeError("ReadableStream is locked or disturbed");315 }316 }317 if (source instanceof Uint8Array) {318 stream = { body: source, consumed: false };319 length = source.byteLength;320 }321 const body = new InnerBody(stream);322 body.source = source;323 body.length = length;324 return { body, contentType };325 }326 webidl.converters["BodyInit"] = (V, opts) => {327 // Union for (ReadableStream or Blob or ArrayBufferView or ArrayBuffer or FormData or URLSearchParams or USVString)328 if (V instanceof ReadableStream) {329 // TODO(lucacasonato): ReadableStream is not branded330 return V;331 } else if (V instanceof Blob) {332 return webidl.converters["Blob"](V, opts);333 } else if (V instanceof FormData) {334 return webidl.converters["FormData"](V, opts);335 } else if (V instanceof URLSearchParams) {336 // TODO(lucacasonato): URLSearchParams is not branded337 return V;338 }339 if (typeof V === "object") {340 if (V instanceof ArrayBuffer || V instanceof SharedArrayBuffer) {341 return webidl.converters["ArrayBuffer"](V, opts);342 }343 if (ArrayBuffer.isView(V)) {344 return webidl.converters["ArrayBufferView"](V, opts);345 }346 }347 return webidl.converters["USVString"](V, opts);348 };349 webidl.converters["BodyInit?"] = webidl.createNullableConverter(350 webidl.converters["BodyInit"],351 );352 window.__bootstrap.fetchBody = { mixinBody, InnerBody, extractBody };...
Using AI Code Generation
1const assert = require('assert');2const { ReadableStream, IsReadableStreamDisturbed } = require('stream/web');3const rs = new ReadableStream({4 start(controller) {5 controller.enqueue('a');6 controller.enqueue('b');7 controller.enqueue('c');8 }9});10const reader = rs.getReader();11assert.strictEqual(IsReadableStreamDisturbed(rs), false);12assert.strictEqual(IsReadableStreamDisturbed(reader), false);13reader.read().then(() => {14 assert.strictEqual(IsReadableStreamDisturbed(rs), true);15 assert.strictEqual(IsReadableStreamDisturbed(reader), true);16 console.log('done');17});
Using AI Code Generation
1const { ReadableStream } = require('stream/web');2const rs = new ReadableStream({3 start(controller) {4 controller.enqueue('a');5 controller.enqueue('b');6 controller.close();7 }8});9const { ReadableStream, CountQueuingStrategy } = require('stream/web');10const rs = new ReadableStream({11 start(controller) {12 controller.enqueue('a');13 controller.enqueue('b');14 controller.close();15 }16}, new CountQueuingStrategy({ highWaterMark: 1 }));17const { ReadableStream, CountQueuingStrategy } = require('stream/web');18const rs = new ReadableStream({19 start(controller) {20 controller.enqueue('a');21 controller.enqueue('b');22 controller.close();23 }24}, new CountQueuingStrategy({ highWaterMark: 1 }));25const reader = rs.getReader();26const { ReadableStream, CountQueuingStrategy } = require('stream/web');27const rs = new ReadableStream({28 start(controller) {29 controller.enqueue('a');30 controller.enqueue('b');31 controller.close();32 }33}, new CountQueuingStrategy({ highWaterMark: 1 }));34const reader = rs.getReader();35const { ReadableStream, CountQueuingStrategy } = require('stream/web');36const rs = new ReadableStream({37 start(controller) {38 controller.enqueue('a');39 controller.enqueue('b
Using AI Code Generation
1const { IsReadableStreamDisturbed } = require('stream/web');2const { ReadableStream } = require('stream/web');3const rs = new ReadableStream({4 start(controller) {5 controller.enqueue('a');6 controller.enqueue('b');7 controller.enqueue('c');8 },9 pull(controller) {10 console.log(controller.desiredSize);11 controller.close();12 },13});14const reader = rs.getReader({ mode: 'byob' });15const read = async () => {16 const { value, done } = await reader.read(new Uint8Array(4));17 console.log(value);18 console.log(done);19}20read();21console.log(IsReadableStreamDisturbed(rs));22> const { IsReadableStreamDisturbed } = require('stream/web');23> const { ReadableStream } = require('stream/web');24> const rs = new ReadableStream({25> start(controller) {26> controller.enqueue('a');27> controller.enqueue('b');28> controller.enqueue('c');29> },30> pull(controller) {31> console.log(controller.desiredSize);32> controller.close();33> },34> });35> const reader = rs.getReader({ mode: 'byob' });36> const read = async () => {37> const { value, done } = await reader.read(new Uint8Array(4));38> console.log(value);39> console.log(done);40> }41> read();42> console.log(IsReadableStreamDisturbed(rs));43Uint8Array(3) [ 97, 98, 99 ]
Using AI Code Generation
1const assert = require('assert');2const { ReadableStream } = require('stream/web');3const { IsReadableStreamDisturbed } = require('internal/webstreams/readablestream');4const readable = new ReadableStream({5 start(c) {6 c.enqueue('a');7 c.enqueue('b');8 c.close();9 }10});11readable.getReader().read().then(console.log);12readable.getReader().read().then(console.log);13assert.strictEqual(IsReadableStreamDisturbed(readable), true);14const assert = require('assert');15const { ReadableStream } = require('stream/web');16const { IsReadableStreamLocked } = require('internal/webstreams/readablestream');17const readable = new ReadableStream({18 start(c) {19 c.enqueue('a');20 c.enqueue('b');21 c.close();22 }23});24assert.strictEqual(IsReadableStreamLocked(readable), false);25const reader = readable.getReader();26assert.strictEqual(IsReadableStreamLocked(readable), true);27reader.releaseLock();28assert.strictEqual(IsReadableStreamLocked(readable), false);29const assert = require('assert');30const { ReadableStream, isReadableStreamDefaultReader } = require('stream/web');31const { IsReadableStreamDefaultReader } = require('internal/webstreams/readablestream');32const readable = new ReadableStream({33 start(c) {34 c.enqueue('a');35 c.enqueue('b');36 c.close();37 }38});39const reader = readable.getReader();40assert.strictEqual(isReadableStreamDefaultReader(reader), true);41assert.strictEqual(IsReadableStreamDefaultReader(reader), true);42const assert = require('assert');43const { ReadableStream, isReadableStreamBYOBReader } = require('stream/web');44const { IsReadableStreamBYOBReader } = require('internal/webstreams/readablestream');45const readable = new ReadableStream({46 start(c) {47 const buffer = Buffer.from('abc');48 c.enqueue(buffer);49 c.close();50 }51});52const reader = readable.getReader({ mode: 'byob' });53assert.strictEqual(isReadableStreamBYOBReader(reader), true);54assert.strictEqual(IsReadableStreamBYOBReader(reader), true);
Using AI Code Generation
1const assert = require("assert");2const { IsReadableStreamDisturbed } = require("./disturbed.js");3const { ReadableStream } = require("stream/web");4const rs = new ReadableStream();5assert.strictEqual(IsReadableStreamDisturbed(rs), false);6rs.cancel();7assert.strictEqual(IsReadableStreamDisturbed(rs), true);8const {9} = require("stream/web");10const {11} = require("internal/webstreams/readablestream");12module.exports.IsReadableStreamDisturbed = function IsReadableStreamDisturbed(stream) {13 if (stream === undefined) {14 return false;15 }16 return stream[kState].disturbed;17};
Using AI Code Generation
1const { IsReadableStreamDisturbed } = require('stream/web');2const { ReadableStream } = require('stream/web');3const rs = new ReadableStream();4console.log(IsReadableStreamDisturbed(rs));5const { IsReadableStreamDisturbed } = require('web-streams-polyfill/ponyfill');6const { ReadableStream } = require('web-streams-polyfill/ponyfill');7const rs = new ReadableStream();8console.log(IsReadableStreamDisturbed(rs));9const { Readable } = require('stream');10const rs = new Readable();11console.log(rs.readableEnded);
Using AI Code Generation
1var rs = new ReadableStream({2 start(controller) {3 controller.enqueue("a");4 controller.close();5 }6});7var reader = rs.getReader();8var result = reader.read();9result.then(function(result) {10 console.log(result);11 var isDisturbed = rs.isDisturbed;12 console.log(isDisturbed);13});14var rs = new ReadableStream({15 start(controller) {16 controller.enqueue("a");17 controller.close();18 }19});20var reader = rs.getReader();21var result = reader.read();22result.then(function(result) {23 console.log(result);24 var isDisturbed = rs.isDisturbed;25 console.log(isDisturbed);26});27var rs = new ReadableStream({28 start(controller) {29 controller.enqueue("a");30 controller.close();31 }32});33var reader = rs.getReader();34var result = reader.read();35result.then(function(result) {36 console.log(result);37 var isDisturbed = rs.isDisturbed;38 console.log(isDisturbed);39});40var rs = new ReadableStream({41 start(controller) {42 controller.enqueue("a");43 controller.close();44 }45});46var reader = rs.getReader();47var result = reader.read();48result.then(function(result) {49 console.log(result);50 var isDisturbed = rs.isDisturbed;51 console.log(isDisturbed);52});53var rs = new ReadableStream({54 start(controller) {55 controller.enqueue("a");56 controller.close();57 }58});59var reader = rs.getReader();60var result = reader.read();61result.then(function(result) {62 console.log(result);63 var isDisturbed = rs.isDisturbed;64 console.log(isDisturbed);65});66var rs = new ReadableStream({67 start(controller) {68 controller.enqueue("a");69 controller.close();70 }71});72var reader = rs.getReader();73var result = reader.read();74result.then(function(result) {75 console.log(result);76 var isDisturbed = rs.isDisturbed;77 console.log(isDisturbed
Using AI Code Generation
1const { ReadableStream } = require('stream/web');2const rs = new ReadableStream();3rs.cancel();4console.log(rs.locked);5console.log(rs.getReader().closed);6const { ReadableStream } = require('stream/web');7const rs = new ReadableStream();8console.log(rs.locked);9console.log(rs.getReader().closed);10const { ReadableStream } = require('stream/web');11const rs = new ReadableStream();12rs.getReader();13console.log(rs.locked);14console.log(rs.getReader().closed);
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!!