spana-test 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/agent/index.d.ts +1 -1
  2. package/dist/agent/index.js +7 -7
  3. package/dist/{android-PAPJJWVN.js → android-GFW6OXPQ.js} +16 -2
  4. package/dist/{chunk-GZK22EIE.js → chunk-EWIR2GVV.js} +54 -1
  5. package/dist/chunk-EWIR2GVV.js.map +1 -0
  6. package/dist/{chunk-7IA2XG3G.js → chunk-KYPLYRKW.js} +9 -9
  7. package/dist/{chunk-YXQEPVEW.js → chunk-LC3QJIHY.js} +71 -3
  8. package/dist/chunk-LC3QJIHY.js.map +1 -0
  9. package/dist/{chunk-KAKHFSVA.js → chunk-MCT4DYDK.js} +145 -54
  10. package/dist/chunk-MCT4DYDK.js.map +1 -0
  11. package/dist/{chunk-DSTUWLSW.js → chunk-PZYZ4O6D.js} +3 -3
  12. package/dist/{chunk-4OHBO7LD.js → chunk-S5JNNDXS.js} +44 -1
  13. package/dist/{chunk-4OHBO7LD.js.map → chunk-S5JNNDXS.js.map} +1 -1
  14. package/dist/{chunk-24KSKK2I.js → chunk-YAV6KBSW.js} +31 -2
  15. package/dist/chunk-YAV6KBSW.js.map +1 -0
  16. package/dist/{chunk-QPIE3IMG.js → chunk-YGHDMA6D.js} +2 -2
  17. package/dist/cli.js +5 -5
  18. package/dist/{discover-NPNF6SWQ.js → discover-CAQY6EG6.js} +4 -4
  19. package/dist/{doctor-command-C3SEQGRQ.js → doctor-command-YGQPO7GH.js} +3 -3
  20. package/dist/{flow-CW0_j7tw.d.ts → flow-thjUxXXx.d.ts} +24 -2
  21. package/dist/gherkin/steps.d.ts +2 -2
  22. package/dist/index.d.ts +3 -3
  23. package/dist/index.js +2 -2
  24. package/dist/index.js.map +1 -1
  25. package/dist/{installer-W5DITECS.js → installer-PVBSX7UC.js} +2 -2
  26. package/dist/{ios-3GRECXAP.js → ios-JPK43TFZ.js} +10 -2
  27. package/dist/{server-MZERO364.js → server-PZBRGU7P.js} +8 -8
  28. package/dist/session-2MZVGYAC.js +17 -0
  29. package/dist/{storybook-BK2JE4ld.d.ts → storybook-pBOPe_1D.d.ts} +6 -2
  30. package/dist/{studio-command-5BUER2RH.js → studio-command-YDWQOMRX.js} +2 -2
  31. package/dist/{test-command-2PXTHASW.js → test-command-B2VLWGDK.js} +86 -15
  32. package/dist/test-command-B2VLWGDK.js.map +1 -0
  33. package/package.json +1 -1
  34. package/dist/chunk-24KSKK2I.js.map +0 -1
  35. package/dist/chunk-GZK22EIE.js.map +0 -1
  36. package/dist/chunk-KAKHFSVA.js.map +0 -1
  37. package/dist/chunk-YXQEPVEW.js.map +0 -1
  38. package/dist/session-3UZ5WAAD.js +0 -17
  39. package/dist/test-command-2PXTHASW.js.map +0 -1
  40. /package/dist/{android-PAPJJWVN.js.map → android-GFW6OXPQ.js.map} +0 -0
  41. /package/dist/{chunk-7IA2XG3G.js.map → chunk-KYPLYRKW.js.map} +0 -0
  42. /package/dist/{chunk-DSTUWLSW.js.map → chunk-PZYZ4O6D.js.map} +0 -0
  43. /package/dist/{chunk-QPIE3IMG.js.map → chunk-YGHDMA6D.js.map} +0 -0
  44. /package/dist/{discover-NPNF6SWQ.js.map → discover-CAQY6EG6.js.map} +0 -0
  45. /package/dist/{doctor-command-C3SEQGRQ.js.map → doctor-command-YGQPO7GH.js.map} +0 -0
  46. /package/dist/{installer-W5DITECS.js.map → installer-PVBSX7UC.js.map} +0 -0
  47. /package/dist/{ios-3GRECXAP.js.map → ios-JPK43TFZ.js.map} +0 -0
  48. /package/dist/{server-MZERO364.js.map → server-PZBRGU7P.js.map} +0 -0
  49. /package/dist/{session-3UZ5WAAD.js.map → session-2MZVGYAC.js.map} +0 -0
  50. /package/dist/{studio-command-5BUER2RH.js.map → studio-command-YDWQOMRX.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/device/ios.ts"],"sourcesContent":["import { execFileSync, execSync } from \"node:child_process\";\nimport { readFileSync, unlinkSync } from \"node:fs\";\nimport { allocatePort, releasePort } from \"../core/port-allocator.js\";\n\nexport interface IOSSimulator {\n udid: string;\n name: string;\n state: \"Booted\" | \"Shutdown\" | string;\n runtime: string; // e.g. \"iOS 17.5\"\n isAvailable: boolean;\n}\n\nexport interface IOSDevice {\n udid: string;\n name: string;\n type: \"simulator\" | \"device\";\n state: string;\n runtime?: string;\n}\n\n/** List iOS simulators */\nexport function listIOSSimulators(): IOSSimulator[] {\n try {\n const output = execSync(\"xcrun simctl list devices -j\", { encoding: \"utf-8\" });\n const data = JSON.parse(output);\n const simulators: IOSSimulator[] = [];\n\n for (const [runtime, devices] of Object.entries(data.devices ?? {})) {\n // runtime looks like \"com.apple.CoreSimulator.SimRuntime.iOS-17-5\"\n const runtimeName = runtime\n .replace(\"com.apple.CoreSimulator.SimRuntime.\", \"\")\n .replaceAll(\"-\", \".\");\n\n for (const device of devices as any[]) {\n simulators.push({\n udid: device.udid,\n name: device.name,\n state: device.state,\n runtime: runtimeName,\n isAvailable: device.isAvailable ?? true,\n });\n }\n }\n\n return simulators;\n } catch {\n return [];\n }\n}\n\n/** List booted iOS simulators */\nexport function listBootedSimulators(): IOSSimulator[] {\n return listIOSSimulators().filter((s) => s.state === \"Booted\" && s.isAvailable);\n}\n\n/** Get first booted simulator, or first available if none booted */\nexport function firstIOSSimulator(): IOSSimulator | null {\n const booted = listBootedSimulators();\n if (booted.length > 0) return booted[0]!;\n\n const available = listIOSSimulators().filter((s) => s.isAvailable);\n return available[0] ?? null;\n}\n\n/** Check whether an app is installed on a simulator */\nexport function hasAppInstalledOnSimulator(udid: string, bundleId: string): boolean {\n if (!bundleId) return false;\n\n try {\n execSync(`xcrun simctl get_app_container ${udid} ${bundleId} app`, { stdio: \"ignore\" });\n return true;\n } catch {\n return false;\n }\n}\n\n/** Prefer a simulator that already has the requested app installed */\nexport function firstIOSSimulatorWithApp(bundleId: string): IOSSimulator | null {\n const bootedWithApp = listBootedSimulators().find((sim) =>\n hasAppInstalledOnSimulator(sim.udid, bundleId),\n );\n if (bootedWithApp) return bootedWithApp;\n\n const availableWithApp = listIOSSimulators()\n .filter((sim) => sim.isAvailable)\n .find((sim) => hasAppInstalledOnSimulator(sim.udid, bundleId));\n if (availableWithApp) return availableWithApp;\n\n return firstIOSSimulator();\n}\n\n/**\n * Ensure an iOS simulator is available and booted.\n * If none booted, boots the first available simulator (preferring one with the app installed).\n * Returns the simulator or null if none available.\n */\nexport function ensureIOSSimulator(bundleId?: string): IOSSimulator | null {\n const sim = bundleId ? firstIOSSimulatorWithApp(bundleId) : firstIOSSimulator();\n if (!sim) return null;\n\n if (sim.state !== \"Booted\") {\n console.log(`Booting iOS simulator \"${sim.name}\"...`);\n bootSimulator(sim.udid);\n }\n\n return sim;\n}\n\n/** Boot a simulator by UDID */\nexport function bootSimulator(udid: string): void {\n try {\n execSync(`xcrun simctl boot ${udid}`, { stdio: \"ignore\" });\n } catch {\n // May already be booted — ignore\n }\n}\n\n/** Install app on simulator */\nexport function installOnSimulator(udid: string, appPath: string): void {\n execSync(`xcrun simctl install ${udid} ${appPath}`);\n}\n\n/** Launch app on simulator */\nexport function launchOnSimulator(udid: string, bundleId: string): void {\n execSync(`xcrun simctl launch ${udid} ${bundleId}`);\n}\n\n/** Launch app on simulator with a deep link URL (bypasses system confirmation dialog) */\nexport function launchWithUrlOnSimulator(udid: string, bundleId: string, url: string): void {\n execFileSync(\"xcrun\", [\"simctl\", \"launch\", udid, bundleId, \"--open-url\", url]);\n}\n\n/** List URL schemes registered by the installed app on simulator */\nexport function installedUrlSchemesOnSimulator(udid: string, bundleId: string): string[] {\n if (!bundleId) return [];\n\n try {\n const appPath = execSync(`xcrun simctl get_app_container ${udid} ${bundleId} app`, {\n encoding: \"utf-8\",\n }).trim();\n\n const raw = execFileSync(\n \"plutil\",\n [\"-extract\", \"CFBundleURLTypes\", \"json\", \"-o\", \"-\", `${appPath}/Info.plist`],\n {\n encoding: \"utf-8\",\n },\n );\n\n const urlTypes = JSON.parse(raw) as Array<{\n CFBundleURLSchemes?: string[];\n }>;\n\n return urlTypes.flatMap((entry) => entry.CFBundleURLSchemes ?? []);\n } catch {\n return [];\n }\n}\n\n/** Open a URL or deep link on simulator */\nexport function openUrlOnSimulator(udid: string, url: string): void {\n execFileSync(\"xcrun\", [\"simctl\", \"openurl\", udid, url], { stdio: \"ignore\" });\n}\n\n/** Terminate app on simulator */\nexport function terminateOnSimulator(udid: string, bundleId: string): void {\n try {\n execSync(`xcrun simctl terminate ${udid} ${bundleId}`, { stdio: \"ignore\" });\n } catch {\n // May not be running\n }\n}\n\n// ---------------------------------------------------------------------------\n// Physical device support\n// ---------------------------------------------------------------------------\n\nexport interface IOSPhysicalDevice {\n udid: string;\n name: string;\n connectionType: \"USB\" | \"Wi-Fi\" | string;\n}\n\n/**\n * List connected physical iOS devices using xcrun devicectl (Xcode 15+).\n * Falls back to system_profiler if devicectl is unavailable.\n */\nexport function listIOSPhysicalDevices(): IOSPhysicalDevice[] {\n // Try xcrun devicectl first (Xcode 15+)\n try {\n const tmpFile = `/tmp/spana-devicectl-${Date.now()}.json`;\n execSync(`xcrun devicectl list devices --json-output ${tmpFile} 2>/dev/null`, {\n timeout: 10_000,\n });\n const output = readFileSync(tmpFile, \"utf-8\");\n try {\n unlinkSync(tmpFile);\n } catch {\n /* cleanup */\n }\n\n const data = JSON.parse(output);\n const devices: IOSPhysicalDevice[] = [];\n\n for (const device of data?.result?.devices ?? []) {\n const deviceType = device.hardwareProperties?.deviceType ?? \"\";\n const transport = device.connectionProperties?.transportType;\n const state = device.connectionProperties?.tunnelState;\n\n // Only treat iPhones/iPads with an active tunnel as available physical\n // devices. devicectl can report remembered Wi-Fi devices with a transport\n // but tunnelState \"disconnected\", which should not trigger a device-first\n // test run attempt.\n if (\n (deviceType === \"iPhone\" || deviceType === \"iPad\") &&\n transport &&\n state === \"connected\"\n ) {\n devices.push({\n udid: device.hardwareProperties?.udid ?? device.identifier,\n name: device.deviceProperties?.name ?? \"Unknown\",\n connectionType: transport === \"wired\" ? \"USB\" : (transport ?? \"unknown\"),\n });\n }\n }\n\n return devices;\n } catch {\n // Fall back to system_profiler for older Xcode\n }\n\n try {\n const output = execSync(\"system_profiler SPUSBDataType -json 2>/dev/null\", {\n encoding: \"utf-8\",\n timeout: 10_000,\n });\n const data = JSON.parse(output);\n const devices: IOSPhysicalDevice[] = [];\n\n function walkUSB(items: any[]): void {\n for (const item of items) {\n // iOS devices have serial_num and contain \"iPhone\" or \"iPad\" in name\n if (item.serial_num && /iPhone|iPad|iPod/i.test(item._name ?? \"\")) {\n devices.push({\n udid: item.serial_num.replaceAll(\"-\", \"\"),\n name: item._name ?? \"iOS Device\",\n connectionType: \"USB\",\n });\n }\n if (item._items) walkUSB(item._items);\n }\n }\n\n walkUSB(data.SPUSBDataType ?? []);\n return devices;\n } catch {\n return [];\n }\n}\n\n/** Get first connected physical iOS device */\nexport function firstIOSPhysicalDevice(): IOSPhysicalDevice | null {\n const devices = listIOSPhysicalDevices();\n return devices[0] ?? null;\n}\n\n/**\n * Start iproxy to tunnel a port from localhost to a physical device via USB.\n * Requires libimobiledevice (`brew install libimobiledevice`).\n *\n * @returns A cleanup function to kill the iproxy process.\n */\nexport function startIproxy(\n udid: string,\n localPort: number,\n devicePort: number,\n): { host: string; port: number; cleanup: () => void } {\n // Check iproxy is available\n try {\n execSync(\"which iproxy\", { stdio: \"ignore\" });\n } catch {\n throw new Error(\"iproxy not found. Install with: brew install libimobiledevice\");\n }\n\n const { spawn } = require(\"node:child_process\") as typeof import(\"node:child_process\");\n const proc = spawn(\"iproxy\", [`${localPort}:${devicePort}`, \"-u\", udid], {\n stdio: \"ignore\",\n detached: true,\n });\n proc.unref();\n\n // Give iproxy a moment to bind\n const waitUntil = Date.now() + 1500;\n while (Date.now() < waitUntil) {\n /* busy wait */\n }\n\n return {\n host: \"localhost\",\n port: localPort,\n cleanup: () => {\n try {\n proc.kill();\n } catch {\n // already dead\n }\n },\n };\n}\n\n/**\n * Connect to a physical iOS device for testing.\n * Sets up iproxy tunnel and returns connection info for WDA.\n *\n * WDA must be pre-installed and running on the device.\n * Install with: xcodebuild -project WebDriverAgent.xcodeproj -scheme WebDriverAgentRunner\n * -destination \"id=<UDID>\" test\n */\nexport function connectPhysicalDevice(\n udid: string,\n wdaPort = 8100,\n): { host: string; port: number; cleanup: () => void } {\n const localPort = allocatePort(8100);\n\n try {\n const tunnel = startIproxy(udid, localPort, wdaPort);\n return {\n ...tunnel,\n cleanup: () => {\n tunnel.cleanup();\n releasePort(localPort);\n },\n };\n } catch (error) {\n releasePort(localPort);\n throw error;\n }\n}\n\n/**\n * Install an app on a physical iOS device using xcrun devicectl (Xcode 15+).\n * Accepts .app bundles or .ipa files.\n */\nexport function installOnPhysicalDevice(udid: string, appPath: string): void {\n try {\n execSync(`xcrun devicectl device install app --device ${udid} ${appPath}`, {\n stdio: \"inherit\",\n timeout: 120_000,\n });\n } catch {\n throw new Error(\n `Failed to install app on device ${udid}. Ensure the app is signed for this device.`,\n );\n }\n}\n\n/**\n * Check if an app is installed on a physical device.\n */\nexport function hasAppOnPhysicalDevice(udid: string, bundleId: string): boolean {\n if (!bundleId) return false;\n try {\n const tmpFile = `/tmp/spana-applist-${Date.now()}.json`;\n execSync(\n `xcrun devicectl device info apps --device ${udid} --json-output ${tmpFile} 2>/dev/null`,\n { timeout: 15_000 },\n );\n const output = readFileSync(tmpFile, \"utf-8\");\n try {\n unlinkSync(tmpFile);\n } catch {\n /* cleanup */\n }\n return output.includes(bundleId);\n } catch {\n return false;\n }\n}\n\n/** Reset simulator keychain (removes all stored passwords and certificates) */\nexport function resetSimulatorKeychain(udid: string): void {\n execSync(`xcrun simctl keychain ${udid} reset`, { stdio: \"ignore\" });\n}\n\n/**\n * Ensure an app is installed on the target device (simulator or physical).\n * Installs from appPath if not already present.\n */\nexport function ensureAppInstalled(opts: {\n udid: string;\n bundleId: string;\n appPath: string;\n isPhysicalDevice: boolean;\n}): void {\n const { udid, bundleId, appPath, isPhysicalDevice } = opts;\n\n if (isPhysicalDevice) {\n if (!hasAppOnPhysicalDevice(udid, bundleId)) {\n console.log(`Installing ${bundleId} on physical device...`);\n installOnPhysicalDevice(udid, appPath);\n }\n } else {\n if (!hasAppInstalledOnSimulator(udid, bundleId)) {\n console.log(`Installing ${bundleId} on simulator...`);\n installOnSimulator(udid, appPath);\n }\n }\n}\n"],"mappings":";;;;;;;;;AAAA,SAAS,cAAc,gBAAgB;AACvC,SAAS,cAAc,kBAAkB;AAoBlC,SAAS,oBAAoC;AAClD,MAAI;AACF,UAAM,SAAS,SAAS,gCAAgC,EAAE,UAAU,QAAQ,CAAC;AAC7E,UAAM,OAAO,KAAK,MAAM,MAAM;AAC9B,UAAM,aAA6B,CAAC;AAEpC,eAAW,CAAC,SAAS,OAAO,KAAK,OAAO,QAAQ,KAAK,WAAW,CAAC,CAAC,GAAG;AAEnE,YAAM,cAAc,QACjB,QAAQ,uCAAuC,EAAE,EACjD,WAAW,KAAK,GAAG;AAEtB,iBAAW,UAAU,SAAkB;AACrC,mBAAW,KAAK;AAAA,UACd,MAAM,OAAO;AAAA,UACb,MAAM,OAAO;AAAA,UACb,OAAO,OAAO;AAAA,UACd,SAAS;AAAA,UACT,aAAa,OAAO,eAAe;AAAA,QACrC,CAAC;AAAA,MACH;AAAA,IACF;AAEA,WAAO;AAAA,EACT,QAAQ;AACN,WAAO,CAAC;AAAA,EACV;AACF;AAGO,SAAS,uBAAuC;AACrD,SAAO,kBAAkB,EAAE,OAAO,CAAC,MAAM,EAAE,UAAU,YAAY,EAAE,WAAW;AAChF;AAGO,SAAS,oBAAyC;AACvD,QAAM,SAAS,qBAAqB;AACpC,MAAI,OAAO,SAAS,EAAG,QAAO,OAAO,CAAC;AAEtC,QAAM,YAAY,kBAAkB,EAAE,OAAO,CAAC,MAAM,EAAE,WAAW;AACjE,SAAO,UAAU,CAAC,KAAK;AACzB;AAGO,SAAS,2BAA2B,MAAc,UAA2B;A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B,IAAI,UAAU,EAAE,OAAO,SAAS,CAAC;AACrE;AAMO,SAAS,mBAAmB,MAK1B;AACP,QAAM,EAAE,MAAM,UAAU,SAAS,iBAAiB,IAAI;AAEtD,MAAI,kBAAkB;AACpB,QAAI,CAAC,uBAAuB,MAAM,QAAQ,GAAG;AAC3C,cAAQ,IAAI,cAAc,QAAQ,wBAAwB;AAC1D,8BAAwB,MAAM,OAAO;AAAA,IACvC;AAAA,EACF,OAAO;AACL,QAAI,CAAC,2BAA2B,MAAM,QAAQ,GAAG;AAC/C,cAAQ,IAAI,cAAc,QAAQ,kBAAkB;AACpD,yBAAmB,MAAM,OAAO;AAAA,IAClC;AAAA,EACF;AACF;","names":["walkUSB"]}
