AbstractOperations.cpp 231 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116
  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. 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]() {
  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) {
  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) {
  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. 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. 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. 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. 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]() {
  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]() {
  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) {
  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) {
  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. 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. 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. readable_stream_default_controller_can_pull_if_needed(controller);
  1570. return {};
  1571. }
  1572. // https://streams.spec.whatwg.org/#readable-stream-default-controller-call-pull-if-needed
  1573. void readable_stream_default_controller_can_pull_if_needed(ReadableStreamDefaultController& controller)
  1574. {
  1575. // 1. Let shouldPull be ! ReadableStreamDefaultControllerShouldCallPull(controller).
  1576. auto should_pull = readable_stream_default_controller_should_call_pull(controller);
  1577. // 2. If shouldPull is false, return.
  1578. if (!should_pull)
  1579. return;
  1580. // 3. If controller.[[pulling]] is true,
  1581. if (controller.pulling()) {
  1582. // 1. Set controller.[[pullAgain]] to true.
  1583. controller.set_pull_again(true);
  1584. // 2. Return.
  1585. return;
  1586. }
  1587. // 4. Assert: controller.[[pullAgain]] is false.
  1588. VERIFY(!controller.pull_again());
  1589. // 5. Set controller.[[pulling]] to true.
  1590. controller.set_pulling(true);
  1591. // 6. Let pullPromise be the result of performing controller.[[pullAlgorithm]].
  1592. auto pull_promise = controller.pull_algorithm()->function()();
  1593. // 7. Upon fulfillment of pullPromise,
  1594. WebIDL::upon_fulfillment(*pull_promise, JS::create_heap_function(controller.heap(), [&controller](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {
  1595. // 1. Set controller.[[pulling]] to false.
  1596. controller.set_pulling(false);
  1597. // 2. If controller.[[pullAgain]] is true,
  1598. if (controller.pull_again()) {
  1599. // 1. Set controller.[[pullAgain]] to false.
  1600. controller.set_pull_again(false);
  1601. // 2. Perform ! ReadableStreamDefaultControllerCallPullIfNeeded(controller).
  1602. readable_stream_default_controller_can_pull_if_needed(controller);
  1603. }
  1604. return JS::js_undefined();
  1605. }));
  1606. // 8. Upon rejection of pullPromise with reason e,
  1607. WebIDL::upon_rejection(*pull_promise, JS::create_heap_function(controller.heap(), [&controller](JS::Value e) -> WebIDL::ExceptionOr<JS::Value> {
  1608. // 1. Perform ! ReadableStreamDefaultControllerError(controller, e).
  1609. readable_stream_default_controller_error(controller, e);
  1610. return JS::js_undefined();
  1611. }));
  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. 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. 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]() {
  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) {
  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]() {
  1949. // Note: callback returns a promise, so invoke_callback will never return an abrupt completion
  1950. auto result = MUST(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) {
  1957. // Note: callback returns a promise, so invoke_callback will never return an abrupt completion
  1958. auto result = MUST(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. 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 = 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. 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. }
  2006. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-clear-algorithms
  2007. void readable_byte_stream_controller_clear_algorithms(ReadableByteStreamController& controller)
  2008. {
  2009. // 1. Set controller.[[pullAlgorithm]] to undefined.
  2010. controller.set_pull_algorithm({});
  2011. // 2. Set controller.[[cancelAlgorithm]] to undefined.
  2012. controller.set_cancel_algorithm({});
  2013. }
  2014. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-clear-pending-pull-intos
  2015. void readable_byte_stream_controller_clear_pending_pull_intos(ReadableByteStreamController& controller)
  2016. {
  2017. // 1. Perform ! ReadableByteStreamControllerInvalidateBYOBRequest(controller).
  2018. readable_byte_stream_controller_invalidate_byob_request(controller);
  2019. // 2. Set controller.[[pendingPullIntos]] to a new empty list.
  2020. controller.pending_pull_intos().clear();
  2021. }
  2022. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-close
  2023. WebIDL::ExceptionOr<void> readable_byte_stream_controller_close(ReadableByteStreamController& controller)
  2024. {
  2025. auto& realm = controller.realm();
  2026. // 1. Let stream be controller.[[stream]].
  2027. auto stream = controller.stream();
  2028. // 2. If controller.[[closeRequested]] is true or stream.[[state]] is not "readable", return.
  2029. if (controller.close_requested() || stream->state() != ReadableStream::State::Readable)
  2030. return {};
  2031. // 3. If controller.[[queueTotalSize]] > 0,
  2032. if (controller.queue_total_size() > 0.0) {
  2033. // 1. Set controller.[[closeRequested]] to true.
  2034. controller.set_close_requested(true);
  2035. // 2. Return.
  2036. return {};
  2037. }
  2038. // 4. If controller.[[pendingPullIntos]] is not empty,
  2039. if (!controller.pending_pull_intos().is_empty()) {
  2040. // 1. Let firstPendingPullInto be controller.[[pendingPullIntos]][0].
  2041. auto& first_pending_pull_into = controller.pending_pull_intos().first();
  2042. // 2. If firstPendingPullInto’s bytes filled > 0,
  2043. if (first_pending_pull_into.bytes_filled > 0) {
  2044. // 1. Let e be a new TypeError exception.
  2045. auto error = JS::TypeError::create(realm, "Cannot close controller in the middle of processing a write request"sv);
  2046. // 2. Perform ! ReadableByteStreamControllerError(controller, e).
  2047. readable_byte_stream_controller_error(controller, error);
  2048. // 3. Throw e.
  2049. return JS::throw_completion(error);
  2050. }
  2051. }
  2052. // 5. Perform ! ReadableByteStreamControllerClearAlgorithms(controller).
  2053. readable_byte_stream_controller_clear_algorithms(controller);
  2054. // 6. Perform ! ReadableStreamClose(stream).
  2055. readable_stream_close(*stream);
  2056. return {};
  2057. }
  2058. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-error
  2059. void readable_byte_stream_controller_error(ReadableByteStreamController& controller, JS::Value error)
  2060. {
  2061. // 1. Let stream be controller.[[stream]].
  2062. auto stream = controller.stream();
  2063. // 2. If stream.[[state]] is not "readable", return.
  2064. if (stream->state() != ReadableStream::State::Readable)
  2065. return;
  2066. // 3. Perform ! ReadableByteStreamControllerClearPendingPullIntos(controller).
  2067. readable_byte_stream_controller_clear_pending_pull_intos(controller);
  2068. // 4. Perform ! ResetQueue(controller).
  2069. reset_queue(controller);
  2070. // 5. Perform ! ReadableByteStreamControllerClearAlgorithms(controller).
  2071. readable_byte_stream_controller_clear_algorithms(controller);
  2072. // 6. Perform ! ReadableStreamError(stream, e).
  2073. readable_stream_error(*stream, error);
  2074. }
  2075. // https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollerfillreadrequestfromqueue
  2076. WebIDL::ExceptionOr<void> readable_byte_stream_controller_fill_read_request_from_queue(ReadableByteStreamController& controller, JS::NonnullGCPtr<ReadRequest> read_request)
  2077. {
  2078. auto& vm = controller.vm();
  2079. auto& realm = controller.realm();
  2080. // 1. Assert: controller.[[queueTotalSize]] > 0.
  2081. VERIFY(controller.queue_total_size() > 0.0);
  2082. // 2. Let entry be controller.[[queue]][0].
  2083. // 3. Remove entry from controller.[[queue]].
  2084. auto entry = controller.queue().take_first();
  2085. // 4. Set controller.[[queueTotalSize]] to controller.[[queueTotalSize]] − entry’s byte length.
  2086. controller.set_queue_total_size(controller.queue_total_size() - entry.byte_length);
  2087. // 5. Perform ! ReadableByteStreamControllerHandleQueueDrain(controller).
  2088. readable_byte_stream_controller_handle_queue_drain(controller);
  2089. // 6. Let view be ! Construct(%Uint8Array%, « entry’s buffer, entry’s byte offset, entry’s byte length »).
  2090. 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)));
  2091. // 7. Perform readRequest’s chunk steps, given view.
  2092. read_request->on_chunk(view);
  2093. return {};
  2094. }
  2095. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-get-desired-size
  2096. Optional<double> readable_byte_stream_controller_get_desired_size(ReadableByteStreamController const& controller)
  2097. {
  2098. auto stream = controller.stream();
  2099. // 1. Let state be controller.[[stream]].[[state]].
  2100. // 2. If state is "errored", return null.
  2101. if (stream->is_errored())
  2102. return {};
  2103. // 3. If state is "closed", return 0.
  2104. if (stream->is_closed())
  2105. return 0.0;
  2106. // 4. Return controller.[[strategyHWM]] − controller.[[queueTotalSize]].
  2107. return controller.strategy_hwm() - controller.queue_total_size();
  2108. }
  2109. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-handle-queue-drain
  2110. void readable_byte_stream_controller_handle_queue_drain(ReadableByteStreamController& controller)
  2111. {
  2112. // 1. Assert: controller.[[stream]].[[state]] is "readable".
  2113. VERIFY(controller.stream()->state() == ReadableStream::State::Readable);
  2114. // 2. If controller.[[queueTotalSize]] is 0 and controller.[[closeRequested]] is true,
  2115. if (controller.queue_total_size() == 0.0 && controller.close_requested()) {
  2116. // 1. Perform ! ReadableByteStreamControllerClearAlgorithms(controller).
  2117. readable_byte_stream_controller_clear_algorithms(controller);
  2118. // 2. Perform ! ReadableStreamClose(controller.[[stream]]).
  2119. readable_stream_close(*controller.stream());
  2120. }
  2121. // 3. Otherwise,
  2122. else {
  2123. // 1. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
  2124. readable_byte_stream_controller_call_pull_if_needed(controller);
  2125. }
  2126. }
  2127. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-invalidate-byob-request
  2128. void readable_byte_stream_controller_invalidate_byob_request(ReadableByteStreamController& controller)
  2129. {
  2130. // 1. If controller.[[byobRequest]] is null, return.
  2131. if (!controller.byob_request())
  2132. return;
  2133. // 2. Set controller.[[byobRequest]].[[controller]] to undefined.
  2134. controller.byob_request()->set_controller({});
  2135. // 3. Set controller.[[byobRequest]].[[view]] to null.
  2136. controller.byob_request()->set_view({});
  2137. // 4. Set controller.[[byobRequest]] to null.
  2138. controller.set_byob_request({});
  2139. }
  2140. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-error
  2141. bool readable_byte_stream_controller_should_call_pull(ReadableByteStreamController const& controller)
  2142. {
  2143. // 1. Let stream be controller.[[stream]].
  2144. auto stream = controller.stream();
  2145. // 2. If stream.[[state]] is not "readable", return false.
  2146. if (stream->state() != ReadableStream::State::Readable)
  2147. return false;
  2148. // 3. If controller.[[closeRequested]] is true, return false.
  2149. if (controller.close_requested())
  2150. return false;
  2151. // 4. If controller.[[started]] is false, return false.
  2152. if (!controller.started())
  2153. return false;
  2154. // 5. If ! ReadableStreamHasDefaultReader(stream) is true and ! ReadableStreamGetNumReadRequests(stream) > 0, return true.
  2155. if (readable_stream_has_default_reader(*stream) && readable_stream_get_num_read_requests(*stream) > 0)
  2156. return true;
  2157. // 6. If ! ReadableStreamHasBYOBReader(stream) is true and ! ReadableStreamGetNumReadIntoRequests(stream) > 0, return true.
  2158. if (readable_stream_has_byob_reader(*stream) && readable_stream_get_num_read_into_requests(*stream) > 0)
  2159. return true;
  2160. // 7. Let desiredSize be ! ReadableByteStreamControllerGetDesiredSize(controller).
  2161. auto desired_size = readable_byte_stream_controller_get_desired_size(controller);
  2162. // 8. Assert: desiredSize is not null.
  2163. VERIFY(desired_size.has_value());
  2164. // 9. If desiredSize > 0, return true.
  2165. if (*desired_size > 0.0)
  2166. return true;
  2167. // 10. Return false.
  2168. return false;
  2169. }
  2170. // https://streams.spec.whatwg.org/#create-readable-stream
  2171. 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)
  2172. {
  2173. // 1. If highWaterMark was not passed, set it to 1.
  2174. if (!high_water_mark.has_value())
  2175. high_water_mark = 1.0;
  2176. // 2. If sizeAlgorithm was not passed, set it to an algorithm that returns 1.
  2177. if (!size_algorithm)
  2178. size_algorithm = JS::create_heap_function(realm.heap(), [](JS::Value) { return JS::normal_completion(JS::Value(1)); });
  2179. // 3. Assert: ! IsNonNegativeNumber(highWaterMark) is true.
  2180. VERIFY(is_non_negative_number(JS::Value { *high_water_mark }));
  2181. // 4. Let stream be a new ReadableStream.
  2182. auto stream = realm.heap().allocate<ReadableStream>(realm, realm);
  2183. // 5. Perform ! InitializeReadableStream(stream).
  2184. initialize_readable_stream(*stream);
  2185. // 6. Let controller be a new ReadableStreamDefaultController.
  2186. auto controller = realm.heap().allocate<ReadableStreamDefaultController>(realm, realm);
  2187. // 7. Perform ? SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm).
  2188. TRY(set_up_readable_stream_default_controller(*stream, *controller, start_algorithm, pull_algorithm, cancel_algorithm, *high_water_mark, *size_algorithm));
  2189. // 8. Return stream.
  2190. return stream;
  2191. }
  2192. // https://streams.spec.whatwg.org/#abstract-opdef-createreadablebytestream
  2193. 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)
  2194. {
  2195. // 1. Let stream be a new ReadableStream.
  2196. auto stream = realm.heap().allocate<ReadableStream>(realm, realm);
  2197. // 2. Perform ! InitializeReadableStream(stream).
  2198. initialize_readable_stream(*stream);
  2199. // 3. Let controller be a new ReadableByteStreamController.
  2200. auto controller = realm.heap().allocate<ReadableByteStreamController>(realm, realm);
  2201. // 4. Perform ? SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined).
  2202. TRY(set_up_readable_byte_stream_controller(stream, controller, start_algorithm, pull_algorithm, cancel_algorithm, 0, JS::js_undefined()));
  2203. // 5. Return stream.
  2204. return stream;
  2205. }
  2206. // https://streams.spec.whatwg.org/#create-writable-stream
  2207. 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)
  2208. {
  2209. // 1. Assert: ! IsNonNegativeNumber(highWaterMark) is true.
  2210. VERIFY(is_non_negative_number(JS::Value { high_water_mark }));
  2211. // 2. Let stream be a new WritableStream.
  2212. auto stream = realm.heap().allocate<WritableStream>(realm, realm);
  2213. // 3. Perform ! InitializeWritableStream(stream).
  2214. initialize_writable_stream(*stream);
  2215. // 4. Let controller be a new WritableStreamDefaultController.
  2216. auto controller = realm.heap().allocate<WritableStreamDefaultController>(realm, realm);
  2217. // 5. Perform ? SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm).
  2218. 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)));
  2219. // 6. Return stream.
  2220. return stream;
  2221. }
  2222. // https://streams.spec.whatwg.org/#initialize-readable-stream
  2223. void initialize_readable_stream(ReadableStream& stream)
  2224. {
  2225. // 1. Set stream.[[state]] to "readable".
  2226. stream.set_state(ReadableStream::State::Readable);
  2227. // 2. Set stream.[[reader]] and stream.[[storedError]] to undefined.
  2228. stream.set_reader({});
  2229. stream.set_stored_error({});
  2230. // 3. Set stream.[[disturbed]] to false.
  2231. stream.set_disturbed(false);
  2232. }
  2233. // https://streams.spec.whatwg.org/#initialize-writable-stream
  2234. void initialize_writable_stream(WritableStream& stream)
  2235. {
  2236. // 1. Set stream.[[state]] to "writable".
  2237. stream.set_state(WritableStream::State::Writable);
  2238. // 2. Set stream.[[storedError]], stream.[[writer]], stream.[[controller]], stream.[[inFlightWriteRequest]],
  2239. // stream.[[closeRequest]], stream.[[inFlightCloseRequest]], and stream.[[pendingAbortRequest]] to undefined.
  2240. stream.set_stored_error(JS::js_undefined());
  2241. stream.set_writer({});
  2242. stream.set_controller({});
  2243. stream.set_in_flight_write_request({});
  2244. stream.set_close_request({});
  2245. stream.set_in_flight_close_request({});
  2246. stream.set_pending_abort_request({});
  2247. // 3. Set stream.[[writeRequests]] to a new empty list.
  2248. stream.write_requests().clear();
  2249. // 4. Set stream.[[backpressure]] to false.
  2250. stream.set_backpressure(false);
  2251. }
  2252. // https://streams.spec.whatwg.org/#acquire-writable-stream-default-writer
  2253. WebIDL::ExceptionOr<JS::NonnullGCPtr<WritableStreamDefaultWriter>> acquire_writable_stream_default_writer(WritableStream& stream)
  2254. {
  2255. auto& realm = stream.realm();
  2256. // 1. Let writer be a new WritableStreamDefaultWriter.
  2257. auto writer = stream.heap().allocate<WritableStreamDefaultWriter>(realm, realm);
  2258. // 2. Perform ? SetUpWritableStreamDefaultWriter(writer, stream).
  2259. TRY(set_up_writable_stream_default_writer(*writer, stream));
  2260. // 3. Return writer.
  2261. return writer;
  2262. }
  2263. // https://streams.spec.whatwg.org/#is-writable-stream-locked
  2264. bool is_writable_stream_locked(WritableStream const& stream)
  2265. {
  2266. // 1. If stream.[[writer]] is undefined, return false.
  2267. if (!stream.writer())
  2268. return false;
  2269. // 2. Return true.
  2270. return true;
  2271. }
  2272. // https://streams.spec.whatwg.org/#set-up-writable-stream-default-writer
  2273. WebIDL::ExceptionOr<void> set_up_writable_stream_default_writer(WritableStreamDefaultWriter& writer, WritableStream& stream)
  2274. {
  2275. auto& realm = writer.realm();
  2276. // 1. If ! IsWritableStreamLocked(stream) is true, throw a TypeError exception.
  2277. if (is_writable_stream_locked(stream))
  2278. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Stream is locked"sv };
  2279. // 2. Set writer.[[stream]] to stream.
  2280. writer.set_stream(stream);
  2281. // 3. Set stream.[[writer]] to writer.
  2282. stream.set_writer(writer);
  2283. // 4. Let state be stream.[[state]].
  2284. auto state = stream.state();
  2285. // 5. If state is "writable",
  2286. if (state == WritableStream::State::Writable) {
  2287. // 1. If ! WritableStreamCloseQueuedOrInFlight(stream) is false and stream.[[backpressure]] is true, set writer.[[readyPromise]] to a new promise.
  2288. if (!writable_stream_close_queued_or_in_flight(stream) && stream.backpressure()) {
  2289. writer.set_ready_promise(WebIDL::create_promise(realm));
  2290. }
  2291. // 2. Otherwise, set writer.[[readyPromise]] to a promise resolved with undefined.
  2292. else {
  2293. writer.set_ready_promise(WebIDL::create_resolved_promise(realm, JS::js_undefined()));
  2294. }
  2295. // 3. Set writer.[[closedPromise]] to a new promise.
  2296. writer.set_closed_promise(WebIDL::create_promise(realm));
  2297. }
  2298. // 6. Otherwise, if state is "erroring",
  2299. else if (state == WritableStream::State::Erroring) {
  2300. // 1. Set writer.[[readyPromise]] to a promise rejected with stream.[[storedError]].
  2301. writer.set_ready_promise(WebIDL::create_rejected_promise(realm, stream.stored_error()));
  2302. // 2. Set writer.[[readyPromise]].[[PromiseIsHandled]] to true.
  2303. WebIDL::mark_promise_as_handled(*writer.ready_promise());
  2304. // 3. Set writer.[[closedPromise]] to a new promise.
  2305. writer.set_closed_promise(WebIDL::create_promise(realm));
  2306. }
  2307. // 7. Otherwise, if state is "closed",
  2308. else if (state == WritableStream::State::Closed) {
  2309. // 1. Set writer.[[readyPromise]] to a promise resolved with undefined.
  2310. writer.set_ready_promise(WebIDL::create_resolved_promise(realm, JS::js_undefined()));
  2311. // 2. Set writer.[[closedPromise]] to a promise resolved with undefined.
  2312. writer.set_closed_promise(WebIDL::create_resolved_promise(realm, JS::js_undefined()));
  2313. }
  2314. // 8. Otherwise,
  2315. else {
  2316. // 1. Assert: state is "errored".
  2317. VERIFY(state == WritableStream::State::Errored);
  2318. // 2. Let storedError be stream.[[storedError]].
  2319. auto stored_error = stream.stored_error();
  2320. // 3. Set writer.[[readyPromise]] to a promise rejected with storedError.
  2321. writer.set_ready_promise(WebIDL::create_rejected_promise(realm, stored_error));
  2322. // 4. Set writer.[[readyPromise]].[[PromiseIsHandled]] to true.
  2323. WebIDL::mark_promise_as_handled(*writer.ready_promise());
  2324. // 5. Set writer.[[closedPromise]] to a promise rejected with storedError.
  2325. writer.set_closed_promise(WebIDL::create_rejected_promise(realm, stored_error));
  2326. // 6. Set writer.[[closedPromise]].[[PromiseIsHandled]] to true.
  2327. WebIDL::mark_promise_as_handled(*writer.closed_promise());
  2328. }
  2329. return {};
  2330. }
  2331. // https://streams.spec.whatwg.org/#set-up-readable-byte-stream-controller
  2332. 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)
  2333. {
  2334. auto& realm = stream.realm();
  2335. // 1. Assert: stream.[[controller]] is undefined.
  2336. VERIFY(!stream.controller().has_value());
  2337. // 2. If autoAllocateChunkSize is not undefined,
  2338. if (!auto_allocate_chunk_size.is_undefined()) {
  2339. // 1. Assert: ! IsInteger(autoAllocateChunkSize) is true.
  2340. VERIFY(auto_allocate_chunk_size.is_integral_number());
  2341. // 2. Assert: autoAllocateChunkSize is positive.
  2342. VERIFY(auto_allocate_chunk_size.as_double() > 0);
  2343. }
  2344. // 3. Set controller.[[stream]] to stream.
  2345. controller.set_stream(stream);
  2346. // 4. Set controller.[[pullAgain]] and controller.[[pulling]] to false.
  2347. controller.set_pull_again(false);
  2348. controller.set_pulling(false);
  2349. // 5. Set controller.[[byobRequest]] to null.
  2350. controller.set_byob_request({});
  2351. // 6. Perform ! ResetQueue(controller).
  2352. reset_queue(controller);
  2353. // 7. Set controller.[[closeRequested]] and controller.[[started]] to false.
  2354. controller.set_close_requested(false);
  2355. controller.set_started(false);
  2356. // 8. Set controller.[[strategyHWM]] to highWaterMark.
  2357. controller.set_strategy_hwm(high_water_mark);
  2358. // 9. Set controller.[[pullAlgorithm]] to pullAlgorithm.
  2359. controller.set_pull_algorithm(pull_algorithm);
  2360. // 10. Set controller.[[cancelAlgorithm]] to cancelAlgorithm.
  2361. controller.set_cancel_algorithm(cancel_algorithm);
  2362. // 11. Set controller.[[autoAllocateChunkSize]] to autoAllocateChunkSize.
  2363. if (auto_allocate_chunk_size.is_integral_number())
  2364. controller.set_auto_allocate_chunk_size(auto_allocate_chunk_size.as_double());
  2365. // 12. Set controller.[[pendingPullIntos]] to a new empty list.
  2366. controller.pending_pull_intos().clear();
  2367. // 13. Set stream.[[controller]] to controller.
  2368. stream.set_controller(ReadableStreamController { controller });
  2369. // 14. Let startResult be the result of performing startAlgorithm.
  2370. auto start_result = TRY(start_algorithm->function()());
  2371. // 15. Let startPromise be a promise resolved with startResult.
  2372. auto start_promise = WebIDL::create_resolved_promise(realm, start_result);
  2373. // 16. Upon fulfillment of startPromise,
  2374. WebIDL::upon_fulfillment(start_promise, JS::create_heap_function(controller.heap(), [&controller](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {
  2375. // 1. Set controller.[[started]] to true.
  2376. controller.set_started(true);
  2377. // 2. Assert: controller.[[pulling]] is false.
  2378. VERIFY(!controller.pulling());
  2379. // 3. Assert: controller.[[pullAgain]] is false.
  2380. VERIFY(!controller.pull_again());
  2381. // 4. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
  2382. readable_byte_stream_controller_call_pull_if_needed(controller);
  2383. return JS::js_undefined();
  2384. }));
  2385. // 17. Upon rejection of startPromise with reason r,
  2386. WebIDL::upon_rejection(start_promise, JS::create_heap_function(controller.heap(), [&controller](JS::Value r) -> WebIDL::ExceptionOr<JS::Value> {
  2387. // 1. Perform ! ReadableByteStreamControllerError(controller, r).
  2388. readable_byte_stream_controller_error(controller, r);
  2389. return JS::js_undefined();
  2390. }));
  2391. return {};
  2392. }
  2393. // https://streams.spec.whatwg.org/#readablestream-enqueue
  2394. WebIDL::ExceptionOr<void> readable_stream_enqueue(ReadableStreamController& controller, JS::Value chunk)
  2395. {
  2396. // 1. If stream.[[controller]] implements ReadableStreamDefaultController,
  2397. if (controller.has<JS::NonnullGCPtr<ReadableStreamDefaultController>>()) {
  2398. // 1. Perform ! ReadableStreamDefaultControllerEnqueue(stream.[[controller]], chunk).
  2399. return readable_stream_default_controller_enqueue(controller.get<JS::NonnullGCPtr<ReadableStreamDefaultController>>(), chunk);
  2400. }
  2401. // 2. Otherwise,
  2402. else {
  2403. // 1. Assert: stream.[[controller]] implements ReadableByteStreamController.
  2404. VERIFY(controller.has<JS::NonnullGCPtr<ReadableByteStreamController>>());
  2405. auto readable_byte_controller = controller.get<JS::NonnullGCPtr<ReadableByteStreamController>>();
  2406. // FIXME: 2. Assert: chunk is an ArrayBufferView.
  2407. // 3. Let byobView be the current BYOB request view for stream.
  2408. // FIXME: This is not what the spec means by 'current BYOB request view'
  2409. auto byob_view = readable_byte_controller->raw_byob_request();
  2410. // 4. If byobView is non-null, and chunk.[[ViewedArrayBuffer]] is byobView.[[ViewedArrayBuffer]], then:
  2411. if (byob_view) {
  2412. // FIXME: 1. Assert: chunk.[[ByteOffset]] is byobView.[[ByteOffset]].
  2413. // FIXME: 2. Assert: chunk.[[ByteLength]] ≤ byobView.[[ByteLength]].
  2414. // FIXME: 3. Perform ? ReadableByteStreamControllerRespond(stream.[[controller]], chunk.[[ByteLength]]).
  2415. TODO();
  2416. }
  2417. // 5. Otherwise, perform ? ReadableByteStreamControllerEnqueue(stream.[[controller]], chunk).
  2418. return readable_byte_stream_controller_enqueue(readable_byte_controller, chunk);
  2419. }
  2420. }
  2421. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-enqueue
  2422. WebIDL::ExceptionOr<void> readable_byte_stream_controller_enqueue(ReadableByteStreamController& controller, JS::Value chunk)
  2423. {
  2424. auto& vm = controller.vm();
  2425. auto& realm = controller.realm();
  2426. // 1. Let stream be controller.[[stream]].
  2427. auto stream = controller.stream();
  2428. // 2. If controller.[[closeRequested]] is true or stream.[[state]] is not "readable", return.
  2429. if (controller.close_requested() || stream->state() != ReadableStream ::State::Readable)
  2430. return {};
  2431. // 3. Let buffer be chunk.[[ViewedArrayBuffer]].
  2432. auto* typed_array = TRY(JS::typed_array_from(vm, chunk));
  2433. auto* buffer = typed_array->viewed_array_buffer();
  2434. // 4. Let byteOffset be chunk.[[ByteOffset]].
  2435. auto byte_offset = typed_array->byte_offset();
  2436. // 6. If ! IsDetachedBuffer(buffer) is true, throw a TypeError exception.
  2437. // FIXME: The streams spec has not been updated for resizable ArrayBuffer objects. We must perform step 6 before
  2438. // invoking TypedArrayByteLength in step 5. We also must check if the array is out-of-bounds, rather than
  2439. // just detached.
  2440. auto typed_array_record = JS::make_typed_array_with_buffer_witness_record(*typed_array, JS::ArrayBuffer::Order::SeqCst);
  2441. if (JS::is_typed_array_out_of_bounds(typed_array_record))
  2442. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BufferOutOfBounds, "TypedArray"sv);
  2443. // 5. Let byteLength be chunk.[[ByteLength]].
  2444. auto byte_length = JS::typed_array_byte_length(typed_array_record);
  2445. // 7. Let transferredBuffer be ? TransferArrayBuffer(buffer).
  2446. auto transferred_buffer = TRY(transfer_array_buffer(realm, *buffer));
  2447. // 8. If controller.[[pendingPullIntos]] is not empty,
  2448. if (!controller.pending_pull_intos().is_empty()) {
  2449. // 1. Let firstPendingPullInto be controller.[[pendingPullIntos]][0].
  2450. auto& first_pending_pull_into = controller.pending_pull_intos().first();
  2451. // 2. If ! IsDetachedBuffer(firstPendingPullInto’s buffer) is true, throw a TypeError exception.
  2452. if (first_pending_pull_into.buffer->is_detached()) {
  2453. auto error = JS::TypeError::create(realm, "Buffer is detached"sv);
  2454. return JS::throw_completion(error);
  2455. }
  2456. // 3. Perform ! ReadableByteStreamControllerInvalidateBYOBRequest(controller).
  2457. readable_byte_stream_controller_invalidate_byob_request(controller);
  2458. // 4. Set firstPendingPullInto’s buffer to ! TransferArrayBuffer(firstPendingPullInto’s buffer).
  2459. first_pending_pull_into.buffer = TRY(transfer_array_buffer(realm, first_pending_pull_into.buffer));
  2460. // 5. If firstPendingPullInto’s reader type is "none", perform ? ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto).
  2461. if (first_pending_pull_into.reader_type == ReaderType::None)
  2462. TRY(readable_byte_stream_controller_enqueue_detached_pull_into_queue(controller, first_pending_pull_into));
  2463. }
  2464. // 9. If ! ReadableStreamHasDefaultReader(stream) is true,
  2465. if (readable_stream_has_default_reader(*stream)) {
  2466. // 1. Perform ! ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller).
  2467. TRY(readable_byte_stream_controller_process_read_requests_using_queue(controller));
  2468. // 2. If ! ReadableStreamGetNumReadRequests(stream) is 0,
  2469. if (readable_stream_get_num_read_requests(*stream) == 0) {
  2470. // 1. Assert: controller.[[pendingPullIntos]] is empty.
  2471. VERIFY(controller.pending_pull_intos().is_empty());
  2472. // 2. Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength).
  2473. readable_byte_stream_controller_enqueue_chunk_to_queue(controller, transferred_buffer, byte_offset, byte_length);
  2474. }
  2475. // 3. Otherwise.
  2476. else {
  2477. // 1. Assert: controller.[[queue]] is empty.
  2478. VERIFY(controller.queue().is_empty());
  2479. // 2. If controller.[[pendingPullIntos]] is not empty,
  2480. if (!controller.pending_pull_intos().is_empty()) {
  2481. // 1. Assert: controller.[[pendingPullIntos]][0]'s reader type is "default".
  2482. VERIFY(controller.pending_pull_intos().first().reader_type == ReaderType::Default);
  2483. // 2. Perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).
  2484. readable_byte_stream_controller_shift_pending_pull_into(controller);
  2485. }
  2486. // 3. Let transferredView be ! Construct(%Uint8Array%, « transferredBuffer, byteOffset, byteLength »).
  2487. 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)));
  2488. // 4. Perform ! ReadableStreamFulfillReadRequest(stream, transferredView, false).
  2489. readable_stream_fulfill_read_request(*stream, transferred_view, false);
  2490. }
  2491. }
  2492. // 10. Otherwise, if ! ReadableStreamHasBYOBReader(stream) is true,
  2493. else if (readable_stream_has_byob_reader(*stream)) {
  2494. // 1. Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength).
  2495. readable_byte_stream_controller_enqueue_chunk_to_queue(controller, transferred_buffer, byte_offset, byte_length);
  2496. // 2. Perform ! ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller).
  2497. readable_byte_stream_controller_process_pull_into_descriptors_using_queue(controller);
  2498. }
  2499. // 11. Otherwise,
  2500. else {
  2501. // 1. Assert: ! IsReadableStreamLocked(stream) is false.
  2502. VERIFY(!is_readable_stream_locked(*stream));
  2503. // 2. Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength).
  2504. readable_byte_stream_controller_enqueue_chunk_to_queue(controller, transferred_buffer, byte_offset, byte_length);
  2505. }
  2506. // 12. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
  2507. readable_byte_stream_controller_call_pull_if_needed(controller);
  2508. return {};
  2509. }
  2510. // https://streams.spec.whatwg.org/#transfer-array-buffer
  2511. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::ArrayBuffer>> transfer_array_buffer(JS::Realm& realm, JS::ArrayBuffer& buffer)
  2512. {
  2513. auto& vm = realm.vm();
  2514. // 1. Assert: ! IsDetachedBuffer(O) is false.
  2515. VERIFY(!buffer.is_detached());
  2516. // 2. Let arrayBufferData be O.[[ArrayBufferData]].
  2517. // 3. Let arrayBufferByteLength be O.[[ArrayBufferByteLength]].
  2518. auto array_buffer = buffer.buffer();
  2519. // 4. Perform ? DetachArrayBuffer(O).
  2520. TRY(JS::detach_array_buffer(vm, buffer));
  2521. // 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.
  2522. return JS::ArrayBuffer::create(realm, move(array_buffer));
  2523. }
  2524. // https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollerenqueuedetachedpullintotoqueue
  2525. WebIDL::ExceptionOr<void> readable_byte_stream_controller_enqueue_detached_pull_into_queue(ReadableByteStreamController& controller, PullIntoDescriptor& pull_into_descriptor)
  2526. {
  2527. // 1. Assert: pullIntoDescriptor’s reader type is "none".
  2528. VERIFY(pull_into_descriptor.reader_type == ReaderType::None);
  2529. // 2. If pullIntoDescriptor’s bytes filled > 0, perform ? ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor’s buffer, pullIntoDescriptor’s byte offset, pullIntoDescriptor’s bytes filled).
  2530. if (pull_into_descriptor.bytes_filled > 0)
  2531. 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));
  2532. // 3. Perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).
  2533. readable_byte_stream_controller_shift_pending_pull_into(controller);
  2534. return {};
  2535. }
  2536. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-commit-pull-into-descriptor
  2537. void readable_byte_stream_controller_commit_pull_into_descriptor(ReadableStream& stream, PullIntoDescriptor const& pull_into_descriptor)
  2538. {
  2539. // 1. Assert: stream.[[state]] is not "errored".
  2540. VERIFY(!stream.is_errored());
  2541. // 2. Assert: pullIntoDescriptor.reader type is not "none".
  2542. VERIFY(pull_into_descriptor.reader_type != ReaderType::None);
  2543. // 3. Let done be false.
  2544. bool done = false;
  2545. // 4. If stream.[[state]] is "closed",
  2546. if (stream.is_closed()) {
  2547. // 1. Assert: pullIntoDescriptor’s bytes filled is 0.
  2548. VERIFY(pull_into_descriptor.bytes_filled == 0);
  2549. // 2. Set done to true.
  2550. done = true;
  2551. }
  2552. // 5. Let filledView be ! ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor).
  2553. auto filled_view = readable_byte_stream_controller_convert_pull_into_descriptor(stream.realm(), pull_into_descriptor);
  2554. // 6. If pullIntoDescriptor’s reader type is "default",
  2555. if (pull_into_descriptor.reader_type == ReaderType::Default) {
  2556. // 1. Perform ! ReadableStreamFulfillReadRequest(stream, filledView, done).
  2557. readable_stream_fulfill_read_request(stream, filled_view, done);
  2558. }
  2559. // 7. Otherwise,
  2560. else {
  2561. // 1. Assert: pullIntoDescriptor’s reader type is "byob".
  2562. VERIFY(pull_into_descriptor.reader_type == ReaderType::Byob);
  2563. // 2. Perform ! ReadableStreamFulfillReadIntoRequest(stream, filledView, done).
  2564. readable_stream_fulfill_read_into_request(stream, filled_view, done);
  2565. }
  2566. }
  2567. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-process-pull-into-descriptors-using-queue
  2568. void readable_byte_stream_controller_process_pull_into_descriptors_using_queue(ReadableByteStreamController& controller)
  2569. {
  2570. // 1. Assert: controller.[[closeRequested]] is false.
  2571. VERIFY(!controller.close_requested());
  2572. // 2. While controller.[[pendingPullIntos]] is not empty,
  2573. while (!controller.pending_pull_intos().is_empty()) {
  2574. // 1. If controller.[[queueTotalSize]] is 0, return.
  2575. if (controller.queue_total_size() == 0)
  2576. return;
  2577. // 2. Let pullIntoDescriptor be controller.[[pendingPullIntos]][0].
  2578. auto& pull_into_descriptor = controller.pending_pull_intos().first();
  2579. // 3. If ! ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) is true,
  2580. if (readable_byte_stream_controller_fill_pull_into_descriptor_from_queue(controller, pull_into_descriptor)) {
  2581. // NOTE: We store the returned pull into descriptor here as the 'shift pending pull into' will remove
  2582. // the first entry into the list which we have a reference to above.
  2583. // 1. Perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).
  2584. auto descriptor = readable_byte_stream_controller_shift_pending_pull_into(controller);
  2585. // 2. Perform ! ReadableByteStreamControllerCommitPullIntoDescriptor(controller.[[stream]], pullIntoDescriptor).
  2586. readable_byte_stream_controller_commit_pull_into_descriptor(*controller.stream(), descriptor);
  2587. }
  2588. }
  2589. }
  2590. // https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollerprocessreadrequestsusingqueue
  2591. WebIDL::ExceptionOr<void> readable_byte_stream_controller_process_read_requests_using_queue(ReadableByteStreamController& controller)
  2592. {
  2593. // 1. Let reader be controller.[[stream]].[[reader]].
  2594. auto reader = controller.stream()->reader();
  2595. // 2. Assert: reader implements ReadableStreamDefaultReader.
  2596. VERIFY(reader->has<JS::NonnullGCPtr<ReadableStreamDefaultReader>>());
  2597. // 3. While reader.[[readRequests]] is not empty,
  2598. auto readable_stream_default_reader = reader->get<JS::NonnullGCPtr<ReadableStreamDefaultReader>>();
  2599. while (!readable_stream_default_reader->read_requests().is_empty()) {
  2600. // 1. If controller.[[queueTotalSize]] is 0, return.
  2601. if (controller.queue_total_size() == 0.0)
  2602. return {};
  2603. // 2. Let readRequest be reader.[[readRequests]][0].
  2604. // 3. Remove readRequest from reader.[[readRequests]].
  2605. auto read_request = readable_stream_default_reader->read_requests().take_first();
  2606. // 4. Perform ! ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest).
  2607. TRY(readable_byte_stream_controller_fill_read_request_from_queue(controller, read_request));
  2608. }
  2609. return {};
  2610. }
  2611. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-enqueue-chunk-to-queue
  2612. void readable_byte_stream_controller_enqueue_chunk_to_queue(ReadableByteStreamController& controller, JS::NonnullGCPtr<JS::ArrayBuffer> buffer, u32 byte_offset, u32 byte_length)
  2613. {
  2614. // 1. Append a new readable byte stream queue entry with buffer buffer, byte offset byteOffset, and byte length byteLength to controller.[[queue]].
  2615. controller.queue().append(ReadableByteStreamQueueEntry {
  2616. .buffer = buffer,
  2617. .byte_offset = byte_offset,
  2618. .byte_length = byte_length,
  2619. });
  2620. // 2. Set controller.[[queueTotalSize]] to controller.[[queueTotalSize]] + byteLength.
  2621. controller.set_queue_total_size(controller.queue_total_size() + byte_length);
  2622. }
  2623. // https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollerenqueueclonedchunktoqueue
  2624. WebIDL::ExceptionOr<void> readable_byte_stream_controller_enqueue_cloned_chunk_to_queue(ReadableByteStreamController& controller, JS::ArrayBuffer& buffer, u64 byte_offset, u64 byte_length)
  2625. {
  2626. auto& vm = controller.vm();
  2627. // 1. Let cloneResult be CloneArrayBuffer(buffer, byteOffset, byteLength, %ArrayBuffer%).
  2628. auto clone_result = JS::clone_array_buffer(vm, buffer, byte_offset, byte_length);
  2629. // 2. If cloneResult is an abrupt completion,
  2630. if (clone_result.is_throw_completion()) {
  2631. auto throw_completion = Bindings::throw_dom_exception_if_needed(vm, [&] { return clone_result; }).throw_completion();
  2632. // 1. Perform ! ReadableByteStreamControllerError(controller, cloneResult.[[Value]]).
  2633. readable_byte_stream_controller_error(controller, throw_completion.value().value());
  2634. // 2. Return cloneResult.
  2635. // Note: We need to return the throw_completion object here, as enqueue needs to throw the same object that the controller is errored with
  2636. return throw_completion;
  2637. }
  2638. // 3. Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(controller, cloneResult.[[Value]], 0, byteLength).
  2639. readable_byte_stream_controller_enqueue_chunk_to_queue(controller, *clone_result.release_value(), 0, byte_length);
  2640. return {};
  2641. }
  2642. // https://streams.spec.whatwg.org/#readable-byte-stream-controller-shift-pending-pull-into
  2643. PullIntoDescriptor readable_byte_stream_controller_shift_pending_pull_into(ReadableByteStreamController& controller)
  2644. {
  2645. // 1. Assert: controller.[[byobRequest]] is null.
  2646. VERIFY(!controller.raw_byob_request());
  2647. // 2. Let descriptor be controller.[[pendingPullIntos]][0].
  2648. // 3. Remove descriptor from controller.[[pendingPullIntos]].
  2649. auto descriptor = controller.pending_pull_intos().take_first();
  2650. // 4. Return descriptor.
  2651. return descriptor;
  2652. }
  2653. // https://streams.spec.whatwg.org/#readablestream-set-up-with-byte-reading-support
  2654. 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)
  2655. {
  2656. auto& realm = stream.realm();
  2657. // 1. Let startAlgorithm be an algorithm that returns undefined.
  2658. auto start_algorithm = JS::create_heap_function(realm.heap(), []() -> WebIDL::ExceptionOr<JS::Value> { return JS::js_undefined(); });
  2659. // 2. Let pullAlgorithmWrapper be an algorithm that runs these steps:
  2660. auto pull_algorithm_wrapper = JS::create_heap_function(realm.heap(), [&realm, pull_algorithm]() {
  2661. // 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.
  2662. JS::GCPtr<JS::PromiseCapability> result = nullptr;
  2663. if (pull_algorithm)
  2664. result = pull_algorithm->function()();
  2665. // 2. If result is a Promise, then return result.
  2666. if (result != nullptr)
  2667. return JS::NonnullGCPtr(*result);
  2668. // 3. Return a promise resolved with undefined.
  2669. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  2670. });
  2671. // 3. Let cancelAlgorithmWrapper be an algorithm that runs these steps:
  2672. auto cancel_algorithm_wrapper = JS::create_heap_function(realm.heap(), [&realm, cancel_algorithm](JS::Value c) {
  2673. // 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.
  2674. JS::GCPtr<JS::PromiseCapability> result = nullptr;
  2675. if (cancel_algorithm)
  2676. result = cancel_algorithm->function()(c);
  2677. // 2. If result is a Promise, then return result.
  2678. if (result != nullptr)
  2679. return JS::NonnullGCPtr(*result);
  2680. // 3. Return a promise resolved with undefined.
  2681. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  2682. });
  2683. // 4. Perform ! InitializeReadableStream(stream).
  2684. // 5. Let controller be a new ReadableByteStreamController.
  2685. auto controller = stream.heap().allocate<ReadableByteStreamController>(realm, realm);
  2686. // 6. Perform ! SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithmWrapper, cancelAlgorithmWrapper, highWaterMark, undefined).
  2687. TRY(set_up_readable_byte_stream_controller(stream, controller, start_algorithm, pull_algorithm_wrapper, cancel_algorithm_wrapper, high_water_mark, JS::js_undefined()));
  2688. return {};
  2689. }
  2690. // https://streams.spec.whatwg.org/#writable-stream-abort
  2691. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> writable_stream_abort(WritableStream& stream, JS::Value reason)
  2692. {
  2693. auto& realm = stream.realm();
  2694. // 1. If stream.[[state]] is "closed" or "errored", return a promise resolved with undefined.
  2695. auto state = stream.state();
  2696. if (state == WritableStream::State::Closed || state == WritableStream::State::Errored)
  2697. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  2698. // 2. Signal abort on stream.[[controller]].[[signal]] with reason.
  2699. stream.controller()->signal()->signal_abort(reason);
  2700. // 3. Let state be stream.[[state]].
  2701. state = stream.state();
  2702. // 4. If state is "closed" or "errored", return a promise resolved with undefined.
  2703. if (state == WritableStream::State::Closed || state == WritableStream::State::Errored)
  2704. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  2705. // 5. If stream.[[pendingAbortRequest]] is not undefined, return stream.[[pendingAbortRequest]]'s promise.
  2706. if (stream.pending_abort_request().has_value())
  2707. return stream.pending_abort_request()->promise;
  2708. // 6. Assert: state is "writable" or "erroring".
  2709. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  2710. // 7. Let wasAlreadyErroring be false.
  2711. auto was_already_erroring = false;
  2712. // 8. If state is "erroring",
  2713. if (state == WritableStream::State::Erroring) {
  2714. // 1. Set wasAlreadyErroring to true.
  2715. was_already_erroring = true;
  2716. // 2. Set reason to undefined.
  2717. reason = JS::js_undefined();
  2718. }
  2719. // 9. Let promise be a new promise.
  2720. auto promise = WebIDL::create_promise(realm);
  2721. // 10. Set stream.[[pendingAbortRequest]] to a new pending abort request whose promise is promise, reason is reason, and was already erroring is wasAlreadyErroring.
  2722. stream.set_pending_abort_request(PendingAbortRequest { promise, reason, was_already_erroring });
  2723. // 11. If wasAlreadyErroring is false, perform ! WritableStreamStartErroring(stream, reason).
  2724. if (!was_already_erroring)
  2725. TRY(writable_stream_start_erroring(stream, reason));
  2726. // 12. Return promise.
  2727. return promise;
  2728. }
  2729. // https://streams.spec.whatwg.org/#writable-stream-close
  2730. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> writable_stream_close(WritableStream& stream)
  2731. {
  2732. auto& realm = stream.realm();
  2733. // 1. Let state be stream.[[state]].
  2734. auto state = stream.state();
  2735. // 2. If state is "closed" or "errored", return a promise rejected with a TypeError exception.
  2736. if (state == WritableStream::State::Closed || state == WritableStream::State::Errored) {
  2737. auto message = state == WritableStream::State::Closed ? "Cannot close a closed stream"sv : "Cannot close an errored stream"sv;
  2738. auto exception = JS::TypeError::create(realm, message);
  2739. return WebIDL::create_rejected_promise(realm, exception);
  2740. }
  2741. // 3. Assert: state is "writable" or "erroring".
  2742. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  2743. // 4. Assert: ! WritableStreamCloseQueuedOrInFlight(stream) is false.
  2744. VERIFY(!writable_stream_close_queued_or_in_flight(stream));
  2745. // 5. Let promise be a new promise.
  2746. auto promise = WebIDL::create_promise(realm);
  2747. // 6. Set stream.[[closeRequest]] to promise.
  2748. stream.set_close_request(promise);
  2749. // 7. Let writer be stream.[[writer]].
  2750. auto writer = stream.writer();
  2751. // 8. If writer is not undefined, and stream.[[backpressure]] is true, and state is "writable", resolve writer.[[readyPromise]] with undefined.
  2752. if (writer && stream.backpressure() && state == WritableStream::State::Writable)
  2753. WebIDL::resolve_promise(realm, *writer->ready_promise(), JS::js_undefined());
  2754. // 9. Perform ! WritableStreamDefaultControllerClose(stream.[[controller]]).
  2755. TRY(writable_stream_default_controller_close(*stream.controller()));
  2756. // 10. Return promise.
  2757. return promise;
  2758. }
  2759. // https://streams.spec.whatwg.org/#writable-stream-add-write-request
  2760. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> writable_stream_add_write_request(WritableStream& stream)
  2761. {
  2762. auto& realm = stream.realm();
  2763. auto& vm = stream.vm();
  2764. // 1. Assert: ! IsWritableStreamLocked(stream) is true.
  2765. VERIFY(is_writable_stream_locked(stream));
  2766. // 2. Assert: stream.[[state]] is "writable".
  2767. VERIFY(stream.state() == WritableStream::State::Writable);
  2768. // 3. Let promise be a new promise.
  2769. auto promise = WebIDL::create_promise(realm);
  2770. // 4. Append promise to stream.[[writeRequests]].
  2771. TRY_OR_THROW_OOM(vm, stream.write_requests().try_append(promise));
  2772. // 5. Return promise.
  2773. return promise;
  2774. }
  2775. // https://streams.spec.whatwg.org/#writable-stream-close-queued-or-in-flight
  2776. bool writable_stream_close_queued_or_in_flight(WritableStream const& stream)
  2777. {
  2778. // 1. If stream.[[closeRequest]] is undefined and stream.[[inFlightCloseRequest]] is undefined, return false.
  2779. if (!stream.close_request() && !stream.in_flight_close_request())
  2780. return false;
  2781. // 2. Return true.
  2782. return true;
  2783. }
  2784. // https://streams.spec.whatwg.org/#writable-stream-deal-with-rejection
  2785. WebIDL::ExceptionOr<void> writable_stream_deal_with_rejection(WritableStream& stream, JS::Value error)
  2786. {
  2787. // 1. Let state be stream.[[state]].
  2788. auto state = stream.state();
  2789. // 2. If state is "writable",
  2790. if (state == WritableStream::State::Writable) {
  2791. // 1. Perform ! WritableStreamStartErroring(stream, error).
  2792. // 2. Return.
  2793. return writable_stream_start_erroring(stream, error);
  2794. }
  2795. // 3. Assert: state is "erroring".
  2796. VERIFY(state == WritableStream::State::Erroring);
  2797. // 4. Perform ! WritableStreamFinishErroring(stream).
  2798. return writable_stream_finish_erroring(stream);
  2799. }
  2800. // https://streams.spec.whatwg.org/#writable-stream-finish-erroring
  2801. WebIDL::ExceptionOr<void> writable_stream_finish_erroring(WritableStream& stream)
  2802. {
  2803. auto& realm = stream.realm();
  2804. // 1. Assert: stream.[[state]] is "erroring".
  2805. VERIFY(stream.state() == WritableStream::State::Erroring);
  2806. // 2. Assert: ! WritableStreamHasOperationMarkedInFlight(stream) is false.
  2807. VERIFY(!writable_stream_has_operation_marked_in_flight(stream));
  2808. // 3. Set stream.[[state]] to "errored".
  2809. stream.set_state(WritableStream::State::Errored);
  2810. // 4. Perform ! stream.[[controller]].[[ErrorSteps]]().
  2811. stream.controller()->error_steps();
  2812. // 5. Let storedError be stream.[[storedError]].
  2813. auto stored_error = stream.stored_error();
  2814. // 6. For each writeRequest of stream.[[writeRequests]]:
  2815. for (auto& write_request : stream.write_requests()) {
  2816. // 1. Reject writeRequest with storedError.
  2817. WebIDL::reject_promise(realm, *write_request, stored_error);
  2818. }
  2819. // 7. Set stream.[[writeRequests]] to an empty list.
  2820. stream.write_requests().clear();
  2821. // 8. If stream.[[pendingAbortRequest]] is undefined,
  2822. if (!stream.pending_abort_request().has_value()) {
  2823. // 1. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream).
  2824. writable_stream_reject_close_and_closed_promise_if_needed(stream);
  2825. // 2. Return.
  2826. return {};
  2827. }
  2828. // 9. Let abortRequest be stream.[[pendingAbortRequest]].
  2829. // 10. Set stream.[[pendingAbortRequest]] to undefined.
  2830. auto abort_request = stream.pending_abort_request().release_value();
  2831. // 11. If abortRequest’s was already erroring is true,
  2832. if (abort_request.was_already_erroring) {
  2833. // 1. Reject abortRequest’s promise with storedError.
  2834. WebIDL::reject_promise(realm, abort_request.promise, stored_error);
  2835. // 2. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream).
  2836. writable_stream_reject_close_and_closed_promise_if_needed(stream);
  2837. // 3. Return.
  2838. return {};
  2839. }
  2840. // 12. Let promise be ! stream.[[controller]].[[AbortSteps]](abortRequest’s reason).
  2841. auto promise = TRY(stream.controller()->abort_steps(abort_request.reason));
  2842. // 13. Upon fulfillment of promise,
  2843. WebIDL::upon_fulfillment(*promise, JS::create_heap_function(realm.heap(), [&realm, &stream, abort_promise = abort_request.promise](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {
  2844. // 1. Resolve abortRequest’s promise with undefined.
  2845. WebIDL::resolve_promise(realm, abort_promise, JS::js_undefined());
  2846. // 2. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream).
  2847. writable_stream_reject_close_and_closed_promise_if_needed(stream);
  2848. return JS::js_undefined();
  2849. }));
  2850. // 14. Upon rejection of promise with reason reason,
  2851. WebIDL::upon_rejection(*promise, JS::create_heap_function(realm.heap(), [&realm, &stream, abort_promise = abort_request.promise](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {
  2852. // 1. Reject abortRequest’s promise with reason.
  2853. WebIDL::reject_promise(realm, abort_promise, reason);
  2854. // 2. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream).
  2855. writable_stream_reject_close_and_closed_promise_if_needed(stream);
  2856. return JS::js_undefined();
  2857. }));
  2858. return {};
  2859. }
  2860. // https://streams.spec.whatwg.org/#writable-stream-finish-in-flight-close
  2861. void writable_stream_finish_in_flight_close(WritableStream& stream)
  2862. {
  2863. auto& realm = stream.realm();
  2864. // 1. Assert: stream.[[inFlightCloseRequest]] is not undefined.
  2865. VERIFY(stream.in_flight_close_request());
  2866. // 2. Resolve stream.[[inFlightCloseRequest]] with undefined.
  2867. WebIDL::resolve_promise(realm, *stream.in_flight_close_request(), JS::js_undefined());
  2868. // 3. Set stream.[[inFlightCloseRequest]] to undefined.
  2869. stream.set_in_flight_close_request({});
  2870. // 4. Let state be stream.[[state]].
  2871. auto state = stream.state();
  2872. // 5. Assert: stream.[[state]] is "writable" or "erroring".
  2873. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  2874. // 6. If state is "erroring",
  2875. if (state == WritableStream::State::Erroring) {
  2876. // 1. Set stream.[[storedError]] to undefined.
  2877. stream.set_stored_error(JS::js_undefined());
  2878. // 2. If stream.[[pendingAbortRequest]] is not undefined,
  2879. if (stream.pending_abort_request().has_value()) {
  2880. // 1. Resolve stream.[[pendingAbortRequest]]'s promise with undefined.
  2881. // 2. Set stream.[[pendingAbortRequest]] to undefined.
  2882. WebIDL::resolve_promise(realm, stream.pending_abort_request().release_value().promise, JS::js_undefined());
  2883. }
  2884. }
  2885. // 7. Set stream.[[state]] to "closed".
  2886. stream.set_state(WritableStream::State::Closed);
  2887. // 8. Let writer be stream.[[writer]].
  2888. auto writer = stream.writer();
  2889. // 9. If writer is not undefined, resolve writer.[[closedPromise]] with undefined.
  2890. if (writer)
  2891. WebIDL::resolve_promise(realm, *writer->closed_promise(), JS::js_undefined());
  2892. // 10. Assert: stream.[[pendingAbortRequest]] is undefined.
  2893. VERIFY(!stream.pending_abort_request().has_value());
  2894. // 11. Assert: stream.[[storedError]] is undefined.
  2895. VERIFY(stream.stored_error().is_undefined());
  2896. }
  2897. // https://streams.spec.whatwg.org/#writable-stream-finish-in-flight-close-with-error
  2898. WebIDL::ExceptionOr<void> writable_stream_finish_in_flight_close_with_error(WritableStream& stream, JS::Value error)
  2899. {
  2900. auto& realm = stream.realm();
  2901. // 1. Assert: stream.[[inFlightCloseRequest]] is not undefined.
  2902. VERIFY(stream.in_flight_close_request());
  2903. // 2. Reject stream.[[inFlightCloseRequest]] with error.
  2904. WebIDL::reject_promise(realm, *stream.in_flight_close_request(), error);
  2905. // 3. Set stream.[[inFlightCloseRequest]] to undefined.
  2906. stream.set_in_flight_close_request({});
  2907. // 4. Assert: stream.[[state]] is "writable" or "erroring".
  2908. auto state = stream.state();
  2909. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  2910. // 5. If stream.[[pendingAbortRequest]] is not undefined,
  2911. if (stream.pending_abort_request().has_value()) {
  2912. // 1. Reject stream.[[pendingAbortRequest]]'s promise with error.
  2913. // 2. Set stream.[[pendingAbortRequest]] to undefined.
  2914. WebIDL::reject_promise(realm, stream.pending_abort_request().release_value().promise, error);
  2915. }
  2916. // 6. Perform ! WritableStreamDealWithRejection(stream, error).
  2917. return writable_stream_deal_with_rejection(stream, error);
  2918. }
  2919. // https://streams.spec.whatwg.org/#writable-stream-finish-in-flight-write
  2920. void writable_stream_finish_in_flight_write(WritableStream& stream)
  2921. {
  2922. auto& realm = stream.realm();
  2923. // 1. Assert: stream.[[inFlightWriteRequest]] is not undefined.
  2924. VERIFY(stream.in_flight_write_request());
  2925. // 2. Resolve stream.[[inFlightWriteRequest]] with undefined.
  2926. WebIDL::resolve_promise(realm, *stream.in_flight_write_request(), JS::js_undefined());
  2927. // 3. Set stream.[[inFlightWriteRequest]] to undefined.
  2928. stream.set_in_flight_write_request({});
  2929. }
  2930. // https://streams.spec.whatwg.org/#writable-stream-finish-in-flight-write-with-error
  2931. WebIDL::ExceptionOr<void> writable_stream_finish_in_flight_write_with_error(WritableStream& stream, JS::Value error)
  2932. {
  2933. auto& realm = stream.realm();
  2934. // 1. Assert: stream.[[inFlightWriteRequest]] is not undefined.
  2935. VERIFY(stream.in_flight_write_request());
  2936. // 2. Reject stream.[[inFlightWriteRequest]] with error.
  2937. WebIDL::reject_promise(realm, *stream.in_flight_write_request(), error);
  2938. // 3. Set stream.[[inFlightWriteRequest]] to undefined.
  2939. stream.set_in_flight_write_request({});
  2940. // 4. Assert: stream.[[state]] is "writable" or "erroring".
  2941. auto state = stream.state();
  2942. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  2943. // 5. Perform ! WritableStreamDealWithRejection(stream, error).
  2944. return writable_stream_deal_with_rejection(stream, error);
  2945. }
  2946. // https://streams.spec.whatwg.org/#writable-stream-has-operation-marked-in-flight
  2947. bool writable_stream_has_operation_marked_in_flight(WritableStream const& stream)
  2948. {
  2949. // 1. If stream.[[inFlightWriteRequest]] is undefined and stream.[[inFlightCloseRequest]] is undefined, return false.
  2950. if (!stream.in_flight_write_request() && !stream.in_flight_close_request())
  2951. return false;
  2952. // 2. Return true.
  2953. return true;
  2954. }
  2955. // https://streams.spec.whatwg.org/#writable-stream-mark-close-request-in-flight
  2956. void writable_stream_mark_close_request_in_flight(WritableStream& stream)
  2957. {
  2958. // 1. Assert: stream.[[inFlightCloseRequest]] is undefined.
  2959. VERIFY(!stream.in_flight_close_request());
  2960. // 2. Assert: stream.[[closeRequest]] is not undefined.
  2961. VERIFY(stream.close_request());
  2962. // 3. Set stream.[[inFlightCloseRequest]] to stream.[[closeRequest]].
  2963. stream.set_in_flight_close_request(stream.close_request());
  2964. // 4. Set stream.[[closeRequest]] to undefined.
  2965. stream.set_close_request({});
  2966. }
  2967. // https://streams.spec.whatwg.org/#writable-stream-mark-first-write-request-in-flight
  2968. void writable_stream_mark_first_write_request_in_flight(WritableStream& stream)
  2969. {
  2970. // 1. Assert: stream.[[inFlightWriteRequest]] is undefined.
  2971. VERIFY(!stream.in_flight_write_request());
  2972. // 2. Assert: stream.[[writeRequests]] is not empty.
  2973. VERIFY(!stream.write_requests().is_empty());
  2974. // 3. Let writeRequest be stream.[[writeRequests]][0].
  2975. // 4. Remove writeRequest from stream.[[writeRequests]].
  2976. auto write_request = stream.write_requests().take_first();
  2977. // 5. Set stream.[[inFlightWriteRequest]] to writeRequest.
  2978. stream.set_in_flight_write_request(write_request);
  2979. }
  2980. // https://streams.spec.whatwg.org/#writable-stream-reject-close-and-closed-promise-if-needed
  2981. void writable_stream_reject_close_and_closed_promise_if_needed(WritableStream& stream)
  2982. {
  2983. auto& realm = stream.realm();
  2984. // 1. Assert: stream.[[state]] is "errored".
  2985. VERIFY(stream.state() == WritableStream::State::Errored);
  2986. // 2. If stream.[[closeRequest]] is not undefined,
  2987. if (stream.close_request()) {
  2988. // 1. Assert: stream.[[inFlightCloseRequest]] is undefined.
  2989. VERIFY(!stream.in_flight_close_request());
  2990. // 2. Reject stream.[[closeRequest]] with stream.[[storedError]].
  2991. WebIDL::reject_promise(realm, *stream.close_request(), stream.stored_error());
  2992. // 3. Set stream.[[closeRequest]] to undefined.
  2993. stream.set_close_request({});
  2994. }
  2995. // 3. Let writer be stream.[[writer]].
  2996. auto writer = stream.writer();
  2997. // 4. If writer is not undefined,
  2998. if (writer) {
  2999. // 1. Reject writer.[[closedPromise]] with stream.[[storedError]].
  3000. WebIDL::reject_promise(realm, *writer->closed_promise(), stream.stored_error());
  3001. // 2. Set writer.[[closedPromise]].[[PromiseIsHandled]] to true.
  3002. WebIDL::mark_promise_as_handled(*writer->closed_promise());
  3003. }
  3004. }
  3005. // https://streams.spec.whatwg.org/#writable-stream-start-erroring
  3006. WebIDL::ExceptionOr<void> writable_stream_start_erroring(WritableStream& stream, JS::Value reason)
  3007. {
  3008. // 1. Assert: stream.[[storedError]] is undefined.
  3009. VERIFY(stream.stored_error().is_undefined());
  3010. // 2. Assert: stream.[[state]] is "writable".
  3011. VERIFY(stream.state() == WritableStream::State::Writable);
  3012. // 3. Let controller be stream.[[controller]].
  3013. auto controller = stream.controller();
  3014. // 4. Assert: controller is not undefined.
  3015. VERIFY(controller);
  3016. // 5. Set stream.[[state]] to "erroring".
  3017. stream.set_state(WritableStream::State::Erroring);
  3018. // 6. Set stream.[[storedError]] to reason.
  3019. stream.set_stored_error(reason);
  3020. // 7. Let writer be stream.[[writer]].
  3021. auto writer = stream.writer();
  3022. // 8. If writer is not undefined, perform ! WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason).
  3023. if (writer)
  3024. writable_stream_default_writer_ensure_ready_promise_rejected(*writer, reason);
  3025. // 9. If ! WritableStreamHasOperationMarkedInFlight(stream) is false and controller.[[started]] is true, perform ! WritableStreamFinishErroring(stream).
  3026. if (!writable_stream_has_operation_marked_in_flight(stream) && controller->started())
  3027. TRY(writable_stream_finish_erroring(stream));
  3028. return {};
  3029. }
  3030. // https://streams.spec.whatwg.org/#writable-stream-update-backpressure
  3031. void writable_stream_update_backpressure(WritableStream& stream, bool backpressure)
  3032. {
  3033. auto& realm = stream.realm();
  3034. // 1. Assert: stream.[[state]] is "writable".
  3035. VERIFY(stream.state() == WritableStream::State::Writable);
  3036. // 2. Assert: ! WritableStreamCloseQueuedOrInFlight(stream) is false.
  3037. VERIFY(!writable_stream_close_queued_or_in_flight(stream));
  3038. // 3. Let writer be stream.[[writer]].
  3039. auto writer = stream.writer();
  3040. // 4. If writer is not undefined and backpressure is not stream.[[backpressure]],
  3041. if (writer && backpressure != stream.backpressure()) {
  3042. // 1. If backpressure is true, set writer.[[readyPromise]] to a new promise.
  3043. if (backpressure) {
  3044. writer->set_ready_promise(WebIDL::create_promise(realm));
  3045. }
  3046. // 2. Otherwise,
  3047. else {
  3048. // 1. Assert: backpressure is false.
  3049. // 2. Resolve writer.[[readyPromise]] with undefined.
  3050. WebIDL::resolve_promise(realm, *writer->ready_promise(), JS::js_undefined());
  3051. }
  3052. }
  3053. // 5. Set stream.[[backpressure]] to backpressure.
  3054. stream.set_backpressure(backpressure);
  3055. }
  3056. // https://streams.spec.whatwg.org/#writable-stream-default-writer-abort
  3057. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> writable_stream_default_writer_abort(WritableStreamDefaultWriter& writer, JS::Value reason)
  3058. {
  3059. // 1. Let stream be writer.[[stream]].
  3060. auto stream = writer.stream();
  3061. // 2. Assert: stream is not undefined.
  3062. VERIFY(stream);
  3063. // 3. Return ! WritableStreamAbort(stream, reason).
  3064. return writable_stream_abort(*stream, reason);
  3065. }
  3066. // https://streams.spec.whatwg.org/#writable-stream-default-writer-close
  3067. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> writable_stream_default_writer_close(WritableStreamDefaultWriter& writer)
  3068. {
  3069. // 1. Let stream be writer.[[stream]].
  3070. auto stream = writer.stream();
  3071. // 2. Assert: stream is not undefined.
  3072. VERIFY(stream);
  3073. // 3. Return ! WritableStreamClose(stream).
  3074. return writable_stream_close(*stream);
  3075. }
  3076. // https://streams.spec.whatwg.org/#writable-stream-default-writer-ensure-closed-promise-rejected
  3077. void writable_stream_default_writer_ensure_closed_promise_rejected(WritableStreamDefaultWriter& writer, JS::Value error)
  3078. {
  3079. auto& realm = writer.realm();
  3080. // 1. If writer.[[closedPromise]].[[PromiseState]] is "pending", reject writer.[[closedPromise]] with error.
  3081. auto& closed_promise = verify_cast<JS::Promise>(*writer.closed_promise()->promise());
  3082. if (closed_promise.state() == JS::Promise::State::Pending) {
  3083. WebIDL::reject_promise(realm, *writer.closed_promise(), error);
  3084. }
  3085. // 2. Otherwise, set writer.[[closedPromise]] to a promise rejected with error.
  3086. else {
  3087. writer.set_closed_promise(WebIDL::create_rejected_promise(realm, error));
  3088. }
  3089. // 3. Set writer.[[closedPromise]].[[PromiseIsHandled]] to true.
  3090. WebIDL::mark_promise_as_handled(*writer.closed_promise());
  3091. }
  3092. // https://streams.spec.whatwg.org/#writable-stream-default-writer-ensure-ready-promise-rejected
  3093. void writable_stream_default_writer_ensure_ready_promise_rejected(WritableStreamDefaultWriter& writer, JS::Value error)
  3094. {
  3095. auto& realm = writer.realm();
  3096. // 1. If writer.[[readyPromise]].[[PromiseState]] is "pending", reject writer.[[readyPromise]] with error.
  3097. auto& ready_promise = verify_cast<JS::Promise>(*writer.ready_promise()->promise());
  3098. if (ready_promise.state() == JS::Promise::State::Pending) {
  3099. WebIDL::reject_promise(realm, *writer.ready_promise(), error);
  3100. }
  3101. // 2. Otherwise, set writer.[[readyPromise]] to a promise rejected with error.
  3102. else {
  3103. writer.set_ready_promise(WebIDL::create_rejected_promise(realm, error));
  3104. }
  3105. // 3. Set writer.[[readyPromise]].[[PromiseIsHandled]] to true.
  3106. WebIDL::mark_promise_as_handled(*writer.ready_promise());
  3107. }
  3108. // https://streams.spec.whatwg.org/#writable-stream-default-writer-get-desired-size
  3109. Optional<double> writable_stream_default_writer_get_desired_size(WritableStreamDefaultWriter const& writer)
  3110. {
  3111. // 1. Let stream be writer.[[stream]].
  3112. auto stream = writer.stream();
  3113. // 2. Let state be stream.[[state]].
  3114. auto state = stream->state();
  3115. // 3. If state is "errored" or "erroring", return null.
  3116. if (state == WritableStream::State::Errored || state == WritableStream::State::Erroring)
  3117. return {};
  3118. // 4. If state is "closed", return 0.
  3119. if (state == WritableStream::State::Closed)
  3120. return 0.0;
  3121. // 5. Return ! WritableStreamDefaultControllerGetDesiredSize(stream.[[controller]]).
  3122. return writable_stream_default_controller_get_desired_size(*stream->controller());
  3123. }
  3124. // https://streams.spec.whatwg.org/#writable-stream-default-writer-release
  3125. WebIDL::ExceptionOr<void> writable_stream_default_writer_release(WritableStreamDefaultWriter& writer)
  3126. {
  3127. auto& realm = writer.realm();
  3128. // 1. Let stream be writer.[[stream]].
  3129. auto stream = writer.stream();
  3130. // 2. Assert: stream is not undefined.
  3131. VERIFY(stream);
  3132. // 3. Assert: stream.[[writer]] is writer.
  3133. VERIFY(stream->writer().ptr() == &writer);
  3134. // 4. Let releasedError be a new TypeError.
  3135. auto released_error = JS::TypeError::create(realm, "Writer's stream lock has been released"sv);
  3136. // 5. Perform ! WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError).
  3137. writable_stream_default_writer_ensure_ready_promise_rejected(writer, released_error);
  3138. // 6. Perform ! WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError).
  3139. writable_stream_default_writer_ensure_closed_promise_rejected(writer, released_error);
  3140. // 7. Set stream.[[writer]] to undefined.
  3141. stream->set_writer({});
  3142. // 8. Set writer.[[stream]] to undefined.
  3143. writer.set_stream({});
  3144. return {};
  3145. }
  3146. // https://streams.spec.whatwg.org/#writable-stream-default-writer-write
  3147. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> writable_stream_default_writer_write(WritableStreamDefaultWriter& writer, JS::Value chunk)
  3148. {
  3149. auto& realm = writer.realm();
  3150. // 1. Let stream be writer.[[stream]].
  3151. auto stream = writer.stream();
  3152. // 2. Assert: stream is not undefined.
  3153. VERIFY(stream);
  3154. // 3. Let controller be stream.[[controller]].
  3155. auto controller = stream->controller();
  3156. // 4. Let chunkSize be ! WritableStreamDefaultControllerGetChunkSize(controller, chunk).
  3157. auto chunk_size = TRY(writable_stream_default_controller_get_chunk_size(*controller, chunk));
  3158. // 5. If stream is not equal to writer.[[stream]], return a promise rejected with a TypeError exception.
  3159. if (stream.ptr() != writer.stream().ptr()) {
  3160. auto exception = JS::TypeError::create(realm, "Writer's locked stream changed during write"sv);
  3161. return WebIDL::create_rejected_promise(realm, exception);
  3162. }
  3163. // 6. Let state be stream.[[state]].
  3164. auto state = stream->state();
  3165. // 7. If state is "errored", return a promise rejected with stream.[[storedError]].
  3166. if (state == WritableStream::State::Errored)
  3167. return WebIDL::create_rejected_promise(realm, stream->stored_error());
  3168. // 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.
  3169. if (writable_stream_close_queued_or_in_flight(*stream) || state == WritableStream::State::Closed) {
  3170. auto exception = JS::TypeError::create(realm, "Cannot write to a writer whose stream is closing or already closed"sv);
  3171. return WebIDL::create_rejected_promise(realm, exception);
  3172. }
  3173. // 9. If state is "erroring", return a promise rejected with stream.[[storedError]].
  3174. if (state == WritableStream::State::Erroring)
  3175. return WebIDL::create_rejected_promise(realm, stream->stored_error());
  3176. // 10. Assert: state is "writable".
  3177. VERIFY(state == WritableStream::State::Writable);
  3178. // 11. Let promise be ! WritableStreamAddWriteRequest(stream).
  3179. auto promise = writable_stream_add_write_request(*stream);
  3180. // 12. Perform ! WritableStreamDefaultControllerWrite(controller, chunk, chunkSize).
  3181. TRY(writable_stream_default_controller_write(*controller, chunk, chunk_size));
  3182. // 13. Return promise.
  3183. return promise;
  3184. }
  3185. // https://streams.spec.whatwg.org/#set-up-writable-stream-default-controller
  3186. 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)
  3187. {
  3188. auto& realm = stream.realm();
  3189. // 1. Assert: stream implements WritableStream.
  3190. // 2. Assert: stream.[[controller]] is undefined.
  3191. VERIFY(!stream.controller());
  3192. // 3. Set controller.[[stream]] to stream.
  3193. controller.set_stream(stream);
  3194. // 4. Set stream.[[controller]] to controller.
  3195. stream.set_controller(controller);
  3196. // 5. Perform ! ResetQueue(controller).
  3197. reset_queue(controller);
  3198. // 6. Set controller.[[signal]] to a new AbortSignal.
  3199. controller.set_signal(realm.heap().allocate<DOM::AbortSignal>(realm, realm));
  3200. // 7. Set controller.[[started]] to false.
  3201. controller.set_started(false);
  3202. // 8. Set controller.[[strategySizeAlgorithm]] to sizeAlgorithm.
  3203. controller.set_strategy_size_algorithm(size_algorithm);
  3204. // 9. Set controller.[[strategyHWM]] to highWaterMark.
  3205. controller.set_strategy_hwm(high_water_mark);
  3206. // 10. Set controller.[[writeAlgorithm]] to writeAlgorithm.
  3207. controller.set_write_algorithm(write_algorithm);
  3208. // 11. Set controller.[[closeAlgorithm]] to closeAlgorithm.
  3209. controller.set_close_algorithm(close_algorithm);
  3210. // 12. Set controller.[[abortAlgorithm]] to abortAlgorithm.
  3211. controller.set_abort_algorithm(abort_algorithm);
  3212. // 13. Let backpressure be ! WritableStreamDefaultControllerGetBackpressure(controller).
  3213. auto backpressure = writable_stream_default_controller_get_backpressure(controller);
  3214. // 14. Perform ! WritableStreamUpdateBackpressure(stream, backpressure).
  3215. writable_stream_update_backpressure(stream, backpressure);
  3216. // 15. Let startResult be the result of performing startAlgorithm. (This may throw an exception.)
  3217. auto start_result = TRY(start_algorithm->function()());
  3218. // 16. Let startPromise be a promise resolved with startResult.
  3219. auto start_promise = WebIDL::create_resolved_promise(realm, start_result);
  3220. // 17. Upon fulfillment of startPromise,
  3221. WebIDL::upon_fulfillment(*start_promise, JS::create_heap_function(realm.heap(), [&controller, &stream](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {
  3222. // 1. Assert: stream.[[state]] is "writable" or "erroring".
  3223. auto state = stream.state();
  3224. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  3225. // 2. Set controller.[[started]] to true.
  3226. controller.set_started(true);
  3227. // 3. Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).
  3228. TRY(writable_stream_default_controller_advance_queue_if_needed(controller));
  3229. return JS::js_undefined();
  3230. }));
  3231. // 18. Upon rejection of startPromise with reason r,
  3232. WebIDL::upon_rejection(*start_promise, JS::create_heap_function(realm.heap(), [&stream, &controller](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {
  3233. // 1. Assert: stream.[[state]] is "writable" or "erroring".
  3234. auto state = stream.state();
  3235. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  3236. // 2. Set controller.[[started]] to true.
  3237. controller.set_started(true);
  3238. // 3. Perform ! WritableStreamDealWithRejection(stream, r).
  3239. TRY(writable_stream_deal_with_rejection(stream, reason));
  3240. return JS::js_undefined();
  3241. }));
  3242. return {};
  3243. }
  3244. // https://streams.spec.whatwg.org/#set-up-writable-stream-default-controller-from-underlying-sink
  3245. 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)
  3246. {
  3247. auto& realm = stream.realm();
  3248. // 1. Let controller be a new WritableStreamDefaultController.
  3249. auto controller = realm.heap().allocate<WritableStreamDefaultController>(realm, realm);
  3250. // 2. Let startAlgorithm be an algorithm that returns undefined.
  3251. auto start_algorithm = JS::create_heap_function(realm.heap(), []() -> WebIDL::ExceptionOr<JS::Value> { return JS::js_undefined(); });
  3252. // 3. Let writeAlgorithm be an algorithm that returns a promise resolved with undefined.
  3253. auto write_algorithm = JS::create_heap_function(realm.heap(), [&realm](JS::Value) {
  3254. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  3255. });
  3256. // 4. Let closeAlgorithm be an algorithm that returns a promise resolved with undefined.
  3257. auto close_algorithm = JS::create_heap_function(realm.heap(), [&realm]() {
  3258. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  3259. });
  3260. // 5. Let abortAlgorithm be an algorithm that returns a promise resolved with undefined.
  3261. auto abort_algorithm = JS::create_heap_function(realm.heap(), [&realm](JS::Value) {
  3262. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  3263. });
  3264. // 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.
  3265. if (underlying_sink.start) {
  3266. start_algorithm = JS::create_heap_function(realm.heap(), [controller, underlying_sink_value, callback = underlying_sink.start]() -> WebIDL::ExceptionOr<JS::Value> {
  3267. // Note: callback does not return a promise, so invoke_callback may return an abrupt completion
  3268. return TRY(WebIDL::invoke_callback(*callback, underlying_sink_value, controller)).release_value();
  3269. });
  3270. }
  3271. // 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.
  3272. if (underlying_sink.write) {
  3273. write_algorithm = JS::create_heap_function(realm.heap(), [&realm, controller, underlying_sink_value, callback = underlying_sink.write](JS::Value chunk) {
  3274. // Note: callback returns a promise, so invoke_callback will never return an abrupt completion
  3275. auto result = MUST(WebIDL::invoke_callback(*callback, underlying_sink_value, chunk, controller)).release_value();
  3276. return WebIDL::create_resolved_promise(realm, result);
  3277. });
  3278. }
  3279. // 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.
  3280. if (underlying_sink.close) {
  3281. close_algorithm = JS::create_heap_function(realm.heap(), [&realm, underlying_sink_value, callback = underlying_sink.close]() {
  3282. // Note: callback returns a promise, so invoke_callback will never return an abrupt completion
  3283. auto result = MUST(WebIDL::invoke_callback(*callback, underlying_sink_value)).release_value();
  3284. return WebIDL::create_resolved_promise(realm, result);
  3285. });
  3286. }
  3287. // 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.
  3288. if (underlying_sink.abort) {
  3289. abort_algorithm = JS::create_heap_function(realm.heap(), [&realm, underlying_sink_value, callback = underlying_sink.abort](JS::Value reason) {
  3290. // Note: callback returns a promise, so invoke_callback will never return an abrupt completion
  3291. auto result = MUST(WebIDL::invoke_callback(*callback, underlying_sink_value, reason)).release_value();
  3292. return WebIDL::create_resolved_promise(realm, result);
  3293. });
  3294. }
  3295. // 10. Perform ? SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm).
  3296. TRY(set_up_writable_stream_default_controller(stream, controller, start_algorithm, write_algorithm, close_algorithm, abort_algorithm, high_water_mark, size_algorithm));
  3297. return {};
  3298. }
  3299. // https://streams.spec.whatwg.org/#writable-stream-default-controller-advance-queue-if-needed
  3300. WebIDL::ExceptionOr<void> writable_stream_default_controller_advance_queue_if_needed(WritableStreamDefaultController& controller)
  3301. {
  3302. // 1. Let stream be controller.[[stream]].
  3303. auto stream = controller.stream();
  3304. // 2. If controller.[[started]] is false, return.
  3305. if (!controller.started())
  3306. return {};
  3307. // 3. If stream.[[inFlightWriteRequest]] is not undefined, return.
  3308. if (stream->in_flight_write_request())
  3309. return {};
  3310. // 4. Let state be stream.[[state]].
  3311. auto state = stream->state();
  3312. // 5. Assert: state is not "closed" or "errored".
  3313. VERIFY(state != WritableStream::State::Closed && state != WritableStream::State::Errored);
  3314. // 6. If state is "erroring",
  3315. if (state == WritableStream::State::Erroring) {
  3316. // 1. Perform ! WritableStreamFinishErroring(stream).
  3317. // 2. Return.
  3318. return writable_stream_finish_erroring(*stream);
  3319. }
  3320. // 7. If controller.[[queue]] is empty, return.
  3321. if (controller.queue().is_empty())
  3322. return {};
  3323. // 8. Let value be ! PeekQueueValue(controller).
  3324. auto value = peek_queue_value(controller);
  3325. // 9. If value is the close sentinel, perform ! WritableStreamDefaultControllerProcessClose(controller).
  3326. if (is_close_sentinel(value)) {
  3327. writable_stream_default_controller_process_close(controller);
  3328. }
  3329. // 10. Otherwise, perform ! WritableStreamDefaultControllerProcessWrite(controller, value).
  3330. else {
  3331. writable_stream_default_controller_process_write(controller, value);
  3332. }
  3333. return {};
  3334. }
  3335. // https://streams.spec.whatwg.org/#writable-stream-default-controller-clear-algorithms
  3336. void writable_stream_default_controller_clear_algorithms(WritableStreamDefaultController& controller)
  3337. {
  3338. // 1. Set controller.[[writeAlgorithm]] to undefined.
  3339. controller.set_write_algorithm({});
  3340. // 2. Set controller.[[closeAlgorithm]] to undefined.
  3341. controller.set_close_algorithm({});
  3342. // 3. Set controller.[[abortAlgorithm]] to undefined.
  3343. controller.set_abort_algorithm({});
  3344. // 4. Set controller.[[strategySizeAlgorithm]] to undefined.
  3345. controller.set_strategy_size_algorithm({});
  3346. }
  3347. // https://streams.spec.whatwg.org/#writable-stream-default-controller-close
  3348. WebIDL::ExceptionOr<void> writable_stream_default_controller_close(WritableStreamDefaultController& controller)
  3349. {
  3350. // 1. Perform ! EnqueueValueWithSize(controller, close sentinel, 0).
  3351. TRY(enqueue_value_with_size(controller, create_close_sentinel(), JS::Value(0.0)));
  3352. // 2. Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).
  3353. TRY(writable_stream_default_controller_advance_queue_if_needed(controller));
  3354. return {};
  3355. }
  3356. // https://streams.spec.whatwg.org/#writable-stream-default-controller-error
  3357. WebIDL::ExceptionOr<void> writable_stream_default_controller_error(WritableStreamDefaultController& controller, JS::Value error)
  3358. {
  3359. // 1. Let stream be controller.[[stream]].
  3360. auto stream = controller.stream();
  3361. // 2. Assert: stream.[[state]] is "writable".
  3362. VERIFY(stream->state() == WritableStream::State::Writable);
  3363. // 3. Perform ! WritableStreamDefaultControllerClearAlgorithms(controller).
  3364. writable_stream_default_controller_clear_algorithms(controller);
  3365. // 4. Perform ! WritableStreamStartErroring(stream, error).
  3366. return writable_stream_start_erroring(stream, error);
  3367. }
  3368. // https://streams.spec.whatwg.org/#writable-stream-default-controller-error-if-needed
  3369. WebIDL::ExceptionOr<void> writable_stream_default_controller_error_if_needed(WritableStreamDefaultController& controller, JS::Value error)
  3370. {
  3371. // 1. If controller.[[stream]].[[state]] is "writable", perform ! WritableStreamDefaultControllerError(controller, error).
  3372. if (controller.stream()->state() == WritableStream::State::Writable)
  3373. TRY(writable_stream_default_controller_error(controller, error));
  3374. return {};
  3375. }
  3376. // https://streams.spec.whatwg.org/#writable-stream-default-controller-get-backpressure
  3377. bool writable_stream_default_controller_get_backpressure(WritableStreamDefaultController const& controller)
  3378. {
  3379. // 1. Let desiredSize be ! WritableStreamDefaultControllerGetDesiredSize(controller).
  3380. auto desired_size = writable_stream_default_controller_get_desired_size(controller);
  3381. // 2. Return true if desiredSize ≤ 0, or false otherwise.
  3382. return desired_size <= 0.0;
  3383. }
  3384. // https://streams.spec.whatwg.org/#writable-stream-default-controller-get-chunk-size
  3385. WebIDL::ExceptionOr<JS::Value> writable_stream_default_controller_get_chunk_size(WritableStreamDefaultController& controller, JS::Value chunk)
  3386. {
  3387. // 1. Let returnValue be the result of performing controller.[[strategySizeAlgorithm]], passing in chunk, and interpreting the result as a completion record.
  3388. auto return_value = controller.strategy_size_algorithm()->function()(chunk);
  3389. // 2. If returnValue is an abrupt completion,
  3390. if (return_value.is_abrupt()) {
  3391. // 1. Perform ! WritableStreamDefaultControllerErrorIfNeeded(controller, returnValue.[[Value]]).
  3392. TRY(writable_stream_default_controller_error_if_needed(controller, *return_value.release_value()));
  3393. // 2. Return 1.
  3394. return 1.0;
  3395. }
  3396. // 3. Return returnValue.[[Value]].
  3397. return *return_value.release_value();
  3398. }
  3399. // https://streams.spec.whatwg.org/#writable-stream-default-controller-get-desired-size
  3400. double writable_stream_default_controller_get_desired_size(WritableStreamDefaultController const& controller)
  3401. {
  3402. // 1. Return controller.[[strategyHWM]] − controller.[[queueTotalSize]].
  3403. return controller.strategy_hwm() - controller.queue_total_size();
  3404. }
  3405. // https://streams.spec.whatwg.org/#writable-stream-default-controller-process-close
  3406. void writable_stream_default_controller_process_close(WritableStreamDefaultController& controller)
  3407. {
  3408. // 1. Let stream be controller.[[stream]].
  3409. auto stream = controller.stream();
  3410. // 2. Perform ! WritableStreamMarkCloseRequestInFlight(stream).
  3411. writable_stream_mark_close_request_in_flight(*stream);
  3412. // 3. Perform ! DequeueValue(controller).
  3413. dequeue_value(controller);
  3414. // 4. Assert: controller.[[queue]] is empty.
  3415. VERIFY(controller.queue().is_empty());
  3416. // 5. Let sinkClosePromise be the result of performing controller.[[closeAlgorithm]].
  3417. auto sink_close_promise = controller.close_algorithm()->function()();
  3418. // 6. Perform ! WritableStreamDefaultControllerClearAlgorithms(controller).
  3419. writable_stream_default_controller_clear_algorithms(controller);
  3420. // 7. Upon fulfillment of sinkClosePromise,
  3421. WebIDL::upon_fulfillment(*sink_close_promise, JS::create_heap_function(controller.heap(), [stream](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {
  3422. // 1. Perform ! WritableStreamFinishInFlightClose(stream).
  3423. writable_stream_finish_in_flight_close(*stream);
  3424. return JS::js_undefined();
  3425. }));
  3426. // 8. Upon rejection of sinkClosePromise with reason reason,
  3427. WebIDL::upon_rejection(*sink_close_promise, JS::create_heap_function(controller.heap(), [stream = stream](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {
  3428. // 1. Perform ! WritableStreamFinishInFlightCloseWithError(stream, reason).
  3429. TRY(writable_stream_finish_in_flight_close_with_error(*stream, reason));
  3430. return JS::js_undefined();
  3431. }));
  3432. }
  3433. // https://streams.spec.whatwg.org/#writable-stream-default-controller-process-write
  3434. void writable_stream_default_controller_process_write(WritableStreamDefaultController& controller, JS::Value chunk)
  3435. {
  3436. // 1. Let stream be controller.[[stream]].
  3437. auto stream = controller.stream();
  3438. // 2. Perform ! WritableStreamMarkFirstWriteRequestInFlight(stream).
  3439. writable_stream_mark_first_write_request_in_flight(*stream);
  3440. // 3. Let sinkWritePromise be the result of performing controller.[[writeAlgorithm]], passing in chunk.
  3441. auto sink_write_promise = controller.write_algorithm()->function()(chunk);
  3442. // 4. Upon fulfillment of sinkWritePromise,
  3443. WebIDL::upon_fulfillment(*sink_write_promise, JS::create_heap_function(controller.heap(), [&controller, stream](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {
  3444. // 1. Perform ! WritableStreamFinishInFlightWrite(stream).
  3445. writable_stream_finish_in_flight_write(*stream);
  3446. // 2. Let state be stream.[[state]].
  3447. auto state = stream->state();
  3448. // 3. Assert: state is "writable" or "erroring".
  3449. VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);
  3450. // 4. Perform ! DequeueValue(controller).
  3451. dequeue_value(controller);
  3452. // 5. If ! WritableStreamCloseQueuedOrInFlight(stream) is false and state is "writable",
  3453. if (!writable_stream_close_queued_or_in_flight(*stream) && state == WritableStream::State::Writable) {
  3454. // 1. Let backpressure be ! WritableStreamDefaultControllerGetBackpressure(controller).
  3455. auto backpressure = writable_stream_default_controller_get_backpressure(controller);
  3456. // 2. Perform ! WritableStreamUpdateBackpressure(stream, backpressure).
  3457. writable_stream_update_backpressure(*stream, backpressure);
  3458. }
  3459. // 6 .Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).
  3460. TRY(writable_stream_default_controller_advance_queue_if_needed(controller));
  3461. return JS::js_undefined();
  3462. }));
  3463. // 5. Upon rejection of sinkWritePromise with reason,
  3464. WebIDL::upon_rejection(*sink_write_promise, JS::create_heap_function(controller.heap(), [&controller, stream](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {
  3465. // 1. If stream.[[state]] is "writable", perform ! WritableStreamDefaultControllerClearAlgorithms(controller).
  3466. if (stream->state() == WritableStream::State::Writable)
  3467. writable_stream_default_controller_clear_algorithms(controller);
  3468. // 2. Perform ! WritableStreamFinishInFlightWriteWithError(stream, reason).
  3469. TRY(writable_stream_finish_in_flight_write_with_error(*stream, reason));
  3470. return JS::js_undefined();
  3471. }));
  3472. }
  3473. // https://streams.spec.whatwg.org/#writable-stream-default-controller-write
  3474. WebIDL::ExceptionOr<void> writable_stream_default_controller_write(WritableStreamDefaultController& controller, JS::Value chunk, JS::Value chunk_size)
  3475. {
  3476. auto& vm = controller.vm();
  3477. // 1. Let enqueueResult be EnqueueValueWithSize(controller, chunk, chunkSize).
  3478. auto enqueue_result = enqueue_value_with_size(controller, chunk, chunk_size);
  3479. // 2. If enqueueResult is an abrupt completion,
  3480. if (enqueue_result.is_exception()) {
  3481. auto throw_completion = Bindings::throw_dom_exception_if_needed(vm, [&] { return enqueue_result; }).throw_completion();
  3482. // 1. Perform ! WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueResult.[[Value]]).
  3483. TRY(writable_stream_default_controller_error_if_needed(controller, *throw_completion.release_value()));
  3484. // 2. Return.
  3485. return {};
  3486. }
  3487. // 3. Let stream be controller.[[stream]].
  3488. auto stream = controller.stream();
  3489. // 4. If ! WritableStreamCloseQueuedOrInFlight(stream) is false and stream.[[state]] is "writable",
  3490. if (!writable_stream_close_queued_or_in_flight(*stream) && stream->state() == WritableStream::State::Writable) {
  3491. // 1. Let backpressure be ! WritableStreamDefaultControllerGetBackpressure(controller).
  3492. auto backpressure = writable_stream_default_controller_get_backpressure(controller);
  3493. // 2. Perform ! WritableStreamUpdateBackpressure(stream, backpressure).
  3494. writable_stream_update_backpressure(*stream, backpressure);
  3495. }
  3496. // 5. Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).
  3497. TRY(writable_stream_default_controller_advance_queue_if_needed(controller));
  3498. return {};
  3499. }
  3500. // https://streams.spec.whatwg.org/#initialize-transform-stream
  3501. 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)
  3502. {
  3503. auto& realm = stream.realm();
  3504. // 1. Let startAlgorithm be an algorithm that returns startPromise.
  3505. auto writable_start_algorithm = JS::create_heap_function(realm.heap(), [start_promise]() -> WebIDL::ExceptionOr<JS::Value> {
  3506. return start_promise->promise();
  3507. });
  3508. auto readable_start_algorithm = JS::create_heap_function(realm.heap(), [start_promise]() -> WebIDL::ExceptionOr<JS::Value> {
  3509. return start_promise->promise();
  3510. });
  3511. // 2. Let writeAlgorithm be the following steps, taking a chunk argument:
  3512. auto write_algorithm = JS::create_heap_function(realm.heap(), [&stream](JS::Value chunk) {
  3513. // 1. Return ! TransformStreamDefaultSinkWriteAlgorithm(stream, chunk).
  3514. return transform_stream_default_sink_write_algorithm(stream, chunk);
  3515. });
  3516. // 3. Let abortAlgorithm be the following steps, taking a reason argument:
  3517. auto abort_algorithm = JS::create_heap_function(realm.heap(), [&stream](JS::Value reason) {
  3518. // 1. Return ! TransformStreamDefaultSinkAbortAlgorithm(stream, reason).
  3519. return MUST(transform_stream_default_sink_abort_algorithm(stream, reason));
  3520. });
  3521. // 4. Let closeAlgorithm be the following steps:
  3522. auto close_algorithm = JS::create_heap_function(realm.heap(), [&stream]() {
  3523. // 1. Return ! TransformStreamDefaultSinkCloseAlgorithm(stream).
  3524. return transform_stream_default_sink_close_algorithm(stream);
  3525. });
  3526. // 5. Set stream.[[writable]] to ! CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm).
  3527. stream.set_writable(TRY(create_writable_stream(realm, writable_start_algorithm, write_algorithm, close_algorithm, abort_algorithm, writable_high_water_mark, writable_size_algorithm)));
  3528. // 6. Let pullAlgorithm be the following steps:
  3529. auto pull_algorithm = JS::create_heap_function(realm.heap(), [&stream]() {
  3530. // 1. Return ! TransformStreamDefaultSourcePullAlgorithm(stream).
  3531. return MUST(transform_stream_default_source_pull_algorithm(stream));
  3532. });
  3533. // 7. Let cancelAlgorithm be the following steps, taking a reason argument:
  3534. auto cancel_algorithm = JS::create_heap_function(realm.heap(), [&stream, &realm](JS::Value reason) {
  3535. // 1. Perform ! TransformStreamErrorWritableAndUnblockWrite(stream, reason).
  3536. MUST(transform_stream_error_writable_and_unblock_write(stream, reason));
  3537. // 2. Return a promise resolved with undefined.
  3538. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  3539. });
  3540. // 8. Set stream.[[readable]] to ! CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm).
  3541. stream.set_readable(TRY(create_readable_stream(realm, readable_start_algorithm, pull_algorithm, cancel_algorithm, readable_high_water_mark, readable_size_algorithm)));
  3542. // 9. Set stream.[[backpressure]] and stream.[[backpressureChangePromise]] to undefined.
  3543. stream.set_backpressure({});
  3544. stream.set_backpressure_change_promise({});
  3545. // 10. Perform ! TransformStreamSetBackpressure(stream, true).
  3546. TRY(transform_stream_set_backpressure(stream, true));
  3547. // 11. Set stream.[[controller]] to undefined.
  3548. stream.set_controller({});
  3549. return {};
  3550. }
  3551. // https://streams.spec.whatwg.org/#set-up-transform-stream-default-controller
  3552. void set_up_transform_stream_default_controller(TransformStream& stream, TransformStreamDefaultController& controller, JS::NonnullGCPtr<TransformAlgorithm> transform_algorithm, JS::NonnullGCPtr<FlushAlgorithm> flush_algorithm)
  3553. {
  3554. // 1. Assert: stream implements TransformStream.
  3555. // 2. Assert: stream.[[controller]] is undefined.
  3556. VERIFY(!stream.controller());
  3557. // 3. Set controller.[[stream]] to stream.
  3558. controller.set_stream(stream);
  3559. // 4. Set stream.[[controller]] to controller.
  3560. stream.set_controller(controller);
  3561. // 5. Set controller.[[transformAlgorithm]] to transformAlgorithm.
  3562. controller.set_transform_algorithm(transform_algorithm);
  3563. // 6. Set controller.[[flushAlgorithm]] to flushAlgorithm.
  3564. controller.set_flush_algorithm(flush_algorithm);
  3565. }
  3566. // https://streams.spec.whatwg.org/#set-up-transform-stream-default-controller-from-transformer
  3567. WebIDL::ExceptionOr<void> set_up_transform_stream_default_controller_from_transformer(TransformStream& stream, JS::Value transformer, Transformer& transformer_dict)
  3568. {
  3569. auto& realm = stream.realm();
  3570. auto& vm = realm.vm();
  3571. // 1. Let controller be a new TransformStreamDefaultController.
  3572. auto controller = realm.heap().allocate<TransformStreamDefaultController>(realm, realm);
  3573. // 2. Let transformAlgorithm be the following steps, taking a chunk argument:
  3574. auto transform_algorithm = JS::create_heap_function(realm.heap(), [controller, &realm, &vm](JS::Value chunk) {
  3575. // 1. Let result be TransformStreamDefaultControllerEnqueue(controller, chunk).
  3576. auto result = transform_stream_default_controller_enqueue(*controller, chunk);
  3577. // 2. If result is an abrupt completion, return a promise rejected with result.[[Value]].
  3578. if (result.is_error()) {
  3579. auto throw_completion = Bindings::dom_exception_to_throw_completion(vm, result.exception());
  3580. return WebIDL::create_rejected_promise(realm, *throw_completion.release_value());
  3581. }
  3582. // 3. Otherwise, return a promise resolved with undefined.
  3583. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  3584. });
  3585. // 3. Let flushAlgorithm be an algorithm which returns a promise resolved with undefined.
  3586. auto flush_algorithm = JS::create_heap_function(realm.heap(), [&realm]() {
  3587. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  3588. });
  3589. // 4. If transformerDict["transform"] exists, set transformAlgorithm to an algorithm which takes an argument chunk
  3590. // and returns the result of invoking transformerDict["transform"] with argument list « chunk, controller » and
  3591. // callback this value transformer.
  3592. if (transformer_dict.transform) {
  3593. transform_algorithm = JS::create_heap_function(realm.heap(), [controller, &realm, transformer, callback = transformer_dict.transform](JS::Value chunk) {
  3594. // Note: callback returns a promise, so invoke_callback will never return an abrupt completion
  3595. auto result = MUST(WebIDL::invoke_callback(*callback, transformer, chunk, controller)).release_value();
  3596. return WebIDL::create_resolved_promise(realm, result);
  3597. });
  3598. }
  3599. // 5. If transformerDict["flush"] exists, set flushAlgorithm to an algorithm which returns the result of invoking
  3600. // transformerDict["flush"] with argument list « controller » and callback this value transformer.
  3601. if (transformer_dict.flush) {
  3602. flush_algorithm = JS::create_heap_function(realm.heap(), [&realm, transformer, callback = transformer_dict.flush, controller]() {
  3603. // Note: callback returns a promise, so invoke_callback will never return an abrupt completion
  3604. auto result = MUST(WebIDL::invoke_callback(*callback, transformer, controller)).release_value();
  3605. return WebIDL::create_resolved_promise(realm, result);
  3606. });
  3607. }
  3608. // 6. Perform ! SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm).
  3609. set_up_transform_stream_default_controller(stream, *controller, transform_algorithm, flush_algorithm);
  3610. return {};
  3611. }
  3612. // https://streams.spec.whatwg.org/#transform-stream-default-controller-clear-algorithms
  3613. void transform_stream_default_controller_clear_algorithms(TransformStreamDefaultController& controller)
  3614. {
  3615. // NOTE: This is observable using weak references. See tc39/proposal-weakrefs#31 for more detail.
  3616. // 1. Set controller.[[transformAlgorithm]] to undefined.
  3617. controller.set_transform_algorithm({});
  3618. // 2. Set controller.[[flushAlgorithm]] to undefined.
  3619. controller.set_flush_algorithm({});
  3620. }
  3621. // https://streams.spec.whatwg.org/#transform-stream-default-controller-enqueue
  3622. WebIDL::ExceptionOr<void> transform_stream_default_controller_enqueue(TransformStreamDefaultController& controller, JS::Value chunk)
  3623. {
  3624. auto& vm = controller.vm();
  3625. // 1. Let stream be controller.[[stream]].
  3626. auto stream = controller.stream();
  3627. // 2. Let readableController be stream.[[readable]].[[controller]].
  3628. VERIFY(stream->readable()->controller().has_value() && stream->readable()->controller()->has<JS::NonnullGCPtr<ReadableStreamDefaultController>>());
  3629. auto& readable_controller = stream->readable()->controller()->get<JS::NonnullGCPtr<ReadableStreamDefaultController>>();
  3630. // 3. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController) is false, throw a TypeError exception.
  3631. if (!readable_stream_default_controller_can_close_or_enqueue(readable_controller))
  3632. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "ReadableController is either closed or not readable."sv };
  3633. // 4. Let enqueueResult be ReadableStreamDefaultControllerEnqueue(readableController, chunk).
  3634. auto enqueue_result = readable_stream_default_controller_enqueue(readable_controller, chunk);
  3635. // 5. If enqueueResult is an abrupt completion,
  3636. if (enqueue_result.is_error()) {
  3637. auto throw_completion = Bindings::dom_exception_to_throw_completion(vm, enqueue_result.exception());
  3638. // 1. Perform ! TransformStreamErrorWritableAndUnblockWrite(stream, enqueueResult.[[Value]]).
  3639. TRY(transform_stream_error_writable_and_unblock_write(*stream, throw_completion.value().value()));
  3640. // 2. Throw stream.[[readable]].[[storedError]].
  3641. return JS::throw_completion(stream->readable()->stored_error());
  3642. }
  3643. // 6. Let backpressure be ! ReadableStreamDefaultControllerHasBackpressure(readableController).
  3644. auto backpressure = readable_stream_default_controller_has_backpressure(readable_controller);
  3645. // 7. If backpressure is not stream.[[backpressure]],
  3646. if (backpressure != stream->backpressure()) {
  3647. // 1. Assert: backpressure is true.
  3648. VERIFY(backpressure);
  3649. // 2. Perform ! TransformStreamSetBackpressure(stream, true).
  3650. TRY(transform_stream_set_backpressure(*stream, true));
  3651. }
  3652. return {};
  3653. }
  3654. // https://streams.spec.whatwg.org/#transform-stream-default-controller-error
  3655. WebIDL::ExceptionOr<void> transform_stream_default_controller_error(TransformStreamDefaultController& controller, JS::Value error)
  3656. {
  3657. // 1. Perform ! TransformStreamError(controller.[[stream]], e).
  3658. TRY(transform_stream_error(*controller.stream(), error));
  3659. return {};
  3660. }
  3661. // https://streams.spec.whatwg.org/#transform-stream-default-controller-terminate
  3662. WebIDL::ExceptionOr<void> transform_stream_default_controller_terminate(TransformStreamDefaultController& controller)
  3663. {
  3664. auto& realm = controller.realm();
  3665. // 1. Let stream be controller.[[stream]].
  3666. auto stream = controller.stream();
  3667. // 2. Let readableController be stream.[[readable]].[[controller]].
  3668. VERIFY(stream->readable()->controller().has_value() && stream->readable()->controller()->has<JS::NonnullGCPtr<ReadableStreamDefaultController>>());
  3669. auto readable_controller = stream->readable()->controller()->get<JS::NonnullGCPtr<ReadableStreamDefaultController>>();
  3670. // 3. Perform ! ReadableStreamDefaultControllerClose(readableController).
  3671. readable_stream_default_controller_close(readable_controller);
  3672. // 4. Let error be a TypeError exception indicating that the stream has been terminated.
  3673. auto error = JS::TypeError::create(realm, "Stream has been terminated."sv);
  3674. // 5. Perform ! TransformStreamErrorWritableAndUnblockWrite(stream, error).
  3675. TRY(transform_stream_error_writable_and_unblock_write(*stream, error));
  3676. return {};
  3677. }
  3678. // https://streams.spec.whatwg.org/#transform-stream-default-controller-perform-transform
  3679. JS::NonnullGCPtr<WebIDL::Promise> transform_stream_default_controller_perform_transform(TransformStreamDefaultController& controller, JS::Value chunk)
  3680. {
  3681. auto& realm = controller.realm();
  3682. // 1. Let transformPromise be the result of performing controller.[[transformAlgorithm]], passing chunk.
  3683. auto transform_promise = controller.transform_algorithm()->function()(chunk);
  3684. // 2. Return the result of reacting to transformPromise with the following rejection steps given the argument r:
  3685. auto react_result = WebIDL::react_to_promise(*transform_promise,
  3686. {},
  3687. JS::create_heap_function(realm.heap(), [&controller](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {
  3688. // 1. Perform ! TransformStreamError(controller.[[stream]], r).
  3689. TRY(transform_stream_error(*controller.stream(), reason));
  3690. // 2. Throw r.
  3691. return JS::throw_completion(reason);
  3692. }));
  3693. return WebIDL::create_resolved_promise(realm, react_result);
  3694. }
  3695. // https://streams.spec.whatwg.org/#transform-stream-default-sink-abort-algorithm
  3696. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> transform_stream_default_sink_abort_algorithm(TransformStream& stream, JS::Value reason)
  3697. {
  3698. auto& realm = stream.realm();
  3699. // 1. Perform ! TransformStreamError(stream, reason).
  3700. TRY(transform_stream_error(stream, reason));
  3701. // 2. Return a promise resolved with undefined.
  3702. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  3703. }
  3704. // https://streams.spec.whatwg.org/#transform-stream-default-sink-close-algorithm
  3705. JS::NonnullGCPtr<WebIDL::Promise> transform_stream_default_sink_close_algorithm(TransformStream& stream)
  3706. {
  3707. auto& realm = stream.realm();
  3708. // 1. Let readable be stream.[[readable]].
  3709. auto readable = stream.readable();
  3710. // 2. Let controller be stream.[[controller]].
  3711. auto controller = stream.controller();
  3712. // 3. Let flushPromise be the result of performing controller.[[flushAlgorithm]].
  3713. auto flush_promise = controller->flush_algorithm()->function()();
  3714. // 4. Perform ! TransformStreamDefaultControllerClearAlgorithms(controller).
  3715. transform_stream_default_controller_clear_algorithms(*controller);
  3716. // 5. Return the result of reacting to flushPromise:
  3717. auto react_result = WebIDL::react_to_promise(
  3718. *flush_promise,
  3719. // 1. If flushPromise was fulfilled, then:
  3720. JS::create_heap_function(realm.heap(), [readable](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {
  3721. // 1. If readable.[[state]] is "errored", throw readable.[[storedError]].
  3722. if (readable->state() == ReadableStream::State::Errored)
  3723. return JS::throw_completion(readable->stored_error());
  3724. VERIFY(readable->controller().has_value() && readable->controller()->has<JS::NonnullGCPtr<ReadableStreamDefaultController>>());
  3725. // 2. Perform ! ReadableStreamDefaultControllerClose(readable.[[controller]]).
  3726. readable_stream_default_controller_close(readable->controller().value().get<JS::NonnullGCPtr<ReadableStreamDefaultController>>());
  3727. return JS::js_undefined();
  3728. }),
  3729. // 2. If flushPromise was rejected with reason r, then:
  3730. JS::create_heap_function(realm.heap(), [&stream, readable](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {
  3731. // 1. Perform ! TransformStreamError(stream, r).
  3732. TRY(transform_stream_error(stream, reason));
  3733. // 2. Throw readable.[[storedError]].
  3734. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, readable->stored_error().as_string().utf8_string() };
  3735. }));
  3736. return WebIDL::create_resolved_promise(realm, react_result);
  3737. }
  3738. // https://streams.spec.whatwg.org/#transform-stream-default-sink-write-algorithm
  3739. JS::NonnullGCPtr<WebIDL::Promise> transform_stream_default_sink_write_algorithm(TransformStream& stream, JS::Value chunk)
  3740. {
  3741. auto& realm = stream.realm();
  3742. // 1. Assert: stream.[[writable]].[[state]] is "writable".
  3743. VERIFY(stream.writable()->state() == WritableStream::State::Writable);
  3744. // 2. Let controller be stream.[[controller]].
  3745. auto controller = stream.controller();
  3746. // 3. If stream.[[backpressure]] is true,
  3747. if (stream.backpressure().has_value() && *stream.backpressure()) {
  3748. // 1. Let backpressureChangePromise be stream.[[backpressureChangePromise]].
  3749. auto backpressure_change_promise = stream.backpressure_change_promise();
  3750. // 2. Assert: backpressureChangePromise is not undefined.
  3751. VERIFY(backpressure_change_promise);
  3752. // 3. Return the result of reacting to backpressureChangePromise with the following fulfillment steps:
  3753. auto react_result = WebIDL::react_to_promise(*backpressure_change_promise,
  3754. JS::create_heap_function(realm.heap(), [&stream, controller, chunk](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {
  3755. // 1. Let writable be stream.[[writable]].
  3756. auto writable = stream.writable();
  3757. // 2. Let state be writable.[[state]].
  3758. auto state = writable->state();
  3759. // 3. If state is "erroring", throw writable.[[storedError]].
  3760. if (state == WritableStream::State::Erroring)
  3761. return JS::throw_completion(writable->stored_error());
  3762. // 4. Assert: state is "writable".
  3763. VERIFY(state == WritableStream::State::Writable);
  3764. // 5. Return ! TransformStreamDefaultControllerPerformTransform(controller, chunk).
  3765. return transform_stream_default_controller_perform_transform(*controller, chunk)->promise();
  3766. }),
  3767. {});
  3768. return WebIDL::create_resolved_promise(realm, react_result);
  3769. }
  3770. // 4. Return ! TransformStreamDefaultControllerPerformTransform(controller, chunk).
  3771. return transform_stream_default_controller_perform_transform(*controller, chunk);
  3772. }
  3773. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> transform_stream_default_source_pull_algorithm(TransformStream& stream)
  3774. {
  3775. // 1. Assert: stream.[[backpressure]] is true.
  3776. VERIFY(stream.backpressure().has_value() && *stream.backpressure());
  3777. // 2. Assert: stream.[[backpressureChangePromise]] is not undefined.
  3778. VERIFY(stream.backpressure_change_promise());
  3779. // 3. Perform ! TransformStreamSetBackpressure(stream, false).
  3780. TRY(transform_stream_set_backpressure(stream, false));
  3781. // 4. Return stream.[[backpressureChangePromise]].
  3782. return JS::NonnullGCPtr { *stream.backpressure_change_promise() };
  3783. }
  3784. // https://streams.spec.whatwg.org/#transform-stream-error
  3785. WebIDL::ExceptionOr<void> transform_stream_error(TransformStream& stream, JS::Value error)
  3786. {
  3787. VERIFY(stream.readable()->controller().has_value() && stream.readable()->controller()->has<JS::NonnullGCPtr<ReadableStreamDefaultController>>());
  3788. auto readable_controller = stream.readable()->controller()->get<JS::NonnullGCPtr<ReadableStreamDefaultController>>();
  3789. // 1. Perform ! ReadableStreamDefaultControllerError(stream.[[readable]].[[controller]], e).
  3790. readable_stream_default_controller_error(*readable_controller, error);
  3791. // 2. Perform ! TransformStreamErrorWritableAndUnblockWrite(stream, e).
  3792. TRY(transform_stream_error_writable_and_unblock_write(stream, error));
  3793. return {};
  3794. }
  3795. // https://streams.spec.whatwg.org/#transform-stream-error-writable-and-unblock-write
  3796. WebIDL::ExceptionOr<void> transform_stream_error_writable_and_unblock_write(TransformStream& stream, JS::Value error)
  3797. {
  3798. // 1. Perform ! TransformStreamDefaultControllerClearAlgorithms(stream.[[controller]]).
  3799. transform_stream_default_controller_clear_algorithms(*stream.controller());
  3800. // 2. Perform ! WritableStreamDefaultControllerErrorIfNeeded(stream.[[writable]].[[controller]], e).
  3801. TRY(writable_stream_default_controller_error_if_needed(*stream.writable()->controller(), error));
  3802. // 3. If stream.[[backpressure]] is true, perform ! TransformStreamSetBackpressure(stream, false).
  3803. if (stream.backpressure().has_value() && *stream.backpressure())
  3804. TRY(transform_stream_set_backpressure(stream, false));
  3805. return {};
  3806. }
  3807. // https://streams.spec.whatwg.org/#transform-stream-set-backpressure
  3808. WebIDL::ExceptionOr<void> transform_stream_set_backpressure(TransformStream& stream, bool backpressure)
  3809. {
  3810. auto& realm = stream.realm();
  3811. // 1. Assert: stream.[[backpressure]] is not backpressure.
  3812. VERIFY(stream.backpressure() != backpressure);
  3813. // 2. If stream.[[backpressureChangePromise]] is not undefined, resolve stream.[[backpressureChangePromise]] with undefined.
  3814. if (stream.backpressure_change_promise())
  3815. WebIDL::resolve_promise(realm, *stream.backpressure_change_promise(), JS::js_undefined());
  3816. // 3. Set stream.[[backpressureChangePromise]] to a new promise.
  3817. stream.set_backpressure_change_promise(WebIDL::create_promise(realm));
  3818. // 4. Set stream.[[backpressure]] to backpressure.
  3819. stream.set_backpressure(backpressure);
  3820. return {};
  3821. }
  3822. // https://streams.spec.whatwg.org/#is-non-negative-number
  3823. bool is_non_negative_number(JS::Value value)
  3824. {
  3825. // 1. If Type(v) is not Number, return false.
  3826. if (!value.is_number())
  3827. return false;
  3828. // 2. If v is NaN, return false.
  3829. if (value.is_nan())
  3830. return false;
  3831. // 3. If v < 0, return false.
  3832. if (value.as_double() < 0.0)
  3833. return false;
  3834. // 4. Return true.
  3835. return true;
  3836. }
  3837. // https://streams.spec.whatwg.org/#can-transfer-array-buffer
  3838. bool can_transfer_array_buffer(JS::ArrayBuffer const& array_buffer)
  3839. {
  3840. // 1. Assert: Type(O) is Object.
  3841. // 2. Assert: O has an [[ArrayBufferData]] internal slot.
  3842. // 3. If ! IsDetachedBuffer(O) is true, return false.
  3843. if (array_buffer.is_detached())
  3844. return false;
  3845. // 4. If SameValue(O.[[ArrayBufferDetachKey]], undefined) is false, return false.
  3846. if (!JS::same_value(array_buffer.detach_key(), JS::js_undefined()))
  3847. return false;
  3848. // 5. Return true.
  3849. return true;
  3850. }
  3851. // https://streams.spec.whatwg.org/#abstract-opdef-cloneasuint8array
  3852. WebIDL::ExceptionOr<JS::Value> clone_as_uint8_array(JS::Realm& realm, WebIDL::ArrayBufferView& view)
  3853. {
  3854. auto& vm = realm.vm();
  3855. // 1. Assert: Type(O) is Object.
  3856. // 2. Assert: O has an [[ViewedArrayBuffer]] internal slot.
  3857. // 3. Assert: ! IsDetachedBuffer(O.[[ViewedArrayBuffer]]) is false.
  3858. VERIFY(!view.viewed_array_buffer()->is_detached());
  3859. // 4. Let buffer be ? CloneArrayBuffer(O.[[ViewedArrayBuffer]], O.[[ByteOffset]], O.[[ByteLength]], %ArrayBuffer%).
  3860. auto* buffer = TRY(JS::clone_array_buffer(vm, *view.viewed_array_buffer(), view.byte_offset(), view.byte_length()));
  3861. // 5. Let array be ! Construct(%Uint8Array%, « buffer »).
  3862. auto array = MUST(JS::construct(vm, *realm.intrinsics().uint8_array_constructor(), buffer));
  3863. // 5. Return array.
  3864. return array;
  3865. }
  3866. // https://streams.spec.whatwg.org/#abstract-opdef-structuredclone
  3867. WebIDL::ExceptionOr<JS::Value> structured_clone(JS::Realm& realm, JS::Value value)
  3868. {
  3869. auto& vm = realm.vm();
  3870. // 1. Let serialized be ? StructuredSerialize(v).
  3871. auto serialized = TRY(HTML::structured_serialize(vm, value));
  3872. // 2. Return ? StructuredDeserialize(serialized, the current Realm).
  3873. return TRY(HTML::structured_deserialize(vm, serialized, realm, {}));
  3874. }
  3875. // https://streams.spec.whatwg.org/#close-sentinel
  3876. // Non-standard function that implements the "close sentinel" value.
  3877. JS::Value create_close_sentinel()
  3878. {
  3879. // 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.
  3880. // 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.
  3881. return {};
  3882. }
  3883. // https://streams.spec.whatwg.org/#close-sentinel
  3884. // Non-standard function that implements the "If value is a close sentinel" check.
  3885. bool is_close_sentinel(JS::Value value)
  3886. {
  3887. return value.is_empty();
  3888. }
  3889. // Non-standard function to aid in converting a user-provided function into a WebIDL::Callback. This is essentially
  3890. // what the Bindings generator would do at compile time, but at runtime instead.
  3891. 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)
  3892. {
  3893. auto property = TRY(value.get(vm, property_key));
  3894. if (property.is_undefined())
  3895. return JS::Handle<WebIDL::CallbackType> {};
  3896. if (!property.is_function())
  3897. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAFunction, property.to_string_without_side_effects());
  3898. return vm.heap().allocate_without_realm<WebIDL::CallbackType>(property.as_object(), HTML::incumbent_settings_object(), operation_returns_promise);
  3899. }
  3900. // https://streams.spec.whatwg.org/#set-up-readable-byte-stream-controller-from-underlying-source
  3901. 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)
  3902. {
  3903. auto& realm = stream.realm();
  3904. // 1. Let controller be a new ReadableByteStreamController.
  3905. auto controller = stream.heap().allocate<ReadableByteStreamController>(realm, realm);
  3906. // 2. Let startAlgorithm be an algorithm that returns undefined.
  3907. auto start_algorithm = JS::create_heap_function(realm.heap(), []() -> WebIDL::ExceptionOr<JS::Value> { return JS::js_undefined(); });
  3908. // 3. Let pullAlgorithm be an algorithm that returns a promise resolved with undefined.
  3909. auto pull_algorithm = JS::create_heap_function(realm.heap(), [&realm]() {
  3910. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  3911. });
  3912. // 4. Let cancelAlgorithm be an algorithm that returns a promise resolved with undefined.
  3913. auto cancel_algorithm = JS::create_heap_function(realm.heap(), [&realm](JS::Value) {
  3914. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  3915. });
  3916. // 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.
  3917. if (underlying_source_dict.start) {
  3918. start_algorithm = JS::create_heap_function(realm.heap(), [controller, underlying_source, callback = underlying_source_dict.start]() -> WebIDL::ExceptionOr<JS::Value> {
  3919. // Note: callback does not return a promise, so invoke_callback may return an abrupt completion
  3920. return TRY(WebIDL::invoke_callback(*callback, underlying_source, controller)).release_value();
  3921. });
  3922. }
  3923. // 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.
  3924. if (underlying_source_dict.pull) {
  3925. pull_algorithm = JS::create_heap_function(realm.heap(), [&realm, controller, underlying_source, callback = underlying_source_dict.pull]() {
  3926. // Note: callback returns a promise, so invoke_callback will never return an abrupt completion
  3927. auto result = MUST(WebIDL::invoke_callback(*callback, underlying_source, controller)).release_value();
  3928. return WebIDL::create_resolved_promise(realm, result);
  3929. });
  3930. }
  3931. // 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.
  3932. if (underlying_source_dict.cancel) {
  3933. cancel_algorithm = JS::create_heap_function(realm.heap(), [&realm, underlying_source, callback = underlying_source_dict.cancel](JS::Value reason) {
  3934. // Note: callback returns a promise, so invoke_callback will never return an abrupt completion
  3935. auto result = MUST(WebIDL::invoke_callback(*callback, underlying_source, reason)).release_value();
  3936. return WebIDL::create_resolved_promise(realm, result);
  3937. });
  3938. }
  3939. // 8. Let autoAllocateChunkSize be underlyingSourceDict["autoAllocateChunkSize"], if it exists, or undefined otherwise.
  3940. auto auto_allocate_chunk_size = underlying_source_dict.auto_allocate_chunk_size.has_value()
  3941. ? JS::Value(underlying_source_dict.auto_allocate_chunk_size.value())
  3942. : JS::js_undefined();
  3943. // 9. If autoAllocateChunkSize is 0, then throw a TypeError exception.
  3944. if (auto_allocate_chunk_size.is_integral_number() && auto_allocate_chunk_size.as_double() == 0)
  3945. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot use an auto allocate chunk size of 0"sv };
  3946. // 10. Perform ? SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize).
  3947. return set_up_readable_byte_stream_controller(stream, controller, start_algorithm, pull_algorithm, cancel_algorithm, high_water_mark, auto_allocate_chunk_size);
  3948. }
  3949. }