Repository navigation
Expand file tree
/
Copy pathclient-session.ts
More file actions
79 lines (70 loc) · 2.5 KB
/
Copy pathclient-session.ts
File metadata and controls
79 lines (70 loc) · 2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/**
* Root client session: create a client, open an app, capture a snapshot, tap
* a node, then close the session — with typed error handling via the
* exported error helpers.
*
* Demonstrates: `createAgentDeviceClient`, `AppError`, `isAgentDeviceError`,
* and `normalizeAgentDeviceError` from the `agent-device` root export.
*
* Prerequisites: an `agent-device` daemon target (a booted iOS simulator).
* This file typechecks without one; running it for real also requires
* `pnpm build` first, so the package resolves at runtime.
*
* Run: node --experimental-strip-types examples/sdk/client-session.ts
*/
import {
AppError,
createAgentDeviceClient,
isAgentDeviceError,
normalizeAgentDeviceError,
} from 'agent-device';
import type { AgentDeviceClient, AgentDeviceDevice } from 'agent-device';
async function resolveSnapshotCapableIosDevice(
client: AgentDeviceClient,
): Promise<AgentDeviceDevice> {
const devices = await client.devices.list({ platform: 'ios' });
const device = devices[0];
if (!device) {
throw new AppError('DEVICE_NOT_FOUND', 'No iOS device available');
}
const capabilities = await client.devices.capabilities({ platform: 'ios' });
if (!capabilities.availableCommands.includes('snapshot')) {
throw new AppError('UNSUPPORTED_OPERATION', 'Selected target does not support snapshots');
}
return device;
}
function reportAgentDeviceError(error: unknown): void {
const normalized = normalizeAgentDeviceError(error);
console.error(`agent-device error [${normalized.code}]: ${normalized.message}`);
if (normalized.hint) {
console.error(`hint: ${normalized.hint}`);
}
process.exitCode = 1;
}
async function main(): Promise<void> {
const client = createAgentDeviceClient({
session: 'sdk-example',
lockPolicy: 'reject',
lockPlatform: 'ios',
});
try {
const device = await resolveSnapshotCapableIosDevice(client);
await client.apps.open({
app: 'com.apple.Preferences',
platform: 'ios',
udid: device.id,
});
const snapshot = await client.capture.snapshot({ interactiveOnly: true });
const target = snapshot.nodes.find((node) => node.role === 'button');
// A node carries a ref only when something can address it, and press needs that address.
if (target?.ref !== undefined) {
await client.interactions.press({ ref: target.ref });
}
} catch (error) {
if (!isAgentDeviceError(error)) throw error;
reportAgentDeviceError(error);
} finally {
await client.sessions.close();
}
}
await main();