/* THIS FILE IS AUTOGENERATED FROM ReadableStream.webidl BY Codegen.py - DO NOT EDIT */

#include <type_traits>
#include "AtomList.h"
#include "MainThreadUtils.h"
#include "QueuingStrategyBinding.h"
#include "ReadableStreamBinding.h"
#include "ReadableStreamDefaultReaderBinding.h"
#include "WrapperFactory.h"
#include "js/Array.h"
#include "js/CallAndConstruct.h"
#include "js/Exception.h"
#include "js/ForOfIterator.h"
#include "js/MapAndSet.h"
#include "js/Object.h"
#include "js/PropertyAndElement.h"
#include "js/PropertyDescriptor.h"
#include "js/Symbol.h"
#include "js/experimental/JitInfo.h"
#include "jsapi.h"
#include "mozilla/Atomics.h"
#include "mozilla/OwningNonNull.h"
#include "mozilla/ProfilerLabels.h"
#include "mozilla/dom/BindingCallContext.h"
#include "mozilla/dom/BindingUtils.h"
#include "mozilla/dom/DOMJSClass.h"
#include "mozilla/dom/IterableIterator.h"
#include "mozilla/dom/NonRefcountedDOMObject.h"
#include "mozilla/dom/PrimitiveConversions.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/dom/ReadableStream.h"
#include "mozilla/dom/ReadableStreamBYOBReader.h"
#include "mozilla/dom/ReadableStreamDefaultReader.h"
#include "mozilla/dom/ScriptSettings.h"
#include "mozilla/dom/SimpleGlobalObject.h"
#include "mozilla/dom/ToJSValue.h"
#include "mozilla/dom/WritableStream.h"
#include "mozilla/dom/XrayExpandoClass.h"

