tauri-plugin-hasgard 0.3.0

Native automation and testing bridge for Tauri 2 applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
(() => {
  "use strict";

  if (window.__HASGARD__) return;

  const idMap = new Map();
  let refCounter = 0;

  const _logs = [];
  let _logIdCounter = 0;
  const MAX_LOGS = 500;

  const _networkRequests = [];
  let _netIdCounter = 0;
  const MAX_REQUESTS = 200;

  const ROLE_MAP = {
    A: "link",
    BUTTON: "button",
    SELECT: "combobox",
    TEXTAREA: "textbox",
    IMG: "img",
    H1: "heading",
    H2: "heading",
    H3: "heading",
    H4: "heading",
    H5: "heading",
    H6: "heading",
    P: "paragraph",
    UL: "list",
    OL: "list",
    LI: "listitem",
    TABLE: "table",
    TR: "row",
    TH: "columnheader",
    TD: "cell",
    NAV: "navigation",
    MAIN: "main",
    ASIDE: "complementary",
    FORM: "form",
    DIALOG: "dialog",
    DETAILS: "group",
  };

  const INTERACTIVE_ROLES = new Set([
    "button",
    "link",
    "checkbox",
    "radio",
    "switch",
    "slider",
    "textbox",
    "combobox",
  ]);

  function serializeArg(arg) {
    if (arg === null) return null;
    if (arg === undefined) return null;
    if (typeof arg === 'string' || typeof arg === 'number' || typeof arg === 'boolean') return arg;
    try {
      JSON.stringify(arg);
      return arg;
    } catch (_) {
      return String(arg);
    }
  }

  function extractSource() {
    try {
      const stack = new Error().stack;
      if (!stack) return null;
      // Skip frames: Error constructor, extractSource, console[level] wrapper
      const lines = stack.split('\n');
      for (let i = 3; i < lines.length; i++) {
        const line = lines[i];
        if (line && !line.includes('__HASGARD__')) return line.trim();
      }
      return null;
    } catch (_) { return null; }
  }

  const _originalConsole = {
    log: console.log.bind(console),
    warn: console.warn.bind(console),
    error: console.error.bind(console),
    info: console.info.bind(console),
  };

  ['log', 'warn', 'error', 'info'].forEach(level => {
    console[level] = function(...args) {
      const entry = {
        id: ++_logIdCounter,
        timestamp: Date.now(),
        level: level,
        args: args.map(serializeArg),
        source: extractSource(),
      };
      _logs.push(entry);
      if (_logs.length > MAX_LOGS) _logs.shift();
      _originalConsole[level].apply(console, args);
    };
  });

  function consoleLogs(options) {
    let result = _logs.slice();
    if (options) {
      if (options.level) {
        result = result.filter(e => e.level === options.level);
      }
      if (options.sinceId) {
        result = result.filter(e => e.id > options.sinceId);
      } else if (options.since) {
        result = result.filter(e => e.timestamp > options.since);
      }
      if (options.last) {
        result = result.slice(-options.last);
      }
    }
    return result;
  }

  function clearLogs() {
    _logs.length = 0;
    return { cleared: true };
  }

  // --- Modal dialogs -------------------------------------------------------
  //
  // `alert`/`confirm`/`prompt` block the webview's main thread until a human
  // clicks. Under automation nobody does, so the app freezes, the bridge stops
  // answering, and every in-flight call dies on a timeout that names the wrong
  // cause. Intercepting them is what makes an app that calls `confirm()`
  // testable at all.
  //
  // The default is to dismiss, matching Playwright: a test that never mentions
  // dialogs should not be silently agreeing to things. Every dialog is recorded
  // either way, so a test can assert on what the app tried to ask.
  const _dialogs = [];
  let _dialogIdCounter = 0;
  const _dialogPolicy = { action: "dismiss", promptText: null };

  function recordDialog(type, message, defaultValue, accepted, returned) {
    const entry = {
      id: ++_dialogIdCounter,
      timestamp: Date.now(),
      type: type,
      message: message == null ? "" : String(message),
      accepted: accepted,
    };
    if (defaultValue !== undefined) entry.defaultValue = String(defaultValue);
    if (returned !== undefined && returned !== null) entry.returned = String(returned);
    _dialogs.push(entry);
    if (_dialogs.length > MAX_LOGS) _dialogs.shift();
    return entry;
  }

  window.alert = function (message) {
    // An alert has one button, so "dismiss" and "accept" are the same act; it is
    // recorded as accepted because the page's only possible outcome is that the
    // user acknowledged it.
    recordDialog("alert", message, undefined, true, undefined);
  };

  window.confirm = function (message) {
    const accepted = _dialogPolicy.action === "accept";
    recordDialog("confirm", message, undefined, accepted, undefined);
    return accepted;
  };

  window.prompt = function (message, defaultValue) {
    const accepted = _dialogPolicy.action === "accept";
    // Accepting with no configured text submits the page's own default, exactly
    // as pressing OK on an untouched prompt would.
    const returned = accepted
      ? (_dialogPolicy.promptText != null ? _dialogPolicy.promptText : (defaultValue == null ? "" : defaultValue))
      : null;
    recordDialog("prompt", message, defaultValue, accepted, returned);
    return returned;
  };

  function dialogs() {
    return { dialogs: _dialogs.slice(), policy: { action: _dialogPolicy.action, promptText: _dialogPolicy.promptText } };
  }

  function clearDialogs() {
    _dialogs.length = 0;
    return { cleared: true };
  }

  function handleDialogs(params) {
    const action = params && params.action;
    if (action !== "accept" && action !== "dismiss") {
      throw new Error('dialog action must be "accept" or "dismiss", got: ' + String(action).slice(0, 64));
    }
    _dialogPolicy.action = action;
    // `promptText` is only meaningful for accept; keeping a stale value around
    // after switching to dismiss would resurface it on the next accept.
    _dialogPolicy.promptText =
      action === "accept" && params.promptText != null ? String(params.promptText) : null;
    return { action: _dialogPolicy.action, promptText: _dialogPolicy.promptText };
  }

  function bodySize(body) {
    if (!body) return 0;
    if (typeof body === "string") return body.length;
    if (body instanceof URLSearchParams) return body.toString().length;
    if (body instanceof Blob) return body.size;
    if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) return body.byteLength;
    return 0;
  }

  // --- Routing -------------------------------------------------------------
  //
  // Rules are declarative rather than Playwright's per-request callback. The
  // bridge cannot call back into the test process and await an answer -- it only
  // ever responds to requests -- so a handler round trip would have to block the
  // page inside `fetch`, which it cannot do. The same constraint shaped the
  // dialog policy above.
  //
  // Rules are checked in registration order; the first match wins, so a narrow
  // rule registered first survives a later catch-all.

  var _routes = [];
  var _routeIdCounter = 0;
  var _routeLog = [];
  const MAX_ROUTE_LOG = 200;

  // Glob to RegExp, with `**` crossing path separators and `*` staying within a
  // segment. Anchored at both ends: a pattern that matched a substring would
  // make `**/api` also intercept `/v2/api-docs`.
  function globToRegExp(pattern) {
    var out = "";
    for (var i = 0; i < pattern.length; i++) {
      var ch = pattern.charAt(i);
      if (ch === "*") {
        if (pattern.charAt(i + 1) === "*") {
          out += ".*";
          i++;
        } else {
          out += "[^/]*";
        }
      } else if (ch === "?") {
        out += "[^/]";
      } else if (".+^${}()|[]\\".indexOf(ch) !== -1) {
        out += "\\" + ch;
      } else {
        out += ch;
      }
    }
    return new RegExp("^" + out + "$");
  }

  // Tauri's own IPC is never routed.
  //
  // Every eval result travels back through `__TAURI_INTERNALS__.invoke`, which
  // on several platforms is an HTTP request to the IPC endpoint. A catch-all
  // rule would therefore swallow the bridge's own replies, and every later call
  // -- including the one that removes the rule -- would die on an eval timeout
  // with nothing to say why. Excluding it here is not a convenience: without it
  // `route({ pattern: "**" })` bricks the session.
  function isTauriIpc(url) {
    return /^ipc:\/\//i.test(url) || /^https?:\/\/ipc\.localhost([:/?#]|$)/i.test(url);
  }

  function matchRoute(url, method) {
    if (isTauriIpc(url)) return null;
    for (var i = 0; i < _routes.length; i++) {
      var route = _routes[i];
      if (route.times != null && route.used >= route.times) continue;
      if (route.method && route.method !== method.toUpperCase()) continue;
      if (!route.regex.test(url)) continue;
      route.used += 1;
      _routeLog.push({
        id: ++_netIdCounter,
        timestamp: Date.now(),
        route_id: route.id,
        method: method.toUpperCase(),
        url: url,
        action: route.action,
        status: route.action === "fulfill" ? route.status : 0,
      });
      if (_routeLog.length > MAX_ROUTE_LOG) _routeLog.shift();
      return route;
    }
    return null;
  }

  function recordNetwork(entry) {
    _networkRequests.push(entry);
    if (_networkRequests.length > MAX_REQUESTS) _networkRequests.shift();
  }

  function routeAdd(params) {
    var pattern = params && params.pattern;
    if (typeof pattern !== "string" || pattern === "") {
      throw new Error("route requires a non-empty 'pattern'");
    }
    var action = (params && params.action) || "fulfill";
    if (action !== "fulfill" && action !== "abort") {
      throw new Error("route 'action' must be 'fulfill' or 'abort', got: " + String(action).slice(0, 32));
    }
    var status = (params && params.status != null) ? params.status : 200;
    if (typeof status !== "number" || status < 100 || status > 599) {
      throw new Error("route 'status' must be an HTTP status code between 100 and 599");
    }
    var times = (params && params.times != null) ? params.times : null;
    if (times != null && (typeof times !== "number" || times < 1 || times % 1 !== 0)) {
      throw new Error("route 'times' must be a positive integer");
    }
    var method = (params && params.method) ? String(params.method).toUpperCase() : null;
    var route = {
      id: ++_routeIdCounter,
      pattern: pattern,
      regex: globToRegExp(pattern),
      method: method,
      action: action,
      status: status,
      body: (params && params.body != null) ? String(params.body) : "",
      contentType: (params && params.contentType) || "text/plain",
      times: times,
      used: 0,
    };
    _routes.push(route);
    return { id: route.id, pattern: route.pattern, action: route.action };
  }

  function routeList() {
    return {
      routes: _routes.map(function (route) {
        return {
          id: route.id,
          pattern: route.pattern,
          method: route.method,
          action: route.action,
          status: route.status,
          times: route.times,
          used: route.used,
        };
      }),
      intercepted: _routeLog.slice(),
    };
  }

  function routeClear() {
    var removed = _routes.length;
    _routes = [];
    _routeLog = [];
    return { removed: removed };
  }

  function fulfilledResponse(route, url) {
    var headers = { "Content-Type": route.contentType };
    if (typeof Response === "function") {
      var response = new Response(route.body, { status: route.status, headers: headers });
      // `Response.url` is read-only and empty on a constructed response, but
      // application code routinely reads it; make it the URL that was asked for.
      try {
        Object.defineProperty(response, "url", { value: url });
      } catch (_) {}
      return response;
    }
    throw new Error("This webview has no Response constructor, so routes cannot be fulfilled");
  }

  const _originalFetch = window.fetch.bind(window);
  window.fetch = function(input, init) {
    const method = (init && init.method) || (input && input.method) || "GET";
    const url = (typeof input === "string") ? input : (input && input.url) || String(input);
    const timestamp = Date.now();
    const requestSize = bodySize(init && init.body);

    // Routed requests are still logged as network activity: the application did
    // issue them and did receive an answer, and a test asserting "the app called
    // /api/user" must not go blind the moment that call is stubbed.
    const route = matchRoute(url, method);
    if (route) {
      if (route.action === "abort") {
        recordNetwork({
          id: ++_netIdCounter, timestamp: timestamp, method: method, url: url, status: 0,
          duration_ms: 0, error: "Aborted by route", request_size: requestSize, response_size: 0,
        });
        return Promise.reject(new TypeError("Failed to fetch"));
      }
      recordNetwork({
        id: ++_netIdCounter, timestamp: timestamp, method: method, url: url, status: route.status,
        duration_ms: 0, error: null, request_size: requestSize, response_size: route.body.length,
      });
      return Promise.resolve(fulfilledResponse(route, url));
    }

    return _originalFetch(input, init).then(function(response) {
      const duration_ms = Date.now() - timestamp;
      const status = response.status;
      const responseSize = parseInt(response.headers.get("Content-Length") || "0", 10) || 0;
      const entry = {
        id: ++_netIdCounter,
        timestamp: timestamp,
        method: method,
        url: url,
        status: status,
        duration_ms: duration_ms,
        error: null,
        request_size: requestSize,
        response_size: responseSize,
      };
      _networkRequests.push(entry);
      if (_networkRequests.length > MAX_REQUESTS) _networkRequests.shift();
      return response;
    }, function(err) {
      const duration_ms = Date.now() - timestamp;
      const entry = {
        id: ++_netIdCounter,
        timestamp: timestamp,
        method: method,
        url: url,
        status: 0,
        duration_ms: duration_ms,
        error: err ? err.message : "Network error",
        request_size: requestSize,
        response_size: 0,
      };
      _networkRequests.push(entry);
      if (_networkRequests.length > MAX_REQUESTS) _networkRequests.shift();
      throw err;
    });
  };

  const _origXhrOpen = XMLHttpRequest.prototype.open;
  const _origXhrSend = XMLHttpRequest.prototype.send;

  XMLHttpRequest.prototype.open = function(method, url) {
    const result = _origXhrOpen.apply(this, arguments);
    this._hasgard = { method: String(method), url: String(url) };
    return result;
  };

  // Deliver a routed answer to an XHR without touching the network.
  //
  // The response fields are read-only accessors on the prototype, so they are
  // shadowed with own properties on this instance. That is confined to requests
  // a rule already matched: an unrouted XHR keeps the real object untouched.
  function deliverRoutedXhr(xhr, route, url, requestSize) {
    var timestamp = Date.now();
    var aborted = route.action === "abort";
    var define = function (name, value) {
      try {
        Object.defineProperty(xhr, name, { configurable: true, get: function () { return value; } });
      } catch (_) {}
    };
    define("readyState", 4);
    define("status", aborted ? 0 : route.status);
    define("statusText", aborted ? "" : "OK");
    define("responseURL", url);
    define("responseText", aborted ? "" : route.body);
    define("response", aborted ? "" : route.body);

    recordNetwork({
      id: ++_netIdCounter, timestamp: timestamp, method: route.method || "GET", url: url,
      status: aborted ? 0 : route.status, duration_ms: 0, error: aborted ? "Aborted by route" : null,
      request_size: requestSize, response_size: aborted ? 0 : route.body.length,
    });

    // Asynchronous, because a synchronous callback would run before the caller
    // had a chance to attach its own listeners -- which is not how any real
    // request behaves.
    var deliver = function () {
      try {
        xhr.dispatchEvent(new Event("readystatechange"));
        xhr.dispatchEvent(new Event(aborted ? "error" : "load"));
        xhr.dispatchEvent(new Event("loadend"));
      } catch (_) {}
    };
    if (typeof setTimeout === "function") setTimeout(deliver, 0);
    else deliver();
  }

  XMLHttpRequest.prototype.send = function(body) {
    if (this._hasgard) {
      var routed = matchRoute(this._hasgard.url, this._hasgard.method);
      if (routed) {
        deliverRoutedXhr(this, routed, this._hasgard.url, bodySize(body));
        return undefined;
      }
    }
    if (this._hasgard) {
      const hasgard = this._hasgard;
      const timestamp = Date.now();
      const requestSize = bodySize(body);
      let recorded = false;
      let onLoad, onError, onTimeout, onAbort;
      const cleanup = () => {
        this.removeEventListener("load", onLoad);
        this.removeEventListener("error", onError);
        this.removeEventListener("timeout", onTimeout);
        this.removeEventListener("abort", onAbort);
      };
      const pushEntry = (status, error, responseSize) => {
        if (recorded) return;
        recorded = true;
        cleanup();
        const entry = {
          id: ++_netIdCounter,
          timestamp: timestamp,
          method: hasgard.method,
          url: hasgard.url,
          status: status,
          duration_ms: Date.now() - timestamp,
          error: error,
          request_size: requestSize,
          response_size: responseSize,
        };
        _networkRequests.push(entry);
        if (_networkRequests.length > MAX_REQUESTS) _networkRequests.shift();
      };
      onLoad = () => {
        const cl = parseInt(this.getResponseHeader("Content-Length") || "0", 10) || 0;
        const r = this.response;
        const responseSize = (this.responseType === "" || this.responseType === "text")
          ? ((r && r.length) || cl)
          : (r instanceof ArrayBuffer ? r.byteLength : (r instanceof Blob ? r.size : cl));
        pushEntry(this.status, null, responseSize);
      };
      onError = () => { pushEntry(0, "Network error", 0); };
      onTimeout = () => { pushEntry(0, "Timeout", 0); };
      onAbort = () => { pushEntry(0, "Aborted", 0); };
      this.addEventListener("load", onLoad);
      this.addEventListener("error", onError);
      this.addEventListener("timeout", onTimeout);
      this.addEventListener("abort", onAbort);
      try {
        return _origXhrSend.apply(this, arguments);
      } catch (err) {
        cleanup();
        throw err;
      }
    }
    return _origXhrSend.apply(this, arguments);
  };

  function networkRequests(options) {
    let result = _networkRequests.slice();
    if (options) {
      if (options.filter) {
        result = result.filter(e => e.url.includes(options.filter));
      }
      if (options.failedOnly) {
        result = result.filter(e => e.status >= 400 || e.status === 0 || e.error);
      }
      if (options.sinceId) {
        result = result.filter(e => e.id > options.sinceId);
      }
      if (options.last) {
        result = result.slice(-options.last);
      }
    }
    return result;
  }

  function clearNetwork() {
    _networkRequests.length = 0;
    return { cleared: true };
  }

  function inputRole(el) {
    const t = (el.getAttribute("type") || "text").toLowerCase();
    switch (t) {
      case "hidden":
        return null;
      case "checkbox":
        return "checkbox";
      case "radio":
        return "radio";
      case "range":
        return "slider";
      case "submit":
      case "reset":
      case "button":
        return "button";
      default:
        return "textbox";
    }
  }

  function getRole(el) {
    const explicit = el.getAttribute("role");
    if (explicit) return explicit;
    if (el.tagName === "INPUT") return inputRole(el);
    return ROLE_MAP[el.tagName] || null;
  }

  function getName(el) {
    const label = el.getAttribute("aria-label");
    if (label) return label.trim().slice(0, 50);

    const labelledBy = el.getAttribute("aria-labelledby");
    if (labelledBy) {
      const parts = labelledBy
        .split(/\s+/)
        .map((id) => {
          const ref = document.getElementById(id);
          return ref ? ref.textContent : "";
        })
        .filter(Boolean);
      if (parts.length > 0) return parts.join(" ").trim().slice(0, 50);
    }

    if (el.tagName === "IMG") {
      const alt = el.getAttribute("alt");
      if (alt) return alt.trim().slice(0, 50);
    }

    if (el.tagName === "INPUT" || el.tagName === "TEXTAREA" || el.tagName === "SELECT") {
      if (el.labels && el.labels.length > 0) {
        const labelText = Array.from(el.labels)
          .map((label) => label.textContent || "")
          .join(" ")
          .replace(/\s+/g, " ")
          .trim();
        if (labelText) return labelText.slice(0, 50);
      }
      const placeholder = el.getAttribute("placeholder");
      if (placeholder) return placeholder.trim().slice(0, 50);
    }

    const text = el.textContent || "";
    const trimmed = text.replace(/\s+/g, " ").trim();
    return trimmed.slice(0, 50) || null;
  }

  function isInteractiveElement(el) {
    const tag = el.tagName;
    if (tag === "INPUT") {
      const t = (el.getAttribute("type") || "text").toLowerCase();
      return t !== "hidden";
    }
    if (
      tag === "BUTTON" ||
      tag === "SELECT" ||
      tag === "TEXTAREA" ||
      tag === "A"
    ) {
      return true;
    }
    if (el.hasAttribute("tabindex")) return true;
    const role = el.getAttribute("role");
    return role ? INTERACTIVE_ROLES.has(role) : false;
  }

  // Build one wire element and register its ref. `snapshot` and `query` both go
  // through here so the two can never drift into reporting different shapes for
  // the same node. Registration appends to `idMap`: only `snapshot` resets it,
  // which keeps the documented "refs are valid until the next snapshot"
  // contract true for query-issued refs as well.
  //
  // `existingRef` re-describes a node under the ref it already holds. `filter`
  // uses it because its input refs are registered by definition: minting new
  // ones would grow `idMap` on every link of a filter chain and make the same
  // element answer to a different name after each refinement.
  function describeElement(node, role, depth, existingRef) {
    let ref = existingRef;
    if (!ref) {
      refCounter++;
      ref = "e" + refCounter;
      idMap.set(ref, node);
    }

    const entry = { ref: ref, role: role, depth: depth };
    const name = getName(node);
    if (name) entry.name = name;
    // `value` is an IDL property whose type varies by element: a string for
    // form controls, but a number for `<li>` (ordinal), `<progress>`, and
    // `<meter>`. Coerce to string so the wire format matches the plugin's
    // `SnapshotElement.value: Option<String>` contract (#120).
    if (node.value !== undefined && node.value !== "") entry.value = String(node.value);
    if (node.tagName === "INPUT") {
      var inputType = (node.getAttribute("type") || "text").toLowerCase();
      if (inputType === "checkbox" || inputType === "radio") {
        entry.checked = node.checked;
      }
    }
    if (node.disabled) entry.disabled = true;
    return entry;
  }

  function snapshot(options) {
    const interactive = (options && options.interactive) || false;
    const selector = (options && options.selector) || null;
    const maxDepth = (options && options.depth != null) ? options.depth : 255;

    refCounter = 0;
    idMap.clear();

    const doc = frameDocument(options && options.frame);
    var root;
    if (selector) {
      try {
        root = doc.querySelector(selector);
      } catch (e) {
        throw new Error("Invalid selector: " + selector);
      }
    } else {
      root = doc.body;
    }
    if (!root) return { elements: [] };

    const elements = [];

    function walk(node, currentDepth) {
      if (currentDepth > maxDepth) return;
      if (node.nodeType !== Node.ELEMENT_NODE) return;

      const role = getRole(node);
      const isInteractive = isInteractiveElement(node);

      if (interactive && !isInteractive) {
        for (const child of node.children) {
          walk(child, currentDepth + 1);
        }
        return;
      }

      if (role) {
        elements.push(describeElement(node, role, currentDepth));
      }

      for (const child of node.children) {
        walk(child, currentDepth + 1);
      }
    }

    walk(root, 0);
    return { elements: elements };
  }

  // `selector` is a dimension so that every locator kind — CSS, role, or
  // text-ish — can be resolved down to refs by one code path. `filter` then
  // refines any of them uniformly instead of needing a per-kind implementation.
  var QUERY_DIMENSIONS = ["text", "label", "placeholder", "testid", "alt", "title", "selector"];

  function normalizeForMatch(value) {
    return String(value == null ? "" : value).replace(/\s+/g, " ").trim();
  }

  // Playwright's rule: non-exact is a case-insensitive substring, exact is a
  // case-sensitive equality. Whitespace is normalized on both sides either way.
  function matchesQuery(actual, wanted, exact) {
    var a = normalizeForMatch(actual);
    var w = normalizeForMatch(wanted);
    if (exact) return a === w;
    return a.toLowerCase().indexOf(w.toLowerCase()) !== -1;
  }

  function elementDepth(node) {
    var depth = 0;
    var current = node.parentElement;
    while (current && current !== document.body) {
      depth++;
      current = current.parentElement;
    }
    return depth;
  }

  // The accessible label of a form control, from every source Playwright's
  // getByLabel consults. Deliberately *not* getName(): that collapses six
  // sources into one and truncates to 50 characters, so a control carrying both
  // an aria-label and a <label> becomes findable by only one of them.
  function labelTextsOf(el) {
    var texts = [];
    var aria = el.getAttribute && el.getAttribute("aria-label");
    if (aria) texts.push(aria);
    var labelledBy = el.getAttribute && el.getAttribute("aria-labelledby");
    if (labelledBy) {
      labelledBy.split(/\s+/).forEach(function (id) {
        var ref = document.getElementById(id);
        if (ref) texts.push(ref.textContent || "");
      });
    }
    if (el.labels) {
      for (var i = 0; i < el.labels.length; i++) {
        texts.push(el.labels[i].textContent || "");
      }
    }
    return texts;
  }

  function queryCandidates(doc, by, value) {
    if (by === "selector") return doc.querySelectorAll(value);
    if (by === "placeholder") return doc.querySelectorAll("[placeholder]");
    if (by === "testid") return doc.querySelectorAll("[data-testid]");
    if (by === "alt") return doc.querySelectorAll("[alt]");
    if (by === "title") return doc.querySelectorAll("[title]");
    if (by === "label") return doc.querySelectorAll("input, textarea, select, button, meter, output, progress");
    return doc.querySelectorAll("*");
  }

  function queryMatches(el, by, value, exact) {
    // `querySelectorAll` already applied the predicate for this dimension.
    if (by === "selector") return true;
    if (by === "placeholder") return matchesQuery(el.getAttribute("placeholder"), value, exact);
    if (by === "alt") return matchesQuery(el.getAttribute("alt"), value, exact);
    if (by === "title") return matchesQuery(el.getAttribute("title"), value, exact);
    // A test id is an identifier, not prose: substring matching on it invites
    // "save" quietly selecting "save-draft", so this dimension is always exact.
    if (by === "testid") return normalizeForMatch(el.getAttribute("data-testid")) === normalizeForMatch(value);
    if (by === "label") {
      return labelTextsOf(el).some(function (text) {
        return matchesQuery(text, value, exact);
      });
    }
    return matchesQuery(el.textContent, value, exact);
  }

  function query(params) {
    var by = params && params.by;
    if (QUERY_DIMENSIONS.indexOf(by) === -1) {
      throw new Error("query: 'by' must be one of " + QUERY_DIMENSIONS.join(", ") + ", got: " + String(by).slice(0, 64));
    }
    if (params.value == null) throw new Error("query requires a 'value'");
    var exact = !!params.exact;

    var matched = [];
    var candidates = queryCandidates(frameDocument(params.frame), by, params.value);
    for (var i = 0; i < candidates.length; i++) {
      if (queryMatches(candidates[i], by, params.value, exact)) matched.push(candidates[i]);
    }

    // Text matching walks every element, so an ancestor matches whenever its
    // descendant does — <html> and <body> would match everything. Keep only the
    // innermost matches, which is the element a user would point at.
    if (by === "text" && matched.length > 1) {
      matched = matched.filter(function (el) {
        return !matched.some(function (other) {
          return other !== el && el.contains(other);
        });
      });
    }

    return {
      elements: matched.map(function (el) {
        return describeElement(el, getRole(el) || "generic", elementDepth(el));
      })
    };
  }

  // Refine an already-resolved set of refs by their rendered text.
  //
  // Filtering by ref rather than re-running the original locator keeps this one
  // implementation valid for every locator kind, and keeps `snapshot` free of a
  // per-element text field that would bloat every unrelated call.
  //
  // `hasText` keeps an element whose subtree text matches; `hasNotText` drops
  // it. Both may be supplied — an element must satisfy each to survive, which
  // is what makes `filter({hasText}).filter({hasNotText})` compose.
  function filterElements(params) {
    var refs = (params && params.refs) || [];
    if (!Array.isArray(refs)) throw new Error("filter requires a 'refs' array");
    var exact = !!(params && params.exact);
    var hasText = params ? params.hasText : null;
    var hasNotText = params ? params.hasNotText : null;
    if (hasText == null && hasNotText == null) {
      throw new Error("filter requires 'hasText' or 'hasNotText'");
    }

    var kept = [];
    for (var i = 0; i < refs.length; i++) {
      // A stale ref means the DOM moved under the caller between resolution and
      // refinement. Dropping it silently would turn that race into a wrong
      // answer, so surface it the same way acting on a stale ref would.
      var el = requireEl(refs[i]);
      var text = el.textContent;
      if (hasText != null && !matchesQuery(text, hasText, exact)) continue;
      if (hasNotText != null && matchesQuery(text, hasNotText, exact)) continue;
      kept.push({ el: el, ref: refs[i] });
    }

    return {
      elements: kept.map(function (entry) {
        return describeElement(entry.el, getRole(entry.el) || "generic", elementDepth(entry.el), entry.ref);
      })
    };
  }

  // Resolve the document a frame-scoped operation should query.
  //
  // `frame` is a chain of CSS selectors, one per nesting level, so an element
  // two iframes deep names both hosts. Omitting it keeps the main document, so
  // every existing caller is unaffected.
  //
  // A cross-origin frame exposes a null `contentDocument`. The same-origin
  // policy binds injected script exactly as it binds the page's own, so this is
  // a wall rather than a gap -- say so, instead of reporting the empty result
  // that a silent fallback to the main document would produce.
  function frameDocument(frame) {
    if (frame == null) return document;
    var chain = Array.isArray(frame) ? frame : [frame];
    var doc = document;
    for (var i = 0; i < chain.length; i++) {
      var selector = chain[i];
      if (typeof selector !== "string" || selector === "") {
        throw new Error("frame must be a CSS selector, or an array of them for nested frames");
      }
      var host = doc.querySelector(selector);
      if (!host) throw new Error("No frame matches selector: " + selector);
      if (!("contentDocument" in host)) {
        var tag = String(host.tagName || "?").toLowerCase();
        throw new Error("Selector " + selector + " matched a <" + tag + ">, expected an <iframe> or <frame>");
      }
      var inner = host.contentDocument;
      if (!inner) {
        throw new Error(
          "Frame " + selector + " is cross-origin, so its document cannot be reached from page script. " +
          "Same-origin frames only."
        );
      }
      doc = inner;
    }
    return doc;
  }

  function resolve(ref) {
    return idMap.get(ref) || null;
  }

  function requireEl(ref) {
    const el = idMap.get(ref);
    if (!el) throw new Error("Unknown ref: " + ref);
    return el;
  }

  // `index` selects among *all* selector matches, so an ordinal locator
  // (`nth`/`first`/`last`) resolves in the same round trip that acts on the
  // element. Counting first and indexing second would let the DOM change in
  // between and silently act on a different node. A negative index counts back
  // from the end, which is what makes `last()` a single call.
  function selectorAt(doc, selector, index) {
    var matches = doc.querySelectorAll(selector);
    var position = index < 0 ? matches.length + index : index;
    var el = matches[position];
    if (!el) {
      throw new Error(
        "No element at index " + index + " for selector: " + selector + " (" + matches.length + " matched)"
      );
    }
    return el;
  }

  function resolveTarget(params) {
    // A ref already identifies one node, whichever document minted it, so the
    // frame chain is not consulted -- re-resolving would only be a chance to
    // disagree with the snapshot that produced the ref.
    if (params.ref) return requireEl(params.ref);
    var doc = frameDocument(params.frame);
    if (params.selector) {
      if (params.index != null) {
        if (typeof params.index !== "number" || !Number.isInteger(params.index)) {
          throw new Error("index must be an integer");
        }
        return selectorAt(doc, params.selector, params.index);
      }
      var el = doc.querySelector(params.selector);
      if (!el) throw new Error("No element matches selector: " + params.selector);
      return el;
    }
    if (params.x != null && params.y != null) {
      // Coordinates are relative to the frame's own viewport, matching how the
      // frame's scripts see them.
      var pointEl = doc.elementFromPoint(params.x, params.y);
      if (!pointEl) throw new Error("No element at (" + params.x + "," + params.y + ")");
      return pointEl;
    }
    throw new Error("No ref, selector, or coordinates provided");
  }

  function dispatchPointerEvent(el, type, options) {
    const init = Object.assign({
      bubbles: true,
      cancelable: true,
      composed: true,
      pointerId: 1,
      pointerType: "mouse",
      isPrimary: true,
      button: 0,
      buttons: type === "pointerdown" ? 1 : 0,
      view: window,
      clientX: 0,
      clientY: 0,
    }, options || {});

    if (typeof PointerEvent === "function") {
      return el.dispatchEvent(new PointerEvent(type, init));
    }

    const event = new MouseEvent(type, init);
    try {
      Object.defineProperty(event, "pointerId", { value: init.pointerId });
      Object.defineProperty(event, "pointerType", { value: init.pointerType });
      Object.defineProperty(event, "isPrimary", { value: init.isPrimary });
    } catch (_) {}
    return el.dispatchEvent(event);
  }

  // MouseEvent.button (which one changed state) and MouseEvent.buttons (bitmask
  // of what is held) use different numbering; a right press is button 2 and
  // buttons 2, but a middle press is button 1 and buttons 4.
  const MOUSE_BUTTONS = {
    left: { button: 0, mask: 1 },
    middle: { button: 1, mask: 4 },
    right: { button: 2, mask: 2 },
  };

  const MODIFIER_FLAGS = {
    Alt: "altKey",
    Control: "ctrlKey",
    Meta: "metaKey",
    Shift: "shiftKey",
  };

  function modifierInit(modifiers) {
    const init = { altKey: false, ctrlKey: false, metaKey: false, shiftKey: false };
    if (!modifiers) return init;
    if (!Array.isArray(modifiers)) throw new Error("modifiers must be an array");
    for (var i = 0; i < modifiers.length; i++) {
      const flag = MODIFIER_FLAGS[modifiers[i]];
      if (!flag) {
        throw new Error(
          "Unknown modifier " + JSON.stringify(modifiers[i]) +
          ". Expected one of Alt, Control, Meta, Shift"
        );
      }
      init[flag] = true;
    }
    return init;
  }

  function mouseButton(name) {
    if (name == null) return MOUSE_BUTTONS.left;
    const spec = MOUSE_BUTTONS[name];
    if (!spec) {
      throw new Error(
        "Unknown button " + JSON.stringify(name) + ". Expected left, middle, or right"
      );
    }
    return spec;
  }

  // Where inside the element the pointer lands. `position` is element-relative,
  // matching Playwright; `params.x/y` stay viewport-absolute because they are
  // also the coordinate *target*, resolved before we ever see the element.
  function clickPoint(el, params) {
    const rect = el.getBoundingClientRect();
    if (params.position) {
      const px = params.position.x;
      const py = params.position.y;
      if (typeof px !== "number" || typeof py !== "number") {
        throw new Error("position must be { x: number, y: number }");
      }
      return { x: rect.left + px, y: rect.top + py };
    }
    return {
      x: params.x != null ? params.x : rect.left + rect.width / 2,
      y: params.y != null ? params.y : rect.top + rect.height / 2,
    };
  }

  function click(params) {
    const el = resolveTarget(params);
    el.scrollIntoView({ behavior: "instant", block: "center", inline: "center" });
    const point = clickPoint(el, params);
    const x = point.x;
    const y = point.y;
    const button = mouseButton(params.button);
    const modifiers = modifierInit(params.modifiers);
    const clickCount = params.clickCount != null ? params.clickCount : 1;
    if (typeof clickCount !== "number" || clickCount < 1 || clickCount % 1 !== 0) {
      throw new Error("clickCount must be a positive integer");
    }
    const mouseInit = function(options) {
      return Object.assign({
        bubbles: true,
        cancelable: true,
        composed: true,
      }, options);
    };

    // A double click is one gesture, not two: the browser raises detail 1 then
    // detail 2 on the *same* element, then a single dblclick. Replaying click()
    // twice would reset detail to 1 and never produce dblclick, so listeners
    // that distinguish the two would see the wrong thing.
    for (var n = 1; n <= clickCount; n++) {
      const downInit = Object.assign({
        clientX: x,
        clientY: y,
        button: button.button,
        buttons: button.mask,
        detail: n,
        view: window,
      }, modifiers);
      const upInit = Object.assign({}, downInit, { buttons: 0 });

      const pointerDownOk = dispatchPointerEvent(el, "pointerdown", downInit);
      if (pointerDownOk) {
        const mouseDownOk = el.dispatchEvent(new MouseEvent("mousedown", mouseInit(downInit)));
        if (mouseDownOk && typeof el.focus === "function") {
          el.focus();
        }
      }
      dispatchPointerEvent(el, "pointerup", upInit);
      if (pointerDownOk) {
        el.dispatchEvent(new MouseEvent("mouseup", mouseInit(upInit)));
      }
      // Only the primary button produces a `click` event. A right press raises
      // `contextmenu` instead, and a middle press raises `auxclick` -- binding a
      // right-click menu to `click` is exactly the bug this lets tests catch.
      if (button.button === 0) {
        dispatchPointerEvent(el, "click", upInit);
      } else {
        el.dispatchEvent(new MouseEvent("auxclick", mouseInit(upInit)));
        if (button.button === 2) {
          el.dispatchEvent(new MouseEvent("contextmenu", mouseInit(upInit)));
        }
      }
    }

    if (clickCount >= 2) {
      el.dispatchEvent(new MouseEvent("dblclick", mouseInit(Object.assign({
        clientX: x,
        clientY: y,
        button: button.button,
        buttons: 0,
        detail: 2,
        view: window,
      }, modifiers))));
    }
    return { ok: true };
  }

  // Resolve the native `value` setter for the element's actual prototype.
  // Frameworks (React, Preact-signals, Vue) sometimes install an instance-level
  // setter that swallows programmatic writes; preferring the prototype setter
  // bypasses that override and keeps WebIDL [LegacyUnforgeable] brand checks
  // happy on <input>, <textarea>, and <select> alike (#85).
  function nativeValueSetter(el) {
    const proto = Object.getPrototypeOf(el);
    const desc = proto && Object.getOwnPropertyDescriptor(proto, "value");
    return desc && typeof desc.set === "function" ? desc.set : null;
  }

  function fill(params) {
    const el = resolveTarget(params);
    el.focus();
    const setter = nativeValueSetter(el);
    if (setter) {
      setter.call(el, params.value);
    } else {
      el.value = params.value;
    }
    el.dispatchEvent(new Event("input", { bubbles: true }));
    el.dispatchEvent(new Event("change", { bubbles: true }));
    return { ok: true };
  }

  function typeText(params) {
    const el = resolveTarget(params);
    el.focus();
    const setter = nativeValueSetter(el);
    for (const ch of params.text) {
      el.dispatchEvent(new KeyboardEvent("keydown", { key: ch, bubbles: true }));
      if (setter) {
        setter.call(el, el.value + ch);
      } else {
        el.value += ch;
      }
      el.dispatchEvent(new InputEvent("input", { data: ch, inputType: "insertText", bubbles: true }));
      el.dispatchEvent(new KeyboardEvent("keyup", { key: ch, bubbles: true }));
    }
    return { ok: true };
  }

  function select(params) {
    const el = resolveTarget(params);
    // The CLI/tool contract is "select acts on <select>". Before the
    // nativeValueSetter refactor, this guarantee fell out of the WebIDL brand
    // check on `HTMLSelectElement.prototype.value` (calling that setter on an
    // <input>/<textarea> threw). The new helper picks the setter from the
    // element's own prototype, so a misrouted selector would now silently
    // succeed against a non-<select> and report ok while no option was
    // actually selected. Re-introduce the type guard with a tag-based check
    // (realm-safe): an `instanceof` constructor check would be tied to the
    // host realm and would reject valid <select> elements coming from another
    // window/iframe realm, which is exactly the case nativeValueSetter was
    // built to support.
    const tag = el && el.tagName ? String(el.tagName).toLowerCase() : "";
    if (tag !== "select") {
      const reported = (tag || String(el)).slice(0, 64);
      throw new Error("select requires a <select> element, got: " + reported);
    }
    // Resolve the target option before mutating anything. Setting
    // `HTMLSelectElement.value` to a string that matches no option `value`
    // silently yields `value=""` / `selectedIndex=-1` per the DOM spec, so
    // "set then trust" reports success on a no-op (#113). Match the option
    // first — by `value`, then by visible label — and error if none matches so
    // a reported `ok` always means an option was actually selected.
    const wanted = String(params.value);
    const options = Array.from(el.options || []);
    const matched =
      options.find((o) => o.value === wanted) ||
      options.find((o) => (o.text || "").trim() === wanted.trim());
    if (!matched) {
      throw new Error("select: no option matches " + JSON.stringify(params.value));
    }
    const setter = nativeValueSetter(el);
    if (setter) {
      setter.call(el, matched.value);
    } else {
      el.value = matched.value;
    }
    el.dispatchEvent(new Event("change", { bubbles: true }));
    return { ok: true };
  }

  // Without `checked` this toggles, which is the documented CLI contract
  // ("Toggle a checkbox"). With an explicit `checked` it drives the box to that
  // state and is a no-op when it is already there, which is what a Playwright
  // `check()`/`uncheck()` promises. A toggle cannot express either of those:
  // running it twice undoes itself, so a retry silently inverts the result.
  function check(params) {
    const el = resolveTarget(params);
    if (params.checked != null) {
      if (typeof params.checked !== "boolean") {
        throw new Error("check: 'checked' must be a boolean");
      }
      if (el.checked === params.checked) return { ok: true };
      el.checked = params.checked;
    } else {
      el.checked = !el.checked;
    }
    el.dispatchEvent(new Event("change", { bubbles: true }));
    return { ok: true };
  }

  function disabled(params) {
    const el = resolveTarget(params);
    const aria = typeof el.getAttribute === "function" ? el.getAttribute("aria-disabled") : null;
    return { disabled: !!el.disabled || aria === "true" };
  }

  function boundingBox(params) {
    const rect = resolveTarget(params).getBoundingClientRect();
    return { x: rect.left, y: rect.top, width: rect.width, height: rect.height };
  }

  function focus(params) {
    const el = resolveTarget(params);
    if (typeof el.focus !== "function") throw new Error("focus: element is not focusable");
    el.focus();
    return { ok: true };
  }

  function blur(params) {
    const el = resolveTarget(params);
    if (typeof el.blur !== "function") throw new Error("blur: element cannot be blurred");
    el.blur();
    return { ok: true };
  }

  function hover(params) {
    const el = resolveTarget(params);
    const rect = el.getBoundingClientRect();
    const x = params.x != null ? params.x : rect.left + rect.width / 2;
    const y = params.y != null ? params.y : rect.top + rect.height / 2;
    const init = { clientX: x, clientY: y, button: 0, buttons: 0, view: window };
    const mouseInit = Object.assign({ bubbles: true, cancelable: true, composed: true }, init);

    dispatchPointerEvent(el, "pointerover", init);
    // `pointerenter`/`mouseenter` do not bubble, matching the real event model.
    dispatchPointerEvent(el, "pointerenter", Object.assign({}, init, { bubbles: false }));
    el.dispatchEvent(new MouseEvent("mouseover", mouseInit));
    el.dispatchEvent(new MouseEvent("mouseenter", Object.assign({}, mouseInit, { bubbles: false })));
    dispatchPointerEvent(el, "pointermove", init);
    el.dispatchEvent(new MouseEvent("mousemove", mouseInit));
    return { ok: true };
  }

  // Kept as its own command for the CLI and for callers that predate
  // `click({ clickCount })`; the gesture itself now has one implementation.
  function dblclick(params) {
    return click(Object.assign({}, params, { clickCount: 2 }));
  }

  function scroll(options) {
    const dir = (options && options.direction) || "down";
    const amount = (options && options.amount) || 300;
    // Route through `resolveTarget` rather than `ref` alone so a selector or
    // point locator can scroll its own element; with `ref`-only, every
    // selector-based caller silently scrolled the document instead.
    const hasTarget =
      options && (options.ref || options.selector || (options.x != null && options.y != null));
    const target = hasTarget ? resolveTarget(options) : window;

    if (dir === "top") {
      if (target === window) {
        target.scrollTo(window.scrollX, 0);
      } else {
        target.scrollTop = 0;
      }
      return { ok: true };
    }
    if (dir === "bottom") {
      if (target === window) {
        const docEl = document.documentElement;
        const body = document.body;
        const fullHeight = Math.max(
          docEl ? docEl.scrollHeight : 0,
          body ? body.scrollHeight : 0
        );
        const viewportHeight = docEl ? docEl.clientHeight : window.innerHeight;
        const max = fullHeight - viewportHeight;
        target.scrollTo(window.scrollX, Math.max(0, max));
      } else {
        target.scrollTop = Math.max(0, target.scrollHeight - target.clientHeight);
      }
      return { ok: true };
    }
    if (dir !== "up" && dir !== "down" && dir !== "left" && dir !== "right") {
      const safeDir = String(dir).slice(0, 64);
      throw new Error("Unknown scroll direction: " + safeDir + " (expected up|down|left|right|top|bottom)");
    }
    const dx = (dir === "left" ? -amount : dir === "right" ? amount : 0);
    const dy = (dir === "up" ? -amount : dir === "down" ? amount : 0);
    target.scrollBy(dx, dy);
    return { ok: true };
  }

  function drag(params) {
    var source = resolveTarget(params.source || params);
    var sourceRect = source.getBoundingClientRect();
    var startX = sourceRect.left + sourceRect.width / 2;
    var startY = sourceRect.top + sourceRect.height / 2;

    var endX, endY, dropTarget;

    if (params.target) {
      dropTarget = resolveTarget(params.target);
      var targetRect = dropTarget.getBoundingClientRect();
      endX = targetRect.left + targetRect.width / 2;
      endY = targetRect.top + targetRect.height / 2;
    } else if (params.offset) {
      // elementFromPoint below is viewport-bound: a start point outside the
      // viewport would make the lookup miss (#130). Scroll the source into
      // view first, like a user would, then recompute the start point.
      // "instant" so a page-level `scroll-behavior: smooth` cannot defer the
      // scroll past the synchronous rect recompute.
      var docEl = document.documentElement;
      var viewportWidth = docEl.clientWidth;
      var viewportHeight = docEl.clientHeight;
      if (startX < 0 || startY < 0 || startX >= viewportWidth || startY >= viewportHeight) {
        source.scrollIntoView({ behavior: "instant", block: "center", inline: "center" });
        sourceRect = source.getBoundingClientRect();
        startX = sourceRect.left + sourceRect.width / 2;
        startY = sourceRect.top + sourceRect.height / 2;
      }
      var offsetX = params.offset.x || 0;
      var offsetY = params.offset.y || 0;
      endX = startX + offsetX;
      endY = startY + offsetY;
      dropTarget = document.elementFromPoint(endX, endY);
      if (!dropTarget) {
        var pointLabel = "(" + Math.round(endX) + "," + Math.round(endY) + ")";
        if (endX < 0 || endY < 0 || endX >= viewportWidth || endY >= viewportHeight) {
          throw new Error("Drop point " + pointLabel + " is outside the viewport (" +
            viewportWidth + "x" + viewportHeight + ") — reduce the offset");
        }
        throw new Error("No element at drop point " + pointLabel +
          " for offset (" + offsetX + "," + offsetY + ")");
      }
    } else {
      throw new Error("drag requires target or offset");
    }

    var dt = typeof DataTransfer === "function" ? new DataTransfer() : new ClipboardEvent("").clipboardData;
    source.dispatchEvent(new MouseEvent("mousedown", { clientX: startX, clientY: startY, bubbles: true }));
    source.dispatchEvent(new DragEvent("dragstart", { clientX: startX, clientY: startY, dataTransfer: dt, bubbles: true }));
    source.dispatchEvent(new DragEvent("dragleave", { clientX: endX, clientY: endY, dataTransfer: dt, bubbles: true }));
    dropTarget.dispatchEvent(new DragEvent("dragenter", { clientX: endX, clientY: endY, dataTransfer: dt, bubbles: true, cancelable: true }));
    dropTarget.dispatchEvent(new DragEvent("dragover", { clientX: endX, clientY: endY, dataTransfer: dt, bubbles: true, cancelable: true }));
    dropTarget.dispatchEvent(new DragEvent("drop", { clientX: endX, clientY: endY, dataTransfer: dt, bubbles: true, cancelable: true }));
    source.dispatchEvent(new DragEvent("dragend", { clientX: endX, clientY: endY, dataTransfer: dt, bubbles: true }));
    return { ok: true };
  }

  function drop(params) {
    var el = resolveTarget(params);
    var rect = el.getBoundingClientRect();
    var x = rect.left + rect.width / 2;
    var y = rect.top + rect.height / 2;
    var dt = buildFileList(params.files);

    el.dispatchEvent(new DragEvent("dragenter", { clientX: x, clientY: y, dataTransfer: dt, bubbles: true, cancelable: true }));
    el.dispatchEvent(new DragEvent("dragover", { clientX: x, clientY: y, dataTransfer: dt, bubbles: true, cancelable: true }));
    el.dispatchEvent(new DragEvent("drop", { clientX: x, clientY: y, dataTransfer: dt, bubbles: true, cancelable: true }));
    return { ok: true };
  }

  // Turn `{name, data}` payloads (data is base64) into real `File` objects.
  // Shared by `drop` and `setInputFiles` so both produce identical `FileList`
  // contents for the same input.
  function buildFileList(files) {
    var dt = typeof DataTransfer === "function" ? new DataTransfer() : new ClipboardEvent("").clipboardData;
    for (var i = 0; i < (files || []).length; i++) {
      var f = files[i];
      var binary = atob(f.data);
      var bytes = new Uint8Array(binary.length);
      for (var j = 0; j < binary.length; j++) bytes[j] = binary.charCodeAt(j);
      dt.items.add(new File([bytes], f.name, { type: f.type || "application/octet-stream" }));
    }
    return dt;
  }

  // Populate an `<input type="file">` without a native file chooser, which a
  // headless-less webview gives no way to drive.
  //
  // `input.files` is settable from a `DataTransfer`'s `FileList` — the same
  // mechanism a real drop uses — so the page sees a genuine `FileList` and its
  // `change` handler cannot tell this from a user's pick. An empty array clears
  // the selection, which is how Playwright spells "deselect everything".
  function setInputFiles(params) {
    var el = resolveTarget(params);
    if (el.tagName !== "INPUT" || String(el.type).toLowerCase() !== "file") {
      // Assigning `.files` to anything else silently no-ops, so the caller would
      // get `ok: true` and an unchanged page.
      throw new Error(
        "setInputFiles requires an <input type=\"file\">, got: " +
          String(el.tagName).toLowerCase() +
          (el.type ? '[type="' + String(el.type).slice(0, 32) + '"]' : "")
      );
    }
    var files = (params && params.files) || [];
    if (!el.multiple && files.length > 1) {
      // The browser would keep only the last file; failing loudly beats
      // silently dropping the caller's other files.
      throw new Error("setInputFiles got " + files.length + " files but the input is not [multiple]");
    }
    el.files = buildFileList(files).files;
    el.dispatchEvent(new Event("input", { bubbles: true }));
    el.dispatchEvent(new Event("change", { bubbles: true }));
    return { ok: true, count: el.files.length };
  }

  // Scroll by wheel, reproducing the browser's own two-step: the page sees a
  // `wheel` event first and may cancel it; only if it does not does the scroll
  // actually happen.
  //
  // A synthetic `WheelEvent` alone would fire listeners but never move the
  // scrollport (untrusted events do not drive default actions), so a caller
  // testing an infinite-scroll list would see handlers run and nothing load.
  // Applying the scroll ourselves — and only when the event was not
  // `preventDefault`ed — keeps both halves of the contract.
  function wheel(params) {
    var hasTarget =
      params && (params.ref || params.selector || (params.x != null && params.y != null));
    var el = hasTarget ? resolveTarget(params) : document.scrollingElement || document.documentElement;
    var deltaX = (params && params.deltaX) || 0;
    var deltaY = (params && params.deltaY) || 0;
    var rect = el.getBoundingClientRect ? el.getBoundingClientRect() : { left: 0, top: 0, width: 0, height: 0 };

    var notCancelled = el.dispatchEvent(
      new WheelEvent("wheel", {
        deltaX: deltaX,
        deltaY: deltaY,
        deltaMode: 0,
        clientX: rect.left + rect.width / 2,
        clientY: rect.top + rect.height / 2,
        bubbles: true,
        cancelable: true,
        composed: true,
        view: window
      })
    );

    if (notCancelled) el.scrollBy(deltaX, deltaY);
    return { ok: true, defaultPrevented: !notCancelled };
  }

  function text(params) {
    return resolveTarget(params).textContent || "";
  }

  function html(params) {
    if (params && (params.ref || params.selector)) {
      return resolveTarget(params).innerHTML;
    }
    return document.documentElement.innerHTML;
  }

  function value(params) {
    return resolveTarget(params).value || "";
  }

  function attrs(params) {
    const el = resolveTarget(params);
    const result = {};
    for (const attr of el.attributes) {
      result[attr.name] = attr.value;
    }
    return result;
  }

  function visible(params) {
    const el = resolveTarget(params);
    const style = getComputedStyle(el);
    const isVisible =
      style.display !== "none" &&
      style.visibility !== "hidden" &&
      style.opacity !== "0" &&
      (el.offsetWidth > 0 || el.offsetHeight > 0);
    return { visible: isVisible };
  }

  function count(params) {
    if (!params || !params.selector) {
      throw new Error("count requires a selector parameter");
    }
    return { count: frameDocument(params.frame).querySelectorAll(params.selector).length };
  }

  function checked(params) {
    const el = resolveTarget(params);
    return { checked: !!el.checked };
  }

  function navigate(options) {
    const url = options && options.url;
    if (url) window.location.href = url;
    return { ok: true };
  }

  function url() {
    return window.location.href;
  }

  function title() {
    return document.title;
  }

  function state() {
    return {
      url: window.location.href,
      title: document.title,
      readyState: document.readyState,
      viewport: { width: window.innerWidth, height: window.innerHeight },
      scroll: { x: window.scrollX, y: window.scrollY },
    };
  }

  function evalScript(options) {
    var script = options && options.script;
    if (!script) throw new Error("No script provided");
    // Stage 1 — expression compile.
    // `{a:1}` keeps its object-literal semantics (not a labeled block) and
    // `class C {}` evaluates to the constructor. Keep compilation separate
    // from execution: a runtime SyntaxError from e.g. `JSON.parse('x')` must
    // propagate, not trigger a fallback — otherwise the script would run twice.
    var expr;
    try {
      expr = new Function("return (\n" + script + "\n)");
    } catch (e1) {
      if (!(e1 instanceof SyntaxError)) throw e1;
      // The newlines around `script` in every wrapper below isolate user
      // tokens from generated closing punctuation. Without them, a trailing
      // `// comment` on the last line of the user script swallows `))()` or
      // `})()` and the wrapper fails to compile.
      if (hasTopLevelAwait(script)) {
        // Stage 2 — async-expression compile (#79).
        // Handles top-level `await` in expression position, e.g.
        // `await Promise.resolve("hi")` or `await fetch(...).then(r => r.json())`.
        // Returns a Promise; the Rust wrapper already awaits it.
        try {
          var asyncExpr = new Function(
            "return (async () => (\n" + script + "\n))()"
          );
          return asyncExpr();
        } catch (e2) {
          if (!(e2 instanceof SyntaxError)) throw e2;
        }
        // Stage 3 — async-statement IIFE (#79).
        // Top-level `await` is not allowed in plain script context, so when
        // the user script does not fit an expression but does contain
        // `await`, we wrap it in an async statement IIFE. The user must use
        // `return` to surface a value; otherwise the result is `null`.
        try {
          var asyncStmt = new Function(
            "return (async () => {\n" + script + "\n})()"
          );
          return asyncStmt();
        } catch (e3) {
          if (!(e3 instanceof SyntaxError)) throw e3;
          throw new SyntaxError(
            "top-level await detected but the script could not be auto-wrapped. " +
              "Wrap explicitly: (async () => { /* ...; */ return value; })() — " +
              "see docs/reference/cli.md"
          );
        }
      }
      // Stage 4 — statement fallback. Indirect eval runs in global script
      // context and returns the completion value of the last expression (#46).
      var indirectEval = eval;
      return indirectEval(script);
    }
    return expr();
  }

  // Heuristic top-level `await` detector. Strips comments and single/double
  // quoted strings, masks property accesses (`obj.await`), then peels
  // nested `function`/arrow-with-block bodies so an `await` buried in a
  // nested function does not trigger top-level detection — otherwise a
  // statement script like `async function f(){ await 1; } f(); 1+1`
  // would be mis-routed to the async-statement wrapper and lose its
  // completion value.
  //
  // Three deliberate non-strips, each documented because the alternative
  // is worse:
  //
  //   * Template literals are NOT stripped. Stripping them with a single-pass
  //     regex cannot balance nested `${...}` braces, and it also drops a real
  //     `` `${await x}` ``. Leaving them in only causes false positives on a
  //     literal like `` `await` ``, which is harmless: the script still runs
  //     wrapped in an async IIFE, only the completion-value contract changes
  //     (the user must use an explicit `return` to surface a value, which is
  //     documented in cli.md).
  //   * Regex literals (`/await/`) are NOT stripped either. A naive
  //     `\/.../[flags]*` match also swallows division expressions like
  //     `a / await foo / c`, which would silently hide a real top-level
  //     `await` and break the auto-wrap fallback. False positives from a
  //     literal `/await/` regex are again harmless wraps.
  //   * Methods inside `class` bodies are NOT recognised — the function-body
  //     strip only matches `function`/arrow blocks. A class with an `await`
  //     inside an `async` method would be flagged. Niche enough that
  //     dragging in keyword-aware parsing isn't worth it.
  //
  // For scripts larger than 100 KB the strip pass is skipped to bound
  // worst-case scan time; the raw `await` test is used instead.
  function hasTopLevelAwait(src) {
    if (src.length > 100000) return /\bawait\b/.test(src);
    // Strip quoted strings BEFORE comments, otherwise a URL like
    // `"http://example.com"` looks like a `//` line comment and the rest
    // of the line — including any real `await` — gets deleted, producing a
    // false negative. Same for `"/* not a comment */"` block markers
    // embedded in a string.
    var stripped = src
      .replace(/'(?:[^'\\]|\\.)*'/g, "''")
      .replace(/"(?:[^"\\]|\\.)*"/g, '""')
      .replace(/\/\*[\s\S]*?\*\//g, "")
      .replace(/\/\/[^\n]*/g, "")
      .replace(/\.\s*await\b/g, ".__prop");
    // Peel innermost `function`/arrow bodies, both block-bodied
    // (`() => { ... }`) and concise (`() => expr`). Each iteration matches
    // bodies with no nested braces, so doubly-nested functions take two
    // passes. Cap the iteration count so a pathological input cannot loop
    // forever. Concise arrow bodies stop at any of `;,){}\n` to avoid
    // chewing through the rest of the script.
    for (var k = 0; k < 6; k++) {
      var prev = stripped;
      stripped = stripped
        .replace(/\bfunction\s*\*?\s*[\w$]*\s*\([^()]*\)\s*\{[^{}]*\}/g, "fn()")
        .replace(/\([^()]*\)\s*=>\s*\{[^{}]*\}/g, "fn()")
        .replace(/\b[\w$]+\s*=>\s*\{[^{}]*\}/g, "fn()")
        .replace(/\([^()]*\)\s*=>\s*[^{};,)\n]+/g, "fn()")
        .replace(/\b[\w$]+\s*=>\s*[^{};,)\n]+/g, "fn()");
      if (stripped === prev) break;
    }
    return /\bawait\b/.test(stripped);
  }

  // A predicate can flip without any DOM mutation — a timer firing, a fetch
  // resolving, a store updating — so this polls instead of reusing waitFor's
  // MutationObserver, which would hang on exactly those cases. A throwing
  // predicate rejects rather than being retried: swallowing the error would
  // turn a genuine bug into a timeout with no clue what happened.
  function waitForExpression(expression, timeout, poll) {
    return new Promise(function (res, rej) {
      var settled = false;
      var poller = null;

      function stop() {
        settled = true;
        clearTimeout(timer);
        if (poller !== null) clearInterval(poller);
      }

      function finish(value) {
        if (settled) return;
        stop();
        res({ found: true, value: serializeArg(value) });
      }

      function fail(err) {
        if (settled) return;
        stop();
        rej(new Error("wait expression threw: " + (err && err.message ? err.message : String(err))));
      }

      var timer = setTimeout(function () {
        if (settled) return;
        stop();
        rej(new Error("Timeout waiting for expression: " + String(expression).slice(0, 200)));
      }, timeout);

      function attempt() {
        var value;
        try {
          value = (0, eval)(expression);
        } catch (e) {
          fail(e);
          return;
        }
        if (value && typeof value.then === "function") {
          value.then(function (resolved) {
            if (resolved) finish(resolved);
          }, fail);
          return;
        }
        if (value) finish(value);
      }

      attempt();
      if (!settled) poller = setInterval(attempt, poll);
    });
  }

  function waitFor(options) {
    var selector = options && options.selector;
    var ref = options && options.ref;
    var expression = options && options.expression;
    var gone = (options && options.gone) || false;
    // Use a `!= null` check (matching `watch` below) rather than `|| 10000` so
    // an explicit `timeout: 0` resolves immediately instead of silently
    // expanding to 10 s — the latter desynchronised the Rust channel padded
    // via `BRIDGE_TIMEOUT_BUFFER_MS` and surfaced the generic "eval timed out"
    // instead of the bridge's own rejection.
    var timeout = (options && options.timeout != null) ? options.timeout : 10000;

    if (!selector && !ref && !expression) {
      return Promise.reject(
        new Error(
          "waitFor requires 'selector', 'ref', or 'expression' (use --selector for CSS, @id for snapshot ref)"
        )
      );
    }

    if (expression) {
      var poll = (options && options.poll != null) ? options.poll : 50;
      return waitForExpression(expression, timeout, poll);
    }

    return new Promise(function (res, rej) {
      function check() {
        if (selector) return frameDocument(options && options.frame).querySelector(selector);
        if (ref) return idMap.get(ref) || null;
        return null;
      }

      var el = check();
      if (!gone && el) return res({ found: true });
      if (gone && !el) return res({ found: true });

      var timer = setTimeout(function () {
        observer.disconnect();
        rej(new Error("Timeout waiting for " + (selector || ref)));
      }, timeout);

      var observer = new MutationObserver(function () {
        var found = check();
        if (!gone && found) {
          observer.disconnect();
          clearTimeout(timer);
          res({ found: true });
        } else if (gone && !found) {
          observer.disconnect();
          clearTimeout(timer);
          res({ found: true });
        }
      });

      observer.observe(document.body, {
        childList: true,
        subtree: true,
        attributes: true,
      });
    });
  }

  var MAX_WATCH_ENTRIES = 200;

  function summarizeNode(node) {
    var entry = { tag: node.tagName.toLowerCase() };
    if (node.id) entry.id = node.id;
    if (node.className && typeof node.className === 'string' && node.className.trim()) entry.class = node.className.trim();
    var text = Array.from(node.childNodes)
      .filter(function(n) { return n.nodeType === Node.TEXT_NODE; })
      .map(function(n) { return n.textContent || ''; })
      .join(' ')
      .replace(/\s+/g, ' ')
      .trim();
    if (text) entry.text = text.substring(0, 80);
    return entry;
  }

  function watch(options) {
    var selector = options && options.selector;
    var timeout = (options && options.timeout != null) ? options.timeout : 10000;
    var stable = (options && options.stable != null) ? options.stable : 300;
    var requireMutation = !!(options && options.requireMutation);

    var root;
    if (selector) {
      root = document.querySelector(selector);
      if (!root) throw new Error("watch: no element matches selector: " + selector);
    } else {
      root = document.body;
    }

    return new Promise(function (res, rej) {
      var changes = { added: [], removed: [], modified: [], truncated: false };
      var stableTimer = null;
      var timeoutTimer = null;
      var settled = false;

      function finish() {
        if (settled) return;
        settled = true;
        clearTimeout(timeoutTimer);
        observer.disconnect();
        res(changes);
      }

      function resetStableTimer() {
        clearTimeout(stableTimer);
        stableTimer = setTimeout(finish, stable);
      }

      timeoutTimer = setTimeout(function () {
        if (settled) return;
        settled = true;
        clearTimeout(stableTimer);
        observer.disconnect();
        if (changes.added.length > 0 || changes.removed.length > 0 || changes.modified.length > 0) {
          res(changes);
        } else {
          rej(new Error("watch timeout: no DOM changes within " + timeout + "ms"));
        }
      }, timeout);

      // With requireMutation we skip starting the stable timer until the first
      // mutation is seen; without it we start immediately so stable windows can
      // resolve even when the DOM is idle.
      if (!requireMutation) {
        resetStableTimer();
      }

      function pushCapped(arr, entry) {
        if (arr.length < MAX_WATCH_ENTRIES) {
          arr.push(entry);
        } else {
          changes.truncated = true;
        }
      }

      var observer = new MutationObserver(function (mutations) {
        for (var i = 0; i < mutations.length; i++) {
          var mutation = mutations[i];
          if (mutation.type === 'childList') {
            for (var j = 0; j < mutation.addedNodes.length; j++) {
              var node = mutation.addedNodes[j];
              if (node.nodeType === Node.ELEMENT_NODE) {
                pushCapped(changes.added, summarizeNode(node));
              }
            }
            for (var k = 0; k < mutation.removedNodes.length; k++) {
              var removedNode = mutation.removedNodes[k];
              if (removedNode.nodeType === Node.ELEMENT_NODE) {
                pushCapped(changes.removed, summarizeNode(removedNode));
              }
            }
          } else if (mutation.type === 'attributes') {
            var target = mutation.target;
            var attrValue = target.getAttribute(mutation.attributeName);
            var entry = {
              tag: target.tagName.toLowerCase(),
              attribute: mutation.attributeName,
            };
            if (attrValue === null) {
              entry.removed = true;
            } else {
              entry.value = attrValue;
            }
            pushCapped(changes.modified, entry);
          } else if (mutation.type === 'characterData') {
            var parent = mutation.target.parentElement;
            if (parent) {
              pushCapped(changes.modified, {
                tag: parent.tagName.toLowerCase(),
                text: (mutation.target.textContent || '').replace(/\s+/g, ' ').trim().substring(0, 80),
              });
            }
          }
        }
        resetStableTimer();
      });

      observer.observe(root, {
        childList: true,
        subtree: true,
        attributes: true,
        characterData: true,
      });
    });
  }

  async function screenshot(options) {
    var selector = options && options.selector;
    var el = selector ? document.querySelector(selector) : document.documentElement;
    if (!el) throw new Error("Element not found: " + selector);
    if (typeof htmlToImage === "undefined" || !htmlToImage.toPng) {
      throw new Error("html-to-image library not loaded. Bundle it into bridge.js for screenshot support.");
    }
    var renderOptions = { pixelRatio: 1 };
    if (!selector) {
      // html-to-image sizes the capture from clientWidth/clientHeight, which
      // for documentElement is the viewport — the render always starts at the
      // document origin, so anything below the fold is silently cropped
      // (#129). Pass the full scroll dimensions to capture the whole page.
      var body = document.body;
      renderOptions.width = Math.max(el.scrollWidth || 0, body ? body.scrollWidth || 0 : 0);
      renderOptions.height = Math.max(el.scrollHeight || 0, body ? body.scrollHeight || 0 : 0);
    }
    var dataUrl = await htmlToImage.toPng(el, renderOptions);
    return dataUrl;
  }

  function storageGet(params) {
    if (typeof params.key !== "string") {
      throw new Error("storageGet requires a string key");
    }
    var storage = params.session ? sessionStorage : localStorage;
    var val = storage.getItem(params.key);
    if (val === null) {
      return { found: false };
    }
    return { found: true, value: val };
  }

  function storageSet(params) {
    if (typeof params.key !== "string" || typeof params.value !== "string") {
      throw new Error("storageSet requires string key and value");
    }
    var storage = params.session ? sessionStorage : localStorage;
    storage.setItem(params.key, params.value);
    return { ok: true };
  }

  var MAX_STORAGE_ENTRIES = 500;

  function storageList(params) {
    var storage = params.session ? sessionStorage : localStorage;
    var total = storage.length;
    var len = Math.min(total, MAX_STORAGE_ENTRIES);
    var entries = [];
    for (var i = 0; i < len; i++) {
      var key = storage.key(i);
      entries.push({ key: key, value: storage.getItem(key) });
    }
    entries.sort(function (a, b) {
      return a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
    });
    return { entries: entries, truncated: total > MAX_STORAGE_ENTRIES };
  }

  function storageClear(params) {
    var storage = params.session ? sessionStorage : localStorage;
    storage.clear();
    return { cleared: true };
  }

  var MAX_FORMS = 100;
  var MAX_FIELDS_PER_FORM = 500;

  function formDump(params) {
    var forms;
    var totalForms;
    if (params && params.selector) {
      var found = document.querySelector(params.selector);
      if (!found) {
        throw new Error("Form not found: " + params.selector);
      }
      if (found.tagName.toLowerCase() !== "form") {
        throw new Error("Selector matched a <" + found.tagName.toLowerCase() + ">, expected a <form>");
      }
      forms = [found];
      totalForms = 1;
    } else {
      var all = document.querySelectorAll("form");
      totalForms = all.length;
      forms = [];
      var formLimit = Math.min(totalForms, MAX_FORMS);
      for (var fi = 0; fi < formLimit; fi++) {
        forms.push(all[fi]);
      }
    }

    var result = [];
    for (var i = 0; i < forms.length; i++) {
      var form = forms[i];
      var fields = [];
      var elements = form.querySelectorAll("input, select, textarea");
      var fieldLimit = Math.min(elements.length, MAX_FIELDS_PER_FORM);
      for (var j = 0; j < fieldLimit; j++) {
        var el = elements[j];
        var tag = el.tagName.toLowerCase();
        var elType = el.type || null;
        var fieldVal;
        if (tag === "select" && el.multiple) {
          var selected = [];
          for (var k = 0; k < el.options.length; k++) {
            if (el.options[k].selected) {
              selected.push(el.options[k].value);
            }
          }
          fieldVal = selected;
        } else {
          fieldVal = el.value;
        }
        var field = {
          tag: tag,
          type: elType,
          name: el.name || "",
          value: fieldVal,
        };
        if (elType === "checkbox" || elType === "radio") {
          field.checked = el.checked;
        }
        fields.push(field);
      }
      var formEntry = {
        id: form.id || "",
        name: form.getAttribute("name") || "",
        action: form.action || "",
        method: form.method || "get",
        fields: fields,
      };
      if (elements.length > MAX_FIELDS_PER_FORM) {
        formEntry.fieldsTruncated = true;
      }
      result.push(formEntry);
    }
    var truncated = totalForms > MAX_FORMS;
    return { forms: result, truncated: truncated };
  }

  window.__HASGARD__ = {
    snapshot: snapshot,
    query: query,
    filter: filterElements,
    resolve: resolve,
    click: click,
    fill: fill,
    type: typeText,
    select: select,
    check: check,
    scroll: scroll,
    text: text,
    html: html,
    value: value,
    attrs: attrs,
    navigate: navigate,
    url: url,
    title: title,
    state: state,
    eval: evalScript,
    wait: waitFor,
    screenshot: screenshot,
    consoleLogs: consoleLogs,
    clearLogs: clearLogs,
    networkRequests: networkRequests,
    clearNetwork: clearNetwork,
    visible: visible,
    count: count,
    checked: checked,
    disabled: disabled,
    boundingBox: boundingBox,
    focus: focus,
    blur: blur,
    hover: hover,
    dblclick: dblclick,
    watch: watch,
    drag: drag,
    drop: drop,
    setInputFiles: setInputFiles,
    wheel: wheel,
    dialogs: dialogs,
    clearDialogs: clearDialogs,
    handleDialogs: handleDialogs,
    storageGet: storageGet,
    storageSet: storageSet,
    storageList: storageList,
    storageClear: storageClear,
    formDump: formDump,
    route: routeAdd,
    routes: routeList,
    clearRoutes: routeClear,
  };
})();