AbstractOperations.cpp 126 KB

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