AbstractOperations.cpp 122 KB

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