namespace mozilla {

namespace dom {

namespace binding_detail {}; // Just to make sure it's known as a namespace
using namespace mozilla::dom::binding_detail;


namespace binding_detail {
constexpr nsLiteralCString EnumStrings<ReadableStreamReaderMode>::Values[1];
} // namespace binding_detail

bool
ToJSValue(JSContext* aCx, ReadableStreamReaderMode aArgument, JS::MutableHandle<JS::Value> aValue)
{
  MOZ_ASSERT(uint32_t(aArgument) < std::size(binding_detail::EnumStrings<ReadableStreamReaderMode>::Values));
  JSString* resultStr =
    JS_NewStringCopyN(aCx, binding_detail::EnumStrings<ReadableStreamReaderMode>::Values[uint32_t(aArgument)].BeginReading(),
                      binding_detail::EnumStrings<ReadableStreamReaderMode>::Values[uint32_t(aArgument)].Length());
  if (!resultStr) {
    return false;
  }
  aValue.setString(resultStr);
  return true;
}



ReadableStreamGetReaderOptions::ReadableStreamGetReaderOptions()
{
  // Safe to pass a null context if we pass a null value
  Init(nullptr, JS::NullHandleValue);
}




bool
ReadableStreamGetReaderOptions::InitIds(JSContext* cx, ReadableStreamGetReaderOptionsAtoms* atomsCache)
{
  MOZ_ASSERT(reinterpret_cast<jsid*>(atomsCache)->isVoid());

  // Initialize these in reverse order so that any failure leaves the first one
  // uninitialized.
  if (!atomsCache->mode_id.init(cx, "mode")) {
    return false;
  }
  return true;
}

bool
ReadableStreamGetReaderOptions::Init(BindingCallContext& cx, JS::Handle<JS::Value> val, const char* sourceDescription, bool passedToJSImpl)
{
  // Passing a null JSContext is OK only if we're initing from null,
  // Since in that case we will not have to do any property gets
  // Also evaluate isNullOrUndefined in order to avoid false-positive
  // checkers by static analysis tools
  MOZ_ASSERT_IF(!cx, val.isNull() && val.isNullOrUndefined());
  ReadableStreamGetReaderOptionsAtoms* atomsCache = nullptr;
  if (cx) {
    atomsCache = GetAtomCache<ReadableStreamGetReaderOptionsAtoms>(cx);
    if (reinterpret_cast<jsid*>(atomsCache)->isVoid() &&
        !InitIds(cx, atomsCache)) {
      return false;
    }
  }

  if (!IsConvertibleToDictionary(val)) {
    return cx.ThrowErrorMessage<MSG_CONVERSION_ERROR>(sourceDescription, "dictionary");
  }

  bool isNull = val.isNullOrUndefined();
  // We only need these if !isNull, in which case we have |cx|.
  Maybe<JS::Rooted<JSObject *> > object;
  Maybe<JS::Rooted<JS::Value> > temp;
  if (!isNull) {
    MOZ_ASSERT(cx);
    object.emplace(cx, &val.toObject());
    temp.emplace(cx);
  }
  if (!isNull) {
    if (!JS_GetPropertyById(cx, *object, atomsCache->mode_id, temp.ptr())) {
      return false;
    }
  }
  if (!isNull && !temp->isUndefined()) {
    mMode.Construct();
    {
      int index;
      if (!binding_detail::FindEnumStringIndex<true>(cx, temp.ref(),
                                                                         binding_detail::EnumStrings<ReadableStreamReaderMode>::Values,
                                                                         "ReadableStreamReaderMode", "'mode' member of ReadableStreamGetReaderOptions",
                                                                         &index)) {
        return false;
      }
      MOZ_ASSERT(index >= 0);
      (mMode.Value()) = static_cast<ReadableStreamReaderMode>(index);
    }
    mIsAnyMemberPresent = true;
  }
  return true;
}

bool
ReadableStreamGetReaderOptions::Init(JSContext* cx_, JS::Handle<JS::Value> val, const char* sourceDescription, bool passedToJSImpl)
{
  // We don't want to use sourceDescription for our context here;
  // that's not really what it's formatted for.
  BindingCallContext cx(cx_, nullptr);
  return Init(cx, val, sourceDescription, passedToJSImpl);
}

void
ReadableStreamGetReaderOptions::TraceDictionary(JSTracer* trc)
{
}

ReadableStreamGetReaderOptions&
ReadableStreamGetReaderOptions::operator=(const ReadableStreamGetReaderOptions& aOther)
{
  DictionaryBase::operator=(aOther);
  mMode.Reset();
  if (aOther.mMode.WasPassed()) {
    mMode.Construct(aOther.mMode.Value());
  }
  return *this;
}



ReadableStreamIteratorOptions::ReadableStreamIteratorOptions()
{
  // Safe to pass a null context if we pass a null value
  Init(nullptr, JS::NullHandleValue);
}




bool
ReadableStreamIteratorOptions::InitIds(JSContext* cx, ReadableStreamIteratorOptionsAtoms* atomsCache)
{
  MOZ_ASSERT(reinterpret_cast<jsid*>(atomsCache)->isVoid());

  // Initialize these in reverse order so that any failure leaves the first one
  // uninitialized.
  if (!atomsCache->preventCancel_id.init(cx, "preventCancel")) {
    return false;
  }
  return true;
}

bool
ReadableStreamIteratorOptions::Init(BindingCallContext& cx, JS::Handle<JS::Value> val, const char* sourceDescription, bool passedToJSImpl)
{
  // Passing a null JSContext is OK only if we're initing from null,
  // Since in that case we will not have to do any property gets
  // Also evaluate isNullOrUndefined in order to avoid false-positive
  // checkers by static analysis tools
  MOZ_ASSERT_IF(!cx, val.isNull() && val.isNullOrUndefined());
  ReadableStreamIteratorOptionsAtoms* atomsCache = nullptr;
  if (cx) {
    atomsCache = GetAtomCache<ReadableStreamIteratorOptionsAtoms>(cx);
    if (reinterpret_cast<jsid*>(atomsCache)->isVoid() &&
        !InitIds(cx, atomsCache)) {
      return false;
    }
  }

  if (!IsConvertibleToDictionary(val)) {
    return cx.ThrowErrorMessage<MSG_CONVERSION_ERROR>(sourceDescription, "dictionary");
  }

  bool isNull = val.isNullOrUndefined();
  // We only need these if !isNull, in which case we have |cx|.
  Maybe<JS::Rooted<JSObject *> > object;
  Maybe<JS::Rooted<JS::Value> > temp;
  if (!isNull) {
    MOZ_ASSERT(cx);
    object.emplace(cx, &val.toObject());
    temp.emplace(cx);
  }
  if (!isNull) {
    if (!JS_GetPropertyById(cx, *object, atomsCache->preventCancel_id, temp.ptr())) {
      return false;
    }
  }
  if (!isNull && !temp->isUndefined()) {
    if (!ValueToPrimitive<bool, eDefault>(cx, temp.ref(), "'preventCancel' member of ReadableStreamIteratorOptions", &mPreventCancel)) {
      return false;
    }
  } else {
    mPreventCancel = false;
  }
  mIsAnyMemberPresent = true;
  return true;
}

bool
ReadableStreamIteratorOptions::Init(JSContext* cx_, JS::Handle<JS::Value> val, const char* sourceDescription, bool passedToJSImpl)
{
  // We don't want to use sourceDescription for our context here;
  // that's not really what it's formatted for.
  BindingCallContext cx(cx_, nullptr);
  return Init(cx, val, sourceDescription, passedToJSImpl);
}

void
ReadableStreamIteratorOptions::TraceDictionary(JSTracer* trc)
{
}

ReadableStreamIteratorOptions&
ReadableStreamIteratorOptions::operator=(const ReadableStreamIteratorOptions& aOther)
{
  DictionaryBase::operator=(aOther);
  mPreventCancel = aOther.mPreventCancel;
  return *this;
}



ReadableWritablePair::ReadableWritablePair()
{
  // Safe to pass a null context if we pass a null value
  Init(nullptr, JS::NullHandleValue);
}




bool
ReadableWritablePair::InitIds(JSContext* cx, ReadableWritablePairAtoms* atomsCache)
{
  MOZ_ASSERT(reinterpret_cast<jsid*>(atomsCache)->isVoid());

  // Initialize these in reverse order so that any failure leaves the first one
  // uninitialized.
  if (!atomsCache->writable_id.init(cx, "writable") ||
      !atomsCache->readable_id.init(cx, "readable")) {
    return false;
  }
  return true;
}

bool
ReadableWritablePair::Init(BindingCallContext& cx, JS::Handle<JS::Value> val, const char* sourceDescription, bool passedToJSImpl)
{
  // Passing a null JSContext is OK only if we're initing from null,
  // Since in that case we will not have to do any property gets
  // Also evaluate isNullOrUndefined in order to avoid false-positive
  // checkers by static analysis tools
  MOZ_ASSERT_IF(!cx, val.isNull() && val.isNullOrUndefined());
  ReadableWritablePairAtoms* atomsCache = nullptr;
  if (cx) {
    atomsCache = GetAtomCache<ReadableWritablePairAtoms>(cx);
    if (reinterpret_cast<jsid*>(atomsCache)->isVoid() &&
        !InitIds(cx, atomsCache)) {
      return false;
    }
  }

  if (!IsConvertibleToDictionary(val)) {
    return cx.ThrowErrorMessage<MSG_CONVERSION_ERROR>(sourceDescription, "dictionary");
  }

  bool isNull = val.isNullOrUndefined();
  // We only need these if !isNull, in which case we have |cx|.
  Maybe<JS::Rooted<JSObject *> > object;
  Maybe<JS::Rooted<JS::Value> > temp;
  if (!isNull) {
    MOZ_ASSERT(cx);
    object.emplace(cx, &val.toObject());
    temp.emplace(cx);
  }
  if (!isNull) {
    if (!JS_GetPropertyById(cx, *object, atomsCache->readable_id, temp.ptr())) {
      return false;
    }
  }
  if (!isNull && !temp->isUndefined()) {
    if (temp.ref().isObject()) {
      static_assert(IsRefcounted<mozilla::dom::ReadableStream>::value, "We can only store refcounted classes.");
      {
        // Our JSContext should be in the right global to do unwrapping in.
        nsresult rv = UnwrapObject<prototypes::id::ReadableStream, mozilla::dom::ReadableStream>(temp.ptr(), mReadable, cx);
        if (NS_FAILED(rv)) {
          cx.ThrowErrorMessage<MSG_DOES_NOT_IMPLEMENT_INTERFACE>("'readable' member of ReadableWritablePair", "ReadableStream");
          return false;
        }
      }
    } else {
      cx.ThrowErrorMessage<MSG_NOT_OBJECT>("'readable' member of ReadableWritablePair");
      return false;
    }
    mIsAnyMemberPresent = true;
  } else if (cx) {
    // Don't error out if we have no cx.  In that
    // situation the caller is default-constructing us and we'll
    // just assume they know what they're doing.
    return cx.ThrowErrorMessage<MSG_MISSING_REQUIRED_DICTIONARY_MEMBER>("'readable' member of ReadableWritablePair");
  }

  if (!isNull) {
    if (!JS_GetPropertyById(cx, *object, atomsCache->writable_id, temp.ptr())) {
      return false;
    }
  }
  if (!isNull && !temp->isUndefined()) {
    if (temp.ref().isObject()) {
      static_assert(IsRefcounted<mozilla::dom::WritableStream>::value, "We can only store refcounted classes.");
      {
        // Our JSContext should be in the right global to do unwrapping in.
        nsresult rv = UnwrapObject<prototypes::id::WritableStream, mozilla::dom::WritableStream>(temp.ptr(), mWritable, cx);
        if (NS_FAILED(rv)) {
          cx.ThrowErrorMessage<MSG_DOES_NOT_IMPLEMENT_INTERFACE>("'writable' member of ReadableWritablePair", "WritableStream");
          return false;
        }
      }
    } else {
      cx.ThrowErrorMessage<MSG_NOT_OBJECT>("'writable' member of ReadableWritablePair");
      return false;
    }
    mIsAnyMemberPresent = true;
  } else if (cx) {
    // Don't error out if we have no cx.  In that
    // situation the caller is default-constructing us and we'll
    // just assume they know what they're doing.
    return cx.ThrowErrorMessage<MSG_MISSING_REQUIRED_DICTIONARY_MEMBER>("'writable' member of ReadableWritablePair");
  }
  return true;
}

bool
ReadableWritablePair::Init(JSContext* cx_, JS::Handle<JS::Value> val, const char* sourceDescription, bool passedToJSImpl)
{
  // We don't want to use sourceDescription for our context here;
  // that's not really what it's formatted for.
  BindingCallContext cx(cx_, nullptr);
  return Init(cx, val, sourceDescription, passedToJSImpl);
}

void
ReadableWritablePair::TraceDictionary(JSTracer* trc)
{
}



ReadableWritablePair&
ReadableWritablePair::operator=(const ReadableWritablePair& aOther)
{
  DictionaryBase::operator=(aOther);
  mReadable = aOther.mReadable;
  mWritable = aOther.mWritable;
  return *this;
}



StreamPipeOptions::StreamPipeOptions()
{
  // Safe to pass a null context if we pass a null value
  Init(nullptr, JS::NullHandleValue);
}




bool
StreamPipeOptions::InitIds(JSContext* cx, StreamPipeOptionsAtoms* atomsCache)
{
  MOZ_ASSERT(reinterpret_cast<jsid*>(atomsCache)->isVoid());

  // Initialize these in reverse order so that any failure leaves the first one
  // uninitialized.
  if (!atomsCache->signal_id.init(cx, "signal") ||
      !atomsCache->preventClose_id.init(cx, "preventClose") ||
      !atomsCache->preventCancel_id.init(cx, "preventCancel") ||
      !atomsCache->preventAbort_id.init(cx, "preventAbort")) {
    return false;
  }
  return true;
}

bool
StreamPipeOptions::Init(BindingCallContext& cx, JS::Handle<JS::Value> val, const char* sourceDescription, bool passedToJSImpl)
{
  // Passing a null JSContext is OK only if we're initing from null,
  // Since in that case we will not have to do any property gets
  // Also evaluate isNullOrUndefined in order to avoid false-positive
  // checkers by static analysis tools
  MOZ_ASSERT_IF(!cx, val.isNull() && val.isNullOrUndefined());
  StreamPipeOptionsAtoms* atomsCache = nullptr;
  if (cx) {
    atomsCache = GetAtomCache<StreamPipeOptionsAtoms>(cx);
    if (reinterpret_cast<jsid*>(atomsCache)->isVoid() &&
        !InitIds(cx, atomsCache)) {
      return false;
    }
  }

  if (!IsConvertibleToDictionary(val)) {
    return cx.ThrowErrorMessage<MSG_CONVERSION_ERROR>(sourceDescription, "dictionary");
  }

  bool isNull = val.isNullOrUndefined();
  // We only need these if !isNull, in which case we have |cx|.
  Maybe<JS::Rooted<JSObject *> > object;
  Maybe<JS::Rooted<JS::Value> > temp;
  if (!isNull) {
    MOZ_ASSERT(cx);
    object.emplace(cx, &val.toObject());
    temp.emplace(cx);
  }
  if (!isNull) {
    if (!JS_GetPropertyById(cx, *object, atomsCache->preventAbort_id, temp.ptr())) {
      return false;
    }
  }
  if (!isNull && !temp->isUndefined()) {
    if (!ValueToPrimitive<bool, eDefault>(cx, temp.ref(), "'preventAbort' member of StreamPipeOptions", &mPreventAbort)) {
      return false;
    }
  } else {
    mPreventAbort = false;
  }
  mIsAnyMemberPresent = true;

  if (!isNull) {
    if (!JS_GetPropertyById(cx, *object, atomsCache->preventCancel_id, temp.ptr())) {
      return false;
    }
  }
  if (!isNull && !temp->isUndefined()) {
    if (!ValueToPrimitive<bool, eDefault>(cx, temp.ref(), "'preventCancel' member of StreamPipeOptions", &mPreventCancel)) {
      return false;
    }
  } else {
    mPreventCancel = false;
  }
  mIsAnyMemberPresent = true;

  if (!isNull) {
    if (!JS_GetPropertyById(cx, *object, atomsCache->preventClose_id, temp.ptr())) {
      return false;
    }
  }
  if (!isNull && !temp->isUndefined()) {
    if (!ValueToPrimitive<bool, eDefault>(cx, temp.ref(), "'preventClose' member of StreamPipeOptions", &mPreventClose)) {
      return false;
    }
  } else {
    mPreventClose = false;
  }
  mIsAnyMemberPresent = true;

  if (!isNull) {
    if (!JS_GetPropertyById(cx, *object, atomsCache->signal_id, temp.ptr())) {
      return false;
    }
  }
  if (!isNull && !temp->isUndefined()) {
    mSignal.Construct();
    if (temp.ref().isObject()) {
      static_assert(IsRefcounted<mozilla::dom::AbortSignal>::value, "We can only store refcounted classes.");
      {
        // Our JSContext should be in the right global to do unwrapping in.
        nsresult rv = UnwrapObject<prototypes::id::AbortSignal, mozilla::dom::AbortSignal>(temp.ptr(), (mSignal.Value()), cx);
        if (NS_FAILED(rv)) {
          cx.ThrowErrorMessage<MSG_DOES_NOT_IMPLEMENT_INTERFACE>("'signal' member of StreamPipeOptions", "AbortSignal");
          return false;
        }
      }
    } else {
      cx.ThrowErrorMessage<MSG_NOT_OBJECT>("'signal' member of StreamPipeOptions");
      return false;
    }
    mIsAnyMemberPresent = true;
  }
  return true;
}

bool
StreamPipeOptions::Init(JSContext* cx_, JS::Handle<JS::Value> val, const char* sourceDescription, bool passedToJSImpl)
{
  // We don't want to use sourceDescription for our context here;
  // that's not really what it's formatted for.
  BindingCallContext cx(cx_, nullptr);
  return Init(cx, val, sourceDescription, passedToJSImpl);
}

void
StreamPipeOptions::TraceDictionary(JSTracer* trc)
{
}



StreamPipeOptions&
StreamPipeOptions::operator=(const StreamPipeOptions& aOther)
{
  DictionaryBase::operator=(aOther);
  mPreventAbort = aOther.mPreventAbort;
  mPreventCancel = aOther.mPreventCancel;
  mPreventClose = aOther.mPreventClose;
  mSignal.Reset();
  if (aOther.mSignal.WasPassed()) {
    mSignal.Construct(aOther.mSignal.Value());
  }
  return *this;
}


namespace ReadableStreamAsyncIterator_Binding {

static bool
Wrap(JSContext* aCx, mozilla::dom::binding_detail::AsyncIterableIteratorNative<mozilla::dom::ReadableStream, true>* aObject, JS::MutableHandle<JSObject*> aReflector);

} // namespace ReadableStreamAsyncIterator_Binding


namespace ReadableStream_Binding {

MOZ_CAN_RUN_SCRIPT static bool
from(JSContext* cx, unsigned argc, JS::Value* vp)
{
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "ReadableStream", "from", DOM, cx,
    uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) |
    uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

  JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
  JS::Rooted<JSObject*> obj(cx, &args.callee());

  if (!args.requireAtLeast(cx, "ReadableStream.from", 1)) {
    return false;
  }
  GlobalObject global(cx, xpc::XrayAwareCalleeGlobal(obj));
  if (global.Failed()) {
    return false;
  }

  JS::Rooted<JS::Value> arg0(cx);
  arg0 = args[0];
  FastErrorResult rv;
  auto result(StrongOrRawPtr<mozilla::dom::ReadableStream>(mozilla::dom::ReadableStream::From(global, arg0, rv)));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "ReadableStream.from"))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  if (!GetOrCreateDOMReflector(cx, result, args.rval())) {
    MOZ_ASSERT(JS_IsExceptionPending(cx));
    return false;
  }
  return true;
}

MOZ_CAN_RUN_SCRIPT static bool
get_locked(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, JSJitGetterCallArgs args)
{
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "ReadableStream", "locked", DOM, cx,
    uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_GETTER) |
    uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

  auto* self = static_cast<mozilla::dom::ReadableStream*>(void_self);
  bool result(MOZ_KnownLive(self)->Locked());
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  args.rval().setBoolean(result);
  return true;
}

static const JSJitInfo locked_getterinfo = {
  { get_locked },
  { prototypes::id::ReadableStream },
  { PrototypeTraits<prototypes::id::ReadableStream>::Depth },
  JSJitInfo::Getter,
  JSJitInfo::AliasEverything, /* aliasSet.  Not relevant for setters. */
  JSVAL_TYPE_BOOLEAN,  /* returnType.  Not relevant for setters. */
  true,  /* isInfallible. False in setters. */
  false,  /* isMovable.  Not relevant for setters. */
  false, /* isEliminatable.  Not relevant for setters. */
  false, /* isAlwaysInSlot.  Only relevant for getters. */
  false, /* isLazilyCachedInSlot.  Only relevant for getters. */
  false,  /* isTypedMethod.  Only relevant for methods. */
  0   /* Reserved slot index, if we're stored in a slot, else 0. */
};

MOZ_CAN_RUN_SCRIPT static bool
cancel(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "ReadableStream", "cancel", DOM, cx,
    uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) |
    uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

  auto* self = static_cast<mozilla::dom::ReadableStream*>(void_self);
  JS::Rooted<JS::Value> arg0(cx);
  if (args.hasDefined(0)) {
    arg0 = args[0];
  } else {
    arg0 = JS::UndefinedValue();
  }
  FastErrorResult rv;
  auto result(StrongOrRawPtr<Promise>(MOZ_KnownLive(self)->Cancel(cx, arg0, rv)));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "ReadableStream.cancel"))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  static_assert(!std::is_pointer_v<decltype(result)>,
                "NewObject implies that we need to keep the object alive with a strong reference.");
  if (!ToJSValue(cx, result, args.rval())) {
    return false;
  }
  return true;
}

MOZ_CAN_RUN_SCRIPT static bool
cancel_promiseWrapper(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
  bool ok = cancel(cx, obj, void_self, args);
  if (ok) {
    return true;
  }
  return ConvertExceptionToPromise(cx, args.rval());
}

static const JSJitInfo cancel_methodinfo = {
  { (JSJitGetterOp)cancel_promiseWrapper },
  { prototypes::id::ReadableStream },
  { PrototypeTraits<prototypes::id::ReadableStream>::Depth },
  JSJitInfo::Method,
  JSJitInfo::AliasEverything, /* aliasSet.  Not relevant for setters. */
  JSVAL_TYPE_OBJECT,  /* returnType.  Not relevant for setters. */
  false,  /* isInfallible. False in setters. */
  false,  /* isMovable.  Not relevant for setters. */
  false, /* isEliminatable.  Not relevant for setters. */
  false, /* isAlwaysInSlot.  Only relevant for getters. */
  false, /* isLazilyCachedInSlot.  Only relevant for getters. */
  false,  /* isTypedMethod.  Only relevant for methods. */
  0   /* Reserved slot index, if we're stored in a slot, else 0. */
};

