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

#include <type_traits>
#include "AtomList.h"
#include "ClipboardBinding.h"
#include "EventTargetBinding.h"
#include "MainThreadUtils.h"
#include "WrapperFactory.h"
#include "XrayWrapper.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/experimental/JitInfo.h"
#include "jsapi.h"
#include "mozilla/Atomics.h"
#include "mozilla/BasePrincipal.h"
#include "mozilla/OwningNonNull.h"
#include "mozilla/ProfilerLabels.h"
#include "mozilla/dom/BindingCallContext.h"
#include "mozilla/dom/BindingUtils.h"
#include "mozilla/dom/Blob.h"
#include "mozilla/dom/Clipboard.h"
#include "mozilla/dom/ClipboardItem.h"
#include "mozilla/dom/DOMJSClass.h"
#include "mozilla/dom/NonRefcountedDOMObject.h"
#include "mozilla/dom/PrimitiveConversions.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/dom/Record.h"
#include "mozilla/dom/ScriptSettings.h"
#include "mozilla/dom/SimpleGlobalObject.h"
#include "mozilla/dom/ToJSValue.h"
#include "mozilla/dom/WebIDLPrefs.h"
#include "mozilla/dom/XrayExpandoClass.h"
#include "nsJSPrincipals.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<PresentationStyle>::Values[3];
} // namespace binding_detail

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


void
ImplCycleCollectionTraverse(nsCycleCollectionTraversalCallback& aCallback, OwningStringOrBlob& aUnion, const char* aName, uint32_t aFlags)
{
  if (aUnion.IsBlob()) {
    ImplCycleCollectionTraverse(aCallback, aUnion.GetAsBlob(), "mBlob", aFlags);
  }
}


void
ImplCycleCollectionUnlink(OwningStringOrBlob& aUnion)
{
  aUnion.Uninit();
}



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




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

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

bool
ClipboardItemOptions::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());
  ClipboardItemOptionsAtoms* atomsCache = nullptr;
  if (cx) {
    atomsCache = GetAtomCache<ClipboardItemOptionsAtoms>(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->presentationStyle_id, temp.ptr())) {
      return false;
    }
  }
  if (!isNull && !temp->isUndefined()) {
    {
      int index;
      if (!binding_detail::FindEnumStringIndex<true>(cx, temp.ref(),
                                                                         binding_detail::EnumStrings<PresentationStyle>::Values,
                                                                         "PresentationStyle", "'presentationStyle' member of ClipboardItemOptions",
                                                                         &index)) {
        return false;
      }
      MOZ_ASSERT(index >= 0);
      mPresentationStyle = static_cast<PresentationStyle>(index);
    }
  } else {
    mPresentationStyle = PresentationStyle::Unspecified;
  }
  mIsAnyMemberPresent = true;
  return true;
}

bool
ClipboardItemOptions::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
ClipboardItemOptions::TraceDictionary(JSTracer* trc)
{
}

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


bool
StringOrBlob::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
StringOrBlob::TrySetToBlob(BindingCallContext& cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
  tryNext = false;
  { // scope for memberSlot
    NonNull<mozilla::dom::Blob>& memberSlot = RawSetAsBlob();
    {
      // Our JSContext should be in the right global to do unwrapping in.
      nsresult rv = UnwrapObject<prototypes::id::Blob, mozilla::dom::Blob>(value, memberSlot, cx);
      if (NS_FAILED(rv)) {
        DestroyBlob();
        tryNext = true;
        return true;
      }
    }
  }
  return true;
}

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







bool
StringOrBlob::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 = !TrySetToBlob(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, "Blob");
    return false;
  }
  return true;
}

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


bool
StringOrBlob::ToJSVal(JSContext* cx, JS::Handle<JSObject*> scopeObj, JS::MutableHandle<JS::Value> rval) const
{
  switch (mType) {
    case eUninitialized: {
      return false;
    }
    case eString: {
      if (!xpc::NonVoidStringToJsval(cx, mValue.mString.Value(), rval)) {
        return false;
      }
      return true;
    }
    case eBlob: {
      if (!GetOrCreateDOMReflector(cx, mValue.mBlob.Value(), rval)) {
        MOZ_ASSERT(JS_IsExceptionPending(cx));
        return false;
      }
      return true;
    }
    default: {
      return false;
    }
  }
}



