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

#include <type_traits>
#include "AtomList.h"
#include "MainThreadUtils.h"
#include "PushManager.h"
#include "PushManagerBinding.h"
#include "WrapperFactory.h"
#include "js/CallAndConstruct.h"
#include "js/Exception.h"
#include "js/MapAndSet.h"
#include "js/Object.h"
#include "js/PropertyAndElement.h"
#include "js/PropertyDescriptor.h"
#include "js/experimental/JitInfo.h"
#include "jsfriendapi.h"
#include "mozilla/Atomics.h"
#include "mozilla/OwningNonNull.h"
#include "mozilla/ProfilerLabels.h"
#include "mozilla/UseCounter.h"
#include "mozilla/dom/BindingCallContext.h"
#include "mozilla/dom/BindingUtils.h"
#include "mozilla/dom/DOMJSClass.h"
#include "mozilla/dom/NonRefcountedDOMObject.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/dom/PushManager.h"
#include "mozilla/dom/RootedDictionary.h"
#include "mozilla/dom/ScriptSettings.h"
#include "mozilla/dom/ToJSValue.h"
#include "mozilla/dom/XrayExpandoClass.h"
#include "nsContentUtils.h"
#include "nsIGlobalObject.h"

namespace mozilla::dom {

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


bool
ArrayBufferViewOrArrayBufferOrString::TrySetToArrayBufferView(BindingCallContext& cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
  tryNext = false;
  { // scope for memberSlot
    RootedSpiderMonkeyInterface<ArrayBufferView>& memberSlot = RawSetAsArrayBufferView(cx);
    if (!memberSlot.Init(&value.toObject())) {
      DestroyArrayBufferView();
      tryNext = true;
      return true;
    }
    if (JS::IsArrayBufferViewShared(memberSlot.Obj())) {
      cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_SHARED>("ArrayBufferView branch of ((ArrayBufferView or ArrayBuffer) or DOMString)");
      return false;
    }
    if (JS::IsLargeArrayBufferView(memberSlot.Obj())) {
      cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_LARGE>("ArrayBufferView branch of ((ArrayBufferView or ArrayBuffer) or DOMString)");
      return false;
    }
    if (JS::IsResizableArrayBufferView(memberSlot.Obj())) {
      cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_RESIZABLE>("ArrayBufferView branch of ((ArrayBufferView or ArrayBuffer) or DOMString)");
      return false;
    }
    if (JS::IsImmutableArrayBufferView(memberSlot.Obj())) {
      cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_IMMUTABLE>("ArrayBufferView branch of ((ArrayBufferView or ArrayBuffer) or DOMString)");
      return false;
    }
  }
  return true;
}

bool
ArrayBufferViewOrArrayBufferOrString::TrySetToArrayBufferView(JSContext* cx_, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
  BindingCallContext cx(cx_, nullptr);
  return TrySetToArrayBufferView(cx, value, tryNext, passedToJSImpl);
}







bool
ArrayBufferViewOrArrayBufferOrString::TrySetToArrayBuffer(BindingCallContext& cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
  tryNext = false;
  { // scope for memberSlot
    RootedSpiderMonkeyInterface<ArrayBuffer>& memberSlot = RawSetAsArrayBuffer(cx);
    if (!memberSlot.Init(&value.toObject())) {
      DestroyArrayBuffer();
      tryNext = true;
      return true;
    }
    if (JS::IsSharedArrayBufferObject(memberSlot.Obj())) {
      cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_SHARED>("ArrayBuffer branch of ((ArrayBufferView or ArrayBuffer) or DOMString)");
      return false;
    }
    if (JS::IsLargeArrayBufferMaybeShared(memberSlot.Obj())) {
      cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_LARGE>("ArrayBuffer branch of ((ArrayBufferView or ArrayBuffer) or DOMString)");
      return false;
    }
    if (JS::IsResizableArrayBufferMaybeShared(memberSlot.Obj())) {
      cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_RESIZABLE>("ArrayBuffer branch of ((ArrayBufferView or ArrayBuffer) or DOMString)");
      return false;
    }
    if (JS::IsImmutableArrayBufferMaybeShared(memberSlot.Obj())) {
      cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_IMMUTABLE>("ArrayBuffer branch of ((ArrayBufferView or ArrayBuffer) or DOMString)");
      return false;
    }
  }
  return true;
}

bool
ArrayBufferViewOrArrayBufferOrString::TrySetToArrayBuffer(JSContext* cx_, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
  BindingCallContext cx(cx_, nullptr);
  return TrySetToArrayBuffer(cx, value, tryNext, passedToJSImpl);
}







bool
ArrayBufferViewOrArrayBufferOrString::TrySetToString(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
  tryNext = false;
  { // scope for memberSlot
    binding_detail::FakeString<char16_t>& memberSlot = RawSetAsString();
    if (!ConvertJSValueToString(cx, value, eStringify, eStringify, memberSlot)) {
      return false;
    }
  }
  return true;
}








bool
ArrayBufferViewOrArrayBufferOrString::Init(BindingCallContext& cx, JS::Handle<JS::Value> value, const char* sourceDescription, bool passedToJSImpl)
{
  MOZ_ASSERT(mType == eUninitialized);

  bool done = false, failed = false, tryNext;
  if (value.isObject()) {
    done = (failed = !TrySetToArrayBufferView(cx, value, tryNext, passedToJSImpl)) || !tryNext ||
           (failed = !TrySetToArrayBuffer(cx, value, tryNext, passedToJSImpl)) || !tryNext;
  }
  if (!done) {
    do {
      done = (failed = !TrySetToString(cx, value, tryNext)) || !tryNext;
      break;
    } while (false);
  }
  if (failed) {
    return false;
  }
  if (!done) {
    cx.ThrowErrorMessage<MSG_NOT_IN_UNION>(sourceDescription, "ArrayBufferView, ArrayBuffer");
    return false;
  }
  return true;
}

bool
ArrayBufferViewOrArrayBufferOrString::Init(JSContext* cx_, JS::Handle<JS::Value> value, const char* sourceDescription, bool passedToJSImpl)
{
  BindingCallContext cx(cx_, nullptr);
  return Init(cx, value, sourceDescription, passedToJSImpl);
}


bool
ArrayBufferViewOrArrayBufferOrString::ToJSVal(JSContext* cx, JS::Handle<JSObject*> scopeObj, JS::MutableHandle<JS::Value> rval) const
{
  switch (mType) {
    case eUninitialized: {
      return false;
    }
    case eArrayBufferView: {
      rval.setObject(*mValue.mArrayBufferView.Value().Obj());
      if (!MaybeWrapNonDOMObjectValue(cx, rval)) {
        return false;
      }
      return true;
    }
    case eArrayBuffer: {
      rval.setObject(*mValue.mArrayBuffer.Value().Obj());
      if (!MaybeWrapNonDOMObjectValue(cx, rval)) {
        return false;
      }
      return true;
    }
    case eString: {
      if (!xpc::NonVoidStringToJsval(cx, mValue.mString.Value(), rval)) {
        return false;
      }
      return true;
    }
    default: {
      return false;
    }
  }
}



OwningArrayBufferViewOrArrayBufferOrString::OwningArrayBufferViewOrArrayBufferOrString(OwningArrayBufferViewOrArrayBufferOrString&& aOther)
  : mType(eUninitialized)
{
  switch (aOther.mType) {
    case eUninitialized: {
      MOZ_ASSERT(mType == eUninitialized,
                 "We need to destroy ourselves?");
      break;
    }
    case eArrayBufferView: {
      mType = eArrayBufferView;
      mValue.mArrayBufferView.SetValue(std::move(aOther.mValue.mArrayBufferView.Value()));
      break;
    }
    case eArrayBuffer: {
      mType = eArrayBuffer;
      mValue.mArrayBuffer.SetValue(std::move(aOther.mValue.mArrayBuffer.Value()));
      break;
    }
    case eString: {
      mType = eString;
      mValue.mString.SetValue(std::move(aOther.mValue.mString.Value()));
      break;
    }
  }
}


bool
OwningArrayBufferViewOrArrayBufferOrString::TrySetToArrayBufferView(BindingCallContext& cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
  tryNext = false;
  { // scope for memberSlot
    ArrayBufferView& memberSlot = RawSetAsArrayBufferView();
    if (!memberSlot.Init(&value.toObject())) {
      DestroyArrayBufferView();
      tryNext = true;
      return true;
    }
    if (JS::IsArrayBufferViewShared(memberSlot.Obj())) {
      cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_SHARED>("ArrayBufferView branch of ((ArrayBufferView or ArrayBuffer) or DOMString)");
      return false;
    }
    if (JS::IsLargeArrayBufferView(memberSlot.Obj())) {
      cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_LARGE>("ArrayBufferView branch of ((ArrayBufferView or ArrayBuffer) or DOMString)");
      return false;
    }
    if (JS::IsResizableArrayBufferView(memberSlot.Obj())) {
      cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_RESIZABLE>("ArrayBufferView branch of ((ArrayBufferView or ArrayBuffer) or DOMString)");
      return false;
    }
    if (JS::IsImmutableArrayBufferView(memberSlot.Obj())) {
      cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_IMMUTABLE>("ArrayBufferView branch of ((ArrayBufferView or ArrayBuffer) or DOMString)");
      return false;
    }
  }
  return true;
}

bool
OwningArrayBufferViewOrArrayBufferOrString::TrySetToArrayBufferView(JSContext* cx_, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
  BindingCallContext cx(cx_, nullptr);
  return TrySetToArrayBufferView(cx, value, tryNext, passedToJSImpl);
}

[[nodiscard]] ArrayBufferView&
OwningArrayBufferViewOrArrayBufferOrString::RawSetAsArrayBufferView()
{
  if (mType == eArrayBufferView) {
    return mValue.mArrayBufferView.Value();
  }
  MOZ_ASSERT(mType == eUninitialized);
  mType = eArrayBufferView;
  return mValue.mArrayBufferView.SetValue();
}

[[nodiscard]] ArrayBufferView&
OwningArrayBufferViewOrArrayBufferOrString::SetAsArrayBufferView()
{
  if (mType == eArrayBufferView) {
    return mValue.mArrayBufferView.Value();
  }
  Uninit();
  mType = eArrayBufferView;
  return mValue.mArrayBufferView.SetValue();
}


void
OwningArrayBufferViewOrArrayBufferOrString::DestroyArrayBufferView()
{
  MOZ_RELEASE_ASSERT(IsArrayBufferView(), "Wrong type!");
  mValue.mArrayBufferView.Destroy();
  mType = eUninitialized;
}



bool
OwningArrayBufferViewOrArrayBufferOrString::TrySetToArrayBuffer(BindingCallContext& cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
  tryNext = false;
  { // scope for memberSlot
    ArrayBuffer& memberSlot = RawSetAsArrayBuffer();
    if (!memberSlot.Init(&value.toObject())) {
      DestroyArrayBuffer();
      tryNext = true;
      return true;
    }
    if (JS::IsSharedArrayBufferObject(memberSlot.Obj())) {
      cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_SHARED>("ArrayBuffer branch of ((ArrayBufferView or ArrayBuffer) or DOMString)");
      return false;
    }
    if (JS::IsLargeArrayBufferMaybeShared(memberSlot.Obj())) {
      cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_LARGE>("ArrayBuffer branch of ((ArrayBufferView or ArrayBuffer) or DOMString)");
      return false;
    }
    if (JS::IsResizableArrayBufferMaybeShared(memberSlot.Obj())) {
      cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_RESIZABLE>("ArrayBuffer branch of ((ArrayBufferView or ArrayBuffer) or DOMString)");
      return false;
    }
    if (JS::IsImmutableArrayBufferMaybeShared(memberSlot.Obj())) {
      cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_IMMUTABLE>("ArrayBuffer branch of ((ArrayBufferView or ArrayBuffer) or DOMString)");
      return false;
    }
  }
  return true;
}

bool
OwningArrayBufferViewOrArrayBufferOrString::TrySetToArrayBuffer(JSContext* cx_, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
  BindingCallContext cx(cx_, nullptr);
  return TrySetToArrayBuffer(cx, value, tryNext, passedToJSImpl);
}

[[nodiscard]] ArrayBuffer&
OwningArrayBufferViewOrArrayBufferOrString::RawSetAsArrayBuffer()
{
  if (mType == eArrayBuffer) {
    return mValue.mArrayBuffer.Value();
  }
  MOZ_ASSERT(mType == eUninitialized);
  mType = eArrayBuffer;
  return mValue.mArrayBuffer.SetValue();
}

[[nodiscard]] ArrayBuffer&
OwningArrayBufferViewOrArrayBufferOrString::SetAsArrayBuffer()
{
  if (mType == eArrayBuffer) {
    return mValue.mArrayBuffer.Value();
  }
  Uninit();
  mType = eArrayBuffer;
  return mValue.mArrayBuffer.SetValue();
}


void
OwningArrayBufferViewOrArrayBufferOrString::DestroyArrayBuffer()
{
  MOZ_RELEASE_ASSERT(IsArrayBuffer(), "Wrong type!");
  mValue.mArrayBuffer.Destroy();
  mType = eUninitialized;
}



bool
OwningArrayBufferViewOrArrayBufferOrString::TrySetToString(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
  tryNext = false;
  { // scope for memberSlot
    nsString& memberSlot = RawSetAsString();
    if (!ConvertJSValueToString(cx, value, eStringify, eStringify, memberSlot)) {
      return false;
    }
  }
  return true;
}

[[nodiscard]] nsString&
OwningArrayBufferViewOrArrayBufferOrString::RawSetAsString()
{
  if (mType == eString) {
    return mValue.mString.Value();
  }
  MOZ_ASSERT(mType == eUninitialized);
  mType = eString;
  return mValue.mString.SetValue();
}

[[nodiscard]] nsString&
OwningArrayBufferViewOrArrayBufferOrString::SetAsString()
{
  if (mType == eString) {
    return mValue.mString.Value();
  }
  Uninit();
  mType = eString;
  return mValue.mString.SetValue();
}



void
OwningArrayBufferViewOrArrayBufferOrString::DestroyString()
{
  MOZ_RELEASE_ASSERT(IsString(), "Wrong type!");
  mValue.mString.Destroy();
  mType = eUninitialized;
}



bool
OwningArrayBufferViewOrArrayBufferOrString::Init(BindingCallContext& cx, JS::Handle<JS::Value> value, const char* sourceDescription, bool passedToJSImpl)
{
  MOZ_ASSERT(mType == eUninitialized);

  bool done = false, failed = false, tryNext;
  if (value.isObject()) {
    done = (failed = !TrySetToArrayBufferView(cx, value, tryNext, passedToJSImpl)) || !tryNext ||
           (failed = !TrySetToArrayBuffer(cx, value, tryNext, passedToJSImpl)) || !tryNext;
  }
  if (!done) {
    do {
      done = (failed = !TrySetToString(cx, value, tryNext)) || !tryNext;
      break;
    } while (false);
  }
  if (failed) {
    return false;
  }
  if (!done) {
    cx.ThrowErrorMessage<MSG_NOT_IN_UNION>(sourceDescription, "ArrayBufferView, ArrayBuffer");
    return false;
  }
  return true;
}

bool
OwningArrayBufferViewOrArrayBufferOrString::Init(JSContext* cx_, JS::Handle<JS::Value> value, const char* sourceDescription, bool passedToJSImpl)
{
  BindingCallContext cx(cx_, nullptr);
  return Init(cx, value, sourceDescription, passedToJSImpl);
}

void
OwningArrayBufferViewOrArrayBufferOrString::Uninit()
{
  switch (mType) {
    case eUninitialized: {
      break;
    }
    case eArrayBufferView: {
      DestroyArrayBufferView();
      break;
    }
    case eArrayBuffer: {
      DestroyArrayBuffer();
      break;
    }
    case eString: {
      DestroyString();
      break;
    }
  }
}

bool
OwningArrayBufferViewOrArrayBufferOrString::ToJSVal(JSContext* cx, JS::Handle<JSObject*> scopeObj, JS::MutableHandle<JS::Value> rval) const
{
  switch (mType) {
    case eUninitialized: {
      return false;
    }
    case eArrayBufferView: {
      rval.setObject(*mValue.mArrayBufferView.Value().Obj());
      if (!MaybeWrapNonDOMObjectValue(cx, rval)) {
        return false;
      }
      return true;
    }
    case eArrayBuffer: {
      rval.setObject(*mValue.mArrayBuffer.Value().Obj());
      if (!MaybeWrapNonDOMObjectValue(cx, rval)) {
        return false;
      }
      return true;
    }
    case eString: {
      if (!xpc::NonVoidStringToJsval(cx, mValue.mString.Value(), rval)) {
        return false;
      }
      return true;
    }
    default: {
      return false;
    }
  }
}

void
OwningArrayBufferViewOrArrayBufferOrString::TraceUnion(JSTracer* trc)
{
  switch (mType) {
    case eArrayBufferView: {
      mValue.mArrayBufferView.Value().TraceSelf(trc);
      break;
    }
    case eArrayBuffer: {
      mValue.mArrayBuffer.Value().TraceSelf(trc);
      break;
    }
    default: {
    }
  }
}

OwningArrayBufferViewOrArrayBufferOrString&
OwningArrayBufferViewOrArrayBufferOrString::operator=(OwningArrayBufferViewOrArrayBufferOrString&& aOther)
{
  this->~OwningArrayBufferViewOrArrayBufferOrString();
  new (this) OwningArrayBufferViewOrArrayBufferOrString (std::move(aOther));
  return *this;
}




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



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

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

bool
PushSubscriptionOptionsInit::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());
  PushSubscriptionOptionsInitAtoms* atomsCache = nullptr;
  if (cx) {
    atomsCache = GetAtomCache<PushSubscriptionOptionsInitAtoms>(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->applicationServerKey_id, temp.ptr())) {
      return false;
    }
  }
  if (!(!isNull && !temp->isUndefined()) || temp.ref().isNullOrUndefined()) {
    mApplicationServerKey.SetNull();
  } else {
    if (!mApplicationServerKey.SetValue().Init(cx, temp.ref(), "'applicationServerKey' member of PushSubscriptionOptionsInit", passedToJSImpl)) {
      return false;
    }
  }
  mIsAnyMemberPresent = true;
  return true;
}