MOZ_CAN_RUN_SCRIPT static bool
getReader(JSContext* cx_, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
  BindingCallContext cx(cx_, "ReadableStream.getReader");
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "ReadableStream", "getReader", DOM, cx,
    uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) |
    uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

  auto* self = static_cast<mozilla::dom::ReadableStream*>(void_self);
  binding_detail::FastReadableStreamGetReaderOptions arg0;
  if (!arg0.Init(cx, (args.hasDefined(0)) ? args[0] : JS::NullHandleValue, "Argument 1", false)) {
    return false;
  }
  FastErrorResult rv;
  OwningReadableStreamDefaultReaderOrReadableStreamBYOBReader result;
  // NOTE: This assert does NOT call the function.
  static_assert(std::is_void_v<decltype(MOZ_KnownLive(self)->GetReader(Constify(arg0), result, rv))>, "Should be returning void here");
  MOZ_KnownLive(self)->GetReader(Constify(arg0), result, rv);
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "ReadableStream.getReader"))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  if (!result.ToJSVal(cx, obj, args.rval())) {
    return false;
  }
  return true;
}

static const JSJitInfo getReader_methodinfo = {
  { (JSJitGetterOp)getReader },
  { prototypes::id::ReadableStream },
  { PrototypeTraits<prototypes::id::ReadableStream>::Depth },
  JSJitInfo::Method,
  JSJitInfo::AliasEverything, /* aliasSet.  Not relevant for setters. */
  JSVAL_TYPE_OBJECT,  /* returnType.  Not relevant for setters. */
  false,  /* isInfallible. False in setters. */
  false,  /* isMovable.  Not relevant for setters. */
  false, /* isEliminatable.  Not relevant for setters. */
  false, /* isAlwaysInSlot.  Only relevant for getters. */
  false, /* isLazilyCachedInSlot.  Only relevant for getters. */
  false,  /* isTypedMethod.  Only relevant for methods. */
  0   /* Reserved slot index, if we're stored in a slot, else 0. */
};

MOZ_CAN_RUN_SCRIPT static bool
pipeThrough(JSContext* cx_, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
  BindingCallContext cx(cx_, "ReadableStream.pipeThrough");
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "ReadableStream", "pipeThrough", DOM, cx,
    uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) |
    uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

  auto* self = static_cast<mozilla::dom::ReadableStream*>(void_self);
  if (!args.requireAtLeast(cx, "ReadableStream.pipeThrough", 1)) {
    return false;
  }
  binding_detail::FastReadableWritablePair arg0;
  if (!arg0.Init(cx, args[0], "Argument 1", false)) {
    return false;
  }
  binding_detail::FastStreamPipeOptions arg1;
  if (!arg1.Init(cx, (args.hasDefined(1)) ? args[1] : JS::NullHandleValue, "Argument 2", false)) {
    return false;
  }
  FastErrorResult rv;
  auto result(StrongOrRawPtr<mozilla::dom::ReadableStream>(MOZ_KnownLive(self)->PipeThrough(Constify(arg0), Constify(arg1), rv)));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "ReadableStream.pipeThrough"))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  if (!GetOrCreateDOMReflector(cx, result, args.rval())) {
    MOZ_ASSERT(JS_IsExceptionPending(cx));
    return false;
  }
  return true;
}

static const JSJitInfo pipeThrough_methodinfo = {
  { (JSJitGetterOp)pipeThrough },
  { prototypes::id::ReadableStream },
  { PrototypeTraits<prototypes::id::ReadableStream>::Depth },
  JSJitInfo::Method,
  JSJitInfo::AliasEverything, /* aliasSet.  Not relevant for setters. */
  JSVAL_TYPE_OBJECT,  /* returnType.  Not relevant for setters. */
  false,  /* isInfallible. False in setters. */
  false,  /* isMovable.  Not relevant for setters. */
  false, /* isEliminatable.  Not relevant for setters. */
  false, /* isAlwaysInSlot.  Only relevant for getters. */
  false, /* isLazilyCachedInSlot.  Only relevant for getters. */
  false,  /* isTypedMethod.  Only relevant for methods. */
  0   /* Reserved slot index, if we're stored in a slot, else 0. */
};

MOZ_CAN_RUN_SCRIPT static bool
pipeTo(JSContext* cx_, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
  BindingCallContext cx(cx_, "ReadableStream.pipeTo");
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "ReadableStream", "pipeTo", DOM, cx,
    uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) |
    uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

  auto* self = static_cast<mozilla::dom::ReadableStream*>(void_self);
  if (!args.requireAtLeast(cx, "ReadableStream.pipeTo", 1)) {
    return false;
  }
  NonNull<mozilla::dom::WritableStream> arg0;
  if (args[0].isObject()) {
    {
      // Our JSContext should be in the right global to do unwrapping in.
      nsresult rv = UnwrapObject<prototypes::id::WritableStream, mozilla::dom::WritableStream>(args[0], arg0, cx);
      if (NS_FAILED(rv)) {
        cx.ThrowErrorMessage<MSG_DOES_NOT_IMPLEMENT_INTERFACE>("Argument 1", "WritableStream");
        return false;
      }
    }
  } else {
    cx.ThrowErrorMessage<MSG_NOT_OBJECT>("Argument 1");
    return false;
  }
  binding_detail::FastStreamPipeOptions arg1;
  if (!arg1.Init(cx, (args.hasDefined(1)) ? args[1] : JS::NullHandleValue, "Argument 2", false)) {
    return false;
  }
  FastErrorResult rv;
  auto result(StrongOrRawPtr<Promise>(MOZ_KnownLive(self)->PipeTo(MOZ_KnownLive(NonNullHelper(arg0)), Constify(arg1), rv)));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "ReadableStream.pipeTo"))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  static_assert(!std::is_pointer_v<decltype(result)>,
                "NewObject implies that we need to keep the object alive with a strong reference.");
  if (!ToJSValue(cx, result, args.rval())) {
    return false;
  }
  return true;
}

MOZ_CAN_RUN_SCRIPT static bool
pipeTo_promiseWrapper(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
  bool ok = pipeTo(cx, obj, void_self, args);
  if (ok) {
    return true;
  }
  return ConvertExceptionToPromise(cx, args.rval());
}

static const JSJitInfo pipeTo_methodinfo = {
  { (JSJitGetterOp)pipeTo_promiseWrapper },
  { prototypes::id::ReadableStream },
  { PrototypeTraits<prototypes::id::ReadableStream>::Depth },
  JSJitInfo::Method,
  JSJitInfo::AliasEverything, /* aliasSet.  Not relevant for setters. */
  JSVAL_TYPE_OBJECT,  /* returnType.  Not relevant for setters. */
  false,  /* isInfallible. False in setters. */
  false,  /* isMovable.  Not relevant for setters. */
  false, /* isEliminatable.  Not relevant for setters. */
  false, /* isAlwaysInSlot.  Only relevant for getters. */
  false, /* isLazilyCachedInSlot.  Only relevant for getters. */
  false,  /* isTypedMethod.  Only relevant for methods. */
  0   /* Reserved slot index, if we're stored in a slot, else 0. */
};

MOZ_CAN_RUN_SCRIPT static bool
tee(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "ReadableStream", "tee", DOM, cx,
    uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) |
    uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

  auto* self = static_cast<mozilla::dom::ReadableStream*>(void_self);
  FastErrorResult rv;
  nsTArray<StrongPtrForMember<mozilla::dom::ReadableStream>> result;
  // NOTE: This assert does NOT call the function.
  static_assert(std::is_void_v<decltype(MOZ_KnownLive(self)->Tee(cx, result, rv))>, "Should be returning void here");
  MOZ_KnownLive(self)->Tee(cx, result, rv);
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "ReadableStream.tee"))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));

  uint32_t length = result.Length();
  JS::Rooted<JSObject*> returnArray(cx, JS::NewArrayObject(cx, length));
  if (!returnArray) {
    return false;
  }
  // Scope for 'tmp'
  {
    JS::Rooted<JS::Value> tmp(cx);
    for (uint32_t sequenceIdx0 = 0; sequenceIdx0 < length; ++sequenceIdx0) {
      // Control block to let us common up the JS_DefineElement calls when there
      // are different ways to succeed at wrapping the object.
      do {
        if (!GetOrCreateDOMReflector(cx, result[sequenceIdx0], &tmp)) {
          MOZ_ASSERT(JS_IsExceptionPending(cx));
          return false;
        }
        break;
      } while (false);
      if (!JS_DefineElement(cx, returnArray, sequenceIdx0, tmp,
                            JSPROP_ENUMERATE)) {
        return false;
      }
    }
  }
  args.rval().setObject(*returnArray);
  return true;
}

