@pyrokine/mcp-chrome 2.4.4 → 3.0.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 (116) hide show
  1. package/README.md +401 -102
  2. package/README_zh.md +319 -79
  3. package/dist/anti-detection/injection.js +3 -3
  4. package/dist/cdp/client.d.ts +1 -1
  5. package/dist/cdp/client.d.ts.map +1 -1
  6. package/dist/cdp/client.js +18 -7
  7. package/dist/cdp/client.js.map +1 -1
  8. package/dist/cdp/launcher.d.ts +2 -3
  9. package/dist/cdp/launcher.d.ts.map +1 -1
  10. package/dist/cdp/launcher.js +84 -24
  11. package/dist/cdp/launcher.js.map +1 -1
  12. package/dist/core/auto-wait.d.ts +3 -3
  13. package/dist/core/auto-wait.d.ts.map +1 -1
  14. package/dist/core/auto-wait.js +45 -20
  15. package/dist/core/auto-wait.js.map +1 -1
  16. package/dist/core/browser-driver.d.ts +101 -12
  17. package/dist/core/browser-driver.d.ts.map +1 -1
  18. package/dist/core/browser-driver.js.map +1 -1
  19. package/dist/core/errors.d.ts +16 -0
  20. package/dist/core/errors.d.ts.map +1 -1
  21. package/dist/core/errors.js +77 -0
  22. package/dist/core/errors.js.map +1 -1
  23. package/dist/core/locator.d.ts.map +1 -1
  24. package/dist/core/locator.js +6 -4
  25. package/dist/core/locator.js.map +1 -1
  26. package/dist/core/os-mouse.d.ts +15 -2
  27. package/dist/core/os-mouse.d.ts.map +1 -1
  28. package/dist/core/os-mouse.js +52 -8
  29. package/dist/core/os-mouse.js.map +1 -1
  30. package/dist/core/session.d.ts +34 -19
  31. package/dist/core/session.d.ts.map +1 -1
  32. package/dist/core/session.js +574 -130
  33. package/dist/core/session.js.map +1 -1
  34. package/dist/core/types.d.ts +2 -0
  35. package/dist/core/types.d.ts.map +1 -1
  36. package/dist/core/types.js.map +1 -1
  37. package/dist/core/unified-session.d.ts +95 -20
  38. package/dist/core/unified-session.d.ts.map +1 -1
  39. package/dist/core/unified-session.js +489 -117
  40. package/dist/core/unified-session.js.map +1 -1
  41. package/dist/core/utils.d.ts +5 -0
  42. package/dist/core/utils.d.ts.map +1 -1
  43. package/dist/core/utils.js +475 -54
  44. package/dist/core/utils.js.map +1 -1
  45. package/dist/extension/bridge.d.ts +46 -36
  46. package/dist/extension/bridge.d.ts.map +1 -1
  47. package/dist/extension/bridge.js +269 -112
  48. package/dist/extension/bridge.js.map +1 -1
  49. package/dist/extension/http-server.d.ts +3 -0
  50. package/dist/extension/http-server.d.ts.map +1 -1
  51. package/dist/extension/http-server.js +19 -2
  52. package/dist/extension/http-server.js.map +1 -1
  53. package/dist/index.js +7 -0
  54. package/dist/index.js.map +1 -1
  55. package/dist/tools/browse.d.ts.map +1 -1
  56. package/dist/tools/browse.js +241 -171
  57. package/dist/tools/browse.js.map +1 -1
  58. package/dist/tools/challenge.d.ts +1 -1
  59. package/dist/tools/challenge.d.ts.map +1 -1
  60. package/dist/tools/challenge.js +75 -37
  61. package/dist/tools/challenge.js.map +1 -1
  62. package/dist/tools/cookies.d.ts.map +1 -1
  63. package/dist/tools/cookies.js +5 -3
  64. package/dist/tools/cookies.js.map +1 -1
  65. package/dist/tools/diagnostics.d.ts +3 -3
  66. package/dist/tools/diagnostics.d.ts.map +1 -1
  67. package/dist/tools/diagnostics.js +13 -12
  68. package/dist/tools/diagnostics.js.map +1 -1
  69. package/dist/tools/evaluate.d.ts.map +1 -1
  70. package/dist/tools/evaluate.js +57 -26
  71. package/dist/tools/evaluate.js.map +1 -1
  72. package/dist/tools/extract.d.ts.map +1 -1
  73. package/dist/tools/extract.js +107 -175
  74. package/dist/tools/extract.js.map +1 -1
  75. package/dist/tools/input.d.ts +1 -1
  76. package/dist/tools/input.d.ts.map +1 -1
  77. package/dist/tools/input.js +380 -158
  78. package/dist/tools/input.js.map +1 -1
  79. package/dist/tools/logs.d.ts.map +1 -1
  80. package/dist/tools/logs.js +5 -5
  81. package/dist/tools/logs.js.map +1 -1
  82. package/dist/tools/manage.d.ts.map +1 -1
  83. package/dist/tools/manage.js +380 -57
  84. package/dist/tools/manage.js.map +1 -1
  85. package/dist/tools/page-context.d.ts +17 -0
  86. package/dist/tools/page-context.d.ts.map +1 -0
  87. package/dist/tools/page-context.js +103 -0
  88. package/dist/tools/page-context.js.map +1 -0
  89. package/dist/tools/png.d.ts +5 -0
  90. package/dist/tools/png.d.ts.map +1 -1
  91. package/dist/tools/png.js +84 -19
  92. package/dist/tools/png.js.map +1 -1
  93. package/dist/tools/post-condition.d.ts.map +1 -1
  94. package/dist/tools/post-condition.js +5 -2
  95. package/dist/tools/post-condition.js.map +1 -1
  96. package/dist/tools/schema.d.ts +9 -0
  97. package/dist/tools/schema.d.ts.map +1 -1
  98. package/dist/tools/schema.js +15 -0
  99. package/dist/tools/schema.js.map +1 -1
  100. package/dist/tools/target-diagnostics.d.ts.map +1 -1
  101. package/dist/tools/target-diagnostics.js +32 -19
  102. package/dist/tools/target-diagnostics.js.map +1 -1
  103. package/dist/tools/wait.d.ts.map +1 -1
  104. package/dist/tools/wait.js +19 -25
  105. package/dist/tools/wait.js.map +1 -1
  106. package/extension/dist/assets/content.ts-C4imZ6A9.js +13 -0
  107. package/extension/dist/assets/content.ts-loader-CnJuCGhl.js +13 -0
  108. package/extension/dist/assets/{index.ts-Bqcu2qiN.js → index.ts-GeHNZBml.js} +2040 -2111
  109. package/extension/dist/assets/page-scripts-CMIY1zhd.js +1379 -0
  110. package/extension/dist/assets/{popup.html-B81xccfq.js → popup.html-CgtWL6Py.js} +48 -1
  111. package/extension/dist/manifest.json +4 -3
  112. package/extension/dist/service-worker-loader.js +1 -1
  113. package/extension/dist/src/popup/popup.html +11 -1
  114. package/package.json +9 -7
  115. package/scripts/start-chrome.ps1 +58 -0
  116. package/extension/dist/assets/content.ts-Cj_iiU2s.js +0 -25
