@xbrowser/cli 1.29.0 → 1.30.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/README.md +2 -2
  2. package/dist/{browser-XD3IOU5I.js → browser-6PFTHZI3.js} +2 -2
  3. package/dist/{browser-2K3XYAKM.js → browser-I2NLJN2A.js} +1 -1
  4. package/dist/{browser-OTEMG5NL.js → browser-KOUA4ZDA.js} +2 -2
  5. package/dist/{cdp-driver-AAS55KT2.js → cdp-driver-3ETNFQA4.js} +1 -1
  6. package/dist/{cdp-driver-XTPY7EXP.js → cdp-driver-U7HDQMQ5.js} +257 -19
  7. package/dist/{cdp-driver-O5I7SJ24.js → cdp-driver-WBFJNOLD.js} +1 -1
  8. package/dist/{chunk-SCYBNSOG.js → chunk-3K57RYVC.js} +378 -115
  9. package/dist/{chunk-FNXA6FDM.js → chunk-BND5O5KC.js} +2 -1
  10. package/dist/{chunk-P33R7F2D.js → chunk-BOZTIIBT.js} +30 -45
  11. package/dist/{chunk-GDKKVT2P.js → chunk-KPTD3SNJ.js} +379 -116
  12. package/dist/{chunk-CO2ZVOVT.js → chunk-NINETOM4.js} +30 -45
  13. package/dist/{chunk-SOPN4XDK.js → chunk-O5PASNI7.js} +2 -1
  14. package/dist/{chunk-NQPXZ74W.js → chunk-OCECE22C.js} +257 -19
  15. package/dist/{chunk-LFSLNHW5.js → chunk-OSIDUT4H.js} +286 -63
  16. package/dist/{chunk-HBMEFSTB.js → chunk-QCV2PI7U.js} +2 -1
  17. package/dist/{chunk-UZ6XPUBD.js → chunk-RMYKVZIZ.js} +78 -0
  18. package/dist/{chunk-N5XTLNKS.js → chunk-SPNWUUHA.js} +257 -19
  19. package/dist/{chunk-PGKV24QN.js → chunk-TBJUSUKF.js} +1 -1
  20. package/dist/{chunk-FCPVQFTQ.js → chunk-VYTQLZAX.js} +78 -0
  21. package/dist/cli.js +45 -16
  22. package/dist/daemon-main.js +581 -157
  23. package/dist/{human-interaction-CTZ4IWXJ.js → human-interaction-ISMMOJOK.js} +2 -2
  24. package/dist/{human-interaction-HJCK45SL.js → human-interaction-STTZZZ5N.js} +1 -1
  25. package/dist/{human-interaction-V3VDGHHI.js → human-interaction-UXFYV7DU.js} +1 -1
  26. package/dist/index.d.ts +106 -12
  27. package/dist/index.js +195 -46
  28. package/dist/{recovery-EBKORYEU.js → recovery-JFGV3DBX.js} +1 -1
  29. package/dist/{recovery-5C4FBA5O.js → recovery-ORHJSBDN.js} +2 -2
  30. package/dist/{recovery-IMZUGWSS.js → recovery-XDKN63O5.js} +1 -1
  31. package/dist/{server-ZTI2K5YJ.js → server-TG47W7MV.js} +3 -3
  32. package/dist/{server-LNZTDAKT.js → server-U3YAX5MJ.js} +2 -2
  33. package/dist/{session-recorder-DF2YGH2E.js → session-recorder-N7VEKJVW.js} +1 -1
  34. package/dist/{session-recorder-R3GDGXLJ.js → session-recorder-RUNQOJ7T.js} +1 -1
  35. package/dist/{session-replayer-CLTZ2URU.js → session-replayer-XLWQ47BB.js} +1 -1
  36. package/package.json +4 -1
package/dist/index.js CHANGED
@@ -48,11 +48,11 @@ import {
48
48
  splitCommand,
49
49
  waitForAIResponse,
50
50
  waitForPage
51
- } from "./chunk-GDKKVT2P.js";
51
+ } from "./chunk-KPTD3SNJ.js";
52
52
  import {
53
53
  SessionRecorder,
54
54
  readMarkdownSummary
55
- } from "./chunk-UZ6XPUBD.js";
55
+ } from "./chunk-RMYKVZIZ.js";
56
56
  import {
57
57
  closeAllSessions,
58
58
  closeSessionByName,
@@ -64,7 +64,7 @@ import {
64
64
  getBrowser,
65
65
  resetForTesting,
66
66
  saveSessionDiskMeta
67
- } from "./chunk-P33R7F2D.js";
67
+ } from "./chunk-BOZTIIBT.js";
68
68
  import "./chunk-JKVUFP3G.js";