OwningStringOrBlob::OwningStringOrBlob(OwningStringOrBlob&& aOther)
  : mType(eUninitialized)
{
  switch (aOther.mType) {
    case eUninitialized: {
      MOZ_ASSERT(mType == eUninitialized,
                 "We need to destroy ourselves?");
      break;
    }
    case eString: {
      mType = eString;
      mValue.mString.SetValue(std::move(aOther.mValue.mString.Value()));
      break;
    }
    case eBlob: {
      mType = eBlob;
      mValue.mBlob.SetValue(std::move(aOther.mValue.mBlob.Value()));
      break;
    }
  }
}



bool
OwningStringOrBlob::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&
OwningStringOrBlob::RawSetAsString()
{
  if (mType == eString) {
    return mValue.mString.Value();
  }
  MOZ_ASSERT(mType == eUninitialized);
  mType = eString;
  return mValue.mString.SetValue();
}

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



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



bool
OwningStringOrBlob::TrySetToBlob(BindingCallContext& cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
  tryNext = false;
  { // scope for memberSlot
    OwningNonNull<mozilla::dom::Blob>& memberSlot = RawSetAsBlob();
    static_assert(IsRefcounted<mozilla::dom::Blob>::value, "We can only store refcounted classes.");
    {
      // Our JSContext should be in the right global to do unwrapping in.
      nsresult rv = UnwrapObject<prototypes::id::Blob, mozilla::dom::Blob>(value, memberSlot, cx);
      if (NS_FAILED(rv)) {
        DestroyBlob();
        tryNext = true;
        return true;
      }
    }
  }
  return true;
}

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

[[nodiscard]] OwningNonNull<mozilla::dom::Blob>&
OwningStringOrBlob::RawSetAsBlob()
{
  if (mType == eBlob) {
    return mValue.mBlob.Value();
  }
  MOZ_ASSERT(mType == eUninitialized);
  mType = eBlob;
  return mValue.mBlob.SetValue();
}

[[nodiscard]] OwningNonNull<mozilla::dom::Blob>&
OwningStringOrBlob::SetAsBlob()
{
  if (mType == eBlob) {
    return mValue.mBlob.Value();
  }
  Uninit();
  mType = eBlob;
  return mValue.mBlob.SetValue();
}


void
OwningStringOrBlob::DestroyBlob()
{
  MOZ_RELEASE_ASSERT(IsBlob(), "Wrong type!");
  mValue.mBlob.Destroy();
  mType = eUninitialized;
}



bool
OwningStringOrBlob::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 = !TrySetToBlob(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, "Blob");
    return false;
  }
  return true;
}

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

void
OwningStringOrBlob::Uninit()
{
  switch (mType) {
    case eUninitialized: {
      break;
    }
    case eString: {
      DestroyString();
      break;
    }
    case eBlob: {
      DestroyBlob();
      break;
    }
  }
}

bool
OwningStringOrBlob::ToJSVal(JSContext* cx, JS::Handle<JSObject*> scopeObj, JS::MutableHandle<JS::Value> rval) const
{
  switch (mType) {
    case eUninitialized: {
      return false;
    }
    case eString: {
      if (!xpc::NonVoidStringToJsval(cx, mValue.mString.Value(), rval)) {
        return false;
      }
      return true;
    }
    case eBlob: {
      if (!GetOrCreateDOMReflector(cx, mValue.mBlob.Value(), rval)) {
        MOZ_ASSERT(JS_IsExceptionPending(cx));
        return false;
      }
      return true;
    }
    default: {
      return false;
    }
  }
}

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


OwningStringOrBlob&
OwningStringOrBlob::operator=(const OwningStringOrBlob& aOther)
{
  switch (aOther.mType) {
    case eUninitialized: {
      MOZ_ASSERT(mType == eUninitialized,
                 "We need to destroy ourselves?");
      break;
    }
    case eString: {
      SetAsString() = aOther.GetAsString();
      break;
    }
    case eBlob: {
      SetAsBlob() = aOther.GetAsBlob();
      break;
    }
  }
  return *this;
}


namespace Clipboard_Binding {

static_assert(IsRefcounted<NativeType>::value == IsRefcounted<EventTarget_Binding::NativeType>::value,
              "Can't inherit from an interface with a different ownership model.");

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

