UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

2,738 lines • 87.2 kB
//#region node_modules/.pnpm/quickjs-wasi@3.6.3/node_modules/quickjs-wasi/dist/wasi-shim.js
/**
* Minimal WASI shim for running QuickJS in any WebAssembly environment.
*
* Implements the subset of WASI snapshot_preview1 that QuickJS needs:
*   - clock_time_get (for Date.now() and Math.random() PRNG seeding)
*   - fd_write (for QuickJS runtime internal logging)
*   - fd_close (stub)
*   - fd_fdstat_get (stub)
*   - fd_seek (stub)
*   - random_get (for crypto extension and WASI libc init)
*
* Users can override any of these by providing their own implementations
* in the `wasi` option when creating a VM. Overrides are applied to both
* the main module and all loaded extensions.
*/
/** Returns a wasi_snapshot_preview1 import object with built-in defaults. */
function createWasiShim(e) {
	const t = 0;
	const n = 8;
	const r = 52;
	const i = 0;
	const a = 1;
	return {
		clock_time_get(n, o, s) {
			const c = e();
			const l = new DataView(c.buffer);
			if (n === i || n === a) {
				const e = BigInt(Date.now()) * 1000000n;
				l.setBigUint64(s, e, true);
				return t;
			}
			return r;
		},
		fd_write(r, i, a, o) {
			const s = e();
			const c = new DataView(s.buffer);
			const l = new Uint8Array(s.buffer);
			let u = 0;
			if (r !== 1 && r !== 2) return n;
			for (let e = 0; e < a; e++) {
				const t = c.getUint32(i + e * 8, true);
				const n = c.getUint32(i + e * 8 + 4, true);
				const a = l.slice(t, t + n);
				const o = new TextDecoder().decode(a);
				if (r === 1) {
					if (typeof process !== "undefined" && process.stdout) process.stdout.write(o);
					else console.log(o);
				} else if (typeof process !== "undefined" && process.stderr) process.stderr.write(o);
				else console.error(o);
				u += n;
			}
			c.setUint32(o, u, true);
			return t;
		},
		fd_close(e) {
			return r;
		},
		fd_fdstat_get(r, i) {
			const a = e();
			const o = new DataView(a.buffer);
			if (r === 1 || r === 2) {
				o.setUint8(i, 2);
				o.setUint16(i + 2, 0, true);
				o.setBigUint64(i + 8, 0n, true);
				o.setBigUint64(i + 16, 0n, true);
				return t;
			}
			return n;
		},
		fd_seek(e, t, n, i) {
			return r;
		},
		random_get(n, r) {
			const i = e();
			const a = new Uint8Array(i.buffer, n, r);
			if (typeof crypto !== "undefined" && crypto.getRandomValues) crypto.getRandomValues(a);
			else for (let e = 0; e < r; e++) a[e] = Math.floor(Math.random() * 256);
			return t;
		}
	};
}
//#endregion
//#region node_modules/.pnpm/quickjs-wasi@3.6.3/node_modules/quickjs-wasi/dist/extensions.js
/**
* WASM Dynamic Linking - Extension Loader
*
* Loads WASM shared libraries (.so) compiled with wasi-sdk as extensions
* for the QuickJS WASM runtime. Extensions can call QuickJS C API functions
* directly through dynamic linking (shared memory + symbol resolution).
*
* Key concepts:
* - Extensions are WASM shared libraries with a `dylink.0` custom section
* - They share linear memory and the indirect function table with the main module
* - Symbol imports (env.*) are resolved against the main module's exports
* - Each extension gets a unique __memory_base and __table_base
* - Extensions export an init function (e.g., `qjs_ext_url_init`)
*/
const decoder = new TextDecoder();
/**
* Parse a null-terminated "key=value\nkey=value" string from WASM memory
* into a Record<string, string>. Used to read version info from extensions.
*/
function parseVersionString(e, t) {
	const n = new Uint8Array(e.buffer);
	let r = t;
	while (n[r] !== 0) r++;
	if (r === t) return {};
	const i = decoder.decode(n.slice(t, r));
	const a = {};
	for (const e of i.split("\n")) {
		const t = e.indexOf("=");
		if (t > 0) a[e.slice(0, t)] = e.slice(t + 1);
	}
	return a;
}
/**
* Check if an extension exports a versions function and parse the result.
*/
function extractExtensionVersions(e, t) {
	const n = `qjs_ext_${e.name.replace(/-/g, "_")}_versions`;
	const r = e.instance.exports[n];
	if (typeof r !== "function") return void 0;
	const i = r();
	if (i === 0) return void 0;
	return parseVersionString(t, i);
}
/** Read a ULEB128-encoded integer from a byte array */
function readULEB128(e, t) {
	let n = 0;
	let r = 0;
	while (t.value < e.length) {
		const i = e[t.value++];
		n |= (i & 127) << r;
		if ((i & 128) === 0) break;
		r += 7;
	}
	return n;
}
/** Parse the dylink.0 custom section from a WASM module */
function parseDylink(e) {
	const t = WebAssembly.Module.customSections(e, "dylink.0");
	if (t.length === 0) return null;
	const n = new Uint8Array(t[0]);
	const r = { value: 0 };
	const i = {
		memorySize: 0,
		memoryAlignment: 0,
		tableSize: 0,
		tableAlignment: 0,
		needed: []
	};
	while (r.value < n.length) {
		const e = readULEB128(n, r);
		const t = readULEB128(n, r);
		const a = r.value + t;
		if (e === 1) {
			i.memorySize = readULEB128(n, r);
			i.memoryAlignment = readULEB128(n, r);
			i.tableSize = readULEB128(n, r);
			i.tableAlignment = readULEB128(n, r);
		} else if (e === 2) {
			const e = readULEB128(n, r);
			for (let t = 0; t < e; t++) {
				const e = readULEB128(n, r);
				const t = new TextDecoder().decode(n.slice(r.value, r.value + e));
				r.value += e;
				i.needed.push(t);
			}
		}
		r.value = a;
	}
	return i;
}
/**
* Load a WASM shared library extension and link it against the main module.
*
* @param descriptor - Extension description (name, wasm bytes, init function)
* @param mainExports - The main QuickJS WASM module's exports
* @param wasiBuiltins - Built-in WASI implementations (lowest priority)
* @param wasiUserOverrides - User-provided WASI overrides (highest priority)
* @param memoryProxy - A memory proxy for extension WASI factories
* @param allocBase - Optional fixed memory/table bases (for snapshot restore)
*/
async function loadExtension(e, t, n, r, i, a) {
	let o;
	if (e.wasm instanceof WebAssembly.Module) o = e.wasm;
	else o = await WebAssembly.compile(e.wasm);
	const s = parseDylink(o);
	if (!s) throw new Error(`Extension "${e.name}" is not a WASM shared library (missing dylink.0 section)`);
	const c = t.memory;
	const l = t.__indirect_function_table;
	const u = t.__stack_pointer;
	const d = t.malloc;
	if (!c) throw new Error("Main module does not export memory");
	if (!l) throw new Error("Main module does not export __indirect_function_table");
	if (!d) throw new Error("Main module does not export malloc");
	let f;
	let p;
	if (a) {
		f = a.memoryBase;
		p = a.tableBase;
	} else if (s.memorySize > 0) {
		f = d(s.memorySize);
		if (f === 0) throw new Error(`Failed to allocate ${s.memorySize} bytes for extension "${e.name}"`);
		new Uint8Array(c.buffer, f, s.memorySize).fill(0);
	} else f = 0;
	if (a) {
		p = a.tableBase;
		if (p + s.tableSize > l.length) l.grow(p + s.tableSize - l.length);
	} else {
		p = l.length;
		if (s.tableSize > 0) l.grow(s.tableSize);
	}
	const m = WebAssembly.Module.imports(o);
	const h = {
		env: {},
		"GOT.mem": {},
		"GOT.func": {}
	};
	if (m.some((e) => e.module === "wasi_snapshot_preview1")) {
		const t = e.wasi && i ? e.wasi(i) : void 0;
		h["wasi_snapshot_preview1"] = {
			...n,
			...t,
			...r
		};
	}
	const g = new Set(WebAssembly.Module.exports(o).filter((e) => e.kind === "function").map((e) => e.name));
	const _ = /* @__PURE__ */ new Set();
	for (const n of m) if (n.module === "env") {
		if (n.name === "memory" && n.kind === "memory") h.env.memory = c;
		else if (n.name === "__indirect_function_table" && n.kind === "table") h.env.__indirect_function_table = l;
		else if (n.name === "__memory_base" && n.kind === "global") h.env.__memory_base = new WebAssembly.Global({
			value: "i32",
			mutable: false
		}, f);
		else if (n.name === "__table_base" && n.kind === "global") h.env.__table_base = new WebAssembly.Global({
			value: "i32",
			mutable: false
		}, p);
		else if (n.name === "__stack_pointer" && n.kind === "global") h.env.__stack_pointer = u;
		else if (n.kind === "function") {
			const r = t[n.name];
			if (r && typeof r === "function") h.env[n.name] = r;
			else {
				_.add(n.name);
				h.env[n.name] = () => {
					throw new Error(`Extension "${e.name}" called unresolved symbol: env.${n.name}`);
				};
			}
		} else if (n.kind === "global") {
			const e = t[n.name];
			if (e instanceof WebAssembly.Global) h.env[n.name] = e;
			else h.env[n.name] = new WebAssembly.Global({
				value: "i32",
				mutable: true
			}, 0);
		}
	} else if (n.module === "GOT.mem" && n.kind === "global") h["GOT.mem"][n.name] = new WebAssembly.Global({
		value: "i32",
		mutable: true
	}, 0);
	else if (n.module === "GOT.func" && n.kind === "global") {
		const e = t[n.name];
		if (e && typeof e === "function") {
			const t = l.length;
			l.grow(1);
			l.set(t, e);
			h["GOT.func"][n.name] = new WebAssembly.Global({
				value: "i32",
				mutable: true
			}, t);
		} else h["GOT.func"][n.name] = new WebAssembly.Global({
			value: "i32",
			mutable: true
		}, 0);
	}
	const v = [..._].filter((e) => g.has(e));
	const y = {};
	for (const t of v) {
		const n = { target: null };
		y[t] = n;
		h.env[t] = (...r) => {
			if (!n.target) throw new Error(`Extension "${e.name}" called unresolved symbol during init: env.${t}`);
			return n.target(...r);
		};
	}
	const b = await WebAssembly.instantiate(o, h);
	const x = b.exports;
	for (const e of v) {
		const t = x[e];
		if (typeof t === "function") y[e].target = t;
	}
	if (typeof x.__wasm_apply_data_relocs === "function") x.__wasm_apply_data_relocs();
	if (typeof x.__wasm_call_ctors === "function") x.__wasm_call_ctors();
	const S = e.initFn ?? `qjs_ext_${e.name.replace(/-/g, "_")}_init`;
	const C = {
		name: e.name,
		module: o,
		instance: b,
		dylink: s,
		memoryBase: f,
		tableBase: p,
		initFn: S
	};
	C.versions = extractExtensionVersions(C, c);
	return C;
}
/**
* Call the extension's init function, passing the JSContext and JSRuntime
* pointers from the main module.
*/
function initExtension(e, t) {
	const n = e.instance.exports[e.initFn];
	if (typeof n !== "function") throw new Error(`Extension "${e.name}" does not export init function "${e.initFn}"`);
	const r = n(t.qjs_get_context_ptr(), t.qjs_get_runtime_ptr());
	if (r !== 0) throw new Error(`Extension "${e.name}" init function returned error code ${r}`);
}
/**
* Re-instantiate extensions for snapshot restore.
*
* During restore, we need to:
* 1. Instantiate extension modules with the same memory/table bases
* 2. Let them populate the function table (via elem segments and __wasm_apply_data_relocs)
* 3. Do NOT call the init function (the state is already in the snapshot memory)
*
* This reconstructs the function table entries that extensions need, without
* modifying linear memory (which will be overwritten by the snapshot).
*/
async function restoreExtensions(e, t, n, r, i, a) {
	const o = [];
	for (const s of t) {
		const t = e.find((e) => e.name === s.name);
		if (!t) throw new Error(`Extension "${s.name}" required by snapshot but not provided`);
		const c = await loadExtension(t, n, r, i, a, {
			memoryBase: s.memoryBase,
			tableBase: s.tableBase
		});
		c.initFn = s.initFn;
		o.push(c);
	}
	return o;
}
//#endregion
//#region node_modules/.pnpm/quickjs-wasi@3.6.3/node_modules/quickjs-wasi/dist/version.js
const VERSION = "3.6.3";
//#endregion
//#region node_modules/.pnpm/quickjs-wasi@3.6.3/node_modules/quickjs-wasi/dist/index.js
/**
* QuickJS WASM - A snapshotable JavaScript runtime via WebAssembly.
*
* Provides a clean JavaScript API for running sandboxed JS code in a QuickJS
* VM compiled to WASM. The key differentiator is the ability to snapshot the
* entire VM state (including pending promises) and restore it in a fresh
* WASM instance.
*/
var __addDisposableResource = void 0 && (void 0).__addDisposableResource || function(e, t, n) {
	if (t !== null && t !== void 0) {
		if (typeof t !== "object" && typeof t !== "function") throw new TypeError("Object expected.");
		var dispose, r;
		if (n) {
			if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
			dispose = t[Symbol.asyncDispose];
		}
		if (dispose === void 0) {
			if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
			dispose = t[Symbol.dispose];
			if (n) r = dispose;
		}
		if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
		if (r) dispose = function() {
			try {
				r.call(this);
			} catch (e) {
				return Promise.reject(e);
			}
		};
		e.stack.push({
			value: t,
			dispose,
			async: n
		});
	} else if (n) e.stack.push({ async: true });
	return t;
};
var __disposeResources = void 0 && (void 0).__disposeResources || (function(e) {
	return function(t) {
		function fail(n) {
			t.error = t.hasError ? new e(n, t.error, "An error was suppressed during disposal.") : n;
			t.hasError = true;
		}
		var n, r = 0;
		function next() {
			while (n = t.stack.pop()) try {
				if (!n.async && r === 1) return r = 0, t.stack.push(n), Promise.resolve().then(next);
				if (n.dispose) {
					var e = n.dispose.call(n.value);
					if (n.async) return r |= 2, Promise.resolve(e).then(next, function(e) {
						fail(e);
						return next();
					});
				} else r |= 1;
			} catch (e) {
				fail(e);
			}
			if (r === 1) return t.hasError ? Promise.reject(t.error) : Promise.resolve();
			if (t.hasError) throw t.error;
		}
		return next();
	};
})(typeof SuppressedError === "function" ? SuppressedError : function(e, t, n) {
	var r = new Error(n);
	return r.name = "SuppressedError", r.error = e, r.suppressed = t, r;
});
/**
* Largest supported QuickJS native stack limit for the shipped WASM binary.
*
* The binary has a 1 MiB linker-defined stack; reserving half of it leaves
* headroom for native frames and stack-overflow exception handling.
*/
const MAX_STACK_SIZE = 524288;
/**
* Flags for `evalCode()`, matching the QuickJS `JS_EVAL_*` constants.
*/
const EvalFlags = {
	/** Global script mode (default). */
	TYPE_GLOBAL: 0,
	/**
	* Module mode. `evalCode()` returns a handle to a Promise that resolves
	* to the module's namespace object (its exports), or rejects if module
	* evaluation throws. Use together with `executePendingJobs()` and
	* `resolvePromise()`.
	*/
	TYPE_MODULE: 1,
	/** Force strict mode. */
	STRICT: 8,
	/** Compile only; do not execute. */
	COMPILE_ONLY: 32,
	/** Omit stack frames before this eval from Error backtraces. */
	BACKTRACE_BARRIER: 64,
	/**
	* Allow top-level `await` in global scripts. When used, `evalCode()`
	* returns a handle to a Promise that resolves to the completion value.
	* Use together with `executePendingJobs()` and `resolvePromise()`.
	*/
	ASYNC: 128
};
/** Magic bytes: "QJSS" (QuickJS Snapshot) */
const SNAPSHOT_MAGIC = 1363825491;
/** Current serialization format version (2 = added extension metadata) */
const SNAPSHOT_VERSION = 2;
/**
* Header layout (version 2):
*   0-3:   Magic "QJSS" (u32 big-endian)
*   4:     Version (u8)
*   5-7:   Reserved (zero)
*   8-11:  Memory size in bytes (u32 little-endian)
*   12-15: Stack pointer (u32 little-endian)
*   16-19: Runtime pointer (u32 little-endian)
*   20-23: Context pointer (u32 little-endian)
*   24-27: Extension count (u32 little-endian)
*   28+:   Extension entries (variable length):
*          nameLen(u32) + name(utf8) + memoryBase(u32) + tableBase(u32) + initFnLen(u32) + initFn(utf8)
*   N+:    Memory data (N = memory size from offset 8)
*
* Version 1 (legacy): no extension metadata, memory starts at offset 24.
*/
const SNAPSHOT_HEADER_SIZE = 24;
var QuickJS = class QuickJS {
	exports;
	module;
	instance;
	encoder = new TextEncoder();
	decoder = new TextDecoder();
	disposed = false;
	/** Registry of host callbacks, keyed by function name */
	hostCallbacks = /* @__PURE__ */ new Map();
	/** Counter for internal-only callbacks (e.g. promise settle handlers) */
	nextInternalId = 1;
	interruptHandler = null;
	unhandledRejectionHandler = null;
	moduleNormalizeHandler = null;
	moduleLoadHandler = null;
	timezoneOffsetHandler = null;
	_global = null;
	_versions = null;
	_undefined = null;
	_null = null;
	_true = null;
	_false = null;
	_ownedHandles = /* @__PURE__ */ new Set();
	/**
	* The innermost active `withScope()` batch, if any. New non-singleton
	* handles register themselves here so they can be freed together.
	* @internal
	*/
	_activeScope = null;
	/** Loaded extensions in deterministic order */
	loadedExtensions = [];
	constructor(e) {
		this.module = e;
		this.instance = null;
		this.exports = null;
	}
	setInstance(e) {
		this.instance = e;
		this.exports = e.exports;
	}
	/**
	* Version information for the runtime and loaded native libraries.
	* Always includes `"quickjs-wasi"` (the npm package version) and
	* `"quickjs"` (the QuickJS engine version). Extensions may contribute
	* additional entries for their native dependencies (e.g. `"ada"`, `"mbedtls"`).
	*/
	get versions() {
		this.assertNotDisposed();
		if (!this._versions) {
			const e = {
				"quickjs-wasi": VERSION,
				quickjs: this.readCString(this.exports.qjs_get_quickjs_version())
			};
			for (const t of this.loadedExtensions) if (t.versions) Object.assign(e, t.versions);
			this._versions = e;
		}
		return this._versions;
	}
	/** The global object. Cached; do not dispose. */
	get global() {
		if (!this._global) this._global = new JSValueHandle(this, this.exports.qjs_get_global(), true);
		return this._global;
	}
	/** The undefined value. Cached; do not dispose. */
	get undefined() {
		if (!this._undefined) this._undefined = new JSValueHandle(this, this.exports.qjs_get_undefined(), true);
		return this._undefined;
	}
	/** The null value. Cached; do not dispose. */
	get null() {
		if (!this._null) this._null = new JSValueHandle(this, this.exports.qjs_get_null(), true);
		return this._null;
	}
	/** The true value. Cached; do not dispose. */
	get true() {
		if (!this._true) this._true = new JSValueHandle(this, this.exports.qjs_get_true(), true);
		return this._true;
	}
	/** The false value. Cached; do not dispose. */
	get false() {
		if (!this._false) this._false = new JSValueHandle(this, this.exports.qjs_get_false(), true);
		return this._false;
	}
	/**
	* Create a fresh QuickJS VM instance.
	*
	* @param options - Optional configuration. Can also pass raw WASM bytes
	*                  directly for backwards compatibility.
	*/
	static async create(e) {
		const t = QuickJS.normalizeOptions(e);
		const n = await QuickJS.resolveModule(t.wasm);
		const r = new QuickJS(n);
		const { instance: i, wasiBuiltins: a, wasiUserOverrides: o, memoryProxy: s } = await QuickJS.instantiate(n, r, t.wasi);
		r.setInstance(i);
		r.exports._initialize();
		if ((t.intrinsics !== void 0 ? r.exports.qjs_init2(t.intrinsics) : r.exports.qjs_init()) !== 0) throw new Error("Failed to initialize QuickJS runtime");
		if (t.extensions) {
			const e = i.exports;
			for (const n of t.extensions) {
				const t = await loadExtension(n, e, a, o, s);
				r.loadedExtensions.push(t);
				initExtension(t, e);
			}
		}
		QuickJS.applyLimits(r, t);
		return r;
	}
	/**
	* Restore a QuickJS VM from a snapshot.
	*
	* @param snapshot - The snapshot to restore from.
	* @param options - Optional configuration. Can also pass raw WASM bytes
	*                  directly for backwards compatibility.
	*/
	static async restore(e, t) {
		const n = QuickJS.normalizeOptions(t);
		const r = await QuickJS.resolveModule(n.wasm);
		const i = new QuickJS(r);
		const { instance: a, wasiBuiltins: o, wasiUserOverrides: s, memoryProxy: c } = await QuickJS.instantiate(r, i, n.wasi);
		i.setInstance(a);
		const l = a.exports;
		const u = i.exports.memory;
		const d = u.buffer.byteLength / 65536;
		const f = Math.ceil(e.memory.byteLength / 65536);
		if (f > d) u.grow(f - d);
		if (e.extensions.length > 0) {
			const t = n.extensions ?? [];
			i.loadedExtensions = await restoreExtensions(t, e.extensions, l, o, s, c);
		}
		new Uint8Array(u.buffer).set(e.memory);
		i.exports.qjs_set_runtime_and_context(e.runtimePtr, e.contextPtr);
		i.exports.__stack_pointer.value = e.stackPointer;
		QuickJS.applyLimits(i, n);
		return i;
	}
	/**
	* Serialize a snapshot to a binary buffer for persistent storage.
	*
	* The format includes a versioned header followed by the raw memory.
	* Apply your own compression (gzip, zstd, etc.) on top for smaller
	* storage. The memory compresses well due to its large zero regions.
	*
	* Format (version 1):
	* ```
	* Offset  Size  Field
	* 0       4     Magic: "QJSS" (0x514A5353, big-endian)
	* 4       1     Version: 1
	* 5       3     Reserved (zero)
	* 8       4     Memory size in bytes (u32 little-endian)
	* 12      4     Stack pointer (u32 little-endian)
	* 16      4     Runtime pointer (u32 little-endian)
	* 20      4     Context pointer (u32 little-endian)
	* 24      N     Memory data (N = memory size from offset 8)
	* ```
	*/
	static serializeSnapshot(e) {
		const t = new TextEncoder();
		let n = 4;
		const r = [];
		const i = [];
		for (const a of e.extensions) {
			const e = t.encode(a.name);
			const o = t.encode(a.initFn);
			r.push(e);
			i.push(o);
			n += 4 + e.length + 4 + 4 + 4 + o.length;
		}
		const a = SNAPSHOT_HEADER_SIZE + n + e.memory.byteLength;
		const o = new ArrayBuffer(a);
		const s = new DataView(o);
		const c = new Uint8Array(o);
		s.setUint32(0, SNAPSHOT_MAGIC, false);
		s.setUint8(4, SNAPSHOT_VERSION);
		s.setUint32(8, e.memory.byteLength, true);
		s.setUint32(12, e.stackPointer, true);
		s.setUint32(16, e.runtimePtr, true);
		s.setUint32(20, e.contextPtr, true);
		let l = SNAPSHOT_HEADER_SIZE;
		s.setUint32(l, e.extensions.length, true);
		l += 4;
		for (let t = 0; t < e.extensions.length; t++) {
			const n = e.extensions[t];
			const a = r[t];
			const o = i[t];
			s.setUint32(l, a.length, true);
			l += 4;
			c.set(a, l);
			l += a.length;
			s.setUint32(l, n.memoryBase, true);
			l += 4;
			s.setUint32(l, n.tableBase, true);
			l += 4;
			s.setUint32(l, o.length, true);
			l += 4;
			c.set(o, l);
			l += o.length;
		}
		c.set(e.memory, l);
		return c;
	}
	/**
	* Deserialize a snapshot from a binary buffer produced by `serializeSnapshot()`.
	*/
	static deserializeSnapshot(e) {
		if (e.length < SNAPSHOT_HEADER_SIZE) throw new Error("Invalid snapshot: too small");
		const t = new DataView(e.buffer, e.byteOffset, e.byteLength);
		const n = t.getUint32(0, false);
		if (n !== SNAPSHOT_MAGIC) throw new Error(`Invalid snapshot: bad magic (expected 0x${SNAPSHOT_MAGIC.toString(16)}, got 0x${n.toString(16)})`);
		const r = t.getUint8(4);
		if (r !== SNAPSHOT_VERSION && r !== 1) throw new Error(`Unsupported snapshot version: ${r} (expected ${SNAPSHOT_VERSION})`);
		const i = t.getUint32(8, true);
		const a = t.getUint32(12, true);
		const o = t.getUint32(16, true);
		const s = t.getUint32(20, true);
		let c = [];
		let l = SNAPSHOT_HEADER_SIZE;
		if (r >= 2) {
			const n = t.getUint32(24, true);
			let r = 28;
			const i = new TextDecoder();
			for (let a = 0; a < n; a++) {
				const n = t.getUint32(r, true);
				r += 4;
				const a = i.decode(e.slice(r, r + n));
				r += n;
				const o = t.getUint32(r, true);
				r += 4;
				const s = t.getUint32(r, true);
				r += 4;
				const l = t.getUint32(r, true);
				r += 4;
				const u = i.decode(e.slice(r, r + l));
				r += l;
				c.push({
					name: a,
					memoryBase: o,
					tableBase: s,
					initFn: u
				});
			}
			l = r;
		}
		const u = l + i;
		if (e.length < u) throw new Error(`Invalid snapshot: expected ${u} bytes, got ${e.length}`);
		return {
			memory: e.slice(l, l + i),
			stackPointer: a,
			runtimePtr: o,
			contextPtr: s,
			extensions: c
		};
	}
	static normalizeOptions(e) {
		if (!e) return { wasm: void 0 };
		if (e instanceof WebAssembly.Module) return { wasm: e };
		if (typeof e === "object" && ("wasm" in e || "wasi" in e || "memoryLimit" in e || "maxStackSize" in e || "interruptHandler" in e || "onUnhandledRejection" in e || "moduleLoader" in e || "intrinsics" in e || "extensions" in e || "timezoneOffset" in e)) {
			const t = e;
			if (t.maxStackSize !== void 0 && (!Number.isInteger(t.maxStackSize) || t.maxStackSize < 0 || t.maxStackSize > 524288)) throw new RangeError(`maxStackSize must be an integer between 0 and ${MAX_STACK_SIZE}`);
			return t;
		}
		return { wasm: e };
	}
	static applyLimits(e, t) {
		if (t.memoryLimit !== void 0) e.exports.qjs_set_memory_limit(t.memoryLimit);
		if (t.maxStackSize !== void 0) e.exports.qjs_set_max_stack_size(t.maxStackSize);
		if (t.interruptHandler) {
			e.interruptHandler = t.interruptHandler;
			e.exports.qjs_set_interrupt_handler(1);
		}
		if (t.onUnhandledRejection) {
			e.unhandledRejectionHandler = t.onUnhandledRejection;
			e.exports.qjs_set_promise_rejection_handler(1);
		}
		if (t.moduleLoader) {
			e.moduleLoadHandler = t.moduleLoader.load;
			e.moduleNormalizeHandler = t.moduleLoader.normalize ?? null;
			e.exports.qjs_set_module_loader(1);
		}
		const n = t.timezoneOffset;
		if (typeof n === "function") e.timezoneOffsetHandler = (e) => -n(e) * 60;
		else if (typeof n === "number") {
			const t = -n * 60;
			e.timezoneOffsetHandler = () => t;
		} else e.timezoneOffsetHandler = (e) => {
			return -(/* @__PURE__ */ new Date(e * 1e3)).getTimezoneOffset() * 60;
		};
	}
	static async resolveModule(e) {
		if (e instanceof WebAssembly.Module) return e;
		if (e) return WebAssembly.compile(e);
		throw new TypeError("QuickJS: `wasm` option is required. Provide WASM bytes or a compiled `WebAssembly.Module`. The binary is shipped at `quickjs-wasi/quickjs.wasm` and can be loaded via your environment's preferred mechanism (e.g. `fetch()`, `node:fs/promises`, or a bundler import like Vite's `?url`).");
	}
	static async instantiate(e, t, n) {
		let r = null;
		const i = new Proxy({}, { get(e, t) {
			return r[t];
		} });
		const a = createWasiShim(() => r);
		const o = n ? n(i) : void 0;
		const s = {
			...a,
			...o
		};
		const hostCall = (e, n, r, i, a) => {
			return t.handleHostCall(e, n, r, i, a);
		};
		const hostInterrupt = () => {
			return t.interruptHandler ? t.interruptHandler() ? 1 : 0 : 0;
		};
		const hostPromiseRejection = (e, n, r) => {
			if (!t.unhandledRejectionHandler) {
				t.exports.qjs_free_value(e);
				t.exports.qjs_free_value(n);
				return;
			}
			const i = new JSValueHandle(t, e);
			const a = new JSValueHandle(t, n);
			try {
				t.unhandledRejectionHandler(i, a, r !== 0);
			} finally {
				i.dispose();
				a.dispose();
			}
		};
		const throwIntoContext = (e) => {
			const n = t.newError(e instanceof Error ? e : String(e));
			t.exports.qjs_throw(n.ptr);
			n.dispose();
		};
		const assertSyncString = (e, t) => {
			if (typeof e === "string") return e;
			const n = e !== null && typeof e === "object" && typeof e.then === "function" ? "a Promise" : `type ${typeof e}`;
			throw new TypeError(`moduleLoader.${t} must synchronously return a string (got ${n}). Async module loading is not supported. Pre-fetch module sources instead (see the "ES Modules" section of the quickjs-wasi README).`);
		};
		const hostModuleNormalize = (e, n) => {
			if (!t.moduleNormalizeHandler) {
				const e = t.readCString(n);
				return t.writeString(e).ptr;
			}
			const r = t.readCString(e);
			const i = t.readCString(n);
			try {
				const e = assertSyncString(t.moduleNormalizeHandler(r, i), "normalize");
				return t.writeString(e).ptr;
			} catch (e) {
				throwIntoContext(e);
				return 0;
			}
		};
		const hostModuleLoad = (e, n) => {
			if (!t.moduleLoadHandler) return 0;
			const r = t.readCString(e);
			try {
				const e = assertSyncString(t.moduleLoadHandler(r), "load");
				const { ptr: i, len: a } = t.writeString(e);
				new Uint32Array(t.exports.memory.buffer, n, 1)[0] = a;
				return i;
			} catch (e) {
				throwIntoContext(e);
				return 0;
			}
		};
		const hostGetTimezoneOffset = (e, n) => {
			const r = Number(BigInt(e) << 32n | BigInt(n >>> 0));
			return t.timezoneOffsetHandler ? t.timezoneOffsetHandler(r) : 0;
		};
		const c = await WebAssembly.instantiate(e, {
			env: {
				host_call: hostCall,
				host_interrupt: hostInterrupt,
				host_promise_rejection: hostPromiseRejection,
				host_module_normalize: hostModuleNormalize,
				host_module_load: hostModuleLoad,
				host_get_timezone_offset: hostGetTimezoneOffset
			},
			wasi_snapshot_preview1: s
		});
		r = c.exports.memory;
		return {
			instance: c,
			wasiBuiltins: a,
			wasiUserOverrides: o,
			memoryProxy: i
		};
	}
	/**
	* Called from WASM when a host function is invoked from QuickJS code.
	*/
	handleHostCall(e, t, n, r, i) {
		const a = this.decoder.decode(new Uint8Array(this.exports.memory.buffer, e, t));
		const o = this.hostCallbacks.get(a);
		if (!o) {
			const e = this.newError(`Host callback "${a}" is not registered: it was unregistered, its ephemeral function handle was disposed, or it was never re-registered after a snapshot restore.`);
			this.exports.qjs_throw(e.ptr);
			e.dispose();
			return 0;
		}
		const s = new JSValueHandle(this, n, false, true);
		const c = [];
		if (r > 0 && i !== 0) {
			const e = new DataView(this.exports.memory.buffer);
			for (let t = 0; t < r; t++) {
				const n = e.getUint32(i + t * 4, true);
				c.push(new JSValueHandle(this, n, false, true));
			}
		}
		try {
			const e = o.call(s, ...c);
			return this.exports.qjs_dup_value(e.ptr);
		} catch (e) {
			const t = this.newError(e instanceof Error ? e : String(e));
			this.exports.qjs_throw(t.ptr);
			t.dispose();
			return 0;
		}
	}
	/** Write a JS string into WASM memory, returning the pointer. Caller must free. */
	writeString(e) {
		const t = encodeWtf8(e);
		const n = this.exports.wasm_malloc(t.length + 1);
		if (n === 0) throw new Error("wasm_malloc failed");
		const r = new Uint8Array(this.exports.memory.buffer);
		r.set(t, n);
		r[n + t.length] = 0;
		return {
			ptr: n,
			len: t.length
		};
	}
	/** Read a null-terminated C string from WASM memory */
	readCString(e) {
		const t = new Uint8Array(this.exports.memory.buffer);
		let n = e;
		while (t[n] !== 0) n++;
		return this.decoder.decode(t.slice(e, n));
	}
	/**
	* Check if a result handle is an exception and throw a JSException if so.
	* Used internally by evalCode and callFunction.
	*/
	throwIfException(e) {
		if (this.exports.qjs_is_exception(e.ptr) !== 0) {
			const t = this.getException();
			e.dispose();
			this._ownedHandles.add(t);
			throw new JSException(t);
		}
		return e;
	}
	/**
	* Evaluate JavaScript code and return the result as a handle.
	* If the code throws, a `JSException` (which extends `Error`) is thrown
	* on the host side, matching standard JavaScript semantics.
	*
	* @param code - The JavaScript source code to evaluate.
	* @param filename - Optional filename for error stack traces (default `'<eval>'`).
	* @param flags - Optional bitwise OR of `EvalFlags.*` constants.
	*   For example, pass `EvalFlags.ASYNC` to allow top-level `await`; the
	*   returned handle will be a Promise that resolves to the completion value.
	*   With `EvalFlags.TYPE_MODULE` the returned handle is a Promise that
	*   resolves to the module's namespace object (its exports).
	*/
	evalCode(e, t = "<eval>", n = 0) {
		this.assertNotDisposed();
		const r = this.writeString(e);
		const i = this.writeString(t);
		const a = this.exports.qjs_eval(r.ptr, r.len, i.ptr, n);
		this.exports.wasm_free(r.ptr);
		this.exports.wasm_free(i.ptr);
		return this.throwIfException(new JSValueHandle(this, a));
	}
	/**
	* Compile JavaScript source code to bytecode without executing it.
	* The returned `Uint8Array` can be stored, transferred, or later executed
	* with `evalBytecode()`.
	*
	* @param code - The JavaScript source code to compile.
	* @param filename - Optional filename for error stack traces (default `'<compile>'`).
	* @param evalFlags - Optional bitwise OR of `EvalFlags.*` constants.
	*   Use `EvalFlags.TYPE_MODULE` to compile as a module.
	* @param compileFlags - Optional bitwise OR of `CompileFlags.*` constants.
	*   Use `CompileFlags.STRIP_SOURCE` and/or `CompileFlags.STRIP_DEBUG` to
	*   reduce bytecode size.
	*/
	compile(e, t = "<compile>", n = 0, r = 0) {
		this.assertNotDisposed();
		const i = this.writeString(e);
		const a = this.writeString(t);
		const o = this.exports.wasm_malloc(4);
		const s = this.exports.qjs_compile(i.ptr, i.len, a.ptr, n, r, o);
		this.exports.wasm_free(i.ptr);
		this.exports.wasm_free(a.ptr);
		if (s === 0) {
			this.exports.wasm_free(o);
			const e = this.getException();
			throw new Error(`Compilation error: ${e.toString()}`);
		}
		const c = new Uint32Array(this.exports.memory.buffer, o, 1)[0];
		this.exports.wasm_free(o);
		const l = new Uint8Array(this.exports.memory.buffer, s, c).slice();
		this.exports.wasm_free(s);
		return l;
	}
	/**
	* Execute previously compiled bytecode (from `compile()`).
	* Returns the evaluation result as a handle.
	*
	* For module bytecode (compiled with `EvalFlags.TYPE_MODULE`), the
	* returned handle is a Promise that resolves to the module's namespace
	* object (its exports).
	*
	* @param bytecode - The bytecode `Uint8Array` from `compile()`.
	*/
	evalBytecode(e) {
		this.assertNotDisposed();
		const t = this.exports.wasm_malloc(e.byteLength);
		new Uint8Array(this.exports.memory.buffer, t, e.byteLength).set(e);
		const n = this.exports.qjs_eval_bytecode(t, e.byteLength);
		this.exports.wasm_free(t);
		return this.throwIfException(new JSValueHandle(this, n));
	}
	/**
	* Execute all pending microtask jobs (promise reactions, etc.)
	* Returns the number of jobs executed.
	*/
	executePendingJobs() {
		this.assertNotDisposed();
		let e = 0;
		while (this.exports.qjs_is_job_pending()) {
			if (this.exports.qjs_execute_pending_job() < 0) {
				const e = this.getException();
				throw new Error(`Job execution error: ${e.toString()}`);
			}
			e++;
		}
		return e;
	}
	/**
	* Explicitly trigger garbage collection. QuickJS runs GC automatically,
	* but this can be useful to reclaim memory at a known point or before
	* taking a snapshot.
	*/
	runGC() {
		this.assertNotDisposed();
		this.exports.qjs_run_gc();
	}
	/**
	* The GC threshold in bytes. When allocated memory exceeds this value,
	* garbage collection is triggered automatically. Set to 0 to disable
	* automatic GC.
	*/
	get gcThreshold() {
		this.assertNotDisposed();
		return this.exports.qjs_get_gc_threshold();
	}
	set gcThreshold(e) {
		this.assertNotDisposed();
		this.exports.qjs_set_gc_threshold(e);
	}
	/**
	* Get detailed memory usage statistics from the QuickJS runtime.
	* Returns counts and sizes for atoms, strings, objects, functions, etc.
	*/
	getMemoryUsage() {
		this.assertNotDisposed();
		const e = this.exports.wasm_malloc(208);
		this.exports.qjs_compute_memory_usage(e);
		const t = new BigInt64Array(this.exports.memory.buffer, e, 26);
		const n = {
			mallocSize: Number(t[0]),
			mallocLimit: Number(t[1]),
			memoryUsedSize: Number(t[2]),
			mallocCount: Number(t[3]),
			memoryUsedCount: Number(t[4]),
			atomCount: Number(t[5]),
			atomSize: Number(t[6]),
			strCount: Number(t[7]),
			strSize: Number(t[8]),
			objCount: Number(t[9]),
			objSize: Number(t[10]),
			propCount: Number(t[11]),
			propSize: Number(t[12]),
			shapeCount: Number(t[13]),
			shapeSize: Number(t[14]),
			jsFuncCount: Number(t[15]),
			jsFuncSize: Number(t[16]),
			jsFuncCodeSize: Number(t[17]),
			jsFuncPc2lineCount: Number(t[18]),
			jsFuncPc2lineSize: Number(t[19]),
			cFuncCount: Number(t[20]),
			arrayCount: Number(t[21]),
			fastArrayCount: Number(t[22]),
			fastArrayElements: Number(t[23]),
			binaryObjectCount: Number(t[24]),
			binaryObjectSize: Number(t[25])
		};
		this.exports.wasm_free(e);
		return n;
	}
	/**
	* Get the global object. Prefer the cached `vm.global` property.
	*/
	getGlobal() {
		this.assertNotDisposed();
		return new JSValueHandle(this, this.exports.qjs_get_global());
	}
	/**
	* Create a new QuickJS string value.
	*/
	newString(e) {
		this.assertNotDisposed();
		const { ptr: t, len: n } = this.writeString(e);
		const r = this.exports.qjs_new_string(t, n);
		this.exports.wasm_free(t);
		return new JSValueHandle(this, r);
	}
	/**
	* Create a new QuickJS number value.
	*/
	newNumber(e) {
		this.assertNotDisposed();
		return new JSValueHandle(this, this.exports.qjs_new_number(e));
	}
	/**
	* Create a new QuickJS BigInt value.
	*/
	newBigInt(e) {
		this.assertNotDisposed();
		const t = Number(e & 4294967295n);
		const n = Number(e >> 32n & 4294967295n);
		return new JSValueHandle(this, this.exports.qjs_new_big_int64(t, n));
	}
	/**
	* Create a new QuickJS object value.
	*/
	newObject() {
		this.assertNotDisposed();
		return new JSValueHandle(this, this.exports.qjs_new_object());
	}
	/**
	* Create a new QuickJS array value.
	*/
	newArray() {
		this.assertNotDisposed();
		return new JSValueHandle(this, this.exports.qjs_new_array());
	}
	/**
	* Create a global symbol (`Symbol.for(description)`).
	* Global symbols with the same description are always the same symbol,
	* even across snapshot/restore.
	*/
	newSymbolFor(e) {
		this.assertNotDisposed();
		const { ptr: t, len: n } = this.writeString(e);
		const r = new JSValueHandle(this, this.exports.qjs_new_symbol(t, n, 1));
		this.exports.wasm_free(t);
		return r;
	}
	/**
	* Create a new QuickJS ArrayBuffer by copying data from a host buffer.
	*/
	newArrayBuffer(e) {
		this.assertNotDisposed();
		const t = e instanceof ArrayBuffer ? new Uint8Array(e) : e;
		const n = this.exports.wasm_malloc(t.length);
		if (n === 0) throw new Error("wasm_malloc failed");
		new Uint8Array(this.exports.memory.buffer).set(t, n);
		const r = new JSValueHandle(this, this.exports.qjs_new_array_buffer(n, t.length));
		this.exports.wasm_free(n);
		return r;
	}
	/**
	* Create a new QuickJS Uint8Array by copying data from a host buffer.
	*/
	newUint8Array(e) {
		this.assertNotDisposed();
		const t = this.exports.wasm_malloc(e.length);
		if (t === 0) throw new Error("wasm_malloc failed");
		new Uint8Array(this.exports.memory.buffer).set(e, t);
		const n = new JSValueHandle(this, this.exports.qjs_new_uint8_array(t, e.length));
		this.exports.wasm_free(t);
		return n;
	}
	/**
	* Get undefined. Prefer the cached `vm.undefined` property.
	*/
	getUndefined() {
		this.assertNotDisposed();
		return new JSValueHandle(this, this.exports.qjs_get_undefined());
	}
	/**
	* Get null. Prefer the cached `vm.null` property.
	*/
	getNull() {
		this.assertNotDisposed();
		return new JSValueHandle(this, this.exports.qjs_get_null());
	}
	/**
	* Get true. Prefer the cached `vm.true` property.
	*/
	getTrue() {
		this.assertNotDisposed();
		return new JSValueHandle(this, this.exports.qjs_get_true());
	}
	/**
	* Get false. Prefer the cached `vm.false` property.
	*/
	getFalse() {
		this.assertNotDisposed();
		return new JSValueHandle(this, this.exports.qjs_get_false());
	}
	/**
	* Create a new QuickJS function backed by a host callback.
	*
	* When the function is called inside QuickJS, the host callback is invoked
	* with the `this` value and arguments as JSValueHandles.
	*/
	newFunction(e, t) {
		this.assertNotDisposed();
		if (this.hostCallbacks.has(e)) throw new Error(`Host callback with name "${e}" is already registered`);
		this.hostCallbacks.set(e, t);
		const { ptr: n, len: r } = this.writeString(e);
		const i = this.exports.qjs_new_host_function(n, r, 0);
		this.exports.wasm_free(n);
		return new JSValueHandle(this, i);
	}
	/**
	* Run `fn` with a handle scope: every handle created during the call is
	* disposed when it returns, except those passed to `scope.escape()`.
	*
	* This is the bulk alternative to disposing handles individually, for code
	* that creates many intermediates, such as walking a large value:
	*
	* ```ts
	* const name = vm.withScope((scope) => {
	*   const user = root.getProp('user');       // freed automatically
	*   const profile = user.getProp('profile'); // freed automatically
	*   return scope.escape(profile.getProp('name'));
	* });
	* ```
	*
	* Scopes nest: `escape()` transfers the handle to the enclosing scope when
	* there is one, so it is still cleaned up at the outer boundary.
	*
	* `fn` must be synchronous. Handles created after an `await` are outside
	* the scope, because it closes as soon as `fn` returns.
	*
	* Host callbacks are safe to trigger inside a scope: the `this`/argument
	* handles the trampoline passes to a callback wrap C-owned pointers and
	* are exempt from scope tracking (see `handleHostCall`), so the scope
	* frees only handles the host actually owns. Handles a callback CREATES
	* (including `dup()`s of its arguments) are tracked normally.
	*/
	withScope(e) {
		this.assertNotDisposed();
		const t = this._activeScope;
		const n = /* @__PURE__ */ new Set();
		this._activeScope = n;
		const r = { escape: (e) => {
			n.delete(e);
			t?.add(e);
			return e;
		} };
		try {
			return e(r);
		} finally {
			this._activeScope = t;
			for (const e of n) e.dispose();
		}
	}
	/**
	* Export a handle as a snapshot-portable token.
	*
	* A handle's heap box lives in the VM's linear memory, so a
	* `snapshot()` taken while the handle is alive carries it, and a VM
	* restored from that snapshot has the identical box at the identical
	* offset. `importHandle(token)` on the restored VM (or on this VM)
	* re-materializes an owned handle for the same guest value without
	* evaluating any guest code.
	*
	* Contract:
	* - the handle must stay undisposed until after `snapshot()`; its
	*   box (and the reference it holds) must be part of the memory image;
	* - the token is only meaningful to THIS VM and VMs restored from a
	*   snapshot of it taken while the handle was alive;
	* - `importHandle` duplicates the underlying value (fresh reference,
	*   fresh box), so it can be called any number of times and each
	*   returned handle is independently owned and disposable. The
	*   exported box's own reference is intentionally never released on
	*   restored VMs (one retained reference per VM image, reclaimed
	*   with the VM).
	*
	* The intended use is boot-time capture: snapshot a VM after capturing
	* references to pristine intrinsics but BEFORE evaluating untrusted or
	* user code, then restore per task and import the captured handles,
	* guaranteeing the references predate anything user code patched,
	* without re-running capture code in the restored VM (where user-
	* patched globals could observe it). See vercel/workflow's host-side
	* serde for a worked example.
	*/
	exportHandle(e) {
		this.assertNotDisposed();
		if (e.vm !== this) throw new Error("exportHandle: handle belongs to a different VM");
		if (e.disposed) throw new Error("exportHandle: handle is disposed");
		if (e._isBorrowed) throw new Error("exportHandle: cannot export a borrowed handle (host-callback this/argument); its box is freed when the callback returns. dup() it and export the duplicate.");
		return e.ptr;
	}
	/**
	* Re-materialize a handle from a token produced by `exportHandle`,
	* on this VM, or on a VM restored from a snapshot taken while the
	* exported handle was alive. Returns a NEW owned handle (the
	* underlying value's refcount is incremented); dispose it like any
	* other handle. See `exportHandle` for the full contract.
	*/
	importHandle(e) {
		this.assertNotDisposed();
		if (!Number.isInteger(e) || e <= 0 || e >= this.exports.memory.buffer.byteLength) throw new Error(`importHandle: invalid token ${e}`);
		return new JSValueHandle(this, this.exports.qjs_dup_value(e));
	}
	/**
	* Create a QuickJS function backed by a host callback whose registration is
	* tied to the returned handle: disposing the handle unregisters the
	* callback.
	*
	* Use this for short-lived callbacks (e.g. a visitor passed to
	* `Map.prototype.forEach`) where the name is an implementation detail.
	* `newFunction()` keeps its callback registered for the lifetime of the VM
	* (by design, so that names can be re-registered after a snapshot is
	* restored), which makes it unsuitable for callbacks created in a loop.
	*
	* The guest must not retain the function past disposal: calling it after
	* the handle is disposed throws, because the callback is gone. Ephemeral
	* functions do not survive snapshot/restore.
	*/
	newEphemeralFunction(e) {
		this.assertNotDisposed();
		const t = `__ephemeral:${this.nextInternalId++}`;
		this.hostCallbacks.set(t, e);
		const { ptr: n, len: r } = this.writeString(t);
		const i = this.exports.qjs_new_host_function(n, r, 0);
		this.exports.wasm_free(n);
		const a = new JSValueHandle(this, i);
		a._onDispose = () => {
			this.hostCallbacks.delete(t);
		};
		return a;
	}
	/**
	* Remove a host callback registered with `newFunction()` or
	* `registerHostCallback()`. Returns true if a callback was removed.
	*
	* Any QuickJS function still referencing the name will throw when called,
	* so only unregister once the guest can no longer reach it.
	*/
	unregisterHostCallback(e) {
		return this.hostCallbacks.delete(e);
	}
	/**
	* Create an internal host function that bypasses the duplicate-name check.
	* Used for ephemeral callbacks (promise settle handlers, resolvePromise, etc.)
	* that are not intended to survive snapshot/restore.
	*/
	newInternalFunction(e, t) {
		this.hostCallbacks.set(e, t);
		const { ptr: n, len: r } = this.writeString(e);
		const i = this.exports.qjs_new_host_function(n, r, 0);
		this.exports.wasm_free(n);
		return new JSValueHandle(this, i);
	}
	/**
	* Create a new promise.
	*
	* Returns a Deferred with:
	* - `handle` - the QuickJS promise object
	* - `settled` - a host Promise that resolves when the QuickJS promise settles
	* - `resolve(value)` - resolve the promise with a QuickJS value
	* - `reject(value)` - reject the promise with a QuickJS value
	*/
	newPromise() {
		this.assertNotDisposed();
		const e = this.exports.wasm_malloc(4);
		const t = this.exports.wasm_malloc(4);
		const n = this.exports.qjs_new_promise(e, t);
		const r = new DataView(this.exports.memory.buffer);
		const i = r.getUint32(e, true);
		const a = r.getUint32(t, true);
		this.exports.wasm_free(e);
		this.exports.wasm_free(t);
		const o = new JSValueHandle(this, n);
		const s = new JSValueHandle(this, i);
		const c = new JSValueHandle(this, a);
		const l = this;
		l._ownedHandles.add(s);
		l._ownedHandles.add(c);
		let u = false;
		const settle = (e, t) => {
			if (u) return;
			u = true;
			l.callFunctionRaw(e, l.undefined, t).dispose();
			l._ownedHandles.delete(s);
			l._ownedHandles.delete(c);
			s.dispose();
			c.dispose();
		};
		let d = null;
		return {
			handle: o,
			get settled() {
				if (!d) {
					let e;
					d = new Promise((t) => {
						e = t;
					});
					const t = `__settle:${l.nextInternalId++}`;
					const n = l.newInternalFunction(t, () => {
						e();
						l.hostCallbacks.delete(t);
						return l.undefined;
					});
					l.promiseThenRaw(o, n, n).dispose();
					n.dispose();
				}
				return d;
			},
			resolve(e) {
				settle(s, e);
			},
			reject(e) {
				settle(c, e);
			}
		};
	}
	/**
	* Resolve a promise handle. Returns a host-side Promise that resolves
	* with the settled value/error of the QuickJS promise.
	*
	* If the handle is not a promise, it is treated as an already-fulfilled value.
	*
	* The returned host Promise resolves to `{ value: JSValueHandle }` on
	* fulfillment or `{ error: JSValueHandle }` on rejection.
	*/
	resolvePromise(e) {
		this.assertNotDisposed();
		if (!this.exports.qjs_is_promise(e.ptr)) return Promise.resolve({ value: e.dup() });
		const t = this.exports.qjs_promise_state(e.ptr);
		if (t === 1) return Promise.resolve({ value: new JSValueHandle(this, this.exports.qjs_promise_result(e.ptr)) });
		else if (t === 2) return Promise.resolve({ error: new JSValueHandle(this, this.exports.qjs_promise_result(e.ptr)) });
		return new Promise((t) => {
			const n = this.nextInternalId++;
			const r = `__onFulfilled:${n}`;
			const i = `__onRejected:${n}`;
			const a = this.newInternalFunction(r, (...e) => {
				const n = e[0]?.dup() ?? this.undefined;
				this.hostCallbacks.delete(r);
				this.hostCallbacks.delete(i);
				t({ value: n });
				return this.undefined;
			});
			const o = this.newInternalFunction(i, (...e) => {
				const n = e[0]?.dup() ?? this.undefined;
				this.hostCallbacks.delete(r);
				this.hostCallbacks.delete(i);
				t({ error: n });
				return this.undefined;
			});
			this.promiseThenRaw(e, a, o).dispose();
			a.dispose();
			o.dispose();
		});
	}
	/**
	* Subscribe to a promise without executing guest code, via quickjs-ng's
	* JS_PromiseThen: no Promise.prototype.then lookup, no Symbol.species.
	* Returns the chained promise. Handler handles are borrowed (caller
	* still owns and disposes them).
	* @internal
	*/
	promiseThenRaw(e, t, n) {
		return new JSValueHandle(this, this.exports.qjs_promise_then(e.ptr, t.ptr, n.ptr));
	}
	/**
	* Mark a promise as handled: an eventual (or already-recorded) rejection
	* will not be reported to `onUnhandledRejection`. Useful when the host
	* observes a rejection through other means (e.g. `resolvePromise()`) and
	* wants to suppress the unhandled-rejection callback for it.
	*
	* No-op if the handle is not a promise.
	*/
	markPromiseHandled(e) {
		this.assertNotDisposed();
		this.exports.qjs_promise_mark_as_handled(e.ptr);
	}
	/**
	* Call a QuickJS function. If the function throws, a `JSException`
	* is thrown on the host side.
	*/
	callFunction(e, t, ...n) {
		return this.throwIfException(this.callFunctionRaw(e, t, ...n));
	}
	/**
	* Invoke a QuickJS constructor with `new`, i.e. `new ctor(...args)`.
	* If the constructor throws (including when `ctor` is not a constructor),
	* a `JSException` is thrown on the host side.
	*
	* This is the counterpart to `callFunction` for building values inside
	* the VM from the host, e.g. `new Date(iso)` on a constructor captured
	* before any user code ran.
	*/
	construct(e, ...t) {
		this.assertNotDisposed();
		const n = t.length;
		let r = 0;
		if (n > 0) {
			r = this.exports.wasm_malloc(n * 4);
			const e = new DataView(this.exports.memory.buffer);
			for (let i = 0; i < n; i++) e.setUint32(r + i * 4, t[i].ptr, true);
		}
		const i = this.exports.qjs_call_constructor(e.ptr, n, r);
		if (r) this.exports.wasm_free(r);
		return this.throwIfException(new JSValueHandle(this, i));
	}
	/**
	* Internal: call a QuickJS function without throwing on exception.
	* Used by promise plumbing where exceptions are handled differently.
	*/
	callFunctionRaw(e, t, ...n) {
		this.assertNotDisposed();
		const r = n.length;
		let i = 0;
		if (r > 0) {
			i = this.exports.wasm_malloc(r * 4);
			const e = new DataView(this.exports.memory.buffer);
			for (let t = 0; t < r; t++) e.setUint32(i + t * 4, n[t].ptr, true);
		}
		const a = this.exports.qjs_call(e.ptr, t.ptr, r, i);
		if (i) this.exports.wasm_free(i);
		return new JSValueHandle(this, a);
	}
	/**
	* Set a property on an object. Accepts string or JSValueHandle as key.
	* JSValueHandle keys support symbols (including `Symbol.for()`).
	*/
	setProp(e, t, n) {
		this.assertNotDisposed();
		if (typeof t === "string") {
			const { ptr: r } = this.writeString(t);
			this.exports.qjs_set_prop_string(e.ptr, r, n.ptr);
			this.exports.wasm_free(r);
		} else this.exports.qjs_set_prop_value(e.ptr, t.ptr, n.ptr);
	}
	/**
	* Define a property on an object with explicit property descriptor flags.
	* Unlike `setProp`, this allows controlling `writable`, `enumerable`, and
	* `configurable` attributes, matching `Object.defineProperty()` semantics.
	* Accepts string or JSValueHandle as key (JSValueHandle keys support symbols).
	*
	* All flags default to `false` when not specified.
	*/
	defineProp(e, t, n, r) {
		this.assertNotDisposed();
		let i = 0;
		if (r?.configurable) i |= 1;
		if (r?.writable) i |= 2;
		if (r?.enumerable) i |= 4;
		if (typeof t === "string") {
			const { ptr: r } = this.writeString(t);
			this.exports.qjs_define_prop_string(e.ptr, r, n.ptr, i);
			this.exports.wasm_free(r);
		} else this.exports.qjs_define_prop_value(e.ptr, t.ptr, n.ptr, i);
	}
	/**
	* Get a property from an object using a JSValueHandle key.
	* Supports symbol keys (including `Symbol.for()`).
	*/
	getProp(e, t) {
		this.assertNotDisposed();
		return new JSValueHandle(this, this.exports.qjs_get_prop_value(e.ptr, t.ptr));
	}
	/**
	* Get the current exception, if any.
	*/
	getException() {
		this.assertNotDisposed();
		return new JSValueHandle(this, this.exports.qjs_get_exception());
	}
	/**
	* Create a new QuickJS Error object.
	* Accepts a string message or a native Error object.
	*/
	newError(e) {
		this.assertNotDisposed();
		const t = this.exports.qjs_new_error();
		const n = new JSValueHandle(this, t);
		if (typeof e === "string") {
			const t = this.newString(e);
			n.setProp("message", t);
			t.dispose();
		} else {
			const t = this.newString(e.message);
			n.setProp("message", t);
			t.dispose();
			if (e.name) {
				const t = this.newString(e.name);
				n.setProp("name", t);
				t.dispose();
			}
			if (e.stack) {
				const t = this.newString(e.stack);
				n.setProp("stack", t);
				t.dispose();
			}
		}
		return n;
	}
	/**
	* Get the typeof a handle as a string.
	*/
	typeof(e) {
		this.assertNotDisposed();
		const t = this.exports;
		if (t.qjs_is_undefined(e.ptr)) return "undefined";
		if (t.qjs_is_null(e.ptr)) return "object";
		if (t.qjs_is_bool(e.ptr)) return "boolean";
		if (t.qjs_is_number(e.ptr)) return "number";
		if (t.qjs_is_big_int(e.ptr)) return "bigint";
		if (t.qjs_is_string(e.ptr)) return "string";
		if (t.qjs_is_symbol(e.ptr)) return "symbol";
		if (t.qjs_is_function(e.ptr)) return "function";
		if (t.qjs_is_object(e.ptr)) return "object";
		return "unknown";
	}
	/**
	* Convert a QuickJS handle to a host JavaScript value.
	* Handles strings, numbers, booleans, null, undefined, bigint, arrays,
	* errors, functions, and plain objects. Circular references in objects
	* are returned as `undefined`.
	*/
	dump(e) {
		this.assertNotDisposed();
		return this._dump(e, /* @__PURE__ */ new Map());
	}
	_dump(e, t) {
		const n = this.exports;
		if (n.qjs_is_undefined(e.ptr)) return void 0;
		if (n.qjs_is_null(e.ptr)) return null;
		if (n.qjs_is_bool(e.ptr)) return n.qjs_get_bool(e.ptr) !== 0;
		if (n.qjs_is_number(e.ptr)) return n.qjs_get_float64(e.ptr);
		if (n.qjs_is_string(e.ptr)) return e.toString();
		if (n.qjs_is_big_int(e.ptr)) return e.toBigInt();
		if (n.qjs_is_symbol(e.ptr)) {
			const t = n.wasm_malloc(4);
			const r = n.qjs_get_symbol_description(e.ptr, t);
			const i = new DataView(n.memory.buffer).getUint32(t, true);
			n.wasm_free(t);
			if (r === 1) {
				const e = new JSValueHandle(this, i);
				const t = e.toString();
				e.dispose();
				return Symbol.for(t);
			} else if (r === 2) {
				new JSValueHandle(this, i).dispose();
				return;
			}
			return;
		}
		if (n.qjs_is_array_buffer(e.ptr)) return e.toArrayBuffer();
		if (n.qjs_is_exception(e.ptr)) {
			const e = this.getException();
			const t = e.toString();
			e.dispose();
			return new Error(t);
		}
		if (n.qjs_is_function(e.ptr)) return void 0;
		if (n.qjs_is_object(e.ptr)) {
			const r = n.qjs_get_value_ptr(e.ptr);
			if (r) {
				const e = t.get(r);
				if (e !== void 0) return e;
			}
		}
		if (n.qjs_is_object(e.ptr)) {
			const t = n.wasm_malloc(4);
			const r = n.wasm_malloc(4);
			const i = n.wasm_malloc(4);
			const a = n.qjs_get_typed_array_buffer(e.ptr, t, r, i);
			const o = new JSValueHandle(this, a);
			if (n.qjs_is_exception(o.ptr) === 0) {
				const e = new DataView(n.memory.buffer);
				const a = e.getUint32(t, true);
				const s = e.getUint32(r, true);
				const c = e.getUint32(i, true);
				n.wasm_free(t);
				n.wasm_free(r);
				n.wasm_free(i);
				const l = n.wasm_malloc(4);
				const u = n.qjs_get_array_buffer(o.ptr, l);
				n.wasm_free(l);
				o.dispose();
				if (u !== 0) {
					const e = new Uint8Array(n.memory.buffer, u + a, s).slice();
					switch (c) {
						case 1: return e;
						case 2: return new Uint16Array(e.buffer);
						case 4: return new Uint32Array(e.buffer);
						case 8: return new Float64Array(e.buffer);
						default: return e;
					}
				}
			} else {
				o.dispose();
				n.wasm_free(t);
				n.wasm_free(r);
				n.wasm_free(i);
			}
		}
		if (n.qjs_is_array(e.ptr)) {
			const r = e.getProp("length");
			const i = n.qjs_get_float64(r.ptr);
			r.dispose();
			const a = [];
			const o = n.qjs_get_value_ptr(e.ptr);
			if (o) t.set(o, a);
			for (let r = 0; r < i; r++) {
				const i = n.qjs_get_prop_uint32(e.ptr, r);
				const o = new JSValueHandle(this, i);
				a.push(this._dump(o, t));
				o.dispose();
			}
			return a;
		}
		if (n.qjs_is_error(e.ptr)) {
			const t = e.getProp("name");
			const n = e.getProp("message");
			const r = e.getProp("stack");
			const i = t.isUndefined ? "Error" : t.toString();
			const a = n.isUndefined ? "" : n.toString();
			const o = r.isUndefined ? void 0 : r.toString();
			t.dispose();
			n.dispose();
			r.dispose();
			const s = new Error(a);
			s.name = i;
			if (o !== void 0) s.stack = o;
			return s;
		}
		if (n.qjs_is_object(e.ptr)) {
			const r = n.qjs_get_own_property_names(e.ptr);
			const i = new JSValueHandle(this, r);
			if (n.qjs_is_exception(i.ptr) !== 0) {
				i.dispose();
				return {};
			}
			const a = i.getProp("length");
			const o = n.qjs_get_float64(a.ptr);
			a.dispose();
			const s = {};
			const c = n.qjs_get_value_ptr(e.ptr);
			if (c) t.set(c, s);
			for (let r = 0; r < o; r++) {
				const a = n.qjs_get_prop_uint32(i.ptr, r);
				const o = new JSValueHandle(this, a);
				const c = o.toString();
				o.dispose();
				const l = e.getProp(c);
				s[c] = this._dump(l, t);
				l.dispose();
			}
			i.dispose();
			return s;
		}
	}
	/**
	* Convert a host JavaScript value to a QuickJS handle.
	*/
	hostToHandle(e) {
		this.assertNotDisposed();
		if (e === void 0) return this.undefined;
		if (e === null) return this.null;
		if (e === true) return this.true;
		if (e === false) return this.false;
		if (typeof e === "number") return this.newNumber(e);
		if (typeof e === "string") return this.newString(e);
		if (typeof e === "bigint") return this.newBigInt(e);
		if (typeof e === "symbol") {
			const t = Symbol.keyFor(e);
			if (t !== void 0) return this.newSymbolFor(t);
			throw new Error(`Cannot convert local symbol to QuickJS handle. Use Symbol.for() for cross-boundary symbols.`);
		}
		if (e instanceof Promise) {
			const t = this.newPromise();
			e.then((e) => {
				t.resolve(this.hostToHandle(e));
				this.executePendingJobs();
			}, (e) => {
				t.reject(this.hostToHandle(e));
				this.executePendingJobs();
			});
			return t.handle;
		}
		if (e instanceof Error) return this.newError(e);
		if (e instanceof ArrayBuffer) return this.newArrayBuffer(e);
		if (e instanceof Uint8Array) return this.newUint8Array(e);
		if (ArrayBuffer.isView(e)) return this.newArrayBuffer(new Uint8Array(e.buffer, e.byteOffset, e.byteLength));
		if (Array.isArray(e)) {
			const t = this.newArray();
			for (let n = 0; n < e.length; n++) {
				const r = this.hostToHandle(e[n]);
				this.exports.qjs_set_prop_uint32(t.ptr, n, r.ptr);
				r.dispose();
			}
			return t;
		}
		if (typeof e === "object" && e !== null) {
			const t = this.newObject();
			for (const [n, r] of Object.entries(e)) {
				const e = this.hostToHandle(r);
				t.setProp(n, e);
				e.dispose();
			}
			return t;
		}
		return this.undefined;
	}
	/**
	* Snapshot the entire VM state.
	*
	* Returns a snapshot containing the full WASM linear memory. Use
	* `QuickJS.serializeSnapshot()` to convert to a versioned binary
	* buffer for persistent storage.
	*/
	snapshot() {
		this.assertNotDisposed();
		return {
			memory: new Uint8Array(this.exports.memory.buffer).slice(),
			stackPointer: this.exports.__stack_pointer.value,
			runtimePtr: this.exports.qjs_get_runtime_ptr(),
			contextPtr: this.exports.qjs_get_context_ptr(),
			extensions: this.loadedExtensions.map((e) => ({
				name: e.name,
				memoryBase: e.memoryBase,
				tableBase: e.tableBase,
				initFn: e.initFn
			}))
		};
	}
	/**
	* Re-register a host callback after restoring from a snapshot.
	* The name must match the name passed to `newFunction()` before the snapshot.
	*/
	registerHostCallback(e, t) {
		this.hostCallbacks.set(e, t);
	}
	/**
	* Dispose the VM, releasing all references to the WASM instance
	* so it can be garbage collected by the host JS engine.
	*/
	dispose() {
		if (!this.disposed) {
			this.disposed = true;
			this._global = null;
			this._undefined = null;
			this._null = null;
			this._true = null;
			this._false = null;
			this._ownedHandles.clear();
			this.hostCallbacks.clear();
			this._activeScope = null;
			this.exports = null;
			this.instance = null;
			this.module = null;
		}
	}
	/**
	* Support for `using` declarations (Explicit Resource Management).
	* Automatically disposes the VM when it goes out of scope.
	*
	* ```typescript
	* using vm = await QuickJS.create(wasmBytes);
	* vm.evalCode('1 + 2');
	* // vm is automatically disposed here
	* ```
	*/
	[Symbol.dispose]() {
		this.dispose();
	}
	assertNotDisposed() {
		if (this.disposed) throw new Error("QuickJS instance has been disposed");
	}
	/** @internal */
	_getExports() {
		return this.exports;
	}
	/** @internal */
	_getMemory() {
		return this.exports.memory;
	}
	/** @internal */
	_writeString(e) {
		return this.writeString(e);
	}
	/** @internal */
	_readCString(e) {
		return this.readCString(e);
	}
};
/**
* Whether a string-typed property key survives the NUL-terminated
* C-string key APIs: embedded U+0000 truncates the key, and an UNPAIRED
* surrogate cannot be UTF-8 encoded (paired surrogates, such as those
* that encode emoji, are fine). Keys that don't survive are routed through length-aware
* guest string values instead.
*/
function stringKeyNeedsValuePath(e) {
	return e.includes("\0") || LONE_SURROGATE_RE.test(e);
}
const wtf8Decoder = new TextDecoder();
const wtf8Encoder = new TextEncoder();
const LONE_SURROGATE_RE = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF]))|(?:(?<![\uD800-\uDBFF])[\uDC00-\uDFFF])/;
/**
* Encode a JS string to WTF-8 bytes. Well-formed strings (including
* paired surrogates, such as emoji) take the native TextEncoder; strings with
* LONE surrogates take a manual encode that writes each unpaired
* surrogate as the 3-byte sequence quickjs's tolerant UTF-8 decoder
* accepts; TextEncoder would replace them with U+FFFD, silently
* corrupting every host→guest string (sources, property keys,
* newString values).
*/
function encodeWtf8(e) {
	if (!LONE_SURROGATE_RE.test(e)) return wtf8Encoder.encode(e);
	const t = [];
	for (let n = 0; n < e.length; n++) {
		const r = e.charCodeAt(n);
		if (r < 128) t.push(r);
		else if (r < 2048) t.push(192 | r >> 6, 128 | r & 63);
		else if (r >= 55296 && r <= 56319 && n + 1 < e.length) {
			const i = e.charCodeAt(n + 1);
			if (i >= 56320 && i <= 57343) {
				const e = 65536 + (r - 55296 << 10) + (i - 56320);
				t.push(240 | e >> 18, 128 | e >> 12 & 63, 128 | e >> 6 & 63, 128 | e & 63);
				n++;
				continue;
			}
			t.push(224 | r >> 12, 128 | r >> 6 & 63, 128 | r & 63);
		} else t.push(224 | r >> 12, 128 | r >> 6 & 63, 128 | r & 63);
	}
	return new Uint8Array(t);
}
/**
* Decode WTF-8 bytes to a JS string. WTF-8 is UTF-8 extended with 3-byte
* sequences for surrogate code points (0xED 0xA0-0xBF 0x80-0xBF), which
* is how quickjs's JS_ToCStringLen2 encodes lone surrogates ("keep
* unmatched surrogate code points"). TextDecoder replaces those
* sequences with U+FFFD, so they are detected first and the rare strings
* containing them take a manual decode; everything else (the
* overwhelming majority) uses the native decoder.
*/
function decodeWtf8(e) {
	let t = false;
	for (let n = 0; n < e.length - 1; n++) if (e[n] === 237 && e[n + 1] >= 160 && e[n + 1] <= 191) {
		t = true;
		break;
	}
	if (!t) return wtf8Decoder.decode(e);
	let n = "";
	let r = 0;
	while (r < e.length) {
		const t = e[r];
		if (t < 128) {
			n += String.fromCharCode(t);
			r += 1;
		} else if (t < 224) {
			n += String.fromCharCode((t & 31) << 6 | e[r + 1] & 63);
			r += 2;
		} else if (t < 240) {
			n += String.fromCharCode((t & 15) << 12 | (e[r + 1] & 63) << 6 | e[r + 2] & 63);
			r += 3;
		} else {
			const i = (t & 7) << 18 | (e[r + 1] & 63) << 12 | (e[r + 2] & 63) << 6 | e[r + 3] & 63;
			n += String.fromCodePoint(i);
			r += 4;
		}
	}
	return n;
}
/**
* An exception thrown from QuickJS code. Extends `Error` so it works with
* standard error handling (`instanceof Error`, `.message`, `.stack`), and
* also exposes a `handle` property, a live `JSValueHandle` to the QuickJS
* exception value, allowing direct inspection of custom properties.
*
* The `handle` must be disposed when you're done with it (or use `using`).
* If the error propagates uncaught, the handle will be cleaned up when the
* VM is disposed.
*/
var JSException = class extends Error {
	/**
	* A live handle to the QuickJS exception value. You can read custom
	* properties, call methods, etc. Must be disposed when done.
	*/
	handle;
	#e;
	#t;
	#n;
	/** @internal */
	constructor(e) {
		const t = {
			stack: [],
			error: void 0,
			hasError: false
		};
		try {
			super();
			this.handle = e;
			delete this.stack;
			const n = __addDisposableResource(t, e.getProp("message"), false);
			this.#e = e.getProp("name").consume((e) => e.isUndefined ? "Error" : e.toString());
			this.#t = n.isUndefined ? e.toString() : n.toString();
			this.#n = e.getProp("stack").consume((e) => e.isUndefined ? void 0 : e.toString());
		} catch (e) {
			t.error = e;
			t.hasError = true;
		} finally {
			__disposeResources(t);
		}
	}
	get name() {
		return this.#e;
	}
	set name(e) {
		this.#e = e;
	}
	get message() {
		return this.#t;
	}
	set message(e) {
		this.#t = e;
	}
	get stack() {
		return this.#n;
	}
	set stack(e) {
		this.#n = e;
	}
	dispose() {
		this.handle.dispose();
	}
	[Symbol.dispose]() {
		this.handle.dispose();
	}
};
/**
* A handle to a JSValue inside the QuickJS WASM instance.
*/
var JSValueHandle = class JSValueHandle {
	/** The QuickJS VM instance this handle belongs to. */
	vm;
	/** @internal */
	ptr;
	disposed_ = false;
	/**
	* When true, this handle is a cached singleton (e.g. `undefined`, `null`,
	* `true`, `false`, the global object) and `dispose()` is a no-op. This
	* prevents code that routinely disposes handles (such as the object/array
	* branches of `hostToHandle`) from freeing the shared heap `JSValue*` that
	* the cached singleton still references, which would corrupt later reads.
	* @internal
	*/
	singleton;
	/**
	* When true, this handle wraps a `JSValue*` OWNED BY THE C CALLER: the
	* `this`/argument handles the host-call trampoline passes to a host
	* callback (`handleHostCall`). The C side frees those values after the
	* call returns, so `dispose()` is a no-op and the handle is never
	* registered with an active `withScope()` (either would double-free
	* the guest value and corrupt the heap). A callback that needs to
	* retain an argument past its own invocation must `dup()` it; the
	* duplicate takes a fresh reference and behaves like any owned handle.
	* @internal
	*/
	borrowed;
	/**
	* Extra cleanup to run when this handle is disposed. Used by
	* `newEphemeralFunction()` to unregister its host callback.
	* @internal
	*/
	_onDispose;
	constructor(e, t, n = false, r = false) {
		this.vm = e;
		this.ptr = t;
		this.singleton = n;
		this.borrowed = r;
		if (!n && !r) e._activeScope?.add(this);
	}
	/**
	* Whether this handle wraps a C-owned pointer (host-callback
	* `this`/arguments). Borrowed handles must never be exported as
	* snapshot tokens: the trampoline frees their boxes after the
	* callback returns. @internal
	*/
	get _isBorrowed() {
		return this.borrowed;
	}
	/**
	* Whether `dispose()` has been called on this handle.
	*
	* Note that handle methods do not currently guard against use after
	* disposal: reading from a disposed handle reads freed memory. Check this
	* when a handle's lifetime is managed elsewhere (e.g. by `withScope()`).
	*/
	get disposed() {
		return this.disposed_;
	}
	get isUndefined() {
		return this.vm._getExports().qjs_is_undefined(this.ptr) !== 0;
	}
	get isNull() {
		return this.vm._getExports().qjs_is_null(this.ptr) !== 0;
	}
	/**
	* Get the promise state: 0 = pending, 1 = fulfilled, 2 = rejected
	*/
	get isBool() {
		return this.vm._getExports().qjs_is_bool(this.ptr) !== 0;
	}
	get isNumber() {
		return this.vm._getExports().qjs_is_number(this.ptr) !== 0;
	}
	get isString() {
		return this.vm._getExports().qjs_is_string(this.ptr) !== 0;
	}
	get isSymbol() {
		return this.vm._getExports().qjs_is_symbol(this.ptr) !== 0;
	}
	get isBigInt() {
		return this.vm._getExports().qjs_is_big_int(this.ptr) !== 0;
	}
	get isObject() {
		return this.vm._getExports().qjs_is_object(this.ptr) !== 0;
	}
	get isArray() {
		return this.vm._getExports().qjs_is_array(this.ptr) !== 0;
	}
	get isFunction() {
		return this.vm._getExports().qjs_is_function(this.ptr) !== 0;
	}
	get isError() {
		return this.vm._getExports().qjs_is_error(this.ptr) !== 0;
	}
	get isPromise() {
		return this.vm._getExports().qjs_is_promise(this.ptr) !== 0;
	}
	get isArrayBuffer() {
		return this.vm._getExports().qjs_is_array_buffer(this.ptr) !== 0;
	}
	/**
	* Whether this value is a Proxy exotic object.
	*
	* This is an engine-level check: it never fires proxy traps and cannot
	* be determined (or spoofed) from within guest JavaScript. Use
	* {@link getProxyTarget} / {@link getProxyHandler} to introspect a
	* detected proxy without executing guest code.
	*/
	get isProxy() {
		return this.vm._getExports().qjs_is_proxy(this.ptr) !== 0;
	}
	/**
	* Whether this value is a Map (engine brand check: trap-free,
	* spoof-proof, and unaffected by prototype/constructor mutation).
	* A Proxy wrapping a Map returns false.
	*/
	get isMap() {
		return this.vm._getExports().qjs_is_map(this.ptr) !== 0;
	}
	/**
	* Whether this value is a Set (engine brand check: trap-free,
	* spoof-proof, and unaffected by prototype/constructor mutation).
	* A Proxy wrapping a Set returns false.
	*/
	get isSet() {
		return this.vm._getExports().qjs_is_set(this.ptr) !== 0;
	}
	/**
	* Whether this value is a Date (engine brand check: trap-free,
	* spoof-proof, and unaffected by prototype/constructor mutation).
	* A Proxy wrapping a Date returns false.
	*/
	get isDate() {
		return this.vm._getExports().qjs_is_date(this.ptr) !== 0;
	}
	/**
	* Whether this value is a RegExp (engine brand check: trap-free,
	* spoof-proof, and unaffected by prototype/constructor mutation).
	* A Proxy wrapping a RegExp returns false.
	*/
	get isRegExp() {
		return this.vm._getExports().qjs_is_regexp(this.ptr) !== 0;
	}
	/** Whether this value is a WeakRef (engine brand check). */
	get isWeakRef() {
		return this.vm._getExports().qjs_is_weak_ref(this.ptr) !== 0;
	}
	/** Whether this value is a WeakMap (engine brand check). */
	get isWeakMap() {
		return this.vm._getExports().qjs_is_weak_map(this.ptr) !== 0;
	}
	/** Whether this value is a WeakSet (engine brand check). */
	get isWeakSet() {
		return this.vm._getExports().qjs_is_weak_set(this.ptr) !== 0;
	}
	/** Whether this value is a DataView (engine brand check). */
	get isDataView() {
		return this.vm._getExports().qjs_is_data_view(this.ptr) !== 0;
	}
	/**
	* A numeric identity for the underlying heap value, or 0 for values that
	* are not heap-allocated (numbers, booleans, `null`, `undefined`).
	*
	* Two handles to the same underlying object always report the same
	* identity, and two live handles to different objects always report
	* different identities, so this is the value to key a `Map` on when
	* deduplicating or detecting cycles across handles (`dump()` uses it for
	* exactly that).
	*
	* The identity is only meaningful while the value is alive; it is an
	* address, so it may be reused after every handle to the value has been
	* disposed. Do not persist it, and do not treat it as unforgeable: a
	* number read out of the guest can trivially collide with one.
	*/
	get identity() {
		return this.vm._getExports().qjs_get_value_ptr(this.ptr);
	}
	/**
	* Extract the value as a boolean, applying JavaScript truthiness
	* (equivalent to `!!value` inside the VM).
	*/
	toBoolean() {
		return this.vm._getExports().qjs_get_bool(this.ptr) !== 0;
	}
	/**
	* The internal QuickJS class ID of this value, or 0 for non-objects.
	* Useful as a generic engine-level brand when no dedicated `is*`
	* getter exists. Class IDs are stable within a VM instance but are an
	* engine implementation detail, so prefer the dedicated getters.
	*/
	get classId() {
		return this.vm._getExports().qjs_get_class_id(this.ptr);
	}
	/**
	* The engine-level class name of this value, e.g. `"Object"`, `"Map"`,
	* `"Date"`, `"RegExp"`, or the registered name of an extension-defined
	* class like `"URL"`, or `undefined` for non-objects and unnamed
	* internal classes.
	*
	* Unlike `constructorName` (which reads the `constructor` and `name`
	* properties and can therefore fire getters/proxy traps and be spoofed),
	* this is trap-free: it reads the engine's class table directly, never
	* executes guest code, and cannot be forged by reassigning prototypes or
	* constructors. Note that the engine registers the Proxy class under the
	* name `"Object"` (mirroring `Object.prototype.toString`), so use `isProxy`
	* to detect proxies and `getProxyTarget()` to read the target's brand.
	*/
	get className() {
		const e = new JSValueHandle(this.vm, this.vm._getExports().qjs_get_class_name(this.ptr));
		if (this.vm._getExports().qjs_is_exception(e.ptr) !== 0) {
			e.dispose();
			throw new JSException(this.vm.getException());
		}
		try {
			return e.isUndefined ? void 0 : e.toString();
		} finally {
			e.dispose();
		}
	}
	get promiseState() {
		return this.vm._getExports().qjs_promise_state(this.ptr);
	}
	/**
	* Get the typeof this value as a string.
	* Returns the same values as the native `typeof` operator.
	*/
	get typeof() {
		return this.vm.typeof(this);
	}
	/**
	* Get the length property of this value (for arrays, strings, etc.).
	*/
	get length() {
		const e = this.getProp("length");
		const t = e.toNumber();
		e.dispose();
		return t;
	}
	/**
	* Get the constructor name of this object, or undefined if unavailable.
	*/
	get constructorName() {
		const e = this.getProp("constructor");
		if (e.isUndefined || e.isNull) {
			e.dispose();
			return;
		}
		const t = e.getProp("name");
		e.dispose();
		if (t.isUndefined || t.isNull) {
			t.dispose();
			return;
		}
		const n = t.toString();
		t.dispose();
		return n;
	}
	/**
	* Get the own enumerable string property names (equivalent to Object.keys()).
	*/
	keys() {
		const e = this.vm._getExports();
		const t = e.qjs_get_own_property_names(this.ptr);
		const n = new JSValueHandle(this.vm, t);
		if (e.qjs_is_exception(n.ptr) !== 0) {
			n.dispose();
			return [];
		}
		const r = n.getProp("length");
		const i = e.qjs_get_float64(r.ptr);
		r.dispose();
		const a = [];
		for (let t = 0; t < i; t++) {
			const r = e.qjs_get_prop_uint32(n.ptr, t);
			const i = new JSValueHandle(this.vm, r);
			a.push(i.toString());
			i.dispose();
		}
		n.dispose();
		return a;
	}
	/**
	* Get all own property names including non-enumerable ones
	* (equivalent to Object.getOwnPropertyNames()).
	*/
	getOwnPropertyNames() {
		const e = this.vm._getExports();
		const t = e.qjs_get_own_property_names_all(this.ptr);
		const n = new JSValueHandle(this.vm, t);
		if (e.qjs_is_exception(n.ptr) !== 0) {
			n.dispose();
			return [];
		}
		const r = n.getProp("length");
		const i = e.qjs_get_float64(r.ptr);
		r.dispose();
		const a = [];
		for (let t = 0; t < i; t++) {
			const r = e.qjs_get_prop_uint32(n.ptr, t);
			const i = new JSValueHandle(this.vm, r);
			a.push(i.toString());
			i.dispose();
		}
		n.dispose();
		return a;
	}
	/**
	* Get ALL own property keys (strings and symbols), including
	* non-enumerable (equivalent to Reflect.ownKeys()).
	*
	* String keys are returned as strings; symbol keys are returned as
	* JSValueHandles which the caller must dispose.
	*
	* Trap-free for ordinary objects; fires the `ownKeys` trap for a
	* Proxy (check {@link isProxy} first if that matters).
	*/
	getOwnPropertyKeys() {
		const e = this.vm._getExports();
		const t = e.qjs_get_own_property_keys(this.ptr);
		const n = new JSValueHandle(this.vm, t);
		if (e.qjs_is_exception(n.ptr) !== 0) {
			n.dispose();
			return [];
		}
		const r = n.getProp("length");
		const i = e.qjs_get_float64(r.ptr);
		r.dispose();
		const a = [];
		for (let t = 0; t < i; t++) {
			const r = e.qjs_get_prop_uint32(n.ptr, t);
			const i = new JSValueHandle(this.vm, r);
			if (i.isSymbol) a.push(i);
			else {
				a.push(i.toString());
				i.dispose();
			}
		}
		n.dispose();
		return a;
	}
	/**
	* Get the own property descriptor for a key WITHOUT invoking getters
	* (equivalent to Object.getOwnPropertyDescriptor()).
	*
	* This is the safe way to inspect a property that may be an accessor:
	* a data property yields `{ value, writable, enumerable, configurable }`,
	* an accessor property yields `{ get, set, enumerable, configurable }`
	* where `get`/`set` are handles to the accessor functions themselves
	* (never invoked). Returns undefined if there is no such own property.
	*
	* The `value`/`get`/`set` handles are owned by the caller and must be
	* disposed.
	*
	* Trap-free for ordinary objects; fires the `getOwnPropertyDescriptor`
	* trap for a Proxy (check {@link isProxy} first if that matters).
	*/
	getOwnPropertyDescriptor(e) {
		const t = {
			stack: [],
			error: void 0,
			hasError: false
		};
		try {
			const n = this.vm._getExports();
			let r;
			let i;
			if (typeof e === "string") {
				r = this.vm.newString(e);
				i = r.ptr;
			} else i = e.ptr;
			const a = n.qjs_get_own_property_descriptor(this.ptr, i);
			r?.dispose();
			if (a === 0) return void 0;
			const o = __addDisposableResource(t, new JSValueHandle(this.vm, a), false);
			if (n.qjs_is_exception(o.ptr) !== 0) throw new JSException(this.vm.getException());
			const s = o.getProp("enumerable").consume((e) => n.qjs_get_bool(e.ptr) !== 0);
			const c = o.getProp("configurable").consume((e) => n.qjs_get_bool(e.ptr) !== 0);
			if (o.hasOwnProperty("value")) return {
				value: o.getProp("value"),
				writable: o.getProp("writable").consume((e) => n.qjs_get_bool(e.ptr) !== 0),
				enumerable: s,
				configurable: c
			};
			return {
				get: o.getProp("get"),
				set: o.getProp("set"),
				enumerable: s,
				configurable: c
			};
		} catch (e) {
			t.error = e;
			t.hasError = true;
		} finally {
			__disposeResources(t);
		}
	}
	/**
	* Check if a property is an own property (equivalent to Object.prototype.hasOwnProperty).
	*/
	hasOwnProperty(e) {
		if (stringKeyNeedsValuePath(e)) {
			const t = {
				stack: [],
				error: void 0,
				hasError: false
			};
			try {
				const n = __addDisposableResource(t, this.vm.newString(e), false);
				return this.vm._getExports().qjs_has_own_property_value(this.ptr, n.ptr) === 1;
			} catch (e) {
				t.error = e;
				t.hasError = true;
			} finally {
				__disposeResources(t);
			}
		}
		const { ptr: t } = this.vm._writeString(e);
		const n = this.vm._getExports().qjs_has_own_property(this.ptr, t);
		this.vm._getExports().wasm_free(t);
		return n === 1;
	}
	/**
	* Check if a property is enumerable (equivalent to Object.prototype.propertyIsEnumerable).
	*/
	propertyIsEnumerable(e) {
		if (stringKeyNeedsValuePath(e)) {
			const t = {
				stack: [],
				error: void 0,
				hasError: false
			};
			try {
				const n = __addDisposableResource(t, this.vm.newString(e), false);
				return this.vm._getExports().qjs_property_is_enumerable_value(this.ptr, n.ptr) === 1;
			} catch (e) {
				t.error = e;
				t.hasError = true;
			} finally {
				__disposeResources(t);
			}
		}
		const { ptr: t } = this.vm._writeString(e);
		const n = this.vm._getExports().qjs_property_is_enumerable(this.ptr, t);
		this.vm._getExports().wasm_free(t);
		return n === 1;
	}
	/**
	* Get the prototype of this object (equivalent to Object.getPrototypeOf()).
	*/
	getPrototypeOf() {
		const e = this.vm._getExports().qjs_get_prototype_of(this.ptr);
		return new JSValueHandle(this.vm, e);
	}
	/**
	* Get the `[[ProxyTarget]]` of this Proxy without firing any traps.
	* Throws {@link JSException} if this value is not a Proxy; check
	* {@link isProxy} first. Note the target may itself be a Proxy.
	*/
	getProxyTarget() {
		const e = this.vm._getExports().qjs_get_proxy_target(this.ptr);
		const t = new JSValueHandle(this.vm, e);
		if (this.vm._getExports().qjs_is_exception(t.ptr) !== 0) {
			t.dispose();
			throw new JSException(this.vm.getException());
		}
		return t;
	}
	/**
	* Get the `[[ProxyHandler]]` of this Proxy without firing any traps.
	* Throws {@link JSException} if this value is not a Proxy; check
	* {@link isProxy} first.
	*/
	getProxyHandler() {
		const e = this.vm._getExports().qjs_get_proxy_handler(this.ptr);
		const t = new JSValueHandle(this.vm, e);
		if (this.vm._getExports().qjs_is_exception(t.ptr) !== 0) {
			t.dispose();
			throw new JSException(this.vm.getException());
		}
		return t;
	}
	/**
	* Get a property by name.
	*/
	getProp(e) {
		if (stringKeyNeedsValuePath(e)) {
			const t = {
				stack: [],
				error: void 0,
				hasError: false
			};
			try {
				const n = __addDisposableResource(t, this.vm.newString(e), false);
				return this.vm.getProp(this, n);
			} catch (e) {
				t.error = e;
				t.hasError = true;
			} finally {
				__disposeResources(t);
			}
		}
		const { ptr: t } = this.vm._writeString(e);
		const n = this.vm._getExports().qjs_get_prop_string(this.ptr, t);
		this.vm._getExports().wasm_free(t);
		return new JSValueHandle(this.vm, n);
	}
	/**
	* Set a property by name.
	*/
	setProp(e, t) {
		if (stringKeyNeedsValuePath(e)) {
			const n = {
				stack: [],
				error: void 0,
				hasError: false
			};
			try {
				const r = __addDisposableResource(n, this.vm.newString(e), false);
				this.vm.setProp(this, r, t);
				return;
			} catch (e) {
				n.error = e;
				n.hasError = true;
			} finally {
				__disposeResources(n);
			}
		}
		const { ptr: n } = this.vm._writeString(e);
		this.vm._getExports().qjs_set_prop_string(this.ptr, n, t.ptr);
		this.vm._getExports().wasm_free(n);
	}
	/**
	* Define a property with explicit property descriptor flags.
	* Unlike `setProp`, this allows controlling `writable`, `enumerable`, and
	* `configurable` attributes, matching `Object.defineProperty()` semantics.
	* Accepts string or JSValueHandle as key (JSValueHandle keys support symbols).
	*
	* All flags default to `false` when not specified.
	*/
	defineProp(e, t, n) {
		let r = 0;
		if (n?.configurable) r |= 1;
		if (n?.writable) r |= 2;
		if (n?.enumerable) r |= 4;
		if (typeof e === "string") {
			if (stringKeyNeedsValuePath(e)) {
				const n = {
					stack: [],
					error: void 0,
					hasError: false
				};
				try {
					const i = __addDisposableResource(n, this.vm.newString(e), false);
					this.vm._getExports().qjs_define_prop_value(this.ptr, i.ptr, t.ptr, r);
					return;
				} catch (e) {
					n.error = e;
					n.hasError = true;
				} finally {
					__disposeResources(n);
				}
			}
			const { ptr: n } = this.vm._writeString(e);
			this.vm._getExports().qjs_define_prop_string(this.ptr, n, t.ptr, r);
			this.vm._getExports().wasm_free(n);
		} else this.vm._getExports().qjs_define_prop_value(this.ptr, e.ptr, t.ptr, r);
	}
	/**
	* Extract the value as a number.
	*/
	toNumber() {
		return this.vm._getExports().qjs_get_float64(this.ptr);
	}
	/**
	* Extract the value as a BigInt.
	*/
	toBigInt() {
		const e = this.vm._getExports();
		const t = e.wasm_malloc(4);
		const n = e.wasm_malloc(4);
		if (e.qjs_get_big_int64(this.ptr, t, n) !== 0) {
			e.wasm_free(t);
			e.wasm_free(n);
			throw new Error("Failed to convert value to BigInt");
		}
		const r = new DataView(e.memory.buffer);
		const i = r.getUint32(t, true);
		const a = r.getInt32(n, true);
		e.wasm_free(t);
		e.wasm_free(n);
		return BigInt(a) << 32n | BigInt(i);
	}
	/**
	* Extract the value as an ArrayBuffer (copies from WASM memory).
	* Works on ArrayBuffer values. For typed arrays, gets the underlying buffer.
	*/
	toArrayBuffer() {
		const e = this.vm._getExports();
		const t = e.wasm_malloc(4);
		if (e.qjs_is_array_buffer(this.ptr)) {
			const n = e.qjs_get_array_buffer(this.ptr, t);
			if (n === 0) {
				e.wasm_free(t);
				throw new Error("Failed to get ArrayBuffer data");
			}
			const r = new DataView(e.memory.buffer).getUint32(t, true);
			e.wasm_free(t);
			return new Uint8Array(e.memory.buffer, n, r).slice().buffer;
		}
		e.wasm_free(t);
		const n = e.wasm_malloc(4);
		const r = e.wasm_malloc(4);
		const i = e.wasm_malloc(4);
		const a = e.qjs_get_typed_array_buffer(this.ptr, n, r, i);
		const o = new JSValueHandle(this.vm, a);
		if (this.vm._getExports().qjs_is_exception(o.ptr) !== 0) {
			o.dispose();
			e.wasm_free(n);
			e.wasm_free(r);
			e.wasm_free(i);
			throw new Error("Value is not an ArrayBuffer or typed array");
		}
		const s = new DataView(e.memory.buffer);
		const c = s.getUint32(n, true);
		const l = s.getUint32(r, true);
		e.wasm_free(n);
		e.wasm_free(r);
		e.wasm_free(i);
		const u = e.wasm_malloc(4);
		const d = e.qjs_get_array_buffer(o.ptr, u);
		e.wasm_free(u);
		o.dispose();
		if (d === 0) throw new Error("Failed to get ArrayBuffer data from typed array");
		return new Uint8Array(e.memory.buffer, d + c, l).slice().buffer;
	}
	/**
	* Extract the value as a Uint8Array (copies from WASM memory).
	* Works on Uint8Array, ArrayBuffer, and other typed array values.
	*/
	toUint8Array() {
		return new Uint8Array(this.toArrayBuffer());
	}
	/**
	* Extract the value as a string. Works on any value.
	*
	* For values that are not already strings this performs a JavaScript
	* string conversion, which **executes guest code**: `toString()` /
	* `valueOf()` / `Symbol.toPrimitive` on the value or its prototype chain,
	* and proxy traps. Guard with `isString` when the caller must not run guest
	* code, and call a captured intrinsic (e.g. `URL.prototype.toString` via
	* `vm.callFunction`) when a specific conversion is wanted.
	*/
	toString() {
		const e = this.vm._getExports();
		const t = e.wasm_malloc(4);
		if (t === 0) throw new Error("wasm_malloc failed");
		try {
			const n = e.qjs_get_string_len(this.ptr, t);
			if (n === 0) return "<null>";
			const r = new DataView(e.memory.buffer).getUint32(t, true);
			const i = decodeWtf8(new Uint8Array(e.memory.buffer, n, r));
			e.qjs_free_cstring(n);
			return i;
		} finally {
			e.wasm_free(t);
		}
	}
	/**
	* Use this handle, then dispose it. Returns the callback's return value.
	*/
	consume(e) {
		try {
			return e(this);
		} finally {
			this.dispose();
		}
	}
	/**
	* Duplicate this handle (increment refcount).
	*/
	dup() {
		return new JSValueHandle(this.vm, this.vm._getExports().qjs_dup_value(this.ptr));
	}
	/**
	* Dispose this handle, freeing the heap-allocated JSValue.
	* Safe to call after the VM has been disposed (becomes a no-op).
	*/
	dispose() {
		if (this.singleton || this.borrowed) return;
		if (!this.disposed_) {
			this.disposed_ = true;
			this._onDispose?.();
			this._onDispose = void 0;
			const e = this.vm._getExports();
			if (e) e.qjs_free_value(this.ptr);
		}
	}
	/**
	* Support for `using` declarations (Explicit Resource Management).
	* Automatically disposes the handle when it goes out of scope.
	*
	* ```typescript
	* using result = vm.evalCode('1 + 2');
	* console.log(result.toNumber()); // 3
	* // result is automatically disposed here
	* ```
	*/
	[Symbol.dispose]() {
		this.dispose();
	}
};
//#endregion
export { QuickJS as i, JSException as n, MAX_STACK_SIZE as r, EvalFlags as t };