import { createInMemoryDatabase, importDatabase, contentFromDatabase, } from "../database/sqlite/index.js";
import { boot } from "../engine/boot.js";
/**
 * In-process, in-memory environment.
 *
 * Runs on the calling thread; great for tests, CLI, or light usage. In
 * browsers, heavy operations can block the UI – prefer the Worker environment for
 * production use.
 */
export class InMemoryEnvironment {
    sqlite;
    engine;
    async open(opts) {
        if (!this.sqlite) {
            this.sqlite = await createInMemoryDatabase({ readOnly: false });
        }
        if (!this.engine) {
            const engine = await boot({
                sqlite: this.sqlite,
                emit: (ev) => opts.emit(ev),
                args: opts.boot.args,
            });
            this.engine = engine;
        }
        return { engine: this.engine };
    }
    async create(opts) {
        this.sqlite = await createInMemoryDatabase({ readOnly: false });
        importDatabase({ db: this.sqlite, content: new Uint8Array(opts.blob) });
        this.engine = undefined;
    }
    async export() {
        if (!this.sqlite)
            throw new Error("Engine not initialized");
        const bytes = contentFromDatabase(this.sqlite);
        const copy = bytes.slice();
        return copy.buffer;
    }
    async close() {
        if (this.sqlite) {
            this.sqlite.close();
            this.sqlite = undefined;
        }
        this.engine = undefined;
    }
    async exists() {
        return false;
    }
    async call(name, args) {
        if (!this.engine)
            throw new Error("Environment not initialized");
        return this.engine.call(name, args);
    }
}
//# sourceMappingURL=in-memory.js.map