import * as _componentor_quickjs_emscripten_core from '@componentor/quickjs-emscripten-core';
import { ContextOptions, Disposable, ContextEvalOptions, QuickJSAsyncContext, QuickJSHandle, VmCallResult } from '@componentor/quickjs-emscripten-core';

/**
 * Available QuickJS variants for the worker pool.
 *
 * - `"singlefile"` (default): Isolated workers with no shared state.
 *   Best for sandboxed execution where workers don't need to share data.
 *
 * - `"wasmfs"`: Workers with shared OPFS filesystem.
 *   All workers mount the same OPFS directory, enabling file-based communication.
 *   Requires SharedArrayBuffer (COOP/COEP headers in browsers).
 */
type WorkerPoolVariant = "singlefile" | "wasmfs";
/**
 * Configuration options for creating a worker pool.
 */
interface WorkerPoolOptions {
    /**
     * Number of workers in the pool.
     * Defaults to `navigator.hardwareConcurrency` in browsers, or 4 in Node.js.
     */
    poolSize?: number;
    /**
     * QuickJS variant to use in workers.
     *
     * - `"singlefile"` (default): Isolated workers, no shared filesystem.
     * - `"wasmfs"`: Workers share an OPFS-backed filesystem.
     *
     * When using `"wasmfs"`, you can configure the mount path with `opfsMountPath`.
     */
    variant?: WorkerPoolVariant;
    /**
     * OPFS mount path when using the "wasmfs" variant.
     * All workers will mount the same OPFS directory at this path.
     * Default is "/data".
     *
     * Only used when `variant` is `"wasmfs"`.
     */
    opfsMountPath?: string;
    /**
     * Context options applied to each worker's QuickJS context.
     */
    contextOptions?: ContextOptions;
    /**
     * Whether to pre-warm workers on pool creation.
     * When true, all workers are initialized immediately.
     * When false (default), workers are initialized lazily on first task.
     */
    preWarm?: boolean;
    /**
     * Default timeout in milliseconds for task execution.
     * 0 means no timeout. Default is 0.
     */
    defaultTimeout?: number;
    /**
     * Maximum number of tasks that can be queued.
     * When exceeded, new tasks are rejected.
     * 0 means unlimited. Default is 0.
     */
    maxQueueSize?: number;
    /**
     * If true, throws an error if multi-threading is not supported.
     * Use this when parallel execution is required for your use case.
     * Default is false (gracefully falls back to single-threaded mode).
     */
    forceMultiThreaded?: boolean;
    /**
     * If true, forces single-threaded mode even if multi-threading is supported.
     * Useful for Node.js ESM environments where worker spawning may be complex.
     * Default is false.
     */
    forceSingleThreaded?: boolean;
    /**
     * If true, enables verbose logging to console for debugging.
     * Logs worker creation, task dispatch, completion, and timing information.
     * Default is false.
     */
    verbose?: boolean;
    /**
     * JavaScript code to run when initializing each worker's QuickJS context.
     * Use this to set up polyfills, globals, or other initialization code
     * that should be available in all worker evaluations.
     *
     * The code runs once per worker when the worker is initialized.
     * It has access to the bare QuickJS context (no Node.js APIs by default).
     *
     * @example
     * ```typescript
     * const pool = await newWorkerPool({
     *   bootstrapCode: `
     *     globalThis.myHelper = function(x) { return x * 2; };
     *     globalThis.Buffer = // ... Buffer polyfill
     *   `
     * })
     * ```
     */
    bootstrapCode?: string;
    /**
     * URL or path to the WASM file for workers to load.
     * Required when workers can't resolve the WASM file from their context.
     *
     * For browser environments, this should be an absolute URL accessible
     * from the worker (e.g., "/wasm/quickjs-wasmfs.wasm").
     */
    wasmLocation?: string;
}
/**
 * A task to execute in a worker.
 */
