omowright 0.3.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -69,6 +69,7 @@ var require_constants = __commonJS(function(exports, module) {
69
69
 
70
70
  // node_modules/ws/lib/buffer-util.js
71
71
  var require_buffer_util = __commonJS(function(exports, module) {
72
+ var { websocketMask, websocketUnmask } = __require("http");
72
73
  var { EMPTY_BUFFER } = require_constants();
73
74
  var FastBuffer = Buffer[Symbol.species];
74
75
  function concat(list, totalLength) {
@@ -126,7 +127,20 @@ var require_buffer_util = __commonJS(function(exports, module) {
126
127
  toBuffer,
127
128
  unmask: _unmask
128
129
  };
129
- if (!process.env.WS_NO_BUFFER_UTIL) {
130
+ if (websocketMask) {
131
+ module.exports.mask = function(source, mask, output, offset, length) {
132
+ if (length < 24)
133
+ _mask(source, mask, output, offset, length);
134
+ else
135
+ websocketMask(source, mask, output, offset, length);
136
+ };
137
+ module.exports.unmask = function(buffer, mask) {
138
+ if (buffer.length < 24)
139
+ _unmask(buffer, mask);
140
+ else
141
+ websocketUnmask(buffer, mask);
142
+ };
143
+ } else if (!process.env.WS_NO_BUFFER_UTIL) {
130
144
  try {
131
145
  const bufferUtil = (()=>{throw new Error("Cannot require module "+"bufferutil");})();
132
146
  module.exports.mask = function(source, mask2, output, offset, length) {
@@ -878,6 +892,7 @@ var require_receiver = __commonJS(function(exports, module) {
878
892
  unmask(data, this._mask);
879
893
  }
880
894
  }
895
+ this._mask = undefined;
881
896
  if (this._opcode > 7) {
882
897
  this.controlMessage(data, cb);
883
898
  return;
@@ -1114,13 +1129,16 @@ var require_sender = __commonJS(function(exports, module) {
1114
1129
  target[2] = target[3] = 0;
1115
1130
  target.writeUIntBE(dataLength, 4, 6);
1116
1131
  }
1117
- if (!options.mask)
1118
- return [target, data];
1132
+ if (!options.mask) {
1133
+ return dataLength ? [target, data] : [target];
1134
+ }
1119
1135
  target[1] |= 128;
1120
1136
  target[offset - 4] = mask[0];
1121
1137
  target[offset - 3] = mask[1];
1122
1138
  target[offset - 2] = mask[2];
1123
1139
  target[offset - 1] = mask[3];
1140
+ if (!dataLength)
1141
+ return [target];
1124
1142
  if (skipMasking)
1125
1143
  return [target, data];
1126
1144
  if (merge) {
@@ -1703,6 +1721,7 @@ var require_websocket = __commonJS(function(exports, module) {
1703
1721
  var https = __require("https");
1704
1722
  var http = __require("http");
1705
1723
  var net = __require("net");
1724
+ var querystring = __require("querystring");
1706
1725
  var tls = __require("tls");
1707
1726
  var { randomBytes, createHash } = __require("crypto");
1708
1727
  var { Duplex, Readable } = __require("stream");
@@ -1754,21 +1773,38 @@ var require_websocket = __commonJS(function(exports, module) {
1754
1773
  this._isServer = false;
1755
1774
  this._redirects = 0;
1756
1775
  if (protocols === undefined) {
1757
- protocols = [];
1776
+ if (!options || options.protocols === undefined) {
1777
+ protocols = [];
1778
+ } else if (Array.isArray(options.protocols)) {
1779
+ protocols = options.protocols;
1780
+ } else {
1781
+ protocols = [options.protocols];
1782
+ }
1758
1783
  } else if (!Array.isArray(protocols)) {
1759
1784
  if (typeof protocols === "object" && protocols !== null) {
1760
1785
  options = protocols;
1761
- protocols = [];
1786
+ if (options.protocols === undefined) {
1787
+ protocols = [];
1788
+ } else if (Array.isArray(options.protocols)) {
1789
+ protocols = options.protocols;
1790
+ } else {
1791
+ protocols = [options.protocols];
1792
+ }
1762
1793
  } else {
1763
1794
  protocols = [protocols];
1764
1795
  }
1765
1796
  }
1766
- initAsClient(this, address, protocols, options);
1797
+ options = initAsClient(this, address, protocols, options);
1767
1798
  } else {
1768
- this._autoPong = options.autoPong;
1769
- this._closeTimeout = options.closeTimeout;
1770
1799
  this._isServer = true;
1771
1800
  }
1801
+ if (options.autoPong) {
1802
+ this._autoPong = true;
1803
+ this._autoPongComplete = () => autoPongComplete(this);
1804
+ this._pendingAutoPongs = 0;
1805
+ this._maxPendingAutoPongs = options.maxPendingAutoPongs | 0;
1806
+ }
1807
+ this._closeTimeout = options.closeTimeout;
1772
1808
  }
1773
1809
  get binaryType() {
1774
1810
  return this._binaryType;
@@ -1877,7 +1913,6 @@ var require_websocket = __commonJS(function(exports, module) {
1877
1913
  }
1878
1914
  return;
1879
1915
  }
1880
- this._readyState = WebSocket.CLOSING;
1881
1916
  this._sender.close(code, data, !this._isServer, (err) => {
1882
1917
  if (err)
1883
1918
  return;
@@ -1886,6 +1921,7 @@ var require_websocket = __commonJS(function(exports, module) {
1886
1921
  this._socket.end();
1887
1922
  }
1888
1923
  });
1924
+ this._readyState = WebSocket.CLOSING;
1889
1925
  setCloseTimer(this);
1890
1926
  }
1891
1927
  pause() {
@@ -2065,6 +2101,7 @@ var require_websocket = __commonJS(function(exports, module) {
2065
2101
  maxBufferedChunks: 256 * 1024,
2066
2102
  maxFragments: 16 * 1024,
2067
2103
  maxPayload: 100 * 1024 * 1024,
2104
+ maxPendingAutoPongs: 60,
2068
2105
  skipUTF8Validation: false,
2069
2106
  perMessageDeflate: true,
2070
2107
  followRedirects: false,
@@ -2073,14 +2110,13 @@ var require_websocket = __commonJS(function(exports, module) {
2073
2110
  socketPath: undefined,
2074
2111
  hostname: undefined,
2075
2112
  protocol: undefined,
2113
+ protocols: undefined,
2076
2114
  timeout: undefined,
2077
2115
  method: "GET",
2078
2116
  host: undefined,
2079
2117
  path: undefined,
2080
2118
  port: undefined
2081
2119
  };
2082
- websocket._autoPong = opts.autoPong;
2083
- websocket._closeTimeout = opts.closeTimeout;
2084
2120
  if (!protocolVersions.includes(opts.protocolVersion)) {
2085
2121
  throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} ` + `(supported versions: ${protocolVersions.join(", ")})`);
2086
2122
  }
@@ -2094,10 +2130,9 @@ var require_websocket = __commonJS(function(exports, module) {
2094
2130
  throw new SyntaxError(`Invalid URL: ${address}`);
2095
2131
  }
2096
2132
  }
2097
- if (parsedUrl.protocol === "http:") {
2098
- parsedUrl.protocol = "ws:";
2099
- } else if (parsedUrl.protocol === "https:") {
2100
- parsedUrl.protocol = "wss:";
2133
+ if (parsedUrl.protocol === "http:" || parsedUrl.protocol === "https:") {
2134
+ parsedUrl = new URL2(parsedUrl);
2135
+ parsedUrl.protocol = parsedUrl.protocol === "http:" ? "ws:" : "wss:";
2101
2136
  }
2102
2137
  websocket._url = parsedUrl.href;
2103
2138
  const isSecure = parsedUrl.protocol === "wss:";
@@ -2164,12 +2199,19 @@ var require_websocket = __commonJS(function(exports, module) {
2164
2199
  }
2165
2200
  }
2166
2201
  if (parsedUrl.username || parsedUrl.password) {
2167
- opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
2202
+ const username = querystring.unescape(parsedUrl.username);
2203
+ const password = querystring.unescape(parsedUrl.password);
2204
+ opts.auth = `${username}:${password}`;
2168
2205
  }
2169
2206
  if (isIpcUrl) {
2170
- const parts = opts.path.split(":");
2171
- opts.socketPath = parts[0];
2172
- opts.path = parts[1];
2207
+ const i = opts.path.indexOf(":");
2208
+ if (i === -1) {
2209
+ opts.socketPath = opts.path;
2210
+ opts.path = "";
2211
+ } else {
2212
+ opts.socketPath = opts.path.slice(0, i);
2213
+ opts.path = opts.path.slice(i + 1);
2214
+ }
2173
2215
  }
2174
2216
  let req;
2175
2217
  if (opts.followRedirects) {
@@ -2313,6 +2355,7 @@ var require_websocket = __commonJS(function(exports, module) {
2313
2355
  } else {
2314
2356
  req.end();
2315
2357
  }
2358
+ return opts;
2316
2359
  }
2317
2360
  function emitErrorAndClose(websocket, err) {
2318
2361
  websocket._readyState = WebSocket.CLOSING;
@@ -2364,8 +2407,13 @@ var require_websocket = __commonJS(function(exports, module) {
2364
2407
  function receiverOnConclude(code, reason) {
2365
2408
  const websocket = this[kWebSocket];
2366
2409
  websocket._closeFrameReceived = true;
2367
- websocket._closeMessage = reason;
2368
2410
  websocket._closeCode = code;
2411
+ if (reason.length === 0) {
2412
+ websocket._closeMessage = EMPTY_BUFFER;
2413
+ } else {
2414
+ websocket._closeMessage = Buffer.allocUnsafeSlow(reason.length);
2415
+ websocket._closeMessage.set(reason);
2416
+ }
2369
2417
  if (websocket._socket[kWebSocket] === undefined)
2370
2418
  return;
2371
2419
  websocket._socket.removeListener("data", socketOnData);
@@ -2400,10 +2448,19 @@ var require_websocket = __commonJS(function(exports, module) {
2400
2448
  }
2401
2449
  function receiverOnPing(data) {
2402
2450
  const websocket = this[kWebSocket];
2403
- if (websocket._autoPong)
2404
- websocket.pong(data, !this._isServer, NOOP);
2451
+ if (websocket._autoPong && websocket.readyState === WebSocket.OPEN) {
2452
+ if (websocket._maxPendingAutoPongs > 0 && websocket._pendingAutoPongs >= websocket._maxPendingAutoPongs) {
2453
+ websocket.terminate();
2454
+ } else {
2455
+ websocket._pendingAutoPongs++;
2456
+ websocket.pong(data, !this._isServer, websocket._autoPongComplete);
2457
+ }
2458
+ }
2405
2459
  websocket.emit("ping", data);
2406
2460
  }
2461
+ function autoPongComplete(websocket) {
2462
+ websocket._pendingAutoPongs--;
2463
+ }
2407
2464
  function receiverOnPong(data) {
2408
2465
  this[kWebSocket].emit("pong", data);
2409
2466
  }
@@ -2642,6 +2699,7 @@ var require_websocket_server = __commonJS(function(exports, module) {
2642
2699
  maxBufferedChunks: 256 * 1024,
2643
2700
  maxFragments: 16 * 1024,
2644
2701
  maxPayload: 100 * 1024 * 1024,
2702
+ maxPendingAutoPongs: 60,
2645
2703
  skipUTF8Validation: false,
2646
2704
  perMessageDeflate: false,
2647
2705
  handleProtocols: null,
@@ -24399,6 +24457,29 @@ async function emulateMedia(options = {}) {
24399
24457
  await updateSessions(this, state);
24400
24458
  }
24401
24459
 
24460
+ // src/redact-value.ts
24461
+ function redactValue(error, value) {
24462
+ if (value.length === 0)
24463
+ return error;
24464
+ const replacement = `<redacted, ${value.length} chars>`;
24465
+ const forms = [...new Set([value, JSON.stringify(value).slice(1, -1)])].toSorted((left, right) => right.length - left.length).map((form) => form.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
24466
+ const pattern = new RegExp(`(?<![\\p{L}\\p{N}])(?:${forms.join("|")})(?![\\p{L}\\p{N}])`, "gu");
24467
+ const scrub = (text) => text.replace(pattern, replacement);
24468
+ if (typeof error === "string")
24469
+ return scrub(error);
24470
+ const seen = new Set;
24471
+ for (let link = error;link instanceof Error && !seen.has(link); link = link.cause) {
24472
+ seen.add(link);
24473
+ link.message = scrub(link.message);
24474
+ if (link.stack !== undefined)
24475
+ link.stack = scrub(link.stack);
24476
+ const data = Reflect.get(link, "data");
24477
+ if (data !== undefined)
24478
+ Reflect.set(link, "data", JSON.parse(scrub(JSON.stringify(data) ?? "null")));
24479
+ }
24480
+ return error;
24481
+ }
24482
+
24402
24483
  // src/core.ts
24403
24484
  function definedOrThrow(value) {
24404
24485
  if (value === undefined)
@@ -27407,8 +27488,12 @@ function createLocatorClass() {
27407
27488
  await clickElement(this.#e, jn, xn, this.#e.modifierState);
27408
27489
  }
27409
27490
  async fill(xn) {
27410
- let jn = await this.#r();
27411
- await fillElement(this.#e, jn, xn);
27491
+ try {
27492
+ let jn = await this.#r();
27493
+ await fillElement(this.#e, jn, xn);
27494
+ } catch (jn) {
27495
+ throw redactValue(jn, xn);
27496
+ }
27412
27497
  }
27413
27498
  async selectOption(xn) {
27414
27499
  let jn = await this.#r();
@@ -27427,8 +27512,12 @@ function createLocatorClass() {
27427
27512
  await pressElement(this.#e, jn, xn, this.#e.keyboard);
27428
27513
  }
27429
27514
  async pressSequentially(xn, jn = {}) {
27430
- let Vn = await this.#r();
27431
- await pressSequentiallyElement(this.#e, Vn, xn, jn.delay, this.#e.keyboard);
27515
+ try {
27516
+ let Vn = await this.#r();
27517
+ await pressSequentiallyElement(this.#e, Vn, xn, jn.delay, this.#e.keyboard);
27518
+ } catch (Vn) {
27519
+ throw redactValue(Vn, xn);
27520
+ }
27432
27521
  }
27433
27522
  async hover() {
27434
27523
  let xn = await this.#r();
@@ -30336,6 +30425,104 @@ async function acquireSharedConnection(webSocketDebuggerUrl, options, { open, ti
30336
30425
  }
30337
30426
  }
30338
30427
 
30428
+ // src/emulate.ts
30429
+ var DEVICE_PRESETS = Object.freeze({
30430
+ "iphone-14": {
30431
+ width: 390,
30432
+ height: 844,
30433
+ deviceScaleFactor: 3,
30434
+ mobile: true,
30435
+ hasTouch: true,
30436
+ userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 16_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Mobile/15E148 Safari/604.1",
30437
+ platform: "iPhone"
30438
+ },
30439
+ "pixel-7": {
30440
+ width: 412,
30441
+ height: 915,
30442
+ deviceScaleFactor: 2.625,
30443
+ mobile: true,
30444
+ hasTouch: true,
30445
+ userAgent: "Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Mobile Safari/537.36",
30446
+ platform: "Linux armv8l"
30447
+ },
30448
+ "ipad-air": {
30449
+ width: 820,
30450
+ height: 1180,
30451
+ deviceScaleFactor: 2,
30452
+ mobile: true,
30453
+ hasTouch: true,
30454
+ userAgent: "Mozilla/5.0 (iPad; CPU OS 16_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Mobile/15E148 Safari/604.1",
30455
+ platform: "MacIntel"
30456
+ },
30457
+ "desktop-1440": {
30458
+ width: 1440,
30459
+ height: 900,
30460
+ deviceScaleFactor: 1,
30461
+ mobile: false,
30462
+ hasTouch: false,
30463
+ userAgent: undefined,
30464
+ platform: undefined
30465
+ }
30466
+ });
30467
+ var presetsByName = DEVICE_PRESETS;
30468
+ var originalUAs = new WeakMap;
30469
+ var emulatedDevices = new WeakMap;
30470
+ function emulatedDevice(page) {
30471
+ return emulatedDevices.get(page);
30472
+ }
30473
+ async function emulate(page, presetNameOrObject) {
30474
+ let preset;
30475
+ if (presetNameOrObject === null) {
30476
+ preset = null;
30477
+ } else if (typeof presetNameOrObject === "string") {
30478
+ const named = presetsByName[presetNameOrObject];
30479
+ if (!named) {
30480
+ throw new Error(`unknown device preset: ${presetNameOrObject}`);
30481
+ }
30482
+ preset = named;
30483
+ } else {
30484
+ preset = presetNameOrObject;
30485
+ }
30486
+ const sessionId = await page.resolveSessionId();
30487
+ if (preset === null) {
30488
+ await page.cdp.send("Emulation.clearDeviceMetricsOverride", {}, sessionId);
30489
+ await page.cdp.send("Emulation.setTouchEmulationEnabled", { enabled: false }, sessionId);
30490
+ emulatedDevices.delete(page);
30491
+ const originalUA = originalUAs.get(page);
30492
+ if (originalUA) {
30493
+ await page.cdp.send("Emulation.setUserAgentOverride", { userAgent: originalUA }, sessionId);
30494
+ }
30495
+ } else {
30496
+ if (!originalUAs.has(page)) {
30497
+ const ua = await page.evaluate(() => navigator.userAgent);
30498
+ originalUAs.set(page, ua);
30499
+ }
30500
+ await page.cdp.send("Emulation.setDeviceMetricsOverride", {
30501
+ width: preset.width,
30502
+ height: preset.height,
30503
+ deviceScaleFactor: preset.deviceScaleFactor,
30504
+ mobile: preset.mobile,
30505
+ screenWidth: preset.width,
30506
+ screenHeight: preset.height
30507
+ }, sessionId);
30508
+ emulatedDevices.set(page, preset);
30509
+ await page.cdp.send("Emulation.setTouchEmulationEnabled", {
30510
+ enabled: preset.hasTouch,
30511
+ maxTouchPoints: preset.hasTouch ? 5 : 1
30512
+ }, sessionId);
30513
+ if (preset.userAgent !== undefined) {
30514
+ await page.cdp.send("Emulation.setUserAgentOverride", {
30515
+ userAgent: preset.userAgent,
30516
+ platform: preset.platform
30517
+ }, sessionId);
30518
+ }
30519
+ }
30520
+ if (page.refreshViewportSize) {
30521
+ await page.refreshViewportSize();
30522
+ }
30523
+ return preset;
30524
+ }
30525
+
30339
30526
  // src/agent-tabs.ts
30340
30527
  var managers = new WeakMap;
30341
30528
  var CAPABILITY = targetCreationCapability;
@@ -30439,13 +30626,13 @@ class AgentTabManager {
30439
30626
  const version = await this.#connection.cdp.send("Browser.getVersion").catch(() => null);
30440
30627
  return /Headless/i.test(version?.product ?? "");
30441
30628
  }
30442
- #queueRepin(record, viewport, reportErrors = false) {
30629
+ #queueRepin(record, viewport, reportErrors = false, device) {
30443
30630
  const size = { ...viewport };
30444
30631
  const operation = record.repinQueue.then(async () => {
30445
30632
  try {
30446
30633
  if (record.page === null)
30447
30634
  throw new TypeError("Cannot read properties of null (reading 'resolveSessionId')");
30448
- await repinViewport(record.page, size);
30635
+ await repinViewport(record.page, device ?? size, device);
30449
30636
  } catch (error) {
30450
30637
  if (reportErrors)
30451
30638
  console.warn(`[agent-tabs] viewport repin failed for ${record.targetId}`, error);
@@ -30459,7 +30646,7 @@ class AgentTabManager {
30459
30646
  return operation;
30460
30647
  }
30461
30648
  async#repin(record) {
30462
- await this.#queueRepin(record, record.viewport, true);
30649
+ await this.#queueRepin(record, record.viewport, true, record.page === null ? undefined : emulatedDevice(record.page));
30463
30650
  }
30464
30651
  async repin(tabOrTargetId, viewport = this.viewport) {
30465
30652
  const id = typeof tabOrTargetId === "string" ? tabOrTargetId : tabOrTargetId?.targetId;
@@ -31414,6 +31601,7 @@ class PipeCdpClient {
31414
31601
  #malformedFrameCount = 0;
31415
31602
  #events = new SerialEmitter;
31416
31603
  #connected = false;
31604
+ #closedByCaller = false;
31417
31605
  #commandTimeoutMs;
31418
31606
  #readinessTimeoutMs;
31419
31607
  #browserPath;
@@ -31459,6 +31647,7 @@ class PipeCdpClient {
31459
31647
  this.#dialogPolicy = normalizeDialogPolicy(policy);
31460
31648
  }
31461
31649
  async ensureConnected() {
31650
+ this.#closedByCaller = false;
31462
31651
  if (this.#connected)
31463
31652
  return;
31464
31653
  const stdio = ["ignore", "pipe", "pipe", "pipe", "pipe"];
@@ -31621,6 +31810,15 @@ ${tail}` : ""));
31621
31810
  if (String(method).startsWith("OmO.")) {
31622
31811
  throw Error(`Extension commands are unavailable over pipe transport: ${method}`);
31623
31812
  }
31813
+ if (this.#closedByCaller) {
31814
+ throw this.#commandError(CdpPipeClosedError, "CDP pipe client closed", {
31815
+ method,
31816
+ sessionId,
31817
+ targetId: this.#sessionTargets.get(sessionId),
31818
+ sentAt: performance.now(),
31819
+ receivedBytes: this.#receivedBytes
31820
+ });
31821
+ }
31624
31822
  await this.ensureConnected();
31625
31823
  return this.#dispatch(method, params, sessionId, opts);
31626
31824
  }
@@ -31679,6 +31877,7 @@ ${tail}` : ""));
31679
31877
  this.#failCommands(CdpSessionDetachedError, "Page closed", sessionId);
31680
31878
  }
31681
31879
  async close() {
31880
+ this.#closedByCaller = true;
31682
31881
  const child = this.#child;
31683
31882
  this.#child = undefined;
31684
31883
  if (child && child.exitCode === null) {
@@ -31686,7 +31885,7 @@ ${tail}` : ""));
31686
31885
  let quitRequested = false;
31687
31886
  if (this.#connected) {
31688
31887
  await Promise.race([
31689
- this.send("Browser.close", undefined, undefined, {
31888
+ this.#dispatch("Browser.close", undefined, undefined, {
31690
31889
  timeoutMs: GRACEFUL_CLOSE_TIMEOUT_MS
31691
31890
  }).then(() => {
31692
31891
  quitRequested = true;
@@ -34493,9 +34692,10 @@ var systemBinary = (...segments) => {
34493
34692
  throw new Error(`${file} is missing`);
34494
34693
  return file;
34495
34694
  };
34695
+ var RUN_TIMEOUT_MS = 60000;
34496
34696
  function run(file, args) {
34497
34697
  return new Promise((resolve, reject) => {
34498
- execFile3(file, args, { timeout: 15000, windowsHide: true, maxBuffer: 4 * 1024 * 1024, encoding: "utf8" }, (error, stdout, stderr) => {
34698
+ execFile3(file, args, { timeout: RUN_TIMEOUT_MS, windowsHide: true, maxBuffer: 4 * 1024 * 1024, encoding: "utf8" }, (error, stdout, stderr) => {
34499
34699
  if (error && (typeof error.code !== "number" || error.killed))
34500
34700
  reject(error);
34501
34701
  else
@@ -35397,97 +35597,6 @@ function createChromeApi2(connection, options = {}) {
35397
35597
  }
35398
35598
  return chrome;
35399
35599
  }
35400
- // src/emulate.ts
35401
- var DEVICE_PRESETS = Object.freeze({
35402
- "iphone-14": {
35403
- width: 390,
35404
- height: 844,
35405
- deviceScaleFactor: 3,
35406
- mobile: true,
35407
- hasTouch: true,
35408
- userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 16_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Mobile/15E148 Safari/604.1",
35409
- platform: "iPhone"
35410
- },
35411
- "pixel-7": {
35412
- width: 412,
35413
- height: 915,
35414
- deviceScaleFactor: 2.625,
35415
- mobile: true,
35416
- hasTouch: true,
35417
- userAgent: "Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Mobile Safari/537.36",
35418
- platform: "Linux armv8l"
35419
- },
35420
- "ipad-air": {
35421
- width: 820,
35422
- height: 1180,
35423
- deviceScaleFactor: 2,
35424
- mobile: true,
35425
- hasTouch: true,
35426
- userAgent: "Mozilla/5.0 (iPad; CPU OS 16_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Mobile/15E148 Safari/604.1",
35427
- platform: "MacIntel"
35428
- },
35429
- "desktop-1440": {
35430
- width: 1440,
35431
- height: 900,
35432
- deviceScaleFactor: 1,
35433
- mobile: false,
35434
- hasTouch: false,
35435
- userAgent: undefined,
35436
- platform: undefined
35437
- }
35438
- });
35439
- var presetsByName = DEVICE_PRESETS;
35440
- var originalUAs = new WeakMap;
35441
- async function emulate(page, presetNameOrObject) {
35442
- let preset;
35443
- if (presetNameOrObject === null) {
35444
- preset = null;
35445
- } else if (typeof presetNameOrObject === "string") {
35446
- const named = presetsByName[presetNameOrObject];
35447
- if (!named) {
35448
- throw new Error(`unknown device preset: ${presetNameOrObject}`);
35449
- }
35450
- preset = named;
35451
- } else {
35452
- preset = presetNameOrObject;
35453
- }
35454
- const sessionId = await page.resolveSessionId();
35455
- if (preset === null) {
35456
- await page.cdp.send("Emulation.clearDeviceMetricsOverride", {}, sessionId);
35457
- await page.cdp.send("Emulation.setTouchEmulationEnabled", { enabled: false }, sessionId);
35458
- const originalUA = originalUAs.get(page);
35459
- if (originalUA) {
35460
- await page.cdp.send("Emulation.setUserAgentOverride", { userAgent: originalUA }, sessionId);
35461
- }
35462
- } else {
35463
- if (!originalUAs.has(page)) {
35464
- const ua = await page.evaluate(() => navigator.userAgent);
35465
- originalUAs.set(page, ua);
35466
- }
35467
- await page.cdp.send("Emulation.setDeviceMetricsOverride", {
35468
- width: preset.width,
35469
- height: preset.height,
35470
- deviceScaleFactor: preset.deviceScaleFactor,
35471
- mobile: preset.mobile,
35472
- screenWidth: preset.width,
35473
- screenHeight: preset.height
35474
- }, sessionId);
35475
- await page.cdp.send("Emulation.setTouchEmulationEnabled", {
35476
- enabled: preset.hasTouch,
35477
- maxTouchPoints: preset.hasTouch ? 5 : 1
35478
- }, sessionId);
35479
- if (preset.userAgent !== undefined) {
35480
- await page.cdp.send("Emulation.setUserAgentOverride", {
35481
- userAgent: preset.userAgent,
35482
- platform: preset.platform
35483
- }, sessionId);
35484
- }
35485
- }
35486
- if (page.refreshViewportSize) {
35487
- await page.refreshViewportSize();
35488
- }
35489
- return preset;
35490
- }
35491
35600
  // src/frames-snapshot.ts
35492
35601
  var AUTO_ATTACH = { autoAttach: true, waitForDebuggerOnStart: false, flatten: true };
35493
35602
  var REF_PATTERN2 = /^(f\d+)?e\d+$/;
@@ -35594,7 +35703,7 @@ async function snapshotWithFrames(page, opts = {}) {
35594
35703
  // package.json
35595
35704
  var package_default = {
35596
35705
  name: "omowright",
35597
- version: "0.3.1",
35706
+ version: "0.3.3",
35598
35707
  description: "OmOWright browser automation for standard Chromium CDP endpoints.",
35599
35708
  keywords: [
35600
35709
  "accessibility-snapshot",
@@ -35640,35 +35749,38 @@ var package_default = {
35640
35749
  provenance: true
35641
35750
  },
35642
35751
  scripts: {
35643
- test: "bun test",
35752
+ test: "bun test --parallel",
35644
35753
  "test:node": "bun scripts/node-test.ts",
35645
35754
  "test:cloak-profile": "bun test test/cloak-profile.test.ts test/cloak-profile.integration.test.ts",
35646
- typecheck: "tsc --noEmit -p tsconfig.json",
35755
+ typecheck: "bun check --no-script --no-pretty -p tsconfig.json",
35647
35756
  "typecheck:control": "bun scripts/typecheck-control.ts",
35648
35757
  check: "bun run typecheck:control && bun run typecheck && bun run lint && bun run fmt:check",
35649
- lint: "oxlint --deny-warnings src bin bridge test scripts",
35758
+ lint: "oxlint --deny-warnings src bin bridge test scripts && bun scripts/lint-ratchet.ts",
35759
+ "lint:ratchet:update": "bun scripts/lint-ratchet.ts --update",
35650
35760
  "lint:fix": "oxlint --fix src bin bridge test scripts",
35651
- fmt: "oxfmt --write src bin bridge test scripts",
35652
- "fmt:check": "oxfmt --check src bin bridge test scripts",
35761
+ fmt: "bun fmt --no-script --write src bin bridge test scripts",
35762
+ "fmt:check": "bun fmt --no-script --check src bin bridge test scripts",
35653
35763
  format: "bun run fmt",
35654
35764
  "format:check": "bun run fmt:check",
35655
35765
  verify: "bun run check",
35766
+ "check:push": "bun run check && bun run build && git diff --exit-code HEAD --",
35767
+ prepare: "husky",
35656
35768
  build: "bun build.ts",
35657
35769
  "build:extension": "bun bridge/build-extension.ts",
35658
35770
  prepack: "bun run build",
35659
35771
  preversion: "git diff --quiet HEAD --"
35660
35772
  },
35661
35773
  dependencies: {
35662
- ws: "^8.18.3",
35663
- zod: "^4.6.6"
35774
+ ws: "^8.23.0",
35775
+ zod: "^4.6.7"
35664
35776
  },
35665
35777
  devDependencies: {
35666
- "@types/bun": "1.4.4",
35667
- acorn: "8.15.0",
35668
- "gpt-tokenizer": "4.1.0",
35669
- oxfmt: "^0.77.0",
35670
- oxlint: "^1.92.0",
35671
- typescript: "^7.0.2",
35778
+ "@types/bun": "1.4.5",
35779
+ acorn: "8.19.0",
35780
+ "gpt-tokenizer": "4.1.2",
35781
+ husky: "9.1.7",
35782
+ "oxc-parser": "0.159.0",
35783
+ oxlint: "^1.94.0",
35672
35784
  "typescript-5": "npm:typescript@5.9.3"
35673
35785
  },
35674
35786
  engines: {
@@ -36284,6 +36396,7 @@ async function* collectWhileScrolling(page, snoop, options = {}) {
36284
36396
  scroll = "wheel",
36285
36397
  settleMs = 800
36286
36398
  } = options;
36399
+ const clock = options.clock ?? globalThis;
36287
36400
  if (scroll !== "wheel" && scroll !== "end")
36288
36401
  throw new TypeError(`Unknown scroll mode: ${String(scroll)}`);
36289
36402
  let rounds = 0;
@@ -36322,9 +36435,33 @@ async function* collectWhileScrolling(page, snoop, options = {}) {
36322
36435
  unchanged = 0;
36323
36436
  }
36324
36437
  lastHeight = height;
36438
+ let timer;
36439
+ const deadline = new Promise((resolve) => {
36440
+ timer = clock.setTimeout(resolve, settleMs);
36441
+ });
36442
+ const response = snoop.waitFor((entry) => JSON_MIME.test(String(entry.mimeType ?? "")), { timeoutMs: settleMs }).catch(() => deadline);
36443
+ const growth = page.evaluate(({ baseline, cleanupMs }) => new Promise((resolve) => {
36444
+ const element = document.scrollingElement;
36445
+ if (!element)
36446
+ throw new TypeError("Cannot read properties of null (reading 'scrollHeight')");
36447
+ const finish = (grew) => {
36448
+ observer.disconnect();
36449
+ clearTimeout(cleanup);
36450
+ resolve(grew);
36451
+ };
36452
+ const observer = new ResizeObserver(() => {
36453
+ if (element.scrollHeight > baseline)
36454
+ finish(true);
36455
+ });
36456
+ const cleanup = setTimeout(() => finish(false), cleanupMs);
36457
+ observer.observe(element);
36458
+ if (element.scrollHeight > baseline)
36459
+ finish(true);
36460
+ }), { baseline: height, cleanupMs: settleMs }).then((grew) => grew ? undefined : deadline, () => deadline);
36325
36461
  await scrollOnce(page, scroll);
36326
36462
  rounds += 1;
36327
- await new Promise((resolve) => setTimeout(resolve, settleMs));
36463
+ await Promise.race([deadline, response, growth]);
36464
+ clock.clearTimeout(timer);
36328
36465
  }
36329
36466
  return { rounds, total, stoppedBecause };
36330
36467
  }
@@ -36515,16 +36652,130 @@ function createTrace(page, options = {}) {
36515
36652
  }
36516
36653
  // src/bsk/ipc-client.ts
36517
36654
  import { connect as connect2 } from "node:net";
36518
- import { existsSync as existsSync5, readdirSync } from "node:fs";
36519
- import path19 from "node:path";
36655
+ import { existsSync as existsSync6, readdirSync } from "node:fs";
36656
+ import path20 from "node:path";
36520
36657
  import { randomBytes } from "node:crypto";
36521
36658
 
36522
36659
  // src/bsk/daemon-info.ts
36523
- import { existsSync as existsSync4, readFileSync as readFileSync4 } from "node:fs";
36660
+ import { existsSync as existsSync5, readFileSync as readFileSync5 } from "node:fs";
36661
+ import { homedir as homedir4 } from "node:os";
36662
+ import path19 from "node:path";
36663
+ import { spawn as spawn7 } from "node:child_process";
36664
+ import { createHash as createHash2 } from "node:crypto";
36665
+
36666
+ // src/bsk/install-cli.ts
36667
+ import { existsSync as existsSync4, readFileSync as readFileSync4, rmSync as rmSync3, writeFileSync as writeFileSync3 } from "node:fs";
36524
36668
  import { homedir as homedir3 } from "node:os";
36525
36669
  import path18 from "node:path";
36526
36670
  import { spawn as spawn6 } from "node:child_process";
36527
- import { createHash as createHash2 } from "node:crypto";
36671
+ var BSK_CLI_VERSION = "0.5.0";
36672
+ var RELEASE_TAG = `cli-v${BSK_CLI_VERSION}`;
36673
+ var INSTALL_SH = `https://raw.githubusercontent.com/Tencent/BrowserSkill/${RELEASE_TAG}/install.sh`;
36674
+ var INSTALL_PS1 = `https://raw.githubusercontent.com/Tencent/BrowserSkill/${RELEASE_TAG}/install.ps1`;
36675
+ var BSK_PINNED_MANIFEST_URL = `https://github.com/Tencent/BrowserSkill/releases/download/${RELEASE_TAG}/version.json`;
36676
+ var RC_FILES = [".zshrc", ".bashrc", ".profile"];
36677
+ function windowsPowerShellEnv(env) {
36678
+ const key = Object.keys(process.env).find((name) => name.toUpperCase() === "PSMODULEPATH");
36679
+ if (!key)
36680
+ return env;
36681
+ const value = process.env[key];
36682
+ if (value === undefined)
36683
+ throw new TypeError(`${key} has no value`);
36684
+ const kept = value.split(";").filter((entry) => entry && !/[\\/]PowerShell[\\/]/i.test(entry));
36685
+ return { ...env, [key]: kept.length > 0 ? kept.join(";") : undefined };
36686
+ }
36687
+ function cliInstallCommand({
36688
+ platform = process.platform,
36689
+ installDir,
36690
+ version = BSK_CLI_VERSION
36691
+ } = {}) {
36692
+ const env = { BSK_INSTALL_DIR: installDir, BSK_VERSION: version };
36693
+ if (platform === "win32") {
36694
+ return {
36695
+ command: windowsSystemTool("WindowsPowerShell\\v1.0\\powershell.exe"),
36696
+ args: ["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", `irm ${INSTALL_PS1} | iex`],
36697
+ env: windowsPowerShellEnv(env)
36698
+ };
36699
+ }
36700
+ return { command: "sh", args: ["-c", `curl -fsSL ${INSTALL_SH} | sh`], env };
36701
+ }
36702
+ function runDefault(command, args, env) {
36703
+ return new Promise((resolve) => {
36704
+ const child = spawn6(command, args, {
36705
+ env: { ...process.env, ...env },
36706
+ stdio: ["ignore", "pipe", "pipe"],
36707
+ windowsHide: true
36708
+ });
36709
+ let stdout = "", stderr = "";
36710
+ child.stdout.on("data", (c) => {
36711
+ stdout = (stdout + c).slice(-8192);
36712
+ });
36713
+ child.stderr.on("data", (c) => {
36714
+ stderr = (stderr + c).slice(-8192);
36715
+ });
36716
+ child.on("error", (error) => resolve({ code: -1, stdout, stderr: error.message }));
36717
+ child.on("exit", (code) => resolve({ code, stdout, stderr }));
36718
+ });
36719
+ }
36720
+ function snapshotRcFiles(home) {
36721
+ const snapshot = new Map;
36722
+ for (const name of RC_FILES) {
36723
+ const file = path18.join(home, name);
36724
+ snapshot.set(file, existsSync4(file) ? readFileSync4(file) : null);
36725
+ }
36726
+ return snapshot;
36727
+ }
36728
+ function restoreRcFiles(snapshot) {
36729
+ const restored = [];
36730
+ for (const [file, before] of snapshot) {
36731
+ const after = existsSync4(file) ? readFileSync4(file) : null;
36732
+ if (before === null && after === null)
36733
+ continue;
36734
+ if (before !== null && after !== null && before.equals(after))
36735
+ continue;
36736
+ if (before === null)
36737
+ rmSync3(file, { force: true });
36738
+ else
36739
+ writeFileSync3(file, before);
36740
+ restored.push(file);
36741
+ }
36742
+ return restored;
36743
+ }
36744
+ async function installBskCli({
36745
+ platform = process.platform,
36746
+ home = homedir3(),
36747
+ installDir = path18.join(home, ".local", "bin"),
36748
+ version,
36749
+ run = runDefault
36750
+ } = {}) {
36751
+ const spec = cliInstallCommand({ platform, installDir, version });
36752
+ const rcBefore = platform === "win32" ? new Map : snapshotRcFiles(home);
36753
+ const result = await run(spec.command, spec.args, spec.env);
36754
+ const restoredRcFiles = restoreRcFiles(rcBefore);
36755
+ const bskBin = path18.join(installDir, platform === "win32" ? "bsk.exe" : "bsk");
36756
+ const installed = result.code === 0 && existsSync4(bskBin);
36757
+ return {
36758
+ installed,
36759
+ bskBin: installed ? bskBin : null,
36760
+ code: result.code,
36761
+ stdout: result.stdout,
36762
+ stderr: result.stderr,
36763
+ restoredRcFiles
36764
+ };
36765
+ }
36766
+ function cliVersionDefault(bskBin) {
36767
+ return new Promise((resolve) => {
36768
+ const child = spawn6(bskBin, ["--version"], { stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
36769
+ let out = "";
36770
+ child.stdout.on("data", (c) => {
36771
+ out += c;
36772
+ });
36773
+ child.on("error", () => resolve(null));
36774
+ child.on("exit", (code) => resolve(code === 0 ? out.trim() : null));
36775
+ });
36776
+ }
36777
+
36778
+ // src/bsk/daemon-info.ts
36528
36779
  function isDaemonInfo(value) {
36529
36780
  if (!value || typeof value !== "object" || !("sock_path" in value))
36530
36781
  return false;
@@ -36534,16 +36785,16 @@ function resolveBskHome(env = process.env) {
36534
36785
  const override = env["BSK_HOME"];
36535
36786
  if (typeof override === "string" && override.length > 0)
36536
36787
  return override;
36537
- const home = env["HOME"] && env["HOME"].length > 0 ? env["HOME"] : homedir3();
36538
- return path18.join(home, ".bsk");
36788
+ const home = env["HOME"] && env["HOME"].length > 0 ? env["HOME"] : homedir4();
36789
+ return path19.join(home, ".bsk");
36539
36790
  }
36540
36791
  function daemonInfoPath(home) {
36541
- return path18.join(home, "daemon.json");
36792
+ return path19.join(home, "daemon.json");
36542
36793
  }
36543
36794
  function readDaemonInfo(home) {
36544
36795
  let raw;
36545
36796
  try {
36546
- raw = readFileSync4(daemonInfoPath(home), "utf8");
36797
+ raw = readFileSync5(daemonInfoPath(home), "utf8");
36547
36798
  } catch {
36548
36799
  return null;
36549
36800
  }
@@ -36558,27 +36809,37 @@ function readDaemonInfo(home) {
36558
36809
  return info;
36559
36810
  }
36560
36811
  function findBskBinary(env = process.env) {
36561
- const home = env["HOME"] && env["HOME"].length > 0 ? env["HOME"] : homedir3();
36812
+ const home = env["HOME"] && env["HOME"].length > 0 ? env["HOME"] : homedir4();
36562
36813
  const candidates = [
36563
36814
  env["BSK_BIN"],
36564
- path18.join(home, ".local", "bin", process.platform === "win32" ? "bsk.exe" : "bsk")
36815
+ path19.join(home, ".local", "bin", process.platform === "win32" ? "bsk.exe" : "bsk")
36565
36816
  ].filter((candidate) => Boolean(candidate));
36566
36817
  for (const candidate of candidates)
36567
- if (existsSync4(candidate))
36818
+ if (existsSync5(candidate))
36568
36819
  return candidate;
36569
36820
  return "bsk";
36570
36821
  }
36571
36822
  var NO_BREAKAWAY = /Job Object/;
36572
36823
  function windowsDaemonTaskName(home) {
36573
- return `bsk-daemon-${createHash2("sha256").update(path18.resolve(home).toLowerCase()).digest("hex").slice(0, 12)}`;
36824
+ return `bsk-daemon-${createHash2("sha256").update(path19.resolve(home).toLowerCase()).digest("hex").slice(0, 12)}`;
36574
36825
  }
36575
36826
  var powershellLiteral = (value) => `'${value.replace(/['\u2018\u2019\u201A\u201B]/g, (quote) => quote + quote)}'`;
36576
- function windowsDaemonLaunch(home, bskBin) {
36577
- const script = `$env:BSK_HOME = ${powershellLiteral(home)}; & ${powershellLiteral(bskBin)} daemon start --foreground; exit $LASTEXITCODE`;
36827
+ function daemonEnv(env, home) {
36828
+ return {
36829
+ ...env,
36830
+ BSK_HOME: home,
36831
+ BSK_AUTO_UPDATE: env["BSK_AUTO_UPDATE"] ?? "off",
36832
+ BSK_UPDATE_MANIFEST_URL: env["BSK_UPDATE_MANIFEST_URL"] ?? BSK_PINNED_MANIFEST_URL
36833
+ };
36834
+ }
36835
+ function windowsDaemonLaunch(env, bskBin) {
36836
+ const assignments = ["BSK_HOME", "BSK_AUTO_UPDATE", "BSK_UPDATE_MANIFEST_URL"].map((name) => `$env:${name} = ${powershellLiteral(env[name] ?? "")}; `).join("");
36837
+ const script = `${assignments}& ${powershellLiteral(bskBin)} daemon start --foreground; exit $LASTEXITCODE`;
36578
36838
  return `--headless "${windowsSystemTool("WindowsPowerShell\\v1.0\\powershell.exe")}" -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(script, "utf16le").toString("base64")}`;
36579
36839
  }
36580
36840
  function startDaemonInWindowsTask({
36581
36841
  home,
36842
+ env,
36582
36843
  bskBin,
36583
36844
  timeoutMs
36584
36845
  }) {
@@ -36592,7 +36853,7 @@ function startDaemonInWindowsTask({
36592
36853
  env: {
36593
36854
  ...process.env,
36594
36855
  BSK_TASK_NAME: windowsDaemonTaskName(home),
36595
- BSK_TASK_ARGUMENT: windowsDaemonLaunch(home, bskBin)
36856
+ BSK_TASK_ARGUMENT: windowsDaemonLaunch(env, bskBin)
36596
36857
  },
36597
36858
  timeoutMs,
36598
36859
  label: "registering the bsk daemon task"
@@ -36600,7 +36861,7 @@ function startDaemonInWindowsTask({
36600
36861
  }
36601
36862
  function runToExit(command, args, { env, timeoutMs, label }) {
36602
36863
  return new Promise((resolve, reject) => {
36603
- const child = spawn6(command, args, { env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
36864
+ const child = spawn7(command, args, { env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
36604
36865
  let output = "";
36605
36866
  const keep = (chunk) => {
36606
36867
  output = (output + chunk).slice(-4096);
@@ -36627,8 +36888,9 @@ async function startDaemonWithCli({
36627
36888
  bskBin = findBskBinary(env),
36628
36889
  timeoutMs = 20000
36629
36890
  } = {}) {
36891
+ const daemon = daemonEnv(env, home);
36630
36892
  const status = await runToExit(bskBin, ["status", "--json"], {
36631
- env: { ...env, BSK_HOME: home },
36893
+ env: daemon,
36632
36894
  timeoutMs,
36633
36895
  label: "bsk status"
36634
36896
  });
@@ -36637,7 +36899,7 @@ async function startDaemonWithCli({
36637
36899
  if (process.platform === "win32" && NO_BREAKAWAY.test(status.output)) {
36638
36900
  if (home === undefined)
36639
36901
  throw new TypeError("startDaemonWithCli needs a home to register the Windows daemon task");
36640
- const task = await startDaemonInWindowsTask({ home, bskBin, timeoutMs });
36902
+ const task = await startDaemonInWindowsTask({ home, env: daemon, bskBin, timeoutMs });
36641
36903
  if (task.code === 0)
36642
36904
  return;
36643
36905
  throw new Error(`${status.output}; registering the bsk daemon task exited with ${task.code}${task.output ? `: ${task.output}` : ""}`);
@@ -36672,7 +36934,7 @@ function ownBudgetMs(params) {
36672
36934
  var PROBE_TIMEOUT_MS = 2000;
36673
36935
  function defaultSocketPath(home, env = process.env) {
36674
36936
  if (process.platform !== "win32")
36675
- return path19.join(home, "run", "daemon.sock");
36937
+ return path20.join(home, "run", "daemon.sock");
36676
36938
  return `\\\\.\\pipe\\bsk-daemon-${rustStrHash(env["USERNAME"] ?? "default", home)}`;
36677
36939
  }
36678
36940
  function rustStrHash(...values) {
@@ -36712,9 +36974,9 @@ function rustStrHash(...values) {
36712
36974
  }
36713
36975
  function socketExists(sockPath) {
36714
36976
  if (process.platform !== "win32")
36715
- return existsSync5(sockPath);
36977
+ return existsSync6(sockPath);
36716
36978
  try {
36717
- return readdirSync("\\\\.\\pipe\\").includes(path19.win32.basename(sockPath));
36979
+ return readdirSync("\\\\.\\pipe\\").includes(path20.win32.basename(sockPath));
36718
36980
  } catch {
36719
36981
  return false;
36720
36982
  }
@@ -37057,7 +37319,11 @@ class BskSession {
37057
37319
  });
37058
37320
  }
37059
37321
  cooperate(action, { tabId, timeoutMs, maxTokens } = {}) {
37060
- return this.tool("cooperate", { action, tab_id: tabId, timeout_ms: timeoutMs, max_tokens: maxTokens });
37322
+ return this.tool("cooperate", { action, tab_id: tabId, timeout_ms: timeoutMs, max_tokens: maxTokens }).catch((error) => {
37323
+ if (error instanceof BskRpcError && error.code === "unknown_method")
37324
+ return { context_id: undefined, supported: false, ready: true };
37325
+ throw error;
37326
+ });
37061
37327
  }
37062
37328
  navigate(url, { tabId, waitUntil, timeoutMs, ...shared } = {}) {
37063
37329
  return this.tool("navigate", {
@@ -37179,6 +37445,8 @@ class BskSession {
37179
37445
  tab_id: tabId,
37180
37446
  timeout_ms: timeoutMs,
37181
37447
  ...sharedTab(shared)
37448
+ }).catch((error) => {
37449
+ throw redactValue(error, value);
37182
37450
  });
37183
37451
  }
37184
37452
  press(key, {
@@ -37336,7 +37604,7 @@ function isTabGroupingExtension(browser) {
37336
37604
  }
37337
37605
  var TAB_GROUPING_EXTENSION_STEP = `Update the BrowserSkill extension to 0.4.1 or later (chrome://extensions -> Developer mode -> Update, or wait for the store update). Version 0.4.0 puts each task's tabs into a "BrowserSkill" tab group that the browser saves and syncs, so the group stays after the task ends; delete any saved "BrowserSkill" tab groups by hand.`;
37338
37606
  function outdatedError(browser) {
37339
- return new BskRpcError("extension_outdated", `the BrowserSkill extension in ${readProperty(browser, "browser_name") ?? "the browser"} [${readProperty(browser, "instance_id")}] is 0.4.0, which leaves a "BrowserSkill" tab group behind in the user's browser after each task. ${TAB_GROUPING_EXTENSION_STEP}`);
37607
+ return new BskRpcError("extension_outdated", `the BrowserSkill extension in ${textField(browser, "browser_name") ?? "the browser"} [${textField(browser, "instance_id") ?? "unknown id"}] is 0.4.0, which leaves a "BrowserSkill" tab group behind in the user's browser after each task. ${TAB_GROUPING_EXTENSION_STEP}`);
37340
37608
  }
37341
37609
  function namesBrowser(b, browser) {
37342
37610
  return readProperty(b, "instance_id") === browser || Boolean(readProperty(b, "label") && readProperty(b, "label") === browser);
@@ -37370,19 +37638,26 @@ function resolveBrowser(browser, browsers) {
37370
37638
  return browser;
37371
37639
  const named = browsers.filter((b) => readProperty(b, "browser_name") === browser);
37372
37640
  if (named.length > 1) {
37373
- throw new BskRpcError("invalid_params", `browser "${browser}" matches ${named.length} connected browsers (${named.map((b) => readProperty(b, "instance_id")).join(", ")}); pass the instance id instead`);
37641
+ throw new BskRpcError("invalid_params", `browser "${browser}" matches ${named.length} connected browsers (${named.map((b) => textField(b, "instance_id") ?? "unknown id").join(", ")}); pass the instance id instead`);
37374
37642
  }
37375
37643
  return named.length === 1 ? readProperty(named[0], "instance_id") : browser;
37376
37644
  }
37645
+ function textField(b, key) {
37646
+ const value = optionalProperty(b, key);
37647
+ if (typeof value === "string")
37648
+ return value;
37649
+ if (typeof value === "number" && Number.isFinite(value))
37650
+ return String(value);
37651
+ return;
37652
+ }
37377
37653
  function describeBrowser(b) {
37378
- const name = optionalProperty(b, "browser_name");
37379
- const label = optionalProperty(b, "label");
37654
+ const name = textField(b, "browser_name");
37380
37655
  const parts = [
37381
- `${String(label || name || "browser")} [${String(optionalProperty(b, "instance_id"))}]`,
37382
- [name, optionalProperty(b, "browser_version")].filter(Boolean).join(" ")
37656
+ `${textField(b, "label") || name || "browser"} [${textField(b, "instance_id") ?? "unknown id"}]`,
37657
+ [name, textField(b, "browser_version")].filter(Boolean).join(" ")
37383
37658
  ];
37384
37659
  const sessions = optionalProperty(b, "session_count");
37385
- if (typeof sessions === "number")
37660
+ if (typeof sessions === "number" && Number.isFinite(sessions))
37386
37661
  parts.push(`${sessions} session${sessions === 1 ? "" : "s"}`);
37387
37662
  const since = optionalProperty(b, "connected_at_ms");
37388
37663
  if (typeof since === "number" && Number.isFinite(since) && Math.abs(since) <= 8640000000000000) {
@@ -37896,117 +38171,6 @@ import { homedir as homedir6 } from "node:os";
37896
38171
  import path22 from "node:path";
37897
38172
  import { spawn as spawn8 } from "node:child_process";
37898
38173
 
37899
- // src/bsk/install-cli.ts
37900
- import { existsSync as existsSync6, readFileSync as readFileSync5, rmSync as rmSync3, writeFileSync as writeFileSync3 } from "node:fs";
37901
- import { homedir as homedir4 } from "node:os";
37902
- import path20 from "node:path";
37903
- import { spawn as spawn7 } from "node:child_process";
37904
- var INSTALL_SH = "https://raw.githubusercontent.com/Tencent/BrowserSkill/main/install.sh";
37905
- var INSTALL_PS1 = "https://raw.githubusercontent.com/Tencent/BrowserSkill/main/install.ps1";
37906
- var RC_FILES = [".zshrc", ".bashrc", ".profile"];
37907
- function windowsPowerShellEnv(env) {
37908
- const key = Object.keys(process.env).find((name) => name.toUpperCase() === "PSMODULEPATH");
37909
- if (!key)
37910
- return env;
37911
- const value = process.env[key];
37912
- if (value === undefined)
37913
- throw new TypeError(`${key} has no value`);
37914
- const kept = value.split(";").filter((entry) => entry && !/[\\/]PowerShell[\\/]/i.test(entry));
37915
- return { ...env, [key]: kept.length > 0 ? kept.join(";") : undefined };
37916
- }
37917
- function cliInstallCommand({
37918
- platform = process.platform,
37919
- installDir,
37920
- version
37921
- } = {}) {
37922
- const env = { BSK_INSTALL_DIR: installDir };
37923
- if (version)
37924
- env["BSK_VERSION"] = version;
37925
- if (platform === "win32") {
37926
- return {
37927
- command: windowsSystemTool("WindowsPowerShell\\v1.0\\powershell.exe"),
37928
- args: ["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", `irm ${INSTALL_PS1} | iex`],
37929
- env: windowsPowerShellEnv(env)
37930
- };
37931
- }
37932
- return { command: "sh", args: ["-c", `curl -fsSL ${INSTALL_SH} | sh`], env };
37933
- }
37934
- function runDefault(command, args, env) {
37935
- return new Promise((resolve) => {
37936
- const child = spawn7(command, args, {
37937
- env: { ...process.env, ...env },
37938
- stdio: ["ignore", "pipe", "pipe"],
37939
- windowsHide: true
37940
- });
37941
- let stdout = "", stderr = "";
37942
- child.stdout.on("data", (c) => {
37943
- stdout = (stdout + c).slice(-8192);
37944
- });
37945
- child.stderr.on("data", (c) => {
37946
- stderr = (stderr + c).slice(-8192);
37947
- });
37948
- child.on("error", (error) => resolve({ code: -1, stdout, stderr: error.message }));
37949
- child.on("exit", (code) => resolve({ code, stdout, stderr }));
37950
- });
37951
- }
37952
- function snapshotRcFiles(home) {
37953
- const snapshot = new Map;
37954
- for (const name of RC_FILES) {
37955
- const file = path20.join(home, name);
37956
- snapshot.set(file, existsSync6(file) ? readFileSync5(file) : null);
37957
- }
37958
- return snapshot;
37959
- }
37960
- function restoreRcFiles(snapshot) {
37961
- const restored = [];
37962
- for (const [file, before] of snapshot) {
37963
- const after = existsSync6(file) ? readFileSync5(file) : null;
37964
- if (before === null && after === null)
37965
- continue;
37966
- if (before !== null && after !== null && before.equals(after))
37967
- continue;
37968
- if (before === null)
37969
- rmSync3(file, { force: true });
37970
- else
37971
- writeFileSync3(file, before);
37972
- restored.push(file);
37973
- }
37974
- return restored;
37975
- }
37976
- async function installBskCli({
37977
- platform = process.platform,
37978
- home = homedir4(),
37979
- installDir = path20.join(home, ".local", "bin"),
37980
- version,
37981
- run = runDefault
37982
- } = {}) {
37983
- const spec = cliInstallCommand({ platform, installDir, version });
37984
- const rcBefore = platform === "win32" ? new Map : snapshotRcFiles(home);
37985
- const result = await run(spec.command, spec.args, spec.env);
37986
- const restoredRcFiles = restoreRcFiles(rcBefore);
37987
- const bskBin = path20.join(installDir, platform === "win32" ? "bsk.exe" : "bsk");
37988
- const installed = result.code === 0 && existsSync6(bskBin);
37989
- return {
37990
- installed,
37991
- bskBin: installed ? bskBin : null,
37992
- code: result.code,
37993
- stdout: result.stdout,
37994
- stderr: result.stderr,
37995
- restoredRcFiles
37996
- };
37997
- }
37998
- function cliVersionDefault(bskBin) {
37999
- return new Promise((resolve) => {
38000
- const child = spawn7(bskBin, ["--version"], { stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
38001
- let out = "";
38002
- child.stdout.on("data", (c) => {
38003
- out += c;
38004
- });
38005
- child.on("error", () => resolve(null));
38006
- child.on("exit", (code) => resolve(code === 0 ? out.trim() : null));
38007
- });
38008
- }
38009
-
38010
38174
  // src/aside/cli-binary.ts
38011
38175
  import { existsSync as existsSync7 } from "node:fs";
38012
38176
  import { homedir as homedir5 } from "node:os";