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.js CHANGED
@@ -1,9 +1,94 @@
1
- import "./chunk-LC3QJIHY.js";
1
+ import {
2
+ launchDirectCdpBrowser,
3
+ makeLightweightCdpDriver,
4
+ orderFlowsLongestFirst,
5
+ speculativelyPrelaunchWebBrowser
6
+ } from "./chunk-KEUZLBQS.js";
7
+ import {
8
+ SPANA_MCP_TOOLS,
9
+ SpanaMcpServer,
10
+ buildFlowFileFromLines,
11
+ formatSelectorCode
12
+ } from "./chunk-C4E4XULT.js";
2
13
  import {
3
14
  defineConfig
4
- } from "./chunk-7VOWF42B.js";
5
- import "./chunk-YAV6KBSW.js";
15
+ } from "./chunk-KBRLIQRA.js";
6
16
  import "./chunk-X2TJP7LB.js";
17
+ import {
18
+ createGitHubPrReporter,
19
+ formatGitHubPrMarkdown
20
+ } from "./chunk-LAMTF4LX.js";
21
+ import {
22
+ applyTestFilters,
23
+ buildFilterCandidates,
24
+ collectGitChanges,
25
+ createLogprobDecisionJudge,
26
+ createOllamaDecisionJudge,
27
+ decisionFilter,
28
+ deterministicImpactFilter,
29
+ formatFilterSummary,
30
+ pathRuleFilter,
31
+ probabilityFromTopLogprobs
32
+ } from "./chunk-3SH5JQF7.js";
33
+ import {
34
+ connectPlaywrightOverCDP,
35
+ connectPlaywrightOverWS,
36
+ domRectToScreenBounds,
37
+ ensureWarmBrowserDaemon,
38
+ findWebViewFrame,
39
+ invalidateWebViewFrameCache,
40
+ isOffscreenInViewport,
41
+ isSystemUISelector,
42
+ isTestIDSelector,
43
+ launchPlaywrightBrowser,
44
+ makeElectronDriver,
45
+ resolveElementAcrossChannels,
46
+ systemUI
47
+ } from "./chunk-PWUJT5HE.js";
48
+ import {
49
+ AndroidWebViewCdpChannel,
50
+ AppleWebInspectorClient,
51
+ CdpDomChannel,
52
+ SpanaBridgeChannel,
53
+ TARGET_CHANNEL_MATRIX,
54
+ WebKitInspectorChannel,
55
+ buildDomFillScript,
56
+ buildDomWaitForHiddenScript,
57
+ buildDomWaitForMatchScript,
58
+ buildDomWaitForSelectorScript,
59
+ createAndroidWebViewCdpChannel,
60
+ createCdpDomChannel,
61
+ createCompositeDomChannel,
62
+ createSpanaBridgeChannel,
63
+ createWebKitInspectorChannel,
64
+ decodeWebInspectorFrames,
65
+ encodeWebInspectorPacket,
66
+ findSimulatorWebInspectorSocket,
67
+ formatTargetMatrixTable,
68
+ makeElectrobunDriver,
69
+ parseAndroidWebViewSockets,
70
+ parseWebInspectorXmlFrame,
71
+ resolveElectrobunEngine,
72
+ resolveElectrobunLaunchPlan,
73
+ resolveTargetDescriptor
74
+ } from "./chunk-LCV673G3.js";
75
+ import "./chunk-HYSTRWYN.js";
76
+ import {
77
+ getHealthyWarmDaemon,
78
+ listWarmDaemons,
79
+ stopAllWarmDaemons,
80
+ stopWarmDaemon,
81
+ updateWarmDaemonSession
82
+ } from "./chunk-DTNK54C2.js";
83
+ import "./chunk-S5JNNDXS.js";
84
+ import "./chunk-OBCFACUW.js";
85
+ import {
86
+ comparePngNative,
87
+ getNativeAcceleratorPath,
88
+ isNativeAcceleratorActive,
89
+ tokenizeXmlNative
90
+ } from "./chunk-4K3FZTSV.js";
91
+ import "./chunk-H27IBIGA.js";
7
92
  import "./chunk-DGUM43GV.js";
