import { openTreecrdtDb } from './open.js';
import { CommonWorkerSession, createCommonWorkerRpcHandlers, openedToRpcInitResult, } from './common-worker.js';
const session = new CommonWorkerSession();
const coreHandlers = createCommonWorkerRpcHandlers(session);
function postMaterialized(event) {
    self.postMessage({ type: 'materialized', event });
}
async function init(baseUrl, filename, storageParam, docId) {
    await session.closeDbAndReset();
    const opened = await openTreecrdtDb({
        baseUrl,
        filename,
        storage: storageParam,
        docId,
        requireOpfs: false,
        onMaterialized: postMaterialized,
    });
    session.applyOpened(opened);
    return openedToRpcInitResult(opened);
}
async function close() {
    await session.closeDbAndReset();
    return null;
}
const methods = {
    init,
    ...coreHandlers,
    close,
    drop: () => session.drop(),
};
self.onmessage = async (ev) => {
    const { id, method, params } = ev.data;
    const respond = (ok, result, error) => {
        self.postMessage({ id, ok, result, error });
    };
    try {
        const methodFn = methods[method];
        if (!methodFn) {
            respond(false, null, `unknown method: ${method}`);
            return;
        }
        const result = await methodFn(...(params ?? []));
        respond(true, result);
    }
    catch (err) {
        respond(false, null, err instanceof Error ? err.message : String(err));
    }
};