static const JSJitInfo tee_methodinfo = {
  { (JSJitGetterOp)tee },
  { prototypes::id::ReadableStream },
  { PrototypeTraits<prototypes::id::ReadableStream>::Depth },
  JSJitInfo::Method,
  JSJitInfo::AliasEverything, /* aliasSet.  Not relevant for setters. */
  JSVAL_TYPE_OBJECT,  /* returnType.  Not relevant for setters. */
  false,  /* isInfallible. False in setters. */
  false,  /* isMovable.  Not relevant for setters. */
  false, /* isEliminatable.  Not relevant for setters. */
  false, /* isAlwaysInSlot.  Only relevant for getters. */
  false, /* isLazilyCachedInSlot.  Only relevant for getters. */
  false,  /* isTypedMethod.  Only relevant for methods. */
  0   /* Reserved slot index, if we're stored in a slot, else 0. */
};

MOZ_CAN_RUN_SCRIPT static bool
values(JSContext* cx_, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
  BindingCallContext cx(cx_, "ReadableStream.values");
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "ReadableStream", "values", DOM, cx,
    uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) |
    uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

  auto* self = static_cast<mozilla::dom::ReadableStream*>(void_self);
  binding_detail::FastReadableStreamIteratorOptions arg0;
  if (!arg0.Init(cx, (args.hasDefined(0)) ? args.get(0) : JS::NullHandleValue, "Argument 1", false)) {
    return false;
  }
  typedef mozilla::dom::binding_detail::WrappableAsyncIterableIterator<mozilla::dom::ReadableStream, true, &ReadableStreamAsyncIterator_Binding::Wrap> itrType;
  RefPtr<itrType> result(new itrType(self,
                                     itrType::IteratorType::Values));
  {
    ErrorResult initError;
    self->InitAsyncIteratorData(result->Data(), itrType::IteratorType::Values, arg0, initError);
    if (initError.MaybeSetPendingException(cx, "Asynchronous iterator initialization steps for ReadableStream failed")) {
      return false;
    }
  }
  static_assert(!std::is_pointer_v<decltype(result)>,
                "NewObject implies that we need to keep the object alive with a strong reference.");
  if (!WrapNewBindingNonWrapperCachedObject(cx, obj, result, args.rval())) {
    MOZ_ASSERT(JS_IsExceptionPending(cx));
    return false;
  }
  return true;
}

static const JSJitInfo::ArgType values_methodinfo_argTypes[] = { JSJitInfo::Object, JSJitInfo::ArgTypeListEnd };
static const JSTypedMethodJitInfo values_methodinfo = {
  {
    { (JSJitGetterOp)values },
    { prototypes::id::ReadableStream },
    { PrototypeTraits<prototypes::id::ReadableStream>::Depth },
    JSJitInfo::Method,
    JSJitInfo::AliasEverything, /* aliasSet.  Not relevant for setters. */
    JSVAL_TYPE_OBJECT,  /* returnType.  Not relevant for setters. */
    false,  /* isInfallible. False in setters. */
    false,  /* isMovable.  Not relevant for setters. */
    false, /* isEliminatable.  Not relevant for setters. */
    false, /* isAlwaysInSlot.  Only relevant for getters. */
    false, /* isLazilyCachedInSlot.  Only relevant for getters. */
    true,  /* isTypedMethod.  Only relevant for methods. */
    0   /* Reserved slot index, if we're stored in a slot, else 0. */
  },
  values_methodinfo_argTypes
};

static void
_finalize(JS::GCContext* gcx, JSObject* obj)
{
  mozilla::dom::ReadableStream* self = UnwrapPossiblyNotInitializedDOMObject<mozilla::dom::ReadableStream>(obj);
  if (self) {
    JS::SetReservedSlot(obj, DOM_OBJECT_SLOT, JS::UndefinedValue());
    ClearWrapper(self, self, obj);
    if (size_t mallocBytes = BindingJSObjectMallocBytes(self)) {
      JS::RemoveAssociatedMemory(obj, mallocBytes,
                                 JS::MemoryUse::DOMBinding);
    }
    AddForDeferredFinalization<mozilla::dom::ReadableStream>(self);
  }
}

MOZ_GLOBINIT static const JSFunctionSpec sStaticMethods_specs[] = {
  JS_FNSPEC("from", from, nullptr, 1, JSPROP_ENUMERATE, nullptr),
  JS_FS_END
};


static const Prefable<const JSFunctionSpec> sStaticMethods[] = {
  { nullptr, &sStaticMethods_specs[0] },
  { nullptr, nullptr }
};

static_assert(1 <= 1ull << NUM_BITS_PROPERTY_INFO_PREF_INDEX,
    "We have a prefable index that is >= (1 << NUM_BITS_PROPERTY_INFO_PREF_INDEX)");
static_assert(1 <= 1ull << NUM_BITS_PROPERTY_INFO_SPEC_INDEX,
    "We have a spec index that is >= (1 << NUM_BITS_PROPERTY_INFO_SPEC_INDEX)");

MOZ_GLOBINIT static const JSFunctionSpec sMethods_specs[] = {
  JS_FNSPEC("cancel", (GenericMethod<NormalThisPolicy, ConvertExceptionsToPromises>), reinterpret_cast<const JSJitInfo*>(&cancel_methodinfo), 0, JSPROP_ENUMERATE, nullptr),
  JS_FNSPEC("getReader", (GenericMethod<NormalThisPolicy, ThrowExceptions>), reinterpret_cast<const JSJitInfo*>(&getReader_methodinfo), 0, JSPROP_ENUMERATE, nullptr),
  JS_FNSPEC("pipeThrough", (GenericMethod<NormalThisPolicy, ThrowExceptions>), reinterpret_cast<const JSJitInfo*>(&pipeThrough_methodinfo), 1, JSPROP_ENUMERATE, nullptr),
  JS_FNSPEC("pipeTo", (GenericMethod<NormalThisPolicy, ConvertExceptionsToPromises>), reinterpret_cast<const JSJitInfo*>(&pipeTo_methodinfo), 1, JSPROP_ENUMERATE, nullptr),
  JS_FNSPEC("tee", (GenericMethod<NormalThisPolicy, ThrowExceptions>), reinterpret_cast<const JSJitInfo*>(&tee_methodinfo), 0, JSPROP_ENUMERATE, nullptr),
  JS_FNSPEC("values", (GenericMethod<NormalThisPolicy, ThrowExceptions>), reinterpret_cast<const JSJitInfo*>(&values_methodinfo), 0, JSPROP_ENUMERATE, nullptr),
  JS_FS_END
};


static const Prefable<const JSFunctionSpec> sMethods[] = {
  { nullptr, &sMethods_specs[0] },
  { nullptr, nullptr }
};

static_assert(1 <= 1ull << NUM_BITS_PROPERTY_INFO_PREF_INDEX,
    "We have a prefable index that is >= (1 << NUM_BITS_PROPERTY_INFO_PREF_INDEX)");
static_assert(6 <= 1ull << NUM_BITS_PROPERTY_INFO_SPEC_INDEX,
    "We have a spec index that is >= (1 << NUM_BITS_PROPERTY_INFO_SPEC_INDEX)");

MOZ_GLOBINIT static const JSPropertySpec sAttributes_specs[] = {
  JSPropertySpec::nativeAccessors("locked", JSPROP_ENUMERATE, GenericGetter<NormalThisPolicy, ThrowExceptions>, &locked_getterinfo, nullptr, nullptr),
  JS_PS_END
};


static const Prefable<const JSPropertySpec> sAttributes[] = {
  { nullptr, &sAttributes_specs[0] },
  { nullptr, nullptr }
};

static_assert(1 <= 1ull << NUM_BITS_PROPERTY_INFO_PREF_INDEX,
    "We have a prefable index that is >= (1 << NUM_BITS_PROPERTY_INFO_PREF_INDEX)");
static_assert(1 <= 1ull << NUM_BITS_PROPERTY_INFO_SPEC_INDEX,
    "We have a spec index that is >= (1 << NUM_BITS_PROPERTY_INFO_SPEC_INDEX)");


static uint16_t sNativeProperties_sortedPropertyIndices[8];
static PropertyInfo sNativeProperties_propertyInfos[8];