69
69
  import {
70
70
  forwardCommandLog,
@@ -98,7 +98,7 @@ import {
98
98
  HumanInteractionManager,
99
99
  ScreencastCapturer,
100
100
  WebhookNotifier
101
- } from "./chunk-SOPN4XDK.js";
101
+ } from "./chunk-O5PASNI7.js";
102
102
  import {
103
103
  NPM_REGISTRY_URL,
104
104
  NPM_SCOPE,
@@ -121,7 +121,7 @@ import {
121
121
  generateJSScript,
122
122
  generatePythonScript
123
123
  } from "./chunk-ETCO4SNK.js";
124
- import "./chunk-N5XTLNKS.js";
124
+ import "./chunk-SPNWUUHA.js";
125
125
  import "./chunk-SMYSNO4M.js";
126
126
  import "./chunk-2KPI5GKP.js";
127
127
  import {
@@ -574,7 +574,7 @@ async function handleBrowserCommand(command, args, options, sessionName, mode, c
574
574
  }
575
575
  case "mouse": {
576
576
  const flatArgs = args.flatMap((a) => a.split(/\s+/).filter(Boolean));
577
- const argActionIdx = flatArgs.findIndex((a) => ["move", "click", "dblclick", "down", "up"].includes(a));
577
+ const argActionIdx = flatArgs.findIndex((a) => ["move", "click", "dblclick", "down", "up", "drag", "wheel"].includes(a));
578
578
  const action = options.action || (argActionIdx >= 0 ? flatArgs[argActionIdx] : void 0);
579
579
  const coordArgs = options.action !== void 0 ? flatArgs : argActionIdx >= 0 ? flatArgs.slice(argActionIdx + 1) : flatArgs;
580
580
  const x = options.x !== void 0 ? Number(options.x) : coordArgs[0] !== void 0 ? Number(coordArgs[0]) : void 0;
@@ -796,6 +796,12 @@ async function handleBrowserCommand(command, args, options, sessionName, mode, c
796
796
  if (tabIndex !== void 0) {
797
797
  params = { ...params, _tabIndex: Number(tabIndex) };
798
798
  }
799
+ const commandFrameIndex = args.findIndex((arg, index) => arg === "--frame" && typeof args[index + 1] === "string");
800
+ if (commandFrameIndex >= 0) {
801
+ params = { ...params, frame: args[commandFrameIndex + 1] };
802
+ } else if (typeof options.frame === "string") {
803
+ params = { ...params, _frame: options.frame };
804
+ }
799
805
  const result = cdpEndpoint ? await executeCommand(cmdName, params, sessionName, { cdpEndpoint }) : await executeCommand(cmdName, params, sessionName);
800
806
  if (mode === "json" || mode === "yaml") {
801
807
  outputEnvelope(result, { command: cmdName }, mode);
@@ -3923,7 +3929,7 @@ async function handleFilter(args, _mode, options) {
3923
3929
  }
3924
3930
  }
3925
3931
  async function handleGeneratePlugin(sessionName, pluginName, outputDir) {
3926
- const { SessionRecorder: SessionRecorder2 } = await import("./session-recorder-R3GDGXLJ.js");
3932
+ const { SessionRecorder: SessionRecorder2 } = await import("./session-recorder-RUNQOJ7T.js");
3927
3933
  const { readSiteKnowledge: readSiteKnowledge2, toMarkdown } = await import("./site-knowledge-SYC6VCDB.js");
3928
3934
  const { mkdirSync: mkdirSync7, writeFileSync: writeFileSync8 } = await import("fs");
3929
3935
  const { join: join8 } = await import("path");
@@ -4815,6 +4821,7 @@ Commands:
4815
4821
  scroll <direction> [--distance N] Scroll page
4816
4822
 
4817
4823
  screenshot [--full-page] [--base64] Take screenshot
4824
+ snapshot Page snapshot: interactive @refs by default (--type aria/text/dom for other modes)
4818
4825
  eval <expression> Evaluate JS
4819
4826
  wait <selector> [--timeout <ms>] Wait for element (-s <sel>)
4820
4827
  waitForTimeout <ms> Wait for milliseconds
@@ -4994,12 +5001,20 @@ function extractSessionNameFromArgv(argv) {
4994
5001
  }
4995
5002
  return process.env.XBROWSER_SESSION || "default";
4996
5003
  }
5004
+ function extractFrameFromArgv(argv) {
5005
+ for (let i = 0; i < argv.length; i++) {
5006
+ if (argv[i] === "--frame" && argv[i + 1]) return argv[i + 1];
5007
+ if (typeof argv[i] === "string" && argv[i].startsWith("--frame=")) return argv[i].slice(7);
5008
+ }
5009
+ return void 0;
5010
+ }
4997
5011
  async function handleStdinMode(stdinCommands, argv) {
4998
5012
  const chain = stdinCommands.join(" ; ");
4999
5013
  const chainResult = await executeChain(chain, {
5000
5014
  fileMode: true,
5001
5015
  cdpEndpoint: argv ? extractCdpFromArgv(argv) : void 0,
5002
- sessionName: argv ? extractSessionNameFromArgv(argv) : "default"
5016
+ sessionName: argv ? extractSessionNameFromArgv(argv) : "default",
5017
+ frame: argv ? extractFrameFromArgv(argv) : void 0
5003
5018
  });
5004
5019
  printChainResult(chainResult);
5005
5020
  if (!chainResult.success) throw new Error("Command failed");
@@ -5022,7 +5037,7 @@ async function handleEvalMode(argv) {
5022
5037
  if (!chainResult.success) throw new Error("Command failed");
5023
5038
  }
5024
5039
  function findEvalStart(argv) {
5025
- const flagsWithValue = /* @__PURE__ */ new Set(["--session", "--cdp"]);
5040
+ const flagsWithValue = /* @__PURE__ */ new Set(["--session", "--cdp", "--frame"]);
5026
5041
  for (let i = 0; i < argv.length; i++) {
5027
5042
  const a = argv[i];
5028
5043
  if (a === "-e" || a === "--eval") return -1;
@@ -5040,9 +5055,14 @@ function findEvalStart(argv) {
5040
5055
  async function handleEvalScript(parts, argv) {
5041
5056
  const cdpEndpoint = extractCdpFromArgv(argv);
5042
5057
  const sessionName = extractSessionNameFromArgv(argv);
5058
+ const mode = argv.some((a) => a === "--json" || a.startsWith("--json=") || a === "-j") ? "json" : argv.some((a) => a === "--yaml" || a.startsWith("--yaml=")) ? "yaml" : "text";
5043
5059
  if (parts[0] === "--script-b64" && parts[1]) {
5044
- const chainResult2 = await executeChain(`eval --script-b64 ${parts[1]}`, { cdpEndpoint, sessionName });
5045
- printChainResult(chainResult2);
5060
+ const chainResult2 = await executeChain(`eval --script-b64 ${parts[1]}`, { cdpEndpoint, sessionName, frame: extractFrameFromArgv(argv) });
5061
+ if (mode === "json" || mode === "yaml") {
5062
+ outputEnvelope({ success: chainResult2.success, data: chainResult2.steps[chainResult2.steps.length - 1]?.data ?? null, duration: chainResult2.totalDuration }, { command: "eval" }, mode);
5063
+ } else {
5064
+ printChainResult(chainResult2);
5065
+ }
5046
5066
  if (!chainResult2.success) throw new Error("Command failed");
5047
5067
  return;
5048
5068
  }
@@ -5055,10 +5075,11 @@ async function handleEvalScript(parts, argv) {
5055
5075
  i++;
5056
5076
  continue;
5057
5077
  }
5058
- if (part === "--session" || part === "--cdp") {
5078
+ if (part === "--session" || part === "--cdp" || part === "--frame") {
5059
5079
  i++;
5060
5080
  continue;
5061
5081
  }
5082
+ if (part === "--json" || part === "--yaml" || part === "-j") continue;
5062
5083
  scriptLines.push(part);
5063
5084
  }
5064
5085
  const script = scriptLines.join("\n");
@@ -5069,14 +5090,22 @@ async function handleEvalScript(parts, argv) {
5069
5090
  const b64 = Buffer.from(script, "utf8").toString("base64url");
5070
5091
  const chain = frame ? `eval --frame ${frame} --script-b64 ${b64}` : `eval --script-b64 ${b64}`;
5071
5092
  const chainResult = await executeChain(chain, { cdpEndpoint, sessionName });
5072
- printChainResult(chainResult);
5093
+ if (mode === "json" || mode === "yaml") {
5094
+ outputEnvelope({ success: chainResult.success, data: chainResult.steps[chainResult.steps.length - 1]?.data ?? null, duration: chainResult.totalDuration }, { command: "eval" }, mode);
5095
+ } else {
5096
+ printChainResult(chainResult);
5097
+ }
5073
5098
  if (!chainResult.success) throw new Error("Command failed");
5074
5099
  }
5075
5100
  async function handleChainInput(input, argv) {
5076
5101
  const hasJson = argv ? argv.some((a) => a === "--json" || a.startsWith("--json=") || a.includes(" --json") || a.startsWith("--json")) || argv.includes("-j") : false;
5077
5102
  const hasYaml = argv ? argv.some((a) => a === "--yaml" || a.startsWith("--yaml=")) : false;
5078
5103
  const mode = hasJson ? "json" : hasYaml ? "yaml" : "text";
5079
- const chainResult = await executeChain(input, { cdpEndpoint: extractCdpFromArgv(argv ?? []) });
5104
+ const chainResult = await executeChain(input, {
5105
+ cdpEndpoint: extractCdpFromArgv(argv ?? []),
5106
+ sessionName: extractSessionNameFromArgv(argv ?? []),
5107
+ frame: argv ? extractFrameFromArgv(argv) : void 0
5108
+ });
5080
5109
  if (mode === "json" || mode === "yaml") {
5081
5110
  outputEnvelope(
5082
5111
  {
@@ -5879,7 +5908,7 @@ async function handleRemote(args, options, mode) {
5879
5908
  }
5880
5909
  }
5881
5910
  async function startMcpServer() {
5882
- const { startMcpStdio } = await import("./server-ZTI2K5YJ.js");
5911
+ const { startMcpStdio } = await import("./server-TG47W7MV.js");
5883
5912
  startMcpStdio();
5884
5913
  }
5885
5914
 
@@ -6194,7 +6223,7 @@ Run "xbrowser ${command} ${subCommand} --help" to see available parameters.`
6194
6223
  const targetPage = pages[cmdTabIndex];
6195
6224
  await targetPage.bringToFront().catch(() => {
6196
6225
  });
6197
- const { setActivePage } = await import("./browser-XD3IOU5I.js");
6226
+ const { setActivePage } = await import("./browser-6PFTHZI3.js");
6198
6227
  setActivePage(session, targetPage);
6199
6228
  }
6200
6229
  }
@@ -6341,7 +6370,7 @@ async function routeCommand(argvIn, stdinCommands) {
6341
6370
  if (argv[0] === "--json" || argv[0] === "--yaml") {
6342
6371
  argv = argv.slice(1);
6343
6372
  }
6344
- const globalFlags = /* @__PURE__ */ new Set(["--session", "--cdp", "--json", "--yaml", "--output", "--timeout", "--help", "-h", "--version"]);
6373
+ const globalFlags = /* @__PURE__ */ new Set(["--session", "--cdp", "--json", "--yaml", "--output", "--timeout", "--help", "-h", "--version", "--frame", "--target", "--tab"]);
6345
6374
  let chainArgIdx = -1;
6346
6375
  let seenCommandWord = false;
6347
6376
  for (let i = 0; i < argv.length; i++) {
@@ -6936,8 +6965,8 @@ var FrameProcessor = class {
6936
6965
  screencastQuality = 80;
6937
6966
  async process(data, config, viewportWidth, viewportHeight, cropConfig) {
6938
6967
  const buffer = Buffer.from(data, "base64");
6939
- const needsResize = config.scale < 1 && !!viewportWidth && !!viewportHeight;
6940
6968
  const needsCrop = !!cropConfig;
6969
+ const needsResize = needsCrop && !!cropConfig || config.scale < 1 && !!viewportWidth && !!viewportHeight;
6941
6970
  const needsReencode = config.format !== this.screencastFormat || config.quality !== this.screencastQuality;
6942
6971
  if (!needsResize && !needsCrop && !needsReencode) {
6943
6972
  return buffer;
@@ -6966,9 +6995,15 @@ var FrameProcessor = class {
6966
6995
  }
6967
6996
  }
6968
6997
  if (needsResize) {
6969
- const newWidth = Math.round((viewportWidth ?? 0) * config.scale);
6970
- const newHeight = Math.round((viewportHeight ?? 0) * config.scale);
6971
- processed = processed.resize(newWidth, newHeight);
6998
+ const newWidth = Math.round(
6999
+ cropConfig ? cropConfig.width : (viewportWidth ?? 0) * config.scale
7000
+ );
7001
+ const newHeight = Math.round(
7002
+ cropConfig ? cropConfig.height : (viewportHeight ?? 0) * config.scale
7003
+ );
7004
+ if (newWidth > 0 && newHeight > 0) {
7005
+ processed = processed.resize(newWidth, newHeight);
7006
+ }
6972
7007
  }
6973
7008
  if (config.format === "jpeg") {
6974
7009
  processed = processed.jpeg({ quality: config.quality });
@@ -6991,6 +7026,8 @@ var StreamCoordinator = class {
6991
7026
  sink;
6992
7027
  lastFrameData = null;
6993
7028
  lastFrameViewport = null;
7029
+ lastUncroppedFrameData = null;
7030
+ lastUncroppedFrameViewport = null;
6994
7031
  stateManager = new StreamStateManager();
6995
7032
  frameRateController = new FrameRateController();
6996
7033
  frameProcessor = new FrameProcessor();
@@ -7022,6 +7059,8 @@ var StreamCoordinator = class {
7022
7059
  clearLastFrame() {
7023
7060
  this.lastFrameData = null;
7024
7061
  this.lastFrameViewport = null;
7062
+ this.lastUncroppedFrameData = null;
7063
+ this.lastUncroppedFrameViewport = null;
7025
7064
  }
7026
7065
  // -----------------------------------------------------------------------
7027
7066
  // Frame capture callbacks (used by SessionManager)
@@ -7035,15 +7074,16 @@ var StreamCoordinator = class {
7035
7074
  return (frame) => {
7036
7075
  resetStaticSnapshotTimer();
7037
7076
  (async () => {
7038
- this.lastFrameData = frame.data.toString("base64");
7039
- this.lastFrameViewport = frame.viewport;
7077
+ const data = frame.data.toString("base64");
7078
+ this.lastUncroppedFrameData = data;
7079
+ this.lastUncroppedFrameViewport = frame.viewport;
7040
7080
  this.stateManager.onFrameReceived();
7041
7081
  const config = this.stateManager.getConfig();
7042
7082
  if (!this.frameRateController.shouldSendFrame(config.maxFps)) {
7043
7083
  return;
7044
7084
  }
7045
7085
  await this.processAndBroadcast(
7046
- this.lastFrameData,
7086
+ data,
7047
7087
  frame.viewport,
7048
7088
  sessionId,
7049
7089
  frame.sessionId,
@@ -7061,7 +7101,8 @@ var StreamCoordinator = class {
7061
7101
  */
7062
7102
  async takeStaticSnapshot(sessionId, page, clientCount) {
7063
7103
  if (clientCount <= 0) return;
7064
- let viewport = page.viewportSize();
7104
+ const logicalViewport = page.viewportSize();
7105
+ let viewport = logicalViewport;
7065
7106
  if (!viewport) {
7066
7107
  try {
7067
7108
  viewport = await page.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight }));
@@ -7070,10 +7111,11 @@ var StreamCoordinator = class {
7070
7111
  }
7071
7112
  }
7072
7113
  const screenshot = await page.screenshot({ type: "jpeg", quality: 100 });
7073
- this.lastFrameData = screenshot.toString("base64");
7074
- this.lastFrameViewport = viewport;
7114
+ const data = screenshot.toString("base64");
7115
+ this.lastUncroppedFrameData = data;
7116
+ this.lastUncroppedFrameViewport = viewport;
7075
7117
  await this.processAndBroadcast(
7076
- this.lastFrameData,
7118
+ data,
7077
7119
  viewport,
7078
7120
  sessionId,
7079
7121
  sessionId,
@@ -7087,10 +7129,12 @@ var StreamCoordinator = class {
7087
7129
  * replay and crop changes).
7088
7130
  */
7089
7131
  async replayLastFrame(sessionId) {
7090
- if (!this.lastFrameData || !this.lastFrameViewport) return;
7132
+ const data = this.lastUncroppedFrameData ?? this.lastFrameData;
7133
+ const viewport = this.lastUncroppedFrameViewport ?? this.lastFrameViewport;
7134
+ if (!data || !viewport) return;
7091
7135
  await this.processAndBroadcast(
7092
- this.lastFrameData,
7093
- this.lastFrameViewport,
7136
+ data,
7137
+ viewport,
7094
7138
  sessionId,
7095
7139
  sessionId,
7096
7140
  crypto.randomUUID(),
@@ -7110,8 +7154,11 @@ var StreamCoordinator = class {
7110
7154
  async processAndBroadcast(frameData, frameViewport, sessionId, frameSessionId, frameId, frameTimestamp, frameUrl) {
7111
7155
  const config = this.stateManager.getConfig();
7112
7156
  const crop = this.sessionCrops.get(sessionId);
7113
- const cropConfig = crop ? crop.box : void 0;
7114
- const effectiveViewport = crop ? { width: crop.box.width, height: crop.box.height } : frameViewport;
7157
+ const cropFitsViewport = crop ? crop.box.x >= 0 && crop.box.y >= 0 && crop.box.x + crop.box.width <= frameViewport.width + 1 && crop.box.y + crop.box.height <= frameViewport.height + 1 : true;
7158
+ const cropConfig = crop && cropFitsViewport ? crop.box : void 0;
7159
+ const frameIsAlreadyCrop = crop && !cropConfig && Math.abs(frameViewport.width - crop.box.width) <= 1 && Math.abs(frameViewport.height - crop.box.height) <= 1;
7160
+ const processCrop = frameIsAlreadyCrop ? void 0 : cropConfig;
7161
+ const effectiveViewport = cropConfig ? { width: cropConfig.width, height: cropConfig.height } : frameViewport;
7115
7162
  const adjustedConfig = adjustConfigForSize(
7116
7163
  config,
7117
7164
  effectiveViewport.width,
@@ -7122,11 +7169,12 @@ var StreamCoordinator = class {
7122
7169
  const processedBuffer = await this.frameProcessor.process(
7123
7170
  frameData,
7124
7171
  adjustedConfig,
7125
- // Pass the ORIGINAL viewport (not cropped) so crop coordinates
7126
- // can be scaled correctly from viewport space to frame pixel space.
7127
- crop ? frameViewport.width : effectiveViewport.width,
7128
- crop ? frameViewport.height : effectiveViewport.height,
7129
- cropConfig
7172
+ // The full viewport maps crop coordinates to source-frame pixels.
7173
+ // FrameProcessor sizes the final crop from cropConfig, never from this
7174
+ // full-page viewport.
7175
+ frameViewport.width,
7176
+ frameViewport.height,
7177
+ processCrop
7130
7178
  );
7131
7179
  const header = Buffer.from(JSON.stringify({
7132
7180
  type: "screenshot",
@@ -7135,7 +7183,7 @@ var StreamCoordinator = class {
7135
7183
  id: frameId,
7136
7184
  timestamp: frameTimestamp,
7137
7185
  url: frameUrl,
7138
- viewport: effectiveViewport,
7186
+ viewport: cropConfig ? effectiveViewport : frameViewport,
7139
7187
  streamState: this.stateManager.getState(),
7140
7188
  fps: this.frameRateController.getCurrentFps()
7141
7189
  }
@@ -7143,6 +7191,8 @@ var StreamCoordinator = class {
7143
7191
  const headerLen = Buffer.alloc(4);
7144
7192
  headerLen.writeUInt32BE(header.length, 0);
7145
7193
  const payload = Buffer.concat([headerLen, header, processedBuffer]);
7194
+ this.lastFrameData = frameData;
7195
+ this.lastFrameViewport = frameViewport;
7146
7196
  this.sink.broadcastBinaryToSession(sessionId, payload);
7147
7197
  }
7148
7198
  };
@@ -7277,21 +7327,58 @@ var ElementMonitor = class {
7277
7327
  if (this.getClientCount() <= 0) return;
7278
7328
  try {
7279
7329
  const elements = await this.page.evaluate(() => {
7280
- const sel = '[role="dialog"],dialog,[class*="modal"],[class*="popup"],[class*="overlay"],[class*="drawer"],form';
7330
+ const sel = [
7331
+ '[role="dialog"]',
7332
+ "dialog",
7333
+ '[class*="modal"]',
7334
+ '[class*="popup"]',
7335
+ '[class*="overlay"]',
7336
+ '[class*="drawer"]',
7337
+ "form",
7338
+ "img",
7339
+ "canvas"
7340
+ ].join(",");
7281
7341
  const els = document.querySelectorAll(sel);
7282
7342
  const results = [];
7283
7343
  const vpW = window.innerWidth, vpH = window.innerHeight;
7284
7344
  for (const el of els) {
7285
7345
  const r = el.getBoundingClientRect();
7286
- if (r.width < 50 || r.height < 30) continue;
7287
- if (r.width * r.height > vpW * vpH * 0.9) continue;
7288
7346
  const style = window.getComputedStyle(el);
7289
7347
  if (style.display === "none" || style.visibility === "hidden" || style.opacity === "0") continue;
7348
+ if (r.bottom < 0 || r.right < 0 || r.top > vpH || r.left > vpW) continue;
7290
7349
  const htmlEl = el;
7350
+ const isImage = el.tagName === "IMG" || el.tagName === "CANVAS";
7351
+ const semantic = `${el.id} ${typeof htmlEl.className === "string" ? htmlEl.className : ""} ${el.getAttribute("alt") || ""} ${el.getAttribute("title") || ""} ${el.getAttribute("src") || ""}`.toLowerCase();
7352
+ const looksLikeQr = isImage && /(qr|qrcode|barcode|二维码)/.test(semantic);
7353
+ const square = Math.abs(r.width - r.height) <= Math.max(8, Math.min(r.width, r.height) * 0.12);
7354
+ if (isImage) {
7355
+ if (r.width < 48 || r.height < 48) continue;
7356
+ if (r.width > vpW || r.height > vpH) continue;
7357
+ if (looksLikeQr && !square) continue;
7358
+ if (!looksLikeQr && !el.getAttribute("src") && !el.getAttribute("alt") && !el.getAttribute("title")) continue;
7359
+ } else {
7360
+ if (r.width < 50 || r.height < 30) continue;
7361
+ if (r.width * r.height > vpW * vpH * 0.9) continue;
7362
+ }
7363
+ let kind = "view";
7364
+ let src;
7365
+ let text;
7366
+ if (looksLikeQr) {
7367
+ kind = "qr";
7368
+ src = el.getAttribute("src") || void 0;
7369
+ text = el.getAttribute("alt") || el.getAttribute("title") || void 0;
7370
+ } else if (isImage) {
7371
+ kind = "image";
7372
+ src = el.getAttribute("src") || void 0;
7373
+ text = el.getAttribute("alt") || el.getAttribute("title") || void 0;
7374
+ }
7291
7375
  results.push({
7292
7376
  tag: el.tagName,
7293
7377
  id: el.id || "",
7294
7378
  cls: (typeof htmlEl.className === "string" ? htmlEl.className : "").slice(0, 40),
7379
+ kind,
7380
+ ...src ? { src } : {},
7381
+ ...text ? { text } : {},
7295
7382
  rect: { x: Math.round(r.x), y: Math.round(r.y), width: Math.round(r.width), height: Math.round(r.height) }
7296
7383
  });
7297
7384
  }
@@ -7308,9 +7395,12 @@ var ElementMonitor = class {
7308
7395
  if (!dupe) deduped.push(el);
7309
7396
  }
7310
7397
  deduped.sort((a, b) => b.rect.width * b.rect.height - a.rect.width * a.rect.height);
7398
+ deduped.sort((a, b) => Number(b.kind === "qr") - Number(a.kind === "qr"));
7311
7399
  const views = deduped.map((e, i) => ({
7312
7400
  id: "el-" + i + "-" + (e.id || e.tag),
7313
- label: e.id || e.cls || e.tag,
7401
+ label: e.kind === "qr" ? e.text || "QR code" : e.kind === "image" ? e.text || e.src || "Image" : e.id || e.cls || e.tag,
7402
+ kind: e.kind,
7403
+ ...e.src ? { src: e.src } : {},
7314
7404
  rect: e.rect
7315
7405
  }));
7316
7406
  this.onViewsUpdate({ type: "views_update", views });
@@ -7363,7 +7453,11 @@ var SessionManager = class extends EventEmitter {
7363
7453
  // Session registration
7364
7454
  // -----------------------------------------------------------------------
7365
7455
  registerSession(sessionId, page, options) {
7366
- if (this.screencasts.has(sessionId)) return;
7456
+ if (this.screencasts.has(sessionId)) {
7457
+ if (this.screencasts.get(sessionId).page === page) return;
7458
+ this.updateSessionPage(sessionId, page);
7459
+ return;
7460
+ }
7367
7461
  this.screencasts.set(sessionId, {
7368
7462
  capturer: new ScreencastCapturer({
7369
7463
  interval: options?.interval ?? 100,
@@ -7389,6 +7483,53 @@ var SessionManager = class extends EventEmitter {
7389
7483
  }
7390
7484
  }
7391
7485
  }
7486
+ // Per-session serialization for page switches: rapid `tab switch` commands
7487
+ // must not interleave stopCapture/startCapture on the shared capturer.
7488
+ pageSwitchTasks = /* @__PURE__ */ new Map();
7489
+ /**
7490
+ * Rebind an already-registered session to a new Page (e.g. after
7491
+ * `tab switch` / `tab new` / `tab close` rebound the session's active
7492
+ * page). Moves the ElementMonitor to the new page, notifies viewers via
7493
+ * the `page-switched` event, and restarts the capturer when it is
7494
+ * streaming so frames immediately come from the new tab.
7495
+ */
7496
+ updateSessionPage(sessionId, page) {
7497
+ const sc = this.screencasts.get(sessionId);
7498
+ if (!sc || sc.page === page) return;
7499
+ const oldMonitor = this.monitors.get(sessionId);
7500
+ if (oldMonitor) {
7501
+ oldMonitor.stop();
7502
+ this.monitors.delete(sessionId);
7503
+ }
7504
+ const monitor = new ElementMonitor(
7505
+ page,
7506
+ (msg) => this.emit("broadcast", sessionId, msg),
7507
+ (msg) => this.emit("broadcast", sessionId, msg),
7508
+ () => this.getSessionClientCount(sessionId)
7509
+ );
7510
+ this.monitors.set(sessionId, monitor);
7511
+ monitor.start();
7512
+ sc.page = page;
7513
+ this.emit("page-switched", sessionId, page);
7514
+ const prev = this.pageSwitchTasks.get(sessionId) ?? Promise.resolve();
7515
+ const task = prev.catch(() => {
7516
+ }).then(async () => {
7517
+ const cur = this.screencasts.get(sessionId);
7518
+ if (!cur || cur.page !== page) return;
7519
+ if (cur.capturer.isActive()) {
7520
+ await cur.capturer.stopCapture().catch(() => {
7521
+ });
7522
+ }
7523
+ if (this.screencasts.get(sessionId) === cur && !cur.capturer.isActive() && cur.clientCount > 0) {
7524
+ await this.startCapturer(sessionId).catch(() => {
7525
+ });
7526
+ }
7527
+ });
7528
+ this.pageSwitchTasks.set(sessionId, task);
7529
+ task.finally(() => {
7530
+ if (this.pageSwitchTasks.get(sessionId) === task) this.pageSwitchTasks.delete(sessionId);
7531
+ });
7532
+ }
7392
7533
  unregisterSession(sessionId) {
7393
7534
  const sc = this.screencasts.get(sessionId);
7394
7535
  if (!sc) return;
@@ -7956,6 +8097,10 @@ var WSServer = class extends EventEmitter2 {
7956
8097
  this.sessionManager.on("screencast-stopped", (sessionId) => {
7957
8098
  this.emit("screencast-stopped", sessionId);
7958
8099
  });
8100
+ this.sessionManager.on("page-switched", (sessionId, page) => {
8101
+ this.streamCoordinator.clearLastFrame();
8102
+ this.broadcastToSession(sessionId, { type: "navigation", url: page.url(), title: "" });
8103
+ });
7959
8104
  }
7960
8105
  // -----------------------------------------------------------------------
7961
8106
  // Public session API (delegates to SessionManager)
@@ -8194,7 +8339,11 @@ var WSServer = class extends EventEmitter2 {
8194
8339
  return;
8195
8340
  }
8196
8341
  const fmt = msg.format === "webp" ? "webp" : "png";
8197
- page2.screenshot({ type: fmt, quality: fmt === "webp" ? msg.quality ?? 90 : void 0 }).then((buf) => {
8342
+ page2.screenshot({
8343
+ type: fmt,
8344
+ quality: fmt === "webp" ? msg.quality ?? 90 : void 0,
8345
+ ...msg.clip ? { clip: { ...msg.clip, scale: msg.scale } } : {}
8346
+ }).then((buf) => {
8198
8347
  this.sendToClient(clientId, {
8199
8348
  type: "snapshot_result",
8200
8349
  data: { data: buf.toString("base64"), format: fmt }
@@ -9348,7 +9497,7 @@ var DataCollector = class {
9348
9497
  return results;
9349
9498
  }
9350
9499
  async createBrowserContext() {
9351
- const { launch } = await import("./cdp-driver-AAS55KT2.js");
9500
+ const { launch } = await import("./cdp-driver-3ETNFQA4.js");
9352
9501
  const { browser } = await launch({
9353
9502
  headless: true,
9354
9503
  args: ["--no-sandbox", "--disable-setuid-sandbox"]
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  HumanInteractionManager
3
- } from "./chunk-FNXA6FDM.js";
3
+ } from "./chunk-BND5O5KC.js";
4
4
  import {
5
5
  buildViewerUrl
6
6
  } from "./chunk-3OD76SUE.js";
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  HumanInteractionManager
3
- } from "./chunk-PGKV24QN.js";
3
+ } from "./chunk-TBJUSUKF.js";
4
4
  import {
5
5
  buildViewerUrl
6
6
  } from "./chunk-TZPKFUBT.js";
7
- import "./chunk-HBMEFSTB.js";
7
+ import "./chunk-QCV2PI7U.js";
8
8
  import "./chunk-CG3D3CHY.js";
9
9
  import "./chunk-KFQGP6VL.js";
10
10
 
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-3OD76SUE.js";
4
4
  import {
5
5
  HumanInteractionManager
6
- } from "./chunk-SOPN4XDK.js";
6
+ } from "./chunk-O5PASNI7.js";
7
7
  import "./chunk-ZTHE5RBZ.js";
8
8
  import "./chunk-Q2DFJQGS.js";
9
9
  import "./chunk-KFQGP6VL.js";
@@ -1,13 +1,13 @@
1
1
  import {
2
2
  executeChain,
3
3
  executeCommand
4
- } from "./chunk-GDKKVT2P.js";
5
- import "./chunk-P33R7F2D.js";
4
+ } from "./chunk-KPTD3SNJ.js";
5
+ import "./chunk-BOZTIIBT.js";
6
6
  import "./chunk-JKVUFP3G.js";
7
7
  import "./chunk-3OD76SUE.js";
8
8
  import "./chunk-ZTHE5RBZ.js";
9
9
  import "./chunk-Q2DFJQGS.js";
10
- import "./chunk-N5XTLNKS.js";
10
+ import "./chunk-SPNWUUHA.js";
11
11
  import "./chunk-SMYSNO4M.js";
12
12
  import "./chunk-2KPI5GKP.js";
13
13
  import "./chunk-GDKLH7ZY.js";
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  executeChain,
3
3
  executeCommand
4
- } from "./chunk-SCYBNSOG.js";
4
+ } from "./chunk-3K57RYVC.js";
5
5
  import "./chunk-JKVUFP3G.js";
6
6
  import "./chunk-3OD76SUE.js";
7
7
  import "./chunk-ZTHE5RBZ.js";
8
8
  import "./chunk-Q2DFJQGS.js";
9
- import "./chunk-LFSLNHW5.js";
9
+ import "./chunk-OSIDUT4H.js";
10
10
  import "./chunk-SMYSNO4M.js";
11
11
  import "./chunk-2KPI5GKP.js";
12
12
  import "./chunk-GDKLH7ZY.js";
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  SessionRecorder
3
- } from "./chunk-FCPVQFTQ.js";
3
+ } from "./chunk-VYTQLZAX.js";
4
4
  import "./chunk-KFQGP6VL.js";
5
5
  export {
6
6
  SessionRecorder
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  SessionRecorder
3
- } from "./chunk-UZ6XPUBD.js";
3
+ } from "./chunk-RMYKVZIZ.js";
4
4
  import "./chunk-OZKD3W4X.js";
5
5
  import "./chunk-KFQGP6VL.js";
6
6
  export {
@@ -142,7 +142,7 @@ var SessionReplayer = class {
142
142
  if (this.opts.page) {
143
143
  this.page = this.opts.page;
144
144
  } else if (this.opts.cdpUrl) {
145
- const { launch } = await import("./cdp-driver-O5I7SJ24.js");
145
+ const { launch } = await import("./cdp-driver-WBFJNOLD.js");
146
146
  const { browser } = await launch({ cdpEndpoint: this.opts.cdpUrl });
147
147
  let contexts = browser.contexts();
148
148
  for (let i = 0; i < 10 && contexts.length === 0; i++) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xbrowser/cli",
3
- "version": "1.29.0",
3
+ "version": "1.30.0",
4
4
  "description": "Browser automation CLI for web scraping, headless browsing, SEO analysis, and AI agent workflows. A command-line alternative to Playwright, Puppeteer, and Selenium.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -112,6 +112,7 @@
112
112
  "devDependencies": {
113
113
  "@tailwindcss/vite": "^4.2.4",
114
114
  "@types/node": "^20.0.0",
115
+ "@types/qrcode": "^1.5.6",
115
116
  "@types/ws": "^8.18.1",
116
117
  "@typescript-eslint/eslint-plugin": "^8.59.2",
117
118
  "@typescript-eslint/parser": "^8.59.2",
@@ -119,7 +120,9 @@
119
120
  "eslint": "^10.3.0",
120
121
  "eslint-config-prettier": "^10.1.8",
121
122
  "husky": "^9.1.7",
123
+ "jsqr": "^1.4.0",
122
124
  "lint-staged": "^17.0.3",
125
+ "qrcode": "^1.5.4",
123
126
  "tailwindcss": "^4.2.4",
124
127
  "tsup": "^8.0.0",
125
128
  "typescript": "^5.0.0",