spana-test 0.4.0 → 0.6.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 (157) hide show
  1. package/.agents/skills/spana-testing/SKILL.md +122 -246
  2. package/LICENSE +0 -0
  3. package/README.md +199 -68
  4. package/dist/{accessibility-audit-RS3VIWRT.js → accessibility-audit-YZOPUY3D.js} +7 -3
  5. package/dist/accessibility-audit-YZOPUY3D.js.map +1 -0
  6. package/dist/agent/index.d.ts +3 -84
  7. package/dist/agent/index.js +11 -10
  8. package/dist/agent/index.js.map +0 -0
  9. package/dist/allure-RNMEYTXS.js +0 -0
  10. package/dist/allure-RNMEYTXS.js.map +0 -0
  11. package/dist/{android-GFW6OXPQ.js → android-4NVTZMHL.js} +6 -2
  12. package/dist/{android-GFW6OXPQ.js.map → android-4NVTZMHL.js.map} +0 -0
  13. package/dist/app-DcLXtpv4.d.ts +908 -0
  14. package/dist/appium-server-66GVUL24.js +0 -0
  15. package/dist/appium-server-66GVUL24.js.map +0 -0
  16. package/dist/baseline-manager-5TIUCNP5.js +0 -0
  17. package/dist/baseline-manager-5TIUCNP5.js.map +0 -0
  18. package/dist/chunk-3FSZNKEF.js +0 -0
  19. package/dist/chunk-3FSZNKEF.js.map +0 -0
  20. package/dist/chunk-3SH5JQF7.js +611 -0
  21. package/dist/chunk-3SH5JQF7.js.map +1 -0
  22. package/dist/chunk-4K3FZTSV.js +179 -0
  23. package/dist/chunk-4K3FZTSV.js.map +1 -0
  24. package/dist/chunk-C4E4XULT.js +540 -0
  25. package/dist/chunk-C4E4XULT.js.map +1 -0
  26. package/dist/{chunk-3J4NG7JU.js → chunk-CY3DKTBZ.js} +8 -2
  27. package/dist/chunk-CY3DKTBZ.js.map +1 -0
  28. package/dist/chunk-DGUM43GV.js +0 -0
  29. package/dist/chunk-DGUM43GV.js.map +0 -0
  30. package/dist/chunk-DTNK54C2.js +127 -0
  31. package/dist/chunk-DTNK54C2.js.map +1 -0
  32. package/dist/{chunk-EWIR2GVV.js → chunk-H27IBIGA.js} +19 -2
  33. package/dist/chunk-H27IBIGA.js.map +1 -0
  34. package/dist/{chunk-PZYZ4O6D.js → chunk-HCG4CJKR.js} +23 -5
  35. package/dist/chunk-HCG4CJKR.js.map +1 -0
  36. package/dist/{chunk-YGHDMA6D.js → chunk-HYSTRWYN.js} +142 -41
  37. package/dist/chunk-HYSTRWYN.js.map +1 -0
  38. package/dist/chunk-IHVZKQQW.js +0 -0
  39. package/dist/chunk-IHVZKQQW.js.map +0 -0
  40. package/dist/{chunk-7VOWF42B.js → chunk-KBRLIQRA.js} +89 -8
  41. package/dist/chunk-KBRLIQRA.js.map +1 -0
  42. package/dist/chunk-KEUZLBQS.js +2935 -0
  43. package/dist/chunk-KEUZLBQS.js.map +1 -0
  44. package/dist/chunk-KJPHH2TW.js +0 -0
  45. package/dist/chunk-KJPHH2TW.js.map +0 -0
  46. package/dist/chunk-LAMTF4LX.js +89 -0
  47. package/dist/chunk-LAMTF4LX.js.map +1 -0
  48. package/dist/chunk-LCV673G3.js +3050 -0
  49. package/dist/chunk-LCV673G3.js.map +1 -0
  50. package/dist/chunk-OBCFACUW.js +0 -0
  51. package/dist/chunk-OBCFACUW.js.map +0 -0
  52. package/dist/{chunk-3TRMQCUT.js → chunk-PLE7RFQE.js} +31 -2
  53. package/dist/chunk-PLE7RFQE.js.map +1 -0
  54. package/dist/chunk-PWUJT5HE.js +5679 -0
  55. package/dist/chunk-PWUJT5HE.js.map +1 -0
  56. package/dist/{chunk-FJAJ4YNC.js → chunk-S4JVAHBR.js} +2 -2
  57. package/dist/{chunk-FJAJ4YNC.js.map → chunk-S4JVAHBR.js.map} +0 -0
  58. package/dist/chunk-S5JNNDXS.js +0 -0
  59. package/dist/chunk-S5JNNDXS.js.map +0 -0
  60. package/dist/{chunk-KYPLYRKW.js → chunk-WBBMEAHU.js} +122 -15
  61. package/dist/chunk-WBBMEAHU.js.map +1 -0
  62. package/dist/chunk-X2TJP7LB.js +0 -0
  63. package/dist/chunk-X2TJP7LB.js.map +0 -0
  64. package/dist/{chunk-5245YBLL.js → chunk-Y2RZNOKU.js} +2 -2
  65. package/dist/{chunk-5245YBLL.js.map → chunk-Y2RZNOKU.js.map} +0 -0
  66. package/dist/cli.js +62 -22
  67. package/dist/cli.js.map +1 -1
  68. package/dist/compiler-X6WTFMYF.js +0 -0
  69. package/dist/compiler-X6WTFMYF.js.map +0 -0
  70. package/dist/config-loader-J4Z2PMUQ.js +9 -0
  71. package/dist/{config-loader-QM72GKEL.js.map → config-loader-J4Z2PMUQ.js.map} +0 -0
  72. package/dist/{console-7UW7VROK.js → console-MI2XB5RG.js} +8 -2
  73. package/dist/console-MI2XB5RG.js.map +1 -0
  74. package/dist/daemon-manager-FBISTX24.js +28 -0
  75. package/dist/{discover-CAQY6EG6.js.map → daemon-manager-FBISTX24.js.map} +0 -0
  76. package/dist/{discover-CAQY6EG6.js → discover-LHEBSUIP.js} +3 -3
  77. package/dist/{installer-PVBSX7UC.js.map → discover-LHEBSUIP.js.map} +0 -0
  78. package/dist/doctor-command-WEHFANT7.js +378 -0
  79. package/dist/doctor-command-WEHFANT7.js.map +1 -0
  80. package/dist/filters-MQG2RMPX.js +26 -0
  81. package/dist/{runner-6HK62Q7B.js.map → filters-MQG2RMPX.js.map} +0 -0
  82. package/dist/flow-C2JQ7gUu.d.ts +95 -0
  83. package/dist/gherkin/steps.d.ts +2 -2
  84. package/dist/gherkin/steps.js +0 -0
  85. package/dist/gherkin/steps.js.map +0 -0
  86. package/dist/github-pr-YMWIPCCZ.js +10 -0
  87. package/dist/{session-2MZVGYAC.js.map → github-pr-YMWIPCCZ.js.map} +0 -0
  88. package/dist/html-F3X3XPSX.js +0 -0
  89. package/dist/html-F3X3XPSX.js.map +0 -0
  90. package/dist/index.d.ts +1323 -6
  91. package/dist/index.js +742 -6
  92. package/dist/index.js.map +1 -1
  93. package/dist/{init-command-U66XCM66.js → init-command-Z3QREABL.js} +60 -1
  94. package/dist/init-command-Z3QREABL.js.map +1 -0
  95. package/dist/{init-flow-command-PR7J5FBM.js → init-flow-command-4EKRVTNT.js} +2 -2
  96. package/dist/{init-flow-command-PR7J5FBM.js.map → init-flow-command-4EKRVTNT.js.map} +0 -0
  97. package/dist/{installer-PVBSX7UC.js → installer-VUPFWP5X.js} +7 -2
  98. package/dist/{validator-HZ2A3NEI.js.map → installer-VUPFWP5X.js.map} +0 -0
  99. package/dist/ios-JPK43TFZ.js +0 -0
  100. package/dist/ios-JPK43TFZ.js.map +0 -0
  101. package/dist/json-JMRPUVY2.js +0 -0
  102. package/dist/json-JMRPUVY2.js.map +0 -0
  103. package/dist/junit-HLC62MK6.js +0 -0
  104. package/dist/junit-HLC62MK6.js.map +0 -0
  105. package/dist/machine-6H25TRTU.js +0 -0
  106. package/dist/machine-6H25TRTU.js.map +0 -0
  107. package/dist/provider-YIPU5K42.js +0 -0
  108. package/dist/provider-YIPU5K42.js.map +0 -0
  109. package/dist/redact-U72BUBBR.js +0 -0
  110. package/dist/redact-U72BUBBR.js.map +0 -0
  111. package/dist/{runner-6HK62Q7B.js → runner-TF4OKPYP.js} +2 -2
  112. package/dist/runner-TF4OKPYP.js.map +1 -0
  113. package/dist/screenshot-compare-5NINZVOK.js +136 -0
  114. package/dist/screenshot-compare-5NINZVOK.js.map +1 -0
  115. package/dist/server-3MGZNK67.js +14 -0
  116. package/dist/server-3MGZNK67.js.map +1 -0
  117. package/dist/{server-PZBRGU7P.js → server-OANRDAHN.js} +15 -14
  118. package/dist/{server-PZBRGU7P.js.map → server-OANRDAHN.js.map} +1 -1
  119. package/dist/session-Daq0mE_a.d.ts +140 -0
  120. package/dist/session-Q3QYHT4Q.js +18 -0
  121. package/dist/session-Q3QYHT4Q.js.map +1 -0
  122. package/dist/{studio-command-YDWQOMRX.js → studio-command-RJYLJT4I.js} +2 -2
  123. package/dist/{studio-command-YDWQOMRX.js.map → studio-command-RJYLJT4I.js.map} +0 -0
  124. package/dist/{test-command-B2VLWGDK.js → test-command-ALH5ZQY5.js} +247 -1343
  125. package/dist/test-command-ALH5ZQY5.js.map +1 -0
  126. package/dist/{validator-HZ2A3NEI.js → validator-BLOLIHUY.js} +3 -3
  127. package/dist/validator-BLOLIHUY.js.map +1 -0
  128. package/package.json +7 -3
  129. package/studio-dist/assets/index-C-Io44gy.js +0 -0
  130. package/studio-dist/assets/index-DfM9lK4p.css +0 -0
  131. package/studio-dist/index.html +0 -0
  132. package/dist/accessibility-audit-RS3VIWRT.js.map +0 -1
  133. package/dist/chunk-3J4NG7JU.js.map +0 -1
  134. package/dist/chunk-3TRMQCUT.js.map +0 -1
  135. package/dist/chunk-7VOWF42B.js.map +0 -1
  136. package/dist/chunk-EWIR2GVV.js.map +0 -1
  137. package/dist/chunk-KYPLYRKW.js.map +0 -1
  138. package/dist/chunk-LC3QJIHY.js +0 -440
  139. package/dist/chunk-LC3QJIHY.js.map +0 -1
  140. package/dist/chunk-MCT4DYDK.js +0 -2671
  141. package/dist/chunk-MCT4DYDK.js.map +0 -1
  142. package/dist/chunk-PZYZ4O6D.js.map +0 -1
  143. package/dist/chunk-YAV6KBSW.js +0 -1318
  144. package/dist/chunk-YAV6KBSW.js.map +0 -1
  145. package/dist/chunk-YGHDMA6D.js.map +0 -1
  146. package/dist/config-loader-QM72GKEL.js +0 -9
  147. package/dist/console-7UW7VROK.js.map +0 -1
  148. package/dist/doctor-command-YGQPO7GH.js +0 -71
  149. package/dist/doctor-command-YGQPO7GH.js.map +0 -1
  150. package/dist/element-DZ0HyJ3C.d.ts +0 -25
  151. package/dist/flow-thjUxXXx.d.ts +0 -168
  152. package/dist/init-command-U66XCM66.js.map +0 -1
  153. package/dist/screenshot-compare-JFHH2WR4.js +0 -75
  154. package/dist/screenshot-compare-JFHH2WR4.js.map +0 -1
  155. package/dist/session-2MZVGYAC.js +0 -17
  156. package/dist/storybook-pBOPe_1D.d.ts +0 -451
  157. package/dist/test-command-B2VLWGDK.js.map +0 -1