bool
PushSubscriptionOptionsInit::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);
}

bool
PushSubscriptionOptionsInit::ToObjectInternal(JSContext* cx, JS::MutableHandle<JS::Value> rval) const
{
  PushSubscriptionOptionsInitAtoms* atomsCache = GetAtomCache<PushSubscriptionOptionsInitAtoms>(cx);
  if (reinterpret_cast<jsid*>(atomsCache)->isVoid() &&
      !InitIds(cx, atomsCache)) {
    return false;
  }

  JS::Rooted<JSObject*> obj(cx, JS_NewPlainObject(cx));
  if (!obj) {
    return false;
  }
  rval.set(JS::ObjectValue(*obj));

  do {
    // block for our 'break' successCode and scope for 'temp' and 'currentValue'
    JS::Rooted<JS::Value> temp(cx);
    Nullable<OwningArrayBufferViewOrArrayBufferOrString > const & currentValue = mApplicationServerKey;
    if (currentValue.IsNull()) {
      temp.setNull();
      if (!JS_DefinePropertyById(cx, obj, atomsCache->applicationServerKey_id, temp, JSPROP_ENUMERATE)) {
        return false;
      }
      break;
    }
    if (!currentValue.Value().ToJSVal(cx, obj, &temp)) {
      return false;
    }
    if (!JS_DefinePropertyById(cx, obj, atomsCache->applicationServerKey_id, temp, JSPROP_ENUMERATE)) {
      return false;
    }
    break;
  } while(false);

  return true;
}

