spana-test 0.14.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/dist/{accessibility-audit-MHQ65DUD.js → accessibility-audit-F5KLUHLS.js} +14 -3
  2. package/dist/accessibility-audit-F5KLUHLS.js.map +1 -0
  3. package/dist/agent/index.js +11 -11
  4. package/dist/agent/session.d.ts +1 -1
  5. package/dist/agent/session.d.ts.map +1 -1
  6. package/dist/api/app.d.ts +11 -2
  7. package/dist/api/app.d.ts.map +1 -1
  8. package/dist/api/expect.d.ts +2 -2
  9. package/dist/api/expect.d.ts.map +1 -1
  10. package/dist/api/flow.d.ts +2 -0
  11. package/dist/api/flow.d.ts.map +1 -1
  12. package/dist/{app-JTWXTFDY.js → app-C353NGBT.js} +3 -3
  13. package/dist/channels/cdp-client.d.ts +14 -5
  14. package/dist/channels/cdp-client.d.ts.map +1 -1
  15. package/dist/channels/dom-channel.d.ts +4 -2
  16. package/dist/channels/dom-channel.d.ts.map +1 -1
  17. package/dist/{chunk-IWGRZNKU.js → chunk-4TYO6O7T.js} +2 -2
  18. package/dist/{chunk-T4FCROSE.js → chunk-5WPPWTC3.js} +740 -257
  19. package/dist/chunk-5WPPWTC3.js.map +1 -0
  20. package/dist/{chunk-PCVXXIEJ.js → chunk-62SDNQKK.js} +3 -3
  21. package/dist/{chunk-WKN6ZW7V.js → chunk-7K7WVTFZ.js} +6 -6
  22. package/dist/{chunk-KWIB77C7.js → chunk-7O5YXVCD.js} +2 -2
  23. package/dist/{chunk-63OBFF2I.js → chunk-CA66JCX2.js} +282 -52
  24. package/dist/chunk-CA66JCX2.js.map +1 -0
  25. package/dist/{chunk-MTCRATOA.js → chunk-EA7DZ5TN.js} +13 -2
  26. package/dist/chunk-EA7DZ5TN.js.map +1 -0
  27. package/dist/{chunk-U7633AII.js → chunk-GMEVJQTT.js} +5 -2
  28. package/dist/chunk-GMEVJQTT.js.map +1 -0
  29. package/dist/{chunk-7WC7NPRU.js → chunk-HIEOI3WN.js} +411 -135
  30. package/dist/chunk-HIEOI3WN.js.map +1 -0
  31. package/dist/{chunk-RGLPQNJG.js → chunk-HJZT6YOA.js} +2 -2
  32. package/dist/{chunk-RQ5TJJZU.js → chunk-JRGJTUPS.js} +3 -3
  33. package/dist/{chunk-JHJSAIPG.js → chunk-KIFNHFFI.js} +47 -19
  34. package/dist/chunk-KIFNHFFI.js.map +1 -0
  35. package/dist/{chunk-NMN2ENQZ.js → chunk-LGFTUVN4.js} +2 -2
  36. package/dist/{chunk-E2JJOVPP.js → chunk-UZU7VYKN.js} +107 -24
  37. package/dist/chunk-UZU7VYKN.js.map +1 -0
  38. package/dist/{chunk-2SJNPLLU.js → chunk-WBCAF7SC.js} +285 -77
  39. package/dist/chunk-WBCAF7SC.js.map +1 -0
  40. package/dist/{chunk-7EMHU56B.js → chunk-ZCSH3QKX.js} +882 -426
  41. package/dist/chunk-ZCSH3QKX.js.map +1 -0
  42. package/dist/cli/config-loader.d.ts.map +1 -1
  43. package/dist/cli/iteration.d.ts +13 -0
  44. package/dist/cli/iteration.d.ts.map +1 -1
  45. package/dist/cli/test-command.d.ts +22 -0
  46. package/dist/cli/test-command.d.ts.map +1 -1
  47. package/dist/cli.js +27 -15
  48. package/dist/cli.js.map +1 -1
  49. package/dist/config-loader-TSADVSBY.js +10 -0
  50. package/dist/core/accessibility-audit.d.ts.map +1 -1
  51. package/dist/core/engine.d.ts.map +1 -1
  52. package/dist/core/orchestrator.d.ts +2 -0
  53. package/dist/core/orchestrator.d.ts.map +1 -1
  54. package/dist/core/parallel.d.ts +9 -1
  55. package/dist/core/parallel.d.ts.map +1 -1
  56. package/dist/core/worker-pool.d.ts +5 -2
  57. package/dist/core/worker-pool.d.ts.map +1 -1
  58. package/dist/{doctor-command-BYKRBS4V.js → doctor-command-UUQ4RFMK.js} +7 -7
  59. package/dist/{driver-GOPO5ZZP.js → driver-3HBDKESK.js} +5 -5
  60. package/dist/{driver-HK4HQAYL.js → driver-LKXSKNG3.js} +4 -4
  61. package/dist/drivers/cdp-browser.d.ts +8 -0
  62. package/dist/drivers/cdp-browser.d.ts.map +1 -1
  63. package/dist/drivers/playwright.d.ts +2 -0
  64. package/dist/drivers/playwright.d.ts.map +1 -1
  65. package/dist/drivers/raw-driver.d.ts +2 -0
  66. package/dist/drivers/raw-driver.d.ts.map +1 -1
  67. package/dist/{electrobun-65Z6KOVN.js → electrobun-HILYDIJ3.js} +5 -5
  68. package/dist/index.d.ts +6 -4
  69. package/dist/index.d.ts.map +1 -1
  70. package/dist/index.js +27 -13
  71. package/dist/index.js.map +1 -1
  72. package/dist/{json-57Z2YSES.js → json-67HY4VQK.js} +6 -1
  73. package/dist/json-67HY4VQK.js.map +1 -0
  74. package/dist/{local-6NRVD5VP.js → local-J2NC6YKI.js} +5 -5
  75. package/dist/{playwright-JUAD3TT4.js → playwright-JMHCABDJ.js} +5 -5
  76. package/dist/report/json.d.ts.map +1 -1
  77. package/dist/report/types.d.ts +2 -0
  78. package/dist/report/types.d.ts.map +1 -1
  79. package/dist/runtime/local.d.ts +0 -4
  80. package/dist/runtime/local.d.ts.map +1 -1
  81. package/dist/schemas/config.d.ts +46 -4
  82. package/dist/schemas/config.d.ts.map +1 -1
  83. package/dist/schemas/element.d.ts +2 -0
  84. package/dist/schemas/element.d.ts.map +1 -1
  85. package/dist/{server-UJ3RDZWT.js → server-RHAHCANZ.js} +2 -2
  86. package/dist/{server-2RCONJCW.js → server-RTDMJIQZ.js} +14 -13
  87. package/dist/{server-2RCONJCW.js.map → server-RTDMJIQZ.js.map} +1 -1
  88. package/dist/{session-7N5XYDXQ.js → session-7CWHTQ2E.js} +12 -12
  89. package/dist/smart/auto-wait.d.ts +2 -0
  90. package/dist/smart/auto-wait.d.ts.map +1 -1
  91. package/dist/smart/coordinator.d.ts +2 -2
  92. package/dist/smart/coordinator.d.ts.map +1 -1
  93. package/dist/studio/api.d.ts +2 -0
  94. package/dist/studio/api.d.ts.map +1 -1
  95. package/dist/studio/routers/inspector.d.ts +2 -0
  96. package/dist/studio/routers/inspector.d.ts.map +1 -1
  97. package/dist/{studio-command-ZCR64XWV.js → studio-command-PZHMLCKE.js} +2 -2
  98. package/dist/{test-command-ENL3DRN4.js → test-command-FJOP2GYD.js} +403 -210
  99. package/dist/test-command-FJOP2GYD.js.map +1 -0
  100. package/package.json +4 -8
  101. package/dist/accessibility-audit-MHQ65DUD.js.map +0 -1
  102. package/dist/chunk-2SJNPLLU.js.map +0 -1
  103. package/dist/chunk-63OBFF2I.js.map +0 -1
  104. package/dist/chunk-7EMHU56B.js.map +0 -1
  105. package/dist/chunk-7WC7NPRU.js.map +0 -1
  106. package/dist/chunk-E2JJOVPP.js.map +0 -1
  107. package/dist/chunk-JHJSAIPG.js.map +0 -1
  108. package/dist/chunk-MTCRATOA.js.map +0 -1
  109. package/dist/chunk-T4FCROSE.js.map +0 -1
  110. package/dist/chunk-U7633AII.js.map +0 -1
  111. package/dist/config-loader-4X7R7XDL.js +0 -10
  112. package/dist/json-57Z2YSES.js.map +0 -1
  113. package/dist/test-command-ENL3DRN4.js.map +0 -1
  114. /package/dist/{app-JTWXTFDY.js.map → app-C353NGBT.js.map} +0 -0
  115. /package/dist/{chunk-IWGRZNKU.js.map → chunk-4TYO6O7T.js.map} +0 -0
  116. /package/dist/{chunk-PCVXXIEJ.js.map → chunk-62SDNQKK.js.map} +0 -0
  117. /package/dist/{chunk-WKN6ZW7V.js.map → chunk-7K7WVTFZ.js.map} +0 -0
  118. /package/dist/{chunk-KWIB77C7.js.map → chunk-7O5YXVCD.js.map} +0 -0
  119. /package/dist/{chunk-RGLPQNJG.js.map → chunk-HJZT6YOA.js.map} +0 -0
  120. /package/dist/{chunk-RQ5TJJZU.js.map → chunk-JRGJTUPS.js.map} +0 -0
  121. /package/dist/{chunk-NMN2ENQZ.js.map → chunk-LGFTUVN4.js.map} +0 -0
  122. /package/dist/{config-loader-4X7R7XDL.js.map → config-loader-TSADVSBY.js.map} +0 -0
  123. /package/dist/{doctor-command-BYKRBS4V.js.map → doctor-command-UUQ4RFMK.js.map} +0 -0
  124. /package/dist/{driver-GOPO5ZZP.js.map → driver-3HBDKESK.js.map} +0 -0
  125. /package/dist/{driver-HK4HQAYL.js.map → driver-LKXSKNG3.js.map} +0 -0
  126. /package/dist/{electrobun-65Z6KOVN.js.map → electrobun-HILYDIJ3.js.map} +0 -0
  127. /package/dist/{local-6NRVD5VP.js.map → local-J2NC6YKI.js.map} +0 -0
  128. /package/dist/{playwright-JUAD3TT4.js.map → playwright-JMHCABDJ.js.map} +0 -0
  129. /package/dist/{server-UJ3RDZWT.js.map → server-RHAHCANZ.js.map} +0 -0
  130. /package/dist/{session-7N5XYDXQ.js.map → session-7CWHTQ2E.js.map} +0 -0
  131. /package/dist/{studio-command-ZCR64XWV.js.map → studio-command-PZHMLCKE.js.map} +0 -0
