polyfill.es2018.mjs 169 KB

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