void
PushSubscriptionOptionsInit::TraceDictionary(JSTracer* trc)
{
  if (!mApplicationServerKey.IsNull()) {
    mApplicationServerKey.Value().TraceUnion(trc);
  }
}


namespace PushManager_Binding {

MOZ_CAN_RUN_SCRIPT static bool
get_supportedContentEncodings(JSContext* cx, unsigned argc, JS::Value* vp)
{
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "PushManager", "supportedContentEncodings", DOM, cx,
    uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_GETTER) |
    uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

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

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

  FastErrorResult rv;
  JS::Rooted<JSObject*> result(cx);
  // NOTE: This assert does NOT call the function.
  static_assert(std::is_void_v<decltype(mozilla::dom::PushManager::GetSupportedContentEncodings(global, &result, rv))>, "Should be returning void here");
  mozilla::dom::PushManager::GetSupportedContentEncodings(global, &result, rv);
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "PushManager.supportedContentEncodings getter"))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  JS::ExposeObjectToActiveJS(result);
  args.rval().setObject(*result);
  if (!MaybeWrapObjectValue(cx, args.rval())) {
    return false;
  }
  return true;
}

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

  auto* self = static_cast<mozilla::dom::PushManager*>(void_self);
  RootedDictionary<binding_detail::FastPushSubscriptionOptionsInit> arg0(cx);
  if (!arg0.Init(cx, (args.hasDefined(0)) ? args[0] : JS::NullHandleValue, "Argument 1", false)) {
    return false;
  }
  FastErrorResult rv;
  auto result(StrongOrRawPtr<Promise>(MOZ_KnownLive(self)->Subscribe(Constify(arg0), rv)));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "PushManager.subscribe"))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  if (NS_IsMainThread()) {
    SetUseCounter(obj, eUseCounter_PushManager_subscribe);

  } else {
    SetUseCounter(UseCounterWorker::PushManager_subscribe);

  }
  if (!ToJSValue(cx, result, args.rval())) {
    return false;
  }
  return true;
}

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

