@vforsh/argus 0.4.0 → 0.5.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 (36) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/argus.js +1108 -558
  3. package/dist/cli/program.d.ts +11 -1
  4. package/dist/cli/program.d.ts.map +1 -1
  5. package/dist/cli/program.js +14 -9
  6. package/dist/cli/program.js.map +1 -1
  7. package/dist/cli/register/index.d.ts.map +1 -1
  8. package/dist/cli/register/index.js +2 -0
  9. package/dist/cli/register/index.js.map +1 -1
  10. package/dist/cli/register/sessionCommands.d.ts +3 -0
  11. package/dist/cli/register/sessionCommands.d.ts.map +1 -0
  12. package/dist/cli/register/sessionCommands.js +24 -0
  13. package/dist/cli/register/sessionCommands.js.map +1 -0
  14. package/dist/output/io.d.ts +7 -0
  15. package/dist/output/io.d.ts.map +1 -1
  16. package/dist/output/io.js +21 -2
  17. package/dist/output/io.js.map +1 -1
  18. package/dist/session/runSession.d.ts +15 -0
  19. package/dist/session/runSession.d.ts.map +1 -0
  20. package/dist/session/runSession.js +184 -0
  21. package/dist/session/runSession.js.map +1 -0
  22. package/dist/session/sessionArgv.d.ts +42 -0
  23. package/dist/session/sessionArgv.d.ts.map +1 -0
  24. package/dist/session/sessionArgv.js +224 -0
  25. package/dist/session/sessionArgv.js.map +1 -0
  26. package/dist/session/sessionDispatch.d.ts +21 -0
  27. package/dist/session/sessionDispatch.d.ts.map +1 -0
  28. package/dist/session/sessionDispatch.js +137 -0
  29. package/dist/session/sessionDispatch.js.map +1 -0
  30. package/dist/session/stdioCapture.d.ts +33 -0
  31. package/dist/session/stdioCapture.d.ts.map +1 -0
  32. package/dist/session/stdioCapture.js +56 -0
  33. package/dist/session/stdioCapture.js.map +1 -0
  34. package/dist/skill/argus/SKILL.md +29 -0
  35. package/dist/skill/argus/reference/SESSION.md +153 -0
  36. package/package.json +5 -5
