Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

mobile-showcase.ts

1,475 lines48.6 KB

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