static const NativePropertiesN<3> sNativeProperties = {
  true,  0 /* sStaticMethods */,
  false, 0,
  true,  1 /* sMethods */,
  true,  2 /* sAttributes */,
  false, 0,
  false, 0,
  false, 0,
  -1,
  8,
  sNativeProperties_sortedPropertyIndices,
  {
    { sStaticMethods, &sNativeProperties_propertyInfos[0] },
    { sMethods, &sNativeProperties_propertyInfos[1] },
    { sAttributes, &sNativeProperties_propertyInfos[7] }
  }
};
static_assert(8 < 1ull << (CHAR_BIT * sizeof(sNativeProperties.propertyInfoCount)),
    "We have a property info count that is oversized");

bool sNativePropertiesInited = false;
const NativePropertyHooks sNativePropertyHooks = {
  nullptr,
  { sNativeProperties.Upcast(), nullptr, &sNativePropertiesInited },
  prototypes::id::ReadableStream,
  constructors::id::ReadableStream,
  &DefaultXrayExpandoObjectClass
};

static bool
_constructor(JSContext* cx_, unsigned argc, JS::Value* vp)
{
  BindingCallContext cx(cx_, "ReadableStream constructor");
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "ReadableStream", "constructor", DOM, cx,
    uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

  JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
  JS::Rooted<JSObject*> obj(cx, &args.callee());
  if (!args.isConstructing()) {
    return ThrowConstructorWithoutNew(cx, "ReadableStream");
  }

  JS::Rooted<JSObject*> desiredProto(cx);
  if (!GetDesiredProto(cx, args,
                       prototypes::id::ReadableStream,
                       CreateInterfaceObjects,
                       &desiredProto)) {
    return false;
  }

  GlobalObject global(cx, obj);
  if (global.Failed()) {
    return false;
  }

  bool objIsXray = xpc::WrapperFactory::IsXrayWrapper(obj);
  Optional<JS::Handle<JSObject*>> arg0;
  if (args.hasDefined(0)) {
    arg0.Construct(cx);
    if (args[0].isObject()) {
      arg0.Value() = &args[0].toObject();
    } else {
      cx.ThrowErrorMessage<MSG_NOT_OBJECT>("Argument 1");
      return false;
    }
  }
  binding_detail::FastQueuingStrategy arg1;
  if (!arg1.Init(cx, (args.hasDefined(1)) ? args[1] : JS::NullHandleValue, "Argument 2", false)) {
    return false;
  }
  Maybe<JSAutoRealm> ar;
  if (objIsXray) {
    // Since our object is an Xray, we can just CheckedUnwrapStatic:
    // we know Xrays have no dynamic unwrap behavior.
    obj = js::CheckedUnwrapStatic(obj);
    if (!obj) {
      return false;
    }
    ar.emplace(cx, obj);
    if (!JS_WrapObject(cx, &desiredProto)) {
      return false;
    }
    if (arg0.WasPassed()) {
      if (!JS_WrapObject(cx, &arg0.Value())) {
        return false;
      }
    }
  }
  FastErrorResult rv;
  auto result(StrongOrRawPtr<mozilla::dom::ReadableStream>(mozilla::dom::ReadableStream::Constructor(global, Constify(arg0), Constify(arg1), rv)));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "ReadableStream constructor"))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  static_assert(!std::is_pointer_v<decltype(result)>,
                "NewObject implies that we need to keep the object alive with a strong reference.");
  if (!GetOrCreateDOMReflector(cx, result, args.rval(), desiredProto)) {
    MOZ_ASSERT(JS_IsExceptionPending(cx));
    return false;
  }
  return true;
}

static const DOMInterfaceInfo sInterfaceObjectInfo = {
  { _constructor, &sNativePropertyHooks },
  JS::GetRealmFunctionPrototypeHandle,
  PrototypeTraits<prototypes::id::ReadableStream>::Depth,
  prototypes::id::ReadableStream,
  true,
  0,
  "ReadableStream",
};

static const DOMIfaceAndProtoJSClass sPrototypeClass = {
  {
    "ReadableStreamPrototype",
    JSCLASS_IS_DOMIFACEANDPROTOJSCLASS | JSCLASS_HAS_RESERVED_SLOTS(DOM_INTERFACE_PROTO_SLOTS_BASE),
    JS_NULL_CLASS_OPS,
    JS_NULL_CLASS_SPEC,
    JS_NULL_CLASS_EXT,
    JS_NULL_OBJECT_OPS
  },
  eInterfacePrototype,
  prototypes::id::ReadableStream,
  PrototypeTraits<prototypes::id::ReadableStream>::Depth,
  &sNativePropertyHooks,
  JS::GetRealmObjectPrototype
};

static const JSClassOps sClassOps = {
  nullptr,               /* addProperty */
  nullptr,               /* delProperty */
  nullptr,               /* enumerate */
  nullptr, /* newEnumerate */
  nullptr, /* resolve */
  nullptr, /* mayResolve */
  _finalize, /* finalize */
  nullptr, /* call */
  nullptr,               /* construct */
  nullptr, /* trace */
};

static const DOMJSClass sClass = {
  { "ReadableStream",
    JSCLASS_IS_DOMJSCLASS | JSCLASS_FOREGROUND_FINALIZE | JSCLASS_HAS_RESERVED_SLOTS(1) | JSCLASS_PRESERVES_WRAPPER,
    &sClassOps,
    JS_NULL_CLASS_SPEC,
    &NativeTypeHelpers<mozilla::dom::ReadableStream>::sClassExtension,
    JS_NULL_OBJECT_OPS
  },
  { prototypes::id::ReadableStream, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count },
  std::is_base_of_v<nsISupports, mozilla::dom::ReadableStream>,
  &sNativePropertyHooks,
  FindAssociatedGlobalForNative<mozilla::dom::ReadableStream>::Get,
  GetProtoObjectHandle,
  GetCCParticipant<mozilla::dom::ReadableStream>::Get(),
  nullptr,
  NativeTypeHelpers<mozilla::dom::ReadableStream>::GetWrapperCache
};
static_assert(1 == DOM_INSTANCE_RESERVED_SLOTS,
              "Must have the right minimal number of reserved slots.");
static_assert(1 >= 1,
              "Must have enough reserved slots.");

bool
Wrap(JSContext* aCx, mozilla::dom::ReadableStream* aObject, nsWrapperCache* aCache, JS::Handle<JSObject*> aGivenProto, JS::MutableHandle<JSObject*> aReflector)
{
  static_assert(!std::is_base_of_v<NonRefcountedDOMObject, mozilla::dom::ReadableStream>,
                "Shouldn't have wrappercached things that are not refcounted.");
  static_assert(std::is_same_v<decltype(aObject), mozilla::dom::ReadableStream*>);
  MOZ_ASSERT(ToSupportsIsCorrect(aObject));
  MOZ_ASSERT_IF(aGivenProto, js::IsObjectInContextCompartment(aGivenProto, aCx));
  MOZ_ASSERT(!aCache->GetWrapper(),
             "You should probably not be using Wrap() directly; use "
             "GetOrCreateDOMReflector instead");

  MOZ_ASSERT(ToSupportsIsOnPrimaryInheritanceChain(aObject, aCache),
             "nsISupports must be on our primary inheritance chain");

  // If the wrapper cache contains a dead reflector then finalize that
  // now, ensuring that the finalizer for the old reflector always
  // runs before the new reflector is created and attached. This
  // avoids the awkward situation where there are multiple reflector
  // objects that contain pointers to the same native.

  if (JSObject* oldReflector = aCache->GetWrapperMaybeDead()) {
    _finalize(nullptr /* unused */, oldReflector);
    MOZ_ASSERT(!aCache->GetWrapperMaybeDead());
  }

  JS::Rooted<JSObject*> global(aCx, FindAssociatedGlobal(aCx, aObject->GetParentObject()));
  if (!global) {
    return false;
  }
  MOZ_ASSERT(JS_IsGlobalObject(global));
  JS::AssertObjectIsNotGray(global);

  // That might have ended up wrapping us already, due to the wonders
  // of XBL.  Check for that, and bail out as needed.
  aReflector.set(aCache->GetWrapper());
  if (aReflector) {
#ifdef DEBUG
    AssertReflectorHasGivenProto(aCx, aReflector, aGivenProto);
#endif // DEBUG
    return true;
  }

  JSAutoRealm ar(aCx, global);
  JS::Handle<JSObject*> canonicalProto = GetProtoObjectHandle(aCx);
  if (!canonicalProto) {
    return false;
  }
  JS::Rooted<JSObject*> proto(aCx);
  if (aGivenProto) {
    proto = aGivenProto;
    // Unfortunately, while aGivenProto was in the compartment of aCx
    // coming in, we changed compartments to that of "parent" so may need
    // to wrap the proto here.
    if (js::GetContextCompartment(aCx) != JS::GetCompartment(proto)) {
      if (!JS_WrapObject(aCx, &proto)) {
        return false;
      }
    }
  } else {
    proto = canonicalProto;
  }

  BindingJSObjectCreator<mozilla::dom::ReadableStream> creator(aCx);
  creator.CreateObject(aCx, sClass.ToJSClass(), proto, aObject, aReflector);
  if (!aReflector) {
    return false;
  }

  aCache->SetWrapper(aReflector);
  creator.InitializationSucceeded();

  MOZ_ASSERT(aCache->GetWrapperPreserveColor() &&
             aCache->GetWrapperPreserveColor() == aReflector);
  // If proto != canonicalProto, we have to preserve our wrapper;
  // otherwise we won't be able to properly recreate it later, since
  // we won't know what proto to use.  Note that we don't check
  // aGivenProto here, since it's entirely possible (and even
  // somewhat common) to have a non-null aGivenProto which is the
  // same as canonicalProto.
  if (proto != canonicalProto) {
    PreserveWrapper(aObject);
  }

  return true;
}