package/dist/index.d.ts CHANGED
@@ -1,8 +1,95 @@
1
- export { F as FlowConfig, a as FlowContext, b as FlowDefinition, c as FlowFn, P as PromiseApp, d as PromiseExpectation, S as SecondarySession, e as SecondarySessionOptions, f as Sessions, g as flow } from './flow-thjUxXXx.js';
2
- import { P as Platform, A as AppiumExecutionConfig, a as AppConfig } from './storybook-pBOPe_1D.js';
3
- export { b as ArtifactConfig, B as BackUntilVisibleOptions, c as BrowserConsoleLog, d as BrowserHAR, e as BrowserJSError, f as BrowserMockResponse, g as BrowserName, h as BrowserNetworkConditions, i as BrowserRouteMatcher, D as DeviceInfo, j as DeviceStateConfig, k as DismissKeyboardOptions, E as ExtendedSelector, L as LaunchOptions, l as ProvConfig, R as RelativeSelector, S as ScrollUntilVisibleOptions, m as Selector, n as StorybookConfig, o as StorybookOpenOptions, p as StorybookValue, T as TouchAction, q as TouchSequence, W as WebExecutionConfig, r as defineConfig } from './storybook-pBOPe_1D.js';
4
- export { E as Element } from './element-DZ0HyJ3C.js';
5
- import 'effect';
1
+ import { F as FlowDefinition, a as FlowContext, b as FlowConfig } from './flow-C2JQ7gUu.js';
2
+ export { c as FlowFn, P as PromiseExpectation, S as SecondarySession, d as SecondarySessionOptions, e as Sessions, f as flow } from './flow-C2JQ7gUu.js';
3
+ import { R as RawDriverService, D as DriverError, a as DomElementMatch, P as Platform, E as ExtendedSelector, T as TapMode, b as ProvConfig, c as DomChannel, d as DomTargetInfo, S as Selector, e as DomWaitForSelectorOptions, f as DomWaitForHiddenOptions, g as DomWaitForMatchOptions, h as DomWaitForMatchResult, i as DomFillOptions, j as DomIdleOptions, k as DomStorageEntries, l as DomClearStorageOptions, B as BrowserRouteMatcher, m as BrowserMockResponse, n as BrowserConsoleLog, o as BrowserJSError, p as BrowserName, V as VirtualAuthenticatorOptions, q as ElectrobunAppConfig, r as ElectrobunRenderer, A as AppiumExecutionConfig, s as AppConfig, t as PromiseApp } from './app-DcLXtpv4.js';
4
+ export { u as ArtifactConfig, v as BackUntilVisibleOptions, w as BridgeConfig, x as BrowserHAR, y as BrowserNetworkConditions, z as DeviceInfo, C as DeviceStateConfig, F as DismissKeyboardOptions, G as DomChannelKind, H as DomRect, I as ElectronAppConfig, L as LaunchOptions, J as RelativeSelector, K as ScrollUntilVisibleOptions, M as StorybookConfig, N as StorybookOpenOptions, O as StorybookValue, Q as TouchAction, U as TouchSequence, W as VirtualCredential, X as WarmDaemonConfig, Y as WebBrowserEngine, Z as WebExecutionConfig, _ as WebResourceBlockType, $ as buildDomFillScript, a0 as buildDomWaitForHiddenScript, a1 as buildDomWaitForMatchScript, a2 as buildDomWaitForSelectorScript, a3 as defineConfig, a4 as isSystemUISelector, a5 as isTestIDSelector, a6 as systemUI } from './app-DcLXtpv4.js';
5
+ import { E as Element, B as Bounds, C as ConnectOptions, S as Session } from './session-Daq0mE_a.js';
6
+ import { Socket } from 'node:net';
7
+ import { Effect } from 'effect';
8
+ import { Browser, _electron, chromium } from 'playwright-core';
9
+ import { spawn } from 'node:child_process';
10
+
11
+ interface HierarchyCache {
12
+ /** Get the hierarchy, using cache if fresh enough. */
13
+ get(driver: RawDriverService, parse: (raw: string) => Element): Effect.Effect<Element, DriverError>;
14
+ /** Invalidate the cache (call after mutation actions like tap, type, scroll). */
15
+ invalidate(): void;
16
+ }
17
+
18
+ type ResolvedChannel = "dom" | "native";
19
+ interface ResolvedElementResult {
20
+ element: Element;
21
+ channel: ResolvedChannel;
22
+ /** Raw DOM match when resolved via DOM channel */
23
+ domMatch?: DomElementMatch;
24
+ /** Resolved WebView frame in native coordinates (when mapped to native coords) */
25
+ webViewFrame?: Bounds;
26
+ }
27
+ /** Explicitly invalidate the cached WebView frame for a driver (e.g. after navigation or rotation). */
28
+ declare function invalidateWebViewFrameCache(driver: RawDriverService<any, any>): void;
29
+ /**
30
+ * Locate the active WebView container's frame inside a parsed native
31
+ * accessibility hierarchy (iOS `XCUIElementTypeWebView` or Android
32
+ * `android.webkit.WebView`). Picks the largest visible WebView container so
33
+ * tiny auxiliary/ad webviews don't win over the primary Capacitor WebView.
34
+ */
35
+ declare function findWebViewFrame(nativeRoot: Element): Bounds | undefined;
36
+ interface CoordinateMappingOptions {
37
+ /**
38
+ * Override coordinate scale factor (CSS px -> native coordinate units).
39
+ * When omitted, derived automatically from `webViewFrame.width / match.viewportWidth`,
40
+ * falling back to `devicePixelRatio` on Android (physical pixels) and `1` on iOS (logical points).
41
+ */
42
+ scaleOverride?: number;
43
+ platform?: Platform;
44
+ /**
45
+ * Optional explicit scroll offset adjustment if a caller provides document-relative
46
+ * coordinates instead of viewport-relative `getBoundingClientRect()` coordinates.
47
+ * Default: false (because `getBoundingClientRect()` is already viewport-relative).
48
+ */
49
+ subtractScrollOffset?: boolean;
50
+ }
51
+ /**
52
+ * Convert a DOM element's `getBoundingClientRect()` into native screen
53
+ * coordinates using the WebView's native frame, viewport/DPR scale, and
54
+ * optional scroll adjustment.
55
+ *
56
+ * - On iOS (WDA): native coordinates are logical points (~1× CSS px).
57
+ * `webViewFrame.width / viewportWidth` is ~1.0, and `webViewFrame.y` adds
58
+ * the status bar / safe-area / native header offset.
59
+ * - On Android (UiAutomator2): native coordinates are physical pixels
60
+ * (`CSS px × devicePixelRatio`). `webViewFrame.width / viewportWidth`
61
+ * equals `devicePixelRatio` automatically (e.g. 1080 / 393 ≈ 2.75).
62
+ */
63
+ declare function domRectToScreenBounds(match: DomElementMatch, webViewFrame?: Bounds, options?: CoordinateMappingOptions): Bounds;
64
+ /**
65
+ * Returns true if the element's center lies outside the visible WebView viewport
66
+ * so we know to auto-scroll it into view before issuing a native coordinate tap.
67
+ */
68
+ declare function isOffscreenInViewport(match: DomElementMatch): boolean;
69
+ interface ChannelResolveOptions {
70
+ /** Whether we're resolving for a touch/click action (maps to screen coords unless tapMode === "dom") */
71
+ forAction?: boolean;
72
+ /** Default "native" (real touch via native driver). Opt-in "dom" skips native coordinate mapping. */
73
+ tapMode?: TapMode;
74
+ platform?: Platform;
75
+ }
76
+ /**
77
+ * Channel-hiding resolver — core of Spana's web-first architecture:
78
+ *
79
+ * 1. If selector is explicitly marked `systemUI` (e.g. SFSafariViewController,
80
+ * Chrome Custom Tabs, OS permission dialogs), query the native tree directly.
81
+ * 2. If selector is `{ testID }` (or a simple non-relative selector when the
82
+ * DOM channel is already connected) and a `domChannel` exists on the driver,
83
+ * query the DOM first (~1ms, locale-independent).
84
+ * - For assertions/reads or `tapMode: "dom"`, return immediately without
85
+ * fetching the native page source.
86
+ * - For real native taps (`tapMode: "native"`), fetch/cache the native
87
+ * hierarchy once to locate the WebView frame, convert the DOM rect into
88
+ * screen coordinates, and return the screen-positioned element.
89
+ * 3. Otherwise, or if step 2 finds nothing (out-of-process browser sheet or
90
+ * native chrome), fall back seamlessly to the native accessibility tree.
91
+ */
92
+ declare function resolveElementAcrossChannels<T extends string = string, R extends string = string>(driver: RawDriverService<T, R>, selector: ExtendedSelector<T>, parse: (raw: string) => Element, cache?: HierarchyCache, options?: ChannelResolveOptions): Effect.Effect<ResolvedElementResult | undefined, DriverError>;
6
93
 
7
94
  /** Result of a single test step (tap, assertVisible, typeText, etc.) within a flow. */
