Open History to see the last commit
1import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import { isCommandAvailable, resolveSpawnCommand } from "@t3tools/shared/shell";
5import * as Clock from "effect/Clock";
6import * as Console from "effect/Console";
7import * as Context from "effect/Context";
8import * as DateTime from "effect/DateTime";
9import * as Crypto from "effect/Crypto";
10import * as Effect from "effect/Effect";
11import * as FileSystem from "effect/FileSystem";
12import * as Option from "effect/Option";
13import * as Path from "effect/Path";
14import * as Random from "effect/Random";
15import * as Schema from "effect/Schema";
16import * as Stream from "effect/Stream";
17import { Argument, Command } from "effect/cli";
18import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
19import { ChildProcess, ChildProcessSpawner } from "effect/process";
20
21export type NativePlatform = "ios" | "android";
22const NativeClientRecord = Schema.Struct({ fingerprint: Schema.String, binary: Schema.String });
23const encodeRecord = Schema.encodeEffect(Schema.fromJsonString(NativeClientRecord));
24const decodeRecord = Schema.decodeUnknownEffect(Schema.fromJsonString(NativeClientRecord));
25const encodeOutput = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
26const isNotLink = Schema.is(Schema.Struct({ code: Schema.Literal("EINVAL") }));
27const decodeSimulators = Schema.decodeUnknownEffect(
28 Schema.fromJsonString(
29 Schema.Struct({
30 devices: Schema.Record(
31 Schema.String,
32 Schema.Array(
33 Schema.Struct({ udid: Schema.String, name: Schema.String, state: Schema.String }),
34 ),
35 ),
36 }),
37 ),
38);
39export type NativeClientRecord = typeof NativeClientRecord.Type;
40export type NativeClientStatus = "compatible" | "missing" | "unknown" | "stale";
41export class NativeClientError extends Schema.TaggedError<NativeClientError>()(
42 "NativeClientError",
43 { message: Schema.String },
44) {}
45
46export function clientStatus(
47 fingerprint: string,
48 binary: string | null,
49 record: NativeClientRecord | null,
50): NativeClientStatus {
51 if (binary === null) return "missing";
52 if (!record || record.binary !== binary) return "unknown";
53 return record.fingerprint === fingerprint ? "compatible" : "stale";
54}
55
56export type ArtifactSource = "local" | "remote" | "build";
57
58/** Keep native sources stable during ensure, as with a normal build; endpoint checks reject detected edits. */
59export const ensureClient = Effect.fn("ensureClient")(function* <E, R, E2, R2>(operations: {
60 fingerprint: Effect.Effect<string, E, R>;
61 installedBinary: Effect.Effect<string | null, E, R>;
62 readRecord: Effect.Effect<NativeClientRecord | null, E, R>;
63 install: (fingerprint: string) => Effect.Effect<ArtifactSource, E, R>;
64 saveRecord: (record: NativeClientRecord) => Effect.Effect<void, E2, R2>;
65}) {
66 const fingerprint = yield* operations.fingerprint;
67 const status = clientStatus(
68 fingerprint,
69 yield* operations.installedBinary,
70 yield* operations.readRecord,
71 );
72 if (status === "compatible") {
73 return { status, installed: false, fingerprint };
74 }
75 const source = yield* operations.install(fingerprint);
76 const binary = yield* operations.installedBinary;
77 if (binary === null)
78 return yield* new NativeClientError({
79 message: "Install finished but the development client is not on the device.",
80 });
81 yield* operations.saveRecord({ fingerprint, binary });
82 return { status: "compatible" as const, installed: true, source, fingerprint };
83});
84
85const digest = Effect.fn("nativeClient.digest")(function* (value: string | Uint8Array) {
86 const crypto = yield* Crypto.Crypto;
87 const bytes = yield* crypto.digest(
88 "SHA-256",
89 typeof value === "string" ? new TextEncoder().encode(value) : value,
90 );
91 return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
92});
93
94/** Hash fixed-size chunks to bound memory, including resources and symlink targets. */
95export const hashBundle = Effect.fn("hashBundle")(function* (root: string) {
96 const fs = yield* FileSystem.FileSystem;
97 const path = yield* Path.Path;
98 const entries: string[] = [];
99 const visit = Effect.fn("mobile-native-client.visit")(function* (
100 relative: string,
101 ): Effect.fn.Return<void, FileSystemError, FileSystem.FileSystem | Crypto.Crypto> {
102 const names = (yield* fs.readDirectory(path.join(root, relative))).sort((a, b) =>
103 a.localeCompare(b, "en"),
104 );
105 for (const name of names) {
106 const key = path.join(relative, name);
107 const absolute = path.join(root, key);
108 // FileSystem.stat follows links; readLink distinguishes them without following a cycle.
109 const link = yield* fs.readLink(absolute).pipe(
110 Effect.catchIf(
111 (error) => isNotLink(error.reason.cause),
112 () => Effect.succeed(null),
113 ),
114 );
115 if (link !== null) {
116 entries.push(`link:${key}:${link}`);
117 continue;
118 }
119 const info = yield* fs.stat(absolute);
120 if (info.type === "Directory") {
121 entries.push(`directory:${key}`);
122 yield* visit(key);
123 } else {
124 const chunks = yield* fs.stream(absolute, { chunkSize: 65536 }).pipe(
125 Stream.mapEffect((chunk) => digest(chunk)),
126 Stream.runCollect,
127 );
128 entries.push(`file:${key}:${yield* digest(chunks.join("\n"))}`);
129 }
130 }
131 });
132 yield* visit("");
133 return yield* digest(entries.map((entry) => `${entry.length}:${entry}`).join(""));
134});
135type FileSystemError = import("effect/PlatformError").PlatformError;
136
137const bundleId = "com.t3tools.t3code.dev";
138const roots = Effect.gen(function* () {
139 const path = yield* Path.Path;
140 const repo = yield* path.fromFileUrl(new URL("../", import.meta.url));
141 return { repo, mobile: path.join(repo, "apps/mobile") };
142});
143const collect = <E>(stream: Stream.Stream<Uint8Array, E>) =>
144 stream.pipe(
145 Stream.decodeText(),
146 Stream.runFold(
147 () => "",
148 (a, b) => a + b,
149 ),
150 );
151export const resolveAdb = Effect.gen(function* () {
152 if (yield* isCommandAvailable("adb")) return "adb";
153 const environment = yield* HostProcess.Environment;
154 const path = yield* Path.Path;
155 const executable = (yield* HostProcess.Platform) === "win32" ? "adb.exe" : "adb";
156 for (const sdk of [environment.ANDROID_SDK_ROOT, environment.ANDROID_HOME]) {
157 if (!sdk) continue;
158 const candidate = path.join(sdk, "platform-tools", executable);
159 if (yield* isCommandAvailable(candidate)) return candidate;
160 }
161 return yield* new NativeClientError({
162 message:
163 "adb was not found on PATH or in ANDROID_SDK_ROOT/ANDROID_HOME. Install Android SDK platform-tools.",
164 });
165});
166
167/** Build tool output goes to this file instead of the caller's terminal; null streams it. */
168const BuildLog = Context.Reference<string | null>("nativeClient/BuildLog", {
169 defaultValue: () => null,
170});
171
172const command = Effect.fn("nativeClient.command")(function* (
173 program: string,
174 args: string[],
175 inherit = false,
176 cwd?: string,
177) {
178 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
179 const environment = yield* HostProcess.Environment;
180 const log = inherit ? yield* BuildLog : null;
181 const spawn = yield* resolveSpawnCommand(program === "adb" ? yield* resolveAdb : program, args);
182 const child = yield* spawner.spawn(
183 ChildProcess.make(spawn.command, spawn.args, {
184 shell: spawn.shell,
185 cwd: cwd ?? (yield* roots).mobile,
186 env: {
187 ...environment,
188 APP_VARIANT: "development",
189 MOBILE_VERSION_POLICY: "appVersion",
190 T3CODE_IOS_PERSONAL_TEAM: "0",
191 CI: "1",
192 EXPO_NO_GIT_STATUS: "1",
193 // macOS tar otherwise adds AppleDouble entries that change the extracted bundle.
194 COPYFILE_DISABLE: "1",
195 },
196 stdin: "ignore",
197 stdout: inherit && !log ? "inherit" : "pipe",
198 stderr: inherit && !log ? "inherit" : "pipe",
199 }),
200 );
201 if (log) {
202 const fs = yield* FileSystem.FileSystem;
203 const append = <E>(stream: Stream.Stream<Uint8Array, E>) =>
204 stream.pipe(Stream.run(fs.sink(log, { flag: "a" })));
205 const [, , code] = yield* Effect.all(
206 [append(child.stdout), append(child.stderr), child.exitCode],
207 { concurrency: "unbounded" },
208 );
209 if (code === 0) return "";
210 const tail = (yield* fs.readFileString(log)).trimEnd().split("\n").slice(-40).join("\n");
211 return yield* new NativeClientError({
212 message: `${program} ${args[0]} failed (${code}). Last lines:\n${tail}\nFull log: ${log}`,
213 });
214 }
215 const [stdout, stderr, code] = yield* Effect.all(
216 [collect(child.stdout), collect(child.stderr), child.exitCode],
217 { concurrency: "unbounded" },
218 );
219 if (code !== 0)
220 return yield* new NativeClientError({
221 message: `${program} ${args[0]} failed (${code}): ${stderr || "see build output"}`,
222 });
223 return stdout.trim();
224}, Effect.scoped);
225
226const fingerprint = Effect.fn("nativeClient.fingerprint")(function* (platform: NativePlatform) {
227 const output = yield* command(yield* HostProcess.ExecutablePath, [
228 "--eval",
229 `require('expo/fingerprint').createFingerprintAsync(process.cwd(), { platforms: [process.argv[1]], silent: true }).then(fp => console.log('T3_NATIVE_FINGERPRINT=' + fp.hash)).catch(e => { console.error(e); process.exitCode = 1; });`,
230 platform,
231 ]);
232 const hash = output
233 .split("\n")
234 .find((line) => line.startsWith("T3_NATIVE_FINGERPRINT="))
235 ?.split("=")[1];
236 if (!hash || !/^[a-f0-9]{40,64}$/.test(hash))
237 return yield* new NativeClientError({ message: "Expo did not return a native fingerprint." });
238 return hash;
239});
240
241const runtimeName = (runtime: string) =>
242 runtime
243 .replace(/^com\.apple\.CoreSimulator\.SimRuntime\./, "")
244 .replace(/-(\d+)-(\d+)$/, " $1.$2");
245
246/** Validate the named device, or pick the only booted one; otherwise list exact commands to choose from. */
247const resolveDevice = Effect.fn("nativeClient.resolveDevice")(function* (
248 platform: NativePlatform,
249 requested: string | undefined,
250) {
251 const choose = (candidates: ReadonlyArray<{ id: string; label: string }>, problem: string) =>
252 new NativeClientError({
253 message: [
254 problem,
255 ...candidates.map(
256 ({ id, label }) => ` vp run mobile:install ${platform} ${id} # ${label}`,
257 ),
258 ].join("\n"),
259 });
260 if (platform === "ios") {
261 if ((yield* HostProcess.Platform) !== "darwin")
262 return yield* new NativeClientError({
263 message: "Run iOS installs on the Mac that hosts the simulator.",
264 });
265 // The shared iOS client is an arm64 simulator build; Intel simulators cannot run it.
266 if ((yield* HostProcess.Architecture) !== "arm64")
267 return yield* new NativeClientError({
268 message: "mobile:install needs an Apple silicon Mac. Use vp run ios:dev on Intel Macs.",
269 });
270 const listing = yield* decodeSimulators(
271 yield* command("xcrun", ["simctl", "list", "devices", "available", "--json"]),
272 );
273 const simulators = Object.entries(listing.devices).flatMap(([runtime, devices]) =>
274 devices.map((device) => ({ ...device, label: `${device.name} (${runtimeName(runtime)})` })),
275 );
276 const booted = simulators
277 .filter((simulator) => simulator.state === "Booted")
278 .map(({ udid, label }) => ({ id: udid, label }));
279 if (requested === undefined) {
280 if (booted.length === 1) return booted[0]!;
281 return yield* booted.length === 0
282 ? new NativeClientError({
283 message:
284 "No iOS simulator is booted. Open one with device_open, or boot one: xcrun simctl boot <udid>",
285 })
286 : choose(booted, "Several iOS simulators are booted. Pick one:");
287 }
288 const simulator = simulators.find((entry) => entry.udid === requested);
289 if (!simulator)
290 return yield* choose(booted, `No available iOS simulator with UDID ${requested}. Booted:`);
291 if (simulator.state !== "Booted")
292 return yield* new NativeClientError({
293 message: `Boot the selected simulator first: xcrun simctl boot ${requested}`,
294 });
295 return { id: simulator.udid, label: simulator.label };
296 }
297 const attached = (yield* command("adb", ["devices", "-l"]))
298 .split("\n")
299 .slice(1)
300 .map((line) => line.trim().split(/\s+/))
301 .filter((parts) => parts.length >= 2)
302 .map(([id, state, ...details]) => ({
303 id: id!,
304 state: state!,
305 label: details.find((detail) => detail.startsWith("model:"))?.slice(6) ?? id!,
306 }));
307 const ready = attached.filter((device) => device.state === "device");
308 const device =
309 requested === undefined ? ready : attached.filter((entry) => entry.id === requested);
310 if (requested === undefined && ready.length !== 1)
311 return yield* ready.length === 0
312 ? new NativeClientError({
313 message:
314 "No Android emulator or phone is connected. Open one with device_open, or start an emulator.",
315 })
316 : choose(ready, "Several Android devices are connected. Pick one:");
317 const selected = device[0];
318 if (!selected)
319 return yield* choose(ready, `Android device ${requested} is not connected. Ready:`);
320 if (selected.state === "unauthorized")
321 return yield* new NativeClientError({
322 message: `Unlock ${selected.label} and accept the USB debugging prompt, then run this again.`,
323 });
324 if (selected.state !== "device")
325 return yield* new NativeClientError({
326 message: `Android device ${selected.id} is ${selected.state}, not ready.`,
327 });
328 // Emulators report a generic model; their AVD name is what users recognize.
329 const avd = selected.id.startsWith("emulator-")
330 ? yield* command("adb", ["-s", selected.id, "emu", "avd", "name"]).pipe(
331 Effect.map((output) => output.split("\n")[0]?.trim()),
332 Effect.orElseSucceed(() => undefined),
333 )
334 : undefined;
335 return { id: selected.id, label: avd || selected.label };
336});
337
338export const installedBinary = Effect.fn("installedBinary")(function* (
339 platform: NativePlatform,
340 device: string,
341 run: typeof command = command,
342) {
343 if (platform === "ios") {
344 const apps = yield* run("xcrun", ["simctl", "listapps", device]);
345 if (!apps.includes(`"${bundleId}"`)) return null;
346 return yield* hashBundle(
347 yield* run("xcrun", ["simctl", "get_app_container", device, bundleId, "app"]),
348 );
349 }
350 const installed = yield* run("adb", ["-s", device, "shell", "pm", "list", "packages", bundleId]);
351 if (!installed.split("\n").some((line) => line.trim() === `package:${bundleId}`)) return null;
352 const packages = yield* run("adb", ["-s", device, "shell", "pm", "path", bundleId]);
353 const apks = packages
354 .split("\n")
355 .filter((line) => line.startsWith("package:"))
356 .map((line) => line.slice(8).trim())
357 .sort();
358 if (apks.length === 0) return null;
359 const hashes = yield* Effect.forEach(apks, (apk) =>
360 Effect.gen(function* () {
361 if (!/^\/[\w/+=.~-]+\.apk$/.test(apk))
362 return yield* new NativeClientError({ message: "Unexpected installed APK path." });
363 const hash = (yield* run("adb", ["-s", device, "shell", "sha256sum", apk])).split(/\s/)[0];
364 if (!hash || !/^[a-f0-9]{64}$/.test(hash))
365 return yield* new NativeClientError({ message: "Could not hash installed APK." });
366 return hash;
367 }),
368 );
369 return yield* digest(hashes.sort().join("\n"));
370});
371
372/** Preserve input-invalidated Gradle/.cxx caches; exclude app/build because its tasks omit inputs. Ignore cache failures. */
373export const prebuildAndroid = Effect.fn("nativeClient.prebuildAndroid")(function* <E, R>(
374 mobile: string,
375 prebuild: Effect.Effect<void, E, R>,
376) {
377 const fs = yield* FileSystem.FileSystem;
378 const path = yield* Path.Path;
379 const android = path.join(mobile, "android");
380 // Sibling renames stay on one filesystem; interrupted runs leave this gitignored cache for next-run cleanup.
381 const saved = path.join(mobile, ".android-cache");
382 const caches = [".gradle", "app/.cxx"];
383 const clear = fs.remove(saved, { recursive: true, force: true }).pipe(Effect.ignore);
384 const move = (from: string, to: string) =>
385 Effect.forEach(
386 caches,
387 (cache) =>
388 Effect.gen(function* () {
389 const source = path.join(from, cache);
390 const target = path.join(to, cache);
391 if (!(yield* fs.exists(source)) || (yield* fs.exists(target))) return;
392 yield* fs.makeDirectory(path.dirname(target), { recursive: true });
393 yield* fs.rename(source, target);
394 }).pipe(Effect.ignore),
395 { discard: true },
396 );
397 yield* Effect.acquireUseRelease(
398 clear.pipe(Effect.andThen(move(android, saved))),
399 () => prebuild,
400 () => move(saved, android).pipe(Effect.andThen(clear)),
401 );
402});
403
404const artifactNames = { ios: "T3CodeDev.app", android: "app-debug.apk" } as const;
405// R2 requires equal-sized parts and Workers cap request bodies at 100 MB.
406const partSize = 64 * 1024 * 1024;
407const RemoteCredentials = Schema.fromJsonString(
408 Schema.Record(Schema.String, Schema.Struct({ name: Schema.String, token: Schema.String })),
409);
410const decodeCredentials = Schema.decodeUnknownEffect(RemoteCredentials);
411const decodeEndpoint = Schema.decodeUnknownEffect(
412 Schema.fromJsonString(Schema.Struct({ endpoint: Schema.String })),
413);
414const decodeUpload = Schema.decodeUnknownEffect(
415 Schema.Union([
416 Schema.Struct({ exists: Schema.Literal(true) }),
417 Schema.Struct({ uploadId: Schema.String }),
418 ]),
419);
420const decodePart = Schema.decodeUnknownEffect(Schema.Struct({ etag: Schema.String }));
421
422interface RemoteCache {
423 readonly url: string;
424 readonly telemetry: string;
425 readonly name: string;
426 readonly token: string;
427}
428
429/** The shared task-cache login (infra/task-cache/install.sh) also authorizes native clients. */
430const remoteCache = Effect.fn("nativeClient.remoteCache")(
431 function* (home: string) {
432 const environment = yield* HostProcess.Environment;
433 if (environment.T3_NATIVE_CLIENT_CACHE === "off") return null;
434 const fs = yield* FileSystem.FileSystem;
435 const path = yield* Path.Path;
436 const { endpoint } = yield* decodeEndpoint(
437 yield* fs.readFileString(path.join((yield* roots).repo, ".task-cache.json")),
438 );
439 const credentials = yield* decodeCredentials(
440 yield* fs.readFileString(path.join(home, ".config/t3-task-cache/credentials.json")),
441 );
442 const login = credentials[endpoint];
443 if (!login) return null;
444 const base = endpoint.replace(/\/$/, "");
445 return {
446 url: `${base}/native-clients`,
447 telemetry: `${base}/telemetry`,
448 ...login,
449 } satisfies RemoteCache;
450 },
451 Effect.catch(() => Effect.succeed(null)),
452);
453
454const authorized = (remote: RemoteCache, request: HttpClientRequest.HttpClientRequest) =>
455 request.pipe(HttpClientRequest.basicAuth(remote.name, remote.token));
456
457// Build duration lives beside the artifact so hits can report the time they saved.
458const sidecar = (directory: string) => `${directory}.json`;
459const decodeSidecar = Schema.decodeUnknownEffect(
460 Schema.fromJsonString(Schema.Struct({ buildMs: Schema.Number })),
461);
462const readBuildMs = (directory: string) =>
463 FileSystem.FileSystem.pipe(
464 Effect.flatMap((fs) => fs.readFileString(sidecar(directory))),
465 Effect.flatMap(decodeSidecar),
466 Effect.map(({ buildMs }) => buildMs),
467 Effect.orElseSucceed(() => 0),
468 );
469const writeBuildMs = (directory: string, buildMs: number) =>
470 FileSystem.FileSystem.pipe(
471 Effect.flatMap((fs) => fs.writeFileString(sidecar(directory), JSON.stringify({ buildMs }))),
472 Effect.ignore,
473 );
474
475/** Download into a sibling staging directory and publish only after the digest matches. */
476const download = Effect.fn("nativeClient.download")(function* (
477 remote: RemoteCache,
478 platform: NativePlatform,
479 key: string,
480 target: string,
481) {
482 const fs = yield* FileSystem.FileSystem;
483 const path = yield* Path.Path;
484 const client = yield* HttpClient.HttpClient;
485 const response = yield* client.execute(
486 authorized(remote, HttpClientRequest.get(`${remote.url}/${key}`)),
487 );
488 if (response.status === 404) return false;
489 yield* HttpClientResponse.filterStatusOk(response);
490 const expected = response.headers["x-t3-digest"] ?? "";
491 if (!/^[a-f0-9]{64}$/.test(expected))
492 return yield* new NativeClientError({ message: "Cached native client has no digest." });
493 yield* Console.error(`Downloading native client ${key} from the shared cache...`);
494 const staging = yield* fs.makeTempDirectory({
495 directory: path.dirname(target),
496 prefix: ".download-",
497 });
498 return yield* Effect.gen(function* () {
499 if (platform === "ios") {
500 const archive = `${staging}.tgz`;
501 yield* response.stream.pipe(
502 Stream.run(fs.sink(archive)),
503 Effect.andThen(command("tar", ["-xzf", archive, "-C", staging])),
504 Effect.ensuring(fs.remove(archive, { force: true }).pipe(Effect.ignore)),
505 );
506 } else {
507 yield* response.stream.pipe(Stream.run(fs.sink(path.join(staging, artifactNames.android))));
508 }
509 if ((yield* hashBundle(staging)) !== expected)
510 return yield* new NativeClientError({ message: "Cached native client failed verification." });
511 yield* publish(staging, target);
512 const buildMs = Number(response.headers["x-t3-build-ms"] ?? 0);
513 yield* writeBuildMs(target, Number.isSafeInteger(buildMs) ? buildMs : 0);
514 return true;
515 }).pipe(
516 Effect.ensuring(fs.remove(staging, { recursive: true, force: true }).pipe(Effect.ignore)),
517 );
518});
519
520/** Upload in fixed-size parts; any failure aborts the upload and leaves the cache unchanged. */
521const upload = Effect.fn("nativeClient.upload")(function* (
522 remote: RemoteCache,
523 platform: NativePlatform,
524 key: string,
525 artifact: string,
526) {
527 const fs = yield* FileSystem.FileSystem;
528 const path = yield* Path.Path;
529 const client = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);
530 const created = yield* client
531 .execute(
532 authorized(remote, HttpClientRequest.post(`${remote.url}/${key}/uploads`)).pipe(
533 HttpClientRequest.setHeader("x-t3-digest", yield* hashBundle(artifact)),
534 HttpClientRequest.setHeader("x-t3-build-ms", String(yield* readBuildMs(artifact))),
535 ),
536 )
537 .pipe(
538 Effect.flatMap((response) => response.json),
539 Effect.flatMap(decodeUpload),
540 );
541 if ("exists" in created) return;
542 const uploadUrl = `${remote.url}/${key}/uploads/${encodeURIComponent(created.uploadId)}`;
543 yield* Console.error(`Uploading native client ${key} to the shared cache...`);
544 yield* Effect.gen(function* () {
545 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-native-upload-" });
546 const file =
547 platform === "ios"
548 ? path.join(directory, "client.tgz")
549 : path.join(artifact, artifactNames.android);
550 if (platform === "ios")
551 yield* command("tar", ["-czf", file, "-C", artifact, artifactNames.ios]);
552 const handle = yield* fs.open(file);
553 const parts: Array<{ partNumber: number; etag: string }> = [];
554 for (let partNumber = 1; ; partNumber++) {
555 const buffer = new Uint8Array(partSize);
556 let filled = 0;
557 while (filled < partSize) {
558 const read = Number(yield* handle.read(buffer.subarray(filled)));
559 if (read === 0) break;
560 filled += read;
561 }
562 if (filled === 0) break;
563 const { etag } = yield* client
564 .execute(
565 authorized(remote, HttpClientRequest.put(`${uploadUrl}/${partNumber}`)).pipe(
566 HttpClientRequest.bodyUint8Array(buffer.subarray(0, filled)),
567 ),
568 )
569 .pipe(
570 Effect.flatMap((response) => response.json),
571 Effect.flatMap(decodePart),
572 );
573 parts.push({ partNumber, etag });
574 if (filled < partSize) break;
575 }
576 yield* client.execute(
577 authorized(remote, HttpClientRequest.post(`${uploadUrl}/complete`)).pipe(
578 HttpClientRequest.bodyJsonUnsafe({ parts }),
579 ),
580 );
581 }).pipe(
582 Effect.scoped,
583 Effect.onError(() =>
584 client.execute(authorized(remote, HttpClientRequest.delete(uploadUrl))).pipe(Effect.ignore),
585 ),
586 );
587});
588
589const publish = Effect.fn("nativeClient.publish")(function* (staging: string, target: string) {
590 const fs = yield* FileSystem.FileSystem;
591 // A concurrent ensure may have published the same fingerprint first; either copy is valid.
592 if (yield* fs.exists(target)) return;
593 yield* fs.rename(staging, target);
594});
595
596const build = Effect.fn("nativeClient.build")(function* (
597 platform: NativePlatform,
598 abi: string | null,
599 target: string,
600 expected: string,
601) {
602 const fs = yield* FileSystem.FileSystem;
603 const path = yield* Path.Path;
604 const { repo, mobile } = yield* roots;
605 const tracked = yield* command("git", ["ls-files", `apps/mobile/${platform}`], false, repo);
606 if (tracked)
607 return yield* new NativeClientError({
608 message: "Native directory contains tracked files; clean prebuild would overwrite them.",
609 });
610 const prebuild = command(
611 "vp",
612 ["exec", "expo", "prebuild", "--clean", "--platform", platform, "--no-install"],
613 true,
614 ).pipe(Effect.asVoid);
615 yield* platform === "android" ? prebuildAndroid(mobile, prebuild) : prebuild;
616 const staging = yield* fs.makeTempDirectory({
617 directory: path.dirname(target),
618 prefix: ".build-",
619 });
620 yield* Effect.gen(function* () {
621 if (platform === "ios") {
622 const output = yield* fs.makeTempDirectoryScoped({ prefix: "t3-native-client-" });
623 yield* command("pod", ["install"], true, path.join(mobile, "ios"));
624 // One device-independent arm64 simulator build installs on every iPhone and iPad simulator.
625 yield* command(
626 "xcrun",
627 [
628 "xcodebuild",
629 "-workspace",
630 path.join(mobile, "ios/T3CodeDev.xcworkspace"),
631 "-scheme",
632 "T3CodeDev",
633 "-configuration",
634 "Debug",
635 "-destination",
636 "generic/platform=iOS Simulator",
637 "-derivedDataPath",
638 output,
639 "ARCHS=arm64",
640 "ONLY_ACTIVE_ARCH=NO",
641 "build",
642 ],
643 true,
644 );
645 yield* command("ditto", [
646 path.join(output, "Build/Products/Debug-iphonesimulator", artifactNames.ios),
647 path.join(staging, artifactNames.ios),
648 ]);
649 } else {
650 const android = path.join(mobile, "android");
651 yield* command(
652 path.join(android, (yield* HostProcess.Platform) === "win32" ? "gradlew.bat" : "gradlew"),
653 ["app:assembleDebug", `-PreactNativeArchitectures=${abi}`],
654 true,
655 android,
656 );
657 yield* fs.copyFile(
658 path.join(android, "app/build/outputs/apk/debug", artifactNames.android),
659 path.join(staging, artifactNames.android),
660 );
661 }
662 // Native edits during the build would publish this binary under a fingerprint it doesn't match.
663 if ((yield* fingerprint(platform)) !== expected)
664 return yield* new NativeClientError({
665 message: "Native inputs changed during the build, so it was discarded. Run this again.",
666 });
667 yield* publish(staging, target);
668 }).pipe(
669 Effect.scoped,
670 Effect.ensuring(fs.remove(staging, { recursive: true, force: true }).pipe(Effect.ignore)),
671 );
672});
673
674/** Keep the newest few fingerprints per platform; each artifact is a few hundred megabytes. */
675const prune = Effect.fn("nativeClient.prune")(
676 function* (parent: string, keep: string) {
677 const fs = yield* FileSystem.FileSystem;
678 const path = yield* Path.Path;
679 const entries = yield* Effect.forEach(
680 (yield* fs.readDirectory(parent)).filter(
681 (name) => !name.startsWith(".") && !name.endsWith(".json"),
682 ),
683 (name) =>
684 fs.stat(path.join(parent, name)).pipe(
685 Effect.map((info) => ({
686 name,
687 modified: Option.getOrUndefined(info.mtime)?.getTime() ?? 0,
688 })),
689 ),
690 );
691 const stale = entries
692 .filter(({ name }) => name !== keep)
693 .sort((a, b) => b.modified - a.modified)
694 .slice(2);
695 yield* Effect.forEach(
696 stale,
697 ({ name }) =>
698 fs
699 .remove(path.join(parent, name), { recursive: true, force: true })
700 .pipe(Effect.andThen(fs.remove(sidecar(path.join(parent, name)), { force: true }))),
701 { discard: true },
702 );
703 },
704 (effect) => Effect.ignore(effect),
705);
706
707/** Local artifact, then the shared cache, then a build that is shared back when credentials allow. */
708export const resolveArtifact = Effect.fn("nativeClient.resolveArtifact")(function* (
709 home: string,
710 platform: NativePlatform,
711 abi: string | null,
712 fingerprint: string,
713) {
714 const fs = yield* FileSystem.FileSystem;
715 const path = yield* Path.Path;
716 const key = `${platform}/${abi ? `development-${abi}` : "development"}/${fingerprint}`;
717 const directory = path.join(home, ".cache/t3code/native-clients/artifacts", key);
718 const artifact = { directory, file: path.join(directory, artifactNames[platform]) };
719 if (yield* fs.exists(artifact.file)) {
720 yield* Console.error(`Using cached client ${key}.`);
721 // Pruning keeps the most recently used, so a client another checkout is installing stays.
722 const now = yield* Clock.currentTimeMillis;
723 yield* fs.utimes(directory, now / 1000, now / 1000).pipe(Effect.ignore);
724 return { ...artifact, source: "local" as const, buildMs: yield* readBuildMs(directory) };
725 }
726 yield* fs.makeDirectory(path.dirname(directory), { recursive: true });
727 const remote = yield* remoteCache(home);
728 if (remote) {
729 const downloaded = yield* download(remote, platform, key, directory).pipe(
730 Effect.catch((error) =>
731 Console.error(`Shared native client cache unavailable (${describe(error)}).`).pipe(
732 Effect.as(false),
733 ),
734 ),
735 );
736 if (downloaded) {
737 yield* prune(path.dirname(directory), fingerprint);
738 return { ...artifact, source: "remote" as const, buildMs: yield* readBuildMs(directory) };
739 }
740 }
741 const log = yield* BuildLog;
742 yield* Console.error(
743 `No cached client for ${key}. Building it once for every machine (5-15 min)${log ? `. Log: ${log}` : ""}`,
744 );
745 const started = yield* Clock.currentTimeMillis;
746 yield* build(platform, abi, directory, fingerprint);
747 yield* writeBuildMs(directory, (yield* Clock.currentTimeMillis) - started);
748 yield* prune(path.dirname(directory), fingerprint);
749 if (remote && (yield* HostProcess.Environment).T3_NATIVE_CLIENT_CACHE !== "read") {
750 yield* upload(remote, platform, key, directory).pipe(
751 Effect.catch((error) => Console.error(`Native client was not shared (${describe(error)}).`)),
752 );
753 }
754 return { ...artifact, source: "build" as const, buildMs: 0 };
755});
756
757const describe = (error: unknown) =>
758 typeof error === "object" &&
759 error !== null &&
760 "message" in error &&
761 typeof error.message === "string"
762 ? error.message
763 : String(error);
764
765const install = Effect.fn("nativeClient.install")(function* (
766 platform: NativePlatform,
767 device: string,
768 file: string,
769) {
770 if (platform === "ios") {
771 yield* command("xcrun", ["simctl", "install", device, file], true);
772 return;
773 }
774 yield* command("adb", ["-s", device, "install", "-r", "-d", file]).pipe(
775 Effect.catchTags({
776 NativeClientError: (error) =>
777 Effect.fail(
778 error.message.includes("INSTALL_FAILED_UPDATE_INCOMPATIBLE")
779 ? new NativeClientError({
780 message: `The installed client has a different signature. Remove it with adb -s ${device} uninstall ${bundleId} (this clears its pairings), then run ensure again.`,
781 })
782 : error,
783 ),
784 }),
785 );
786 // Emulators reach Metro through 10.0.2.2; a phone on USB needs the port forwarded.
787 if ((yield* command("adb", ["-s", device, "shell", "getprop", "ro.kernel.qemu"])) !== "1")
788 yield* command("adb", ["-s", device, "reverse", "tcp:8081", "tcp:8081"]).pipe(Effect.ignore);
789});
790
791const reportTelemetry = Effect.fn("nativeClient.reportTelemetry")(
792 function* (
793 home: string,
794 task: string,
795 source: "local" | "remote" | "executed" | "failed",
796 savedMs: number,
797 ) {
798 const remote = yield* remoteCache(home);
799 if (!remote) return;
800 const environment = yield* HostProcess.Environment;
801 const recordedAt = yield* Clock.currentTimeMillis;
802 // Same machine label as Vite task reports (infra/task-cache/src/telemetry.ts).
803 const fs = yield* FileSystem.FileSystem;
804 const machine = yield* fs.readFileString(`${home}/.agents/MACHINE`).pipe(
805 Effect.map((value) => value.trim()),
806 Effect.orElseSucceed(() => ""),
807 );
808 const host =
809 environment.T3_TASK_CACHE_HOST ||
810 machine ||
811 (environment.GITHUB_ACTIONS === "true"
812 ? `${environment.RUNNER_ENVIRONMENT || "github"}/${environment.RUNNER_OS}/${environment.RUNNER_ARCH}`
813 : yield* HostProcess.Hostname);
814 const client = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);
815 yield* client.execute(
816 authorized(remote, HttpClientRequest.post(remote.telemetry)).pipe(
817 HttpClientRequest.bodyJsonUnsafe({
818 id: yield* digest(`${host}:${task}:${recordedAt}:${yield* Random.nextInt}`),
819 recordedAt,
820 host,
821 platform: yield* HostProcess.Platform,
822 arch: yield* HostProcess.Architecture,
823 ci: environment.CI === "true" || environment.CI === "1",
824 runId: environment.GITHUB_RUN_ID ?? "",
825 tasks: [{ package: "@t3tools/mobile", task, source, savedMs: Math.round(savedMs) }],
826 }),
827 ),
828 );
829 },
830 (effect) => effect.pipe(Effect.timeout("5 seconds"), Effect.ignore),
831);
832
833const main = Command.make(
834 "mobile-native-client",
835 {
836 mode: Argument.Literals("mode", ["check", "ensure"]),
837 platform: Argument.Literals("platform", ["ios", "android"]),
838 device: Argument.String("device").pipe(Argument.optional),
839 },
840 Effect.fn("nativeClient.main")(function* ({ mode, platform, device: requested }) {
841 const started = yield* Clock.currentTimeMillis;
842 const target = yield* resolveDevice(platform, Option.getOrUndefined(requested));
843 const device = target.id;
844 yield* Console.error(`Device: ${target.label} (${device})`);
845 const fs = yield* FileSystem.FileSystem;
846 const path = yield* Path.Path;
847 const environment = yield* HostProcess.Environment;
848 const home = environment.HOME ?? environment.USERPROFILE;
849 if (!home)
850 return yield* new NativeClientError({
851 message: "HOME or USERPROFILE must be set to store native client records.",
852 });
853 const cache = path.join(home, ".cache/t3code/native-clients");
854 const recordPath = path.join(cache, platform, `${yield* digest(device)}.json`);
855 // An iOS simulator build is arm64 for every device; an APK carries only the device's own ABI.
856 const abi = Effect.gen(function* () {
857 if (platform === "ios") return null;
858 const value = yield* command("adb", ["-s", device, "shell", "getprop", "ro.product.cpu.abi"]);
859 if (value !== "x86_64" && value !== "arm64-v8a")
860 return yield* new NativeClientError({ message: `Unsupported Android ABI ${value}.` });
861 return value;
862 });
863 let task = `native-client:${platform}`;
864 let savedMs = 0;
865 const operations = {
866 fingerprint: fingerprint(platform),
867 installedBinary: installedBinary(platform, device),
868 readRecord: fs.readFileString(recordPath).pipe(
869 Effect.flatMap(decodeRecord),
870 Effect.catchTags({ SchemaError: () => Effect.succeed(null) }),
871 Effect.catchIf(
872 (error) => error.reason._tag === "NotFound",
873 () => Effect.succeed(null),
874 ),
875 ),
876 install: Effect.fn(function* (fingerprint: string) {
877 const deviceAbi = yield* abi;
878 if (deviceAbi) task = `native-client:android-${deviceAbi}`;
879 const artifact = yield* resolveArtifact(home, platform, deviceAbi, fingerprint);
880 savedMs = artifact.buildMs;
881 yield* Console.error(`Installing on ${target.label}...`);
882 yield* install(platform, device, artifact.file);
883 return artifact.source;
884 }),
885 saveRecord: Effect.fn(function* (record: NativeClientRecord) {
886 yield* fs.makeDirectory(path.dirname(recordPath), { recursive: true });
887 yield* fs.writeFileString(recordPath, yield* encodeRecord(record));
888 }),
889 };
890 if (mode === "check") {
891 const current = yield* operations.fingerprint;
892 const status = clientStatus(
893 current,
894 yield* operations.installedBinary,
895 yield* operations.readRecord,
896 );
897 yield* Console.log(
898 yield* encodeOutput({
899 status,
900 fingerprint: current,
901 device,
902 next:
903 status === "compatible"
904 ? "Start Metro with vp run dev:client"
905 : `vp run mobile:install ${platform} ${device}`,
906 }),
907 );
908 process.exitCode = status === "compatible" ? 0 : 2;
909 return;
910 }
911 const logs = path.join(cache, "logs");
912 yield* fs.makeDirectory(logs, { recursive: true });
913 yield* prune(logs, "");
914 const stamp = DateTime.formatIso(DateTime.makeUnsafe(started)).replaceAll(":", "-");
915 const log = path.join(logs, `${stamp}-${platform}.log`);
916 const result = yield* ensureClient(operations).pipe(
917 Effect.provideService(BuildLog, environment.T3_NATIVE_CLIENT_VERBOSE === "1" ? null : log),
918 Effect.tapError(() => reportTelemetry(home, task, "failed", 0)),
919 );
920 if (result.installed && result.source)
921 yield* reportTelemetry(
922 home,
923 task,
924 result.source === "build" ? "executed" : result.source,
925 result.source === "build" ? 0 : savedMs,
926 );
927 const seconds = Math.round(((yield* Clock.currentTimeMillis) - started) / 1000);
928 yield* Console.error(
929 result.installed
930 ? `Installed on ${target.label} in ${seconds}s (${result.source}). Next: start Metro with vp run dev:client.`
931 : `${target.label} already has the client for this checkout. Next: start Metro with vp run dev:client.`,
932 );
933 yield* Console.log(yield* encodeOutput({ ...result, device, seconds }));
934 }),
935);
936
937if (import.meta.main) {
938 Command.run(main, { version: "0.0.0" }).pipe(
939 // Expected failures carry their next step; a stack trace only buries it.
940 Effect.catchTags({
941 NativeClientError: (error) =>
942 Console.error(error.message).pipe(
943 Effect.andThen(Effect.sync(() => (process.exitCode = 1))),
944 ),
945 }),
946 Effect.scoped,
947 Effect.provide([NodeServices.layer, FetchHttpClient.layer]),
948 NodeRuntime.runMain,
949 );
950}