  auto* self = static_cast<mozilla::dom::Clipboard*>(void_self);
  FastErrorResult rv;
  NonNull<nsIPrincipal> subjectPrincipal;
  {
    JS::Realm* realm = js::GetContextRealm(cx);
    MOZ_ASSERT(realm);
    JSPrincipals* principals = JS::GetRealmPrincipals(realm);
    nsIPrincipal* principal = nsJSPrincipals::get(principals);

    subjectPrincipal = principal;
  }
  auto result(StrongOrRawPtr<Promise>(MOZ_KnownLive(self)->Read(MOZ_KnownLive(NonNullHelper(subjectPrincipal)), rv)));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "Clipboard.read"))) {
    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
read_promiseWrapper(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
  bool ok = read(cx, obj, void_self, args);
  if (ok) {
    return true;
  }
  return ConvertExceptionToPromise(cx, args.rval());
}

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

  auto* self = static_cast<mozilla::dom::Clipboard*>(void_self);
  FastErrorResult rv;
  NonNull<nsIPrincipal> subjectPrincipal;
  {
    JS::Realm* realm = js::GetContextRealm(cx);
    MOZ_ASSERT(realm);
    JSPrincipals* principals = JS::GetRealmPrincipals(realm);
    nsIPrincipal* principal = nsJSPrincipals::get(principals);

    subjectPrincipal = principal;
  }
  auto result(StrongOrRawPtr<Promise>(MOZ_KnownLive(self)->ReadText(MOZ_KnownLive(NonNullHelper(subjectPrincipal)), rv)));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "Clipboard.readText"))) {
    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
readText_promiseWrapper(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
  bool ok = readText(cx, obj, void_self, args);
  if (ok) {
    return true;
  }
  return ConvertExceptionToPromise(cx, args.rval());
}

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

  auto* self = static_cast<mozilla::dom::Clipboard*>(void_self);
  if (!args.requireAtLeast(cx, "Clipboard.write", 1)) {
    return false;
  }
  binding_detail::AutoSequence<OwningNonNull<mozilla::dom::ClipboardItem>> arg0;
  if (args[0].isObject()) {
    JS::ForOfIterator iter(cx);
    if (!iter.init(args[0], JS::ForOfIterator::AllowNonIterable)) {
      return false;
    }
    if (!iter.valueIsIterable()) {
      cx.ThrowErrorMessage<MSG_CONVERSION_ERROR>("Argument 1", "sequence");
      return false;
    }
    binding_detail::AutoSequence<OwningNonNull<mozilla::dom::ClipboardItem>> &arr = arg0;
    JS::Rooted<JS::Value> temp(cx);
    while (true) {
      bool done;
      if (!iter.next(&temp, &done)) {
        return false;
      }
      if (done) {
        break;
      }
      OwningNonNull<mozilla::dom::ClipboardItem>* slotPtr = arr.AppendElement(mozilla::fallible);
      if (!slotPtr) {
        JS_ReportOutOfMemory(cx);
        return false;
      }
      OwningNonNull<mozilla::dom::ClipboardItem>& slot = *slotPtr;
      if (temp.isObject()) {
        static_assert(IsRefcounted<mozilla::dom::ClipboardItem>::value, "We can only store refcounted classes.");
        {
          // Our JSContext should be in the right global to do unwrapping in.
          nsresult rv = UnwrapObject<prototypes::id::ClipboardItem, mozilla::dom::ClipboardItem>(&temp, slot, cx);
          if (NS_FAILED(rv)) {
            cx.ThrowErrorMessage<MSG_DOES_NOT_IMPLEMENT_INTERFACE>("Element of argument 1", "ClipboardItem");
            return false;
          }
        }
      } else {
        cx.ThrowErrorMessage<MSG_NOT_OBJECT>("Element of argument 1");
        return false;
      }
    }
  } else {
    cx.ThrowErrorMessage<MSG_CONVERSION_ERROR>("Argument 1", "sequence");
    return false;
  }
  FastErrorResult rv;
  NonNull<nsIPrincipal> subjectPrincipal;
  {
    JS::Realm* realm = js::GetContextRealm(cx);
    MOZ_ASSERT(realm);
    JSPrincipals* principals = JS::GetRealmPrincipals(realm);
    nsIPrincipal* principal = nsJSPrincipals::get(principals);

    subjectPrincipal = principal;
  }
  auto result(StrongOrRawPtr<Promise>(MOZ_KnownLive(self)->Write(Constify(arg0), MOZ_KnownLive(NonNullHelper(subjectPrincipal)), rv)));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "Clipboard.write"))) {
    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
write_promiseWrapper(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
  bool ok = write(cx, obj, void_self, args);
  if (ok) {
    return true;
  }
  return ConvertExceptionToPromise(cx, args.rval());
}

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

  auto* self = static_cast<mozilla::dom::Clipboard*>(void_self);
  if (!args.requireAtLeast(cx, "Clipboard.writeText", 1)) {
    return false;
  }
  binding_detail::FakeString<char16_t> arg0;
  if (!ConvertJSValueToString(cx, args[0], eStringify, eStringify, arg0)) {
    return false;
  }
  FastErrorResult rv;
  NonNull<nsIPrincipal> subjectPrincipal;
  {
    JS::Realm* realm = js::GetContextRealm(cx);
    MOZ_ASSERT(realm);
    JSPrincipals* principals = JS::GetRealmPrincipals(realm);
    nsIPrincipal* principal = nsJSPrincipals::get(principals);

    subjectPrincipal = principal;
  }
  auto result(StrongOrRawPtr<Promise>(MOZ_KnownLive(self)->WriteText(NonNullHelper(Constify(arg0)), MOZ_KnownLive(NonNullHelper(subjectPrincipal)), rv)));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "Clipboard.writeText"))) {
    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
writeText_promiseWrapper(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
  bool ok = writeText(cx, obj, void_self, args);
  if (ok) {
    return true;
  }
  return ConvertExceptionToPromise(cx, args.rval());
}

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

MOZ_GLOBINIT static const JSFunctionSpec sMethods_specs[] = {
  JS_FNSPEC("read", (GenericMethod<NormalThisPolicy, ConvertExceptionsToPromises>), reinterpret_cast<const JSJitInfo*>(&read_methodinfo), 0, JSPROP_ENUMERATE, nullptr),
  JS_FNSPEC("readText", (GenericMethod<NormalThisPolicy, ConvertExceptionsToPromises>), reinterpret_cast<const JSJitInfo*>(&readText_methodinfo), 0, JSPROP_ENUMERATE, nullptr),
  JS_FNSPEC("write", (GenericMethod<NormalThisPolicy, ConvertExceptionsToPromises>), reinterpret_cast<const JSJitInfo*>(&write_methodinfo), 1, JSPROP_ENUMERATE, nullptr),
  JS_FNSPEC("writeText", (GenericMethod<NormalThisPolicy, ConvertExceptionsToPromises>), reinterpret_cast<const JSJitInfo*>(&writeText_methodinfo), 1, JSPROP_ENUMERATE, nullptr),
  JS_FS_END
};

static const PrefableDisablers sMethods_disablers0 = {
  WebIDLPrefIndex::NoPref, 0, true, OriginTrial(0), nullptr
};

static const Prefable<const JSFunctionSpec> sMethods[] = {
  { &sMethods_disablers0, &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(4 <= 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<1> sNativeProperties = {
  false, 0,
  false, 0,
  true,  0 /* sMethods */,
  false, 0,
  false, 0,
  false, 0,
  false, 0,
  -1,
  4,
  sNativeProperties_sortedPropertyIndices,
  {
    { sMethods, &sNativeProperties_propertyInfos[0] }
  }
};
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::Clipboard,
  constructors::id::Clipboard,
  &DefaultXrayExpandoObjectClass
};

static const DOMInterfaceInfo sInterfaceObjectInfo = {
  { ThrowingConstructor, &sNativePropertyHooks },
  EventTarget_Binding::GetConstructorObjectHandle,
  PrototypeTraits<prototypes::id::Clipboard>::Depth,
  prototypes::id::Clipboard,
  true,
  0,
  "Clipboard",
};

static const DOMIfaceAndProtoJSClass sPrototypeClass = {
  {
    "ClipboardPrototype",
    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::Clipboard,
  PrototypeTraits<prototypes::id::Clipboard>::Depth,
  &sNativePropertyHooks,
  EventTarget_Binding::GetProtoObject
};

bool
ConstructorEnabled(JSContext* aCx, JS::Handle<JSObject*> aObj)
{
  return mozilla::dom::IsSecureContextOrObjectIsFromSecureContext(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 = {
  { "Clipboard",
    JSCLASS_IS_DOMJSCLASS | JSCLASS_FOREGROUND_FINALIZE | JSCLASS_HAS_RESERVED_SLOTS(1) | JSCLASS_PRESERVES_WRAPPER,
    &sClassOps,
    JS_NULL_CLASS_SPEC,
    &NativeTypeHelpers<mozilla::dom::Clipboard>::sClassExtension,
    JS_NULL_OBJECT_OPS
  },
  { prototypes::id::EventTarget, prototypes::id::Clipboard, 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::Clipboard>,
  &sNativePropertyHooks,
  FindAssociatedGlobalForNative<mozilla::dom::Clipboard>::Get,
  GetProtoObjectHandle,
  GetCCParticipant<mozilla::dom::Clipboard>::Get(),
  nullptr,
  NativeTypeHelpers<mozilla::dom::Clipboard>::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::Clipboard* aObject, nsWrapperCache* aCache, JS::Handle<JSObject*> aGivenProto, JS::MutableHandle<JSObject*> aReflector)
{
  static_assert(!std::is_base_of_v<NonRefcountedDOMObject, mozilla::dom::Clipboard>,
                "Shouldn't have wrappercached things that are not refcounted.");
  static_assert(std::is_same_v<decltype(aObject), mozilla::dom::Clipboard*>);
  MOZ_ASSERT(static_cast<mozilla::dom::EventTarget*>(aObject) ==
             reinterpret_cast<mozilla::dom::EventTarget*>(aObject),
             "Multiple inheritance for mozilla::dom::EventTarget is broken.");
  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::Clipboard> 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::Clipboard);
  JS::Heap<JSObject*>* interfaceCache = &aProtoAndIfaceCache.EntrySlotOrCreate(constructors::id::Clipboard);

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

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

  dom::CreateInterfaceObjects(aCx, aGlobal, parentProto,
                              &sPrototypeClass, protoCache,
                              constructorProto, &sInterfaceObjectInfo, 0, false, Span<const LegacyFactoryFunction, 0>{},
                              interfaceCache,
                              sNativeProperties.Upcast(),
                              nullptr,
                              "Clipboard",
                              ShouldExpose<Clipboard_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::Clipboard,
                                     &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::Clipboard,
                                     &CreateInterfaceObjects,
                                     DefineInterfaceProperty::CheckExposure);
}

} // namespace Clipboard_Binding



namespace ClipboardItem_Binding {

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

  auto* self = static_cast<mozilla::dom::ClipboardItem*>(void_self);
  PresentationStyle result(MOZ_KnownLive(self)->PresentationStyle());
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  if (!ToJSValue(cx, result, args.rval())) {
    return false;
  }
  return true;
}

static const JSJitInfo presentationStyle_getterinfo = {
  { get_presentationStyle },
  { prototypes::id::ClipboardItem },
  { PrototypeTraits<prototypes::id::ClipboardItem>::Depth },
  JSJitInfo::Getter,
  JSJitInfo::AliasEverything, /* aliasSet.  Not relevant for setters. */
  JSVAL_TYPE_STRING,  /* 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
get_types(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, JSJitGetterCallArgs args)
{
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "ClipboardItem", "types", DOM, cx,
    uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_GETTER) |
    uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

  auto* self = static_cast<mozilla::dom::ClipboardItem*>(void_self);
  // Have to either root across the getter call or reget after.
  bool isXray;
  JS::Rooted<JSObject*> slotStorage(cx, GetCachedSlotStorageObject(cx, obj, &isXray));
  if (!slotStorage) {
    return false;
  }
  const size_t slotIndex = isXray ? (DOM_EXPANDO_RESERVED_SLOTS + 0) : (DOM_INSTANCE_RESERVED_SLOTS + 0);
  MOZ_ASSERT(slotIndex < JSCLASS_RESERVED_SLOTS(JS::GetClass(slotStorage)));
  {
    // Scope for cachedVal
    JS::Value cachedVal = JS::GetReservedSlot(slotStorage, slotIndex);
    if (!cachedVal.isUndefined()) {
      args.rval().set(cachedVal);
      // The cached value is in the compartment of slotStorage,
      // so wrap into the caller compartment as needed.
      return MaybeWrapNonDOMObjectValue(cx, args.rval());
    }
  }

  nsTArray<nsString> result;
  // NOTE: This assert does NOT call the function.
  static_assert(std::is_void_v<decltype(MOZ_KnownLive(self)->GetTypes(result))>, "Should be returning void here");
  MOZ_KnownLive(self)->GetTypes(result);
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  {
    JS::Rooted<JSObject*> conversionScope(cx, isXray ? JS::CurrentGlobalOrNull(cx) : slotStorage);
    JSAutoRealm ar(cx, conversionScope);
    do { // block we break out of when done wrapping

      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 (!xpc::NonVoidStringToJsval(cx, result[sequenceIdx0], &tmp)) {
              return false;
            }
            break;
          } while (false);
          if (!JS_DefineElement(cx, returnArray, sequenceIdx0, tmp,
                                JSPROP_ENUMERATE)) {
            return false;
          }
        }
      }
      args.rval().setObject(*returnArray);
      break;
    } while (false);
    JS::Rooted<JSObject*> rvalObj(cx, &args.rval().toObject());
    if (!JS_FreezeObject(cx, rvalObj)) {
      return false;
    }
  }
  { // And now store things in the realm of our slotStorage.
    JSAutoRealm ar(cx, slotStorage);
    // Make a copy so that we don't do unnecessary wrapping on args.rval().
    JS::Rooted<JS::Value> storedVal(cx, args.rval());
    if (!MaybeWrapNonDOMObjectValue(cx, &storedVal)) {
      return false;
    }
    JS::SetReservedSlot(slotStorage, slotIndex, storedVal);
    if (!isXray) {
      // In the Xray case we don't need to do this, because getting the
      // expando object already preserved our wrapper.
      PreserveWrapper(self);
    }
  }
  // And now make sure args.rval() is in the caller realm.
  return MaybeWrapNonDOMObjectValue(cx, args.rval());
}

static const JSJitInfo types_getterinfo = {
  { get_types },
  { prototypes::id::ClipboardItem },
  { PrototypeTraits<prototypes::id::ClipboardItem>::Depth },
  JSJitInfo::Getter,
  JSJitInfo::AliasDOMSets, /* aliasSet.  Not relevant for setters. */
  JSVAL_TYPE_OBJECT,  /* returnType.  Not relevant for setters. */
  false,  /* isInfallible. False in setters. */
  true,  /* isMovable.  Not relevant for setters. */
  true, /* isEliminatable.  Not relevant for setters. */
  false, /* isAlwaysInSlot.  Only relevant for getters. */
  true, /* isLazilyCachedInSlot.  Only relevant for getters. */
  false,  /* isTypedMethod.  Only relevant for methods. */
  (DOM_INSTANCE_RESERVED_SLOTS + 0)   /* Reserved slot index, if we're stored in a slot, else 0. */
};
static_assert((DOM_INSTANCE_RESERVED_SLOTS + 0) <= JSJitInfo::maxSlotIndex, "We won't fit");
static_assert((DOM_INSTANCE_RESERVED_SLOTS + 0) < 2, "There is no slot for us");

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

  auto* self = static_cast<mozilla::dom::ClipboardItem*>(void_self);
  if (!args.requireAtLeast(cx, "ClipboardItem.getType", 1)) {
    return false;
  }
  binding_detail::FakeString<char16_t> arg0;
  if (!ConvertJSValueToString(cx, args[0], eStringify, eStringify, arg0)) {
    return false;
  }
  FastErrorResult rv;
  auto result(StrongOrRawPtr<Promise>(MOZ_KnownLive(self)->GetType(NonNullHelper(Constify(arg0)), rv)));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "ClipboardItem.getType"))) {
    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
getType_promiseWrapper(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
  bool ok = getType(cx, obj, void_self, args);
  if (ok) {
    return true;
  }
  return ConvertExceptionToPromise(cx, args.rval());
}

static const JSJitInfo getType_methodinfo = {
  { (JSJitGetterOp)getType_promiseWrapper },
  { prototypes::id::ClipboardItem },
  { PrototypeTraits<prototypes::id::ClipboardItem>::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
supports(JSContext* cx, unsigned argc, JS::Value* vp)
{
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "ClipboardItem", "supports", 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, "ClipboardItem.supports", 1)) {
    return false;
  }
  GlobalObject global(cx, xpc::XrayAwareCalleeGlobal(obj));
  if (global.Failed()) {
    return false;
  }

  binding_detail::FakeString<char16_t> arg0;
  if (!ConvertJSValueToString(cx, args[0], eStringify, eStringify, arg0)) {
    return false;
  }
  bool result(mozilla::dom::ClipboardItem::Supports(global, NonNullHelper(Constify(arg0))));
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  args.rval().setBoolean(result);
  return true;
}

static void
_finalize(JS::GCContext* gcx, JSObject* obj)
{
  mozilla::dom::ClipboardItem* self = UnwrapPossiblyNotInitializedDOMObject<mozilla::dom::ClipboardItem>(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::ClipboardItem>(self);
  }
}

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

static const PrefableDisablers sStaticMethods_disablers0 = {
  WebIDLPrefIndex::NoPref, 0, true, OriginTrial(0), nullptr
};

static const Prefable<const JSFunctionSpec> sStaticMethods[] = {
  { &sStaticMethods_disablers0, &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("getType", (GenericMethod<NormalThisPolicy, ConvertExceptionsToPromises>), reinterpret_cast<const JSJitInfo*>(&getType_methodinfo), 1, JSPROP_ENUMERATE, nullptr),
  JS_FS_END
};

static const PrefableDisablers sMethods_disablers0 = {
  WebIDLPrefIndex::NoPref, 0, true, OriginTrial(0), nullptr
};

static const Prefable<const JSFunctionSpec> sMethods[] = {
  { &sMethods_disablers0, &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(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 JSPropertySpec sAttributes_specs[] = {
  JSPropertySpec::nativeAccessors("presentationStyle", JSPROP_ENUMERATE, GenericGetter<NormalThisPolicy, ThrowExceptions>, &presentationStyle_getterinfo, nullptr, nullptr),
  JSPropertySpec::nativeAccessors("types", JSPROP_ENUMERATE, GenericGetter<NormalThisPolicy, ThrowExceptions>, &types_getterinfo, nullptr, nullptr),
  JS_PS_END
};

static const PrefableDisablers sAttributes_disablers0 = {
  WebIDLPrefIndex::NoPref, 0, true, OriginTrial(0), nullptr
};

static const Prefable<const JSPropertySpec> sAttributes[] = {
  { &sAttributes_disablers0, &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(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[4];
static PropertyInfo sNativeProperties_propertyInfos[4];

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

// This may allocate too many slots, because we only really need
// slots for our non-interface-typed members that we cache.  But
// allocating slots only for those would make the slot index
// computations much more complicated, so let's do this the simple
// way for now.
DEFINE_XRAY_EXPANDO_CLASS_WITH_OPS(static, sXrayExpandoObjectClass, 1,
                                   &xpc::XrayExpandoObjectClassOps);

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

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

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

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

  bool objIsXray = xpc::WrapperFactory::IsXrayWrapper(obj);
  Record<nsString, OwningNonNull<Promise>> arg0;
  if (args[0].isObject()) {
    auto& recordEntries = arg0.Entries();

    JS::Rooted<JSObject*> recordObj(cx, &args[0].toObject());
    JS::RootedVector<jsid> ids(cx);
    if (!js::GetPropertyKeys(cx, recordObj,
                             JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS, &ids)) {
      return false;
    }
    if (!recordEntries.SetCapacity(ids.length(), mozilla::fallible)) {
      JS_ReportOutOfMemory(cx);
      return false;
    }
    JS::Rooted<JS::Value> propNameValue(cx);
    JS::Rooted<JS::Value> temp(cx);
    JS::Rooted<jsid> curId(cx);
    JS::Rooted<JS::Value> idVal(cx);
    // Use a hashset to keep track of ids seen, to avoid
    // introducing nasty O(N^2) behavior scanning for them all the
    // time.  Ideally we'd use a data structure with O(1) lookup
    // _and_ ordering for the MozMap, but we don't have one lying
    // around.
    nsTHashtable<nsStringHashKey> idsSeen;
    for (size_t i = 0; i < ids.length(); ++i) {
      curId = ids[i];

      JS::Rooted<mozilla::Maybe<JS::PropertyDescriptor>> desc(cx);
      if (!JS_GetOwnPropertyDescriptorById(cx, recordObj, curId,
                                           &desc)) {
        return false;
      }

      if (desc.isNothing() || !desc->enumerable()) {
        continue;
      }

      idVal = js::IdToValue(curId);
      nsString propName;
      // This will just throw if idVal is a Symbol, like the spec says
      // to do.
      if (!ConvertJSValueToString(cx, idVal, "key of argument 1", propName)) {
        return false;
      }

      if (!JS_GetPropertyById(cx, recordObj, curId, &temp)) {
        return false;
      }

      Record<nsString, OwningNonNull<Promise>>::EntryType* entry;
      if (!idsSeen.EnsureInserted(propName)) {
        // Find the existing entry.
        auto idx = recordEntries.IndexOf(propName);
        MOZ_ASSERT(idx != recordEntries.NoIndex,
                   "Why is it not found?");
        // Now blow it away to make it look like it was just added
        // to the array, because it's not obvious that it's
        // safe to write to its already-initialized mValue via our
        // normal codegen conversions.  For example, the value
        // could be a union and this would change its type, but
        // codegen assumes we won't do that.
        entry = recordEntries.ReconstructElementAt(idx);
      } else {
        // Safe to do an infallible append here, because we did a
        // SetCapacity above to the right capacity.
        entry = recordEntries.AppendElement();
      }
      entry->mKey = propName;
      OwningNonNull<Promise>& slot = entry->mValue;
      { // Scope for our GlobalObject, FastErrorResult, JSAutoRealm,
        // etc.

        JS::Rooted<JSObject*> globalObj(cx);
        globalObj = JS::CurrentGlobalOrNull(cx);
        JSAutoRealm ar(cx, globalObj);
        GlobalObject promiseGlobal(cx, globalObj);
        if (promiseGlobal.Failed()) {
          return false;
        }

        JS::Rooted<JS::Value> valueToResolve(cx, temp);
        if (!JS_WrapValue(cx, &valueToResolve)) {
          return false;
        }
        binding_detail::FastErrorResult promiseRv;
        nsCOMPtr<nsIGlobalObject> global =
          do_QueryInterface(promiseGlobal.GetAsSupports());
        if (!global) {
          promiseRv.Throw(NS_ERROR_UNEXPECTED);
          MOZ_ALWAYS_TRUE(promiseRv.MaybeSetPendingException(cx));
          return false;
        }
        slot = Promise::Resolve(global, cx, valueToResolve,
                                        promiseRv);
        if (promiseRv.MaybeSetPendingException(cx)) {
          return false;
        }
      }
    }
  } else {
    cx.ThrowErrorMessage<MSG_NOT_OBJECT>("Argument 1");
    return false;
  }
  binding_detail::FastClipboardItemOptions 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;
    }
  }
  FastErrorResult rv;
  auto result(StrongOrRawPtr<mozilla::dom::ClipboardItem>(mozilla::dom::ClipboardItem::Constructor(global, Constify(arg0), Constify(arg1), rv)));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "ClipboardItem 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::ClipboardItem>::Depth,
  prototypes::id::ClipboardItem,
  true,
  1,
  "ClipboardItem",
};

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

bool
ConstructorEnabled(JSContext* aCx, JS::Handle<JSObject*> aObj)
{
  return mozilla::dom::IsSecureContextOrObjectIsFromSecureContext(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 = {
  { "ClipboardItem",
    JSCLASS_IS_DOMJSCLASS | JSCLASS_FOREGROUND_FINALIZE | JSCLASS_HAS_RESERVED_SLOTS(2) | JSCLASS_PRESERVES_WRAPPER,
    &sClassOps,
    JS_NULL_CLASS_SPEC,
    &NativeTypeHelpers<mozilla::dom::ClipboardItem>::sClassExtension,
    JS_NULL_OBJECT_OPS
  },
  { prototypes::id::ClipboardItem, 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::ClipboardItem>,
  &sNativePropertyHooks,
  FindAssociatedGlobalForNative<mozilla::dom::ClipboardItem>::Get,
  GetProtoObjectHandle,
  GetCCParticipant<mozilla::dom::ClipboardItem>::Get(),
  nullptr,
  NativeTypeHelpers<mozilla::dom::ClipboardItem>::GetWrapperCache
};
static_assert(1 == DOM_INSTANCE_RESERVED_SLOTS,
              "Must have the right minimal number of reserved slots.");
static_assert(2 >= 2,
              "Must have enough reserved slots.");

bool
Wrap(JSContext* aCx, mozilla::dom::ClipboardItem* aObject, nsWrapperCache* aCache, JS::Handle<JSObject*> aGivenProto, JS::MutableHandle<JSObject*> aReflector)
{
  static_assert(!std::is_base_of_v<NonRefcountedDOMObject, mozilla::dom::ClipboardItem>,
                "Shouldn't have wrappercached things that are not refcounted.");
  static_assert(std::is_same_v<decltype(aObject), mozilla::dom::ClipboardItem*>);
  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::ClipboardItem> 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
ClearCachedTypesValue(mozilla::dom::ClipboardItem* aObject)
{
  JSObject* obj;
  obj = aObject->GetWrapper();
  if (!obj) {
    return;
  }
  JS::SetReservedSlot(obj, (DOM_INSTANCE_RESERVED_SLOTS + 0), JS::UndefinedValue());
  ClearXrayExpandoSlots(RootingCx(), obj, (DOM_EXPANDO_RESERVED_SLOTS + 0));
}

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

  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(),
                              nullptr,
                              "ClipboardItem",
                              ShouldExpose<ClipboardItem_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::ClipboardItem,
                                     &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::ClipboardItem,
                                     &CreateInterfaceObjects,
                                     DefineInterfaceProperty::CheckExposure);
}

} // namespace ClipboardItem_Binding



} // namespace dom


} // namespace mozilla
