Open History to see the last commit
1#!/usr/bin/env node
2// @effect-diagnostics nodeBuiltinImport:off globalTimers:off globalDate:off - Host-side simulator and emulator automation uses Node subprocess and timing APIs directly.
3
4import * as NodeChildProcess from "node:child_process";
5import * as NodeFSP from "node:fs/promises";
6import * as NodeNet from "node:net";
7import * as NodeOS from "node:os";
8import * as NodePath from "node:path";
9import * as NodeProcess from "node:process";
10import * as NodeURL from "node:url";
11
12import { PNG } from "pngjs";
13
14import showcaseConfig, {
15 type ShowcaseAppearance,
16 type ShowcaseAndroidDevice,
17 type ShowcaseConfig,
18 type ShowcaseDevice,
19 type ShowcaseIosDevice,
20 type ShowcaseStoreAssetSpec,
21 SHOWCASE_SCENES,
22 type ShowcaseScene,
23} from "./mobile-showcase.config.ts";
24import {
25 SHOWCASE_ENVIRONMENTS,
26 SHOWCASE_PROJECTS,
27 SHOWCASE_TERMINAL_ID,
28 SHOWCASE_THREAD_ID,
29 seedShowcaseEnvironment,
30} from "./mobile-showcase-environment.ts";
31
32const REPO_ROOT = NodePath.resolve(NodePath.dirname(NodeURL.fileURLToPath(import.meta.url)), "..");
33const MOBILE_ROOT = NodePath.join(REPO_ROOT, "apps/mobile");
34const ANDROID_PACKAGE = "com.t3tools.t3code";
35const APP_SCHEME = "t3code";
36const IOS_READY_FILENAME = "T3ShowcaseReadyScene";
37const SERVER_HOST = "0.0.0.0";
38const IOS_SIMULATOR_ARCH = NodeProcess.arch === "arm64" ? "arm64" : "x86_64";
39const IOS_APP_PATH = NodePath.join(
40 MOBILE_ROOT,
41 ".showcase/ios-derived-data/Build/Products/Debug-iphonesimulator/T3Code.app",
42);
43const ANDROID_APK_PATH = NodePath.join(
44 MOBILE_ROOT,
45 "android/app/build/outputs/apk/debug/app-debug.apk",
46);
47export function resolveAndroidSdkRoot(
48 environment: Readonly<Record<string, string | undefined>>,
49 platform: NodeJS.Platform = NodeProcess.platform,
50): string {
51 const configured = environment.ANDROID_HOME ?? environment.ANDROID_SDK_ROOT;
52 if (configured) return configured;
53 const home = environment.HOME ?? environment.USERPROFILE ?? "";
54 return NodePath.join(home, platform === "darwin" ? "Library/Android/sdk" : "Android/Sdk");
55}
56
57const ANDROID_SDK_ROOT = resolveAndroidSdkRoot(NodeProcess.env);
58const MOBILE_BUILD_ENV = {
59 ...NodeProcess.env,
60 ANDROID_HOME: ANDROID_SDK_ROOT,
61 APP_VARIANT: "production",
62 EXPO_NO_GIT_STATUS: "1",
63 // Lets the capture build require full screen on iPad so the app can rotate
64 // itself to landscape (see app.config.ts).
65 T3_SHOWCASE_CAPTURE_BUILD: "1",
66 JAVA_HOME:
67 NodeProcess.env.JAVA_HOME ??
68 (NodeProcess.platform === "darwin"
69 ? "/Applications/Android Studio.app/Contents/jbr/Contents/Home"
70 : undefined),
71 NODE_ENV: "development",
72};
73
74interface CliOptions {
75 readonly platforms: ReadonlySet<ShowcaseDevice["platform"]>;
76 readonly deviceIds: ReadonlySet<string>;
77 readonly scenes: ReadonlySet<ShowcaseScene>;
78 readonly appearances: ReadonlySet<ShowcaseAppearance>;
79 readonly skipBuild: boolean;
80 readonly skipMetro: boolean;
81 readonly keepRunning: boolean;
82 readonly validateOnly: boolean;
83 readonly list: boolean;
84}
85
86export interface ShowcaseCapture {
87 readonly device: ShowcaseDevice;
88 readonly scenes: ReadonlyArray<ShowcaseScene>;
89 readonly appearance: ShowcaseAppearance;
90}
91
92interface IosCaptureCleanup {
93 readonly udid: string;
94 readonly startedByRunner: boolean;
95 readonly createdByRunner: boolean;
96}
97
98interface AndroidCaptureCleanup {
99 readonly device: ShowcaseAndroidDevice;
100 readonly serial: string;
101 readonly startedByRunner: boolean;
102}
103
104interface NetworkAddress {
105 readonly address: string;
106 readonly family: string;
107 readonly internal: boolean;
108}
109
110export function selectLanIpv4Address(addresses: ReadonlyArray<NetworkAddress>): string | null {
111 return (
112 addresses.find(
113 ({ address, family, internal }) =>
114 family === "IPv4" && !internal && !address.startsWith("169.254."),
115 )?.address ?? null
116 );
117}
118
119function lanIpv4Address(): string {
120 const address = selectLanIpv4Address(
121 Object.values(NodeOS.networkInterfaces()).flatMap((addresses) => addresses ?? []),
122 );
123 if (!address) {
124 throw new Error("No LAN IPv4 address is available for the iOS Simulator to reach Metro.");
125 }
126 return address;
127}
128
129export interface PngMetadata {
130 readonly width: number;
131 readonly height: number;
132 readonly bitDepth: number;
133 readonly colorType: number;
134 readonly hasAlpha: boolean;
135}
136
137export function readPngMetadata(bytes: Uint8Array): PngMetadata {
138 const pngSignature = [137, 80, 78, 71, 13, 10, 26, 10];
139 if (bytes.byteLength < 26 || !pngSignature.every((value, index) => bytes[index] === value)) {
140 throw new Error("Captured file is not a valid PNG.");
141 }
142 const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
143 const colorType = view.getUint8(25);
144 return {
145 width: view.getUint32(16),
146 height: view.getUint32(20),
147 bitDepth: view.getUint8(24),
148 colorType,
149 hasAlpha: colorType === 4 || colorType === 6,
150 };
151}
152
153export function readPngDimensions(bytes: Uint8Array): {
154 readonly width: number;
155 readonly height: number;
156} {
157 const { width, height } = readPngMetadata(bytes);
158 return { width, height };
159}
160
161export function normalizeStorePng(bytes: Uint8Array): Buffer {
162 const png = PNG.sync.read(Buffer.from(bytes));
163 return PNG.sync.write(png, {
164 bitDepth: 8,
165 colorType: 2,
166 inputColorType: 6,
167 inputHasAlpha: true,
168 });
169}
170
171export function validateStoreAsset(
172 spec: ShowcaseStoreAssetSpec,
173 bytes: Uint8Array,
174 label = "Screenshot",
175): PngMetadata {
176 const metadata = readPngMetadata(bytes);
177 if (metadata.width !== spec.width || metadata.height !== spec.height) {
178 throw new Error(
179 `${label} is ${metadata.width}×${metadata.height}; ${spec.store} requires ${spec.width}×${spec.height}.`,
180 );
181 }
182 if (metadata.bitDepth !== 8 || metadata.colorType !== 2 || metadata.hasAlpha) {
183 throw new Error(
184 `${label} must be an 8-bit, 24-bit RGB PNG without alpha (found bit depth ${metadata.bitDepth}, color type ${metadata.colorType}).`,
185 );
186 }
187 if (spec.maximumFileSizeBytes && bytes.byteLength > spec.maximumFileSizeBytes) {
188 throw new Error(
189 `${label} is ${bytes.byteLength} bytes; ${spec.store} allows at most ${spec.maximumFileSizeBytes} bytes.`,
190 );
191 }
192 if (spec.store === "google-play") {
193 const shortestSide = Math.min(metadata.width, metadata.height);
194 const longestSide = Math.max(metadata.width, metadata.height);
195 if (shortestSide < 320 || longestSide > 3_840 || longestSide > shortestSide * 2) {
196 throw new Error(
197 `${label} does not meet Google Play's 320–3,840 px bounds and 2:1 maximum aspect ratio.`,
198 );
199 }
200 if (metadata.width * 16 !== metadata.height * 9) {
201 throw new Error(`${label} must use Google Play's recommended portrait 9:16 aspect ratio.`);
202 }
203 }
204 return metadata;
205}
206
207export function validateStoreAssetCount(
208 spec: ShowcaseStoreAssetSpec,
209 count: number,
210 requireMinimum: boolean,
211): void {
212 if (count > spec.maximumUploadCount) {
213 throw new Error(
214 `${spec.directory} contains ${count} screenshots; ${spec.store} allows at most ${spec.maximumUploadCount}.`,
215 );
216 }
217 if (requireMinimum && count < spec.minimumUploadCount) {
218 throw new Error(
219 `${spec.directory} contains ${count} screenshots; ${spec.store} requires at least ${spec.minimumUploadCount}.`,
220 );
221 }
222}
223
224export function showcaseCaptureDirectory(
225 outputDirectory: string,
226 capture: Pick<ShowcaseCapture, "device" | "appearance">,
227): string {
228 return NodePath.join(outputDirectory, capture.device.storeAsset.directory, capture.appearance);
229}
230
231async function finalizeCapture(destination: string, device: ShowcaseDevice): Promise<void> {
232 const normalized = normalizeStorePng(await NodeFSP.readFile(destination));
233 await NodeFSP.writeFile(destination, normalized);
234 const metadata = validateStoreAsset(
235 device.storeAsset,
236 normalized,
237 NodePath.basename(destination),
238 );
239 NodeProcess.stdout.write(
240 `Captured ${NodePath.relative(REPO_ROOT, destination)} (${metadata.width}×${metadata.height}, 24-bit RGB, validated for ${device.storeAsset.store})\n`,
241 );
242}
243
244async function validateCaptureSet(
245 capture: ShowcaseCapture,
246 outputDirectory: string,
247 requireMinimum: boolean,
248): Promise<void> {
249 const directory = showcaseCaptureDirectory(outputDirectory, capture);
250 const files = (await NodeFSP.readdir(directory)).filter((file) => file.endsWith(".png")).sort();
251 const expectedFiles = capture.scenes.map((scene) => `${scene}.png`).sort();
252 const missingFiles = expectedFiles.filter((file) => !files.includes(file));
253 if (missingFiles.length > 0) {
254 throw new Error(`${capture.device.id} is missing ${missingFiles.join(", ")} in ${directory}.`);
255 }
256 validateStoreAssetCount(capture.device.storeAsset, files.length, requireMinimum);
257 for (const file of files) {
258 const bytes = await NodeFSP.readFile(NodePath.join(directory, file));
259 validateStoreAsset(capture.device.storeAsset, bytes, `${capture.device.id}/${file}`);
260 }
261 NodeProcess.stdout.write(
262 `Validated ${files.length} upload-ready ${capture.device.storeAsset.store} screenshots in ${NodePath.relative(REPO_ROOT, directory)}/\n`,
263 );
264}
265
266function argumentValue(args: ReadonlyArray<string>, index: number, flag: string): string {
267 const value = args[index + 1];
268 if (!value || value.startsWith("--")) {
269 throw new Error(`${flag} requires a value.`);
270 }
271 return value;
272}
273
274export function parseShowcaseCliArgs(args: ReadonlyArray<string>): CliOptions {
275 const platforms = new Set<ShowcaseDevice["platform"]>();
276 const deviceIds = new Set<string>();
277 const scenes = new Set<ShowcaseScene>();
278 const appearances = new Set<ShowcaseAppearance>();
279 let skipBuild = false;
280 let skipMetro = false;
281 let keepRunning = false;
282 let validateOnly = false;
283 let list = false;
284
285 for (let index = 0; index < args.length; index += 1) {
286 const argument = args[index];
287 if (argument === "--platform") {
288 const value = argumentValue(args, index, argument);
289 if (value !== "ios" && value !== "android" && value !== "all") {
290 throw new Error(`Unsupported platform '${value}'. Use ios, android, or all.`);
291 }
292 if (value === "all") {
293 platforms.add("ios");
294 platforms.add("android");
295 } else {
296 platforms.add(value);
297 }
298 index += 1;
299 } else if (argument === "--device") {
300 deviceIds.add(argumentValue(args, index, argument));
301 index += 1;
302 } else if (argument === "--scene") {
303 const value = argumentValue(args, index, argument);
304 if (!SHOWCASE_SCENES.includes(value as ShowcaseScene)) {
305 throw new Error(`Unsupported scene '${value}'. Use ${SHOWCASE_SCENES.join(", ")}.`);
306 }
307 scenes.add(value as ShowcaseScene);
308 index += 1;
309 } else if (argument === "--appearance") {
310 const value = argumentValue(args, index, argument);
311 if (value !== "light" && value !== "dark" && value !== "both") {
312 throw new Error(`Unsupported appearance '${value}'. Use light, dark, or both.`);
313 }
314 if (value === "both") {
315 appearances.add("light");
316 appearances.add("dark");
317 } else {
318 appearances.add(value);
319 }
320 index += 1;
321 } else if (argument === "--skip-build") {
322 skipBuild = true;
323 } else if (argument === "--skip-metro") {
324 skipMetro = true;
325 } else if (argument === "--keep-running") {
326 keepRunning = true;
327 } else if (argument === "--validate-only") {
328 validateOnly = true;
329 } else if (argument === "--list") {
330 list = true;
331 } else if (argument === "--help" || argument === "-h") {
332 list = true;
333 } else {
334 throw new Error(`Unknown option '${argument}'.`);
335 }
336 }
337
338 return {
339 platforms,
340 deviceIds,
341 scenes,
342 appearances,
343 skipBuild,
344 skipMetro,
345 keepRunning,
346 validateOnly,
347 list,
348 };
349}
350
351export function planShowcaseCaptures(
352 config: ShowcaseConfig,
353 options: Pick<CliOptions, "platforms" | "deviceIds" | "scenes" | "appearances">,
354): ReadonlyArray<ShowcaseCapture> {
355 const captures = config.devices
356 .filter((device) => options.platforms.size === 0 || options.platforms.has(device.platform))
357 .filter((device) => options.deviceIds.size === 0 || options.deviceIds.has(device.id))
358 .flatMap((device) => {
359 const appearances =
360 options.appearances.size === 0 ? [device.appearance] : options.appearances;
361 return [...appearances].map((appearance) => ({
362 device,
363 appearance,
364 scenes:
365 options.scenes.size === 0
366 ? device.scenes
367 : device.scenes.filter((scene) => options.scenes.has(scene)),
368 }));
369 })
370 .filter((capture) => capture.scenes.length > 0);
371
372 const knownDeviceIds = new Set(config.devices.map((device) => device.id));
373 for (const id of options.deviceIds) {
374 if (!knownDeviceIds.has(id)) {
375 throw new Error(`Unknown device '${id}'. Run with --list to see configured devices.`);
376 }
377 }
378 if (captures.length === 0) {
379 throw new Error("No captures match the selected platform, device, and scene filters.");
380 }
381 return captures;
382}
383
384function printUsage(config: ShowcaseConfig): void {
385 NodeProcess.stdout.write(`App screenshot showcase
386
387Usage:
388 pnpm --filter @t3tools/mobile screenshots [options]
389
390Options:
391 --platform ios|android|all Capture one platform (repeatable)
392 --device <id> Capture one configured device (repeatable)
393 --scene <name> Capture one scene (repeatable)
394 --appearance light|dark|both
395 Override the configured appearance
396 --skip-build Reuse the existing simulator app / debug APK
397 --skip-metro Reuse an already running showcase Metro server
398 --keep-running Leave devices and Metro running after capture
399 --validate-only Validate existing upload assets without capturing
400 --list Print this help and the configured matrix
401
402Scenes: ${SHOWCASE_SCENES.join(", ")}
403
404Configured devices:
405${config.devices
406 .map((device) => {
407 const target = device.platform === "ios" ? device.simulator : device.avd;
408 return ` ${device.id.padEnd(18)} ${device.platform.padEnd(8)} ${target} -> ${device.storeAsset.directory}/{light|dark} (${device.storeAsset.width}×${device.storeAsset.height}, default ${device.appearance}) [${device.scenes.join(", ")}]`;
409 })
410 .join("\n")}
411`);
412}
413
414function spawnProcess(
415 command: string,
416 args: ReadonlyArray<string>,
417 options: NodeChildProcess.SpawnOptions = {},
418): NodeChildProcess.ChildProcess {
419 return NodeChildProcess.spawn(command, args, {
420 cwd: REPO_ROOT,
421 env: NodeProcess.env,
422 stdio: "inherit",
423 ...options,
424 });
425}
426
427async function runCommand(
428 command: string,
429 args: ReadonlyArray<string>,
430 options: NodeChildProcess.SpawnOptions = {},
431): Promise<void> {
432 await new Promise<void>((resolve, reject) => {
433 const child = spawnProcess(command, args, options);
434 child.once("error", reject);
435 child.once("exit", (code, signal) => {
436 if (code === 0) {
437 resolve();
438 } else {
439 reject(
440 new Error(
441 `${command} ${args.join(" ")} failed ${signal ? `with signal ${signal}` : `with code ${String(code)}`}.`,
442 ),
443 );
444 }
445 });
446 });
447}
448
449async function commandOutput(
450 command: string,
451 args: ReadonlyArray<string>,
452 options: NodeChildProcess.ExecFileOptions = {},
453): Promise<string> {
454 return await new Promise<string>((resolve, reject) => {
455 NodeChildProcess.execFile(
456 command,
457 [...args],
458 { cwd: REPO_ROOT, encoding: "utf8", maxBuffer: 10 * 1024 * 1024, ...options },
459 (error, stdout) => {
460 if (error) reject(error);
461 else resolve(String(stdout));
462 },
463 );
464 });
465}
466
467function delay(milliseconds: number): Promise<void> {
468 return new Promise((resolve) => setTimeout(resolve, milliseconds));
469}
470
471async function stopProcess(child: NodeChildProcess.ChildProcess): Promise<void> {
472 if (child.exitCode !== null || child.signalCode !== null) return;
473
474 const exited = new Promise<void>((resolve) => {
475 child.once("exit", () => resolve());
476 });
477 child.kill("SIGTERM");
478 await Promise.race([exited, delay(5_000)]);
479 if (child.exitCode !== null || child.signalCode !== null) return;
480
481 child.kill("SIGKILL");
482 await Promise.race([exited, delay(1_000)]);
483}
484
485async function waitForPort(port: number, label = "Process", timeoutMs = 60_000): Promise<void> {
486 const deadline = Date.now() + timeoutMs;
487 while (Date.now() < deadline) {
488 const open = await new Promise<boolean>((resolve) => {
489 const socket = NodeNet.createConnection({ host: "127.0.0.1", port });
490 socket.once("connect", () => {
491 socket.destroy();
492 resolve(true);
493 });
494 socket.once("error", () => resolve(false));
495 socket.setTimeout(500, () => {
496 socket.destroy();
497 resolve(false);
498 });
499 });
500 if (open) return;
501 await delay(500);
502 }
503 throw new Error(`${label} did not begin listening on port ${port} within ${timeoutMs}ms.`);
504}
505
506async function waitForFileContent(
507 filePath: string,
508 label: string,
509 timeoutMs = 60_000,
510): Promise<string> {
511 const deadline = Date.now() + timeoutMs;
512 while (Date.now() < deadline) {
513 const content = await NodeFSP.readFile(filePath, "utf8").then(
514 (value) => value.trim(),
515 () => "",
516 );
517 if (content) return content;
518 await delay(250);
519 }
520 throw new Error(`${label} was not written to ${filePath} within ${timeoutMs}ms.`);
521}
522
523async function reserveAvailablePort(): Promise<number> {
524 return await new Promise<number>((resolve, reject) => {
525 const server = NodeNet.createServer();
526 server.once("error", reject);
527 server.listen(0, "127.0.0.1", () => {
528 const address = server.address();
529 if (!address || typeof address === "string") {
530 server.close();
531 reject(new Error("Could not reserve a local port for the showcase environment."));
532 return;
533 }
534 server.close((error) => (error ? reject(error) : resolve(address.port)));
535 });
536 });
537}
538
539async function createShowcaseShell(baseDir: string): Promise<string> {
540 const shellPath = NodePath.join(baseDir, "showcase-shell");
541 await NodeFSP.writeFile(
542 shellPath,
543 `#!/bin/sh
544if [ "$1" = "-ilc" ] || [ "$1" = "-lic" ]; then
545 exec /bin/sh -c "$2"
546fi
547exec /bin/cat
548`,
549 { mode: 0o755 },
550 );
551 return shellPath;
552}
553
554async function createShowcaseLabelProbe(baseDir: string, label: string): Promise<string> {
555 const binDirectory = NodePath.join(baseDir, "showcase-bin");
556 await NodeFSP.mkdir(binDirectory, { recursive: true });
557 const probeScript = `#!/bin/sh
558if [ "$1" = "--get" ] && [ "$2" = "ComputerName" ]; then
559 printf '%s\\n' ${JSON.stringify(label)}
560 exit 0
561fi
562if [ "$1" = "--pretty" ]; then
563 printf '%s\\n' ${JSON.stringify(label)}
564 exit 0
565fi
566exit 1
567`;
568 await Promise.all(
569 ["scutil", "hostnamectl"].map((executable) =>
570 NodeFSP.writeFile(NodePath.join(binDirectory, executable), probeScript, { mode: 0o755 }),
571 ),
572 );
573 return binDirectory;
574}
575
576function startShowcaseServer(
577 baseDir: string,
578 workspaceRoot: string,
579 port: number,
580 shellPath: string,
581 labelProbeDirectory: string,
582): NodeChildProcess.ChildProcess {
583 return spawnProcess(
584 "node",
585 [
586 "apps/server/src/bin.ts",
587 "serve",
588 "--host",
589 SERVER_HOST,
590 "--port",
591 String(port),
592 "--base-dir",
593 baseDir,
594 "--no-browser",
595 "--log-level",
596 "error",
597 workspaceRoot,
598 ],
599 {
600 env: {
601 ...NodeProcess.env,
602 PATH: `${labelProbeDirectory}:${NodeProcess.env.PATH ?? ""}`,
603 SHELL: shellPath,
604 },
605 },
606 );
607}
608
609export function parsePairingCredentialOutput(output: string): string {
610 const jsonStart = output.indexOf("{");
611 const jsonEnd = output.lastIndexOf("}");
612 if (jsonStart === -1 || jsonEnd < jsonStart) {
613 throw new Error("Pairing credential command did not return JSON.");
614 }
615 const parsed = JSON.parse(output.slice(jsonStart, jsonEnd + 1)) as {
616 readonly credential?: unknown;
617 };
618 if (typeof parsed.credential !== "string" || parsed.credential.length === 0) {
619 throw new Error("Pairing credential command returned no credential.");
620 }
621 return parsed.credential;
622}
623
624async function issuePairingCredential(baseDir: string): Promise<string> {
625 const output = await commandOutput(
626 "node",
627 ["apps/server/src/bin.ts", "auth", "pairing", "create", "--base-dir", baseDir, "--json"],
628 { env: { ...NodeProcess.env, NO_COLOR: "1" } },
629 );
630 return parsePairingCredentialOutput(output);
631}
632
633function buildShowcasePairingUrl(host: string, port: number, credential: string): string {
634 const url = new URL(`http://${host}:${port}/`);
635 url.hash = new URLSearchParams([["token", credential]]).toString();
636 return url.toString();
637}
638
639export function showcaseSceneUrl(scene: ShowcaseScene, environmentId: string): string {
640 if (scene === "threads") return `${APP_SCHEME}://`;
641 if (scene === "environments") return `${APP_SCHEME}://settings/environments`;
642 const threadPath = `threads/${encodeURIComponent(environmentId)}/${SHOWCASE_THREAD_ID}`;
643 if (scene === "thread") return `${APP_SCHEME}://${threadPath}`;
644 if (scene === "terminal") {
645 return `${APP_SCHEME}://${threadPath}/terminal?terminalId=${SHOWCASE_TERMINAL_ID}`;
646 }
647 return `${APP_SCHEME}://${threadPath}/review`;
648}
649
650export function encodeAndroidPairingUrls(pairingUrls: ReadonlyArray<string>): string {
651 return `json-uri:${encodeURIComponent(JSON.stringify(pairingUrls))}`;
652}
653
654function startMetro(config: ShowcaseConfig): NodeChildProcess.ChildProcess {
655 return spawnProcess(
656 "pnpm",
657 ["exec", "expo", "start", "--dev-client", "--port", String(config.metroPort)],
658 {
659 cwd: MOBILE_ROOT,
660 env: {
661 ...MOBILE_BUILD_ENV,
662 EXPO_PUBLIC_SHOWCASE: "1",
663 },
664 },
665 );
666}
667
668async function warmMetroBundle(
669 platform: ShowcaseDevice["platform"],
670 host: string,
671 config: ShowcaseConfig,
672): Promise<void> {
673 const url = `http://${host}:${config.metroPort}/apps/mobile/index.bundle?platform=${platform}&dev=true&minify=false`;
674 await runCommand("curl", ["--fail", "--silent", "--show-error", "--output", "/dev/null", url]);
675}
676
677async function buildIos(): Promise<string> {
678 const derivedData = NodePath.join(MOBILE_ROOT, ".showcase/ios-derived-data");
679 await runCommand("pnpm", ["exec", "expo", "prebuild", "--clean", "--platform", "ios"], {
680 cwd: MOBILE_ROOT,
681 env: MOBILE_BUILD_ENV,
682 });
683 await runCommand(
684 "xcodebuild",
685 [
686 "-workspace",
687 NodePath.join(MOBILE_ROOT, "ios/T3Code.xcworkspace"),
688 "-scheme",
689 "T3Code",
690 "-configuration",
691 "Debug",
692 "-sdk",
693 "iphonesimulator",
694 "-derivedDataPath",
695 derivedData,
696 "-quiet",
697 `ARCHS=${IOS_SIMULATOR_ARCH}`,
698 "ONLY_ACTIVE_ARCH=YES",
699 "build",
700 ],
701 { cwd: MOBILE_ROOT, env: MOBILE_BUILD_ENV },
702 );
703 return IOS_APP_PATH;
704}
705
706async function buildAndroid(abis: ReadonlyArray<string>): Promise<string> {
707 await runCommand("pnpm", ["exec", "expo", "prebuild", "--clean", "--platform", "android"], {
708 cwd: MOBILE_ROOT,
709 env: MOBILE_BUILD_ENV,
710 });
711 await runCommand(
712 "./gradlew",
713 [
714 "app:assembleDebug",
715 ...(abis.length > 0 ? [`-PreactNativeArchitectures=${abis.join(",")}`] : []),
716 ],
717 {
718 cwd: NodePath.join(MOBILE_ROOT, "android"),
719 env: MOBILE_BUILD_ENV,
720 },
721 );
722 return ANDROID_APK_PATH;
723}
724
725async function existingArtifact(path: string): Promise<string | null> {
726 return await NodeFSP.access(path).then(
727 () => path,
728 () => null,
729 );
730}
731
732interface SimctlDevice {
733 readonly name: string;
734 readonly udid: string;
735 readonly state: "Booted" | "Shutdown" | string;
736 readonly isAvailable: boolean;
737}
738
739async function findIosSimulator(name: string): Promise<SimctlDevice | null> {
740 const parsed = JSON.parse(
741 await commandOutput("xcrun", ["simctl", "list", "devices", "available", "-j"]),
742 ) as {
743 readonly devices: Readonly<Record<string, ReadonlyArray<SimctlDevice>>>;
744 };
745 const candidates = Object.entries(parsed.devices)
746 .filter(([runtime]) => runtime.includes("iOS"))
747 .flatMap(([, devices]) => devices)
748 .filter((device) => device.isAvailable && device.name === name);
749 return candidates.at(-1) ?? null;
750}
751
752async function ensureIosSimulator(device: ShowcaseIosDevice): Promise<{
753 readonly simulator: SimctlDevice;
754 readonly createdByRunner: boolean;
755}> {
756 const existing = await findIosSimulator(device.simulator);
757 if (existing) return { simulator: existing, createdByRunner: false };
758 if (!device.simulatorDeviceType) {
759 throw new Error(
760 `iOS simulator '${device.simulator}' is not installed and has no simulatorDeviceType configured.`,
761 );
762 }
763 const udid = (
764 await commandOutput("xcrun", ["simctl", "create", device.simulator, device.simulatorDeviceType])
765 ).trim();
766 if (!udid) throw new Error(`Could not create iOS simulator '${device.simulator}'.`);
767 return {
768 simulator: {
769 name: device.simulator,
770 udid,
771 state: "Shutdown",
772 isAvailable: true,
773 },
774 createdByRunner: true,
775 };
776}
777
778async function normalizeIosSimulator(appearance: ShowcaseAppearance, udid: string): Promise<void> {
779 await runCommand("xcrun", ["simctl", "ui", udid, "appearance", appearance]);
780 await runCommand("xcrun", [
781 "simctl",
782 "status_bar",
783 udid,
784 "override",
785 "--time",
786 "9:41",
787 "--batteryState",
788 "charged",
789 "--batteryLevel",
790 "100",
791 "--wifiBars",
792 "3",
793 "--cellularBars",
794 "4",
795 ]);
796}
797
798// iPadOS 26 windowing ("Chamois") runs UIRequiresFullScreen apps in a fixed
799// portrait compatibility window, which defeats the in-app landscape rotation
800// the capture build relies on. Switch the device to Full Screen Apps mode
801// (Settings > Multitasking & Gestures) and restart SpringBoard to apply it.
802async function ensureIosFullScreenAppsMode(udid: string): Promise<void> {
803 const current = await commandOutput("xcrun", [
804 "simctl",
805 "spawn",
806 udid,
807 "defaults",
808 "read",
809 "com.apple.springboard",
810 "SBChamoisWindowingEnabled",
811 ]).catch(() => "");
812 if (current.trim() === "0") return;
813 // The Settings toggle writes all three keys; SBChamoisWindowingEnabled
814 // alone is not honored on a freshly created device.
815 for (const key of [
816 "SBChamoisWindowingEnabled",
817 "SBMedusaMultitaskingEnabled",
818 "SBFlexibleWindowingPreviouslyEnabledAutomaticStageCreation",
819 ]) {
820 await runCommand("xcrun", [
821 "simctl",
822 "spawn",
823 udid,
824 "defaults",
825 "write",
826 "com.apple.springboard",
827 key,
828 "-bool",
829 "false",
830 ]);
831 }
832 // A SpringBoard restart is not enough on a freshly created simulator (the
833 // first CI run captured with windowing still active), so reboot the device
834 // and verify the mode actually stuck.
835 await runCommand("xcrun", ["simctl", "shutdown", udid]);
836 await runCommand("xcrun", ["simctl", "boot", udid]);
837 await runCommand("xcrun", ["simctl", "bootstatus", udid, "-b"]);
838 const applied = await commandOutput("xcrun", [
839 "simctl",
840 "spawn",
841 udid,
842 "defaults",
843 "read",
844 "com.apple.springboard",
845 "SBChamoisWindowingEnabled",
846 ]).catch(() => "");
847 if (applied.trim() !== "0") {
848 throw new Error(`Simulator ${udid} did not switch to Full Screen Apps mode.`);
849 }
850}
851
852async function iosAppContainer(udid: string): Promise<string> {
853 return (
854 await commandOutput("xcrun", ["simctl", "get_app_container", udid, ANDROID_PACKAGE, "data"])
855 ).trim();
856}
857
858async function waitForIosShowcaseScene(
859 udid: string,
860 scene: ShowcaseScene,
861 timeoutMs = 90_000,
862): Promise<void> {
863 const readyPath = NodePath.join(
864 await iosAppContainer(udid),
865 "Library/Caches",
866 IOS_READY_FILENAME,
867 );
868 const deadline = Date.now() + timeoutMs;
869 while (Date.now() < deadline) {
870 const readyScene = await NodeFSP.readFile(readyPath, "utf8").catch(() => "");
871 if (readyScene.trim() === scene) return;
872 await delay(500);
873 }
874 throw new Error(`iOS showcase scene '${scene}' did not render within ${timeoutMs}ms.`);
875}
876
877async function captureIos(
878 capture: ShowcaseCapture & { readonly device: ShowcaseIosDevice },
879 appPath: string | null,
880 outputDirectory: string,
881 config: ShowcaseConfig,
882 metroHost: string,
883 pairingUrls: ReadonlyArray<string>,
884 registerCleanup: (cleanup: IosCaptureCleanup) => void,
885): Promise<void> {
886 const { simulator, createdByRunner } = await ensureIosSimulator(capture.device);
887 const startedByRunner = simulator.state !== "Booted";
888 registerCleanup({ udid: simulator.udid, startedByRunner, createdByRunner });
889 if (!startedByRunner) {
890 // Clear transient SpringBoard state (permission prompts, stale URL-open
891 // confirmations, keyboards) without erasing the developer's simulator.
892 await runCommand("xcrun", ["simctl", "shutdown", simulator.udid]);
893 }
894 await runCommand("xcrun", ["simctl", "boot", simulator.udid]);
895 await runCommand("xcrun", ["simctl", "bootstatus", simulator.udid, "-b"]);
896 if (capture.device.orientation === "landscape") {
897 await ensureIosFullScreenAppsMode(simulator.udid);
898 }
899 await normalizeIosSimulator(capture.appearance, simulator.udid);
900 if (appPath) {
901 await runCommand("xcrun", ["simctl", "uninstall", simulator.udid, ANDROID_PACKAGE]).catch(
902 () => undefined,
903 );
904 await runCommand("xcrun", ["simctl", "install", simulator.udid, appPath]);
905 }
906
907 for (const [key, value] of [
908 ["EXDevMenuIsOnboardingFinished", "true"],
909 ["EXDevMenuShowFloatingActionButton", "false"],
910 ["EXDevMenuShowsAtLaunch", "false"],
911 ] as const) {
912 await runCommand("xcrun", [
913 "simctl",
914 "spawn",
915 simulator.udid,
916 "defaults",
917 "write",
918 ANDROID_PACKAGE,
919 key,
920 "-bool",
921 value,
922 ]);
923 }
924
925 const metroUrl = `http://${metroHost}:${config.metroPort}?disableOnboarding=1`;
926 const scenePath = NodePath.join(
927 await iosAppContainer(simulator.udid),
928 "Library/Caches/T3ShowcaseScene",
929 );
930 const readyPath = NodePath.join(
931 await iosAppContainer(simulator.udid),
932 "Library/Caches",
933 IOS_READY_FILENAME,
934 );
935 const firstScene = capture.scenes[0] ?? "threads";
936 const launchShowcaseApp = async (terminateRunningProcess: boolean) => {
937 await runCommand("xcrun", [
938 "simctl",
939 "launch",
940 ...(terminateRunningProcess ? ["--terminate-running-process"] : []),
941 simulator.udid,
942 ANDROID_PACKAGE,
943 "--initialUrl",
944 metroUrl,
945 "--showcasePairingUrl",
946 JSON.stringify(pairingUrls),
947 "--showcaseScene",
948 firstScene,
949 // The app rotates itself; Simulator menu UI scripting needs macOS
950 // Accessibility permission that CI runners do not grant to osascript.
951 "--showcaseOrientation",
952 capture.device.orientation ?? "portrait",
953 ]);
954 };
955 await NodeFSP.rm(readyPath, { force: true });
956 await NodeFSP.writeFile(scenePath, firstScene);
957 await launchShowcaseApp(false);
958 for (const [sceneIndex, scene] of capture.scenes.entries()) {
959 if (sceneIndex > 0) await NodeFSP.rm(readyPath, { force: true });
960 await NodeFSP.writeFile(scenePath, scene);
961 if (sceneIndex === 0) {
962 for (let attempt = 0; attempt < 2; attempt += 1) {
963 const isLastAttempt = attempt === 1;
964 try {
965 // A freshly installed Expo development build can spend well over 30s
966 // applying an already-bundled update after it reaches 100%. Killing it
967 // at that point sends the next capture back to the dev launcher.
968 await waitForIosShowcaseScene(simulator.udid, scene, 120_000);
969 break;
970 } catch (error) {
971 if (isLastAttempt) throw error;
972 await launchShowcaseApp(true);
973 }
974 }
975 } else {
976 await waitForIosShowcaseScene(simulator.udid, scene);
977 }
978 await delay(scene === "review" ? Math.max(config.settleDelayMs, 8_000) : config.settleDelayMs);
979 const destination = NodePath.join(
980 showcaseCaptureDirectory(outputDirectory, capture),
981 `${scene}.png`,
982 );
983 await runCommand("xcrun", ["simctl", "io", simulator.udid, "screenshot", destination]);
984 if (capture.device.orientation === "landscape") {
985 // A headless simulator keeps its display portrait while the rotated app
986 // renders sideways inside it; with Simulator.app attached the display
987 // itself rotates. Only post-rotate the former.
988 const { width, height } = readPngDimensions(await NodeFSP.readFile(destination));
989 if (height > width) {
990 await runCommand("sips", ["--rotate", "270", destination]);
991 }
992 }
993 await finalizeCapture(destination, capture.device);
994 }
995}
996
997function androidSdkTool(relativePath: string): string {
998 return NodePath.join(ANDROID_SDK_ROOT, relativePath);
999}
1000
1001async function adbOutput(serial: string, args: ReadonlyArray<string>): Promise<string> {
1002 return await commandOutput(androidSdkTool("platform-tools/adb"), ["-s", serial, ...args]);
1003}
1004
1005async function runAdb(serial: string, args: ReadonlyArray<string>): Promise<void> {
1006 await runCommand(androidSdkTool("platform-tools/adb"), ["-s", serial, ...args]);
1007}
1008
1009async function runningAndroidAvds(): Promise<ReadonlyMap<string, string>> {
1010 const adb = androidSdkTool("platform-tools/adb");
1011 const devices = (await commandOutput(adb, ["devices"]))
1012 .split("\n")
1013 .map((line) => line.trim().split(/\s+/u))
1014 .filter((parts) => parts[0]?.startsWith("emulator-") && parts[1] === "device")
1015 .map((parts) => parts[0] as string);
1016 const result = new Map<string, string>();
1017 for (const serial of devices) {
1018 const avdName = (await adbOutput(serial, ["emu", "avd", "name"])).split("\n")[0]?.trim();
1019 if (avdName) result.set(avdName, serial);
1020 }
1021 return result;
1022}
1023
1024async function waitForAndroidSerial(avd: string, timeoutMs = 120_000): Promise<string> {
1025 const deadline = Date.now() + timeoutMs;
1026 while (Date.now() < deadline) {
1027 const serial = (await runningAndroidAvds()).get(avd);
1028 if (serial) {
1029 await runAdb(serial, ["wait-for-device"]);
1030 const bootCompleted = (
1031 await adbOutput(serial, ["shell", "getprop", "sys.boot_completed"])
1032 ).trim();
1033 if (bootCompleted === "1") return serial;
1034 }
1035 await delay(1_000);
1036 }
1037 throw new Error(`Android AVD '${avd}' did not finish booting within ${timeoutMs}ms.`);
1038}
1039
1040async function normalizeAndroidEmulator(
1041 device: ShowcaseAndroidDevice,
1042 appearance: ShowcaseAppearance,
1043 serial: string,
1044): Promise<void> {
1045 await runAdb(serial, ["shell", "settings", "put", "global", "window_animation_scale", "0"]);
1046 await runAdb(serial, ["shell", "settings", "put", "global", "transition_animation_scale", "0"]);
1047 await runAdb(serial, ["shell", "settings", "put", "global", "animator_duration_scale", "0"]);
1048 await runAdb(serial, ["shell", "cmd", "uimode", "night", appearance === "dark" ? "yes" : "no"]);
1049 await runAdb(serial, ["shell", "settings", "put", "system", "time_12_24", "12"]);
1050 await runAdb(serial, ["emu", "power", "capacity", "100"]);
1051 await runAdb(serial, ["shell", "settings", "put", "global", "sysui_demo_allowed", "1"]);
1052 await runAdb(serial, [
1053 "shell",
1054 "am",
1055 "broadcast",
1056 "-a",
1057 "com.android.systemui.demo",
1058 "-e",
1059 "command",
1060 "enter",
1061 ]);
1062 await runAdb(serial, [
1063 "shell",
1064 "am",
1065 "broadcast",
1066 "-a",
1067 "com.android.systemui.demo",
1068 "-e",
1069 "command",
1070 "clock",
1071 "-e",
1072 "hhmm",
1073 "0941",
1074 ]);
1075 await runAdb(serial, [
1076 "shell",
1077 "am",
1078 "broadcast",
1079 "-a",
1080 "com.android.systemui.demo",
1081 "-e",
1082 "command",
1083 "battery",
1084 "-e",
1085 "level",
1086 "100",
1087 "-e",
1088 "plugged",
1089 "false",
1090 ]);
1091 if (device.viewport) {
1092 await runAdb(serial, [
1093 "shell",
1094 "wm",
1095 "size",
1096 `${device.viewport.width}x${device.viewport.height}`,
1097 ]);
1098 if (device.viewport.density) {
1099 await runAdb(serial, ["shell", "wm", "density", String(device.viewport.density)]);
1100 }
1101 }
1102}
1103
1104async function waitForAndroidShowcaseScene(
1105 serial: string,
1106 scene: ShowcaseScene,
1107 timeoutMs = 90_000,
1108): Promise<void> {
1109 const deadline = Date.now() + timeoutMs;
1110 while (Date.now() < deadline) {
1111 const readyScene = await adbOutput(serial, [
1112 "shell",
1113 "run-as",
1114 ANDROID_PACKAGE,
1115 "cat",
1116 "files/t3-showcase-ready",
1117 ]).catch(() => "");
1118 if (readyScene.trim() === scene) return;
1119 await delay(500);
1120 }
1121 throw new Error(`Android showcase scene '${scene}' did not render within ${timeoutMs}ms.`);
1122}
1123
1124async function writeAndroidShowcaseScene(serial: string, scene: ShowcaseScene): Promise<void> {
1125 await runAdb(serial, [
1126 "shell",
1127 `run-as ${ANDROID_PACKAGE} sh -c 'mkdir -p files && rm -f files/t3-showcase-ready && printf %s ${scene} > files/t3-showcase-scene'`,
1128 ]);
1129}
1130
1131async function prepareAndroidShowcaseApp(serial: string): Promise<void> {
1132 const preferences = `<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
1133<map>
1134 <boolean name="isOnboardingFinished" value="true" />
1135 <boolean name="showsAtLaunch" value="false" />
1136 <boolean name="showFab" value="false" />
1137 <boolean name="motionGestureEnabled" value="false" />
1138 <boolean name="touchGestureEnabled" value="false" />
1139 <boolean name="keyCommandsEnabled" value="false" />
1140</map>`;
1141 const encodedPreferences = Buffer.from(preferences).toString("base64");
1142 await runAdb(serial, [
1143 "shell",
1144 `run-as ${ANDROID_PACKAGE} sh -c 'mkdir -p shared_prefs && printf %s ${encodedPreferences} | base64 -d > shared_prefs/expo.modules.devmenu.sharedpreferences.xml'`,
1145 ]);
1146}
1147
1148async function captureAndroid(
1149 capture: ShowcaseCapture & { readonly device: ShowcaseAndroidDevice },
1150 apkPath: string | null,
1151 outputDirectory: string,
1152 config: ShowcaseConfig,
1153 pairingUrls: ReadonlyArray<string>,
1154 registerCleanup: (cleanup: AndroidCaptureCleanup) => void,
1155): Promise<void> {
1156 const running = await runningAndroidAvds();
1157 const existingSerial = running.get(capture.device.avd);
1158 const startedByRunner = !existingSerial;
1159 let launchedEmulator: NodeChildProcess.ChildProcess | null = null;
1160 if (startedByRunner) {
1161 const installedAvds = (await commandOutput(androidSdkTool("emulator/emulator"), ["-list-avds"]))
1162 .split("\n")
1163 .map((value) => value.trim());
1164 if (!installedAvds.includes(capture.device.avd)) {
1165 throw new Error(
1166 `Android AVD '${capture.device.avd}' is not installed. Run emulator -list-avds.`,
1167 );
1168 }
1169 launchedEmulator = spawnProcess(
1170 androidSdkTool("emulator/emulator"),
1171 ["-avd", capture.device.avd, "-no-snapshot-load", "-no-boot-anim"],
1172 { stdio: "ignore", detached: true },
1173 );
1174 launchedEmulator.unref();
1175 }
1176 const serial =
1177 existingSerial ??
1178 (await waitForAndroidSerial(capture.device.avd).catch(async (error: unknown) => {
1179 if (launchedEmulator) await stopProcess(launchedEmulator);
1180 throw error;
1181 }));
1182 registerCleanup({ device: capture.device, serial, startedByRunner });
1183 await normalizeAndroidEmulator(capture.device, capture.appearance, serial);
1184 if (apkPath) {
1185 await runAdb(serial, ["install", "-r", apkPath]);
1186 }
1187 await runAdb(serial, ["shell", "pm", "clear", ANDROID_PACKAGE]);
1188 await prepareAndroidShowcaseApp(serial);
1189 await runAdb(serial, ["reverse", `tcp:${config.metroPort}`, `tcp:${config.metroPort}`]);
1190 const metroUrl = encodeURIComponent(`http://127.0.0.1:${config.metroPort}?disableOnboarding=1`);
1191 const firstScene = capture.scenes[0] ?? "threads";
1192 await runAdb(serial, [
1193 "shell",
1194 "am",
1195 "start",
1196 "-W",
1197 "-a",
1198 "android.intent.action.VIEW",
1199 "-d",
1200 `${APP_SCHEME}://expo-development-client/?url=${metroUrl}`,
1201 "--es",
1202 "showcasePairingUrl",
1203 encodeAndroidPairingUrls(pairingUrls),
1204 "--es",
1205 "showcaseScene",
1206 firstScene,
1207 ANDROID_PACKAGE,
1208 ]);
1209 for (const [sceneIndex, scene] of capture.scenes.entries()) {
1210 if (sceneIndex > 0) await writeAndroidShowcaseScene(serial, scene);
1211 await waitForAndroidShowcaseScene(serial, scene);
1212 await delay(Math.max(config.settleDelayMs, scene === "review" ? 8_000 : 5_000));
1213 const destination = NodePath.join(
1214 showcaseCaptureDirectory(outputDirectory, capture),
1215 `${scene}.png`,
1216 );
1217 const png = await new Promise<Buffer>((resolve, reject) => {
1218 NodeChildProcess.execFile(
1219 androidSdkTool("platform-tools/adb"),
1220 ["-s", serial, "exec-out", "screencap", "-p"],
1221 { cwd: REPO_ROOT, encoding: "buffer", maxBuffer: 64 * 1024 * 1024 },
1222 (error, stdout) => {
1223 if (error) reject(error);
1224 else resolve(stdout);
1225 },
1226 );
1227 });
1228 await NodeFSP.writeFile(destination, png);
1229 await finalizeCapture(destination, capture.device);
1230 }
1231}
1232
1233async function cleanupAndroidViewport(
1234 device: ShowcaseAndroidDevice,
1235 serial: string,
1236): Promise<void> {
1237 await runAdb(serial, [
1238 "shell",
1239 "am",
1240 "broadcast",
1241 "-a",
1242 "com.android.systemui.demo",
1243 "-e",
1244 "command",
1245 "exit",
1246 ]);
1247 if (!device.viewport) return;
1248 await runAdb(serial, ["shell", "wm", "size", "reset"]);
1249 if (device.viewport.density) {
1250 await runAdb(serial, ["shell", "wm", "density", "reset"]);
1251 }
1252}
1253
1254async function main(): Promise<void> {
1255 const options = parseShowcaseCliArgs(NodeProcess.argv.slice(2));
1256 if (options.list) {
1257 printUsage(showcaseConfig);
1258 return;
1259 }
1260 const captures = planShowcaseCaptures(showcaseConfig, options);
1261 const outputDirectory = NodePath.resolve(REPO_ROOT, showcaseConfig.outputDirectory);
1262 if (options.validateOnly) {
1263 for (const capture of captures) {
1264 await validateCaptureSet(
1265 capture,
1266 outputDirectory,
1267 capture.scenes.length === capture.device.scenes.length,
1268 );
1269 }
1270 return;
1271 }
1272 const hasIos = captures.some((capture) => capture.device.platform === "ios");
1273 const hasAndroid = captures.some((capture) => capture.device.platform === "android");
1274 const metroHost = hasIos ? lanIpv4Address() : "127.0.0.1";
1275 await NodeFSP.mkdir(outputDirectory, { recursive: true });
1276 for (const capture of captures) {
1277 const directory = showcaseCaptureDirectory(outputDirectory, capture);
1278 await NodeFSP.rm(directory, { recursive: true, force: true });
1279 await NodeFSP.mkdir(directory, { recursive: true });
1280 }
1281
1282 const showcaseRootDir = await NodeFSP.mkdtemp(
1283 NodePath.join(NodeOS.tmpdir(), "t3-mobile-showcase-"),
1284 );
1285 const showcaseServers: NodeChildProcess.ChildProcess[] = [];
1286 const showcaseEnvironments: Array<{
1287 readonly baseDir: string;
1288 readonly environmentId: string;
1289 readonly label: string;
1290 readonly port: number;
1291 }> = [];
1292 let metro: NodeChildProcess.ChildProcess | null = null;
1293 const iosCleanups: IosCaptureCleanup[] = [];
1294 const androidCleanups: AndroidCaptureCleanup[] = [];
1295
1296 try {
1297 for (const environment of SHOWCASE_ENVIRONMENTS) {
1298 const projectId = environment.projectIds[0];
1299 const project = SHOWCASE_PROJECTS.find((candidate) => candidate.id === projectId);
1300 if (!project) throw new Error(`Showcase environment '${environment.id}' has no project.`);
1301
1302 const baseDir = NodePath.join(showcaseRootDir, "environments", environment.id);
1303 const workspaceRoot = NodePath.join(baseDir, "workspace", project.directory);
1304 const port = await reserveAvailablePort();
1305 await NodeFSP.mkdir(workspaceRoot, { recursive: true });
1306 const shellPath = await createShowcaseShell(baseDir);
1307 const labelProbeDirectory = await createShowcaseLabelProbe(baseDir, environment.label);
1308 const server = startShowcaseServer(
1309 baseDir,
1310 workspaceRoot,
1311 port,
1312 shellPath,
1313 labelProbeDirectory,
1314 );
1315 showcaseServers.push(server);
1316 await waitForPort(port, `${environment.label} server`);
1317 await seedShowcaseEnvironment({ baseDir, projectIds: environment.projectIds });
1318 // The server begins listening before the ServerEnvironment layer
1319 // persists the environment id, so poll rather than read once.
1320 const environmentId = await waitForFileContent(
1321 NodePath.join(baseDir, "userdata", "environment-id"),
1322 `${environment.label} environment id`,
1323 );
1324 showcaseEnvironments.push({ baseDir, environmentId, label: environment.label, port });
1325 }
1326
1327 if (!options.skipMetro) {
1328 metro = startMetro(showcaseConfig);
1329 await waitForPort(showcaseConfig.metroPort, "Metro");
1330 await Promise.all([
1331 hasIos ? warmMetroBundle("ios", metroHost, showcaseConfig) : Promise.resolve(),
1332 hasAndroid ? warmMetroBundle("android", "127.0.0.1", showcaseConfig) : Promise.resolve(),
1333 ]);
1334 }
1335
1336 const iosAppPath = hasIos
1337 ? options.skipBuild
1338 ? await existingArtifact(IOS_APP_PATH)
1339 : await buildIos()
1340 : null;
1341 const androidAbis = captures.flatMap((capture) =>
1342 capture.device.platform === "android" && capture.device.abi ? [capture.device.abi] : [],
1343 );
1344 const androidApkPath = hasAndroid
1345 ? options.skipBuild
1346 ? await existingArtifact(ANDROID_APK_PATH)
1347 : await buildAndroid([...new Set(androidAbis)])
1348 : null;
1349
1350 for (const capture of captures) {
1351 const pairingHost = capture.device.platform === "ios" ? "127.0.0.1" : "10.0.2.2";
1352 const pairingUrls = await Promise.all(
1353 showcaseEnvironments.map(async (environment) => {
1354 const credential = await issuePairingCredential(environment.baseDir);
1355 return buildShowcasePairingUrl(pairingHost, environment.port, credential);
1356 }),
1357 );
1358 if (capture.device.platform === "ios") {
1359 await captureIos(
1360 capture as ShowcaseCapture & { readonly device: ShowcaseIosDevice },
1361 iosAppPath,
1362 outputDirectory,
1363 showcaseConfig,
1364 metroHost,
1365 pairingUrls,
1366 (cleanup) => iosCleanups.push(cleanup),
1367 );
1368 } else {
1369 await captureAndroid(
1370 capture as ShowcaseCapture & { readonly device: ShowcaseAndroidDevice },
1371 androidApkPath,
1372 outputDirectory,
1373 showcaseConfig,
1374 pairingUrls,
1375 (cleanup) => androidCleanups.push(cleanup),
1376 );
1377 }
1378 await validateCaptureSet(
1379 capture,
1380 outputDirectory,
1381 capture.scenes.length === capture.device.scenes.length,
1382 );
1383 }
1384
1385 NodeProcess.stdout.write(
1386 `\nDone. Upload-ready screenshots are in ${NodePath.relative(REPO_ROOT, outputDirectory)}/apple/ and ${NodePath.relative(REPO_ROOT, outputDirectory)}/google-play/.\n`,
1387 );
1388 if (options.keepRunning) {
1389 const serverSummary = showcaseEnvironments
1390 .map((environment) => `${environment.label}:${environment.port}`)
1391 .join(", ");
1392 NodeProcess.stdout.write(
1393 `Showcase environments kept at ${showcaseRootDir} (${serverSummary}).\n`,
1394 );
1395 }
1396 } finally {
1397 if (options.keepRunning) {
1398 metro?.unref();
1399 for (const server of showcaseServers) server.unref();
1400 } else {
1401 for (const cleanup of androidCleanups) {
1402 await cleanupAndroidViewport(cleanup.device, cleanup.serial).catch(() => undefined);
1403 if (cleanup.startedByRunner) {
1404 await runAdb(cleanup.serial, ["emu", "kill"]).catch(() => undefined);
1405 }
1406 }
1407 for (const cleanup of iosCleanups) {
1408 if (cleanup.startedByRunner || cleanup.createdByRunner) {
1409 await runCommand("xcrun", ["simctl", "shutdown", cleanup.udid]).catch(() => undefined);
1410 }
1411 if (cleanup.createdByRunner) {
1412 await runCommand("xcrun", ["simctl", "delete", cleanup.udid]).catch(() => undefined);
1413 }
1414 }
1415 await Promise.all([
1416 ...(metro ? [stopProcess(metro)] : []),
1417 ...showcaseServers.map((server) => stopProcess(server)),
1418 ]);
1419 await NodeFSP.rm(showcaseRootDir, {
1420 recursive: true,
1421 force: true,
1422 maxRetries: 5,
1423 retryDelay: 100,
1424 });
1425 }
1426 }
1427}
1428
1429if (import.meta.main) {
1430 void main().catch((error: unknown) => {
1431 // Stack over message: the harness only fails in CI, where the line that
1432 // threw is the whole diagnosis and there is nobody at a terminal to
1433 // re-run it with more output.
1434 NodeProcess.stderr.write(
1435 `${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`,
1436 );
1437 NodeProcess.exit(1);
1438 });
1439}