simcast-host 0.0.0-stage → 0.9.1
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.
- package/LICENSE +21 -0
- package/README.md +72 -2
- package/bin/simcast-host.js +11 -0
- package/package.json +28 -4
- package/proto/idb.proto +1816 -0
- package/src/agent/admin.js +87 -0
- package/src/agent/awake.js +136 -0
- package/src/agent/bonjour.js +172 -0
- package/src/agent/build.js +24 -0
- package/src/agent/checks.js +618 -0
- package/src/agent/clean.js +419 -0
- package/src/agent/cli.js +617 -0
- package/src/agent/clients.js +475 -0
- package/src/agent/exec.js +163 -0
- package/src/agent/live.js +709 -0
- package/src/agent/macinfo.js +75 -0
- package/src/agent/pairing.js +123 -0
- package/src/agent/paths.js +23 -0
- package/src/agent/recipes/expo.js +134 -0
- package/src/agent/recipes/index.js +66 -0
- package/src/agent/recipes/kit.js +124 -0
- package/src/agent/record.js +133 -0
- package/src/agent/runtime.js +166 -0
- package/src/agent/screen.js +285 -0
- package/src/agent/server.js +577 -0
- package/src/agent/service.js +119 -0
- package/src/agent/setup.js +283 -0
- package/src/agent/sim.js +129 -0
- package/src/agent/stalls.js +32 -0
- package/src/agent/state.js +121 -0
- package/src/agent/tunnel.js +464 -0
- package/src/common.js +119 -0
|
@@ -0,0 +1,75 @@
|
|
|
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
|
+
// A hardware address we can't wake with: missing, all zeros, or locally
|
|
45
|
+
// administered (bit 0x02 of the first octet), such as the 02:00:00:00:00:00
|
|
46
|
+
// macOS 27 reports to Node for every interface (privacy masking).
|
|
47
|
+
const unusableMac = (mac) => !mac || /^(00:){5}00$/.test(mac) || (parseInt(mac.slice(0, 2), 16) & 0x02) !== 0;
|
|
48
|
+
|
|
49
|
+
// The address in `networksetup -getmacaddress <interface>` output
|
|
50
|
+
// ("Ethernet Address: aa:bb:… (Device: en0)"), else null.
|
|
51
|
+
export function parseMacAddress(output) {
|
|
52
|
+
return /Ethernet Address:\s*([0-9a-f]{2}(?::[0-9a-f]{2}){5})/i.exec(output || '')?.[1].toLowerCase() || null;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Wake-on-LAN details of the interface a request came in on: the interface in
|
|
56
|
+
// os.networkInterfaces() whose IPv4 address equals `localAddress`
|
|
57
|
+
// (req.socket.localAddress; an IPv4-mapped "::ffff:" prefix is removed):
|
|
58
|
+
// { mac, interface, address, netmask }, else null (an IPv6 or loopback address,
|
|
59
|
+
// no such interface, or no usable hardware address). When Node's MAC is masked,
|
|
60
|
+
// the real one comes from networksetup (ifconfig run by Node is masked too).
|
|
61
|
+
export async function wakeInfo(localAddress, interfaces = os.networkInterfaces(), macOf = (name) => probe('networksetup', ['-getmacaddress', name])) {
|
|
62
|
+
const address = String(localAddress || '').replace(/^::ffff:/i, '');
|
|
63
|
+
if (!/^\d{1,3}(\.\d{1,3}){3}$/.test(address)) return null;
|
|
64
|
+
for (const [name, addrs] of Object.entries(interfaces || {})) {
|
|
65
|
+
for (const a of addrs || []) {
|
|
66
|
+
const v4 = a.family === 'IPv4' || a.family === 4;
|
|
67
|
+
if (!v4 || a.internal || a.address !== address) continue;
|
|
68
|
+
let mac = a.mac?.toLowerCase();
|
|
69
|
+
if (unusableMac(mac)) mac = parseMacAddress(await macOf(name));
|
|
70
|
+
if (unusableMac(mac)) return null;
|
|
71
|
+
return { mac, interface: name, address, netmask: a.netmask || null };
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
@@ -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,134 @@
|
|
|
1
|
+
// Expo (dev builds with expo-dev-client). The reference recipe.
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { LOCKFILES } from '../../common.js';
|
|
5
|
+
import * as tunnelModule from '../tunnel.js';
|
|
6
|
+
import * as kit from './kit.js';
|
|
7
|
+
|
|
8
|
+
export const id = 'expo';
|
|
9
|
+
export const name = 'Expo';
|
|
10
|
+
|
|
11
|
+
export function detect(src) {
|
|
12
|
+
return kit.packageDeps(src).has('expo');
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export const deps = kit.installJsDeps;
|
|
16
|
+
|
|
17
|
+
// Runs in a fresh `node` so nothing is cached between runs: in the agent's own
|
|
18
|
+
// process, Node's module cache and expo-modules-autolinking's memo kept the old
|
|
19
|
+
// hash after a native module was added. argv: src, options as JSON.
|
|
20
|
+
const FINGERPRINT_SCRIPT = `
|
|
21
|
+
const path = require('node:path');
|
|
22
|
+
const [src, opts] = process.argv.slice(1);
|
|
23
|
+
const mod = require('node:module').createRequire(path.join(src, 'package.json'))('@expo/fingerprint');
|
|
24
|
+
const create = mod.createFingerprintAsync || mod.default?.createFingerprintAsync;
|
|
25
|
+
create(src, JSON.parse(opts)).then((r) => process.stdout.write(JSON.stringify({ hash: r?.hash })));
|
|
26
|
+
`;
|
|
27
|
+
|
|
28
|
+
// Hash of everything that affects the native binary. Uses Expo's own
|
|
29
|
+
// @expo/fingerprint from the project when available.
|
|
30
|
+
export async function fingerprint({ src, options: { cng } }) {
|
|
31
|
+
const opts = { platforms: ['ios'] };
|
|
32
|
+
// In prebuild mode, ios/ is generated on the Mac and must not change the hash.
|
|
33
|
+
if (cng) opts.ignorePaths = ['ios/**', 'android/**'];
|
|
34
|
+
try {
|
|
35
|
+
const res = await kit.run(process.execPath, ['-e', FINGERPRINT_SCRIPT, src, JSON.stringify(opts)], { cwd: src, capture: true });
|
|
36
|
+
const hash = res.code === 0 && JSON.parse(res.stdout.toString().trim().split('\n').at(-1)).hash;
|
|
37
|
+
if (hash) return { hash, source: '@expo/fingerprint' };
|
|
38
|
+
} catch {
|
|
39
|
+
// fall through to the simple fingerprint
|
|
40
|
+
}
|
|
41
|
+
const hash = kit.hashPaths(src, {
|
|
42
|
+
files: [
|
|
43
|
+
'package.json', ...LOCKFILES.map(([f]) => f), 'app.json', 'app.config.js',
|
|
44
|
+
'app.config.ts', 'app.config.mjs', 'app.config.cjs', 'eas.json',
|
|
45
|
+
],
|
|
46
|
+
dirs: ['plugins', ...(cng ? [] : ['ios'])],
|
|
47
|
+
});
|
|
48
|
+
return { hash, source: 'fallback' };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export async function build({ src, derived, options: { cng, clean }, onLine, step }) {
|
|
52
|
+
const ios = path.join(src, 'ios');
|
|
53
|
+
if (cng) {
|
|
54
|
+
step('Running expo prebuild');
|
|
55
|
+
const args = ['expo', 'prebuild', '--platform', 'ios', '--no-install'];
|
|
56
|
+
if (clean) args.push('--clean');
|
|
57
|
+
await kit.runOk('npx', args, { cwd: src, env: kit.agentEnv({ CI: '1' }), onLine });
|
|
58
|
+
} else if (!fs.existsSync(ios)) {
|
|
59
|
+
throw new Error('This project has no ios/ folder. Remove it from .gitignore rules or let simcast run prebuild.');
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
step('Installing CocoaPods');
|
|
63
|
+
await kit.podInstall(ios, { onLine });
|
|
64
|
+
|
|
65
|
+
const { workspace, scheme } = kit.findWorkspace(ios);
|
|
66
|
+
step(`Compiling with xcodebuild (scheme ${scheme})`);
|
|
67
|
+
return kit.xcodebuild({
|
|
68
|
+
src, workspace, scheme, derived, clean, onLine,
|
|
69
|
+
// Don't bundle JS into the app and don't start a Metro on the Mac:
|
|
70
|
+
// the app loads JS from Metro on the Windows PC.
|
|
71
|
+
env: { SKIP_BUNDLING: '1', RCT_NO_LAUNCH_PACKAGER: '1' },
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// How long the dev client gets between "simctl launch" and the openurl. Opening
|
|
76
|
+
// the URL tears down the JS runtime the launch started; doing it while that
|
|
77
|
+
// runtime is still starting shows a red "[runtime not ready]: React Native Runtime
|
|
78
|
+
// is shutting down" toast for a few seconds (seen on iOS 27). A guess, not
|
|
79
|
+
// measured: it should outlast the launcher's start-up on a normal Mac.
|
|
80
|
+
export const LAUNCH_SETTLE_MS = 1500;
|
|
81
|
+
|
|
82
|
+
// The warning when the agent's own Metro check fails, worded for how the PC
|
|
83
|
+
// reaches the Mac (docs/protocol.md, "Tunnel mode"):
|
|
84
|
+
// tunnel up a loopback URL whose port the PC's tunnel listens on
|
|
85
|
+
// no tunnel http://localhost:<p> with no tunnel listening on p
|
|
86
|
+
// direct anything else: the PC's own address (0.6 and --direct)
|
|
87
|
+
export function metroWarning(devServerUrl, error, tunnel) {
|
|
88
|
+
const url = URL.canParse(devServerUrl) ? new URL(devServerUrl) : null;
|
|
89
|
+
const port = url ? url.port || (url.protocol === 'https:' ? '443' : '80') : '8081';
|
|
90
|
+
const host = url?.hostname.replace(/^\[|\]$/g, '').toLowerCase();
|
|
91
|
+
const loopback = ['localhost', '127.0.0.1', '::1'].includes(host);
|
|
92
|
+
if (loopback && tunnel?.listening(Number(port))) {
|
|
93
|
+
return `Metro on the PC didn't answer through the tunnel (${error}). Is "npx expo start" running on the PC?`;
|
|
94
|
+
}
|
|
95
|
+
if (host === 'localhost') {
|
|
96
|
+
return `No tunnel from the PC for port ${port}. Run simcast run ios again, or simcast tunnel to check it.`;
|
|
97
|
+
}
|
|
98
|
+
// EHOSTUNREACH is macOS's Local Network privacy blocking this agent (the
|
|
99
|
+
// simulator's apps may still get through); Windows Firewall times out instead.
|
|
100
|
+
return String(error).includes('EHOSTUNREACH')
|
|
101
|
+
? `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`
|
|
102
|
+
: `The Mac can't reach Metro at ${devServerUrl} (${error}). Is "npx expo start" running, and is port ${port} allowed through your computer's firewall?`;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// ctx.tunnel ({ listening(port) }) comes from the agent; tunnel.js itself when
|
|
106
|
+
// the caller leaves it out.
|
|
107
|
+
export async function launch({ options: { devServerUrl }, sim, info, warn, tunnel = tunnelModule }, { udid, meta }) {
|
|
108
|
+
if (devServerUrl) {
|
|
109
|
+
const metro = await kit.metroRunning(devServerUrl);
|
|
110
|
+
if (!metro.ok) warn(metroWarning(devServerUrl, metro.error, tunnel));
|
|
111
|
+
}
|
|
112
|
+
// expo-dev-client registers an "exp+<slug>" scheme.
|
|
113
|
+
const devClientScheme = meta.urlSchemes.find((s) => s.startsWith('exp+'));
|
|
114
|
+
if (devClientScheme && devServerUrl) {
|
|
115
|
+
const url = `${devClientScheme}://expo-development-client/?url=${encodeURIComponent(devServerUrl)}`;
|
|
116
|
+
// Approved first, or iOS asks "Open in <app>?" the first time and nothing
|
|
117
|
+
// happens until someone taps Open. A failure only means it may ask.
|
|
118
|
+
await sim.approveScheme(udid, devClientScheme, meta.bundleId);
|
|
119
|
+
await sim.launch(udid, meta.bundleId);
|
|
120
|
+
await new Promise((resolve) => setTimeout(resolve, LAUNCH_SETTLE_MS));
|
|
121
|
+
await sim.openUrl(udid, url);
|
|
122
|
+
info(`Opened ${url}`);
|
|
123
|
+
} else {
|
|
124
|
+
// A debug build without expo-dev-client asks React Native's default bundle
|
|
125
|
+
// location, localhost:8081 on the Mac; the tunnel or --direct is elsewhere.
|
|
126
|
+
if (!devClientScheme && devServerUrl && URL.canParse(devServerUrl)) {
|
|
127
|
+
const url = new URL(devServerUrl);
|
|
128
|
+
const hostPort = `${url.hostname}:${url.port || (url.protocol === 'https:' ? '443' : '80')}`;
|
|
129
|
+
await sim.setJsLocation(udid, meta.bundleId, hostPort);
|
|
130
|
+
info(`expo-dev-client isn't installed; the app loads JS from ${hostPort}`);
|
|
131
|
+
}
|
|
132
|
+
await sim.launch(udid, meta.bundleId);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
@@ -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, run, runOk } from '../exec.js';
|
|
7
|
+
|
|
8
|
+
export { agentEnv, run, 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
|
+
}
|