AbstractOperations.cpp 234 KB

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