Open History to see the last commit
1import type { DeviceToolVersions } from "@t3tools/contracts";
2/**
3 * npm extracts files before it finishes, so an entry file alone does not prove
4 * a usable tree.
5 */
6import * as Duration from "effect/Duration";
7import * as Effect from "effect/Effect";
8import * as FileSystem from "effect/FileSystem";
9import * as Option from "effect/Option";
10import * as Path from "effect/Path";
11import * as PlatformError from "effect/PlatformError";
12import * as Schema from "effect/Schema";
13import * as Semaphore from "effect/Semaphore";
14
15import * as ProcessRunner from "../processRunner.ts";
16import DEVICE_TOOL_VERSIONS from "./deviceToolVersions.json" with { type: "json" };
17
18const DEVICE_HUB_PACKAGE = "expo-device-hub";
19export const DEVICE_HUB_VERSION = DEVICE_TOOL_VERSIONS[DEVICE_HUB_PACKAGE];
20const AGENT_DEVICE_PACKAGE = "agent-device";
21export const AGENT_DEVICE_VERSION = DEVICE_TOOL_VERSIONS[AGENT_DEVICE_PACKAGE];
22
23const INSTALL_TIMEOUT = Duration.minutes(10);
24const installLock = Semaphore.makeUnsafe(1);
25
26export interface DeviceToolPaths {
27 readonly installDir: string;
28 readonly entryPath: string;
29 readonly sentinelPath: string;
30}
31
32export interface DeviceToolchainPaths {
33 readonly hub: DeviceToolPaths;
34 readonly agentDevice: DeviceToolPaths;
35}
36
37export class DeviceToolchainInstallError extends Schema.TaggedError<DeviceToolchainInstallError>()(
38 "DeviceToolchainInstallError",
39 {
40 tool: Schema.String,
41 step: Schema.String,
42 exitCode: Schema.optional(Schema.Number),
43 cause: Schema.optional(Schema.Defect()),
44 },
45) {
46 override get message(): string {
47 const suffix = this.exitCode === undefined ? "" : ` (exit code ${this.exitCode})`;
48 return `Installing ${this.tool} failed while ${this.step}${suffix}.`;
49 }
50}
51
52interface ToolSpec {
53 readonly name: string;
54 readonly version: string;
55 readonly entry: ReadonlyArray<string>;
56}
57
58const HUB_SPEC: ToolSpec = {
59 name: DEVICE_HUB_PACKAGE,
60 version: DEVICE_HUB_VERSION,
61 entry: ["dist", "server", "cli.mjs"],
62};
63
64const AGENT_DEVICE_SPEC: ToolSpec = {
65 name: AGENT_DEVICE_PACKAGE,
66 version: AGENT_DEVICE_VERSION,
67 entry: ["bin", "agent-device.mjs"],
68};
69
70const toolPaths = (path: Path.Path, baseDir: string, spec: ToolSpec): DeviceToolPaths => {
71 const installDir = path.join(baseDir, "tools", spec.name, spec.version);
72 return {
73 installDir,
74 entryPath: path.join(installDir, "node_modules", spec.name, ...spec.entry),
75 sentinelPath: path.join(installDir, ".install-complete"),
76 };
77};
78
79const deviceToolchainPaths = (path: Path.Path, baseDir: string): DeviceToolchainPaths => ({
80 hub: toolPaths(path, baseDir, HUB_SPEC),
81 agentDevice: toolPaths(path, baseDir, AGENT_DEVICE_SPEC),
82});
83
84export const agentDeviceStateDir = (path: Path.Path, stateDir: string): string =>
85 path.join(stateDir, "device", "agent-device");
86
87const isInstalled = Effect.fn("DeviceToolchain.isInstalled")(function* (
88 fs: FileSystem.FileSystem,
89 paths: DeviceToolPaths,
90 version: string,
91) {
92 const [entryExists, sentinel] = yield* Effect.all([
93 fs.exists(paths.entryPath),
94 fs.readFileString(paths.sentinelPath).pipe(Effect.option),
95 ]).pipe(Effect.orElseSucceed(() => [false, Option.none<string>()] as const));
96 return entryExists && Option.isSome(sentinel) && sentinel.value.trim() === version;
97});
98
99const installTool = Effect.fn("DeviceToolchain.installTool")(function* (
100 spec: ToolSpec,
101 paths: DeviceToolPaths,
102) {
103 const fs = yield* FileSystem.FileSystem;
104 const path = yield* Path.Path;
105 const runner = yield* ProcessRunner.ProcessRunner;
106 const fail = (step: string) => (cause: unknown) =>
107 new DeviceToolchainInstallError({ tool: spec.name, step, cause });
108
109 if (yield* isInstalled(fs, paths, spec.version)) return paths;
110
111 const parentDir = path.dirname(paths.installDir);
112 yield* fs
113 .remove(paths.installDir, { recursive: true, force: true })
114 .pipe(Effect.mapError(fail("removing an incomplete install")));
115 yield* fs
116 .makeDirectory(parentDir, { recursive: true })
117 .pipe(Effect.mapError(fail("preparing the install directory")));
118 const stagingDir = yield* fs
119 .makeTempDirectory({ directory: parentDir, prefix: ".staging-" })
120 .pipe(Effect.mapError(fail("preparing the install directory")));
121
122 return yield* Effect.gen(function* () {
123 const installArgs = [
124 "install",
125 "--prefix",
126 stagingDir,
127 "--no-fund",
128 "--no-audit",
129 `${spec.name}@${spec.version}`,
130 ];
131 const result = yield* runner
132 .run({ command: "npm", args: installArgs, timeout: INSTALL_TIMEOUT })
133 .pipe(
134 Effect.catchTags({
135 ProcessSpawnError: (error) =>
136 error.cause instanceof PlatformError.PlatformError &&
137 error.cause.reason._tag === "NotFound"
138 ? runner.run({
139 command: "pnpm",
140 args: ["--package=npm@11", "dlx", "npm", ...installArgs],
141 timeout: INSTALL_TIMEOUT,
142 })
143 : Effect.fail(error),
144 }),
145 Effect.mapError(fail("running npm install")),
146 );
147 if (result.code !== 0) {
148 return yield* new DeviceToolchainInstallError({
149 tool: spec.name,
150 step: "running npm install",
151 exitCode: Number(result.code),
152 cause: result,
153 });
154 }
155 const stagedEntry = path.join(stagingDir, "node_modules", spec.name, ...spec.entry);
156 if (!(yield* fs.exists(stagedEntry).pipe(Effect.orElseSucceed(() => false)))) {
157 return yield* new DeviceToolchainInstallError({
158 tool: spec.name,
159 step: "verifying the installed entry point",
160 });
161 }
162 yield* fs
163 .writeFileString(path.join(stagingDir, ".install-complete"), `${spec.version}\n`)
164 .pipe(Effect.mapError(fail("recording the completed install")));
165 yield* fs
166 .rename(stagingDir, paths.installDir)
167 .pipe(
168 Effect.catch((cause) =>
169 isInstalled(fs, paths, spec.version).pipe(
170 Effect.flatMap((published) =>
171 published ? Effect.void : Effect.fail(fail("publishing the install")(cause)),
172 ),
173 ),
174 ),
175 );
176 return paths;
177 }).pipe(
178 Effect.ensuring(fs.remove(stagingDir, { recursive: true, force: true }).pipe(Effect.ignore)),
179 );
180});
181
182const ensureTool = Effect.fn("DeviceToolchain.ensureTool")(function* (
183 baseDir: string,
184 spec: ToolSpec,
185 select: (paths: DeviceToolchainPaths) => DeviceToolPaths,
186) {
187 const path = yield* Path.Path;
188 const paths = deviceToolchainPaths(path, baseDir);
189 return yield* installLock.withPermit(installTool(spec, select(paths)));
190});
191
192export const ensureDeviceHub = (baseDir: string) =>
193 ensureTool(baseDir, HUB_SPEC, (paths) => paths.hub);
194
195export const ensureAgentDevice = (baseDir: string) =>
196 ensureTool(baseDir, AGENT_DEVICE_SPEC, (paths) => paths.agentDevice);
197
198const isToolInstalled = Effect.fn("DeviceToolchain.isToolInstalled")(function* (
199 baseDir: string,
200 spec: ToolSpec,
201 select: (paths: DeviceToolchainPaths) => DeviceToolPaths,
202) {
203 const fs = yield* FileSystem.FileSystem;
204 const path = yield* Path.Path;
205 const paths = deviceToolchainPaths(path, baseDir);
206 return yield* isInstalled(fs, select(paths), spec.version);
207});
208
209export const isDeviceHubInstalled = (baseDir: string) =>
210 isToolInstalled(baseDir, HUB_SPEC, (paths) => paths.hub);
211
212export const isAgentDeviceInstalled = (baseDir: string) =>
213 isToolInstalled(baseDir, AGENT_DEVICE_SPEC, (paths) => paths.agentDevice);
214
215export const deviceToolVersions = Effect.fn("DeviceToolchain.versions")(function* (
216 baseDir: string,
217 running: { hub?: string; agent?: string } = {},
218) {
219 const fs = yield* FileSystem.FileSystem;
220 const path = yield* Path.Path;
221 const inspect = Effect.fn("DeviceToolchain.inspect")(function* (spec: ToolSpec) {
222 const directory = path.join(baseDir, "tools", spec.name);
223 const names = yield* fs.readDirectory(directory).pipe(
224 Effect.catchIf(
225 (error) => error.reason._tag === "NotFound",
226 () => Effect.succeed([]),
227 ),
228 );
229 const versions = yield* Effect.filter(names, (version) =>
230 /^[0-9]+\.[0-9]+\.[0-9]+(?:-[a-zA-Z0-9.-]+)?$/.test(version)
231 ? Effect.gen(function* () {
232 const paths = toolPaths(path, baseDir, { ...spec, version });
233 const sentinel = yield* fs.readFileString(paths.sentinelPath).pipe(
234 Effect.catchIf(
235 (error) => error.reason._tag === "NotFound",
236 () => Effect.succeed(null),
237 ),
238 );
239 return sentinel?.trim() === version && (yield* fs.exists(paths.entryPath));
240 })
241 : Effect.succeed(false),
242 );
243 return {
244 requiredVersion: spec.version,
245 installedVersions: versions.sort(),
246 runningVersion: (spec.name === DEVICE_HUB_PACKAGE ? running.hub : running.agent) ?? null,
247 };
248 });
249 return yield* Effect.gen(function* () {
250 return {
251 hub: yield* inspect(HUB_SPEC),
252 agent: yield* inspect(AGENT_DEVICE_SPEC),
253 } satisfies DeviceToolVersions;
254 }).pipe(Effect.orElseSucceed(() => undefined));
255});