AbstractOperations.cpp 175 KB

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