interface WorkerTask {
    /** JavaScript code to evaluate */
    code: string;
    /** Optional filename for error stack traces */
    filename?: string;
    /** Timeout in milliseconds for this specific task (overrides pool default) */
    timeout?: number;
    /** Priority: higher numbers execute first. Default is 0. */
    priority?: number;
}
/**
 * Error information from a failed worker task.
 */
interface WorkerTaskError {
    /** Error name (e.g., "Error", "TypeError") */
    name: string;
    /** Error message */
    message: string;
    /** Stack trace if available */
    stack?: string;
    /** True if the error was caused by a timeout */
    isTimeout?: boolean;
    /** True if the worker crashed unexpectedly */
    isWorkerCrash?: boolean;
    /** True if the task was cancelled */
    isCancelled?: boolean;
}
/**
 * Result of a worker task execution.
 * Follows the SuccessOrFail pattern from quickjs-emscripten-core.
 */
type WorkerTaskResult<T = unknown> = {
    value: T;
    error?: undefined;
} | {
    value?: undefined;
    error: WorkerTaskError;
};
/**
 * Handle to a pending task, allowing cancellation and status checking.
 */
interface TaskHandle<T = unknown> {
    /** Promise that resolves when the task completes */
    readonly promise: Promise<WorkerTaskResult<T>>;
    /** Cancel the task. If queued, removes from queue. If executing, attempts to abort. */
    cancel(): void;
    /** Whether the task is still pending (queued or executing) */
    readonly pending: boolean;
    /** Unique identifier for this task */
    readonly taskId: string;
}
/**
 * Statistics about the worker pool.
 */
interface PoolStats {
    /** Total number of workers in the pool */
    poolSize: number;
    /** Number of workers currently executing tasks */
    busyWorkers: number;
    /** Number of workers available to accept tasks */
    availableWorkers: number;
    /** Number of tasks waiting in the queue */
    queuedTasks: number;
    /** Total number of tasks completed successfully */
    completedTasks: number;
    /** Total number of tasks that failed */
    failedTasks: number;
    /** Average execution time in milliseconds */
    averageExecutionTimeMs: number;
    /** Whether the pool is using multi-threading (true) or single-threaded fallback (false) */
    isMultiThreaded: boolean;
}
/**
 * A session provides persistent state across multiple evaluations.
 *
 * Unlike regular pool tasks which may execute on any available worker,
 * a session pins all evaluations to a single worker, preserving:
 * - Global variables
 * - Defined functions
 * - Module state
 * - Filesystem state (when using wasmfs variant)
 *
 * @example
 * ```typescript
 * const session = await pool.createSession()
 *
 * await session.evalCode('globalThis.counter = 0')
 * await session.evalCode('counter++')
 * await session.evalCode('counter++')
 * const result = await session.evalCode('counter')
 * console.log(result.value) // 2
 *
 * session.release() // Return worker to pool
 * ```
 */
interface WorkerSession extends Disposable {
    /** Unique session identifier */
    readonly sessionId: string;
    /** The worker ID this session is pinned to */
    readonly workerId: number;
    /** Whether the session is still active */
    readonly alive: boolean;
    /**
     * Evaluate code in this session's persistent context.
     * All evaluations share the same global state.
     */
    evalCode(code: string, options?: SessionEvalOptions): Promise<WorkerTaskResult>;
    /**
     * Release the session and return the worker to the pool.
     * After calling release(), the session can no longer be used.
     */
    release(): void;
}
/**
 * Options for session evaluation.
 */
interface SessionEvalOptions {
    /** Optional filename for error stack traces */
    filename?: string;
    /** Timeout in milliseconds for this evaluation */
    timeout?: number;
}

