agent-device-x86sim 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +192 -2
- package/ax-hook/libx86sim-ax.dylib +0 -0
- package/dist/cli.js +127 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +226 -0
- package/dist/start-server-C84E8KRm.js +1182 -0
- package/dist/system-DMZAX-z7.js +203 -0
- package/package.json +59 -3
|
@@ -0,0 +1,1182 @@
|
|
|
1
|
+
import { n as isPhoneRunning } from "./system-DMZAX-z7.js";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { access, mkdtemp, readFile, readdir, realpath, rm, unlink } from "node:fs/promises";
|
|
4
|
+
import { tmpdir, userInfo } from "node:os";
|
|
5
|
+
import { createConnection, createServer } from "node:net";
|
|
6
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
import { execFile, spawn } from "node:child_process";
|
|
9
|
+
import { createServer as createServer$1 } from "node:http";
|
|
10
|
+
//#region \0rolldown/runtime.js
|
|
11
|
+
var __defProp = Object.defineProperty;
|
|
12
|
+
var __exportAll = (all, no_symbols) => {
|
|
13
|
+
let target = {};
|
|
14
|
+
for (var name in all) __defProp(target, name, {
|
|
15
|
+
get: all[name],
|
|
16
|
+
enumerable: true
|
|
17
|
+
});
|
|
18
|
+
if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
|
|
19
|
+
return target;
|
|
20
|
+
};
|
|
21
|
+
//#endregion
|
|
22
|
+
//#region src/cli/hook-path.ts
|
|
23
|
+
/** The hook's place in the package, relative to the built `dist/` folder. */
|
|
24
|
+
const PACKAGED_HOOK = "../ax-hook/libx86sim-ax.dylib";
|
|
25
|
+
/** The absolute path of the accessibility hook this package ships, resolved from where it is installed. */
|
|
26
|
+
async function packagedHookPath(moduleUrl = import.meta.url) {
|
|
27
|
+
const file = fileURLToPath(new URL(PACKAGED_HOOK, moduleUrl));
|
|
28
|
+
try {
|
|
29
|
+
await access(file);
|
|
30
|
+
} catch {
|
|
31
|
+
throw new Error(`The accessibility hook is missing from this install, at ${file}. Reinstall agent-device-x86sim.`);
|
|
32
|
+
}
|
|
33
|
+
return file;
|
|
34
|
+
}
|
|
35
|
+
/** Where x86Sim mounts the Linux file system inside the phone. */
|
|
36
|
+
const PHONE_MOUNT_OF_HOST = "/Volumes/SystemRoot";
|
|
37
|
+
/**
|
|
38
|
+
* The files `sim.env` says the phone loaded into every process, as Linux paths. The phone sees
|
|
39
|
+
* the host file system under `/Volumes/SystemRoot`, so that prefix comes off.
|
|
40
|
+
*/
|
|
41
|
+
function insertedLibraries(simEnv) {
|
|
42
|
+
return (/^DYLD_INSERT_LIBRARIES=(.*)$/m.exec(simEnv)?.[1] ?? "").split(":").filter((entry) => entry !== "").map((entry) => entry.startsWith(`${PHONE_MOUNT_OF_HOST}/`) ? entry.slice(19) : entry);
|
|
43
|
+
}
|
|
44
|
+
const digestOf = async (file) => await readFile(file).then((bytes) => createHash("sha256").update(bytes).digest("hex"), () => void 0);
|
|
45
|
+
/**
|
|
46
|
+
* Whether the phone loaded exactly the hook this package ships. A hook from an older install
|
|
47
|
+
* differs in its bytes, and one whose file is gone from disk counts as different.
|
|
48
|
+
*/
|
|
49
|
+
async function loadedHookIsPackaged(simEnv, packaged) {
|
|
50
|
+
const wanted = await digestOf(packaged);
|
|
51
|
+
if (wanted === void 0) return false;
|
|
52
|
+
for (const file of insertedLibraries(simEnv)) if (await digestOf(file) === wanted) return true;
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
/** A touch that begins within this share of the display width of an edge is an edge touch. */
|
|
56
|
+
const EDGE_MARGIN = .04;
|
|
57
|
+
/**
|
|
58
|
+
* The screen edge a touch begins on, which simhid needs for system gestures such as the home
|
|
59
|
+
* indicator and Control Center. Top and bottom win in the corners.
|
|
60
|
+
*/
|
|
61
|
+
function edgeAt(at, screen) {
|
|
62
|
+
const margin = EDGE_MARGIN * screen.width;
|
|
63
|
+
if (at.y >= screen.height - margin) return "bottom";
|
|
64
|
+
if (at.y <= margin) return "top";
|
|
65
|
+
if (at.x <= margin) return "left";
|
|
66
|
+
if (at.x >= screen.width - margin) return "right";
|
|
67
|
+
}
|
|
68
|
+
const clamp01 = (value) => Math.min(1, Math.max(0, value));
|
|
69
|
+
function touchLine(phase, at, screen, edge) {
|
|
70
|
+
return `touch ${phase} ${clamp01(at.x / screen.width).toFixed(5)} ${clamp01(at.y / screen.height).toFixed(5)}${edge ? ` ${edge}` : ""}`;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Turns device-point touch events into simhid lines and waits. Points are normalized to the
|
|
74
|
+
* display and clamped to it. A touch that lifts sooner than {@link MIN_TOUCH_MS} after it
|
|
75
|
+
* landed gets a wait before its `up`, counted from the pauses the events themselves carry.
|
|
76
|
+
*/
|
|
77
|
+
function touchSteps(events, screen) {
|
|
78
|
+
const steps = [];
|
|
79
|
+
let pressed = false;
|
|
80
|
+
let heldMs = 0;
|
|
81
|
+
for (const event of events) switch (event.kind) {
|
|
82
|
+
case "down":
|
|
83
|
+
steps.push({
|
|
84
|
+
kind: "line",
|
|
85
|
+
line: touchLine("down", event.at, screen, edgeAt(event.at, screen))
|
|
86
|
+
});
|
|
87
|
+
pressed = true;
|
|
88
|
+
heldMs = 0;
|
|
89
|
+
break;
|
|
90
|
+
case "move":
|
|
91
|
+
steps.push({
|
|
92
|
+
kind: "line",
|
|
93
|
+
line: touchLine("move", event.at, screen)
|
|
94
|
+
});
|
|
95
|
+
break;
|
|
96
|
+
case "pause":
|
|
97
|
+
steps.push({
|
|
98
|
+
kind: "wait",
|
|
99
|
+
ms: event.ms
|
|
100
|
+
});
|
|
101
|
+
if (pressed) heldMs += event.ms;
|
|
102
|
+
break;
|
|
103
|
+
case "up":
|
|
104
|
+
if (pressed && heldMs < 80) steps.push({
|
|
105
|
+
kind: "wait",
|
|
106
|
+
ms: 80 - heldMs
|
|
107
|
+
});
|
|
108
|
+
steps.push({
|
|
109
|
+
kind: "line",
|
|
110
|
+
line: touchLine("up", event.at, screen)
|
|
111
|
+
});
|
|
112
|
+
pressed = false;
|
|
113
|
+
}
|
|
114
|
+
return steps;
|
|
115
|
+
}
|
|
116
|
+
const SIMHID_BUTTON = {
|
|
117
|
+
home: "home",
|
|
118
|
+
lock: "lock",
|
|
119
|
+
volumeUp: "volup",
|
|
120
|
+
volumeDown: "voldown"
|
|
121
|
+
};
|
|
122
|
+
/** A press: down, hold, up. */
|
|
123
|
+
function buttonSteps(button) {
|
|
124
|
+
const name = SIMHID_BUTTON[button];
|
|
125
|
+
return [
|
|
126
|
+
{
|
|
127
|
+
kind: "line",
|
|
128
|
+
line: `button ${name} down`
|
|
129
|
+
},
|
|
130
|
+
{
|
|
131
|
+
kind: "wait",
|
|
132
|
+
ms: 100
|
|
133
|
+
},
|
|
134
|
+
{
|
|
135
|
+
kind: "line",
|
|
136
|
+
line: `button ${name} up`
|
|
137
|
+
}
|
|
138
|
+
];
|
|
139
|
+
}
|
|
140
|
+
/** Reads the panel from a device's `sim.env`, which holds `SIMULATOR_MAINSCREEN_*` lines. */
|
|
141
|
+
function parseSimEnv(text) {
|
|
142
|
+
const values = /* @__PURE__ */ new Map();
|
|
143
|
+
for (const line of text.split("\n")) {
|
|
144
|
+
const found = /^SIMULATOR_MAINSCREEN_(WIDTH|HEIGHT|SCALE)=(\S+)$/.exec(line.trim());
|
|
145
|
+
if (found?.[1] && found[2]) values.set(found[1], Number(found[2]));
|
|
146
|
+
}
|
|
147
|
+
const width = values.get("WIDTH");
|
|
148
|
+
const height = values.get("HEIGHT");
|
|
149
|
+
const scale = values.get("SCALE");
|
|
150
|
+
if (!(width && height && scale && width > 0 && height > 0 && scale > 0)) throw new Error("sim.env has no usable SIMULATOR_MAINSCREEN_WIDTH, HEIGHT and SCALE.");
|
|
151
|
+
return {
|
|
152
|
+
pixels: {
|
|
153
|
+
width,
|
|
154
|
+
height
|
|
155
|
+
},
|
|
156
|
+
scale
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
function pointSize({ pixels, scale }) {
|
|
160
|
+
return {
|
|
161
|
+
width: pixels.width / scale,
|
|
162
|
+
height: pixels.height / scale
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
/** The phone's identity, which names its sockets. `sim.env` holds it as `SIMULATOR_UDID`. */
|
|
166
|
+
function parseSimulatorUdid(text) {
|
|
167
|
+
const found = /^SIMULATOR_UDID=([0-9A-Fa-f-]+)$/m.exec(text);
|
|
168
|
+
if (!found?.[1]) throw new Error("sim.env has no SIMULATOR_UDID.");
|
|
169
|
+
return found[1];
|
|
170
|
+
}
|
|
171
|
+
//#endregion
|
|
172
|
+
//#region ../server/src/backends/ax-hook.ts
|
|
173
|
+
const SPRINGBOARD_BUNDLE_ID = "com.apple.springboard";
|
|
174
|
+
/** The hook names its socket `x86sim-ax-<udid>-<pid>.sock` in the phone's runtime directory. */
|
|
175
|
+
const socketName = (udid) => new RegExp(`^x86sim-ax-${udid}-\\d+\\.sock$`);
|
|
176
|
+
/** The hook sockets of one phone among the files of a directory. */
|
|
177
|
+
function hookSocketNames(files, udid) {
|
|
178
|
+
const pattern = socketName(udid);
|
|
179
|
+
return files.filter((file) => pattern.test(file));
|
|
180
|
+
}
|
|
181
|
+
const MAX_TREE_DEPTH = 80;
|
|
182
|
+
const isRecord$2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
183
|
+
/** The hook answered with a reason instead of a tree, such as accessibility being off in the phone. */
|
|
184
|
+
var HookRefusedError = class extends Error {};
|
|
185
|
+
function fail(where, expected) {
|
|
186
|
+
throw new Error(`Hook reply is malformed at ${where}, expected ${expected}.`);
|
|
187
|
+
}
|
|
188
|
+
function parseFrame(value, where) {
|
|
189
|
+
if (!isRecord$2(value)) fail(where, "an object with x, y, width and height");
|
|
190
|
+
const { x, y, width, height } = value;
|
|
191
|
+
for (const [key, number] of Object.entries({
|
|
192
|
+
x,
|
|
193
|
+
y,
|
|
194
|
+
width,
|
|
195
|
+
height
|
|
196
|
+
})) if (typeof number !== "number" || !Number.isFinite(number)) fail(`${where}.${key}`, "a finite number");
|
|
197
|
+
return {
|
|
198
|
+
x,
|
|
199
|
+
y,
|
|
200
|
+
width,
|
|
201
|
+
height
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
function parseOptionalString(record, key, where) {
|
|
205
|
+
const value = record[key];
|
|
206
|
+
if (value === void 0) return void 0;
|
|
207
|
+
if (typeof value !== "string") fail(`${where}.${key}`, "a string");
|
|
208
|
+
return value;
|
|
209
|
+
}
|
|
210
|
+
function parseNode(value, where, depth) {
|
|
211
|
+
if (!isRecord$2(value)) fail(where, "an element object");
|
|
212
|
+
if (depth > MAX_TREE_DEPTH) fail(where, `a tree no deeper than ${MAX_TREE_DEPTH}`);
|
|
213
|
+
const { type, enabled, visible, children } = value;
|
|
214
|
+
if (typeof type !== "string" || !type.startsWith("XCUIElementType")) fail(`${where}.type`, "an XCUIElementType name");
|
|
215
|
+
if (typeof enabled !== "boolean") fail(`${where}.enabled`, "a boolean");
|
|
216
|
+
if (typeof visible !== "boolean") fail(`${where}.visible`, "a boolean");
|
|
217
|
+
if (!Array.isArray(children)) fail(`${where}.children`, "an array");
|
|
218
|
+
const name = parseOptionalString(value, "name", where);
|
|
219
|
+
const label = parseOptionalString(value, "label", where);
|
|
220
|
+
const text = parseOptionalString(value, "value", where);
|
|
221
|
+
return {
|
|
222
|
+
type,
|
|
223
|
+
...name === void 0 ? {} : { name },
|
|
224
|
+
...label === void 0 ? {} : { label },
|
|
225
|
+
...text === void 0 ? {} : { value: text },
|
|
226
|
+
frame: parseFrame(value.frame, `${where}.frame`),
|
|
227
|
+
enabled,
|
|
228
|
+
visible,
|
|
229
|
+
children: children.map((child, index) => parseNode(child, `${where}.children[${index}]`, depth + 1))
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
/** Checks one line of the hook's JSON at the boundary, so nothing downstream sees a loose shape. */
|
|
233
|
+
function parseHookReply(text) {
|
|
234
|
+
let json;
|
|
235
|
+
try {
|
|
236
|
+
json = JSON.parse(text);
|
|
237
|
+
} catch (error) {
|
|
238
|
+
throw new Error(`Hook reply is not JSON: ${error instanceof Error ? error.message : String(error)}`);
|
|
239
|
+
}
|
|
240
|
+
if (!isRecord$2(json)) fail("the reply", "an object");
|
|
241
|
+
if (typeof json.error === "string") throw new HookRefusedError(`The hook refused the request: ${json.error}`);
|
|
242
|
+
const { pid, bundleId, front } = json;
|
|
243
|
+
if (typeof pid !== "number" || !Number.isInteger(pid)) fail("pid", "an integer");
|
|
244
|
+
if (typeof bundleId !== "string") fail("bundleId", "a string");
|
|
245
|
+
const root = parseNode(json.root, "root", 0);
|
|
246
|
+
if (root.type !== "XCUIElementTypeApplication") fail("root.type", "XCUIElementTypeApplication");
|
|
247
|
+
if (front === void 0 || front === null) return {
|
|
248
|
+
pid,
|
|
249
|
+
bundleId,
|
|
250
|
+
...front === null ? { front: null } : {},
|
|
251
|
+
root
|
|
252
|
+
};
|
|
253
|
+
if (!isRecord$2(front)) fail("front", "null or an object with pid and bundleId");
|
|
254
|
+
if (typeof front.pid !== "number" || !Number.isInteger(front.pid)) fail("front.pid", "an integer");
|
|
255
|
+
if (typeof front.bundleId !== "string") fail("front.bundleId", "a string");
|
|
256
|
+
return {
|
|
257
|
+
pid,
|
|
258
|
+
bundleId,
|
|
259
|
+
front: {
|
|
260
|
+
pid: front.pid,
|
|
261
|
+
bundleId: front.bundleId
|
|
262
|
+
},
|
|
263
|
+
root
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
/** Asks one hook for its tree. Rejects on a dead socket, a timeout, an abort or a malformed answer. */
|
|
267
|
+
function queryHook(socketPath, timeoutMs, signal) {
|
|
268
|
+
return new Promise((resolve, reject) => {
|
|
269
|
+
const socket = createConnection(socketPath);
|
|
270
|
+
const chunks = [];
|
|
271
|
+
const finish = (error) => {
|
|
272
|
+
clearTimeout(timer);
|
|
273
|
+
signal.removeEventListener("abort", onAbort);
|
|
274
|
+
socket.destroy();
|
|
275
|
+
reject(error);
|
|
276
|
+
};
|
|
277
|
+
const onAbort = () => finish(/* @__PURE__ */ new Error(`The query to ${socketPath} was abandoned.`));
|
|
278
|
+
const timer = setTimeout(() => finish(/* @__PURE__ */ new Error(`No answer from ${socketPath} in ${timeoutMs} ms.`)), timeoutMs);
|
|
279
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
280
|
+
socket.on("connect", () => socket.write("tree\n"));
|
|
281
|
+
socket.on("data", (chunk) => chunks.push(chunk));
|
|
282
|
+
socket.on("error", finish);
|
|
283
|
+
socket.on("close", () => {
|
|
284
|
+
clearTimeout(timer);
|
|
285
|
+
signal.removeEventListener("abort", onAbort);
|
|
286
|
+
try {
|
|
287
|
+
resolve(parseHookReply(Buffer.concat(chunks).toString("utf8")));
|
|
288
|
+
} catch (error) {
|
|
289
|
+
reject(error instanceof Error ? error : new Error(String(error)));
|
|
290
|
+
}
|
|
291
|
+
});
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
/** The first value to settle that satisfies `match`, or `undefined` once every promise has settled without one. */
|
|
295
|
+
function firstMatching(promises, match) {
|
|
296
|
+
return new Promise((resolve) => {
|
|
297
|
+
let pending = promises.length;
|
|
298
|
+
if (pending === 0) resolve(void 0);
|
|
299
|
+
for (const promise of promises) promise.then((value) => {
|
|
300
|
+
if (value !== void 0 && match(value)) resolve(value);
|
|
301
|
+
else if ((pending -= 1) === 0) resolve(void 0);
|
|
302
|
+
});
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
/** SpringBoard names a front app that has not bound its hook socket yet, which a freshly launched app has not. */
|
|
306
|
+
var FrontAppNotListening = class extends Error {};
|
|
307
|
+
const pidOf = (name) => Number(/-(\d+)\.sock$/.exec(name)?.[1]);
|
|
308
|
+
/**
|
|
309
|
+
* The accessibility tree of what is on screen. SpringBoard names the app in front, or none for the
|
|
310
|
+
* home screen, so only SpringBoard and that app are waited for. A suspended app takes the
|
|
311
|
+
* connection and never answers, which would cost every other snapshot the full timeout. A socket
|
|
312
|
+
* whose process has died refuses the connection, and its file is removed.
|
|
313
|
+
*/
|
|
314
|
+
async function readFrontTree(dir, udid, timeoutMs) {
|
|
315
|
+
const abort = new AbortController();
|
|
316
|
+
const queries = /* @__PURE__ */ new Map();
|
|
317
|
+
/** A refusal says more than a missing answer, so it is what a failed snapshot reports. */
|
|
318
|
+
const refusals = /* @__PURE__ */ new Map();
|
|
319
|
+
for (const name of hookSocketNames(await readdir(dir), udid)) {
|
|
320
|
+
const socketPath = path.join(dir, name);
|
|
321
|
+
queries.set(pidOf(name), queryHook(socketPath, timeoutMs, abort.signal).catch(async (error) => {
|
|
322
|
+
if (error instanceof HookRefusedError) refusals.set(pidOf(name), error);
|
|
323
|
+
if (error instanceof Error && "code" in error && error.code === "ECONNREFUSED") await unlink(socketPath).catch(() => void 0);
|
|
324
|
+
}));
|
|
325
|
+
}
|
|
326
|
+
try {
|
|
327
|
+
const springboard = await firstMatching([...queries.values()], (reply) => reply.bundleId === SPRINGBOARD_BUNDLE_ID);
|
|
328
|
+
if (!springboard) throw refusals.values().next().value ?? /* @__PURE__ */ new Error(`SpringBoard's accessibility hook did not answer in ${dir}.`);
|
|
329
|
+
if (!springboard.front) return springboard.root;
|
|
330
|
+
if (!queries.has(springboard.front.pid)) throw new FrontAppNotListening(`The front app ${springboard.front.bundleId} (pid ${springboard.front.pid}) has no hook socket yet.`);
|
|
331
|
+
const app = await queries.get(springboard.front.pid);
|
|
332
|
+
if (!app) throw refusals.get(springboard.front.pid) ?? /* @__PURE__ */ new Error(`The front app ${springboard.front.bundleId} (pid ${springboard.front.pid}) did not answer on its hook socket.`);
|
|
333
|
+
return app.root;
|
|
334
|
+
} finally {
|
|
335
|
+
abort.abort();
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
const sleep$2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
339
|
+
/**
|
|
340
|
+
* {@link readFrontTree}, which waits up to `waitMs` for an app that was launched a moment ago to
|
|
341
|
+
* bind its hook socket. An app that answers badly, or a phone without SpringBoard's hook, fails at once.
|
|
342
|
+
*/
|
|
343
|
+
async function readFrontTreeWhenListening(dir, udid, timeoutMs, waitMs, retryMs = 500) {
|
|
344
|
+
const deadline = Date.now() + waitMs;
|
|
345
|
+
for (;;) try {
|
|
346
|
+
return await readFrontTree(dir, udid, timeoutMs);
|
|
347
|
+
} catch (error) {
|
|
348
|
+
if (!(error instanceof FrontAppNotListening) || Date.now() + retryMs > deadline) throw error;
|
|
349
|
+
await sleep$2(retryMs);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
//#endregion
|
|
353
|
+
//#region ../server/src/backends/x86sim.ts
|
|
354
|
+
/** Where the accessibility hooks bind their sockets. */
|
|
355
|
+
const defaultHookSocketDir = () => `/run/user/${userInfo().uid}`;
|
|
356
|
+
const CLI_TIMEOUT_MS = 6e4;
|
|
357
|
+
/** A hook that does not answer in this long fails the snapshot. A phone that is still booting answers in seconds. */
|
|
358
|
+
const HOOK_TIMEOUT_MS = 5e3;
|
|
359
|
+
/** A launched app takes a few seconds to start UIKit and bind its hook socket. */
|
|
360
|
+
const LAUNCH_WAIT_MS = 15e3;
|
|
361
|
+
const sleep$1 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
362
|
+
/** The simulator behind an x86Sim AppImage, driven by its CLI and by one simhid connection. */
|
|
363
|
+
var X86SimBackend = class {
|
|
364
|
+
#config;
|
|
365
|
+
#geometry;
|
|
366
|
+
#socket;
|
|
367
|
+
/** Touches and buttons share one finger, so their steps never interleave. */
|
|
368
|
+
#input = Promise.resolve();
|
|
369
|
+
constructor(config) {
|
|
370
|
+
this.#config = config;
|
|
371
|
+
}
|
|
372
|
+
#deviceGeometry() {
|
|
373
|
+
this.#geometry ??= readFile(path.join(this.#config.device, "sim.env"), "utf8").then(parseSimEnv);
|
|
374
|
+
return this.#geometry;
|
|
375
|
+
}
|
|
376
|
+
#cli(args) {
|
|
377
|
+
return new Promise((resolve, reject) => {
|
|
378
|
+
const launch = this.#config.cli(args);
|
|
379
|
+
execFile(launch.command, launch.args, {
|
|
380
|
+
env: {
|
|
381
|
+
...process.env,
|
|
382
|
+
...launch.env,
|
|
383
|
+
X86SIM_DEVICE: this.#config.device
|
|
384
|
+
},
|
|
385
|
+
timeout: CLI_TIMEOUT_MS
|
|
386
|
+
}, (error, stdout, stderr) => {
|
|
387
|
+
if (error) reject(/* @__PURE__ */ new Error(`x86sim ${args[0]} failed: ${stderr.trim() || error.message}`));
|
|
388
|
+
else resolve(stdout);
|
|
389
|
+
});
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
/** The connection is opened on first use and again after it drops. */
|
|
393
|
+
#connect() {
|
|
394
|
+
this.#socket ??= (async () => {
|
|
395
|
+
const socketPath = await realpath(path.join(this.#config.device, "data", "simhid.sock"));
|
|
396
|
+
const socket = createConnection(socketPath);
|
|
397
|
+
socket.setNoDelay(true);
|
|
398
|
+
socket.on("data", () => {});
|
|
399
|
+
const forget = () => {
|
|
400
|
+
this.#socket = void 0;
|
|
401
|
+
};
|
|
402
|
+
socket.on("close", forget);
|
|
403
|
+
socket.on("error", forget);
|
|
404
|
+
await new Promise((resolve, reject) => {
|
|
405
|
+
socket.once("connect", resolve);
|
|
406
|
+
socket.once("error", reject);
|
|
407
|
+
});
|
|
408
|
+
return socket;
|
|
409
|
+
})();
|
|
410
|
+
this.#socket.catch(() => {
|
|
411
|
+
this.#socket = void 0;
|
|
412
|
+
});
|
|
413
|
+
return this.#socket;
|
|
414
|
+
}
|
|
415
|
+
#play(steps) {
|
|
416
|
+
const run = this.#input.then(async () => {
|
|
417
|
+
const socket = await this.#connect();
|
|
418
|
+
for (const step of steps) if (step.kind === "wait") await sleep$1(step.ms);
|
|
419
|
+
else await new Promise((resolve, reject) => socket.write(`${step.line}\n`, (error) => error ? reject(error) : resolve()));
|
|
420
|
+
});
|
|
421
|
+
this.#input = run.catch(() => void 0);
|
|
422
|
+
return run;
|
|
423
|
+
}
|
|
424
|
+
async screen() {
|
|
425
|
+
return pointSize(await this.#deviceGeometry());
|
|
426
|
+
}
|
|
427
|
+
async accessibilityTree() {
|
|
428
|
+
const udid = parseSimulatorUdid(await readFile(path.join(this.#config.device, "sim.env"), "utf8"));
|
|
429
|
+
return await readFrontTreeWhenListening(this.#config.hookSocketDir ?? defaultHookSocketDir(), udid, HOOK_TIMEOUT_MS, LAUNCH_WAIT_MS);
|
|
430
|
+
}
|
|
431
|
+
async screenshot() {
|
|
432
|
+
const dir = await mkdtemp(path.join(tmpdir(), "x86sim-shot-"));
|
|
433
|
+
try {
|
|
434
|
+
const file = path.join(dir, "screen.png");
|
|
435
|
+
await this.#cli([
|
|
436
|
+
"screenshot",
|
|
437
|
+
file,
|
|
438
|
+
"1"
|
|
439
|
+
]);
|
|
440
|
+
return await readFile(file);
|
|
441
|
+
} finally {
|
|
442
|
+
await rm(dir, {
|
|
443
|
+
recursive: true,
|
|
444
|
+
force: true
|
|
445
|
+
});
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
async touch(events) {
|
|
449
|
+
await this.#play(touchSteps(events, await this.screen()));
|
|
450
|
+
}
|
|
451
|
+
async typeText(text) {
|
|
452
|
+
await this.#cli(["type", text]);
|
|
453
|
+
}
|
|
454
|
+
async pressButton(button) {
|
|
455
|
+
await this.#play(buttonSteps(button));
|
|
456
|
+
}
|
|
457
|
+
async installApp(appPath) {
|
|
458
|
+
await this.#cli(["install", appPath]);
|
|
459
|
+
}
|
|
460
|
+
async launchApp(bundleId) {
|
|
461
|
+
await this.#cli(["launch", bundleId]);
|
|
462
|
+
}
|
|
463
|
+
/** Ending an app that is not running is not an error, as in Appium and `simctl terminate`, so a relaunch can start from either state. */
|
|
464
|
+
async terminateApp(bundleId) {
|
|
465
|
+
await this.#cli(["terminate", bundleId]).catch((error) => {
|
|
466
|
+
if (!/not running/.test(error.message)) throw error;
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
async openUrl(url) {
|
|
470
|
+
await this.#cli(["openurl", url]);
|
|
471
|
+
}
|
|
472
|
+
};
|
|
473
|
+
//#endregion
|
|
474
|
+
//#region ../server/src/errors.ts
|
|
475
|
+
/**
|
|
476
|
+
* A W3C WebDriver error. `error` is the spec's error code and the HTTP status follows the
|
|
477
|
+
* spec's table, so clients can tell "this route does not exist" from "this request is bad".
|
|
478
|
+
*/
|
|
479
|
+
var WebDriverError = class extends Error {
|
|
480
|
+
error;
|
|
481
|
+
status;
|
|
482
|
+
constructor(error, status, message) {
|
|
483
|
+
super(message);
|
|
484
|
+
this.name = "WebDriverError";
|
|
485
|
+
this.error = error;
|
|
486
|
+
this.status = status;
|
|
487
|
+
}
|
|
488
|
+
};
|
|
489
|
+
const unknownCommand = (message) => new WebDriverError("unknown command", 404, message);
|
|
490
|
+
const invalidArgument = (message) => new WebDriverError("invalid argument", 400, message);
|
|
491
|
+
const invalidSessionId = (id) => new WebDriverError("invalid session id", 404, `No active session with id ${id}`);
|
|
492
|
+
const sessionNotCreated = (message) => new WebDriverError("session not created", 500, message);
|
|
493
|
+
const unsupportedOperation = (message) => new WebDriverError("unsupported operation", 500, message);
|
|
494
|
+
const unknownError = (message) => new WebDriverError("unknown error", 500, message);
|
|
495
|
+
//#endregion
|
|
496
|
+
//#region ../server/src/router.ts
|
|
497
|
+
const isReply = (result) => typeof result === "object" && result !== null && "reply" in result;
|
|
498
|
+
function compile(route) {
|
|
499
|
+
const names = [];
|
|
500
|
+
const source = route.path.split("/").map((segment) => {
|
|
501
|
+
if (!segment.startsWith(":")) return segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
502
|
+
names.push(segment.slice(1));
|
|
503
|
+
return "([^/]+)";
|
|
504
|
+
}).join("/");
|
|
505
|
+
return {
|
|
506
|
+
...route,
|
|
507
|
+
pattern: new RegExp(`^${source}$`),
|
|
508
|
+
names
|
|
509
|
+
};
|
|
510
|
+
}
|
|
511
|
+
/**
|
|
512
|
+
* One matcher over a route table. An unknown path or method is the W3C `unknown command`
|
|
513
|
+
* error, which clients read as "this driver does not implement that route".
|
|
514
|
+
*/
|
|
515
|
+
function createRouter(routes) {
|
|
516
|
+
const compiled = routes.map(compile);
|
|
517
|
+
return { match(method, pathname) {
|
|
518
|
+
for (const route of compiled) {
|
|
519
|
+
if (route.method !== method) continue;
|
|
520
|
+
const found = route.pattern.exec(pathname);
|
|
521
|
+
if (!found) continue;
|
|
522
|
+
return {
|
|
523
|
+
route,
|
|
524
|
+
params: Object.fromEntries(route.names.map((name, index) => [name, decodeURIComponent(found[index + 1] ?? "")]))
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
throw unknownCommand(`Unknown command: ${method} ${pathname}`);
|
|
528
|
+
} };
|
|
529
|
+
}
|
|
530
|
+
//#endregion
|
|
531
|
+
//#region ../server/src/actions.ts
|
|
532
|
+
/** How often an interpolated drag reports a position. 16 ms is about one display frame. */
|
|
533
|
+
const MOVE_STEP_MS = 16;
|
|
534
|
+
const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
535
|
+
function parsePointerAction(raw) {
|
|
536
|
+
if (!isRecord$1(raw)) throw invalidArgument("Pointer action must be an object.");
|
|
537
|
+
const duration = raw.duration;
|
|
538
|
+
if (duration !== void 0 && (typeof duration !== "number" || !(duration >= 0))) throw invalidArgument("Pointer action duration must be a non-negative number.");
|
|
539
|
+
switch (raw.type) {
|
|
540
|
+
case "pointerMove":
|
|
541
|
+
if (typeof raw.x !== "number" || typeof raw.y !== "number") throw invalidArgument("pointerMove needs numeric x and y.");
|
|
542
|
+
if (raw.origin !== void 0 && raw.origin !== "viewport") throw invalidArgument("Only the viewport pointer origin is supported.");
|
|
543
|
+
return {
|
|
544
|
+
type: "pointerMove",
|
|
545
|
+
x: raw.x,
|
|
546
|
+
y: raw.y,
|
|
547
|
+
...duration === void 0 ? {} : { duration }
|
|
548
|
+
};
|
|
549
|
+
case "pointerDown":
|
|
550
|
+
case "pointerUp": return { type: raw.type };
|
|
551
|
+
case "pause": return {
|
|
552
|
+
type: "pause",
|
|
553
|
+
...duration === void 0 ? {} : { duration }
|
|
554
|
+
};
|
|
555
|
+
default: throw invalidArgument(`Unsupported pointer action type: ${String(raw.type)}`);
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
/** The boundary: untrusted `POST /actions` body to typed sequences. */
|
|
559
|
+
function parseActions(body) {
|
|
560
|
+
if (!isRecord$1(body) || !Array.isArray(body.actions)) throw invalidArgument("Request body needs an \"actions\" array.");
|
|
561
|
+
return body.actions.map((raw) => {
|
|
562
|
+
if (!isRecord$1(raw) || typeof raw.id !== "string" || !Array.isArray(raw.actions)) throw invalidArgument("Each action sequence needs a string id and an actions array.");
|
|
563
|
+
if (raw.type === "pointer") {
|
|
564
|
+
const parameters = isRecord$1(raw.parameters) ? raw.parameters : void 0;
|
|
565
|
+
return {
|
|
566
|
+
type: "pointer",
|
|
567
|
+
id: raw.id,
|
|
568
|
+
...parameters ? { parameters } : {},
|
|
569
|
+
actions: raw.actions.map(parsePointerAction)
|
|
570
|
+
};
|
|
571
|
+
}
|
|
572
|
+
if (raw.type === "key" || raw.type === "none" || raw.type === "wheel") return {
|
|
573
|
+
type: raw.type,
|
|
574
|
+
id: raw.id,
|
|
575
|
+
actions: raw.actions
|
|
576
|
+
};
|
|
577
|
+
throw invalidArgument(`Unsupported action source type: ${String(raw.type)}`);
|
|
578
|
+
});
|
|
579
|
+
}
|
|
580
|
+
function lerp(from, to, t) {
|
|
581
|
+
return {
|
|
582
|
+
x: from.x + (to.x - from.x) * t,
|
|
583
|
+
y: from.y + (to.y - from.y) * t
|
|
584
|
+
};
|
|
585
|
+
}
|
|
586
|
+
/**
|
|
587
|
+
* Flattens W3C pointer actions to the single-finger touch stream a simhid-style device takes.
|
|
588
|
+
*
|
|
589
|
+
* - The pointer starts at (0, 0), as in the spec, and `pointerMove` outside a press only
|
|
590
|
+
* repositions it, so a tap is `down` and `up` at the last position.
|
|
591
|
+
* - A timed drag becomes `move` steps every 16 ms, so the device sees a gesture with velocity
|
|
592
|
+
* rather than a jump after a wait.
|
|
593
|
+
* - A timed move outside a press becomes a `pause`.
|
|
594
|
+
* - Key, none and wheel sources are ignored here. A second pointer sequence is refused,
|
|
595
|
+
* because one touch point cannot play two fingers.
|
|
596
|
+
*/
|
|
597
|
+
function toTouchEvents(sequences) {
|
|
598
|
+
const pointers = sequences.filter((sequence) => sequence.type === "pointer");
|
|
599
|
+
if (pointers.length > 1) throw unsupportedOperation("Multi-pointer actions are not supported by this touch backend.");
|
|
600
|
+
const pointer = pointers[0];
|
|
601
|
+
if (pointer?.type !== "pointer") return [];
|
|
602
|
+
const events = [];
|
|
603
|
+
let position = {
|
|
604
|
+
x: 0,
|
|
605
|
+
y: 0
|
|
606
|
+
};
|
|
607
|
+
let pressed = false;
|
|
608
|
+
for (const action of pointer.actions) switch (action.type) {
|
|
609
|
+
case "pointerMove": {
|
|
610
|
+
const target = {
|
|
611
|
+
x: action.x,
|
|
612
|
+
y: action.y
|
|
613
|
+
};
|
|
614
|
+
const duration = action.duration ?? 0;
|
|
615
|
+
if (!pressed) {
|
|
616
|
+
if (duration > 0) events.push({
|
|
617
|
+
kind: "pause",
|
|
618
|
+
ms: duration
|
|
619
|
+
});
|
|
620
|
+
} else if (duration <= MOVE_STEP_MS) events.push({
|
|
621
|
+
kind: "move",
|
|
622
|
+
at: target
|
|
623
|
+
});
|
|
624
|
+
else {
|
|
625
|
+
const steps = Math.ceil(duration / MOVE_STEP_MS);
|
|
626
|
+
for (let step = 1; step <= steps; step += 1) {
|
|
627
|
+
events.push({
|
|
628
|
+
kind: "pause",
|
|
629
|
+
ms: duration / steps
|
|
630
|
+
});
|
|
631
|
+
events.push({
|
|
632
|
+
kind: "move",
|
|
633
|
+
at: step === steps ? target : lerp(position, target, step / steps)
|
|
634
|
+
});
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
position = target;
|
|
638
|
+
break;
|
|
639
|
+
}
|
|
640
|
+
case "pointerDown":
|
|
641
|
+
if (!pressed) events.push({
|
|
642
|
+
kind: "down",
|
|
643
|
+
at: position
|
|
644
|
+
});
|
|
645
|
+
pressed = true;
|
|
646
|
+
break;
|
|
647
|
+
case "pointerUp":
|
|
648
|
+
if (pressed) events.push({
|
|
649
|
+
kind: "up",
|
|
650
|
+
at: position
|
|
651
|
+
});
|
|
652
|
+
pressed = false;
|
|
653
|
+
break;
|
|
654
|
+
case "pause": if ((action.duration ?? 0) > 0) events.push({
|
|
655
|
+
kind: "pause",
|
|
656
|
+
ms: action.duration ?? 0
|
|
657
|
+
});
|
|
658
|
+
}
|
|
659
|
+
return events;
|
|
660
|
+
}
|
|
661
|
+
//#endregion
|
|
662
|
+
//#region ../server/src/xcui-source.ts
|
|
663
|
+
const XML_ESCAPES = {
|
|
664
|
+
"&": "&",
|
|
665
|
+
"<": "<",
|
|
666
|
+
">": ">",
|
|
667
|
+
"\"": """,
|
|
668
|
+
"'": "'",
|
|
669
|
+
"\n": " ",
|
|
670
|
+
"\r": " ",
|
|
671
|
+
" ": "	"
|
|
672
|
+
};
|
|
673
|
+
function escapeAttribute(value) {
|
|
674
|
+
return value.replace(/[&<>"'\n\r\t]/g, (char) => XML_ESCAPES[char] ?? char);
|
|
675
|
+
}
|
|
676
|
+
function attributes(node) {
|
|
677
|
+
return [
|
|
678
|
+
["type", node.type],
|
|
679
|
+
["name", node.name],
|
|
680
|
+
["label", node.label],
|
|
681
|
+
["value", node.value],
|
|
682
|
+
["enabled", String(node.enabled)],
|
|
683
|
+
["visible", String(node.visible)],
|
|
684
|
+
["x", String(node.frame.x)],
|
|
685
|
+
["y", String(node.frame.y)],
|
|
686
|
+
["width", String(node.frame.width)],
|
|
687
|
+
["height", String(node.frame.height)]
|
|
688
|
+
].flatMap(([key, value]) => value === void 0 ? [] : [`${key}="${escapeAttribute(value)}"`]).join(" ");
|
|
689
|
+
}
|
|
690
|
+
function element(node, depth) {
|
|
691
|
+
const indent = " ".repeat(depth);
|
|
692
|
+
const open = `${indent}<${node.type} ${attributes(node)}`;
|
|
693
|
+
if (node.children.length === 0) return `${open} />`;
|
|
694
|
+
return `${open}>\n${node.children.map((child) => element(child, depth + 1)).join("\n")}\n${indent}</${node.type}>`;
|
|
695
|
+
}
|
|
696
|
+
/**
|
|
697
|
+
* The XCUITest page source shape: an `AppiumAUT` wrapper around the element tree, one tag per
|
|
698
|
+
* element named by its XCUIElementType, with geometry as `x`, `y`, `width` and `height`.
|
|
699
|
+
* Absent `name`, `label` and `value` are omitted, as XCUITest omits null attributes.
|
|
700
|
+
*/
|
|
701
|
+
function toXcuiSource(root) {
|
|
702
|
+
return `<?xml version="1.0" encoding="UTF-8"?>\n<AppiumAUT>\n${element(root, 1)}\n</AppiumAUT>`;
|
|
703
|
+
}
|
|
704
|
+
//#endregion
|
|
705
|
+
//#region ../server/src/routes.ts
|
|
706
|
+
const SESSION_PREFIX = "/session/:sessionId";
|
|
707
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
708
|
+
function requireString(body, ...keys) {
|
|
709
|
+
if (isRecord(body)) for (const key of keys) {
|
|
710
|
+
const value = body[key];
|
|
711
|
+
if (typeof value === "string" && value.length > 0) return value;
|
|
712
|
+
}
|
|
713
|
+
throw invalidArgument(`Request body needs a string "${keys.join("\" or \"")}".`);
|
|
714
|
+
}
|
|
715
|
+
const HARDWARE_BUTTONS = {
|
|
716
|
+
home: "home",
|
|
717
|
+
volumeup: "volumeUp",
|
|
718
|
+
volumedown: "volumeDown"
|
|
719
|
+
};
|
|
720
|
+
/** The `mobile:` scripts of XCUITest that this server answers. Others are `unknown command`. */
|
|
721
|
+
const MOBILE_SCRIPTS = {
|
|
722
|
+
"mobile: pressButton": async (backend, args) => {
|
|
723
|
+
const button = HARDWARE_BUTTONS[String(args.name).toLowerCase()];
|
|
724
|
+
if (!button) throw invalidArgument(`Unsupported hardware button: ${String(args.name)}`);
|
|
725
|
+
await backend.pressButton(button);
|
|
726
|
+
return null;
|
|
727
|
+
},
|
|
728
|
+
"mobile: deepLink": async (backend, args) => {
|
|
729
|
+
await backend.openUrl(requireString(args, "url"));
|
|
730
|
+
return null;
|
|
731
|
+
},
|
|
732
|
+
"mobile: activateApp": async (backend, args) => {
|
|
733
|
+
await backend.launchApp(requireString(args, "bundleId", "appId"));
|
|
734
|
+
return null;
|
|
735
|
+
},
|
|
736
|
+
"mobile: terminateApp": async (backend, args) => {
|
|
737
|
+
await backend.terminateApp(requireString(args, "bundleId", "appId"));
|
|
738
|
+
return true;
|
|
739
|
+
}
|
|
740
|
+
};
|
|
741
|
+
function windowRect(backend) {
|
|
742
|
+
return backend.screen().then((size) => ({
|
|
743
|
+
x: 0,
|
|
744
|
+
y: 0,
|
|
745
|
+
...size
|
|
746
|
+
}));
|
|
747
|
+
}
|
|
748
|
+
/** The WebDriver and Appium routes this server implements. */
|
|
749
|
+
function webDriverRoutes(backend, sessions) {
|
|
750
|
+
const inSession = (method, suffix, handler) => ({
|
|
751
|
+
method,
|
|
752
|
+
path: `${SESSION_PREFIX}${suffix}`,
|
|
753
|
+
handler
|
|
754
|
+
});
|
|
755
|
+
return [
|
|
756
|
+
{
|
|
757
|
+
method: "GET",
|
|
758
|
+
path: "/status",
|
|
759
|
+
handler: async () => ({
|
|
760
|
+
ready: true,
|
|
761
|
+
message: "x86sim-webdriver ready"
|
|
762
|
+
})
|
|
763
|
+
},
|
|
764
|
+
{
|
|
765
|
+
method: "POST",
|
|
766
|
+
path: "/session",
|
|
767
|
+
handler: async ({ body }) => {
|
|
768
|
+
if (sessions.current) throw sessionNotCreated(`Session ${sessions.current.id} is still active.`);
|
|
769
|
+
const requested = isRecord(body) && isRecord(body.capabilities) ? body.capabilities : {};
|
|
770
|
+
const alwaysMatch = isRecord(requested.alwaysMatch) ? requested.alwaysMatch : {};
|
|
771
|
+
const session = {
|
|
772
|
+
id: randomUUID(),
|
|
773
|
+
capabilities: {
|
|
774
|
+
...alwaysMatch,
|
|
775
|
+
platformName: "iOS",
|
|
776
|
+
"appium:automationName": "XCUITest"
|
|
777
|
+
}
|
|
778
|
+
};
|
|
779
|
+
sessions.current = session;
|
|
780
|
+
return {
|
|
781
|
+
sessionId: session.id,
|
|
782
|
+
capabilities: session.capabilities
|
|
783
|
+
};
|
|
784
|
+
}
|
|
785
|
+
},
|
|
786
|
+
inSession("DELETE", "", async ({ params }) => {
|
|
787
|
+
if (sessions.current?.id === params.sessionId) sessions.current = void 0;
|
|
788
|
+
return null;
|
|
789
|
+
}),
|
|
790
|
+
inSession("GET", "/source", async () => toXcuiSource(await backend.accessibilityTree())),
|
|
791
|
+
inSession("GET", "/screenshot", async () => (await backend.screenshot()).toString("base64")),
|
|
792
|
+
inSession("GET", "/window/rect", async () => await windowRect(backend)),
|
|
793
|
+
inSession("POST", "/actions", async ({ body }) => {
|
|
794
|
+
const events = toTouchEvents(parseActions(body));
|
|
795
|
+
if (events.length > 0) await backend.touch(events);
|
|
796
|
+
return null;
|
|
797
|
+
}),
|
|
798
|
+
inSession("DELETE", "/actions", async () => null),
|
|
799
|
+
inSession("POST", "/keys", async ({ body }) => {
|
|
800
|
+
const value = isRecord(body) ? body.value : void 0;
|
|
801
|
+
if (!Array.isArray(value)) throw invalidArgument("Request body needs a \"value\" array.");
|
|
802
|
+
await backend.typeText(value.map(String).join(""));
|
|
803
|
+
return null;
|
|
804
|
+
}),
|
|
805
|
+
inSession("POST", "/appium/device/install_app", async ({ body }) => {
|
|
806
|
+
await backend.installApp(requireString(body, "appPath"));
|
|
807
|
+
return null;
|
|
808
|
+
}),
|
|
809
|
+
inSession("POST", "/appium/device/activate_app", async ({ body }) => {
|
|
810
|
+
await backend.launchApp(requireString(body, "appId", "bundleId"));
|
|
811
|
+
return null;
|
|
812
|
+
}),
|
|
813
|
+
inSession("POST", "/appium/device/terminate_app", async ({ body }) => {
|
|
814
|
+
await backend.terminateApp(requireString(body, "appId", "bundleId"));
|
|
815
|
+
return true;
|
|
816
|
+
}),
|
|
817
|
+
inSession("POST", "/execute/sync", async ({ body }) => {
|
|
818
|
+
const script = requireString(body, "script");
|
|
819
|
+
const handler = MOBILE_SCRIPTS[script];
|
|
820
|
+
if (!handler) throw unknownCommand(`Unknown mobile command: ${script}`);
|
|
821
|
+
const args = isRecord(body) && Array.isArray(body.args) ? body.args[0] : void 0;
|
|
822
|
+
return await handler(backend, isRecord(args) ? args : {});
|
|
823
|
+
})
|
|
824
|
+
];
|
|
825
|
+
}
|
|
826
|
+
function requireActiveSession(sessions, id) {
|
|
827
|
+
if (sessions.current?.id !== id) throw invalidSessionId(id);
|
|
828
|
+
return sessions.current;
|
|
829
|
+
}
|
|
830
|
+
//#endregion
|
|
831
|
+
//#region ../server/src/server.ts
|
|
832
|
+
const BODY_LOG_LIMIT = 160;
|
|
833
|
+
async function readJson(request) {
|
|
834
|
+
const chunks = [];
|
|
835
|
+
for await (const chunk of request) chunks.push(chunk);
|
|
836
|
+
const text = Buffer.concat(chunks).toString("utf8");
|
|
837
|
+
if (text.length === 0) return void 0;
|
|
838
|
+
try {
|
|
839
|
+
return JSON.parse(text);
|
|
840
|
+
} catch {
|
|
841
|
+
throw invalidArgument("Request body is not valid JSON.");
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
function send(response, status, json) {
|
|
845
|
+
const payload = JSON.stringify(json);
|
|
846
|
+
response.writeHead(status, {
|
|
847
|
+
"content-type": "application/json; charset=utf-8",
|
|
848
|
+
"content-length": Buffer.byteLength(payload)
|
|
849
|
+
});
|
|
850
|
+
response.end(payload);
|
|
851
|
+
}
|
|
852
|
+
function errorReply(error) {
|
|
853
|
+
const failure = error instanceof WebDriverError ? error : unknownError(String(error));
|
|
854
|
+
return {
|
|
855
|
+
status: failure.status,
|
|
856
|
+
json: { value: {
|
|
857
|
+
error: failure.error,
|
|
858
|
+
message: failure.message,
|
|
859
|
+
stacktrace: ""
|
|
860
|
+
} }
|
|
861
|
+
};
|
|
862
|
+
}
|
|
863
|
+
function bodySummary(body) {
|
|
864
|
+
if (body === void 0) return "";
|
|
865
|
+
const text = JSON.stringify(body);
|
|
866
|
+
return ` ${text.length > BODY_LOG_LIMIT ? `${text.slice(0, BODY_LOG_LIMIT)}...` : text}`;
|
|
867
|
+
}
|
|
868
|
+
function createServer$2(options) {
|
|
869
|
+
const sessions = { current: void 0 };
|
|
870
|
+
const router = createRouter([...webDriverRoutes(options.backend, sessions), ...options.extraRoutes ?? []]);
|
|
871
|
+
const log = options.log ?? ((line) => process.stderr.write(`${line}\n`));
|
|
872
|
+
return createServer$1(async (request, response) => {
|
|
873
|
+
const started = Date.now();
|
|
874
|
+
const method = request.method ?? "GET";
|
|
875
|
+
const { pathname } = new URL(request.url ?? "/", "http://localhost");
|
|
876
|
+
let body;
|
|
877
|
+
let reply;
|
|
878
|
+
try {
|
|
879
|
+
body = await readJson(request);
|
|
880
|
+
const { route, params } = router.match(method, pathname);
|
|
881
|
+
if (params.sessionId !== void 0) requireActiveSession(sessions, params.sessionId);
|
|
882
|
+
const result = await route.handler({
|
|
883
|
+
params,
|
|
884
|
+
body
|
|
885
|
+
});
|
|
886
|
+
reply = isReply(result) ? result.reply : {
|
|
887
|
+
status: 200,
|
|
888
|
+
json: { value: result ?? null }
|
|
889
|
+
};
|
|
890
|
+
} catch (error) {
|
|
891
|
+
reply = errorReply(error);
|
|
892
|
+
}
|
|
893
|
+
send(response, reply.status, reply.json);
|
|
894
|
+
log(`${method} ${pathname} -> ${reply.status} ${Date.now() - started}ms${bodySummary(body)}`);
|
|
895
|
+
});
|
|
896
|
+
}
|
|
897
|
+
//#endregion
|
|
898
|
+
//#region src/cli/accessibility-prefs.ts
|
|
899
|
+
/**
|
|
900
|
+
* A Python 3 program that reads or sets the phone's accessibility preferences. x86Sim needs
|
|
901
|
+
* Python 3, so it is on every machine that runs this. The Python standard library reads and
|
|
902
|
+
* writes binary property lists, which Node does not.
|
|
903
|
+
*
|
|
904
|
+
* The first two keys make UIKit describe its controls. `AutomationEnabled` makes UIKit build
|
|
905
|
+
* them the way XCTest sees them, which is the element types the hook reports.
|
|
906
|
+
*
|
|
907
|
+
* `check <file>` prints `true` when all three keys are on. `enable <file>` turns them on, keeps
|
|
908
|
+
* every other key, and replaces the file in one rename so the phone never sees half a file. Run
|
|
909
|
+
* it only while the phone is stopped, because a running phone's `cfprefsd` would overwrite it.
|
|
910
|
+
*/
|
|
911
|
+
const ACCESSIBILITY_PREFS_SCRIPT = `
|
|
912
|
+
import os, plistlib, sys, tempfile
|
|
913
|
+
mode, path = sys.argv[1], sys.argv[2]
|
|
914
|
+
KEYS = ("ApplicationAccessibilityEnabled", "AccessibilityEnabled", "AutomationEnabled")
|
|
915
|
+
try:
|
|
916
|
+
with open(path, "rb") as f:
|
|
917
|
+
prefs = plistlib.load(f)
|
|
918
|
+
except FileNotFoundError:
|
|
919
|
+
prefs = {}
|
|
920
|
+
on = all(prefs.get(key) is True for key in KEYS)
|
|
921
|
+
if mode == "check":
|
|
922
|
+
print("true" if on else "false")
|
|
923
|
+
elif not on:
|
|
924
|
+
prefs.update({key: True for key in KEYS})
|
|
925
|
+
folder = os.path.dirname(path)
|
|
926
|
+
os.makedirs(folder, exist_ok=True)
|
|
927
|
+
fd, temp = tempfile.mkstemp(dir=folder, prefix=".ax-prefs-", suffix=".tmp")
|
|
928
|
+
try:
|
|
929
|
+
with os.fdopen(fd, "wb") as f:
|
|
930
|
+
plistlib.dump(prefs, f, fmt=plistlib.FMT_BINARY)
|
|
931
|
+
os.chmod(temp, os.stat(path).st_mode & 0o777 if os.path.exists(path) else 0o644)
|
|
932
|
+
os.replace(temp, path)
|
|
933
|
+
except BaseException:
|
|
934
|
+
os.unlink(temp)
|
|
935
|
+
raise
|
|
936
|
+
`;
|
|
937
|
+
//#endregion
|
|
938
|
+
//#region src/cli/phone-control.ts
|
|
939
|
+
/** x86Sim's `wait home` limit in seconds. */
|
|
940
|
+
const HOME_TIMEOUT_S = 540;
|
|
941
|
+
const HOOK_WAIT_MS = 9e4;
|
|
942
|
+
const POLL_MS = 2e3;
|
|
943
|
+
const PROBE_TIMEOUT_MS = 5e3;
|
|
944
|
+
const hasRenderNode = async () => (await readdir("/dev/dri").catch(() => [])).some((name) => name.startsWith("renderD"));
|
|
945
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
946
|
+
/**
|
|
947
|
+
* Runs a command to its exit. It waits for `exit`, not `close`, because the boot script leaves
|
|
948
|
+
* the phone running and the phone's processes keep the output pipes open.
|
|
949
|
+
*/
|
|
950
|
+
function run(launch, stream) {
|
|
951
|
+
return new Promise((resolve, reject) => {
|
|
952
|
+
const child = spawn(launch.command, launch.args, {
|
|
953
|
+
env: {
|
|
954
|
+
...process.env,
|
|
955
|
+
...launch.env
|
|
956
|
+
},
|
|
957
|
+
...launch.cwd === void 0 ? {} : { cwd: launch.cwd },
|
|
958
|
+
stdio: [
|
|
959
|
+
"ignore",
|
|
960
|
+
"pipe",
|
|
961
|
+
"pipe"
|
|
962
|
+
]
|
|
963
|
+
});
|
|
964
|
+
let output = "";
|
|
965
|
+
const collect = (chunk) => {
|
|
966
|
+
const text = chunk.toString("utf8");
|
|
967
|
+
output += text;
|
|
968
|
+
stream?.(text);
|
|
969
|
+
};
|
|
970
|
+
child.stdout.on("data", collect);
|
|
971
|
+
child.stderr.on("data", collect);
|
|
972
|
+
child.once("error", reject);
|
|
973
|
+
child.once("exit", (code) => {
|
|
974
|
+
setTimeout(() => {
|
|
975
|
+
child.stdout.destroy();
|
|
976
|
+
child.stderr.destroy();
|
|
977
|
+
}, 200).unref();
|
|
978
|
+
resolve({
|
|
979
|
+
code,
|
|
980
|
+
tail: output.trimEnd().split("\n").slice(-40).join("\n")
|
|
981
|
+
});
|
|
982
|
+
});
|
|
983
|
+
});
|
|
984
|
+
}
|
|
985
|
+
async function runPython(args) {
|
|
986
|
+
const finished = await run({
|
|
987
|
+
command: "python3",
|
|
988
|
+
args: [
|
|
989
|
+
"-I",
|
|
990
|
+
"-c",
|
|
991
|
+
ACCESSIBILITY_PREFS_SCRIPT,
|
|
992
|
+
...args
|
|
993
|
+
],
|
|
994
|
+
env: {}
|
|
995
|
+
}, void 0);
|
|
996
|
+
if (finished.code !== 0) throw new Error(`Could not read or write the phone's accessibility preferences.\n${finished.tail}`);
|
|
997
|
+
return finished.tail;
|
|
998
|
+
}
|
|
999
|
+
function createPhoneControl(config) {
|
|
1000
|
+
const prefsFile = path.join(config.device, "data", "Library", "Preferences", "com.apple.Accessibility.plist");
|
|
1001
|
+
const stream = config.verbose ? config.write : void 0;
|
|
1002
|
+
const x86simEnv = { X86SIM_DEVICE: config.device };
|
|
1003
|
+
const bootEnv = {
|
|
1004
|
+
A64_DEVICE: config.device,
|
|
1005
|
+
X86SIM_DEVICE: config.device
|
|
1006
|
+
};
|
|
1007
|
+
async function script(env, what) {
|
|
1008
|
+
const launch = config.x86sim.boot();
|
|
1009
|
+
const finished = await run({
|
|
1010
|
+
...launch,
|
|
1011
|
+
env: {
|
|
1012
|
+
...launch.env,
|
|
1013
|
+
...env
|
|
1014
|
+
}
|
|
1015
|
+
}, stream);
|
|
1016
|
+
if (finished.code !== 0) throw new Error(`x86Sim failed to ${what} (exit ${finished.code}).\n${finished.tail}`);
|
|
1017
|
+
}
|
|
1018
|
+
async function springBoardAnswers(simEnv) {
|
|
1019
|
+
const udid = parseSimulatorUdid(simEnv);
|
|
1020
|
+
const dir = config.hookSocketDir ?? defaultHookSocketDir();
|
|
1021
|
+
const abort = new AbortController();
|
|
1022
|
+
try {
|
|
1023
|
+
const replies = hookSocketNames(await readdir(dir), udid).map((name) => queryHook(path.join(dir, name), PROBE_TIMEOUT_MS, abort.signal).then((reply) => reply.bundleId === SPRINGBOARD_BUNDLE_ID, () => false));
|
|
1024
|
+
return (await Promise.all(replies)).some(Boolean);
|
|
1025
|
+
} finally {
|
|
1026
|
+
abort.abort();
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
async function hookState() {
|
|
1030
|
+
const simEnv = await readFile(path.join(config.device, "sim.env"), "utf8");
|
|
1031
|
+
if (!await springBoardAnswers(simEnv)) return "none";
|
|
1032
|
+
return await loadedHookIsPackaged(simEnv, config.hook) ? "current" : "outdated";
|
|
1033
|
+
}
|
|
1034
|
+
async function waitForHook() {
|
|
1035
|
+
const deadline = Date.now() + HOOK_WAIT_MS;
|
|
1036
|
+
while (await hookState() === "none") {
|
|
1037
|
+
if (Date.now() > deadline) throw new Error(`The phone reached the home screen, but SpringBoard's accessibility hook did not answer in ${HOOK_WAIT_MS / 1e3} s. Check that ${config.hook} exists, then run with --verbose.`);
|
|
1038
|
+
await sleep(POLL_MS);
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
return {
|
|
1042
|
+
async observe() {
|
|
1043
|
+
const running = await isPhoneRunning(config.device);
|
|
1044
|
+
return {
|
|
1045
|
+
running,
|
|
1046
|
+
hook: running ? await hookState() : "none",
|
|
1047
|
+
axPrefs: await runPython(["check", prefsFile]) === "true"
|
|
1048
|
+
};
|
|
1049
|
+
},
|
|
1050
|
+
async perform(action) {
|
|
1051
|
+
switch (action) {
|
|
1052
|
+
case "stop": return await script({
|
|
1053
|
+
...bootEnv,
|
|
1054
|
+
A64_STOP_ONLY: "1"
|
|
1055
|
+
}, "stop the phone");
|
|
1056
|
+
case "write-prefs":
|
|
1057
|
+
await runPython(["enable", prefsFile]);
|
|
1058
|
+
return;
|
|
1059
|
+
case "boot": {
|
|
1060
|
+
const gpu = await (config.hasGpu ?? hasRenderNode)();
|
|
1061
|
+
return await script({
|
|
1062
|
+
...bootEnv,
|
|
1063
|
+
X86SIM_INSERT: config.hook,
|
|
1064
|
+
A64_KEEP: "1",
|
|
1065
|
+
...gpu ? {} : { X86SIM_METAL: "0" }
|
|
1066
|
+
}, "boot the phone");
|
|
1067
|
+
}
|
|
1068
|
+
case "wait-home": {
|
|
1069
|
+
const launch = config.x86sim.cli([
|
|
1070
|
+
"wait",
|
|
1071
|
+
"home",
|
|
1072
|
+
String(HOME_TIMEOUT_S)
|
|
1073
|
+
]);
|
|
1074
|
+
const finished = await run({
|
|
1075
|
+
...launch,
|
|
1076
|
+
env: {
|
|
1077
|
+
...launch.env,
|
|
1078
|
+
...x86simEnv
|
|
1079
|
+
}
|
|
1080
|
+
}, stream);
|
|
1081
|
+
if (finished.code !== 0) throw new Error(`The phone did not reach the home screen in ${HOME_TIMEOUT_S} s.\n${finished.tail}`);
|
|
1082
|
+
return;
|
|
1083
|
+
}
|
|
1084
|
+
case "wait-hook": return await waitForHook();
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
};
|
|
1088
|
+
}
|
|
1089
|
+
//#endregion
|
|
1090
|
+
//#region src/cli/phone.ts
|
|
1091
|
+
const phaseOf = ({ running, hook, axPrefs }) => {
|
|
1092
|
+
if (!running) return "stopped";
|
|
1093
|
+
return hook === "current" && axPrefs ? "ready" : "stale";
|
|
1094
|
+
};
|
|
1095
|
+
/**
|
|
1096
|
+
* Each phase and what brings the phone to `ready`. A running phone loads the hook and the
|
|
1097
|
+
* accessibility preferences only when it boots, so a stale one is stopped and then booted.
|
|
1098
|
+
*/
|
|
1099
|
+
const PLAN = {
|
|
1100
|
+
ready: [],
|
|
1101
|
+
stale: ["stop"],
|
|
1102
|
+
stopped: [
|
|
1103
|
+
"write-prefs",
|
|
1104
|
+
"boot",
|
|
1105
|
+
"wait-home",
|
|
1106
|
+
"wait-hook"
|
|
1107
|
+
]
|
|
1108
|
+
};
|
|
1109
|
+
const PROGRESS = {
|
|
1110
|
+
stop: "Stopping the phone.",
|
|
1111
|
+
"write-prefs": "Turning on accessibility in the phone.",
|
|
1112
|
+
boot: "Booting the phone with the accessibility hook. This takes 1.5 to 6 minutes.",
|
|
1113
|
+
"wait-home": "Waiting for the home screen.",
|
|
1114
|
+
"wait-hook": "Waiting for the hook to answer."
|
|
1115
|
+
};
|
|
1116
|
+
/** Stop, then boot, then confirm. A fourth round means something outside this tool keeps changing the phone. */
|
|
1117
|
+
const MAX_ROUNDS = 3;
|
|
1118
|
+
/**
|
|
1119
|
+
* Brings the phone to `ready` from whatever state it is in. It looks at the phone each round,
|
|
1120
|
+
* not at what an earlier run did, so running it again changes nothing once the phone is ready.
|
|
1121
|
+
*/
|
|
1122
|
+
async function preparePhone(control, log) {
|
|
1123
|
+
for (let round = 0; round < MAX_ROUNDS; round += 1) {
|
|
1124
|
+
const state = await control.observe();
|
|
1125
|
+
const phase = phaseOf(state);
|
|
1126
|
+
if (phase === "ready") {
|
|
1127
|
+
log(round === 0 ? "The phone is already running with the hook loaded." : "The phone is ready.");
|
|
1128
|
+
return;
|
|
1129
|
+
}
|
|
1130
|
+
if (phase === "stale") log(`Restarting the phone to ${[state.hook === "current" ? void 0 : `load the ${state.hook === "outdated" ? "updated " : ""}accessibility hook`, state.axPrefs ? void 0 : "turn on accessibility"].filter(Boolean).join(" and ")}.`);
|
|
1131
|
+
for (const action of PLAN[phase]) {
|
|
1132
|
+
log(PROGRESS[action]);
|
|
1133
|
+
await control.perform(action);
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
throw new Error(`The phone is not ready after ${MAX_ROUNDS} attempts. Last seen: ${JSON.stringify(await control.observe())}.`);
|
|
1137
|
+
}
|
|
1138
|
+
//#endregion
|
|
1139
|
+
//#region src/cli/start-server.ts
|
|
1140
|
+
var start_server_exports = /* @__PURE__ */ __exportAll({ startServer: () => startServer });
|
|
1141
|
+
/** Fails now, not after a boot that takes minutes, when something else holds the port. */
|
|
1142
|
+
async function assertPortFree(host, port) {
|
|
1143
|
+
if (port === 0) return;
|
|
1144
|
+
const probe = createServer();
|
|
1145
|
+
await new Promise((resolve, reject) => {
|
|
1146
|
+
probe.once("error", (error) => reject(error.code === "EADDRINUSE" ? /* @__PURE__ */ new Error(`Port ${port} on ${host} is in use. Stop what uses it, or pass --port.`) : error));
|
|
1147
|
+
probe.listen(port, host, () => probe.close(() => resolve()));
|
|
1148
|
+
});
|
|
1149
|
+
}
|
|
1150
|
+
/**
|
|
1151
|
+
* Brings the phone to ready, then starts the WebDriver server in front of it. `serve` and the
|
|
1152
|
+
* plugin's own start-up both call this.
|
|
1153
|
+
*/
|
|
1154
|
+
async function startServer(options) {
|
|
1155
|
+
await assertPortFree(options.host, options.port);
|
|
1156
|
+
const hook = await packagedHookPath();
|
|
1157
|
+
await preparePhone(createPhoneControl({
|
|
1158
|
+
x86sim: options.target.x86sim,
|
|
1159
|
+
device: options.target.device,
|
|
1160
|
+
hook,
|
|
1161
|
+
verbose: options.verbose,
|
|
1162
|
+
write: (text) => process.stderr.write(text)
|
|
1163
|
+
}), options.log);
|
|
1164
|
+
const server = createServer$2({
|
|
1165
|
+
backend: new X86SimBackend({
|
|
1166
|
+
cli: (args) => options.target.x86sim.cli(args),
|
|
1167
|
+
device: options.target.device
|
|
1168
|
+
}),
|
|
1169
|
+
log: options.verbose ? (line) => process.stderr.write(`${line}\n`) : () => {}
|
|
1170
|
+
});
|
|
1171
|
+
await new Promise((resolve, reject) => {
|
|
1172
|
+
server.once("error", reject);
|
|
1173
|
+
server.listen(options.port, options.host, resolve);
|
|
1174
|
+
});
|
|
1175
|
+
const { port } = server.address();
|
|
1176
|
+
return {
|
|
1177
|
+
endpoint: `http://${options.host}:${port}`,
|
|
1178
|
+
close: () => new Promise((resolve) => (server.closeAllConnections(), server.close(() => resolve())))
|
|
1179
|
+
};
|
|
1180
|
+
}
|
|
1181
|
+
//#endregion
|
|
1182
|
+
export { start_server_exports as n, packagedHookPath as r, startServer as t };
|