1
+ {"version":3,"sources":["../src/device/ios.ts"],"sourcesContent":["import { execFileSync, execSync } from \"node:child_process\";\nimport { readFileSync, unlinkSync } from \"node:fs\";\nimport { allocatePort, releasePort } from \"../core/port-allocator.js\";\n\nexport interface IOSSimulator {\n udid: string;\n name: string;\n state: \"Booted\" | \"Shutdown\" | string;\n runtime: string; // e.g. \"iOS 17.5\"\n isAvailable: boolean;\n}\n\nexport interface IOSDevice {\n udid: string;\n name: string;\n type: \"simulator\" | \"device\";\n state: string;\n runtime?: string;\n}\n\n/** List iOS simulators */\nexport function listIOSSimulators(): IOSSimulator[] {\n try {\n const output = execSync(\"xcrun simctl list devices -j\", { encoding: \"utf-8\" });\n const data = JSON.parse(output);\n const simulators: IOSSimulator[] = [];\n\n for (const [runtime, devices] of Object.entries(data.devices ?? {})) {\n // runtime looks like \"com.apple.CoreSimulator.SimRuntime.iOS-17-5\"\n const runtimeName = runtime\n .replace(\"com.apple.CoreSimulator.SimRuntime.\", \"\")\n .replaceAll(\"-\", \".\");\n\n for (const device of devices as any[]) {\n simulators.push({\n udid: device.udid,\n name: device.name,\n state: device.state,\n runtime: runtimeName,\n isAvailable: device.isAvailable ?? true,\n });\n }\n }\n\n return simulators;\n } catch {\n return [];\n }\n}\n\n/** List booted iOS simulators */\nexport function listBootedSimulators(): IOSSimulator[] {\n return listIOSSimulators().filter((s) => s.state === \"Booted\" && s.isAvailable);\n}\n\n/** Get first booted simulator, or first available if none booted */\nexport function firstIOSSimulator(): IOSSimulator | null {\n const booted = listBootedSimulators();\n if (booted.length > 0) return booted[0]!;\n\n const available = listIOSSimulators().filter((s) => s.isAvailable);\n return available[0] ?? null;\n}\n\n/** Check whether an app is installed on a simulator */\nexport function hasAppInstalledOnSimulator(udid: string, bundleId: string): boolean {\n if (!bundleId) return false;\n\n try {\n execSync(`xcrun simctl get_app_container ${udid} ${bundleId} app`, { stdio: \"ignore\" });\n return true;\n } catch {\n return false;\n }\n}\n\n/** Prefer a simulator that already has the requested app installed */\nexport function firstIOSSimulatorWithApp(bundleId: string): IOSSimulator | null {\n const bootedWithApp = listBootedSimulators().find((sim) =>\n hasAppInstalledOnSimulator(sim.udid, bundleId),\n );\n if (bootedWithApp) return bootedWithApp;\n\n const availableWithApp = listIOSSimulators()\n .filter((sim) => sim.isAvailable)\n .find((sim) => hasAppInstalledOnSimulator(sim.udid, bundleId));\n if (availableWithApp) return availableWithApp;\n\n return firstIOSSimulator();\n}\n\n/**\n * Ensure an iOS simulator is available and booted.\n * If none booted, boots the first available simulator (preferring one with the app installed).\n * Returns the simulator or null if none available.\n */\nexport function ensureIOSSimulator(bundleId?: string): IOSSimulator | null {\n const sim = bundleId ? firstIOSSimulatorWithApp(bundleId) : firstIOSSimulator();\n if (!sim) return null;\n\n if (sim.state !== \"Booted\") {\n console.log(`Booting iOS simulator \"${sim.name}\"...`);\n bootSimulator(sim.udid);\n }\n\n return sim;\n}\n\n/** Boot a simulator by UDID */\nexport function bootSimulator(udid: string): void {\n try {\n execSync(`xcrun simctl boot ${udid}`, { stdio: \"ignore\" });\n } catch {\n // May already be booted — ignore\n }\n}\n\n/** Install app on simulator */\nexport function installOnSimulator(udid: string, appPath: string): void {\n execSync(`xcrun simctl install ${udid} ${appPath}`);\n}\n\n/** Launch app on simulator */\nexport function launchOnSimulator(udid: string, bundleId: string): void {\n execSync(`xcrun simctl launch ${udid} ${bundleId}`);\n}\n\n/** Launch app on simulator with a deep link URL (bypasses system confirmation dialog) */\nexport function launchWithUrlOnSimulator(udid: string, bundleId: string, url: string): void {\n execFileSync(\"xcrun\", [\"simctl\", \"launch\", udid, bundleId, \"--open-url\", url]);\n}\n\n/** List URL schemes registered by the installed app on simulator */\nexport function installedUrlSchemesOnSimulator(udid: string, bundleId: string): string[] {\n if (!bundleId) return [];\n\n try {\n const appPath = execSync(`xcrun simctl get_app_container ${udid} ${bundleId} app`, {\n encoding: \"utf-8\",\n }).trim();\n\n const raw = execFileSync(\n \"plutil\",\n [\"-extract\", \"CFBundleURLTypes\", \"json\", \"-o\", \"-\", `${appPath}/Info.plist`],\n {\n encoding: \"utf-8\",\n },\n );\n\n const urlTypes = JSON.parse(raw) as Array<{\n CFBundleURLSchemes?: string[];\n }>;\n\n return urlTypes.flatMap((entry) => entry.CFBundleURLSchemes ?? []);\n } catch {\n return [];\n }\n}\n\n/** Open a URL or deep link on simulator */\nexport function openUrlOnSimulator(udid: string, url: string): void {\n execFileSync(\"xcrun\", [\"simctl\", \"openurl\", udid, url], { stdio: \"ignore\" });\n}\n\n/** Terminate app on simulator */\nexport function terminateOnSimulator(udid: string, bundleId: string): void {\n try {\n execSync(`xcrun simctl terminate ${udid} ${bundleId}`, { stdio: \"ignore\" });\n } catch {\n // May not be running\n }\n}\n\n// ---------------------------------------------------------------------------\n// Physical device support\n// ---------------------------------------------------------------------------\n\nexport interface IOSPhysicalDevice {\n udid: string;\n name: string;\n connectionType: \"USB\" | \"Wi-Fi\" | string;\n}\n\n/**\n * List connected physical iOS devices using xcrun devicectl (Xcode 15+).\n * Falls back to system_profiler if devicectl is unavailable.\n */\nexport function listIOSPhysicalDevices(): IOSPhysicalDevice[] {\n // Try xcrun devicectl first (Xcode 15+)\n try {\n const tmpFile = `/tmp/spana-devicectl-${Date.now()}.json`;\n execSync(`xcrun devicectl list devices --json-output ${tmpFile} 2>/dev/null`, {\n timeout: 10_000,\n });\n const output = readFileSync(tmpFile, \"utf-8\");\n try {\n unlinkSync(tmpFile);\n } catch {\n /* cleanup */\n }\n\n const data = JSON.parse(output);\n const devices: IOSPhysicalDevice[] = [];\n\n for (const device of data?.result?.devices ?? []) {\n const deviceType = device.hardwareProperties?.deviceType ?? \"\";\n const transport = device.connectionProperties?.transportType;\n const state = device.connectionProperties?.tunnelState;\n\n // Only treat iPhones/iPads with an active tunnel as available physical\n // devices. devicectl can report remembered Wi-Fi devices with a transport\n // but tunnelState \"disconnected\", which should not trigger a device-first\n // test run attempt.\n if (\n (deviceType === \"iPhone\" || deviceType === \"iPad\") &&\n transport &&\n state === \"connected\"\n ) {\n devices.push({\n udid: device.hardwareProperties?.udid ?? device.identifier,\n name: device.deviceProperties?.name ?? \"Unknown\",\n connectionType: transport === \"wired\" ? \"USB\" : (transport ?? \"unknown\"),\n });\n }\n }\n\n return devices;\n } catch {\n // Fall back to system_profiler for older Xcode\n }\n\n try {\n const output = execSync(\"system_profiler SPUSBDataType -json 2>/dev/null\", {\n encoding: \"utf-8\",\n timeout: 10_000,\n });\n const data = JSON.parse(output);\n const devices: IOSPhysicalDevice[] = [];\n\n function walkUSB(items: any[]): void {\n for (const item of items) {\n // iOS devices have serial_num and contain \"iPhone\" or \"iPad\" in name\n if (item.serial_num && /iPhone|iPad|iPod/i.test(item._name ?? \"\")) {\n devices.push({\n udid: item.serial_num.replaceAll(\"-\", \"\"),\n name: item._name ?? \"iOS Device\",\n connectionType: \"USB\",\n });\n }\n if (item._items) walkUSB(item._items);\n }\n }\n\n walkUSB(data.SPUSBDataType ?? []);\n return devices;\n } catch {\n return [];\n }\n}\n\n/** Get first connected physical iOS device */\nexport function firstIOSPhysicalDevice(): IOSPhysicalDevice | null {\n const devices = listIOSPhysicalDevices();\n return devices[0] ?? null;\n}\n\n/**\n * Start iproxy to tunnel a port from localhost to a physical device via USB.\n * Requires libimobiledevice (`brew install libimobiledevice`).\n *\n * @returns A cleanup function to kill the iproxy process.\n */\nexport function startIproxy(\n udid: string,\n localPort: number,\n devicePort: number,\n): { host: string; port: number; cleanup: () => void } {\n // Check iproxy is available\n try {\n execSync(\"which iproxy\", { stdio: \"ignore\" });\n } catch {\n throw new Error(\"iproxy not found. Install with: brew install libimobiledevice\");\n }\n\n const { spawn } = require(\"node:child_process\") as typeof import(\"node:child_process\");\n const proc = spawn(\"iproxy\", [`${localPort}:${devicePort}`, \"-u\", udid], {\n stdio: \"ignore\",\n detached: true,\n });\n proc.unref();\n\n // Give iproxy a moment to bind\n const waitUntil = Date.now() + 1500;\n while (Date.now() < waitUntil) {\n /* busy wait */\n }\n\n return {\n host: \"localhost\",\n port: localPort,\n cleanup: () => {\n try {\n proc.kill();\n } catch {\n // already dead\n }\n },\n };\n}\n\n/**\n * Connect to a physical iOS device for testing.\n * Sets up iproxy tunnel and returns connection info for WDA.\n *\n * WDA must be pre-installed and running on the device.\n * Install with: xcodebuild -project WebDriverAgent.xcodeproj -scheme WebDriverAgentRunner\n * -destination \"id=<UDID>\" test\n */\nexport function connectPhysicalDevice(\n udid: string,\n wdaPort = 8100,\n): { host: string; port: number; cleanup: () => void } {\n const localPort = allocatePort(8100);\n\n try {\n const tunnel = startIproxy(udid, localPort, wdaPort);\n return {\n ...tunnel,\n cleanup: () => {\n tunnel.cleanup();\n releasePort(localPort);\n },\n };\n } catch (error) {\n releasePort(localPort);\n throw error;\n }\n}\n\n/**\n * Install an app on a physical iOS device using xcrun devicectl (Xcode 15+).\n * Accepts .app bundles or .ipa files.\n */\nexport function installOnPhysicalDevice(udid: string, appPath: string): void {\n try {\n execSync(`xcrun devicectl device install app --device ${udid} ${appPath}`, {\n stdio: \"inherit\",\n timeout: 120_000,\n });\n } catch {\n throw new Error(\n `Failed to install app on device ${udid}. Ensure the app is signed for this device.`,\n );\n }\n}\n\n/**\n * Check if an app is installed on a physical device.\n */\nexport function hasAppOnPhysicalDevice(udid: string, bundleId: string): boolean {\n if (!bundleId) return false;\n try {\n const tmpFile = `/tmp/spana-applist-${Date.now()}.json`;\n execSync(\n `xcrun devicectl device info apps --device ${udid} --json-output ${tmpFile} 2>/dev/null`,\n { timeout: 15_000 },\n );\n const output = readFileSync(tmpFile, \"utf-8\");\n try {\n unlinkSync(tmpFile);\n } catch {\n /* cleanup */\n }\n return output.includes(bundleId);\n } catch {\n return false;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Network control helpers (pfctl / dnctl)\n// ---------------------------------------------------------------------------\n// WARNING: These functions affect the entire host Mac's network stack.\n// iOS simulators share the host network — there is no per-simulator isolation.\n// Requires sudo.\n\n/** pfctl anchor name used by spana for network rules */\nexport const SPANA_ANCHOR = \"com.spana.network\";\n\n/**\n * Block or unblock all outbound network traffic using pfctl.\n * When enabled, adds a \"block out all\" rule to the spana anchor.\n * When disabled, flushes all rules from the spana anchor.\n */\nexport function pfctlSetOffline(enable: boolean): void {\n if (enable) {\n execSync(`echo \"block out all\\n\" | sudo pfctl -a ${SPANA_ANCHOR} -f -`, { stdio: \"ignore\" });\n try {\n execSync(\"sudo pfctl -e 2>/dev/null\", { stdio: \"ignore\" });\n } catch {\n // May already be enabled\n }\n } else {\n try {\n execSync(`sudo pfctl -a ${SPANA_ANCHOR} -F all`, { stdio: \"ignore\" });\n } catch {\n // Ignore errors\n }\n }\n}\n\n/**\n * Throttle network using dnctl pipe and pfctl dummynet rules.\n * Configures bandwidth and delay for all outbound traffic.\n */\nexport function pfctlSetThrottle(throughputKbps: number, delayMs: number): void {\n execSync(`sudo dnctl pipe 1 config bw ${throughputKbps}Kbit/s delay ${delayMs}ms`, {\n stdio: \"ignore\",\n });\n execSync(`echo \"dummynet out all pipe 1\\n\" | sudo pfctl -a ${SPANA_ANCHOR} -f -`, {\n stdio: \"ignore\",\n });\n try {\n execSync(\"sudo pfctl -e 2>/dev/null\", { stdio: \"ignore\" });\n } catch {\n // May already be enabled\n }\n}\n\n/**\n * Reset all network modifications — flush pfctl anchor rules and dnctl pipes.\n */\nexport function pfctlResetNetwork(): void {\n try {\n execSync(`sudo pfctl -a ${SPANA_ANCHOR} -F all`, { stdio: \"ignore\" });\n } catch {\n // Ignore errors\n }\n try {\n execSync(\"sudo dnctl -q flush\", { stdio: \"ignore\" });\n } catch {\n // Ignore errors\n }\n}\n\n/** Reset simulator keychain (removes all stored passwords and certificates) */\nexport function resetSimulatorKeychain(udid: string): void {\n execSync(`xcrun simctl keychain ${udid} reset`, { stdio: \"ignore\" });\n}\n\n/**\n * Ensure an app is installed on the target device (simulator or physical).\n * Installs from appPath if not already present.\n */\nexport function ensureAppInstalled(opts: {\n udid: string;\n bundleId: string;\n appPath: string;\n isPhysicalDevice: boolean;\n}): void {\n const { udid, bundleId, appPath, isPhysicalDevice } = opts;\n\n if (isPhysicalDevice) {\n if (!hasAppOnPhysicalDevice(udid, bundleId)) {\n console.log(`Installing ${bundleId} on physical device...`);\n installOnPhysicalDevice(udid, appPath);\n }\n } else {\n if (!hasAppInstalledOnSimulator(udid, bundleId)) {\n console.log(`Installing ${bundleId} on simulator...`);\n installOnSimulator(udid, appPath);\n }\n }\n}\n"],"mappings":";;;;;;;;;AAAA,SAAS,cAAc,gBAAgB;AACvC,SAAS,cAAc,kBAAkB;AAoBlC,SAAS,oBAAoC;AAClD,MAAI;AACF,UAAM,SAAS,SAAS,gCAAgC,EAAE,UAAU,QAAQ,CAAC;AAC7E,UAAM,OAAO,KAAK,MAAM,MAAM;AAC9B,UAAM,aAA6B,CAAC;AAEpC,eAAW,CAAC,SAAS,OAAO,KAAK,OAAO,QAAQ,KAAK,WAAW,CAAC,CAAC,GAAG;AAEnE,YAAM,cAAc,QACjB,QAAQ,uCAAuC,EAAE,EACjD,WAAW,KAAK,GAAG;AAEtB,iBAAW,UAAU,SAAkB;AACrC,mBAAW,KAAK;AAAA,UACd,MAAM,OAAO;AAAA,UACb,MAAM,OAAO;AAAA,UACb,OAAO,OAAO;AAAA,UACd,SAAS;AAAA,UACT,aAAa,OAAO,eAAe;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uBAAuB,MAAoB;AACzD,WAAS,yBAAyB,IAAI,UAAU,EAAE,OAAO,SAAS,CAAC;AACrE;AAMO,SAAS,mBAAmB,MAK1B;AACP,QAAM,EAAE,MAAM,UAAU,SAAS,iBAAiB,IAAI;AAEtD,MAAI,kBAAkB;AACpB,QAAI,CAAC,uBAAuB,MAAM,QAAQ,GAAG;AAC3C,cAAQ,IAAI,cAAc,QAAQ,wBAAwB;AAC1D,8BAAwB,MAAM,OAAO;AAAA,IACvC;AAAA,EACF,OAAO;AACL,QAAI,CAAC,2BAA2B,MAAM,QAAQ,GAAG;AAC/C,cAAQ,IAAI,cAAc,QAAQ,kBAAkB;AACpD,yBAAmB,MAAM,OAAO;AAAA,IAClC;AAAA,EACF;AACF;","names":["walkUSB"]}
@@ -1165,6 +1165,34 @@ function buildStorybookUrl(storyId, options, runtime) {
1165
1165
  return url.toString();
1166
1166
  }
