import { execFile, execFileSync } from 'node:child_process'; import { chmodSync, mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import type { ProjectPluginHost } from 'stim/plugin'; import { exactOffload } from '../offload.mjs'; import { EXACT_SIM_TARGET, localToolProblems } from '../toolchain.mjs'; let root: string; let app: string; let exact2: string; let sha: string; function git(dir: string, ...args: string[]): string { return execFileSync('git', ['-C', dir, ...args], { encoding: 'utf8', env: { ...process.env, GIT_AUTHOR_NAME: 't', GIT_AUTHOR_EMAIL: 't@t', GIT_COMMITTER_NAME: 't', GIT_COMMITTER_EMAIL: 't@t', }, }).trim(); } function script(path: string, body: string): void { writeFileSync(path, `#!/bin/sh\n${body}\n`); chmodSync(path, 0o755); } /** A host that runs programs in `at` with `env`, as Stim's host does: any exit resolves, a spawn failure rejects. */ function host(at: string, env: NodeJS.ProcessEnv = process.env): ProjectPluginHost { return { root: at, signal: new AbortController().signal, exec: (file, args, { timeoutMs, env: extra }) => new Promise((resolve, reject) => { execFile( file, [...args], { cwd: at, timeout: timeoutMs, env: { ...env, ...extra } }, (error, stdout, stderr) => { if (error && typeof error.code !== 'number') reject(error); else resolve({ code: error ? Number(error.code) : 0, stdout, stderr }); }, ); }), }; } const plan = (at: string, env: NodeJS.ProcessEnv) => exactOffload(host(at)).plan(at, env); beforeEach(() => { root = mkdtempSync(join(tmpdir(), 'stim-exact-offload-')); exact2 = join(root, 'pins', 'exact2'); mkdirSync(exact2, { recursive: true }); writeFileSync(join(exact2, 'rust-toolchain.toml'), '[toolchain]\nchannel = "1.97.0"\n'); git(exact2, 'init', '-q'); git(exact2, 'add', '.'); git(exact2, 'commit', '-q', '-m', 'pin'); sha = git(exact2, 'rev-parse', 'HEAD'); app = join(root, 'apps', 'shop-app'); mkdirSync(app, { recursive: true }); writeFileSync( join(app, 'exact.mjs'), [ '#!/bin/sh', `const EXACT2 = resolve(import.meta.dir, process.env.EXACT2 ?? "../../pins/exact2");`, 'ensureBun("1.4.2");', ].join('\n'), ); writeFileSync( join(app, 'app.json'), JSON.stringify({ env: ['API_URL', 'STORE_ID', 'REGION', 'UNSET', 'lower'], modules: ['shop-map'] }), ); writeFileSync(join(app, '.env.local'), 'API_URL=from-file\nSTORE_ID="42"\nOTHER=secret\n'); writeFileSync(join(app, '.env'), 'STORE_ID=1\nREGION=ca\n'); }); afterEach(() => { rmSync(root, { recursive: true, force: true }); }); test('an offload carries the pins, the app directory name, the declared settings in Exact order and the exact2 path', async () => { const planned = await plan(app, { API_URL: 'from-shell' }); expect(planned).toEqual({ pins: { exact2: sha, bun: '1.4.2', rust: '1.97.0', checkout: 'exact2', url: null }, payload: { env: { API_URL: 'from-shell', STORE_ID: '42', REGION: 'ca' } }, checkout: { name: 'shop-app', sibling: '../../pins/exact2' }, }); if ('unsupported' in planned) throw new Error(planned.unsupported); expect(await exactOffload(host(root)).check(planned.pins, planned.payload)).toBeNull(); }); test('an app in a subdirectory whose exact2 sits more than one folder above its repository builds here', async () => { const repo = join(root, 'deep', 'repo'); const nested = join(repo, 'sub', 'shop-app'); mkdirSync(join(repo, 'sub'), { recursive: true }); renameSync(app, nested); git(repo, 'init', '-q'); expect(await plan(nested, { EXACT2: exact2 })).toMatchObject({ unsupported: expect.stringContaining('exact2 sits 2 folders above the repository'), }); renameSync(repo, join(root, 'repo')); expect(await plan(join(root, 'repo', 'sub', 'shop-app'), { EXACT2: exact2 })).toMatchObject({ checkout: { sibling: '../../../pins/exact2' }, }); }); test('an app whose exact2 path lands on an entry a build machine keeps for itself builds here', async () => { const moved = join(root, 'src', 'exact2'); mkdirSync(join(root, 'src')); renameSync(exact2, moved); expect(await plan(app, { EXACT2: moved })).toMatchObject({ unsupported: expect.stringContaining('lands on src') }); }); test('an offload names the remote that has the exact2 commit, never one carrying credentials', async () => { git(exact2, 'remote', 'add', 'leaky', 'https://user:token@github.com/someone/exact.git'); git(exact2, 'update-ref', 'refs/remotes/leaky/main', 'HEAD'); expect(await plan(app, {})).toMatchObject({ pins: { url: null } }); git(exact2, 'remote', 'add', 'fork', 'https://github.com/someone/exact.git'); git(exact2, 'update-ref', 'refs/remotes/fork/feature', 'HEAD'); expect(await plan(app, {})).toMatchObject({ pins: { url: 'https://github.com/someone/exact.git' } }); }); test.each([ [ 'a changed exact2', () => writeFileSync(join(exact2, 'rust-toolchain.toml'), 'channel = "1.98.0"\n'), /local changes/, ], ['no exact2 there', () => rmSync(exact2, { recursive: true }), /no exact2 checkout/], ])('an app with %s builds here', async (_name, change, reason) => { change(); const planned = await plan(app, {}); expect('unsupported' in planned && planned.unsupported).toMatch(reason); }); test('EXACT2 in the environment overrides the launcher default', async () => { const moved = join(root, 'elsewhere'); execFileSync('git', ['clone', '-q', exact2, moved]); rmSync(exact2, { recursive: true }); expect(await plan(app, { EXACT2: moved })).toMatchObject({ pins: { exact2: sha } }); }); test.each(['店', '店 '])('a non-ASCII Git checkout root %j is refused', async (name) => { const checkout = join(root, name); renameSync(app, checkout); git(checkout, 'init', '-q'); expect(await plan(checkout, { EXACT2: exact2 })).toMatchObject({ unsupported: /plain ASCII file name/ }); }); test('a build machine refuses malformed Exact pins and settings, and reads an older request', async () => { const { check } = exactOffload(host(root)); const pins = { exact2: sha, bun: '1.4.2', rust: '1.97.0', checkout: 'scroll-zoom', url: 'git@github.com:someone/exact.git', }; const payload = { env: { API_URL: 'x' } }; expect(await check(pins, payload)).toBeNull(); expect(await check(pins, null)).toBeNull(); const { checkout: _checkout, url: _url, ...olderPins } = pins; expect(await check(olderPins, payload)).toBeNull(); for (const bad of [ { exact2: 'main' }, { checkout: '..' }, { url: 'https://user:token@github.com/someone/exact.git' }, ]) { expect(await check({ ...pins, ...bad }, payload)).toBe( 'An Exact build needs an iOS request with its app name, pins and settings.', ); expect(await check({ ...pins, ...bad }, null)).toBe( 'An Exact offer needs the exact2 commit and the Bun and Rust versions.', ); } for (const env of [{ 'BAD-NAME': 'x' }, { API_URL: 1 }]) expect(await check(pins, { env })).toBe( 'An Exact build needs an iOS request with its app name, pins and settings.', ); }); test("a machine reports each missing piece of Exact's toolchain with the command that installs it", async () => { const home = join(root, 'home'); const pins = { exact2: sha, bun: '1.4.2', rust: '1.97.0', checkout: 'fork', url: 'https://github.com/someone/exact.git', }; const offload = exactOffload(host(root, { ...process.env, HOME: home })); const tools = (value: Record) => offload.tools?.(value, { HOME: home }) ?? []; const bare = await tools(pins); expect(bare.map((each) => each.reason)).toEqual([ 'no Bun 1.4.2 at ~/.bun-1.4.2', 'no rustup', `no exact2 ${sha.slice(0, 10)} at ~/.exact/exact2/${sha} or ~/.exact/exact2/fork`, ]); expect(bare.every((each) => each.commands.length > 0)).toBe(true); expect(bare.at(-1)?.commands.slice(0, 2)).toEqual([ `git clone https://github.com/someone/exact.git ~/.exact/exact2/${sha}`, `git -C ~/.exact/exact2/${sha} fetch https://github.com/someone/exact.git ${sha}`, ]); mkdirSync(join(home, '.bun-1.4.2', 'bin'), { recursive: true }); script(join(home, '.bun-1.4.2', 'bin', 'bun'), 'echo 1.4.2'); mkdirSync(join(home, '.cargo', 'bin'), { recursive: true }); mkdirSync(join(home, '.cargo', 'hermes-lean-sys')); script(join(home, '.cargo', 'bin', 'rustup'), 'echo aarch64-apple-darwin'); const checkout = join(home, '.exact', 'exact2', sha); mkdirSync(join(checkout, 'scripts'), { recursive: true }); mkdirSync(join(checkout, 'node_modules')); writeFileSync(join(checkout, 'scripts', 'app-cli.mjs'), ''); expect((await tools(pins)).map((each) => each.reason)).toContain( `~/.exact/exact2/${sha} is not at commit ${sha.slice(0, 10)}`, ); expect((await tools({ ...pins, url: null })).map((each) => each.reason)).toContain( `~/.exact/exact2/${sha} is not at commit ${sha.slice(0, 10)}; the client's exact2 checkout has ${sha.slice(0, 10)} on no remote branch whose URL Stim passes on, so push it where this machine can fetch it`, ); execFileSync('git', ['clone', '-q', exact2, join(root, 'clone')]); execFileSync('mv', [join(root, 'clone', '.git'), join(checkout, '.git')]); git(checkout, 'checkout', '-q', '--', '.'); expect(await tools(pins)).toEqual([ { reason: `no Rust 1.97.0 target ${EXACT_SIM_TARGET}`, commands: [`rustup target add --toolchain 1.97.0 ${EXACT_SIM_TARGET}`], }, ]); script( join(home, '.cargo', 'bin', 'rustup'), `[ "$RUSTUP_AUTO_INSTALL" = 0 ] || exit 9; printf 'aarch64-apple-darwin\\n${EXACT_SIM_TARGET}\\n'`, ); expect(await tools(pins)).toEqual([]); renameSync(checkout, join(home, '.exact', 'exact2', 'fork')); expect(await tools(pins)).toEqual([]); const previous = process.env.HOME; process.env.HOME = home; try { expect(await offload.source?.(pins)).toEqual({ dir: join(home, '.exact', 'exact2', 'fork'), commit: sha }); } finally { process.env.HOME = previous; } }); test("doctor finds this Mac's Bun, exact2 and Rust where the app's launcher looks, at or above the pins", async () => { const home = join(root, 'home'); const path = join(root, 'path'); mkdirSync(path); const env = { HOME: home, PATH: path }; const problems = (with_: NodeJS.ProcessEnv) => localToolProblems(host(app, with_), app, with_, 20_000); expect((await problems({ ...env, EXACT2: join(root, 'missing') })).map((each) => each.reason)).toEqual([ 'no Bun 1.4.2 (exact.mjs runs ~/.bun-1.4.2/bin/bun, else bun on PATH)', expect.stringMatching(/^no exact2 checkout at .*missing \(exact.mjs reads EXACT2, else \.\.\/\.\.\/pins\/exact2\)/), 'no rustup', ]); script(join(path, 'bun'), 'echo 1.3.9'); mkdirSync(join(exact2, 'scripts')); writeFileSync(join(exact2, 'scripts', 'app-cli.mjs'), ''); mkdirSync(join(exact2, 'node_modules')); mkdirSync(join(home, '.cargo', 'hermes-lean-sys'), { recursive: true }); script(join(path, 'rustup'), '[ "$RUSTUP_AUTO_INSTALL" = 0 ] || exit 9; echo aarch64-apple-darwin'); expect(await problems(env)).toEqual([ { reason: `Bun 1.3.9 at ${join(path, 'bun')} is older than the 1.4.2 exact.mjs pins`, commands: ['curl -fsSL https://bun.sh/install | BUN_INSTALL="$HOME/.bun-1.4.2" bash -s "bun-v1.4.2"'], }, { reason: `no Rust 1.97.0 target ${EXACT_SIM_TARGET}`, commands: [`rustup target add --toolchain 1.97.0 ${EXACT_SIM_TARGET}`], }, ]); script(join(path, 'bun'), 'echo 1.5.0'); writeFileSync(join(app, 'rust-toolchain.toml'), '[toolchain]\nchannel = "1.98.0"\n'); script( join(path, 'rustup'), `[ "$RUSTUP_AUTO_INSTALL" = 0 ] || exit 9; [ "$5" = 1.98.0 ] && printf '${EXACT_SIM_TARGET}\\n'`, ); expect(await problems(env)).toEqual([]); const creator = join(root, "creator's bun"); writeFileSync( join(app, 'exact.mjs'), [ `':' //; if [ -n "$BUN" ]; then exec "$BUN" "$0" "$@"; else exec '${creator.replaceAll("'", "'\\''")}' "$0" "$@"; fi`, `const EXACT2 = resolve(import.meta.dir, process.env.EXACT2 ?? "../../pins/exact2");`, 'ensureBun("1.4.2");', ].join('\n'), ); expect((await problems(env)).map((each) => each.reason)).toEqual([ `no Bun 1.4.2 (exact.mjs runs ~/.bun-1.4.2/bin/bun, else ${creator})`, ]); script(creator, 'echo 1.4.2'); expect(await problems(env)).toEqual([]); });