AbstractOperations.cpp 168 KB

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