static const JSJitInfo subscribe_methodinfo = {
  { (JSJitGetterOp)subscribe_promiseWrapper },
  { prototypes::id::PushManager },
  { PrototypeTraits<prototypes::id::PushManager>::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
getSubscription(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "PushManager", "getSubscription", DOM, cx,
    uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) |
    uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

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

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

static const JSJitInfo getSubscription_methodinfo = {
  { (JSJitGetterOp)getSubscription_promiseWrapper },
  { prototypes::id::PushManager },
  { PrototypeTraits<prototypes::id::PushManager>::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
permissionState(JSContext* cx_, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
  BindingCallContext cx(cx_, "PushManager.permissionState");
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "PushManager", "permissionState", DOM, cx,
    uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) |
    uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

  auto* self = static_cast<mozilla::dom::PushManager*>(void_self);
  RootedDictionary<binding_detail::FastPushSubscriptionOptionsInit> arg0(cx);
  if (!arg0.Init(cx, (args.hasDefined(0)) ? args[0] : JS::NullHandleValue, "Argument 1", false)) {
    return false;
  }
  FastErrorResult rv;
  auto result(StrongOrRawPtr<Promise>(MOZ_KnownLive(self)->PermissionState(Constify(arg0), rv)));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "PushManager.permissionState"))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  if (!ToJSValue(cx, result, args.rval())) {
    return false;
  }
  return true;
}

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

static const JSJitInfo permissionState_methodinfo = {
  { (JSJitGetterOp)permissionState_promiseWrapper },
  { prototypes::id::PushManager },
  { PrototypeTraits<prototypes::id::PushManager>::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::PushManager* self = UnwrapPossiblyNotInitializedDOMObject<mozilla::dom::PushManager>(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::PushManager>(self);
  }
}

MOZ_GLOBINIT static const JSPropertySpec sStaticAttributes_specs[] = {
  JSPropertySpec::nativeAccessors("supportedContentEncodings", JSPROP_ENUMERATE, get_supportedContentEncodings, nullptr, nullptr, nullptr),
  JS_PS_END
};


static const Prefable<const JSPropertySpec> sStaticAttributes[] = {
  { nullptr, &sStaticAttributes_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("subscribe", (GenericMethod<NormalThisPolicy, ConvertExceptionsToPromises>), reinterpret_cast<const JSJitInfo*>(&subscribe_methodinfo), 0, JSPROP_ENUMERATE, nullptr),
  JS_FNSPEC("getSubscription", (GenericMethod<NormalThisPolicy, ConvertExceptionsToPromises>), reinterpret_cast<const JSJitInfo*>(&getSubscription_methodinfo), 0, JSPROP_ENUMERATE, nullptr),
  JS_FNSPEC("permissionState", (GenericMethod<NormalThisPolicy, ConvertExceptionsToPromises>), reinterpret_cast<const JSJitInfo*>(&permissionState_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(3 <= 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[4];
static PropertyInfo sNativeProperties_propertyInfos[4];

static const NativePropertiesN<2> sNativeProperties = {
  false, 0,
  true,  0 /* sStaticAttributes */,
  true,  1 /* sMethods */,
  false, 0,
  false, 0,
  false, 0,
  false, 0,
  -1,
  4,
  sNativeProperties_sortedPropertyIndices,
  {
    { sStaticAttributes, &sNativeProperties_propertyInfos[0] },
    { sMethods, &sNativeProperties_propertyInfos[1] }
  }
};
static_assert(4 < 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::PushManager,
  constructors::id::PushManager,
  &DefaultXrayExpandoObjectClass
};

static bool
_constructor(JSContext* cx, unsigned argc, JS::Value* vp)
{
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "PushManager", "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 (!nsContentUtils::ThreadsafeIsSystemCaller(cx)) {
    return ThrowingConstructor(cx, argc, vp);
  }

  if (!args.isConstructing()) {
    return ThrowConstructorWithoutNew(cx, "PushManager");
  }

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

  if (!args.requireAtLeast(cx, "PushManager constructor", 1)) {
    return false;
  }
  GlobalObject global(cx, obj);
  if (global.Failed()) {
    return false;
  }

  bool objIsXray = xpc::WrapperFactory::IsXrayWrapper(obj);
  binding_detail::FakeString<char16_t> arg0;
  if (!ConvertJSValueToString(cx, args[0], eStringify, eStringify, arg0)) {
    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;
    }
  }
  FastErrorResult rv;
  auto result(StrongOrRawPtr<mozilla::dom::PushManager>(mozilla::dom::PushManager::Constructor(global, NonNullHelper(Constify(arg0)), rv)));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "PushManager 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::PushManager>::Depth,
  prototypes::id::PushManager,
  true,
  1,
  "PushManager",
};

static const DOMIfaceAndProtoJSClass sPrototypeClass = {
  {
    "PushManagerPrototype",
    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::PushManager,
  PrototypeTraits<prototypes::id::PushManager>::Depth,
  &sNativePropertyHooks,
  JS::GetRealmObjectPrototype
};

bool
ConstructorEnabled(JSContext* aCx, JS::Handle<JSObject*> aObj)
{
  return PushManager::IsEnabled(aCx, aObj);
}

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 = {
  { "PushManager",
    JSCLASS_IS_DOMJSCLASS | JSCLASS_FOREGROUND_FINALIZE | JSCLASS_HAS_RESERVED_SLOTS(1) | JSCLASS_PRESERVES_WRAPPER,
    &sClassOps,
    JS_NULL_CLASS_SPEC,
    &NativeTypeHelpers<mozilla::dom::PushManager>::sClassExtension,
    JS_NULL_OBJECT_OPS
  },
  { prototypes::id::PushManager, 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::PushManager>,
  &sNativePropertyHooks,
  FindAssociatedGlobalForNative<mozilla::dom::PushManager>::Get,
  GetProtoObjectHandle,
  GetCCParticipant<mozilla::dom::PushManager>::Get(),
  nullptr,
  NativeTypeHelpers<mozilla::dom::PushManager>::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::PushManager* aObject, nsWrapperCache* aCache, JS::Handle<JSObject*> aGivenProto, JS::MutableHandle<JSObject*> aReflector)
{
  static_assert(!std::is_base_of_v<NonRefcountedDOMObject, mozilla::dom::PushManager>,
                "Shouldn't have wrappercached things that are not refcounted.");
  static_assert(std::is_same_v<decltype(aObject), mozilla::dom::PushManager*>);
  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::PushManager> 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::PushManager);
  JS::Heap<JSObject*>* interfaceCache = &aProtoAndIfaceCache.EntrySlotOrCreate(constructors::id::PushManager);

  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, 1, true, Span<const LegacyFactoryFunction, 0>{},
                              interfaceCache,
                              sNativeProperties.Upcast(),
                              nullptr,
                              "PushManager",
                              ShouldExpose<PushManager_Binding::ConstructorEnabled>(aCx, aGlobal, aDefineOnGlobal),
                              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::PushManager,
                                     &CreateInterfaceObjects,
                                     DefineInterfaceProperty::CheckExposure);

}

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::PushManager,
                                     &CreateInterfaceObjects,
                                     DefineInterfaceProperty::CheckExposure);
}

} // namespace PushManager_Binding



namespace PushManagerImpl_Binding {

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

  auto* self = static_cast<mozilla::dom::PushManagerImpl*>(void_self);
  Maybe<JS::Rooted<JSObject*> > unwrappedObj;
  bool objIsXray = xpc::WrapperFactory::IsXrayWrapper(obj);
  if (objIsXray) {
    unwrappedObj.emplace(cx, obj);
  }
  RootedDictionary<binding_detail::FastPushSubscriptionOptionsInit> arg0(cx);
  if (!arg0.Init(cx, (args.hasDefined(0)) ? args[0] : JS::NullHandleValue, "Argument 1", true)) {
    return false;
  }
  if (objIsXray) {
    // Since our object is an Xray, we can just CheckedUnwrapStatic:
    // we know Xrays have no dynamic unwrap behavior.
    unwrappedObj.ref() = js::CheckedUnwrapStatic(unwrappedObj.ref());
    if (!unwrappedObj.ref()) {
      return false;
    }
  }
  FastErrorResult rv;
  auto result(StrongOrRawPtr<Promise>(MOZ_KnownLive(self)->Subscribe(Constify(arg0), rv, (unwrappedObj ? js::GetNonCCWObjectRealm(*unwrappedObj) : js::GetContextRealm(cx)))));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "PushManagerImpl.subscribe"))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  if (!ToJSValue(cx, result, args.rval())) {
    return false;
  }
  return true;
}

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

