Repository navigation
Expand file tree
/
Copy pathares.ts
More file actions
150 lines (130 loc) · 5.25 KB
/
Copy pathares.ts
File metadata and controls
150 lines (130 loc) · 5.25 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
import { execFile, spawn } from 'node:child_process';
import path from 'node:path';
import { promisify } from 'node:util';
import { Deadline, pollUntilSettled } from '@agent-device/host-kit/retry';
import { AppError } from '@agent-device/kernel/errors';
import { listTargets, type CdpTarget } from './cdp.ts';
const run = promisify(execFile);
export type AresDevice = Readonly<{
name: string;
ip: string;
isDefault: boolean;
}>;
export type Inspector = Readonly<{
target: CdpTarget;
close(): void;
}>;
type AresSetupEntry = {
profile: string;
name: string;
default: boolean;
deviceinfo: { ip: string };
};
export type HostEnv = Readonly<Record<string, string | undefined>>;
export function createAres(bin: string | undefined, hostEnv: HostEnv) {
const command = (name: string) => (bin ? path.join(bin, name) : name);
const env = bin
? { ...hostEnv, PATH: [bin, hostEnv.PATH].filter(Boolean).join(path.delimiter) }
: hostEnv;
const ares = async (name: string, args: string[]) => {
try {
return (await run(command(name), args, { env, timeout: 60_000 })).stdout;
} catch (error) {
throw aresError(name, error);
}
};
const forDevice = (device: string) => ({
async launch(appId: string) {
await ares('ares-launch', ['-d', device, appId]);
},
async close(appId: string) {
await ares('ares-launch', ['-d', device, '--close', appId]);
},
async listApps(): Promise<{ id: string; name: string }[]> {
return parseAppList(await ares('ares-install', ['-d', device, '--listfull']));
},
async install(packagePath: string) {
await ares('ares-install', ['-d', device, packagePath]);
},
async remove(appId: string) {
await ares('ares-install', ['-d', device, '--remove', appId]);
},
// ares-inspect is a long-lived ssh tunnel that prints its local inspector port once it is up.
// The page target only appears once the app has loaded, so the port alone is not enough.
async inspect(appId: string, timeoutMs = 30_000): Promise<Inspector> {
const child = spawn(command('ares-inspect'), ['-d', device, '-a', appId], { env });
let output = '';
let spawnError: unknown;
child.on('error', (error) => (spawnError = error));
child.stdout.on('data', (chunk) => (output += chunk));
child.stderr.on('data', (chunk) => (output += chunk));
const close = () => child.kill();
const { value: target } = await pollUntilSettled({
deadline: Deadline.fromTimeoutMs(timeoutMs),
intervalMs: 500,
settled: (found) => found !== undefined,
probe: async () => {
if (spawnError) throw aresError('ares-inspect', spawnError);
if (child.exitCode !== null || child.signalCode !== null) {
throw new AppError('COMMAND_FAILED', `ares-inspect exited: ${output.trim()}`, {
hint: `Check that ${device} is reachable with ares-setup-device and in Developer Mode.`,
});
}
const port = Number(output.match(/localhost:(\d+)/)?.[1]);
return port ? await appTarget(port, appId) : undefined;
},
}).catch((error: unknown) => {
close();
throw error;
});
if (target) return { target, close };
close();
throw new AppError(
'COMMAND_FAILED',
`ares-inspect found no page for ${appId} on ${device} within ${timeoutMs}ms`,
{ output: output.trim(), hint: `Check that ${appId} is installed and starts on the TV.` },
);
},
});
return {
async listDevices(): Promise<AresDevice[]> {
const devices: AresSetupEntry[] = JSON.parse(await ares('ares-setup-device', ['--listfull']));
return devices
.filter((device) => device.profile === 'tv')
.map((device) => ({
name: device.name,
ip: device.deviceinfo.ip,
isDefault: device.default,
}));
},
forDevice,
};
}
export type Ares = ReturnType<typeof createAres>;
export type AresTv = ReturnType<Ares['forDevice']>;
async function appTarget(port: number, appId: string): Promise<CdpTarget | undefined> {
const targets = await listTargets(port).catch(() => []);
return targets.find((target) => target.url.includes(`/${appId}/`));
}
function aresError(name: string, error: unknown): AppError {
if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
return new AppError('TOOL_MISSING', `${name} is not installed or not on PATH`, {
hint: 'Install the webOS CLI (npm install -g @webos-tools/cli), or set the plugin option aresBin to the directory that holds it.',
});
}
const stderr =
error instanceof Error && 'stderr' in error && typeof error.stderr === 'string'
? error.stderr.trim()
: '';
return new AppError('COMMAND_FAILED', `${name} failed${stderr ? `: ${stderr}` : ''}`, {
hint: 'Check that the TV is on, in Developer Mode, and registered with ares-setup-device.',
});
}
// `ares-install --listfull` prints one `key : value` block per app, separated by blank lines.
function parseAppList(output: string) {
return output.split(/\n\s*\n/).flatMap((block) => {
const id = block.match(/^id : (.+)$/m)?.[1]?.trim();
const title = block.match(/^title : (.+)$/m)?.[1]?.trim();
return id ? [{ id, name: title ?? id }] : [];
});
}