polyfill.es2018.js 186 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241
  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. const exports$1 = {
  4154. ReadableStream,
  4155. ReadableStreamDefaultController,
  4156. ReadableByteStreamController,
  4157. ReadableStreamBYOBRequest,
  4158. ReadableStreamDefaultReader,
  4159. ReadableStreamBYOBReader,
  4160. WritableStream,
  4161. WritableStreamDefaultController,
  4162. WritableStreamDefaultWriter,
  4163. ByteLengthQueuingStrategy,
  4164. CountQueuingStrategy,
  4165. TransformStream,
  4166. TransformStreamDefaultController
  4167. };
  4168. // Add classes to global scope
  4169. if (typeof globals !== 'undefined') {
  4170. for (const prop in exports$1) {
  4171. if (Object.prototype.hasOwnProperty.call(exports$1, prop)) {
  4172. Object.defineProperty(globals, prop, {
  4173. value: exports$1[prop],
  4174. writable: true,
  4175. configurable: true
  4176. });
  4177. }
  4178. }
  4179. }
  4180. exports.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy;
  4181. exports.CountQueuingStrategy = CountQueuingStrategy;
  4182. exports.ReadableByteStreamController = ReadableByteStreamController;
  4183. exports.ReadableStream = ReadableStream;
  4184. exports.ReadableStreamBYOBReader = ReadableStreamBYOBReader;
  4185. exports.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest;
  4186. exports.ReadableStreamDefaultController = ReadableStreamDefaultController;
  4187. exports.ReadableStreamDefaultReader = ReadableStreamDefaultReader;
  4188. exports.TransformStream = TransformStream;
  4189. exports.TransformStreamDefaultController = TransformStreamDefaultController;
  4190. exports.WritableStream = WritableStream;
  4191. exports.WritableStreamDefaultController = WritableStreamDefaultController;
  4192. exports.WritableStreamDefaultWriter = WritableStreamDefaultWriter;
  4193. Object.defineProperty(exports, '__esModule', { value: true });
  4194. })));
  4195. //# sourceMappingURL=polyfill.es2018.js.map