static const JSJitInfo subscribe_methodinfo = {
  { (JSJitGetterOp)subscribe_promiseWrapper },
  { prototypes::id::PushManagerImpl },
  { PrototypeTraits<prototypes::id::PushManagerImpl>::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
getSubscription(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "PushManagerImpl", "getSubscription", DOM, cx,
    uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) |
    uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

  auto* self = static_cast<mozilla::dom::PushManagerImpl*>(void_self);
  Maybe<JS::Rooted<JSObject*> > unwrappedObj;
  bool objIsXray = xpc::WrapperFactory::IsXrayWrapper(obj);
  if (objIsXray) {
    unwrappedObj.emplace(cx, obj);
  }
  if (objIsXray) {
    // Since our object is an Xray, we can just CheckedUnwrapStatic:
    // we know Xrays have no dynamic unwrap behavior.
    unwrappedObj.ref() = js::CheckedUnwrapStatic(unwrappedObj.ref());
    if (!unwrappedObj.ref()) {
      return false;
    }
  }
  FastErrorResult rv;
  auto result(StrongOrRawPtr<Promise>(MOZ_KnownLive(self)->GetSubscription(rv, (unwrappedObj ? js::GetNonCCWObjectRealm(*unwrappedObj) : js::GetContextRealm(cx)))));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "PushManagerImpl.getSubscription"))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  if (!ToJSValue(cx, result, args.rval())) {
    return false;
  }
  return true;
}

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

static const JSJitInfo getSubscription_methodinfo = {
  { (JSJitGetterOp)getSubscription_promiseWrapper },
  { prototypes::id::PushManagerImpl },
  { PrototypeTraits<prototypes::id::PushManagerImpl>::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
permissionState(JSContext* cx_, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
  BindingCallContext cx(cx_, "PushManagerImpl.permissionState");
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "PushManagerImpl", "permissionState", DOM, cx,
    uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) |
    uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

  auto* self = static_cast<mozilla::dom::PushManagerImpl*>(void_self);
  Maybe<JS::Rooted<JSObject*> > unwrappedObj;
  bool objIsXray = xpc::WrapperFactory::IsXrayWrapper(obj);
  if (objIsXray) {
    unwrappedObj.emplace(cx, obj);
  }
  RootedDictionary<binding_detail::FastPushSubscriptionOptionsInit> arg0(cx);
  if (!arg0.Init(cx, (args.hasDefined(0)) ? args[0] : JS::NullHandleValue, "Argument 1", true)) {
    return false;
  }
  if (objIsXray) {
    // Since our object is an Xray, we can just CheckedUnwrapStatic:
    // we know Xrays have no dynamic unwrap behavior.
    unwrappedObj.ref() = js::CheckedUnwrapStatic(unwrappedObj.ref());
    if (!unwrappedObj.ref()) {
      return false;
    }
  }
  FastErrorResult rv;
  auto result(StrongOrRawPtr<Promise>(MOZ_KnownLive(self)->PermissionState(Constify(arg0), rv, (unwrappedObj ? js::GetNonCCWObjectRealm(*unwrappedObj) : js::GetContextRealm(cx)))));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "PushManagerImpl.permissionState"))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  if (!ToJSValue(cx, result, args.rval())) {
    return false;
  }
  return true;
}

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

