@xiaou66/vite-plugin-vue-mcp-next 1.2.0 → 1.3.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.
@@ -1,6 +1,116 @@
1
1
  // src/runtime/client.ts
2
2
  import { createHotContext } from "vite-hot-client";
3
3
 
4
+ // src/shared/limits.ts
5
+ var DEFAULT_DOM_MAX_DEPTH = 8;
6
+ var DEFAULT_DOM_MAX_NODES = 2e3;
7
+ var DEFAULT_DOM_MAX_TEXT_LENGTH = 300;
8
+ var DEFAULT_CONSOLE_MAX_RECORDS = 1e3;
9
+ var DEFAULT_NETWORK_MAX_RECORDS = 500;
10
+ var DEFAULT_NETWORK_MAX_BODY_SIZE = 1e5;
11
+ var DEFAULT_MASK_HEADERS = [
12
+ "authorization",
13
+ "cookie",
14
+ "set-cookie"
15
+ ];
16
+
17
+ // src/constants.ts
18
+ var DEFAULT_MCP_PATH = "/__mcp";
19
+ var DEFAULT_SCREENSHOT_MAX_BYTES = 5 * 1024 * 1024;
20
+ var DEFAULT_SCREENSHOT_SAVE_DIR = ".vite-mcp/screenshot";
21
+ var DEFAULT_PERFORMANCE_SAVE_DIR = ".vite-mcp/performance";
22
+ var DEFAULT_PERFORMANCE_MAX_DURATION_MS = 3e4;
23
+ var DEFAULT_PERFORMANCE_SAMPLE_INTERVAL_MS = 250;
24
+ var DEFAULT_PERFORMANCE_LONG_TASK_THRESHOLD_MS = 50;
25
+ var VIRTUAL_RUNTIME_ID = "virtual:vite-plugin-vue-mcp-next/runtime";
26
+ var RESOLVED_VIRTUAL_RUNTIME_ID = `\0${VIRTUAL_RUNTIME_ID}`;
27
+ var VIRTUAL_SCREENSHOT_CONFIG_ID = "virtual:vite-plugin-vue-mcp-next/screenshot-config";
28
+ var RESOLVED_VIRTUAL_SCREENSHOT_CONFIG_ID = `\0${VIRTUAL_SCREENSHOT_CONFIG_ID}`;
29
+ var VIRTUAL_SNAPDOM_LOADER_ID = "virtual:vite-plugin-vue-mcp-next/snapdom-loader";
30
+ var RESOLVED_VIRTUAL_SNAPDOM_LOADER_ID = `\0${VIRTUAL_SNAPDOM_LOADER_ID}`;
31
+ var DEFAULT_MCP_CLIENT_SERVER_NAME = "vite-mcp-next";
32
+ var RUNTIME_PAGE_CONNECTED_EVENT = "vite-plugin-vue-mcp-next:page-connected";
33
+ var RUNTIME_PAGE_DISCONNECTED_EVENT = "vite-plugin-vue-mcp-next:page-disconnected";
34
+ var RUNTIME_PAGE_HEARTBEAT_EVENT = "vite-plugin-vue-mcp-next:heartbeat";
35
+ var DEFAULT_RUNTIME_PAGE_HEARTBEAT_INTERVAL_MS = 15e3;
36
+ var DEFAULT_ELEMENT_PICKER_TOAST_DURATION_MS = 2200;
37
+ var DEFAULT_OPTIONS = {
38
+ mcpPath: DEFAULT_MCP_PATH,
39
+ host: "localhost",
40
+ printUrl: true,
41
+ updateCursorMcpJson: {
42
+ enabled: true,
43
+ serverName: DEFAULT_MCP_CLIENT_SERVER_NAME
44
+ },
45
+ mcpClients: {
46
+ cursor: true,
47
+ codex: true,
48
+ claudeCode: true,
49
+ trae: true,
50
+ serverName: DEFAULT_MCP_CLIENT_SERVER_NAME
51
+ },
52
+ skill: {
53
+ autoConfig: true
54
+ },
55
+ elementPicker: {
56
+ enabled: true,
57
+ shortcut: {
58
+ altKey: true,
59
+ shiftKey: true,
60
+ metaKey: false,
61
+ ctrlKey: false
62
+ },
63
+ toastDurationMs: DEFAULT_ELEMENT_PICKER_TOAST_DURATION_MS
64
+ },
65
+ runtime: {
66
+ mode: "auto",
67
+ evaluate: {
68
+ enabled: false,
69
+ timeoutMs: 3e3
70
+ }
71
+ },
72
+ cdp: {},
73
+ network: {
74
+ mode: "auto",
75
+ maxRecords: DEFAULT_NETWORK_MAX_RECORDS,
76
+ captureRequestBody: true,
77
+ captureResponseBody: true,
78
+ maxBodySize: DEFAULT_NETWORK_MAX_BODY_SIZE,
79
+ maskHeaders: [...DEFAULT_MASK_HEADERS]
80
+ },
81
+ dom: {
82
+ maxDepth: DEFAULT_DOM_MAX_DEPTH,
83
+ maxNodes: DEFAULT_DOM_MAX_NODES,
84
+ maxTextLength: DEFAULT_DOM_MAX_TEXT_LENGTH
85
+ },
86
+ console: {
87
+ maxRecords: DEFAULT_CONSOLE_MAX_RECORDS
88
+ },
89
+ screenshot: {
90
+ type: "path",
91
+ saveDir: DEFAULT_SCREENSHOT_SAVE_DIR,
92
+ prefer: "auto",
93
+ maxBytes: DEFAULT_SCREENSHOT_MAX_BYTES,
94
+ snapdom: {
95
+ options: {},
96
+ plugins: []
97
+ }
98
+ },
99
+ performance: {
100
+ mode: "auto",
101
+ maxDurationMs: DEFAULT_PERFORMANCE_MAX_DURATION_MS,
102
+ sampleIntervalMs: DEFAULT_PERFORMANCE_SAMPLE_INTERVAL_MS,
103
+ longTaskThresholdMs: DEFAULT_PERFORMANCE_LONG_TASK_THRESHOLD_MS,
104
+ saveDir: DEFAULT_PERFORMANCE_SAVE_DIR,
105
+ memory: {
106
+ enabled: true
107
+ },
108
+ stacks: {
109
+ enabled: true
110
+ }
111
+ }
112
+ };
113
+
4
114
  // src/runtime/consoleHook.ts
