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