static const JSJitInfo permissionState_methodinfo = {
  { (JSJitGetterOp)permissionState_promiseWrapper },
  { prototypes::id::PushManagerImpl },
  { PrototypeTraits<prototypes::id::PushManagerImpl>::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::PushManagerImpl* self = UnwrapPossiblyNotInitializedDOMObject<mozilla::dom::PushManagerImpl>(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::PushManagerImpl>(self);
  }
}

MOZ_GLOBINIT static const JSFunctionSpec sChromeStaticMethods_specs[] = {
  JS_FNSPEC("_create", PushManagerImpl::_Create, nullptr, 2, 0, nullptr),
  JS_FS_END
};


static const Prefable<const JSFunctionSpec> sChromeStaticMethods[] = {
  { nullptr, &sChromeStaticMethods_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("subscribe", (GenericMethod<NormalThisPolicy, ConvertExceptionsToPromises>), reinterpret_cast<const JSJitInfo*>(&subscribe_methodinfo), 0, JSPROP_ENUMERATE, nullptr),
  JS_FNSPEC("getSubscription", (GenericMethod<NormalThisPolicy, ConvertExceptionsToPromises>), reinterpret_cast<const JSJitInfo*>(&getSubscription_methodinfo), 0, JSPROP_ENUMERATE, nullptr),
  JS_FNSPEC("permissionState", (GenericMethod<NormalThisPolicy, ConvertExceptionsToPromises>), reinterpret_cast<const JSJitInfo*>(&permissionState_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(3 <= 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[3];
static PropertyInfo sNativeProperties_propertyInfos[3];

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

static uint16_t sChromeOnlyNativeProperties_sortedPropertyIndices[1];
static PropertyInfo sChromeOnlyNativeProperties_propertyInfos[1];

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

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

static bool
_constructor(JSContext* cx, unsigned argc, JS::Value* vp)
{
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "PushManagerImpl", "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, "PushManagerImpl");
  }

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

  if (!args.requireAtLeast(cx, "PushManagerImpl constructor", 1)) {
    return false;
  }
  GlobalObject global(cx, obj);
  if (global.Failed()) {
    return false;
  }

  bool objIsXray = xpc::WrapperFactory::IsXrayWrapper(obj);
  binding_detail::FakeString<char16_t> arg0;
  if (!ConvertJSValueToString(cx, args[0], eStringify, eStringify, arg0)) {
    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;
    }
  }
  FastErrorResult rv;
  auto result(StrongOrRawPtr<mozilla::dom::PushManagerImpl>(mozilla::dom::PushManagerImpl::Constructor(global, cx, NonNullHelper(Constify(arg0)), rv, desiredProto)));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "PushManagerImpl 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::PushManagerImpl>::Depth,
  prototypes::id::PushManagerImpl,
  true,
  1,
  "PushManagerImpl",
};

static const DOMIfaceAndProtoJSClass sPrototypeClass = {
  {
    "PushManagerImplPrototype",
    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::PushManagerImpl,
  PrototypeTraits<prototypes::id::PushManagerImpl>::Depth,
  &sNativePropertyHooks,
  JS::GetRealmObjectPrototype
};

bool
ConstructorEnabled(JSContext* aCx, JS::Handle<JSObject*> aObj)
{
  return nsContentUtils::ThreadsafeIsSystemCaller(aCx);
}

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 = {
  { "PushManagerImpl",
    JSCLASS_IS_DOMJSCLASS | JSCLASS_FOREGROUND_FINALIZE | JSCLASS_HAS_RESERVED_SLOTS(1) | JSCLASS_PRESERVES_WRAPPER,
    &sClassOps,
    JS_NULL_CLASS_SPEC,
    &NativeTypeHelpers<mozilla::dom::PushManagerImpl>::sClassExtension,
    JS_NULL_OBJECT_OPS
  },
  { prototypes::id::PushManagerImpl, 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::PushManagerImpl>,
  &sNativePropertyHooks,
  FindAssociatedGlobalForNative<mozilla::dom::PushManagerImpl>::Get,
  GetProtoObjectHandle,
  GetCCParticipant<mozilla::dom::PushManagerImpl>::Get(),
  nullptr,
  NativeTypeHelpers<mozilla::dom::PushManagerImpl>::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::PushManagerImpl* aObject, nsWrapperCache* aCache, JS::Handle<JSObject*> aGivenProto, JS::MutableHandle<JSObject*> aReflector)
{
  static_assert(!std::is_base_of_v<NonRefcountedDOMObject, mozilla::dom::PushManagerImpl>,
                "Shouldn't have wrappercached things that are not refcounted.");
  static_assert(std::is_same_v<decltype(aObject), mozilla::dom::PushManagerImpl*>);
  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::PushManagerImpl> 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::PushManagerImpl);
  JS::Heap<JSObject*>* interfaceCache = &aProtoAndIfaceCache.EntrySlotOrCreate(constructors::id::PushManagerImpl);

  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, 1, false, Span<const LegacyFactoryFunction, 0>{},
                              interfaceCache,
                              sNativeProperties.Upcast(),
                              sChromeOnlyNativeProperties.Upcast(),
                              "PushManagerImpl",
                              ShouldExpose<PushManagerImpl_Binding::ConstructorEnabled>(aCx, aGlobal, aDefineOnGlobal),
                              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::PushManagerImpl,
                                     &CreateInterfaceObjects,
                                     DefineInterfaceProperty::CheckExposure);

}

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::PushManagerImpl,
                                     &CreateInterfaceObjects,
                                     DefineInterfaceProperty::CheckExposure);
}

} // namespace PushManagerImpl_Binding



already_AddRefed<Promise>
PushManagerImplJSImpl::Subscribe(const PushSubscriptionOptionsInit& options, ErrorResult& aRv, JS::Realm* aRealm)
{
  CallSetup s(this, aRv, "PushManagerImpl.subscribe", eRethrowContentExceptions, aRealm, /* aIsJSImplementedWebIDL = */ true);
  if (aRv.Failed()) {
    return nullptr;
  }
  MOZ_ASSERT(s.GetContext());
  BindingCallContext& cx = s.GetCallContext();

  JS::Rooted<JS::Value> rval(cx);
  JS::RootedVector<JS::Value> argv(cx);
  if (!argv.resize(1)) {
    // That threw an exception on the JSContext, and our CallSetup will do
    // the right thing with that.
    return nullptr;
  }
  unsigned argc = 1;

  do {
    if (!options.ToObjectInternal(cx, argv[0])) {
      aRv.Throw(NS_ERROR_UNEXPECTED);
      return nullptr;
    }
    break;
  } while (false);

  JS::Rooted<JS::Value> callable(cx);
  PushManagerImplAtoms* atomsCache = GetAtomCache<PushManagerImplAtoms>(cx);
  if ((reinterpret_cast<jsid*>(atomsCache)->isVoid() &&
       !InitIds(cx, atomsCache)) ||
      !GetCallableProperty(cx, atomsCache->subscribe_id, &callable)) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return nullptr;
  }
  JS::Rooted<JS::Value> thisValue(cx, JS::ObjectValue(*mCallback));
  if (!JS::Call(cx, thisValue, callable,
                JS::HandleValueArray::subarray(argv, 0, argc), &rval)) {
    aRv.NoteJSContextException(cx);
    return nullptr;
  }
  RefPtr<Promise> rvalDecl;
  { // Scope for our GlobalObject, FastErrorResult, JSAutoRealm,
    // etc.

    JS::Rooted<JSObject*> globalObj(cx);
    if (!rval.isObject()) {
      aRv.ThrowTypeError<MSG_NOT_OBJECT>("return value of PushManagerImpl.subscribe");
      return nullptr;
    }
    JSObject* unwrappedVal = js::CheckedUnwrapStatic(&rval.toObject());
    if (!unwrappedVal) {
      // A slight lie, but not much of one, for a dead object wrapper.
      aRv.ThrowTypeError<MSG_NOT_OBJECT>("return value of PushManagerImpl.subscribe");
      return nullptr;
    }
    globalObj = JS::GetNonCCWObjectGlobal(unwrappedVal);
    JSAutoRealm ar(cx, globalObj);
    GlobalObject promiseGlobal(cx, globalObj);
    if (promiseGlobal.Failed()) {
      aRv.Throw(NS_ERROR_UNEXPECTED);
      return nullptr;
    }

    JS::Rooted<JS::Value> valueToResolve(cx, rval);
    if (!JS_WrapValue(cx, &valueToResolve)) {
      aRv.Throw(NS_ERROR_UNEXPECTED);
      return nullptr;
    }
    binding_detail::FastErrorResult promiseRv;
    nsCOMPtr<nsIGlobalObject> global =
      do_QueryInterface(promiseGlobal.GetAsSupports());
    if (!global) {
      promiseRv.Throw(NS_ERROR_UNEXPECTED);
      MOZ_ALWAYS_TRUE(promiseRv.MaybeSetPendingException(cx));
      aRv.Throw(NS_ERROR_UNEXPECTED);
      return nullptr;
    }
    rvalDecl = Promise::Resolve(global, cx, valueToResolve,
                                    promiseRv);
    if (promiseRv.MaybeSetPendingException(cx)) {
      aRv.Throw(NS_ERROR_UNEXPECTED);
      return nullptr;
    }
  }
  return rvalDecl.forget();
}

