AbstractOperations.cpp 148 KB

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