import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { rm } from 'node:fs/promises';
import { buildCodebaseIndex, CodeIndexBudgetExceededError } from './build.js';
import { writeSectionedCodeIndex } from './index-io.js';
import { slimifyIndex } from './slim.js';
function send(msg) {
    process.send?.(msg);
}
let abortController;
process.on('message', async (msg) => {
    if (msg.type === 'abort') {
        abortController?.abort();
        return;
    }
    if (msg.type !== 'start')
        return;
    let resultPath;
    try {
        abortController = new AbortController();
        const index = await buildCodebaseIndex(msg.options, (event) => {
            send({ type: 'progress', event });
        }, abortController.signal);
        const exportIndex = msg.slim ? slimifyIndex(index) : index;
        resultPath = join(tmpdir(), `occ-code-index-${process.pid}-${Date.now()}`);
        await writeSectionedCodeIndex(resultPath, exportIndex, {}, abortController.signal);
        send({ type: 'complete', resultPath });
    }
    catch (err) {
        const error = err instanceof Error ? err : new Error(String(err));
        // Remove any partially written artifact so an aborted/failed build leaves
        // nothing behind for the parent to clean.
        if (resultPath) {
            await rm(resultPath, { recursive: true, force: true }).catch(() => undefined);
        }
        if (error.name === 'AbortError') {
            send({ type: 'aborted' });
        }
        else {
            const code = error.code;
            send({
                type: 'error',
                message: error.message,
                name: error.name,
                code: typeof code === 'string' ? code : undefined,
                budget: error instanceof CodeIndexBudgetExceededError ? error.budget : undefined,
            });
        }
    }
    process.disconnect?.();
});
//# sourceMappingURL=isolated-runner.js.map