AbstractOperations.cpp 195 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349
  1. /*
  2. * Copyright (c) 2022, Linus Groh <linusg@serenityos.org>
  3. * Copyright (c) 2023, Matthew Olsson <mattco@serenityos.org>
  4. * Copyright (c) 2023-2024, Shannon Booth <shannon@serenityos.org>
  5. * Copyright (c) 2023, Kenneth Myhra <kennethmyhra@serenityos.org>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include <LibJS/Runtime/Array.h>
  10. #include <LibJS/Runtime/ArrayBuffer.h>
  11. #include <LibJS/Runtime/DataView.h>
  12. #include <LibJS/Runtime/DataViewConstructor.h>
  13. #include <LibJS/Runtime/Intrinsics.h>
  14. #include <LibJS/Runtime/PromiseCapability.h>
  15. #include <LibJS/Runtime/PromiseConstructor.h>
  16. #include <LibJS/Runtime/TypedArray.h>
  17. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  18. #include <LibWeb/DOM/AbortSignal.h>
  19. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  20. #include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
  21. #include <LibWeb/HTML/StructuredSerialize.h>
  22. #include <LibWeb/Streams/AbstractOperations.h>
  23. #include <LibWeb/Streams/QueuingStrategy.h>
  24. #include <LibWeb/Streams/ReadableByteStreamController.h>
  25. #include <LibWeb/Streams/ReadableStream.h>
  26. #include <LibWeb/Streams/ReadableStreamBYOBReader.h>
  27. #include <LibWeb/Streams/ReadableStreamBYOBRequest.h>
  28. #include <LibWeb/Streams/ReadableStreamDefaultController.h>
  29. #include <LibWeb/Streams/ReadableStreamDefaultReader.h>
  30. #include <LibWeb/Streams/ReadableStreamGenericReader.h>
  31. #include <LibWeb/Streams/TransformStream.h>
  32. #include <LibWeb/Streams/TransformStreamDefaultController.h>
  33. #include <LibWeb/Streams/Transformer.h>
  34. #include <LibWeb/Streams/UnderlyingSink.h>
  35. #include <LibWeb/Streams/UnderlyingSource.h>
  36. #include <LibWeb/Streams/WritableStream.h>
  37. #include <LibWeb/Streams/WritableStreamDefaultController.h>
  38. #include <LibWeb/Streams/WritableStreamDefaultWriter.h>
  39. #include <LibWeb/WebIDL/AbstractOperations.h>
  40. #include <LibWeb/WebIDL/Buffers.h>
  41. #include <LibWeb/WebIDL/ExceptionOr.h>
  42. #include <LibWeb/WebIDL/Promise.h>
  43. namespace Web::Streams {
  44. // https://streams.spec.whatwg.org/#acquire-readable-stream-reader
  45. WebIDL::ExceptionOr<JS::NonnullGCPtr<ReadableStreamDefaultReader>> acquire_readable_stream_default_reader(ReadableStream& stream)
  46. {
  47. auto& realm = stream.realm();
  48. // 1. Let reader be a new ReadableStreamDefaultReader.
  49. auto reader = realm.heap().allocate<ReadableStreamDefaultReader>(realm, realm);
  50. // 2. Perform ? SetUpReadableStreamDefaultReader(reader, stream).
  51. TRY(set_up_readable_stream_default_reader(reader, stream));
  52. // 3. Return reader.
  53. return reader;
  54. }
  55. // https://streams.spec.whatwg.org/#acquire-readable-stream-byob-reader
  56. WebIDL::ExceptionOr<JS::NonnullGCPtr<ReadableStreamBYOBReader>> acquire_readable_stream_byob_reader(ReadableStream& stream)
  57. {
  58. auto& realm = stream.realm();
  59. // 1. Let reader be a new ReadableStreamBYOBReader.
  60. auto reader = realm.heap().allocate<ReadableStreamBYOBReader>(realm, realm);
  61. // 2. Perform ? SetUpReadableStreamBYOBReader(reader, stream).
  62. TRY(set_up_readable_stream_byob_reader(reader, stream));
  63. // 3. Return reader.
  64. return reader;
  65. }
  66. // https://streams.spec.whatwg.org/#is-readable-stream-locked
  67. bool is_readable_stream_locked(ReadableStream const& stream)
  68. {
  69. // 1. If stream.[[reader]] is undefined, return false.
  70. if (!stream.reader().has_value())
  71. return false;
  72. // 2. Return true.
  73. return true;
  74. }
  75. // https://streams.spec.whatwg.org/#readable-stream-cancel
  76. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> readable_stream_cancel(ReadableStream& stream, JS::Value reason)
  77. {
  78. auto& realm = stream.realm();
  79. // 1. Set stream.[[disturbed]] to true.
  80. stream.set_disturbed(true);
  81. // 2. If stream.[[state]] is "closed", return a promise resolved with undefined.
  82. if (stream.state() == ReadableStream::State::Closed)
  83. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  84. // 3. If stream.[[state]] is "errored", return a promise rejected with stream.[[storedError]].
  85. if (stream.state() == ReadableStream::State::Errored)
  86. return WebIDL::create_rejected_promise(realm, stream.stored_error());
  87. // 4. Perform ! ReadableStreamClose(stream).
  88. readable_stream_close(stream);
  89. // 5. Let reader be stream.[[reader]].
  90. auto reader = stream.reader();
  91. // 6. If reader is not undefined and reader implements ReadableStreamBYOBReader,
  92. if (reader.has_value() && reader->has<JS::NonnullGCPtr<ReadableStreamBYOBReader>>()) {
  93. // 1. Let readIntoRequests be reader.[[readIntoRequests]].
  94. // 2. Set reader.[[readIntoRequests]] to an empty list.
  95. auto read_into_requests = move(reader->get<JS::NonnullGCPtr<ReadableStreamBYOBReader>>()->read_into_requests());
  96. // 3. For each readIntoRequest of readIntoRequests,
  97. for (auto& read_into_request : read_into_requests) {
  98. // 1. Perform readIntoRequest’s close steps, given undefined.
  99. read_into_request->on_close(JS::js_undefined());
  100. }
  101. }
  102. // 7. Let sourceCancelPromise be ! stream.[[controller]].[[CancelSteps]](reason).
  103. auto source_cancel_promise = TRY(stream.controller()->visit([&](auto const& controller) {
  104. return controller->cancel_steps(reason);
  105. }));
  106. // 8. Return the result of reacting to sourceCancelPromise with a fulfillment step that returns undefined.
  107. auto react_result = WebIDL::react_to_promise(*source_cancel_promise,
  108. [](auto const&) -> WebIDL::ExceptionOr<JS::Value> { return JS::js_undefined(); },
  109. {});
  110. return WebIDL::create_resolved_promise(realm, react_result);
  111. }
  112. // https://streams.spec.whatwg.org/#readable-stream-fulfill-read-into-request
  113. void readable_stream_fulfill_read_into_request(ReadableStream& stream, JS::Value chunk, bool done)
  114. {
  115. // 1. Assert: ! ReadableStreamHasBYOBReader(stream) is true.
  116. VERIFY(readable_stream_has_byob_reader(stream));
  117. // 2. Let reader be stream.[[reader]].
  118. auto reader = stream.reader()->get<JS::NonnullGCPtr<ReadableStreamBYOBReader>>();
  119. // 3. Assert: reader.[[readIntoRequests]] is not empty.
  120. VERIFY(!reader->read_into_requests().is_empty());
  121. // 4. Let readIntoRequest be reader.[[readIntoRequests]][0].
  122. // 5. Remove readIntoRequest from reader.[[readIntoRequests]].
  123. auto read_into_request = reader->read_into_requests().take_first();
  124. // 6. If done is true, perform readIntoRequest’s close steps, given chunk.
  125. if (done) {
  126. read_into_request->on_close(chunk);
  127. }
  128. // 7. Otherwise, perform readIntoRequest’s chunk steps, given chunk.
  129. else {
  130. read_into_request->on_chunk(chunk);
  131. }
  132. }
  133. // https://streams.spec.whatwg.org/#readable-stream-fulfill-read-request
  134. void readable_stream_fulfill_read_request(ReadableStream& stream, JS::Value chunk, bool done)
  135. {
  136. // 1. Assert: ! ReadableStreamHasDefaultReader(stream) is true.
  137. VERIFY(readable_stream_has_default_reader(stream));
  138. // 2. Let reader be stream.[[reader]].
  139. auto reader = stream.reader()->get<JS::NonnullGCPtr<ReadableStreamDefaultReader>>();
  140. // 3. Assert: reader.[[readRequests]] is not empty.
  141. VERIFY(!reader->read_requests().is_empty());
  142. // 4. Let readRequest be reader.[[readRequests]][0].
  143. // 5. Remove readRequest from reader.[[readRequests]].
  144. auto read_request = reader->read_requests().take_first();
  145. // 6. If done is true, perform readRequest’s close steps.
  146. if (done) {
  147. read_request->on_close();
  148. }
  149. // 7. Otherwise, perform readRequest’s chunk steps, given chunk.
  150. else {
  151. read_request->on_chunk(chunk);
  152. }
  153. }
  154. // https://streams.spec.whatwg.org/#readable-stream-get-num-read-into-requests
  155. size_t readable_stream_get_num_read_into_requests(ReadableStream const& stream)
  156. {
  157. // 1. Assert: ! ReadableStreamHasBYOBReader(stream) is true.
  158. VERIFY(readable_stream_has_byob_reader(stream));
  159. // 2. Return stream.[[reader]].[[readIntoRequests]]'s size.
  160. return stream.reader()->get<JS::NonnullGCPtr<ReadableStreamBYOBReader>>()->read_into_requests().size();
  161. }
  162. // https://streams.spec.whatwg.org/#readable-stream-get-num-read-requests
  163. size_t readable_stream_get_num_read_requests(ReadableStream const& stream)
  164. {
  165. // 1. Assert: ! ReadableStreamHasDefaultReader(stream) is true.
  166. VERIFY(readable_stream_has_default_reader(stream));
  167. // 2. Return stream.[[reader]].[[readRequests]]'s size.
  168. return stream.reader()->get<JS::NonnullGCPtr<ReadableStreamDefaultReader>>()->read_requests().size();
  169. }
  170. // https://streams.spec.whatwg.org/#readable-stream-has-byob-reader
  171. bool readable_stream_has_byob_reader(ReadableStream const& stream)
  172. {
  173. // 1. Let reader be stream.[[reader]].
  174. auto reader = stream.reader();
  175. // 2. If reader is undefined, return false.
  176. if (!reader.has_value())
  177. return false;
  178. // 3. If reader implements ReadableStreamBYOBReader, return true.
  179. if (reader->has<JS::NonnullGCPtr<ReadableStreamBYOBReader>>())
  180. return true;
  181. // 4. Return false.
  182. return false;
  183. }
  184. // https://streams.spec.whatwg.org/#readable-stream-has-default-reader
  185. bool readable_stream_has_default_reader(ReadableStream const& stream)
  186. {
  187. // 1. Let reader be stream.[[reader]].
  188. auto reader = stream.reader();
  189. // 2. If reader is undefined, return false.
  190. if (!reader.has_value())
  191. return false;
  192. // 3. If reader implements ReadableStreamDefaultReader, return true.
  193. if (reader->has<JS::NonnullGCPtr<ReadableStreamDefaultReader>>())
  194. return true;
  195. // 4. Return false.
  196. return false;
  197. }
  198. // https://streams.spec.whatwg.org/#readable-stream-tee
  199. WebIDL::ExceptionOr<ReadableStreamPair> readable_stream_tee(JS::Realm& realm, ReadableStream& stream, bool clone_for_branch2)
  200. {
  201. // 1. Assert: stream implements ReadableStream.
  202. // 2. Assert: cloneForBranch2 is a boolean.
  203. // 3. If stream.[[controller]] implements ReadableByteStreamController, return ? ReadableByteStreamTee(stream).
  204. if (stream.controller()->has<JS::NonnullGCPtr<Streams::ReadableByteStreamController>>()) {
  205. return realm.vm().throw_completion<JS::InternalError>(JS::ErrorType::NotImplemented, "Byte stream teeing");
  206. }
  207. // 4. Return ? ReadableStreamDefaultTee(stream, cloneForBranch2).
  208. return TRY(readable_stream_default_tee(realm, stream, clone_for_branch2));
  209. }
  210. struct DefaultStreamTeeParams final : JS::Cell {
  211. JS_CELL(TeeParams, JS::Cell);
  212. JS_DECLARE_ALLOCATOR(DefaultStreamTeeParams);
  213. virtual void visit_edges(Visitor& visitor) override
  214. {
  215. Base::visit_edges(visitor);
  216. visitor.visit(reason1);
  217. visitor.visit(reason2);
  218. visitor.visit(branch1);
  219. visitor.visit(branch2);
  220. visitor.visit(pull_algorithm);
  221. }
  222. bool reading { false };
  223. bool read_again { false };
  224. bool canceled1 { false };
  225. bool canceled2 { false };
  226. JS::Value reason1 { JS::js_undefined() };
  227. JS::Value reason2 { JS::js_undefined() };
  228. JS::GCPtr<ReadableStream> branch1;
  229. JS::GCPtr<ReadableStream> branch2;
  230. JS::GCPtr<PullAlgorithm> pull_algorithm;
  231. };
  232. JS_DEFINE_ALLOCATOR(DefaultStreamTeeParams);
  233. // https://streams.spec.whatwg.org/#ref-for-read-request③
  234. class DefaultStreamTeeReadRequest final : public ReadRequest {
  235. JS_CELL(DefaultStreamTeeReadRequest, Cell);
  236. JS_DECLARE_ALLOCATOR(DefaultStreamTeeReadRequest);
  237. public:
  238. DefaultStreamTeeReadRequest(
  239. JS::Realm& realm,
  240. JS::NonnullGCPtr<ReadableStream> stream,
  241. JS::NonnullGCPtr<DefaultStreamTeeParams> params,
  242. JS::NonnullGCPtr<WebIDL::Promise> cancel_promise,
  243. bool clone_for_branch2)
  244. : m_realm(realm)
  245. , m_stream(stream)
  246. , m_params(params)
  247. , m_cancel_promise(cancel_promise)
  248. , m_clone_for_branch2(clone_for_branch2)
  249. {
  250. }
  251. // https://streams.spec.whatwg.org/#ref-for-read-request-chunk-steps③
  252. virtual void on_chunk(JS::Value chunk) override
  253. {
  254. // 1. Queue a microtask to perform the following steps:
  255. HTML::queue_a_microtask(nullptr, [this, chunk]() {
  256. HTML::TemporaryExecutionContext execution_context { Bindings::host_defined_environment_settings_object(m_realm) };
  257. auto controller1 = m_params->branch1->controller()->get<JS::NonnullGCPtr<ReadableStreamDefaultController>>();
  258. auto controller2 = m_params->branch2->controller()->get<JS::NonnullGCPtr<ReadableStreamDefaultController>>();
  259. // 1. Set readAgain to false.
  260. m_params->read_again = false;
  261. // 2. Let chunk1 and chunk2 be chunk.
  262. auto chunk1 = chunk;
  263. auto chunk2 = chunk;
  264. // 3. If canceled2 is false and cloneForBranch2 is true,
  265. if (!m_params->canceled2 && m_clone_for_branch2) {
  266. // 1. Let cloneResult be StructuredClone(chunk2).
  267. auto clone_result = structured_clone(m_realm, chunk2);
  268. // 2. If cloneResult is an abrupt completion,
  269. if (clone_result.is_exception()) {
  270. auto completion = Bindings::dom_exception_to_throw_completion(m_realm->vm(), clone_result.release_error());
  271. // 1. Perform ! ReadableStreamDefaultControllerError(branch1.[[controller]], cloneResult.[[Value]]).
  272. readable_stream_default_controller_error(controller1, completion.value().value());
  273. // 2. Perform ! ReadableStreamDefaultControllerError(branch2.[[controller]], cloneResult.[[Value]]).
  274. readable_stream_default_controller_error(controller2, completion.value().value());
  275. // 3. Resolve cancelPromise with ! ReadableStreamCancel(stream, cloneResult.[[Value]]).
  276. auto cancel_result = MUST(readable_stream_cancel(m_stream, completion.value().value()));
  277. JS::NonnullGCPtr cancel_value = verify_cast<JS::Promise>(*cancel_result->promise().ptr());
  278. WebIDL::resolve_promise(m_realm, m_cancel_promise, cancel_value);
  279. // 4. Return.
  280. return;
  281. }
  282. // 3. Otherwise, set chunk2 to cloneResult.[[Value]].
  283. chunk2 = clone_result.release_value();
  284. }
  285. // 4. If canceled1 is false, perform ! ReadableStreamDefaultControllerEnqueue(branch1.[[controller]], chunk1).
  286. if (!m_params->canceled1) {
  287. MUST(readable_stream_default_controller_enqueue(controller1, chunk1));
  288. }
  289. // 5. If canceled2 is false, perform ! ReadableStreamDefaultControllerEnqueue(branch2.[[controller]], chunk2).
  290. if (!m_params->canceled2) {
  291. MUST(readable_stream_default_controller_enqueue(controller2, chunk2));
  292. }
  293. // 6. Set reading to false.
  294. m_params->reading = false;
  295. // 7. If readAgain is true, perform pullAlgorithm.
  296. if (m_params->read_again) {
  297. MUST(m_params->pull_algorithm->function()());
  298. }
  299. });
  300. // NOTE: The microtask delay here is necessary because it takes at least a microtask to detect errors, when we
  301. // use reader.[[closedPromise]] below. We want errors in stream to error both branches immediately, so we
  302. // cannot let successful synchronously-available reads happen ahead of asynchronously-available errors.
  303. }
  304. // https://streams.spec.whatwg.org/#ref-for-read-request-close-steps②
  305. virtual void on_close() override
  306. {
  307. auto controller1 = m_params->branch1->controller()->get<JS::NonnullGCPtr<ReadableStreamDefaultController>>();
  308. auto controller2 = m_params->branch2->controller()->get<JS::NonnullGCPtr<ReadableStreamDefaultController>>();
  309. // 1. Set reading to false.
  310. m_params->reading = false;
  311. // 2. If canceled1 is false, perform ! ReadableStreamDefaultControllerClose(branch1.[[controller]]).
  312. if (!m_params->canceled1) {
  313. readable_stream_default_controller_close(controller1);
  314. }
  315. // 3. If canceled2 is false, perform ! ReadableStreamDefaultControllerClose(branch2.[[controller]]).
  316. if (!m_params->canceled2) {
  317. readable_stream_default_controller_close(controller2);
  318. }
  319. // 4. If canceled1 is false or canceled2 is false, resolve cancelPromise with undefined.
  320. if (!m_params->canceled1 || !m_params->canceled2) {
  321. WebIDL::resolve_promise(m_realm, m_cancel_promise, JS::js_undefined());
  322. }
  323. }
  324. // https://streams.spec.whatwg.org/#ref-for-read-request-error-steps③
  325. virtual void on_error(JS::Value) override
  326. {
  327. // 1. Set reading to false.
  328. m_params->reading = false;
  329. }
  330. private:
  331. virtual void visit_edges(Visitor& visitor) override
  332. {
  333. Base::visit_edges(visitor);
  334. visitor.visit(m_realm);
  335. visitor.visit(m_stream);
  336. visitor.visit(m_params);
  337. visitor.visit(m_cancel_promise);
  338. }
  339. JS::NonnullGCPtr<JS::Realm> m_realm;
  340. JS::NonnullGCPtr<ReadableStream> m_stream;
  341. JS::NonnullGCPtr<DefaultStreamTeeParams> m_params;
  342. JS::NonnullGCPtr<WebIDL::Promise> m_cancel_promise;
  343. bool m_clone_for_branch2 { false };
  344. };
  345. JS_DEFINE_ALLOCATOR(DefaultStreamTeeReadRequest);
  346. // https://streams.spec.whatwg.org/#abstract-opdef-readablestreamdefaulttee
  347. WebIDL::ExceptionOr<ReadableStreamPair> readable_stream_default_tee(JS::Realm& realm, ReadableStream& stream, bool clone_for_branch2)
  348. {
  349. // 1. Assert: stream implements ReadableStream.
  350. // 2. Assert: cloneForBranch2 is a boolean.
  351. // 3. Let reader be ? AcquireReadableStreamDefaultReader(stream).
  352. auto reader = TRY(acquire_readable_stream_default_reader(stream));
  353. // 4. Let reading be false.
  354. // 5. Let readAgain be false.
  355. // 6. Let canceled1 be false.
  356. // 7. Let canceled2 be false.
  357. // 8. Let reason1 be undefined.
  358. // 9. Let reason2 be undefined.
  359. // 10. Let branch1 be undefined.
  360. // 11. Let branch2 be undefined.
  361. auto params = realm.heap().allocate<DefaultStreamTeeParams>(realm);
  362. // 12. Let cancelPromise be a new promise.
  363. auto cancel_promise = WebIDL::create_promise(realm);
  364. // 13. Let pullAlgorithm be the following steps:
  365. auto pull_algorithm = JS::create_heap_function(realm.heap(), [&realm, &stream, reader, params, cancel_promise, clone_for_branch2]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  366. // 1. If reading is true,
  367. if (params->reading) {
  368. // 1. Set readAgain to true.
  369. params->read_again = true;
  370. // 2. Return a promise resolved with undefined.
  371. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  372. }
  373. // 2. Set reading to true.
  374. params->reading = true;
  375. // 3. Let readRequest be a read request with the following items:
  376. auto read_request = realm.heap().allocate_without_realm<DefaultStreamTeeReadRequest>(realm, stream, params, cancel_promise, clone_for_branch2);
  377. // 4. Perform ! ReadableStreamDefaultReaderRead(reader, readRequest).
  378. MUST(readable_stream_default_reader_read(reader, read_request));
  379. // 5. Return a promise resolved with undefined.
  380. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  381. });
  382. // AD-HOC: The read request within the pull algorithm must be able to re-invoke the pull algorithm, so cache it here.
  383. params->pull_algorithm = pull_algorithm;
  384. // 14. Let cancel1Algorithm be the following steps, taking a reason argument:
  385. auto cancel1_algorithm = JS::create_heap_function(realm.heap(), [&realm, &stream, params, cancel_promise](JS::Value reason) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  386. // 1. Set canceled1 to true.
  387. params->canceled1 = true;
  388. // 2. Set reason1 to reason.
  389. params->reason1 = reason;
  390. // 3. If canceled2 is true,
  391. if (params->canceled2) {
  392. // 1. Let compositeReason be ! CreateArrayFromList(« reason1, reason2 »).
  393. auto composite_reason = JS::Array::create_from(realm, AK::Array { params->reason1, params->reason2 });
  394. // 2. Let cancelResult be ! ReadableStreamCancel(stream, compositeReason).
  395. auto cancel_result = MUST(readable_stream_cancel(stream, composite_reason));
  396. // 3. Resolve cancelPromise with cancelResult.
  397. JS::NonnullGCPtr cancel_value = verify_cast<JS::Promise>(*cancel_result->promise().ptr());
  398. WebIDL::resolve_promise(realm, cancel_promise, cancel_value);
  399. }
  400. // 4. Return cancelPromise.
  401. return cancel_promise;
  402. });
  403. // 15. Let cancel2Algorithm be the following steps, taking a reason argument:
  404. auto cancel2_algorithm = JS::create_heap_function(realm.heap(), [&realm, &stream, params, cancel_promise](JS::Value reason) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  405. // 1. Set canceled2 to true.
  406. params->canceled2 = true;
  407. // 2. Set reason2 to reason.
  408. params->reason2 = reason;
  409. // 3. If canceled1 is true,
  410. if (params->canceled1) {
  411. // 1. Let compositeReason be ! CreateArrayFromList(« reason1, reason2 »).
  412. auto composite_reason = JS::Array::create_from(realm, AK::Array { params->reason1, params->reason2 });
  413. // 2. Let cancelResult be ! ReadableStreamCancel(stream, compositeReason).
  414. auto cancel_result = MUST(readable_stream_cancel(stream, composite_reason));
  415. // 3. Resolve cancelPromise with cancelResult.
  416. JS::NonnullGCPtr cancel_value = verify_cast<JS::Promise>(*cancel_result->promise().ptr());
  417. WebIDL::resolve_promise(realm, cancel_promise, cancel_value);
  418. }
  419. // 4. Return cancelPromise.
  420. return cancel_promise;
  421. });
  422. // 16. Let startAlgorithm be an algorithm that returns undefined.
  423. auto start_algorithm = JS::create_heap_function(realm.heap(), []() -> WebIDL::ExceptionOr<JS::Value> {
  424. return JS::js_undefined();
  425. });
  426. // 17. Set branch1 to ! CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm).
  427. params->branch1 = MUST(create_readable_stream(realm, start_algorithm, pull_algorithm, cancel1_algorithm));
  428. // 18. Set branch2 to ! CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm).
  429. params->branch2 = MUST(create_readable_stream(realm, start_algorithm, pull_algorithm, cancel2_algorithm));
  430. // 19. Upon rejection of reader.[[closedPromise]] with reason r,
  431. WebIDL::upon_rejection(*reader->closed_promise_capability(), [&realm, params, cancel_promise](auto reason) -> WebIDL::ExceptionOr<JS::Value> {
  432. auto controller1 = params->branch1->controller()->get<JS::NonnullGCPtr<ReadableStreamDefaultController>>();
  433. auto controller2 = params->branch2->controller()->get<JS::NonnullGCPtr<ReadableStreamDefaultController>>();
  434. // 1. Perform ! ReadableStreamDefaultControllerError(branch1.[[controller]], r).
  435. readable_stream_default_controller_error(controller1, reason);
  436. // 2. Perform ! ReadableStreamDefaultControllerError(branch2.[[controller]], r).
  437. readable_stream_default_controller_error(controller2, reason);
  438. // 3. If canceled1 is false or canceled2 is false, resolve cancelPromise with undefined.
  439. if (!params->canceled1 || !params->canceled2) {
  440. WebIDL::resolve_promise(realm, cancel_promise, JS::js_undefined());
  441. }
  442. return JS::js_undefined();
  443. });
  444. // 20. Return « branch1, branch2 ».
  445. return ReadableStreamPair { *params->branch1, *params->branch2 };
  446. }
  447. // https://streams.spec.whatwg.org/#make-size-algorithm-from-size-function
  448. JS::NonnullGCPtr<SizeAlgorithm> extract_size_algorithm(JS::VM& vm, QueuingStrategy const& strategy)
  449. {
  450. // 1. If strategy["size"] does not exist, return an algorithm that returns 1.
  451. if (!strategy.size)
  452. return JS::create_heap_function(vm.heap(), [](JS::Value) { return JS::normal_completion(JS::Value(1)); });
  453. // 2. Return an algorithm that performs the following steps, taking a chunk argument:
  454. return JS::create_heap_function(vm.heap(), [size = strategy.size](JS::Value chunk) {
  455. return WebIDL::invoke_callback(*size, JS::js_undefined(), chunk);
  456. });
  457. }
  458. // https://streams.spec.whatwg.org/#validate-and-normalize-high-water-mark
  459. WebIDL::ExceptionOr<double> extract_high_water_mark(QueuingStrategy const& strategy, double default_hwm)
  460. {
  461. // 1. If strategy["highWaterMark"] does not exist, return defaultHWM.
  462. if (!strategy.high_water_mark.has_value())
  463. return default_hwm;
  464. // 2. Let highWaterMark be strategy["highWaterMark"].
  465. auto high_water_mark = strategy.high_water_mark.value();
  466. // 3. If highWaterMark is NaN or highWaterMark < 0, throw a RangeError exception.
  467. if (isnan(high_water_mark) || high_water_mark < 0)
  468. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Invalid value for high water mark"sv };
  469. // 4. Return highWaterMark.
  470. return high_water_mark;
  471. }
  472. // https://streams.spec.whatwg.org/#readable-stream-close
  473. void readable_stream_close(ReadableStream& stream)
  474. {
  475. auto& realm = stream.realm();
  476. // 1. Assert: stream.[[state]] is "readable".
  477. VERIFY(stream.state() == ReadableStream::State::Readable);
  478. // 2. Set stream.[[state]] to "closed".
  479. stream.set_state(ReadableStream::State::Closed);
  480. // 3. Let reader be stream.[[reader]].
  481. auto reader = stream.reader();
  482. // 4. If reader is undefined, return.
  483. if (!reader.has_value())
  484. return;
  485. // 5. Resolve reader.[[closedPromise]] with undefined.
  486. WebIDL::resolve_promise(realm, *reader->visit([](auto& reader) {
  487. return reader->closed_promise_capability();
  488. }));
  489. // 6. If reader implements ReadableStreamDefaultReader,
  490. if (reader->has<JS::NonnullGCPtr<ReadableStreamDefaultReader>>()) {
  491. // 1. Let readRequests be reader.[[readRequests]].
  492. // 2. Set reader.[[readRequests]] to an empty list.
  493. auto read_requests = move(reader->get<JS::NonnullGCPtr<ReadableStreamDefaultReader>>()->read_requests());
  494. // 3. For each readRequest of readRequests,
  495. for (auto& read_request : read_requests) {
  496. // 1. Perform readRequest’s close steps.
  497. read_request->on_close();
  498. }
  499. }
  500. }
  501. // https://streams.spec.whatwg.org/#readable-stream-error
  502. void readable_stream_error(ReadableStream& stream, JS::Value error)
  503. {
  504. auto& realm = stream.realm();
  505. // 1. Assert: stream.[[state]] is "readable".
  506. VERIFY(stream.state() == ReadableStream::State::Readable);
  507. // 2. Set stream.[[state]] to "errored".
  508. stream.set_state(ReadableStream::State::Errored);
  509. // 3. Set stream.[[storedError]] to e.
  510. stream.set_stored_error(error);
  511. // 4. Let reader be stream.[[reader]].
  512. auto reader = stream.reader();
  513. // 5. If reader is undefined, return.
  514. if (!reader.has_value())
  515. return;
  516. auto closed_promise_capability = reader->visit([](auto& reader) { return reader->closed_promise_capability(); });
  517. // 6. Reject reader.[[closedPromise]] with e.
  518. WebIDL::reject_promise(realm, *closed_promise_capability, error);
  519. // 7. Set reader.[[closedPromise]].[[PromiseIsHandled]] to true.
  520. WebIDL::mark_promise_as_handled(*closed_promise_capability);
  521. // 8. If reader implements ReadableStreamDefaultReader,
  522. if (reader->has<JS::NonnullGCPtr<ReadableStreamDefaultReader>>()) {
  523. // 1. Perform ! ReadableStreamDefaultReaderErrorReadRequests(reader, e).
  524. readable_stream_default_reader_error_read_requests(*reader->get<JS::NonnullGCPtr<ReadableStreamDefaultReader>>(), error);
  525. }
  526. // 9. Otherwise,
  527. else {
  528. // 1. Assert: reader implements ReadableStreamBYOBReader.
  529. VERIFY(reader->has<JS::NonnullGCPtr<ReadableStreamBYOBReader>>());
  530. // 2. Perform ! ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e).
  531. readable_stream_byob_reader_error_read_into_requests(*reader->get<JS::NonnullGCPtr<ReadableStreamBYOBReader>>(), error);
  532. }
  533. }
  534. // https://streams.spec.whatwg.org/#readable-stream-add-read-request
  535. void readable_stream_add_read_request(ReadableStream& stream, JS::NonnullGCPtr<ReadRequest> read_request)
  536. {
  537. // 1. Assert: stream.[[reader]] implements ReadableStreamDefaultReader.
  538. VERIFY(stream.reader().has_value() && stream.reader()->has<JS::NonnullGCPtr<ReadableStreamDefaultReader>>());
  539. // 2. Assert: stream.[[state]] is "readable".
  540. VERIFY(stream.state() == ReadableStream::State::Readable);
  541. // 3. Append readRequest to stream.[[reader]].[[readRequests]].
  542. stream.reader()->get<JS::NonnullGCPtr<ReadableStreamDefaultReader>>()->read_requests().append(read_request);
  543. }
  544. // https://streams.spec.whatwg.org/#readable-stream-add-read-into-request
  545. void readable_stream_add_read_into_request(ReadableStream& stream, JS::NonnullGCPtr<ReadIntoRequest> read_into_request)
  546. {
  547. // 1. Assert: stream.[[reader]] implements ReadableStreamBYOBReader.
  548. VERIFY(stream.reader().has_value() && stream.reader()->has<JS::NonnullGCPtr<ReadableStreamBYOBReader>>());
  549. // 2. Assert: stream.[[state]] is "readable" or "closed".
  550. VERIFY(stream.is_readable() || stream.is_closed());
  551. // 3. Append readRequest to stream.[[reader]].[[readIntoRequests]].
  552. stream.reader()->get<JS::NonnullGCPtr<ReadableStreamBYOBReader>>()->read_into_requests().append(read_into_request);
  553. }
  554. // https://streams.spec.whatwg.org/#readable-stream-reader-generic-cancel
  555. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> readable_stream_reader_generic_cancel(ReadableStreamGenericReaderMixin& reader, JS::Value reason)
  556. {
  557. // 1. Let stream be reader.[[stream]]
  558. auto stream = reader.stream();
  559. // 2. Assert: stream is not undefined
  560. VERIFY(stream);
  561. // 3. Return ! ReadableStreamCancel(stream, reason)
  562. return TRY(readable_stream_cancel(*stream, reason));
  563. }
  564. // https://streams.spec.whatwg.org/#readable-stream-reader-generic-initialize
  565. void readable_stream_reader_generic_initialize(ReadableStreamReader reader, ReadableStream& stream)
  566. {
  567. auto& realm = stream.realm();
  568. // 1. Set reader.[[stream]] to stream.
  569. reader.visit([&](auto& reader) { reader->set_stream(stream); });
  570. // 2. Set stream.[[reader]] to reader.
  571. stream.set_reader(reader);
  572. // 3. If stream.[[state]] is "readable",
  573. if (stream.state() == ReadableStream::State::Readable) {
  574. // 1. Set reader.[[closedPromise]] to a new promise.
  575. reader.visit([&](auto& reader) { reader->set_closed_promise_capability(WebIDL::create_promise(realm)); });
  576. }
  577. // 4. Otherwise, if stream.[[state]] is "closed",
  578. else if (stream.state() == ReadableStream::State::Closed) {
  579. // 1. Set reader.[[closedPromise]] to a promise resolved with undefined.
  580. reader.visit([&](auto& reader) {
  581. reader->set_closed_promise_capability(WebIDL::create_resolved_promise(realm, JS::js_undefined()));
  582. });
  583. }
  584. // 5. Otherwise,
  585. else {
  586. // 1. Assert: stream.[[state]] is "errored".
  587. VERIFY(stream.state() == ReadableStream::State::Errored);
  588. // 2. Set reader.[[closedPromise]] to a promise rejected with stream.[[storedError]].
  589. // 3. Set reader.[[closedPromise]].[[PromiseIsHandled]] to true.
  590. reader.visit([&](auto& reader) {
  591. reader->set_closed_promise_capability(WebIDL::create_rejected_promise(realm, stream.stored_error()));
  592. WebIDL::mark_promise_as_handled(*reader->closed_promise_capability());
  593. });
  594. }
  595. }
  596. // https://streams.spec.whatwg.org/#readable-stream-reader-generic-release
  597. WebIDL::ExceptionOr<void> readable_stream_reader_generic_release(ReadableStreamGenericReaderMixin& reader)
  598. {
  599. // 1. Let stream be reader.[[stream]].
  600. auto stream = reader.stream();
  601. // 2. Assert: stream is not undefined.
  602. VERIFY(stream);
  603. // 3. Assert: stream.[[reader]] is reader.
  604. VERIFY(stream->reader()->visit([](auto& reader) -> ReadableStreamGenericReaderMixin* { return reader.ptr(); }) == &reader);
  605. auto& realm = stream->realm();
  606. // 4. If stream.[[state]] is "readable", reject reader.[[closedPromise]] with a TypeError exception.
  607. auto exception = JS::TypeError::create(realm, "Released readable stream"sv);
  608. if (stream->is_readable()) {
  609. WebIDL::reject_promise(realm, *reader.closed_promise_capability(), exception);
  610. }
  611. // 5. Otherwise, set reader.[[closedPromise]] to a promise rejected with a TypeError exception.
  612. else {
  613. reader.set_closed_promise_capability(WebIDL::create_rejected_promise(realm, exception));
  614. }
  615. // 6. Set reader.[[closedPromise]].[[PromiseIsHandled]] to true.
  616. WebIDL::mark_promise_as_handled(*reader.closed_promise_capability());
  617. // 7. Perform ! stream.[[controller]].[[ReleaseSteps]]().
  618. TRY(stream->controller()->visit([](auto const& controller) { return controller->release_steps(); }));
  619. // 8. Set stream.[[reader]] to undefined.
  620. stream->set_reader({});
  621. // 9. Set reader.[[stream]] to undefined.
  622. reader.set_stream({});
  623. return {};
  624. }
  625. // https://streams.spec.whatwg.org/#abstract-opdef-readablestreamdefaultreadererrorreadrequests
  626. void readable_stream_default_reader_error_read_requests(ReadableStreamDefaultReader& reader, JS::Value error)
  627. {
  628. // 1. Let readRequests be reader.[[readRequests]].
  629. auto read_requests = move(reader.read_requests());
  630. // 2. Set reader.[[readRequests]] to a new empty list.
  631. reader.read_requests().clear();
  632. // 3. For each readRequest of readRequests,
  633. for (auto& read_request : read_requests) {
  634. // 1. Perform readRequest’s error steps, given e.
  635. read_request->on_error(error);
  636. }
  637. }
  638. // https://streams.spec.whatwg.org/#abstract-opdef-readablestreambyobreadererrorreadintorequests
  639. void readable_stream_byob_reader_error_read_into_requests(ReadableStreamBYOBReader& reader, JS::Value error)
  640. {
  641. // 1. Let readIntoRequests be reader.[[readIntoRequests]].
  642. auto read_into_requests = move(reader.read_into_requests());
  643. // 2. Set reader.[[readIntoRequests]] to a new empty list.
  644. reader.read_into_requests().clear();
  645. // 3. For each readIntoRequest of readIntoRequests,
  646. for (auto& read_into_request : read_into_requests) {
  647. // 1. Perform readIntoRequest’s error steps, given e.
  648. read_into_request->on_error(error);
  649. }
  650. }
  651. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-fill-head-pull-into-descriptor
  652. void readable_byte_stream_controller_fill_head_pull_into_descriptor(ReadableByteStreamController const& controller, u64 size, PullIntoDescriptor& pull_into_descriptor)
  653. {
  654. // 1. Assert: either controller.[[pendingPullIntos]] is empty, or controller.[[pendingPullIntos]][0] is pullIntoDescriptor.
  655. VERIFY(controller.pending_pull_intos().is_empty() || &controller.pending_pull_intos().first() == &pull_into_descriptor);
  656. // 2. Assert: controller.[[byobRequest]] is null.
  657. VERIFY(!controller.raw_byob_request());
  658. // 3. Set pullIntoDescriptor’s bytes filled to bytes filled + size.
  659. pull_into_descriptor.bytes_filled += size;
  660. }
  661. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-fill-pull-into-descriptor-from-queue
  662. bool readable_byte_stream_controller_fill_pull_into_descriptor_from_queue(ReadableByteStreamController& controller, PullIntoDescriptor& pull_into_descriptor)
  663. {
  664. // 1. Let elementSize be pullIntoDescriptor.[[elementSize]].
  665. auto element_size = pull_into_descriptor.element_size;
  666. // 2. Let currentAlignedBytes be pullIntoDescriptor’s bytes filled − (pullIntoDescriptor’s bytes filled mod elementSize).
  667. auto current_aligned_bytes = pull_into_descriptor.bytes_filled - (pull_into_descriptor.bytes_filled % pull_into_descriptor.element_size);
  668. // 3. Let maxBytesToCopy be min(controller.[[queueTotalSize]], pullIntoDescriptor’s byte length − pullIntoDescriptor’s bytes filled).
  669. auto max_bytes_to_copy = min(controller.queue_total_size(), pull_into_descriptor.byte_length - pull_into_descriptor.bytes_filled);
  670. // 4. Let maxBytesFilled be pullIntoDescriptor’s bytes filled + maxBytesToCopy.
  671. u64 max_bytes_filled = pull_into_descriptor.bytes_filled + max_bytes_to_copy;
  672. // 5. Let maxAlignedBytes be maxBytesFilled − (maxBytesFilled mod elementSize).
  673. auto max_aligned_bytes = max_bytes_filled - (max_bytes_filled % element_size);
  674. // 6. Let totalBytesToCopyRemaining be maxBytesToCopy.
  675. auto total_bytes_to_copy_remaining = max_bytes_to_copy;
  676. // 7. Let ready be false.
  677. bool ready = false;
  678. // 8. If maxAlignedBytes > currentAlignedBytes,
  679. if (max_aligned_bytes > current_aligned_bytes) {
  680. // 1. Set totalBytesToCopyRemaining to maxAlignedBytes − pullIntoDescriptor’s bytes filled.
  681. total_bytes_to_copy_remaining = max_aligned_bytes - pull_into_descriptor.bytes_filled;
  682. // 2. Set ready to true.
  683. ready = true;
  684. }
  685. // 9. Let queue be controller.[[queue]].
  686. auto& queue = controller.queue();
  687. // 10. While totalBytesToCopyRemaining > 0,
  688. while (total_bytes_to_copy_remaining > 0) {
  689. // 1. Let headOfQueue be queue[0].
  690. auto& head_of_queue = queue.first();
  691. // 2. Let bytesToCopy be min(totalBytesToCopyRemaining, headOfQueue’s byte length).
  692. auto bytes_to_copy = min(total_bytes_to_copy_remaining, head_of_queue.byte_length);
  693. // 3. Let destStart be pullIntoDescriptor’s byte offset + pullIntoDescriptor’s bytes filled.
  694. auto dest_start = pull_into_descriptor.byte_offset + pull_into_descriptor.bytes_filled;
  695. // 4. Perform ! CopyDataBlockBytes(pullIntoDescriptor’s buffer.[[ArrayBufferData]], destStart, headOfQueue’s buffer.[[ArrayBufferData]], headOfQueue’s byte offset, bytesToCopy).
  696. JS::copy_data_block_bytes(pull_into_descriptor.buffer->buffer(), dest_start, head_of_queue.buffer->buffer(), head_of_queue.byte_offset, bytes_to_copy);
  697. // 5. If headOfQueue’s byte length is bytesToCopy,
  698. if (head_of_queue.byte_length == bytes_to_copy) {
  699. // 1. Remove queue[0].
  700. queue.take_first();
  701. }
  702. // 6. Otherwise,
  703. else {
  704. // 1. Set headOfQueue’s byte offset to headOfQueue’s byte offset + bytesToCopy.
  705. head_of_queue.byte_offset += bytes_to_copy;
  706. // 2. Set headOfQueue’s byte length to headOfQueue’s byte length − bytesToCopy.
  707. head_of_queue.byte_length -= bytes_to_copy;
  708. }
  709. // 7. Set controller.[[queueTotalSize]] to controller.[[queueTotalSize]] − bytesToCopy.
  710. controller.set_queue_total_size(controller.queue_total_size() - bytes_to_copy);
  711. // 8, Perform ! ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor).
  712. readable_byte_stream_controller_fill_head_pull_into_descriptor(controller, bytes_to_copy, pull_into_descriptor);
  713. // 9. Set totalBytesToCopyRemaining to totalBytesToCopyRemaining − bytesToCopy.
  714. total_bytes_to_copy_remaining -= bytes_to_copy;
  715. }
  716. // 11. If ready is false,
  717. if (!ready) {
  718. // 1. Assert: controller.[[queueTotalSize]] is 0.
  719. VERIFY(controller.queue_total_size() == 0);
  720. // 2. Assert: pullIntoDescriptor’s bytes filled > 0.
  721. VERIFY(pull_into_descriptor.bytes_filled > 0);
  722. // 3. Assert: pullIntoDescriptor’s bytes filled < pullIntoDescriptor’s element size.
  723. VERIFY(pull_into_descriptor.bytes_filled < pull_into_descriptor.element_size);
  724. }
  725. // 12. Return ready.
  726. return ready;
  727. }
  728. // https://streams.spec.whatwg.org/#readable-stream-default-reader-read
  729. WebIDL::ExceptionOr<void> readable_stream_default_reader_read(ReadableStreamDefaultReader& reader, ReadRequest& read_request)
  730. {
  731. // 1. Let stream be reader.[[stream]].
  732. auto stream = reader.stream();
  733. // 2. Assert: stream is not undefined.
  734. VERIFY(stream);
  735. // 3. Set stream.[[disturbed]] to true.
  736. stream->set_disturbed(true);
  737. // 4. If stream.[[state]] is "closed", perform readRequest’s close steps.
  738. if (stream->is_closed()) {
  739. read_request.on_close();
  740. }
  741. // 5. Otherwise, if stream.[[state]] is "errored", perform readRequest’s error steps given stream.[[storedError]].
  742. else if (stream->is_errored()) {
  743. read_request.on_error(stream->stored_error());
  744. }
  745. // 6. Otherwise,
  746. else {
  747. // 1. Assert: stream.[[state]] is "readable".
  748. VERIFY(stream->is_readable());
  749. // 2. Perform ! stream.[[controller]].[[PullSteps]](readRequest).
  750. TRY(stream->controller()->visit([&](auto const& controller) {
  751. return controller->pull_steps(read_request);
  752. }));
  753. }
  754. return {};
  755. }
  756. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-convert-pull-into-descriptor
  757. JS::Value readable_byte_stream_controller_convert_pull_into_descriptor(JS::Realm& realm, PullIntoDescriptor const& pull_into_descriptor)
  758. {
  759. auto& vm = realm.vm();
  760. // 1. Let bytesFilled be pullIntoDescriptor’s bytes filled.
  761. auto bytes_filled = pull_into_descriptor.bytes_filled;
  762. // 2. Let elementSize be pullIntoDescriptor’s element size.
  763. auto element_size = pull_into_descriptor.element_size;
  764. // 3. Assert: bytesFilled ≤ pullIntoDescriptor’s byte length.
  765. VERIFY(bytes_filled <= pull_into_descriptor.byte_length);
  766. // 4. Assert: bytesFilled mod elementSize is 0.
  767. VERIFY(bytes_filled % element_size == 0);
  768. // 5. Let buffer be ! TransferArrayBuffer(pullIntoDescriptor’s buffer).
  769. auto buffer = MUST(transfer_array_buffer(realm, pull_into_descriptor.buffer));
  770. // 6. Return ! Construct(pullIntoDescriptor’s view constructor, « buffer, pullIntoDescriptor’s byte offset, bytesFilled ÷ elementSize »).
  771. return MUST(JS::construct(vm, *pull_into_descriptor.view_constructor, buffer, JS::Value(pull_into_descriptor.byte_offset), JS::Value(bytes_filled / element_size)));
  772. }
  773. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-pull-into
  774. void readable_byte_stream_controller_pull_into(ReadableByteStreamController& controller, WebIDL::ArrayBufferView& view, ReadIntoRequest& read_into_request)
  775. {
  776. auto& vm = controller.vm();
  777. auto& realm = controller.realm();
  778. // 1. Let stream be controller.[[stream]].
  779. auto stream = controller.stream();
  780. // 2. Let elementSize be 1.
  781. size_t element_size = 1;
  782. // 3. Let ctor be %DataView%.
  783. JS::NativeFunction* ctor = realm.intrinsics().data_view_constructor();
  784. // 4. If view has a [[TypedArrayName]] internal slot (i.e., it is not a DataView),
  785. if (view.bufferable_object().has<JS::NonnullGCPtr<JS::TypedArrayBase>>()) {
  786. auto const& typed_array = *view.bufferable_object().get<JS::NonnullGCPtr<JS::TypedArrayBase>>();
  787. // 1. Set elementSize to the element size specified in the typed array constructors table for view.[[TypedArrayName]].
  788. element_size = typed_array.element_size();
  789. // 2. Set ctor to the constructor specified in the typed array constructors table for view.[[TypedArrayName]].
  790. switch (typed_array.kind()) {
  791. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, Type) \
  792. case JS::TypedArrayBase::Kind::ClassName: \
  793. ctor = realm.intrinsics().snake_name##_constructor(); \
  794. break;
  795. JS_ENUMERATE_TYPED_ARRAYS
  796. #undef __JS_ENUMERATE
  797. }
  798. }
  799. // 5. Let byteOffset be view.[[ByteOffset]].
  800. auto byte_offset = view.byte_offset();
  801. // 6. Let byteLength be view.[[ByteLength]].
  802. auto byte_length = view.byte_length();
  803. // 7. Let bufferResult be TransferArrayBuffer(view.[[ViewedArrayBuffer]]).
  804. auto buffer_result = transfer_array_buffer(realm, *view.viewed_array_buffer());
  805. // 8. If bufferResult is an abrupt completion,
  806. if (buffer_result.is_exception()) {
  807. // 1. Perform readIntoRequest’s error steps, given bufferResult.[[Value]].
  808. auto throw_completion = Bindings::dom_exception_to_throw_completion(vm, buffer_result.exception());
  809. read_into_request.on_error(*throw_completion.release_value());
  810. // 2. Return.
  811. return;
  812. }
  813. // 9. Let buffer be bufferResult.[[Value]].
  814. auto buffer = buffer_result.value();
  815. // 10. Let pullIntoDescriptor be a new pull-into descriptor with buffer buffer, buffer byte length buffer.[[ArrayBufferByteLength]],
  816. // byte offset byteOffset, byte length byteLength, bytes filled 0, element size elementSize, view constructor ctor, and reader type "byob".
  817. PullIntoDescriptor pull_into_descriptor {
  818. .buffer = buffer,
  819. .buffer_byte_length = buffer->byte_length(),
  820. .byte_offset = byte_offset,
  821. .byte_length = byte_length,
  822. .bytes_filled = 0,
  823. .element_size = element_size,
  824. .view_constructor = *ctor,
  825. .reader_type = ReaderType::Byob,
  826. };
  827. // 11. If controller.[[pendingPullIntos]] is not empty,
  828. if (!controller.pending_pull_intos().is_empty()) {
  829. // 1. Append pullIntoDescriptor to controller.[[pendingPullIntos]].
  830. controller.pending_pull_intos().append(pull_into_descriptor);
  831. // 2. Perform ! ReadableStreamAddReadIntoRequest(stream, readIntoRequest).
  832. readable_stream_add_read_into_request(*stream, read_into_request);
  833. // 3. Return.
  834. return;
  835. }
  836. // 12. If stream.[[state]] is "closed",
  837. if (stream->is_closed()) {
  838. // 1. Let emptyView be ! Construct(ctor, « pullIntoDescriptor’s buffer, pullIntoDescriptor’s byte offset, 0 »).
  839. auto empty_view = MUST(JS::construct(vm, *ctor, pull_into_descriptor.buffer, JS::Value(pull_into_descriptor.byte_offset), JS::Value(0)));
  840. // 2. Perform readIntoRequest’s close steps, given emptyView.
  841. read_into_request.on_close(empty_view);
  842. // 3. Return.
  843. return;
  844. }
  845. // 13. If controller.[[queueTotalSize]] > 0,
  846. if (controller.queue_total_size() > 0) {
  847. // 1. If ! ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) is true,
  848. if (readable_byte_stream_controller_fill_pull_into_descriptor_from_queue(controller, pull_into_descriptor)) {
  849. // 1. Let filledView be ! ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor).
  850. auto filled_view = readable_byte_stream_controller_convert_pull_into_descriptor(realm, pull_into_descriptor);
  851. // 2. Perform ! ReadableByteStreamControllerHandleQueueDrain(controller).
  852. MUST(readable_byte_stream_controller_handle_queue_drain(controller));
  853. // 3. Perform readIntoRequest’s chunk steps, given filledView.
  854. read_into_request.on_chunk(filled_view);
  855. // 4. Return.
  856. return;
  857. }
  858. // 2. If controller.[[closeRequested]] is true,
  859. if (controller.close_requested()) {
  860. // 1. Let e be a TypeError exception.
  861. auto error = JS::TypeError::create(realm, "Reader has been released"sv);
  862. // 2. Perform ! ReadableByteStreamControllerError(controller, e).
  863. readable_byte_stream_controller_error(controller, error);
  864. // 3. Perform readIntoRequest’s error steps, given e.
  865. read_into_request.on_error(error);
  866. // 4. Return.
  867. return;
  868. }
  869. }
  870. // 14. Append pullIntoDescriptor to controller.[[pendingPullIntos]].
  871. controller.pending_pull_intos().append(pull_into_descriptor);
  872. // 15. Perform ! ReadableStreamAddReadIntoRequest(stream, readIntoRequest).
  873. readable_stream_add_read_into_request(*stream, read_into_request);
  874. // 16. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
  875. MUST(readable_byte_stream_controller_call_pull_if_needed(controller));
  876. }
  877. // https://streams.spec.whatwg.org/#readable-stream-byob-reader-read
  878. void readable_stream_byob_reader_read(ReadableStreamBYOBReader& reader, WebIDL::ArrayBufferView& view, ReadIntoRequest& read_into_request)
  879. {
  880. // 1. Let stream be reader.[[stream]].
  881. auto stream = reader.stream();
  882. // 2. Assert: stream is not undefined.
  883. VERIFY(stream);
  884. // 3. Set stream.[[disturbed]] to true.
  885. stream->set_disturbed(true);
  886. // 4. If stream.[[state]] is "errored", perform readIntoRequest’s error steps given stream.[[storedError]].
  887. if (stream->is_errored()) {
  888. read_into_request.on_error(stream->stored_error());
  889. }
  890. // 5. Otherwise, perform ! ReadableByteStreamControllerPullInto(stream.[[controller]], view, readIntoRequest).
  891. else {
  892. readable_byte_stream_controller_pull_into(*stream->controller()->get<JS::NonnullGCPtr<ReadableByteStreamController>>(), view, read_into_request);
  893. }
  894. }
  895. // https://streams.spec.whatwg.org/#abstract-opdef-readablestreamdefaultreaderrelease
  896. WebIDL::ExceptionOr<void> readable_stream_default_reader_release(ReadableStreamDefaultReader& reader)
  897. {
  898. auto& realm = reader.realm();
  899. // 1. Perform ! ReadableStreamReaderGenericRelease(reader).
  900. TRY(readable_stream_reader_generic_release(reader));
  901. // 2. Let e be a new TypeError exception.
  902. auto exception = JS::TypeError::create(realm, "Reader has been released"sv);
  903. // 3. Perform ! ReadableStreamDefaultReaderErrorReadRequests(reader, e).
  904. readable_stream_default_reader_error_read_requests(reader, exception);
  905. return {};
  906. }
  907. // https://streams.spec.whatwg.org/#abstract-opdef-readablestreambyobreaderrelease
  908. void readable_stream_byob_reader_release(ReadableStreamBYOBReader& reader)
  909. {
  910. auto& realm = reader.realm();
  911. // 1. Perform ! ReadableStreamReaderGenericRelease(reader).
  912. MUST(readable_stream_reader_generic_release(reader));
  913. // 2. Let e be a new TypeError exception.
  914. auto exception = JS::TypeError::create(realm, "Reader has been released"sv);
  915. // 3. Perform ! ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e).
  916. readable_stream_byob_reader_error_read_into_requests(reader, exception);
  917. }
  918. // https://streams.spec.whatwg.org/#set-up-readable-stream-default-reader
  919. WebIDL::ExceptionOr<void> set_up_readable_stream_default_reader(ReadableStreamDefaultReader& reader, ReadableStream& stream)
  920. {
  921. // 1. If ! IsReadableStreamLocked(stream) is true, throw a TypeError exception.
  922. if (is_readable_stream_locked(stream))
  923. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot create stream reader for a locked stream"sv };
  924. // 2. Perform ! ReadableStreamReaderGenericInitialize(reader, stream).
  925. // 3. Set reader.[[readRequests]] to a new empty list.
  926. readable_stream_reader_generic_initialize(ReadableStreamReader { reader }, stream);
  927. return {};
  928. }
  929. // https://streams.spec.whatwg.org/#set-up-readable-stream-byob-reader
  930. WebIDL::ExceptionOr<void> set_up_readable_stream_byob_reader(ReadableStreamBYOBReader& reader, ReadableStream& stream)
  931. {
  932. // 1. If ! IsReadableStreamLocked(stream) is true, throw a TypeError exception.
  933. if (is_readable_stream_locked(stream))
  934. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot create stream reader for a locked stream"sv };
  935. // 2. If stream.[[controller]] does not implement ReadableByteStreamController, throw a TypeError exception.
  936. if (!stream.controller()->has<JS::NonnullGCPtr<ReadableByteStreamController>>())
  937. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "BYOB reader cannot set up reader from non-byte stream"sv };
  938. // 3. Perform ! ReadableStreamReaderGenericInitialize(reader, stream).
  939. readable_stream_reader_generic_initialize(ReadableStreamReader { reader }, stream);
  940. // 4. Set reader.[[readIntoRequests]] to a new empty list.
  941. reader.read_into_requests().clear();
  942. return {};
  943. }
  944. // https://streams.spec.whatwg.org/#readable-stream-default-controller-close
  945. void readable_stream_default_controller_close(ReadableStreamDefaultController& controller)
  946. {
  947. // 1. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) is false, return.
  948. if (!readable_stream_default_controller_can_close_or_enqueue(controller))
  949. return;
  950. // 2. Let stream be controller.[[stream]].
  951. auto stream = controller.stream();
  952. // 3. Set controller.[[closeRequested]] to true.
  953. controller.set_close_requested(true);
  954. // 4. If controller.[[queue]] is empty,
  955. if (controller.queue().is_empty()) {
  956. // 1. Perform ! ReadableStreamDefaultControllerClearAlgorithms(controller).
  957. readable_stream_default_controller_clear_algorithms(controller);
  958. // 2. Perform ! ReadableStreamClose(stream).
  959. readable_stream_close(*stream);
  960. }
  961. }
  962. // https://streams.spec.whatwg.org/#rs-default-controller-has-backpressure
  963. bool readable_stream_default_controller_has_backpressure(ReadableStreamDefaultController& controller)
  964. {
  965. // 1. If ! ReadableStreamDefaultControllerShouldCallPull(controller) is true, return false.
  966. if (readable_stream_default_controller_should_call_pull(controller))
  967. return false;
  968. // 2. Otherwise, return true.
  969. return true;
  970. }
  971. // https://streams.spec.whatwg.org/#readable-stream-default-controller-enqueue
  972. WebIDL::ExceptionOr<void> readable_stream_default_controller_enqueue(ReadableStreamDefaultController& controller, JS::Value chunk)
  973. {
  974. auto& vm = controller.vm();
  975. // 1. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) is false, return.
  976. if (!readable_stream_default_controller_can_close_or_enqueue(controller))
  977. return {};
  978. // 2. Let stream be controller.[[stream]].
  979. auto stream = controller.stream();
  980. // 3. If ! IsReadableStreamLocked(stream) is true and ! ReadableStreamGetNumReadRequests(stream) > 0, perform ! ReadableStreamFulfillReadRequest(stream, chunk, false).
  981. if (is_readable_stream_locked(*stream) && readable_stream_get_num_read_requests(*stream) > 0) {
  982. readable_stream_fulfill_read_request(*stream, chunk, false);
  983. }
  984. // 4. Otherwise,
  985. else {
  986. // 1. Let result be the result of performing controller.[[strategySizeAlgorithm]], passing in chunk, and interpreting the result as a completion record.
  987. auto result = controller.strategy_size_algorithm()->function()(chunk);
  988. // 2. If result is an abrupt completion,
  989. if (result.is_abrupt()) {
  990. // 1. Perform ! ReadableStreamDefaultControllerError(controller, result.[[Value]]).
  991. readable_stream_default_controller_error(controller, result.value().value());
  992. // 2. Return result.
  993. return result;
  994. }
  995. // 3. Let chunkSize be result.[[Value]].
  996. auto chunk_size = result.release_value().release_value();
  997. // 4. Let enqueueResult be EnqueueValueWithSize(controller, chunk, chunkSize).
  998. auto enqueue_result = enqueue_value_with_size(controller, chunk, chunk_size);
  999. // 5. If enqueueResult is an abrupt completion,
  1000. if (enqueue_result.is_error()) {
  1001. auto throw_completion = Bindings::throw_dom_exception_if_needed(vm, [&] { return enqueue_result; }).throw_completion();
  1002. // 1. Perform ! ReadableStreamDefaultControllerError(controller, enqueueResult.[[Value]]).
  1003. readable_stream_default_controller_error(controller, throw_completion.value().value());
  1004. // 2. Return enqueueResult.
  1005. // Note: We need to return the throw_completion object here, as enqueue needs to throw the same object that the controller is errored with
  1006. return throw_completion;
  1007. }
  1008. }
  1009. // 5. Perform ! ReadableStreamDefaultControllerCallPullIfNeeded(controller).
  1010. return readable_stream_default_controller_can_pull_if_needed(controller);
  1011. }
  1012. // https://streams.spec.whatwg.org/#readable-stream-default-controller-call-pull-if-needed
  1013. WebIDL::ExceptionOr<void> readable_stream_default_controller_can_pull_if_needed(ReadableStreamDefaultController& controller)
  1014. {
  1015. // 1. Let shouldPull be ! ReadableStreamDefaultControllerShouldCallPull(controller).
  1016. auto should_pull = readable_stream_default_controller_should_call_pull(controller);
  1017. // 2. If shouldPull is false, return.
  1018. if (!should_pull)
  1019. return {};
  1020. // 3. If controller.[[pulling]] is true,
  1021. if (controller.pulling()) {
  1022. // 1. Set controller.[[pullAgain]] to true.
  1023. controller.set_pull_again(true);
  1024. // 2. Return.
  1025. return {};
  1026. }
  1027. // 4. Assert: controller.[[pullAgain]] is false.
  1028. VERIFY(!controller.pull_again());
  1029. // 5. Set controller.[[pulling]] to true.
  1030. controller.set_pulling(true);
  1031. // 6. Let pullPromise be the result of performing controller.[[pullAlgorithm]].
  1032. auto pull_promise = TRY(controller.pull_algorithm()->function()());
  1033. // 7. Upon fulfillment of pullPromise,
  1034. WebIDL::upon_fulfillment(*pull_promise, [&](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  1035. // 1. Set controller.[[pulling]] to false.
  1036. controller.set_pulling(false);
  1037. // 2. If controller.[[pullAgain]] is true,
  1038. if (controller.pull_again()) {
  1039. // 1. Set controller.[[pullAgain]] to false.
  1040. controller.set_pull_again(false);
  1041. // 2. Perform ! ReadableStreamDefaultControllerCallPullIfNeeded(controller).
  1042. TRY(readable_stream_default_controller_can_pull_if_needed(controller));
  1043. }
  1044. return JS::js_undefined();
  1045. });
  1046. // 8. Upon rejection of pullPromise with reason e,
  1047. WebIDL::upon_rejection(*pull_promise, [&](auto const& e) -> WebIDL::ExceptionOr<JS::Value> {
  1048. // 1. Perform ! ReadableStreamDefaultControllerError(controller, e).
  1049. readable_stream_default_controller_error(controller, e);
  1050. return JS::js_undefined();
  1051. });
  1052. return {};
  1053. }
  1054. // https://streams.spec.whatwg.org/#readable-stream-default-controller-should-call-pull
  1055. bool readable_stream_default_controller_should_call_pull(ReadableStreamDefaultController& controller)
  1056. {
  1057. // 1. Let stream be controller.[[stream]].
  1058. auto stream = controller.stream();
  1059. // 2. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) is false, return false.
  1060. if (!readable_stream_default_controller_can_close_or_enqueue(controller))
  1061. return false;
  1062. // 3. If controller.[[started]] is false, return false.
  1063. if (!controller.started())
  1064. return false;
  1065. // 4. If ! IsReadableStreamLocked(stream) is true and ! ReadableStreamGetNumReadRequests(stream) > 0, return true.
  1066. if (is_readable_stream_locked(*stream) && readable_stream_get_num_read_requests(*stream) > 0)
  1067. return true;
  1068. // 5. Let desiredSize be ! ReadableStreamDefaultControllerGetDesiredSize(controller).
  1069. auto desired_size = readable_stream_default_controller_get_desired_size(controller);
  1070. // 6. Assert: desiredSize is not null.
  1071. VERIFY(desired_size.has_value());
  1072. // 7. If desiredSize > 0, return true.
  1073. if (desired_size.release_value() > 0.0)
  1074. return true;
  1075. // 8. Return false.
  1076. return false;
  1077. }
  1078. // https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollergetbyobrequest
  1079. JS::GCPtr<ReadableStreamBYOBRequest> readable_byte_stream_controller_get_byob_request(JS::NonnullGCPtr<ReadableByteStreamController> controller)
  1080. {
  1081. auto& vm = controller->vm();
  1082. auto& realm = controller->realm();
  1083. // 1. If controller.[[byobRequest]] is null and controller.[[pendingPullIntos]] is not empty,
  1084. if (!controller->raw_byob_request() && !controller->pending_pull_intos().is_empty()) {
  1085. // 1. Let firstDescriptor be controller.[[pendingPullIntos]][0].
  1086. auto const& first_descriptor = controller->pending_pull_intos().first();
  1087. // 2. Let view be ! Construct(%Uint8Array%, « firstDescriptor’s buffer, firstDescriptor’s byte offset + firstDescriptor’s bytes filled, firstDescriptor’s byte length − firstDescriptor’s bytes filled »).
  1088. auto view = MUST(JS::construct(vm, *realm.intrinsics().uint8_array_constructor(), first_descriptor.buffer, JS::Value(first_descriptor.byte_offset + first_descriptor.bytes_filled), JS::Value(first_descriptor.byte_length - first_descriptor.bytes_filled)));
  1089. // 3. Let byobRequest be a new ReadableStreamBYOBRequest.
  1090. auto byob_request = realm.heap().allocate<ReadableStreamBYOBRequest>(realm, realm);
  1091. // 4. Set byobRequest.[[controller]] to controller.
  1092. byob_request->set_controller(controller);
  1093. // 5. Set byobRequest.[[view]] to view.
  1094. auto array_buffer_view = vm.heap().allocate<WebIDL::ArrayBufferView>(realm, view);
  1095. byob_request->set_view(array_buffer_view);
  1096. // 6. Set controller.[[byobRequest]] to byobRequest.
  1097. controller->set_byob_request(byob_request);
  1098. }
  1099. // 2. Return controller.[[byobRequest]].
  1100. return controller->raw_byob_request();
  1101. }
  1102. // https://streams.spec.whatwg.org/#readable-stream-default-controller-clear-algorithms
  1103. void readable_stream_default_controller_clear_algorithms(ReadableStreamDefaultController& controller)
  1104. {
  1105. // 1. Set controller.[[pullAlgorithm]] to undefined.
  1106. controller.set_pull_algorithm({});
  1107. // 2. Set controller.[[cancelAlgorithm]] to undefined.
  1108. controller.set_cancel_algorithm({});
  1109. // 3. Set controller.[[strategySizeAlgorithm]] to undefined.
  1110. controller.set_strategy_size_algorithm({});
  1111. }
  1112. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-respond-in-readable-state
  1113. WebIDL::ExceptionOr<void> readable_byte_stream_controller_respond_in_readable_state(ReadableByteStreamController& controller, u64 bytes_written, PullIntoDescriptor& pull_into_descriptor)
  1114. {
  1115. // 1. Assert: pullIntoDescriptor’s bytes filled + bytesWritten ≤ pullIntoDescriptor’s byte length.
  1116. VERIFY(pull_into_descriptor.bytes_filled + bytes_written <= pull_into_descriptor.byte_length);
  1117. // 2. Perform ! ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor).
  1118. readable_byte_stream_controller_fill_head_pull_into_descriptor(controller, bytes_written, pull_into_descriptor);
  1119. // 3. If pullIntoDescriptor’s reader type is "none",
  1120. if (pull_into_descriptor.reader_type == ReaderType::None) {
  1121. // 1. Perform ? ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor).
  1122. TRY(readable_byte_stream_controller_enqueue_detached_pull_into_queue(controller, pull_into_descriptor));
  1123. // 2. Perform ! ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller).
  1124. readable_byte_stream_controller_process_pull_into_descriptors_using_queue(controller);
  1125. // 3. Return.
  1126. return {};
  1127. }
  1128. // 4. If pullIntoDescriptor’s bytes filled < pullIntoDescriptor’s minimum fill, return.
  1129. // FIXME: Support minimum fill.
  1130. if (pull_into_descriptor.bytes_filled < pull_into_descriptor.element_size)
  1131. return {};
  1132. // NOTE: A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head of the queue, so the underlying source can keep filling it.
  1133. // 5. Perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).
  1134. // NOTE: We need to take a copy of pull_into_descriptor here as the shift destroys the pull into descriptor we are given.
  1135. auto pull_into_descriptor_copy = readable_byte_stream_controller_shift_pending_pull_into(controller);
  1136. // 6. Let remainderSize be the remainder after dividing pullIntoDescriptor’s bytes filled by pullIntoDescriptor’s element size.
  1137. auto remainder_size = pull_into_descriptor_copy.bytes_filled % pull_into_descriptor_copy.element_size;
  1138. // 7. If remainderSize > 0,
  1139. if (remainder_size > 0) {
  1140. // 1. Let end be pullIntoDescriptor’s byte offset + pullIntoDescriptor’s bytes filled.
  1141. auto end = pull_into_descriptor_copy.byte_offset + pull_into_descriptor_copy.bytes_filled;
  1142. // 2. Perform ? ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor’s buffer, end − remainderSize, remainderSize).
  1143. TRY(readable_byte_stream_controller_enqueue_cloned_chunk_to_queue(controller, *pull_into_descriptor_copy.buffer, end - remainder_size, remainder_size));
  1144. }
  1145. // 8. Set pullIntoDescriptor’s bytes filled to pullIntoDescriptor’s bytes filled − remainderSize.
  1146. pull_into_descriptor_copy.bytes_filled -= remainder_size;
  1147. // 9. Perform ! ReadableByteStreamControllerCommitPullIntoDescriptor(controller.[[stream]], pullIntoDescriptor).
  1148. readable_byte_stream_controller_commit_pull_into_descriptor(*controller.stream(), pull_into_descriptor_copy);
  1149. return {};
  1150. }
  1151. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-respond-in-closed-state
  1152. void readable_byte_stream_controller_respond_in_closed_state(ReadableByteStreamController& controller, PullIntoDescriptor& first_descriptor)
  1153. {
  1154. // 1. Assert: the remainder after dividing firstDescriptor’s bytes filled by firstDescriptor’s element size is 0.
  1155. VERIFY(first_descriptor.bytes_filled % first_descriptor.element_size == 0);
  1156. // 2. If firstDescriptor’s reader type is "none", perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).
  1157. if (first_descriptor.reader_type == ReaderType::None)
  1158. readable_byte_stream_controller_shift_pending_pull_into(controller);
  1159. // 3. Let stream be controller.[[stream]].
  1160. auto& stream = *controller.stream();
  1161. // 4. If ! ReadableStreamHasBYOBReader(stream) is true,
  1162. if (readable_stream_has_default_reader(stream)) {
  1163. // 1. While ! ReadableStreamGetNumReadIntoRequests(stream) > 0,
  1164. while (readable_stream_get_num_read_requests(stream) > 0) {
  1165. // 1. Let pullIntoDescriptor be ! ReadableByteStreamControllerShiftPendingPullInto(controller).
  1166. auto pull_into_descriptor = readable_byte_stream_controller_shift_pending_pull_into(controller);
  1167. // 2. Perform ! ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor).
  1168. readable_byte_stream_controller_commit_pull_into_descriptor(stream, pull_into_descriptor);
  1169. }
  1170. }
  1171. }
  1172. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-respond-internal
  1173. WebIDL::ExceptionOr<void> readable_byte_stream_controller_respond_internal(ReadableByteStreamController& controller, u64 bytes_written)
  1174. {
  1175. // 1. Let firstDescriptor be controller.[[pendingPullIntos]][0].
  1176. auto& first_descriptor = controller.pending_pull_intos().first();
  1177. // 2. Assert: ! CanTransferArrayBuffer(firstDescriptor’s buffer) is true.
  1178. VERIFY(can_transfer_array_buffer(*first_descriptor.buffer));
  1179. // 3. Perform ! ReadableByteStreamControllerInvalidateBYOBRequest(controller).
  1180. readable_byte_stream_controller_invalidate_byob_request(controller);
  1181. // 4. Let state be controller.[[stream]].[[state]].
  1182. auto state = controller.stream()->state();
  1183. // 5. If state is "closed",
  1184. if (state == ReadableStream::State::Closed) {
  1185. // 1. Assert: bytesWritten is 0.
  1186. VERIFY(bytes_written == 0);
  1187. // 2. Perform ! ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor).
  1188. readable_byte_stream_controller_respond_in_closed_state(controller, first_descriptor);
  1189. }
  1190. // 6. Otherwise,
  1191. else {
  1192. // 1. Assert: state is "readable".
  1193. VERIFY(state == ReadableStream::State::Readable);
  1194. // 2. Assert: bytesWritten > 0.
  1195. VERIFY(bytes_written > 0);
  1196. // 3. Perform ? ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor).
  1197. TRY(readable_byte_stream_controller_respond_in_readable_state(controller, bytes_written, first_descriptor));
  1198. }
  1199. // 7. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
  1200. MUST(readable_byte_stream_controller_call_pull_if_needed(controller));
  1201. return {};
  1202. }
  1203. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-respond
  1204. WebIDL::ExceptionOr<void> readable_byte_stream_controller_respond(ReadableByteStreamController& controller, u64 bytes_written)
  1205. {
  1206. auto& realm = controller.realm();
  1207. // 1. Assert: controller.[[pendingPullIntos]] is not empty.
  1208. VERIFY(!controller.pending_pull_intos().is_empty());
  1209. // 2. Let firstDescriptor be controller.[[pendingPullIntos]][0].
  1210. auto& first_descriptor = controller.pending_pull_intos().first();
  1211. // 3. Let state be controller.[[stream]].[[state]].
  1212. auto state = controller.stream()->state();
  1213. // 4. If state is "closed",
  1214. if (state == ReadableStream::State::Closed) {
  1215. // 1. If bytesWritten is not 0, throw a TypeError exception.
  1216. if (bytes_written != 0)
  1217. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Bytes written is not zero for closed stream"sv };
  1218. }
  1219. // 5. Otherwise,
  1220. else {
  1221. // 1. Assert: state is "readable".
  1222. VERIFY(state == ReadableStream::State::Readable);
  1223. // 2. If bytesWritten is 0, throw a TypeError exception.
  1224. if (bytes_written == 0)
  1225. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Bytes written is zero for stream which is not closed"sv };
  1226. // 3. If firstDescriptor’s bytes filled + bytesWritten > firstDescriptor’s byte length, throw a RangeError exception.
  1227. if (first_descriptor.bytes_filled + bytes_written > first_descriptor.byte_length)
  1228. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Bytes written is greater than the pull requests byte length"sv };
  1229. }
  1230. // 6. Set firstDescriptor’s buffer to ! TransferArrayBuffer(firstDescriptor’s buffer).
  1231. first_descriptor.buffer = MUST(transfer_array_buffer(realm, *first_descriptor.buffer));
  1232. // 7. Perform ? ReadableByteStreamControllerRespondInternal(controller, bytesWritten).
  1233. return readable_byte_stream_controller_respond_internal(controller, bytes_written);
  1234. }
  1235. // https://streams.spec.whatwg.org/#readable-stream-default-controller-error
  1236. void readable_stream_default_controller_error(ReadableStreamDefaultController& controller, JS::Value error)
  1237. {
  1238. // 1. Let stream be controller.[[stream]].
  1239. auto stream = controller.stream();
  1240. // 2. If stream.[[state]] is not "readable", return.
  1241. if (!stream->is_readable())
  1242. return;
  1243. // 3. Perform ! ResetQueue(controller).
  1244. reset_queue(controller);
  1245. // 4. Perform ! ReadableStreamDefaultControllerClearAlgorithms(controller).
  1246. readable_stream_default_controller_clear_algorithms(controller);
  1247. // 5. Perform ! ReadableStreamError(stream, e).
  1248. readable_stream_error(*stream, error);
  1249. }
  1250. // https://streams.spec.whatwg.org/#readable-stream-default-controller-get-desired-size
  1251. Optional<double> readable_stream_default_controller_get_desired_size(ReadableStreamDefaultController& controller)
  1252. {
  1253. auto stream = controller.stream();
  1254. // 1. Let state be controller.[[stream]].[[state]].
  1255. // 2. If state is "errored", return null.
  1256. if (stream->is_errored())
  1257. return {};
  1258. // 3. If state is "closed", return 0.
  1259. if (stream->is_closed())
  1260. return 0.0;
  1261. // 4. Return controller.[[strategyHWM]] − controller.[[queueTotalSize]].
  1262. return controller.strategy_hwm() - controller.queue_total_size();
  1263. }
  1264. // https://streams.spec.whatwg.org/#readable-stream-default-controller-can-close-or-enqueue
  1265. bool readable_stream_default_controller_can_close_or_enqueue(ReadableStreamDefaultController& controller)
  1266. {
  1267. // 1. Let state be controller.[[stream]].[[state]].
  1268. // 2. If controller.[[closeRequested]] is false and state is "readable", return true.
  1269. // 3. Otherwise, return false.
  1270. return !controller.close_requested() && controller.stream()->is_readable();
  1271. }
  1272. // https://streams.spec.whatwg.org/#set-up-readable-stream-default-controller
  1273. WebIDL::ExceptionOr<void> set_up_readable_stream_default_controller(ReadableStream& stream, ReadableStreamDefaultController& controller, JS::NonnullGCPtr<StartAlgorithm> start_algorithm, JS::NonnullGCPtr<PullAlgorithm> pull_algorithm, JS::NonnullGCPtr<CancelAlgorithm> cancel_algorithm, double high_water_mark, JS::NonnullGCPtr<SizeAlgorithm> size_algorithm)
  1274. {
  1275. auto& realm = stream.realm();
  1276. // 1. Assert: stream.[[controller]] is undefined.
  1277. VERIFY(!stream.controller().has_value());
  1278. // 2. Set controller.[[stream]] to stream.
  1279. controller.set_stream(stream);
  1280. // 3. Perform ! ResetQueue(controller).
  1281. reset_queue(controller);
  1282. // 4. Set controller.[[started]], controller.[[closeRequested]], controller.[[pullAgain]], and controller.[[pulling]] to false.
  1283. controller.set_started(false);
  1284. controller.set_close_requested(false);
  1285. controller.set_pull_again(false);
  1286. controller.set_pulling(false);
  1287. // 5. Set controller.[[strategySizeAlgorithm]] to sizeAlgorithm and controller.[[strategyHWM]] to highWaterMark.
  1288. controller.set_strategy_size_algorithm(size_algorithm);
  1289. controller.set_strategy_hwm(high_water_mark);
  1290. // 6. Set controller.[[pullAlgorithm]] to pullAlgorithm.
  1291. controller.set_pull_algorithm(pull_algorithm);
  1292. // 7. Set controller.[[cancelAlgorithm]] to cancelAlgorithm.
  1293. controller.set_cancel_algorithm(cancel_algorithm);
  1294. // 8. Set stream.[[controller]] to controller.
  1295. stream.set_controller(ReadableStreamController { controller });
  1296. // 9. Let startResult be the result of performing startAlgorithm. (This might throw an exception.)
  1297. auto start_result = TRY(start_algorithm->function()());
  1298. // 10. Let startPromise be a promise resolved with startResult.
  1299. auto start_promise = WebIDL::create_resolved_promise(realm, start_result);
  1300. // 11. Upon fulfillment of startPromise,
  1301. WebIDL::upon_fulfillment(start_promise, [&](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  1302. // 1. Set controller.[[started]] to true.
  1303. controller.set_started(true);
  1304. // 2. Assert: controller.[[pulling]] is false.
  1305. VERIFY(!controller.pulling());
  1306. // 3. Assert: controller.[[pullAgain]] is false.
  1307. VERIFY(!controller.pull_again());
  1308. // 4. Perform ! ReadableStreamDefaultControllerCallPullIfNeeded(controller).
  1309. TRY(readable_stream_default_controller_can_pull_if_needed(controller));
  1310. return JS::js_undefined();
  1311. });
  1312. // 12. Upon rejection of startPromise with reason r,
  1313. WebIDL::upon_rejection(start_promise, [&](auto const& r) -> WebIDL::ExceptionOr<JS::Value> {
  1314. // 1. Perform ! ReadableStreamDefaultControllerError(controller, r).
  1315. readable_stream_default_controller_error(controller, r);
  1316. return JS::js_undefined();
  1317. });
  1318. return {};
  1319. }
  1320. // https://streams.spec.whatwg.org/#set-up-readable-stream-default-controller-from-underlying-source
  1321. WebIDL::ExceptionOr<void> set_up_readable_stream_default_controller_from_underlying_source(ReadableStream& stream, JS::Value underlying_source_value, UnderlyingSource underlying_source, double high_water_mark, JS::NonnullGCPtr<SizeAlgorithm> size_algorithm)
  1322. {
  1323. auto& realm = stream.realm();
  1324. // 1. Let controller be a new ReadableStreamDefaultController.
  1325. auto controller = stream.heap().allocate<ReadableStreamDefaultController>(realm, realm);
  1326. // 2. Let startAlgorithm be an algorithm that returns undefined.
  1327. auto start_algorithm = JS::create_heap_function(realm.heap(), []() -> WebIDL::ExceptionOr<JS::Value> {
  1328. return JS::js_undefined();
  1329. });
  1330. // 3. Let pullAlgorithm be an algorithm that returns a promise resolved with undefined.
  1331. auto pull_algorithm = JS::create_heap_function(realm.heap(), [&realm]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  1332. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  1333. });
  1334. // 4. Let cancelAlgorithm be an algorithm that returns a promise resolved with undefined.
  1335. auto cancel_algorithm = JS::create_heap_function(realm.heap(), [&realm](JS::Value) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  1336. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  1337. });
  1338. // 5. If underlyingSourceDict["start"] exists, then set startAlgorithm to an algorithm which returns the result of invoking underlyingSourceDict["start"] with argument list « controller » and callback this value underlyingSource.
  1339. if (underlying_source.start) {
  1340. start_algorithm = JS::create_heap_function(realm.heap(), [controller, underlying_source_value, callback = underlying_source.start]() -> WebIDL::ExceptionOr<JS::Value> {
  1341. // Note: callback does not return a promise, so invoke_callback may return an abrupt completion
  1342. return TRY(WebIDL::invoke_callback(*callback, underlying_source_value, controller)).release_value();
  1343. });
  1344. }
  1345. // 6. If underlyingSourceDict["pull"] exists, then set pullAlgorithm to an algorithm which returns the result of invoking underlyingSourceDict["pull"] with argument list « controller » and callback this value underlyingSource.
  1346. if (underlying_source.pull) {
  1347. pull_algorithm = JS::create_heap_function(realm.heap(), [&realm, controller, underlying_source_value, callback = underlying_source.pull]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  1348. // Note: callback return a promise, so invoke_callback will never return an abrupt completion
  1349. auto result = MUST_OR_THROW_OOM(WebIDL::invoke_callback(*callback, underlying_source_value, controller)).release_value();
  1350. return WebIDL::create_resolved_promise(realm, result);
  1351. });
  1352. }
  1353. // 7. If underlyingSourceDict["cancel"] exists, then set cancelAlgorithm to an algorithm which takes an argument reason and returns the result of invoking underlyingSourceDict["cancel"] with argument list « reason » and callback this value underlyingSource.
  1354. if (underlying_source.cancel) {
  1355. cancel_algorithm = JS::create_heap_function(realm.heap(), [&realm, underlying_source_value, callback = underlying_source.cancel](JS::Value reason) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  1356. // Note: callback return a promise, so invoke_callback will never return an abrupt completion
  1357. auto result = MUST_OR_THROW_OOM(WebIDL::invoke_callback(*callback, underlying_source_value, reason)).release_value();
  1358. return WebIDL::create_resolved_promise(realm, result);
  1359. });
  1360. }
  1361. // 8. Perform ? SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm).
  1362. return set_up_readable_stream_default_controller(stream, controller, start_algorithm, pull_algorithm, cancel_algorithm, high_water_mark, size_algorithm);
  1363. }
  1364. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-call-pull-if-needed
  1365. WebIDL::ExceptionOr<void> readable_byte_stream_controller_call_pull_if_needed(ReadableByteStreamController& controller)
  1366. {
  1367. // 1. Let shouldPull be ! ReadableByteStreamControllerShouldCallPull(controller).
  1368. auto should_pull = readable_byte_stream_controller_should_call_pull(controller);
  1369. // 2. If shouldPull is false, return.
  1370. if (!should_pull)
  1371. return {};
  1372. // 3. If controller.[[pulling]] is true,
  1373. if (controller.pulling()) {
  1374. // 1. Set controller.[[pullAgain]] to true.
  1375. controller.set_pull_again(true);
  1376. // 2. Return.
  1377. return {};
  1378. }
  1379. // 4. Assert: controller.[[pullAgain]] is false.
  1380. VERIFY(!controller.pull_again());
  1381. // 5. Set controller.[[pulling]] to true.
  1382. controller.set_pulling(true);
  1383. // 6. Let pullPromise be the result of performing controller.[[pullAlgorithm]].
  1384. auto pull_promise = TRY(controller.pull_algorithm()->function()());
  1385. // 7. Upon fulfillment of pullPromise,
  1386. WebIDL::upon_fulfillment(*pull_promise, [&](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  1387. // 1. Set controller.[[pulling]] to false.
  1388. controller.set_pulling(false);
  1389. // 2. If controller.[[pullAgain]] is true,
  1390. if (controller.pull_again()) {
  1391. // 1. Set controller.[[pullAgain]] to false.
  1392. controller.set_pull_again(false);
  1393. // 2. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
  1394. TRY(readable_byte_stream_controller_call_pull_if_needed(controller));
  1395. }
  1396. return JS::js_undefined();
  1397. });
  1398. // 8. Upon rejection of pullPromise with reason e,
  1399. WebIDL::upon_rejection(*pull_promise, [&](auto const& error) -> WebIDL::ExceptionOr<JS::Value> {
  1400. // 1. Perform ! ReadableByteStreamControllerError(controller, e).
  1401. readable_byte_stream_controller_error(controller, error);
  1402. return JS::js_undefined();
  1403. });
  1404. return {};
  1405. }
  1406. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-clear-algorithms
  1407. void readable_byte_stream_controller_clear_algorithms(ReadableByteStreamController& controller)
  1408. {
  1409. // 1. Set controller.[[pullAlgorithm]] to undefined.
  1410. controller.set_pull_algorithm({});
  1411. // 2. Set controller.[[cancelAlgorithm]] to undefined.
  1412. controller.set_cancel_algorithm({});
  1413. }
  1414. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-clear-pending-pull-intos
  1415. void readable_byte_stream_controller_clear_pending_pull_intos(ReadableByteStreamController& controller)
  1416. {
  1417. // 1. Perform ! ReadableByteStreamControllerInvalidateBYOBRequest(controller).
  1418. readable_byte_stream_controller_invalidate_byob_request(controller);
  1419. // 2. Set controller.[[pendingPullIntos]] to a new empty list.
  1420. controller.pending_pull_intos().clear();
  1421. }
  1422. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-close
  1423. WebIDL::ExceptionOr<void> readable_byte_stream_controller_close(ReadableByteStreamController& controller)
  1424. {
  1425. auto& realm = controller.realm();
  1426. // 1. Let stream be controller.[[stream]].
  1427. auto stream = controller.stream();
  1428. // 2. If controller.[[closeRequested]] is true or stream.[[state]] is not "readable", return.
  1429. if (controller.close_requested() || stream->state() != ReadableStream::State::Readable)
  1430. return {};
  1431. // 3. If controller.[[queueTotalSize]] > 0,
  1432. if (controller.queue_total_size() > 0.0) {
  1433. // 1. Set controller.[[closeRequested]] to true.
  1434. controller.set_close_requested(true);
  1435. // 2. Return.
  1436. return {};
  1437. }
  1438. // 4. If controller.[[pendingPullIntos]] is not empty,
  1439. if (!controller.pending_pull_intos().is_empty()) {
  1440. // 1. Let firstPendingPullInto be controller.[[pendingPullIntos]][0].
  1441. auto& first_pending_pull_into = controller.pending_pull_intos().first();
  1442. // 2. If firstPendingPullInto’s bytes filled > 0,
  1443. if (first_pending_pull_into.bytes_filled > 0) {
  1444. // 1. Let e be a new TypeError exception.
  1445. auto error = JS::TypeError::create(realm, "Cannot close controller in the middle of processing a write request"sv);
  1446. // 2. Perform ! ReadableByteStreamControllerError(controller, e).
  1447. readable_byte_stream_controller_error(controller, error);
  1448. // 3. Throw e.
  1449. return JS::throw_completion(error);
  1450. }
  1451. }
  1452. // 5. Perform ! ReadableByteStreamControllerClearAlgorithms(controller).
  1453. readable_byte_stream_controller_clear_algorithms(controller);
  1454. // 6. Perform ! ReadableStreamClose(stream).
  1455. readable_stream_close(*stream);
  1456. return {};
  1457. }
  1458. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-error
  1459. void readable_byte_stream_controller_error(ReadableByteStreamController& controller, JS::Value error)
  1460. {
  1461. // 1. Let stream be controller.[[stream]].
  1462. auto stream = controller.stream();
  1463. // 2. If stream.[[state]] is not "readable", return.
  1464. if (stream->state() != ReadableStream::State::Readable)
  1465. return;
  1466. // 3. Perform ! ReadableByteStreamControllerClearPendingPullIntos(controller).
  1467. readable_byte_stream_controller_clear_pending_pull_intos(controller);
  1468. // 4. Perform ! ResetQueue(controller).
  1469. reset_queue(controller);
  1470. // 5. Perform ! ReadableByteStreamControllerClearAlgorithms(controller).
  1471. readable_byte_stream_controller_clear_algorithms(controller);
  1472. // 6. Perform ! ReadableStreamError(stream, e).
  1473. readable_stream_error(*stream, error);
  1474. }
  1475. // https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollerfillreadrequestfromqueue
  1476. WebIDL::ExceptionOr<void> readable_byte_stream_controller_fill_read_request_from_queue(ReadableByteStreamController& controller, JS::NonnullGCPtr<ReadRequest> read_request)
  1477. {
  1478. auto& vm = controller.vm();
  1479. auto& realm = controller.realm();
  1480. // 1. Assert: controller.[[queueTotalSize]] > 0.
  1481. VERIFY(controller.queue_total_size() > 0.0);
  1482. // 2. Let entry be controller.[[queue]][0].
  1483. // 3. Remove entry from controller.[[queue]].
  1484. auto entry = controller.queue().take_first();
  1485. // 4. Set controller.[[queueTotalSize]] to controller.[[queueTotalSize]] − entry’s byte length.
  1486. controller.set_queue_total_size(controller.queue_total_size() - entry.byte_length);
  1487. // 5. Perform ! ReadableByteStreamControllerHandleQueueDrain(controller).
  1488. TRY(readable_byte_stream_controller_handle_queue_drain(controller));
  1489. // 6. Let view be ! Construct(%Uint8Array%, « entry’s buffer, entry’s byte offset, entry’s byte length »).
  1490. auto view = MUST_OR_THROW_OOM(JS::construct(vm, *realm.intrinsics().uint8_array_constructor(), entry.buffer, JS::Value(entry.byte_offset), JS::Value(entry.byte_length)));
  1491. // 7. Perform readRequest’s chunk steps, given view.
  1492. read_request->on_chunk(view);
  1493. return {};
  1494. }
  1495. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-get-desired-size
  1496. Optional<double> readable_byte_stream_controller_get_desired_size(ReadableByteStreamController const& controller)
  1497. {
  1498. auto stream = controller.stream();
  1499. // 1. Let state be controller.[[stream]].[[state]].
  1500. // 2. If state is "errored", return null.
  1501. if (stream->is_errored())
  1502. return {};
  1503. // 3. If state is "closed", return 0.
  1504. if (stream->is_closed())
  1505. return 0.0;
  1506. // 4. Return controller.[[strategyHWM]] − controller.[[queueTotalSize]].
  1507. return controller.strategy_hwm() - controller.queue_total_size();
  1508. }
  1509. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-handle-queue-drain
  1510. WebIDL::ExceptionOr<void> readable_byte_stream_controller_handle_queue_drain(ReadableByteStreamController& controller)
  1511. {
  1512. // 1. Assert: controller.[[stream]].[[state]] is "readable".
  1513. VERIFY(controller.stream()->state() == ReadableStream::State::Readable);
  1514. // 2. If controller.[[queueTotalSize]] is 0 and controller.[[closeRequested]] is true,
  1515. if (controller.queue_total_size() == 0.0 && controller.close_requested()) {
  1516. // 1. Perform ! ReadableByteStreamControllerClearAlgorithms(controller).
  1517. readable_byte_stream_controller_clear_algorithms(controller);
  1518. // 2. Perform ! ReadableStreamClose(controller.[[stream]]).
  1519. readable_stream_close(*controller.stream());
  1520. }
  1521. // 3. Otherwise,
  1522. else {
  1523. // 1. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
  1524. TRY(readable_byte_stream_controller_call_pull_if_needed(controller));
  1525. }
  1526. return {};
  1527. }
  1528. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-invalidate-byob-request
  1529. void readable_byte_stream_controller_invalidate_byob_request(ReadableByteStreamController& controller)
  1530. {
  1531. // 1. If controller.[[byobRequest]] is null, return.
  1532. if (!controller.byob_request())
  1533. return;
  1534. // 2. Set controller.[[byobRequest]].[[controller]] to undefined.
  1535. controller.byob_request()->set_controller({});
  1536. // 3. Set controller.[[byobRequest]].[[view]] to null.
  1537. controller.byob_request()->set_view({});
  1538. // 4. Set controller.[[byobRequest]] to null.
  1539. controller.set_byob_request({});
  1540. }
  1541. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-error
  1542. bool readable_byte_stream_controller_should_call_pull(ReadableByteStreamController const& controller)
  1543. {
  1544. // 1. Let stream be controller.[[stream]].
  1545. auto stream = controller.stream();
  1546. // 2. If stream.[[state]] is not "readable", return false.
  1547. if (stream->state() != ReadableStream::State::Readable)
  1548. return false;
  1549. // 3. If controller.[[closeRequested]] is true, return false.
  1550. if (controller.close_requested())
  1551. return false;
  1552. // 4. If controller.[[started]] is false, return false.
  1553. if (!controller.started())
  1554. return false;
  1555. // 5. If ! ReadableStreamHasDefaultReader(stream) is true and ! ReadableStreamGetNumReadRequests(stream) > 0, return true.
  1556. if (readable_stream_has_default_reader(*stream) && readable_stream_get_num_read_requests(*stream) > 0)
  1557. return true;
  1558. // 6. If ! ReadableStreamHasBYOBReader(stream) is true and ! ReadableStreamGetNumReadIntoRequests(stream) > 0, return true.
  1559. if (readable_stream_has_byob_reader(*stream) && readable_stream_get_num_read_into_requests(*stream) > 0)
  1560. return true;
  1561. // 7. Let desiredSize be ! ReadableByteStreamControllerGetDesiredSize(controller).
  1562. auto desired_size = readable_byte_stream_controller_get_desired_size(controller);
  1563. // 8. Assert: desiredSize is not null.
  1564. VERIFY(desired_size.has_value());
  1565. // 9. If desiredSize > 0, return true.
  1566. if (*desired_size > 0.0)
  1567. return true;
  1568. // 10. Return false.
  1569. return false;
  1570. }
  1571. // https://streams.spec.whatwg.org/#create-readable-stream
  1572. WebIDL::ExceptionOr<JS::NonnullGCPtr<ReadableStream>> create_readable_stream(JS::Realm& realm, JS::NonnullGCPtr<StartAlgorithm> start_algorithm, JS::NonnullGCPtr<PullAlgorithm> pull_algorithm, JS::NonnullGCPtr<CancelAlgorithm> cancel_algorithm, Optional<double> high_water_mark, JS::GCPtr<SizeAlgorithm> size_algorithm)
  1573. {
  1574. // 1. If highWaterMark was not passed, set it to 1.
  1575. if (!high_water_mark.has_value())
  1576. high_water_mark = 1.0;
  1577. // 2. If sizeAlgorithm was not passed, set it to an algorithm that returns 1.
  1578. if (!size_algorithm)
  1579. size_algorithm = JS::create_heap_function(realm.heap(), [](JS::Value) { return JS::normal_completion(JS::Value(1)); });
  1580. // 3. Assert: ! IsNonNegativeNumber(highWaterMark) is true.
  1581. VERIFY(is_non_negative_number(JS::Value { *high_water_mark }));
  1582. // 4. Let stream be a new ReadableStream.
  1583. auto stream = realm.heap().allocate<ReadableStream>(realm, realm);
  1584. // 5. Perform ! InitializeReadableStream(stream).
  1585. initialize_readable_stream(*stream);
  1586. // 6. Let controller be a new ReadableStreamDefaultController.
  1587. auto controller = realm.heap().allocate<ReadableStreamDefaultController>(realm, realm);
  1588. // 7. Perform ? SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm).
  1589. TRY(set_up_readable_stream_default_controller(*stream, *controller, start_algorithm, pull_algorithm, cancel_algorithm, *high_water_mark, *size_algorithm));
  1590. // 8. Return stream.
  1591. return stream;
  1592. }
  1593. // https://streams.spec.whatwg.org/#abstract-opdef-createreadablebytestream
  1594. WebIDL::ExceptionOr<JS::NonnullGCPtr<ReadableStream>> create_readable_byte_stream(JS::Realm& realm, JS::NonnullGCPtr<StartAlgorithm> start_algorithm, JS::NonnullGCPtr<PullAlgorithm> pull_algorithm, JS::NonnullGCPtr<CancelAlgorithm> cancel_algorithm)
  1595. {
  1596. // 1. Let stream be a new ReadableStream.
  1597. auto stream = realm.heap().allocate<ReadableStream>(realm, realm);
  1598. // 2. Perform ! InitializeReadableStream(stream).
  1599. initialize_readable_stream(*stream);
  1600. // 3. Let controller be a new ReadableByteStreamController.
  1601. auto controller = realm.heap().allocate<ReadableByteStreamController>(realm, realm);
  1602. // 4. Perform ? SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined).
  1603. TRY(set_up_readable_byte_stream_controller(stream, controller, start_algorithm, pull_algorithm, cancel_algorithm, 0, JS::js_undefined()));
  1604. // 5. Return stream.
  1605. return stream;
  1606. }
  1607. // https://streams.spec.whatwg.org/#create-writable-stream
  1608. WebIDL::ExceptionOr<JS::NonnullGCPtr<WritableStream>> create_writable_stream(JS::Realm& realm, JS::NonnullGCPtr<StartAlgorithm> start_algorithm, JS::NonnullGCPtr<WriteAlgorithm> write_algorithm, JS::NonnullGCPtr<CloseAlgorithm> close_algorithm, JS::NonnullGCPtr<AbortAlgorithm> abort_algorithm, double high_water_mark, JS::NonnullGCPtr<SizeAlgorithm> size_algorithm)
  1609. {
  1610. // 1. Assert: ! IsNonNegativeNumber(highWaterMark) is true.
  1611. VERIFY(is_non_negative_number(JS::Value { high_water_mark }));
  1612. // 2. Let stream be a new WritableStream.
  1613. auto stream = realm.heap().allocate<WritableStream>(realm, realm);
  1614. // 3. Perform ! InitializeWritableStream(stream).
  1615. initialize_writable_stream(*stream);
  1616. // 4. Let controller be a new WritableStreamDefaultController.
  1617. auto controller = realm.heap().allocate<WritableStreamDefaultController>(realm, realm);
  1618. // 5. Perform ? SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm).
  1619. TRY(set_up_writable_stream_default_controller(*stream, *controller, move(start_algorithm), move(write_algorithm), move(close_algorithm), move(abort_algorithm), high_water_mark, move(size_algorithm)));
  1620. // 6. Return stream.
  1621. return stream;
  1622. }
  1623. // https://streams.spec.whatwg.org/#initialize-readable-stream
  1624. void initialize_readable_stream(ReadableStream& stream)
  1625. {
  1626. // 1. Set stream.[[state]] to "readable".
  1627. stream.set_state(ReadableStream::State::Readable);
  1628. // 2. Set stream.[[reader]] and stream.[[storedError]] to undefined.
  1629. stream.set_reader({});
  1630. stream.set_stored_error({});
  1631. // 3. Set stream.[[disturbed]] to false.
  1632. stream.set_disturbed(false);
  1633. }
  1634. // https://streams.spec.whatwg.org/#initialize-writable-stream
  1635. void initialize_writable_stream(WritableStream& stream)
  1636. {
  1637. // 1. Set stream.[[state]] to "writable".
  1638. stream.set_state(WritableStream::State::Writable);
  1639. // 2. Set stream.[[storedError]], stream.[[writer]], stream.[[controller]], stream.[[inFlightWriteRequest]],
  1640. // stream.[[closeRequest]], stream.[[inFlightCloseRequest]], and stream.[[pendingAbortRequest]] to undefined.
  1641. stream.set_stored_error(JS::js_undefined());
  1642. stream.set_writer({});
  1643. stream.set_controller({});
  1644. stream.set_in_flight_write_request({});
  1645. stream.set_close_request({});
  1646. stream.set_in_flight_close_request({});
  1647. stream.set_pending_abort_request({});
  1648. // 3. Set stream.[[writeRequests]] to a new empty list.
  1649. stream.write_requests().clear();
  1650. // 4. Set stream.[[backpressure]] to false.
  1651. stream.set_backpressure(false);
  1652. }
  1653. // https://streams.spec.whatwg.org/#acquire-writable-stream-default-writer
  1654. WebIDL::ExceptionOr<JS::NonnullGCPtr<WritableStreamDefaultWriter>> acquire_writable_stream_default_writer(WritableStream& stream)
  1655. {
  1656. auto& realm = stream.realm();
  1657. // 1. Let writer be a new WritableStreamDefaultWriter.
  1658. auto writer = stream.heap().allocate<WritableStreamDefaultWriter>(realm, realm);
  1659. // 2. Perform ? SetUpWritableStreamDefaultWriter(writer, stream).
  1660. TRY(set_up_writable_stream_default_writer(*writer, stream));
  1661. // 3. Return writer.
  1662. return writer;
  1663. }
  1664. // https://streams.spec.whatwg.org/#is-writable-stream-locked
  1665. bool is_writable_stream_locked(WritableStream const& stream)
  1666. {
  1667. // 1. If stream.[[writer]] is undefined, return false.
  1668. if (!stream.writer())
  1669. return false;
  1670. // 2. Return true.
  1671. return true;
  1672. }
  1673. // https://streams.spec.whatwg.org/#set-up-writable-stream-default-writer
  1674. WebIDL::ExceptionOr<void> set_up_writable_stream_default_writer(WritableStreamDefaultWriter& writer, WritableStream& stream)
  1675. {
  1676. auto& realm = writer.realm();
  1677. // 1. If ! IsWritableStreamLocked(stream) is true, throw a TypeError exception.
  1678. if (is_writable_stream_locked(stream))
  1679. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Stream is locked"sv };
  1680. // 2. Set writer.[[stream]] to stream.
  1681. writer.set_stream(stream);
  1682. // 3. Set stream.[[writer]] to writer.
  1683. stream.set_writer(writer);
  1684. // 4. Let state be stream.[[state]].
  1685. auto state = stream.state();
  1686. // 5. If state is "writable",
  1687. if (state == WritableStream::State::Writable) {
  1688. // 1. If ! WritableStreamCloseQueuedOrInFlight(stream) is false and stream.[[backpressure]] is true, set writer.[[readyPromise]] to a new promise.
  1689. if (!writable_stream_close_queued_or_in_flight(stream) && stream.backpressure()) {
  1690. writer.set_ready_promise(WebIDL::create_promise(realm));
  1691. }
  1692. // 2. Otherwise, set writer.[[readyPromise]] to a promise resolved with undefined.
  1693. else {
  1694. writer.set_ready_promise(WebIDL::create_resolved_promise(realm, JS::js_undefined()));
  1695. }
  1696. // 3. Set writer.[[closedPromise]] to a new promise.
  1697. writer.set_closed_promise(WebIDL::create_promise(realm));
  1698. }
  1699. // 6. Otherwise, if state is "erroring",
  1700. else if (state == WritableStream::State::Erroring) {
  1701. // 1. Set writer.[[readyPromise]] to a promise rejected with stream.[[storedError]].
  1702. writer.set_ready_promise(WebIDL::create_rejected_promise(realm, stream.stored_error()));
  1703. // 2. Set writer.[[readyPromise]].[[PromiseIsHandled]] to true.
  1704. WebIDL::mark_promise_as_handled(*writer.ready_promise());
  1705. // 3. Set writer.[[closedPromise]] to a new promise.
  1706. writer.set_closed_promise(WebIDL::create_promise(realm));
  1707. }
  1708. // 7. Otherwise, if state is "closed",
  1709. else if (state == WritableStream::State::Closed) {
  1710. // 1. Set writer.[[readyPromise]] to a promise resolved with undefined.
  1711. writer.set_ready_promise(WebIDL::create_resolved_promise(realm, JS::js_undefined()));
  1712. // 2. Set writer.[[closedPromise]] to a promise resolved with undefined.
  1713. writer.set_closed_promise(WebIDL::create_resolved_promise(realm, JS::js_undefined()));
  1714. }
  1715. // 8. Otherwise,
  1716. else {
  1717. // 1. Assert: state is "errored".
  1718. VERIFY(state == WritableStream::State::Errored);
  1719. // 2. Let storedError be stream.[[storedError]].
  1720. auto stored_error = stream.stored_error();
  1721. // 3. Set writer.[[readyPromise]] to a promise rejected with storedError.
  1722. writer.set_ready_promise(WebIDL::create_rejected_promise(realm, stored_error));
  1723. // 4. Set writer.[[readyPromise]].[[PromiseIsHandled]] to true.
  1724. WebIDL::mark_promise_as_handled(*writer.ready_promise());
  1725. // 5. Set writer.[[closedPromise]] to a promise rejected with storedError.
  1726. writer.set_closed_promise(WebIDL::create_rejected_promise(realm, stored_error));
  1727. // 6. Set writer.[[closedPromise]].[[PromiseIsHandled]] to true.
  1728. WebIDL::mark_promise_as_handled(*writer.closed_promise());
  1729. }
  1730. return {};
  1731. }
  1732. // https://streams.spec.whatwg.org/#set-up-readable-byte-stream-controller
  1733. WebIDL::ExceptionOr<void> set_up_readable_byte_stream_controller(ReadableStream& stream, ReadableByteStreamController& controller, JS::NonnullGCPtr<StartAlgorithm> start_algorithm, JS::NonnullGCPtr<PullAlgorithm> pull_algorithm, JS::NonnullGCPtr<CancelAlgorithm> cancel_algorithm, double high_water_mark, JS::Value auto_allocate_chunk_size)
  1734. {
  1735. auto& realm = stream.realm();
  1736. // 1. Assert: stream.[[controller]] is undefined.
  1737. VERIFY(!stream.controller().has_value());
  1738. // 2. If autoAllocateChunkSize is not undefined,
  1739. if (!auto_allocate_chunk_size.is_undefined()) {
  1740. // 1. Assert: ! IsInteger(autoAllocateChunkSize) is true.
  1741. VERIFY(auto_allocate_chunk_size.is_integral_number());
  1742. // 2. Assert: autoAllocateChunkSize is positive.
  1743. VERIFY(auto_allocate_chunk_size.as_double() > 0);
  1744. }
  1745. // 3. Set controller.[[stream]] to stream.
  1746. controller.set_stream(stream);
  1747. // 4. Set controller.[[pullAgain]] and controller.[[pulling]] to false.
  1748. controller.set_pull_again(false);
  1749. controller.set_pulling(false);
  1750. // 5. Set controller.[[byobRequest]] to null.
  1751. controller.set_byob_request({});
  1752. // 6. Perform ! ResetQueue(controller).
  1753. reset_queue(controller);
  1754. // 7. Set controller.[[closeRequested]] and controller.[[started]] to false.
  1755. controller.set_close_requested(false);
  1756. controller.set_started(false);
  1757. // 8. Set controller.[[strategyHWM]] to highWaterMark.
  1758. controller.set_strategy_hwm(high_water_mark);
  1759. // 9. Set controller.[[pullAlgorithm]] to pullAlgorithm.
  1760. controller.set_pull_algorithm(pull_algorithm);
  1761. // 10. Set controller.[[cancelAlgorithm]] to cancelAlgorithm.
  1762. controller.set_cancel_algorithm(cancel_algorithm);
  1763. // 11. Set controller.[[autoAllocateChunkSize]] to autoAllocateChunkSize.
  1764. if (auto_allocate_chunk_size.is_integral_number())
  1765. controller.set_auto_allocate_chunk_size(auto_allocate_chunk_size.as_double());
  1766. // 12. Set controller.[[pendingPullIntos]] to a new empty list.
  1767. controller.pending_pull_intos().clear();
  1768. // 13. Set stream.[[controller]] to controller.
  1769. stream.set_controller(ReadableStreamController { controller });
  1770. // 14. Let startResult be the result of performing startAlgorithm.
  1771. auto start_result = TRY(start_algorithm->function()());
  1772. // 15. Let startPromise be a promise resolved with startResult.
  1773. auto start_promise = WebIDL::create_resolved_promise(realm, start_result);
  1774. // 16. Upon fulfillment of startPromise,
  1775. WebIDL::upon_fulfillment(start_promise, [&](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  1776. // 1. Set controller.[[started]] to true.
  1777. controller.set_started(true);
  1778. // 2. Assert: controller.[[pulling]] is false.
  1779. VERIFY(!controller.pulling());
  1780. // 3. Assert: controller.[[pullAgain]] is false.
  1781. VERIFY(!controller.pull_again());
  1782. // 4. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
  1783. TRY(readable_byte_stream_controller_call_pull_if_needed(controller));
  1784. return JS::js_undefined();
  1785. });
  1786. // 17. Upon rejection of startPromise with reason r,
  1787. WebIDL::upon_rejection(start_promise, [&](auto const& r) -> WebIDL::ExceptionOr<JS::Value> {
  1788. // 1. Perform ! ReadableByteStreamControllerError(controller, r).
  1789. readable_byte_stream_controller_error(controller, r);
  1790. return JS::js_undefined();
  1791. });
  1792. return {};
  1793. }
  1794. // https://streams.spec.whatwg.org/#readablestream-enqueue
  1795. WebIDL::ExceptionOr<void> readable_stream_enqueue(ReadableStreamController& controller, JS::Value chunk)
  1796. {
  1797. // 1. If stream.[[controller]] implements ReadableStreamDefaultController,
  1798. if (controller.has<JS::NonnullGCPtr<ReadableStreamDefaultController>>()) {
  1799. // 1. Perform ! ReadableStreamDefaultControllerEnqueue(stream.[[controller]], chunk).
  1800. return readable_stream_default_controller_enqueue(controller.get<JS::NonnullGCPtr<ReadableStreamDefaultController>>(), chunk);
  1801. }
  1802. // 2. Otherwise,
  1803. else {
  1804. // 1. Assert: stream.[[controller]] implements ReadableByteStreamController.
  1805. VERIFY(controller.has<JS::NonnullGCPtr<ReadableByteStreamController>>());
  1806. auto readable_byte_controller = controller.get<JS::NonnullGCPtr<ReadableByteStreamController>>();
  1807. // FIXME: 2. Assert: chunk is an ArrayBufferView.
  1808. // 3. Let byobView be the current BYOB request view for stream.
  1809. // FIXME: This is not what the spec means by 'current BYOB request view'
  1810. auto byob_view = readable_byte_controller->raw_byob_request();
  1811. // 4. If byobView is non-null, and chunk.[[ViewedArrayBuffer]] is byobView.[[ViewedArrayBuffer]], then:
  1812. if (byob_view) {
  1813. // FIXME: 1. Assert: chunk.[[ByteOffset]] is byobView.[[ByteOffset]].
  1814. // FIXME: 2. Assert: chunk.[[ByteLength]] ≤ byobView.[[ByteLength]].
  1815. // FIXME: 3. Perform ? ReadableByteStreamControllerRespond(stream.[[controller]], chunk.[[ByteLength]]).
  1816. TODO();
  1817. }
  1818. // 5. Otherwise, perform ? ReadableByteStreamControllerEnqueue(stream.[[controller]], chunk).
  1819. return readable_byte_stream_controller_enqueue(readable_byte_controller, chunk);
  1820. }
  1821. }
  1822. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-enqueue
  1823. WebIDL::ExceptionOr<void> readable_byte_stream_controller_enqueue(ReadableByteStreamController& controller, JS::Value chunk)
  1824. {
  1825. auto& vm = controller.vm();
  1826. auto& realm = controller.realm();
  1827. // 1. Let stream be controller.[[stream]].
  1828. auto stream = controller.stream();
  1829. // 2. If controller.[[closeRequested]] is true or stream.[[state]] is not "readable", return.
  1830. if (controller.close_requested() || stream->state() != ReadableStream ::State::Readable)
  1831. return {};
  1832. // 3. Let buffer be chunk.[[ViewedArrayBuffer]].
  1833. auto* typed_array = TRY(JS::typed_array_from(vm, chunk));
  1834. auto* buffer = typed_array->viewed_array_buffer();
  1835. // 4. Let byteOffset be chunk.[[ByteOffset]].
  1836. auto byte_offset = typed_array->byte_offset();
  1837. // 6. If ! IsDetachedBuffer(buffer) is true, throw a TypeError exception.
  1838. // FIXME: The streams spec has not been updated for resizable ArrayBuffer objects. We must perform step 6 before
  1839. // invoking TypedArrayByteLength in step 5. We also must check if the array is out-of-bounds, rather than
  1840. // just detached.
  1841. auto typed_array_record = JS::make_typed_array_with_buffer_witness_record(*typed_array, JS::ArrayBuffer::Order::SeqCst);
  1842. if (JS::is_typed_array_out_of_bounds(typed_array_record))
  1843. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BufferOutOfBounds, "TypedArray"sv);
  1844. // 5. Let byteLength be chunk.[[ByteLength]].
  1845. auto byte_length = JS::typed_array_byte_length(typed_array_record);
  1846. // 7. Let transferredBuffer be ? TransferArrayBuffer(buffer).
  1847. auto transferred_buffer = TRY(transfer_array_buffer(realm, *buffer));
  1848. // 8. If controller.[[pendingPullIntos]] is not empty,
  1849. if (!controller.pending_pull_intos().is_empty()) {
  1850. // 1. Let firstPendingPullInto be controller.[[pendingPullIntos]][0].
  1851. auto& first_pending_pull_into = controller.pending_pull_intos().first();
  1852. // 2. If ! IsDetachedBuffer(firstPendingPullInto’s buffer) is true, throw a TypeError exception.
  1853. if (first_pending_pull_into.buffer->is_detached()) {
  1854. auto error = JS::TypeError::create(realm, "Buffer is detached"sv);
  1855. return JS::throw_completion(error);
  1856. }
  1857. // 3. Perform ! ReadableByteStreamControllerInvalidateBYOBRequest(controller).
  1858. readable_byte_stream_controller_invalidate_byob_request(controller);
  1859. // 4. Set firstPendingPullInto’s buffer to ! TransferArrayBuffer(firstPendingPullInto’s buffer).
  1860. first_pending_pull_into.buffer = TRY(transfer_array_buffer(realm, first_pending_pull_into.buffer));
  1861. // 5. If firstPendingPullInto’s reader type is "none", perform ? ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto).
  1862. if (first_pending_pull_into.reader_type == ReaderType::None)
  1863. TRY(readable_byte_stream_controller_enqueue_detached_pull_into_queue(controller, first_pending_pull_into));
  1864. }
  1865. // 9. If ! ReadableStreamHasDefaultReader(stream) is true,
  1866. if (readable_stream_has_default_reader(*stream)) {
  1867. // 1. Perform ! ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller).
  1868. TRY(readable_byte_stream_controller_process_read_requests_using_queue(controller));
  1869. // 2. If ! ReadableStreamGetNumReadRequests(stream) is 0,
  1870. if (readable_stream_get_num_read_requests(*stream) == 0) {
  1871. // 1. Assert: controller.[[pendingPullIntos]] is empty.
  1872. VERIFY(controller.pending_pull_intos().is_empty());
  1873. // 2. Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength).
  1874. readable_byte_stream_controller_enqueue_chunk_to_queue(controller, transferred_buffer, byte_offset, byte_length);
  1875. }
  1876. // 3. Otherwise.
  1877. else {
  1878. // 1. Assert: controller.[[queue]] is empty.
  1879. VERIFY(controller.queue().is_empty());
  1880. // 2. If controller.[[pendingPullIntos]] is not empty,
  1881. if (!controller.pending_pull_intos().is_empty()) {
  1882. // 1. Assert: controller.[[pendingPullIntos]][0]'s reader type is "default".
  1883. VERIFY(controller.pending_pull_intos().first().reader_type == ReaderType::Default);
  1884. // 2. Perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).
  1885. readable_byte_stream_controller_shift_pending_pull_into(controller);
  1886. }
  1887. // 3. Let transferredView be ! Construct(%Uint8Array%, « transferredBuffer, byteOffset, byteLength »).
  1888. auto transferred_view = MUST_OR_THROW_OOM(JS::construct(vm, *realm.intrinsics().uint8_array_constructor(), transferred_buffer, JS::Value(byte_offset), JS::Value(byte_length)));
  1889. // 4. Perform ! ReadableStreamFulfillReadRequest(stream, transferredView, false).
  1890. readable_stream_fulfill_read_request(*stream, transferred_view, false);
  1891. }
  1892. }
  1893. // 10. Otherwise, if ! ReadableStreamHasBYOBReader(stream) is true,
  1894. else if (readable_stream_has_byob_reader(*stream)) {
  1895. // 1. Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength).
  1896. readable_byte_stream_controller_enqueue_chunk_to_queue(controller, transferred_buffer, byte_offset, byte_length);
  1897. // 2. Perform ! ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller).
  1898. readable_byte_stream_controller_process_pull_into_descriptors_using_queue(controller);
  1899. }
  1900. // 11. Otherwise,
  1901. else {
  1902. // 1. Assert: ! IsReadableStreamLocked(stream) is false.
  1903. VERIFY(!is_readable_stream_locked(*stream));
  1904. // 2. Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength).
  1905. readable_byte_stream_controller_enqueue_chunk_to_queue(controller, transferred_buffer, byte_offset, byte_length);
  1906. }
  1907. // 12. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
  1908. TRY(readable_byte_stream_controller_call_pull_if_needed(controller));
  1909. return {};
  1910. }
  1911. // https://streams.spec.whatwg.org/#transfer-array-buffer
  1912. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::ArrayBuffer>> transfer_array_buffer(JS::Realm& realm, JS::ArrayBuffer& buffer)
  1913. {
  1914. auto& vm = realm.vm();
  1915. // 1. Assert: ! IsDetachedBuffer(O) is false.
  1916. VERIFY(!buffer.is_detached());
  1917. // 2. Let arrayBufferData be O.[[ArrayBufferData]].
  1918. // 3. Let arrayBufferByteLength be O.[[ArrayBufferByteLength]].
  1919. auto array_buffer = buffer.buffer();
  1920. // 4. Perform ? DetachArrayBuffer(O).
  1921. TRY(JS::detach_array_buffer(vm, buffer));
  1922. // 5. Return a new ArrayBuffer object, created in the current Realm, whose [[ArrayBufferData]] internal slot value is arrayBufferData and whose [[ArrayBufferByteLength]] internal slot value is arrayBufferByteLength.
  1923. return JS::ArrayBuffer::create(realm, move(array_buffer));
  1924. }
  1925. // https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollerenqueuedetachedpullintotoqueue
  1926. WebIDL::ExceptionOr<void> readable_byte_stream_controller_enqueue_detached_pull_into_queue(ReadableByteStreamController& controller, PullIntoDescriptor& pull_into_descriptor)
  1927. {
  1928. // 1. Assert: pullIntoDescriptor’s reader type is "none".
  1929. VERIFY(pull_into_descriptor.reader_type == ReaderType::None);
  1930. // 2. If pullIntoDescriptor’s bytes filled > 0, perform ? ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor’s buffer, pullIntoDescriptor’s byte offset, pullIntoDescriptor’s bytes filled).
  1931. if (pull_into_descriptor.bytes_filled > 0)
  1932. TRY(readable_byte_stream_controller_enqueue_cloned_chunk_to_queue(controller, pull_into_descriptor.buffer, pull_into_descriptor.byte_offset, pull_into_descriptor.bytes_filled));
  1933. // 3. Perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).
  1934. readable_byte_stream_controller_shift_pending_pull_into(controller);
  1935. return {};
  1936. }
  1937. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-commit-pull-into-descriptor
  1938. void readable_byte_stream_controller_commit_pull_into_descriptor(ReadableStream& stream, PullIntoDescriptor const& pull_into_descriptor)
  1939. {
  1940. // 1. Assert: stream.[[state]] is not "errored".
  1941. VERIFY(!stream.is_errored());
  1942. // 2. Assert: pullIntoDescriptor.reader type is not "none".
  1943. VERIFY(pull_into_descriptor.reader_type != ReaderType::None);
  1944. // 3. Let done be false.
  1945. bool done = false;
  1946. // 4. If stream.[[state]] is "closed",
  1947. if (stream.is_closed()) {
  1948. // 1. Assert: pullIntoDescriptor’s bytes filled is 0.
  1949. VERIFY(pull_into_descriptor.bytes_filled == 0);
  1950. // 2. Set done to true.
  1951. done = true;
  1952. }
  1953. // 5. Let filledView be ! ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor).
  1954. auto filled_view = readable_byte_stream_controller_convert_pull_into_descriptor(stream.realm(), pull_into_descriptor);
  1955. // 6. If pullIntoDescriptor’s reader type is "default",
  1956. if (pull_into_descriptor.reader_type == ReaderType::Default) {
  1957. // 1. Perform ! ReadableStreamFulfillReadRequest(stream, filledView, done).
  1958. readable_stream_fulfill_read_request(stream, filled_view, done);
  1959. }
  1960. // 7. Otherwise,
  1961. else {
  1962. // 1. Assert: pullIntoDescriptor’s reader type is "byob".
  1963. VERIFY(pull_into_descriptor.reader_type == ReaderType::Byob);
  1964. // 2. Perform ! ReadableStreamFulfillReadIntoRequest(stream, filledView, done).
  1965. readable_stream_fulfill_read_into_request(stream, filled_view, done);
  1966. }
  1967. }
  1968. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-process-pull-into-descriptors-using-queue
  1969. void readable_byte_stream_controller_process_pull_into_descriptors_using_queue(ReadableByteStreamController& controller)
  1970. {
  1971. // 1. Assert: controller.[[closeRequested]] is false.
  1972. VERIFY(!controller.close_requested());
  1973. // 2. While controller.[[pendingPullIntos]] is not empty,
  1974. while (!controller.pending_pull_intos().is_empty()) {
  1975. // 1. If controller.[[queueTotalSize]] is 0, return.
  1976. if (controller.queue_total_size() == 0)
  1977. return;
  1978. // 2. Let pullIntoDescriptor be controller.[[pendingPullIntos]][0].
  1979. auto& pull_into_descriptor = controller.pending_pull_intos().first();
  1980. // 3. If ! ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) is true,
  1981. if (readable_byte_stream_controller_fill_pull_into_descriptor_from_queue(controller, pull_into_descriptor)) {
  1982. // NOTE: We store the returned pull into descriptor here as the 'shift pending pull into' will remove
  1983. // the first entry into the list which we have a reference to above.
  1984. // 1. Perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).
  1985. auto descriptor = readable_byte_stream_controller_shift_pending_pull_into(controller);
  1986. // 2. Perform ! ReadableByteStreamControllerCommitPullIntoDescriptor(controller.[[stream]], pullIntoDescriptor).
  1987. readable_byte_stream_controller_commit_pull_into_descriptor(*controller.stream(), descriptor);
  1988. }
  1989. }
  1990. }
  1991. // https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollerprocessreadrequestsusingqueue
  1992. WebIDL::ExceptionOr<void> readable_byte_stream_controller_process_read_requests_using_queue(ReadableByteStreamController& controller)
  1993. {
  1994. // 1. Let reader be controller.[[stream]].[[reader]].
  1995. auto reader = controller.stream()->reader();
  1996. // 2. Assert: reader implements ReadableStreamDefaultReader.
  1997. VERIFY(reader->has<JS::NonnullGCPtr<ReadableStreamDefaultReader>>());
  1998. // 3. While reader.[[readRequests]] is not empty,
  1999. auto readable_stream_default_reader = reader->get<JS::NonnullGCPtr<ReadableStreamDefaultReader>>();
  2000. while (!readable_stream_default_reader->read_requests().is_empty()) {
  2001. // 1. If controller.[[queueTotalSize]] is 0, return.
  2002. if (controller.queue_total_size() == 0.0)
  2003. return {};
  2004. // 2. Let readRequest be reader.[[readRequests]][0].
  2005. // 3. Remove readRequest from reader.[[readRequests]].
  2006. auto read_request = readable_stream_default_reader->read_requests().take_first();
  2007. // 4. Perform ! ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest).
  2008. TRY(readable_byte_stream_controller_fill_read_request_from_queue(controller, read_request));
  2009. }
  2010. return {};
  2011. }
  2012. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-enqueue-chunk-to-queue
  2013. void readable_byte_stream_controller_enqueue_chunk_to_queue(ReadableByteStreamController& controller, JS::NonnullGCPtr<JS::ArrayBuffer> buffer, u32 byte_offset, u32 byte_length)
  2014. {
  2015. // 1. Append a new readable byte stream queue entry with buffer buffer, byte offset byteOffset, and byte length byteLength to controller.[[queue]].
  2016. controller.queue().append(ReadableByteStreamQueueEntry {
  2017. .buffer = buffer,
  2018. .byte_offset = byte_offset,
  2019. .byte_length = byte_length,
  2020. });
  2021. // 2. Set controller.[[queueTotalSize]] to controller.[[queueTotalSize]] + byteLength.
  2022. controller.set_queue_total_size(controller.queue_total_size() + byte_length);
  2023. }
  2024. // https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollerenqueueclonedchunktoqueue
  2025. WebIDL::ExceptionOr<void> readable_byte_stream_controller_enqueue_cloned_chunk_to_queue(ReadableByteStreamController& controller, JS::ArrayBuffer& buffer, u64 byte_offset, u64 byte_length)
  2026. {
  2027. auto& vm = controller.vm();
  2028. // 1. Let cloneResult be CloneArrayBuffer(buffer, byteOffset, byteLength, %ArrayBuffer%).
  2029. auto clone_result = JS::clone_array_buffer(vm, buffer, byte_offset, byte_length);
  2030. // 2. If cloneResult is an abrupt completion,
  2031. if (clone_result.is_throw_completion()) {
  2032. auto throw_completion = Bindings::throw_dom_exception_if_needed(vm, [&] { return clone_result; }).throw_completion();
  2033. // 1. Perform ! ReadableByteStreamControllerError(controller, cloneResult.[[Value]]).
  2034. readable_byte_stream_controller_error(controller, throw_completion.value().value());
  2035. // 2. Return cloneResult.
  2036. // Note: We need to return the throw_completion object here, as enqueue needs to throw the same object that the controller is errored with
  2037. return throw_completion;
  2038. }
  2039. // 3. Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(controller, cloneResult.[[Value]], 0, byteLength).
  2040. readable_byte_stream_controller_enqueue_chunk_to_queue(controller, *clone_result.release_value(), 0, byte_length);
  2041. return {};
  2042. }
  2043. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-shift-pending-pull-into
  2044. PullIntoDescriptor readable_byte_stream_controller_shift_pending_pull_into(ReadableByteStreamController& controller)
  2045. {
  2046. // 1. Assert: controller.[[byobRequest]] is null.
  2047. VERIFY(!controller.raw_byob_request());
  2048. // 2. Let descriptor be controller.[[pendingPullIntos]][0].
  2049. // 3. Remove descriptor from controller.[[pendingPullIntos]].
  2050. auto descriptor = controller.pending_pull_intos().take_first();
  2051. // 4. Return descriptor.
  2052. return descriptor;
  2053. }
  2054. // https://streams.spec.whatwg.org/#readablestream-set-up-with-byte-reading-support
  2055. WebIDL::ExceptionOr<void> set_up_readable_stream_controller_with_byte_reading_support(ReadableStream& stream, JS::GCPtr<PullAlgorithm> pull_algorithm, JS::GCPtr<CancelAlgorithm> cancel_algorithm, double high_water_mark)
  2056. {
  2057. auto& realm = stream.realm();
  2058. // 1. Let startAlgorithm be an algorithm that returns undefined.
  2059. auto start_algorithm = JS::create_heap_function(realm.heap(), []() -> WebIDL::ExceptionOr<JS::Value> { return JS::js_undefined(); });
  2060. // 2. Let pullAlgorithmWrapper be an algorithm that runs these steps:
  2061. auto pull_algorithm_wrapper = JS::create_heap_function(realm.heap(), [&realm, pull_algorithm]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  2062. // 1. Let result be the result of running pullAlgorithm, if pullAlgorithm was given, or null otherwise. If this throws an exception e, return a promise rejected with e.
  2063. JS::GCPtr<JS::PromiseCapability> result = nullptr;
  2064. if (pull_algorithm)
  2065. result = TRY(pull_algorithm->function()());
  2066. // 2. If result is a Promise, then return result.
  2067. if (result != nullptr)
  2068. return JS::NonnullGCPtr(*result);
  2069. // 3. Return a promise resolved with undefined.
  2070. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  2071. });
  2072. // 3. Let cancelAlgorithmWrapper be an algorithm that runs these steps:
  2073. auto cancel_algorithm_wrapper = JS::create_heap_function(realm.heap(), [&realm, cancel_algorithm](JS::Value c) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  2074. // 1. Let result be the result of running cancelAlgorithm, if cancelAlgorithm was given, or null otherwise. If this throws an exception e, return a promise rejected with e.
  2075. JS::GCPtr<JS::PromiseCapability> result = nullptr;
  2076. if (cancel_algorithm)
  2077. result = TRY(cancel_algorithm->function()(c));
  2078. // 2. If result is a Promise, then return result.
  2079. if (result != nullptr)
  2080. return JS::NonnullGCPtr(*result);
  2081. // 3. Return a promise resolved with undefined.
  2082. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  2083. });
  2084. // 4. Perform ! InitializeReadableStream(stream).
  2085. // 5. Let controller be a new ReadableByteStreamController.
  2086. auto controller = stream.heap().allocate<ReadableByteStreamController>(realm, realm);
  2087. // 6. Perform ! SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithmWrapper, cancelAlgorithmWrapper, highWaterMark, undefined).
  2088. TRY(set_up_readable_byte_stream_controller(stream, controller, start_algorithm, pull_algorithm_wrapper, cancel_algorithm_wrapper, high_water_mark, JS::js_undefined()));
  2089. return {};
  2090. }
  2091. // https://streams.spec.whatwg.org/#writable-stream-abort
  2092. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> writable_stream_abort(WritableStream& stream, JS::Value reason)
  2093. {
  2094. auto& realm = stream.realm();
  2095. // 1. If stream.[[state]] is "closed" or "errored", return a promise resolved with undefined.
  2096. auto state = stream.state();
  2097. if (state == WritableStream::State::Closed || state == WritableStream::State::Errored)
  2098. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  2099. // 2. Signal abort on stream.[[controller]].[[signal]] with reason.
  2100. stream.controller()->signal()->signal_abort(reason);
  2101. // 3. Let state be stream.[[state]].
  2102. state = stream.state();
  2103. // 4. If state is "closed" or "errored", return a promise resolved with undefined.
  2104. if (state == WritableStream::State::Closed || state == WritableStream::State::Errored)
  2105. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  2106. // 5. If stream.[[pendingAbortRequest]] is not undefined, return stream.[[pendingAbortRequest]]'s promise.
  2107. if (stream.pending_abort_request().has_value())
  2108. return stream.pending_abort_request()->promise;
  2109. // 6. Assert: state is "writable" or "erroring".
  2110. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  2111. // 7. Let wasAlreadyErroring be false.
  2112. auto was_already_erroring = false;
  2113. // 8. If state is "erroring",
  2114. if (state == WritableStream::State::Erroring) {
  2115. // 1. Set wasAlreadyErroring to true.
  2116. was_already_erroring = true;
  2117. // 2. Set reason to undefined.
  2118. reason = JS::js_undefined();
  2119. }
  2120. // 9. Let promise be a new promise.
  2121. auto promise = WebIDL::create_promise(realm);
  2122. // 10. Set stream.[[pendingAbortRequest]] to a new pending abort request whose promise is promise, reason is reason, and was already erroring is wasAlreadyErroring.
  2123. stream.set_pending_abort_request(PendingAbortRequest { promise, reason, was_already_erroring });
  2124. // 11. If wasAlreadyErroring is false, perform ! WritableStreamStartErroring(stream, reason).
  2125. if (!was_already_erroring)
  2126. TRY(writable_stream_start_erroring(stream, reason));
  2127. // 12. Return promise.
  2128. return promise;
  2129. }
  2130. // https://streams.spec.whatwg.org/#writable-stream-close
  2131. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> writable_stream_close(WritableStream& stream)
  2132. {
  2133. auto& realm = stream.realm();
  2134. // 1. Let state be stream.[[state]].
  2135. auto state = stream.state();
  2136. // 2. If state is "closed" or "errored", return a promise rejected with a TypeError exception.
  2137. if (state == WritableStream::State::Closed || state == WritableStream::State::Errored) {
  2138. auto message = state == WritableStream::State::Closed ? "Cannot close a closed stream"sv : "Cannot close an errored stream"sv;
  2139. auto exception = JS::TypeError::create(realm, message);
  2140. return WebIDL::create_rejected_promise(realm, exception);
  2141. }
  2142. // 3. Assert: state is "writable" or "erroring".
  2143. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  2144. // 4. Assert: ! WritableStreamCloseQueuedOrInFlight(stream) is false.
  2145. VERIFY(!writable_stream_close_queued_or_in_flight(stream));
  2146. // 5. Let promise be a new promise.
  2147. auto promise = WebIDL::create_promise(realm);
  2148. // 6. Set stream.[[closeRequest]] to promise.
  2149. stream.set_close_request(promise);
  2150. // 7. Let writer be stream.[[writer]].
  2151. auto writer = stream.writer();
  2152. // 8. If writer is not undefined, and stream.[[backpressure]] is true, and state is "writable", resolve writer.[[readyPromise]] with undefined.
  2153. if (writer && stream.backpressure() && state == WritableStream::State::Writable)
  2154. WebIDL::resolve_promise(realm, *writer->ready_promise(), JS::js_undefined());
  2155. // 9. Perform ! WritableStreamDefaultControllerClose(stream.[[controller]]).
  2156. TRY(writable_stream_default_controller_close(*stream.controller()));
  2157. // 10. Return promise.
  2158. return promise;
  2159. }
  2160. // https://streams.spec.whatwg.org/#writable-stream-add-write-request
  2161. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> writable_stream_add_write_request(WritableStream& stream)
  2162. {
  2163. auto& realm = stream.realm();
  2164. auto& vm = stream.vm();
  2165. // 1. Assert: ! IsWritableStreamLocked(stream) is true.
  2166. VERIFY(is_writable_stream_locked(stream));
  2167. // 2. Assert: stream.[[state]] is "writable".
  2168. VERIFY(stream.state() == WritableStream::State::Writable);
  2169. // 3. Let promise be a new promise.
  2170. auto promise = WebIDL::create_promise(realm);
  2171. // 4. Append promise to stream.[[writeRequests]].
  2172. TRY_OR_THROW_OOM(vm, stream.write_requests().try_append(promise));
  2173. // 5. Return promise.
  2174. return promise;
  2175. }
  2176. // https://streams.spec.whatwg.org/#writable-stream-close-queued-or-in-flight
  2177. bool writable_stream_close_queued_or_in_flight(WritableStream const& stream)
  2178. {
  2179. // 1. If stream.[[closeRequest]] is undefined and stream.[[inFlightCloseRequest]] is undefined, return false.
  2180. if (!stream.close_request() && !stream.in_flight_write_request())
  2181. return false;
  2182. // 2. Return true.
  2183. return true;
  2184. }
  2185. // https://streams.spec.whatwg.org/#writable-stream-deal-with-rejection
  2186. WebIDL::ExceptionOr<void> writable_stream_deal_with_rejection(WritableStream& stream, JS::Value error)
  2187. {
  2188. // 1. Let state be stream.[[state]].
  2189. auto state = stream.state();
  2190. // 2. If state is "writable",
  2191. if (state == WritableStream::State::Writable) {
  2192. // 1. Perform ! WritableStreamStartErroring(stream, error).
  2193. // 2. Return.
  2194. return writable_stream_start_erroring(stream, error);
  2195. }
  2196. // 3. Assert: state is "erroring".
  2197. VERIFY(state == WritableStream::State::Erroring);
  2198. // 4. Perform ! WritableStreamFinishErroring(stream).
  2199. return writable_stream_finish_erroring(stream);
  2200. }
  2201. // https://streams.spec.whatwg.org/#writable-stream-finish-erroring
  2202. WebIDL::ExceptionOr<void> writable_stream_finish_erroring(WritableStream& stream)
  2203. {
  2204. auto& realm = stream.realm();
  2205. // 1. Assert: stream.[[state]] is "erroring".
  2206. VERIFY(stream.state() == WritableStream::State::Erroring);
  2207. // 2. Assert: ! WritableStreamHasOperationMarkedInFlight(stream) is false.
  2208. VERIFY(!writable_stream_has_operation_marked_in_flight(stream));
  2209. // 3. Set stream.[[state]] to "errored".
  2210. stream.set_state(WritableStream::State::Errored);
  2211. // 4. Perform ! stream.[[controller]].[[ErrorSteps]]().
  2212. stream.controller()->error_steps();
  2213. // 5. Let storedError be stream.[[storedError]].
  2214. auto stored_error = stream.stored_error();
  2215. // 6. For each writeRequest of stream.[[writeRequests]]:
  2216. for (auto& write_request : stream.write_requests()) {
  2217. // 1. Reject writeRequest with storedError.
  2218. WebIDL::reject_promise(realm, *write_request, stored_error);
  2219. }
  2220. // 7. Set stream.[[writeRequests]] to an empty list.
  2221. stream.write_requests().clear();
  2222. // 8. If stream.[[pendingAbortRequest]] is undefined,
  2223. if (!stream.pending_abort_request().has_value()) {
  2224. // 1. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream).
  2225. writable_stream_reject_close_and_closed_promise_if_needed(stream);
  2226. // 2. Return.
  2227. return {};
  2228. }
  2229. // 9. Let abortRequest be stream.[[pendingAbortRequest]].
  2230. // 10. Set stream.[[pendingAbortRequest]] to undefined.
  2231. auto abort_request = stream.pending_abort_request().release_value();
  2232. // 11. If abortRequest’s was already erroring is true,
  2233. if (abort_request.was_already_erroring) {
  2234. // 1. Reject abortRequest’s promise with storedError.
  2235. WebIDL::reject_promise(realm, abort_request.promise, stored_error);
  2236. // 2. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream).
  2237. writable_stream_reject_close_and_closed_promise_if_needed(stream);
  2238. // 3. Return.
  2239. return {};
  2240. }
  2241. // 12. Let promise be ! stream.[[controller]].[[AbortSteps]](abortRequest’s reason).
  2242. auto promise = TRY(stream.controller()->abort_steps(abort_request.reason));
  2243. // 13. Upon fulfillment of promise,
  2244. WebIDL::upon_fulfillment(*promise, [&, abort_promise = abort_request.promise](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  2245. // 1. Resolve abortRequest’s promise with undefined.
  2246. WebIDL::resolve_promise(realm, abort_promise, JS::js_undefined());
  2247. // 2. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream).
  2248. writable_stream_reject_close_and_closed_promise_if_needed(stream);
  2249. return JS::js_undefined();
  2250. });
  2251. // 14. Upon rejection of promise with reason reason,
  2252. WebIDL::upon_rejection(*promise, [&, abort_promise = abort_request.promise](auto const& reason) -> WebIDL::ExceptionOr<JS::Value> {
  2253. // 1. Reject abortRequest’s promise with reason.
  2254. WebIDL::reject_promise(realm, abort_promise, reason);
  2255. // 2. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream).
  2256. writable_stream_reject_close_and_closed_promise_if_needed(stream);
  2257. return JS::js_undefined();
  2258. });
  2259. return {};
  2260. }
  2261. // https://streams.spec.whatwg.org/#writable-stream-finish-in-flight-close
  2262. void writable_stream_finish_in_flight_close(WritableStream& stream)
  2263. {
  2264. auto& realm = stream.realm();
  2265. // 1. Assert: stream.[[inFlightCloseRequest]] is not undefined.
  2266. VERIFY(stream.in_flight_close_request());
  2267. // 2. Resolve stream.[[inFlightCloseRequest]] with undefined.
  2268. WebIDL::resolve_promise(realm, *stream.in_flight_close_request(), JS::js_undefined());
  2269. // 3. Set stream.[[inFlightCloseRequest]] to undefined.
  2270. stream.set_in_flight_close_request({});
  2271. // 4. Let state be stream.[[state]].
  2272. auto state = stream.state();
  2273. // 5. Assert: stream.[[state]] is "writable" or "erroring".
  2274. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  2275. // 6. If state is "erroring",
  2276. if (state == WritableStream::State::Erroring) {
  2277. // 1. Set stream.[[storedError]] to undefined.
  2278. stream.set_stored_error(JS::js_undefined());
  2279. // 2. If stream.[[pendingAbortRequest]] is not undefined,
  2280. if (stream.pending_abort_request().has_value()) {
  2281. // 1. Resolve stream.[[pendingAbortRequest]]'s promise with undefined.
  2282. // 2. Set stream.[[pendingAbortRequest]] to undefined.
  2283. WebIDL::resolve_promise(realm, stream.pending_abort_request().release_value().promise, JS::js_undefined());
  2284. }
  2285. }
  2286. // 7. Set stream.[[state]] to "closed".
  2287. stream.set_state(WritableStream::State::Closed);
  2288. // 8. Let writer be stream.[[writer]].
  2289. auto writer = stream.writer();
  2290. // 9. If writer is not undefined, resolve writer.[[closedPromise]] with undefined.
  2291. if (writer)
  2292. WebIDL::resolve_promise(realm, *writer->closed_promise(), JS::js_undefined());
  2293. // 10. Assert: stream.[[pendingAbortRequest]] is undefined.
  2294. VERIFY(!stream.pending_abort_request().has_value());
  2295. // 11. Assert: stream.[[storedError]] is undefined.
  2296. VERIFY(stream.stored_error().is_undefined());
  2297. }
  2298. // https://streams.spec.whatwg.org/#writable-stream-finish-in-flight-close-with-error
  2299. WebIDL::ExceptionOr<void> writable_stream_finish_in_flight_close_with_error(WritableStream& stream, JS::Value error)
  2300. {
  2301. auto& realm = stream.realm();
  2302. // 1. Assert: stream.[[inFlightCloseRequest]] is not undefined.
  2303. VERIFY(stream.in_flight_close_request());
  2304. // 2. Reject stream.[[inFlightCloseRequest]] with error.
  2305. WebIDL::reject_promise(realm, *stream.in_flight_close_request(), error);
  2306. // 3. Set stream.[[inFlightCloseRequest]] to undefined.
  2307. stream.set_in_flight_close_request({});
  2308. // 4. Assert: stream.[[state]] is "writable" or "erroring".
  2309. auto state = stream.state();
  2310. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  2311. // 5. If stream.[[pendingAbortRequest]] is not undefined,
  2312. if (stream.pending_abort_request().has_value()) {
  2313. // 1. Reject stream.[[pendingAbortRequest]]'s promise with error.
  2314. // 2. Set stream.[[pendingAbortRequest]] to undefined.
  2315. WebIDL::reject_promise(realm, stream.pending_abort_request().release_value().promise, error);
  2316. }
  2317. // 6. Perform ! WritableStreamDealWithRejection(stream, error).
  2318. return writable_stream_deal_with_rejection(stream, error);
  2319. }
  2320. // https://streams.spec.whatwg.org/#writable-stream-finish-in-flight-write
  2321. void writable_stream_finish_in_flight_write(WritableStream& stream)
  2322. {
  2323. auto& realm = stream.realm();
  2324. // 1. Assert: stream.[[inFlightWriteRequest]] is not undefined.
  2325. VERIFY(stream.in_flight_write_request());
  2326. // 2. Resolve stream.[[inFlightWriteRequest]] with undefined.
  2327. WebIDL::resolve_promise(realm, *stream.in_flight_write_request(), JS::js_undefined());
  2328. // 3. Set stream.[[inFlightWriteRequest]] to undefined.
  2329. stream.set_in_flight_write_request({});
  2330. }
  2331. // https://streams.spec.whatwg.org/#writable-stream-finish-in-flight-write-with-error
  2332. WebIDL::ExceptionOr<void> writable_stream_finish_in_flight_write_with_error(WritableStream& stream, JS::Value error)
  2333. {
  2334. auto& realm = stream.realm();
  2335. // 1. Assert: stream.[[inFlightWriteRequest]] is not undefined.
  2336. VERIFY(stream.in_flight_write_request());
  2337. // 2. Reject stream.[[inFlightWriteRequest]] with error.
  2338. WebIDL::reject_promise(realm, *stream.in_flight_write_request(), error);
  2339. // 3. Set stream.[[inFlightWriteRequest]] to undefined.
  2340. stream.set_in_flight_write_request({});
  2341. // 4. Assert: stream.[[state]] is "writable" or "erroring".
  2342. auto state = stream.state();
  2343. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  2344. // 5. Perform ! WritableStreamDealWithRejection(stream, error).
  2345. return writable_stream_deal_with_rejection(stream, error);
  2346. }
  2347. // https://streams.spec.whatwg.org/#writable-stream-has-operation-marked-in-flight
  2348. bool writable_stream_has_operation_marked_in_flight(WritableStream const& stream)
  2349. {
  2350. // 1. If stream.[[inFlightWriteRequest]] is undefined and stream.[[inFlightCloseRequest]] is undefined, return false.
  2351. if (!stream.in_flight_write_request() && !stream.in_flight_close_request())
  2352. return false;
  2353. // 2. Return true.
  2354. return true;
  2355. }
  2356. // https://streams.spec.whatwg.org/#writable-stream-mark-close-request-in-flight
  2357. void writable_stream_mark_close_request_in_flight(WritableStream& stream)
  2358. {
  2359. // 1. Assert: stream.[[inFlightCloseRequest]] is undefined.
  2360. VERIFY(!stream.in_flight_close_request());
  2361. // 2. Assert: stream.[[closeRequest]] is not undefined.
  2362. VERIFY(stream.close_request());
  2363. // 3. Set stream.[[inFlightCloseRequest]] to stream.[[closeRequest]].
  2364. stream.set_in_flight_close_request(stream.close_request());
  2365. // 4. Set stream.[[closeRequest]] to undefined.
  2366. stream.set_close_request({});
  2367. }
  2368. // https://streams.spec.whatwg.org/#writable-stream-mark-first-write-request-in-flight
  2369. void writable_stream_mark_first_write_request_in_flight(WritableStream& stream)
  2370. {
  2371. // 1. Assert: stream.[[inFlightWriteRequest]] is undefined.
  2372. VERIFY(!stream.in_flight_write_request());
  2373. // 2. Assert: stream.[[writeRequests]] is not empty.
  2374. VERIFY(!stream.write_requests().is_empty());
  2375. // 3. Let writeRequest be stream.[[writeRequests]][0].
  2376. // 4. Remove writeRequest from stream.[[writeRequests]].
  2377. auto write_request = stream.write_requests().take_first();
  2378. // 5. Set stream.[[inFlightWriteRequest]] to writeRequest.
  2379. stream.set_in_flight_write_request(write_request);
  2380. }
  2381. // https://streams.spec.whatwg.org/#writable-stream-reject-close-and-closed-promise-if-needed
  2382. void writable_stream_reject_close_and_closed_promise_if_needed(WritableStream& stream)
  2383. {
  2384. auto& realm = stream.realm();
  2385. // 1. Assert: stream.[[state]] is "errored".
  2386. VERIFY(stream.state() == WritableStream::State::Errored);
  2387. // 2. If stream.[[closeRequest]] is not undefined,
  2388. if (stream.close_request()) {
  2389. // 1. Assert: stream.[[inFlightCloseRequest]] is undefined.
  2390. VERIFY(!stream.in_flight_close_request());
  2391. // 2. Reject stream.[[closeRequest]] with stream.[[storedError]].
  2392. WebIDL::reject_promise(realm, *stream.close_request(), stream.stored_error());
  2393. // 3. Set stream.[[closeRequest]] to undefined.
  2394. stream.set_close_request({});
  2395. }
  2396. // 3. Let writer be stream.[[writer]].
  2397. auto writer = stream.writer();
  2398. // 4. If writer is not undefined,
  2399. if (writer) {
  2400. // 1. Reject writer.[[closedPromise]] with stream.[[storedError]].
  2401. WebIDL::reject_promise(realm, *writer->closed_promise(), stream.stored_error());
  2402. // 2. Set writer.[[closedPromise]].[[PromiseIsHandled]] to true.
  2403. WebIDL::mark_promise_as_handled(*writer->closed_promise());
  2404. }
  2405. }
  2406. // https://streams.spec.whatwg.org/#writable-stream-start-erroring
  2407. WebIDL::ExceptionOr<void> writable_stream_start_erroring(WritableStream& stream, JS::Value reason)
  2408. {
  2409. // 1. Assert: stream.[[storedError]] is undefined.
  2410. VERIFY(stream.stored_error().is_undefined());
  2411. // 2. Assert: stream.[[state]] is "writable".
  2412. VERIFY(stream.state() == WritableStream::State::Writable);
  2413. // 3. Let controller be stream.[[controller]].
  2414. auto controller = stream.controller();
  2415. // 4. Assert: controller is not undefined.
  2416. VERIFY(controller);
  2417. // 5. Set stream.[[state]] to "erroring".
  2418. stream.set_state(WritableStream::State::Erroring);
  2419. // 6. Set stream.[[storedError]] to reason.
  2420. stream.set_stored_error(reason);
  2421. // 7. Let writer be stream.[[writer]].
  2422. auto writer = stream.writer();
  2423. // 8. If writer is not undefined, perform ! WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason).
  2424. if (writer)
  2425. writable_stream_default_writer_ensure_ready_promise_rejected(*writer, reason);
  2426. // 9. If ! WritableStreamHasOperationMarkedInFlight(stream) is false and controller.[[started]] is true, perform ! WritableStreamFinishErroring(stream).
  2427. if (!writable_stream_has_operation_marked_in_flight(stream) && controller->started())
  2428. TRY(writable_stream_finish_erroring(stream));
  2429. return {};
  2430. }
  2431. // https://streams.spec.whatwg.org/#writable-stream-update-backpressure
  2432. void writable_stream_update_backpressure(WritableStream& stream, bool backpressure)
  2433. {
  2434. auto& realm = stream.realm();
  2435. // 1. Assert: stream.[[state]] is "writable".
  2436. VERIFY(stream.state() == WritableStream::State::Writable);
  2437. // 2. Assert: ! WritableStreamCloseQueuedOrInFlight(stream) is false.
  2438. VERIFY(!writable_stream_close_queued_or_in_flight(stream));
  2439. // 3. Let writer be stream.[[writer]].
  2440. auto writer = stream.writer();
  2441. // 4. If writer is not undefined and backpressure is not stream.[[backpressure]],
  2442. if (writer && backpressure != stream.backpressure()) {
  2443. // 1. If backpressure is true, set writer.[[readyPromise]] to a new promise.
  2444. if (backpressure) {
  2445. writer->set_ready_promise(WebIDL::create_promise(realm));
  2446. }
  2447. // 2. Otherwise,
  2448. else {
  2449. // 1. Assert: backpressure is false.
  2450. // 2. Resolve writer.[[readyPromise]] with undefined.
  2451. WebIDL::resolve_promise(realm, *writer->ready_promise(), JS::js_undefined());
  2452. }
  2453. }
  2454. // 5. Set stream.[[backpressure]] to backpressure.
  2455. stream.set_backpressure(backpressure);
  2456. }
  2457. // https://streams.spec.whatwg.org/#writable-stream-default-writer-abort
  2458. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> writable_stream_default_writer_abort(WritableStreamDefaultWriter& writer, JS::Value reason)
  2459. {
  2460. // 1. Let stream be writer.[[stream]].
  2461. auto stream = writer.stream();
  2462. // 2. Assert: stream is not undefined.
  2463. VERIFY(stream);
  2464. // 3. Return ! WritableStreamAbort(stream, reason).
  2465. return writable_stream_abort(*stream, reason);
  2466. }
  2467. // https://streams.spec.whatwg.org/#writable-stream-default-writer-close
  2468. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> writable_stream_default_writer_close(WritableStreamDefaultWriter& writer)
  2469. {
  2470. // 1. Let stream be writer.[[stream]].
  2471. auto stream = writer.stream();
  2472. // 2. Assert: stream is not undefined.
  2473. VERIFY(stream);
  2474. // 3. Return ! WritableStreamClose(stream).
  2475. return writable_stream_close(*stream);
  2476. }
  2477. // https://streams.spec.whatwg.org/#writable-stream-default-writer-ensure-closed-promise-rejected
  2478. void writable_stream_default_writer_ensure_closed_promise_rejected(WritableStreamDefaultWriter& writer, JS::Value error)
  2479. {
  2480. auto& realm = writer.realm();
  2481. // 1. If writer.[[closedPromise]].[[PromiseState]] is "pending", reject writer.[[closedPromise]] with error.
  2482. auto& closed_promise = verify_cast<JS::Promise>(*writer.closed_promise()->promise());
  2483. if (closed_promise.state() == JS::Promise::State::Pending) {
  2484. WebIDL::reject_promise(realm, *writer.closed_promise(), error);
  2485. }
  2486. // 2. Otherwise, set writer.[[closedPromise]] to a promise rejected with error.
  2487. else {
  2488. writer.set_closed_promise(WebIDL::create_rejected_promise(realm, error));
  2489. }
  2490. // 3. Set writer.[[closedPromise]].[[PromiseIsHandled]] to true.
  2491. WebIDL::mark_promise_as_handled(*writer.closed_promise());
  2492. }
  2493. // https://streams.spec.whatwg.org/#writable-stream-default-writer-ensure-ready-promise-rejected
  2494. void writable_stream_default_writer_ensure_ready_promise_rejected(WritableStreamDefaultWriter& writer, JS::Value error)
  2495. {
  2496. auto& realm = writer.realm();
  2497. // 1. If writer.[[readyPromise]].[[PromiseState]] is "pending", reject writer.[[readyPromise]] with error.
  2498. auto& ready_promise = verify_cast<JS::Promise>(*writer.ready_promise()->promise());
  2499. if (ready_promise.state() == JS::Promise::State::Pending) {
  2500. WebIDL::reject_promise(realm, *writer.ready_promise(), error);
  2501. }
  2502. // 2. Otherwise, set writer.[[readyPromise]] to a promise rejected with error.
  2503. else {
  2504. writer.set_ready_promise(WebIDL::create_rejected_promise(realm, error));
  2505. }
  2506. // 3. Set writer.[[readyPromise]].[[PromiseIsHandled]] to true.
  2507. WebIDL::mark_promise_as_handled(*writer.ready_promise());
  2508. }
  2509. // https://streams.spec.whatwg.org/#writable-stream-default-writer-get-desired-size
  2510. Optional<double> writable_stream_default_writer_get_desired_size(WritableStreamDefaultWriter const& writer)
  2511. {
  2512. // 1. Let stream be writer.[[stream]].
  2513. auto stream = writer.stream();
  2514. // 2. Let state be stream.[[state]].
  2515. auto state = stream->state();
  2516. // 3. If state is "errored" or "erroring", return null.
  2517. if (state == WritableStream::State::Errored || state == WritableStream::State::Erroring)
  2518. return {};
  2519. // 4. If state is "closed", return 0.
  2520. if (state == WritableStream::State::Closed)
  2521. return 0.0;
  2522. // 5. Return ! WritableStreamDefaultControllerGetDesiredSize(stream.[[controller]]).
  2523. return writable_stream_default_controller_get_desired_size(*stream->controller());
  2524. }
  2525. // https://streams.spec.whatwg.org/#writable-stream-default-writer-release
  2526. WebIDL::ExceptionOr<void> writable_stream_default_writer_release(WritableStreamDefaultWriter& writer)
  2527. {
  2528. auto& realm = writer.realm();
  2529. // 1. Let stream be writer.[[stream]].
  2530. auto stream = writer.stream();
  2531. // 2. Assert: stream is not undefined.
  2532. VERIFY(stream);
  2533. // 3. Assert: stream.[[writer]] is writer.
  2534. VERIFY(stream->writer().ptr() == &writer);
  2535. // 4. Let releasedError be a new TypeError.
  2536. auto released_error = JS::TypeError::create(realm, "Writer's stream lock has been released"sv);
  2537. // 5. Perform ! WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError).
  2538. writable_stream_default_writer_ensure_ready_promise_rejected(writer, released_error);
  2539. // 6. Perform ! WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError).
  2540. writable_stream_default_writer_ensure_closed_promise_rejected(writer, released_error);
  2541. // 7. Set stream.[[writer]] to undefined.
  2542. stream->set_writer({});
  2543. // 8. Set writer.[[stream]] to undefined.
  2544. writer.set_stream({});
  2545. return {};
  2546. }
  2547. // https://streams.spec.whatwg.org/#writable-stream-default-writer-write
  2548. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> writable_stream_default_writer_write(WritableStreamDefaultWriter& writer, JS::Value chunk)
  2549. {
  2550. auto& realm = writer.realm();
  2551. // 1. Let stream be writer.[[stream]].
  2552. auto stream = writer.stream();
  2553. // 2. Assert: stream is not undefined.
  2554. VERIFY(stream);
  2555. // 3. Let controller be stream.[[controller]].
  2556. auto controller = stream->controller();
  2557. // 4. Let chunkSize be ! WritableStreamDefaultControllerGetChunkSize(controller, chunk).
  2558. auto chunk_size = TRY(writable_stream_default_controller_get_chunk_size(*controller, chunk));
  2559. // 5. If stream is not equal to writer.[[stream]], return a promise rejected with a TypeError exception.
  2560. if (stream.ptr() != writer.stream().ptr()) {
  2561. auto exception = JS::TypeError::create(realm, "Writer's locked stream changed during write"sv);
  2562. return WebIDL::create_rejected_promise(realm, exception);
  2563. }
  2564. // 6. Let state be stream.[[state]].
  2565. auto state = stream->state();
  2566. // 7. If state is "errored", return a promise rejected with stream.[[storedError]].
  2567. if (state == WritableStream::State::Errored)
  2568. return WebIDL::create_rejected_promise(realm, stream->stored_error());
  2569. // 8. If ! WritableStreamCloseQueuedOrInFlight(stream) is true or state is "closed", return a promise rejected with a TypeError exception indicating that the stream is closing or closed.
  2570. if (writable_stream_close_queued_or_in_flight(*stream) || state == WritableStream::State::Closed) {
  2571. auto exception = JS::TypeError::create(realm, "Cannot write to a writer whose stream is closing or already closed"sv);
  2572. return WebIDL::create_rejected_promise(realm, exception);
  2573. }
  2574. // 9. If state is "erroring", return a promise rejected with stream.[[storedError]].
  2575. if (state == WritableStream::State::Erroring)
  2576. return WebIDL::create_rejected_promise(realm, stream->stored_error());
  2577. // 10. Assert: state is "writable".
  2578. VERIFY(state == WritableStream::State::Writable);
  2579. // 11. Let promise be ! WritableStreamAddWriteRequest(stream).
  2580. auto promise = writable_stream_add_write_request(*stream);
  2581. // 12. Perform ! WritableStreamDefaultControllerWrite(controller, chunk, chunkSize).
  2582. TRY(writable_stream_default_controller_write(*controller, chunk, chunk_size));
  2583. // 13. Return promise.
  2584. return promise;
  2585. }
  2586. // https://streams.spec.whatwg.org/#set-up-writable-stream-default-controller
  2587. WebIDL::ExceptionOr<void> set_up_writable_stream_default_controller(WritableStream& stream, WritableStreamDefaultController& controller, JS::NonnullGCPtr<StartAlgorithm> start_algorithm, JS::NonnullGCPtr<WriteAlgorithm> write_algorithm, JS::NonnullGCPtr<CloseAlgorithm> close_algorithm, JS::NonnullGCPtr<AbortAlgorithm> abort_algorithm, double high_water_mark, JS::NonnullGCPtr<SizeAlgorithm> size_algorithm)
  2588. {
  2589. auto& realm = stream.realm();
  2590. // 1. Assert: stream implements WritableStream.
  2591. // 2. Assert: stream.[[controller]] is undefined.
  2592. VERIFY(!stream.controller());
  2593. // 3. Set controller.[[stream]] to stream.
  2594. controller.set_stream(stream);
  2595. // 4. Set stream.[[controller]] to controller.
  2596. stream.set_controller(controller);
  2597. // 5. Perform ! ResetQueue(controller).
  2598. reset_queue(controller);
  2599. // 6. Set controller.[[signal]] to a new AbortSignal.
  2600. controller.set_signal(realm.heap().allocate<DOM::AbortSignal>(realm, realm));
  2601. // 7. Set controller.[[started]] to false.
  2602. controller.set_started(false);
  2603. // 8. Set controller.[[strategySizeAlgorithm]] to sizeAlgorithm.
  2604. controller.set_strategy_size_algorithm(size_algorithm);
  2605. // 9. Set controller.[[strategyHWM]] to highWaterMark.
  2606. controller.set_strategy_hwm(high_water_mark);
  2607. // 10. Set controller.[[writeAlgorithm]] to writeAlgorithm.
  2608. controller.set_write_algorithm(write_algorithm);
  2609. // 11. Set controller.[[closeAlgorithm]] to closeAlgorithm.
  2610. controller.set_close_algorithm(close_algorithm);
  2611. // 12. Set controller.[[abortAlgorithm]] to abortAlgorithm.
  2612. controller.set_abort_algorithm(abort_algorithm);
  2613. // 13. Let backpressure be ! WritableStreamDefaultControllerGetBackpressure(controller).
  2614. auto backpressure = writable_stream_default_controller_get_backpressure(controller);
  2615. // 14. Perform ! WritableStreamUpdateBackpressure(stream, backpressure).
  2616. writable_stream_update_backpressure(stream, backpressure);
  2617. // 15. Let startResult be the result of performing startAlgorithm. (This may throw an exception.)
  2618. auto start_result = TRY(start_algorithm->function()());
  2619. // 16. Let startPromise be a promise resolved with startResult.
  2620. auto start_promise = WebIDL::create_resolved_promise(realm, start_result);
  2621. // 17. Upon fulfillment of startPromise,
  2622. WebIDL::upon_fulfillment(*start_promise, [&](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  2623. // 1. Assert: stream.[[state]] is "writable" or "erroring".
  2624. auto state = stream.state();
  2625. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  2626. // 2. Set controller.[[started]] to true.
  2627. controller.set_started(true);
  2628. // 3. Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).
  2629. TRY(writable_stream_default_controller_advance_queue_if_needed(controller));
  2630. return JS::js_undefined();
  2631. });
  2632. // 18. Upon rejection of startPromise with reason r,
  2633. WebIDL::upon_rejection(*start_promise, [&](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {
  2634. // 1. Assert: stream.[[state]] is "writable" or "erroring".
  2635. auto state = stream.state();
  2636. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  2637. // 2. Set controller.[[started]] to true.
  2638. controller.set_started(true);
  2639. // 3. Perform ! WritableStreamDealWithRejection(stream, r).
  2640. TRY(writable_stream_deal_with_rejection(stream, reason));
  2641. return JS::js_undefined();
  2642. });
  2643. return {};
  2644. }
  2645. // https://streams.spec.whatwg.org/#set-up-writable-stream-default-controller-from-underlying-sink
  2646. WebIDL::ExceptionOr<void> set_up_writable_stream_default_controller_from_underlying_sink(WritableStream& stream, JS::Value underlying_sink_value, UnderlyingSink& underlying_sink, double high_water_mark, JS::NonnullGCPtr<SizeAlgorithm> size_algorithm)
  2647. {
  2648. auto& realm = stream.realm();
  2649. // 1. Let controller be a new WritableStreamDefaultController.
  2650. auto controller = realm.heap().allocate<WritableStreamDefaultController>(realm, realm);
  2651. // 2. Let startAlgorithm be an algorithm that returns undefined.
  2652. auto start_algorithm = JS::create_heap_function(realm.heap(), []() -> WebIDL::ExceptionOr<JS::Value> { return JS::js_undefined(); });
  2653. // 3. Let writeAlgorithm be an algorithm that returns a promise resolved with undefined.
  2654. auto write_algorithm = JS::create_heap_function(realm.heap(), [&realm](JS::Value) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  2655. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  2656. });
  2657. // 4. Let closeAlgorithm be an algorithm that returns a promise resolved with undefined.
  2658. auto close_algorithm = JS::create_heap_function(realm.heap(), [&realm]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  2659. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  2660. });
  2661. // 5. Let abortAlgorithm be an algorithm that returns a promise resolved with undefined.
  2662. auto abort_algorithm = JS::create_heap_function(realm.heap(), [&realm](JS::Value) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  2663. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  2664. });
  2665. // 6. If underlyingSinkDict["start"] exists, then set startAlgorithm to an algorithm which returns the result of invoking underlyingSinkDict["start"] with argument list « controller » and callback this value underlyingSink.
  2666. if (underlying_sink.start) {
  2667. start_algorithm = JS::create_heap_function(realm.heap(), [controller, underlying_sink_value, callback = underlying_sink.start]() -> WebIDL::ExceptionOr<JS::Value> {
  2668. // Note: callback does not return a promise, so invoke_callback may return an abrupt completion
  2669. return TRY(WebIDL::invoke_callback(*callback, underlying_sink_value, controller)).release_value();
  2670. });
  2671. }
  2672. // 7. If underlyingSinkDict["write"] exists, then set writeAlgorithm to an algorithm which takes an argument chunk and returns the result of invoking underlyingSinkDict["write"] with argument list « chunk, controller » and callback this value underlyingSink.
  2673. if (underlying_sink.write) {
  2674. write_algorithm = JS::create_heap_function(realm.heap(), [&realm, controller, underlying_sink_value, callback = underlying_sink.write](JS::Value chunk) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  2675. // Note: callback return a promise, so invoke_callback will never return an abrupt completion
  2676. auto result = MUST_OR_THROW_OOM(WebIDL::invoke_callback(*callback, underlying_sink_value, chunk, controller)).release_value();
  2677. return WebIDL::create_resolved_promise(realm, result);
  2678. });
  2679. }
  2680. // 8. If underlyingSinkDict["close"] exists, then set closeAlgorithm to an algorithm which returns the result of invoking underlyingSinkDict["close"] with argument list «» and callback this value underlyingSink.
  2681. if (underlying_sink.close) {
  2682. close_algorithm = JS::create_heap_function(realm.heap(), [&realm, underlying_sink_value, callback = underlying_sink.close]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  2683. // Note: callback return a promise, so invoke_callback will never return an abrupt completion
  2684. auto result = MUST_OR_THROW_OOM(WebIDL::invoke_callback(*callback, underlying_sink_value)).release_value();
  2685. return WebIDL::create_resolved_promise(realm, result);
  2686. });
  2687. }
  2688. // 9. If underlyingSinkDict["abort"] exists, then set abortAlgorithm to an algorithm which takes an argument reason and returns the result of invoking underlyingSinkDict["abort"] with argument list « reason » and callback this value underlyingSink.
  2689. if (underlying_sink.abort) {
  2690. abort_algorithm = JS::create_heap_function(realm.heap(), [&realm, underlying_sink_value, callback = underlying_sink.abort](JS::Value reason) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  2691. // Note: callback return a promise, so invoke_callback will never return an abrupt completion
  2692. auto result = MUST_OR_THROW_OOM(WebIDL::invoke_callback(*callback, underlying_sink_value, reason)).release_value();
  2693. return WebIDL::create_resolved_promise(realm, result);
  2694. });
  2695. }
  2696. // 10. Perform ? SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm).
  2697. TRY(set_up_writable_stream_default_controller(stream, controller, start_algorithm, write_algorithm, close_algorithm, abort_algorithm, high_water_mark, size_algorithm));
  2698. return {};
  2699. }
  2700. // https://streams.spec.whatwg.org/#writable-stream-default-controller-advance-queue-if-needed
  2701. WebIDL::ExceptionOr<void> writable_stream_default_controller_advance_queue_if_needed(WritableStreamDefaultController& controller)
  2702. {
  2703. // 1. Let stream be controller.[[stream]].
  2704. auto stream = controller.stream();
  2705. // 2. If controller.[[started]] is false, return.
  2706. if (!controller.started())
  2707. return {};
  2708. // 3. If stream.[[inFlightWriteRequest]] is not undefined, return.
  2709. if (stream->in_flight_write_request())
  2710. return {};
  2711. // 4. Let state be stream.[[state]].
  2712. auto state = stream->state();
  2713. // 5. Assert: state is not "closed" or "errored".
  2714. VERIFY(state != WritableStream::State::Closed && state != WritableStream::State::Errored);
  2715. // 6. If state is "erroring",
  2716. if (state == WritableStream::State::Erroring) {
  2717. // 1. Perform ! WritableStreamFinishErroring(stream).
  2718. // 2. Return.
  2719. return writable_stream_finish_erroring(*stream);
  2720. }
  2721. // 7. If controller.[[queue]] is empty, return.
  2722. if (controller.queue().is_empty())
  2723. return {};
  2724. // 8. Let value be ! PeekQueueValue(controller).
  2725. auto value = peek_queue_value(controller);
  2726. // 9. If value is the close sentinel, perform ! WritableStreamDefaultControllerProcessClose(controller).
  2727. if (is_close_sentinel(value)) {
  2728. TRY(writable_stream_default_controller_process_close(controller));
  2729. }
  2730. // 10. Otherwise, perform ! WritableStreamDefaultControllerProcessWrite(controller, value).
  2731. else {
  2732. TRY(writable_stream_default_controller_process_write(controller, value));
  2733. }
  2734. return {};
  2735. }
  2736. // https://streams.spec.whatwg.org/#writable-stream-default-controller-clear-algorithms
  2737. void writable_stream_default_controller_clear_algorithms(WritableStreamDefaultController& controller)
  2738. {
  2739. // 1. Set controller.[[writeAlgorithm]] to undefined.
  2740. controller.set_write_algorithm({});
  2741. // 2. Set controller.[[closeAlgorithm]] to undefined.
  2742. controller.set_close_algorithm({});
  2743. // 3. Set controller.[[abortAlgorithm]] to undefined.
  2744. controller.set_abort_algorithm({});
  2745. // 4. Set controller.[[strategySizeAlgorithm]] to undefined.
  2746. controller.set_strategy_size_algorithm({});
  2747. }
  2748. // https://streams.spec.whatwg.org/#writable-stream-default-controller-close
  2749. WebIDL::ExceptionOr<void> writable_stream_default_controller_close(WritableStreamDefaultController& controller)
  2750. {
  2751. // 1. Perform ! EnqueueValueWithSize(controller, close sentinel, 0).
  2752. TRY(enqueue_value_with_size(controller, create_close_sentinel(), JS::Value(0.0)));
  2753. // 2. Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).
  2754. TRY(writable_stream_default_controller_advance_queue_if_needed(controller));
  2755. return {};
  2756. }
  2757. // https://streams.spec.whatwg.org/#writable-stream-default-controller-error
  2758. WebIDL::ExceptionOr<void> writable_stream_default_controller_error(WritableStreamDefaultController& controller, JS::Value error)
  2759. {
  2760. // 1. Let stream be controller.[[stream]].
  2761. auto stream = controller.stream();
  2762. // 2. Assert: stream.[[state]] is "writable".
  2763. VERIFY(stream->state() == WritableStream::State::Writable);
  2764. // 3. Perform ! WritableStreamDefaultControllerClearAlgorithms(controller).
  2765. writable_stream_default_controller_clear_algorithms(controller);
  2766. // 4. Perform ! WritableStreamStartErroring(stream, error).
  2767. return writable_stream_start_erroring(stream, error);
  2768. }
  2769. // https://streams.spec.whatwg.org/#writable-stream-default-controller-error-if-needed
  2770. WebIDL::ExceptionOr<void> writable_stream_default_controller_error_if_needed(WritableStreamDefaultController& controller, JS::Value error)
  2771. {
  2772. // 1. If controller.[[stream]].[[state]] is "writable", perform ! WritableStreamDefaultControllerError(controller, error).
  2773. if (controller.stream()->state() == WritableStream::State::Writable)
  2774. TRY(writable_stream_default_controller_error(controller, error));
  2775. return {};
  2776. }
  2777. // https://streams.spec.whatwg.org/#writable-stream-default-controller-get-backpressure
  2778. bool writable_stream_default_controller_get_backpressure(WritableStreamDefaultController const& controller)
  2779. {
  2780. // 1. Let desiredSize be ! WritableStreamDefaultControllerGetDesiredSize(controller).
  2781. auto desired_size = writable_stream_default_controller_get_desired_size(controller);
  2782. // 2. Return true if desiredSize ≤ 0, or false otherwise.
  2783. return desired_size <= 0.0;
  2784. }
  2785. // https://streams.spec.whatwg.org/#writable-stream-default-controller-get-chunk-size
  2786. WebIDL::ExceptionOr<JS::Value> writable_stream_default_controller_get_chunk_size(WritableStreamDefaultController& controller, JS::Value chunk)
  2787. {
  2788. // 1. Let returnValue be the result of performing controller.[[strategySizeAlgorithm]], passing in chunk, and interpreting the result as a completion record.
  2789. auto return_value = controller.strategy_size_algorithm()->function()(chunk);
  2790. // 2. If returnValue is an abrupt completion,
  2791. if (return_value.is_abrupt()) {
  2792. // 1. Perform ! WritableStreamDefaultControllerErrorIfNeeded(controller, returnValue.[[Value]]).
  2793. TRY(writable_stream_default_controller_error_if_needed(controller, *return_value.release_value()));
  2794. // 2. Return 1.
  2795. return 1.0;
  2796. }
  2797. // 3. Return returnValue.[[Value]].
  2798. return *return_value.release_value();
  2799. }
  2800. // https://streams.spec.whatwg.org/#writable-stream-default-controller-get-desired-size
  2801. double writable_stream_default_controller_get_desired_size(WritableStreamDefaultController const& controller)
  2802. {
  2803. // 1. Return controller.[[strategyHWM]] − controller.[[queueTotalSize]].
  2804. return controller.strategy_hwm() - controller.queue_total_size();
  2805. }
  2806. // https://streams.spec.whatwg.org/#writable-stream-default-controller-process-close
  2807. WebIDL::ExceptionOr<void> writable_stream_default_controller_process_close(WritableStreamDefaultController& controller)
  2808. {
  2809. // 1. Let stream be controller.[[stream]].
  2810. auto stream = controller.stream();
  2811. // 2. Perform ! WritableStreamMarkCloseRequestInFlight(stream).
  2812. writable_stream_mark_close_request_in_flight(*stream);
  2813. // 3. Perform ! DequeueValue(controller).
  2814. dequeue_value(controller);
  2815. // 4. Assert: controller.[[queue]] is empty.
  2816. VERIFY(controller.queue().is_empty());
  2817. // 5. Let sinkClosePromise be the result of performing controller.[[closeAlgorithm]].
  2818. auto sink_close_promise = TRY(controller.close_algorithm()->function()());
  2819. // 6. Perform ! WritableStreamDefaultControllerClearAlgorithms(controller).
  2820. writable_stream_default_controller_clear_algorithms(controller);
  2821. // 7. Upon fulfillment of sinkClosePromise,
  2822. WebIDL::upon_fulfillment(*sink_close_promise, [&, stream = stream](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  2823. // 1. Perform ! WritableStreamFinishInFlightClose(stream).
  2824. writable_stream_finish_in_flight_close(*stream);
  2825. return JS::js_undefined();
  2826. });
  2827. // 8. Upon rejection of sinkClosePromise with reason reason,
  2828. WebIDL::upon_rejection(*sink_close_promise, [&, stream = stream](auto const& reason) -> WebIDL::ExceptionOr<JS::Value> {
  2829. // 1. Perform ! WritableStreamFinishInFlightCloseWithError(stream, reason).
  2830. TRY(writable_stream_finish_in_flight_close_with_error(*stream, reason));
  2831. return JS::js_undefined();
  2832. });
  2833. return {};
  2834. }
  2835. // https://streams.spec.whatwg.org/#writable-stream-default-controller-process-write
  2836. WebIDL::ExceptionOr<void> writable_stream_default_controller_process_write(WritableStreamDefaultController& controller, JS::Value chunk)
  2837. {
  2838. // 1. Let stream be controller.[[stream]].
  2839. auto stream = controller.stream();
  2840. // 2. Perform ! WritableStreamMarkFirstWriteRequestInFlight(stream).
  2841. writable_stream_mark_first_write_request_in_flight(*stream);
  2842. // 3. Let sinkWritePromise be the result of performing controller.[[writeAlgorithm]], passing in chunk.
  2843. auto sink_write_promise = TRY(controller.write_algorithm()->function()(chunk));
  2844. // 4. Upon fulfillment of sinkWritePromise,
  2845. WebIDL::upon_fulfillment(*sink_write_promise, [&, stream = stream](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  2846. // 1. Perform ! WritableStreamFinishInFlightWrite(stream).
  2847. writable_stream_finish_in_flight_write(*stream);
  2848. // 2. Let state be stream.[[state]].
  2849. auto state = stream->state();
  2850. // 3. Assert: state is "writable" or "erroring".
  2851. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  2852. // 4. Perform ! DequeueValue(controller).
  2853. dequeue_value(controller);
  2854. // 5. If ! WritableStreamCloseQueuedOrInFlight(stream) is false and state is "writable",
  2855. if (!writable_stream_close_queued_or_in_flight(*stream) && state == WritableStream::State::Writable) {
  2856. // 1. Let backpressure be ! WritableStreamDefaultControllerGetBackpressure(controller).
  2857. auto backpressure = writable_stream_default_controller_get_backpressure(controller);
  2858. // 2. Perform ! WritableStreamUpdateBackpressure(stream, backpressure).
  2859. writable_stream_update_backpressure(*stream, backpressure);
  2860. }
  2861. // 6 .Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).
  2862. TRY(writable_stream_default_controller_advance_queue_if_needed(controller));
  2863. return JS::js_undefined();
  2864. });
  2865. // 5. Upon rejection of sinkWritePromise with reason,
  2866. WebIDL::upon_rejection(*sink_write_promise, [&, stream = stream](auto const& reason) -> WebIDL::ExceptionOr<JS::Value> {
  2867. // 1. If stream.[[state]] is "writable", perform ! WritableStreamDefaultControllerClearAlgorithms(controller).
  2868. if (stream->state() == WritableStream::State::Writable)
  2869. writable_stream_default_controller_clear_algorithms(controller);
  2870. // 2. Perform ! WritableStreamFinishInFlightWriteWithError(stream, reason).
  2871. TRY(writable_stream_finish_in_flight_write_with_error(*stream, reason));
  2872. return JS::js_undefined();
  2873. });
  2874. return {};
  2875. }
  2876. // https://streams.spec.whatwg.org/#writable-stream-default-controller-write
  2877. WebIDL::ExceptionOr<void> writable_stream_default_controller_write(WritableStreamDefaultController& controller, JS::Value chunk, JS::Value chunk_size)
  2878. {
  2879. auto& vm = controller.vm();
  2880. // 1. Let enqueueResult be EnqueueValueWithSize(controller, chunk, chunkSize).
  2881. auto enqueue_result = enqueue_value_with_size(controller, chunk, chunk_size);
  2882. // 2. If enqueueResult is an abrupt completion,
  2883. if (enqueue_result.is_exception()) {
  2884. auto throw_completion = Bindings::throw_dom_exception_if_needed(vm, [&] { return enqueue_result; }).throw_completion();
  2885. // 1. Perform ! WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueResult.[[Value]]).
  2886. TRY(writable_stream_default_controller_error_if_needed(controller, *throw_completion.release_value()));
  2887. // 2. Return.
  2888. return {};
  2889. }
  2890. // 3. Let stream be controller.[[stream]].
  2891. auto stream = controller.stream();
  2892. // 4. If ! WritableStreamCloseQueuedOrInFlight(stream) is false and stream.[[state]] is "writable",
  2893. if (!writable_stream_close_queued_or_in_flight(*stream) && stream->state() == WritableStream::State::Writable) {
  2894. // 1. Let backpressure be ! WritableStreamDefaultControllerGetBackpressure(controller).
  2895. auto backpressure = writable_stream_default_controller_get_backpressure(controller);
  2896. // 2. Perform ! WritableStreamUpdateBackpressure(stream, backpressure).
  2897. writable_stream_update_backpressure(*stream, backpressure);
  2898. }
  2899. // 5. Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).
  2900. TRY(writable_stream_default_controller_advance_queue_if_needed(controller));
  2901. return {};
  2902. }
  2903. // https://streams.spec.whatwg.org/#initialize-transform-stream
  2904. WebIDL::ExceptionOr<void> initialize_transform_stream(TransformStream& stream, JS::NonnullGCPtr<JS::PromiseCapability> start_promise, double writable_high_water_mark, JS::NonnullGCPtr<SizeAlgorithm> writable_size_algorithm, double readable_high_water_mark, JS::NonnullGCPtr<SizeAlgorithm> readable_size_algorithm)
  2905. {
  2906. auto& realm = stream.realm();
  2907. // 1. Let startAlgorithm be an algorithm that returns startPromise.
  2908. auto writable_start_algorithm = JS::create_heap_function(realm.heap(), [start_promise]() -> WebIDL::ExceptionOr<JS::Value> {
  2909. return start_promise->promise();
  2910. });
  2911. auto readable_start_algorithm = JS::create_heap_function(realm.heap(), [start_promise]() -> WebIDL::ExceptionOr<JS::Value> {
  2912. return start_promise->promise();
  2913. });
  2914. // 2. Let writeAlgorithm be the following steps, taking a chunk argument:
  2915. auto write_algorithm = JS::create_heap_function(realm.heap(), [&stream](JS::Value chunk) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  2916. // 1. Return ! TransformStreamDefaultSinkWriteAlgorithm(stream, chunk).
  2917. return transform_stream_default_sink_write_algorithm(stream, chunk);
  2918. });
  2919. // 3. Let abortAlgorithm be the following steps, taking a reason argument:
  2920. auto abort_algorithm = JS::create_heap_function(realm.heap(), [&stream](JS::Value reason) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  2921. // 1. Return ! TransformStreamDefaultSinkAbortAlgorithm(stream, reason).
  2922. return transform_stream_default_sink_abort_algorithm(stream, reason);
  2923. });
  2924. // 4. Let closeAlgorithm be the following steps:
  2925. auto close_algorithm = JS::create_heap_function(realm.heap(), [&stream]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  2926. // 1. Return ! TransformStreamDefaultSinkCloseAlgorithm(stream).
  2927. return transform_stream_default_sink_close_algorithm(stream);
  2928. });
  2929. // 5. Set stream.[[writable]] to ! CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm).
  2930. stream.set_writable(TRY(create_writable_stream(realm, writable_start_algorithm, write_algorithm, close_algorithm, abort_algorithm, writable_high_water_mark, writable_size_algorithm)));
  2931. // 6. Let pullAlgorithm be the following steps:
  2932. auto pull_algorithm = JS::create_heap_function(realm.heap(), [&stream]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  2933. // 1. Return ! TransformStreamDefaultSourcePullAlgorithm(stream).
  2934. return transform_stream_default_source_pull_algorithm(stream);
  2935. });
  2936. // 7. Let cancelAlgorithm be the following steps, taking a reason argument:
  2937. auto cancel_algorithm = JS::create_heap_function(realm.heap(), [&stream, &realm](JS::Value reason) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  2938. // 1. Perform ! TransformStreamErrorWritableAndUnblockWrite(stream, reason).
  2939. TRY(transform_stream_error_writable_and_unblock_write(stream, reason));
  2940. // 2. Return a promise resolved with undefined.
  2941. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  2942. });
  2943. // 8. Set stream.[[readable]] to ! CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm).
  2944. stream.set_readable(TRY(create_readable_stream(realm, readable_start_algorithm, pull_algorithm, cancel_algorithm, readable_high_water_mark, readable_size_algorithm)));
  2945. // 9. Set stream.[[backpressure]] and stream.[[backpressureChangePromise]] to undefined.
  2946. stream.set_backpressure({});
  2947. stream.set_backpressure_change_promise({});
  2948. // 10. Perform ! TransformStreamSetBackpressure(stream, true).
  2949. TRY(transform_stream_set_backpressure(stream, true));
  2950. // 11. Set stream.[[controller]] to undefined.
  2951. stream.set_controller({});
  2952. return {};
  2953. }
  2954. // https://streams.spec.whatwg.org/#set-up-transform-stream-default-controller
  2955. void set_up_transform_stream_default_controller(TransformStream& stream, TransformStreamDefaultController& controller, JS::NonnullGCPtr<TransformAlgorithm> transform_algorithm, JS::NonnullGCPtr<FlushAlgorithm> flush_algorithm)
  2956. {
  2957. // 1. Assert: stream implements TransformStream.
  2958. // 2. Assert: stream.[[controller]] is undefined.
  2959. VERIFY(!stream.controller());
  2960. // 3. Set controller.[[stream]] to stream.
  2961. controller.set_stream(stream);
  2962. // 4. Set stream.[[controller]] to controller.
  2963. stream.set_controller(controller);
  2964. // 5. Set controller.[[transformAlgorithm]] to transformAlgorithm.
  2965. controller.set_transform_algorithm(transform_algorithm);
  2966. // 6. Set controller.[[flushAlgorithm]] to flushAlgorithm.
  2967. controller.set_flush_algorithm(flush_algorithm);
  2968. }
  2969. // https://streams.spec.whatwg.org/#set-up-transform-stream-default-controller-from-transformer
  2970. WebIDL::ExceptionOr<void> set_up_transform_stream_default_controller_from_transformer(TransformStream& stream, JS::Value transformer, Transformer& transformer_dict)
  2971. {
  2972. auto& realm = stream.realm();
  2973. auto& vm = realm.vm();
  2974. // 1. Let controller be a new TransformStreamDefaultController.
  2975. auto controller = realm.heap().allocate<TransformStreamDefaultController>(realm, realm);
  2976. // 2. Let transformAlgorithm be the following steps, taking a chunk argument:
  2977. auto transform_algorithm = JS::create_heap_function(realm.heap(), [controller, &realm, &vm](JS::Value chunk) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  2978. // 1. Let result be TransformStreamDefaultControllerEnqueue(controller, chunk).
  2979. auto result = transform_stream_default_controller_enqueue(*controller, chunk);
  2980. // 2. If result is an abrupt completion, return a promise rejected with result.[[Value]].
  2981. if (result.is_error()) {
  2982. auto throw_completion = Bindings::dom_exception_to_throw_completion(vm, result.exception());
  2983. return WebIDL::create_rejected_promise(realm, *throw_completion.release_value());
  2984. }
  2985. // 3. Otherwise, return a promise resolved with undefined.
  2986. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  2987. });
  2988. // 3. Let flushAlgorithm be an algorithm which returns a promise resolved with undefined.
  2989. auto flush_algorithm = JS::create_heap_function(realm.heap(), [&realm]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  2990. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  2991. });
  2992. // 4. If transformerDict["transform"] exists, set transformAlgorithm to an algorithm which takes an argument chunk
  2993. // and returns the result of invoking transformerDict["transform"] with argument list « chunk, controller » and
  2994. // callback this value transformer.
  2995. if (transformer_dict.transform) {
  2996. transform_algorithm = JS::create_heap_function(realm.heap(), [controller, &realm, transformer, callback = transformer_dict.transform](JS::Value chunk) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  2997. // Note: callback does not return a promise, so invoke_callback may return an abrupt completion
  2998. auto result = WebIDL::invoke_callback(*callback, transformer, chunk, controller);
  2999. if (result.is_error())
  3000. return WebIDL::create_rejected_promise(realm, *result.release_value());
  3001. return WebIDL::create_resolved_promise(realm, *result.release_value());
  3002. });
  3003. }
  3004. // 5. If transformerDict["flush"] exists, set flushAlgorithm to an algorithm which returns the result of invoking
  3005. // transformerDict["flush"] with argument list « controller » and callback this value transformer.
  3006. if (transformer_dict.flush) {
  3007. flush_algorithm = JS::create_heap_function(realm.heap(), [&realm, transformer, callback = transformer_dict.flush, controller]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  3008. // Note: callback does not return a promise, so invoke_callback may return an abrupt completion
  3009. auto result = WebIDL::invoke_callback(*callback, transformer, controller);
  3010. if (result.is_error()) {
  3011. return WebIDL::create_rejected_promise(realm, *result.release_value());
  3012. }
  3013. return WebIDL::create_resolved_promise(realm, *result.release_value());
  3014. });
  3015. }
  3016. // 6. Perform ! SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm).
  3017. set_up_transform_stream_default_controller(stream, *controller, transform_algorithm, flush_algorithm);
  3018. return {};
  3019. }
  3020. // https://streams.spec.whatwg.org/#transform-stream-default-controller-clear-algorithms
  3021. void transform_stream_default_controller_clear_algorithms(TransformStreamDefaultController& controller)
  3022. {
  3023. // NOTE: This is observable using weak references. See tc39/proposal-weakrefs#31 for more detail.
  3024. // 1. Set controller.[[transformAlgorithm]] to undefined.
  3025. controller.set_transform_algorithm({});
  3026. // 2. Set controller.[[flushAlgorithm]] to undefined.
  3027. controller.set_flush_algorithm({});
  3028. }
  3029. // https://streams.spec.whatwg.org/#transform-stream-default-controller-enqueue
  3030. WebIDL::ExceptionOr<void> transform_stream_default_controller_enqueue(TransformStreamDefaultController& controller, JS::Value chunk)
  3031. {
  3032. auto& vm = controller.vm();
  3033. // 1. Let stream be controller.[[stream]].
  3034. auto stream = controller.stream();
  3035. // 2. Let readableController be stream.[[readable]].[[controller]].
  3036. VERIFY(stream->readable()->controller().has_value() && stream->readable()->controller()->has<JS::NonnullGCPtr<ReadableStreamDefaultController>>());
  3037. auto& readable_controller = stream->readable()->controller()->get<JS::NonnullGCPtr<ReadableStreamDefaultController>>();
  3038. // 3. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController) is false, throw a TypeError exception.
  3039. if (!readable_stream_default_controller_can_close_or_enqueue(readable_controller))
  3040. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "ReadableController is either closed or not readable."sv };
  3041. // 4. Let enqueueResult be ReadableStreamDefaultControllerEnqueue(readableController, chunk).
  3042. auto enqueue_result = readable_stream_default_controller_enqueue(readable_controller, chunk);
  3043. // 5. If enqueueResult is an abrupt completion,
  3044. if (enqueue_result.is_error()) {
  3045. auto throw_completion = Bindings::dom_exception_to_throw_completion(vm, enqueue_result.exception());
  3046. // 1. Perform ! TransformStreamErrorWritableAndUnblockWrite(stream, enqueueResult.[[Value]]).
  3047. TRY(transform_stream_error_writable_and_unblock_write(*stream, throw_completion.value().value()));
  3048. // 2. Throw stream.[[readable]].[[storedError]].
  3049. return JS::throw_completion(stream->readable()->stored_error());
  3050. }
  3051. // 6. Let backpressure be ! ReadableStreamDefaultControllerHasBackpressure(readableController).
  3052. auto backpressure = readable_stream_default_controller_has_backpressure(readable_controller);
  3053. // 7. If backpressure is not stream.[[backpressure]],
  3054. if (backpressure != stream->backpressure()) {
  3055. // 1. Assert: backpressure is true.
  3056. VERIFY(backpressure);
  3057. // 2. Perform ! TransformStreamSetBackpressure(stream, true).
  3058. TRY(transform_stream_set_backpressure(*stream, true));
  3059. }
  3060. return {};
  3061. }
  3062. // https://streams.spec.whatwg.org/#transform-stream-default-controller-error
  3063. WebIDL::ExceptionOr<void> transform_stream_default_controller_error(TransformStreamDefaultController& controller, JS::Value error)
  3064. {
  3065. // 1. Perform ! TransformStreamError(controller.[[stream]], e).
  3066. TRY(transform_stream_error(*controller.stream(), error));
  3067. return {};
  3068. }
  3069. // https://streams.spec.whatwg.org/#transform-stream-default-controller-terminate
  3070. WebIDL::ExceptionOr<void> transform_stream_default_controller_terminate(TransformStreamDefaultController& controller)
  3071. {
  3072. auto& realm = controller.realm();
  3073. // 1. Let stream be controller.[[stream]].
  3074. auto stream = controller.stream();
  3075. // 2. Let readableController be stream.[[readable]].[[controller]].
  3076. VERIFY(stream->readable()->controller().has_value() && stream->readable()->controller()->has<JS::NonnullGCPtr<ReadableStreamDefaultController>>());
  3077. auto readable_controller = stream->readable()->controller()->get<JS::NonnullGCPtr<ReadableStreamDefaultController>>();
  3078. // 3. Perform ! ReadableStreamDefaultControllerClose(readableController).
  3079. readable_stream_default_controller_close(readable_controller);
  3080. // 4. Let error be a TypeError exception indicating that the stream has been terminated.
  3081. auto error = JS::TypeError::create(realm, "Stream has been terminated."sv);
  3082. // 5. Perform ! TransformStreamErrorWritableAndUnblockWrite(stream, error).
  3083. TRY(transform_stream_error_writable_and_unblock_write(*stream, error));
  3084. return {};
  3085. }
  3086. // https://streams.spec.whatwg.org/#transform-stream-default-controller-perform-transform
  3087. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> transform_stream_default_controller_perform_transform(TransformStreamDefaultController& controller, JS::Value chunk)
  3088. {
  3089. auto& realm = controller.realm();
  3090. // 1. Let transformPromise be the result of performing controller.[[transformAlgorithm]], passing chunk.
  3091. auto transform_promise = TRY(controller.transform_algorithm()->function()(chunk));
  3092. // 2. Return the result of reacting to transformPromise with the following rejection steps given the argument r:
  3093. auto react_result = WebIDL::react_to_promise(*transform_promise,
  3094. {},
  3095. [&](auto const& reason) -> WebIDL::ExceptionOr<JS::Value> {
  3096. // 1. Perform ! TransformStreamError(controller.[[stream]], r).
  3097. TRY(transform_stream_error(*controller.stream(), reason));
  3098. // 2. Throw r.
  3099. return JS::throw_completion(reason);
  3100. });
  3101. return WebIDL::create_resolved_promise(realm, react_result);
  3102. }
  3103. // https://streams.spec.whatwg.org/#transform-stream-default-sink-abort-algorithm
  3104. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> transform_stream_default_sink_abort_algorithm(TransformStream& stream, JS::Value reason)
  3105. {
  3106. auto& realm = stream.realm();
  3107. // 1. Perform ! TransformStreamError(stream, reason).
  3108. TRY(transform_stream_error(stream, reason));
  3109. // 2. Return a promise resolved with undefined.
  3110. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  3111. }
  3112. // https://streams.spec.whatwg.org/#transform-stream-default-sink-close-algorithm
  3113. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> transform_stream_default_sink_close_algorithm(TransformStream& stream)
  3114. {
  3115. auto& realm = stream.realm();
  3116. // 1. Let readable be stream.[[readable]].
  3117. auto readable = stream.readable();
  3118. // 2. Let controller be stream.[[controller]].
  3119. auto controller = stream.controller();
  3120. // 3. Let flushPromise be the result of performing controller.[[flushAlgorithm]].
  3121. auto flush_promise = TRY(controller->flush_algorithm()->function()());
  3122. // 4. Perform ! TransformStreamDefaultControllerClearAlgorithms(controller).
  3123. transform_stream_default_controller_clear_algorithms(*controller);
  3124. // 5. Return the result of reacting to flushPromise:
  3125. auto react_result = WebIDL::react_to_promise(
  3126. *flush_promise,
  3127. // 1. If flushPromise was fulfilled, then:
  3128. [readable](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  3129. // 1. If readable.[[state]] is "errored", throw readable.[[storedError]].
  3130. if (readable->state() == ReadableStream::State::Errored)
  3131. return JS::throw_completion(readable->stored_error());
  3132. VERIFY(readable->controller().has_value() && readable->controller()->has<JS::NonnullGCPtr<ReadableStreamDefaultController>>());
  3133. // 2. Perform ! ReadableStreamDefaultControllerClose(readable.[[controller]]).
  3134. readable_stream_default_controller_close(readable->controller().value().get<JS::NonnullGCPtr<ReadableStreamDefaultController>>());
  3135. return JS::js_undefined();
  3136. },
  3137. // 2. If flushPromise was rejected with reason r, then:
  3138. [&stream, readable](auto const& reason) -> WebIDL::ExceptionOr<JS::Value> {
  3139. // 1. Perform ! TransformStreamError(stream, r).
  3140. TRY(transform_stream_error(stream, reason));
  3141. // 2. Throw readable.[[storedError]].
  3142. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, readable->stored_error().as_string().utf8_string() };
  3143. });
  3144. return WebIDL::create_resolved_promise(realm, react_result);
  3145. }
  3146. // https://streams.spec.whatwg.org/#transform-stream-default-sink-write-algorithm
  3147. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> transform_stream_default_sink_write_algorithm(TransformStream& stream, JS::Value chunk)
  3148. {
  3149. auto& realm = stream.realm();
  3150. // 1. Assert: stream.[[writable]].[[state]] is "writable".
  3151. VERIFY(stream.writable()->state() == WritableStream::State::Writable);
  3152. // 2. Let controller be stream.[[controller]].
  3153. auto controller = stream.controller();
  3154. // 3. If stream.[[backpressure]] is true,
  3155. if (stream.backpressure().has_value() && *stream.backpressure()) {
  3156. // 1. Let backpressureChangePromise be stream.[[backpressureChangePromise]].
  3157. auto backpressure_change_promise = stream.backpressure_change_promise();
  3158. // 2. Assert: backpressureChangePromise is not undefined.
  3159. VERIFY(backpressure_change_promise);
  3160. // 3. Return the result of reacting to backpressureChangePromise with the following fulfillment steps:
  3161. auto react_result = WebIDL::react_to_promise(*backpressure_change_promise,
  3162. [&stream, controller, chunk](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  3163. // 1. Let writable be stream.[[writable]].
  3164. auto writable = stream.writable();
  3165. // 2. Let state be writable.[[state]].
  3166. auto state = writable->state();
  3167. // 3. If state is "erroring", throw writable.[[storedError]].
  3168. if (state == WritableStream::State::Erroring)
  3169. return JS::throw_completion(writable->stored_error());
  3170. // 4. Assert: state is "writable".
  3171. VERIFY(state == WritableStream::State::Writable);
  3172. // 5. Return ! TransformStreamDefaultControllerPerformTransform(controller, chunk).
  3173. return TRY(transform_stream_default_controller_perform_transform(*controller, chunk))->promise();
  3174. },
  3175. {});
  3176. return WebIDL::create_resolved_promise(realm, react_result);
  3177. }
  3178. // 4. Return ! TransformStreamDefaultControllerPerformTransform(controller, chunk).
  3179. return transform_stream_default_controller_perform_transform(*controller, chunk);
  3180. }
  3181. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> transform_stream_default_source_pull_algorithm(TransformStream& stream)
  3182. {
  3183. // 1. Assert: stream.[[backpressure]] is true.
  3184. VERIFY(stream.backpressure().has_value() && *stream.backpressure());
  3185. // 2. Assert: stream.[[backpressureChangePromise]] is not undefined.
  3186. VERIFY(stream.backpressure_change_promise());
  3187. // 3. Perform ! TransformStreamSetBackpressure(stream, false).
  3188. TRY(transform_stream_set_backpressure(stream, false));
  3189. // 4. Return stream.[[backpressureChangePromise]].
  3190. return JS::NonnullGCPtr { *stream.backpressure_change_promise() };
  3191. }
  3192. // https://streams.spec.whatwg.org/#transform-stream-error
  3193. WebIDL::ExceptionOr<void> transform_stream_error(TransformStream& stream, JS::Value error)
  3194. {
  3195. VERIFY(stream.readable()->controller().has_value() && stream.readable()->controller()->has<JS::NonnullGCPtr<ReadableStreamDefaultController>>());
  3196. auto readable_controller = stream.readable()->controller()->get<JS::NonnullGCPtr<ReadableStreamDefaultController>>();
  3197. // 1. Perform ! ReadableStreamDefaultControllerError(stream.[[readable]].[[controller]], e).
  3198. readable_stream_default_controller_error(*readable_controller, error);
  3199. // 2. Perform ! TransformStreamErrorWritableAndUnblockWrite(stream, e).
  3200. TRY(transform_stream_error_writable_and_unblock_write(stream, error));
  3201. return {};
  3202. }
  3203. // https://streams.spec.whatwg.org/#transform-stream-error-writable-and-unblock-write
  3204. WebIDL::ExceptionOr<void> transform_stream_error_writable_and_unblock_write(TransformStream& stream, JS::Value error)
  3205. {
  3206. // 1. Perform ! TransformStreamDefaultControllerClearAlgorithms(stream.[[controller]]).
  3207. transform_stream_default_controller_clear_algorithms(*stream.controller());
  3208. // 2. Perform ! WritableStreamDefaultControllerErrorIfNeeded(stream.[[writable]].[[controller]], e).
  3209. TRY(writable_stream_default_controller_error_if_needed(*stream.writable()->controller(), error));
  3210. // 3. If stream.[[backpressure]] is true, perform ! TransformStreamSetBackpressure(stream, false).
  3211. if (stream.backpressure().has_value() && *stream.backpressure())
  3212. TRY(transform_stream_set_backpressure(stream, false));
  3213. return {};
  3214. }
  3215. // https://streams.spec.whatwg.org/#transform-stream-set-backpressure
  3216. WebIDL::ExceptionOr<void> transform_stream_set_backpressure(TransformStream& stream, bool backpressure)
  3217. {
  3218. auto& realm = stream.realm();
  3219. // 1. Assert: stream.[[backpressure]] is not backpressure.
  3220. VERIFY(stream.backpressure() != backpressure);
  3221. // 2. If stream.[[backpressureChangePromise]] is not undefined, resolve stream.[[backpressureChangePromise]] with undefined.
  3222. if (stream.backpressure_change_promise())
  3223. WebIDL::resolve_promise(realm, *stream.backpressure_change_promise(), JS::js_undefined());
  3224. // 3. Set stream.[[backpressureChangePromise]] to a new promise.
  3225. stream.set_backpressure_change_promise(WebIDL::create_promise(realm));
  3226. // 4. Set stream.[[backpressure]] to backpressure.
  3227. stream.set_backpressure(backpressure);
  3228. return {};
  3229. }
  3230. // https://streams.spec.whatwg.org/#is-non-negative-number
  3231. bool is_non_negative_number(JS::Value value)
  3232. {
  3233. // 1. If Type(v) is not Number, return false.
  3234. if (!value.is_number())
  3235. return false;
  3236. // 2. If v is NaN, return false.
  3237. if (value.is_nan())
  3238. return false;
  3239. // 3. If v < 0, return false.
  3240. if (value.as_double() < 0.0)
  3241. return false;
  3242. // 4. Return true.
  3243. return true;
  3244. }
  3245. // https://streams.spec.whatwg.org/#can-transfer-array-buffer
  3246. bool can_transfer_array_buffer(JS::ArrayBuffer const& array_buffer)
  3247. {
  3248. // 1. Assert: Type(O) is Object.
  3249. // 2. Assert: O has an [[ArrayBufferData]] internal slot.
  3250. // 3. If ! IsDetachedBuffer(O) is true, return false.
  3251. if (array_buffer.is_detached())
  3252. return false;
  3253. // 4. If SameValue(O.[[ArrayBufferDetachKey]], undefined) is false, return false.
  3254. if (!JS::same_value(array_buffer.detach_key(), JS::js_undefined()))
  3255. return false;
  3256. // 5. Return true.
  3257. return true;
  3258. }
  3259. // https://streams.spec.whatwg.org/#abstract-opdef-structuredclone
  3260. WebIDL::ExceptionOr<JS::Value> structured_clone(JS::Realm& realm, JS::Value value)
  3261. {
  3262. auto& vm = realm.vm();
  3263. // 1. Let serialized be ? StructuredSerialize(v).
  3264. auto serialized = TRY(HTML::structured_serialize(vm, value));
  3265. // 2. Return ? StructuredDeserialize(serialized, the current Realm).
  3266. return TRY(HTML::structured_deserialize(vm, serialized, realm, {}));
  3267. }
  3268. // https://streams.spec.whatwg.org/#close-sentinel
  3269. // Non-standard function that implements the "close sentinel" value.
  3270. JS::Value create_close_sentinel()
  3271. {
  3272. // The close sentinel is a unique value enqueued into [[queue]], in lieu of a chunk, to signal that the stream is closed. It is only used internally, and is never exposed to web developers.
  3273. // Note: We use the empty Value to signal this as, similarly to the note above, the empty value is not exposed to nor creatable by web developers.
  3274. return {};
  3275. }
  3276. // https://streams.spec.whatwg.org/#close-sentinel
  3277. // Non-standard function that implements the "If value is a close sentinel" check.
  3278. bool is_close_sentinel(JS::Value value)
  3279. {
  3280. return value.is_empty();
  3281. }
  3282. // Non-standard function to aid in converting a user-provided function into a WebIDL::Callback. This is essentially
  3283. // what the Bindings generator would do at compile time, but at runtime instead.
  3284. JS::ThrowCompletionOr<JS::Handle<WebIDL::CallbackType>> property_to_callback(JS::VM& vm, JS::Value value, JS::PropertyKey const& property_key, WebIDL::OperationReturnsPromise operation_returns_promise)
  3285. {
  3286. auto property = TRY(value.get(vm, property_key));
  3287. if (property.is_undefined())
  3288. return JS::Handle<WebIDL::CallbackType> {};
  3289. if (!property.is_function())
  3290. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAFunction, property.to_string_without_side_effects());
  3291. return vm.heap().allocate_without_realm<WebIDL::CallbackType>(property.as_object(), HTML::incumbent_settings_object(), operation_returns_promise);
  3292. }
  3293. // https://streams.spec.whatwg.org/#set-up-readable-byte-stream-controller-from-underlying-source
  3294. WebIDL::ExceptionOr<void> set_up_readable_byte_stream_controller_from_underlying_source(ReadableStream& stream, JS::Value underlying_source, UnderlyingSource const& underlying_source_dict, double high_water_mark)
  3295. {
  3296. auto& realm = stream.realm();
  3297. // 1. Let controller be a new ReadableByteStreamController.
  3298. auto controller = stream.heap().allocate<ReadableByteStreamController>(realm, realm);
  3299. // 2. Let startAlgorithm be an algorithm that returns undefined.
  3300. auto start_algorithm = JS::create_heap_function(realm.heap(), []() -> WebIDL::ExceptionOr<JS::Value> { return JS::js_undefined(); });
  3301. // 3. Let pullAlgorithm be an algorithm that returns a promise resolved with undefined.
  3302. auto pull_algorithm = JS::create_heap_function(realm.heap(), [&realm]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  3303. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  3304. });
  3305. // 4. Let cancelAlgorithm be an algorithm that returns a promise resolved with undefined.
  3306. auto cancel_algorithm = JS::create_heap_function(realm.heap(), [&realm](JS::Value) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  3307. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  3308. });
  3309. // 5. If underlyingSourceDict["start"] exists, then set startAlgorithm to an algorithm which returns the result of invoking underlyingSourceDict["start"] with argument list « controller » and callback this value underlyingSource.
  3310. if (underlying_source_dict.start) {
  3311. start_algorithm = JS::create_heap_function(realm.heap(), [controller, underlying_source, callback = underlying_source_dict.start]() -> WebIDL::ExceptionOr<JS::Value> {
  3312. // Note: callback does not return a promise, so invoke_callback may return an abrupt completion
  3313. return TRY(WebIDL::invoke_callback(*callback, underlying_source, controller)).release_value();
  3314. });
  3315. }
  3316. // 6. If underlyingSourceDict["pull"] exists, then set pullAlgorithm to an algorithm which returns the result of invoking underlyingSourceDict["pull"] with argument list « controller » and callback this value underlyingSource.
  3317. if (underlying_source_dict.pull) {
  3318. pull_algorithm = JS::create_heap_function(realm.heap(), [&realm, controller, underlying_source, callback = underlying_source_dict.pull]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  3319. // Note: callback return a promise, so invoke_callback will never return an abrupt completion
  3320. auto result = MUST_OR_THROW_OOM(WebIDL::invoke_callback(*callback, underlying_source, controller)).release_value();
  3321. return WebIDL::create_resolved_promise(realm, result);
  3322. });
  3323. }
  3324. // 7. If underlyingSourceDict["cancel"] exists, then set cancelAlgorithm to an algorithm which takes an argument reason and returns the result of invoking underlyingSourceDict["cancel"] with argument list « reason » and callback this value underlyingSource.
  3325. if (underlying_source_dict.cancel) {
  3326. cancel_algorithm = JS::create_heap_function(realm.heap(), [&realm, underlying_source, callback = underlying_source_dict.cancel](JS::Value reason) -> WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> {
  3327. // Note: callback return a promise, so invoke_callback will never return an abrupt completion
  3328. auto result = MUST_OR_THROW_OOM(WebIDL::invoke_callback(*callback, underlying_source, reason)).release_value();
  3329. return WebIDL::create_resolved_promise(realm, result);
  3330. });
  3331. }
  3332. // 8. Let autoAllocateChunkSize be underlyingSourceDict["autoAllocateChunkSize"], if it exists, or undefined otherwise.
  3333. auto auto_allocate_chunk_size = underlying_source_dict.auto_allocate_chunk_size.has_value()
  3334. ? JS::Value(underlying_source_dict.auto_allocate_chunk_size.value())
  3335. : JS::js_undefined();
  3336. // 9. If autoAllocateChunkSize is 0, then throw a TypeError exception.
  3337. if (auto_allocate_chunk_size.is_integral_number() && auto_allocate_chunk_size.as_double() == 0)
  3338. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot use an auto allocate chunk size of 0"sv };
  3339. // 10. Perform ? SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize).
  3340. return set_up_readable_byte_stream_controller(stream, controller, start_algorithm, pull_algorithm, cancel_algorithm, high_water_mark, auto_allocate_chunk_size);
  3341. }
  3342. }