/**
 * A pool of workers for parallel QuickJS execution.
 *
 * Each worker runs in a separate thread with its own isolated WASM module
 * and QuickJS context, providing true parallelism for CPU-bound tasks.
 *
 * When SharedArrayBuffer is not available (no COOP/COEP headers), the pool
 * automatically falls back to single-threaded execution on the main thread.
 *
 * @example
 * ```typescript
 * const pool = await newWorkerPool({ poolSize: 4 })
 *
 * // Check if we're using real workers
 * console.log('Multi-threaded:', pool.isMultiThreaded)
 *
 * // Execute tasks in parallel (or sequentially in fallback mode)
 * const results = await Promise.all([
 *   pool.evalCode('1 + 1'),
 *   pool.evalCode('2 * 2'),
 *   pool.evalCode('Math.sqrt(16)'),
 * ])
 *
 * // Clean up
 * pool.dispose()
 * ```
 */
declare class QuickJSWorkerPool implements Disposable {
    private readonly taskQueue;
    private readonly executor;
    private readonly logger;
    private taskIdCounter;
    private sessionIdCounter;
    private completedTasks;
    private failedTasks;
    private totalExecutionTime;
    private _alive;
    private pendingExecutions;
    private activeSessions;
    private constructor();
    /**
     * Create a new worker pool.
     *
     * @param options Configuration options for the pool
     * @returns A new QuickJSWorkerPool instance
     *
     * @throws {MultiThreadingNotSupportedError} If forceMultiThreaded is true and
     *   SharedArrayBuffer is not available
     */
    static create(options?: WorkerPoolOptions): Promise<QuickJSWorkerPool>;
    /**
     * Whether the pool is using multi-threading (true) or single-threaded fallback (false).
     */
    get isMultiThreaded(): boolean;
    /**
     * Whether the pool is still alive (not disposed).
     */
    get alive(): boolean;
    /**
     * Number of workers currently executing tasks.
     */
    get busyWorkers(): number;
    /**
     * Number of workers available to accept tasks.
     */
    get availableWorkers(): number;
    /**
     * Number of tasks waiting in the queue.
     */
    get queuedTasks(): number;
    /**
     * Number of active sessions.
     */
    get activeSessionCount(): number;
    /**
     * Create a session for persistent state across multiple evaluations.
     *
     * A session pins all evaluations to a single worker, preserving:
     * - Global variables
     * - Defined functions
     * - Module state
     * - Filesystem state (when using wasmfs variant)
     *
     * @returns A session object for persistent evaluations
     * @throws {PoolDisposedError} If the pool has been disposed
     * @throws {Error} If no workers are available
     *
     * @example
     * ```typescript
     * const session = await pool.createSession()
     *
     * await session.evalCode('globalThis.counter = 0')
     * await session.evalCode('counter++')
     * const result = await session.evalCode('counter')
     * console.log(result.value) // 1
     *
     * session.release() // Return worker to pool
     * ```
     */
    createSession(): Promise<WorkerSession>;
    /**
     * Evaluate JavaScript code in an available worker.
     *
     * @param code JavaScript code to evaluate
     * @param options Optional task options (timeout, filename, priority)
     * @returns The result of the evaluation
     */
    evalCode(code: string, options?: Partial<Omit<WorkerTask, "code">>): Promise<WorkerTaskResult>;
    /**
     * Execute multiple tasks and return when all complete.
     *
     * @param tasks Array of tasks to execute
     * @returns Array of results in the same order as the input tasks
     */
    evalCodeBatch(tasks: WorkerTask[]): Promise<WorkerTaskResult[]>;
    /**
     * Submit a task and get a handle for status checking and cancellation.
     *
     * @param task The task to execute
     * @returns A handle to the pending task
     *
     * @throws {PoolDisposedError} If the pool has been disposed
     * @throws {QueueFullError} If the queue is full
     */
    submit(task: WorkerTask): TaskHandle;
    private executeTask;
    private processNextTask;
    /**
     * Get pool statistics.
     */
    getStats(): PoolStats;
    /**
     * Dispose of the pool and all its workers.
     * Rejects any pending tasks and releases all sessions.
     */
    dispose(): void;
    [Symbol.dispose](): void;
}
/**
 * Create a new worker pool.
 *
 * @param options Configuration options for the pool
 * @returns A new QuickJSWorkerPool instance
 */
