import { execFileSync } from 'node:child_process';
import { readFileSync } from 'node:fs';
import path from 'node:path';
import esbuild from 'esbuild';
import { writeFile } from 'node:fs/promises';
const pkgDir = path.resolve(import.meta.dirname, '..');
const distDir = path.join(pkgDir, 'dist');
const pkgJsonPath = path.join(pkgDir, 'package.json');
const pkg = JSON.parse(readFileSync(pkgJsonPath, 'utf8'));
const version = pkg.version;
execFileSync('npx', ['tsc', '-p', pkgDir], { stdio: 'inherit' });
const banner = `/** @generated by scripts/build.mjs */\n/** @mcp-exec version: ${version} */\n`;
// Simple, deterministic injection without relying on bundler constant folding.
// Replace any placeholder occurrences in the emitted JS.
const distIndexPath = path.join(distDir, 'index.js');
const distIndex = readFileSync(distIndexPath, 'utf8');
const withoutShebang = distIndex.replace(/^#!.*\n/, '');
const replaced = withoutShebang.replaceAll('__MCP_EXEC_VERSION__', version);
await writeFile(distIndexPath, banner + replaced);
await esbuild.build({
entryPoints: [path.join(distDir, 'index.js')],
outfile: path.join(distDir, 'index.js'),
allowOverwrite: true,
bundle: true,
platform: 'node',
format: 'esm',
sourcemap: false,
packages: 'external',
minify: false,
keepNames: true,
logLevel: 'info',
define: {
'__MCP_EXEC_VERSION__': JSON.stringify(version),
},
});