Skip to main content

victauri_plugin/
js_bridge.rs

1/// JS bridge log capacity configuration.
2pub struct BridgeCapacities {
3    /// Maximum console log entries to retain.
4    pub console_logs: usize,
5    /// Maximum DOM mutation batches to retain.
6    pub mutation_log: usize,
7    /// Maximum network request entries to retain.
8    pub network_log: usize,
9    /// Maximum navigation history entries to retain.
10    pub navigation_log: usize,
11    /// Maximum dialog event entries to retain.
12    pub dialog_log: usize,
13    /// Maximum long task entries to retain.
14    pub long_tasks: usize,
15}
16
17impl Default for BridgeCapacities {
18    fn default() -> Self {
19        Self {
20            console_logs: 1000,
21            mutation_log: 500,
22            network_log: 1000,
23            navigation_log: 200,
24            dialog_log: 100,
25            long_tasks: 100,
26        }
27    }
28}
29
30/// Generate the JS init script with custom log capacities.
31#[must_use]
32pub fn init_script(caps: &BridgeCapacities) -> String {
33    format!(
34        "\n(function() {{\
35        \n    if (window.__VICTAURI__) return;\
36        \n\
37        \n    var CAP_CONSOLE = {console_logs};\
38        \n    var CAP_MUTATION = {mutation_log};\
39        \n    var CAP_NETWORK = {network_log};\
40        \n    var CAP_NAVIGATION = {navigation_log};\
41        \n    var CAP_DIALOG = {dialog_log};\
42        \n    var CAP_LONG_TASKS = {long_tasks};\
43        \n",
44        console_logs = caps.console_logs,
45        mutation_log = caps.mutation_log,
46        network_log = caps.network_log,
47        navigation_log = caps.navigation_log,
48        dialog_log = caps.dialog_log,
49        long_tasks = caps.long_tasks,
50    ) + INIT_SCRIPT_BODY
51}
52
53/// The body of the init script (after capacity variable declarations).
54/// Uses CAP_* variables for all log limits.
55const INIT_SCRIPT_BODY: &str = r#"
56    var refMap = new Map();
57    var refCounter = 0;
58    var weakRefMap = new Map();
59
60    function resolveRef(refId) {
61        var direct = refMap.get(refId);
62        if (direct) {
63            if (direct.isConnected) return direct;
64            refMap.delete(refId);
65            return null;
66        }
67        var weak = weakRefMap.get(refId);
68        if (weak) {
69            var el = weak.deref();
70            if (el && el.isConnected) return el;
71            weakRefMap.delete(refId);
72            return null;
73        }
74        return null;
75    }
76
77    var REF_MAP_LIMIT = 10000;
78
79    function registerRef(node) {
80        var ref_id = 'e' + (refCounter++);
81        if (refMap.size >= REF_MAP_LIMIT) {
82            var oldest = refMap.keys().next().value;
83            refMap.delete(oldest);
84            weakRefMap.delete(oldest);
85        }
86        refMap.set(ref_id, node);
87        if (typeof WeakRef !== 'undefined') {
88            weakRefMap.set(ref_id, new WeakRef(node));
89        }
90        return ref_id;
91    }
92
93    function getStaleRefs() {
94        var stale = [];
95        weakRefMap.forEach(function(weak, refId) {
96            var el = weak.deref();
97            if (!el || !el.isConnected) {
98                stale.push(refId);
99                weakRefMap.delete(refId);
100                refMap.delete(refId);
101            }
102        });
103        return stale;
104    }
105    var consoleLogs = [];
106    var mutationLog = [];
107    var networkLog = [];
108    var networkCounter = 0;
109    var navigationLog = [];
110    var dialogLog = [];
111    var interactionLog = [];
112    var CAP_INTERACTION = 500;
113    var ipcWaiters = [];
114    var longTasks = [];
115    var listenerCount = 0;
116
117    // ── Network route rules (Phase 1: interception / mock / block / delay) ──
118    var routeRules = [];
119    var routeCounter = 0;
120    var routeMatchLog = [];
121    var CAP_ROUTE_MATCHES = 200;
122
123    // Convert a glob ("*" wildcard) to a RegExp. Other chars are escaped.
124    function globToRegExp(glob) {
125        var re = glob.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*');
126        return new RegExp('^' + re + '$');
127    }
128
129    // Find the first active route rule matching url+method, or null.
130    // Never matches Victauri's own internal IPC traffic.
131    function matchRoute(url, method) {
132        if (!routeRules.length) return null;
133        if (url.indexOf('plugin%3Avictauri%7C') !== -1 || url.indexOf('plugin:victauri|') !== -1) {
134            return null;
135        }
136        var m = (method || 'GET').toUpperCase();
137        for (var i = 0; i < routeRules.length; i++) {
138            var r = routeRules[i];
139            if (r.times && r.triggered >= r.times) continue;
140            if (r.method && r.method.toUpperCase() !== m) continue;
141            var hit = false;
142            try {
143                if (r.match_type === 'exact') hit = (url === r.pattern);
144                else if (r.match_type === 'regex') hit = new RegExp(r.pattern).test(url);
145                else if (r.match_type === 'glob') hit = globToRegExp(r.pattern).test(url);
146                else hit = (url.indexOf(r.pattern) !== -1); // substring (default)
147            } catch (e) { hit = false; }
148            if (hit) return r;
149        }
150        return null;
151    }
152
153    function recordRouteMatch(rule, url, method) {
154        rule.triggered = (rule.triggered || 0) + 1;
155        routeMatchLog.push({
156            rule_id: rule.id, action: rule.action, url: url,
157            method: (method || 'GET').toUpperCase(), timestamp: Date.now(),
158            trigger_count: rule.triggered,
159        });
160        if (routeMatchLog.length > CAP_ROUTE_MATCHES) routeMatchLog.shift();
161    }
162
163    function checkActionable(el) {
164        if (!el || !el.isConnected) return { error: 'element is detached from DOM', hint: 'RETRY_LATER' };
165        if (el.disabled) return { error: 'element is disabled (disabled attribute)', hint: 'RETRY_LATER' };
166        if (el.getAttribute && el.getAttribute('aria-disabled') === 'true') return { error: 'element is disabled (aria-disabled)', hint: 'RETRY_LATER' };
167        // Use the element's OWN document/window so the viewport and occlusion
168        // (elementFromPoint) checks are correct for elements inside same-origin
169        // iframes — getBoundingClientRect() is relative to the element's own
170        // frame viewport, not the top document.
171        var doc = el.ownerDocument || document;
172        var win = doc.defaultView || window;
173        var cs = win.getComputedStyle(el);
174        if (cs.display === 'none') return { error: 'element is not visible (display: none)', hint: 'RETRY_LATER' };
175        if (cs.visibility === 'hidden') return { error: 'element is not visible (visibility: hidden)', hint: 'RETRY_LATER' };
176        if (parseFloat(cs.opacity) < 0.01) return { error: 'element is not visible (opacity: ' + cs.opacity + ')', hint: 'RETRY_LATER' };
177        var rect = el.getBoundingClientRect();
178        if (rect.width === 0 && rect.height === 0) return { error: 'element has zero size', hint: 'RETRY_LATER' };
179        if (cs.pointerEvents === 'none') return { error: 'element has pointer-events: none', hint: 'RETRY_LATER' };
180        var vw = win.innerWidth || doc.documentElement.clientWidth;
181        var vh = win.innerHeight || doc.documentElement.clientHeight;
182        if (rect.bottom < 0 || rect.top > vh || rect.right < 0 || rect.left > vw) {
183            el.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' });
184            rect = el.getBoundingClientRect();
185            if (rect.bottom < 0 || rect.top > vh || rect.right < 0 || rect.left > vw) {
186                return { error: 'element is outside viewport after scroll attempt', hint: 'CHECK_INPUT' };
187            }
188        }
189        var cx = rect.left + rect.width / 2;
190        var cy = rect.top + rect.height / 2;
191        var topEl = doc.elementFromPoint(cx, cy);
192        if (topEl && topEl !== el && !el.contains(topEl) && !topEl.contains(el)) {
193            var tag = topEl.tagName ? topEl.tagName.toLowerCase() : 'unknown';
194            var info = tag;
195            if (topEl.id) info += '#' + topEl.id;
196            else if (topEl.className && typeof topEl.className === 'string') {
197                var cls = topEl.className.trim().split(/\s+/)[0];
198                if (cls) info += '.' + cls;
199            }
200            return { error: 'element is covered by ' + info + ' at (' + Math.round(cx) + ',' + Math.round(cy) + ')', hint: 'RETRY_LATER' };
201        }
202        return null;
203    }
204
205    function withAutoWait(refId, timeoutMs, actionFn) {
206        return new Promise(function(resolve) {
207            var deadline = Date.now() + (timeoutMs || 5000);
208            function attempt() {
209                var el = resolveRef(refId);
210                if (!el) {
211                    if (Date.now() >= deadline) { resolve({ ok: false, error: 'ref not found: ' + refId, hint: 'CHECK_INPUT' }); return; }
212                    setTimeout(attempt, 50); return;
213                }
214                var check = checkActionable(el);
215                if (check) {
216                    if (check.hint === 'CHECK_INPUT' || Date.now() >= deadline) {
217                        var msg = Date.now() >= deadline ? 'timeout (' + (timeoutMs || 5000) + 'ms): ' + check.error : check.error;
218                        resolve({ ok: false, error: msg, hint: check.hint || 'RETRY_LATER' }); return;
219                    }
220                    setTimeout(attempt, 50); return;
221                }
222                try { var r = actionFn(el); resolve(r || { ok: true }); }
223                catch (e) { resolve({ ok: false, error: 'action threw: ' + e.message, hint: 'CHECK_INPUT' }); }
224            }
225            attempt();
226        });
227    }
228
229    // ── Public API ───────────────────────────────────────────────────────────
230
231    window.__VICTAURI__ = {
232        version: '0.7.5',
233        _captureIpcBodies: true,
234
235        // ── DOM ──────────────────────────────────────────────────────────────
236
237        snapshot: function(format) {
238            var previousRefs = new Set(refMap.keys());
239            refMap.clear();
240            var fmt = format || 'compact';
241            var tree;
242            if (fmt === 'json') {
243                tree = walkDom(document.body);
244            } else {
245                tree = walkDomCompact(document.body, 0);
246            }
247            var currentRefs = new Set(refMap.keys());
248            var stale = [];
249            previousRefs.forEach(function(refId) {
250                if (!currentRefs.has(refId)) {
251                    var weak = weakRefMap.get(refId);
252                    if (weak) {
253                        var el = weak.deref();
254                        if (!el || !el.isConnected) {
255                            stale.push(refId);
256                            weakRefMap.delete(refId);
257                        }
258                    } else {
259                        stale.push(refId);
260                    }
261                }
262            });
263            weakRefMap.forEach(function(weak, rid) {
264                if (!weak.deref()) {
265                    weakRefMap.delete(rid);
266                    stale.push(rid);
267                }
268            });
269            return { tree: tree, stale_refs: stale, format: fmt };
270        },
271
272        getRef: function(refId) {
273            return resolveRef(refId);
274        },
275
276        getStaleRefs: function() {
277            return getStaleRefs();
278        },
279
280        findElements: function(query) {
281            var results = [];
282            var maxResults = query.max_results || 10;
283
284            if (query.css) {
285                try { document.body.matches(query.css); } catch(e) {
286                    return { error: 'invalid CSS selector: ' + query.css + ' — ' + e.message };
287                }
288            }
289
290            function matches(el) {
291                if (query.text) {
292                    var txt = (el.textContent || '').trim();
293                    if (query.exact) {
294                        if (txt !== query.text) return false;
295                    } else {
296                        if (txt.toLowerCase().indexOf(query.text.toLowerCase()) === -1) return false;
297                    }
298                }
299                if (query.role) {
300                    var role = el.getAttribute('role') || inferRole(el);
301                    if (role !== query.role) return false;
302                }
303                if (query.test_id) {
304                    if (el.getAttribute('data-testid') !== query.test_id) return false;
305                }
306                if (query.css) {
307                    if (!el.matches(query.css)) return false;
308                }
309                if (query.name) {
310                    var name = el.getAttribute('aria-label')
311                        || el.getAttribute('title')
312                        || el.getAttribute('placeholder') || '';
313                    if (name.toLowerCase().indexOf(query.name.toLowerCase()) === -1) return false;
314                }
315                if (query.tag) {
316                    if (el.tagName.toLowerCase() !== query.tag.toLowerCase()) return false;
317                }
318                if (query.placeholder) {
319                    if ((el.getAttribute('placeholder') || '').toLowerCase().indexOf(query.placeholder.toLowerCase()) === -1) return false;
320                }
321                if (query.alt) {
322                    if ((el.getAttribute('alt') || '').toLowerCase().indexOf(query.alt.toLowerCase()) === -1) return false;
323                }
324                if (query.title_attr) {
325                    if ((el.getAttribute('title') || '').toLowerCase().indexOf(query.title_attr.toLowerCase()) === -1) return false;
326                }
327                if (query.enabled === true && el.disabled) return false;
328                if (query.enabled === false && !el.disabled) return false;
329                return true;
330            }
331
332            function buildResult(node, style) {
333                var existingRef = null;
334                refMap.forEach(function(el, refId) {
335                    if (el === node) existingRef = refId;
336                });
337                var ref_id = existingRef || registerRef(node);
338                var role = node.getAttribute('role') || inferRole(node);
339                var rect = node.getBoundingClientRect();
340                var vis = true;
341                if (style) {
342                    vis = style.display !== 'none' && style.visibility !== 'hidden';
343                }
344                return {
345                    ref_id: ref_id,
346                    tag: node.tagName.toLowerCase(),
347                    role: role,
348                    name: node.getAttribute('aria-label') || node.getAttribute('title') || null,
349                    text: (node.textContent || '').trim().substring(0, 100),
350                    bounds: { x: Math.round(rect.x), y: Math.round(rect.y), width: Math.round(rect.width), height: Math.round(rect.height) },
351                    visible: vis,
352                    enabled: !node.disabled,
353                    value: node.value || null
354                };
355            }
356
357            if (query.label) {
358                var labels = document.querySelectorAll('label');
359                for (var li = 0; li < labels.length && results.length < maxResults; li++) {
360                    var lbl = labels[li];
361                    if ((lbl.textContent || '').toLowerCase().indexOf(query.label.toLowerCase()) === -1) continue;
362                    var target = null;
363                    var forAttr = lbl.getAttribute('for');
364                    if (forAttr) {
365                        target = document.getElementById(forAttr);
366                    }
367                    if (!target) {
368                        target = lbl.querySelector('input, textarea, select');
369                    }
370                    if (target) {
371                        var ts = window.getComputedStyle(target);
372                        results.push(buildResult(target, ts));
373                    }
374                }
375                return results;
376            }
377
378            function search(node) {
379                if (results.length >= maxResults) return;
380                if (!node || node.nodeType !== 1) return;
381                var style = window.getComputedStyle(node);
382                if (style.display === 'none' || style.visibility === 'hidden') return;
383
384                if (matches(node)) {
385                    results.push(buildResult(node, style));
386                }
387
388                for (var c = 0; c < node.children.length; c++) {
389                    search(node.children[c]);
390                }
391                if (node.shadowRoot) {
392                    for (var s = 0; s < node.shadowRoot.children.length; s++) {
393                        search(node.shadowRoot.children[s]);
394                    }
395                }
396                // Same-origin iframe traversal.
397                if (node.tagName === 'IFRAME' || node.tagName === 'FRAME') {
398                    try {
399                        var idoc = node.contentDocument;
400                        if (idoc && idoc.body) search(idoc.body);
401                    } catch (e) { /* cross-origin: skip */ }
402                }
403            }
404
405            search(document.body);
406            return results;
407        },
408
409        // ── Interactions ─────────────────────────────────────────────────────
410
411        click: function(refId, timeoutMs) {
412            return withAutoWait(refId, timeoutMs, function(el) {
413                el.click();
414                return { ok: true };
415            });
416        },
417
418        doubleClick: function(refId, timeoutMs) {
419            return withAutoWait(refId, timeoutMs, function(el) {
420                el.dispatchEvent(new MouseEvent('dblclick', { bubbles: true, cancelable: true }));
421                return { ok: true };
422            });
423        },
424
425        hover: function(refId, timeoutMs) {
426            return withAutoWait(refId, timeoutMs, function(el) {
427                el.dispatchEvent(new MouseEvent('mouseenter', { bubbles: true }));
428                el.dispatchEvent(new MouseEvent('mouseover', { bubbles: true }));
429                return { ok: true };
430            });
431        },
432
433        fill: function(refId, value, timeoutMs) {
434            return withAutoWait(refId, timeoutMs, function(el) {
435                if (!el.matches('input, textarea, [contenteditable="true"]')) {
436                    return { ok: false, error: 'element is not fillable (not input, textarea, or contenteditable): ' + (el.tagName || '').toLowerCase(), hint: 'CHECK_INPUT' };
437                }
438                var proto = el instanceof HTMLTextAreaElement
439                    ? HTMLTextAreaElement.prototype
440                    : HTMLInputElement.prototype;
441                var desc = Object.getOwnPropertyDescriptor(proto, 'value');
442                if (desc && desc.set) {
443                    desc.set.call(el, value);
444                } else {
445                    el.value = value;
446                }
447                el.dispatchEvent(new Event('input', { bubbles: true }));
448                el.dispatchEvent(new Event('change', { bubbles: true }));
449                return { ok: true };
450            });
451        },
452
453        type: function(refId, text, timeoutMs) {
454            return withAutoWait(refId, timeoutMs, function(el) {
455                el.focus();
456                var proto = el instanceof HTMLTextAreaElement
457                    ? HTMLTextAreaElement.prototype
458                    : HTMLInputElement.prototype;
459                var desc = Object.getOwnPropertyDescriptor(proto, 'value');
460                for (var i = 0; i < text.length; i++) {
461                    var ch = text[i];
462                    el.dispatchEvent(new KeyboardEvent('keydown', { key: ch, bubbles: true }));
463                    el.dispatchEvent(new KeyboardEvent('keypress', { key: ch, bubbles: true }));
464                    var current = el.value || '';
465                    if (desc && desc.set) {
466                        desc.set.call(el, current + ch);
467                    } else {
468                        el.value = current + ch;
469                    }
470                    el.dispatchEvent(new InputEvent('input', { bubbles: true, data: ch, inputType: 'insertText' }));
471                    el.dispatchEvent(new KeyboardEvent('keyup', { key: ch, bubbles: true }));
472                }
473                el.dispatchEvent(new Event('change', { bubbles: true }));
474                return { ok: true };
475            });
476        },
477
478        pressKey: function(key) {
479            var target = document.activeElement || document.body;
480            var parts = key.split('+');
481            if (parts.length === 1 || (parts.length === 2 && parts[0] === '' && parts[1] === '')) {
482                var k = parts.length === 1 ? key : '+';
483                target.dispatchEvent(new KeyboardEvent('keydown', { key: k, bubbles: true }));
484                target.dispatchEvent(new KeyboardEvent('keyup', { key: k, bubbles: true }));
485                return { ok: true };
486            }
487            var finalKey = parts.pop();
488            var mods = { ctrlKey: false, shiftKey: false, altKey: false, metaKey: false };
489            for (var m = 0; m < parts.length; m++) {
490                var mod = parts[m];
491                if (mod === 'Control' || mod === 'Ctrl') mods.ctrlKey = true;
492                else if (mod === 'Shift') mods.shiftKey = true;
493                else if (mod === 'Alt') mods.altKey = true;
494                else if (mod === 'Meta' || mod === 'Command' || mod === 'Cmd') mods.metaKey = true;
495            }
496            var modKeys = [];
497            if (mods.ctrlKey) modKeys.push('Control');
498            if (mods.shiftKey) modKeys.push('Shift');
499            if (mods.altKey) modKeys.push('Alt');
500            if (mods.metaKey) modKeys.push('Meta');
501            for (var i = 0; i < modKeys.length; i++) {
502                target.dispatchEvent(new KeyboardEvent('keydown', { key: modKeys[i], bubbles: true, ctrlKey: mods.ctrlKey, shiftKey: mods.shiftKey, altKey: mods.altKey, metaKey: mods.metaKey }));
503            }
504            target.dispatchEvent(new KeyboardEvent('keydown', { key: finalKey, bubbles: true, ctrlKey: mods.ctrlKey, shiftKey: mods.shiftKey, altKey: mods.altKey, metaKey: mods.metaKey }));
505            target.dispatchEvent(new KeyboardEvent('keyup', { key: finalKey, bubbles: true, ctrlKey: mods.ctrlKey, shiftKey: mods.shiftKey, altKey: mods.altKey, metaKey: mods.metaKey }));
506            for (var j = modKeys.length - 1; j >= 0; j--) {
507                target.dispatchEvent(new KeyboardEvent('keyup', { key: modKeys[j], bubbles: true, ctrlKey: mods.ctrlKey, shiftKey: mods.shiftKey, altKey: mods.altKey, metaKey: mods.metaKey }));
508            }
509            return { ok: true };
510        },
511
512        selectOption: function(refId, values, timeoutMs) {
513            return withAutoWait(refId, timeoutMs, function(el) {
514                if (el.tagName !== 'SELECT') {
515                    return { ok: false, error: 'element is not a <select>', hint: 'CHECK_INPUT' };
516                }
517                var valSet = new Set(values);
518                for (var i = 0; i < el.options.length; i++) {
519                    el.options[i].selected = valSet.has(el.options[i].value);
520                }
521                el.dispatchEvent(new Event('change', { bubbles: true }));
522                return { ok: true };
523            });
524        },
525
526        scrollTo: function(refId, x, y, timeoutMs) {
527            if (refId) {
528                return withAutoWait(refId, timeoutMs, function(el) {
529                    el.scrollIntoView({ behavior: 'smooth', block: 'center' });
530                    return { ok: true };
531                });
532            } else {
533                window.scrollTo({ left: x || 0, top: y || 0, behavior: 'smooth' });
534                return Promise.resolve({ ok: true });
535            }
536        },
537
538        focusElement: function(refId, timeoutMs) {
539            return withAutoWait(refId, timeoutMs, function(el) {
540                el.focus();
541                return { ok: true, tag: el.tagName.toLowerCase() };
542            });
543        },
544
545        // ── IPC Log ──────────────────────────────────────────────────────────
546
547        getIpcLog: function(limit) {
548            var ipcPrefix = 'http://ipc.localhost/';
549            var victauriPrefix = 'plugin%3Avictauri%7C';
550            var entries = [];
551            for (var i = 0; i < networkLog.length; i++) {
552                var n = networkLog[i];
553                if (n.url.indexOf(ipcPrefix) !== 0) continue;
554                var raw = n.url.substring(ipcPrefix.length);
555                if (raw.indexOf(victauriPrefix) === 0) continue;
556                var command;
557                try { command = decodeURIComponent(raw); } catch(e) { command = raw; }
558                entries.push({
559                    id: n.id,
560                    command: command,
561                    args: n.request_args || {},
562                    timestamp: n.timestamp,
563                    status: n.status === 200 ? 'ok' : (n.status === 'pending' ? 'pending' : 'error'),
564                    duration_ms: n.duration_ms,
565                    result: n.response_body || null,
566                    error: n.status !== 200 && n.status !== 'pending' ? 'HTTP ' + n.status : null,
567                });
568            }
569            if (limit) return entries.slice(-limit);
570            return entries;
571        },
572
573        clearIpcLog: function() {
574            var ipcPrefix = 'http://ipc.localhost/';
575            for (var i = networkLog.length - 1; i >= 0; i--) {
576                if (networkLog[i].url.indexOf(ipcPrefix) === 0) networkLog.splice(i, 1);
577            }
578        },
579
580        waitForIpcComplete: function(timeoutMs) {
581            var log = window.__VICTAURI__.getIpcLog();
582            if (log.length > 0) {
583                var last = log[log.length - 1];
584                if (last.duration_ms !== null && last.duration_ms !== undefined && last.result !== null) {
585                    return Promise.resolve(true);
586                }
587            }
588            return new Promise(function(resolve) {
589                var timer = setTimeout(function() {
590                    var idx = ipcWaiters.indexOf(waiterFn);
591                    if (idx !== -1) ipcWaiters.splice(idx, 1);
592                    resolve(false);
593                }, timeoutMs || 500);
594                function waiterFn() {
595                    clearTimeout(timer);
596                    resolve(true);
597                }
598                ipcWaiters.push(waiterFn);
599            });
600        },
601
602        // ── Console ──────────────────────────────────────────────────────────
603
604        getConsoleLogs: function(since) {
605            if (since) return consoleLogs.filter(function(l) { return l.timestamp >= since; });
606            return consoleLogs;
607        },
608
609        clearConsoleLogs: function() {
610            consoleLogs.length = 0;
611        },
612
613        // ── Mutations ────────────────────────────────────────────────────────
614
615        getMutationLog: function(since) {
616            if (since) return mutationLog.filter(function(m) { return m.timestamp >= since; });
617            return mutationLog;
618        },
619
620        clearMutationLog: function() {
621            mutationLog.length = 0;
622        },
623
624        // ── Network ──────────────────────────────────────────────────────────
625
626        getNetworkLog: function(filter, limit) {
627            var log = networkLog;
628            if (filter) {
629                log = log.filter(function(e) { return e.url.indexOf(filter) !== -1; });
630            }
631            if (limit) log = log.slice(-limit);
632            return log;
633        },
634
635        clearNetworkLog: function() {
636            networkLog.length = 0;
637        },
638
639        // ── Network routing (interception / mock / block / delay) ──────────────
640        // Add a route rule. `rule` is an object: { pattern, match_type, method,
641        // action ('block'|'fulfill'|'delay'), status, status_text, headers,
642        // body, content_type, delay_ms, times }. Returns the assigned id.
643        addRoute: function(rule) {
644            if (typeof rule === 'string') { try { rule = JSON.parse(rule); } catch (e) { return { ok: false, error: 'invalid rule JSON' }; } }
645            if (!rule || !rule.pattern) return { ok: false, error: 'route rule requires a pattern' };
646            var r = {
647                id: ++routeCounter,
648                pattern: String(rule.pattern),
649                match_type: rule.match_type || 'substring',
650                method: rule.method || null,
651                action: rule.action || 'fulfill',
652                status: typeof rule.status === 'number' ? rule.status : 200,
653                status_text: rule.status_text || '',
654                headers: rule.headers || {},
655                body: (rule.body === undefined || rule.body === null) ? '' : rule.body,
656                content_type: rule.content_type || 'application/json',
657                delay_ms: typeof rule.delay_ms === 'number' ? rule.delay_ms : 0,
658                times: typeof rule.times === 'number' ? rule.times : 0,
659                triggered: 0,
660            };
661            routeRules.push(r);
662            return { ok: true, id: r.id, rule: r };
663        },
664
665        getRouteRules: function() { return routeRules; },
666
667        clearRoute: function(id) {
668            var before = routeRules.length;
669            routeRules = routeRules.filter(function(r) { return r.id !== id; });
670            return { ok: true, removed: before - routeRules.length };
671        },
672
673        clearRoutes: function() {
674            var n = routeRules.length;
675            routeRules = [];
676            return { ok: true, removed: n };
677        },
678
679        getRouteMatches: function(limit) {
680            return limit ? routeMatchLog.slice(-limit) : routeMatchLog;
681        },
682
683        // ── Storage ──────────────────────────────────────────────────────────
684
685        getLocalStorage: function(key) {
686            if (key !== undefined && key !== null) {
687                var v = localStorage.getItem(key);
688                try { return JSON.parse(v); } catch(e) { return v; }
689            }
690            var obj = {};
691            for (var i = 0; i < localStorage.length; i++) {
692                var k = localStorage.key(i);
693                var val = localStorage.getItem(k);
694                try { obj[k] = JSON.parse(val); } catch(e) { obj[k] = val; }
695            }
696            return obj;
697        },
698
699        setLocalStorage: function(key, value) {
700            localStorage.setItem(key, typeof value === 'string' ? value : JSON.stringify(value));
701            return { ok: true };
702        },
703
704        deleteLocalStorage: function(key) {
705            localStorage.removeItem(key);
706            return { ok: true };
707        },
708
709        getSessionStorage: function(key) {
710            if (key !== undefined && key !== null) {
711                var v = sessionStorage.getItem(key);
712                try { return JSON.parse(v); } catch(e) { return v; }
713            }
714            var obj = {};
715            for (var i = 0; i < sessionStorage.length; i++) {
716                var k = sessionStorage.key(i);
717                var val = sessionStorage.getItem(k);
718                try { obj[k] = JSON.parse(val); } catch(e) { obj[k] = val; }
719            }
720            return obj;
721        },
722
723        setSessionStorage: function(key, value) {
724            sessionStorage.setItem(key, typeof value === 'string' ? value : JSON.stringify(value));
725            return { ok: true };
726        },
727
728        deleteSessionStorage: function(key) {
729            sessionStorage.removeItem(key);
730            return { ok: true };
731        },
732
733        getCookies: function() {
734            if (!document.cookie) return [];
735            return document.cookie.split(';').map(function(c) {
736                var parts = c.trim().split('=');
737                return { name: parts[0], value: parts.slice(1).join('=') };
738            });
739        },
740
741        // ── Navigation ───────────────────────────────────────────────────────
742
743        getNavigationLog: function() {
744            return navigationLog;
745        },
746
747        navigate: function(url) {
748            window.location.href = url;
749            return { ok: true };
750        },
751
752        navigateBack: function() {
753            history.back();
754            return { ok: true };
755        },
756
757        // ── Dialogs ──────────────────────────────────────────────────────────
758
759        getDialogLog: function() {
760            return dialogLog;
761        },
762
763        clearDialogLog: function() {
764            dialogLog.length = 0;
765        },
766
767        setDialogAutoResponse: function(type, action, text) {
768            dialogAutoResponses[type] = { action: action, text: text };
769            return { ok: true };
770        },
771
772        // ── Combined Event Stream ────────────────────────────────────────────
773
774        getEventStream: function(since) {
775            var events = [];
776            var ts = since || 0;
777
778            consoleLogs.forEach(function(l) {
779                if (l.timestamp >= ts) {
780                    events.push({ type: 'console', level: l.level, message: l.message, timestamp: l.timestamp });
781                }
782            });
783
784            mutationLog.forEach(function(m) {
785                if (m.timestamp >= ts) {
786                    events.push({ type: 'dom_mutation', count: m.count, timestamp: m.timestamp });
787                }
788            });
789
790            var ipcPrefix = 'http://ipc.localhost/';
791            var victauriPrefix = 'plugin%3Avictauri%7C';
792            networkLog.forEach(function(n) {
793                if (n.timestamp >= ts && n.url.indexOf(ipcPrefix) === 0) {
794                    var raw = n.url.substring(ipcPrefix.length);
795                    if (raw.indexOf(victauriPrefix) === 0) return;
796                    var cmd; try { cmd = decodeURIComponent(raw); } catch(e) { cmd = raw; }
797                    events.push({ type: 'ipc', command: cmd, status: n.status === 200 ? 'ok' : (n.status === 'pending' ? 'pending' : 'error'), duration_ms: n.duration_ms, timestamp: n.timestamp });
798                }
799            });
800
801            networkLog.forEach(function(n) {
802                if (n.timestamp >= ts) {
803                    events.push({ type: 'network', method: n.method, url: n.url, status: n.status, duration_ms: n.duration_ms, timestamp: n.timestamp });
804                }
805            });
806
807            navigationLog.forEach(function(n) {
808                if (n.timestamp >= ts) {
809                    events.push({ type: 'navigation', url: n.url, nav_type: n.type, timestamp: n.timestamp });
810                }
811            });
812
813            interactionLog.forEach(function(i) {
814                if (i.timestamp >= ts) {
815                    events.push({ type: 'dom_interaction', action: i.action, selector: i.selector, value: i.value, timestamp: i.timestamp });
816                }
817            });
818
819            events.sort(function(a, b) { return a.timestamp - b.timestamp; });
820            return events;
821        },
822
823        // ── Wait ─────────────────────────────────────────────────────────────
824
825        waitFor: function(opts) {
826            return new Promise(function(resolve) {
827                var timeout = opts.timeout_ms || 10000;
828                var poll = opts.poll_ms || 200;
829                var start = Date.now();
830
831                function check() {
832                    var elapsed = Date.now() - start;
833                    if (elapsed >= timeout) {
834                        resolve({ ok: false, error: 'timeout after ' + timeout + 'ms', elapsed_ms: elapsed });
835                        return;
836                    }
837
838                    function getFullText(root) {
839                        var text = root.innerText || '';
840                        var els = root.querySelectorAll('*');
841                        for (var j = 0; j < els.length; j++) {
842                            if (els[j].shadowRoot) text += ' ' + getFullText(els[j].shadowRoot);
843                        }
844                        return text;
845                    }
846                    var met = false;
847                    if (opts.condition === 'text' && opts.value) {
848                        met = getFullText(document.body).indexOf(opts.value) !== -1;
849                    } else if (opts.condition === 'text_gone' && opts.value) {
850                        met = getFullText(document.body).indexOf(opts.value) === -1;
851                    } else if (opts.condition === 'selector' && opts.value) {
852                        met = !!document.querySelector(opts.value);
853                    } else if (opts.condition === 'selector_gone' && opts.value) {
854                        met = !document.querySelector(opts.value);
855                    } else if (opts.condition === 'url' && opts.value) {
856                        met = window.location.href.indexOf(opts.value) !== -1;
857                    } else if (opts.condition === 'ipc_idle') {
858                        met = networkLog.filter(function(n) { return n.url.indexOf('http://ipc.localhost/') === 0; }).every(function(n) { return n.status !== 'pending'; });
859                    } else if (opts.condition === 'network_idle') {
860                        met = networkLog.every(function(n) { return n.status !== 'pending'; });
861                    }
862
863                    if (met) {
864                        resolve({ ok: true, elapsed_ms: Date.now() - start });
865                    } else {
866                        setTimeout(check, poll);
867                    }
868                }
869                check();
870            });
871        },
872        // ── CSS / Style Introspection ────────────────────────────────────────
873
874        getStyles: function(refId, properties) {
875            var el = resolveRef(refId);
876            if (!el) return { error: 'ref not found: ' + refId };
877            var computed = window.getComputedStyle(el);
878            var result = {};
879            if (properties && properties.length > 0) {
880                for (var i = 0; i < properties.length; i++) {
881                    result[properties[i]] = computed.getPropertyValue(properties[i]);
882                }
883            } else {
884                var important = ['display','position','width','height','margin','padding',
885                    'color','background-color','font-size','font-family','font-weight',
886                    'border','border-radius','opacity','visibility','overflow','z-index',
887                    'flex-direction','justify-content','align-items','gap','grid-template-columns',
888                    'box-shadow','transform','transition','cursor','pointer-events','text-align',
889                    'line-height','letter-spacing','white-space','text-overflow','max-width',
890                    'max-height','min-width','min-height','top','right','bottom','left'];
891                // Interactivity-critical props are always shown (when non-empty),
892                // even at 'none'/'hidden'/'auto' — `display:none`,
893                // `visibility:hidden`, and `pointer-events:none` are exactly the
894                // "why can't I interact with this?" answers, and the compactness
895                // filter below would otherwise drop them as if they were defaults.
896                var alwaysShow = ['display', 'visibility', 'pointer-events'];
897                for (var i = 0; i < important.length; i++) {
898                    var v = computed.getPropertyValue(important[i]);
899                    var critical = alwaysShow.indexOf(important[i]) !== -1;
900                    if (v && v !== '' && (critical
901                        || (v !== 'none' && v !== 'normal' && v !== 'auto'
902                            && v !== '0px' && v !== 'rgba(0, 0, 0, 0)'))) {
903                        result[important[i]] = v;
904                    }
905                }
906            }
907            return { ref_id: refId, tag: el.tagName.toLowerCase(), styles: result };
908        },
909
910        getBoundingBoxes: function(refIds) {
911            var results = [];
912            for (var i = 0; i < refIds.length; i++) {
913                var el = resolveRef(refIds[i]);
914                if (!el) { results.push({ ref_id: refIds[i], error: 'ref not found' }); continue; }
915                var rect = el.getBoundingClientRect();
916                var computed = window.getComputedStyle(el);
917                results.push({
918                    ref_id: refIds[i],
919                    tag: el.tagName.toLowerCase(),
920                    x: Math.round(rect.x),
921                    y: Math.round(rect.y),
922                    width: Math.round(rect.width),
923                    height: Math.round(rect.height),
924                    margin: {
925                        top: parseInt(computed.marginTop) || 0,
926                        right: parseInt(computed.marginRight) || 0,
927                        bottom: parseInt(computed.marginBottom) || 0,
928                        left: parseInt(computed.marginLeft) || 0,
929                    },
930                    padding: {
931                        top: parseInt(computed.paddingTop) || 0,
932                        right: parseInt(computed.paddingRight) || 0,
933                        bottom: parseInt(computed.paddingBottom) || 0,
934                        left: parseInt(computed.paddingLeft) || 0,
935                    },
936                    border: {
937                        top: parseInt(computed.borderTopWidth) || 0,
938                        right: parseInt(computed.borderRightWidth) || 0,
939                        bottom: parseInt(computed.borderBottomWidth) || 0,
940                        left: parseInt(computed.borderLeftWidth) || 0,
941                    },
942                });
943            }
944            return results;
945        },
946
947        // ── Visual Debug Overlays ────────────────────────────────────────────
948
949        highlightElement: function(refId, color, label) {
950            var el = resolveRef(refId);
951            if (!el) return { error: 'ref not found: ' + refId };
952            var c = color || 'rgba(255, 0, 0, 0.3)';
953            var overlay = document.createElement('div');
954            overlay.className = '__victauri_highlight__';
955            overlay.setAttribute('data-victauri-ref', refId);
956            var rect = el.getBoundingClientRect();
957            overlay.style.cssText = 'position:fixed;pointer-events:none;z-index:2147483647;' +
958                'border:2px solid ' + c + ';background:' + c + ';' +
959                'left:' + rect.left + 'px;top:' + rect.top + 'px;' +
960                'width:' + rect.width + 'px;height:' + rect.height + 'px;' +
961                'transition:all 0.2s ease;';
962            if (label) {
963                var tag = document.createElement('span');
964                tag.textContent = label;
965                tag.style.cssText = 'position:absolute;top:-20px;left:0;background:#222;color:#fff;' +
966                    'font-size:11px;padding:2px 6px;border-radius:3px;white-space:nowrap;font-family:monospace;';
967                overlay.appendChild(tag);
968            }
969            document.body.appendChild(overlay);
970            return { ok: true, ref_id: refId };
971        },
972
973        clearHighlights: function() {
974            var overlays = document.querySelectorAll('.__victauri_highlight__');
975            for (var i = 0; i < overlays.length; i++) overlays[i].remove();
976            return { ok: true, removed: overlays.length };
977        },
978
979        // ── CSS Injection ────────────────────────────────────────────────────
980
981        injectCss: function(css) {
982            var existing = document.getElementById('__victauri_injected_css__');
983            if (existing) existing.remove();
984            var style = document.createElement('style');
985            style.id = '__victauri_injected_css__';
986            style.textContent = css;
987            document.head.appendChild(style);
988            return { ok: true, length: css.length };
989        },
990
991        removeInjectedCss: function() {
992            var existing = document.getElementById('__victauri_injected_css__');
993            if (!existing) return { ok: true, removed: false };
994            existing.remove();
995            return { ok: true, removed: true };
996        },
997
998        // ── Accessibility Audit ──────────────────────────────────────────────
999
1000        auditAccessibility: function() {
1001            var violations = [];
1002            var warnings = [];
1003
1004            // Images without alt text
1005            var imgs = document.querySelectorAll('img');
1006            for (var i = 0; i < imgs.length; i++) {
1007                if (!imgs[i].hasAttribute('alt')) {
1008                    violations.push({ rule: 'img-alt', severity: 'critical', element: describeEl(imgs[i]),
1009                        message: 'Image missing alt attribute' });
1010                } else if (imgs[i].alt.trim() === '') {
1011                    warnings.push({ rule: 'img-alt-empty', severity: 'minor', element: describeEl(imgs[i]),
1012                        message: 'Image has empty alt (ok if decorative)' });
1013                }
1014            }
1015
1016            // Form inputs without labels
1017            var inputs = document.querySelectorAll('input, select, textarea');
1018            for (var i = 0; i < inputs.length; i++) {
1019                var inp = inputs[i];
1020                if (inp.type === 'hidden') continue;
1021                var hasLabel = false;
1022                if (inp.id) {
1023                    try { hasLabel = !!document.querySelector('label[for=\"' + CSS.escape(inp.id) + '\"]'); }
1024                    catch(e) { /* malformed id — skip */ }
1025                }
1026                var hasAria = inp.getAttribute('aria-label') || inp.getAttribute('aria-labelledby');
1027                var hasTitle = inp.title;
1028                var hasPlaceholder = inp.placeholder;
1029                if (!hasLabel && !hasAria && !hasTitle && !hasPlaceholder) {
1030                    violations.push({ rule: 'input-label', severity: 'serious', element: describeEl(inp),
1031                        message: 'Form input has no accessible label' });
1032                }
1033            }
1034
1035            // Buttons without accessible text
1036            var buttons = document.querySelectorAll('button, [role="button"]');
1037            for (var i = 0; i < buttons.length; i++) {
1038                var btn = buttons[i];
1039                var text = (btn.textContent || '').trim();
1040                var ariaLabel = btn.getAttribute('aria-label');
1041                var ariaLabelledBy = btn.getAttribute('aria-labelledby');
1042                if (!text && !ariaLabel && !ariaLabelledBy && !btn.title) {
1043                    var hasImg = btn.querySelector('img[alt], svg[aria-label]');
1044                    if (!hasImg) {
1045                        violations.push({ rule: 'button-name', severity: 'serious', element: describeEl(btn),
1046                            message: 'Button has no accessible name' });
1047                    }
1048                }
1049            }
1050
1051            // Links without text
1052            var links = document.querySelectorAll('a[href]');
1053            for (var i = 0; i < links.length; i++) {
1054                var link = links[i];
1055                var text = (link.textContent || '').trim();
1056                var ariaLabel = link.getAttribute('aria-label');
1057                if (!text && !ariaLabel && !link.title) {
1058                    violations.push({ rule: 'link-name', severity: 'serious', element: describeEl(link),
1059                        message: 'Link has no accessible text' });
1060                }
1061            }
1062
1063            // Missing document language
1064            if (!document.documentElement.lang) {
1065                violations.push({ rule: 'html-lang', severity: 'serious', element: '<html>',
1066                    message: 'Document missing lang attribute' });
1067            }
1068
1069            // Heading hierarchy
1070            var headings = document.querySelectorAll('h1, h2, h3, h4, h5, h6');
1071            var prevLevel = 0;
1072            for (var i = 0; i < headings.length; i++) {
1073                var level = parseInt(headings[i].tagName.charAt(1));
1074                if (level > prevLevel + 1 && prevLevel > 0) {
1075                    warnings.push({ rule: 'heading-order', severity: 'moderate', element: describeEl(headings[i]),
1076                        message: 'Heading level skipped from h' + prevLevel + ' to h' + level });
1077                }
1078                prevLevel = level;
1079            }
1080
1081            // Missing page title
1082            if (!document.title || document.title.trim() === '') {
1083                violations.push({ rule: 'document-title', severity: 'serious', element: '<head>',
1084                    message: 'Document has no title' });
1085            }
1086
1087            // Color contrast (simplified — checks text elements against backgrounds)
1088            var textEls = document.querySelectorAll('p, span, a, button, h1, h2, h3, h4, h5, h6, li, td, th, label, div');
1089            var contrastIssues = 0;
1090            for (var i = 0; i < textEls.length && contrastIssues < 10; i++) {
1091                var el = textEls[i];
1092                if (!el.textContent || el.textContent.trim() === '') continue;
1093                if (el.children.length > 0 && el.children[0].textContent === el.textContent) continue;
1094                var cs = window.getComputedStyle(el);
1095                var fg = parseColor(cs.color);
1096                var bg = parseColor(cs.backgroundColor);
1097                if (fg && bg && bg.a > 0) {
1098                    var ratio = contrastRatio(fg, bg);
1099                    var fontSize = parseFloat(cs.fontSize);
1100                    var isBold = parseInt(cs.fontWeight) >= 700;
1101                    var isLarge = fontSize >= 24 || (fontSize >= 18.66 && isBold);
1102                    var threshold = isLarge ? 3 : 4.5;
1103                    if (ratio < threshold) {
1104                        contrastIssues++;
1105                        warnings.push({ rule: 'color-contrast', severity: 'serious',
1106                            element: describeEl(el),
1107                            message: 'Contrast ratio ' + ratio.toFixed(2) + ':1 (needs ' + threshold + ':1)',
1108                            details: { fg: cs.color, bg: cs.backgroundColor, ratio: ratio.toFixed(2) } });
1109                    }
1110                }
1111            }
1112
1113            // ARIA role validity
1114            var ariaEls = document.querySelectorAll('[role]');
1115            var validRoles = new Set(['alert','alertdialog','application','article','banner','button',
1116                'cell','checkbox','columnheader','combobox','complementary','contentinfo','definition',
1117                'dialog','directory','document','feed','figure','form','grid','gridcell','group',
1118                'heading','img','link','list','listbox','listitem','log','main','marquee','math',
1119                'menu','menubar','menuitem','menuitemcheckbox','menuitemradio','meter','navigation',
1120                'none','note','option','presentation','progressbar','radio','radiogroup','region',
1121                'row','rowgroup','rowheader','scrollbar','search','searchbox','separator','slider',
1122                'spinbutton','status','switch','tab','table','tablist','tabpanel','term','textbox',
1123                'timer','toolbar','tooltip','tree','treegrid','treeitem']);
1124            for (var i = 0; i < ariaEls.length; i++) {
1125                var role = ariaEls[i].getAttribute('role');
1126                if (role && !validRoles.has(role)) {
1127                    warnings.push({ rule: 'aria-role', severity: 'moderate', element: describeEl(ariaEls[i]),
1128                        message: 'Invalid ARIA role: ' + role });
1129                }
1130            }
1131
1132            // Tab index > 0
1133            var tabbable = document.querySelectorAll('[tabindex]');
1134            for (var i = 0; i < tabbable.length; i++) {
1135                var ti = parseInt(tabbable[i].getAttribute('tabindex'));
1136                if (ti > 0) {
1137                    warnings.push({ rule: 'tabindex-positive', severity: 'moderate', element: describeEl(tabbable[i]),
1138                        message: 'Positive tabindex disrupts natural tab order (tabindex=' + ti + ')' });
1139                }
1140            }
1141
1142            return {
1143                violations: violations,
1144                warnings: warnings,
1145                summary: {
1146                    critical: violations.filter(function(v) { return v.severity === 'critical'; }).length,
1147                    serious: violations.filter(function(v) { return v.severity === 'serious'; }).length + warnings.filter(function(w) { return w.severity === 'serious'; }).length,
1148                    moderate: warnings.filter(function(w) { return w.severity === 'moderate'; }).length,
1149                    minor: warnings.filter(function(w) { return w.severity === 'minor'; }).length,
1150                    total: violations.length + warnings.length,
1151                }
1152            };
1153        },
1154
1155        // ── Performance Metrics ──────────────────────────────────────────────
1156
1157        getPerformanceMetrics: function() {
1158            var result = {};
1159
1160            // Navigation timing
1161            var nav = performance.getEntriesByType('navigation')[0];
1162            if (nav) {
1163                result.navigation = {
1164                    dns_ms: Math.round(nav.domainLookupEnd - nav.domainLookupStart),
1165                    connect_ms: Math.round(nav.connectEnd - nav.connectStart),
1166                    ttfb_ms: Math.round(nav.responseStart - nav.requestStart),
1167                    response_ms: Math.round(nav.responseEnd - nav.responseStart),
1168                    dom_interactive_ms: Math.round(nav.domInteractive - nav.startTime),
1169                    dom_complete_ms: Math.round(nav.domComplete - nav.startTime),
1170                    load_event_ms: Math.round(nav.loadEventEnd - nav.startTime),
1171                    transfer_size: nav.transferSize,
1172                    encoded_body_size: nav.encodedBodySize,
1173                    decoded_body_size: nav.decodedBodySize,
1174                };
1175            }
1176
1177            // Resource summary
1178            var resources = performance.getEntriesByType('resource');
1179            var byType = {};
1180            var totalTransfer = 0;
1181            for (var i = 0; i < resources.length; i++) {
1182                var r = resources[i];
1183                var type = r.initiatorType || 'other';
1184                if (!byType[type]) byType[type] = { count: 0, total_ms: 0, total_bytes: 0 };
1185                byType[type].count++;
1186                byType[type].total_ms += r.duration;
1187                byType[type].total_bytes += r.transferSize || 0;
1188                totalTransfer += r.transferSize || 0;
1189            }
1190            result.resources = {
1191                total_count: resources.length,
1192                total_transfer_bytes: totalTransfer,
1193                by_type: byType,
1194                slowest: resources.sort(function(a, b) { return b.duration - a.duration; }).slice(0, 5).map(function(r) {
1195                    return { name: r.name.split('/').pop().split('?')[0], duration_ms: Math.round(r.duration), size: r.transferSize || 0, type: r.initiatorType };
1196                }),
1197            };
1198
1199            // Paint timing
1200            var paints = performance.getEntriesByType('paint');
1201            result.paint = {};
1202            for (var i = 0; i < paints.length; i++) {
1203                result.paint[paints[i].name] = Math.round(paints[i].startTime);
1204            }
1205
1206            // Memory (Chrome/Edge)
1207            if (performance.memory) {
1208                result.js_heap = {
1209                    used_mb: Math.round(performance.memory.usedJSHeapSize / 1048576 * 100) / 100,
1210                    total_mb: Math.round(performance.memory.totalJSHeapSize / 1048576 * 100) / 100,
1211                    limit_mb: Math.round(performance.memory.jsHeapSizeLimit / 1048576 * 100) / 100,
1212                };
1213            }
1214
1215            // Long tasks (if PerformanceObserver captured any)
1216            if (longTasks.length > 0) {
1217                result.long_tasks = {
1218                    count: longTasks.length,
1219                    total_ms: Math.round(longTasks.reduce(function(s, t) { return s + t.duration; }, 0)),
1220                    worst_ms: Math.round(Math.max.apply(null, longTasks.map(function(t) { return t.duration; }))),
1221                };
1222            }
1223
1224            // DOM stats
1225            result.dom = {
1226                elements: document.querySelectorAll('*').length,
1227                max_depth: (function() { var d = 0; var walk = function(el, depth) { if (depth > d) d = depth; for (var i = 0; i < el.children.length && i < 5; i++) walk(el.children[i], depth + 1); }; walk(document.body, 0); return d; })(),
1228                event_listeners: listenerCount,
1229            };
1230
1231            return result;
1232        },
1233
1234        getDiagnostics: function() {
1235            var diag = { warnings: [], info: {} };
1236
1237            // Service worker detection
1238            if (navigator.serviceWorker && navigator.serviceWorker.controller) {
1239                diag.warnings.push({
1240                    id: 'service-worker-active',
1241                    severity: 'high',
1242                    message: 'Active service worker detected — may intercept fetch calls to ipc.localhost, causing IPC log gaps',
1243                    details: { scope: navigator.serviceWorker.controller.scriptURL }
1244                });
1245            }
1246
1247            // Closed shadow DOM detection
1248            var allEls = document.querySelectorAll('*');
1249            var closedShadowCount = 0;
1250            for (var i = 0; i < allEls.length; i++) {
1251                if (allEls[i].attachShadow && !allEls[i].shadowRoot) {
1252                    var tagName = allEls[i].tagName.toLowerCase();
1253                    if (tagName.includes('-')) closedShadowCount++;
1254                }
1255            }
1256            if (closedShadowCount > 0) {
1257                diag.warnings.push({
1258                    id: 'closed-shadow-dom',
1259                    severity: 'medium',
1260                    message: closedShadowCount + ' custom element(s) may use closed shadow DOM — their contents are invisible to dom_snapshot',
1261                    details: { count: closedShadowCount }
1262                });
1263            }
1264
1265            // iframe detection
1266            var iframes = document.querySelectorAll('iframe');
1267            if (iframes.length > 0) {
1268                diag.warnings.push({
1269                    id: 'iframes-present',
1270                    severity: 'medium',
1271                    message: iframes.length + ' iframe(s) found — Victauri bridge is not injected inside iframes (Tauri limitation)',
1272                    details: { count: iframes.length, srcs: Array.from(iframes).slice(0, 5).map(function(f) { return f.src || '(empty)'; }) }
1273                });
1274            }
1275
1276            // DOM size warning
1277            var elementCount = allEls.length;
1278            if (elementCount > 5000) {
1279                diag.warnings.push({
1280                    id: 'large-dom',
1281                    severity: 'low',
1282                    message: 'DOM has ' + elementCount + ' elements — dom_snapshot may be slow (>100ms)',
1283                    details: { count: elementCount }
1284                });
1285            }
1286
1287            // CSP detection (best-effort)
1288            var cspMeta = document.querySelector('meta[http-equiv="Content-Security-Policy"]');
1289            if (cspMeta) {
1290                var cspContent = cspMeta.getAttribute('content') || '';
1291                diag.info.csp_meta = cspContent;
1292                if (cspContent.indexOf('unsafe-eval') === -1 && cspContent.indexOf('script-src') !== -1) {
1293                    diag.info.csp_note = 'CSP restricts eval — Victauri uses native webview.eval() which bypasses CSP on most platforms';
1294                }
1295            }
1296
1297            // Environment info
1298            diag.info.bridge_version = window.__VICTAURI__.version;
1299            diag.info.user_agent = navigator.userAgent;
1300            diag.info.url = window.location.href;
1301            diag.info.dom_elements = elementCount;
1302            diag.info.open_shadow_roots = (function() { var c = 0; for (var i = 0; i < allEls.length; i++) { if (allEls[i].shadowRoot) c++; } return c; })();
1303            diag.info.event_listeners = listenerCount;
1304            diag.info.protocol = window.location.protocol;
1305
1306            return diag;
1307        },
1308
1309        // ── Animation Introspection (Web Animations API) ─────────────────────
1310        // Reads the running CSS animations/transitions so an agent can see what
1311        // the webview's animation engine is actually doing: declared timing,
1312        // easing, keyframes, current progress, and the animating element. Pure
1313        // standard DOM — works identically on WebView2/WKWebView/WebKitGTK.
1314        listAnimations: function(selector) {
1315            function rect(el) {
1316                if (!el || !el.getBoundingClientRect) return null;
1317                var b = el.getBoundingClientRect();
1318                return { x: Math.round(b.x), y: Math.round(b.y),
1319                         w: Math.round(b.width), h: Math.round(b.height) };
1320            }
1321            function describe(el) {
1322                if (!el) return null;
1323                var cls = (el.className && el.className.toString)
1324                    ? el.className.toString().substring(0, 60) : null;
1325                return { tag: el.tagName ? el.tagName.toLowerCase() : null,
1326                         id: el.id || null, cls: cls, rect: rect(el) };
1327            }
1328            var anims;
1329            try {
1330                if (selector) {
1331                    var scope = document.querySelectorAll(selector);
1332                    anims = [];
1333                    for (var i = 0; i < scope.length; i++) {
1334                        if (scope[i].getAnimations) {
1335                            anims = anims.concat(scope[i].getAnimations());
1336                        }
1337                    }
1338                } else {
1339                    anims = document.getAnimations ? document.getAnimations() : [];
1340                }
1341            } catch (e) {
1342                return { error: 'getAnimations failed: ' + (e && e.message) };
1343            }
1344            return anims.map(function(a) {
1345                var e = a.effect;
1346                var t = (e && e.getTiming) ? e.getTiming() : {};
1347                var ct = (e && e.getComputedTiming) ? e.getComputedTiming() : {};
1348                var kf = [];
1349                try { kf = (e && e.getKeyframes) ? e.getKeyframes() : []; } catch (_) {}
1350                return {
1351                    type: a.constructor ? a.constructor.name : 'Animation',
1352                    id: a.id || null,
1353                    animation_name: a.animationName || null,
1354                    transition_property: a.transitionProperty || null,
1355                    play_state: a.playState,
1356                    current_time: a.currentTime,
1357                    playback_rate: a.playbackRate,
1358                    timing: { duration: t.duration, delay: t.delay, end_delay: t.endDelay,
1359                              easing: t.easing, iterations: t.iterations,
1360                              direction: t.direction, fill: t.fill },
1361                    computed: { active_duration: ct.activeDuration, end_time: ct.endTime,
1362                                progress: ct.progress, current_iteration: ct.currentIteration },
1363                    target: describe(e && e.target),
1364                    keyframes: kf
1365                };
1366            });
1367        },
1368
1369        // ── Deterministic animation scrubbing ────────────────────────────────
1370        // Pause the target's WAAPI animations and hold state across calls so the
1371        // Rust side can seek to evenly-spaced progress points and capture a
1372        // jank-free frame at each. The paused+seeked frame is frozen, so the
1373        // (slow) native screenshot has nothing to race — this is why scrubbing
1374        // beats real-time capture for fast animations.
1375        scrubPrepare: function(selector) {
1376            var el = selector ? document.querySelector(selector) : null;
1377            if (!el) {
1378                var all = document.getAnimations ? document.getAnimations() : [];
1379                for (var i = 0; i < all.length; i++) {
1380                    if (all[i].effect && all[i].effect.target) { el = all[i].effect.target; break; }
1381                }
1382            }
1383            if (!el) {
1384                return Promise.resolve({ error: 'no target: selector matched nothing and no '
1385                    + 'animation is currently running. Trigger the animation, then scrub.',
1386                    anim_count: 0 });
1387            }
1388            var anims = (el.getAnimations ? el.getAnimations() : []).filter(function(a) {
1389                var ct = (a.effect && a.effect.getComputedTiming) ? a.effect.getComputedTiming() : null;
1390                return ct && isFinite(ct.endTime) && ct.endTime > 0;
1391            });
1392            if (!anims.length) {
1393                return Promise.resolve({ error: 'no seekable WAAPI animation on target — it may '
1394                    + 'be JS/requestAnimationFrame-driven (not seekable). Use animation sample '
1395                    + 'instead.', anim_count: 0 });
1396            }
1397            var ends = anims.map(function(a) { return a.effect.getComputedTiming().endTime; });
1398            var duration = Math.max.apply(null, ends);
1399            anims.forEach(function(a) { try { a.pause(); } catch (e) {} });
1400            window.__VICTAURI_SCRUB__ = { el: el, anims: anims, ends: ends, duration: duration };
1401            return Promise.all(anims.map(function(a) { return a.ready.catch(function(){}); }))
1402                .then(function() {
1403                    var b = el.getBoundingClientRect();
1404                    return { prepared: true, anim_count: anims.length, duration: duration,
1405                        target: { tag: el.tagName.toLowerCase(), id: el.id || null,
1406                            rect: { x: Math.round(b.x), y: Math.round(b.y),
1407                                    w: Math.round(b.width), h: Math.round(b.height) } } };
1408                });
1409        },
1410
1411        scrubSeek: function(progress) {
1412            var S = window.__VICTAURI_SCRUB__;
1413            if (!S) return Promise.resolve({ error: 'not prepared — scrubPrepare first' });
1414            var t = progress * S.duration;
1415            for (var i = 0; i < S.anims.length; i++) {
1416                try { S.anims[i].currentTime = Math.max(0, Math.min(t, S.ends[i])); } catch (e) {}
1417            }
1418            return Promise.all(S.anims.map(function(a) { return a.ready.catch(function(){}); }))
1419                .then(function() {
1420                    return new Promise(function(res) {
1421                        requestAnimationFrame(function() { requestAnimationFrame(res); });
1422                    });
1423                })
1424                .then(function() {
1425                    var el = S.el, b = el.getBoundingClientRect(), cs = window.getComputedStyle(el);
1426                    var tf = (function(s) {
1427                        if (!s || s.indexOf('matrix') !== 0) return { tx: 0, ty: 0, sx: 1, sy: 1 };
1428                        var m = s.match(/-?[\d.eE+]+/g);
1429                        if (!m) return { tx: 0, ty: 0, sx: 1, sy: 1 };
1430                        m = m.map(Number);
1431                        return m.length === 6
1432                            ? { tx: m[4], ty: m[5], sx: m[0], sy: m[3] }
1433                            : { tx: m[12], ty: m[13], sx: m[0], sy: m[5] };
1434                    })(cs.transform);
1435                    var r2 = function(n) { return Math.round(n * 100) / 100; };
1436                    return { progress: progress, t: r2(t),
1437                        rect: { x: r2(b.x), y: r2(b.y), w: Math.round(b.width), h: Math.round(b.height) },
1438                        transform: { tx: r2(tf.tx), ty: r2(tf.ty), sx: tf.sx, sy: tf.sy },
1439                        opacity: parseFloat(cs.opacity) };
1440                });
1441        },
1442
1443        scrubRestore: function(resume) {
1444            var S = window.__VICTAURI_SCRUB__;
1445            if (!S) return { restored: false };
1446            S.anims.forEach(function(a) { try { if (resume) a.play(); } catch (e) {} });
1447            window.__VICTAURI_SCRUB__ = null;
1448            return { restored: true, resumed: !!resume };
1449        },
1450
1451        // ── Real-time motion + jank recorder ─────────────────────────────────
1452        // Arm a requestAnimationFrame watcher that samples the target's geometry
1453        // every frame while it animates. Decoupled from the (blocking) eval call
1454        // so event-triggered sweeps are catchable: arm it, trigger the sweep,
1455        // then read back the measured curve + dropped-frame (jank) stats.
1456        installSweepRecorder: function(selector) {
1457            var R = (window.__VICTAURI_SWEEP__ = { sel: selector || null,
1458                sessions: [], cur: null });
1459            var matrix = function(el) {
1460                var s = getComputedStyle(el).transform;
1461                if (!s || s.indexOf('matrix') !== 0) return { tx: 0, ty: 0, sx: 1 };
1462                var m = s.match(/-?[\d.eE+]+/g);
1463                if (!m) return { tx: 0, ty: 0, sx: 1 };
1464                m = m.map(Number);
1465                return m.length === 6 ? { tx: m[4], ty: m[5], sx: m[0] }
1466                                      : { tx: m[12], ty: m[13], sx: m[0] };
1467            };
1468            var pick = function() {
1469                if (R.sel) return document.querySelector(R.sel);
1470                var list = document.getAnimations ? document.getAnimations() : [];
1471                for (var i = 0; i < list.length; i++) {
1472                    if (list[i].playState === 'running' && list[i].effect && list[i].effect.target) {
1473                        return list[i].effect.target;
1474                    }
1475                }
1476                return null;
1477            };
1478            var tick = function() {
1479                // Stop if a newer recorder superseded this one.
1480                if (window.__VICTAURI_SWEEP__ !== R) return;
1481                var el = pick();
1482                var anims = (el && el.getAnimations) ? el.getAnimations() : [];
1483                var running = anims.some(function(a) { return a.playState === 'running'; });
1484                if (running && !R.cur) {
1485                    var e = anims[0] && anims[0].effect;
1486                    R.cur = { t0: performance.now(), samples: [],
1487                        timing: (e && e.getTiming) ? e.getTiming() : {},
1488                        keyframes: (function() {
1489                            try { return (e && e.getKeyframes) ? e.getKeyframes() : []; }
1490                            catch (_) { return []; }
1491                        })() };
1492                }
1493                if (R.cur && el) {
1494                    var b = el.getBoundingClientRect(), tf = matrix(el);
1495                    R.cur.samples.push({ t: performance.now() - R.cur.t0,
1496                        x: b.x, y: b.y, w: b.width, h: b.height,
1497                        tx: tf.tx, ty: tf.ty, sx: tf.sx,
1498                        opacity: parseFloat(getComputedStyle(el).opacity) });
1499                    if (R.cur.samples.length > 2000) R.cur.samples.shift();
1500                    if (!running) {
1501                        R.sessions.push(R.cur);
1502                        if (R.sessions.length > 10) R.sessions.shift();
1503                        R.cur = null;
1504                    }
1505                }
1506                requestAnimationFrame(tick);
1507            };
1508            requestAnimationFrame(tick);
1509            return { installed: true, selector: R.sel };
1510        },
1511
1512        readSweep: function(clear) {
1513            var R = window.__VICTAURI_SWEEP__;
1514            if (!R) {
1515                return { error: 'no recorder armed — call sample with record=true first, then '
1516                    + 'trigger the animation' };
1517            }
1518            var r2 = function(n) { return Math.round(n * 100) / 100; };
1519            var out = R.sessions.map(function(s) {
1520                var f = s.samples, gaps = [];
1521                for (var i = 1; i < f.length; i++) gaps.push(f[i].t - f[i - 1].t);
1522                var jank = gaps.filter(function(g) { return g > 25; }).length;
1523                var maxGap = gaps.length ? Math.max.apply(null, gaps) : 0;
1524                return {
1525                    measured_duration_ms: f.length ? r2(f[f.length - 1].t) : 0,
1526                    declared: { duration: s.timing.duration, easing: s.timing.easing,
1527                                delay: s.timing.delay },
1528                    frames: f.length, jank_frames: jank, max_frame_gap_ms: r2(maxGap),
1529                    start: f.length ? { x: r2(f[0].x), tx: r2(f[0].tx), opacity: f[0].opacity } : null,
1530                    end: f.length ? { x: r2(f[f.length - 1].x), tx: r2(f[f.length - 1].tx),
1531                                      opacity: f[f.length - 1].opacity } : null,
1532                    keyframes: s.keyframes,
1533                    curve: f.map(function(p) {
1534                        return { t: r2(p.t), x: r2(p.x), tx: r2(p.tx), op: p.opacity };
1535                    })
1536                };
1537            });
1538            var active = !!R.cur;
1539            if (clear) R.sessions = [];
1540            return { armed: true, selector: R.sel, recording_active: active,
1541                     session_count: out.length, sessions: out };
1542        },
1543    };
1544
1545    try {
1546        Object.freeze(window.__VICTAURI__);
1547        Object.defineProperty(window, '__VICTAURI__', {
1548            value: window.__VICTAURI__,
1549            configurable: false,
1550            writable: false,
1551        });
1552    } catch(e) {}
1553
1554    // ── Accessibility Helpers ────────────────────────────────────────────────
1555
1556    function describeEl(el) {
1557        var s = '<' + el.tagName.toLowerCase();
1558        if (el.id) s += ' id="' + el.id + '"';
1559        if (el.className && typeof el.className === 'string') {
1560            var cls = el.className.trim();
1561            if (cls) s += ' class="' + cls.substring(0, 50) + '"';
1562        }
1563        s += '>';
1564        return s;
1565    }
1566
1567    function parseColor(str) {
1568        if (!str) return null;
1569        var m = str.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
1570        if (!m) return null;
1571        return { r: parseInt(m[1]), g: parseInt(m[2]), b: parseInt(m[3]), a: m[4] !== undefined ? parseFloat(m[4]) : 1 };
1572    }
1573
1574    function luminance(c) {
1575        var rs = c.r / 255, gs = c.g / 255, bs = c.b / 255;
1576        var r = rs <= 0.03928 ? rs / 12.92 : Math.pow((rs + 0.055) / 1.055, 2.4);
1577        var g = gs <= 0.03928 ? gs / 12.92 : Math.pow((gs + 0.055) / 1.055, 2.4);
1578        var b = bs <= 0.03928 ? bs / 12.92 : Math.pow((bs + 0.055) / 1.055, 2.4);
1579        return 0.2126 * r + 0.7152 * g + 0.0722 * b;
1580    }
1581
1582    function contrastRatio(fg, bg) {
1583        var l1 = luminance(fg), l2 = luminance(bg);
1584        var lighter = Math.max(l1, l2), darker = Math.min(l1, l2);
1585        return (lighter + 0.05) / (darker + 0.05);
1586    }
1587
1588    // ── Long Task Observer ──────────────────────────────────────────────────
1589
1590    try {
1591        var ltObserver = new PerformanceObserver(function(list) {
1592            var entries = list.getEntries();
1593            for (var i = 0; i < entries.length; i++) {
1594                longTasks.push({ duration: entries[i].duration, startTime: entries[i].startTime });
1595                if (longTasks.length > CAP_LONG_TASKS) longTasks.shift();
1596            }
1597        });
1598        ltObserver.observe({ type: 'longtask', buffered: true });
1599    } catch(e) {}
1600
1601    // ── Event Listener Counter ──────────────────────────────────────────────
1602
1603    (function() {
1604        var origAdd = EventTarget.prototype.addEventListener;
1605        var origRemove = EventTarget.prototype.removeEventListener;
1606        EventTarget.prototype.addEventListener = function() {
1607            listenerCount++;
1608            return origAdd.apply(this, arguments);
1609        };
1610        EventTarget.prototype.removeEventListener = function() {
1611            if (listenerCount > 0) listenerCount--;
1612            return origRemove.apply(this, arguments);
1613        };
1614    })();
1615
1616    // ── DOM Walking ──────────────────────────────────────────────────────────
1617
1618    function walkDom(node) {
1619        if (!node || node.nodeType !== 1) return null;
1620
1621        var style = window.getComputedStyle(node);
1622        var visible = style.display !== 'none'
1623            && style.visibility !== 'hidden'
1624            && style.opacity !== '0';
1625
1626        if (!visible) return null;
1627
1628        var ref_id = registerRef(node);
1629
1630        var rect = node.getBoundingClientRect();
1631        var role = node.getAttribute('role') || inferRole(node);
1632        var name = node.getAttribute('aria-label')
1633            || node.getAttribute('title')
1634            || node.getAttribute('placeholder')
1635            || (node.tagName === 'BUTTON' ? node.textContent.trim().substring(0, 80) : null)
1636            || (node.tagName === 'A' ? node.textContent.trim().substring(0, 80) : null);
1637
1638        var element = {
1639            ref_id: ref_id,
1640            tag: node.tagName.toLowerCase(),
1641            role: role,
1642            name: name,
1643            text: getDirectText(node),
1644            value: (node.tagName === 'INPUT' && (node.getAttribute('type') || '').toLowerCase() === 'password') ? '[REDACTED]' : (node.value || null),
1645            enabled: !node.disabled,
1646            visible: true,
1647            focusable: node.tabIndex >= 0 || ['INPUT','BUTTON','SELECT','TEXTAREA','A'].indexOf(node.tagName) !== -1,
1648            bounds: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
1649            children: [],
1650            attributes: {}
1651        };
1652
1653        var interestingAttrs = ['data-testid', 'id', 'type', 'href', 'src', 'checked', 'selected'];
1654        for (var a = 0; a < interestingAttrs.length; a++) {
1655            if (node.hasAttribute(interestingAttrs[a])) {
1656                element.attributes[interestingAttrs[a]] = node.getAttribute(interestingAttrs[a]);
1657            }
1658        }
1659
1660        for (var c = 0; c < node.children.length; c++) {
1661            var childEl = walkDom(node.children[c]);
1662            if (childEl) element.children.push(childEl);
1663        }
1664
1665        if (node.shadowRoot) {
1666            for (var s = 0; s < node.shadowRoot.children.length; s++) {
1667                var shadowChild = walkDom(node.shadowRoot.children[s]);
1668                if (shadowChild) element.children.push(shadowChild);
1669            }
1670        }
1671
1672        // Same-origin iframe traversal: descend into accessible frame documents.
1673        // Cross-origin frames throw on contentDocument access — mark and skip.
1674        if (node.tagName === 'IFRAME' || node.tagName === 'FRAME') {
1675            try {
1676                var idoc = node.contentDocument;
1677                if (idoc && idoc.body) {
1678                    var frameChild = walkDom(idoc.body);
1679                    if (frameChild) {
1680                        frameChild.frame = true;
1681                        element.children.push(frameChild);
1682                    }
1683                } else {
1684                    element.attributes['cross_origin_frame'] = 'true';
1685                }
1686            } catch (e) {
1687                element.attributes['cross_origin_frame'] = 'true';
1688            }
1689        }
1690
1691        return element;
1692    }
1693
1694    function walkDomCompact(node, depth) {
1695        if (!node || node.nodeType !== 1) return '';
1696
1697        var style = window.getComputedStyle(node);
1698        var visible = style.display !== 'none'
1699            && style.visibility !== 'hidden'
1700            && style.opacity !== '0';
1701
1702        if (!visible) return '';
1703
1704        var ref_id = registerRef(node);
1705        var indent = '';
1706        for (var d = 0; d < depth; d++) indent += '  ';
1707
1708        var role = node.getAttribute('role') || inferRole(node);
1709        var name = node.getAttribute('aria-label')
1710            || node.getAttribute('title')
1711            || node.getAttribute('placeholder')
1712            || '';
1713        var text = getDirectText(node) || '';
1714        var tag = node.tagName.toLowerCase();
1715
1716        var line = indent + '[' + ref_id + '] ';
1717
1718        if (role && role !== tag) {
1719            line += role;
1720        } else {
1721            line += tag;
1722        }
1723
1724        if (name) {
1725            line += ' "' + name.substring(0, 60) + '"';
1726        } else if (text && text.length <= 60) {
1727            line += ' "' + text + '"';
1728        } else if (text) {
1729            line += ' "' + text.substring(0, 57) + '..."';
1730        }
1731
1732        if (node.disabled) line += ' [disabled]';
1733        if (node.value) {
1734            var isPassword = node.tagName === 'INPUT' && (node.getAttribute('type') || '').toLowerCase() === 'password';
1735            line += ' value=' + JSON.stringify(isPassword ? '[REDACTED]' : node.value.substring(0, 40));
1736        }
1737
1738        var testId = node.getAttribute('data-testid');
1739        if (testId) line += ' @' + testId;
1740
1741        var type = node.getAttribute('type');
1742        if (type && tag === 'input') line += ' type=' + type;
1743
1744        var href = node.getAttribute('href');
1745        if (href && tag === 'a') line += ' href=' + href.substring(0, 60);
1746
1747        var result = line + '\n';
1748
1749        for (var c = 0; c < node.children.length; c++) {
1750            result += walkDomCompact(node.children[c], depth + 1);
1751        }
1752
1753        if (node.shadowRoot) {
1754            for (var s = 0; s < node.shadowRoot.children.length; s++) {
1755                result += walkDomCompact(node.shadowRoot.children[s], depth + 1);
1756            }
1757        }
1758
1759        // Same-origin iframe traversal (see walkDom for rationale).
1760        if (node.tagName === 'IFRAME' || node.tagName === 'FRAME') {
1761            try {
1762                var idoc = node.contentDocument;
1763                if (idoc && idoc.body) {
1764                    result += indent + '  ⤷ iframe content:\n';
1765                    result += walkDomCompact(idoc.body, depth + 2);
1766                } else {
1767                    result += indent + '  ⤷ [cross-origin iframe]\n';
1768                }
1769            } catch (e) {
1770                result += indent + '  ⤷ [cross-origin iframe]\n';
1771            }
1772        }
1773
1774        return result;
1775    }
1776
1777    function inferRole(node) {
1778        var tag = node.tagName;
1779        var roles = {
1780            'BUTTON': 'button', 'A': 'link', 'INPUT': 'textbox',
1781            'SELECT': 'combobox', 'TEXTAREA': 'textbox', 'IMG': 'img',
1782            'NAV': 'navigation', 'MAIN': 'main', 'HEADER': 'banner',
1783            'FOOTER': 'contentinfo', 'ASIDE': 'complementary',
1784            'H1': 'heading', 'H2': 'heading', 'H3': 'heading',
1785            'H4': 'heading', 'H5': 'heading', 'H6': 'heading',
1786            'UL': 'list', 'OL': 'list', 'LI': 'listitem',
1787            'TABLE': 'table', 'FORM': 'form', 'DIALOG': 'dialog',
1788        };
1789        if (tag === 'INPUT') {
1790            var type = node.getAttribute('type');
1791            if (type === 'checkbox') return 'checkbox';
1792            if (type === 'radio') return 'radio';
1793            if (type === 'range') return 'slider';
1794            if (type === 'submit' || type === 'button') return 'button';
1795        }
1796        return roles[tag] || null;
1797    }
1798
1799    function getDirectText(node) {
1800        var text = '';
1801        for (var i = 0; i < node.childNodes.length; i++) {
1802            if (node.childNodes[i].nodeType === 3) text += node.childNodes[i].textContent;
1803        }
1804        text = text.trim();
1805        return text.length > 0 ? text.substring(0, 200) : null;
1806    }
1807
1808    // ── Console Hooking ──────────────────────────────────────────────────────
1809
1810    var originalConsole = {
1811        log: console.log, warn: console.warn,
1812        error: console.error, info: console.info, debug: console.debug
1813    };
1814
1815    var CTRL_RE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F\x1B]/g;
1816
1817    function hookConsole(level) {
1818        console[level] = function() {
1819            var args = Array.prototype.slice.call(arguments);
1820            var msg = args.map(String).join(' ').replace(CTRL_RE, '');
1821            consoleLogs.push({ level: level, message: msg, timestamp: Date.now() });
1822            if (consoleLogs.length > CAP_CONSOLE) consoleLogs.shift();
1823            originalConsole[level].apply(console, args);
1824        };
1825    }
1826
1827    hookConsole('log');
1828    hookConsole('warn');
1829    hookConsole('error');
1830    hookConsole('info');
1831    hookConsole('debug');
1832
1833    // ── Global Error Capture ────────────────────────────────────────────────
1834
1835    window.addEventListener('error', function(e) {
1836        var msg = e.message || 'Unknown error';
1837        if (e.filename) msg += ' at ' + e.filename + ':' + e.lineno + ':' + e.colno;
1838        consoleLogs.push({ level: 'error', message: ('[uncaught] ' + msg).replace(CTRL_RE, ''), timestamp: Date.now() });
1839        if (consoleLogs.length > CAP_CONSOLE) consoleLogs.shift();
1840    });
1841
1842    window.addEventListener('unhandledrejection', function(e) {
1843        var msg = e.reason ? (e.reason.message || String(e.reason)) : 'Unhandled promise rejection';
1844        consoleLogs.push({ level: 'error', message: ('[unhandled rejection] ' + msg).replace(CTRL_RE, ''), timestamp: Date.now() });
1845        if (consoleLogs.length > CAP_CONSOLE) consoleLogs.shift();
1846    });
1847
1848    // ── Interaction Observer (for record mode) ────────────────────────────────
1849
1850    function bestSelector(el) {
1851        if (el.dataset && el.dataset.testid) return '[data-testid="' + el.dataset.testid + '"]';
1852        if (el.id) return '#' + el.id;
1853        if (el.getAttribute && el.getAttribute('role')) {
1854            var role = el.getAttribute('role');
1855            var text = (el.textContent || '').trim().substring(0, 50);
1856            if (text) return '[role="' + role + '"]:has-text("' + text + '")';
1857            return '[role="' + role + '"]';
1858        }
1859        var tag = (el.tagName || 'div').toLowerCase();
1860        var text = (el.textContent || '').trim().substring(0, 50);
1861        if (text && ['button', 'a', 'label', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'span'].indexOf(tag) !== -1) {
1862            return tag + ':has-text("' + text + '")';
1863        }
1864        if (el.name) return tag + '[name="' + el.name + '"]';
1865        if (el.className && typeof el.className === 'string') {
1866            var cls = el.className.trim().split(/\s+/).slice(0, 2).join('.');
1867            if (cls) return tag + '.' + cls;
1868        }
1869        return tag;
1870    }
1871
1872    function pushInteraction(action, el, value) {
1873        interactionLog.push({
1874            type: 'dom_interaction',
1875            action: action,
1876            selector: bestSelector(el),
1877            value: value || null,
1878            timestamp: Date.now()
1879        });
1880        if (interactionLog.length > CAP_INTERACTION) interactionLog.shift();
1881    }
1882
1883    document.addEventListener('click', function(e) {
1884        if (e.isTrusted && e.target) pushInteraction('click', e.target, null);
1885    }, true);
1886
1887    document.addEventListener('dblclick', function(e) {
1888        if (e.isTrusted && e.target) pushInteraction('double_click', e.target, null);
1889    }, true);
1890
1891    document.addEventListener('change', function(e) {
1892        if (!e.isTrusted || !e.target) return;
1893        var el = e.target;
1894        var tag = (el.tagName || '').toLowerCase();
1895        if (tag === 'select') {
1896            pushInteraction('select', el, el.value);
1897        } else if (tag === 'input' || tag === 'textarea') {
1898            var isPassword = tag === 'input' && el.type === 'password';
1899            pushInteraction('fill', el, isPassword ? '[REDACTED]' : el.value);
1900        }
1901    }, true);
1902
1903    document.addEventListener('keydown', function(e) {
1904        if (!e.isTrusted) return;
1905        if (['Enter', 'Escape', 'Tab', 'Backspace', 'Delete', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].indexOf(e.key) !== -1) {
1906            pushInteraction('key_press', e.target || document.body, e.key);
1907        }
1908    }, true);
1909
1910    // ── Mutation Observer (deferred) ─────────────────────────────────────────
1911
1912    var mutationBatchCount = 0;
1913    var mutationBatchTimer = null;
1914    var __mutationObserver = null;
1915
1916    function startMutationObserver() {
1917        if (!document.documentElement) return false;
1918        __mutationObserver = new MutationObserver(function(mutations) {
1919            mutationBatchCount += mutations.length;
1920            if (!mutationBatchTimer) {
1921                mutationBatchTimer = setTimeout(function() {
1922                    mutationLog.push({ count: mutationBatchCount, timestamp: Date.now() });
1923                    if (mutationLog.length > CAP_MUTATION) mutationLog.shift();
1924                    mutationBatchCount = 0;
1925                    mutationBatchTimer = null;
1926                }, 100);
1927            }
1928        });
1929        __mutationObserver.observe(document.documentElement, {
1930            childList: true, subtree: true, attributes: true, characterData: true,
1931        });
1932        return true;
1933    }
1934
1935    if (!startMutationObserver()) {
1936        document.addEventListener('DOMContentLoaded', startMutationObserver);
1937    }
1938
1939    // IPC logging is derived from the network log: Tauri 2.0 sends all IPC
1940    // via fetch to http://ipc.localhost/<command>. The fetch interceptor below
1941    // captures these, and getIpcLog() filters them from networkLog. This avoids
1942    // the need to patch __TAURI_INTERNALS__.invoke, which Tauri freezes with
1943    // configurable:false, writable:false.
1944
1945    // ── Network Interception ─────────────────────────────────────────────────
1946
1947    (function interceptNetwork() {
1948        // fetch
1949        var origFetch = window.fetch;
1950        if (origFetch) {
1951            window.fetch = function(input, init) {
1952                var id = ++networkCounter;
1953                var url = typeof input === 'string' ? input : (input && input.url ? input.url : String(input));
1954                var method = (init && init.method) || (input && input.method) || 'GET';
1955                var isIpc = url.indexOf('http://ipc.localhost/') === 0;
1956                var isVictauriInternal = isIpc && url.indexOf('plugin%3Avictauri%7C') !== -1;
1957                var entry = { id: id, method: method.toUpperCase(), url: url, timestamp: Date.now(), status: 'pending', duration_ms: null };
1958
1959                if (isIpc && !isVictauriInternal && init && init.body && window.__VICTAURI__._captureIpcBodies !== false) {
1960                    try {
1961                        var bodyStr = typeof init.body === 'string' ? init.body : null;
1962                        if (bodyStr) {
1963                            var parsed = JSON.parse(bodyStr);
1964                            entry.request_args = parsed;
1965                        }
1966                    } catch(e) {}
1967                }
1968
1969                if (!isVictauriInternal) {
1970                    networkLog.push(entry);
1971                    if (networkLog.length > CAP_NETWORK) networkLog.shift();
1972                }
1973
1974                var self = this;
1975                function flushIpcWaiters() {
1976                    for (var w = ipcWaiters.length - 1; w >= 0; w--) { ipcWaiters[w](); }
1977                    ipcWaiters.length = 0;
1978                }
1979
1980                // Phase 1: apply a matching route rule (block / fulfill / delay).
1981                var route = matchRoute(url, method);
1982                if (route) {
1983                    recordRouteMatch(route, url, method);
1984                    if (route.action === 'block') {
1985                        entry.status = 'blocked';
1986                        entry.blocked = true;
1987                        entry.duration_ms = Date.now() - entry.timestamp;
1988                        if (isIpc) flushIpcWaiters();
1989                        return Promise.reject(new TypeError('victauri: request blocked by route #' + route.id + ' (' + url + ')'));
1990                    }
1991                    if (route.action === 'fulfill') {
1992                        var makeResp = function() {
1993                            var bodyStr = (typeof route.body === 'string') ? route.body : JSON.stringify(route.body);
1994                            var hdrs = { 'content-type': route.content_type };
1995                            for (var k in route.headers) { if (Object.prototype.hasOwnProperty.call(route.headers, k)) hdrs[k] = route.headers[k]; }
1996                            entry.status = route.status;
1997                            entry.status_text = route.status_text;
1998                            entry.mocked = true;
1999                            entry.duration_ms = Date.now() - entry.timestamp;
2000                            if (isIpc) {
2001                                try { entry.response_body = JSON.parse(bodyStr); } catch (e) { entry.response_body = bodyStr; }
2002                                flushIpcWaiters();
2003                            }
2004                            return new Response(bodyStr, { status: route.status, statusText: route.status_text, headers: hdrs });
2005                        };
2006                        return route.delay_ms > 0
2007                            ? new Promise(function(res) { setTimeout(function() { res(makeResp()); }, route.delay_ms); })
2008                            : Promise.resolve(makeResp());
2009                    }
2010                    if (route.action === 'delay' && route.delay_ms > 0) {
2011                        return new Promise(function(resolve, reject) {
2012                            setTimeout(function() { doRealFetch().then(resolve, reject); }, route.delay_ms);
2013                        });
2014                    }
2015                }
2016                return doRealFetch();
2017
2018                function doRealFetch() {
2019                    return origFetch.call(self, input, init).then(function(response) {
2020                        entry.status = response.status;
2021                        entry.status_text = response.statusText;
2022                        entry.duration_ms = Date.now() - entry.timestamp;
2023
2024                        if (isIpc) {
2025                            if (window.__VICTAURI__._captureIpcBodies !== false) {
2026                                var cloned = response.clone();
2027                                cloned.text().then(function(text) {
2028                                    try { entry.response_body = JSON.parse(text); } catch(e) { entry.response_body = text; }
2029                                }).catch(function() {}).then(function() {
2030                                    flushIpcWaiters();
2031                                });
2032                            } else {
2033                                flushIpcWaiters();
2034                            }
2035                        }
2036
2037                        return response;
2038                    }, function(err) {
2039                        entry.status = 'error';
2040                        entry.error = String(err);
2041                        entry.duration_ms = Date.now() - entry.timestamp;
2042                        flushIpcWaiters();
2043                        throw err;
2044                    });
2045                }
2046            };
2047        }
2048
2049        // XMLHttpRequest
2050        var origOpen = XMLHttpRequest.prototype.open;
2051        var origSend = XMLHttpRequest.prototype.send;
2052        XMLHttpRequest.prototype.open = function(method, url) {
2053            this.__victauri_net = { method: method, url: url };
2054            return origOpen.apply(this, arguments);
2055        };
2056        XMLHttpRequest.prototype.send = function() {
2057            if (this.__victauri_net) {
2058                var isVictauriInternal = this.__victauri_net.url.indexOf('plugin%3Avictauri%7C') !== -1
2059                    || this.__victauri_net.url.indexOf('plugin:victauri|') !== -1;
2060                if (isVictauriInternal) {
2061                    return origSend.apply(this, arguments);
2062                }
2063                var id = ++networkCounter;
2064                var entry = {
2065                    id: id,
2066                    method: this.__victauri_net.method.toUpperCase(),
2067                    url: this.__victauri_net.url,
2068                    timestamp: Date.now(),
2069                    status: 'pending',
2070                    duration_ms: null,
2071                };
2072                networkLog.push(entry);
2073                if (networkLog.length > CAP_NETWORK) networkLog.shift();
2074                var self = this;
2075                this.addEventListener('load', function() {
2076                    entry.status = self.status;
2077                    entry.status_text = self.statusText;
2078                    entry.duration_ms = Date.now() - entry.timestamp;
2079                });
2080                this.addEventListener('error', function() {
2081                    entry.status = 'error';
2082                    entry.duration_ms = Date.now() - entry.timestamp;
2083                });
2084
2085                // Phase 1 routing for XHR: block + delay are supported here.
2086                // `fulfill` (synthetic response) is fetch-only — faking the full
2087                // XHR response surface is unreliable; document as a limitation.
2088                var xroute = matchRoute(this.__victauri_net.url, this.__victauri_net.method);
2089                if (xroute) {
2090                    recordRouteMatch(xroute, this.__victauri_net.url, this.__victauri_net.method);
2091                    if (xroute.action === 'block') {
2092                        entry.status = 'blocked';
2093                        entry.blocked = true;
2094                        entry.duration_ms = Date.now() - entry.timestamp;
2095                        var blockedXhr = this;
2096                        setTimeout(function() {
2097                            try { blockedXhr.dispatchEvent(new Event('error')); } catch (e) {}
2098                        }, 0);
2099                        return; // do not send
2100                    }
2101                    if ((xroute.action === 'delay' || xroute.action === 'fulfill') && xroute.delay_ms > 0) {
2102                        var dArgs = arguments, dSelf = this;
2103                        setTimeout(function() { origSend.apply(dSelf, dArgs); }, xroute.delay_ms);
2104                        return;
2105                    }
2106                }
2107            }
2108            return origSend.apply(this, arguments);
2109        };
2110    })();
2111
2112    // ── Navigation Tracking ──────────────────────────────────────────────────
2113
2114    (function trackNavigation() {
2115        navigationLog.push({ url: window.location.href, timestamp: Date.now(), type: 'initial' });
2116
2117        var origPushState = history.pushState;
2118        var origReplaceState = history.replaceState;
2119        history.pushState = function() {
2120            var result = origPushState.apply(this, arguments);
2121            navigationLog.push({ url: window.location.href, timestamp: Date.now(), type: 'pushState' });
2122            if (navigationLog.length > CAP_NAVIGATION) navigationLog.shift();
2123            return result;
2124        };
2125        history.replaceState = function() {
2126            var result = origReplaceState.apply(this, arguments);
2127            navigationLog.push({ url: window.location.href, timestamp: Date.now(), type: 'replaceState' });
2128            if (navigationLog.length > CAP_NAVIGATION) navigationLog.shift();
2129            return result;
2130        };
2131        window.addEventListener('popstate', function() {
2132            navigationLog.push({ url: window.location.href, timestamp: Date.now(), type: 'popstate' });
2133        });
2134        window.addEventListener('hashchange', function(e) {
2135            navigationLog.push({ url: window.location.href, timestamp: Date.now(), type: 'hashchange', old_url: e.oldURL });
2136        });
2137    })();
2138
2139    // ── Dialog Capture ───────────────────────────────────────────────────────
2140
2141    // Default fail-CLOSED (audit #32): merely loading the bridge must not silently
2142    // auto-approve "are you sure?" gates. confirm() -> false, prompt() -> null until
2143    // an explicit set_dialog_response opts into accepting.
2144    var dialogAutoResponses = { alert: { action: 'accept' }, confirm: { action: 'dismiss' }, prompt: { action: 'dismiss', text: '' } };
2145
2146    // ── Resource Cleanup ────────────────────────────────────────────────────
2147
2148    window.addEventListener('pagehide', function() {
2149        if (__mutationObserver) { __mutationObserver.disconnect(); __mutationObserver = null; }
2150        if (mutationBatchTimer) { clearTimeout(mutationBatchTimer); mutationBatchTimer = null; }
2151        console.log = originalConsole.log;
2152        console.warn = originalConsole.warn;
2153        console.error = originalConsole.error;
2154        console.info = originalConsole.info;
2155        console.debug = originalConsole.debug;
2156        consoleLogs.length = 0;
2157        mutationLog.length = 0;
2158        networkLog.length = 0;
2159        navigationLog.length = 0;
2160        dialogLog.length = 0;
2161        interactionLog.length = 0;
2162        refMap.clear();
2163        weakRefMap.clear();
2164        refCounter = 0;
2165    });
2166
2167    (function captureDialogs() {
2168        window.alert = function(msg) {
2169            dialogLog.push({ type: 'alert', message: String(msg || ''), timestamp: Date.now() });
2170            if (dialogLog.length > CAP_DIALOG) dialogLog.shift();
2171        };
2172        window.confirm = function(msg) {
2173            var resp = dialogAutoResponses.confirm;
2174            var result = resp.action === 'accept';
2175            dialogLog.push({ type: 'confirm', message: String(msg || ''), timestamp: Date.now(), result: result });
2176            if (dialogLog.length > CAP_DIALOG) dialogLog.shift();
2177            return result;
2178        };
2179        window.prompt = function(msg, defaultValue) {
2180            var resp = dialogAutoResponses.prompt;
2181            var result = resp.action === 'accept' ? (resp.text || defaultValue || '') : null;
2182            dialogLog.push({ type: 'prompt', message: String(msg || ''), timestamp: Date.now(), result: result });
2183            if (dialogLog.length > CAP_DIALOG) dialogLog.shift();
2184            return result;
2185        };
2186    })();
2187
2188    // Signal to the Rust backend that the JS bridge is fully initialized.
2189    try {
2190        window.__TAURI_INTERNALS__.invoke('plugin:victauri|victauri_eval_callback', {
2191            id: '__victauri_bridge_ready__',
2192            result: ''
2193        });
2194    } catch(e) {}
2195})();
2196"#;