Bug 1553001 - Move module APIs out of jsapi.{cpp,h} into js/public/Modules.h and js/src/vm/Modules.cpp for better isolation of module-related APIs. r=arai
authorJeff Walden <jwalden@mit.edu>
Tue, 21 May 2019 00:57:38 +0000
changeset 474650 719664f29265db2a45289862512a3fb40932e7a1
parent 474649 3166a00a4f13f0bca069681a382c0e8af814eb3f
child 474651 b86f55e872014493b2b0534e7d8dd87eeb32acba
push id36042
push userdvarga@mozilla.com
push dateTue, 21 May 2019 04:19:40 +0000
treeherdermozilla-central@ca560ff55451 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersarai
bugs1553001
milestone69.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1553001 - Move module APIs out of jsapi.{cpp,h} into js/public/Modules.h and js/src/vm/Modules.cpp for better isolation of module-related APIs. r=arai Differential Revision: https://phabricator.services.mozilla.com/D31917
dom/base/nsJSUtils.cpp
dom/script/LoadedScript.cpp
dom/script/ScriptLoader.cpp
js/public/Modules.h
js/src/builtin/ModuleObject.cpp
js/src/jsapi.cpp
js/src/jsapi.h
js/src/moz.build
js/src/shell/js.cpp
js/src/vm/Modules.cpp
js/src/vm/Runtime.h
js/src/vm/SelfHosting.cpp
--- a/dom/base/nsJSUtils.cpp
+++ b/dom/base/nsJSUtils.cpp
@@ -10,16 +10,17 @@
  * The goal of the utility functions is to cut down on the size of
  * the generated code itself.
  */
 
 #include "nsJSUtils.h"
 #include "jsapi.h"
 #include "jsfriendapi.h"
 #include "js/CompilationAndEvaluation.h"
+#include "js/Modules.h"  // JS::CompileModule, JS::GetModuleScript, JS::Module{Instantiate,Evaluate}
 #include "js/OffThreadScriptCompilation.h"
 #include "js/SourceText.h"
 #include "nsIScriptContext.h"
 #include "nsIScriptElement.h"
 #include "nsIScriptGlobalObject.h"
 #include "nsIXPConnect.h"
 #include "nsCOMPtr.h"
 #include "nsIScriptSecurityManager.h"
--- a/dom/script/LoadedScript.cpp
+++ b/dom/script/LoadedScript.cpp
@@ -4,16 +4,17 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "LoadedScript.h"
 
 #include "mozilla/HoldDropJSObjects.h"
 
 #include "jsfriendapi.h"
+#include "js/Modules.h"  // JS::{Get,Set}ModulePrivate
 #include "ScriptLoader.h"
 
 namespace mozilla {
 namespace dom {
 
 //////////////////////////////////////////////////////////////
 // LoadedScript
 //////////////////////////////////////////////////////////////
--- a/dom/script/ScriptLoader.cpp
+++ b/dom/script/ScriptLoader.cpp
@@ -11,16 +11,17 @@
 #include "LoadedScript.h"
 #include "ModuleLoadRequest.h"
 
 #include "prsystem.h"
 #include "jsapi.h"
 #include "jsfriendapi.h"
 #include "js/CompilationAndEvaluation.h"
 #include "js/MemoryFunctions.h"
+#include "js/Modules.h"  // JS::CompileModule, JS::FinishDynamicModuleImport, JS::{G,S}etModuleResolveHook, JS::Get{ModulePrivate,ModuleScript,RequestedModule{s,Specifier,SourcePos}}, JS::SetModule{DynamicImport,Metadata}Hook
 #include "js/OffThreadScriptCompilation.h"
 #include "js/Realm.h"
 #include "js/SourceText.h"
 #include "js/Utility.h"
 #include "xpcpublic.h"
 #include "nsCycleCollectionParticipant.h"
 #include "nsIContent.h"
 #include "nsJSUtils.h"
copy from js/src/jsapi.h
copy to js/public/Modules.h
--- a/js/src/jsapi.h
+++ b/js/public/Modules.h
@@ -1,1946 +1,72 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  * vim: set ts=8 sts=2 et sw=2 tw=80:
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-/* JavaScript API. */
-
-#ifndef jsapi_h
-#define jsapi_h
-
-#include "mozilla/AlreadyAddRefed.h"
-#include "mozilla/FloatingPoint.h"
-#include "mozilla/MemoryReporting.h"
-#include "mozilla/Range.h"
-#include "mozilla/RangedPtr.h"
-#include "mozilla/RefPtr.h"
-#include "mozilla/Utf8.h"
-#include "mozilla/Variant.h"
-
-#include <stdarg.h>
-#include <stddef.h>
-#include <stdint.h>
-#include <stdio.h>
-
-#include "jspubtd.h"
-
-#include "js/AllocPolicy.h"
-#include "js/CallArgs.h"
-#include "js/CharacterEncoding.h"
-#include "js/Class.h"
-#include "js/CompileOptions.h"
-#include "js/ErrorReport.h"
-#include "js/GCVector.h"
-#include "js/HashTable.h"
-#include "js/Id.h"
-#include "js/OffThreadScriptCompilation.h"
-#include "js/Principals.h"
-#include "js/PropertyDescriptor.h"
-#include "js/PropertySpec.h"
-#include "js/Realm.h"
-#include "js/RealmOptions.h"
-#include "js/RefCounted.h"
-#include "js/RootingAPI.h"
-#include "js/TracingAPI.h"
-#include "js/Transcoding.h"
-#include "js/UniquePtr.h"
-#include "js/Utility.h"
-#include "js/Value.h"
-#include "js/Vector.h"
-
-/************************************************************************/
-
-struct JSFreeOp;
-struct JSFunctionSpec;
-struct JSPropertySpec;
-
-namespace JS {
-
-template <typename UnitT>
-class SourceText;
-
-class TwoByteChars;
-
-/** AutoValueArray roots an internal fixed-size array of Values. */
-template <size_t N>
-class MOZ_RAII AutoValueArray : public AutoGCRooter {
-  const size_t length_;
-  Value elements_[N];
-
- public:
-  explicit AutoValueArray(JSContext* cx MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
-      : AutoGCRooter(cx, AutoGCRooter::Tag::ValueArray), length_(N) {
-    /* Always initialize in case we GC before assignment. */
-    mozilla::PodArrayZero(elements_);
-    MOZ_GUARD_OBJECT_NOTIFIER_INIT;
-  }
-
-  unsigned length() const { return length_; }
-  const Value* begin() const { return elements_; }
-  Value* begin() { return elements_; }
-
-  HandleValue operator[](unsigned i) const {
-    MOZ_ASSERT(i < N);
-    return HandleValue::fromMarkedLocation(&elements_[i]);
-  }
-  MutableHandleValue operator[](unsigned i) {
-    MOZ_ASSERT(i < N);
-    return MutableHandleValue::fromMarkedLocation(&elements_[i]);
-  }
-
-  MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
-};
+/* JavaScript module (as in, the syntactic construct) operations. */
 
-using ValueVector = JS::GCVector<JS::Value>;
-using IdVector = JS::GCVector<jsid>;
-using ScriptVector = JS::GCVector<JSScript*>;
-using StringVector = JS::GCVector<JSString*>;
-
-/**
- * Custom rooting behavior for internal and external clients.
- */
-class MOZ_RAII JS_PUBLIC_API CustomAutoRooter : private AutoGCRooter {
- public:
-  template <typename CX>
-  explicit CustomAutoRooter(const CX& cx MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
-      : AutoGCRooter(cx, AutoGCRooter::Tag::Custom) {
-    MOZ_GUARD_OBJECT_NOTIFIER_INIT;
-  }
-
-  friend void AutoGCRooter::trace(JSTracer* trc);
-
- protected:
-  virtual ~CustomAutoRooter() {}
-
-  /** Supplied by derived class to trace roots. */
-  virtual void trace(JSTracer* trc) = 0;
-
- private:
-  MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
-};
-
-/** A handle to an array of rooted values. */
-class HandleValueArray {
-  const size_t length_;
-  const Value* const elements_;
-
-  HandleValueArray(size_t len, const Value* elements)
-      : length_(len), elements_(elements) {}
-
- public:
-  explicit HandleValueArray(HandleValue value)
-      : length_(1), elements_(value.address()) {}
-
-  MOZ_IMPLICIT HandleValueArray(const RootedValueVector& values)
-      : length_(values.length()), elements_(values.begin()) {}
-
-  template <size_t N>
-  MOZ_IMPLICIT HandleValueArray(const AutoValueArray<N>& values)
-      : length_(N), elements_(values.begin()) {}
+#ifndef js_Modules_h
+#define js_Modules_h
 
-  /** CallArgs must already be rooted somewhere up the stack. */
-  MOZ_IMPLICIT HandleValueArray(const JS::CallArgs& args)
-      : length_(args.length()), elements_(args.array()) {}
-
-  /** Use with care! Only call this if the data is guaranteed to be marked. */
-  static HandleValueArray fromMarkedLocation(size_t len,
-                                             const Value* elements) {
-    return HandleValueArray(len, elements);
-  }
-
-  static HandleValueArray subarray(const HandleValueArray& values,
-                                   size_t startIndex, size_t len) {
-    MOZ_ASSERT(startIndex + len <= values.length());
-    return HandleValueArray(len, values.begin() + startIndex);
-  }
-
-  static HandleValueArray empty() { return HandleValueArray(0, nullptr); }
-
-  size_t length() const { return length_; }
-  const Value* begin() const { return elements_; }
+#include <stdint.h>  // uint32_t
 
-  HandleValue operator[](size_t i) const {
-    MOZ_ASSERT(i < length_);
-    return HandleValue::fromMarkedLocation(&elements_[i]);
-  }
-};
-
-} /* namespace JS */
-
-/* Callbacks and their arguments. */
-
-/************************************************************************/
-
-typedef bool (*JSInterruptCallback)(JSContext* cx);
-
-/**
- * Callback used to ask the embedding for the cross compartment wrapper handler
- * that implements the desired prolicy for this kind of object in the
- * destination compartment. |obj| is the object to be wrapped. If |existing| is
- * non-nullptr, it will point to an existing wrapper object that should be
- * re-used if possible. |existing| is guaranteed to be a cross-compartment
- * wrapper with a lazily-defined prototype and the correct global. It is
- * guaranteed not to wrap a function.
- */
-typedef JSObject* (*JSWrapObjectCallback)(JSContext* cx,
-                                          JS::HandleObject existing,
-                                          JS::HandleObject obj);
+#include "jstypes.h"  // JS_PUBLIC_API
 
-/**
- * Callback used by the wrap hook to ask the embedding to prepare an object
- * for wrapping in a context. This might include unwrapping other wrappers
- * or even finding a more suitable object for the new compartment.
- */
-typedef void (*JSPreWrapCallback)(JSContext* cx, JS::HandleObject scope,
-                                  JS::HandleObject obj,
-                                  JS::HandleObject objectPassedToWrap,
-                                  JS::MutableHandleObject retObj);
-
-struct JSWrapObjectCallbacks {
-  JSWrapObjectCallback wrap;
-  JSPreWrapCallback preWrap;
-};
-
-typedef void (*JSDestroyCompartmentCallback)(JSFreeOp* fop,
-                                             JS::Compartment* compartment);
-
-typedef size_t (*JSSizeOfIncludingThisCompartmentCallback)(
-    mozilla::MallocSizeOf mallocSizeOf, JS::Compartment* compartment);
-
-/**
- * Callback used by memory reporting to ask the embedder how much memory an
- * external string is keeping alive.  The embedder is expected to return a value
- * that corresponds to the size of the allocation that will be released by the
- * JSStringFinalizer passed to JS_NewExternalString for this string.
- *
- * Implementations of this callback MUST NOT do anything that can cause GC.
- */
-using JSExternalStringSizeofCallback =
-    size_t (*)(JSString* str, mozilla::MallocSizeOf mallocSizeOf);
-
-/**
- * Callback used to intercept JavaScript errors.
- */
-struct JSErrorInterceptor {
-  /**
-   * This method is called whenever an error has been raised from JS code.
-   *
-   * This method MUST be infallible.
-   */
-  virtual void interceptError(JSContext* cx, JS::HandleValue error) = 0;
-};
-
-/************************************************************************/
-
-static MOZ_ALWAYS_INLINE JS::Value JS_NumberValue(double d) {
-  int32_t i;
-  d = JS::CanonicalizeNaN(d);
-  if (mozilla::NumberIsInt32(d, &i)) {
-    return JS::Int32Value(i);
-  }
-  return JS::DoubleValue(d);
-}
-
-/************************************************************************/
-
-JS_PUBLIC_API bool JS_StringHasBeenPinned(JSContext* cx, JSString* str);
-
-/************************************************************************/
-
-/** Microseconds since the epoch, midnight, January 1, 1970 UTC. */
-extern JS_PUBLIC_API int64_t JS_Now(void);
-
-/** Don't want to export data, so provide accessors for non-inline Values. */
-extern JS_PUBLIC_API JS::Value JS_GetNaNValue(JSContext* cx);
-
-extern JS_PUBLIC_API JS::Value JS_GetNegativeInfinityValue(JSContext* cx);
-
-extern JS_PUBLIC_API JS::Value JS_GetPositiveInfinityValue(JSContext* cx);
-
-extern JS_PUBLIC_API JS::Value JS_GetEmptyStringValue(JSContext* cx);
-
-extern JS_PUBLIC_API JSString* JS_GetEmptyString(JSContext* cx);
-
-extern JS_PUBLIC_API bool JS_ValueToObject(JSContext* cx, JS::HandleValue v,
-                                           JS::MutableHandleObject objp);
-
-extern JS_PUBLIC_API JSFunction* JS_ValueToFunction(JSContext* cx,
-                                                    JS::HandleValue v);
-
-extern JS_PUBLIC_API JSFunction* JS_ValueToConstructor(JSContext* cx,
-                                                       JS::HandleValue v);
-
-extern JS_PUBLIC_API JSString* JS_ValueToSource(JSContext* cx,
-                                                JS::Handle<JS::Value> v);
-
-extern JS_PUBLIC_API bool JS_DoubleIsInt32(double d, int32_t* ip);
-
-extern JS_PUBLIC_API JSType JS_TypeOfValue(JSContext* cx,
-                                           JS::Handle<JS::Value> v);
-
-namespace JS {
-
-extern JS_PUBLIC_API const char* InformalValueTypeName(const JS::Value& v);
-
-} /* namespace JS */
+#include "js/CompileOptions.h"  // JS::ReadOnlyCompileOptions
+#include "js/RootingAPI.h"      // JS::{Mutable,}Handle
+#include "js/Value.h"           // JS::Value
 
-/** True iff fun is the global eval function. */
-extern JS_PUBLIC_API bool JS_IsBuiltinEvalFunction(JSFunction* fun);
-
-/** True iff fun is the Function constructor. */
-extern JS_PUBLIC_API bool JS_IsBuiltinFunctionConstructor(JSFunction* fun);
-
-/************************************************************************/
-
-// [SMDOC] Data Structures (JSContext, JSRuntime, Realm, Compartment, Zone)
-//
-// SpiderMonkey uses some data structures that behave a lot like Russian dolls:
-// runtimes contain zones, zones contain compartments, compartments contain
-// realms. Each layer has its own purpose.
-//
-// Realm
-// -----
-// Data associated with a global object. In the browser each frame has its
-// own global/realm.
-//
-// Compartment
-// -----------
-// Security membrane; when an object from compartment A is used in compartment
-// B, a cross-compartment wrapper (a kind of proxy) is used. In the browser each
-// compartment currently contains one global/realm, but we want to change that
-// so each compartment contains multiple same-origin realms (bug 1357862).
-//
-// Zone
-// ----
-// A Zone is a group of compartments that share GC resources (arenas, strings,
-// etc) for memory usage and performance reasons. Zone is the GC unit: the GC
-// can operate on one or more zones at a time. The browser uses roughly one zone
-// per tab.
-//
-// Context
-// -------
-// JSContext represents a thread: there must be exactly one JSContext for each
-// thread running JS/Wasm. Internally, helper threads have their own JSContext.
-//
-// Runtime
-// -------
-// JSRuntime is very similar to JSContext: each runtime belongs to one context
-// (thread), but helper threads don't have their own runtimes (they're shared by
-// all runtimes in the process and use the runtime of the task they're
-// executing).
-
-/*
- * Locking, contexts, and memory allocation.
- *
- * It is important that SpiderMonkey be initialized, and the first context
- * be created, in a single-threaded fashion.  Otherwise the behavior of the
- * library is undefined.
- * See:
- * https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/JSAPI_reference
- */
-
-// Create a new context (and runtime) for this thread.
-extern JS_PUBLIC_API JSContext* JS_NewContext(
-    uint32_t maxbytes, uint32_t maxNurseryBytes = JS::DefaultNurseryBytes,
-    JSRuntime* parentRuntime = nullptr);
-
-// The methods below for controlling the active context in a cooperatively
-// multithreaded runtime are not threadsafe, and the caller must ensure they
-// are called serially if there is a chance for contention between threads.
-
-// Called from the active context for a runtime, yield execution so that
-// this context is no longer active and can no longer use the API.
-extern JS_PUBLIC_API void JS_YieldCooperativeContext(JSContext* cx);
-
-// Called from a context whose runtime has no active context, this thread
-// becomes the active context for that runtime and may use the API.
-extern JS_PUBLIC_API void JS_ResumeCooperativeContext(JSContext* cx);
-
-// Create a new context on this thread for cooperative multithreading in the
-// same runtime as siblingContext. Called on a runtime (as indicated by
-// siblingContet) which has no active context, on success the new context will
-// become the runtime's active context.
-extern JS_PUBLIC_API JSContext* JS_NewCooperativeContext(
-    JSContext* siblingContext);
-
-// Destroy a context allocated with JS_NewContext or JS_NewCooperativeContext.
-// The context must be the current active context in the runtime, and after
-// this call the runtime will have no active context.
-extern JS_PUBLIC_API void JS_DestroyContext(JSContext* cx);
-
-JS_PUBLIC_API void* JS_GetContextPrivate(JSContext* cx);
-
-JS_PUBLIC_API void JS_SetContextPrivate(JSContext* cx, void* data);
-
-extern JS_PUBLIC_API JSRuntime* JS_GetParentRuntime(JSContext* cx);
-
-extern JS_PUBLIC_API JSRuntime* JS_GetRuntime(JSContext* cx);
-
-extern JS_PUBLIC_API void JS_SetFutexCanWait(JSContext* cx);
-
-namespace js {
-
-void AssertHeapIsIdle();
-
-} /* namespace js */
+struct JSContext;
+class JSObject;
+struct JSRuntime;
+class JSString;
 
 namespace JS {
-
-/**
- * Initialize the runtime's self-hosted code. Embeddings should call this
- * exactly once per runtime/context, before the first JS_NewGlobalObject
- * call.
- */
-JS_PUBLIC_API bool InitSelfHostedCode(JSContext* cx);
-
-/**
- * Asserts (in debug and release builds) that `obj` belongs to the current
- * thread's context.
- */
-JS_PUBLIC_API void AssertObjectBelongsToCurrentThread(JSObject* obj);
-
-} /* namespace JS */
-
-extern JS_PUBLIC_API const char* JS_GetImplementationVersion(void);
-
-extern JS_PUBLIC_API void JS_SetDestroyCompartmentCallback(
-    JSContext* cx, JSDestroyCompartmentCallback callback);
-
-extern JS_PUBLIC_API void JS_SetSizeOfIncludingThisCompartmentCallback(
-    JSContext* cx, JSSizeOfIncludingThisCompartmentCallback callback);
-
-extern JS_PUBLIC_API void JS_SetWrapObjectCallbacks(
-    JSContext* cx, const JSWrapObjectCallbacks* callbacks);
-
-extern JS_PUBLIC_API void JS_SetExternalStringSizeofCallback(
-    JSContext* cx, JSExternalStringSizeofCallback callback);
-
-#if defined(NIGHTLY_BUILD)
-
-// Set a callback that will be called whenever an error
-// is thrown in this runtime. This is designed as a mechanism
-// for logging errors. Note that the VM makes no attempt to sanitize
-// the contents of the error (so it may contain private data)
-// or to sort out among errors (so it may not be the error you
-// are interested in or for the component in which you are
-// interested).
-//
-// If the callback sets a new error, this new error
-// will replace the original error.
-//
-// May be `nullptr`.
-extern JS_PUBLIC_API void JS_SetErrorInterceptorCallback(
-    JSRuntime*, JSErrorInterceptor* callback);
-
-extern JS_PUBLIC_API JSErrorInterceptor* JS_GetErrorInterceptorCallback(
-    JSRuntime*);
-
-// Examine a value to determine if it is one of the built-in Error types.
-// If so, return the error type.
-extern JS_PUBLIC_API mozilla::Maybe<JSExnType> JS_GetErrorType(
-    const JS::Value& val);
-
-#endif  // defined(NIGHTLY_BUILD)
-
-extern JS_PUBLIC_API void JS_SetCompartmentPrivate(JS::Compartment* compartment,
-                                                   void* data);
-
-extern JS_PUBLIC_API void* JS_GetCompartmentPrivate(
-    JS::Compartment* compartment);
-
-extern JS_PUBLIC_API void JS_SetZoneUserData(JS::Zone* zone, void* data);
-
-extern JS_PUBLIC_API void* JS_GetZoneUserData(JS::Zone* zone);
-
-extern JS_PUBLIC_API bool JS_WrapObject(JSContext* cx,
-                                        JS::MutableHandleObject objp);
-
-extern JS_PUBLIC_API bool JS_WrapValue(JSContext* cx,
-                                       JS::MutableHandleValue vp);
-
-extern JS_PUBLIC_API JSObject* JS_TransplantObject(JSContext* cx,
-                                                   JS::HandleObject origobj,
-                                                   JS::HandleObject target);
-
-extern JS_PUBLIC_API bool JS_RefreshCrossCompartmentWrappers(
-    JSContext* cx, JS::Handle<JSObject*> obj);
-
-/*
- * At any time, a JSContext has a current (possibly-nullptr) realm.
- * Realms are described in:
- *
- *   developer.mozilla.org/en-US/docs/SpiderMonkey/SpiderMonkey_compartments
- *
- * The current realm of a context may be changed. The preferred way to do
- * this is with JSAutoRealm:
- *
- *   void foo(JSContext* cx, JSObject* obj) {
- *     // in some realm 'r'
- *     {
- *       JSAutoRealm ar(cx, obj);  // constructor enters
- *       // in the realm of 'obj'
- *     }                           // destructor leaves
- *     // back in realm 'r'
- *   }
- *
- * The object passed to JSAutoRealm must *not* be a cross-compartment wrapper,
- * because CCWs are not associated with a single realm.
- *
- * For more complicated uses that don't neatly fit in a C++ stack frame, the
- * realm can be entered and left using separate function calls:
- *
- *   void foo(JSContext* cx, JSObject* obj) {
- *     // in 'oldRealm'
- *     JS::Realm* oldRealm = JS::EnterRealm(cx, obj);
- *     // in the realm of 'obj'
- *     JS::LeaveRealm(cx, oldRealm);
- *     // back in 'oldRealm'
- *   }
- *
- * Note: these calls must still execute in a LIFO manner w.r.t all other
- * enter/leave calls on the context. Furthermore, only the return value of a
- * JS::EnterRealm call may be passed as the 'oldRealm' argument of
- * the corresponding JS::LeaveRealm call.
- *
- * Entering a realm roots the realm and its global object for the lifetime of
- * the JSAutoRealm.
- */
-
-class MOZ_RAII JS_PUBLIC_API JSAutoRealm {
-  JSContext* cx_;
-  JS::Realm* oldRealm_;
-
- public:
-  JSAutoRealm(JSContext* cx, JSObject* target MOZ_GUARD_OBJECT_NOTIFIER_PARAM);
-  JSAutoRealm(JSContext* cx, JSScript* target MOZ_GUARD_OBJECT_NOTIFIER_PARAM);
-  ~JSAutoRealm();
-
-  MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
-};
-
-class MOZ_RAII JS_PUBLIC_API JSAutoNullableRealm {
-  JSContext* cx_;
-  JS::Realm* oldRealm_;
-
- public:
-  explicit JSAutoNullableRealm(
-      JSContext* cx, JSObject* targetOrNull MOZ_GUARD_OBJECT_NOTIFIER_PARAM);
-  ~JSAutoNullableRealm();
-
-  MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
-};
-
-namespace JS {
-
-/** NB: This API is infallible; a nullptr return value does not indicate error.
- *
- * |target| must not be a cross-compartment wrapper because CCWs are not
- * associated with a single realm.
- *
- * Entering a realm roots the realm and its global object until the matching
- * JS::LeaveRealm() call.
- */
-extern JS_PUBLIC_API JS::Realm* EnterRealm(JSContext* cx, JSObject* target);
-
-extern JS_PUBLIC_API void LeaveRealm(JSContext* cx, JS::Realm* oldRealm);
-
-using IterateRealmCallback = void (*)(JSContext* cx, void* data,
-                                      Handle<Realm*> realm);
-
-/**
- * This function calls |realmCallback| on every realm. Beware that there is no
- * guarantee that the realm will survive after the callback returns. Also,
- * barriers are disabled via the TraceSession.
- */
-extern JS_PUBLIC_API void IterateRealms(JSContext* cx, void* data,
-                                        IterateRealmCallback realmCallback);
-
-/**
- * Like IterateRealms, but only call the callback for realms using |principals|.
- */
-extern JS_PUBLIC_API void IterateRealmsWithPrincipals(
-    JSContext* cx, JSPrincipals* principals, void* data,
-    IterateRealmCallback realmCallback);
-
-/**
- * Like IterateRealms, but only iterates realms in |compartment|.
- */
-extern JS_PUBLIC_API void IterateRealmsInCompartment(
-    JSContext* cx, JS::Compartment* compartment, void* data,
-    IterateRealmCallback realmCallback);
-
-}  // namespace JS
-
-/**
- * An enum that JSIterateCompartmentCallback can return to indicate
- * whether to keep iterating.
- */
-namespace JS {
-enum class CompartmentIterResult { KeepGoing, Stop };
+template <typename UnitT>
+class SourceText;
 }  // namespace JS
 
-typedef JS::CompartmentIterResult (*JSIterateCompartmentCallback)(
-    JSContext* cx, void* data, JS::Compartment* compartment);
-
-/**
- * This function calls |compartmentCallback| on every compartment until either
- * all compartments have been iterated or CompartmentIterResult::Stop is
- * returned. Beware that there is no guarantee that the compartment will survive
- * after the callback returns. Also, barriers are disabled via the TraceSession.
- */
-extern JS_PUBLIC_API void JS_IterateCompartments(
-    JSContext* cx, void* data,
-    JSIterateCompartmentCallback compartmentCallback);
-
-/**
- * This function calls |compartmentCallback| on every compartment in the given
- * zone until either all compartments have been iterated or
- * CompartmentIterResult::Stop is returned. Beware that there is no guarantee
- * that the compartment will survive after the callback returns. Also, barriers
- * are disabled via the TraceSession.
- */
-extern JS_PUBLIC_API void JS_IterateCompartmentsInZone(
-    JSContext* cx, JS::Zone* zone, void* data,
-    JSIterateCompartmentCallback compartmentCallback);
-
-/**
- * Mark a jsid after entering a new compartment. Different zones separately
- * mark the ids in a runtime, and this must be used any time an id is obtained
- * from one compartment and then used in another compartment, unless the two
- * compartments are guaranteed to be in the same zone.
- */
-extern JS_PUBLIC_API void JS_MarkCrossZoneId(JSContext* cx, jsid id);
-
-/**
- * If value stores a jsid (an atomized string or symbol), mark that id as for
- * JS_MarkCrossZoneId.
- */
-extern JS_PUBLIC_API void JS_MarkCrossZoneIdValue(JSContext* cx,
-                                                  const JS::Value& value);
-
-/**
- * Resolve id, which must contain either a string or an int, to a standard
- * class name in obj if possible, defining the class's constructor and/or
- * prototype and storing true in *resolved.  If id does not name a standard
- * class or a top-level property induced by initializing a standard class,
- * store false in *resolved and just return true.  Return false on error,
- * as usual for bool result-typed API entry points.
- *
- * This API can be called directly from a global object class's resolve op,
- * to define standard classes lazily. The class should either have an enumerate
- * hook that calls JS_EnumerateStandardClasses, or a newEnumerate hook that
- * calls JS_NewEnumerateStandardClasses. newEnumerate is preferred because it's
- * faster (does not define all standard classes).
- */
-extern JS_PUBLIC_API bool JS_ResolveStandardClass(JSContext* cx,
-                                                  JS::HandleObject obj,
-                                                  JS::HandleId id,
-                                                  bool* resolved);
-
-extern JS_PUBLIC_API bool JS_MayResolveStandardClass(const JSAtomState& names,
-                                                     jsid id,
-                                                     JSObject* maybeObj);
-
-extern JS_PUBLIC_API bool JS_EnumerateStandardClasses(JSContext* cx,
-                                                      JS::HandleObject obj);
-
-/**
- * Fill "properties" with a list of standard class names that have not yet been
- * resolved on "obj".  This can be used as (part of) a newEnumerate class hook
- * on a global.  Already-resolved things are excluded because they might have
- * been deleted by script after being resolved and enumeration considers
- * already-defined properties anyway.
- */
-extern JS_PUBLIC_API bool JS_NewEnumerateStandardClasses(
-    JSContext* cx, JS::HandleObject obj, JS::MutableHandleIdVector properties,
-    bool enumerableOnly);
-
-/**
- * Fill "properties" with a list of standard class names.  This can be used for
- * proxies that want to define behavior that looks like enumerating a global
- * without touching the global itself.
- */
-extern JS_PUBLIC_API bool JS_NewEnumerateStandardClassesIncludingResolved(
-    JSContext* cx, JS::HandleObject obj, JS::MutableHandleIdVector properties,
-    bool enumerableOnly);
-
-extern JS_PUBLIC_API bool JS_GetClassObject(JSContext* cx, JSProtoKey key,
-                                            JS::MutableHandle<JSObject*> objp);
-
-extern JS_PUBLIC_API bool JS_GetClassPrototype(
-    JSContext* cx, JSProtoKey key, JS::MutableHandle<JSObject*> objp);
-
-namespace JS {
-
-/*
- * Determine if the given object is an instance/prototype/constructor for a
- * standard class. If so, return the associated JSProtoKey. If not, return
- * JSProto_Null.
- */
-
-extern JS_PUBLIC_API JSProtoKey IdentifyStandardInstance(JSObject* obj);
-
-extern JS_PUBLIC_API JSProtoKey IdentifyStandardPrototype(JSObject* obj);
-
-extern JS_PUBLIC_API JSProtoKey
-IdentifyStandardInstanceOrPrototype(JSObject* obj);
-
-extern JS_PUBLIC_API JSProtoKey IdentifyStandardConstructor(JSObject* obj);
-
-extern JS_PUBLIC_API void ProtoKeyToId(JSContext* cx, JSProtoKey key,
-                                       JS::MutableHandleId idp);
-
-} /* namespace JS */
-
-extern JS_PUBLIC_API JSProtoKey JS_IdToProtoKey(JSContext* cx, JS::HandleId id);
-
-extern JS_PUBLIC_API bool JS_IsGlobalObject(JSObject* obj);
-
-extern JS_PUBLIC_API JSObject* JS_GlobalLexicalEnvironment(JSObject* obj);
-
-extern JS_PUBLIC_API bool JS_HasExtensibleLexicalEnvironment(JSObject* obj);
-
-extern JS_PUBLIC_API JSObject* JS_ExtensibleLexicalEnvironment(JSObject* obj);
-
-namespace JS {
-
-/**
- * Get the current realm's global. Returns nullptr if no realm has been
- * entered.
- */
-extern JS_PUBLIC_API JSObject* CurrentGlobalOrNull(JSContext* cx);
-
-/**
- * Get the global object associated with an object's realm. The object must not
- * be a cross-compartment wrapper (because CCWs are shared by all realms in the
- * compartment).
- */
-extern JS_PUBLIC_API JSObject* GetNonCCWObjectGlobal(JSObject* obj);
-
-}  // namespace JS
-
-/**
- * Add 'Reflect.parse', a SpiderMonkey extension, to the Reflect object on the
- * given global.
- */
-extern JS_PUBLIC_API bool JS_InitReflectParse(JSContext* cx,
-                                              JS::HandleObject global);
-
-/**
- * Add various profiling-related functions as properties of the given object.
- * Defined in builtin/Profilers.cpp.
- */
-extern JS_PUBLIC_API bool JS_DefineProfilingFunctions(JSContext* cx,
-                                                      JS::HandleObject obj);
-
-/* Defined in vm/Debugger.cpp. */
-extern JS_PUBLIC_API bool JS_DefineDebuggerObject(JSContext* cx,
-                                                  JS::HandleObject obj);
-
-namespace JS {
-
-/**
- * Tell JS engine whether Profile Timeline Recording is enabled or not.
- * If Profile Timeline Recording is enabled, data shown there like stack won't
- * be optimized out.
- * This is global state and not associated with specific runtime or context.
- */
-extern JS_PUBLIC_API void SetProfileTimelineRecordingEnabled(bool enabled);
-
-extern JS_PUBLIC_API bool IsProfileTimelineRecordingEnabled();
-
-}  // namespace JS
-
-#ifdef JS_HAS_CTYPES
-/**
- * Initialize the 'ctypes' object on a global variable 'obj'. The 'ctypes'
- * object will be sealed.
- */
-extern JS_PUBLIC_API bool JS_InitCTypesClass(JSContext* cx,
-                                             JS::HandleObject global);
-
-/**
- * Convert a unicode string 'source' of length 'slen' to the platform native
- * charset, returning a null-terminated string allocated with JS_malloc. On
- * failure, this function should report an error.
- */
-typedef char* (*JSCTypesUnicodeToNativeFun)(JSContext* cx,
-                                            const char16_t* source,
-                                            size_t slen);
-
-/**
- * Set of function pointers that ctypes can use for various internal functions.
- * See JS_SetCTypesCallbacks below. Providing nullptr for a function is safe,
- * and will result in the applicable ctypes functionality not being available.
- */
-struct JSCTypesCallbacks {
-  JSCTypesUnicodeToNativeFun unicodeToNative;
-};
-
-/**
- * Set the callbacks on the provided 'ctypesObj' object. 'callbacks' should be a
- * pointer to static data that exists for the lifetime of 'ctypesObj', but it
- * may safely be altered after calling this function and without having
- * to call this function again.
- */
-extern JS_PUBLIC_API void JS_SetCTypesCallbacks(
-    JSObject* ctypesObj, const JSCTypesCallbacks* callbacks);
-#endif
-
-/*
- * A replacement for MallocAllocPolicy that allocates in the JS heap and adds no
- * extra behaviours.
- *
- * This is currently used for allocating source buffers for parsing. Since these
- * are temporary and will not be freed by GC, the memory is not tracked by the
- * usual accounting.
- */
-class JS_PUBLIC_API JSMallocAllocPolicy : public js::AllocPolicyBase {
- public:
-  void reportAllocOverflow() const {}
-
-  MOZ_MUST_USE bool checkSimulatedOOM() const { return true; }
-};
-
-/**
- * Set the size of the native stack that should not be exceed. To disable
- * stack size checking pass 0.
- *
- * SpiderMonkey allows for a distinction between system code (such as GCs, which
- * may incidentally be triggered by script but are not strictly performed on
- * behalf of such script), trusted script (as determined by
- * JS_SetTrustedPrincipals), and untrusted script. Each kind of code may have a
- * different stack quota, allowing embedders to keep higher-priority machinery
- * running in the face of scripted stack exhaustion by something else.
- *
- * The stack quotas for each kind of code should be monotonically descending,
- * and may be specified with this function. If 0 is passed for a given kind
- * of code, it defaults to the value of the next-highest-priority kind.
- *
- * This function may only be called immediately after the runtime is initialized
- * and before any code is executed and/or interrupts requested.
- */
-extern JS_PUBLIC_API void JS_SetNativeStackQuota(
-    JSContext* cx, size_t systemCodeStackSize,
-    size_t trustedScriptStackSize = 0, size_t untrustedScriptStackSize = 0);
-
-/************************************************************************/
-
-extern JS_PUBLIC_API bool JS_ValueToId(JSContext* cx, JS::HandleValue v,
-                                       JS::MutableHandleId idp);
-
-extern JS_PUBLIC_API bool JS_StringToId(JSContext* cx, JS::HandleString s,
-                                        JS::MutableHandleId idp);
-
-extern JS_PUBLIC_API bool JS_IdToValue(JSContext* cx, jsid id,
-                                       JS::MutableHandle<JS::Value> vp);
-
-namespace JS {
-
-/**
- * Convert obj to a primitive value. On success, store the result in vp and
- * return true.
- *
- * The hint argument must be JSTYPE_STRING, JSTYPE_NUMBER, or
- * JSTYPE_UNDEFINED (no hint).
- *
- * Implements: ES6 7.1.1 ToPrimitive(input, [PreferredType]).
- */
-extern JS_PUBLIC_API bool ToPrimitive(JSContext* cx, JS::HandleObject obj,
-                                      JSType hint, JS::MutableHandleValue vp);
-
-/**
- * If args.get(0) is one of the strings "string", "number", or "default", set
- * result to JSTYPE_STRING, JSTYPE_NUMBER, or JSTYPE_UNDEFINED accordingly and
- * return true. Otherwise, return false with a TypeError pending.
- *
- * This can be useful in implementing a @@toPrimitive method.
- */
-extern JS_PUBLIC_API bool GetFirstArgumentAsTypeHint(JSContext* cx,
-                                                     CallArgs args,
-                                                     JSType* result);
-
-} /* namespace JS */
-
-template <typename T>
-struct JSConstScalarSpec {
-  const char* name;
-  T val;
-};
-
-using JSConstDoubleSpec = JSConstScalarSpec<double>;
-using JSConstIntegerSpec = JSConstScalarSpec<int32_t>;
-
-extern JS_PUBLIC_API JSObject* JS_InitClass(
-    JSContext* cx, JS::HandleObject obj, JS::HandleObject parent_proto,
-    const JSClass* clasp, JSNative constructor, unsigned nargs,
-    const JSPropertySpec* ps, const JSFunctionSpec* fs,
-    const JSPropertySpec* static_ps, const JSFunctionSpec* static_fs);
-
-/**
- * Set up ctor.prototype = proto and proto.constructor = ctor with the
- * right property flags.
- */
-extern JS_PUBLIC_API bool JS_LinkConstructorAndPrototype(
-    JSContext* cx, JS::Handle<JSObject*> ctor, JS::Handle<JSObject*> proto);
-
-extern JS_PUBLIC_API const JSClass* JS_GetClass(JSObject* obj);
-
-extern JS_PUBLIC_API bool JS_InstanceOf(JSContext* cx,
-                                        JS::Handle<JSObject*> obj,
-                                        const JSClass* clasp,
-                                        JS::CallArgs* args);
-
-extern JS_PUBLIC_API bool JS_HasInstance(JSContext* cx,
-                                         JS::Handle<JSObject*> obj,
-                                         JS::Handle<JS::Value> v, bool* bp);
-
-namespace JS {
-
-// Implementation of
-// http://www.ecma-international.org/ecma-262/6.0/#sec-ordinaryhasinstance.  If
-// you're looking for the equivalent of "instanceof", you want JS_HasInstance,
-// not this function.
-extern JS_PUBLIC_API bool OrdinaryHasInstance(JSContext* cx,
-                                              HandleObject objArg,
-                                              HandleValue v, bool* bp);
-
-// Implementation of
-// https://www.ecma-international.org/ecma-262/6.0/#sec-instanceofoperator
-// This is almost identical to JS_HasInstance, except the latter may call a
-// custom hasInstance class op instead of InstanceofOperator.
-extern JS_PUBLIC_API bool InstanceofOperator(JSContext* cx, HandleObject obj,
-                                             HandleValue v, bool* bp);
-
-}  // namespace JS
-
-extern JS_PUBLIC_API void* JS_GetPrivate(JSObject* obj);
-
-extern JS_PUBLIC_API void JS_SetPrivate(JSObject* obj, void* data);
-
-extern JS_PUBLIC_API void* JS_GetInstancePrivate(JSContext* cx,
-                                                 JS::Handle<JSObject*> obj,
-                                                 const JSClass* clasp,
-                                                 JS::CallArgs* args);
-
-extern JS_PUBLIC_API JSObject* JS_GetConstructor(JSContext* cx,
-                                                 JS::Handle<JSObject*> proto);
-
 namespace JS {
 
-/**
- * During global creation, we fire notifications to callbacks registered
- * via the Debugger API. These callbacks are arbitrary script, and can touch
- * the global in arbitrary ways. When that happens, the global should not be
- * in a half-baked state. But this creates a problem for consumers that need
- * to set slots on the global to put it in a consistent state.
- *
- * This API provides a way for consumers to set slots atomically (immediately
- * after the global is created), before any debugger hooks are fired. It's
- * unfortunately on the clunky side, but that's the way the cookie crumbles.
- *
- * If callers have no additional state on the global to set up, they may pass
- * |FireOnNewGlobalHook| to JS_NewGlobalObject, which causes that function to
- * fire the hook as its final act before returning. Otherwise, callers should
- * pass |DontFireOnNewGlobalHook|, which means that they are responsible for
- * invoking JS_FireOnNewGlobalObject upon successfully creating the global. If
- * an error occurs and the operation aborts, callers should skip firing the
- * hook. But otherwise, callers must take care to fire the hook exactly once
- * before compiling any script in the global's scope (we have assertions in
- * place to enforce this). This lets us be sure that debugger clients never miss
- * breakpoints.
- */
-enum OnNewGlobalHookOption { FireOnNewGlobalHook, DontFireOnNewGlobalHook };
-
-} /* namespace JS */
-
-extern JS_PUBLIC_API JSObject* JS_NewGlobalObject(
-    JSContext* cx, const JSClass* clasp, JSPrincipals* principals,
-    JS::OnNewGlobalHookOption hookOption, const JS::RealmOptions& options);
-/**
- * Spidermonkey does not have a good way of keeping track of what compartments
- * should be marked on their own. We can mark the roots unconditionally, but
- * marking GC things only relevant in live compartments is hard. To mitigate
- * this, we create a static trace hook, installed on each global object, from
- * which we can be sure the compartment is relevant, and mark it.
- *
- * It is still possible to specify custom trace hooks for global object classes.
- * They can be provided via the RealmOptions passed to JS_NewGlobalObject.
- */
-extern JS_PUBLIC_API void JS_GlobalObjectTraceHook(JSTracer* trc,
-                                                   JSObject* global);
-
-namespace JS {
-
-/**
- * This allows easily constructing a global object without having to deal with
- * JSClassOps, forgetting to add JS_GlobalObjectTraceHook, or forgetting to call
- * JS::InitRealmStandardClasses(). Example:
- *
- *     const JSClass globalClass = { "MyGlobal", JSCLASS_GLOBAL_FLAGS,
- *         &JS::DefaultGlobalClassOps };
- *     JS_NewGlobalObject(cx, &globalClass, ...);
- */
-extern JS_PUBLIC_DATA const JSClassOps DefaultGlobalClassOps;
-
-}  // namespace JS
-
-extern JS_PUBLIC_API void JS_FireOnNewGlobalObject(JSContext* cx,
-                                                   JS::HandleObject global);
-
-extern JS_PUBLIC_API JSObject* JS_NewObject(JSContext* cx,
-                                            const JSClass* clasp);
-
-extern JS_PUBLIC_API bool JS_IsNative(JSObject* obj);
-
-/**
- * Unlike JS_NewObject, JS_NewObjectWithGivenProto does not compute a default
- * proto. If proto is nullptr, the JS object will have `null` as [[Prototype]].
- */
-extern JS_PUBLIC_API JSObject* JS_NewObjectWithGivenProto(
-    JSContext* cx, const JSClass* clasp, JS::Handle<JSObject*> proto);
-
-/**
- * Creates a new plain object, like `new Object()`, with Object.prototype as
- * [[Prototype]].
- */
-extern JS_PUBLIC_API JSObject* JS_NewPlainObject(JSContext* cx);
-
-/**
- * Freeze obj, and all objects it refers to, recursively. This will not recurse
- * through non-extensible objects, on the assumption that those are already
- * deep-frozen.
- */
-extern JS_PUBLIC_API bool JS_DeepFreezeObject(JSContext* cx,
-                                              JS::Handle<JSObject*> obj);
-
-/**
- * Freezes an object; see ES5's Object.freeze(obj) method.
- */
-extern JS_PUBLIC_API bool JS_FreezeObject(JSContext* cx,
-                                          JS::Handle<JSObject*> obj);
-
-/*** Standard internal methods **********************************************
- *
- * The functions below are the fundamental operations on objects.
- *
- * ES6 specifies 14 internal methods that define how objects behave.  The
- * standard is actually quite good on this topic, though you may have to read
- * it a few times. See ES6 sections 6.1.7.2 and 6.1.7.3.
- *
- * When 'obj' is an ordinary object, these functions have boring standard
- * behavior as specified by ES6 section 9.1; see the section about internal
- * methods in js/src/vm/NativeObject.h.
- *
- * Proxies override the behavior of internal methods. So when 'obj' is a proxy,
- * any one of the functions below could do just about anything. See
- * js/public/Proxy.h.
- */
-
-/**
- * Get the prototype of obj, storing it in result.
- *
- * Implements: ES6 [[GetPrototypeOf]] internal method.
- */
-extern JS_PUBLIC_API bool JS_GetPrototype(JSContext* cx, JS::HandleObject obj,
-                                          JS::MutableHandleObject result);
-
-/**
- * If |obj| (underneath any functionally-transparent wrapper proxies) has as
- * its [[GetPrototypeOf]] trap the ordinary [[GetPrototypeOf]] behavior defined
- * for ordinary objects, set |*isOrdinary = true| and store |obj|'s prototype
- * in |result|.  Otherwise set |*isOrdinary = false|.  In case of error, both
- * outparams have unspecified value.
- */
-extern JS_PUBLIC_API bool JS_GetPrototypeIfOrdinary(
-    JSContext* cx, JS::HandleObject obj, bool* isOrdinary,
-    JS::MutableHandleObject result);
-
-/**
- * Change the prototype of obj.
- *
- * Implements: ES6 [[SetPrototypeOf]] internal method.
- *
- * In cases where ES6 [[SetPrototypeOf]] returns false without an exception,
- * JS_SetPrototype throws a TypeError and returns false.
- *
- * Performance warning: JS_SetPrototype is very bad for performance. It may
- * cause compiled jit-code to be invalidated. It also causes not only obj but
- * all other objects in the same "group" as obj to be permanently deoptimized.
- * It's better to create the object with the right prototype from the start.
- */
-extern JS_PUBLIC_API bool JS_SetPrototype(JSContext* cx, JS::HandleObject obj,
-                                          JS::HandleObject proto);
-
-/**
- * Determine whether obj is extensible. Extensible objects can have new
- * properties defined on them. Inextensible objects can't, and their
- * [[Prototype]] slot is fixed as well.
- *
- * Implements: ES6 [[IsExtensible]] internal method.
- */
-extern JS_PUBLIC_API bool JS_IsExtensible(JSContext* cx, JS::HandleObject obj,
-                                          bool* extensible);
-
-/**
- * Attempt to make |obj| non-extensible.
- *
- * Not all failures are treated as errors. See the comment on
- * JS::ObjectOpResult in js/public/Class.h.
- *
- * Implements: ES6 [[PreventExtensions]] internal method.
- */
-extern JS_PUBLIC_API bool JS_PreventExtensions(JSContext* cx,
-                                               JS::HandleObject obj,
-                                               JS::ObjectOpResult& result);
-
-/**
- * Attempt to make the [[Prototype]] of |obj| immutable, such that any attempt
- * to modify it will fail.  If an error occurs during the attempt, return false
- * (with a pending exception set, depending upon the nature of the error).  If
- * no error occurs, return true with |*succeeded| set to indicate whether the
- * attempt successfully made the [[Prototype]] immutable.
- *
- * This is a nonstandard internal method.
- */
-extern JS_PUBLIC_API bool JS_SetImmutablePrototype(JSContext* cx,
-                                                   JS::HandleObject obj,
-                                                   bool* succeeded);
-
-/**
- * Get a description of one of obj's own properties. If no such property exists
- * on obj, return true with desc.object() set to null.
- *
- * Implements: ES6 [[GetOwnProperty]] internal method.
- */
-extern JS_PUBLIC_API bool JS_GetOwnPropertyDescriptorById(
-    JSContext* cx, JS::HandleObject obj, JS::HandleId id,
-    JS::MutableHandle<JS::PropertyDescriptor> desc);
-
-extern JS_PUBLIC_API bool JS_GetOwnPropertyDescriptor(
-    JSContext* cx, JS::HandleObject obj, const char* name,
-    JS::MutableHandle<JS::PropertyDescriptor> desc);
-
-extern JS_PUBLIC_API bool JS_GetOwnUCPropertyDescriptor(
-    JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen,
-    JS::MutableHandle<JS::PropertyDescriptor> desc);
-
-/**
- * Like JS_GetOwnPropertyDescriptorById, but also searches the prototype chain
- * if no own property is found directly on obj. The object on which the
- * property is found is returned in desc.object(). If the property is not found
- * on the prototype chain, this returns true with desc.object() set to null.
- */
-extern JS_PUBLIC_API bool JS_GetPropertyDescriptorById(
-    JSContext* cx, JS::HandleObject obj, JS::HandleId id,
-    JS::MutableHandle<JS::PropertyDescriptor> desc);
-
-extern JS_PUBLIC_API bool JS_GetPropertyDescriptor(
-    JSContext* cx, JS::HandleObject obj, const char* name,
-    JS::MutableHandle<JS::PropertyDescriptor> desc);
-
-extern JS_PUBLIC_API bool JS_GetUCPropertyDescriptor(
-    JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen,
-    JS::MutableHandle<JS::PropertyDescriptor> desc);
-
-/**
- * Define a property on obj.
- *
- * This function uses JS::ObjectOpResult to indicate conditions that ES6
- * specifies as non-error failures. This is inconvenient at best, so use this
- * function only if you are implementing a proxy handler's defineProperty()
- * method. For all other purposes, use one of the many DefineProperty functions
- * below that throw an exception in all failure cases.
- *
- * Implements: ES6 [[DefineOwnProperty]] internal method.
- */
-extern JS_PUBLIC_API bool JS_DefinePropertyById(
-    JSContext* cx, JS::HandleObject obj, JS::HandleId id,
-    JS::Handle<JS::PropertyDescriptor> desc, JS::ObjectOpResult& result);
-
-/**
- * Define a property on obj, throwing a TypeError if the attempt fails.
- * This is the C++ equivalent of `Object.defineProperty(obj, id, desc)`.
- */
-extern JS_PUBLIC_API bool JS_DefinePropertyById(
-    JSContext* cx, JS::HandleObject obj, JS::HandleId id,
-    JS::Handle<JS::PropertyDescriptor> desc);
-
-extern JS_PUBLIC_API bool JS_DefinePropertyById(JSContext* cx,
-                                                JS::HandleObject obj,
-                                                JS::HandleId id,
-                                                JS::HandleValue value,
-                                                unsigned attrs);
-
-extern JS_PUBLIC_API bool JS_DefinePropertyById(
-    JSContext* cx, JS::HandleObject obj, JS::HandleId id, JSNative getter,
-    JSNative setter, unsigned attrs);
-
-extern JS_PUBLIC_API bool JS_DefinePropertyById(
-    JSContext* cx, JS::HandleObject obj, JS::HandleId id,
-    JS::HandleObject getter, JS::HandleObject setter, unsigned attrs);
-
-extern JS_PUBLIC_API bool JS_DefinePropertyById(JSContext* cx,
-                                                JS::HandleObject obj,
-                                                JS::HandleId id,
-                                                JS::HandleObject value,
-                                                unsigned attrs);
-
-extern JS_PUBLIC_API bool JS_DefinePropertyById(JSContext* cx,
-                                                JS::HandleObject obj,
-                                                JS::HandleId id,
-                                                JS::HandleString value,
-                                                unsigned attrs);
-
-extern JS_PUBLIC_API bool JS_DefinePropertyById(JSContext* cx,
-                                                JS::HandleObject obj,
-                                                JS::HandleId id, int32_t value,
-                                                unsigned attrs);
-
-extern JS_PUBLIC_API bool JS_DefinePropertyById(JSContext* cx,
-                                                JS::HandleObject obj,
-                                                JS::HandleId id, uint32_t value,
-                                                unsigned attrs);
-
-extern JS_PUBLIC_API bool JS_DefinePropertyById(JSContext* cx,
-                                                JS::HandleObject obj,
-                                                JS::HandleId id, double value,
-                                                unsigned attrs);
-
-extern JS_PUBLIC_API bool JS_DefineProperty(JSContext* cx, JS::HandleObject obj,
-                                            const char* name,
-                                            JS::HandleValue value,
-                                            unsigned attrs);
-
-extern JS_PUBLIC_API bool JS_DefineProperty(JSContext* cx, JS::HandleObject obj,
-                                            const char* name, JSNative getter,
-                                            JSNative setter, unsigned attrs);
-
-extern JS_PUBLIC_API bool JS_DefineProperty(JSContext* cx, JS::HandleObject obj,
-                                            const char* name,
-                                            JS::HandleObject getter,
-                                            JS::HandleObject setter,
-                                            unsigned attrs);
-
-extern JS_PUBLIC_API bool JS_DefineProperty(JSContext* cx, JS::HandleObject obj,
-                                            const char* name,
-                                            JS::HandleObject value,
-                                            unsigned attrs);
-
-extern JS_PUBLIC_API bool JS_DefineProperty(JSContext* cx, JS::HandleObject obj,
-                                            const char* name,
-                                            JS::HandleString value,
-                                            unsigned attrs);
-
-extern JS_PUBLIC_API bool JS_DefineProperty(JSContext* cx, JS::HandleObject obj,
-                                            const char* name, int32_t value,
-                                            unsigned attrs);
-
-extern JS_PUBLIC_API bool JS_DefineProperty(JSContext* cx, JS::HandleObject obj,
-                                            const char* name, uint32_t value,
-                                            unsigned attrs);
-
-extern JS_PUBLIC_API bool JS_DefineProperty(JSContext* cx, JS::HandleObject obj,
-                                            const char* name, double value,
-                                            unsigned attrs);
-
-extern JS_PUBLIC_API bool JS_DefineUCProperty(
-    JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen,
-    JS::Handle<JS::PropertyDescriptor> desc, JS::ObjectOpResult& result);
-
-extern JS_PUBLIC_API bool JS_DefineUCProperty(
-    JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen,
-    JS::Handle<JS::PropertyDescriptor> desc);
-
-extern JS_PUBLIC_API bool JS_DefineUCProperty(
-    JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen,
-    JS::HandleValue value, unsigned attrs);
-
-extern JS_PUBLIC_API bool JS_DefineUCProperty(
-    JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen,
-    JS::HandleObject getter, JS::HandleObject setter, unsigned attrs);
-
-extern JS_PUBLIC_API bool JS_DefineUCProperty(
-    JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen,
-    JS::HandleObject value, unsigned attrs);
-
-extern JS_PUBLIC_API bool JS_DefineUCProperty(
-    JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen,
-    JS::HandleString value, unsigned attrs);
-
-extern JS_PUBLIC_API bool JS_DefineUCProperty(JSContext* cx,
-                                              JS::HandleObject obj,
-                                              const char16_t* name,
-                                              size_t namelen, int32_t value,
-                                              unsigned attrs);
-
-extern JS_PUBLIC_API bool JS_DefineUCProperty(JSContext* cx,
-                                              JS::HandleObject obj,
-                                              const char16_t* name,
-                                              size_t namelen, uint32_t value,
-                                              unsigned attrs);
-
-extern JS_PUBLIC_API bool JS_DefineUCProperty(JSContext* cx,
-                                              JS::HandleObject obj,
-                                              const char16_t* name,
-                                              size_t namelen, double value,
-                                              unsigned attrs);
-
-extern JS_PUBLIC_API bool JS_DefineElement(JSContext* cx, JS::HandleObject obj,
-                                           uint32_t index,
-                                           JS::HandleValue value,
-                                           unsigned attrs);
-
-extern JS_PUBLIC_API bool JS_DefineElement(JSContext* cx, JS::HandleObject obj,
-                                           uint32_t index,
-                                           JS::HandleObject getter,
-                                           JS::HandleObject setter,
-                                           unsigned attrs);
-
-extern JS_PUBLIC_API bool JS_DefineElement(JSContext* cx, JS::HandleObject obj,
-                                           uint32_t index,
-                                           JS::HandleObject value,
-                                           unsigned attrs);
-
-extern JS_PUBLIC_API bool JS_DefineElement(JSContext* cx, JS::HandleObject obj,
-                                           uint32_t index,
-                                           JS::HandleString value,
-                                           unsigned attrs);
-
-extern JS_PUBLIC_API bool JS_DefineElement(JSContext* cx, JS::HandleObject obj,
-                                           uint32_t index, int32_t value,
-                                           unsigned attrs);
-
-extern JS_PUBLIC_API bool JS_DefineElement(JSContext* cx, JS::HandleObject obj,
-                                           uint32_t index, uint32_t value,
-                                           unsigned attrs);
-
-extern JS_PUBLIC_API bool JS_DefineElement(JSContext* cx, JS::HandleObject obj,
-                                           uint32_t index, double value,
-                                           unsigned attrs);
-
-/**
- * Compute the expression `id in obj`.
- *
- * If obj has an own or inherited property obj[id], set *foundp = true and
- * return true. If not, set *foundp = false and return true. On error, return
- * false with an exception pending.
- *
- * Implements: ES6 [[Has]] internal method.
- */
-extern JS_PUBLIC_API bool JS_HasPropertyById(JSContext* cx,
-                                             JS::HandleObject obj,
-                                             JS::HandleId id, bool* foundp);
-
-extern JS_PUBLIC_API bool JS_HasProperty(JSContext* cx, JS::HandleObject obj,
-                                         const char* name, bool* foundp);
-
-extern JS_PUBLIC_API bool JS_HasUCProperty(JSContext* cx, JS::HandleObject obj,
-                                           const char16_t* name, size_t namelen,
-                                           bool* vp);
-
-extern JS_PUBLIC_API bool JS_HasElement(JSContext* cx, JS::HandleObject obj,
-                                        uint32_t index, bool* foundp);
-
-/**
- * Determine whether obj has an own property with the key `id`.
- *
- * Implements: ES6 7.3.11 HasOwnProperty(O, P).
- */
-extern JS_PUBLIC_API bool JS_HasOwnPropertyById(JSContext* cx,
-                                                JS::HandleObject obj,
-                                                JS::HandleId id, bool* foundp);
-
-extern JS_PUBLIC_API bool JS_HasOwnProperty(JSContext* cx, JS::HandleObject obj,
-                                            const char* name, bool* foundp);
-
-/**
- * Get the value of the property `obj[id]`, or undefined if no such property
- * exists. This is the C++ equivalent of `vp = Reflect.get(obj, id, receiver)`.
- *
- * Most callers don't need the `receiver` argument. Consider using
- * JS_GetProperty instead. (But if you're implementing a proxy handler's set()
- * method, it's often correct to call this function and pass the receiver
- * through.)
- *
- * Implements: ES6 [[Get]] internal method.
- */
-extern JS_PUBLIC_API bool JS_ForwardGetPropertyTo(JSContext* cx,
-                                                  JS::HandleObject obj,
-                                                  JS::HandleId id,
-                                                  JS::HandleValue receiver,
-                                                  JS::MutableHandleValue vp);
-
-extern JS_PUBLIC_API bool JS_ForwardGetElementTo(JSContext* cx,
-                                                 JS::HandleObject obj,
-                                                 uint32_t index,
-                                                 JS::HandleObject receiver,
-                                                 JS::MutableHandleValue vp);
-
-/**
- * Get the value of the property `obj[id]`, or undefined if no such property
- * exists. The result is stored in vp.
- *
- * Implements: ES6 7.3.1 Get(O, P).
- */
-extern JS_PUBLIC_API bool JS_GetPropertyById(JSContext* cx,
-                                             JS::HandleObject obj,
-                                             JS::HandleId id,
-                                             JS::MutableHandleValue vp);
-
-extern JS_PUBLIC_API bool JS_GetProperty(JSContext* cx, JS::HandleObject obj,
-                                         const char* name,
-                                         JS::MutableHandleValue vp);
-
-extern JS_PUBLIC_API bool JS_GetUCProperty(JSContext* cx, JS::HandleObject obj,
-                                           const char16_t* name, size_t namelen,
-                                           JS::MutableHandleValue vp);
-
-extern JS_PUBLIC_API bool JS_GetElement(JSContext* cx, JS::HandleObject obj,
-                                        uint32_t index,
-                                        JS::MutableHandleValue vp);
-
-/**
- * Perform the same property assignment as `Reflect.set(obj, id, v, receiver)`.
- *
- * This function has a `receiver` argument that most callers don't need.
- * Consider using JS_SetProperty instead.
- *
- * Implements: ES6 [[Set]] internal method.
- */
-extern JS_PUBLIC_API bool JS_ForwardSetPropertyTo(
-    JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleValue v,
-    JS::HandleValue receiver, JS::ObjectOpResult& result);
-
-/**
- * Perform the assignment `obj[id] = v`.
- *
- * This function performs non-strict assignment, so if the property is
- * read-only, nothing happens and no error is thrown.
- */
-extern JS_PUBLIC_API bool JS_SetPropertyById(JSContext* cx,
-                                             JS::HandleObject obj,
-                                             JS::HandleId id,
-                                             JS::HandleValue v);
-
-extern JS_PUBLIC_API bool JS_SetProperty(JSContext* cx, JS::HandleObject obj,
-                                         const char* name, JS::HandleValue v);
-
-extern JS_PUBLIC_API bool JS_SetUCProperty(JSContext* cx, JS::HandleObject obj,
-                                           const char16_t* name, size_t namelen,
-                                           JS::HandleValue v);
-
-extern JS_PUBLIC_API bool JS_SetElement(JSContext* cx, JS::HandleObject obj,
-                                        uint32_t index, JS::HandleValue v);
-
-extern JS_PUBLIC_API bool JS_SetElement(JSContext* cx, JS::HandleObject obj,
-                                        uint32_t index, JS::HandleObject v);
-
-extern JS_PUBLIC_API bool JS_SetElement(JSContext* cx, JS::HandleObject obj,
-                                        uint32_t index, JS::HandleString v);
-
-extern JS_PUBLIC_API bool JS_SetElement(JSContext* cx, JS::HandleObject obj,
-                                        uint32_t index, int32_t v);
-
-extern JS_PUBLIC_API bool JS_SetElement(JSContext* cx, JS::HandleObject obj,
-                                        uint32_t index, uint32_t v);
-
-extern JS_PUBLIC_API bool JS_SetElement(JSContext* cx, JS::HandleObject obj,
-                                        uint32_t index, double v);
-
-/**
- * Delete a property. This is the C++ equivalent of
- * `result = Reflect.deleteProperty(obj, id)`.
- *
- * This function has a `result` out parameter that most callers don't need.
- * Unless you can pass through an ObjectOpResult provided by your caller, it's
- * probably best to use the JS_DeletePropertyById signature with just 3
- * arguments.
- *
- * Implements: ES6 [[Delete]] internal method.
- */
-extern JS_PUBLIC_API bool JS_DeletePropertyById(JSContext* cx,
-                                                JS::HandleObject obj,
-                                                JS::HandleId id,
-                                                JS::ObjectOpResult& result);
-
-extern JS_PUBLIC_API bool JS_DeleteProperty(JSContext* cx, JS::HandleObject obj,
-                                            const char* name,
-                                            JS::ObjectOpResult& result);
-
-extern JS_PUBLIC_API bool JS_DeleteUCProperty(JSContext* cx,
-                                              JS::HandleObject obj,
-                                              const char16_t* name,
-                                              size_t namelen,
-                                              JS::ObjectOpResult& result);
-
-extern JS_PUBLIC_API bool JS_DeleteElement(JSContext* cx, JS::HandleObject obj,
-                                           uint32_t index,
-                                           JS::ObjectOpResult& result);
-
-/**
- * Delete a property, ignoring strict failures. This is the C++ equivalent of
- * the JS `delete obj[id]` in non-strict mode code.
- */
-extern JS_PUBLIC_API bool JS_DeletePropertyById(JSContext* cx,
-                                                JS::HandleObject obj, jsid id);
-
-extern JS_PUBLIC_API bool JS_DeleteProperty(JSContext* cx, JS::HandleObject obj,
-                                            const char* name);
-
-extern JS_PUBLIC_API bool JS_DeleteElement(JSContext* cx, JS::HandleObject obj,
-                                           uint32_t index);
-
-/**
- * Get an array of the non-symbol enumerable properties of obj.
- * This function is roughly equivalent to:
- *
- *     var result = [];
- *     for (key in obj) {
- *         result.push(key);
- *     }
- *     return result;
- *
- * This is the closest thing we currently have to the ES6 [[Enumerate]]
- * internal method.
- *
- * The array of ids returned by JS_Enumerate must be rooted to protect its
- * contents from garbage collection. Use JS::Rooted<JS::IdVector>.
- */
-extern JS_PUBLIC_API bool JS_Enumerate(JSContext* cx, JS::HandleObject obj,
-                                       JS::MutableHandle<JS::IdVector> props);
-
-/**
- * Equivalent to `Object.assign(target, src)`: Copies the properties from the
- * `src` object (which must not be null) to `target` (which also must not be
- * null).
- */
-extern JS_PUBLIC_API bool JS_AssignObject(JSContext* cx,
-                                          JS::HandleObject target,
-                                          JS::HandleObject src);
-
-/*
- * API for determining callability and constructability. [[Call]] and
- * [[Construct]] are internal methods that aren't present on all objects, so it
- * is useful to ask if they are there or not. The standard itself asks these
- * questions routinely.
- */
-namespace JS {
-
-/**
- * Return true if the given object is callable. In ES6 terms, an object is
- * callable if it has a [[Call]] internal method.
- *
- * Implements: ES6 7.2.3 IsCallable(argument).
- *
- * Functions are callable. A scripted proxy or wrapper is callable if its
- * target is callable. Most other objects aren't callable.
- */
-extern JS_PUBLIC_API bool IsCallable(JSObject* obj);
-
-/**
- * Return true if the given object is a constructor. In ES6 terms, an object is
- * a constructor if it has a [[Construct]] internal method. The expression
- * `new obj()` throws a TypeError if obj is not a constructor.
- *
- * Implements: ES6 7.2.4 IsConstructor(argument).
- *
- * JS functions and classes are constructors. Arrow functions and most builtin
- * functions are not. A scripted proxy or wrapper is a constructor if its
- * target is a constructor.
- */
-extern JS_PUBLIC_API bool IsConstructor(JSObject* obj);
-
-} /* namespace JS */
-
-/**
- * Call a function, passing a this-value and arguments. This is the C++
- * equivalent of `rval = Reflect.apply(fun, obj, args)`.
- *
- * Implements: ES6 7.3.12 Call(F, V, [argumentsList]).
- * Use this function to invoke the [[Call]] internal method.
- */
-extern JS_PUBLIC_API bool JS_CallFunctionValue(JSContext* cx,
-                                               JS::HandleObject obj,
-                                               JS::HandleValue fval,
-                                               const JS::HandleValueArray& args,
-                                               JS::MutableHandleValue rval);
-
-extern JS_PUBLIC_API bool JS_CallFunction(JSContext* cx, JS::HandleObject obj,
-                                          JS::HandleFunction fun,
-                                          const JS::HandleValueArray& args,
-                                          JS::MutableHandleValue rval);
-
-/**
- * Perform the method call `rval = obj[name](args)`.
- */
-extern JS_PUBLIC_API bool JS_CallFunctionName(JSContext* cx,
-                                              JS::HandleObject obj,
-                                              const char* name,
-                                              const JS::HandleValueArray& args,
-                                              JS::MutableHandleValue rval);
-
-namespace JS {
-
-static inline bool Call(JSContext* cx, JS::HandleObject thisObj,
-                        JS::HandleFunction fun,
-                        const JS::HandleValueArray& args,
-                        MutableHandleValue rval) {
-  return !!JS_CallFunction(cx, thisObj, fun, args, rval);
-}
-
-static inline bool Call(JSContext* cx, JS::HandleObject thisObj,
-                        JS::HandleValue fun, const JS::HandleValueArray& args,
-                        MutableHandleValue rval) {
-  return !!JS_CallFunctionValue(cx, thisObj, fun, args, rval);
-}
-
-static inline bool Call(JSContext* cx, JS::HandleObject thisObj,
-                        const char* name, const JS::HandleValueArray& args,
-                        MutableHandleValue rval) {
-  return !!JS_CallFunctionName(cx, thisObj, name, args, rval);
-}
-
-extern JS_PUBLIC_API bool Call(JSContext* cx, JS::HandleValue thisv,
-                               JS::HandleValue fun,
-                               const JS::HandleValueArray& args,
-                               MutableHandleValue rval);
-
-static inline bool Call(JSContext* cx, JS::HandleValue thisv,
-                        JS::HandleObject funObj,
-                        const JS::HandleValueArray& args,
-                        MutableHandleValue rval) {
-  MOZ_ASSERT(funObj);
-  JS::RootedValue fun(cx, JS::ObjectValue(*funObj));
-  return Call(cx, thisv, fun, args, rval);
-}
-
-/**
- * Invoke a constructor. This is the C++ equivalent of
- * `rval = Reflect.construct(fun, args, newTarget)`.
- *
- * JS::Construct() takes a `newTarget` argument that most callers don't need.
- * Consider using the four-argument Construct signature instead. (But if you're
- * implementing a subclass or a proxy handler's construct() method, this is the
- * right function to call.)
- *
- * Implements: ES6 7.3.13 Construct(F, [argumentsList], [newTarget]).
- * Use this function to invoke the [[Construct]] internal method.
- */
-extern JS_PUBLIC_API bool Construct(JSContext* cx, JS::HandleValue fun,
-                                    HandleObject newTarget,
-                                    const JS::HandleValueArray& args,
-                                    MutableHandleObject objp);
-
-/**
- * Invoke a constructor. This is the C++ equivalent of
- * `rval = new fun(...args)`.
- *
- * Implements: ES6 7.3.13 Construct(F, [argumentsList], [newTarget]), when
- * newTarget is omitted.
- */
-extern JS_PUBLIC_API bool Construct(JSContext* cx, JS::HandleValue fun,
-                                    const JS::HandleValueArray& args,
-                                    MutableHandleObject objp);
-
-} /* namespace JS */
-
-/**
- * Invoke a constructor, like the JS expression `new ctor(...args)`. Returns
- * the new object, or null on error.
- */
-extern JS_PUBLIC_API JSObject* JS_New(JSContext* cx, JS::HandleObject ctor,
-                                      const JS::HandleValueArray& args);
-
-/*** Other property-defining functions **************************************/
-
-extern JS_PUBLIC_API JSObject* JS_DefineObject(JSContext* cx,
-                                               JS::HandleObject obj,
-                                               const char* name,
-                                               const JSClass* clasp = nullptr,
-                                               unsigned attrs = 0);
-
-extern JS_PUBLIC_API bool JS_DefineConstDoubles(JSContext* cx,
-                                                JS::HandleObject obj,
-                                                const JSConstDoubleSpec* cds);
-
-extern JS_PUBLIC_API bool JS_DefineConstIntegers(JSContext* cx,
-                                                 JS::HandleObject obj,
-                                                 const JSConstIntegerSpec* cis);
-
-extern JS_PUBLIC_API bool JS_DefineProperties(JSContext* cx,
-                                              JS::HandleObject obj,
-                                              const JSPropertySpec* ps);
-
-/* * */
-
-extern JS_PUBLIC_API bool JS_AlreadyHasOwnPropertyById(JSContext* cx,
-                                                       JS::HandleObject obj,
-                                                       JS::HandleId id,
-                                                       bool* foundp);
-
-extern JS_PUBLIC_API bool JS_AlreadyHasOwnProperty(JSContext* cx,
-                                                   JS::HandleObject obj,
-                                                   const char* name,
-                                                   bool* foundp);
-
-extern JS_PUBLIC_API bool JS_AlreadyHasOwnUCProperty(JSContext* cx,
-                                                     JS::HandleObject obj,
-                                                     const char16_t* name,
-                                                     size_t namelen,
-                                                     bool* foundp);
-
-extern JS_PUBLIC_API bool JS_AlreadyHasOwnElement(JSContext* cx,
-                                                  JS::HandleObject obj,
-                                                  uint32_t index, bool* foundp);
-
-extern JS_PUBLIC_API JSObject* JS_NewArrayObject(
-    JSContext* cx, const JS::HandleValueArray& contents);
-
-extern JS_PUBLIC_API JSObject* JS_NewArrayObject(JSContext* cx, size_t length);
-
-/**
- * On success, returns true, setting |*isArray| to true if |value| is an Array
- * object or a wrapper around one, or to false if not.  Returns false on
- * failure.
- *
- * This method returns true with |*isArray == false| when passed an ES6 proxy
- * whose target is an Array, or when passed a revoked proxy.
- */
-extern JS_PUBLIC_API bool JS_IsArrayObject(JSContext* cx, JS::HandleValue value,
-                                           bool* isArray);
-
-/**
- * On success, returns true, setting |*isArray| to true if |obj| is an Array
- * object or a wrapper around one, or to false if not.  Returns false on
- * failure.
- *
- * This method returns true with |*isArray == false| when passed an ES6 proxy
- * whose target is an Array, or when passed a revoked proxy.
- */
-extern JS_PUBLIC_API bool JS_IsArrayObject(JSContext* cx, JS::HandleObject obj,
-                                           bool* isArray);
-
-extern JS_PUBLIC_API bool JS_GetArrayLength(JSContext* cx,
-                                            JS::Handle<JSObject*> obj,
-                                            uint32_t* lengthp);
-
-extern JS_PUBLIC_API bool JS_SetArrayLength(JSContext* cx,
-                                            JS::Handle<JSObject*> obj,
-                                            uint32_t length);
-
-namespace JS {
-
-/**
- * On success, returns true, setting |*isMap| to true if |obj| is a Map object
- * or a wrapper around one, or to false if not.  Returns false on failure.
- *
- * This method returns true with |*isMap == false| when passed an ES6 proxy
- * whose target is a Map, or when passed a revoked proxy.
- */
-extern JS_PUBLIC_API bool IsMapObject(JSContext* cx, JS::HandleObject obj,
-                                      bool* isMap);
-
-/**
- * On success, returns true, setting |*isSet| to true if |obj| is a Set object
- * or a wrapper around one, or to false if not.  Returns false on failure.
- *
- * This method returns true with |*isSet == false| when passed an ES6 proxy
- * whose target is a Set, or when passed a revoked proxy.
- */
-extern JS_PUBLIC_API bool IsSetObject(JSContext* cx, JS::HandleObject obj,
-                                      bool* isSet);
-
-} /* namespace JS */
-
-/**
- * Assign 'undefined' to all of the object's non-reserved slots. Note: this is
- * done for all slots, regardless of the associated property descriptor.
- */
-JS_PUBLIC_API void JS_SetAllNonReservedSlotsToUndefined(JS::HandleObject obj);
-
-extern JS_PUBLIC_API JS::Value JS_GetReservedSlot(JSObject* obj,
-                                                  uint32_t index);
-
-extern JS_PUBLIC_API void JS_SetReservedSlot(JSObject* obj, uint32_t index,
-                                             const JS::Value& v);
-
-/************************************************************************/
-
-/* native that can be called as a ctor */
-static constexpr unsigned JSFUN_CONSTRUCTOR = 0x400;
-
-/* | of all the JSFUN_* flags */
-static constexpr unsigned JSFUN_FLAGS_MASK = 0x400;
-
-static_assert((JSPROP_FLAGS_MASK & JSFUN_FLAGS_MASK) == 0,
-              "JSFUN_* flags do not overlap JSPROP_* flags, because bits from "
-              "the two flag-sets appear in the same flag in some APIs");
-
-/*
- * Functions and scripts.
- */
-extern JS_PUBLIC_API JSFunction* JS_NewFunction(JSContext* cx, JSNative call,
-                                                unsigned nargs, unsigned flags,
-                                                const char* name);
-
-namespace JS {
-
-extern JS_PUBLIC_API JSFunction* GetSelfHostedFunction(
-    JSContext* cx, const char* selfHostedName, HandleId id, unsigned nargs);
-
-/**
- * Create a new function based on the given JSFunctionSpec, *fs.
- * id is the result of a successful call to
- * `PropertySpecNameToPermanentId(cx, fs->name, &id)`.
- *
- * Unlike JS_DefineFunctions, this does not treat fs as an array.
- * *fs must not be JS_FS_END.
- */
-extern JS_PUBLIC_API JSFunction* NewFunctionFromSpec(JSContext* cx,
-                                                     const JSFunctionSpec* fs,
-                                                     HandleId id);
-
-} /* namespace JS */
-
-extern JS_PUBLIC_API JSObject* JS_GetFunctionObject(JSFunction* fun);
-
-/**
- * Return the function's identifier as a JSString, or null if fun is unnamed.
- * The returned string lives as long as fun, so you don't need to root a saved
- * reference to it if fun is well-connected or rooted, and provided you bound
- * the use of the saved reference by fun's lifetime.
- */
-extern JS_PUBLIC_API JSString* JS_GetFunctionId(JSFunction* fun);
-
-/**
- * Return a function's display name. This is the defined name if one was given
- * where the function was defined, or it could be an inferred name by the JS
- * engine in the case that the function was defined to be anonymous. This can
- * still return nullptr if a useful display name could not be inferred. The
- * same restrictions on rooting as those in JS_GetFunctionId apply.
- */
-extern JS_PUBLIC_API JSString* JS_GetFunctionDisplayId(JSFunction* fun);
-
-/*
- * Return the arity of fun, which includes default parameters and rest
- * parameter.  This can be used as `nargs` parameter for other functions.
- */
-extern JS_PUBLIC_API uint16_t JS_GetFunctionArity(JSFunction* fun);
-
-/*
- * Return the length of fun, which is the original value of .length property.
- */
-JS_PUBLIC_API bool JS_GetFunctionLength(JSContext* cx, JS::HandleFunction fun,
-                                        uint16_t* length);
-
-/**
- * Infallible predicate to test whether obj is a function object (faster than
- * comparing obj's class name to "Function", but equivalent unless someone has
- * overwritten the "Function" identifier with a different constructor and then
- * created instances using that constructor that might be passed in as obj).
- */
-extern JS_PUBLIC_API bool JS_ObjectIsFunction(JSObject* obj);
-
-extern JS_PUBLIC_API bool JS_IsNativeFunction(JSObject* funobj, JSNative call);
-
-/** Return whether the given function is a valid constructor. */
-extern JS_PUBLIC_API bool JS_IsConstructor(JSFunction* fun);
-
-extern JS_PUBLIC_API bool JS_DefineFunctions(JSContext* cx,
-                                             JS::Handle<JSObject*> obj,
-                                             const JSFunctionSpec* fs);
-
-extern JS_PUBLIC_API JSFunction* JS_DefineFunction(
-    JSContext* cx, JS::Handle<JSObject*> obj, const char* name, JSNative call,
-    unsigned nargs, unsigned attrs);
-
-extern JS_PUBLIC_API JSFunction* JS_DefineUCFunction(
-    JSContext* cx, JS::Handle<JSObject*> obj, const char16_t* name,
-    size_t namelen, JSNative call, unsigned nargs, unsigned attrs);
-
-extern JS_PUBLIC_API JSFunction* JS_DefineFunctionById(
-    JSContext* cx, JS::Handle<JSObject*> obj, JS::Handle<jsid> id,
-    JSNative call, unsigned nargs, unsigned attrs);
-
-extern JS_PUBLIC_API bool JS_IsFunctionBound(JSFunction* fun);
-
-extern JS_PUBLIC_API JSObject* JS_GetBoundFunctionTarget(JSFunction* fun);
-
-namespace JS {
-
-/**
- * Clone a top-level function into cx's global. This function will dynamically
- * fail if funobj was lexically nested inside some other function.
- */
-extern JS_PUBLIC_API JSObject* CloneFunctionObject(JSContext* cx,
-                                                   HandleObject funobj);
-
-/**
- * As above, but providing an explicit scope chain.  scopeChain must not include
- * the global object on it; that's implicit.  It needs to contain the other
- * objects that should end up on the clone's scope chain.
- */
-extern JS_PUBLIC_API JSObject* CloneFunctionObject(
-    JSContext* cx, HandleObject funobj, HandleObjectVector scopeChain);
-
-}  // namespace JS
-
-extern JS_PUBLIC_API JSObject* JS_GetGlobalFromScript(JSScript* script);
-
-extern JS_PUBLIC_API const char* JS_GetScriptFilename(JSScript* script);
-
-extern JS_PUBLIC_API unsigned JS_GetScriptBaseLineNumber(JSContext* cx,
-                                                         JSScript* script);
-
-extern JS_PUBLIC_API JSScript* JS_GetFunctionScript(JSContext* cx,
-                                                    JS::HandleFunction fun);
-
-extern JS_PUBLIC_API JSString* JS_DecompileScript(JSContext* cx,
-                                                  JS::Handle<JSScript*> script);
-
-extern JS_PUBLIC_API JSString* JS_DecompileFunction(
-    JSContext* cx, JS::Handle<JSFunction*> fun);
-
-namespace JS {
-
-using ModuleResolveHook = JSObject* (*)(JSContext*, HandleValue, HandleString);
+using ModuleResolveHook = JSObject* (*)(JSContext*, Handle<Value>,
+                                        Handle<JSString*>);
 
 /**
  * Get the HostResolveImportedModule hook for the runtime.
  */
 extern JS_PUBLIC_API ModuleResolveHook GetModuleResolveHook(JSRuntime* rt);
 
 /**
  * Set the HostResolveImportedModule hook for the runtime to the given function.
  */
 extern JS_PUBLIC_API void SetModuleResolveHook(JSRuntime* rt,
                                                ModuleResolveHook func);
 
-using ModuleMetadataHook = bool (*)(JSContext*, HandleValue, HandleObject);
+using ModuleMetadataHook = bool (*)(JSContext*, Handle<Value>,
+                                    Handle<JSObject*>);
 
 /**
  * Get the hook for populating the import.meta metadata object.
  */
 extern JS_PUBLIC_API ModuleMetadataHook GetModuleMetadataHook(JSRuntime* rt);
 
 /**
  * Set the hook for populating the import.meta metadata object to the given
  * function.
  */
 extern JS_PUBLIC_API void SetModuleMetadataHook(JSRuntime* rt,
                                                 ModuleMetadataHook func);
 
 using ModuleDynamicImportHook = bool (*)(JSContext* cx,
-                                         HandleValue referencingPrivate,
-                                         HandleString specifier,
-                                         HandleObject promise);
+                                         Handle<Value> referencingPrivate,
+                                         Handle<JSString*> specifier,
+                                         Handle<JSObject*> promise);
 
 /**
  * Get the HostImportModuleDynamically hook for the runtime.
  */
 extern JS_PUBLIC_API ModuleDynamicImportHook
 GetModuleDynamicImportHook(JSRuntime* rt);
 
 /**
@@ -1949,94 +75,61 @@ GetModuleDynamicImportHook(JSRuntime* rt
  *
  * If this hook is not set (or set to nullptr) then the JS engine will throw an
  * exception if dynamic module import is attempted.
  */
 extern JS_PUBLIC_API void SetModuleDynamicImportHook(
     JSRuntime* rt, ModuleDynamicImportHook func);
 
 extern JS_PUBLIC_API bool FinishDynamicModuleImport(
-    JSContext* cx, HandleValue referencingPrivate, HandleString specifier,
-    HandleObject promise);
+    JSContext* cx, Handle<Value> referencingPrivate,
+    Handle<JSString*> specifier, Handle<JSObject*> promise);
 
 /**
  * Parse the given source buffer as a module in the scope of the current global
  * of cx and return a source text module record.
  */
 extern JS_PUBLIC_API bool CompileModule(JSContext* cx,
                                         const ReadOnlyCompileOptions& options,
                                         SourceText<char16_t>& srcBuf,
-                                        JS::MutableHandleObject moduleRecord);
+                                        MutableHandle<JSObject*> moduleRecord);
 
 /**
  * Set a private value associated with a source text module record.
  */
 extern JS_PUBLIC_API void SetModulePrivate(JSObject* module,
-                                           const JS::Value& value);
+                                           const Value& value);
 
 /**
  * Get the private value associated with a source text module record.
  */
-extern JS_PUBLIC_API JS::Value GetModulePrivate(JSObject* module);
-
-/**
- * Set a private value associated with a script. Note that this value is shared
- * by all nested scripts compiled from a single source file.
- */
-extern JS_PUBLIC_API void SetScriptPrivate(JSScript* script,
-                                           const JS::Value& value);
-
-/**
- * Get the private value associated with a script. Note that this value is
- * shared by all nested scripts compiled from a single source file.
- */
-extern JS_PUBLIC_API JS::Value GetScriptPrivate(JSScript* script);
-
-/*
- * Return the private value associated with currently executing script or
- * module, or undefined if there is no such script.
- */
-extern JS_PUBLIC_API JS::Value GetScriptedCallerPrivate(JSContext* cx);
-
-/**
- * Hooks called when references to a script private value are created or
- * destroyed. This allows use of a reference counted object as the
- * script private.
- */
-using ScriptPrivateReferenceHook = void (*)(const JS::Value&);
-
-/**
- * Set the script private finalize hook for the runtime to the given function.
- */
-extern JS_PUBLIC_API void SetScriptPrivateReferenceHooks(
-    JSRuntime* rt, ScriptPrivateReferenceHook addRefHook,
-    ScriptPrivateReferenceHook releaseHook);
+extern JS_PUBLIC_API Value GetModulePrivate(JSObject* module);
 
 /*
  * Perform the ModuleInstantiate operation on the given source text module
  * record.
  *
  * This transitively resolves all module dependencies (calling the
  * HostResolveImportedModule hook) and initializes the environment record for
  * the module.
  */
 extern JS_PUBLIC_API bool ModuleInstantiate(JSContext* cx,
-                                            JS::HandleObject moduleRecord);
+                                            Handle<JSObject*> moduleRecord);
 
 /*
  * Perform the ModuleEvaluate operation on the given source text module record.
  *
  * This does nothing if this module has already been evaluated. Otherwise, it
  * transitively evaluates all dependences of this module and then evaluates this
  * module.
  *
  * ModuleInstantiate must have completed prior to calling this.
  */
 extern JS_PUBLIC_API bool ModuleEvaluate(JSContext* cx,
-                                         JS::HandleObject moduleRecord);
+                                         Handle<JSObject*> moduleRecord);
 
 /*
  * Get a list of the module specifiers used by a source text module
  * record to request importation of modules.
  *
  * The result is a JavaScript array of object values.  To extract the individual
  * values use only JS_GetArrayLength and JS_GetElement with indices 0 to length
  * - 1.
@@ -2045,1289 +138,25 @@ extern JS_PUBLIC_API bool ModuleEvaluate
  *  - moduleSpecifier: the module specifier string
  *  - lineNumber: the line number of the import in the source text
  *  - columnNumber: the column number of the import in the source text
  *
  * These property values can be extracted with GetRequestedModuleSpecifier() and
  * GetRequestedModuleSourcePos()
  */
 extern JS_PUBLIC_API JSObject* GetRequestedModules(
-    JSContext* cx, JS::HandleObject moduleRecord);
+    JSContext* cx, Handle<JSObject*> moduleRecord);
 
 extern JS_PUBLIC_API JSString* GetRequestedModuleSpecifier(
-    JSContext* cx, JS::HandleValue requestedModuleObject);
+    JSContext* cx, Handle<Value> requestedModuleObject);
 
 extern JS_PUBLIC_API void GetRequestedModuleSourcePos(
-    JSContext* cx, JS::HandleValue requestedModuleObject, uint32_t* lineNumber,
+    JSContext* cx, Handle<Value> requestedModuleObject, uint32_t* lineNumber,
     uint32_t* columnNumber);
 
 /*
  * Get the top-level script for a module which has not yet been executed.
  */
-extern JS_PUBLIC_API JSScript* GetModuleScript(JS::HandleObject moduleRecord);
-
-} /* namespace JS */
-
-#if defined(JS_BUILD_BINAST)
-
-namespace JS {
-
-extern JS_PUBLIC_API JSScript* DecodeBinAST(
-    JSContext* cx, const ReadOnlyCompileOptions& options, FILE* file);
-
-extern JS_PUBLIC_API JSScript* DecodeBinAST(
-    JSContext* cx, const ReadOnlyCompileOptions& options, const uint8_t* buf,
-    size_t length);
-
-extern JS_PUBLIC_API bool CanDecodeBinASTOffThread(
-    JSContext* cx, const ReadOnlyCompileOptions& options, size_t length);
-
-extern JS_PUBLIC_API bool DecodeBinASTOffThread(
-    JSContext* cx, const ReadOnlyCompileOptions& options, const uint8_t* buf,
-    size_t length, OffThreadCompileCallback callback, void* callbackData);
-
-extern JS_PUBLIC_API JSScript* FinishOffThreadBinASTDecode(
-    JSContext* cx, OffThreadToken* token);
-
-} /* namespace JS */
-
-#endif /* JS_BUILD_BINAST */
-
-extern JS_PUBLIC_API bool JS_CheckForInterrupt(JSContext* cx);
-
-/*
- * These functions allow setting an interrupt callback that will be called
- * from the JS thread some time after any thread triggered the callback using
- * JS_RequestInterruptCallback(cx).
- *
- * To schedule the GC and for other activities the engine internally triggers
- * interrupt callbacks. The embedding should thus not rely on callbacks being
- * triggered through the external API only.
- *
- * Important note: Additional callbacks can occur inside the callback handler
- * if it re-enters the JS engine. The embedding must ensure that the callback
- * is disconnected before attempting such re-entry.
- */
-extern JS_PUBLIC_API bool JS_AddInterruptCallback(JSContext* cx,
-                                                  JSInterruptCallback callback);
-
-extern JS_PUBLIC_API bool JS_DisableInterruptCallback(JSContext* cx);
-
-extern JS_PUBLIC_API void JS_ResetInterruptCallback(JSContext* cx, bool enable);
-
-extern JS_PUBLIC_API void JS_RequestInterruptCallback(JSContext* cx);
-
-extern JS_PUBLIC_API void JS_RequestInterruptCallbackCanWait(JSContext* cx);
-
-namespace JS {
-
-/**
- * The ConsumeStreamCallback is called from an active JSContext, passing a
- * StreamConsumer that wishes to consume the given host object as a stream of
- * bytes with the given MIME type. On failure, the embedding must report the
- * appropriate error on 'cx'. On success, the embedding must call
- * consumer->consumeChunk() repeatedly on any thread until exactly one of:
- *  - consumeChunk() returns false
- *  - the embedding calls consumer->streamEnd()
- *  - the embedding calls consumer->streamError()
- * before JS_DestroyContext(cx) or JS::ShutdownAsyncTasks(cx) is called.
- *
- * Note: consumeChunk(), streamEnd() and streamError() may be called
- * synchronously by ConsumeStreamCallback.
- *
- * When streamEnd() is called, the embedding may optionally pass an
- * OptimizedEncodingListener*, indicating that there is a cache entry associated
- * with this stream that can store an optimized encoding of the bytes that were
- * just streamed at some point in the future by having SpiderMonkey call
- * storeOptimizedEncoding(). Until the optimized encoding is ready, SpiderMonkey
- * will hold an outstanding refcount to keep the listener alive.
- *
- * After storeOptimizedEncoding() is called, on cache hit, the embedding
- * may call consumeOptimizedEncoding() instead of consumeChunk()/streamEnd().
- * The embedding must ensure that the GetOptimizedEncodingBuildId() (see
- * js/BuildId.h) at the time when an optimized encoding is created is the same
- * as when it is later consumed.
- */
-
-using OptimizedEncodingBytes = js::Vector<uint8_t, 0, js::SystemAllocPolicy>;
-using UniqueOptimizedEncodingBytes = js::UniquePtr<OptimizedEncodingBytes>;
-
-class OptimizedEncodingListener {
- protected:
-  virtual ~OptimizedEncodingListener() {}
-
- public:
-  // SpiderMonkey will hold an outstanding reference count as long as it holds
-  // a pointer to OptimizedEncodingListener.
-  virtual MozExternalRefCountType MOZ_XPCOM_ABI AddRef() = 0;
-  virtual MozExternalRefCountType MOZ_XPCOM_ABI Release() = 0;
-
-  // SpiderMonkey may optionally call storeOptimizedEncoding() after it has
-  // finished processing a streamed resource.
-  virtual void storeOptimizedEncoding(UniqueOptimizedEncodingBytes bytes) = 0;
-};
-
-class JS_PUBLIC_API StreamConsumer {
- protected:
-  // AsyncStreamConsumers are created and destroyed by SpiderMonkey.
-  StreamConsumer() = default;
-  virtual ~StreamConsumer() = default;
-
- public:
-  // Called by the embedding as each chunk of bytes becomes available.
-  // If this function returns 'false', the stream must drop all pointers to
-  // this StreamConsumer.
-  virtual bool consumeChunk(const uint8_t* begin, size_t length) = 0;
-
-  // Called by the embedding when the stream reaches end-of-file, passing the
-  // listener described above.
-  virtual void streamEnd(OptimizedEncodingListener* listener = nullptr) = 0;
-
-  // Called by the embedding when there is an error during streaming. The
-  // given error code should be passed to the ReportStreamErrorCallback on the
-  // main thread to produce the semantically-correct rejection value.
-  virtual void streamError(size_t errorCode) = 0;
-
-  // Called by the embedding *instead of* consumeChunk()/streamEnd() if an
-  // optimized encoding is available from a previous streaming of the same
-  // contents with the same optimized build id.
-  virtual void consumeOptimizedEncoding(const uint8_t* begin,
-                                        size_t length) = 0;
-
-  // Provides optional stream attributes such as base or source mapping URLs.
-  // Necessarily called before consumeChunk(), streamEnd(), streamError() or
-  // consumeOptimizedEncoding(). The caller retains ownership of the strings.
-  virtual void noteResponseURLs(const char* maybeUrl,
-                                const char* maybeSourceMapUrl) = 0;
-};
-
-enum class MimeType { Wasm };
-
-typedef bool (*ConsumeStreamCallback)(JSContext* cx, JS::HandleObject obj,
-                                      MimeType mimeType,
-                                      StreamConsumer* consumer);
-
-typedef void (*ReportStreamErrorCallback)(JSContext* cx, size_t errorCode);
-
-extern JS_PUBLIC_API void InitConsumeStreamCallback(
-    JSContext* cx, ConsumeStreamCallback consume,
-    ReportStreamErrorCallback report);
-
-/**
- * Supply an alternative stack to incorporate into captured SavedFrame
- * backtraces as the imputed caller of asynchronous JavaScript calls, like async
- * function resumptions and DOM callbacks.
- *
- * When one async function awaits the result of another, it's natural to think
- * of that as a sort of function call: just as execution resumes from an
- * ordinary call expression when the callee returns, with the return value
- * providing the value of the call expression, execution resumes from an 'await'
- * expression after the awaited asynchronous function call returns, passing the
- * return value along.
- *
- * Call the two async functions in such a situation the 'awaiter' and the
- * 'awaitee'.
- *
- * As an async function, the awaitee contains 'await' expressions of its own.
- * Whenever it executes after its first 'await', there are never any actual
- * frames on the JavaScript stack under it; its awaiter is certainly not there.
- * An await expression's continuation is invoked as a promise callback, and
- * those are always called directly from the event loop in their own microtick.
- * (Ignore unusual cases like nested event loops.)
- *
- * But because await expressions bear such a strong resemblance to calls (and
- * deliberately so!), it would be unhelpful for stacks captured within the
- * awaitee to be empty; instead, they should present the awaiter as the caller.
- *
- * The AutoSetAsyncStackForNewCalls RAII class supplies a SavedFrame stack to
- * treat as the caller of any JavaScript invocations that occur within its
- * lifetime. Any SavedFrame stack captured during such an invocation uses the
- * SavedFrame passed to the constructor's 'stack' parameter as the 'asyncParent'
- * property of the SavedFrame for the invocation's oldest frame. Its 'parent'
- * property will be null, so stack-walking code can distinguish this
- * awaiter/awaitee transition from an ordinary caller/callee transition.
- *
- * The constructor's 'asyncCause' parameter supplies a string explaining what
- * sort of asynchronous call caused 'stack' to be spliced into the backtrace;
- * for example, async function resumptions use the string "async". This appears
- * as the 'asyncCause' property of the 'asyncParent' SavedFrame.
- *
- * Async callers are distinguished in the string form of a SavedFrame chain by
- * including the 'asyncCause' string in the frame. It appears before the
- * function name, with the two separated by a '*'.
- *
- * Note that, as each compartment has its own set of SavedFrames, the
- * 'asyncParent' may actually point to a copy of 'stack', rather than the exact
- * SavedFrame object passed.
- *
- * The youngest frame of 'stack' is not mutated to take the asyncCause string as
- * its 'asyncCause' property; SavedFrame objects are immutable. Rather, a fresh
- * clone of the frame is created with the needed 'asyncCause' property.
- *
- * The 'kind' argument specifies how aggressively 'stack' supplants any
- * JavaScript frames older than this AutoSetAsyncStackForNewCalls object. If
- * 'kind' is 'EXPLICIT', then all captured SavedFrame chains take on 'stack' as
- * their 'asyncParent' where the chain crosses this object's scope. If 'kind' is
- * 'IMPLICIT', then 'stack' is only included in captured chains if there are no
- * other JavaScript frames on the stack --- that is, only if the stack would
- * otherwise end at that point.
- *
- * AutoSetAsyncStackForNewCalls affects only SavedFrame chains; it does not
- * affect Debugger.Frame or js::FrameIter. SavedFrame chains are used for
- * Error.stack, allocation profiling, Promise debugging, and so on.
- *
- * See also `js/src/doc/SavedFrame/SavedFrame.md` for documentation on async
- * stack frames.
- */
-class MOZ_STACK_CLASS JS_PUBLIC_API AutoSetAsyncStackForNewCalls {
-  JSContext* cx;
-  RootedObject oldAsyncStack;
-  const char* oldAsyncCause;
-  bool oldAsyncCallIsExplicit;
-
- public:
-  enum class AsyncCallKind {
-    // The ordinary kind of call, where we may apply an async
-    // parent if there is no ordinary parent.
-    IMPLICIT,
-    // An explicit async parent, e.g., callFunctionWithAsyncStack,
-    // where we always want to override any ordinary parent.
-    EXPLICIT
-  };
-
-  // The stack parameter cannot be null by design, because it would be
-  // ambiguous whether that would clear any scheduled async stack and make the
-  // normal stack reappear in the new call, or just keep the async stack
-  // already scheduled for the new call, if any.
-  //
-  // asyncCause is owned by the caller and its lifetime must outlive the
-  // lifetime of the AutoSetAsyncStackForNewCalls object. It is strongly
-  // encouraged that asyncCause be a string constant or similar statically
-  // allocated string.
-  AutoSetAsyncStackForNewCalls(JSContext* cx, HandleObject stack,
-                               const char* asyncCause,
-                               AsyncCallKind kind = AsyncCallKind::IMPLICIT);
-  ~AutoSetAsyncStackForNewCalls();
-};
+extern JS_PUBLIC_API JSScript* GetModuleScript(Handle<JSObject*> moduleRecord);
 
 }  // namespace JS
 
-/************************************************************************/
-
-/*
- * Strings.
- *
- * NB: JS_NewUCString takes ownership of bytes on success, avoiding a copy;
- * but on error (signified by null return), it leaves chars owned by the
- * caller. So the caller must free bytes in the error case, if it has no use
- * for them. In contrast, all the JS_New*StringCopy* functions do not take
- * ownership of the character memory passed to them -- they copy it.
- */
-extern JS_PUBLIC_API JSString* JS_NewStringCopyN(JSContext* cx, const char* s,
-                                                 size_t n);
-
-extern JS_PUBLIC_API JSString* JS_NewStringCopyZ(JSContext* cx, const char* s);
-
-extern JS_PUBLIC_API JSString* JS_NewStringCopyUTF8Z(
-    JSContext* cx, const JS::ConstUTF8CharsZ s);
-
-extern JS_PUBLIC_API JSString* JS_NewStringCopyUTF8N(JSContext* cx,
-                                                     const JS::UTF8Chars s);
-
-extern JS_PUBLIC_API JSString* JS_AtomizeAndPinJSString(JSContext* cx,
-                                                        JS::HandleString str);
-
-extern JS_PUBLIC_API JSString* JS_AtomizeStringN(JSContext* cx, const char* s,
-                                                 size_t length);
-
-extern JS_PUBLIC_API JSString* JS_AtomizeString(JSContext* cx, const char* s);
-
-extern JS_PUBLIC_API JSString* JS_AtomizeAndPinStringN(JSContext* cx,
-                                                       const char* s,
-                                                       size_t length);
-
-extern JS_PUBLIC_API JSString* JS_AtomizeAndPinString(JSContext* cx,
-                                                      const char* s);
-
-extern JS_PUBLIC_API JSString* JS_NewLatin1String(
-    JSContext* cx, js::UniquePtr<JS::Latin1Char[], JS::FreePolicy> chars,
-    size_t length);
-
-extern JS_PUBLIC_API JSString* JS_NewUCString(JSContext* cx,
-                                              JS::UniqueTwoByteChars chars,
-                                              size_t length);
-
-extern JS_PUBLIC_API JSString* JS_NewUCStringDontDeflate(
-    JSContext* cx, JS::UniqueTwoByteChars chars, size_t length);
-
-extern JS_PUBLIC_API JSString* JS_NewUCStringCopyN(JSContext* cx,
-                                                   const char16_t* s, size_t n);
-
-extern JS_PUBLIC_API JSString* JS_NewUCStringCopyZ(JSContext* cx,
-                                                   const char16_t* s);
-
-extern JS_PUBLIC_API JSString* JS_AtomizeUCStringN(JSContext* cx,
-                                                   const char16_t* s,
-                                                   size_t length);
-
-extern JS_PUBLIC_API JSString* JS_AtomizeUCString(JSContext* cx,
-                                                  const char16_t* s);
-
-extern JS_PUBLIC_API JSString* JS_AtomizeAndPinUCStringN(JSContext* cx,
-                                                         const char16_t* s,
-                                                         size_t length);
-
-extern JS_PUBLIC_API JSString* JS_AtomizeAndPinUCString(JSContext* cx,
-                                                        const char16_t* s);
-
-extern JS_PUBLIC_API bool JS_CompareStrings(JSContext* cx, JSString* str1,
-                                            JSString* str2, int32_t* result);
-
-extern JS_PUBLIC_API bool JS_StringEqualsAscii(JSContext* cx, JSString* str,
-                                               const char* asciiBytes,
-                                               bool* match);
-
-extern JS_PUBLIC_API size_t JS_PutEscapedString(JSContext* cx, char* buffer,
-                                                size_t size, JSString* str,
-                                                char quote);
-
-/*
- * Extracting string characters and length.
- *
- * While getting the length of a string is infallible, getting the chars can
- * fail. As indicated by the lack of a JSContext parameter, there are two
- * special cases where getting the chars is infallible:
- *
- * The first case is for strings that have been atomized, e.g. directly by
- * JS_AtomizeAndPinString or implicitly because it is stored in a jsid.
- *
- * The second case is "flat" strings that have been explicitly prepared in a
- * fallible context by JS_FlattenString. To catch errors, a separate opaque
- * JSFlatString type is returned by JS_FlattenString and expected by
- * JS_GetFlatStringChars. Note, though, that this is purely a syntactic
- * distinction: the input and output of JS_FlattenString are the same actual
- * GC-thing. If a JSString is known to be flat, JS_ASSERT_STRING_IS_FLAT can be
- * used to make a debug-checked cast. Example:
- *
- *   // in a fallible context
- *   JSFlatString* fstr = JS_FlattenString(cx, str);
- *   if (!fstr) {
- *     return false;
- *   }
- *   MOZ_ASSERT(fstr == JS_ASSERT_STRING_IS_FLAT(str));
- *
- *   // in an infallible context, for the same 'str'
- *   AutoCheckCannotGC nogc;
- *   const char16_t* chars = JS_GetTwoByteFlatStringChars(nogc, fstr)
- *   MOZ_ASSERT(chars);
- *
- * Flat strings and interned strings are always null-terminated, so
- * JS_FlattenString can be used to get a null-terminated string.
- *
- * Additionally, string characters are stored as either Latin1Char (8-bit)
- * or char16_t (16-bit). Clients can use JS_StringHasLatin1Chars and can then
- * call either the Latin1* or TwoByte* functions. Some functions like
- * JS_CopyStringChars and JS_GetStringCharAt accept both Latin1 and TwoByte
- * strings.
- */
-
-extern JS_PUBLIC_API size_t JS_GetStringLength(JSString* str);
-
-extern JS_PUBLIC_API bool JS_StringIsFlat(JSString* str);
-
-/** Returns true iff the string's characters are stored as Latin1. */
-extern JS_PUBLIC_API bool JS_StringHasLatin1Chars(JSString* str);
-
-extern JS_PUBLIC_API const JS::Latin1Char* JS_GetLatin1StringCharsAndLength(
-    JSContext* cx, const JS::AutoRequireNoGC& nogc, JSString* str,
-    size_t* length);
-
-extern JS_PUBLIC_API const char16_t* JS_GetTwoByteStringCharsAndLength(
-    JSContext* cx, const JS::AutoRequireNoGC& nogc, JSString* str,
-    size_t* length);
-
-extern JS_PUBLIC_API bool JS_GetStringCharAt(JSContext* cx, JSString* str,
-                                             size_t index, char16_t* res);
-
-extern JS_PUBLIC_API char16_t JS_GetFlatStringCharAt(JSFlatString* str,
-                                                     size_t index);
-
-extern JS_PUBLIC_API const char16_t* JS_GetTwoByteExternalStringChars(
-    JSString* str);
-
-extern JS_PUBLIC_API bool JS_CopyStringChars(JSContext* cx,
-                                             mozilla::Range<char16_t> dest,
-                                             JSString* str);
-
-extern JS_PUBLIC_API JSFlatString* JS_FlattenString(JSContext* cx,
-                                                    JSString* str);
-
-extern JS_PUBLIC_API const JS::Latin1Char* JS_GetLatin1FlatStringChars(
-    const JS::AutoRequireNoGC& nogc, JSFlatString* str);
-
-extern JS_PUBLIC_API const char16_t* JS_GetTwoByteFlatStringChars(
-    const JS::AutoRequireNoGC& nogc, JSFlatString* str);
-
-static MOZ_ALWAYS_INLINE JSFlatString* JSID_TO_FLAT_STRING(jsid id) {
-  MOZ_ASSERT(JSID_IS_STRING(id));
-  return (JSFlatString*)JSID_TO_STRING(id);
-}
-
-static MOZ_ALWAYS_INLINE JSFlatString* JS_ASSERT_STRING_IS_FLAT(JSString* str) {
-  MOZ_ASSERT(JS_StringIsFlat(str));
-  return (JSFlatString*)str;
-}
-
-static MOZ_ALWAYS_INLINE JSString* JS_FORGET_STRING_FLATNESS(
-    JSFlatString* fstr) {
-  return (JSString*)fstr;
-}
-
-/*
- * Additional APIs that avoid fallibility when given a flat string.
- */
-
-extern JS_PUBLIC_API bool JS_FlatStringEqualsAscii(JSFlatString* str,
-                                                   const char* asciiBytes);
-
-extern JS_PUBLIC_API size_t JS_PutEscapedFlatString(char* buffer, size_t size,
-                                                    JSFlatString* str,
-                                                    char quote);
-
-/**
- * Create a dependent string, i.e., a string that owns no character storage,
- * but that refers to a slice of another string's chars.  Dependent strings
- * are mutable by definition, so the thread safety comments above apply.
- */
-extern JS_PUBLIC_API JSString* JS_NewDependentString(JSContext* cx,
-                                                     JS::HandleString str,
-                                                     size_t start,
-                                                     size_t length);
-
-/**
- * Concatenate two strings, possibly resulting in a rope.
- * See above for thread safety comments.
- */
-extern JS_PUBLIC_API JSString* JS_ConcatStrings(JSContext* cx,
-                                                JS::HandleString left,
-                                                JS::HandleString right);
-
-/**
- * For JS_DecodeBytes, set *dstlenp to the size of the destination buffer before
- * the call; on return, *dstlenp contains the number of characters actually
- * stored. To determine the necessary destination buffer size, make a sizing
- * call that passes nullptr for dst.
- *
- * On errors, the functions report the error. In that case, *dstlenp contains
- * the number of characters or bytes transferred so far.  If cx is nullptr, no
- * error is reported on failure, and the functions simply return false.
- *
- * NB: This function does not store an additional zero byte or char16_t after
- * the transcoded string.
- */
-JS_PUBLIC_API bool JS_DecodeBytes(JSContext* cx, const char* src, size_t srclen,
-                                  char16_t* dst, size_t* dstlenp);
-
-/**
- * Get number of bytes in the string encoding (without accounting for a
- * terminating zero bytes. The function returns (size_t) -1 if the string
- * can not be encoded into bytes and reports an error using cx accordingly.
- */
-JS_PUBLIC_API size_t JS_GetStringEncodingLength(JSContext* cx, JSString* str);
-
-/**
- * Encode string into a buffer. The function does not stores an additional
- * zero byte. The function returns (size_t) -1 if the string can not be
- * encoded into bytes with no error reported. Otherwise it returns the number
- * of bytes that are necessary to encode the string. If that exceeds the
- * length parameter, the string will be cut and only length bytes will be
- * written into the buffer.
- */
-MOZ_MUST_USE JS_PUBLIC_API bool JS_EncodeStringToBuffer(JSContext* cx,
-                                                        JSString* str,
-                                                        char* buffer,
-                                                        size_t length);
-
-namespace JS {
-
-JS_PUBLIC_API bool PropertySpecNameEqualsId(JSPropertySpec::Name name,
-                                            HandleId id);
-
-/**
- * Create a jsid that does not need to be marked for GC.
- *
- * 'name' is a JSPropertySpec::name or JSFunctionSpec::name value. The
- * resulting jsid, on success, is either an interned string or a well-known
- * symbol; either way it is immune to GC so there is no need to visit *idp
- * during GC marking.
- */
-JS_PUBLIC_API bool PropertySpecNameToPermanentId(JSContext* cx,
-                                                 JSPropertySpec::Name name,
-                                                 jsid* idp);
-
-} /* namespace JS */
-
-/************************************************************************/
-
-/*
- * Error reporting.
- *
- * There are four encoding variants for the error reporting API:
- *   UTF-8
- *     JSAPI's default encoding for error handling.  Use this when the encoding
- *     of the error message, format string, and arguments is UTF-8.
- *   ASCII
- *     Equivalent to UTF-8, but also asserts that the error message, format
- *     string, and arguments are all ASCII.  Because ASCII is a subset of UTF-8,
- *     any use of this encoding variant *could* be replaced with use of the
- *     UTF-8 variant.  This variant exists solely to double-check the
- *     developer's assumption that all these strings truly are ASCII, given that
- *     UTF-8 and ASCII strings regrettably have the same C++ type.
- *   UC = UTF-16
- *     Use this when arguments are UTF-16.  The format string must be UTF-8.
- *   Latin1 (planned to be removed)
- *     In this variant, all strings are interpreted byte-for-byte as the
- *     corresponding Unicode codepoint.  This encoding may *safely* be used on
- *     any null-terminated string, regardless of its encoding.  (You shouldn't
- *     *actually* be uncertain, but in the real world, a string's encoding -- if
- *     promised at all -- may be more...aspirational...than reality.)  This
- *     encoding variant will eventually be removed -- work to convert your uses
- *     to UTF-8 as you're able.
- */
-
-namespace JS {
-const uint16_t MaxNumErrorArguments = 10;
-};
-
-/**
- * Report an exception represented by the sprintf-like conversion of format
- * and its arguments.
- */
-extern JS_PUBLIC_API void JS_ReportErrorASCII(JSContext* cx, const char* format,
-                                              ...) MOZ_FORMAT_PRINTF(2, 3);
-
-extern JS_PUBLIC_API void JS_ReportErrorLatin1(JSContext* cx,
-                                               const char* format, ...)
-    MOZ_FORMAT_PRINTF(2, 3);
-
-extern JS_PUBLIC_API void JS_ReportErrorUTF8(JSContext* cx, const char* format,
-                                             ...) MOZ_FORMAT_PRINTF(2, 3);
-
-/*
- * Use an errorNumber to retrieve the format string, args are char*
- */
-extern JS_PUBLIC_API void JS_ReportErrorNumberASCII(
-    JSContext* cx, JSErrorCallback errorCallback, void* userRef,
-    const unsigned errorNumber, ...);
-
-extern JS_PUBLIC_API void JS_ReportErrorNumberASCIIVA(
-    JSContext* cx, JSErrorCallback errorCallback, void* userRef,
-    const unsigned errorNumber, va_list ap);
-
-extern JS_PUBLIC_API void JS_ReportErrorNumberLatin1(
-    JSContext* cx, JSErrorCallback errorCallback, void* userRef,
-    const unsigned errorNumber, ...);
-
-#ifdef va_start
-extern JS_PUBLIC_API void JS_ReportErrorNumberLatin1VA(
-    JSContext* cx, JSErrorCallback errorCallback, void* userRef,
-    const unsigned errorNumber, va_list ap);
-#endif
-
-extern JS_PUBLIC_API void JS_ReportErrorNumberUTF8(
-    JSContext* cx, JSErrorCallback errorCallback, void* userRef,
-    const unsigned errorNumber, ...);
-
-#ifdef va_start
-extern JS_PUBLIC_API void JS_ReportErrorNumberUTF8VA(
-    JSContext* cx, JSErrorCallback errorCallback, void* userRef,
-    const unsigned errorNumber, va_list ap);
-#endif
-
-/*
- * Use an errorNumber to retrieve the format string, args are char16_t*
- */
-extern JS_PUBLIC_API void JS_ReportErrorNumberUC(JSContext* cx,
-                                                 JSErrorCallback errorCallback,
-                                                 void* userRef,
-                                                 const unsigned errorNumber,
-                                                 ...);
-
-extern JS_PUBLIC_API void JS_ReportErrorNumberUCArray(
-    JSContext* cx, JSErrorCallback errorCallback, void* userRef,
-    const unsigned errorNumber, const char16_t** args);
-
-extern JS_PUBLIC_API bool JS_ReportErrorFlagsAndNumberASCII(
-    JSContext* cx, unsigned flags, JSErrorCallback errorCallback, void* userRef,
-    const unsigned errorNumber, ...);
-
-extern JS_PUBLIC_API bool JS_ReportErrorFlagsAndNumberLatin1(
-    JSContext* cx, unsigned flags, JSErrorCallback errorCallback, void* userRef,
-    const unsigned errorNumber, ...);
-
-extern JS_PUBLIC_API bool JS_ReportErrorFlagsAndNumberUTF8(
-    JSContext* cx, unsigned flags, JSErrorCallback errorCallback, void* userRef,
-    const unsigned errorNumber, ...);
-
-extern JS_PUBLIC_API bool JS_ReportErrorFlagsAndNumberUC(
-    JSContext* cx, unsigned flags, JSErrorCallback errorCallback, void* userRef,
-    const unsigned errorNumber, ...);
-
-/**
- * Complain when out of memory.
- */
-extern MOZ_COLD JS_PUBLIC_API void JS_ReportOutOfMemory(JSContext* cx);
-
-/**
- * Complain when an allocation size overflows the maximum supported limit.
- */
-extern JS_PUBLIC_API void JS_ReportAllocationOverflow(JSContext* cx);
-
-namespace JS {
-
-extern JS_PUBLIC_API bool CreateError(
-    JSContext* cx, JSExnType type, HandleObject stack, HandleString fileName,
-    uint32_t lineNumber, uint32_t columnNumber, JSErrorReport* report,
-    HandleString message, MutableHandleValue rval);
-
-/************************************************************************/
-
-/*
- * Weak Maps.
- */
-
-extern JS_PUBLIC_API JSObject* NewWeakMapObject(JSContext* cx);
-
-extern JS_PUBLIC_API bool IsWeakMapObject(JSObject* obj);
-
-extern JS_PUBLIC_API bool GetWeakMapEntry(JSContext* cx,
-                                          JS::HandleObject mapObj,
-                                          JS::HandleObject key,
-                                          JS::MutableHandleValue val);
-
-extern JS_PUBLIC_API bool SetWeakMapEntry(JSContext* cx,
-                                          JS::HandleObject mapObj,
-                                          JS::HandleObject key,
-                                          JS::HandleValue val);
-
-/*
- * Map
- */
-extern JS_PUBLIC_API JSObject* NewMapObject(JSContext* cx);
-
-extern JS_PUBLIC_API uint32_t MapSize(JSContext* cx, HandleObject obj);
-
-extern JS_PUBLIC_API bool MapGet(JSContext* cx, HandleObject obj,
-                                 HandleValue key, MutableHandleValue rval);
-
-extern JS_PUBLIC_API bool MapHas(JSContext* cx, HandleObject obj,
-                                 HandleValue key, bool* rval);
-
-extern JS_PUBLIC_API bool MapSet(JSContext* cx, HandleObject obj,
-                                 HandleValue key, HandleValue val);
-
-extern JS_PUBLIC_API bool MapDelete(JSContext* cx, HandleObject obj,
-                                    HandleValue key, bool* rval);
-
-extern JS_PUBLIC_API bool MapClear(JSContext* cx, HandleObject obj);
-
-extern JS_PUBLIC_API bool MapKeys(JSContext* cx, HandleObject obj,
-                                  MutableHandleValue rval);
-
-extern JS_PUBLIC_API bool MapValues(JSContext* cx, HandleObject obj,
-                                    MutableHandleValue rval);
-
-extern JS_PUBLIC_API bool MapEntries(JSContext* cx, HandleObject obj,
-                                     MutableHandleValue rval);
-
-extern JS_PUBLIC_API bool MapForEach(JSContext* cx, HandleObject obj,
-                                     HandleValue callbackFn,
-                                     HandleValue thisVal);
-
-/*
- * Set
- */
-extern JS_PUBLIC_API JSObject* NewSetObject(JSContext* cx);
-
-extern JS_PUBLIC_API uint32_t SetSize(JSContext* cx, HandleObject obj);
-
-extern JS_PUBLIC_API bool SetHas(JSContext* cx, HandleObject obj,
-                                 HandleValue key, bool* rval);
-
-extern JS_PUBLIC_API bool SetDelete(JSContext* cx, HandleObject obj,
-                                    HandleValue key, bool* rval);
-
-extern JS_PUBLIC_API bool SetAdd(JSContext* cx, HandleObject obj,
-                                 HandleValue key);
-
-extern JS_PUBLIC_API bool SetClear(JSContext* cx, HandleObject obj);
-
-extern JS_PUBLIC_API bool SetKeys(JSContext* cx, HandleObject obj,
-                                  MutableHandleValue rval);
-
-extern JS_PUBLIC_API bool SetValues(JSContext* cx, HandleObject obj,
-                                    MutableHandleValue rval);
-
-extern JS_PUBLIC_API bool SetEntries(JSContext* cx, HandleObject obj,
-                                     MutableHandleValue rval);
-
-extern JS_PUBLIC_API bool SetForEach(JSContext* cx, HandleObject obj,
-                                     HandleValue callbackFn,
-                                     HandleValue thisVal);
-
-} /* namespace JS */
-
-/************************************************************************/
-
-extern JS_PUBLIC_API bool JS_IsExceptionPending(JSContext* cx);
-
-extern JS_PUBLIC_API bool JS_GetPendingException(JSContext* cx,
-                                                 JS::MutableHandleValue vp);
-
-namespace JS {
-
-enum class ExceptionStackBehavior : bool {
-  // Do not capture any stack.
-  DoNotCapture,
-
-  // Capture the current JS stack when setting the exception. It may be
-  // retrieved by JS::GetPendingExceptionStack.
-  Capture
-};
-
-}  // namespace JS
-
-extern JS_PUBLIC_API void JS_SetPendingException(
-    JSContext* cx, JS::HandleValue v,
-    JS::ExceptionStackBehavior behavior = JS::ExceptionStackBehavior::Capture);
-
-extern JS_PUBLIC_API void JS_ClearPendingException(JSContext* cx);
-
-namespace JS {
-
-/**
- * Save and later restore the current exception state of a given JSContext.
- * This is useful for implementing behavior in C++ that's like try/catch
- * or try/finally in JS.
- *
- * Typical usage:
- *
- *     bool ok = JS::Evaluate(cx, ...);
- *     AutoSaveExceptionState savedExc(cx);
- *     ... cleanup that might re-enter JS ...
- *     return ok;
- */
-class JS_PUBLIC_API AutoSaveExceptionState {
- private:
-  JSContext* context;
-  bool wasPropagatingForcedReturn;
-  bool wasOverRecursed;
-  bool wasThrowing;
-  RootedValue exceptionValue;
-  RootedObject exceptionStack;
-
- public:
-  /*
-   * Take a snapshot of cx's current exception state. Then clear any current
-   * pending exception in cx.
-   */
-  explicit AutoSaveExceptionState(JSContext* cx);
-
-  /*
-   * If neither drop() nor restore() was called, restore the exception
-   * state only if no exception is currently pending on cx.
-   */
-  ~AutoSaveExceptionState();
-
-  /*
-   * Discard any stored exception state.
-   * If this is called, the destructor is a no-op.
-   */
-  void drop();
-
-  /*
-   * Replace cx's exception state with the stored exception state. Then
-   * discard the stored exception state. If this is called, the
-   * destructor is a no-op.
-   */
-  void restore();
-};
-
-// Set both the exception and its associated stack on the context. The stack
-// must be a SavedFrame.
-JS_PUBLIC_API void SetPendingExceptionAndStack(JSContext* cx, HandleValue value,
-                                               HandleObject stack);
-
-/**
- * Get the SavedFrame stack object captured when the pending exception was set
- * on the JSContext. This fuzzily correlates with a `throw` statement in JS,
- * although arbitrary JSAPI consumers or VM code may also set pending exceptions
- * via `JS_SetPendingException`.
- *
- * This is not the same stack as `e.stack` when `e` is an `Error` object. (That
- * would be JS::ExceptionStackOrNull).
- */
-MOZ_MUST_USE JS_PUBLIC_API JSObject* GetPendingExceptionStack(JSContext* cx);
-
-} /* namespace JS */
-
-/* Deprecated API. Use AutoSaveExceptionState instead. */
-extern JS_PUBLIC_API JSExceptionState* JS_SaveExceptionState(JSContext* cx);
-
-extern JS_PUBLIC_API void JS_RestoreExceptionState(JSContext* cx,
-                                                   JSExceptionState* state);
-
-extern JS_PUBLIC_API void JS_DropExceptionState(JSContext* cx,
-                                                JSExceptionState* state);
-
-/**
- * If the given object is an exception object, the exception will have (or be
- * able to lazily create) an error report struct, and this function will return
- * the address of that struct.  Otherwise, it returns nullptr. The lifetime
- * of the error report struct that might be returned is the same as the
- * lifetime of the exception object.
- */
-extern JS_PUBLIC_API JSErrorReport* JS_ErrorFromException(JSContext* cx,
-                                                          JS::HandleObject obj);
-
-namespace JS {
-/**
- * If the given object is an exception object (or an unwrappable
- * cross-compartment wrapper for one), return the stack for that exception, if
- * any.  Will return null if the given object is not an exception object
- * (including if it's null or a security wrapper that can't be unwrapped) or if
- * the exception has no stack.
- */
-extern JS_PUBLIC_API JSObject* ExceptionStackOrNull(JS::HandleObject obj);
-
-/**
- * If this process is recording or replaying and the given value is an
- * exception object (or an unwrappable cross-compartment wrapper for one),
- * return the point where this exception was thrown, for time warping later.
- * Returns zero otherwise.
- */
-extern JS_PUBLIC_API uint64_t ExceptionTimeWarpTarget(JS::HandleValue exn);
-
-} /* namespace JS */
-
-/**
- * A JS context always has an "owner thread". The owner thread is set when the
- * context is created (to the current thread) and practically all entry points
- * into the JS engine check that a context (or anything contained in the
- * context: runtime, compartment, object, etc) is only touched by its owner
- * thread. Embeddings may check this invariant outside the JS engine by calling
- * JS_AbortIfWrongThread (which will abort if not on the owner thread, even for
- * non-debug builds).
- */
-
-extern JS_PUBLIC_API void JS_AbortIfWrongThread(JSContext* cx);
-
-/************************************************************************/
-
-/**
- * A constructor can request that the JS engine create a default new 'this'
- * object of the given class, using the callee to determine parentage and
- * [[Prototype]].
- */
-extern JS_PUBLIC_API JSObject* JS_NewObjectForConstructor(
-    JSContext* cx, const JSClass* clasp, const JS::CallArgs& args);
-
-/************************************************************************/
-
-#ifdef JS_GC_ZEAL
-#  define JS_DEFAULT_ZEAL_FREQ 100
-
-extern JS_PUBLIC_API void JS_GetGCZealBits(JSContext* cx, uint32_t* zealBits,
-                                           uint32_t* frequency,
-                                           uint32_t* nextScheduled);
-
-extern JS_PUBLIC_API void JS_SetGCZeal(JSContext* cx, uint8_t zeal,
-                                       uint32_t frequency);
-
-extern JS_PUBLIC_API void JS_UnsetGCZeal(JSContext* cx, uint8_t zeal);
-
-extern JS_PUBLIC_API void JS_ScheduleGC(JSContext* cx, uint32_t count);
-#endif
-
-extern JS_PUBLIC_API void JS_SetParallelParsingEnabled(JSContext* cx,
-                                                       bool enabled);
-
-extern JS_PUBLIC_API void JS_SetOffthreadIonCompilationEnabled(JSContext* cx,
-                                                               bool enabled);
-
-// clang-format off
-#define JIT_COMPILER_OPTIONS(Register) \
-  Register(BASELINE_WARMUP_TRIGGER, "baseline.warmup.trigger") \
-  Register(ION_NORMAL_WARMUP_TRIGGER, "ion.warmup.trigger") \
-  Register(ION_FULL_WARMUP_TRIGGER, "ion.full.warmup.trigger") \
-  Register(ION_GVN_ENABLE, "ion.gvn.enable") \
-  Register(ION_FORCE_IC, "ion.forceinlineCaches") \
-  Register(ION_ENABLE, "ion.enable") \
-  Register(ION_CHECK_RANGE_ANALYSIS, "ion.check-range-analysis") \
-  Register(ION_FREQUENT_BAILOUT_THRESHOLD, "ion.frequent-bailout-threshold") \
-  Register(BASELINE_ENABLE, "baseline.enable") \
-  Register(OFFTHREAD_COMPILATION_ENABLE, "offthread-compilation.enable") \
-  Register(FULL_DEBUG_CHECKS, "jit.full-debug-checks") \
-  Register(JUMP_THRESHOLD, "jump-threshold") \
-  Register(TRACK_OPTIMIZATIONS, "jit.track-optimizations")\
-  Register(UNBOXED_OBJECTS, "unboxed_objects") \
-  Register(SIMULATOR_ALWAYS_INTERRUPT, "simulator.always-interrupt") \
-  Register(SPECTRE_INDEX_MASKING, "spectre.index-masking") \
-  Register(SPECTRE_OBJECT_MITIGATIONS_BARRIERS, "spectre.object-mitigations.barriers") \
-  Register(SPECTRE_OBJECT_MITIGATIONS_MISC, "spectre.object-mitigations.misc") \
-  Register(SPECTRE_STRING_MITIGATIONS, "spectre.string-mitigations") \
-  Register(SPECTRE_VALUE_MASKING, "spectre.value-masking") \
-  Register(SPECTRE_JIT_TO_CXX_CALLS, "spectre.jit-to-C++-calls") \
-  Register(WASM_FOLD_OFFSETS, "wasm.fold-offsets") \
-  Register(WASM_DELAY_TIER2, "wasm.delay-tier2")
-// clang-format on
-
-typedef enum JSJitCompilerOption {
-#define JIT_COMPILER_DECLARE(key, str) JSJITCOMPILER_##key,
-
-  JIT_COMPILER_OPTIONS(JIT_COMPILER_DECLARE)
-#undef JIT_COMPILER_DECLARE
-
-      JSJITCOMPILER_NOT_AN_OPTION
-} JSJitCompilerOption;
-
-extern JS_PUBLIC_API void JS_SetGlobalJitCompilerOption(JSContext* cx,
-                                                        JSJitCompilerOption opt,
-                                                        uint32_t value);
-extern JS_PUBLIC_API bool JS_GetGlobalJitCompilerOption(JSContext* cx,
-                                                        JSJitCompilerOption opt,
-                                                        uint32_t* valueOut);
-
-/**
- * Convert a uint32_t index into a jsid.
- */
-extern JS_PUBLIC_API bool JS_IndexToId(JSContext* cx, uint32_t index,
-                                       JS::MutableHandleId);
-
-/**
- * Convert chars into a jsid.
- *
- * |chars| may not be an index.
- */
-extern JS_PUBLIC_API bool JS_CharsToId(JSContext* cx, JS::TwoByteChars chars,
-                                       JS::MutableHandleId);
-
-/**
- *  Test if the given string is a valid ECMAScript identifier
- */
-extern JS_PUBLIC_API bool JS_IsIdentifier(JSContext* cx, JS::HandleString str,
-                                          bool* isIdentifier);
-
-/**
- * Test whether the given chars + length are a valid ECMAScript identifier.
- * This version is infallible, so just returns whether the chars are an
- * identifier.
- */
-extern JS_PUBLIC_API bool JS_IsIdentifier(const char16_t* chars, size_t length);
-
-namespace js {
-class ScriptSource;
-}  // namespace js
-
-namespace JS {
-
-class MOZ_RAII JS_PUBLIC_API AutoFilename {
- private:
-  js::ScriptSource* ss_;
-  mozilla::Variant<const char*, UniqueChars> filename_;
-
-  AutoFilename(const AutoFilename&) = delete;
-  AutoFilename& operator=(const AutoFilename&) = delete;
-
- public:
-  AutoFilename()
-      : ss_(nullptr), filename_(mozilla::AsVariant<const char*>(nullptr)) {}
-
-  ~AutoFilename() { reset(); }
-
-  void reset();
-
-  void setOwned(UniqueChars&& filename);
-  void setUnowned(const char* filename);
-  void setScriptSource(js::ScriptSource* ss);
-
-  const char* get() const;
-};
-
-/**
- * Return the current filename, line number and column number of the most
- * currently running frame. Returns true if a scripted frame was found, false
- * otherwise.
- *
- * If a the embedding has hidden the scripted caller for the topmost activation
- * record, this will also return false.
- */
-extern JS_PUBLIC_API bool DescribeScriptedCaller(
-    JSContext* cx, AutoFilename* filename = nullptr, unsigned* lineno = nullptr,
-    unsigned* column = nullptr);
-
-extern JS_PUBLIC_API JSObject* GetScriptedCallerGlobal(JSContext* cx);
-
-/**
- * Informs the JS engine that the scripted caller should be hidden. This can be
- * used by the embedding to maintain an override of the scripted caller in its
- * calculations, by hiding the scripted caller in the JS engine and pushing data
- * onto a separate stack, which it inspects when DescribeScriptedCaller returns
- * null.
- *
- * We maintain a counter on each activation record. Add() increments the counter
- * of the topmost activation, and Remove() decrements it. The count may never
- * drop below zero, and must always be exactly zero when the activation is
- * popped from the stack.
- */
-extern JS_PUBLIC_API void HideScriptedCaller(JSContext* cx);
-
-extern JS_PUBLIC_API void UnhideScriptedCaller(JSContext* cx);
-
-class MOZ_RAII AutoHideScriptedCaller {
- public:
-  explicit AutoHideScriptedCaller(JSContext* cx MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
-      : mContext(cx) {
-    MOZ_GUARD_OBJECT_NOTIFIER_INIT;
-    HideScriptedCaller(mContext);
-  }
-  ~AutoHideScriptedCaller() { UnhideScriptedCaller(mContext); }
-
- protected:
-  JSContext* mContext;
-  MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
-};
-
-} /* namespace JS */
-
-namespace js {
-
-enum class StackFormat { SpiderMonkey, V8, Default };
-
-/*
- * Sets the format used for stringifying Error stacks.
- *
- * The default format is StackFormat::SpiderMonkey.  Use StackFormat::V8
- * in order to emulate V8's stack formatting.  StackFormat::Default can't be
- * used here.
- */
-extern JS_PUBLIC_API void SetStackFormat(JSContext* cx, StackFormat format);
-
-extern JS_PUBLIC_API StackFormat GetStackFormat(JSContext* cx);
-
-}  // namespace js
-
-namespace JS {
-
-/**
- * The WasmModule interface allows the embedding to hold a reference to the
- * underying C++ implementation of a JS WebAssembly.Module object for purposes
- * of efficient postMessage() and (de)serialization from a random thread.
- *
- * In particular, this allows postMessage() of a WebAssembly.Module:
- * GetWasmModule() is called when making a structured clone of a payload
- * containing a WebAssembly.Module object. The structured clone buffer holds a
- * refcount of the JS::WasmModule until createObject() is called in the target
- * agent's JSContext. The new WebAssembly.Module object continues to hold the
- * JS::WasmModule and thus the final reference of a JS::WasmModule may be
- * dropped from any thread and so the virtual destructor (and all internal
- * methods of the C++ module) must be thread-safe.
- */
-
-struct WasmModule : js::AtomicRefCounted<WasmModule> {
-  virtual ~WasmModule() {}
-  virtual JSObject* createObject(JSContext* cx) = 0;
-};
-
-extern JS_PUBLIC_API bool IsWasmModuleObject(HandleObject obj);
-
-extern JS_PUBLIC_API RefPtr<WasmModule> GetWasmModule(HandleObject obj);
-
-/**
- * This function will be removed when bug 1487479 expunges the last remaining
- * bits of wasm IDB support.
- */
-
-extern JS_PUBLIC_API RefPtr<WasmModule> DeserializeWasmModule(
-    PRFileDesc* bytecode, JS::UniqueChars filename, unsigned line);
-
-/**
- * If a large allocation fails when calling pod_{calloc,realloc}CanGC, the JS
- * engine may call the large-allocation-failure callback, if set, to allow the
- * embedding to flush caches, possibly perform shrinking GCs, etc. to make some
- * room. The allocation will then be retried (and may still fail.) This callback
- * can be called on any thread and must be set at most once in a process.
- */
-
-typedef void (*LargeAllocationFailureCallback)();
-
-extern JS_PUBLIC_API void SetProcessLargeAllocationFailureCallback(
-    LargeAllocationFailureCallback afc);
-
-/**
- * Unlike the error reporter, which is only called if the exception for an OOM
- * bubbles up and is not caught, the OutOfMemoryCallback is called immediately
- * at the OOM site to allow the embedding to capture the current state of heap
- * allocation before anything is freed. If the large-allocation-failure callback
- * is called at all (not all allocation sites call the large-allocation-failure
- * callback on failure), it is called before the out-of-memory callback; the
- * out-of-memory callback is only called if the allocation still fails after the
- * large-allocation-failure callback has returned.
- */
-
-typedef void (*OutOfMemoryCallback)(JSContext* cx, void* data);
-
-extern JS_PUBLIC_API void SetOutOfMemoryCallback(JSContext* cx,
-                                                 OutOfMemoryCallback cb,
-                                                 void* data);
-
-/**
- * Capture all frames.
- */
-struct AllFrames {};
-
-/**
- * Capture at most this many frames.
- */
-struct MaxFrames {
-  uint32_t maxFrames;
-
-  explicit MaxFrames(uint32_t max) : maxFrames(max) { MOZ_ASSERT(max > 0); }
-};
-
-/**
- * Capture the first frame with the given principals. By default, do not
- * consider self-hosted frames with the given principals as satisfying the stack
- * capture.
- */
-struct JS_PUBLIC_API FirstSubsumedFrame {
-  JSContext* cx;
-  JSPrincipals* principals;
-  bool ignoreSelfHosted;
-
-  /**
-   * Use the cx's current compartment's principals.
-   */
-  explicit FirstSubsumedFrame(JSContext* cx,
-                              bool ignoreSelfHostedFrames = true);
-
-  explicit FirstSubsumedFrame(JSContext* ctx, JSPrincipals* p,
-                              bool ignoreSelfHostedFrames = true)
-      : cx(ctx), principals(p), ignoreSelfHosted(ignoreSelfHostedFrames) {
-    if (principals) {
-      JS_HoldPrincipals(principals);
-    }
-  }
-
-  // No copying because we want to avoid holding and dropping principals
-  // unnecessarily.
-  FirstSubsumedFrame(const FirstSubsumedFrame&) = delete;
-  FirstSubsumedFrame& operator=(const FirstSubsumedFrame&) = delete;
-
-  FirstSubsumedFrame(FirstSubsumedFrame&& rhs)
-      : principals(rhs.principals), ignoreSelfHosted(rhs.ignoreSelfHosted) {
-    MOZ_ASSERT(this != &rhs, "self move disallowed");
-    rhs.principals = nullptr;
-  }
-
-  FirstSubsumedFrame& operator=(FirstSubsumedFrame&& rhs) {
-    new (this) FirstSubsumedFrame(std::move(rhs));
-    return *this;
-  }
-
-  ~FirstSubsumedFrame() {
-    if (principals) {
-      JS_DropPrincipals(cx, principals);
-    }
-  }
-};
-
-using StackCapture = mozilla::Variant<AllFrames, MaxFrames, FirstSubsumedFrame>;
-
-/**
- * Capture the current call stack as a chain of SavedFrame JSObjects, and set
- * |stackp| to the SavedFrame for the youngest stack frame, or nullptr if there
- * are no JS frames on the stack.
- *
- * The |capture| parameter describes the portion of the JS stack to capture:
- *
- *   * |JS::AllFrames|: Capture all frames on the stack.
- *
- *   * |JS::MaxFrames|: Capture no more than |JS::MaxFrames::maxFrames| from the
- *      stack.
- *
- *   * |JS::FirstSubsumedFrame|: Capture the first frame whose principals are
- *     subsumed by |JS::FirstSubsumedFrame::principals|. By default, do not
- *     consider self-hosted frames; this can be controlled via the
- *     |JS::FirstSubsumedFrame::ignoreSelfHosted| flag. Do not capture any async
- *     stack.
- */
-extern JS_PUBLIC_API bool CaptureCurrentStack(
-    JSContext* cx, MutableHandleObject stackp,
-    StackCapture&& capture = StackCapture(AllFrames()));
-
-/*
- * This is a utility function for preparing an async stack to be used
- * by some other object.  This may be used when you need to treat a
- * given stack trace as an async parent.  If you just need to capture
- * the current stack, async parents and all, use CaptureCurrentStack
- * instead.
- *
- * Here |asyncStack| is the async stack to prepare.  It is copied into
- * |cx|'s current compartment, and the newest frame is given
- * |asyncCause| as its asynchronous cause.  If |maxFrameCount| is
- * |Some(n)|, capture at most the youngest |n| frames.  The
- * new stack object is written to |stackp|.  Returns true on success,
- * or sets an exception and returns |false| on error.
- */
-extern JS_PUBLIC_API bool CopyAsyncStack(
-    JSContext* cx, HandleObject asyncStack, HandleString asyncCause,
-    MutableHandleObject stackp, const mozilla::Maybe<size_t>& maxFrameCount);
-
-/**
- * Given a SavedFrame JSObject stack, stringify it in the same format as
- * Error.prototype.stack. The stringified stack out parameter is placed in the
- * cx's compartment. Defaults to the empty string.
- *
- * The same notes above about SavedFrame accessors applies here as well: cx
- * doesn't need to be in stack's compartment, and stack can be null, a
- * SavedFrame object, or a wrapper (CCW or Xray) around a SavedFrame object.
- * SavedFrames not subsumed by |principals| are skipped.
- *
- * Optional indent parameter specifies the number of white spaces to indent
- * each line.
- */
-extern JS_PUBLIC_API bool BuildStackString(
-    JSContext* cx, JSPrincipals* principals, HandleObject stack,
-    MutableHandleString stringp, size_t indent = 0,
-    js::StackFormat stackFormat = js::StackFormat::Default);
-
-/**
- * Return true iff the given object is either a SavedFrame object or wrapper
- * around a SavedFrame object, and it is not the SavedFrame.prototype object.
- */
-extern JS_PUBLIC_API bool IsMaybeWrappedSavedFrame(JSObject* obj);
-
-/**
- * Return true iff the given object is a SavedFrame object and not the
- * SavedFrame.prototype object.
- */
-extern JS_PUBLIC_API bool IsUnwrappedSavedFrame(JSObject* obj);
-
-} /* namespace JS */
-
-namespace js {
-
-/**
- * Hint that we expect a crash. Currently, the only thing that cares is the
- * breakpad injector, which (if loaded) will suppress minidump generation.
- */
-extern JS_PUBLIC_API void NoteIntentionalCrash();
-
-} /* namespace js */
-
-namespace js {
-
-enum class CompletionKind { Normal, Return, Throw };
-
-} /* namespace js */
-
-#endif /* jsapi_h */
+#endif  // js_Modules_h
--- a/js/src/builtin/ModuleObject.cpp
+++ b/js/src/builtin/ModuleObject.cpp
@@ -11,16 +11,17 @@
 
 #include "builtin/Promise.h"
 #include "builtin/SelfHostingDefines.h"
 #include "frontend/ParseNode.h"
 #include "frontend/SharedContext.h"
 #include "gc/FreeOp.h"
 #include "gc/Policy.h"
 #include "gc/Tracer.h"
+#include "js/Modules.h"  // JS::GetModulePrivate, JS::ModuleDynamicImportHook
 #include "js/PropertySpec.h"
 #include "vm/AsyncFunction.h"
 #include "vm/AsyncIteration.h"
 #include "vm/EqualityOperations.h"  // js::SameValue
 #include "vm/ModuleBuilder.h"       // js::ModuleBuilder
 #include "vm/SelfHosting.h"
 
 #include "vm/JSObject-inl.h"
--- a/js/src/jsapi.cpp
+++ b/js/src/jsapi.cpp
@@ -3684,84 +3684,16 @@ JS_PUBLIC_API JSString* JS_DecompileFunc
                                              HandleFunction fun) {
   MOZ_ASSERT(!cx->zone()->isAtomsZone());
   AssertHeapIsIdle();
   CHECK_THREAD(cx);
   cx->check(fun);
   return FunctionToString(cx, fun, /* isToSource = */ false);
 }
 
-JS_PUBLIC_API JS::ModuleResolveHook JS::GetModuleResolveHook(JSRuntime* rt) {
-  AssertHeapIsIdle();
-  return rt->moduleResolveHook;
-}
-
-JS_PUBLIC_API void JS::SetModuleResolveHook(JSRuntime* rt,
-                                            JS::ModuleResolveHook func) {
-  AssertHeapIsIdle();
-  rt->moduleResolveHook = func;
-}
-
-JS_PUBLIC_API JS::ModuleMetadataHook JS::GetModuleMetadataHook(JSRuntime* rt) {
-  AssertHeapIsIdle();
-  return rt->moduleMetadataHook;
-}
-
-JS_PUBLIC_API void JS::SetModuleMetadataHook(JSRuntime* rt,
-                                             JS::ModuleMetadataHook func) {
-  AssertHeapIsIdle();
-  rt->moduleMetadataHook = func;
-}
-
-JS_PUBLIC_API JS::ModuleDynamicImportHook JS::GetModuleDynamicImportHook(
-    JSRuntime* rt) {
-  AssertHeapIsIdle();
-  return rt->moduleDynamicImportHook;
-}
-
-JS_PUBLIC_API void JS::SetModuleDynamicImportHook(
-    JSRuntime* rt, JS::ModuleDynamicImportHook func) {
-  AssertHeapIsIdle();
-  rt->moduleDynamicImportHook = func;
-}
-
-JS_PUBLIC_API bool JS::FinishDynamicModuleImport(JSContext* cx,
-                                                 HandleValue referencingPrivate,
-                                                 HandleString specifier,
-                                                 HandleObject promise) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(referencingPrivate, promise);
-
-  return js::FinishDynamicModuleImport(cx, referencingPrivate, specifier,
-                                       promise);
-}
-
-JS_PUBLIC_API bool JS::CompileModule(JSContext* cx,
-                                     const ReadOnlyCompileOptions& options,
-                                     SourceText<char16_t>& srcBuf,
-                                     JS::MutableHandleObject module) {
-  MOZ_ASSERT(!cx->zone()->isAtomsZone());
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-
-  module.set(frontend::CompileModule(cx, options, srcBuf));
-  return !!module;
-}
-
-JS_PUBLIC_API void JS::SetModulePrivate(JSObject* module,
-                                        const JS::Value& value) {
-  JSRuntime* rt = module->zone()->runtimeFromMainThread();
-  module->as<ModuleObject>().scriptSourceObject()->setPrivate(rt, value);
-}
-
-JS_PUBLIC_API JS::Value JS::GetModulePrivate(JSObject* module) {
-  return module->as<ModuleObject>().scriptSourceObject()->canonicalPrivate();
-}
-
 JS_PUBLIC_API void JS::SetScriptPrivate(JSScript* script,
                                         const JS::Value& value) {
   JSRuntime* rt = script->zone()->runtimeFromMainThread();
   script->sourceObject()->setPrivate(rt, value);
 }
 
 JS_PUBLIC_API JS::Value JS::GetScriptPrivate(JSScript* script) {
   return script->sourceObject()->canonicalPrivate();
@@ -3782,68 +3714,16 @@ JS_PUBLIC_API JS::Value JS::GetScriptedC
 JS_PUBLIC_API void JS::SetScriptPrivateReferenceHooks(
     JSRuntime* rt, JS::ScriptPrivateReferenceHook addRefHook,
     JS::ScriptPrivateReferenceHook releaseHook) {
   AssertHeapIsIdle();
   rt->scriptPrivateAddRefHook = addRefHook;
   rt->scriptPrivateReleaseHook = releaseHook;
 }
 
-JS_PUBLIC_API bool JS::ModuleInstantiate(JSContext* cx,
-                                         JS::HandleObject moduleArg) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->releaseCheck(moduleArg);
-  return ModuleObject::Instantiate(cx, moduleArg.as<ModuleObject>());
-}
-
-JS_PUBLIC_API bool JS::ModuleEvaluate(JSContext* cx,
-                                      JS::HandleObject moduleArg) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->releaseCheck(moduleArg);
-  return ModuleObject::Evaluate(cx, moduleArg.as<ModuleObject>());
-}
-
-JS_PUBLIC_API JSObject* JS::GetRequestedModules(JSContext* cx,
-                                                JS::HandleObject moduleArg) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(moduleArg);
-  return &moduleArg->as<ModuleObject>().requestedModules();
-}
-
-JS_PUBLIC_API JSString* JS::GetRequestedModuleSpecifier(JSContext* cx,
-                                                        JS::HandleValue value) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(value);
-  JSObject* obj = &value.toObject();
-  return obj->as<RequestedModuleObject>().moduleSpecifier();
-}
-
-JS_PUBLIC_API void JS::GetRequestedModuleSourcePos(JSContext* cx,
-                                                   JS::HandleValue value,
-                                                   uint32_t* lineNumber,
-                                                   uint32_t* columnNumber) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(value);
-  MOZ_ASSERT(lineNumber);
-  MOZ_ASSERT(columnNumber);
-  auto& requested = value.toObject().as<RequestedModuleObject>();
-  *lineNumber = requested.lineNumber();
-  *columnNumber = requested.columnNumber();
-}
-
-JS_PUBLIC_API JSScript* JS::GetModuleScript(JS::HandleObject moduleRecord) {
-  AssertHeapIsIdle();
-  return moduleRecord->as<ModuleObject>().script();
-}
-
 JS_PUBLIC_API JSObject* JS_New(JSContext* cx, HandleObject ctor,
                                const JS::HandleValueArray& inputArgs) {
   AssertHeapIsIdle();
   CHECK_THREAD(cx);
   cx->check(ctor, inputArgs);
 
   RootedValue ctorVal(cx, ObjectValue(*ctor));
   if (!IsConstructor(ctorVal)) {
--- a/js/src/jsapi.h
+++ b/js/src/jsapi.h
@@ -1900,88 +1900,16 @@ extern JS_PUBLIC_API JSScript* JS_GetFun
 extern JS_PUBLIC_API JSString* JS_DecompileScript(JSContext* cx,
                                                   JS::Handle<JSScript*> script);
 
 extern JS_PUBLIC_API JSString* JS_DecompileFunction(
     JSContext* cx, JS::Handle<JSFunction*> fun);
 
 namespace JS {
 
-using ModuleResolveHook = JSObject* (*)(JSContext*, HandleValue, HandleString);
-
-/**
- * Get the HostResolveImportedModule hook for the runtime.
- */
-extern JS_PUBLIC_API ModuleResolveHook GetModuleResolveHook(JSRuntime* rt);
-
-/**
- * Set the HostResolveImportedModule hook for the runtime to the given function.
- */
-extern JS_PUBLIC_API void SetModuleResolveHook(JSRuntime* rt,
-                                               ModuleResolveHook func);
-
-using ModuleMetadataHook = bool (*)(JSContext*, HandleValue, HandleObject);
-
-/**
- * Get the hook for populating the import.meta metadata object.
- */
-extern JS_PUBLIC_API ModuleMetadataHook GetModuleMetadataHook(JSRuntime* rt);
-
-/**
- * Set the hook for populating the import.meta metadata object to the given
- * function.
- */
-extern JS_PUBLIC_API void SetModuleMetadataHook(JSRuntime* rt,
-                                                ModuleMetadataHook func);
-
-using ModuleDynamicImportHook = bool (*)(JSContext* cx,
-                                         HandleValue referencingPrivate,
-                                         HandleString specifier,
-                                         HandleObject promise);
-
-/**
- * Get the HostImportModuleDynamically hook for the runtime.
- */
-extern JS_PUBLIC_API ModuleDynamicImportHook
-GetModuleDynamicImportHook(JSRuntime* rt);
-
-/**
- * Set the HostImportModuleDynamically hook for the runtime to the given
- * function.
- *
- * If this hook is not set (or set to nullptr) then the JS engine will throw an
- * exception if dynamic module import is attempted.
- */
-extern JS_PUBLIC_API void SetModuleDynamicImportHook(
-    JSRuntime* rt, ModuleDynamicImportHook func);
-
-extern JS_PUBLIC_API bool FinishDynamicModuleImport(
-    JSContext* cx, HandleValue referencingPrivate, HandleString specifier,
-    HandleObject promise);
-
-/**
- * Parse the given source buffer as a module in the scope of the current global
- * of cx and return a source text module record.
- */
-extern JS_PUBLIC_API bool CompileModule(JSContext* cx,
-                                        const ReadOnlyCompileOptions& options,
-                                        SourceText<char16_t>& srcBuf,
-                                        JS::MutableHandleObject moduleRecord);
-
-/**
- * Set a private value associated with a source text module record.
- */
-extern JS_PUBLIC_API void SetModulePrivate(JSObject* module,
-                                           const JS::Value& value);
-
-/**
- * Get the private value associated with a source text module record.
- */
-extern JS_PUBLIC_API JS::Value GetModulePrivate(JSObject* module);
-
 /**
  * Set a private value associated with a script. Note that this value is shared
  * by all nested scripts compiled from a single source file.
  */
 extern JS_PUBLIC_API void SetScriptPrivate(JSScript* script,
                                            const JS::Value& value);
 
 /**
@@ -2005,70 +1933,16 @@ using ScriptPrivateReferenceHook = void 
 
 /**
  * Set the script private finalize hook for the runtime to the given function.
  */
 extern JS_PUBLIC_API void SetScriptPrivateReferenceHooks(
     JSRuntime* rt, ScriptPrivateReferenceHook addRefHook,
     ScriptPrivateReferenceHook releaseHook);
 
-/*
- * Perform the ModuleInstantiate operation on the given source text module
- * record.
- *
- * This transitively resolves all module dependencies (calling the
- * HostResolveImportedModule hook) and initializes the environment record for
- * the module.
- */
-extern JS_PUBLIC_API bool ModuleInstantiate(JSContext* cx,
-                                            JS::HandleObject moduleRecord);
-
-/*
- * Perform the ModuleEvaluate operation on the given source text module record.
- *
- * This does nothing if this module has already been evaluated. Otherwise, it
- * transitively evaluates all dependences of this module and then evaluates this
- * module.
- *
- * ModuleInstantiate must have completed prior to calling this.
- */
-extern JS_PUBLIC_API bool ModuleEvaluate(JSContext* cx,
-                                         JS::HandleObject moduleRecord);
-
-/*
- * Get a list of the module specifiers used by a source text module
- * record to request importation of modules.
- *
- * The result is a JavaScript array of object values.  To extract the individual
- * values use only JS_GetArrayLength and JS_GetElement with indices 0 to length
- * - 1.
- *
- * The element values are objects with the following properties:
- *  - moduleSpecifier: the module specifier string
- *  - lineNumber: the line number of the import in the source text
- *  - columnNumber: the column number of the import in the source text
- *
- * These property values can be extracted with GetRequestedModuleSpecifier() and
- * GetRequestedModuleSourcePos()
- */
-extern JS_PUBLIC_API JSObject* GetRequestedModules(
-    JSContext* cx, JS::HandleObject moduleRecord);
-
-extern JS_PUBLIC_API JSString* GetRequestedModuleSpecifier(
-    JSContext* cx, JS::HandleValue requestedModuleObject);
-
-extern JS_PUBLIC_API void GetRequestedModuleSourcePos(
-    JSContext* cx, JS::HandleValue requestedModuleObject, uint32_t* lineNumber,
-    uint32_t* columnNumber);
-
-/*
- * Get the top-level script for a module which has not yet been executed.
- */
-extern JS_PUBLIC_API JSScript* GetModuleScript(JS::HandleObject moduleRecord);
-
 } /* namespace JS */
 
 #if defined(JS_BUILD_BINAST)
 
 namespace JS {
 
 extern JS_PUBLIC_API JSScript* DecodeBinAST(
     JSContext* cx, const ReadOnlyCompileOptions& options, FILE* file);
--- a/js/src/moz.build
+++ b/js/src/moz.build
@@ -141,16 +141,17 @@ EXPORTS.js += [
     '../public/HashTable.h',
     '../public/HeapAPI.h',
     '../public/Id.h',
     '../public/Initialization.h',
     '../public/JSON.h',
     '../public/LocaleSensitive.h',
     '../public/MemoryFunctions.h',
     '../public/MemoryMetrics.h',
+    '../public/Modules.h',
     '../public/OffThreadScriptCompilation.h',
     '../public/Principals.h',
     '../public/Printf.h',
     '../public/ProfilingCategory.h',
     '../public/ProfilingFrameIterator.h',
     '../public/ProfilingStack.h',
     '../public/Promise.h',
     '../public/PropertyDescriptor.h',
@@ -299,16 +300,17 @@ UNIFIED_SOURCES += [
     'vm/JSContext.cpp',
     'vm/JSFunction.cpp',
     'vm/JSObject.cpp',
     'vm/JSONParser.cpp',
     'vm/JSONPrinter.cpp',
     'vm/JSScript.cpp',
     'vm/List.cpp',
     'vm/MemoryMetrics.cpp',
+    'vm/Modules.cpp',
     'vm/NativeObject.cpp',
     'vm/ObjectGroup.cpp',
     'vm/OffThreadScriptCompilation.cpp',
     'vm/PIC.cpp',
     'vm/Printer.cpp',
     'vm/Probes.cpp',
     'vm/ProxyObject.cpp',
     'vm/Realm.cpp',
--- a/js/src/shell/js.cpp
+++ b/js/src/shell/js.cpp
@@ -93,16 +93,17 @@
 #include "js/ContextOptions.h"  // JS::ContextOptions{,Ref}
 #include "js/Debug.h"
 #include "js/Equality.h"                 // JS::SameValue
 #include "js/experimental/SourceHook.h"  // js::{Set,Forget,}SourceHook
 #include "js/GCVector.h"
 #include "js/Initialization.h"
 #include "js/JSON.h"
 #include "js/MemoryFunctions.h"
+#include "js/Modules.h"  // JS::GetModulePrivate, JS::SetModule{DynamicImport,Metadata,Resolve}Hook, JS::SetModulePrivate
 #include "js/Printf.h"
 #include "js/PropertySpec.h"
 #include "js/Realm.h"
 #include "js/RegExp.h"  // JS::ObjectIsRegExp
 #include "js/SourceText.h"
 #include "js/StableStringChars.h"
 #include "js/StructuredClone.h"
 #include "js/SweepingAPI.h"
copy from js/src/jsapi.cpp
copy to js/src/vm/Modules.cpp
--- a/js/src/jsapi.cpp
+++ b/js/src/vm/Modules.cpp
@@ -1,6000 +1,160 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  * vim: set ts=8 sts=2 et sw=2 tw=80:
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-/*
- * JavaScript API.
- */
-
-#include "jsapi.h"
-
-#include "mozilla/FloatingPoint.h"
-#include "mozilla/Maybe.h"
-#include "mozilla/PodOperations.h"
-#include "mozilla/Sprintf.h"
-
-#ifdef __linux__
-#  include <dlfcn.h>
-#endif
-#include <stdarg.h>
-#include <string.h>
-
-#include "jsdate.h"
-#include "jsexn.h"
-#include "jsfriendapi.h"
-#include "jsmath.h"
-#include "jsnum.h"
-#include "jstypes.h"
-#include "jsutil.h"
-
-#include "builtin/Array.h"
-#include "builtin/AtomicsObject.h"
-#include "builtin/Boolean.h"
-#include "builtin/Eval.h"
-#include "builtin/JSON.h"
-#include "builtin/MapObject.h"
-#include "builtin/Promise.h"
-#include "builtin/Stream.h"
-#include "builtin/String.h"
-#include "builtin/Symbol.h"
-#ifdef ENABLE_TYPED_OBJECTS
-#  include "builtin/TypedObject.h"
-#endif
-#include "frontend/BytecodeCompiler.h"
-#include "gc/FreeOp.h"
-#include "gc/Marking.h"
-#include "gc/Policy.h"
-#include "gc/PublicIterators.h"
-#include "gc/WeakMap.h"
-#include "jit/JitCommon.h"
-#include "jit/JitSpewer.h"
-#include "js/CharacterEncoding.h"
-#include "js/CompilationAndEvaluation.h"
-#include "js/CompileOptions.h"
-#include "js/ContextOptions.h"  // JS::ContextOptions{,Ref}
-#include "js/Conversions.h"
-#include "js/Date.h"
-#include "js/Initialization.h"
-#include "js/JSON.h"
-#include "js/LocaleSensitive.h"
-#include "js/MemoryFunctions.h"
-#include "js/PropertySpec.h"
-#include "js/Proxy.h"
-#include "js/SliceBudget.h"
-#include "js/SourceText.h"
-#include "js/StableStringChars.h"
-#include "js/StructuredClone.h"
-#include "js/Symbol.h"
-#include "js/Utility.h"
-#include "js/Wrapper.h"
-#include "util/CompleteFile.h"
-#include "util/StringBuffer.h"
-#include "util/Text.h"
-#include "vm/AsyncFunction.h"
-#include "vm/AsyncIteration.h"
-#include "vm/DateObject.h"
-#include "vm/Debugger.h"
-#include "vm/EnvironmentObject.h"
-#include "vm/ErrorObject.h"
-#include "vm/HelperThreads.h"
-#include "vm/Interpreter.h"
-#include "vm/Iteration.h"
-#include "vm/JSAtom.h"
-#include "vm/JSContext.h"
-#include "vm/JSFunction.h"
-#include "vm/JSObject.h"
-#include "vm/JSScript.h"
-#include "vm/Runtime.h"
-#include "vm/SavedStacks.h"
-#include "vm/SelfHosting.h"
-#include "vm/Shape.h"
-#include "vm/StringType.h"
-#include "vm/SymbolType.h"
-#include "vm/WrapperObject.h"
-#include "vm/Xdr.h"
-#include "wasm/WasmModule.h"
-
-#include "vm/Compartment-inl.h"
-#include "vm/Interpreter-inl.h"
-#include "vm/JSAtom-inl.h"
-#include "vm/JSFunction-inl.h"
-#include "vm/JSScript-inl.h"
-#include "vm/NativeObject-inl.h"
-#include "vm/SavedStacks-inl.h"
-#include "vm/StringType-inl.h"
-
-using namespace js;
-
-using mozilla::Maybe;
-using mozilla::PodCopy;
-using mozilla::Some;
-
-using JS::AutoStableStringChars;
-using JS::CompileOptions;
-using JS::ReadOnlyCompileOptions;
-using JS::SourceText;
-
-#ifdef HAVE_VA_LIST_AS_ARRAY
-#  define JS_ADDRESSOF_VA_LIST(ap) ((va_list*)(ap))
-#else
-#  define JS_ADDRESSOF_VA_LIST(ap) (&(ap))
-#endif
-
-JS_PUBLIC_API void JS::CallArgs::reportMoreArgsNeeded(JSContext* cx,
-                                                      const char* fnname,
-                                                      unsigned required,
-                                                      unsigned actual) {
-  char requiredArgsStr[40];
-  SprintfLiteral(requiredArgsStr, "%u", required);
-  char actualArgsStr[40];
-  SprintfLiteral(actualArgsStr, "%u", actual);
-  JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
-                            JSMSG_MORE_ARGS_NEEDED, fnname, requiredArgsStr,
-                            required == 1 ? "" : "s", actualArgsStr);
-}
-
-static bool ErrorTakesArguments(unsigned msg) {
-  MOZ_ASSERT(msg < JSErr_Limit);
-  unsigned argCount = js_ErrorFormatString[msg].argCount;
-  MOZ_ASSERT(argCount <= 2);
-  return argCount == 1 || argCount == 2;
-}
-
-static bool ErrorTakesObjectArgument(unsigned msg) {
-  MOZ_ASSERT(msg < JSErr_Limit);
-  unsigned argCount = js_ErrorFormatString[msg].argCount;
-  MOZ_ASSERT(argCount <= 2);
-  return argCount == 2;
-}
-
-JS_PUBLIC_API bool JS::ObjectOpResult::reportStrictErrorOrWarning(
-    JSContext* cx, HandleObject obj, HandleId id, bool strict) {
-  static_assert(unsigned(OkCode) == unsigned(JSMSG_NOT_AN_ERROR),
-                "unsigned value of OkCode must not be an error code");
-  MOZ_ASSERT(code_ != Uninitialized);
-  MOZ_ASSERT(!ok());
-  cx->check(obj);
-
-  unsigned flags =
-      strict ? JSREPORT_ERROR : (JSREPORT_WARNING | JSREPORT_STRICT);
-  if (code_ == JSMSG_OBJECT_NOT_EXTENSIBLE) {
-    RootedValue val(cx, ObjectValue(*obj));
-    return ReportValueErrorFlags(cx, flags, code_, JSDVG_IGNORE_STACK, val,
-                                 nullptr, nullptr, nullptr);
-  }
-
-  if (ErrorTakesArguments(code_)) {
-    UniqueChars propName =
-        IdToPrintableUTF8(cx, id, IdToPrintableBehavior::IdIsPropertyKey);
-    if (!propName) {
-      return false;
-    }
-
-    if (code_ == JSMSG_SET_NON_OBJECT_RECEIVER) {
-      // We know that the original receiver was a primitive, so unbox it.
-      RootedValue val(cx, ObjectValue(*obj));
-      if (!obj->is<ProxyObject>()) {
-        if (!Unbox(cx, obj, &val)) {
-          return false;
-        }
-      }
-      return ReportValueErrorFlags(cx, flags, code_, JSDVG_IGNORE_STACK, val,
-                                   nullptr, propName.get(), nullptr);
-    }
-
-    if (ErrorTakesObjectArgument(code_)) {
-      return JS_ReportErrorFlagsAndNumberUTF8(
-          cx, flags, GetErrorMessage, nullptr, code_, obj->getClass()->name,
-          propName.get());
-    }
-
-    return JS_ReportErrorFlagsAndNumberUTF8(cx, flags, GetErrorMessage, nullptr,
-                                            code_, propName.get());
-  }
-  return JS_ReportErrorFlagsAndNumberASCII(cx, flags, GetErrorMessage, nullptr,
-                                           code_);
-}
-
-JS_PUBLIC_API bool JS::ObjectOpResult::reportStrictErrorOrWarning(
-    JSContext* cx, HandleObject obj, bool strict) {
-  MOZ_ASSERT(code_ != Uninitialized);
-  MOZ_ASSERT(!ok());
-  MOZ_ASSERT(!ErrorTakesArguments(code_));
-  cx->check(obj);
-
-  unsigned flags =
-      strict ? JSREPORT_ERROR : (JSREPORT_WARNING | JSREPORT_STRICT);
-  return JS_ReportErrorFlagsAndNumberASCII(cx, flags, GetErrorMessage, nullptr,
-                                           code_);
-}
-
-JS_PUBLIC_API bool JS::ObjectOpResult::failCantRedefineProp() {
-  return fail(JSMSG_CANT_REDEFINE_PROP);
-}
-
-JS_PUBLIC_API bool JS::ObjectOpResult::failReadOnly() {
-  return fail(JSMSG_READ_ONLY);
-}
-
-JS_PUBLIC_API bool JS::ObjectOpResult::failGetterOnly() {
-  return fail(JSMSG_GETTER_ONLY);
-}
-
-JS_PUBLIC_API bool JS::ObjectOpResult::failCantDelete() {
-  return fail(JSMSG_CANT_DELETE);
-}
-
-JS_PUBLIC_API bool JS::ObjectOpResult::failCantSetInterposed() {
-  return fail(JSMSG_CANT_SET_INTERPOSED);
-}
-
-JS_PUBLIC_API bool JS::ObjectOpResult::failCantDefineWindowElement() {
-  return fail(JSMSG_CANT_DEFINE_WINDOW_ELEMENT);
-}
-
-JS_PUBLIC_API bool JS::ObjectOpResult::failCantDeleteWindowElement() {
-  return fail(JSMSG_CANT_DELETE_WINDOW_ELEMENT);
-}
-
-JS_PUBLIC_API bool JS::ObjectOpResult::failCantDeleteWindowNamedProperty() {
-  return fail(JSMSG_CANT_DELETE_WINDOW_NAMED_PROPERTY);
-}
-
-JS_PUBLIC_API bool JS::ObjectOpResult::failCantDefineWindowNonConfigurable() {
-  return fail(JSMSG_CANT_DEFINE_WINDOW_NC);
-}
-
-JS_PUBLIC_API bool JS::ObjectOpResult::failCantPreventExtensions() {
-  return fail(JSMSG_CANT_PREVENT_EXTENSIONS);
-}
-
-JS_PUBLIC_API bool JS::ObjectOpResult::failCantSetProto() {
-  return fail(JSMSG_CANT_SET_PROTO);
-}
-
-JS_PUBLIC_API bool JS::ObjectOpResult::failNoNamedSetter() {
-  return fail(JSMSG_NO_NAMED_SETTER);
-}
-
-JS_PUBLIC_API bool JS::ObjectOpResult::failNoIndexedSetter() {
-  return fail(JSMSG_NO_INDEXED_SETTER);
-}
-
-JS_PUBLIC_API bool JS::ObjectOpResult::failNotDataDescriptor() {
-  return fail(JSMSG_NOT_DATA_DESCRIPTOR);
-}
-
-JS_PUBLIC_API int64_t JS_Now() { return PRMJ_Now(); }
-
-JS_PUBLIC_API Value JS_GetNaNValue(JSContext* cx) {
-  return cx->runtime()->NaNValue;
-}
-
-JS_PUBLIC_API Value JS_GetNegativeInfinityValue(JSContext* cx) {
-  return cx->runtime()->negativeInfinityValue;
-}
-
-JS_PUBLIC_API Value JS_GetPositiveInfinityValue(JSContext* cx) {
-  return cx->runtime()->positiveInfinityValue;
-}
-
-JS_PUBLIC_API Value JS_GetEmptyStringValue(JSContext* cx) {
-  return StringValue(cx->runtime()->emptyString);
-}
-
-JS_PUBLIC_API JSString* JS_GetEmptyString(JSContext* cx) {
-  MOZ_ASSERT(cx->emptyString());
-  return cx->emptyString();
-}
-
-namespace js {
-
-void AssertHeapIsIdle() { MOZ_ASSERT(!JS::RuntimeHeapIsBusy()); }
-
-}  // namespace js
-
-static void AssertHeapIsIdleOrIterating() {
-  MOZ_ASSERT(!JS::RuntimeHeapIsCollecting());
-}
-
-static void AssertHeapIsIdleOrStringIsFlat(JSString* str) {
-  /*
-   * We allow some functions to be called during a GC as long as the argument
-   * is a flat string, since that will not cause allocation.
-   */
-  MOZ_ASSERT_IF(JS::RuntimeHeapIsBusy(), str->isFlat());
-}
-
-JS_PUBLIC_API bool JS_ValueToObject(JSContext* cx, HandleValue value,
-                                    MutableHandleObject objp) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(value);
-  if (value.isNullOrUndefined()) {
-    objp.set(nullptr);
-    return true;
-  }
-  JSObject* obj = ToObject(cx, value);
-  if (!obj) {
-    return false;
-  }
-  objp.set(obj);
-  return true;
-}
-
-JS_PUBLIC_API JSFunction* JS_ValueToFunction(JSContext* cx, HandleValue value) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(value);
-  return ReportIfNotFunction(cx, value);
-}
-
-JS_PUBLIC_API JSFunction* JS_ValueToConstructor(JSContext* cx,
-                                                HandleValue value) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(value);
-  return ReportIfNotFunction(cx, value);
-}
-
-JS_PUBLIC_API JSString* JS_ValueToSource(JSContext* cx, HandleValue value) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(value);
-  return ValueToSource(cx, value);
-}
-
-JS_PUBLIC_API bool JS_DoubleIsInt32(double d, int32_t* ip) {
-  return mozilla::NumberIsInt32(d, ip);
-}
-
-JS_PUBLIC_API JSType JS_TypeOfValue(JSContext* cx, HandleValue value) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(value);
-  return TypeOfValue(value);
-}
-
-JS_PUBLIC_API bool JS_IsBuiltinEvalFunction(JSFunction* fun) {
-  return IsAnyBuiltinEval(fun);
-}
-
-JS_PUBLIC_API bool JS_IsBuiltinFunctionConstructor(JSFunction* fun) {
-  return fun->isBuiltinFunctionConstructor();
-}
-
-JS_PUBLIC_API bool JS_IsFunctionBound(JSFunction* fun) {
-  return fun->isBoundFunction();
-}
-
-JS_PUBLIC_API JSObject* JS_GetBoundFunctionTarget(JSFunction* fun) {
-  return fun->isBoundFunction() ? fun->getBoundFunctionTarget() : nullptr;
-}
-
-/************************************************************************/
-
-JS_PUBLIC_API JSContext* JS_NewContext(uint32_t maxbytes,
-                                       uint32_t maxNurseryBytes,
-                                       JSRuntime* parentRuntime) {
-  MOZ_ASSERT(JS::detail::libraryInitState == JS::detail::InitState::Running,
-             "must call JS_Init prior to creating any JSContexts");
-
-  // Make sure that all parent runtimes are the topmost parent.
-  while (parentRuntime && parentRuntime->parentRuntime) {
-    parentRuntime = parentRuntime->parentRuntime;
-  }
-
-  return NewContext(maxbytes, maxNurseryBytes, parentRuntime);
-}
-
-JS_PUBLIC_API JSContext* JS_NewCooperativeContext(JSContext* siblingContext) {
-  MOZ_CRASH("Cooperative scheduling is unsupported");
-}
-
-JS_PUBLIC_API void JS_YieldCooperativeContext(JSContext* cx) {
-  MOZ_CRASH("Cooperative scheduling is unsupported");
-}
-
-JS_PUBLIC_API void JS_ResumeCooperativeContext(JSContext* cx) {
-  MOZ_CRASH("Cooperative scheduling is unsupported");
-}
-
-JS_PUBLIC_API void JS_DestroyContext(JSContext* cx) { DestroyContext(cx); }
-
-JS_PUBLIC_API void* JS_GetContextPrivate(JSContext* cx) { return cx->data; }
-
-JS_PUBLIC_API void JS_SetContextPrivate(JSContext* cx, void* data) {
-  cx->data = data;
-}
-
-JS_PUBLIC_API void JS_SetFutexCanWait(JSContext* cx) {
-  cx->fx.setCanWait(true);
-}
-
-JS_PUBLIC_API JSRuntime* JS_GetParentRuntime(JSContext* cx) {
-  return cx->runtime()->parentRuntime ? cx->runtime()->parentRuntime
-                                      : cx->runtime();
-}
-
-JS_PUBLIC_API JSRuntime* JS_GetRuntime(JSContext* cx) { return cx->runtime(); }
-
-JS_PUBLIC_API JS::ContextOptions& JS::ContextOptionsRef(JSContext* cx) {
-  return cx->options();
-}
-
-JS_PUBLIC_API bool JS::InitSelfHostedCode(JSContext* cx) {
-  MOZ_RELEASE_ASSERT(!cx->runtime()->hasInitializedSelfHosting(),
-                     "JS::InitSelfHostedCode() called more than once");
-
-  AutoNoteSingleThreadedRegion anstr;
-
-  JSRuntime* rt = cx->runtime();
-
-  if (!rt->initializeAtoms(cx)) {
-    return false;
-  }
-
-#ifndef JS_CODEGEN_NONE
-  if (!rt->createJitRuntime(cx)) {
-    return false;
-  }
-#endif
-
-  if (!rt->initSelfHosting(cx)) {
-    return false;
-  }
-
-  if (!rt->parentRuntime && !rt->initMainAtomsTables(cx)) {
-    return false;
-  }
-
-  return true;
-}
-
-JS_PUBLIC_API const char* JS_GetImplementationVersion(void) {
-  return "JavaScript-C" MOZILLA_VERSION;
-}
+/* JavaScript modules (as in, the syntactic construct) implementation. */
 
-JS_PUBLIC_API void JS_SetDestroyCompartmentCallback(
-    JSContext* cx, JSDestroyCompartmentCallback callback) {
-  cx->runtime()->destroyCompartmentCallback = callback;
-}
-
-JS_PUBLIC_API void JS_SetSizeOfIncludingThisCompartmentCallback(
-    JSContext* cx, JSSizeOfIncludingThisCompartmentCallback callback) {
-  cx->runtime()->sizeOfIncludingThisCompartmentCallback = callback;
-}
-
-#if defined(NIGHTLY_BUILD)
-JS_PUBLIC_API void JS_SetErrorInterceptorCallback(
-    JSRuntime* rt, JSErrorInterceptor* callback) {
-  rt->errorInterception.interceptor = callback;
-}
-
-JS_PUBLIC_API JSErrorInterceptor* JS_GetErrorInterceptorCallback(
-    JSRuntime* rt) {
-  return rt->errorInterception.interceptor;
-}
-
-JS_PUBLIC_API Maybe<JSExnType> JS_GetErrorType(const JS::Value& val) {
-  // All errors are objects.
-  if (!val.isObject()) {
-    return mozilla::Nothing();
-  }
-
-  const JSObject& obj = val.toObject();
-
-  // All errors are `ErrorObject`.
-  if (!obj.is<js::ErrorObject>()) {
-    // Not one of the primitive errors.
-    return mozilla::Nothing();
-  }
-
-  const js::ErrorObject& err = obj.as<js::ErrorObject>();
-  return mozilla::Some(err.type());
-}
-
-#endif  // defined(NIGHTLY_BUILD)
-
-JS_PUBLIC_API void JS_SetWrapObjectCallbacks(
-    JSContext* cx, const JSWrapObjectCallbacks* callbacks) {
-  cx->runtime()->wrapObjectCallbacks = callbacks;
-}
-
-JS_PUBLIC_API void JS_SetExternalStringSizeofCallback(
-    JSContext* cx, JSExternalStringSizeofCallback callback) {
-  cx->runtime()->externalStringSizeofCallback = callback;
-}
-
-JS_PUBLIC_API Realm* JS::EnterRealm(JSContext* cx, JSObject* target) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-
-  MOZ_DIAGNOSTIC_ASSERT(!js::IsCrossCompartmentWrapper(target));
-
-  Realm* oldRealm = cx->realm();
-  cx->enterRealmOf(target);
-  return oldRealm;
-}
-
-JS_PUBLIC_API void JS::LeaveRealm(JSContext* cx, JS::Realm* oldRealm) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->leaveRealm(oldRealm);
-}
-
-JSAutoRealm::JSAutoRealm(
-    JSContext* cx, JSObject* target MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL)
-    : cx_(cx), oldRealm_(cx->realm()) {
-  MOZ_GUARD_OBJECT_NOTIFIER_INIT;
-  MOZ_DIAGNOSTIC_ASSERT(!js::IsCrossCompartmentWrapper(target));
-  AssertHeapIsIdleOrIterating();
-  cx_->enterRealmOf(target);
-}
-
-JSAutoRealm::JSAutoRealm(
-    JSContext* cx, JSScript* target MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL)
-    : cx_(cx), oldRealm_(cx->realm()) {
-  MOZ_GUARD_OBJECT_NOTIFIER_INIT;
-  AssertHeapIsIdleOrIterating();
-  cx_->enterRealmOf(target);
-}
-
-JSAutoRealm::~JSAutoRealm() { cx_->leaveRealm(oldRealm_); }
-
-JSAutoNullableRealm::JSAutoNullableRealm(
-    JSContext* cx,
-    JSObject* targetOrNull MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL)
-    : cx_(cx), oldRealm_(cx->realm()) {
-  MOZ_GUARD_OBJECT_NOTIFIER_INIT;
-  AssertHeapIsIdleOrIterating();
-  if (targetOrNull) {
-    MOZ_DIAGNOSTIC_ASSERT(!js::IsCrossCompartmentWrapper(targetOrNull));
-    cx_->enterRealmOf(targetOrNull);
-  } else {
-    cx_->enterNullRealm();
-  }
-}
-
-JSAutoNullableRealm::~JSAutoNullableRealm() { cx_->leaveRealm(oldRealm_); }
-
-JS_PUBLIC_API void JS_SetCompartmentPrivate(JS::Compartment* compartment,
-                                            void* data) {
-  compartment->data = data;
-}
-
-JS_PUBLIC_API void* JS_GetCompartmentPrivate(JS::Compartment* compartment) {
-  return compartment->data;
-}
-
-JS_PUBLIC_API void JS_MarkCrossZoneId(JSContext* cx, jsid id) {
-  cx->markId(id);
-}
-
-JS_PUBLIC_API void JS_MarkCrossZoneIdValue(JSContext* cx, const Value& value) {
-  cx->markAtomValue(value);
-}
-
-JS_PUBLIC_API void JS_SetZoneUserData(JS::Zone* zone, void* data) {
-  zone->data = data;
-}
-
-JS_PUBLIC_API void* JS_GetZoneUserData(JS::Zone* zone) { return zone->data; }
-
-JS_PUBLIC_API bool JS_WrapObject(JSContext* cx, MutableHandleObject objp) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  if (objp) {
-    JS::ExposeObjectToActiveJS(objp);
-  }
-  return cx->compartment()->wrap(cx, objp);
-}
-
-JS_PUBLIC_API bool JS_WrapValue(JSContext* cx, MutableHandleValue vp) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  JS::ExposeValueToActiveJS(vp);
-  return cx->compartment()->wrap(cx, vp);
-}
-
-static void ReleaseAssertObjectHasNoWrappers(JSContext* cx,
-                                             HandleObject target) {
-  RootedValue origv(cx, ObjectValue(*target));
-
-  for (CompartmentsIter c(cx->runtime()); !c.done(); c.next()) {
-    if (c->lookupWrapper(origv)) {
-      MOZ_CRASH("wrapper found for target object");
-    }
-  }
-}
-
-/*
- * [SMDOC] Brain transplants.
- *
- * Not for beginners or the squeamish.
- *
- * Sometimes a web spec requires us to transplant an object from one
- * compartment to another, like when a DOM node is inserted into a document in
- * another window and thus gets "adopted". We cannot literally change the
- * `.compartment()` of a `JSObject`; that would break the compartment
- * invariants. However, as usual, we have a workaround using wrappers.
- *
- * Of all the wrapper-based workarounds we do, it's safe to say this is the
- * most spectacular and questionable.
- *
- * `JS_TransplantObject(cx, origobj, target)` changes `origobj` into a
- * simulacrum of `target`, using highly esoteric means. To JS code, the effect
- * is as if `origobj` magically "became" `target`, but most often what actually
- * happens is that `origobj` gets turned into a cross-compartment wrapper for
- * `target`. The old behavior and contents of `origobj` are overwritten or
- * discarded.
- *
- * Thus, to "transplant" an object from one compartment to another:
- *
- * 1.  Let `origobj` be the object that you want to move. First, create a
- *     clone of it, `target`, in the destination compartment.
- *
- *     In our DOM adoption example, `target` will be a Node of the same type as
- *     `origobj`, same content, but in the adopting document.  We're not done
- *     yet: the spec for DOM adoption requires that `origobj.ownerDocument`
- *     actually change. All we've done so far is make a copy.
- *
- * 2.  Call `JS_TransplantObject(cx, origobj, target)`. This typically turns
- *     `origobj` into a wrapper for `target`, so that any JS code that has a
- *     reference to `origobj` will observe it to have the behavior of `target`
- *     going forward. In addition, all existing wrappers for `origobj` are
- *     changed into wrappers for `target`, extending the illusion to those
- *     compartments as well.
- *
- * During navigation, we use the above technique to transplant the WindowProxy
- * into the new Window's compartment.
- *
- * A few rules:
- *
- * -   `origobj` and `target` must be two distinct objects of the same
- *     `JSClass`.  Some classes may not support transplantation; WindowProxy
- *     objects and DOM nodes are OK.
- *
- * -   `target` should be created specifically to be passed to this function.
- *     There must be no existing cross-compartment wrappers for it; ideally
- *     there shouldn't be any pointers to it at all, except the one passed in.
- *
- * -   `target` shouldn't be used afterwards. Instead, `JS_TransplantObject`
- *     returns a pointer to the transplanted object, which might be `target`
- *     but might be some other object in the same compartment. Use that.
- *
- * The reason for this last rule is that JS_TransplantObject does very strange
- * things in some cases, like swapping `target`'s brain with that of another
- * object. Leaving `target` behaving like its former self is not a goal.
- *
- * We don't have a good way to recover from failure in this function, so
- * we intentionally crash instead.
- */
-
-JS_PUBLIC_API JSObject* JS_TransplantObject(JSContext* cx, HandleObject origobj,
-                                            HandleObject target) {
-  AssertHeapIsIdle();
-  MOZ_ASSERT(origobj != target);
-  MOZ_ASSERT(!origobj->is<CrossCompartmentWrapperObject>());
-  MOZ_ASSERT(!target->is<CrossCompartmentWrapperObject>());
-  MOZ_ASSERT(origobj->getClass() == target->getClass());
-  ReleaseAssertObjectHasNoWrappers(cx, target);
-  JS::AssertCellIsNotGray(origobj);
-  JS::AssertCellIsNotGray(target);
-
-  RootedValue origv(cx, ObjectValue(*origobj));
-  RootedObject newIdentity(cx);
-
-  // Don't allow a compacting GC to observe any intermediate state.
-  AutoDisableCompactingGC nocgc(cx);
-
-  AutoDisableProxyCheck adpc;
-
-  JS::Compartment* destination = target->compartment();
-
-  if (origobj->compartment() == destination) {
-    // If the original object is in the same compartment as the
-    // destination, then we know that we won't find a wrapper in the
-    // destination's cross compartment map and that the same
-    // object will continue to work.
-    AutoRealm ar(cx, origobj);
-    JSObject::swap(cx, origobj, target);
-    newIdentity = origobj;
-  } else if (WrapperMap::Ptr p = destination->lookupWrapper(origv)) {
-    // There might already be a wrapper for the original object in
-    // the new compartment. If there is, we use its identity and swap
-    // in the contents of |target|.
-    newIdentity = &p->value().get().toObject();
-
-    // When we remove origv from the wrapper map, its wrapper, newIdentity,
-    // must immediately cease to be a cross-compartment wrapper. Nuke it.
-    destination->removeWrapper(p);
-    NukeCrossCompartmentWrapper(cx, newIdentity);
-
-    AutoRealm ar(cx, newIdentity);
-    JSObject::swap(cx, newIdentity, target);
-  } else {
-    // Otherwise, we use |target| for the new identity object.
-    newIdentity = target;
-  }
-
-  // Now, iterate through other scopes looking for references to the old
-  // object, and update the relevant cross-compartment wrappers. We do this
-  // even if origobj is in the same compartment as target and thus
-  // `newIdentity == origobj`, because this process also clears out any
-  // cached wrapper state.
-  if (!RemapAllWrappersForObject(cx, origobj, newIdentity)) {
-    MOZ_CRASH();
-  }
-
-  // Lastly, update the original object to point to the new one.
-  if (origobj->compartment() != destination) {
-    RootedObject newIdentityWrapper(cx, newIdentity);
-    AutoRealm ar(cx, origobj);
-    if (!JS_WrapObject(cx, &newIdentityWrapper)) {
-      MOZ_CRASH();
-    }
-    MOZ_ASSERT(Wrapper::wrappedObject(newIdentityWrapper) == newIdentity);
-    JSObject::swap(cx, origobj, newIdentityWrapper);
-    if (!origobj->compartment()->putWrapper(
-            cx, CrossCompartmentKey(newIdentity), origv)) {
-      MOZ_CRASH();
-    }
-  }
-
-  // The new identity object might be one of several things. Return it to avoid
-  // ambiguity.
-  JS::AssertCellIsNotGray(newIdentity);
-  return newIdentity;
-}
-
-/*
- * Recompute all cross-compartment wrappers for an object, resetting state.
- * Gecko uses this to clear Xray wrappers when doing a navigation that reuses
- * the inner window and global object.
- */
-JS_PUBLIC_API bool JS_RefreshCrossCompartmentWrappers(JSContext* cx,
-                                                      HandleObject obj) {
-  return RemapAllWrappersForObject(cx, obj, obj);
-}
-
-typedef struct JSStdName {
-  size_t atomOffset; /* offset of atom pointer in JSAtomState */
-  JSProtoKey key;
-  bool isDummy() const { return key == JSProto_Null; }
-  bool isSentinel() const { return key == JSProto_LIMIT; }
-} JSStdName;
-
-static const JSStdName* LookupStdName(const JSAtomState& names, JSAtom* name,
-                                      const JSStdName* table) {
-  for (unsigned i = 0; !table[i].isSentinel(); i++) {
-    if (table[i].isDummy()) {
-      continue;
-    }
-    JSAtom* atom = AtomStateOffsetToName(names, table[i].atomOffset);
-    MOZ_ASSERT(atom);
-    if (name == atom) {
-      return &table[i];
-    }
-  }
-
-  return nullptr;
-}
-
-/*
- * Table of standard classes, indexed by JSProtoKey. For entries where the
- * JSProtoKey does not correspond to a class with a meaningful constructor, we
- * insert a null entry into the table.
- */
-#define STD_NAME_ENTRY(name, init, clasp) {NAME_OFFSET(name), JSProto_##name},
-#define STD_DUMMY_ENTRY(name, init, dummy) {0, JSProto_Null},
-static const JSStdName standard_class_names[] = {
-    JS_FOR_PROTOTYPES(STD_NAME_ENTRY, STD_DUMMY_ENTRY){0, JSProto_LIMIT}};
-
-/*
- * Table of top-level function and constant names and the JSProtoKey of the
- * standard class that initializes them.
- */
-static const JSStdName builtin_property_names[] = {
-    {NAME_OFFSET(eval), JSProto_Object},
-
-    /* Global properties and functions defined by the Number class. */
-    {NAME_OFFSET(NaN), JSProto_Number},
-    {NAME_OFFSET(Infinity), JSProto_Number},
-    {NAME_OFFSET(isNaN), JSProto_Number},
-    {NAME_OFFSET(isFinite), JSProto_Number},
-    {NAME_OFFSET(parseFloat), JSProto_Number},
-    {NAME_OFFSET(parseInt), JSProto_Number},
-
-    /* String global functions. */
-    {NAME_OFFSET(escape), JSProto_String},
-    {NAME_OFFSET(unescape), JSProto_String},
-    {NAME_OFFSET(decodeURI), JSProto_String},
-    {NAME_OFFSET(encodeURI), JSProto_String},
-    {NAME_OFFSET(decodeURIComponent), JSProto_String},
-    {NAME_OFFSET(encodeURIComponent), JSProto_String},
-    {NAME_OFFSET(uneval), JSProto_String},
-
-    {0, JSProto_LIMIT}};
-
-JS_PUBLIC_API bool JS_ResolveStandardClass(JSContext* cx, HandleObject obj,
-                                           HandleId id, bool* resolved) {
-  const JSStdName* stdnm;
-
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(obj, id);
-
-  Handle<GlobalObject*> global = obj.as<GlobalObject>();
-  *resolved = false;
-
-  if (!JSID_IS_ATOM(id)) {
-    return true;
-  }
-
-  /* Check whether we're resolving 'undefined', and define it if so. */
-  JSAtom* idAtom = JSID_TO_ATOM(id);
-  if (idAtom == cx->names().undefined) {
-    *resolved = true;
-    return DefineDataProperty(
-        cx, global, id, UndefinedHandleValue,
-        JSPROP_PERMANENT | JSPROP_READONLY | JSPROP_RESOLVING);
-  }
-
-  // Resolve a "globalThis" self-referential property if necessary.
-  if (idAtom == cx->names().globalThis) {
-    return GlobalObject::maybeResolveGlobalThis(cx, global, resolved);
-  }
-
-  /* Try for class constructors/prototypes named by well-known atoms. */
-  stdnm = LookupStdName(cx->names(), idAtom, standard_class_names);
-
-  /* Try less frequently used top-level functions and constants. */
-  if (!stdnm) {
-    stdnm = LookupStdName(cx->names(), idAtom, builtin_property_names);
-  }
-
-  if (stdnm && GlobalObject::skipDeselectedConstructor(cx, stdnm->key)) {
-    stdnm = nullptr;
-  }
-
-  // If this class is anonymous, then it doesn't exist as a global
-  // property, so we won't resolve anything.
-  JSProtoKey key = stdnm ? stdnm->key : JSProto_Null;
-  if (key != JSProto_Null) {
-    const Class* clasp = ProtoKeyToClass(key);
-    if (!clasp || clasp->specShouldDefineConstructor()) {
-      if (!GlobalObject::ensureConstructor(cx, global, key)) {
-        return false;
-      }
-
-      *resolved = true;
-      return true;
-    }
-  }
-
-  // There is no such property to resolve. An ordinary resolve hook would
-  // just return true at this point. But the global object is special in one
-  // more way: its prototype chain is lazily initialized. That is,
-  // global->getProto() might be null right now because we haven't created
-  // Object.prototype yet. Force it now.
-  return GlobalObject::getOrCreateObjectPrototype(cx, global);
-}
-
-JS_PUBLIC_API bool JS_MayResolveStandardClass(const JSAtomState& names, jsid id,
-                                              JSObject* maybeObj) {
-  MOZ_ASSERT_IF(maybeObj, maybeObj->is<GlobalObject>());
-
-  // The global object's resolve hook is special: JS_ResolveStandardClass
-  // initializes the prototype chain lazily. Only attempt to optimize here
-  // if we know the prototype chain has been initialized.
-  if (!maybeObj || !maybeObj->staticPrototype()) {
-    return true;
-  }
-
-  if (!JSID_IS_ATOM(id)) {
-    return false;
-  }
-
-  JSAtom* atom = JSID_TO_ATOM(id);
-
-  // This will return true even for deselected constructors.  (To do
-  // better, we need a JSContext here; it's fine as it is.)
-
-  return atom == names.undefined || atom == names.globalThis ||
-         LookupStdName(names, atom, standard_class_names) ||
-         LookupStdName(names, atom, builtin_property_names);
-}
-
-JS_PUBLIC_API bool JS_EnumerateStandardClasses(JSContext* cx,
-                                               HandleObject obj) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(obj);
-  Handle<GlobalObject*> global = obj.as<GlobalObject>();
-  return GlobalObject::initStandardClasses(cx, global);
-}
+#include "js/Modules.h"
 
-static bool EnumerateStandardClassesInTable(JSContext* cx,
-                                            Handle<GlobalObject*> global,
-                                            MutableHandleIdVector properties,
-                                            const JSStdName* table,
-                                            bool includeResolved) {
-  for (unsigned i = 0; !table[i].isSentinel(); i++) {
-    if (table[i].isDummy()) {
-      continue;
-    }
-
-    JSProtoKey key = table[i].key;
-
-    // If the standard class has been resolved, the properties have been
-    // defined on the global so we don't need to add them here.
-    if (!includeResolved && global->isStandardClassResolved(key)) {
-      continue;
-    }
-
-    if (GlobalObject::skipDeselectedConstructor(cx, key)) {
-      continue;
-    }
-
-    if (const Class* clasp = ProtoKeyToClass(key)) {
-      if (!clasp->specShouldDefineConstructor()) {
-        continue;
-      }
-    }
-
-    jsid id = NameToId(AtomStateOffsetToName(cx->names(), table[i].atomOffset));
-    if (!properties.append(id)) {
-      return false;
-    }
-  }
-
-  return true;
-}
-
-static bool EnumerateStandardClasses(JSContext* cx, JS::HandleObject obj,
-                                     JS::MutableHandleIdVector properties,
-                                     bool enumerableOnly,
-                                     bool includeResolved) {
-  if (enumerableOnly) {
-    // There are no enumerable standard classes and "undefined" is
-    // not enumerable.
-    return true;
-  }
-
-  Handle<GlobalObject*> global = obj.as<GlobalObject>();
-
-  // It's fine to always append |undefined| here, it's non-configurable and
-  // the enumeration code filters duplicates.
-  if (!properties.append(NameToId(cx->names().undefined))) {
-    return false;
-  }
-
-  if (!EnumerateStandardClassesInTable(cx, global, properties,
-                                       standard_class_names, includeResolved)) {
-    return false;
-  }
-  if (!EnumerateStandardClassesInTable(
-          cx, global, properties, builtin_property_names, includeResolved)) {
-    return false;
-  }
-
-  return true;
-}
-
-JS_PUBLIC_API bool JS_NewEnumerateStandardClasses(
-    JSContext* cx, JS::HandleObject obj, JS::MutableHandleIdVector properties,
-    bool enumerableOnly) {
-  return EnumerateStandardClasses(cx, obj, properties, enumerableOnly, false);
-}
-
-JS_PUBLIC_API bool JS_NewEnumerateStandardClassesIncludingResolved(
-    JSContext* cx, JS::HandleObject obj, JS::MutableHandleIdVector properties,
-    bool enumerableOnly) {
-  return EnumerateStandardClasses(cx, obj, properties, enumerableOnly, true);
-}
-
-JS_PUBLIC_API bool JS_GetClassObject(JSContext* cx, JSProtoKey key,
-                                     MutableHandleObject objp) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  JSObject* obj = GlobalObject::getOrCreateConstructor(cx, key);
-  if (!obj) {
-    return false;
-  }
-  objp.set(obj);
-  return true;
-}
-
-JS_PUBLIC_API bool JS_GetClassPrototype(JSContext* cx, JSProtoKey key,
-                                        MutableHandleObject objp) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  JSObject* proto = GlobalObject::getOrCreatePrototype(cx, key);
-  if (!proto) {
-    return false;
-  }
-  objp.set(proto);
-  return true;
-}
-
-namespace JS {
-
-JS_PUBLIC_API void ProtoKeyToId(JSContext* cx, JSProtoKey key,
-                                MutableHandleId idp) {
-  idp.set(NameToId(ClassName(key, cx)));
-}
-
-} /* namespace JS */
-
-JS_PUBLIC_API JSProtoKey JS_IdToProtoKey(JSContext* cx, HandleId id) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(id);
-
-  if (!JSID_IS_ATOM(id)) {
-    return JSProto_Null;
-  }
-
-  JSAtom* atom = JSID_TO_ATOM(id);
-  const JSStdName* stdnm =
-      LookupStdName(cx->names(), atom, standard_class_names);
-  if (!stdnm) {
-    return JSProto_Null;
-  }
-
-  if (GlobalObject::skipDeselectedConstructor(cx, stdnm->key)) {
-    return JSProto_Null;
-  }
-
-  MOZ_ASSERT(MOZ_ARRAY_LENGTH(standard_class_names) == JSProto_LIMIT + 1);
-  return static_cast<JSProtoKey>(stdnm - standard_class_names);
-}
-
-extern JS_PUBLIC_API bool JS_IsGlobalObject(JSObject* obj) {
-  return obj->is<GlobalObject>();
-}
-
-extern JS_PUBLIC_API JSObject* JS_GlobalLexicalEnvironment(JSObject* obj) {
-  return &obj->as<GlobalObject>().lexicalEnvironment();
-}
-
-extern JS_PUBLIC_API bool JS_HasExtensibleLexicalEnvironment(JSObject* obj) {
-  return obj->is<GlobalObject>() ||
-         ObjectRealm::get(obj).getNonSyntacticLexicalEnvironment(obj);
-}
-
-extern JS_PUBLIC_API JSObject* JS_ExtensibleLexicalEnvironment(JSObject* obj) {
-  JSObject* lexical = nullptr;
-  if (obj->is<GlobalObject>()) {
-    lexical = JS_GlobalLexicalEnvironment(obj);
-  } else {
-    lexical = ObjectRealm::get(obj).getNonSyntacticLexicalEnvironment(obj);
-  }
-  MOZ_ASSERT(lexical);
-  return lexical;
-}
-
-JS_PUBLIC_API JSObject* JS::CurrentGlobalOrNull(JSContext* cx) {
-  AssertHeapIsIdleOrIterating();
-  CHECK_THREAD(cx);
-  if (!cx->realm()) {
-    return nullptr;
-  }
-  return cx->global();
-}
-
-JS_PUBLIC_API JSObject* JS::GetNonCCWObjectGlobal(JSObject* obj) {
-  AssertHeapIsIdleOrIterating();
-  MOZ_DIAGNOSTIC_ASSERT(!IsCrossCompartmentWrapper(obj));
-  return &obj->nonCCWGlobal();
-}
-
-JS_PUBLIC_API bool JS::detail::ComputeThis(JSContext* cx, Value* vp,
-                                           MutableHandleObject thisObject) {
-  AssertHeapIsIdle();
-  cx->check(vp[0], vp[1]);
-
-  MutableHandleValue thisv = MutableHandleValue::fromMarkedLocation(&vp[1]);
-  if (!BoxNonStrictThis(cx, thisv, thisv)) {
-    return false;
-  }
-
-  thisObject.set(&thisv.toObject());
-  return true;
-}
-
-static bool gProfileTimelineRecordingEnabled = false;
-
-JS_PUBLIC_API void JS::SetProfileTimelineRecordingEnabled(bool enabled) {
-  gProfileTimelineRecordingEnabled = enabled;
-}
-
-JS_PUBLIC_API bool JS::IsProfileTimelineRecordingEnabled() {
-  return gProfileTimelineRecordingEnabled;
-}
-
-JS_PUBLIC_API void* JS_malloc(JSContext* cx, size_t nbytes) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  return static_cast<void*>(cx->maybe_pod_malloc<uint8_t>(nbytes));
-}
-
-JS_PUBLIC_API void* JS_realloc(JSContext* cx, void* p, size_t oldBytes,
-                               size_t newBytes) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  return static_cast<void*>(cx->maybe_pod_realloc<uint8_t>(
-      static_cast<uint8_t*>(p), oldBytes, newBytes));
-}
-
-JS_PUBLIC_API void JS_free(JSContext* cx, void* p) { return js_free(p); }
-
-JS_PUBLIC_API void* JS_string_malloc(JSContext* cx, size_t nbytes) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  return static_cast<void*>(
-      cx->maybe_pod_malloc<uint8_t>(nbytes, js::StringBufferArena));
-}
-
-JS_PUBLIC_API void* JS_string_realloc(JSContext* cx, void* p, size_t oldBytes,
-                                      size_t newBytes) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  return static_cast<void*>(cx->maybe_pod_realloc<uint8_t>(
-      static_cast<uint8_t*>(p), oldBytes, newBytes, js::StringBufferArena));
-}
-
-JS_PUBLIC_API void JS_string_free(JSContext* cx, void* p) { return js_free(p); }
-
-JS_PUBLIC_API void JS_freeop(JSFreeOp* fop, void* p) {
-  return FreeOp::get(fop)->free_(p);
-}
-
-JS_PUBLIC_API void JS::AddAssociatedMemory(JSObject* obj, size_t nbytes,
-                                           JS::MemoryUse use) {
-  MOZ_ASSERT(obj);
-  if (!nbytes) {
-    return;
-  }
-
-  Zone* zone = obj->zone();
-  zone->updateMallocCounter(nbytes);
-  zone->addCellMemory(obj, nbytes, js::MemoryUse(use));
-  zone->runtimeFromMainThread()->gc.maybeAllocTriggerZoneGC(zone);
-}
-
-JS_PUBLIC_API void JS::RemoveAssociatedMemory(JSObject* obj, size_t nbytes,
-                                              JS::MemoryUse use) {
-  MOZ_ASSERT(obj);
-  if (!nbytes) {
-    return;
-  }
-
-  obj->zoneFromAnyThread()->removeCellMemory(obj, nbytes, js::MemoryUse(use));
-}
-
-#undef JS_AddRoot
-
-JS_PUBLIC_API bool JS_AddExtraGCRootsTracer(JSContext* cx,
-                                            JSTraceDataOp traceOp, void* data) {
-  return cx->runtime()->gc.addBlackRootsTracer(traceOp, data);
-}
-
-JS_PUBLIC_API void JS_RemoveExtraGCRootsTracer(JSContext* cx,
-                                               JSTraceDataOp traceOp,
-                                               void* data) {
-  return cx->runtime()->gc.removeBlackRootsTracer(traceOp, data);
-}
-
-JS_PUBLIC_API bool JS::IsIdleGCTaskNeeded(JSRuntime* rt) {
-  // Currently, we only collect nursery during idle time.
-  return rt->gc.nursery().shouldCollect();
-}
-
-JS_PUBLIC_API void JS::RunIdleTimeGCTask(JSRuntime* rt) {
-  gc::GCRuntime& gc = rt->gc;
-  if (gc.nursery().shouldCollect()) {
-    gc.minorGC(JS::GCReason::IDLE_TIME_COLLECTION);
-  }
-}
-
-JS_PUBLIC_API void JS_GC(JSContext* cx, JS::GCReason reason) {
-  AssertHeapIsIdle();
-  JS::PrepareForFullGC(cx);
-  cx->runtime()->gc.gc(GC_NORMAL, reason);
-}
-
-JS_PUBLIC_API void JS_MaybeGC(JSContext* cx) {
-  gc::GCRuntime& gc = cx->runtime()->gc;
-  gc.maybeGC(cx->zone());
-}
-
-JS_PUBLIC_API void JS_SetGCCallback(JSContext* cx, JSGCCallback cb,
-                                    void* data) {
-  AssertHeapIsIdle();
-  cx->runtime()->gc.setGCCallback(cb, data);
-}
-
-JS_PUBLIC_API void JS_SetObjectsTenuredCallback(JSContext* cx,
-                                                JSObjectsTenuredCallback cb,
-                                                void* data) {
-  AssertHeapIsIdle();
-  cx->runtime()->gc.setObjectsTenuredCallback(cb, data);
-}
-
-JS_PUBLIC_API bool JS_AddFinalizeCallback(JSContext* cx, JSFinalizeCallback cb,
-                                          void* data) {
-  AssertHeapIsIdle();
-  return cx->runtime()->gc.addFinalizeCallback(cb, data);
-}
-
-JS_PUBLIC_API void JS_RemoveFinalizeCallback(JSContext* cx,
-                                             JSFinalizeCallback cb) {
-  cx->runtime()->gc.removeFinalizeCallback(cb);
-}
-
-JS_PUBLIC_API bool JS_AddWeakPointerZonesCallback(JSContext* cx,
-                                                  JSWeakPointerZonesCallback cb,
-                                                  void* data) {
-  AssertHeapIsIdle();
-  return cx->runtime()->gc.addWeakPointerZonesCallback(cb, data);
-}
-
-JS_PUBLIC_API void JS_RemoveWeakPointerZonesCallback(
-    JSContext* cx, JSWeakPointerZonesCallback cb) {
-  cx->runtime()->gc.removeWeakPointerZonesCallback(cb);
-}
-
-JS_PUBLIC_API bool JS_AddWeakPointerCompartmentCallback(
-    JSContext* cx, JSWeakPointerCompartmentCallback cb, void* data) {
-  AssertHeapIsIdle();
-  return cx->runtime()->gc.addWeakPointerCompartmentCallback(cb, data);
-}
-
-JS_PUBLIC_API void JS_RemoveWeakPointerCompartmentCallback(
-    JSContext* cx, JSWeakPointerCompartmentCallback cb) {
-  cx->runtime()->gc.removeWeakPointerCompartmentCallback(cb);
-}
-
-JS_PUBLIC_API void JS_UpdateWeakPointerAfterGC(JS::Heap<JSObject*>* objp) {
-  JS_UpdateWeakPointerAfterGCUnbarriered(objp->unsafeGet());
-}
-
-JS_PUBLIC_API void JS_UpdateWeakPointerAfterGCUnbarriered(JSObject** objp) {
-  if (IsAboutToBeFinalizedUnbarriered(objp)) {
-    *objp = nullptr;
-  }
-}
-
-JS_PUBLIC_API void JS_SetGCParameter(JSContext* cx, JSGCParamKey key,
-                                     uint32_t value) {
-  cx->runtime()->gc.waitBackgroundSweepEnd();
-  AutoLockGC lock(cx->runtime());
-  MOZ_ALWAYS_TRUE(cx->runtime()->gc.setParameter(key, value, lock));
-}
-
-JS_PUBLIC_API void JS_ResetGCParameter(JSContext* cx, JSGCParamKey key) {
-  cx->runtime()->gc.waitBackgroundSweepEnd();
-  AutoLockGC lock(cx->runtime());
-  cx->runtime()->gc.resetParameter(key, lock);
-}
-
-JS_PUBLIC_API uint32_t JS_GetGCParameter(JSContext* cx, JSGCParamKey key) {
-  AutoLockGC lock(cx->runtime());
-  return cx->runtime()->gc.getParameter(key, lock);
-}
-
-JS_PUBLIC_API void JS_SetGCParametersBasedOnAvailableMemory(JSContext* cx,
-                                                            uint32_t availMem) {
-  struct JSGCConfig {
-    JSGCParamKey key;
-    uint32_t value;
-  };
-
-  static const JSGCConfig minimal[] = {
-      {JSGC_MAX_MALLOC_BYTES, 6 * 1024 * 1024},
-      {JSGC_SLICE_TIME_BUDGET, 30},
-      {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1500},
-      {JSGC_HIGH_FREQUENCY_HIGH_LIMIT, 40},
-      {JSGC_HIGH_FREQUENCY_LOW_LIMIT, 0},
-      {JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MAX, 300},
-      {JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MIN, 120},
-      {JSGC_LOW_FREQUENCY_HEAP_GROWTH, 120},
-      {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1500},
-      {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1500},
-      {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1500},
-      {JSGC_ALLOCATION_THRESHOLD, 1},
-      {JSGC_MODE, JSGC_MODE_ZONE_INCREMENTAL}};
-
-  static const JSGCConfig nominal[] = {
-      {JSGC_MAX_MALLOC_BYTES, 6 * 1024 * 1024},
-      {JSGC_SLICE_TIME_BUDGET, 30},
-      {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1000},
-      {JSGC_HIGH_FREQUENCY_HIGH_LIMIT, 500},
-      {JSGC_HIGH_FREQUENCY_LOW_LIMIT, 100},
-      {JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MAX, 300},
-      {JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MIN, 150},
-      {JSGC_LOW_FREQUENCY_HEAP_GROWTH, 150},
-      {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1500},
-      {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1500},
-      {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1500},
-      {JSGC_ALLOCATION_THRESHOLD, 30},
-      {JSGC_MODE, JSGC_MODE_ZONE}};
-
-  const auto& configSet = availMem > 512 ? nominal : minimal;
-  for (const auto& config : configSet) {
-    JS_SetGCParameter(cx, config.key, config.value);
-  }
-}
-
-JS_PUBLIC_API JSString* JS_NewExternalString(JSContext* cx,
-                                             const char16_t* chars,
-                                             size_t length,
-                                             const JSStringFinalizer* fin) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  JSString* s = JSExternalString::new_(cx, chars, length, fin);
-  return s;
-}
-
-JS_PUBLIC_API JSString* JS_NewMaybeExternalString(JSContext* cx,
-                                                  const char16_t* chars,
-                                                  size_t length,
-                                                  const JSStringFinalizer* fin,
-                                                  bool* allocatedExternal) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  return NewMaybeExternalString(cx, chars, length, fin, allocatedExternal);
-}
-
-extern JS_PUBLIC_API bool JS_IsExternalString(JSString* str) {
-  return str->isExternal();
-}
-
-extern JS_PUBLIC_API const JSStringFinalizer* JS_GetExternalStringFinalizer(
-    JSString* str) {
-  return str->asExternal().externalFinalizer();
-}
-
-static void SetNativeStackQuotaAndLimit(JSContext* cx, JS::StackKind kind,
-                                        size_t stackSize) {
-  cx->nativeStackQuota[kind] = stackSize;
+#include "mozilla/Assertions.h"  // MOZ_ASSERT
 
-#if JS_STACK_GROWTH_DIRECTION > 0
-  if (stackSize == 0) {
-    cx->nativeStackLimit[kind] = UINTPTR_MAX;
-  } else {
-    MOZ_ASSERT(cx->nativeStackBase <= size_t(-1) - stackSize);
-    cx->nativeStackLimit[kind] = cx->nativeStackBase + stackSize - 1;
-  }
-#else
-  if (stackSize == 0) {
-    cx->nativeStackLimit[kind] = 0;
-  } else {
-    MOZ_ASSERT(cx->nativeStackBase >= stackSize);
-    cx->nativeStackLimit[kind] = cx->nativeStackBase - (stackSize - 1);
-  }
-#endif
-}
-
-JS_PUBLIC_API void JS_SetNativeStackQuota(JSContext* cx,
-                                          size_t systemCodeStackSize,
-                                          size_t trustedScriptStackSize,
-                                          size_t untrustedScriptStackSize) {
-  MOZ_ASSERT(!cx->activation());
-
-  if (!trustedScriptStackSize) {
-    trustedScriptStackSize = systemCodeStackSize;
-  } else {
-    MOZ_ASSERT(trustedScriptStackSize < systemCodeStackSize);
-  }
-
-  if (!untrustedScriptStackSize) {
-    untrustedScriptStackSize = trustedScriptStackSize;
-  } else {
-    MOZ_ASSERT(untrustedScriptStackSize < trustedScriptStackSize);
-  }
-
-  SetNativeStackQuotaAndLimit(cx, JS::StackForSystemCode, systemCodeStackSize);
-  SetNativeStackQuotaAndLimit(cx, JS::StackForTrustedScript,
-                              trustedScriptStackSize);
-  SetNativeStackQuotaAndLimit(cx, JS::StackForUntrustedScript,
-                              untrustedScriptStackSize);
-
-  if (cx->isMainThreadContext()) {
-    cx->initJitStackLimit();
-  }
-}
-
-/************************************************************************/
-
-JS_PUBLIC_API bool JS_ValueToId(JSContext* cx, HandleValue value,
-                                MutableHandleId idp) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(value);
-  return ValueToId<CanGC>(cx, value, idp);
-}
-
-JS_PUBLIC_API bool JS_StringToId(JSContext* cx, HandleString string,
-                                 MutableHandleId idp) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(string);
-  RootedValue value(cx, StringValue(string));
-  return ValueToId<CanGC>(cx, value, idp);
-}
-
-JS_PUBLIC_API bool JS_IdToValue(JSContext* cx, jsid id, MutableHandleValue vp) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(id);
-  vp.set(IdToValue(id));
-  cx->check(vp);
-  return true;
-}
-
-JS_PUBLIC_API bool JS::ToPrimitive(JSContext* cx, HandleObject obj, JSType hint,
-                                   MutableHandleValue vp) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(obj);
-  MOZ_ASSERT(obj != nullptr);
-  MOZ_ASSERT(hint == JSTYPE_UNDEFINED || hint == JSTYPE_STRING ||
-             hint == JSTYPE_NUMBER);
-  vp.setObject(*obj);
-  return ToPrimitiveSlow(cx, hint, vp);
-}
-
-JS_PUBLIC_API bool JS::GetFirstArgumentAsTypeHint(JSContext* cx, CallArgs args,
-                                                  JSType* result) {
-  if (!args.get(0).isString()) {
-    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
-                              JSMSG_NOT_EXPECTED_TYPE, "Symbol.toPrimitive",
-                              "\"string\", \"number\", or \"default\"",
-                              InformalValueTypeName(args.get(0)));
-    return false;
-  }
-
-  RootedString str(cx, args.get(0).toString());
-  bool match;
-
-  if (!EqualStrings(cx, str, cx->names().default_, &match)) {
-    return false;
-  }
-  if (match) {
-    *result = JSTYPE_UNDEFINED;
-    return true;
-  }
-
-  if (!EqualStrings(cx, str, cx->names().string, &match)) {
-    return false;
-  }
-  if (match) {
-    *result = JSTYPE_STRING;
-    return true;
-  }
-
-  if (!EqualStrings(cx, str, cx->names().number, &match)) {
-    return false;
-  }
-  if (match) {
-    *result = JSTYPE_NUMBER;
-    return true;
-  }
-
-  UniqueChars bytes;
-  const char* source = ValueToSourceForError(cx, args.get(0), bytes);
-  if (!source) {
-    ReportOutOfMemory(cx);
-    return false;
-  }
-
-  JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
-                           JSMSG_NOT_EXPECTED_TYPE, "Symbol.toPrimitive",
-                           "\"string\", \"number\", or \"default\"", source);
-  return false;
-}
-
-JS_PUBLIC_API JSObject* JS_InitClass(JSContext* cx, HandleObject obj,
-                                     HandleObject parent_proto,
-                                     const JSClass* clasp, JSNative constructor,
-                                     unsigned nargs, const JSPropertySpec* ps,
-                                     const JSFunctionSpec* fs,
-                                     const JSPropertySpec* static_ps,
-                                     const JSFunctionSpec* static_fs) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(obj, parent_proto);
-  return InitClass(cx, obj, parent_proto, Valueify(clasp), constructor, nargs,
-                   ps, fs, static_ps, static_fs);
-}
-
-JS_PUBLIC_API bool JS_LinkConstructorAndPrototype(JSContext* cx,
-                                                  HandleObject ctor,
-                                                  HandleObject proto) {
-  return LinkConstructorAndPrototype(cx, ctor, proto);
-}
-
-JS_PUBLIC_API const JSClass* JS_GetClass(JSObject* obj) {
-  return obj->getJSClass();
-}
-
-JS_PUBLIC_API bool JS_InstanceOf(JSContext* cx, HandleObject obj,
-                                 const JSClass* clasp, CallArgs* args) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-#ifdef DEBUG
-  if (args) {
-    cx->check(obj);
-    cx->check(args->thisv(), args->calleev());
-  }
-#endif
-  if (!obj || obj->getJSClass() != clasp) {
-    if (args) {
-      ReportIncompatibleMethod(cx, *args, Valueify(clasp));
-    }
-    return false;
-  }
-  return true;
-}
-
-JS_PUBLIC_API bool JS_HasInstance(JSContext* cx, HandleObject obj,
-                                  HandleValue value, bool* bp) {
-  AssertHeapIsIdle();
-  cx->check(obj, value);
-  return HasInstance(cx, obj, value, bp);
-}
-
-JS_PUBLIC_API void* JS_GetPrivate(JSObject* obj) {
-  /* This function can be called by a finalizer. */
-  return obj->as<NativeObject>().getPrivate();
-}
-
-JS_PUBLIC_API void JS_SetPrivate(JSObject* obj, void* data) {
-  /* This function can be called by a finalizer. */
-  obj->as<NativeObject>().setPrivate(data);
-}
-
-JS_PUBLIC_API void* JS_GetInstancePrivate(JSContext* cx, HandleObject obj,
-                                          const JSClass* clasp,
-                                          CallArgs* args) {
-  if (!JS_InstanceOf(cx, obj, clasp, args)) {
-    return nullptr;
-  }
-  return obj->as<NativeObject>().getPrivate();
-}
-
-JS_PUBLIC_API JSObject* JS_GetConstructor(JSContext* cx, HandleObject proto) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(proto);
-
-  RootedValue cval(cx);
-  if (!GetProperty(cx, proto, proto, cx->names().constructor, &cval)) {
-    return nullptr;
-  }
-  if (!IsFunctionObject(cval)) {
-    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
-                              JSMSG_NO_CONSTRUCTOR, proto->getClass()->name);
-    return nullptr;
-  }
-  return &cval.toObject();
-}
-
-bool JS::RealmBehaviors::extraWarnings(JSContext* cx) const {
-  return extraWarningsOverride_.get(cx->options().extraWarnings());
-}
-
-JS::RealmCreationOptions&
-JS::RealmCreationOptions::setNewCompartmentInSystemZone() {
-  compSpec_ = CompartmentSpecifier::NewCompartmentInSystemZone;
-  comp_ = nullptr;
-  return *this;
-}
+#include <stdint.h>  // uint32_t
 
-JS::RealmCreationOptions&
-JS::RealmCreationOptions::setNewCompartmentInExistingZone(JSObject* obj) {
-  compSpec_ = CompartmentSpecifier::NewCompartmentInExistingZone;
-  zone_ = obj->zone();
-  return *this;
-}
-
-JS::RealmCreationOptions& JS::RealmCreationOptions::setExistingCompartment(
-    JSObject* obj) {
-  compSpec_ = CompartmentSpecifier::ExistingCompartment;
-  comp_ = obj->compartment();
-  return *this;
-}
-
-JS::RealmCreationOptions& JS::RealmCreationOptions::setExistingCompartment(
-    JS::Compartment* compartment) {
-  compSpec_ = CompartmentSpecifier::ExistingCompartment;
-  comp_ = compartment;
-  return *this;
-}
-
-JS::RealmCreationOptions& JS::RealmCreationOptions::setNewCompartmentAndZone() {
-  compSpec_ = CompartmentSpecifier::NewCompartmentAndZone;
-  comp_ = nullptr;
-  return *this;
-}
-
-const JS::RealmCreationOptions& JS::RealmCreationOptionsRef(Realm* realm) {
-  return realm->creationOptions();
-}
-
-const JS::RealmCreationOptions& JS::RealmCreationOptionsRef(JSContext* cx) {
-  return cx->realm()->creationOptions();
-}
-
-bool JS::RealmCreationOptions::getSharedMemoryAndAtomicsEnabled() const {
-  return sharedMemoryAndAtomics_;
-}
-
-JS::RealmCreationOptions&
-JS::RealmCreationOptions::setSharedMemoryAndAtomicsEnabled(bool flag) {
-  sharedMemoryAndAtomics_ = flag;
-  return *this;
-}
-
-JS::RealmBehaviors& JS::RealmBehaviorsRef(JS::Realm* realm) {
-  return realm->behaviors();
-}
-
-JS::RealmBehaviors& JS::RealmBehaviorsRef(JSContext* cx) {
-  return cx->realm()->behaviors();
-}
-
-JS_PUBLIC_API JSObject* JS_NewGlobalObject(JSContext* cx, const JSClass* clasp,
-                                           JSPrincipals* principals,
-                                           JS::OnNewGlobalHookOption hookOption,
-                                           const JS::RealmOptions& options) {
-  MOZ_RELEASE_ASSERT(
-      cx->runtime()->hasInitializedSelfHosting(),
-      "Must call JS::InitSelfHostedCode() before creating a global");
-
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-
-  return GlobalObject::new_(cx, Valueify(clasp), principals, hookOption,
-                            options);
-}
-
-JS_PUBLIC_API void JS_GlobalObjectTraceHook(JSTracer* trc, JSObject* global) {
-  GlobalObject* globalObj = &global->as<GlobalObject>();
-  Realm* globalRealm = globalObj->realm();
-
-  // Off thread parsing and compilation tasks create a dummy global which is
-  // then merged back into the host realm. Since it used to be a global, it
-  // will still have this trace hook, but it does not have a meaning relative
-  // to its new realm. We can safely skip it.
-  //
-  // Similarly, if we GC when creating the global, we may not have set that
-  // global's realm's global pointer yet. In this case, the realm will not yet
-  // contain anything that needs to be traced.
-  if (globalRealm->unsafeUnbarrieredMaybeGlobal() != globalObj) {
-    return;
-  }
-
-  // Trace the realm for any GC things that should only stick around if we
-  // know the global is live.
-  globalRealm->traceGlobal(trc);
-
-  if (JSTraceOp trace = globalRealm->creationOptions().getTrace()) {
-    trace(trc, global);
-  }
-}
-
-const JSClassOps JS::DefaultGlobalClassOps = {nullptr,  // addProperty
-                                              nullptr,  // deleteProperty
-                                              nullptr,  // enumerate
-                                              JS_NewEnumerateStandardClasses,
-                                              JS_ResolveStandardClass,
-                                              JS_MayResolveStandardClass,
-                                              nullptr,  // finalize
-                                              nullptr,  // call
-                                              nullptr,  // hasInstance
-                                              nullptr,  // construct
-                                              JS_GlobalObjectTraceHook};
-
-JS_PUBLIC_API void JS_FireOnNewGlobalObject(JSContext* cx,
-                                            JS::HandleObject global) {
-  // This hook is infallible, because we don't really want arbitrary script
-  // to be able to throw errors during delicate global creation routines.
-  // This infallibility will eat OOM and slow script, but if that happens
-  // we'll likely run up into them again soon in a fallible context.
-  cx->check(global);
-  Rooted<js::GlobalObject*> globalObject(cx, &global->as<GlobalObject>());
-  Debugger::onNewGlobalObject(cx, globalObject);
-}
-
-JS_PUBLIC_API JSObject* JS_NewObject(JSContext* cx, const JSClass* jsclasp) {
-  MOZ_ASSERT(!cx->zone()->isAtomsZone());
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-
-  const Class* clasp = Valueify(jsclasp);
-  if (!clasp) {
-    clasp = &PlainObject::class_; /* default class is Object */
-  }
-
-  MOZ_ASSERT(clasp != &JSFunction::class_);
-  MOZ_ASSERT(!(clasp->flags & JSCLASS_IS_GLOBAL));
-
-  return NewBuiltinClassInstance(cx, clasp);
-}
-
-JS_PUBLIC_API JSObject* JS_NewObjectWithGivenProto(JSContext* cx,
-                                                   const JSClass* jsclasp,
-                                                   HandleObject proto) {
-  MOZ_ASSERT(!cx->zone()->isAtomsZone());
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(proto);
-
-  const Class* clasp = Valueify(jsclasp);
-  if (!clasp) {
-    clasp = &PlainObject::class_; /* default class is Object */
-  }
-
-  MOZ_ASSERT(clasp != &JSFunction::class_);
-  MOZ_ASSERT(!(clasp->flags & JSCLASS_IS_GLOBAL));
-
-  return NewObjectWithGivenProto(cx, clasp, proto);
-}
-
-JS_PUBLIC_API JSObject* JS_NewPlainObject(JSContext* cx) {
-  MOZ_ASSERT(!cx->zone()->isAtomsZone());
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-
-  return NewBuiltinClassInstance<PlainObject>(cx);
-}
-
-JS_PUBLIC_API JSObject* JS_NewObjectForConstructor(JSContext* cx,
-                                                   const JSClass* clasp,
-                                                   const CallArgs& args) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-
-  Value callee = args.calleev();
-  cx->check(callee);
-  RootedObject obj(cx, &callee.toObject());
-  return CreateThis(cx, Valueify(clasp), obj);
-}
-
-JS_PUBLIC_API bool JS_IsNative(JSObject* obj) { return obj->isNative(); }
-
-JS_PUBLIC_API void JS::AssertObjectBelongsToCurrentThread(JSObject* obj) {
-  JSRuntime* rt = obj->compartment()->runtimeFromAnyThread();
-  MOZ_RELEASE_ASSERT(CurrentThreadCanAccessRuntime(rt));
-}
-
-/*** Standard internal methods **********************************************/
-
-JS_PUBLIC_API bool JS_GetPrototype(JSContext* cx, HandleObject obj,
-                                   MutableHandleObject result) {
-  cx->check(obj);
-  return GetPrototype(cx, obj, result);
-}
-
-JS_PUBLIC_API bool JS_SetPrototype(JSContext* cx, HandleObject obj,
-                                   HandleObject proto) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(obj, proto);
-
-  return SetPrototype(cx, obj, proto);
-}
-
-JS_PUBLIC_API bool JS_GetPrototypeIfOrdinary(JSContext* cx, HandleObject obj,
-                                             bool* isOrdinary,
-                                             MutableHandleObject result) {
-  cx->check(obj);
-  return GetPrototypeIfOrdinary(cx, obj, isOrdinary, result);
-}
-
-JS_PUBLIC_API bool JS_IsExtensible(JSContext* cx, HandleObject obj,
-                                   bool* extensible) {
-  cx->check(obj);
-  return IsExtensible(cx, obj, extensible);
-}
-
-JS_PUBLIC_API bool JS_PreventExtensions(JSContext* cx, JS::HandleObject obj,
-                                        ObjectOpResult& result) {
-  cx->check(obj);
-  return PreventExtensions(cx, obj, result);
-}
-
-JS_PUBLIC_API bool JS_SetImmutablePrototype(JSContext* cx, JS::HandleObject obj,
-                                            bool* succeeded) {
-  cx->check(obj);
-  return SetImmutablePrototype(cx, obj, succeeded);
-}
-
-JS_PUBLIC_API bool JS_GetOwnPropertyDescriptorById(
-    JSContext* cx, HandleObject obj, HandleId id,
-    MutableHandle<PropertyDescriptor> desc) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(obj, id);
-
-  return GetOwnPropertyDescriptor(cx, obj, id, desc);
-}
-
-JS_PUBLIC_API bool JS_GetOwnPropertyDescriptor(
-    JSContext* cx, HandleObject obj, const char* name,
-    MutableHandle<PropertyDescriptor> desc) {
-  JSAtom* atom = Atomize(cx, name, strlen(name));
-  if (!atom) {
-    return false;
-  }
-  RootedId id(cx, AtomToId(atom));
-  return JS_GetOwnPropertyDescriptorById(cx, obj, id, desc);
-}
+#include "jsapi.h"    // js::AssertHeapIsIdle
+#include "jstypes.h"  // JS_PUBLIC_API
 
-JS_PUBLIC_API bool JS_GetOwnUCPropertyDescriptor(
-    JSContext* cx, HandleObject obj, const char16_t* name, size_t namelen,
-    MutableHandle<PropertyDescriptor> desc) {
-  JSAtom* atom = AtomizeChars(cx, name, namelen);
-  if (!atom) {
-    return false;
-  }
-  RootedId id(cx, AtomToId(atom));
-  return JS_GetOwnPropertyDescriptorById(cx, obj, id, desc);
-}
-
-JS_PUBLIC_API bool JS_GetPropertyDescriptorById(
-    JSContext* cx, HandleObject obj, HandleId id,
-    MutableHandle<PropertyDescriptor> desc) {
-  cx->check(obj, id);
-  return GetPropertyDescriptor(cx, obj, id, desc);
-}
-
-JS_PUBLIC_API bool JS_GetPropertyDescriptor(
-    JSContext* cx, HandleObject obj, const char* name,
-    MutableHandle<PropertyDescriptor> desc) {
-  JSAtom* atom = Atomize(cx, name, strlen(name));
-  if (!atom) {
-    return false;
-  }
-  RootedId id(cx, AtomToId(atom));
-  return JS_GetPropertyDescriptorById(cx, obj, id, desc);
-}
-
-JS_PUBLIC_API bool JS_GetUCPropertyDescriptor(
-    JSContext* cx, HandleObject obj, const char16_t* name, size_t namelen,
-    MutableHandle<PropertyDescriptor> desc) {
-  JSAtom* atom = AtomizeChars(cx, name, namelen);
-  if (!atom) {
-    return false;
-  }
-  RootedId id(cx, AtomToId(atom));
-  return JS_GetPropertyDescriptorById(cx, obj, id, desc);
-}
-
-static bool DefinePropertyByDescriptor(JSContext* cx, HandleObject obj,
-                                       HandleId id,
-                                       Handle<PropertyDescriptor> desc,
-                                       ObjectOpResult& result) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(obj, id, desc);
-  return DefineProperty(cx, obj, id, desc, result);
-}
-
-JS_PUBLIC_API bool JS_DefinePropertyById(JSContext* cx, HandleObject obj,
-                                         HandleId id,
-                                         Handle<PropertyDescriptor> desc,
-                                         ObjectOpResult& result) {
-  return DefinePropertyByDescriptor(cx, obj, id, desc, result);
-}
-
-JS_PUBLIC_API bool JS_DefinePropertyById(JSContext* cx, HandleObject obj,
-                                         HandleId id,
-                                         Handle<PropertyDescriptor> desc) {
-  ObjectOpResult result;
-  return DefinePropertyByDescriptor(cx, obj, id, desc, result) &&
-         result.checkStrict(cx, obj, id);
-}
-
-static bool DefineAccessorPropertyById(JSContext* cx, HandleObject obj,
-                                       HandleId id, HandleObject getter,
-                                       HandleObject setter, unsigned attrs) {
-  MOZ_ASSERT_IF(getter, attrs & JSPROP_GETTER);
-  MOZ_ASSERT_IF(setter, attrs & JSPROP_SETTER);
-
-  // JSPROP_READONLY has no meaning when accessors are involved. Ideally we'd
-  // throw if this happens, but we've accepted it for long enough that it's
-  // not worth trying to make callers change their ways. Just flip it off on
-  // its way through the API layer so that we can enforce this internally.
-  if (attrs & (JSPROP_GETTER | JSPROP_SETTER)) {
-    attrs &= ~JSPROP_READONLY;
-  }
-
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(obj, id, getter, setter);
-
-  return js::DefineAccessorProperty(cx, obj, id, getter, setter, attrs);
-}
-
-static bool DefineAccessorPropertyById(JSContext* cx, HandleObject obj,
-                                       HandleId id, const JSNativeWrapper& get,
-                                       const JSNativeWrapper& set,
-                                       unsigned attrs) {
-  // Getter/setter are both possibly-null JSNatives. Wrap them in JSFunctions.
-
-  MOZ_ASSERT(!(attrs & (JSPROP_GETTER | JSPROP_SETTER)));
-
-  RootedFunction getter(cx);
-  if (get.op) {
-    RootedAtom atom(cx, IdToFunctionName(cx, id, FunctionPrefixKind::Get));
-    if (!atom) {
-      return false;
-    }
-    getter = NewNativeFunction(cx, get.op, 0, atom);
-    if (!getter) {
-      return false;
-    }
-
-    if (get.info) {
-      getter->setJitInfo(get.info);
-    }
-
-    attrs |= JSPROP_GETTER;
-  }
-
-  RootedFunction setter(cx);
-  if (set.op) {
-    RootedAtom atom(cx, IdToFunctionName(cx, id, FunctionPrefixKind::Set));
-    if (!atom) {
-      return false;
-    }
-    setter = NewNativeFunction(cx, set.op, 1, atom);
-    if (!setter) {
-      return false;
-    }
-
-    if (set.info) {
-      setter->setJitInfo(set.info);
-    }
-
-    attrs |= JSPROP_SETTER;
-  }
-
-  return DefineAccessorPropertyById(cx, obj, id, getter, setter, attrs);
-}
-
-static bool DefineDataPropertyById(JSContext* cx, HandleObject obj, HandleId id,
-                                   HandleValue value, unsigned attrs) {
-  MOZ_ASSERT(!(attrs & (JSPROP_GETTER | JSPROP_SETTER)));
-
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(obj, id, value);
-
-  return js::DefineDataProperty(cx, obj, id, value, attrs);
-}
-
-/*
- * Wrapper functions to create wrappers with no corresponding JSJitInfo from API
- * function arguments.
- */
-static JSNativeWrapper NativeOpWrapper(Native native) {
-  JSNativeWrapper ret;
-  ret.op = native;
-  ret.info = nullptr;
-  return ret;
-}
-
-JS_PUBLIC_API bool JS_DefinePropertyById(JSContext* cx, HandleObject obj,
-                                         HandleId id, HandleValue value,
-                                         unsigned attrs) {
-  return DefineDataPropertyById(cx, obj, id, value, attrs);
-}
-
-JS_PUBLIC_API bool JS_DefinePropertyById(JSContext* cx, HandleObject obj,
-                                         HandleId id, Native getter,
-                                         Native setter, unsigned attrs) {
-  return DefineAccessorPropertyById(cx, obj, id, NativeOpWrapper(getter),
-                                    NativeOpWrapper(setter), attrs);
-}
-
-JS_PUBLIC_API bool JS_DefinePropertyById(JSContext* cx, HandleObject obj,
-                                         HandleId id, HandleObject getter,
-                                         HandleObject setter, unsigned attrs) {
-  return DefineAccessorPropertyById(cx, obj, id, getter, setter, attrs);
-}
-
-JS_PUBLIC_API bool JS_DefinePropertyById(JSContext* cx, HandleObject obj,
-                                         HandleId id, HandleObject valueArg,
-                                         unsigned attrs) {
-  RootedValue value(cx, ObjectValue(*valueArg));
-  return DefineDataPropertyById(cx, obj, id, value, attrs);
-}
-
-JS_PUBLIC_API bool JS_DefinePropertyById(JSContext* cx, HandleObject obj,
-                                         HandleId id, HandleString valueArg,
-                                         unsigned attrs) {
-  RootedValue value(cx, StringValue(valueArg));
-  return DefineDataPropertyById(cx, obj, id, value, attrs);
-}
-
-JS_PUBLIC_API bool JS_DefinePropertyById(JSContext* cx, HandleObject obj,
-                                         HandleId id, int32_t valueArg,
-                                         unsigned attrs) {
-  Value value = Int32Value(valueArg);
-  return DefineDataPropertyById(cx, obj, id,
-                                HandleValue::fromMarkedLocation(&value), attrs);
-}
-
-JS_PUBLIC_API bool JS_DefinePropertyById(JSContext* cx, HandleObject obj,
-                                         HandleId id, uint32_t valueArg,
-                                         unsigned attrs) {
-  Value value = NumberValue(valueArg);
-  return DefineDataPropertyById(cx, obj, id,
-                                HandleValue::fromMarkedLocation(&value), attrs);
-}
-
-JS_PUBLIC_API bool JS_DefinePropertyById(JSContext* cx, HandleObject obj,
-                                         HandleId id, double valueArg,
-                                         unsigned attrs) {
-  Value value = NumberValue(valueArg);
-  return DefineDataPropertyById(cx, obj, id,
-                                HandleValue::fromMarkedLocation(&value), attrs);
-}
-
-static bool DefineDataProperty(JSContext* cx, HandleObject obj,
-                               const char* name, HandleValue value,
-                               unsigned attrs) {
-  JSAtom* atom = Atomize(cx, name, strlen(name));
-  if (!atom) {
-    return false;
-  }
-  RootedId id(cx, AtomToId(atom));
-
-  return DefineDataPropertyById(cx, obj, id, value, attrs);
-}
-
-JS_PUBLIC_API bool JS_DefineProperty(JSContext* cx, HandleObject obj,
-                                     const char* name, HandleValue value,
-                                     unsigned attrs) {
-  return DefineDataProperty(cx, obj, name, value, attrs);
-}
-
-JS_PUBLIC_API bool JS_DefineProperty(JSContext* cx, HandleObject obj,
-                                     const char* name, Native getter,
-                                     Native setter, unsigned attrs) {
-  JSAtom* atom = Atomize(cx, name, strlen(name));
-  if (!atom) {
-    return false;
-  }
-  RootedId id(cx, AtomToId(atom));
-  return DefineAccessorPropertyById(cx, obj, id, NativeOpWrapper(getter),
-                                    NativeOpWrapper(setter), attrs);
-}
-
-JS_PUBLIC_API bool JS_DefineProperty(JSContext* cx, HandleObject obj,
-                                     const char* name, HandleObject getter,
-                                     HandleObject setter, unsigned attrs) {
-  JSAtom* atom = Atomize(cx, name, strlen(name));
-  if (!atom) {
-    return false;
-  }
-  RootedId id(cx, AtomToId(atom));
-
-  return DefineAccessorPropertyById(cx, obj, id, getter, setter, attrs);
-}
-
-JS_PUBLIC_API bool JS_DefineProperty(JSContext* cx, HandleObject obj,
-                                     const char* name, HandleObject valueArg,
-                                     unsigned attrs) {
-  RootedValue value(cx, ObjectValue(*valueArg));
-  return DefineDataProperty(cx, obj, name, value, attrs);
-}
-
-JS_PUBLIC_API bool JS_DefineProperty(JSContext* cx, HandleObject obj,
-                                     const char* name, HandleString valueArg,
-                                     unsigned attrs) {
-  RootedValue value(cx, StringValue(valueArg));
-  return DefineDataProperty(cx, obj, name, value, attrs);
-}
-
-JS_PUBLIC_API bool JS_DefineProperty(JSContext* cx, HandleObject obj,
-                                     const char* name, int32_t valueArg,
-                                     unsigned attrs) {
-  Value value = Int32Value(valueArg);
-  return DefineDataProperty(cx, obj, name,
-                            HandleValue::fromMarkedLocation(&value), attrs);
-}
-
-JS_PUBLIC_API bool JS_DefineProperty(JSContext* cx, HandleObject obj,
-                                     const char* name, uint32_t valueArg,
-                                     unsigned attrs) {
-  Value value = NumberValue(valueArg);
-  return DefineDataProperty(cx, obj, name,
-                            HandleValue::fromMarkedLocation(&value), attrs);
-}
-
-JS_PUBLIC_API bool JS_DefineProperty(JSContext* cx, HandleObject obj,
-                                     const char* name, double valueArg,
-                                     unsigned attrs) {
-  Value value = NumberValue(valueArg);
-  return DefineDataProperty(cx, obj, name,
-                            HandleValue::fromMarkedLocation(&value), attrs);
-}
-
-#define AUTO_NAMELEN(s, n) (((n) == (size_t)-1) ? js_strlen(s) : (n))
-
-JS_PUBLIC_API bool JS_DefineUCProperty(JSContext* cx, HandleObject obj,
-                                       const char16_t* name, size_t namelen,
-                                       Handle<PropertyDescriptor> desc,
-                                       ObjectOpResult& result) {
-  JSAtom* atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen));
-  if (!atom) {
-    return false;
-  }
-  RootedId id(cx, AtomToId(atom));
-  return DefinePropertyByDescriptor(cx, obj, id, desc, result);
-}
-
-JS_PUBLIC_API bool JS_DefineUCProperty(JSContext* cx, HandleObject obj,
-                                       const char16_t* name, size_t namelen,
-                                       Handle<PropertyDescriptor> desc) {
-  JSAtom* atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen));
-  if (!atom) {
-    return false;
-  }
-  RootedId id(cx, AtomToId(atom));
-  ObjectOpResult result;
-  return DefinePropertyByDescriptor(cx, obj, id, desc, result) &&
-         result.checkStrict(cx, obj, id);
-}
-
-static bool DefineUCDataProperty(JSContext* cx, HandleObject obj,
-                                 const char16_t* name, size_t namelen,
-                                 HandleValue value, unsigned attrs) {
-  JSAtom* atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen));
-  if (!atom) {
-    return false;
-  }
-  RootedId id(cx, AtomToId(atom));
-  return DefineDataPropertyById(cx, obj, id, value, attrs);
-}
-
-JS_PUBLIC_API bool JS_DefineUCProperty(JSContext* cx, HandleObject obj,
-                                       const char16_t* name, size_t namelen,
-                                       HandleValue value, unsigned attrs) {
-  return DefineUCDataProperty(cx, obj, name, namelen, value, attrs);
-}
-
-JS_PUBLIC_API bool JS_DefineUCProperty(JSContext* cx, HandleObject obj,
-                                       const char16_t* name, size_t namelen,
-                                       HandleObject getter, HandleObject setter,
-                                       unsigned attrs) {
-  JSAtom* atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen));
-  if (!atom) {
-    return false;
-  }
-  RootedId id(cx, AtomToId(atom));
-  return DefineAccessorPropertyById(cx, obj, id, getter, setter, attrs);
-}
-
-JS_PUBLIC_API bool JS_DefineUCProperty(JSContext* cx, HandleObject obj,
-                                       const char16_t* name, size_t namelen,
-                                       HandleObject valueArg, unsigned attrs) {
-  RootedValue value(cx, ObjectValue(*valueArg));
-  return DefineUCDataProperty(cx, obj, name, namelen, value, attrs);
-}
-
-JS_PUBLIC_API bool JS_DefineUCProperty(JSContext* cx, HandleObject obj,
-                                       const char16_t* name, size_t namelen,
-                                       HandleString valueArg, unsigned attrs) {
-  RootedValue value(cx, StringValue(valueArg));
-  return DefineUCDataProperty(cx, obj, name, namelen, value, attrs);
-}
-
-JS_PUBLIC_API bool JS_DefineUCProperty(JSContext* cx, HandleObject obj,
-                                       const char16_t* name, size_t namelen,
-                                       int32_t valueArg, unsigned attrs) {
-  Value value = Int32Value(valueArg);
-  return DefineUCDataProperty(cx, obj, name, namelen,
-                              HandleValue::fromMarkedLocation(&value), attrs);
-}
-
-JS_PUBLIC_API bool JS_DefineUCProperty(JSContext* cx, HandleObject obj,
-                                       const char16_t* name, size_t namelen,
-                                       uint32_t valueArg, unsigned attrs) {
-  Value value = NumberValue(valueArg);
-  return DefineUCDataProperty(cx, obj, name, namelen,
-                              HandleValue::fromMarkedLocation(&value), attrs);
-}
-
-JS_PUBLIC_API bool JS_DefineUCProperty(JSContext* cx, HandleObject obj,
-                                       const char16_t* name, size_t namelen,
-                                       double valueArg, unsigned attrs) {
-  Value value = NumberValue(valueArg);
-  return DefineUCDataProperty(cx, obj, name, namelen,
-                              HandleValue::fromMarkedLocation(&value), attrs);
-}
-
-static bool DefineDataElement(JSContext* cx, HandleObject obj, uint32_t index,
-                              HandleValue value, unsigned attrs) {
-  cx->check(obj, value);
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  RootedId id(cx);
-  if (!IndexToId(cx, index, &id)) {
-    return false;
-  }
-  return DefineDataPropertyById(cx, obj, id, value, attrs);
-}
-
-JS_PUBLIC_API bool JS_DefineElement(JSContext* cx, HandleObject obj,
-                                    uint32_t index, HandleValue value,
-                                    unsigned attrs) {
-  return ::DefineDataElement(cx, obj, index, value, attrs);
-}
-
-JS_PUBLIC_API bool JS_DefineElement(JSContext* cx, HandleObject obj,
-                                    uint32_t index, HandleObject getter,
-                                    HandleObject setter, unsigned attrs) {
-  RootedId id(cx);
-  if (!IndexToId(cx, index, &id)) {
-    return false;
-  }
-  return DefineAccessorPropertyById(cx, obj, id, getter, setter, attrs);
-}
-
-JS_PUBLIC_API bool JS_DefineElement(JSContext* cx, HandleObject obj,
-                                    uint32_t index, HandleObject valueArg,
-                                    unsigned attrs) {
-  RootedValue value(cx, ObjectValue(*valueArg));
-  return ::DefineDataElement(cx, obj, index, value, attrs);
-}
-
-JS_PUBLIC_API bool JS_DefineElement(JSContext* cx, HandleObject obj,
-                                    uint32_t index, HandleString valueArg,
-                                    unsigned attrs) {
-  RootedValue value(cx, StringValue(valueArg));
-  return ::DefineDataElement(cx, obj, index, value, attrs);
-}
-
-JS_PUBLIC_API bool JS_DefineElement(JSContext* cx, HandleObject obj,
-                                    uint32_t index, int32_t valueArg,
-                                    unsigned attrs) {
-  Value value = Int32Value(valueArg);
-  return ::DefineDataElement(cx, obj, index,
-                             HandleValue::fromMarkedLocation(&value), attrs);
-}
-
-JS_PUBLIC_API bool JS_DefineElement(JSContext* cx, HandleObject obj,
-                                    uint32_t index, uint32_t valueArg,
-                                    unsigned attrs) {
-  Value value = NumberValue(valueArg);
-  return ::DefineDataElement(cx, obj, index,
-                             HandleValue::fromMarkedLocation(&value), attrs);
-}
-
-JS_PUBLIC_API bool JS_DefineElement(JSContext* cx, HandleObject obj,
-                                    uint32_t index, double valueArg,
-                                    unsigned attrs) {
-  Value value = NumberValue(valueArg);
-  return ::DefineDataElement(cx, obj, index,
-                             HandleValue::fromMarkedLocation(&value), attrs);
-}
-
-JS_PUBLIC_API bool JS_HasPropertyById(JSContext* cx, HandleObject obj,
-                                      HandleId id, bool* foundp) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(obj, id);
-
-  return HasProperty(cx, obj, id, foundp);
-}
-
-JS_PUBLIC_API bool JS_HasProperty(JSContext* cx, HandleObject obj,
-                                  const char* name, bool* foundp) {
-  JSAtom* atom = Atomize(cx, name, strlen(name));
-  if (!atom) {
-    return false;
-  }
-  RootedId id(cx, AtomToId(atom));
-  return JS_HasPropertyById(cx, obj, id, foundp);
-}
-
-JS_PUBLIC_API bool JS_HasUCProperty(JSContext* cx, HandleObject obj,
-                                    const char16_t* name, size_t namelen,
-                                    bool* foundp) {
-  JSAtom* atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen));
-  if (!atom) {
-    return false;
-  }
-  RootedId id(cx, AtomToId(atom));
-  return JS_HasPropertyById(cx, obj, id, foundp);
-}
-
-JS_PUBLIC_API bool JS_HasElement(JSContext* cx, HandleObject obj,
-                                 uint32_t index, bool* foundp) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  RootedId id(cx);
-  if (!IndexToId(cx, index, &id)) {
-    return false;
-  }
-  return JS_HasPropertyById(cx, obj, id, foundp);
-}
-
-JS_PUBLIC_API bool JS_HasOwnPropertyById(JSContext* cx, HandleObject obj,
-                                         HandleId id, bool* foundp) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(obj, id);
-
-  return HasOwnProperty(cx, obj, id, foundp);
-}
-
-JS_PUBLIC_API bool JS_HasOwnProperty(JSContext* cx, HandleObject obj,
-                                     const char* name, bool* foundp) {
-  JSAtom* atom = Atomize(cx, name, strlen(name));
-  if (!atom) {
-    return false;
-  }
-  RootedId id(cx, AtomToId(atom));
-  return JS_HasOwnPropertyById(cx, obj, id, foundp);
-}
-
-JS_PUBLIC_API bool JS_ForwardGetPropertyTo(JSContext* cx, HandleObject obj,
-                                           HandleId id, HandleValue receiver,
-                                           MutableHandleValue vp) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(obj, id, receiver);
-
-  return GetProperty(cx, obj, receiver, id, vp);
-}
-
-JS_PUBLIC_API bool JS_ForwardGetElementTo(JSContext* cx, HandleObject obj,
-                                          uint32_t index, HandleObject receiver,
-                                          MutableHandleValue vp) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(obj);
-
-  return GetElement(cx, obj, receiver, index, vp);
-}
-
-JS_PUBLIC_API bool JS_GetPropertyById(JSContext* cx, HandleObject obj,
-                                      HandleId id, MutableHandleValue vp) {
-  RootedValue receiver(cx, ObjectValue(*obj));
-  return JS_ForwardGetPropertyTo(cx, obj, id, receiver, vp);
-}
-
-JS_PUBLIC_API bool JS_GetProperty(JSContext* cx, HandleObject obj,
-                                  const char* name, MutableHandleValue vp) {
-  JSAtom* atom = Atomize(cx, name, strlen(name));
-  if (!atom) {
-    return false;
-  }
-  RootedId id(cx, AtomToId(atom));
-  return JS_GetPropertyById(cx, obj, id, vp);
-}
-
-JS_PUBLIC_API bool JS_GetUCProperty(JSContext* cx, HandleObject obj,
-                                    const char16_t* name, size_t namelen,
-                                    MutableHandleValue vp) {
-  JSAtom* atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen));
-  if (!atom) {
-    return false;
-  }
-  RootedId id(cx, AtomToId(atom));
-  return JS_GetPropertyById(cx, obj, id, vp);
-}
-
-JS_PUBLIC_API bool JS_GetElement(JSContext* cx, HandleObject objArg,
-                                 uint32_t index, MutableHandleValue vp) {
-  return JS_ForwardGetElementTo(cx, objArg, index, objArg, vp);
-}
-
-JS_PUBLIC_API bool JS_ForwardSetPropertyTo(JSContext* cx, HandleObject obj,
-                                           HandleId id, HandleValue v,
-                                           HandleValue receiver,
-                                           ObjectOpResult& result) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(obj, id, v, receiver);
-
-  return SetProperty(cx, obj, id, v, receiver, result);
-}
-
-JS_PUBLIC_API bool JS_SetPropertyById(JSContext* cx, HandleObject obj,
-                                      HandleId id, HandleValue v) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(obj, id, v);
-
-  RootedValue receiver(cx, ObjectValue(*obj));
-  ObjectOpResult ignored;
-  return SetProperty(cx, obj, id, v, receiver, ignored);
-}
-
-JS_PUBLIC_API bool JS_SetProperty(JSContext* cx, HandleObject obj,
-                                  const char* name, HandleValue v) {
-  JSAtom* atom = Atomize(cx, name, strlen(name));
-  if (!atom) {
-    return false;
-  }
-  RootedId id(cx, AtomToId(atom));
-  return JS_SetPropertyById(cx, obj, id, v);
-}
-
-JS_PUBLIC_API bool JS_SetUCProperty(JSContext* cx, HandleObject obj,
-                                    const char16_t* name, size_t namelen,
-                                    HandleValue v) {
-  JSAtom* atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen));
-  if (!atom) {
-    return false;
-  }
-  RootedId id(cx, AtomToId(atom));
-  return JS_SetPropertyById(cx, obj, id, v);
-}
-
-static bool SetElement(JSContext* cx, HandleObject obj, uint32_t index,
-                       HandleValue v) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(obj, v);
-
-  RootedValue receiver(cx, ObjectValue(*obj));
-  ObjectOpResult ignored;
-  return SetElement(cx, obj, index, v, receiver, ignored);
-}
-
-JS_PUBLIC_API bool JS_SetElement(JSContext* cx, HandleObject obj,
-                                 uint32_t index, HandleValue v) {
-  return SetElement(cx, obj, index, v);
-}
-
-JS_PUBLIC_API bool JS_SetElement(JSContext* cx, HandleObject obj,
-                                 uint32_t index, HandleObject v) {
-  RootedValue value(cx, ObjectOrNullValue(v));
-  return SetElement(cx, obj, index, value);
-}
-
-JS_PUBLIC_API bool JS_SetElement(JSContext* cx, HandleObject obj,
-                                 uint32_t index, HandleString v) {
-  RootedValue value(cx, StringValue(v));
-  return SetElement(cx, obj, index, value);
-}
-
-JS_PUBLIC_API bool JS_SetElement(JSContext* cx, HandleObject obj,
-                                 uint32_t index, int32_t v) {
-  RootedValue value(cx, NumberValue(v));
-  return SetElement(cx, obj, index, value);
-}
-
-JS_PUBLIC_API bool JS_SetElement(JSContext* cx, HandleObject obj,
-                                 uint32_t index, uint32_t v) {
-  RootedValue value(cx, NumberValue(v));
-  return SetElement(cx, obj, index, value);
-}
-
-JS_PUBLIC_API bool JS_SetElement(JSContext* cx, HandleObject obj,
-                                 uint32_t index, double v) {
-  RootedValue value(cx, NumberValue(v));
-  return SetElement(cx, obj, index, value);
-}
-
-JS_PUBLIC_API bool JS_DeletePropertyById(JSContext* cx, HandleObject obj,
-                                         HandleId id, ObjectOpResult& result) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(obj, id);
-
-  return DeleteProperty(cx, obj, id, result);
-}
-
-JS_PUBLIC_API bool JS_DeleteProperty(JSContext* cx, HandleObject obj,
-                                     const char* name, ObjectOpResult& result) {
-  CHECK_THREAD(cx);
-  cx->check(obj);
-
-  JSAtom* atom = Atomize(cx, name, strlen(name));
-  if (!atom) {
-    return false;
-  }
-  RootedId id(cx, AtomToId(atom));
-  return DeleteProperty(cx, obj, id, result);
-}
-
-JS_PUBLIC_API bool JS_DeleteUCProperty(JSContext* cx, HandleObject obj,
-                                       const char16_t* name, size_t namelen,
-                                       ObjectOpResult& result) {
-  CHECK_THREAD(cx);
-  cx->check(obj);
-
-  JSAtom* atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen));
-  if (!atom) {
-    return false;
-  }
-  RootedId id(cx, AtomToId(atom));
-  return DeleteProperty(cx, obj, id, result);
-}
-
-JS_PUBLIC_API bool JS_DeleteElement(JSContext* cx, HandleObject obj,
-                                    uint32_t index, ObjectOpResult& result) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(obj);
-
-  return DeleteElement(cx, obj, index, result);
-}
-
-JS_PUBLIC_API bool JS_DeletePropertyById(JSContext* cx, HandleObject obj,
-                                         HandleId id) {
-  ObjectOpResult ignored;
-  return JS_DeletePropertyById(cx, obj, id, ignored);
-}
-
-JS_PUBLIC_API bool JS_DeleteProperty(JSContext* cx, HandleObject obj,
-                                     const char* name) {
-  ObjectOpResult ignored;
-  return JS_DeleteProperty(cx, obj, name, ignored);
-}
-
-JS_PUBLIC_API bool JS_DeleteElement(JSContext* cx, HandleObject obj,
-                                    uint32_t index) {
-  ObjectOpResult ignored;
-  return JS_DeleteElement(cx, obj, index, ignored);
-}
-
-JS_PUBLIC_API bool JS_Enumerate(JSContext* cx, HandleObject obj,
-                                JS::MutableHandle<IdVector> props) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(obj, props);
-  MOZ_ASSERT(props.empty());
-
-  RootedIdVector ids(cx);
-  if (!GetPropertyKeys(cx, obj, JSITER_OWNONLY, &ids)) {
-    return false;
-  }
-
-  return props.append(ids.begin(), ids.end());
-}
-
-JS_PUBLIC_API bool JS::IsCallable(JSObject* obj) { return obj->isCallable(); }
-
-JS_PUBLIC_API bool JS::IsConstructor(JSObject* obj) {
-  return obj->isConstructor();
-}
-
-JS_PUBLIC_API bool JS_CallFunctionValue(JSContext* cx, HandleObject obj,
-                                        HandleValue fval,
-                                        const HandleValueArray& args,
-                                        MutableHandleValue rval) {
-  MOZ_ASSERT(!cx->zone()->isAtomsZone());
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(obj, fval, args);
-
-  InvokeArgs iargs(cx);
-  if (!FillArgumentsFromArraylike(cx, iargs, args)) {
-    return false;
-  }
-
-  RootedValue thisv(cx, ObjectOrNullValue(obj));
-  return Call(cx, fval, thisv, iargs, rval);
-}
-
-JS_PUBLIC_API bool JS_CallFunction(JSContext* cx, HandleObject obj,
-                                   HandleFunction fun,
-                                   const HandleValueArray& args,
-                                   MutableHandleValue rval) {
-  MOZ_ASSERT(!cx->zone()->isAtomsZone());
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(obj, fun, args);
-
-  InvokeArgs iargs(cx);
-  if (!FillArgumentsFromArraylike(cx, iargs, args)) {
-    return false;
-  }
-
-  RootedValue fval(cx, ObjectValue(*fun));
-  RootedValue thisv(cx, ObjectOrNullValue(obj));
-  return Call(cx, fval, thisv, iargs, rval);
-}
-
-JS_PUBLIC_API bool JS_CallFunctionName(JSContext* cx, HandleObject obj,
-                                       const char* name,
-                                       const HandleValueArray& args,
-                                       MutableHandleValue rval) {
-  MOZ_ASSERT(!cx->zone()->isAtomsZone());
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(obj, args);
-
-  JSAtom* atom = Atomize(cx, name, strlen(name));
-  if (!atom) {
-    return false;
-  }
-
-  RootedValue fval(cx);
-  RootedId id(cx, AtomToId(atom));
-  if (!GetProperty(cx, obj, obj, id, &fval)) {
-    return false;
-  }
-
-  InvokeArgs iargs(cx);
-  if (!FillArgumentsFromArraylike(cx, iargs, args)) {
-    return false;
-  }
-
-  RootedValue thisv(cx, ObjectOrNullValue(obj));
-  return Call(cx, fval, thisv, iargs, rval);
-}
-
-JS_PUBLIC_API bool JS::Call(JSContext* cx, HandleValue thisv, HandleValue fval,
-                            const JS::HandleValueArray& args,
-                            MutableHandleValue rval) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(thisv, fval, args);
-
-  InvokeArgs iargs(cx);
-  if (!FillArgumentsFromArraylike(cx, iargs, args)) {
-    return false;
-  }
-
-  return Call(cx, fval, thisv, iargs, rval);
-}
-
-JS_PUBLIC_API bool JS::Construct(JSContext* cx, HandleValue fval,
-                                 HandleObject newTarget,
-                                 const JS::HandleValueArray& args,
-                                 MutableHandleObject objp) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(fval, newTarget, args);
-
-  if (!IsConstructor(fval)) {
-    ReportValueError(cx, JSMSG_NOT_CONSTRUCTOR, JSDVG_IGNORE_STACK, fval,
-                     nullptr);
-    return false;
-  }
-
-  RootedValue newTargetVal(cx, ObjectValue(*newTarget));
-  if (!IsConstructor(newTargetVal)) {
-    ReportValueError(cx, JSMSG_NOT_CONSTRUCTOR, JSDVG_IGNORE_STACK,
-                     newTargetVal, nullptr);
-    return false;
-  }
-
-  ConstructArgs cargs(cx);
-  if (!FillArgumentsFromArraylike(cx, cargs, args)) {
-    return false;
-  }
-
-  return js::Construct(cx, fval, cargs, newTargetVal, objp);
-}
-
-JS_PUBLIC_API bool JS::Construct(JSContext* cx, HandleValue fval,
-                                 const JS::HandleValueArray& args,
-                                 MutableHandleObject objp) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(fval, args);
-
-  if (!IsConstructor(fval)) {
-    ReportValueError(cx, JSMSG_NOT_CONSTRUCTOR, JSDVG_IGNORE_STACK, fval,
-                     nullptr);
-    return false;
-  }
-
-  ConstructArgs cargs(cx);
-  if (!FillArgumentsFromArraylike(cx, cargs, args)) {
-    return false;
-  }
-
-  return js::Construct(cx, fval, cargs, fval, objp);
-}
-
-/* * */
-
-JS_PUBLIC_API bool JS_AlreadyHasOwnPropertyById(JSContext* cx, HandleObject obj,
-                                                HandleId id, bool* foundp) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(obj, id);
-
-  if (!obj->isNative()) {
-    return js::HasOwnProperty(cx, obj, id, foundp);
-  }
-
-  RootedNativeObject nativeObj(cx, &obj->as<NativeObject>());
-  Rooted<PropertyResult> prop(cx);
-  NativeLookupOwnPropertyNoResolve(cx, nativeObj, id, &prop);
-  *foundp = prop.isFound();
-  return true;
-}
-
-JS_PUBLIC_API bool JS_AlreadyHasOwnProperty(JSContext* cx, HandleObject obj,
-                                            const char* name, bool* foundp) {
-  JSAtom* atom = Atomize(cx, name, strlen(name));
-  if (!atom) {
-    return false;
-  }
-  RootedId id(cx, AtomToId(atom));
-  return JS_AlreadyHasOwnPropertyById(cx, obj, id, foundp);
-}
-
-JS_PUBLIC_API bool JS_AlreadyHasOwnUCProperty(JSContext* cx, HandleObject obj,
-                                              const char16_t* name,
-                                              size_t namelen, bool* foundp) {
-  JSAtom* atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen));
-  if (!atom) {
-    return false;
-  }
-  RootedId id(cx, AtomToId(atom));
-  return JS_AlreadyHasOwnPropertyById(cx, obj, id, foundp);
-}
-
-JS_PUBLIC_API bool JS_AlreadyHasOwnElement(JSContext* cx, HandleObject obj,
-                                           uint32_t index, bool* foundp) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  RootedId id(cx);
-  if (!IndexToId(cx, index, &id)) {
-    return false;
-  }
-  return JS_AlreadyHasOwnPropertyById(cx, obj, id, foundp);
-}
-
-JS_PUBLIC_API bool JS_FreezeObject(JSContext* cx, HandleObject obj) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(obj);
-  return FreezeObject(cx, obj);
-}
+#include "builtin/ModuleObject.h"  // js::FinishDynamicModuleImport, js::{,Requested}ModuleObject
+#include "frontend/BytecodeCompiler.h"  // js::frontend::CompileModule
+#include "js/RootingAPI.h"              // JS::MutableHandle
+#include "js/Value.h"                   // JS::Value
+#include "vm/JSContext.h"               // CHECK_THREAD, JSContext
+#include "vm/JSObject.h"                // JSObject
+#include "vm/Runtime.h"                 // JSRuntime
 
-static bool DeepFreezeSlot(JSContext* cx, const Value& v) {
-  if (v.isPrimitive()) {
-    return true;
-  }
-  RootedObject obj(cx, &v.toObject());
-  return JS_DeepFreezeObject(cx, obj);
-}
-
-JS_PUBLIC_API bool JS_DeepFreezeObject(JSContext* cx, HandleObject obj) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(obj);
-
-  // Assume that non-extensible objects are already deep-frozen, to avoid
-  // divergence.
-  bool extensible;
-  if (!IsExtensible(cx, obj, &extensible)) {
-    return false;
-  }
-  if (!extensible) {
-    return true;
-  }
-
-  if (!FreezeObject(cx, obj)) {
-    return false;
-  }
-
-  // Walk slots in obj and if any value is a non-null object, seal it.
-  if (obj->isNative()) {
-    RootedNativeObject nobj(cx, &obj->as<NativeObject>());
-    for (uint32_t i = 0, n = nobj->slotSpan(); i < n; ++i) {
-      if (!DeepFreezeSlot(cx, nobj->getSlot(i))) {
-        return false;
-      }
-    }
-    for (uint32_t i = 0, n = nobj->getDenseInitializedLength(); i < n; ++i) {
-      if (!DeepFreezeSlot(cx, nobj->getDenseElement(i))) {
-        return false;
-      }
-    }
-  }
-
-  return true;
-}
-
-static bool DefineSelfHostedProperty(JSContext* cx, HandleObject obj,
-                                     HandleId id, const char* getterName,
-                                     const char* setterName, unsigned attrs) {
-  JSAtom* getterNameAtom = Atomize(cx, getterName, strlen(getterName));
-  if (!getterNameAtom) {
-    return false;
-  }
-  RootedPropertyName getterNameName(cx, getterNameAtom->asPropertyName());
-
-  RootedAtom name(cx, IdToFunctionName(cx, id));
-  if (!name) {
-    return false;
-  }
-
-  RootedValue getterValue(cx);
-  if (!GlobalObject::getSelfHostedFunction(cx, cx->global(), getterNameName,
-                                           name, 0, &getterValue)) {
-    return false;
-  }
-  MOZ_ASSERT(getterValue.isObject() && getterValue.toObject().is<JSFunction>());
-  RootedFunction getterFunc(cx, &getterValue.toObject().as<JSFunction>());
-
-  RootedFunction setterFunc(cx);
-  if (setterName) {
-    JSAtom* setterNameAtom = Atomize(cx, setterName, strlen(setterName));
-    if (!setterNameAtom) {
-      return false;
-    }
-    RootedPropertyName setterNameName(cx, setterNameAtom->asPropertyName());
-
-    RootedValue setterValue(cx);
-    if (!GlobalObject::getSelfHostedFunction(cx, cx->global(), setterNameName,
-                                             name, 0, &setterValue)) {
-      return false;
-    }
-    MOZ_ASSERT(setterValue.isObject() &&
-               setterValue.toObject().is<JSFunction>());
-    setterFunc = &setterValue.toObject().as<JSFunction>();
-  }
-
-  return DefineAccessorPropertyById(cx, obj, id, getterFunc, setterFunc, attrs);
-}
-
-JS_PUBLIC_API JSObject* JS_DefineObject(JSContext* cx, HandleObject obj,
-                                        const char* name,
-                                        const JSClass* jsclasp,
-                                        unsigned attrs) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(obj);
-
-  const Class* clasp = Valueify(jsclasp);
-  if (!clasp) {
-    clasp = &PlainObject::class_; /* default class is Object */
-  }
-
-  RootedObject nobj(cx, NewBuiltinClassInstance(cx, clasp));
-  if (!nobj) {
-    return nullptr;
-  }
-
-  RootedValue nobjValue(cx, ObjectValue(*nobj));
-  if (!DefineDataProperty(cx, obj, name, nobjValue, attrs)) {
-    return nullptr;
-  }
-
-  return nobj;
-}
-
-static inline Value ValueFromScalar(double x) { return DoubleValue(x); }
-static inline Value ValueFromScalar(int32_t x) { return Int32Value(x); }
-
-template <typename T>
-static bool DefineConstScalar(JSContext* cx, HandleObject obj,
-                              const JSConstScalarSpec<T>* cds) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  unsigned attrs = JSPROP_READONLY | JSPROP_PERMANENT;
-  for (; cds->name; cds++) {
-    RootedValue value(cx, ValueFromScalar(cds->val));
-    if (!DefineDataProperty(cx, obj, cds->name, value, attrs)) {
-      return false;
-    }
-  }
-  return true;
-}
-
-JS_PUBLIC_API bool JS_DefineConstDoubles(JSContext* cx, HandleObject obj,
-                                         const JSConstDoubleSpec* cds) {
-  return DefineConstScalar(cx, obj, cds);
-}
-JS_PUBLIC_API bool JS_DefineConstIntegers(JSContext* cx, HandleObject obj,
-                                          const JSConstIntegerSpec* cis) {
-  return DefineConstScalar(cx, obj, cis);
-}
-
-JS_PUBLIC_API bool JSPropertySpec::getValue(JSContext* cx,
-                                            MutableHandleValue vp) const {
-  MOZ_ASSERT(!isAccessor());
-
-  if (u.value.type == JSVAL_TYPE_STRING) {
-    RootedAtom atom(cx, Atomize(cx, u.value.string, strlen(u.value.string)));
-    if (!atom) {
-      return false;
-    }
-    vp.setString(atom);
-  } else {
-    MOZ_ASSERT(u.value.type == JSVAL_TYPE_INT32);
-    vp.setInt32(u.value.int32);
-  }
-
-  return true;
-}
-
-bool PropertySpecNameToId(JSContext* cx, JSPropertySpec::Name name,
-                          MutableHandleId id,
-                          js::PinningBehavior pin = js::DoNotPinAtom) {
-  if (name.isSymbol()) {
-    id.set(SYMBOL_TO_JSID(cx->wellKnownSymbols().get(name.symbol())));
-  } else {
-    JSAtom* atom = Atomize(cx, name.string(), strlen(name.string()), pin);
-    if (!atom) {
-      return false;
-    }
-    id.set(AtomToId(atom));
-  }
-  return true;
-}
-
-JS_PUBLIC_API bool JS::PropertySpecNameToPermanentId(JSContext* cx,
-                                                     JSPropertySpec::Name name,
-                                                     jsid* idp) {
-  // We are calling fromMarkedLocation(idp) even though idp points to a
-  // location that will never be marked. This is OK because the whole point
-  // of this API is to populate *idp with a jsid that does not need to be
-  // marked.
-  return PropertySpecNameToId(
-      cx, name, MutableHandleId::fromMarkedLocation(idp), js::PinAtom);
-}
-
-JS_PUBLIC_API bool JS_DefineProperties(JSContext* cx, HandleObject obj,
-                                       const JSPropertySpec* ps) {
-  RootedId id(cx);
-
-  for (; ps->name; ps++) {
-    if (!PropertySpecNameToId(cx, ps->name, &id)) {
-      return false;
-    }
-
-    if (ps->isAccessor()) {
-      if (ps->isSelfHosted()) {
-        if (!DefineSelfHostedProperty(
-                cx, obj, id, ps->u.accessors.getter.selfHosted.funname,
-                ps->u.accessors.setter.selfHosted.funname, ps->flags)) {
-          return false;
-        }
-      } else {
-        if (!DefineAccessorPropertyById(
-                cx, obj, id, ps->u.accessors.getter.native,
-                ps->u.accessors.setter.native, ps->flags)) {
-          return false;
-        }
-      }
-    } else {
-      RootedValue v(cx);
-      if (!ps->getValue(cx, &v)) {
-        return false;
-      }
-
-      if (!DefineDataPropertyById(cx, obj, id, v,
-                                  ps->flags & ~JSPROP_INTERNAL_USE_BIT)) {
-        return false;
-      }
-    }
-  }
-  return true;
-}
-
-JS_PUBLIC_API bool JS::ObjectToCompletePropertyDescriptor(
-    JSContext* cx, HandleObject obj, HandleValue descObj,
-    MutableHandle<PropertyDescriptor> desc) {
-  // |obj| can be in a different compartment here. The caller is responsible
-  // for wrapping it (see JS_WrapPropertyDescriptor).
-  cx->check(descObj);
-  if (!ToPropertyDescriptor(cx, descObj, true, desc)) {
-    return false;
-  }
-  CompletePropertyDescriptor(desc);
-  desc.object().set(obj);
-  return true;
-}
-
-JS_PUBLIC_API void JS_SetAllNonReservedSlotsToUndefined(JS::HandleObject obj) {
-  if (!obj->isNative()) {
-    return;
-  }
-
-  const Class* clasp = obj->getClass();
-  unsigned numReserved = JSCLASS_RESERVED_SLOTS(clasp);
-  unsigned numSlots = obj->as<NativeObject>().slotSpan();
-  for (unsigned i = numReserved; i < numSlots; i++) {
-    obj->as<NativeObject>().setSlot(i, UndefinedValue());
-  }
-}
-
-JS_PUBLIC_API Value JS_GetReservedSlot(JSObject* obj, uint32_t index) {
-  return obj->as<NativeObject>().getReservedSlot(index);
-}
-
-JS_PUBLIC_API void JS_SetReservedSlot(JSObject* obj, uint32_t index,
-                                      const Value& value) {
-  obj->as<NativeObject>().setReservedSlot(index, value);
-}
-
-JS_PUBLIC_API JSObject* JS_NewArrayObject(
-    JSContext* cx, const JS::HandleValueArray& contents) {
-  MOZ_ASSERT(!cx->zone()->isAtomsZone());
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-
-  cx->check(contents);
-  return NewDenseCopiedArray(cx, contents.length(), contents.begin());
-}
-
-JS_PUBLIC_API JSObject* JS_NewArrayObject(JSContext* cx, size_t length) {
-  MOZ_ASSERT(!cx->zone()->isAtomsZone());
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-
-  return NewDenseFullyAllocatedArray(cx, length);
-}
-
-inline bool IsGivenTypeObject(JSContext* cx, JS::HandleObject obj,
-                              const ESClass& typeClass, bool* isType) {
-  cx->check(obj);
-
-  ESClass cls;
-  if (!GetBuiltinClass(cx, obj, &cls)) {
-    return false;
-  }
-
-  *isType = cls == typeClass;
-  return true;
-}
-
-JS_PUBLIC_API bool JS_IsArrayObject(JSContext* cx, JS::HandleObject obj,
-                                    bool* isArray) {
-  return IsGivenTypeObject(cx, obj, ESClass::Array, isArray);
-}
-
-JS_PUBLIC_API bool JS_IsArrayObject(JSContext* cx, JS::HandleValue value,
-                                    bool* isArray) {
-  if (!value.isObject()) {
-    *isArray = false;
-    return true;
-  }
-
-  RootedObject obj(cx, &value.toObject());
-  return JS_IsArrayObject(cx, obj, isArray);
-}
-
-JS_PUBLIC_API bool JS_GetArrayLength(JSContext* cx, HandleObject obj,
-                                     uint32_t* lengthp) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(obj);
-  return GetLengthProperty(cx, obj, lengthp);
-}
-
-JS_PUBLIC_API bool JS_SetArrayLength(JSContext* cx, HandleObject obj,
-                                     uint32_t length) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(obj);
-  return SetLengthProperty(cx, obj, length);
-}
-
-JS_PUBLIC_API bool JS::IsMapObject(JSContext* cx, JS::HandleObject obj,
-                                   bool* isMap) {
-  return IsGivenTypeObject(cx, obj, ESClass::Map, isMap);
-}
-
-JS_PUBLIC_API bool JS::IsSetObject(JSContext* cx, JS::HandleObject obj,
-                                   bool* isSet) {
-  return IsGivenTypeObject(cx, obj, ESClass::Set, isSet);
-}
-
-JS_PUBLIC_API void JS_HoldPrincipals(JSPrincipals* principals) {
-  ++principals->refcount;
-}
-
-JS_PUBLIC_API void JS_DropPrincipals(JSContext* cx, JSPrincipals* principals) {
-  int rc = --principals->refcount;
-  if (rc == 0) {
-    JS::AutoSuppressGCAnalysis nogc;
-    cx->runtime()->destroyPrincipals(principals);
-  }
-}
-
-JS_PUBLIC_API void JS_SetSecurityCallbacks(JSContext* cx,
-                                           const JSSecurityCallbacks* scb) {
-  MOZ_ASSERT(scb != &NullSecurityCallbacks);
-  cx->runtime()->securityCallbacks = scb ? scb : &NullSecurityCallbacks;
-}
-
-JS_PUBLIC_API const JSSecurityCallbacks* JS_GetSecurityCallbacks(
-    JSContext* cx) {
-  return (cx->runtime()->securityCallbacks != &NullSecurityCallbacks)
-             ? cx->runtime()->securityCallbacks.ref()
-             : nullptr;
-}
-
-JS_PUBLIC_API void JS_SetTrustedPrincipals(JSContext* cx, JSPrincipals* prin) {
-  cx->runtime()->setTrustedPrincipals(prin);
-}
-
-extern JS_PUBLIC_API void JS_InitDestroyPrincipalsCallback(
-    JSContext* cx, JSDestroyPrincipalsOp destroyPrincipals) {
-  MOZ_ASSERT(destroyPrincipals);
-  MOZ_ASSERT(!cx->runtime()->destroyPrincipals);
-  cx->runtime()->destroyPrincipals = destroyPrincipals;
-}
-
-extern JS_PUBLIC_API void JS_InitReadPrincipalsCallback(
-    JSContext* cx, JSReadPrincipalsOp read) {
-  MOZ_ASSERT(read);
-  MOZ_ASSERT(!cx->runtime()->readPrincipals);
-  cx->runtime()->readPrincipals = read;
-}
-
-JS_PUBLIC_API JSFunction* JS_NewFunction(JSContext* cx, JSNative native,
-                                         unsigned nargs, unsigned flags,
-                                         const char* name) {
-  MOZ_ASSERT(!cx->zone()->isAtomsZone());
-
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-
-  RootedAtom atom(cx);
-  if (name) {
-    atom = Atomize(cx, name, strlen(name));
-    if (!atom) {
-      return nullptr;
-    }
-  }
-
-  return (flags & JSFUN_CONSTRUCTOR)
-             ? NewNativeConstructor(cx, native, nargs, atom)
-             : NewNativeFunction(cx, native, nargs, atom);
-}
-
-JS_PUBLIC_API JSFunction* JS::GetSelfHostedFunction(JSContext* cx,
-                                                    const char* selfHostedName,
-                                                    HandleId id,
-                                                    unsigned nargs) {
-  MOZ_ASSERT(!cx->zone()->isAtomsZone());
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(id);
-
-  RootedAtom name(cx, IdToFunctionName(cx, id));
-  if (!name) {
-    return nullptr;
-  }
-
-  JSAtom* shAtom = Atomize(cx, selfHostedName, strlen(selfHostedName));
-  if (!shAtom) {
-    return nullptr;
-  }
-  RootedPropertyName shName(cx, shAtom->asPropertyName());
-  RootedValue funVal(cx);
-  if (!GlobalObject::getSelfHostedFunction(cx, cx->global(), shName, name,
-                                           nargs, &funVal)) {
-    return nullptr;
-  }
-  return &funVal.toObject().as<JSFunction>();
-}
-
-JS_PUBLIC_API JSFunction* JS::NewFunctionFromSpec(JSContext* cx,
-                                                  const JSFunctionSpec* fs,
-                                                  HandleId id) {
-  cx->check(id);
-
-  // Delay cloning self-hosted functions until they are called. This is
-  // achieved by passing DefineFunction a nullptr JSNative which produces an
-  // interpreted JSFunction where !hasScript. Interpreted call paths then
-  // call InitializeLazyFunctionScript if !hasScript.
-  if (fs->selfHostedName) {
-    MOZ_ASSERT(!fs->call.op);
-    MOZ_ASSERT(!fs->call.info);
-
-    JSAtom* shAtom =
-        Atomize(cx, fs->selfHostedName, strlen(fs->selfHostedName));
-    if (!shAtom) {
-      return nullptr;
-    }
-    RootedPropertyName shName(cx, shAtom->asPropertyName());
-    RootedAtom name(cx, IdToFunctionName(cx, id));
-    if (!name) {
-      return nullptr;
-    }
-    RootedValue funVal(cx);
-    if (!GlobalObject::getSelfHostedFunction(cx, cx->global(), shName, name,
-                                             fs->nargs, &funVal)) {
-      return nullptr;
-    }
-    return &funVal.toObject().as<JSFunction>();
-  }
-
-  RootedAtom atom(cx, IdToFunctionName(cx, id));
-  if (!atom) {
-    return nullptr;
-  }
+#include "vm/JSContext-inl.h"  // JSContext::{c,releaseC}heck
 
-  JSFunction* fun;
-  if (!fs->call.op) {
-    fun =
-        NewScriptedFunction(cx, fs->nargs, JSFunction::INTERPRETED_LAZY, atom);
-  } else if (fs->flags & JSFUN_CONSTRUCTOR) {
-    fun = NewNativeConstructor(cx, fs->call.op, fs->nargs, atom);
-  } else {
-    fun = NewNativeFunction(cx, fs->call.op, fs->nargs, atom);
-  }
-  if (!fun) {
-    return nullptr;
-  }
-
-  if (fs->call.info) {
-    fun->setJitInfo(fs->call.info);
-  }
-  return fun;
-}
-
-static bool IsFunctionCloneable(HandleFunction fun) {
-  // If a function was compiled with non-global syntactic environments on
-  // the environment chain, we could have baked in EnvironmentCoordinates
-  // into the script. We cannot clone it without breaking the compiler's
-  // assumptions.
-  for (ScopeIter si(fun->nonLazyScript()->enclosingScope()); si; si++) {
-    if (si.scope()->is<GlobalScope>()) {
-      return true;
-    }
-    if (si.hasSyntacticEnvironment()) {
-      return false;
-    }
-  }
-
-  return true;
-}
-
-static JSObject* CloneFunctionObject(JSContext* cx, HandleObject funobj,
-                                     HandleObject env, HandleScope scope) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(env);
-  MOZ_ASSERT(env);
-  // Note that funobj can be in a different compartment.
-
-  if (!funobj->is<JSFunction>()) {
-    MOZ_RELEASE_ASSERT(!IsCrossCompartmentWrapper(funobj));
-    AutoRealm ar(cx, funobj);
-    RootedValue v(cx, ObjectValue(*funobj));
-    ReportIsNotFunction(cx, v);
-    return nullptr;
-  }
-
-  // Only allow cloning normal, interpreted functions.
-  RootedFunction fun(cx, &funobj->as<JSFunction>());
-  if (fun->isNative() || fun->isBoundFunction() ||
-      fun->kind() != JSFunction::NormalFunction || fun->isExtended() ||
-      fun->isSelfHostedBuiltin()) {
-    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
-                              JSMSG_CANT_CLONE_OBJECT);
-    return nullptr;
-  }
-
-  if (fun->isInterpretedLazy()) {
-    AutoRealm ar(cx, fun);
-    if (!JSFunction::getOrCreateScript(cx, fun)) {
-      return nullptr;
-    }
-  }
-  RootedScript script(cx, fun->nonLazyScript());
-
-  if (!IsFunctionCloneable(fun)) {
-    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
-                              JSMSG_BAD_CLONE_FUNOBJ_SCOPE);
-    return nullptr;
-  }
-
-  if (CanReuseScriptForClone(cx->realm(), fun, env)) {
-    return CloneFunctionReuseScript(cx, fun, env, fun->getAllocKind());
-  }
-
-  Rooted<ScriptSourceObject*> sourceObject(cx, script->sourceObject());
-  if (cx->compartment() != sourceObject->compartment()) {
-    sourceObject = ScriptSourceObject::clone(cx, sourceObject);
-    if (!sourceObject) {
-      return nullptr;
-    }
-  }
-
-  JSFunction* clone = CloneFunctionAndScript(cx, fun, env, scope, sourceObject,
-                                             fun->getAllocKind());
-
-#ifdef DEBUG
-  // The cloned function should itself be cloneable.
-  RootedFunction cloneRoot(cx, clone);
-  MOZ_ASSERT_IF(cloneRoot, IsFunctionCloneable(cloneRoot));
-#endif
-
-  return clone;
-}
-
-JS_PUBLIC_API JSObject* JS::CloneFunctionObject(JSContext* cx,
-                                                HandleObject funobj) {
-  RootedObject globalLexical(cx, &cx->global()->lexicalEnvironment());
-  RootedScope emptyGlobalScope(cx, &cx->global()->emptyGlobalScope());
-  return CloneFunctionObject(cx, funobj, globalLexical, emptyGlobalScope);
-}
-
-extern JS_PUBLIC_API JSObject* JS::CloneFunctionObject(
-    JSContext* cx, HandleObject funobj, HandleObjectVector envChain) {
-  RootedObject env(cx);
-  RootedScope scope(cx);
-  if (!CreateNonSyntacticEnvironmentChain(cx, envChain, &env, &scope)) {
-    return nullptr;
-  }
-  return CloneFunctionObject(cx, funobj, env, scope);
-}
-
-JS_PUBLIC_API JSObject* JS_GetFunctionObject(JSFunction* fun) { return fun; }
-
-JS_PUBLIC_API JSString* JS_GetFunctionId(JSFunction* fun) {
-  return fun->explicitName();
-}
-
-JS_PUBLIC_API JSString* JS_GetFunctionDisplayId(JSFunction* fun) {
-  return fun->displayAtom();
-}
-
-JS_PUBLIC_API uint16_t JS_GetFunctionArity(JSFunction* fun) {
-  return fun->nargs();
-}
-
-JS_PUBLIC_API bool JS_GetFunctionLength(JSContext* cx, HandleFunction fun,
-                                        uint16_t* length) {
-  cx->check(fun);
-  return JSFunction::getLength(cx, fun, length);
-}
-
-JS_PUBLIC_API bool JS_ObjectIsFunction(JSObject* obj) {
-  return obj->is<JSFunction>();
-}
-
-JS_PUBLIC_API bool JS_IsNativeFunction(JSObject* funobj, JSNative call) {
-  if (!funobj->is<JSFunction>()) {
-    return false;
-  }
-  JSFunction* fun = &funobj->as<JSFunction>();
-  return fun->isNative() && fun->native() == call;
-}
-
-extern JS_PUBLIC_API bool JS_IsConstructor(JSFunction* fun) {
-  return fun->isConstructor();
-}
-
-JS_PUBLIC_API bool JS_DefineFunctions(JSContext* cx, HandleObject obj,
-                                      const JSFunctionSpec* fs) {
-  MOZ_ASSERT(!cx->zone()->isAtomsZone());
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(obj);
-
-  return DefineFunctions(cx, obj, fs, NotIntrinsic);
-}
-
-JS_PUBLIC_API JSFunction* JS_DefineFunction(JSContext* cx, HandleObject obj,
-                                            const char* name, JSNative call,
-                                            unsigned nargs, unsigned attrs) {
-  MOZ_ASSERT(!cx->zone()->isAtomsZone());
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(obj);
-  JSAtom* atom = Atomize(cx, name, strlen(name));
-  if (!atom) {
-    return nullptr;
-  }
-  Rooted<jsid> id(cx, AtomToId(atom));
-  return DefineFunction(cx, obj, id, call, nargs, attrs);
-}
-
-JS_PUBLIC_API JSFunction* JS_DefineUCFunction(JSContext* cx, HandleObject obj,
-                                              const char16_t* name,
-                                              size_t namelen, JSNative call,
-                                              unsigned nargs, unsigned attrs) {
-  MOZ_ASSERT(!cx->zone()->isAtomsZone());
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(obj);
-  JSAtom* atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen));
-  if (!atom) {
-    return nullptr;
-  }
-  Rooted<jsid> id(cx, AtomToId(atom));
-  return DefineFunction(cx, obj, id, call, nargs, attrs);
-}
-
-extern JS_PUBLIC_API JSFunction* JS_DefineFunctionById(
-    JSContext* cx, HandleObject obj, HandleId id, JSNative call, unsigned nargs,
-    unsigned attrs) {
-  MOZ_ASSERT(!cx->zone()->isAtomsZone());
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(obj, id);
-  return DefineFunction(cx, obj, id, call, nargs, attrs);
-}
-
-void JS::TransitiveCompileOptions::copyPODTransitiveOptions(
-    const TransitiveCompileOptions& rhs) {
-  mutedErrors_ = rhs.mutedErrors_;
-  selfHostingMode = rhs.selfHostingMode;
-  canLazilyParse = rhs.canLazilyParse;
-  strictOption = rhs.strictOption;
-  extraWarningsOption = rhs.extraWarningsOption;
-  werrorOption = rhs.werrorOption;
-  asmJSOption = rhs.asmJSOption;
-  throwOnAsmJSValidationFailureOption = rhs.throwOnAsmJSValidationFailureOption;
-  forceAsync = rhs.forceAsync;
-  sourceIsLazy = rhs.sourceIsLazy;
-  introductionType = rhs.introductionType;
-  introductionLineno = rhs.introductionLineno;
-  introductionOffset = rhs.introductionOffset;
-  hasIntroductionInfo = rhs.hasIntroductionInfo;
-  isProbablySystemCode = rhs.isProbablySystemCode;
-  hideScriptFromDebugger = rhs.hideScriptFromDebugger;
-  bigIntEnabledOption = rhs.bigIntEnabledOption;
-  fieldsEnabledOption = rhs.fieldsEnabledOption;
-};
-
-void JS::ReadOnlyCompileOptions::copyPODOptions(
-    const ReadOnlyCompileOptions& rhs) {
-  copyPODTransitiveOptions(rhs);
-  lineno = rhs.lineno;
-  column = rhs.column;
-  scriptSourceOffset = rhs.scriptSourceOffset;
-  isRunOnce = rhs.isRunOnce;
-  noScriptRval = rhs.noScriptRval;
-  nonSyntacticScope = rhs.nonSyntacticScope;
-}
-
-JS::OwningCompileOptions::OwningCompileOptions(JSContext* cx)
-    : ReadOnlyCompileOptions(),
-      elementRoot(cx),
-      elementAttributeNameRoot(cx),
-      introductionScriptRoot(cx),
-      scriptOrModuleRoot(cx) {}
-
-JS::OwningCompileOptions::~OwningCompileOptions() {
-  // OwningCompileOptions always owns these, so these casts are okay.
-  js_free(const_cast<char*>(filename_));
-  js_free(const_cast<char16_t*>(sourceMapURL_));
-  js_free(const_cast<char*>(introducerFilename_));
-}
-
-size_t JS::OwningCompileOptions::sizeOfExcludingThis(
-    mozilla::MallocSizeOf mallocSizeOf) const {
-  return mallocSizeOf(filename_) + mallocSizeOf(sourceMapURL_) +
-         mallocSizeOf(introducerFilename_);
-}
-
-bool JS::OwningCompileOptions::copy(JSContext* cx,
-                                    const ReadOnlyCompileOptions& rhs) {
-  copyPODOptions(rhs);
-
-  setElement(rhs.element());
-  setElementAttributeName(rhs.elementAttributeName());
-  setIntroductionScript(rhs.introductionScript());
-  setScriptOrModule(rhs.scriptOrModule());
-
-  return setFileAndLine(cx, rhs.filename(), rhs.lineno) &&
-         setSourceMapURL(cx, rhs.sourceMapURL()) &&
-         setIntroducerFilename(cx, rhs.introducerFilename());
-}
-
-bool JS::OwningCompileOptions::setFile(JSContext* cx, const char* f) {
-  char* copy = nullptr;
-  if (f) {
-    copy = DuplicateString(cx, f).release();
-    if (!copy) {
-      return false;
-    }
-  }
-
-  // OwningCompileOptions always owns filename_, so this cast is okay.
-  js_free(const_cast<char*>(filename_));
-
-  filename_ = copy;
-  return true;
-}
-
-bool JS::OwningCompileOptions::setFileAndLine(JSContext* cx, const char* f,
-                                              unsigned l) {
-  if (!setFile(cx, f)) {
-    return false;
-  }
-
-  lineno = l;
-  return true;
-}
-
-bool JS::OwningCompileOptions::setSourceMapURL(JSContext* cx,
-                                               const char16_t* s) {
-  UniqueTwoByteChars copy;
-  if (s) {
-    copy = DuplicateString(cx, s);
-    if (!copy) {
-      return false;
-    }
-  }
-
-  // OwningCompileOptions always owns sourceMapURL_, so this cast is okay.
-  js_free(const_cast<char16_t*>(sourceMapURL_));
-
-  sourceMapURL_ = copy.release();
-  return true;
-}
-
-bool JS::OwningCompileOptions::setIntroducerFilename(JSContext* cx,
-                                                     const char* s) {
-  char* copy = nullptr;
-  if (s) {
-    copy = DuplicateString(cx, s).release();
-    if (!copy) {
-      return false;
-    }
-  }
-
-  // OwningCompileOptions always owns introducerFilename_, so this cast is okay.
-  js_free(const_cast<char*>(introducerFilename_));
-
-  introducerFilename_ = copy;
-  return true;
-}
-
-JS::CompileOptions::CompileOptions(JSContext* cx)
-    : ReadOnlyCompileOptions(),
-      elementRoot(cx),
-      elementAttributeNameRoot(cx),
-      introductionScriptRoot(cx),
-      scriptOrModuleRoot(cx) {
-  strictOption = cx->options().strictMode();
-  extraWarningsOption = cx->realm()->behaviors().extraWarnings(cx);
-  isProbablySystemCode = cx->realm()->isProbablySystemCode();
-  werrorOption = cx->options().werror();
-  if (!cx->options().asmJS()) {
-    asmJSOption = AsmJSOption::Disabled;
-  } else if (cx->realm()->debuggerObservesAsmJS()) {
-    asmJSOption = AsmJSOption::DisabledByDebugger;
-  } else {
-    asmJSOption = AsmJSOption::Enabled;
-  }
-  throwOnAsmJSValidationFailureOption =
-      cx->options().throwOnAsmJSValidationFailure();
-  bigIntEnabledOption = cx->realm()->creationOptions().getBigIntEnabled();
-  fieldsEnabledOption = cx->realm()->creationOptions().getFieldsEnabled();
-}
-
-CompileOptions& CompileOptions::setIntroductionInfoToCaller(
-    JSContext* cx, const char* introductionType) {
-  RootedScript maybeScript(cx);
-  const char* filename;
-  unsigned lineno;
-  uint32_t pcOffset;
-  bool mutedErrors;
-  DescribeScriptedCallerForCompilation(cx, &maybeScript, &filename, &lineno,
-                                       &pcOffset, &mutedErrors);
-  if (filename) {
-    return setIntroductionInfo(filename, introductionType, lineno, maybeScript,
-                               pcOffset);
-  } else {
-    return setIntroductionType(introductionType);
-  }
-}
-
-#if defined(JS_BUILD_BINAST)
-
-JSScript* JS::DecodeBinAST(JSContext* cx, const ReadOnlyCompileOptions& options,
-                           const uint8_t* buf, size_t length) {
-  MOZ_ASSERT(!cx->zone()->isAtomsZone());
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-
-  return frontend::CompileGlobalBinASTScript(cx, cx->tempLifoAlloc(), options,
-                                             buf, length);
-}
-
-JSScript* JS::DecodeBinAST(JSContext* cx, const ReadOnlyCompileOptions& options,
-                           FILE* file) {
-  FileContents fileContents(cx);
-  if (!ReadCompleteFile(cx, file, fileContents)) {
-    return nullptr;
-  }
-
-  return DecodeBinAST(cx, options, fileContents.begin(), fileContents.length());
-}
-
-JS_PUBLIC_API bool JS::DecodeBinASTOffThread(
-    JSContext* cx, const ReadOnlyCompileOptions& options, const uint8_t* buf,
-    size_t length, OffThreadCompileCallback callback, void* callbackData) {
-  return StartOffThreadDecodeBinAST(cx, options, buf, length, callback,
-                                    callbackData);
-}
-
-JS_PUBLIC_API JSScript* JS::FinishOffThreadBinASTDecode(
-    JSContext* cx, JS::OffThreadToken* token) {
-  MOZ_ASSERT(cx);
-  MOZ_ASSERT(CurrentThreadCanAccessRuntime(cx->runtime()));
-  return HelperThreadState().finishBinASTDecodeTask(cx, token);
-}
-#endif
-
-JS_PUBLIC_API JSObject* JS_GetGlobalFromScript(JSScript* script) {
-  return &script->global();
-}
-
-JS_PUBLIC_API const char* JS_GetScriptFilename(JSScript* script) {
-  // This is called from ThreadStackHelper which can be called from another
-  // thread or inside a signal hander, so we need to be careful in case a
-  // copmacting GC is currently moving things around.
-  return script->maybeForwardedFilename();
-}
-
-JS_PUBLIC_API unsigned JS_GetScriptBaseLineNumber(JSContext* cx,
-                                                  JSScript* script) {
-  return script->lineno();
-}
-
-JS_PUBLIC_API JSScript* JS_GetFunctionScript(JSContext* cx,
-                                             HandleFunction fun) {
-  if (fun->isNative()) {
-    return nullptr;
-  }
-  if (fun->isInterpretedLazy()) {
-    AutoRealm ar(cx, fun);
-    JSScript* script = JSFunction::getOrCreateScript(cx, fun);
-    if (!script) {
-      MOZ_CRASH();
-    }
-    return script;
-  }
-  return fun->nonLazyScript();
-}
-
-JS_PUBLIC_API JSString* JS_DecompileScript(JSContext* cx, HandleScript script) {
-  MOZ_ASSERT(!cx->zone()->isAtomsZone());
-
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  script->ensureNonLazyCanonicalFunction();
-  RootedFunction fun(cx, script->functionNonDelazifying());
-  if (fun) {
-    return JS_DecompileFunction(cx, fun);
-  }
-  bool haveSource;
-  if (!ScriptSource::loadSource(cx, script->scriptSource(), &haveSource)) {
-    return nullptr;
-  }
-  return haveSource ? JSScript::sourceData(cx, script)
-                    : NewStringCopyZ<CanGC>(cx, "[no source]");
-}
-
-JS_PUBLIC_API JSString* JS_DecompileFunction(JSContext* cx,
-                                             HandleFunction fun) {
-  MOZ_ASSERT(!cx->zone()->isAtomsZone());
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(fun);
-  return FunctionToString(cx, fun, /* isToSource = */ false);
-}
+using js::AssertHeapIsIdle;
+using js::ModuleObject;
+using js::RequestedModuleObject;
 
 JS_PUBLIC_API JS::ModuleResolveHook JS::GetModuleResolveHook(JSRuntime* rt) {
   AssertHeapIsIdle();
+
   return rt->moduleResolveHook;
 }
 
 JS_PUBLIC_API void JS::SetModuleResolveHook(JSRuntime* rt,
-                                            JS::ModuleResolveHook func) {
+                                            ModuleResolveHook func) {
   AssertHeapIsIdle();
+
   rt->moduleResolveHook = func;
 }
 
 JS_PUBLIC_API JS::ModuleMetadataHook JS::GetModuleMetadataHook(JSRuntime* rt) {
   AssertHeapIsIdle();
+
   return rt->moduleMetadataHook;
 }
 
 JS_PUBLIC_API void JS::SetModuleMetadataHook(JSRuntime* rt,
-                                             JS::ModuleMetadataHook func) {
+                                             ModuleMetadataHook func) {
   AssertHeapIsIdle();
+
   rt->moduleMetadataHook = func;
 }
 
 JS_PUBLIC_API JS::ModuleDynamicImportHook JS::GetModuleDynamicImportHook(
     JSRuntime* rt) {
   AssertHeapIsIdle();
+
   return rt->moduleDynamicImportHook;
 }
 
 JS_PUBLIC_API void JS::SetModuleDynamicImportHook(
-    JSRuntime* rt, JS::ModuleDynamicImportHook func) {
+    JSRuntime* rt, ModuleDynamicImportHook func) {
   AssertHeapIsIdle();
+
   rt->moduleDynamicImportHook = func;
 }
 
-JS_PUBLIC_API bool JS::FinishDynamicModuleImport(JSContext* cx,
-                                                 HandleValue referencingPrivate,
-                                                 HandleString specifier,
-                                                 HandleObject promise) {
+JS_PUBLIC_API bool JS::FinishDynamicModuleImport(
+    JSContext* cx, Handle<Value> referencingPrivate,
+    Handle<JSString*> specifier, Handle<JSObject*> promise) {
   AssertHeapIsIdle();
   CHECK_THREAD(cx);
   cx->check(referencingPrivate, promise);
 
   return js::FinishDynamicModuleImport(cx, referencingPrivate, specifier,
                                        promise);
 }
 
 JS_PUBLIC_API bool JS::CompileModule(JSContext* cx,
                                      const ReadOnlyCompileOptions& options,
                                      SourceText<char16_t>& srcBuf,
-                                     JS::MutableHandleObject module) {
+                                     MutableHandle<JSObject*> module) {
   MOZ_ASSERT(!cx->zone()->isAtomsZone());
   AssertHeapIsIdle();
   CHECK_THREAD(cx);
 
-  module.set(frontend::CompileModule(cx, options, srcBuf));
+  module.set(js::frontend::CompileModule(cx, options, srcBuf));
   return !!module;
 }
 
-JS_PUBLIC_API void JS::SetModulePrivate(JSObject* module,
-                                        const JS::Value& value) {
+JS_PUBLIC_API void JS::SetModulePrivate(JSObject* module, const Value& value) {
   JSRuntime* rt = module->zone()->runtimeFromMainThread();
   module->as<ModuleObject>().scriptSourceObject()->setPrivate(rt, value);
 }
 
 JS_PUBLIC_API JS::Value JS::GetModulePrivate(JSObject* module) {
   return module->as<ModuleObject>().scriptSourceObject()->canonicalPrivate();
 }
 
-JS_PUBLIC_API void JS::SetScriptPrivate(JSScript* script,
-                                        const JS::Value& value) {
-  JSRuntime* rt = script->zone()->runtimeFromMainThread();
-  script->sourceObject()->setPrivate(rt, value);
-}
-
-JS_PUBLIC_API JS::Value JS::GetScriptPrivate(JSScript* script) {
-  return script->sourceObject()->canonicalPrivate();
-}
-
-JS_PUBLIC_API JS::Value JS::GetScriptedCallerPrivate(JSContext* cx) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-
-  NonBuiltinFrameIter iter(cx, cx->realm()->principals());
-  if (iter.done() || !iter.hasScript()) {
-    return UndefinedValue();
-  }
-
-  return iter.script()->sourceObject()->canonicalPrivate();
-}
-
-JS_PUBLIC_API void JS::SetScriptPrivateReferenceHooks(
-    JSRuntime* rt, JS::ScriptPrivateReferenceHook addRefHook,
-    JS::ScriptPrivateReferenceHook releaseHook) {
-  AssertHeapIsIdle();
-  rt->scriptPrivateAddRefHook = addRefHook;
-  rt->scriptPrivateReleaseHook = releaseHook;
-}
-
 JS_PUBLIC_API bool JS::ModuleInstantiate(JSContext* cx,
-                                         JS::HandleObject moduleArg) {
+                                         Handle<JSObject*> moduleArg) {
   AssertHeapIsIdle();
   CHECK_THREAD(cx);
   cx->releaseCheck(moduleArg);
+
   return ModuleObject::Instantiate(cx, moduleArg.as<ModuleObject>());
 }
 
 JS_PUBLIC_API bool JS::ModuleEvaluate(JSContext* cx,
-                                      JS::HandleObject moduleArg) {
+                                      Handle<JSObject*> moduleArg) {
   AssertHeapIsIdle();
   CHECK_THREAD(cx);
   cx->releaseCheck(moduleArg);
+
   return ModuleObject::Evaluate(cx, moduleArg.as<ModuleObject>());
 }
 
 JS_PUBLIC_API JSObject* JS::GetRequestedModules(JSContext* cx,
-                                                JS::HandleObject moduleArg) {
+                                                Handle<JSObject*> moduleArg) {
   AssertHeapIsIdle();
   CHECK_THREAD(cx);
   cx->check(moduleArg);
+
   return &moduleArg->as<ModuleObject>().requestedModules();
 }
 
 JS_PUBLIC_API JSString* JS::GetRequestedModuleSpecifier(JSContext* cx,
-                                                        JS::HandleValue value) {
+                                                        Handle<Value> value) {
   AssertHeapIsIdle();
   CHECK_THREAD(cx);
   cx->check(value);
+
   JSObject* obj = &value.toObject();
   return obj->as<RequestedModuleObject>().moduleSpecifier();
 }
 
 JS_PUBLIC_API void JS::GetRequestedModuleSourcePos(JSContext* cx,
                                                    JS::HandleValue value,
                                                    uint32_t* lineNumber,
                                                    uint32_t* columnNumber) {
   AssertHeapIsIdle();
   CHECK_THREAD(cx);
   cx->check(value);
   MOZ_ASSERT(lineNumber);
   MOZ_ASSERT(columnNumber);
+
   auto& requested = value.toObject().as<RequestedModuleObject>();
   *lineNumber = requested.lineNumber();
   *columnNumber = requested.columnNumber();
 }
 
 JS_PUBLIC_API JSScript* JS::GetModuleScript(JS::HandleObject moduleRecord) {
   AssertHeapIsIdle();
+
   return moduleRecord->as<ModuleObject>().script();
 }
-
-JS_PUBLIC_API JSObject* JS_New(JSContext* cx, HandleObject ctor,
-                               const JS::HandleValueArray& inputArgs) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(ctor, inputArgs);
-
-  RootedValue ctorVal(cx, ObjectValue(*ctor));
-  if (!IsConstructor(ctorVal)) {
-    ReportValueError(cx, JSMSG_NOT_CONSTRUCTOR, JSDVG_IGNORE_STACK, ctorVal,
-                     nullptr);
-    return nullptr;
-  }
-
-  ConstructArgs args(cx);
-  if (!FillArgumentsFromArraylike(cx, args, inputArgs)) {
-    return nullptr;
-  }
-
-  RootedObject obj(cx);
-  if (!js::Construct(cx, ctorVal, args, ctorVal, &obj)) {
-    return nullptr;
-  }
-
-  return obj;
-}
-
-JS_PUBLIC_API bool JS_CheckForInterrupt(JSContext* cx) {
-  return js::CheckForInterrupt(cx);
-}
-
-JS_PUBLIC_API bool JS_AddInterruptCallback(JSContext* cx,
-                                           JSInterruptCallback callback) {
-  return cx->interruptCallbacks().append(callback);
-}
-
-JS_PUBLIC_API bool JS_DisableInterruptCallback(JSContext* cx) {
-  bool result = cx->interruptCallbackDisabled;
-  cx->interruptCallbackDisabled = true;
-  return result;
-}
-
-JS_PUBLIC_API void JS_ResetInterruptCallback(JSContext* cx, bool enable) {
-  cx->interruptCallbackDisabled = enable;
-}
-
-/************************************************************************/
-
-/*
- * Promises.
- */
-JS_PUBLIC_API void JS::SetJobQueue(JSContext* cx, JobQueue* queue) {
-  cx->jobQueue = queue;
-}
-
-extern JS_PUBLIC_API void JS::SetPromiseRejectionTrackerCallback(
-    JSContext* cx, PromiseRejectionTrackerCallback callback,
-    void* data /* = nullptr */) {
-  cx->promiseRejectionTrackerCallback = callback;
-  cx->promiseRejectionTrackerCallbackData = data;
-}
-
-extern JS_PUBLIC_API void JS::JobQueueIsEmpty(JSContext* cx) {
-  cx->canSkipEnqueuingJobs = true;
-}
-
-extern JS_PUBLIC_API void JS::JobQueueMayNotBeEmpty(JSContext* cx) {
-  cx->canSkipEnqueuingJobs = false;
-}
-
-JS_PUBLIC_API JSObject* JS::NewPromiseObject(
-    JSContext* cx, HandleObject executor, HandleObject proto /* = nullptr */) {
-  MOZ_ASSERT(!cx->zone()->isAtomsZone());
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(executor, proto);
-
-  if (!executor) {
-    return PromiseObject::createSkippingExecutor(cx);
-  }
-
-  MOZ_ASSERT(IsCallable(executor));
-  return PromiseObject::create(cx, executor, proto);
-}
-
-JS_PUBLIC_API bool JS::IsPromiseObject(JS::HandleObject obj) {
-  return obj->is<PromiseObject>();
-}
-
-JS_PUBLIC_API JSObject* JS::GetPromiseConstructor(JSContext* cx) {
-  CHECK_THREAD(cx);
-  Rooted<GlobalObject*> global(cx, cx->global());
-  return GlobalObject::getOrCreatePromiseConstructor(cx, global);
-}
-
-JS_PUBLIC_API JSObject* JS::GetPromisePrototype(JSContext* cx) {
-  CHECK_THREAD(cx);
-  Rooted<GlobalObject*> global(cx, cx->global());
-  return GlobalObject::getOrCreatePromisePrototype(cx, global);
-}
-
-JS_PUBLIC_API JS::PromiseState JS::GetPromiseState(
-    JS::HandleObject promiseObj_) {
-  PromiseObject* promiseObj = promiseObj_->maybeUnwrapIf<PromiseObject>();
-  if (!promiseObj) {
-    return JS::PromiseState::Pending;
-  }
-
-  return promiseObj->state();
-}
-
-JS_PUBLIC_API uint64_t JS::GetPromiseID(JS::HandleObject promise) {
-  return promise->as<PromiseObject>().getID();
-}
-
-JS_PUBLIC_API JS::Value JS::GetPromiseResult(JS::HandleObject promiseObj) {
-  PromiseObject* promise = &promiseObj->as<PromiseObject>();
-  MOZ_ASSERT(promise->state() != JS::PromiseState::Pending);
-  return promise->state() == JS::PromiseState::Fulfilled ? promise->value()
-                                                         : promise->reason();
-}
-
-JS_PUBLIC_API bool JS::GetPromiseIsHandled(JS::HandleObject promiseObj) {
-  PromiseObject* promise = &promiseObj->as<PromiseObject>();
-  return !promise->isUnhandled();
-}
-
-JS_PUBLIC_API JSObject* JS::GetPromiseAllocationSite(JS::HandleObject promise) {
-  return promise->as<PromiseObject>().allocationSite();
-}
-
-JS_PUBLIC_API JSObject* JS::GetPromiseResolutionSite(JS::HandleObject promise) {
-  return promise->as<PromiseObject>().resolutionSite();
-}
-
-#ifdef DEBUG
-JS_PUBLIC_API void JS::DumpPromiseAllocationSite(JSContext* cx,
-                                                 JS::HandleObject promise) {
-  RootedObject stack(cx, promise->as<PromiseObject>().allocationSite());
-  JSPrincipals* principals = cx->realm()->principals();
-  UniqueChars stackStr = BuildUTF8StackString(cx, principals, stack);
-  if (stackStr) {
-    fputs(stackStr.get(), stderr);
-  }
-}
-
-JS_PUBLIC_API void JS::DumpPromiseResolutionSite(JSContext* cx,
-                                                 JS::HandleObject promise) {
-  RootedObject stack(cx, promise->as<PromiseObject>().resolutionSite());
-  JSPrincipals* principals = cx->realm()->principals();
-  UniqueChars stackStr = BuildUTF8StackString(cx, principals, stack);
-  if (stackStr) {
-    fputs(stackStr.get(), stderr);
-  }
-}
-#endif
-
-JS_PUBLIC_API JSObject* JS::CallOriginalPromiseResolve(
-    JSContext* cx, JS::HandleValue resolutionValue) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(resolutionValue);
-
-  RootedObject promise(cx,
-                       PromiseObject::unforgeableResolve(cx, resolutionValue));
-  MOZ_ASSERT_IF(promise, promise->canUnwrapAs<PromiseObject>());
-  return promise;
-}
-
-JS_PUBLIC_API JSObject* JS::CallOriginalPromiseReject(
-    JSContext* cx, JS::HandleValue rejectionValue) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(rejectionValue);
-
-  RootedObject promise(cx,
-                       PromiseObject::unforgeableReject(cx, rejectionValue));
-  MOZ_ASSERT_IF(promise, promise->canUnwrapAs<PromiseObject>());
-  return promise;
-}
-
-static bool ResolveOrRejectPromise(JSContext* cx, JS::HandleObject promiseObj,
-                                   JS::HandleValue resultOrReason_,
-                                   bool reject) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(promiseObj, resultOrReason_);
-
-  mozilla::Maybe<AutoRealm> ar;
-  Rooted<PromiseObject*> promise(cx);
-  RootedValue resultOrReason(cx, resultOrReason_);
-  if (IsWrapper(promiseObj)) {
-    promise = promiseObj->maybeUnwrapAs<PromiseObject>();
-    if (!promise) {
-      ReportAccessDenied(cx);
-      return false;
-    }
-    ar.emplace(cx, promise);
-    if (!cx->compartment()->wrap(cx, &resultOrReason)) {
-      return false;
-    }
-  } else {
-    promise = promiseObj.as<PromiseObject>();
-  }
-
-  return reject ? PromiseObject::reject(cx, promise, resultOrReason)
-                : PromiseObject::resolve(cx, promise, resultOrReason);
-}
-
-JS_PUBLIC_API bool JS::ResolvePromise(JSContext* cx,
-                                      JS::HandleObject promiseObj,
-                                      JS::HandleValue resolutionValue) {
-  return ResolveOrRejectPromise(cx, promiseObj, resolutionValue, false);
-}
-
-JS_PUBLIC_API bool JS::RejectPromise(JSContext* cx, JS::HandleObject promiseObj,
-                                     JS::HandleValue rejectionValue) {
-  return ResolveOrRejectPromise(cx, promiseObj, rejectionValue, true);
-}
-
-static MOZ_MUST_USE bool CallOriginalPromiseThenImpl(
-    JSContext* cx, JS::HandleObject promiseObj, JS::HandleObject onFulfilledObj,
-    JS::HandleObject onRejectedObj, JS::MutableHandleObject resultObj,
-    CreateDependentPromise createDependent) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(promiseObj, onFulfilledObj, onRejectedObj);
-
-  MOZ_ASSERT_IF(onFulfilledObj, IsCallable(onFulfilledObj));
-  MOZ_ASSERT_IF(onRejectedObj, IsCallable(onRejectedObj));
-
-  RootedValue onFulfilled(cx, ObjectOrNullValue(onFulfilledObj));
-  RootedValue onRejected(cx, ObjectOrNullValue(onRejectedObj));
-  return OriginalPromiseThen(cx, promiseObj, onFulfilled, onRejected, resultObj,
-                             createDependent);
-}
-
-JS_PUBLIC_API JSObject* JS::CallOriginalPromiseThen(
-    JSContext* cx, JS::HandleObject promiseObj, JS::HandleObject onResolvedObj,
-    JS::HandleObject onRejectedObj) {
-  RootedObject resultPromise(cx);
-  if (!CallOriginalPromiseThenImpl(cx, promiseObj, onResolvedObj, onRejectedObj,
-                                   &resultPromise,
-                                   CreateDependentPromise::Always)) {
-    return nullptr;
-  }
-  return resultPromise;
-}
-
-JS_PUBLIC_API bool JS::AddPromiseReactions(JSContext* cx,
-                                           JS::HandleObject promiseObj,
-                                           JS::HandleObject onResolvedObj,
-                                           JS::HandleObject onRejectedObj) {
-  RootedObject resultPromise(cx);
-  bool result = CallOriginalPromiseThenImpl(cx, promiseObj, onResolvedObj,
-                                            onRejectedObj, &resultPromise,
-                                            CreateDependentPromise::Never);
-  MOZ_ASSERT(!resultPromise);
-  return result;
-}
-
-JS_PUBLIC_API JS::PromiseUserInputEventHandlingState
-JS::GetPromiseUserInputEventHandlingState(JS::HandleObject promiseObj_) {
-  PromiseObject* promise = promiseObj_->maybeUnwrapIf<PromiseObject>();
-  if (!promise) {
-    return JS::PromiseUserInputEventHandlingState::DontCare;
-  }
-
-  if (!promise->requiresUserInteractionHandling()) {
-    return JS::PromiseUserInputEventHandlingState::DontCare;
-  }
-  if (promise->hadUserInteractionUponCreation()) {
-    return JS::PromiseUserInputEventHandlingState::HadUserInteractionAtCreation;
-  }
-  return JS::PromiseUserInputEventHandlingState::
-      DidntHaveUserInteractionAtCreation;
-}
-
-JS_PUBLIC_API bool JS::SetPromiseUserInputEventHandlingState(
-    JS::HandleObject promiseObj_,
-    JS::PromiseUserInputEventHandlingState state) {
-  PromiseObject* promise = promiseObj_->maybeUnwrapIf<PromiseObject>();
-  if (!promise) {
-    return false;
-  }
-
-  switch (state) {
-    case JS::PromiseUserInputEventHandlingState::DontCare:
-      promise->setRequiresUserInteractionHandling(false);
-      break;
-    case JS::PromiseUserInputEventHandlingState::HadUserInteractionAtCreation:
-      promise->setRequiresUserInteractionHandling(true);
-      promise->setHadUserInteractionUponCreation(true);
-      break;
-    case JS::PromiseUserInputEventHandlingState::
-        DidntHaveUserInteractionAtCreation:
-      promise->setRequiresUserInteractionHandling(true);
-      promise->setHadUserInteractionUponCreation(false);
-      break;
-    default:
-      MOZ_ASSERT_UNREACHABLE(
-          "Invalid PromiseUserInputEventHandlingState enum value");
-      return false;
-  }
-  return true;
-}
-
-/**
- * Unforgeable version of Promise.all for internal use.
- *
- * Takes a dense array of Promise objects and returns a promise that's
- * resolved with an array of resolution values when all those promises ahve
- * been resolved, or rejected with the rejection value of the first rejected
- * promise.
- *
- * Asserts that the array is dense and all entries are Promise objects.
- */
-JS_PUBLIC_API JSObject* JS::GetWaitForAllPromise(
-    JSContext* cx, JS::HandleObjectVector promises) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-
-  return js::GetWaitForAllPromise(cx, promises);
-}
-
-JS_PUBLIC_API void JS::InitDispatchToEventLoop(
-    JSContext* cx, JS::DispatchToEventLoopCallback callback, void* closure) {
-  cx->runtime()->offThreadPromiseState.ref().init(callback, closure);
-}
-
-JS_PUBLIC_API void JS::ShutdownAsyncTasks(JSContext* cx) {
-  cx->runtime()->offThreadPromiseState.ref().shutdown(cx);
-}
-
-JS_PUBLIC_API void JS::InitConsumeStreamCallback(
-    JSContext* cx, ConsumeStreamCallback consume,
-    ReportStreamErrorCallback report) {
-  cx->runtime()->consumeStreamCallback = consume;
-  cx->runtime()->reportStreamErrorCallback = report;
-}
-
-JS_PUBLIC_API void JS_RequestInterruptCallback(JSContext* cx) {
-  cx->requestInterrupt(InterruptReason::CallbackUrgent);
-}
-
-JS_PUBLIC_API void JS_RequestInterruptCallbackCanWait(JSContext* cx) {
-  cx->requestInterrupt(InterruptReason::CallbackCanWait);
-}
-
-JS::AutoSetAsyncStackForNewCalls::AutoSetAsyncStackForNewCalls(
-    JSContext* cx, HandleObject stack, const char* asyncCause,
-    JS::AutoSetAsyncStackForNewCalls::AsyncCallKind kind)
-    : cx(cx),
-      oldAsyncStack(cx, cx->asyncStackForNewActivations()),
-      oldAsyncCause(cx->asyncCauseForNewActivations),
-      oldAsyncCallIsExplicit(cx->asyncCallIsExplicit) {
-  CHECK_THREAD(cx);
-
-  // The option determines whether we actually use the new values at this
-  // point. It will not affect restoring the previous values when the object
-  // is destroyed, so if the option changes it won't cause consistency issues.
-  if (!cx->options().asyncStack()) {
-    return;
-  }
-
-  SavedFrame* asyncStack = &stack->as<SavedFrame>();
-
-  cx->asyncStackForNewActivations() = asyncStack;
-  cx->asyncCauseForNewActivations = asyncCause;
-  cx->asyncCallIsExplicit = kind == AsyncCallKind::EXPLICIT;
-}
-
-JS::AutoSetAsyncStackForNewCalls::~AutoSetAsyncStackForNewCalls() {
-  cx->asyncCauseForNewActivations = oldAsyncCause;
-  cx->asyncStackForNewActivations() =
-      oldAsyncStack ? &oldAsyncStack->as<SavedFrame>() : nullptr;
-  cx->asyncCallIsExplicit = oldAsyncCallIsExplicit;
-}
-
-/************************************************************************/
-JS_PUBLIC_API JSString* JS_NewStringCopyN(JSContext* cx, const char* s,
-                                          size_t n) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  return NewStringCopyN<CanGC>(cx, s, n);
-}
-
-JS_PUBLIC_API JSString* JS_NewStringCopyZ(JSContext* cx, const char* s) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  if (!s) {
-    return cx->runtime()->emptyString;
-  }
-  return NewStringCopyZ<CanGC>(cx, s);
-}
-
-JS_PUBLIC_API JSString* JS_NewStringCopyUTF8Z(JSContext* cx,
-                                              const JS::ConstUTF8CharsZ s) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  return NewStringCopyUTF8Z<CanGC>(cx, s);
-}
-
-JS_PUBLIC_API JSString* JS_NewStringCopyUTF8N(JSContext* cx,
-                                              const JS::UTF8Chars s) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  return NewStringCopyUTF8N<CanGC>(cx, s);
-}
-
-JS_PUBLIC_API bool JS_StringHasBeenPinned(JSContext* cx, JSString* str) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-
-  if (!str->isAtom()) {
-    return false;
-  }
-
-  return str->asAtom().isPinned();
-}
-
-JS_PUBLIC_API jsid INTERNED_STRING_TO_JSID(JSContext* cx, JSString* str) {
-  MOZ_ASSERT(str);
-  MOZ_ASSERT(((size_t)str & JSID_TYPE_MASK) == 0);
-  MOZ_ASSERT_IF(cx, JS_StringHasBeenPinned(cx, str));
-  return AtomToId(&str->asAtom());
-}
-
-JS_PUBLIC_API JSString* JS_AtomizeAndPinJSString(JSContext* cx,
-                                                 HandleString str) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  JSAtom* atom = AtomizeString(cx, str, PinAtom);
-  MOZ_ASSERT_IF(atom, JS_StringHasBeenPinned(cx, atom));
-  return atom;
-}
-
-JS_PUBLIC_API JSString* JS_AtomizeString(JSContext* cx, const char* s) {
-  return JS_AtomizeStringN(cx, s, strlen(s));
-}
-
-JS_PUBLIC_API JSString* JS_AtomizeStringN(JSContext* cx, const char* s,
-                                          size_t length) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  return Atomize(cx, s, length, DoNotPinAtom);
-}
-
-JS_PUBLIC_API JSString* JS_AtomizeAndPinString(JSContext* cx, const char* s) {
-  return JS_AtomizeAndPinStringN(cx, s, strlen(s));
-}
-
-JS_PUBLIC_API JSString* JS_AtomizeAndPinStringN(JSContext* cx, const char* s,
-                                                size_t length) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  JSAtom* atom = Atomize(cx, s, length, PinAtom);
-  MOZ_ASSERT_IF(atom, JS_StringHasBeenPinned(cx, atom));
-  return atom;
-}
-
-JS_PUBLIC_API JSString* JS_NewLatin1String(
-    JSContext* cx, js::UniquePtr<JS::Latin1Char[], JS::FreePolicy> chars,
-    size_t length) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  return NewString(cx, std::move(chars), length);
-}
-
-JS_PUBLIC_API JSString* JS_NewUCString(JSContext* cx,
-                                       JS::UniqueTwoByteChars chars,
-                                       size_t length) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  return NewString(cx, std::move(chars), length);
-}
-
-JS_PUBLIC_API JSString* JS_NewUCStringDontDeflate(JSContext* cx,
-                                                  JS::UniqueTwoByteChars chars,
-                                                  size_t length) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  return NewStringDontDeflate(cx, std::move(chars), length);
-}
-
-JS_PUBLIC_API JSString* JS_NewUCStringCopyN(JSContext* cx, const char16_t* s,
-                                            size_t n) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  if (!n) {
-    return cx->names().empty;
-  }
-  return NewStringCopyN<CanGC>(cx, s, n);
-}
-
-JS_PUBLIC_API JSString* JS_NewUCStringCopyZ(JSContext* cx, const char16_t* s) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  if (!s) {
-    return cx->runtime()->emptyString;
-  }
-  return NewStringCopyZ<CanGC>(cx, s);
-}
-
-JS_PUBLIC_API JSString* JS_AtomizeUCString(JSContext* cx, const char16_t* s) {
-  return JS_AtomizeUCStringN(cx, s, js_strlen(s));
-}
-
-JS_PUBLIC_API JSString* JS_AtomizeUCStringN(JSContext* cx, const char16_t* s,
-                                            size_t length) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  return AtomizeChars(cx, s, length, DoNotPinAtom);
-}
-
-JS_PUBLIC_API JSString* JS_AtomizeAndPinUCStringN(JSContext* cx,
-                                                  const char16_t* s,
-                                                  size_t length) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  JSAtom* atom = AtomizeChars(cx, s, length, PinAtom);
-  MOZ_ASSERT_IF(atom, JS_StringHasBeenPinned(cx, atom));
-  return atom;
-}
-
-JS_PUBLIC_API JSString* JS_AtomizeAndPinUCString(JSContext* cx,
-                                                 const char16_t* s) {
-  return JS_AtomizeAndPinUCStringN(cx, s, js_strlen(s));
-}
-
-JS_PUBLIC_API size_t JS_GetStringLength(JSString* str) { return str->length(); }
-
-JS_PUBLIC_API bool JS_StringIsFlat(JSString* str) { return str->isFlat(); }
-
-JS_PUBLIC_API bool JS_StringHasLatin1Chars(JSString* str) {
-  return str->hasLatin1Chars();
-}
-
-JS_PUBLIC_API const JS::Latin1Char* JS_GetLatin1StringCharsAndLength(
-    JSContext* cx, const JS::AutoRequireNoGC& nogc, JSString* str,
-    size_t* plength) {
-  MOZ_ASSERT(plength);
-  AssertHeapIsIdleOrStringIsFlat(str);
-  CHECK_THREAD(cx);
-  cx->check(str);
-  JSLinearString* linear = str->ensureLinear(cx);
-  if (!linear) {
-    return nullptr;
-  }
-  *plength = linear->length();
-  return linear->latin1Chars(nogc);
-}
-
-JS_PUBLIC_API const char16_t* JS_GetTwoByteStringCharsAndLength(
-    JSContext* cx, const JS::AutoRequireNoGC& nogc, JSString* str,
-    size_t* plength) {
-  MOZ_ASSERT(plength);
-  AssertHeapIsIdleOrStringIsFlat(str);
-  CHECK_THREAD(cx);
-  cx->check(str);
-  JSLinearString* linear = str->ensureLinear(cx);
-  if (!linear) {
-    return nullptr;
-  }
-  *plength = linear->length();
-  return linear->twoByteChars(nogc);
-}
-
-JS_PUBLIC_API const char16_t* JS_GetTwoByteExternalStringChars(JSString* str) {
-  return str->asExternal().twoByteChars();
-}
-
-JS_PUBLIC_API bool JS_GetStringCharAt(JSContext* cx, JSString* str,
-                                      size_t index, char16_t* res) {
-  AssertHeapIsIdleOrStringIsFlat(str);
-  CHECK_THREAD(cx);
-  cx->check(str);
-
-  JSLinearString* linear = str->ensureLinear(cx);
-  if (!linear) {
-    return false;
-  }
-
-  *res = linear->latin1OrTwoByteChar(index);
-  return true;
-}
-
-JS_PUBLIC_API char16_t JS_GetFlatStringCharAt(JSFlatString* str, size_t index) {
-  return str->latin1OrTwoByteChar(index);
-}
-
-JS_PUBLIC_API bool JS_CopyStringChars(JSContext* cx,
-                                      mozilla::Range<char16_t> dest,
-                                      JSString* str) {
-  AssertHeapIsIdleOrStringIsFlat(str);
-  CHECK_THREAD(cx);
-  cx->check(str);
-
-  JSLinearString* linear = str->ensureLinear(cx);
-  if (!linear) {
-    return false;
-  }
-
-  MOZ_ASSERT(linear->length() <= dest.length());
-  CopyChars(dest.begin().get(), *linear);
-  return true;
-}
-
-JS_PUBLIC_API const Latin1Char* JS_GetLatin1InternedStringChars(
-    const JS::AutoRequireNoGC& nogc, JSString* str) {
-  MOZ_ASSERT(str->isAtom());
-  JSFlatString* flat = str->ensureFlat(nullptr);
-  if (!flat) {
-    return nullptr;
-  }
-  return flat->latin1Chars(nogc);
-}
-
-JS_PUBLIC_API const char16_t* JS_GetTwoByteInternedStringChars(
-    const JS::AutoRequireNoGC& nogc, JSString* str) {
-  MOZ_ASSERT(str->isAtom());
-  JSFlatString* flat = str->ensureFlat(nullptr);
-  if (!flat) {
-    return nullptr;
-  }
-  return flat->twoByteChars(nogc);
-}
-
-extern JS_PUBLIC_API JSFlatString* JS_FlattenString(JSContext* cx,
-                                                    JSString* str) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(str);
-  JSFlatString* flat = str->ensureFlat(cx);
-  if (!flat) {
-    return nullptr;
-  }
-  return flat;
-}
-
-extern JS_PUBLIC_API const Latin1Char* JS_GetLatin1FlatStringChars(
-    const JS::AutoRequireNoGC& nogc, JSFlatString* str) {
-  return str->latin1Chars(nogc);
-}
-
-extern JS_PUBLIC_API const char16_t* JS_GetTwoByteFlatStringChars(
-    const JS::AutoRequireNoGC& nogc, JSFlatString* str) {
-  return str->twoByteChars(nogc);
-}
-
-JS_PUBLIC_API bool JS_CompareStrings(JSContext* cx, JSString* str1,
-                                     JSString* str2, int32_t* result) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-
-  return CompareStrings(cx, str1, str2, result);
-}
-
-JS_PUBLIC_API bool JS_StringEqualsAscii(JSContext* cx, JSString* str,
-                                        const char* asciiBytes, bool* match) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-
-  JSLinearString* linearStr = str->ensureLinear(cx);
-  if (!linearStr) {
-    return false;
-  }
-  *match = StringEqualsAscii(linearStr, asciiBytes);
-  return true;
-}
-
-JS_PUBLIC_API bool JS_FlatStringEqualsAscii(JSFlatString* str,
-                                            const char* asciiBytes) {
-  return StringEqualsAscii(str, asciiBytes);
-}
-
-JS_PUBLIC_API size_t JS_PutEscapedFlatString(char* buffer, size_t size,
-                                             JSFlatString* str, char quote) {
-  return PutEscapedString(buffer, size, str, quote);
-}
-
-JS_PUBLIC_API size_t JS_PutEscapedString(JSContext* cx, char* buffer,
-                                         size_t size, JSString* str,
-                                         char quote) {
-  AssertHeapIsIdle();
-  JSLinearString* linearStr = str->ensureLinear(cx);
-  if (!linearStr) {
-    return size_t(-1);
-  }
-  return PutEscapedString(buffer, size, linearStr, quote);
-}
-
-JS_PUBLIC_API JSString* JS_NewDependentString(JSContext* cx, HandleString str,
-                                              size_t start, size_t length) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  return NewDependentString(cx, str, start, length);
-}
-
-JS_PUBLIC_API JSString* JS_ConcatStrings(JSContext* cx, HandleString left,
-                                         HandleString right) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  return ConcatStrings<CanGC>(cx, left, right);
-}
-
-JS_PUBLIC_API bool JS_DecodeBytes(JSContext* cx, const char* src, size_t srclen,
-                                  char16_t* dst, size_t* dstlenp) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-
-  if (!dst) {
-    *dstlenp = srclen;
-    return true;
-  }
-
-  size_t dstlen = *dstlenp;
-
-  if (srclen > dstlen) {
-    CopyAndInflateChars(dst, src, dstlen);
-
-    gc::AutoSuppressGC suppress(cx);
-    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
-                              JSMSG_BUFFER_TOO_SMALL);
-    return false;
-  }
-
-  CopyAndInflateChars(dst, src, srclen);
-  *dstlenp = srclen;
-  return true;
-}
-
-JS_PUBLIC_API JS::UniqueChars JS_EncodeStringToASCII(JSContext* cx,
-                                                     JSString* str) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-
-  return js::EncodeAscii(cx, str);
-}
-
-JS_PUBLIC_API JS::UniqueChars JS_EncodeStringToLatin1(JSContext* cx,
-                                                      JSString* str) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-
-  return js::EncodeLatin1(cx, str);
-}
-
-JS_PUBLIC_API JS::UniqueChars JS_EncodeStringToUTF8(JSContext* cx,
-                                                    HandleString str) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-
-  return StringToNewUTF8CharsZ(cx, *str);
-}
-
-JS_PUBLIC_API size_t JS_GetStringEncodingLength(JSContext* cx, JSString* str) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-
-  if (!str->ensureLinear(cx)) {
-    return size_t(-1);
-  }
-  return str->length();
-}
-
-JS_PUBLIC_API bool JS_EncodeStringToBuffer(JSContext* cx, JSString* str,
-                                           char* buffer, size_t length) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-
-  JSLinearString* linear = str->ensureLinear(cx);
-  if (!linear) {
-    return false;
-  }
-
-  JS::AutoCheckCannotGC nogc;
-  size_t writeLength = Min(linear->length(), length);
-  if (linear->hasLatin1Chars()) {
-    mozilla::PodCopy(reinterpret_cast<Latin1Char*>(buffer),
-                     linear->latin1Chars(nogc), writeLength);
-  } else {
-    const char16_t* src = linear->twoByteChars(nogc);
-    for (size_t i = 0; i < writeLength; i++) {
-      buffer[i] = char(src[i]);
-    }
-  }
-  return true;
-}
-
-JS_PUBLIC_API JS::Symbol* JS::NewSymbol(JSContext* cx,
-                                        HandleString description) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  if (description) {
-    cx->check(description);
-  }
-
-  return Symbol::new_(cx, SymbolCode::UniqueSymbol, description);
-}
-
-JS_PUBLIC_API JS::Symbol* JS::GetSymbolFor(JSContext* cx, HandleString key) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(key);
-
-  return Symbol::for_(cx, key);
-}
-
-JS_PUBLIC_API JSString* JS::GetSymbolDescription(HandleSymbol symbol) {
-  return symbol->description();
-}
-
-JS_PUBLIC_API JS::SymbolCode JS::GetSymbolCode(Handle<Symbol*> symbol) {
-  return symbol->code();
-}
-
-JS_PUBLIC_API JS::Symbol* JS::GetWellKnownSymbol(JSContext* cx,
-                                                 JS::SymbolCode which) {
-  return cx->wellKnownSymbols().get(which);
-}
-
-#ifdef DEBUG
-static bool PropertySpecNameIsDigits(JSPropertySpec::Name name) {
-  if (name.isSymbol()) {
-    return false;
-  }
-  const char* s = name.string();
-  if (!*s) {
-    return false;
-  }
-  for (; *s; s++) {
-    if (*s < '0' || *s > '9') {
-      return false;
-    }
-  }
-  return true;
-}
-#endif  // DEBUG
-
-JS_PUBLIC_API bool JS::PropertySpecNameEqualsId(JSPropertySpec::Name name,
-                                                HandleId id) {
-  if (name.isSymbol()) {
-    if (!JSID_IS_SYMBOL(id)) {
-      return false;
-    }
-    Symbol* sym = JSID_TO_SYMBOL(id);
-    return sym->isWellKnownSymbol() && sym->code() == name.symbol();
-  }
-
-  MOZ_ASSERT(!PropertySpecNameIsDigits(name));
-  return JSID_IS_ATOM(id) &&
-         JS_FlatStringEqualsAscii(JSID_TO_ATOM(id), name.string());
-}
-
-JS_PUBLIC_API bool JS_Stringify(JSContext* cx, MutableHandleValue vp,
-                                HandleObject replacer, HandleValue space,
-                                JSONWriteCallback callback, void* data) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(replacer, space);
-  StringBuffer sb(cx);
-  if (!sb.ensureTwoByteChars()) {
-    return false;
-  }
-  if (!Stringify(cx, vp, replacer, space, sb, StringifyBehavior::Normal)) {
-    return false;
-  }
-  if (sb.empty() && !sb.append(cx->names().null)) {
-    return false;
-  }
-  return callback(sb.rawTwoByteBegin(), sb.length(), data);
-}
-
-JS_PUBLIC_API bool JS::ToJSONMaybeSafely(JSContext* cx, JS::HandleObject input,
-                                         JSONWriteCallback callback,
-                                         void* data) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(input);
-
-  StringBuffer sb(cx);
-  if (!sb.ensureTwoByteChars()) {
-    return false;
-  }
-
-  RootedValue inputValue(cx, ObjectValue(*input));
-  if (!Stringify(cx, &inputValue, nullptr, NullHandleValue, sb,
-                 StringifyBehavior::RestrictedSafe))
-    return false;
-
-  if (sb.empty() && !sb.append(cx->names().null)) {
-    return false;
-  }
-
-  return callback(sb.rawTwoByteBegin(), sb.length(), data);
-}
-
-JS_PUBLIC_API bool JS_ParseJSON(JSContext* cx, const char16_t* chars,
-                                uint32_t len, MutableHandleValue vp) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  return ParseJSONWithReviver(cx, mozilla::Range<const char16_t>(chars, len),
-                              NullHandleValue, vp);
-}
-
-JS_PUBLIC_API bool JS_ParseJSON(JSContext* cx, HandleString str,
-                                MutableHandleValue vp) {
-  return JS_ParseJSONWithReviver(cx, str, NullHandleValue, vp);
-}
-
-JS_PUBLIC_API bool JS_ParseJSONWithReviver(JSContext* cx, const char16_t* chars,
-                                           uint32_t len, HandleValue reviver,
-                                           MutableHandleValue vp) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  return ParseJSONWithReviver(cx, mozilla::Range<const char16_t>(chars, len),
-                              reviver, vp);
-}
-
-JS_PUBLIC_API bool JS_ParseJSONWithReviver(JSContext* cx, HandleString str,
-                                           HandleValue reviver,
-                                           MutableHandleValue vp) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(str);
-
-  AutoStableStringChars stableChars(cx);
-  if (!stableChars.init(cx, str)) {
-    return false;
-  }
-
-  return stableChars.isLatin1()
-             ? ParseJSONWithReviver(cx, stableChars.latin1Range(), reviver, vp)
-             : ParseJSONWithReviver(cx, stableChars.twoByteRange(), reviver,
-                                    vp);
-}
-
-/************************************************************************/
-
-JS_PUBLIC_API void JS_ReportErrorASCII(JSContext* cx, const char* format, ...) {
-  va_list ap;
-
-  AssertHeapIsIdle();
-  va_start(ap, format);
-  ReportErrorVA(cx, JSREPORT_ERROR, format, ArgumentsAreASCII, ap);
-  va_end(ap);
-}
-
-JS_PUBLIC_API void JS_ReportErrorLatin1(JSContext* cx, const char* format,
-                                        ...) {
-  va_list ap;
-
-  AssertHeapIsIdle();
-  va_start(ap, format);
-  ReportErrorVA(cx, JSREPORT_ERROR, format, ArgumentsAreLatin1, ap);
-  va_end(ap);
-}
-
-JS_PUBLIC_API void JS_ReportErrorUTF8(JSContext* cx, const char* format, ...) {
-  va_list ap;
-
-  AssertHeapIsIdle();
-  va_start(ap, format);
-  ReportErrorVA(cx, JSREPORT_ERROR, format, ArgumentsAreUTF8, ap);
-  va_end(ap);
-}
-
-JS_PUBLIC_API void JS_ReportErrorNumberASCII(JSContext* cx,
-                                             JSErrorCallback errorCallback,
-                                             void* userRef,
-                                             const unsigned errorNumber, ...) {
-  va_list ap;
-  va_start(ap, errorNumber);
-  JS_ReportErrorNumberASCIIVA(cx, errorCallback, userRef, errorNumber, ap);
-  va_end(ap);
-}
-
-JS_PUBLIC_API void JS_ReportErrorNumberASCIIVA(JSContext* cx,
-                                               JSErrorCallback errorCallback,
-                                               void* userRef,
-                                               const unsigned errorNumber,
-                                               va_list ap) {
-  AssertHeapIsIdle();
-  ReportErrorNumberVA(cx, JSREPORT_ERROR, errorCallback, userRef, errorNumber,
-                      ArgumentsAreASCII, ap);
-}
-
-JS_PUBLIC_API void JS_ReportErrorNumberLatin1(JSContext* cx,
-                                              JSErrorCallback errorCallback,
-                                              void* userRef,
-                                              const unsigned errorNumber, ...) {
-  va_list ap;
-  va_start(ap, errorNumber);
-  JS_ReportErrorNumberLatin1VA(cx, errorCallback, userRef, errorNumber, ap);
-  va_end(ap);
-}
-
-JS_PUBLIC_API void JS_ReportErrorNumberLatin1VA(JSContext* cx,
-                                                JSErrorCallback errorCallback,
-                                                void* userRef,
-                                                const unsigned errorNumber,
-                                                va_list ap) {
-  AssertHeapIsIdle();
-  ReportErrorNumberVA(cx, JSREPORT_ERROR, errorCallback, userRef, errorNumber,
-                      ArgumentsAreLatin1, ap);
-}
-
-JS_PUBLIC_API void JS_ReportErrorNumberUTF8(JSContext* cx,
-                                            JSErrorCallback errorCallback,
-                                            void* userRef,
-                                            const unsigned errorNumber, ...) {
-  va_list ap;
-  va_start(ap, errorNumber);
-  JS_ReportErrorNumberUTF8VA(cx, errorCallback, userRef, errorNumber, ap);
-  va_end(ap);
-}
-
-JS_PUBLIC_API void JS_ReportErrorNumberUTF8VA(JSContext* cx,
-                                              JSErrorCallback errorCallback,
-                                              void* userRef,
-                                              const unsigned errorNumber,
-                                              va_list ap) {
-  AssertHeapIsIdle();
-  ReportErrorNumberVA(cx, JSREPORT_ERROR, errorCallback, userRef, errorNumber,
-                      ArgumentsAreUTF8, ap);
-}
-
-JS_PUBLIC_API void JS_ReportErrorNumberUC(JSContext* cx,
-                                          JSErrorCallback errorCallback,
-                                          void* userRef,
-                                          const unsigned errorNumber, ...) {
-  va_list ap;
-
-  AssertHeapIsIdle();
-  va_start(ap, errorNumber);
-  ReportErrorNumberVA(cx, JSREPORT_ERROR, errorCallback, userRef, errorNumber,
-                      ArgumentsAreUnicode, ap);
-  va_end(ap);
-}
-
-JS_PUBLIC_API void JS_ReportErrorNumberUCArray(JSContext* cx,
-                                               JSErrorCallback errorCallback,
-                                               void* userRef,
-                                               const unsigned errorNumber,
-                                               const char16_t** args) {
-  AssertHeapIsIdle();
-  ReportErrorNumberUCArray(cx, JSREPORT_ERROR, errorCallback, userRef,
-                           errorNumber, args);
-}
-
-JS_PUBLIC_API bool JS_ReportErrorFlagsAndNumberASCII(
-    JSContext* cx, unsigned flags, JSErrorCallback errorCallback, void* userRef,
-    const unsigned errorNumber, ...) {
-  va_list ap;
-  bool ok;
-
-  AssertHeapIsIdle();
-  va_start(ap, errorNumber);
-  ok = ReportErrorNumberVA(cx, flags, errorCallback, userRef, errorNumber,
-                           ArgumentsAreASCII, ap);
-  va_end(ap);
-  return ok;
-}
-
-JS_PUBLIC_API bool JS_ReportErrorFlagsAndNumberLatin1(
-    JSContext* cx, unsigned flags, JSErrorCallback errorCallback, void* userRef,
-    const unsigned errorNumber, ...) {
-  va_list ap;
-  bool ok;
-
-  AssertHeapIsIdle();
-  va_start(ap, errorNumber);
-  ok = ReportErrorNumberVA(cx, flags, errorCallback, userRef, errorNumber,
-                           ArgumentsAreLatin1, ap);
-  va_end(ap);
-  return ok;
-}
-
-JS_PUBLIC_API bool JS_ReportErrorFlagsAndNumberUTF8(
-    JSContext* cx, unsigned flags, JSErrorCallback errorCallback, void* userRef,
-    const unsigned errorNumber, ...) {
-  va_list ap;
-  bool ok;
-
-  AssertHeapIsIdle();
-  va_start(ap, errorNumber);
-  ok = ReportErrorNumberVA(cx, flags, errorCallback, userRef, errorNumber,
-                           ArgumentsAreUTF8, ap);
-  va_end(ap);
-  return ok;
-}
-
-JS_PUBLIC_API bool JS_ReportErrorFlagsAndNumberUC(JSContext* cx, unsigned flags,
-                                                  JSErrorCallback errorCallback,
-                                                  void* userRef,
-                                                  const unsigned errorNumber,
-                                                  ...) {
-  va_list ap;
-  bool ok;
-
-  AssertHeapIsIdle();
-  va_start(ap, errorNumber);
-  ok = ReportErrorNumberVA(cx, flags, errorCallback, userRef, errorNumber,
-                           ArgumentsAreUnicode, ap);
-  va_end(ap);
-  return ok;
-}
-
-JS_PUBLIC_API void JS_ReportOutOfMemory(JSContext* cx) {
-  ReportOutOfMemory(cx);
-}
-
-JS_PUBLIC_API void JS_ReportAllocationOverflow(JSContext* cx) {
-  ReportAllocationOverflow(cx);
-}
-
-/************************************************************************/
-
-JS_PUBLIC_API bool JS_SetDefaultLocale(JSRuntime* rt, const char* locale) {
-  AssertHeapIsIdle();
-  return rt->setDefaultLocale(locale);
-}
-
-JS_PUBLIC_API UniqueChars JS_GetDefaultLocale(JSContext* cx) {
-  AssertHeapIsIdle();
-  if (const char* locale = cx->runtime()->getDefaultLocale()) {
-    return DuplicateString(cx, locale);
-  }
-
-  return nullptr;
-}
-
-JS_PUBLIC_API void JS_ResetDefaultLocale(JSRuntime* rt) {
-  AssertHeapIsIdle();
-  rt->resetDefaultLocale();
-}
-
-JS_PUBLIC_API void JS_SetLocaleCallbacks(JSRuntime* rt,
-                                         const JSLocaleCallbacks* callbacks) {
-  AssertHeapIsIdle();
-  rt->localeCallbacks = callbacks;
-}
-
-JS_PUBLIC_API const JSLocaleCallbacks* JS_GetLocaleCallbacks(JSRuntime* rt) {
-  /* This function can be called by a finalizer. */
-  return rt->localeCallbacks;
-}
-
-/************************************************************************/
-
-JS_PUBLIC_API bool JS_IsExceptionPending(JSContext* cx) {
-  /* This function can be called by a finalizer. */
-  return (bool)cx->isExceptionPending();
-}
-
-JS_PUBLIC_API bool JS_GetPendingException(JSContext* cx,
-                                          MutableHandleValue vp) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  if (!cx->isExceptionPending()) {
-    return false;
-  }
-  return cx->getPendingException(vp);
-}
-
-JS_PUBLIC_API void JS_SetPendingException(JSContext* cx, HandleValue value,
-                                          JS::ExceptionStackBehavior behavior) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->releaseCheck(value);
-
-  if (behavior == JS::ExceptionStackBehavior::Capture) {
-    cx->setPendingExceptionAndCaptureStack(value);
-  } else {
-    cx->setPendingException(value, nullptr);
-  }
-}
-
-JS_PUBLIC_API void JS_ClearPendingException(JSContext* cx) {
-  AssertHeapIsIdle();
-  cx->clearPendingException();
-}
-
-JS_PUBLIC_API void JS::SetPendingExceptionAndStack(JSContext* cx,
-                                                   HandleValue value,
-                                                   HandleObject stack) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->releaseCheck(value);
-  cx->releaseCheck(stack);
-
-  RootedSavedFrame nstack(cx);
-  if (stack) {
-    nstack = &UncheckedUnwrap(stack)->as<SavedFrame>();
-  }
-  cx->setPendingException(value, nstack);
-}
-
-JS_PUBLIC_API JSObject* JS::GetPendingExceptionStack(JSContext* cx) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  return cx->getPendingExceptionStack();
-}
-
-JS::AutoSaveExceptionState::AutoSaveExceptionState(JSContext* cx)
-    : context(cx),
-      wasPropagatingForcedReturn(cx->propagatingForcedReturn_),
-      wasOverRecursed(cx->overRecursed_),
-      wasThrowing(cx->throwing),
-      exceptionValue(cx),
-      exceptionStack(cx) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  if (wasPropagatingForcedReturn) {
-    cx->clearPropagatingForcedReturn();
-  }
-  if (wasOverRecursed) {
-    cx->overRecursed_ = false;
-  }
-  if (wasThrowing) {
-    exceptionValue = cx->unwrappedException();
-    exceptionStack = cx->unwrappedExceptionStack();
-    cx->clearPendingException();
-  }
-}
-
-void JS::AutoSaveExceptionState::drop() {
-  wasPropagatingForcedReturn = false;
-  wasOverRecursed = false;
-  wasThrowing = false;
-  exceptionValue.setUndefined();
-  exceptionStack = nullptr;
-}
-
-void JS::AutoSaveExceptionState::restore() {
-  context->propagatingForcedReturn_ = wasPropagatingForcedReturn;
-  context->overRecursed_ = wasOverRecursed;
-  context->throwing = wasThrowing;
-  context->unwrappedException() = exceptionValue;
-  if (exceptionStack) {
-    context->unwrappedExceptionStack() = &exceptionStack->as<SavedFrame>();
-  }
-  drop();
-}
-
-JS::AutoSaveExceptionState::~AutoSaveExceptionState() {
-  if (!context->isExceptionPending()) {
-    if (wasPropagatingForcedReturn) {
-      context->setPropagatingForcedReturn();
-    }
-    if (wasThrowing) {
-      context->overRecursed_ = wasOverRecursed;
-      context->throwing = true;
-      context->unwrappedException() = exceptionValue;
-      if (exceptionStack) {
-        context->unwrappedExceptionStack() = &exceptionStack->as<SavedFrame>();
-      }
-    }
-  }
-}
-
-struct JSExceptionState {
-  explicit JSExceptionState(JSContext* cx) : throwing(false), exception(cx) {}
-  bool throwing;
-  PersistentRootedValue exception;
-};
-
-JS_PUBLIC_API JSExceptionState* JS_SaveExceptionState(JSContext* cx) {
-  JSExceptionState* state;
-
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  state = cx->new_<JSExceptionState>(cx);
-  if (state) {
-    state->throwing = JS_GetPendingException(cx, &state->exception);
-  }
-  return state;
-}
-
-JS_PUBLIC_API void JS_RestoreExceptionState(JSContext* cx,
-                                            JSExceptionState* state) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  if (state) {
-    if (state->throwing) {
-      JS_SetPendingException(cx, state->exception);
-    } else {
-      JS_ClearPendingException(cx);
-    }
-    JS_DropExceptionState(cx, state);
-  }
-}
-
-JS_PUBLIC_API void JS_DropExceptionState(JSContext* cx,
-                                         JSExceptionState* state) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  js_delete(state);
-}
-
-JS_PUBLIC_API JSErrorReport* JS_ErrorFromException(JSContext* cx,
-                                                   HandleObject obj) {
-  AssertHeapIsIdle();
-  CHECK_THREAD(cx);
-  cx->check(obj);
-  return ErrorFromException(cx, obj);
-}
-
-void JSErrorReport::initBorrowedLinebuf(const char16_t* linebufArg,
-                                        size_t linebufLengthArg,
-                                        size_t tokenOffsetArg) {
-  MOZ_ASSERT(linebufArg);
-  MOZ_ASSERT(tokenOffsetArg <= linebufLengthArg);
-  MOZ_ASSERT(linebufArg[linebufLengthArg] == '\0');
-
-  linebuf_ = linebufArg;
-  linebufLength_ = linebufLengthArg;
-  tokenOffset_ = tokenOffsetArg;
-}
-
-void JSErrorReport::freeLinebuf() {
-  if (ownsLinebuf_ && linebuf_) {
-    js_free((void*)linebuf_);
-    ownsLinebuf_ = false;
-  }
-  linebuf_ = nullptr;
-}
-
-JSString* JSErrorBase::newMessageString(JSContext* cx) {
-  if (!message_) {
-    return cx->runtime()->emptyString;
-  }
-
-  return JS_NewStringCopyUTF8Z(cx, message_);
-}
-
-void JSErrorBase::freeMessage() {
-  if (ownsMessage_) {
-    js_free((void*)message_.get());
-    ownsMessage_ = false;
-  }
-  message_ = JS::ConstUTF8CharsZ();
-}
-
-JSErrorNotes::JSErrorNotes() : notes_() {}
-
-JSErrorNotes::~JSErrorNotes() {}
-
-static UniquePtr<JSErrorNotes::Note> CreateErrorNoteVA(
-    JSContext* cx, const char* filename, unsigned sourceId, unsigned lineno,
-    unsigned column, JSErrorCallback errorCallback, void* userRef,
-    const unsigned errorNumber, ErrorArgumentsType argumentsType, va_list ap) {
-  auto note = MakeUnique<JSErrorNotes::Note>();
-  if (!note) {
-    ReportOutOfMemory(cx);
-    return nullptr;
-  }
-
-  note->errorNumber = errorNumber;
-  note->filename = filename;
-  note->sourceId = sourceId;
-  note->lineno = lineno;
-  note->column = column;
-
-  if (!ExpandErrorArgumentsVA(cx, errorCallback, userRef, errorNumber, nullptr,
-                              argumentsType, note.get(), ap)) {
-    return nullptr;
-  }
-
-  return note;
-}
-
-bool JSErrorNotes::addNoteASCII(JSContext* cx, const char* filename,
-                                unsigned sourceId, unsigned lineno,
-                                unsigned column, JSErrorCallback errorCallback,
-                                void* userRef, const unsigned errorNumber,
-                                ...) {
-  va_list ap;
-  va_start(ap, errorNumber);
-  auto note =
-      CreateErrorNoteVA(cx, filename, sourceId, lineno, column, errorCallback,
-                        userRef, errorNumber, ArgumentsAreASCII, ap);
-  va_end(ap);
-
-  if (!note) {
-    return false;
-  }
-  if (!notes_.append(std::move(note))) {
-    ReportOutOfMemory(cx);
-    return false;
-  }
-  return true;
-}
-
-bool JSErrorNotes::addNoteLatin1(JSContext* cx, const char* filename,
-                                 unsigned sourceId, unsigned lineno,
-                                 unsigned column, JSErrorCallback errorCallback,
-                                 void* userRef, const unsigned errorNumber,
-                                 ...) {
-  va_list ap;
-  va_start(ap, errorNumber);
-  auto note =
-      CreateErrorNoteVA(cx, filename, sourceId, lineno, column, errorCallback,
-                        userRef, errorNumber, ArgumentsAreLatin1, ap);
-  va_end(ap);
-
-  if (!note) {
-    return false;
-  }
-  if (!notes_.append(std::move(note))) {
-    ReportOutOfMemory(cx);
-    return false;
-  }
-  return true;
-}
-
-bool JSErrorNotes::addNoteUTF8(JSContext* cx, const char* filename,
-                               unsigned sourceId, unsigned lineno,
-                               unsigned column, JSErrorCallback errorCallback,
-                               void* userRef, const unsigned errorNumber, ...) {
-  va_list ap;
-  va_start(ap, errorNumber);
-  auto note =
-      CreateErrorNoteVA(cx, filename, sourceId, lineno, column, errorCallback,
-                        userRef, errorNumber, ArgumentsAreUTF8, ap);
-  va_end(ap);
-
-  if (!note) {
-    return false;
-  }
-  if (!notes_.append(std::move(note))) {
-    ReportOutOfMemory(cx);
-    return false;
-  }
-  return true;
-}
-
-JS_PUBLIC_API size_t JSErrorNotes::length() { return notes_.length(); }
-
-UniquePtr<JSErrorNotes> JSErrorNotes::copy(JSContext* cx) {
-  auto copiedNotes = MakeUnique<JSErrorNotes>();
-  if (!copiedNotes) {
-    ReportOutOfMemory(cx);
-    return nullptr;
-  }
-
-  for (auto&& note : *this) {
-    UniquePtr<JSErrorNotes::Note> copied = CopyErrorNote(cx, note.get());
-    if (!copied) {
-      return nullptr;
-    }
-
-    if (!copiedNotes->notes_.append(std::move(copied))) {
-      return nullptr;
-    }
-  }
-
-  return copiedNotes;
-}
-
-JS_PUBLIC_API JSErrorNotes::iterator JSErrorNotes::begin() {
-  return iterator(notes_.begin());
-}
-
-JS_PUBLIC_API JSErrorNotes::iterator JSErrorNotes::end() {
-  return iterator(notes_.end());
-}
-
-extern MOZ_NEVER_INLINE JS_PUBLIC_API void JS_AbortIfWrongThread(
-    JSContext* cx) {
-  if (!CurrentThreadCanAccessRuntime(cx->runtime())) {
-    MOZ_CRASH();
-  }
-  if (TlsContext.get() != cx) {
-    MOZ_CRASH();
-  }
-}
-
-#ifdef JS_GC_ZEAL
-JS_PUBLIC_API void JS_GetGCZealBits(JSContext* cx, uint32_t* zealBits,
-                                    uint32_t* frequency,
-                                    uint32_t* nextScheduled) {
-  cx->runtime()->gc.getZealBits(zealBits, frequency, nextScheduled);
-}
-
-JS_PUBLIC_API void JS_SetGCZeal(JSContext* cx, uint8_t zeal,
-                                uint32_t frequency) {
-  cx->runtime()->gc.setZeal(zeal, frequency);
-}
-
-JS_PUBLIC_API void JS_UnsetGCZeal(JSContext* cx, uint8_t zeal) {
-  cx->runtime()->gc.unsetZeal(zeal);
-}
-
-JS_PUBLIC_API void JS_ScheduleGC(JSContext* cx, uint32_t count) {
-  cx->runtime()->gc.setNextScheduled(count);
-}
-#endif
-
-JS_PUBLIC_API void JS_SetParallelParsingEnabled(JSContext* cx, bool enabled) {
-  cx->runtime()->setParallelParsingEnabled(enabled);
-}
-
-JS_PUBLIC_API void JS_SetOffthreadIonCompilationEnabled(JSContext* cx,
-                                                        bool enabled) {
-  cx->runtime()->setOffthreadIonCompilationEnabled(enabled);
-}
-
-JS_PUBLIC_API void JS_SetGlobalJitCompilerOption(JSContext* cx,
-                                                 JSJitCompilerOption opt,
-                                                 uint32_t value) {
-  JSRuntime* rt = cx->runtime();
-  switch (opt) {
-    case JSJITCOMPILER_BASELINE_WARMUP_TRIGGER:
-      if (value == uint32_t(-1)) {
-        jit::DefaultJitOptions defaultValues;
-        value = defaultValues.baselineWarmUpThreshold;
-      }
-      jit::JitOptions.baselineWarmUpThreshold = value;
-      break;
-    case JSJITCOMPILER_ION_NORMAL_WARMUP_TRIGGER:
-      if (value == uint32_t(-1)) {
-        jit::JitOptions.resetNormalIonWarmUpThreshold();
-        break;
-      }
-      jit::JitOptions.setNormalIonWarmUpThreshold(value);
-      break;
-    case JSJITCOMPILER_ION_FULL_WARMUP_TRIGGER:
-      if (value == uint32_t(-1)) {
-        jit::JitOptions.resetFullIonWarmUpThreshold();
-        break;
-      }
-      jit::JitOptions.setFullIonWarmUpThreshold(value);
-      break;
-    case JSJITCOMPILER_ION_GVN_ENABLE:
-      if (value == 0) {
-        jit::JitOptions.enableGvn(false);
-        JitSpew(js::jit::JitSpew_IonScripts, "Disable ion's GVN");
-      } else {
-        jit::JitOptions.enableGvn(true);
-        JitSpew(js::jit::JitSpew_IonScripts, "Enable ion's GVN");
-      }
-      break;
-    case JSJITCOMPILER_ION_FORCE_IC:
-      if (value == 0) {
-        jit::JitOptions.forceInlineCaches = false;
-        JitSpew(js::jit::JitSpew_IonScripts,
-                "IonBuilder: Enable non-IC optimizations.");
-      } else {
-        jit::JitOptions.forceInlineCaches = true;
-        JitSpew(js::jit::JitSpew_IonScripts,
-                "IonBuilder: Disable non-IC optimizations.");
-      }
-      break;
-    case JSJITCOMPILER_ION_CHECK_RANGE_ANALYSIS:
-      if (value == 0) {
-        jit::JitOptions.checkRangeAnalysis = false;
-        JitSpew(js::jit::JitSpew_IonScripts,
-                "IonBuilder: Enable range analysis checks.");
-      } else {
-        jit::JitOptions.checkRangeAnalysis = true;
-        JitSpew(js::jit::JitSpew_IonScripts,
-                "IonBuilder: Disable range analysis checks.");
-      }
-      break;
-    case JSJITCOMPILER_ION_ENABLE:
-      if (value == 1) {
-        JS::ContextOptionsRef(cx).setIon(true);
-        JitSpew(js::jit::JitSpew_IonScripts, "Enable ion");
-      } else if (value == 0) {
-        JS::ContextOptionsRef(cx).setIon(false);
-        JitSpew(js::jit::JitSpew_IonScripts, "Disable ion");
-      }
-      break;
-    case JSJITCOMPILER_ION_FREQUENT_BAILOUT_THRESHOLD:
-      if (value == uint32_t(-1)) {
-        jit::DefaultJitOptions defaultValues;
-        value = defaultValues.frequentBailoutThreshold;
-      }
-      jit::JitOptions.frequentBailoutThreshold = value;
-      break;
-    case JSJITCOMPILER_BASELINE_ENABLE:
-      if (value == 1) {
-        JS::ContextOptionsRef(cx).setBaseline(true);
-        ReleaseAllJITCode(rt->defaultFreeOp());
-        JitSpew(js::jit::JitSpew_BaselineScripts, "Enable baseline");
-      } else if (value == 0) {
-        JS::ContextOptionsRef(cx).setBaseline(false);
-        ReleaseAllJITCode(rt->defaultFreeOp());
-        JitSpew(js::jit::JitSpew_BaselineScripts, "Disable baseline");
-      }
-      break;
-    case JSJITCOMPILER_OFFTHREAD_COMPILATION_ENABLE:
-      if (value == 1) {
-        rt->setOffthreadIonCompilationEnabled(true);
-        JitSpew(js::jit::JitSpew_IonScripts, "Enable offthread compilation");
-      } else if (value == 0) {
-        rt->setOffthreadIonCompilationEnabled(false);
-        JitSpew(js::jit::JitSpew_IonScripts, "Disable offthread compilation");
-      }
-      break;
-    case JSJITCOMPILER_JUMP_THRESHOLD:
-      if (value == uint32_t(-1)) {
-        jit::DefaultJitOptions defaultValues;
-        value = defaultValues.jumpThreshold;
-      }
-      jit::JitOptions.jumpThreshold = value;
-      break;
-    case JSJITCOMPILER_TRACK_OPTIMIZATIONS:
-      jit::JitOptions.disableOptimizationTracking = !value;
-      break;
-    case JSJITCOMPILER_SPECTRE_INDEX_MASKING:
-      jit::JitOptions.spectreIndexMasking = !!value;
-      break;
-    case JSJITCOMPILER_SPECTRE_OBJECT_MITIGATIONS_BARRIERS:
-      jit::JitOptions.spectreObjectMitigationsBarriers = !!value;
-      break;
-    case JSJITCOMPILER_SPECTRE_OBJECT_MITIGATIONS_MISC:
-      jit::JitOptions.spectreObjectMitigationsMisc = !!value;
-      break;
-    case JSJITCOMPILER_SPECTRE_STRING_MITIGATIONS:
-      jit::JitOptions.spectreStringMitigations = !!value;
-      break;
-    case JSJITCOMPILER_SPECTRE_VALUE_MASKING:
-      jit::JitOptions.spectreValueMasking = !!value;
-      break;
-    case JSJITCOMPILER_SPECTRE_JIT_TO_CXX_CALLS:
-      jit::JitOptions.spectreJitToCxxCalls = !!value;
-      break;
-    case JSJITCOMPILER_WASM_FOLD_OFFSETS:
-      jit::JitOptions.wasmFoldOffsets = !!value;
-      break;
-    case JSJITCOMPILER_WASM_DELAY_TIER2:
-      jit::JitOptions.wasmDelayTier2 = !!value;
-      break;
-#ifdef DEBUG
-    case JSJITCOMPILER_FULL_DEBUG_CHECKS:
-      jit::JitOptions.fullDebugChecks = !!value;
-      break;
-#endif
-    default:
-      break;
-  }
-}
-
-JS_PUBLIC_API bool JS_GetGlobalJitCompilerOption(JSContext* cx,
-                                                 JSJitCompilerOption opt,
-                                                 uint32_t* valueOut) {
-  MOZ_ASSERT(valueOut);
-#ifndef JS_CODEGEN_NONE
-  JSRuntime* rt = cx->runtime();
-  switch (opt) {
-    case JSJITCOMPILER_BASELINE_WARMUP_TRIGGER:
-      *valueOut = jit::JitOptions.baselineWarmUpThreshold;
-      break;
-    case JSJITCOMPILER_ION_NORMAL_WARMUP_TRIGGER:
-      *valueOut = jit::JitOptions.normalIonWarmUpThreshold;
-      break;
-    case JSJITCOMPILER_ION_FULL_WARMUP_TRIGGER:
-      *valueOut = jit::JitOptions.fullIonWarmUpThreshold;
-      break;
-    case JSJITCOMPILER_ION_FORCE_IC:
-      *valueOut = jit::JitOptions.forceInlineCaches;
-      break;
-    case JSJITCOMPILER_ION_CHECK_RANGE_ANALYSIS:
-      *valueOut = jit::JitOptions.checkRangeAnalysis;
-      break;
-    case JSJITCOMPILER_ION_ENABLE:
-      *valueOut = JS::ContextOptionsRef(cx).ion();
-      break;
-    case JSJITCOMPILER_ION_FREQUENT_BAILOUT_THRESHOLD:
-      *valueOut = jit::JitOptions.frequentBailoutThreshold;
-      break;
-    case JSJITCOMPILER_BASELINE_ENABLE:
-      *valueOut = JS::ContextOptionsRef(cx).baseline();
-      break;
-    case JSJITCOMPILER_OFFTHREAD_COMPILATION_ENABLE:
-      *valueOut = rt->canUseOffthreadIonCompilation();
-      break;
-    case JSJITCOMPILER_WASM_FOLD_OFFSETS:
-      *valueOut = jit::JitOptions.wasmFoldOffsets ? 1 : 0;
-      break;
-#  ifdef DEBUG
-    case JSJITCOMPILER_FULL_DEBUG_CHECKS:
-      *valueOut = jit::JitOptions.fullDebugChecks ? 1 : 0;
-      break;
-#  endif
-    default:
-      return false;
-  }
-#else
-  *valueOut = 0;
-#endif
-  return true;
-}
-
-/************************************************************************/
-
-#if !defined(STATIC_EXPORTABLE_JS_API) && !defined(STATIC_JS_API) && \
-    defined(XP_WIN)
-
-#  include "util/Windows.h"
-
-/*
- * Initialization routine for the JS DLL.
- */
-BOOL WINAPI DllMain(HINSTANCE hDLL, DWORD dwReason, LPVOID lpReserved) {
-  return TRUE;
-}
-
-#endif
-
-JS_PUBLIC_API bool JS_IndexToId(JSContext* cx, uint32_t index,
-                                MutableHandleId id) {
-  return IndexToId(cx, index, id);
-}
-
-JS_PUBLIC_API bool JS_CharsToId(JSContext* cx, JS::TwoByteChars chars,
-                                MutableHandleId idp) {
-  RootedAtom atom(cx, AtomizeChars(cx, chars.begin().get(), chars.length()));
-  if (!atom) {
-    return false;
-  }
-#ifdef DEBUG
-  uint32_t dummy;
-  MOZ_ASSERT(!atom->isIndex(&dummy),
-             "API misuse: |chars| must not encode an index");
-#endif
-  idp.set(AtomToId(atom));
-  return true;
-}
-
-JS_PUBLIC_API bool JS_IsIdentifier(JSContext* cx, HandleString str,
-                                   bool* isIdentifier) {
-  cx->check(str);
-
-  JSLinearString* linearStr = str->ensureLinear(cx);
-  if (!linearStr) {
-    return false;
-  }
-
-  *isIdentifier = js::frontend::IsIdentifier(linearStr);
-  return true;
-}
-
-JS_PUBLIC_API bool JS_IsIdentifier(const char16_t* chars, size_t length) {
-  return js::frontend::IsIdentifier(chars, length);
-}
-
-namespace JS {
-
-void AutoFilename::reset() {
-  if (ss_) {
-    ss_->decref();
-    ss_ = nullptr;
-  }
-  if (filename_.is<const char*>()) {
-    filename_.as<const char*>() = nullptr;
-  } else {
-    filename_.as<UniqueChars>().reset();
-  }
-}
-
-void AutoFilename::setScriptSource(js::ScriptSource* p) {
-  MOZ_ASSERT(!ss_);
-  MOZ_ASSERT(!get());
-  ss_ = p;
-  if (p) {
-    p->incref();
-    setUnowned(p->filename());
-  }
-}
-
-void AutoFilename::setUnowned(const char* filename) {
-  MOZ_ASSERT(!get());
-  filename_.as<const char*>() = filename ? filename : "";
-}
-
-void AutoFilename::setOwned(UniqueChars&& filename) {
-  MOZ_ASSERT(!get());
-  filename_ = AsVariant(std::move(filename));
-}
-
-const char* AutoFilename::get() const {
-  if (filename_.is<const char*>()) {
-    return filename_.as<const char*>();
-  }
-  return filename_.as<UniqueChars>().get();
-}
-
-JS_PUBLIC_API bool DescribeScriptedCaller(JSContext* cx, AutoFilename* filename,
-                                          unsigned* lineno, unsigned* column) {
-  if (filename) {
-    filename->reset();
-  }
-  if (lineno) {
-    *lineno = 0;
-  }
-  if (column) {
-    *column = 0;
-  }
-
-  if (!cx->compartment()) {
-    return false;
-  }
-
-  NonBuiltinFrameIter i(cx, cx->realm()->principals());
-  if (i.done()) {
-    return false;
-  }
-
-  // If the caller is hidden, the embedding wants us to return false here so
-  // that it can check its own stack (see HideScriptedCaller).
-  if (i.activation()->scriptedCallerIsHidden()) {
-    return false;
-  }
-
-  if (filename) {
-    if (i.isWasm()) {
-      // For Wasm, copy out the filename, there is no script source.
-      UniqueChars copy = DuplicateString(i.filename() ? i.filename() : "");
-      if (!copy) {
-        filename->setUnowned("out of memory");
-      } else {
-        filename->setOwned(std::move(copy));
-      }
-    } else {
-      // All other frames have a script source to read the filename from.
-      filename->setScriptSource(i.scriptSource());
-    }
-  }
-
-  if (lineno) {
-    *lineno = i.computeLine(column);
-  } else if (column) {
-    i.computeLine(column);
-  }
-