spana-test 0.10.0 → 0.12.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 +0 -0
- package/LICENSE +0 -0
- package/README.md +4 -1
- package/dist/{accessibility-audit-YZOPUY3D.js → accessibility-audit-MHQ65DUD.js} +61 -12
- package/dist/accessibility-audit-MHQ65DUD.js.map +1 -0
- package/dist/agent/index.d.ts +3 -11
- package/dist/agent/index.d.ts.map +1 -0
- package/dist/agent/index.js +20 -12
- package/dist/agent/index.js.map +1 -1
- package/dist/{session-Bt_mbUWg.d.ts → agent/session.d.ts} +14 -42
- package/dist/agent/session.d.ts.map +1 -0
- package/dist/agent-fixture-H6GOUHNX.js +20 -0
- package/dist/{android-6BOQTMM3.js.map → agent-fixture-H6GOUHNX.js.map} +0 -0
- package/dist/{allure-FGVR5LND.js → allure-XOM7BXL5.js} +5 -2
- package/dist/{allure-FGVR5LND.js.map → allure-XOM7BXL5.js.map} +1 -1
- package/dist/{android-6BOQTMM3.js → android-C2S4B4TH.js} +3 -3
- package/dist/{chunk-DGUM43GV.js.map → android-C2S4B4TH.js.map} +0 -0
- package/dist/api/agent-fixture.d.ts +119 -0
- package/dist/api/agent-fixture.d.ts.map +1 -0
- package/dist/api/app.d.ts +359 -0
- package/dist/api/app.d.ts.map +1 -0
- package/dist/api/expect.d.ts +167 -0
- package/dist/api/expect.d.ts.map +1 -0
- package/dist/api/fixtures.d.ts +165 -0
- package/dist/api/fixtures.d.ts.map +1 -0
- package/dist/api/flow.d.ts +123 -0
- package/dist/api/flow.d.ts.map +1 -0
- package/dist/api/index.d.ts +4 -0
- package/dist/api/index.d.ts.map +1 -0
- package/dist/api/snapshots.d.ts +26 -0
- package/dist/api/snapshots.d.ts.map +1 -0
- package/dist/api/storybook.d.ts +18 -0
- package/dist/api/storybook.d.ts.map +1 -0
- package/dist/api/suite.d.ts +46 -0
- package/dist/api/suite.d.ts.map +1 -0
- package/dist/app-CBHH5GMB.js +10 -0
- package/dist/{config-loader-WLPQ5WVH.js.map → app-CBHH5GMB.js.map} +0 -0
- package/dist/{appium-server-66GVUL24.js → appium-server-M6CWWUWF.js} +5 -2
- package/dist/{appium-server-66GVUL24.js.map → appium-server-M6CWWUWF.js.map} +1 -1
- package/dist/{baseline-manager-5TIUCNP5.js → baseline-manager-LVUVH2MJ.js} +5 -2
- package/dist/{baseline-manager-5TIUCNP5.js.map → baseline-manager-LVUVH2MJ.js.map} +1 -1
- package/dist/cache-command-OL7HUK2K.js +12 -0
- package/dist/{daemon-manager-2EQDVUVM.js.map → cache-command-OL7HUK2K.js.map} +0 -0
- package/dist/channels/android-cdp.d.ts +71 -0
- package/dist/channels/android-cdp.d.ts.map +1 -0
- package/dist/channels/apple-webinspector.d.ts +85 -0
- package/dist/channels/apple-webinspector.d.ts.map +1 -0
- package/dist/channels/bidi-client.d.ts +79 -0
- package/dist/channels/bidi-client.d.ts.map +1 -0
- package/dist/channels/bridge-server.d.ts +69 -0
- package/dist/channels/bridge-server.d.ts.map +1 -0
- package/dist/channels/cdp-client.d.ts +102 -0
- package/dist/channels/cdp-client.d.ts.map +1 -0
- package/dist/channels/dom-channel.d.ts +246 -0
- package/dist/channels/dom-channel.d.ts.map +1 -0
- package/dist/channels/index.d.ts +8 -0
- package/dist/channels/index.d.ts.map +1 -0
- package/dist/channels/webkit-inspector.d.ts +85 -0
- package/dist/channels/webkit-inspector.d.ts.map +1 -0
- package/dist/channels/ws-server.d.ts +21 -0
- package/dist/channels/ws-server.d.ts.map +1 -0
- package/dist/{chunk-WV3ALL3H.js → chunk-2MA5G2VH.js} +6 -2
- package/dist/{chunk-WV3ALL3H.js.map → chunk-2MA5G2VH.js.map} +1 -1
- package/dist/{chunk-6GBAPW6K.js → chunk-53TGNQTM.js} +22 -14
- package/dist/{chunk-6GBAPW6K.js.map → chunk-53TGNQTM.js.map} +1 -1
- package/dist/{chunk-JPZCZHL4.js → chunk-7Q7TSUNL.js} +6 -1
- package/dist/{chunk-JPZCZHL4.js.map → chunk-7Q7TSUNL.js.map} +1 -1
- package/dist/{chunk-X2TJP7LB.js → chunk-7WHQIQPM.js} +11 -1
- package/dist/chunk-7WHQIQPM.js.map +1 -0
- package/dist/{chunk-IXON7DMB.js → chunk-AMBU26PB.js} +9 -3
- package/dist/{chunk-IXON7DMB.js.map → chunk-AMBU26PB.js.map} +1 -1
- package/dist/{chunk-66D3C7NB.js → chunk-BWEQ4XT2.js} +1707 -2159
- package/dist/chunk-BWEQ4XT2.js.map +1 -0
- package/dist/{chunk-Y6KMJJ2T.js → chunk-F2YUBD4E.js} +364 -3
- package/dist/chunk-F2YUBD4E.js.map +1 -0
- package/dist/chunk-F3AFZ6UX.js +326 -0
- package/dist/chunk-F3AFZ6UX.js.map +1 -0
- package/dist/{chunk-Z6K4QQAR.js → chunk-FHCOPLYB.js} +36 -7
- package/dist/chunk-FHCOPLYB.js.map +1 -0
- package/dist/{chunk-3SH5JQF7.js → chunk-FSPMFRJO.js} +6 -1
- package/dist/{chunk-3SH5JQF7.js.map → chunk-FSPMFRJO.js.map} +1 -1
- package/dist/chunk-FTXUQMGH.js +56 -0
- package/dist/chunk-FTXUQMGH.js.map +1 -0
- package/dist/chunk-GAWJL6Q3.js +2268 -0
- package/dist/chunk-GAWJL6Q3.js.map +1 -0
- package/dist/{chunk-B473XZOM.js → chunk-GDDCZ2PL.js} +183 -2004
- package/dist/chunk-GDDCZ2PL.js.map +1 -0
- package/dist/chunk-HIGFQRWM.js +562 -0
- package/dist/chunk-HIGFQRWM.js.map +1 -0
- package/dist/chunk-LQQNE2OE.js +4358 -0
- package/dist/chunk-LQQNE2OE.js.map +1 -0
- package/dist/{chunk-KJPHH2TW.js → chunk-NHT3XSX3.js} +6 -1
- package/dist/{chunk-KJPHH2TW.js.map → chunk-NHT3XSX3.js.map} +1 -1
- package/dist/{chunk-3FSZNKEF.js → chunk-NXET4BFJ.js} +7 -1
- package/dist/{chunk-3FSZNKEF.js.map → chunk-NXET4BFJ.js.map} +1 -1
- package/dist/chunk-OQRGR542.js +3061 -0
- package/dist/chunk-OQRGR542.js.map +1 -0
- package/dist/{chunk-B35G77DN.js → chunk-PPAPRKQU.js} +734 -3493
- package/dist/chunk-PPAPRKQU.js.map +1 -0
- package/dist/{chunk-DP7MGXHN.js → chunk-PRQTAIYA.js} +56 -6
- package/dist/chunk-PRQTAIYA.js.map +1 -0
- package/dist/{chunk-SF7UYW4I.js → chunk-QOL44BNJ.js} +8 -4
- package/dist/{chunk-SF7UYW4I.js.map → chunk-QOL44BNJ.js.map} +1 -1
- package/dist/{chunk-CY3DKTBZ.js → chunk-RIXZISMX.js} +6 -1
- package/dist/{chunk-CY3DKTBZ.js.map → chunk-RIXZISMX.js.map} +1 -1
- package/dist/chunk-TFEXYI6N.js +77 -0
- package/dist/chunk-TFEXYI6N.js.map +1 -0
- package/dist/chunk-U56N5JCJ.js +19842 -0
- package/dist/chunk-U56N5JCJ.js.map +1 -0
- package/dist/{chunk-IHVZKQQW.js → chunk-UKUXNFQP.js} +6 -1
- package/dist/{chunk-IHVZKQQW.js.map → chunk-UKUXNFQP.js.map} +1 -1
- package/dist/{chunk-54ASKII6.js → chunk-VOYJQDSI.js} +6 -1
- package/dist/{chunk-54ASKII6.js.map → chunk-VOYJQDSI.js.map} +1 -1
- package/dist/{chunk-C2HBFEMQ.js → chunk-WJH5K42V.js} +6 -2
- package/dist/{chunk-C2HBFEMQ.js.map → chunk-WJH5K42V.js.map} +1 -1
- package/dist/{chunk-VP6V4XEJ.js → chunk-XD6A3VXB.js} +10 -5
- package/dist/{chunk-VP6V4XEJ.js.map → chunk-XD6A3VXB.js.map} +1 -1
- package/dist/chunk-XQRXQBDQ.js +133 -0
- package/dist/chunk-XQRXQBDQ.js.map +1 -0
- package/dist/{chunk-2AFWVHQK.js → chunk-XVL4FHXA.js} +6 -1
- package/dist/{chunk-2AFWVHQK.js.map → chunk-XVL4FHXA.js.map} +1 -1
- package/dist/{chunk-LAMTF4LX.js → chunk-ZIETAMAD.js} +6 -1
- package/dist/{chunk-LAMTF4LX.js.map → chunk-ZIETAMAD.js.map} +1 -1
- package/dist/cli/cache-command.d.ts +29 -0
- package/dist/cli/cache-command.d.ts.map +1 -0
- package/dist/cli/command-errors.d.ts +7 -0
- package/dist/cli/command-errors.d.ts.map +1 -0
- package/dist/cli/config-loader.d.ts +11 -0
- package/dist/cli/config-loader.d.ts.map +1 -0
- package/dist/cli/doctor-command.d.ts +64 -0
- package/dist/cli/doctor-command.d.ts.map +1 -0
- package/dist/cli/gen-types-command.d.ts +2 -0
- package/dist/cli/gen-types-command.d.ts.map +1 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.d.ts.map +1 -0
- package/dist/cli/init-command.d.ts +7 -0
- package/dist/cli/init-command.d.ts.map +1 -0
- package/dist/cli/init-flow-command.d.ts +11 -0
- package/dist/cli/init-flow-command.d.ts.map +1 -0
- package/dist/cli/iteration.d.ts +44 -0
- package/dist/cli/iteration.d.ts.map +1 -0
- package/dist/cli/scaffolds.d.ts +13 -0
- package/dist/cli/scaffolds.d.ts.map +1 -0
- package/dist/cli/studio-command.d.ts +8 -0
- package/dist/cli/studio-command.d.ts.map +1 -0
- package/dist/cli/test-command.d.ts +61 -0
- package/dist/cli/test-command.d.ts.map +1 -0
- package/dist/cli/watch-mode.d.ts +9 -0
- package/dist/cli/watch-mode.d.ts.map +1 -0
- package/dist/cli.js +255 -26
- package/dist/cli.js.map +1 -1
- package/dist/cloud/browserstack.d.ts +9 -0
- package/dist/cloud/browserstack.d.ts.map +1 -0
- package/dist/cloud/common.d.ts +26 -0
- package/dist/cloud/common.d.ts.map +1 -0
- package/dist/cloud/provider.d.ts +21 -0
- package/dist/cloud/provider.d.ts.map +1 -0
- package/dist/cloud/saucelabs.d.ts +9 -0
- package/dist/cloud/saucelabs.d.ts.map +1 -0
- package/dist/{compiler-X6WTFMYF.js → compiler-44UW2FID.js} +7 -3
- package/dist/{compiler-X6WTFMYF.js.map → compiler-44UW2FID.js.map} +1 -1
- package/dist/config-loader-V26XXHPH.js +10 -0
- package/dist/{discover-RLSKEBAX.js.map → config-loader-V26XXHPH.js.map} +0 -0
- package/dist/{console-DIYEJSSP.js → console-T6TVZ65G.js} +8 -2
- package/dist/console-T6TVZ65G.js.map +1 -0
- package/dist/core/accessibility-audit.d.ts +29 -0
- package/dist/core/accessibility-audit.d.ts.map +1 -0
- package/dist/core/artifacts.d.ts +27 -0
- package/dist/core/artifacts.d.ts.map +1 -0
- package/dist/core/baseline-manager.d.ts +18 -0
- package/dist/core/baseline-manager.d.ts.map +1 -0
- package/dist/core/benchmark.d.ts +21 -0
- package/dist/core/benchmark.d.ts.map +1 -0
- package/dist/core/debug-repl.d.ts +17 -0
- package/dist/core/debug-repl.d.ts.map +1 -0
- package/dist/core/engine.d.ts +51 -0
- package/dist/core/engine.d.ts.map +1 -0
- package/dist/core/filters.d.ts +248 -0
- package/dist/core/filters.d.ts.map +1 -0
- package/dist/core/flow-generator.d.ts +13 -0
- package/dist/core/flow-generator.d.ts.map +1 -0
- package/dist/core/graphemes.d.ts +2 -0
- package/dist/core/graphemes.d.ts.map +1 -0
- package/dist/core/index.d.ts +6 -0
- package/dist/core/index.d.ts.map +1 -0
- package/dist/core/native-accel.d.ts +21 -0
- package/dist/core/native-accel.d.ts.map +1 -0
- package/dist/core/network-cache.d.ts +68 -0
- package/dist/core/network-cache.d.ts.map +1 -0
- package/dist/core/orchestrator.d.ts +44 -0
- package/dist/core/orchestrator.d.ts.map +1 -0
- package/dist/core/parallel.d.ts +42 -0
- package/dist/core/parallel.d.ts.map +1 -0
- package/dist/core/port-allocator.d.ts +16 -0
- package/dist/core/port-allocator.d.ts.map +1 -0
- package/dist/core/projects.d.ts +60 -0
- package/dist/core/projects.d.ts.map +1 -0
- package/dist/core/replay-cache.d.ts +127 -0
- package/dist/core/replay-cache.d.ts.map +1 -0
- package/dist/core/runner.d.ts +50 -0
- package/dist/core/runner.d.ts.map +1 -0
- package/dist/core/screenshot-compare.d.ts +50 -0
- package/dist/core/screenshot-compare.d.ts.map +1 -0
- package/dist/core/session-manager.d.ts +35 -0
- package/dist/core/session-manager.d.ts.map +1 -0
- package/dist/core/step-recorder.d.ts +20 -0
- package/dist/core/step-recorder.d.ts.map +1 -0
- package/dist/core/target-matrix.d.ts +29 -0
- package/dist/core/target-matrix.d.ts.map +1 -0
- package/dist/core/trace-viewer.d.ts +91 -0
- package/dist/core/trace-viewer.d.ts.map +1 -0
- package/dist/core/validator.d.ts +18 -0
- package/dist/core/validator.d.ts.map +1 -0
- package/dist/core/video-recorder.d.ts +120 -0
- package/dist/core/video-recorder.d.ts.map +1 -0
- package/dist/core/worker-pool.d.ts +87 -0
- package/dist/core/worker-pool.d.ts.map +1 -0
- package/dist/{daemon-manager-2EQDVUVM.js → daemon-manager-2SK5PHJR.js} +3 -3
- package/dist/{filters-MQG2RMPX.js.map → daemon-manager-2SK5PHJR.js.map} +0 -0
- package/dist/device/android.d.ts +66 -0
- package/dist/device/android.d.ts.map +1 -0
- package/dist/device/discover.d.ts +15 -0
- package/dist/device/discover.d.ts.map +1 -0
- package/dist/device/index.d.ts +4 -0
- package/dist/device/index.d.ts.map +1 -0
- package/dist/device/ios.d.ts +126 -0
- package/dist/device/ios.d.ts.map +1 -0
- package/dist/diagnostics/live-inspector.d.ts +121 -0
- package/dist/diagnostics/live-inspector.d.ts.map +1 -0
- package/dist/diagnostics/native-logs.d.ts +38 -0
- package/dist/diagnostics/native-logs.d.ts.map +1 -0
- package/dist/discover-43C3BE7I.js +15 -0
- package/dist/{github-pr-YMWIPCCZ.js.map → discover-43C3BE7I.js.map} +0 -0
- package/dist/{doctor-command-QIYBI7ZF.js → doctor-command-CLKEEOAX.js} +14 -10
- package/dist/{doctor-command-QIYBI7ZF.js.map → doctor-command-CLKEEOAX.js.map} +1 -1
- package/dist/drivers/adapter-registry.d.ts +96 -0
- package/dist/drivers/adapter-registry.d.ts.map +1 -0
- package/dist/drivers/appium/android.d.ts +22 -0
- package/dist/drivers/appium/android.d.ts.map +1 -0
- package/dist/drivers/appium/client.d.ts +26 -0
- package/dist/drivers/appium/client.d.ts.map +1 -0
- package/dist/drivers/appium/ios.d.ts +28 -0
- package/dist/drivers/appium/ios.d.ts.map +1 -0
- package/dist/drivers/appium/window-size.d.ts +8 -0
- package/dist/drivers/appium/window-size.d.ts.map +1 -0
- package/dist/drivers/browser-extensions.d.ts +62 -0
- package/dist/drivers/browser-extensions.d.ts.map +1 -0
- package/dist/drivers/cdp-browser.d.ts +102 -0
- package/dist/drivers/cdp-browser.d.ts.map +1 -0
- package/dist/drivers/common/xml-tokenizer.d.ts +26 -0
- package/dist/drivers/common/xml-tokenizer.d.ts.map +1 -0
- package/dist/drivers/device-controls.d.ts +36 -0
- package/dist/drivers/device-controls.d.ts.map +1 -0
- package/dist/drivers/electrobun.d.ts +47 -0
- package/dist/drivers/electrobun.d.ts.map +1 -0
- package/dist/drivers/electron.d.ts +36 -0
- package/dist/drivers/electron.d.ts.map +1 -0
- package/dist/drivers/index.d.ts +2 -0
- package/dist/drivers/index.d.ts.map +1 -0
- package/dist/drivers/launch-options.d.ts +10 -0
- package/dist/drivers/launch-options.d.ts.map +1 -0
- package/dist/drivers/network-profiles.d.ts +9 -0
- package/dist/drivers/network-profiles.d.ts.map +1 -0
- package/dist/drivers/playwright-parser.d.ts +16 -0
- package/dist/drivers/playwright-parser.d.ts.map +1 -0
- package/dist/drivers/playwright.d.ts +69 -0
- package/dist/drivers/playwright.d.ts.map +1 -0
- package/dist/drivers/raw-driver.d.ts +399 -0
- package/dist/drivers/raw-driver.d.ts.map +1 -0
- package/dist/drivers/uiautomator2/client.d.ts +77 -0
- package/dist/drivers/uiautomator2/client.d.ts.map +1 -0
- package/dist/drivers/uiautomator2/driver.d.ts +20 -0
- package/dist/drivers/uiautomator2/driver.d.ts.map +1 -0
- package/dist/drivers/uiautomator2/index.d.ts +5 -0
- package/dist/drivers/uiautomator2/index.d.ts.map +1 -0
- package/dist/drivers/uiautomator2/installer.d.ts +20 -0
- package/dist/drivers/uiautomator2/installer.d.ts.map +1 -0
- package/dist/drivers/uiautomator2/pagesource.d.ts +12 -0
- package/dist/drivers/uiautomator2/pagesource.d.ts.map +1 -0
- package/dist/drivers/wda/client.d.ts +116 -0
- package/dist/drivers/wda/client.d.ts.map +1 -0
- package/dist/drivers/wda/driver.d.ts +26 -0
- package/dist/drivers/wda/driver.d.ts.map +1 -0
- package/dist/drivers/wda/index.d.ts +5 -0
- package/dist/drivers/wda/index.d.ts.map +1 -0
- package/dist/drivers/wda/installer.d.ts +51 -0
- package/dist/drivers/wda/installer.d.ts.map +1 -0
- package/dist/drivers/wda/pagesource.d.ts +12 -0
- package/dist/drivers/wda/pagesource.d.ts.map +1 -0
- package/dist/errors.d.ts +82 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/{filters-MQG2RMPX.js → filters-5DCGGJRN.js} +3 -3
- package/dist/{installer-5UHTYQTB.js.map → filters-5DCGGJRN.js.map} +0 -0
- package/dist/gherkin/compiler.d.ts +3 -0
- package/dist/gherkin/compiler.d.ts.map +1 -0
- package/dist/gherkin/index.d.ts +7 -0
- package/dist/gherkin/index.d.ts.map +1 -0
- package/dist/gherkin/matcher.d.ts +9 -0
- package/dist/gherkin/matcher.d.ts.map +1 -0
- package/dist/gherkin/registry.d.ts +28 -0
- package/dist/gherkin/registry.d.ts.map +1 -0
- package/dist/gherkin/steps.d.ts +13 -32
- package/dist/gherkin/steps.d.ts.map +1 -0
- package/dist/gherkin/steps.js +5 -2
- package/dist/gherkin/steps.js.map +1 -1
- package/dist/gherkin/world.d.ts +15 -0
- package/dist/gherkin/world.d.ts.map +1 -0
- package/dist/{github-pr-YMWIPCCZ.js → github-pr-RYO6IAKD.js} +3 -3
- package/dist/{ios-Y4TO5MBR.js.map → github-pr-RYO6IAKD.js.map} +0 -0
- package/dist/{html-FLMWPFQD.js → html-KJ2QAGF4.js} +6 -3
- package/dist/{html-FLMWPFQD.js.map → html-KJ2QAGF4.js.map} +1 -1
- package/dist/index.d.ts +54 -1912
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +534 -291
- package/dist/index.js.map +1 -1
- package/dist/{init-command-Z3QREABL.js → init-command-V5VGN3IS.js} +5 -2
- package/dist/{init-command-Z3QREABL.js.map → init-command-V5VGN3IS.js.map} +1 -1
- package/dist/{init-flow-command-4EKRVTNT.js → init-flow-command-INYUCC6N.js} +6 -3
- package/dist/{init-flow-command-4EKRVTNT.js.map → init-flow-command-INYUCC6N.js.map} +1 -1
- package/dist/{installer-5UHTYQTB.js → installer-DMTY47SI.js} +5 -5
- package/dist/{machine-6H25TRTU.js.map → installer-DMTY47SI.js.map} +0 -0
- package/dist/{ios-Y4TO5MBR.js → ios-SZ4RBI7Q.js} +4 -4
- package/dist/{provider-YIPU5K42.js.map → ios-SZ4RBI7Q.js.map} +0 -0
- package/dist/json-57Z2YSES.js +39 -0
- package/dist/json-57Z2YSES.js.map +1 -0
- package/dist/{junit-CGB3LKHD.js → junit-MHD5AXBU.js} +26 -6
- package/dist/junit-MHD5AXBU.js.map +1 -0
- package/dist/local-RH5EFGYF.js +31 -0
- package/dist/{runner-JID2YWRE.js.map → local-RH5EFGYF.js.map} +0 -0
- package/dist/{machine-6H25TRTU.js → machine-NOOFRT45.js} +3 -3
- package/dist/{server-UIRGHUYM.js.map → machine-NOOFRT45.js.map} +0 -0
- package/dist/machine.d.ts +20 -0
- package/dist/machine.d.ts.map +1 -0
- package/dist/mcp/server.d.ts +73 -0
- package/dist/mcp/server.d.ts.map +1 -0
- package/dist/{provider-YIPU5K42.js → provider-CBAXZ2VA.js} +3 -3
- package/dist/{session-BE6U34DA.js.map → provider-CBAXZ2VA.js.map} +0 -0
- package/dist/{redact-U72BUBBR.js → redact-OG4M3IEU.js} +5 -2
- package/dist/{redact-U72BUBBR.js.map → redact-OG4M3IEU.js.map} +1 -1
- package/dist/report/allure.d.ts +3 -0
- package/dist/report/allure.d.ts.map +1 -0
- package/dist/report/classify-error.d.ts +7 -0
- package/dist/report/classify-error.d.ts.map +1 -0
- package/dist/report/code-frame.d.ts +16 -0
- package/dist/report/code-frame.d.ts.map +1 -0
- package/dist/report/console.d.ts +7 -0
- package/dist/report/console.d.ts.map +1 -0
- package/dist/report/failure-bundle.d.ts +66 -0
- package/dist/report/failure-bundle.d.ts.map +1 -0
- package/dist/report/failure-diagnostics.d.ts +11 -0
- package/dist/report/failure-diagnostics.d.ts.map +1 -0
- package/dist/report/github-pr.d.ts +20 -0
- package/dist/report/github-pr.d.ts.map +1 -0
- package/dist/report/html.d.ts +3 -0
- package/dist/report/html.d.ts.map +1 -0
- package/dist/report/index.d.ts +8 -0
- package/dist/report/index.d.ts.map +1 -0
- package/dist/report/json.d.ts +3 -0
- package/dist/report/json.d.ts.map +1 -0
- package/dist/report/junit.d.ts +3 -0
- package/dist/report/junit.d.ts.map +1 -0
- package/dist/report/redact.d.ts +29 -0
- package/dist/report/redact.d.ts.map +1 -0
- package/dist/report/selector-guardrails.d.ts +12 -0
- package/dist/report/selector-guardrails.d.ts.map +1 -0
- package/dist/report/types.d.ts +164 -0
- package/dist/report/types.d.ts.map +1 -0
- package/dist/{runner-JID2YWRE.js → runner-ABGUVOJG.js} +5 -3
- package/dist/{validator-YWNHCU2S.js.map → runner-ABGUVOJG.js.map} +0 -0
- package/dist/runtime/appium-server.d.ts +34 -0
- package/dist/runtime/appium-server.d.ts.map +1 -0
- package/dist/runtime/appium.d.ts +5 -0
- package/dist/runtime/appium.d.ts.map +1 -0
- package/dist/runtime/capabilities.d.ts +19 -0
- package/dist/runtime/capabilities.d.ts.map +1 -0
- package/dist/runtime/daemon-manager.d.ts +83 -0
- package/dist/runtime/daemon-manager.d.ts.map +1 -0
- package/dist/runtime/local.d.ts +38 -0
- package/dist/runtime/local.d.ts.map +1 -0
- package/dist/runtime/types.d.ts +21 -0
- package/dist/runtime/types.d.ts.map +1 -0
- package/dist/runtime/web-server.d.ts +57 -0
- package/dist/runtime/web-server.d.ts.map +1 -0
- package/dist/schemas/config.d.ts +780 -0
- package/dist/schemas/config.d.ts.map +1 -0
- package/dist/schemas/device.d.ts +12 -0
- package/dist/schemas/device.d.ts.map +1 -0
- package/dist/schemas/element.d.ts +66 -0
- package/dist/schemas/element.d.ts.map +1 -0
- package/dist/schemas/index.d.ts +5 -0
- package/dist/schemas/index.d.ts.map +1 -0
- package/dist/schemas/selector.d.ts +193 -0
- package/dist/schemas/selector.d.ts.map +1 -0
- package/dist/screenshot-compare-V4JQG73R.js +2410 -0
- package/dist/screenshot-compare-V4JQG73R.js.map +1 -0
- package/dist/server-D45AO34E.js +6731 -0
- package/dist/server-D45AO34E.js.map +1 -0
- package/dist/{server-UIRGHUYM.js → server-KLZBJOMQ.js} +3 -3
- package/dist/server-KLZBJOMQ.js.map +1 -0
- package/dist/session-N6DEYVPM.js +21 -0
- package/dist/session-N6DEYVPM.js.map +1 -0
- package/dist/smart/auto-wait.d.ts +38 -0
- package/dist/smart/auto-wait.d.ts.map +1 -0
- package/dist/smart/channel-resolver.d.ts +90 -0
- package/dist/smart/channel-resolver.d.ts.map +1 -0
- package/dist/smart/coordinator.d.ts +162 -0
- package/dist/smart/coordinator.d.ts.map +1 -0
- package/dist/smart/diagnostics.d.ts +15 -0
- package/dist/smart/diagnostics.d.ts.map +1 -0
- package/dist/smart/element-matcher.d.ts +24 -0
- package/dist/smart/element-matcher.d.ts.map +1 -0
- package/dist/smart/hierarchy-cache.d.ts +16 -0
- package/dist/smart/hierarchy-cache.d.ts.map +1 -0
- package/dist/smart/index.d.ts +4 -0
- package/dist/smart/index.d.ts.map +1 -0
- package/dist/studio/api.d.ts +317 -0
- package/dist/studio/api.d.ts.map +1 -0
- package/dist/studio/context.d.ts +7 -0
- package/dist/studio/context.d.ts.map +1 -0
- package/dist/studio/core/element-tree.d.ts +15 -0
- package/dist/studio/core/element-tree.d.ts.map +1 -0
- package/dist/studio/effect-handler.d.ts +3 -0
- package/dist/studio/effect-handler.d.ts.map +1 -0
- package/dist/studio/procedures.d.ts +4 -0
- package/dist/studio/procedures.d.ts.map +1 -0
- package/dist/studio/recording-session.d.ts +31 -0
- package/dist/studio/recording-session.d.ts.map +1 -0
- package/dist/studio/routers/devices.d.ts +11 -0
- package/dist/studio/routers/devices.d.ts.map +1 -0
- package/dist/studio/routers/inspector.d.ts +104 -0
- package/dist/studio/routers/inspector.d.ts.map +1 -0
- package/dist/studio/routers/recording.d.ts +130 -0
- package/dist/studio/routers/recording.d.ts.map +1 -0
- package/dist/studio/routers/tests.d.ts +93 -0
- package/dist/studio/routers/tests.d.ts.map +1 -0
- package/dist/studio/server.d.ts +12 -0
- package/dist/studio/server.d.ts.map +1 -0
- package/dist/{studio-command-TXQTIWRS.js → studio-command-TNSJGTFA.js} +6 -3
- package/dist/{studio-command-TXQTIWRS.js.map → studio-command-TNSJGTFA.js.map} +1 -1
- package/dist/{test-command-CCSQPKWU.js → test-command-EXPYFDTF.js} +452 -85
- package/dist/test-command-EXPYFDTF.js.map +1 -0
- package/dist/{validator-YWNHCU2S.js → validator-AJNOFBQM.js} +4 -4
- package/dist/validator-AJNOFBQM.js.map +1 -0
- package/native/darwin-arm64/libspana_native.dylib +0 -0
- package/native/darwin-x64/libspana_native.dylib +0 -0
- package/native/linux-arm64/libspana_native.so +0 -0
- package/native/linux-x64/libspana_native.so +0 -0
- package/native/win32-x64/spana_native.dll +0 -0
- package/package.json +15 -18
- package/studio-dist/assets/index-CHLA4F7b.css +2 -0
- package/studio-dist/assets/index-DXGUfzm3.js +23 -0
- package/studio-dist/index.html +2 -2
- package/dist/accessibility-audit-YZOPUY3D.js.map +0 -1
- package/dist/app-xIYd2jde.d.ts +0 -1309
- package/dist/chunk-66D3C7NB.js.map +0 -1
- package/dist/chunk-7QFJ7MDH.js +0 -249
- package/dist/chunk-7QFJ7MDH.js.map +0 -1
- package/dist/chunk-B35G77DN.js.map +0 -1
- package/dist/chunk-B473XZOM.js.map +0 -1
- package/dist/chunk-DGUM43GV.js +0 -11
- package/dist/chunk-DP7MGXHN.js.map +0 -1
- package/dist/chunk-X2TJP7LB.js.map +0 -1
- package/dist/chunk-Y6KMJJ2T.js.map +0 -1
- package/dist/chunk-Z6K4QQAR.js.map +0 -1
- package/dist/config-loader-WLPQ5WVH.js +0 -9
- package/dist/console-DIYEJSSP.js.map +0 -1
- package/dist/discover-RLSKEBAX.js +0 -15
- package/dist/flow-CI5parw2.d.ts +0 -90
- package/dist/json-JMRPUVY2.js +0 -20
- package/dist/json-JMRPUVY2.js.map +0 -1
- package/dist/junit-CGB3LKHD.js.map +0 -1
- package/dist/screenshot-compare-POTXVUTL.js +0 -136
- package/dist/screenshot-compare-POTXVUTL.js.map +0 -1
- package/dist/server-6KQSTQIG.js +0 -852
- package/dist/server-6KQSTQIG.js.map +0 -1
- package/dist/session-BE6U34DA.js +0 -18
- package/dist/test-command-CCSQPKWU.js.map +0 -1
- package/studio-dist/assets/index-CBFsOh-9.js +0 -193
- package/studio-dist/assets/index-DH_18EyL.css +0 -1
|
@@ -1,132 +1,162 @@
|
|
|
1
1
|
import {
|
|
2
2
|
connectPlaywrightOverCDP,
|
|
3
3
|
connectPlaywrightOverWS,
|
|
4
|
-
createPromiseApp,
|
|
5
|
-
createPromiseExpect,
|
|
6
4
|
createUiAutomator2Driver,
|
|
7
5
|
createWDADriver,
|
|
8
6
|
ensureWarmBrowserDaemon,
|
|
9
|
-
flattenElements,
|
|
10
7
|
launchPlaywrightBrowser,
|
|
11
8
|
makeElectronDriver,
|
|
12
9
|
makePlaywrightDriver,
|
|
13
|
-
mergeLaunchOptions,
|
|
14
10
|
parseAndroidHierarchy,
|
|
15
11
|
parseIOSHierarchy,
|
|
16
12
|
parseWebHierarchy,
|
|
17
13
|
resolveNetworkConditions,
|
|
18
14
|
setupUiAutomator2
|
|
19
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-PPAPRKQU.js";
|
|
20
16
|
import {
|
|
21
17
|
CdpDomChannel,
|
|
22
|
-
DriverError,
|
|
23
|
-
SPANA_INJECTED_RUNTIME_SCRIPT,
|
|
24
|
-
buildDomFindElementScript,
|
|
25
18
|
createSpanaBridgeChannel,
|
|
26
19
|
makeElectrobunDriver
|
|
27
|
-
} from "./chunk-
|
|
20
|
+
} from "./chunk-GDDCZ2PL.js";
|
|
21
|
+
import {
|
|
22
|
+
adbReverse,
|
|
23
|
+
adbReverseRemove,
|
|
24
|
+
ensureAndroidDevice
|
|
25
|
+
} from "./chunk-XVL4FHXA.js";
|
|
28
26
|
import {
|
|
29
27
|
connectPhysicalDevice,
|
|
30
28
|
ensureAppInstalled,
|
|
31
29
|
ensureIOSSimulator,
|
|
32
30
|
firstIOSPhysicalDevice
|
|
33
|
-
} from "./chunk-
|
|
31
|
+
} from "./chunk-2MA5G2VH.js";
|
|
34
32
|
import {
|
|
35
33
|
setupWDA
|
|
36
|
-
} from "./chunk-
|
|
34
|
+
} from "./chunk-XD6A3VXB.js";
|
|
37
35
|
import {
|
|
38
36
|
getHealthyWarmDaemon,
|
|
39
37
|
registerWarmDaemon,
|
|
40
38
|
updateWarmDaemonSession
|
|
41
|
-
} from "./chunk-
|
|
39
|
+
} from "./chunk-FHCOPLYB.js";
|
|
42
40
|
import {
|
|
43
|
-
allocateFreePort,
|
|
44
41
|
allocatePort
|
|
45
|
-
} from "./chunk-
|
|
42
|
+
} from "./chunk-7Q7TSUNL.js";
|
|
46
43
|
import {
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
44
|
+
DriverError,
|
|
45
|
+
SPANA_INJECTED_RUNTIME_SCRIPT,
|
|
46
|
+
buildDomFindElementScript
|
|
47
|
+
} from "./chunk-GAWJL6Q3.js";
|
|
50
48
|
import {
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
49
|
+
init_esm_shims
|
|
50
|
+
} from "./chunk-FTXUQMGH.js";
|
|
51
|
+
|
|
52
|
+
// src/runtime/local.ts
|
|
53
|
+
init_esm_shims();
|
|
54
|
+
import { Effect as Effect2 } from "effect";
|
|
55
55
|
|
|
56
|
-
// src/
|
|
56
|
+
// src/drivers/cdp-browser.ts
|
|
57
|
+
init_esm_shims();
|
|
58
|
+
import { spawn } from "child_process";
|
|
59
|
+
import { createHash } from "crypto";
|
|
60
|
+
import { existsSync as existsSync2, mkdtempSync, readFileSync as readFileSync2, rmSync } from "fs";
|
|
61
|
+
import { copyFile, readFile, writeFile } from "fs/promises";
|
|
62
|
+
import { tmpdir } from "os";
|
|
63
|
+
import { join as join2 } from "path";
|
|
57
64
|
import { Effect } from "effect";
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
65
|
+
|
|
66
|
+
// src/drivers/browser-extensions.ts
|
|
67
|
+
init_esm_shims();
|
|
68
|
+
import { existsSync, readFileSync, statSync } from "fs";
|
|
69
|
+
import { join, resolve } from "path";
|
|
70
|
+
function resolveBrowserExtensions(extensionPaths, baseDir = process.cwd()) {
|
|
71
|
+
return extensionPaths.map((rawPath) => {
|
|
72
|
+
const absPath = resolve(baseDir, rawPath);
|
|
73
|
+
if (!existsSync(absPath) || !statSync(absPath).isDirectory()) {
|
|
74
|
+
throw new Error(`Browser extension directory not found: ${absPath}`);
|
|
75
|
+
}
|
|
76
|
+
const manifestPath = join(absPath, "manifest.json");
|
|
77
|
+
if (!existsSync(manifestPath)) {
|
|
78
|
+
throw new Error(`Browser extension at ${absPath} is missing manifest.json`);
|
|
79
|
+
}
|
|
80
|
+
const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
|
|
81
|
+
const manifestVersion = Number(manifest["manifest_version"] ?? 3);
|
|
82
|
+
const action = manifest["action"] ?? manifest["browser_action"];
|
|
83
|
+
return {
|
|
84
|
+
path: absPath,
|
|
85
|
+
name: String(manifest["name"] ?? "Unnamed Extension"),
|
|
86
|
+
version: String(manifest["version"] ?? "0.0.0"),
|
|
87
|
+
manifestVersion,
|
|
88
|
+
...action?.default_popup ? { defaultPopup: action.default_popup } : {}
|
|
89
|
+
};
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
function applyExtensionChromeArgs(baseArgs, extensions) {
|
|
93
|
+
if (extensions.length === 0) return [...baseArgs];
|
|
94
|
+
const paths = extensions.map((e) => typeof e === "string" ? resolve(e) : e.path);
|
|
95
|
+
const joined = paths.join(",");
|
|
96
|
+
const filtered = baseArgs.filter(
|
|
97
|
+
(arg) => arg !== "--disable-extensions" && !arg.startsWith("--disable-extensions-except=") && !arg.startsWith("--load-extension=")
|
|
98
|
+
);
|
|
99
|
+
return [...filtered, `--disable-extensions-except=${joined}`, `--load-extension=${joined}`];
|
|
91
100
|
}
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
101
|
+
async function getLoadedExtensions(cdp) {
|
|
102
|
+
const res = await cdp.send("Target.getTargets");
|
|
103
|
+
const targets = Array.isArray(res?.targetInfos) ? res.targetInfos : [];
|
|
104
|
+
const results = [];
|
|
105
|
+
for (const t of targets) {
|
|
106
|
+
const url = String(t.url ?? "");
|
|
107
|
+
const match = url.match(/^chrome-extension:\/\/([a-z0-9]{16,})\//i);
|
|
108
|
+
if (!match?.[1]) continue;
|
|
109
|
+
results.push({
|
|
110
|
+
extensionId: match[1],
|
|
111
|
+
targetId: String(t.targetId ?? ""),
|
|
112
|
+
type: String(t.type ?? "unknown"),
|
|
113
|
+
url,
|
|
114
|
+
...t.title ? { title: t.title } : {}
|
|
115
|
+
});
|
|
96
116
|
}
|
|
97
|
-
|
|
98
|
-
|
|
117
|
+
return results;
|
|
118
|
+
}
|
|
119
|
+
async function runOAuthPopupFlow(app, options) {
|
|
120
|
+
const timeoutMs = options.timeoutMs ?? 1e4;
|
|
121
|
+
const pollIntervalMs = options.pollIntervalMs ?? 100;
|
|
122
|
+
const returnToOpener = options.returnToOpener !== false;
|
|
123
|
+
const beforeTabs = await app.getTabIds();
|
|
124
|
+
const openerTabIndex = Math.max(0, beforeTabs.length - 1);
|
|
125
|
+
const beforeSet = new Set(beforeTabs);
|
|
126
|
+
await options.trigger();
|
|
127
|
+
const deadline = Date.now() + timeoutMs;
|
|
128
|
+
let popupIndex = -1;
|
|
129
|
+
let popupTabId = "";
|
|
130
|
+
while (Date.now() < deadline) {
|
|
131
|
+
const currentTabs = await app.getTabIds();
|
|
132
|
+
const foundIdx = currentTabs.findIndex((id) => !beforeSet.has(id));
|
|
133
|
+
if (foundIdx >= 0) {
|
|
134
|
+
popupIndex = foundIdx;
|
|
135
|
+
popupTabId = currentTabs[foundIdx];
|
|
136
|
+
break;
|
|
137
|
+
}
|
|
138
|
+
await new Promise((r) => setTimeout(r, pollIntervalMs));
|
|
99
139
|
}
|
|
100
|
-
|
|
101
|
-
|
|
140
|
+
if (popupIndex < 0) {
|
|
141
|
+
throw new Error(`Timed out after ${timeoutMs}ms waiting for OAuth popup tab to open.`);
|
|
102
142
|
}
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
143
|
+
await app.switchToTab(popupIndex);
|
|
144
|
+
try {
|
|
145
|
+
await options.inPopup(app);
|
|
146
|
+
} finally {
|
|
147
|
+
if (returnToOpener) {
|
|
148
|
+
const remaining = await app.getTabIds().catch(() => []);
|
|
149
|
+
if (remaining.length > 0) {
|
|
150
|
+
const targetIdx = Math.min(openerTabIndex, remaining.length - 1);
|
|
151
|
+
await app.switchToTab(targetIdx).catch(() => {
|
|
152
|
+
});
|
|
110
153
|
}
|
|
111
154
|
}
|
|
112
|
-
this.sessions = [];
|
|
113
|
-
if (errors.length > 0) {
|
|
114
|
-
console.warn(
|
|
115
|
-
`SessionManager: ${errors.length} error(s) during cleanup:`,
|
|
116
|
-
errors.map((e) => e instanceof Error ? e.message : String(e))
|
|
117
|
-
);
|
|
118
|
-
}
|
|
119
155
|
}
|
|
120
|
-
};
|
|
156
|
+
return { popupTabId, openerTabIndex };
|
|
157
|
+
}
|
|
121
158
|
|
|
122
159
|
// src/drivers/cdp-browser.ts
|
|
123
|
-
import { spawn } from "child_process";
|
|
124
|
-
import { createHash } from "crypto";
|
|
125
|
-
import { existsSync, mkdtempSync, rmSync } from "fs";
|
|
126
|
-
import { copyFile, readFile, writeFile } from "fs/promises";
|
|
127
|
-
import { tmpdir } from "os";
|
|
128
|
-
import { join } from "path";
|
|
129
|
-
import { Effect as Effect2 } from "effect";
|
|
130
160
|
var INSTANT_ANIMATIONS_CDP_SCRIPT = `
|
|
131
161
|
(() => {
|
|
132
162
|
const inject = () => {
|
|
@@ -149,7 +179,7 @@ function resolveDirectCdpScopeKey(scope) {
|
|
|
149
179
|
return `cdp-${cwdHash}`;
|
|
150
180
|
}
|
|
151
181
|
function resolveChromiumExecutable(explicit) {
|
|
152
|
-
if (explicit &&
|
|
182
|
+
if (explicit && existsSync2(explicit)) return explicit;
|
|
153
183
|
const candidates = process.platform === "darwin" ? [
|
|
154
184
|
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
|
155
185
|
"/Applications/Chromium.app/Contents/MacOS/Chromium",
|
|
@@ -165,7 +195,7 @@ function resolveChromiumExecutable(explicit) {
|
|
|
165
195
|
"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
|
|
166
196
|
];
|
|
167
197
|
for (const path of candidates) {
|
|
168
|
-
if (
|
|
198
|
+
if (existsSync2(path)) return path;
|
|
169
199
|
}
|
|
170
200
|
return explicit ?? "google-chrome";
|
|
171
201
|
}
|
|
@@ -186,19 +216,64 @@ async function fetchBrowserWsUrl(httpEndpoint, timeoutMs = 1e4) {
|
|
|
186
216
|
}
|
|
187
217
|
throw new Error(`Direct CDP browser did not expose /json/version on ${httpEndpoint}`);
|
|
188
218
|
}
|
|
219
|
+
async function waitForDevToolsActivePort(userDataDir, child, getExitInfo, getStderr, timeoutMs) {
|
|
220
|
+
const activePortFile = join2(userDataDir, "DevToolsActivePort");
|
|
221
|
+
const deadline = Date.now() + timeoutMs;
|
|
222
|
+
while (Date.now() < deadline) {
|
|
223
|
+
const exit = getExitInfo();
|
|
224
|
+
if (exit.exited) {
|
|
225
|
+
const tail2 = getStderr().trim();
|
|
226
|
+
throw new Error(
|
|
227
|
+
`Direct CDP browser exited prematurely (code=${exit.code}, signal=${exit.signal})${tail2 ? `
|
|
228
|
+
stderr:
|
|
229
|
+
${tail2}` : ""}`
|
|
230
|
+
);
|
|
231
|
+
}
|
|
232
|
+
if (existsSync2(activePortFile)) {
|
|
233
|
+
try {
|
|
234
|
+
const lines = readFileSync2(activePortFile, "utf8").split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
|
|
235
|
+
const port = Number.parseInt(lines[0] ?? "", 10);
|
|
236
|
+
const wsPath = lines[1] ?? "";
|
|
237
|
+
if (Number.isFinite(port) && port > 0 && wsPath.startsWith("/")) {
|
|
238
|
+
const httpEndpoint = `http://127.0.0.1:${port}`;
|
|
239
|
+
const res = await fetch(`${httpEndpoint}/json/version`, {
|
|
240
|
+
signal: AbortSignal.timeout(1e3)
|
|
241
|
+
});
|
|
242
|
+
if (res.ok) {
|
|
243
|
+
const data = await res.json();
|
|
244
|
+
const wsUrl = data.webSocketDebuggerUrl ?? `ws://127.0.0.1:${port}${wsPath}`;
|
|
245
|
+
if (wsUrl.includes(wsPath) || wsUrl.startsWith(`ws://127.0.0.1:${port}/`)) {
|
|
246
|
+
return { port, wsPath, browserWsUrl: wsUrl, httpEndpoint };
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
} catch {
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
await new Promise((r) => setTimeout(r, 40));
|
|
254
|
+
}
|
|
255
|
+
const tail = getStderr().trim();
|
|
256
|
+
throw new Error(
|
|
257
|
+
`Direct CDP browser did not expose DevToolsActivePort / /json/version within ${timeoutMs}ms (pid=${child.pid ?? "unknown"})${tail ? `
|
|
258
|
+
stderr:
|
|
259
|
+
${tail}` : ""}`
|
|
260
|
+
);
|
|
261
|
+
}
|
|
189
262
|
async function launchDirectCdpBrowser(options = {}) {
|
|
190
263
|
const daemonKey = resolveDirectCdpScopeKey(options.warmBrowserScope);
|
|
264
|
+
const launchTimeoutMs = options.launchTimeout ?? 3e4;
|
|
191
265
|
if (options.warmBrowser) {
|
|
192
266
|
const existing = await getHealthyWarmDaemon("chromium", daemonKey, {
|
|
193
|
-
statusPath: "/json/version"
|
|
267
|
+
statusPath: "/json/version",
|
|
268
|
+
stateFile: options.daemonStateFile
|
|
194
269
|
});
|
|
195
270
|
if (existing) {
|
|
196
|
-
const
|
|
271
|
+
const httpEndpoint = `http://${existing.host}:${existing.port}`;
|
|
197
272
|
try {
|
|
198
|
-
const
|
|
273
|
+
const browserWsUrl = await fetchBrowserWsUrl(httpEndpoint, 1500);
|
|
199
274
|
return {
|
|
200
|
-
httpEndpoint
|
|
201
|
-
browserWsUrl
|
|
275
|
+
httpEndpoint,
|
|
276
|
+
browserWsUrl,
|
|
202
277
|
reused: true,
|
|
203
278
|
pid: existing.pid,
|
|
204
279
|
close: async () => {
|
|
@@ -213,18 +288,17 @@ async function launchDirectCdpBrowser(options = {}) {
|
|
|
213
288
|
try {
|
|
214
289
|
const { chromium } = await import("playwright-core");
|
|
215
290
|
const pwPath = chromium.executablePath();
|
|
216
|
-
if (pwPath &&
|
|
291
|
+
if (pwPath && existsSync2(pwPath)) {
|
|
217
292
|
execPath = pwPath;
|
|
218
293
|
}
|
|
219
294
|
} catch {
|
|
220
295
|
}
|
|
221
296
|
}
|
|
222
297
|
execPath = resolveChromiumExecutable(execPath);
|
|
223
|
-
const
|
|
224
|
-
const
|
|
225
|
-
const chromeArgs = [
|
|
298
|
+
const userDataDir = mkdtempSync(join2(tmpdir(), "spana-cdp-profile-"));
|
|
299
|
+
const baseChromeArgs = [
|
|
226
300
|
...options.headless !== false ? ["--headless=new"] : [],
|
|
227
|
-
|
|
301
|
+
"--remote-debugging-port=0",
|
|
228
302
|
"--remote-debugging-address=127.0.0.1",
|
|
229
303
|
`--user-data-dir=${userDataDir}`,
|
|
230
304
|
"--no-first-run",
|
|
@@ -244,17 +318,42 @@ async function launchDirectCdpBrowser(options = {}) {
|
|
|
244
318
|
...options.args ?? [],
|
|
245
319
|
"about:blank"
|
|
246
320
|
];
|
|
321
|
+
const resolvedExts = options.extensions && options.extensions.length > 0 ? resolveBrowserExtensions(options.extensions) : [];
|
|
322
|
+
const chromeArgs = resolvedExts.length > 0 ? applyExtensionChromeArgs(baseChromeArgs, resolvedExts) : baseChromeArgs;
|
|
247
323
|
const child = spawn(execPath, chromeArgs, {
|
|
248
324
|
detached: Boolean(options.warmBrowser),
|
|
249
|
-
stdio: "ignore"
|
|
325
|
+
stdio: ["ignore", "ignore", "pipe"]
|
|
250
326
|
});
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
327
|
+
let stderrBuf = "";
|
|
328
|
+
const MAX_STDERR = 8192;
|
|
329
|
+
child.stderr?.on("data", (chunk) => {
|
|
330
|
+
stderrBuf += typeof chunk === "string" ? chunk : chunk.toString("utf8");
|
|
331
|
+
if (stderrBuf.length > MAX_STDERR) {
|
|
332
|
+
stderrBuf = stderrBuf.slice(-MAX_STDERR);
|
|
333
|
+
}
|
|
334
|
+
});
|
|
335
|
+
let exitState = {
|
|
336
|
+
exited: false,
|
|
337
|
+
code: null,
|
|
338
|
+
signal: null
|
|
339
|
+
};
|
|
340
|
+
child.once("exit", (code, signal) => {
|
|
341
|
+
exitState = { exited: true, code, signal };
|
|
342
|
+
});
|
|
343
|
+
child.once("error", (err) => {
|
|
344
|
+
stderrBuf += `
|
|
345
|
+
spawn error: ${err.message}`;
|
|
346
|
+
exitState = { exited: true, code: -1, signal: null };
|
|
347
|
+
});
|
|
348
|
+
let bound;
|
|
256
349
|
try {
|
|
257
|
-
|
|
350
|
+
bound = await waitForDevToolsActivePort(
|
|
351
|
+
userDataDir,
|
|
352
|
+
child,
|
|
353
|
+
() => exitState,
|
|
354
|
+
() => stderrBuf,
|
|
355
|
+
launchTimeoutMs
|
|
356
|
+
);
|
|
258
357
|
} catch (err) {
|
|
259
358
|
try {
|
|
260
359
|
child.kill("SIGKILL");
|
|
@@ -264,19 +363,25 @@ async function launchDirectCdpBrowser(options = {}) {
|
|
|
264
363
|
throw err;
|
|
265
364
|
}
|
|
266
365
|
if (options.warmBrowser) {
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
366
|
+
child.stderr?.removeAllListeners("data");
|
|
367
|
+
child.stderr?.destroy();
|
|
368
|
+
child.unref();
|
|
369
|
+
registerWarmDaemon(
|
|
370
|
+
{
|
|
371
|
+
kind: "chromium",
|
|
372
|
+
deviceId: daemonKey,
|
|
373
|
+
host: "127.0.0.1",
|
|
374
|
+
port: bound.port,
|
|
375
|
+
pid: child.pid,
|
|
376
|
+
userDataDir,
|
|
377
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
378
|
+
},
|
|
379
|
+
options.daemonStateFile
|
|
380
|
+
);
|
|
276
381
|
}
|
|
277
382
|
return {
|
|
278
|
-
httpEndpoint,
|
|
279
|
-
browserWsUrl,
|
|
383
|
+
httpEndpoint: bound.httpEndpoint,
|
|
384
|
+
browserWsUrl: bound.browserWsUrl,
|
|
280
385
|
reused: Boolean(options.warmBrowser),
|
|
281
386
|
pid: child.pid,
|
|
282
387
|
close: async () => {
|
|
@@ -396,7 +501,7 @@ var RESOURCE_BLOCK_PATTERNS = {
|
|
|
396
501
|
stylesheet: ["*.css"]
|
|
397
502
|
};
|
|
398
503
|
function makeLightweightCdpDriver(options) {
|
|
399
|
-
return
|
|
504
|
+
return Effect.gen(function* () {
|
|
400
505
|
const isBrowserWs = options.cdpUrl.includes("/devtools/browser/");
|
|
401
506
|
const useContexts = Boolean(
|
|
402
507
|
options.useBrowserContexts || options.freshContextPerFlow || isBrowserWs
|
|
@@ -405,7 +510,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
405
510
|
const httpEndpoint = isWs ? options.cdpUrl.replace(/^ws(s?):\/\//, "http$1://").replace(/\/devtools\/.*$/, "") : options.cdpUrl.replace(/\/+$/, "");
|
|
406
511
|
let connectWsUrl = isWs ? options.cdpUrl : void 0;
|
|
407
512
|
if (useContexts && !connectWsUrl) {
|
|
408
|
-
connectWsUrl = yield*
|
|
513
|
+
connectWsUrl = yield* Effect.tryPromise({
|
|
409
514
|
try: () => fetchBrowserWsUrl(httpEndpoint, 5e3),
|
|
410
515
|
catch: (e) => new DriverError({
|
|
411
516
|
message: `Failed to resolve browser CDP WebSocket at ${options.cdpUrl}: ${e}`
|
|
@@ -415,46 +520,66 @@ function makeLightweightCdpDriver(options) {
|
|
|
415
520
|
const cdpChannel = new CdpDomChannel({
|
|
416
521
|
endpointUrl: httpEndpoint,
|
|
417
522
|
...connectWsUrl ? { webSocketUrl: connectWsUrl } : {},
|
|
523
|
+
timeoutMs: options.evaluateTimeout ?? 1e4,
|
|
418
524
|
fetchFn: options.fetchFn,
|
|
419
525
|
createWebSocket: options.createWebSocket
|
|
420
526
|
});
|
|
421
|
-
yield*
|
|
527
|
+
yield* Effect.tryPromise({
|
|
422
528
|
try: () => cdpChannel.connect(),
|
|
423
529
|
catch: (e) => new DriverError({
|
|
424
530
|
message: `Failed to connect lightweight CDP browser at ${options.cdpUrl}: ${e}`
|
|
425
531
|
})
|
|
426
532
|
});
|
|
427
|
-
|
|
428
|
-
|
|
533
|
+
let width = options.viewport?.width ?? 1280;
|
|
534
|
+
let height = options.viewport?.height ?? 720;
|
|
429
535
|
const label = options.engineLabel ?? "cdp";
|
|
430
536
|
let activeSlot;
|
|
431
537
|
let prefetchedSlotPromise;
|
|
432
538
|
let hasRunFirstFlow = false;
|
|
433
539
|
let activeAuthenticatorId;
|
|
540
|
+
let dialogHandler = null;
|
|
434
541
|
const backgroundDisposals = [];
|
|
435
542
|
const consoleLogs = [];
|
|
436
543
|
const jsErrors = [];
|
|
437
544
|
const routeRules = [];
|
|
545
|
+
const initScripts = [];
|
|
546
|
+
const exposedFunctions = /* @__PURE__ */ new Map();
|
|
547
|
+
const requestListeners = /* @__PURE__ */ new Set();
|
|
548
|
+
const navigationUrls = [];
|
|
549
|
+
const uploadTempDirs = [];
|
|
550
|
+
let currentNetworkConditions;
|
|
551
|
+
let cachedUserAgent;
|
|
438
552
|
let fetchInterceptEnabled = false;
|
|
439
553
|
let activeResponseWatchers = 0;
|
|
440
554
|
let nextTabSeq = 1;
|
|
441
555
|
let downloadDir;
|
|
556
|
+
const popupWaiters = [];
|
|
442
557
|
const completedDownloads = [];
|
|
443
558
|
const downloadWaiters = [];
|
|
444
559
|
const pendingDownloadGuids = /* @__PURE__ */ new Map();
|
|
445
560
|
cdpChannel.onEvent("Browser.downloadWillBegin", (params) => {
|
|
446
561
|
if (params?.guid && downloadDir) {
|
|
447
|
-
|
|
562
|
+
const guid = String(params.guid);
|
|
563
|
+
pendingDownloadGuids.set(guid, {
|
|
564
|
+
filePath: join2(downloadDir, guid),
|
|
565
|
+
suggestedFilename: String(params?.suggestedFilename ?? guid),
|
|
566
|
+
url: String(params?.url ?? "")
|
|
567
|
+
});
|
|
448
568
|
}
|
|
449
569
|
});
|
|
450
570
|
cdpChannel.onEvent("Browser.downloadProgress", (params) => {
|
|
451
571
|
if (params?.state === "completed" && params?.guid) {
|
|
452
|
-
const
|
|
453
|
-
pendingDownloadGuids.
|
|
454
|
-
|
|
572
|
+
const guid = String(params.guid);
|
|
573
|
+
const entry = pendingDownloadGuids.get(guid) ?? (downloadDir ? {
|
|
574
|
+
filePath: join2(downloadDir, guid),
|
|
575
|
+
suggestedFilename: guid,
|
|
576
|
+
url: ""
|
|
577
|
+
} : void 0);
|
|
578
|
+
pendingDownloadGuids.delete(guid);
|
|
579
|
+
if (!entry) return;
|
|
455
580
|
const waiter = downloadWaiters.shift();
|
|
456
|
-
if (waiter) waiter.resolve(
|
|
457
|
-
else completedDownloads.push(
|
|
581
|
+
if (waiter) waiter.resolve(entry);
|
|
582
|
+
else completedDownloads.push(entry);
|
|
458
583
|
}
|
|
459
584
|
});
|
|
460
585
|
const loadStorageStateFile = async (path) => {
|
|
@@ -486,10 +611,63 @@ function makeLightweightCdpDriver(options) {
|
|
|
486
611
|
};
|
|
487
612
|
const useInjectedRuntime = options.useInjectedRuntime ?? !options.createWebSocket;
|
|
488
613
|
cdpChannel.enableInjectedRuntime(useInjectedRuntime);
|
|
614
|
+
const applyLocaleOverride = async (sessionId, locale) => {
|
|
615
|
+
await cdpChannel.sendCommand("Emulation.setLocaleOverride", { locale }, sessionId).catch(() => {
|
|
616
|
+
});
|
|
617
|
+
if (!cachedUserAgent) {
|
|
618
|
+
const ua = await cdpChannel.evaluateOnSession(sessionId, "navigator.userAgent").catch(() => "");
|
|
619
|
+
if (ua) cachedUserAgent = ua;
|
|
620
|
+
}
|
|
621
|
+
const acceptLanguage = locale.includes("-") ? `${locale},${locale.split("-")[0]};q=0.9` : locale;
|
|
622
|
+
await cdpChannel.sendCommand(
|
|
623
|
+
"Emulation.setUserAgentOverride",
|
|
624
|
+
{
|
|
625
|
+
userAgent: cachedUserAgent || "Mozilla/5.0",
|
|
626
|
+
acceptLanguage
|
|
627
|
+
},
|
|
628
|
+
sessionId
|
|
629
|
+
).catch(() => {
|
|
630
|
+
});
|
|
631
|
+
};
|
|
632
|
+
const applyNetworkConditionsToSession = async (sessionId, conditions) => {
|
|
633
|
+
const resolved = resolveNetworkConditions(conditions);
|
|
634
|
+
await cdpChannel.sendCommand("Network.enable", {}, sessionId).catch(() => {
|
|
635
|
+
});
|
|
636
|
+
await cdpChannel.sendCommand(
|
|
637
|
+
"Network.emulateNetworkConditions",
|
|
638
|
+
{
|
|
639
|
+
offline: resolved.offline,
|
|
640
|
+
latency: resolved.latencyMs,
|
|
641
|
+
downloadThroughput: resolved.downloadThroughputKbps < 0 ? -1 : Math.max(Math.round(resolved.downloadThroughputKbps * 1024 / 8), 0),
|
|
642
|
+
uploadThroughput: resolved.uploadThroughputKbps < 0 ? -1 : Math.max(Math.round(resolved.uploadThroughputKbps * 1024 / 8), 0)
|
|
643
|
+
},
|
|
644
|
+
sessionId
|
|
645
|
+
).catch(() => {
|
|
646
|
+
});
|
|
647
|
+
};
|
|
648
|
+
const installExposeFunctionOnSession = async (sessionId, name) => {
|
|
649
|
+
const bindingName = `__spana_bind_${name}`;
|
|
650
|
+
await cdpChannel.sendCommand("Runtime.addBinding", { name: bindingName }, sessionId).catch(() => {
|
|
651
|
+
});
|
|
652
|
+
const wrapperSource = `(() => {
|
|
653
|
+
if (window[${JSON.stringify(name)}]) return;
|
|
654
|
+
let seq = 0;
|
|
655
|
+
const pending = (window.__spanaBindPending = window.__spanaBindPending || {});
|
|
656
|
+
window[${JSON.stringify(name)}] = (...args) => new Promise((resolve, reject) => {
|
|
657
|
+
const id = ${JSON.stringify(name)} + ":" + (++seq);
|
|
658
|
+
pending[id] = { resolve, reject };
|
|
659
|
+
window[${JSON.stringify(bindingName)}](JSON.stringify({ id, name: ${JSON.stringify(name)}, args }));
|
|
660
|
+
});
|
|
661
|
+
})();`;
|
|
662
|
+
await cdpChannel.sendCommand("Page.addScriptToEvaluateOnNewDocument", { source: wrapperSource }, sessionId).catch(() => {
|
|
663
|
+
});
|
|
664
|
+
await cdpChannel.evaluateOnSession(sessionId, wrapperSource).catch(() => {
|
|
665
|
+
});
|
|
666
|
+
};
|
|
489
667
|
const configureSession = async (sessionId, storageStatePath) => {
|
|
490
668
|
const state = await loadStorageStateFile(storageStatePath);
|
|
491
669
|
const needsNetworkDomain = Boolean(
|
|
492
|
-
options.blockResources && options.blockResources.length > 0 || state?.cookies && state.cookies.length > 0
|
|
670
|
+
options.blockResources && options.blockResources.length > 0 || state?.cookies && state.cookies.length > 0 || requestListeners.size > 0 || currentNetworkConditions
|
|
493
671
|
);
|
|
494
672
|
await Promise.all([
|
|
495
673
|
cdpChannel.sendCommand("Page.enable", {}, sessionId).catch(() => {
|
|
@@ -527,6 +705,13 @@ function makeLightweightCdpDriver(options) {
|
|
|
527
705
|
).catch(() => {
|
|
528
706
|
});
|
|
529
707
|
}
|
|
708
|
+
for (const scriptSource of initScripts) {
|
|
709
|
+
await cdpChannel.sendCommand("Page.addScriptToEvaluateOnNewDocument", { source: scriptSource }, sessionId).catch(() => {
|
|
710
|
+
});
|
|
711
|
+
}
|
|
712
|
+
for (const fnName of exposedFunctions.keys()) {
|
|
713
|
+
await installExposeFunctionOnSession(sessionId, fnName);
|
|
714
|
+
}
|
|
530
715
|
if (options.blockResources && options.blockResources.length > 0) {
|
|
531
716
|
const urls = options.blockResources.flatMap((t) => RESOURCE_BLOCK_PATTERNS[t] ?? []);
|
|
532
717
|
if (urls.length > 0) {
|
|
@@ -558,9 +743,43 @@ function makeLightweightCdpDriver(options) {
|
|
|
558
743
|
});
|
|
559
744
|
}
|
|
560
745
|
if (routeRules.length > 0) {
|
|
746
|
+
fetchInterceptEnabled = true;
|
|
561
747
|
await cdpChannel.sendCommand("Fetch.enable", { patterns: [{ urlPattern: "*" }] }, sessionId).catch(() => {
|
|
562
748
|
});
|
|
563
749
|
}
|
|
750
|
+
if (currentNetworkConditions) {
|
|
751
|
+
await applyNetworkConditionsToSession(sessionId, currentNetworkConditions);
|
|
752
|
+
}
|
|
753
|
+
if (options.emulation) {
|
|
754
|
+
const emuFeatures = [];
|
|
755
|
+
if (options.emulation.colorScheme !== void 0) {
|
|
756
|
+
emuFeatures.push({
|
|
757
|
+
name: "prefers-color-scheme",
|
|
758
|
+
value: options.emulation.colorScheme === "no-preference" ? "" : options.emulation.colorScheme
|
|
759
|
+
});
|
|
760
|
+
}
|
|
761
|
+
if (options.emulation.reducedMotion !== void 0) {
|
|
762
|
+
emuFeatures.push({
|
|
763
|
+
name: "prefers-reduced-motion",
|
|
764
|
+
value: options.emulation.reducedMotion === "no-preference" ? "" : options.emulation.reducedMotion
|
|
765
|
+
});
|
|
766
|
+
}
|
|
767
|
+
if (emuFeatures.length > 0) {
|
|
768
|
+
await cdpChannel.sendCommand("Emulation.setEmulatedMedia", { features: emuFeatures }, sessionId).catch(() => {
|
|
769
|
+
});
|
|
770
|
+
}
|
|
771
|
+
if (options.emulation.locale) {
|
|
772
|
+
await applyLocaleOverride(sessionId, options.emulation.locale);
|
|
773
|
+
}
|
|
774
|
+
if (options.emulation.timezoneId) {
|
|
775
|
+
await cdpChannel.sendCommand(
|
|
776
|
+
"Emulation.setTimezoneOverride",
|
|
777
|
+
{ timezoneId: options.emulation.timezoneId },
|
|
778
|
+
sessionId
|
|
779
|
+
).catch(() => {
|
|
780
|
+
});
|
|
781
|
+
}
|
|
782
|
+
}
|
|
564
783
|
let authenticatorId;
|
|
565
784
|
if (options.virtualAuthenticator) {
|
|
566
785
|
const authOpts = typeof options.virtualAuthenticator === "object" ? options.virtualAuthenticator : void 0;
|
|
@@ -651,9 +870,11 @@ function makeLightweightCdpDriver(options) {
|
|
|
651
870
|
const alreadyTracked = activeSlot.tabs.some(
|
|
652
871
|
(t) => t.sessionId === childSid || t.targetId === targetInfo.targetId
|
|
653
872
|
);
|
|
873
|
+
let newTabId;
|
|
654
874
|
if (!alreadyTracked) {
|
|
875
|
+
newTabId = `tab-${nextTabSeq++}`;
|
|
655
876
|
activeSlot.tabs.push({
|
|
656
|
-
tabId:
|
|
877
|
+
tabId: newTabId,
|
|
657
878
|
targetId: String(targetInfo.targetId ?? ""),
|
|
658
879
|
sessionId: childSid
|
|
659
880
|
});
|
|
@@ -665,10 +886,19 @@ function makeLightweightCdpDriver(options) {
|
|
|
665
886
|
cdpChannel.sendCommand("Runtime.enable", {}, childSid).catch(() => {
|
|
666
887
|
})
|
|
667
888
|
];
|
|
668
|
-
if (activeResponseWatchers > 0) {
|
|
889
|
+
if (activeResponseWatchers > 0 || requestListeners.size > 0) {
|
|
669
890
|
setupCalls.push(cdpChannel.sendCommand("Network.enable", {}, childSid).catch(() => {
|
|
670
891
|
}));
|
|
671
892
|
}
|
|
893
|
+
if (currentNetworkConditions) {
|
|
894
|
+
setupCalls.push(applyNetworkConditionsToSession(childSid, currentNetworkConditions));
|
|
895
|
+
}
|
|
896
|
+
if (fetchInterceptEnabled) {
|
|
897
|
+
setupCalls.push(
|
|
898
|
+
cdpChannel.sendCommand("Fetch.enable", { patterns: [{ urlPattern: "*" }] }, childSid).catch(() => {
|
|
899
|
+
})
|
|
900
|
+
);
|
|
901
|
+
}
|
|
672
902
|
if (useInjectedRuntime) {
|
|
673
903
|
setupCalls.push(
|
|
674
904
|
cdpChannel.sendCommand(
|
|
@@ -679,11 +909,25 @@ function makeLightweightCdpDriver(options) {
|
|
|
679
909
|
})
|
|
680
910
|
);
|
|
681
911
|
}
|
|
912
|
+
for (const scriptSource of initScripts) {
|
|
913
|
+
setupCalls.push(
|
|
914
|
+
cdpChannel.sendCommand(
|
|
915
|
+
"Page.addScriptToEvaluateOnNewDocument",
|
|
916
|
+
{ source: scriptSource },
|
|
917
|
+
childSid
|
|
918
|
+
).catch(() => {
|
|
919
|
+
})
|
|
920
|
+
);
|
|
921
|
+
}
|
|
682
922
|
await Promise.all(setupCalls);
|
|
683
923
|
if (waiting) {
|
|
684
924
|
await cdpChannel.sendCommand("Runtime.runIfWaitingForDebugger", {}, childSid).catch(() => {
|
|
685
925
|
});
|
|
686
926
|
}
|
|
927
|
+
if (newTabId && popupWaiters.length > 0) {
|
|
928
|
+
const waiter = popupWaiters.shift();
|
|
929
|
+
if (waiter) waiter.resolve(newTabId);
|
|
930
|
+
}
|
|
687
931
|
})();
|
|
688
932
|
} else if (waiting && typeof childSid === "string") {
|
|
689
933
|
void cdpChannel.sendCommand("Runtime.runIfWaitingForDebugger", {}, childSid).catch(() => {
|
|
@@ -699,8 +943,51 @@ function makeLightweightCdpDriver(options) {
|
|
|
699
943
|
}
|
|
700
944
|
});
|
|
701
945
|
cdpChannel.onEvent("Page.javascriptDialogOpening", (params, sid) => {
|
|
702
|
-
const
|
|
703
|
-
|
|
946
|
+
const targetSid = sid ?? null;
|
|
947
|
+
const dialogType = String(params?.type ?? "alert");
|
|
948
|
+
const message = String(params?.message ?? "");
|
|
949
|
+
const defaultValue = String(params?.defaultPrompt ?? "");
|
|
950
|
+
const activeHandler = dialogHandler;
|
|
951
|
+
if (!activeHandler) {
|
|
952
|
+
const accept = dialogType === "beforeunload";
|
|
953
|
+
void cdpChannel.sendCommand("Page.handleJavaScriptDialog", { accept }, targetSid).catch(() => {
|
|
954
|
+
});
|
|
955
|
+
return;
|
|
956
|
+
}
|
|
957
|
+
let handled = false;
|
|
958
|
+
const info = {
|
|
959
|
+
type: dialogType,
|
|
960
|
+
message,
|
|
961
|
+
defaultValue,
|
|
962
|
+
accept: async (promptText) => {
|
|
963
|
+
if (handled) return;
|
|
964
|
+
handled = true;
|
|
965
|
+
await cdpChannel.sendCommand(
|
|
966
|
+
"Page.handleJavaScriptDialog",
|
|
967
|
+
{
|
|
968
|
+
accept: true,
|
|
969
|
+
...promptText !== void 0 ? { promptText } : {}
|
|
970
|
+
},
|
|
971
|
+
targetSid
|
|
972
|
+
);
|
|
973
|
+
},
|
|
974
|
+
dismiss: async () => {
|
|
975
|
+
if (handled) return;
|
|
976
|
+
handled = true;
|
|
977
|
+
await cdpChannel.sendCommand("Page.handleJavaScriptDialog", { accept: false }, targetSid);
|
|
978
|
+
}
|
|
979
|
+
};
|
|
980
|
+
void Promise.resolve(activeHandler(info)).catch(() => {
|
|
981
|
+
}).finally(() => {
|
|
982
|
+
if (!handled) {
|
|
983
|
+
handled = true;
|
|
984
|
+
void cdpChannel.sendCommand(
|
|
985
|
+
"Page.handleJavaScriptDialog",
|
|
986
|
+
{ accept: dialogType === "beforeunload" },
|
|
987
|
+
targetSid
|
|
988
|
+
).catch(() => {
|
|
989
|
+
});
|
|
990
|
+
}
|
|
704
991
|
});
|
|
705
992
|
});
|
|
706
993
|
cdpChannel.setFrameOffsetResolver(async (child) => {
|
|
@@ -733,9 +1020,91 @@ function makeLightweightCdpDriver(options) {
|
|
|
733
1020
|
message: detail?.exception?.description ?? detail?.text ?? "Uncaught exception"
|
|
734
1021
|
});
|
|
735
1022
|
});
|
|
1023
|
+
const recordNavUrl = (url, sid) => {
|
|
1024
|
+
if (activeSlot && sid && sid !== activeSlot.sessionId) return;
|
|
1025
|
+
if (typeof url === "string" && url.length > 0) {
|
|
1026
|
+
navigationUrls.push(url);
|
|
1027
|
+
if (navigationUrls.length > 50) navigationUrls.shift();
|
|
1028
|
+
}
|
|
1029
|
+
};
|
|
1030
|
+
cdpChannel.onEvent("Page.frameNavigated", (params, sid) => {
|
|
1031
|
+
if (!params?.frame?.parentId) {
|
|
1032
|
+
recordNavUrl(params?.frame?.url, sid);
|
|
1033
|
+
}
|
|
1034
|
+
});
|
|
1035
|
+
cdpChannel.onEvent("Page.navigatedWithinDocument", (params, sid) => {
|
|
1036
|
+
recordNavUrl(params?.url, sid);
|
|
1037
|
+
});
|
|
1038
|
+
cdpChannel.onEvent("Runtime.bindingCalled", (params, sid) => {
|
|
1039
|
+
const payloadRaw = params?.payload;
|
|
1040
|
+
if (typeof payloadRaw !== "string") return;
|
|
1041
|
+
let parsed;
|
|
1042
|
+
try {
|
|
1043
|
+
parsed = JSON.parse(payloadRaw);
|
|
1044
|
+
} catch {
|
|
1045
|
+
return;
|
|
1046
|
+
}
|
|
1047
|
+
if (!parsed.id || !parsed.name) return;
|
|
1048
|
+
const fn = exposedFunctions.get(parsed.name);
|
|
1049
|
+
if (!fn) return;
|
|
1050
|
+
void (async () => {
|
|
1051
|
+
try {
|
|
1052
|
+
const val = await fn(...parsed.args ?? []);
|
|
1053
|
+
const serialized = val === void 0 ? "undefined" : JSON.stringify(val);
|
|
1054
|
+
await cdpChannel.evaluateOnSession(
|
|
1055
|
+
sid ?? activeSlot?.sessionId ?? null,
|
|
1056
|
+
`(() => { const p = window.__spanaBindPending?.[${JSON.stringify(parsed.id)}]; if (p) { delete window.__spanaBindPending[${JSON.stringify(parsed.id)}]; p.resolve(${serialized}); } })()`
|
|
1057
|
+
);
|
|
1058
|
+
} catch (err) {
|
|
1059
|
+
const errMsg = err instanceof Error ? err.message : String(err);
|
|
1060
|
+
await cdpChannel.evaluateOnSession(
|
|
1061
|
+
sid ?? activeSlot?.sessionId ?? null,
|
|
1062
|
+
`(() => { const p = window.__spanaBindPending?.[${JSON.stringify(parsed.id)}]; if (p) { delete window.__spanaBindPending[${JSON.stringify(parsed.id)}]; p.reject(new Error(${JSON.stringify(errMsg)})); } })()`
|
|
1063
|
+
).catch(() => {
|
|
1064
|
+
});
|
|
1065
|
+
}
|
|
1066
|
+
})();
|
|
1067
|
+
});
|
|
1068
|
+
cdpChannel.onEvent("Network.requestWillBeSent", (params, sid) => {
|
|
1069
|
+
if (requestListeners.size === 0) return;
|
|
1070
|
+
if (activeSlot && sid && !activeSlot.tabs.some((t) => t.sessionId === sid) && sid !== activeSlot.sessionId) {
|
|
1071
|
+
return;
|
|
1072
|
+
}
|
|
1073
|
+
const req = params?.request;
|
|
1074
|
+
if (!req?.url) return;
|
|
1075
|
+
const rawHeaders = req.headers ?? {};
|
|
1076
|
+
const headers = {};
|
|
1077
|
+
for (const [k, v] of Object.entries(rawHeaders)) {
|
|
1078
|
+
headers[k.toLowerCase()] = String(v);
|
|
1079
|
+
}
|
|
1080
|
+
const postDataStr = typeof req.postData === "string" ? req.postData : null;
|
|
1081
|
+
const info = {
|
|
1082
|
+
url: String(req.url),
|
|
1083
|
+
method: String(req.method ?? "GET"),
|
|
1084
|
+
headers,
|
|
1085
|
+
resourceType: typeof params?.type === "string" ? params.type.toLowerCase() : void 0,
|
|
1086
|
+
postData: () => postDataStr,
|
|
1087
|
+
postDataJSON: () => {
|
|
1088
|
+
if (!postDataStr) return null;
|
|
1089
|
+
try {
|
|
1090
|
+
return JSON.parse(postDataStr);
|
|
1091
|
+
} catch {
|
|
1092
|
+
return null;
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
};
|
|
1096
|
+
for (const listener of requestListeners) {
|
|
1097
|
+
try {
|
|
1098
|
+
listener(info);
|
|
1099
|
+
} catch {
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
});
|
|
736
1103
|
cdpChannel.onEvent("Fetch.requestPaused", (params, sid) => {
|
|
1104
|
+
if (!fetchInterceptEnabled) return;
|
|
737
1105
|
const reqId = params?.requestId;
|
|
738
|
-
const
|
|
1106
|
+
const reqObj = params?.request ?? {};
|
|
1107
|
+
const url = String(reqObj.url ?? "");
|
|
739
1108
|
if (!reqId) return;
|
|
740
1109
|
const rule = routeRules.find((r) => matchUrl(r.matcher, url));
|
|
741
1110
|
if (!rule) {
|
|
@@ -743,6 +1112,124 @@ function makeLightweightCdpDriver(options) {
|
|
|
743
1112
|
});
|
|
744
1113
|
return;
|
|
745
1114
|
}
|
|
1115
|
+
const fulfillWith = async (resp) => {
|
|
1116
|
+
const bodyStr = resp.json !== void 0 ? JSON.stringify(resp.json) : resp.body ?? "";
|
|
1117
|
+
const headersObj = { ...resp.headers };
|
|
1118
|
+
if (resp.contentType && !Object.keys(headersObj).some((k) => k.toLowerCase() === "content-type")) {
|
|
1119
|
+
headersObj["content-type"] = resp.contentType;
|
|
1120
|
+
} else if (resp.json !== void 0 && !Object.keys(headersObj).some((k) => k.toLowerCase() === "content-type")) {
|
|
1121
|
+
headersObj["content-type"] = "application/json";
|
|
1122
|
+
}
|
|
1123
|
+
const responseHeaders = Object.entries(headersObj).map(([name, value]) => ({
|
|
1124
|
+
name,
|
|
1125
|
+
value
|
|
1126
|
+
}));
|
|
1127
|
+
await cdpChannel.sendCommand(
|
|
1128
|
+
"Fetch.fulfillRequest",
|
|
1129
|
+
{
|
|
1130
|
+
requestId: reqId,
|
|
1131
|
+
responseCode: resp.status ?? 200,
|
|
1132
|
+
responseHeaders,
|
|
1133
|
+
body: Buffer.from(bodyStr, "utf8").toString("base64")
|
|
1134
|
+
},
|
|
1135
|
+
sid ?? null
|
|
1136
|
+
);
|
|
1137
|
+
};
|
|
1138
|
+
if (rule.kind === "handler" && rule.handler) {
|
|
1139
|
+
const rawHeaders = reqObj.headers ?? {};
|
|
1140
|
+
const headers = {};
|
|
1141
|
+
for (const [k, v] of Object.entries(rawHeaders)) {
|
|
1142
|
+
headers[k.toLowerCase()] = String(v);
|
|
1143
|
+
}
|
|
1144
|
+
const postDataStr = typeof reqObj.postData === "string" ? reqObj.postData : null;
|
|
1145
|
+
const reqInfo = {
|
|
1146
|
+
url,
|
|
1147
|
+
method: String(reqObj.method ?? "GET"),
|
|
1148
|
+
headers,
|
|
1149
|
+
resourceType: typeof params?.resourceType === "string" ? params.resourceType.toLowerCase() : void 0,
|
|
1150
|
+
postData: () => postDataStr,
|
|
1151
|
+
postDataJSON: () => {
|
|
1152
|
+
if (!postDataStr) return null;
|
|
1153
|
+
try {
|
|
1154
|
+
return JSON.parse(postDataStr);
|
|
1155
|
+
} catch {
|
|
1156
|
+
return null;
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
};
|
|
1160
|
+
let handled = false;
|
|
1161
|
+
const routeObj = {
|
|
1162
|
+
request: () => reqInfo,
|
|
1163
|
+
continue: async (overrides) => {
|
|
1164
|
+
if (handled) return;
|
|
1165
|
+
handled = true;
|
|
1166
|
+
await cdpChannel.sendCommand(
|
|
1167
|
+
"Fetch.continueRequest",
|
|
1168
|
+
{
|
|
1169
|
+
requestId: reqId,
|
|
1170
|
+
...overrides?.url ? { url: overrides.url } : {},
|
|
1171
|
+
...overrides?.method ? { method: overrides.method } : {},
|
|
1172
|
+
...overrides?.headers ? {
|
|
1173
|
+
headers: Object.entries(overrides.headers).map(([name, value]) => ({
|
|
1174
|
+
name,
|
|
1175
|
+
value
|
|
1176
|
+
}))
|
|
1177
|
+
} : {},
|
|
1178
|
+
...overrides?.postData !== void 0 ? { postData: Buffer.from(overrides.postData, "utf8").toString("base64") } : {}
|
|
1179
|
+
},
|
|
1180
|
+
sid ?? null
|
|
1181
|
+
);
|
|
1182
|
+
},
|
|
1183
|
+
abort: async (errorCode) => {
|
|
1184
|
+
if (handled) return;
|
|
1185
|
+
handled = true;
|
|
1186
|
+
await cdpChannel.sendCommand(
|
|
1187
|
+
"Fetch.failRequest",
|
|
1188
|
+
{ requestId: reqId, errorReason: errorCode ?? "Failed" },
|
|
1189
|
+
sid ?? null
|
|
1190
|
+
);
|
|
1191
|
+
},
|
|
1192
|
+
fulfill: async (response) => {
|
|
1193
|
+
if (handled) return;
|
|
1194
|
+
handled = true;
|
|
1195
|
+
await fulfillWith(response);
|
|
1196
|
+
},
|
|
1197
|
+
fetch: async (overrides) => {
|
|
1198
|
+
const targetUrl = overrides?.url ?? url;
|
|
1199
|
+
const fetchHeaders = { ...headers, ...overrides?.headers };
|
|
1200
|
+
const fetchMethod = overrides?.method ?? reqInfo.method;
|
|
1201
|
+
const body = overrides?.postData !== void 0 ? overrides.postData : fetchMethod !== "GET" && fetchMethod !== "HEAD" ? postDataStr ?? void 0 : void 0;
|
|
1202
|
+
const res = await fetch(targetUrl, {
|
|
1203
|
+
method: fetchMethod,
|
|
1204
|
+
headers: fetchHeaders,
|
|
1205
|
+
...body !== void 0 ? { body } : {}
|
|
1206
|
+
});
|
|
1207
|
+
const resText = await res.text();
|
|
1208
|
+
const outHeaders = {};
|
|
1209
|
+
res.headers.forEach((v, k) => {
|
|
1210
|
+
outHeaders[k.toLowerCase()] = v;
|
|
1211
|
+
});
|
|
1212
|
+
return {
|
|
1213
|
+
url: res.url || targetUrl,
|
|
1214
|
+
status: res.status,
|
|
1215
|
+
statusText: res.statusText,
|
|
1216
|
+
headers: outHeaders,
|
|
1217
|
+
method: fetchMethod,
|
|
1218
|
+
body: async () => resText,
|
|
1219
|
+
json: async () => JSON.parse(resText)
|
|
1220
|
+
};
|
|
1221
|
+
}
|
|
1222
|
+
};
|
|
1223
|
+
void Promise.resolve(rule.handler(routeObj)).catch(() => {
|
|
1224
|
+
}).finally(() => {
|
|
1225
|
+
if (!handled) {
|
|
1226
|
+
handled = true;
|
|
1227
|
+
void cdpChannel.sendCommand("Fetch.continueRequest", { requestId: reqId }, sid ?? null).catch(() => {
|
|
1228
|
+
});
|
|
1229
|
+
}
|
|
1230
|
+
});
|
|
1231
|
+
return;
|
|
1232
|
+
}
|
|
746
1233
|
if (rule.kind === "block") {
|
|
747
1234
|
void cdpChannel.sendCommand(
|
|
748
1235
|
"Fetch.failRequest",
|
|
@@ -752,29 +1239,11 @@ function makeLightweightCdpDriver(options) {
|
|
|
752
1239
|
});
|
|
753
1240
|
return;
|
|
754
1241
|
}
|
|
755
|
-
|
|
756
|
-
const bodyStr = resp.json !== void 0 ? JSON.stringify(resp.json) : resp.body ?? "";
|
|
757
|
-
const headersObj = { ...resp.headers };
|
|
758
|
-
if (resp.contentType && !Object.keys(headersObj).some((k) => k.toLowerCase() === "content-type")) {
|
|
759
|
-
headersObj["content-type"] = resp.contentType;
|
|
760
|
-
} else if (resp.json !== void 0 && !Object.keys(headersObj).some((k) => k.toLowerCase() === "content-type")) {
|
|
761
|
-
headersObj["content-type"] = "application/json";
|
|
762
|
-
}
|
|
763
|
-
const responseHeaders = Object.entries(headersObj).map(([name, value]) => ({ name, value }));
|
|
764
|
-
void cdpChannel.sendCommand(
|
|
765
|
-
"Fetch.fulfillRequest",
|
|
766
|
-
{
|
|
767
|
-
requestId: reqId,
|
|
768
|
-
responseCode: resp.status ?? 200,
|
|
769
|
-
responseHeaders,
|
|
770
|
-
body: Buffer.from(bodyStr, "utf8").toString("base64")
|
|
771
|
-
},
|
|
772
|
-
sid ?? null
|
|
773
|
-
).catch(() => {
|
|
1242
|
+
void fulfillWith(rule.response ?? {}).catch(() => {
|
|
774
1243
|
});
|
|
775
1244
|
});
|
|
776
1245
|
if (useContexts) {
|
|
777
|
-
yield*
|
|
1246
|
+
yield* Effect.tryPromise({
|
|
778
1247
|
try: () => cdpChannel.sendCommand(
|
|
779
1248
|
"Target.setAutoAttach",
|
|
780
1249
|
{
|
|
@@ -787,8 +1256,8 @@ function makeLightweightCdpDriver(options) {
|
|
|
787
1256
|
).catch(() => {
|
|
788
1257
|
}),
|
|
789
1258
|
catch: () => new DriverError({ message: "Failed to enable Target.setAutoAttach" })
|
|
790
|
-
}).pipe(
|
|
791
|
-
activeSlot = yield*
|
|
1259
|
+
}).pipe(Effect.catch(() => Effect.void));
|
|
1260
|
+
activeSlot = yield* Effect.tryPromise({
|
|
792
1261
|
try: () => createContextSlot(options.storageState),
|
|
793
1262
|
catch: (e) => new DriverError({ message: `Failed to create direct CDP browser context: ${e}` })
|
|
794
1263
|
});
|
|
@@ -829,7 +1298,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
829
1298
|
let coverageSession;
|
|
830
1299
|
const service = {
|
|
831
1300
|
domChannel: cdpChannel,
|
|
832
|
-
startJSCoverage: () =>
|
|
1301
|
+
startJSCoverage: () => Effect.tryPromise({
|
|
833
1302
|
try: async () => {
|
|
834
1303
|
const session = activeSlot?.sessionId ?? null;
|
|
835
1304
|
await cdpChannel.sendCommand("Profiler.enable", {}, session);
|
|
@@ -848,7 +1317,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
848
1317
|
},
|
|
849
1318
|
catch: (error) => new DriverError({ message: `CDP JavaScript coverage is unavailable: ${error}` })
|
|
850
1319
|
}),
|
|
851
|
-
stopJSCoverage: () =>
|
|
1320
|
+
stopJSCoverage: () => Effect.tryPromise({
|
|
852
1321
|
try: async () => {
|
|
853
1322
|
const session = coverageSession;
|
|
854
1323
|
coverageSession = void 0;
|
|
@@ -869,10 +1338,12 @@ function makeLightweightCdpDriver(options) {
|
|
|
869
1338
|
},
|
|
870
1339
|
catch: (error) => new DriverError({ message: `CDP JavaScript coverage collection failed: ${error}` })
|
|
871
1340
|
}),
|
|
872
|
-
beginFlow: (_flowName) =>
|
|
1341
|
+
beginFlow: (_flowName) => Effect.tryPromise({
|
|
873
1342
|
try: async () => {
|
|
874
1343
|
consoleLogs.length = 0;
|
|
875
1344
|
jsErrors.length = 0;
|
|
1345
|
+
navigationUrls.length = 0;
|
|
1346
|
+
dialogHandler = null;
|
|
876
1347
|
cdpChannel.clearChildSessions();
|
|
877
1348
|
if (useContexts && options.freshContextPerFlow && hasRunFirstFlow) {
|
|
878
1349
|
if (options.contextIsolation === "hot-cache" && activeSlot) {
|
|
@@ -901,30 +1372,54 @@ function makeLightweightCdpDriver(options) {
|
|
|
901
1372
|
await cdpChannel.sendCommand("Network.setCookies", { cookies: state.cookies }).catch(() => {
|
|
902
1373
|
});
|
|
903
1374
|
}
|
|
1375
|
+
if (options.virtualAuthenticator && !activeSlot.authenticatorId) {
|
|
1376
|
+
const authOpts = typeof options.virtualAuthenticator === "object" ? options.virtualAuthenticator : void 0;
|
|
1377
|
+
activeSlot.authenticatorId = await attachVirtualAuthenticatorForSession(
|
|
1378
|
+
activeSlot.sessionId,
|
|
1379
|
+
authOpts
|
|
1380
|
+
).catch(() => void 0);
|
|
1381
|
+
}
|
|
1382
|
+
activeAuthenticatorId = activeSlot.authenticatorId;
|
|
904
1383
|
} else {
|
|
905
1384
|
const previousSlot = activeSlot;
|
|
906
1385
|
const pending = prefetchedSlotPromise;
|
|
907
1386
|
prefetchedSlotPromise = void 0;
|
|
908
1387
|
activeSlot = pending ? await pending : await createContextSlot(options.storageState);
|
|
909
1388
|
cdpChannel.setSessionId(activeSlot.sessionId);
|
|
1389
|
+
if (options.virtualAuthenticator && !activeSlot.authenticatorId) {
|
|
1390
|
+
const authOpts = typeof options.virtualAuthenticator === "object" ? options.virtualAuthenticator : void 0;
|
|
1391
|
+
activeSlot.authenticatorId = await attachVirtualAuthenticatorForSession(
|
|
1392
|
+
activeSlot.sessionId,
|
|
1393
|
+
authOpts
|
|
1394
|
+
).catch(() => void 0);
|
|
1395
|
+
}
|
|
910
1396
|
activeAuthenticatorId = activeSlot.authenticatorId;
|
|
911
1397
|
if (previousSlot) {
|
|
912
1398
|
disposeSlotInBackground(previousSlot);
|
|
913
1399
|
}
|
|
914
1400
|
}
|
|
1401
|
+
} else if (activeSlot) {
|
|
1402
|
+
if (options.virtualAuthenticator && !activeSlot.authenticatorId) {
|
|
1403
|
+
const authOpts = typeof options.virtualAuthenticator === "object" ? options.virtualAuthenticator : void 0;
|
|
1404
|
+
activeSlot.authenticatorId = await attachVirtualAuthenticatorForSession(
|
|
1405
|
+
activeSlot.sessionId,
|
|
1406
|
+
authOpts
|
|
1407
|
+
).catch(() => void 0);
|
|
1408
|
+
}
|
|
1409
|
+
activeAuthenticatorId = activeSlot.authenticatorId;
|
|
915
1410
|
}
|
|
916
1411
|
hasRunFirstFlow = true;
|
|
917
1412
|
},
|
|
918
1413
|
catch: (e) => new DriverError({ message: `CDP beginFlow failed: ${e}` })
|
|
919
1414
|
}),
|
|
920
|
-
dumpHierarchy: () =>
|
|
1415
|
+
dumpHierarchy: () => Effect.tryPromise({
|
|
921
1416
|
try: async () => {
|
|
922
1417
|
const raw = await cdpChannel.evaluate(CDP_DUMP_HIERARCHY_SCRIPT);
|
|
923
1418
|
return raw ?? "{}";
|
|
924
1419
|
},
|
|
925
1420
|
catch: (e) => new DriverError({ message: `CDP dumpHierarchy failed: ${e}` })
|
|
926
1421
|
}),
|
|
927
|
-
tapAtCoordinate: (x, y) =>
|
|
1422
|
+
tapAtCoordinate: (x, y) => Effect.tryPromise({
|
|
928
1423
|
try: async () => {
|
|
929
1424
|
await Promise.all([
|
|
930
1425
|
cdpChannel.sendCommand("Input.dispatchMouseEvent", {
|
|
@@ -950,7 +1445,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
950
1445
|
},
|
|
951
1446
|
catch: (e) => new DriverError({ message: `CDP tap failed at (${x}, ${y}): ${e}` })
|
|
952
1447
|
}),
|
|
953
|
-
doubleTapAtCoordinate: (x, y) =>
|
|
1448
|
+
doubleTapAtCoordinate: (x, y) => Effect.tryPromise({
|
|
954
1449
|
try: async () => {
|
|
955
1450
|
await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
|
|
956
1451
|
type: "mousePressed",
|
|
@@ -969,7 +1464,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
969
1464
|
},
|
|
970
1465
|
catch: (e) => new DriverError({ message: `CDP doubleTap failed: ${e}` })
|
|
971
1466
|
}),
|
|
972
|
-
longPressAtCoordinate: (x, y, duration) =>
|
|
1467
|
+
longPressAtCoordinate: (x, y, duration) => Effect.tryPromise({
|
|
973
1468
|
try: async () => {
|
|
974
1469
|
await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
|
|
975
1470
|
type: "mousePressed",
|
|
@@ -989,7 +1484,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
989
1484
|
},
|
|
990
1485
|
catch: (e) => new DriverError({ message: `CDP longPress failed: ${e}` })
|
|
991
1486
|
}),
|
|
992
|
-
swipe: (startX, startY, endX, endY) =>
|
|
1487
|
+
swipe: (startX, startY, endX, endY) => Effect.tryPromise({
|
|
993
1488
|
try: async () => {
|
|
994
1489
|
const dx = startX - endX;
|
|
995
1490
|
const dy = startY - endY;
|
|
@@ -997,13 +1492,47 @@ function makeLightweightCdpDriver(options) {
|
|
|
997
1492
|
},
|
|
998
1493
|
catch: (e) => new DriverError({ message: `CDP swipe failed: ${e}` })
|
|
999
1494
|
}),
|
|
1000
|
-
inputText: (text) =>
|
|
1495
|
+
inputText: (text) => Effect.tryPromise({
|
|
1001
1496
|
try: async () => {
|
|
1002
1497
|
await cdpChannel.sendCommand("Input.insertText", { text });
|
|
1003
1498
|
},
|
|
1004
1499
|
catch: (e) => new DriverError({ message: `CDP inputText failed: ${e}` })
|
|
1005
1500
|
}),
|
|
1006
|
-
|
|
1501
|
+
typeText: (text, opts) => Effect.tryPromise({
|
|
1502
|
+
try: async () => {
|
|
1503
|
+
const delay = opts?.delay ?? 0;
|
|
1504
|
+
for (const ch of Array.from(text)) {
|
|
1505
|
+
const desc = parseCdpKeyDescriptor(ch);
|
|
1506
|
+
await cdpChannel.sendCommand("Input.dispatchKeyEvent", {
|
|
1507
|
+
type: "keyDown",
|
|
1508
|
+
key: desc.key,
|
|
1509
|
+
...desc.code ? { code: desc.code } : {},
|
|
1510
|
+
...desc.windowsVirtualKeyCode ? {
|
|
1511
|
+
windowsVirtualKeyCode: desc.windowsVirtualKeyCode,
|
|
1512
|
+
nativeVirtualKeyCode: desc.windowsVirtualKeyCode
|
|
1513
|
+
} : {},
|
|
1514
|
+
modifiers: desc.modifiers,
|
|
1515
|
+
text: ch,
|
|
1516
|
+
unmodifiedText: ch
|
|
1517
|
+
});
|
|
1518
|
+
await cdpChannel.sendCommand("Input.dispatchKeyEvent", {
|
|
1519
|
+
type: "keyUp",
|
|
1520
|
+
key: desc.key,
|
|
1521
|
+
...desc.code ? { code: desc.code } : {},
|
|
1522
|
+
...desc.windowsVirtualKeyCode ? {
|
|
1523
|
+
windowsVirtualKeyCode: desc.windowsVirtualKeyCode,
|
|
1524
|
+
nativeVirtualKeyCode: desc.windowsVirtualKeyCode
|
|
1525
|
+
} : {},
|
|
1526
|
+
modifiers: desc.modifiers
|
|
1527
|
+
});
|
|
1528
|
+
if (delay > 0) {
|
|
1529
|
+
await new Promise((r) => setTimeout(r, delay));
|
|
1530
|
+
}
|
|
1531
|
+
}
|
|
1532
|
+
},
|
|
1533
|
+
catch: (e) => new DriverError({ message: `CDP typeText failed: ${e}` })
|
|
1534
|
+
}),
|
|
1535
|
+
pressKey: (key) => Effect.tryPromise({
|
|
1007
1536
|
try: async () => {
|
|
1008
1537
|
const desc = parseCdpKeyDescriptor(key);
|
|
1009
1538
|
await cdpChannel.sendCommand("Input.dispatchKeyEvent", {
|
|
@@ -1031,7 +1560,73 @@ function makeLightweightCdpDriver(options) {
|
|
|
1031
1560
|
},
|
|
1032
1561
|
catch: (e) => new DriverError({ message: `CDP pressKey failed: ${e}` })
|
|
1033
1562
|
}),
|
|
1034
|
-
|
|
1563
|
+
keyDown: (key) => Effect.tryPromise({
|
|
1564
|
+
try: async () => {
|
|
1565
|
+
const desc = parseCdpKeyDescriptor(key);
|
|
1566
|
+
await cdpChannel.sendCommand("Input.dispatchKeyEvent", {
|
|
1567
|
+
type: desc.text ? "keyDown" : "rawKeyDown",
|
|
1568
|
+
key: desc.key,
|
|
1569
|
+
...desc.code ? { code: desc.code } : {},
|
|
1570
|
+
...desc.windowsVirtualKeyCode ? {
|
|
1571
|
+
windowsVirtualKeyCode: desc.windowsVirtualKeyCode,
|
|
1572
|
+
nativeVirtualKeyCode: desc.windowsVirtualKeyCode
|
|
1573
|
+
} : {},
|
|
1574
|
+
modifiers: desc.modifiers,
|
|
1575
|
+
...desc.text ? { text: desc.text, unmodifiedText: desc.text } : {}
|
|
1576
|
+
});
|
|
1577
|
+
},
|
|
1578
|
+
catch: (e) => new DriverError({ message: `CDP keyDown failed: ${e}` })
|
|
1579
|
+
}),
|
|
1580
|
+
keyUp: (key) => Effect.tryPromise({
|
|
1581
|
+
try: async () => {
|
|
1582
|
+
const desc = parseCdpKeyDescriptor(key);
|
|
1583
|
+
await cdpChannel.sendCommand("Input.dispatchKeyEvent", {
|
|
1584
|
+
type: "keyUp",
|
|
1585
|
+
key: desc.key,
|
|
1586
|
+
...desc.code ? { code: desc.code } : {},
|
|
1587
|
+
...desc.windowsVirtualKeyCode ? {
|
|
1588
|
+
windowsVirtualKeyCode: desc.windowsVirtualKeyCode,
|
|
1589
|
+
nativeVirtualKeyCode: desc.windowsVirtualKeyCode
|
|
1590
|
+
} : {},
|
|
1591
|
+
modifiers: desc.modifiers
|
|
1592
|
+
});
|
|
1593
|
+
},
|
|
1594
|
+
catch: (e) => new DriverError({ message: `CDP keyUp failed: ${e}` })
|
|
1595
|
+
}),
|
|
1596
|
+
mouseDown: (x, y, opts) => Effect.tryPromise({
|
|
1597
|
+
try: async () => {
|
|
1598
|
+
const button = opts?.button ?? "left";
|
|
1599
|
+
await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
|
|
1600
|
+
type: "mouseMoved",
|
|
1601
|
+
x,
|
|
1602
|
+
y
|
|
1603
|
+
});
|
|
1604
|
+
await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
|
|
1605
|
+
type: "mousePressed",
|
|
1606
|
+
x,
|
|
1607
|
+
y,
|
|
1608
|
+
button,
|
|
1609
|
+
buttons: button === "left" ? 1 : button === "right" ? 2 : 4,
|
|
1610
|
+
clickCount: 1
|
|
1611
|
+
});
|
|
1612
|
+
},
|
|
1613
|
+
catch: (e) => new DriverError({ message: `CDP mouseDown failed: ${e}` })
|
|
1614
|
+
}),
|
|
1615
|
+
mouseUp: (x, y, opts) => Effect.tryPromise({
|
|
1616
|
+
try: async () => {
|
|
1617
|
+
const button = opts?.button ?? "left";
|
|
1618
|
+
await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
|
|
1619
|
+
type: "mouseReleased",
|
|
1620
|
+
x,
|
|
1621
|
+
y,
|
|
1622
|
+
button,
|
|
1623
|
+
buttons: 0,
|
|
1624
|
+
clickCount: 1
|
|
1625
|
+
});
|
|
1626
|
+
},
|
|
1627
|
+
catch: (e) => new DriverError({ message: `CDP mouseUp failed: ${e}` })
|
|
1628
|
+
}),
|
|
1629
|
+
hoverAtCoordinate: (x, y) => Effect.tryPromise({
|
|
1035
1630
|
try: async () => {
|
|
1036
1631
|
await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
|
|
1037
1632
|
type: "mouseMoved",
|
|
@@ -1041,7 +1636,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
1041
1636
|
},
|
|
1042
1637
|
catch: (e) => new DriverError({ message: `CDP hover failed at (${x}, ${y}): ${e}` })
|
|
1043
1638
|
}),
|
|
1044
|
-
reload: (reloadOpts) =>
|
|
1639
|
+
reload: (reloadOpts) => Effect.tryPromise({
|
|
1045
1640
|
try: async () => {
|
|
1046
1641
|
const waitUntil = reloadOpts?.waitUntil ?? options.waitUntil ?? "domcontentloaded";
|
|
1047
1642
|
const targetSid = activeSlot?.sessionId;
|
|
@@ -1057,7 +1652,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
1057
1652
|
},
|
|
1058
1653
|
catch: (e) => new DriverError({ message: `CDP reload failed: ${e}` })
|
|
1059
1654
|
}),
|
|
1060
|
-
getUrl: () =>
|
|
1655
|
+
getUrl: () => Effect.tryPromise({
|
|
1061
1656
|
try: async () => {
|
|
1062
1657
|
const url = await cdpChannel.evaluate(
|
|
1063
1658
|
"typeof window !== 'undefined' && window.location ? String(window.location.href || '') : ''"
|
|
@@ -1066,8 +1661,98 @@ function makeLightweightCdpDriver(options) {
|
|
|
1066
1661
|
},
|
|
1067
1662
|
catch: (e) => new DriverError({ message: `CDP getUrl failed: ${e}` })
|
|
1068
1663
|
}),
|
|
1069
|
-
|
|
1070
|
-
|
|
1664
|
+
getNavigationUrls: () => [...navigationUrls],
|
|
1665
|
+
waitForLoadState: (state = "load", waitOpts) => Effect.tryPromise({
|
|
1666
|
+
try: async () => {
|
|
1667
|
+
const timeoutMs = waitOpts?.timeout ?? 15e3;
|
|
1668
|
+
const targetSid = activeSlot?.sessionId;
|
|
1669
|
+
if (state === "domcontentloaded") {
|
|
1670
|
+
const ready = await cdpChannel.evaluate("document.readyState").catch(() => "");
|
|
1671
|
+
if (ready === "interactive" || ready === "complete") return;
|
|
1672
|
+
await cdpChannel.waitForEvent(
|
|
1673
|
+
"Page.domContentEventFired",
|
|
1674
|
+
timeoutMs,
|
|
1675
|
+
(_p, sid) => !targetSid || !sid || sid === targetSid
|
|
1676
|
+
).catch(() => {
|
|
1677
|
+
});
|
|
1678
|
+
return;
|
|
1679
|
+
}
|
|
1680
|
+
if (state === "load") {
|
|
1681
|
+
const ready = await cdpChannel.evaluate("document.readyState").catch(() => "");
|
|
1682
|
+
if (ready === "complete") return;
|
|
1683
|
+
await cdpChannel.waitForEvent(
|
|
1684
|
+
"Page.loadEventFired",
|
|
1685
|
+
timeoutMs,
|
|
1686
|
+
(_p, sid) => !targetSid || !sid || sid === targetSid
|
|
1687
|
+
).catch(() => {
|
|
1688
|
+
});
|
|
1689
|
+
return;
|
|
1690
|
+
}
|
|
1691
|
+
await cdpChannel.sendCommand("Network.enable").catch(() => {
|
|
1692
|
+
});
|
|
1693
|
+
await new Promise((resolve2) => {
|
|
1694
|
+
let inflight = 0;
|
|
1695
|
+
let settled = false;
|
|
1696
|
+
let idleTimer;
|
|
1697
|
+
const finish = () => {
|
|
1698
|
+
if (settled) return;
|
|
1699
|
+
settled = true;
|
|
1700
|
+
clearTimeout(maxTimer);
|
|
1701
|
+
if (idleTimer) clearTimeout(idleTimer);
|
|
1702
|
+
offStart();
|
|
1703
|
+
offEnd();
|
|
1704
|
+
offFail();
|
|
1705
|
+
resolve2();
|
|
1706
|
+
};
|
|
1707
|
+
const armIdle = () => {
|
|
1708
|
+
if (idleTimer) clearTimeout(idleTimer);
|
|
1709
|
+
if (inflight <= 0) {
|
|
1710
|
+
idleTimer = setTimeout(finish, 500);
|
|
1711
|
+
}
|
|
1712
|
+
};
|
|
1713
|
+
const maxTimer = setTimeout(finish, timeoutMs);
|
|
1714
|
+
const offStart = cdpChannel.onEvent("Network.requestWillBeSent", (_p, sid) => {
|
|
1715
|
+
if (targetSid && sid && sid !== targetSid) return;
|
|
1716
|
+
inflight += 1;
|
|
1717
|
+
if (idleTimer) clearTimeout(idleTimer);
|
|
1718
|
+
});
|
|
1719
|
+
const onDone = (_p, sid) => {
|
|
1720
|
+
if (targetSid && sid && sid !== targetSid) return;
|
|
1721
|
+
inflight = Math.max(0, inflight - 1);
|
|
1722
|
+
armIdle();
|
|
1723
|
+
};
|
|
1724
|
+
const offEnd = cdpChannel.onEvent("Network.loadingFinished", onDone);
|
|
1725
|
+
const offFail = cdpChannel.onEvent("Network.loadingFailed", onDone);
|
|
1726
|
+
armIdle();
|
|
1727
|
+
});
|
|
1728
|
+
},
|
|
1729
|
+
catch: (e) => new DriverError({ message: `CDP waitForLoadState failed: ${e}` })
|
|
1730
|
+
}),
|
|
1731
|
+
waitForPopup: (triggerFn, waitOpts) => Effect.tryPromise({
|
|
1732
|
+
try: async () => {
|
|
1733
|
+
const timeoutMs = waitOpts?.timeout ?? 15e3;
|
|
1734
|
+
const popupPromise = new Promise((resolve2, reject) => {
|
|
1735
|
+
const timer = setTimeout(() => {
|
|
1736
|
+
reject(new Error(`Timed out waiting for popup after ${timeoutMs}ms`));
|
|
1737
|
+
}, timeoutMs);
|
|
1738
|
+
popupWaiters.push({
|
|
1739
|
+
resolve: (tabId) => {
|
|
1740
|
+
clearTimeout(timer);
|
|
1741
|
+
resolve2(tabId);
|
|
1742
|
+
},
|
|
1743
|
+
reject: (err) => {
|
|
1744
|
+
clearTimeout(timer);
|
|
1745
|
+
reject(err);
|
|
1746
|
+
}
|
|
1747
|
+
});
|
|
1748
|
+
});
|
|
1749
|
+
await triggerFn();
|
|
1750
|
+
return await popupPromise;
|
|
1751
|
+
},
|
|
1752
|
+
catch: (e) => new DriverError({ message: `CDP waitForPopup failed: ${e}` })
|
|
1753
|
+
}),
|
|
1754
|
+
hideKeyboard: () => Effect.void,
|
|
1755
|
+
takeScreenshot: () => Effect.tryPromise({
|
|
1071
1756
|
try: async () => {
|
|
1072
1757
|
const res = await cdpChannel.sendCommand("Page.captureScreenshot", {
|
|
1073
1758
|
format: "png"
|
|
@@ -1076,7 +1761,61 @@ function makeLightweightCdpDriver(options) {
|
|
|
1076
1761
|
},
|
|
1077
1762
|
catch: (e) => new DriverError({ message: `CDP screenshot failed: ${e}` })
|
|
1078
1763
|
}),
|
|
1079
|
-
|
|
1764
|
+
takeFullPageScreenshot: () => Effect.tryPromise({
|
|
1765
|
+
try: async () => {
|
|
1766
|
+
const res = await cdpChannel.sendCommand("Page.captureScreenshot", {
|
|
1767
|
+
format: "png",
|
|
1768
|
+
captureBeyondViewport: true,
|
|
1769
|
+
fromSurface: true
|
|
1770
|
+
});
|
|
1771
|
+
return new Uint8Array(Buffer.from(res?.data ?? "", "base64"));
|
|
1772
|
+
},
|
|
1773
|
+
catch: (e) => new DriverError({ message: `CDP fullPage screenshot failed: ${e}` })
|
|
1774
|
+
}),
|
|
1775
|
+
setGeolocation: (point) => Effect.tryPromise({
|
|
1776
|
+
try: async () => {
|
|
1777
|
+
await cdpChannel.sendCommand("Emulation.setGeolocationOverride", {
|
|
1778
|
+
latitude: point.latitude,
|
|
1779
|
+
longitude: point.longitude,
|
|
1780
|
+
accuracy: point.accuracy ?? 1
|
|
1781
|
+
});
|
|
1782
|
+
},
|
|
1783
|
+
catch: (e) => new DriverError({ message: `CDP setGeolocation failed: ${e}` })
|
|
1784
|
+
}),
|
|
1785
|
+
setPermission: (_appId, permission, state, permOpts) => Effect.tryPromise({
|
|
1786
|
+
try: async () => {
|
|
1787
|
+
const cdpName = permission === "clipboard-read" ? "clipboardReadWrite" : permission === "clipboard-write" ? "clipboardSanitizedWrite" : permission === "midi-sysex" ? "midi" : permission;
|
|
1788
|
+
const origin = permOpts?.origin;
|
|
1789
|
+
const ctxId = activeSlot?.browserContextId;
|
|
1790
|
+
if (state === "grant") {
|
|
1791
|
+
await cdpChannel.sendCommand(
|
|
1792
|
+
"Browser.grantPermissions",
|
|
1793
|
+
{
|
|
1794
|
+
permissions: [cdpName],
|
|
1795
|
+
...origin ? { origin } : {},
|
|
1796
|
+
...ctxId ? { browserContextId: ctxId } : {}
|
|
1797
|
+
},
|
|
1798
|
+
null
|
|
1799
|
+
);
|
|
1800
|
+
} else {
|
|
1801
|
+
await cdpChannel.sendCommand(
|
|
1802
|
+
"Browser.setPermission",
|
|
1803
|
+
{
|
|
1804
|
+
permission: {
|
|
1805
|
+
name: cdpName,
|
|
1806
|
+
...permission === "midi-sysex" ? { sysex: true } : {}
|
|
1807
|
+
},
|
|
1808
|
+
setting: "denied",
|
|
1809
|
+
...origin ? { origin } : {},
|
|
1810
|
+
...ctxId ? { browserContextId: ctxId } : {}
|
|
1811
|
+
},
|
|
1812
|
+
null
|
|
1813
|
+
);
|
|
1814
|
+
}
|
|
1815
|
+
},
|
|
1816
|
+
catch: (e) => new DriverError({ message: `CDP setPermission failed: ${e}` })
|
|
1817
|
+
}),
|
|
1818
|
+
getDeviceInfo: () => Effect.succeed({
|
|
1080
1819
|
platform: "web",
|
|
1081
1820
|
deviceId: `${label}:${options.cdpUrl}`,
|
|
1082
1821
|
name: `${label} (CDP-direct)`,
|
|
@@ -1085,7 +1824,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
1085
1824
|
screenHeight: height,
|
|
1086
1825
|
driverType: "cdp"
|
|
1087
1826
|
}),
|
|
1088
|
-
launchApp: (url, opts) =>
|
|
1827
|
+
launchApp: (url, opts) => Effect.tryPromise({
|
|
1089
1828
|
try: async () => {
|
|
1090
1829
|
if (opts?.clearState) {
|
|
1091
1830
|
await cdpChannel.sendCommand("Network.clearBrowserCookies").catch(() => {
|
|
@@ -1098,11 +1837,11 @@ function makeLightweightCdpDriver(options) {
|
|
|
1098
1837
|
},
|
|
1099
1838
|
catch: (e) => new DriverError({ message: `CDP launchApp failed: ${e}` })
|
|
1100
1839
|
}),
|
|
1101
|
-
stopApp: () =>
|
|
1840
|
+
stopApp: () => Effect.tryPromise({
|
|
1102
1841
|
try: () => navigate("about:blank"),
|
|
1103
1842
|
catch: (e) => new DriverError({ message: `CDP stopApp failed: ${e}` })
|
|
1104
1843
|
}),
|
|
1105
|
-
killApp: () =>
|
|
1844
|
+
killApp: () => Effect.tryPromise({
|
|
1106
1845
|
try: async () => {
|
|
1107
1846
|
const pendingPrefetch = prefetchedSlotPromise;
|
|
1108
1847
|
prefetchedSlotPromise = void 0;
|
|
@@ -1131,11 +1870,17 @@ function makeLightweightCdpDriver(options) {
|
|
|
1131
1870
|
}
|
|
1132
1871
|
downloadDir = void 0;
|
|
1133
1872
|
}
|
|
1873
|
+
for (const dir of uploadTempDirs.splice(0)) {
|
|
1874
|
+
try {
|
|
1875
|
+
rmSync(dir, { recursive: true, force: true });
|
|
1876
|
+
} catch {
|
|
1877
|
+
}
|
|
1878
|
+
}
|
|
1134
1879
|
await cdpChannel.disconnect();
|
|
1135
1880
|
},
|
|
1136
1881
|
catch: (e) => new DriverError({ message: `CDP disconnect failed: ${e}` })
|
|
1137
1882
|
}),
|
|
1138
|
-
clearAppState: () =>
|
|
1883
|
+
clearAppState: () => Effect.tryPromise({
|
|
1139
1884
|
try: async () => {
|
|
1140
1885
|
await cdpChannel.sendCommand("Network.clearBrowserCookies").catch(() => {
|
|
1141
1886
|
});
|
|
@@ -1145,26 +1890,104 @@ function makeLightweightCdpDriver(options) {
|
|
|
1145
1890
|
},
|
|
1146
1891
|
catch: (e) => new DriverError({ message: `CDP clearAppState failed: ${e}` })
|
|
1147
1892
|
}),
|
|
1148
|
-
openLink: (url) =>
|
|
1893
|
+
openLink: (url) => Effect.tryPromise({
|
|
1149
1894
|
try: () => navigate(url),
|
|
1150
1895
|
catch: (e) => new DriverError({ message: `CDP openLink failed: ${e}` })
|
|
1151
1896
|
}),
|
|
1152
|
-
back: () =>
|
|
1897
|
+
back: () => Effect.tryPromise({
|
|
1153
1898
|
try: async () => {
|
|
1899
|
+
const targetSid = activeSlot?.sessionId;
|
|
1900
|
+
const history = await cdpChannel.sendCommand("Page.getNavigationHistory", {}).catch(() => null);
|
|
1901
|
+
if (history?.entries && typeof history.currentIndex === "number") {
|
|
1902
|
+
const targetEntry = history.entries[history.currentIndex - 1];
|
|
1903
|
+
if (!targetEntry) return;
|
|
1904
|
+
const eventName = (options.waitUntil ?? "domcontentloaded") === "load" ? "Page.loadEventFired" : "Page.domContentEventFired";
|
|
1905
|
+
const waiter = Promise.race([
|
|
1906
|
+
cdpChannel.waitForEvent(
|
|
1907
|
+
eventName,
|
|
1908
|
+
1e4,
|
|
1909
|
+
(_p, sid) => !targetSid || !sid || sid === targetSid
|
|
1910
|
+
),
|
|
1911
|
+
cdpChannel.waitForEvent(
|
|
1912
|
+
"Page.navigatedWithinDocument",
|
|
1913
|
+
1e4,
|
|
1914
|
+
(_p, sid) => !targetSid || !sid || sid === targetSid
|
|
1915
|
+
)
|
|
1916
|
+
]);
|
|
1917
|
+
await cdpChannel.sendCommand("Page.navigateToHistoryEntry", {
|
|
1918
|
+
entryId: targetEntry.id
|
|
1919
|
+
});
|
|
1920
|
+
await waiter.catch(() => {
|
|
1921
|
+
});
|
|
1922
|
+
return;
|
|
1923
|
+
}
|
|
1154
1924
|
await cdpChannel.evaluate("window.history.back()");
|
|
1155
1925
|
},
|
|
1156
1926
|
catch: (e) => new DriverError({ message: `CDP back failed: ${e}` })
|
|
1157
1927
|
}),
|
|
1158
|
-
|
|
1928
|
+
forward: () => Effect.tryPromise({
|
|
1929
|
+
try: async () => {
|
|
1930
|
+
const targetSid = activeSlot?.sessionId;
|
|
1931
|
+
const history = await cdpChannel.sendCommand("Page.getNavigationHistory", {}).catch(() => null);
|
|
1932
|
+
if (history?.entries && typeof history.currentIndex === "number") {
|
|
1933
|
+
const targetEntry = history.entries[history.currentIndex + 1];
|
|
1934
|
+
if (!targetEntry) return;
|
|
1935
|
+
const eventName = (options.waitUntil ?? "domcontentloaded") === "load" ? "Page.loadEventFired" : "Page.domContentEventFired";
|
|
1936
|
+
const waiter = Promise.race([
|
|
1937
|
+
cdpChannel.waitForEvent(
|
|
1938
|
+
eventName,
|
|
1939
|
+
1e4,
|
|
1940
|
+
(_p, sid) => !targetSid || !sid || sid === targetSid
|
|
1941
|
+
),
|
|
1942
|
+
cdpChannel.waitForEvent(
|
|
1943
|
+
"Page.navigatedWithinDocument",
|
|
1944
|
+
1e4,
|
|
1945
|
+
(_p, sid) => !targetSid || !sid || sid === targetSid
|
|
1946
|
+
)
|
|
1947
|
+
]);
|
|
1948
|
+
await cdpChannel.sendCommand("Page.navigateToHistoryEntry", {
|
|
1949
|
+
entryId: targetEntry.id
|
|
1950
|
+
});
|
|
1951
|
+
await waiter.catch(() => {
|
|
1952
|
+
});
|
|
1953
|
+
return;
|
|
1954
|
+
}
|
|
1955
|
+
await cdpChannel.evaluate("window.history.forward()");
|
|
1956
|
+
},
|
|
1957
|
+
catch: (e) => new DriverError({ message: `CDP forward failed: ${e}` })
|
|
1958
|
+
}),
|
|
1959
|
+
evaluate: (fn, ...args) => Effect.tryPromise({
|
|
1159
1960
|
try: async () => {
|
|
1160
1961
|
if (typeof fn === "string") {
|
|
1161
1962
|
return await cdpChannel.evaluate(fn);
|
|
1162
1963
|
}
|
|
1163
|
-
const serializedArgs = args.map((a) => JSON.stringify(a)).join(", ");
|
|
1964
|
+
const serializedArgs = args.map((a) => a === void 0 ? "undefined" : JSON.stringify(a)).join(", ");
|
|
1164
1965
|
return await cdpChannel.evaluate(`(${fn.toString()})(${serializedArgs})`);
|
|
1165
1966
|
},
|
|
1166
1967
|
catch: (e) => new DriverError({ message: `CDP evaluate failed: ${e}` })
|
|
1167
1968
|
}),
|
|
1969
|
+
addInitScript: (script, ...args) => Effect.tryPromise({
|
|
1970
|
+
try: async () => {
|
|
1971
|
+
const source = typeof script === "string" ? script : `(${script.toString()})(${args.map((a) => a === void 0 ? "undefined" : JSON.stringify(a)).join(", ")});`;
|
|
1972
|
+
initScripts.push(source);
|
|
1973
|
+
const sessions = activeSlot ? activeSlot.tabs.map((t) => t.sessionId) : [null];
|
|
1974
|
+
await Promise.all(
|
|
1975
|
+
sessions.map(
|
|
1976
|
+
(sid) => cdpChannel.sendCommand("Page.addScriptToEvaluateOnNewDocument", { source }, sid).catch(() => {
|
|
1977
|
+
})
|
|
1978
|
+
)
|
|
1979
|
+
);
|
|
1980
|
+
},
|
|
1981
|
+
catch: (e) => new DriverError({ message: `CDP addInitScript failed: ${e}` })
|
|
1982
|
+
}),
|
|
1983
|
+
exposeFunction: (name, fn) => Effect.tryPromise({
|
|
1984
|
+
try: async () => {
|
|
1985
|
+
exposedFunctions.set(name, fn);
|
|
1986
|
+
const sessions = activeSlot ? activeSlot.tabs.map((t) => t.sessionId) : [null];
|
|
1987
|
+
await Promise.all(sessions.map((sid) => installExposeFunctionOnSession(sid, name)));
|
|
1988
|
+
},
|
|
1989
|
+
catch: (e) => new DriverError({ message: `CDP exposeFunction failed: ${e}` })
|
|
1990
|
+
}),
|
|
1168
1991
|
getRawPage: () => ({
|
|
1169
1992
|
kind: "cdp",
|
|
1170
1993
|
cdpChannel,
|
|
@@ -1184,21 +2007,28 @@ function makeLightweightCdpDriver(options) {
|
|
|
1184
2007
|
return activeSlot?.browserContextId;
|
|
1185
2008
|
}
|
|
1186
2009
|
}),
|
|
1187
|
-
|
|
2010
|
+
route: (matcher, handler) => Effect.tryPromise({
|
|
2011
|
+
try: async () => {
|
|
2012
|
+
routeRules.push({ kind: "handler", matcher, handler });
|
|
2013
|
+
await ensureFetchIntercept();
|
|
2014
|
+
},
|
|
2015
|
+
catch: (e) => new DriverError({ message: `CDP route failed: ${e}` })
|
|
2016
|
+
}),
|
|
2017
|
+
mockNetwork: (matcher, response) => Effect.tryPromise({
|
|
1188
2018
|
try: async () => {
|
|
1189
2019
|
routeRules.push({ kind: "mock", matcher, response });
|
|
1190
2020
|
await ensureFetchIntercept();
|
|
1191
2021
|
},
|
|
1192
2022
|
catch: (e) => new DriverError({ message: `CDP mockNetwork failed: ${e}` })
|
|
1193
2023
|
}),
|
|
1194
|
-
blockNetwork: (matcher) =>
|
|
2024
|
+
blockNetwork: (matcher) => Effect.tryPromise({
|
|
1195
2025
|
try: async () => {
|
|
1196
2026
|
routeRules.push({ kind: "block", matcher });
|
|
1197
2027
|
await ensureFetchIntercept();
|
|
1198
2028
|
},
|
|
1199
2029
|
catch: (e) => new DriverError({ message: `CDP blockNetwork failed: ${e}` })
|
|
1200
2030
|
}),
|
|
1201
|
-
clearNetworkMocks: () =>
|
|
2031
|
+
clearNetworkMocks: () => Effect.tryPromise({
|
|
1202
2032
|
try: async () => {
|
|
1203
2033
|
routeRules.length = 0;
|
|
1204
2034
|
if (fetchInterceptEnabled) {
|
|
@@ -1209,14 +2039,25 @@ function makeLightweightCdpDriver(options) {
|
|
|
1209
2039
|
},
|
|
1210
2040
|
catch: (e) => new DriverError({ message: `CDP clearNetworkMocks failed: ${e}` })
|
|
1211
2041
|
}),
|
|
1212
|
-
saveCookies: (path) =>
|
|
2042
|
+
saveCookies: (path) => Effect.tryPromise({
|
|
1213
2043
|
try: async () => {
|
|
1214
|
-
const
|
|
1215
|
-
|
|
2044
|
+
const cookies = await (async () => {
|
|
2045
|
+
if (activeSlot?.browserContextId) {
|
|
2046
|
+
const storageRes = await cdpChannel.sendCommand(
|
|
2047
|
+
"Storage.getCookies",
|
|
2048
|
+
{ browserContextId: activeSlot.browserContextId },
|
|
2049
|
+
null
|
|
2050
|
+
).catch(() => null);
|
|
2051
|
+
if (Array.isArray(storageRes?.cookies)) return storageRes.cookies;
|
|
2052
|
+
}
|
|
2053
|
+
const res = await cdpChannel.sendCommand("Network.getCookies");
|
|
2054
|
+
return res?.cookies ?? [];
|
|
2055
|
+
})();
|
|
2056
|
+
await writeFile(path, JSON.stringify(cookies, null, 2), "utf8");
|
|
1216
2057
|
},
|
|
1217
2058
|
catch: (e) => new DriverError({ message: `CDP saveCookies failed: ${e}` })
|
|
1218
2059
|
}),
|
|
1219
|
-
loadCookies: (path) =>
|
|
2060
|
+
loadCookies: (path) => Effect.tryPromise({
|
|
1220
2061
|
try: async () => {
|
|
1221
2062
|
const cookies = JSON.parse(await readFile(path, "utf8"));
|
|
1222
2063
|
if (Array.isArray(cookies)) {
|
|
@@ -1225,30 +2066,41 @@ function makeLightweightCdpDriver(options) {
|
|
|
1225
2066
|
},
|
|
1226
2067
|
catch: (e) => new DriverError({ message: `CDP loadCookies failed: ${e}` })
|
|
1227
2068
|
}),
|
|
1228
|
-
getCookies: (urls) =>
|
|
2069
|
+
getCookies: (urls) => Effect.tryPromise({
|
|
1229
2070
|
try: async () => {
|
|
1230
|
-
|
|
1231
|
-
"Network.getCookies",
|
|
1232
|
-
|
|
1233
|
-
|
|
2071
|
+
if (urls && urls.length > 0) {
|
|
2072
|
+
const res2 = await cdpChannel.sendCommand("Network.getCookies", { urls });
|
|
2073
|
+
return Array.isArray(res2?.cookies) ? res2.cookies : [];
|
|
2074
|
+
}
|
|
2075
|
+
if (activeSlot?.browserContextId) {
|
|
2076
|
+
const storageRes = await cdpChannel.sendCommand(
|
|
2077
|
+
"Storage.getCookies",
|
|
2078
|
+
{ browserContextId: activeSlot.browserContextId },
|
|
2079
|
+
null
|
|
2080
|
+
).catch(() => null);
|
|
2081
|
+
if (Array.isArray(storageRes?.cookies)) return storageRes.cookies;
|
|
2082
|
+
}
|
|
2083
|
+
const allRes = await cdpChannel.sendCommand("Network.getAllCookies").catch(() => null);
|
|
2084
|
+
if (Array.isArray(allRes?.cookies)) return allRes.cookies;
|
|
2085
|
+
const res = await cdpChannel.sendCommand("Network.getCookies", {});
|
|
1234
2086
|
return Array.isArray(res?.cookies) ? res.cookies : [];
|
|
1235
2087
|
},
|
|
1236
2088
|
catch: (e) => new DriverError({ message: `CDP getCookies failed: ${e}` })
|
|
1237
2089
|
}),
|
|
1238
|
-
setCookies: (cookies) =>
|
|
2090
|
+
setCookies: (cookies) => Effect.tryPromise({
|
|
1239
2091
|
try: async () => {
|
|
1240
2092
|
if (cookies.length === 0) return;
|
|
1241
2093
|
await cdpChannel.sendCommand("Network.setCookies", { cookies });
|
|
1242
2094
|
},
|
|
1243
2095
|
catch: (e) => new DriverError({ message: `CDP setCookies failed: ${e}` })
|
|
1244
2096
|
}),
|
|
1245
|
-
clearCookies: () =>
|
|
2097
|
+
clearCookies: () => Effect.tryPromise({
|
|
1246
2098
|
try: async () => {
|
|
1247
2099
|
await cdpChannel.sendCommand("Network.clearBrowserCookies");
|
|
1248
2100
|
},
|
|
1249
2101
|
catch: (e) => new DriverError({ message: `CDP clearCookies failed: ${e}` })
|
|
1250
2102
|
}),
|
|
1251
|
-
waitForResponse: (matcher, waitOpts) =>
|
|
2103
|
+
waitForResponse: (matcher, waitOpts) => Effect.tryPromise({
|
|
1252
2104
|
try: async () => {
|
|
1253
2105
|
const timeoutMs = waitOpts?.timeout ?? 15e3;
|
|
1254
2106
|
const slotSessions = () => {
|
|
@@ -1278,7 +2130,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
1278
2130
|
});
|
|
1279
2131
|
}
|
|
1280
2132
|
const requestMethods = /* @__PURE__ */ new Map();
|
|
1281
|
-
return await new Promise((
|
|
2133
|
+
return await new Promise((resolve2, reject) => {
|
|
1282
2134
|
let cleaned = false;
|
|
1283
2135
|
const cleanup = () => {
|
|
1284
2136
|
if (cleaned) return;
|
|
@@ -1337,39 +2189,97 @@ function makeLightweightCdpDriver(options) {
|
|
|
1337
2189
|
const matched = typeof matcher === "function" ? matcher(info) : matchUrl(matcher, info.url);
|
|
1338
2190
|
if (matched) {
|
|
1339
2191
|
cleanup();
|
|
1340
|
-
|
|
2192
|
+
resolve2(info);
|
|
1341
2193
|
}
|
|
1342
2194
|
});
|
|
1343
2195
|
});
|
|
1344
2196
|
},
|
|
1345
2197
|
catch: (e) => new DriverError({ message: `CDP waitForResponse failed: ${e}` })
|
|
1346
2198
|
}),
|
|
1347
|
-
|
|
2199
|
+
onRequest: (listener) => {
|
|
2200
|
+
requestListeners.add(listener);
|
|
2201
|
+
const sessions = activeSlot ? activeSlot.tabs.map((t) => t.sessionId) : [null];
|
|
2202
|
+
for (const sid of sessions) {
|
|
2203
|
+
void cdpChannel.sendCommand("Network.enable", {}, sid).catch(() => {
|
|
2204
|
+
});
|
|
2205
|
+
}
|
|
2206
|
+
return () => {
|
|
2207
|
+
requestListeners.delete(listener);
|
|
2208
|
+
};
|
|
2209
|
+
},
|
|
2210
|
+
waitForRequest: (matcher, waitOpts) => Effect.tryPromise({
|
|
2211
|
+
try: async () => {
|
|
2212
|
+
const timeoutMs = waitOpts?.timeout ?? 15e3;
|
|
2213
|
+
const sessions = activeSlot ? activeSlot.tabs.map((t) => t.sessionId) : [null];
|
|
2214
|
+
await Promise.all(
|
|
2215
|
+
sessions.map(
|
|
2216
|
+
(sid) => cdpChannel.sendCommand("Network.enable", {}, sid).catch(() => {
|
|
2217
|
+
})
|
|
2218
|
+
)
|
|
2219
|
+
);
|
|
2220
|
+
return await new Promise((resolve2, reject) => {
|
|
2221
|
+
let settled = false;
|
|
2222
|
+
const cleanup = () => {
|
|
2223
|
+
if (settled) return;
|
|
2224
|
+
settled = true;
|
|
2225
|
+
clearTimeout(timer);
|
|
2226
|
+
requestListeners.delete(onReq);
|
|
2227
|
+
};
|
|
2228
|
+
const timer = setTimeout(() => {
|
|
2229
|
+
cleanup();
|
|
2230
|
+
reject(new Error(`Timed out waiting for request after ${timeoutMs}ms`));
|
|
2231
|
+
}, timeoutMs);
|
|
2232
|
+
const onReq = (req) => {
|
|
2233
|
+
const matched = typeof matcher === "function" ? matcher(req) : matchUrl(matcher, req.url);
|
|
2234
|
+
if (matched) {
|
|
2235
|
+
cleanup();
|
|
2236
|
+
resolve2(req);
|
|
2237
|
+
}
|
|
2238
|
+
};
|
|
2239
|
+
requestListeners.add(onReq);
|
|
2240
|
+
});
|
|
2241
|
+
},
|
|
2242
|
+
catch: (e) => new DriverError({ message: `CDP waitForRequest failed: ${e}` })
|
|
2243
|
+
}),
|
|
2244
|
+
createIsolatedContext: (ctxOpts) => Effect.tryPromise({
|
|
1348
2245
|
try: async () => {
|
|
1349
|
-
const childDriver = await
|
|
2246
|
+
const childDriver = await Effect.runPromise(
|
|
1350
2247
|
makeLightweightCdpDriver({
|
|
1351
2248
|
...options,
|
|
1352
2249
|
cdpUrl: connectWsUrl ?? options.cdpUrl,
|
|
1353
2250
|
useBrowserContexts: true,
|
|
1354
|
-
freshContextPerFlow: false
|
|
2251
|
+
freshContextPerFlow: false,
|
|
2252
|
+
...ctxOpts?.viewport ? { viewport: ctxOpts.viewport } : {},
|
|
2253
|
+
...ctxOpts?.locale ? { emulation: { ...options.emulation, locale: ctxOpts.locale } } : {}
|
|
1355
2254
|
})
|
|
1356
2255
|
);
|
|
1357
2256
|
if (ctxOpts?.url) {
|
|
1358
|
-
await
|
|
2257
|
+
await Effect.runPromise(childDriver.openLink(ctxOpts.url));
|
|
1359
2258
|
}
|
|
1360
2259
|
return {
|
|
1361
2260
|
driver: childDriver,
|
|
1362
2261
|
close: async () => {
|
|
1363
|
-
await
|
|
2262
|
+
await Effect.runPromise(childDriver.killApp("isolated-context")).catch(() => {
|
|
1364
2263
|
});
|
|
1365
2264
|
}
|
|
1366
2265
|
};
|
|
1367
2266
|
},
|
|
1368
2267
|
catch: (e) => new DriverError({ message: `CDP createIsolatedContext failed: ${e}` })
|
|
1369
2268
|
}),
|
|
1370
|
-
saveAuthState: (path) =>
|
|
2269
|
+
saveAuthState: (path) => Effect.tryPromise({
|
|
1371
2270
|
try: async () => {
|
|
1372
|
-
const
|
|
2271
|
+
const cookies = await (async () => {
|
|
2272
|
+
if (activeSlot?.browserContextId) {
|
|
2273
|
+
const storageRes = await cdpChannel.sendCommand(
|
|
2274
|
+
"Storage.getCookies",
|
|
2275
|
+
{ browserContextId: activeSlot.browserContextId },
|
|
2276
|
+
null
|
|
2277
|
+
).catch(() => null);
|
|
2278
|
+
if (Array.isArray(storageRes?.cookies)) return storageRes.cookies;
|
|
2279
|
+
}
|
|
2280
|
+
const res = await cdpChannel.sendCommand("Network.getCookies");
|
|
2281
|
+
return res?.cookies ?? [];
|
|
2282
|
+
})();
|
|
1373
2283
|
const originState = await cdpChannel.evaluate(
|
|
1374
2284
|
`(() => {
|
|
1375
2285
|
const entries = [];
|
|
@@ -1383,14 +2293,14 @@ function makeLightweightCdpDriver(options) {
|
|
|
1383
2293
|
})()`
|
|
1384
2294
|
).catch(() => null);
|
|
1385
2295
|
const payload = {
|
|
1386
|
-
cookies
|
|
2296
|
+
cookies,
|
|
1387
2297
|
origins: originState && originState.origin !== "null" ? [originState] : []
|
|
1388
2298
|
};
|
|
1389
2299
|
await writeFile(path, JSON.stringify(payload, null, 2), "utf8");
|
|
1390
2300
|
},
|
|
1391
2301
|
catch: (e) => new DriverError({ message: `CDP saveAuthState failed: ${e}` })
|
|
1392
2302
|
}),
|
|
1393
|
-
loadAuthState: (path) =>
|
|
2303
|
+
loadAuthState: (path) => Effect.tryPromise({
|
|
1394
2304
|
try: async () => {
|
|
1395
2305
|
if (useContexts) {
|
|
1396
2306
|
const previousSlot = activeSlot;
|
|
@@ -1407,17 +2317,18 @@ function makeLightweightCdpDriver(options) {
|
|
|
1407
2317
|
},
|
|
1408
2318
|
catch: (e) => new DriverError({ message: `CDP loadAuthState failed: ${e}` })
|
|
1409
2319
|
}),
|
|
1410
|
-
enableVirtualAuthenticator: (opts) =>
|
|
2320
|
+
enableVirtualAuthenticator: (opts) => Effect.tryPromise({
|
|
1411
2321
|
try: async () => {
|
|
1412
2322
|
activeAuthenticatorId = await attachVirtualAuthenticatorForSession(
|
|
1413
2323
|
activeSlot?.sessionId ?? null,
|
|
1414
2324
|
opts
|
|
1415
2325
|
);
|
|
2326
|
+
if (activeSlot) activeSlot.authenticatorId = activeAuthenticatorId;
|
|
1416
2327
|
return activeAuthenticatorId;
|
|
1417
2328
|
},
|
|
1418
2329
|
catch: (e) => new DriverError({ message: `CDP enableVirtualAuthenticator failed: ${e}` })
|
|
1419
2330
|
}),
|
|
1420
|
-
removeVirtualAuthenticator: (authenticatorId) =>
|
|
2331
|
+
removeVirtualAuthenticator: (authenticatorId) => Effect.tryPromise({
|
|
1421
2332
|
try: async () => {
|
|
1422
2333
|
const id = authenticatorId ?? activeAuthenticatorId;
|
|
1423
2334
|
if (!id) return;
|
|
@@ -1425,10 +2336,13 @@ function makeLightweightCdpDriver(options) {
|
|
|
1425
2336
|
authenticatorId: id
|
|
1426
2337
|
});
|
|
1427
2338
|
if (id === activeAuthenticatorId) activeAuthenticatorId = void 0;
|
|
2339
|
+
if (activeSlot && activeSlot.authenticatorId === id) {
|
|
2340
|
+
activeSlot.authenticatorId = void 0;
|
|
2341
|
+
}
|
|
1428
2342
|
},
|
|
1429
2343
|
catch: (e) => new DriverError({ message: `CDP removeVirtualAuthenticator failed: ${e}` })
|
|
1430
2344
|
}),
|
|
1431
|
-
getVirtualCredentials: (authenticatorId) =>
|
|
2345
|
+
getVirtualCredentials: (authenticatorId) => Effect.tryPromise({
|
|
1432
2346
|
try: async () => {
|
|
1433
2347
|
const id = authenticatorId ?? activeAuthenticatorId;
|
|
1434
2348
|
if (!id) return [];
|
|
@@ -1439,7 +2353,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
1439
2353
|
},
|
|
1440
2354
|
catch: (e) => new DriverError({ message: `CDP getVirtualCredentials failed: ${e}` })
|
|
1441
2355
|
}),
|
|
1442
|
-
addVirtualCredential: (credential, authenticatorId) =>
|
|
2356
|
+
addVirtualCredential: (credential, authenticatorId) => Effect.tryPromise({
|
|
1443
2357
|
try: async () => {
|
|
1444
2358
|
let id = authenticatorId ?? activeAuthenticatorId;
|
|
1445
2359
|
if (!id) {
|
|
@@ -1461,7 +2375,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
1461
2375
|
},
|
|
1462
2376
|
catch: (e) => new DriverError({ message: `CDP addVirtualCredential failed: ${e}` })
|
|
1463
2377
|
}),
|
|
1464
|
-
clearVirtualCredentials: (authenticatorId) =>
|
|
2378
|
+
clearVirtualCredentials: (authenticatorId) => Effect.tryPromise({
|
|
1465
2379
|
try: async () => {
|
|
1466
2380
|
const id = authenticatorId ?? activeAuthenticatorId;
|
|
1467
2381
|
if (!id) return;
|
|
@@ -1469,24 +2383,39 @@ function makeLightweightCdpDriver(options) {
|
|
|
1469
2383
|
},
|
|
1470
2384
|
catch: (e) => new DriverError({ message: `CDP clearVirtualCredentials failed: ${e}` })
|
|
1471
2385
|
}),
|
|
1472
|
-
getConsoleLogs: () =>
|
|
1473
|
-
getJSErrors: () =>
|
|
1474
|
-
setNetworkConditions: (conditions) =>
|
|
2386
|
+
getConsoleLogs: () => Effect.succeed([...consoleLogs]),
|
|
2387
|
+
getJSErrors: () => Effect.succeed([...jsErrors]),
|
|
2388
|
+
setNetworkConditions: (conditions) => Effect.tryPromise({
|
|
1475
2389
|
try: async () => {
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
});
|
|
2390
|
+
currentNetworkConditions = { ...conditions };
|
|
2391
|
+
const sessions = activeSlot ? Array.from(
|
|
2392
|
+
/* @__PURE__ */ new Set([activeSlot.sessionId, ...activeSlot.tabs.map((t) => t.sessionId)])
|
|
2393
|
+
) : [null];
|
|
2394
|
+
await Promise.all(
|
|
2395
|
+
sessions.map((sid) => applyNetworkConditionsToSession(sid, conditions))
|
|
2396
|
+
);
|
|
1484
2397
|
},
|
|
1485
2398
|
catch: (e) => new DriverError({ message: `CDP setNetworkConditions failed: ${e}` })
|
|
1486
2399
|
}),
|
|
1487
|
-
uploadFile: (selector, filePath) =>
|
|
2400
|
+
uploadFile: (selector, filePath) => Effect.tryPromise({
|
|
1488
2401
|
try: async () => {
|
|
1489
|
-
const
|
|
2402
|
+
const rawItems = Array.isArray(filePath) ? filePath : [filePath];
|
|
2403
|
+
const files = [];
|
|
2404
|
+
let batchTempDir;
|
|
2405
|
+
for (const item of rawItems) {
|
|
2406
|
+
if (typeof item === "string") {
|
|
2407
|
+
files.push(item);
|
|
2408
|
+
} else {
|
|
2409
|
+
if (!batchTempDir) {
|
|
2410
|
+
batchTempDir = mkdtempSync(join2(tmpdir(), "spana-cdp-upload-"));
|
|
2411
|
+
uploadTempDirs.push(batchTempDir);
|
|
2412
|
+
}
|
|
2413
|
+
const safeFileName = item.name.replaceAll(/[\\/]/g, "_") || "upload.bin";
|
|
2414
|
+
const dest = join2(batchTempDir, safeFileName);
|
|
2415
|
+
await writeFile(dest, Buffer.from(item.buffer));
|
|
2416
|
+
files.push(dest);
|
|
2417
|
+
}
|
|
2418
|
+
}
|
|
1490
2419
|
const expr = buildDomFindElementScript(selector);
|
|
1491
2420
|
await cdpChannel.sendCommand("DOM.enable");
|
|
1492
2421
|
await cdpChannel.sendCommand("DOM.getDocument", { depth: 0 }).catch(() => {
|
|
@@ -1526,10 +2455,10 @@ function makeLightweightCdpDriver(options) {
|
|
|
1526
2455
|
},
|
|
1527
2456
|
catch: (e) => new DriverError({ message: `CDP uploadFile failed: ${e}` })
|
|
1528
2457
|
}),
|
|
1529
|
-
downloadFile: (destPath) =>
|
|
2458
|
+
downloadFile: (destPath) => Effect.tryPromise({
|
|
1530
2459
|
try: async () => {
|
|
1531
2460
|
if (!downloadDir) {
|
|
1532
|
-
downloadDir = mkdtempSync(
|
|
2461
|
+
downloadDir = mkdtempSync(join2(tmpdir(), "spana-cdp-dl-"));
|
|
1533
2462
|
await cdpChannel.sendCommand(
|
|
1534
2463
|
"Browser.setDownloadBehavior",
|
|
1535
2464
|
{
|
|
@@ -1541,14 +2470,14 @@ function makeLightweightCdpDriver(options) {
|
|
|
1541
2470
|
null
|
|
1542
2471
|
);
|
|
1543
2472
|
}
|
|
1544
|
-
const downloaded = completedDownloads.shift() ?? await new Promise((
|
|
2473
|
+
const downloaded = completedDownloads.shift() ?? await new Promise((resolve2, reject) => {
|
|
1545
2474
|
const timer = setTimeout(() => {
|
|
1546
2475
|
reject(new Error("Timed out waiting for CDP file download"));
|
|
1547
2476
|
}, 15e3);
|
|
1548
2477
|
downloadWaiters.push({
|
|
1549
|
-
resolve: (
|
|
2478
|
+
resolve: (entry) => {
|
|
1550
2479
|
clearTimeout(timer);
|
|
1551
|
-
|
|
2480
|
+
resolve2(entry);
|
|
1552
2481
|
},
|
|
1553
2482
|
reject: (err) => {
|
|
1554
2483
|
clearTimeout(timer);
|
|
@@ -1556,11 +2485,196 @@ function makeLightweightCdpDriver(options) {
|
|
|
1556
2485
|
}
|
|
1557
2486
|
});
|
|
1558
2487
|
});
|
|
1559
|
-
await copyFile(downloaded, destPath);
|
|
2488
|
+
await copyFile(downloaded.filePath, destPath);
|
|
1560
2489
|
},
|
|
1561
2490
|
catch: (e) => new DriverError({ message: `CDP downloadFile failed: ${e}` })
|
|
1562
2491
|
}),
|
|
1563
|
-
|
|
2492
|
+
dragAndDrop: (fromX, fromY, toX, toY, steps = 10) => Effect.tryPromise({
|
|
2493
|
+
try: async () => {
|
|
2494
|
+
const totalSteps = Math.max(1, Math.round(steps));
|
|
2495
|
+
await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
|
|
2496
|
+
type: "mouseMoved",
|
|
2497
|
+
x: fromX,
|
|
2498
|
+
y: fromY
|
|
2499
|
+
});
|
|
2500
|
+
await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
|
|
2501
|
+
type: "mousePressed",
|
|
2502
|
+
x: fromX,
|
|
2503
|
+
y: fromY,
|
|
2504
|
+
button: "left",
|
|
2505
|
+
buttons: 1,
|
|
2506
|
+
clickCount: 1
|
|
2507
|
+
});
|
|
2508
|
+
for (let i = 1; i <= totalSteps; i++) {
|
|
2509
|
+
const t = i / totalSteps;
|
|
2510
|
+
await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
|
|
2511
|
+
type: "mouseMoved",
|
|
2512
|
+
x: fromX + (toX - fromX) * t,
|
|
2513
|
+
y: fromY + (toY - fromY) * t,
|
|
2514
|
+
button: "left",
|
|
2515
|
+
buttons: 1
|
|
2516
|
+
});
|
|
2517
|
+
}
|
|
2518
|
+
await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
|
|
2519
|
+
type: "mouseReleased",
|
|
2520
|
+
x: toX,
|
|
2521
|
+
y: toY,
|
|
2522
|
+
button: "left",
|
|
2523
|
+
buttons: 0,
|
|
2524
|
+
clickCount: 1
|
|
2525
|
+
});
|
|
2526
|
+
},
|
|
2527
|
+
catch: (e) => new DriverError({ message: `CDP dragAndDrop failed: ${e}` })
|
|
2528
|
+
}),
|
|
2529
|
+
setViewport: (viewport) => Effect.tryPromise({
|
|
2530
|
+
try: async () => {
|
|
2531
|
+
width = viewport.width;
|
|
2532
|
+
height = viewport.height;
|
|
2533
|
+
await cdpChannel.sendCommand("Emulation.setDeviceMetricsOverride", {
|
|
2534
|
+
width: viewport.width,
|
|
2535
|
+
height: viewport.height,
|
|
2536
|
+
deviceScaleFactor: viewport.deviceScaleFactor ?? 1,
|
|
2537
|
+
mobile: viewport.mobile ?? false
|
|
2538
|
+
});
|
|
2539
|
+
},
|
|
2540
|
+
catch: (e) => new DriverError({ message: `CDP setViewport failed: ${e}` })
|
|
2541
|
+
}),
|
|
2542
|
+
setEmulation: (emulationOpts) => Effect.tryPromise({
|
|
2543
|
+
try: async () => {
|
|
2544
|
+
const features = [];
|
|
2545
|
+
if (emulationOpts.colorScheme !== void 0) {
|
|
2546
|
+
features.push({
|
|
2547
|
+
name: "prefers-color-scheme",
|
|
2548
|
+
value: emulationOpts.colorScheme === "no-preference" ? "" : emulationOpts.colorScheme
|
|
2549
|
+
});
|
|
2550
|
+
}
|
|
2551
|
+
if (emulationOpts.reducedMotion !== void 0) {
|
|
2552
|
+
features.push({
|
|
2553
|
+
name: "prefers-reduced-motion",
|
|
2554
|
+
value: emulationOpts.reducedMotion === "no-preference" ? "" : emulationOpts.reducedMotion
|
|
2555
|
+
});
|
|
2556
|
+
}
|
|
2557
|
+
if (features.length > 0) {
|
|
2558
|
+
await cdpChannel.sendCommand("Emulation.setEmulatedMedia", { features });
|
|
2559
|
+
}
|
|
2560
|
+
if (emulationOpts.locale !== void 0) {
|
|
2561
|
+
await applyLocaleOverride(activeSlot?.sessionId ?? null, emulationOpts.locale);
|
|
2562
|
+
}
|
|
2563
|
+
if (emulationOpts.timezoneId !== void 0) {
|
|
2564
|
+
await cdpChannel.sendCommand("Emulation.setTimezoneOverride", {
|
|
2565
|
+
timezoneId: emulationOpts.timezoneId
|
|
2566
|
+
}).catch(() => {
|
|
2567
|
+
});
|
|
2568
|
+
}
|
|
2569
|
+
},
|
|
2570
|
+
catch: (e) => new DriverError({ message: `CDP setEmulation failed: ${e}` })
|
|
2571
|
+
}),
|
|
2572
|
+
setDialogHandler: (handler) => Effect.sync(() => {
|
|
2573
|
+
dialogHandler = handler;
|
|
2574
|
+
}),
|
|
2575
|
+
getClipboard: () => Effect.tryPromise({
|
|
2576
|
+
try: async () => {
|
|
2577
|
+
if (activeSlot?.browserContextId) {
|
|
2578
|
+
await cdpChannel.sendCommand(
|
|
2579
|
+
"Browser.grantPermissions",
|
|
2580
|
+
{
|
|
2581
|
+
permissions: ["clipboardReadWrite", "clipboardSanitizedWrite"],
|
|
2582
|
+
browserContextId: activeSlot.browserContextId
|
|
2583
|
+
},
|
|
2584
|
+
null
|
|
2585
|
+
).catch(() => {
|
|
2586
|
+
});
|
|
2587
|
+
}
|
|
2588
|
+
const res = await cdpChannel.sendCommand("Runtime.evaluate", {
|
|
2589
|
+
expression: `(async () => {
|
|
2590
|
+
if (navigator.clipboard && typeof navigator.clipboard.readText === "function") {
|
|
2591
|
+
try { return await navigator.clipboard.readText(); } catch {}
|
|
2592
|
+
}
|
|
2593
|
+
return typeof window.__spanaClipboardText === "string" ? window.__spanaClipboardText : "";
|
|
2594
|
+
})()`,
|
|
2595
|
+
awaitPromise: true,
|
|
2596
|
+
returnByValue: true,
|
|
2597
|
+
userGesture: true
|
|
2598
|
+
});
|
|
2599
|
+
return typeof res?.result?.value === "string" ? res.result.value : "";
|
|
2600
|
+
},
|
|
2601
|
+
catch: (e) => new DriverError({ message: `CDP getClipboard failed: ${e}` })
|
|
2602
|
+
}),
|
|
2603
|
+
setClipboard: (text) => Effect.tryPromise({
|
|
2604
|
+
try: async () => {
|
|
2605
|
+
if (activeSlot?.browserContextId) {
|
|
2606
|
+
await cdpChannel.sendCommand(
|
|
2607
|
+
"Browser.grantPermissions",
|
|
2608
|
+
{
|
|
2609
|
+
permissions: ["clipboardReadWrite", "clipboardSanitizedWrite"],
|
|
2610
|
+
browserContextId: activeSlot.browserContextId
|
|
2611
|
+
},
|
|
2612
|
+
null
|
|
2613
|
+
).catch(() => {
|
|
2614
|
+
});
|
|
2615
|
+
}
|
|
2616
|
+
const encoded = JSON.stringify(text);
|
|
2617
|
+
await cdpChannel.sendCommand("Runtime.evaluate", {
|
|
2618
|
+
expression: `(async (txt) => {
|
|
2619
|
+
window.__spanaClipboardText = txt;
|
|
2620
|
+
if (navigator.clipboard && typeof navigator.clipboard.writeText === "function") {
|
|
2621
|
+
try { await navigator.clipboard.writeText(txt); return; } catch {}
|
|
2622
|
+
}
|
|
2623
|
+
})(${encoded})`,
|
|
2624
|
+
awaitPromise: true,
|
|
2625
|
+
returnByValue: true,
|
|
2626
|
+
userGesture: true
|
|
2627
|
+
});
|
|
2628
|
+
},
|
|
2629
|
+
catch: (e) => new DriverError({ message: `CDP setClipboard failed: ${e}` })
|
|
2630
|
+
}),
|
|
2631
|
+
waitForDownload: (triggerFn, dlOpts) => Effect.tryPromise({
|
|
2632
|
+
try: async () => {
|
|
2633
|
+
const timeoutMs = dlOpts?.timeout ?? 15e3;
|
|
2634
|
+
if (!downloadDir) {
|
|
2635
|
+
downloadDir = mkdtempSync(join2(tmpdir(), "spana-cdp-dl-"));
|
|
2636
|
+
await cdpChannel.sendCommand(
|
|
2637
|
+
"Browser.setDownloadBehavior",
|
|
2638
|
+
{
|
|
2639
|
+
behavior: "allowAndName",
|
|
2640
|
+
downloadPath: downloadDir,
|
|
2641
|
+
eventsEnabled: true,
|
|
2642
|
+
...activeSlot?.browserContextId ? { browserContextId: activeSlot.browserContextId } : {}
|
|
2643
|
+
},
|
|
2644
|
+
null
|
|
2645
|
+
);
|
|
2646
|
+
}
|
|
2647
|
+
const downloadPromise = new Promise((resolve2, reject) => {
|
|
2648
|
+
const timer = setTimeout(() => {
|
|
2649
|
+
reject(new Error(`Timed out waiting for download after ${timeoutMs}ms`));
|
|
2650
|
+
}, timeoutMs);
|
|
2651
|
+
downloadWaiters.push({
|
|
2652
|
+
resolve: (entry2) => {
|
|
2653
|
+
clearTimeout(timer);
|
|
2654
|
+
resolve2(entry2);
|
|
2655
|
+
},
|
|
2656
|
+
reject: (err) => {
|
|
2657
|
+
clearTimeout(timer);
|
|
2658
|
+
reject(err);
|
|
2659
|
+
}
|
|
2660
|
+
});
|
|
2661
|
+
});
|
|
2662
|
+
await triggerFn();
|
|
2663
|
+
const entry = await downloadPromise;
|
|
2664
|
+
return {
|
|
2665
|
+
suggestedFilename: entry.suggestedFilename,
|
|
2666
|
+
path: entry.filePath,
|
|
2667
|
+
url: entry.url,
|
|
2668
|
+
text: () => readFile(entry.filePath, "utf8"),
|
|
2669
|
+
bytes: async () => new Uint8Array(await readFile(entry.filePath)),
|
|
2670
|
+
saveAs: async (destPath) => {
|
|
2671
|
+
await copyFile(entry.filePath, destPath);
|
|
2672
|
+
}
|
|
2673
|
+
};
|
|
2674
|
+
},
|
|
2675
|
+
catch: (e) => new DriverError({ message: `CDP waitForDownload failed: ${e}` })
|
|
2676
|
+
}),
|
|
2677
|
+
newTab: (url) => Effect.tryPromise({
|
|
1564
2678
|
try: async () => {
|
|
1565
2679
|
if (!activeSlot) {
|
|
1566
2680
|
throw new Error("newTab() requires browser-context mode (engine: 'cdp')");
|
|
@@ -1594,7 +2708,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
1594
2708
|
},
|
|
1595
2709
|
catch: (e) => new DriverError({ message: `CDP newTab failed: ${e}` })
|
|
1596
2710
|
}),
|
|
1597
|
-
switchToTab: (index) =>
|
|
2711
|
+
switchToTab: (index) => Effect.tryPromise({
|
|
1598
2712
|
try: async () => {
|
|
1599
2713
|
if (!activeSlot || !activeSlot.tabs[index]) {
|
|
1600
2714
|
throw new Error(`Tab index ${index} is out of range.`);
|
|
@@ -1608,7 +2722,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
1608
2722
|
},
|
|
1609
2723
|
catch: (e) => new DriverError({ message: `CDP switchToTab failed: ${e}` })
|
|
1610
2724
|
}),
|
|
1611
|
-
closeTab: () =>
|
|
2725
|
+
closeTab: () => Effect.tryPromise({
|
|
1612
2726
|
try: async () => {
|
|
1613
2727
|
if (!activeSlot) return;
|
|
1614
2728
|
if (activeSlot.tabs.length <= 1) {
|
|
@@ -1627,23 +2741,84 @@ function makeLightweightCdpDriver(options) {
|
|
|
1627
2741
|
},
|
|
1628
2742
|
catch: (e) => new DriverError({ message: `CDP closeTab failed: ${e}` })
|
|
1629
2743
|
}),
|
|
1630
|
-
getTabIds: () =>
|
|
2744
|
+
getTabIds: () => Effect.sync(() => activeSlot ? activeSlot.tabs.map((t) => t.tabId) : ["tab-1"])
|
|
1631
2745
|
};
|
|
1632
2746
|
return service;
|
|
1633
2747
|
});
|
|
1634
2748
|
}
|
|
1635
2749
|
|
|
1636
|
-
// src/
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
2750
|
+
// src/drivers/adapter-registry.ts
|
|
2751
|
+
init_esm_shims();
|
|
2752
|
+
var driverAdapters = /* @__PURE__ */ new Map();
|
|
2753
|
+
var domTransports = /* @__PURE__ */ new Map();
|
|
2754
|
+
function defineDriverAdapter(adapter) {
|
|
2755
|
+
return adapter;
|
|
2756
|
+
}
|
|
2757
|
+
function defineDomTransport(adapter) {
|
|
2758
|
+
return adapter;
|
|
2759
|
+
}
|
|
2760
|
+
function registerDriverAdapter(adapter) {
|
|
2761
|
+
driverAdapters.set(adapter.name, adapter);
|
|
2762
|
+
return () => {
|
|
2763
|
+
if (driverAdapters.get(adapter.name) === adapter) {
|
|
2764
|
+
driverAdapters.delete(adapter.name);
|
|
2765
|
+
}
|
|
2766
|
+
};
|
|
2767
|
+
}
|
|
2768
|
+
function unregisterDriverAdapter(name) {
|
|
2769
|
+
return driverAdapters.delete(name);
|
|
2770
|
+
}
|
|
2771
|
+
function listDriverAdapters() {
|
|
2772
|
+
return Array.from(driverAdapters.values());
|
|
2773
|
+
}
|
|
2774
|
+
function resolveDriverAdapter(platform, engine) {
|
|
2775
|
+
if (engine && driverAdapters.has(engine)) {
|
|
2776
|
+
const byName = driverAdapters.get(engine);
|
|
2777
|
+
if (byName.platforms.includes(platform) || byName.platforms.includes("*")) {
|
|
2778
|
+
return byName;
|
|
1643
2779
|
}
|
|
1644
2780
|
}
|
|
2781
|
+
const all = Array.from(driverAdapters.values()).toReversed();
|
|
2782
|
+
if (engine) {
|
|
2783
|
+
const exactEngine = all.find(
|
|
2784
|
+
(a) => (a.platforms.includes(platform) || a.platforms.includes("*")) && a.engines?.includes(engine)
|
|
2785
|
+
);
|
|
2786
|
+
if (exactEngine) return exactEngine;
|
|
2787
|
+
}
|
|
2788
|
+
return all.find(
|
|
2789
|
+
(a) => (a.platforms.includes(platform) || a.platforms.includes("*")) && (!a.engines || a.engines.length === 0 || engine !== void 0 && a.engines.includes(engine))
|
|
2790
|
+
);
|
|
1645
2791
|
}
|
|
1646
|
-
|
|
2792
|
+
function registerDomTransport(adapter) {
|
|
2793
|
+
domTransports.set(adapter.name, adapter);
|
|
2794
|
+
return () => {
|
|
2795
|
+
if (domTransports.get(adapter.name) === adapter) {
|
|
2796
|
+
domTransports.delete(adapter.name);
|
|
2797
|
+
}
|
|
2798
|
+
};
|
|
2799
|
+
}
|
|
2800
|
+
function unregisterDomTransport(name) {
|
|
2801
|
+
return domTransports.delete(name);
|
|
2802
|
+
}
|
|
2803
|
+
function listDomTransports() {
|
|
2804
|
+
return Array.from(domTransports.values());
|
|
2805
|
+
}
|
|
2806
|
+
function resolveDomTransport(nameOrKind) {
|
|
2807
|
+
const direct = domTransports.get(nameOrKind);
|
|
2808
|
+
if (direct) return direct;
|
|
2809
|
+
return Array.from(domTransports.values()).toReversed().find((t) => t.kind === nameOrKind);
|
|
2810
|
+
}
|
|
2811
|
+
|
|
2812
|
+
// src/runtime/local.ts
|
|
2813
|
+
async function safeCleanup(...fns) {
|
|
2814
|
+
for (const fn of fns) {
|
|
2815
|
+
try {
|
|
2816
|
+
await fn();
|
|
2817
|
+
} catch {
|
|
2818
|
+
}
|
|
2819
|
+
}
|
|
2820
|
+
}
|
|
2821
|
+
async function maybeStartBridge(appBridge, globalBridge) {
|
|
1647
2822
|
const merged = appBridge ?? globalBridge;
|
|
1648
2823
|
if (!merged) return void 0;
|
|
1649
2824
|
const enabled = merged.enabled ?? Boolean(merged.port || merged.url);
|
|
@@ -1682,11 +2857,14 @@ function buildEngineConfig(appId, platform, parseFn, config, screenSize) {
|
|
|
1682
2857
|
},
|
|
1683
2858
|
autoLaunch: true,
|
|
1684
2859
|
flowTimeout: config.defaults?.waitTimeout ? config.defaults.waitTimeout * 10 : 6e4,
|
|
2860
|
+
toPassTimeout: config.defaults?.toPassTimeout,
|
|
1685
2861
|
artifactConfig: config.artifacts,
|
|
1686
2862
|
launchOptions: config.launchOptions,
|
|
1687
2863
|
hooks: config.hooks,
|
|
1688
2864
|
storybook: platform === "web" ? config.execution?.web?.storybook : void 0,
|
|
1689
|
-
visualRegression: config.visualRegression
|
|
2865
|
+
visualRegression: config.visualRegression,
|
|
2866
|
+
replayCache: config.replayCache,
|
|
2867
|
+
agent: config.agent
|
|
1690
2868
|
};
|
|
1691
2869
|
}
|
|
1692
2870
|
function resolveWebEngine(config) {
|
|
@@ -1716,14 +2894,18 @@ function speculativelyPrelaunchWebBrowser(config) {
|
|
|
1716
2894
|
const cdpBrowserPromise = launchDirectCdpBrowser({
|
|
1717
2895
|
executablePath: webExecution?.executablePath,
|
|
1718
2896
|
headless: webExecution?.headless ?? true,
|
|
2897
|
+
extensions: webExecution?.extensions,
|
|
2898
|
+
args: webExecution?.args,
|
|
2899
|
+
launchTimeout: webExecution?.launchTimeout,
|
|
1719
2900
|
warmBrowser: useWarm2,
|
|
1720
|
-
warmBrowserScope: webExecution?.warmBrowserScope ? `${webExecution.warmBrowserScope}-w0` : void 0
|
|
2901
|
+
warmBrowserScope: webExecution?.warmBrowserScope ? `${webExecution.warmBrowserScope}-w0` : void 0,
|
|
2902
|
+
daemonStateFile: config.execution?.warmDaemons?.stateFile
|
|
1721
2903
|
});
|
|
1722
2904
|
cdpBrowserPromise.catch(() => {
|
|
1723
2905
|
});
|
|
1724
2906
|
return {
|
|
1725
2907
|
browserPromise: Promise.resolve(void 0),
|
|
1726
|
-
ownsBrowser:
|
|
2908
|
+
ownsBrowser: !useWarm2,
|
|
1727
2909
|
cdpBrowserPromise
|
|
1728
2910
|
};
|
|
1729
2911
|
}
|
|
@@ -1737,7 +2919,8 @@ function speculativelyPrelaunchWebBrowser(config) {
|
|
|
1737
2919
|
browser: webExecution?.browser,
|
|
1738
2920
|
headless: webExecution?.headless ?? true,
|
|
1739
2921
|
executablePath: webExecution?.executablePath,
|
|
1740
|
-
channel: webExecution?.channel
|
|
2922
|
+
channel: webExecution?.channel,
|
|
2923
|
+
args: webExecution?.args
|
|
1741
2924
|
});
|
|
1742
2925
|
browserPromise.catch(() => {
|
|
1743
2926
|
});
|
|
@@ -1747,6 +2930,45 @@ async function buildWebRuntime(config, prelaunched) {
|
|
|
1747
2930
|
const webUrl = config.apps?.web?.url ?? "http://localhost:3000";
|
|
1748
2931
|
const webExecution = config.execution?.web;
|
|
1749
2932
|
const bridge = await maybeStartBridge(config.apps?.web?.bridge, config.execution?.bridge);
|
|
2933
|
+
const requestedEngine = webExecution?.engine;
|
|
2934
|
+
const customAdapter = resolveDriverAdapter("web", requestedEngine);
|
|
2935
|
+
if (customAdapter) {
|
|
2936
|
+
const handle = await customAdapter.create({
|
|
2937
|
+
platform: "web",
|
|
2938
|
+
engine: requestedEngine,
|
|
2939
|
+
appId: webUrl,
|
|
2940
|
+
config,
|
|
2941
|
+
domChannel: bridge,
|
|
2942
|
+
resolvePath: (p) => p
|
|
2943
|
+
});
|
|
2944
|
+
const driver2 = bridge && !handle.driver.domChannel ? { ...handle.driver, domChannel: bridge } : handle.driver;
|
|
2945
|
+
const deviceInfo2 = await Effect2.runPromise(driver2.getDeviceInfo());
|
|
2946
|
+
return {
|
|
2947
|
+
runtime: {
|
|
2948
|
+
driver: driver2,
|
|
2949
|
+
cleanup: () => safeCleanup(
|
|
2950
|
+
() => handle.cleanup(),
|
|
2951
|
+
() => bridge?.disconnect() ?? Promise.resolve()
|
|
2952
|
+
),
|
|
2953
|
+
metadata: {
|
|
2954
|
+
platform: "web",
|
|
2955
|
+
mode: "local",
|
|
2956
|
+
adapter: customAdapter.name,
|
|
2957
|
+
...handle.metadata
|
|
2958
|
+
}
|
|
2959
|
+
},
|
|
2960
|
+
engineConfig: buildEngineConfig(
|
|
2961
|
+
webUrl,
|
|
2962
|
+
"web",
|
|
2963
|
+
handle.parseHierarchy ?? parseWebHierarchy,
|
|
2964
|
+
config,
|
|
2965
|
+
{
|
|
2966
|
+
width: deviceInfo2.screenWidth,
|
|
2967
|
+
height: deviceInfo2.screenHeight
|
|
2968
|
+
}
|
|
2969
|
+
)
|
|
2970
|
+
};
|
|
2971
|
+
}
|
|
1750
2972
|
const prelaunchedBrowser = prelaunched && !prelaunched.cdpBrowserPromise ? await prelaunched.browserPromise : void 0;
|
|
1751
2973
|
let launchedDirectCdp;
|
|
1752
2974
|
let rawDriver;
|
|
@@ -1758,16 +2980,29 @@ async function buildWebRuntime(config, prelaunched) {
|
|
|
1758
2980
|
launchedDirectCdp = prelaunched?.cdpBrowserPromise ? await prelaunched.cdpBrowserPromise : await launchDirectCdpBrowser({
|
|
1759
2981
|
executablePath: webExecution?.executablePath,
|
|
1760
2982
|
headless: webExecution?.headless ?? true,
|
|
2983
|
+
extensions: webExecution?.extensions,
|
|
2984
|
+
args: webExecution?.args,
|
|
2985
|
+
launchTimeout: webExecution?.launchTimeout,
|
|
1761
2986
|
warmBrowser: webExecution?.warmBrowser ?? config.execution?.warmDaemons?.enabled ?? false,
|
|
1762
|
-
warmBrowserScope: webExecution?.warmBrowserScope ? `${webExecution.warmBrowserScope}-w0` : void 0
|
|
2987
|
+
warmBrowserScope: webExecution?.warmBrowserScope ? `${webExecution.warmBrowserScope}-w0` : void 0,
|
|
2988
|
+
daemonStateFile: config.execution?.warmDaemons?.stateFile
|
|
1763
2989
|
});
|
|
1764
2990
|
targetCdpUrl = launchedDirectCdp.browserWsUrl;
|
|
1765
2991
|
}
|
|
1766
|
-
|
|
2992
|
+
const effectiveLocale = webExecution?.locale ?? config.defaults?.locale;
|
|
2993
|
+
const cdpEmulation = webExecution?.colorScheme || webExecution?.reducedMotion || webExecution?.timezoneId || effectiveLocale ? {
|
|
2994
|
+
colorScheme: webExecution?.colorScheme,
|
|
2995
|
+
reducedMotion: webExecution?.reducedMotion,
|
|
2996
|
+
timezoneId: webExecution?.timezoneId,
|
|
2997
|
+
locale: effectiveLocale
|
|
2998
|
+
} : void 0;
|
|
2999
|
+
rawDriver = await Effect2.runPromise(
|
|
1767
3000
|
makeLightweightCdpDriver({
|
|
1768
3001
|
cdpUrl: targetCdpUrl ?? "http://127.0.0.1:9222",
|
|
1769
3002
|
baseUrl: webUrl,
|
|
1770
3003
|
engineLabel: engine,
|
|
3004
|
+
viewport: webExecution?.viewport,
|
|
3005
|
+
evaluateTimeout: webExecution?.evaluateTimeout,
|
|
1771
3006
|
useBrowserContexts: useContexts,
|
|
1772
3007
|
freshContextPerFlow: webExecution?.freshContextPerFlow,
|
|
1773
3008
|
contextIsolation: webExecution?.contextIsolation,
|
|
@@ -1775,16 +3010,23 @@ async function buildWebRuntime(config, prelaunched) {
|
|
|
1775
3010
|
instantAnimations: webExecution?.instantAnimations,
|
|
1776
3011
|
blockResources: webExecution?.blockResources,
|
|
1777
3012
|
virtualAuthenticator: webExecution?.virtualAuthenticator,
|
|
1778
|
-
storageState: webExecution?.storageState
|
|
3013
|
+
storageState: webExecution?.storageState,
|
|
3014
|
+
emulation: cdpEmulation
|
|
1779
3015
|
})
|
|
1780
3016
|
);
|
|
1781
3017
|
} else {
|
|
1782
|
-
rawDriver = await
|
|
3018
|
+
rawDriver = await Effect2.runPromise(
|
|
1783
3019
|
makePlaywrightDriver({
|
|
1784
3020
|
browser: webExecution?.browser,
|
|
1785
3021
|
headless: webExecution?.headless ?? true,
|
|
1786
3022
|
executablePath: webExecution?.executablePath,
|
|
1787
3023
|
channel: webExecution?.channel,
|
|
3024
|
+
args: webExecution?.args,
|
|
3025
|
+
viewport: webExecution?.viewport,
|
|
3026
|
+
locale: webExecution?.locale ?? config.defaults?.locale,
|
|
3027
|
+
timezoneId: webExecution?.timezoneId,
|
|
3028
|
+
colorScheme: webExecution?.colorScheme,
|
|
3029
|
+
reducedMotion: webExecution?.reducedMotion,
|
|
1788
3030
|
baseUrl: webUrl,
|
|
1789
3031
|
storageState: webExecution?.storageState,
|
|
1790
3032
|
verboseLogging: webExecution?.verboseLogging,
|
|
@@ -1803,12 +3045,12 @@ async function buildWebRuntime(config, prelaunched) {
|
|
|
1803
3045
|
);
|
|
1804
3046
|
}
|
|
1805
3047
|
const driver = bridge ? { ...rawDriver, domChannel: bridge } : rawDriver;
|
|
1806
|
-
const deviceInfo = await
|
|
3048
|
+
const deviceInfo = await Effect2.runPromise(driver.getDeviceInfo());
|
|
1807
3049
|
return {
|
|
1808
3050
|
runtime: {
|
|
1809
3051
|
driver,
|
|
1810
3052
|
cleanup: () => safeCleanup(
|
|
1811
|
-
() =>
|
|
3053
|
+
() => Effect2.runPromise(driver.killApp("")),
|
|
1812
3054
|
() => prelaunchedBrowser && prelaunched?.ownsBrowser ? prelaunchedBrowser.close() : Promise.resolve(),
|
|
1813
3055
|
() => launchedDirectCdp ? launchedDirectCdp.close() : Promise.resolve(),
|
|
1814
3056
|
() => bridge?.disconnect() ?? Promise.resolve()
|
|
@@ -1850,8 +3092,12 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
|
|
|
1850
3092
|
(_v, bIdx) => bIdx === 0 && prelaunched?.cdpBrowserPromise ? prelaunched.cdpBrowserPromise : launchDirectCdpBrowser({
|
|
1851
3093
|
executablePath: webExecution?.executablePath,
|
|
1852
3094
|
headless: webExecution?.headless ?? true,
|
|
3095
|
+
extensions: webExecution?.extensions,
|
|
3096
|
+
args: webExecution?.args,
|
|
3097
|
+
launchTimeout: webExecution?.launchTimeout,
|
|
1853
3098
|
warmBrowser: useWarm2,
|
|
1854
|
-
warmBrowserScope: `${baseScope}-w${bIdx}
|
|
3099
|
+
warmBrowserScope: `${baseScope}-w${bIdx}`,
|
|
3100
|
+
daemonStateFile: config.execution?.warmDaemons?.stateFile
|
|
1855
3101
|
})
|
|
1856
3102
|
)
|
|
1857
3103
|
);
|
|
@@ -1862,14 +3108,23 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
|
|
|
1862
3108
|
handles[i % handles.length].remaining += 1;
|
|
1863
3109
|
}
|
|
1864
3110
|
}
|
|
3111
|
+
const effectivePoolLocale = webExecution?.locale ?? config.defaults?.locale;
|
|
3112
|
+
const poolEmulation = webExecution?.colorScheme || webExecution?.reducedMotion || webExecution?.timezoneId || effectivePoolLocale ? {
|
|
3113
|
+
colorScheme: webExecution?.colorScheme,
|
|
3114
|
+
reducedMotion: webExecution?.reducedMotion,
|
|
3115
|
+
timezoneId: webExecution?.timezoneId,
|
|
3116
|
+
locale: effectivePoolLocale
|
|
3117
|
+
} : void 0;
|
|
1865
3118
|
const results2 = [];
|
|
1866
3119
|
for (let i = 0; i < workerCount; i++) {
|
|
1867
3120
|
const bucket = handles[i % handles.length];
|
|
1868
|
-
const driver = await
|
|
3121
|
+
const driver = await Effect2.runPromise(
|
|
1869
3122
|
makeLightweightCdpDriver({
|
|
1870
3123
|
cdpUrl: bucket.cdpUrl,
|
|
1871
3124
|
baseUrl: webUrl,
|
|
1872
3125
|
engineLabel: "cdp",
|
|
3126
|
+
viewport: webExecution?.viewport,
|
|
3127
|
+
evaluateTimeout: webExecution?.evaluateTimeout,
|
|
1873
3128
|
useBrowserContexts: true,
|
|
1874
3129
|
freshContextPerFlow: webExecution?.freshContextPerFlow,
|
|
1875
3130
|
contextIsolation: webExecution?.contextIsolation,
|
|
@@ -1877,10 +3132,11 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
|
|
|
1877
3132
|
instantAnimations: webExecution?.instantAnimations,
|
|
1878
3133
|
blockResources: webExecution?.blockResources,
|
|
1879
3134
|
virtualAuthenticator: webExecution?.virtualAuthenticator,
|
|
1880
|
-
storageState: webExecution?.storageState
|
|
3135
|
+
storageState: webExecution?.storageState,
|
|
3136
|
+
emulation: poolEmulation
|
|
1881
3137
|
})
|
|
1882
3138
|
);
|
|
1883
|
-
const deviceInfo = await
|
|
3139
|
+
const deviceInfo = await Effect2.runPromise(driver.getDeviceInfo());
|
|
1884
3140
|
let cleaned = false;
|
|
1885
3141
|
results2.push({
|
|
1886
3142
|
runtime: {
|
|
@@ -1888,7 +3144,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
|
|
|
1888
3144
|
cleanup: () => safeCleanup(async () => {
|
|
1889
3145
|
if (cleaned) return;
|
|
1890
3146
|
cleaned = true;
|
|
1891
|
-
await
|
|
3147
|
+
await Effect2.runPromise(driver.killApp(""));
|
|
1892
3148
|
bucket.remaining -= 1;
|
|
1893
3149
|
if (bucket.remaining <= 0 && bucket.handle) {
|
|
1894
3150
|
await bucket.handle.close();
|
|
@@ -1946,7 +3202,8 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
|
|
|
1946
3202
|
browser: webExecution?.browser,
|
|
1947
3203
|
headless: webExecution?.headless ?? true,
|
|
1948
3204
|
executablePath: webExecution?.executablePath,
|
|
1949
|
-
channel: webExecution?.channel
|
|
3205
|
+
channel: webExecution?.channel,
|
|
3206
|
+
args: webExecution?.args
|
|
1950
3207
|
}),
|
|
1951
3208
|
owns: true,
|
|
1952
3209
|
remaining: 0
|
|
@@ -1961,12 +3218,18 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
|
|
|
1961
3218
|
const results = [];
|
|
1962
3219
|
for (let i = 0; i < workerCount; i++) {
|
|
1963
3220
|
const bucket = browserBuckets[i % browserBuckets.length];
|
|
1964
|
-
const driver = await
|
|
3221
|
+
const driver = await Effect2.runPromise(
|
|
1965
3222
|
makePlaywrightDriver({
|
|
1966
3223
|
browser: webExecution?.browser,
|
|
1967
3224
|
headless: webExecution?.headless ?? true,
|
|
1968
3225
|
executablePath: webExecution?.executablePath,
|
|
1969
3226
|
channel: webExecution?.channel,
|
|
3227
|
+
args: webExecution?.args,
|
|
3228
|
+
viewport: webExecution?.viewport,
|
|
3229
|
+
locale: webExecution?.locale ?? config.defaults?.locale,
|
|
3230
|
+
timezoneId: webExecution?.timezoneId,
|
|
3231
|
+
colorScheme: webExecution?.colorScheme,
|
|
3232
|
+
reducedMotion: webExecution?.reducedMotion,
|
|
1970
3233
|
baseUrl: webUrl,
|
|
1971
3234
|
storageState: webExecution?.storageState,
|
|
1972
3235
|
verboseLogging: webExecution?.verboseLogging,
|
|
@@ -1980,7 +3243,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
|
|
|
1980
3243
|
warmBrowserScope: webExecution?.warmBrowserScope
|
|
1981
3244
|
})
|
|
1982
3245
|
);
|
|
1983
|
-
const deviceInfo = await
|
|
3246
|
+
const deviceInfo = await Effect2.runPromise(driver.getDeviceInfo());
|
|
1984
3247
|
let cleaned = false;
|
|
1985
3248
|
results.push({
|
|
1986
3249
|
runtime: {
|
|
@@ -1988,7 +3251,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
|
|
|
1988
3251
|
cleanup: () => safeCleanup(async () => {
|
|
1989
3252
|
if (cleaned) return;
|
|
1990
3253
|
cleaned = true;
|
|
1991
|
-
await
|
|
3254
|
+
await Effect2.runPromise(driver.killApp(""));
|
|
1992
3255
|
bucket.remaining -= 1;
|
|
1993
3256
|
if (bucket.remaining <= 0 && bucket.owns) {
|
|
1994
3257
|
await bucket.browser.close();
|
|
@@ -2011,7 +3274,45 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
|
|
|
2011
3274
|
async function buildElectronRuntime(config, resolveFromConfig) {
|
|
2012
3275
|
const electronCfg = config.apps?.electron ?? {};
|
|
2013
3276
|
const bridge = await maybeStartBridge(electronCfg.bridge, config.execution?.bridge);
|
|
2014
|
-
const
|
|
3277
|
+
const customAdapter = resolveDriverAdapter("electron");
|
|
3278
|
+
if (customAdapter) {
|
|
3279
|
+
const appId = electronCfg.url ?? electronCfg.entry ?? "electron";
|
|
3280
|
+
const handle = await customAdapter.create({
|
|
3281
|
+
platform: "electron",
|
|
3282
|
+
appId,
|
|
3283
|
+
config,
|
|
3284
|
+
domChannel: bridge,
|
|
3285
|
+
resolvePath: resolveFromConfig
|
|
3286
|
+
});
|
|
3287
|
+
const driver2 = bridge && !handle.driver.domChannel ? { ...handle.driver, domChannel: bridge } : handle.driver;
|
|
3288
|
+
const deviceInfo2 = await Effect2.runPromise(driver2.getDeviceInfo());
|
|
3289
|
+
return {
|
|
3290
|
+
runtime: {
|
|
3291
|
+
driver: driver2,
|
|
3292
|
+
cleanup: () => safeCleanup(
|
|
3293
|
+
() => handle.cleanup(),
|
|
3294
|
+
() => bridge?.disconnect() ?? Promise.resolve()
|
|
3295
|
+
),
|
|
3296
|
+
metadata: {
|
|
3297
|
+
platform: "electron",
|
|
3298
|
+
mode: "local",
|
|
3299
|
+
adapter: customAdapter.name,
|
|
3300
|
+
...handle.metadata
|
|
3301
|
+
}
|
|
3302
|
+
},
|
|
3303
|
+
engineConfig: buildEngineConfig(
|
|
3304
|
+
appId,
|
|
3305
|
+
"electron",
|
|
3306
|
+
handle.parseHierarchy ?? parseWebHierarchy,
|
|
3307
|
+
config,
|
|
3308
|
+
{
|
|
3309
|
+
width: deviceInfo2.screenWidth,
|
|
3310
|
+
height: deviceInfo2.screenHeight
|
|
3311
|
+
}
|
|
3312
|
+
)
|
|
3313
|
+
};
|
|
3314
|
+
}
|
|
3315
|
+
const driver = await Effect2.runPromise(
|
|
2015
3316
|
makeElectronDriver({
|
|
2016
3317
|
entry: electronCfg.entry ? resolveFromConfig(electronCfg.entry) : void 0,
|
|
2017
3318
|
executablePath: electronCfg.executablePath ? resolveFromConfig(electronCfg.executablePath) : void 0,
|
|
@@ -2027,12 +3328,12 @@ async function buildElectronRuntime(config, resolveFromConfig) {
|
|
|
2027
3328
|
domChannel: bridge
|
|
2028
3329
|
})
|
|
2029
3330
|
);
|
|
2030
|
-
const deviceInfo = await
|
|
3331
|
+
const deviceInfo = await Effect2.runPromise(driver.getDeviceInfo());
|
|
2031
3332
|
return {
|
|
2032
3333
|
runtime: {
|
|
2033
3334
|
driver,
|
|
2034
3335
|
cleanup: () => safeCleanup(
|
|
2035
|
-
() =>
|
|
3336
|
+
() => Effect2.runPromise(driver.killApp("")),
|
|
2036
3337
|
() => bridge?.disconnect() ?? Promise.resolve()
|
|
2037
3338
|
),
|
|
2038
3339
|
metadata: {
|
|
@@ -2056,7 +3357,45 @@ async function buildElectronRuntime(config, resolveFromConfig) {
|
|
|
2056
3357
|
async function buildElectrobunRuntime(config, resolveFromConfig) {
|
|
2057
3358
|
const electrobunCfg = config.apps?.electrobun ?? {};
|
|
2058
3359
|
const bridge = await maybeStartBridge(electrobunCfg.bridge, config.execution?.bridge);
|
|
2059
|
-
const
|
|
3360
|
+
const customAdapter = resolveDriverAdapter("electrobun");
|
|
3361
|
+
if (customAdapter) {
|
|
3362
|
+
const appId = electrobunCfg.url ?? electrobunCfg.executablePath ?? "electrobun";
|
|
3363
|
+
const handle = await customAdapter.create({
|
|
3364
|
+
platform: "electrobun",
|
|
3365
|
+
appId,
|
|
3366
|
+
config,
|
|
3367
|
+
domChannel: bridge,
|
|
3368
|
+
resolvePath: resolveFromConfig
|
|
3369
|
+
});
|
|
3370
|
+
const driver2 = bridge && !handle.driver.domChannel ? { ...handle.driver, domChannel: bridge } : handle.driver;
|
|
3371
|
+
const deviceInfo2 = await Effect2.runPromise(driver2.getDeviceInfo());
|
|
3372
|
+
return {
|
|
3373
|
+
runtime: {
|
|
3374
|
+
driver: driver2,
|
|
3375
|
+
cleanup: () => safeCleanup(
|
|
3376
|
+
() => handle.cleanup(),
|
|
3377
|
+
() => bridge?.disconnect() ?? Promise.resolve()
|
|
3378
|
+
),
|
|
3379
|
+
metadata: {
|
|
3380
|
+
platform: "electrobun",
|
|
3381
|
+
mode: "local",
|
|
3382
|
+
adapter: customAdapter.name,
|
|
3383
|
+
...handle.metadata
|
|
3384
|
+
}
|
|
3385
|
+
},
|
|
3386
|
+
engineConfig: buildEngineConfig(
|
|
3387
|
+
appId,
|
|
3388
|
+
"electrobun",
|
|
3389
|
+
handle.parseHierarchy ?? parseWebHierarchy,
|
|
3390
|
+
config,
|
|
3391
|
+
{
|
|
3392
|
+
width: deviceInfo2.screenWidth,
|
|
3393
|
+
height: deviceInfo2.screenHeight
|
|
3394
|
+
}
|
|
3395
|
+
)
|
|
3396
|
+
};
|
|
3397
|
+
}
|
|
3398
|
+
const driver = await Effect2.runPromise(
|
|
2060
3399
|
makeElectrobunDriver({
|
|
2061
3400
|
executablePath: electrobunCfg.executablePath ? resolveFromConfig(electrobunCfg.executablePath) : void 0,
|
|
2062
3401
|
appDir: electrobunCfg.appDir ? resolveFromConfig(electrobunCfg.appDir) : void 0,
|
|
@@ -2074,12 +3413,12 @@ async function buildElectrobunRuntime(config, resolveFromConfig) {
|
|
|
2074
3413
|
domChannel: bridge
|
|
2075
3414
|
})
|
|
2076
3415
|
);
|
|
2077
|
-
const deviceInfo = await
|
|
3416
|
+
const deviceInfo = await Effect2.runPromise(driver.getDeviceInfo());
|
|
2078
3417
|
return {
|
|
2079
3418
|
runtime: {
|
|
2080
3419
|
driver,
|
|
2081
3420
|
cleanup: () => safeCleanup(
|
|
2082
|
-
() =>
|
|
3421
|
+
() => Effect2.runPromise(driver.killApp("")),
|
|
2083
3422
|
() => bridge?.disconnect() ?? Promise.resolve()
|
|
2084
3423
|
),
|
|
2085
3424
|
metadata: {
|
|
@@ -2101,6 +3440,45 @@ async function buildElectrobunRuntime(config, resolveFromConfig) {
|
|
|
2101
3440
|
};
|
|
2102
3441
|
}
|
|
2103
3442
|
async function buildLocalAndroidRuntime(config, targetDevice, resolveFromConfig) {
|
|
3443
|
+
const customAdapter = resolveDriverAdapter("android");
|
|
3444
|
+
if (customAdapter) {
|
|
3445
|
+
const packageName2 = config.apps?.android?.packageName ?? "";
|
|
3446
|
+
const bridge2 = await maybeStartBridge(config.apps?.android?.bridge, config.execution?.bridge);
|
|
3447
|
+
const handle = await customAdapter.create({
|
|
3448
|
+
platform: "android",
|
|
3449
|
+
appId: packageName2,
|
|
3450
|
+
config,
|
|
3451
|
+
domChannel: bridge2,
|
|
3452
|
+
resolvePath: resolveFromConfig
|
|
3453
|
+
});
|
|
3454
|
+
const driver = bridge2 && !handle.driver.domChannel ? { ...handle.driver, domChannel: bridge2 } : handle.driver;
|
|
3455
|
+
const deviceInfo = await Effect2.runPromise(driver.getDeviceInfo());
|
|
3456
|
+
return {
|
|
3457
|
+
runtime: {
|
|
3458
|
+
driver,
|
|
3459
|
+
cleanup: () => safeCleanup(
|
|
3460
|
+
() => handle.cleanup(),
|
|
3461
|
+
() => bridge2?.disconnect() ?? Promise.resolve()
|
|
3462
|
+
),
|
|
3463
|
+
metadata: {
|
|
3464
|
+
platform: "android",
|
|
3465
|
+
mode: "local",
|
|
3466
|
+
adapter: customAdapter.name,
|
|
3467
|
+
...handle.metadata
|
|
3468
|
+
}
|
|
3469
|
+
},
|
|
3470
|
+
engineConfig: buildEngineConfig(
|
|
3471
|
+
packageName2,
|
|
3472
|
+
"android",
|
|
3473
|
+
handle.parseHierarchy ?? parseAndroidHierarchy,
|
|
3474
|
+
config,
|
|
3475
|
+
{
|
|
3476
|
+
width: deviceInfo.screenWidth,
|
|
3477
|
+
height: deviceInfo.screenHeight
|
|
3478
|
+
}
|
|
3479
|
+
)
|
|
3480
|
+
};
|
|
3481
|
+
}
|
|
2104
3482
|
const device = targetDevice?.platform === "android" ? {
|
|
2105
3483
|
serial: targetDevice.id,
|
|
2106
3484
|
state: "device",
|
|
@@ -2114,7 +3492,7 @@ async function buildLocalAndroidRuntime(config, targetDevice, resolveFromConfig)
|
|
|
2114
3492
|
const androidAppPath = config.apps?.android?.appPath;
|
|
2115
3493
|
if (androidAppPath && packageName) {
|
|
2116
3494
|
try {
|
|
2117
|
-
const { adbShell, adbInstall } = await import("./android-
|
|
3495
|
+
const { adbShell, adbInstall } = await import("./android-C2S4B4TH.js");
|
|
2118
3496
|
const output = adbShell(device.serial, `pm list packages ${packageName}`);
|
|
2119
3497
|
if (!output.includes(packageName)) {
|
|
2120
3498
|
console.log(`Installing ${packageName} on Android device...`);
|
|
@@ -2122,7 +3500,7 @@ async function buildLocalAndroidRuntime(config, targetDevice, resolveFromConfig)
|
|
|
2122
3500
|
}
|
|
2123
3501
|
} catch {
|
|
2124
3502
|
console.log(`Installing ${packageName} on Android device...`);
|
|
2125
|
-
const { adbInstall } = await import("./android-
|
|
3503
|
+
const { adbInstall } = await import("./android-C2S4B4TH.js");
|
|
2126
3504
|
adbInstall(device.serial, resolveFromConfig(androidAppPath));
|
|
2127
3505
|
}
|
|
2128
3506
|
}
|
|
@@ -2141,18 +3519,18 @@ async function buildLocalAndroidRuntime(config, targetDevice, resolveFromConfig)
|
|
|
2141
3519
|
warm: warmDaemons?.enabled,
|
|
2142
3520
|
daemonStateFile: warmDaemons?.stateFile
|
|
2143
3521
|
});
|
|
2144
|
-
const driver = await
|
|
3522
|
+
const driver = await Effect2.runPromise(
|
|
2145
3523
|
createUiAutomator2Driver(conn.host, conn.port, device.serial, packageName, {
|
|
2146
3524
|
domChannel: bridge,
|
|
2147
3525
|
cdpPort: config.apps?.android?.cdpPort
|
|
2148
3526
|
})
|
|
2149
3527
|
);
|
|
2150
|
-
const deviceInfo = await
|
|
3528
|
+
const deviceInfo = await Effect2.runPromise(driver.getDeviceInfo());
|
|
2151
3529
|
return {
|
|
2152
3530
|
runtime: {
|
|
2153
3531
|
driver,
|
|
2154
3532
|
cleanup: () => safeCleanup(
|
|
2155
|
-
() =>
|
|
3533
|
+
() => Effect2.runPromise(driver.killApp("")),
|
|
2156
3534
|
() => bridge?.disconnect() ?? Promise.resolve(),
|
|
2157
3535
|
() => {
|
|
2158
3536
|
if (reversedBridgePort !== null) {
|
|
@@ -2181,6 +3559,45 @@ async function buildLocalAndroidRuntime(config, targetDevice, resolveFromConfig)
|
|
|
2181
3559
|
}
|
|
2182
3560
|
}
|
|
2183
3561
|
async function buildLocalIOSRuntime(config, targetDevice, resolveFromConfig) {
|
|
3562
|
+
const customAdapter = resolveDriverAdapter("ios");
|
|
3563
|
+
if (customAdapter) {
|
|
3564
|
+
const bundleId2 = config.apps?.ios?.bundleId ?? "";
|
|
3565
|
+
const bridge2 = await maybeStartBridge(config.apps?.ios?.bridge, config.execution?.bridge);
|
|
3566
|
+
const handle = await customAdapter.create({
|
|
3567
|
+
platform: "ios",
|
|
3568
|
+
appId: bundleId2,
|
|
3569
|
+
config,
|
|
3570
|
+
domChannel: bridge2,
|
|
3571
|
+
resolvePath: resolveFromConfig
|
|
3572
|
+
});
|
|
3573
|
+
const driver = bridge2 && !handle.driver.domChannel ? { ...handle.driver, domChannel: bridge2 } : handle.driver;
|
|
3574
|
+
const deviceInfo = await Effect2.runPromise(driver.getDeviceInfo());
|
|
3575
|
+
return {
|
|
3576
|
+
runtime: {
|
|
3577
|
+
driver,
|
|
3578
|
+
cleanup: () => safeCleanup(
|
|
3579
|
+
() => handle.cleanup(),
|
|
3580
|
+
() => bridge2?.disconnect() ?? Promise.resolve()
|
|
3581
|
+
),
|
|
3582
|
+
metadata: {
|
|
3583
|
+
platform: "ios",
|
|
3584
|
+
mode: "local",
|
|
3585
|
+
adapter: customAdapter.name,
|
|
3586
|
+
...handle.metadata
|
|
3587
|
+
}
|
|
3588
|
+
},
|
|
3589
|
+
engineConfig: buildEngineConfig(
|
|
3590
|
+
bundleId2,
|
|
3591
|
+
"ios",
|
|
3592
|
+
handle.parseHierarchy ?? parseIOSHierarchy,
|
|
3593
|
+
config,
|
|
3594
|
+
{
|
|
3595
|
+
width: deviceInfo.screenWidth,
|
|
3596
|
+
height: deviceInfo.screenHeight
|
|
3597
|
+
}
|
|
3598
|
+
)
|
|
3599
|
+
};
|
|
3600
|
+
}
|
|
2184
3601
|
const bundleId = config.apps?.ios?.bundleId ?? "";
|
|
2185
3602
|
const iosAppPath = config.apps?.ios?.appPath;
|
|
2186
3603
|
const signing = config.apps?.ios?.signing;
|
|
@@ -2189,7 +3606,7 @@ async function buildLocalIOSRuntime(config, targetDevice, resolveFromConfig) {
|
|
|
2189
3606
|
const bridge = await maybeStartBridge(config.apps?.ios?.bridge, config.execution?.bridge);
|
|
2190
3607
|
const createIOSRuntime = async (deviceId, conn, simulatorUdid) => {
|
|
2191
3608
|
const reuseSession = warmDaemons?.enabled && warmDaemons.reuseSession !== false;
|
|
2192
|
-
const driver = await
|
|
3609
|
+
const driver = await Effect2.runPromise(
|
|
2193
3610
|
createWDADriver(conn.host, conn.port, bundleId, simulatorUdid, snapshotMaxDepth, {
|
|
2194
3611
|
domChannel: bridge,
|
|
2195
3612
|
webkitInspectorUrl: config.apps?.ios?.webkitInspectorUrl,
|
|
@@ -2199,12 +3616,12 @@ async function buildLocalIOSRuntime(config, targetDevice, resolveFromConfig) {
|
|
|
2199
3616
|
onSessionCreated: reuseSession ? (sessionId) => updateWarmDaemonSession("wda", deviceId, sessionId, bundleId, warmDaemons?.stateFile) : void 0
|
|
2200
3617
|
})
|
|
2201
3618
|
);
|
|
2202
|
-
const deviceInfo = await
|
|
3619
|
+
const deviceInfo = await Effect2.runPromise(driver.getDeviceInfo());
|
|
2203
3620
|
return {
|
|
2204
3621
|
runtime: {
|
|
2205
3622
|
driver,
|
|
2206
3623
|
cleanup: () => safeCleanup(
|
|
2207
|
-
() =>
|
|
3624
|
+
() => Effect2.runPromise(driver.killApp("")),
|
|
2208
3625
|
() => bridge?.disconnect() ?? Promise.resolve(),
|
|
2209
3626
|
() => conn.cleanup?.() ?? Promise.resolve()
|
|
2210
3627
|
),
|
|
@@ -2233,7 +3650,7 @@ async function buildLocalIOSRuntime(config, targetDevice, resolveFromConfig) {
|
|
|
2233
3650
|
});
|
|
2234
3651
|
}
|
|
2235
3652
|
if (signing?.teamId) {
|
|
2236
|
-
const { setupWDAForDevice } = await import("./installer-
|
|
3653
|
+
const { setupWDAForDevice } = await import("./installer-DMTY47SI.js");
|
|
2237
3654
|
const wdaPort2 = allocatePort(8100);
|
|
2238
3655
|
conn = await setupWDAForDevice(
|
|
2239
3656
|
physicalDevice2.udid,
|
|
@@ -2335,1872 +3752,21 @@ async function buildLocalIOSRuntime(config, targetDevice, resolveFromConfig) {
|
|
|
2335
3752
|
}
|
|
2336
3753
|
}
|
|
2337
3754
|
|
|
2338
|
-
// src/report/code-frame.ts
|
|
2339
|
-
import { existsSync as existsSync2, readFileSync } from "fs";
|
|
2340
|
-
import { fileURLToPath } from "url";
|
|
2341
|
-
var INTERNAL_FRAME_PATTERNS = [
|
|
2342
|
-
/node_modules\//,
|
|
2343
|
-
/^node:/,
|
|
2344
|
-
/^bun:/,
|
|
2345
|
-
/^internal\//,
|
|
2346
|
-
/\/packages\/spana\/(?:src|dist)\/(?!.*\.test\.[jt]sx?$)/,
|
|
2347
|
-
/\/spana(?:-test)?\/dist\//
|
|
2348
|
-
];
|
|
2349
|
-
function normalizeStackFile(raw) {
|
|
2350
|
-
const trimmed = raw.trim();
|
|
2351
|
-
if (trimmed.startsWith("file://")) {
|
|
2352
|
-
try {
|
|
2353
|
-
return fileURLToPath(trimmed);
|
|
2354
|
-
} catch {
|
|
2355
|
-
return trimmed.replace(/^file:\/\//, "");
|
|
2356
|
-
}
|
|
2357
|
-
}
|
|
2358
|
-
return trimmed;
|
|
2359
|
-
}
|
|
2360
|
-
function parseStackFrames(stack) {
|
|
2361
|
-
const frames = [];
|
|
2362
|
-
for (const rawLine of stack.split("\n")) {
|
|
2363
|
-
const line = rawLine.trim();
|
|
2364
|
-
if (!line.startsWith("at ")) continue;
|
|
2365
|
-
const match = line.match(/\((.+):(\d+):(\d+)\)$/) ?? line.match(/^at\s+(.+):(\d+):(\d+)$/);
|
|
2366
|
-
if (!match) continue;
|
|
2367
|
-
const file = normalizeStackFile(match[1]);
|
|
2368
|
-
const lineNum = Number.parseInt(match[2], 10);
|
|
2369
|
-
const colNum = Number.parseInt(match[3], 10);
|
|
2370
|
-
if (!file || !Number.isFinite(lineNum) || lineNum < 1) continue;
|
|
2371
|
-
frames.push({
|
|
2372
|
-
file,
|
|
2373
|
-
line: lineNum,
|
|
2374
|
-
column: Number.isFinite(colNum) && colNum > 0 ? colNum : 1
|
|
2375
|
-
});
|
|
2376
|
-
}
|
|
2377
|
-
return frames;
|
|
2378
|
-
}
|
|
2379
|
-
function isInternalFrame(file) {
|
|
2380
|
-
const normalized = file.replaceAll("\\", "/");
|
|
2381
|
-
return INTERNAL_FRAME_PATTERNS.some((re) => re.test(normalized));
|
|
2382
|
-
}
|
|
2383
|
-
function formatCodeFrame(source, line, column, contextLines = 3) {
|
|
2384
|
-
const lines = source.split(/\r?\n/);
|
|
2385
|
-
if (line < 1 || line > lines.length) return "";
|
|
2386
|
-
const startLine = Math.max(1, line - contextLines);
|
|
2387
|
-
const endLine = Math.min(lines.length, line + contextLines);
|
|
2388
|
-
const gutterWidth = String(endLine).length;
|
|
2389
|
-
const out = [];
|
|
2390
|
-
for (let current = startLine; current <= endLine; current++) {
|
|
2391
|
-
const marker = current === line ? ">" : " ";
|
|
2392
|
-
const num = String(current).padStart(gutterWidth, " ");
|
|
2393
|
-
const content = lines[current - 1] ?? "";
|
|
2394
|
-
out.push(`${marker} ${num} | ${content}`);
|
|
2395
|
-
if (current === line) {
|
|
2396
|
-
const caretOffset = Math.max(0, Math.min(column - 1, content.length));
|
|
2397
|
-
out.push(` ${" ".repeat(gutterWidth)} | ${" ".repeat(caretOffset)}^`);
|
|
2398
|
-
}
|
|
2399
|
-
}
|
|
2400
|
-
return out.join("\n");
|
|
2401
|
-
}
|
|
2402
|
-
function extractCodeFrame(stack, preferredFile, contextLines = 3) {
|
|
2403
|
-
if (!stack) return void 0;
|
|
2404
|
-
const frames = parseStackFrames(stack);
|
|
2405
|
-
if (frames.length === 0) return void 0;
|
|
2406
|
-
const normalizedPreferred = preferredFile ? normalizeStackFile(preferredFile) : void 0;
|
|
2407
|
-
let chosen = normalizedPreferred ? frames.find(
|
|
2408
|
-
(f) => (f.file === normalizedPreferred || f.file.endsWith(normalizedPreferred)) && existsSync2(f.file)
|
|
2409
|
-
) : void 0;
|
|
2410
|
-
if (!chosen) {
|
|
2411
|
-
chosen = frames.find((f) => /\.flow\.[cm]?[jt]sx?$/.test(f.file) && existsSync2(f.file));
|
|
2412
|
-
}
|
|
2413
|
-
if (!chosen) {
|
|
2414
|
-
chosen = frames.find((f) => !isInternalFrame(f.file) && existsSync2(f.file));
|
|
2415
|
-
}
|
|
2416
|
-
if (!chosen) return void 0;
|
|
2417
|
-
try {
|
|
2418
|
-
const source = readFileSync(chosen.file, "utf8");
|
|
2419
|
-
const frame = formatCodeFrame(source, chosen.line, chosen.column, contextLines);
|
|
2420
|
-
if (!frame) return void 0;
|
|
2421
|
-
return {
|
|
2422
|
-
location: { file: chosen.file, line: chosen.line, column: chosen.column },
|
|
2423
|
-
frame
|
|
2424
|
-
};
|
|
2425
|
-
} catch {
|
|
2426
|
-
return void 0;
|
|
2427
|
-
}
|
|
2428
|
-
}
|
|
2429
|
-
|
|
2430
|
-
// src/core/video-recorder.ts
|
|
2431
|
-
import { execFileSync, spawn as spawn2 } from "child_process";
|
|
2432
|
-
import {
|
|
2433
|
-
existsSync as existsSync3,
|
|
2434
|
-
mkdirSync,
|
|
2435
|
-
mkdtempSync as mkdtempSync2,
|
|
2436
|
-
readFileSync as readFileSync2,
|
|
2437
|
-
rmSync as rmSync2,
|
|
2438
|
-
unlinkSync,
|
|
2439
|
-
writeFileSync
|
|
2440
|
-
} from "fs";
|
|
2441
|
-
import { tmpdir as tmpdir2 } from "os";
|
|
2442
|
-
import { join as join2 } from "path";
|
|
2443
|
-
function hasFfmpegOnPath() {
|
|
2444
|
-
try {
|
|
2445
|
-
execFileSync(process.platform === "win32" ? "where" : "which", ["ffmpeg"], {
|
|
2446
|
-
stdio: "ignore"
|
|
2447
|
-
});
|
|
2448
|
-
return true;
|
|
2449
|
-
} catch {
|
|
2450
|
-
return false;
|
|
2451
|
-
}
|
|
2452
|
-
}
|
|
2453
|
-
async function exportFramesToMp4(frames, outputPath, spawnFn = spawn2) {
|
|
2454
|
-
if (frames.length === 0 || !hasFfmpegOnPath()) return void 0;
|
|
2455
|
-
const tempDir = mkdtempSync2(join2(tmpdir2(), "spana-vid-"));
|
|
2456
|
-
try {
|
|
2457
|
-
const ext = frames[0].mimeType === "image/png" ? "png" : "jpg";
|
|
2458
|
-
const listLines = [];
|
|
2459
|
-
for (let i = 0; i < frames.length; i++) {
|
|
2460
|
-
const f = frames[i];
|
|
2461
|
-
const framePath = join2(tempDir, `frame-${String(i).padStart(5, "0")}.${ext}`);
|
|
2462
|
-
writeFileSync(framePath, Buffer.from(f.dataBase64, "base64"));
|
|
2463
|
-
const nextTs = frames[i + 1]?.timestampMs ?? f.timestampMs + 250;
|
|
2464
|
-
const durSec = Math.max(0.05, Math.min(2, (nextTs - f.timestampMs) / 1e3));
|
|
2465
|
-
listLines.push(`file '${framePath.replaceAll("'", "'\\''")}'`);
|
|
2466
|
-
listLines.push(`duration ${durSec.toFixed(3)}`);
|
|
2467
|
-
}
|
|
2468
|
-
const lastPath = join2(tempDir, `frame-${String(frames.length - 1).padStart(5, "0")}.${ext}`);
|
|
2469
|
-
listLines.push(`file '${lastPath.replaceAll("'", "'\\''")}'`);
|
|
2470
|
-
const listFile = join2(tempDir, "frames.txt");
|
|
2471
|
-
writeFileSync(listFile, listLines.join("\n"), "utf8");
|
|
2472
|
-
const ok = await new Promise((resolve) => {
|
|
2473
|
-
const child = spawnFn(
|
|
2474
|
-
"ffmpeg",
|
|
2475
|
-
[
|
|
2476
|
-
"-y",
|
|
2477
|
-
"-f",
|
|
2478
|
-
"concat",
|
|
2479
|
-
"-safe",
|
|
2480
|
-
"0",
|
|
2481
|
-
"-i",
|
|
2482
|
-
listFile,
|
|
2483
|
-
"-vf",
|
|
2484
|
-
"pad=ceil(iw/2)*2:ceil(ih/2)*2",
|
|
2485
|
-
"-c:v",
|
|
2486
|
-
"libx264",
|
|
2487
|
-
"-pix_fmt",
|
|
2488
|
-
"yuv420p",
|
|
2489
|
-
"-movflags",
|
|
2490
|
-
"+faststart",
|
|
2491
|
-
outputPath
|
|
2492
|
-
],
|
|
2493
|
-
{ stdio: "ignore" }
|
|
2494
|
-
);
|
|
2495
|
-
child.on("error", () => resolve(false));
|
|
2496
|
-
child.on("close", (code) => resolve(code === 0));
|
|
2497
|
-
});
|
|
2498
|
-
return ok && existsSync3(outputPath) ? outputPath : void 0;
|
|
2499
|
-
} catch {
|
|
2500
|
-
return void 0;
|
|
2501
|
-
} finally {
|
|
2502
|
-
try {
|
|
2503
|
-
rmSync2(tempDir, { recursive: true, force: true });
|
|
2504
|
-
} catch {
|
|
2505
|
-
}
|
|
2506
|
-
}
|
|
2507
|
-
}
|
|
2508
|
-
async function startCdpScreencastRecorder(cdp, options) {
|
|
2509
|
-
const startedAt = Date.now();
|
|
2510
|
-
const startedAtIso = new Date(startedAt).toISOString();
|
|
2511
|
-
const maxFrames = options.maxFrames ?? 180;
|
|
2512
|
-
const frames = [];
|
|
2513
|
-
let stopped = false;
|
|
2514
|
-
const unsubscribe = cdp.onEvent("Page.screencastFrame", (params) => {
|
|
2515
|
-
if (stopped) return;
|
|
2516
|
-
const sessionId = params?.sessionId;
|
|
2517
|
-
if (sessionId !== void 0) {
|
|
2518
|
-
void cdp.sendCommand("Page.screencastFrameAck", { sessionId }).catch(() => {
|
|
2519
|
-
});
|
|
2520
|
-
}
|
|
2521
|
-
if (typeof params?.data === "string" && params.data.length > 0) {
|
|
2522
|
-
if (frames.length >= maxFrames) {
|
|
2523
|
-
frames.splice(1, 1);
|
|
2524
|
-
}
|
|
2525
|
-
frames.push({
|
|
2526
|
-
timestampMs: Math.max(0, Date.now() - startedAt),
|
|
2527
|
-
dataBase64: params.data,
|
|
2528
|
-
mimeType: "image/jpeg"
|
|
2529
|
-
});
|
|
2530
|
-
}
|
|
2531
|
-
});
|
|
2532
|
-
await cdp.sendCommand("Page.startScreencast", {
|
|
2533
|
-
format: "jpeg",
|
|
2534
|
-
quality: options.quality ?? 65,
|
|
2535
|
-
maxWidth: options.maxWidth ?? 1280,
|
|
2536
|
-
maxHeight: options.maxHeight ?? 720,
|
|
2537
|
-
everyNthFrame: options.everyNthFrame ?? 2
|
|
2538
|
-
}).catch(() => {
|
|
2539
|
-
});
|
|
2540
|
-
return {
|
|
2541
|
-
stop: async (stopOpts) => {
|
|
2542
|
-
if (stopped) return { frameCount: frames.length };
|
|
2543
|
-
stopped = true;
|
|
2544
|
-
unsubscribe();
|
|
2545
|
-
await cdp.sendCommand("Page.stopScreencast").catch(() => {
|
|
2546
|
-
});
|
|
2547
|
-
if (!stopOpts.keep) {
|
|
2548
|
-
return { frameCount: 0 };
|
|
2549
|
-
}
|
|
2550
|
-
if (frames.length === 0) {
|
|
2551
|
-
try {
|
|
2552
|
-
const snap = await cdp.sendCommand("Page.captureScreenshot", {
|
|
2553
|
-
format: "jpeg",
|
|
2554
|
-
quality: options.quality ?? 65
|
|
2555
|
-
});
|
|
2556
|
-
if (typeof snap?.data === "string" && snap.data.length > 0) {
|
|
2557
|
-
frames.push({
|
|
2558
|
-
timestampMs: Math.max(0, Date.now() - startedAt),
|
|
2559
|
-
dataBase64: snap.data,
|
|
2560
|
-
mimeType: "image/jpeg"
|
|
2561
|
-
});
|
|
2562
|
-
}
|
|
2563
|
-
} catch {
|
|
2564
|
-
}
|
|
2565
|
-
}
|
|
2566
|
-
if (frames.length === 0) {
|
|
2567
|
-
return { frameCount: 0 };
|
|
2568
|
-
}
|
|
2569
|
-
mkdirSync(stopOpts.outputDir, { recursive: true });
|
|
2570
|
-
let videoPath;
|
|
2571
|
-
if (options.exportMp4 !== false) {
|
|
2572
|
-
const mp4Target = join2(stopOpts.outputDir, `${stopOpts.fileStem}.mp4`);
|
|
2573
|
-
videoPath = await exportFramesToMp4(frames, mp4Target, options.spawnFn);
|
|
2574
|
-
}
|
|
2575
|
-
const trace = {
|
|
2576
|
-
version: 1,
|
|
2577
|
-
flowName: options.flowName,
|
|
2578
|
-
platform: options.platform,
|
|
2579
|
-
startedAtIso,
|
|
2580
|
-
durationMs: Math.max(1, Date.now() - startedAt),
|
|
2581
|
-
viewport: stopOpts.viewport,
|
|
2582
|
-
frames,
|
|
2583
|
-
steps: stopOpts.steps ?? [],
|
|
2584
|
-
...videoPath ? { videoPath } : {}
|
|
2585
|
-
};
|
|
2586
|
-
const playbackJsonPath = join2(stopOpts.outputDir, `${stopOpts.fileStem}-playback.json`);
|
|
2587
|
-
writeFileSync(playbackJsonPath, JSON.stringify(trace), "utf8");
|
|
2588
|
-
return { playbackJsonPath, videoPath, frameCount: frames.length };
|
|
2589
|
-
}
|
|
2590
|
-
};
|
|
2591
|
-
}
|
|
2592
|
-
function startAndroidVideoRecorder(serial, options) {
|
|
2593
|
-
const spawnFn = options.spawnFn ?? spawn2;
|
|
2594
|
-
const execSyncFn = options.execFileSyncFn ?? execFileSync;
|
|
2595
|
-
const remotePath = `/sdcard/spana-rec-${Date.now()}-${Math.floor(Math.random() * 1e4)}.mp4`;
|
|
2596
|
-
const child = spawnFn(
|
|
2597
|
-
"adb",
|
|
2598
|
-
["-s", serial, "shell", "screenrecord", "--time-limit", "180", remotePath],
|
|
2599
|
-
{ stdio: "ignore" }
|
|
2600
|
-
);
|
|
2601
|
-
let stopped = false;
|
|
2602
|
-
return {
|
|
2603
|
-
stop: async ({ keep }) => {
|
|
2604
|
-
if (stopped) return { frameCount: 0 };
|
|
2605
|
-
stopped = true;
|
|
2606
|
-
try {
|
|
2607
|
-
child.kill("SIGINT");
|
|
2608
|
-
} catch {
|
|
2609
|
-
}
|
|
2610
|
-
await new Promise((resolve) => {
|
|
2611
|
-
const timer = setTimeout(resolve, 1200);
|
|
2612
|
-
child.once("close", () => {
|
|
2613
|
-
clearTimeout(timer);
|
|
2614
|
-
resolve();
|
|
2615
|
-
});
|
|
2616
|
-
});
|
|
2617
|
-
let savedPath;
|
|
2618
|
-
if (keep) {
|
|
2619
|
-
try {
|
|
2620
|
-
execSyncFn("adb", ["-s", serial, "pull", remotePath, options.outputPath], {
|
|
2621
|
-
stdio: "ignore"
|
|
2622
|
-
});
|
|
2623
|
-
if (existsSync3(options.outputPath)) savedPath = options.outputPath;
|
|
2624
|
-
} catch {
|
|
2625
|
-
}
|
|
2626
|
-
}
|
|
2627
|
-
try {
|
|
2628
|
-
execSyncFn("adb", ["-s", serial, "shell", "rm", "-f", remotePath], { stdio: "ignore" });
|
|
2629
|
-
} catch {
|
|
2630
|
-
}
|
|
2631
|
-
return { videoPath: savedPath, frameCount: savedPath ? 1 : 0 };
|
|
2632
|
-
}
|
|
2633
|
-
};
|
|
2634
|
-
}
|
|
2635
|
-
function startIosSimulatorVideoRecorder(udid, options) {
|
|
2636
|
-
const spawnFn = options.spawnFn ?? spawn2;
|
|
2637
|
-
const child = spawnFn(
|
|
2638
|
-
"xcrun",
|
|
2639
|
-
["simctl", "io", udid, "recordVideo", "--codec=h264", "--force", options.outputPath],
|
|
2640
|
-
{ stdio: "ignore" }
|
|
2641
|
-
);
|
|
2642
|
-
let stopped = false;
|
|
2643
|
-
return {
|
|
2644
|
-
stop: async ({ keep }) => {
|
|
2645
|
-
if (stopped) return { frameCount: 0 };
|
|
2646
|
-
stopped = true;
|
|
2647
|
-
try {
|
|
2648
|
-
child.kill("SIGINT");
|
|
2649
|
-
} catch {
|
|
2650
|
-
}
|
|
2651
|
-
await new Promise((resolve) => {
|
|
2652
|
-
const timer = setTimeout(resolve, 1500);
|
|
2653
|
-
child.once("close", () => {
|
|
2654
|
-
clearTimeout(timer);
|
|
2655
|
-
resolve();
|
|
2656
|
-
});
|
|
2657
|
-
});
|
|
2658
|
-
if (!keep) {
|
|
2659
|
-
try {
|
|
2660
|
-
if (existsSync3(options.outputPath)) unlinkSync(options.outputPath);
|
|
2661
|
-
} catch {
|
|
2662
|
-
}
|
|
2663
|
-
return { frameCount: 0 };
|
|
2664
|
-
}
|
|
2665
|
-
return {
|
|
2666
|
-
videoPath: existsSync3(options.outputPath) ? options.outputPath : void 0,
|
|
2667
|
-
frameCount: existsSync3(options.outputPath) ? 1 : 0
|
|
2668
|
-
};
|
|
2669
|
-
}
|
|
2670
|
-
};
|
|
2671
|
-
}
|
|
2672
|
-
function buildPlaybackTraceFromSteps(input) {
|
|
2673
|
-
const frames = [];
|
|
2674
|
-
const markers = [];
|
|
2675
|
-
let cursorMs = 0;
|
|
2676
|
-
for (let i = 0; i < input.steps.length; i++) {
|
|
2677
|
-
const step = input.steps[i];
|
|
2678
|
-
const tapPoint = extractTapPointFromStep(step);
|
|
2679
|
-
markers.push({
|
|
2680
|
-
index: i,
|
|
2681
|
-
command: step.command,
|
|
2682
|
-
selector: step.selector,
|
|
2683
|
-
startedAtMs: cursorMs,
|
|
2684
|
-
durationMs: step.durationMs,
|
|
2685
|
-
status: step.status,
|
|
2686
|
-
error: step.error,
|
|
2687
|
-
...tapPoint ? { tapPoint } : {}
|
|
2688
|
-
});
|
|
2689
|
-
const img = step.attachments?.find(
|
|
2690
|
-
(a) => a.contentType === "image/png" || a.contentType === "image/jpeg"
|
|
2691
|
-
);
|
|
2692
|
-
if (img && existsSync3(img.path)) {
|
|
2693
|
-
try {
|
|
2694
|
-
const dataBase64 = readFileSync2(img.path).toString("base64");
|
|
2695
|
-
frames.push({
|
|
2696
|
-
timestampMs: cursorMs + step.durationMs,
|
|
2697
|
-
dataBase64,
|
|
2698
|
-
mimeType: img.contentType === "image/jpeg" ? "image/jpeg" : "image/png"
|
|
2699
|
-
});
|
|
2700
|
-
} catch {
|
|
2701
|
-
}
|
|
2702
|
-
}
|
|
2703
|
-
cursorMs += Math.max(1, step.durationMs);
|
|
2704
|
-
}
|
|
2705
|
-
if (frames.length === 0 && !input.videoPath) return null;
|
|
2706
|
-
return {
|
|
2707
|
-
version: 1,
|
|
2708
|
-
flowName: input.flowName,
|
|
2709
|
-
platform: input.platform,
|
|
2710
|
-
startedAtIso: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2711
|
-
durationMs: Math.max(1, input.durationMs),
|
|
2712
|
-
viewport: input.viewport,
|
|
2713
|
-
frames,
|
|
2714
|
-
steps: markers,
|
|
2715
|
-
...input.videoPath ? { videoPath: input.videoPath } : {}
|
|
2716
|
-
};
|
|
2717
|
-
}
|
|
2718
|
-
function extractTapPointFromStep(step) {
|
|
2719
|
-
const sel = step.selector;
|
|
2720
|
-
if (!sel || typeof sel !== "object") return void 0;
|
|
2721
|
-
const pt = sel["point"];
|
|
2722
|
-
if (pt && typeof pt["x"] === "number" && typeof pt["y"] === "number") {
|
|
2723
|
-
return { x: pt["x"], y: pt["y"] };
|
|
2724
|
-
}
|
|
2725
|
-
return void 0;
|
|
2726
|
-
}
|
|
2727
|
-
|
|
2728
|
-
// src/core/engine.ts
|
|
2729
|
-
import { Effect as Effect6 } from "effect";
|
|
2730
|
-
|
|
2731
|
-
// src/core/artifacts.ts
|
|
2732
|
-
import { writeFileSync as writeFileSync2, mkdirSync as mkdirSync2 } from "fs";
|
|
2733
|
-
import { join as join3 } from "path";
|
|
2734
|
-
import { Effect as Effect4 } from "effect";
|
|
2735
|
-
var DEFAULT_ARTIFACT_CONFIG = {
|
|
2736
|
-
outputDir: "./spana-output",
|
|
2737
|
-
captureOnFailure: true,
|
|
2738
|
-
captureOnSuccess: false,
|
|
2739
|
-
captureSteps: false,
|
|
2740
|
-
screenshot: true,
|
|
2741
|
-
uiHierarchy: true,
|
|
2742
|
-
consoleLogs: true,
|
|
2743
|
-
jsErrors: true,
|
|
2744
|
-
har: true,
|
|
2745
|
-
jsCoverage: false,
|
|
2746
|
-
video: "off",
|
|
2747
|
-
playback: false
|
|
2748
|
-
};
|
|
2749
|
-
function safeArtifactName(value) {
|
|
2750
|
-
return value.replaceAll(/[^a-zA-Z0-9-_]/g, "_").replaceAll(/_+/g, "_").replaceAll(/^_+|_+$/g, "").slice(0, 80) || "artifact";
|
|
2751
|
-
}
|
|
2752
|
-
var safeName = safeArtifactName;
|
|
2753
|
-
function flowArtifactDir(config, flowName, platform) {
|
|
2754
|
-
const dir = join3(config.outputDir, `${safeName(flowName)}-${platform}`);
|
|
2755
|
-
mkdirSync2(dir, { recursive: true });
|
|
2756
|
-
return dir;
|
|
2757
|
-
}
|
|
2758
|
-
function createAttachment(name, contentType, path) {
|
|
2759
|
-
return { name, contentType, path };
|
|
2760
|
-
}
|
|
2761
|
-
function writeJsonAttachment(dir, fileName, attachmentName, value) {
|
|
2762
|
-
const path = join3(dir, fileName);
|
|
2763
|
-
writeFileSync2(path, JSON.stringify(value, null, 2), "utf-8");
|
|
2764
|
-
return createAttachment(attachmentName, "application/json", path);
|
|
2765
|
-
}
|
|
2766
|
-
function writeTextAttachment(dir, fileName, attachmentName, value) {
|
|
2767
|
-
const path = join3(dir, fileName);
|
|
2768
|
-
writeFileSync2(path, value, "utf-8");
|
|
2769
|
-
return createAttachment(attachmentName, "text/plain", path);
|
|
2770
|
-
}
|
|
2771
|
-
function resolveArtifactConfig(...configs) {
|
|
2772
|
-
return configs.reduce(
|
|
2773
|
-
(resolved, config) => ({
|
|
2774
|
-
...resolved,
|
|
2775
|
-
...config
|
|
2776
|
-
}),
|
|
2777
|
-
{ ...DEFAULT_ARTIFACT_CONFIG }
|
|
2778
|
-
);
|
|
2779
|
-
}
|
|
2780
|
-
async function captureArtifacts(driver, config, flowName, platform, status) {
|
|
2781
|
-
const shouldCapture = status === "failed" && config.captureOnFailure || status === "passed" && config.captureOnSuccess;
|
|
2782
|
-
if (!shouldCapture) return [];
|
|
2783
|
-
const attachments = [];
|
|
2784
|
-
const dir = flowArtifactDir(config, flowName, platform);
|
|
2785
|
-
if (config.screenshot) {
|
|
2786
|
-
try {
|
|
2787
|
-
const screenshot = await Effect4.runPromise(Effect4.orDie(driver.takeScreenshot()));
|
|
2788
|
-
const path = join3(dir, "screenshot.png");
|
|
2789
|
-
writeFileSync2(path, screenshot);
|
|
2790
|
-
attachments.push(createAttachment(`${status}-screenshot`, "image/png", path));
|
|
2791
|
-
} catch {
|
|
2792
|
-
}
|
|
2793
|
-
}
|
|
2794
|
-
if (config.uiHierarchy) {
|
|
2795
|
-
try {
|
|
2796
|
-
const hierarchy = await Effect4.runPromise(Effect4.orDie(driver.dumpHierarchy()));
|
|
2797
|
-
const path = join3(dir, "hierarchy.json");
|
|
2798
|
-
writeFileSync2(path, hierarchy, "utf-8");
|
|
2799
|
-
attachments.push(createAttachment(`${status}-hierarchy`, "application/json", path));
|
|
2800
|
-
} catch {
|
|
2801
|
-
}
|
|
2802
|
-
}
|
|
2803
|
-
if (config.consoleLogs && driver.getConsoleLogs) {
|
|
2804
|
-
try {
|
|
2805
|
-
const consoleLogs = await Effect4.runPromise(Effect4.orDie(driver.getConsoleLogs()));
|
|
2806
|
-
if (consoleLogs.length > 0) {
|
|
2807
|
-
attachments.push(
|
|
2808
|
-
writeJsonAttachment(dir, "console-logs.json", `${status}-console-logs`, consoleLogs)
|
|
2809
|
-
);
|
|
2810
|
-
}
|
|
2811
|
-
} catch {
|
|
2812
|
-
}
|
|
2813
|
-
}
|
|
2814
|
-
if (config.jsErrors && driver.getJSErrors) {
|
|
2815
|
-
try {
|
|
2816
|
-
const jsErrors = await Effect4.runPromise(Effect4.orDie(driver.getJSErrors()));
|
|
2817
|
-
if (jsErrors.length > 0) {
|
|
2818
|
-
attachments.push(
|
|
2819
|
-
writeJsonAttachment(dir, "js-errors.json", `${status}-js-errors`, jsErrors)
|
|
2820
|
-
);
|
|
2821
|
-
}
|
|
2822
|
-
} catch {
|
|
2823
|
-
}
|
|
2824
|
-
}
|
|
2825
|
-
if (config.har && driver.getHAR) {
|
|
2826
|
-
try {
|
|
2827
|
-
const har = await Effect4.runPromise(Effect4.orDie(driver.getHAR()));
|
|
2828
|
-
if (har.log.entries.length > 0) {
|
|
2829
|
-
attachments.push(writeJsonAttachment(dir, "network.har", `${status}-network-har`, har));
|
|
2830
|
-
}
|
|
2831
|
-
} catch {
|
|
2832
|
-
}
|
|
2833
|
-
}
|
|
2834
|
-
if (status === "failed" && driver.getDriverLogs) {
|
|
2835
|
-
try {
|
|
2836
|
-
const driverLogs = await Effect4.runPromise(Effect4.orDie(driver.getDriverLogs()));
|
|
2837
|
-
if (driverLogs.length > 0) {
|
|
2838
|
-
attachments.push(
|
|
2839
|
-
writeTextAttachment(
|
|
2840
|
-
dir,
|
|
2841
|
-
"driver-logs.txt",
|
|
2842
|
-
`${status}-driver-logs`,
|
|
2843
|
-
driverLogs.join("\n")
|
|
2844
|
-
)
|
|
2845
|
-
);
|
|
2846
|
-
}
|
|
2847
|
-
} catch {
|
|
2848
|
-
}
|
|
2849
|
-
}
|
|
2850
|
-
return attachments;
|
|
2851
|
-
}
|
|
2852
|
-
async function captureStepScreenshot(driver, config, flowName, platform, stepIndex, stepName, screenshot) {
|
|
2853
|
-
if (!config.screenshot) return void 0;
|
|
2854
|
-
try {
|
|
2855
|
-
const dir = join3(flowArtifactDir(config, flowName, platform), "steps");
|
|
2856
|
-
mkdirSync2(dir, { recursive: true });
|
|
2857
|
-
const fileName = `${String(stepIndex).padStart(3, "0")}-${safeName(stepName)}.png`;
|
|
2858
|
-
const path = join3(dir, fileName);
|
|
2859
|
-
const bytes = screenshot ?? await Effect4.runPromise(Effect4.orDie(driver.takeScreenshot()));
|
|
2860
|
-
writeFileSync2(path, bytes);
|
|
2861
|
-
return createAttachment(stepName, "image/png", path);
|
|
2862
|
-
} catch {
|
|
2863
|
-
return void 0;
|
|
2864
|
-
}
|
|
2865
|
-
}
|
|
2866
|
-
|
|
2867
|
-
// src/core/debug-repl.ts
|
|
2868
|
-
import * as repl from "repl";
|
|
2869
|
-
import { Effect as Effect5 } from "effect";
|
|
2870
|
-
var didStartDebugRepl = false;
|
|
2871
|
-
function toSuggestedSelectors(root) {
|
|
2872
|
-
return flattenElements(root).filter((el) => el.visible !== false && (el.id || el.text || el.accessibilityLabel)).map((el) => ({
|
|
2873
|
-
suggestedSelector: el.id ? { testID: el.id } : el.accessibilityLabel ? { accessibilityLabel: el.accessibilityLabel } : el.text ? { text: el.text } : "",
|
|
2874
|
-
elementType: el.elementType,
|
|
2875
|
-
text: el.text,
|
|
2876
|
-
accessibilityLabel: el.accessibilityLabel,
|
|
2877
|
-
bounds: el.bounds,
|
|
2878
|
-
id: el.id
|
|
2879
|
-
}));
|
|
2880
|
-
}
|
|
2881
|
-
async function runDebugReplOnce(context) {
|
|
2882
|
-
if (didStartDebugRepl) {
|
|
2883
|
-
return false;
|
|
2884
|
-
}
|
|
2885
|
-
didStartDebugRepl = true;
|
|
2886
|
-
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
|
2887
|
-
console.log("Skipping debug REPL because stdin/stdout is not interactive.");
|
|
2888
|
-
return false;
|
|
2889
|
-
}
|
|
2890
|
-
const hierarchy = async () => context.parseHierarchy(await Effect5.runPromise(context.driver.dumpHierarchy()));
|
|
2891
|
-
const selectors = async () => toSuggestedSelectors(await hierarchy());
|
|
2892
|
-
console.log("");
|
|
2893
|
-
console.log(`Entering debug REPL for failed flow "${context.flowName}" on ${context.platform}.`);
|
|
2894
|
-
console.log(
|
|
2895
|
-
"Available bindings: app, expect, driver, platform, flowName, error, hierarchy(), selectors(), help()"
|
|
2896
|
-
);
|
|
2897
|
-
console.log('Use top-level await for async calls, for example: await app.tap({ text: "Login" })');
|
|
2898
|
-
const replServer = repl.start({
|
|
2899
|
-
prompt: `spana:${context.platform}> `,
|
|
2900
|
-
ignoreUndefined: true,
|
|
2901
|
-
useGlobal: false
|
|
2902
|
-
});
|
|
2903
|
-
replServer.context.app = context.app;
|
|
2904
|
-
replServer.context.expect = context.expect;
|
|
2905
|
-
replServer.context.driver = context.driver;
|
|
2906
|
-
replServer.context.platform = context.platform;
|
|
2907
|
-
replServer.context.flowName = context.flowName;
|
|
2908
|
-
replServer.context.error = context.error;
|
|
2909
|
-
replServer.context.hierarchy = hierarchy;
|
|
2910
|
-
replServer.context.selectors = selectors;
|
|
2911
|
-
replServer.context.help = () => {
|
|
2912
|
-
console.log("app Promise-based app API with auto-waiting");
|
|
2913
|
-
console.log("expect Assertion helper, e.g. await expect({ text: 'Done' }).toBeVisible()");
|
|
2914
|
-
console.log("driver Raw driver service");
|
|
2915
|
-
console.log("hierarchy Async helper returning the parsed UI tree");
|
|
2916
|
-
console.log("selectors Async helper returning suggested selectors");
|
|
2917
|
-
console.log(".exit Leave the REPL");
|
|
2918
|
-
};
|
|
2919
|
-
await new Promise((resolve) => replServer.on("exit", resolve));
|
|
2920
|
-
console.log("");
|
|
2921
|
-
return true;
|
|
2922
|
-
}
|
|
2923
|
-
|
|
2924
|
-
// src/core/step-recorder.ts
|
|
2925
|
-
function errorMessage(error) {
|
|
2926
|
-
return error instanceof Error ? error.message : String(error);
|
|
2927
|
-
}
|
|
2928
|
-
function createStepResult(command, durationMs, status, selector, error, attachments) {
|
|
2929
|
-
return {
|
|
2930
|
-
command,
|
|
2931
|
-
selector,
|
|
2932
|
-
status,
|
|
2933
|
-
durationMs,
|
|
2934
|
-
error,
|
|
2935
|
-
attachments: attachments && attachments.length > 0 ? attachments : void 0
|
|
2936
|
-
};
|
|
2937
|
-
}
|
|
2938
|
-
function createStepRecorder(driver, artifactConfig, flowName, platform) {
|
|
2939
|
-
const steps = [];
|
|
2940
|
-
let lastFailureStack;
|
|
2941
|
-
return {
|
|
2942
|
-
async runStep(command, action, opts) {
|
|
2943
|
-
const startedAt = Date.now();
|
|
2944
|
-
const callSiteStack = new Error().stack;
|
|
2945
|
-
try {
|
|
2946
|
-
const result = await action();
|
|
2947
|
-
const attachments = [];
|
|
2948
|
-
if (opts?.captureScreenshot && artifactConfig.captureSteps) {
|
|
2949
|
-
const attachment = await captureStepScreenshot(
|
|
2950
|
-
driver,
|
|
2951
|
-
artifactConfig,
|
|
2952
|
-
flowName,
|
|
2953
|
-
platform,
|
|
2954
|
-
steps.length + 1,
|
|
2955
|
-
command
|
|
2956
|
-
);
|
|
2957
|
-
if (attachment) attachments.push(attachment);
|
|
2958
|
-
}
|
|
2959
|
-
steps.push(
|
|
2960
|
-
createStepResult(
|
|
2961
|
-
command,
|
|
2962
|
-
Date.now() - startedAt,
|
|
2963
|
-
"passed",
|
|
2964
|
-
opts?.selector,
|
|
2965
|
-
void 0,
|
|
2966
|
-
attachments
|
|
2967
|
-
)
|
|
2968
|
-
);
|
|
2969
|
-
return result;
|
|
2970
|
-
} catch (error) {
|
|
2971
|
-
lastFailureStack = callSiteStack;
|
|
2972
|
-
steps.push(
|
|
2973
|
-
createStepResult(
|
|
2974
|
-
command,
|
|
2975
|
-
Date.now() - startedAt,
|
|
2976
|
-
"failed",
|
|
2977
|
-
opts?.selector,
|
|
2978
|
-
errorMessage(error)
|
|
2979
|
-
)
|
|
2980
|
-
);
|
|
2981
|
-
throw error;
|
|
2982
|
-
}
|
|
2983
|
-
},
|
|
2984
|
-
async runScreenshotStep(command, action, opts) {
|
|
2985
|
-
const startedAt = Date.now();
|
|
2986
|
-
const callSiteStack = new Error().stack;
|
|
2987
|
-
try {
|
|
2988
|
-
const screenshot = await action();
|
|
2989
|
-
const attachment = await captureStepScreenshot(
|
|
2990
|
-
driver,
|
|
2991
|
-
artifactConfig,
|
|
2992
|
-
flowName,
|
|
2993
|
-
platform,
|
|
2994
|
-
steps.length + 1,
|
|
2995
|
-
opts?.name ?? command,
|
|
2996
|
-
screenshot
|
|
2997
|
-
);
|
|
2998
|
-
steps.push(
|
|
2999
|
-
createStepResult(
|
|
3000
|
-
command,
|
|
3001
|
-
Date.now() - startedAt,
|
|
3002
|
-
"passed",
|
|
3003
|
-
opts?.selector,
|
|
3004
|
-
void 0,
|
|
3005
|
-
attachment ? [attachment] : void 0
|
|
3006
|
-
)
|
|
3007
|
-
);
|
|
3008
|
-
return screenshot;
|
|
3009
|
-
} catch (error) {
|
|
3010
|
-
lastFailureStack = callSiteStack;
|
|
3011
|
-
steps.push(
|
|
3012
|
-
createStepResult(
|
|
3013
|
-
command,
|
|
3014
|
-
Date.now() - startedAt,
|
|
3015
|
-
"failed",
|
|
3016
|
-
opts?.selector,
|
|
3017
|
-
errorMessage(error)
|
|
3018
|
-
)
|
|
3019
|
-
);
|
|
3020
|
-
throw error;
|
|
3021
|
-
}
|
|
3022
|
-
},
|
|
3023
|
-
getSteps() {
|
|
3024
|
-
return steps;
|
|
3025
|
-
},
|
|
3026
|
-
getLastFailureStack() {
|
|
3027
|
-
return lastFailureStack;
|
|
3028
|
-
}
|
|
3029
|
-
};
|
|
3030
|
-
}
|
|
3031
|
-
|
|
3032
|
-
// src/report/classify-error.ts
|
|
3033
|
-
var TAG_KEY = "_tag";
|
|
3034
|
-
var FIBER_FAILURE_CAUSE_SYMBOL = /* @__PURE__ */ Symbol.for("effect/Runtime/FiberFailure/Cause");
|
|
3035
|
-
function unwrapTaggedError(error) {
|
|
3036
|
-
if (!error || typeof error !== "object") return {};
|
|
3037
|
-
const obj = error;
|
|
3038
|
-
if (typeof obj[TAG_KEY] === "string") {
|
|
3039
|
-
return obj;
|
|
3040
|
-
}
|
|
3041
|
-
const cause = obj[FIBER_FAILURE_CAUSE_SYMBOL];
|
|
3042
|
-
if (cause && typeof cause === "object") {
|
|
3043
|
-
const inner = cause["error"] ?? cause["defect"];
|
|
3044
|
-
if (inner && typeof inner === "object" && typeof inner[TAG_KEY] === "string") {
|
|
3045
|
-
return inner;
|
|
3046
|
-
}
|
|
3047
|
-
}
|
|
3048
|
-
return obj;
|
|
3049
|
-
}
|
|
3050
|
-
function selectorHint(selector) {
|
|
3051
|
-
if (selector && typeof selector === "object") {
|
|
3052
|
-
const s = selector;
|
|
3053
|
-
if (s.testID) return `testID="${s.testID}"`;
|
|
3054
|
-
if (s.text) return `text="${s.text}"`;
|
|
3055
|
-
if (s.accessibilityLabel) return `accessibilityLabel="${s.accessibilityLabel}"`;
|
|
3056
|
-
}
|
|
3057
|
-
return JSON.stringify(selector);
|
|
3058
|
-
}
|
|
3059
|
-
function categorizeElementFailure(message) {
|
|
3060
|
-
const lower = message.toLowerCase();
|
|
3061
|
-
if (lower.includes("not visible") || lower.includes("visible=false")) {
|
|
3062
|
-
return "element-not-visible";
|
|
3063
|
-
}
|
|
3064
|
-
if (lower.includes("off-screen") || lower.includes("zero size")) {
|
|
3065
|
-
return "element-off-screen";
|
|
3066
|
-
}
|
|
3067
|
-
if (lower.includes("disabled") || lower.includes("not interactive")) {
|
|
3068
|
-
return "element-not-interactive";
|
|
3069
|
-
}
|
|
3070
|
-
return "element-not-found";
|
|
3071
|
-
}
|
|
3072
|
-
function elementSuggestion(category, selector, timeoutMs) {
|
|
3073
|
-
switch (category) {
|
|
3074
|
-
case "element-not-visible":
|
|
3075
|
-
return [
|
|
3076
|
-
`Selector ${selector} matched an element, but it is currently hidden.`,
|
|
3077
|
-
"Check whether an animation, modal, or loading state is covering it before retrying.",
|
|
3078
|
-
"Consider increasing waitTimeout if the element becomes visible after a delay."
|
|
3079
|
-
].join("\n");
|
|
3080
|
-
case "element-off-screen":
|
|
3081
|
-
return [
|
|
3082
|
-
`Selector ${selector} matched an element that is off-screen.`,
|
|
3083
|
-
"Use scrollUntilVisible() or scroll to the element before interacting with it.",
|
|
3084
|
-
"If the target is above the current viewport, reverse the search direction."
|
|
3085
|
-
].join("\n");
|
|
3086
|
-
case "element-not-interactive":
|
|
3087
|
-
return [
|
|
3088
|
-
`Selector ${selector} matched an element that is disabled or not interactive.`,
|
|
3089
|
-
"Wait for the app to enable it, or verify the prerequisite app state first.",
|
|
3090
|
-
"Consider increasing waitTimeout if the control becomes enabled after async work completes."
|
|
3091
|
-
].join("\n");
|
|
3092
|
-
default:
|
|
3093
|
-
return [
|
|
3094
|
-
`Selector ${selector} was not found within ${timeoutMs ?? "?"}ms.`,
|
|
3095
|
-
"Run `spana selectors` to inspect the current screen and confirm the best selector.",
|
|
3096
|
-
"Consider increasing waitTimeout if the element appears after a delay."
|
|
3097
|
-
].join("\n");
|
|
3098
|
-
}
|
|
3099
|
-
}
|
|
3100
|
-
function categorizeDynamic(error, tag, msg) {
|
|
3101
|
-
if (tag === "ElementNotFoundError" || tag === "WaitTimeoutError") {
|
|
3102
|
-
const sel = selectorHint(error.selector);
|
|
3103
|
-
if (msg.includes("scroll(s) toward")) {
|
|
3104
|
-
return {
|
|
3105
|
-
category: "element-not-found",
|
|
3106
|
-
suggestion: [
|
|
3107
|
-
`Selector ${sel} stayed off-screen while scrolling.`,
|
|
3108
|
-
"Try increasing `maxScrolls` or `timeout`, or reverse the search direction",
|
|
3109
|
-
'if the target is actually above the current viewport (for example `{ direction: "up" }`).'
|
|
3110
|
-
].join("\n")
|
|
3111
|
-
};
|
|
3112
|
-
}
|
|
3113
|
-
if (msg.includes("back action(s)")) {
|
|
3114
|
-
return {
|
|
3115
|
-
category: "element-not-found",
|
|
3116
|
-
suggestion: [
|
|
3117
|
-
`Selector ${sel} was not reached while navigating back.`,
|
|
3118
|
-
"Try increasing `maxBacks` or `timeout`, or prefer an explicit in-app",
|
|
3119
|
-
"back / close control on iOS-style screens instead of relying on system back."
|
|
3120
|
-
].join("\n")
|
|
3121
|
-
};
|
|
3122
|
-
}
|
|
3123
|
-
const category = categorizeElementFailure(msg);
|
|
3124
|
-
return {
|
|
3125
|
-
category,
|
|
3126
|
-
suggestion: elementSuggestion(category, sel, error.timeoutMs)
|
|
3127
|
-
};
|
|
3128
|
-
}
|
|
3129
|
-
if (tag === "TextMismatchError") {
|
|
3130
|
-
const e = error;
|
|
3131
|
-
return {
|
|
3132
|
-
category: "text-mismatch",
|
|
3133
|
-
suggestion: [
|
|
3134
|
-
`Expected text "${e.expected}" but found "${e.actual ?? "(empty)"}".`,
|
|
3135
|
-
"The element exists but its content differs. Check for whitespace, truncation,",
|
|
3136
|
-
"or platform-specific text rendering differences."
|
|
3137
|
-
].join("\n")
|
|
3138
|
-
};
|
|
3139
|
-
}
|
|
3140
|
-
if (tag === "DeviceDisconnectedError") {
|
|
3141
|
-
const id = error.deviceId ? ` (${error.deviceId})` : "";
|
|
3142
|
-
return {
|
|
3143
|
-
category: "device-disconnected",
|
|
3144
|
-
suggestion: [
|
|
3145
|
-
`The device${id} disconnected during the test.`,
|
|
3146
|
-
"Check the physical connection or emulator/simulator stability.",
|
|
3147
|
-
"Run `spana devices` to verify available devices."
|
|
3148
|
-
].join("\n")
|
|
3149
|
-
};
|
|
3150
|
-
}
|
|
3151
|
-
if (tag === "AppCrashedError") {
|
|
3152
|
-
const app = error.appId ? ` (${error.appId})` : "";
|
|
3153
|
-
return {
|
|
3154
|
-
category: "app-crashed",
|
|
3155
|
-
suggestion: [
|
|
3156
|
-
`The app${app} crashed during the test.`,
|
|
3157
|
-
"Check the device logs for a crash stack trace:",
|
|
3158
|
-
" Android: `adb logcat -d | grep FATAL`",
|
|
3159
|
-
" iOS: Check Console.app or `log show --predicate 'process == \"your-app\"'`"
|
|
3160
|
-
].join("\n")
|
|
3161
|
-
};
|
|
3162
|
-
}
|
|
3163
|
-
if (tag === "AppNotInstalledError") {
|
|
3164
|
-
return {
|
|
3165
|
-
category: "app-not-installed",
|
|
3166
|
-
suggestion: [
|
|
3167
|
-
`App "${error.appId}" is not installed on the device.`,
|
|
3168
|
-
"Install it before running tests, or configure `apps.android.appPath`",
|
|
3169
|
-
"/ `apps.ios.appPath` in spana.config.ts for auto-install."
|
|
3170
|
-
].join("\n")
|
|
3171
|
-
};
|
|
3172
|
-
}
|
|
3173
|
-
if (tag === "DriverError") {
|
|
3174
|
-
return categorizeDynamicDriver(error, msg);
|
|
3175
|
-
}
|
|
3176
|
-
return void 0;
|
|
3177
|
-
}
|
|
3178
|
-
function categorizeDynamicDriver(error, msg) {
|
|
3179
|
-
for (const rule of driverRules) {
|
|
3180
|
-
if (rule.pattern && matchesPattern(msg, rule.pattern)) {
|
|
3181
|
-
return {
|
|
3182
|
-
category: typeof rule.category === "function" ? rule.category(msg) : rule.category,
|
|
3183
|
-
suggestion: typeof rule.suggestion === "function" ? rule.suggestion(error, msg) : rule.suggestion
|
|
3184
|
-
};
|
|
3185
|
-
}
|
|
3186
|
-
}
|
|
3187
|
-
return {
|
|
3188
|
-
category: "driver-error",
|
|
3189
|
-
suggestion: error.command ? `Driver command "${error.command}" failed. Check the device connection and driver logs.` : "A low-level driver operation failed. Check the device connection and driver logs."
|
|
3190
|
-
};
|
|
3191
|
-
}
|
|
3192
|
-
var driverRules = [
|
|
3193
|
-
{
|
|
3194
|
-
pattern: "dismissKeyboard()",
|
|
3195
|
-
category: "driver-error",
|
|
3196
|
-
suggestion: [
|
|
3197
|
-
"Keyboard dismissal failed.",
|
|
3198
|
-
'On Android, try `app.dismissKeyboard({ strategy: "back" })`.',
|
|
3199
|
-
"On iOS, prefer tapping a visible Done / Close control or a non-input element."
|
|
3200
|
-
].join("\n")
|
|
3201
|
-
},
|
|
3202
|
-
{
|
|
3203
|
-
pattern: "backUntilVisible()",
|
|
3204
|
-
category: "driver-error",
|
|
3205
|
-
suggestion: [
|
|
3206
|
-
"System back navigation failed before the target screen became visible.",
|
|
3207
|
-
"If this route uses app-level navigation, tap the visible back / close control instead.",
|
|
3208
|
-
"This is especially common on iOS where a system back button may not exist."
|
|
3209
|
-
].join("\n")
|
|
3210
|
-
},
|
|
3211
|
-
{
|
|
3212
|
-
pattern: "Input text failed",
|
|
3213
|
-
category: "driver-error",
|
|
3214
|
-
suggestion: [
|
|
3215
|
-
"Text input failed at the driver layer.",
|
|
3216
|
-
"Make sure the field is focused first, and retry with shorter input chunks if needed.",
|
|
3217
|
-
"If the keyboard is in the way, dismiss it before continuing the flow."
|
|
3218
|
-
].join("\n")
|
|
3219
|
-
}
|
|
3220
|
-
];
|
|
3221
|
-
var tagOnlyRules = [
|
|
3222
|
-
{
|
|
3223
|
-
tag: "TimeoutError",
|
|
3224
|
-
category: "timeout",
|
|
3225
|
-
suggestion: [
|
|
3226
|
-
"The operation took longer than the allowed timeout.",
|
|
3227
|
-
"Try increasing `defaults.waitTimeout` in spana.config.ts,",
|
|
3228
|
-
"or set a per-flow timeout: `flow('name', { timeout: 30000 }, ...)`."
|
|
3229
|
-
].join("\n")
|
|
3230
|
-
},
|
|
3231
|
-
{
|
|
3232
|
-
tag: ["ConfigError", "FlowSyntaxError"],
|
|
3233
|
-
category: "config-error",
|
|
3234
|
-
suggestion: "Run `spana validate-config` to check your configuration."
|
|
3235
|
-
}
|
|
3236
|
-
];
|
|
3237
|
-
var heuristicRules = [
|
|
3238
|
-
{
|
|
3239
|
-
pattern: /[Tt]imed out/,
|
|
3240
|
-
category: "timeout",
|
|
3241
|
-
suggestion: "The operation timed out. Try increasing `defaults.waitTimeout` in spana.config.ts."
|
|
3242
|
-
},
|
|
3243
|
-
{
|
|
3244
|
-
pattern: /not found|not visible|not fillable|covered by/,
|
|
3245
|
-
category: (msg) => categorizeElementFailure(msg),
|
|
3246
|
-
suggestion: (_error, msg) => {
|
|
3247
|
-
if (msg.includes("scroll(s) toward")) {
|
|
3248
|
-
return "The target stayed off-screen while scrolling. Increase `maxScrolls` / `timeout`, or reverse the scroll search direction.";
|
|
3249
|
-
}
|
|
3250
|
-
const category = categorizeElementFailure(msg);
|
|
3251
|
-
return elementSuggestion(category, "the target selector", void 0);
|
|
3252
|
-
}
|
|
3253
|
-
},
|
|
3254
|
-
{
|
|
3255
|
-
pattern: "dismissKeyboard()",
|
|
3256
|
-
category: "driver-error",
|
|
3257
|
-
suggestion: 'Keyboard dismissal failed. On Android try `app.dismissKeyboard({ strategy: "back" })`; on iOS prefer an explicit Done / Close control.'
|
|
3258
|
-
},
|
|
3259
|
-
{
|
|
3260
|
-
pattern: /ECONNREFUSED|ECONNRESET|disconnected/,
|
|
3261
|
-
category: "device-disconnected",
|
|
3262
|
-
suggestion: "The connection was lost. Check the device or emulator/simulator is still running."
|
|
3263
|
-
}
|
|
3264
|
-
];
|
|
3265
|
-
function matchesPattern(msg, pattern) {
|
|
3266
|
-
return typeof pattern === "string" ? msg.includes(pattern) : pattern.test(msg);
|
|
3267
|
-
}
|
|
3268
|
-
function matchesTag(tag, rule) {
|
|
3269
|
-
if (!rule.tag) return true;
|
|
3270
|
-
if (Array.isArray(rule.tag)) return tag != null && rule.tag.includes(tag);
|
|
3271
|
-
return tag === rule.tag;
|
|
3272
|
-
}
|
|
3273
|
-
function categorize(error) {
|
|
3274
|
-
const tag = error[TAG_KEY];
|
|
3275
|
-
const msg = error.message ?? "";
|
|
3276
|
-
const dynamic = categorizeDynamic(error, tag, msg);
|
|
3277
|
-
if (dynamic) return dynamic;
|
|
3278
|
-
for (const rule of tagOnlyRules) {
|
|
3279
|
-
if (matchesTag(tag, rule)) {
|
|
3280
|
-
return {
|
|
3281
|
-
category: typeof rule.category === "function" ? rule.category(msg) : rule.category,
|
|
3282
|
-
suggestion: typeof rule.suggestion === "function" ? rule.suggestion(error, msg) : rule.suggestion
|
|
3283
|
-
};
|
|
3284
|
-
}
|
|
3285
|
-
}
|
|
3286
|
-
for (const rule of heuristicRules) {
|
|
3287
|
-
if (rule.pattern && matchesPattern(msg, rule.pattern)) {
|
|
3288
|
-
return {
|
|
3289
|
-
category: typeof rule.category === "function" ? rule.category(msg) : rule.category,
|
|
3290
|
-
suggestion: typeof rule.suggestion === "function" ? rule.suggestion(error, msg) : rule.suggestion
|
|
3291
|
-
};
|
|
3292
|
-
}
|
|
3293
|
-
}
|
|
3294
|
-
return { category: "unknown" };
|
|
3295
|
-
}
|
|
3296
|
-
function classifyError(error, opts) {
|
|
3297
|
-
const tagged = unwrapTaggedError(error);
|
|
3298
|
-
const { category, suggestion } = categorize(tagged);
|
|
3299
|
-
const extracted = extractCodeFrame(error.stack, opts?.flowFilePath) ?? extractCodeFrame(opts?.fallbackStack, opts?.flowFilePath);
|
|
3300
|
-
return {
|
|
3301
|
-
message: tagged.message ?? error.message,
|
|
3302
|
-
stack: error.stack,
|
|
3303
|
-
category,
|
|
3304
|
-
suggestion,
|
|
3305
|
-
...extracted ? { location: extracted.location, codeFrame: extracted.frame } : {}
|
|
3306
|
-
};
|
|
3307
|
-
}
|
|
3308
|
-
|
|
3309
|
-
// src/core/engine.ts
|
|
3310
|
-
import { writeFileSync as writeFileSync4 } from "fs";
|
|
3311
|
-
import { join as join5 } from "path";
|
|
3312
|
-
|
|
3313
|
-
// src/report/failure-bundle.ts
|
|
3314
|
-
import { writeFileSync as writeFileSync3, readFileSync as readFileSync3, existsSync as existsSync4 } from "fs";
|
|
3315
|
-
import { join as join4, basename } from "path";
|
|
3316
|
-
function levenshtein(a, b) {
|
|
3317
|
-
const m = a.length;
|
|
3318
|
-
const n = b.length;
|
|
3319
|
-
const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
|
|
3320
|
-
for (let i = 0; i <= m; i++) dp[i][0] = i;
|
|
3321
|
-
for (let j = 0; j <= n; j++) dp[0][j] = j;
|
|
3322
|
-
for (let i = 1; i <= m; i++) {
|
|
3323
|
-
for (let j = 1; j <= n; j++) {
|
|
3324
|
-
dp[i][j] = a[i - 1] === b[j - 1] ? dp[i - 1][j - 1] : 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
|
|
3325
|
-
}
|
|
3326
|
-
}
|
|
3327
|
-
return dp[m][n];
|
|
3328
|
-
}
|
|
3329
|
-
function extractIdentifiers(hierarchyJson) {
|
|
3330
|
-
const testIDs = [];
|
|
3331
|
-
const texts = [];
|
|
3332
|
-
try {
|
|
3333
|
-
const root = JSON.parse(hierarchyJson);
|
|
3334
|
-
const queue = [root];
|
|
3335
|
-
while (queue.length > 0) {
|
|
3336
|
-
const node = queue.pop();
|
|
3337
|
-
if (!node || typeof node !== "object") continue;
|
|
3338
|
-
if (node.testID && typeof node.testID === "string") testIDs.push(node.testID);
|
|
3339
|
-
if (node.text && typeof node.text === "string") texts.push(node.text);
|
|
3340
|
-
if (Array.isArray(node.children)) {
|
|
3341
|
-
for (const child of node.children) queue.push(child);
|
|
3342
|
-
}
|
|
3343
|
-
}
|
|
3344
|
-
} catch {
|
|
3345
|
-
}
|
|
3346
|
-
return { testIDs, texts };
|
|
3347
|
-
}
|
|
3348
|
-
function findNearbySelectors(attempted, hierarchyJson) {
|
|
3349
|
-
if (!hierarchyJson) return [];
|
|
3350
|
-
const { testIDs, texts } = extractIdentifiers(hierarchyJson);
|
|
3351
|
-
let target;
|
|
3352
|
-
let candidates;
|
|
3353
|
-
if (typeof attempted === "string") {
|
|
3354
|
-
target = attempted.toLowerCase();
|
|
3355
|
-
candidates = [...testIDs, ...texts];
|
|
3356
|
-
} else if (attempted && typeof attempted === "object") {
|
|
3357
|
-
const sel = attempted;
|
|
3358
|
-
if (typeof sel.testID === "string") {
|
|
3359
|
-
target = sel.testID.toLowerCase();
|
|
3360
|
-
candidates = testIDs;
|
|
3361
|
-
} else if (typeof sel.text === "string") {
|
|
3362
|
-
target = sel.text.toLowerCase();
|
|
3363
|
-
candidates = texts;
|
|
3364
|
-
} else if (typeof sel.accessibilityLabel === "string") {
|
|
3365
|
-
target = sel.accessibilityLabel.toLowerCase();
|
|
3366
|
-
candidates = [...testIDs, ...texts];
|
|
3367
|
-
} else {
|
|
3368
|
-
return [];
|
|
3369
|
-
}
|
|
3370
|
-
} else {
|
|
3371
|
-
return [];
|
|
3372
|
-
}
|
|
3373
|
-
const scored = candidates.filter((c) => c !== target).map((c) => {
|
|
3374
|
-
const cl = c.toLowerCase();
|
|
3375
|
-
const substringMatch = cl.includes(target) || target.includes(cl);
|
|
3376
|
-
const dist = levenshtein(target, cl);
|
|
3377
|
-
return { value: c, score: substringMatch ? 0 : dist };
|
|
3378
|
-
}).filter((s) => s.score <= 5).toSorted((a, b) => a.score - b.score);
|
|
3379
|
-
const seen = /* @__PURE__ */ new Set();
|
|
3380
|
-
const results = [];
|
|
3381
|
-
for (const s of scored) {
|
|
3382
|
-
if (!seen.has(s.value)) {
|
|
3383
|
-
seen.add(s.value);
|
|
3384
|
-
results.push(s.value);
|
|
3385
|
-
if (results.length >= 5) break;
|
|
3386
|
-
}
|
|
3387
|
-
}
|
|
3388
|
-
return results;
|
|
3389
|
-
}
|
|
3390
|
-
function buildArtifactMap(attachments) {
|
|
3391
|
-
const map = {};
|
|
3392
|
-
if (!attachments) return map;
|
|
3393
|
-
for (const att of attachments) {
|
|
3394
|
-
const filename = basename(att.path);
|
|
3395
|
-
if (filename === "screenshot.png") map.screenshot = filename;
|
|
3396
|
-
else if (filename === "hierarchy.json") map.hierarchy = filename;
|
|
3397
|
-
else if (filename === "console-logs.json") map.consoleLogs = filename;
|
|
3398
|
-
else if (filename === "js-errors.json") map.jsErrors = filename;
|
|
3399
|
-
else if (filename === "network.har") map.har = filename;
|
|
3400
|
-
else if (filename === "driver-logs.txt") map.driverLogs = filename;
|
|
3401
|
-
}
|
|
3402
|
-
return map;
|
|
3403
|
-
}
|
|
3404
|
-
function createFailureBundle(flowName, platform, steps, error, artifactDir, attachments, flowPath) {
|
|
3405
|
-
const failedStepIndex = steps.findLastIndex((s) => s.status === "failed");
|
|
3406
|
-
const failedStep = failedStepIndex >= 0 ? {
|
|
3407
|
-
index: failedStepIndex,
|
|
3408
|
-
command: steps[failedStepIndex].command,
|
|
3409
|
-
selector: steps[failedStepIndex].selector ?? null,
|
|
3410
|
-
durationMs: steps[failedStepIndex].durationMs,
|
|
3411
|
-
error: steps[failedStepIndex].error
|
|
3412
|
-
} : null;
|
|
3413
|
-
const lastPassedIndex = failedStepIndex > 0 ? steps.findLastIndex((s, i) => i < failedStepIndex && s.status === "passed") : -1;
|
|
3414
|
-
const lastPassedStep = lastPassedIndex >= 0 ? {
|
|
3415
|
-
index: lastPassedIndex,
|
|
3416
|
-
command: steps[lastPassedIndex].command,
|
|
3417
|
-
selector: steps[lastPassedIndex].selector ?? null,
|
|
3418
|
-
durationMs: steps[lastPassedIndex].durationMs
|
|
3419
|
-
} : null;
|
|
3420
|
-
let selectorContext;
|
|
3421
|
-
if (failedStep?.selector && (error.category === "element-not-found" || error.category === "element-not-visible")) {
|
|
3422
|
-
const hierarchyPath = join4(artifactDir, "hierarchy.json");
|
|
3423
|
-
let hierarchyJson = null;
|
|
3424
|
-
if (existsSync4(hierarchyPath)) {
|
|
3425
|
-
try {
|
|
3426
|
-
hierarchyJson = readFileSync3(hierarchyPath, "utf-8");
|
|
3427
|
-
} catch {
|
|
3428
|
-
}
|
|
3429
|
-
}
|
|
3430
|
-
const nearbyAlternatives = findNearbySelectors(failedStep.selector, hierarchyJson);
|
|
3431
|
-
selectorContext = {
|
|
3432
|
-
attempted: failedStep.selector,
|
|
3433
|
-
nearbyAlternatives
|
|
3434
|
-
};
|
|
3435
|
-
}
|
|
3436
|
-
const shellQuote = (value) => `'${value.replaceAll("'", `'\\''`)}'`;
|
|
3437
|
-
const flowFile = flowPath ?? `flows/${flowName.replaceAll(" ", "-")}.flow.ts`;
|
|
3438
|
-
const reproCommand = `spana test ${shellQuote(flowFile)} --platform ${platform} --grep ${shellQuote(flowName)}`;
|
|
3439
|
-
let runtimeDiagnostics;
|
|
3440
|
-
const consolePath = join4(artifactDir, "console-logs.json");
|
|
3441
|
-
const jsErrPath = join4(artifactDir, "js-errors.json");
|
|
3442
|
-
if (existsSync4(consolePath) || existsSync4(jsErrPath)) {
|
|
3443
|
-
let consoleErrorCount = 0;
|
|
3444
|
-
let consoleWarnCount = 0;
|
|
3445
|
-
const recentConsoleErrors = [];
|
|
3446
|
-
let jsErrorCount = 0;
|
|
3447
|
-
const recentJsErrors = [];
|
|
3448
|
-
if (existsSync4(consolePath)) {
|
|
3449
|
-
try {
|
|
3450
|
-
const logs = JSON.parse(readFileSync3(consolePath, "utf-8"));
|
|
3451
|
-
if (Array.isArray(logs)) {
|
|
3452
|
-
for (const entry of logs) {
|
|
3453
|
-
const lvl = (entry.type ?? entry.level ?? "").toLowerCase();
|
|
3454
|
-
const text = entry.text ?? entry.message ?? "";
|
|
3455
|
-
if (lvl === "error") {
|
|
3456
|
-
consoleErrorCount++;
|
|
3457
|
-
if (text) recentConsoleErrors.push(text);
|
|
3458
|
-
} else if (lvl === "warn" || lvl === "warning") {
|
|
3459
|
-
consoleWarnCount++;
|
|
3460
|
-
}
|
|
3461
|
-
}
|
|
3462
|
-
}
|
|
3463
|
-
} catch {
|
|
3464
|
-
}
|
|
3465
|
-
}
|
|
3466
|
-
if (existsSync4(jsErrPath)) {
|
|
3467
|
-
try {
|
|
3468
|
-
const errs = JSON.parse(readFileSync3(jsErrPath, "utf-8"));
|
|
3469
|
-
if (Array.isArray(errs)) {
|
|
3470
|
-
jsErrorCount = errs.length;
|
|
3471
|
-
for (const e of errs.slice(-5)) {
|
|
3472
|
-
const msg = e.message ?? e.text ?? String(e);
|
|
3473
|
-
if (msg) recentJsErrors.push(msg);
|
|
3474
|
-
}
|
|
3475
|
-
}
|
|
3476
|
-
} catch {
|
|
3477
|
-
}
|
|
3478
|
-
}
|
|
3479
|
-
if (consoleErrorCount > 0 || consoleWarnCount > 0 || jsErrorCount > 0) {
|
|
3480
|
-
runtimeDiagnostics = {
|
|
3481
|
-
consoleErrorCount,
|
|
3482
|
-
consoleWarnCount,
|
|
3483
|
-
recentConsoleErrors: recentConsoleErrors.slice(-5),
|
|
3484
|
-
jsErrorCount,
|
|
3485
|
-
recentJsErrors
|
|
3486
|
-
};
|
|
3487
|
-
}
|
|
3488
|
-
}
|
|
3489
|
-
const bundle = {
|
|
3490
|
-
schemaVersion: 1,
|
|
3491
|
-
flow: flowName,
|
|
3492
|
-
platform,
|
|
3493
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3494
|
-
failedStep,
|
|
3495
|
-
lastPassedStep,
|
|
3496
|
-
steps: steps.map((s, index) => ({
|
|
3497
|
-
index,
|
|
3498
|
-
command: s.command,
|
|
3499
|
-
selector: s.selector ?? null,
|
|
3500
|
-
durationMs: s.durationMs,
|
|
3501
|
-
status: s.status,
|
|
3502
|
-
...s.error !== void 0 ? { error: s.error } : {}
|
|
3503
|
-
})),
|
|
3504
|
-
error: {
|
|
3505
|
-
message: error.message,
|
|
3506
|
-
category: error.category,
|
|
3507
|
-
suggestion: error.suggestion,
|
|
3508
|
-
errorCode: error.errorCode,
|
|
3509
|
-
...error.location ? { location: error.location } : {},
|
|
3510
|
-
...error.codeFrame ? { codeFrame: error.codeFrame } : {}
|
|
3511
|
-
},
|
|
3512
|
-
selectorContext,
|
|
3513
|
-
...runtimeDiagnostics ? { runtimeDiagnostics } : {},
|
|
3514
|
-
artifacts: buildArtifactMap(attachments),
|
|
3515
|
-
reproCommand,
|
|
3516
|
-
durationMs: steps.reduce((sum, s) => sum + s.durationMs, 0)
|
|
3517
|
-
};
|
|
3518
|
-
return bundle;
|
|
3519
|
-
}
|
|
3520
|
-
function writeFailureBundle(bundle, artifactDir) {
|
|
3521
|
-
const path = join4(artifactDir, "failure-bundle.json");
|
|
3522
|
-
writeFileSync3(path, JSON.stringify(bundle, null, 2), "utf-8");
|
|
3523
|
-
return path;
|
|
3524
|
-
}
|
|
3525
|
-
|
|
3526
|
-
// src/core/engine.ts
|
|
3527
|
-
function isCdpScreencastCapable(channel) {
|
|
3528
|
-
return Boolean(channel) && typeof channel.sendCommand === "function" && typeof channel.onEvent === "function";
|
|
3529
|
-
}
|
|
3530
|
-
function buildPlaybackStepMarkers(steps) {
|
|
3531
|
-
let cursorMs = 0;
|
|
3532
|
-
return steps.map((step, index) => {
|
|
3533
|
-
const startedAtMs = cursorMs;
|
|
3534
|
-
cursorMs += Math.max(1, step.durationMs);
|
|
3535
|
-
const sel = step.selector;
|
|
3536
|
-
const pt = sel && typeof sel === "object" ? sel["point"] : void 0;
|
|
3537
|
-
const tapPoint = pt && typeof pt["x"] === "number" && typeof pt["y"] === "number" ? { x: pt["x"], y: pt["y"] } : void 0;
|
|
3538
|
-
return {
|
|
3539
|
-
index,
|
|
3540
|
-
command: step.command,
|
|
3541
|
-
selector: step.selector,
|
|
3542
|
-
startedAtMs,
|
|
3543
|
-
durationMs: step.durationMs,
|
|
3544
|
-
status: step.status,
|
|
3545
|
-
error: step.error,
|
|
3546
|
-
...tapPoint ? { tapPoint } : {}
|
|
3547
|
-
};
|
|
3548
|
-
});
|
|
3549
|
-
}
|
|
3550
|
-
async function executeFlow(flow, driver, config) {
|
|
3551
|
-
const start2 = Date.now();
|
|
3552
|
-
const { platform, coordinatorConfig, appId } = config;
|
|
3553
|
-
const skip = getFlowSkip(flow, platform);
|
|
3554
|
-
if (skip) return skip;
|
|
3555
|
-
const autoLaunch = flow.config.autoLaunch ?? config.autoLaunch ?? true;
|
|
3556
|
-
const timeout = flow.config.timeout ?? config.flowTimeout ?? 6e4;
|
|
3557
|
-
const artifactConfig = resolveArtifactConfig(config.artifactConfig, flow.config.artifacts);
|
|
3558
|
-
const stepRecorder = createStepRecorder(driver, artifactConfig, flow.name, platform);
|
|
3559
|
-
const launchOptions = mergeLaunchOptions(config.launchOptions, flow.config.launchOptions);
|
|
3560
|
-
const flowDefaults = flow.config.defaults;
|
|
3561
|
-
const mergedCoordinatorConfig = flowDefaults ? {
|
|
3562
|
-
...coordinatorConfig,
|
|
3563
|
-
defaults: {
|
|
3564
|
-
...coordinatorConfig.defaults,
|
|
3565
|
-
timeout: flowDefaults.waitTimeout ?? coordinatorConfig.defaults?.timeout,
|
|
3566
|
-
pollInterval: flowDefaults.pollInterval ?? coordinatorConfig.defaults?.pollInterval,
|
|
3567
|
-
settleTimeout: flowDefaults.settleTimeout ?? coordinatorConfig.defaults?.settleTimeout,
|
|
3568
|
-
initialPollInterval: flowDefaults.initialPollInterval ?? coordinatorConfig.defaults?.initialPollInterval
|
|
3569
|
-
},
|
|
3570
|
-
waitForIdleTimeout: flowDefaults.waitForIdleTimeout ?? coordinatorConfig.waitForIdleTimeout,
|
|
3571
|
-
typingDelay: flowDefaults.typingDelay ?? coordinatorConfig.typingDelay,
|
|
3572
|
-
hierarchyCacheTtl: flowDefaults.hierarchyCacheTtl ?? coordinatorConfig.hierarchyCacheTtl
|
|
3573
|
-
} : coordinatorConfig;
|
|
3574
|
-
const softFailures = [];
|
|
3575
|
-
const aggregateFailures = (hardFailure) => {
|
|
3576
|
-
const messages = softFailures.map(
|
|
3577
|
-
(error, i) => `${i + 1}. ${error instanceof Error ? error.message : String(error)}`
|
|
3578
|
-
);
|
|
3579
|
-
return new AggregateError(
|
|
3580
|
-
hardFailure ? [hardFailure, ...softFailures] : softFailures,
|
|
3581
|
-
`${hardFailure ? `${hardFailure.message}
|
|
3582
|
-
` : ""}${softFailures.length} soft assertion(s) failed:
|
|
3583
|
-
${messages.join("\n")}`,
|
|
3584
|
-
{ cause: hardFailure ?? softFailures[0] }
|
|
3585
|
-
);
|
|
3586
|
-
};
|
|
3587
|
-
const flowMeta = {
|
|
3588
|
-
flowFilePath: flow.sourcePath ?? "",
|
|
3589
|
-
flowName: flow.name,
|
|
3590
|
-
platform,
|
|
3591
|
-
updateBaselines: config.updateBaselines ?? false,
|
|
3592
|
-
recordSoftFailure: (error) => {
|
|
3593
|
-
softFailures.push(error);
|
|
3594
|
-
}
|
|
3595
|
-
};
|
|
3596
|
-
const extraCleanups = [];
|
|
3597
|
-
const app = createPromiseApp(driver, appId, mergedCoordinatorConfig, stepRecorder, {
|
|
3598
|
-
platform,
|
|
3599
|
-
storybook: config.storybook,
|
|
3600
|
-
launchOptions,
|
|
3601
|
-
onRegisterCleanup: (fn) => extraCleanups.push(fn),
|
|
3602
|
-
flowContext: flowMeta,
|
|
3603
|
-
visualRegression: config.visualRegression
|
|
3604
|
-
});
|
|
3605
|
-
const expect = createPromiseExpect(
|
|
3606
|
-
driver,
|
|
3607
|
-
mergedCoordinatorConfig,
|
|
3608
|
-
stepRecorder,
|
|
3609
|
-
flowMeta,
|
|
3610
|
-
config.visualRegression
|
|
3611
|
-
);
|
|
3612
|
-
const flowCtx = { app, expect, platform, updateBaselines: flowMeta.updateBaselines };
|
|
3613
|
-
const sessionManager = new SessionManager();
|
|
3614
|
-
const sessions = createSessions(
|
|
3615
|
-
sessionManager,
|
|
3616
|
-
async (opts) => {
|
|
3617
|
-
const pwDriver = await Effect6.runPromise(
|
|
3618
|
-
makePlaywrightDriver({
|
|
3619
|
-
browser: opts.browser,
|
|
3620
|
-
headless: opts.headless ?? true,
|
|
3621
|
-
baseUrl: opts.baseUrl,
|
|
3622
|
-
storageState: opts.storageState,
|
|
3623
|
-
verboseLogging: opts.verboseLogging
|
|
3624
|
-
})
|
|
3625
|
-
);
|
|
3626
|
-
return pwDriver;
|
|
3627
|
-
},
|
|
3628
|
-
{ parse: (raw) => parseWebHierarchy(raw) },
|
|
3629
|
-
{ ...flowMeta, platform: "web" }
|
|
3630
|
-
);
|
|
3631
|
-
flowCtx.sessions = sessions;
|
|
3632
|
-
let videoRecorder;
|
|
3633
|
-
let collectingCoverage = false;
|
|
3634
|
-
let recordingFinalized = false;
|
|
3635
|
-
const wantRecording = artifactConfig.video !== "off" || artifactConfig.playback;
|
|
3636
|
-
const captureCoverage = async (attachments, status) => {
|
|
3637
|
-
if (!collectingCoverage || !driver.stopJSCoverage) return;
|
|
3638
|
-
collectingCoverage = false;
|
|
3639
|
-
try {
|
|
3640
|
-
const entries = await Effect6.runPromise(driver.stopJSCoverage());
|
|
3641
|
-
const path = join5(flowArtifactDir(artifactConfig, flow.name, platform), "js-coverage.json");
|
|
3642
|
-
writeFileSync4(path, JSON.stringify(entries), "utf8");
|
|
3643
|
-
attachments.push({ name: "js-coverage", contentType: "application/json", path });
|
|
3644
|
-
} catch (error) {
|
|
3645
|
-
if (status === "passed") throw error;
|
|
3646
|
-
console.warn(
|
|
3647
|
-
`Failed to capture JavaScript coverage: ${error instanceof Error ? error.message : String(error)}`
|
|
3648
|
-
);
|
|
3649
|
-
}
|
|
3650
|
-
};
|
|
3651
|
-
const finalizeRecording = async (status, attachments, steps, durationMs) => {
|
|
3652
|
-
if (recordingFinalized || !wantRecording) return;
|
|
3653
|
-
recordingFinalized = true;
|
|
3654
|
-
const keep = artifactConfig.video === "on" || artifactConfig.playback || artifactConfig.video === "retain-on-failure" && status === "failed";
|
|
3655
|
-
const fileStem = safeArtifactName(flow.name);
|
|
3656
|
-
const outputDir = keep ? flowArtifactDir(artifactConfig, flow.name, platform) : artifactConfig.outputDir;
|
|
3657
|
-
let viewport;
|
|
3658
|
-
try {
|
|
3659
|
-
const info = await Effect6.runPromise(Effect6.orDie(driver.getDeviceInfo()));
|
|
3660
|
-
if (info.screenWidth > 0 && info.screenHeight > 0) {
|
|
3661
|
-
viewport = { width: info.screenWidth, height: info.screenHeight };
|
|
3662
|
-
}
|
|
3663
|
-
} catch {
|
|
3664
|
-
}
|
|
3665
|
-
let stopRes;
|
|
3666
|
-
if (videoRecorder) {
|
|
3667
|
-
try {
|
|
3668
|
-
stopRes = await videoRecorder.stop({
|
|
3669
|
-
keep,
|
|
3670
|
-
outputDir,
|
|
3671
|
-
fileStem,
|
|
3672
|
-
steps: buildPlaybackStepMarkers(steps),
|
|
3673
|
-
viewport
|
|
3674
|
-
});
|
|
3675
|
-
} catch {
|
|
3676
|
-
}
|
|
3677
|
-
}
|
|
3678
|
-
if (!keep) return;
|
|
3679
|
-
if (stopRes?.videoPath) {
|
|
3680
|
-
attachments.push({
|
|
3681
|
-
name: "video",
|
|
3682
|
-
contentType: stopRes.videoPath.endsWith(".webm") ? "video/webm" : "video/mp4",
|
|
3683
|
-
path: stopRes.videoPath
|
|
3684
|
-
});
|
|
3685
|
-
}
|
|
3686
|
-
if (stopRes?.playbackJsonPath) {
|
|
3687
|
-
attachments.push({
|
|
3688
|
-
name: "playback",
|
|
3689
|
-
contentType: "application/json",
|
|
3690
|
-
path: stopRes.playbackJsonPath
|
|
3691
|
-
});
|
|
3692
|
-
return;
|
|
3693
|
-
}
|
|
3694
|
-
const fallbackTrace = buildPlaybackTraceFromSteps({
|
|
3695
|
-
flowName: flow.name,
|
|
3696
|
-
platform,
|
|
3697
|
-
durationMs,
|
|
3698
|
-
steps,
|
|
3699
|
-
viewport,
|
|
3700
|
-
videoPath: stopRes?.videoPath
|
|
3701
|
-
});
|
|
3702
|
-
if (fallbackTrace) {
|
|
3703
|
-
const playbackPath = join5(outputDir, `${fileStem}-playback.json`);
|
|
3704
|
-
writeFileSync4(playbackPath, JSON.stringify(fallbackTrace), "utf8");
|
|
3705
|
-
attachments.push({
|
|
3706
|
-
name: "playback",
|
|
3707
|
-
contentType: "application/json",
|
|
3708
|
-
path: playbackPath
|
|
3709
|
-
});
|
|
3710
|
-
}
|
|
3711
|
-
};
|
|
3712
|
-
const buildFailureResult = async (error) => {
|
|
3713
|
-
const attachments = await captureArtifacts(
|
|
3714
|
-
driver,
|
|
3715
|
-
artifactConfig,
|
|
3716
|
-
flow.name,
|
|
3717
|
-
platform,
|
|
3718
|
-
"failed"
|
|
3719
|
-
);
|
|
3720
|
-
await captureCoverage(attachments, "failed");
|
|
3721
|
-
const steps = stepRecorder.getSteps();
|
|
3722
|
-
const durationMs = Date.now() - start2;
|
|
3723
|
-
await finalizeRecording("failed", attachments, steps, durationMs);
|
|
3724
|
-
const normalized = error instanceof Error ? error : new Error(String(error));
|
|
3725
|
-
return {
|
|
3726
|
-
name: flow.name,
|
|
3727
|
-
platform,
|
|
3728
|
-
status: "failed",
|
|
3729
|
-
durationMs,
|
|
3730
|
-
error: classifyError(normalized, {
|
|
3731
|
-
flowFilePath: flow.sourcePath,
|
|
3732
|
-
fallbackStack: stepRecorder.getLastFailureStack?.()
|
|
3733
|
-
}),
|
|
3734
|
-
attachments,
|
|
3735
|
-
steps,
|
|
3736
|
-
scenarioSteps: flowCtx.__scenarioSteps
|
|
3737
|
-
};
|
|
3738
|
-
};
|
|
3739
|
-
if (driver.beginFlow) {
|
|
3740
|
-
try {
|
|
3741
|
-
await Effect6.runPromise(driver.beginFlow(flow.name));
|
|
3742
|
-
} catch (error) {
|
|
3743
|
-
return buildFailureResult(error);
|
|
3744
|
-
}
|
|
3745
|
-
}
|
|
3746
|
-
if (artifactConfig.jsCoverage && platform === "web") {
|
|
3747
|
-
if (!driver.startJSCoverage || !driver.stopJSCoverage) {
|
|
3748
|
-
return buildFailureResult(
|
|
3749
|
-
new Error(
|
|
3750
|
-
"JavaScript coverage is not supported on web with the current driver; use Chromium with Playwright or direct CDP"
|
|
3751
|
-
)
|
|
3752
|
-
);
|
|
3753
|
-
}
|
|
3754
|
-
try {
|
|
3755
|
-
await Effect6.runPromise(driver.startJSCoverage());
|
|
3756
|
-
collectingCoverage = true;
|
|
3757
|
-
} catch (error) {
|
|
3758
|
-
return buildFailureResult(error);
|
|
3759
|
-
}
|
|
3760
|
-
}
|
|
3761
|
-
if (wantRecording) {
|
|
3762
|
-
try {
|
|
3763
|
-
if (isCdpScreencastCapable(driver.domChannel)) {
|
|
3764
|
-
videoRecorder = await startCdpScreencastRecorder(driver.domChannel, {
|
|
3765
|
-
flowName: flow.name,
|
|
3766
|
-
platform,
|
|
3767
|
-
exportMp4: artifactConfig.video !== "off"
|
|
3768
|
-
});
|
|
3769
|
-
} else if (artifactConfig.video !== "off" && (platform === "android" || platform === "ios")) {
|
|
3770
|
-
const info = await Effect6.runPromise(Effect6.orDie(driver.getDeviceInfo())).catch(
|
|
3771
|
-
() => void 0
|
|
3772
|
-
);
|
|
3773
|
-
if (info?.deviceId) {
|
|
3774
|
-
const outDir = flowArtifactDir(artifactConfig, flow.name, platform);
|
|
3775
|
-
const videoOut = join5(outDir, `${safeArtifactName(flow.name)}.mp4`);
|
|
3776
|
-
videoRecorder = platform === "android" ? startAndroidVideoRecorder(info.deviceId, { outputPath: videoOut }) : startIosSimulatorVideoRecorder(info.deviceId, { outputPath: videoOut });
|
|
3777
|
-
}
|
|
3778
|
-
}
|
|
3779
|
-
} catch {
|
|
3780
|
-
}
|
|
3781
|
-
}
|
|
3782
|
-
if (config.hooks?.beforeEach) {
|
|
3783
|
-
try {
|
|
3784
|
-
await config.hooks.beforeEach({ app, platform });
|
|
3785
|
-
} catch (error) {
|
|
3786
|
-
return buildFailureResult(error);
|
|
3787
|
-
}
|
|
3788
|
-
}
|
|
3789
|
-
let result;
|
|
3790
|
-
let softFailureError;
|
|
3791
|
-
try {
|
|
3792
|
-
if (autoLaunch) {
|
|
3793
|
-
await app.launch();
|
|
3794
|
-
}
|
|
3795
|
-
await Promise.race([
|
|
3796
|
-
flow.fn(flowCtx),
|
|
3797
|
-
new Promise(
|
|
3798
|
-
(_, reject) => setTimeout(
|
|
3799
|
-
() => reject(new Error(`Flow "${flow.name}" timed out after ${timeout}ms`)),
|
|
3800
|
-
timeout
|
|
3801
|
-
)
|
|
3802
|
-
)
|
|
3803
|
-
]);
|
|
3804
|
-
if (softFailures.length > 0) {
|
|
3805
|
-
softFailureError = aggregateFailures();
|
|
3806
|
-
throw softFailureError;
|
|
3807
|
-
}
|
|
3808
|
-
const attachments = await captureArtifacts(
|
|
3809
|
-
driver,
|
|
3810
|
-
artifactConfig,
|
|
3811
|
-
flow.name,
|
|
3812
|
-
platform,
|
|
3813
|
-
"passed"
|
|
3814
|
-
);
|
|
3815
|
-
await captureCoverage(attachments, "passed");
|
|
3816
|
-
const steps = stepRecorder.getSteps();
|
|
3817
|
-
const durationMs = Date.now() - start2;
|
|
3818
|
-
await finalizeRecording("passed", attachments, steps, durationMs);
|
|
3819
|
-
result = {
|
|
3820
|
-
name: flow.name,
|
|
3821
|
-
platform,
|
|
3822
|
-
status: "passed",
|
|
3823
|
-
durationMs,
|
|
3824
|
-
attachments,
|
|
3825
|
-
steps,
|
|
3826
|
-
scenarioSteps: flowCtx.__scenarioSteps
|
|
3827
|
-
};
|
|
3828
|
-
} catch (error) {
|
|
3829
|
-
const attachments = await captureArtifacts(
|
|
3830
|
-
driver,
|
|
3831
|
-
artifactConfig,
|
|
3832
|
-
flow.name,
|
|
3833
|
-
platform,
|
|
3834
|
-
"failed"
|
|
3835
|
-
);
|
|
3836
|
-
await captureCoverage(attachments, "failed");
|
|
3837
|
-
const steps = stepRecorder.getSteps();
|
|
3838
|
-
const durationMs = Date.now() - start2;
|
|
3839
|
-
await finalizeRecording("failed", attachments, steps, durationMs);
|
|
3840
|
-
const normalized = error instanceof Error ? error : new Error(String(error));
|
|
3841
|
-
const flowError = softFailures.length > 0 && error !== softFailureError ? aggregateFailures(normalized) : normalized;
|
|
3842
|
-
result = {
|
|
3843
|
-
name: flow.name,
|
|
3844
|
-
platform,
|
|
3845
|
-
status: "failed",
|
|
3846
|
-
durationMs,
|
|
3847
|
-
error: classifyError(flowError, {
|
|
3848
|
-
flowFilePath: flow.sourcePath,
|
|
3849
|
-
fallbackStack: stepRecorder.getLastFailureStack?.()
|
|
3850
|
-
}),
|
|
3851
|
-
attachments,
|
|
3852
|
-
steps,
|
|
3853
|
-
scenarioSteps: flowCtx.__scenarioSteps
|
|
3854
|
-
};
|
|
3855
|
-
if (artifactConfig.captureOnFailure && result.error) {
|
|
3856
|
-
try {
|
|
3857
|
-
const artDir = join5(
|
|
3858
|
-
artifactConfig.outputDir,
|
|
3859
|
-
`${flow.name.replaceAll(/[^a-zA-Z0-9-_]/g, "_").replaceAll(/_+/g, "_").slice(0, 80) || "artifact"}-${platform}`
|
|
3860
|
-
);
|
|
3861
|
-
const bundle = createFailureBundle(
|
|
3862
|
-
flow.name,
|
|
3863
|
-
platform,
|
|
3864
|
-
stepRecorder.getSteps(),
|
|
3865
|
-
result.error,
|
|
3866
|
-
artDir,
|
|
3867
|
-
attachments,
|
|
3868
|
-
flow.sourcePath
|
|
3869
|
-
);
|
|
3870
|
-
writeFailureBundle(bundle, artDir);
|
|
3871
|
-
} catch {
|
|
3872
|
-
}
|
|
3873
|
-
}
|
|
3874
|
-
if (config.debugOnFailure) {
|
|
3875
|
-
await runDebugReplOnce({
|
|
3876
|
-
app,
|
|
3877
|
-
expect,
|
|
3878
|
-
driver,
|
|
3879
|
-
error: flowError,
|
|
3880
|
-
flowName: flow.name,
|
|
3881
|
-
platform,
|
|
3882
|
-
parseHierarchy: coordinatorConfig.parse
|
|
3883
|
-
});
|
|
3884
|
-
}
|
|
3885
|
-
}
|
|
3886
|
-
for (const cleanup of extraCleanups.toReversed()) {
|
|
3887
|
-
try {
|
|
3888
|
-
await cleanup();
|
|
3889
|
-
} catch {
|
|
3890
|
-
}
|
|
3891
|
-
}
|
|
3892
|
-
try {
|
|
3893
|
-
await sessionManager.disconnectAll();
|
|
3894
|
-
} catch {
|
|
3895
|
-
}
|
|
3896
|
-
if (config.hooks?.afterEach) {
|
|
3897
|
-
try {
|
|
3898
|
-
await config.hooks.afterEach({ app, platform, result });
|
|
3899
|
-
} catch (hookError) {
|
|
3900
|
-
console.warn(
|
|
3901
|
-
`afterEach hook failed: ${hookError instanceof Error ? hookError.message : hookError}`
|
|
3902
|
-
);
|
|
3903
|
-
}
|
|
3904
|
-
}
|
|
3905
|
-
return result;
|
|
3906
|
-
}
|
|
3907
|
-
|
|
3908
|
-
// src/core/parallel.ts
|
|
3909
|
-
function orderFlowsLongestFirst(flows, durationHintsMs) {
|
|
3910
|
-
if (!durationHintsMs || Object.keys(durationHintsMs).length === 0) {
|
|
3911
|
-
return flows;
|
|
3912
|
-
}
|
|
3913
|
-
return flows.toSorted((a, b) => (durationHintsMs[b.name] ?? 0) - (durationHintsMs[a.name] ?? 0));
|
|
3914
|
-
}
|
|
3915
|
-
async function runParallel(config) {
|
|
3916
|
-
const {
|
|
3917
|
-
workers,
|
|
3918
|
-
flows: rawFlows,
|
|
3919
|
-
onFlowComplete,
|
|
3920
|
-
onFlowStart,
|
|
3921
|
-
retries = 0,
|
|
3922
|
-
retryDelay = 0,
|
|
3923
|
-
bail,
|
|
3924
|
-
durationHintsMs,
|
|
3925
|
-
claimNextFlow
|
|
3926
|
-
} = config;
|
|
3927
|
-
const flows = orderFlowsLongestFirst(focusFlows(rawFlows), durationHintsMs);
|
|
3928
|
-
const start2 = Date.now();
|
|
3929
|
-
const results = [];
|
|
3930
|
-
let nextFlowIndex = 0;
|
|
3931
|
-
let failureCount = 0;
|
|
3932
|
-
let bailedOut = false;
|
|
3933
|
-
const workerPromises = workers.map(async (worker) => {
|
|
3934
|
-
const stats = { flowCount: 0, totalMs: 0 };
|
|
3935
|
-
while (true) {
|
|
3936
|
-
if (bail !== void 0 && failureCount >= bail) break;
|
|
3937
|
-
let flow;
|
|
3938
|
-
if (claimNextFlow) {
|
|
3939
|
-
const claimed = await claimNextFlow();
|
|
3940
|
-
if (!claimed) break;
|
|
3941
|
-
flow = claimed;
|
|
3942
|
-
} else {
|
|
3943
|
-
const flowIdx = nextFlowIndex++;
|
|
3944
|
-
if (flowIdx >= flows.length) break;
|
|
3945
|
-
flow = flows[flowIdx];
|
|
3946
|
-
}
|
|
3947
|
-
const skip = getFlowSkip(flow, worker.engineConfig.platform);
|
|
3948
|
-
if (skip) {
|
|
3949
|
-
results.push(skip);
|
|
3950
|
-
onFlowComplete?.(skip, worker.name);
|
|
3951
|
-
continue;
|
|
3952
|
-
}
|
|
3953
|
-
const flowRetries = flow.config.retries ?? retries;
|
|
3954
|
-
onFlowStart?.(flow.name, worker.name);
|
|
3955
|
-
let result = await executeFlow(flow, worker.driver, worker.engineConfig);
|
|
3956
|
-
let attempts = 1;
|
|
3957
|
-
while (result.status === "failed" && attempts <= flowRetries) {
|
|
3958
|
-
if (retryDelay > 0) {
|
|
3959
|
-
await new Promise((resolve) => setTimeout(resolve, retryDelay));
|
|
3960
|
-
}
|
|
3961
|
-
result = await executeFlow(flow, worker.driver, worker.engineConfig);
|
|
3962
|
-
attempts++;
|
|
3963
|
-
}
|
|
3964
|
-
if (result.status === "passed" && attempts > 1) {
|
|
3965
|
-
result.flaky = true;
|
|
3966
|
-
}
|
|
3967
|
-
result.attempts = attempts;
|
|
3968
|
-
results.push(result);
|
|
3969
|
-
stats.flowCount++;
|
|
3970
|
-
stats.totalMs += result.durationMs;
|
|
3971
|
-
if (result.status === "failed") {
|
|
3972
|
-
failureCount++;
|
|
3973
|
-
}
|
|
3974
|
-
onFlowComplete?.(result, worker.name);
|
|
3975
|
-
}
|
|
3976
|
-
return { workerId: worker.id, stats };
|
|
3977
|
-
});
|
|
3978
|
-
const workerResults = await Promise.all(workerPromises);
|
|
3979
|
-
if (!claimNextFlow && bail !== void 0 && failureCount >= bail) {
|
|
3980
|
-
bailedOut = true;
|
|
3981
|
-
while (nextFlowIndex < flows.length) {
|
|
3982
|
-
const flow = flows[nextFlowIndex++];
|
|
3983
|
-
results.push(
|
|
3984
|
-
getFlowSkip(flow, workers[0].engineConfig.platform) ?? {
|
|
3985
|
-
name: flow.name,
|
|
3986
|
-
platform: workers[0].engineConfig.platform,
|
|
3987
|
-
status: "skipped",
|
|
3988
|
-
durationMs: 0,
|
|
3989
|
-
attempts: 0
|
|
3990
|
-
}
|
|
3991
|
-
);
|
|
3992
|
-
}
|
|
3993
|
-
}
|
|
3994
|
-
const workerStats = /* @__PURE__ */ new Map();
|
|
3995
|
-
for (const wr of workerResults) {
|
|
3996
|
-
workerStats.set(wr.workerId, wr.stats);
|
|
3997
|
-
}
|
|
3998
|
-
return {
|
|
3999
|
-
results,
|
|
4000
|
-
totalDurationMs: Date.now() - start2,
|
|
4001
|
-
passed: results.filter((r) => r.status === "passed").length,
|
|
4002
|
-
failed: results.filter((r) => r.status === "failed").length,
|
|
4003
|
-
skipped: results.filter((r) => r.status === "skipped").length,
|
|
4004
|
-
flaky: results.filter((r) => r.flaky === true).length,
|
|
4005
|
-
bailedOut: bailedOut || void 0,
|
|
4006
|
-
workerStats
|
|
4007
|
-
};
|
|
4008
|
-
}
|
|
4009
|
-
|
|
4010
|
-
// src/core/worker-pool.ts
|
|
4011
|
-
import { spawn as spawn3 } from "child_process";
|
|
4012
|
-
import { mkdir, readFile as readFile2, unlink, writeFile as writeFile2 } from "fs/promises";
|
|
4013
|
-
import { createServer } from "http";
|
|
4014
|
-
import { dirname } from "path";
|
|
4015
|
-
var DEFAULT_MAX_WORKERS_PER_PROCESS = 8;
|
|
4016
|
-
async function startSharedFlowQueueServer(orderedFlowNames) {
|
|
4017
|
-
const queue = [...orderedFlowNames];
|
|
4018
|
-
let cursor = 0;
|
|
4019
|
-
const server = createServer((req, res) => {
|
|
4020
|
-
if (req.url === "/claim" && (req.method === "POST" || req.method === "GET")) {
|
|
4021
|
-
const flowName = cursor < queue.length ? queue[cursor++] : null;
|
|
4022
|
-
const body = JSON.stringify({ flowName });
|
|
4023
|
-
res.writeHead(200, { "content-type": "application/json" });
|
|
4024
|
-
res.end(body);
|
|
4025
|
-
return;
|
|
4026
|
-
}
|
|
4027
|
-
res.writeHead(404);
|
|
4028
|
-
res.end();
|
|
4029
|
-
});
|
|
4030
|
-
await new Promise((resolve, reject) => {
|
|
4031
|
-
server.once("error", reject);
|
|
4032
|
-
server.listen(0, "127.0.0.1", () => resolve());
|
|
4033
|
-
});
|
|
4034
|
-
const addr = server.address();
|
|
4035
|
-
const url = `http://127.0.0.1:${addr.port}`;
|
|
4036
|
-
return {
|
|
4037
|
-
url,
|
|
4038
|
-
remaining: () => Math.max(0, queue.length - cursor),
|
|
4039
|
-
close: () => new Promise((resolve) => {
|
|
4040
|
-
server.close(() => resolve());
|
|
4041
|
-
})
|
|
4042
|
-
};
|
|
4043
|
-
}
|
|
4044
|
-
function createRemoteFlowClaimer(queueUrl) {
|
|
4045
|
-
const endpoint = `${queueUrl.replace(/\/+$/, "")}/claim`;
|
|
4046
|
-
return async () => {
|
|
4047
|
-
const res = await fetch(endpoint, { method: "POST" });
|
|
4048
|
-
if (!res.ok) return null;
|
|
4049
|
-
const data = await res.json();
|
|
4050
|
-
return typeof data.flowName === "string" ? data.flowName : null;
|
|
4051
|
-
};
|
|
4052
|
-
}
|
|
4053
|
-
function planProcessPool(totalWorkers, maxWorkersPerProcess = DEFAULT_MAX_WORKERS_PER_PROCESS, explicitProcesses) {
|
|
4054
|
-
const safeTotal = Math.max(1, Math.floor(totalWorkers));
|
|
4055
|
-
const safeMax = Math.max(1, Math.floor(maxWorkersPerProcess));
|
|
4056
|
-
const processCount = explicitProcesses !== void 0 && explicitProcesses >= 1 ? Math.min(Math.floor(explicitProcesses), safeTotal) : safeTotal <= safeMax ? 1 : Math.ceil(safeTotal / safeMax);
|
|
4057
|
-
if (processCount <= 1) {
|
|
4058
|
-
return {
|
|
4059
|
-
totalWorkers: safeTotal,
|
|
4060
|
-
maxWorkersPerProcess: safeMax,
|
|
4061
|
-
processCount: 1,
|
|
4062
|
-
workersPerProcess: [safeTotal]
|
|
4063
|
-
};
|
|
4064
|
-
}
|
|
4065
|
-
const base = Math.floor(safeTotal / processCount);
|
|
4066
|
-
const remainder = safeTotal % processCount;
|
|
4067
|
-
const workersPerProcess = Array.from(
|
|
4068
|
-
{ length: processCount },
|
|
4069
|
-
(_v, i) => base + (i < remainder ? 1 : 0)
|
|
4070
|
-
);
|
|
4071
|
-
return {
|
|
4072
|
-
totalWorkers: safeTotal,
|
|
4073
|
-
maxWorkersPerProcess: safeMax,
|
|
4074
|
-
processCount,
|
|
4075
|
-
workersPerProcess
|
|
4076
|
-
};
|
|
4077
|
-
}
|
|
4078
|
-
function partitionFlowsAcrossProcesses(items, processCount, options) {
|
|
4079
|
-
const count = Math.max(1, Math.min(Math.floor(processCount), Math.max(1, items.length)));
|
|
4080
|
-
if (count === 1 || items.length === 0) {
|
|
4081
|
-
return items.length === 0 ? [] : [items];
|
|
4082
|
-
}
|
|
4083
|
-
const hints = options?.durationHintsMs;
|
|
4084
|
-
const getName = options?.getName;
|
|
4085
|
-
const known = hints ? Object.values(hints).filter((v) => typeof v === "number" && v > 0) : [];
|
|
4086
|
-
const defaultWeight = known.length > 0 ? known.reduce((a, b) => a + b, 0) / known.length : 1e3;
|
|
4087
|
-
const indexed = items.map((item, idx) => ({
|
|
4088
|
-
item,
|
|
4089
|
-
idx,
|
|
4090
|
-
weight: hints && getName ? hints[getName(item)] ?? defaultWeight : 1e3
|
|
4091
|
-
}));
|
|
4092
|
-
const ordered = hints && getName && Object.keys(hints).length > 0 ? indexed.toSorted((a, b) => b.weight - a.weight || a.idx - b.idx) : indexed;
|
|
4093
|
-
const loads = Array.from({ length: count }, () => 0);
|
|
4094
|
-
const buckets = Array.from({ length: count }, () => []);
|
|
4095
|
-
for (const entry of ordered) {
|
|
4096
|
-
let best = 0;
|
|
4097
|
-
for (let i = 1; i < count; i++) {
|
|
4098
|
-
if (loads[i] < loads[best]) best = i;
|
|
4099
|
-
}
|
|
4100
|
-
loads[best] = loads[best] + entry.weight;
|
|
4101
|
-
buckets[best].push({ item: entry.item, idx: entry.idx });
|
|
4102
|
-
}
|
|
4103
|
-
return buckets.map((bucket) => bucket.toSorted((a, b) => a.idx - b.idx).map((e) => e.item)).filter((b) => b.length > 0);
|
|
4104
|
-
}
|
|
4105
|
-
async function writeWorkerProcessReport(results, env = process.env) {
|
|
4106
|
-
const reportPath = env["SPANA_WORKER_REPORT_PATH"];
|
|
4107
|
-
if (!reportPath) return null;
|
|
4108
|
-
await mkdir(dirname(reportPath), { recursive: true });
|
|
4109
|
-
await writeFile2(reportPath, JSON.stringify({ results }, null, 2), "utf8");
|
|
4110
|
-
return reportPath;
|
|
4111
|
-
}
|
|
4112
|
-
async function defaultReadJsonReport(reportJsonPath) {
|
|
4113
|
-
let content;
|
|
4114
|
-
try {
|
|
4115
|
-
content = await readFile2(reportJsonPath, "utf8");
|
|
4116
|
-
} catch {
|
|
4117
|
-
return [];
|
|
4118
|
-
}
|
|
4119
|
-
const raw = JSON.parse(content);
|
|
4120
|
-
return Array.isArray(raw.results) ? raw.results : [];
|
|
4121
|
-
}
|
|
4122
|
-
async function runMultiProcessPool(options) {
|
|
4123
|
-
const plan = planProcessPool(
|
|
4124
|
-
options.totalWorkers,
|
|
4125
|
-
options.maxWorkersPerProcess,
|
|
4126
|
-
options.processes
|
|
4127
|
-
);
|
|
4128
|
-
const spawnFn = options.spawnFn ?? spawn3;
|
|
4129
|
-
const readReport = options.readReportFn ?? defaultReadJsonReport;
|
|
4130
|
-
const shouldCleanup = options.cleanupReportFiles !== false;
|
|
4131
|
-
const startedAt = Date.now();
|
|
4132
|
-
const processResults = await Promise.all(
|
|
4133
|
-
plan.workersPerProcess.map(async (workerCount, shardIdx) => {
|
|
4134
|
-
const shardStart = Date.now();
|
|
4135
|
-
const spec = options.buildShardCommand(shardIdx + 1, plan.processCount, workerCount);
|
|
4136
|
-
let exitCode = null;
|
|
4137
|
-
let spawnError;
|
|
4138
|
-
try {
|
|
4139
|
-
exitCode = await new Promise((resolve, reject) => {
|
|
4140
|
-
const child = spawnFn(spec.command, spec.args, {
|
|
4141
|
-
env: { ...process.env, ...spec.env },
|
|
4142
|
-
stdio: "inherit"
|
|
4143
|
-
});
|
|
4144
|
-
child.on("error", reject);
|
|
4145
|
-
child.on("close", (code) => resolve(code));
|
|
4146
|
-
});
|
|
4147
|
-
} catch (err) {
|
|
4148
|
-
spawnError = err instanceof Error ? err.message : String(err);
|
|
4149
|
-
}
|
|
4150
|
-
let shardResults = [];
|
|
4151
|
-
try {
|
|
4152
|
-
shardResults = await readReport(spec.reportJsonPath);
|
|
4153
|
-
} catch (err) {
|
|
4154
|
-
if (!spawnError) {
|
|
4155
|
-
spawnError = `Failed to parse shard ${shardIdx + 1} report: ${err instanceof Error ? err.message : String(err)}`;
|
|
4156
|
-
}
|
|
4157
|
-
}
|
|
4158
|
-
if (shouldCleanup) {
|
|
4159
|
-
try {
|
|
4160
|
-
await unlink(spec.reportJsonPath);
|
|
4161
|
-
} catch {
|
|
4162
|
-
}
|
|
4163
|
-
}
|
|
4164
|
-
if (exitCode !== 0 && shardResults.length === 0) {
|
|
4165
|
-
shardResults.push({
|
|
4166
|
-
name: `worker-process-${shardIdx + 1}`,
|
|
4167
|
-
platform: "web",
|
|
4168
|
-
status: "failed",
|
|
4169
|
-
durationMs: Date.now() - shardStart,
|
|
4170
|
-
error: {
|
|
4171
|
-
category: "driver-error",
|
|
4172
|
-
message: spawnError ?? `Worker process ${shardIdx + 1} exited with code ${exitCode ?? "unknown"}`
|
|
4173
|
-
}
|
|
4174
|
-
});
|
|
4175
|
-
}
|
|
4176
|
-
return {
|
|
4177
|
-
shardIndex: shardIdx + 1,
|
|
4178
|
-
workerCount,
|
|
4179
|
-
exitCode,
|
|
4180
|
-
durationMs: Date.now() - shardStart,
|
|
4181
|
-
results: shardResults,
|
|
4182
|
-
...spawnError ? { error: spawnError } : {}
|
|
4183
|
-
};
|
|
4184
|
-
})
|
|
4185
|
-
);
|
|
4186
|
-
const results = processResults.flatMap((p) => p.results);
|
|
4187
|
-
const passed = results.filter((r) => r.status === "passed").length;
|
|
4188
|
-
const failed = results.filter((r) => r.status === "failed").length;
|
|
4189
|
-
const skipped = results.filter((r) => r.status === "skipped").length;
|
|
4190
|
-
const flaky = results.filter((r) => r.flaky).length;
|
|
4191
|
-
return {
|
|
4192
|
-
results,
|
|
4193
|
-
totalDurationMs: Date.now() - startedAt,
|
|
4194
|
-
passed,
|
|
4195
|
-
failed,
|
|
4196
|
-
skipped,
|
|
4197
|
-
flaky,
|
|
4198
|
-
processCount: plan.processCount,
|
|
4199
|
-
processResults
|
|
4200
|
-
};
|
|
4201
|
-
}
|
|
4202
|
-
|
|
4203
3755
|
export {
|
|
3756
|
+
defineDriverAdapter,
|
|
3757
|
+
defineDomTransport,
|
|
3758
|
+
registerDriverAdapter,
|
|
3759
|
+
unregisterDriverAdapter,
|
|
3760
|
+
listDriverAdapters,
|
|
3761
|
+
resolveDriverAdapter,
|
|
3762
|
+
registerDomTransport,
|
|
3763
|
+
unregisterDomTransport,
|
|
3764
|
+
listDomTransports,
|
|
3765
|
+
resolveDomTransport,
|
|
3766
|
+
resolveBrowserExtensions,
|
|
3767
|
+
applyExtensionChromeArgs,
|
|
3768
|
+
getLoadedExtensions,
|
|
3769
|
+
runOAuthPopupFlow,
|
|
4204
3770
|
launchDirectCdpBrowser,
|
|
4205
3771
|
UPLOAD_ATTACH_TIMEOUT_MS,
|
|
4206
3772
|
makeLightweightCdpDriver,
|
|
@@ -4211,24 +3777,6 @@ export {
|
|
|
4211
3777
|
buildElectronRuntime,
|
|
4212
3778
|
buildElectrobunRuntime,
|
|
4213
3779
|
buildLocalAndroidRuntime,
|
|
4214
|
-
buildLocalIOSRuntime
|
|
4215
|
-
formatCodeFrame,
|
|
4216
|
-
extractCodeFrame,
|
|
4217
|
-
classifyError,
|
|
4218
|
-
exportFramesToMp4,
|
|
4219
|
-
startCdpScreencastRecorder,
|
|
4220
|
-
startAndroidVideoRecorder,
|
|
4221
|
-
startIosSimulatorVideoRecorder,
|
|
4222
|
-
buildPlaybackTraceFromSteps,
|
|
4223
|
-
executeFlow,
|
|
4224
|
-
orderFlowsLongestFirst,
|
|
4225
|
-
runParallel,
|
|
4226
|
-
DEFAULT_MAX_WORKERS_PER_PROCESS,
|
|
4227
|
-
startSharedFlowQueueServer,
|
|
4228
|
-
createRemoteFlowClaimer,
|
|
4229
|
-
planProcessPool,
|
|
4230
|
-
partitionFlowsAcrossProcesses,
|
|
4231
|
-
writeWorkerProcessReport,
|
|
4232
|
-
runMultiProcessPool
|
|
3780
|
+
buildLocalIOSRuntime
|
|
4233
3781
|
};
|
|
4234
|
-
//# sourceMappingURL=chunk-
|
|
3782
|
+
//# sourceMappingURL=chunk-BWEQ4XT2.js.map
|