Bodies.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. * Copyright (c) 2022-2023, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/PromiseCapability.h>
  7. #include <LibWeb/Bindings/MainThreadVM.h>
  8. #include <LibWeb/Fetch/BodyInit.h>
  9. #include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>
  10. #include <LibWeb/WebIDL/Promise.h>
  11. namespace Web::Fetch::Infrastructure {
  12. Body::Body(JS::Handle<Streams::ReadableStream> stream)
  13. : m_stream(move(stream))
  14. {
  15. }
  16. Body::Body(JS::Handle<Streams::ReadableStream> stream, SourceType source, Optional<u64> length)
  17. : m_stream(move(stream))
  18. , m_source(move(source))
  19. , m_length(move(length))
  20. {
  21. }
  22. // https://fetch.spec.whatwg.org/#concept-body-clone
  23. WebIDL::ExceptionOr<Body> Body::clone(JS::Realm& realm) const
  24. {
  25. // To clone a body body, run these steps:
  26. // FIXME: 1. Let « out1, out2 » be the result of teeing body’s stream.
  27. // FIXME: 2. Set body’s stream to out1.
  28. auto out2 = MUST_OR_THROW_OOM(realm.heap().allocate<Streams::ReadableStream>(realm, realm));
  29. // 3. Return a body whose stream is out2 and other members are copied from body.
  30. return Body { JS::make_handle(out2), m_source, m_length };
  31. }
  32. // https://fetch.spec.whatwg.org/#fully-reading-body-as-promise
  33. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> Body::fully_read_as_promise() const
  34. {
  35. auto& vm = Bindings::main_thread_vm();
  36. auto& realm = *vm.current_realm();
  37. // FIXME: Implement the streams spec - this is completely made up for now :^)
  38. if (auto const* byte_buffer = m_source.get_pointer<ByteBuffer>()) {
  39. // FIXME: The buffer may or may not be valid UTF-8.
  40. auto result = TRY_OR_THROW_OOM(vm, String::from_utf8(*byte_buffer));
  41. return WebIDL::create_resolved_promise(realm, JS::PrimitiveString::create(vm, move(result)));
  42. }
  43. // Empty, Blob, FormData
  44. return WebIDL::create_rejected_promise(realm, JS::InternalError::create(realm, "Reading body isn't fully implemented"sv).release_allocated_value_but_fixme_should_propagate_errors());
  45. }
  46. // https://fetch.spec.whatwg.org/#byte-sequence-as-a-body
  47. WebIDL::ExceptionOr<Body> byte_sequence_as_body(JS::Realm& realm, ReadonlyBytes bytes)
  48. {
  49. // To get a byte sequence bytes as a body, return the body of the result of safely extracting bytes.
  50. auto [body, _] = TRY(safely_extract_body(realm, bytes));
  51. return body;
  52. }
  53. }