void
CreateInterfaceObjects(JSContext* aCx, JS::Handle<JSObject*> aGlobal, ProtoAndIfaceCache& aProtoAndIfaceCache, DefineInterfaceProperty aDefineOnGlobal)
{
  JS::Heap<JSObject*>* protoCache = &aProtoAndIfaceCache.EntrySlotOrCreate(prototypes::id::ReadableStream);
  JS::Heap<JSObject*>* interfaceCache = &aProtoAndIfaceCache.EntrySlotOrCreate(constructors::id::ReadableStream);

  JS::Handle<JSObject*> parentProto(JS::GetRealmObjectPrototypeHandle(aCx));
  if (!parentProto) {
    return;
  }

  JS::Handle<JSObject*> constructorProto(JS::GetRealmFunctionPrototypeHandle(aCx));
  if (!constructorProto) {
    return;
  }

  dom::CreateInterfaceObjects(aCx, aGlobal, parentProto,
                              &sPrototypeClass, protoCache,
                              constructorProto, &sInterfaceObjectInfo, 0, false, Span<const LegacyFactoryFunction, 0>{},
                              interfaceCache,
                              sNativeProperties.Upcast(),
                              nullptr,
                              "ReadableStream",
                              aDefineOnGlobal != DefineInterfaceProperty::No,
                              nullptr,
                              false,
                              nullptr);

  JS::AssertObjectIsNotGray(*protoCache);
  JS::Handle<JSObject*> proto = JS::Handle<JSObject*>::fromMarkedLocation(protoCache->unsafeAddress());
  if (!proto) {
    *protoCache = nullptr;
    if (interfaceCache) {
      *interfaceCache = nullptr;
    }
    return;
  }

  // Set up aliases on the interface prototype object we just created.
  JS::Rooted<JS::Value> aliasedVal(aCx);

  if (!JS_GetProperty(aCx, proto, "values", &aliasedVal)) {
    *protoCache = nullptr;
    if (interfaceCache) {
      *interfaceCache = nullptr;
    }
    return;
  }
  JS::Rooted<jsid> asyncIteratorId(aCx, JS::GetWellKnownSymbolKey(aCx, JS::SymbolCode::asyncIterator));
  if (!JS_DefinePropertyById(aCx, proto, asyncIteratorId, aliasedVal, 0)) {
    *protoCache = nullptr;
    if (interfaceCache) {
      *interfaceCache = nullptr;
    }
    return;
  }
}

JS::Handle<JSObject*>
GetProtoObjectHandle(JSContext* aCx)
{
  /* Get the interface prototype object for this class.  This will create the
     object as needed. */
  return GetPerInterfaceObjectHandle(aCx, prototypes::id::ReadableStream,
                                     &CreateInterfaceObjects,
                                     DefineInterfaceProperty::CheckExposure);

}

JSObject*
GetProtoObject(JSContext* aCx)
{
  return GetProtoObjectHandle(aCx);
}

JS::Handle<JSObject*>
GetConstructorObjectHandle(JSContext* aCx)
{
  /* Get the interface object for this class.  This will create the object as
     needed. */

  return GetPerInterfaceObjectHandle(aCx, constructors::id::ReadableStream,
                                     &CreateInterfaceObjects,
                                     DefineInterfaceProperty::CheckExposure);
}

} // namespace ReadableStream_Binding



namespace ReadableStreamAsyncIterator_Binding {

MOZ_CAN_RUN_SCRIPT static bool
next(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "ReadableStreamAsyncIterator", "next", DOM, cx,
    uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) |
    uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

  auto* self = static_cast<mozilla::dom::binding_detail::AsyncIterableIteratorNative<mozilla::dom::ReadableStream, true>*>(void_self);
  FastErrorResult rv;
  auto result(StrongOrRawPtr<Promise>(MOZ_KnownLive(self)->Next(cx, rv)));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "ReadableStreamAsyncIterator.next"))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  if (!ToJSValue(cx, result, args.rval())) {
    return false;
  }
  return true;
}

MOZ_CAN_RUN_SCRIPT static bool
next_promiseWrapper(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
  bool ok = next(cx, obj, void_self, args);
  if (ok) {
    return true;
  }
  return ConvertExceptionToPromise(cx, args.rval());
}

static const JSJitInfo next_methodinfo = {
  { (JSJitGetterOp)next_promiseWrapper },
  { prototypes::id::ReadableStreamAsyncIterator },
  { PrototypeTraits<prototypes::id::ReadableStreamAsyncIterator>::Depth },
  JSJitInfo::Method,
  JSJitInfo::AliasEverything, /* aliasSet.  Not relevant for setters. */
  JSVAL_TYPE_OBJECT,  /* returnType.  Not relevant for setters. */
  false,  /* isInfallible. False in setters. */
  false,  /* isMovable.  Not relevant for setters. */
  false, /* isEliminatable.  Not relevant for setters. */
  false, /* isAlwaysInSlot.  Only relevant for getters. */
  false, /* isLazilyCachedInSlot.  Only relevant for getters. */
  false,  /* isTypedMethod.  Only relevant for methods. */
  0   /* Reserved slot index, if we're stored in a slot, else 0. */
};

MOZ_CAN_RUN_SCRIPT static bool
_return_(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "ReadableStreamAsyncIterator", "return", DOM, cx,
    uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) |
    uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

  auto* self = static_cast<mozilla::dom::binding_detail::AsyncIterableIteratorNative<mozilla::dom::ReadableStream, true>*>(void_self);
  JS::Rooted<JS::Value> arg0(cx);
  if (args.hasDefined(0)) {
    arg0 = args[0];
  } else {
    arg0 = JS::UndefinedValue();
  }
  FastErrorResult rv;
  auto result(StrongOrRawPtr<Promise>(MOZ_KnownLive(self)->Return(cx, arg0, rv)));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "ReadableStreamAsyncIterator.return"))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  if (!ToJSValue(cx, result, args.rval())) {
    return false;
  }
  return true;
}

MOZ_CAN_RUN_SCRIPT static bool
_return__promiseWrapper(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
  bool ok = _return_(cx, obj, void_self, args);
  if (ok) {
    return true;
  }
  return ConvertExceptionToPromise(cx, args.rval());
}

static const JSJitInfo return_methodinfo = {
  { (JSJitGetterOp)_return__promiseWrapper },
  { prototypes::id::ReadableStreamAsyncIterator },
  { PrototypeTraits<prototypes::id::ReadableStreamAsyncIterator>::Depth },
  JSJitInfo::Method,
  JSJitInfo::AliasEverything, /* aliasSet.  Not relevant for setters. */
  JSVAL_TYPE_OBJECT,  /* returnType.  Not relevant for setters. */
  false,  /* isInfallible. False in setters. */
  false,  /* isMovable.  Not relevant for setters. */
  false, /* isEliminatable.  Not relevant for setters. */
  false, /* isAlwaysInSlot.  Only relevant for getters. */
  false, /* isLazilyCachedInSlot.  Only relevant for getters. */
  false,  /* isTypedMethod.  Only relevant for methods. */
  0   /* Reserved slot index, if we're stored in a slot, else 0. */
};

