noracu 0.3.0 → 0.3.2

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.
@@ -6,11 +6,14 @@
6
6
  // This module finds the device, starts the runner through xcodebuild, and talks to it.
7
7
  //
8
8
  // What it keeps to:
9
- // • No internet. xcodebuild and devicectl are local tools; the socket goes to a paired device over
9
+ // • No internet. xcodebuild, devicectl and simctl are local tools; the socket goes to a paired device over
10
10
  // Apple's tunnel, or to 127.0.0.1 for a simulator.
11
11
  // • Every subprocess gets its arguments as an argv array — nothing is put into a shell line.
12
12
  // • devicectl answers are read from --json-output files, never from terminal text (Apple documents
13
- // the JSON as the stable interface and the terminal output as free to change).
13
+ // the JSON as the stable interface and the terminal output as free to change); the simulator list is
14
+ // simctl's --json output.
15
+ // • iPhones are found with devicectl, simulators with simctl: devicectl does not list simulators with
16
+ // every Xcode (see listSimulators).
14
17
  // • Every runner call has a hard time limit. A call that timed out, or whose connection broke after
15
18
  // the request left, is reported as such — "delivery unknown" for input commands — and never
16
19
  // re-sent. The connection is dropped so a late answer cannot be taken for the next call's.
@@ -69,12 +72,16 @@ export function defaultRun(file, argv, { timeoutMs = 30000, env } = {}) {
69
72
  // the devicectl / simctl calls still running: ended when the server goes away
70
73
  export function killPending() { for (const c of pending) { try { c.kill("SIGKILL"); } catch { /* already gone */ } } pending.clear(); }
71
74
 
72
- // One devicectl call. Returns { ok: true, result } or { ok: false, error, message }.
73
- export async function devicectl(args, { run = defaultRun, timeoutMs = 30000 } = {}) {
75
+ // One devicectl call. Returns { ok: true, result } or { ok: false, error, message }. beforeRun: the caller's last look
76
+ // before devicectl starts, made after its temporary folder is; a result it returns is the answer, and devicectl is
77
+ // not started.
78
+ export async function devicectl(args, { run = defaultRun, timeoutMs = 30000, beforeRun } = {}) {
74
79
  let dir;
75
80
  try {
76
81
  dir = await mkdtemp(join(tmpdir(), "noracu-dc-")); // 0700, ours alone
77
82
  const out = join(dir, "out.json");
83
+ const refused = beforeRun ? beforeRun() : null;
84
+ if (refused) return refused;
78
85
  const r = await run(XCRUN, ["devicectl", ...args, "--quiet", "--json-output", out], { timeoutMs });
79
86
  if (r.timedOut) return { ok: false, error: "devicectl_timeout", message: `devicectl ${args.slice(0, 3).join(" ")} gave no answer in ${timeoutMs} ms` };
80
87
  let doc = null;
@@ -117,6 +124,38 @@ export async function listDevices(opts = {}) {
117
124
  return { ok: true, devices };
118
125
  }
119
126
 
127
+ // The iOS simulators `simctl list --json` reports (its devices, runtimes and device types), with the fields
128
+ // parseDevice gives — set as devicectl reports a simulator: paired, on this same Mac, its tunnel up while it is
129
+ // booted, no Developer Mode. One that simctl marks unavailable (its runtime is gone) is left out.
130
+ export function parseSimulators(doc) {
131
+ const runtimes = new Map((Array.isArray(doc?.runtimes) ? doc.runtimes : []).map((r) => [r?.identifier, r]));
132
+ const types = new Map((Array.isArray(doc?.devicetypes) ? doc.devicetypes : []).map((t) => [t?.identifier, t]));
133
+ const out = [];
134
+ for (const [key, list] of Object.entries(doc?.devices && typeof doc.devices === "object" ? doc.devices : {})) {
135
+ const rt = runtimes.get(key), m = /SimRuntime\.iOS-(\d+)-(\d+)(?:-(\d+))?$/.exec(key);
136
+ if ((rt?.platform ?? (m ? "iOS" : null)) !== "iOS" || !Array.isArray(list)) continue;
137
+ const os = typeof rt?.version === "string" ? rt.version : m ? [m[1], m[2], m[3]].filter((x) => x !== undefined).join(".") : null;
138
+ for (const d of list) {
139
+ if (typeof d?.udid !== "string" || d.isAvailable === false) continue;
140
+ const booted = d.state === "Booted";
141
+ out.push({ udid: d.udid, name: typeof d.name === "string" ? d.name : null, model: types.get(d.deviceTypeIdentifier)?.name ?? null, os, platform: "iOS",
142
+ simulated: true, transport: "sameMachine", paired: true, tunnel: booted, tunnelIP: null, developerMode: false, booted });
143
+ }
144
+ }
145
+ return out;
146
+ }
147
+
148
+ // Simulators are looked up with simctl, never with devicectl: devicectl does not list them with every Xcode. With
149
+ // Xcode 26.6 (a macOS 26 CI runner, 2026-11) it listed none, or gave no answer in 30 s; Xcode 27.2 lists them.
150
+ export async function listSimulators({ run = defaultRun, timeoutMs = 30000 } = {}) {
151
+ const r = await run(XCRUN, ["simctl", "list", "--json"], { timeoutMs });
152
+ if (r.timedOut) return { ok: false, error: "simctl_timeout", message: `simctl list gave no answer in ${timeoutMs} ms` };
153
+ let doc = null;
154
+ try { doc = JSON.parse(r.stdout); } catch { /* reported below */ }
155
+ if (r.code !== 0 || !doc || typeof doc !== "object") return { ok: false, error: "simctl_failed", message: oneLine(r.stderr || (r.code === 0 ? "simctl list did not answer in JSON" : `exit ${r.code}`)) };
156
+ return { ok: true, devices: parseSimulators(doc) };
157
+ }
158
+
120
159
  export async function deviceDetails(udid, opts = {}) {
121
160
  if (!validUdid(udid)) return { ok: false, error: "invalid_args", message: "udid is not a device identifier" };
122
161
  const r = await devicectl(["device", "info", "details", "--device", udid], opts);
@@ -131,7 +170,7 @@ export function bindAddressFor(device) {
131
170
  if (!device.developerMode) return { ok: false, error: "device_not_ready", message: "Developer Mode is off on the iPhone" };
132
171
  if (!device.tunnel || !device.tunnelIP) return { ok: false, error: "device_not_ready", message: "no CoreDevice tunnel to the iPhone (unlock it and check the cable or network)" };
133
172
  if (!net.isIPv6(device.tunnelIP)) return { ok: false, error: "device_not_ready", message: "the tunnel address is not an IPv6 address" };
134
- // the CoreDevice tunnel's address is unique-local (fc00::/7); anything else would listen beyond it (review S4A-s7-grok-3)
173
+ // the CoreDevice tunnel's address is unique-local (fc00::/7); anything else would listen beyond it
135
174
  if (device.tunnelIP !== "::1" && !/^f[cd][0-9a-f]{0,2}:/i.test(device.tunnelIP)) return { ok: false, error: "device_not_ready", message: "the tunnel address is not a unique-local (fc00::/7) address" };
136
175
  return { ok: true, bind: device.tunnelIP };
137
176
  }
@@ -151,13 +190,15 @@ export async function launchApp(udid, bundleId, { terminateExisting = false, ...
151
190
  if (!validBundleId(bundleId)) return { ok: false, error: "invalid_args", message: "bundle_id is not a bundle identifier" };
152
191
  const r = await devicectl(["device", "process", "launch", "--device", udid, ...(terminateExisting ? ["--terminate-existing"] : []), bundleId], opts);
153
192
  if (!r.ok) return r;
154
- return { ok: true, pid: r.result.process?.processIdentifier ?? null, activated: r.result.launchOptions?.activatedWhenStarted === true }; // never assumed (review S4A-s7-A-1)
193
+ return { ok: true, pid: r.result.process?.processIdentifier ?? null, activated: r.result.launchOptions?.activatedWhenStarted === true }; // never assumed
155
194
  }
156
195
 
157
196
  // The same for a simulator, which devicectl does not launch apps on: simctl, by exit code.
158
- export async function simLaunch(udid, bundleId, { terminateExisting = false, run = defaultRun, timeoutMs = 30000 } = {}) {
197
+ export async function simLaunch(udid, bundleId, { terminateExisting = false, run = defaultRun, timeoutMs = 30000, beforeRun } = {}) {
159
198
  if (!isSimulatorUdid(udid)) return { ok: false, error: "invalid_args", message: "udid is not a simulator identifier" };
160
199
  if (!validBundleId(bundleId)) return { ok: false, error: "invalid_args", message: "bundle_id is not a bundle identifier" };
200
+ const refused = beforeRun ? beforeRun() : null; // the caller's last look before simctl starts, as for devicectl
201
+ if (refused) return refused;
161
202
  const r = await run(XCRUN, ["simctl", "launch", ...(terminateExisting ? ["--terminate-running-process"] : []), udid, bundleId], { timeoutMs });
162
203
  if (r.timedOut) return { ok: false, error: "simctl_timeout", message: `simctl launch gave no answer in ${timeoutMs} ms` };
163
204
  if (r.code !== 0) return { ok: false, error: "simctl_failed", message: oneLine(r.stderr || r.stdout || `exit ${r.code}`) };
@@ -230,7 +271,7 @@ export function runnerSourceHash(dir = RUNNER_DIR) {
230
271
  }
231
272
  // What a runner must name to be used: the hash of this copy of its sources. The build line in them must say the
232
273
  // same — a change under ios-runner/ without scripts/gen-runner-build.mjs would otherwise build a runner that
233
- // passes for the one before it (pre-review P4).
274
+ // passes for the one before it.
234
275
  export function expectedRunnerBuild(dir = RUNNER_DIR) {
235
276
  let hash;
236
277
  try { hash = runnerSourceHash(dir); } catch { return { ok: false, message: "this noracu's runner sources (ios-runner/) could not be read, so a runner cannot be checked against them" }; }
@@ -254,15 +295,17 @@ export function startRunner({ udid, xctestrun, bind, token = newToken(), port =
254
295
  try { argv = xcodebuildArgv({ xctestrun, udid }); extra = runnerEnv({ token, bind, port }); }
255
296
  catch (e) { return Promise.resolve({ ok: false, error: "invalid_args", message: e.message }); }
256
297
  return new Promise((resolve) => {
257
- let child, seen = "", settled = false, timer = null, exited = null;
298
+ let child, seen = "", settled = false, timer = null, exited = null, gone = false;
258
299
  // xcodebuild and what it started get a process group of their own (detached), so the whole group is
259
300
  // signalled; a child without one (a test's stand-in) is signalled alone
260
- const signal = (sig) => { if (!child) return; try { process.kill(-child.pid, sig); } catch { try { child.kill(sig); } catch { /* already gone */ } } };
301
+ // an xcodebuild that has exited is not signalled: its pid — and its group's — may be another process's by then
302
+ const signal = (sig) => { if (!child || gone) return; try { process.kill(-child.pid, sig); } catch { try { child.kill(sig); } catch { /* already gone */ } } };
261
303
  const kill = () => { signal("SIGTERM"); const k = setTimeout(() => signal("SIGKILL"), 3000); k.unref?.(); };
262
304
  const finish = (v) => { if (settled) return; settled = true; clearTimeout(timer); if (!v.ok) kill(); resolve(v.ok || !exited ? v : { ...v, exited }); };
263
305
  try { child = spawnImpl(XCODEBUILD, argv, { env: { ...env, ...extra }, stdio: ["ignore", "pipe", "pipe"], detached: true }); }
264
306
  catch (e) { return finish({ ok: false, error: "runner_start_failed", message: oneLine(e && e.message) }); }
265
307
  exited = new Promise((res) => { child.once?.("exit", res); child.once?.("error", res); });
308
+ child.once?.("exit", () => { gone = true; });
266
309
  const onData = (chunk) => {
267
310
  if (settled) return;
268
311
  seen = (seen + String(chunk)).slice(-65536);
@@ -308,7 +351,14 @@ export class RunnerClient {
308
351
  this.sock = null; this.nextId = 1; this.pending = null; this.chunks = []; this.size = 0;
309
352
  }
310
353
 
311
- close() { const s = this.sock; this.sock = null; this.chunks = []; this.size = 0; if (s) s.destroy(); }
354
+ // close() from outside (the session stopping the runner): a call in flight is answered now — it waited for its own
355
+ // timeout. Inside, a failure that answers the call itself drops the connection with _drop().
356
+ close() {
357
+ const p = this.pending;
358
+ this._drop();
359
+ if (p) p.settle({ ok: false, error: "runner_unreachable", message: "the connection to the runner was closed before it answered", delivery: p.sentBytes ? (INPUT_OPS.has(p.op) ? "unknown" : "not_applicable") : "not_delivered" });
360
+ }
361
+ _drop() { const s = this.sock; this.sock = null; this.chunks = []; this.size = 0; if (s) s.destroy(); }
312
362
 
313
363
  _connect() {
314
364
  return new Promise((resolve) => {
@@ -320,12 +370,14 @@ export class RunnerClient {
320
370
  });
321
371
  }
322
372
 
323
- _fail(error, message) { const p = this.pending; this.close(); if (p) p.settle({ ok: false, error, message, delivery: p.sentBytes ? (INPUT_OPS.has(p.op) ? "unknown" : "not_applicable") : "not_delivered" }); }
373
+ _fail(error, message) { const p = this.pending; this._drop(); if (p) p.settle({ ok: false, error, message, delivery: p.sentBytes ? (INPUT_OPS.has(p.op) ? "unknown" : "not_applicable") : "not_delivered" }); }
324
374
  _onClose(s) { if (s !== this.sock) return; this._fail("runner_unreachable", "the connection to the runner closed before it answered"); }
325
375
 
326
376
  _onData(d) {
327
377
  let from = 0, nl;
328
378
  while ((nl = d.indexOf(10, from)) !== -1) {
379
+ // a whole line counts against the limit as a tail without a newline does
380
+ if (this.size + (nl - from) > this.maxAnswerBytes) return this._fail("runner_protocol", "the runner sent a line longer than the limit");
329
381
  this.chunks.push(d.subarray(from, nl));
330
382
  const line = Buffer.concat(this.chunks).toString("utf8");
331
383
  this.chunks = []; this.size = 0; from = nl + 1;
@@ -346,12 +398,14 @@ export class RunnerClient {
346
398
  const code = typeof msg.error === "string" && /^[a-z_]{1,40}$/.test(msg.error) ? msg.error : "runner_error";
347
399
  const input = INPUT_OPS.has(p.op);
348
400
  const delivery = !input ? "not_applicable" : (msg.sent === false || NOTHING_SENT.has(code)) ? "not_delivered" : "unknown";
349
- if (code === "auth") this.close();
401
+ if (code === "auth") this._drop();
350
402
  p.settle({ ok: false, error: code, message: oneLine(msg.message), delivery });
351
403
  }
352
404
 
353
405
  // → { ok: true, result } | { ok: false, error, message, delivery: "not_delivered" | "unknown" | "not_applicable" }
354
- async call(op, args = {}, { timeoutMs = 15000 } = {}) {
406
+ // beforeSend: the caller's last look before the command is written, made after the connection that may have to be
407
+ // opened first. A result it returns is the answer, and nothing is written.
408
+ async call(op, args = {}, { timeoutMs = 15000, beforeSend } = {}) {
355
409
  if (this.pending) return { ok: false, error: "runner_busy", message: "another runner call is in flight", delivery: "not_delivered" };
356
410
  const id = this.nextId++;
357
411
  const line = JSON.stringify({ id, token: this.token, op, args }) + "\n";
@@ -361,11 +415,13 @@ export class RunnerClient {
361
415
  const p = this.pending = { id, op, sentBytes: 0, settle: (v) => { if (this.pending === p) this.pending = null; clearTimeout(p.timer); settle(v); } };
362
416
  p.timer = setTimeout(() => {
363
417
  const delivery = p.sentBytes ? (INPUT_OPS.has(op) ? "unknown" : "not_applicable") : "not_delivered";
364
- this.close(); // a late answer must not be read as the next call's
418
+ this._drop(); // a late answer must not be read as the next call's
365
419
  p.settle({ ok: false, error: "ios_timeout", message: `the runner did not answer ${op} in ${timeoutMs} ms`, delivery });
366
420
  }, timeoutMs);
367
421
  if (!this.sock && !(await this._connect())) { if (this.pending === p) p.settle({ ok: false, error: "runner_unreachable", message: "could not connect to the runner", delivery: "not_delivered" }); return done; }
368
422
  if (this.pending !== p) return done; // timed out while connecting
423
+ const refused = beforeSend ? beforeSend() : null;
424
+ if (refused) { p.settle(refused); return done; }
369
425
  p.sentBytes = Buffer.byteLength(line);
370
426
  this.sock.write(line);
371
427
  return done;