already_AddRefed<Promise>
PushManagerImplJSImpl::GetSubscription(ErrorResult& aRv, JS::Realm* aRealm)
{
  CallSetup s(this, aRv, "PushManagerImpl.getSubscription", eRethrowContentExceptions, aRealm, /* aIsJSImplementedWebIDL = */ true);
  if (aRv.Failed()) {
    return nullptr;
  }
  MOZ_ASSERT(s.GetContext());
  BindingCallContext& cx = s.GetCallContext();

  JS::Rooted<JS::Value> rval(cx);

  JS::Rooted<JS::Value> callable(cx);
  PushManagerImplAtoms* atomsCache = GetAtomCache<PushManagerImplAtoms>(cx);
  if ((reinterpret_cast<jsid*>(atomsCache)->isVoid() &&
       !InitIds(cx, atomsCache)) ||
      !GetCallableProperty(cx, atomsCache->getSubscription_id, &callable)) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return nullptr;
  }
  JS::Rooted<JS::Value> thisValue(cx, JS::ObjectValue(*mCallback));
  if (!JS::Call(cx, thisValue, callable,
                JS::HandleValueArray::empty(), &rval)) {
    aRv.NoteJSContextException(cx);
    return nullptr;
  }
  RefPtr<Promise> rvalDecl;
  { // Scope for our GlobalObject, FastErrorResult, JSAutoRealm,
    // etc.

    JS::Rooted<JSObject*> globalObj(cx);
    if (!rval.isObject()) {
      aRv.ThrowTypeError<MSG_NOT_OBJECT>("return value of PushManagerImpl.getSubscription");
      return nullptr;
    }
    JSObject* unwrappedVal = js::CheckedUnwrapStatic(&rval.toObject());
    if (!unwrappedVal) {
      // A slight lie, but not much of one, for a dead object wrapper.
      aRv.ThrowTypeError<MSG_NOT_OBJECT>("return value of PushManagerImpl.getSubscription");
      return nullptr;
    }
    globalObj = JS::GetNonCCWObjectGlobal(unwrappedVal);
    JSAutoRealm ar(cx, globalObj);
    GlobalObject promiseGlobal(cx, globalObj);
    if (promiseGlobal.Failed()) {
      aRv.Throw(NS_ERROR_UNEXPECTED);
      return nullptr;
    }

    JS::Rooted<JS::Value> valueToResolve(cx, rval);
    if (!JS_WrapValue(cx, &valueToResolve)) {
      aRv.Throw(NS_ERROR_UNEXPECTED);
      return nullptr;
    }
    binding_detail::FastErrorResult promiseRv;
    nsCOMPtr<nsIGlobalObject> global =
      do_QueryInterface(promiseGlobal.GetAsSupports());
    if (!global) {
      promiseRv.Throw(NS_ERROR_UNEXPECTED);
      MOZ_ALWAYS_TRUE(promiseRv.MaybeSetPendingException(cx));
      aRv.Throw(NS_ERROR_UNEXPECTED);
      return nullptr;
    }
    rvalDecl = Promise::Resolve(global, cx, valueToResolve,
                                    promiseRv);
    if (promiseRv.MaybeSetPendingException(cx)) {
      aRv.Throw(NS_ERROR_UNEXPECTED);
      return nullptr;
    }
  }
  return rvalDecl.forget();
}

already_AddRefed<Promise>
PushManagerImplJSImpl::PermissionState(const PushSubscriptionOptionsInit& options, ErrorResult& aRv, JS::Realm* aRealm)
{
  CallSetup s(this, aRv, "PushManagerImpl.permissionState", eRethrowContentExceptions, aRealm, /* aIsJSImplementedWebIDL = */ true);
  if (aRv.Failed()) {
    return nullptr;
  }
  MOZ_ASSERT(s.GetContext());
  BindingCallContext& cx = s.GetCallContext();

  JS::Rooted<JS::Value> rval(cx);
  JS::RootedVector<JS::Value> argv(cx);
  if (!argv.resize(1)) {
    // That threw an exception on the JSContext, and our CallSetup will do
    // the right thing with that.
    return nullptr;
  }
  unsigned argc = 1;

  do {
    if (!options.ToObjectInternal(cx, argv[0])) {
      aRv.Throw(NS_ERROR_UNEXPECTED);
      return nullptr;
    }
    break;
  } while (false);

  JS::Rooted<JS::Value> callable(cx);
  PushManagerImplAtoms* atomsCache = GetAtomCache<PushManagerImplAtoms>(cx);
  if ((reinterpret_cast<jsid*>(atomsCache)->isVoid() &&
       !InitIds(cx, atomsCache)) ||
      !GetCallableProperty(cx, atomsCache->permissionState_id, &callable)) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return nullptr;
  }
  JS::Rooted<JS::Value> thisValue(cx, JS::ObjectValue(*mCallback));
  if (!JS::Call(cx, thisValue, callable,
                JS::HandleValueArray::subarray(argv, 0, argc), &rval)) {
    aRv.NoteJSContextException(cx);
    return nullptr;
  }
  RefPtr<Promise> rvalDecl;
  { // Scope for our GlobalObject, FastErrorResult, JSAutoRealm,
    // etc.

    JS::Rooted<JSObject*> globalObj(cx);
    if (!rval.isObject()) {
      aRv.ThrowTypeError<MSG_NOT_OBJECT>("return value of PushManagerImpl.permissionState");
      return nullptr;
    }
    JSObject* unwrappedVal = js::CheckedUnwrapStatic(&rval.toObject());
    if (!unwrappedVal) {
      // A slight lie, but not much of one, for a dead object wrapper.
      aRv.ThrowTypeError<MSG_NOT_OBJECT>("return value of PushManagerImpl.permissionState");
      return nullptr;
    }
    globalObj = JS::GetNonCCWObjectGlobal(unwrappedVal);
    JSAutoRealm ar(cx, globalObj);
    GlobalObject promiseGlobal(cx, globalObj);
    if (promiseGlobal.Failed()) {
      aRv.Throw(NS_ERROR_UNEXPECTED);
      return nullptr;
    }

    JS::Rooted<JS::Value> valueToResolve(cx, rval);
    if (!JS_WrapValue(cx, &valueToResolve)) {
      aRv.Throw(NS_ERROR_UNEXPECTED);
      return nullptr;
    }
    binding_detail::FastErrorResult promiseRv;
    nsCOMPtr<nsIGlobalObject> global =
      do_QueryInterface(promiseGlobal.GetAsSupports());
    if (!global) {
      promiseRv.Throw(NS_ERROR_UNEXPECTED);
      MOZ_ALWAYS_TRUE(promiseRv.MaybeSetPendingException(cx));
      aRv.Throw(NS_ERROR_UNEXPECTED);
      return nullptr;
    }
    rvalDecl = Promise::Resolve(global, cx, valueToResolve,
                                    promiseRv);
    if (promiseRv.MaybeSetPendingException(cx)) {
      aRv.Throw(NS_ERROR_UNEXPECTED);
      return nullptr;
    }
  }
  return rvalDecl.forget();
}

