spana-test 0.5.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.
- package/.agents/skills/spana-testing/SKILL.md +122 -246
- package/README.md +2 -2
- package/dist/agent/index.d.ts +2 -2
- package/dist/agent/index.js +5 -5
- package/dist/{storybook-CxaP3YDz.d.ts → app-DcLXtpv4.d.ts} +205 -9
- package/dist/{chunk-3YE2POGD.js → chunk-3SH5JQF7.js} +143 -3
- package/dist/chunk-3SH5JQF7.js.map +1 -0
- package/dist/chunk-4K3FZTSV.js +179 -0
- package/dist/chunk-4K3FZTSV.js.map +1 -0
- package/dist/{chunk-H3RWZCID.js → chunk-C4E4XULT.js} +104 -3
- package/dist/chunk-C4E4XULT.js.map +1 -0
- package/dist/{chunk-SQL3YRR5.js → chunk-KBRLIQRA.js} +16 -1
- package/dist/chunk-KBRLIQRA.js.map +1 -0
- package/dist/{chunk-LRGT342X.js → chunk-KEUZLBQS.js} +1110 -475
- package/dist/chunk-KEUZLBQS.js.map +1 -0
- package/dist/{chunk-XENRC3YO.js → chunk-LCV673G3.js} +605 -41
- package/dist/chunk-LCV673G3.js.map +1 -0
- package/dist/{chunk-3TRMQCUT.js → chunk-PLE7RFQE.js} +31 -2
- package/dist/chunk-PLE7RFQE.js.map +1 -0
- package/dist/{chunk-PJKIXVSO.js → chunk-PWUJT5HE.js} +898 -238
- package/dist/chunk-PWUJT5HE.js.map +1 -0
- package/dist/{chunk-WSA5QPTA.js → chunk-S4JVAHBR.js} +2 -2
- package/dist/{chunk-UJQ7PID5.js → chunk-WBBMEAHU.js} +78 -3
- package/dist/chunk-WBBMEAHU.js.map +1 -0
- package/dist/{chunk-5245YBLL.js → chunk-Y2RZNOKU.js} +2 -2
- package/dist/cli.js +11 -11
- package/dist/cli.js.map +1 -1
- package/dist/config-loader-J4Z2PMUQ.js +9 -0
- package/dist/{doctor-command-WB3O2H64.js → doctor-command-WEHFANT7.js} +3 -3
- package/dist/{filters-Q3ALKWZ5.js → filters-MQG2RMPX.js} +4 -2
- package/dist/flow-C2JQ7gUu.d.ts +95 -0
- package/dist/gherkin/steps.d.ts +2 -2
- package/dist/index.d.ts +214 -20
- package/dist/index.js +173 -6
- package/dist/index.js.map +1 -1
- package/dist/{runner-6HK62Q7B.js → runner-TF4OKPYP.js} +2 -2
- package/dist/{screenshot-compare-3QRHHSFZ.js → screenshot-compare-5NINZVOK.js} +21 -1
- package/dist/screenshot-compare-5NINZVOK.js.map +1 -0
- package/dist/{server-QWJJB3WG.js → server-3MGZNK67.js} +2 -2
- package/dist/{server-PRM7BVVD.js → server-OANRDAHN.js} +5 -5
- package/dist/{session-Ddem-Q5n.d.ts → session-Daq0mE_a.d.ts} +22 -1
- package/dist/{session-2E6OK6BH.js → session-Q3QYHT4Q.js} +4 -4
- package/dist/{studio-command-O3NN5BCG.js → studio-command-RJYLJT4I.js} +2 -2
- package/dist/{test-command-FYOZ6QAE.js → test-command-ALH5ZQY5.js} +23 -9
- package/dist/test-command-ALH5ZQY5.js.map +1 -0
- package/dist/{validator-HZ2A3NEI.js → validator-BLOLIHUY.js} +3 -3
- package/package.json +2 -2
- package/dist/chunk-3TRMQCUT.js.map +0 -1
- package/dist/chunk-3YE2POGD.js.map +0 -1
- package/dist/chunk-H3RWZCID.js.map +0 -1
- package/dist/chunk-LRGT342X.js.map +0 -1
- package/dist/chunk-PJKIXVSO.js.map +0 -1
- package/dist/chunk-SQL3YRR5.js.map +0 -1
- package/dist/chunk-UJQ7PID5.js.map +0 -1
- package/dist/chunk-XENRC3YO.js.map +0 -1
- package/dist/config-loader-XGDDJGVY.js +0 -9
- package/dist/flow-CyRC-tTc.d.ts +0 -176
- package/dist/screenshot-compare-3QRHHSFZ.js.map +0 -1
- package/dist/test-command-FYOZ6QAE.js.map +0 -1
- /package/dist/{chunk-WSA5QPTA.js.map → chunk-S4JVAHBR.js.map} +0 -0
- /package/dist/{chunk-5245YBLL.js.map → chunk-Y2RZNOKU.js.map} +0 -0
- /package/dist/{config-loader-XGDDJGVY.js.map → config-loader-J4Z2PMUQ.js.map} +0 -0
- /package/dist/{doctor-command-WB3O2H64.js.map → doctor-command-WEHFANT7.js.map} +0 -0
- /package/dist/{filters-Q3ALKWZ5.js.map → filters-MQG2RMPX.js.map} +0 -0
- /package/dist/{runner-6HK62Q7B.js.map → runner-TF4OKPYP.js.map} +0 -0
- /package/dist/{server-QWJJB3WG.js.map → server-3MGZNK67.js.map} +0 -0
- /package/dist/{server-PRM7BVVD.js.map → server-OANRDAHN.js.map} +0 -0
- /package/dist/{session-2E6OK6BH.js.map → session-Q3QYHT4Q.js.map} +0 -0
- /package/dist/{studio-command-O3NN5BCG.js.map → studio-command-RJYLJT4I.js.map} +0 -0
- /package/dist/{validator-HZ2A3NEI.js.map → validator-BLOLIHUY.js.map} +0 -0
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import {
|
|
2
|
-
buildStorybookUrl,
|
|
3
2
|
connectPlaywrightOverCDP,
|
|
3
|
+
connectPlaywrightOverWS,
|
|
4
4
|
createCoordinator,
|
|
5
|
+
createPromiseApp,
|
|
5
6
|
createUiAutomator2Driver,
|
|
6
7
|
createWDADriver,
|
|
7
8
|
ensureWarmBrowserDaemon,
|
|
@@ -13,19 +14,21 @@ import {
|
|
|
13
14
|
parseAndroidHierarchy,
|
|
14
15
|
parseIOSHierarchy,
|
|
15
16
|
parseWebHierarchy,
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
} from "./chunk-
|
|
17
|
+
resolveNetworkConditions,
|
|
18
|
+
setupUiAutomator2
|
|
19
|
+
} from "./chunk-PWUJT5HE.js";
|
|
19
20
|
import {
|
|
20
21
|
CdpDomChannel,
|
|
21
22
|
DriverError,
|
|
22
23
|
createSpanaBridgeChannel,
|
|
23
24
|
makeElectrobunDriver
|
|
24
|
-
} from "./chunk-
|
|
25
|
+
} from "./chunk-LCV673G3.js";
|
|
25
26
|
import {
|
|
26
27
|
setupWDA
|
|
27
28
|
} from "./chunk-HYSTRWYN.js";
|
|
28
29
|
import {
|
|
30
|
+
getHealthyWarmDaemon,
|
|
31
|
+
registerWarmDaemon,
|
|
29
32
|
updateWarmDaemonSession
|
|
30
33
|
} from "./chunk-DTNK54C2.js";
|
|
31
34
|
import {
|
|
@@ -43,336 +46,8 @@ import {
|
|
|
43
46
|
ensureAndroidDevice
|
|
44
47
|
} from "./chunk-H27IBIGA.js";
|
|
45
48
|
|
|
46
|
-
// src/api/app.ts
|
|
47
|
-
import { Effect } from "effect";
|
|
48
|
-
var describeMatcher = (matcher) => typeof matcher === "string" ? matcher : matcher.toString();
|
|
49
|
-
function createPromiseApp(driver, appId, config, recorder, options = {}) {
|
|
50
|
-
const coord = createCoordinator(driver, config);
|
|
51
|
-
const platform = options.platform ?? (appId.startsWith("http://") || appId.startsWith("https://") ? "web" : void 0);
|
|
52
|
-
const run = (effect) => Effect.runPromise(effect);
|
|
53
|
-
const unsupportedWebFeature = (feature) => Effect.fail(new DriverError({ message: `${feature}() is only supported on the web platform` }));
|
|
54
|
-
const optionalMethod = (name, method) => method ?? ((..._args) => unsupportedWebFeature(name));
|
|
55
|
-
const runStep = (command, action, opts) => recorder ? recorder.runStep(command, action, opts) : action();
|
|
56
|
-
const runScreenshotStep = (command, action, opts) => recorder ? recorder.runScreenshotStep(command, action, opts) : action();
|
|
57
|
-
return {
|
|
58
|
-
tap: (selector, opts) => runStep("tap", () => run(coord.tap(selector, opts)), { selector, captureScreenshot: true }),
|
|
59
|
-
tapXY: (x, y) => runStep("tapXY", () => run(coord.tapXY(x, y)), {
|
|
60
|
-
selector: { point: { x, y } },
|
|
61
|
-
captureScreenshot: true
|
|
62
|
-
}),
|
|
63
|
-
doubleTap: (selector, opts) => runStep("doubleTap", () => run(coord.doubleTap(selector, opts)), {
|
|
64
|
-
selector,
|
|
65
|
-
captureScreenshot: true
|
|
66
|
-
}),
|
|
67
|
-
longPress: (selector, opts) => runStep("longPress", () => run(coord.longPress(selector, opts?.duration, opts)), {
|
|
68
|
-
selector,
|
|
69
|
-
captureScreenshot: true
|
|
70
|
-
}),
|
|
71
|
-
longPressXY: (x, y, opts) => runStep("longPressXY", () => run(coord.longPressXY(x, y, opts?.duration)), {
|
|
72
|
-
selector: { point: { x, y } },
|
|
73
|
-
captureScreenshot: true
|
|
74
|
-
}),
|
|
75
|
-
inputText: (text) => runStep("inputText", () => run(coord.inputText(text)), { captureScreenshot: true }),
|
|
76
|
-
pressKey: (key) => runStep(`pressKey(${key})`, () => run(coord.pressKey(key)), { captureScreenshot: true }),
|
|
77
|
-
hideKeyboard: () => runStep("hideKeyboard", () => run(coord.hideKeyboard()), { captureScreenshot: true }),
|
|
78
|
-
dismissKeyboard: (opts) => runStep(
|
|
79
|
-
`dismissKeyboard(${opts?.strategy ?? "auto"})`,
|
|
80
|
-
() => run(coord.dismissKeyboard(opts)),
|
|
81
|
-
{
|
|
82
|
-
selector: { strategy: opts?.strategy ?? "auto" },
|
|
83
|
-
captureScreenshot: true
|
|
84
|
-
}
|
|
85
|
-
),
|
|
86
|
-
swipe: (direction, opts) => runStep(`swipe(${direction})`, () => run(coord.swipe(direction, opts)), {
|
|
87
|
-
captureScreenshot: true
|
|
88
|
-
}),
|
|
89
|
-
scroll: (direction) => runStep(`scroll(${direction})`, () => run(coord.scroll(direction)), {
|
|
90
|
-
captureScreenshot: true
|
|
91
|
-
}),
|
|
92
|
-
scrollUntilVisible: (selector, opts) => runStep(
|
|
93
|
-
`scrollUntilVisible(${opts?.direction ?? "down"})`,
|
|
94
|
-
() => run(coord.scrollUntilVisible(selector, opts)),
|
|
95
|
-
{
|
|
96
|
-
selector: {
|
|
97
|
-
target: selector,
|
|
98
|
-
...opts,
|
|
99
|
-
direction: opts?.direction ?? "down",
|
|
100
|
-
maxScrolls: opts?.maxScrolls ?? 5
|
|
101
|
-
},
|
|
102
|
-
captureScreenshot: true
|
|
103
|
-
}
|
|
104
|
-
),
|
|
105
|
-
backUntilVisible: (selector, opts) => runStep(
|
|
106
|
-
`backUntilVisible(${opts?.maxBacks ?? 3})`,
|
|
107
|
-
() => run(coord.backUntilVisible(selector, opts)),
|
|
108
|
-
{
|
|
109
|
-
selector: {
|
|
110
|
-
target: selector,
|
|
111
|
-
...opts,
|
|
112
|
-
maxBacks: opts?.maxBacks ?? 3
|
|
113
|
-
},
|
|
114
|
-
captureScreenshot: true
|
|
115
|
-
}
|
|
116
|
-
),
|
|
117
|
-
launch: (opts) => {
|
|
118
|
-
const mergedLaunchOptions = mergeLaunchOptions(options.launchOptions, opts);
|
|
119
|
-
return runStep("launch", () => run(driver.launchApp(appId, mergedLaunchOptions)), {
|
|
120
|
-
selector: mergedLaunchOptions,
|
|
121
|
-
captureScreenshot: true
|
|
122
|
-
});
|
|
123
|
-
},
|
|
124
|
-
stop: () => runStep("stop", () => run(driver.stopApp(appId)), { captureScreenshot: true }),
|
|
125
|
-
kill: () => runStep("kill", () => run(driver.killApp(appId)), { captureScreenshot: true }),
|
|
126
|
-
clearState: () => runStep("clearState", () => run(driver.clearAppState(appId)), { captureScreenshot: true }),
|
|
127
|
-
openLink: (url) => runStep("openLink", () => run(driver.openLink(url)), {
|
|
128
|
-
selector: { url },
|
|
129
|
-
captureScreenshot: true
|
|
130
|
-
}),
|
|
131
|
-
openStory: (storyId, opts) => runStep(
|
|
132
|
-
`openStory(${storyId})`,
|
|
133
|
-
async () => {
|
|
134
|
-
if (platform !== "web") {
|
|
135
|
-
await run(unsupportedWebFeature("openStory"));
|
|
136
|
-
return;
|
|
137
|
-
}
|
|
138
|
-
const url = buildStorybookUrl(storyId, opts, {
|
|
139
|
-
appBaseUrl: appId,
|
|
140
|
-
storybook: options.storybook
|
|
141
|
-
});
|
|
142
|
-
await run(driver.openLink(url));
|
|
143
|
-
},
|
|
144
|
-
{
|
|
145
|
-
selector: {
|
|
146
|
-
storyId,
|
|
147
|
-
viewMode: opts?.viewMode ?? "story",
|
|
148
|
-
args: opts?.args,
|
|
149
|
-
globals: opts?.globals,
|
|
150
|
-
baseUrl: opts?.baseUrl
|
|
151
|
-
},
|
|
152
|
-
captureScreenshot: true
|
|
153
|
-
}
|
|
154
|
-
),
|
|
155
|
-
back: () => runStep("back", () => run(driver.back()), { captureScreenshot: true }),
|
|
156
|
-
takeScreenshot: (name) => runScreenshotStep(
|
|
157
|
-
name ? `takeScreenshot(${name})` : "takeScreenshot",
|
|
158
|
-
() => run(driver.takeScreenshot()),
|
|
159
|
-
{ name }
|
|
160
|
-
),
|
|
161
|
-
evaluate: (fn, ...args) => runStep("evaluate", () => run(driver.evaluate(fn, ...args))),
|
|
162
|
-
mockNetwork: (matcher, response) => runStep(
|
|
163
|
-
"mockNetwork",
|
|
164
|
-
() => run(optionalMethod("mockNetwork", driver.mockNetwork)(matcher, response)),
|
|
165
|
-
{
|
|
166
|
-
selector: { matcher: describeMatcher(matcher), response }
|
|
167
|
-
}
|
|
168
|
-
),
|
|
169
|
-
blockNetwork: (matcher) => runStep(
|
|
170
|
-
"blockNetwork",
|
|
171
|
-
() => run(optionalMethod("blockNetwork", driver.blockNetwork)(matcher)),
|
|
172
|
-
{
|
|
173
|
-
selector: { matcher: describeMatcher(matcher) }
|
|
174
|
-
}
|
|
175
|
-
),
|
|
176
|
-
clearNetworkMocks: () => runStep(
|
|
177
|
-
"clearNetworkMocks",
|
|
178
|
-
() => run(optionalMethod("clearNetworkMocks", driver.clearNetworkMocks)())
|
|
179
|
-
),
|
|
180
|
-
setNetworkConditions: (conditions) => runStep(
|
|
181
|
-
"setNetworkConditions",
|
|
182
|
-
() => run(optionalMethod("setNetworkConditions", driver.setNetworkConditions)(conditions)),
|
|
183
|
-
{ selector: conditions }
|
|
184
|
-
),
|
|
185
|
-
saveCookies: (path) => runStep("saveCookies", () => run(optionalMethod("saveCookies", driver.saveCookies)(path)), {
|
|
186
|
-
selector: { path }
|
|
187
|
-
}),
|
|
188
|
-
loadCookies: (path) => runStep("loadCookies", () => run(optionalMethod("loadCookies", driver.loadCookies)(path)), {
|
|
189
|
-
selector: { path }
|
|
190
|
-
}),
|
|
191
|
-
saveAuthState: (path) => runStep(
|
|
192
|
-
"saveAuthState",
|
|
193
|
-
() => run(optionalMethod("saveAuthState", driver.saveAuthState)(path)),
|
|
194
|
-
{ selector: { path } }
|
|
195
|
-
),
|
|
196
|
-
loadAuthState: (path) => runStep(
|
|
197
|
-
"loadAuthState",
|
|
198
|
-
() => run(optionalMethod("loadAuthState", driver.loadAuthState)(path)),
|
|
199
|
-
{ selector: { path } }
|
|
200
|
-
),
|
|
201
|
-
downloadFile: (path) => runStep(
|
|
202
|
-
"downloadFile",
|
|
203
|
-
() => run(optionalMethod("downloadFile", driver.downloadFile)(path)),
|
|
204
|
-
{ selector: { path } }
|
|
205
|
-
),
|
|
206
|
-
uploadFile: (selector, path) => runStep(
|
|
207
|
-
"uploadFile",
|
|
208
|
-
() => run(optionalMethod("uploadFile", driver.uploadFile)(selector, path)),
|
|
209
|
-
{
|
|
210
|
-
selector: { target: selector, path },
|
|
211
|
-
captureScreenshot: true
|
|
212
|
-
}
|
|
213
|
-
),
|
|
214
|
-
newTab: (url) => runStep("newTab", () => run(optionalMethod("newTab", driver.newTab)(url)), {
|
|
215
|
-
selector: url ? { url } : void 0,
|
|
216
|
-
captureScreenshot: true
|
|
217
|
-
}),
|
|
218
|
-
switchToTab: (index) => runStep(
|
|
219
|
-
`switchToTab(${index})`,
|
|
220
|
-
() => run(optionalMethod("switchToTab", driver.switchToTab)(index)),
|
|
221
|
-
{
|
|
222
|
-
selector: { index },
|
|
223
|
-
captureScreenshot: true
|
|
224
|
-
}
|
|
225
|
-
),
|
|
226
|
-
closeTab: () => runStep("closeTab", () => run(optionalMethod("closeTab", driver.closeTab)()), {
|
|
227
|
-
captureScreenshot: true
|
|
228
|
-
}),
|
|
229
|
-
getTabIds: () => runStep("getTabIds", () => run(optionalMethod("getTabIds", driver.getTabIds)())),
|
|
230
|
-
getConsoleLogs: () => runStep(
|
|
231
|
-
"getConsoleLogs",
|
|
232
|
-
() => run(optionalMethod("getConsoleLogs", driver.getConsoleLogs)())
|
|
233
|
-
),
|
|
234
|
-
getJSErrors: () => runStep("getJSErrors", () => run(optionalMethod("getJSErrors", driver.getJSErrors)())),
|
|
235
|
-
getHAR: () => runStep("getHAR", () => run(optionalMethod("getHAR", driver.getHAR)())),
|
|
236
|
-
pinch: (selector, opts) => runStep("pinch", () => run(coord.pinch(selector, opts)), {
|
|
237
|
-
selector,
|
|
238
|
-
captureScreenshot: true
|
|
239
|
-
}),
|
|
240
|
-
zoom: (selector, opts) => runStep("zoom", () => run(coord.zoom(selector, opts)), {
|
|
241
|
-
selector,
|
|
242
|
-
captureScreenshot: true
|
|
243
|
-
}),
|
|
244
|
-
multiTouch: (sequences) => runStep("multiTouch", () => run(coord.multiTouch(sequences)), { captureScreenshot: true }),
|
|
245
|
-
getText: (selector, opts) => runStep("getText", () => run(coord.getText(selector, opts)), { selector }),
|
|
246
|
-
getAttribute: (selector, name, opts) => runStep(`getAttribute(${name})`, () => run(coord.getAttribute(selector, name, opts)), {
|
|
247
|
-
selector
|
|
248
|
-
}),
|
|
249
|
-
isVisible: (selector, opts) => {
|
|
250
|
-
const timeout = opts?.timeout ?? 1e3;
|
|
251
|
-
return run(
|
|
252
|
-
Effect.gen(function* () {
|
|
253
|
-
const result = yield* Effect.either(
|
|
254
|
-
waitForElement(
|
|
255
|
-
driver,
|
|
256
|
-
selector,
|
|
257
|
-
config.parse,
|
|
258
|
-
{ timeout, pollInterval: 100 },
|
|
259
|
-
void 0
|
|
260
|
-
)
|
|
261
|
-
);
|
|
262
|
-
return result._tag === "Right";
|
|
263
|
-
})
|
|
264
|
-
);
|
|
265
|
-
},
|
|
266
|
-
isEnabled: (selector, opts) => runStep("isEnabled", () => run(coord.isElementEnabled(selector, opts)), { selector }),
|
|
267
|
-
// Web-first bridge & fast state helpers
|
|
268
|
-
waitForIdle: (opts) => runStep("waitForIdle", async () => {
|
|
269
|
-
if (driver.domChannel?.waitForIdle) {
|
|
270
|
-
await driver.domChannel.waitForIdle(opts);
|
|
271
|
-
}
|
|
272
|
-
}),
|
|
273
|
-
setStorage: (entries) => runStep("setStorage", async () => {
|
|
274
|
-
if (driver.domChannel?.setStorage) {
|
|
275
|
-
await driver.domChannel.setStorage(entries);
|
|
276
|
-
return;
|
|
277
|
-
}
|
|
278
|
-
const serialized = JSON.stringify(entries);
|
|
279
|
-
await run(
|
|
280
|
-
driver.evaluate(
|
|
281
|
-
`((payload) => {
|
|
282
|
-
if (payload.localStorage) {
|
|
283
|
-
for (const [k, v] of Object.entries(payload.localStorage)) {
|
|
284
|
-
window.localStorage.setItem(k, v);
|
|
285
|
-
}
|
|
286
|
-
}
|
|
287
|
-
if (payload.sessionStorage) {
|
|
288
|
-
for (const [k, v] of Object.entries(payload.sessionStorage)) {
|
|
289
|
-
window.sessionStorage.setItem(k, v);
|
|
290
|
-
}
|
|
291
|
-
}
|
|
292
|
-
if (payload.cookies) {
|
|
293
|
-
for (const c of payload.cookies) {
|
|
294
|
-
const path = c.path ? '; path=' + c.path : '; path=/';
|
|
295
|
-
const domain = c.domain ? '; domain=' + c.domain : '';
|
|
296
|
-
document.cookie = encodeURIComponent(c.name) + '=' + encodeURIComponent(c.value) + path + domain;
|
|
297
|
-
}
|
|
298
|
-
}
|
|
299
|
-
})(${serialized})`
|
|
300
|
-
)
|
|
301
|
-
);
|
|
302
|
-
}),
|
|
303
|
-
clearStorage: (opts) => runStep("clearStorage", async () => {
|
|
304
|
-
if (driver.domChannel?.clearStorage) {
|
|
305
|
-
await driver.domChannel.clearStorage(opts);
|
|
306
|
-
return;
|
|
307
|
-
}
|
|
308
|
-
const serialized = JSON.stringify(opts ?? {});
|
|
309
|
-
await run(
|
|
310
|
-
driver.evaluate(
|
|
311
|
-
`((clearOpts) => {
|
|
312
|
-
if (clearOpts.localStorage !== false) {
|
|
313
|
-
try { window.localStorage.clear(); } catch {}
|
|
314
|
-
}
|
|
315
|
-
if (clearOpts.sessionStorage !== false) {
|
|
316
|
-
try { window.sessionStorage.clear(); } catch {}
|
|
317
|
-
}
|
|
318
|
-
})(${serialized})`
|
|
319
|
-
)
|
|
320
|
-
);
|
|
321
|
-
}),
|
|
322
|
-
resetFast: () => runStep("resetFast", async () => {
|
|
323
|
-
if (driver.resetFast) {
|
|
324
|
-
await run(driver.resetFast());
|
|
325
|
-
return;
|
|
326
|
-
}
|
|
327
|
-
if (driver.domChannel?.clearStorage) {
|
|
328
|
-
await driver.domChannel.clearStorage({
|
|
329
|
-
localStorage: true,
|
|
330
|
-
sessionStorage: true,
|
|
331
|
-
cookies: true,
|
|
332
|
-
indexedDB: true,
|
|
333
|
-
capacitorPreferences: true
|
|
334
|
-
});
|
|
335
|
-
if (driver.domChannel.reload) {
|
|
336
|
-
await driver.domChannel.reload();
|
|
337
|
-
}
|
|
338
|
-
return;
|
|
339
|
-
}
|
|
340
|
-
await run(driver.clearAppState(appId));
|
|
341
|
-
}),
|
|
342
|
-
// WebView / hybrid context switching (low-level escape hatches)
|
|
343
|
-
getContexts: () => runStep(
|
|
344
|
-
"getContexts",
|
|
345
|
-
() => run((driver.getContexts ?? (() => Effect.succeed(["NATIVE_APP"])))())
|
|
346
|
-
),
|
|
347
|
-
getCurrentContext: () => runStep(
|
|
348
|
-
"getCurrentContext",
|
|
349
|
-
() => run((driver.getCurrentContext ?? (() => Effect.succeed("NATIVE_APP")))())
|
|
350
|
-
),
|
|
351
|
-
switchToContext: (contextId) => runStep(
|
|
352
|
-
`switchToContext(${contextId})`,
|
|
353
|
-
() => run((driver.setContext ?? ((_id) => Effect.void))(contextId))
|
|
354
|
-
),
|
|
355
|
-
switchToWebView: () => runStep("switchToWebView", async () => {
|
|
356
|
-
const contexts = await run(
|
|
357
|
-
(driver.getContexts ?? (() => Effect.succeed(["NATIVE_APP"])))()
|
|
358
|
-
);
|
|
359
|
-
const webview = contexts.find((c) => c.startsWith("WEBVIEW_"));
|
|
360
|
-
if (!webview) {
|
|
361
|
-
throw new DriverError({
|
|
362
|
-
message: `No WebView context found. Available contexts: ${contexts.join(", ")}`
|
|
363
|
-
});
|
|
364
|
-
}
|
|
365
|
-
await run((driver.setContext ?? ((_id) => Effect.void))(webview));
|
|
366
|
-
}),
|
|
367
|
-
switchToNativeApp: () => runStep(
|
|
368
|
-
"switchToNativeApp",
|
|
369
|
-
() => run((driver.setContext ?? ((_id) => Effect.void))("NATIVE_APP"))
|
|
370
|
-
)
|
|
371
|
-
};
|
|
372
|
-
}
|
|
373
|
-
|
|
374
49
|
// src/api/expect.ts
|
|
375
|
-
import { Effect
|
|
50
|
+
import { Effect } from "effect";
|
|
376
51
|
function selectorToCss(sel) {
|
|
377
52
|
if (typeof sel === "string") return sel;
|
|
378
53
|
if (typeof sel === "object" && sel !== null && "testID" in sel && sel.testID)
|
|
@@ -388,7 +63,7 @@ function createPromiseExpect(driver, config, recorder, flowContext, visualRegres
|
|
|
388
63
|
platform: "web"
|
|
389
64
|
};
|
|
390
65
|
const coord = createCoordinator(driver, config);
|
|
391
|
-
const run = (effect) =>
|
|
66
|
+
const run = (effect) => Effect.runPromise(effect);
|
|
392
67
|
const runStep = (command, selector, action) => recorder ? recorder.runStep(command, action, { selector, captureScreenshot: false }) : action();
|
|
393
68
|
return (selector) => ({
|
|
394
69
|
toBeVisible: (opts) => runStep(
|
|
@@ -478,7 +153,7 @@ function createPromiseExpect(driver, config, recorder, flowContext, visualRegres
|
|
|
478
153
|
}
|
|
479
154
|
|
|
480
155
|
// src/core/session-manager.ts
|
|
481
|
-
import { Effect as
|
|
156
|
+
import { Effect as Effect2 } from "effect";
|
|
482
157
|
function createSessions(manager, driverFactory, coordinatorConfig) {
|
|
483
158
|
const coordConfig = coordinatorConfig ?? { parse: parseWebHierarchy };
|
|
484
159
|
return {
|
|
@@ -489,7 +164,7 @@ function createSessions(manager, driverFactory, coordinatorConfig) {
|
|
|
489
164
|
}
|
|
490
165
|
const driver = await driverFactory(opts);
|
|
491
166
|
const baseUrl = opts.baseUrl ?? "http://localhost:3000";
|
|
492
|
-
await
|
|
167
|
+
await Effect2.runPromise(driver.launchApp(baseUrl));
|
|
493
168
|
const app = createPromiseApp(driver, baseUrl, coordConfig, void 0, {
|
|
494
169
|
platform: "web"
|
|
495
170
|
});
|
|
@@ -500,12 +175,12 @@ function createSessions(manager, driverFactory, coordinatorConfig) {
|
|
|
500
175
|
app,
|
|
501
176
|
expect,
|
|
502
177
|
async disconnect() {
|
|
503
|
-
await
|
|
178
|
+
await Effect2.runPromise(driver.killApp(baseUrl));
|
|
504
179
|
manager.remove(opts.name);
|
|
505
180
|
}
|
|
506
181
|
};
|
|
507
182
|
const cleanup = async () => {
|
|
508
|
-
await
|
|
183
|
+
await Effect2.runPromise(driver.killApp(baseUrl));
|
|
509
184
|
};
|
|
510
185
|
manager.register(session, cleanup);
|
|
511
186
|
return session;
|
|
@@ -543,7 +218,165 @@ var SessionManager = class {
|
|
|
543
218
|
};
|
|
544
219
|
|
|
545
220
|
// src/drivers/cdp-browser.ts
|
|
546
|
-
import {
|
|
221
|
+
import { spawn } from "child_process";
|
|
222
|
+
import { createHash } from "crypto";
|
|
223
|
+
import { existsSync, mkdtempSync, rmSync } from "fs";
|
|
224
|
+
import { copyFile, readFile, writeFile } from "fs/promises";
|
|
225
|
+
import { tmpdir } from "os";
|
|
226
|
+
import { join } from "path";
|
|
227
|
+
import { Effect as Effect3 } from "effect";
|
|
228
|
+
var INSTANT_ANIMATIONS_CDP_SCRIPT = `
|
|
229
|
+
(() => {
|
|
230
|
+
const inject = () => {
|
|
231
|
+
if (document.getElementById("__spana_instant_anim")) return;
|
|
232
|
+
const style = document.createElement("style");
|
|
233
|
+
style.id = "__spana_instant_anim";
|
|
234
|
+
style.textContent = "*, *::before, *::after { transition-duration: 0.001ms !important; transition-delay: 0ms !important; animation-duration: 0.001ms !important; animation-delay: 0ms !important; scroll-behavior: auto !important; }";
|
|
235
|
+
(document.head || document.documentElement).appendChild(style);
|
|
236
|
+
};
|
|
237
|
+
if (document.readyState === "loading") {
|
|
238
|
+
document.addEventListener("DOMContentLoaded", inject, { once: true });
|
|
239
|
+
} else {
|
|
240
|
+
inject();
|
|
241
|
+
}
|
|
242
|
+
})();
|
|
243
|
+
`;
|
|
244
|
+
function resolveDirectCdpScopeKey(scope) {
|
|
245
|
+
if (scope && scope.trim().length > 0) return scope.trim();
|
|
246
|
+
const cwdHash = createHash("sha1").update(process.cwd()).digest("hex").slice(0, 10);
|
|
247
|
+
return `cdp-${cwdHash}`;
|
|
248
|
+
}
|
|
249
|
+
function resolveChromiumExecutable(explicit) {
|
|
250
|
+
if (explicit && existsSync(explicit)) return explicit;
|
|
251
|
+
const candidates = process.platform === "darwin" ? [
|
|
252
|
+
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
|
253
|
+
"/Applications/Chromium.app/Contents/MacOS/Chromium",
|
|
254
|
+
"/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",
|
|
255
|
+
"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"
|
|
256
|
+
] : process.platform === "linux" ? [
|
|
257
|
+
"/usr/bin/google-chrome",
|
|
258
|
+
"/usr/bin/google-chrome-stable",
|
|
259
|
+
"/usr/bin/chromium",
|
|
260
|
+
"/usr/bin/chromium-browser"
|
|
261
|
+
] : [
|
|
262
|
+
"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
|
|
263
|
+
"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
|
|
264
|
+
];
|
|
265
|
+
for (const path of candidates) {
|
|
266
|
+
if (existsSync(path)) return path;
|
|
267
|
+
}
|
|
268
|
+
return explicit ?? "google-chrome";
|
|
269
|
+
}
|
|
270
|
+
async function fetchBrowserWsUrl(httpEndpoint, timeoutMs = 1e4) {
|
|
271
|
+
const deadline = Date.now() + timeoutMs;
|
|
272
|
+
while (Date.now() < deadline) {
|
|
273
|
+
try {
|
|
274
|
+
const res = await fetch(`${httpEndpoint}/json/version`, {
|
|
275
|
+
signal: AbortSignal.timeout(500)
|
|
276
|
+
});
|
|
277
|
+
if (res.ok) {
|
|
278
|
+
const data = await res.json();
|
|
279
|
+
if (data.webSocketDebuggerUrl) return data.webSocketDebuggerUrl;
|
|
280
|
+
}
|
|
281
|
+
} catch {
|
|
282
|
+
}
|
|
283
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
284
|
+
}
|
|
285
|
+
throw new Error(`Direct CDP browser did not expose /json/version on ${httpEndpoint}`);
|
|
286
|
+
}
|
|
287
|
+
async function launchDirectCdpBrowser(options = {}) {
|
|
288
|
+
const daemonKey = resolveDirectCdpScopeKey(options.warmBrowserScope);
|
|
289
|
+
if (options.warmBrowser) {
|
|
290
|
+
const existing = await getHealthyWarmDaemon("chromium", daemonKey, {
|
|
291
|
+
statusPath: "/json/version"
|
|
292
|
+
});
|
|
293
|
+
if (existing) {
|
|
294
|
+
const httpEndpoint2 = `http://${existing.host}:${existing.port}`;
|
|
295
|
+
try {
|
|
296
|
+
const browserWsUrl2 = await fetchBrowserWsUrl(httpEndpoint2, 1500);
|
|
297
|
+
return {
|
|
298
|
+
httpEndpoint: httpEndpoint2,
|
|
299
|
+
browserWsUrl: browserWsUrl2,
|
|
300
|
+
reused: true,
|
|
301
|
+
pid: existing.pid,
|
|
302
|
+
close: async () => {
|
|
303
|
+
}
|
|
304
|
+
};
|
|
305
|
+
} catch {
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
let execPath = options.executablePath;
|
|
310
|
+
if (!execPath) {
|
|
311
|
+
try {
|
|
312
|
+
const { chromium } = await import("playwright-core");
|
|
313
|
+
const pwPath = chromium.executablePath();
|
|
314
|
+
if (pwPath && existsSync(pwPath)) {
|
|
315
|
+
execPath = pwPath;
|
|
316
|
+
}
|
|
317
|
+
} catch {
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
execPath = resolveChromiumExecutable(execPath);
|
|
321
|
+
const port = allocatePort(9350);
|
|
322
|
+
const userDataDir = mkdtempSync(join(tmpdir(), "spana-cdp-profile-"));
|
|
323
|
+
const chromeArgs = [
|
|
324
|
+
...options.headless !== false ? ["--headless=new"] : [],
|
|
325
|
+
`--remote-debugging-port=${port}`,
|
|
326
|
+
"--remote-debugging-address=127.0.0.1",
|
|
327
|
+
`--user-data-dir=${userDataDir}`,
|
|
328
|
+
"--no-first-run",
|
|
329
|
+
"--no-default-browser-check",
|
|
330
|
+
"--disable-background-networking",
|
|
331
|
+
"--disable-background-timer-throttling",
|
|
332
|
+
"--disable-backgrounding-occluded-windows",
|
|
333
|
+
"--disable-renderer-backgrounding",
|
|
334
|
+
"--disable-ipc-flooding-protection",
|
|
335
|
+
"--disable-hang-monitor",
|
|
336
|
+
"--disable-default-apps",
|
|
337
|
+
"--disable-extensions",
|
|
338
|
+
"--disable-sync",
|
|
339
|
+
...options.headless !== false ? ["--disable-gpu"] : [],
|
|
340
|
+
"--metrics-recording-only",
|
|
341
|
+
"--disable-features=Translate,BackForwardCache,AcceptCHFrame,MediaRouter,OptimizationHints",
|
|
342
|
+
...options.args ?? [],
|
|
343
|
+
"about:blank"
|
|
344
|
+
];
|
|
345
|
+
const child = spawn(execPath, chromeArgs, {
|
|
346
|
+
detached: Boolean(options.warmBrowser),
|
|
347
|
+
stdio: "ignore"
|
|
348
|
+
});
|
|
349
|
+
if (options.warmBrowser) {
|
|
350
|
+
child.unref();
|
|
351
|
+
}
|
|
352
|
+
const httpEndpoint = `http://127.0.0.1:${port}`;
|
|
353
|
+
const browserWsUrl = await fetchBrowserWsUrl(httpEndpoint, 1e4);
|
|
354
|
+
if (options.warmBrowser) {
|
|
355
|
+
registerWarmDaemon({
|
|
356
|
+
kind: "chromium",
|
|
357
|
+
deviceId: daemonKey,
|
|
358
|
+
host: "127.0.0.1",
|
|
359
|
+
port,
|
|
360
|
+
pid: child.pid,
|
|
361
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
return {
|
|
365
|
+
httpEndpoint,
|
|
366
|
+
browserWsUrl,
|
|
367
|
+
reused: Boolean(options.warmBrowser),
|
|
368
|
+
pid: child.pid,
|
|
369
|
+
close: async () => {
|
|
370
|
+
if (options.warmBrowser) return;
|
|
371
|
+
try {
|
|
372
|
+
child.kill("SIGTERM");
|
|
373
|
+
} catch {
|
|
374
|
+
}
|
|
375
|
+
await new Promise((r) => setTimeout(r, 200));
|
|
376
|
+
rmSync(userDataDir, { recursive: true, force: true });
|
|
377
|
+
}
|
|
378
|
+
};
|
|
379
|
+
}
|
|
547
380
|
var CDP_DUMP_HIERARCHY_SCRIPT = `(() => {
|
|
548
381
|
function walk(el) {
|
|
549
382
|
const rect = el.getBoundingClientRect ? el.getBoundingClientRect() : { x: 0, y: 0, width: 0, height: 0 };
|
|
@@ -564,16 +397,44 @@ var CDP_DUMP_HIERARCHY_SCRIPT = `(() => {
|
|
|
564
397
|
}
|
|
565
398
|
return document.body ? JSON.stringify(walk(document.body)) : JSON.stringify({ bounds: { x: 0, y: 0, width: 0, height: 0 }, children: [] });
|
|
566
399
|
})()`;
|
|
400
|
+
function matchUrl(matcher, url) {
|
|
401
|
+
if (matcher instanceof RegExp) return matcher.test(url);
|
|
402
|
+
if (matcher.includes("*")) {
|
|
403
|
+
const escaped = matcher.replaceAll(/[.+?^${}()|[\]\\]/g, "\\$&").replaceAll("**", ".*").replaceAll("*", "[^/]*");
|
|
404
|
+
return new RegExp(escaped).test(url);
|
|
405
|
+
}
|
|
406
|
+
return url.includes(matcher);
|
|
407
|
+
}
|
|
408
|
+
var RESOURCE_BLOCK_PATTERNS = {
|
|
409
|
+
image: ["*.png", "*.jpg", "*.jpeg", "*.gif", "*.webp", "*.svg", "*.ico", "*.avif"],
|
|
410
|
+
font: ["*.woff", "*.woff2", "*.ttf", "*.otf", "*.eot"],
|
|
411
|
+
media: ["*.mp4", "*.webm", "*.ogg", "*.mp3", "*.wav", "*.m4a"],
|
|
412
|
+
stylesheet: ["*.css"]
|
|
413
|
+
};
|
|
567
414
|
function makeLightweightCdpDriver(options) {
|
|
568
|
-
return
|
|
415
|
+
return Effect3.gen(function* () {
|
|
416
|
+
const isBrowserWs = options.cdpUrl.includes("/devtools/browser/");
|
|
417
|
+
const useContexts = Boolean(
|
|
418
|
+
options.useBrowserContexts || options.freshContextPerFlow || isBrowserWs
|
|
419
|
+
);
|
|
569
420
|
const isWs = options.cdpUrl.startsWith("ws://") || options.cdpUrl.startsWith("wss://");
|
|
421
|
+
const httpEndpoint = isWs ? options.cdpUrl.replace(/^ws(s?):\/\//, "http$1://").replace(/\/devtools\/.*$/, "") : options.cdpUrl.replace(/\/+$/, "");
|
|
422
|
+
let connectWsUrl = isWs ? options.cdpUrl : void 0;
|
|
423
|
+
if (useContexts && !connectWsUrl) {
|
|
424
|
+
connectWsUrl = yield* Effect3.tryPromise({
|
|
425
|
+
try: () => fetchBrowserWsUrl(httpEndpoint, 5e3),
|
|
426
|
+
catch: (e) => new DriverError({
|
|
427
|
+
message: `Failed to resolve browser CDP WebSocket at ${options.cdpUrl}: ${e}`
|
|
428
|
+
})
|
|
429
|
+
});
|
|
430
|
+
}
|
|
570
431
|
const cdpChannel = new CdpDomChannel({
|
|
571
|
-
endpointUrl:
|
|
572
|
-
...
|
|
432
|
+
endpointUrl: httpEndpoint,
|
|
433
|
+
...connectWsUrl ? { webSocketUrl: connectWsUrl } : {},
|
|
573
434
|
fetchFn: options.fetchFn,
|
|
574
435
|
createWebSocket: options.createWebSocket
|
|
575
436
|
});
|
|
576
|
-
yield*
|
|
437
|
+
yield* Effect3.tryPromise({
|
|
577
438
|
try: () => cdpChannel.connect(),
|
|
578
439
|
catch: (e) => new DriverError({
|
|
579
440
|
message: `Failed to connect lightweight CDP browser at ${options.cdpUrl}: ${e}`
|
|
@@ -582,41 +443,329 @@ function makeLightweightCdpDriver(options) {
|
|
|
582
443
|
const width = options.viewport?.width ?? 1280;
|
|
583
444
|
const height = options.viewport?.height ?? 720;
|
|
584
445
|
const label = options.engineLabel ?? "cdp";
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
446
|
+
let activeSlot;
|
|
447
|
+
let prefetchedSlotPromise;
|
|
448
|
+
let hasRunFirstFlow = false;
|
|
449
|
+
let activeAuthenticatorId;
|
|
450
|
+
const backgroundDisposals = [];
|
|
451
|
+
const consoleLogs = [];
|
|
452
|
+
const jsErrors = [];
|
|
453
|
+
const routeRules = [];
|
|
454
|
+
let fetchInterceptEnabled = false;
|
|
455
|
+
let nextTabSeq = 1;
|
|
456
|
+
let downloadDir;
|
|
457
|
+
const completedDownloads = [];
|
|
458
|
+
const downloadWaiters = [];
|
|
459
|
+
const pendingDownloadGuids = /* @__PURE__ */ new Map();
|
|
460
|
+
cdpChannel.onEvent("Browser.downloadWillBegin", (params) => {
|
|
461
|
+
if (params?.guid && downloadDir) {
|
|
462
|
+
pendingDownloadGuids.set(String(params.guid), join(downloadDir, String(params.guid)));
|
|
463
|
+
}
|
|
464
|
+
});
|
|
465
|
+
cdpChannel.onEvent("Browser.downloadProgress", (params) => {
|
|
466
|
+
if (params?.state === "completed" && params?.guid) {
|
|
467
|
+
const filePath = pendingDownloadGuids.get(String(params.guid)) ?? (downloadDir ? join(downloadDir, String(params.guid)) : "");
|
|
468
|
+
pendingDownloadGuids.delete(String(params.guid));
|
|
469
|
+
if (!filePath) return;
|
|
470
|
+
const waiter = downloadWaiters.shift();
|
|
471
|
+
if (waiter) waiter.resolve(filePath);
|
|
472
|
+
else completedDownloads.push(filePath);
|
|
473
|
+
}
|
|
474
|
+
});
|
|
475
|
+
const loadStorageStateFile = async (path) => {
|
|
476
|
+
if (!path) return null;
|
|
477
|
+
try {
|
|
478
|
+
const raw = await readFile(path, "utf8");
|
|
479
|
+
return JSON.parse(raw);
|
|
480
|
+
} catch {
|
|
481
|
+
return null;
|
|
482
|
+
}
|
|
483
|
+
};
|
|
484
|
+
const attachVirtualAuthenticatorForSession = async (sessionId, opts) => {
|
|
485
|
+
await cdpChannel.sendCommand("WebAuthn.enable", { enableUI: false }, sessionId);
|
|
486
|
+
const res = await cdpChannel.sendCommand(
|
|
487
|
+
"WebAuthn.addVirtualAuthenticator",
|
|
488
|
+
{
|
|
489
|
+
options: {
|
|
490
|
+
protocol: opts?.protocol ?? "ctap2",
|
|
491
|
+
transport: opts?.transport ?? "internal",
|
|
492
|
+
hasResidentKey: opts?.hasResidentKey ?? true,
|
|
493
|
+
hasUserVerification: opts?.hasUserVerification ?? true,
|
|
494
|
+
isUserVerified: opts?.isUserVerified ?? true,
|
|
495
|
+
automaticPresenceSimulation: opts?.automaticPresenceSimulation ?? true
|
|
496
|
+
}
|
|
497
|
+
},
|
|
498
|
+
sessionId
|
|
499
|
+
);
|
|
500
|
+
return res?.authenticatorId ?? "cdp-virtual-auth-1";
|
|
501
|
+
};
|
|
502
|
+
const configureSession = async (sessionId, storageStatePath) => {
|
|
503
|
+
const state = await loadStorageStateFile(storageStatePath);
|
|
504
|
+
const needsNetworkDomain = Boolean(
|
|
505
|
+
options.blockResources && options.blockResources.length > 0 || state?.cookies && state.cookies.length > 0
|
|
506
|
+
);
|
|
507
|
+
await Promise.all([
|
|
508
|
+
cdpChannel.sendCommand("Page.enable", {}, sessionId).catch(() => {
|
|
509
|
+
}),
|
|
510
|
+
cdpChannel.sendCommand("Runtime.enable", {}, sessionId).catch(() => {
|
|
511
|
+
}),
|
|
512
|
+
...needsNetworkDomain ? [cdpChannel.sendCommand("Network.enable", {}, sessionId).catch(() => {
|
|
513
|
+
})] : [],
|
|
514
|
+
cdpChannel.sendCommand(
|
|
515
|
+
"Emulation.setDeviceMetricsOverride",
|
|
516
|
+
{ width, height, deviceScaleFactor: 1, mobile: false },
|
|
517
|
+
sessionId
|
|
518
|
+
).catch(() => {
|
|
519
|
+
})
|
|
520
|
+
]);
|
|
521
|
+
if (options.instantAnimations) {
|
|
522
|
+
await cdpChannel.sendCommand(
|
|
523
|
+
"Page.addScriptToEvaluateOnNewDocument",
|
|
524
|
+
{ source: INSTANT_ANIMATIONS_CDP_SCRIPT },
|
|
525
|
+
sessionId
|
|
526
|
+
).catch(() => {
|
|
527
|
+
});
|
|
528
|
+
}
|
|
529
|
+
if (options.blockResources && options.blockResources.length > 0) {
|
|
530
|
+
const urls = options.blockResources.flatMap((t) => RESOURCE_BLOCK_PATTERNS[t] ?? []);
|
|
531
|
+
if (urls.length > 0) {
|
|
532
|
+
await cdpChannel.sendCommand("Network.setBlockedURLs", { urls }, sessionId).catch(() => {
|
|
533
|
+
});
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
if (state?.cookies && state.cookies.length > 0) {
|
|
537
|
+
await cdpChannel.sendCommand("Network.setCookies", { cookies: state.cookies }, sessionId).catch(() => {
|
|
538
|
+
});
|
|
539
|
+
}
|
|
540
|
+
if (state?.origins && state.origins.length > 0) {
|
|
541
|
+
const originsJson = JSON.stringify(state.origins);
|
|
542
|
+
await cdpChannel.sendCommand(
|
|
543
|
+
"Page.addScriptToEvaluateOnNewDocument",
|
|
544
|
+
{
|
|
545
|
+
source: `(() => {
|
|
546
|
+
const origins = ${originsJson};
|
|
547
|
+
const hit = origins.find((o) => o.origin === window.location.origin);
|
|
548
|
+
if (hit && Array.isArray(hit.localStorage)) {
|
|
549
|
+
for (const item of hit.localStorage) {
|
|
550
|
+
try { window.localStorage.setItem(item.name, item.value); } catch {}
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
})();`
|
|
554
|
+
},
|
|
555
|
+
sessionId
|
|
556
|
+
).catch(() => {
|
|
557
|
+
});
|
|
558
|
+
}
|
|
559
|
+
if (routeRules.length > 0) {
|
|
560
|
+
await cdpChannel.sendCommand("Fetch.enable", { patterns: [{ urlPattern: "*" }] }, sessionId).catch(() => {
|
|
561
|
+
});
|
|
562
|
+
}
|
|
563
|
+
let authenticatorId;
|
|
564
|
+
if (options.virtualAuthenticator) {
|
|
565
|
+
const authOpts = typeof options.virtualAuthenticator === "object" ? options.virtualAuthenticator : void 0;
|
|
566
|
+
authenticatorId = await attachVirtualAuthenticatorForSession(sessionId, authOpts).catch(
|
|
567
|
+
() => void 0
|
|
568
|
+
);
|
|
569
|
+
}
|
|
570
|
+
return authenticatorId;
|
|
571
|
+
};
|
|
572
|
+
const createContextSlot = async (storageStatePath) => {
|
|
573
|
+
const ctxRes = await cdpChannel.sendCommand(
|
|
574
|
+
"Target.createBrowserContext",
|
|
575
|
+
{ disposeOnDetach: true },
|
|
576
|
+
null
|
|
577
|
+
);
|
|
578
|
+
const targetRes = await cdpChannel.sendCommand(
|
|
579
|
+
"Target.createTarget",
|
|
580
|
+
{ url: "about:blank", browserContextId: ctxRes.browserContextId, width, height },
|
|
581
|
+
null
|
|
582
|
+
);
|
|
583
|
+
const attachRes = await cdpChannel.sendCommand(
|
|
584
|
+
"Target.attachToTarget",
|
|
585
|
+
{ targetId: targetRes.targetId, flatten: true },
|
|
586
|
+
null
|
|
587
|
+
);
|
|
588
|
+
const authenticatorId = await configureSession(
|
|
589
|
+
attachRes.sessionId,
|
|
590
|
+
storageStatePath ?? options.storageState
|
|
591
|
+
);
|
|
592
|
+
const firstTabId = `tab-${nextTabSeq++}`;
|
|
593
|
+
return {
|
|
594
|
+
browserContextId: ctxRes.browserContextId,
|
|
595
|
+
targetId: targetRes.targetId,
|
|
596
|
+
sessionId: attachRes.sessionId,
|
|
597
|
+
authenticatorId,
|
|
598
|
+
tabs: [{ tabId: firstTabId, targetId: targetRes.targetId, sessionId: attachRes.sessionId }]
|
|
599
|
+
};
|
|
600
|
+
};
|
|
601
|
+
const disposeSlotInBackground = (slot) => {
|
|
602
|
+
const p = new Promise((r) => setTimeout(r, 120)).then(
|
|
603
|
+
() => cdpChannel.sendCommand(
|
|
604
|
+
"Target.disposeBrowserContext",
|
|
605
|
+
{ browserContextId: slot.browserContextId },
|
|
606
|
+
null
|
|
607
|
+
)
|
|
608
|
+
).catch(() => {
|
|
609
|
+
}).finally(() => {
|
|
610
|
+
const idx = backgroundDisposals.indexOf(p);
|
|
611
|
+
if (idx >= 0) backgroundDisposals.splice(idx, 1);
|
|
612
|
+
});
|
|
613
|
+
backgroundDisposals.push(p);
|
|
614
|
+
};
|
|
615
|
+
const schedulePrefetch = () => {
|
|
616
|
+
if (!useContexts || !options.freshContextPerFlow || prefetchedSlotPromise) return;
|
|
617
|
+
prefetchedSlotPromise = createContextSlot(options.storageState);
|
|
618
|
+
prefetchedSlotPromise.catch(() => {
|
|
619
|
+
prefetchedSlotPromise = void 0;
|
|
620
|
+
});
|
|
621
|
+
};
|
|
622
|
+
cdpChannel.onEvent("Runtime.consoleAPICalled", (params, sid) => {
|
|
623
|
+
if (activeSlot && sid && sid !== activeSlot.sessionId) return;
|
|
624
|
+
const args = Array.isArray(params?.args) ? params.args.map((a) => a.value ?? a.description ?? "").join(" ") : "";
|
|
625
|
+
consoleLogs.push({ type: String(params?.type ?? "log"), text: args });
|
|
626
|
+
});
|
|
627
|
+
cdpChannel.onEvent("Runtime.exceptionThrown", (params, sid) => {
|
|
628
|
+
if (activeSlot && sid && sid !== activeSlot.sessionId) return;
|
|
629
|
+
const detail = params?.exceptionDetails;
|
|
630
|
+
jsErrors.push({
|
|
631
|
+
name: detail?.exception?.className ?? "Error",
|
|
632
|
+
message: detail?.exception?.description ?? detail?.text ?? "Uncaught exception"
|
|
633
|
+
});
|
|
634
|
+
});
|
|
635
|
+
cdpChannel.onEvent("Fetch.requestPaused", (params, sid) => {
|
|
636
|
+
const reqId = params?.requestId;
|
|
637
|
+
const url = String(params?.request?.url ?? "");
|
|
638
|
+
if (!reqId) return;
|
|
639
|
+
const rule = routeRules.find((r) => matchUrl(r.matcher, url));
|
|
640
|
+
if (!rule) {
|
|
641
|
+
void cdpChannel.sendCommand("Fetch.continueRequest", { requestId: reqId }, sid ?? null).catch(() => {
|
|
642
|
+
});
|
|
643
|
+
return;
|
|
644
|
+
}
|
|
645
|
+
if (rule.kind === "block") {
|
|
646
|
+
void cdpChannel.sendCommand(
|
|
647
|
+
"Fetch.failRequest",
|
|
648
|
+
{ requestId: reqId, errorReason: "BlockedByClient" },
|
|
649
|
+
sid ?? null
|
|
650
|
+
).catch(() => {
|
|
651
|
+
});
|
|
652
|
+
return;
|
|
653
|
+
}
|
|
654
|
+
const resp = rule.response ?? {};
|
|
655
|
+
const bodyStr = resp.json !== void 0 ? JSON.stringify(resp.json) : resp.body ?? "";
|
|
656
|
+
const headersObj = { ...resp.headers };
|
|
657
|
+
if (resp.contentType && !Object.keys(headersObj).some((k) => k.toLowerCase() === "content-type")) {
|
|
658
|
+
headersObj["content-type"] = resp.contentType;
|
|
659
|
+
} else if (resp.json !== void 0 && !Object.keys(headersObj).some((k) => k.toLowerCase() === "content-type")) {
|
|
660
|
+
headersObj["content-type"] = "application/json";
|
|
661
|
+
}
|
|
662
|
+
const responseHeaders = Object.entries(headersObj).map(([name, value]) => ({ name, value }));
|
|
663
|
+
void cdpChannel.sendCommand(
|
|
664
|
+
"Fetch.fulfillRequest",
|
|
665
|
+
{
|
|
666
|
+
requestId: reqId,
|
|
667
|
+
responseCode: resp.status ?? 200,
|
|
668
|
+
responseHeaders,
|
|
669
|
+
body: Buffer.from(bodyStr, "utf8").toString("base64")
|
|
670
|
+
},
|
|
671
|
+
sid ?? null
|
|
672
|
+
).catch(() => {
|
|
673
|
+
});
|
|
674
|
+
});
|
|
675
|
+
if (useContexts) {
|
|
676
|
+
activeSlot = yield* Effect3.tryPromise({
|
|
677
|
+
try: () => createContextSlot(options.storageState),
|
|
678
|
+
catch: (e) => new DriverError({ message: `Failed to create direct CDP browser context: ${e}` })
|
|
588
679
|
});
|
|
680
|
+
cdpChannel.setSessionId(activeSlot.sessionId);
|
|
681
|
+
activeAuthenticatorId = activeSlot.authenticatorId;
|
|
682
|
+
}
|
|
683
|
+
const resolveUrl = (rawUrl) => rawUrl.startsWith("http://") || rawUrl.startsWith("https://") || rawUrl === "about:blank" ? rawUrl : options.baseUrl ? `${options.baseUrl.replace(/\/$/, "")}/${rawUrl.replace(/^\//, "")}` : rawUrl;
|
|
684
|
+
const navigate = async (rawUrl) => {
|
|
685
|
+
const target = resolveUrl(rawUrl);
|
|
686
|
+
if (!useContexts) {
|
|
687
|
+
await cdpChannel.sendCommand("Page.enable").catch(() => {
|
|
688
|
+
});
|
|
689
|
+
await cdpChannel.sendCommand("Page.navigate", { url: target });
|
|
690
|
+
return;
|
|
691
|
+
}
|
|
692
|
+
const waitUntil = options.waitUntil ?? "load";
|
|
693
|
+
const targetSid = activeSlot?.sessionId;
|
|
694
|
+
if (waitUntil === "commit" || target === "about:blank") {
|
|
695
|
+
await cdpChannel.sendCommand("Page.navigate", { url: target });
|
|
696
|
+
return;
|
|
697
|
+
}
|
|
698
|
+
const eventName = waitUntil === "domcontentloaded" ? "Page.domContentEventFired" : "Page.loadEventFired";
|
|
699
|
+
const waiter = cdpChannel.waitForEvent(
|
|
700
|
+
eventName,
|
|
701
|
+
15e3,
|
|
702
|
+
(_p, sid) => !targetSid || !sid || sid === targetSid
|
|
703
|
+
);
|
|
589
704
|
await cdpChannel.sendCommand("Page.navigate", { url: target });
|
|
705
|
+
await waiter.catch(() => {
|
|
706
|
+
});
|
|
707
|
+
schedulePrefetch();
|
|
708
|
+
};
|
|
709
|
+
const ensureFetchIntercept = async () => {
|
|
710
|
+
if (fetchInterceptEnabled) return;
|
|
711
|
+
fetchInterceptEnabled = true;
|
|
712
|
+
await cdpChannel.sendCommand("Fetch.enable", { patterns: [{ urlPattern: "*" }] });
|
|
590
713
|
};
|
|
591
714
|
const service = {
|
|
592
715
|
domChannel: cdpChannel,
|
|
593
|
-
|
|
716
|
+
beginFlow: (_flowName) => Effect3.tryPromise({
|
|
717
|
+
try: async () => {
|
|
718
|
+
consoleLogs.length = 0;
|
|
719
|
+
jsErrors.length = 0;
|
|
720
|
+
if (useContexts && options.freshContextPerFlow && hasRunFirstFlow) {
|
|
721
|
+
const previousSlot = activeSlot;
|
|
722
|
+
const pending = prefetchedSlotPromise;
|
|
723
|
+
prefetchedSlotPromise = void 0;
|
|
724
|
+
activeSlot = pending ? await pending : await createContextSlot(options.storageState);
|
|
725
|
+
cdpChannel.setSessionId(activeSlot.sessionId);
|
|
726
|
+
activeAuthenticatorId = activeSlot.authenticatorId;
|
|
727
|
+
if (previousSlot) {
|
|
728
|
+
disposeSlotInBackground(previousSlot);
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
hasRunFirstFlow = true;
|
|
732
|
+
},
|
|
733
|
+
catch: (e) => new DriverError({ message: `CDP beginFlow failed: ${e}` })
|
|
734
|
+
}),
|
|
735
|
+
dumpHierarchy: () => Effect3.tryPromise({
|
|
594
736
|
try: async () => {
|
|
595
737
|
const raw = await cdpChannel.evaluate(CDP_DUMP_HIERARCHY_SCRIPT);
|
|
596
738
|
return raw ?? "{}";
|
|
597
739
|
},
|
|
598
740
|
catch: (e) => new DriverError({ message: `CDP dumpHierarchy failed: ${e}` })
|
|
599
741
|
}),
|
|
600
|
-
tapAtCoordinate: (x, y) =>
|
|
742
|
+
tapAtCoordinate: (x, y) => Effect3.tryPromise({
|
|
601
743
|
try: async () => {
|
|
602
|
-
await
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
744
|
+
await Promise.all([
|
|
745
|
+
cdpChannel.sendCommand("Input.dispatchMouseEvent", {
|
|
746
|
+
type: "mouseMoved",
|
|
747
|
+
x,
|
|
748
|
+
y
|
|
749
|
+
}),
|
|
750
|
+
cdpChannel.sendCommand("Input.dispatchMouseEvent", {
|
|
751
|
+
type: "mousePressed",
|
|
752
|
+
x,
|
|
753
|
+
y,
|
|
754
|
+
button: "left",
|
|
755
|
+
clickCount: 1
|
|
756
|
+
}),
|
|
757
|
+
cdpChannel.sendCommand("Input.dispatchMouseEvent", {
|
|
758
|
+
type: "mouseReleased",
|
|
759
|
+
x,
|
|
760
|
+
y,
|
|
761
|
+
button: "left",
|
|
762
|
+
clickCount: 1
|
|
763
|
+
})
|
|
764
|
+
]);
|
|
616
765
|
},
|
|
617
766
|
catch: (e) => new DriverError({ message: `CDP tap failed at (${x}, ${y}): ${e}` })
|
|
618
767
|
}),
|
|
619
|
-
doubleTapAtCoordinate: (x, y) =>
|
|
768
|
+
doubleTapAtCoordinate: (x, y) => Effect3.tryPromise({
|
|
620
769
|
try: async () => {
|
|
621
770
|
await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
|
|
622
771
|
type: "mousePressed",
|
|
@@ -635,7 +784,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
635
784
|
},
|
|
636
785
|
catch: (e) => new DriverError({ message: `CDP doubleTap failed: ${e}` })
|
|
637
786
|
}),
|
|
638
|
-
longPressAtCoordinate: (x, y, duration) =>
|
|
787
|
+
longPressAtCoordinate: (x, y, duration) => Effect3.tryPromise({
|
|
639
788
|
try: async () => {
|
|
640
789
|
await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
|
|
641
790
|
type: "mousePressed",
|
|
@@ -655,7 +804,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
655
804
|
},
|
|
656
805
|
catch: (e) => new DriverError({ message: `CDP longPress failed: ${e}` })
|
|
657
806
|
}),
|
|
658
|
-
swipe: (startX, startY, endX, endY) =>
|
|
807
|
+
swipe: (startX, startY, endX, endY) => Effect3.tryPromise({
|
|
659
808
|
try: async () => {
|
|
660
809
|
const dx = startX - endX;
|
|
661
810
|
const dy = startY - endY;
|
|
@@ -663,21 +812,21 @@ function makeLightweightCdpDriver(options) {
|
|
|
663
812
|
},
|
|
664
813
|
catch: (e) => new DriverError({ message: `CDP swipe failed: ${e}` })
|
|
665
814
|
}),
|
|
666
|
-
inputText: (text) =>
|
|
815
|
+
inputText: (text) => Effect3.tryPromise({
|
|
667
816
|
try: async () => {
|
|
668
817
|
await cdpChannel.sendCommand("Input.insertText", { text });
|
|
669
818
|
},
|
|
670
819
|
catch: (e) => new DriverError({ message: `CDP inputText failed: ${e}` })
|
|
671
820
|
}),
|
|
672
|
-
pressKey: (key) =>
|
|
821
|
+
pressKey: (key) => Effect3.tryPromise({
|
|
673
822
|
try: async () => {
|
|
674
823
|
await cdpChannel.sendCommand("Input.dispatchKeyEvent", { type: "keyDown", key });
|
|
675
824
|
await cdpChannel.sendCommand("Input.dispatchKeyEvent", { type: "keyUp", key });
|
|
676
825
|
},
|
|
677
826
|
catch: (e) => new DriverError({ message: `CDP pressKey failed: ${e}` })
|
|
678
827
|
}),
|
|
679
|
-
hideKeyboard: () =>
|
|
680
|
-
takeScreenshot: () =>
|
|
828
|
+
hideKeyboard: () => Effect3.void,
|
|
829
|
+
takeScreenshot: () => Effect3.tryPromise({
|
|
681
830
|
try: async () => {
|
|
682
831
|
const res = await cdpChannel.sendCommand("Page.captureScreenshot", {
|
|
683
832
|
format: "png"
|
|
@@ -686,7 +835,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
686
835
|
},
|
|
687
836
|
catch: (e) => new DriverError({ message: `CDP screenshot failed: ${e}` })
|
|
688
837
|
}),
|
|
689
|
-
getDeviceInfo: () =>
|
|
838
|
+
getDeviceInfo: () => Effect3.succeed({
|
|
690
839
|
platform: "web",
|
|
691
840
|
deviceId: `${label}:${options.cdpUrl}`,
|
|
692
841
|
name: `${label} (CDP-direct)`,
|
|
@@ -695,44 +844,77 @@ function makeLightweightCdpDriver(options) {
|
|
|
695
844
|
screenHeight: height,
|
|
696
845
|
driverType: "cdp"
|
|
697
846
|
}),
|
|
698
|
-
launchApp: (url, opts) =>
|
|
847
|
+
launchApp: (url, opts) => Effect3.tryPromise({
|
|
699
848
|
try: async () => {
|
|
700
849
|
if (opts?.clearState) {
|
|
850
|
+
await cdpChannel.sendCommand("Network.clearBrowserCookies").catch(() => {
|
|
851
|
+
});
|
|
701
852
|
await cdpChannel.evaluate(
|
|
702
853
|
"try { localStorage.clear(); sessionStorage.clear(); } catch {}"
|
|
703
854
|
);
|
|
704
855
|
}
|
|
705
|
-
await navigate(url);
|
|
856
|
+
await navigate(opts?.deepLink || url || options.baseUrl || "about:blank");
|
|
706
857
|
},
|
|
707
858
|
catch: (e) => new DriverError({ message: `CDP launchApp failed: ${e}` })
|
|
708
859
|
}),
|
|
709
|
-
stopApp: () =>
|
|
860
|
+
stopApp: () => Effect3.tryPromise({
|
|
710
861
|
try: () => navigate("about:blank"),
|
|
711
862
|
catch: (e) => new DriverError({ message: `CDP stopApp failed: ${e}` })
|
|
712
863
|
}),
|
|
713
|
-
killApp: () =>
|
|
714
|
-
try: () =>
|
|
864
|
+
killApp: () => Effect3.tryPromise({
|
|
865
|
+
try: async () => {
|
|
866
|
+
const pendingPrefetch = prefetchedSlotPromise;
|
|
867
|
+
prefetchedSlotPromise = void 0;
|
|
868
|
+
if (useContexts) {
|
|
869
|
+
const slotsToDispose = [];
|
|
870
|
+
if (activeSlot) slotsToDispose.push(activeSlot);
|
|
871
|
+
if (pendingPrefetch) {
|
|
872
|
+
const prefetched = await pendingPrefetch.catch(() => void 0);
|
|
873
|
+
if (prefetched) slotsToDispose.push(prefetched);
|
|
874
|
+
}
|
|
875
|
+
await Promise.allSettled([
|
|
876
|
+
...slotsToDispose.map(
|
|
877
|
+
(s) => cdpChannel.sendCommand(
|
|
878
|
+
"Target.disposeBrowserContext",
|
|
879
|
+
{ browserContextId: s.browserContextId },
|
|
880
|
+
null
|
|
881
|
+
)
|
|
882
|
+
),
|
|
883
|
+
...backgroundDisposals
|
|
884
|
+
]);
|
|
885
|
+
}
|
|
886
|
+
if (downloadDir) {
|
|
887
|
+
try {
|
|
888
|
+
rmSync(downloadDir, { recursive: true, force: true });
|
|
889
|
+
} catch {
|
|
890
|
+
}
|
|
891
|
+
downloadDir = void 0;
|
|
892
|
+
}
|
|
893
|
+
await cdpChannel.disconnect();
|
|
894
|
+
},
|
|
715
895
|
catch: (e) => new DriverError({ message: `CDP disconnect failed: ${e}` })
|
|
716
896
|
}),
|
|
717
|
-
clearAppState: () =>
|
|
897
|
+
clearAppState: () => Effect3.tryPromise({
|
|
718
898
|
try: async () => {
|
|
899
|
+
await cdpChannel.sendCommand("Network.clearBrowserCookies").catch(() => {
|
|
900
|
+
});
|
|
719
901
|
await cdpChannel.evaluate(
|
|
720
902
|
"try { localStorage.clear(); sessionStorage.clear(); } catch {}"
|
|
721
903
|
);
|
|
722
904
|
},
|
|
723
905
|
catch: (e) => new DriverError({ message: `CDP clearAppState failed: ${e}` })
|
|
724
906
|
}),
|
|
725
|
-
openLink: (url) =>
|
|
907
|
+
openLink: (url) => Effect3.tryPromise({
|
|
726
908
|
try: () => navigate(url),
|
|
727
909
|
catch: (e) => new DriverError({ message: `CDP openLink failed: ${e}` })
|
|
728
910
|
}),
|
|
729
|
-
back: () =>
|
|
911
|
+
back: () => Effect3.tryPromise({
|
|
730
912
|
try: async () => {
|
|
731
913
|
await cdpChannel.evaluate("window.history.back()");
|
|
732
914
|
},
|
|
733
915
|
catch: (e) => new DriverError({ message: `CDP back failed: ${e}` })
|
|
734
916
|
}),
|
|
735
|
-
evaluate: (fn, ...args) =>
|
|
917
|
+
evaluate: (fn, ...args) => Effect3.tryPromise({
|
|
736
918
|
try: async () => {
|
|
737
919
|
if (typeof fn === "string") {
|
|
738
920
|
return await cdpChannel.evaluate(fn);
|
|
@@ -741,14 +923,290 @@ function makeLightweightCdpDriver(options) {
|
|
|
741
923
|
return await cdpChannel.evaluate(`(${fn.toString()})(${serializedArgs})`);
|
|
742
924
|
},
|
|
743
925
|
catch: (e) => new DriverError({ message: `CDP evaluate failed: ${e}` })
|
|
744
|
-
})
|
|
926
|
+
}),
|
|
927
|
+
getRawPage: () => ({
|
|
928
|
+
kind: "cdp",
|
|
929
|
+
cdpChannel,
|
|
930
|
+
sessionId: activeSlot?.sessionId ?? null,
|
|
931
|
+
browserContextId: activeSlot?.browserContextId ?? null
|
|
932
|
+
}),
|
|
933
|
+
mockNetwork: (matcher, response) => Effect3.tryPromise({
|
|
934
|
+
try: async () => {
|
|
935
|
+
routeRules.push({ kind: "mock", matcher, response });
|
|
936
|
+
await ensureFetchIntercept();
|
|
937
|
+
},
|
|
938
|
+
catch: (e) => new DriverError({ message: `CDP mockNetwork failed: ${e}` })
|
|
939
|
+
}),
|
|
940
|
+
blockNetwork: (matcher) => Effect3.tryPromise({
|
|
941
|
+
try: async () => {
|
|
942
|
+
routeRules.push({ kind: "block", matcher });
|
|
943
|
+
await ensureFetchIntercept();
|
|
944
|
+
},
|
|
945
|
+
catch: (e) => new DriverError({ message: `CDP blockNetwork failed: ${e}` })
|
|
946
|
+
}),
|
|
947
|
+
clearNetworkMocks: () => Effect3.tryPromise({
|
|
948
|
+
try: async () => {
|
|
949
|
+
routeRules.length = 0;
|
|
950
|
+
if (fetchInterceptEnabled) {
|
|
951
|
+
fetchInterceptEnabled = false;
|
|
952
|
+
await cdpChannel.sendCommand("Fetch.disable").catch(() => {
|
|
953
|
+
});
|
|
954
|
+
}
|
|
955
|
+
},
|
|
956
|
+
catch: (e) => new DriverError({ message: `CDP clearNetworkMocks failed: ${e}` })
|
|
957
|
+
}),
|
|
958
|
+
saveCookies: (path) => Effect3.tryPromise({
|
|
959
|
+
try: async () => {
|
|
960
|
+
const res = await cdpChannel.sendCommand("Network.getCookies");
|
|
961
|
+
await writeFile(path, JSON.stringify(res?.cookies ?? [], null, 2), "utf8");
|
|
962
|
+
},
|
|
963
|
+
catch: (e) => new DriverError({ message: `CDP saveCookies failed: ${e}` })
|
|
964
|
+
}),
|
|
965
|
+
loadCookies: (path) => Effect3.tryPromise({
|
|
966
|
+
try: async () => {
|
|
967
|
+
const cookies = JSON.parse(await readFile(path, "utf8"));
|
|
968
|
+
if (Array.isArray(cookies)) {
|
|
969
|
+
await cdpChannel.sendCommand("Network.setCookies", { cookies });
|
|
970
|
+
}
|
|
971
|
+
},
|
|
972
|
+
catch: (e) => new DriverError({ message: `CDP loadCookies failed: ${e}` })
|
|
973
|
+
}),
|
|
974
|
+
saveAuthState: (path) => Effect3.tryPromise({
|
|
975
|
+
try: async () => {
|
|
976
|
+
const res = await cdpChannel.sendCommand("Network.getCookies");
|
|
977
|
+
const originState = await cdpChannel.evaluate(
|
|
978
|
+
`(() => {
|
|
979
|
+
const entries = [];
|
|
980
|
+
try {
|
|
981
|
+
for (let i = 0; i < localStorage.length; i++) {
|
|
982
|
+
const k = localStorage.key(i);
|
|
983
|
+
if (k !== null) entries.push({ name: k, value: localStorage.getItem(k) ?? "" });
|
|
984
|
+
}
|
|
985
|
+
} catch {}
|
|
986
|
+
return { origin: window.location.origin, localStorage: entries };
|
|
987
|
+
})()`
|
|
988
|
+
).catch(() => null);
|
|
989
|
+
const payload = {
|
|
990
|
+
cookies: res?.cookies ?? [],
|
|
991
|
+
origins: originState && originState.origin !== "null" ? [originState] : []
|
|
992
|
+
};
|
|
993
|
+
await writeFile(path, JSON.stringify(payload, null, 2), "utf8");
|
|
994
|
+
},
|
|
995
|
+
catch: (e) => new DriverError({ message: `CDP saveAuthState failed: ${e}` })
|
|
996
|
+
}),
|
|
997
|
+
loadAuthState: (path) => Effect3.tryPromise({
|
|
998
|
+
try: async () => {
|
|
999
|
+
if (useContexts) {
|
|
1000
|
+
const previousSlot = activeSlot;
|
|
1001
|
+
activeSlot = await createContextSlot(path);
|
|
1002
|
+
cdpChannel.setSessionId(activeSlot.sessionId);
|
|
1003
|
+
activeAuthenticatorId = activeSlot.authenticatorId;
|
|
1004
|
+
if (previousSlot) disposeSlotInBackground(previousSlot);
|
|
1005
|
+
return;
|
|
1006
|
+
}
|
|
1007
|
+
const state = await loadStorageStateFile(path);
|
|
1008
|
+
if (state?.cookies?.length) {
|
|
1009
|
+
await cdpChannel.sendCommand("Network.setCookies", { cookies: state.cookies });
|
|
1010
|
+
}
|
|
1011
|
+
},
|
|
1012
|
+
catch: (e) => new DriverError({ message: `CDP loadAuthState failed: ${e}` })
|
|
1013
|
+
}),
|
|
1014
|
+
enableVirtualAuthenticator: (opts) => Effect3.tryPromise({
|
|
1015
|
+
try: async () => {
|
|
1016
|
+
activeAuthenticatorId = await attachVirtualAuthenticatorForSession(
|
|
1017
|
+
activeSlot?.sessionId ?? null,
|
|
1018
|
+
opts
|
|
1019
|
+
);
|
|
1020
|
+
return activeAuthenticatorId;
|
|
1021
|
+
},
|
|
1022
|
+
catch: (e) => new DriverError({ message: `CDP enableVirtualAuthenticator failed: ${e}` })
|
|
1023
|
+
}),
|
|
1024
|
+
removeVirtualAuthenticator: (authenticatorId) => Effect3.tryPromise({
|
|
1025
|
+
try: async () => {
|
|
1026
|
+
const id = authenticatorId ?? activeAuthenticatorId;
|
|
1027
|
+
if (!id) return;
|
|
1028
|
+
await cdpChannel.sendCommand("WebAuthn.removeVirtualAuthenticator", {
|
|
1029
|
+
authenticatorId: id
|
|
1030
|
+
});
|
|
1031
|
+
if (id === activeAuthenticatorId) activeAuthenticatorId = void 0;
|
|
1032
|
+
},
|
|
1033
|
+
catch: (e) => new DriverError({ message: `CDP removeVirtualAuthenticator failed: ${e}` })
|
|
1034
|
+
}),
|
|
1035
|
+
getVirtualCredentials: (authenticatorId) => Effect3.tryPromise({
|
|
1036
|
+
try: async () => {
|
|
1037
|
+
const id = authenticatorId ?? activeAuthenticatorId;
|
|
1038
|
+
if (!id) return [];
|
|
1039
|
+
const res = await cdpChannel.sendCommand("WebAuthn.getCredentials", {
|
|
1040
|
+
authenticatorId: id
|
|
1041
|
+
});
|
|
1042
|
+
return Array.isArray(res?.credentials) ? res.credentials : [];
|
|
1043
|
+
},
|
|
1044
|
+
catch: (e) => new DriverError({ message: `CDP getVirtualCredentials failed: ${e}` })
|
|
1045
|
+
}),
|
|
1046
|
+
clearVirtualCredentials: (authenticatorId) => Effect3.tryPromise({
|
|
1047
|
+
try: async () => {
|
|
1048
|
+
const id = authenticatorId ?? activeAuthenticatorId;
|
|
1049
|
+
if (!id) return;
|
|
1050
|
+
await cdpChannel.sendCommand("WebAuthn.clearCredentials", { authenticatorId: id });
|
|
1051
|
+
},
|
|
1052
|
+
catch: (e) => new DriverError({ message: `CDP clearVirtualCredentials failed: ${e}` })
|
|
1053
|
+
}),
|
|
1054
|
+
getConsoleLogs: () => Effect3.succeed([...consoleLogs]),
|
|
1055
|
+
getJSErrors: () => Effect3.succeed([...jsErrors]),
|
|
1056
|
+
setNetworkConditions: (conditions) => Effect3.tryPromise({
|
|
1057
|
+
try: async () => {
|
|
1058
|
+
const resolved = resolveNetworkConditions(conditions);
|
|
1059
|
+
await cdpChannel.sendCommand("Network.enable");
|
|
1060
|
+
await cdpChannel.sendCommand("Network.emulateNetworkConditions", {
|
|
1061
|
+
offline: resolved.offline,
|
|
1062
|
+
latency: resolved.latencyMs,
|
|
1063
|
+
downloadThroughput: resolved.downloadThroughputKbps < 0 ? -1 : Math.max(Math.round(resolved.downloadThroughputKbps * 1024 / 8), 0),
|
|
1064
|
+
uploadThroughput: resolved.uploadThroughputKbps < 0 ? -1 : Math.max(Math.round(resolved.uploadThroughputKbps * 1024 / 8), 0)
|
|
1065
|
+
});
|
|
1066
|
+
},
|
|
1067
|
+
catch: (e) => new DriverError({ message: `CDP setNetworkConditions failed: ${e}` })
|
|
1068
|
+
}),
|
|
1069
|
+
uploadFile: (selector, filePath) => Effect3.tryPromise({
|
|
1070
|
+
try: async () => {
|
|
1071
|
+
const serialized = JSON.stringify(selector);
|
|
1072
|
+
const expr = `(function(sel) {
|
|
1073
|
+
if (typeof sel === "object" && sel !== null && "testID" in sel) {
|
|
1074
|
+
return document.querySelector('[data-testid="' + sel.testID + '"], [testID="' + sel.testID + '"]');
|
|
1075
|
+
}
|
|
1076
|
+
if (typeof sel === "object" && sel !== null && "accessibilityLabel" in sel) {
|
|
1077
|
+
return document.querySelector('[aria-label="' + sel.accessibilityLabel + '"]');
|
|
1078
|
+
}
|
|
1079
|
+
return document.querySelector('input[type="file"]');
|
|
1080
|
+
})(${serialized})`;
|
|
1081
|
+
await cdpChannel.sendCommand("DOM.enable");
|
|
1082
|
+
const evalRes = await cdpChannel.sendCommand("Runtime.evaluate", {
|
|
1083
|
+
expression: expr,
|
|
1084
|
+
returnByValue: false
|
|
1085
|
+
});
|
|
1086
|
+
const objectId = evalRes?.result?.objectId;
|
|
1087
|
+
if (!objectId) {
|
|
1088
|
+
throw new Error(`No matching file input found for selector ${serialized}`);
|
|
1089
|
+
}
|
|
1090
|
+
const nodeRes = await cdpChannel.sendCommand("DOM.requestNode", { objectId });
|
|
1091
|
+
if (!nodeRes?.nodeId) {
|
|
1092
|
+
throw new Error("Failed to resolve DOM nodeId for file input");
|
|
1093
|
+
}
|
|
1094
|
+
await cdpChannel.sendCommand("DOM.setFileInputFiles", {
|
|
1095
|
+
nodeId: nodeRes.nodeId,
|
|
1096
|
+
files: [filePath]
|
|
1097
|
+
});
|
|
1098
|
+
},
|
|
1099
|
+
catch: (e) => new DriverError({ message: `CDP uploadFile failed: ${e}` })
|
|
1100
|
+
}),
|
|
1101
|
+
downloadFile: (destPath) => Effect3.tryPromise({
|
|
1102
|
+
try: async () => {
|
|
1103
|
+
if (!downloadDir) {
|
|
1104
|
+
downloadDir = mkdtempSync(join(tmpdir(), "spana-cdp-dl-"));
|
|
1105
|
+
await cdpChannel.sendCommand(
|
|
1106
|
+
"Browser.setDownloadBehavior",
|
|
1107
|
+
{
|
|
1108
|
+
behavior: "allowAndName",
|
|
1109
|
+
downloadPath: downloadDir,
|
|
1110
|
+
eventsEnabled: true,
|
|
1111
|
+
...activeSlot?.browserContextId ? { browserContextId: activeSlot.browserContextId } : {}
|
|
1112
|
+
},
|
|
1113
|
+
null
|
|
1114
|
+
);
|
|
1115
|
+
}
|
|
1116
|
+
const downloaded = completedDownloads.shift() ?? await new Promise((resolve, reject) => {
|
|
1117
|
+
const timer = setTimeout(() => {
|
|
1118
|
+
reject(new Error("Timed out waiting for CDP file download"));
|
|
1119
|
+
}, 15e3);
|
|
1120
|
+
downloadWaiters.push({
|
|
1121
|
+
resolve: (fp) => {
|
|
1122
|
+
clearTimeout(timer);
|
|
1123
|
+
resolve(fp);
|
|
1124
|
+
},
|
|
1125
|
+
reject: (err) => {
|
|
1126
|
+
clearTimeout(timer);
|
|
1127
|
+
reject(err);
|
|
1128
|
+
}
|
|
1129
|
+
});
|
|
1130
|
+
});
|
|
1131
|
+
await copyFile(downloaded, destPath);
|
|
1132
|
+
},
|
|
1133
|
+
catch: (e) => new DriverError({ message: `CDP downloadFile failed: ${e}` })
|
|
1134
|
+
}),
|
|
1135
|
+
newTab: (url) => Effect3.tryPromise({
|
|
1136
|
+
try: async () => {
|
|
1137
|
+
if (!activeSlot) {
|
|
1138
|
+
throw new Error("newTab() requires browser-context mode (engine: 'cdp')");
|
|
1139
|
+
}
|
|
1140
|
+
const targetRes = await cdpChannel.sendCommand(
|
|
1141
|
+
"Target.createTarget",
|
|
1142
|
+
{
|
|
1143
|
+
url: url ? resolveUrl(url) : "about:blank",
|
|
1144
|
+
browserContextId: activeSlot.browserContextId,
|
|
1145
|
+
width,
|
|
1146
|
+
height
|
|
1147
|
+
},
|
|
1148
|
+
null
|
|
1149
|
+
);
|
|
1150
|
+
const attachRes = await cdpChannel.sendCommand(
|
|
1151
|
+
"Target.attachToTarget",
|
|
1152
|
+
{ targetId: targetRes.targetId, flatten: true },
|
|
1153
|
+
null
|
|
1154
|
+
);
|
|
1155
|
+
await configureSession(attachRes.sessionId, options.storageState);
|
|
1156
|
+
const tabId = `tab-${nextTabSeq++}`;
|
|
1157
|
+
activeSlot.tabs.push({
|
|
1158
|
+
tabId,
|
|
1159
|
+
targetId: targetRes.targetId,
|
|
1160
|
+
sessionId: attachRes.sessionId
|
|
1161
|
+
});
|
|
1162
|
+
activeSlot.targetId = targetRes.targetId;
|
|
1163
|
+
activeSlot.sessionId = attachRes.sessionId;
|
|
1164
|
+
cdpChannel.setSessionId(attachRes.sessionId);
|
|
1165
|
+
return tabId;
|
|
1166
|
+
},
|
|
1167
|
+
catch: (e) => new DriverError({ message: `CDP newTab failed: ${e}` })
|
|
1168
|
+
}),
|
|
1169
|
+
switchToTab: (index) => Effect3.tryPromise({
|
|
1170
|
+
try: async () => {
|
|
1171
|
+
if (!activeSlot || !activeSlot.tabs[index]) {
|
|
1172
|
+
throw new Error(`Tab index ${index} is out of range.`);
|
|
1173
|
+
}
|
|
1174
|
+
const target = activeSlot.tabs[index];
|
|
1175
|
+
activeSlot.targetId = target.targetId;
|
|
1176
|
+
activeSlot.sessionId = target.sessionId;
|
|
1177
|
+
cdpChannel.setSessionId(target.sessionId);
|
|
1178
|
+
await cdpChannel.sendCommand("Target.activateTarget", { targetId: target.targetId }, null).catch(() => {
|
|
1179
|
+
});
|
|
1180
|
+
},
|
|
1181
|
+
catch: (e) => new DriverError({ message: `CDP switchToTab failed: ${e}` })
|
|
1182
|
+
}),
|
|
1183
|
+
closeTab: () => Effect3.tryPromise({
|
|
1184
|
+
try: async () => {
|
|
1185
|
+
if (!activeSlot) return;
|
|
1186
|
+
if (activeSlot.tabs.length <= 1) {
|
|
1187
|
+
await navigate("about:blank");
|
|
1188
|
+
return;
|
|
1189
|
+
}
|
|
1190
|
+
const idx = activeSlot.tabs.findIndex((t) => t.sessionId === activeSlot.sessionId);
|
|
1191
|
+
const closing = activeSlot.tabs[idx >= 0 ? idx : activeSlot.tabs.length - 1];
|
|
1192
|
+
activeSlot.tabs = activeSlot.tabs.filter((t) => t.sessionId !== closing.sessionId);
|
|
1193
|
+
const fallback = activeSlot.tabs[Math.max(0, Math.min(idx - 1, activeSlot.tabs.length - 1))];
|
|
1194
|
+
activeSlot.targetId = fallback.targetId;
|
|
1195
|
+
activeSlot.sessionId = fallback.sessionId;
|
|
1196
|
+
cdpChannel.setSessionId(fallback.sessionId);
|
|
1197
|
+
await cdpChannel.sendCommand("Target.closeTarget", { targetId: closing.targetId }, null).catch(() => {
|
|
1198
|
+
});
|
|
1199
|
+
},
|
|
1200
|
+
catch: (e) => new DriverError({ message: `CDP closeTab failed: ${e}` })
|
|
1201
|
+
}),
|
|
1202
|
+
getTabIds: () => Effect3.sync(() => activeSlot ? activeSlot.tabs.map((t) => t.tabId) : ["tab-1"])
|
|
745
1203
|
};
|
|
746
1204
|
return service;
|
|
747
1205
|
});
|
|
748
1206
|
}
|
|
749
1207
|
|
|
750
1208
|
// src/runtime/local.ts
|
|
751
|
-
import { Effect as
|
|
1209
|
+
import { Effect as Effect4 } from "effect";
|
|
752
1210
|
async function safeCleanup(...fns) {
|
|
753
1211
|
for (const fn of fns) {
|
|
754
1212
|
try {
|
|
@@ -804,14 +1262,37 @@ function buildEngineConfig(appId, platform, parseFn, config, screenSize) {
|
|
|
804
1262
|
}
|
|
805
1263
|
function speculativelyPrelaunchWebBrowser(config) {
|
|
806
1264
|
const webExecution = config.execution?.web;
|
|
807
|
-
if (webExecution?.engine === "
|
|
1265
|
+
if (webExecution?.engine === "lightpanda") {
|
|
808
1266
|
return void 0;
|
|
809
1267
|
}
|
|
1268
|
+
if (webExecution?.engine === "cdp") {
|
|
1269
|
+
if (webExecution.cdpUrl) return void 0;
|
|
1270
|
+
const useWarm2 = webExecution.warmBrowser ?? config.execution?.warmDaemons?.enabled ?? false;
|
|
1271
|
+
const cdpBrowserPromise = launchDirectCdpBrowser({
|
|
1272
|
+
executablePath: webExecution.executablePath,
|
|
1273
|
+
headless: webExecution.headless ?? true,
|
|
1274
|
+
warmBrowser: useWarm2,
|
|
1275
|
+
warmBrowserScope: webExecution.warmBrowserScope ? `${webExecution.warmBrowserScope}-w0` : void 0
|
|
1276
|
+
});
|
|
1277
|
+
cdpBrowserPromise.catch(() => {
|
|
1278
|
+
});
|
|
1279
|
+
return {
|
|
1280
|
+
browserPromise: Promise.resolve(void 0),
|
|
1281
|
+
ownsBrowser: false,
|
|
1282
|
+
cdpBrowserPromise
|
|
1283
|
+
};
|
|
1284
|
+
}
|
|
810
1285
|
const useWarm = (webExecution?.warmBrowser ?? config.execution?.warmDaemons?.enabled ?? false) && (webExecution?.browser ?? "chromium") === "chromium";
|
|
811
|
-
const ownsBrowser = !useWarm && !webExecution?.cdpUrl;
|
|
812
|
-
const browserPromise = webExecution?.
|
|
1286
|
+
const ownsBrowser = !useWarm && !webExecution?.cdpUrl && !webExecution?.wsEndpoint;
|
|
1287
|
+
const browserPromise = webExecution?.wsEndpoint ? connectPlaywrightOverWS(webExecution.wsEndpoint, webExecution.browser) : webExecution?.cdpUrl ? connectPlaywrightOverCDP(webExecution.cdpUrl) : useWarm ? ensureWarmBrowserDaemon({
|
|
1288
|
+
headless: webExecution?.headless ?? true,
|
|
1289
|
+
executablePath: webExecution?.executablePath,
|
|
1290
|
+
warmBrowserScope: webExecution?.warmBrowserScope
|
|
1291
|
+
}).then((r) => r.browser) : launchPlaywrightBrowser({
|
|
813
1292
|
browser: webExecution?.browser,
|
|
814
|
-
headless: webExecution?.headless ?? true
|
|
1293
|
+
headless: webExecution?.headless ?? true,
|
|
1294
|
+
executablePath: webExecution?.executablePath,
|
|
1295
|
+
channel: webExecution?.channel
|
|
815
1296
|
});
|
|
816
1297
|
browserPromise.catch(() => {
|
|
817
1298
|
});
|
|
@@ -821,37 +1302,68 @@ async function buildWebRuntime(config, prelaunched) {
|
|
|
821
1302
|
const webUrl = config.apps?.web?.url ?? "http://localhost:3000";
|
|
822
1303
|
const webExecution = config.execution?.web;
|
|
823
1304
|
const bridge = await maybeStartBridge(config.apps?.web?.bridge, config.execution?.bridge);
|
|
824
|
-
const prelaunchedBrowser = prelaunched ? await prelaunched.browserPromise : void 0;
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
1305
|
+
const prelaunchedBrowser = prelaunched && !prelaunched.cdpBrowserPromise ? await prelaunched.browserPromise : void 0;
|
|
1306
|
+
let launchedDirectCdp;
|
|
1307
|
+
let rawDriver;
|
|
1308
|
+
if (webExecution?.engine === "cdp" || webExecution?.engine === "lightpanda") {
|
|
1309
|
+
let targetCdpUrl = webExecution.cdpUrl;
|
|
1310
|
+
const useContexts = webExecution.engine === "cdp";
|
|
1311
|
+
if (!targetCdpUrl && webExecution.engine === "cdp") {
|
|
1312
|
+
launchedDirectCdp = prelaunched?.cdpBrowserPromise ? await prelaunched.cdpBrowserPromise : await launchDirectCdpBrowser({
|
|
1313
|
+
executablePath: webExecution.executablePath,
|
|
1314
|
+
headless: webExecution.headless ?? true,
|
|
1315
|
+
warmBrowser: webExecution.warmBrowser ?? config.execution?.warmDaemons?.enabled ?? false,
|
|
1316
|
+
warmBrowserScope: webExecution.warmBrowserScope ? `${webExecution.warmBrowserScope}-w0` : void 0
|
|
1317
|
+
});
|
|
1318
|
+
targetCdpUrl = launchedDirectCdp.browserWsUrl;
|
|
1319
|
+
}
|
|
1320
|
+
rawDriver = await Effect4.runPromise(
|
|
1321
|
+
makeLightweightCdpDriver({
|
|
1322
|
+
cdpUrl: targetCdpUrl ?? "http://127.0.0.1:9222",
|
|
1323
|
+
baseUrl: webUrl,
|
|
1324
|
+
engineLabel: webExecution.engine,
|
|
1325
|
+
useBrowserContexts: useContexts,
|
|
1326
|
+
freshContextPerFlow: webExecution.freshContextPerFlow,
|
|
1327
|
+
waitUntil: webExecution.waitUntil,
|
|
1328
|
+
instantAnimations: webExecution.instantAnimations,
|
|
1329
|
+
blockResources: webExecution.blockResources,
|
|
1330
|
+
virtualAuthenticator: webExecution.virtualAuthenticator,
|
|
1331
|
+
storageState: webExecution.storageState
|
|
1332
|
+
})
|
|
1333
|
+
);
|
|
1334
|
+
} else {
|
|
1335
|
+
rawDriver = await Effect4.runPromise(
|
|
1336
|
+
makePlaywrightDriver({
|
|
1337
|
+
browser: webExecution?.browser,
|
|
1338
|
+
headless: webExecution?.headless ?? true,
|
|
1339
|
+
executablePath: webExecution?.executablePath,
|
|
1340
|
+
channel: webExecution?.channel,
|
|
1341
|
+
baseUrl: webUrl,
|
|
1342
|
+
storageState: webExecution?.storageState,
|
|
1343
|
+
verboseLogging: webExecution?.verboseLogging,
|
|
1344
|
+
recordHar: Boolean(config.artifacts?.har),
|
|
1345
|
+
waitUntil: webExecution?.waitUntil,
|
|
1346
|
+
instantAnimations: webExecution?.instantAnimations,
|
|
1347
|
+
blockResources: webExecution?.blockResources,
|
|
1348
|
+
freshContextPerFlow: webExecution?.freshContextPerFlow,
|
|
1349
|
+
virtualAuthenticator: webExecution?.virtualAuthenticator,
|
|
1350
|
+
warmBrowserScope: webExecution?.warmBrowserScope,
|
|
1351
|
+
sharedBrowser: prelaunchedBrowser,
|
|
1352
|
+
cdpEndpoint: prelaunchedBrowser ? void 0 : webExecution?.cdpUrl,
|
|
1353
|
+
wsEndpoint: prelaunchedBrowser ? void 0 : webExecution?.wsEndpoint,
|
|
1354
|
+
warmBrowser: prelaunchedBrowser ? false : webExecution?.warmBrowser ?? config.execution?.warmDaemons?.enabled ?? false
|
|
1355
|
+
})
|
|
1356
|
+
);
|
|
1357
|
+
}
|
|
847
1358
|
const driver = bridge ? { ...rawDriver, domChannel: bridge } : rawDriver;
|
|
848
|
-
const deviceInfo = await
|
|
1359
|
+
const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
|
|
849
1360
|
return {
|
|
850
1361
|
runtime: {
|
|
851
1362
|
driver,
|
|
852
1363
|
cleanup: () => safeCleanup(
|
|
853
|
-
() =>
|
|
1364
|
+
() => Effect4.runPromise(driver.killApp("")),
|
|
854
1365
|
() => prelaunchedBrowser && prelaunched?.ownsBrowser ? prelaunchedBrowser.close() : Promise.resolve(),
|
|
1366
|
+
() => launchedDirectCdp ? launchedDirectCdp.close() : Promise.resolve(),
|
|
855
1367
|
() => bridge?.disconnect() ?? Promise.resolve()
|
|
856
1368
|
),
|
|
857
1369
|
metadata: {
|
|
@@ -867,37 +1379,159 @@ async function buildWebRuntime(config, prelaunched) {
|
|
|
867
1379
|
}
|
|
868
1380
|
async function buildWebRuntimePool(config, workerCount, prelaunched) {
|
|
869
1381
|
const webExecution = config.execution?.web;
|
|
870
|
-
if (workerCount <= 1 || webExecution?.engine === "
|
|
1382
|
+
if (workerCount <= 1 || webExecution?.engine === "lightpanda") {
|
|
871
1383
|
return [await buildWebRuntime(config, prelaunched)];
|
|
872
1384
|
}
|
|
873
1385
|
const webUrl = config.apps?.web?.url ?? "http://localhost:3000";
|
|
1386
|
+
const maxPerBrowser = Math.max(
|
|
1387
|
+
1,
|
|
1388
|
+
webExecution?.maxContextsPerBrowser ?? (webExecution?.engine === "cdp" ? 1 : 2)
|
|
1389
|
+
);
|
|
1390
|
+
if (webExecution?.engine === "cdp") {
|
|
1391
|
+
const useExternalCdp = Boolean(webExecution.cdpUrl);
|
|
1392
|
+
const browserCount2 = useExternalCdp ? 1 : Math.ceil(workerCount / maxPerBrowser);
|
|
1393
|
+
const handles = [];
|
|
1394
|
+
if (useExternalCdp) {
|
|
1395
|
+
handles.push({ cdpUrl: webExecution.cdpUrl, remaining: workerCount });
|
|
1396
|
+
} else {
|
|
1397
|
+
const useWarm2 = webExecution.warmBrowser ?? config.execution?.warmDaemons?.enabled ?? false;
|
|
1398
|
+
const baseScope = webExecution.warmBrowserScope ?? "pool";
|
|
1399
|
+
const launched = await Promise.all(
|
|
1400
|
+
Array.from(
|
|
1401
|
+
{ length: browserCount2 },
|
|
1402
|
+
(_v, bIdx) => bIdx === 0 && prelaunched?.cdpBrowserPromise ? prelaunched.cdpBrowserPromise : launchDirectCdpBrowser({
|
|
1403
|
+
executablePath: webExecution.executablePath,
|
|
1404
|
+
headless: webExecution.headless ?? true,
|
|
1405
|
+
warmBrowser: useWarm2,
|
|
1406
|
+
warmBrowserScope: `${baseScope}-w${bIdx}`
|
|
1407
|
+
})
|
|
1408
|
+
)
|
|
1409
|
+
);
|
|
1410
|
+
for (const h of launched) {
|
|
1411
|
+
handles.push({ cdpUrl: h.browserWsUrl, handle: h, remaining: 0 });
|
|
1412
|
+
}
|
|
1413
|
+
for (let i = 0; i < workerCount; i++) {
|
|
1414
|
+
handles[i % handles.length].remaining += 1;
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
const results2 = [];
|
|
1418
|
+
for (let i = 0; i < workerCount; i++) {
|
|
1419
|
+
const bucket = handles[i % handles.length];
|
|
1420
|
+
const driver = await Effect4.runPromise(
|
|
1421
|
+
makeLightweightCdpDriver({
|
|
1422
|
+
cdpUrl: bucket.cdpUrl,
|
|
1423
|
+
baseUrl: webUrl,
|
|
1424
|
+
engineLabel: "cdp",
|
|
1425
|
+
useBrowserContexts: true,
|
|
1426
|
+
freshContextPerFlow: webExecution.freshContextPerFlow,
|
|
1427
|
+
waitUntil: webExecution.waitUntil,
|
|
1428
|
+
instantAnimations: webExecution.instantAnimations,
|
|
1429
|
+
blockResources: webExecution.blockResources,
|
|
1430
|
+
virtualAuthenticator: webExecution.virtualAuthenticator,
|
|
1431
|
+
storageState: webExecution.storageState
|
|
1432
|
+
})
|
|
1433
|
+
);
|
|
1434
|
+
const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
|
|
1435
|
+
let cleaned = false;
|
|
1436
|
+
results2.push({
|
|
1437
|
+
runtime: {
|
|
1438
|
+
driver,
|
|
1439
|
+
cleanup: () => safeCleanup(async () => {
|
|
1440
|
+
if (cleaned) return;
|
|
1441
|
+
cleaned = true;
|
|
1442
|
+
await Effect4.runPromise(driver.killApp(""));
|
|
1443
|
+
bucket.remaining -= 1;
|
|
1444
|
+
if (bucket.remaining <= 0 && bucket.handle) {
|
|
1445
|
+
await bucket.handle.close();
|
|
1446
|
+
}
|
|
1447
|
+
}),
|
|
1448
|
+
metadata: {
|
|
1449
|
+
platform: "web",
|
|
1450
|
+
mode: "local",
|
|
1451
|
+
deviceId: `cdp-context-${i + 1}`
|
|
1452
|
+
}
|
|
1453
|
+
},
|
|
1454
|
+
engineConfig: buildEngineConfig(webUrl, "web", parseWebHierarchy, config, {
|
|
1455
|
+
width: deviceInfo.screenWidth,
|
|
1456
|
+
height: deviceInfo.screenHeight
|
|
1457
|
+
})
|
|
1458
|
+
});
|
|
1459
|
+
}
|
|
1460
|
+
return results2;
|
|
1461
|
+
}
|
|
874
1462
|
const useWarm = (webExecution?.warmBrowser ?? config.execution?.warmDaemons?.enabled ?? false) && (webExecution?.browser ?? "chromium") === "chromium";
|
|
875
|
-
const
|
|
876
|
-
const
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
1463
|
+
const singleExternalEndpoint = Boolean(webExecution?.cdpUrl || webExecution?.wsEndpoint);
|
|
1464
|
+
const browserCount = singleExternalEndpoint ? 1 : Math.ceil(workerCount / maxPerBrowser);
|
|
1465
|
+
const launchOneBrowser = async (idx) => {
|
|
1466
|
+
if (idx === 0 && prelaunched) {
|
|
1467
|
+
return {
|
|
1468
|
+
browser: await prelaunched.browserPromise,
|
|
1469
|
+
owns: prelaunched.ownsBrowser,
|
|
1470
|
+
remaining: 0
|
|
1471
|
+
};
|
|
1472
|
+
}
|
|
1473
|
+
if (webExecution?.wsEndpoint) {
|
|
1474
|
+
return {
|
|
1475
|
+
browser: await connectPlaywrightOverWS(webExecution.wsEndpoint, webExecution.browser),
|
|
1476
|
+
owns: false,
|
|
1477
|
+
remaining: 0
|
|
1478
|
+
};
|
|
1479
|
+
}
|
|
1480
|
+
if (webExecution?.cdpUrl) {
|
|
1481
|
+
return {
|
|
1482
|
+
browser: await connectPlaywrightOverCDP(webExecution.cdpUrl),
|
|
1483
|
+
owns: false,
|
|
1484
|
+
remaining: 0
|
|
1485
|
+
};
|
|
1486
|
+
}
|
|
1487
|
+
if (idx === 0 && useWarm) {
|
|
1488
|
+
const warm = await ensureWarmBrowserDaemon({
|
|
1489
|
+
headless: webExecution?.headless ?? true,
|
|
1490
|
+
executablePath: webExecution?.executablePath,
|
|
1491
|
+
warmBrowserScope: webExecution?.warmBrowserScope
|
|
1492
|
+
});
|
|
1493
|
+
return { browser: warm.browser, owns: false, remaining: 0 };
|
|
1494
|
+
}
|
|
1495
|
+
return {
|
|
1496
|
+
browser: await launchPlaywrightBrowser({
|
|
1497
|
+
browser: webExecution?.browser,
|
|
1498
|
+
headless: webExecution?.headless ?? true,
|
|
1499
|
+
executablePath: webExecution?.executablePath,
|
|
1500
|
+
channel: webExecution?.channel
|
|
1501
|
+
}),
|
|
1502
|
+
owns: true,
|
|
1503
|
+
remaining: 0
|
|
1504
|
+
};
|
|
1505
|
+
};
|
|
1506
|
+
const browserBuckets = await Promise.all(
|
|
1507
|
+
Array.from({ length: browserCount }, (_v, idx) => launchOneBrowser(idx))
|
|
1508
|
+
);
|
|
1509
|
+
for (let i = 0; i < workerCount; i++) {
|
|
1510
|
+
browserBuckets[i % browserBuckets.length].remaining += 1;
|
|
1511
|
+
}
|
|
884
1512
|
const results = [];
|
|
885
1513
|
for (let i = 0; i < workerCount; i++) {
|
|
886
|
-
const
|
|
1514
|
+
const bucket = browserBuckets[i % browserBuckets.length];
|
|
1515
|
+
const driver = await Effect4.runPromise(
|
|
887
1516
|
makePlaywrightDriver({
|
|
888
1517
|
browser: webExecution?.browser,
|
|
889
1518
|
headless: webExecution?.headless ?? true,
|
|
1519
|
+
executablePath: webExecution?.executablePath,
|
|
1520
|
+
channel: webExecution?.channel,
|
|
890
1521
|
baseUrl: webUrl,
|
|
891
1522
|
storageState: webExecution?.storageState,
|
|
892
1523
|
verboseLogging: webExecution?.verboseLogging,
|
|
893
|
-
sharedBrowser:
|
|
1524
|
+
sharedBrowser: bucket.browser,
|
|
894
1525
|
recordHar: Boolean(config.artifacts?.har),
|
|
895
1526
|
waitUntil: webExecution?.waitUntil,
|
|
896
1527
|
instantAnimations: webExecution?.instantAnimations,
|
|
897
|
-
blockResources: webExecution?.blockResources
|
|
1528
|
+
blockResources: webExecution?.blockResources,
|
|
1529
|
+
freshContextPerFlow: webExecution?.freshContextPerFlow,
|
|
1530
|
+
virtualAuthenticator: webExecution?.virtualAuthenticator,
|
|
1531
|
+
warmBrowserScope: webExecution?.warmBrowserScope
|
|
898
1532
|
})
|
|
899
1533
|
);
|
|
900
|
-
const deviceInfo = await
|
|
1534
|
+
const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
|
|
901
1535
|
let cleaned = false;
|
|
902
1536
|
results.push({
|
|
903
1537
|
runtime: {
|
|
@@ -905,10 +1539,10 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
|
|
|
905
1539
|
cleanup: () => safeCleanup(async () => {
|
|
906
1540
|
if (cleaned) return;
|
|
907
1541
|
cleaned = true;
|
|
908
|
-
await
|
|
909
|
-
remaining -= 1;
|
|
910
|
-
if (remaining <= 0 &&
|
|
911
|
-
await
|
|
1542
|
+
await Effect4.runPromise(driver.killApp(""));
|
|
1543
|
+
bucket.remaining -= 1;
|
|
1544
|
+
if (bucket.remaining <= 0 && bucket.owns) {
|
|
1545
|
+
await bucket.browser.close();
|
|
912
1546
|
}
|
|
913
1547
|
}),
|
|
914
1548
|
metadata: {
|
|
@@ -928,7 +1562,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
|
|
|
928
1562
|
async function buildElectronRuntime(config, resolveFromConfig) {
|
|
929
1563
|
const electronCfg = config.apps?.electron ?? {};
|
|
930
1564
|
const bridge = await maybeStartBridge(electronCfg.bridge, config.execution?.bridge);
|
|
931
|
-
const driver = await
|
|
1565
|
+
const driver = await Effect4.runPromise(
|
|
932
1566
|
makeElectronDriver({
|
|
933
1567
|
entry: electronCfg.entry ? resolveFromConfig(electronCfg.entry) : void 0,
|
|
934
1568
|
executablePath: electronCfg.executablePath ? resolveFromConfig(electronCfg.executablePath) : void 0,
|
|
@@ -944,12 +1578,12 @@ async function buildElectronRuntime(config, resolveFromConfig) {
|
|
|
944
1578
|
domChannel: bridge
|
|
945
1579
|
})
|
|
946
1580
|
);
|
|
947
|
-
const deviceInfo = await
|
|
1581
|
+
const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
|
|
948
1582
|
return {
|
|
949
1583
|
runtime: {
|
|
950
1584
|
driver,
|
|
951
1585
|
cleanup: () => safeCleanup(
|
|
952
|
-
() =>
|
|
1586
|
+
() => Effect4.runPromise(driver.killApp("")),
|
|
953
1587
|
() => bridge?.disconnect() ?? Promise.resolve()
|
|
954
1588
|
),
|
|
955
1589
|
metadata: {
|
|
@@ -973,7 +1607,7 @@ async function buildElectronRuntime(config, resolveFromConfig) {
|
|
|
973
1607
|
async function buildElectrobunRuntime(config, resolveFromConfig) {
|
|
974
1608
|
const electrobunCfg = config.apps?.electrobun ?? {};
|
|
975
1609
|
const bridge = await maybeStartBridge(electrobunCfg.bridge, config.execution?.bridge);
|
|
976
|
-
const driver = await
|
|
1610
|
+
const driver = await Effect4.runPromise(
|
|
977
1611
|
makeElectrobunDriver({
|
|
978
1612
|
executablePath: electrobunCfg.executablePath ? resolveFromConfig(electrobunCfg.executablePath) : void 0,
|
|
979
1613
|
appDir: electrobunCfg.appDir ? resolveFromConfig(electrobunCfg.appDir) : void 0,
|
|
@@ -991,12 +1625,12 @@ async function buildElectrobunRuntime(config, resolveFromConfig) {
|
|
|
991
1625
|
domChannel: bridge
|
|
992
1626
|
})
|
|
993
1627
|
);
|
|
994
|
-
const deviceInfo = await
|
|
1628
|
+
const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
|
|
995
1629
|
return {
|
|
996
1630
|
runtime: {
|
|
997
1631
|
driver,
|
|
998
1632
|
cleanup: () => safeCleanup(
|
|
999
|
-
() =>
|
|
1633
|
+
() => Effect4.runPromise(driver.killApp("")),
|
|
1000
1634
|
() => bridge?.disconnect() ?? Promise.resolve()
|
|
1001
1635
|
),
|
|
1002
1636
|
metadata: {
|
|
@@ -1058,18 +1692,18 @@ async function buildLocalAndroidRuntime(config, targetDevice, resolveFromConfig)
|
|
|
1058
1692
|
warm: warmDaemons?.enabled,
|
|
1059
1693
|
daemonStateFile: warmDaemons?.stateFile
|
|
1060
1694
|
});
|
|
1061
|
-
const driver = await
|
|
1695
|
+
const driver = await Effect4.runPromise(
|
|
1062
1696
|
createUiAutomator2Driver(conn.host, conn.port, device.serial, packageName, {
|
|
1063
1697
|
domChannel: bridge,
|
|
1064
1698
|
cdpPort: config.apps?.android?.cdpPort
|
|
1065
1699
|
})
|
|
1066
1700
|
);
|
|
1067
|
-
const deviceInfo = await
|
|
1701
|
+
const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
|
|
1068
1702
|
return {
|
|
1069
1703
|
runtime: {
|
|
1070
1704
|
driver,
|
|
1071
1705
|
cleanup: () => safeCleanup(
|
|
1072
|
-
() =>
|
|
1706
|
+
() => Effect4.runPromise(driver.killApp("")),
|
|
1073
1707
|
() => bridge?.disconnect() ?? Promise.resolve(),
|
|
1074
1708
|
() => {
|
|
1075
1709
|
if (reversedBridgePort !== null) {
|
|
@@ -1106,7 +1740,7 @@ async function buildLocalIOSRuntime(config, targetDevice, resolveFromConfig) {
|
|
|
1106
1740
|
const bridge = await maybeStartBridge(config.apps?.ios?.bridge, config.execution?.bridge);
|
|
1107
1741
|
const createIOSRuntime = async (deviceId, conn, simulatorUdid) => {
|
|
1108
1742
|
const reuseSession = warmDaemons?.enabled && warmDaemons.reuseSession !== false;
|
|
1109
|
-
const driver = await
|
|
1743
|
+
const driver = await Effect4.runPromise(
|
|
1110
1744
|
createWDADriver(conn.host, conn.port, bundleId, simulatorUdid, snapshotMaxDepth, {
|
|
1111
1745
|
domChannel: bridge,
|
|
1112
1746
|
webkitInspectorUrl: config.apps?.ios?.webkitInspectorUrl,
|
|
@@ -1116,12 +1750,12 @@ async function buildLocalIOSRuntime(config, targetDevice, resolveFromConfig) {
|
|
|
1116
1750
|
onSessionCreated: reuseSession ? (sessionId) => updateWarmDaemonSession("wda", deviceId, sessionId, bundleId, warmDaemons?.stateFile) : void 0
|
|
1117
1751
|
})
|
|
1118
1752
|
);
|
|
1119
|
-
const deviceInfo = await
|
|
1753
|
+
const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
|
|
1120
1754
|
return {
|
|
1121
1755
|
runtime: {
|
|
1122
1756
|
driver,
|
|
1123
1757
|
cleanup: () => safeCleanup(
|
|
1124
|
-
() =>
|
|
1758
|
+
() => Effect4.runPromise(driver.killApp("")),
|
|
1125
1759
|
() => bridge?.disconnect() ?? Promise.resolve(),
|
|
1126
1760
|
() => conn.cleanup?.() ?? Promise.resolve()
|
|
1127
1761
|
),
|
|
@@ -1253,12 +1887,12 @@ async function buildLocalIOSRuntime(config, targetDevice, resolveFromConfig) {
|
|
|
1253
1887
|
}
|
|
1254
1888
|
|
|
1255
1889
|
// src/core/engine.ts
|
|
1256
|
-
import { Effect as
|
|
1890
|
+
import { Effect as Effect7 } from "effect";
|
|
1257
1891
|
|
|
1258
1892
|
// src/core/artifacts.ts
|
|
1259
1893
|
import { writeFileSync, mkdirSync } from "fs";
|
|
1260
|
-
import { join } from "path";
|
|
1261
|
-
import { Effect as
|
|
1894
|
+
import { join as join2 } from "path";
|
|
1895
|
+
import { Effect as Effect5 } from "effect";
|
|
1262
1896
|
var DEFAULT_ARTIFACT_CONFIG = {
|
|
1263
1897
|
outputDir: "./spana-output",
|
|
1264
1898
|
captureOnFailure: true,
|
|
@@ -1274,7 +1908,7 @@ function safeName(value) {
|
|
|
1274
1908
|
return value.replaceAll(/[^a-zA-Z0-9-_]/g, "_").replaceAll(/_+/g, "_").replaceAll(/^_+|_+$/g, "").slice(0, 80) || "artifact";
|
|
1275
1909
|
}
|
|
1276
1910
|
function flowArtifactDir(config, flowName, platform) {
|
|
1277
|
-
const dir =
|
|
1911
|
+
const dir = join2(config.outputDir, `${safeName(flowName)}-${platform}`);
|
|
1278
1912
|
mkdirSync(dir, { recursive: true });
|
|
1279
1913
|
return dir;
|
|
1280
1914
|
}
|
|
@@ -1282,12 +1916,12 @@ function createAttachment(name, contentType, path) {
|
|
|
1282
1916
|
return { name, contentType, path };
|
|
1283
1917
|
}
|
|
1284
1918
|
function writeJsonAttachment(dir, fileName, attachmentName, value) {
|
|
1285
|
-
const path =
|
|
1919
|
+
const path = join2(dir, fileName);
|
|
1286
1920
|
writeFileSync(path, JSON.stringify(value, null, 2), "utf-8");
|
|
1287
1921
|
return createAttachment(attachmentName, "application/json", path);
|
|
1288
1922
|
}
|
|
1289
1923
|
function writeTextAttachment(dir, fileName, attachmentName, value) {
|
|
1290
|
-
const path =
|
|
1924
|
+
const path = join2(dir, fileName);
|
|
1291
1925
|
writeFileSync(path, value, "utf-8");
|
|
1292
1926
|
return createAttachment(attachmentName, "text/plain", path);
|
|
1293
1927
|
}
|
|
@@ -1307,8 +1941,8 @@ async function captureArtifacts(driver, config, flowName, platform, status) {
|
|
|
1307
1941
|
const dir = flowArtifactDir(config, flowName, platform);
|
|
1308
1942
|
if (config.screenshot) {
|
|
1309
1943
|
try {
|
|
1310
|
-
const screenshot = await
|
|
1311
|
-
const path =
|
|
1944
|
+
const screenshot = await Effect5.runPromise(Effect5.orDie(driver.takeScreenshot()));
|
|
1945
|
+
const path = join2(dir, "screenshot.png");
|
|
1312
1946
|
writeFileSync(path, screenshot);
|
|
1313
1947
|
attachments.push(createAttachment(`${status}-screenshot`, "image/png", path));
|
|
1314
1948
|
} catch {
|
|
@@ -1316,8 +1950,8 @@ async function captureArtifacts(driver, config, flowName, platform, status) {
|
|
|
1316
1950
|
}
|
|
1317
1951
|
if (config.uiHierarchy) {
|
|
1318
1952
|
try {
|
|
1319
|
-
const hierarchy = await
|
|
1320
|
-
const path =
|
|
1953
|
+
const hierarchy = await Effect5.runPromise(Effect5.orDie(driver.dumpHierarchy()));
|
|
1954
|
+
const path = join2(dir, "hierarchy.json");
|
|
1321
1955
|
writeFileSync(path, hierarchy, "utf-8");
|
|
1322
1956
|
attachments.push(createAttachment(`${status}-hierarchy`, "application/json", path));
|
|
1323
1957
|
} catch {
|
|
@@ -1325,7 +1959,7 @@ async function captureArtifacts(driver, config, flowName, platform, status) {
|
|
|
1325
1959
|
}
|
|
1326
1960
|
if (config.consoleLogs && driver.getConsoleLogs) {
|
|
1327
1961
|
try {
|
|
1328
|
-
const consoleLogs = await
|
|
1962
|
+
const consoleLogs = await Effect5.runPromise(Effect5.orDie(driver.getConsoleLogs()));
|
|
1329
1963
|
if (consoleLogs.length > 0) {
|
|
1330
1964
|
attachments.push(
|
|
1331
1965
|
writeJsonAttachment(dir, "console-logs.json", `${status}-console-logs`, consoleLogs)
|
|
@@ -1336,7 +1970,7 @@ async function captureArtifacts(driver, config, flowName, platform, status) {
|
|
|
1336
1970
|
}
|
|
1337
1971
|
if (config.jsErrors && driver.getJSErrors) {
|
|
1338
1972
|
try {
|
|
1339
|
-
const jsErrors = await
|
|
1973
|
+
const jsErrors = await Effect5.runPromise(Effect5.orDie(driver.getJSErrors()));
|
|
1340
1974
|
if (jsErrors.length > 0) {
|
|
1341
1975
|
attachments.push(
|
|
1342
1976
|
writeJsonAttachment(dir, "js-errors.json", `${status}-js-errors`, jsErrors)
|
|
@@ -1347,7 +1981,7 @@ async function captureArtifacts(driver, config, flowName, platform, status) {
|
|
|
1347
1981
|
}
|
|
1348
1982
|
if (config.har && driver.getHAR) {
|
|
1349
1983
|
try {
|
|
1350
|
-
const har = await
|
|
1984
|
+
const har = await Effect5.runPromise(Effect5.orDie(driver.getHAR()));
|
|
1351
1985
|
if (har.log.entries.length > 0) {
|
|
1352
1986
|
attachments.push(writeJsonAttachment(dir, "network.har", `${status}-network-har`, har));
|
|
1353
1987
|
}
|
|
@@ -1356,7 +1990,7 @@ async function captureArtifacts(driver, config, flowName, platform, status) {
|
|
|
1356
1990
|
}
|
|
1357
1991
|
if (status === "failed" && driver.getDriverLogs) {
|
|
1358
1992
|
try {
|
|
1359
|
-
const driverLogs = await
|
|
1993
|
+
const driverLogs = await Effect5.runPromise(Effect5.orDie(driver.getDriverLogs()));
|
|
1360
1994
|
if (driverLogs.length > 0) {
|
|
1361
1995
|
attachments.push(
|
|
1362
1996
|
writeTextAttachment(
|
|
@@ -1375,11 +2009,11 @@ async function captureArtifacts(driver, config, flowName, platform, status) {
|
|
|
1375
2009
|
async function captureStepScreenshot(driver, config, flowName, platform, stepIndex, stepName, screenshot) {
|
|
1376
2010
|
if (!config.screenshot) return void 0;
|
|
1377
2011
|
try {
|
|
1378
|
-
const dir =
|
|
2012
|
+
const dir = join2(flowArtifactDir(config, flowName, platform), "steps");
|
|
1379
2013
|
mkdirSync(dir, { recursive: true });
|
|
1380
2014
|
const fileName = `${String(stepIndex).padStart(3, "0")}-${safeName(stepName)}.png`;
|
|
1381
|
-
const path =
|
|
1382
|
-
const bytes = screenshot ?? await
|
|
2015
|
+
const path = join2(dir, fileName);
|
|
2016
|
+
const bytes = screenshot ?? await Effect5.runPromise(Effect5.orDie(driver.takeScreenshot()));
|
|
1383
2017
|
writeFileSync(path, bytes);
|
|
1384
2018
|
return createAttachment(stepName, "image/png", path);
|
|
1385
2019
|
} catch {
|
|
@@ -1389,7 +2023,7 @@ async function captureStepScreenshot(driver, config, flowName, platform, stepInd
|
|
|
1389
2023
|
|
|
1390
2024
|
// src/core/debug-repl.ts
|
|
1391
2025
|
import * as repl from "repl";
|
|
1392
|
-
import { Effect as
|
|
2026
|
+
import { Effect as Effect6 } from "effect";
|
|
1393
2027
|
var didStartDebugRepl = false;
|
|
1394
2028
|
function toSuggestedSelectors(root) {
|
|
1395
2029
|
return flattenElements(root).filter((el) => el.visible !== false && (el.id || el.text || el.accessibilityLabel)).map((el) => ({
|
|
@@ -1410,7 +2044,7 @@ async function runDebugReplOnce(context) {
|
|
|
1410
2044
|
console.log("Skipping debug REPL because stdin/stdout is not interactive.");
|
|
1411
2045
|
return false;
|
|
1412
2046
|
}
|
|
1413
|
-
const hierarchy = async () => context.parseHierarchy(await
|
|
2047
|
+
const hierarchy = async () => context.parseHierarchy(await Effect6.runPromise(context.driver.dumpHierarchy()));
|
|
1414
2048
|
const selectors = async () => toSuggestedSelectors(await hierarchy());
|
|
1415
2049
|
console.log("");
|
|
1416
2050
|
console.log(`Entering debug REPL for failed flow "${context.flowName}" on ${context.platform}.`);
|
|
@@ -1804,11 +2438,11 @@ function classifyError(error) {
|
|
|
1804
2438
|
}
|
|
1805
2439
|
|
|
1806
2440
|
// src/core/engine.ts
|
|
1807
|
-
import { join as
|
|
2441
|
+
import { join as join4 } from "path";
|
|
1808
2442
|
|
|
1809
2443
|
// src/report/failure-bundle.ts
|
|
1810
|
-
import { writeFileSync as writeFileSync2, readFileSync, existsSync } from "fs";
|
|
1811
|
-
import { join as
|
|
2444
|
+
import { writeFileSync as writeFileSync2, readFileSync, existsSync as existsSync2 } from "fs";
|
|
2445
|
+
import { join as join3, basename } from "path";
|
|
1812
2446
|
function levenshtein(a, b) {
|
|
1813
2447
|
const m = a.length;
|
|
1814
2448
|
const n = b.length;
|
|
@@ -1915,9 +2549,9 @@ function createFailureBundle(flowName, platform, steps, error, artifactDir, atta
|
|
|
1915
2549
|
} : null;
|
|
1916
2550
|
let selectorContext;
|
|
1917
2551
|
if (failedStep?.selector && (error.category === "element-not-found" || error.category === "element-not-visible")) {
|
|
1918
|
-
const hierarchyPath =
|
|
2552
|
+
const hierarchyPath = join3(artifactDir, "hierarchy.json");
|
|
1919
2553
|
let hierarchyJson = null;
|
|
1920
|
-
if (
|
|
2554
|
+
if (existsSync2(hierarchyPath)) {
|
|
1921
2555
|
try {
|
|
1922
2556
|
hierarchyJson = readFileSync(hierarchyPath, "utf-8");
|
|
1923
2557
|
} catch {
|
|
@@ -1932,15 +2566,15 @@ function createFailureBundle(flowName, platform, steps, error, artifactDir, atta
|
|
|
1932
2566
|
const flowFile = flowPath ?? `flows/${flowName.replaceAll(" ", "-")}.flow.ts`;
|
|
1933
2567
|
const reproCommand = `spana test ${flowFile} --platform ${platform} --grep '${flowName}'`;
|
|
1934
2568
|
let runtimeDiagnostics;
|
|
1935
|
-
const consolePath =
|
|
1936
|
-
const jsErrPath =
|
|
1937
|
-
if (
|
|
2569
|
+
const consolePath = join3(artifactDir, "console-logs.json");
|
|
2570
|
+
const jsErrPath = join3(artifactDir, "js-errors.json");
|
|
2571
|
+
if (existsSync2(consolePath) || existsSync2(jsErrPath)) {
|
|
1938
2572
|
let consoleErrorCount = 0;
|
|
1939
2573
|
let consoleWarnCount = 0;
|
|
1940
2574
|
const recentConsoleErrors = [];
|
|
1941
2575
|
let jsErrorCount = 0;
|
|
1942
2576
|
const recentJsErrors = [];
|
|
1943
|
-
if (
|
|
2577
|
+
if (existsSync2(consolePath)) {
|
|
1944
2578
|
try {
|
|
1945
2579
|
const logs = JSON.parse(readFileSync(consolePath, "utf-8"));
|
|
1946
2580
|
if (Array.isArray(logs)) {
|
|
@@ -1958,7 +2592,7 @@ function createFailureBundle(flowName, platform, steps, error, artifactDir, atta
|
|
|
1958
2592
|
} catch {
|
|
1959
2593
|
}
|
|
1960
2594
|
}
|
|
1961
|
-
if (
|
|
2595
|
+
if (existsSync2(jsErrPath)) {
|
|
1962
2596
|
try {
|
|
1963
2597
|
const errs = JSON.parse(readFileSync(jsErrPath, "utf-8"));
|
|
1964
2598
|
if (Array.isArray(errs)) {
|
|
@@ -2003,7 +2637,7 @@ function createFailureBundle(flowName, platform, steps, error, artifactDir, atta
|
|
|
2003
2637
|
return bundle;
|
|
2004
2638
|
}
|
|
2005
2639
|
function writeFailureBundle(bundle, artifactDir) {
|
|
2006
|
-
const path =
|
|
2640
|
+
const path = join3(artifactDir, "failure-bundle.json");
|
|
2007
2641
|
writeFileSync2(path, JSON.stringify(bundle, null, 2), "utf-8");
|
|
2008
2642
|
return path;
|
|
2009
2643
|
}
|
|
@@ -2054,7 +2688,7 @@ async function executeFlow(flow, driver, config) {
|
|
|
2054
2688
|
const sessions = createSessions(
|
|
2055
2689
|
sessionManager,
|
|
2056
2690
|
async (opts) => {
|
|
2057
|
-
const pwDriver = await
|
|
2691
|
+
const pwDriver = await Effect7.runPromise(
|
|
2058
2692
|
makePlaywrightDriver({
|
|
2059
2693
|
browser: opts.browser,
|
|
2060
2694
|
headless: opts.headless ?? true,
|
|
@@ -2090,7 +2724,7 @@ async function executeFlow(flow, driver, config) {
|
|
|
2090
2724
|
};
|
|
2091
2725
|
if (driver.beginFlow) {
|
|
2092
2726
|
try {
|
|
2093
|
-
await
|
|
2727
|
+
await Effect7.runPromise(driver.beginFlow(flow.name));
|
|
2094
2728
|
} catch (error) {
|
|
2095
2729
|
return buildFailureResult(error);
|
|
2096
2730
|
}
|
|
@@ -2153,7 +2787,7 @@ async function executeFlow(flow, driver, config) {
|
|
|
2153
2787
|
};
|
|
2154
2788
|
if (artifactConfig.captureOnFailure && result.error) {
|
|
2155
2789
|
try {
|
|
2156
|
-
const artDir =
|
|
2790
|
+
const artDir = join4(
|
|
2157
2791
|
artifactConfig.outputDir,
|
|
2158
2792
|
`${flow.name.replaceAll(/[^a-zA-Z0-9-_]/g, "_").replaceAll(/_+/g, "_").slice(0, 80) || "artifact"}-${platform}`
|
|
2159
2793
|
);
|
|
@@ -2284,6 +2918,7 @@ async function runParallel(config) {
|
|
|
2284
2918
|
}
|
|
2285
2919
|
|
|
2286
2920
|
export {
|
|
2921
|
+
launchDirectCdpBrowser,
|
|
2287
2922
|
makeLightweightCdpDriver,
|
|
2288
2923
|
speculativelyPrelaunchWebBrowser,
|
|
2289
2924
|
buildWebRuntime,
|
|
@@ -2297,4 +2932,4 @@ export {
|
|
|
2297
2932
|
orderFlowsLongestFirst,
|
|
2298
2933
|
runParallel
|
|
2299
2934
|
};
|
|
2300
|
-
//# sourceMappingURL=chunk-
|
|
2935
|
+
//# sourceMappingURL=chunk-KEUZLBQS.js.map
|