1167
1167
 
1168
+ // src/drivers/playwright-parser.ts
1169
+ function rawNodeToElement(node) {
1170
+ const children = node.children && node.children.length > 0 ? node.children.map(rawNodeToElement) : void 0;
1171
+ return {
1172
+ ...node.id !== void 0 ? { id: node.id } : {},
1173
+ ...node.text !== void 0 ? { text: node.text } : {},
1174
+ ...node.value !== void 0 ? { value: node.value } : {},
1175
+ ...node.accessibilityLabel !== void 0 ? { accessibilityLabel: node.accessibilityLabel } : {},
1176
+ // Use role as elementType when present, otherwise fall back to HTML tag name
1177
+ ...node.role !== void 0 ? { elementType: node.role } : node.tag !== void 0 ? { elementType: node.tag } : {},
1178
+ bounds: {
1179
+ x: node.bounds.x,
1180
+ y: node.bounds.y,
1181
+ width: node.bounds.width,
1182
+ height: node.bounds.height
1183
+ },
1184
+ ...node.enabled !== void 0 ? { enabled: node.enabled } : {},
1185
+ ...node.visible !== void 0 ? { visible: node.visible } : {},
1186
+ ...node.clickable !== void 0 ? { clickable: node.clickable } : {},
1187
+ ...node.attributes !== void 0 ? { attributes: node.attributes } : {},
1188
+ ...children !== void 0 ? { children } : {}
1189
+ };
1190
+ }
1191
+ function parseWebHierarchy(json) {
1192
+ const raw = JSON.parse(json);
1193
+ return rawNodeToElement(raw);
1194
+ }
1195
+
1168
1196
  // src/drivers/raw-driver.ts
1169
1197
  import { Context, Effect as Effect4 } from "effect";
