AbstractOperations.cpp 123 KB

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