8
93
 
9
94
  // src/api/flow.ts
@@ -47,16 +132,667 @@ var ViewHierarchy = Schema.Struct({
47
132
  // src/schemas/device.ts
48
133
  import { Schema as Schema2 } from "effect";
49
134
  var DeviceInfo = Schema2.Struct({
50
- platform: Schema2.Literal("android", "ios", "web"),
135
+ platform: Schema2.Literal("android", "ios", "web", "electron", "electrobun"),
51
136
  deviceId: Schema2.String,
52
137
  name: Schema2.String,
53
138
  isEmulator: Schema2.Boolean,
54
139
  screenWidth: Schema2.Number,
55
140
  screenHeight: Schema2.Number,
56
- driverType: Schema2.Literal("playwright", "uiautomator2", "wda", "appium")
141
+ driverType: Schema2.Literal(
142
+ "playwright",
143
+ "uiautomator2",
144
+ "wda",
145
+ "appium",
146
+ "electron",
147
+ "electrobun"
148
+ )
57
149
  });
150
+
151
+ // src/api/fixtures.ts
152
+ function defineSetup(name, config) {
153
+ return { name, ...config };
154
+ }
155
+ async function applyNamedSetup(setup, ctx) {
156
+ const app = ctx.app;
157
+ if (setup.storageStatePath && ctx.platform === "web") {
158
+ await app.loadAuthState(setup.storageStatePath);
159
+ }
160
+ if (setup.clearBefore !== false && setup.storage) {
161
+ const clearOpts = typeof setup.clearBefore === "object" ? setup.clearBefore : void 0;
162
+ try {
163
+ await app.clearStorage(clearOpts);
164
+ } catch {
165
+ if (ctx.platform === "web") {
166
+ await app.evaluate("localStorage.clear(); sessionStorage.clear();");
167
+ }
168
+ }
169
+ }
170
+ if (setup.storage) {
171
+ try {
172
+ await app.setStorage(setup.storage);
173
+ } catch {
174
+ if (ctx.platform === "web") {
175
+ const serialized = JSON.stringify(setup.storage);
176
+ await app.evaluate(
177
+ `(() => { const entries = ${serialized}; if (entries.localStorage) { for (const [k, v] of Object.entries(entries.localStorage)) localStorage.setItem(k, v); } if (entries.sessionStorage) { for (const [k, v] of Object.entries(entries.sessionStorage)) sessionStorage.setItem(k, v); } })()`
178
+ );
179
+ } else {
180
+ throw new Error(
181
+ `Named setup "${setup.name}" requires spana-bridge or a DOM channel to inject storage on ${ctx.platform}.`
182
+ );
183
+ }
184
+ }
185
+ if (setup.navigateTo) {
186
+ await app.openLink(setup.navigateTo);
187
+ } else if (setup.reloadAfterStorage !== false) {
188
+ try {
189
+ await app.resetFast();
190
+ } catch {
191
+ if (ctx.platform === "web") {
192
+ await app.evaluate("window.location.reload();");
193
+ }
194
+ }
195
+ }
196
+ } else if (setup.navigateTo) {
197
+ await app.openLink(setup.navigateTo);
198
+ }
199
+ if (setup.run) {
200
+ await setup.run(ctx);
201
+ }
202
+ }
203
+ function extractDestructuredParamNames(fn) {
204
+ const src = fn.toString().trim();
205
+ const openParen = src.indexOf("(");
206
+ if (openParen < 0) return [];
207
+ let i = openParen + 1;
208
+ while (i < src.length && /\s/.test(src[i])) i++;
209
+ if (src[i] !== "{") return [];
210
+ let depth = 0;
211
+ const start = i + 1;
212
+ let end = -1;
213
+ for (; i < src.length; i++) {
214
+ const ch = src[i];
215
+ if (ch === "{") depth++;
216
+ else if (ch === "}") {
217
+ depth--;
218
+ if (depth === 0) {
219
+ end = i;
220
+ break;
221
+ }
222
+ }
223
+ }
224
+ if (end < 0) return [];
225
+ const inner = src.slice(start, end);
226
+ const names = [];
227
+ let token = "";
228
+ let nested = 0;
229
+ for (let j = 0; j < inner.length; j++) {
230
+ const ch = inner[j];
231
+ if (ch === "{" || ch === "[" || ch === "(") nested++;
232
+ else if (ch === "}" || ch === "]" || ch === ")") nested--;
233
+ else if (ch === "," && nested === 0) {
234
+ const parsed = parseDestructuredKey(token);
235
+ if (parsed) names.push(parsed);
236
+ token = "";
237
+ continue;
238
+ }
239
+ token += ch;
240
+ }
241
+ const last = parseDestructuredKey(token);
242
+ if (last) names.push(last);
243
+ return names;
244
+ }
245
+ function parseDestructuredKey(raw) {
246
+ const cleaned = raw.trim();
247
+ if (!cleaned || cleaned.startsWith("...")) return null;
248
+ const keyMatch = cleaned.match(/^([A-Za-z_$][A-Za-z0-9_$]*)/);
249
+ return keyMatch?.[1] ?? null;
250
+ }
251
+ function createFlowWithFixtures(options) {
252
+ const fixtureMap = /* @__PURE__ */ new Map();
253
+ const rawFixtures = options.fixtures ?? {};
254
+ const setups = options.setups ?? {};
255
+ for (const [name, def] of Object.entries(rawFixtures)) {
256
+ const fn = typeof def === "function" ? def : def.setup;
257
+ const auto = typeof def === "function" ? false : Boolean(def.auto);
258
+ const explicitDeps = typeof def === "function" ? void 0 : def.deps;
259
+ const inferredDeps = explicitDeps ?? extractDestructuredParamNames(fn);
260
+ fixtureMap.set(name, { name, setup: fn, auto, deps: inferredDeps });
261
+ }
262
+ function resolveFixtureOrder(requested) {
263
+ const ordered = [];
264
+ const visiting = /* @__PURE__ */ new Set();
265
+ const visited = /* @__PURE__ */ new Set();
266
+ const visit = (name) => {
267
+ if (visited.has(name)) return;
268
+ const fix = fixtureMap.get(name);
269
+ if (!fix) return;
270
+ if (visiting.has(name)) {
271
+ throw new Error(`Circular fixture dependency detected involving "${name}"`);
272
+ }
273
+ visiting.add(name);
274
+ for (const dep of fix.deps) {
275
+ if (fixtureMap.has(dep)) {
276
+ visit(dep);
277
+ }
278
+ }
279
+ visiting.delete(name);
280
+ visited.add(name);
281
+ ordered.push(fix);
282
+ };
283
+ for (const fix of fixtureMap.values()) {
284
+ if (fix.auto) visit(fix.name);
285
+ }
286
+ for (const name of requested) {
287
+ visit(name);
288
+ }
289
+ return ordered;
290
+ }
291
+ function extendedFlow(name, configOrFn, maybeFn) {
292
+ const isFnOnly = typeof configOrFn === "function";
293
+ const extConfig = isFnOnly ? {} : configOrFn;
294
+ const userFn = isFnOnly ? configOrFn : maybeFn;
295
+ const requestedNames = [
296
+ ...extConfig.uses ?? [],
297
+ ...extractDestructuredParamNames(userFn).filter((n) => fixtureMap.has(n))
298
+ ];
299
+ const wrappedFn = async (baseCtx) => {
300
+ if (extConfig.session) {
301
+ const setup = setups[extConfig.session];
302
+ if (!setup) {
303
+ throw new Error(
304
+ `Unknown setup session "${extConfig.session}". Registered setups: ${Object.keys(setups).join(", ") || "(none)"}`
305
+ );
306
+ }
307
+ await applyNamedSetup(setup, baseCtx);
308
+ }
309
+ const orderedFixtures = resolveFixtureOrder(requestedNames);
310
+ const mergedCtx = { ...baseCtx };
311
+ const runChain = async (idx) => {
312
+ if (idx >= orderedFixtures.length) {
313
+ await userFn(mergedCtx);
314
+ return;
315
+ }
316
+ const fix = orderedFixtures[idx];
317
+ let useCalled = false;
318
+ let flowError;
319
+ let hasFlowError = false;
320
+ await fix.setup(mergedCtx, async (val) => {
321
+ useCalled = true;
322
+ mergedCtx[fix.name] = val;
323
+ try {
324
+ await runChain(idx + 1);
325
+ } catch (err) {
326
+ flowError = err;
327
+ hasFlowError = true;
328
+ }
329
+ });
330
+ if (!useCalled) {
331
+ throw new Error(`Fixture "${fix.name}" finished without calling use(value).`);
332
+ }
333
+ if (hasFlowError) {
334
+ throw flowError;
335
+ }
336
+ };
337
+ await runChain(0);
338
+ };
339
+ const { session: _session, uses: _uses, ...baseFlowConfig } = extConfig;
340
+ return {
341
+ name,
342
+ config: baseFlowConfig,
343
+ fn: wrappedFn
344
+ };
345
+ }
346
+ return extendedFlow;
347
+ }
348
+ function createApiClient(options) {
349
+ const baseUrl = options.baseUrl.replace(/\/+$/, "");
350
+ const defaultHeaders = options.headers ?? {};
351
+ const fetchFn = options.fetchFn ?? fetch;
352
+ const cleanups = [];
353
+ const request = async (method, path, body, opts) => {
354
+ const cleanPath = path.startsWith("http://") || path.startsWith("https://") ? path : `${baseUrl}/${path.replace(/^\/+/, "")}`;
355
+ const url = new URL(cleanPath);
356
+ if (opts?.query) {
357
+ for (const [k, v] of Object.entries(opts.query)) {
358
+ if (v !== void 0) url.searchParams.set(k, String(v));
359
+ }
360
+ }
361
+ const headers = {
362
+ ...defaultHeaders,
363
+ ...body !== void 0 ? { "content-type": "application/json" } : {},
364
+ ...opts?.headers
365
+ };
366
+ const res = await fetchFn(url.toString(), {
367
+ method,
368
+ headers,
369
+ ...body !== void 0 ? { body: typeof body === "string" ? body : JSON.stringify(body) } : {},
370
+ ...opts?.signal ? { signal: opts.signal } : {}
371
+ });
372
+ const contentType = res.headers.get("content-type") ?? "";
373
+ let data;
374
+ if (contentType.includes("application/json")) {
375
+ data = await res.json().catch(() => null);
376
+ } else {
377
+ const text = await res.text().catch(() => "");
378
+ try {
379
+ data = text ? JSON.parse(text) : text;
380
+ } catch {
381
+ data = text;
382
+ }
383
+ }
384
+ return {
385
+ status: res.status,
386
+ ok: res.ok,
387
+ headers: res.headers,
388
+ data
389
+ };
390
+ };
391
+ return {
392
+ get: (path, opts) => request("GET", path, void 0, opts),
393
+ post: (path, body, opts) => request("POST", path, body, opts),
394
+ put: (path, body, opts) => request("PUT", path, body, opts),
395
+ patch: (path, body, opts) => request("PATCH", path, body, opts),
396
+ delete: (path, opts) => request("DELETE", path, void 0, opts),
397
+ onCleanup: (fn) => {
398
+ cleanups.push(fn);
399
+ },
400
+ cleanup: async () => {
401
+ const pending = cleanups.splice(0, cleanups.length).toReversed();
402
+ const errors = [];
403
+ for (const fn of pending) {
404
+ try {
405
+ await fn();
406
+ } catch (err) {
407
+ errors.push(err);
408
+ }
409
+ }
410
+ if (errors.length > 0) {
411
+ throw errors[0];
412
+ }
413
+ }
414
+ };
415
+ }
416
+ function createApiFixture(options) {
417
+ return async (ctx, use) => {
418
+ const resolved = typeof options === "function" ? options(ctx) : options;
419
+ const api = createApiClient(resolved);
420
+ try {
421
+ await use(api);
422
+ } finally {
423
+ await api.cleanup();
424
+ }
425
+ };
426
+ }
427
+ function definePersona(name, config) {
428
+ return { name, ...config };
429
+ }
430
+ var PersonaAuthCache = class {
431
+ cache = /* @__PURE__ */ new Map();
432
+ inflight = /* @__PURE__ */ new Map();
433
+ keyFor(persona) {
434
+ return `${persona.name}::${persona.cacheKey ?? "default"}`;
435
+ }
436
+ get(name, cacheKey = "default") {
437
+ return this.cache.get(`${name}::${cacheKey}`);
438
+ }
439
+ invalidate(name, cacheKey = "default") {
440
+ if (!name) {
441
+ this.cache.clear();
442
+ return;
443
+ }
444
+ this.cache.delete(`${name}::${cacheKey}`);
445
+ }
446
+ /**
447
+ * Ensure `persona` is authenticated in `ctx`. On cache miss, executes `persona.signIn(ctx)`
448
+ * once (coalescing concurrent callers); on cache hit, restores cookies/storageState directly.
449
+ */
450
+ async authenticate(persona, ctx) {
451
+ const key = this.keyFor(persona);
452
+ let state = this.cache.get(key);
453
+ let wasMiss = false;
454
+ if (!state) {
455
+ wasMiss = true;
456
+ let pending = this.inflight.get(key);
457
+ if (!pending) {
458
+ pending = (async () => {
459
+ const produced = await persona.signIn(ctx) ?? {};
460
+ const entry = {
461
+ storage: produced.storage,
462
+ storageStatePath: produced.storageStatePath,
463
+ cachedAt: Date.now()
464
+ };
465
+ this.cache.set(key, entry);
466
+ return entry;
467
+ })().finally(() => {
468
+ this.inflight.delete(key);
469
+ });
470
+ this.inflight.set(key, pending);
471
+ }
472
+ state = await pending;
473
+ }
474
+ const app = ctx.app;
475
+ if (!wasMiss) {
476
+ if (state.storageStatePath && ctx.platform === "web") {
477
+ await app.loadAuthState(state.storageStatePath);
478
+ }
479
+ if (state.storage) {
480
+ await app.setStorage(state.storage);
481
+ }
482
+ }
483
+ if (persona.navigateTo) {
484
+ await app.openLink(persona.navigateTo);
485
+ }
486
+ return state;
487
+ }
488
+ };
489
+
490
+ // src/core/replay-cache.ts
491
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "fs";
492
+ import { dirname, join } from "path";
493
+ import { createHash } from "crypto";
494
+ function buildReplayCacheKey(flowName, platform, goal) {
495
+ const hash = createHash("sha256").update(`${flowName}\0${platform}\0${goal.trim()}`).digest("hex").slice(0, 16);
496
+ const slug = flowName.toLowerCase().replaceAll(/[^a-z0-9]+/g, "-").replaceAll(/^-|-$/g, "").slice(0, 40);
497
+ return `${slug || "flow"}-${platform}-${hash}`;
498
+ }
499
+ var ReplayCacheStore = class {
500
+ cacheDir;
501
+ constructor(cacheDir = ".spana/cache") {
502
+ this.cacheDir = cacheDir;
503
+ }
504
+ filePath(key) {
505
+ return join(this.cacheDir, `${key}.json`);
506
+ }
507
+ get(key) {
508
+ const p = this.filePath(key);
509
+ if (!existsSync(p)) return null;
510
+ try {
511
+ const raw = readFileSync(p, "utf-8");
512
+ const parsed = JSON.parse(raw);
513
+ if (parsed.schemaVersion !== 1 || !Array.isArray(parsed.actions)) return null;
514
+ return parsed;
515
+ } catch {
516
+ return null;
517
+ }
518
+ }
519
+ set(entry) {
520
+ const p = this.filePath(entry.key);
521
+ mkdirSync(dirname(p), { recursive: true });
522
+ writeFileSync(p, JSON.stringify(entry, null, 2), "utf-8");
523
+ }
524
+ delete(key) {
525
+ const p = this.filePath(key);
526
+ if (!existsSync(p)) return false;
527
+ rmSync(p, { force: true });
528
+ return true;
529
+ }
530
+ };
531
+ async function replayRecordedAction(app, action) {
532
+ switch (action.kind) {
533
+ case "tap":
534
+ await app.tap(action.selector);
535
+ break;
536
+ case "doubleTap":
537
+ await app.doubleTap(action.selector);
538
+ break;
539
+ case "longPress":
540
+ await app.longPress(action.selector);
541
+ break;
542
+ case "inputText":
543
+ await app.inputText(action.text);
544
+ break;
545
+ case "pressKey":
546
+ await app.pressKey(action.key);
547
+ break;
548
+ case "scroll":
549
+ await app.scroll(action.direction);
550
+ break;
551
+ case "scrollUntilVisible":
552
+ await app.scrollUntilVisible(action.selector);
553
+ break;
554
+ case "openLink":
555
+ await app.openLink(action.url);
556
+ break;
557
+ }
558
+ }
559
+ var ReplaySession = class {
560
+ flowName;
561
+ platform;
562
+ app;
563
+ store;
564
+ mode;
565
+ executor;
566
+ pendingWrites = [];
567
+ replayedKeys = [];
568
+ outcomes = [];
569
+ constructor(options) {
570
+ this.flowName = options.flowName;
571
+ this.platform = options.platform;
572
+ this.app = options.app;
573
+ this.store = options.store ?? new ReplayCacheStore();
574
+ this.mode = options.mode ?? "read-write";
575
+ this.executor = options.executor;
576
+ }
577
+ /** Execute a natural-language goal using replay cache first, falling back to `executor`. */
578
+ async act(goal) {
579
+ const key = buildReplayCacheKey(this.flowName, this.platform, goal);
580
+ const cached = this.mode === "off" ? null : this.store.get(key);
581
+ if (cached && cached.actions.length > 0) {
582
+ try {
583
+ for (const action of cached.actions) {
584
+ await replayRecordedAction(this.app, action);
585
+ }
586
+ const outcome = {
587
+ goal,
588
+ key,
589
+ status: "replayed",
590
+ writeStatus: "kept",
591
+ actionCount: cached.actions.length
592
+ };
593
+ const idx = this.outcomes.push(outcome) - 1;
594
+ this.replayedKeys.push({ key, outcomeIndex: idx });
595
+ return outcome;
596
+ } catch (err) {
597
+ const errMsg = err instanceof Error ? err.message : String(err);
598
+ if (this.mode === "strict") {
599
+ throw new Error(
600
+ `Strict replay cache mismatch for "${goal}" (${key}): ${errMsg}. Re-run locally without --strict-cache to self-heal and update .spana/cache/.`,
601
+ { cause: err }
602
+ );
603
+ }
604
+ return this.runLiveAndQueue(goal, key, true, errMsg);
605
+ }
606
+ }
607
+ if (this.mode === "strict") {
608
+ throw new Error(
609
+ `Strict replay cache miss for "${goal}" (${key}). No verified recording found in ${this.store.cacheDir}.`
610
+ );
611
+ }
612
+ return this.runLiveAndQueue(goal, key, false);
613
+ }
614
+ async runLiveAndQueue(goal, key, wasExisting, handoffReason) {
615
+ if (!this.executor) {
616
+ throw new Error(
617
+ `No agent executor configured for goal "${goal}" and no cached replay exists.`
618
+ );
619
+ }
620
+ const result = await this.executor.act({
621
+ goal,
622
+ app: this.app,
623
+ handoffReason
624
+ });
625
+ const outcome = {
626
+ goal,
627
+ key,
628
+ status: wasExisting ? "handed-off" : this.mode === "off" ? "live" : "missed",
629
+ writeStatus: this.mode === "off" ? "skipped" : "unconfirmed",
630
+ actionCount: result.actions.length
631
+ };
632
+ const idx = this.outcomes.push(outcome) - 1;
633
+ if (this.mode === "read-write" && result.actions.length > 0) {
634
+ this.pendingWrites.push({
635
+ wasExisting,
636
+ outcomeIndex: idx,
637
+ entry: {
638
+ schemaVersion: 1,
639
+ key,
640
+ goal,
641
+ flowName: this.flowName,
642
+ platform: this.platform,
643
+ actions: result.actions,
644
+ recordedAt: (/* @__PURE__ */ new Date()).toISOString(),
645
+ verifiedBy: ""
646
+ }
647
+ });
648
+ }
649
+ return outcome;
650
+ }
651
+ /**
652
+ * Call when a real post-action assertion (`expect(...).toBeVisible()`, `toHaveText()`, etc.)
653
+ * succeeds. Flushes all preceding pending recordings to disk in `read-write` mode.
654
+ */
655
+ markVerified(verifierName) {
656
+ if (this.mode !== "read-write") return 0;
657
+ let saved = 0;
658
+ for (const pending of this.pendingWrites) {
659
+ pending.entry.verifiedBy = verifierName;
660
+ this.store.set(pending.entry);
661
+ this.outcomes[pending.outcomeIndex].writeStatus = "saved";
662
+ saved += 1;
663
+ }
664
+ this.pendingWrites = [];
665
+ return saved;
666
+ }
667
+ /**
668
+ * Call when the flow attempt fails: evicts any replayed recordings involved in the
669
+ * failure (in `read-write` mode) and discards unconfirmed recordings so broken paths
670
+ * are never persisted.
671
+ */
672
+ markFailed() {
673
+ let evicted = 0;
674
+ if (this.mode === "read-write") {
675
+ for (const replayed of this.replayedKeys) {
676
+ if (this.store.delete(replayed.key)) {
677
+ this.outcomes[replayed.outcomeIndex].writeStatus = "evicted";
678
+ evicted += 1;
679
+ }
680
+ }
681
+ for (const pending of this.pendingWrites) {
682
+ if (pending.wasExisting && this.store.delete(pending.entry.key)) {
683
+ this.outcomes[pending.outcomeIndex].writeStatus = "evicted";
684
+ evicted += 1;
685
+ }
686
+ }
687
+ }
688
+ this.pendingWrites = [];
689
+ this.replayedKeys = [];
690
+ return evicted;
691
+ }
692
+ getOutcomes() {
693
+ return [...this.outcomes];
694
+ }
695
+ getSummary() {
696
+ const summary = {
697
+ replayed: 0,
698
+ handedOff: 0,
699
+ missed: 0,
700
+ saved: 0,
701
+ evicted: 0,
702
+ unconfirmed: 0
703
+ };
704
+ for (const o of this.outcomes) {
705
+ if (o.status === "replayed") summary.replayed++;
706
+ else if (o.status === "handed-off") summary.handedOff++;
707
+ else if (o.status === "missed") summary.missed++;
708
+ if (o.writeStatus === "saved") summary.saved++;
709
+ else if (o.writeStatus === "evicted") summary.evicted++;
710
+ else if (o.writeStatus === "unconfirmed") summary.unconfirmed++;
711
+ }
712
+ return summary;
713
+ }
714
+ };
58
715
  export {
716
+ AndroidWebViewCdpChannel,
717
+ AppleWebInspectorClient,
718
+ CdpDomChannel,
719
+ PersonaAuthCache,
720
+ ReplayCacheStore,
721
+ ReplaySession,
722
+ SPANA_MCP_TOOLS,
723
+ SpanaBridgeChannel,
724
+ SpanaMcpServer,
725
+ TARGET_CHANNEL_MATRIX,
726
+ WebKitInspectorChannel,
727
+ applyNamedSetup,
728
+ applyTestFilters,
729
+ buildDomFillScript,
730
+ buildDomWaitForHiddenScript,
731
+ buildDomWaitForMatchScript,
732
+ buildDomWaitForSelectorScript,
733
+ buildFilterCandidates,
734
+ buildFlowFileFromLines,
735
+ buildReplayCacheKey,
736
+ collectGitChanges,
737
+ comparePngNative,
738
+ connectPlaywrightOverCDP,
739
+ connectPlaywrightOverWS,
740
+ createAndroidWebViewCdpChannel,
741
+ createApiClient,
742
+ createApiFixture,
743
+ createCdpDomChannel,
744
+ createCompositeDomChannel,
745
+ createFlowWithFixtures,
746
+ createGitHubPrReporter,
747
+ createLogprobDecisionJudge,
748
+ createOllamaDecisionJudge,
749
+ createSpanaBridgeChannel,
750
+ createWebKitInspectorChannel,
751
+ decisionFilter,
752
+ decodeWebInspectorFrames,
59
753
  defineConfig,
60
- flow
754
+ definePersona,
755
+ defineSetup,
756
+ deterministicImpactFilter,
757
+ domRectToScreenBounds,
758
+ encodeWebInspectorPacket,
759
+ ensureWarmBrowserDaemon,
760
+ extractDestructuredParamNames,
761
+ findSimulatorWebInspectorSocket,
762
+ findWebViewFrame,
763
+ flow,
764
+ formatFilterSummary,
765
+ formatGitHubPrMarkdown,
766
+ formatSelectorCode,
767
+ formatTargetMatrixTable,
768
+ getHealthyWarmDaemon,
769
+ getNativeAcceleratorPath,
770
+ invalidateWebViewFrameCache,
771
+ isNativeAcceleratorActive,
772
+ isOffscreenInViewport,
773
+ isSystemUISelector,
774
+ isTestIDSelector,
775
+ launchDirectCdpBrowser,
776
+ launchPlaywrightBrowser,
777
+ listWarmDaemons,
778
+ makeElectrobunDriver,
779
+ makeElectronDriver,
780
+ makeLightweightCdpDriver,
781
+ orderFlowsLongestFirst,
782
+ parseAndroidWebViewSockets,
783
+ parseWebInspectorXmlFrame,
784
+ pathRuleFilter,
785
+ probabilityFromTopLogprobs,
786
+ replayRecordedAction,
787
+ resolveElectrobunEngine,
788
+ resolveElectrobunLaunchPlan,
789
+ resolveElementAcrossChannels,
790
+ resolveTargetDescriptor,
791
+ speculativelyPrelaunchWebBrowser,
792
+ stopAllWarmDaemons,
793
+ stopWarmDaemon,
794
+ systemUI,
795
+ tokenizeXmlNative,
796
+ updateWarmDaemonSession
61
797
  };
62
798
  //# sourceMappingURL=index.js.map