diff --git a/scripts/mobile-audit.ts b/scripts/mobile-audit.ts index dfb30070de2e2..19b0d87e3db10 100644 --- a/scripts/mobile-audit.ts +++ b/scripts/mobile-audit.ts @@ -1,18 +1,28 @@ #!/usr/bin/env node -// @effect-diagnostics nodeBuiltinImport:off - Host-side mobile accessibility audit CLI uses Node subprocess and filesystem APIs directly. - -import * as NodeChildProcess from "node:child_process"; -import * as NodeFS from "node:fs"; -import * as NodeFSP from "node:fs/promises"; -import * as NodePath from "node:path"; -import * as NodeProcess from "node:process"; -import * as NodeURL from "node:url"; +import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { fromJsonStringPretty } from "@t3tools/shared/schemaJson"; +import * as Console from "effect/Console"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; +import { Argument, Command, Flag } from "effect/cli"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; import { renderBeforeAfterComparison, renderSingleAnnotatedImage, } from "./mobile-audit/annotate.ts"; import { + AgentDeviceEnvelopeSchema, + AuditCaptureSchema, + AuditPayloadSchema, + AuditPlatformSchema, + RawSnapshotDataSchema, buildOverlayBoxes, diffAuditCaptures, findingTag, @@ -21,216 +31,258 @@ import { resolveViewport, unitForPlatform, type AuditCapture, - type AuditFinding, type AuditPlatform, - type RawSnapshotData, type ScreenDiff, } from "./mobile-audit/diff.ts"; -const REPO_ROOT = NodePath.resolve(NodePath.dirname(NodeURL.fileURLToPath(import.meta.url)), ".."); -const DEFAULT_AGENT_DEVICE_ENTRY = NodePath.join( - REPO_ROOT, - "scripts/node_modules/agent-device/bin/agent-device.mjs", -); - -function usage(): never { - NodeProcess.stderr.write(`Usage: - vp run mobile:audit capture --platform --screen --out [--agent-device ] [-- ] - vp run mobile:audit compare --before --after --out [--before-label ] [--after-label ] [--all] [--fail-on-regression] - vp run mobile:audit report --dir --out -`); - NodeProcess.exit(2); -} - -function parseFlags(argv: ReadonlyArray) { - const separator = argv.indexOf("--"); - const own = separator >= 0 ? argv.slice(0, separator) : argv; - const passThrough = separator >= 0 ? argv.slice(separator + 1) : []; - const flags = new Map(); - for (let i = 0; i < own.length; i++) { - const token = own[i]!; - if (!token.startsWith("--")) continue; - const eq = token.indexOf("="); - if (eq >= 0) { - flags.set(token.slice(2, eq), token.slice(eq + 1)); - } else { - const next = own[i + 1]; - if (next !== undefined && !next.startsWith("--")) { - flags.set(token.slice(2), next); - i += 1; - } else { - flags.set(token.slice(2), true); - } - } +class MobileAuditError extends Schema.TaggedError< + MobileAuditError, + { readonly brand: unique symbol } +>()("MobileAuditError", { + operation: Schema.String, + detail: Schema.String, + cause: Schema.optional(Schema.Defect()), +}) { + override get message(): string { + return `${this.operation}: ${this.detail}`; } - return { flags, passThrough }; } -function requiredString(flags: Map, name: string): string { - const value = flags.get(name); - if (typeof value !== "string" || value.trim().length === 0) { - NodeProcess.stderr.write(`Missing required flag: --${name}\n`); - usage(); +const decodeEnvelope = Schema.decodeUnknownEffect(Schema.fromJsonString(AgentDeviceEnvelopeSchema)); +const decodeAuditPayload = Schema.decodeUnknownEffect(AuditPayloadSchema); +const decodeRawSnapshot = Schema.decodeUnknownEffect(RawSnapshotDataSchema); +const decodeAuditCapture = Schema.decodeUnknownEffect(Schema.fromJsonString(AuditCaptureSchema)); +const encodeAuditCapture = Schema.encodeEffect(fromJsonStringPretty(AuditCaptureSchema)); +const encodePrettyJson = Schema.encodeEffect(fromJsonStringPretty(Schema.Unknown)); + +const execAgentDevice = Effect.fn("mobileAudit.execAgentDevice")(function* ( + bin: Option.Option, + args: ReadonlyArray, +) { + const path = yield* Path.Path; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const execPath = yield* HostProcess.ExecutablePath; + const defaultEntry = path.resolve( + import.meta.dirname, + "../scripts/node_modules/agent-device/bin/agent-device.mjs", + ); + const program = Option.isSome(bin) ? bin.value : execPath; + const fullArgs = Option.isSome(bin) ? [...args] : [defaultEntry, ...args]; + + const child = yield* spawner.spawn( + ChildProcess.make(program, fullArgs, { + stdin: "ignore", + stdout: "pipe", + stderr: "pipe", + }), + ); + const [stdout, stderr, exitCode] = yield* Effect.all( + [ + Stream.mkString(Stream.decodeText(child.stdout)), + Stream.mkString(Stream.decodeText(child.stderr)), + child.exitCode, + ], + { concurrency: "unbounded" }, + ); + if (exitCode !== 0) { + return yield* new MobileAuditError({ + operation: `agent-device ${args[0] ?? ""}`.trim(), + detail: `exited with ${exitCode}: ${stderr.trim().slice(-600)}`, + }); } - return value; -} - -function execAgentDevice(bin: string | undefined, args: ReadonlyArray): string { - const file = bin ?? NodeProcess.execPath; - const fullArgs = bin ? args : [DEFAULT_AGENT_DEVICE_ENTRY, ...args]; - return NodeChildProcess.execFileSync(file, fullArgs, { - encoding: "utf8", - maxBuffer: 50 * 1024 * 1024, - }); -} - -function parseJsonPayload(raw: string, label: string): T { - const parsed = JSON.parse(raw) as { - readonly success?: boolean; - readonly data?: T; - readonly error?: { readonly message?: string; readonly hint?: string }; - }; - if (parsed.success === false) { - throw new Error( - `${label} failed: ${parsed.error?.message ?? "unknown error"}${parsed.error?.hint ? ` (${parsed.error.hint})` : ""}`, + return stdout; +}, Effect.scoped); + +const decodeAgentDeviceJson = ( + schema: S, + decodeData: (input: unknown) => Effect.Effect, +) => + Effect.fn("mobileAudit.decodeJson")(function* (raw: string, label: string) { + const envelope = yield* decodeEnvelope(raw).pipe( + Effect.mapError( + (cause) => + new MobileAuditError({ + operation: label, + detail: "invalid JSON response", + cause, + }), + ), ); - } - return (parsed.data ?? parsed) as T; -} + if (envelope.success === false) { + const hint = envelope.error?.hint ? ` (${envelope.error.hint})` : ""; + return yield* new MobileAuditError({ + operation: label, + detail: `${envelope.error?.message ?? "unknown error"}${hint}`, + }); + } + const payload = envelope.data ?? envelope; + return yield* decodeData(payload).pipe( + Effect.mapError( + (cause) => + new MobileAuditError({ + operation: label, + detail: "unexpected payload shape", + cause, + }), + ), + ); + }); -async function runCapture(argv: ReadonlyArray) { - const { flags, passThrough } = parseFlags(argv); - const platformRaw = requiredString(flags, "platform"); - if (platformRaw !== "ios" && platformRaw !== "android") { - throw new Error(`Invalid --platform "${platformRaw}" (expected ios or android).`); - } - const platform: AuditPlatform = platformRaw; - const screen = requiredString(flags, "screen"); - const outRoot = NodePath.resolve(requiredString(flags, "out")); - const agentDevice = - typeof flags.get("agent-device") === "string" - ? (flags.get("agent-device") as string) - : undefined; - - const platformDir = NodePath.join(outRoot, platform); - await NodeFSP.mkdir(platformDir, { recursive: true }); - - const pngPath = NodePath.join(platformDir, `${screen}.png`); +const decodeAuditJson = decodeAgentDeviceJson(AuditPayloadSchema, decodeAuditPayload); +const decodeRawSnapshotJson = decodeAgentDeviceJson(RawSnapshotDataSchema, decodeRawSnapshot); + +const runCapture = Effect.fn("mobileAudit.capture")(function* (input: { + readonly platform: AuditPlatform; + readonly screen: string; + readonly out: string; + readonly agentDevice: Option.Option; + readonly agentDeviceArgs: ReadonlyArray; +}) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cwd = yield* HostProcess.WorkingDirectory; + const outRoot = path.resolve(cwd, input.out); + const platformDir = path.join(outRoot, input.platform); + yield* fs.makeDirectory(platformDir, { recursive: true }); + + const pngPath = path.join(platformDir, `${input.screen}.png`); const screenshotArgs = - platform === "ios" - ? ["screenshot", "--pixel-density", "3", pngPath, ...passThrough] - : ["screenshot", pngPath, ...passThrough]; - execAgentDevice(agentDevice, screenshotArgs); - - const auditRaw = execAgentDevice(agentDevice, ["audit", "--json", ...passThrough]); - const auditData = parseJsonPayload<{ - readonly findings?: ReadonlyArray; - readonly guidance?: Readonly>; - readonly limitations?: ReadonlyArray; - }>(auditRaw, "agent-device audit"); - - const snapRaw = execAgentDevice(agentDevice, ["snapshot", "--raw", "--json", ...passThrough]); - const snapData = parseJsonPayload(snapRaw, "agent-device snapshot"); - + input.platform === "ios" + ? ["screenshot", "--pixel-density", "3", pngPath, ...input.agentDeviceArgs] + : ["screenshot", pngPath, ...input.agentDeviceArgs]; + yield* execAgentDevice(input.agentDevice, screenshotArgs); + + const auditRaw = yield* execAgentDevice(input.agentDevice, [ + "audit", + "--json", + ...input.agentDeviceArgs, + ]); + const auditData = yield* decodeAuditJson(auditRaw, "agent-device audit"); + + const snapRaw = yield* execAgentDevice(input.agentDevice, [ + "snapshot", + "--raw", + "--json", + ...input.agentDeviceArgs, + ]); + const snapData = yield* decodeRawSnapshotJson(snapRaw, "agent-device snapshot"); + + const viewport = resolveViewport({}, snapData); const capture: AuditCapture = { - platform, - screen, - viewport: resolveViewport({}, snapData), - pixelDensity: platform === "android" ? (snapData.androidSnapshot?.pixelDensity ?? 1) : 1, + platform: input.platform, + screen: input.screen, + ...(viewport === undefined ? {} : { viewport }), + pixelDensity: input.platform === "android" ? (snapData.androidSnapshot?.pixelDensity ?? 1) : 1, findings: auditData.findings ?? [], - guidance: auditData.guidance, - limitations: auditData.limitations, + ...(auditData.guidance === undefined ? {} : { guidance: auditData.guidance }), + ...(auditData.limitations === undefined ? {} : { limitations: auditData.limitations }), }; - await NodeFSP.writeFile(NodePath.join(platformDir, `${screen}.raw.json`), snapRaw); - await NodeFSP.writeFile( - NodePath.join(platformDir, `${screen}.audit.json`), - `${JSON.stringify(capture, null, 2)}\n`, + yield* fs.writeFileString(path.join(platformDir, `${input.screen}.raw.json`), snapRaw); + const encodedCapture = yield* encodeAuditCapture(capture); + yield* fs.writeFileString( + path.join(platformDir, `${input.screen}.audit.json`), + `${encodedCapture}\n`, ); - const unit = unitForPlatform(platform); - NodeProcess.stdout.write( - `[${platform}] ${screen}: ${capture.findings.length} finding(s) -> ${pngPath}\n`, + const unit = unitForPlatform(input.platform); + yield* Console.log( + `[${input.platform}] ${input.screen}: ${capture.findings.length} finding(s) -> ${pngPath}`, ); for (const finding of capture.findings) { - NodeProcess.stdout.write( - ` [${finding.kind}] ${finding.role} ${findingTag(finding, capture.pixelDensity, unit)} ${finding.label ? JSON.stringify(finding.label) : "(unnamed)"}\n`, + yield* Console.log( + ` [${finding.kind}] ${finding.role} ${findingTag(finding, capture.pixelDensity, unit)} ${finding.label ? `"${finding.label}"` : "(unnamed)"}`, ); } -} +}); -async function listCapturedScreens( +const listCapturedScreens = Effect.fn("mobileAudit.listCapturedScreens")(function* ( rootDir: string, -): Promise> { +) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; const results: Array<{ readonly platform: AuditPlatform; readonly screen: string }> = []; - for (const platform of ["ios", "android"] as const) { - const dir = NodePath.join(rootDir, platform); - if (!NodeFS.existsSync(dir)) continue; - const files = (await NodeFSP.readdir(dir)).filter((f) => f.endsWith(".audit.json")).sort(); + for (const platform of AuditPlatformSchema.literals) { + const dir = path.join(rootDir, platform); + if (!(yield* fs.exists(dir))) continue; + const files = (yield* fs.readDirectory(dir)).filter((f) => f.endsWith(".audit.json")).sort(); for (const file of files) { results.push({ platform, screen: file.replace(/\.audit\.json$/, "") }); } } return results; -} +}); -async function readCaptureSet(rootDir: string, platform: AuditPlatform, screen: string) { - const base = NodePath.join(rootDir, platform, screen); - const parsed = JSON.parse( - await NodeFSP.readFile(`${base}.audit.json`, "utf8"), - ) as Partial; - const capture: AuditCapture = { - platform: parsed.platform ?? platform, - screen: parsed.screen ?? screen, - viewport: parsed.viewport, - pixelDensity: parsed.pixelDensity ?? 1, - findings: parsed.findings ?? [], - guidance: parsed.guidance, - limitations: parsed.limitations, - }; +const readCaptureSet = Effect.fn("mobileAudit.readCaptureSet")(function* ( + rootDir: string, + platform: AuditPlatform, + screen: string, +) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const base = path.join(rootDir, platform, screen); + const auditPath = `${base}.audit.json`; + const capture = yield* fs.readFileString(auditPath).pipe( + Effect.flatMap(decodeAuditCapture), + Effect.mapError( + (cause) => + new MobileAuditError({ + operation: "readCaptureSet", + detail: `failed to read ${auditPath}`, + cause, + }), + ), + ); const rawPath = `${base}.raw.json`; - const raw = NodeFS.existsSync(rawPath) - ? parseJsonPayload(await NodeFSP.readFile(rawPath, "utf8"), rawPath) + const raw = (yield* fs.exists(rawPath)) + ? yield* fs + .readFileString(rawPath) + .pipe(Effect.flatMap((content) => decodeRawSnapshotJson(content, rawPath))) : undefined; return { capture, raw, pngPath: `${base}.png`, }; -} - -async function runCompare(argv: ReadonlyArray) { - const { flags } = parseFlags(argv); - const beforeDir = NodePath.resolve(requiredString(flags, "before")); - const afterDir = NodePath.resolve(requiredString(flags, "after")); - const outDir = NodePath.resolve(requiredString(flags, "out")); - const beforeLabel = - typeof flags.get("before-label") === "string" - ? (flags.get("before-label") as string) - : "BEFORE (base)"; - const afterLabel = - typeof flags.get("after-label") === "string" - ? (flags.get("after-label") as string) - : "AFTER (head)"; - const renderAll = flags.get("all") === true; - const failOnRegression = flags.get("fail-on-regression") === true; - - await NodeFSP.mkdir(outDir, { recursive: true }); - const beforeScreens = await listCapturedScreens(beforeDir); - const afterScreens = await listCapturedScreens(afterDir); +}); + +const runCompare = Effect.fn("mobileAudit.compare")(function* (input: { + readonly before: string; + readonly after: string; + readonly out: string; + readonly beforeLabel: string; + readonly afterLabel: string; + readonly all: boolean; + readonly failOnRegression: boolean; +}) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cwd = yield* HostProcess.WorkingDirectory; + const beforeDir = path.resolve(cwd, input.before); + const afterDir = path.resolve(cwd, input.after); + const outDir = path.resolve(cwd, input.out); + + yield* fs.makeDirectory(outDir, { recursive: true }); + const [beforeScreens, afterScreens] = yield* Effect.all([ + listCapturedScreens(beforeDir), + listCapturedScreens(afterDir), + ]); const afterSet = new Set(afterScreens.map((s) => `${s.platform}/${s.screen}`)); const pairs = beforeScreens.filter((s) => afterSet.has(`${s.platform}/${s.screen}`)); if (pairs.length === 0) { - throw new Error( - `No matching /.audit.json captures in both ${beforeDir} and ${afterDir}.`, - ); + return yield* new MobileAuditError({ + operation: "compare", + detail: `no matching /.audit.json captures in both ${beforeDir} and ${afterDir}`, + }); } const diffs: Array = []; for (const pair of pairs) { - const before = await readCaptureSet(beforeDir, pair.platform, pair.screen); - const after = await readCaptureSet(afterDir, pair.platform, pair.screen); + const [before, after] = yield* Effect.all([ + readCaptureSet(beforeDir, pair.platform, pair.screen), + readCaptureSet(afterDir, pair.platform, pair.screen), + ]); const diff = diffAuditCaptures({ before: before.capture, after: after.capture, @@ -239,26 +291,26 @@ async function runCompare(argv: ReadonlyArray) { }); const hasDelta = diff.fixed.length > 0 || diff.regressions.length > 0; + const [hasBeforePng, hasAfterPng] = yield* Effect.all([ + fs.exists(before.pngPath), + fs.exists(after.pngPath), + ]); let imagePath: string | undefined; - if ( - (hasDelta || renderAll) && - NodeFS.existsSync(before.pngPath) && - NodeFS.existsSync(after.pngPath) - ) { + if ((hasDelta || input.all) && hasBeforePng && hasAfterPng) { const { beforeBoxes, afterBoxes } = buildOverlayBoxes( diff, after.capture.pixelDensity || 1, before.capture.pixelDensity || 1, ); - const outPng = NodePath.join(outDir, `${pair.platform}-${pair.screen}.png`); - await renderBeforeAfterComparison({ + const outPng = path.join(outDir, `${pair.platform}-${pair.screen}.png`); + yield* renderBeforeAfterComparison({ beforePng: before.pngPath, beforeBoxes, - beforeTitle: `${beforeLabel} · ${diff.beforeCount} finding(s)`, + beforeTitle: `${input.beforeLabel} · ${diff.beforeCount} finding(s)`, beforeViewport: resolveViewport(before.capture, before.raw), afterPng: after.pngPath, afterBoxes, - afterTitle: `${afterLabel} · ${diff.afterCount} finding(s) (${diff.fixed.length} fixed, ${diff.regressions.length} new)`, + afterTitle: `${input.afterLabel} · ${diff.afterCount} finding(s) (${diff.fixed.length} fixed, ${diff.regressions.length} new)`, afterBannerBg: diff.regressions.length > 0 ? "#b91c1c" : "#15803d", afterViewport: resolveViewport(after.capture, after.raw), outPath: outPng, @@ -266,30 +318,36 @@ async function runCompare(argv: ReadonlyArray) { imagePath = outPng; } - diffs.push({ ...diff, ...(imagePath ? { imagePath } : {}) }); + diffs.push({ ...diff, ...(imagePath === undefined ? {} : { imagePath }) }); } const markdown = renderMarkdownReport(diffs); - await NodeFSP.writeFile( - NodePath.join(outDir, "diff.json"), - `${JSON.stringify(diffs, null, 2)}\n`, - ); - await NodeFSP.writeFile(NodePath.join(outDir, "report.md"), markdown); - NodeProcess.stdout.write(markdown); + const diffJson = yield* encodePrettyJson(diffs); + yield* fs.writeFileString(path.join(outDir, "diff.json"), `${diffJson}\n`); + yield* fs.writeFileString(path.join(outDir, "report.md"), markdown); + yield* Console.log(markdown.trimEnd()); const totalRegressions = diffs.reduce((n, d) => n + d.regressions.length, 0); - if (failOnRegression && totalRegressions > 0) { - NodeProcess.exit(1); + if (input.failOnRegression && totalRegressions > 0) { + return yield* new MobileAuditError({ + operation: "compare", + detail: `${totalRegressions} accessibility regression(s) detected`, + }); } -} - -async function runReport(argv: ReadonlyArray) { - const { flags } = parseFlags(argv); - const dir = NodePath.resolve(requiredString(flags, "dir")); - const outDir = NodePath.resolve(requiredString(flags, "out")); - await NodeFSP.mkdir(outDir, { recursive: true }); - - const screens = await listCapturedScreens(dir); +}); + +const runReport = Effect.fn("mobileAudit.report")(function* (input: { + readonly dir: string; + readonly out: string; +}) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cwd = yield* HostProcess.WorkingDirectory; + const dir = path.resolve(cwd, input.dir); + const outDir = path.resolve(cwd, input.out); + yield* fs.makeDirectory(outDir, { recursive: true }); + + const screens = yield* listCapturedScreens(dir); const lines: string[] = [ "### Mobile accessibility audit report (`agent-device audit`)", "", @@ -298,14 +356,14 @@ async function runReport(argv: ReadonlyArray) { ]; for (const entry of screens) { - const { capture, raw, pngPath } = await readCaptureSet(dir, entry.platform, entry.screen); + const { capture, raw, pngPath } = yield* readCaptureSet(dir, entry.platform, entry.screen); const viewport = resolveViewport(capture, raw); const findings = capture.findings.filter( (f) => !isPlatformNoise(f, capture.platform, viewport), ); lines.push(`| ${entry.platform} | \`${entry.screen}\` | ${findings.length} |`); - if (findings.length > 0 && NodeFS.existsSync(pngPath)) { + if (findings.length > 0 && (yield* fs.exists(pngPath))) { const unit = unitForPlatform(entry.platform); const boxes = findings .filter((f) => f.rect !== undefined) @@ -314,8 +372,8 @@ async function runReport(argv: ReadonlyArray) { tag: findingTag(f, capture.pixelDensity || 1, unit), color: "#ef4444", })); - const outPng = NodePath.join(outDir, `${entry.platform}-${entry.screen}.png`); - await renderSingleAnnotatedImage({ + const outPng = path.join(outDir, `${entry.platform}-${entry.screen}.png`); + yield* renderSingleAnnotatedImage({ pngPath, boxes, bannerText: `${entry.platform} · ${entry.screen} · ${findings.length} finding(s)`, @@ -327,17 +385,87 @@ async function runReport(argv: ReadonlyArray) { } const markdown = `${lines.join("\n")}\n`; - await NodeFSP.writeFile(NodePath.join(outDir, "report.md"), markdown); - NodeProcess.stdout.write(markdown); -} + yield* fs.writeFileString(path.join(outDir, "report.md"), markdown); + yield* Console.log(markdown.trimEnd()); +}); + +const captureCommand = Command.make( + "capture", + { + platform: Flag.Literals("platform", AuditPlatformSchema.literals).pipe( + Flag.withDescription("Target mobile platform (ios or android)."), + ), + screen: Flag.String("screen").pipe(Flag.withDescription("Screen identifier for output files.")), + out: Flag.String("out").pipe(Flag.withDescription("Directory to write captured artifacts.")), + agentDevice: Flag.String("agent-device").pipe( + Flag.withDescription( + "Optional path to an agent-device launcher; defaults to the workspace CLI.", + ), + Flag.optional, + ), + agentDeviceArgs: Argument.String("agent-device-arg").pipe( + Argument.withDescription("Extra arguments forwarded to agent-device (pass after `--`)."), + Argument.variadic(), + ), + }, + (input) => runCapture(input), +).pipe( + Command.withDescription( + "Capture a screenshot, native agent-device audit JSON, and raw accessibility snapshot.", + ), +); + +const compareCommand = Command.make( + "compare", + { + before: Flag.String("before").pipe(Flag.withDescription("Baseline capture directory.")), + after: Flag.String("after").pipe(Flag.withDescription("Candidate capture directory.")), + out: Flag.String("out").pipe( + Flag.withDescription("Output directory for diff.json, report.md, and comparison PNGs."), + ), + beforeLabel: Flag.String("before-label").pipe( + Flag.withDescription("Banner label for the before panel."), + Flag.withDefault("BEFORE (base)"), + ), + afterLabel: Flag.String("after-label").pipe( + Flag.withDescription("Banner label for the after panel."), + Flag.withDefault("AFTER (head)"), + ), + all: Flag.Boolean("all").pipe( + Flag.withDescription("Render comparison PNGs even for screens with no delta."), + Flag.withDefault(false), + ), + failOnRegression: Flag.Boolean("fail-on-regression").pipe( + Flag.withDescription("Exit non-zero if any screen introduces new findings."), + Flag.withDefault(false), + ), + }, + (input) => runCompare(input), +).pipe( + Command.withDescription( + "Diff two audit capture directories and render annotated side-by-side PNGs and Markdown.", + ), +); -const [subcommand, ...rest] = NodeProcess.argv.slice(2); -if (subcommand === "capture") { - await runCapture(rest); -} else if (subcommand === "compare") { - await runCompare(rest); -} else if (subcommand === "report") { - await runReport(rest); -} else { - usage(); +const reportCommand = Command.make( + "report", + { + dir: Flag.String("dir").pipe(Flag.withDescription("Capture directory to annotate.")), + out: Flag.String("out").pipe( + Flag.withDescription("Output directory for report.md and annotated PNGs."), + ), + }, + (input) => runReport(input), +).pipe(Command.withDescription("Annotate a single audit capture directory with hit-box overlays.")); + +const mobileAuditCommand = Command.make("mobile-audit").pipe( + Command.withDescription("Capture, diff, and visualize mobile accessibility audits."), + Command.withSubcommands([captureCommand, compareCommand, reportCommand]), +); + +if (import.meta.main) { + Command.run(mobileAuditCommand, { version: "0.0.0" }).pipe( + Effect.provide(NodeServices.layer), + NodeRuntime.runMain, + ); } diff --git a/scripts/mobile-audit/annotate.ts b/scripts/mobile-audit/annotate.ts index 359aed53006f7..e2194bbf32371 100644 --- a/scripts/mobile-audit/annotate.ts +++ b/scripts/mobile-audit/annotate.ts @@ -1,10 +1,22 @@ -// @effect-diagnostics nodeBuiltinImport:off - Host-side image rendering uses Node filesystem APIs directly. - -import * as NodeFSP from "node:fs/promises"; -import * as NodePath from "node:path"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; import sharp from "sharp"; -import type { OverlayBox } from "./diff.ts"; +import type { AuditViewport, OverlayBox } from "./diff.ts"; + +class MobileAuditRenderError extends Schema.TaggedError< + MobileAuditRenderError, + { readonly brand: unique symbol } +>()("MobileAuditRenderError", { + path: Schema.String, + cause: Schema.Defect(), +}) { + override get message(): string { + return `Failed to render annotated audit image for ${this.path}.`; + } +} function escapeXml(value: string): string { return value @@ -14,104 +26,117 @@ function escapeXml(value: string): string { .replaceAll('"', """); } -async function renderAnnotatedPanel(input: { +// Covered by the caller's renderSingle / renderComparison span. +const renderAnnotatedPanel = Effect.fnUntraced(function* (input: { readonly pngPath: string; readonly boxes: ReadonlyArray; readonly bannerText: string; readonly bannerBg: string; - readonly viewport?: { readonly width: number; readonly height: number } | undefined; + readonly viewport?: AuditViewport | undefined; readonly targetWidth: number; -}): Promise<{ readonly buffer: Buffer; readonly width: number; readonly height: number }> { - const meta = await sharp(input.pngPath).metadata(); - const srcWidth = meta.width ?? input.targetWidth; - const srcHeight = meta.height ?? input.targetWidth * 2; - const coordScaleX = input.viewport?.width ? srcWidth / input.viewport.width : 1; - const coordScaleY = input.viewport?.height ? srcHeight / input.viewport.height : 1; - - const scale = input.targetWidth / srcWidth; - const targetHeight = Math.round(srcHeight * scale); - const bannerHeight = 44; - - const rectsSvg = input.boxes - .map((box) => { - const rx = Math.round(box.x * coordScaleX * scale); - const ry = Math.round(box.y * coordScaleY * scale); - const rw = Math.max(8, Math.round(box.width * coordScaleX * scale)); - const rh = Math.max(8, Math.round(box.height * coordScaleY * scale)); - const stroke = box.color; - const fill = stroke === "#16a34a" ? "rgba(22,163,74,0.14)" : "rgba(239,68,68,0.16)"; - const tag = box.tag; - const tagW = Math.min( - input.targetWidth - 12, - Math.max(46, Math.round(tag.length * 7.2 + 14)), +}) { + const fs = yield* FileSystem.FileSystem; + const sourceBytes = yield* fs + .readFile(input.pngPath) + .pipe(Effect.mapError((cause) => new MobileAuditRenderError({ path: input.pngPath, cause }))); + + return yield* Effect.tryPromise({ + try: async () => { + const meta = await sharp(sourceBytes).metadata(); + const srcWidth = meta.width ?? input.targetWidth; + const srcHeight = meta.height ?? input.targetWidth * 2; + const coordScaleX = input.viewport?.width ? srcWidth / input.viewport.width : 1; + const coordScaleY = input.viewport?.height ? srcHeight / input.viewport.height : 1; + + const scale = input.targetWidth / srcWidth; + const targetHeight = Math.round(srcHeight * scale); + const bannerHeight = 44; + + const rectsSvg = input.boxes + .map((box) => { + const rx = Math.round(box.x * coordScaleX * scale); + const ry = Math.round(box.y * coordScaleY * scale); + const rw = Math.max(8, Math.round(box.width * coordScaleX * scale)); + const rh = Math.max(8, Math.round(box.height * coordScaleY * scale)); + const stroke = box.color; + const fill = stroke === "#16a34a" ? "rgba(22,163,74,0.14)" : "rgba(239,68,68,0.16)"; + const tag = box.tag; + const tagW = Math.min( + input.targetWidth - 12, + Math.max(46, Math.round(tag.length * 7.2 + 14)), + ); + const tagH = 20; + let tx = Math.min(input.targetWidth - tagW - 4, Math.max(4, rx)); + let ty = ry - tagH - 2; + if (ty < 4) ty = Math.min(targetHeight - tagH - 4, ry + rh + 2); + if (box.tagSide === "right") { + tx = Math.min(input.targetWidth - tagW - 4, rx + rw - tagW); + } else if (box.tagSide === "below") { + ty = Math.min(targetHeight - tagH - 4, ry + rh + 2); + } else if (box.tagSide === "inside-right") { + tx = Math.min(input.targetWidth - tagW - 4, rx + rw - tagW - 4); + ty = Math.max(4, ry + Math.round((rh - tagH) / 2)); + } + return [ + ``, + tag + ? `` + + `${escapeXml(tag)}` + : "", + ].join(""); + }) + .join("\n"); + + const overlaySvg = Buffer.from( + `${rectsSvg}`, + ); + + const annotatedImg = await sharp(sourceBytes) + .resize(input.targetWidth, targetHeight) + .composite([{ input: overlaySvg, top: 0, left: 0 }]) + .png() + .toBuffer(); + + const headerSvg = Buffer.from( + `` + + `` + + `${escapeXml(input.bannerText)}` + + ``, ); - const tagH = 20; - let tx = Math.min(input.targetWidth - tagW - 4, Math.max(4, rx)); - let ty = ry - tagH - 2; - if (ty < 4) ty = Math.min(targetHeight - tagH - 4, ry + rh + 2); - if (box.tagSide === "right") { - tx = Math.min(input.targetWidth - tagW - 4, rx + rw - tagW); - } else if (box.tagSide === "below") { - ty = Math.min(targetHeight - tagH - 4, ry + rh + 2); - } else if (box.tagSide === "inside-right") { - tx = Math.min(input.targetWidth - tagW - 4, rx + rw - tagW - 4); - ty = Math.max(4, ry + Math.round((rh - tagH) / 2)); - } - return [ - ``, - tag - ? `` + - `${escapeXml(tag)}` - : "", - ].join(""); - }) - .join("\n"); - - const overlaySvg = Buffer.from( - `${rectsSvg}`, - ); - - const annotatedImg = await sharp(input.pngPath) - .resize(input.targetWidth, targetHeight) - .composite([{ input: overlaySvg, top: 0, left: 0 }]) - .png() - .toBuffer(); - - const headerSvg = Buffer.from( - `` + - `` + - `${escapeXml(input.bannerText)}` + - ``, - ); - - const combined = await sharp({ - create: { - width: input.targetWidth, - height: targetHeight + bannerHeight, - channels: 4, - background: { r: 24, g: 24, b: 27, alpha: 1 }, + + const combined = await sharp({ + create: { + width: input.targetWidth, + height: targetHeight + bannerHeight, + channels: 4, + background: { r: 24, g: 24, b: 27, alpha: 1 }, + }, + }) + .composite([ + { input: headerSvg, top: 0, left: 0 }, + { input: annotatedImg, top: bannerHeight, left: 0 }, + ]) + .png() + .toBuffer(); + + return { buffer: combined, width: input.targetWidth, height: targetHeight + bannerHeight }; }, - }) - .composite([ - { input: headerSvg, top: 0, left: 0 }, - { input: annotatedImg, top: bannerHeight, left: 0 }, - ]) - .png() - .toBuffer(); - - return { buffer: combined, width: input.targetWidth, height: targetHeight + bannerHeight }; -} + catch: (cause) => new MobileAuditRenderError({ path: input.pngPath, cause }), + }); +}); -export async function renderSingleAnnotatedImage(input: { +export const renderSingleAnnotatedImage = Effect.fn("mobileAudit.renderSingle")(function* (input: { readonly pngPath: string; readonly boxes: ReadonlyArray; readonly bannerText: string; readonly bannerBg: string; - readonly viewport?: { readonly width: number; readonly height: number } | undefined; + readonly viewport?: AuditViewport | undefined; readonly outPath: string; readonly targetWidth?: number | undefined; -}): Promise { - const panel = await renderAnnotatedPanel({ +}) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const panel = yield* renderAnnotatedPanel({ pngPath: input.pngPath, boxes: input.boxes, bannerText: input.bannerText, @@ -119,63 +144,84 @@ export async function renderSingleAnnotatedImage(input: { viewport: input.viewport, targetWidth: input.targetWidth ?? 540, }); - await NodeFSP.mkdir(NodePath.dirname(input.outPath), { recursive: true }); - await NodeFSP.writeFile(input.outPath, panel.buffer); -} - -export async function renderBeforeAfterComparison(input: { - readonly beforePng: string; - readonly beforeBoxes: ReadonlyArray; - readonly beforeTitle: string; - readonly beforeViewport?: { readonly width: number; readonly height: number } | undefined; - readonly afterPng: string; - readonly afterBoxes: ReadonlyArray; - readonly afterTitle: string; - readonly afterBannerBg?: string | undefined; - readonly afterViewport?: { readonly width: number; readonly height: number } | undefined; - readonly outPath: string; - readonly panelWidth?: number | undefined; -}): Promise<{ readonly width: number; readonly height: number }> { - const targetWidth = input.panelWidth ?? 540; - const [left, right] = await Promise.all([ - renderAnnotatedPanel({ - pngPath: input.beforePng, - boxes: input.beforeBoxes, - bannerText: input.beforeTitle, - bannerBg: "#b91c1c", - viewport: input.beforeViewport, - targetWidth, - }), - renderAnnotatedPanel({ - pngPath: input.afterPng, - boxes: input.afterBoxes, - bannerText: input.afterTitle, - bannerBg: input.afterBannerBg ?? "#15803d", - viewport: input.afterViewport, - targetWidth, - }), - ]); - - const gap = 16; - const pad = 16; - const width = left.width + right.width + gap + pad * 2; - const height = Math.max(left.height, right.height) + pad * 2; - - await NodeFSP.mkdir(NodePath.dirname(input.outPath), { recursive: true }); - await sharp({ - create: { - width, - height, - channels: 4, - background: { r: 24, g: 24, b: 27, alpha: 1 }, - }, - }) - .composite([ - { input: left.buffer, top: pad, left: pad }, - { input: right.buffer, top: pad, left: pad + left.width + gap }, - ]) - .png() - .toFile(input.outPath); - - return { width, height }; -} + yield* fs + .makeDirectory(path.dirname(input.outPath), { recursive: true }) + .pipe(Effect.mapError((cause) => new MobileAuditRenderError({ path: input.outPath, cause }))); + yield* fs + .writeFile(input.outPath, panel.buffer) + .pipe(Effect.mapError((cause) => new MobileAuditRenderError({ path: input.outPath, cause }))); +}); + +export const renderBeforeAfterComparison = Effect.fn("mobileAudit.renderComparison")( + function* (input: { + readonly beforePng: string; + readonly beforeBoxes: ReadonlyArray; + readonly beforeTitle: string; + readonly beforeViewport?: AuditViewport | undefined; + readonly afterPng: string; + readonly afterBoxes: ReadonlyArray; + readonly afterTitle: string; + readonly afterBannerBg?: string | undefined; + readonly afterViewport?: AuditViewport | undefined; + readonly outPath: string; + readonly panelWidth?: number | undefined; + }) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const targetWidth = input.panelWidth ?? 540; + const [left, right] = yield* Effect.all( + [ + renderAnnotatedPanel({ + pngPath: input.beforePng, + boxes: input.beforeBoxes, + bannerText: input.beforeTitle, + bannerBg: "#b91c1c", + viewport: input.beforeViewport, + targetWidth, + }), + renderAnnotatedPanel({ + pngPath: input.afterPng, + boxes: input.afterBoxes, + bannerText: input.afterTitle, + bannerBg: input.afterBannerBg ?? "#15803d", + viewport: input.afterViewport, + targetWidth, + }), + ], + { concurrency: 2 }, + ); + + const gap = 16; + const pad = 16; + const width = left.width + right.width + gap + pad * 2; + const height = Math.max(left.height, right.height) + pad * 2; + + const outputBuffer = yield* Effect.tryPromise({ + try: () => + sharp({ + create: { + width, + height, + channels: 4, + background: { r: 24, g: 24, b: 27, alpha: 1 }, + }, + }) + .composite([ + { input: left.buffer, top: pad, left: pad }, + { input: right.buffer, top: pad, left: pad + left.width + gap }, + ]) + .png() + .toBuffer(), + catch: (cause) => new MobileAuditRenderError({ path: input.outPath, cause }), + }); + + yield* fs + .makeDirectory(path.dirname(input.outPath), { recursive: true }) + .pipe(Effect.mapError((cause) => new MobileAuditRenderError({ path: input.outPath, cause }))); + yield* fs + .writeFile(input.outPath, outputBuffer) + .pipe(Effect.mapError((cause) => new MobileAuditRenderError({ path: input.outPath, cause }))); + + return { width, height }; + }, +); diff --git a/scripts/mobile-audit/diff.test.ts b/scripts/mobile-audit/diff.test.ts index 8acd32a05c1f0..9b1e7e8da311b 100644 --- a/scripts/mobile-audit/diff.test.ts +++ b/scripts/mobile-audit/diff.test.ts @@ -1,10 +1,9 @@ -// @effect-diagnostics nodeBuiltinImport:off - Image rendering test writes temporary PNGs directly. - -import * as NodeFSP from "node:fs/promises"; -import * as NodeOS from "node:os"; -import * as NodePath from "node:path"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; import sharp from "sharp"; -import { describe, expect, it } from "vite-plus/test"; import { renderBeforeAfterComparison } from "./annotate.ts"; import { @@ -156,35 +155,31 @@ describe("mobile-audit diff", () => { expect(md).toContain("![android connections-new before vs after](android-connections-new.png)"); }); - it("composites a side-by-side annotated PNG for Retina 3x iOS screenshots", async () => { - const tmp = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "mobile-audit-test-")); - try { - const beforePng = NodePath.join(tmp, "before.png"); - const afterPng = NodePath.join(tmp, "after.png"); - const outPng = NodePath.join(tmp, "comparison.png"); - - await sharp({ - create: { - width: 1206, - height: 2622, - channels: 4, - background: { r: 255, g: 255, b: 255, alpha: 1 }, - }, - }) - .png() - .toFile(beforePng); - await sharp({ - create: { - width: 1206, - height: 2622, - channels: 4, - background: { r: 255, g: 255, b: 255, alpha: 1 }, - }, - }) - .png() - .toFile(afterPng); - - const result = await renderBeforeAfterComparison({ + it.effect("composites a side-by-side annotated PNG for Retina 3x iOS screenshots", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const tmp = yield* fs.makeTempDirectoryScoped({ prefix: "mobile-audit-test-" }); + const beforePng = path.join(tmp, "before.png"); + const afterPng = path.join(tmp, "after.png"); + const outPng = path.join(tmp, "comparison.png"); + + const blankPng = yield* Effect.promise(() => + sharp({ + create: { + width: 1206, + height: 2622, + channels: 4, + background: { r: 255, g: 255, b: 255, alpha: 1 }, + }, + }) + .png() + .toBuffer(), + ); + yield* fs.writeFile(beforePng, blankPng); + yield* fs.writeFile(afterPng, blankPng); + + const result = yield* renderBeforeAfterComparison({ beforePng, beforeBoxes: [{ x: 111, y: 431, width: 260, height: 23, tag: "23.3pt", color: "#ef4444" }], beforeTitle: "BEFORE (main)", @@ -196,13 +191,12 @@ describe("mobile-audit diff", () => { outPath: outPng, }); - const outMeta = await sharp(outPng).metadata(); + const outBytes = yield* fs.readFile(outPng); + const outMeta = yield* Effect.promise(() => sharp(outBytes).metadata()); expect(outMeta.format).toBe("png"); expect(outMeta.width).toBe(result.width); expect(outMeta.height).toBe(result.height); expect(outMeta.width).toBe(1128); - } finally { - await NodeFSP.rm(tmp, { recursive: true, force: true }); - } - }); + }).pipe(Effect.provide(NodeServices.layer)), + ); }); diff --git a/scripts/mobile-audit/diff.ts b/scripts/mobile-audit/diff.ts index c64b0138d0801..9acbcedd6b112 100644 --- a/scripts/mobile-audit/diff.ts +++ b/scripts/mobile-audit/diff.ts @@ -1,68 +1,104 @@ -export type AuditPlatform = "ios" | "android"; - -export interface AuditRect { - readonly x: number; - readonly y: number; - readonly width: number; - readonly height: number; -} - -export interface SmallTargetDetail { - readonly unit: string; - readonly width: number; - readonly height: number; - readonly recommendedSize: number; -} - -export interface AmbiguousNameDetail { - readonly name: string; - readonly count: number; -} - -export interface AuditFinding { - readonly ref: string; - readonly kind: "small-target" | "missing-name" | "ambiguous-name" | "covered-control" | string; - readonly severity?: string; - readonly role: string; - readonly label?: string; - readonly identifier?: string; - readonly rect?: AuditRect; - readonly detail?: SmallTargetDetail | AmbiguousNameDetail | Record; -} - -export interface RawSnapshotNode { - readonly index: number; - readonly parentIndex?: number; - readonly ref?: string; - readonly type?: string; - readonly role?: string; - readonly label?: string; - readonly identifier?: string; - readonly contentDescription?: string; - readonly text?: string; - readonly rect?: AuditRect; - readonly enabled?: boolean; - readonly hittable?: boolean; - readonly visibleToUser?: boolean; - readonly keyboardOwned?: boolean; - readonly systemBar?: string; -} - -export interface RawSnapshotData { - readonly nodes: ReadonlyArray; - readonly viewport?: { readonly width: number; readonly height: number }; - readonly androidSnapshot?: { readonly pixelDensity?: number; readonly backend?: string }; -} - -export interface AuditCapture { - readonly platform: AuditPlatform; - readonly screen: string; - readonly viewport?: { readonly width: number; readonly height: number } | undefined; - readonly pixelDensity: number; - readonly findings: ReadonlyArray; - readonly guidance?: Readonly> | undefined; - readonly limitations?: ReadonlyArray | undefined; -} +import * as Schema from "effect/Schema"; + +export const AuditPlatformSchema = Schema.Literals(["ios", "android"]); +export type AuditPlatform = typeof AuditPlatformSchema.Type; + +const AuditRectSchema = Schema.Struct({ + x: Schema.Number, + y: Schema.Number, + width: Schema.Number, + height: Schema.Number, +}); +export type AuditRect = typeof AuditRectSchema.Type; + +const ViewportSchema = Schema.Struct({ + width: Schema.Number, + height: Schema.Number, +}); +export type AuditViewport = typeof ViewportSchema.Type; + +const SmallTargetDetailSchema = Schema.Struct({ + unit: Schema.String, + width: Schema.Number, + height: Schema.Number, + recommendedSize: Schema.Number, +}); + +const AmbiguousNameDetailSchema = Schema.Struct({ + name: Schema.String, + count: Schema.Number, +}); + +const AuditFindingSchema = Schema.Struct({ + ref: Schema.String, + kind: Schema.String, + severity: Schema.optional(Schema.String), + role: Schema.String, + label: Schema.optional(Schema.String), + identifier: Schema.optional(Schema.String), + rect: Schema.optional(AuditRectSchema), + detail: Schema.optional(Schema.Unknown), +}); +export type AuditFinding = typeof AuditFindingSchema.Type; + +const RawSnapshotNodeSchema = Schema.Struct({ + index: Schema.Number, + parentIndex: Schema.optional(Schema.Number), + ref: Schema.optional(Schema.String), + type: Schema.optional(Schema.String), + role: Schema.optional(Schema.String), + label: Schema.optional(Schema.String), + identifier: Schema.optional(Schema.String), + contentDescription: Schema.optional(Schema.String), + text: Schema.optional(Schema.String), + rect: Schema.optional(AuditRectSchema), + enabled: Schema.optional(Schema.Boolean), + hittable: Schema.optional(Schema.Boolean), + visibleToUser: Schema.optional(Schema.Boolean), + keyboardOwned: Schema.optional(Schema.Boolean), + systemBar: Schema.optional(Schema.String), +}); +export type RawSnapshotNode = typeof RawSnapshotNodeSchema.Type; + +export const RawSnapshotDataSchema = Schema.Struct({ + nodes: Schema.Array(RawSnapshotNodeSchema), + viewport: Schema.optional(ViewportSchema), + androidSnapshot: Schema.optional( + Schema.Struct({ + pixelDensity: Schema.optional(Schema.Number), + backend: Schema.optional(Schema.String), + }), + ), +}); +export type RawSnapshotData = typeof RawSnapshotDataSchema.Type; + +export const AuditPayloadSchema = Schema.Struct({ + findings: Schema.optional(Schema.Array(AuditFindingSchema)), + guidance: Schema.optional(Schema.Record(Schema.String, Schema.String)), + limitations: Schema.optional(Schema.Array(Schema.String)), +}); + +export const AuditCaptureSchema = Schema.Struct({ + platform: AuditPlatformSchema, + screen: Schema.String, + viewport: Schema.optional(ViewportSchema), + pixelDensity: Schema.Number, + findings: Schema.Array(AuditFindingSchema), + guidance: Schema.optional(Schema.Record(Schema.String, Schema.String)), + limitations: Schema.optional(Schema.Array(Schema.String)), +}); +export type AuditCapture = typeof AuditCaptureSchema.Type; + +export const AgentDeviceEnvelopeSchema = Schema.Struct({ + success: Schema.optional(Schema.Boolean), + data: Schema.optional(Schema.Unknown), + error: Schema.optional( + Schema.Struct({ + message: Schema.optional(Schema.String), + hint: Schema.optional(Schema.String), + }), + ), +}); export interface FixedFinding { readonly before: AuditFinding; @@ -94,6 +130,9 @@ export interface OverlayBox { const VIEWPORT_EDGE_CLIP_TOLERANCE = 10; +const isSmallTargetDetail = Schema.is(SmallTargetDetailSchema); +const isAmbiguousNameDetail = Schema.is(AmbiguousNameDetailSchema); + export function unitForPlatform(platform: AuditPlatform): "pt" | "dp" { return platform === "ios" ? "pt" : "dp"; } @@ -101,7 +140,7 @@ export function unitForPlatform(platform: AuditPlatform): "pt" | "dp" { export function resolveViewport( capture: Pick, raw?: RawSnapshotData, -): { readonly width: number; readonly height: number } | undefined { +): AuditViewport | undefined { if (capture.viewport?.width && capture.viewport?.height) return capture.viewport; if (raw?.viewport?.width && raw?.viewport?.height) return raw.viewport; const rootRect = raw?.nodes[0]?.rect; @@ -116,24 +155,6 @@ export function formatHeight(rect: AuditRect, density: number, unit: "pt" | "dp" return `${h}${unit}`; } -function isSmallTargetDetail(detail: AuditFinding["detail"]): detail is SmallTargetDetail { - return ( - typeof detail === "object" && - detail !== null && - typeof (detail as SmallTargetDetail).width === "number" && - typeof (detail as SmallTargetDetail).height === "number" - ); -} - -function isAmbiguousNameDetail(detail: AuditFinding["detail"]): detail is AmbiguousNameDetail { - return ( - typeof detail === "object" && - detail !== null && - typeof (detail as AmbiguousNameDetail).name === "string" && - typeof (detail as AmbiguousNameDetail).count === "number" - ); -} - /** * Filters known platform-chrome and viewport-clipping artifacts so regressions stay high-signal: * - iOS 26/27 native UISwitch accessibility frames report 63×28pt. @@ -143,7 +164,7 @@ function isAmbiguousNameDetail(detail: AuditFinding["detail"]): detail is Ambigu export function isPlatformNoise( finding: AuditFinding, platform: AuditPlatform, - viewport?: { readonly width: number; readonly height: number }, + viewport?: AuditViewport, ): boolean { if (platform === "ios") { if (