declare function newWorkerPool(options?: WorkerPoolOptions): Promise<QuickJSWorkerPool>;
/**
 * Get a shared singleton worker pool.
 *
 * This is convenient for simple use cases. For more control,
 * use {@link newWorkerPool} to create isolated pool instances.
 *
 * @returns The singleton QuickJSWorkerPool instance
 */
declare function getWorkerPool(): Promise<QuickJSWorkerPool>;
/**
 * Provides synchronous access to the singleton pool, if it has been initialized.
 *
 * @throws Error if the singleton has not been initialized via {@link getWorkerPool}
 */
declare function getWorkerPoolSync(): QuickJSWorkerPool;

/**
 * Result type that mirrors QuickJSContextResult from the main runtime.
 * Provides a familiar API for clients using the worker pool.
 */
type WorkerPoolContextResult<T = unknown> = {
    value: T;
    error?: undefined;
} | {
    error: WorkerTaskError;
    value?: undefined;
};
/**
 * Options for evalCodeAsync, mirroring the main runtime API.
 */
interface WorkerPoolEvalOptions extends ContextEvalOptions {
    /** Timeout in milliseconds */
    timeout?: number;
    /** Filename for error messages */
    filename?: string;
}
/**
 * A context-like wrapper around QuickJSWorkerPool that provides an API
 * similar to QuickJSAsyncContext for seamless integration.
 *
 * This allows clients to use a familiar interface while automatically
 * benefiting from parallel worker execution when available.
 *
 * Key differences from QuickJSAsyncContext:
 * - No handle-based operations (newFunction, newObject, etc.)
 * - Values are automatically serialized/deserialized across worker boundaries
 * - Multiple concurrent evalCodeAsync calls are distributed across workers
 * - State is isolated per-worker (use sessions for persistent state)
 *
 * @example
 * ```typescript
 * // Create a pool-backed context
 * const pool = await newWorkerPool({ poolSize: 4 })
 * const context = new WorkerPoolContext(pool)
 *
 * // Use like QuickJSAsyncContext
 * const result = await context.evalCodeAsync('1 + 1')
 * if (result.value !== undefined) {
 *   console.log('Result:', result.value) // 2
 * }
 *
 * // Parallel execution - multiple calls are distributed across workers
 * const results = await Promise.all([
 *   context.evalCodeAsync('Math.sqrt(16)'),
 *   context.evalCodeAsync('Math.pow(2, 10)'),
 *   context.evalCodeAsync('[1,2,3].map(x => x * 2)'),
 * ])
 *
 * context.dispose()
 * ```
 */