void
PushManagerImplJSImpl::__Init(const nsAString& scope, ErrorResult& aRv, JS::Realm* aRealm)
{
  CallSetup s(this, aRv, "__init", eRethrowContentExceptions, aRealm, /* aIsJSImplementedWebIDL = */ true);
  if (aRv.Failed()) {
    return;
  }
  MOZ_ASSERT(s.GetContext());
  BindingCallContext& cx = s.GetCallContext();

  JS::Rooted<JS::Value> rval(cx);
  JS::RootedVector<JS::Value> argv(cx);
  if (!argv.resize(1)) {
    // That threw an exception on the JSContext, and our CallSetup will do
    // the right thing with that.
    return;
  }
  unsigned argc = 1;

  do {
    if (!xpc::NonVoidStringToJsval(cx, scope, argv[0])) {
      aRv.Throw(NS_ERROR_UNEXPECTED);
      return;
    }
    break;
  } while (false);

  JS::Rooted<JS::Value> callable(cx);
  PushManagerImplAtoms* atomsCache = GetAtomCache<PushManagerImplAtoms>(cx);
  if ((reinterpret_cast<jsid*>(atomsCache)->isVoid() &&
       !InitIds(cx, atomsCache)) ||
      !GetCallableProperty(cx, atomsCache->__init_id, &callable)) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return;
  }
  JS::Rooted<JS::Value> thisValue(cx, JS::ObjectValue(*mCallback));
  if (!JS::Call(cx, thisValue, callable,
                JS::HandleValueArray::subarray(argv, 0, argc), &rval)) {
    aRv.NoteJSContextException(cx);
    return;
  }
}

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

  // Initialize these in reverse order so that any failure leaves the first one
  // uninitialized.
  if (!atomsCache->__init_id.init(cx, "__init") ||
      !atomsCache->permissionState_id.init(cx, "permissionState") ||
      !atomsCache->getSubscription_id.init(cx, "getSubscription") ||
      !atomsCache->subscribe_id.init(cx, "subscribe")) {
    return false;
  }
  return true;
}



NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE_CLASS(PushManagerImpl)
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(PushManagerImpl)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mImpl)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mParent)
  NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER
  tmp->ClearWeakReferences();
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(PushManagerImpl)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mImpl)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mParent)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
NS_IMPL_CYCLE_COLLECTING_ADDREF(PushManagerImpl)
NS_IMPL_CYCLE_COLLECTING_RELEASE(PushManagerImpl)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(PushManagerImpl)
  NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
  NS_INTERFACE_MAP_ENTRY(nsISupports)
  NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
NS_INTERFACE_MAP_END

PushManagerImpl::PushManagerImpl(JS::Handle<JSObject*> aJSImplObject, JS::Handle<JSObject*> aJSImplGlobal, nsIGlobalObject* aParent)
  : mImpl(new PushManagerImplJSImpl(nullptr, aJSImplObject, aJSImplGlobal, /* aIncumbentGlobal = */ nullptr)),
    mParent(aParent)
{
}


PushManagerImpl::~PushManagerImpl()
{
}

nsISupports*
PushManagerImpl::GetParentObject() const
{
  return mParent;
}

JSObject*
PushManagerImpl::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto)
{
  JS::Rooted<JSObject*> obj(aCx, PushManagerImpl_Binding::Wrap(aCx, this, aGivenProto));
  if (!obj) {
    return nullptr;
  }

  // Now define it on our chrome object
  JSAutoRealm ar(aCx, mImpl->CallbackGlobalOrNull());
  if (!JS_WrapObject(aCx, &obj)) {
    return nullptr;
  }
  JS::Rooted<JSObject*> callback(aCx, mImpl->CallbackOrNull());
  if (!JS_DefineProperty(aCx, callback, "__DOM_IMPL__", obj, 0)) {
    return nullptr;
  }
  return obj;
}

already_AddRefed<PushManagerImpl>
PushManagerImpl::Constructor(const GlobalObject& global, JSContext* cx, const nsAString& scope, ErrorResult& aRv, JS::Handle<JSObject*> aGivenProto)
{
  RefPtr<PushManagerImpl> impl =
    ConstructJSImplementation<PushManagerImpl>("@mozilla.org/push/PushManager;1", global, aRv);
  if (aRv.Failed()) {
    return nullptr;
  }
  // Wrap the object before calling __Init so that __DOM_IMPL__ is available.
  JS::Rooted<JSObject*> scopeObj(cx, global.Get());
  MOZ_ASSERT(js::IsObjectInContextCompartment(scopeObj, cx));
  JS::Rooted<JS::Value> wrappedVal(cx);
  if (!GetOrCreateDOMReflector(cx, impl, &wrappedVal, aGivenProto)) {
    MOZ_ASSERT(JS_IsExceptionPending(cx));
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return nullptr;
  }
  // Initialize the object with the constructor arguments.
  impl->mImpl->__Init(scope, aRv, js::GetNonCCWObjectRealm(scopeObj));
  if (aRv.Failed()) {
    return nullptr;
  }
  return impl.forget();
}

// Return a raw pointer here to avoid refcounting, but make sure it's safe (the object should be kept alive by the callee).
already_AddRefed<Promise>
PushManagerImpl::Subscribe(const PushSubscriptionOptionsInit& options, ErrorResult& aRv, JS::Realm* aRealm)
{
  return mImpl->Subscribe(options, aRv, aRealm);
}

// Return a raw pointer here to avoid refcounting, but make sure it's safe (the object should be kept alive by the callee).
already_AddRefed<Promise>
PushManagerImpl::GetSubscription(ErrorResult& aRv, JS::Realm* aRealm)
{
  return mImpl->GetSubscription(aRv, aRealm);
}

// Return a raw pointer here to avoid refcounting, but make sure it's safe (the object should be kept alive by the callee).
already_AddRefed<Promise>
PushManagerImpl::PermissionState(const PushSubscriptionOptionsInit& options, ErrorResult& aRv, JS::Realm* aRealm)
{
  return mImpl->PermissionState(options, aRv, aRealm);
}

bool
PushManagerImpl::_Create(JSContext* cx, unsigned argc, JS::Value* vp)
{
  JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
  if (!args.requireAtLeast(cx, "PushManagerImpl._create", 2)) {
    return false;
  }
  BindingCallContext callCx(cx, "PushManagerImpl._create");
  if (!args[0].isObject()) {
    return callCx.ThrowErrorMessage<MSG_NOT_OBJECT>("Argument 1");
  }
  if (!args[1].isObject()) {
    return callCx.ThrowErrorMessage<MSG_NOT_OBJECT>("Argument 2");
  }

  // GlobalObject will go through wrappers as needed for us, and
  // is simpler than the right UnwrapArg incantation.
  GlobalObject global(cx, &args[0].toObject());
  if (global.Failed()) {
    return false;
  }
  nsCOMPtr<nsIGlobalObject> globalHolder = do_QueryInterface(global.GetAsSupports());
  MOZ_ASSERT(globalHolder);
  JS::Rooted<JSObject*> arg(cx, &args[1].toObject());
  JS::Rooted<JSObject*> argGlobal(cx, JS::CurrentGlobalOrNull(cx));
  RefPtr<PushManagerImpl> impl = new PushManagerImpl(arg, argGlobal, globalHolder);
  MOZ_ASSERT(js::IsObjectInContextCompartment(arg, cx));
  return GetOrCreateDOMReflector(cx, impl, args.rval());
}


} // namespace mozilla::dom
