#!/usr/bin/env node // Builds a single-file executable (Node.js SEA) that needs no Node.js on the target machine. // node scripts/build-exe.mjs win-x64 (also: darwin-arm64, darwin-x64, linux-x64) // The official Node.js binary for the target is downloaded from nodejs.org once (SHA-256 verified) // and cached in build/cache. Its version must match the Node.js running this script. import { build } from 'esbuild'; import { execFileSync } from 'node:child_process'; import { createHash } from 'node:crypto'; import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync, statSync, rmSync, copyFileSync } from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); const BUILD = path.join(ROOT, 'build'); const CACHE = path.join(BUILD, 'cache'); const DIST = path.join(ROOT, 'dist'); const VERSION = process.versions.node; const target = process.argv[2] || 'win-x64'; const TARGETS = { 'win-x64': { archive: `node-v${VERSION}-win-x64.zip`, inner: `node-v${VERSION}-win-x64/node.exe`, exe: 'srt-translator.exe' }, 'darwin-arm64': { archive: `node-v${VERSION}-darwin-arm64.tar.xz`, inner: `node-v${VERSION}-darwin-arm64/bin/node`, exe: 'srt-translator' }, 'darwin-x64': { archive: `node-v${VERSION}-darwin-x64.tar.xz`, inner: `node-v${VERSION}-darwin-x64/bin/node`, exe: 'srt-translator' }, 'linux-x64': { archive: `node-v${VERSION}-linux-x64.tar.xz`, inner: `node-v${VERSION}-linux-x64/bin/node`, exe: 'srt-translator' }, }; const t = TARGETS[target]; if (!t) throw new Error(`Unknown target ${target}. Use one of: ${Object.keys(TARGETS).join(', ')}`); const log = (m) => console.log(`[build] ${m}`); mkdirSync(CACHE, { recursive: true }); mkdirSync(DIST, { recursive: true }); // 1) Bundle the server and all modules (incl. @lmstudio/sdk) into one CommonJS file. const bundle = path.join(BUILD, 'app.cjs'); await build({ entryPoints: [path.join(ROOT, 'server.js')], bundle: true, platform: 'node', format: 'cjs', target: `node${VERSION.split('.')[0]}`, outfile: bundle, external: ['bufferutil', 'utf-8-validate'], // optional native add-ons of `ws` logLevel: 'warning', logOverride: { 'empty-import-meta': 'silent' }, // handled in server.js legalComments: 'none', }); log(`bundle: ${path.relative(ROOT, bundle)} (${(statSync(bundle).size / 1024).toFixed(0)} KB)`); // 2) Official Node.js binaries (cached, checksum-verified): one to inject into (target) and one // to run the build if this Node has SEA disabled (Homebrew builds do). const base = `https://nodejs.org/dist/v${VERSION}`; const sumsPath = path.join(CACHE, `SHASUMS256-v${VERSION}.txt`); async function download(url, dest) { log(`downloading ${url}`); const res = await fetch(url); if (!res.ok) throw new Error(`${url}: HTTP ${res.status}`); writeFileSync(dest, Buffer.from(await res.arrayBuffer())); } async function ensureNode(name) { const spec = TARGETS[name]; if (!spec) throw new Error(`No official Node.js build known for ${name}`); if (!existsSync(sumsPath)) { const legacy = path.join(CACHE, 'SHASUMS256.txt'); if (existsSync(legacy) && readFileSync(legacy, 'utf8').includes(`v${VERSION}`)) copyFileSync(legacy, sumsPath); else await download(`${base}/SHASUMS256.txt`, sumsPath); } const archivePath = path.join(CACHE, spec.archive); if (!existsSync(archivePath)) await download(`${base}/${spec.archive}`, archivePath); const expected = readFileSync(sumsPath, 'utf8').split('\n').find((l) => l.endsWith(` ${spec.archive}`))?.split(/\s+/)[0]; const actual = createHash('sha256').update(readFileSync(archivePath)).digest('hex'); if (!expected || expected !== actual) throw new Error(`Checksum mismatch for ${spec.archive}: expected ${expected}, got ${actual}`); const dir = path.join(CACHE, `node-${VERSION}-${name}`); const bin = path.join(dir, spec.inner); if (!existsSync(bin)) { mkdirSync(dir, { recursive: true }); execFileSync('tar', ['-xf', archivePath, '-C', dir, spec.inner], { stdio: 'inherit' }); // bsdtar also reads .zip } log(`node ${VERSION} for ${name}: checksum OK`); return bin; } const nodeBin = await ensureNode(target); function seaEnabled(bin) { try { execFileSync(bin, ['--experimental-sea-config', path.join(BUILD, 'nonexistent.json')], { stdio: 'pipe' }); } catch (e) { return !/Single executable application is disabled/.test(String(e.stderr) + String(e.stdout)); } return true; } let builder = process.execPath; if (!seaEnabled(builder)) { const host = `${process.platform === 'win32' ? 'win' : process.platform}-${process.arch}`; log(`this Node has SEA disabled (${builder}) — using the official Node.js for ${host} to build`); builder = await ensureNode(host); } // 3) Single executable: bundle + UI files as assets, injected into the target's node binary. const assets = Object.fromEntries(readdirSync(path.join(ROOT, 'public')).map((f) => [f, path.join(ROOT, 'public', f)])); const outDir = path.join(DIST, target); rmSync(outDir, { recursive: true, force: true }); mkdirSync(outDir, { recursive: true }); const output = path.join(outDir, t.exe); const seaConfig = path.join(BUILD, `sea-config-${target}.json`); writeFileSync(seaConfig, JSON.stringify({ main: bundle, mainFormat: 'commonjs', executable: nodeBin, output, disableExperimentalSEAWarning: true, useSnapshot: false, // must be off for cross-platform builds useCodeCache: false, assets, }, null, 2)); execFileSync(builder, ['--build-sea', seaConfig], { stdio: 'inherit' }); if (target.startsWith('darwin') && process.platform === 'darwin') execFileSync('codesign', ['--sign', '-', '--force', output], { stdio: 'inherit' }); log(`executable: ${path.relative(ROOT, output)} (${(statSync(output).size / 2 ** 20).toFixed(1)} MB)`); // 4) Short instructions for whoever gets the file, then a zip to send around. const howto = path.join(outDir, 'JAK-URUCHOMIC.txt'); writeFileSync(howto, readFileSync(path.join(ROOT, 'scripts', 'JAK-URUCHOMIC.txt'), 'utf8').replace(/\n/g, target.startsWith('win') ? '\r\n' : '\n')); const zip = path.join(DIST, `srt-translator-${target}.zip`); rmSync(zip, { force: true }); execFileSync('zip', ['-j', '-q', '-9', zip, output, howto]); log(`zip: ${path.relative(ROOT, zip)} (${(statSync(zip).size / 2 ** 20).toFixed(1)} MB)`);