static void
_finalize(JS::GCContext* gcx, JSObject* obj)
{
  mozilla::dom::binding_detail::AsyncIterableIteratorNative<mozilla::dom::ReadableStream, true>* self = UnwrapPossiblyNotInitializedDOMObject<mozilla::dom::binding_detail::AsyncIterableIteratorNative<mozilla::dom::ReadableStream, true>>(obj);
  if (self) {
    JS::SetReservedSlot(obj, DOM_OBJECT_SLOT, JS::UndefinedValue());
    if (size_t mallocBytes = BindingJSObjectMallocBytes(self)) {
      JS::RemoveAssociatedMemory(obj, mallocBytes,
                                 JS::MemoryUse::DOMBinding);
    }
    AddForDeferredFinalization<mozilla::dom::binding_detail::AsyncIterableIteratorNative<mozilla::dom::ReadableStream, true>>(self);
  }
}

MOZ_GLOBINIT static const JSFunctionSpec sMethods_specs[] = {
  JS_FNSPEC("next", (GenericMethod<NormalThisPolicy, ConvertExceptionsToPromises>), reinterpret_cast<const JSJitInfo*>(&next_methodinfo), 0, JSPROP_ENUMERATE, nullptr),
  JS_FNSPEC("return", (GenericMethod<NormalThisPolicy, ConvertExceptionsToPromises>), reinterpret_cast<const JSJitInfo*>(&return_methodinfo), 0, JSPROP_ENUMERATE, nullptr),
  JS_FS_END
};


static const Prefable<const JSFunctionSpec> sMethods[] = {
  { nullptr, &sMethods_specs[0] },
  { nullptr, nullptr }
};

static_assert(1 <= 1ull << NUM_BITS_PROPERTY_INFO_PREF_INDEX,
    "We have a prefable index that is >= (1 << NUM_BITS_PROPERTY_INFO_PREF_INDEX)");
static_assert(2 <= 1ull << NUM_BITS_PROPERTY_INFO_SPEC_INDEX,
    "We have a spec index that is >= (1 << NUM_BITS_PROPERTY_INFO_SPEC_INDEX)");


static uint16_t sNativeProperties_sortedPropertyIndices[2];
static PropertyInfo sNativeProperties_propertyInfos[2];

static const NativePropertiesN<1> sNativeProperties = {
  false, 0,
  false, 0,
  true,  0 /* sMethods */,
  false, 0,
  false, 0,
  false, 0,
  false, 0,
  -1,
  2,
  sNativeProperties_sortedPropertyIndices,
  {
    { sMethods, &sNativeProperties_propertyInfos[0] }
  }
};
static_assert(2 < 1ull << (CHAR_BIT * sizeof(sNativeProperties.propertyInfoCount)),
    "We have a property info count that is oversized");

bool sNativePropertiesInited = false;
const NativePropertyHooks sNativePropertyHooks = {
  nullptr,
  { sNativeProperties.Upcast(), nullptr, &sNativePropertiesInited },
  prototypes::id::ReadableStreamAsyncIterator,
  constructors::id::_ID_Count,
  &DefaultXrayExpandoObjectClass
};

static const DOMIfaceAndProtoJSClass sPrototypeClass = {
  {
    "ReadableStream AsyncIteratorPrototype",
    JSCLASS_IS_DOMIFACEANDPROTOJSCLASS | JSCLASS_HAS_RESERVED_SLOTS(DOM_INTERFACE_PROTO_SLOTS_BASE),
    JS_NULL_CLASS_OPS,
    JS_NULL_CLASS_SPEC,
    JS_NULL_CLASS_EXT,
    JS_NULL_OBJECT_OPS
  },
  eInterfacePrototype,
  prototypes::id::ReadableStreamAsyncIterator,
  PrototypeTraits<prototypes::id::ReadableStreamAsyncIterator>::Depth,
  &sNativePropertyHooks,
  JS::GetRealmAsyncIteratorPrototype
};

static JS::Handle<JSObject*>
GetProtoObjectHandle(JSContext* aCx);

static const JSClassOps sClassOps = {
  nullptr,               /* addProperty */
  nullptr,               /* delProperty */
  nullptr,               /* enumerate */
  nullptr, /* newEnumerate */
  nullptr, /* resolve */
  nullptr, /* mayResolve */
  _finalize, /* finalize */
  nullptr, /* call */
  nullptr,               /* construct */
  nullptr, /* trace */
};

static const DOMJSClass sClass = {
  { "ReadableStream AsyncIterator",
    JSCLASS_IS_DOMJSCLASS | JSCLASS_FOREGROUND_FINALIZE | JSCLASS_HAS_RESERVED_SLOTS(1),
    &sClassOps,
    JS_NULL_CLASS_SPEC,
    JS_NULL_CLASS_EXT,
    JS_NULL_OBJECT_OPS
  },
  { prototypes::id::ReadableStreamAsyncIterator, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count },
  std::is_base_of_v<nsISupports, mozilla::dom::binding_detail::AsyncIterableIteratorNative<mozilla::dom::ReadableStream, true>>,
  &sNativePropertyHooks,
  FindAssociatedGlobalForNative<mozilla::dom::binding_detail::AsyncIterableIteratorNative<mozilla::dom::ReadableStream, true>>::Get,
  GetProtoObjectHandle,
  GetCCParticipant<mozilla::dom::binding_detail::AsyncIterableIteratorNative<mozilla::dom::ReadableStream, true>>::Get(),
  nullptr,
  nullptr
};
static_assert(1 == DOM_INSTANCE_RESERVED_SLOTS,
              "Must have the right minimal number of reserved slots.");
static_assert(1 >= 1,
              "Must have enough reserved slots.");

static bool
Wrap(JSContext* aCx, mozilla::dom::binding_detail::AsyncIterableIteratorNative<mozilla::dom::ReadableStream, true>* aObject, JS::MutableHandle<JSObject*> aReflector)
{
  static_assert(std::is_same_v<decltype(aObject), mozilla::dom::binding_detail::AsyncIterableIteratorNative<mozilla::dom::ReadableStream, true>*>);
  MOZ_ASSERT(ToSupportsIsCorrect(aObject));

  JS::Rooted<JSObject*> global(aCx, JS::CurrentGlobalOrNull(aCx));
  JS::Handle<JSObject*> proto = GetProtoObjectHandle(aCx);
  if (!proto) {
    return false;
  }

  BindingJSObjectCreator<mozilla::dom::binding_detail::AsyncIterableIteratorNative<mozilla::dom::ReadableStream, true>> creator(aCx);
  creator.CreateObject(aCx, sClass.ToJSClass(), proto, aObject, aReflector);
  if (!aReflector) {
    return false;
  }



  creator.InitializationSucceeded();
  return true;
}

static void
CreateInterfaceObjects(JSContext* aCx, JS::Handle<JSObject*> aGlobal, ProtoAndIfaceCache& aProtoAndIfaceCache, DefineInterfaceProperty aDefineOnGlobal)
{
  JS::Heap<JSObject*>* protoCache = &aProtoAndIfaceCache.EntrySlotOrCreate(prototypes::id::ReadableStreamAsyncIterator);
  JS::Heap<JSObject*>* interfaceCache = nullptr;

  JS::Rooted<JSObject*> parentProto(aCx, JS::GetRealmAsyncIteratorPrototype(aCx));
  if (!parentProto) {
    return;
  }

  dom::CreateInterfaceObjects(aCx, aGlobal, parentProto,
                              &sPrototypeClass, protoCache,
                              nullptr, nullptr, 0, false, Span<const LegacyFactoryFunction, 0>{},
                              interfaceCache,
                              sNativeProperties.Upcast(),
                              nullptr,
                              "ReadableStream AsyncIterator",
                              aDefineOnGlobal != DefineInterfaceProperty::No,
                              nullptr,
                              false,
                              nullptr);
}

static JS::Handle<JSObject*>
GetProtoObjectHandle(JSContext* aCx)
{
  /* Get the interface prototype object for this class.  This will create the
     object as needed. */
  return GetPerInterfaceObjectHandle(aCx, prototypes::id::ReadableStreamAsyncIterator,
                                     &CreateInterfaceObjects,
                                     DefineInterfaceProperty::CheckExposure);

}

} // namespace ReadableStreamAsyncIterator_Binding



} // namespace dom


} // namespace mozilla
