@pyrokine/mcp-chrome 3.0.0 → 3.1.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 (144) hide show
  1. package/README.md +721 -303
  2. package/README_zh.md +750 -292
  3. package/dist/cdp/client.d.ts +7 -3
  4. package/dist/cdp/client.d.ts.map +1 -1
  5. package/dist/cdp/client.js +252 -63
  6. package/dist/cdp/client.js.map +1 -1
  7. package/dist/cdp/launcher.d.ts +1 -1
  8. package/dist/cdp/launcher.d.ts.map +1 -1
  9. package/dist/cdp/launcher.js +33 -12
  10. package/dist/cdp/launcher.js.map +1 -1
  11. package/dist/core/auto-wait.d.ts.map +1 -1
  12. package/dist/core/auto-wait.js +88 -52
  13. package/dist/core/auto-wait.js.map +1 -1
  14. package/dist/core/browser-driver.d.ts +76 -18
  15. package/dist/core/browser-driver.d.ts.map +1 -1
  16. package/dist/core/browser-driver.js.map +1 -1
  17. package/dist/core/browser-event-schema.d.ts +287 -0
  18. package/dist/core/browser-event-schema.d.ts.map +1 -0
  19. package/dist/core/browser-event-schema.js +104 -0
  20. package/dist/core/browser-event-schema.js.map +1 -0
  21. package/dist/core/browser-events.d.ts +99 -0
  22. package/dist/core/browser-events.d.ts.map +1 -0
  23. package/dist/core/browser-events.js +1312 -0
  24. package/dist/core/browser-events.js.map +1 -0
  25. package/dist/core/challenge-page.d.ts +39 -0
  26. package/dist/core/challenge-page.d.ts.map +1 -0
  27. package/dist/core/challenge-page.js +226 -0
  28. package/dist/core/challenge-page.js.map +1 -0
  29. package/dist/core/dom-helpers.d.ts +28 -0
  30. package/dist/core/dom-helpers.d.ts.map +1 -0
  31. package/dist/core/dom-helpers.js +311 -0
  32. package/dist/core/dom-helpers.js.map +1 -0
  33. package/dist/core/errors.d.ts +10 -4
  34. package/dist/core/errors.d.ts.map +1 -1
  35. package/dist/core/errors.js +63 -13
  36. package/dist/core/errors.js.map +1 -1
  37. package/dist/core/file-upload.d.ts +22 -0
  38. package/dist/core/file-upload.d.ts.map +1 -0
  39. package/dist/core/file-upload.js +194 -0
  40. package/dist/core/file-upload.js.map +1 -0
  41. package/dist/core/locator.d.ts +17 -2
  42. package/dist/core/locator.d.ts.map +1 -1
  43. package/dist/core/locator.js +156 -212
  44. package/dist/core/locator.js.map +1 -1
  45. package/dist/core/os-mouse.d.ts +11 -0
  46. package/dist/core/os-mouse.d.ts.map +1 -1
  47. package/dist/core/os-mouse.js +102 -29
  48. package/dist/core/os-mouse.js.map +1 -1
  49. package/dist/core/retry.d.ts.map +1 -1
  50. package/dist/core/retry.js +4 -1
  51. package/dist/core/retry.js.map +1 -1
  52. package/dist/core/session.d.ts +65 -14
  53. package/dist/core/session.d.ts.map +1 -1
  54. package/dist/core/session.js +1089 -273
  55. package/dist/core/session.js.map +1 -1
  56. package/dist/core/types.d.ts +5 -1
  57. package/dist/core/types.d.ts.map +1 -1
  58. package/dist/core/types.js +16 -1
  59. package/dist/core/types.js.map +1 -1
  60. package/dist/core/unified-session.d.ts +50 -41
  61. package/dist/core/unified-session.d.ts.map +1 -1
  62. package/dist/core/unified-session.js +938 -285
  63. package/dist/core/unified-session.js.map +1 -1
  64. package/dist/core/utils.d.ts +5 -4
  65. package/dist/core/utils.d.ts.map +1 -1
  66. package/dist/core/utils.js +73 -18
  67. package/dist/core/utils.js.map +1 -1
  68. package/dist/extension/bridge.d.ts +50 -19
  69. package/dist/extension/bridge.d.ts.map +1 -1
  70. package/dist/extension/bridge.js +289 -57
  71. package/dist/extension/bridge.js.map +1 -1
  72. package/dist/extension/http-server.d.ts +7 -2
  73. package/dist/extension/http-server.d.ts.map +1 -1
  74. package/dist/extension/http-server.js +219 -48
  75. package/dist/extension/http-server.js.map +1 -1
  76. package/dist/index.js +14 -1
  77. package/dist/index.js.map +1 -1
  78. package/dist/tools/browse.d.ts.map +1 -1
  79. package/dist/tools/browse.js +66 -32
  80. package/dist/tools/browse.js.map +1 -1
  81. package/dist/tools/browser-event-output.d.ts +7 -0
  82. package/dist/tools/browser-event-output.d.ts.map +1 -0
  83. package/dist/tools/browser-event-output.js +19 -0
  84. package/dist/tools/browser-event-output.js.map +1 -0
  85. package/dist/tools/challenge.d.ts +17 -5
  86. package/dist/tools/challenge.d.ts.map +1 -1
  87. package/dist/tools/challenge.js +113 -195
  88. package/dist/tools/challenge.js.map +1 -1
  89. package/dist/tools/cookies.d.ts.map +1 -1
  90. package/dist/tools/cookies.js +33 -8
  91. package/dist/tools/cookies.js.map +1 -1
  92. package/dist/tools/diagnostics.d.ts.map +1 -1
  93. package/dist/tools/diagnostics.js +14 -0
  94. package/dist/tools/diagnostics.js.map +1 -1
  95. package/dist/tools/evaluate.d.ts +6 -5
  96. package/dist/tools/evaluate.d.ts.map +1 -1
  97. package/dist/tools/evaluate.js +102 -52
  98. package/dist/tools/evaluate.js.map +1 -1
  99. package/dist/tools/extract.d.ts.map +1 -1
  100. package/dist/tools/extract.js +178 -124
  101. package/dist/tools/extract.js.map +1 -1
  102. package/dist/tools/input.d.ts.map +1 -1
  103. package/dist/tools/input.js +623 -271
  104. package/dist/tools/input.js.map +1 -1
  105. package/dist/tools/logs.d.ts.map +1 -1
  106. package/dist/tools/logs.js +50 -11
  107. package/dist/tools/logs.js.map +1 -1
  108. package/dist/tools/manage.d.ts.map +1 -1
  109. package/dist/tools/manage.js +127 -46
  110. package/dist/tools/manage.js.map +1 -1
  111. package/dist/tools/network-sanitizer.d.ts +1 -0
  112. package/dist/tools/network-sanitizer.d.ts.map +1 -1
  113. package/dist/tools/network-sanitizer.js +30 -1
  114. package/dist/tools/network-sanitizer.js.map +1 -1
  115. package/dist/tools/page-context.d.ts +4 -3
  116. package/dist/tools/page-context.d.ts.map +1 -1
  117. package/dist/tools/page-context.js +56 -14
  118. package/dist/tools/page-context.js.map +1 -1
  119. package/dist/tools/post-condition.d.ts +1 -1
  120. package/dist/tools/post-condition.d.ts.map +1 -1
  121. package/dist/tools/post-condition.js +153 -47
  122. package/dist/tools/post-condition.js.map +1 -1
  123. package/dist/tools/schema.d.ts +7 -4
  124. package/dist/tools/schema.d.ts.map +1 -1
  125. package/dist/tools/schema.js +32 -122
  126. package/dist/tools/schema.js.map +1 -1
  127. package/dist/tools/target-diagnostics.d.ts +10 -2
  128. package/dist/tools/target-diagnostics.d.ts.map +1 -1
  129. package/dist/tools/target-diagnostics.js +74 -21
  130. package/dist/tools/target-diagnostics.js.map +1 -1
  131. package/dist/tools/wait.d.ts.map +1 -1
  132. package/dist/tools/wait.js +108 -42
  133. package/dist/tools/wait.js.map +1 -1
  134. package/extension/dist/assets/{content.ts-C4imZ6A9.js → content.ts-BAMOcF3R.js} +1 -1
  135. package/extension/dist/assets/{content.ts-loader-CnJuCGhl.js → content.ts-loader-4F9a1EWZ.js} +1 -1
  136. package/extension/dist/assets/index.ts-B79g2ikq.js +19820 -0
  137. package/extension/dist/assets/{page-scripts-CMIY1zhd.js → page-scripts-CSxn58h1.js} +300 -410
  138. package/extension/dist/assets/{popup.html-CgtWL6Py.js → popup.html-DwwHo00N.js} +8 -6
  139. package/extension/dist/manifest.json +4 -4
  140. package/extension/dist/service-worker-loader.js +1 -1
  141. package/extension/dist/src/popup/popup.html +3 -3
  142. package/package.json +15 -7
  143. package/scripts/start-chrome.ps1 +9 -1
  144. package/extension/dist/assets/index.ts-GeHNZBml.js +0 -8972
