AbstractOperations.cpp 199 KB

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