declare class WorkerPoolContext implements Disposable {
    private _pool;
    private _alive;
    /**
     * Create a new WorkerPoolContext wrapping the given pool.
     *
     * @param pool The worker pool to use for code execution
     */
    constructor(pool: QuickJSWorkerPool);
    /**
     * Whether the context is still alive (not disposed).
     */
    get alive(): boolean;
    /**
     * Whether the underlying pool is using multi-threading.
     */
    get isMultiThreaded(): boolean;
    /**
     * Evaluate JavaScript code asynchronously.
     *
     * This method mirrors QuickJSAsyncContext.evalCodeAsync() but routes
     * execution to a worker pool for parallel processing.
     *
     * @param code JavaScript code to evaluate
     * @param filenameOrOptions Filename string or evaluation options
     * @returns Promise resolving to the evaluation result
     *
     * @example
     * ```typescript
     * // Simple usage
     * const result = await context.evalCodeAsync('1 + 1')
     *
     * // With filename
     * const result = await context.evalCodeAsync('throw new Error("oops")', 'test.js')
     *
     * // With options
     * const result = await context.evalCodeAsync('while(true){}', {
     *   filename: 'infinite.js',
     *   timeout: 1000,
     * })
     * ```
     */
    evalCodeAsync(code: string, filenameOrOptions?: string | WorkerPoolEvalOptions): Promise<WorkerPoolContextResult>;
    /**
     * Evaluate multiple code snippets in parallel.
     *
     * This takes advantage of the worker pool to execute all tasks
     * concurrently across available workers.
     *
     * @param tasks Array of code snippets or task objects
     * @returns Promise resolving to array of results in the same order
     *
     * @example
     * ```typescript
     * const results = await context.evalCodeBatch([
     *   '1 + 1',
     *   '2 * 2',
     *   'Math.sqrt(16)',
     * ])
     * console.log(results.map(r => r.value)) // [2, 4, 4]
     *
     * // With options
     * const results = await context.evalCodeBatch([
     *   { code: 'compute()', timeout: 5000 },
     *   { code: 'process()', timeout: 10000 },
     * ])
     * ```
     */
    evalCodeBatch(tasks: (string | {
        code: string;
        filename?: string;
        timeout?: number;
    })[]): Promise<WorkerPoolContextResult[]>;
    /**
     * Unwrap a result, throwing if it's an error.
     *
     * This is a convenience method that mirrors QuickJSContext.unwrapResult().
     *
     * @param result The result to unwrap
     * @returns The value if successful
     * @throws Error if the result contains an error
     */
    unwrapResult<T>(result: WorkerPoolContextResult<T>): T;
    /**
     * Dispose of the context.
     *
     * Note: This does NOT dispose the underlying pool. The pool should be
     * disposed separately when no longer needed.
     */
    dispose(): void;
    [Symbol.dispose](): void;
}
/**
 * Create a context-like wrapper around a worker pool.
 *
 * This provides an API similar to QuickJSAsyncContext while routing
 * code execution to workers for parallel processing.
 *
 * @param pool The worker pool to wrap
 * @returns A context-like interface to the pool
 */
declare function newWorkerPoolContext(pool: QuickJSWorkerPool): WorkerPoolContext;

/**
 * Options for creating a WorkerEnabledContext.
 */
interface WorkerEnabledContextOptions extends WorkerPoolOptions {
    /**
     * If true, only use workers for evalCodeAsync (no local context).
     * Useful when you only need code evaluation without handle operations.
     * @default false
     */
    workerOnly?: boolean;
    /**
     * Whether to use a session for sequential evalCodeAsync calls.
     * When true, all evalCodeAsync calls go to the same worker,
     * preserving state (variables, functions) across calls.
     * When false (default), each eval may go to a different worker (parallel execution).
     *
     * For shared state across parallel workers, use `bootstrapCode` instead.
     *
     * @default false
     */
    useSession?: boolean;
    /**
     * Strategy for routing evalCodeAsync calls.
     * - "workers": Always route to workers (default when pool available)
     * - "local": Always use local context
     * - "auto": Use workers for standalone evals, local for code that needs handles
     * @default "workers"
     */
    evalStrategy?: "workers" | "local" | "auto";
}
/**
 * Result type that matches QuickJSContextResult for API compatibility.
 */
