#!/usr/bin/env node
import { resolve } from "node:path";
import { pathToFileURL } from "node:url";
const tool = process.argv[2];
const distDir = process.argv[3];
const args = process.argv.slice(4);
if ((tool !== "ffmpeg" && tool !== "ffprobe") || !distDir) {
    process.stderr.write("usage: run-generated <ffmpeg|ffprobe> <dist-dir> [...args]\n");
    process.exit(64);
}
let exitCode = 0;
let resolveExit;
const exited = new Promise((resolvePromise) => {
    resolveExit = resolvePromise;
});
try {
    const jsPath = resolve(distDir, `${tool}.js`);
    const imported = await import(pathToFileURL(jsPath).href);
    const createModule = getDefaultFactory(imported);
    if (!createModule) {
        throw new Error(`Invalid Emscripten module: ${jsPath}`);
    }
    const module = createModule({
        arguments: args,
        thisProgram: tool,
        locateFile: (name) => resolve(distDir, name),
        print: (line) => process.stdout.write(`${line}\n`),
        printErr: (line) => process.stderr.write(`${line}\n`),
        onExit: (code) => {
            exitCode = code;
            resolveExit();
        },
    });
    await Promise.race([
        exited,
        module.then(() => new Promise(() => { }), (error) => {
            if (isExitStatus(error)) {
                exitCode =
                    typeof error.status === "number" ? error.status : (parseExitStatus(error) ?? exitCode);
                resolveExit();
                return new Promise(() => { });
            }
            throw error;
        }),
    ]);
    process.exit(exitCode);
}
catch (error) {
    process.stderr.write(`${formatError(error)}\n`);
    process.exit(1);
}
function getDefaultFactory(value) {
    if (value === null || value === undefined || typeof value !== "object" || !("default" in value)) {
        return undefined;
    }
    const maybeFactory = Reflect.get(value, "default");
    return typeof maybeFactory === "function" ? maybeFactory : undefined;
}
function isExitStatus(error) {
    const text = formatError(error);
    return ((typeof error === "object" &&
        error !== null &&
        "name" in error &&
        error.name === "ExitStatus") ||
        text.startsWith("Program terminated with exit("));
}
function parseExitStatus(error) {
    const match = /exit\((?<status>\d+)\)/u.exec(formatError(error));
    const status = match?.groups?.status;
    return status === undefined ? undefined : Number(status);
}
function formatError(error) {
    if (error instanceof Error)
        return error.stack ?? error.message;
    if (typeof error === "string")
        return error;
    return JSON.stringify(error);
}
//# sourceMappingURL=run-generated.js.map