ponyfill.es2018.mjs 168 KB

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