type WorkerEnabledContextResult<T = unknown> = {
    value: T;
    error?: undefined;
} | {
    error: QuickJSHandle;
    value?: undefined;
};
/**
 * A hybrid context that combines local QuickJSAsyncContext with worker pool execution.
 *
 * This allows you to use the familiar QuickJS API while automatically benefiting
 * from parallel worker execution.
 *
 * **How it works:**
 * - By default, uses parallel execution across workers (useSession: false)
 * - Use `bootstrapCode` to set up shared state (like mocks) on all workers
 * - Handle operations (newFunction, newObject, etc.) use the local context
 * - Falls back to local context when workers unavailable
 *
 * **Use cases:**
 * - Parallel execution of independent tasks across workers
 * - Shared initial state via `bootstrapCode` (e.g., HTTP client mocks)
 * - Use `useSession: true` if you need state to persist across calls
 *
 * @example
 * ```typescript
 * // Create with automatic worker pool and parallel execution (default)
 * const ctx = await newWorkerEnabledContext({
 *   poolSize: 4,
 *   // Bootstrap code runs on each worker - great for mocks!
 *   bootstrapCode: `
 *     globalThis.mockFetch = (url) => ({ status: 200, data: 'mocked' })
 *   `
 * })
 *
 * // Parallel execution - each call may hit a different worker
 * // But all workers have mockFetch available from bootstrap!
 * const results = await Promise.all([
 *   ctx.evalCodeAsync('mockFetch("/api/1")'),  // Worker 1
 *   ctx.evalCodeAsync('mockFetch("/api/2")'),  // Worker 2
 *   ctx.evalCodeAsync('mockFetch("/api/3")'),  // Worker 3
 * ])
 *
 * ctx.dispose()
 * ```
 */
