simcast-host 0.0.0-stage → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,61 @@
1
+ // Small probes of the Mac's toolchain, shared by /info, status and the checks.
2
+ // Each answers null when the tool is missing or fails.
3
+ import os from 'node:os';
4
+ import { run } from './exec.js';
5
+
6
+ // Trimmed stdout of a command that exits 0, else null.
7
+ export async function probe(cmd, args = []) {
8
+ try {
9
+ const r = await run(cmd, args, { capture: true });
10
+ return r.code === 0 ? r.stdout.toString().trim() : null;
11
+ } catch {
12
+ return null;
13
+ }
14
+ }
15
+
16
+ // "Xcode 26.0" (the first line of xcodebuild -version).
17
+ export async function xcodeVersion() {
18
+ return (await probe('xcodebuild', ['-version']))?.split('\n')[0] || null;
19
+ }
20
+
21
+ // e.g. /Applications/Xcode.app/Contents/Developer
22
+ export function developerDir() {
23
+ return probe('xcode-select', ['-p']);
24
+ }
25
+
26
+ // Free space on the volume holding the home folder, in whole GB (1e9 bytes).
27
+ export async function freeDiskGB() {
28
+ const df = await probe('df', ['-k', os.homedir()]);
29
+ const availKb = df ? Number(df.split('\n')[1]?.trim().split(/\s+/)[3]) : NaN;
30
+ return Number.isFinite(availKb) ? Math.round(availKb / 1e6) : null;
31
+ }
32
+
33
+ // e.g. "15.5"
34
+ export function macosVersion() {
35
+ return probe('sw_vers', ['-productVersion']);
36
+ }
37
+
38
+ // The Mac's name for pairing and Bonjour: `scutil --get ComputerName`, else
39
+ // os.hostname() without ".local".
40
+ export async function computerName() {
41
+ return (await probe('scutil', ['--get', 'ComputerName'])) || os.hostname().replace(/\.local$/i, '');
42
+ }
43
+
44
+ // Wake-on-LAN details of the interface a request came in on: the interface in
45
+ // os.networkInterfaces() whose IPv4 address equals `localAddress`
46
+ // (req.socket.localAddress; an IPv4-mapped "::ffff:" prefix is removed):
47
+ // { mac, interface, address, netmask }, else null (an IPv6 or loopback address,
48
+ // no such interface, or one without a hardware address).
49
+ export function wakeInfo(localAddress, interfaces = os.networkInterfaces()) {
50
+ const address = String(localAddress || '').replace(/^::ffff:/i, '');
51
+ if (!/^\d{1,3}(\.\d{1,3}){3}$/.test(address)) return null;
52
+ for (const [name, addrs] of Object.entries(interfaces || {})) {
53
+ for (const a of addrs || []) {
54
+ const v4 = a.family === 'IPv4' || a.family === 4;
55
+ if (!v4 || a.internal || a.address !== address) continue;
56
+ if (!a.mac || /^(00:){5}00$/.test(a.mac)) return null;
57
+ return { mac: a.mac.toLowerCase(), interface: name, address, netmask: a.netmask || null };
58
+ }
59
+ }
60
+ return null;
61
+ }
@@ -0,0 +1,123 @@
1
+ // The pairing window (docs/protocol.md, "Pairing by code"), in memory:
2
+ // { codeHash, expiresAt, attemptsLeft, closedBecause, pairedPC }.
3
+ // - The code: crypto.randomInt(0, 1e6), zero-padded, compared in constant time
4
+ // (only its hash is kept).
5
+ // - 2 minutes (SIMCAST_PAIRING_MS overrides it for tests), 3 tries, single use.
6
+ // - A wrong code: 403 { code: "wrong-code", attemptsLeft }; the third closes the
7
+ // window: 403 { code: "pairing-locked" }. No window: 403 { code: "pairing-closed" }.
8
+ // - A right code while another PC is connected and !force: 409 { code: "in-use", by },
9
+ // and the code is not used up and no try is counted.
10
+ // - Two PCs racing with the same code: the first wins, the second gets
11
+ // pairing-closed (tryCode is synchronous, so one runs to the end first).
12
+ import crypto from 'node:crypto';
13
+ import * as clients from './clients.js';
14
+ import { HttpError } from './clients.js';
15
+
16
+ export const DEFAULT_SECONDS = 120;
17
+ export const MAX_SECONDS = 600;
18
+ export const ATTEMPTS = 3;
19
+
20
+ const CLOSED = 'Pairing isn\'t open on the Mac. Run simcast-host pair on the Mac.';
21
+ const LOCKED = 'Too many wrong codes, so the Mac closed pairing. Run simcast-host pair on the Mac for a new code.';
22
+ const log = (msg) => console.log(`[${new Date().toISOString()}] pairing: ${msg}`);
23
+
24
+ const hashCode = (code) => crypto.createHash('sha256').update(String(code)).digest();
25
+
26
+ let win = null; // { codeHash, expiresAt (ms), attemptsLeft, closedBecause, pairedPC }
27
+
28
+ // How long a window lasts, in ms.
29
+ function durationMs(seconds) {
30
+ const fromEnv = Number(process.env.SIMCAST_PAIRING_MS);
31
+ if (Number.isFinite(fromEnv) && fromEnv > 0) return fromEnv;
32
+ const s = Number(seconds);
33
+ return Math.round((Number.isFinite(s) && s > 0 ? Math.min(s, MAX_SECONDS) : DEFAULT_SECONDS) * 1000);
34
+ }
35
+
36
+ // Marks an open window whose time ran out as expired.
37
+ function expireIfDue() {
38
+ if (win && !win.closedBecause && Date.now() >= win.expiresAt) {
39
+ win.closedBecause = 'expired';
40
+ win.codeHash = null;
41
+ log('the code expired');
42
+ }
43
+ }
44
+
45
+ const isOpen = () => {
46
+ expireIfDue();
47
+ return Boolean(win && !win.closedBecause);
48
+ };
49
+
50
+ function close(why, pc = null) {
51
+ if (!win) return;
52
+ win.closedBecause = why;
53
+ win.codeHash = null;
54
+ win.pairedPC = pc;
55
+ }
56
+
57
+ // Opens a window (replacing any open one): { code, expiresAt, attemptsLeft }.
58
+ export function open(seconds = DEFAULT_SECONDS) {
59
+ const code = String(crypto.randomInt(0, 1e6)).padStart(6, '0');
60
+ const expiresAt = Date.now() + durationMs(seconds);
61
+ win = { codeHash: hashCode(code), expiresAt, attemptsLeft: ATTEMPTS, closedBecause: null, pairedPC: null };
62
+ log(`a pairing window is open until ${new Date(expiresAt).toISOString()}`);
63
+ return { code, expiresAt: new Date(expiresAt).toISOString(), attemptsLeft: ATTEMPTS };
64
+ }
65
+
66
+ // { open, expiresAt, attemptsLeft, closedBecause: "paired" | "expired" | "locked" | "cancelled" | null,
67
+ // pairedPC: { id, name } | null }
68
+ export function status() {
69
+ const isNowOpen = isOpen();
70
+ if (!win) return { open: false, expiresAt: null, attemptsLeft: 0, closedBecause: null, pairedPC: null };
71
+ return {
72
+ open: isNowOpen,
73
+ expiresAt: new Date(win.expiresAt).toISOString(),
74
+ attemptsLeft: isNowOpen ? win.attemptsLeft : 0,
75
+ closedBecause: win.closedBecause,
76
+ pairedPC: win.pairedPC,
77
+ };
78
+ }
79
+
80
+ // Closes the window (closedBecause: "cancelled"). True when one was open.
81
+ export function cancel() {
82
+ if (!isOpen()) return false;
83
+ close('cancelled');
84
+ log('pairing was cancelled on the Mac');
85
+ return true;
86
+ }
87
+
88
+ // POST /pair/code: checks `code` (spaces and dashes stripped) for `client`
89
+ // ({ id, name }). On success uses the code up, closes the window, makes the PC
90
+ // the active one with a new own token and returns { token, issuedAt, previous }.
91
+ // Otherwise throws an HttpError with `status` and `code` (see the top of this file).
92
+ export function tryCode(client, code, force = false) {
93
+ if (!isOpen()) throw new HttpError(403, CLOSED, { code: 'pairing-closed' });
94
+ const given = String(code ?? '').replace(/[\s-]/g, '');
95
+ const right = /^\d{6}$/.test(given) && crypto.timingSafeEqual(hashCode(given), win.codeHash);
96
+ if (!right) {
97
+ win.attemptsLeft -= 1;
98
+ if (win.attemptsLeft <= 0) {
99
+ close('locked');
100
+ log(`${client.name} sent a wrong code; pairing is closed after ${ATTEMPTS} wrong codes`);
101
+ throw new HttpError(403, LOCKED, { code: 'pairing-locked' });
102
+ }
103
+ log(`${client.name} sent a wrong code (${win.attemptsLeft} tries left)`);
104
+ const left = win.attemptsLeft;
105
+ throw new HttpError(403, `That code is wrong. ${left} ${left === 1 ? 'try' : 'tries'} left.`, { code: 'wrong-code', attemptsLeft: left });
106
+ }
107
+ // The right code. Refusals from here on leave the window as it is.
108
+ if (!clients.canPair(client.id)) {
109
+ throw new HttpError(403, `This Mac already has ${clients.MAX_PCS} paired PCs. Unpair one on the Mac first: simcast-host pcs, then simcast-host unpair <name>.`, { code: 'too-many-pcs' });
110
+ }
111
+ const by = clients.inUseBy(client.id);
112
+ if (by && !force) {
113
+ throw new HttpError(409, `This Mac is in use by ${by} right now. Pair again with --force to take it over.`, { code: 'in-use', by });
114
+ }
115
+ close('paired', { id: client.id, name: client.name });
116
+ log(`${client.name} paired with the code`);
117
+ return clients.pairWithCode(client);
118
+ }
119
+
120
+ // For tests: forget the window.
121
+ export function reset() {
122
+ win = null;
123
+ }
@@ -0,0 +1,23 @@
1
+ import os from 'node:os';
2
+ import path from 'node:path';
3
+ import { agentHome } from './state.js';
4
+
5
+ // Read once at import, like agentHome: tests set the env before importing.
6
+ const home = os.homedir();
7
+
8
+ export const LOG_FILE = process.env.SIMCAST_LOG_FILE || path.join(home, 'Library', 'Logs', 'simcast-host.log');
9
+ export const STATUS_FILE = path.join(agentHome, 'agent-status.json');
10
+ // Tools setup installs without Homebrew (idb_companion). On the agent's PATH
11
+ // through agent.json extraPath (addExtraPath in checks.js).
12
+ export const HOST_BIN = path.join(agentHome, 'bin');
13
+ export const LAUNCH_AGENTS_DIR = path.join(home, 'Library', 'LaunchAgents');
14
+ // The agent's LaunchAgent, written by setup/install.
15
+ export const AGENT_LABEL = 'com.simcast.host';
16
+
17
+ // 501 is the first user account on a Mac; only matters off macOS (tests).
18
+ export const uid = () => process.getuid?.() ?? 501;
19
+
20
+ export const isMac = () => process.platform === 'darwin' || Boolean(process.env.SIMCAST_FAKE_TOOLS);
21
+
22
+ // The name a running host gives in /health.
23
+ export const HOST_NAMES = ['simcast-host'];
@@ -0,0 +1,119 @@
1
+ // Expo (dev builds with expo-dev-client). The reference recipe.
2
+ import fs from 'node:fs';
3
+ import { createRequire } from 'node:module';
4
+ import path from 'node:path';
5
+ import { LOCKFILES } from '../../common.js';
6
+ import * as tunnelModule from '../tunnel.js';
7
+ import * as kit from './kit.js';
8
+
9
+ export const id = 'expo';
10
+ export const name = 'Expo';
11
+
12
+ export function detect(src) {
13
+ return kit.packageDeps(src).has('expo');
14
+ }
15
+
16
+ export const deps = kit.installJsDeps;
17
+
18
+ // Hash of everything that affects the native binary. Uses Expo's own
19
+ // @expo/fingerprint from the project when available.
20
+ export async function fingerprint({ src, options: { cng } }) {
21
+ try {
22
+ const req = createRequire(path.join(src, 'package.json'));
23
+ const mod = req('@expo/fingerprint');
24
+ const create = mod.createFingerprintAsync || mod.default?.createFingerprintAsync;
25
+ const opts = { platforms: ['ios'] };
26
+ // In prebuild mode, ios/ is generated on the Mac and must not change the hash.
27
+ if (cng) opts.ignorePaths = ['ios/**', 'android/**'];
28
+ const result = await create(src, opts);
29
+ if (result?.hash) return { hash: result.hash, source: '@expo/fingerprint' };
30
+ } catch {
31
+ // fall through to the simple fingerprint
32
+ }
33
+ const hash = kit.hashPaths(src, {
34
+ files: [
35
+ 'package.json', ...LOCKFILES.map(([f]) => f), 'app.json', 'app.config.js',
36
+ 'app.config.ts', 'app.config.mjs', 'app.config.cjs', 'eas.json',
37
+ ],
38
+ dirs: ['plugins', ...(cng ? [] : ['ios'])],
39
+ });
40
+ return { hash, source: 'fallback' };
41
+ }
42
+
43
+ export async function build({ src, derived, options: { cng, clean }, onLine, step }) {
44
+ const ios = path.join(src, 'ios');
45
+ if (cng) {
46
+ step('Running expo prebuild');
47
+ const args = ['expo', 'prebuild', '--platform', 'ios', '--no-install'];
48
+ if (clean) args.push('--clean');
49
+ await kit.runOk('npx', args, { cwd: src, env: kit.agentEnv({ CI: '1' }), onLine });
50
+ } else if (!fs.existsSync(ios)) {
51
+ throw new Error('This project has no ios/ folder. Remove it from .gitignore rules or let simcast run prebuild.');
52
+ }
53
+
54
+ step('Installing CocoaPods');
55
+ await kit.podInstall(ios, { onLine });
56
+
57
+ const { workspace, scheme } = kit.findWorkspace(ios);
58
+ step(`Compiling with xcodebuild (scheme ${scheme})`);
59
+ return kit.xcodebuild({
60
+ src, workspace, scheme, derived, clean, onLine,
61
+ // Don't bundle JS into the app and don't start a Metro on the Mac:
62
+ // the app loads JS from Metro on the Windows PC.
63
+ env: { SKIP_BUNDLING: '1', RCT_NO_LAUNCH_PACKAGER: '1' },
64
+ });
65
+ }
66
+
67
+ // How long the dev client gets between "simctl launch" and the openurl. Opening
68
+ // the URL tears down the JS runtime the launch started; doing it while that
69
+ // runtime is still starting shows a red "[runtime not ready]: React Native Runtime
70
+ // is shutting down" toast for a few seconds (seen on iOS 27). A guess, not
71
+ // measured: it should outlast the launcher's start-up on a normal Mac.
72
+ export const LAUNCH_SETTLE_MS = 1500;
73
+
74
+ // The warning when the agent's own Metro check fails, worded for how the PC
75
+ // reaches the Mac (docs/protocol.md, "Tunnel mode"):
76
+ // tunnel up a loopback URL whose port the PC's tunnel listens on
77
+ // no tunnel http://localhost:<p> with no tunnel listening on p
78
+ // direct anything else: the PC's own address (0.6 and --direct)
79
+ export function metroWarning(devServerUrl, error, tunnel) {
80
+ const url = URL.canParse(devServerUrl) ? new URL(devServerUrl) : null;
81
+ const port = url ? url.port || (url.protocol === 'https:' ? '443' : '80') : '8081';
82
+ const host = url?.hostname.replace(/^\[|\]$/g, '').toLowerCase();
83
+ const loopback = ['localhost', '127.0.0.1', '::1'].includes(host);
84
+ if (loopback && tunnel?.listening(Number(port))) {
85
+ return `Metro on the PC didn't answer through the tunnel (${error}). Is "npx expo start" running on the PC?`;
86
+ }
87
+ if (host === 'localhost') {
88
+ return `No tunnel from the PC for port ${port}. Run simcast run ios again, or simcast tunnel to check it.`;
89
+ }
90
+ // EHOSTUNREACH is macOS's Local Network privacy blocking this agent (the
91
+ // simulator's apps may still get through); Windows Firewall times out instead.
92
+ return String(error).includes('EHOSTUNREACH')
93
+ ? `The Mac can't reach Metro at ${devServerUrl} (${error}): macOS keeps the agent off your network. On the Mac, turn on node in System Settings › Privacy & Security › Local Network, then run: simcast-host install`
94
+ : `The Mac can't reach Metro at ${devServerUrl} (${error}). Is "npx expo start" running, and is port ${port} allowed through your computer's firewall?`;
95
+ }
96
+
97
+ // ctx.tunnel ({ listening(port) }) comes from the agent; tunnel.js itself when
98
+ // the caller leaves it out.
99
+ export async function launch({ options: { devServerUrl }, sim, info, warn, tunnel = tunnelModule }, { udid, meta }) {
100
+ if (devServerUrl) {
101
+ const metro = await kit.metroRunning(devServerUrl);
102
+ if (!metro.ok) warn(metroWarning(devServerUrl, metro.error, tunnel));
103
+ }
104
+ // expo-dev-client registers an "exp+<slug>" scheme.
105
+ const devClientScheme = meta.urlSchemes.find((s) => s.startsWith('exp+'));
106
+ if (devClientScheme && devServerUrl) {
107
+ const url = `${devClientScheme}://expo-development-client/?url=${encodeURIComponent(devServerUrl)}`;
108
+ // Approved first, or iOS asks "Open in <app>?" the first time and nothing
109
+ // happens until someone taps Open. A failure only means it may ask.
110
+ await sim.approveScheme(udid, devClientScheme, meta.bundleId);
111
+ await sim.launch(udid, meta.bundleId);
112
+ await new Promise((resolve) => setTimeout(resolve, LAUNCH_SETTLE_MS));
113
+ await sim.openUrl(udid, url);
114
+ info(`Opened ${url}`);
115
+ } else {
116
+ await sim.launch(udid, meta.bundleId);
117
+ if (!devClientScheme) warn('expo-dev-client was not detected, so the app was launched without a Metro URL.');
118
+ }
119
+ }
@@ -0,0 +1,66 @@
1
+ // Recipes: one file per framework, telling the agent how to install, build and
2
+ // launch that kind of project. Everything else (sync, the build cache, the
3
+ // simulator, installing the .app, logs) is shared and lives outside recipes.
4
+ //
5
+ // A recipe is a module (or object) with:
6
+ //
7
+ // id Short name clients can ask for, e.g. 'expo'.
8
+ // name Shown to the user, e.g. 'Expo' ("Expo project").
9
+ // detect(src) True if the synced project at src is this kind of project.
10
+ // Synchronous and cheap: look at files, don't run tools.
11
+ // deps?(ctx) Optional. Installs JS or other dependencies on the Mac.
12
+ // Returns true if it installed something, false if they
13
+ // were already up to date.
14
+ // fingerprint(ctx) Hash of everything that affects the native binary, as
15
+ // { hash, source }. source says how it was computed and is
16
+ // shown to the user. Same hash = reuse the cached .app.
17
+ // build(ctx) Builds a Debug .app for the simulator and returns its path.
18
+ // Only called when the fingerprint has no cached build.
19
+ // launch(ctx, app) Starts the installed app, app = { udid, appPath, meta };
20
+ // meta is { bundleId, executable, urlSchemes } from the
21
+ // app's Info.plist. Connect it to the dev server here.
22
+ //
23
+ // ctx, the same object for every call in one run:
24
+ //
25
+ // src Absolute path of the project's mirror on the Mac.
26
+ // derived Folder for xcodebuild's derived data (kept between runs).
27
+ // state The project's saved state; the agent saves it after deps().
28
+ // options { cng, clean, devServerUrl } from the client:
29
+ // cng true when native folders are generated on the Mac
30
+ // (Expo prebuild) rather than synced from the PC.
31
+ // clean the user asked for a clean build.
32
+ // devServerUrl where the PC's dev server (Metro etc.) is, or undefined.
33
+ // sim The simulator helpers (src/agent/sim.js): openUrl, launch, ...
34
+ // tunnel { listening(port) }: whether the PC's tunnel listens on that Mac
35
+ // port, so a localhost dev server URL reaches the PC.
36
+ // onLine (line, stream) => void, pass to commands so their output reaches the user.
37
+ // step(msg) Starts a new phase, e.g. step('Installing CocoaPods').
38
+ // info(msg) Detail for the current phase.
39
+ // warn(msg) Something the user should fix; the run goes on.
40
+ //
41
+ // Throw an Error to fail the run; its message is shown to the user.
42
+ //
43
+ // kit.js has the building blocks (lockfile installs, hashing, pod install,
44
+ // xcodebuild, Info.plist, checking Metro); expo.js is the reference recipe.
45
+ // An optional `session` for interactive dev loops (e.g. Flutter's hot reload)
46
+ // is planned but not part of the contract yet.
47
+ import * as expo from './expo.js';
48
+
49
+ // Checked in order; the first recipe whose detect() matches wins.
50
+ export const recipes = [expo];
51
+
52
+ export function pickRecipe(src, id) {
53
+ if (id) {
54
+ const recipe = recipes.find((r) => r.id === id);
55
+ if (!recipe) throw new Error(`Unknown recipe "${id}". Available: ${recipes.map((r) => r.id).join(', ')}.`);
56
+ return recipe;
57
+ }
58
+ const recipe = recipes.find((r) => r.detect(src));
59
+ if (!recipe) {
60
+ throw new Error(
61
+ `simcast doesn't recognize this project. Supported frameworks: ${recipes.map((r) => r.name).join(', ')}. `
62
+ + 'To add one, see "Adding support for a framework" in CONTRIBUTING.md.',
63
+ );
64
+ }
65
+ return recipe;
66
+ }
@@ -0,0 +1,124 @@
1
+ // Building blocks for recipes. Most recipes should be a few calls to these.
2
+ import crypto from 'node:crypto';
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { LOCKFILES, sha1File } from '../../common.js';
6
+ import { agentEnv, runOk } from '../exec.js';
7
+
8
+ export { agentEnv, runOk };
9
+
10
+ export function readJson(file) {
11
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
12
+ }
13
+
14
+ // Names of everything in package.json's dependencies and devDependencies.
15
+ export function packageDeps(src) {
16
+ const file = path.join(src, 'package.json');
17
+ if (!fs.existsSync(file)) return new Set();
18
+ try {
19
+ const pkg = readJson(file);
20
+ return new Set([...Object.keys(pkg.dependencies || {}), ...Object.keys(pkg.devDependencies || {})]);
21
+ } catch {
22
+ return new Set();
23
+ }
24
+ }
25
+
26
+ // Installs JS dependencies on the Mac, only when the lockfile changed.
27
+ export async function installJsDeps({ src, state, onLine }) {
28
+ const lock = LOCKFILES.find(([file]) => fs.existsSync(path.join(src, file)));
29
+ const lockFile = lock ? lock[0] : 'package.json';
30
+ const hash = await sha1File(path.join(src, lockFile));
31
+ if (state.lockHash === hash && fs.existsSync(path.join(src, 'node_modules'))) return false;
32
+ const [cmd, ...args] = lock ? lock[1] : ['npm', 'install'];
33
+ await runOk(cmd, args, { cwd: src, env: agentEnv({ CI: '1' }), onLine });
34
+ state.lockHash = hash;
35
+ return true;
36
+ }
37
+
38
+ // SHA-1 over the given files (paths relative to src, missing ones skipped) and
39
+ // then the given folders, walked in sorted order. Don't change the order or the
40
+ // separators: build caches are keyed on this hash.
41
+ export function hashPaths(src, { files = [], dirs = [] } = {}) {
42
+ const hash = crypto.createHash('sha1');
43
+ for (const f of files) {
44
+ const p = path.join(src, f);
45
+ if (fs.existsSync(p)) hash.update(`${f}\0`).update(fs.readFileSync(p));
46
+ }
47
+ for (const dir of dirs) hashDir(hash, src, dir);
48
+ return hash.digest('hex');
49
+ }
50
+
51
+ function hashDir(hash, root, rel) {
52
+ const abs = path.join(root, rel);
53
+ if (!fs.existsSync(abs)) return;
54
+ for (const ent of fs.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
55
+ if (['Pods', 'build', 'node_modules', 'xcuserdata'].includes(ent.name)) continue;
56
+ const child = `${rel}/${ent.name}`;
57
+ if (ent.isDirectory()) hashDir(hash, root, child);
58
+ else if (ent.isFile()) hash.update(`${child}\0`).update(fs.readFileSync(path.join(root, child)));
59
+ }
60
+ }
61
+
62
+ export async function podInstall(iosDir, { onLine }) {
63
+ await runOk('pod', ['install'], { cwd: iosDir, onLine });
64
+ }
65
+
66
+ export function findWorkspace(iosDir) {
67
+ const workspace = fs.readdirSync(iosDir).find((f) => f.endsWith('.xcworkspace'));
68
+ if (!workspace) throw new Error('No .xcworkspace found in ios/ after pod install.');
69
+ return { workspace: path.join(iosDir, workspace), scheme: path.basename(workspace, '.xcworkspace') };
70
+ }
71
+
72
+ // Debug build for the simulator. Returns the path of the built .app.
73
+ export async function xcodebuild({ src, workspace, scheme, derived, clean = false, env = {}, onLine }) {
74
+ if (clean) fs.rmSync(derived, { recursive: true, force: true });
75
+ const arch = process.arch === 'arm64' ? 'arm64' : 'x86_64';
76
+ await runOk('xcodebuild', [
77
+ '-workspace', workspace,
78
+ '-scheme', scheme,
79
+ '-configuration', 'Debug',
80
+ '-sdk', 'iphonesimulator',
81
+ '-destination', 'generic/platform=iOS Simulator',
82
+ '-derivedDataPath', derived,
83
+ `ARCHS=${arch}`,
84
+ 'ONLY_ACTIVE_ARCH=NO',
85
+ // Saves time and disk on a small Mac; you don't need Xcode's index here.
86
+ 'COMPILER_INDEX_STORE_ENABLE=NO',
87
+ 'build',
88
+ ], { cwd: src, env: agentEnv(env), onLine });
89
+
90
+ const products = path.join(derived, 'Build', 'Products', 'Debug-iphonesimulator');
91
+ const apps = fs.readdirSync(products).filter((f) => f.endsWith('.app'));
92
+ const app = apps.find((f) => f === `${scheme}.app`) || apps[0];
93
+ if (!app) throw new Error(`Build finished but no .app was found in ${products}`);
94
+ return path.join(products, app);
95
+ }
96
+
97
+ export async function readAppMeta(appPath) {
98
+ const { stdout } = await runOk('plutil', ['-convert', 'json', '-o', '-', path.join(appPath, 'Info.plist')], { capture: true });
99
+ const info = JSON.parse(stdout.toString());
100
+ return {
101
+ bundleId: info.CFBundleIdentifier,
102
+ executable: info.CFBundleExecutable,
103
+ urlSchemes: (info.CFBundleURLTypes || []).flatMap((t) => t.CFBundleURLSchemes || []),
104
+ };
105
+ }
106
+
107
+ // Fetches url from the Mac's side: { ok, status, body } (the first 200
108
+ // characters), or { ok: false, error } when nothing answers.
109
+ export async function probe(url, timeoutMs = 3000) {
110
+ try {
111
+ const res = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
112
+ const text = await res.text();
113
+ return { ok: res.ok, status: res.status, body: text.slice(0, 200) };
114
+ } catch (err) {
115
+ return { ok: false, error: err.cause?.code || err.message };
116
+ }
117
+ }
118
+
119
+ // Whether a Metro dev server answers at url (from the Mac's side).
120
+ export async function metroRunning(url) {
121
+ const status = await probe(`${url}/status`);
122
+ if (status.ok && status.body.includes('running')) return { ok: true };
123
+ return { ok: false, error: status.error || `HTTP ${status.status}` };
124
+ }
@@ -0,0 +1,133 @@
1
+ // Screen recordings: an MP4 of a simulator's screen, made on the Mac and handed
2
+ // to the PC when it stops. Recorded by idb_companion (the same framebuffer the
3
+ // live view reads, so the two run side by side); `simctl io recordVideo` when the
4
+ // companion can't.
5
+
6
+ import { spawn } from 'node:child_process';
7
+ import fs from 'node:fs';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+ import zlib from 'node:zlib';
11
+ import { agentEnv } from './exec.js';
12
+ import { companionFor } from './live.js';
13
+
14
+ const log = (msg) => console.log(`[${new Date().toISOString()}] record: ${msg}`);
15
+ // A recording nobody stops ends here, so a forgotten one can't fill the disk.
16
+ const MAX_MS = 15 * 60 * 1000;
17
+ // One that ended that way waits this long for the PC to collect it.
18
+ const KEEP_MS = 10 * 60 * 1000;
19
+
20
+ const recordings = new Map(); // udid -> { file, finish, capTimer, keepTimer }
21
+
22
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
23
+ function within(promise, ms, what) {
24
+ let timer;
25
+ return Promise.race([promise, new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`${what} timed out`)), ms); })])
26
+ .finally(() => clearTimeout(timer));
27
+ }
28
+ const hasData = (file) => { try { return fs.statSync(file).size > 0; } catch { return false; } };
29
+
30
+ // Starts the companion's record RPC; resolves to a function that stops it.
31
+ async function viaCompanion(udid, file) {
32
+ const { client } = await companionFor(udid);
33
+ const call = client.record();
34
+ const chunks = [];
35
+ const ended = new Promise((resolve, reject) => {
36
+ call.on('data', (r) => { if (r.payload?.data?.length) chunks.push(r.payload.data); });
37
+ call.on('error', reject);
38
+ call.on('end', resolve);
39
+ });
40
+ ended.catch(() => {});
41
+ call.write({ start: { file_path: file } });
42
+ // A companion that can't record (too old, no disk) says so straight away.
43
+ await Promise.race([ended.then(() => { throw new Error('the companion ended the recording at once'); }), sleep(800)]);
44
+ return async () => {
45
+ call.write({ stop: {} });
46
+ call.end();
47
+ await within(ended, 30000, 'Finishing the recording');
48
+ // The companion writes to file_path; one that sends the video back instead
49
+ // sends it gzipped unless it says otherwise.
50
+ if (!hasData(file) && chunks.length) {
51
+ const data = Buffer.concat(chunks);
52
+ let video = data;
53
+ try { video = zlib.gunzipSync(data); } catch { /* not compressed */ }
54
+ fs.writeFileSync(file, video);
55
+ }
56
+ };
57
+ }
58
+
59
+ async function viaSimctl(udid, file) {
60
+ const child = spawn('xcrun', ['simctl', 'io', udid, 'recordVideo', '--codec=h264', '--force', file], {
61
+ env: agentEnv(), stdio: ['ignore', 'pipe', 'pipe'],
62
+ });
63
+ let out = '';
64
+ const exited = new Promise((resolve) => {
65
+ child.on('error', (e) => { out += e.message; resolve(-1); });
66
+ child.on('close', resolve);
67
+ });
68
+ const started = new Promise((resolve) => {
69
+ const watch = (d) => { out += d; if (/Recording started/i.test(out)) resolve(); };
70
+ child.stdout.on('data', watch);
71
+ child.stderr.on('data', watch);
72
+ });
73
+ await Promise.race([started, exited.then((code) => { throw new Error(`simctl couldn't record (code ${code}): ${out.trim().slice(-300)}`); }), sleep(5000)]);
74
+ return async () => {
75
+ // simctl finishes the file on Ctrl+C.
76
+ child.kill('SIGINT');
77
+ await within(exited, 30000, 'Finishing the recording');
78
+ };
79
+ }
80
+
81
+ export async function startRecording(udid) {
82
+ const old = recordings.get(udid);
83
+ if (old && !old.finished) throw new Error('This simulator is already recording');
84
+ if (old) discardRecording(udid);
85
+ const file = path.join(os.tmpdir(), `simcast-rec-${udid}-${Date.now()}.mp4`);
86
+ let stop;
87
+ try {
88
+ stop = await viaCompanion(udid, file);
89
+ log(`recording ${udid} through idb_companion`);
90
+ } catch (err) {
91
+ log(`idb_companion can't record ${udid} (${err.details || err.message}); using simctl`);
92
+ stop = await viaSimctl(udid, file);
93
+ log(`recording ${udid} through simctl`);
94
+ }
95
+ const rec = { file, finished: false, stopping: null, keepTimer: null };
96
+ rec.finish = () => (rec.stopping ??= stop().finally(() => {
97
+ rec.finished = true;
98
+ clearTimeout(rec.capTimer);
99
+ }));
100
+ rec.capTimer = setTimeout(() => {
101
+ log(`recording ${udid} reached ${MAX_MS / 60000} minutes; stopping it`);
102
+ rec.finish().catch((e) => log(`stopping ${udid} failed: ${e.message}`));
103
+ rec.keepTimer = setTimeout(() => discardRecording(udid), KEEP_MS);
104
+ }, MAX_MS);
105
+ recordings.set(udid, rec);
106
+ }
107
+
108
+ // Stops the recording and returns the MP4.
109
+ export async function stopRecording(udid) {
110
+ const rec = recordings.get(udid);
111
+ if (!rec) throw new Error("This simulator isn't recording");
112
+ try {
113
+ await rec.finish();
114
+ if (!hasData(rec.file)) throw new Error('The recording came out empty');
115
+ return fs.readFileSync(rec.file);
116
+ } finally {
117
+ discardRecording(udid);
118
+ }
119
+ }
120
+
121
+ // Ends a recording without keeping it (its window went away).
122
+ export function discardRecording(udid) {
123
+ const rec = recordings.get(udid);
124
+ if (!rec) return;
125
+ recordings.delete(udid);
126
+ clearTimeout(rec.capTimer);
127
+ clearTimeout(rec.keepTimer);
128
+ rec.finish().catch(() => {}).finally(() => fs.rmSync(rec.file, { force: true }));
129
+ }
130
+
131
+ export function discardAllRecordings() {
132
+ for (const udid of [...recordings.keys()]) discardRecording(udid);
133
+ }