Bodies.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. // processBody must be an algorithm accepting a byte sequence.
  24. using ProcessBodyCallback = JS::SafeFunction<void(ByteBuffer)>;
  25. // processBodyError must be an algorithm optionally accepting an exception.
  26. using ProcessBodyErrorCallback = JS::SafeFunction<void(JS::GCPtr<WebIDL::DOMException>)>;
  27. explicit Body(JS::Handle<Streams::ReadableStream>);
  28. Body(JS::Handle<Streams::ReadableStream>, SourceType, Optional<u64>);
  29. [[nodiscard]] JS::NonnullGCPtr<Streams::ReadableStream> stream() const { return *m_stream; }
  30. [[nodiscard]] SourceType const& source() const { return m_source; }
  31. [[nodiscard]] Optional<u64> const& length() const { return m_length; }
  32. WebIDL::ExceptionOr<Body> clone(JS::Realm&) const;
  33. WebIDL::ExceptionOr<void> fully_read(JS::Realm&, ProcessBodyCallback process_body, ProcessBodyErrorCallback process_body_error, TaskDestination task_destination) const;
  34. private:
  35. // https://fetch.spec.whatwg.org/#concept-body-stream
  36. // A stream (a ReadableStream object).
  37. JS::Handle<Streams::ReadableStream> m_stream;
  38. // https://fetch.spec.whatwg.org/#concept-body-source
  39. // A source (null, a byte sequence, a Blob object, or a FormData object), initially null.
  40. SourceType m_source;
  41. // https://fetch.spec.whatwg.org/#concept-body-total-bytes
  42. // A length (null or an integer), initially null.
  43. Optional<u64> m_length;
  44. };
  45. // https://fetch.spec.whatwg.org/#body-with-type
  46. // A body with type is a tuple that consists of a body (a body) and a type (a header value or null).
  47. struct BodyWithType {
  48. Body body;
  49. Optional<ByteBuffer> type;
  50. };
  51. WebIDL::ExceptionOr<Body> byte_sequence_as_body(JS::Realm&, ReadonlyBytes);
  52. }