5
115
  import { nanoid } from "nanoid";
6
116
 
@@ -70,8 +180,227 @@ function installConsoleHook(options) {
70
180
  };
71
181
  }
72
182
 
73
- // src/runtime/networkHook.ts
183
+ // src/runtime/elementRegistry.ts
74
184
  import { nanoid as nanoid2 } from "nanoid";
185
+ var RUNTIME_ELEMENT_ID_PREFIX = "runtime:vmcp_";
186
+ var RUNTIME_ELEMENT_ID_SIZE = 8;
187
+ var runtimeElementRegistry = createRuntimeElementRegistry();
188
+ function createRuntimeElementId() {
189
+ return `${RUNTIME_ELEMENT_ID_PREFIX}${nanoid2(RUNTIME_ELEMENT_ID_SIZE)}`;
190
+ }
191
+ function createRuntimeElementRegistry() {
192
+ const records = /* @__PURE__ */ new Map();
193
+ return {
194
+ register(element) {
195
+ const elementId = createRuntimeElementId();
196
+ records.set(elementId, {
197
+ elementId,
198
+ element,
199
+ createdAt: Date.now()
200
+ });
201
+ return elementId;
202
+ },
203
+ get(elementId) {
204
+ return records.get(elementId);
205
+ },
206
+ clear() {
207
+ records.clear();
208
+ }
209
+ };
210
+ }
211
+
212
+ // src/runtime/elementPicker.ts
213
+ var MCP_ID_ATTR = "data-v-mcp-id";
214
+ var INTERNAL_ATTR = "data-v-mcp-internal";
215
+ var SUCCESS_MESSAGE = "\u5143\u7D20\u4F4D\u7F6E\u5DF2\u590D\u5236\uFF0C\u8BF7\u53D1\u9001\u7ED9 AI";
216
+ var COPY_FAILED_PREFIX = "\u590D\u5236\u5931\u8D25\uFF0C\u8BF7\u624B\u52A8\u590D\u5236\u5143\u7D20 ID";
217
+ var OVERLAY_Z_INDEX = "2147483647";
218
+ var TOAST_Z_INDEX = "2147483647";
219
+ function installElementPicker(options) {
220
+ if (!options.enabled) {
221
+ return;
222
+ }
223
+ const registry = runtimeElementRegistry;
224
+ const overlay = createOverlay();
225
+ let active = false;
226
+ let currentElement;
227
+ window.addEventListener("keydown", (event) => {
228
+ active = matchesShortcut(event, options.shortcut);
229
+ });
230
+ window.addEventListener("keyup", () => {
231
+ active = false;
232
+ currentElement = void 0;
233
+ updateOverlay(overlay);
234
+ });
235
+ window.addEventListener("mousemove", (event) => {
236
+ if (!active) {
237
+ return;
238
+ }
239
+ currentElement = document.elementFromPoint(event.clientX, event.clientY) ?? void 0;
240
+ updateOverlay(overlay, currentElement);
241
+ });
242
+ window.addEventListener(
243
+ "click",
244
+ (event) => {
245
+ if (!active || !isElementLike(event.target)) {
246
+ return;
247
+ }
248
+ event.preventDefault();
249
+ event.stopPropagation();
250
+ void copyAndNotify(event.target, registry, options.toastDurationMs);
251
+ },
252
+ true
253
+ );
254
+ }
255
+ function matchesShortcut(event, shortcut) {
256
+ return event.altKey === shortcut.altKey && event.shiftKey === shortcut.shiftKey && event.metaKey === shortcut.metaKey && event.ctrlKey === shortcut.ctrlKey;
257
+ }
258
+ function resolveElementId(element, registry) {
259
+ return element.getAttribute(MCP_ID_ATTR) ?? registry.register(element);
260
+ }
261
+ async function copyAndNotify(element, registry, toastDurationMs) {
262
+ const elementId = resolveElementId(element, registry);
263
+ const copied = await copyElementId(elementId);
264
+ showToast(
265
+ copied ? SUCCESS_MESSAGE : `${COPY_FAILED_PREFIX}: ${elementId}`,
266
+ toastDurationMs
267
+ );
268
+ }
269
+ async function copyElementId(elementId) {
270
+ try {
271
+ await navigator.clipboard.writeText(elementId);
272
+ return true;
273
+ } catch {
274
+ return false;
275
+ }
276
+ }
277
+ function createOverlay() {
278
+ const overlay = document.createElement("div");
279
+ markInternalElement(overlay);
280
+ Object.assign(overlay.style, {
281
+ position: "fixed",
282
+ pointerEvents: "none",
283
+ border: "2px solid #1d4ed8",
284
+ background: "rgba(29, 78, 216, 0.08)",
285
+ zIndex: OVERLAY_Z_INDEX,
286
+ display: "none"
287
+ });
288
+ document.body.appendChild(overlay);
289
+ return overlay;
290
+ }
291
+ function updateOverlay(overlay, element) {
292
+ if (!element || getElementAttr(element, INTERNAL_ATTR) === "true") {
293
+ overlay.style.display = "none";
294
+ return;
295
+ }
296
+ const rect = element.getBoundingClientRect();
297
+ Object.assign(overlay.style, {
298
+ display: "block",
299
+ left: `${String(rect.x)}px`,
300
+ top: `${String(rect.y)}px`,
301
+ width: `${String(rect.width)}px`,
302
+ height: `${String(rect.height)}px`
303
+ });
304
+ }
305
+ function showToast(message, durationMs) {
306
+ const toast = document.createElement("div");
307
+ markInternalElement(toast);
308
+ toast.textContent = message;
309
+ Object.assign(toast.style, {
310
+ position: "fixed",
311
+ left: "50%",
312
+ bottom: "32px",
313
+ transform: "translateX(-50%)",
314
+ zIndex: TOAST_Z_INDEX,
315
+ padding: "8px 12px",
316
+ borderRadius: "6px",
317
+ background: "rgba(17, 24, 39, 0.92)",
318
+ color: "#fff",
319
+ fontSize: "13px",
320
+ pointerEvents: "none"
321
+ });
322
+ document.body.appendChild(toast);
323
+ globalThis.setTimeout(() => {
324
+ toast.remove();
325
+ }, durationMs);
326
+ }
327
+ function isElementLike(value) {
328
+ return Boolean(
329
+ value && typeof value === "object" && "getAttribute" in value && "getBoundingClientRect" in value
330
+ );
331
+ }
332
+ function markInternalElement(element) {
333
+ if (typeof element.setAttribute === "function") {
334
+ element.setAttribute(INTERNAL_ATTR, "true");
335
+ }
336
+ element.dataset.vMcpInternal = "true";
337
+ }
338
+ function getElementAttr(element, name) {
339
+ if (typeof element.getAttribute === "function") {
340
+ return element.getAttribute(name);
341
+ }
342
+ return null;
343
+ }
344
+
345
+ // src/shared/elementId.ts
346
+ var PROJECT_SOURCE_ID_PATTERN = /^(.+\.(?:vue|tsx|jsx|ts|js)):(\d+):(\d+)$/;
347
+ var RUNTIME_ID_PATTERN = /^runtime:([A-Za-z0-9_-]+)$/;
348
+ var PACKAGE_ID_PREFIX = "pkg:";
349
+ function parseElementId(elementId) {
350
+ const sourceMatch = PROJECT_SOURCE_ID_PATTERN.exec(elementId);
351
+ if (sourceMatch) {
352
+ return {
353
+ kind: "project-source",
354
+ elementId,
355
+ file: sourceMatch[1],
356
+ line: Number(sourceMatch[2]),
357
+ column: Number(sourceMatch[3])
358
+ };
359
+ }
360
+ if (elementId.startsWith(PACKAGE_ID_PREFIX)) {
361
+ return parsePackageElementId(elementId);
362
+ }
363
+ const runtimeMatch = RUNTIME_ID_PATTERN.exec(elementId);
364
+ if (runtimeMatch) {
365
+ return {
366
+ kind: "runtime",
367
+ elementId,
368
+ runtimeId: runtimeMatch[1]
369
+ };
370
+ }
371
+ return {
372
+ kind: "invalid",
373
+ elementId,
374
+ reason: "unsupported elementId format"
375
+ };
376
+ }
377
+ function parsePackageElementId(elementId) {
378
+ const value = elementId.slice(PACKAGE_ID_PREFIX.length);
379
+ const parts = value.split("/").filter(Boolean);
380
+ if (parts.length < 2) {
381
+ return {
382
+ kind: "invalid",
383
+ elementId,
384
+ reason: "package elementId must include packageName and entryFile"
385
+ };
386
+ }
387
+ const scoped = parts[0]?.startsWith("@");
388
+ const packageName = scoped ? parts.slice(0, 2).join("/") : parts[0];
389
+ const entryFile = parts.slice(scoped ? 2 : 1).join("/");
390
+ if (!entryFile) {
391
+ return {
392
+ kind: "invalid",
393
+ elementId,
394
+ reason: "package elementId must include entryFile"
395
+ };
396
+ }
397
+ return {
398
+ kind: "package",
399
+ elementId,
400
+ packageName,
401
+ entryFile
402
+ };
403
+ }
75
404
 
