AbstractOperations.cpp 150 KB

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