8
95
  interface StepResult {
@@ -149,6 +236,614 @@ interface Reporter {
149
236
  platformFlowCounts?: Partial<Record<Platform, number>>;
150
237
  }
151
238
 
239
+ type TargetShell = "browser" | "capacitor" | "electron" | "electrobun";
240
+ type TargetEngine = "chromium" | "webkit" | "firefox" | "wkwebview" | "webview2" | "webkitgtk" | "android-webview" | "cef";
241
+ type TargetChannel = "bridge" | "cdp" | "webkit-inspector" | "native-ax";
242
+ interface TargetDescriptor {
243
+ platform: Platform;
244
+ shell: TargetShell;
245
+ engine: TargetEngine;
246
+ channels: readonly TargetChannel[];
247
+ domChannels: readonly Exclude<TargetChannel, "native-ax">[];
248
+ nativeChannel: "native-ax" | null;
249
+ supportsSystemSheets: boolean;
250
+ notes: string;
251
+ }
252
+ type HostOS = "darwin" | "win32" | "linux";
253
+ /**
254
+ * Canonical matrix describing how Spana reaches the DOM and native UI on each
255
+ * supported web-first target:
256
+ * target = shell + engine + channels
257
+ */
258
+ declare const TARGET_CHANNEL_MATRIX: Record<Platform, TargetDescriptor>;
259
+ declare function resolveElectrobunEngine(renderer?: "native" | "cef", hostOs?: HostOS): {
260
+ engine: TargetEngine;
261
+ channels: TargetChannel[];
262
+ };
263
+ declare function resolveTargetDescriptor(platform: Platform, config?: ProvConfig, hostOs?: HostOS): TargetDescriptor;
264
+ declare function formatTargetMatrixTable(platforms?: Platform[], config?: ProvConfig, hostOs?: HostOS): string;
265
+
266
+ interface MinimalWebSocket {
267
+ readonly readyState: number;
268
+ send(data: string): void;
269
+ close(): void;
270
+ addEventListener(type: string, listener: (event: any) => void): void;
271
+ removeEventListener?(type: string, listener: (event: any) => void): void;
272
+ }
273
+ type WebSocketFactory = (url: string) => MinimalWebSocket;
274
+ interface CdpDomChannelOptions {
275
+ /** Base HTTP URL of the CDP debug endpoint, e.g. `http://127.0.0.1:9222` */
276
+ endpointUrl: string;
277
+ /** Optional direct WebSocket URL (skips `/json/list` discovery) */
278
+ webSocketUrl?: string;
279
+ /** Optional target filter (matches URL or title substring/RegExp) */
280
+ targetFilter?: string | RegExp;
281
+ /** Command timeout in ms. Default: 10_000. */
282
+ timeoutMs?: number;
283
+ /** Injectable fetch for testing */
284
+ fetchFn?: typeof fetch;
285
+ /** Injectable WebSocket factory for testing */
286
+ createWebSocket?: WebSocketFactory;
287
+ }
288
+ declare class CdpDomChannel implements DomChannel {
289
+ readonly kind: "cdp";
290
+ private readonly endpointUrl;
291
+ private readonly explicitWsUrl?;
292
+ private readonly targetFilter?;
293
+ private readonly timeoutMs;
294
+ private readonly fetchFn;
295
+ private readonly createWebSocket;
296
+ private ws;
297
+ private connected;
298
+ private nextId;
299
+ private pending;
300
+ private eventListeners;
301
+ private currentTargetId;
302
+ private activeSessionId;
303
+ constructor(options: CdpDomChannelOptions);
304
+ isConnected(): boolean;
305
+ listTargets(): Promise<DomTargetInfo[]>;
306
+ private fetchTargets;
307
+ selectTarget(targetId: string): Promise<void>;
308
+ connect(): Promise<void>;
309
+ private openSocket;
310
+ private rejectAllPending;
311
+ setSessionId(sessionId: string | null): void;
312
+ get sessionId(): string | null;
313
+ onEvent(method: string, listener: (params: any, sessionId?: string) => void): () => void;
314
+ waitForEvent<T = any>(method: string, timeoutMs?: number, predicate?: (params: T, sessionId?: string) => boolean): Promise<T>;
315
+ sendCommand<T = any>(method: string, params?: Record<string, unknown>, sessionId?: string | null): Promise<T>;
316
+ evaluate<T = unknown>(script: string | ((...args: any[]) => T), ...args: any[]): Promise<T>;
317
+ query(selector: Selector): Promise<DomElementMatch[]>;
318
+ waitForSelector(selector: Selector, opts?: DomWaitForSelectorOptions): Promise<DomElementMatch[]>;
319
+ waitForHidden(selector: Selector, opts?: DomWaitForHiddenOptions): Promise<boolean>;
320
+ waitForMatch(selector: Selector, opts: DomWaitForMatchOptions): Promise<DomWaitForMatchResult>;
321
+ fillDom(selector: Selector, value: string, opts?: DomFillOptions): Promise<boolean>;
322
+ tapDom(selector: Selector): Promise<boolean>;
323
+ scrollIntoView(selector: Selector): Promise<DomElementMatch | null>;
324
+ reload(): Promise<void>;
325
+ disconnect(): Promise<void>;
326
+ get targetId(): string | null;
327
+ }
328
+ declare function createCdpDomChannel(options: CdpDomChannelOptions): CdpDomChannel;
329
+
330
+ interface AndroidWebViewSocket {
331
+ socketName: string;
332
+ pid?: number;
333
+ }
334
+ interface AndroidWebViewCdpOptions {
335
+ serial: string;
336
+ packageName?: string;
337
+ /** Optional explicit local TCP port to forward to */
338
+ localPort?: number;
339
+ /** Optional explicit abstract socket name (skips /proc/net/unix discovery) */
340
+ socketName?: string;
341
+ timeoutMs?: number;
342
+ /** Injectable command runner for tests */
343
+ runAdb?: (args: string) => string;
344
+ fetchFn?: typeof fetch;
345
+ createWebSocket?: WebSocketFactory;
346
+ }
347
+ /**
348
+ * Parse `/proc/net/unix` output from an Android device and extract all
349
+ * `webview_devtools_remote_*` abstract Unix domain sockets.
350
+ */
351
+ declare function parseAndroidWebViewSockets(procNetUnixOutput: string): AndroidWebViewSocket[];
352
+ /**
353
+ * Direct Android System WebView CDP channel without Appium.
354
+ *
355
+ * Requires `WebView.setWebContentsDebuggingEnabled(true)` (Capacitor's
356
+ * `webContentsDebuggingEnabled: true`). Discovers `webview_devtools_remote_<pid>`,
357
+ * forwards it via `adb forward tcp:<port> localabstract:<socket>`, and speaks
358
+ * CDP directly over WebSocket.
359
+ */
360
+ declare class AndroidWebViewCdpChannel implements DomChannel {
361
+ readonly kind: "cdp";
362
+ private readonly options;
363
+ private forwardedPort;
364
+ private allocatedByUs;
365
+ private activeSocketName;
366
+ private cdp;
367
+ constructor(options: AndroidWebViewCdpOptions);
368
+ private execAdb;
369
+ isConnected(): boolean;
370
+ get socketName(): string | null;
371
+ get localPort(): number | null;
372
+ connect(): Promise<void>;
373
+ evaluate<T = unknown>(script: string | ((...args: any[]) => T), ...args: any[]): Promise<T>;
374
+ query(selector: Selector): Promise<DomElementMatch[]>;
375
+ tapDom(selector: Selector): Promise<boolean>;
376
+ scrollIntoView(selector: Selector): Promise<DomElementMatch | null>;
377
+ listTargets(): Promise<DomTargetInfo[]>;
378
+ selectTarget(targetId: string): Promise<void>;
379
+ reload(): Promise<void>;
380
+ disconnect(): Promise<void>;
381
+ }
382
+ declare function createAndroidWebViewCdpChannel(options: AndroidWebViewCdpOptions): AndroidWebViewCdpChannel;
383
+
384
+ interface WebKitInspectorOptions {
385
+ /** Base HTTP URL of the WebKit inspector proxy (e.g. `http://127.0.0.1:9221` or `27753`) */
386
+ endpointUrl?: string;
387
+ /** Port for ios-webkit-debug-proxy / simulator webinspectord bridge (default: 9221) */
388
+ port?: number;
389
+ /** Direct WebSocket URL (skips `/json` target listing) */
390
+ webSocketUrl?: string;
391
+ /** Target device / simulator UDID (used when auto-starting ios_webkit_debug_proxy) */
392
+ udid?: string;
393
+ /** Optional bundleId / URL filter to pick the right WKWebView page */
394
+ bundleId?: string;
395
+ /** Automatically spawn `ios_webkit_debug_proxy` if installed and endpoint isn't up */
396
+ autoStartProxy?: boolean;
397
+ timeoutMs?: number;
398
+ fetchFn?: typeof fetch;
399
+ createWebSocket?: WebSocketFactory;
400
+ }
401
+ /**
402
+ * Direct WebKit Remote Inspector channel for iOS `WKWebView` (iOS 16.4+
403
+ * `webView.isInspectable = true`) and macOS WKWebView — without Appium.
404
+ *
405
+ * Talks WebKit Inspector JSON-RPC (`Runtime.evaluate` with `returnByValue`)
406
+ * over WebSocket via `ios_webkit_debug_proxy` or a simulator `webinspectord`
407
+ * endpoint.
408
+ */
409
+ declare class WebKitInspectorChannel implements DomChannel {
410
+ readonly kind: "webkit-inspector";
411
+ private readonly endpointUrl;
412
+ private readonly explicitWsUrl?;
413
+ private readonly udid?;
414
+ private readonly bundleId?;
415
+ private readonly port;
416
+ private readonly autoStartProxy;
417
+ private readonly timeoutMs;
418
+ private readonly fetchFn;
419
+ private readonly createWebSocket;
420
+ private ws;
421
+ private nativeInspector;
422
+ private proxyProcess;
423
+ private connected;
424
+ private nextId;
425
+ private pending;
426
+ private currentTargetId;
427
+ constructor(options?: WebKitInspectorOptions);
428
+ isConnected(): boolean;
429
+ private ensureProxyIfNeeded;
430
+ private fetchTargets;
431
+ listTargets(): Promise<DomTargetInfo[]>;
432
+ selectTarget(targetId: string): Promise<void>;
433
+ connect(): Promise<void>;
434
+ private openSocket;
435
+ private rejectAllPending;
436
+ sendCommand<T = any>(method: string, params?: Record<string, unknown>): Promise<T>;
437
+ evaluate<T = unknown>(script: string | ((...args: any[]) => T), ...args: any[]): Promise<T>;
438
+ query(selector: Selector): Promise<DomElementMatch[]>;
439
+ tapDom(selector: Selector): Promise<boolean>;
440
+ scrollIntoView(selector: Selector): Promise<DomElementMatch | null>;
441
+ reload(): Promise<void>;
442
+ private disconnectSocketOnly;
443
+ disconnect(): Promise<void>;
444
+ get targetId(): string | null;
445
+ }
446
+ declare function createWebKitInspectorChannel(options?: WebKitInspectorOptions): WebKitInspectorChannel;
447
+
448
+ /**
449
+ * Zero-dependency Apple WebInspector RPC framing over Unix domain sockets
450
+ * (iOS Simulator `com.apple.webinspector` / CoreSimulator tmp sockets).
451
+ *
452
+ * Apple's `webinspectord` exchanges length-prefixed XML/binary plist envelopes:
453
+ * - 4-byte big-endian uint32 byte length
454
+ * - XML plist payload containing `__selector` + `__argument` dictionary
455
+ *
456
+ * This lets Spana evaluate JS and query WKWebView DOMs on iOS Simulators even
457
+ * when `ios_webkit_debug_proxy` is not installed.
458
+ */
459
+ interface WebInspectorListingPage {
460
+ appId: string;
461
+ pageId: number;
462
+ title?: string;
463
+ url?: string;
464
+ type?: string;
465
+ }
466
+ /** Encode an Apple WebInspector RPC message into a 4-byte length-prefixed XML plist frame. */
467
+ declare function encodeWebInspectorPacket(selector: string, args: Record<string, unknown>): Buffer;
468
+ /**
469
+ * Decode complete 4-byte length-prefixed frames from a streaming byte buffer.
470
+ * Returns decoded UTF-8 XML strings plus any trailing incomplete bytes.
471
+ */
472
+ declare function decodeWebInspectorFrames(buffer: Buffer): {
473
+ frames: string[];
474
+ remaining: Buffer;
475
+ };
476
+ /**
477
+ * Extract the `__selector` and key fields (`WIRApplicationIdentifierKey`,
478
+ * `WIRMessageDataKey`, `WIRListingKey`) from a decoded XML plist frame.
479
+ */
480
+ declare function parseWebInspectorXmlFrame(xml: string): {
481
+ selector: string | null;
482
+ appId?: string;
483
+ messageDataJson?: Record<string, any>;
484
+ pages?: WebInspectorListingPage[];
485
+ };
486
+ /**
487
+ * Discover a running iOS Simulator's `com.apple.webinspector` Unix domain
488
+ * socket path (no external binaries required).
489
+ */
490
+ declare function findSimulatorWebInspectorSocket(udid?: string): string | null;
491
+ interface AppleWebInspectorClientOptions {
492
+ socketPath: string;
493
+ bundleId?: string;
494
+ timeoutMs?: number;
495
+ /** Injectable socket connector for unit tests */
496
+ connectSocket?: (socketPath: string) => Socket;
497
+ }
498
+ /**
499
+ * Direct Apple `webinspectord` Unix-socket client implementing the
500
+ * `_rpc_reportIdentifier:` → `_rpc_forwardSocketSetup:` → `_rpc_forwardSocketData:`
501
+ * JSON-RPC flow without `ios_webkit_debug_proxy` or Appium.
502
+ */
503
+ declare class AppleWebInspectorClient {
504
+ private readonly socketPath;
505
+ private readonly bundleId?;
506
+ private readonly timeoutMs;
507
+ private readonly connectSocket;
508
+ private readonly connectionId;
509
+ private readonly senderKey;
510
+ private socket;
511
+ private readBuffer;
512
+ private connected;
513
+ private nextRpcId;
514
+ private pages;
515
+ private activePage;
516
+ private pendingRpc;
517
+ private listingWaiters;
518
+ constructor(options: AppleWebInspectorClientOptions);
519
+ isConnected(): boolean;
520
+ connect(): Promise<void>;
521
+ private handleFrame;
522
+ listPages(): Promise<WebInspectorListingPage[]>;
523
+ ensurePageAttached(): Promise<WebInspectorListingPage>;
524
+ sendInspectorCommand<T = any>(method: string, params?: Record<string, unknown>): Promise<T>;
525
+ disconnect(): Promise<void>;
526
+ }
527
+
528
+ interface WsConnection {
529
+ readonly id: string;
530
+ readonly isOpen: boolean;
531
+ send(text: string): void;
532
+ close(code?: number): void;
533
+ onMessage(listener: (text: string) => void): void;
534
+ onClose(listener: () => void): void;
535
+ }
536
+
537
+ interface SpanaBridgeServerOptions {
538
+ host?: string;
539
+ port?: number;
540
+ connectTimeoutMs?: number;
541
+ requestTimeoutMs?: number;
542
+ }
543
+ /**
544
+ * Runner-side WebSocket server that accepts connections from `spana-bridge`
545
+ * running inside the app under test (web, Capacitor iOS/Android, Electron,
546
+ * or Electrobun) and exposes the unified `DomChannel` interface.
547
+ */
548
+ declare class SpanaBridgeChannel implements DomChannel {
549
+ readonly kind: "bridge";
550
+ private readonly host;
551
+ private readonly requestedPort;
552
+ private readonly connectTimeoutMs;
553
+ private readonly requestTimeoutMs;
554
+ private server;
555
+ private activeConn;
556
+ private nextId;
557
+ private pending;
558
+ private connectionWaiters;
559
+ private helloMeta;
560
+ constructor(options?: SpanaBridgeServerOptions);
561
+ get url(): string | null;
562
+ get port(): number | null;
563
+ get clientMetadata(): Record<string, unknown> | null;
564
+ isConnected(): boolean;
565
+ /** Start listening for an incoming `spana-bridge` WebSocket connection. */
566
+ start(): Promise<{
567
+ host: string;
568
+ port: number;
569
+ url: string;
570
+ }>;
571
+ /** Wait until a `spana-bridge` client connects (starting the server if needed). */
572
+ connect(): Promise<void>;
573
+ waitForClient(timeoutMs?: number): Promise<WsConnection>;
574
+ /** Wait for a brand-new bridge client connection (e.g. after a page navigation or reload). */
575
+ waitForNextClient(timeoutMs?: number): Promise<WsConnection>;
576
+ private handleMessage;
577
+ private rejectAllPending;
578
+ call<T = any>(method: string, params?: Record<string, unknown>): Promise<T>;
579
+ evaluate<T = unknown>(script: string | ((...args: any[]) => T), ...args: any[]): Promise<T>;
580
+ query(selector: Selector): Promise<DomElementMatch[]>;
581
+ tapDom(selector: Selector): Promise<boolean>;
582
+ scrollIntoView(selector: Selector): Promise<DomElementMatch | null>;
583
+ dispatch(selector: Selector, eventType: string, eventInit?: Record<string, unknown>): Promise<boolean>;
584
+ waitForIdle(opts?: DomIdleOptions): Promise<void>;
585
+ setStorage(entries: DomStorageEntries): Promise<void>;
586
+ clearStorage(opts?: DomClearStorageOptions): Promise<void>;
587
+ reload(): Promise<void>;
588
+ mockNetwork(matcher: BrowserRouteMatcher, response: BrowserMockResponse): Promise<void>;
589
+ blockNetwork(matcher: BrowserRouteMatcher): Promise<void>;
590
+ clearNetworkMocks(): Promise<void>;
591
+ getConsoleLogs(): Promise<BrowserConsoleLog[]>;
592
+ getJSErrors(): Promise<BrowserJSError[]>;
593
+ disconnect(): Promise<void>;
594
+ }
595
+ declare function createSpanaBridgeChannel(options?: SpanaBridgeServerOptions): SpanaBridgeChannel;
596
+ /**
597
+ * Composite channel that tries an ordered list of DOM channels (e.g. bridge
598
+ * first, then WebKit Inspector or Android WebView CDP).
599
+ */
600
+ declare function createCompositeDomChannel(channels: DomChannel[]): DomChannel;
601
+
602
+ interface PlaywrightConfig {
603
+ browser?: BrowserName;
604
+ headless?: boolean;
605
+ baseUrl?: string;
606
+ storageState?: string;
607
+ verboseLogging?: boolean;
608
+ /** Optional pre-launched Browser instance shared across parallel BrowserContext workers. */
609
+ sharedBrowser?: Browser;
610
+ /** Optional browser channel (e.g. "chrome") or explicit executable path. */
611
+ channel?: string;
612
+ executablePath?: string;
613
+ /** Navigation wait condition for launchApp / openLink (e.g. "domcontentloaded" for prefetch-heavy SSR apps). */
614
+ waitUntil?: "domcontentloaded" | "load" | "networkidle" | "commit";
615
+ /** Record per-request HAR metadata over CDP/IPC. Disable when `artifacts.har` is off for faster page loads. Default: true. */
616
+ recordHar?: boolean;
617
+ /** Flashwright-inspired: speed up CSS transitions & animations to 0.001ms so actions never stall on transitions. */
618
+ instantAnimations?: boolean;
619
+ /** Flashwright-inspired: abort specified resource types (e.g. ["image", "font", "media"]) before hitting the network. */
620
+ blockResources?: Array<"image" | "font" | "media" | "stylesheet">;
621
+ /** Connect to an already-running warm Chromium CDP endpoint instead of launching a new browser process. */
622
+ cdpEndpoint?: string;
623
+ /** Connect to a remote Playwright WebSocket server (e.g. BrowserStack Automate Web `wss://cdp.browserstack.com/playwright?...`). */
624
+ wsEndpoint?: string;
625
+ /** Reuse a persistent detached headless Chromium daemon across CLI runs (Flashwright-style warm session). */
626
+ warmBrowser?: boolean;
627
+ /** Scope key for isolating warm Chromium daemons across concurrent repos/runs (defaults to cwd hash). */
628
+ warmBrowserScope?: string;
629
+ /** Create a fresh isolated BrowserContext per flow via a pre-warmed context pool + background teardown. */
630
+ freshContextPerFlow?: boolean;
631
+ /** Automatically attach a CDP WebAuthn virtual authenticator (passkey) to every fresh context. */
632
+ virtualAuthenticator?: boolean | VirtualAuthenticatorOptions;
633
+ /** Attach a built-in zero-setup Playwright DOM channel for ~1ms `{ testID }` queries without full DOM dumps. Default: true. */
634
+ enableDomChannel?: boolean;
635
+ }
636
+ /**
637
+ * Connect to an existing warm headless Chromium daemon or start a detached one
638
+ * registered in Spana's warm daemon registry (`spana daemon status|stop`).
639
+ */
640
+ declare function ensureWarmBrowserDaemon(config?: Pick<PlaywrightConfig, "executablePath" | "headless" | "warmBrowserScope">): Promise<{
641
+ browser: Browser;
642
+ cdpUrl: string;
643
+ reused: boolean;
644
+ }>;
645
+ declare function connectPlaywrightOverCDP(cdpEndpoint: string): Promise<Browser>;
646
+ declare function connectPlaywrightOverWS(wsEndpoint: string, browserName?: BrowserName): Promise<Browser>;
647
+ declare function launchPlaywrightBrowser(config?: Pick<PlaywrightConfig, "browser" | "headless" | "channel" | "executablePath">): Promise<Browser>;
648
+
649
+ interface DirectCdpBrowserLaunchOptions {
650
+ /** Explicit Chromium/Chrome binary path. Auto-detects system Chrome or Playwright Chromium if omitted. */
651
+ executablePath?: string;
652
+ /** Run headless (default: true). */
653
+ headless?: boolean;
654
+ /** Reuse a detached warm Chromium daemon across CLI runs. */
655
+ warmBrowser?: boolean;
656
+ /** Isolation scope key for warm Chromium daemon (defaults to cwd hash). */
657
+ warmBrowserScope?: string;
658
+ /** Extra Chrome launch flags. */
659
+ args?: string[];
660
+ }
661
+ interface DirectCdpBrowserHandle {
662
+ /** HTTP debugging endpoint, e.g. `http://127.0.0.1:9322`. */
663
+ httpEndpoint: string;
664
+ /** Browser-level CDP WebSocket URL (`ws://127.0.0.1:.../devtools/browser/...`). */
665
+ browserWsUrl: string;
666
+ /** True when attached to a pre-existing warm daemon (close will NOT kill it). */
667
+ reused: boolean;
668
+ pid?: number;
669
+ close(): Promise<void>;
670
+ }
671
+ /**
672
+ * Launch (or attach to a warm) Chromium process directly over raw CDP WebSocket —
673
+ * completely bypassing Playwright's Node client↔server IPC pipe!
674
+ */
675
+ declare function launchDirectCdpBrowser(options?: DirectCdpBrowserLaunchOptions): Promise<DirectCdpBrowserHandle>;
676
+ interface LightweightCdpDriverOptions {
677
+ /**
678
+ * HTTP CDP endpoint (e.g. `"http://127.0.0.1:9222"` for Lightpanda or Chrome `--remote-debugging-port`)
679
+ * OR direct WebSocket debugger URL (`"ws://127.0.0.1:9222/devtools/page/..."` or `"/devtools/browser/..."`).
680
+ */
681
+ cdpUrl: string;
682
+ /** Optional base URL used when `launchApp()` receives a relative path. */
683
+ baseUrl?: string;
684
+ /** Engine label reported in `getDeviceInfo()` (e.g. `"lightpanda"` or `"cdp"`). */
685
+ engineLabel?: string;
686
+ /** Optional viewport dimensions reported to coordinator (default: 1280×720). */
687
+ viewport?: {
688
+ width: number;
689
+ height: number;
690
+ };
691
+ /**
692
+ * Use isolated CDP browser contexts (`Target.createBrowserContext` + flattened CDP sessions)
693
+ * on a browser-level WebSocket — zero Playwright Node client↔server pipe!
694
+ * Auto-enabled when `cdpUrl` is a `/devtools/browser/` URL or `freshContextPerFlow` is true.
695
+ */
696
+ useBrowserContexts?: boolean;
697
+ /** Pre-warm the next isolated CDP browser context while the current flow runs, and dispose old contexts asynchronously. */
698
+ freshContextPerFlow?: boolean;
699
+ /** Navigation wait condition (`"load"`, `"domcontentloaded"`, or `"commit"`). Default: `"load"` in browser-context mode. */
700
+ waitUntil?: "domcontentloaded" | "load" | "networkidle" | "commit";
701
+ /** Collapse CSS transitions & animations to 0.001ms via `Page.addScriptToEvaluateOnNewDocument`. */
702
+ instantAnimations?: boolean;
703
+ /** Abort specified resource types before hitting the network. */
704
+ blockResources?: Array<"image" | "font" | "media" | "stylesheet">;
705
+ /** Automatically attach a CDP WebAuthn virtual authenticator (passkey) to every context. */
706
+ virtualAuthenticator?: boolean | VirtualAuthenticatorOptions;
707
+ /** Optional Playwright-compatible storageState JSON path to preload into contexts. */
708
+ storageState?: string;
709
+ /** Injectable fetch & WebSocket factory for tests. */
710
+ fetchFn?: typeof fetch;
711
+ createWebSocket?: WebSocketFactory;
712
+ }
713
+ /**
714
+ * Direct CDP Chromium / Lightpanda driver speaking raw WebSocket CDP directly
715
+ * from Bun/Node to the browser — completely eliminating Playwright's Node
716
+ * client↔server IPC pipe!
717
+ *
718
+ * Supports:
719
+ * - Page-level attach (Lightpanda or existing tab)
720
+ * - Full browser-level isolated contexts (`Target.createBrowserContext`), pre-warmed
721
+ * context pooling (`freshContextPerFlow`), background async context disposal,
722
+ * built-in WebAuthn virtual passkeys, network mocking (`Fetch`), cookies/auth state,
723
+ * and single-round-trip MutationObserver actionability via `CdpDomChannel`.
724
+ */
725
+ declare function makeLightweightCdpDriver(options: LightweightCdpDriverOptions): Effect.Effect<RawDriverService, DriverError>;
726
+
727
+ interface PrelaunchedWebBrowser {
728
+ browserPromise: Promise<Browser>;
729
+ ownsBrowser: boolean;
730
+ /** Populated when `execution.web.engine === "cdp"` speculatively launches direct Chromium. */
731
+ cdpBrowserPromise?: Promise<DirectCdpBrowserHandle>;
732
+ }
733
+ /**
734
+ * Start launching (or connecting to a warm/CDP) browser immediately
735
+ * so browser boot overlaps with flow discovery and TypeScript imports.
736
+ */
737
+ declare function speculativelyPrelaunchWebBrowser(config: ProvConfig): PrelaunchedWebBrowser | undefined;
738
+
739
+ /** Order flows descending by known duration (longest first) while preserving order on ties. */
740
+ declare function orderFlowsLongestFirst(flows: FlowDefinition[], durationHintsMs?: Record<string, number>): FlowDefinition[];
741
+
742
+ interface ElectronDriverOptions {
743
+ /** Path to Electron main entry file or app directory (passed to `_electron.launch`) */
744
+ entry?: string;
745
+ /** Path to packaged Electron executable */
746
+ executablePath?: string;
747
+ /** Extra CLI args passed to Electron */
748
+ args?: string[];
749
+ cwd?: string;
750
+ env?: Record<string, string>;
751
+ /** Attach to an already running Electron app over CDP instead of launching */
752
+ cdpUrl?: string;
753
+ /** Remote debugging port (when attaching over CDP or launching with debugging enabled) */
754
+ cdpPort?: number;
755
+ /** Optional initial URL to load inside the first Electron window */
756
+ url?: string;
757
+ /** Optional spana-bridge DOM channel */
758
+ domChannel?: DomChannel;
759
+ /** Injectable launchers for unit testing */
760
+ launchElectron?: typeof _electron.launch;
761
+ connectOverCDP?: typeof chromium.connectOverCDP;
762
+ }
763
+ /**
764
+ * Create a Spana driver for Electron apps.
765
+ *
766
+ * Uses Playwright's `_electron.launch()` by default (zero extra setup), or
767
+ * connects via CDP (`chromium.connectOverCDP`) when `cdpUrl` / `cdpPort` is
768
+ * specified. Reuses the running Electron process across flows and resets
769
+ * storage cleanly between runs.
770
+ */
771
+ declare function makeElectronDriver(options: ElectronDriverOptions): Effect.Effect<RawDriverService, DriverError>;
772
+
773
+ interface ElectrobunLaunchPlan {
774
+ renderer: ElectrobunRenderer;
775
+ engine: TargetEngine;
776
+ hostOs: HostOS;
777
+ preferredChannels: TargetChannel[];
778
+ env: Record<string, string>;
779
+ args: string[];
780
+ cdpUrl?: string;
781
+ webkitInspectorUrl?: string;
782
+ notes: string;
783
+ }
784
+ /**
785
+ * Resolve the exact Electrobun engine flags & environment variables for each
786
+ * OS and renderer combination:
787
+ *
788
+ * - Bundled CEF (`renderer: "cef"`):
789
+ * Passes `--remote-debugging-port=<port>` + `ELECTROBUN_CDP_PORT=<port>`.
790
+ * In packaged builds, also configure `build.<os>.chromiumFlags["remote-debugging-port"]`
791
+ * in `electrobun.config.ts`.
792
+ * - Windows native (`WebView2`):
793
+ * Sets `WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS="--remote-debugging-port=<port>"`
794
+ * and `ELECTROBUN_CDP_PORT=<port>`, then attaches via CDP.
795
+ * - macOS native (`WKWebView`):
796
+ * Uses `spana-bridge` (preferred) or WebKit Remote Inspector (`webkitInspectorPort`).
797
+ * - Linux native (`WebKitGTK`):
798
+ * Sets `WEBKIT_INSPECTOR_SERVER=127.0.0.1:<port>` and attaches via `spana-bridge`
799
+ * or WebKit Inspector / WebKitWebDriver.
800
+ */
801
+ declare function resolveElectrobunLaunchPlan(config: ElectrobunAppConfig, hostOs?: HostOS): ElectrobunLaunchPlan;
802
+ interface ElectrobunDriverOptions extends ElectrobunAppConfig {
803
+ /** Optional spana-bridge DOM channel (recommended for cross-OS consistency on Electrobun) */
804
+ domChannel?: DomChannel;
805
+ hostOs?: HostOS;
806
+ /** Optional custom spawner for testing */
807
+ spawnProcess?: typeof spawn;
808
+ /** Skip spawning executable (e.g. attach-only mode) */
809
+ attachOnly?: boolean;
810
+ }
811
+ declare function makeElectrobunDriver(options: ElectrobunDriverOptions): Effect.Effect<RawDriverService, DriverError>;
812
+
813
+ type WarmDaemonKind = "wda" | "uiautomator2" | "iproxy" | "chromium";
814
+ interface WarmDaemonRecord {
815
+ kind: WarmDaemonKind;
816
+ deviceId: string;
817
+ host: string;
818
+ port: number;
819
+ pid?: number;
820
+ tunnelPid?: number;
821
+ xctestrunPath?: string;
822
+ /** Optional reusable WDA/UiAutomator2 session ID persisted across runs */
823
+ sessionId?: string;
824
+ bundleId?: string;
825
+ startedAt: string;
826
+ }
827
+ /** Persist a warm WDA/UiAutomator2 session ID on an existing daemon record for cross-run reuse. */
828
+ declare function updateWarmDaemonSession(kind: WarmDaemonKind, deviceId: string, sessionId: string, bundleId?: string, stateFile?: string): void;
829
+ declare function listWarmDaemons(stateFile?: string): WarmDaemonRecord[];
830
+ /**
831
+ * Probe whether a recorded warm WDA / UiAutomator2 daemon is still healthy on
832
+ * `GET http://<host>:<port>/status`. Removes stale records automatically.
833
+ */
834
+ declare function getHealthyWarmDaemon(kind: WarmDaemonKind, deviceId: string, options?: {
835
+ stateFile?: string;
836
+ fetchFn?: typeof fetch;
837
+ timeoutMs?: number;
838
+ /** HTTP health endpoint path (default: "/status", use "/json/version" for chromium). */
839
+ statusPath?: string;
840
+ }): Promise<WarmDaemonRecord | null>;
841
+ /**
842
+ * Stop only the specific process PIDs started by Spana for this daemon record.
843
+ */
844
+ declare function stopWarmDaemon(kind: WarmDaemonKind, deviceId: string, stateFile?: string): boolean;
845
+ declare function stopAllWarmDaemons(stateFile?: string): number;
846
+
152
847
  interface ProviderRunResult {
153
848
  passed: boolean;
154
849
  name?: string;
@@ -165,4 +860,626 @@ interface CloudProvider {
165
860
  reportResult(appiumUrl: string, meta: Record<string, string>, result: ProviderRunResult): Promise<void>;
166
861
  }
167
862
 
168
- export { AppConfig, type Attachment, type CloudProvider, type CloudProviderHelper, type FailureCategory, type FlowError, type FlowResult, Platform, type Reporter, type RunSummary, type ScenarioStepResult, type StepResult };
863
+ interface GitHubPrReporterOptions {
864
+ /** Directory where `github-pr-summary.md` is written (default: `./spana-output`). */
865
+ outputDir?: string;
866
+ /** Optional filter summary lines (from `--changed-since` filters) to include in the comment. */
867
+ filterSummaries?: string[];
868
+ /** Write to `process.env.GITHUB_STEP_SUMMARY` automatically when present (default: true). */
869
+ writeStepSummary?: boolean;
870
+ }
871
+ /**
872
+ * Format a concise Markdown summary suitable for GitHub Actions Job Summaries
873
+ * and Pull Request comments (inspired by `@e2e-dev/github`).
874
+ */
875
+ declare function formatGitHubPrMarkdown(summary: RunSummary, filterSummaries?: string[]): string;
876
+ /**
877
+ * Built-in `"github"` reporter: writes `github-pr-summary.md` to the artifact
878
+ * output directory and appends to `$GITHUB_STEP_SUMMARY` in GitHub Actions.
879
+ */
880
+ declare function createGitHubPrReporter(options?: GitHubPrReporterOptions): Reporter;
881
+
882
+ /** A file changed between `baseRef` and `HEAD` (or working tree). */
883
+ interface ChangedFile {
884
+ path: string;
885
+ status: "A" | "M" | "D" | "R" | "C" | string;
886
+ }
887
+ /** Git diff snapshot provided to test filters when `--changed-since <ref>` is active. */
888
+ interface GitChanges {
889
+ baseRef: string;
890
+ mergeBase?: string;
891
+ files: string[];
892
+ entries: ChangedFile[];
893
+ /** Unified diff text (truncated when exceeding `maxDiffBytes`). */
894
+ diff: string;
895
+ /** Full byte length of the raw diff before truncation. */
896
+ diffBytes: number;
897
+ /** True when the diff exceeded the configured safety cap. */
898
+ truncated: boolean;
899
+ }
900
+ /** Descriptor for a candidate flow passed into a `TestFilter`. */
901
+ interface FilterCandidate {
902
+ id: string;
903
+ name: string;
904
+ file: string;
905
+ tags: string[];
906
+ platforms?: Platform[];
907
+ source?: string;
908
+ }
909
+ /** Context supplied to every `TestFilter.filter()` invocation. */
910
+ interface FilterContext {
911
+ cwd: string;
912
+ changes: GitChanges;
913
+ configPath?: string;
914
+ platforms: Platform[];
915
+ }
916
+ interface FilterUsage {
917
+ calls?: number;
918
+ tokens?: number;
919
+ costUsd?: number;
920
+ }
921
+ interface FilterDecisionOutput {
922
+ /** Map of candidate `id` -> human-readable skip reason. Any ID not present is kept. */
923
+ exclude: Record<string, string>;
924
+ /** Optional summary note displayed next to the filter output. */
925
+ note?: string;
926
+ /** Optional model/API usage metrics for summary logging. */
927
+ usage?: FilterUsage;
928
+ }
929
+ /**
930
+ * Pluggable CI test filter inspired by `e2e-inc/e2e`'s Filters API.
931
+ * Compose deterministic path/tag rules or plug in a decision model / LLM.
932
+ */
933
+ interface TestFilter {
934
+ name: string;
935
+ filter(flows: FilterCandidate[], context: FilterContext): Promise<FilterDecisionOutput> | FilterDecisionOutput;
936
+ }
937
+ interface AppliedFilterReport {
938
+ filterName: string;
939
+ total: number;
940
+ kept: number;
941
+ excluded: number;
942
+ note?: string;
943
+ usage?: FilterUsage;
944
+ failedOpen?: boolean;
945
+ }
946
+ interface ApplyFiltersResult<T> {
947
+ kept: T[];
948
+ excluded: Array<{
949
+ item: T;
950
+ candidate: FilterCandidate;
951
+ filterName: string;
952
+ reason: string;
953
+ }>;
954
+ reports: AppliedFilterReport[];
955
+ }
956
+ /**
957
+ * Collect changed files and unified diff relative to `baseRef` using `git merge-base`.
958
+ * Fails cleanly if git is unavailable or `baseRef` does not exist (shallow checkout).
959
+ */
960
+ declare function collectGitChanges(baseRef: string, cwd?: string, maxDiffBytes?: number, runGit?: (args: string[], workdir: string) => string): GitChanges;
961
+ /** Build filter candidates from loaded Spana flows (including source file content when readable). */
962
+ declare function buildFilterCandidates(loaded: Array<{
963
+ sourcePath: string;
964
+ flow: FlowDefinition;
965
+ }>, cwd?: string): FilterCandidate[];
966
+ interface DecisionJudgeInput {
967
+ candidate: FilterCandidate;
968
+ changes: GitChanges;
969
+ }
970
+ interface DecisionJudgeResult {
971
+ /** Probability [0..1] that the PR changes can affect this flow. */
972
+ probability: number;
973
+ reason?: string;
974
+ usage?: FilterUsage;
975
+ }
976
+ type DecisionModelJudge = (input: DecisionJudgeInput) => Promise<DecisionJudgeResult> | DecisionJudgeResult;
977
+ interface DecisionBatchJudgeResult {
978
+ /** Map of candidate `id` -> probability `[0, 1]` that the PR changes affect it. */
979
+ probabilities: Record<string, number>;
980
+ reasons?: Record<string, string>;
981
+ usage?: FilterUsage;
982
+ }
983
+ type DecisionBatchJudge = (input: {
984
+ candidates: FilterCandidate[];
985
+ changes: GitChanges;
986
+ }) => Promise<DecisionBatchJudgeResult> | DecisionBatchJudgeResult;
987
+ interface DecisionFilterOptions {
988
+ /** Optional custom name (default: "decision") */
989
+ name?: string;
990
+ /**
991
+ * Per-flow model judge function returning an impact probability in `[0, 1]`.
992
+ * Provide either `judge` or `batchJudge` (batched evaluates all flows in 1 LLM call).
993
+ */
994
+ judge?: DecisionModelJudge;
995
+ /**
996
+ * Batched model judge evaluating all candidate flows in a single model call
997
+ * (dramatically faster for local Ollama/MLX models and cloud decision models).
998
+ */
999
+ batchJudge?: DecisionBatchJudge;
1000
+ /**
1001
+ * Skip a flow only when `probability < threshold`.
1002
+ * Default: `0.20` (fail-open safety bias — runs anything >= 20% likely affected).
1003
+ */
1004
+ threshold?: number;
1005
+ /** Max diff size in bytes before failing open and running everything. Default: 60 kB. */
1006
+ maxDiffBytes?: number;
1007
+ /** Max single flow file size in bytes before failing open for that flow. Default: 32 kB. */
1008
+ maxFileBytes?: number;
1009
+ /** Tags that are NEVER excluded (e.g. `["smoke"]`). */
1010
+ alwaysRunTags?: string[];
1011
+ /** Path prefixes that force the entire suite to run (e.g. `["infra/", "db/migrations/"]`). */
1012
+ runAllOnPaths?: string[];
1013
+ }
1014
+ /**
1015
+ * Create a fail-open decision-model filter for `--changed-since`:
1016
+ *
1017
+ * Safety invariants (never skip important tests):
1018
+ * 1. Changed flow files always run.
1019
+ * 2. Config or lockfile changes run the entire suite.
1020
+ * 3. Diffs over `maxDiffBytes` (default 60 kB) run the entire suite.
1021
+ * 4. Flows tagged in `alwaysRunTags` always run.
1022
+ * 5. Any judge error or invalid probability fails open (flow runs).
1023
+ * 6. A flow is excluded only when `probability < threshold` (default 0.20).
1024
+ */
1025
+ declare function decisionFilter(options: DecisionFilterOptions): TestFilter;
1026
+ interface OllamaDecisionJudgeOptions {
1027
+ /** Ollama model tag, e.g. `"qwen2.5:1.5b"` or `"qwen2.5:0.5b"`. */
1028
+ model: string;
1029
+ /** Ollama HTTP endpoint (default: `"http://127.0.0.1:11434"`). */
1030
+ baseUrl?: string;
1031
+ /** Request timeout in ms (default: 15000). */
1032
+ timeoutMs?: number;
1033
+ /** Optional custom fetch implementation for testing. */
1034
+ fetchFn?: typeof fetch;
1035
+ }
1036
+ /**
1037
+ * Built-in local batched decision judge for Ollama (Apple Silicon / local GPU).
1038
+ * Evaluates all candidate flows against a PR diff in ONE structured JSON call
1039
+ * with `temperature: 0` and zero cloud token cost ($0.0000).
1040
+ */
1041
+ declare function createOllamaDecisionJudge(options: OllamaDecisionJudgeOptions): DecisionBatchJudge;
1042
+ interface LogprobDecisionJudgeOptions {
1043
+ /** Model identifier (e.g. `"hf.co/apus-ailab/APUS-OpenJev-v1-9B-GGUF:Q8_0"`, `"jevk5-4b-v0.3:q8_0"`, `"decider4b-v2:bf16"`, `"plumb-4b"`). */
1044
+ model: string;
1045
+ /** Protocol backend: `"openai"` (vLLM / SGLang / llama-server / OpenRouter / Typesafe AI) or `"ollama"`. */
1046
+ provider: "openai" | "ollama";
1047
+ /** Base URL (default: `http://127.0.0.1:8000/v1` for openai, `http://127.0.0.1:11434` for ollama). */
1048
+ baseUrl?: string;
1049
+ /** Optional Bearer API key for hosted OpenAI-compatible endpoints. */
1050
+ apiKey?: string;
1051
+ /** Request timeout per flow judgment in ms (default: 15000). */
1052
+ timeoutMs?: number;
1053
+ /** Injectable fetch for unit tests. */
1054
+ fetchFn?: typeof fetch;
1055
+ }
1056
+ /**
1057
+ * Compute calibrated binary YES probability from OpenAI-style `top_logprobs`
1058
+ * on a 1-token decision model response (`max_tokens: 1`, `logprobs: true`).
1059
+ * Returns `null` when neither YES nor NO tokens appeared in top_logprobs.
1060
+ */
1061
+ declare function probabilityFromTopLogprobs(topLogprobs: Array<{
1062
+ token: string;
1063
+ logprob: number;
1064
+ }>): number | null;
1065
+ /**
1066
+ * Native 1-Token Logprob Decision Judge for System-1 decision models
1067
+ * (OpenJev, JevK5, Decider-4B, Plumb-4B, Winnow-12B, Typesafe AI Jev).
1068
+ *
1069
+ * Places the shared git diff prefix at the start of every prompt so vLLM,
1070
+ * SGLang, and llama.cpp automatically reuse the KV cache across all flows in a PR,
1071
+ * generating only **1 single token** (`YES` / `NO`) with exact calibrated probabilities.
1072
+ */
1073
+ declare function createLogprobDecisionJudge(options: LogprobDecisionJudgeOptions): DecisionModelJudge;
1074
+ interface PathRule {
1075
+ /** Flow tag or path prefix this rule owns. */
1076
+ matchFlow: {
1077
+ tag?: string;
1078
+ filePrefix?: string;
1079
+ };
1080
+ /** Source path prefixes that can affect matching flows. */
1081
+ watchPaths: string[];
1082
+ }
1083
+ interface PathRuleFilterOptions {
1084
+ name?: string;
1085
+ rules: PathRule[];
1086
+ alwaysRunTags?: string[];
1087
+ runAllOnPaths?: string[];
1088
+ }
1089
+ /**
1090
+ * 100% deterministic zero-LLM filter mapping repo path prefixes to flow tags/files.
1091
+ * Flows not matched by any rule fail open and run automatically.
1092
+ */
1093
+ declare function pathRuleFilter(options: PathRuleFilterOptions): TestFilter;
1094
+ interface DeterministicImpactFilterOptions {
1095
+ name?: string;
1096
+ /** Additional path-to-flow rules combined with automatic static import-graph tracing. */
1097
+ pathMappings?: PathRule[];
1098
+ /** Flow tags that are NEVER skipped (e.g. `["smoke"]`). */
1099
+ alwaysRunTags?: string[];
1100
+ /** Path prefixes that force the entire suite to run (e.g. `["src/shared/", "db/"]`). */
1101
+ runAllOnPaths?: string[];
1102
+ /**
1103
+ * When true (default), if a changed file is NOT imported by any flow and does not
1104
+ * match any `pathMappings`, fail open and run all flows so unmapped app changes are
1105
+ * never silently missed. Set to `false` for strict import-graph-only selection.
1106
+ */
1107
+ failOpenOnUnmappedChange?: boolean;
1108
+ /** Max recursive import depth to trace from each flow file. Default: 12. */
1109
+ maxDepth?: number;
1110
+ }
1111
+ /**
1112
+ * 100% deterministic, zero-AI test impact filter for `--changed-since`.
1113
+ *
1114
+ * Recursively traces static ESM/CJS imports (`import`, `export ... from`, `require`)
1115
+ * from every `.flow.ts` file and combines them with optional `pathMappings`.
1116
+ * Fails open on config/lockfile changes, `runAllOnPaths`, and (by default) any
1117
+ * changed file not covered by any import graph or path mapping.
1118
+ */
1119
+ declare function deterministicImpactFilter(options?: DeterministicImpactFilterOptions): TestFilter;
1120
+ /**
1121
+ * Run a chain of `TestFilter`s sequentially over candidate flows.
1122
+ * Any filter that throws fails open (keeps all remaining flows) and logs a note.
1123
+ */
1124
+ declare function applyTestFilters<T>(items: T[], candidates: FilterCandidate[], filters: TestFilter[], context: FilterContext): Promise<ApplyFiltersResult<T>>;
1125
+ /** Format a concise, `e2e`-style CI summary line for each applied filter. */
1126
+ declare function formatFilterSummary(reports: AppliedFilterReport[]): string[];
1127
+
1128
+ /**
1129
+ * Declarative named setup state (e.g. `"admin"`, `"authenticated"`, `"seeded-cart"`).
1130
+ * Automatically uses `spana-bridge` storage injection on mobile/desktop/bridge-web
1131
+ * and Playwright `loadAuthState` / `evaluate` on web.
1132
+ */
1133
+ interface NamedSetupDefinition<T extends string = string, R extends string = string> {
1134
+ name: string;
1135
+ /** Clear storage before restoring state (default: true). */
1136
+ clearBefore?: boolean | DomClearStorageOptions;
1137
+ /** Storage entries injected via `app.setStorage(...)` (localStorage/sessionStorage/cookies/Preferences). */
1138
+ storage?: DomStorageEntries;
1139
+ /** Optional Playwright storageState JSON file path for web runs. */
1140
+ storageStatePath?: string;
1141
+ /** Optional URL/route to navigate to after injecting state (or `reload` when omitted and storage was injected). */
1142
+ navigateTo?: R;
1143
+ /** Whether to reload the WebView/page after injecting storage when `navigateTo` is omitted (default: true). */
1144
+ reloadAfterStorage?: boolean;
1145
+ /** Optional custom setup hook for seeding API state or performing extra actions. */
1146
+ run?: (ctx: FlowContext<T, R>) => Promise<void>;
1147
+ }
1148
+ /** Define a reusable named setup state for `{ session: "<name>" }` flows. */
1149
+ declare function defineSetup<T extends string = string, R extends string = string>(name: string, config: Omit<NamedSetupDefinition<T, R>, "name">): NamedSetupDefinition<T, R>;
1150
+ /** Apply a named setup state to the active `FlowContext`. */
1151
+ declare function applyNamedSetup<T extends string = string, R extends string = string>(setup: NamedSetupDefinition<T, R>, ctx: FlowContext<T, R>): Promise<void>;
1152
+ type FixtureFn<Value, Deps extends Record<string, unknown>, T extends string = string, R extends string = string> = (ctx: FlowContext<T, R> & Deps, use: (value: Value) => Promise<void>) => Promise<void>;
1153
+ type FixtureDefinition<Value, Deps extends Record<string, unknown>, T extends string = string, R extends string = string> = FixtureFn<Value, Deps, T, R> | {
1154
+ setup: FixtureFn<Value, Deps, T, R>;
1155
+ /** When true, always runs for every flow even if not destructured. */
1156
+ auto?: boolean;
1157
+ /** Explicit fixture dependency names (optional — also inferred from parameter destructuring). */
1158
+ deps?: Array<keyof Deps & string>;
1159
+ };
1160
+ type FixtureMap<Fixtures extends Record<string, unknown>, T extends string = string, R extends string = string> = {
1161
+ [K in keyof Fixtures]: FixtureDefinition<Fixtures[K], Omit<Fixtures, K>, T, R>;
1162
+ };
1163
+ interface ExtendedFlowConfig<R extends string = string, SessionName extends string = string> extends FlowConfig<R> {
1164
+ /** Optional named setup state applied before any lazy fixtures run. */
1165
+ session?: SessionName;
1166
+ /** Optional explicit fixture names to activate (in addition to destructured params). */
1167
+ uses?: string[];
1168
+ }
1169
+ /**
1170
+ * Extract top-level destructured parameter names from the first argument of a function:
1171
+ * `async ({ app, project, task: t }) => ...` -> `["app", "project", "task"]`
1172
+ */
1173
+ declare function extractDestructuredParamNames(fn: (...args: any[]) => unknown): string[];
1174
+ interface CreateFixturesOptions<Fixtures extends Record<string, unknown>, SessionName extends string = string, T extends string = string, R extends string = string> {
1175
+ fixtures?: FixtureMap<Fixtures, T, R>;
1176
+ setups?: Record<SessionName, NamedSetupDefinition<T, R>>;
1177
+ }
1178
+ /**
1179
+ * Create a `flow()` builder enhanced with lazy composable fixtures and named
1180
+ * setup states (`{ session: "admin" }`), inspired by Playwright and `e2e`.
1181
+ *
1182
+ * - Fixtures only run when destructured by the flow (or marked `{ auto: true }`).
1183
+ * - Fixtures can depend on other fixtures; cycles are detected immediately.
1184
+ * - Teardown runs in strict reverse (LIFO) order even when the flow throws.
1185
+ */
1186
+ declare function createFlowWithFixtures<Fixtures extends Record<string, unknown> = Record<string, never>, SessionName extends string = string, T extends string = string, R extends string = string>(options: CreateFixturesOptions<Fixtures, SessionName, T, R>): {
1187
+ (name: string, fn: (ctx: FlowContext<T, R> & Fixtures) => Promise<void>): FlowDefinition<T, R>;
1188
+ (name: string, config: ExtendedFlowConfig<R, SessionName>, fn: (ctx: FlowContext<T, R> & Fixtures) => Promise<void>): FlowDefinition<T, R>;
1189
+ };
1190
+ interface ApiClientOptions {
1191
+ /** Base URL for API/test-control endpoints (e.g. `"http://localhost:3000/api"`). */
1192
+ baseUrl: string;
1193
+ /** Default headers attached to every request (e.g. `{ Authorization: "Bearer ..." }`). */
1194
+ headers?: Record<string, string>;
1195
+ /** Optional custom fetch implementation for testing. */
1196
+ fetchFn?: typeof fetch;
1197
+ }
1198
+ interface ApiRequestOptions {
1199
+ headers?: Record<string, string>;
1200
+ query?: Record<string, string | number | boolean | undefined>;
1201
+ signal?: AbortSignal;
1202
+ }
1203
+ interface ApiResponse<T = unknown> {
1204
+ status: number;
1205
+ ok: boolean;
1206
+ headers: Headers;
1207
+ data: T;
1208
+ }
1209
+ interface ApiClient {
1210
+ get<T = unknown>(path: string, opts?: ApiRequestOptions): Promise<ApiResponse<T>>;
1211
+ post<T = unknown>(path: string, body?: unknown, opts?: ApiRequestOptions): Promise<ApiResponse<T>>;
1212
+ put<T = unknown>(path: string, body?: unknown, opts?: ApiRequestOptions): Promise<ApiResponse<T>>;
1213
+ patch<T = unknown>(path: string, body?: unknown, opts?: ApiRequestOptions): Promise<ApiResponse<T>>;
1214
+ delete<T = unknown>(path: string, opts?: ApiRequestOptions): Promise<ApiResponse<T>>;
1215
+ /** Register an automatic teardown callback (runs in strict LIFO order on `cleanup()`). */
1216
+ onCleanup(fn: () => Promise<void> | void): void;
1217
+ /** Run all registered cleanup callbacks in reverse (LIFO) order and clear the queue. */
1218
+ cleanup(): Promise<void>;
1219
+ }
1220
+ /**
1221
+ * First-class HTTP client for seeding and tearing down test data via API/test-control
1222
+ * endpoints inside Spana flows and lazy fixtures (far faster than UI setup).
1223
+ */
1224
+ declare function createApiClient(options: ApiClientOptions): ApiClient;
1225
+ /**
1226
+ * Convenience lazy fixture builder for `createFlowWithFixtures`:
1227
+ * provides a fresh `ApiClient` to each flow and automatically executes all
1228
+ * `api.onCleanup(...)` hooks in LIFO order even when the flow throws.
1229
+ */
1230
+ declare function createApiFixture<Deps extends Record<string, unknown> = Record<string, never>, T extends string = string, R extends string = string>(options: ApiClientOptions | ((ctx: FlowContext<T, R> & Deps) => ApiClientOptions)): FixtureFn<ApiClient, Deps, T, R>;
1231
+ interface PersonaDefinition<T extends string = string, R extends string = string> {
1232
+ name: string;
1233
+ /** Sign in once (via API, virtual passkey, or UI) and return storage entries or a saved storageStatePath. */
1234
+ signIn: (ctx: FlowContext<T, R>) => Promise<{
1235
+ storage?: DomStorageEntries;
1236
+ storageStatePath?: string;
1237
+ } | void>;
1238
+ /** Optional cache key discriminator (e.g. base URL or tenant ID). */
1239
+ cacheKey?: string;
1240
+ /** Optional route to navigate to after restoring cached auth state. */
1241
+ navigateTo?: R;
1242
+ }
1243
+ /** Define a reusable authenticated persona for `PersonaAuthCache`. */
1244
+ declare function definePersona<T extends string = string, R extends string = string>(name: string, config: Omit<PersonaDefinition<T, R>, "name">): PersonaDefinition<T, R>;
1245
+ interface CachedPersonaState {
1246
+ storage?: DomStorageEntries;
1247
+ storageStatePath?: string;
1248
+ cachedAt: number;
1249
+ }
1250
+ /**
1251
+ * In-memory per-persona auth state cache (single-flight safe across parallel workers).
1252
+ * Signs a persona in ONCE (including passkey / WebAuthn flows), caches its auth state,
1253
+ * and restores it in milliseconds across all remaining flows.
1254
+ */
1255
+ declare class PersonaAuthCache {
1256
+ private readonly cache;
1257
+ private readonly inflight;
1258
+ private keyFor;
1259
+ get(name: string, cacheKey?: string): CachedPersonaState | undefined;
1260
+ invalidate(name?: string, cacheKey?: string): void;
1261
+ /**
1262
+ * Ensure `persona` is authenticated in `ctx`. On cache miss, executes `persona.signIn(ctx)`
1263
+ * once (coalescing concurrent callers); on cache hit, restores cookies/storageState directly.
1264
+ */
1265
+ authenticate<T extends string = string, R extends string = string>(persona: PersonaDefinition<T, R>, ctx: FlowContext<T, R>): Promise<CachedPersonaState>;
1266
+ }
1267
+
1268
+ /** A deterministic action recorded from an `agent.act(goal)` execution. */
1269
+ type RecordedAction = {
1270
+ kind: "tap";
1271
+ selector: ExtendedSelector;
1272
+ } | {
1273
+ kind: "doubleTap";
1274
+ selector: ExtendedSelector;
1275
+ } | {
1276
+ kind: "longPress";
1277
+ selector: ExtendedSelector;
1278
+ } | {
1279
+ kind: "inputText";
1280
+ text: string;
1281
+ } | {
1282
+ kind: "pressKey";
1283
+ key: string;
1284
+ } | {
1285
+ kind: "scroll";
1286
+ direction: "up" | "down" | "left" | "right";
1287
+ } | {
1288
+ kind: "scrollUntilVisible";
1289
+ selector: ExtendedSelector;
1290
+ } | {
1291
+ kind: "openLink";
1292
+ url: string;
1293
+ };
1294
+ interface ReplayCacheEntry {
1295
+ schemaVersion: 1;
1296
+ key: string;
1297
+ goal: string;
1298
+ flowName: string;
1299
+ platform: string;
1300
+ actions: RecordedAction[];
1301
+ recordedAt: string;
1302
+ verifiedBy: string;
1303
+ }
1304
+ type ReplayCacheMode = "read-write" | "strict" | "off";
1305
+ type CacheWriteStatus = "saved" | "kept" | "unconfirmed" | "evicted" | "skipped";
1306
+ interface ReplayStepOutcome {
1307
+ goal: string;
1308
+ key: string;
1309
+ status: "replayed" | "handed-off" | "missed" | "live";
1310
+ writeStatus?: CacheWriteStatus;
1311
+ actionCount: number;
1312
+ error?: string;
1313
+ }
1314
+ interface ReplayCacheSummary {
1315
+ replayed: number;
1316
+ handedOff: number;
1317
+ missed: number;
1318
+ saved: number;
1319
+ evicted: number;
1320
+ unconfirmed: number;
1321
+ }
1322
+ /**
1323
+ * Pluggable agent executor called ONLY on cache miss or self-healing handoff.
1324
+ * Returns the deterministic list of actions it executed to achieve `goal`.
1325
+ */
1326
+ interface AgentActExecutor {
1327
+ act(input: {
1328
+ goal: string;
1329
+ app: PromiseApp;
1330
+ handoffReason?: string;
1331
+ }): Promise<{
1332
+ actions: RecordedAction[];
1333
+ }>;
1334
+ }
1335
+ /** Compute a stable cache key for a `(flowName, platform, goal)` tuple. */
1336
+ declare function buildReplayCacheKey(flowName: string, platform: string, goal: string): string;
1337
+ /** Disk-backed replay cache store (default directory: `.spana/cache`). */
1338
+ declare class ReplayCacheStore {
1339
+ readonly cacheDir: string;
1340
+ constructor(cacheDir?: string);
1341
+ private filePath;
1342
+ get(key: string): ReplayCacheEntry | null;
1343
+ set(entry: ReplayCacheEntry): void;
1344
+ delete(key: string): boolean;
1345
+ }
1346
+ /** Execute a single recorded deterministic action against `PromiseApp`. */
1347
+ declare function replayRecordedAction(app: PromiseApp, action: RecordedAction): Promise<void>;
1348
+ interface ReplaySessionOptions {
1349
+ flowName: string;
1350
+ platform: string;
1351
+ app: PromiseApp;
1352
+ store?: ReplayCacheStore;
1353
+ mode?: ReplayCacheMode;
1354
+ executor?: AgentActExecutor;
1355
+ }
1356
+ /**
1357
+ * Verified Replay Cache session inspired by `e2e-inc/e2e`:
1358
+ *
1359
+ * - On cache hit: replays deterministic `{ testID }` / `systemUI()` actions with ZERO LLM calls.
1360
+ * - In `strict` mode (`--strict-cache`): fails deterministically if a recording is missing or no longer matches.
1361
+ * - In `read-write` mode: hands off to `executor` on miss or mismatch (self-healing), and ONLY commits
1362
+ * new/healed recordings to `.spana/cache/` after `markVerified(verifierName)` is called by a real assertion!
1363
+ */
1364
+ declare class ReplaySession {
1365
+ private readonly flowName;
1366
+ private readonly platform;
1367
+ private readonly app;
1368
+ private readonly store;
1369
+ private readonly mode;
1370
+ private readonly executor?;
1371
+ private pendingWrites;
1372
+ private replayedKeys;
1373
+ private outcomes;
1374
+ constructor(options: ReplaySessionOptions);
1375
+ /** Execute a natural-language goal using replay cache first, falling back to `executor`. */
1376
+ act(goal: string): Promise<ReplayStepOutcome>;
1377
+ private runLiveAndQueue;
1378
+ /**
1379
+ * Call when a real post-action assertion (`expect(...).toBeVisible()`, `toHaveText()`, etc.)
1380
+ * succeeds. Flushes all preceding pending recordings to disk in `read-write` mode.
1381
+ */
1382
+ markVerified(verifierName: string): number;
1383
+ /**
1384
+ * Call when the flow attempt fails: evicts any replayed recordings involved in the
1385
+ * failure (in `read-write` mode) and discards unconfirmed recordings so broken paths
1386
+ * are never persisted.
1387
+ */
1388
+ markFailed(): number;
1389
+ getOutcomes(): ReplayStepOutcome[];
1390
+ getSummary(): ReplayCacheSummary;
1391
+ }
1392
+
1393
+ interface NativePngCompareResult {
1394
+ match: boolean;
1395
+ sizeMismatch: boolean;
1396
+ diffPixelCount: number;
1397
+ diffPixelRatio: number;
1398
+ diffImage?: Buffer;
1399
+ }
1400
+ interface NativeXmlRawNode {
1401
+ tagName: string;
1402
+ attrs: Record<string, string>;
1403
+ children: NativeXmlRawNode[];
1404
+ }
1405
+ /** Check whether Spana's native Rust accelerator (`libspana_native`) is loaded and active. */
1406
+ declare function isNativeAcceleratorActive(): boolean;
1407
+ /** Return the loaded native Rust library path, or `null` when running in pure-JS fallback mode. */
1408
+ declare function getNativeAcceleratorPath(): string | null;
1409
+ /** Accelerated Rust PNG diff (returns `null` if unavailable so caller falls back cleanly to JS). */
1410
+ declare function comparePngNative(expected: Buffer | Uint8Array, actual: Buffer | Uint8Array, threshold: number, maxDiffRatio: number, layoutTolerant: boolean): NativePngCompareResult | null;
1411
+ /** Accelerated Rust XML hierarchy tokenizer (returns `null` if unavailable so caller falls back to JS). */
1412
+ declare function tokenizeXmlNative(xml: string, wrapperTag: string): NativeXmlRawNode[] | null;
1413
+
1414
+ /** MCP Tool definition advertised by `tools/list`. */
1415
+ interface McpToolDefinition {
1416
+ name: string;
1417
+ description: string;
1418
+ inputSchema: {
1419
+ type: "object";
1420
+ properties: Record<string, unknown>;
1421
+ required?: string[];
1422
+ };
1423
+ }
1424
+ interface McpContentBlock {
1425
+ type: "text" | "image";
1426
+ text?: string;
1427
+ data?: string;
1428
+ mimeType?: string;
1429
+ }
1430
+ interface McpToolResult {
1431
+ content: McpContentBlock[];
1432
+ isError?: boolean;
1433
+ }
1434
+ interface JsonRpcRequest {
1435
+ jsonrpc: "2.0";
1436
+ id?: string | number | null;
1437
+ method: string;
1438
+ params?: Record<string, unknown>;
1439
+ }
1440
+ interface JsonRpcResponse {
1441
+ jsonrpc: "2.0";
1442
+ id: string | number | null;
1443
+ result?: unknown;
1444
+ error?: {
1445
+ code: number;
1446
+ message: string;
1447
+ data?: unknown;
1448
+ };
1449
+ }
1450
+ interface SpanaMcpServerOptions {
1451
+ /** Custom session connector (defaults to `connect()` from `agent/session.js`). */
1452
+ connectFn?: (opts: ConnectOptions) => Promise<Session>;
1453
+ /** Custom flow runner for `spana_run_flow` (defaults to `runTestCommand`). */
1454
+ runFlowFn?: (opts: {
1455
+ flowPath: string;
1456
+ platform?: Platform;
1457
+ }) => Promise<boolean>;
1458
+ }
1459
+ /** Format a Spana selector into clean TypeScript code for verified `.flow.ts` generation. */
1460
+ declare function formatSelectorCode(selector: ExtendedSelector): string;
1461
+ /** Generate a complete `.flow.ts` file from recorded verified MCP actions. */
1462
+ declare function buildFlowFileFromLines(flowName: string, lines: string[]): string;
1463
+ declare const SPANA_MCP_TOOLS: McpToolDefinition[];
1464
+ /**
1465
+ * Model-free MCP (Model Context Protocol) server for Spana.
1466
+ *
1467
+ * Lets coding agents (Claude Code, Codex, Cursor, Antigravity) drive live
1468
+ * web, iOS, Android, Electron, and Electrobun sessions, inspect unified
1469
+ * DOM/native + console/error diagnostics, and receive verified `.flow.ts` lines.
1470
+ */
1471
+ declare class SpanaMcpServer {
1472
+ private session;
1473
+ private recordedLines;
1474
+ private readonly connectFn;
1475
+ private readonly runFlowFn;
1476
+ constructor(options?: SpanaMcpServerOptions);
1477
+ private requireSession;
1478
+ handleRequest(req: JsonRpcRequest): Promise<JsonRpcResponse | null>;
1479
+ callTool(name: string, args: Record<string, unknown>): Promise<McpToolResult>;
1480
+ private jsonResult;
1481
+ /** Run the server over newline-delimited JSON-RPC stdio until stdin closes. */
1482
+ runStdio(): Promise<void>;
1483
+ }
1484
+
1485
+ export { type AgentActExecutor, AndroidWebViewCdpChannel, type AndroidWebViewCdpOptions, type ApiClient, type ApiClientOptions, type ApiRequestOptions, type ApiResponse, AppConfig, AppleWebInspectorClient, type AppliedFilterReport, type ApplyFiltersResult, type Attachment, BrowserConsoleLog, BrowserJSError, BrowserMockResponse, BrowserName, BrowserRouteMatcher, type CacheWriteStatus, type CachedPersonaState, CdpDomChannel, type CdpDomChannelOptions, type ChangedFile, type CloudProvider, type CloudProviderHelper, type CreateFixturesOptions, type DecisionBatchJudge, type DecisionBatchJudgeResult, type DecisionFilterOptions, type DecisionModelJudge, type DeterministicImpactFilterOptions, type DirectCdpBrowserHandle, type DirectCdpBrowserLaunchOptions, DomChannel, DomClearStorageOptions, DomElementMatch, DomFillOptions, DomIdleOptions, DomStorageEntries, DomTargetInfo, DomWaitForHiddenOptions, DomWaitForMatchOptions, DomWaitForMatchResult, DomWaitForSelectorOptions, ElectrobunAppConfig, type ElectrobunDriverOptions, type ElectrobunLaunchPlan, ElectrobunRenderer, type ElectronDriverOptions, Element, type ExtendedFlowConfig, ExtendedSelector, type FailureCategory, type FilterCandidate, type FilterContext, type FilterDecisionOutput, type FilterUsage, type FixtureDefinition, type FixtureFn, type FixtureMap, FlowConfig, FlowContext, FlowDefinition, type FlowError, type FlowResult, type GitChanges, type GitHubPrReporterOptions, type HostOS, type JsonRpcRequest, type JsonRpcResponse, type LightweightCdpDriverOptions, type LogprobDecisionJudgeOptions, type McpContentBlock, type McpToolDefinition, type McpToolResult, type NamedSetupDefinition, type NativePngCompareResult, type NativeXmlRawNode, type OllamaDecisionJudgeOptions, type PathRule, type PathRuleFilterOptions, PersonaAuthCache, type PersonaDefinition, Platform, type PrelaunchedWebBrowser, PromiseApp, ProvConfig, type RecordedAction, type ReplayCacheEntry, type ReplayCacheMode, ReplayCacheStore, type ReplayCacheSummary, ReplaySession, type ReplaySessionOptions, type ReplayStepOutcome, type Reporter, type ResolvedElementResult, type RunSummary, SPANA_MCP_TOOLS, type ScenarioStepResult, Selector, SpanaBridgeChannel, type SpanaBridgeServerOptions, SpanaMcpServer, type SpanaMcpServerOptions, type StepResult, TARGET_CHANNEL_MATRIX, TapMode, type TargetChannel, type TargetDescriptor, type TargetEngine, type TargetShell, type TestFilter, VirtualAuthenticatorOptions, type WarmDaemonRecord, type WebInspectorListingPage, WebKitInspectorChannel, type WebKitInspectorOptions, applyNamedSetup, applyTestFilters, buildFilterCandidates, buildFlowFileFromLines, buildReplayCacheKey, collectGitChanges, comparePngNative, connectPlaywrightOverCDP, connectPlaywrightOverWS, createAndroidWebViewCdpChannel, createApiClient, createApiFixture, createCdpDomChannel, createCompositeDomChannel, createFlowWithFixtures, createGitHubPrReporter, createLogprobDecisionJudge, createOllamaDecisionJudge, createSpanaBridgeChannel, createWebKitInspectorChannel, decisionFilter, decodeWebInspectorFrames, definePersona, defineSetup, deterministicImpactFilter, domRectToScreenBounds, encodeWebInspectorPacket, ensureWarmBrowserDaemon, extractDestructuredParamNames, findSimulatorWebInspectorSocket, findWebViewFrame, formatFilterSummary, formatGitHubPrMarkdown, formatSelectorCode, formatTargetMatrixTable, getHealthyWarmDaemon, getNativeAcceleratorPath, invalidateWebViewFrameCache, isNativeAcceleratorActive, isOffscreenInViewport, launchDirectCdpBrowser, launchPlaywrightBrowser, listWarmDaemons, makeElectrobunDriver, makeElectronDriver, makeLightweightCdpDriver, orderFlowsLongestFirst, parseAndroidWebViewSockets, parseWebInspectorXmlFrame, pathRuleFilter, probabilityFromTopLogprobs, replayRecordedAction, resolveElectrobunEngine, resolveElectrobunLaunchPlan, resolveElementAcrossChannels, resolveTargetDescriptor, speculativelyPrelaunchWebBrowser, stopAllWarmDaemons, stopWarmDaemon, tokenizeXmlNative, updateWarmDaemonSession };