import { ContextEvalOptions } from 'quickjs-emscripten'; import { InterruptHandler } from 'quickjs-emscripten'; import { Intrinsics } from 'quickjs-emscripten'; import { QuickJSAsyncContext } from 'quickjs-emscripten'; import { QuickJSContext } from 'quickjs-emscripten'; import { QuickJSDeferredPromise } from 'quickjs-emscripten'; import { QuickJSHandle } from 'quickjs-emscripten'; import { SuccessOrFail } from 'quickjs-emscripten'; import { VmCallResult } from 'quickjs-emscripten'; /** * The Arena class manages all generated handles at once by quickjs-emscripten and automatically converts objects between the host and the QuickJS VM. */ export declare class Arena { context: QuickJSContextEx; _map: VMMap; _registeredMap: VMMap; _registeredMapDispose: Set; _transientHandles: Set; _sync: Set; _temporalSync: Set; _symbol: symbol; _symbolHandle: QuickJSHandle; _wrapHandleImpl: WrapHandle; _options?: Options; /** Constructs a new Arena instance. It requires a quickjs-emscripten context initialized with `quickjs.newContext()`. */ constructor(ctx: QuickJSContext, options?: Options); /** * Dispose of the arena and managed handles. This method won't dispose the VM itself, so the VM has to be disposed of manually. */ dispose(): void; /** Allows `using arena = new Arena(...)` to dispose the arena automatically. */ [Symbol.dispose](): void; /** * Evaluate JS code in the VM and get the result as an object on the host side. It also converts and re-throws error objects when an error is thrown during evaluation. * * @param code - The JS code to evaluate * @param filename - Optional filename used in error stacks and for debugging * @param options - Optional eval options forwarded to quickjs-emscripten's * `evalCode`, either an `EvalFlags` bitmask (`number`) or a * {@link ContextEvalOptions} object (e.g. `{ strict: true }`) */ evalCode(code: string, filename?: string, options?: number | ContextEvalOptions): T; /** * Evaluate ES module code in the VM and get the module's exports. * * Requires quickjs-emscripten >= 0.29.0 for export access. * * @param code - The ES module code to evaluate * @param filename - Optional filename for debugging purposes (default: "module.js") * @param options - Optional {@link ContextEvalOptions}. `type` is always forced * to `"module"`, so any `type` in `options` is overridden. A numeric * `EvalFlags` bitmask cannot be merged with the forced module type and is * therefore not supported here; if a number is passed it is ignored. * @returns The module's exports object, or a Promise resolving to exports if using top-level await * * @example * ```js * // Simple module with exports * const exports = arena.evalModule(` * export const value = 42; * export function greet(name) { * return "Hello, " + name; * } * `); * console.log(exports.value); // 42 * console.log(exports.greet("World")); // "Hello, World" * * // Module with default export * const mod = arena.evalModule('export default function(x) { return x * 2; }'); * console.log(mod.default(21)); // 42 * * // Module with top-level await * const promise = arena.evalModule('export const data = await Promise.resolve(123);'); * arena.executePendingJobs(); * const exports = await promise; * console.log(exports.data); // 123 * ``` */ evalModule(code: string, filename?: string, options?: number | ContextEvalOptions): T | Promise; /** * Almost same as `vm.executePendingJobs()`, but it converts and re-throws error objects when an error is thrown during evaluation. */ executePendingJobs(maxJobsToExecute?: number): number; /** * Set the max memory this runtime can allocate. * To remove the limit, set to `-1`. * * This is useful for preventing runaway memory usage in untrusted code. * * @param limitBytes - Maximum memory in bytes, or -1 to remove limit * * @example * ```js * // Limit sandbox to 10MB * arena.setMemoryLimit(10 * 1024 * 1024); * * try { * arena.evalCode(`const huge = new Array(1000000000);`); * } catch (e) { * console.log("Memory limit exceeded"); * } * ``` */ setMemoryLimit(limitBytes: number): void; /** * Set the max stack size for this runtime, in bytes. * To remove the limit, set to `0`. * * This is useful for preventing stack overflow from deeply nested calls or recursion. * * @param stackSize - Maximum stack size in bytes, or 0 to remove limit * * @example * ```js * // Limit stack to 512KB * arena.setMaxStackSize(512 * 1024); * * try { * arena.evalCode(`function recurse() { recurse(); } recurse();`); * } catch (e) { * console.log("Stack overflow prevented"); * } * ``` */ setMaxStackSize(stackSize: number): void; /** * Set a callback which is regularly called by the QuickJS engine when it is * executing code. This callback can be used to implement an execution * timeout: return `true` from the handler to interrupt the running code. * * This is useful for preventing runaway CPU usage (e.g. infinite loops) in * untrusted code. * * @param cb - The interrupt handler. Return `true` to interrupt execution. * * @example * ```js * // Interrupt evaluation after 1 second * const deadline = Date.now() + 1000; * arena.setInterruptHandler(() => Date.now() > deadline); * * try { * arena.evalCode(`while (true) {}`); * } catch (e) { * console.log("Execution interrupted"); * } * ``` */ setInterruptHandler(cb: InterruptHandler): void; /** * Remove the interrupt handler previously set with `setInterruptHandler`. * * @example * ```js * arena.removeInterruptHandler(); * ``` */ removeInterruptHandler(): void; /** * Get detailed memory usage statistics for this runtime. * * @returns An object containing detailed memory allocation information * * @example * ```js * const stats = arena.getMemoryUsage(); * console.log(`Memory used: ${stats.memory_used_size} bytes`); * console.log(`Object count: ${stats.obj_count}`); * console.log(`Memory limit: ${stats.malloc_limit}`); * ``` */ getMemoryUsage(): { malloc_limit: number; memory_used_size: number; malloc_count: number; memory_used_count: number; atom_count: number; atom_size: number; str_count: number; str_size: number; obj_count: number; obj_size: number; prop_count: number; prop_size: number; shape_count: number; shape_size: number; js_func_count: number; js_func_size: number; js_func_code_size: number; js_func_pc2line_count: number; js_func_pc2line_size: number; c_func_count: number; array_count: number; fast_array_count: number; fast_array_elements: number; binary_object_count: number; binary_object_size: number; }; /** * Get a human-readable description of memory usage in this runtime. * * @returns A formatted string showing memory statistics * * @example * ```js * console.log(arena.dumpMemoryUsage()); * // Output: * // QuickJS memory usage: * // malloc_limit: 4294967295 * // memory_used_size: 67078 * // ... * ``` */ dumpMemoryUsage(): string; /** * Expose objects as global objects in the VM. * * By default, exposed objects are not synchronized between the host and the VM. * If you want to sync an objects, first wrap the object with sync method, and then expose the wrapped object. */ expose(obj: Record): void; /** * Enables sync for the object between the host and the VM and returns objects wrapped with proxies. * * The return value is necessary in order to reflect changes to the object from the host to the VM. Please note that setting a value in the field or deleting a field in the original object will not synchronize it. */ sync(target: T): T; /** * Register a pair of objects that will be considered the same between the host and the QuickJS VM. * * Instead of a string, you can also pass a QuickJSHandle directly. In that case, however, when you have to dispose them manually when destroying the VM. */ register(target: any, handleOrCode: QuickJSHandle | string): void; /** * Execute `register` methods for each pair. */ registerAll(map: Iterable<[any, QuickJSHandle | string]>): void; /** * Unregister a pair of objects that were registered with `registeredObjects` option and `register` method. */ unregister(target: any, dispose?: boolean): void; /** * Execute `unregister` methods for each target. */ unregisterAll(targets: Iterable, dispose?: boolean): void; startSync(target: any): void; endSync(target: any): void; _unwrapResult(result: SuccessOrFail): T; _unwrapResultAndUnmarshal(result: VmCallResult | undefined): any; _isMarshalable: (t: unknown) => boolean | "json"; _marshalByReference: (t: unknown) => boolean; _asyncify: (t: unknown) => boolean; _registerHostRef: (t: unknown, handle: QuickJSHandle) => QuickJSHandle; _marshalFind: (t: unknown) => QuickJSHandle | undefined; _marshalPre: (t: unknown, h: QuickJSHandle | QuickJSDeferredPromise, mode: true | "json" | undefined) => Wrapped | undefined; _registerTransient: (handle: QuickJSHandle) => void; _disposeTransient: (handle: QuickJSHandle) => void; _marshalPreApply: (target: (...args: any[]) => any, that: unknown, args: unknown[]) => void; _marshal: (target: any) => [QuickJSHandle, boolean]; _prepareMarshalReturn: (h: QuickJSHandle) => QuickJSHandle; _preUnmarshal: (t: any, h: QuickJSHandle) => Wrapped; _unmarshalFind: (h: QuickJSHandle) => unknown; _unmarshal: (handle: QuickJSHandle) => any; _register(t: any, h: QuickJSHandle, map?: VMMap, sync?: boolean): [Wrapped, Wrapped] | undefined; _syncMode: (obj: any) => "both" | undefined; _wrap(target: T): Wrapped | undefined; _unwrap(target: T): T; _unwrapIfNotSynced: (target: T) => T; _wrapHandle(handle: QuickJSHandle): [Wrapped | undefined, boolean]; _unwrapHandle(target: QuickJSHandle): [QuickJSHandle, boolean]; } /** * An Arena backed by a {@link QuickJSAsyncContext}. In addition to everything * `Arena` offers, it can evaluate code asynchronously with `evalCodeAsync`, * which lets the VM await host promises (e.g. async module loaders or async * functions exposed from the host) without manually pumping pending jobs. */ export declare class AsyncArena extends Arena { asyncContext: QuickJSAsyncContext; constructor(ctx: QuickJSAsyncContext, options?: Options); /** * Evaluate JS code asynchronously in the VM and get the result on the host * side. Like `evalCode`, it converts and re-throws errors thrown during * evaluation. Use this when the code awaits host-provided promises. * * @param code - The JS code to evaluate * @param filename - Optional filename used in error stacks and for debugging * @param options - Optional eval options forwarded to quickjs-emscripten's * `evalCodeAsync`, either an `EvalFlags` bitmask (`number`) or a * {@link ContextEvalOptions} object (e.g. `{ strict: true }`) */ evalCodeAsync(code: string, filename?: string, options?: number | ContextEvalOptions): Promise; } export declare function call(ctx: QuickJSContext, code: string, thisArg?: QuickJSHandle, ...args: QuickJSHandle[]): QuickJSHandle; /** * Measure the complexity of an object as you traverse the field and prototype chain. If max is specified, when the complexity reaches max, the traversal is terminated and it returns the max. In this function, one object and function are counted as a complexity of 1, and primitives are not counted as a complexity. */ export declare function complexity(value: any, max?: number): number; export declare function consumeAll(handles: T, cb: (handles: T) => K): K; export { ContextEvalOptions } /** * Default value of registeredObjects option of the Arena class constructor. */ export declare const defaultRegisteredObjects: [any, string][]; export { InterruptHandler } export { Intrinsics } export declare function isES2015Class(cls: any): cls is new (...args: any[]) => any; export declare function isHandleObject(ctx: QuickJSContext, h: QuickJSHandle): boolean; export declare function isObject(value: any): value is object | ((...args: any[]) => any); export declare function json(ctx: QuickJSContext, target: any): QuickJSHandle; export declare function marshal(target: unknown, options: Options_2): QuickJSHandle; export declare type Options = { /** A callback that returns a boolean value that determines whether an object is marshalled or not. If false, no marshaling will be done and undefined will be passed to the QuickJS VM, otherwise marshaling will be done. By default, all objects will be marshalled. */ isMarshalable?: boolean | "json" | ((target: any) => boolean | "json"); /** Pre-registered pairs of objects that will be considered the same between the host and the QuickJS VM. This will be used automatically during the conversion. By default, it will be registered automatically with `defaultRegisteredObjects`. * * Instead of a string, you can also pass a QuickJSHandle directly. In that case, however, you have to dispose of them manually when destroying the VM. */ registeredObjects?: Iterable<[any, QuickJSHandle | string]>; /** Register functions to convert an object to a QuickJS handle. */ customMarshaller?: Iterable<(target: unknown, ctx: QuickJSContext) => QuickJSHandle | undefined>; /** Register functions to convert a QuickJS handle to an object. */ customUnmarshaller?: Iterable<(target: QuickJSHandle, ctx: QuickJSContext) => any>; /** A callback that returns a boolean value that determines whether an object is wrappable by proxies. If returns false, note that the object cannot be synchronized between the host and the QuickJS even if arena.sync is used. */ isWrappable?: (target: any) => boolean; /** A callback that returns a boolean value that determines whether an QuickJS handle is wrappable by proxies. If returns false, note that the handle cannot be synchronized between the host and the QuickJS even if arena.sync is used. */ isHandleWrappable?: (handle: QuickJSHandle, ctx: QuickJSContext) => boolean; /** Compatibility with quickjs-emscripten prior to v0.15. Inject code for compatibility into context at Arena class initialization time. */ compat?: boolean; /** Experimental: use QuickJSContextEx, which wraps existing QuickJSContext. */ experimentalContextEx?: boolean; /** Globally enable sync mode (default `true`). When `false`, objects are not wrapped with proxies and marshalled handles are disposed after use, so `arena.sync` has no effect but objects are not retained for their whole lifetime. Useful to avoid memory growth when frequently exchanging short-lived objects. */ syncEnabled?: boolean; /** A callback that returns whether an object should be passed to the VM by reference (as an opaque HostRef) instead of being marshalled by value/proxy. The guest cannot read such objects, but can hold them and pass them back to the host, where they resolve to the original object. */ marshalByReference?: (target: any) => boolean; /** * Marshal selected host functions as *asyncified* functions. Normally an async * host function is marshalled like any other function, so the guest receives a * marshalled `Promise`. When a function is asyncified, the QuickJS VM instead * suspends until the host promise settles and the guest receives the resolved * value synchronously (as if the call were blocking). * * - `true`: asyncify every host function that is *declared* async, auto-detected * via `Object.prototype.toString.call(fn) === "[object AsyncFunction]"`. Note * that functions transpiled to ES5 (e.g. by Babel/TypeScript targeting older * runtimes) are plain functions returning a promise and are **not** detected — * use the predicate form for those. * - predicate: asyncify exactly the functions for which it returns `true`. It is * called with the *unwrapped* target (the original function, not a sync proxy), * like `isMarshalable`. * - absent/`false`: current behavior; async functions yield a `Promise` in the guest. * * Constraints (Emscripten Asyncify): * - Asyncified functions only work when evaluation is entered through an async * entry point ({@link AsyncArena.evalCodeAsync}). Calling one during a * synchronous `evalCode` fails with `Error: Function unexpectedly returned a Promise`. * - Only ONE suspended call is allowed at a time; concurrent suspension throws a * runtime error from quickjs-emscripten. * - If the context does not support `newAsyncifiedFunction` (a plain sync context * from `getQuickJS().newContext()`), this option is silently ignored and async * functions behave as today (Promise). */ asyncify?: boolean | ((target: (...args: any[]) => any) => boolean); }; declare type Options_2 = { ctx: QuickJSContext; unmarshal: (handle: QuickJSHandle) => unknown; isMarshalable?: (target: unknown) => boolean | "json"; marshalByReference?: (target: unknown) => boolean; registerHostRef?: (target: unknown, handle: QuickJSHandle) => QuickJSHandle; find: (target: unknown) => QuickJSHandle | undefined; registerTransient?: (handle: QuickJSHandle) => void; disposeTransient?: (handle: QuickJSHandle) => void; pre: (target: unknown, handle: QuickJSHandle | QuickJSDeferredPromise, mode: true | "json" | undefined) => QuickJSHandle | undefined; preApply?: (target: (...args: any[]) => any, thisArg: unknown, args: unknown[]) => any; prepareReturn?: (handle: QuickJSHandle) => QuickJSHandle; unwrap?: (target: unknown) => unknown; asyncify?: (target: unknown) => boolean; custom?: Iterable<(obj: unknown, ctx: QuickJSContext) => QuickJSHandle | undefined>; }; declare type Options_3 = { ctx: QuickJSContext; /** marshal returns handle and boolean indicates that the handle should be disposed after use */ marshal: (target: unknown) => [QuickJSHandle, boolean]; find: (handle: QuickJSHandle) => unknown | undefined; pre: (target: T, handle: QuickJSHandle) => T | undefined; custom?: Iterable<(obj: QuickJSHandle, ctx: QuickJSContext) => any>; /** When true, resolve opaque HostRef handles back to their host value. */ hostRef?: boolean; }; declare type QuickJSContextEx = QuickJSContext & { disposeEx?: () => void; }; export declare function unmarshal(handle: QuickJSHandle, options: Options_3): any; /** * Bidirectional map between host values and QuickJS handles. * * Each registered pair gets a numeric id. A value may be registered under two * keys (e.g. a proxy-wrapped object and the underlying object), each with its * own handle, so every lookup direction is backed by an explicit map and id * reverse-lookups, keeping `delete` O(1). */ export declare class VMMap { ctx: QuickJSContext; _keyToId: Map; _key2ToId: Map; _idToHandle: Map; _idToHandle2: Map; _idToKey: Map; _idToKey2: Map; _disposables: Set; _mapGet: QuickJSHandle; _mapSet: QuickJSHandle; _mapDelete: QuickJSHandle; _mapClear: QuickJSHandle; _nextId: number; constructor(ctx: QuickJSContext); set(key: any, handle: QuickJSHandle, key2?: any, handle2?: QuickJSHandle): boolean; merge(iteratable: Iterable<[any, QuickJSHandle | undefined] | [any, QuickJSHandle | undefined, any, QuickJSHandle | undefined]> | undefined): void; get(key: any): QuickJSHandle | undefined; getByHandle(handle: QuickJSHandle): any; has(key: any): boolean; hasHandle(handle: QuickJSHandle): boolean; keys(): MapIterator; delete(key: any, dispose?: boolean): void; deleteByHandle(handle: QuickJSHandle, dispose?: boolean): void; clear(): void; dispose(): void; get size(): number; [Symbol.iterator](): Iterator<[any, QuickJSHandle, any, QuickJSHandle | undefined]>; _call(fn: QuickJSHandle, thisArg: QuickJSHandle | undefined, ...args: QuickJSHandle[]): QuickJSHandle; } export declare function walkObject(value: any, callback?: (target: any, set: Set) => boolean | void): Set; declare type WrapHandle = { /** Wrap a VM handle with the shared proxyFuncs, like the old `wrapHandle`. */ wrapHandle: (handle: QuickJSHandle) => [Wrapped | undefined, boolean]; /** Dispose the shared proxyFuncs handle. Call exactly once, at Arena dispose. */ dispose: () => void; }; declare type Wrapped = T & { __qes_wrapped: never; }; export { }