import type { BindParams, Database, QueryExecResult } from "sql.js"; import { RpcProvider } from "worker-rpc"; import DbWorker from "./db.worker?worker"; import { dbStatusAtom, jotaiStore } from "../../src/globals"; import { DbStatusCode } from "./constants"; const worker = new DbWorker(); const rpcProvider = new RpcProvider((message, transfer) => worker.postMessage(message, transfer), ); worker.onmessage = (e) => rpcProvider.dispatch(e.data); rpcProvider.registerSignalHandler("db", ({ status }) => { jotaiStore.set(dbStatusAtom, (prevState) => ({ ...prevState, status })); }); interface AsyncDatabase { exec(sql: string, params?: BindParams): Promise; run(sql: string, params?: BindParams): Promise; rpc(cmd: string, args: any): Promise; } export let dbClient: AsyncDatabase; export async function getDbClient() { await new Promise((resolve) => { rpcProvider.registerSignalHandler(DbStatusCode.READY, () => { resolve(); }); }); dbClient = { async run(s: string, p?: BindParams): Promise { return await rpcProvider.rpc("run", { s, p }); }, async exec(s: string, p?: BindParams): Promise { return await rpcProvider.rpc("exec", { s, p }); }, async rpc(cmd, args): Promise { return await rpcProvider.rpc(cmd, args); }, }; console.log("done :3"); }