declare class WorkerEnabledContext implements Disposable {
    private _module;
    private _localContext;
    private _pool;
    private _session;
    private _alive;
    private _useSession;
    private _evalStrategy;
    private constructor();
    /**
     * Create a new WorkerEnabledContext.
     *
     * Automatically creates a worker pool when SharedArrayBuffer is available,
     * falling back to local-only execution otherwise.
     *
     * By default, uses parallel execution (useSession: false). Use `bootstrapCode`
     * to set up shared state across all workers.
     */
    static create(options?: WorkerEnabledContextOptions): Promise<WorkerEnabledContext>;
    /**
     * Whether the context is still alive.
     */
    get alive(): boolean;
    /**
     * Whether workers are available for parallel execution.
     */
    get hasWorkerPool(): boolean;
    /**
     * Whether the worker pool is using real multi-threading.
     */
    get isMultiThreaded(): boolean;
    /**
     * The underlying local context (null if worker-only mode).
     * Use this for advanced handle operations.
     */
    get localContext(): QuickJSAsyncContext | null;
    /**
     * The underlying worker pool (null if not available).
     */
    get pool(): QuickJSWorkerPool | null;
    /**
     * The underlying worker session (null if not using sessions or unavailable).
     */
    get session(): WorkerSession | null;
    /**
     * Whether this context uses a session for persistent state.
     */
    get usesSession(): boolean;
    /**
     * The global object of the local context.
     * @throws Error if in worker-only mode
     */
    get global(): QuickJSHandle;
    /**
     * The runtime of the local context.
     * @throws Error if in worker-only mode
     */
    get runtime(): _componentor_quickjs_emscripten_core.QuickJSAsyncRuntime;
    /**
     * Evaluate JavaScript code asynchronously.
     *
     * By default (useSession: false), this routes to any available worker for parallel execution.
     * Use `bootstrapCode` to set up shared state across all workers.
     *
     * When useSession is true, all calls go to the same worker (state persists).
     *
     * Falls back to the local context when workers are unavailable.
     *
     * @param code JavaScript code to evaluate
     * @param filename Optional filename for error messages
     * @param options Optional evaluation options
     */
    evalCodeAsync(code: string, filename?: string, options?: number | ContextEvalOptions): Promise<VmCallResult<QuickJSHandle>>;
    /**
     * Evaluate code on workers and return the raw worker result.
     * Use this when you don't need QuickJS handles.
     */
    evalCodeOnWorkers(code: string, options?: {
        filename?: string;
        timeout?: number;
    }): Promise<WorkerTaskResult>;
    /**
     * Evaluate multiple code snippets in parallel across workers.
     */
    evalCodeBatch(tasks: (string | {
        code: string;
        filename?: string;
        timeout?: number;
    })[]): Promise<WorkerTaskResult[]>;
    /**
     * Create a new QuickJS function.
     * @throws Error if in worker-only mode
     */
    newFunction(name: string, fn: (this: QuickJSHandle, ...args: QuickJSHandle[]) => QuickJSHandle | undefined): QuickJSHandle;
    /**
     * Create a new QuickJS object.
     * @throws Error if in worker-only mode
     */
    newObject(prototype?: QuickJSHandle): QuickJSHandle;
    /**
     * Create a new QuickJS array.
     * @throws Error if in worker-only mode
     */
    newArray(): QuickJSHandle;
    /**
     * Create a new QuickJS string.
     * @throws Error if in worker-only mode
     */
    newString(str: string): QuickJSHandle;
    /**
     * Create a new QuickJS number.
     * @throws Error if in worker-only mode
     */
    newNumber(num: number): QuickJSHandle;
    /**
     * Create a new QuickJS BigInt.
     * @throws Error if in worker-only mode
     */
    newBigInt(num: bigint): QuickJSHandle;
    /**
     * Get the undefined value.
     * @throws Error if in worker-only mode
     */
    get undefined(): QuickJSHandle;
    /**
     * Get the null value.
     * @throws Error if in worker-only mode
     */
    get null(): QuickJSHandle;
    /**
     * Get the true value.
     * @throws Error if in worker-only mode
     */
    get true(): QuickJSHandle;
    /**
     * Get the false value.
     * @throws Error if in worker-only mode
     */
    get false(): QuickJSHandle;
    /**
     * Get a string from a handle.
     * @throws Error if in worker-only mode
     */
    getString(handle: QuickJSHandle): string;
    /**
     * Get a number from a handle.
     * @throws Error if in worker-only mode
     */
    getNumber(handle: QuickJSHandle): number;
    /**
     * Get a BigInt from a handle.
     * @throws Error if in worker-only mode
     */
    getBigInt(handle: QuickJSHandle): bigint;
    /**
     * Get a property from an object.
     * @throws Error if in worker-only mode
     */
    getProp(handle: QuickJSHandle, key: QuickJSHandle | string): QuickJSHandle;
    /**
     * Set a property on an object.
     * @throws Error if in worker-only mode
     */
    setProp(handle: QuickJSHandle, key: QuickJSHandle | string, value: QuickJSHandle): void;
    /**
     * Call a function.
     * @throws Error if in worker-only mode
     */
    callFunction(func: QuickJSHandle, thisVal: QuickJSHandle, ...args: QuickJSHandle[]): VmCallResult<QuickJSHandle>;
    /**
     * Dump a handle to a JavaScript value.
     * @throws Error if in worker-only mode
     */
    dump(handle: QuickJSHandle): unknown;
    /**
     * Get the type of a handle.
     * @throws Error if in worker-only mode
     */
    typeof(handle: QuickJSHandle): string;
    /**
     * Convert a worker result to VmCallResult format.
     * Creates handles in the local context for the values.
     */
    private workerResultToVmResult;
    /**
     * Convert a JavaScript value to a QuickJS handle.
     */
    private valueToHandle;
    /**
     * Dispose of the context and all resources.
     */
    dispose(): void;
    [Symbol.dispose](): void;
}
/**
 * Create a new WorkerEnabledContext.
 *
 * This is the recommended way to use QuickJS with parallel worker execution.
 *
 * By default (useSession: false), evalCodeAsync calls are distributed across workers
 * for parallel execution. Use `bootstrapCode` to set up shared state (like mocks)
 * that runs on each worker.
 *
 * @example
 * ```typescript
 * // Parallel execution with shared mocks via bootstrapCode
 * const ctx = await newWorkerEnabledContext({
 *   poolSize: 4,
 *   bootstrapCode: `
 *     globalThis.mockFetch = (url) => ({ status: 200, url })
 *   `
 * })
 *
 * // Parallel execution - each call may hit a different worker
 * // All workers have mockFetch from bootstrap!
 * const results = await Promise.all([
 *   ctx.evalCodeAsync('mockFetch("/api/1")'),
 *   ctx.evalCodeAsync('mockFetch("/api/2")'),
 *   ctx.evalCodeAsync('mockFetch("/api/3")'),
 * ])
 *
 * ctx.dispose()
 * ```
 *
 * @example
 * ```typescript
 * // Use session for state persistence (sequential execution)
 * const ctx = await newWorkerEnabledContext({
 *   poolSize: 4,
 *   useSession: true,  // All calls go to same worker
 * })
 *
 * await ctx.evalCodeAsync('let x = 10')
 * await ctx.evalCodeAsync('x += 5')
 * const result = await ctx.evalCodeAsync('x')  // returns 15
 * ```
 */
