Open History to see the last commit
1/**
2 * Pinned installs of the two external tools device support is built on.
3 *
4 * `expo-device-hub` streams simulator and emulator screens and `agent-device`
5 * drives them. Each is npm-installed separately after its matching consent
6 * step into `<baseDir>/tools/<name>/<version>` and executed from there with the
7 * resolved Node runtime, never `npx`: an ephemeral
8 * npx cache would make every first `device_open` after a reboot depend on the
9 * registry, and the pinned versions are part of the contract the injected
10 * agent instructions describe.
11 *
12 * Install follows the pinned-runtime recipe: stage into a temp sibling, write a
13 * sentinel only after npm exits 0, then rename into place. npm extracts files
14 * before it finishes, so an entry file alone does not prove a usable tree.
15 */
16import * as Duration from "effect/Duration";
17import * as Effect from "effect/Effect";
18import * as FileSystem from "effect/FileSystem";
19import * as Option from "effect/Option";
20import * as Path from "effect/Path";
21import * as PlatformError from "effect/PlatformError";
22import * as Schema from "effect/Schema";
23import * as Semaphore from "effect/Semaphore";
24
25import * as ProcessRunner from "../processRunner.ts";
26
27const DEVICE_HUB_PACKAGE = "expo-device-hub";
28export const DEVICE_HUB_VERSION = "0.9.0";
29const AGENT_DEVICE_PACKAGE = "agent-device";
30export const AGENT_DEVICE_VERSION = "0.20.10";
31
32const INSTALL_TIMEOUT = Duration.minutes(10);
33const installLock = Semaphore.makeUnsafe(1);
34
35export interface DeviceToolPaths {
36 readonly installDir: string;
37 /** Absolute path of the tool's entry script, run with a resolved Node runtime. */
38 readonly entryPath: string;
39 readonly sentinelPath: string;
40}
41
42export interface DeviceToolchainPaths {
43 readonly hub: DeviceToolPaths;
44 readonly agentDevice: DeviceToolPaths;
45}
46
47export class DeviceToolchainInstallError extends Schema.TaggedError<DeviceToolchainInstallError>()(
48 "DeviceToolchainInstallError",
49 {
50 tool: Schema.String,
51 step: Schema.String,
52 exitCode: Schema.optional(Schema.Number),
53 cause: Schema.optional(Schema.Defect()),
54 },
55) {
56 override get message(): string {
57 const suffix = this.exitCode === undefined ? "" : ` (exit code ${this.exitCode})`;
58 return `Installing ${this.tool} failed while ${this.step}${suffix}.`;
59 }
60}
61
62interface ToolSpec {
63 readonly name: string;
64 readonly version: string;
65 readonly entry: ReadonlyArray<string>;
66}
67
68const HUB_SPEC: ToolSpec = {
69 name: DEVICE_HUB_PACKAGE,
70 version: DEVICE_HUB_VERSION,
71 entry: ["dist", "server", "cli.mjs"],
72};
73
74const AGENT_DEVICE_SPEC: ToolSpec = {
75 name: AGENT_DEVICE_PACKAGE,
76 version: AGENT_DEVICE_VERSION,
77 entry: ["bin", "agent-device.mjs"],
78};
79
80const toolPaths = (path: Path.Path, baseDir: string, spec: ToolSpec): DeviceToolPaths => {
81 const installDir = path.join(baseDir, "tools", spec.name, spec.version);
82 return {
83 installDir,
84 entryPath: path.join(installDir, "node_modules", spec.name, ...spec.entry),
85 sentinelPath: path.join(installDir, ".install-complete"),
86 };
87};
88
89const deviceToolchainPaths = (path: Path.Path, baseDir: string): DeviceToolchainPaths => ({
90 hub: toolPaths(path, baseDir, HUB_SPEC),
91 agentDevice: toolPaths(path, baseDir, AGENT_DEVICE_SPEC),
92});
93
94/** Keep daemon state (daemon.json, sessions) in userdata, separate from tool installs. */
95export const agentDeviceStateDir = (path: Path.Path, stateDir: string): string =>
96 path.join(stateDir, "device", "agent-device");
97
98const isInstalled = Effect.fn("DeviceToolchain.isInstalled")(function* (
99 fs: FileSystem.FileSystem,
100 paths: DeviceToolPaths,
101 version: string,
102) {
103 const [entryExists, sentinel] = yield* Effect.all([
104 fs.exists(paths.entryPath),
105 fs.readFileString(paths.sentinelPath).pipe(Effect.option),
106 ]).pipe(Effect.orElseSucceed(() => [false, Option.none<string>()] as const));
107 return entryExists && Option.isSome(sentinel) && sentinel.value.trim() === version;
108});
109
110const installTool = Effect.fn("DeviceToolchain.installTool")(function* (
111 spec: ToolSpec,
112 paths: DeviceToolPaths,
113) {
114 const fs = yield* FileSystem.FileSystem;
115 const path = yield* Path.Path;
116 const runner = yield* ProcessRunner.ProcessRunner;
117 const fail = (step: string) => (cause: unknown) =>
118 new DeviceToolchainInstallError({ tool: spec.name, step, cause });
119
120 if (yield* isInstalled(fs, paths, spec.version)) return paths;
121
122 const parentDir = path.dirname(paths.installDir);
123 yield* fs
124 .remove(paths.installDir, { recursive: true, force: true })
125 .pipe(Effect.mapError(fail("removing an incomplete install")));
126 yield* fs
127 .makeDirectory(parentDir, { recursive: true })
128 .pipe(Effect.mapError(fail("preparing the install directory")));
129 const stagingDir = yield* fs
130 .makeTempDirectory({ directory: parentDir, prefix: ".staging-" })
131 .pipe(Effect.mapError(fail("preparing the install directory")));
132
133 return yield* Effect.gen(function* () {
134 const installArgs = [
135 "install",
136 "--prefix",
137 stagingDir,
138 "--no-fund",
139 "--no-audit",
140 `${spec.name}@${spec.version}`,
141 ];
142 const result = yield* runner
143 .run({ command: "npm", args: installArgs, timeout: INSTALL_TIMEOUT })
144 .pipe(
145 Effect.catchTags({
146 ProcessSpawnError: (error) =>
147 error.cause instanceof PlatformError.PlatformError &&
148 error.cause.reason._tag === "NotFound"
149 ? runner.run({
150 command: "pnpm",
151 args: ["--package=npm@11", "dlx", "npm", ...installArgs],
152 timeout: INSTALL_TIMEOUT,
153 })
154 : Effect.fail(error),
155 }),
156 Effect.mapError(fail("running npm install")),
157 );
158 if (result.code !== 0) {
159 return yield* new DeviceToolchainInstallError({
160 tool: spec.name,
161 step: "running npm install",
162 exitCode: Number(result.code),
163 cause: result,
164 });
165 }
166 const stagedEntry = path.join(stagingDir, "node_modules", spec.name, ...spec.entry);
167 if (!(yield* fs.exists(stagedEntry).pipe(Effect.orElseSucceed(() => false)))) {
168 return yield* new DeviceToolchainInstallError({
169 tool: spec.name,
170 step: "verifying the installed entry point",
171 });
172 }
173 yield* fs
174 .writeFileString(path.join(stagingDir, ".install-complete"), `${spec.version}\n`)
175 .pipe(Effect.mapError(fail("recording the completed install")));
176 yield* fs.rename(stagingDir, paths.installDir).pipe(
177 Effect.catch((cause) =>
178 // A concurrent server may have published the same version first.
179 isInstalled(fs, paths, spec.version).pipe(
180 Effect.flatMap((published) =>
181 published ? Effect.void : Effect.fail(fail("publishing the install")(cause)),
182 ),
183 ),
184 ),
185 );
186 return paths;
187 }).pipe(
188 Effect.ensuring(fs.remove(stagingDir, { recursive: true, force: true }).pipe(Effect.ignore)),
189 );
190});
191
192const ensureTool = Effect.fn("DeviceToolchain.ensureTool")(function* (
193 baseDir: string,
194 spec: ToolSpec,
195 select: (paths: DeviceToolchainPaths) => DeviceToolPaths,
196) {
197 const path = yield* Path.Path;
198 const paths = deviceToolchainPaths(path, baseDir);
199 return yield* installLock.withPermit(installTool(spec, select(paths)));
200});
201
202export const ensureDeviceHub = (baseDir: string) =>
203 ensureTool(baseDir, HUB_SPEC, (paths) => paths.hub);
204
205export const ensureAgentDevice = (baseDir: string) =>
206 ensureTool(baseDir, AGENT_DEVICE_SPEC, (paths) => paths.agentDevice);
207
208const isToolInstalled = Effect.fn("DeviceToolchain.isToolInstalled")(function* (
209 baseDir: string,
210 spec: ToolSpec,
211 select: (paths: DeviceToolchainPaths) => DeviceToolPaths,
212) {
213 const fs = yield* FileSystem.FileSystem;
214 const path = yield* Path.Path;
215 const paths = deviceToolchainPaths(path, baseDir);
216 return yield* isInstalled(fs, select(paths), spec.version);
217});
218
219export const isDeviceHubInstalled = (baseDir: string) =>
220 isToolInstalled(baseDir, HUB_SPEC, (paths) => paths.hub);
221
222export const isAgentDeviceInstalled = (baseDir: string) =>
223 isToolInstalled(baseDir, AGENT_DEVICE_SPEC, (paths) => paths.agentDevice);