1170
1198
  var RawDriver = class extends Context.Tag("RawDriver")() {
@@ -1284,6 +1312,7 @@ export {
1284
1312
  flattenElements,
1285
1313
  waitForElement,
1286
1314
  createCoordinator,
1287
- buildStorybookUrl
1315
+ buildStorybookUrl,
1316
+ parseWebHierarchy
1288
1317
  };
1289
- //# sourceMappingURL=chunk-24KSKK2I.js.map
1318
+ //# sourceMappingURL=chunk-YAV6KBSW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/schemas/selector.ts","../src/smart/element-matcher.ts","../src/smart/coordinator.ts","../src/core/graphemes.ts","../src/smart/auto-wait.ts","../src/smart/diagnostics.ts","../src/smart/hierarchy-cache.ts","../src/api/storybook.ts","../src/drivers/playwright-parser.ts","../src/drivers/raw-driver.ts","../src/drivers/launch-options.ts"],"sourcesContent":["import { Schema } from \"effect\";\n\n// Assertion errors\n\nexport class ElementNotFoundError extends Schema.TaggedError<ElementNotFoundError>()(\n \"ElementNotFoundError\",\n {\n message: Schema.String,\n selector: Schema.Unknown,\n timeoutMs: Schema.optional(Schema.Number),\n },\n) {}\n\nexport class TextMismatchError extends Schema.TaggedError<TextMismatchError>()(\n \"TextMismatchError\",\n {\n message: Schema.String,\n expected: Schema.String,\n actual: Schema.optional(Schema.String),\n selector: Schema.Unknown,\n },\n) {}\n\n// Timeout errors\n\nexport class TimeoutError extends Schema.TaggedError<TimeoutError>()(\"TimeoutError\", {\n message: Schema.String,\n operation: Schema.String,\n timeoutMs: Schema.Number,\n}) {}\n\nexport class WaitTimeoutError extends Schema.TaggedError<WaitTimeoutError>()(\"WaitTimeoutError\", {\n message: Schema.String,\n selector: Schema.Unknown,\n timeoutMs: Schema.Number,\n}) {}\n\n// Connection errors\n\nexport class DriverError extends Schema.TaggedError<DriverError>()(\"DriverError\", {\n message: Schema.String,\n command: Schema.optional(Schema.String),\n exitCode: Schema.optional(Schema.Number),\n stdout: Schema.optional(Schema.String),\n stderr: Schema.optional(Schema.String),\n}) {}\n\nexport class DeviceDisconnectedError extends Schema.TaggedError<DeviceDisconnectedError>()(\n \"DeviceDisconnectedError\",\n {\n message: Schema.String,\n deviceId: Schema.optional(Schema.String),\n platform: Schema.optional(Schema.String),\n },\n) {}\n\n// App errors\n\nexport class AppCrashedError extends Schema.TaggedError<AppCrashedError>()(\"AppCrashedError\", {\n message: Schema.String,\n appId: Schema.optional(Schema.String),\n platform: Schema.optional(Schema.String),\n}) {}\n\nexport class AppNotInstalledError extends Schema.TaggedError<AppNotInstalledError>()(\n \"AppNotInstalledError\",\n {\n message: Schema.String,\n appId: Schema.String,\n platform: Schema.optional(Schema.String),\n },\n) {}\n\n// Config errors\n\nexport class FlowSyntaxError extends Schema.TaggedError<FlowSyntaxError>()(\"FlowSyntaxError\", {\n message: Schema.String,\n filePath: Schema.String,\n}) {}\n\nexport class DeviceNotFoundError extends Schema.TaggedError<DeviceNotFoundError>()(\n \"DeviceNotFoundError\",\n {\n message: Schema.String,\n platform: Schema.optional(Schema.String),\n deviceId: Schema.optional(Schema.String),\n },\n) {}\n\nexport class ConfigError extends Schema.TaggedError<ConfigError>()(\"ConfigError\", {\n message: Schema.String,\n filePath: Schema.optional(Schema.String),\n}) {}\n\n// Union type of all error types\n\nexport type ProvError =\n | ElementNotFoundError\n | TextMismatchError\n | TimeoutError\n | WaitTimeoutError\n | DriverError\n | DeviceDisconnectedError\n | AppCrashedError\n | AppNotInstalledError\n | FlowSyntaxError\n | DeviceNotFoundError\n | ConfigError;\n","import { Schema } from \"effect\";\n\nexport type Platform = \"android\" | \"ios\" | \"web\";\n\n// Runtime schema definitions — used for Schema.decode / .parse on config-time\n// selector payloads. The TypeScript types below are generic over a testID\n// string union `T` so projects can pass a typed set of testIDs and get\n// autocomplete + misspelling protection at the call site.\nconst _TestIDSelectorSchema = Schema.Struct({ testID: Schema.String });\nconst _TextSelectorSchema = Schema.Struct({ text: Schema.String });\nconst _AccessibilityLabelSelectorSchema = Schema.Struct({ accessibilityLabel: Schema.String });\nconst _PointSelectorSchema = Schema.Struct({\n point: Schema.Struct({ x: Schema.Number, y: Schema.Number }),\n});\n\nexport const SelectorSchema = Schema.Union(\n Schema.String,\n _TestIDSelectorSchema,\n _TextSelectorSchema,\n _AccessibilityLabelSelectorSchema,\n _PointSelectorSchema,\n);\n\n/**\n * Selector types. Generic parameter `T` lets projects pin a union of known\n * testIDs so `{ testID: \"bogus-id\" }` becomes a type error.\n */\nexport type Selector<T extends string = string> =\n | T\n | { testID: T }\n | { text: string }\n | { accessibilityLabel: string }\n | { point: { x: number; y: number } };\n\n/** Relative selector — find element relative to an anchor element's position. */\nexport interface RelativeSelector<T extends string = string> {\n selector: Selector<T>;\n below?: Selector<T>;\n above?: Selector<T>;\n leftOf?: Selector<T>;\n rightOf?: Selector<T>;\n childOf?: Selector<T>;\n}\n\n/** Extended selector that supports both simple and relative selectors. */\nexport type ExtendedSelector<T extends string = string> = Selector<T> | RelativeSelector<T>;\n\nexport function isRelativeSelector<T extends string = string>(\n sel: ExtendedSelector<T>,\n): sel is RelativeSelector<T> {\n return typeof sel === \"object\" && sel !== null && \"selector\" in sel;\n}\n","import type { Element } from \"../schemas/element.js\";\nimport type { Selector, ExtendedSelector, RelativeSelector } from \"../schemas/selector.js\";\nimport { isRelativeSelector } from \"../schemas/selector.js\";\n\n/** Flatten an element tree into a list (iterative DFS — avoids recursive spread allocation) */\nexport function flattenElements(root: Element): Element[] {\n const result: Element[] = [];\n const stack: Element[] = [root];\n while (stack.length > 0) {\n const node = stack.pop()!;\n result.push(node);\n if (node.children) {\n // Push in reverse so left-most children are visited first (preserves DFS order)\n for (let i = node.children.length - 1; i >= 0; i--) {\n stack.push(node.children[i]!);\n }\n }\n }\n return result;\n}\n\n/** Check if an element matches a selector */\nexport function matchesSelector(element: Element, selector: Selector): boolean {\n if (typeof selector === \"string\") {\n // String shorthand = text match (case-insensitive)\n return element.text?.toLowerCase().includes(selector.toLowerCase()) ?? false;\n }\n if (\"testID\" in selector) {\n return element.id === selector.testID;\n }\n if (\"text\" in selector) {\n return element.text?.toLowerCase().includes(selector.text.toLowerCase()) ?? false;\n }\n if (\"accessibilityLabel\" in selector) {\n return element.accessibilityLabel === selector.accessibilityLabel;\n }\n if (\"point\" in selector) {\n const { x, y } = selector.point;\n const b = element.bounds;\n return x >= b.x && x <= b.x + b.width && y >= b.y && y <= b.y + b.height;\n }\n return false;\n}\n\n/** Find all elements matching a selector */\nexport function findElements(root: Element, selector: Selector): Element[] {\n return flattenElements(root).filter((el) => matchesSelector(el, selector));\n}\n\ninterface ElementPath {\n element: Element;\n ancestors: Element[];\n}\n\nfunction isProbablyOnScreen(element: Element): boolean {\n const centerX = element.bounds.x + element.bounds.width / 2;\n const centerY = element.bounds.y + element.bounds.height / 2;\n\n return element.bounds.width > 0 && element.bounds.height > 0 && centerX >= 0 && centerY >= 0;\n}\n\nfunction findPathToElement(root: Element, target: Element): ElementPath | undefined {\n const stack: ElementPath[] = [{ element: root, ancestors: [] }];\n\n while (stack.length > 0) {\n const current = stack.pop()!;\n if (current.element === target) {\n return current;\n }\n\n const children = current.element.children;\n if (!children) {\n continue;\n }\n\n for (let index = children.length - 1; index >= 0; index -= 1) {\n const child = children[index]!;\n stack.push({\n element: child,\n ancestors: [...current.ancestors, current.element],\n });\n }\n }\n\n return undefined;\n}\n\nfunction isActionable(element: Element): boolean {\n return (\n element.visible !== false &&\n element.enabled !== false &&\n element.clickable === true &&\n isProbablyOnScreen(element)\n );\n}\n\nfunction resolveActionTarget(root: Element, element: Element): Element {\n const path = findPathToElement(root, element);\n if (!path) {\n return element;\n }\n\n const candidates = [path.element, ...path.ancestors.toReversed()];\n return candidates.find(isActionable) ?? element;\n}\n\n/** Find the best matching element — prefer clickable, then deepest */\nexport function findElement(root: Element, selector: Selector): Element | undefined {\n const matches = findElements(root, selector).filter((el) => el.visible !== false);\n if (matches.length === 0) return undefined;\n\n const visibleMatches = matches.filter(isProbablyOnScreen);\n if (visibleMatches.length === 0) return undefined;\n\n // Prefer clickable elements\n const clickable = visibleMatches.filter((el) => el.clickable);\n if (clickable.length > 0) return clickable[clickable.length - 1]!; // deepest clickable\n return visibleMatches[visibleMatches.length - 1]!; // deepest match\n}\n\n/** Find the best actionable target for touch-style interactions. */\nexport function findActionElement(root: Element, selector: Selector): Element | undefined {\n const match = findElement(root, selector);\n return match ? resolveActionTarget(root, match) : undefined;\n}\n\n/** Calculate the center point of an element's bounds */\nexport function centerOf(element: Element): { x: number; y: number } {\n return {\n x: Math.round(element.bounds.x + element.bounds.width / 2),\n y: Math.round(element.bounds.y + element.bounds.height / 2),\n };\n}\n\n/** Format a selector (simple or extended) as a human-readable string for error messages */\nexport function formatSelector(sel: ExtendedSelector): string {\n if (isRelativeSelector(sel)) {\n const parts = [formatSimpleSelector(sel.selector)];\n if (sel.below) parts.push(`below ${formatSimpleSelector(sel.below)}`);\n if (sel.above) parts.push(`above ${formatSimpleSelector(sel.above)}`);\n if (sel.leftOf) parts.push(`leftOf ${formatSimpleSelector(sel.leftOf)}`);\n if (sel.rightOf) parts.push(`rightOf ${formatSimpleSelector(sel.rightOf)}`);\n if (sel.childOf) parts.push(`childOf ${formatSimpleSelector(sel.childOf)}`);\n return parts.join(\" \");\n }\n return formatSimpleSelector(sel);\n}\n\nfunction formatSimpleSelector(sel: Selector): string {\n if (typeof sel === \"string\") return `\"${sel}\"`;\n if (\"testID\" in sel) return `testID: \"${sel.testID}\"`;\n if (\"text\" in sel) return `text: \"${sel.text}\"`;\n if (\"accessibilityLabel\" in sel) return `accessibilityLabel: \"${sel.accessibilityLabel}\"`;\n if (\"point\" in sel) return `point: (${sel.point.x}, ${sel.point.y})`;\n return JSON.stringify(sel);\n}\n\n/** Find an element using an extended selector (simple or relative) */\nexport function findElementExtended(\n root: Element,\n selector: ExtendedSelector,\n): Element | undefined {\n if (!isRelativeSelector(selector)) {\n return findElement(root, selector);\n }\n\n return findRelativeElement(root, selector);\n}\n\n/** Find the best actionable element for a simple or relative selector. */\nexport function findActionElementExtended(\n root: Element,\n selector: ExtendedSelector,\n): Element | undefined {\n const match = findElementExtended(root, selector);\n return match ? resolveActionTarget(root, match) : undefined;\n}\n\nfunction findRelativeElement(root: Element, rel: RelativeSelector): Element | undefined {\n // Find all candidates matching the base selector\n const all = flattenElements(root).filter((el) => el.visible !== false && isProbablyOnScreen(el));\n let candidates = all.filter((el) => matchesSelector(el, rel.selector));\n\n if (candidates.length === 0) return undefined;\n\n // Apply each relative constraint\n if (rel.below) {\n const anchor = findElement(root, rel.below);\n if (!anchor) return undefined;\n const anchorBottom = anchor.bounds.y + anchor.bounds.height;\n candidates = candidates.filter((el) => el.bounds.y >= anchorBottom);\n // Sort by proximity (closest below first)\n candidates.sort((a, b) => a.bounds.y - b.bounds.y);\n }\n\n if (rel.above) {\n const anchor = findElement(root, rel.above);\n if (!anchor) return undefined;\n const anchorTop = anchor.bounds.y;\n candidates = candidates.filter((el) => el.bounds.y + el.bounds.height <= anchorTop);\n // Sort by proximity (closest above first = highest y)\n candidates.sort((a, b) => b.bounds.y - a.bounds.y);\n }\n\n if (rel.leftOf) {\n const anchor = findElement(root, rel.leftOf);\n if (!anchor) return undefined;\n const anchorLeft = anchor.bounds.x;\n candidates = candidates.filter((el) => el.bounds.x + el.bounds.width <= anchorLeft);\n // Sort by proximity (closest left first = highest x)\n candidates.sort((a, b) => b.bounds.x - a.bounds.x);\n }\n\n if (rel.rightOf) {\n const anchor = findElement(root, rel.rightOf);\n if (!anchor) return undefined;\n const anchorRight = anchor.bounds.x + anchor.bounds.width;\n candidates = candidates.filter((el) => el.bounds.x >= anchorRight);\n // Sort by proximity (closest right first)\n candidates.sort((a, b) => a.bounds.x - b.bounds.x);\n }\n\n if (rel.childOf) {\n const parent = findElement(root, rel.childOf);\n if (!parent) return undefined;\n // Filter to elements that are descendants of the parent\n const descendants = flattenElements(parent);\n const descendantSet = new Set(descendants);\n candidates = candidates.filter((el) => descendantSet.has(el) && el !== parent);\n }\n\n return candidates[0];\n}\n","import { Duration, Effect } from \"effect\";\nimport type { RawDriverService } from \"../drivers/raw-driver.js\";\nimport type { Element } from \"../schemas/element.js\";\nimport type { ExtendedSelector } from \"../schemas/selector.js\";\nimport type { WaitTimeoutError } from \"../errors.js\";\nimport { DriverError, ElementNotFoundError, TextMismatchError } from \"../errors.js\";\nimport { splitGraphemes } from \"../core/graphemes.js\";\nimport { centerOf, findElementExtended, formatSelector } from \"./element-matcher.js\";\nimport {\n waitForActionElement,\n waitForElement,\n waitForNotVisible,\n type WaitOptions,\n} from \"./auto-wait.js\";\nimport {\n createHierarchyCache,\n type HierarchyCacheConfig,\n type HierarchyCache,\n} from \"./hierarchy-cache.js\";\n\nexport type Direction = \"up\" | \"down\" | \"left\" | \"right\";\n\ntype HierarchyParser = (raw: string) => Element;\n\n// The `_T` type parameter is reserved for typed-testID projects that want to\n// thread a testID union through options. It's unused in the interface body\n// but enabled at the type level so `ScrollUntilVisibleOptions<\"foo\"|\"bar\">`\n// works when called from a typed app.\nexport interface ScrollUntilVisibleOptions<_T extends string = string> extends WaitOptions {\n /** Where the target is relative to the current viewport. Default: \"down\". */\n direction?: Direction;\n /** Max number of scroll gestures to attempt before failing. Default: 5. */\n maxScrolls?: number;\n}\n\nexport type KeyboardDismissStrategy = \"auto\" | \"driver\" | \"back\";\n\nexport interface DismissKeyboardOptions {\n /** Default: \"auto\" (driver hideKeyboard, then Android back fallback). */\n strategy?: KeyboardDismissStrategy;\n}\n\nexport interface BackUntilVisibleOptions<_T extends string = string> extends WaitOptions {\n /** Max number of back actions to attempt before failing. Default: 3. */\n maxBacks?: number;\n}\n\nconst DEFAULT_SCROLL_SEARCH_DIRECTION: Direction = \"down\";\nconst DEFAULT_MAX_SCROLLS = 5;\nconst DEFAULT_DISMISS_KEYBOARD_STRATEGY: KeyboardDismissStrategy = \"auto\";\nconst DEFAULT_MAX_BACKS = 3;\n\nfunction computeSwipeCoords(\n direction: Direction,\n screenW: number,\n screenH: number,\n offsetFraction: number,\n): { startX: number; startY: number; endX: number; endY: number } {\n const cx = screenW / 2;\n const cy = screenH / 2;\n const offset = Math.min(screenW, screenH) * offsetFraction;\n\n return {\n up: { startX: cx, startY: cy + offset, endX: cx, endY: cy - offset },\n down: { startX: cx, startY: cy - offset, endX: cx, endY: cy + offset },\n left: { startX: cx + offset, startY: cy, endX: cx - offset, endY: cy },\n right: { startX: cx - offset, startY: cy, endX: cx + offset, endY: cy },\n }[direction];\n}\n\ntype PollMatchResult = { matched: boolean; actual?: string };\n\nexport interface CoordinatorConfig {\n parse: HierarchyParser;\n defaults?: WaitOptions;\n screenWidth?: number;\n screenHeight?: number;\n /** Pause after each action (tap, scroll) to let the UI settle. */\n waitForIdleTimeout?: number;\n /** Delay between each character when typing. */\n typingDelay?: number;\n /** Hierarchy cache TTL in ms. Default: 100. Set to 0 to disable caching. */\n hierarchyCacheTtl?: number;\n /** Default output directory for screenshot diffs. */\n outputDir?: string;\n}\n\nexport function createCoordinator<T extends string = string, R extends string = string>(\n driver: RawDriverService<T, R>,\n config: CoordinatorConfig,\n) {\n const { parse, defaults } = config;\n\n const cacheConfig: HierarchyCacheConfig = {\n hierarchyCacheTtl: config.hierarchyCacheTtl,\n };\n const cache: HierarchyCache = createHierarchyCache(cacheConfig);\n\n const idleWait = (): Effect.Effect<void> => {\n const ms = config.waitForIdleTimeout;\n return ms && ms > 0 ? Effect.sleep(Duration.millis(ms)) : Effect.void;\n };\n\n /** Invalidate cache after any mutation action */\n const afterMutation = (): Effect.Effect<void> =>\n Effect.gen(function* () {\n cache.invalidate();\n yield* idleWait();\n });\n\n // Clamp Y to avoid iOS system gesture zones (home indicator, notification center).\n // Uses screen dimensions from coordinator config (fetched once at init).\n const screenH = config.screenHeight ?? 1920;\n const safeMinY = screenH * 0.15;\n const safeMaxY = screenH * 0.85;\n const clampY = (y: number): number => Math.max(safeMinY, Math.min(safeMaxY, y));\n\n const swipeEffect = (\n direction: Direction,\n opts?: { duration?: number },\n ): Effect.Effect<void, DriverError> =>\n Effect.gen(function* () {\n const w = config.screenWidth ?? 1080;\n const h = config.screenHeight ?? 1920;\n const coords = computeSwipeCoords(direction, w, h, 0.2);\n yield* driver.swipe(\n coords.startX,\n clampY(coords.startY),\n coords.endX,\n clampY(coords.endY),\n opts?.duration ?? 300,\n );\n yield* afterMutation();\n });\n\n const scrollEffect = (direction: Direction): Effect.Effect<void, DriverError> =>\n Effect.gen(function* () {\n const w = config.screenWidth ?? 1080;\n const h = config.screenHeight ?? 1920;\n const coords = computeSwipeCoords(direction, w, h, 0.3);\n yield* driver.swipe(\n coords.startX,\n clampY(coords.startY),\n coords.endX,\n clampY(coords.endY),\n 500,\n );\n // Wait for scroll animation to settle before probing hierarchy\n yield* Effect.promise(() => new Promise((r) => setTimeout(r, 300)));\n yield* afterMutation();\n });\n\n const probeVisible = (\n selector: ExtendedSelector,\n opts?: WaitOptions & { probeTimeout?: number },\n ): Effect.Effect<boolean, DriverError> =>\n Effect.gen(function* () {\n cache.invalidate();\n const probeTimeout = opts?.probeTimeout ?? 1;\n const result = yield* Effect.either(\n waitForElement(\n driver,\n selector,\n parse,\n { ...defaults, ...opts, timeout: probeTimeout },\n cache,\n ),\n );\n\n if (result._tag === \"Right\") {\n return true;\n }\n\n if (result.left._tag === \"ElementNotFoundError\" || result.left._tag === \"WaitTimeoutError\") {\n return false;\n }\n\n return yield* result.left;\n });\n\n const gestureDirectionForSearch = (direction: Direction): Direction => {\n const directionMap: Record<Direction, Direction> = {\n up: \"down\",\n down: \"up\",\n left: \"right\",\n right: \"left\",\n };\n\n return directionMap[direction];\n };\n\n const pollUntilMatch = (\n selector: ExtendedSelector,\n opts: WaitOptions | undefined,\n check: (el: Element) => PollMatchResult,\n formatError: (\n actual: string | undefined,\n timeout: number,\n ) => {\n message: string;\n expected: string;\n },\n ): Effect.Effect<\n void,\n ElementNotFoundError | WaitTimeoutError | TextMismatchError | DriverError\n > =>\n Effect.gen(function* () {\n const timeout = opts?.timeout ?? defaults?.timeout ?? 5000;\n const pollInterval = opts?.pollInterval ?? defaults?.pollInterval ?? 200;\n const start = Date.now();\n let lastActual: string | undefined;\n\n while (Date.now() - start < timeout) {\n if (cache) cache.invalidate();\n const raw = yield* driver.dumpHierarchy();\n const root = parse(raw);\n const element = findElementExtended(root, selector);\n if (element) {\n const result = check(element);\n if (result.matched) return;\n lastActual = result.actual;\n }\n yield* Effect.sleep(Duration.millis(pollInterval));\n }\n\n const err = formatError(lastActual, timeout);\n return yield* new TextMismatchError({\n message: err.message,\n expected: err.expected,\n actual: lastActual,\n selector,\n });\n });\n\n const dismissKeyboardWithDriver = (): Effect.Effect<void, DriverError> =>\n Effect.gen(function* () {\n yield* driver.hideKeyboard();\n yield* afterMutation();\n });\n\n const dismissKeyboardWithBack = (): Effect.Effect<void, DriverError> =>\n Effect.gen(function* () {\n yield* driver.back();\n yield* afterMutation();\n });\n\n const scaleGesture = (\n methodName: \"pinch\" | \"zoom\",\n selector: ExtendedSelector,\n opts?: { scale?: number; duration?: number } & WaitOptions,\n ): Effect.Effect<void, ElementNotFoundError | WaitTimeoutError | DriverError> =>\n Effect.gen(function* () {\n const element = yield* waitForActionElement(\n driver,\n selector,\n parse,\n { ...defaults, ...opts },\n cache,\n );\n const { x, y } = centerOf(element);\n const scale = opts?.scale ?? 0.5;\n const duration = opts?.duration ?? 1500;\n const fn = methodName === \"pinch\" ? driver.pinch : driver.zoom;\n if (!fn) {\n return yield* new DriverError({\n message: `${methodName}() is only supported on mobile platforms (Android/iOS)`,\n });\n }\n yield* fn.call(driver, x, y, scale, duration);\n yield* afterMutation();\n });\n\n const assertEnabledState = (\n selector: ExtendedSelector,\n expectedEnabled: boolean,\n opts?: WaitOptions,\n ): Effect.Effect<\n void,\n ElementNotFoundError | WaitTimeoutError | TextMismatchError | DriverError\n > =>\n Effect.gen(function* () {\n const element = yield* waitForElement(\n driver,\n selector,\n parse,\n { ...defaults, ...opts },\n cache,\n );\n const isEnabled = element.enabled !== false;\n if (isEnabled !== expectedEnabled) {\n const state = expectedEnabled ? \"enabled\" : \"disabled\";\n const actual = expectedEnabled ? \"disabled\" : \"enabled\";\n return yield* new TextMismatchError({\n message: `Expected element to be ${state} but it is ${actual} — selector: ${formatSelector(selector)}`,\n expected: state,\n actual,\n selector,\n });\n }\n });\n\n const createAssertions = () => ({\n assertVisible: (\n selector: ExtendedSelector,\n opts?: WaitOptions,\n ): Effect.Effect<Element, ElementNotFoundError | WaitTimeoutError | DriverError> =>\n waitForElement(driver, selector, parse, { ...defaults, ...opts }, cache),\n\n assertHidden: (\n selector: ExtendedSelector,\n opts?: WaitOptions,\n ): Effect.Effect<void, WaitTimeoutError | DriverError> =>\n waitForNotVisible(driver, selector, parse, { ...defaults, ...opts }, cache),\n\n assertText: (\n selector: ExtendedSelector,\n expected: string,\n opts?: WaitOptions,\n ): Effect.Effect<\n void,\n ElementNotFoundError | WaitTimeoutError | TextMismatchError | DriverError\n > =>\n pollUntilMatch(\n selector,\n opts,\n (el) => ({ matched: el.text === expected, actual: el.text }),\n (actual, timeout) => ({\n message: `Expected text \"${expected}\" but got \"${actual ?? \"(no text)\"}\" after ${timeout}ms`,\n expected,\n }),\n ),\n\n assertContainsText: (\n selector: ExtendedSelector,\n expected: string,\n opts?: WaitOptions,\n ): Effect.Effect<\n void,\n ElementNotFoundError | WaitTimeoutError | TextMismatchError | DriverError\n > =>\n pollUntilMatch(\n selector,\n opts,\n (el) => {\n const actual = el.text ?? \"\";\n return {\n matched: actual.toLowerCase().includes(expected.toLowerCase()),\n actual: el.text,\n };\n },\n (actual, timeout) => ({\n message: `Expected text to contain \"${expected}\" but got \"${actual ?? \"(no text)\"}\" after ${timeout}ms`,\n expected,\n }),\n ),\n\n assertEnabled: (\n selector: ExtendedSelector,\n opts?: WaitOptions,\n ): Effect.Effect<\n void,\n ElementNotFoundError | WaitTimeoutError | TextMismatchError | DriverError\n > => assertEnabledState(selector, true, opts),\n\n assertDisabled: (\n selector: ExtendedSelector,\n opts?: WaitOptions,\n ): Effect.Effect<\n void,\n ElementNotFoundError | WaitTimeoutError | TextMismatchError | DriverError\n > => assertEnabledState(selector, false, opts),\n\n getText: (\n selector: ExtendedSelector,\n opts?: WaitOptions,\n ): Effect.Effect<string, ElementNotFoundError | WaitTimeoutError | DriverError> =>\n Effect.gen(function* () {\n const element = yield* waitForElement(\n driver,\n selector,\n parse,\n { ...defaults, ...opts },\n cache,\n );\n return element.text ?? \"\";\n }),\n\n isElementEnabled: (\n selector: ExtendedSelector,\n opts?: WaitOptions,\n ): Effect.Effect<boolean, ElementNotFoundError | WaitTimeoutError | DriverError> =>\n Effect.gen(function* () {\n const element = yield* waitForElement(\n driver,\n selector,\n parse,\n { ...defaults, ...opts },\n cache,\n );\n return element.enabled !== false;\n }),\n\n assertValue: (\n selector: ExtendedSelector,\n expected: string | number,\n opts?: WaitOptions,\n ): Effect.Effect<\n void,\n ElementNotFoundError | WaitTimeoutError | TextMismatchError | DriverError\n > => {\n const expectedStr = String(expected);\n return pollUntilMatch(\n selector,\n opts,\n (el) => {\n const actual = el.value ?? \"\";\n return { matched: actual === expectedStr, actual };\n },\n (actual, timeout) => ({\n message: `Expected value \"${expectedStr}\" but got \"${actual ?? \"(no value)\"}\" after ${timeout}ms`,\n expected: expectedStr,\n }),\n );\n },\n\n assertAttribute: (\n selector: ExtendedSelector,\n name: string,\n expectedValue?: string,\n opts?: WaitOptions,\n ): Effect.Effect<\n void,\n ElementNotFoundError | WaitTimeoutError | TextMismatchError | DriverError\n > =>\n pollUntilMatch(\n selector,\n opts,\n (el) => {\n const actual = el.attributes?.[name];\n if (expectedValue === undefined) {\n return { matched: actual !== undefined, actual };\n }\n return { matched: actual === expectedValue, actual };\n },\n (actual, timeout) =>\n expectedValue === undefined\n ? {\n message: `Expected attribute \"${name}\" to exist but it was not found after ${timeout}ms`,\n expected: name,\n }\n : {\n message: `Expected attribute \"${name}\" to be \"${expectedValue}\" but got \"${actual ?? \"(not found)\"}\" after ${timeout}ms`,\n expected: expectedValue,\n },\n ),\n\n assertMatchesText: (\n selector: ExtendedSelector,\n pattern: RegExp,\n opts?: WaitOptions,\n ): Effect.Effect<\n void,\n ElementNotFoundError | WaitTimeoutError | TextMismatchError | DriverError\n > =>\n pollUntilMatch(\n selector,\n opts,\n (el) => {\n const actual = el.text ?? \"\";\n return { matched: pattern.test(actual), actual };\n },\n (actual, timeout) => ({\n message: `Expected text to match ${pattern} but got \"${actual ?? \"(no text)\"}\" after ${timeout}ms`,\n expected: String(pattern),\n }),\n ),\n\n getAttribute: (\n selector: ExtendedSelector,\n name: string,\n opts?: WaitOptions,\n ): Effect.Effect<string | undefined, ElementNotFoundError | WaitTimeoutError | DriverError> =>\n Effect.gen(function* () {\n const element = yield* waitForElement(\n driver,\n selector,\n parse,\n { ...defaults, ...opts },\n cache,\n );\n return element.attributes?.[name];\n }),\n\n assertScreenshot: (\n selector: ExtendedSelector | undefined,\n name: string,\n flowFilePath: string,\n flowName: string,\n platform: string,\n options: {\n threshold?: number;\n maxDiffPixelRatio?: number;\n mask?: Array<{ x: number; y: number; width: number; height: number }>;\n updateBaselines?: boolean;\n outputDir?: string;\n baselinesDir?: string;\n },\n ): Effect.Effect<void, ElementNotFoundError | WaitTimeoutError | DriverError> =>\n Effect.gen(function* () {\n const { resolveBaselinePath, readBaseline, writeBaseline } = yield* Effect.promise(\n () => import(\"../core/baseline-manager.js\"),\n );\n const { cropToElement, applyMask, compareScreenshots } = yield* Effect.promise(\n () => import(\"../core/screenshot-compare.js\"),\n );\n\n // 1. Take screenshot\n const raw = yield* driver.takeScreenshot();\n\n // 2. Optionally crop to element bounds\n let screenshotBuf: Buffer;\n if (selector !== undefined) {\n const element = yield* waitForElement(driver, selector, parse, { ...defaults }, cache);\n screenshotBuf = yield* Effect.promise(() => cropToElement(raw, element.bounds));\n } else {\n screenshotBuf = Buffer.from(raw);\n }\n\n // 3. Resolve baseline path\n const baselinePath = resolveBaselinePath(\n flowFilePath,\n flowName,\n platform,\n name,\n options.baselinesDir,\n );\n\n // 4. If updateBaselines: write baseline and return\n if (options.updateBaselines) {\n yield* Effect.promise(() => Promise.resolve(writeBaseline(baselinePath, screenshotBuf)));\n return;\n }\n\n // 5. If no baseline exists (first run): write baseline and return\n const existing = readBaseline(baselinePath);\n if (existing === null) {\n yield* Effect.promise(() => Promise.resolve(writeBaseline(baselinePath, screenshotBuf)));\n return;\n }\n\n // 6. Apply masks if provided\n let actualBuf: Buffer = screenshotBuf;\n if (options.mask && options.mask.length > 0) {\n actualBuf = yield* Effect.promise(() => applyMask(screenshotBuf, options.mask!));\n }\n\n // 7. Compare\n const result = compareScreenshots(existing, actualBuf, {\n threshold: options.threshold,\n maxDiffPixelRatio: options.maxDiffPixelRatio,\n });\n\n // 8. If mismatch: write output images and fail\n if (!result.match) {\n const { writeFileSync, mkdirSync } = yield* Effect.promise(() => import(\"node:fs\"));\n const { join } = yield* Effect.promise(() => import(\"node:path\"));\n const outDir = options.outputDir ?? config.outputDir ?? \"spana-output\";\n mkdirSync(outDir, { recursive: true });\n const safeFlowName = flowName\n .toLowerCase()\n .replaceAll(/[^a-z0-9]+/g, \"-\")\n .replaceAll(/^-|-$/g, \"\");\n const prefix = join(outDir, `${safeFlowName}-${platform}-${name}`);\n writeFileSync(`${prefix}-expected.png`, existing);\n writeFileSync(`${prefix}-actual.png`, actualBuf);\n if (result.diffImage) {\n writeFileSync(`${prefix}-diff.png`, result.diffImage);\n }\n const detail = result.sizeMismatch\n ? \"image dimensions differ\"\n : `${result.diffPixelCount} differing pixels (ratio: ${(result.diffPixelRatio * 100).toFixed(2)}%)`;\n return yield* new DriverError({\n message: `Screenshot mismatch for \"${name}\": ${detail}. Expected: ${prefix}-expected.png, Actual: ${prefix}-actual.png${result.diffImage ? `, Diff: ${prefix}-diff.png` : \"\"}`,\n });\n }\n }),\n\n assertAccessibilityLabel: (\n selector: ExtendedSelector,\n expected?: string,\n opts?: WaitOptions,\n ): Effect.Effect<\n void,\n ElementNotFoundError | WaitTimeoutError | TextMismatchError | DriverError\n > =>\n pollUntilMatch(\n selector,\n opts,\n (el) => {\n const label = el.accessibilityLabel;\n if (expected === undefined) {\n return { matched: label !== undefined && label.length > 0, actual: label };\n }\n return { matched: label === expected, actual: label };\n },\n (actual, timeout) =>\n expected === undefined\n ? {\n message: `Expected element to have a non-empty accessibilityLabel but got \"${actual ?? \"(none)\"}\" after ${timeout}ms`,\n expected: \"(non-empty)\",\n }\n : {\n message: `Expected accessibilityLabel \"${expected}\" but got \"${actual ?? \"(none)\"}\" after ${timeout}ms`,\n expected,\n },\n ),\n\n assertFocusable: (\n selector: ExtendedSelector,\n platform: string,\n opts?: WaitOptions,\n ): Effect.Effect<\n void,\n ElementNotFoundError | WaitTimeoutError | TextMismatchError | DriverError\n > =>\n Effect.gen(function* () {\n const { isFocusable } = yield* Effect.promise(\n () => import(\"../core/accessibility-audit.js\"),\n );\n yield* pollUntilMatch(\n selector,\n opts,\n (el) => {\n const focusable = isFocusable(el as unknown as Record<string, unknown>, {\n platform: platform as import(\"../schemas/selector.js\").Platform,\n });\n return { matched: focusable, actual: focusable ? \"focusable\" : \"not focusable\" };\n },\n (actual, timeout) => ({\n message: `Expected element to be focusable but it was \"${actual ?? \"not focusable\"}\" after ${timeout}ms — selector: ${formatSelector(selector)}`,\n expected: \"focusable\",\n }),\n );\n }),\n\n assertRole: (\n selector: ExtendedSelector,\n expectedRole: string,\n platform: string,\n opts?: WaitOptions,\n ): Effect.Effect<\n void,\n ElementNotFoundError | WaitTimeoutError | TextMismatchError | DriverError\n > =>\n Effect.gen(function* () {\n const { normalizeRole } = yield* Effect.promise(\n () => import(\"../core/accessibility-audit.js\"),\n );\n yield* pollUntilMatch(\n selector,\n opts,\n (el) => {\n const actual = normalizeRole(\n platform as import(\"../schemas/selector.js\").Platform,\n el.elementType ?? \"\",\n el.attributes ?? {},\n );\n return { matched: actual === expectedRole, actual };\n },\n (actual, timeout) => ({\n message: `Expected role \"${expectedRole}\" but got \"${actual ?? \"(unknown)\"}\" after ${timeout}ms — selector: ${formatSelector(selector)}`,\n expected: expectedRole,\n }),\n );\n }),\n\n assertMinTouchTarget: (\n selector: ExtendedSelector,\n minSize: number,\n opts?: WaitOptions,\n ): Effect.Effect<\n void,\n ElementNotFoundError | WaitTimeoutError | TextMismatchError | DriverError\n > =>\n pollUntilMatch(\n selector,\n opts,\n (el) => {\n const { width, height } = el.bounds;\n const passed = width >= minSize && height >= minSize;\n const actual = `${width}x${height}`;\n return { matched: passed, actual };\n },\n (actual, timeout) => ({\n message: `Expected touch target to be at least ${minSize}x${minSize}px but got \"${actual ?? \"(unknown)\"}\" after ${timeout}ms — selector: ${formatSelector(selector)}`,\n expected: `${minSize}x${minSize}`,\n }),\n ),\n\n assertAccessibilityAudit: (\n platform: string,\n options: {\n severity?: \"critical\" | \"serious\" | \"moderate\" | \"minor\";\n rules?: string[];\n targetSelector?: string;\n excludeSelectors?: string[];\n } = {},\n ): Effect.Effect<void, DriverError> =>\n Effect.gen(function* () {\n if (platform !== \"web\") {\n return yield* new DriverError({\n message: `assertAccessibilityAudit() is only supported on web — platform \"${platform}\" is not supported`,\n });\n }\n\n const { readFileSync } = yield* Effect.promise(() => import(\"node:fs\"));\n const { createRequire } = yield* Effect.promise(() => import(\"node:module\"));\n const require = createRequire(import.meta.url);\n const axePath: string = require.resolve(\"axe-core/axe.js\");\n const axeSource = readFileSync(axePath, \"utf-8\");\n\n const { filterViolations, formatViolationSummary } = yield* Effect.promise(\n () => import(\"../core/accessibility-audit.js\"),\n );\n\n const axeContext: Record<string, string[][]> = {};\n if (options.targetSelector) {\n axeContext[\"include\"] = [[options.targetSelector]];\n }\n if (options.excludeSelectors && options.excludeSelectors.length > 0) {\n axeContext[\"exclude\"] = options.excludeSelectors.map((s) => [s]);\n }\n const serializedContext =\n Object.keys(axeContext).length > 0 ? JSON.stringify(axeContext) : \"document\";\n\n const axeOptions: Record<string, unknown> = {};\n if (options.rules && options.rules.length > 0) {\n const rulesConfig: Record<string, { enabled: boolean }> = {};\n for (const r of options.rules) rulesConfig[r] = { enabled: true };\n axeOptions[\"rules\"] = rulesConfig;\n }\n\n // Inject axe-core and run\n const script = `\n (function() {\n ${axeSource}\n return axe.run(${serializedContext}, ${JSON.stringify(axeOptions)});\n })()\n `;\n\n type AxeResult = {\n violations: Array<{\n id: string;\n impact: string;\n description: string;\n helpUrl: string;\n tags: string[];\n nodes: Array<{\n target: string[];\n html: string;\n failureSummary: string;\n }>;\n }>;\n };\n\n const axeResult = yield* driver.evaluate<AxeResult>(script);\n\n const violations = axeResult.violations.map((v) => ({\n ruleId: v.id,\n severity: (v.impact ?? \"minor\") as \"critical\" | \"serious\" | \"moderate\" | \"minor\",\n description: v.description,\n helpUrl: v.helpUrl,\n wcagCriteria: v.tags.filter((t) => t.startsWith(\"wcag\")),\n elements: v.nodes.map((n) => ({\n selector: n.target.join(\", \"),\n html: n.html,\n failureSummary: n.failureSummary,\n })),\n }));\n\n const minSeverity = options.severity ?? \"serious\";\n const filtered = filterViolations(violations, minSeverity);\n\n if (filtered.length > 0) {\n const summary = formatViolationSummary(filtered);\n return yield* new DriverError({ message: summary });\n }\n }),\n });\n\n return {\n tap: (\n selector: ExtendedSelector,\n opts?: WaitOptions,\n ): Effect.Effect<void, ElementNotFoundError | WaitTimeoutError | DriverError> =>\n Effect.gen(function* () {\n const element = yield* waitForActionElement(\n driver,\n selector,\n parse,\n { ...defaults, ...opts },\n cache,\n );\n const { x, y } = centerOf(element);\n yield* driver.tapAtCoordinate(x, y);\n yield* afterMutation();\n }),\n\n tapXY: (x: number, y: number): Effect.Effect<void, DriverError> =>\n Effect.gen(function* () {\n yield* driver.tapAtCoordinate(x, y);\n yield* afterMutation();\n }),\n\n doubleTap: (\n selector: ExtendedSelector,\n opts?: WaitOptions,\n ): Effect.Effect<void, ElementNotFoundError | WaitTimeoutError | DriverError> =>\n Effect.gen(function* () {\n const element = yield* waitForActionElement(\n driver,\n selector,\n parse,\n { ...defaults, ...opts },\n cache,\n );\n const { x, y } = centerOf(element);\n yield* driver.tapAtCoordinate(x, y);\n yield* Effect.promise(() => new Promise((r) => setTimeout(r, 200)));\n yield* driver.tapAtCoordinate(x, y);\n yield* afterMutation();\n }),\n\n longPress: (\n selector: ExtendedSelector,\n duration: number = 1000,\n opts?: WaitOptions,\n ): Effect.Effect<void, ElementNotFoundError | WaitTimeoutError | DriverError> =>\n Effect.gen(function* () {\n const element = yield* waitForActionElement(\n driver,\n selector,\n parse,\n { ...defaults, ...opts },\n cache,\n );\n const { x, y } = centerOf(element);\n yield* driver.longPressAtCoordinate(x, y, duration);\n yield* afterMutation();\n }),\n\n longPressXY: (\n x: number,\n y: number,\n duration: number = 1000,\n ): Effect.Effect<void, DriverError> =>\n Effect.gen(function* () {\n yield* driver.longPressAtCoordinate(x, y, duration);\n yield* afterMutation();\n }),\n\n inputText: (text: string): Effect.Effect<void, DriverError> =>\n Effect.gen(function* () {\n const delay = config.typingDelay;\n if (delay && delay > 0) {\n for (const segment of splitGraphemes(text)) {\n yield* driver.inputText(segment);\n yield* Effect.sleep(Duration.millis(delay));\n }\n } else {\n yield* driver.inputText(text);\n }\n yield* afterMutation();\n }),\n\n pressKey: (key: string): Effect.Effect<void, DriverError> =>\n Effect.gen(function* () {\n yield* driver.pressKey(key);\n cache.invalidate();\n }),\n\n hideKeyboard: (): Effect.Effect<void, DriverError> =>\n Effect.gen(function* () {\n yield* driver.hideKeyboard();\n cache.invalidate();\n }),\n\n dismissKeyboard: (opts?: DismissKeyboardOptions): Effect.Effect<void, DriverError> =>\n Effect.gen(function* () {\n const strategy = opts?.strategy ?? DEFAULT_DISMISS_KEYBOARD_STRATEGY;\n if (strategy === \"driver\") {\n return yield* dismissKeyboardWithDriver();\n }\n if (strategy === \"back\") {\n return yield* dismissKeyboardWithBack();\n }\n\n const platform = (yield* driver.getDeviceInfo()).platform;\n const hideKeyboardResult = yield* Effect.either(driver.hideKeyboard());\n if (hideKeyboardResult._tag === \"Right\") {\n yield* afterMutation();\n return;\n }\n\n if (platform === \"android\") {\n const backResult = yield* Effect.either(driver.back());\n if (backResult._tag === \"Right\") {\n yield* afterMutation();\n return;\n }\n\n return yield* new DriverError({\n message: `dismissKeyboard() failed with strategy \"auto\" on android. hideKeyboard(): ${hideKeyboardResult.left.message}. back(): ${backResult.left.message}`,\n });\n }\n\n return yield* new DriverError({\n message: `dismissKeyboard() failed with strategy \"auto\" on ${platform}. hideKeyboard(): ${hideKeyboardResult.left.message}`,\n });\n }),\n\n swipe: (direction: Direction, opts?: { duration?: number }): Effect.Effect<void, DriverError> =>\n swipeEffect(direction, opts),\n\n scroll: (direction: Direction): Effect.Effect<void, DriverError> => scrollEffect(direction),\n\n scrollUntilVisible: (\n selector: ExtendedSelector,\n opts?: ScrollUntilVisibleOptions,\n ): Effect.Effect<void, ElementNotFoundError | DriverError> =>\n Effect.gen(function* () {\n const searchDirection = opts?.direction ?? DEFAULT_SCROLL_SEARCH_DIRECTION;\n const gestureDirection = gestureDirectionForSearch(searchDirection);\n const maxScrolls = Math.max(0, opts?.maxScrolls ?? DEFAULT_MAX_SCROLLS);\n const totalTimeout = opts?.timeout ?? defaults?.timeout ?? 5000;\n const deadline = Date.now() + totalTimeout;\n let scrollCount = 0;\n\n while (scrollCount <= maxScrolls && Date.now() <= deadline) {\n const found = yield* probeVisible(selector, opts);\n if (found) {\n return;\n }\n\n if (scrollCount === maxScrolls) {\n break;\n }\n\n yield* scrollEffect(gestureDirection);\n scrollCount += 1;\n }\n\n return yield* new ElementNotFoundError({\n message: `Element not found after ${scrollCount} scroll(s) toward ${searchDirection} — selector: ${formatSelector(selector)}`,\n selector,\n timeoutMs: totalTimeout,\n });\n }),\n\n backUntilVisible: (\n selector: ExtendedSelector,\n opts?: BackUntilVisibleOptions,\n ): Effect.Effect<void, ElementNotFoundError | DriverError> =>\n Effect.gen(function* () {\n const maxBacks = Math.max(0, opts?.maxBacks ?? DEFAULT_MAX_BACKS);\n const totalTimeout = opts?.timeout ?? defaults?.timeout ?? 5000;\n const deadline = Date.now() + totalTimeout;\n let backCount = 0;\n\n while (backCount <= maxBacks && Date.now() <= deadline) {\n const found = yield* probeVisible(selector, opts);\n if (found) {\n return;\n }\n\n if (backCount === maxBacks) {\n break;\n }\n\n const backResult = yield* Effect.either(driver.back());\n if (backResult._tag === \"Left\") {\n return yield* new DriverError({\n message: `backUntilVisible() failed on back attempt ${backCount + 1}: ${backResult.left.message}`,\n });\n }\n\n yield* afterMutation();\n backCount += 1;\n }\n\n return yield* new ElementNotFoundError({\n message: `Element not found after ${backCount} back action(s) — selector: ${formatSelector(selector)}. If this screen uses an in-app close or back control, tap that element instead of relying on system back.`,\n selector,\n timeoutMs: totalTimeout,\n });\n }),\n\n pinch: (\n selector: ExtendedSelector,\n opts?: { scale?: number; duration?: number } & WaitOptions,\n ): Effect.Effect<void, ElementNotFoundError | WaitTimeoutError | DriverError> =>\n scaleGesture(\"pinch\", selector, opts),\n\n zoom: (\n selector: ExtendedSelector,\n opts?: { scale?: number; duration?: number } & WaitOptions,\n ): Effect.Effect<void, ElementNotFoundError | WaitTimeoutError | DriverError> =>\n scaleGesture(\"zoom\", selector, opts),\n\n multiTouch: (\n sequences: import(\"../drivers/raw-driver.js\").TouchSequence[],\n ): Effect.Effect<void, DriverError> =>\n Effect.gen(function* () {\n if (!driver.multiTouch) {\n return yield* new DriverError({\n message: \"multiTouch() is only supported on mobile platforms (Android/iOS)\",\n });\n }\n yield* driver.multiTouch(sequences);\n yield* afterMutation();\n }),\n\n ...createAssertions(),\n };\n}\n","export function splitGraphemes(text: string): string[] {\n if (text.length === 0) {\n return [];\n }\n\n const Segmenter = globalThis.Intl?.Segmenter;\n if (!Segmenter) {\n return Array.from(text);\n }\n\n return Array.from(\n new Segmenter(undefined, { granularity: \"grapheme\" }).segment(text),\n (part) => part.segment,\n );\n}\n","import { Duration, Effect } from \"effect\";\nimport { type DriverError, ElementNotFoundError, WaitTimeoutError } from \"../errors.js\";\nimport type { Element } from \"../schemas/element.js\";\nimport type { ExtendedSelector } from \"../schemas/selector.js\";\nimport type { RawDriverService } from \"../drivers/raw-driver.js\";\nimport {\n findActionElementExtended,\n findElementExtended,\n formatSelector,\n} from \"./element-matcher.js\";\nimport type { HierarchyCache } from \"./hierarchy-cache.js\";\nimport { diagnoseElementNotFound, formatDiagnostic } from \"./diagnostics.js\";\n\nexport interface WaitOptions {\n timeout?: number; // default 5000ms\n pollInterval?: number; // default 200ms\n settleTimeout?: number; // default 0ms — wait for hierarchy to stabilize before returning\n /** Starting poll interval for adaptive polling. Default: 50ms. Set equal to pollInterval to disable adaptive backoff. */\n initialPollInterval?: number;\n}\n\nconst DEFAULT_TIMEOUT = 5000;\nconst DEFAULT_POLL_INTERVAL = 200;\nconst DEFAULT_INITIAL_POLL_INTERVAL = 50;\nconst DEFAULT_SETTLE_TIMEOUT = 0;\n\n/** Parse a raw hierarchy string (JSON from web, XML from native — caller provides parser) */\ntype HierarchyParser = (raw: string) => Element;\n\n/** Get the hierarchy root — uses cache if provided, otherwise dumps fresh. */\n// Generic on `<T, R>` so the wait helpers can be called from typed flow code\n// without widening errors. None of the body actually uses T/R — we only need\n// the parameters so `RawDriverService<T, R>` passes assignability checks.\nfunction getHierarchy<T extends string = string, R extends string = string>(\n driver: RawDriverService<T, R>,\n parse: HierarchyParser,\n cache?: HierarchyCache,\n): Effect.Effect<Element, DriverError> {\n if (cache) return cache.get(driver as unknown as RawDriverService, parse);\n return Effect.gen(function* () {\n const raw = yield* driver.dumpHierarchy();\n return parse(raw);\n });\n}\n\n/** Calculate next poll interval with linear backoff from initial to max. */\nfunction nextInterval(elapsed: number, timeout: number, initial: number, max: number): number {\n if (initial >= max) return max;\n // Linear ramp from initial to max over the first half of the timeout\n const rampDuration = timeout / 2;\n const progress = Math.min(elapsed / rampDuration, 1);\n return Math.round(initial + (max - initial) * progress);\n}\n\n/** Poll until an element matching selector is found */\nfunction waitForResolvedElement<T extends string = string, R extends string = string>(\n driver: RawDriverService<T, R>,\n selector: ExtendedSelector<T>,\n parse: HierarchyParser,\n resolveElement: (root: Element, selector: ExtendedSelector<T>) => Element | undefined,\n opts?: WaitOptions,\n cache?: HierarchyCache,\n): Effect.Effect<Element, ElementNotFoundError | WaitTimeoutError | DriverError> {\n const timeout = opts?.timeout ?? DEFAULT_TIMEOUT;\n const pollInterval = opts?.pollInterval ?? DEFAULT_POLL_INTERVAL;\n const initialPollInterval = opts?.initialPollInterval ?? DEFAULT_INITIAL_POLL_INTERVAL;\n const settleTimeout = opts?.settleTimeout ?? DEFAULT_SETTLE_TIMEOUT;\n\n return Effect.gen(function* () {\n const start = Date.now();\n // First iteration: use cache if available (element may already be visible)\n let isFirstPoll = true;\n while (Date.now() - start < timeout) {\n // After the first poll, invalidate cache so subsequent polls get fresh data\n if (!isFirstPoll && cache) cache.invalidate();\n isFirstPoll = false;\n\n const root = yield* getHierarchy(driver, parse, cache);\n const element = resolveElement(root, selector);\n if (element) {\n if (settleTimeout > 0) {\n // Wait, then re-check with fresh data to ensure the element is stable\n yield* Effect.sleep(Duration.millis(settleTimeout));\n if (cache) cache.invalidate();\n const settledRoot = yield* getHierarchy(driver, parse, cache);\n const settledElement = resolveElement(settledRoot, selector);\n if (settledElement) return settledElement;\n // Element disappeared during settle — keep polling\n } else {\n return element;\n }\n }\n const elapsed = Date.now() - start;\n const interval = nextInterval(elapsed, timeout, initialPollInterval, pollInterval);\n yield* Effect.sleep(Duration.millis(interval));\n }\n // Capture diagnostic info from the last hierarchy\n if (cache) cache.invalidate();\n const diagRoot = yield* getHierarchy(driver, parse, cache);\n const diagnostic = diagnoseElementNotFound(diagRoot, selector);\n const diagMessage = formatDiagnostic(diagnostic);\n\n return yield* new ElementNotFoundError({\n message: `Element not found within ${timeout}ms — selector: ${formatSelector(selector)}\\n${diagMessage}`,\n selector,\n timeoutMs: timeout,\n });\n });\n}\n\n/** Poll until an element matching selector is found. */\nexport function waitForElement<T extends string = string, R extends string = string>(\n driver: RawDriverService<T, R>,\n selector: ExtendedSelector<T>,\n parse: HierarchyParser,\n opts?: WaitOptions,\n cache?: HierarchyCache,\n): Effect.Effect<Element, ElementNotFoundError | WaitTimeoutError | DriverError> {\n return waitForResolvedElement(driver, selector, parse, findElementExtended, opts, cache);\n}\n\n/** Poll until an actionable element matching selector is found. */\nexport function waitForActionElement<T extends string = string, R extends string = string>(\n driver: RawDriverService<T, R>,\n selector: ExtendedSelector<T>,\n parse: HierarchyParser,\n opts?: WaitOptions,\n cache?: HierarchyCache,\n): Effect.Effect<Element, ElementNotFoundError | WaitTimeoutError | DriverError> {\n return waitForResolvedElement(driver, selector, parse, findActionElementExtended, opts, cache);\n}\n\n/** Poll until element matching selector is NOT visible */\nexport function waitForNotVisible<T extends string = string, R extends string = string>(\n driver: RawDriverService<T, R>,\n selector: ExtendedSelector<T>,\n parse: HierarchyParser,\n opts?: WaitOptions,\n cache?: HierarchyCache,\n): Effect.Effect<void, WaitTimeoutError | DriverError> {\n const timeout = opts?.timeout ?? DEFAULT_TIMEOUT;\n const pollInterval = opts?.pollInterval ?? DEFAULT_POLL_INTERVAL;\n const initialPollInterval = opts?.initialPollInterval ?? DEFAULT_INITIAL_POLL_INTERVAL;\n\n return Effect.gen(function* () {\n const start = Date.now();\n let isFirstPoll = true;\n while (Date.now() - start < timeout) {\n if (!isFirstPoll && cache) cache.invalidate();\n isFirstPoll = false;\n\n const root = yield* getHierarchy(driver, parse, cache);\n const element = findElementExtended(root, selector);\n if (!element) return;\n const elapsed = Date.now() - start;\n const interval = nextInterval(elapsed, timeout, initialPollInterval, pollInterval);\n yield* Effect.sleep(Duration.millis(interval));\n }\n return yield* new WaitTimeoutError({\n message: `Element still visible after ${timeout}ms — selector: ${formatSelector(selector)}`,\n selector,\n timeoutMs: timeout,\n });\n });\n}\n","import type { Element } from \"../schemas/element.js\";\nimport type { ExtendedSelector } from \"../schemas/selector.js\";\nimport { flattenElements, matchesSelector } from \"./element-matcher.js\";\nimport { isRelativeSelector } from \"../schemas/selector.js\";\n\nexport interface DiagnosticResult {\n /** Why the element wasn't found */\n reason: \"not-found\" | \"not-visible\" | \"not-interactive\" | \"off-screen\";\n /** Suggested similar selectors */\n suggestions: string[];\n /** Total elements in the tree */\n totalElements: number;\n}\n\n/** Analyze why an element wasn't found and suggest alternatives */\nexport function diagnoseElementNotFound(\n root: Element,\n selector: ExtendedSelector,\n): DiagnosticResult {\n const allElements = flattenElements(root);\n const totalElements = allElements.length;\n const suggestions: string[] = [];\n\n // Extract the simple selector for matching\n const simpleSelector = isRelativeSelector(selector) ? selector.selector : selector;\n\n // 1. Check if element matches but is not visible\n const matchingButHidden = allElements.filter(\n (el) => matchesSelector(el, simpleSelector) && el.visible === false,\n );\n if (matchingButHidden.length > 0) {\n return {\n reason: \"not-visible\",\n suggestions: [\n `Element matches selector but has visible=false (${matchingButHidden.length} match(es))`,\n ],\n totalElements,\n };\n }\n\n // 2. Check if element matches but is off-screen\n const matchingButOffScreen = allElements.filter(\n (el) =>\n matchesSelector(el, simpleSelector) &&\n el.visible !== false &&\n (el.bounds.width <= 0 ||\n el.bounds.height <= 0 ||\n el.bounds.x + el.bounds.width / 2 < 0 ||\n el.bounds.y + el.bounds.height / 2 < 0),\n );\n if (matchingButOffScreen.length > 0) {\n return {\n reason: \"off-screen\",\n suggestions: [\n `Element matches selector but is off-screen or has zero size (${matchingButOffScreen.length} match(es))`,\n ],\n totalElements,\n };\n }\n\n // 3. Check if element matches but is not interactive (enabled=false)\n const matchingButDisabled = allElements.filter(\n (el) => matchesSelector(el, simpleSelector) && el.visible !== false && el.enabled === false,\n );\n if (matchingButDisabled.length > 0) {\n return {\n reason: \"not-interactive\",\n suggestions: [`Element matches selector but is disabled (enabled=false)`],\n totalElements,\n };\n }\n\n // 4. Suggest similar selectors (fuzzy matching for testID and text)\n if (typeof simpleSelector === \"string\") {\n // Text selector — find elements with similar text\n const similar = findSimilarByText(allElements, simpleSelector);\n suggestions.push(...similar);\n } else if (\"testID\" in simpleSelector && simpleSelector.testID) {\n const similar = findSimilarByTestID(allElements, simpleSelector.testID);\n suggestions.push(...similar);\n } else if (\"text\" in simpleSelector && simpleSelector.text) {\n const similar = findSimilarByText(allElements, simpleSelector.text);\n suggestions.push(...similar);\n }\n\n return { reason: \"not-found\", suggestions, totalElements };\n}\n\nfunction findSimilarByTestID(elements: Element[], targetId: string): string[] {\n const lower = targetId.toLowerCase();\n const prefix = lower.slice(0, Math.max(3, Math.floor(lower.length / 2)));\n return elements\n .filter((el) => el.id && el.id.toLowerCase().includes(prefix))\n .slice(0, 3)\n .map((el) => `Did you mean testID \"${el.id}\"?`);\n}\n\nfunction findSimilarByText(elements: Element[], targetText: string): string[] {\n const lower = targetText.toLowerCase();\n const prefix = lower.slice(0, 3);\n return elements\n .filter((el) => {\n if (!el.text) return false;\n const elLower = el.text.toLowerCase();\n // Check if they share a significant substring\n return elLower.includes(prefix) || lower.includes(elLower.slice(0, 3));\n })\n .filter((el) => el.visible !== false)\n .slice(0, 3)\n .map((el) => `Did you mean text \"${el.text}\"?`);\n}\n\n/** Format diagnostic result into a human-readable suggestion string */\nexport function formatDiagnostic(diag: DiagnosticResult): string {\n const parts: string[] = [];\n\n if (diag.reason === \"not-visible\") {\n parts.push(\"Element exists but is not visible.\");\n } else if (diag.reason === \"off-screen\") {\n parts.push(\"Element exists but is off-screen or has zero size. Try scrolling to it.\");\n } else if (diag.reason === \"not-interactive\") {\n parts.push(\"Element exists but is disabled (not interactive).\");\n }\n\n if (diag.suggestions.length > 0) {\n parts.push(...diag.suggestions);\n }\n\n parts.push(`(${diag.totalElements} elements in hierarchy)`);\n\n return parts.join(\"\\n\");\n}\n","import { Effect } from \"effect\";\nimport type { RawDriverService } from \"../drivers/raw-driver.js\";\nimport type { DriverError } from \"../errors.js\";\nimport type { Element } from \"../schemas/element.js\";\n\nexport interface HierarchyCacheConfig {\n /** Max age in ms before the cached hierarchy is considered stale. Default: 100. Set to 0 to disable. */\n hierarchyCacheTtl?: number;\n}\n\nconst DEFAULT_CACHE_TTL = 100;\n\nexport interface HierarchyCache {\n /** Get the hierarchy, using cache if fresh enough. */\n get(\n driver: RawDriverService,\n parse: (raw: string) => Element,\n ): Effect.Effect<Element, DriverError>;\n /** Invalidate the cache (call after mutation actions like tap, type, scroll). */\n invalidate(): void;\n}\n\nexport function createHierarchyCache(config?: HierarchyCacheConfig): HierarchyCache {\n const ttl = config?.hierarchyCacheTtl ?? DEFAULT_CACHE_TTL;\n\n let cachedRoot: Element | undefined;\n let cachedAt = 0;\n\n return {\n get(driver, parse) {\n return Effect.gen(function* () {\n const now = Date.now();\n if (ttl > 0 && cachedRoot && now - cachedAt < ttl) {\n return cachedRoot;\n }\n const raw = yield* driver.dumpHierarchy();\n const root = parse(raw);\n if (ttl > 0) {\n cachedRoot = root;\n cachedAt = Date.now();\n }\n return root;\n });\n },\n invalidate() {\n cachedRoot = undefined;\n cachedAt = 0;\n },\n };\n}\n","import { DriverError } from \"../errors.js\";\nimport type { StorybookConfig, StorybookValue } from \"../schemas/config.js\";\n\nexport interface StorybookOpenOptions {\n /** Override the Storybook base URL for this call. */\n baseUrl?: string;\n /** Storybook view mode. Defaults to \"story\". */\n viewMode?: \"story\" | \"docs\";\n /** Story args encoded into the Storybook iframe query string. */\n args?: Record<string, StorybookValue>;\n /** Story globals encoded into the Storybook iframe query string. */\n globals?: Record<string, StorybookValue>;\n}\n\ninterface StorybookRuntimeOptions {\n appBaseUrl?: string;\n storybook?: StorybookConfig;\n}\n\nfunction assertSafeStorybookToken(\n group: \"args\" | \"globals\",\n key: string,\n value: StorybookValue,\n): void {\n if (/[;:=]/.test(key)) {\n throw new DriverError({\n message: `openStory() ${group} key \"${key}\" contains unsupported Storybook query characters (;, :, =).`,\n });\n }\n\n if (typeof value === \"string\" && /[;:]/.test(value)) {\n throw new DriverError({\n message: `openStory() ${group}.${key} contains unsupported Storybook query characters (; or :).`,\n });\n }\n}\n\nfunction encodeStorybookValue(value: StorybookValue): string {\n if (value === null) {\n return \"!null\";\n }\n\n return String(value);\n}\n\nfunction encodeStorybookEntries(\n group: \"args\" | \"globals\",\n entries: Record<string, StorybookValue> | undefined,\n): string | undefined {\n if (!entries) {\n return undefined;\n }\n\n const pairs = Object.entries(entries);\n if (pairs.length === 0) {\n return undefined;\n }\n\n return pairs\n .map(([key, value]) => {\n assertSafeStorybookToken(group, key, value);\n return `${key}:${encodeStorybookValue(value)}`;\n })\n .join(\";\");\n}\n\nexport function buildStorybookUrl(\n storyId: string,\n options: StorybookOpenOptions | undefined,\n runtime: StorybookRuntimeOptions,\n): string {\n const trimmedStoryId = storyId.trim();\n if (!trimmedStoryId) {\n throw new DriverError({ message: \"openStory() requires a non-empty Storybook story ID.\" });\n }\n\n const baseUrl = options?.baseUrl ?? runtime.storybook?.url ?? runtime.appBaseUrl;\n if (!baseUrl) {\n throw new DriverError({\n message:\n \"openStory() requires apps.web.url, execution.web.storybook.url, or options.baseUrl.\",\n });\n }\n\n let url: URL;\n try {\n url = new URL(runtime.storybook?.iframePath ?? \"/iframe.html\", baseUrl);\n } catch (error) {\n throw new DriverError({\n message: `openStory() could not build a Storybook URL from \"${baseUrl}\": ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n\n url.searchParams.set(\"id\", trimmedStoryId);\n url.searchParams.set(\"viewMode\", options?.viewMode ?? \"story\");\n\n const args = encodeStorybookEntries(\"args\", options?.args);\n if (args) {\n url.searchParams.set(\"args\", args);\n }\n\n const globals = encodeStorybookEntries(\"globals\", options?.globals);\n if (globals) {\n url.searchParams.set(\"globals\", globals);\n }\n\n return url.toString();\n}\n","import type { Element } from \"../schemas/element.js\";\n\n/**\n * Raw JSON node shape emitted by the page.evaluate walk in playwright.ts.\n */\ninterface RawWebNode {\n tag?: string;\n id?: string;\n text?: string;\n value?: string;\n accessibilityLabel?: string;\n role?: string;\n bounds: { x: number; y: number; width: number; height: number };\n enabled?: boolean;\n visible?: boolean;\n clickable?: boolean;\n attributes?: Record<string, string>;\n children?: RawWebNode[];\n}\n\nfunction rawNodeToElement(node: RawWebNode): Element {\n const children =\n node.children && node.children.length > 0 ? node.children.map(rawNodeToElement) : undefined;\n\n return {\n ...(node.id !== undefined ? { id: node.id } : {}),\n ...(node.text !== undefined ? { text: node.text } : {}),\n ...(node.value !== undefined ? { value: node.value } : {}),\n ...(node.accessibilityLabel !== undefined\n ? { accessibilityLabel: node.accessibilityLabel }\n : {}),\n // Use role as elementType when present, otherwise fall back to HTML tag name\n ...(node.role !== undefined\n ? { elementType: node.role }\n : node.tag !== undefined\n ? { elementType: node.tag }\n : {}),\n bounds: {\n x: node.bounds.x,\n y: node.bounds.y,\n width: node.bounds.width,\n height: node.bounds.height,\n },\n ...(node.enabled !== undefined ? { enabled: node.enabled } : {}),\n ...(node.visible !== undefined ? { visible: node.visible } : {}),\n ...(node.clickable !== undefined ? { clickable: node.clickable } : {}),\n ...(node.attributes !== undefined ? { attributes: node.attributes } : {}),\n ...(children !== undefined ? { children } : {}),\n };\n}\n\n/**\n * Parses the JSON string produced by Playwright's dumpHierarchy into the unified Element tree.\n *\n * The JSON shape matches what page.evaluate produces in playwright.ts:\n * - `id` comes from data-testid / testID attributes\n * - `accessibilityLabel` comes from aria-label\n * - `role` is preferred over `tag` as the elementType\n * - `bounds` is a {x, y, width, height} object from getBoundingClientRect\n * - `enabled`, `visible`, `clickable` are booleans\n *\n * @throws SyntaxError if the string is not valid JSON\n * @throws Error if the JSON does not have a `bounds` field at the root\n */\nexport function parseWebHierarchy(json: string): Element {\n const raw = JSON.parse(json) as RawWebNode;\n return rawNodeToElement(raw);\n}\n","import { Context, Effect } from \"effect\";\nimport type { DriverError } from \"../errors.js\";\nimport type { DeviceInfo } from \"../schemas/device.js\";\nimport type { Selector } from \"../schemas/selector.js\";\n\nexport type RawHierarchy = string; // Raw XML (Android/iOS) or JSON (web) — parsed by platform-specific parsers\n\n/**\n * Per-launch device state overrides (language/locale/timeZone) applied at app\n * launch time. Maps to the `appium:language` / `appium:locale` /\n * `appium:timeZone` capabilities on Appium providers; used to drive Expo /\n * React Native localization for the duration of a flow.\n */\nexport interface DeviceStateConfig {\n language?: string;\n locale?: string;\n timeZone?: string;\n}\n\nexport interface LaunchOptions<R extends string = string> {\n clearState?: boolean;\n clearKeychain?: boolean;\n /** Native deep link URL (e.g. `spana://playground`). `R` lets projects type it. */\n deepLink?: R;\n launchArguments?: Record<string, unknown>;\n deviceState?: DeviceStateConfig;\n}\n\nexport type BrowserRouteMatcher = string | RegExp;\n\nexport interface BrowserMockResponse {\n status?: number;\n body?: string;\n json?: unknown;\n headers?: Record<string, string>;\n contentType?: string;\n}\n\nexport type NetworkProfile = \"wifi\" | \"4g\" | \"3g\" | \"2g\" | \"edge\" | \"offline\";\n\nexport interface NetworkConditions {\n profile?: NetworkProfile;\n offline?: boolean;\n latencyMs?: number;\n downloadThroughputKbps?: number;\n uploadThroughputKbps?: number;\n}\n\n/** @deprecated Use `NetworkConditions` instead. */\nexport type BrowserNetworkConditions = NetworkConditions;\n\nexport interface BrowserConsoleLogLocation {\n url?: string;\n lineNumber?: number;\n columnNumber?: number;\n}\n\nexport interface BrowserConsoleLog {\n type: string;\n text: string;\n location?: BrowserConsoleLogLocation;\n}\n\nexport interface BrowserJSError {\n name?: string;\n message: string;\n stack?: string;\n}\n\nexport interface BrowserHARHeader {\n name: string;\n value: string;\n}\n\nexport interface BrowserHAREntry {\n pageref: string;\n startedDateTime: string;\n time: number;\n request: {\n method: string;\n url: string;\n httpVersion: string;\n headers: BrowserHARHeader[];\n queryString: BrowserHARHeader[];\n headersSize: number;\n bodySize: number;\n postData?: {\n mimeType: string;\n text?: string;\n };\n };\n response: {\n status: number;\n statusText: string;\n httpVersion: string;\n headers: BrowserHARHeader[];\n redirectURL: string;\n headersSize: number;\n bodySize: number;\n content: {\n size: number;\n mimeType: string;\n };\n };\n cache: Record<string, never>;\n timings: {\n blocked: number;\n dns: number;\n connect: number;\n ssl: number;\n send: number;\n wait: number;\n receive: number;\n };\n serverIPAddress?: string;\n _resourceType?: string;\n _failureText?: string;\n}\n\nexport interface BrowserHARPage {\n id: string;\n title: string;\n startedDateTime: string;\n pageTimings: {\n onContentLoad: number;\n onLoad: number;\n };\n}\n\nexport interface BrowserHAR {\n log: {\n version: \"1.2\";\n creator: {\n name: \"spana\";\n version: string;\n };\n browser: {\n name: string;\n };\n pages: BrowserHARPage[];\n entries: BrowserHAREntry[];\n };\n}\n\nexport type TouchAction =\n | { type: \"move\"; x: number; y: number; duration?: number }\n | { type: \"down\" }\n | { type: \"up\" }\n | { type: \"pause\"; duration: number };\n\nexport interface TouchSequence {\n id: number;\n actions: TouchAction[];\n}\n\nexport interface RawDriverService<_T extends string = string, R extends string = string> {\n // Flow lifecycle\n readonly beginFlow?: (flowName: string) => Effect.Effect<void, DriverError>;\n readonly getDriverLogs?: () => Effect.Effect<string[], DriverError>;\n\n // Hierarchy\n readonly dumpHierarchy: () => Effect.Effect<RawHierarchy, DriverError>;\n\n // Coordinate-level actions\n readonly tapAtCoordinate: (x: number, y: number) => Effect.Effect<void, DriverError>;\n readonly doubleTapAtCoordinate: (x: number, y: number) => Effect.Effect<void, DriverError>;\n readonly longPressAtCoordinate: (\n x: number,\n y: number,\n duration: number,\n ) => Effect.Effect<void, DriverError>;\n readonly swipe: (\n startX: number,\n startY: number,\n endX: number,\n endY: number,\n duration: number,\n ) => Effect.Effect<void, DriverError>;\n\n // Multi-touch gestures (mobile only)\n readonly pinch?: (\n cx: number,\n cy: number,\n scale: number,\n duration: number,\n ) => Effect.Effect<void, DriverError>;\n readonly zoom?: (\n cx: number,\n cy: number,\n scale: number,\n duration: number,\n ) => Effect.Effect<void, DriverError>;\n readonly multiTouch?: (sequences: TouchSequence[]) => Effect.Effect<void, DriverError>;\n\n // Text input\n readonly inputText: (text: string) => Effect.Effect<void, DriverError>;\n readonly pressKey: (key: string) => Effect.Effect<void, DriverError>;\n readonly hideKeyboard: () => Effect.Effect<void, DriverError>;\n\n // Queries\n readonly takeScreenshot: () => Effect.Effect<Uint8Array, DriverError>;\n readonly getDeviceInfo: () => Effect.Effect<DeviceInfo, DriverError>;\n\n // App lifecycle\n readonly launchApp: (\n bundleId: string,\n opts?: LaunchOptions<R>,\n ) => Effect.Effect<void, DriverError>;\n readonly stopApp: (bundleId: string) => Effect.Effect<void, DriverError>;\n readonly killApp: (bundleId: string) => Effect.Effect<void, DriverError>;\n readonly clearAppState: (bundleId: string) => Effect.Effect<void, DriverError>;\n\n // Navigation\n readonly openLink: (url: string) => Effect.Effect<void, DriverError>;\n readonly back: () => Effect.Effect<void, DriverError>;\n\n // Scripting\n readonly evaluate: <T = unknown>(\n script: string | ((...args: unknown[]) => T),\n ...args: unknown[]\n ) => Effect.Effect<T, DriverError>;\n\n // WebView / hybrid context switching (mobile only)\n readonly getContexts?: () => Effect.Effect<string[], DriverError>;\n readonly getCurrentContext?: () => Effect.Effect<string, DriverError>;\n readonly setContext?: (contextId: string) => Effect.Effect<void, DriverError>;\n\n // Network & browser state helpers\n readonly mockNetwork?: (\n matcher: BrowserRouteMatcher,\n response: BrowserMockResponse,\n ) => Effect.Effect<void, DriverError>;\n readonly blockNetwork?: (matcher: BrowserRouteMatcher) => Effect.Effect<void, DriverError>;\n readonly clearNetworkMocks?: () => Effect.Effect<void, DriverError>;\n readonly setNetworkConditions?: (\n conditions: NetworkConditions,\n ) => Effect.Effect<void, DriverError>;\n readonly saveCookies?: (path: string) => Effect.Effect<void, DriverError>;\n readonly loadCookies?: (path: string) => Effect.Effect<void, DriverError>;\n readonly saveAuthState?: (path: string) => Effect.Effect<void, DriverError>;\n readonly loadAuthState?: (path: string) => Effect.Effect<void, DriverError>;\n readonly downloadFile?: (path: string) => Effect.Effect<void, DriverError>;\n readonly uploadFile?: (selector: Selector, path: string) => Effect.Effect<void, DriverError>;\n readonly newTab?: (url?: string) => Effect.Effect<string, DriverError>;\n readonly switchToTab?: (index: number) => Effect.Effect<void, DriverError>;\n readonly closeTab?: () => Effect.Effect<void, DriverError>;\n readonly getTabIds?: () => Effect.Effect<string[], DriverError>;\n readonly getConsoleLogs?: () => Effect.Effect<BrowserConsoleLog[], DriverError>;\n readonly getJSErrors?: () => Effect.Effect<BrowserJSError[], DriverError>;\n readonly getHAR?: () => Effect.Effect<BrowserHAR, DriverError>;\n}\n\n// Non-generic Context.Tag — the Effect runtime always resolves to the default\n// string-string instantiation; type parameters only matter at the call-site.\nexport class RawDriver extends Context.Tag(\"RawDriver\")<RawDriver, RawDriverService>() {}\n\ntype DriverEffect<A> = Effect.Effect<A, DriverError>;\n\nfunction appendDriverLog(logs: string[], message: string): void {\n logs.push(`[${new Date().toISOString()}] ${message}`);\n}\n\nfunction wrapLoggedMethod<Args extends unknown[], A>(\n logs: string[],\n methodName: string,\n fn: (...args: Args) => DriverEffect<A>,\n): (...args: Args) => DriverEffect<A> {\n return (...args: Args) => {\n const startedAt = Date.now();\n appendDriverLog(logs, `${methodName} started`);\n\n return fn(...args).pipe(\n Effect.tap(() =>\n Effect.sync(() => {\n appendDriverLog(logs, `${methodName} succeeded (${Date.now() - startedAt}ms)`);\n }),\n ),\n Effect.tapError((error) =>\n Effect.sync(() => {\n appendDriverLog(\n logs,\n `${methodName} failed (${Date.now() - startedAt}ms): ${error.message}`,\n );\n }),\n ),\n );\n };\n}\n\nfunction wrapOptionalMethod<Args extends unknown[], A>(\n logs: string[],\n methodName: string,\n fn: ((...args: Args) => DriverEffect<A>) | undefined,\n): ((...args: Args) => DriverEffect<A>) | undefined {\n return fn ? wrapLoggedMethod(logs, methodName, fn) : undefined;\n}\n\nexport function withBufferedDriverLogs(driver: RawDriverService): RawDriverService {\n const logs: string[] = [];\n\n return {\n ...driver,\n beginFlow: (flowName: string) => {\n logs.length = 0;\n appendDriverLog(logs, `beginFlow ${flowName}`);\n\n const startedAt = Date.now();\n const effect = driver.beginFlow ? driver.beginFlow(flowName) : Effect.void;\n\n return effect.pipe(\n Effect.tap(() =>\n Effect.sync(() => {\n appendDriverLog(logs, `beginFlow ready (${Date.now() - startedAt}ms)`);\n }),\n ),\n Effect.tapError((error) =>\n Effect.sync(() => {\n appendDriverLog(\n logs,\n `beginFlow failed (${Date.now() - startedAt}ms): ${error.message}`,\n );\n }),\n ),\n );\n },\n getDriverLogs: () => Effect.succeed([...logs]),\n dumpHierarchy: wrapLoggedMethod(logs, \"dumpHierarchy\", driver.dumpHierarchy),\n tapAtCoordinate: wrapLoggedMethod(logs, \"tapAtCoordinate\", driver.tapAtCoordinate),\n doubleTapAtCoordinate: wrapLoggedMethod(\n logs,\n \"doubleTapAtCoordinate\",\n driver.doubleTapAtCoordinate,\n ),\n longPressAtCoordinate: wrapLoggedMethod(\n logs,\n \"longPressAtCoordinate\",\n driver.longPressAtCoordinate,\n ),\n swipe: wrapLoggedMethod(logs, \"swipe\", driver.swipe),\n pinch: wrapOptionalMethod(logs, \"pinch\", driver.pinch),\n zoom: wrapOptionalMethod(logs, \"zoom\", driver.zoom),\n multiTouch: wrapOptionalMethod(logs, \"multiTouch\", driver.multiTouch),\n inputText: wrapLoggedMethod(logs, \"inputText\", driver.inputText),\n pressKey: wrapLoggedMethod(logs, \"pressKey\", driver.pressKey),\n hideKeyboard: wrapLoggedMethod(logs, \"hideKeyboard\", driver.hideKeyboard),\n takeScreenshot: wrapLoggedMethod(logs, \"takeScreenshot\", driver.takeScreenshot),\n getDeviceInfo: wrapLoggedMethod(logs, \"getDeviceInfo\", driver.getDeviceInfo),\n launchApp: wrapLoggedMethod(logs, \"launchApp\", driver.launchApp),\n stopApp: wrapLoggedMethod(logs, \"stopApp\", driver.stopApp),\n killApp: wrapLoggedMethod(logs, \"killApp\", driver.killApp),\n clearAppState: wrapLoggedMethod(logs, \"clearAppState\", driver.clearAppState),\n openLink: wrapLoggedMethod(logs, \"openLink\", driver.openLink),\n back: wrapLoggedMethod(logs, \"back\", driver.back),\n evaluate: wrapLoggedMethod(logs, \"evaluate\", driver.evaluate),\n getContexts: wrapOptionalMethod(logs, \"getContexts\", driver.getContexts),\n getCurrentContext: wrapOptionalMethod(logs, \"getCurrentContext\", driver.getCurrentContext),\n setContext: wrapOptionalMethod(logs, \"setContext\", driver.setContext),\n mockNetwork: wrapOptionalMethod(logs, \"mockNetwork\", driver.mockNetwork),\n blockNetwork: wrapOptionalMethod(logs, \"blockNetwork\", driver.blockNetwork),\n clearNetworkMocks: wrapOptionalMethod(logs, \"clearNetworkMocks\", driver.clearNetworkMocks),\n setNetworkConditions: wrapOptionalMethod(\n logs,\n \"setNetworkConditions\",\n driver.setNetworkConditions,\n ),\n saveCookies: wrapOptionalMethod(logs, \"saveCookies\", driver.saveCookies),\n loadCookies: wrapOptionalMethod(logs, \"loadCookies\", driver.loadCookies),\n saveAuthState: wrapOptionalMethod(logs, \"saveAuthState\", driver.saveAuthState),\n loadAuthState: wrapOptionalMethod(logs, \"loadAuthState\", driver.loadAuthState),\n downloadFile: wrapOptionalMethod(logs, \"downloadFile\", driver.downloadFile),\n uploadFile: wrapOptionalMethod(logs, \"uploadFile\", driver.uploadFile),\n newTab: wrapOptionalMethod(logs, \"newTab\", driver.newTab),\n switchToTab: wrapOptionalMethod(logs, \"switchToTab\", driver.switchToTab),\n closeTab: wrapOptionalMethod(logs, \"closeTab\", driver.closeTab),\n getTabIds: wrapOptionalMethod(logs, \"getTabIds\", driver.getTabIds),\n getConsoleLogs: wrapOptionalMethod(logs, \"getConsoleLogs\", driver.getConsoleLogs),\n getJSErrors: wrapOptionalMethod(logs, \"getJSErrors\", driver.getJSErrors),\n getHAR: wrapOptionalMethod(logs, \"getHAR\", driver.getHAR),\n };\n}\n","import type { Platform } from \"../schemas/selector.js\";\nimport type { DeviceStateConfig, LaunchOptions } from \"./raw-driver.js\";\n\nfunction mergeRecord<T extends object>(base?: T, override?: T): T | undefined {\n if (!base && !override) return undefined;\n return { ...base, ...override } as T;\n}\n\nfunction stringifyLaunchValue(value: unknown): string {\n if (typeof value === \"string\") return value;\n if (typeof value === \"number\" || typeof value === \"boolean\" || value == null) {\n return String(value);\n }\n return JSON.stringify(value);\n}\n\nfunction splitLocale(locale?: string): { language?: string; remainder?: string } {\n if (!locale) return {};\n const [language, ...rest] = locale.split(/[-_]/).filter(Boolean);\n if (!language || rest.length === 0) {\n return {};\n }\n return { language, remainder: rest.join(\"_\") };\n}\n\nfunction resolveAndroidDeviceState(deviceState?: DeviceStateConfig): DeviceStateConfig {\n if (!deviceState) return {};\n const split = splitLocale(deviceState.locale);\n return {\n language: deviceState.language ?? split.language,\n locale: split.remainder ?? deviceState.locale,\n timeZone: deviceState.timeZone,\n };\n}\n\nfunction resolveIOSDeviceState(deviceState?: DeviceStateConfig): DeviceStateConfig {\n if (!deviceState) return {};\n const split = splitLocale(deviceState.locale);\n const language = deviceState.language ?? split.language;\n const locale =\n deviceState.locale && split.remainder && language\n ? `${language}_${split.remainder}`\n : deviceState.locale && !split.remainder && language\n ? `${language}_${deviceState.locale}`\n : deviceState.locale?.replaceAll(\"-\", \"_\");\n\n return {\n language,\n locale,\n timeZone: deviceState.timeZone,\n };\n}\n\nexport function mergeLaunchOptions<R extends string = string>(\n base?: LaunchOptions<R>,\n override?: LaunchOptions<R>,\n): LaunchOptions<R> | undefined {\n if (!base && !override) return undefined;\n\n return {\n ...base,\n ...override,\n launchArguments: mergeRecord(base?.launchArguments, override?.launchArguments),\n deviceState: mergeRecord(base?.deviceState, override?.deviceState),\n };\n}\n\nexport function hasLaunchDeviceState(deviceState?: DeviceStateConfig): boolean {\n return Boolean(deviceState?.language || deviceState?.locale || deviceState?.timeZone);\n}\n\nexport function deviceStateToAppiumCapabilities(\n platform: Extract<Platform, \"android\" | \"ios\">,\n deviceState?: DeviceStateConfig,\n): Record<string, unknown> {\n const normalizedState =\n platform === \"android\"\n ? resolveAndroidDeviceState(deviceState)\n : resolveIOSDeviceState(deviceState);\n if (!normalizedState.language && !normalizedState.locale && !normalizedState.timeZone) return {};\n\n if (platform === \"android\") {\n const hasLanguage = Boolean(normalizedState.language);\n const hasLocale = Boolean(normalizedState.locale);\n if (hasLanguage !== hasLocale) {\n throw new Error(\n \"Appium Android deviceState requires both language and locale when either is provided.\",\n );\n }\n }\n\n const capabilities: Record<string, unknown> = {};\n if (normalizedState.language) {\n capabilities[\"appium:language\"] = normalizedState.language;\n }\n if (normalizedState.locale) {\n capabilities[\"appium:locale\"] = normalizedState.locale;\n }\n if (normalizedState.timeZone) {\n capabilities[platform === \"ios\" ? \"appium:appTimeZone\" : \"appium:timeZone\"] =\n normalizedState.timeZone;\n }\n\n return capabilities;\n}\n\nexport function buildIOSLaunchConfiguration(options?: LaunchOptions):\n | {\n arguments?: string[];\n environment?: Record<string, string>;\n }\n | undefined {\n if (!options) return undefined;\n\n const argumentsList: string[] = [];\n const environment: Record<string, string> = {};\n const normalizedState = resolveIOSDeviceState(options.deviceState);\n\n if (normalizedState.language) {\n argumentsList.push(\"-AppleLanguages\", `(${normalizedState.language})`);\n }\n if (normalizedState.locale) {\n argumentsList.push(\"-AppleLocale\", normalizedState.locale);\n }\n if (options.launchArguments) {\n for (const [key, value] of Object.entries(options.launchArguments)) {\n argumentsList.push(`-${key}`, stringifyLaunchValue(value));\n }\n }\n if (normalizedState.timeZone) {\n environment.TZ = normalizedState.timeZone;\n }\n\n if (argumentsList.length === 0 && Object.keys(environment).length === 0) {\n return undefined;\n }\n\n return {\n arguments: argumentsList.length > 0 ? argumentsList : undefined,\n environment: Object.keys(environment).length > 0 ? environment : undefined,\n };\n}\n"],"mappings":";AAAA,SAAS,cAAc;AAIhB,IAAM,uBAAN,cAAmC,OAAO,YAAkC;AAAA,EACjF;AAAA,EACA;AAAA,IACE,SAAS,OAAO;AAAA,IAChB,UAAU,OAAO;AAAA,IACjB,WAAW,OAAO,SAAS,OAAO,MAAM;AAAA,EAC1C;AACF,EAAE;AAAC;AAEI,IAAM,oBAAN,cAAgC,OAAO,YAA+B;AAAA,EAC3E;AAAA,EACA;AAAA,IACE,SAAS,OAAO;AAAA,IAChB,UAAU,OAAO;AAAA,IACjB,QAAQ,OAAO,SAAS,OAAO,MAAM;AAAA,IACrC,UAAU,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ice(deviceUDID, port = 8100, teamId, signingIdentit
164
164
  buildWDAForDevice(deviceUDID, teamId, signingIdentity);
165
165
  }
