import { existsSync } from 'fs';
import { copyFile, mkdir, writeFile } from 'fs/promises';
import { basename, dirname, join } from 'path';
function resolvePackageDir(tracePaths) {
    const rootHtmlPath = tracePaths[0];
    if (!rootHtmlPath) {
        throw new Error('No trace exports to package');
    }
    const outputDir = dirname(rootHtmlPath);
    const rootBase = basename(rootHtmlPath, '.html');
    const basePackageDir = join(outputDir, `${rootBase}-trace-export`);
    if (!existsSync(basePackageDir))
        return basePackageDir;
    let suffix = 2;
    while (existsSync(`${basePackageDir}-${suffix}`)) {
        suffix++;
    }
    return `${basePackageDir}-${suffix}`;
}
export async function packageTraceExports(tracePaths) {
    if (tracePaths.length === 0) {
        throw new Error('No trace exports to package');
    }
    const packageDir = resolvePackageDir(tracePaths);
    const htmlFiles = tracePaths.map((tracePath) => basename(tracePath));
    await mkdir(packageDir, { recursive: true });
    for (const tracePath of tracePaths) {
        await copyFile(tracePath, join(packageDir, basename(tracePath)));
    }
    await writeFile(join(packageDir, 'manifest.json'), JSON.stringify({
        rootHtmlFile: htmlFiles[0],
        htmlFiles
    }, null, 2), 'utf8');
    return packageDir;
}
//# sourceMappingURL=trace-package.js.map