@@ -1,27 +1,74 @@
1
1
  //#region src/background/page-scripts.ts
2
+ function observeNativePointer(operation, id, deadline) {
3
+ const scope = globalThis;
4
+ if (operation === "start") {
5
+ scope.__mcpNativePointer?.stop();
6
+ const listener = (event) => {
7
+ if (event.isTrusted && scope.__mcpNativePointer?.id === id) {
8
+ scope.__mcpNativePointer.sample = {
9
+ at: Date.now(),
10
+ previousAt: scope.__mcpNativePointer.sample?.at,
11
+ sameTarget: scope.__mcpNativePointer.target === event.target,
12
+ clientX: event.clientX,
13
+ clientY: event.clientY,
14
+ screenX: event.screenX,
15
+ screenY: event.screenY,
16
+ scale: window.devicePixelRatio || 1
17
+ };
18
+ scope.__mcpNativePointer.target = event.target;
19
+ }
20
+ };
21
+ const stop = () => {
22
+ removeEventListener("pointermove", listener, true);
23
+ clearTimeout(timer);
24
+ if (scope.__mcpNativePointer?.id === id) delete scope.__mcpNativePointer;
25
+ };
26
+ const timer = setTimeout(stop, Math.max(0, deadline - Date.now()));
27
+ scope.__mcpNativePointer = {
28
+ id,
29
+ stop
30
+ };
31
+ addEventListener("pointermove", listener, true);
32
+ }
33
+ const current = scope.__mcpNativePointer;
34
+ if (current?.id !== id) return { active: false };
35
+ if (operation === "stop") current.stop();
36
+ return {
37
+ active: true,
38
+ sample: current.sample
39
+ };
40
+ }
2
41
  function installFrameProbeListener() {
3
42
  const probeWindow = window;
4
- if (probeWindow.__mcpFrameProbeListenerInstalled) return;
5
- window.addEventListener("message", (event) => {
43
+ if (probeWindow.__mcpFrameProbeListenerV2) return;
44
+ const onMessage = async (event) => {
6
45
  const data = event.data;
7
- if (event.source !== window.parent || data?.type !== "mcp-frame-probe" || typeof data.token !== "string" || data.token.length > 100 || !Number.isInteger(data.index) || (data.index ?? -1) < 0) return;
46
+ if (event.source !== window.parent || data?.type !== "mcp-frame-probe-v2" || typeof data.token !== "string" || data.token.length > 100 || !Number.isInteger(data.index) || (data.index ?? -1) < 0) return;
8
47
  const source = event.source;
9
- chrome.runtime.sendMessage({
10
- type: "MCP_FRAME_PROBE",
11
- token: data.token,
12
- index: data.index
13
- }).then((response) => {
14
- if (!response?.accepted) return;
15
- source.postMessage({
16
- type: "mcp-frame-probe-ack",
48
+ try {
49
+ const runtime = typeof chrome === "undefined" ? void 0 : chrome.runtime;
50
+ if (typeof runtime?.sendMessage !== "function") throw new Error("Extension context invalidated: runtime messaging is unavailable");
51
+ if ((await runtime.sendMessage({
52
+ type: "MCP_FRAME_PROBE",
53
+ token: data.token,
54
+ index: data.index
55
+ }))?.accepted) source.postMessage({
56
+ type: "mcp-frame-probe-ack-v2",
17
57
  token: data.token,
18
58
  index: data.index
19
59
  }, "*");
20
- }).catch((error) => {
21
- console.warn("[MCP] iframe identity probe failed:", error instanceof Error ? error.message : String(error));
22
- });
23
- });
24
- probeWindow.__mcpFrameProbeListenerInstalled = true;
60
+ } catch (error) {
61
+ const message = error instanceof Error ? error.message : String(error);
62
+ if (/Extension context invalidated/i.test(message)) {
63
+ if (probeWindow.__mcpFrameProbeListenerV2 !== onMessage) return;
64
+ window.removeEventListener("message", onMessage);
65
+ delete probeWindow.__mcpFrameProbeListenerV2;
66
+ }
67
+ console.warn("[MCP] iframe identity probe failed:", message);
68
+ }
69
+ };
70
+ window.addEventListener("message", onMessage);
71
+ probeWindow.__mcpFrameProbeListenerV2 = onMessage;
25
72
  }
26
73
  function generateAccessibilityTree(filter, maxDepth, maxLength, refId, expectedUrl) {
27
74
  if (expectedUrl != null && location.href !== expectedUrl) throw new Error("页面 URL 已变化,未读取");
@@ -31,83 +78,24 @@ function generateAccessibilityTree(filter, maxDepth, maxLength, refId, expectedU
31
78
  win.__mcpRefCounter = win.__mcpRefCounter || 0;
32
79
  const lines = [];
33
80
  function getRole(element) {
34
- const role = element.getAttribute("role");
35
- if (role) return role;
36
- const tag = element.tagName.toLowerCase();
37
- const type = element.getAttribute("type");
38
- return {
39
- a: "link",
40
- button: "button",
41
- input: type === "submit" || type === "button" ? "button" : type === "checkbox" ? "checkbox" : type === "radio" ? "radio" : type === "file" ? "button" : "textbox",
42
- select: "combobox",
43
- textarea: "textbox",
44
- h1: "heading",
45
- h2: "heading",
46
- h3: "heading",
47
- h4: "heading",
48
- h5: "heading",
49
- h6: "heading",
50
- img: "image",
51
- nav: "navigation",
52
- main: "main",
53
- header: "banner",
54
- footer: "contentinfo",
55
- section: "region",
56
- article: "article",
57
- aside: "complementary",
58
- form: "form",
59
- table: "table",
60
- ul: "list",
61
- ol: "list",
62
- li: "listitem",
63
- label: "label"
64
- }[tag] || "generic";
81
+ return globalThis.__mcpDomHelpers.role(element);
65
82
  }
66
83
  function getName(element) {
67
- const tag = element.tagName.toLowerCase();
68
- if (tag === "select") {
69
- const select = element;
70
- const selected = select.querySelector("option[selected]") || select.options[select.selectedIndex];
71
- if (selected?.textContent) return selected.textContent.trim();
72
- }
73
- const ariaLabel = element.getAttribute("aria-label");
74
- if (ariaLabel?.trim()) return ariaLabel.trim();
75
- const placeholder = element.getAttribute("placeholder");
76
- if (placeholder?.trim()) return placeholder.trim();
77
- const title = element.getAttribute("title");
78
- if (title?.trim()) return title.trim();
79
- const alt = element.getAttribute("alt");
80
- if (alt?.trim()) return alt.trim();
81
- if (element.id) {
82
- const label = document.querySelector(`label[for="${CSS.escape(element.id)}"]`);
83
- if (label?.textContent?.trim()) return label.textContent.trim();
84
- }
85
- if (tag === "input") {
86
- const input = element;
87
- const inputType = input.type || "";
88
- if (inputType === "submit" && input.value?.trim()) return input.value.trim();
89
- if (inputType !== "password" && input.value && input.value.length < 50) return input.value.trim();
90
- }
84
+ return globalThis.__mcpDomHelpers.accessibleName(element, filter === "all");
85
+ }
86
+ function currentValue(element, name) {
87
+ if (element.tagName.toLowerCase() !== "input") return;
88
+ const input = element;
91
89
  if ([
90
+ "hidden",
91
+ "password",
92
+ "file"
93
+ ].includes(input.type) || name && [
92
94
  "button",
93
- "a",
94
- "summary"
95
- ].includes(tag)) {
96
- let text = "";
97
- for (const child of element.childNodes) if (child.nodeType === Node.TEXT_NODE) text += child.textContent;
98
- if (text.trim()) return text.trim();
99
- }
100
- if (tag.match(/^h[1-6]$/)) {
101
- const text = element.textContent;
102
- if (text?.trim()) return text.trim().substring(0, 100);
103
- }
104
- let textContent = "";
105
- for (const child of element.childNodes) if (child.nodeType === Node.TEXT_NODE) textContent += child.textContent;
106
- if (textContent.trim().length >= 3) {
107
- const trimmed = textContent.trim();
108
- return trimmed.length > 100 ? trimmed.substring(0, 100) + "..." : trimmed;
109
- }
110
- return "";
95
+ "submit",
96
+ "reset"
97
+ ].includes(input.type)) return;
98
+ return input.value;
111
99
  }
112
100
  function isVisible(element) {
113
101
  const style = window.getComputedStyle(element);
@@ -200,17 +188,18 @@ function generateAccessibilityTree(filter, maxDepth, maxLength, refId, expectedU
200
188
  function isCovered(element) {
201
189
  const rect = element.getBoundingClientRect();
202
190
  if (rect.width <= 0 || rect.height <= 0) return false;
203
- const hit = document.elementFromPoint(rect.x + rect.width / 2, rect.y + rect.height / 2);
204
- return Boolean(hit && hit !== element && !element.contains(hit) && !hit.contains(element));
191
+ const hit = globalThis.__mcpDomHelpers.deepElementFromPoint(rect.x + rect.width / 2, rect.y + rect.height / 2);
192
+ return Boolean(hit && !globalThis.__mcpDomHelpers.containsComposed(element, hit));
205
193
  }
206
194
  const interactiveElements = [];
207
- function rememberInteractive(element, elementRefId, role, name) {
195
+ function rememberInteractive(element, elementRefId, role, name, value) {
208
196
  if (!isInteractive(element) || interactiveElements.length >= 100) return;
209
197
  const rect = element.getBoundingClientRect();
210
198
  interactiveElements.push({
211
199
  refId: elementRefId,
212
200
  role,
213
201
  name,
202
+ ...value !== void 0 ? { value } : {},
214
203
  selector: cssSelector(element),
215
204
  visible: isVisible(element),
216
205
  disabled: isDisabled(element),
@@ -223,35 +212,50 @@ function generateAccessibilityTree(filter, maxDepth, maxLength, refId, expectedU
223
212
  covered: isCovered(element)
224
213
  });
225
214
  }
226
- function traverse(element, level, checkRefId) {
227
- if (level > maxDepth || !element || !element.tagName) return;
228
- const include = shouldInclude(element, checkRefId) || checkRefId && level === 0;
229
- if (include) {
230
- const role = getRole(element);
231
- const name = getName(element);
232
- const elementRefId = getOrCreateRef(element);
233
- let line = " ".repeat(level) + role;
234
- if (name) line += ` "${name.replace(/\s+/g, " ").replace(/"/g, "\\\"")}"`;
235
- line += ` [${elementRefId}]`;
236
- const href = element.getAttribute("href");
237
- if (href) line += ` href="${href}"`;
238
- const type = element.getAttribute("type");
239
- if (type) line += ` type="${type}"`;
240
- lines.push(line);
241
- rememberInteractive(element, elementRefId, role, name);
242
- if (element.tagName.toLowerCase() === "select") {
243
- const select = element;
244
- for (const option of select.options) {
245
- let optLine = " ".repeat(level + 1) + "option";
246
- const optText = option.textContent?.trim() || "";
247
- if (optText) optLine += ` "${optText.replace(/\s+/g, " ").substring(0, 100).replace(/"/g, "\\\"")}"`;
248
- if (option.selected) optLine += " (selected)";
249
- if (option.value && option.value !== optText) optLine += ` value="${option.value.replace(/"/g, "\\\"")}"`;
250
- lines.push(optLine);
215
+ function traverse(root, rootLevel, checkRefId) {
216
+ const pending = [{
217
+ element: root,
218
+ level: rootLevel
219
+ }];
220
+ while (pending.length) {
221
+ const { element, level } = pending.pop();
222
+ if (level > maxDepth || !element || !element.tagName) continue;
223
+ const include = shouldInclude(element, checkRefId) || checkRefId && level === 0;
224
+ if (include) {
225
+ const role = getRole(element);
226
+ const name = getName(element);
227
+ const elementRefId = getOrCreateRef(element);
228
+ let line = " ".repeat(level) + role;
229
+ if (name) line += ` "${name.replace(/\s+/g, " ").replace(/"/g, "\\\"")}"`;
230
+ line += ` [${elementRefId}]`;
231
+ const href = element.getAttribute("href");
232
+ if (href) line += ` href="${href}"`;
233
+ const type = element.getAttribute("type");
234
+ if (type) line += ` type="${type}"`;
235
+ const value = currentValue(element, name);
236
+ if (value !== void 0) line += ` value=${JSON.stringify(value)}`;
237
+ lines.push(line);
238
+ rememberInteractive(element, elementRefId, role, name, value);
239
+ if (element.tagName.toLowerCase() === "select") {
240
+ const select = element;
241
+ for (const option of select.options) {
242
+ let optLine = " ".repeat(level + 1) + "option";
243
+ const optText = option.textContent?.trim() || "";
244
+ if (optText) optLine += ` "${optText.replace(/\s+/g, " ").substring(0, 100).replace(/"/g, "\\\"")}"`;
245
+ if (option.selected) optLine += " (selected)";
246
+ if (option.value && option.value !== optText) optLine += ` value="${option.value.replace(/"/g, "\\\"")}"`;
247
+ lines.push(optLine);
248
+ }
251
249
  }
252
250
  }
251
+ if (element.children && level < maxDepth) {
252
+ const children = [...element.shadowRoot ? Array.from(element.shadowRoot.children) : [], ...Array.from(element.children)];
253
+ for (let index = children.length - 1; index >= 0; --index) pending.push({
254
+ element: children[index],
255
+ level: include ? level + 1 : level
256
+ });
257
+ }
253
258
  }
254
- if (element.children && level < maxDepth) for (const child of element.children) traverse(child, include ? level + 1 : level, checkRefId);
255
259
  }
256
260
  if (refId) {
257
261
  const ref = win.__mcpElementMap[refId];
@@ -300,7 +304,7 @@ function generateAccessibilityTree(filter, maxDepth, maxLength, refId, expectedU
300
304
  interactiveElements
301
305
  };
302
306
  }
303
- function performClick(refId) {
307
+ function performClick(refId, modifiers) {
304
308
  const ref = window.__mcpElementMap?.[refId];
305
309
  if (!ref) return {
306
310
  success: false,
@@ -317,7 +321,7 @@ function performClick(refId) {
317
321
  });
318
322
  const el = element;
319
323
  el.focus();
320
- el.click();
324
+ globalThis.__mcpDomHelpers.click(el, modifiers);
321
325
  return { success: true };
322
326
  }
323
327
  function performType(refId, text, clear) {
@@ -335,12 +339,18 @@ function performType(refId, text, clear) {
335
339
  el.focus();
336
340
  if ("value" in el) {
337
341
  el.value = clear ? text : el.value + text;
338
- el.dispatchEvent(new Event("input", { bubbles: true }));
342
+ el.dispatchEvent(new Event("input", {
343
+ bubbles: true,
344
+ composed: true
345
+ }));
339
346
  el.dispatchEvent(new Event("change", { bubbles: true }));
340
347
  } else if (element.contentEditable === "true") {
341
348
  if (clear) element.textContent = text;
342
349
  else element.textContent = (element.textContent || "") + text;
343
- element.dispatchEvent(new Event("input", { bubbles: true }));
350
+ element.dispatchEvent(new Event("input", {
351
+ bubbles: true,
352
+ composed: true
353
+ }));
344
354
  }
345
355
  return { success: true };
346
356
  }
@@ -375,48 +385,82 @@ function performScroll(x, y, refId) {
375
385
  };
376
386
  }
377
387
  async function executeCode(code, timeout) {
388
+ const errorText = (error) => {
389
+ try {
390
+ return error instanceof Error ? String(error.message) : String(error);
391
+ } catch {
392
+ return "Unprintable page exception";
393
+ }
394
+ };
378
395
  function evaluateSerializationError(message, suggestion, context) {
379
- return JSON.stringify({ error: {
380
- code: "NON_SERIALIZABLE_EVALUATE_RESULT",
381
- message,
382
- suggestion,
383
- context
384
- } });
396
+ return {
397
+ error: JSON.stringify({ error: {
398
+ code: "NON_SERIALIZABLE_EVALUATE_RESULT",
399
+ message,
400
+ suggestion,
401
+ context
402
+ } }),
403
+ errorMessage: message
404
+ };
385
405
  }
386
406
  function serializeEvaluateResult(result) {
387
- if (result instanceof Node) {
388
- const element = result instanceof Element ? result : result.parentElement;
389
- return {
407
+ try {
408
+ if (result instanceof Node) {
409
+ const element = result instanceof Element ? result : result.parentElement;
410
+ return {
411
+ success: false,
412
+ errorSource: "output",
413
+ ...evaluateSerializationError(`返回值是 DOM 节点 ${result.nodeName},不能直接 JSON 序列化`, "请返回 textContent、outerHTML、getAttribute(...) 等简单字段,或改用 extract type=\"text\"/\"html\"", {
414
+ nodeType: result.nodeType,
415
+ nodeName: result.nodeName,
416
+ selector: element?.id ? `#${CSS.escape(element.id)}` : element?.tagName.toLowerCase()
417
+ })
418
+ };
419
+ }
420
+ if (result instanceof NodeList || result instanceof HTMLCollection) return {
390
421
  success: false,
391
- error: evaluateSerializationError(`返回值是 DOM 节点 ${result.nodeName},不能直接 JSON 序列化`, "请返回 textContent、outerHTML、getAttribute(...) 等简单字段,或改用 extract type=\"text\"/\"html\"", {
392
- nodeType: result.nodeType,
393
- nodeName: result.nodeName,
394
- selector: element?.id ? `#${CSS.escape(element.id)}` : element?.tagName.toLowerCase()
422
+ errorSource: "output",
423
+ ...evaluateSerializationError(`返回值是 ${result.constructor.name},不能直接 JSON 序列化`, "请用 Array.from(value).map(...) 提取需要的字段,例如 textContent、href、outerHTML", {
424
+ className: result.constructor.name,
425
+ length: result.length
395
426
  })
396
427
  };
397
- }
398
- if (result instanceof NodeList || result instanceof HTMLCollection) return {
399
- success: false,
400
- error: evaluateSerializationError(`返回值是 ${result.constructor.name},不能直接 JSON 序列化`, "请用 Array.from(value).map(...) 提取需要的字段,例如 textContent、href、outerHTML", {
401
- className: result.constructor.name,
402
- length: result.length
403
- })
404
- };
405
- try {
406
428
  return {
407
429
  success: true,
408
430
  result: JSON.stringify(result)
409
431
  };
410
432
  } catch (error) {
411
- const errorMsg = error instanceof Error ? error.message : String(error);
412
- return {
413
- success: false,
414
- error: evaluateSerializationError(`evaluate 返回值无法 JSON 序列化: ${errorMsg}`, "请返回字符串、数字、布尔值、数组或普通对象,避免返回循环引用、BigInt、DOM 对象", { error: errorMsg })
415
- };
433
+ const errorMsg = errorText(error);
434
+ try {
435
+ return {
436
+ success: false,
437
+ errorSource: "output",
438
+ ...evaluateSerializationError(`evaluate 返回值检查或序列化失败: ${errorMsg}`, "请返回可 JSON 序列化的简单数据,并检查自定义原型或 getter 是否抛错", { error: errorMsg })
439
+ };
440
+ } catch (detailError) {
441
+ return {
442
+ success: false,
443
+ errorSource: "output",
444
+ errorCode: "NON_SERIALIZABLE_EVALUATE_RESULT",
445
+ error: `evaluate 返回值检查或序列化失败: ${errorMsg};输出错误详情生成失败: ${errorText(detailError)}`
446
+ };
447
+ }
416
448
  }
417
449
  }
450
+ let fn;
418
451
  try {
419
- const result = new Function(`return (${code})`)();
452
+ fn = new Function(`return (${code})`);
453
+ } catch (error) {
454
+ return {
455
+ success: false,
456
+ error: errorText(error),
457
+ errorSource: "context",
458
+ actionExecuted: false,
459
+ ...error instanceof EvalError ? { errorCode: "CSP_BLOCKED" } : {}
460
+ };
461
+ }
462
+ try {
463
+ const result = fn();
420
464
  if (timeout === void 0) return serializeEvaluateResult(await result);
421
465
  const timedOut = Symbol("evaluate-timeout");
422
466
  let timeoutId;
@@ -434,14 +478,10 @@ async function executeCode(code, timeout) {
434
478
  if (timeoutId !== void 0) clearTimeout(timeoutId);
435
479
  }
436
480
  } catch (error) {
437
- const errorMsg = error instanceof Error ? error.message : "Unknown error";
438
- if (errorMsg.includes("Content Security Policy") || errorMsg.includes("'unsafe-eval'")) return {
439
- success: false,
440
- error: `CSP 限制:此页面禁止动态代码执行,建议使用 extract 工具获取页面内容或使用 CDP 模式,原始错误: ${errorMsg}`
441
- };
442
481
  return {
443
482
  success: false,
444
- error: errorMsg
483
+ error: errorText(error),
484
+ errorSource: "page"
445
485
  };
446
486
  }
447
487
  }
@@ -591,87 +631,57 @@ function extractAttribute(selector, refId, attribute, expectedUrl) {
591
631
  }
592
632
  return { value: element.getAttribute(attribute) };
593
633
  }
594
- function findElements(selector, text, xpath, expectedUrl, point, matchIndex) {
634
+ function findElements(selector, text, xpath, expectedUrl, point, matchIndex, semantic) {
595
635
  if (expectedUrl != null && location.href !== expectedUrl) throw new Error("页面 URL 已变化,未读取");
636
+ const helpers = globalThis.__mcpDomHelpers;
637
+ if (!helpers) throw new Error("DOM query helpers are not installed");
638
+ if (!point && !selector && !text && !xpath && !semantic) return { error: "find requires at least one of: selector, xpath, text, semantic" };
596
639
  const win = window;
597
- win.__mcpElementMap = win.__mcpElementMap || {};
598
- win.__mcpElementToRefId = win.__mcpElementToRefId || /* @__PURE__ */ new WeakMap();
599
- win.__mcpRefCounter = win.__mcpRefCounter || 0;
600
- const results = [];
640
+ win.__mcpElementMap ??= {};
641
+ win.__mcpElementToRefId ??= /* @__PURE__ */ new WeakMap();
642
+ win.__mcpRefCounter ??= 0;
601
643
  let elements;
602
- if (point) {
603
- const element = document.elementFromPoint(point.x, point.y);
604
- elements = element ? [element] : [];
605
- } else if (xpath) {
606
- elements = [];
607
- const xpathResult = document.evaluate(xpath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
608
- for (let i = 0; i < xpathResult.snapshotLength; i++) {
609
- const node = xpathResult.snapshotItem(i);
610
- if (node instanceof Element) elements.push(node);
611
- }
612
- } else if (selector) try {
613
- elements = Array.from(document.querySelectorAll(selector));
614
- } catch (e) {
615
- const err = e;
616
- if (err?.name === "SyntaxError") return { error: `Invalid CSS selector: "${selector}" (${err.message})` };
617
- throw e;
644
+ try {
645
+ const hit = point ? helpers.deepElementFromPoint(point.x, point.y) : null;
646
+ elements = point ? hit ? [hit] : [] : helpers.query({
647
+ selector,
648
+ text,
649
+ xpath,
650
+ semantic
651
+ });
652
+ } catch (error) {
653
+ if (error.name === "SyntaxError") return { error: "Invalid CSS selector: " + selector };
654
+ throw error;
618
655
  }
619
- else if (text) {
620
- elements = [];
621
- const seen = /* @__PURE__ */ new Set();
622
- const walker = document.createTreeWalker(document.body || document.documentElement, NodeFilter.SHOW_TEXT, { acceptNode: (node) => node.data?.includes(text) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT });
623
- let n = walker.nextNode();
624
- let textMatchIndex = 0;
625
- while (n && (matchIndex !== void 0 || elements.length < 200)) {
626
- const parent = n.parentElement;
627
- if (parent && !seen.has(parent)) {
628
- seen.add(parent);
629
- if (matchIndex === void 0 || textMatchIndex++ === matchIndex) {
630
- elements.push(parent);
631
- if (matchIndex !== void 0) break;
632
- }
633
- }
634
- n = walker.nextNode();
635
- }
636
- } else return { error: "find requires at least one of: selector, xpath, text" };
637
- let matched = 0;
638
- for (const element of elements) {
639
- if (text) {
640
- if (!(element.textContent || "").includes(text)) continue;
641
- }
642
- if (matchIndex !== void 0 && (selector || xpath || point) && matched++ !== matchIndex) continue;
643
- let refId = win.__mcpElementToRefId.get(element) ?? null;
644
- if (refId && win.__mcpElementMap[refId]?.deref() !== element) refId = null;
656
+ const results = (matchIndex == null ? elements.slice(0, 50) : elements.slice(matchIndex, matchIndex + 1)).map((element) => {
657
+ let refId = win.__mcpElementToRefId.get(element);
658
+ if (refId && win.__mcpElementMap[refId]?.deref() !== element) refId = void 0;
645
659
  if (!refId) {
646
- refId = `ref_${++win.__mcpRefCounter}`;
660
+ refId = "ref_" + ++win.__mcpRefCounter;
647
661
  win.__mcpElementMap[refId] = new WeakRef(element);
648
662
  win.__mcpElementToRefId.set(element, refId);
649
663
  }
650
664
  const rect = element.getBoundingClientRect();
651
- results.push({
665
+ return {
652
666
  refId,
653
667
  tag: element.tagName.toLowerCase(),
654
- text: (element.textContent || "").trim().substring(0, 100),
668
+ text: (element.textContent ?? "").trim().substring(0, 100),
655
669
  rect: {
656
670
  x: rect.x,
657
671
  y: rect.y,
658
672
  width: rect.width,
659
673
  height: rect.height
660
674
  }
661
- });
662
- if (matchIndex !== void 0 || results.length >= 50) break;
663
- }
664
- {
665
- const w = window;
666
- const counter = (w.__mcpSweepCounter ?? 0) + 1;
667
- w.__mcpSweepCounter = counter;
668
- if (counter % 10 === 0 || Object.keys(win.__mcpElementMap).length > 500) {
669
- for (const id of Object.keys(win.__mcpElementMap)) if (!win.__mcpElementMap[id].deref()) delete win.__mcpElementMap[id];
670
- }
675
+ };
676
+ });
677
+ const counter = (win.__mcpSweepCounter ?? 0) + 1;
678
+ win.__mcpSweepCounter = counter;
679
+ if (counter % 10 === 0 || Object.keys(win.__mcpElementMap).length > 500) {
680
+ for (const [key, ref] of Object.entries(win.__mcpElementMap)) if (!ref.deref()?.isConnected) delete win.__mcpElementMap[key];
671
681
  }
672
682
  return results;
673
683
  }
674
- function simulateMouseClick(x, y, button, clickCount = 1, refId) {
684
+ function simulateMouseClick(x, y, button, clickCount = 1, refId, modifiers) {
675
685
  let element = null;
676
686
  if (refId) {
677
687
  const resolved = (window.__mcpElementMap?.[refId])?.deref();
@@ -682,19 +692,21 @@ function simulateMouseClick(x, y, button, clickCount = 1, refId) {
682
692
  y = r.y + r.height / 2;
683
693
  }
684
694
  }
685
- if (!element) element = document.elementFromPoint(x, y);
695
+ if (!element) element = globalThis.__mcpDomHelpers.deepElementFromPoint(x, y);
686
696
  if (!element) return { success: false };
687
697
  const buttonCode = button === "right" ? 2 : button === "middle" ? 1 : 0;
688
698
  const buttonsMask = button === "right" ? 2 : button === "middle" ? 4 : 1;
689
699
  const baseOptions = {
690
700
  bubbles: true,
701
+ composed: true,
691
702
  cancelable: true,
692
703
  view: window,
693
704
  clientX: x,
694
705
  clientY: y,
695
706
  screenX: x + window.screenX,
696
707
  screenY: y + window.screenY,
697
- button: buttonCode
708
+ button: buttonCode,
709
+ ...modifiers
698
710
  };
699
711
  const pressed = {
700
712
  ...baseOptions,
@@ -707,48 +719,36 @@ function simulateMouseClick(x, y, button, clickCount = 1, refId) {
707
719
  element.dispatchEvent(new MouseEvent("mouseover", released));
708
720
  element.dispatchEvent(new MouseEvent("mouseenter", {
709
721
  ...released,
710
- bubbles: false
722
+ bubbles: false,
723
+ composed: false,
724
+ cancelable: false
711
725
  }));
712
726
  element.dispatchEvent(new MouseEvent("mousemove", released));
713
- element.dispatchEvent(new MouseEvent("mousedown", {
714
- ...pressed,
715
- detail: 1
716
- }));
717
- if ("focus" in element && typeof element.focus === "function") element.focus();
718
- element.dispatchEvent(new MouseEvent("mouseup", {
719
- ...released,
720
- detail: 1
721
- }));
722
- if (button === "right") element.dispatchEvent(new MouseEvent("contextmenu", released));
723
- else element.dispatchEvent(new MouseEvent("click", {
724
- ...released,
725
- detail: 1
726
- }));
727
- for (let i = 2; i <= clickCount; i++) {
727
+ const clickType = button === "right" ? "contextmenu" : button === "middle" ? "auxclick" : "click";
728
+ for (let detail = 1; detail <= clickCount; ++detail) {
728
729
  element.dispatchEvent(new MouseEvent("mousedown", {
729
730
  ...pressed,
730
- detail: i
731
+ detail
731
732
  }));
733
+ if (detail === 1 && "focus" in element && typeof element.focus === "function") element.focus();
732
734
  element.dispatchEvent(new MouseEvent("mouseup", {
733
735
  ...released,
734
- detail: i
736
+ detail
737
+ }));
738
+ element.dispatchEvent(new MouseEvent(clickType, {
739
+ ...released,
740
+ detail
741
+ }));
742
+ if (button === "left" && detail === 2) element.dispatchEvent(new MouseEvent("dblclick", {
743
+ ...released,
744
+ detail
735
745
  }));
736
- if (button !== "right") {
737
- element.dispatchEvent(new MouseEvent("click", {
738
- ...released,
739
- detail: i
740
- }));
741
- if (i === 2) element.dispatchEvent(new MouseEvent("dblclick", {
742
- ...released,
743
- detail: i
744
- }));
745
- }
746
746
  }
747
747
  return { success: true };
748
748
  }
749
749
  async function simulateKeyboardType(text, delay, deadline) {
750
750
  const expired = () => deadline !== void 0 && Date.now() >= deadline;
751
- const activeElement = document.activeElement;
751
+ const activeElement = globalThis.__mcpDomHelpers.activeElement();
752
752
  if (!activeElement) return {
753
753
  success: false,
754
754
  error: "No active element"
@@ -779,6 +779,7 @@ async function simulateKeyboardType(text, delay, deadline) {
779
779
  };
780
780
  const keyEventOptions = {
781
781
  bubbles: true,
782
+ composed: true,
782
783
  cancelable: true,
783
784
  key: char,
784
785
  code: char >= "a" && char <= "z" ? `Key${char.toUpperCase()}` : char >= "A" && char <= "Z" ? `Key${char}` : char >= "0" && char <= "9" ? `Digit${char}` : "Key",
@@ -793,7 +794,7 @@ async function simulateKeyboardType(text, delay, deadline) {
793
794
  else if (activeElement.isContentEditable) activeElement.textContent = (activeElement.textContent || "") + char;
794
795
  activeElement.dispatchEvent(new InputEvent("input", {
795
796
  bubbles: true,
796
- cancelable: true,
797
+ composed: true,
797
798
  inputType: "insertText",
798
799
  data: char
799
800
  }));
@@ -807,10 +808,12 @@ async function simulateKeyboardType(text, delay, deadline) {
807
808
  activeElement.dispatchEvent(new Event("change", { bubbles: true }));
808
809
  return { success: true };
809
810
  }
810
- function simulateKeyEvent(key, type, modifiers) {
811
- const activeElement = document.activeElement || document.body;
811
+ function simulateKeyEvent(key, type, modifiers, deadline) {
812
+ if (deadline !== void 0 && Date.now() >= deadline) throw new Error("input timeout before event dispatch");
813
+ const activeElement = globalThis.__mcpDomHelpers.activeElement() || document.body;
812
814
  const keyEventOptions = {
813
815
  bubbles: true,
816
+ composed: true,
814
817
  cancelable: true,
815
818
  key,
816
819
  code: key.length === 1 ? `Key${key.toUpperCase()}` : key,
@@ -825,13 +828,14 @@ function simulateKeyEvent(key, type, modifiers) {
825
828
  if (type === "up" || type === "press") activeElement.dispatchEvent(new KeyboardEvent("keyup", keyEventOptions));
826
829
  return { success: true };
827
830
  }
828
- function simulateMouseEvent(type, x, y, button, deadline) {
829
- if (deadline !== void 0 && Date.now() >= deadline) throw new Error("input timeout before mouse event dispatch");
830
- const element = document.elementFromPoint(x, y) || document.body;
831
+ function simulateMouseEvent(type, x, y, button, deadline, modifiers) {
832
+ if (deadline != null && Date.now() >= deadline) throw new Error("input timeout before mouse event dispatch");
833
+ const element = globalThis.__mcpDomHelpers.deepElementFromPoint(x, y) || document.body;
831
834
  const buttonCode = button === "right" ? 2 : button === "middle" ? 1 : 0;
832
835
  const buttonsMask = button === "right" ? 2 : button === "middle" ? 4 : 1;
833
836
  const eventOptions = {
834
837
  bubbles: true,
838
+ composed: type !== "mouseenter" && type !== "mouseleave",
835
839
  cancelable: true,
836
840
  view: window,
837
841
  clientX: x,
@@ -839,12 +843,15 @@ function simulateMouseEvent(type, x, y, button, deadline) {
839
843
  screenX: x + window.screenX,
840
844
  screenY: y + window.screenY,
841
845
  button: buttonCode,
846
+ ...modifiers,
842
847
  buttons: type === "mousedown" ? buttonsMask : 0
843
848
  };
844
849
  element.dispatchEvent(new MouseEvent(type, eventOptions));
845
850
  if (type === "mousedown" && "focus" in element && typeof element.focus === "function") element.focus();
846
- if (type === "mouseup") if (button === "right") element.dispatchEvent(new MouseEvent("contextmenu", eventOptions));
847
- else element.dispatchEvent(new MouseEvent("click", eventOptions));
851
+ if (type === "mouseup") {
852
+ const clickType = button === "right" ? "contextmenu" : button === "middle" ? "auxclick" : "click";
853
+ element.dispatchEvent(new MouseEvent(clickType, eventOptions));
854
+ }
848
855
  return { success: true };
849
856
  }
850
857
  function injectStealthScripts() {
@@ -1011,8 +1018,8 @@ function installActionabilityHelpers() {
1011
1018
  const vw = window.innerWidth;
1012
1019
  const vh = window.innerHeight;
1013
1020
  if (rect.bottom < 0 || rect.top > vh || rect.right < 0 || rect.left > vw) return failure("not-in-viewport");
1014
- const hitEl = document.elementFromPoint(clickPoint.x, clickPoint.y);
1015
- if (hitEl && hitEl !== element && !element.contains(hitEl) && !hitEl.contains(element)) return failure("covered", {
1021
+ const hitEl = globalThis.__mcpDomHelpers.deepElementFromPoint(clickPoint.x, clickPoint.y);
1022
+ if (hitEl && !globalThis.__mcpDomHelpers.containsComposed(element, hitEl)) return failure("covered", {
1016
1023
  coveringElement: describeElement(hitEl),
1017
1024
  coveringRect: plainRect(hitEl.getBoundingClientRect())
1018
1025
  });
@@ -1082,7 +1089,7 @@ function checkActionability(refId) {
1082
1089
  * 4. 验证 hit target
1083
1090
  * 5. 执行点击
1084
1091
  */
1085
- function performActionableClick(refId, force) {
1092
+ function performActionableClick(refId, force, modifiers) {
1086
1093
  const helpers = window.__mcpActionability;
1087
1094
  if (!helpers) return {
1088
1095
  success: false,
@@ -1092,13 +1099,17 @@ function performActionableClick(refId, force) {
1092
1099
  };
1093
1100
  function dispatchClickSequence(el) {
1094
1101
  const rect = el.getBoundingClientRect();
1102
+ const cx = Math.round(rect.x + rect.width / 2);
1103
+ const cy = Math.round(rect.y + rect.height / 2);
1095
1104
  const opts = {
1096
1105
  bubbles: true,
1106
+ composed: true,
1097
1107
  cancelable: true,
1098
1108
  button: 0,
1099
1109
  buttons: 1,
1100
- clientX: Math.round(rect.x + rect.width / 2),
1101
- clientY: Math.round(rect.y + rect.height / 2),
1110
+ ...modifiers,
1111
+ clientX: cx,
1112
+ clientY: cy,
1102
1113
  view: window
1103
1114
  };
1104
1115
  el.dispatchEvent(new MouseEvent("mousedown", opts));
@@ -1107,10 +1118,10 @@ function performActionableClick(refId, force) {
1107
1118
  ...opts,
1108
1119
  buttons: 0
1109
1120
  }));
1110
- el.dispatchEvent(new MouseEvent("click", {
1121
+ globalThis.__mcpDomHelpers.click(el, modifiers, {
1111
1122
  ...opts,
1112
1123
  buttons: 0
1113
- }));
1124
+ });
1114
1125
  }
1115
1126
  if (force) {
1116
1127
  const ref = window.__mcpElementMap?.[refId];
@@ -1209,12 +1220,32 @@ function dispatchInputToElement(refId, val) {
1209
1220
  success: false,
1210
1221
  error: `Element ${refId} not found`
1211
1222
  };
1223
+ const tag = el.namespaceURI === "http://www.w3.org/1999/xhtml" ? el.localName : void 0;
1224
+ const prototype = tag === "input" ? HTMLInputElement.prototype : tag === "textarea" ? HTMLTextAreaElement.prototype : tag === "select" ? HTMLSelectElement.prototype : void 0;
1225
+ if (!prototype && !el.isContentEditable) return {
1226
+ success: false,
1227
+ error: "controlled 输入需要 input、textarea、select 或 contenteditable 目标"
1228
+ };
1229
+ if (el.matches(":disabled") || "readOnly" in el && el.readOnly) return {
1230
+ success: false,
1231
+ error: "controlled 输入目标处于 disabled 或 readonly 状态"
1232
+ };
1233
+ if (tag === "input" && el.type === "file") return {
1234
+ success: false,
1235
+ error: "文件控件请使用 upload 事件"
1236
+ };
1237
+ const setter = prototype ? Object.getOwnPropertyDescriptor(prototype, "value")?.set : void 0;
1238
+ if (prototype && !setter) return {
1239
+ success: false,
1240
+ error: "controlled 输入目标的原生 value setter 不可用"
1241
+ };
1212
1242
  el.focus();
1213
- const proto = Object.getPrototypeOf(el);
1214
- const setter = Object.getOwnPropertyDescriptor(proto, "value") ?? Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value") ?? Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value");
1215
- if (setter?.set) setter.set.call(el, val);
1216
- else el.value = val;
1217
- el.dispatchEvent(new Event("input", { bubbles: true }));
1243
+ if (setter) setter.call(el, val);
1244
+ else el.textContent = val;
1245
+ el.dispatchEvent(new Event("input", {
1246
+ bubbles: true,
1247
+ composed: true
1248
+ }));
1218
1249
  el.dispatchEvent(new Event("change", { bubbles: true }));
1219
1250
  return { success: true };
1220
1251
  }
@@ -1234,146 +1265,5 @@ function getComputedStyleFromElement(refId, prop, expectedUrl) {
1234
1265
  }
1235
1266
  return cs.getPropertyValue(prop);
1236
1267
  }
1237
- function inspectChallengePage(options) {
1238
- const title = document.title || "";
1239
- const url = location.href || "";
1240
- const visibleBodyText = (document.body && document.body.innerText ? document.body.innerText : "").replace(/\s+/g, " ");
1241
- const isVisible = (el) => {
1242
- if (!el) return false;
1243
- const style = window.getComputedStyle(el);
1244
- if (style.display === "none" || style.visibility === "hidden" || Number(style.opacity) === 0) return false;
1245
- const rect = el.getBoundingClientRect();
1246
- return rect.width > 0 && rect.height > 0;
1247
- };
1248
- const bringIntoView = (el) => {
1249
- if (!el || typeof el.scrollIntoView !== "function") return;
1250
- el.scrollIntoView({
1251
- block: "center",
1252
- inline: "nearest",
1253
- behavior: "instant"
1254
- });
1255
- };
1256
- const hits = (selectors) => selectors.filter((selector) => {
1257
- try {
1258
- return Array.from(document.querySelectorAll(selector)).some(isVisible);
1259
- } catch {
1260
- return false;
1261
- }
1262
- });
1263
- const isCloudflareFrame = (el) => {
1264
- if (!el) return false;
1265
- if (el.tagName.toUpperCase() === "IFRAME") {
1266
- const src = String(el.getAttribute("src") || el.src || "");
1267
- return src.includes("challenges.cloudflare.com") || src.includes("turnstile");
1268
- }
1269
- return Boolean(el.closest(options.frameSelectors.join(",")));
1270
- };
1271
- const selectorHits = hits(options.challengeSelectors);
1272
- const deniedHits = hits(options.deniedSelectors);
1273
- const widgetHits = hits(options.widgetSelectors);
1274
- const frameHits = hits(options.frameSelectors);
1275
- const cloudflareFramePresent = Array.from(document.querySelectorAll("iframe")).some((el) => isCloudflareFrame(el));
1276
- const normalizedTitle = title.trim().toLowerCase().replace(/…/g, "...");
1277
- const titlePending = options.titleNeedles.some((needle) => normalizedTitle.includes(String(needle).toLowerCase()));
1278
- const textHits = options.textMarkers.filter((marker) => visibleBodyText.toLowerCase().includes(String(marker).toLowerCase()));
1279
- const originResponsePending = options.originResponsePendingTextMarkers.some((marker) => visibleBodyText.toLowerCase().includes(String(marker).toLowerCase()));
1280
- const interstitialPending = selectorHits.length > 0 || titlePending || textHits.length > 0;
1281
- const findVisibleTurnstileBox = () => {
1282
- const input = document.querySelector("input[name=\"cf-turnstile-response\"]");
1283
- if (!input) return null;
1284
- const candidates = [];
1285
- let node = input.parentElement;
1286
- while (node && node !== document.documentElement) {
1287
- if (isVisible(node)) {
1288
- const rect = node.getBoundingClientRect();
1289
- if (rect.width >= 120 && rect.height >= 40) candidates.push(node);
1290
- }
1291
- node = node.parentElement;
1292
- }
1293
- if (candidates.length === 0) return null;
1294
- return candidates.find((el) => {
1295
- const rect = el.getBoundingClientRect();
1296
- return rect.width >= 250 && rect.width <= 340 && rect.height >= 50 && rect.height <= 85;
1297
- }) || candidates[0];
1298
- };
1299
- const turnstileBox = findVisibleTurnstileBox();
1300
- const hostVerify = Array.from(document.querySelectorAll(options.verifyButtonSelectors.join(","))).find(isVisible) || Array.from(document.querySelectorAll("button")).find((el) => {
1301
- const text = (el.textContent || "").trim();
1302
- return isVisible(el) && (text === "Verify you are human" || text === "请验证您是真人");
1303
- });
1304
- const useIframeClick = cloudflareFramePresent || !hostVerify && interstitialPending && Boolean(document.querySelector("input[name=\"cf-turnstile-response\"]"));
1305
- const turnstilePresent = widgetHits.length > 0 || useIframeClick || interstitialPending && frameHits.length > 0 || Boolean(turnstileBox);
1306
- const pointFromRect = (rect, kind) => {
1307
- if (!rect || rect.width < 8 || rect.height < 8) return null;
1308
- const y = Math.round(rect.top + Math.min(rect.height, 65) / 2);
1309
- if (kind === "verify") return {
1310
- x: Math.round(rect.left + rect.width / 2),
1311
- y
1312
- };
1313
- const widgetWidth = Math.min(rect.width, 300);
1314
- return {
1315
- x: Math.round(rect.left + Math.min(20, Math.max(14, widgetWidth / 15))),
1316
- y
1317
- };
1318
- };
1319
- let clickPoint = null;
1320
- let clickTargetKind = null;
1321
- let clickSource = null;
1322
- const setClickTarget = (el, kind) => {
1323
- if (!el) return;
1324
- bringIntoView(el);
1325
- const point = pointFromRect(el.getBoundingClientRect(), kind);
1326
- if (!point) return;
1327
- clickPoint = point;
1328
- clickTargetKind = kind;
1329
- clickSource = isCloudflareFrame(el) || useIframeClick ? "iframe" : "page";
1330
- };
1331
- if (hostVerify) setClickTarget(hostVerify, "verify");
1332
- if (!clickPoint && turnstileBox) {
1333
- const boxRect = turnstileBox.getBoundingClientRect();
1334
- if (boxRect.width <= 340 && boxRect.height <= 85) setClickTarget(turnstileBox, "widget");
1335
- }
1336
- if (!clickPoint && turnstilePresent) {
1337
- const frame = Array.from(document.querySelectorAll(options.frameSelectors.join(","))).find(isVisible);
1338
- if (frame) setClickTarget(frame, "widget");
1339
- }
1340
- if (!clickPoint && turnstilePresent) {
1341
- const widget = Array.from(document.querySelectorAll(options.widgetSelectors.join(","))).find(isVisible);
1342
- if (widget) setClickTarget(widget, "widget");
1343
- }
1344
- if (!clickPoint && turnstileBox) setClickTarget(turnstileBox, "widget");
1345
- const viewport = {
1346
- screenX: Number(window.screenX),
1347
- screenY: Number(window.screenY),
1348
- innerWidth: Number(window.innerWidth),
1349
- innerHeight: Number(window.innerHeight),
1350
- outerWidth: Number(window.outerWidth),
1351
- outerHeight: Number(window.outerHeight),
1352
- devicePixelRatio: Number(window.devicePixelRatio || 1)
1353
- };
1354
- const horizontal = Math.max(0, viewport.outerWidth - viewport.innerWidth);
1355
- const vertical = Math.max(0, viewport.outerHeight - viewport.innerHeight);
1356
- const chromeLeft = Math.round(horizontal / 2);
1357
- const chromeTop = Math.max(0, vertical - horizontal);
1358
- const resolvedClickPoint = clickPoint;
1359
- const screenPoint = resolvedClickPoint === null ? null : {
1360
- x: Math.round(viewport.screenX + chromeLeft + resolvedClickPoint.x),
1361
- y: Math.round(viewport.screenY + chromeTop + resolvedClickPoint.y)
1362
- };
1363
- return {
1364
- title,
1365
- url,
1366
- selectorHits,
1367
- deniedHits,
1368
- textHits,
1369
- originResponsePending,
1370
- turnstilePresent,
1371
- clickPoint: resolvedClickPoint,
1372
- clickTargetKind,
1373
- clickSource,
1374
- screenPoint,
1375
- viewport
1376
- };
1377
- }
1378
1268
  //#endregion
1379
- export { simulateMouseClick as C, simulateKeyboardType as S, performClick as _, extractHtml as a, performType as b, extractText as c, getComputedStyleFromElement as d, injectStealthScripts as f, performActionableClick as g, installFrameProbeListener as h, extractAttribute as i, findElements as l, installActionabilityHelpers as m, dispatchInputToElement as n, extractHtmlWithImages as o, inspectChallengePage as p, executeCode as r, extractMetadata as s, checkActionability as t, generateAccessibilityTree as u, performDragAndDrop as v, simulateMouseEvent as w, simulateKeyEvent as x, performScroll as y };
1269
+ export { simulateMouseClick as C, simulateKeyboardType as S, performClick as _, extractHtml as a, performType as b, extractText as c, getComputedStyleFromElement as d, injectStealthScripts as f, performActionableClick as g, observeNativePointer as h, extractAttribute as i, findElements as l, installFrameProbeListener as m, dispatchInputToElement as n, extractHtmlWithImages as o, installActionabilityHelpers as p, executeCode as r, extractMetadata as s, checkActionability as t, generateAccessibilityTree as u, performDragAndDrop as v, simulateMouseEvent as w, simulateKeyEvent as x, performScroll as y };