@@ -7,14 +7,14 @@ import {
7
7
  } from "./chunk-HNQLWFHL.js";
8
8
  import {
9
9
  CdpDomChannel
10
- } from "./chunk-7WC7NPRU.js";
10
+ } from "./chunk-HIEOI3WN.js";
11
11
  import {
12
12
  SPANA_INJECTED_RUNTIME_SCRIPT,
13
13
  SPANA_WASM_HOOK_SCRIPT,
14
14
  buildDomFindElementScript,
15
15
  isWasmTrapError,
16
16
  resolveChromiumGpuArgs
17
- } from "./chunk-63OBFF2I.js";
17
+ } from "./chunk-CA66JCX2.js";
18
18
  import {
19
19
  DriverError
20
20
  } from "./chunk-A7Z52TDQ.js";
@@ -228,8 +228,9 @@ async function waitForDevToolsActivePort(userDataDir, child, getExitInfo, getStd
228
228
  const exit = getExitInfo();
229
229
  if (exit.exited) {
230
230
  const tail2 = getStderr().trim();
231
+ const sandboxHint = /no usable sandbox/i.test(tail2) ? '\nHint: Chromium\'s OS sandbox is blocked on this host (common on Ubuntu 23.10+ / GitHub Actions with AppArmor unprivileged userns restrictions). Either keep `execution.web.chromiumSandbox: false` (default), add `execution.web.args: ["--no-sandbox"]`, or allow unprivileged user namespaces via `sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0`.' : "";
231
232
  throw new Error(
232
- `Direct CDP browser exited prematurely (code=${exit.code}, signal=${exit.signal})${tail2 ? `
233
+ `Direct CDP browser exited prematurely (code=${exit.code}, signal=${exit.signal})${sandboxHint}${tail2 ? `
233
234
  stderr:
234
235
  ${tail2}` : ""}`
235
236
  );
@@ -265,8 +266,11 @@ ${tail}` : ""}`
265
266
  );
266
267
  }
267
268
  function buildDirectChromiumLaunchArgs(options) {
269
+ const extraArgs = options.args ?? [];
270
+ const needNoSandbox = options.chromiumSandbox !== true && !extraArgs.includes("--no-sandbox");
268
271
  return [
269
272
  ...options.headless !== false ? ["--headless=new"] : [],
273
+ ...needNoSandbox ? ["--no-sandbox"] : [],
270
274
  `--remote-debugging-port=${options.remoteDebuggingPort ?? 0}`,
271
275
  "--remote-debugging-address=127.0.0.1",
272
276
  `--user-data-dir=${options.userDataDir}`,
@@ -293,7 +297,7 @@ function buildDirectChromiumLaunchArgs(options) {
293
297
  }),
294
298
  "--metrics-recording-only",
295
299
  "--disable-features=Translate,BackForwardCache,AcceptCHFrame,MediaRouter,OptimizationHints",
296
- ...options.args ?? [],
300
+ ...extraArgs,
297
301
  "about:blank"
298
302
  ];
299
303
  }
@@ -336,11 +340,14 @@ async function launchDirectCdpBrowser(options = {}) {
336
340
  }
337
341
  }
338
342
  execPath = resolveChromiumExecutable(execPath);