76
405
  // src/shared/sanitize.ts
77
406
  function truncateText(text, maxLength) {
@@ -96,6 +425,270 @@ function maskHeaders(headers = {}, maskNames = []) {
96
425
  );
97
426
  }
98
427
 
428
+ // src/runtime/domSnapshot.ts
429
+ function createDomSnapshot(root, options) {
430
+ let count = 0;
431
+ function visit(node, depth) {
432
+ if (count >= options.maxNodes || depth > options.maxDepth) {
433
+ return null;
434
+ }
435
+ if (node.nodeType === Node.TEXT_NODE) {
436
+ return createTextSnapshot(node, options, () => {
437
+ count += 1;
438
+ });
439
+ }
440
+ if (!(node instanceof Element)) {
441
+ return null;
442
+ }
443
+ const tag = node.tagName.toLowerCase();
444
+ if (["script", "style", "noscript"].includes(tag) || isInternalMcpElement(node)) {
445
+ return null;
446
+ }
447
+ count += 1;
448
+ return createElementSnapshot(node, tag, (child) => visit(child, depth + 1));
449
+ }
450
+ return visit(root, 0) ?? { tag: root.tagName.toLowerCase() };
451
+ }
452
+ function queryDomElements(selector, limit) {
453
+ return Array.from(document.querySelectorAll(selector)).filter((element) => !isInternalMcpElement(element)).slice(0, limit).map((element) => createDomElementSummary(element));
454
+ }
455
+ function createDomElementSummary(element) {
456
+ return {
457
+ tag: element.tagName.toLowerCase(),
458
+ text: element.textContent.trim(),
459
+ attrs: collectAttrs(element),
460
+ rect: serializeRect(element.getBoundingClientRect())
461
+ };
462
+ }
463
+ function createTextSnapshot(node, options, markVisited) {
464
+ const text = node.textContent?.trim();
465
+ if (!text) {
466
+ return null;
467
+ }
468
+ markVisited();
469
+ return { tag: "#text", text: truncateText(text, options.maxTextLength).text };
470
+ }
471
+ function createElementSnapshot(node, tag, visitChild) {
472
+ const attrs = collectAttrs(node);
473
+ const children = Array.from(node.childNodes).map((child) => visitChild(child)).filter((child) => Boolean(child));
474
+ return {
475
+ tag,
476
+ ...node.textContent.trim() ? { text: node.textContent.trim() } : {},
477
+ ...Object.keys(attrs).length ? { attrs } : {},
478
+ ...children.length ? { children } : {}
479
+ };
480
+ }
481
+ function collectAttrs(element) {
482
+ const attrs = {};
483
+ for (const attr of Array.from(element.attributes)) {
484
+ attrs[attr.name] = attr.value;
485
+ }
486
+ if (typeof HTMLInputElement !== "undefined" && element instanceof HTMLInputElement && element.type === "password") {
487
+ attrs.value = "[masked]";
488
+ }
489
+ return attrs;
490
+ }
491
+ function serializeRect(rect) {
492
+ return {
493
+ x: rect.x,
494
+ y: rect.y,
495
+ width: rect.width,
496
+ height: rect.height,
497
+ top: rect.top,
498
+ right: rect.right,
499
+ bottom: rect.bottom,
500
+ left: rect.left
501
+ };
502
+ }
503
+ function isInternalMcpElement(element) {
504
+ return element.getAttribute("data-v-mcp-internal") === "true";
505
+ }
506
+
507
+ // src/runtime/vueComponentLocator.ts
508
+ function locateVueComponentForElement(element, root) {
509
+ const component = findNearestComponent(element);
510
+ if (!component) {
511
+ return void 0;
512
+ }
513
+ const file = getComponentFile(component);
514
+ const name = getComponentName(component);
515
+ if (!file) {
516
+ return { name };
517
+ }
518
+ const packageLocation = parseNodeModulesFile(file);
519
+ if (packageLocation) {
520
+ return {
521
+ name,
522
+ source: void 0,
523
+ packageLocation
524
+ };
525
+ }
526
+ return {
527
+ name,
528
+ source: {
529
+ file: createProjectRelativePath(root, file)
530
+ },
531
+ packageLocation: void 0
532
+ };
533
+ }
534
+ function findNearestComponent(element) {
535
+ let current = element;
536
+ while (current) {
537
+ const component = current.__vueParentComponent;
538
+ if (isVueRuntimeComponent(component)) {
539
+ return component;
540
+ }
541
+ current = current.parentElement;
542
+ }
543
+ return void 0;
544
+ }
545
+ function getComponentName(component) {
546
+ return component.type?.name ?? component.type?.__name ?? component.type?.displayName;
547
+ }
548
+ function getComponentFile(component) {
549
+ return component.type?.__file;
550
+ }
551
+ function parseNodeModulesFile(file) {
552
+ const normalized = normalizePath(file);
553
+ const marker = "/node_modules/";
554
+ const index = normalized.lastIndexOf(marker);
555
+ if (index < 0) {
556
+ return void 0;
557
+ }
558
+ const parts = normalized.slice(index + marker.length).split("/").filter(Boolean);
559
+ const scoped = parts[0]?.startsWith("@");
560
+ const packageName = scoped ? parts.slice(0, 2).join("/") : parts[0];
561
+ const entryFile = parts.slice(scoped ? 2 : 1).join("/");
562
+ if (!packageName || !entryFile) {
563
+ return void 0;
564
+ }
565
+ return {
566
+ packageName,
567
+ entryFile
568
+ };
569
+ }
570
+ function normalizePath(path) {
571
+ return path.replace(/\\/g, "/");
572
+ }
573
+ function createProjectRelativePath(root, file) {
574
+ const normalizedRoot = normalizePath(root).replace(/\/$/, "");
575
+ const normalizedFile = normalizePath(file);
576
+ const prefix = `${normalizedRoot}/`;
577
+ if (normalizedFile.startsWith(prefix)) {
578
+ return normalizedFile.slice(prefix.length);
579
+ }
580
+ return normalizedFile.replace(/^\//, "");
581
+ }
582
+ function isVueRuntimeComponent(value) {
583
+ return Boolean(value && typeof value === "object" && "type" in value);
584
+ }
585
+
586
+ // src/runtime/elementContext.ts
587
+ var activeResolver;
588
+ function createElementContextResolver(options) {
589
+ return {
590
+ getElementContext(elementId) {
591
+ const parsed = parseElementId(elementId);
592
+ if (parsed.kind === "project-source") {
593
+ const element = options.querySelector(
594
+ `[data-v-mcp-id="${escapeSelector(elementId)}"]`
595
+ );
596
+ return createProjectSourceContext(parsed, element, options.root);
597
+ }
598
+ if (parsed.kind === "package") {
599
+ return createPackageContext(parsed);
600
+ }
601
+ if (parsed.kind === "runtime") {
602
+ const record = options.registry.get(elementId);
603
+ if (!record) {
604
+ return createMissingRuntimeElementError(elementId);
605
+ }
606
+ return createRuntimeContext(elementId, record.element, options.root);
607
+ }
608
+ return {
609
+ ok: false,
610
+ error: parsed.reason,
611
+ elementId,
612
+ limitations: ["please provide a copied elementId from the element picker"]
613
+ };
614
+ }
615
+ };
616
+ }
617
+ function setElementContextResolver(resolver) {
618
+ activeResolver = resolver;
619
+ }
620
+ function getElementContextResolver() {
621
+ activeResolver ??= createElementContextResolver({
622
+ root: "/",
623
+ registry: runtimeElementRegistry,
624
+ querySelector(selector) {
625
+ return document.querySelector(selector);
626
+ }
627
+ });
628
+ return activeResolver;
629
+ }
630
+ function createProjectSourceContext(parsed, element, root) {
631
+ return {
632
+ ok: true,
633
+ elementId: parsed.elementId,
634
+ editable: true,
635
+ codeLocation: {
636
+ file: parsed.file,
637
+ line: parsed.line,
638
+ column: parsed.column
639
+ },
640
+ ...element ? { component: locateVueComponentForElement(element, root) } : {},
641
+ ...element ? { dom: createDomElementSummary(element) } : {},
642
+ limitations: element ? [] : ["runtime DOM element was not found"]
643
+ };
644
+ }
645
+ function createPackageContext(parsed) {
646
+ return {
647
+ ok: true,
648
+ elementId: parsed.elementId,
649
+ editable: false,
650
+ packageLocation: {
651
+ packageName: parsed.packageName,
652
+ entryFile: parsed.entryFile
653
+ },
654
+ limitations: ["third-party package source is not editable from this project"]
655
+ };
656
+ }
657
+ function createRuntimeContext(elementId, element, root) {
658
+ const component = locateVueComponentForElement(element, root);
659
+ const sourceFile = component?.source?.file;
660
+ return {
661
+ ok: true,
662
+ elementId,
663
+ editable: Boolean(sourceFile),
664
+ ...sourceFile ? { codeLocation: { file: sourceFile, line: 1, column: 1 } } : {},
665
+ component,
666
+ dom: createDomElementSummary(element),
667
+ limitations: sourceFile ? ["runtime id maps to nearest component file, exact template node is unavailable"] : ["runtime id is only valid during the current page lifecycle"]
668
+ };
669
+ }
670
+ function createMissingRuntimeElementError(elementId) {
671
+ return {
672
+ ok: false,
673
+ error: "element not found",
674
+ elementId,
675
+ limitations: [
676
+ "element was removed or page refreshed",
677
+ "please ask the user to pick the element again"
678
+ ]
679
+ };
680
+ }
681
+ function escapeSelector(value) {
682
+ const css = globalThis.CSS;
683
+ if (css?.escape) {
684
+ return css.escape(value);
685
+ }
686
+ return value.replace(/["\\]/g, "\\$&");
687
+ }
688
+
689
+ // src/runtime/networkHook.ts
690
+ import { nanoid as nanoid3 } from "nanoid";
691
+
99
692
  // src/shared/url.ts
100
693
  function parseRequestQuery(url) {
101
694
  const parsed = new URL(url, "http://vite-plugin-vue-mcp-next.local");
@@ -125,7 +718,7 @@ function safeUrlPathname(url) {
125
718
  // src/runtime/networkHook.ts
126
719
  function createHookNetworkRecord(input) {
127
720
  return {
128
- id: nanoid2(),
721
+ id: nanoid3(),
129
722
  pageId: input.pageId,
130
723
  source: "hook",
131
724
  url: input.url,
@@ -280,12 +873,12 @@ function safeReadXhrResponseText(xhr) {
280
873
  }
281
874
 
282
875
  // src/runtime/pageIdentity.ts
283
- import { nanoid as nanoid3 } from "nanoid";
876
+ import { nanoid as nanoid4 } from "nanoid";
284
877
  var RUNTIME_CLIENT_ID_STORAGE_KEY = "vite-plugin-vue-mcp-next:runtime-client-id";
285
878
  var RUNTIME_CLIENT_ID_WINDOW_NAME_PREFIX = "vite-plugin-vue-mcp-next:runtime-client-id=";
286
879
  var RUNTIME_CLIENT_ID_WINDOW_NAME_SEPARATOR = "\n";
287
880
  function createRuntimeClientId() {
288
- return `runtime-client-${nanoid3()}`;
881
+ return `runtime-client-${nanoid4()}`;
289
882
  }
290
883
  function readRuntimeClientIdFromTabScope(tabScope) {
291
884
  if (!tabScope) {
@@ -334,7 +927,7 @@ function getRuntimeClientId(storage, tabScope) {
334
927
  }
335
928
  }
336
929
  function createRuntimePageId() {
337
- return `runtime-${nanoid3()}`;
930
+ return `runtime-${nanoid4()}`;
338
931
  }
339
932
  function getRuntimePageIdentity(input) {
340
933
  return {
@@ -354,102 +947,7 @@ function getRuntimePageIdentity(input) {
354
947
  }
355
948
 
356
949
  // src/runtime/performanceHook.ts
357
- import { nanoid as nanoid4 } from "nanoid";
358
-
359
- // src/shared/limits.ts
360
- var DEFAULT_DOM_MAX_DEPTH = 8;
361
- var DEFAULT_DOM_MAX_NODES = 2e3;
362
- var DEFAULT_DOM_MAX_TEXT_LENGTH = 300;
363
- var DEFAULT_CONSOLE_MAX_RECORDS = 1e3;
364
- var DEFAULT_NETWORK_MAX_RECORDS = 500;
365
- var DEFAULT_NETWORK_MAX_BODY_SIZE = 1e5;
366
- var DEFAULT_MASK_HEADERS = [
367
- "authorization",
368
- "cookie",
369
- "set-cookie"
370
- ];
371
-
372
- // src/constants.ts
373
- var DEFAULT_MCP_PATH = "/__mcp";
374
- var DEFAULT_SCREENSHOT_MAX_BYTES = 5 * 1024 * 1024;
375
- var DEFAULT_SCREENSHOT_SAVE_DIR = ".vite-mcp/screenshot";
376
- var DEFAULT_PERFORMANCE_SAVE_DIR = ".vite-mcp/performance";
377
- var DEFAULT_PERFORMANCE_MAX_DURATION_MS = 3e4;
378
- var DEFAULT_PERFORMANCE_SAMPLE_INTERVAL_MS = 250;
379
- var DEFAULT_PERFORMANCE_LONG_TASK_THRESHOLD_MS = 50;
380
- var VIRTUAL_RUNTIME_ID = "virtual:vite-plugin-vue-mcp-next/runtime";
381
- var RESOLVED_VIRTUAL_RUNTIME_ID = `\0${VIRTUAL_RUNTIME_ID}`;
382
- var VIRTUAL_SCREENSHOT_CONFIG_ID = "virtual:vite-plugin-vue-mcp-next/screenshot-config";
383
- var RESOLVED_VIRTUAL_SCREENSHOT_CONFIG_ID = `\0${VIRTUAL_SCREENSHOT_CONFIG_ID}`;
384
- var VIRTUAL_SNAPDOM_LOADER_ID = "virtual:vite-plugin-vue-mcp-next/snapdom-loader";
385
- var RESOLVED_VIRTUAL_SNAPDOM_LOADER_ID = `\0${VIRTUAL_SNAPDOM_LOADER_ID}`;
386
- var DEFAULT_MCP_CLIENT_SERVER_NAME = "vite-mcp-next";
387
- var DEFAULT_OPTIONS = {
388
- mcpPath: DEFAULT_MCP_PATH,
389
- host: "localhost",
390
- printUrl: true,
391
- updateCursorMcpJson: {
392
- enabled: true,
393
- serverName: DEFAULT_MCP_CLIENT_SERVER_NAME
394
- },
395
- mcpClients: {
396
- cursor: true,
397
- codex: true,
398
- claudeCode: true,
399
- trae: true,
400
- serverName: DEFAULT_MCP_CLIENT_SERVER_NAME
401
- },
402
- skill: {
403
- autoConfig: true
404
- },
405
- runtime: {
406
- mode: "auto",
407
- evaluate: {
408
- enabled: false,
409
- timeoutMs: 3e3
410
- }
411
- },
412
- cdp: {},
413
- network: {
414
- mode: "auto",
415
- maxRecords: DEFAULT_NETWORK_MAX_RECORDS,
416
- captureRequestBody: true,
417
- captureResponseBody: true,
418
- maxBodySize: DEFAULT_NETWORK_MAX_BODY_SIZE,
419
- maskHeaders: [...DEFAULT_MASK_HEADERS]
420
- },
421
- dom: {
422
- maxDepth: DEFAULT_DOM_MAX_DEPTH,
423
- maxNodes: DEFAULT_DOM_MAX_NODES,
424
- maxTextLength: DEFAULT_DOM_MAX_TEXT_LENGTH
425
- },
426
- console: {
427
- maxRecords: DEFAULT_CONSOLE_MAX_RECORDS
428
- },
429
- screenshot: {
430
- type: "path",
431
- saveDir: DEFAULT_SCREENSHOT_SAVE_DIR,
432
- prefer: "auto",
433
- maxBytes: DEFAULT_SCREENSHOT_MAX_BYTES,
434
- snapdom: {
435
- options: {},
436
- plugins: []
437
- }
438
- },
439
- performance: {
440
- mode: "auto",
441
- maxDurationMs: DEFAULT_PERFORMANCE_MAX_DURATION_MS,
442
- sampleIntervalMs: DEFAULT_PERFORMANCE_SAMPLE_INTERVAL_MS,
443
- longTaskThresholdMs: DEFAULT_PERFORMANCE_LONG_TASK_THRESHOLD_MS,
444
- saveDir: DEFAULT_PERFORMANCE_SAVE_DIR,
445
- memory: {
446
- enabled: true
447
- },
448
- stacks: {
449
- enabled: true
450
- }
451
- }
452
- };
950
+ import { nanoid as nanoid5 } from "nanoid";
453
951
 
454
952
  // src/performance/summary.ts
455
953
  function buildPerformanceSummary(input) {
@@ -623,7 +1121,7 @@ function createPerformanceCollector(deps) {
623
1121
  };
624
1122
  }
625
1123
  function createRecordingId() {
626
- return `performance-${nanoid4()}`;
1124
+ return `performance-${nanoid5()}`;
627
1125
  }
628
1126
  function startSession(state, deps, options) {
629
1127
  const recordingId = createRecordingId();
@@ -998,78 +1496,6 @@ import {
998
1496
  } from "@vue/devtools-kit";
999
1497
  import { createRPCClient } from "vite-dev-rpc";
1000
1498
 
1001
- // src/runtime/domSnapshot.ts
1002
- function createDomSnapshot(root, options) {
1003
- let count = 0;
1004
- function visit(node, depth) {
1005
- if (count >= options.maxNodes || depth > options.maxDepth) {
1006
- return null;
1007
- }
1008
- if (node.nodeType === Node.TEXT_NODE) {
1009
- return createTextSnapshot(node, options, () => {
1010
- count += 1;
1011
- });
1012
- }
1013
- if (!(node instanceof Element)) {
1014
- return null;
1015
- }
1016
- const tag = node.tagName.toLowerCase();
1017
- if (["script", "style", "noscript"].includes(tag)) {
1018
- return null;
1019
- }
1020
- count += 1;
1021
- return createElementSnapshot(node, tag, (child) => visit(child, depth + 1));
1022
- }
1023
- return visit(root, 0) ?? { tag: root.tagName.toLowerCase() };
1024
- }
1025
- function queryDomElements(selector, limit) {
1026
- return Array.from(document.querySelectorAll(selector)).slice(0, limit).map((element) => ({
1027
- tag: element.tagName.toLowerCase(),
1028
- text: element.textContent.trim(),
1029
- attrs: collectAttrs(element),
1030
- rect: serializeRect(element.getBoundingClientRect())
1031
- }));
1032
- }
1033
- function createTextSnapshot(node, options, markVisited) {
1034
- const text = node.textContent?.trim();
1035
- if (!text) {
1036
- return null;
1037
- }
1038
- markVisited();
1039
- return { tag: "#text", text: truncateText(text, options.maxTextLength).text };
1040
- }
1041
- function createElementSnapshot(node, tag, visitChild) {
1042
- const attrs = collectAttrs(node);
1043
- const children = Array.from(node.childNodes).map((child) => visitChild(child)).filter((child) => Boolean(child));
1044
- return {
1045
- tag,
1046
- ...Object.keys(attrs).length ? { attrs } : {},
1047
- ...children.length ? { children } : {}
1048
- };
1049
- }
1050
- function collectAttrs(element) {
1051
- const attrs = {};
1052
- for (const attr of Array.from(element.attributes)) {
1053
- attrs[attr.name] = attr.value;
1054
- }
1055
- if (element instanceof HTMLInputElement && element.type === "password") {
1056
- attrs.value = "[masked]";
1057
- }
1058
- return attrs;
1059
- }
1060
- function serializeRect(rect) {
1061
- return {
1062
- x: rect.x,
1063
- y: rect.y,
1064
- width: rect.width,
1065
- height: rect.height,
1066
- top: rect.top,
1067
- right: rect.right,
1068
- bottom: rect.bottom,
1069
- left: rect.left
1070
- };
1071
- }
1072
-
1073
1499
  // src/runtime/evaluateExpression.ts
1074
1500
  async function evaluateExpression(request) {
1075
1501
  const value = runExpression(request.expression);
@@ -1497,6 +1923,22 @@ function createRuntimeDevtoolsRpc(getRpc) {
1497
1923
  );
1498
1924
  },
1499
1925
  onDomQueryUpdated: () => void 0,
1926
+ getElementContext(options) {
1927
+ try {
1928
+ getRpc().onElementContextUpdated(
1929
+ options.event,
1930
+ getElementContextResolver().getElementContext(options.elementId)
1931
+ );
1932
+ } catch (error) {
1933
+ getRpc().onElementContextUpdated(options.event, {
1934
+ ok: false,
1935
+ elementId: options.elementId,
1936
+ error: error instanceof Error ? error.message : String(error),
1937
+ limitations: ["runtime element context lookup failed"]
1938
+ });
1939
+ }
1940
+ },
1941
+ onElementContextUpdated: () => void 0,
1500
1942
  reloadPage(options) {
1501
1943
  getRpc().onPageReloaded(options.event, { ok: true, source: "hook" });
1502
1944
  setTimeout(() => {
@@ -1833,13 +2275,16 @@ function createMissingComponentError(componentName) {
1833
2275
  }
1834
2276
 
1835
2277
  // src/runtime/client.ts
1836
- async function startRuntimeClient() {
2278
+ async function startRuntimeClient(runtimeOptions = {
2279
+ elementPicker: DEFAULT_OPTIONS.elementPicker
2280
+ }) {
1837
2281
  initializeVueDevtoolsHook();
1838
2282
  const hot = await createHotContext("vite-plugin-vue-mcp-next", "/");
1839
2283
  if (!hot) {
1840
2284
  return;
1841
2285
  }
1842
2286
  installVueBridge(hot);
2287
+ installElementPicker(runtimeOptions.elementPicker);
1843
2288
  const identity = getRuntimePageIdentity({
1844
2289
  href: window.location.href,
1845
2290
  title: document.title,
@@ -1848,7 +2293,20 @@ async function startRuntimeClient() {
1848
2293
  innerHeight: window.innerHeight,
1849
2294
  readyState: document.readyState
1850
2295
  });
1851
- hot.send("vite-plugin-vue-mcp-next:page-connected", identity);
2296
+ setElementContextResolver(
2297
+ createElementContextResolver({
2298
+ root: runtimeOptions.projectRoot ?? "/",
2299
+ registry: runtimeElementRegistry,
2300
+ querySelector(selector) {
2301
+ return document.querySelector(selector);
2302
+ }
2303
+ })
2304
+ );
2305
+ hot.send(RUNTIME_PAGE_CONNECTED_EVENT, identity);
2306
+ installRuntimePageLifecycle({
2307
+ pageId: identity.pageId,
2308
+ send: hot.send.bind(hot)
2309
+ });
1852
2310
  installPerformanceHook({
1853
2311
  pageId: identity.pageId,
1854
2312
  send(report) {
@@ -1870,6 +2328,27 @@ async function startRuntimeClient() {
1870
2328
  }
1871
2329
  });
1872
2330
  }
2331
+ function installRuntimePageLifecycle(options) {
2332
+ let disconnected = false;
2333
+ const heartbeatTimer = setInterval(() => {
2334
+ options.send(RUNTIME_PAGE_HEARTBEAT_EVENT, {
2335
+ pageId: options.pageId,
2336
+ timestamp: Date.now()
2337
+ });
2338
+ }, DEFAULT_RUNTIME_PAGE_HEARTBEAT_INTERVAL_MS);
2339
+ const disconnect = () => {
2340
+ if (disconnected) {
2341
+ return;
2342
+ }
2343
+ disconnected = true;
2344
+ clearInterval(heartbeatTimer);
2345
+ options.send(RUNTIME_PAGE_DISCONNECTED_EVENT, {
2346
+ pageId: options.pageId
2347
+ });
2348
+ };
2349
+ window.addEventListener("pagehide", disconnect, { once: true });
2350
+ window.addEventListener("beforeunload", disconnect, { once: true });
2351
+ }
1873
2352
  export {
1874
2353
  evaluateExpression,
1875
2354
  setScreenshotModuleRegistry,