166
166
  wdaProcess = startWDAOnDevice(deviceUDID, 8100, derivedDataPath);
167
- const { startIproxy } = await import("./ios-3GRECXAP.js");
167
+ const { startIproxy } = await import("./ios-JPK43TFZ.js");
168
168
  tunnel = startIproxy(deviceUDID, port, 8100);
169
169
  const maxRetries = 45;
170
170
  for (let i = 0; i < maxRetries; i++) {
@@ -241,4 +241,4 @@ export {
241
241
  setupWDAForDevice,
242
242
  setupWDA
243
243
  };
244
- //# sourceMappingURL=chunk-QPIE3IMG.js.map
244
+ //# sourceMappingURL=chunk-YGHDMA6D.js.map
package/dist/cli.js CHANGED
@@ -126,7 +126,7 @@ if (command === "test") {
126
126
  flowPath = arg;
127
127
  }
128
128
  }
129
- const { runTestCommand } = await import("./test-command-2PXTHASW.js");
129
+ const { runTestCommand } = await import("./test-command-B2VLWGDK.js");
130
130
  const success = await runTestCommand({
131
131
  platforms,
132
132
  tags,
@@ -181,7 +181,7 @@ if (command === "test") {
181
181
  }
182
182
  process.exit(1);
183
183
  }
184
- const { connect } = await import("./session-3UZ5WAAD.js");
184
+ const { connect } = await import("./session-2MZVGYAC.js");
185
185
  let session;
186
186
  try {
187
187
  session = await connect({
@@ -359,7 +359,7 @@ if (command === "test") {
359
359
  pretty = true;
360
360
  }
361
361
  }
362
- const { runDoctorCommand } = await import("./doctor-command-C3SEQGRQ.js");
362
+ const { runDoctorCommand } = await import("./doctor-command-YGQPO7GH.js");
363
363
  const success = await runDoctorCommand({
364
364
  configPath,
365
365
  platforms,
@@ -388,7 +388,7 @@ if (command === "test") {
388
388
  console.log(error instanceof Error ? error.message : String(error));
389
389
  process.exit(1);
390
390
  }
391
- const { runStudioCommand } = await import("./studio-command-5BUER2RH.js");
391
+ const { runStudioCommand } = await import("./studio-command-YDWQOMRX.js");
392
392
  await runStudioCommand({ port, open, config });
393
393
  } else if (command === "init") {
394
394
  const force = args.includes("--force");
@@ -455,7 +455,7 @@ if (command === "test") {
455
455
  process.exit(success ? 0 : 1);
456
456
  } else if (command === "devices") {
457
457
  const jsonMode = args.includes("--json");
458
- const { discoverDevices } = await import("./discover-NPNF6SWQ.js");
458
+ const { discoverDevices } = await import("./discover-CAQY6EG6.js");
459
459
  const devices = discoverDevices(["web", "android", "ios"]);
460
460
  if (jsonMode) {
461
461
  printMachinePayload(
@@ -2,9 +2,9 @@ import {
2
2
  discoverDevices,
3
3
  findDeviceById,
4
4
  firstDeviceForPlatform
5
- } from "./chunk-DSTUWLSW.js";
6
- import "./chunk-GZK22EIE.js";
7
- import "./chunk-4OHBO7LD.js";
5
+ } from "./chunk-PZYZ4O6D.js";
6
+ import "./chunk-EWIR2GVV.js";
7
+ import "./chunk-S5JNNDXS.js";
8
8
  import "./chunk-OBCFACUW.js";
9
9
  import "./chunk-DGUM43GV.js";
10
10
  export {
@@ -12,4 +12,4 @@ export {
12
12
  findDeviceById,
13
13
  firstDeviceForPlatform
14
14
  };
15
- //# sourceMappingURL=discover-NPNF6SWQ.js.map
15
+ //# sourceMappingURL=discover-CAQY6EG6.js.map
@@ -28,7 +28,7 @@ async function runDoctorCommand(options) {
28
28
  allGood = false;
29
29
  }
30
30
  } else if (platform === "android") {
31
- const { discoverDevices } = await import("./discover-NPNF6SWQ.js");
31
+ const { discoverDevices } = await import("./discover-CAQY6EG6.js");
32
32
  const devices = discoverDevices(["android"]);
33
33
  if (devices.length > 0) {
34
34
  checks.push({
@@ -40,7 +40,7 @@ async function runDoctorCommand(options) {
40
40
  checks.push({ name: "android", status: "warn", message: "No Android devices connected" });
41
41
  }
42
42
  } else if (platform === "ios") {
43
- const { discoverDevices } = await import("./discover-NPNF6SWQ.js");
43
+ const { discoverDevices } = await import("./discover-CAQY6EG6.js");
44
44
  const devices = discoverDevices(["ios"]);
45
45
  if (devices.length > 0) {
46
46
  checks.push({
@@ -68,4 +68,4 @@ async function runDoctorCommand(options) {
68
68
  export {
69
69
  runDoctorCommand
70
70
  };
71
- //# sourceMappingURL=doctor-command-C3SEQGRQ.js.map
71
+ //# sourceMappingURL=doctor-command-YGQPO7GH.js.map
@@ -1,4 +1,4 @@
1
- import { E as ExtendedSelector, s as WaitOptions, k as DismissKeyboardOptions, t as Direction, S as ScrollUntilVisibleOptions, B as BackUntilVisibleOptions, L as LaunchOptions, o as StorybookOpenOptions, i as BrowserRouteMatcher, f as BrowserMockResponse, h as BrowserNetworkConditions, m as Selector, c as BrowserConsoleLog, e as BrowserJSError, d as BrowserHAR, q as TouchSequence, P as Platform, b as ArtifactConfig } from './storybook-BK2JE4ld.js';
1
+ import { E as ExtendedSelector, s as WaitOptions, k as DismissKeyboardOptions, t as Direction, S as ScrollUntilVisibleOptions, B as BackUntilVisibleOptions, L as LaunchOptions, o as StorybookOpenOptions, i as BrowserRouteMatcher, f as BrowserMockResponse, h as BrowserNetworkConditions, m as Selector, c as BrowserConsoleLog, e as BrowserJSError, d as BrowserHAR, q as TouchSequence, g as BrowserName, n as StorybookConfig, P as Platform, b as ArtifactConfig } from './storybook-pBOPe_1D.js';
2
2
 
3
3
  interface PromiseApp<T extends string = string, R extends string = string> {
4
4
  tap(selector: ExtendedSelector<T>, opts?: WaitOptions): Promise<void>;
@@ -99,6 +99,27 @@ interface PromiseExpectation<T extends string = string> {
99
99
  toHaveMinTouchTarget(size?: number): Promise<void>;
100
100
  }
101
101
 
102
+ interface SecondarySessionOptions {
103
+ name: string;
104
+ platform: "web";
105
+ baseUrl?: string;
106
+ headless?: boolean;
107
+ browser?: BrowserName;
108
+ storageState?: string;
109
+ verboseLogging?: boolean;
110
+ storybook?: StorybookConfig;
111
+ }
112
+ interface SecondarySession {
113
+ readonly name: string;
114
+ readonly platform: "web";
115
+ readonly app: PromiseApp;
116
+ readonly expect: (selector: ExtendedSelector) => PromiseExpectation;
117
+ disconnect(): Promise<void>;
118
+ }
119
+ interface Sessions {
120
+ open(opts: SecondarySessionOptions): Promise<SecondarySession>;
121
+ }
122
+
102
123
  interface WhenCondition {
103
124
  /** Only run on these platforms */
104
125
  platform?: Platform | Platform[];
@@ -132,6 +153,7 @@ interface FlowContext<T extends string = string, R extends string = string> {
132
153
  app: PromiseApp<T, R>;
133
154
  expect: (selector: ExtendedSelector<T>) => PromiseExpectation<T>;
134
155
  platform: Platform;
156
+ sessions: Sessions;
135
157
  }
136
158
  type FlowFn<T extends string = string, R extends string = string> = (ctx: FlowContext<T, R>) => Promise<void>;
137
159
  interface FlowDefinition<T extends string = string, R extends string = string> {
@@ -143,4 +165,4 @@ interface FlowDefinition<T extends string = string, R extends string = string> {
143
165
  declare function flow<T extends string = string, R extends string = string>(name: string, fn: FlowFn<T, R>): FlowDefinition<T, R>;
144
166
  declare function flow<T extends string = string, R extends string = string>(name: string, config: FlowConfig<R>, fn: FlowFn<T, R>): FlowDefinition<T, R>;
145
167
 
146
- export { type FlowConfig as F, type PromiseApp as P, type FlowContext as a, type FlowDefinition as b, type FlowFn as c, type PromiseExpectation as d, flow as f };
168
+ export { type FlowConfig as F, type PromiseApp as P, type SecondarySession as S, type FlowContext as a, type FlowDefinition as b, type FlowFn as c, type PromiseExpectation as d, type SecondarySessionOptions as e, type Sessions as f, flow as g };
@@ -1,5 +1,5 @@
1
- import { a as FlowContext } from '../flow-CW0_j7tw.js';
2
- import '../storybook-BK2JE4ld.js';
1
+ import { a as FlowContext } from '../flow-thjUxXXx.js';
2
+ import '../storybook-pBOPe_1D.js';
3
3
  import 'effect';
4
4
 
5
5
  type StepContext<W = unknown> = FlowContext & {