339
- const userDataDir = mkdtempSync(join2(tmpdir(), "spana-cdp-profile-"));
343
+ const rawTmp = tmpdir();
344
+ const safeTmpDir = process.platform === "linux" && rawTmp.length > 50 && existsSync2("/tmp") ? "/tmp" : rawTmp;
345
+ const userDataDir = mkdtempSync(join2(safeTmpDir, "spana-cdp-profile-"));
340
346
  const baseChromeArgs = buildDirectChromiumLaunchArgs({
341
347
  userDataDir,
342
348
  remoteDebuggingPort: 0,
343
349
  headless: options.headless,
350
+ chromiumSandbox: options.chromiumSandbox,
344
351
  gpu: options.gpu,
345
352
  webgpu: options.webgpu,
346
353
  args: options.args
@@ -349,7 +356,8 @@ async function launchDirectCdpBrowser(options = {}) {
349
356
  const chromeArgs = resolvedExts.length > 0 ? applyExtensionChromeArgs(baseChromeArgs, resolvedExts) : baseChromeArgs;
350
357
  const child = spawn(execPath, chromeArgs, {
351
358
  detached: Boolean(options.warmBrowser),
352
- stdio: ["ignore", "ignore", "pipe"]
359
+ stdio: ["ignore", "ignore", "pipe"],
360
+ ...safeTmpDir !== rawTmp ? { env: { ...process.env, TMPDIR: safeTmpDir } } : {}
353
361
  });
354
362
  let stderrBuf = "";
355
363
  const MAX_STDERR = 8192;
@@ -596,9 +604,12 @@ function makeLightweightCdpDriver(options) {
596
604
  let height = initialHeight;
597
605
  let emulationMutated = false;
598
606
  let viewportMutated = false;
607
+ let geolocationMutated = false;
608
+ let permissionsMutated = false;
599
609
  let isAtBlank = true;
600
610
  const label = options.engineLabel ?? "cdp";
601
611
  const contextIsolation = options.contextIsolation ?? "hot-cache";
612
+ const readyInitScript = options.readyExpression ? `(() => { window.__SPANA_APP_READY__ = () => { try { return Boolean(${options.readyExpression}); } catch { return false; } }; })();` : void 0;
602
613
  let activeSlot;
603
614
  let prefetchedSlotPromise;
604
615
  let hasRunFirstFlow = false;
@@ -608,11 +619,62 @@ function makeLightweightCdpDriver(options) {
608
619
  const consoleLogs = [];
609
620
  const jsErrors = [];
610
621
  const routeRules = [];
611
- const initScripts = [];
612
- const exposedFunctions = /* @__PURE__ */ new Map();
622
+ const flowInitScripts = [];
623
+ const flowInitScriptIds = /* @__PURE__ */ new Map();
624
+ let clockInitScript = null;
625
+ const clockInitScriptIds = /* @__PURE__ */ new Map();
626
+ const flowExposedFunctions = /* @__PURE__ */ new Map();
627
+ const flowExposedBindingNames = /* @__PURE__ */ new Map();
628
+ const flowExposedScriptIds = /* @__PURE__ */ new Map();
613
629
  const requestListeners = /* @__PURE__ */ new Set();
614
630
  const navigationUrls = [];
631
+ const observedOrigins = /* @__PURE__ */ new Set();
632
+ const observedStorageKeys = /* @__PURE__ */ new Set();
615
633
  const uploadTempDirs = [];
634
+ const recordScriptId = (map, sessionId, res) => {
635
+ const id = res?.identifier;
636
+ if (typeof id === "string" && id.length > 0) {
637
+ const list = map.get(sessionId) ?? [];
638
+ list.push(id);
639
+ map.set(sessionId, list);
640
+ }
641
+ };
642
+ const removeTrackedScripts = async (map) => {
643
+ const ops = [];
644
+ for (const [sid, ids] of map.entries()) {
645
+ for (const identifier of ids) {
646
+ ops.push(
647
+ cdpChannel.sendCommand("Page.removeScriptToEvaluateOnNewDocument", { identifier }, sid).catch(() => {
648
+ })
649
+ );
650
+ }
651
+ }
652
+ map.clear();
653
+ if (ops.length > 0) {
654
+ await Promise.all(ops);
655
+ }
656
+ };
657
+ const cleanupFlowScopedHooks = async () => {
658
+ flowInitScripts.length = 0;
659
+ clockInitScript = null;
660
+ flowExposedFunctions.clear();
661
+ const bindingOps = [];
662
+ for (const [sid, names] of flowExposedBindingNames.entries()) {
663
+ for (const name of names) {
664
+ bindingOps.push(
665
+ cdpChannel.sendCommand("Runtime.removeBinding", { name }, sid).catch(() => {
666
+ })
667
+ );
668
+ }
669
+ }
670
+ flowExposedBindingNames.clear();
671
+ await Promise.all([
672
+ removeTrackedScripts(flowInitScriptIds),
673
+ removeTrackedScripts(clockInitScriptIds),
674
+ removeTrackedScripts(flowExposedScriptIds),
675
+ ...bindingOps
676
+ ]);
677
+ };
616
678
  let currentNetworkConditions;
617
679
  let cachedUserAgent;
618
680
  let fetchInterceptEnabled = false;
@@ -715,6 +777,9 @@ function makeLightweightCdpDriver(options) {
715
777
  const bindingName = `__spana_bind_${name}`;
716
778
  await cdpChannel.sendCommand("Runtime.addBinding", { name: bindingName }, sessionId).catch(() => {
717
779
  });
780
+ const boundSet = flowExposedBindingNames.get(sessionId) ?? /* @__PURE__ */ new Set();
781
+ boundSet.add(bindingName);
782
+ flowExposedBindingNames.set(sessionId, boundSet);
718
783
  const wrapperSource = `(() => {
719
784
  if (window[${JSON.stringify(name)}]) return;
720
785
  let seq = 0;
@@ -725,12 +790,12 @@ function makeLightweightCdpDriver(options) {
725
790
  window[${JSON.stringify(bindingName)}](JSON.stringify({ id, name: ${JSON.stringify(name)}, args }));
726
791
  });
727
792
  })();`;
728
- await cdpChannel.sendCommand("Page.addScriptToEvaluateOnNewDocument", { source: wrapperSource }, sessionId).catch(() => {
729
- });
793
+ const addRes = await cdpChannel.sendCommand("Page.addScriptToEvaluateOnNewDocument", { source: wrapperSource }, sessionId).catch(() => null);
794
+ recordScriptId(flowExposedScriptIds, sessionId, addRes);
730
795
  await cdpChannel.evaluateOnSession(sessionId, wrapperSource).catch(() => {
731
796
  });
732
797
  };
733
- const configureSession = async (sessionId, storageStatePath) => {
798
+ const configureSession = async (sessionId, storageStatePath, includeFlowState = false) => {
734
799
  const state = await loadStorageStateFile(storageStatePath);
735
800
  await Promise.all([
736
801
  cdpChannel.sendCommand("Page.enable", {}, sessionId).catch(() => {
@@ -748,6 +813,14 @@ function makeLightweightCdpDriver(options) {
748
813
  ).catch(() => {
749
814
  })
750
815
  ] : [],
816
+ ...readyInitScript ? [
817
+ cdpChannel.sendCommand(
818
+ "Page.addScriptToEvaluateOnNewDocument",
819
+ { source: readyInitScript },
820
+ sessionId
821
+ ).catch(() => {
822
+ })
823
+ ] : [],
751
824
  cdpChannel.sendCommand(
752
825
  "Target.setAutoAttach",
753
826
  { autoAttach: true, waitForDebuggerOnStart: false, flatten: true },
@@ -769,12 +842,26 @@ function makeLightweightCdpDriver(options) {
769
842
  ).catch(() => {
770
843
  });
771
844
  }
772
- for (const scriptSource of initScripts) {
773
- await cdpChannel.sendCommand("Page.addScriptToEvaluateOnNewDocument", { source: scriptSource }, sessionId).catch(() => {
774
- });
775
- }
776
- for (const fnName of exposedFunctions.keys()) {
777
- await installExposeFunctionOnSession(sessionId, fnName);
845
+ if (includeFlowState) {
846
+ for (const scriptSource of flowInitScripts) {
847
+ const res = await cdpChannel.sendCommand(
848
+ "Page.addScriptToEvaluateOnNewDocument",
849
+ { source: scriptSource },
850
+ sessionId
851
+ ).catch(() => null);
852
+ recordScriptId(flowInitScriptIds, sessionId, res);
853
+ }
854
+ if (clockInitScript) {
855
+ const res = await cdpChannel.sendCommand(
856
+ "Page.addScriptToEvaluateOnNewDocument",
857
+ { source: clockInitScript },
858
+ sessionId
859
+ ).catch(() => null);
860
+ recordScriptId(clockInitScriptIds, sessionId, res);
861
+ }
862
+ for (const fnName of flowExposedFunctions.keys()) {
863
+ await installExposeFunctionOnSession(sessionId, fnName);
864
+ }
778
865
  }
779
866
  if (options.blockResources && options.blockResources.length > 0) {
780
867
  const urls = options.blockResources.flatMap((t) => RESOURCE_BLOCK_PATTERNS[t] ?? []);
@@ -907,59 +994,26 @@ function makeLightweightCdpDriver(options) {
907
994
  };
908
995
  const workerSessions = /* @__PURE__ */ new Map();
909
996
  const wasmTraps = [];
910
- cdpChannel.onEvent("Target.attachedToTarget", (params) => {
997
+ cdpChannel.onEvent("Target.targetCreated", (params) => {
911
998
  const targetInfo = params?.targetInfo;
912
- const childSid = params?.sessionId;
913
- const waiting = Boolean(params?.waitingForDebugger);
914
- if ((targetInfo?.type === "worker" || targetInfo?.type === "service_worker") && typeof childSid === "string") {
915
- workerSessions.set(childSid, typeof targetInfo.url === "string" ? targetInfo.url : "");
916
- void (async () => {
917
- await cdpChannel.sendCommand("Runtime.enable", {}, childSid).catch(() => {
918
- });
919
- await cdpChannel.evaluateOnSession(childSid, SPANA_WASM_HOOK_SCRIPT).catch(() => {
920
- });
921
- if (waiting) {
922
- await cdpChannel.sendCommand("Runtime.runIfWaitingForDebugger", {}, childSid).catch(() => {
923
- });
924
- }
925
- })();
999
+ if (targetInfo?.type !== "page" || !targetInfo.targetId || !targetInfo.openerId || !activeSlot || targetInfo.browserContextId !== activeSlot.browserContextId) {
926
1000
  return;
927
1001
  }
928
- if (targetInfo?.type === "iframe" && typeof childSid === "string") {
929
- cdpChannel.addChildSession(childSid, {
930
- targetId: typeof targetInfo.targetId === "string" ? targetInfo.targetId : void 0,
931
- url: typeof targetInfo.url === "string" ? targetInfo.url : void 0
932
- });
933
- void (async () => {
934
- await cdpChannel.sendCommand("Runtime.enable", {}, childSid).catch(() => {
935
- });
936
- if (useInjectedRuntime) {
937
- await cdpChannel.sendCommand(
938
- "Page.addScriptToEvaluateOnNewDocument",
939
- { source: SPANA_INJECTED_RUNTIME_SCRIPT },
940
- childSid
941
- ).catch(() => {
942
- });
943
- }
944
- if (waiting) {
945
- await cdpChannel.sendCommand("Runtime.runIfWaitingForDebugger", {}, childSid).catch(() => {
946
- });
1002
+ const targetId = String(targetInfo.targetId);
1003
+ if (activeSlot.tabs.some((t) => t.targetId === targetId)) return;
1004
+ void (async () => {
1005
+ try {
1006
+ const attachRes = await cdpChannel.sendCommand(
1007
+ "Target.attachToTarget",
1008
+ { targetId, flatten: true },
1009
+ null
1010
+ );
1011
+ const childSid = attachRes?.sessionId;
1012
+ if (!childSid || !activeSlot) return;
1013
+ const newTabId = `tab-${nextTabSeq++}`;
1014
+ if (!activeSlot.tabs.some((t) => t.targetId === targetId)) {
1015
+ activeSlot.tabs.push({ tabId: newTabId, targetId, sessionId: childSid });
947
1016
  }
948
- })();
949
- } else if (targetInfo?.type === "page" && typeof childSid === "string" && activeSlot && targetInfo.browserContextId === activeSlot.browserContextId) {
950
- const alreadyTracked = activeSlot.tabs.some(
951
- (t) => t.sessionId === childSid || t.targetId === targetInfo.targetId
952
- );
953
- let newTabId;
954
- if (!alreadyTracked) {
955
- newTabId = `tab-${nextTabSeq++}`;
956
- activeSlot.tabs.push({
957
- tabId: newTabId,
958
- targetId: String(targetInfo.targetId ?? ""),
959
- sessionId: childSid
960
- });
961
- }
962
- void (async () => {
963
1017
  const setupCalls = [
964
1018
  cdpChannel.sendCommand("Page.enable", {}, childSid).catch(() => {
965
1019
  }),
@@ -989,24 +1043,100 @@ function makeLightweightCdpDriver(options) {
989
1043
  })
990
1044
  );
991
1045
  }
992
- for (const scriptSource of initScripts) {
1046
+ if (readyInitScript) {
993
1047
  setupCalls.push(
994
1048
  cdpChannel.sendCommand(
995
1049
  "Page.addScriptToEvaluateOnNewDocument",
996
- { source: scriptSource },
1050
+ { source: readyInitScript },
997
1051
  childSid
998
1052
  ).catch(() => {
999
1053
  })
1000
1054
  );
1001
1055
  }
1056
+ for (const scriptSource of flowInitScripts) {
1057
+ setupCalls.push(
1058
+ cdpChannel.sendCommand(
1059
+ "Page.addScriptToEvaluateOnNewDocument",
1060
+ { source: scriptSource },
1061
+ childSid
1062
+ ).then((res) => recordScriptId(flowInitScriptIds, childSid, res)).catch(() => {
1063
+ })
1064
+ );
1065
+ }
1066
+ if (clockInitScript) {
1067
+ setupCalls.push(
1068
+ cdpChannel.sendCommand(
1069
+ "Page.addScriptToEvaluateOnNewDocument",
1070
+ { source: clockInitScript },
1071
+ childSid
1072
+ ).then((res) => recordScriptId(clockInitScriptIds, childSid, res)).catch(() => {
1073
+ })
1074
+ );
1075
+ }
1076
+ for (const fnName of flowExposedFunctions.keys()) {
1077
+ setupCalls.push(installExposeFunctionOnSession(childSid, fnName).catch(() => {
1078
+ }));
1079
+ }
1002
1080
  await Promise.all(setupCalls);
1081
+ if (popupWaiters.length > 0) {
1082
+ const waiter = popupWaiters.shift();
1083
+ if (waiter) waiter.resolve(newTabId);
1084
+ }
1085
+ } catch {
1086
+ }
1087
+ })();
1088
+ });
1089
+ cdpChannel.onEvent("Target.attachedToTarget", (params) => {
1090
+ const targetInfo = params?.targetInfo;
1091
+ const childSid = params?.sessionId;
1092
+ const waiting = Boolean(params?.waitingForDebugger);
1093
+ if ((targetInfo?.type === "worker" || targetInfo?.type === "service_worker") && typeof childSid === "string") {
1094
+ workerSessions.set(childSid, typeof targetInfo.url === "string" ? targetInfo.url : "");
1095
+ void (async () => {
1096
+ await cdpChannel.sendCommand("Runtime.enable", {}, childSid).catch(() => {
1097
+ });
1098
+ await cdpChannel.evaluateOnSession(childSid, SPANA_WASM_HOOK_SCRIPT).catch(() => {
1099
+ });
1003
1100
  if (waiting) {
1004
1101
  await cdpChannel.sendCommand("Runtime.runIfWaitingForDebugger", {}, childSid).catch(() => {
1005
1102
  });
1006
1103
  }
1007
- if (newTabId && popupWaiters.length > 0) {
1008
- const waiter = popupWaiters.shift();
1009
- if (waiter) waiter.resolve(newTabId);
1104
+ })();
1105
+ return;
1106
+ }
1107
+ if (targetInfo?.type === "iframe" && typeof childSid === "string") {
1108
+ const frameTargetId = typeof targetInfo.targetId === "string" ? targetInfo.targetId : void 0;
1109
+ cdpChannel.addChildSession(childSid, {
1110
+ targetId: frameTargetId,
1111
+ url: typeof targetInfo.url === "string" ? targetInfo.url : void 0
1112
+ });
1113
+ if (typeof targetInfo.url === "string") {
1114
+ try {
1115
+ const parsed = new URL(targetInfo.url);
1116
+ if (parsed.protocol === "http:" || parsed.protocol === "https:") {
1117
+ observedOrigins.add(parsed.origin);
1118
+ }
1119
+ } catch {
1120
+ }
1121
+ }
1122
+ void (async () => {
1123
+ await cdpChannel.sendCommand("Runtime.enable", {}, childSid).catch(() => {
1124
+ });
1125
+ if (frameTargetId) {
1126
+ const skRes = await cdpChannel.sendCommand("Storage.getStorageKeyForFrame", { frameId: frameTargetId }, childSid).catch(() => null);
1127
+ if (skRes?.storageKey) observedStorageKeys.add(skRes.storageKey);
1128
+ }
1129
+ if (useInjectedRuntime) {
1130
+ await cdpChannel.sendCommand(
1131
+ "Page.addScriptToEvaluateOnNewDocument",
1132
+ { source: SPANA_INJECTED_RUNTIME_SCRIPT },
1133
+ childSid
1134
+ ).catch(() => {
1135
+ });
1136
+ }
1137
+ if (waiting) {
1138
+ await cdpChannel.sendCommand("Runtime.runIfWaitingForDebugger", {}, childSid).catch(() => {
1139
+ });
1010
1140
  }
1011
1141
  })();
1012
1142
  } else if (waiting && typeof childSid === "string") {
@@ -1018,7 +1148,14 @@ function makeLightweightCdpDriver(options) {
1018
1148
  if (typeof params?.sessionId === "string") {
1019
1149
  cdpChannel.removeChildSession(params.sessionId);
1020
1150
  if (activeSlot) {
1151
+ const wasActive = activeSlot.sessionId === params.sessionId;
1021
1152
  activeSlot.tabs = activeSlot.tabs.filter((t) => t.sessionId !== params.sessionId);
1153
+ if (wasActive && activeSlot.tabs.length > 0) {
1154
+ const fallback = activeSlot.tabs[0];
1155
+ activeSlot.targetId = fallback.targetId;
1156
+ activeSlot.sessionId = fallback.sessionId;
1157
+ cdpChannel.setSessionId(fallback.sessionId);
1158
+ }
1022
1159
  }
1023
1160
  }
1024
1161
  });
@@ -1143,7 +1280,7 @@ function makeLightweightCdpDriver(options) {
1143
1280
  return;
1144
1281
  }
1145
1282
  if (!parsed.id || !parsed.name) return;
1146
- const fn = exposedFunctions.get(parsed.name);
1283
+ const fn = flowExposedFunctions.get(parsed.name);
1147
1284
  if (!fn) return;
1148
1285
  void (async () => {
1149
1286
  try {
@@ -1164,12 +1301,19 @@ function makeLightweightCdpDriver(options) {
1164
1301
  })();
1165
1302
  });
1166
1303
  cdpChannel.onEvent("Network.requestWillBeSent", (params, sid) => {
1167
- if (requestListeners.size === 0) return;
1168
1304
  if (activeSlot && sid && !activeSlot.tabs.some((t) => t.sessionId === sid) && sid !== activeSlot.sessionId) {
1169
1305
  return;
1170
1306
  }
1171
1307
  const req = params?.request;
1172
1308
  if (!req?.url) return;
1309
+ try {
1310
+ const parsed = new URL(String(req.url));
1311
+ if (parsed.protocol === "http:" || parsed.protocol === "https:") {
1312
+ observedOrigins.add(parsed.origin);
1313
+ }
1314
+ } catch {
1315
+ }
1316
+ if (requestListeners.size === 0) return;
1173
1317
  const rawHeaders = req.headers ?? {};
1174
1318
  const headers = {};
1175
1319
  for (const [k, v] of Object.entries(rawHeaders)) {
@@ -1343,17 +1487,15 @@ function makeLightweightCdpDriver(options) {
1343
1487
  if (useContexts) {
1344
1488
  yield* Effect.tryPromise({
1345
1489
  try: () => cdpChannel.sendCommand(
1346
- "Target.setAutoAttach",
1490
+ "Target.setDiscoverTargets",
1347
1491
  {
1348
- autoAttach: true,
1349
- waitForDebuggerOnStart: true,
1350
- flatten: true,
1492
+ discover: true,
1351
1493
  filter: [{ type: "page" }]
1352
1494
  },
1353
1495
  null
1354
1496
  ).catch(() => {
1355
1497
  }),
1356
- catch: () => new DriverError({ message: "Failed to enable Target.setAutoAttach" })
1498
+ catch: () => new DriverError({ message: "Failed to enable Target.setDiscoverTargets" })
1357
1499
  }).pipe(Effect.catch(() => Effect.void));
1358
1500
  activeSlot = yield* Effect.tryPromise({
1359
1501
  try: () => createContextSlot(options.storageState),
@@ -1362,9 +1504,30 @@ function makeLightweightCdpDriver(options) {
1362
1504
  cdpChannel.setSessionId(activeSlot.sessionId);
1363
1505
  activeAuthenticatorId = activeSlot.authenticatorId;
1364
1506
  }
1365
- const resolveUrl = (rawUrl) => rawUrl.startsWith("http://") || rawUrl.startsWith("https://") || rawUrl === "about:blank" ? rawUrl : options.baseUrl ? `${options.baseUrl.replace(/\/$/, "")}/${rawUrl.replace(/^\//, "")}` : rawUrl;
1507
+ const resolveUrlAsync = async (rawUrl) => {
1508
+ if (rawUrl.startsWith("http://") || rawUrl.startsWith("https://") || rawUrl === "about:blank" || rawUrl.startsWith("data:") || rawUrl.startsWith("file:")) {
1509
+ return rawUrl;
1510
+ }
1511
+ if (options.baseUrl && options.baseUrl !== "about:blank") {
1512
+ try {
1513
+ return new URL(rawUrl, options.baseUrl).toString();
1514
+ } catch {
1515
+ return `${options.baseUrl.replace(/\/$/, "")}/${rawUrl.replace(/^\//, "")}`;
1516
+ }
1517
+ }
1518
+ const cur = await cdpChannel.evaluate(
1519
+ "typeof window !== 'undefined' && window.location ? String(window.location.href || '') : ''"
1520
+ ).catch(() => "");
1521
+ if (cur && (cur.startsWith("http://") || cur.startsWith("https://"))) {
1522
+ try {
1523
+ return new URL(rawUrl, new URL(cur).origin).toString();
1524
+ } catch {
1525
+ }
1526
+ }
1527
+ return rawUrl;
1528
+ };
1366
1529
  const navigate = async (rawUrl) => {
1367
- const target = resolveUrl(rawUrl);
1530
+ const target = await resolveUrlAsync(rawUrl);
1368
1531
  if (!useContexts) {
1369
1532
  await cdpChannel.sendCommand("Page.enable").catch(() => {
1370
1533
  });
@@ -1446,7 +1609,107 @@ function makeLightweightCdpDriver(options) {
1446
1609
  }),
1447
1610
  beginFlow: (_flowName) => Effect.tryPromise({
1448
1611
  try: async () => {
1449
- const visitedOrigins = /* @__PURE__ */ new Set();
1612
+ const ensureVirtualAuthenticatorForSlot = async (slot, clearExisting) => {
1613
+ if (!options.virtualAuthenticator) {
1614
+ activeAuthenticatorId = slot.authenticatorId;
1615
+ return;
1616
+ }
1617
+ const authOpts = typeof options.virtualAuthenticator === "object" ? options.virtualAuthenticator : void 0;
1618
+ await cdpChannel.sendCommand("WebAuthn.enable", { enableUI: false }, slot.sessionId).catch(() => {
1619
+ });
1620
+ if (slot.authenticatorId) {
1621
+ if (clearExisting) {
1622
+ try {
1623
+ await cdpChannel.sendCommand(
1624
+ "WebAuthn.clearCredentials",
1625
+ { authenticatorId: slot.authenticatorId },
1626
+ slot.sessionId
1627
+ );
1628
+ } catch {
1629
+ slot.authenticatorId = await attachVirtualAuthenticatorForSession(
1630
+ slot.sessionId,
1631
+ authOpts
1632
+ ).catch(() => void 0);
1633
+ }
1634
+ }
1635
+ } else {
1636
+ slot.authenticatorId = await attachVirtualAuthenticatorForSession(
1637
+ slot.sessionId,
1638
+ authOpts
1639
+ ).catch(() => void 0);
1640
+ }
1641
+ activeAuthenticatorId = slot.authenticatorId;
1642
+ };
1643
+ const ensureActiveSlotHealthy = async () => {
1644
+ if (!activeSlot) return false;
1645
+ const checkSessionAlive = async (sid) => {
1646
+ try {
1647
+ await cdpChannel.sendCommand(
1648
+ "Runtime.evaluate",
1649
+ { expression: "1", returnByValue: true },
1650
+ sid,
1651
+ 2e3
1652
+ );
1653
+ return true;
1654
+ } catch {
1655
+ return false;
1656
+ }
1657
+ };
1658
+ if (activeSlot.tabs.length > 0 && await checkSessionAlive(activeSlot.sessionId)) {
1659
+ return true;
1660
+ }
1661
+ const survivingTabs = activeSlot.tabs.slice();
1662
+ for (const tab of survivingTabs) {
1663
+ if (tab.sessionId !== activeSlot.sessionId && await checkSessionAlive(tab.sessionId)) {
1664
+ activeSlot.targetId = tab.targetId;
1665
+ activeSlot.sessionId = tab.sessionId;
1666
+ cdpChannel.setSessionId(tab.sessionId);
1667
+ return true;
1668
+ }
1669
+ }
1670
+ try {
1671
+ const targetRes = await cdpChannel.sendCommand(
1672
+ "Target.createTarget",
1673
+ {
1674
+ url: "about:blank",
1675
+ browserContextId: activeSlot.browserContextId,
1676
+ width: initialWidth,
1677
+ height: initialHeight
1678
+ },
1679
+ null
1680
+ );
1681
+ const existing = activeSlot.tabs.find((t) => t.targetId === targetRes.targetId);
1682
+ let sid = existing?.sessionId;
1683
+ if (!sid) {
1684
+ const attachRes = await cdpChannel.sendCommand(
1685
+ "Target.attachToTarget",
1686
+ { targetId: targetRes.targetId, flatten: true },
1687
+ null
1688
+ );
1689
+ sid = attachRes.sessionId;
1690
+ }
1691
+ const authId = await configureSession(sid, options.storageState, false);
1692
+ const tabId = existing?.tabId ?? `tab-${nextTabSeq++}`;
1693
+ activeSlot.targetId = targetRes.targetId;
1694
+ activeSlot.sessionId = sid;
1695
+ activeSlot.authenticatorId = authId;
1696
+ activeSlot.tabs = [{ tabId, targetId: targetRes.targetId, sessionId: sid }];
1697
+ cdpChannel.setSessionId(sid);
1698
+ isAtBlank = true;
1699
+ return false;
1700
+ } catch {
1701
+ activeSlot = await createContextSlot(options.storageState);
1702
+ cdpChannel.setSessionId(activeSlot.sessionId);
1703
+ activeAuthenticatorId = activeSlot.authenticatorId;
1704
+ isAtBlank = true;
1705
+ return false;
1706
+ }
1707
+ };
1708
+ const visitedOrigins = new Set(observedOrigins);
1709
+ observedOrigins.clear();
1710
+ const visitedStorageKeys = new Set(observedStorageKeys);
1711
+ observedStorageKeys.clear();
1712
+ const activeChildSessions = cdpChannel.getChildSessions();
1450
1713
  for (const u of navigationUrls) {
1451
1714
  try {
1452
1715
  const parsed = new URL(u);
@@ -1465,167 +1728,248 @@ function makeLightweightCdpDriver(options) {
1465
1728
  currentNetworkConditions = void 0;
1466
1729
  width = initialWidth;
1467
1730
  height = initialHeight;
1468
- cdpChannel.clearChildSessions();
1731
+ await cleanupFlowScopedHooks();
1469
1732
  if (useContexts && options.freshContextPerFlow && hasRunFirstFlow) {
1470
1733
  if (contextIsolation === "hot-cache" && activeSlot) {
1471
- const preResetOps = [];
1472
- if (activeSlot.tabs.length > 1) {
1473
- const primaryTab = activeSlot.tabs[0];
1474
- const extraTabs = activeSlot.tabs.slice(1);
1475
- activeSlot.tabs = [primaryTab];
1476
- activeSlot.targetId = primaryTab.targetId;
1477
- activeSlot.sessionId = primaryTab.sessionId;
1478
- cdpChannel.setSessionId(primaryTab.sessionId);
1479
- for (const extra of extraTabs) {
1734
+ const slotWasHealthy = await ensureActiveSlotHealthy();
1735
+ if (slotWasHealthy && activeSlot) {
1736
+ const frameIdsToQuery = [];
1737
+ const frameTreeRes = await cdpChannel.sendCommand("Page.getFrameTree", {}, activeSlot.sessionId, 1500).catch(() => null);
1738
+ const collectFrameOrigins = (node) => {
1739
+ if (!node) return;
1740
+ const u = node.frame?.url;
1741
+ if (typeof node.frame?.id === "string") {
1742
+ frameIdsToQuery.push({ frameId: node.frame.id, sid: activeSlot.sessionId });
1743
+ }
1744
+ if (typeof u === "string") {
1745
+ try {
1746
+ const parsed = new URL(u);
1747
+ if (parsed.protocol === "http:" || parsed.protocol === "https:") {
1748
+ visitedOrigins.add(parsed.origin);
1749
+ }
1750
+ } catch {
1751
+ }
1752
+ }
1753
+ if (Array.isArray(node.childFrames)) {
1754
+ for (const child of node.childFrames) collectFrameOrigins(child);
1755
+ }
1756
+ };
1757
+ collectFrameOrigins(frameTreeRes?.frameTree);
1758
+ for (const child of activeChildSessions) {
1759
+ if (child.targetId) {
1760
+ frameIdsToQuery.push({ frameId: child.targetId, sid: child.sessionId });
1761
+ }
1762
+ if (child.url) {
1763
+ try {
1764
+ const parsed = new URL(child.url);
1765
+ if (parsed.protocol === "http:" || parsed.protocol === "https:") {
1766
+ visitedOrigins.add(parsed.origin);
1767
+ }
1768
+ } catch {
1769
+ }
1770
+ }
1771
+ }
1772
+ if (frameIdsToQuery.length > 0) {
1773
+ const skResults = await Promise.all(
1774
+ frameIdsToQuery.map(
1775
+ ({ frameId, sid }) => cdpChannel.sendCommand("Storage.getStorageKeyForFrame", { frameId }, sid, 1e3).catch(() => null)
1776
+ )
1777
+ );
1778
+ for (const res of skResults) {
1779
+ const sk = res?.storageKey;
1780
+ if (sk) visitedStorageKeys.add(sk);
1781
+ }
1782
+ }
1783
+ const preResetOps = [];
1784
+ for (const child of activeChildSessions) {
1480
1785
  preResetOps.push(
1481
- cdpChannel.sendCommand("Target.closeTarget", { targetId: extra.targetId }, null).catch(() => {
1786
+ cdpChannel.evaluateOnSession(
1787
+ child.sessionId,
1788
+ "try { localStorage.clear(); sessionStorage.clear(); } catch {}"
1789
+ ).catch(() => {
1482
1790
  })
1483
1791
  );
1484
1792
  }
1485
- }
1486
- if (!isAtBlank) {
1487
- preResetOps.push(
1488
- cdpChannel.evaluateFast(
1489
- `(async () => {
1490
- try { localStorage.clear(); sessionStorage.clear(); } catch {}
1491
- try {
1492
- if (navigator.storage && typeof navigator.storage.getDirectory === "function") {
1493
- const root = await navigator.storage.getDirectory();
1494
- if (root && typeof root.entries === "function") {
1495
- for await (const [name] of root.entries()) {
1496
- await root.removeEntry(name, { recursive: true }).catch(() => {});
1793
+ if (activeSlot.tabs.length > 1) {
1794
+ const primaryTab = activeSlot.tabs[0];
1795
+ const extraTabs = activeSlot.tabs.slice(1);
1796
+ activeSlot.tabs = [primaryTab];
1797
+ activeSlot.targetId = primaryTab.targetId;
1798
+ activeSlot.sessionId = primaryTab.sessionId;
1799
+ cdpChannel.setSessionId(primaryTab.sessionId);
1800
+ for (const extra of extraTabs) {
1801
+ preResetOps.push(
1802
+ cdpChannel.sendCommand("Target.closeTarget", { targetId: extra.targetId }, null).catch(() => {
1803
+ })
1804
+ );
1805
+ }
1806
+ }
1807
+ if (!isAtBlank) {
1808
+ preResetOps.push(
1809
+ cdpChannel.evaluateFast(
1810
+ `(async () => {
1811
+ try { if (window.__spanaClock && typeof window.__spanaClock.resume === "function") window.__spanaClock.resume(); } catch {}
1812
+ try { localStorage.clear(); sessionStorage.clear(); } catch {}
1813
+ try {
1814
+ if (navigator.storage && typeof navigator.storage.getDirectory === "function") {
1815
+ const root = await navigator.storage.getDirectory();
1816
+ if (root && typeof root.entries === "function") {
1817
+ for await (const [name] of root.entries()) {
1818
+ await root.removeEntry(name, { recursive: true }).catch(() => {});
1819
+ }
1497
1820
  }
1498
1821
  }
1499
- }
1500
- } catch {}
1501
- })()`
1502
- ).catch(() => {
1503
- }).then(
1504
- () => cdpChannel.sendCommand("Page.navigate", { url: "about:blank" }, void 0, 4e3).catch(() => {
1822
+ } catch {}
1823
+ })()`
1824
+ ).catch(() => {
1825
+ }).then(
1826
+ () => cdpChannel.sendCommand("Page.navigate", { url: "about:blank" }, void 0, 4e3).catch(() => {
1827
+ })
1828
+ ).then(() => {
1829
+ isAtBlank = true;
1505
1830
  })
1506
- ).then(() => {
1507
- isAtBlank = true;
1831
+ );
1832
+ }
1833
+ if (preResetOps.length > 0) {
1834
+ await Promise.all(preResetOps);
1835
+ }
1836
+ cdpChannel.clearChildSessions();
1837
+ const resetOps = [
1838
+ cdpChannel.sendCommand("Network.clearBrowserCookies").catch(() => {
1508
1839
  })
1509
- );
1510
- }
1511
- if (preResetOps.length > 0) {
1512
- await Promise.all(preResetOps);
1513
- }
1514
- const resetOps = [
1515
- cdpChannel.sendCommand("Network.clearBrowserCookies").catch(() => {
1516
- })
1517
- ];
1518
- for (const origin of visitedOrigins) {
1840
+ ];
1841
+ const storageTypes = "cookies,local_storage,session_storage,indexeddb,cache_storage,service_workers,file_systems";
1842
+ for (const origin of visitedOrigins) {
1843
+ resetOps.push(
1844
+ cdpChannel.sendCommand("Storage.clearDataForOrigin", { origin, storageTypes }).catch(() => {
1845
+ })
1846
+ );
1847
+ }
1848
+ for (const storageKey of visitedStorageKeys) {
1849
+ resetOps.push(
1850
+ cdpChannel.sendCommand("Storage.clearDataForStorageKey", {
1851
+ storageKey,
1852
+ storageTypes
1853
+ }).catch(() => {
1854
+ })
1855
+ );
1856
+ }
1857
+ if (permissionsMutated) {
1858
+ permissionsMutated = false;
1859
+ resetOps.push(
1860
+ cdpChannel.sendCommand(
1861
+ "Browser.resetPermissions",
1862
+ { browserContextId: activeSlot.browserContextId },
1863
+ null
1864
+ ).catch(() => {
1865
+ })
1866
+ );
1867
+ }
1868
+ if (geolocationMutated) {
1869
+ geolocationMutated = false;
1870
+ resetOps.push(
1871
+ cdpChannel.sendCommand("Emulation.clearGeolocationOverride", {}).catch(() => {
1872
+ })
1873
+ );
1874
+ }
1875
+ if (fetchInterceptEnabled) {
1876
+ fetchInterceptEnabled = false;
1877
+ resetOps.push(cdpChannel.sendCommand("Fetch.disable").catch(() => {
1878
+ }));
1879
+ }
1880
+ if (viewportMutated) {
1881
+ viewportMutated = false;
1882
+ resetOps.push(
1883
+ cdpChannel.sendCommand("Emulation.setDeviceMetricsOverride", {
1884
+ width: initialWidth,
1885
+ height: initialHeight,
1886
+ deviceScaleFactor: 1,
1887
+ mobile: false
1888
+ }).catch(() => {
1889
+ })
1890
+ );
1891
+ }
1892
+ if (emulationMutated) {
1893
+ emulationMutated = false;
1894
+ const defaultLocale = options.emulation?.locale ?? "";
1895
+ resetOps.push(
1896
+ cdpChannel.sendCommand("Emulation.setLocaleOverride", { locale: defaultLocale }).catch(() => {
1897
+ }),
1898
+ cdpChannel.sendCommand("Emulation.setUserAgentOverride", {
1899
+ userAgent: cachedUserAgent || "Mozilla/5.0",
1900
+ acceptLanguage: defaultLocale ? defaultLocale.includes("-") ? `${defaultLocale},${defaultLocale.split("-")[0]};q=0.9` : defaultLocale : ""
1901
+ }).catch(() => {
1902
+ }),
1903
+ cdpChannel.sendCommand("Emulation.setEmulatedMedia", {
1904
+ media: "",
1905
+ features: [
1906
+ {
1907
+ name: "prefers-color-scheme",
1908
+ value: options.emulation?.colorScheme && options.emulation.colorScheme !== "no-preference" ? options.emulation.colorScheme : ""
1909
+ },
1910
+ {
1911
+ name: "prefers-reduced-motion",
1912
+ value: options.emulation?.reducedMotion && options.emulation.reducedMotion !== "no-preference" ? options.emulation.reducedMotion : ""
1913
+ }
1914
+ ]
1915
+ }).catch(() => {
1916
+ }),
1917
+ cdpChannel.sendCommand("Emulation.setTimezoneOverride", {
1918
+ timezoneId: options.emulation?.timezoneId ?? ""
1919
+ }).catch(() => {
1920
+ })
1921
+ );
1922
+ }
1519
1923
  resetOps.push(
1520
- cdpChannel.sendCommand("Storage.clearDataForOrigin", {
1521
- origin,
1522
- storageTypes: "cookies,local_storage,session_storage,indexeddb,cache_storage,service_workers,file_systems"
1924
+ cdpChannel.sendCommand("Network.emulateNetworkConditions", {
1925
+ offline: false,
1926
+ latency: 0,
1927
+ downloadThroughput: -1,
1928
+ uploadThroughput: -1
1523
1929
  }).catch(() => {
1524
1930
  })
1525
1931
  );
1526
- }
1527
- if (fetchInterceptEnabled) {
1932
+ await Promise.all(resetOps);
1933
+ const state = await loadStorageStateFile(options.storageState);
1934
+ if (state?.cookies && state.cookies.length > 0) {
1935
+ await cdpChannel.sendCommand("Network.setCookies", { cookies: state.cookies }).catch(() => {
1936
+ });
1937
+ }
1938
+ } else {
1939
+ cdpChannel.clearChildSessions();
1528
1940
  fetchInterceptEnabled = false;
1529
- resetOps.push(cdpChannel.sendCommand("Fetch.disable").catch(() => {
1530
- }));
1531
- }
1532
- if (viewportMutated) {
1533
- viewportMutated = false;
1534
- resetOps.push(
1535
- cdpChannel.sendCommand("Emulation.setDeviceMetricsOverride", {
1536
- width: initialWidth,
1537
- height: initialHeight,
1538
- deviceScaleFactor: 1,
1539
- mobile: false
1540
- }).catch(() => {
1541
- })
1542
- );
1543
- }
1544
- if (emulationMutated) {
1545
1941
  emulationMutated = false;
1546
- const defaultLocale = options.emulation?.locale ?? "";
1547
- resetOps.push(
1548
- cdpChannel.sendCommand("Emulation.setLocaleOverride", { locale: defaultLocale }).catch(() => {
1549
- }),
1550
- cdpChannel.sendCommand("Emulation.setUserAgentOverride", {
1551
- userAgent: cachedUserAgent || "Mozilla/5.0",
1552
- acceptLanguage: defaultLocale ? defaultLocale.includes("-") ? `${defaultLocale},${defaultLocale.split("-")[0]};q=0.9` : defaultLocale : ""
1553
- }).catch(() => {
1554
- }),
1555
- cdpChannel.sendCommand("Emulation.setEmulatedMedia", {
1556
- media: "",
1557
- features: [
1558
- {
1559
- name: "prefers-color-scheme",
1560
- value: options.emulation?.colorScheme && options.emulation.colorScheme !== "no-preference" ? options.emulation.colorScheme : ""
1561
- },
1562
- {
1563
- name: "prefers-reduced-motion",
1564
- value: options.emulation?.reducedMotion && options.emulation.reducedMotion !== "no-preference" ? options.emulation.reducedMotion : ""
1565
- }
1566
- ]
1567
- }).catch(() => {
1568
- }),
1569
- cdpChannel.sendCommand("Emulation.setTimezoneOverride", {
1570
- timezoneId: options.emulation?.timezoneId ?? ""
1571
- }).catch(() => {
1572
- })
1573
- );
1574
- }
1575
- resetOps.push(
1576
- cdpChannel.sendCommand("Network.emulateNetworkConditions", {
1577
- offline: false,
1578
- latency: 0,
1579
- downloadThroughput: -1,
1580
- uploadThroughput: -1
1581
- }).catch(() => {
1582
- })
1583
- );
1584
- await Promise.all(resetOps);
1585
- const state = await loadStorageStateFile(options.storageState);
1586
- if (state?.cookies && state.cookies.length > 0) {
1587
- await cdpChannel.sendCommand("Network.setCookies", { cookies: state.cookies }).catch(() => {
1588
- });
1942
+ viewportMutated = false;
1943
+ permissionsMutated = false;
1944
+ geolocationMutated = false;
1589
1945
  }
1590
- if (options.virtualAuthenticator && !activeSlot.authenticatorId) {
1591
- const authOpts = typeof options.virtualAuthenticator === "object" ? options.virtualAuthenticator : void 0;
1592
- activeSlot.authenticatorId = await attachVirtualAuthenticatorForSession(
1593
- activeSlot.sessionId,
1594
- authOpts
1595
- ).catch(() => void 0);
1946
+ if (activeSlot) {
1947
+ await ensureVirtualAuthenticatorForSlot(activeSlot, true);
1596
1948
  }
1597
- activeAuthenticatorId = activeSlot.authenticatorId;
1598
1949
  } else {
1950
+ cdpChannel.clearChildSessions();
1599
1951
  fetchInterceptEnabled = false;
1600
1952
  emulationMutated = false;
1601
1953
  viewportMutated = false;
1954
+ permissionsMutated = false;
1955
+ geolocationMutated = false;
1602
1956
  isAtBlank = true;
1603
1957
  const previousSlot = activeSlot;
1604
1958
  const pending = prefetchedSlotPromise;
1605
1959
  prefetchedSlotPromise = void 0;
1606
1960
  activeSlot = pending ? await pending : await createContextSlot(options.storageState);
1607
1961
  cdpChannel.setSessionId(activeSlot.sessionId);
1608
- if (options.virtualAuthenticator && !activeSlot.authenticatorId) {
1609
- const authOpts = typeof options.virtualAuthenticator === "object" ? options.virtualAuthenticator : void 0;
1610
- activeSlot.authenticatorId = await attachVirtualAuthenticatorForSession(
1611
- activeSlot.sessionId,
1612
- authOpts
1613
- ).catch(() => void 0);
1614
- }
1615
- activeAuthenticatorId = activeSlot.authenticatorId;
1962
+ await ensureVirtualAuthenticatorForSlot(activeSlot, false);
1616
1963
  if (previousSlot) {
1617
1964
  disposeSlotInBackground(previousSlot);
1618
1965
  }
1619
1966
  }
1620
1967
  } else if (activeSlot) {
1621
- if (options.virtualAuthenticator && !activeSlot.authenticatorId) {
1622
- const authOpts = typeof options.virtualAuthenticator === "object" ? options.virtualAuthenticator : void 0;
1623
- activeSlot.authenticatorId = await attachVirtualAuthenticatorForSession(
1624
- activeSlot.sessionId,
1625
- authOpts
1626
- ).catch(() => void 0);
1968
+ cdpChannel.clearChildSessions();
1969
+ await ensureActiveSlotHealthy();
1970
+ if (activeSlot) {
1971
+ await ensureVirtualAuthenticatorForSlot(activeSlot, false);
1627
1972
  }
1628
- activeAuthenticatorId = activeSlot.authenticatorId;
1629
1973
  }
1630
1974
  hasRunFirstFlow = true;
1631
1975
  },
@@ -1703,11 +2047,44 @@ function makeLightweightCdpDriver(options) {
1703
2047
  },
1704
2048
  catch: (e) => new DriverError({ message: `CDP longPress failed: ${e}` })
1705
2049
  }),
1706
- swipe: (startX, startY, endX, endY) => Effect.tryPromise({
2050
+ swipe: (startX, startY, endX, endY, duration = 300) => Effect.tryPromise({
1707
2051
  try: async () => {
1708
- const dx = startX - endX;
1709
- const dy = startY - endY;
1710
- await cdpChannel.evaluate(`window.scrollBy(${dx}, ${dy})`);
2052
+ const totalSteps = Math.max(4, Math.min(20, Math.round((duration || 300) / 20)));
2053
+ const stepDelayMs = duration > 0 ? Math.max(0, Math.floor(duration / totalSteps)) : 0;
2054
+ await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
2055
+ type: "mouseMoved",
2056
+ x: startX,
2057
+ y: startY
2058
+ });
2059
+ await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
2060
+ type: "mousePressed",
2061
+ x: startX,
2062
+ y: startY,
2063
+ button: "left",
2064
+ buttons: 1,
2065
+ clickCount: 1
2066
+ });
2067
+ for (let i = 1; i <= totalSteps; i++) {
2068
+ const t = i / totalSteps;
2069
+ await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
2070
+ type: "mouseMoved",
2071
+ x: startX + (endX - startX) * t,
2072
+ y: startY + (endY - startY) * t,
2073
+ button: "left",
2074
+ buttons: 1
2075
+ });
2076
+ if (stepDelayMs > 0) {
2077
+ await new Promise((r) => setTimeout(r, stepDelayMs));
2078
+ }
2079
+ }
2080
+ await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
2081
+ type: "mouseReleased",
2082
+ x: endX,
2083
+ y: endY,
2084
+ button: "left",
2085
+ buttons: 0,
2086
+ clickCount: 1
2087
+ });
1711
2088
  },
1712
2089
  catch: (e) => new DriverError({ message: `CDP swipe failed: ${e}` })
1713
2090
  }),
@@ -2063,6 +2440,7 @@ function makeLightweightCdpDriver(options) {
2063
2440
  }),
2064
2441
  setGeolocation: (point) => Effect.tryPromise({
2065
2442
  try: async () => {
2443
+ geolocationMutated = true;
2066
2444
  await cdpChannel.sendCommand("Emulation.setGeolocationOverride", {
2067
2445
  latitude: point.latitude,
2068
2446
  longitude: point.longitude,
@@ -2073,6 +2451,7 @@ function makeLightweightCdpDriver(options) {
2073
2451
  }),
2074
2452
  setPermission: (_appId, permission, state, permOpts) => Effect.tryPromise({
2075
2453
  try: async () => {
2454
+ permissionsMutated = true;
2076
2455
  const cdpName = permission === "clipboard-read" ? "clipboardReadWrite" : permission === "clipboard-write" ? "clipboardSanitizedWrite" : permission === "midi-sysex" ? "midi" : permission;
2077
2456
  const origin = permOpts?.origin;
2078
2457
  const ctxId = activeSlot?.browserContextId;
@@ -2133,13 +2512,18 @@ function makeLightweightCdpDriver(options) {
2133
2512
  killApp: () => Effect.tryPromise({
2134
2513
  try: async () => {
2135
2514
  prefetchedSlotPromise = void 0;
2136
- if (useContexts && activeSlot) {
2137
- void cdpChannel.sendCommand(
2138
- "Target.disposeBrowserContext",
2139
- { browserContextId: activeSlot.browserContextId },
2140
- null
2141
- ).catch(() => {
2142
- });
2515
+ const slotToDispose = activeSlot;
2516
+ activeSlot = void 0;
2517
+ if (useContexts && slotToDispose) {
2518
+ await Promise.race([
2519
+ cdpChannel.sendCommand(
2520
+ "Target.disposeBrowserContext",
2521
+ { browserContextId: slotToDispose.browserContextId },
2522
+ null
2523
+ ).catch(() => {
2524
+ }),
2525
+ new Promise((r) => setTimeout(r, 1500))
2526
+ ]);
2143
2527
  }
2144
2528
  if (downloadDir) {
2145
2529
  try {
@@ -2154,6 +2538,9 @@ function makeLightweightCdpDriver(options) {
2154
2538
  } catch {
2155
2539
  }
2156
2540
  }
2541
+ if (options._markClosedOnKill) {
2542
+ cdpChannel.markClosed("Browser context closed");
2543
+ }
2157
2544
  await cdpChannel.disconnect();
2158
2545
  },
2159
2546
  catch: (e) => new DriverError({ message: `CDP disconnect failed: ${e}` })
@@ -2197,6 +2584,17 @@ function makeLightweightCdpDriver(options) {
2197
2584
  });
2198
2585
  await waiter.catch(() => {
2199
2586
  });
2587
+ await cdpChannel.evaluateFast(
2588
+ `new Promise((resolve) => {
2589
+ let done = false;
2590
+ const finish = () => { if (!done) { done = true; clearTimeout(maxT); clearTimeout(idleT); obs.disconnect(); resolve(true); } };
2591
+ const maxT = setTimeout(finish, 400);
2592
+ let idleT = setTimeout(finish, 80);
2593
+ const obs = new MutationObserver(() => { clearTimeout(idleT); idleT = setTimeout(finish, 80); });
2594
+ try { obs.observe(document.documentElement || document, { childList: true, subtree: true, attributes: true }); } catch { finish(); }
2595
+ })`
2596
+ ).catch(() => {
2597
+ });
2200
2598
  return;
2201
2599
  }
2202
2600
  await cdpChannel.evaluate("window.history.back()");
@@ -2228,6 +2626,17 @@ function makeLightweightCdpDriver(options) {
2228
2626
  });
2229
2627
  await waiter.catch(() => {
2230
2628
  });
2629
+ await cdpChannel.evaluateFast(
2630
+ `new Promise((resolve) => {
2631
+ let done = false;
2632
+ const finish = () => { if (!done) { done = true; clearTimeout(maxT); clearTimeout(idleT); obs.disconnect(); resolve(true); } };
2633
+ const maxT = setTimeout(finish, 400);
2634
+ let idleT = setTimeout(finish, 80);
2635
+ const obs = new MutationObserver(() => { clearTimeout(idleT); idleT = setTimeout(finish, 80); });
2636
+ try { obs.observe(document.documentElement || document, { childList: true, subtree: true, attributes: true }); } catch { finish(); }
2637
+ })`
2638
+ ).catch(() => {
2639
+ });
2231
2640
  return;
2232
2641
  }
2233
2642
  await cdpChannel.evaluate("window.history.forward()");
@@ -2237,30 +2646,45 @@ function makeLightweightCdpDriver(options) {
2237
2646
  evaluate: (fn, ...args) => Effect.tryPromise({
2238
2647
  try: async () => {
2239
2648
  if (typeof fn === "string") {
2240
- return await cdpChannel.evaluate(fn);
2649
+ return await cdpChannel.evaluateOnce(fn);
2241
2650
  }
2242
2651
  const serializedArgs = args.map((a) => a === void 0 ? "undefined" : JSON.stringify(a)).join(", ");
2243
- return await cdpChannel.evaluate(`(${fn.toString()})(${serializedArgs})`);
2652
+ return await cdpChannel.evaluateOnce(`(${fn.toString()})(${serializedArgs})`);
2244
2653
  },
2245
2654
  catch: (e) => new DriverError({ message: `CDP evaluate failed: ${e}` })
2246
2655
  }),
2247
2656
  addInitScript: (script, ...args) => Effect.tryPromise({
2248
2657
  try: async () => {
2249
2658
  const source = typeof script === "string" ? script : `(${script.toString()})(${args.map((a) => a === void 0 ? "undefined" : JSON.stringify(a)).join(", ")});`;
2250
- initScripts.push(source);
2659
+ flowInitScripts.push(source);
2251
2660
  const sessions = activeSlot ? activeSlot.tabs.map((t) => t.sessionId) : [null];
2252
2661
  await Promise.all(
2253
2662
  sessions.map(
2254
- (sid) => cdpChannel.sendCommand("Page.addScriptToEvaluateOnNewDocument", { source }, sid).catch(() => {
2663
+ (sid) => cdpChannel.sendCommand("Page.addScriptToEvaluateOnNewDocument", { source }, sid).then((res) => recordScriptId(flowInitScriptIds, sid, res)).catch(() => {
2255
2664
  })
2256
2665
  )
2257
2666
  );
2258
2667
  },
2259
2668
  catch: (e) => new DriverError({ message: `CDP addInitScript failed: ${e}` })
2260
2669
  }),
2670
+ setClockInitScript: (script) => Effect.tryPromise({
2671
+ try: async () => {
2672
+ await removeTrackedScripts(clockInitScriptIds);
2673
+ clockInitScript = script;
2674
+ if (!script) return;
2675
+ const sessions = activeSlot ? activeSlot.tabs.map((t) => t.sessionId) : [null];
2676
+ await Promise.all(
2677
+ sessions.map(
2678
+ (sid) => cdpChannel.sendCommand("Page.addScriptToEvaluateOnNewDocument", { source: script }, sid).then((res) => recordScriptId(clockInitScriptIds, sid, res)).catch(() => {
2679
+ })
2680
+ )
2681
+ );
2682
+ },
2683
+ catch: (e) => new DriverError({ message: `CDP setClockInitScript failed: ${e}` })
2684
+ }),
2261
2685
  exposeFunction: (name, fn) => Effect.tryPromise({
2262
2686
  try: async () => {
2263
- exposedFunctions.set(name, fn);
2687
+ flowExposedFunctions.set(name, fn);
2264
2688
  const sessions = activeSlot ? activeSlot.tabs.map((t) => t.sessionId) : [null];
2265
2689
  await Promise.all(sessions.map((sid) => installExposeFunctionOnSession(sid, name)));
2266
2690
  },
@@ -2532,6 +2956,7 @@ function makeLightweightCdpDriver(options) {
2532
2956
  cdpUrl: connectWsUrl ?? options.cdpUrl,
2533
2957
  useBrowserContexts: true,
2534
2958
  freshContextPerFlow: false,
2959
+ _markClosedOnKill: true,
2535
2960
  ...ctxOpts?.viewport ? { viewport: ctxOpts.viewport } : {},
2536
2961
  ...ctxOpts?.locale ? { emulation: { ...options.emulation, locale: ctxOpts.locale } } : {}
2537
2962
  })
@@ -2683,22 +3108,7 @@ function makeLightweightCdpDriver(options) {
2683
3108
  uploadFile: (selector, filePath) => Effect.tryPromise({
2684
3109
  try: async () => {
2685
3110
  const rawItems = Array.isArray(filePath) ? filePath : [filePath];
2686
- const files = [];
2687
- let batchTempDir;
2688
- for (const item of rawItems) {
2689
- if (typeof item === "string") {
2690
- files.push(item);
2691
- } else {
2692
- if (!batchTempDir) {
2693
- batchTempDir = mkdtempSync(join2(tmpdir(), "spana-cdp-upload-"));
2694
- uploadTempDirs.push(batchTempDir);
2695
- }
2696
- const safeFileName = item.name.replaceAll(/[\\/]/g, "_") || "upload.bin";
2697
- const dest = join2(batchTempDir, safeFileName);
2698
- await writeFile(dest, Buffer.from(item.buffer));
2699
- files.push(dest);
2700
- }
2701
- }
3111
+ const hasInMemoryPayload = rawItems.some((item) => typeof item !== "string");
2702
3112
  const expr = buildDomFindElementScript(selector);
2703
3113
  await cdpChannel.sendCommand("DOM.enable");
2704
3114
  await cdpChannel.sendCommand("DOM.getDocument", { depth: 0 }).catch(() => {
@@ -2723,6 +3133,44 @@ function makeLightweightCdpDriver(options) {
2723
3133
  `No matching file input found within ${attachTimeout}ms for selector ${JSON.stringify(selector)}`
2724
3134
  );
2725
3135
  }
3136
+ if (hasInMemoryPayload) {
3137
+ const serializedItems = [];
3138
+ for (const item of rawItems) {
3139
+ if (typeof item === "string") {
3140
+ const buf = await readFile(item);
3141
+ const base = item.split(/[\\/]/).pop() || "upload.bin";
3142
+ serializedItems.push({
3143
+ name: base,
3144
+ mimeType: "application/octet-stream",
3145
+ bytes: Array.from(new Uint8Array(buf))
3146
+ });
3147
+ } else {
3148
+ serializedItems.push({
3149
+ name: item.name || "upload.bin",
3150
+ mimeType: item.mimeType || "application/octet-stream",
3151
+ bytes: Array.from(new Uint8Array(item.buffer))
3152
+ });
3153
+ }
3154
+ }
3155
+ await cdpChannel.sendCommand("Runtime.callFunctionOn", {
3156
+ objectId,
3157
+ functionDeclaration: `function(items) {
3158
+ var dt = new DataTransfer();
3159
+ for (var i = 0; i < items.length; i++) {
3160
+ var it = items[i];
3161
+ var f = new File([new Uint8Array(it.bytes)], it.name, { type: it.mimeType });
3162
+ dt.items.add(f);
3163
+ }
3164
+ this.files = dt.files;
3165
+ this.dispatchEvent(new Event("input", { bubbles: true, composed: true }));
3166
+ this.dispatchEvent(new Event("change", { bubbles: true, composed: true }));
3167
+ }`,
3168
+ arguments: [{ value: serializedItems }],
3169
+ returnByValue: true
3170
+ });
3171
+ return;
3172
+ }
3173
+ const files = rawItems;
2726
3174
  const nodeRes = await cdpChannel.sendCommand("DOM.requestNode", { objectId }).catch(() => ({}));
2727
3175
  if (nodeRes?.nodeId && nodeRes.nodeId > 0) {
2728
3176
  await cdpChannel.sendCommand("DOM.setFileInputFiles", {
@@ -2877,6 +3325,7 @@ function makeLightweightCdpDriver(options) {
2877
3325
  getClipboard: () => Effect.tryPromise({
2878
3326
  try: async () => {
2879
3327
  if (activeSlot?.browserContextId) {
3328
+ permissionsMutated = true;
2880
3329
  await cdpChannel.sendCommand(
2881
3330
  "Browser.grantPermissions",
2882
3331
  {
@@ -2905,6 +3354,7 @@ function makeLightweightCdpDriver(options) {
2905
3354
  setClipboard: (text) => Effect.tryPromise({
2906
3355
  try: async () => {
2907
3356
  if (activeSlot?.browserContextId) {
3357
+ permissionsMutated = true;
2908
3358
  await cdpChannel.sendCommand(
2909
3359
  "Browser.grantPermissions",
2910
3360
  {
@@ -2981,29 +3431,35 @@ function makeLightweightCdpDriver(options) {
2981
3431
  if (!activeSlot) {
2982
3432
  throw new Error("newTab() requires browser-context mode (engine: 'cdp')");
2983
3433
  }
3434
+ const targetUrl = url ? await resolveUrlAsync(url) : "about:blank";
2984
3435
  const targetRes = await cdpChannel.sendCommand(
2985
3436
  "Target.createTarget",
2986
3437
  {
2987
- url: url ? resolveUrl(url) : "about:blank",
3438
+ url: targetUrl,
2988
3439
  browserContextId: activeSlot.browserContextId
2989
3440
  },
2990
3441
  null
2991
3442
  );
2992
- const attachRes = await cdpChannel.sendCommand(
2993
- "Target.attachToTarget",
2994
- { targetId: targetRes.targetId, flatten: true },
2995
- null
2996
- );
2997
- await configureSession(attachRes.sessionId, options.storageState);
2998
- const tabId = `tab-${nextTabSeq++}`;
2999
- activeSlot.tabs.push({
3000
- tabId,
3001
- targetId: targetRes.targetId,
3002
- sessionId: attachRes.sessionId
3003
- });
3443
+ const autoTracked = activeSlot.tabs.find((t) => t.targetId === targetRes.targetId);
3444
+ let sessionId = autoTracked?.sessionId;
3445
+ if (!sessionId) {
3446
+ const attachRes = await cdpChannel.sendCommand(
3447
+ "Target.attachToTarget",
3448
+ { targetId: targetRes.targetId, flatten: true },
3449
+ null
3450
+ );
3451
+ sessionId = attachRes.sessionId;
3452
+ }
3453
+ await configureSession(sessionId, options.storageState, true);
3454
+ const existingAfter = activeSlot.tabs.find((t) => t.targetId === targetRes.targetId);
3455
+ const tabId = existingAfter?.tabId ?? `tab-${nextTabSeq++}`;
3456
+ activeSlot.tabs = [
3457
+ ...activeSlot.tabs.filter((t) => t.targetId !== targetRes.targetId),
3458
+ { tabId, targetId: targetRes.targetId, sessionId }
3459
+ ];
3004
3460
  activeSlot.targetId = targetRes.targetId;
3005
- activeSlot.sessionId = attachRes.sessionId;
3006
- cdpChannel.setSessionId(attachRes.sessionId);
3461
+ activeSlot.sessionId = sessionId;
3462
+ cdpChannel.setSessionId(sessionId);
3007
3463
  return tabId;
3008
3464
  },
3009
3465
  catch: (e) => new DriverError({ message: `CDP newTab failed: ${e}` })
@@ -3031,7 +3487,34 @@ function makeLightweightCdpDriver(options) {
3031
3487
  }
3032
3488
  const idx = activeSlot.tabs.findIndex((t) => t.sessionId === activeSlot.sessionId);
3033
3489
  const closing = activeSlot.tabs[idx >= 0 ? idx : activeSlot.tabs.length - 1];
3034
- activeSlot.tabs = activeSlot.tabs.filter((t) => t.sessionId !== closing.sessionId);
3490
+ activeSlot.tabs = activeSlot.tabs.filter(
3491
+ (t) => t.targetId !== closing.targetId && t.sessionId !== closing.sessionId
3492
+ );
3493
+ if (activeSlot.tabs.length === 0) {
3494
+ const targetRes = await cdpChannel.sendCommand(
3495
+ "Target.createTarget",
3496
+ {
3497
+ url: "about:blank",
3498
+ browserContextId: activeSlot.browserContextId,
3499
+ width: initialWidth,
3500
+ height: initialHeight
3501
+ },
3502
+ null
3503
+ );
3504
+ const attachRes = await cdpChannel.sendCommand(
3505
+ "Target.attachToTarget",
3506
+ { targetId: targetRes.targetId, flatten: true },
3507
+ null
3508
+ );
3509
+ await configureSession(attachRes.sessionId, options.storageState, true);
3510
+ activeSlot.tabs = [
3511
+ {
3512
+ tabId: `tab-${nextTabSeq++}`,
3513
+ targetId: targetRes.targetId,
3514
+ sessionId: attachRes.sessionId
3515
+ }
3516
+ ];
3517
+ }
3035
3518
  const fallback = activeSlot.tabs[Math.max(0, Math.min(idx - 1, activeSlot.tabs.length - 1))];
3036
3519
  activeSlot.targetId = fallback.targetId;
3037
3520
  activeSlot.sessionId = fallback.sessionId;
@@ -3057,4 +3540,4 @@ export {
3057
3540
  UPLOAD_ATTACH_TIMEOUT_MS,
3058
3541
  makeLightweightCdpDriver
3059
3542
  };
3060
- //# sourceMappingURL=chunk-T4FCROSE.js.map
3543
+ //# sourceMappingURL=chunk-5WPPWTC3.js.map