@@ -0,0 +1,1379 @@
1
+ //#region src/background/page-scripts.ts
2
+ function installFrameProbeListener() {
3
+ const probeWindow = window;
4
+ if (probeWindow.__mcpFrameProbeListenerInstalled) return;
5
+ window.addEventListener("message", (event) => {
6
+ 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;
8
+ 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",
17
+ token: data.token,
18
+ index: data.index
19
+ }, "*");
20
+ }).catch((error) => {
21
+ console.warn("[MCP] iframe identity probe failed:", error instanceof Error ? error.message : String(error));
22
+ });
23
+ });
24
+ probeWindow.__mcpFrameProbeListenerInstalled = true;
25
+ }
26
+ function generateAccessibilityTree(filter, maxDepth, maxLength, refId, expectedUrl) {
27
+ if (expectedUrl != null && location.href !== expectedUrl) throw new Error("页面 URL 已变化,未读取");
28
+ const win = window;
29
+ win.__mcpElementMap = win.__mcpElementMap || {};
30
+ win.__mcpElementToRefId = win.__mcpElementToRefId || /* @__PURE__ */ new WeakMap();
31
+ win.__mcpRefCounter = win.__mcpRefCounter || 0;
32
+ const lines = [];
33
+ 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";
65
+ }
66
+ 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
+ }
91
+ if ([
92
+ "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 "";
111
+ }
112
+ function isVisible(element) {
113
+ const style = window.getComputedStyle(element);
114
+ const el = element;
115
+ return style.display !== "none" && style.visibility !== "hidden" && style.opacity !== "0" && el.offsetWidth > 0 && el.offsetHeight > 0;
116
+ }
117
+ function isInteractive(element) {
118
+ const tag = element.tagName.toLowerCase();
119
+ return [
120
+ "a",
121
+ "button",
122
+ "input",
123
+ "select",
124
+ "textarea",
125
+ "details",
126
+ "summary"
127
+ ].includes(tag) || element.getAttribute("onclick") !== null || element.getAttribute("tabindex") !== null || element.getAttribute("role") === "button" || element.getAttribute("role") === "link" || element.getAttribute("contenteditable") === "true";
128
+ }
129
+ function isLandmark(element) {
130
+ const tag = element.tagName.toLowerCase();
131
+ return [
132
+ "h1",
133
+ "h2",
134
+ "h3",
135
+ "h4",
136
+ "h5",
137
+ "h6",
138
+ "nav",
139
+ "main",
140
+ "header",
141
+ "footer",
142
+ "section",
143
+ "article",
144
+ "aside"
145
+ ].includes(tag) || element.getAttribute("role") !== null;
146
+ }
147
+ function shouldInclude(element, checkRefId) {
148
+ const tag = element.tagName.toLowerCase();
149
+ if ([
150
+ "script",
151
+ "style",
152
+ "meta",
153
+ "link",
154
+ "title",
155
+ "noscript"
156
+ ].includes(tag)) return false;
157
+ if (filter !== "all" && element.getAttribute("aria-hidden") === "true") return false;
158
+ if (filter !== "all" && !isVisible(element)) return false;
159
+ if (filter !== "all" && !checkRefId) {
160
+ const rect = element.getBoundingClientRect();
161
+ if (!(rect.top < window.innerHeight && rect.bottom > 0 && rect.left < window.innerWidth && rect.right > 0)) return false;
162
+ }
163
+ if (filter === "interactive") return isInteractive(element);
164
+ if (isInteractive(element)) return true;
165
+ if (isLandmark(element)) return true;
166
+ if (getName(element).length > 0) return true;
167
+ const role = getRole(element);
168
+ return role !== "generic" && role !== "image";
169
+ }
170
+ function getOrCreateRef(element) {
171
+ const existing = win.__mcpElementToRefId.get(element);
172
+ if (existing && win.__mcpElementMap[existing]?.deref() === element) return existing;
173
+ const newRefId = `ref_${++win.__mcpRefCounter}`;
174
+ win.__mcpElementMap[newRefId] = new WeakRef(element);
175
+ win.__mcpElementToRefId.set(element, newRefId);
176
+ return newRefId;
177
+ }
178
+ function cssSelector(element) {
179
+ if (element.id) return `#${CSS.escape(element.id)}`;
180
+ const parts = [];
181
+ let current = element;
182
+ while (current && current !== document.body && parts.length < 4) {
183
+ const tag = current.tagName.toLowerCase();
184
+ const parent = current.parentElement;
185
+ if (!parent) {
186
+ parts.unshift(tag);
187
+ break;
188
+ }
189
+ const currentTag = current.tagName;
190
+ const siblings = Array.from(parent.children).filter((child) => child.tagName === currentTag);
191
+ const nth = siblings.length > 1 ? `:nth-of-type(${siblings.indexOf(current) + 1})` : "";
192
+ parts.unshift(`${tag}${nth}`);
193
+ current = parent;
194
+ }
195
+ return parts.join(" > ");
196
+ }
197
+ function isDisabled(element) {
198
+ return Boolean(element.disabled) || element.getAttribute("aria-disabled") === "true";
199
+ }
200
+ function isCovered(element) {
201
+ const rect = element.getBoundingClientRect();
202
+ 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));
205
+ }
206
+ const interactiveElements = [];
207
+ function rememberInteractive(element, elementRefId, role, name) {
208
+ if (!isInteractive(element) || interactiveElements.length >= 100) return;
209
+ const rect = element.getBoundingClientRect();
210
+ interactiveElements.push({
211
+ refId: elementRefId,
212
+ role,
213
+ name,
214
+ selector: cssSelector(element),
215
+ visible: isVisible(element),
216
+ disabled: isDisabled(element),
217
+ bounds: {
218
+ x: rect.x,
219
+ y: rect.y,
220
+ width: rect.width,
221
+ height: rect.height
222
+ },
223
+ covered: isCovered(element)
224
+ });
225
+ }
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);
251
+ }
252
+ }
253
+ }
254
+ if (element.children && level < maxDepth) for (const child of element.children) traverse(child, include ? level + 1 : level, checkRefId);
255
+ }
256
+ if (refId) {
257
+ const ref = win.__mcpElementMap[refId];
258
+ if (!ref) return {
259
+ error: `Element with ref_id '${refId}' not found`,
260
+ pageContent: "",
261
+ viewport: {
262
+ width: window.innerWidth,
263
+ height: window.innerHeight
264
+ }
265
+ };
266
+ const element = ref.deref();
267
+ if (!element) return {
268
+ error: `Element with ref_id '${refId}' no longer exists`,
269
+ pageContent: "",
270
+ viewport: {
271
+ width: window.innerWidth,
272
+ height: window.innerHeight
273
+ }
274
+ };
275
+ traverse(element, 0, true);
276
+ } else if (document.body) traverse(document.body, 0, false);
277
+ {
278
+ const w = window;
279
+ const counter = (w.__mcpSweepCounter ?? 0) + 1;
280
+ w.__mcpSweepCounter = counter;
281
+ if (counter % 10 === 0 || Object.keys(win.__mcpElementMap).length > 500) {
282
+ for (const id of Object.keys(win.__mcpElementMap)) if (!win.__mcpElementMap[id].deref()) delete win.__mcpElementMap[id];
283
+ }
284
+ }
285
+ const content = lines.join("\n");
286
+ if (maxLength && content.length > maxLength) return {
287
+ error: `Output exceeds ${maxLength} character limit (${content.length} characters)`,
288
+ pageContent: "",
289
+ viewport: {
290
+ width: window.innerWidth,
291
+ height: window.innerHeight
292
+ }
293
+ };
294
+ return {
295
+ pageContent: content,
296
+ viewport: {
297
+ width: window.innerWidth,
298
+ height: window.innerHeight
299
+ },
300
+ interactiveElements
301
+ };
302
+ }
303
+ function performClick(refId) {
304
+ const ref = window.__mcpElementMap?.[refId];
305
+ if (!ref) return {
306
+ success: false,
307
+ error: `Element ${refId} not found`
308
+ };
309
+ const element = ref.deref();
310
+ if (!element) return {
311
+ success: false,
312
+ error: `Element ${refId} no longer exists`
313
+ };
314
+ element.scrollIntoView({
315
+ behavior: "smooth",
316
+ block: "center"
317
+ });
318
+ const el = element;
319
+ el.focus();
320
+ el.click();
321
+ return { success: true };
322
+ }
323
+ function performType(refId, text, clear) {
324
+ const ref = window.__mcpElementMap?.[refId];
325
+ if (!ref) return {
326
+ success: false,
327
+ error: `Element ${refId} not found`
328
+ };
329
+ const element = ref.deref();
330
+ if (!element) return {
331
+ success: false,
332
+ error: `Element ${refId} no longer exists`
333
+ };
334
+ const el = element;
335
+ el.focus();
336
+ if ("value" in el) {
337
+ el.value = clear ? text : el.value + text;
338
+ el.dispatchEvent(new Event("input", { bubbles: true }));
339
+ el.dispatchEvent(new Event("change", { bubbles: true }));
340
+ } else if (element.contentEditable === "true") {
341
+ if (clear) element.textContent = text;
342
+ else element.textContent = (element.textContent || "") + text;
343
+ element.dispatchEvent(new Event("input", { bubbles: true }));
344
+ }
345
+ return { success: true };
346
+ }
347
+ function performScroll(x, y, refId) {
348
+ if (refId) {
349
+ const ref = window.__mcpElementMap?.[refId];
350
+ if (!ref) return {
351
+ success: false,
352
+ error: `Element ${refId} not found`,
353
+ scrollX: 0,
354
+ scrollY: 0
355
+ };
356
+ const element = ref.deref();
357
+ if (!element) return {
358
+ success: false,
359
+ error: `Element ${refId} no longer exists`,
360
+ scrollX: 0,
361
+ scrollY: 0
362
+ };
363
+ element.scrollBy(x, y);
364
+ return {
365
+ success: true,
366
+ scrollX: element.scrollLeft,
367
+ scrollY: element.scrollTop
368
+ };
369
+ }
370
+ window.scrollBy(x, y);
371
+ return {
372
+ success: true,
373
+ scrollX: window.scrollX,
374
+ scrollY: window.scrollY
375
+ };
376
+ }
377
+ async function executeCode(code, timeout) {
378
+ function evaluateSerializationError(message, suggestion, context) {
379
+ return JSON.stringify({ error: {
380
+ code: "NON_SERIALIZABLE_EVALUATE_RESULT",
381
+ message,
382
+ suggestion,
383
+ context
384
+ } });
385
+ }
386
+ function serializeEvaluateResult(result) {
387
+ if (result instanceof Node) {
388
+ const element = result instanceof Element ? result : result.parentElement;
389
+ return {
390
+ 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()
395
+ })
396
+ };
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
+ return {
407
+ success: true,
408
+ result: JSON.stringify(result)
409
+ };
410
+ } 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
+ };
416
+ }
417
+ }
418
+ try {
419
+ const result = new Function(`return (${code})`)();
420
+ if (timeout === void 0) return serializeEvaluateResult(await result);
421
+ const timedOut = Symbol("evaluate-timeout");
422
+ let timeoutId;
423
+ const timeoutResult = new Promise((resolve) => {
424
+ timeoutId = setTimeout(() => resolve(timedOut), timeout);
425
+ });
426
+ try {
427
+ const settled = await Promise.race([Promise.resolve(result), timeoutResult]);
428
+ if (settled === timedOut) return {
429
+ success: false,
430
+ error: `Evaluation timeout after ${timeout}ms`
431
+ };
432
+ return serializeEvaluateResult(settled);
433
+ } finally {
434
+ if (timeoutId !== void 0) clearTimeout(timeoutId);
435
+ }
436
+ } 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
+ return {
443
+ success: false,
444
+ error: errorMsg
445
+ };
446
+ }
447
+ }
448
+ function extractText(selector, expectedUrl, refId) {
449
+ if (expectedUrl != null && location.href !== expectedUrl) throw new Error("页面 URL 已变化,未读取");
450
+ if (refId) {
451
+ const element = window.__mcpElementMap?.[refId]?.deref();
452
+ return { text: element?.isConnected ? element instanceof HTMLElement ? element.innerText : element.textContent ?? "" : "" };
453
+ }
454
+ if (selector) {
455
+ let element;
456
+ try {
457
+ element = document.querySelector(selector);
458
+ } catch (e) {
459
+ const err = e;
460
+ if (err?.name === "SyntaxError") return {
461
+ text: "",
462
+ error: `Invalid CSS selector: "${selector}" (${err.message})`
463
+ };
464
+ throw e;
465
+ }
466
+ return { text: element instanceof HTMLElement ? element.innerText : element?.textContent ?? "" };
467
+ }
468
+ return { text: document.body.innerText };
469
+ }
470
+ function extractHtml(selector, outer, expectedUrl, refId) {
471
+ if (expectedUrl != null && location.href !== expectedUrl) throw new Error("页面 URL 已变化,未读取");
472
+ if (refId) {
473
+ const element = window.__mcpElementMap?.[refId]?.deref();
474
+ return { html: element?.isConnected ? outer ? element.outerHTML : element.innerHTML : "" };
475
+ }
476
+ if (selector) {
477
+ let element;
478
+ try {
479
+ element = document.querySelector(selector);
480
+ } catch (e) {
481
+ const err = e;
482
+ if (err?.name === "SyntaxError") return {
483
+ html: "",
484
+ error: `Invalid CSS selector: "${selector}" (${err.message})`
485
+ };
486
+ throw e;
487
+ }
488
+ if (!element) return { html: "" };
489
+ return { html: outer ? element.outerHTML : element.innerHTML };
490
+ }
491
+ return { html: document.documentElement.outerHTML };
492
+ }
493
+ function extractHtmlWithImages(selector, outer, expectedUrl, refId) {
494
+ if (expectedUrl != null && location.href !== expectedUrl) throw new Error("页面 URL 已变化,未读取");
495
+ let root;
496
+ if (refId) {
497
+ const element = window.__mcpElementMap?.[refId]?.deref();
498
+ root = element?.isConnected ? element : null;
499
+ } else if (selector) try {
500
+ root = document.querySelector(selector);
501
+ } catch (e) {
502
+ const err = e;
503
+ if (err?.name === "SyntaxError") throw new Error(`Invalid CSS selector: "${selector}" (${err.message})`, { cause: e });
504
+ throw e;
505
+ }
506
+ else root = document.documentElement;
507
+ if (!root) return {
508
+ html: "",
509
+ images: []
510
+ };
511
+ const html = selector || refId ? outer ? root.outerHTML : root.innerHTML : document.documentElement.outerHTML;
512
+ const imgList = [];
513
+ if (root.tagName === "IMG") imgList.push(root);
514
+ root.querySelectorAll("img").forEach((img) => imgList.push(img));
515
+ return {
516
+ html,
517
+ images: imgList.map((img, index) => ({
518
+ index,
519
+ src: img.src,
520
+ dataSrc: (() => {
521
+ const raw = img.dataset.src || img.dataset.lazySrc || img.dataset.original || "";
522
+ if (!raw) return "";
523
+ try {
524
+ return new URL(raw, location.href).href;
525
+ } catch {
526
+ return raw;
527
+ }
528
+ })(),
529
+ alt: img.alt,
530
+ width: img.width,
531
+ height: img.height,
532
+ naturalWidth: img.naturalWidth,
533
+ naturalHeight: img.naturalHeight
534
+ }))
535
+ };
536
+ }
537
+ function extractMetadata(expectedUrl) {
538
+ if (expectedUrl != null && location.href !== expectedUrl) throw new Error("页面 URL 已变化,未读取");
539
+ const meta = (name) => document.querySelector(`meta[name="${name}"],meta[property="${name}"]`)?.content || void 0;
540
+ return {
541
+ url: location.href || document.baseURI || void 0,
542
+ title: document.title,
543
+ description: meta("description"),
544
+ canonical: document.querySelector("link[rel=\"canonical\"]")?.href || void 0,
545
+ charset: document.characterSet,
546
+ viewport: meta("viewport"),
547
+ og: Object.fromEntries(Array.from(document.querySelectorAll("meta[property^=\"og:\"]")).map((m) => [m.getAttribute("property"), m.content ?? ""])),
548
+ twitter: Object.fromEntries(Array.from(document.querySelectorAll("meta[name^=\"twitter:\"]")).map((m) => [m.getAttribute("name"), m.content ?? ""])),
549
+ jsonLd: Array.from(document.querySelectorAll("script[type=\"application/ld+json\"]")).map((s) => {
550
+ try {
551
+ return JSON.parse(s.textContent ?? "");
552
+ } catch {
553
+ return null;
554
+ }
555
+ }).filter(Boolean),
556
+ alternates: Array.from(document.querySelectorAll("link[rel=\"alternate\"]")).map((l) => ({
557
+ href: l.href,
558
+ type: l.getAttribute("type") || void 0,
559
+ hreflang: l.getAttribute("hreflang") || void 0
560
+ })),
561
+ feeds: Array.from(document.querySelectorAll("link[type=\"application/rss+xml\"],link[type=\"application/atom+xml\"]")).map((l) => ({
562
+ href: l.href,
563
+ type: l.getAttribute("type"),
564
+ title: l.getAttribute("title") || void 0
565
+ }))
566
+ };
567
+ }
568
+ function extractAttribute(selector, refId, attribute, expectedUrl) {
569
+ if (expectedUrl != null && location.href !== expectedUrl) throw new Error("页面 URL 已变化,未读取");
570
+ let element = null;
571
+ if (refId) element = (window.__mcpElementMap?.[refId])?.deref() ?? null;
572
+ else if (selector) try {
573
+ element = document.querySelector(selector);
574
+ } catch (e) {
575
+ const err = e;
576
+ if (err?.name === "SyntaxError") throw new Error(`Invalid CSS selector: "${selector}" (${err.message})`, { cause: e });
577
+ throw e;
578
+ }
579
+ if (!element) return { value: null };
580
+ if ([
581
+ "value",
582
+ "checked",
583
+ "selected",
584
+ "disabled",
585
+ "readOnly",
586
+ "indeterminate"
587
+ ].includes(attribute)) {
588
+ const propValue = element[attribute];
589
+ if (typeof propValue === "boolean") return { value: propValue ? "true" : "false" };
590
+ return { value: propValue != null ? String(propValue) : null };
591
+ }
592
+ return { value: element.getAttribute(attribute) };
593
+ }
594
+ function findElements(selector, text, xpath, expectedUrl, point, matchIndex) {
595
+ if (expectedUrl != null && location.href !== expectedUrl) throw new Error("页面 URL 已变化,未读取");
596
+ 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 = [];
601
+ 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;
618
+ }
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;
645
+ if (!refId) {
646
+ refId = `ref_${++win.__mcpRefCounter}`;
647
+ win.__mcpElementMap[refId] = new WeakRef(element);
648
+ win.__mcpElementToRefId.set(element, refId);
649
+ }
650
+ const rect = element.getBoundingClientRect();
651
+ results.push({
652
+ refId,
653
+ tag: element.tagName.toLowerCase(),
654
+ text: (element.textContent || "").trim().substring(0, 100),
655
+ rect: {
656
+ x: rect.x,
657
+ y: rect.y,
658
+ width: rect.width,
659
+ height: rect.height
660
+ }
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
+ }
671
+ }
672
+ return results;
673
+ }
674
+ function simulateMouseClick(x, y, button, clickCount = 1, refId) {
675
+ let element = null;
676
+ if (refId) {
677
+ const resolved = (window.__mcpElementMap?.[refId])?.deref();
678
+ if (resolved && resolved.isConnected) {
679
+ element = resolved;
680
+ const r = resolved.getBoundingClientRect();
681
+ x = r.x + r.width / 2;
682
+ y = r.y + r.height / 2;
683
+ }
684
+ }
685
+ if (!element) element = document.elementFromPoint(x, y);
686
+ if (!element) return { success: false };
687
+ const buttonCode = button === "right" ? 2 : button === "middle" ? 1 : 0;
688
+ const buttonsMask = button === "right" ? 2 : button === "middle" ? 4 : 1;
689
+ const baseOptions = {
690
+ bubbles: true,
691
+ cancelable: true,
692
+ view: window,
693
+ clientX: x,
694
+ clientY: y,
695
+ screenX: x + window.screenX,
696
+ screenY: y + window.screenY,
697
+ button: buttonCode
698
+ };
699
+ const pressed = {
700
+ ...baseOptions,
701
+ buttons: buttonsMask
702
+ };
703
+ const released = {
704
+ ...baseOptions,
705
+ buttons: 0
706
+ };
707
+ element.dispatchEvent(new MouseEvent("mouseover", released));
708
+ element.dispatchEvent(new MouseEvent("mouseenter", {
709
+ ...released,
710
+ bubbles: false
711
+ }));
712
+ 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++) {
728
+ element.dispatchEvent(new MouseEvent("mousedown", {
729
+ ...pressed,
730
+ detail: i
731
+ }));
732
+ element.dispatchEvent(new MouseEvent("mouseup", {
733
+ ...released,
734
+ detail: i
735
+ }));
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
+ }
747
+ return { success: true };
748
+ }
749
+ async function simulateKeyboardType(text, delay, deadline) {
750
+ const expired = () => deadline !== void 0 && Date.now() >= deadline;
751
+ const activeElement = document.activeElement;
752
+ if (!activeElement) return {
753
+ success: false,
754
+ error: "No active element"
755
+ };
756
+ if (!(activeElement.tagName === "INPUT" || activeElement.tagName === "TEXTAREA" || activeElement.isContentEditable)) return {
757
+ success: false,
758
+ error: `Active element does not accept keyboard input: ${activeElement.tagName}`
759
+ };
760
+ const proto = Object.getPrototypeOf(activeElement);
761
+ const valueSetter = Object.getOwnPropertyDescriptor(proto, "value") ?? Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value") ?? Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value");
762
+ const setNativeValue = (val) => {
763
+ if (valueSetter?.set) valueSetter.set.call(activeElement, val);
764
+ else if ("value" in activeElement) activeElement.value = val;
765
+ };
766
+ let firstCharacter = true;
767
+ for (const char of text.replace(/\r\n?/g, "\n")) {
768
+ if (expired()) return {
769
+ success: false,
770
+ error: "input timeout during typing"
771
+ };
772
+ if (delay > 0 && !firstCharacter) {
773
+ const remaining = deadline === void 0 ? delay : Math.max(0, deadline - Date.now());
774
+ await new Promise((r) => setTimeout(r, Math.min(delay, remaining)));
775
+ }
776
+ if (expired()) return {
777
+ success: false,
778
+ error: "input timeout during typing"
779
+ };
780
+ const keyEventOptions = {
781
+ bubbles: true,
782
+ cancelable: true,
783
+ key: char,
784
+ code: char >= "a" && char <= "z" ? `Key${char.toUpperCase()}` : char >= "A" && char <= "Z" ? `Key${char}` : char >= "0" && char <= "9" ? `Digit${char}` : "Key",
785
+ charCode: char.charCodeAt(0),
786
+ keyCode: char.charCodeAt(0),
787
+ which: char.charCodeAt(0),
788
+ view: window
789
+ };
790
+ activeElement.dispatchEvent(new KeyboardEvent("keydown", keyEventOptions));
791
+ activeElement.dispatchEvent(new KeyboardEvent("keypress", keyEventOptions));
792
+ if ("value" in activeElement) setNativeValue((activeElement.value ?? "") + char);
793
+ else if (activeElement.isContentEditable) activeElement.textContent = (activeElement.textContent || "") + char;
794
+ activeElement.dispatchEvent(new InputEvent("input", {
795
+ bubbles: true,
796
+ cancelable: true,
797
+ inputType: "insertText",
798
+ data: char
799
+ }));
800
+ activeElement.dispatchEvent(new KeyboardEvent("keyup", keyEventOptions));
801
+ firstCharacter = false;
802
+ }
803
+ if (expired()) return {
804
+ success: false,
805
+ error: "input timeout during typing"
806
+ };
807
+ activeElement.dispatchEvent(new Event("change", { bubbles: true }));
808
+ return { success: true };
809
+ }
810
+ function simulateKeyEvent(key, type, modifiers) {
811
+ const activeElement = document.activeElement || document.body;
812
+ const keyEventOptions = {
813
+ bubbles: true,
814
+ cancelable: true,
815
+ key,
816
+ code: key.length === 1 ? `Key${key.toUpperCase()}` : key,
817
+ view: window,
818
+ ctrlKey: modifiers.includes("ctrl"),
819
+ shiftKey: modifiers.includes("shift"),
820
+ altKey: modifiers.includes("alt"),
821
+ metaKey: modifiers.includes("meta")
822
+ };
823
+ if (type === "down" || type === "press") activeElement.dispatchEvent(new KeyboardEvent("keydown", keyEventOptions));
824
+ if (type === "press") activeElement.dispatchEvent(new KeyboardEvent("keypress", keyEventOptions));
825
+ if (type === "up" || type === "press") activeElement.dispatchEvent(new KeyboardEvent("keyup", keyEventOptions));
826
+ return { success: true };
827
+ }
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
+ const buttonCode = button === "right" ? 2 : button === "middle" ? 1 : 0;
832
+ const buttonsMask = button === "right" ? 2 : button === "middle" ? 4 : 1;
833
+ const eventOptions = {
834
+ bubbles: true,
835
+ cancelable: true,
836
+ view: window,
837
+ clientX: x,
838
+ clientY: y,
839
+ screenX: x + window.screenX,
840
+ screenY: y + window.screenY,
841
+ button: buttonCode,
842
+ buttons: type === "mousedown" ? buttonsMask : 0
843
+ };
844
+ element.dispatchEvent(new MouseEvent(type, eventOptions));
845
+ 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));
848
+ return { success: true };
849
+ }
850
+ function injectStealthScripts() {
851
+ Object.defineProperty(navigator, "webdriver", {
852
+ get: () => void 0,
853
+ configurable: true
854
+ });
855
+ Object.defineProperty(navigator, "plugins", {
856
+ get: () => {
857
+ const plugins = [
858
+ {
859
+ name: "Chrome PDF Plugin",
860
+ filename: "internal-pdf-viewer"
861
+ },
862
+ {
863
+ name: "Chrome PDF Viewer",
864
+ filename: "mhjfbmdgcfjbbpaeojofohoefgiehjai"
865
+ },
866
+ {
867
+ name: "Native Client",
868
+ filename: "internal-nacl-plugin"
869
+ }
870
+ ];
871
+ const pluginArray = Object.create(globalThis.PluginArray.prototype);
872
+ plugins.forEach((p, i) => {
873
+ const plugin = Object.create(globalThis.Plugin.prototype);
874
+ Object.defineProperties(plugin, {
875
+ name: { value: p.name },
876
+ filename: { value: p.filename },
877
+ description: { value: "" },
878
+ length: { value: 0 }
879
+ });
880
+ pluginArray[i] = plugin;
881
+ });
882
+ Object.defineProperty(pluginArray, "length", { value: plugins.length });
883
+ return pluginArray;
884
+ },
885
+ configurable: true
886
+ });
887
+ Object.defineProperty(navigator, "languages", {
888
+ get: () => [
889
+ "zh-CN",
890
+ "zh",
891
+ "en-US",
892
+ "en"
893
+ ],
894
+ configurable: true
895
+ });
896
+ const originalChrome = window.chrome;
897
+ const chromeDescriptor = Object.getOwnPropertyDescriptor(window, "chrome");
898
+ if (originalChrome && chromeDescriptor?.configurable) Object.defineProperty(window, "chrome", {
899
+ get: () => {
900
+ const chrome = { ...originalChrome };
901
+ delete chrome.runtime;
902
+ return chrome;
903
+ },
904
+ configurable: true
905
+ });
906
+ window.Error = new Proxy(Error, { construct(target, args) {
907
+ const error = new target(...args);
908
+ const originalStack = error.stack;
909
+ if (originalStack) error.stack = originalStack.split("\n").filter((line) => !line.includes("chrome-extension://")).join("\n");
910
+ return error;
911
+ } });
912
+ if (navigator.permissions) {
913
+ const originalQuery = navigator.permissions.query.bind(navigator.permissions);
914
+ navigator.permissions.query = async (descriptor) => {
915
+ if (descriptor.name === "notifications") return {
916
+ state: "prompt",
917
+ onchange: null
918
+ };
919
+ return originalQuery(descriptor);
920
+ };
921
+ }
922
+ const originalGetParameter = WebGLRenderingContext.prototype.getParameter;
923
+ WebGLRenderingContext.prototype.getParameter = function(parameter) {
924
+ if (parameter === 37445) return "Google Inc. (NVIDIA)";
925
+ if (parameter === 37446) return "ANGLE (NVIDIA, NVIDIA GeForce GTX 1080 Direct3D11 vs_5_0 ps_5_0, D3D11)";
926
+ return originalGetParameter.call(this, parameter);
927
+ };
928
+ console.log("[MCP Stealth] Anti-detection scripts injected");
929
+ }
930
+ function installActionabilityHelpers() {
931
+ const win = window;
932
+ function plainRect(r) {
933
+ return {
934
+ x: r.x,
935
+ y: r.y,
936
+ width: r.width,
937
+ height: r.height
938
+ };
939
+ }
940
+ function selectorFor(el) {
941
+ if (el.id) return `#${CSS.escape(el.id)}`;
942
+ const tag = el.tagName.toLowerCase();
943
+ const parent = el.parentElement;
944
+ if (!parent) return tag;
945
+ const siblings = Array.from(parent.children).filter((child) => child.tagName === el.tagName);
946
+ return `${tag}${siblings.length > 1 ? `:nth-of-type(${siblings.indexOf(el) + 1})` : ""}`;
947
+ }
948
+ function textFor(el) {
949
+ return (el.textContent || el.getAttribute("aria-label") || el.getAttribute("placeholder") || "").trim().slice(0, 80);
950
+ }
951
+ function describeElement(el) {
952
+ const tag = el.tagName.toLowerCase();
953
+ const cls = el.className ? `.${String(el.className).split(/\s+/).filter(Boolean).slice(0, 2).join(".")}` : "";
954
+ return `<${tag}${el.id ? `#${el.id}` : ""}${cls}>`;
955
+ }
956
+ function candidatesAt(point) {
957
+ if (point.x < 0 || point.y < 0 || point.x > window.innerWidth || point.y > window.innerHeight) return [];
958
+ return Array.from(document.elementsFromPoint(point.x, point.y)).slice(0, 8).map((el) => ({
959
+ tag: el.tagName.toLowerCase(),
960
+ selector: selectorFor(el),
961
+ text: textFor(el),
962
+ rect: plainRect(el.getBoundingClientRect())
963
+ }));
964
+ }
965
+ function suggestionsFor(reason) {
966
+ if (reason === "covered") return ["点击点被其他元素覆盖,请关闭遮罩层、换用更精确 target,或确认后使用 force=true"];
967
+ if (reason === "not-in-viewport") return ["元素不在视口内,请先滚动到目标元素或改用可见元素定位"];
968
+ if (reason === "not-visible") return ["元素不可见,请等待页面渲染完成,或改用当前可见的元素定位"];
969
+ if (reason === "not-enabled") return ["元素被禁用,请等待 enabled 状态或检查表单前置条件"];
970
+ if (reason === "pointer-events-none") return ["元素设置了 pointer-events:none,请定位实际接收事件的子元素或父元素"];
971
+ return ["元素引用失效,请重新执行 extract type=\"state\" 获取新的 refId"];
972
+ }
973
+ function resolveElement(refId) {
974
+ return win.__mcpElementMap?.[refId]?.deref();
975
+ }
976
+ function check(refId) {
977
+ const element = resolveElement(refId);
978
+ if (!element || !element.isConnected) return {
979
+ actionable: false,
980
+ reason: "not-connected",
981
+ suggestions: suggestionsFor("not-connected")
982
+ };
983
+ const style = window.getComputedStyle(element);
984
+ const rect = element.getBoundingClientRect();
985
+ const clickPoint = {
986
+ x: rect.x + rect.width / 2,
987
+ y: rect.y + rect.height / 2
988
+ };
989
+ const failure = (reason, extra = {}) => ({
990
+ actionable: false,
991
+ reason,
992
+ rect: plainRect(rect),
993
+ clickPoint,
994
+ candidates: candidatesAt(clickPoint),
995
+ suggestions: suggestionsFor(reason),
996
+ ...extra
997
+ });
998
+ if (typeof element.checkVisibility === "function" && !element.checkVisibility()) return failure("not-visible");
999
+ if (style.visibility !== "visible") return failure("not-visible");
1000
+ if (style.display !== "contents" && rect.width === 0 && rect.height === 0) {
1001
+ if (!(element.querySelector("svg, canvas, img, video") !== null)) return failure("not-visible");
1002
+ }
1003
+ const htmlEl = element;
1004
+ if ("disabled" in htmlEl && htmlEl.disabled) return failure("not-enabled");
1005
+ let ancestor = element;
1006
+ while (ancestor) {
1007
+ if (ancestor.getAttribute("aria-disabled") === "true") return failure("not-enabled");
1008
+ ancestor = ancestor.parentElement;
1009
+ }
1010
+ if (style.pointerEvents === "none") return failure("pointer-events-none");
1011
+ const vw = window.innerWidth;
1012
+ const vh = window.innerHeight;
1013
+ 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", {
1016
+ coveringElement: describeElement(hitEl),
1017
+ coveringRect: plainRect(hitEl.getBoundingClientRect())
1018
+ });
1019
+ return {
1020
+ actionable: true,
1021
+ rect: plainRect(rect),
1022
+ clickPoint,
1023
+ candidates: candidatesAt(clickPoint)
1024
+ };
1025
+ }
1026
+ function scrollIntoViewWithRetry(refId) {
1027
+ const element = resolveElement(refId);
1028
+ if (!element || !element.isConnected) return {
1029
+ actionable: false,
1030
+ reason: "not-connected",
1031
+ suggestions: suggestionsFor("not-connected")
1032
+ };
1033
+ for (const alignment of [
1034
+ {
1035
+ block: "center",
1036
+ inline: "center",
1037
+ behavior: "instant"
1038
+ },
1039
+ {
1040
+ block: "end",
1041
+ inline: "end",
1042
+ behavior: "instant"
1043
+ },
1044
+ {
1045
+ block: "start",
1046
+ inline: "start",
1047
+ behavior: "instant"
1048
+ },
1049
+ {
1050
+ block: "nearest",
1051
+ inline: "nearest",
1052
+ behavior: "instant"
1053
+ }
1054
+ ]) {
1055
+ element.scrollIntoView(alignment);
1056
+ const result = check(refId);
1057
+ if (result.actionable) return result;
1058
+ }
1059
+ return check(refId);
1060
+ }
1061
+ win.__mcpActionability = {
1062
+ check,
1063
+ scrollIntoViewWithRetry
1064
+ };
1065
+ }
1066
+ function checkActionability(refId) {
1067
+ const helpers = window.__mcpActionability;
1068
+ if (!helpers) return {
1069
+ actionable: false,
1070
+ reason: "not-connected",
1071
+ suggestions: ["actionability helper 未安装,请重试当前操作"]
1072
+ };
1073
+ return helpers.check(refId);
1074
+ }
1075
+ /**
1076
+ * 带 actionability 检查的点击(注入到页面执行)
1077
+ *
1078
+ * 流程:
1079
+ * 1. 检查可操作性
1080
+ * 2. 不在视口 → 滚动(4 种对齐轮换)
1081
+ * 3. 重新检查可操作性(滚动后坐标变化)
1082
+ * 4. 验证 hit target
1083
+ * 5. 执行点击
1084
+ */
1085
+ function performActionableClick(refId, force) {
1086
+ const helpers = window.__mcpActionability;
1087
+ if (!helpers) return {
1088
+ success: false,
1089
+ error: "actionability helper 未安装,请重试当前操作",
1090
+ reason: "not-connected",
1091
+ suggestions: ["actionability helper 未安装,请重试当前操作"]
1092
+ };
1093
+ function dispatchClickSequence(el) {
1094
+ const rect = el.getBoundingClientRect();
1095
+ const opts = {
1096
+ bubbles: true,
1097
+ cancelable: true,
1098
+ button: 0,
1099
+ buttons: 1,
1100
+ clientX: Math.round(rect.x + rect.width / 2),
1101
+ clientY: Math.round(rect.y + rect.height / 2),
1102
+ view: window
1103
+ };
1104
+ el.dispatchEvent(new MouseEvent("mousedown", opts));
1105
+ el.focus();
1106
+ el.dispatchEvent(new MouseEvent("mouseup", {
1107
+ ...opts,
1108
+ buttons: 0
1109
+ }));
1110
+ el.dispatchEvent(new MouseEvent("click", {
1111
+ ...opts,
1112
+ buttons: 0
1113
+ }));
1114
+ }
1115
+ if (force) {
1116
+ const ref = window.__mcpElementMap?.[refId];
1117
+ if (!ref) return {
1118
+ success: false,
1119
+ error: `Element ${refId} not found`
1120
+ };
1121
+ const element = ref.deref();
1122
+ if (!element) return {
1123
+ success: false,
1124
+ error: `Element ${refId} no longer exists`
1125
+ };
1126
+ const el = element;
1127
+ el.focus();
1128
+ dispatchClickSequence(el);
1129
+ return { success: true };
1130
+ }
1131
+ let result = helpers.check(refId);
1132
+ if (!result.actionable && result.reason === "not-in-viewport") result = helpers.scrollIntoViewWithRetry(refId);
1133
+ if (!result.actionable) return {
1134
+ success: false,
1135
+ error: result.reason === "covered" ? `Element is covered by ${result.coveringElement}` : `Element is not actionable: ${result.reason}`,
1136
+ reason: result.reason,
1137
+ coveringElement: result.coveringElement,
1138
+ coveringRect: result.coveringRect,
1139
+ rect: result.rect,
1140
+ clickPoint: result.clickPoint,
1141
+ candidates: result.candidates,
1142
+ suggestions: result.suggestions
1143
+ };
1144
+ const element = (window.__mcpElementMap?.[refId])?.deref();
1145
+ if (!element) return {
1146
+ success: false,
1147
+ error: `Element ${refId} no longer exists`
1148
+ };
1149
+ const el = element;
1150
+ el.focus();
1151
+ dispatchClickSequence(el);
1152
+ return { success: true };
1153
+ }
1154
+ /**
1155
+ * HTML5 drag 必须通过 DragEvent dispatchEvent 模拟(原生鼠标事件无法触发)
1156
+ * 在 MAIN 世界执行,refId 创建与消费侧均在 MAIN,共享 __mcpElementMap
1157
+ */
1158
+ function performDragAndDrop(srcRefId, dstRefId) {
1159
+ const win = window;
1160
+ const srcRef = win.__mcpElementMap?.[srcRefId];
1161
+ const dstRef = win.__mcpElementMap?.[dstRefId];
1162
+ const src = srcRef?.deref();
1163
+ const dst = dstRef?.deref();
1164
+ if (!src) return {
1165
+ success: false,
1166
+ code: "REF_STALE",
1167
+ error: `drag 源元素 ${srcRefId} 不存在或已从 DOM 移除`
1168
+ };
1169
+ if (!dst) return {
1170
+ success: false,
1171
+ code: "REF_STALE",
1172
+ error: `drag 目标元素 ${dstRefId} 不存在或已从 DOM 移除`
1173
+ };
1174
+ const dt = new DataTransfer();
1175
+ src.dispatchEvent(new DragEvent("dragstart", {
1176
+ bubbles: true,
1177
+ cancelable: true,
1178
+ dataTransfer: dt
1179
+ }));
1180
+ dst.dispatchEvent(new DragEvent("dragenter", {
1181
+ bubbles: true,
1182
+ cancelable: true,
1183
+ dataTransfer: dt
1184
+ }));
1185
+ dst.dispatchEvent(new DragEvent("dragover", {
1186
+ bubbles: true,
1187
+ cancelable: true,
1188
+ dataTransfer: dt
1189
+ }));
1190
+ dst.dispatchEvent(new DragEvent("drop", {
1191
+ bubbles: true,
1192
+ cancelable: true,
1193
+ dataTransfer: dt
1194
+ }));
1195
+ src.dispatchEvent(new DragEvent("dragend", {
1196
+ bubbles: true,
1197
+ cancelable: true,
1198
+ dataTransfer: dt
1199
+ }));
1200
+ return { success: true };
1201
+ }
1202
+ /**
1203
+ * 通过 nativeInputValueSetter 直接设置 value 并触发 input/change 事件
1204
+ * 兼容 React/Vue 等框架的受控组件(参考 Playwright fill())
1205
+ */
1206
+ function dispatchInputToElement(refId, val) {
1207
+ const el = (window.__mcpElementMap?.[refId])?.deref();
1208
+ if (!el) return {
1209
+ success: false,
1210
+ error: `Element ${refId} not found`
1211
+ };
1212
+ 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 }));
1218
+ el.dispatchEvent(new Event("change", { bubbles: true }));
1219
+ return { success: true };
1220
+ }
1221
+ /**
1222
+ * 获取元素的 computed style
1223
+ * prop = '*' 返回全部属性 JSON;否则返回指定属性值
1224
+ */
1225
+ function getComputedStyleFromElement(refId, prop, expectedUrl) {
1226
+ if (expectedUrl != null && location.href !== expectedUrl) throw new Error("页面 URL 已变化,未读取");
1227
+ const el = (window.__mcpElementMap?.[refId])?.deref();
1228
+ if (!el) return null;
1229
+ const cs = window.getComputedStyle(el);
1230
+ if (prop === "*") {
1231
+ const obj = {};
1232
+ for (let i = 0; i < cs.length; i++) obj[cs[i]] = cs.getPropertyValue(cs[i]);
1233
+ return JSON.stringify(obj);
1234
+ }
1235
+ return cs.getPropertyValue(prop);
1236
+ }
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
+ //#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 };