ponyfill.es2018.js 185 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213
  1. /**
  2. * web-streams-polyfill v3.2.1
  3. */
  4. (function (global, factory) {
  5. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  6. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  7. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.WebStreamsPolyfill = {}));
  8. }(this, (function (exports) { 'use strict';
  9. /// <reference lib="es2015.symbol" />
  10. const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?
  11. Symbol :
  12. description => `Symbol(${description})`;
  13. /// <reference lib="dom" />
  14. function noop() {
  15. return undefined;
  16. }
  17. function getGlobals() {
  18. if (typeof self !== 'undefined') {
  19. return self;
  20. }
  21. else if (typeof window !== 'undefined') {
  22. return window;
  23. }
  24. else if (typeof global !== 'undefined') {
  25. return global;
  26. }
  27. return undefined;
  28. }
  29. const globals = getGlobals();
  30. function typeIsObject(x) {
  31. return (typeof x === 'object' && x !== null) || typeof x === 'function';
  32. }
  33. const rethrowAssertionErrorRejection = noop;
  34. const originalPromise = Promise;
  35. const originalPromiseThen = Promise.prototype.then;
  36. const originalPromiseResolve = Promise.resolve.bind(originalPromise);
  37. const originalPromiseReject = Promise.reject.bind(originalPromise);
  38. function newPromise(executor) {
  39. return new originalPromise(executor);
  40. }
  41. function promiseResolvedWith(value) {
  42. return originalPromiseResolve(value);
  43. }
  44. function promiseRejectedWith(reason) {
  45. return originalPromiseReject(reason);
  46. }
  47. function PerformPromiseThen(promise, onFulfilled, onRejected) {
  48. // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an
  49. // approximation.
  50. return originalPromiseThen.call(promise, onFulfilled, onRejected);
  51. }
  52. function uponPromise(promise, onFulfilled, onRejected) {
  53. PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection);
  54. }
  55. function uponFulfillment(promise, onFulfilled) {
  56. uponPromise(promise, onFulfilled);
  57. }
  58. function uponRejection(promise, onRejected) {
  59. uponPromise(promise, undefined, onRejected);
  60. }
  61. function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) {
  62. return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);
  63. }
  64. function setPromiseIsHandledToTrue(promise) {
  65. PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);
  66. }
  67. const queueMicrotask = (() => {
  68. const globalQueueMicrotask = globals && globals.queueMicrotask;
  69. if (typeof globalQueueMicrotask === 'function') {
  70. return globalQueueMicrotask;
  71. }
  72. const resolvedPromise = promiseResolvedWith(undefined);
  73. return (fn) => PerformPromiseThen(resolvedPromise, fn);
  74. })();
  75. function reflectCall(F, V, args) {
  76. if (typeof F !== 'function') {
  77. throw new TypeError('Argument is not a function');
  78. }
  79. return Function.prototype.apply.call(F, V, args);
  80. }
  81. function promiseCall(F, V, args) {
  82. try {
  83. return promiseResolvedWith(reflectCall(F, V, args));
  84. }
  85. catch (value) {
  86. return promiseRejectedWith(value);
  87. }
  88. }
  89. // Original from Chromium
  90. // https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js
  91. const QUEUE_MAX_ARRAY_SIZE = 16384;
  92. /**
  93. * Simple queue structure.
  94. *
  95. * Avoids scalability issues with using a packed array directly by using
  96. * multiple arrays in a linked list and keeping the array size bounded.
  97. */
  98. class SimpleQueue {
  99. constructor() {
  100. this._cursor = 0;
  101. this._size = 0;
  102. // _front and _back are always defined.
  103. this._front = {
  104. _elements: [],
  105. _next: undefined
  106. };
  107. this._back = this._front;
  108. // The cursor is used to avoid calling Array.shift().
  109. // It contains the index of the front element of the array inside the
  110. // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).
  111. this._cursor = 0;
  112. // When there is only one node, size === elements.length - cursor.
  113. this._size = 0;
  114. }
  115. get length() {
  116. return this._size;
  117. }
  118. // For exception safety, this method is structured in order:
  119. // 1. Read state
  120. // 2. Calculate required state mutations
  121. // 3. Perform state mutations
  122. push(element) {
  123. const oldBack = this._back;
  124. let newBack = oldBack;
  125. if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {
  126. newBack = {
  127. _elements: [],
  128. _next: undefined
  129. };
  130. }
  131. // push() is the mutation most likely to throw an exception, so it
  132. // goes first.
  133. oldBack._elements.push(element);
  134. if (newBack !== oldBack) {
  135. this._back = newBack;
  136. oldBack._next = newBack;
  137. }
  138. ++this._size;
  139. }
  140. // Like push(), shift() follows the read -> calculate -> mutate pattern for
  141. // exception safety.
  142. shift() { // must not be called on an empty queue
  143. const oldFront = this._front;
  144. let newFront = oldFront;
  145. const oldCursor = this._cursor;
  146. let newCursor = oldCursor + 1;
  147. const elements = oldFront._elements;
  148. const element = elements[oldCursor];
  149. if (newCursor === QUEUE_MAX_ARRAY_SIZE) {
  150. newFront = oldFront._next;
  151. newCursor = 0;
  152. }
  153. // No mutations before this point.
  154. --this._size;
  155. this._cursor = newCursor;
  156. if (oldFront !== newFront) {
  157. this._front = newFront;
  158. }
  159. // Permit shifted element to be garbage collected.
  160. elements[oldCursor] = undefined;
  161. return element;
  162. }
  163. // The tricky thing about forEach() is that it can be called
  164. // re-entrantly. The queue may be mutated inside the callback. It is easy to
  165. // see that push() within the callback has no negative effects since the end
  166. // of the queue is checked for on every iteration. If shift() is called
  167. // repeatedly within the callback then the next iteration may return an
  168. // element that has been removed. In this case the callback will be called
  169. // with undefined values until we either "catch up" with elements that still
  170. // exist or reach the back of the queue.
  171. forEach(callback) {
  172. let i = this._cursor;
  173. let node = this._front;
  174. let elements = node._elements;
  175. while (i !== elements.length || node._next !== undefined) {
  176. if (i === elements.length) {
  177. node = node._next;
  178. elements = node._elements;
  179. i = 0;
  180. if (elements.length === 0) {
  181. break;
  182. }
  183. }
  184. callback(elements[i]);
  185. ++i;
  186. }
  187. }
  188. // Return the element that would be returned if shift() was called now,
  189. // without modifying the queue.
  190. peek() { // must not be called on an empty queue
  191. const front = this._front;
  192. const cursor = this._cursor;
  193. return front._elements[cursor];
  194. }
  195. }
  196. function ReadableStreamReaderGenericInitialize(reader, stream) {
  197. reader._ownerReadableStream = stream;
  198. stream._reader = reader;
  199. if (stream._state === 'readable') {
  200. defaultReaderClosedPromiseInitialize(reader);
  201. }
  202. else if (stream._state === 'closed') {
  203. defaultReaderClosedPromiseInitializeAsResolved(reader);
  204. }
  205. else {
  206. defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);
  207. }
  208. }
  209. // A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state
  210. // check.
  211. function ReadableStreamReaderGenericCancel(reader, reason) {
  212. const stream = reader._ownerReadableStream;
  213. return ReadableStreamCancel(stream, reason);
  214. }
  215. function ReadableStreamReaderGenericRelease(reader) {
  216. if (reader._ownerReadableStream._state === 'readable') {
  217. defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
  218. }
  219. else {
  220. defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
  221. }
  222. reader._ownerReadableStream._reader = undefined;
  223. reader._ownerReadableStream = undefined;
  224. }
  225. // Helper functions for the readers.
  226. function readerLockException(name) {
  227. return new TypeError('Cannot ' + name + ' a stream using a released reader');
  228. }
  229. // Helper functions for the ReadableStreamDefaultReader.
  230. function defaultReaderClosedPromiseInitialize(reader) {
  231. reader._closedPromise = newPromise((resolve, reject) => {
  232. reader._closedPromise_resolve = resolve;
  233. reader._closedPromise_reject = reject;
  234. });
  235. }
  236. function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) {
  237. defaultReaderClosedPromiseInitialize(reader);
  238. defaultReaderClosedPromiseReject(reader, reason);
  239. }
  240. function defaultReaderClosedPromiseInitializeAsResolved(reader) {
  241. defaultReaderClosedPromiseInitialize(reader);
  242. defaultReaderClosedPromiseResolve(reader);
  243. }
  244. function defaultReaderClosedPromiseReject(reader, reason) {
  245. if (reader._closedPromise_reject === undefined) {
  246. return;
  247. }
  248. setPromiseIsHandledToTrue(reader._closedPromise);
  249. reader._closedPromise_reject(reason);
  250. reader._closedPromise_resolve = undefined;
  251. reader._closedPromise_reject = undefined;
  252. }
  253. function defaultReaderClosedPromiseResetToRejected(reader, reason) {
  254. defaultReaderClosedPromiseInitializeAsRejected(reader, reason);
  255. }
  256. function defaultReaderClosedPromiseResolve(reader) {
  257. if (reader._closedPromise_resolve === undefined) {
  258. return;
  259. }
  260. reader._closedPromise_resolve(undefined);
  261. reader._closedPromise_resolve = undefined;
  262. reader._closedPromise_reject = undefined;
  263. }
  264. const AbortSteps = SymbolPolyfill('[[AbortSteps]]');
  265. const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]');
  266. const CancelSteps = SymbolPolyfill('[[CancelSteps]]');
  267. const PullSteps = SymbolPolyfill('[[PullSteps]]');
  268. /// <reference lib="es2015.core" />
  269. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill
  270. const NumberIsFinite = Number.isFinite || function (x) {
  271. return typeof x === 'number' && isFinite(x);
  272. };
  273. /// <reference lib="es2015.core" />
  274. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill
  275. const MathTrunc = Math.trunc || function (v) {
  276. return v < 0 ? Math.ceil(v) : Math.floor(v);
  277. };
  278. // https://heycam.github.io/webidl/#idl-dictionaries
  279. function isDictionary(x) {
  280. return typeof x === 'object' || typeof x === 'function';
  281. }
  282. function assertDictionary(obj, context) {
  283. if (obj !== undefined && !isDictionary(obj)) {
  284. throw new TypeError(`${context} is not an object.`);
  285. }
  286. }
  287. // https://heycam.github.io/webidl/#idl-callback-functions
  288. function assertFunction(x, context) {
  289. if (typeof x !== 'function') {
  290. throw new TypeError(`${context} is not a function.`);
  291. }
  292. }
  293. // https://heycam.github.io/webidl/#idl-object
  294. function isObject(x) {
  295. return (typeof x === 'object' && x !== null) || typeof x === 'function';
  296. }
  297. function assertObject(x, context) {
  298. if (!isObject(x)) {
  299. throw new TypeError(`${context} is not an object.`);
  300. }
  301. }
  302. function assertRequiredArgument(x, position, context) {
  303. if (x === undefined) {
  304. throw new TypeError(`Parameter ${position} is required in '${context}'.`);
  305. }
  306. }
  307. function assertRequiredField(x, field, context) {
  308. if (x === undefined) {
  309. throw new TypeError(`${field} is required in '${context}'.`);
  310. }
  311. }
  312. // https://heycam.github.io/webidl/#idl-unrestricted-double
  313. function convertUnrestrictedDouble(value) {
  314. return Number(value);
  315. }
  316. function censorNegativeZero(x) {
  317. return x === 0 ? 0 : x;
  318. }
  319. function integerPart(x) {
  320. return censorNegativeZero(MathTrunc(x));
  321. }
  322. // https://heycam.github.io/webidl/#idl-unsigned-long-long
  323. function convertUnsignedLongLongWithEnforceRange(value, context) {
  324. const lowerBound = 0;
  325. const upperBound = Number.MAX_SAFE_INTEGER;
  326. let x = Number(value);
  327. x = censorNegativeZero(x);
  328. if (!NumberIsFinite(x)) {
  329. throw new TypeError(`${context} is not a finite number`);
  330. }
  331. x = integerPart(x);
  332. if (x < lowerBound || x > upperBound) {
  333. throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);
  334. }
  335. if (!NumberIsFinite(x) || x === 0) {
  336. return 0;
  337. }
  338. // TODO Use BigInt if supported?
  339. // let xBigInt = BigInt(integerPart(x));
  340. // xBigInt = BigInt.asUintN(64, xBigInt);
  341. // return Number(xBigInt);
  342. return x;
  343. }
  344. function assertReadableStream(x, context) {
  345. if (!IsReadableStream(x)) {
  346. throw new TypeError(`${context} is not a ReadableStream.`);
  347. }
  348. }
  349. // Abstract operations for the ReadableStream.
  350. function AcquireReadableStreamDefaultReader(stream) {
  351. return new ReadableStreamDefaultReader(stream);
  352. }
  353. // ReadableStream API exposed for controllers.
  354. function ReadableStreamAddReadRequest(stream, readRequest) {
  355. stream._reader._readRequests.push(readRequest);
  356. }
  357. function ReadableStreamFulfillReadRequest(stream, chunk, done) {
  358. const reader = stream._reader;
  359. const readRequest = reader._readRequests.shift();
  360. if (done) {
  361. readRequest._closeSteps();
  362. }
  363. else {
  364. readRequest._chunkSteps(chunk);
  365. }
  366. }
  367. function ReadableStreamGetNumReadRequests(stream) {
  368. return stream._reader._readRequests.length;
  369. }
  370. function ReadableStreamHasDefaultReader(stream) {
  371. const reader = stream._reader;
  372. if (reader === undefined) {
  373. return false;
  374. }
  375. if (!IsReadableStreamDefaultReader(reader)) {
  376. return false;
  377. }
  378. return true;
  379. }
  380. /**
  381. * A default reader vended by a {@link ReadableStream}.
  382. *
  383. * @public
  384. */
  385. class ReadableStreamDefaultReader {
  386. constructor(stream) {
  387. assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');
  388. assertReadableStream(stream, 'First parameter');
  389. if (IsReadableStreamLocked(stream)) {
  390. throw new TypeError('This stream has already been locked for exclusive reading by another reader');
  391. }
  392. ReadableStreamReaderGenericInitialize(this, stream);
  393. this._readRequests = new SimpleQueue();
  394. }
  395. /**
  396. * Returns a promise that will be fulfilled when the stream becomes closed,
  397. * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.
  398. */
  399. get closed() {
  400. if (!IsReadableStreamDefaultReader(this)) {
  401. return promiseRejectedWith(defaultReaderBrandCheckException('closed'));
  402. }
  403. return this._closedPromise;
  404. }
  405. /**
  406. * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
  407. */
  408. cancel(reason = undefined) {
  409. if (!IsReadableStreamDefaultReader(this)) {
  410. return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));
  411. }
  412. if (this._ownerReadableStream === undefined) {
  413. return promiseRejectedWith(readerLockException('cancel'));
  414. }
  415. return ReadableStreamReaderGenericCancel(this, reason);
  416. }
  417. /**
  418. * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.
  419. *
  420. * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
  421. */
  422. read() {
  423. if (!IsReadableStreamDefaultReader(this)) {
  424. return promiseRejectedWith(defaultReaderBrandCheckException('read'));
  425. }
  426. if (this._ownerReadableStream === undefined) {
  427. return promiseRejectedWith(readerLockException('read from'));
  428. }
  429. let resolvePromise;
  430. let rejectPromise;
  431. const promise = newPromise((resolve, reject) => {
  432. resolvePromise = resolve;
  433. rejectPromise = reject;
  434. });
  435. const readRequest = {
  436. _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),
  437. _closeSteps: () => resolvePromise({ value: undefined, done: true }),
  438. _errorSteps: e => rejectPromise(e)
  439. };
  440. ReadableStreamDefaultReaderRead(this, readRequest);
  441. return promise;
  442. }
  443. /**
  444. * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
  445. * If the associated stream is errored when the lock is released, the reader will appear errored in the same way
  446. * from now on; otherwise, the reader will appear closed.
  447. *
  448. * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
  449. * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to
  450. * do so will throw a `TypeError` and leave the reader locked to the stream.
  451. */
  452. releaseLock() {
  453. if (!IsReadableStreamDefaultReader(this)) {
  454. throw defaultReaderBrandCheckException('releaseLock');
  455. }
  456. if (this._ownerReadableStream === undefined) {
  457. return;
  458. }
  459. if (this._readRequests.length > 0) {
  460. throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');
  461. }
  462. ReadableStreamReaderGenericRelease(this);
  463. }
  464. }
  465. Object.defineProperties(ReadableStreamDefaultReader.prototype, {
  466. cancel: { enumerable: true },
  467. read: { enumerable: true },
  468. releaseLock: { enumerable: true },
  469. closed: { enumerable: true }
  470. });
  471. if (typeof SymbolPolyfill.toStringTag === 'symbol') {
  472. Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, {
  473. value: 'ReadableStreamDefaultReader',
  474. configurable: true
  475. });
  476. }
  477. // Abstract operations for the readers.
  478. function IsReadableStreamDefaultReader(x) {
  479. if (!typeIsObject(x)) {
  480. return false;
  481. }
  482. if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {
  483. return false;
  484. }
  485. return x instanceof ReadableStreamDefaultReader;
  486. }
  487. function ReadableStreamDefaultReaderRead(reader, readRequest) {
  488. const stream = reader._ownerReadableStream;
  489. stream._disturbed = true;
  490. if (stream._state === 'closed') {
  491. readRequest._closeSteps();
  492. }
  493. else if (stream._state === 'errored') {
  494. readRequest._errorSteps(stream._storedError);
  495. }
  496. else {
  497. stream._readableStreamController[PullSteps](readRequest);
  498. }
  499. }
  500. // Helper functions for the ReadableStreamDefaultReader.
  501. function defaultReaderBrandCheckException(name) {
  502. return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);
  503. }
  504. /// <reference lib="es2018.asynciterable" />
  505. /* eslint-disable @typescript-eslint/no-empty-function */
  506. const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () { }).prototype);
  507. /// <reference lib="es2018.asynciterable" />
  508. class ReadableStreamAsyncIteratorImpl {
  509. constructor(reader, preventCancel) {
  510. this._ongoingPromise = undefined;
  511. this._isFinished = false;
  512. this._reader = reader;
  513. this._preventCancel = preventCancel;
  514. }
  515. next() {
  516. const nextSteps = () => this._nextSteps();
  517. this._ongoingPromise = this._ongoingPromise ?
  518. transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :
  519. nextSteps();
  520. return this._ongoingPromise;
  521. }
  522. return(value) {
  523. const returnSteps = () => this._returnSteps(value);
  524. return this._ongoingPromise ?
  525. transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :
  526. returnSteps();
  527. }
  528. _nextSteps() {
  529. if (this._isFinished) {
  530. return Promise.resolve({ value: undefined, done: true });
  531. }
  532. const reader = this._reader;
  533. if (reader._ownerReadableStream === undefined) {
  534. return promiseRejectedWith(readerLockException('iterate'));
  535. }
  536. let resolvePromise;
  537. let rejectPromise;
  538. const promise = newPromise((resolve, reject) => {
  539. resolvePromise = resolve;
  540. rejectPromise = reject;
  541. });
  542. const readRequest = {
  543. _chunkSteps: chunk => {
  544. this._ongoingPromise = undefined;
  545. // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.
  546. // FIXME Is this a bug in the specification, or in the test?
  547. queueMicrotask(() => resolvePromise({ value: chunk, done: false }));
  548. },
  549. _closeSteps: () => {
  550. this._ongoingPromise = undefined;
  551. this._isFinished = true;
  552. ReadableStreamReaderGenericRelease(reader);
  553. resolvePromise({ value: undefined, done: true });
  554. },
  555. _errorSteps: reason => {
  556. this._ongoingPromise = undefined;
  557. this._isFinished = true;
  558. ReadableStreamReaderGenericRelease(reader);
  559. rejectPromise(reason);
  560. }
  561. };
  562. ReadableStreamDefaultReaderRead(reader, readRequest);
  563. return promise;
  564. }
  565. _returnSteps(value) {
  566. if (this._isFinished) {
  567. return Promise.resolve({ value, done: true });
  568. }
  569. this._isFinished = true;
  570. const reader = this._reader;
  571. if (reader._ownerReadableStream === undefined) {
  572. return promiseRejectedWith(readerLockException('finish iterating'));
  573. }
  574. if (!this._preventCancel) {
  575. const result = ReadableStreamReaderGenericCancel(reader, value);
  576. ReadableStreamReaderGenericRelease(reader);
  577. return transformPromiseWith(result, () => ({ value, done: true }));
  578. }
  579. ReadableStreamReaderGenericRelease(reader);
  580. return promiseResolvedWith({ value, done: true });
  581. }
  582. }
  583. const ReadableStreamAsyncIteratorPrototype = {
  584. next() {
  585. if (!IsReadableStreamAsyncIterator(this)) {
  586. return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));
  587. }
  588. return this._asyncIteratorImpl.next();
  589. },
  590. return(value) {
  591. if (!IsReadableStreamAsyncIterator(this)) {
  592. return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));
  593. }
  594. return this._asyncIteratorImpl.return(value);
  595. }
  596. };
  597. if (AsyncIteratorPrototype !== undefined) {
  598. Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);
  599. }
  600. // Abstract operations for the ReadableStream.
  601. function AcquireReadableStreamAsyncIterator(stream, preventCancel) {
  602. const reader = AcquireReadableStreamDefaultReader(stream);
  603. const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);
  604. const iterator = Object.create(ReadableStreamAsyncIteratorPrototype);
  605. iterator._asyncIteratorImpl = impl;
  606. return iterator;
  607. }
  608. function IsReadableStreamAsyncIterator(x) {
  609. if (!typeIsObject(x)) {
  610. return false;
  611. }
  612. if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {
  613. return false;
  614. }
  615. try {
  616. // noinspection SuspiciousTypeOfGuard
  617. return x._asyncIteratorImpl instanceof
  618. ReadableStreamAsyncIteratorImpl;
  619. }
  620. catch (_a) {
  621. return false;
  622. }
  623. }
  624. // Helper functions for the ReadableStream.
  625. function streamAsyncIteratorBrandCheckException(name) {
  626. return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);
  627. }
  628. /// <reference lib="es2015.core" />
  629. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill
  630. const NumberIsNaN = Number.isNaN || function (x) {
  631. // eslint-disable-next-line no-self-compare
  632. return x !== x;
  633. };
  634. function CreateArrayFromList(elements) {
  635. // We use arrays to represent lists, so this is basically a no-op.
  636. // Do a slice though just in case we happen to depend on the unique-ness.
  637. return elements.slice();
  638. }
  639. function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) {
  640. new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);
  641. }
  642. // Not implemented correctly
  643. function TransferArrayBuffer(O) {
  644. return O;
  645. }
  646. // Not implemented correctly
  647. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  648. function IsDetachedBuffer(O) {
  649. return false;
  650. }
  651. function ArrayBufferSlice(buffer, begin, end) {
  652. // ArrayBuffer.prototype.slice is not available on IE10
  653. // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice
  654. if (buffer.slice) {
  655. return buffer.slice(begin, end);
  656. }
  657. const length = end - begin;
  658. const slice = new ArrayBuffer(length);
  659. CopyDataBlockBytes(slice, 0, buffer, begin, length);
  660. return slice;
  661. }
  662. function IsNonNegativeNumber(v) {
  663. if (typeof v !== 'number') {
  664. return false;
  665. }
  666. if (NumberIsNaN(v)) {
  667. return false;
  668. }
  669. if (v < 0) {
  670. return false;
  671. }
  672. return true;
  673. }
  674. function CloneAsUint8Array(O) {
  675. const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);
  676. return new Uint8Array(buffer);
  677. }
  678. function DequeueValue(container) {
  679. const pair = container._queue.shift();
  680. container._queueTotalSize -= pair.size;
  681. if (container._queueTotalSize < 0) {
  682. container._queueTotalSize = 0;
  683. }
  684. return pair.value;
  685. }
  686. function EnqueueValueWithSize(container, value, size) {
  687. if (!IsNonNegativeNumber(size) || size === Infinity) {
  688. throw new RangeError('Size must be a finite, non-NaN, non-negative number.');
  689. }
  690. container._queue.push({ value, size });
  691. container._queueTotalSize += size;
  692. }
  693. function PeekQueueValue(container) {
  694. const pair = container._queue.peek();
  695. return pair.value;
  696. }
  697. function ResetQueue(container) {
  698. container._queue = new SimpleQueue();
  699. container._queueTotalSize = 0;
  700. }
  701. /**
  702. * A pull-into request in a {@link ReadableByteStreamController}.
  703. *
  704. * @public
  705. */
  706. class ReadableStreamBYOBRequest {
  707. constructor() {
  708. throw new TypeError('Illegal constructor');
  709. }
  710. /**
  711. * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.
  712. */
  713. get view() {
  714. if (!IsReadableStreamBYOBRequest(this)) {
  715. throw byobRequestBrandCheckException('view');
  716. }
  717. return this._view;
  718. }
  719. respond(bytesWritten) {
  720. if (!IsReadableStreamBYOBRequest(this)) {
  721. throw byobRequestBrandCheckException('respond');
  722. }
  723. assertRequiredArgument(bytesWritten, 1, 'respond');
  724. bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');
  725. if (this._associatedReadableByteStreamController === undefined) {
  726. throw new TypeError('This BYOB request has been invalidated');
  727. }
  728. if (IsDetachedBuffer(this._view.buffer)) ;
  729. ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);
  730. }
  731. respondWithNewView(view) {
  732. if (!IsReadableStreamBYOBRequest(this)) {
  733. throw byobRequestBrandCheckException('respondWithNewView');
  734. }
  735. assertRequiredArgument(view, 1, 'respondWithNewView');
  736. if (!ArrayBuffer.isView(view)) {
  737. throw new TypeError('You can only respond with array buffer views');
  738. }
  739. if (this._associatedReadableByteStreamController === undefined) {
  740. throw new TypeError('This BYOB request has been invalidated');
  741. }
  742. if (IsDetachedBuffer(view.buffer)) ;
  743. ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);
  744. }
  745. }
  746. Object.defineProperties(ReadableStreamBYOBRequest.prototype, {
  747. respond: { enumerable: true },
  748. respondWithNewView: { enumerable: true },
  749. view: { enumerable: true }
  750. });
  751. if (typeof SymbolPolyfill.toStringTag === 'symbol') {
  752. Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, {
  753. value: 'ReadableStreamBYOBRequest',
  754. configurable: true
  755. });
  756. }
  757. /**
  758. * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.
  759. *
  760. * @public
  761. */
  762. class ReadableByteStreamController {
  763. constructor() {
  764. throw new TypeError('Illegal constructor');
  765. }
  766. /**
  767. * Returns the current BYOB pull request, or `null` if there isn't one.
  768. */
  769. get byobRequest() {
  770. if (!IsReadableByteStreamController(this)) {
  771. throw byteStreamControllerBrandCheckException('byobRequest');
  772. }
  773. return ReadableByteStreamControllerGetBYOBRequest(this);
  774. }
  775. /**
  776. * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
  777. * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.
  778. */
  779. get desiredSize() {
  780. if (!IsReadableByteStreamController(this)) {
  781. throw byteStreamControllerBrandCheckException('desiredSize');
  782. }
  783. return ReadableByteStreamControllerGetDesiredSize(this);
  784. }
  785. /**
  786. * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
  787. * the stream, but once those are read, the stream will become closed.
  788. */
  789. close() {
  790. if (!IsReadableByteStreamController(this)) {
  791. throw byteStreamControllerBrandCheckException('close');
  792. }
  793. if (this._closeRequested) {
  794. throw new TypeError('The stream has already been closed; do not close it again!');
  795. }
  796. const state = this._controlledReadableByteStream._state;
  797. if (state !== 'readable') {
  798. throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);
  799. }
  800. ReadableByteStreamControllerClose(this);
  801. }
  802. enqueue(chunk) {
  803. if (!IsReadableByteStreamController(this)) {
  804. throw byteStreamControllerBrandCheckException('enqueue');
  805. }
  806. assertRequiredArgument(chunk, 1, 'enqueue');
  807. if (!ArrayBuffer.isView(chunk)) {
  808. throw new TypeError('chunk must be an array buffer view');
  809. }
  810. if (chunk.byteLength === 0) {
  811. throw new TypeError('chunk must have non-zero byteLength');
  812. }
  813. if (chunk.buffer.byteLength === 0) {
  814. throw new TypeError(`chunk's buffer must have non-zero byteLength`);
  815. }
  816. if (this._closeRequested) {
  817. throw new TypeError('stream is closed or draining');
  818. }
  819. const state = this._controlledReadableByteStream._state;
  820. if (state !== 'readable') {
  821. throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);
  822. }
  823. ReadableByteStreamControllerEnqueue(this, chunk);
  824. }
  825. /**
  826. * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
  827. */
  828. error(e = undefined) {
  829. if (!IsReadableByteStreamController(this)) {
  830. throw byteStreamControllerBrandCheckException('error');
  831. }
  832. ReadableByteStreamControllerError(this, e);
  833. }
  834. /** @internal */
  835. [CancelSteps](reason) {
  836. ReadableByteStreamControllerClearPendingPullIntos(this);
  837. ResetQueue(this);
  838. const result = this._cancelAlgorithm(reason);
  839. ReadableByteStreamControllerClearAlgorithms(this);
  840. return result;
  841. }
  842. /** @internal */
  843. [PullSteps](readRequest) {
  844. const stream = this._controlledReadableByteStream;
  845. if (this._queueTotalSize > 0) {
  846. const entry = this._queue.shift();
  847. this._queueTotalSize -= entry.byteLength;
  848. ReadableByteStreamControllerHandleQueueDrain(this);
  849. const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);
  850. readRequest._chunkSteps(view);
  851. return;
  852. }
  853. const autoAllocateChunkSize = this._autoAllocateChunkSize;
  854. if (autoAllocateChunkSize !== undefined) {
  855. let buffer;
  856. try {
  857. buffer = new ArrayBuffer(autoAllocateChunkSize);
  858. }
  859. catch (bufferE) {
  860. readRequest._errorSteps(bufferE);
  861. return;
  862. }
  863. const pullIntoDescriptor = {
  864. buffer,
  865. bufferByteLength: autoAllocateChunkSize,
  866. byteOffset: 0,
  867. byteLength: autoAllocateChunkSize,
  868. bytesFilled: 0,
  869. elementSize: 1,
  870. viewConstructor: Uint8Array,
  871. readerType: 'default'
  872. };
  873. this._pendingPullIntos.push(pullIntoDescriptor);
  874. }
  875. ReadableStreamAddReadRequest(stream, readRequest);
  876. ReadableByteStreamControllerCallPullIfNeeded(this);
  877. }
  878. }
  879. Object.defineProperties(ReadableByteStreamController.prototype, {
  880. close: { enumerable: true },
  881. enqueue: { enumerable: true },
  882. error: { enumerable: true },
  883. byobRequest: { enumerable: true },
  884. desiredSize: { enumerable: true }
  885. });
  886. if (typeof SymbolPolyfill.toStringTag === 'symbol') {
  887. Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, {
  888. value: 'ReadableByteStreamController',
  889. configurable: true
  890. });
  891. }
  892. // Abstract operations for the ReadableByteStreamController.
  893. function IsReadableByteStreamController(x) {
  894. if (!typeIsObject(x)) {
  895. return false;
  896. }
  897. if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {
  898. return false;
  899. }
  900. return x instanceof ReadableByteStreamController;
  901. }
  902. function IsReadableStreamBYOBRequest(x) {
  903. if (!typeIsObject(x)) {
  904. return false;
  905. }
  906. if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {
  907. return false;
  908. }
  909. return x instanceof ReadableStreamBYOBRequest;
  910. }
  911. function ReadableByteStreamControllerCallPullIfNeeded(controller) {
  912. const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);
  913. if (!shouldPull) {
  914. return;
  915. }
  916. if (controller._pulling) {
  917. controller._pullAgain = true;
  918. return;
  919. }
  920. controller._pulling = true;
  921. // TODO: Test controller argument
  922. const pullPromise = controller._pullAlgorithm();
  923. uponPromise(pullPromise, () => {
  924. controller._pulling = false;
  925. if (controller._pullAgain) {
  926. controller._pullAgain = false;
  927. ReadableByteStreamControllerCallPullIfNeeded(controller);
  928. }
  929. }, e => {
  930. ReadableByteStreamControllerError(controller, e);
  931. });
  932. }
  933. function ReadableByteStreamControllerClearPendingPullIntos(controller) {
  934. ReadableByteStreamControllerInvalidateBYOBRequest(controller);
  935. controller._pendingPullIntos = new SimpleQueue();
  936. }
  937. function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) {
  938. let done = false;
  939. if (stream._state === 'closed') {
  940. done = true;
  941. }
  942. const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
  943. if (pullIntoDescriptor.readerType === 'default') {
  944. ReadableStreamFulfillReadRequest(stream, filledView, done);
  945. }
  946. else {
  947. ReadableStreamFulfillReadIntoRequest(stream, filledView, done);
  948. }
  949. }
  950. function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) {
  951. const bytesFilled = pullIntoDescriptor.bytesFilled;
  952. const elementSize = pullIntoDescriptor.elementSize;
  953. return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize);
  954. }
  955. function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) {
  956. controller._queue.push({ buffer, byteOffset, byteLength });
  957. controller._queueTotalSize += byteLength;
  958. }
  959. function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) {
  960. const elementSize = pullIntoDescriptor.elementSize;
  961. const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;
  962. const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);
  963. const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;
  964. const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;
  965. let totalBytesToCopyRemaining = maxBytesToCopy;
  966. let ready = false;
  967. if (maxAlignedBytes > currentAlignedBytes) {
  968. totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;
  969. ready = true;
  970. }
  971. const queue = controller._queue;
  972. while (totalBytesToCopyRemaining > 0) {
  973. const headOfQueue = queue.peek();
  974. const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);
  975. const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
  976. CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);
  977. if (headOfQueue.byteLength === bytesToCopy) {
  978. queue.shift();
  979. }
  980. else {
  981. headOfQueue.byteOffset += bytesToCopy;
  982. headOfQueue.byteLength -= bytesToCopy;
  983. }
  984. controller._queueTotalSize -= bytesToCopy;
  985. ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);
  986. totalBytesToCopyRemaining -= bytesToCopy;
  987. }
  988. return ready;
  989. }
  990. function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) {
  991. pullIntoDescriptor.bytesFilled += size;
  992. }
  993. function ReadableByteStreamControllerHandleQueueDrain(controller) {
  994. if (controller._queueTotalSize === 0 && controller._closeRequested) {
  995. ReadableByteStreamControllerClearAlgorithms(controller);
  996. ReadableStreamClose(controller._controlledReadableByteStream);
  997. }
  998. else {
  999. ReadableByteStreamControllerCallPullIfNeeded(controller);
  1000. }
  1001. }
  1002. function ReadableByteStreamControllerInvalidateBYOBRequest(controller) {
  1003. if (controller._byobRequest === null) {
  1004. return;
  1005. }
  1006. controller._byobRequest._associatedReadableByteStreamController = undefined;
  1007. controller._byobRequest._view = null;
  1008. controller._byobRequest = null;
  1009. }
  1010. function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) {
  1011. while (controller._pendingPullIntos.length > 0) {
  1012. if (controller._queueTotalSize === 0) {
  1013. return;
  1014. }
  1015. const pullIntoDescriptor = controller._pendingPullIntos.peek();
  1016. if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {
  1017. ReadableByteStreamControllerShiftPendingPullInto(controller);
  1018. ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
  1019. }
  1020. }
  1021. }
  1022. function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) {
  1023. const stream = controller._controlledReadableByteStream;
  1024. let elementSize = 1;
  1025. if (view.constructor !== DataView) {
  1026. elementSize = view.constructor.BYTES_PER_ELEMENT;
  1027. }
  1028. const ctor = view.constructor;
  1029. // try {
  1030. const buffer = TransferArrayBuffer(view.buffer);
  1031. // } catch (e) {
  1032. // readIntoRequest._errorSteps(e);
  1033. // return;
  1034. // }
  1035. const pullIntoDescriptor = {
  1036. buffer,
  1037. bufferByteLength: buffer.byteLength,
  1038. byteOffset: view.byteOffset,
  1039. byteLength: view.byteLength,
  1040. bytesFilled: 0,
  1041. elementSize,
  1042. viewConstructor: ctor,
  1043. readerType: 'byob'
  1044. };
  1045. if (controller._pendingPullIntos.length > 0) {
  1046. controller._pendingPullIntos.push(pullIntoDescriptor);
  1047. // No ReadableByteStreamControllerCallPullIfNeeded() call since:
  1048. // - No change happens on desiredSize
  1049. // - The source has already been notified of that there's at least 1 pending read(view)
  1050. ReadableStreamAddReadIntoRequest(stream, readIntoRequest);
  1051. return;
  1052. }
  1053. if (stream._state === 'closed') {
  1054. const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);
  1055. readIntoRequest._closeSteps(emptyView);
  1056. return;
  1057. }
  1058. if (controller._queueTotalSize > 0) {
  1059. if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {
  1060. const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
  1061. ReadableByteStreamControllerHandleQueueDrain(controller);
  1062. readIntoRequest._chunkSteps(filledView);
  1063. return;
  1064. }
  1065. if (controller._closeRequested) {
  1066. const e = new TypeError('Insufficient bytes to fill elements in the given buffer');
  1067. ReadableByteStreamControllerError(controller, e);
  1068. readIntoRequest._errorSteps(e);
  1069. return;
  1070. }
  1071. }
  1072. controller._pendingPullIntos.push(pullIntoDescriptor);
  1073. ReadableStreamAddReadIntoRequest(stream, readIntoRequest);
  1074. ReadableByteStreamControllerCallPullIfNeeded(controller);
  1075. }
  1076. function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) {
  1077. const stream = controller._controlledReadableByteStream;
  1078. if (ReadableStreamHasBYOBReader(stream)) {
  1079. while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {
  1080. const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);
  1081. ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);
  1082. }
  1083. }
  1084. }
  1085. function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) {
  1086. ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);
  1087. if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {
  1088. return;
  1089. }
  1090. ReadableByteStreamControllerShiftPendingPullInto(controller);
  1091. const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;
  1092. if (remainderSize > 0) {
  1093. const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
  1094. const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end);
  1095. ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);
  1096. }
  1097. pullIntoDescriptor.bytesFilled -= remainderSize;
  1098. ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
  1099. ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
  1100. }
  1101. function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) {
  1102. const firstDescriptor = controller._pendingPullIntos.peek();
  1103. ReadableByteStreamControllerInvalidateBYOBRequest(controller);
  1104. const state = controller._controlledReadableByteStream._state;
  1105. if (state === 'closed') {
  1106. ReadableByteStreamControllerRespondInClosedState(controller);
  1107. }
  1108. else {
  1109. ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);
  1110. }
  1111. ReadableByteStreamControllerCallPullIfNeeded(controller);
  1112. }
  1113. function ReadableByteStreamControllerShiftPendingPullInto(controller) {
  1114. const descriptor = controller._pendingPullIntos.shift();
  1115. return descriptor;
  1116. }
  1117. function ReadableByteStreamControllerShouldCallPull(controller) {
  1118. const stream = controller._controlledReadableByteStream;
  1119. if (stream._state !== 'readable') {
  1120. return false;
  1121. }
  1122. if (controller._closeRequested) {
  1123. return false;
  1124. }
  1125. if (!controller._started) {
  1126. return false;
  1127. }
  1128. if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
  1129. return true;
  1130. }
  1131. if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {
  1132. return true;
  1133. }
  1134. const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);
  1135. if (desiredSize > 0) {
  1136. return true;
  1137. }
  1138. return false;
  1139. }
  1140. function ReadableByteStreamControllerClearAlgorithms(controller) {
  1141. controller._pullAlgorithm = undefined;
  1142. controller._cancelAlgorithm = undefined;
  1143. }
  1144. // A client of ReadableByteStreamController may use these functions directly to bypass state check.
  1145. function ReadableByteStreamControllerClose(controller) {
  1146. const stream = controller._controlledReadableByteStream;
  1147. if (controller._closeRequested || stream._state !== 'readable') {
  1148. return;
  1149. }
  1150. if (controller._queueTotalSize > 0) {
  1151. controller._closeRequested = true;
  1152. return;
  1153. }
  1154. if (controller._pendingPullIntos.length > 0) {
  1155. const firstPendingPullInto = controller._pendingPullIntos.peek();
  1156. if (firstPendingPullInto.bytesFilled > 0) {
  1157. const e = new TypeError('Insufficient bytes to fill elements in the given buffer');
  1158. ReadableByteStreamControllerError(controller, e);
  1159. throw e;
  1160. }
  1161. }
  1162. ReadableByteStreamControllerClearAlgorithms(controller);
  1163. ReadableStreamClose(stream);
  1164. }
  1165. function ReadableByteStreamControllerEnqueue(controller, chunk) {
  1166. const stream = controller._controlledReadableByteStream;
  1167. if (controller._closeRequested || stream._state !== 'readable') {
  1168. return;
  1169. }
  1170. const buffer = chunk.buffer;
  1171. const byteOffset = chunk.byteOffset;
  1172. const byteLength = chunk.byteLength;
  1173. const transferredBuffer = TransferArrayBuffer(buffer);
  1174. if (controller._pendingPullIntos.length > 0) {
  1175. const firstPendingPullInto = controller._pendingPullIntos.peek();
  1176. if (IsDetachedBuffer(firstPendingPullInto.buffer)) ;
  1177. firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);
  1178. }
  1179. ReadableByteStreamControllerInvalidateBYOBRequest(controller);
  1180. if (ReadableStreamHasDefaultReader(stream)) {
  1181. if (ReadableStreamGetNumReadRequests(stream) === 0) {
  1182. ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
  1183. }
  1184. else {
  1185. if (controller._pendingPullIntos.length > 0) {
  1186. ReadableByteStreamControllerShiftPendingPullInto(controller);
  1187. }
  1188. const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);
  1189. ReadableStreamFulfillReadRequest(stream, transferredView, false);
  1190. }
  1191. }
  1192. else if (ReadableStreamHasBYOBReader(stream)) {
  1193. // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.
  1194. ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
  1195. ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
  1196. }
  1197. else {
  1198. ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
  1199. }
  1200. ReadableByteStreamControllerCallPullIfNeeded(controller);
  1201. }
  1202. function ReadableByteStreamControllerError(controller, e) {
  1203. const stream = controller._controlledReadableByteStream;
  1204. if (stream._state !== 'readable') {
  1205. return;
  1206. }
  1207. ReadableByteStreamControllerClearPendingPullIntos(controller);
  1208. ResetQueue(controller);
  1209. ReadableByteStreamControllerClearAlgorithms(controller);
  1210. ReadableStreamError(stream, e);
  1211. }
  1212. function ReadableByteStreamControllerGetBYOBRequest(controller) {
  1213. if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {
  1214. const firstDescriptor = controller._pendingPullIntos.peek();
  1215. const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled);
  1216. const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype);
  1217. SetUpReadableStreamBYOBRequest(byobRequest, controller, view);
  1218. controller._byobRequest = byobRequest;
  1219. }
  1220. return controller._byobRequest;
  1221. }
  1222. function ReadableByteStreamControllerGetDesiredSize(controller) {
  1223. const state = controller._controlledReadableByteStream._state;
  1224. if (state === 'errored') {
  1225. return null;
  1226. }
  1227. if (state === 'closed') {
  1228. return 0;
  1229. }
  1230. return controller._strategyHWM - controller._queueTotalSize;
  1231. }
  1232. function ReadableByteStreamControllerRespond(controller, bytesWritten) {
  1233. const firstDescriptor = controller._pendingPullIntos.peek();
  1234. const state = controller._controlledReadableByteStream._state;
  1235. if (state === 'closed') {
  1236. if (bytesWritten !== 0) {
  1237. throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');
  1238. }
  1239. }
  1240. else {
  1241. if (bytesWritten === 0) {
  1242. throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');
  1243. }
  1244. if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {
  1245. throw new RangeError('bytesWritten out of range');
  1246. }
  1247. }
  1248. firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);
  1249. ReadableByteStreamControllerRespondInternal(controller, bytesWritten);
  1250. }
  1251. function ReadableByteStreamControllerRespondWithNewView(controller, view) {
  1252. const firstDescriptor = controller._pendingPullIntos.peek();
  1253. const state = controller._controlledReadableByteStream._state;
  1254. if (state === 'closed') {
  1255. if (view.byteLength !== 0) {
  1256. throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream');
  1257. }
  1258. }
  1259. else {
  1260. if (view.byteLength === 0) {
  1261. throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream');
  1262. }
  1263. }
  1264. if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {
  1265. throw new RangeError('The region specified by view does not match byobRequest');
  1266. }
  1267. if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {
  1268. throw new RangeError('The buffer of view has different capacity than byobRequest');
  1269. }
  1270. if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {
  1271. throw new RangeError('The region specified by view is larger than byobRequest');
  1272. }
  1273. const viewByteLength = view.byteLength;
  1274. firstDescriptor.buffer = TransferArrayBuffer(view.buffer);
  1275. ReadableByteStreamControllerRespondInternal(controller, viewByteLength);
  1276. }
  1277. function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) {
  1278. controller._controlledReadableByteStream = stream;
  1279. controller._pullAgain = false;
  1280. controller._pulling = false;
  1281. controller._byobRequest = null;
  1282. // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.
  1283. controller._queue = controller._queueTotalSize = undefined;
  1284. ResetQueue(controller);
  1285. controller._closeRequested = false;
  1286. controller._started = false;
  1287. controller._strategyHWM = highWaterMark;
  1288. controller._pullAlgorithm = pullAlgorithm;
  1289. controller._cancelAlgorithm = cancelAlgorithm;
  1290. controller._autoAllocateChunkSize = autoAllocateChunkSize;
  1291. controller._pendingPullIntos = new SimpleQueue();
  1292. stream._readableStreamController = controller;
  1293. const startResult = startAlgorithm();
  1294. uponPromise(promiseResolvedWith(startResult), () => {
  1295. controller._started = true;
  1296. ReadableByteStreamControllerCallPullIfNeeded(controller);
  1297. }, r => {
  1298. ReadableByteStreamControllerError(controller, r);
  1299. });
  1300. }
  1301. function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) {
  1302. const controller = Object.create(ReadableByteStreamController.prototype);
  1303. let startAlgorithm = () => undefined;
  1304. let pullAlgorithm = () => promiseResolvedWith(undefined);
  1305. let cancelAlgorithm = () => promiseResolvedWith(undefined);
  1306. if (underlyingByteSource.start !== undefined) {
  1307. startAlgorithm = () => underlyingByteSource.start(controller);
  1308. }
  1309. if (underlyingByteSource.pull !== undefined) {
  1310. pullAlgorithm = () => underlyingByteSource.pull(controller);
  1311. }
  1312. if (underlyingByteSource.cancel !== undefined) {
  1313. cancelAlgorithm = reason => underlyingByteSource.cancel(reason);
  1314. }
  1315. const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;
  1316. if (autoAllocateChunkSize === 0) {
  1317. throw new TypeError('autoAllocateChunkSize must be greater than 0');
  1318. }
  1319. SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize);
  1320. }
  1321. function SetUpReadableStreamBYOBRequest(request, controller, view) {
  1322. request._associatedReadableByteStreamController = controller;
  1323. request._view = view;
  1324. }
  1325. // Helper functions for the ReadableStreamBYOBRequest.
  1326. function byobRequestBrandCheckException(name) {
  1327. return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);
  1328. }
  1329. // Helper functions for the ReadableByteStreamController.
  1330. function byteStreamControllerBrandCheckException(name) {
  1331. return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);
  1332. }
  1333. // Abstract operations for the ReadableStream.
  1334. function AcquireReadableStreamBYOBReader(stream) {
  1335. return new ReadableStreamBYOBReader(stream);
  1336. }
  1337. // ReadableStream API exposed for controllers.
  1338. function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) {
  1339. stream._reader._readIntoRequests.push(readIntoRequest);
  1340. }
  1341. function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) {
  1342. const reader = stream._reader;
  1343. const readIntoRequest = reader._readIntoRequests.shift();
  1344. if (done) {
  1345. readIntoRequest._closeSteps(chunk);
  1346. }
  1347. else {
  1348. readIntoRequest._chunkSteps(chunk);
  1349. }
  1350. }
  1351. function ReadableStreamGetNumReadIntoRequests(stream) {
  1352. return stream._reader._readIntoRequests.length;
  1353. }
  1354. function ReadableStreamHasBYOBReader(stream) {
  1355. const reader = stream._reader;
  1356. if (reader === undefined) {
  1357. return false;
  1358. }
  1359. if (!IsReadableStreamBYOBReader(reader)) {
  1360. return false;
  1361. }
  1362. return true;
  1363. }
  1364. /**
  1365. * A BYOB reader vended by a {@link ReadableStream}.
  1366. *
  1367. * @public
  1368. */
  1369. class ReadableStreamBYOBReader {
  1370. constructor(stream) {
  1371. assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');
  1372. assertReadableStream(stream, 'First parameter');
  1373. if (IsReadableStreamLocked(stream)) {
  1374. throw new TypeError('This stream has already been locked for exclusive reading by another reader');
  1375. }
  1376. if (!IsReadableByteStreamController(stream._readableStreamController)) {
  1377. throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +
  1378. 'source');
  1379. }
  1380. ReadableStreamReaderGenericInitialize(this, stream);
  1381. this._readIntoRequests = new SimpleQueue();
  1382. }
  1383. /**
  1384. * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
  1385. * the reader's lock is released before the stream finishes closing.
  1386. */
  1387. get closed() {
  1388. if (!IsReadableStreamBYOBReader(this)) {
  1389. return promiseRejectedWith(byobReaderBrandCheckException('closed'));
  1390. }
  1391. return this._closedPromise;
  1392. }
  1393. /**
  1394. * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
  1395. */
  1396. cancel(reason = undefined) {
  1397. if (!IsReadableStreamBYOBReader(this)) {
  1398. return promiseRejectedWith(byobReaderBrandCheckException('cancel'));
  1399. }
  1400. if (this._ownerReadableStream === undefined) {
  1401. return promiseRejectedWith(readerLockException('cancel'));
  1402. }
  1403. return ReadableStreamReaderGenericCancel(this, reason);
  1404. }
  1405. /**
  1406. * Attempts to reads bytes into view, and returns a promise resolved with the result.
  1407. *
  1408. * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
  1409. */
  1410. read(view) {
  1411. if (!IsReadableStreamBYOBReader(this)) {
  1412. return promiseRejectedWith(byobReaderBrandCheckException('read'));
  1413. }
  1414. if (!ArrayBuffer.isView(view)) {
  1415. return promiseRejectedWith(new TypeError('view must be an array buffer view'));
  1416. }
  1417. if (view.byteLength === 0) {
  1418. return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));
  1419. }
  1420. if (view.buffer.byteLength === 0) {
  1421. return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));
  1422. }
  1423. if (IsDetachedBuffer(view.buffer)) ;
  1424. if (this._ownerReadableStream === undefined) {
  1425. return promiseRejectedWith(readerLockException('read from'));
  1426. }
  1427. let resolvePromise;
  1428. let rejectPromise;
  1429. const promise = newPromise((resolve, reject) => {
  1430. resolvePromise = resolve;
  1431. rejectPromise = reject;
  1432. });
  1433. const readIntoRequest = {
  1434. _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),
  1435. _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),
  1436. _errorSteps: e => rejectPromise(e)
  1437. };
  1438. ReadableStreamBYOBReaderRead(this, view, readIntoRequest);
  1439. return promise;
  1440. }
  1441. /**
  1442. * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
  1443. * If the associated stream is errored when the lock is released, the reader will appear errored in the same way
  1444. * from now on; otherwise, the reader will appear closed.
  1445. *
  1446. * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
  1447. * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to
  1448. * do so will throw a `TypeError` and leave the reader locked to the stream.
  1449. */
  1450. releaseLock() {
  1451. if (!IsReadableStreamBYOBReader(this)) {
  1452. throw byobReaderBrandCheckException('releaseLock');
  1453. }
  1454. if (this._ownerReadableStream === undefined) {
  1455. return;
  1456. }
  1457. if (this._readIntoRequests.length > 0) {
  1458. throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');
  1459. }
  1460. ReadableStreamReaderGenericRelease(this);
  1461. }
  1462. }
  1463. Object.defineProperties(ReadableStreamBYOBReader.prototype, {
  1464. cancel: { enumerable: true },
  1465. read: { enumerable: true },
  1466. releaseLock: { enumerable: true },
  1467. closed: { enumerable: true }
  1468. });
  1469. if (typeof SymbolPolyfill.toStringTag === 'symbol') {
  1470. Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, {
  1471. value: 'ReadableStreamBYOBReader',
  1472. configurable: true
  1473. });
  1474. }
  1475. // Abstract operations for the readers.
  1476. function IsReadableStreamBYOBReader(x) {
  1477. if (!typeIsObject(x)) {
  1478. return false;
  1479. }
  1480. if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {
  1481. return false;
  1482. }
  1483. return x instanceof ReadableStreamBYOBReader;
  1484. }
  1485. function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) {
  1486. const stream = reader._ownerReadableStream;
  1487. stream._disturbed = true;
  1488. if (stream._state === 'errored') {
  1489. readIntoRequest._errorSteps(stream._storedError);
  1490. }
  1491. else {
  1492. ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest);
  1493. }
  1494. }
  1495. // Helper functions for the ReadableStreamBYOBReader.
  1496. function byobReaderBrandCheckException(name) {
  1497. return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);
  1498. }
  1499. function ExtractHighWaterMark(strategy, defaultHWM) {
  1500. const { highWaterMark } = strategy;
  1501. if (highWaterMark === undefined) {
  1502. return defaultHWM;
  1503. }
  1504. if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {
  1505. throw new RangeError('Invalid highWaterMark');
  1506. }
  1507. return highWaterMark;
  1508. }
  1509. function ExtractSizeAlgorithm(strategy) {
  1510. const { size } = strategy;
  1511. if (!size) {
  1512. return () => 1;
  1513. }
  1514. return size;
  1515. }
  1516. function convertQueuingStrategy(init, context) {
  1517. assertDictionary(init, context);
  1518. const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark;
  1519. const size = init === null || init === void 0 ? void 0 : init.size;
  1520. return {
  1521. highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),
  1522. size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)
  1523. };
  1524. }
  1525. function convertQueuingStrategySize(fn, context) {
  1526. assertFunction(fn, context);
  1527. return chunk => convertUnrestrictedDouble(fn(chunk));
  1528. }
  1529. function convertUnderlyingSink(original, context) {
  1530. assertDictionary(original, context);
  1531. const abort = original === null || original === void 0 ? void 0 : original.abort;
  1532. const close = original === null || original === void 0 ? void 0 : original.close;
  1533. const start = original === null || original === void 0 ? void 0 : original.start;
  1534. const type = original === null || original === void 0 ? void 0 : original.type;
  1535. const write = original === null || original === void 0 ? void 0 : original.write;
  1536. return {
  1537. abort: abort === undefined ?
  1538. undefined :
  1539. convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`),
  1540. close: close === undefined ?
  1541. undefined :
  1542. convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`),
  1543. start: start === undefined ?
  1544. undefined :
  1545. convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`),
  1546. write: write === undefined ?
  1547. undefined :
  1548. convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`),
  1549. type
  1550. };
  1551. }
  1552. function convertUnderlyingSinkAbortCallback(fn, original, context) {
  1553. assertFunction(fn, context);
  1554. return (reason) => promiseCall(fn, original, [reason]);
  1555. }
  1556. function convertUnderlyingSinkCloseCallback(fn, original, context) {
  1557. assertFunction(fn, context);
  1558. return () => promiseCall(fn, original, []);
  1559. }
  1560. function convertUnderlyingSinkStartCallback(fn, original, context) {
  1561. assertFunction(fn, context);
  1562. return (controller) => reflectCall(fn, original, [controller]);
  1563. }
  1564. function convertUnderlyingSinkWriteCallback(fn, original, context) {
  1565. assertFunction(fn, context);
  1566. return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);
  1567. }
  1568. function assertWritableStream(x, context) {
  1569. if (!IsWritableStream(x)) {
  1570. throw new TypeError(`${context} is not a WritableStream.`);
  1571. }
  1572. }
  1573. function isAbortSignal(value) {
  1574. if (typeof value !== 'object' || value === null) {
  1575. return false;
  1576. }
  1577. try {
  1578. return typeof value.aborted === 'boolean';
  1579. }
  1580. catch (_a) {
  1581. // AbortSignal.prototype.aborted throws if its brand check fails
  1582. return false;
  1583. }
  1584. }
  1585. const supportsAbortController = typeof AbortController === 'function';
  1586. /**
  1587. * Construct a new AbortController, if supported by the platform.
  1588. *
  1589. * @internal
  1590. */
  1591. function createAbortController() {
  1592. if (supportsAbortController) {
  1593. return new AbortController();
  1594. }
  1595. return undefined;
  1596. }
  1597. /**
  1598. * A writable stream represents a destination for data, into which you can write.
  1599. *
  1600. * @public
  1601. */
  1602. class WritableStream {
  1603. constructor(rawUnderlyingSink = {}, rawStrategy = {}) {
  1604. if (rawUnderlyingSink === undefined) {
  1605. rawUnderlyingSink = null;
  1606. }
  1607. else {
  1608. assertObject(rawUnderlyingSink, 'First parameter');
  1609. }
  1610. const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');
  1611. const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');
  1612. InitializeWritableStream(this);
  1613. const type = underlyingSink.type;
  1614. if (type !== undefined) {
  1615. throw new RangeError('Invalid type is specified');
  1616. }
  1617. const sizeAlgorithm = ExtractSizeAlgorithm(strategy);
  1618. const highWaterMark = ExtractHighWaterMark(strategy, 1);
  1619. SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);
  1620. }
  1621. /**
  1622. * Returns whether or not the writable stream is locked to a writer.
  1623. */
  1624. get locked() {
  1625. if (!IsWritableStream(this)) {
  1626. throw streamBrandCheckException$2('locked');
  1627. }
  1628. return IsWritableStreamLocked(this);
  1629. }
  1630. /**
  1631. * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be
  1632. * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort
  1633. * mechanism of the underlying sink.
  1634. *
  1635. * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled
  1636. * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel
  1637. * the stream) if the stream is currently locked.
  1638. */
  1639. abort(reason = undefined) {
  1640. if (!IsWritableStream(this)) {
  1641. return promiseRejectedWith(streamBrandCheckException$2('abort'));
  1642. }
  1643. if (IsWritableStreamLocked(this)) {
  1644. return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));
  1645. }
  1646. return WritableStreamAbort(this, reason);
  1647. }
  1648. /**
  1649. * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its
  1650. * close behavior. During this time any further attempts to write will fail (without erroring the stream).
  1651. *
  1652. * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream
  1653. * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with
  1654. * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.
  1655. */
  1656. close() {
  1657. if (!IsWritableStream(this)) {
  1658. return promiseRejectedWith(streamBrandCheckException$2('close'));
  1659. }
  1660. if (IsWritableStreamLocked(this)) {
  1661. return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));
  1662. }
  1663. if (WritableStreamCloseQueuedOrInFlight(this)) {
  1664. return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));
  1665. }
  1666. return WritableStreamClose(this);
  1667. }
  1668. /**
  1669. * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream
  1670. * is locked, no other writer can be acquired until this one is released.
  1671. *
  1672. * This functionality is especially useful for creating abstractions that desire the ability to write to a stream
  1673. * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at
  1674. * the same time, which would cause the resulting written data to be unpredictable and probably useless.
  1675. */
  1676. getWriter() {
  1677. if (!IsWritableStream(this)) {
  1678. throw streamBrandCheckException$2('getWriter');
  1679. }
  1680. return AcquireWritableStreamDefaultWriter(this);
  1681. }
  1682. }
  1683. Object.defineProperties(WritableStream.prototype, {
  1684. abort: { enumerable: true },
  1685. close: { enumerable: true },
  1686. getWriter: { enumerable: true },
  1687. locked: { enumerable: true }
  1688. });
  1689. if (typeof SymbolPolyfill.toStringTag === 'symbol') {
  1690. Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, {
  1691. value: 'WritableStream',
  1692. configurable: true
  1693. });
  1694. }
  1695. // Abstract operations for the WritableStream.
  1696. function AcquireWritableStreamDefaultWriter(stream) {
  1697. return new WritableStreamDefaultWriter(stream);
  1698. }
  1699. // Throws if and only if startAlgorithm throws.
  1700. function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
  1701. const stream = Object.create(WritableStream.prototype);
  1702. InitializeWritableStream(stream);
  1703. const controller = Object.create(WritableStreamDefaultController.prototype);
  1704. SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
  1705. return stream;
  1706. }
  1707. function InitializeWritableStream(stream) {
  1708. stream._state = 'writable';
  1709. // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is
  1710. // 'erroring' or 'errored'. May be set to an undefined value.
  1711. stream._storedError = undefined;
  1712. stream._writer = undefined;
  1713. // Initialize to undefined first because the constructor of the controller checks this
  1714. // variable to validate the caller.
  1715. stream._writableStreamController = undefined;
  1716. // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data
  1717. // producer without waiting for the queued writes to finish.
  1718. stream._writeRequests = new SimpleQueue();
  1719. // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents
  1720. // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.
  1721. stream._inFlightWriteRequest = undefined;
  1722. // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer
  1723. // has been detached.
  1724. stream._closeRequest = undefined;
  1725. // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it
  1726. // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.
  1727. stream._inFlightCloseRequest = undefined;
  1728. // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.
  1729. stream._pendingAbortRequest = undefined;
  1730. // The backpressure signal set by the controller.
  1731. stream._backpressure = false;
  1732. }
  1733. function IsWritableStream(x) {
  1734. if (!typeIsObject(x)) {
  1735. return false;
  1736. }
  1737. if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {
  1738. return false;
  1739. }
  1740. return x instanceof WritableStream;
  1741. }
  1742. function IsWritableStreamLocked(stream) {
  1743. if (stream._writer === undefined) {
  1744. return false;
  1745. }
  1746. return true;
  1747. }
  1748. function WritableStreamAbort(stream, reason) {
  1749. var _a;
  1750. if (stream._state === 'closed' || stream._state === 'errored') {
  1751. return promiseResolvedWith(undefined);
  1752. }
  1753. stream._writableStreamController._abortReason = reason;
  1754. (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort();
  1755. // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',
  1756. // but it doesn't know that signaling abort runs author code that might have changed the state.
  1757. // Widen the type again by casting to WritableStreamState.
  1758. const state = stream._state;
  1759. if (state === 'closed' || state === 'errored') {
  1760. return promiseResolvedWith(undefined);
  1761. }
  1762. if (stream._pendingAbortRequest !== undefined) {
  1763. return stream._pendingAbortRequest._promise;
  1764. }
  1765. let wasAlreadyErroring = false;
  1766. if (state === 'erroring') {
  1767. wasAlreadyErroring = true;
  1768. // reason will not be used, so don't keep a reference to it.
  1769. reason = undefined;
  1770. }
  1771. const promise = newPromise((resolve, reject) => {
  1772. stream._pendingAbortRequest = {
  1773. _promise: undefined,
  1774. _resolve: resolve,
  1775. _reject: reject,
  1776. _reason: reason,
  1777. _wasAlreadyErroring: wasAlreadyErroring
  1778. };
  1779. });
  1780. stream._pendingAbortRequest._promise = promise;
  1781. if (!wasAlreadyErroring) {
  1782. WritableStreamStartErroring(stream, reason);
  1783. }
  1784. return promise;
  1785. }
  1786. function WritableStreamClose(stream) {
  1787. const state = stream._state;
  1788. if (state === 'closed' || state === 'errored') {
  1789. return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`));
  1790. }
  1791. const promise = newPromise((resolve, reject) => {
  1792. const closeRequest = {
  1793. _resolve: resolve,
  1794. _reject: reject
  1795. };
  1796. stream._closeRequest = closeRequest;
  1797. });
  1798. const writer = stream._writer;
  1799. if (writer !== undefined && stream._backpressure && state === 'writable') {
  1800. defaultWriterReadyPromiseResolve(writer);
  1801. }
  1802. WritableStreamDefaultControllerClose(stream._writableStreamController);
  1803. return promise;
  1804. }
  1805. // WritableStream API exposed for controllers.
  1806. function WritableStreamAddWriteRequest(stream) {
  1807. const promise = newPromise((resolve, reject) => {
  1808. const writeRequest = {
  1809. _resolve: resolve,
  1810. _reject: reject
  1811. };
  1812. stream._writeRequests.push(writeRequest);
  1813. });
  1814. return promise;
  1815. }
  1816. function WritableStreamDealWithRejection(stream, error) {
  1817. const state = stream._state;
  1818. if (state === 'writable') {
  1819. WritableStreamStartErroring(stream, error);
  1820. return;
  1821. }
  1822. WritableStreamFinishErroring(stream);
  1823. }
  1824. function WritableStreamStartErroring(stream, reason) {
  1825. const controller = stream._writableStreamController;
  1826. stream._state = 'erroring';
  1827. stream._storedError = reason;
  1828. const writer = stream._writer;
  1829. if (writer !== undefined) {
  1830. WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);
  1831. }
  1832. if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {
  1833. WritableStreamFinishErroring(stream);
  1834. }
  1835. }
  1836. function WritableStreamFinishErroring(stream) {
  1837. stream._state = 'errored';
  1838. stream._writableStreamController[ErrorSteps]();
  1839. const storedError = stream._storedError;
  1840. stream._writeRequests.forEach(writeRequest => {
  1841. writeRequest._reject(storedError);
  1842. });
  1843. stream._writeRequests = new SimpleQueue();
  1844. if (stream._pendingAbortRequest === undefined) {
  1845. WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
  1846. return;
  1847. }
  1848. const abortRequest = stream._pendingAbortRequest;
  1849. stream._pendingAbortRequest = undefined;
  1850. if (abortRequest._wasAlreadyErroring) {
  1851. abortRequest._reject(storedError);
  1852. WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
  1853. return;
  1854. }
  1855. const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);
  1856. uponPromise(promise, () => {
  1857. abortRequest._resolve();
  1858. WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
  1859. }, (reason) => {
  1860. abortRequest._reject(reason);
  1861. WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
  1862. });
  1863. }
  1864. function WritableStreamFinishInFlightWrite(stream) {
  1865. stream._inFlightWriteRequest._resolve(undefined);
  1866. stream._inFlightWriteRequest = undefined;
  1867. }
  1868. function WritableStreamFinishInFlightWriteWithError(stream, error) {
  1869. stream._inFlightWriteRequest._reject(error);
  1870. stream._inFlightWriteRequest = undefined;
  1871. WritableStreamDealWithRejection(stream, error);
  1872. }
  1873. function WritableStreamFinishInFlightClose(stream) {
  1874. stream._inFlightCloseRequest._resolve(undefined);
  1875. stream._inFlightCloseRequest = undefined;
  1876. const state = stream._state;
  1877. if (state === 'erroring') {
  1878. // The error was too late to do anything, so it is ignored.
  1879. stream._storedError = undefined;
  1880. if (stream._pendingAbortRequest !== undefined) {
  1881. stream._pendingAbortRequest._resolve();
  1882. stream._pendingAbortRequest = undefined;
  1883. }
  1884. }
  1885. stream._state = 'closed';
  1886. const writer = stream._writer;
  1887. if (writer !== undefined) {
  1888. defaultWriterClosedPromiseResolve(writer);
  1889. }
  1890. }
  1891. function WritableStreamFinishInFlightCloseWithError(stream, error) {
  1892. stream._inFlightCloseRequest._reject(error);
  1893. stream._inFlightCloseRequest = undefined;
  1894. // Never execute sink abort() after sink close().
  1895. if (stream._pendingAbortRequest !== undefined) {
  1896. stream._pendingAbortRequest._reject(error);
  1897. stream._pendingAbortRequest = undefined;
  1898. }
  1899. WritableStreamDealWithRejection(stream, error);
  1900. }
  1901. // TODO(ricea): Fix alphabetical order.
  1902. function WritableStreamCloseQueuedOrInFlight(stream) {
  1903. if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {
  1904. return false;
  1905. }
  1906. return true;
  1907. }
  1908. function WritableStreamHasOperationMarkedInFlight(stream) {
  1909. if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {
  1910. return false;
  1911. }
  1912. return true;
  1913. }
  1914. function WritableStreamMarkCloseRequestInFlight(stream) {
  1915. stream._inFlightCloseRequest = stream._closeRequest;
  1916. stream._closeRequest = undefined;
  1917. }
  1918. function WritableStreamMarkFirstWriteRequestInFlight(stream) {
  1919. stream._inFlightWriteRequest = stream._writeRequests.shift();
  1920. }
  1921. function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) {
  1922. if (stream._closeRequest !== undefined) {
  1923. stream._closeRequest._reject(stream._storedError);
  1924. stream._closeRequest = undefined;
  1925. }
  1926. const writer = stream._writer;
  1927. if (writer !== undefined) {
  1928. defaultWriterClosedPromiseReject(writer, stream._storedError);
  1929. }
  1930. }
  1931. function WritableStreamUpdateBackpressure(stream, backpressure) {
  1932. const writer = stream._writer;
  1933. if (writer !== undefined && backpressure !== stream._backpressure) {
  1934. if (backpressure) {
  1935. defaultWriterReadyPromiseReset(writer);
  1936. }
  1937. else {
  1938. defaultWriterReadyPromiseResolve(writer);
  1939. }
  1940. }
  1941. stream._backpressure = backpressure;
  1942. }
  1943. /**
  1944. * A default writer vended by a {@link WritableStream}.
  1945. *
  1946. * @public
  1947. */
  1948. class WritableStreamDefaultWriter {
  1949. constructor(stream) {
  1950. assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');
  1951. assertWritableStream(stream, 'First parameter');
  1952. if (IsWritableStreamLocked(stream)) {
  1953. throw new TypeError('This stream has already been locked for exclusive writing by another writer');
  1954. }
  1955. this._ownerWritableStream = stream;
  1956. stream._writer = this;
  1957. const state = stream._state;
  1958. if (state === 'writable') {
  1959. if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {
  1960. defaultWriterReadyPromiseInitialize(this);
  1961. }
  1962. else {
  1963. defaultWriterReadyPromiseInitializeAsResolved(this);
  1964. }
  1965. defaultWriterClosedPromiseInitialize(this);
  1966. }
  1967. else if (state === 'erroring') {
  1968. defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);
  1969. defaultWriterClosedPromiseInitialize(this);
  1970. }
  1971. else if (state === 'closed') {
  1972. defaultWriterReadyPromiseInitializeAsResolved(this);
  1973. defaultWriterClosedPromiseInitializeAsResolved(this);
  1974. }
  1975. else {
  1976. const storedError = stream._storedError;
  1977. defaultWriterReadyPromiseInitializeAsRejected(this, storedError);
  1978. defaultWriterClosedPromiseInitializeAsRejected(this, storedError);
  1979. }
  1980. }
  1981. /**
  1982. * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
  1983. * the writer’s lock is released before the stream finishes closing.
  1984. */
  1985. get closed() {
  1986. if (!IsWritableStreamDefaultWriter(this)) {
  1987. return promiseRejectedWith(defaultWriterBrandCheckException('closed'));
  1988. }
  1989. return this._closedPromise;
  1990. }
  1991. /**
  1992. * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.
  1993. * A producer can use this information to determine the right amount of data to write.
  1994. *
  1995. * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort
  1996. * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when
  1997. * the writer’s lock is released.
  1998. */
  1999. get desiredSize() {
  2000. if (!IsWritableStreamDefaultWriter(this)) {
  2001. throw defaultWriterBrandCheckException('desiredSize');
  2002. }
  2003. if (this._ownerWritableStream === undefined) {
  2004. throw defaultWriterLockException('desiredSize');
  2005. }
  2006. return WritableStreamDefaultWriterGetDesiredSize(this);
  2007. }
  2008. /**
  2009. * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions
  2010. * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips
  2011. * back to zero or below, the getter will return a new promise that stays pending until the next transition.
  2012. *
  2013. * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become
  2014. * rejected.
  2015. */
  2016. get ready() {
  2017. if (!IsWritableStreamDefaultWriter(this)) {
  2018. return promiseRejectedWith(defaultWriterBrandCheckException('ready'));
  2019. }
  2020. return this._readyPromise;
  2021. }
  2022. /**
  2023. * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.
  2024. */
  2025. abort(reason = undefined) {
  2026. if (!IsWritableStreamDefaultWriter(this)) {
  2027. return promiseRejectedWith(defaultWriterBrandCheckException('abort'));
  2028. }
  2029. if (this._ownerWritableStream === undefined) {
  2030. return promiseRejectedWith(defaultWriterLockException('abort'));
  2031. }
  2032. return WritableStreamDefaultWriterAbort(this, reason);
  2033. }
  2034. /**
  2035. * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.
  2036. */
  2037. close() {
  2038. if (!IsWritableStreamDefaultWriter(this)) {
  2039. return promiseRejectedWith(defaultWriterBrandCheckException('close'));
  2040. }
  2041. const stream = this._ownerWritableStream;
  2042. if (stream === undefined) {
  2043. return promiseRejectedWith(defaultWriterLockException('close'));
  2044. }
  2045. if (WritableStreamCloseQueuedOrInFlight(stream)) {
  2046. return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));
  2047. }
  2048. return WritableStreamDefaultWriterClose(this);
  2049. }
  2050. /**
  2051. * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.
  2052. * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from
  2053. * now on; otherwise, the writer will appear closed.
  2054. *
  2055. * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the
  2056. * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).
  2057. * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents
  2058. * other producers from writing in an interleaved manner.
  2059. */
  2060. releaseLock() {
  2061. if (!IsWritableStreamDefaultWriter(this)) {
  2062. throw defaultWriterBrandCheckException('releaseLock');
  2063. }
  2064. const stream = this._ownerWritableStream;
  2065. if (stream === undefined) {
  2066. return;
  2067. }
  2068. WritableStreamDefaultWriterRelease(this);
  2069. }
  2070. write(chunk = undefined) {
  2071. if (!IsWritableStreamDefaultWriter(this)) {
  2072. return promiseRejectedWith(defaultWriterBrandCheckException('write'));
  2073. }
  2074. if (this._ownerWritableStream === undefined) {
  2075. return promiseRejectedWith(defaultWriterLockException('write to'));
  2076. }
  2077. return WritableStreamDefaultWriterWrite(this, chunk);
  2078. }
  2079. }
  2080. Object.defineProperties(WritableStreamDefaultWriter.prototype, {
  2081. abort: { enumerable: true },
  2082. close: { enumerable: true },
  2083. releaseLock: { enumerable: true },
  2084. write: { enumerable: true },
  2085. closed: { enumerable: true },
  2086. desiredSize: { enumerable: true },
  2087. ready: { enumerable: true }
  2088. });
  2089. if (typeof SymbolPolyfill.toStringTag === 'symbol') {
  2090. Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, {
  2091. value: 'WritableStreamDefaultWriter',
  2092. configurable: true
  2093. });
  2094. }
  2095. // Abstract operations for the WritableStreamDefaultWriter.
  2096. function IsWritableStreamDefaultWriter(x) {
  2097. if (!typeIsObject(x)) {
  2098. return false;
  2099. }
  2100. if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {
  2101. return false;
  2102. }
  2103. return x instanceof WritableStreamDefaultWriter;
  2104. }
  2105. // A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.
  2106. function WritableStreamDefaultWriterAbort(writer, reason) {
  2107. const stream = writer._ownerWritableStream;
  2108. return WritableStreamAbort(stream, reason);
  2109. }
  2110. function WritableStreamDefaultWriterClose(writer) {
  2111. const stream = writer._ownerWritableStream;
  2112. return WritableStreamClose(stream);
  2113. }
  2114. function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) {
  2115. const stream = writer._ownerWritableStream;
  2116. const state = stream._state;
  2117. if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {
  2118. return promiseResolvedWith(undefined);
  2119. }
  2120. if (state === 'errored') {
  2121. return promiseRejectedWith(stream._storedError);
  2122. }
  2123. return WritableStreamDefaultWriterClose(writer);
  2124. }
  2125. function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) {
  2126. if (writer._closedPromiseState === 'pending') {
  2127. defaultWriterClosedPromiseReject(writer, error);
  2128. }
  2129. else {
  2130. defaultWriterClosedPromiseResetToRejected(writer, error);
  2131. }
  2132. }
  2133. function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) {
  2134. if (writer._readyPromiseState === 'pending') {
  2135. defaultWriterReadyPromiseReject(writer, error);
  2136. }
  2137. else {
  2138. defaultWriterReadyPromiseResetToRejected(writer, error);
  2139. }
  2140. }
  2141. function WritableStreamDefaultWriterGetDesiredSize(writer) {
  2142. const stream = writer._ownerWritableStream;
  2143. const state = stream._state;
  2144. if (state === 'errored' || state === 'erroring') {
  2145. return null;
  2146. }
  2147. if (state === 'closed') {
  2148. return 0;
  2149. }
  2150. return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);
  2151. }
  2152. function WritableStreamDefaultWriterRelease(writer) {
  2153. const stream = writer._ownerWritableStream;
  2154. const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`);
  2155. WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);
  2156. // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not
  2157. // rejected until afterwards. This means that simply testing state will not work.
  2158. WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);
  2159. stream._writer = undefined;
  2160. writer._ownerWritableStream = undefined;
  2161. }
  2162. function WritableStreamDefaultWriterWrite(writer, chunk) {
  2163. const stream = writer._ownerWritableStream;
  2164. const controller = stream._writableStreamController;
  2165. const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);
  2166. if (stream !== writer._ownerWritableStream) {
  2167. return promiseRejectedWith(defaultWriterLockException('write to'));
  2168. }
  2169. const state = stream._state;
  2170. if (state === 'errored') {
  2171. return promiseRejectedWith(stream._storedError);
  2172. }
  2173. if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {
  2174. return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));
  2175. }
  2176. if (state === 'erroring') {
  2177. return promiseRejectedWith(stream._storedError);
  2178. }
  2179. const promise = WritableStreamAddWriteRequest(stream);
  2180. WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);
  2181. return promise;
  2182. }
  2183. const closeSentinel = {};
  2184. /**
  2185. * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.
  2186. *
  2187. * @public
  2188. */
  2189. class WritableStreamDefaultController {
  2190. constructor() {
  2191. throw new TypeError('Illegal constructor');
  2192. }
  2193. /**
  2194. * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.
  2195. *
  2196. * @deprecated
  2197. * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.
  2198. * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.
  2199. */
  2200. get abortReason() {
  2201. if (!IsWritableStreamDefaultController(this)) {
  2202. throw defaultControllerBrandCheckException$2('abortReason');
  2203. }
  2204. return this._abortReason;
  2205. }
  2206. /**
  2207. * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.
  2208. */
  2209. get signal() {
  2210. if (!IsWritableStreamDefaultController(this)) {
  2211. throw defaultControllerBrandCheckException$2('signal');
  2212. }
  2213. if (this._abortController === undefined) {
  2214. // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.
  2215. // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,
  2216. // so instead we only implement support for `signal` if we find a global `AbortController` constructor.
  2217. throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');
  2218. }
  2219. return this._abortController.signal;
  2220. }
  2221. /**
  2222. * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.
  2223. *
  2224. * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying
  2225. * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the
  2226. * normal lifecycle of interactions with the underlying sink.
  2227. */
  2228. error(e = undefined) {
  2229. if (!IsWritableStreamDefaultController(this)) {
  2230. throw defaultControllerBrandCheckException$2('error');
  2231. }
  2232. const state = this._controlledWritableStream._state;
  2233. if (state !== 'writable') {
  2234. // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so
  2235. // just treat it as a no-op.
  2236. return;
  2237. }
  2238. WritableStreamDefaultControllerError(this, e);
  2239. }
  2240. /** @internal */
  2241. [AbortSteps](reason) {
  2242. const result = this._abortAlgorithm(reason);
  2243. WritableStreamDefaultControllerClearAlgorithms(this);
  2244. return result;
  2245. }
  2246. /** @internal */
  2247. [ErrorSteps]() {
  2248. ResetQueue(this);
  2249. }
  2250. }
  2251. Object.defineProperties(WritableStreamDefaultController.prototype, {
  2252. abortReason: { enumerable: true },
  2253. signal: { enumerable: true },
  2254. error: { enumerable: true }
  2255. });
  2256. if (typeof SymbolPolyfill.toStringTag === 'symbol') {
  2257. Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
  2258. value: 'WritableStreamDefaultController',
  2259. configurable: true
  2260. });
  2261. }
  2262. // Abstract operations implementing interface required by the WritableStream.
  2263. function IsWritableStreamDefaultController(x) {
  2264. if (!typeIsObject(x)) {
  2265. return false;
  2266. }
  2267. if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {
  2268. return false;
  2269. }
  2270. return x instanceof WritableStreamDefaultController;
  2271. }
  2272. function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) {
  2273. controller._controlledWritableStream = stream;
  2274. stream._writableStreamController = controller;
  2275. // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.
  2276. controller._queue = undefined;
  2277. controller._queueTotalSize = undefined;
  2278. ResetQueue(controller);
  2279. controller._abortReason = undefined;
  2280. controller._abortController = createAbortController();
  2281. controller._started = false;
  2282. controller._strategySizeAlgorithm = sizeAlgorithm;
  2283. controller._strategyHWM = highWaterMark;
  2284. controller._writeAlgorithm = writeAlgorithm;
  2285. controller._closeAlgorithm = closeAlgorithm;
  2286. controller._abortAlgorithm = abortAlgorithm;
  2287. const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
  2288. WritableStreamUpdateBackpressure(stream, backpressure);
  2289. const startResult = startAlgorithm();
  2290. const startPromise = promiseResolvedWith(startResult);
  2291. uponPromise(startPromise, () => {
  2292. controller._started = true;
  2293. WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
  2294. }, r => {
  2295. controller._started = true;
  2296. WritableStreamDealWithRejection(stream, r);
  2297. });
  2298. }
  2299. function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) {
  2300. const controller = Object.create(WritableStreamDefaultController.prototype);
  2301. let startAlgorithm = () => undefined;
  2302. let writeAlgorithm = () => promiseResolvedWith(undefined);
  2303. let closeAlgorithm = () => promiseResolvedWith(undefined);
  2304. let abortAlgorithm = () => promiseResolvedWith(undefined);
  2305. if (underlyingSink.start !== undefined) {
  2306. startAlgorithm = () => underlyingSink.start(controller);
  2307. }
  2308. if (underlyingSink.write !== undefined) {
  2309. writeAlgorithm = chunk => underlyingSink.write(chunk, controller);
  2310. }
  2311. if (underlyingSink.close !== undefined) {
  2312. closeAlgorithm = () => underlyingSink.close();
  2313. }
  2314. if (underlyingSink.abort !== undefined) {
  2315. abortAlgorithm = reason => underlyingSink.abort(reason);
  2316. }
  2317. SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
  2318. }
  2319. // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.
  2320. function WritableStreamDefaultControllerClearAlgorithms(controller) {
  2321. controller._writeAlgorithm = undefined;
  2322. controller._closeAlgorithm = undefined;
  2323. controller._abortAlgorithm = undefined;
  2324. controller._strategySizeAlgorithm = undefined;
  2325. }
  2326. function WritableStreamDefaultControllerClose(controller) {
  2327. EnqueueValueWithSize(controller, closeSentinel, 0);
  2328. WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
  2329. }
  2330. function WritableStreamDefaultControllerGetChunkSize(controller, chunk) {
  2331. try {
  2332. return controller._strategySizeAlgorithm(chunk);
  2333. }
  2334. catch (chunkSizeE) {
  2335. WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);
  2336. return 1;
  2337. }
  2338. }
  2339. function WritableStreamDefaultControllerGetDesiredSize(controller) {
  2340. return controller._strategyHWM - controller._queueTotalSize;
  2341. }
  2342. function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) {
  2343. try {
  2344. EnqueueValueWithSize(controller, chunk, chunkSize);
  2345. }
  2346. catch (enqueueE) {
  2347. WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);
  2348. return;
  2349. }
  2350. const stream = controller._controlledWritableStream;
  2351. if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {
  2352. const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
  2353. WritableStreamUpdateBackpressure(stream, backpressure);
  2354. }
  2355. WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
  2356. }
  2357. // Abstract operations for the WritableStreamDefaultController.
  2358. function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) {
  2359. const stream = controller._controlledWritableStream;
  2360. if (!controller._started) {
  2361. return;
  2362. }
  2363. if (stream._inFlightWriteRequest !== undefined) {
  2364. return;
  2365. }
  2366. const state = stream._state;
  2367. if (state === 'erroring') {
  2368. WritableStreamFinishErroring(stream);
  2369. return;
  2370. }
  2371. if (controller._queue.length === 0) {
  2372. return;
  2373. }
  2374. const value = PeekQueueValue(controller);
  2375. if (value === closeSentinel) {
  2376. WritableStreamDefaultControllerProcessClose(controller);
  2377. }
  2378. else {
  2379. WritableStreamDefaultControllerProcessWrite(controller, value);
  2380. }
  2381. }
  2382. function WritableStreamDefaultControllerErrorIfNeeded(controller, error) {
  2383. if (controller._controlledWritableStream._state === 'writable') {
  2384. WritableStreamDefaultControllerError(controller, error);
  2385. }
  2386. }
  2387. function WritableStreamDefaultControllerProcessClose(controller) {
  2388. const stream = controller._controlledWritableStream;
  2389. WritableStreamMarkCloseRequestInFlight(stream);
  2390. DequeueValue(controller);
  2391. const sinkClosePromise = controller._closeAlgorithm();
  2392. WritableStreamDefaultControllerClearAlgorithms(controller);
  2393. uponPromise(sinkClosePromise, () => {
  2394. WritableStreamFinishInFlightClose(stream);
  2395. }, reason => {
  2396. WritableStreamFinishInFlightCloseWithError(stream, reason);
  2397. });
  2398. }
  2399. function WritableStreamDefaultControllerProcessWrite(controller, chunk) {
  2400. const stream = controller._controlledWritableStream;
  2401. WritableStreamMarkFirstWriteRequestInFlight(stream);
  2402. const sinkWritePromise = controller._writeAlgorithm(chunk);
  2403. uponPromise(sinkWritePromise, () => {
  2404. WritableStreamFinishInFlightWrite(stream);
  2405. const state = stream._state;
  2406. DequeueValue(controller);
  2407. if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {
  2408. const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
  2409. WritableStreamUpdateBackpressure(stream, backpressure);
  2410. }
  2411. WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
  2412. }, reason => {
  2413. if (stream._state === 'writable') {
  2414. WritableStreamDefaultControllerClearAlgorithms(controller);
  2415. }
  2416. WritableStreamFinishInFlightWriteWithError(stream, reason);
  2417. });
  2418. }
  2419. function WritableStreamDefaultControllerGetBackpressure(controller) {
  2420. const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);
  2421. return desiredSize <= 0;
  2422. }
  2423. // A client of WritableStreamDefaultController may use these functions directly to bypass state check.
  2424. function WritableStreamDefaultControllerError(controller, error) {
  2425. const stream = controller._controlledWritableStream;
  2426. WritableStreamDefaultControllerClearAlgorithms(controller);
  2427. WritableStreamStartErroring(stream, error);
  2428. }
  2429. // Helper functions for the WritableStream.
  2430. function streamBrandCheckException$2(name) {
  2431. return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);
  2432. }
  2433. // Helper functions for the WritableStreamDefaultController.
  2434. function defaultControllerBrandCheckException$2(name) {
  2435. return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);
  2436. }
  2437. // Helper functions for the WritableStreamDefaultWriter.
  2438. function defaultWriterBrandCheckException(name) {
  2439. return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);
  2440. }
  2441. function defaultWriterLockException(name) {
  2442. return new TypeError('Cannot ' + name + ' a stream using a released writer');
  2443. }
  2444. function defaultWriterClosedPromiseInitialize(writer) {
  2445. writer._closedPromise = newPromise((resolve, reject) => {
  2446. writer._closedPromise_resolve = resolve;
  2447. writer._closedPromise_reject = reject;
  2448. writer._closedPromiseState = 'pending';
  2449. });
  2450. }
  2451. function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) {
  2452. defaultWriterClosedPromiseInitialize(writer);
  2453. defaultWriterClosedPromiseReject(writer, reason);
  2454. }
  2455. function defaultWriterClosedPromiseInitializeAsResolved(writer) {
  2456. defaultWriterClosedPromiseInitialize(writer);
  2457. defaultWriterClosedPromiseResolve(writer);
  2458. }
  2459. function defaultWriterClosedPromiseReject(writer, reason) {
  2460. if (writer._closedPromise_reject === undefined) {
  2461. return;
  2462. }
  2463. setPromiseIsHandledToTrue(writer._closedPromise);
  2464. writer._closedPromise_reject(reason);
  2465. writer._closedPromise_resolve = undefined;
  2466. writer._closedPromise_reject = undefined;
  2467. writer._closedPromiseState = 'rejected';
  2468. }
  2469. function defaultWriterClosedPromiseResetToRejected(writer, reason) {
  2470. defaultWriterClosedPromiseInitializeAsRejected(writer, reason);
  2471. }
  2472. function defaultWriterClosedPromiseResolve(writer) {
  2473. if (writer._closedPromise_resolve === undefined) {
  2474. return;
  2475. }
  2476. writer._closedPromise_resolve(undefined);
  2477. writer._closedPromise_resolve = undefined;
  2478. writer._closedPromise_reject = undefined;
  2479. writer._closedPromiseState = 'resolved';
  2480. }
  2481. function defaultWriterReadyPromiseInitialize(writer) {
  2482. writer._readyPromise = newPromise((resolve, reject) => {
  2483. writer._readyPromise_resolve = resolve;
  2484. writer._readyPromise_reject = reject;
  2485. });
  2486. writer._readyPromiseState = 'pending';
  2487. }
  2488. function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) {
  2489. defaultWriterReadyPromiseInitialize(writer);
  2490. defaultWriterReadyPromiseReject(writer, reason);
  2491. }
  2492. function defaultWriterReadyPromiseInitializeAsResolved(writer) {
  2493. defaultWriterReadyPromiseInitialize(writer);
  2494. defaultWriterReadyPromiseResolve(writer);
  2495. }
  2496. function defaultWriterReadyPromiseReject(writer, reason) {
  2497. if (writer._readyPromise_reject === undefined) {
  2498. return;
  2499. }
  2500. setPromiseIsHandledToTrue(writer._readyPromise);
  2501. writer._readyPromise_reject(reason);
  2502. writer._readyPromise_resolve = undefined;
  2503. writer._readyPromise_reject = undefined;
  2504. writer._readyPromiseState = 'rejected';
  2505. }
  2506. function defaultWriterReadyPromiseReset(writer) {
  2507. defaultWriterReadyPromiseInitialize(writer);
  2508. }
  2509. function defaultWriterReadyPromiseResetToRejected(writer, reason) {
  2510. defaultWriterReadyPromiseInitializeAsRejected(writer, reason);
  2511. }
  2512. function defaultWriterReadyPromiseResolve(writer) {
  2513. if (writer._readyPromise_resolve === undefined) {
  2514. return;
  2515. }
  2516. writer._readyPromise_resolve(undefined);
  2517. writer._readyPromise_resolve = undefined;
  2518. writer._readyPromise_reject = undefined;
  2519. writer._readyPromiseState = 'fulfilled';
  2520. }
  2521. /// <reference lib="dom" />
  2522. const NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined;
  2523. /// <reference types="node" />
  2524. function isDOMExceptionConstructor(ctor) {
  2525. if (!(typeof ctor === 'function' || typeof ctor === 'object')) {
  2526. return false;
  2527. }
  2528. try {
  2529. new ctor();
  2530. return true;
  2531. }
  2532. catch (_a) {
  2533. return false;
  2534. }
  2535. }
  2536. function createDOMExceptionPolyfill() {
  2537. // eslint-disable-next-line no-shadow
  2538. const ctor = function DOMException(message, name) {
  2539. this.message = message || '';
  2540. this.name = name || 'Error';
  2541. if (Error.captureStackTrace) {
  2542. Error.captureStackTrace(this, this.constructor);
  2543. }
  2544. };
  2545. ctor.prototype = Object.create(Error.prototype);
  2546. Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });
  2547. return ctor;
  2548. }
  2549. // eslint-disable-next-line no-redeclare
  2550. const DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill();
  2551. function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) {
  2552. const reader = AcquireReadableStreamDefaultReader(source);
  2553. const writer = AcquireWritableStreamDefaultWriter(dest);
  2554. source._disturbed = true;
  2555. let shuttingDown = false;
  2556. // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.
  2557. let currentWrite = promiseResolvedWith(undefined);
  2558. return newPromise((resolve, reject) => {
  2559. let abortAlgorithm;
  2560. if (signal !== undefined) {
  2561. abortAlgorithm = () => {
  2562. const error = new DOMException$1('Aborted', 'AbortError');
  2563. const actions = [];
  2564. if (!preventAbort) {
  2565. actions.push(() => {
  2566. if (dest._state === 'writable') {
  2567. return WritableStreamAbort(dest, error);
  2568. }
  2569. return promiseResolvedWith(undefined);
  2570. });
  2571. }
  2572. if (!preventCancel) {
  2573. actions.push(() => {
  2574. if (source._state === 'readable') {
  2575. return ReadableStreamCancel(source, error);
  2576. }
  2577. return promiseResolvedWith(undefined);
  2578. });
  2579. }
  2580. shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);
  2581. };
  2582. if (signal.aborted) {
  2583. abortAlgorithm();
  2584. return;
  2585. }
  2586. signal.addEventListener('abort', abortAlgorithm);
  2587. }
  2588. // Using reader and writer, read all chunks from this and write them to dest
  2589. // - Backpressure must be enforced
  2590. // - Shutdown must stop all activity
  2591. function pipeLoop() {
  2592. return newPromise((resolveLoop, rejectLoop) => {
  2593. function next(done) {
  2594. if (done) {
  2595. resolveLoop();
  2596. }
  2597. else {
  2598. // Use `PerformPromiseThen` instead of `uponPromise` to avoid
  2599. // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers
  2600. PerformPromiseThen(pipeStep(), next, rejectLoop);
  2601. }
  2602. }
  2603. next(false);
  2604. });
  2605. }
  2606. function pipeStep() {
  2607. if (shuttingDown) {
  2608. return promiseResolvedWith(true);
  2609. }
  2610. return PerformPromiseThen(writer._readyPromise, () => {
  2611. return newPromise((resolveRead, rejectRead) => {
  2612. ReadableStreamDefaultReaderRead(reader, {
  2613. _chunkSteps: chunk => {
  2614. currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);
  2615. resolveRead(false);
  2616. },
  2617. _closeSteps: () => resolveRead(true),
  2618. _errorSteps: rejectRead
  2619. });
  2620. });
  2621. });
  2622. }
  2623. // Errors must be propagated forward
  2624. isOrBecomesErrored(source, reader._closedPromise, storedError => {
  2625. if (!preventAbort) {
  2626. shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);
  2627. }
  2628. else {
  2629. shutdown(true, storedError);
  2630. }
  2631. });
  2632. // Errors must be propagated backward
  2633. isOrBecomesErrored(dest, writer._closedPromise, storedError => {
  2634. if (!preventCancel) {
  2635. shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);
  2636. }
  2637. else {
  2638. shutdown(true, storedError);
  2639. }
  2640. });
  2641. // Closing must be propagated forward
  2642. isOrBecomesClosed(source, reader._closedPromise, () => {
  2643. if (!preventClose) {
  2644. shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));
  2645. }
  2646. else {
  2647. shutdown();
  2648. }
  2649. });
  2650. // Closing must be propagated backward
  2651. if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {
  2652. const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');
  2653. if (!preventCancel) {
  2654. shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);
  2655. }
  2656. else {
  2657. shutdown(true, destClosed);
  2658. }
  2659. }
  2660. setPromiseIsHandledToTrue(pipeLoop());
  2661. function waitForWritesToFinish() {
  2662. // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait
  2663. // for that too.
  2664. const oldCurrentWrite = currentWrite;
  2665. return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined);
  2666. }
  2667. function isOrBecomesErrored(stream, promise, action) {
  2668. if (stream._state === 'errored') {
  2669. action(stream._storedError);
  2670. }
  2671. else {
  2672. uponRejection(promise, action);
  2673. }
  2674. }
  2675. function isOrBecomesClosed(stream, promise, action) {
  2676. if (stream._state === 'closed') {
  2677. action();
  2678. }
  2679. else {
  2680. uponFulfillment(promise, action);
  2681. }
  2682. }
  2683. function shutdownWithAction(action, originalIsError, originalError) {
  2684. if (shuttingDown) {
  2685. return;
  2686. }
  2687. shuttingDown = true;
  2688. if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {
  2689. uponFulfillment(waitForWritesToFinish(), doTheRest);
  2690. }
  2691. else {
  2692. doTheRest();
  2693. }
  2694. function doTheRest() {
  2695. uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError));
  2696. }
  2697. }
  2698. function shutdown(isError, error) {
  2699. if (shuttingDown) {
  2700. return;
  2701. }
  2702. shuttingDown = true;
  2703. if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {
  2704. uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));
  2705. }
  2706. else {
  2707. finalize(isError, error);
  2708. }
  2709. }
  2710. function finalize(isError, error) {
  2711. WritableStreamDefaultWriterRelease(writer);
  2712. ReadableStreamReaderGenericRelease(reader);
  2713. if (signal !== undefined) {
  2714. signal.removeEventListener('abort', abortAlgorithm);
  2715. }
  2716. if (isError) {
  2717. reject(error);
  2718. }
  2719. else {
  2720. resolve(undefined);
  2721. }
  2722. }
  2723. });
  2724. }
  2725. /**
  2726. * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.
  2727. *
  2728. * @public
  2729. */
  2730. class ReadableStreamDefaultController {
  2731. constructor() {
  2732. throw new TypeError('Illegal constructor');
  2733. }
  2734. /**
  2735. * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
  2736. * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.
  2737. */
  2738. get desiredSize() {
  2739. if (!IsReadableStreamDefaultController(this)) {
  2740. throw defaultControllerBrandCheckException$1('desiredSize');
  2741. }
  2742. return ReadableStreamDefaultControllerGetDesiredSize(this);
  2743. }
  2744. /**
  2745. * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
  2746. * the stream, but once those are read, the stream will become closed.
  2747. */
  2748. close() {
  2749. if (!IsReadableStreamDefaultController(this)) {
  2750. throw defaultControllerBrandCheckException$1('close');
  2751. }
  2752. if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {
  2753. throw new TypeError('The stream is not in a state that permits close');
  2754. }
  2755. ReadableStreamDefaultControllerClose(this);
  2756. }
  2757. enqueue(chunk = undefined) {
  2758. if (!IsReadableStreamDefaultController(this)) {
  2759. throw defaultControllerBrandCheckException$1('enqueue');
  2760. }
  2761. if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {
  2762. throw new TypeError('The stream is not in a state that permits enqueue');
  2763. }
  2764. return ReadableStreamDefaultControllerEnqueue(this, chunk);
  2765. }
  2766. /**
  2767. * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
  2768. */
  2769. error(e = undefined) {
  2770. if (!IsReadableStreamDefaultController(this)) {
  2771. throw defaultControllerBrandCheckException$1('error');
  2772. }
  2773. ReadableStreamDefaultControllerError(this, e);
  2774. }
  2775. /** @internal */
  2776. [CancelSteps](reason) {
  2777. ResetQueue(this);
  2778. const result = this._cancelAlgorithm(reason);
  2779. ReadableStreamDefaultControllerClearAlgorithms(this);
  2780. return result;
  2781. }
  2782. /** @internal */
  2783. [PullSteps](readRequest) {
  2784. const stream = this._controlledReadableStream;
  2785. if (this._queue.length > 0) {
  2786. const chunk = DequeueValue(this);
  2787. if (this._closeRequested && this._queue.length === 0) {
  2788. ReadableStreamDefaultControllerClearAlgorithms(this);
  2789. ReadableStreamClose(stream);
  2790. }
  2791. else {
  2792. ReadableStreamDefaultControllerCallPullIfNeeded(this);
  2793. }
  2794. readRequest._chunkSteps(chunk);
  2795. }
  2796. else {
  2797. ReadableStreamAddReadRequest(stream, readRequest);
  2798. ReadableStreamDefaultControllerCallPullIfNeeded(this);
  2799. }
  2800. }
  2801. }
  2802. Object.defineProperties(ReadableStreamDefaultController.prototype, {
  2803. close: { enumerable: true },
  2804. enqueue: { enumerable: true },
  2805. error: { enumerable: true },
  2806. desiredSize: { enumerable: true }
  2807. });
  2808. if (typeof SymbolPolyfill.toStringTag === 'symbol') {
  2809. Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
  2810. value: 'ReadableStreamDefaultController',
  2811. configurable: true
  2812. });
  2813. }
  2814. // Abstract operations for the ReadableStreamDefaultController.
  2815. function IsReadableStreamDefaultController(x) {
  2816. if (!typeIsObject(x)) {
  2817. return false;
  2818. }
  2819. if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {
  2820. return false;
  2821. }
  2822. return x instanceof ReadableStreamDefaultController;
  2823. }
  2824. function ReadableStreamDefaultControllerCallPullIfNeeded(controller) {
  2825. const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);
  2826. if (!shouldPull) {
  2827. return;
  2828. }
  2829. if (controller._pulling) {
  2830. controller._pullAgain = true;
  2831. return;
  2832. }
  2833. controller._pulling = true;
  2834. const pullPromise = controller._pullAlgorithm();
  2835. uponPromise(pullPromise, () => {
  2836. controller._pulling = false;
  2837. if (controller._pullAgain) {
  2838. controller._pullAgain = false;
  2839. ReadableStreamDefaultControllerCallPullIfNeeded(controller);
  2840. }
  2841. }, e => {
  2842. ReadableStreamDefaultControllerError(controller, e);
  2843. });
  2844. }
  2845. function ReadableStreamDefaultControllerShouldCallPull(controller) {
  2846. const stream = controller._controlledReadableStream;
  2847. if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
  2848. return false;
  2849. }
  2850. if (!controller._started) {
  2851. return false;
  2852. }
  2853. if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
  2854. return true;
  2855. }
  2856. const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);
  2857. if (desiredSize > 0) {
  2858. return true;
  2859. }
  2860. return false;
  2861. }
  2862. function ReadableStreamDefaultControllerClearAlgorithms(controller) {
  2863. controller._pullAlgorithm = undefined;
  2864. controller._cancelAlgorithm = undefined;
  2865. controller._strategySizeAlgorithm = undefined;
  2866. }
  2867. // A client of ReadableStreamDefaultController may use these functions directly to bypass state check.
  2868. function ReadableStreamDefaultControllerClose(controller) {
  2869. if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
  2870. return;
  2871. }
  2872. const stream = controller._controlledReadableStream;
  2873. controller._closeRequested = true;
  2874. if (controller._queue.length === 0) {
  2875. ReadableStreamDefaultControllerClearAlgorithms(controller);
  2876. ReadableStreamClose(stream);
  2877. }
  2878. }
  2879. function ReadableStreamDefaultControllerEnqueue(controller, chunk) {
  2880. if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
  2881. return;
  2882. }
  2883. const stream = controller._controlledReadableStream;
  2884. if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
  2885. ReadableStreamFulfillReadRequest(stream, chunk, false);
  2886. }
  2887. else {
  2888. let chunkSize;
  2889. try {
  2890. chunkSize = controller._strategySizeAlgorithm(chunk);
  2891. }
  2892. catch (chunkSizeE) {
  2893. ReadableStreamDefaultControllerError(controller, chunkSizeE);
  2894. throw chunkSizeE;
  2895. }
  2896. try {
  2897. EnqueueValueWithSize(controller, chunk, chunkSize);
  2898. }
  2899. catch (enqueueE) {
  2900. ReadableStreamDefaultControllerError(controller, enqueueE);
  2901. throw enqueueE;
  2902. }
  2903. }
  2904. ReadableStreamDefaultControllerCallPullIfNeeded(controller);
  2905. }
  2906. function ReadableStreamDefaultControllerError(controller, e) {
  2907. const stream = controller._controlledReadableStream;
  2908. if (stream._state !== 'readable') {
  2909. return;
  2910. }
  2911. ResetQueue(controller);
  2912. ReadableStreamDefaultControllerClearAlgorithms(controller);
  2913. ReadableStreamError(stream, e);
  2914. }
  2915. function ReadableStreamDefaultControllerGetDesiredSize(controller) {
  2916. const state = controller._controlledReadableStream._state;
  2917. if (state === 'errored') {
  2918. return null;
  2919. }
  2920. if (state === 'closed') {
  2921. return 0;
  2922. }
  2923. return controller._strategyHWM - controller._queueTotalSize;
  2924. }
  2925. // This is used in the implementation of TransformStream.
  2926. function ReadableStreamDefaultControllerHasBackpressure(controller) {
  2927. if (ReadableStreamDefaultControllerShouldCallPull(controller)) {
  2928. return false;
  2929. }
  2930. return true;
  2931. }
  2932. function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) {
  2933. const state = controller._controlledReadableStream._state;
  2934. if (!controller._closeRequested && state === 'readable') {
  2935. return true;
  2936. }
  2937. return false;
  2938. }
  2939. function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) {
  2940. controller._controlledReadableStream = stream;
  2941. controller._queue = undefined;
  2942. controller._queueTotalSize = undefined;
  2943. ResetQueue(controller);
  2944. controller._started = false;
  2945. controller._closeRequested = false;
  2946. controller._pullAgain = false;
  2947. controller._pulling = false;
  2948. controller._strategySizeAlgorithm = sizeAlgorithm;
  2949. controller._strategyHWM = highWaterMark;
  2950. controller._pullAlgorithm = pullAlgorithm;
  2951. controller._cancelAlgorithm = cancelAlgorithm;
  2952. stream._readableStreamController = controller;
  2953. const startResult = startAlgorithm();
  2954. uponPromise(promiseResolvedWith(startResult), () => {
  2955. controller._started = true;
  2956. ReadableStreamDefaultControllerCallPullIfNeeded(controller);
  2957. }, r => {
  2958. ReadableStreamDefaultControllerError(controller, r);
  2959. });
  2960. }
  2961. function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) {
  2962. const controller = Object.create(ReadableStreamDefaultController.prototype);
  2963. let startAlgorithm = () => undefined;
  2964. let pullAlgorithm = () => promiseResolvedWith(undefined);
  2965. let cancelAlgorithm = () => promiseResolvedWith(undefined);
  2966. if (underlyingSource.start !== undefined) {
  2967. startAlgorithm = () => underlyingSource.start(controller);
  2968. }
  2969. if (underlyingSource.pull !== undefined) {
  2970. pullAlgorithm = () => underlyingSource.pull(controller);
  2971. }
  2972. if (underlyingSource.cancel !== undefined) {
  2973. cancelAlgorithm = reason => underlyingSource.cancel(reason);
  2974. }
  2975. SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
  2976. }
  2977. // Helper functions for the ReadableStreamDefaultController.
  2978. function defaultControllerBrandCheckException$1(name) {
  2979. return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);
  2980. }
  2981. function ReadableStreamTee(stream, cloneForBranch2) {
  2982. if (IsReadableByteStreamController(stream._readableStreamController)) {
  2983. return ReadableByteStreamTee(stream);
  2984. }
  2985. return ReadableStreamDefaultTee(stream);
  2986. }
  2987. function ReadableStreamDefaultTee(stream, cloneForBranch2) {
  2988. const reader = AcquireReadableStreamDefaultReader(stream);
  2989. let reading = false;
  2990. let readAgain = false;
  2991. let canceled1 = false;
  2992. let canceled2 = false;
  2993. let reason1;
  2994. let reason2;
  2995. let branch1;
  2996. let branch2;
  2997. let resolveCancelPromise;
  2998. const cancelPromise = newPromise(resolve => {
  2999. resolveCancelPromise = resolve;
  3000. });
  3001. function pullAlgorithm() {
  3002. if (reading) {
  3003. readAgain = true;
  3004. return promiseResolvedWith(undefined);
  3005. }
  3006. reading = true;
  3007. const readRequest = {
  3008. _chunkSteps: chunk => {
  3009. // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using
  3010. // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let
  3011. // successful synchronously-available reads get ahead of asynchronously-available errors.
  3012. queueMicrotask(() => {
  3013. readAgain = false;
  3014. const chunk1 = chunk;
  3015. const chunk2 = chunk;
  3016. // There is no way to access the cloning code right now in the reference implementation.
  3017. // If we add one then we'll need an implementation for serializable objects.
  3018. // if (!canceled2 && cloneForBranch2) {
  3019. // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));
  3020. // }
  3021. if (!canceled1) {
  3022. ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);
  3023. }
  3024. if (!canceled2) {
  3025. ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);
  3026. }
  3027. reading = false;
  3028. if (readAgain) {
  3029. pullAlgorithm();
  3030. }
  3031. });
  3032. },
  3033. _closeSteps: () => {
  3034. reading = false;
  3035. if (!canceled1) {
  3036. ReadableStreamDefaultControllerClose(branch1._readableStreamController);
  3037. }
  3038. if (!canceled2) {
  3039. ReadableStreamDefaultControllerClose(branch2._readableStreamController);
  3040. }
  3041. if (!canceled1 || !canceled2) {
  3042. resolveCancelPromise(undefined);
  3043. }
  3044. },
  3045. _errorSteps: () => {
  3046. reading = false;
  3047. }
  3048. };
  3049. ReadableStreamDefaultReaderRead(reader, readRequest);
  3050. return promiseResolvedWith(undefined);
  3051. }
  3052. function cancel1Algorithm(reason) {
  3053. canceled1 = true;
  3054. reason1 = reason;
  3055. if (canceled2) {
  3056. const compositeReason = CreateArrayFromList([reason1, reason2]);
  3057. const cancelResult = ReadableStreamCancel(stream, compositeReason);
  3058. resolveCancelPromise(cancelResult);
  3059. }
  3060. return cancelPromise;
  3061. }
  3062. function cancel2Algorithm(reason) {
  3063. canceled2 = true;
  3064. reason2 = reason;
  3065. if (canceled1) {
  3066. const compositeReason = CreateArrayFromList([reason1, reason2]);
  3067. const cancelResult = ReadableStreamCancel(stream, compositeReason);
  3068. resolveCancelPromise(cancelResult);
  3069. }
  3070. return cancelPromise;
  3071. }
  3072. function startAlgorithm() {
  3073. // do nothing
  3074. }
  3075. branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);
  3076. branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);
  3077. uponRejection(reader._closedPromise, (r) => {
  3078. ReadableStreamDefaultControllerError(branch1._readableStreamController, r);
  3079. ReadableStreamDefaultControllerError(branch2._readableStreamController, r);
  3080. if (!canceled1 || !canceled2) {
  3081. resolveCancelPromise(undefined);
  3082. }
  3083. });
  3084. return [branch1, branch2];
  3085. }
  3086. function ReadableByteStreamTee(stream) {
  3087. let reader = AcquireReadableStreamDefaultReader(stream);
  3088. let reading = false;
  3089. let readAgainForBranch1 = false;
  3090. let readAgainForBranch2 = false;
  3091. let canceled1 = false;
  3092. let canceled2 = false;
  3093. let reason1;
  3094. let reason2;
  3095. let branch1;
  3096. let branch2;
  3097. let resolveCancelPromise;
  3098. const cancelPromise = newPromise(resolve => {
  3099. resolveCancelPromise = resolve;
  3100. });
  3101. function forwardReaderError(thisReader) {
  3102. uponRejection(thisReader._closedPromise, r => {
  3103. if (thisReader !== reader) {
  3104. return;
  3105. }
  3106. ReadableByteStreamControllerError(branch1._readableStreamController, r);
  3107. ReadableByteStreamControllerError(branch2._readableStreamController, r);
  3108. if (!canceled1 || !canceled2) {
  3109. resolveCancelPromise(undefined);
  3110. }
  3111. });
  3112. }
  3113. function pullWithDefaultReader() {
  3114. if (IsReadableStreamBYOBReader(reader)) {
  3115. ReadableStreamReaderGenericRelease(reader);
  3116. reader = AcquireReadableStreamDefaultReader(stream);
  3117. forwardReaderError(reader);
  3118. }
  3119. const readRequest = {
  3120. _chunkSteps: chunk => {
  3121. // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using
  3122. // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let
  3123. // successful synchronously-available reads get ahead of asynchronously-available errors.
  3124. queueMicrotask(() => {
  3125. readAgainForBranch1 = false;
  3126. readAgainForBranch2 = false;
  3127. const chunk1 = chunk;
  3128. let chunk2 = chunk;
  3129. if (!canceled1 && !canceled2) {
  3130. try {
  3131. chunk2 = CloneAsUint8Array(chunk);
  3132. }
  3133. catch (cloneE) {
  3134. ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);
  3135. ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);
  3136. resolveCancelPromise(ReadableStreamCancel(stream, cloneE));
  3137. return;
  3138. }
  3139. }
  3140. if (!canceled1) {
  3141. ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);
  3142. }
  3143. if (!canceled2) {
  3144. ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);
  3145. }
  3146. reading = false;
  3147. if (readAgainForBranch1) {
  3148. pull1Algorithm();
  3149. }
  3150. else if (readAgainForBranch2) {
  3151. pull2Algorithm();
  3152. }
  3153. });
  3154. },
  3155. _closeSteps: () => {
  3156. reading = false;
  3157. if (!canceled1) {
  3158. ReadableByteStreamControllerClose(branch1._readableStreamController);
  3159. }
  3160. if (!canceled2) {
  3161. ReadableByteStreamControllerClose(branch2._readableStreamController);
  3162. }
  3163. if (branch1._readableStreamController._pendingPullIntos.length > 0) {
  3164. ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);
  3165. }
  3166. if (branch2._readableStreamController._pendingPullIntos.length > 0) {
  3167. ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);
  3168. }
  3169. if (!canceled1 || !canceled2) {
  3170. resolveCancelPromise(undefined);
  3171. }
  3172. },
  3173. _errorSteps: () => {
  3174. reading = false;
  3175. }
  3176. };
  3177. ReadableStreamDefaultReaderRead(reader, readRequest);
  3178. }
  3179. function pullWithBYOBReader(view, forBranch2) {
  3180. if (IsReadableStreamDefaultReader(reader)) {
  3181. ReadableStreamReaderGenericRelease(reader);
  3182. reader = AcquireReadableStreamBYOBReader(stream);
  3183. forwardReaderError(reader);
  3184. }
  3185. const byobBranch = forBranch2 ? branch2 : branch1;
  3186. const otherBranch = forBranch2 ? branch1 : branch2;
  3187. const readIntoRequest = {
  3188. _chunkSteps: chunk => {
  3189. // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using
  3190. // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let
  3191. // successful synchronously-available reads get ahead of asynchronously-available errors.
  3192. queueMicrotask(() => {
  3193. readAgainForBranch1 = false;
  3194. readAgainForBranch2 = false;
  3195. const byobCanceled = forBranch2 ? canceled2 : canceled1;
  3196. const otherCanceled = forBranch2 ? canceled1 : canceled2;
  3197. if (!otherCanceled) {
  3198. let clonedChunk;
  3199. try {
  3200. clonedChunk = CloneAsUint8Array(chunk);
  3201. }
  3202. catch (cloneE) {
  3203. ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);
  3204. ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);
  3205. resolveCancelPromise(ReadableStreamCancel(stream, cloneE));
  3206. return;
  3207. }
  3208. if (!byobCanceled) {
  3209. ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);
  3210. }
  3211. ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);
  3212. }
  3213. else if (!byobCanceled) {
  3214. ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);
  3215. }
  3216. reading = false;
  3217. if (readAgainForBranch1) {
  3218. pull1Algorithm();
  3219. }
  3220. else if (readAgainForBranch2) {
  3221. pull2Algorithm();
  3222. }
  3223. });
  3224. },
  3225. _closeSteps: chunk => {
  3226. reading = false;
  3227. const byobCanceled = forBranch2 ? canceled2 : canceled1;
  3228. const otherCanceled = forBranch2 ? canceled1 : canceled2;
  3229. if (!byobCanceled) {
  3230. ReadableByteStreamControllerClose(byobBranch._readableStreamController);
  3231. }
  3232. if (!otherCanceled) {
  3233. ReadableByteStreamControllerClose(otherBranch._readableStreamController);
  3234. }
  3235. if (chunk !== undefined) {
  3236. if (!byobCanceled) {
  3237. ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);
  3238. }
  3239. if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {
  3240. ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);
  3241. }
  3242. }
  3243. if (!byobCanceled || !otherCanceled) {
  3244. resolveCancelPromise(undefined);
  3245. }
  3246. },
  3247. _errorSteps: () => {
  3248. reading = false;
  3249. }
  3250. };
  3251. ReadableStreamBYOBReaderRead(reader, view, readIntoRequest);
  3252. }
  3253. function pull1Algorithm() {
  3254. if (reading) {
  3255. readAgainForBranch1 = true;
  3256. return promiseResolvedWith(undefined);
  3257. }
  3258. reading = true;
  3259. const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);
  3260. if (byobRequest === null) {
  3261. pullWithDefaultReader();
  3262. }
  3263. else {
  3264. pullWithBYOBReader(byobRequest._view, false);
  3265. }
  3266. return promiseResolvedWith(undefined);
  3267. }
  3268. function pull2Algorithm() {
  3269. if (reading) {
  3270. readAgainForBranch2 = true;
  3271. return promiseResolvedWith(undefined);
  3272. }
  3273. reading = true;
  3274. const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);
  3275. if (byobRequest === null) {
  3276. pullWithDefaultReader();
  3277. }
  3278. else {
  3279. pullWithBYOBReader(byobRequest._view, true);
  3280. }
  3281. return promiseResolvedWith(undefined);
  3282. }
  3283. function cancel1Algorithm(reason) {
  3284. canceled1 = true;
  3285. reason1 = reason;
  3286. if (canceled2) {
  3287. const compositeReason = CreateArrayFromList([reason1, reason2]);
  3288. const cancelResult = ReadableStreamCancel(stream, compositeReason);
  3289. resolveCancelPromise(cancelResult);
  3290. }
  3291. return cancelPromise;
  3292. }
  3293. function cancel2Algorithm(reason) {
  3294. canceled2 = true;
  3295. reason2 = reason;
  3296. if (canceled1) {
  3297. const compositeReason = CreateArrayFromList([reason1, reason2]);
  3298. const cancelResult = ReadableStreamCancel(stream, compositeReason);
  3299. resolveCancelPromise(cancelResult);
  3300. }
  3301. return cancelPromise;
  3302. }
  3303. function startAlgorithm() {
  3304. return;
  3305. }
  3306. branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);
  3307. branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);
  3308. forwardReaderError(reader);
  3309. return [branch1, branch2];
  3310. }
  3311. function convertUnderlyingDefaultOrByteSource(source, context) {
  3312. assertDictionary(source, context);
  3313. const original = source;
  3314. const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize;
  3315. const cancel = original === null || original === void 0 ? void 0 : original.cancel;
  3316. const pull = original === null || original === void 0 ? void 0 : original.pull;
  3317. const start = original === null || original === void 0 ? void 0 : original.start;
  3318. const type = original === null || original === void 0 ? void 0 : original.type;
  3319. return {
  3320. autoAllocateChunkSize: autoAllocateChunkSize === undefined ?
  3321. undefined :
  3322. convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`),
  3323. cancel: cancel === undefined ?
  3324. undefined :
  3325. convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`),
  3326. pull: pull === undefined ?
  3327. undefined :
  3328. convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`),
  3329. start: start === undefined ?
  3330. undefined :
  3331. convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`),
  3332. type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)
  3333. };
  3334. }
  3335. function convertUnderlyingSourceCancelCallback(fn, original, context) {
  3336. assertFunction(fn, context);
  3337. return (reason) => promiseCall(fn, original, [reason]);
  3338. }
  3339. function convertUnderlyingSourcePullCallback(fn, original, context) {
  3340. assertFunction(fn, context);
  3341. return (controller) => promiseCall(fn, original, [controller]);
  3342. }
  3343. function convertUnderlyingSourceStartCallback(fn, original, context) {
  3344. assertFunction(fn, context);
  3345. return (controller) => reflectCall(fn, original, [controller]);
  3346. }
  3347. function convertReadableStreamType(type, context) {
  3348. type = `${type}`;
  3349. if (type !== 'bytes') {
  3350. throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);
  3351. }
  3352. return type;
  3353. }
  3354. function convertReaderOptions(options, context) {
  3355. assertDictionary(options, context);
  3356. const mode = options === null || options === void 0 ? void 0 : options.mode;
  3357. return {
  3358. mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)
  3359. };
  3360. }
  3361. function convertReadableStreamReaderMode(mode, context) {
  3362. mode = `${mode}`;
  3363. if (mode !== 'byob') {
  3364. throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);
  3365. }
  3366. return mode;
  3367. }
  3368. function convertIteratorOptions(options, context) {
  3369. assertDictionary(options, context);
  3370. const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;
  3371. return { preventCancel: Boolean(preventCancel) };
  3372. }
  3373. function convertPipeOptions(options, context) {
  3374. assertDictionary(options, context);
  3375. const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort;
  3376. const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;
  3377. const preventClose = options === null || options === void 0 ? void 0 : options.preventClose;
  3378. const signal = options === null || options === void 0 ? void 0 : options.signal;
  3379. if (signal !== undefined) {
  3380. assertAbortSignal(signal, `${context} has member 'signal' that`);
  3381. }
  3382. return {
  3383. preventAbort: Boolean(preventAbort),
  3384. preventCancel: Boolean(preventCancel),
  3385. preventClose: Boolean(preventClose),
  3386. signal
  3387. };
  3388. }
  3389. function assertAbortSignal(signal, context) {
  3390. if (!isAbortSignal(signal)) {
  3391. throw new TypeError(`${context} is not an AbortSignal.`);
  3392. }
  3393. }
  3394. function convertReadableWritablePair(pair, context) {
  3395. assertDictionary(pair, context);
  3396. const readable = pair === null || pair === void 0 ? void 0 : pair.readable;
  3397. assertRequiredField(readable, 'readable', 'ReadableWritablePair');
  3398. assertReadableStream(readable, `${context} has member 'readable' that`);
  3399. const writable = pair === null || pair === void 0 ? void 0 : pair.writable;
  3400. assertRequiredField(writable, 'writable', 'ReadableWritablePair');
  3401. assertWritableStream(writable, `${context} has member 'writable' that`);
  3402. return { readable, writable };
  3403. }
  3404. /**
  3405. * A readable stream represents a source of data, from which you can read.
  3406. *
  3407. * @public
  3408. */
  3409. class ReadableStream {
  3410. constructor(rawUnderlyingSource = {}, rawStrategy = {}) {
  3411. if (rawUnderlyingSource === undefined) {
  3412. rawUnderlyingSource = null;
  3413. }
  3414. else {
  3415. assertObject(rawUnderlyingSource, 'First parameter');
  3416. }
  3417. const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');
  3418. const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');
  3419. InitializeReadableStream(this);
  3420. if (underlyingSource.type === 'bytes') {
  3421. if (strategy.size !== undefined) {
  3422. throw new RangeError('The strategy for a byte stream cannot have a size function');
  3423. }
  3424. const highWaterMark = ExtractHighWaterMark(strategy, 0);
  3425. SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark);
  3426. }
  3427. else {
  3428. const sizeAlgorithm = ExtractSizeAlgorithm(strategy);
  3429. const highWaterMark = ExtractHighWaterMark(strategy, 1);
  3430. SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm);
  3431. }
  3432. }
  3433. /**
  3434. * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.
  3435. */
  3436. get locked() {
  3437. if (!IsReadableStream(this)) {
  3438. throw streamBrandCheckException$1('locked');
  3439. }
  3440. return IsReadableStreamLocked(this);
  3441. }
  3442. /**
  3443. * Cancels the stream, signaling a loss of interest in the stream by a consumer.
  3444. *
  3445. * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}
  3446. * method, which might or might not use it.
  3447. */
  3448. cancel(reason = undefined) {
  3449. if (!IsReadableStream(this)) {
  3450. return promiseRejectedWith(streamBrandCheckException$1('cancel'));
  3451. }
  3452. if (IsReadableStreamLocked(this)) {
  3453. return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));
  3454. }
  3455. return ReadableStreamCancel(this, reason);
  3456. }
  3457. getReader(rawOptions = undefined) {
  3458. if (!IsReadableStream(this)) {
  3459. throw streamBrandCheckException$1('getReader');
  3460. }
  3461. const options = convertReaderOptions(rawOptions, 'First parameter');
  3462. if (options.mode === undefined) {
  3463. return AcquireReadableStreamDefaultReader(this);
  3464. }
  3465. return AcquireReadableStreamBYOBReader(this);
  3466. }
  3467. pipeThrough(rawTransform, rawOptions = {}) {
  3468. if (!IsReadableStream(this)) {
  3469. throw streamBrandCheckException$1('pipeThrough');
  3470. }
  3471. assertRequiredArgument(rawTransform, 1, 'pipeThrough');
  3472. const transform = convertReadableWritablePair(rawTransform, 'First parameter');
  3473. const options = convertPipeOptions(rawOptions, 'Second parameter');
  3474. if (IsReadableStreamLocked(this)) {
  3475. throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');
  3476. }
  3477. if (IsWritableStreamLocked(transform.writable)) {
  3478. throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');
  3479. }
  3480. const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal);
  3481. setPromiseIsHandledToTrue(promise);
  3482. return transform.readable;
  3483. }
  3484. pipeTo(destination, rawOptions = {}) {
  3485. if (!IsReadableStream(this)) {
  3486. return promiseRejectedWith(streamBrandCheckException$1('pipeTo'));
  3487. }
  3488. if (destination === undefined) {
  3489. return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);
  3490. }
  3491. if (!IsWritableStream(destination)) {
  3492. return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`));
  3493. }
  3494. let options;
  3495. try {
  3496. options = convertPipeOptions(rawOptions, 'Second parameter');
  3497. }
  3498. catch (e) {
  3499. return promiseRejectedWith(e);
  3500. }
  3501. if (IsReadableStreamLocked(this)) {
  3502. return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream'));
  3503. }
  3504. if (IsWritableStreamLocked(destination)) {
  3505. return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream'));
  3506. }
  3507. return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal);
  3508. }
  3509. /**
  3510. * Tees this readable stream, returning a two-element array containing the two resulting branches as
  3511. * new {@link ReadableStream} instances.
  3512. *
  3513. * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.
  3514. * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be
  3515. * propagated to the stream's underlying source.
  3516. *
  3517. * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,
  3518. * this could allow interference between the two branches.
  3519. */
  3520. tee() {
  3521. if (!IsReadableStream(this)) {
  3522. throw streamBrandCheckException$1('tee');
  3523. }
  3524. const branches = ReadableStreamTee(this);
  3525. return CreateArrayFromList(branches);
  3526. }
  3527. values(rawOptions = undefined) {
  3528. if (!IsReadableStream(this)) {
  3529. throw streamBrandCheckException$1('values');
  3530. }
  3531. const options = convertIteratorOptions(rawOptions, 'First parameter');
  3532. return AcquireReadableStreamAsyncIterator(this, options.preventCancel);
  3533. }
  3534. }
  3535. Object.defineProperties(ReadableStream.prototype, {
  3536. cancel: { enumerable: true },
  3537. getReader: { enumerable: true },
  3538. pipeThrough: { enumerable: true },
  3539. pipeTo: { enumerable: true },
  3540. tee: { enumerable: true },
  3541. values: { enumerable: true },
  3542. locked: { enumerable: true }
  3543. });
  3544. if (typeof SymbolPolyfill.toStringTag === 'symbol') {
  3545. Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, {
  3546. value: 'ReadableStream',
  3547. configurable: true
  3548. });
  3549. }
  3550. if (typeof SymbolPolyfill.asyncIterator === 'symbol') {
  3551. Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, {
  3552. value: ReadableStream.prototype.values,
  3553. writable: true,
  3554. configurable: true
  3555. });
  3556. }
  3557. // Abstract operations for the ReadableStream.
  3558. // Throws if and only if startAlgorithm throws.
  3559. function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
  3560. const stream = Object.create(ReadableStream.prototype);
  3561. InitializeReadableStream(stream);
  3562. const controller = Object.create(ReadableStreamDefaultController.prototype);
  3563. SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
  3564. return stream;
  3565. }
  3566. // Throws if and only if startAlgorithm throws.
  3567. function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) {
  3568. const stream = Object.create(ReadableStream.prototype);
  3569. InitializeReadableStream(stream);
  3570. const controller = Object.create(ReadableByteStreamController.prototype);
  3571. SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);
  3572. return stream;
  3573. }
  3574. function InitializeReadableStream(stream) {
  3575. stream._state = 'readable';
  3576. stream._reader = undefined;
  3577. stream._storedError = undefined;
  3578. stream._disturbed = false;
  3579. }
  3580. function IsReadableStream(x) {
  3581. if (!typeIsObject(x)) {
  3582. return false;
  3583. }
  3584. if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {
  3585. return false;
  3586. }
  3587. return x instanceof ReadableStream;
  3588. }
  3589. function IsReadableStreamLocked(stream) {
  3590. if (stream._reader === undefined) {
  3591. return false;
  3592. }
  3593. return true;
  3594. }
  3595. // ReadableStream API exposed for controllers.
  3596. function ReadableStreamCancel(stream, reason) {
  3597. stream._disturbed = true;
  3598. if (stream._state === 'closed') {
  3599. return promiseResolvedWith(undefined);
  3600. }
  3601. if (stream._state === 'errored') {
  3602. return promiseRejectedWith(stream._storedError);
  3603. }
  3604. ReadableStreamClose(stream);
  3605. const reader = stream._reader;
  3606. if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {
  3607. reader._readIntoRequests.forEach(readIntoRequest => {
  3608. readIntoRequest._closeSteps(undefined);
  3609. });
  3610. reader._readIntoRequests = new SimpleQueue();
  3611. }
  3612. const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);
  3613. return transformPromiseWith(sourceCancelPromise, noop);
  3614. }
  3615. function ReadableStreamClose(stream) {
  3616. stream._state = 'closed';
  3617. const reader = stream._reader;
  3618. if (reader === undefined) {
  3619. return;
  3620. }
  3621. defaultReaderClosedPromiseResolve(reader);
  3622. if (IsReadableStreamDefaultReader(reader)) {
  3623. reader._readRequests.forEach(readRequest => {
  3624. readRequest._closeSteps();
  3625. });
  3626. reader._readRequests = new SimpleQueue();
  3627. }
  3628. }
  3629. function ReadableStreamError(stream, e) {
  3630. stream._state = 'errored';
  3631. stream._storedError = e;
  3632. const reader = stream._reader;
  3633. if (reader === undefined) {
  3634. return;
  3635. }
  3636. defaultReaderClosedPromiseReject(reader, e);
  3637. if (IsReadableStreamDefaultReader(reader)) {
  3638. reader._readRequests.forEach(readRequest => {
  3639. readRequest._errorSteps(e);
  3640. });
  3641. reader._readRequests = new SimpleQueue();
  3642. }
  3643. else {
  3644. reader._readIntoRequests.forEach(readIntoRequest => {
  3645. readIntoRequest._errorSteps(e);
  3646. });
  3647. reader._readIntoRequests = new SimpleQueue();
  3648. }
  3649. }
  3650. // Helper functions for the ReadableStream.
  3651. function streamBrandCheckException$1(name) {
  3652. return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);
  3653. }
  3654. function convertQueuingStrategyInit(init, context) {
  3655. assertDictionary(init, context);
  3656. const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark;
  3657. assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');
  3658. return {
  3659. highWaterMark: convertUnrestrictedDouble(highWaterMark)
  3660. };
  3661. }
  3662. // The size function must not have a prototype property nor be a constructor
  3663. const byteLengthSizeFunction = (chunk) => {
  3664. return chunk.byteLength;
  3665. };
  3666. try {
  3667. Object.defineProperty(byteLengthSizeFunction, 'name', {
  3668. value: 'size',
  3669. configurable: true
  3670. });
  3671. }
  3672. catch (_a) {
  3673. // This property is non-configurable in older browsers, so ignore if this throws.
  3674. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility
  3675. }
  3676. /**
  3677. * A queuing strategy that counts the number of bytes in each chunk.
  3678. *
  3679. * @public
  3680. */
  3681. class ByteLengthQueuingStrategy {
  3682. constructor(options) {
  3683. assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');
  3684. options = convertQueuingStrategyInit(options, 'First parameter');
  3685. this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;
  3686. }
  3687. /**
  3688. * Returns the high water mark provided to the constructor.
  3689. */
  3690. get highWaterMark() {
  3691. if (!IsByteLengthQueuingStrategy(this)) {
  3692. throw byteLengthBrandCheckException('highWaterMark');
  3693. }
  3694. return this._byteLengthQueuingStrategyHighWaterMark;
  3695. }
  3696. /**
  3697. * Measures the size of `chunk` by returning the value of its `byteLength` property.
  3698. */
  3699. get size() {
  3700. if (!IsByteLengthQueuingStrategy(this)) {
  3701. throw byteLengthBrandCheckException('size');
  3702. }
  3703. return byteLengthSizeFunction;
  3704. }
  3705. }
  3706. Object.defineProperties(ByteLengthQueuingStrategy.prototype, {
  3707. highWaterMark: { enumerable: true },
  3708. size: { enumerable: true }
  3709. });
  3710. if (typeof SymbolPolyfill.toStringTag === 'symbol') {
  3711. Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, {
  3712. value: 'ByteLengthQueuingStrategy',
  3713. configurable: true
  3714. });
  3715. }
  3716. // Helper functions for the ByteLengthQueuingStrategy.
  3717. function byteLengthBrandCheckException(name) {
  3718. return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);
  3719. }
  3720. function IsByteLengthQueuingStrategy(x) {
  3721. if (!typeIsObject(x)) {
  3722. return false;
  3723. }
  3724. if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {
  3725. return false;
  3726. }
  3727. return x instanceof ByteLengthQueuingStrategy;
  3728. }
  3729. // The size function must not have a prototype property nor be a constructor
  3730. const countSizeFunction = () => {
  3731. return 1;
  3732. };
  3733. try {
  3734. Object.defineProperty(countSizeFunction, 'name', {
  3735. value: 'size',
  3736. configurable: true
  3737. });
  3738. }
  3739. catch (_a) {
  3740. // This property is non-configurable in older browsers, so ignore if this throws.
  3741. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility
  3742. }
  3743. /**
  3744. * A queuing strategy that counts the number of chunks.
  3745. *
  3746. * @public
  3747. */
  3748. class CountQueuingStrategy {
  3749. constructor(options) {
  3750. assertRequiredArgument(options, 1, 'CountQueuingStrategy');
  3751. options = convertQueuingStrategyInit(options, 'First parameter');
  3752. this._countQueuingStrategyHighWaterMark = options.highWaterMark;
  3753. }
  3754. /**
  3755. * Returns the high water mark provided to the constructor.
  3756. */
  3757. get highWaterMark() {
  3758. if (!IsCountQueuingStrategy(this)) {
  3759. throw countBrandCheckException('highWaterMark');
  3760. }
  3761. return this._countQueuingStrategyHighWaterMark;
  3762. }
  3763. /**
  3764. * Measures the size of `chunk` by always returning 1.
  3765. * This ensures that the total queue size is a count of the number of chunks in the queue.
  3766. */
  3767. get size() {
  3768. if (!IsCountQueuingStrategy(this)) {
  3769. throw countBrandCheckException('size');
  3770. }
  3771. return countSizeFunction;
  3772. }
  3773. }
  3774. Object.defineProperties(CountQueuingStrategy.prototype, {
  3775. highWaterMark: { enumerable: true },
  3776. size: { enumerable: true }
  3777. });
  3778. if (typeof SymbolPolyfill.toStringTag === 'symbol') {
  3779. Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, {
  3780. value: 'CountQueuingStrategy',
  3781. configurable: true
  3782. });
  3783. }
  3784. // Helper functions for the CountQueuingStrategy.
  3785. function countBrandCheckException(name) {
  3786. return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);
  3787. }
  3788. function IsCountQueuingStrategy(x) {
  3789. if (!typeIsObject(x)) {
  3790. return false;
  3791. }
  3792. if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {
  3793. return false;
  3794. }
  3795. return x instanceof CountQueuingStrategy;
  3796. }
  3797. function convertTransformer(original, context) {
  3798. assertDictionary(original, context);
  3799. const flush = original === null || original === void 0 ? void 0 : original.flush;
  3800. const readableType = original === null || original === void 0 ? void 0 : original.readableType;
  3801. const start = original === null || original === void 0 ? void 0 : original.start;
  3802. const transform = original === null || original === void 0 ? void 0 : original.transform;
  3803. const writableType = original === null || original === void 0 ? void 0 : original.writableType;
  3804. return {
  3805. flush: flush === undefined ?
  3806. undefined :
  3807. convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`),
  3808. readableType,
  3809. start: start === undefined ?
  3810. undefined :
  3811. convertTransformerStartCallback(start, original, `${context} has member 'start' that`),
  3812. transform: transform === undefined ?
  3813. undefined :
  3814. convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`),
  3815. writableType
  3816. };
  3817. }
  3818. function convertTransformerFlushCallback(fn, original, context) {
  3819. assertFunction(fn, context);
  3820. return (controller) => promiseCall(fn, original, [controller]);
  3821. }
  3822. function convertTransformerStartCallback(fn, original, context) {
  3823. assertFunction(fn, context);
  3824. return (controller) => reflectCall(fn, original, [controller]);
  3825. }
  3826. function convertTransformerTransformCallback(fn, original, context) {
  3827. assertFunction(fn, context);
  3828. return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);
  3829. }
  3830. // Class TransformStream
  3831. /**
  3832. * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},
  3833. * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.
  3834. * In a manner specific to the transform stream in question, writes to the writable side result in new data being
  3835. * made available for reading from the readable side.
  3836. *
  3837. * @public
  3838. */
  3839. class TransformStream {
  3840. constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) {
  3841. if (rawTransformer === undefined) {
  3842. rawTransformer = null;
  3843. }
  3844. const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');
  3845. const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');
  3846. const transformer = convertTransformer(rawTransformer, 'First parameter');
  3847. if (transformer.readableType !== undefined) {
  3848. throw new RangeError('Invalid readableType specified');
  3849. }
  3850. if (transformer.writableType !== undefined) {
  3851. throw new RangeError('Invalid writableType specified');
  3852. }
  3853. const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);
  3854. const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);
  3855. const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);
  3856. const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);
  3857. let startPromise_resolve;
  3858. const startPromise = newPromise(resolve => {
  3859. startPromise_resolve = resolve;
  3860. });
  3861. InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
  3862. SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);
  3863. if (transformer.start !== undefined) {
  3864. startPromise_resolve(transformer.start(this._transformStreamController));
  3865. }
  3866. else {
  3867. startPromise_resolve(undefined);
  3868. }
  3869. }
  3870. /**
  3871. * The readable side of the transform stream.
  3872. */
  3873. get readable() {
  3874. if (!IsTransformStream(this)) {
  3875. throw streamBrandCheckException('readable');
  3876. }
  3877. return this._readable;
  3878. }
  3879. /**
  3880. * The writable side of the transform stream.
  3881. */
  3882. get writable() {
  3883. if (!IsTransformStream(this)) {
  3884. throw streamBrandCheckException('writable');
  3885. }
  3886. return this._writable;
  3887. }
  3888. }
  3889. Object.defineProperties(TransformStream.prototype, {
  3890. readable: { enumerable: true },
  3891. writable: { enumerable: true }
  3892. });
  3893. if (typeof SymbolPolyfill.toStringTag === 'symbol') {
  3894. Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, {
  3895. value: 'TransformStream',
  3896. configurable: true
  3897. });
  3898. }
  3899. function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) {
  3900. function startAlgorithm() {
  3901. return startPromise;
  3902. }
  3903. function writeAlgorithm(chunk) {
  3904. return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);
  3905. }
  3906. function abortAlgorithm(reason) {
  3907. return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);
  3908. }
  3909. function closeAlgorithm() {
  3910. return TransformStreamDefaultSinkCloseAlgorithm(stream);
  3911. }
  3912. stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm);
  3913. function pullAlgorithm() {
  3914. return TransformStreamDefaultSourcePullAlgorithm(stream);
  3915. }
  3916. function cancelAlgorithm(reason) {
  3917. TransformStreamErrorWritableAndUnblockWrite(stream, reason);
  3918. return promiseResolvedWith(undefined);
  3919. }
  3920. stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
  3921. // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.
  3922. stream._backpressure = undefined;
  3923. stream._backpressureChangePromise = undefined;
  3924. stream._backpressureChangePromise_resolve = undefined;
  3925. TransformStreamSetBackpressure(stream, true);
  3926. stream._transformStreamController = undefined;
  3927. }
  3928. function IsTransformStream(x) {
  3929. if (!typeIsObject(x)) {
  3930. return false;
  3931. }
  3932. if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {
  3933. return false;
  3934. }
  3935. return x instanceof TransformStream;
  3936. }
  3937. // This is a no-op if both sides are already errored.
  3938. function TransformStreamError(stream, e) {
  3939. ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);
  3940. TransformStreamErrorWritableAndUnblockWrite(stream, e);
  3941. }
  3942. function TransformStreamErrorWritableAndUnblockWrite(stream, e) {
  3943. TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);
  3944. WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);
  3945. if (stream._backpressure) {
  3946. // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()
  3947. // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time
  3948. // _backpressure is set.
  3949. TransformStreamSetBackpressure(stream, false);
  3950. }
  3951. }
  3952. function TransformStreamSetBackpressure(stream, backpressure) {
  3953. // Passes also when called during construction.
  3954. if (stream._backpressureChangePromise !== undefined) {
  3955. stream._backpressureChangePromise_resolve();
  3956. }
  3957. stream._backpressureChangePromise = newPromise(resolve => {
  3958. stream._backpressureChangePromise_resolve = resolve;
  3959. });
  3960. stream._backpressure = backpressure;
  3961. }
  3962. // Class TransformStreamDefaultController
  3963. /**
  3964. * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.
  3965. *
  3966. * @public
  3967. */
  3968. class TransformStreamDefaultController {
  3969. constructor() {
  3970. throw new TypeError('Illegal constructor');
  3971. }
  3972. /**
  3973. * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.
  3974. */
  3975. get desiredSize() {
  3976. if (!IsTransformStreamDefaultController(this)) {
  3977. throw defaultControllerBrandCheckException('desiredSize');
  3978. }
  3979. const readableController = this._controlledTransformStream._readable._readableStreamController;
  3980. return ReadableStreamDefaultControllerGetDesiredSize(readableController);
  3981. }
  3982. enqueue(chunk = undefined) {
  3983. if (!IsTransformStreamDefaultController(this)) {
  3984. throw defaultControllerBrandCheckException('enqueue');
  3985. }
  3986. TransformStreamDefaultControllerEnqueue(this, chunk);
  3987. }
  3988. /**
  3989. * Errors both the readable side and the writable side of the controlled transform stream, making all future
  3990. * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.
  3991. */
  3992. error(reason = undefined) {
  3993. if (!IsTransformStreamDefaultController(this)) {
  3994. throw defaultControllerBrandCheckException('error');
  3995. }
  3996. TransformStreamDefaultControllerError(this, reason);
  3997. }
  3998. /**
  3999. * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the
  4000. * transformer only needs to consume a portion of the chunks written to the writable side.
  4001. */
  4002. terminate() {
  4003. if (!IsTransformStreamDefaultController(this)) {
  4004. throw defaultControllerBrandCheckException('terminate');
  4005. }
  4006. TransformStreamDefaultControllerTerminate(this);
  4007. }
  4008. }
  4009. Object.defineProperties(TransformStreamDefaultController.prototype, {
  4010. enqueue: { enumerable: true },
  4011. error: { enumerable: true },
  4012. terminate: { enumerable: true },
  4013. desiredSize: { enumerable: true }
  4014. });
  4015. if (typeof SymbolPolyfill.toStringTag === 'symbol') {
  4016. Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
  4017. value: 'TransformStreamDefaultController',
  4018. configurable: true
  4019. });
  4020. }
  4021. // Transform Stream Default Controller Abstract Operations
  4022. function IsTransformStreamDefaultController(x) {
  4023. if (!typeIsObject(x)) {
  4024. return false;
  4025. }
  4026. if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {
  4027. return false;
  4028. }
  4029. return x instanceof TransformStreamDefaultController;
  4030. }
  4031. function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) {
  4032. controller._controlledTransformStream = stream;
  4033. stream._transformStreamController = controller;
  4034. controller._transformAlgorithm = transformAlgorithm;
  4035. controller._flushAlgorithm = flushAlgorithm;
  4036. }
  4037. function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) {
  4038. const controller = Object.create(TransformStreamDefaultController.prototype);
  4039. let transformAlgorithm = (chunk) => {
  4040. try {
  4041. TransformStreamDefaultControllerEnqueue(controller, chunk);
  4042. return promiseResolvedWith(undefined);
  4043. }
  4044. catch (transformResultE) {
  4045. return promiseRejectedWith(transformResultE);
  4046. }
  4047. };
  4048. let flushAlgorithm = () => promiseResolvedWith(undefined);
  4049. if (transformer.transform !== undefined) {
  4050. transformAlgorithm = chunk => transformer.transform(chunk, controller);
  4051. }
  4052. if (transformer.flush !== undefined) {
  4053. flushAlgorithm = () => transformer.flush(controller);
  4054. }
  4055. SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);
  4056. }
  4057. function TransformStreamDefaultControllerClearAlgorithms(controller) {
  4058. controller._transformAlgorithm = undefined;
  4059. controller._flushAlgorithm = undefined;
  4060. }
  4061. function TransformStreamDefaultControllerEnqueue(controller, chunk) {
  4062. const stream = controller._controlledTransformStream;
  4063. const readableController = stream._readable._readableStreamController;
  4064. if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {
  4065. throw new TypeError('Readable side is not in a state that permits enqueue');
  4066. }
  4067. // We throttle transform invocations based on the backpressure of the ReadableStream, but we still
  4068. // accept TransformStreamDefaultControllerEnqueue() calls.
  4069. try {
  4070. ReadableStreamDefaultControllerEnqueue(readableController, chunk);
  4071. }
  4072. catch (e) {
  4073. // This happens when readableStrategy.size() throws.
  4074. TransformStreamErrorWritableAndUnblockWrite(stream, e);
  4075. throw stream._readable._storedError;
  4076. }
  4077. const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);
  4078. if (backpressure !== stream._backpressure) {
  4079. TransformStreamSetBackpressure(stream, true);
  4080. }
  4081. }
  4082. function TransformStreamDefaultControllerError(controller, e) {
  4083. TransformStreamError(controller._controlledTransformStream, e);
  4084. }
  4085. function TransformStreamDefaultControllerPerformTransform(controller, chunk) {
  4086. const transformPromise = controller._transformAlgorithm(chunk);
  4087. return transformPromiseWith(transformPromise, undefined, r => {
  4088. TransformStreamError(controller._controlledTransformStream, r);
  4089. throw r;
  4090. });
  4091. }
  4092. function TransformStreamDefaultControllerTerminate(controller) {
  4093. const stream = controller._controlledTransformStream;
  4094. const readableController = stream._readable._readableStreamController;
  4095. ReadableStreamDefaultControllerClose(readableController);
  4096. const error = new TypeError('TransformStream terminated');
  4097. TransformStreamErrorWritableAndUnblockWrite(stream, error);
  4098. }
  4099. // TransformStreamDefaultSink Algorithms
  4100. function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) {
  4101. const controller = stream._transformStreamController;
  4102. if (stream._backpressure) {
  4103. const backpressureChangePromise = stream._backpressureChangePromise;
  4104. return transformPromiseWith(backpressureChangePromise, () => {
  4105. const writable = stream._writable;
  4106. const state = writable._state;
  4107. if (state === 'erroring') {
  4108. throw writable._storedError;
  4109. }
  4110. return TransformStreamDefaultControllerPerformTransform(controller, chunk);
  4111. });
  4112. }
  4113. return TransformStreamDefaultControllerPerformTransform(controller, chunk);
  4114. }
  4115. function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) {
  4116. // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already
  4117. // errored.
  4118. TransformStreamError(stream, reason);
  4119. return promiseResolvedWith(undefined);
  4120. }
  4121. function TransformStreamDefaultSinkCloseAlgorithm(stream) {
  4122. // stream._readable cannot change after construction, so caching it across a call to user code is safe.
  4123. const readable = stream._readable;
  4124. const controller = stream._transformStreamController;
  4125. const flushPromise = controller._flushAlgorithm();
  4126. TransformStreamDefaultControllerClearAlgorithms(controller);
  4127. // Return a promise that is fulfilled with undefined on success.
  4128. return transformPromiseWith(flushPromise, () => {
  4129. if (readable._state === 'errored') {
  4130. throw readable._storedError;
  4131. }
  4132. ReadableStreamDefaultControllerClose(readable._readableStreamController);
  4133. }, r => {
  4134. TransformStreamError(stream, r);
  4135. throw readable._storedError;
  4136. });
  4137. }
  4138. // TransformStreamDefaultSource Algorithms
  4139. function TransformStreamDefaultSourcePullAlgorithm(stream) {
  4140. // Invariant. Enforced by the promises returned by start() and pull().
  4141. TransformStreamSetBackpressure(stream, false);
  4142. // Prevent the next pull() call until there is backpressure.
  4143. return stream._backpressureChangePromise;
  4144. }
  4145. // Helper functions for the TransformStreamDefaultController.
  4146. function defaultControllerBrandCheckException(name) {
  4147. return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);
  4148. }
  4149. // Helper functions for the TransformStream.
  4150. function streamBrandCheckException(name) {
  4151. return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`);
  4152. }
  4153. exports.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy;
  4154. exports.CountQueuingStrategy = CountQueuingStrategy;
  4155. exports.ReadableByteStreamController = ReadableByteStreamController;
  4156. exports.ReadableStream = ReadableStream;
  4157. exports.ReadableStreamBYOBReader = ReadableStreamBYOBReader;
  4158. exports.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest;
  4159. exports.ReadableStreamDefaultController = ReadableStreamDefaultController;
  4160. exports.ReadableStreamDefaultReader = ReadableStreamDefaultReader;
  4161. exports.TransformStream = TransformStream;
  4162. exports.TransformStreamDefaultController = TransformStreamDefaultController;
  4163. exports.WritableStream = WritableStream;
  4164. exports.WritableStreamDefaultController = WritableStreamDefaultController;
  4165. exports.WritableStreamDefaultWriter = WritableStreamDefaultWriter;
  4166. Object.defineProperty(exports, '__esModule', { value: true });
  4167. })));
  4168. //# sourceMappingURL=ponyfill.es2018.js.map