ponyfill.es6.mjs 169 KB

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