Bodies.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * Copyright (c) 2022-2023, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/ByteBuffer.h>
  8. #include <AK/Forward.h>
  9. #include <AK/NonnullRefPtr.h>
  10. #include <AK/Optional.h>
  11. #include <AK/Variant.h>
  12. #include <LibJS/Heap/GCPtr.h>
  13. #include <LibJS/Heap/Handle.h>
  14. #include <LibWeb/Fetch/Infrastructure/Task.h>
  15. #include <LibWeb/FileAPI/Blob.h>
  16. #include <LibWeb/Streams/ReadableStream.h>
  17. #include <LibWeb/WebIDL/Promise.h>
  18. namespace Web::Fetch::Infrastructure {
  19. // https://fetch.spec.whatwg.org/#concept-body
  20. class Body final {
  21. public:
  22. using SourceType = Variant<Empty, ByteBuffer, JS::Handle<FileAPI::Blob>>;
  23. using ProcessBodyCallback = JS::SafeFunction<void(ByteBuffer)>;
  24. using ProcessBodyErrorCallback = JS::SafeFunction<void(JS::Object&)>;
  25. explicit Body(JS::Handle<Streams::ReadableStream>);
  26. Body(JS::Handle<Streams::ReadableStream>, SourceType, Optional<u64>);
  27. [[nodiscard]] JS::NonnullGCPtr<Streams::ReadableStream> stream() const { return *m_stream; }
  28. [[nodiscard]] SourceType const& source() const { return m_source; }
  29. [[nodiscard]] Optional<u64> const& length() const { return m_length; }
  30. WebIDL::ExceptionOr<Body> clone(JS::Realm&) const;
  31. WebIDL::ExceptionOr<void> fully_read(JS::Realm&, ProcessBodyCallback process_body, ProcessBodyErrorCallback process_body_error, TaskDestination task_destination) const;
  32. private:
  33. // https://fetch.spec.whatwg.org/#concept-body-stream
  34. // A stream (a ReadableStream object).
  35. JS::Handle<Streams::ReadableStream> m_stream;
  36. // https://fetch.spec.whatwg.org/#concept-body-source
  37. // A source (null, a byte sequence, a Blob object, or a FormData object), initially null.
  38. SourceType m_source;
  39. // https://fetch.spec.whatwg.org/#concept-body-total-bytes
  40. // A length (null or an integer), initially null.
  41. Optional<u64> m_length;
  42. };
  43. // https://fetch.spec.whatwg.org/#body-with-type
  44. // A body with type is a tuple that consists of a body (a body) and a type (a header value or null).
  45. struct BodyWithType {
  46. Body body;
  47. Optional<ByteBuffer> type;
  48. };
  49. WebIDL::ExceptionOr<Body> byte_sequence_as_body(JS::Realm&, ReadonlyBytes);
  50. }