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

screenshot.ts

31 lines1.4 KB

1// @effect-diagnostics globalFetch:off - This browser transport runs without an Effect runtime, like the live stream.
2import * as Schema from "effect/Schema";
3import { extractPng } from "@t3tools/shared/png";
4import { withDeviceHubQuery } from "./hubAccess.ts";
5import type { DeviceStreamTarget } from "./stream.ts";
6​
7export class DeviceScreenshotError extends Schema.TaggedError<DeviceScreenshotError>()(
8 "DeviceScreenshotError",
9 { status: Schema.Number },
10) {
11 override get message(): string {
12 return `Screenshot capture failed (${this.status}). Try again.`;
13 }
15​
16export async function captureDeviceScreenshot(target: DeviceStreamTarget, signal: AbortSignal) {
17 const vendor = target.platform === "ios" ? "serve-sim" : "serve-emu";
18 const url = withDeviceHubQuery(
19 `${target.access.httpBase}/vendor/${vendor}/api/screenshot?device=${encodeURIComponent(target.deviceId)}`,
20 target.access,
21 );
22 const response = await fetch(url, {
23 method: "POST",
24 credentials: target.access.credentials ? "include" : "omit",
25 signal: AbortSignal.any([signal, AbortSignal.timeout(20_000)]),
26 });
27 if (!response.ok) throw new DeviceScreenshotError({ status: response.status });
28 const png = extractPng(new Uint8Array(await response.arrayBuffer()));
29 if (!png) throw new Error("The device returned an incomplete screenshot. Try again.");
30 return new Blob([png], { type: "image/png" });