declare function newWorkerEnabledContext(options?: WorkerEnabledContextOptions): Promise<WorkerEnabledContext>;

/**
 * Detect if multi-threading via Web Workers with SharedArrayBuffer is supported.
 *
 * In browsers, this requires:
 * - SharedArrayBuffer to be available
 * - The page to be cross-origin isolated (COOP/COEP headers set)
 *
 * In Node.js, worker_threads is always available.
 *
 * @returns true if multi-threading is supported, false otherwise
 */
declare function isMultiThreadingSupported(): boolean;
/**
 * Get the default pool size based on the environment.
 *
 * @returns The number of logical CPU cores, or 4 as a fallback
 */
declare function getDefaultPoolSize(): number;
/**
 * Detect the current platform.
 *
 * @returns 'node' for Node.js, 'browser' for browser environments
 */
declare function detectPlatform(): "node" | "browser";

/**
 * Thrown when a task times out.
 */
declare class WorkerTaskTimeoutError extends Error {
    readonly taskId: string;
    readonly timeoutMs: number;
    readonly name = "WorkerTaskTimeoutError";
    readonly isTimeout = true;
    constructor(taskId: string, timeoutMs: number);
}
/**
 * Thrown when a task is cancelled.
 */
declare class WorkerTaskCancelledError extends Error {
    readonly taskId: string;
    readonly name = "WorkerTaskCancelledError";
    readonly isCancelled = true;
    constructor(taskId: string);
}
/**
 * Thrown when a worker crashes unexpectedly.
 */
declare class WorkerCrashError extends Error {
    readonly taskId: string;
    readonly originalError?: Error | undefined;
    readonly name = "WorkerCrashError";
    readonly isWorkerCrash = true;
    constructor(taskId: string, originalError?: Error | undefined);
}
/**
 * Thrown when the pool is disposed while tasks are pending.
 */
declare class PoolDisposedError extends Error {
    readonly name = "PoolDisposedError";
    constructor();
}
/**
 * Thrown when the task queue is full and cannot accept more tasks.
 */
declare class QueueFullError extends Error {
    readonly maxSize: number;
    readonly name = "QueueFullError";
    constructor(maxSize: number);
}
/**
 * Thrown when multi-threading is required but not available.
 */
declare class MultiThreadingNotSupportedError extends Error {
    readonly name = "MultiThreadingNotSupportedError";
    constructor();
}

export { MultiThreadingNotSupportedError, PoolDisposedError, type PoolStats, QueueFullError, QuickJSWorkerPool, type SessionEvalOptions, type TaskHandle, WorkerCrashError, WorkerEnabledContext, type WorkerEnabledContextOptions, type WorkerEnabledContextResult, WorkerPoolContext, type WorkerPoolContextResult, type WorkerPoolEvalOptions, type WorkerPoolOptions, type WorkerPoolVariant, type WorkerSession, type WorkerTask, WorkerTaskCancelledError, type WorkerTaskError, type WorkerTaskResult, WorkerTaskTimeoutError, detectPlatform, getDefaultPoolSize, getWorkerPool, getWorkerPoolSync, isMultiThreadingSupported, newWorkerEnabledContext, newWorkerPool, newWorkerPoolContext };