package/dist/argus.js CHANGED
@@ -2130,7 +2130,7 @@ var {
2130
2130
  // package.json
2131
2131
  var package_default = {
2132
2132
  name: "@vforsh/argus",
2133
- version: "0.4.0",
2133
+ version: "0.5.0",
2134
2134
  repository: {
2135
2135
  type: "git",
2136
2136
  url: "git+https://github.com/vforsh/argus.git",
@@ -2160,10 +2160,10 @@ var package_default = {
2160
2160
  access: "public"
2161
2161
  },
2162
2162
  dependencies: {
2163
- "@vforsh/argus-client": "^0.4.0",
2164
- "@vforsh/argus-core": "^0.4.0",
2165
- "@vforsh/argus-plugin-api": "^0.4.0",
2166
- "@vforsh/argus-watcher": "^0.4.0",
2163
+ "@vforsh/argus-client": "^0.5.0",
2164
+ "@vforsh/argus-core": "^0.5.0",
2165
+ "@vforsh/argus-plugin-api": "^0.5.0",
2166
+ "@vforsh/argus-watcher": "^0.5.0",
2167
2167
  commander: "14.0.2",
2168
2168
  esbuild: "0.25.12",
2169
2169
  prettier: "3.7.4"
@@ -2178,19 +2178,23 @@ var package_default = {
2178
2178
  };
2179
2179
 
2180
2180
  // dist/cli/program.js
2181
- function createProgram() {
2181
+ function createProgram(options = {}) {
2182
2182
  const program2 = new Command;
2183
2183
  program2.name("argus").description("Argus CLI for local watcher servers").version(package_default.version).option("--plugin <specifier>", "Load an extra CLI plugin for this invocation", collectPluginOption, []).configureOutput({
2184
2184
  outputError: (str, write) => write(str)
2185
- }).showSuggestionAfterError(true).enablePositionalOptions().exitOverride((error) => {
2186
- if (error.code === "commander.helpDisplayed" || error.code === "commander.version") {
2187
- process.exit(0);
2188
- }
2189
- console.error(error.message);
2190
- process.exit(2);
2191
- });
2185
+ }).showSuggestionAfterError(true).enablePositionalOptions().exitOverride(options.mode === "session" ? throwOnExit : exitProcess);
2192
2186
  return program2;
2193
2187
  }
2188
+ var throwOnExit = (error) => {
2189
+ throw error;
2190
+ };
2191
+ var exitProcess = (error) => {
2192
+ if (error.code === "commander.helpDisplayed" || error.code === "commander.version") {
2193
+ process.exit(0);
2194
+ }
2195
+ console.error(error.message);
2196
+ process.exit(2);
2197
+ };
2194
2198
  var collectPluginOption = (value, previous) => [...previous, value];
2195
2199
 
2196
2200
  // dist/cli/defineCommand.js
@@ -3571,6 +3575,11 @@ var ARGUS_ERROR_CODES = [
3571
3575
  "not_interactable",
3572
3576
  "nth_out_of_range",
3573
3577
  "payload_too_large",
3578
+ "session_command_failed",
3579
+ "session_command_rejected",
3580
+ "session_invalid_request",
3581
+ "session_request_timeout",
3582
+ "session_unknown_command",
3574
3583
  "unexpected_matches",
3575
3584
  "unsupported_platform"
3576
3585
  ];
@@ -3640,6 +3649,53 @@ var describeProtocolMismatch = (protocolVersion, watcherVersion) => {
3640
3649
  };
3641
3650
  // ../argus-core/dist/protocol/native-messaging.js
3642
3651
  var NATIVE_MESSAGING_PROTOCOL_VERSION = 2;
3652
+ // ../argus-core/dist/protocol/session.js
3653
+ var SESSION_PROTOCOL_VERSION = 1;
3654
+ var optionalRequestId = (source, key) => {
3655
+ const field = source[key];
3656
+ if (field == null) {
3657
+ return;
3658
+ }
3659
+ if (typeof field === "string") {
3660
+ return field;
3661
+ }
3662
+ if (typeof field === "number" && Number.isFinite(field)) {
3663
+ return field;
3664
+ }
3665
+ return fieldError(`${key} must be a string or a finite number`);
3666
+ };
3667
+ var optionalTimeout = (source, key) => {
3668
+ const field = source[key];
3669
+ if (field == null) {
3670
+ return;
3671
+ }
3672
+ if (typeof field === "string") {
3673
+ return field;
3674
+ }
3675
+ if (typeof field === "number" && Number.isFinite(field) && field > 0) {
3676
+ return field;
3677
+ }
3678
+ return fieldError(`${key} must be a duration string or a positive number of milliseconds`);
3679
+ };
3680
+ var SESSION_REQUEST_SCHEMA = defineProtocolSchema((value) => {
3681
+ const invalid = requireObject(value);
3682
+ if (invalid)
3683
+ return invalid;
3684
+ const source = value;
3685
+ const fields = readFields(source, {
3686
+ id: optionalRequestId,
3687
+ cmd: requiredString,
3688
+ args: optionalRecord,
3689
+ argv: optionalStringArray,
3690
+ timeout: optionalTimeout
3691
+ });
3692
+ if (!fields.ok)
3693
+ return fields;
3694
+ if (fields.value.args && fields.value.argv) {
3695
+ return invalidProtocolPayload("args and argv are mutually exclusive");
3696
+ }
3697
+ return { ok: true, value: compact(fields.value) };
3698
+ });
3643
3699
  // ../argus-core/dist/registry/registry.js
3644
3700
  import fs2 from "node:fs/promises";
3645
3701
  import path3 from "node:path";
@@ -4408,9 +4464,16 @@ var ensureTrailingNewline = (value) => value.endsWith(`
4408
4464
  `) ? value : `${value}
4409
4465
  `;
4410
4466
  var configureMachineSafeConsole = (argv) => {
4411
- if (!argv.includes("--json") && !argv.includes("--json-full")) {
4412
- return;
4467
+ if (argv.includes("--json") || argv.includes("--json-full") || isMachineOnlyCommand(argv)) {
4468
+ routeConsoleToStderr();
4413
4469
  }
4470
+ };
4471
+ var MACHINE_ONLY_COMMANDS = new Set(["session"]);
4472
+ var isMachineOnlyCommand = (argv) => {
4473
+ const command = argv.find((token, index) => !token.startsWith("-") && argv[index - 1] !== "--plugin");
4474
+ return command != null && MACHINE_ONLY_COMMANDS.has(command);
4475
+ };
4476
+ var routeConsoleToStderr = () => {
4414
4477
  const writeConsoleError = console.error.bind(console);
4415
4478
  console.log = writeConsoleError;
4416
4479
  console.info = writeConsoleError;
@@ -7211,7 +7274,7 @@ var normalizeTimeout = (value) => {
7211
7274
  // ../argus-watcher/package.json
7212
7275
  var package_default2 = {
7213
7276
  name: "@vforsh/argus-watcher",
7214
- version: "0.4.0",
7277
+ version: "0.5.0",
7215
7278
  repository: {
7216
7279
  type: "git",
7217
7280
  url: "git+https://github.com/vforsh/argus.git",
@@ -7238,7 +7301,7 @@ var package_default2 = {
7238
7301
  },
7239
7302
  dependencies: {
7240
7303
  "@jridgewell/trace-mapping": "^0.3.31",
7241
- "@vforsh/argus-core": "^0.4.0",
7304
+ "@vforsh/argus-core": "^0.5.0",
7242
7305
  emittery: "^1.2.0"
7243
7306
  },
7244
7307
  scripts: {
@@ -8299,9 +8362,9 @@ var netMockRoutes = [
8299
8362
  ];
8300
8363
 
8301
8364
  // ../argus-watcher/dist/cdp/pageState.js
8302
- var evaluateInPage = async (session, expression, options = {}) => {
8365
+ var evaluateInPage = async (session2, expression, options = {}) => {
8303
8366
  const { failureMessage, awaitPromise, ...sendOptions } = options;
8304
- const payload = await session.sendAndWait("Runtime.evaluate", {
8367
+ const payload = await session2.sendAndWait("Runtime.evaluate", {
8305
8368
  expression,
8306
8369
  awaitPromise: awaitPromise ?? false,
8307
8370
  returnByValue: true
@@ -8311,17 +8374,17 @@ var evaluateInPage = async (session, expression, options = {}) => {
8311
8374
  }
8312
8375
  return payload.result?.value;
8313
8376
  };
8314
- var tryEvaluateInPage = async (session, expression, options = {}) => {
8377
+ var tryEvaluateInPage = async (session2, expression, options = {}) => {
8315
8378
  try {
8316
- return await evaluateInPage(session, expression, options);
8379
+ return await evaluateInPage(session2, expression, options);
8317
8380
  } catch {
8318
8381
  return;
8319
8382
  }
8320
8383
  };
8321
8384
  var formatPageException = (details, fallback = "Page evaluation failed") => details.exception?.description ?? details.text ?? fallback;
8322
- var callFunctionOnNode = async (session, node, fn, options = {}) => {
8385
+ var callFunctionOnNode = async (session2, node, fn, options = {}) => {
8323
8386
  const { onUnresolved, ...sendOptions } = options;
8324
- const resolved = await session.sendAndWait("DOM.resolveNode", node, sendOptions);
8387
+ const resolved = await session2.sendAndWait("DOM.resolveNode", node, sendOptions);
8325
8388
  const objectId = resolved.object?.objectId;
8326
8389
  if (!objectId) {
8327
8390
  if (onUnresolved) {
@@ -8329,7 +8392,7 @@ var callFunctionOnNode = async (session, node, fn, options = {}) => {
8329
8392
  }
8330
8393
  return;
8331
8394
  }
8332
- const result = await session.sendAndWait("Runtime.callFunctionOn", {
8395
+ const result = await session2.sendAndWait("Runtime.callFunctionOn", {
8333
8396
  objectId,
8334
8397
  functionDeclaration: fn.code,
8335
8398
  arguments: fn.args,
@@ -8343,8 +8406,8 @@ var callFunctionOnNode = async (session, node, fn, options = {}) => {
8343
8406
  };
8344
8407
 
8345
8408
  // ../argus-watcher/dist/cdp/authPageState.js
8346
- var inspectPageState = async (session) => {
8347
- const state2 = await evaluateInPage(session, `(() => {
8409
+ var inspectPageState = async (session2) => {
8410
+ const state2 = await evaluateInPage(session2, `(() => {
8348
8411
  try {
8349
8412
  const url = String(location.href)
8350
8413
  const origin = new URL(url).origin
@@ -8567,9 +8630,9 @@ var normalizeSetCookieInput = (cookie) => ({
8567
8630
  var normalizeCookieExpires = (value) => typeof value === "number" && Number.isFinite(value) ? value : null;
8568
8631
 
8569
8632
  // ../argus-watcher/dist/cdp/authCookies.js
8570
- var inspectAuthCookies = async (session, options) => {
8571
- const { origin } = await inspectPageState(session);
8572
- const raw = await readRawCookies(session);
8633
+ var inspectAuthCookies = async (session2, options) => {
8634
+ const { origin } = await inspectPageState(session2);
8635
+ const raw = await readRawCookies(session2);
8573
8636
  const cookies2 = raw.map((cookie) => toAuthCookie(toStateCookie(cookie), options.includeValues === true)).sort(compareCookieIdentity);
8574
8637
  const normalizedDomain = normalizeCookieDomainFilter(options.domain);
8575
8638
  return {
@@ -8578,19 +8641,19 @@ var inspectAuthCookies = async (session, options) => {
8578
8641
  cookies: cookies2.filter((cookie) => matchesCookieDomain(cookie.domain, normalizedDomain))
8579
8642
  };
8580
8643
  };
8581
- var inspectAuthCookie = async (session, options) => {
8582
- const pageState = await inspectPageState(session);
8583
- const cookie = await findContextCookie(session, pageState, options, options.readBrowserCookies);
8644
+ var inspectAuthCookie = async (session2, options) => {
8645
+ const pageState = await inspectPageState(session2);
8646
+ const cookie = await findContextCookie(session2, pageState, options, options.readBrowserCookies);
8584
8647
  return {
8585
8648
  ok: true,
8586
8649
  origin: pageState.origin,
8587
8650
  cookie: cookie ? toAuthCookie(cookie, options.includeValue === true) : null
8588
8651
  };
8589
8652
  };
8590
- var setAuthCookie = async (session, options) => {
8591
- const pageState = await inspectPageState(session);
8653
+ var setAuthCookie = async (session2, options) => {
8654
+ const pageState = await inspectPageState(session2);
8592
8655
  const cookie = normalizeSetCookieInput(options.cookie);
8593
- const payload = await session.sendAndWait("Network.setCookie", {
8656
+ const payload = await session2.sendAndWait("Network.setCookie", {
8594
8657
  name: cookie.name,
8595
8658
  value: cookie.value,
8596
8659
  domain: cookie.domain,
@@ -8603,16 +8666,16 @@ var setAuthCookie = async (session, options) => {
8603
8666
  if (payload.success === false) {
8604
8667
  throw new Error(`Chrome rejected cookie ${cookie.name}`);
8605
8668
  }
8606
- const stored = await findContextCookie(session, pageState, cookie, options.readBrowserCookies);
8669
+ const stored = await findContextCookie(session2, pageState, cookie, options.readBrowserCookies);
8607
8670
  return {
8608
8671
  ok: true,
8609
8672
  origin: pageState.origin,
8610
8673
  cookie: toAuthCookie(stored ?? cookie, false)
8611
8674
  };
8612
8675
  };
8613
- var deleteAuthCookie = async (session, options) => {
8614
- const pageState = await inspectPageState(session);
8615
- const existing = await findContextCookie(session, pageState, options, options.readBrowserCookies);
8676
+ var deleteAuthCookie = async (session2, options) => {
8677
+ const pageState = await inspectPageState(session2);
8678
+ const existing = await findContextCookie(session2, pageState, options, options.readBrowserCookies);
8616
8679
  if (!existing) {
8617
8680
  return {
8618
8681
  ok: true,
@@ -8621,7 +8684,7 @@ var deleteAuthCookie = async (session, options) => {
8621
8684
  cookie: toCookieIdentity(options)
8622
8685
  };
8623
8686
  }
8624
- await deleteCookie(session, existing);
8687
+ await deleteCookie(session2, existing);
8625
8688
  return {
8626
8689
  ok: true,
8627
8690
  origin: pageState.origin,
@@ -8629,13 +8692,13 @@ var deleteAuthCookie = async (session, options) => {
8629
8692
  cookie: toCookieIdentity(existing)
8630
8693
  };
8631
8694
  };
8632
- var clearAuthCookies = async (session, options) => {
8633
- const pageState = await inspectPageState(session);
8634
- const cookies2 = await readStateCookies(session, options.readBrowserCookies, { url: pageState.url });
8695
+ var clearAuthCookies = async (session2, options) => {
8696
+ const pageState = await inspectPageState(session2);
8697
+ const cookies2 = await readStateCookies(session2, options.readBrowserCookies, { url: pageState.url });
8635
8698
  const matcher = createClearCookieMatcher(pageState, options);
8636
8699
  const targets = cookies2.filter((cookie) => matcher(cookie) && matchesCookieClearFilters(cookie, options));
8637
8700
  for (const cookie of targets) {
8638
- await deleteCookie(session, cookie);
8701
+ await deleteCookie(session2, cookie);
8639
8702
  }
8640
8703
  return {
8641
8704
  ok: true,
@@ -8648,30 +8711,30 @@ var clearAuthCookies = async (session, options) => {
8648
8711
  cookies: targets.map((cookie) => toCookieIdentity(cookie)).sort(compareCookieIdentity)
8649
8712
  };
8650
8713
  };
8651
- var readStateCookies = async (session, readBrowserCookiesFromSource, query2) => {
8714
+ var readStateCookies = async (session2, readBrowserCookiesFromSource, query2) => {
8652
8715
  const [browserCookies, pageCookies] = await Promise.all([
8653
- readBrowserCookiesFromSource ? readBrowserCookiesFromSource(query2) : readBrowserCookiesFromSession(session),
8654
- readRawCookies(session)
8716
+ readBrowserCookiesFromSource ? readBrowserCookiesFromSource(query2) : readBrowserCookiesFromSession(session2),
8717
+ readRawCookies(session2)
8655
8718
  ]);
8656
8719
  return mergeStateCookies(browserCookies, pageCookies.map(toStateCookie)).filter((cookie) => matchesCookieDomain(cookie.domain, query2.domain ?? null)).sort(compareCookieIdentity);
8657
8720
  };
8658
- var findContextCookie = async (session, pageState, identity, readBrowserCookiesFromSource) => {
8659
- const cookies2 = await readStateCookies(session, readBrowserCookiesFromSource, { url: pageState.url });
8721
+ var findContextCookie = async (session2, pageState, identity, readBrowserCookiesFromSource) => {
8722
+ const cookies2 = await readStateCookies(session2, readBrowserCookiesFromSource, { url: pageState.url });
8660
8723
  return cookies2.find((cookie) => matchesCookieIdentity(cookie, identity)) ?? null;
8661
8724
  };
8662
- var deleteCookie = async (session, cookie) => {
8663
- await session.sendAndWait("Network.deleteCookies", { name: cookie.name, domain: cookie.domain, path: cookie.path }, { timeoutMs: 5000 });
8725
+ var deleteCookie = async (session2, cookie) => {
8726
+ await session2.sendAndWait("Network.deleteCookies", { name: cookie.name, domain: cookie.domain, path: cookie.path }, { timeoutMs: 5000 });
8664
8727
  };
8665
- var readRawCookies = async (session) => {
8666
- const payload = await session.sendAndWait("Network.getCookies", {}, { timeoutMs: 5000 });
8728
+ var readRawCookies = async (session2) => {
8729
+ const payload = await session2.sendAndWait("Network.getCookies", {}, { timeoutMs: 5000 });
8667
8730
  return payload.cookies ?? [];
8668
8731
  };
8669
- var readBrowserCookiesFromSession = async (session) => {
8732
+ var readBrowserCookiesFromSession = async (session2) => {
8670
8733
  try {
8671
- const payload = await session.sendAndWait("Storage.getCookies", {}, { timeoutMs: 5000 });
8734
+ const payload = await session2.sendAndWait("Storage.getCookies", {}, { timeoutMs: 5000 });
8672
8735
  return (payload.cookies ?? []).map(toStateCookie);
8673
8736
  } catch {
8674
- return (await readRawCookies(session)).map(toStateCookie);
8737
+ return (await readRawCookies(session2)).map(toStateCookie);
8675
8738
  }
8676
8739
  };
8677
8740
  var mergeStateCookies = (...groups) => {
@@ -8751,11 +8814,11 @@ var route15 = defineJsonRoute({
8751
8814
  });
8752
8815
 
8753
8816
  // ../argus-watcher/dist/cdp/authSnapshot.js
8754
- var inspectAuthState = async (session, options) => {
8755
- const pageState = await inspectPageState(session);
8817
+ var inspectAuthState = async (session2, options) => {
8818
+ const pageState = await inspectPageState(session2);
8756
8819
  const siteDomain = getLikelySiteDomain(pageState.origin);
8757
8820
  const normalizedDomain = normalizeCookieDomainFilter(options.domain) ?? siteDomain;
8758
- const cookies2 = await readStateCookies(session, options.readBrowserCookies, {
8821
+ const cookies2 = await readStateCookies(session2, options.readBrowserCookies, {
8759
8822
  domain: normalizedDomain,
8760
8823
  url: pageState.url
8761
8824
  });
@@ -9008,12 +9071,12 @@ import { randomUUID as randomUUID2 } from "node:crypto";
9008
9071
  var SCENARIO_ACTION_TIMEOUT_MS = 30000;
9009
9072
  var DEFAULT_LOG_LIMIT = 500;
9010
9073
  var MAX_LOG_LIMIT = 5000;
9011
- var installScenarioBridge = async (session, expression, args, services, timeoutMs) => {
9074
+ var installScenarioBridge = async (session2, expression, args, services, timeoutMs) => {
9012
9075
  const token = randomUUID2();
9013
9076
  const suffix = token.replaceAll("-", "");
9014
9077
  const bindingName = `__argusScenarioSend_${suffix}`;
9015
9078
  const responseName = `__argusScenarioReceive_${suffix}`;
9016
- const off = session.onEvent("Runtime.bindingCalled", (rawEvent, meta) => {
9079
+ const off = session2.onEvent("Runtime.bindingCalled", (rawEvent, meta) => {
9017
9080
  const { name, payload, executionContextId } = rawEvent;
9018
9081
  if (name !== bindingName || typeof payload !== "string" || typeof executionContextId !== "number" || !Number.isInteger(executionContextId)) {
9019
9082
  return;
@@ -9022,10 +9085,10 @@ var installScenarioBridge = async (session, expression, args, services, timeoutM
9022
9085
  if (!request) {
9023
9086
  return;
9024
9087
  }
9025
- respondToBridgeRequest(session, responseName, request, services, executionContextId, meta, timeoutMs);
9088
+ respondToBridgeRequest(session2, responseName, request, services, executionContextId, meta, timeoutMs);
9026
9089
  });
9027
9090
  try {
9028
- await session.sendAndWait("Runtime.addBinding", { name: bindingName }, { timeoutMs });
9091
+ await session2.sendAndWait("Runtime.addBinding", { name: bindingName }, { timeoutMs });
9029
9092
  } catch (error) {
9030
9093
  off();
9031
9094
  throw error;
@@ -9039,7 +9102,7 @@ var installScenarioBridge = async (session, expression, args, services, timeoutM
9039
9102
  disposed = true;
9040
9103
  off();
9041
9104
  try {
9042
- await session.sendAndWait("Runtime.removeBinding", { name: bindingName }, { timeoutMs });
9105
+ await session2.sendAndWait("Runtime.removeBinding", { name: bindingName }, { timeoutMs });
9043
9106
  } catch {}
9044
9107
  }
9045
9108
  };
@@ -9059,7 +9122,7 @@ var parseBridgeRequest = (payload, token) => {
9059
9122
  return null;
9060
9123
  }
9061
9124
  };
9062
- var respondToBridgeRequest = async (session, responseName, request, services, executionContextId, meta, timeoutMs) => {
9125
+ var respondToBridgeRequest = async (session2, responseName, request, services, executionContextId, meta, timeoutMs) => {
9063
9126
  let response;
9064
9127
  try {
9065
9128
  response = { id: request.id, ok: true, result: await handleBridgeRequest(request, services) };
@@ -9067,7 +9130,7 @@ var respondToBridgeRequest = async (session, responseName, request, services, ex
9067
9130
  response = { id: request.id, ok: false, error: formatError(error) };
9068
9131
  }
9069
9132
  try {
9070
- await sendBridgeResponse(session, responseName, response, executionContextId, meta, timeoutMs);
9133
+ await sendBridgeResponse(session2, responseName, response, executionContextId, meta, timeoutMs);
9071
9134
  } catch {}
9072
9135
  };
9073
9136
  var handleBridgeRequest = async (request, services) => {
@@ -9199,8 +9262,8 @@ var requireRecord = (value, label) => {
9199
9262
  }
9200
9263
  return value;
9201
9264
  };
9202
- var sendBridgeResponse = async (session, responseName, response, executionContextId, meta, timeoutMs) => {
9203
- await session.sendAndWait("Runtime.evaluate", {
9265
+ var sendBridgeResponse = async (session2, responseName, response, executionContextId, meta, timeoutMs) => {
9266
+ await session2.sendAndWait("Runtime.evaluate", {
9204
9267
  expression: `globalThis[${JSON.stringify(responseName)}]?.(${JSON.stringify(response)})`,
9205
9268
  contextId: executionContextId,
9206
9269
  returnByValue: true,
@@ -9283,7 +9346,7 @@ var buildScenarioExpression = (expression, options) => `(async () => {
9283
9346
  })()`;
9284
9347
 
9285
9348
  // ../argus-watcher/dist/cdp/eval.js
9286
- var evaluateExpression = async (session, options) => {
9349
+ var evaluateExpression = async (session2, options) => {
9287
9350
  const args = hasEvalArgs(options.args) ? options.args : undefined;
9288
9351
  let scenarioBridge;
9289
9352
  try {
@@ -9291,9 +9354,9 @@ var evaluateExpression = async (session, options) => {
9291
9354
  if (!options.scenarioServices) {
9292
9355
  throw new Error("Scenario host services are unavailable");
9293
9356
  }
9294
- scenarioBridge = await installScenarioBridge(session, options.expression, args, options.scenarioServices, options.timeoutMs);
9357
+ scenarioBridge = await installScenarioBridge(session2, options.expression, args, options.scenarioServices, options.timeoutMs);
9295
9358
  }
9296
- const recordResult = await evaluateAndAwaitRecord(session, {
9359
+ const recordResult = await evaluateAndAwaitRecord(session2, {
9297
9360
  ...options,
9298
9361
  expression: wrapExpressionWithArgs(scenarioBridge?.expression ?? options.expression, args),
9299
9362
  replMode: scenarioBridge ? false : options.replMode
@@ -9302,7 +9365,7 @@ var evaluateExpression = async (session, options) => {
9302
9365
  return recordResult.response;
9303
9366
  const record2 = recordResult.record;
9304
9367
  if (options.jsonValue) {
9305
- const jsonResult = await materializeJsonValue(session, record2, options);
9368
+ const jsonResult = await materializeJsonValue(session2, record2, options);
9306
9369
  if (!jsonResult.ok)
9307
9370
  return jsonResult.response;
9308
9371
  return {
@@ -9312,7 +9375,7 @@ var evaluateExpression = async (session, options) => {
9312
9375
  exception: null
9313
9376
  };
9314
9377
  }
9315
- const value = await materializeRemoteObject(session, record2, options);
9378
+ const value = await materializeRemoteObject(session2, record2, options);
9316
9379
  return {
9317
9380
  ok: true,
9318
9381
  result: value ?? null,
@@ -9331,8 +9394,8 @@ var wrapExpressionWithArgs = (expression, args) => {
9331
9394
  ${expression}
9332
9395
  }`;
9333
9396
  };
9334
- var evaluateAndAwaitRecord = async (session, options) => {
9335
- const payload = await evaluateRawExpression(session, options);
9397
+ var evaluateAndAwaitRecord = async (session2, options) => {
9398
+ const payload = await evaluateRawExpression(session2, options);
9336
9399
  if (payload.exceptionDetails) {
9337
9400
  return { response: formatExceptionResponse(payload), exception: true };
9338
9401
  }
@@ -9340,7 +9403,7 @@ var evaluateAndAwaitRecord = async (session, options) => {
9340
9403
  if (!(options.awaitPromise ?? true) || record2?.subtype !== "promise" || !record2.objectId) {
9341
9404
  return { record: record2, exception: false };
9342
9405
  }
9343
- const awaitedPayload = await awaitPromiseResult(session, record2.objectId, options.timeoutMs);
9406
+ const awaitedPayload = await awaitPromiseResult(session2, record2.objectId, options.timeoutMs);
9344
9407
  if (awaitedPayload.exceptionDetails) {
9345
9408
  return { response: formatExceptionResponse(awaitedPayload), exception: true };
9346
9409
  }
@@ -9355,25 +9418,25 @@ var formatExceptionResponse = (payload) => ({
9355
9418
  details: payload.exceptionDetails?.exception ?? null
9356
9419
  }
9357
9420
  });
9358
- var evaluateRawExpression = async (session, options) => await session.sendAndWait("Runtime.evaluate", {
9421
+ var evaluateRawExpression = async (session2, options) => await session2.sendAndWait("Runtime.evaluate", {
9359
9422
  expression: options.expression,
9360
9423
  replMode: options.replMode ?? true,
9361
9424
  awaitPromise: false,
9362
9425
  returnByValue: false
9363
9426
  }, { timeoutMs: options.timeoutMs });
9364
- var awaitPromiseResult = async (session, promiseObjectId, timeoutMs) => await session.sendAndWait("Runtime.awaitPromise", {
9427
+ var awaitPromiseResult = async (session2, promiseObjectId, timeoutMs) => await session2.sendAndWait("Runtime.awaitPromise", {
9365
9428
  promiseObjectId,
9366
9429
  returnByValue: false
9367
9430
  }, { timeoutMs });
9368
9431
  var EMPTY_JSON_ENVELOPE = "{}";
9369
- var materializeJsonValue = async (session, record2, options) => {
9432
+ var materializeJsonValue = async (session2, record2, options) => {
9370
9433
  if (!record2) {
9371
9434
  return { ok: true, json: EMPTY_JSON_ENVELOPE };
9372
9435
  }
9373
9436
  if (!record2.objectId) {
9374
9437
  return { ok: true, json: JSON.stringify({ v: record2.value }) ?? EMPTY_JSON_ENVELOPE };
9375
9438
  }
9376
- const payload = await session.sendAndWait("Runtime.callFunctionOn", {
9439
+ const payload = await session2.sendAndWait("Runtime.callFunctionOn", {
9377
9440
  objectId: record2.objectId,
9378
9441
  functionDeclaration: "function () { return JSON.stringify({ v: this }) }",
9379
9442
  returnByValue: true
@@ -9384,23 +9447,23 @@ var materializeJsonValue = async (session, record2, options) => {
9384
9447
  const json = payload.result?.value;
9385
9448
  return { ok: true, json: typeof json === "string" ? json : EMPTY_JSON_ENVELOPE };
9386
9449
  };
9387
- var materializeRemoteObject = async (session, record2, options) => {
9450
+ var materializeRemoteObject = async (session2, record2, options) => {
9388
9451
  if (!record2) {
9389
9452
  return null;
9390
9453
  }
9391
9454
  if ((options.returnByValue ?? true) && shouldMaterializeByValue(record2)) {
9392
9455
  try {
9393
- const byValuePayload = await session.sendAndWait("Runtime.callFunctionOn", {
9456
+ const byValuePayload = await session2.sendAndWait("Runtime.callFunctionOn", {
9394
9457
  objectId: record2.objectId,
9395
9458
  functionDeclaration: "function () { return this; }",
9396
9459
  returnByValue: true
9397
9460
  }, { timeoutMs: options.timeoutMs });
9398
9461
  if (byValuePayload.result) {
9399
- return await serializeRemoteObject(byValuePayload.result, session);
9462
+ return await serializeRemoteObject(byValuePayload.result, session2);
9400
9463
  }
9401
9464
  } catch {}
9402
9465
  }
9403
- return await serializeRemoteObject(record2, session);
9466
+ return await serializeRemoteObject(record2, session2);
9404
9467
  };
9405
9468
  var shouldMaterializeByValue = (record2) => {
9406
9469
  return Boolean(record2.objectId) && record2.type === "object" && (record2.subtype == null || record2.subtype === "array");
@@ -9493,11 +9556,11 @@ var route21 = defineJsonRoute({
9493
9556
  });
9494
9557
 
9495
9558
  // ../argus-watcher/dist/cdp/text-filter.js
9496
- var filterNodesByText = async (session, nodeIds, text) => {
9559
+ var filterNodesByText = async (session2, nodeIds, text) => {
9497
9560
  const pattern = parseTextPattern(text);
9498
9561
  const filtered = [];
9499
9562
  for (const nodeId of nodeIds) {
9500
- const trimmedText = await callFunctionOnNode(session, { nodeId }, { code: "function() { return this.textContent?.trim(); }" });
9563
+ const trimmedText = await callFunctionOnNode(session2, { nodeId }, { code: "function() { return this.textContent?.trim(); }" });
9501
9564
  if (typeof trimmedText !== "string") {
9502
9565
  continue;
9503
9566
  }
@@ -9515,27 +9578,27 @@ var filterNodesByText = async (session, nodeIds, text) => {
9515
9578
  };
9516
9579
 
9517
9580
  // ../argus-watcher/dist/cdp/dom/selector.js
9518
- var getDomRootId = async (session) => {
9519
- const targetContext = await session.getReadyTargetContext();
9581
+ var getDomRootId = async (session2) => {
9582
+ const targetContext = await session2.getReadyTargetContext();
9520
9583
  if (targetContext?.kind === "frame") {
9521
- return getFrameDomRootId(session, targetContext);
9584
+ return getFrameDomRootId(session2, targetContext);
9522
9585
  }
9523
- return getDocumentRootId(session);
9586
+ return getDocumentRootId(session2);
9524
9587
  };
9525
- var resolveSelectorMatches = async (session, rootId, selector, all, text) => {
9526
- const result = await session.sendAndWait("DOM.querySelectorAll", { nodeId: rootId, selector });
9588
+ var resolveSelectorMatches = async (session2, rootId, selector, all, text) => {
9589
+ const result = await session2.sendAndWait("DOM.querySelectorAll", { nodeId: rootId, selector });
9527
9590
  let allNodeIds = result.nodeIds ?? [];
9528
9591
  if (text != null) {
9529
- allNodeIds = await filterNodesByText(session, allNodeIds, text);
9592
+ allNodeIds = await filterNodesByText(session2, allNodeIds, text);
9530
9593
  }
9531
9594
  const nodeIds = all ? allNodeIds : allNodeIds.slice(0, 1);
9532
9595
  return { allNodeIds, nodeIds };
9533
9596
  };
9534
- var waitForSelectorMatches = async (session, selector, all, text, waitMs, intervalMs = 100) => {
9597
+ var waitForSelectorMatches = async (session2, selector, all, text, waitMs, intervalMs = 100) => {
9535
9598
  const deadline = Date.now() + waitMs;
9536
9599
  while (true) {
9537
- const rootId = await getDomRootId(session);
9538
- const result = await resolveSelectorMatches(session, rootId, selector, all, text);
9600
+ const rootId = await getDomRootId(session2);
9601
+ const result = await resolveSelectorMatches(session2, rootId, selector, all, text);
9539
9602
  if (result.allNodeIds.length > 0)
9540
9603
  return result;
9541
9604
  const remaining = deadline - Date.now();
@@ -9544,17 +9607,17 @@ var waitForSelectorMatches = async (session, selector, all, text, waitMs, interv
9544
9607
  await new Promise((r) => setTimeout(r, Math.min(intervalMs, remaining)));
9545
9608
  }
9546
9609
  };
9547
- var resolveSelectorTargets = async (session, options) => {
9548
- await session.sendAndWait("DOM.enable");
9610
+ var resolveSelectorTargets = async (session2, options) => {
9611
+ await session2.sendAndWait("DOM.enable");
9549
9612
  const waitMs = options.waitMs ?? 0;
9550
9613
  if (waitMs > 0) {
9551
- return waitForSelectorMatches(session, options.selector, options.all, options.text, waitMs);
9614
+ return waitForSelectorMatches(session2, options.selector, options.all, options.text, waitMs);
9552
9615
  }
9553
- const rootId = await getDomRootId(session);
9554
- return resolveSelectorMatches(session, rootId, options.selector, options.all, options.text);
9616
+ const rootId = await getDomRootId(session2);
9617
+ return resolveSelectorMatches(session2, rootId, options.selector, options.all, options.text);
9555
9618
  };
9556
- var resolveElementTargets = async (session, elementRefs, options) => {
9557
- await session.sendAndWait("DOM.enable");
9619
+ var resolveElementTargets = async (session2, elementRefs, options) => {
9620
+ await session2.sendAndWait("DOM.enable");
9558
9621
  if (options.ref) {
9559
9622
  const backendNodeId = elementRefs.resolve(options.ref);
9560
9623
  if (backendNodeId == null) {
@@ -9578,7 +9641,7 @@ var resolveElementTargets = async (session, elementRefs, options) => {
9578
9641
  if (!options.selector) {
9579
9642
  throw new Error("selector or ref is required");
9580
9643
  }
9581
- const result = (options.waitMs ?? 0) > 0 ? await waitForSelectorMatches(session, options.selector, options.all, options.text, options.waitMs ?? 0) : await resolveSelectorMatches(session, await getDomRootId(session), options.selector, options.all, options.text);
9644
+ const result = (options.waitMs ?? 0) > 0 ? await waitForSelectorMatches(session2, options.selector, options.all, options.text, options.waitMs ?? 0) : await resolveSelectorMatches(session2, await getDomRootId(session2), options.selector, options.all, options.text);
9582
9645
  return {
9583
9646
  target: { kind: "selector", value: options.selector },
9584
9647
  allHandles: result.allNodeIds.map((nodeId) => ({ nodeId })),
@@ -9586,28 +9649,28 @@ var resolveElementTargets = async (session, elementRefs, options) => {
9586
9649
  ...result
9587
9650
  };
9588
9651
  };
9589
- var resolveFirstSelectorNodeId = async (session, selector, text) => {
9590
- const { nodeIds } = await resolveSelectorTargets(session, {
9652
+ var resolveFirstSelectorNodeId = async (session2, selector, text) => {
9653
+ const { nodeIds } = await resolveSelectorTargets(session2, {
9591
9654
  selector,
9592
9655
  all: false,
9593
9656
  text
9594
9657
  });
9595
9658
  return nodeIds[0] ?? null;
9596
9659
  };
9597
- var describeNodeByBackendId = async (session, backendNodeId) => {
9598
- const described = await session.sendAndWait("DOM.describeNode", {
9660
+ var describeNodeByBackendId = async (session2, backendNodeId) => {
9661
+ const described = await session2.sendAndWait("DOM.describeNode", {
9599
9662
  backendNodeId,
9600
9663
  depth: 0
9601
9664
  });
9602
9665
  return described.node ?? null;
9603
9666
  };
9604
- var resolveNodeIdByBackendId = async (session, backendNodeId) => {
9605
- const describedNode = await describeNodeByBackendId(session, backendNodeId);
9667
+ var resolveNodeIdByBackendId = async (session2, backendNodeId) => {
9668
+ const describedNode = await describeNodeByBackendId(session2, backendNodeId);
9606
9669
  if (describedNode?.nodeId) {
9607
9670
  return describedNode.nodeId;
9608
9671
  }
9609
- await getDomRootId(session);
9610
- const pushed = await session.sendAndWait("DOM.pushNodesByBackendIdsToFrontend", {
9672
+ await getDomRootId(session2);
9673
+ const pushed = await session2.sendAndWait("DOM.pushNodesByBackendIdsToFrontend", {
9611
9674
  backendNodeIds: [backendNodeId]
9612
9675
  });
9613
9676
  const nodeId = pushed.nodeIds?.[0];
@@ -9622,14 +9685,14 @@ var toDomNodeDescriptor = (handle) => {
9622
9685
  }
9623
9686
  throw new Error("DOM node handle is missing both nodeId and backendNodeId");
9624
9687
  };
9625
- var getFrameDomRootId = async (session, targetContext) => {
9688
+ var getFrameDomRootId = async (session2, targetContext) => {
9626
9689
  if (targetContext.sessionId) {
9627
- return getDocumentRootId(session);
9690
+ return getDocumentRootId(session2);
9628
9691
  }
9629
9692
  if (targetContext.executionContextId == null) {
9630
9693
  throw new Error(`Selected frame is not ready yet: ${targetContext.frameId}`);
9631
9694
  }
9632
- const evaluated = await session.sendAndWait("Runtime.evaluate", {
9695
+ const evaluated = await session2.sendAndWait("Runtime.evaluate", {
9633
9696
  expression: "document",
9634
9697
  contextId: targetContext.executionContextId,
9635
9698
  returnByValue: false
@@ -9638,14 +9701,14 @@ var getFrameDomRootId = async (session, targetContext) => {
9638
9701
  if (!objectId) {
9639
9702
  throw new Error(`Unable to resolve DOM root for frame: ${targetContext.frameId}`);
9640
9703
  }
9641
- const requested = await session.sendAndWait("DOM.requestNode", { objectId });
9704
+ const requested = await session2.sendAndWait("DOM.requestNode", { objectId });
9642
9705
  if (!requested.nodeId) {
9643
9706
  throw new Error(`Unable to resolve DOM root for frame: ${targetContext.frameId}`);
9644
9707
  }
9645
9708
  return requested.nodeId;
9646
9709
  };
9647
- var getDocumentRootId = async (session) => {
9648
- const result = await session.sendAndWait("DOM.getDocument", { depth: 1 });
9710
+ var getDocumentRootId = async (session2) => {
9711
+ const result = await session2.sendAndWait("DOM.getDocument", { depth: 1 });
9649
9712
  const rootId = result.root?.nodeId;
9650
9713
  if (!rootId) {
9651
9714
  throw new Error("Unable to resolve DOM root");
@@ -9737,9 +9800,9 @@ var RELEVANT_PROPERTIES = new Set([
9737
9800
  "multiselectable",
9738
9801
  "orientation"
9739
9802
  ]);
9740
- var fetchAccessibilitySnapshot = async (session, options, elementRefs) => {
9741
- await session.sendAndWait("Accessibility.enable");
9742
- const nodes = await resolveAccessibilityNodes(session, options.selector);
9803
+ var fetchAccessibilitySnapshot = async (session2, options, elementRefs) => {
9804
+ await session2.sendAndWait("Accessibility.enable");
9805
+ const nodes = await resolveAccessibilityNodes(session2, options.selector);
9743
9806
  const totalNodes = nodes.length;
9744
9807
  const roots = buildTree(nodes, {
9745
9808
  depth: options.depth,
@@ -9749,8 +9812,8 @@ var fetchAccessibilitySnapshot = async (session, options, elementRefs) => {
9749
9812
  const returnedNodes = countNodes(roots);
9750
9813
  return { ok: true, roots, totalNodes, returnedNodes };
9751
9814
  };
9752
- var listAccessibleElements = async (session, elementRefs, options = {}) => {
9753
- const nodes = await resolveAccessibilityNodes(session, options.selector);
9815
+ var listAccessibleElements = async (session2, elementRefs, options = {}) => {
9816
+ const nodes = await resolveAccessibilityNodes(session2, options.selector);
9754
9817
  return collectAccessibleElements(nodes, elementRefs);
9755
9818
  };
9756
9819
  var buildTree = (cdpNodes, options) => {
@@ -9821,24 +9884,24 @@ var convertNode = (nodeMap, nodeId, currentDepth, options) => {
9821
9884
  }
9822
9885
  return [result];
9823
9886
  };
9824
- var fetchAccessibilityNodes = async (session) => {
9825
- const axResult = await session.sendAndWait("Accessibility.getFullAXTree");
9887
+ var fetchAccessibilityNodes = async (session2) => {
9888
+ const axResult = await session2.sendAndWait("Accessibility.getFullAXTree");
9826
9889
  return axResult.nodes ?? [];
9827
9890
  };
9828
- var resolveAccessibilityNodes = async (session, selector) => {
9829
- const nodes = await fetchAccessibilityNodes(session);
9891
+ var resolveAccessibilityNodes = async (session2, selector) => {
9892
+ const nodes = await fetchAccessibilityNodes(session2);
9830
9893
  if (!selector) {
9831
9894
  return nodes;
9832
9895
  }
9833
- return filterAccessibilityNodesBySelector(session, nodes, selector);
9896
+ return filterAccessibilityNodesBySelector(session2, nodes, selector);
9834
9897
  };
9835
- var filterAccessibilityNodesBySelector = async (session, nodes, selector) => {
9836
- const domNodeId = await resolveFirstSelectorNodeId(session, selector);
9898
+ var filterAccessibilityNodesBySelector = async (session2, nodes, selector) => {
9899
+ const domNodeId = await resolveFirstSelectorNodeId(session2, selector);
9837
9900
  if (!domNodeId) {
9838
9901
  throw new Error(`No element found for selector: ${selector}`);
9839
9902
  }
9840
- await session.sendAndWait("DOM.getDocument", { depth: -1 });
9841
- const allDescendants = await session.sendAndWait("DOM.querySelectorAll", {
9903
+ await session2.sendAndWait("DOM.getDocument", { depth: -1 });
9904
+ const allDescendants = await session2.sendAndWait("DOM.querySelectorAll", {
9842
9905
  nodeId: domNodeId,
9843
9906
  selector: "*"
9844
9907
  });
@@ -9846,7 +9909,7 @@ var filterAccessibilityNodesBySelector = async (session, nodes, selector) => {
9846
9909
  const backendIds = new Set;
9847
9910
  const allDomNodeIds = [domNodeId, ...descendantNodeIds];
9848
9911
  for (const nid of allDomNodeIds) {
9849
- const desc = await session.sendAndWait("DOM.describeNode", { nodeId: nid, depth: 0 });
9912
+ const desc = await session2.sendAndWait("DOM.describeNode", { nodeId: nid, depth: 0 });
9850
9913
  if (desc.node?.backendNodeId != null) {
9851
9914
  backendIds.add(desc.node.backendNodeId);
9852
9915
  }
@@ -9981,8 +10044,8 @@ var route22 = defineJsonRoute({
9981
10044
 
9982
10045
  // ../argus-watcher/dist/cdp/locate.js
9983
10046
  var LABELABLE_ROLES = new Set(["button", "checkbox", "combobox", "listbox", "radio", "searchbox", "slider", "spinbutton", "switch", "textbox"]);
9984
- var locateByRole = async (session, elementRefs, request) => {
9985
- const matches = (await listAccessibleElements(session, elementRefs)).filter((element) => {
10047
+ var locateByRole = async (session2, elementRefs, request) => {
10048
+ const matches = (await listAccessibleElements(session2, elementRefs)).filter((element) => {
9986
10049
  if (normalizeText(element.role) !== normalizeText(request.role)) {
9987
10050
  return false;
9988
10051
  }
@@ -9991,29 +10054,29 @@ var locateByRole = async (session, elementRefs, request) => {
9991
10054
  }
9992
10055
  return matchesText(element.name, request.name, request.exact ?? false);
9993
10056
  });
9994
- return buildLocateResponse(session, request.all ?? false, matches);
10057
+ return buildLocateResponse(session2, request.all ?? false, matches);
9995
10058
  };
9996
- var locateByText = async (session, elementRefs, request) => {
9997
- const matches = (await listAccessibleElements(session, elementRefs)).filter((element) => matchesText(element.name, request.text, request.exact ?? false) || matchesText(element.value ?? "", request.text, request.exact ?? false));
9998
- return buildLocateResponse(session, request.all ?? false, matches);
10059
+ var locateByText = async (session2, elementRefs, request) => {
10060
+ const matches = (await listAccessibleElements(session2, elementRefs)).filter((element) => matchesText(element.name, request.text, request.exact ?? false) || matchesText(element.value ?? "", request.text, request.exact ?? false));
10061
+ return buildLocateResponse(session2, request.all ?? false, matches);
9999
10062
  };
10000
- var locateByLabel = async (session, elementRefs, request) => {
10001
- const matches = (await listAccessibleElements(session, elementRefs)).filter((element) => {
10063
+ var locateByLabel = async (session2, elementRefs, request) => {
10064
+ const matches = (await listAccessibleElements(session2, elementRefs)).filter((element) => {
10002
10065
  if (!LABELABLE_ROLES.has(element.role)) {
10003
10066
  return false;
10004
10067
  }
10005
10068
  return matchesText(element.name, request.label, request.exact ?? false);
10006
10069
  });
10007
- return buildLocateResponse(session, request.all ?? false, await removeCompositeLabelWrappers(session, matches));
10070
+ return buildLocateResponse(session2, request.all ?? false, await removeCompositeLabelWrappers(session2, matches));
10008
10071
  };
10009
10072
  var NATIVE_LABELABLE_TAGS = new Set(["button", "input", "select", "textarea"]);
10010
- var removeCompositeLabelWrappers = async (session, matches) => {
10073
+ var removeCompositeLabelWrappers = async (session2, matches) => {
10011
10074
  if (matches.length < 2)
10012
10075
  return matches;
10013
10076
  const candidates = await Promise.all(matches.map(async (match) => {
10014
10077
  const [node, nodeId] = await Promise.all([
10015
- describeNodeByBackendId(session, match.backendNodeId),
10016
- resolveNodeIdByBackendId(session, match.backendNodeId)
10078
+ describeNodeByBackendId(session2, match.backendNodeId),
10079
+ resolveNodeIdByBackendId(session2, match.backendNodeId)
10017
10080
  ]);
10018
10081
  const tag = node ? (node.localName ?? node.nodeName).toLowerCase() : "";
10019
10082
  return { match, nodeId, native: NATIVE_LABELABLE_TAGS.has(tag) };
@@ -10027,7 +10090,7 @@ var removeCompositeLabelWrappers = async (session, matches) => {
10027
10090
  kept.push(candidate.match);
10028
10091
  continue;
10029
10092
  }
10030
- const descendants = await session.sendAndWait("DOM.querySelectorAll", {
10093
+ const descendants = await session2.sendAndWait("DOM.querySelectorAll", {
10031
10094
  nodeId: candidate.nodeId,
10032
10095
  selector: "button,input,select,textarea"
10033
10096
  });
@@ -10038,17 +10101,17 @@ var removeCompositeLabelWrappers = async (session, matches) => {
10038
10101
  }
10039
10102
  return kept;
10040
10103
  };
10041
- var buildLocateResponse = async (session, all, matches) => {
10104
+ var buildLocateResponse = async (session2, all, matches) => {
10042
10105
  const selected = all ? matches : matches.slice(0, 1);
10043
- const elements = await Promise.all(selected.map((element) => toLocatedElement(session, element)));
10106
+ const elements = await Promise.all(selected.map((element) => toLocatedElement(session2, element)));
10044
10107
  return {
10045
10108
  ok: true,
10046
10109
  matches: matches.length,
10047
10110
  elements
10048
10111
  };
10049
10112
  };
10050
- var toLocatedElement = async (session, element) => {
10051
- const node = await describeNodeByBackendId(session, element.backendNodeId);
10113
+ var toLocatedElement = async (session2, element) => {
10114
+ const node = await describeNodeByBackendId(session2, element.backendNodeId);
10052
10115
  const attributes = node?.attributes ? toAttributesRecord(node.attributes) : undefined;
10053
10116
  return {
10054
10117
  ref: element.ref,
@@ -10189,13 +10252,13 @@ var DEFAULT_DEPTH = 2;
10189
10252
  var DEFAULT_MAX_NODES = 5000;
10190
10253
  var MAX_DEPTH = 10;
10191
10254
  var MAX_MAX_NODES = 50000;
10192
- var fetchDomSubtreeBySelector = async (session, options) => {
10255
+ var fetchDomSubtreeBySelector = async (session2, options) => {
10193
10256
  const depth = clamp(options.depth ?? DEFAULT_DEPTH, 0, MAX_DEPTH);
10194
10257
  const maxNodes = clamp(options.maxNodes ?? DEFAULT_MAX_NODES, 1, MAX_MAX_NODES);
10195
10258
  const all = options.all ?? false;
10196
- await session.sendAndWait("DOM.enable");
10197
- const rootId = await getDomRootId(session);
10198
- const { allNodeIds, nodeIds } = await resolveSelectorMatches(session, rootId, options.selector, all, options.text);
10259
+ await session2.sendAndWait("DOM.enable");
10260
+ const rootId = await getDomRootId(session2);
10261
+ const { allNodeIds, nodeIds } = await resolveSelectorMatches(session2, rootId, options.selector, all, options.text);
10199
10262
  if (allNodeIds.length === 0) {
10200
10263
  return { ok: true, matches: 0, roots: [], truncated: false };
10201
10264
  }
@@ -10207,7 +10270,7 @@ var fetchDomSubtreeBySelector = async (session, options) => {
10207
10270
  state2.truncatedReason = "max_nodes";
10208
10271
  break;
10209
10272
  }
10210
- const describeResult = await session.sendAndWait("DOM.describeNode", {
10273
+ const describeResult = await session2.sendAndWait("DOM.describeNode", {
10211
10274
  nodeId,
10212
10275
  depth: depth + 1
10213
10276
  });
@@ -10278,10 +10341,10 @@ var toDomNodeTree = (node, remainingDepth, state2) => {
10278
10341
  // ../argus-watcher/dist/cdp/dom/info.js
10279
10342
  var DEFAULT_OUTER_HTML_MAX_CHARS = 50000;
10280
10343
  var MAX_OUTER_HTML_CHARS = 500000;
10281
- var fetchDomInfoBySelector = async (session, elementRefs, options) => {
10344
+ var fetchDomInfoBySelector = async (session2, elementRefs, options) => {
10282
10345
  const all = options.all ?? false;
10283
10346
  const maxChars = clamp(options.outerHtmlMaxChars ?? DEFAULT_OUTER_HTML_MAX_CHARS, 0, MAX_OUTER_HTML_CHARS);
10284
- const resolved = await resolveElementTargets(session, elementRefs, {
10347
+ const resolved = await resolveElementTargets(session2, elementRefs, {
10285
10348
  selector: options.selector,
10286
10349
  ref: options.ref,
10287
10350
  all,
@@ -10297,7 +10360,7 @@ var fetchDomInfoBySelector = async (session, elementRefs, options) => {
10297
10360
  const elements = [];
10298
10361
  for (const handle of handles) {
10299
10362
  const descriptor = toDomNodeDescriptor(handle);
10300
- const describeResult = await session.sendAndWait("DOM.describeNode", {
10363
+ const describeResult = await session2.sendAndWait("DOM.describeNode", {
10301
10364
  ...descriptor,
10302
10365
  depth: 1
10303
10366
  });
@@ -10310,7 +10373,7 @@ var fetchDomInfoBySelector = async (session, elementRefs, options) => {
10310
10373
  let outerHTML = null;
10311
10374
  let outerHTMLTruncated = false;
10312
10375
  try {
10313
- const htmlResult = await session.sendAndWait("DOM.getOuterHTML", descriptor);
10376
+ const htmlResult = await session2.sendAndWait("DOM.getOuterHTML", descriptor);
10314
10377
  outerHTML = htmlResult.outerHTML ?? null;
10315
10378
  if (outerHTML && outerHTML.length > maxChars) {
10316
10379
  outerHTML = outerHTML.slice(0, maxChars);
@@ -10330,18 +10393,18 @@ var fetchDomInfoBySelector = async (session, elementRefs, options) => {
10330
10393
  return { ok: true, matches: allHandles.length, elements };
10331
10394
  };
10332
10395
  // ../argus-watcher/dist/cdp/dom/mutate.js
10333
- var mutateMatchedElements = async (session, target, apply) => {
10334
- await session.sendAndWait("DOM.enable");
10335
- const rootId = await getDomRootId(session);
10336
- const { allNodeIds, nodeIds } = await resolveSelectorMatches(session, rootId, target.selector, target.all ?? false, target.text);
10396
+ var mutateMatchedElements = async (session2, target, apply) => {
10397
+ await session2.sendAndWait("DOM.enable");
10398
+ const rootId = await getDomRootId(session2);
10399
+ const { allNodeIds, nodeIds } = await resolveSelectorMatches(session2, rootId, target.selector, target.all ?? false, target.text);
10337
10400
  for (const nodeId of nodeIds) {
10338
10401
  await apply(nodeId);
10339
10402
  }
10340
10403
  return { allNodeIds, mutatedCount: nodeIds.length };
10341
10404
  };
10342
- var mutateWithPageFunction = (session, target, fn) => mutateMatchedElements(session, target, (nodeId) => callFunctionOnNode(session, { nodeId }, fn));
10343
- var removeElements = (session, options) => mutateWithPageFunction(session, options, { code: "function() { this.remove(); }" });
10344
- var modifyElements = (session, options) => mutateWithPageFunction(session, options, buildModifyFunction(options));
10405
+ var mutateWithPageFunction = (session2, target, fn) => mutateMatchedElements(session2, target, (nodeId) => callFunctionOnNode(session2, { nodeId }, fn));
10406
+ var removeElements = (session2, options) => mutateWithPageFunction(session2, options, { code: "function() { this.remove(); }" });
10407
+ var modifyElements = (session2, options) => mutateWithPageFunction(session2, options, buildModifyFunction(options));
10345
10408
  var FILL_FUNCTION = `function(value) {
10346
10409
  var el = this;
10347
10410
  el.focus();
@@ -10363,29 +10426,29 @@ var FILL_FUNCTION = `function(value) {
10363
10426
  el.dispatchEvent(new Event('input', { bubbles: true }));
10364
10427
  el.dispatchEvent(new Event('change', { bubbles: true }));
10365
10428
  }`;
10366
- var fillResolvedNodes = async (session, handles, value) => {
10429
+ var fillResolvedNodes = async (session2, handles, value) => {
10367
10430
  for (const handle of handles) {
10368
- await callFunctionOnNode(session, toDomNodeDescriptor(handle), { code: FILL_FUNCTION, args: [{ value }] });
10431
+ await callFunctionOnNode(session2, toDomNodeDescriptor(handle), { code: FILL_FUNCTION, args: [{ value }] });
10369
10432
  }
10370
10433
  return handles.length;
10371
10434
  };
10372
- var insertAdjacentHtml = async (session, options) => {
10435
+ var insertAdjacentHtml = async (session2, options) => {
10373
10436
  if (options.nodeIds.length === 0) {
10374
10437
  return 0;
10375
10438
  }
10376
- await session.sendAndWait("DOM.enable");
10439
+ await session2.sendAndWait("DOM.enable");
10377
10440
  const fn = {
10378
10441
  code: options.text ? "function(pos, value) { this.insertAdjacentText(pos, value); }" : "function(pos, html) { this.insertAdjacentHTML(pos, html); }",
10379
10442
  args: [{ value: options.position ?? "beforeend" }, { value: options.html }]
10380
10443
  };
10381
10444
  for (const nodeId of options.nodeIds) {
10382
- await callFunctionOnNode(session, { nodeId }, fn);
10445
+ await callFunctionOnNode(session2, { nodeId }, fn);
10383
10446
  }
10384
10447
  return options.nodeIds.length;
10385
10448
  };
10386
- var setFileOnResolvedNodes = async (session, nodeIds, files) => {
10449
+ var setFileOnResolvedNodes = async (session2, nodeIds, files) => {
10387
10450
  for (const nodeId of nodeIds) {
10388
- await session.sendAndWait("DOM.setFileInputFiles", { files, nodeId });
10451
+ await session2.sendAndWait("DOM.setFileInputFiles", { files, nodeId });
10389
10452
  }
10390
10453
  return nodeIds.length;
10391
10454
  };
@@ -10502,27 +10565,27 @@ var route28 = defineJsonRoute({
10502
10565
  });
10503
10566
 
10504
10567
  // ../argus-watcher/dist/cdp/mouse.js
10505
- var resolveDomSelectorMatches = async (session, selector, all, text) => {
10506
- return resolveSelectorTargets(session, { selector, all, text });
10568
+ var resolveDomSelectorMatches = async (session2, selector, all, text) => {
10569
+ return resolveSelectorTargets(session2, { selector, all, text });
10507
10570
  };
10508
- var hoverDomNodes = async (session, handles) => {
10571
+ var hoverDomNodes = async (session2, handles) => {
10509
10572
  if (handles.length === 0) {
10510
10573
  return;
10511
10574
  }
10512
10575
  for (const handle of handles) {
10513
- await scrollIntoView(session, handle);
10514
- const point = await resolveNodePoint(session, handle);
10515
- await dispatchMouseEvent(session, { type: "mouseMoved", x: point.x, y: point.y });
10576
+ await scrollIntoView(session2, handle);
10577
+ const point = await resolveNodePoint(session2, handle);
10578
+ await dispatchMouseEvent(session2, { type: "mouseMoved", x: point.x, y: point.y });
10516
10579
  }
10517
10580
  };
10518
10581
  var BUTTON_MASK = { left: 1, middle: 4, right: 2 };
10519
- var clickAtPoint = async (session, x, y, button = "left") => {
10582
+ var clickAtPoint = async (session2, x, y, button = "left") => {
10520
10583
  const mask = BUTTON_MASK[button] ?? 1;
10521
- await dispatchMouseEvent(session, { type: "mouseMoved", x, y });
10522
- await dispatchMouseEvent(session, { type: "mousePressed", x, y, button, buttons: mask, clickCount: 1 });
10523
- await dispatchMouseEvent(session, { type: "mouseReleased", x, y, button, buttons: 0, clickCount: 1 });
10584
+ await dispatchMouseEvent(session2, { type: "mouseMoved", x, y });
10585
+ await dispatchMouseEvent(session2, { type: "mousePressed", x, y, button, buttons: mask, clickCount: 1 });
10586
+ await dispatchMouseEvent(session2, { type: "mouseReleased", x, y, button, buttons: 0, clickCount: 1 });
10524
10587
  };
10525
- var dragAtPoints = async (session, start, end, options = {}) => {
10588
+ var dragAtPoints = async (session2, start, end, options = {}) => {
10526
10589
  const button = options.button ?? "left";
10527
10590
  const mask = BUTTON_MASK[button] ?? 1;
10528
10591
  const steps = Math.max(1, Math.floor(options.steps ?? 12));
@@ -10530,35 +10593,35 @@ var dragAtPoints = async (session, start, end, options = {}) => {
10530
10593
  const stepDelayMs = durationMs / steps;
10531
10594
  let latest = start;
10532
10595
  let pressed = false;
10533
- await dispatchMouseEvent(session, { type: "mouseMoved", x: start.x, y: start.y });
10596
+ await dispatchMouseEvent(session2, { type: "mouseMoved", x: start.x, y: start.y });
10534
10597
  try {
10535
- await dispatchMouseEvent(session, { type: "mousePressed", x: start.x, y: start.y, button, buttons: mask, clickCount: 1 });
10598
+ await dispatchMouseEvent(session2, { type: "mousePressed", x: start.x, y: start.y, button, buttons: mask, clickCount: 1 });
10536
10599
  pressed = true;
10537
10600
  for (let i = 1;i <= steps; i++) {
10538
10601
  if (stepDelayMs > 0) {
10539
10602
  await delay(stepDelayMs);
10540
10603
  }
10541
10604
  latest = interpolatePoint(start, end, i / steps);
10542
- await dispatchMouseEvent(session, { type: "mouseMoved", x: latest.x, y: latest.y, button, buttons: mask, clickCount: 1 });
10605
+ await dispatchMouseEvent(session2, { type: "mouseMoved", x: latest.x, y: latest.y, button, buttons: mask, clickCount: 1 });
10543
10606
  }
10544
- await dispatchMouseEvent(session, { type: "mouseReleased", x: end.x, y: end.y, button, buttons: 0, clickCount: 1 });
10607
+ await dispatchMouseEvent(session2, { type: "mouseReleased", x: end.x, y: end.y, button, buttons: 0, clickCount: 1 });
10545
10608
  pressed = false;
10546
10609
  } finally {
10547
10610
  if (pressed) {
10548
- await dispatchMouseEvent(session, { type: "mouseReleased", x: latest.x, y: latest.y, button, buttons: 0, clickCount: 1 }).catch(() => {
10611
+ await dispatchMouseEvent(session2, { type: "mouseReleased", x: latest.x, y: latest.y, button, buttons: 0, clickCount: 1 }).catch(() => {
10549
10612
  return;
10550
10613
  });
10551
10614
  }
10552
10615
  }
10553
10616
  };
10554
- var dragDomNodes = async (session, handles, destination, options = {}) => {
10617
+ var dragDomNodes = async (session2, handles, destination, options = {}) => {
10555
10618
  if (handles.length === 0) {
10556
10619
  return;
10557
10620
  }
10558
10621
  for (const handle of handles) {
10559
- await scrollIntoView(session, handle);
10560
- const start = await resolveNodePoint(session, handle, options.offset);
10561
- await dragAtPoints(session, start, resolveDragEndPoint(start, destination), options);
10622
+ await scrollIntoView(session2, handle);
10623
+ const start = await resolveNodePoint(session2, handle, options.offset);
10624
+ await dragAtPoints(session2, start, resolveDragEndPoint(start, destination), options);
10562
10625
  }
10563
10626
  };
10564
10627
  var resolveDragEndPoint = (start, destination) => {
@@ -10570,67 +10633,67 @@ var resolveDragEndPoint = (start, destination) => {
10570
10633
  y: start.y + destination.delta.y
10571
10634
  };
10572
10635
  };
10573
- var clickDomNodes = async (session, handles, button = "left") => {
10636
+ var clickDomNodes = async (session2, handles, button = "left") => {
10574
10637
  if (handles.length === 0) {
10575
10638
  return;
10576
10639
  }
10577
10640
  const mask = BUTTON_MASK[button] ?? 1;
10578
10641
  for (const handle of handles) {
10579
- await scrollIntoView(session, handle);
10580
- const point = await resolveNodePoint(session, handle);
10581
- await dispatchMouseEvent(session, { type: "mouseMoved", x: point.x, y: point.y });
10582
- await dispatchMouseEvent(session, { type: "mousePressed", x: point.x, y: point.y, button, buttons: mask, clickCount: 1 });
10583
- await dispatchMouseEvent(session, { type: "mouseReleased", x: point.x, y: point.y, button, buttons: 0, clickCount: 1 });
10642
+ await scrollIntoView(session2, handle);
10643
+ const point = await resolveNodePoint(session2, handle);
10644
+ await dispatchMouseEvent(session2, { type: "mouseMoved", x: point.x, y: point.y });
10645
+ await dispatchMouseEvent(session2, { type: "mousePressed", x: point.x, y: point.y, button, buttons: mask, clickCount: 1 });
10646
+ await dispatchMouseEvent(session2, { type: "mouseReleased", x: point.x, y: point.y, button, buttons: 0, clickCount: 1 });
10584
10647
  }
10585
10648
  };
10586
- var focusDomNodes = async (session, handles) => {
10649
+ var focusDomNodes = async (session2, handles) => {
10587
10650
  if (handles.length === 0) {
10588
10651
  return;
10589
10652
  }
10590
10653
  for (const handle of handles) {
10591
- await scrollIntoView(session, handle);
10592
- await session.sendAndWait("DOM.focus", toDomNodeDescriptor(handle));
10654
+ await scrollIntoView(session2, handle);
10655
+ await session2.sendAndWait("DOM.focus", toDomNodeDescriptor(handle));
10593
10656
  }
10594
10657
  };
10595
- var scrollIntoView = async (session, handle) => {
10658
+ var scrollIntoView = async (session2, handle) => {
10596
10659
  const descriptor = toDomNodeDescriptor(handle);
10597
10660
  try {
10598
- await session.sendAndWait("DOM.scrollIntoViewIfNeeded", descriptor);
10661
+ await session2.sendAndWait("DOM.scrollIntoViewIfNeeded", descriptor);
10599
10662
  return;
10600
10663
  } catch {}
10601
- await callFunctionOnNode(session, descriptor, { code: 'function() { this.scrollIntoView({ block: "center", inline: "center" }); }' }, { onUnresolved: () => createNotInteractableError("Unable to resolve node for scrolling") });
10664
+ await callFunctionOnNode(session2, descriptor, { code: 'function() { this.scrollIntoView({ block: "center", inline: "center" }); }' }, { onUnresolved: () => createNotInteractableError("Unable to resolve node for scrolling") });
10602
10665
  };
10603
- var scrollDomNodes = async (session, handles, mode) => {
10666
+ var scrollDomNodes = async (session2, handles, mode) => {
10604
10667
  if (handles.length === 0) {
10605
- return getViewportScroll(session);
10668
+ return getViewportScroll(session2);
10606
10669
  }
10607
10670
  for (const handle of handles) {
10608
10671
  if (mode.to || mode.by) {
10609
- await scrollElementContainer(session, handle, mode);
10672
+ await scrollElementContainer(session2, handle, mode);
10610
10673
  } else {
10611
- await scrollIntoView(session, handle);
10674
+ await scrollIntoView(session2, handle);
10612
10675
  }
10613
10676
  }
10614
- return getViewportScroll(session);
10677
+ return getViewportScroll(session2);
10615
10678
  };
10616
- var scrollViewport = async (session, mode) => {
10679
+ var scrollViewport = async (session2, mode) => {
10617
10680
  const fn = mode.to ? `window.scrollTo(${mode.to.x}, ${mode.to.y})` : `window.scrollBy(${mode.by.x}, ${mode.by.y})`;
10618
- await evaluateInPage(session, fn);
10619
- return getViewportScroll(session);
10681
+ await evaluateInPage(session2, fn);
10682
+ return getViewportScroll(session2);
10620
10683
  };
10621
- var scrollElementContainer = async (session, handle, mode) => {
10684
+ var scrollElementContainer = async (session2, handle, mode) => {
10622
10685
  const fn = mode.to ? `function() { this.scrollTo(${mode.to.x}, ${mode.to.y}); }` : `function() { this.scrollBy(${mode.by.x}, ${mode.by.y}); }`;
10623
- await callFunctionOnNode(session, toDomNodeDescriptor(handle), { code: fn }, {
10686
+ await callFunctionOnNode(session2, toDomNodeDescriptor(handle), { code: fn }, {
10624
10687
  onUnresolved: () => createNotInteractableError("Unable to resolve node for scrolling")
10625
10688
  });
10626
10689
  };
10627
- var getViewportScroll = async (session) => {
10628
- const serialized = await evaluateInPage(session, "JSON.stringify({scrollX:window.scrollX,scrollY:window.scrollY})");
10690
+ var getViewportScroll = async (session2) => {
10691
+ const serialized = await evaluateInPage(session2, "JSON.stringify({scrollX:window.scrollX,scrollY:window.scrollY})");
10629
10692
  const parsed = serialized ? JSON.parse(serialized) : { scrollX: 0, scrollY: 0 };
10630
10693
  return { scrollX: parsed.scrollX, scrollY: parsed.scrollY };
10631
10694
  };
10632
- var resolveNodePoint = async (session, handle, offset) => {
10633
- const { x, y, w, h } = await resolveNodeRect(session, handle);
10695
+ var resolveNodePoint = async (session2, handle, offset) => {
10696
+ const { x, y, w, h } = await resolveNodeRect(session2, handle);
10634
10697
  if (w <= 0 || h <= 0) {
10635
10698
  throw createNotInteractableError("Element has zero area");
10636
10699
  }
@@ -10639,9 +10702,9 @@ var resolveNodePoint = async (session, handle, offset) => {
10639
10702
  }
10640
10703
  return { x: x + w / 2, y: y + h / 2 };
10641
10704
  };
10642
- var resolveNodeRect = async (session, handle) => {
10705
+ var resolveNodeRect = async (session2, handle) => {
10643
10706
  const descriptor = toDomNodeDescriptor(handle);
10644
- const boxModel = await session.sendAndWait("DOM.getBoxModel", descriptor).catch(() => null);
10707
+ const boxModel = await session2.sendAndWait("DOM.getBoxModel", descriptor).catch(() => null);
10645
10708
  const quad = boxModel?.model?.border ?? boxModel?.model?.content;
10646
10709
  if (quad && quad.length >= 8) {
10647
10710
  const xs = [quad[0], quad[2], quad[4], quad[6]];
@@ -10652,7 +10715,7 @@ var resolveNodeRect = async (session, handle) => {
10652
10715
  const maxY = Math.max(...ys);
10653
10716
  return { x: minX, y: minY, w: maxX - minX, h: maxY - minY };
10654
10717
  }
10655
- const rect = await callFunctionOnNode(session, descriptor, {
10718
+ const rect = await callFunctionOnNode(session2, descriptor, {
10656
10719
  code: "function(){var r=this.getBoundingClientRect();return{x:r.x,y:r.y,w:r.width,h:r.height}}"
10657
10720
  });
10658
10721
  if (!rect || !Number.isFinite(rect.x) || !Number.isFinite(rect.y)) {
@@ -10660,8 +10723,8 @@ var resolveNodeRect = async (session, handle) => {
10660
10723
  }
10661
10724
  return rect;
10662
10725
  };
10663
- var emulateScroll = async (session, x, y, delta) => {
10664
- await session.sendAndWait("Input.dispatchMouseEvent", {
10726
+ var emulateScroll = async (session2, x, y, delta) => {
10727
+ await session2.sendAndWait("Input.dispatchMouseEvent", {
10665
10728
  type: "mouseWheel",
10666
10729
  x,
10667
10730
  y,
@@ -10669,18 +10732,18 @@ var emulateScroll = async (session, x, y, delta) => {
10669
10732
  deltaY: delta.y
10670
10733
  });
10671
10734
  };
10672
- var emulateScrollOnNodes = async (session, handles, delta) => {
10735
+ var emulateScrollOnNodes = async (session2, handles, delta) => {
10673
10736
  if (handles.length === 0) {
10674
10737
  return;
10675
10738
  }
10676
10739
  for (const handle of handles) {
10677
- await scrollIntoView(session, handle);
10678
- const point = await resolveNodePoint(session, handle);
10679
- await emulateScroll(session, point.x, point.y, delta);
10740
+ await scrollIntoView(session2, handle);
10741
+ const point = await resolveNodePoint(session2, handle);
10742
+ await emulateScroll(session2, point.x, point.y, delta);
10680
10743
  }
10681
10744
  };
10682
- var dispatchMouseEvent = async (session, options) => {
10683
- await session.sendAndWait("Input.dispatchMouseEvent", {
10745
+ var dispatchMouseEvent = async (session2, options) => {
10746
+ await session2.sendAndWait("Input.dispatchMouseEvent", {
10684
10747
  type: options.type,
10685
10748
  x: options.x,
10686
10749
  y: options.y,
@@ -10963,12 +11026,12 @@ var resolveEventText = (key, def) => {
10963
11026
  };
10964
11027
  var isSingleLetter = (value) => /^[a-z]$/i.test(value);
10965
11028
  var isShift = (modifiers) => (modifiers & MODIFIER_BITS.shift) !== 0;
10966
- var dispatchKeydown = async (session, options) => {
11029
+ var dispatchKeydown = async (session2, options) => {
10967
11030
  const { selector } = options;
10968
11031
  const event = resolveKeyboardEvent(options);
10969
11032
  let focused = false;
10970
11033
  if (selector) {
10971
- const { allNodeIds, nodeIds } = await resolveDomSelectorMatches(session, selector, false);
11034
+ const { allNodeIds, nodeIds } = await resolveDomSelectorMatches(session2, selector, false);
10972
11035
  if (allNodeIds.length === 0) {
10973
11036
  throw new Error(`No element found for selector: ${selector}`);
10974
11037
  }
@@ -10976,7 +11039,7 @@ var dispatchKeydown = async (session, options) => {
10976
11039
  throw codedError("multiple_matches", `Selector matched ${allNodeIds.length} elements; keydown requires exactly one target`);
10977
11040
  }
10978
11041
  const nodeId = nodeIds[0];
10979
- await session.sendAndWait("DOM.focus", { nodeId });
11042
+ await session2.sendAndWait("DOM.focus", { nodeId });
10980
11043
  focused = true;
10981
11044
  }
10982
11045
  const isPrintable = event.text != null && event.text !== "\r";
@@ -10988,12 +11051,12 @@ var dispatchKeydown = async (session, options) => {
10988
11051
  modifiers: event.modifiers
10989
11052
  };
10990
11053
  if (isPrintable) {
10991
- await session.sendAndWait("Input.dispatchKeyEvent", { ...baseParams, type: "keyDown", text: event.text });
10992
- await session.sendAndWait("Input.dispatchKeyEvent", { ...baseParams, type: "char", text: event.text });
10993
- await session.sendAndWait("Input.dispatchKeyEvent", { ...baseParams, type: "keyUp" });
11054
+ await session2.sendAndWait("Input.dispatchKeyEvent", { ...baseParams, type: "keyDown", text: event.text });
11055
+ await session2.sendAndWait("Input.dispatchKeyEvent", { ...baseParams, type: "char", text: event.text });
11056
+ await session2.sendAndWait("Input.dispatchKeyEvent", { ...baseParams, type: "keyUp" });
10994
11057
  } else {
10995
- await session.sendAndWait("Input.dispatchKeyEvent", { ...baseParams, type: "rawKeyDown", text: event.text });
10996
- await session.sendAndWait("Input.dispatchKeyEvent", { ...baseParams, type: "keyUp" });
11058
+ await session2.sendAndWait("Input.dispatchKeyEvent", { ...baseParams, type: "rawKeyDown", text: event.text });
11059
+ await session2.sendAndWait("Input.dispatchKeyEvent", { ...baseParams, type: "keyUp" });
10997
11060
  }
10998
11061
  return { key: event.key, code: event.code, modifiers: event.modifiers, focused, event };
10999
11062
  };
@@ -11195,8 +11258,8 @@ var route39 = defineJsonRoute({
11195
11258
  return { ok: true, matches: allNodeIds.length, scrolled: nodeIds.length };
11196
11259
  }
11197
11260
  });
11198
- var getViewportSize = async (session) => {
11199
- const serialized = await evaluateInPage(session, "JSON.stringify({width:window.innerWidth,height:window.innerHeight})");
11261
+ var getViewportSize = async (session2) => {
11262
+ const serialized = await evaluateInPage(session2, "JSON.stringify({width:window.innerWidth,height:window.innerHeight})");
11200
11263
  const parsed = serialized ? JSON.parse(serialized) : { width: 800, height: 600 };
11201
11264
  return { width: parsed.width, height: parsed.height };
11202
11265
  };
@@ -11242,11 +11305,11 @@ var route42 = defineJsonRoute({
11242
11305
  bodySchema: emulationRequestSchema,
11243
11306
  endpoint: "emulation",
11244
11307
  handle: async ({ ctx, body: payload }) => {
11245
- const session = ctx.cdpSession.isAttached() ? ctx.cdpSession : null;
11308
+ const session2 = ctx.cdpSession.isAttached() ? ctx.cdpSession : null;
11246
11309
  if (payload.action === "clear") {
11247
- return ctx.emulationController.clearDesired(session);
11310
+ return ctx.emulationController.clearDesired(session2);
11248
11311
  }
11249
- return ctx.emulationController.setDesired(payload.state, session);
11312
+ return ctx.emulationController.setDesired(payload.state, session2);
11250
11313
  }
11251
11314
  });
11252
11315
 
@@ -11265,11 +11328,11 @@ var route44 = defineJsonRoute({
11265
11328
  bodySchema: throttleRequestSchema,
11266
11329
  endpoint: "throttle",
11267
11330
  handle: ({ ctx, body: payload }) => {
11268
- const session = ctx.cdpSession.isAttached() ? ctx.cdpSession : null;
11331
+ const session2 = ctx.cdpSession.isAttached() ? ctx.cdpSession : null;
11269
11332
  if (payload.action === "clear") {
11270
- return ctx.throttleController.clearDesired(session);
11333
+ return ctx.throttleController.clearDesired(session2);
11271
11334
  }
11272
- return ctx.throttleController.setDesired(payload.rate, session);
11335
+ return ctx.throttleController.setDesired(payload.rate, session2);
11273
11336
  }
11274
11337
  });
11275
11338
 
@@ -11319,9 +11382,9 @@ var route47 = defineJsonRoute({
11319
11382
  endpoint: "visibility",
11320
11383
  handle: async ({ ctx, body: payload }) => {
11321
11384
  const lock = payload.action === "show" ? "shown" : "default";
11322
- const session = ctx.pageCdpSession;
11323
- const attached = session.isAttached();
11324
- await ctx.visibilityController.setLock(attached ? session : null, lock);
11385
+ const session2 = ctx.pageCdpSession;
11386
+ const attached = session2.isAttached();
11387
+ await ctx.visibilityController.setLock(attached ? session2 : null, lock);
11325
11388
  return { ok: true, attached, state: lock };
11326
11389
  }
11327
11390
  });
@@ -11331,8 +11394,8 @@ var storageAccessors = {
11331
11394
  local: "localStorage",
11332
11395
  session: "sessionStorage"
11333
11396
  };
11334
- var executeStorage = async (session, area, request) => {
11335
- return await evaluateInPage(session, buildStorageExpression(area, request), { timeoutMs: 5000 });
11397
+ var executeStorage = async (session2, area, request) => {
11398
+ return await evaluateInPage(session2, buildStorageExpression(area, request), { timeoutMs: 5000 });
11336
11399
  };
11337
11400
  var buildStorageExpression = (area, request) => {
11338
11401
  return `(() => {
@@ -11676,8 +11739,8 @@ var createInjectOnAttach = (inject, record2) => {
11676
11739
  if (!inject?.script) {
11677
11740
  return async () => {};
11678
11741
  }
11679
- return async (session, target) => {
11680
- if (!session.isAttached()) {
11742
+ return async (session2, target) => {
11743
+ if (!session2.isAttached()) {
11681
11744
  return;
11682
11745
  }
11683
11746
  const trimmedScript = inject.script.trim();
@@ -11699,8 +11762,8 @@ var createInjectOnAttach = (inject, record2) => {
11699
11762
  }
11700
11763
  } : null;
11701
11764
  const expression = buildInjectExpression(trimmedScript, argusPayload);
11702
- await runInjectStep("register", record2.id, () => session.sendAndWait("Page.addScriptToEvaluateOnNewDocument", { source: expression }));
11703
- await runInjectStep("run", record2.id, () => session.sendAndWait("Runtime.evaluate", { expression, silent: true }));
11765
+ await runInjectStep("register", record2.id, () => session2.sendAndWait("Page.addScriptToEvaluateOnNewDocument", { source: expression }));
11766
+ await runInjectStep("run", record2.id, () => session2.sendAndWait("Runtime.evaluate", { expression, silent: true }));
11704
11767
  };
11705
11768
  };
11706
11769
  var runInjectStep = async (step, watcherId, action) => {
@@ -12150,11 +12213,11 @@ var createPageIndicatorController = (options) => {
12150
12213
  let currentSession = null;
12151
12214
  let currentInfo = null;
12152
12215
  let currentState = { recording: false };
12153
- const onAttach = (session, _target, info) => {
12216
+ const onAttach = (session2, _target, info) => {
12154
12217
  stop();
12155
- currentSession = session;
12218
+ currentSession = session2;
12156
12219
  currentInfo = info;
12157
- installIndicator(session, {
12220
+ installIndicator(session2, {
12158
12221
  info,
12159
12222
  position,
12160
12223
  ttlMs,
@@ -12172,9 +12235,9 @@ var createPageIndicatorController = (options) => {
12172
12235
  sendHeartbeat(currentSession, currentInfo, currentState);
12173
12236
  }, heartbeatMs);
12174
12237
  };
12175
- const onNavigation = (session, info) => {
12238
+ const onNavigation = (session2, info) => {
12176
12239
  currentInfo = info;
12177
- installIndicator(session, {
12240
+ installIndicator(session2, {
12178
12241
  info,
12179
12242
  position,
12180
12243
  ttlMs,
@@ -12229,7 +12292,7 @@ var createPageIndicatorController = (options) => {
12229
12292
  };
12230
12293
  return { onAttach, onNavigation, setRecording, reinstall, onDetach, stop };
12231
12294
  };
12232
- var installIndicator = async (session, params) => {
12295
+ var installIndicator = async (session2, params) => {
12233
12296
  const { info, position, ttlMs, bgColor, hoverBgColor, iconColor, margin, size, state: state2 } = params;
12234
12297
  const expression = buildInstallExpression({
12235
12298
  info,
@@ -12242,15 +12305,15 @@ var installIndicator = async (session, params) => {
12242
12305
  size,
12243
12306
  state: state2
12244
12307
  });
12245
- await tryEvaluateInPage(session, expression);
12308
+ await tryEvaluateInPage(session2, expression);
12246
12309
  };
12247
- var sendHeartbeat = async (session, info, state2) => {
12310
+ var sendHeartbeat = async (session2, info, state2) => {
12248
12311
  const expression = buildHeartbeatExpression(info, state2);
12249
- await tryEvaluateInPage(session, expression);
12312
+ await tryEvaluateInPage(session2, expression);
12250
12313
  };
12251
- var removeIndicator = async (session) => {
12314
+ var removeIndicator = async (session2) => {
12252
12315
  const expression = buildRemoveExpression();
12253
- await tryEvaluateInPage(session, expression);
12316
+ await tryEvaluateInPage(session2, expression);
12254
12317
  };
12255
12318
 
12256
12319
  // ../argus-watcher/dist/runtime/watcherIndicator.js
@@ -12268,23 +12331,23 @@ var createIndicatorBinding = (input) => {
12268
12331
  attachedAt: attachedAt ?? Date.now()
12269
12332
  });
12270
12333
  return {
12271
- onNavigation: (session, info) => {
12334
+ onNavigation: (session2, info) => {
12272
12335
  if (!controller) {
12273
12336
  return;
12274
12337
  }
12275
12338
  const status2 = input.getCdpStatus();
12276
12339
  const target = status2.attached ? { title: status2.target?.title ?? null, url: status2.target?.url ?? info.url } : { title: null, url: info.url };
12277
- controller.onNavigation(session, buildInfo(target));
12340
+ controller.onNavigation(session2, buildInfo(target));
12278
12341
  },
12279
12342
  onLoad: () => {
12280
12343
  controller?.reinstall();
12281
12344
  },
12282
- onAttach: (session, target) => {
12345
+ onAttach: (session2, target) => {
12283
12346
  if (!controller) {
12284
12347
  return;
12285
12348
  }
12286
12349
  attachedAt = Date.now();
12287
- controller.onAttach(session, {
12350
+ controller.onAttach(session2, {
12288
12351
  id: target.id,
12289
12352
  title: target.title,
12290
12353
  url: target.url,
@@ -13530,7 +13593,7 @@ var nextId = 1;
13530
13593
  var createCdpSessionHandle = () => {
13531
13594
  let connection = null;
13532
13595
  const handlers = new Map;
13533
- const session = {
13596
+ const session2 = {
13534
13597
  isAttached: () => Boolean(connection),
13535
13598
  sendAndWait: async (method, params, options) => {
13536
13599
  if (!connection) {
@@ -13633,7 +13696,7 @@ var createCdpSessionHandle = () => {
13633
13696
  }
13634
13697
  connection = null;
13635
13698
  };
13636
- return { session, attach, detach };
13699
+ return { session: session2, attach, detach };
13637
13700
  };
13638
13701
  var createCdpNotAttachedError = () => createNotAttachedError("Watcher not attached to a CDP target");
13639
13702
  var parseMessage = (data) => {
@@ -13686,30 +13749,30 @@ var openCdpConnection = async (wsUrl, connectTimeoutMs = 5000) => {
13686
13749
  };
13687
13750
 
13688
13751
  // ../argus-watcher/dist/cdp/emulation.js
13689
- var applyEmulation = async (session, state2, baseline) => {
13752
+ var applyEmulation = async (session2, state2, baseline) => {
13690
13753
  if (state2.viewport) {
13691
- await session.sendAndWait("Emulation.setDeviceMetricsOverride", {
13754
+ await session2.sendAndWait("Emulation.setDeviceMetricsOverride", {
13692
13755
  width: state2.viewport.width,
13693
13756
  height: state2.viewport.height,
13694
13757
  deviceScaleFactor: state2.viewport.deviceScaleFactor,
13695
13758
  mobile: state2.viewport.mobile
13696
13759
  });
13697
13760
  } else {
13698
- await session.sendAndWait("Emulation.clearDeviceMetricsOverride");
13761
+ await session2.sendAndWait("Emulation.clearDeviceMetricsOverride");
13699
13762
  }
13700
13763
  const touchEnabled = state2.touch?.enabled ?? false;
13701
- await session.sendAndWait("Emulation.setTouchEmulationEnabled", { enabled: touchEnabled });
13764
+ await session2.sendAndWait("Emulation.setTouchEmulationEnabled", { enabled: touchEnabled });
13702
13765
  if (state2.userAgent?.value != null) {
13703
- await session.sendAndWait("Emulation.setUserAgentOverride", { userAgent: state2.userAgent.value });
13766
+ await session2.sendAndWait("Emulation.setUserAgentOverride", { userAgent: state2.userAgent.value });
13704
13767
  } else if (baseline.userAgent) {
13705
- await session.sendAndWait("Emulation.setUserAgentOverride", { userAgent: baseline.userAgent });
13768
+ await session2.sendAndWait("Emulation.setUserAgentOverride", { userAgent: baseline.userAgent });
13706
13769
  }
13707
13770
  };
13708
- var clearEmulation = async (session, baseline) => {
13709
- await session.sendAndWait("Emulation.clearDeviceMetricsOverride");
13710
- await session.sendAndWait("Emulation.setTouchEmulationEnabled", { enabled: false });
13771
+ var clearEmulation = async (session2, baseline) => {
13772
+ await session2.sendAndWait("Emulation.clearDeviceMetricsOverride");
13773
+ await session2.sendAndWait("Emulation.setTouchEmulationEnabled", { enabled: false });
13711
13774
  if (baseline.userAgent) {
13712
- await session.sendAndWait("Emulation.setUserAgentOverride", { userAgent: baseline.userAgent });
13775
+ await session2.sendAndWait("Emulation.setUserAgentOverride", { userAgent: baseline.userAgent });
13713
13776
  }
13714
13777
  };
13715
13778
 
@@ -13719,7 +13782,7 @@ var createStickyController = (options) => {
13719
13782
  let applied = false;
13720
13783
  let lastError = null;
13721
13784
  const getState = () => ({ applied, state: desired, lastError });
13722
- const run = async (session, action, appliedOnSuccess) => {
13785
+ const run = async (session2, action, appliedOnSuccess) => {
13723
13786
  try {
13724
13787
  await action();
13725
13788
  applied = appliedOnSuccess;
@@ -13737,30 +13800,30 @@ var createStickyController = (options) => {
13737
13800
  };
13738
13801
  return {
13739
13802
  getState,
13740
- setDesired: async (state2, session) => {
13803
+ setDesired: async (state2, session2) => {
13741
13804
  desired = state2;
13742
13805
  lastError = null;
13743
- if (!session?.isAttached()) {
13806
+ if (!session2?.isAttached()) {
13744
13807
  return detached();
13745
13808
  }
13746
- return await run(session, () => options.apply(session, state2), true);
13809
+ return await run(session2, () => options.apply(session2, state2), true);
13747
13810
  },
13748
- clearDesired: async (session) => {
13811
+ clearDesired: async (session2) => {
13749
13812
  desired = null;
13750
13813
  lastError = null;
13751
- if (!session?.isAttached()) {
13814
+ if (!session2?.isAttached()) {
13752
13815
  return detached();
13753
13816
  }
13754
- return await run(session, () => options.clear(session), false);
13817
+ return await run(session2, () => options.clear(session2), false);
13755
13818
  },
13756
- onAttach: async (session) => {
13757
- await options.onBeforeReapply?.(session);
13819
+ onAttach: async (session2) => {
13820
+ await options.onBeforeReapply?.(session2);
13758
13821
  if (!desired) {
13759
13822
  applied = false;
13760
13823
  return;
13761
13824
  }
13762
13825
  try {
13763
- await options.apply(session, desired);
13826
+ await options.apply(session2, desired);
13764
13827
  applied = true;
13765
13828
  lastError = null;
13766
13829
  } catch (error) {
@@ -13778,10 +13841,10 @@ var createEmulationController = () => {
13778
13841
  const getBaseline = () => ({ userAgent: baselineUserAgent });
13779
13842
  const sticky = createStickyController({
13780
13843
  label: "Emulation",
13781
- apply: (session, state2) => applyEmulation(session, state2, getBaseline()),
13782
- clear: (session) => clearEmulation(session, getBaseline()),
13783
- onBeforeReapply: async (session) => {
13784
- const value = await evaluateInPage(session, "navigator.userAgent").catch(() => null);
13844
+ apply: (session2, state2) => applyEmulation(session2, state2, getBaseline()),
13845
+ clear: (session2) => clearEmulation(session2, getBaseline()),
13846
+ onBeforeReapply: async (session2) => {
13847
+ const value = await evaluateInPage(session2, "navigator.userAgent").catch(() => null);
13785
13848
  baselineUserAgent = typeof value === "string" ? value : null;
13786
13849
  }
13787
13850
  });
@@ -13790,12 +13853,12 @@ var createEmulationController = () => {
13790
13853
  const { applied, state: state2, lastError } = sticky.getState();
13791
13854
  return { ok: true, attached: ctx.attached, applied, state: state2, baseline: getBaseline(), lastError };
13792
13855
  },
13793
- setDesired: async (state2, session) => {
13794
- const { attached, applied, state: next, lastError } = await sticky.setDesired(state2, session);
13856
+ setDesired: async (state2, session2) => {
13857
+ const { attached, applied, state: next, lastError } = await sticky.setDesired(state2, session2);
13795
13858
  return { ok: true, attached, applied, state: next, ...lastError ? { error: lastError } : {} };
13796
13859
  },
13797
- clearDesired: async (session) => {
13798
- const { attached, applied, lastError } = await sticky.clearDesired(session);
13860
+ clearDesired: async (session2) => {
13861
+ const { attached, applied, lastError } = await sticky.clearDesired(session2);
13799
13862
  return { ok: true, attached, applied, state: null, ...lastError ? { error: lastError } : {} };
13800
13863
  },
13801
13864
  onAttach: sticky.onAttach
@@ -13803,31 +13866,31 @@ var createEmulationController = () => {
13803
13866
  };
13804
13867
 
13805
13868
  // ../argus-watcher/dist/cdp/throttle.js
13806
- var applyThrottle = async (session, rate) => {
13807
- await session.sendAndWait("Emulation.setCPUThrottlingRate", { rate });
13869
+ var applyThrottle = async (session2, rate) => {
13870
+ await session2.sendAndWait("Emulation.setCPUThrottlingRate", { rate });
13808
13871
  };
13809
- var clearThrottle = async (session) => {
13810
- await session.sendAndWait("Emulation.setCPUThrottlingRate", { rate: 1 });
13872
+ var clearThrottle = async (session2) => {
13873
+ await session2.sendAndWait("Emulation.setCPUThrottlingRate", { rate: 1 });
13811
13874
  };
13812
13875
 
13813
13876
  // ../argus-watcher/dist/throttle/ThrottleController.js
13814
13877
  var createThrottleController = () => {
13815
13878
  const sticky = createStickyController({
13816
13879
  label: "Throttle",
13817
- apply: (session, state2) => applyThrottle(session, state2.rate),
13818
- clear: (session) => clearThrottle(session)
13880
+ apply: (session2, state2) => applyThrottle(session2, state2.rate),
13881
+ clear: (session2) => clearThrottle(session2)
13819
13882
  });
13820
13883
  return {
13821
13884
  getStatus: (ctx) => {
13822
13885
  const { applied, state: state2, lastError } = sticky.getState();
13823
13886
  return { ok: true, attached: ctx.attached, applied, state: state2, lastError };
13824
13887
  },
13825
- setDesired: async (rate, session) => {
13826
- const { attached, applied, state: state2, lastError } = await sticky.setDesired({ rate }, session);
13888
+ setDesired: async (rate, session2) => {
13889
+ const { attached, applied, state: state2, lastError } = await sticky.setDesired({ rate }, session2);
13827
13890
  return { ok: true, attached, applied, state: state2, ...lastError ? { error: lastError } : {} };
13828
13891
  },
13829
- clearDesired: async (session) => {
13830
- const { attached, applied, lastError } = await sticky.clearDesired(session);
13892
+ clearDesired: async (session2) => {
13893
+ const { attached, applied, lastError } = await sticky.clearDesired(session2);
13831
13894
  return { ok: true, attached, applied, state: null, ...lastError ? { error: lastError } : {} };
13832
13895
  },
13833
13896
  onAttach: sticky.onAttach
@@ -13896,8 +13959,8 @@ class NetMockInterception {
13896
13959
  if (reset) {
13897
13960
  this.enabledTargets.clear();
13898
13961
  }
13899
- const session = this.binding?.pageSession;
13900
- if (!session?.isAttached()) {
13962
+ const session2 = this.binding?.pageSession;
13963
+ if (!session2?.isAttached()) {
13901
13964
  this.enabledTargets.clear();
13902
13965
  return false;
13903
13966
  }
@@ -13936,12 +13999,12 @@ class NetMockInterception {
13936
13999
  return targets;
13937
14000
  }
13938
14001
  async sendCommand(target, method, params = {}) {
13939
- const session = this.binding?.pageSession;
13940
- if (!session?.isAttached()) {
14002
+ const session2 = this.binding?.pageSession;
14003
+ if (!session2?.isAttached()) {
13941
14004
  return false;
13942
14005
  }
13943
14006
  try {
13944
- await session.sendAndWait(method, params, target.sessionId ? { sessionId: target.sessionId } : undefined);
14007
+ await session2.sendAndWait(method, params, target.sessionId ? { sessionId: target.sessionId } : undefined);
13945
14008
  return true;
13946
14009
  } catch (error) {
13947
14010
  if (!isBenignInterceptionError(error)) {
@@ -14157,35 +14220,35 @@ var toPublicRule = (rule) => ({
14157
14220
  });
14158
14221
 
14159
14222
  // ../argus-watcher/dist/visibility/VisibilityController.js
14160
- var applyLock = async (session, lock) => {
14223
+ var applyLock = async (session2, lock) => {
14161
14224
  if (lock !== "shown") {
14162
- await session.sendAndWait("Emulation.setFocusEmulationEnabled", { enabled: false });
14225
+ await session2.sendAndWait("Emulation.setFocusEmulationEnabled", { enabled: false });
14163
14226
  return;
14164
14227
  }
14165
14228
  try {
14166
- await session.sendAndWait("Page.bringToFront");
14229
+ await session2.sendAndWait("Page.bringToFront");
14167
14230
  } catch {}
14168
- await session.sendAndWait("Emulation.setFocusEmulationEnabled", { enabled: true });
14231
+ await session2.sendAndWait("Emulation.setFocusEmulationEnabled", { enabled: true });
14169
14232
  };
14170
14233
  var createVisibilityController = () => {
14171
14234
  const sticky = createStickyController({
14172
14235
  label: "Visibility",
14173
14236
  apply: applyLock,
14174
- clear: (session) => applyLock(session, "default")
14237
+ clear: (session2) => applyLock(session2, "default")
14175
14238
  });
14176
14239
  return {
14177
14240
  getDesired: () => sticky.getState().state ?? "default",
14178
- setLock: async (session, lock) => {
14179
- const result = await sticky.setDesired(lock, session);
14241
+ setLock: async (session2, lock) => {
14242
+ const result = await sticky.setDesired(lock, session2);
14180
14243
  if (result.lastError) {
14181
14244
  throw new Error(result.lastError.message);
14182
14245
  }
14183
14246
  },
14184
- onAttach: async (session) => {
14247
+ onAttach: async (session2) => {
14185
14248
  if (sticky.getState().state !== "shown") {
14186
14249
  return;
14187
14250
  }
14188
- await sticky.onAttach(session);
14251
+ await sticky.onAttach(session2);
14189
14252
  }
14190
14253
  };
14191
14254
  };
@@ -14992,25 +15055,25 @@ var createTraceRecorder = (options) => {
14992
15055
  import fs7 from "node:fs/promises";
14993
15056
 
14994
15057
  // ../argus-watcher/dist/cdp/visualCapture.js
14995
- var createVisualCapturePlan = async (session, pageSession, request) => {
15058
+ var createVisualCapturePlan = async (session2, pageSession, request) => {
14996
15059
  const subject = resolveVisualCaptureSubject(request);
14997
- const targetContext = await session.getReadyTargetContext();
15060
+ const targetContext = await session2.getReadyTargetContext();
14998
15061
  if (targetContext?.kind === "frame" && pageSession) {
14999
15062
  return createFrameCapturePlan({
15000
- frameSession: session,
15063
+ frameSession: session2,
15001
15064
  pageSession,
15002
15065
  frameContext: targetContext,
15003
15066
  subject
15004
15067
  });
15005
15068
  }
15006
- const clip = await resolveSubjectClip(session, subject);
15069
+ const clip = await resolveSubjectClip(session2, subject);
15007
15070
  if (!clip) {
15008
- return { session };
15071
+ return { session: session2 };
15009
15072
  }
15010
15073
  return {
15011
- session,
15074
+ session: session2,
15012
15075
  clip,
15013
- viewport: await resolveViewportSize(session)
15076
+ viewport: await resolveViewportSize(session2)
15014
15077
  };
15015
15078
  };
15016
15079
  var createFrameCapturePlan = async (options) => {
@@ -15039,21 +15102,21 @@ var resolveFrameViewportClip = async (pageSession, frameId) => {
15039
15102
  }
15040
15103
  return resolveNodeClip(pageSession, owner);
15041
15104
  };
15042
- var resolveSelectorClip = async (session, selector) => {
15043
- const nodeId = await resolveFirstSelectorNodeId(session, selector);
15105
+ var resolveSelectorClip = async (session2, selector) => {
15106
+ const nodeId = await resolveFirstSelectorNodeId(session2, selector);
15044
15107
  if (!nodeId) {
15045
15108
  throw new Error(`No element found for selector: ${selector}`);
15046
15109
  }
15047
- return resolveNodeClip(session, { nodeId });
15110
+ return resolveNodeClip(session2, { nodeId });
15048
15111
  };
15049
- var resolveSubjectClip = async (session, subject) => {
15112
+ var resolveSubjectClip = async (session2, subject) => {
15050
15113
  switch (subject.kind) {
15051
15114
  case "viewport":
15052
15115
  return null;
15053
15116
  case "selector":
15054
- return resolveSelectorClip(session, subject.selector);
15117
+ return resolveSelectorClip(session2, subject.selector);
15055
15118
  case "clip":
15056
- return resolveViewportRectClip(session, subject.clip);
15119
+ return resolveViewportRectClip(session2, subject.clip);
15057
15120
  }
15058
15121
  };
15059
15122
  var resolveVisualCaptureSubject = (request) => {
@@ -15065,8 +15128,8 @@ var resolveVisualCaptureSubject = (request) => {
15065
15128
  }
15066
15129
  return { kind: "viewport" };
15067
15130
  };
15068
- var resolveViewportRectClip = async (session, clip) => {
15069
- const viewport = await resolveVisualViewport(session);
15131
+ var resolveViewportRectClip = async (session2, clip) => {
15132
+ const viewport = await resolveVisualViewport(session2);
15070
15133
  return {
15071
15134
  x: clip.x,
15072
15135
  y: clip.y,
@@ -15075,8 +15138,8 @@ var resolveViewportRectClip = async (session, clip) => {
15075
15138
  scale: viewport?.scale ?? 1
15076
15139
  };
15077
15140
  };
15078
- var resolveNodeClip = async (session, target) => {
15079
- const boxResult = await session.sendAndWait("DOM.getBoxModel", target.nodeId != null ? { nodeId: target.nodeId } : { backendNodeId: target.backendNodeId });
15141
+ var resolveNodeClip = async (session2, target) => {
15142
+ const boxResult = await session2.sendAndWait("DOM.getBoxModel", target.nodeId != null ? { nodeId: target.nodeId } : { backendNodeId: target.backendNodeId });
15080
15143
  const quad = boxResult.model?.content ?? boxResult.model?.border;
15081
15144
  if (!quad || quad.length < 8) {
15082
15145
  throw new Error("Unable to compute element box model");
@@ -15085,7 +15148,7 @@ var resolveNodeClip = async (session, target) => {
15085
15148
  if (rect.width <= 0 || rect.height <= 0) {
15086
15149
  throw new Error("Element has zero area");
15087
15150
  }
15088
- const viewport = await resolveVisualViewport(session);
15151
+ const viewport = await resolveVisualViewport(session2);
15089
15152
  const pageX = viewport?.pageX ?? 0;
15090
15153
  const pageY = viewport?.pageY ?? 0;
15091
15154
  const scale = viewport?.scale ?? 1;
@@ -15097,17 +15160,17 @@ var resolveNodeClip = async (session, target) => {
15097
15160
  scale
15098
15161
  };
15099
15162
  };
15100
- var resolveVisualViewport = async (session) => {
15101
- const metrics = await session.sendAndWait("Page.getLayoutMetrics");
15163
+ var resolveVisualViewport = async (session2) => {
15164
+ const metrics = await session2.sendAndWait("Page.getLayoutMetrics");
15102
15165
  const payload = metrics;
15103
15166
  return payload.cssVisualViewport ?? payload.visualViewport;
15104
15167
  };
15105
- var resolveViewportSize = async (session) => {
15106
- const viewport = await resolveVisualViewport(session);
15168
+ var resolveViewportSize = async (session2) => {
15169
+ const viewport = await resolveVisualViewport(session2);
15107
15170
  if (isPositiveFiniteNumber(viewport?.clientWidth) && isPositiveFiniteNumber(viewport?.clientHeight)) {
15108
15171
  return { width: viewport.clientWidth, height: viewport.clientHeight };
15109
15172
  }
15110
- const evaluated = await evaluateInPage(session, "({width: window.visualViewport?.width ?? window.innerWidth, height: window.visualViewport?.height ?? window.innerHeight})");
15173
+ const evaluated = await evaluateInPage(session2, "({width: window.visualViewport?.width ?? window.innerWidth, height: window.visualViewport?.height ?? window.innerHeight})");
15111
15174
  const width = evaluated?.width;
15112
15175
  const height = evaluated?.height;
15113
15176
  if (!isPositiveFiniteNumber(width) || !isPositiveFiniteNumber(height)) {
@@ -15161,11 +15224,11 @@ var createScreenshotter = (options) => {
15161
15224
  };
15162
15225
  return { capture };
15163
15226
  };
15164
- var captureScreenshot = async (session, options) => {
15227
+ var captureScreenshot = async (session2, options) => {
15165
15228
  let lastError;
15166
15229
  for (let attempt = 1;attempt <= SCREENSHOT_CDP_MAX_ATTEMPTS; attempt += 1) {
15167
15230
  try {
15168
- const payload = await session.sendAndWait("Page.captureScreenshot", {
15231
+ const payload = await session2.sendAndWait("Page.captureScreenshot", {
15169
15232
  format: options.format,
15170
15233
  clip: options.clip
15171
15234
  }, { timeoutMs: SCREENSHOT_CDP_TIMEOUT_MS });
@@ -15549,7 +15612,7 @@ var QUIET_PERIOD_MS = 100;
15549
15612
  var ENABLE_TIMEOUT_MS = 5000;
15550
15613
  var DEFAULT_READ_LIMIT = 2000;
15551
15614
  var MAX_GREP_MATCHES = 500;
15552
- var createRuntimeEditor = (session) => {
15615
+ var createRuntimeEditor = (session2) => {
15553
15616
  const scripts = new Map;
15554
15617
  const stylesheets = new Map;
15555
15618
  const sources = new Map;
@@ -15595,9 +15658,9 @@ var createRuntimeEditor = (session) => {
15595
15658
  await ensureEnabled();
15596
15659
  const resource = getResource(url);
15597
15660
  if (resource.type === "stylesheet") {
15598
- await session.sendAndWait("CSS.setStyleSheetText", { styleSheetId: resource.id, text: source }, getSessionOptions(resource));
15661
+ await session2.sendAndWait("CSS.setStyleSheetText", { styleSheetId: resource.id, text: source }, getSessionOptions(resource));
15599
15662
  } else {
15600
- await editScript(session, resource, source);
15663
+ await editScript(session2, resource, source);
15601
15664
  }
15602
15665
  sources.set(getSourceCacheKey(resource), source);
15603
15666
  return { ok: true, resource: toCodeResource(resource) };
@@ -15686,9 +15749,9 @@ var createRuntimeEditor = (session) => {
15686
15749
  }
15687
15750
  enabling = (async () => {
15688
15751
  clearResourceState();
15689
- await session.sendAndWait("Debugger.enable", undefined, { timeoutMs: ENABLE_TIMEOUT_MS });
15690
- await session.sendAndWait("DOM.enable", undefined, { timeoutMs: ENABLE_TIMEOUT_MS });
15691
- await session.sendAndWait("CSS.enable", undefined, { timeoutMs: ENABLE_TIMEOUT_MS });
15752
+ await session2.sendAndWait("Debugger.enable", undefined, { timeoutMs: ENABLE_TIMEOUT_MS });
15753
+ await session2.sendAndWait("DOM.enable", undefined, { timeoutMs: ENABLE_TIMEOUT_MS });
15754
+ await session2.sendAndWait("CSS.enable", undefined, { timeoutMs: ENABLE_TIMEOUT_MS });
15692
15755
  await waitForResourceQuietPeriod();
15693
15756
  enabled = true;
15694
15757
  })();
@@ -15703,13 +15766,13 @@ var createRuntimeEditor = (session) => {
15703
15766
  return;
15704
15767
  }
15705
15768
  listenerDisposers = [
15706
- session.onEvent("Debugger.scriptParsed", (params, meta) => {
15769
+ session2.onEvent("Debugger.scriptParsed", (params, meta) => {
15707
15770
  handleScriptParsed(params, meta);
15708
15771
  }),
15709
- session.onEvent("CSS.styleSheetAdded", (params, meta) => {
15772
+ session2.onEvent("CSS.styleSheetAdded", (params, meta) => {
15710
15773
  handleStyleSheetAdded(params, meta);
15711
15774
  }),
15712
- session.onEvent("CSS.styleSheetRemoved", (params, meta) => {
15775
+ session2.onEvent("CSS.styleSheetRemoved", (params, meta) => {
15713
15776
  handleStyleSheetRemoved(params, meta);
15714
15777
  })
15715
15778
  ];
@@ -15822,11 +15885,11 @@ var createRuntimeEditor = (session) => {
15822
15885
  sources.clear();
15823
15886
  }
15824
15887
  async function readStylesheetSource(resource) {
15825
- const result = await session.sendAndWait("CSS.getStyleSheetText", { styleSheetId: resource.id }, getSessionOptions(resource));
15888
+ const result = await session2.sendAndWait("CSS.getStyleSheetText", { styleSheetId: resource.id }, getSessionOptions(resource));
15826
15889
  return result.text ?? "";
15827
15890
  }
15828
15891
  async function readScriptSource(resource) {
15829
- const result = await session.sendAndWait("Debugger.getScriptSource", { scriptId: resource.id }, getSessionOptions(resource));
15892
+ const result = await session2.sendAndWait("Debugger.getScriptSource", { scriptId: resource.id }, getSessionOptions(resource));
15830
15893
  return result.scriptSource ?? "";
15831
15894
  }
15832
15895
  };
@@ -15851,10 +15914,10 @@ var matchesUrlPattern = (resource, pattern) => !pattern || resource.url.toLowerC
15851
15914
  var matchesLine = (line, pattern) => matchesTextPattern(line, pattern);
15852
15915
  var getSessionOptions = (resource) => resource.sessionId ? { sessionId: resource.sessionId } : undefined;
15853
15916
  var getSourceCacheKey = (resource) => `${resource.type}:${resource.sessionId ?? "root"}:${resource.id}`;
15854
- async function editScript(session, resource, source) {
15917
+ async function editScript(session2, resource, source) {
15855
15918
  let result;
15856
15919
  try {
15857
- result = await session.sendAndWait("Debugger.setScriptSource", { scriptId: resource.id, scriptSource: source }, getSessionOptions(resource));
15920
+ result = await session2.sendAndWait("Debugger.setScriptSource", { scriptId: resource.id, scriptSource: source }, getSessionOptions(resource));
15858
15921
  } catch (error) {
15859
15922
  const message = formatError(error);
15860
15923
  if (/setScriptSource.*no longer available/i.test(message)) {
@@ -15997,9 +16060,9 @@ var toExceptionEvent = async (params, page, config) => {
15997
16060
  };
15998
16061
  return applyLocation(baseEvent, details?.stackTrace?.callFrames, config);
15999
16062
  };
16000
- var fetchPageIntl = async (session) => {
16063
+ var fetchPageIntl = async (session2) => {
16001
16064
  try {
16002
- const result = await session.sendAndWait("Runtime.evaluate", {
16065
+ const result = await session2.sendAndWait("Runtime.evaluate", {
16003
16066
  expression: "(() => { const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone ?? null; const locale = navigator.language ?? null; return { timezone, locale }; })()",
16004
16067
  returnByValue: true
16005
16068
  });
@@ -16214,7 +16277,7 @@ var startCdpWatcher = (options) => {
16214
16277
  let stopped = false;
16215
16278
  let socket = null;
16216
16279
  let currentTarget = null;
16217
- const { session, attach, detach } = options.sessionHandle ?? createCdpSessionHandle();
16280
+ const { session: session2, attach, detach } = options.sessionHandle ?? createCdpSessionHandle();
16218
16281
  const stop = async () => {
16219
16282
  stopped = true;
16220
16283
  if (socket) {
@@ -16222,19 +16285,19 @@ var startCdpWatcher = (options) => {
16222
16285
  }
16223
16286
  };
16224
16287
  runLoop();
16225
- session.onEvent("Runtime.consoleAPICalled", (params) => {
16288
+ session2.onEvent("Runtime.consoleAPICalled", (params) => {
16226
16289
  if (!currentTarget) {
16227
16290
  return;
16228
16291
  }
16229
- toConsoleEvent(params, currentTarget, { ...options, cdp: session }).then((event) => options.onLog(event));
16292
+ toConsoleEvent(params, currentTarget, { ...options, cdp: session2 }).then((event) => options.onLog(event));
16230
16293
  });
16231
- session.onEvent("Runtime.exceptionThrown", (params) => {
16294
+ session2.onEvent("Runtime.exceptionThrown", (params) => {
16232
16295
  if (!currentTarget) {
16233
16296
  return;
16234
16297
  }
16235
- toExceptionEvent(params, currentTarget, { ...options, cdp: session }).then((event) => options.onLog(event));
16298
+ toExceptionEvent(params, currentTarget, { ...options, cdp: session2 }).then((event) => options.onLog(event));
16236
16299
  });
16237
- session.onEvent("Page.frameNavigated", (params) => {
16300
+ session2.onEvent("Page.frameNavigated", (params) => {
16238
16301
  if (!currentTarget) {
16239
16302
  return;
16240
16303
  }
@@ -16245,7 +16308,7 @@ var startCdpWatcher = (options) => {
16245
16308
  currentTarget.url = navigation.url;
16246
16309
  options.onPageNavigation?.({ url: navigation.url, title: currentTarget.title ?? null });
16247
16310
  });
16248
- session.onEvent("Page.domContentEventFired", () => {
16311
+ session2.onEvent("Page.domContentEventFired", () => {
16249
16312
  if (!currentTarget) {
16250
16313
  return;
16251
16314
  }
@@ -16253,7 +16316,7 @@ var startCdpWatcher = (options) => {
16253
16316
  });
16254
16317
  return {
16255
16318
  stop,
16256
- session,
16319
+ session: session2,
16257
16320
  getTarget: () => currentTarget ? { ...currentTarget } : null
16258
16321
  };
16259
16322
  async function runLoop() {
@@ -16295,13 +16358,13 @@ var startCdpWatcher = (options) => {
16295
16358
  options.onStatus({ attached: false, target: null, reason });
16296
16359
  options.onDetach?.(reason);
16297
16360
  });
16298
- const pageIntl = await fetchPageIntl(session);
16361
+ const pageIntl = await fetchPageIntl(session2);
16299
16362
  if (pageIntl) {
16300
16363
  options.onPageIntl?.(pageIntl);
16301
16364
  }
16302
- await session.sendAndWait("Runtime.enable");
16303
- await session.sendAndWait("Page.enable");
16304
- await options.onAttach?.(session, target);
16365
+ await session2.sendAndWait("Runtime.enable");
16366
+ await session2.sendAndWait("Page.enable");
16367
+ await options.onAttach?.(session2, target);
16305
16368
  options.onStatus({
16306
16369
  attached: true,
16307
16370
  target: {
@@ -16417,7 +16480,7 @@ var createCdpSource = (options) => {
16417
16480
  onPageNavigation: events.onPageNavigation,
16418
16481
  onPageLoad: events.onPageLoad,
16419
16482
  onPageIntl: events.onPageIntl,
16420
- onAttach: events.onAttach ? (session, target) => events.onAttach(session, {
16483
+ onAttach: events.onAttach ? (session2, target) => events.onAttach(session2, {
16421
16484
  id: target.id,
16422
16485
  title: target.title,
16423
16486
  url: target.url,
@@ -16615,12 +16678,12 @@ class SessionManager {
16615
16678
  }
16616
16679
  }
16617
16680
  handleTabAttached(message) {
16618
- const session = this.createSession(message);
16619
- this.events.onAttach(session);
16681
+ const session2 = this.createSession(message);
16682
+ this.events.onAttach(session2);
16620
16683
  }
16621
16684
  handleTabDetached(message) {
16622
- const session = this.sessions.get(message.tabId);
16623
- if (session) {
16685
+ const session2 = this.sessions.get(message.tabId);
16686
+ if (session2) {
16624
16687
  this.sessions.delete(message.tabId);
16625
16688
  this.eventHandlers.delete(message.tabId);
16626
16689
  }
@@ -16688,7 +16751,7 @@ class SessionManager {
16688
16751
  getTargetContext: () => ({ kind: "page" }),
16689
16752
  getReadyTargetContext: async () => ({ kind: "page" })
16690
16753
  };
16691
- const session = {
16754
+ const session2 = {
16692
16755
  tabId,
16693
16756
  url,
16694
16757
  title,
@@ -16709,8 +16772,8 @@ class SessionManager {
16709
16772
  }), options?.timeoutMs ?? 1e4);
16710
16773
  }
16711
16774
  };
16712
- this.sessions.set(tabId, session);
16713
- return session;
16775
+ this.sessions.set(tabId, session2);
16776
+ return session2;
16714
16777
  }
16715
16778
  async getCookies(tabId, query2, timeoutMs = 5000) {
16716
16779
  if (!this.sessions.has(tabId)) {
@@ -16773,13 +16836,13 @@ var parseExtensionTargetId = (targetId) => {
16773
16836
  }
16774
16837
  throw new Error(`Invalid extension target id: ${targetId}`);
16775
16838
  };
16776
- var buildPageTarget = (session, options) => ({
16777
- id: formatPageTargetId(session.tabId),
16778
- title: session.title,
16779
- url: session.url,
16839
+ var buildPageTarget = (session2, options) => ({
16840
+ id: formatPageTargetId(session2.tabId),
16841
+ title: session2.title,
16842
+ url: session2.url,
16780
16843
  type: "page",
16781
16844
  parentId: null,
16782
- faviconUrl: session.faviconUrl,
16845
+ faviconUrl: session2.faviconUrl,
16783
16846
  attached: options.attached
16784
16847
  });
16785
16848
  var frameToTarget = (tabId, frame, options) => ({
@@ -16949,7 +17012,7 @@ var createDelegatingSession = (options) => {
16949
17012
  rebind: rebindSubscriptions,
16950
17013
  dispose: disposeSubscriptions
16951
17014
  };
16952
- const session = {
17015
+ const session2 = {
16953
17016
  isAttached: () => options.getCurrentSession()?.handle.isAttached() ?? false,
16954
17017
  sendAndWait: async (method, params, commandOptions) => {
16955
17018
  const currentSession = options.requireCurrentSession();
@@ -16983,7 +17046,7 @@ var createDelegatingSession = (options) => {
16983
17046
  getReadyTargetContext: options.getReadyTargetContext ?? (async () => options.getTargetContext())
16984
17047
  };
16985
17048
  controller.rebind();
16986
- return { session, controller };
17049
+ return { session: session2, controller };
16987
17050
  };
16988
17051
  var createDelegatingEventSubscription = (method, handler) => ({
16989
17052
  method,
@@ -16996,32 +17059,32 @@ var createDelegatingEventSubscription = (method, handler) => ({
16996
17059
  });
16997
17060
 
16998
17061
  // ../argus-watcher/dist/sources/extension-session-events.js
16999
- var registerExtensionSessionEventHandlers = ({ session, events, ignoreMatcher, stripUrlPrefixes: stripUrlPrefixes2, sourcemaps, getOrCreateFrameState, reconcileTargetSelection, removeFrame, refreshFrameTitle, emitTargetChanged, setCurrentSession }) => {
17000
- session.handle.onEvent("Runtime.executionContextCreated", (params, meta) => {
17062
+ var registerExtensionSessionEventHandlers = ({ session: session2, events, ignoreMatcher, stripUrlPrefixes: stripUrlPrefixes2, sourcemaps, getOrCreateFrameState, reconcileTargetSelection, removeFrame, refreshFrameTitle, emitTargetChanged, setCurrentSession }) => {
17063
+ session2.handle.onEvent("Runtime.executionContextCreated", (params, meta) => {
17001
17064
  const context = parseExecutionContext(params);
17002
17065
  if (!context?.isDefault || !context.frameId) {
17003
17066
  return;
17004
17067
  }
17005
- const state2 = getOrCreateFrameState(session.tabId);
17068
+ const state2 = getOrCreateFrameState(session2.tabId);
17006
17069
  state2.executionContexts.set(context.frameId, context.id);
17007
17070
  const frame = state2.frames.get(context.frameId);
17008
17071
  if (frame) {
17009
17072
  frame.sessionId = meta.sessionId ?? null;
17010
17073
  }
17011
- refreshFrameTitle(session, context.frameId, context.id);
17012
- reconcileTargetSelection(session);
17074
+ refreshFrameTitle(session2, context.frameId, context.id);
17075
+ reconcileTargetSelection(session2);
17013
17076
  });
17014
- session.handle.onEvent("Runtime.executionContextsCleared", () => {
17015
- const state2 = getOrCreateFrameState(session.tabId);
17077
+ session2.handle.onEvent("Runtime.executionContextsCleared", () => {
17078
+ const state2 = getOrCreateFrameState(session2.tabId);
17016
17079
  state2.executionContexts.clear();
17017
17080
  state2.pendingTitleLoads.clear();
17018
17081
  });
17019
- session.handle.onEvent("Runtime.executionContextDestroyed", (params) => {
17082
+ session2.handle.onEvent("Runtime.executionContextDestroyed", (params) => {
17020
17083
  const record2 = params;
17021
17084
  if (record2.executionContextId == null) {
17022
17085
  return;
17023
17086
  }
17024
- const state2 = getOrCreateFrameState(session.tabId);
17087
+ const state2 = getOrCreateFrameState(session2.tabId);
17025
17088
  for (const [frameId, contextId] of state2.executionContexts.entries()) {
17026
17089
  if (contextId === record2.executionContextId) {
17027
17090
  state2.executionContexts.delete(frameId);
@@ -17029,42 +17092,42 @@ var registerExtensionSessionEventHandlers = ({ session, events, ignoreMatcher, s
17029
17092
  }
17030
17093
  }
17031
17094
  });
17032
- session.handle.onEvent("Page.frameNavigated", (params, meta) => {
17095
+ session2.handle.onEvent("Page.frameNavigated", (params, meta) => {
17033
17096
  const frame = parseFrame(params);
17034
17097
  if (!frame) {
17035
17098
  return;
17036
17099
  }
17037
- const state2 = getOrCreateFrameState(session.tabId);
17100
+ const state2 = getOrCreateFrameState(session2.tabId);
17038
17101
  const preservedSessionId = pickFrameSessionId(meta.sessionId, state2.frames.get(frame.frameId)?.sessionId);
17039
17102
  state2.frames.set(frame.frameId, frame);
17040
17103
  frame.sessionId = preservedSessionId;
17041
17104
  if (!frame.parentFrameId) {
17042
17105
  if (!meta.sessionId) {
17043
17106
  state2.topFrameId = frame.frameId;
17044
- session.url = frame.url;
17107
+ session2.url = frame.url;
17045
17108
  } else if (state2.topFrameId == null) {
17046
17109
  state2.topFrameId = frame.parentFrameId;
17047
17110
  }
17048
17111
  } else if (state2.executionContexts.has(frame.frameId)) {
17049
- refreshFrameTitle(session, frame.frameId);
17112
+ refreshFrameTitle(session2, frame.frameId);
17050
17113
  }
17051
- setCurrentSession(session);
17114
+ setCurrentSession(session2);
17052
17115
  if (!frame.parentFrameId && !meta.sessionId) {
17053
- events.onPageNavigation?.({ url: frame.url, title: session.title ?? null });
17116
+ events.onPageNavigation?.({ url: frame.url, title: session2.title ?? null });
17054
17117
  }
17055
- if (reconcileTargetSelection(session)) {
17118
+ if (reconcileTargetSelection(session2)) {
17056
17119
  return;
17057
17120
  }
17058
17121
  if (!frame.parentFrameId && state2.activeFrameId == null || state2.activeFrameId === frame.frameId) {
17059
- emitTargetChanged(session);
17122
+ emitTargetChanged(session2);
17060
17123
  }
17061
17124
  });
17062
- session.handle.onEvent("Page.frameAttached", (params, meta) => {
17125
+ session2.handle.onEvent("Page.frameAttached", (params, meta) => {
17063
17126
  const record2 = params;
17064
17127
  if (!record2.frameId) {
17065
17128
  return;
17066
17129
  }
17067
- const state2 = getOrCreateFrameState(session.tabId);
17130
+ const state2 = getOrCreateFrameState(session2.tabId);
17068
17131
  state2.frames.set(record2.frameId, {
17069
17132
  frameId: record2.frameId,
17070
17133
  parentFrameId: record2.parentFrameId ?? state2.topFrameId ?? null,
@@ -17072,25 +17135,25 @@ var registerExtensionSessionEventHandlers = ({ session, events, ignoreMatcher, s
17072
17135
  title: null,
17073
17136
  sessionId: pickFrameSessionId(meta.sessionId, state2.frames.get(record2.frameId)?.sessionId)
17074
17137
  });
17075
- reconcileTargetSelection(session);
17138
+ reconcileTargetSelection(session2);
17076
17139
  });
17077
- session.handle.onEvent("Page.frameDetached", (params) => {
17140
+ session2.handle.onEvent("Page.frameDetached", (params) => {
17078
17141
  const record2 = params;
17079
17142
  if (!record2.frameId) {
17080
17143
  return;
17081
17144
  }
17082
- removeFrame(session.tabId, record2.frameId);
17083
- reconcileTargetSelection(session);
17145
+ removeFrame(session2.tabId, record2.frameId);
17146
+ reconcileTargetSelection(session2);
17084
17147
  });
17085
- session.handle.onEvent("Page.domContentEventFired", () => {
17148
+ session2.handle.onEvent("Page.domContentEventFired", () => {
17086
17149
  events.onPageLoad?.();
17087
17150
  });
17088
- const logConfig = { ignoreMatcher, stripUrlPrefixes: stripUrlPrefixes2, sourcemaps, cdp: session.handle };
17089
- session.handle.onEvent("Runtime.consoleAPICalled", (params) => {
17090
- toConsoleEvent(params, session, logConfig).then((event) => events.onLog(event));
17151
+ const logConfig = { ignoreMatcher, stripUrlPrefixes: stripUrlPrefixes2, sourcemaps, cdp: session2.handle };
17152
+ session2.handle.onEvent("Runtime.consoleAPICalled", (params) => {
17153
+ toConsoleEvent(params, session2, logConfig).then((event) => events.onLog(event));
17091
17154
  });
17092
- session.handle.onEvent("Runtime.exceptionThrown", (params) => {
17093
- toExceptionEvent(params, session, logConfig).then((event) => events.onLog(event));
17155
+ session2.handle.onEvent("Runtime.exceptionThrown", (params) => {
17156
+ toExceptionEvent(params, session2, logConfig).then((event) => events.onLog(event));
17094
17157
  });
17095
17158
  };
17096
17159
  var pickFrameSessionId = (nextSessionId, existingSessionId) => nextSessionId ?? existingSessionId ?? null;
@@ -17280,18 +17343,18 @@ var FRAME_COMMAND_READY_POLL_MS = 100;
17280
17343
  var createTargetRecovery = (deps) => {
17281
17344
  const { getCurrentSession, getOrCreateFrameState, refreshFrameTree, reconcileTargetSelection } = deps;
17282
17345
  const recoveryByTabId = new Map;
17283
- const sync = (session, state2) => {
17346
+ const sync = (session2, state2) => {
17284
17347
  if (!needsTargetRecovery(state2)) {
17285
- clear(session.tabId);
17348
+ clear(session2.tabId);
17286
17349
  return;
17287
17350
  }
17288
- if (recoveryByTabId.has(session.tabId)) {
17351
+ if (recoveryByTabId.has(session2.tabId)) {
17289
17352
  return;
17290
17353
  }
17291
17354
  const timer = setInterval(() => {
17292
- retry(session.tabId);
17355
+ retry(session2.tabId);
17293
17356
  }, TARGET_RECOVERY_INTERVAL_MS);
17294
- recoveryByTabId.set(session.tabId, {
17357
+ recoveryByTabId.set(session2.tabId, {
17295
17358
  timer,
17296
17359
  deadline: Date.now() + TARGET_RECOVERY_TIMEOUT_MS
17297
17360
  });
@@ -17311,8 +17374,8 @@ var createTargetRecovery = (deps) => {
17311
17374
  };
17312
17375
  const retry = async (tabId) => {
17313
17376
  const recovery = recoveryByTabId.get(tabId);
17314
- const session = getCurrentSession();
17315
- if (!recovery || !session || session.tabId !== tabId) {
17377
+ const session2 = getCurrentSession();
17378
+ if (!recovery || !session2 || session2.tabId !== tabId) {
17316
17379
  clear(tabId);
17317
17380
  return;
17318
17381
  }
@@ -17326,32 +17389,32 @@ var createTargetRecovery = (deps) => {
17326
17389
  return;
17327
17390
  }
17328
17391
  try {
17329
- await refreshFrameTree(session);
17392
+ await refreshFrameTree(session2);
17330
17393
  } catch {}
17331
- reconcileTargetSelection(session);
17394
+ reconcileTargetSelection(session2);
17332
17395
  if (!needsTargetRecovery(getOrCreateFrameState(tabId))) {
17333
17396
  clear(tabId);
17334
17397
  }
17335
17398
  };
17336
- const kick = async (session) => {
17337
- const state2 = getOrCreateFrameState(session.tabId);
17399
+ const kick = async (session2) => {
17400
+ const state2 = getOrCreateFrameState(session2.tabId);
17338
17401
  if (!needsTargetRecovery(state2)) {
17339
17402
  return;
17340
17403
  }
17341
- sync(session, state2);
17342
- await retry(session.tabId);
17404
+ sync(session2, state2);
17405
+ await retry(session2.tabId);
17343
17406
  };
17344
17407
  const waitForSelectedFrameCommandTarget = async () => {
17345
- const session = getCurrentSession();
17346
- if (!session) {
17408
+ const session2 = getCurrentSession();
17409
+ if (!session2) {
17347
17410
  throw createNotAttachedError();
17348
17411
  }
17349
- const tabId = session.tabId;
17412
+ const tabId = session2.tabId;
17350
17413
  const immediate = resolveSelectedFrameCommandState(getOrCreateFrameState(tabId));
17351
17414
  if (immediate.kind === "frame") {
17352
17415
  return buildFrameTargetContext(getOrCreateFrameState(tabId), immediate.frameId);
17353
17416
  }
17354
- await kick(session);
17417
+ await kick(session2);
17355
17418
  const deadline = Date.now() + FRAME_COMMAND_READY_TIMEOUT_MS;
17356
17419
  while (Date.now() < deadline) {
17357
17420
  await delay(FRAME_COMMAND_READY_POLL_MS);
@@ -17372,11 +17435,11 @@ var needsTargetRecovery = (state2) => resolveSelectedFrameCommandState(state2).k
17372
17435
  var buildSelectedFrameNotReadyError = (tabId) => codedError("extension_frame_not_ready", `Selected iframe target on tab ${tabId} is not executable yet after reload. Try again in a few seconds or reattach the watcher if the problem persists.`);
17373
17436
 
17374
17437
  // ../argus-watcher/dist/sources/extension-frame-snapshot.js
17375
- var applyExtensionFrameSnapshot = (session, state2, snapshot2, deps) => {
17438
+ var applyExtensionFrameSnapshot = (session2, state2, snapshot2, deps) => {
17376
17439
  const nextIds = new Set(snapshot2.frames.map((frame) => frame.frameId));
17377
17440
  for (const frameId of [...state2.frames.keys()]) {
17378
17441
  if (!nextIds.has(frameId)) {
17379
- deps.removeFrame(session.tabId, frameId);
17442
+ deps.removeFrame(session2.tabId, frameId);
17380
17443
  }
17381
17444
  }
17382
17445
  let activeTargetTouched = false;
@@ -17407,29 +17470,29 @@ var applyExtensionFrameSnapshot = (session, state2, snapshot2, deps) => {
17407
17470
  const record2 = state2.frames.get(frame.frameId);
17408
17471
  const needsTitle = (!existing || urlChanged || record2.title == null) && frame.frameId !== snapshot2.topFrameId;
17409
17472
  if (needsTitle && state2.executionContexts.has(frame.frameId)) {
17410
- deps.refreshFrameTitle(session, frame.frameId);
17473
+ deps.refreshFrameTitle(session2, frame.frameId);
17411
17474
  }
17412
17475
  }
17413
17476
  if (snapshot2.topFrameId != null) {
17414
17477
  state2.topFrameId = snapshot2.topFrameId;
17415
17478
  const topFrame = state2.frames.get(snapshot2.topFrameId);
17416
17479
  if (topFrame?.url) {
17417
- session.url = topFrame.url;
17480
+ session2.url = topFrame.url;
17418
17481
  }
17419
17482
  }
17420
- const selectionChanged = deps.reconcileTargetSelection(session);
17483
+ const selectionChanged = deps.reconcileTargetSelection(session2);
17421
17484
  if (!selectionChanged && activeTargetTouched) {
17422
- deps.emitTargetChanged(session);
17485
+ deps.emitTargetChanged(session2);
17423
17486
  }
17424
17487
  };
17425
17488
 
17426
17489
  // ../argus-watcher/dist/sources/extension-frame-runtime.js
17427
- var seedExtensionFrameState = (session, state2) => {
17428
- if (state2.frames.size > 0 || session.frames.length === 0) {
17490
+ var seedExtensionFrameState = (session2, state2) => {
17491
+ if (state2.frames.size > 0 || session2.frames.length === 0) {
17429
17492
  return state2;
17430
17493
  }
17431
- state2.topFrameId = session.topFrameId;
17432
- for (const frame of session.frames) {
17494
+ state2.topFrameId = session2.topFrameId;
17495
+ for (const frame of session2.frames) {
17433
17496
  state2.frames.set(frame.frameId, {
17434
17497
  frameId: frame.frameId,
17435
17498
  parentFrameId: frame.parentFrameId,
@@ -17440,16 +17503,16 @@ var seedExtensionFrameState = (session, state2) => {
17440
17503
  }
17441
17504
  return state2;
17442
17505
  };
17443
- var getSelectedExtensionTarget = (session, state2) => {
17506
+ var getSelectedExtensionTarget = (session2, state2) => {
17444
17507
  const frameId = state2?.requestedFrameId ?? state2?.activeFrameId;
17445
17508
  if (!state2 || !frameId) {
17446
- return buildPageTarget(session, { attached: true });
17509
+ return buildPageTarget(session2, { attached: true });
17447
17510
  }
17448
17511
  const frame = state2.frames.get(frameId);
17449
17512
  if (frame) {
17450
- return frameToTarget(session.tabId, frame, { attached: true, faviconUrl: session.faviconUrl, topFrameId: state2.topFrameId });
17513
+ return frameToTarget(session2.tabId, frame, { attached: true, faviconUrl: session2.faviconUrl, topFrameId: state2.topFrameId });
17451
17514
  }
17452
- return buildSelectedIframeFallbackTarget(session, state2);
17515
+ return buildSelectedIframeFallbackTarget(session2, state2);
17453
17516
  };
17454
17517
  var setRequestedTargetSelection = (state2, frameId) => {
17455
17518
  if (state2.requestedFrameId !== frameId) {
@@ -17459,13 +17522,13 @@ var setRequestedTargetSelection = (state2, frameId) => {
17459
17522
  state2.requestedFrameId = frameId;
17460
17523
  state2.requestedFrameHint = frameId ? createRequestedFrameHint(state2.frames.get(frameId)) ?? previousHint : null;
17461
17524
  };
17462
- var listExtensionTargets = (session, state2) => {
17525
+ var listExtensionTargets = (session2, state2) => {
17463
17526
  if (!state2) {
17464
- return [buildPageTarget(session, { attached: true })];
17527
+ return [buildPageTarget(session2, { attached: true })];
17465
17528
  }
17466
- const selected = getSelectedExtensionTarget(session, state2);
17529
+ const selected = getSelectedExtensionTarget(session2, state2);
17467
17530
  selected.targetReady = isSelectedTargetReady(state2);
17468
- const targets = [buildPageTarget(session, { attached: false }), ...buildFrameTargets(state2, session.tabId, null, session.faviconUrl)];
17531
+ const targets = [buildPageTarget(session2, { attached: false }), ...buildFrameTargets(state2, session2.tabId, null, session2.faviconUrl)];
17469
17532
  const selectedIndex = targets.findIndex((target) => target.id === selected.id);
17470
17533
  if (selectedIndex < 0) {
17471
17534
  targets.push(selected);
@@ -17474,7 +17537,7 @@ var listExtensionTargets = (session, state2) => {
17474
17537
  }
17475
17538
  return targets;
17476
17539
  };
17477
- var reconcileExtensionTargetSelection = (session, state2, onTargetChanged) => {
17540
+ var reconcileExtensionTargetSelection = (session2, state2, onTargetChanged) => {
17478
17541
  const resolution = resolveRequestedTarget(state2);
17479
17542
  if (resolution.kind === "page") {
17480
17543
  return activatePageTarget(state2, onTargetChanged);
@@ -17507,7 +17570,7 @@ var removeExtensionFrame = (state2, frameId) => {
17507
17570
  state2.executionContexts.delete(frameId);
17508
17571
  state2.pendingTitleLoads.delete(frameId);
17509
17572
  };
17510
- var refreshExtensionFrameTitle = async (session, state2, frameId, onActiveFrameUpdated, contextId) => {
17573
+ var refreshExtensionFrameTitle = async (session2, state2, frameId, onActiveFrameUpdated, contextId) => {
17511
17574
  if (frameId === state2.topFrameId || state2.pendingTitleLoads.has(frameId)) {
17512
17575
  return;
17513
17576
  }
@@ -17521,7 +17584,7 @@ var refreshExtensionFrameTitle = async (session, state2, frameId, onActiveFrameU
17521
17584
  }
17522
17585
  state2.pendingTitleLoads.add(frameId);
17523
17586
  try {
17524
- const evaluated = await session.handle.sendAndWait("Runtime.evaluate", {
17587
+ const evaluated = await session2.handle.sendAndWait("Runtime.evaluate", {
17525
17588
  expression: "document.title",
17526
17589
  contextId: executionContextId,
17527
17590
  returnByValue: true,
@@ -17568,19 +17631,19 @@ var syncRequestedFrameSelection = (state2, frameId) => {
17568
17631
  state2.requestedFrameId = frameId;
17569
17632
  state2.requestedFrameHint = createRequestedFrameHint(frame);
17570
17633
  };
17571
- var buildSelectedIframeFallbackTarget = (session, state2) => {
17634
+ var buildSelectedIframeFallbackTarget = (session2, state2) => {
17572
17635
  const hint = state2.requestedFrameHint;
17573
17636
  const frameId = state2.requestedFrameId ?? state2.activeFrameId;
17574
17637
  if (!frameId) {
17575
- return buildPageTarget(session, { attached: true });
17638
+ return buildPageTarget(session2, { attached: true });
17576
17639
  }
17577
17640
  return {
17578
- id: formatFrameTargetId(session.tabId, frameId),
17641
+ id: formatFrameTargetId(session2.tabId, frameId),
17579
17642
  title: hint?.title ?? hint?.url ?? `iframe ${frameId}`,
17580
- url: hint?.url ?? session.url,
17643
+ url: hint?.url ?? session2.url,
17581
17644
  type: "iframe",
17582
- parentId: formatPageTargetId(session.tabId),
17583
- faviconUrl: session.faviconUrl,
17645
+ parentId: formatPageTargetId(session2.tabId),
17646
+ faviconUrl: session2.faviconUrl,
17584
17647
  attached: true,
17585
17648
  targetReady: false
17586
17649
  };
@@ -17618,17 +17681,17 @@ var createExtensionSource = (options) => {
17618
17681
  });
17619
17682
  const frameSnapshotDeps = {
17620
17683
  removeFrame,
17621
- refreshFrameTitle: (session, frameId) => refreshFrameTitle(session, frameId),
17684
+ refreshFrameTitle: (session2, frameId) => refreshFrameTitle(session2, frameId),
17622
17685
  reconcileTargetSelection,
17623
17686
  emitTargetChanged
17624
17687
  };
17625
17688
  const sessionManager = new SessionManager(messaging, {
17626
- onAttach: (session) => {
17627
- console.error(`[ExtensionSource] Tab attached: ${session.tabId} - ${session.url}`);
17628
- currentSession = session;
17689
+ onAttach: (session2) => {
17690
+ console.error(`[ExtensionSource] Tab attached: ${session2.tabId} - ${session2.url}`);
17691
+ currentSession = session2;
17629
17692
  rebindDelegatingSessions();
17630
- seedFrameState(session);
17631
- bootstrapAttachedSession(session);
17693
+ seedFrameState(session2);
17694
+ bootstrapAttachedSession(session2);
17632
17695
  },
17633
17696
  onDetach: (tabId, reason) => {
17634
17697
  console.error(`[ExtensionSource] Tab detached: ${tabId} - ${reason}`);
@@ -17642,20 +17705,20 @@ var createExtensionSource = (options) => {
17642
17705
  events.onDetach?.(reason);
17643
17706
  },
17644
17707
  onTargetSelected: (tabId, frameId) => {
17645
- const session = currentSession;
17646
- if (!session || session.tabId !== tabId) {
17708
+ const session2 = currentSession;
17709
+ if (!session2 || session2.tabId !== tabId) {
17647
17710
  const state2 = getOrCreateFrameState(tabId);
17648
17711
  setRequestedTargetSelection(state2, frameId);
17649
17712
  return;
17650
17713
  }
17651
- requestTargetSelection(session, frameId);
17714
+ requestTargetSelection(session2, frameId);
17652
17715
  },
17653
17716
  onFrameSnapshot: (snapshot2) => {
17654
- const session = currentSession;
17655
- if (!session || session.tabId !== snapshot2.tabId) {
17717
+ const session2 = currentSession;
17718
+ if (!session2 || session2.tabId !== snapshot2.tabId) {
17656
17719
  return;
17657
17720
  }
17658
- applyExtensionFrameSnapshot(session, getOrCreateFrameState(snapshot2.tabId), snapshot2, frameSnapshotDeps);
17721
+ applyExtensionFrameSnapshot(session2, getOrCreateFrameState(snapshot2.tabId), snapshot2, frameSnapshotDeps);
17659
17722
  }
17660
17723
  });
17661
17724
  const { session: proxySession, controller: proxyController } = createDelegatingSession({
@@ -17710,70 +17773,70 @@ var createExtensionSource = (options) => {
17710
17773
  messaging.stop();
17711
17774
  };
17712
17775
  const listTargets = async () => {
17713
- const session = currentSession;
17714
- if (!session) {
17776
+ const session2 = currentSession;
17777
+ if (!session2) {
17715
17778
  return [];
17716
17779
  }
17717
- return listExtensionTargets(session, frameStateByTabId.get(session.tabId));
17780
+ return listExtensionTargets(session2, frameStateByTabId.get(session2.tabId));
17718
17781
  };
17719
17782
  const attachTarget = async (targetId) => {
17720
17783
  const target = parseExtensionTargetId(targetId);
17721
- const session = currentSession;
17722
- if (!session) {
17784
+ const session2 = currentSession;
17785
+ if (!session2) {
17723
17786
  if (target.frameId) {
17724
17787
  throw new Error(`Cannot attach iframe ${target.frameId} before tab ${target.tabId} is attached`);
17725
17788
  }
17726
17789
  throw new Error(`Watcher ${hostInfo.watcherId} is a tab watcher. Use extension-control to attach tab ${target.tabId}.`);
17727
17790
  }
17728
- if (session.tabId !== target.tabId) {
17729
- throw new Error(`Watcher ${hostInfo.watcherId} is pinned to tab ${session.tabId}, not tab ${target.tabId}`);
17791
+ if (session2.tabId !== target.tabId) {
17792
+ throw new Error(`Watcher ${hostInfo.watcherId} is pinned to tab ${session2.tabId}, not tab ${target.tabId}`);
17730
17793
  }
17731
- requestTargetSelection(session, target.frameId);
17732
- return { ok: true, tab: sessionToBrowserTab(session), watcherId: hostInfo.watcherId };
17794
+ requestTargetSelection(session2, target.frameId);
17795
+ return { ok: true, tab: sessionToBrowserTab(session2), watcherId: hostInfo.watcherId };
17733
17796
  };
17734
17797
  const detachTarget = async (targetId) => {
17735
17798
  const target = parseExtensionTargetId(targetId);
17736
- const session = currentSession;
17737
- if (!session || session.tabId === target.tabId) {
17799
+ const session2 = currentSession;
17800
+ if (!session2 || session2.tabId === target.tabId) {
17738
17801
  sessionManager.detachTab(target.tabId);
17739
17802
  return {
17740
17803
  ok: true,
17741
- tab: session ? { ...sessionToBrowserTab(session), attached: false, watcherId: undefined } : { tabId: target.tabId, url: "", title: "", attached: false }
17804
+ tab: session2 ? { ...sessionToBrowserTab(session2), attached: false, watcherId: undefined } : { tabId: target.tabId, url: "", title: "", attached: false }
17742
17805
  };
17743
17806
  }
17744
- throw new Error(`Watcher ${hostInfo.watcherId} is pinned to tab ${session.tabId}, not tab ${target.tabId}`);
17807
+ throw new Error(`Watcher ${hostInfo.watcherId} is pinned to tab ${session2.tabId}, not tab ${target.tabId}`);
17745
17808
  };
17746
17809
  return {
17747
17810
  session: proxySession,
17748
17811
  pageSession,
17749
17812
  readBrowserCookies: async ({ domain, url }) => {
17750
- const session = getCurrentExtensionSession();
17751
- return await sessionManager.getCookies(session.tabId, {
17813
+ const session2 = getCurrentExtensionSession();
17814
+ return await sessionManager.getCookies(session2.tabId, {
17752
17815
  domain: domain ?? undefined,
17753
17816
  url: url ?? undefined
17754
17817
  });
17755
17818
  },
17756
17819
  getNetFilterContext: () => {
17757
- const session = currentSession;
17758
- if (!session) {
17820
+ const session2 = currentSession;
17821
+ if (!session2) {
17759
17822
  return null;
17760
17823
  }
17761
- const state2 = frameStateByTabId.get(session.tabId);
17762
- const selectedTarget = getSelectedTarget(session);
17824
+ const state2 = frameStateByTabId.get(session2.tabId);
17825
+ const selectedTarget = getSelectedTarget(session2);
17763
17826
  return {
17764
17827
  sourceMode: "extension",
17765
17828
  selectedFrameId: state2?.activeFrameId ?? null,
17766
- topFrameId: state2?.topFrameId ?? session.topFrameId,
17767
- selectedTargetUrl: selectedTarget?.url ?? session.url,
17768
- pageUrl: session.url
17829
+ topFrameId: state2?.topFrameId ?? session2.topFrameId,
17830
+ selectedTargetUrl: selectedTarget?.url ?? session2.url,
17831
+ pageUrl: session2.url
17769
17832
  };
17770
17833
  },
17771
17834
  getFrameSessionId: (frameId) => {
17772
- const session = currentSession;
17773
- if (!session) {
17835
+ const session2 = currentSession;
17836
+ if (!session2) {
17774
17837
  return null;
17775
17838
  }
17776
- const state2 = frameStateByTabId.get(session.tabId);
17839
+ const state2 = frameStateByTabId.get(session2.tabId);
17777
17840
  return state2?.frames.get(frameId)?.sessionId ?? null;
17778
17841
  },
17779
17842
  syncWatcherInfo: (info) => {
@@ -17809,10 +17872,10 @@ var createExtensionSource = (options) => {
17809
17872
  }
17810
17873
  delegatingSessions.clear();
17811
17874
  }
17812
- async function bootstrapAttachedSession(session) {
17875
+ async function bootstrapAttachedSession(session2) {
17813
17876
  try {
17814
17877
  registerExtensionSessionEventHandlers({
17815
- session,
17878
+ session: session2,
17816
17879
  events,
17817
17880
  ignoreMatcher: ignoreMatcherObj,
17818
17881
  stripUrlPrefixes: stripUrlPrefixes2,
@@ -17826,34 +17889,34 @@ var createExtensionSource = (options) => {
17826
17889
  currentSession = nextSession;
17827
17890
  }
17828
17891
  });
17829
- await enableBootstrapDomains(session);
17830
- await refreshFrameTree(session);
17831
- if (currentSession?.tabId !== session.tabId) {
17892
+ await enableBootstrapDomains(session2);
17893
+ await refreshFrameTree(session2);
17894
+ if (currentSession?.tabId !== session2.tabId) {
17832
17895
  return;
17833
17896
  }
17834
- const target = getSelectedTarget(session) ?? buildPageTarget(session, { attached: true });
17897
+ const target = getSelectedTarget(session2) ?? buildPageTarget(session2, { attached: true });
17835
17898
  emitStatus(target, null);
17836
- await events.onAttach?.(session.handle, target);
17837
- reconcileTargetSelection(session);
17899
+ await events.onAttach?.(session2.handle, target);
17900
+ reconcileTargetSelection(session2);
17838
17901
  } catch (error) {
17839
17902
  const message = formatError(error);
17840
- console.error(`[ExtensionSource] Failed to bootstrap attached tab ${session.tabId}: ${message}`);
17841
- if (currentSession?.tabId === session.tabId) {
17903
+ console.error(`[ExtensionSource] Failed to bootstrap attached tab ${session2.tabId}: ${message}`);
17904
+ if (currentSession?.tabId === session2.tabId) {
17842
17905
  emitStatus(null, message);
17843
17906
  events.onDetach?.(message);
17844
17907
  }
17845
17908
  }
17846
17909
  }
17847
- async function enableBootstrapDomains(session) {
17848
- await session.handle.sendAndWait("Runtime.enable");
17849
- await session.handle.sendAndWait("Page.enable");
17910
+ async function enableBootstrapDomains(session2) {
17911
+ await session2.handle.sendAndWait("Runtime.enable");
17912
+ await session2.handle.sendAndWait("Page.enable");
17850
17913
  }
17851
17914
  function getCurrentTargetContext() {
17852
- const session = currentSession;
17853
- if (!session) {
17915
+ const session2 = currentSession;
17916
+ if (!session2) {
17854
17917
  return null;
17855
17918
  }
17856
- const state2 = frameStateByTabId.get(session.tabId);
17919
+ const state2 = frameStateByTabId.get(session2.tabId);
17857
17920
  const frameId = state2?.requestedFrameId ?? state2?.activeFrameId;
17858
17921
  if (!state2 || !frameId) {
17859
17922
  return { kind: "page" };
@@ -17869,13 +17932,13 @@ var createExtensionSource = (options) => {
17869
17932
  frameStateByTabId.set(tabId, created);
17870
17933
  return created;
17871
17934
  }
17872
- function seedFrameState(session) {
17873
- const state2 = getOrCreateFrameState(session.tabId);
17874
- return seedExtensionFrameState(session, state2);
17935
+ function seedFrameState(session2) {
17936
+ const state2 = getOrCreateFrameState(session2.tabId);
17937
+ return seedExtensionFrameState(session2, state2);
17875
17938
  }
17876
17939
  function emitStatus(target, reason) {
17877
- const session = currentSession;
17878
- const targetReady = target == null ? null : session ? isTargetReady(session.tabId) : true;
17940
+ const session2 = currentSession;
17941
+ const targetReady = target == null ? null : session2 ? isTargetReady(session2.tabId) : true;
17879
17942
  events.onStatus({
17880
17943
  attached: Boolean(target),
17881
17944
  targetReady,
@@ -17888,16 +17951,16 @@ var createExtensionSource = (options) => {
17888
17951
  reason
17889
17952
  });
17890
17953
  }
17891
- function emitTargetChanged(session) {
17892
- const target = getSelectedTarget(session);
17954
+ function emitTargetChanged(session2) {
17955
+ const target = getSelectedTarget(session2);
17893
17956
  if (!target) {
17894
17957
  return;
17895
17958
  }
17896
- const state2 = getOrCreateFrameState(session.tabId);
17959
+ const state2 = getOrCreateFrameState(session2.tabId);
17897
17960
  if (state2.activeAttachedAt == null) {
17898
17961
  state2.activeAttachedAt = Date.now();
17899
17962
  }
17900
- const targetReady = isTargetReady(session.tabId);
17963
+ const targetReady = isTargetReady(session2.tabId);
17901
17964
  emitStatus(target, null);
17902
17965
  messaging.send({
17903
17966
  type: "target_info",
@@ -17907,46 +17970,46 @@ var createExtensionSource = (options) => {
17907
17970
  attachedAt: state2.activeAttachedAt,
17908
17971
  targetReady
17909
17972
  });
17910
- events.onTargetChanged?.(session.handle, target);
17973
+ events.onTargetChanged?.(session2.handle, target);
17911
17974
  }
17912
- function getSelectedTarget(session) {
17913
- return getSelectedExtensionTarget(session, frameStateByTabId.get(session.tabId));
17975
+ function getSelectedTarget(session2) {
17976
+ return getSelectedExtensionTarget(session2, frameStateByTabId.get(session2.tabId));
17914
17977
  }
17915
- function requestTargetSelection(session, frameId) {
17916
- const state2 = getOrCreateFrameState(session.tabId);
17978
+ function requestTargetSelection(session2, frameId) {
17979
+ const state2 = getOrCreateFrameState(session2.tabId);
17917
17980
  setRequestedTargetSelection(state2, frameId);
17918
- reconcileTargetSelection(session);
17981
+ reconcileTargetSelection(session2);
17919
17982
  }
17920
- function reconcileTargetSelection(session) {
17921
- const state2 = getOrCreateFrameState(session.tabId);
17922
- const changed = reconcileExtensionTargetSelection(session, state2, () => {
17923
- emitTargetChanged(session);
17983
+ function reconcileTargetSelection(session2) {
17984
+ const state2 = getOrCreateFrameState(session2.tabId);
17985
+ const changed = reconcileExtensionTargetSelection(session2, state2, () => {
17986
+ emitTargetChanged(session2);
17924
17987
  });
17925
- targetRecovery.sync(session, state2);
17988
+ targetRecovery.sync(session2, state2);
17926
17989
  return changed;
17927
17990
  }
17928
- async function refreshFrameTree(session) {
17929
- await session.requestFrameSnapshot({ refresh: true });
17991
+ async function refreshFrameTree(session2) {
17992
+ await session2.requestFrameSnapshot({ refresh: true });
17930
17993
  }
17931
17994
  function removeFrame(tabId, frameId) {
17932
17995
  const state2 = getOrCreateFrameState(tabId);
17933
17996
  removeExtensionFrame(state2, frameId);
17934
17997
  }
17935
- async function refreshFrameTitle(session, frameId, contextId) {
17936
- const state2 = getOrCreateFrameState(session.tabId);
17937
- await refreshExtensionFrameTitle(session, state2, frameId, () => {
17938
- emitTargetChanged(session);
17998
+ async function refreshFrameTitle(session2, frameId, contextId) {
17999
+ const state2 = getOrCreateFrameState(session2.tabId);
18000
+ await refreshExtensionFrameTitle(session2, state2, frameId, () => {
18001
+ emitTargetChanged(session2);
17939
18002
  }, contextId);
17940
18003
  }
17941
18004
  function isTargetReady(tabId) {
17942
18005
  return isSelectedTargetReady(getOrCreateFrameState(tabId));
17943
18006
  }
17944
18007
  };
17945
- var sessionToBrowserTab = (session) => ({
17946
- tabId: session.tabId,
17947
- url: session.url,
17948
- title: session.title,
17949
- faviconUrl: session.faviconUrl,
18008
+ var sessionToBrowserTab = (session2) => ({
18009
+ tabId: session2.tabId,
18010
+ url: session2.url,
18011
+ title: session2.title,
18012
+ faviconUrl: session2.faviconUrl,
17950
18013
  attached: true
17951
18014
  });
17952
18015
 
@@ -18075,19 +18138,19 @@ var createWatcherHandle = async (options, watcherId) => {
18075
18138
  const handlePageIntl = (info) => {
18076
18139
  fileLogger?.setPageIntl(info);
18077
18140
  };
18078
- const handleSourceAttach = async (session, target) => {
18141
+ const handleSourceAttach = async (session2, target) => {
18079
18142
  elementRefs.reset();
18080
18143
  dialogTracker.clear();
18081
18144
  runtimeEditor?.rebind();
18082
- await emulationController.onAttach(session);
18083
- await throttleController.onAttach(session);
18145
+ await emulationController.onAttach(session2);
18146
+ await throttleController.onAttach(session2);
18084
18147
  await visibilityController.onAttach(getPageSession());
18085
18148
  await netMockController.onAttach();
18086
18149
  await networkCapture?.onAttached();
18087
- indicator.onAttach(session, target);
18088
- await injectOnAttach(session, target);
18150
+ indicator.onAttach(session2, target);
18151
+ await injectOnAttach(session2, target);
18089
18152
  };
18090
- const handleTargetChanged = (session, target) => {
18153
+ const handleTargetChanged = (session2, target) => {
18091
18154
  elementRefs.reset();
18092
18155
  updateCdpStatus({
18093
18156
  attached: true,
@@ -18100,7 +18163,7 @@ var createWatcherHandle = async (options, watcherId) => {
18100
18163
  reason: null
18101
18164
  });
18102
18165
  netMockController.onTargetChanged();
18103
- indicator.onAttach(session, target);
18166
+ indicator.onAttach(session2, target);
18104
18167
  };
18105
18168
  const handleSourceDetach = (reason) => {
18106
18169
  elementRefs.reset();
@@ -23629,14 +23692,14 @@ var parseCookieSetInput = (input, output) => {
23629
23692
  if (sameSite === "None" && input.secure !== true) {
23630
23693
  return writeCookieInputError(output, "sameSite=None requires --secure");
23631
23694
  }
23632
- const session = input.session === true || expires === undefined;
23695
+ const session2 = input.session === true || expires === undefined;
23633
23696
  return {
23634
23697
  ...identity,
23635
23698
  value: input.value,
23636
23699
  secure: input.secure === true,
23637
23700
  httpOnly: input.httpOnly === true,
23638
- session,
23639
- expires: session ? null : expires,
23701
+ session: session2,
23702
+ expires: session2 ? null : expires,
23640
23703
  sameSite
23641
23704
  };
23642
23705
  };
@@ -51859,6 +51922,492 @@ var skillCommands = [
51859
51922
  }
51860
51923
  ];
51861
51924
 
51925
+ // dist/session/runSession.js
51926
+ import readline from "node:readline";
51927
+
51928
+ // dist/session/sessionArgv.js
51929
+ var resolveSessionCommand = (program2, cmd) => {
51930
+ const tokens = cmd.trim().split(/\s+/).filter(Boolean);
51931
+ if (tokens.length === 0) {
51932
+ return { ok: false, code: "session_invalid_request", message: "cmd must name a command" };
51933
+ }
51934
+ let current = program2;
51935
+ const path25 = [];
51936
+ for (const token of tokens) {
51937
+ const next = current.commands.find((candidate) => candidate.name() === token || candidate.aliases().includes(token));
51938
+ if (!next) {
51939
+ const context = path25.length > 0 ? ` under "${path25.join(" ")}"` : "";
51940
+ return { ok: false, code: "session_unknown_command", message: `Unknown command "${token}"${context}.` };
51941
+ }
51942
+ current = next;
51943
+ path25.push(next.name());
51944
+ }
51945
+ return { ok: true, command: current, path: path25 };
51946
+ };
51947
+ var buildSessionArgv = (input) => {
51948
+ const resolved = resolveSessionCommand(input.program, input.request.cmd);
51949
+ if (!resolved.ok) {
51950
+ return resolved;
51951
+ }
51952
+ const blocked = rejectNonSessionCommand(resolved.path);
51953
+ if (blocked) {
51954
+ return blocked;
51955
+ }
51956
+ const tail = input.request.argv ? [...input.request.argv] : buildArgvFromArgs(resolved.command, input.request.args ?? {});
51957
+ if (isArgvFailure(tail)) {
51958
+ return tail;
51959
+ }
51960
+ const argv = [...resolved.path];
51961
+ if (takesWatcherId(resolved.command) && tail[0] !== input.watcherId) {
51962
+ argv.push(input.watcherId);
51963
+ }
51964
+ argv.push(...tail);
51965
+ if (declaresOption(resolved.command, "json") && !tail.some(isJsonFlag)) {
51966
+ argv.push("--json");
51967
+ }
51968
+ const rejected = rejectStdinInput(argv, resolved.path);
51969
+ if (rejected) {
51970
+ return rejected;
51971
+ }
51972
+ return { ok: true, argv, resolved };
51973
+ };
51974
+ var NON_SESSION_COMMANDS = new Set(["session", "start", "chrome start", "watcher start", "watcher native-host", "logs tail", "net tail", "net sse"]);
51975
+ var rejectNonSessionCommand = (path25) => {
51976
+ const name = path25.join(" ");
51977
+ if (!NON_SESSION_COMMANDS.has(name)) {
51978
+ return null;
51979
+ }
51980
+ return {
51981
+ ok: false,
51982
+ code: "session_command_rejected",
51983
+ message: `"${name}" runs until interrupted and cannot be dispatched from a session; run it as its own process.`
51984
+ };
51985
+ };
51986
+ var rejectStdinInput = (argv, path25) => {
51987
+ const readsStdin = argv.includes("--stdin") || STDIN_DASH_COMMANDS.has(path25[0]) && argv.includes("-");
51988
+ if (!readsStdin) {
51989
+ return null;
51990
+ }
51991
+ return {
51992
+ ok: false,
51993
+ code: "session_command_rejected",
51994
+ message: "stdin belongs to the session transport; pass the expression inline or with --file instead of reading stdin."
51995
+ };
51996
+ };
51997
+ var STDIN_DASH_COMMANDS = new Set(["eval", "eval-until"]);
51998
+ var isArgvFailure = (value) => !Array.isArray(value);
51999
+ var isJsonFlag = (token) => token === "--json" || token === "--no-json" || token === "--json-full";
52000
+ var takesWatcherId = (command) => command.registeredArguments[0]?.name() === "id";
52001
+ var declaresOption = (command, name) => findOptions(command, name).length > 0;
52002
+ var buildArgvFromArgs = (command, args) => {
52003
+ const names = positionalNames(command);
52004
+ const tokens = [];
52005
+ const positionals = {};
52006
+ for (const [key, value] of Object.entries(args)) {
52007
+ if (value === undefined)
52008
+ continue;
52009
+ const options = findOptions(command, key);
52010
+ if (options.length === 0) {
52011
+ if (!names.includes(camelCase(key))) {
52012
+ const path25 = commandPath(command);
52013
+ return {
52014
+ ok: false,
52015
+ code: "session_invalid_request",
52016
+ message: `Unknown argument "${key}" for command "${path25}". Run \`argus ${path25} --help\` for the accepted flags.`
52017
+ };
52018
+ }
52019
+ positionals[camelCase(key)] = value;
52020
+ continue;
52021
+ }
52022
+ const emitted = emitOption(options, key, value);
52023
+ if (isArgvFailure(emitted)) {
52024
+ return emitted;
52025
+ }
52026
+ tokens.push(...emitted);
52027
+ }
52028
+ const ordered = orderPositionals(names, positionals);
52029
+ if (isArgvFailure(ordered)) {
52030
+ return ordered;
52031
+ }
52032
+ return [...ordered, ...tokens];
52033
+ };
52034
+ var emitOption = (options, key, value) => {
52035
+ const positive = options.find((option) => !option.negate);
52036
+ const negated = options.find((option) => option.negate);
52037
+ const valued = options.find((option) => option.required || option.optional);
52038
+ if (valued) {
52039
+ const values = Array.isArray(value) ? value : [value];
52040
+ const tokens = [];
52041
+ for (const entry of values) {
52042
+ if (entry == null)
52043
+ continue;
52044
+ if (typeof entry === "object") {
52045
+ return { ok: false, code: "session_invalid_request", message: `Argument "${key}" must be a string, number, or boolean.` };
52046
+ }
52047
+ tokens.push(flagOf(valued), String(entry));
52048
+ }
52049
+ return tokens;
52050
+ }
52051
+ if (typeof value !== "boolean") {
52052
+ return { ok: false, code: "session_invalid_request", message: `Argument "${key}" is a switch and must be true or false.` };
52053
+ }
52054
+ const wanted = value ? positive : negated;
52055
+ return wanted ? [flagOf(wanted)] : [];
52056
+ };
52057
+ var orderPositionals = (declaredNames, values) => {
52058
+ const tokens = [];
52059
+ let missing = null;
52060
+ for (const name of declaredNames) {
52061
+ if (name === "id")
52062
+ continue;
52063
+ const value = values[name];
52064
+ if (value === undefined) {
52065
+ missing ??= name;
52066
+ continue;
52067
+ }
52068
+ if (missing) {
52069
+ return {
52070
+ ok: false,
52071
+ code: "session_invalid_request",
52072
+ message: `Argument "${name}" cannot be set without "${missing}"; positional arguments are filled in order.`
52073
+ };
52074
+ }
52075
+ for (const entry of Array.isArray(value) ? value : [value]) {
52076
+ if (entry != null && typeof entry === "object") {
52077
+ return { ok: false, code: "session_invalid_request", message: `Argument "${name}" must be a string, number, or boolean.` };
52078
+ }
52079
+ tokens.push(String(entry));
52080
+ }
52081
+ }
52082
+ return tokens;
52083
+ };
52084
+ var findOptions = (command, key) => {
52085
+ const wanted = camelCase(key);
52086
+ return commandChain(command).flatMap((current) => current.options).filter((option) => option.attributeName() === wanted || option.name() === key || option.short === `-${key}`);
52087
+ };
52088
+ var positionalNames = (command) => command.registeredArguments.map((argument) => camelCase(argument.name()));
52089
+ var flagOf = (option) => option.long ?? option.short ?? `--${option.name()}`;
52090
+ var commandPath = (command) => commandChain(command).map((current) => current.name()).reverse().join(" ");
52091
+ var commandChain = (command) => {
52092
+ const chain = [];
52093
+ for (let current = command;current?.parent; current = current.parent) {
52094
+ chain.push(current);
52095
+ }
52096
+ return chain;
52097
+ };
52098
+ var camelCase = (value) => value.replace(/[-_]([a-z0-9])/g, (_4, character) => character.toUpperCase());
52099
+
52100
+ // dist/session/sessionDispatch.js
52101
+ var dispatchSessionRequest = async (input) => {
52102
+ const { request } = input;
52103
+ const respond = createResponder(request, Date.now());
52104
+ const timeoutMs = resolveTimeoutMs(request.timeout, input.defaultTimeoutMs);
52105
+ if (timeoutMs == null) {
52106
+ return respond.failure({ message: `Invalid timeout "${String(request.timeout)}".`, code: "session_invalid_request" }, 2);
52107
+ }
52108
+ const built = buildSessionArgv({ program: input.program, request, watcherId: input.watcherId });
52109
+ if (!built.ok) {
52110
+ return respond.failure({ message: built.message, code: built.code }, 2);
52111
+ }
52112
+ const sink = { stdout: [], stderr: [] };
52113
+ process.exitCode = 0;
52114
+ const running = input.capture.run(sink, async () => {
52115
+ try {
52116
+ await input.program.parseAsync(built.argv, { from: "user" });
52117
+ return null;
52118
+ } catch (error) {
52119
+ return error;
52120
+ }
52121
+ });
52122
+ const settled = await raceWithTimeout(running, timeoutMs);
52123
+ const stderr = sink.stderr.join("");
52124
+ if (settled.timedOut) {
52125
+ return respond.failure({ message: `Request timed out after ${timeoutMs}ms.`, code: "session_request_timeout" }, 1, stderr);
52126
+ }
52127
+ const exitCode = typeof process.exitCode === "number" ? process.exitCode : 0;
52128
+ process.exitCode = 0;
52129
+ const stdout = sink.stdout.join("");
52130
+ if (settled.error) {
52131
+ return fromThrownError(respond, settled.error, stdout, stderr);
52132
+ }
52133
+ if (exitCode !== 0) {
52134
+ return respond.failure(errorDetailFrom(stdout, stderr), exitCode, stderr);
52135
+ }
52136
+ return respond.success(stdout, stderr);
52137
+ };
52138
+ var fromThrownError = (respond, error, stdout, stderr) => {
52139
+ if (!(error instanceof CommanderError)) {
52140
+ return respond.failure({ message: formatError(error), code: "session_command_failed" }, 1, stderr);
52141
+ }
52142
+ if (error.exitCode === 0) {
52143
+ return respond.success(stdout, stderr);
52144
+ }
52145
+ return respond.failure({ message: error.message, code: "session_invalid_request" }, error.exitCode || 2, stderr);
52146
+ };
52147
+ var decodeStdout = (stdout) => {
52148
+ const lines = stdout.split(`
52149
+ `).filter((line) => line.trim() !== "");
52150
+ if (lines.length === 0) {
52151
+ return { result: null };
52152
+ }
52153
+ const documents = [];
52154
+ for (const line of lines) {
52155
+ try {
52156
+ documents.push(JSON.parse(line));
52157
+ } catch {
52158
+ return { result: stdout, raw: true };
52159
+ }
52160
+ }
52161
+ return documents.length === 1 ? { result: documents[0] } : { result: documents, stream: true };
52162
+ };
52163
+ var errorDetailFrom = (stdout, stderr) => {
52164
+ const document = decodeStdout(stdout).result;
52165
+ if (document && typeof document === "object" && document.ok === false) {
52166
+ const detail = document.error;
52167
+ if (detail?.message) {
52168
+ return detail;
52169
+ }
52170
+ }
52171
+ const message = stderr.trim().split(`
52172
+ `).filter(Boolean).at(-1);
52173
+ return { message: message ?? "Command failed.", code: "session_command_failed" };
52174
+ };
52175
+ var createResponder = (request, startedAt) => {
52176
+ const id = request.id === undefined ? {} : { id: request.id };
52177
+ const trailer = (stderr) => ({ durationMs: Date.now() - startedAt, ...stderr === "" ? {} : { stderr } });
52178
+ return {
52179
+ success: (stdout, stderr) => ({ ...id, ok: true, ...decodeStdout(stdout), ...trailer(stderr) }),
52180
+ failure: (error, exitCode, stderr = "") => ({ ...id, ok: false, error, exitCode, ...trailer(stderr) })
52181
+ };
52182
+ };
52183
+ var resolveTimeoutMs = (timeout, fallbackMs) => {
52184
+ if (timeout == null) {
52185
+ return fallbackMs;
52186
+ }
52187
+ if (typeof timeout === "number") {
52188
+ return timeout;
52189
+ }
52190
+ return parseDurationMs(timeout, "ms");
52191
+ };
52192
+ var raceWithTimeout = async (running, timeoutMs) => {
52193
+ if (timeoutMs <= 0) {
52194
+ return { timedOut: false, error: await running };
52195
+ }
52196
+ let timer;
52197
+ const watchdog = new Promise((resolve2) => {
52198
+ timer = setTimeout(() => resolve2({ timedOut: true }), timeoutMs);
52199
+ });
52200
+ try {
52201
+ return await Promise.race([running.then((error) => ({ timedOut: false, error })), watchdog]);
52202
+ } finally {
52203
+ clearTimeout(timer);
52204
+ }
52205
+ };
52206
+
52207
+ // dist/session/stdioCapture.js
52208
+ import { AsyncLocalStorage } from "node:async_hooks";
52209
+ var installStdioCapture = () => {
52210
+ const storage2 = new AsyncLocalStorage;
52211
+ const originalStdoutWrite = process.stdout.write.bind(process.stdout);
52212
+ const originalStderrWrite = process.stderr.write.bind(process.stderr);
52213
+ process.stdout.write = createCapturingWrite(storage2, originalStdoutWrite, (sink) => sink.stdout, false);
52214
+ process.stderr.write = createCapturingWrite(storage2, originalStderrWrite, (sink) => sink.stderr, true);
52215
+ return {
52216
+ run: (sink, body) => storage2.run(sink, body),
52217
+ writeStdout: (text) => {
52218
+ originalStdoutWrite(text);
52219
+ },
52220
+ restore: () => {
52221
+ process.stdout.write = originalStdoutWrite;
52222
+ process.stderr.write = originalStderrWrite;
52223
+ }
52224
+ };
52225
+ };
52226
+ var createCapturingWrite = (storage2, original, select, mirror) => {
52227
+ const forward = original;
52228
+ return (chunk, encoding, callback) => {
52229
+ const sink = storage2.getStore();
52230
+ if (!sink) {
52231
+ return forward(chunk, encoding, callback);
52232
+ }
52233
+ select(sink).push(decodeChunk(chunk, encoding));
52234
+ if (mirror) {
52235
+ forward(chunk, encoding);
52236
+ }
52237
+ const done = typeof encoding === "function" ? encoding : callback;
52238
+ if (typeof done === "function") {
52239
+ done();
52240
+ }
52241
+ return true;
52242
+ };
52243
+ };
52244
+ var decodeChunk = (chunk, encoding) => {
52245
+ if (typeof chunk === "string") {
52246
+ return chunk;
52247
+ }
52248
+ const bufferEncoding = typeof encoding === "string" ? encoding : "utf8";
52249
+ return Buffer.from(chunk).toString(bufferEncoding);
52250
+ };
52251
+
52252
+ // dist/session/runSession.js
52253
+ var DEFAULT_REQUEST_TIMEOUT_MS = 120000;
52254
+ var WATCHER_PROBE_TIMEOUT_MS = 1500;
52255
+ var runSession = async (id, options) => {
52256
+ routeConsoleToStderr();
52257
+ const output = createOutput({ json: true });
52258
+ const defaultTimeoutMs = resolveDefaultTimeout(options, output);
52259
+ if (defaultTimeoutMs == null)
52260
+ return;
52261
+ const resolved = await resolveWatcherOrExit({ id }, output);
52262
+ if (!resolved)
52263
+ return;
52264
+ const program2 = await buildSessionProgram();
52265
+ const capture = installStdioCapture();
52266
+ const writeLine = (line) => capture.writeStdout(`${JSON.stringify(line)}
52267
+ `);
52268
+ writeLine(readyEvent(resolved.watcher));
52269
+ const exitCode = await serveRequests({
52270
+ program: program2,
52271
+ capture,
52272
+ writeLine,
52273
+ output,
52274
+ watcher: resolved.watcher,
52275
+ defaultTimeoutMs,
52276
+ reconnect: options.reconnect === true
52277
+ });
52278
+ capture.restore();
52279
+ await flushStdout();
52280
+ process.exit(exitCode);
52281
+ };
52282
+ var serveRequests = async (input) => {
52283
+ const lines = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
52284
+ try {
52285
+ for await (const line of lines) {
52286
+ if (line.trim() === "")
52287
+ continue;
52288
+ const request = parseRequestLine(line);
52289
+ if (!request.ok) {
52290
+ input.writeLine(request.response);
52291
+ continue;
52292
+ }
52293
+ if (request.value.cmd === "quit") {
52294
+ input.writeLine(controlResponse(request.value.id, { closed: true }));
52295
+ return 0;
52296
+ }
52297
+ if (request.value.cmd === "ping") {
52298
+ input.writeLine(controlResponse(request.value.id, { pong: true, watcher: input.watcher.id }));
52299
+ continue;
52300
+ }
52301
+ const response = await dispatchSessionRequest({
52302
+ program: input.program,
52303
+ capture: input.capture,
52304
+ request: request.value,
52305
+ watcherId: input.watcher.id,
52306
+ defaultTimeoutMs: input.defaultTimeoutMs
52307
+ });
52308
+ input.writeLine(response);
52309
+ if (await watcherLost(response, input)) {
52310
+ input.output.writeWarn(`Watcher ${input.watcher.id} is no longer reachable; closing session.`);
52311
+ return 1;
52312
+ }
52313
+ }
52314
+ } finally {
52315
+ lines.close();
52316
+ }
52317
+ return 0;
52318
+ };
52319
+ var watcherLost = async (response, input) => {
52320
+ if (response.ok || input.reconnect)
52321
+ return false;
52322
+ if (response.error.code && FRAMING_ERROR_CODES.has(response.error.code))
52323
+ return false;
52324
+ return !await watcherReachable(input.watcher.id);
52325
+ };
52326
+ var FRAMING_ERROR_CODES = new Set(["session_invalid_request", "session_unknown_command", "session_command_rejected"]);
52327
+ var watcherReachable = async (id) => {
52328
+ const resolved = await resolveWatcher({ id });
52329
+ if (!resolved.ok)
52330
+ return false;
52331
+ try {
52332
+ await fetchWatcherJson(resolved.watcher, { path: "/status", timeoutMs: WATCHER_PROBE_TIMEOUT_MS });
52333
+ return true;
52334
+ } catch {
52335
+ return false;
52336
+ }
52337
+ };
52338
+ var parseRequestLine = (line) => {
52339
+ let decoded;
52340
+ try {
52341
+ decoded = JSON.parse(line);
52342
+ } catch (error) {
52343
+ return { ok: false, response: framingError(`Request is not valid JSON: ${error.message}`) };
52344
+ }
52345
+ const parsed = SESSION_REQUEST_SCHEMA.parse(decoded);
52346
+ if (!parsed.ok) {
52347
+ const id = decoded?.id;
52348
+ return { ok: false, response: framingError(formatProtocolValidationIssues(parsed.issues), id) };
52349
+ }
52350
+ return { ok: true, value: parsed.value };
52351
+ };
52352
+ var framingError = (message, id) => ({
52353
+ ...idOf(id),
52354
+ ok: false,
52355
+ error: { message, code: "session_invalid_request" },
52356
+ exitCode: 2,
52357
+ durationMs: 0
52358
+ });
52359
+ var controlResponse = (id, result) => ({ ...idOf(id), ok: true, result, durationMs: 0 });
52360
+ var idOf = (id) => id === undefined ? {} : { id };
52361
+ var buildSessionProgram = async () => {
52362
+ const program2 = createProgram({ mode: "session" });
52363
+ for (const registerProgramPart of coreProgramRegistrars) {
52364
+ registerProgramPart(program2);
52365
+ }
52366
+ await registerPlugins(program2);
52367
+ return program2;
52368
+ };
52369
+ var readyEvent = (watcher2) => ({
52370
+ type: "ready",
52371
+ protocolVersion: SESSION_PROTOCOL_VERSION,
52372
+ argusVersion: package_default.version,
52373
+ watcher: { id: watcher2.id, host: watcher2.host, port: watcher2.port }
52374
+ });
52375
+ var resolveDefaultTimeout = (options, output) => {
52376
+ if (options.requestTimeout == null) {
52377
+ return DEFAULT_REQUEST_TIMEOUT_MS;
52378
+ }
52379
+ const parsed = parseDurationMs(options.requestTimeout, "ms");
52380
+ if (parsed == null || parsed < 0) {
52381
+ usageError({ json: output.json }, `Invalid --request-timeout: ${options.requestTimeout}`);
52382
+ return null;
52383
+ }
52384
+ return parsed;
52385
+ };
52386
+ var flushStdout = () => new Promise((resolve2) => process.stdout.write("", () => resolve2()));
52387
+
52388
+ // dist/cli/register/sessionCommands.js
52389
+ var sessionCommands = [
52390
+ {
52391
+ name: "session",
52392
+ description: "Serve JSONL commands over stdin/stdout against one watcher, in a single process",
52393
+ arguments: [{ flags: "[id]", description: "Watcher id to pin the session to" }],
52394
+ options: [
52395
+ { flags: "--request-timeout <duration>", description: "Per-request watchdog when the request omits one (default: 120s; 0 disables)" },
52396
+ { flags: "--reconnect", description: "Stay alive when the watcher disappears and re-resolve it by id on the next request" },
52397
+ { ...jsonOption, description: "Accepted for symmetry; the transport is always JSONL" }
52398
+ ],
52399
+ examples: [
52400
+ "argus session app",
52401
+ "argus session app --request-timeout 30s",
52402
+ "argus session app --reconnect",
52403
+ `echo '{"id":1,"cmd":"eval","args":{"expression":"location.href"}}' | argus session app`
52404
+ ],
52405
+ action: async (id, options) => {
52406
+ await runSession(id, options);
52407
+ }
52408
+ }
52409
+ ];
52410
+
51862
52411
  // dist/cli/register/index.js
51863
52412
  var coreCommandDefinitions = [
51864
52413
  ...quickAccessCommands,
@@ -51885,6 +52434,7 @@ var coreCommandDefinitions = [
51885
52434
  ...recordCommands,
51886
52435
  ...traceCommands,
51887
52436
  ...configCommands,
52437
+ ...sessionCommands,
51888
52438
  ...pluginCommands,
51889
52439
  ...skillCommands,
51890
52440
  ...extensionCommands