ponyfill.mjs 178 KB

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