summaryrefslogtreecommitdiffstats
path: root/devtools/server/actors/webconsole.js
blob: 8c302cfd02b5a03d375942802037205be33d7ce0 (plain)
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
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

/* global XPCNativeWrapper */
const { ActorClassWithSpec, Actor } = require("devtools/shared/protocol");
const { webconsoleSpec } = require("devtools/shared/specs/webconsole");

const Services = require("Services");
const { Cc, Ci, Cu } = require("chrome");
const { DevToolsServer } = require("devtools/server/devtools-server");
const { ThreadActor } = require("devtools/server/actors/thread");
const { ObjectActor } = require("devtools/server/actors/object");
const { LongStringActor } = require("devtools/server/actors/string");
const {
  createValueGrip,
  isArray,
  stringIsLong,
} = require("devtools/server/actors/object/utils");
const DevToolsUtils = require("devtools/shared/DevToolsUtils");
const ErrorDocs = require("devtools/server/actors/errordocs");

loader.lazyRequireGetter(
  this,
  "evalWithDebugger",
  "devtools/server/actors/webconsole/eval-with-debugger",
  true
);
loader.lazyRequireGetter(
  this,
  "NetworkMonitorActor",
  "devtools/server/actors/network-monitor/network-monitor",
  true
);
loader.lazyRequireGetter(
  this,
  "ConsoleFileActivityListener",
  "devtools/server/actors/webconsole/listeners/console-file-activity",
  true
);
loader.lazyRequireGetter(
  this,
  "StackTraceCollector",
  "devtools/server/actors/network-monitor/stack-trace-collector",
  true
);
loader.lazyRequireGetter(
  this,
  "JSPropertyProvider",
  "devtools/shared/webconsole/js-property-provider",
  true
);
loader.lazyRequireGetter(
  this,
  "NetUtil",
  "resource://gre/modules/NetUtil.jsm",
  true
);
loader.lazyRequireGetter(
  this,
  ["isCommand", "validCommands"],
  "devtools/server/actors/webconsole/commands",
  true
);
loader.lazyRequireGetter(
  this,
  "createMessageManagerMocks",
  "devtools/server/actors/webconsole/message-manager-mock",
  true
);
loader.lazyRequireGetter(
  this,
  ["addWebConsoleCommands", "CONSOLE_WORKER_IDS", "WebConsoleUtils"],
  "devtools/server/actors/webconsole/utils",
  true
);
loader.lazyRequireGetter(
  this,
  "EnvironmentActor",
  "devtools/server/actors/environment",
  true
);
loader.lazyRequireGetter(this, "EventEmitter", "devtools/shared/event-emitter");
loader.lazyRequireGetter(
  this,
  "MESSAGE_CATEGORY",
  "devtools/shared/constants",
  true
);
loader.lazyRequireGetter(
  this,
  "stringToCauseType",
  "devtools/server/actors/network-monitor/network-observer",
  true
);

// Generated by /devtools/shared/webconsole/GenerateReservedWordsJS.py
loader.lazyRequireGetter(
  this,
  "RESERVED_JS_KEYWORDS",
  "devtools/shared/webconsole/reserved-js-words"
);

// Overwrite implemented listeners for workers so that we don't attempt
// to load an unsupported module.
if (isWorker) {
  loader.lazyRequireGetter(
    this,
    ["ConsoleAPIListener", "ConsoleServiceListener"],
    "devtools/server/actors/webconsole/worker-listeners",
    true
  );
} else {
  loader.lazyRequireGetter(
    this,
    "ConsoleAPIListener",
    "devtools/server/actors/webconsole/listeners/console-api",
    true
  );
  loader.lazyRequireGetter(
    this,
    "ConsoleServiceListener",
    "devtools/server/actors/webconsole/listeners/console-service",
    true
  );
  loader.lazyRequireGetter(
    this,
    "ConsoleReflowListener",
    "devtools/server/actors/webconsole/listeners/console-reflow",
    true
  );
  loader.lazyRequireGetter(
    this,
    "ContentProcessListener",
    "devtools/server/actors/webconsole/listeners/content-process",
    true
  );
  loader.lazyRequireGetter(
    this,
    "DocumentEventsListener",
    "devtools/server/actors/webconsole/listeners/document-events",
    true
  );
}
loader.lazyRequireGetter(
  this,
  "ObjectUtils",
  "devtools/server/actors/object/utils"
);

function isObject(value) {
  return Object(value) === value;
}

/**
 * The WebConsoleActor implements capabilities needed for the Web Console
 * feature.
 *
 * @constructor
 * @param object connection
 *        The connection to the client, DevToolsServerConnection.
 * @param object [parentActor]
 *        Optional, the parent actor.
 */
const WebConsoleActor = ActorClassWithSpec(webconsoleSpec, {
  initialize: function(connection, parentActor) {
    Actor.prototype.initialize.call(this, connection);
    this.conn = connection;
    this.parentActor = parentActor;

    this._prefs = {};
    this.dbg = this.parentActor.dbg;

    this._gripDepth = 0;
    this._evalCounter = 0;
    this._listeners = new Set();
    this._lastConsoleInputEvaluation = undefined;

    this.objectGrip = this.objectGrip.bind(this);
    this._onWillNavigate = this._onWillNavigate.bind(this);
    this._onChangedToplevelDocument = this._onChangedToplevelDocument.bind(
      this
    );
    this.onConsoleServiceMessage = this.onConsoleServiceMessage.bind(this);
    this.onConsoleAPICall = this.onConsoleAPICall.bind(this);
    this.onDocumentEvent = this.onDocumentEvent.bind(this);

    EventEmitter.on(
      this.parentActor,
      "changed-toplevel-document",
      this._onChangedToplevelDocument
    );
    this._onObserverNotification = this._onObserverNotification.bind(this);
    if (this.parentActor.isRootActor) {
      Services.obs.addObserver(
        this._onObserverNotification,
        "last-pb-context-exited"
      );
    }

    this.traits = {
      // Supports retrieving blocked urls
      blockedUrls: true,
    };
  },
  /**
   * Debugger instance.
   *
   * @see jsdebugger.jsm
   */
  dbg: null,

  /**
   * This is used by the ObjectActor to keep track of the depth of grip() calls.
   * @private
   * @type number
   */
  _gripDepth: null,

  /**
   * Web Console-related preferences.
   * @private
   * @type object
   */
  _prefs: null,

  /**
   * Holds a set of all currently registered listeners.
   *
   * @private
   * @type Set
   */
  _listeners: null,

  /**
   * The devtools server connection instance.
   * @type object
   */
  conn: null,

  /**
   * List of supported features by the console actor.
   * @type object
   */
  traits: null,

  /**
   * The global we work with (this can be a Window, a Worker global or even a Sandbox
   * for processes and addons).
   *
   * @type nsIDOMWindow, WorkerGlobalScope or Sandbox
   */
  get global() {
    if (this.parentActor.isRootActor) {
      return this._getWindowForBrowserConsole();
    }
    return this.parentActor.window || this.parentActor.workerGlobal;
  },

  /**
   * Get a window to use for the browser console.
   *
   * @private
   * @return nsIDOMWindow
   *         The window to use, or null if no window could be found.
   */
  _getWindowForBrowserConsole: function() {
    // Check if our last used chrome window is still live.
    let window = this._lastChromeWindow && this._lastChromeWindow.get();
    // If not, look for a new one.
    if (!window || window.closed) {
      window = this.parentActor.window;
      if (!window) {
        // Try to find the Browser Console window to use instead.
        window = Services.wm.getMostRecentWindow("devtools:webconsole");
        // We prefer the normal chrome window over the console window,
        // so we'll look for those windows in order to replace our reference.
        const onChromeWindowOpened = () => {
          // We'll look for this window when someone next requests window()
          Services.obs.removeObserver(onChromeWindowOpened, "domwindowopened");
          this._lastChromeWindow = null;
        };
        Services.obs.addObserver(onChromeWindowOpened, "domwindowopened");
      }

      this._handleNewWindow(window);
    }

    return window;
  },

  /**
   * Store a newly found window on the actor to be used in the future.
   *
   * @private
   * @param nsIDOMWindow window
   *        The window to store on the actor (can be null).
   */
  _handleNewWindow: function(window) {
    if (window) {
      if (this._hadChromeWindow) {
        Services.console.logStringMessage("Webconsole context has changed");
      }
      this._lastChromeWindow = Cu.getWeakReference(window);
      this._hadChromeWindow = true;
    } else {
      this._lastChromeWindow = null;
    }
  },

  /**
   * Whether we've been using a window before.
   *
   * @private
   * @type boolean
   */
  _hadChromeWindow: false,

  /**
   * A weak reference to the last chrome window we used to work with.
   *
   * @private
   * @type nsIWeakReference
   */
  _lastChromeWindow: null,

  // The evalGlobal is used at the scope for JS evaluation.
  _evalGlobal: null,
  get evalGlobal() {
    return this._evalGlobal || this.global;
  },

  set evalGlobal(global) {
    this._evalGlobal = global;

    if (!this._progressListenerActive) {
      EventEmitter.on(this.parentActor, "will-navigate", this._onWillNavigate);
      this._progressListenerActive = true;
    }
  },

  /**
   * Flag used to track if we are listening for events from the progress
   * listener of the target actor. We use the progress listener to clear
   * this.evalGlobal on page navigation.
   *
   * @private
   * @type boolean
   */
  _progressListenerActive: false,

  /**
   * The ConsoleServiceListener instance.
   * @type object
   */
  consoleServiceListener: null,

  /**
   * The ConsoleAPIListener instance.
   */
  consoleAPIListener: null,

  /**
   * The ConsoleFileActivityListener instance.
   */
  consoleFileActivityListener: null,

  /**
   * The ConsoleReflowListener instance.
   */
  consoleReflowListener: null,

  /**
   * The Web Console Commands names cache.
   * @private
   * @type array
   */
  _webConsoleCommandsCache: null,

  grip: function() {
    return { actor: this.actorID };
  },

  hasNativeConsoleAPI: function(window) {
    if (isWorker || !(window instanceof Ci.nsIDOMWindow)) {
      // We can only use XPCNativeWrapper on non-worker nsIDOMWindow.
      return true;
    }

    let isNative = false;
    try {
      // We are very explicitly examining the "console" property of
      // the non-Xrayed object here.
      const console = window.wrappedJSObject.console;
      // In xpcshell tests, console ends up being undefined and XPCNativeWrapper
      // crashes in debug builds.
      if (console) {
        isNative = new XPCNativeWrapper(console).IS_NATIVE_CONSOLE;
      }
    } catch (ex) {
      // ignored
    }
    return isNative;
  },

  _findProtoChain: ThreadActor.prototype._findProtoChain,
  _removeFromProtoChain: ThreadActor.prototype._removeFromProtoChain,

  /**
   * Destroy the current WebConsoleActor instance.
   */
  destroy() {
    this.stopListeners();
    Actor.prototype.destroy.call(this);

    EventEmitter.off(
      this.parentActor,
      "changed-toplevel-document",
      this._onChangedToplevelDocument
    );

    if (this.parentActor.isRootActor) {
      Services.obs.removeObserver(
        this._onObserverNotification,
        "last-pb-context-exited"
      );
    }

    this._webConsoleCommandsCache = null;
    this._lastConsoleInputEvaluation = null;
    this._evalGlobal = null;
    this.dbg = null;
    this.conn = null;
  },

  /**
   * Create and return an environment actor that corresponds to the provided
   * Debugger.Environment. This is a straightforward clone of the ThreadActor's
   * method except that it stores the environment actor in the web console
   * actor's pool.
   *
   * @param Debugger.Environment environment
   *        The lexical environment we want to extract.
   * @return The EnvironmentActor for |environment| or |undefined| for host
   *         functions or functions scoped to a non-debuggee global.
   */
  createEnvironmentActor: function(environment) {
    if (!environment) {
      return undefined;
    }

    if (environment.actor) {
      return environment.actor;
    }

    const actor = new EnvironmentActor(environment, this);
    this.manage(actor);
    environment.actor = actor;

    return actor;
  },

  /**
   * Create a grip for the given value.
   *
   * @param mixed value
   * @return object
   */
  createValueGrip: function(value) {
    return createValueGrip(value, this, this.objectGrip);
  },

  /**
   * Make a debuggee value for the given value.
   *
   * @param mixed value
   *        The value you want to get a debuggee value for.
   * @param boolean useObjectGlobal
   *        If |true| the object global is determined and added as a debuggee,
   *        otherwise |this.global| is used when makeDebuggeeValue() is invoked.
   * @return object
   *         Debuggee value for |value|.
   */
  makeDebuggeeValue: function(value, useObjectGlobal) {
    if (useObjectGlobal && isObject(value)) {
      try {
        const global = Cu.getGlobalForObject(value);
        const dbgGlobal = this.dbg.makeGlobalObjectReference(global);
        return dbgGlobal.makeDebuggeeValue(value);
      } catch (ex) {
        // The above can throw an exception if value is not an actual object
        // or 'Object in compartment marked as invisible to Debugger'
      }
    }
    const dbgGlobal = this.dbg.makeGlobalObjectReference(this.global);
    return dbgGlobal.makeDebuggeeValue(value);
  },

  /**
   * Create a grip for the given object.
   *
   * @param object object
   *        The object you want.
   * @param object pool
   *        A Pool where the new actor instance is added.
   * @param object
   *        The object grip.
   */
  objectGrip: function(object, pool) {
    const actor = new ObjectActor(
      object,
      {
        thread: this.parentActor.threadActor,
        getGripDepth: () => this._gripDepth,
        incrementGripDepth: () => this._gripDepth++,
        decrementGripDepth: () => this._gripDepth--,
        createValueGrip: v => this.createValueGrip(v),
        createEnvironmentActor: env => this.createEnvironmentActor(env),
      },
      this.conn
    );
    pool.manage(actor);
    return actor.form();
  },

  /**
   * Create a grip for the given string.
   *
   * @param string string
   *        The string you want to create the grip for.
   * @param object pool
   *        A Pool where the new actor instance is added.
   * @return object
   *         A LongStringActor object that wraps the given string.
   */
  longStringGrip: function(string, pool) {
    const actor = new LongStringActor(this.conn, string);
    pool.manage(actor);
    return actor.form();
  },

  /**
   * Create a long string grip if needed for the given string.
   *
   * @private
   * @param string string
   *        The string you want to create a long string grip for.
   * @return string|object
   *         A string is returned if |string| is not a long string.
   *         A LongStringActor grip is returned if |string| is a long string.
   */
  _createStringGrip: function(string) {
    if (string && stringIsLong(string)) {
      return this.longStringGrip(string, this);
    }
    return string;
  },

  /**
   * Returns the latest web console input evaluation.
   * This is undefined if no evaluations have been completed.
   *
   * @return object
   */
  getLastConsoleInputEvaluation: function() {
    return this._lastConsoleInputEvaluation;
  },

  /**
   * Preprocess a debugger object (e.g. return the `boundTargetFunction`
   * debugger object if the given debugger object is a bound function).
   *
   * This method is called by both the `inspect` binding implemented
   * for the webconsole and the one implemented for the devtools API
   * `browser.devtools.inspectedWindow.eval`.
   */
  preprocessDebuggerObject(dbgObj) {
    // Returns the bound target function on a bound function.
    if (dbgObj?.isBoundFunction && dbgObj?.boundTargetFunction) {
      return dbgObj.boundTargetFunction;
    }

    return dbgObj;
  },

  /**
   * This helper is used by the WebExtensionInspectedWindowActor to
   * inspect an object in the developer toolbox.
   *
   * NOTE: shared parts related to preprocess the debugger object (between
   * this function and the `inspect` webconsole command defined in
   * "devtools/server/actor/webconsole/utils.js") should be added to
   * the webconsole actors' `preprocessDebuggerObject` method.
   */
  inspectObject(dbgObj, inspectFromAnnotation) {
    dbgObj = this.preprocessDebuggerObject(dbgObj);
    this.emit("inspectObject", {
      objectActor: this.createValueGrip(dbgObj),
      inspectFromAnnotation,
    });
  },

  // Request handlers for known packet types.

  /**
   * Handler for the "startListeners" request.
   *
   * @param array listeners
   *        An array of events to start sent by the Web Console client.
   * @return object
   *        The response object which holds the startedListeners array.
   */
  // eslint-disable-next-line complexity
  startListeners: async function(listeners) {
    const startedListeners = [];
    const global = !this.parentActor.isRootActor ? this.global : null;

    for (const event of listeners) {
      switch (event) {
        case "PageError":
          // Workers don't support this message type yet
          if (isWorker) {
            break;
          }
          if (!this.consoleServiceListener) {
            this.consoleServiceListener = new ConsoleServiceListener(
              global,
              this.onConsoleServiceMessage
            );
            this.consoleServiceListener.init();
          }
          startedListeners.push(event);
          break;
        case "ConsoleAPI":
          if (!this.consoleAPIListener) {
            // Create the consoleAPIListener
            // (and apply the filtering options defined in the parent actor).
            this.consoleAPIListener = new ConsoleAPIListener(
              global,
              this.onConsoleAPICall,
              this.parentActor.consoleAPIListenerOptions
            );
            this.consoleAPIListener.init();
          }
          startedListeners.push(event);
          break;
        case "NetworkActivity":
          // Workers don't support this message type
          if (isWorker) {
            break;
          }
          if (!this.netmonitors) {
            // Instanciate fake message managers used for service worker's netmonitor
            // when running in the content process, and for netmonitor running in the
            // same process when running in the parent process.
            // `createMessageManagerMocks` returns a couple of connected messages
            // managers that pass messages to each other to simulate the process
            // boundary. We will use the first one for the webconsole-actor and the
            // second one will be used by the netmonitor-actor.
            const [mmMockParent, mmMockChild] = createMessageManagerMocks();

            // Maintain the list of message manager we should message to/listen from
            // to support the netmonitor instances, also records actorID of each
            // NetworkMonitorActor.
            // Array of `{ messageManager, parentProcess }`.
            // Where `parentProcess` is true for the netmonitor actor instanciated in the
            // parent process.
            this.netmonitors = [];

            // Check if the actor is running in a content process
            const isInContentProcess =
              Services.appinfo.processType !=
                Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT &&
              this.parentActor.messageManager;
            if (isInContentProcess) {
              // Start a network monitor in the parent process to listen to
              // most requests that happen in parent. This one will communicate through
              // `messageManager`.
              await this.conn.spawnActorInParentProcess(this.actorID, {
                module:
                  "devtools/server/actors/network-monitor/network-monitor",
                constructor: "NetworkMonitorActor",
                args: [{ browserId: this.parentActor.browserId }, this.actorID],
              });
              this.netmonitors.push({
                messageManager: this.parentActor.messageManager,
                parentProcess: true,
              });
            }

            // When the console actor runs in the parent process, Netmonitor can be ran
            // in the process and communicate through `messageManagerMock`.
            // And while it runs in the content process, we also spawn one in the content
            // to listen to requests that happen in the content process (for instance
            // service workers requests)
            new NetworkMonitorActor(
              this.conn,
              { window: global },
              this.actorID,
              mmMockParent
            );

            this.netmonitors.push({
              messageManager: mmMockChild,
              parentProcess: !isInContentProcess,
            });

            // Create a StackTraceCollector that's going to be shared both by
            // the NetworkMonitorActor running in the same process for service worker
            // requests, as well with the NetworkMonitorActor running in the parent
            // process. It will communicate via message manager for this one.
            this.stackTraceCollector = new StackTraceCollector(
              { window: global },
              this.netmonitors
            );
            this.stackTraceCollector.init();
          }
          startedListeners.push(event);
          break;
        case "FileActivity":
          // Workers don't support this message type
          if (isWorker) {
            break;
          }
          if (this.global instanceof Ci.nsIDOMWindow) {
            if (!this.consoleFileActivityListener) {
              this.consoleFileActivityListener = new ConsoleFileActivityListener(
                this.global,
                this
              );
            }
            this.consoleFileActivityListener.startMonitor();
            startedListeners.push(event);
          }
          break;
        case "ReflowActivity":
          // Workers don't support this message type
          if (isWorker) {
            break;
          }
          if (!this.consoleReflowListener) {
            this.consoleReflowListener = new ConsoleReflowListener(
              this.global,
              this
            );
          }
          startedListeners.push(event);
          break;
        case "ContentProcessMessages":
          // Workers don't support this message type
          if (isWorker) {
            break;
          }
          if (!this.contentProcessListener) {
            this.contentProcessListener = new ContentProcessListener(
              this.onConsoleAPICall
            );
          }
          startedListeners.push(event);
          break;
        case "DocumentEvents":
          // Workers don't support this message type
          if (isWorker) {
            break;
          }
          if (!this.documentEventsListener) {
            this.documentEventsListener = new DocumentEventsListener(
              this.parentActor
            );
            this.documentEventsListener.on("*", this.onDocumentEvent);
            this.documentEventsListener.listen();
          }
          startedListeners.push(event);
          break;
      }
    }

    // Update the live list of running listeners
    startedListeners.forEach(this._listeners.add, this._listeners);

    return {
      startedListeners: startedListeners,
      nativeConsoleAPI: this.hasNativeConsoleAPI(this.global),
      traits: this.traits,
    };
  },

  /**
   * Handler for the "stopListeners" request.
   *
   * @param array listeners
   *        An array of events to stop sent by the Web Console client.
   * @return object
   *        The response packet to send to the client: holds the
   *        stoppedListeners array.
   */
  stopListeners: function(listeners) {
    const stoppedListeners = [];

    // If no specific listeners are requested to be detached, we stop all
    // listeners.
    const eventsToDetach = listeners || [
      "PageError",
      "ConsoleAPI",
      "NetworkActivity",
      "FileActivity",
      "ReflowActivity",
      "ContentProcessMessages",
      "DocumentEvents",
    ];

    for (const event of eventsToDetach) {
      switch (event) {
        case "PageError":
          if (this.consoleServiceListener) {
            this.consoleServiceListener.destroy();
            this.consoleServiceListener = null;
          }
          stoppedListeners.push(event);
          break;
        case "ConsoleAPI":
          if (this.consoleAPIListener) {
            this.consoleAPIListener.destroy();
            this.consoleAPIListener = null;
          }
          stoppedListeners.push(event);
          break;
        case "NetworkActivity":
          if (this.netmonitors) {
            for (const { messageManager } of this.netmonitors) {
              messageManager.sendAsyncMessage("debug:destroy-network-monitor", {
                actorID: this.actorID,
              });
            }
            this.netmonitors = null;
          }
          if (this.stackTraceCollector) {
            this.stackTraceCollector.destroy();
            this.stackTraceCollector = null;
          }
          stoppedListeners.push(event);
          break;
        case "FileActivity":
          if (this.consoleFileActivityListener) {
            this.consoleFileActivityListener.stopMonitor();
            this.consoleFileActivityListener = null;
          }
          stoppedListeners.push(event);
          break;
        case "ReflowActivity":
          if (this.consoleReflowListener) {
            this.consoleReflowListener.destroy();
            this.consoleReflowListener = null;
          }
          stoppedListeners.push(event);
          break;
        case "ContentProcessMessages":
          if (this.contentProcessListener) {
            this.contentProcessListener.destroy();
            this.contentProcessListener = null;
          }
          stoppedListeners.push(event);
          break;
        case "DocumentEvents":
          if (this.documentEventsListener) {
            this.documentEventsListener.destroy();
            this.documentEventsListener = null;
          }
          stoppedListeners.push(event);
          break;
      }
    }

    // Update the live list of running listeners
    stoppedListeners.forEach(this._listeners.delete, this._listeners);

    return { stoppedListeners: stoppedListeners };
  },

  /**
   * Handler for the "getCachedMessages" request. This method sends the cached
   * error messages and the window.console API calls to the client.
   *
   * @param array messageTypes
   *        An array of message types sent by the Web Console client.
   * @return object
   *         The response packet to send to the client: it holds the cached
   *         messages array.
   */
  getCachedMessages: function(messageTypes) {
    if (!messageTypes) {
      return {
        error: "missingParameter",
        message: "The messageTypes parameter is missing.",
      };
    }

    const messages = [];

    const consoleServiceCachedMessages =
      messageTypes.includes("PageError") || messageTypes.includes("LogMessage")
        ? this.consoleServiceListener?.getCachedMessages(
            !this.parentActor.isRootActor
          )
        : null;

    for (const type of messageTypes) {
      switch (type) {
        case "ConsoleAPI": {
          if (!this.consoleAPIListener) {
            break;
          }

          // this.global might not be a window (can be a worker global or a Sandbox),
          // and in such case performance isn't defined
          const winStartTime = this.global?.performance?.timing
            ?.navigationStart;

          const cache = this.consoleAPIListener.getCachedMessages(
            !this.parentActor.isRootActor
          );
          cache.forEach(cachedMessage => {
            // Filter out messages that came from a ServiceWorker but happened
            // before the page was requested.
            if (
              cachedMessage.innerID === "ServiceWorker" &&
              winStartTime > cachedMessage.timeStamp
            ) {
              return;
            }

            messages.push({
              message: this.prepareConsoleMessageForRemote(cachedMessage),
              type: "consoleAPICall",
            });
          });
          break;
        }

        case "PageError": {
          if (!consoleServiceCachedMessages) {
            break;
          }

          for (const cachedMessage of consoleServiceCachedMessages) {
            if (!(cachedMessage instanceof Ci.nsIScriptError)) {
              continue;
            }

            messages.push({
              pageError: this.preparePageErrorForRemote(cachedMessage),
              type: "pageError",
            });
          }
          break;
        }

        case "LogMessage": {
          if (!consoleServiceCachedMessages) {
            break;
          }

          for (const cachedMessage of consoleServiceCachedMessages) {
            if (cachedMessage instanceof Ci.nsIScriptError) {
              continue;
            }

            messages.push({
              message: this._createStringGrip(cachedMessage.message),
              timeStamp: cachedMessage.timeStamp,
              type: "logMessage",
            });
          }
          break;
        }
      }
    }

    return {
      messages: messages,
    };
  },

  /**
   * Handler for the "evaluateJSAsync" request. This method evaluates a given
   * JavaScript string with an associated `resultID`.
   *
   * The result will be returned later as an unsolicited `evaluationResult`,
   * that can be associated back to this request via the `resultID` field.
   *
   * @param object request
   *        The JSON request object received from the Web Console client.
   * @return object
   *         The response packet to send to with the unique id in the
   *         `resultID` field.
   */
  evaluateJSAsync: async function(request) {
    const startTime = Date.now();
    // Use Date instead of UUID as this code is used by workers, which
    // don't have access to the UUID XPCOM component.
    // Also use a counter in order to prevent mixing up response when calling
    // evaluateJSAsync during the same millisecond.
    const resultID = startTime + "-" + this._evalCounter++;

    // Execute the evaluation in the next event loop in order to immediately
    // reply with the resultID.
    DevToolsUtils.executeSoon(async () => {
      try {
        // Execute the script that may pause.
        let response = await this.evaluateJS(request);
        // Wait for any potential returned Promise.
        response = await this._maybeWaitForResponseResult(response);
        // Set the timestamp only now, so any messages logged in the expression will come
        // before the result. Add an extra millisecond so the result has a different timestamp
        // than the console message it might have emitted (unlike the evaluation result,
        // console api messages are throttled before being handled by the webconsole client,
        // which might cause some ordering issue).
        response.timestamp = Date.now() + 1;
        // Finally, emit an unsolicited evaluationResult packet with the evaluation result.
        this.emit("evaluationResult", {
          type: "evaluationResult",
          resultID,
          startTime,
          ...response,
        });
        return;
      } catch (e) {
        const message = `Encountered error while waiting for Helper Result: ${e}\n${e.stack}`;
        DevToolsUtils.reportException("evaluateJSAsync", Error(message));
      }
    });
    return { resultID };
  },

  /**
   * In order to have asynchronous commands (e.g. screenshot, top-level await, …) ,
   * we have to be able to handle promises. This method handles waiting for the promise,
   * and then returns the result.
   *
   * @private
   * @param object response
   *         The response packet to send to with the unique id in the
   *         `resultID` field, and potentially a promise in the `helperResult` or in the
   *         `awaitResult` field.
   *
   * @return object
   *         The updated response object.
   */
  _maybeWaitForResponseResult: async function(response) {
    if (!response) {
      return response;
    }

    const thenable = obj => obj && typeof obj.then === "function";
    const waitForHelperResult =
      response.helperResult && thenable(response.helperResult);
    const waitForAwaitResult =
      response.awaitResult && thenable(response.awaitResult);

    if (!waitForAwaitResult && !waitForHelperResult) {
      return response;
    }

    // Wait for asynchronous command completion before sending back the response
    if (waitForHelperResult) {
      response.helperResult = await response.helperResult;
    } else if (waitForAwaitResult) {
      let result;
      try {
        result = await response.awaitResult;

        // `createValueGrip` expect a debuggee value, while here we have the raw object.
        // We need to call `makeDebuggeeValue` on it to make it work.
        const dbgResult = this.makeDebuggeeValue(result);
        response.result = this.createValueGrip(dbgResult);
      } catch (e) {
        // The promise was rejected. We let the engine handle this as it will report a
        // `uncaught exception` error.
        response.topLevelAwaitRejected = true;
      }

      // Remove the promise from the response object.
      delete response.awaitResult;
    }

    return response;
  },

  /**
   * Handler for the "evaluateJS" request. This method evaluates the given
   * JavaScript string and sends back the result.
   *
   * @param object request
   *        The JSON request object received from the Web Console client.
   * @return object
   *         The evaluation response packet.
   */
  evaluateJS: function(request) {
    const input = request.text;

    const evalOptions = {
      frameActor: request.frameActor,
      url: request.url,
      innerWindowID: request.innerWindowID,
      selectedNodeActor: request.selectedNodeActor,
      selectedObjectActor: request.selectedObjectActor,
      eager: request.eager,
      bindings: request.bindings,
      lineNumber: request.lineNumber,
    };

    const { mapped } = request;

    // Set a flag on the thread actor which indicates an evaluation is being
    // done for the client. This can affect how debugger handlers behave.
    this.parentActor.threadActor.insideClientEvaluation = evalOptions;

    const evalInfo = evalWithDebugger(input, evalOptions, this);

    this.parentActor.threadActor.insideClientEvaluation = null;

    return new Promise((resolve, reject) => {
      // Queue up a task to run in the next tick so any microtask created by the evaluated
      // expression has the time to be run.
      // e.g. in :
      // ```
      // const promiseThenCb = result => "result: " + result;
      // new Promise(res => res("hello")).then(promiseThenCb)
      // ```
      // we want`promiseThenCb` to have run before handling the result.
      DevToolsUtils.executeSoon(() => {
        try {
          const result = this.prepareEvaluationResult(
            evalInfo,
            input,
            request.eager,
            mapped
          );
          resolve(result);
        } catch (err) {
          reject(err);
        }
      });
    });
  },

  // eslint-disable-next-line complexity
  prepareEvaluationResult: function(evalInfo, input, eager, mapped) {
    const evalResult = evalInfo.result;
    const helperResult = evalInfo.helperResult;

    let result,
      errorDocURL,
      errorMessage,
      errorNotes = null,
      errorGrip = null,
      frame = null,
      awaitResult,
      errorMessageName,
      exceptionStack;
    if (evalResult) {
      if ("return" in evalResult) {
        result = evalResult.return;
        if (
          mapped?.await &&
          result &&
          result.class === "Promise" &&
          typeof result.unsafeDereference === "function"
        ) {
          awaitResult = result.unsafeDereference();
        }
      } else if ("yield" in evalResult) {
        result = evalResult.yield;
      } else if ("throw" in evalResult) {
        const error = evalResult.throw;
        errorGrip = this.createValueGrip(error);

        exceptionStack = this.prepareStackForRemote(evalResult.stack);

        if (exceptionStack) {
          // Set the frame based on the topmost stack frame for the exception.
          const {
            filename: source,
            sourceId,
            lineNumber: line,
            columnNumber: column,
          } = exceptionStack[0];
          frame = { source, sourceId, line, column };

          exceptionStack = WebConsoleUtils.removeFramesAboveDebuggerEval(
            exceptionStack
          );
        }

        errorMessage = String(error);
        if (typeof error === "object" && error !== null) {
          try {
            errorMessage = DevToolsUtils.callPropertyOnObject(
              error,
              "toString"
            );
          } catch (e) {
            // If the debuggee is not allowed to access the "toString" property
            // of the error object, calling this property from the debuggee's
            // compartment will fail. The debugger should show the error object
            // as it is seen by the debuggee, so this behavior is correct.
            //
            // Unfortunately, we have at least one test that assumes calling the
            // "toString" property of an error object will succeed if the
            // debugger is allowed to access it, regardless of whether the
            // debuggee is allowed to access it or not.
            //
            // To accomodate these tests, if calling the "toString" property
            // from the debuggee compartment fails, we rewrap the error object
            // in the debugger's compartment, and then call the "toString"
            // property from there.
            if (typeof error.unsafeDereference === "function") {
              const rawError = error.unsafeDereference();
              errorMessage = rawError ? rawError.toString() : "";
            }
          }
        }

        // It is possible that we won't have permission to unwrap an
        // object and retrieve its errorMessageName.
        try {
          errorDocURL = ErrorDocs.GetURL(error);
          errorMessageName = error.errorMessageName;
        } catch (ex) {
          // ignored
        }

        try {
          const line = error.errorLineNumber;
          const column = error.errorColumnNumber;

          if (typeof line === "number" && typeof column === "number") {
            // Set frame only if we have line/column numbers.
            frame = {
              source: "debugger eval code",
              line,
              column,
            };
          }
        } catch (ex) {
          // ignored
        }

        try {
          const notes = error.errorNotes;
          if (notes?.length) {
            errorNotes = [];
            for (const note of notes) {
              errorNotes.push({
                messageBody: this._createStringGrip(note.message),
                frame: {
                  source: note.fileName,
                  line: note.lineNumber,
                  column: note.columnNumber,
                },
              });
            }
          }
        } catch (ex) {
          // ignored
        }
      }
    }

    // If a value is encountered that the devtools server doesn't support yet,
    // the console should remain functional.
    let resultGrip;
    if (!awaitResult) {
      try {
        const objectActor = this.parentActor.threadActor.getThreadLifetimeObject(
          result
        );
        if (objectActor) {
          resultGrip = this.parentActor.threadActor.createValueGrip(result);
        } else {
          resultGrip = this.createValueGrip(result);
        }
      } catch (e) {
        errorMessage = e;
      }
    }

    // Don't update _lastConsoleInputEvaluation in eager evaluation, as it would interfere
    // with the $_ command.
    if (!eager) {
      if (!awaitResult) {
        this._lastConsoleInputEvaluation = result;
      } else {
        // If we evaluated a top-level await expression, we want to assign its result to the
        // _lastConsoleInputEvaluation only when the promise resolves, and only if it
        // resolves. If the promise rejects, we don't re-assign _lastConsoleInputEvaluation,
        // it will keep its previous value.

        const p = awaitResult.then(res => {
          this._lastConsoleInputEvaluation = this.makeDebuggeeValue(res);
        });

        // If the top level await was already rejected (e.g. `await Promise.reject("bleh")`),
        // catch the resulting promise of awaitResult.then.
        // If we don't do that, the new Promise will also be rejected, and since it's
        // unhandled, it will generate an error.
        // We don't want to do that for pending promise (e.g. `await new Promise((res, rej) => setTimeout(rej,250))`),
        // as the the Promise rejection will be considered as handled, and the "Uncaught (in promise)"
        // message wouldn't be emitted.
        const { state } = ObjectUtils.getPromiseState(evalResult.return);
        if (state === "rejected") {
          p.catch(() => {});
        }
      }
    }

    return {
      input: input,
      result: resultGrip,
      awaitResult,
      exception: errorGrip,
      exceptionMessage: this._createStringGrip(errorMessage),
      exceptionDocURL: errorDocURL,
      exceptionStack,
      hasException: errorGrip !== null,
      errorMessageName,
      frame,
      helperResult: helperResult,
      notes: errorNotes,
    };
  },

  /**
   * The Autocomplete request handler.
   *
   * @param string text
   *        The request message - what input to autocomplete.
   * @param number cursor
   *        The cursor position at the moment of starting autocomplete.
   * @param string frameActor
   *        The frameactor id of the current paused frame.
   * @param string selectedNodeActor
   *        The actor id of the currently selected node.
   * @param array authorizedEvaluations
   *        Array of the properties access which can be executed by the engine.
   * @return object
   *         The response message - matched properties.
   */
  autocomplete: function(
    text,
    cursor,
    frameActorId,
    selectedNodeActor,
    authorizedEvaluations,
    expressionVars = []
  ) {
    let dbgObject = null;
    let environment = null;
    let matches = [];
    let matchProp;
    let isElementAccess;

    const reqText = text.substr(0, cursor);

    if (isCommand(reqText)) {
      const commandsCache = this._getWebConsoleCommandsCache();
      matchProp = reqText;
      matches = validCommands
        .filter(
          c =>
            `:${c}`.startsWith(reqText) &&
            commandsCache.find(n => `:${n}`.startsWith(reqText))
        )
        .map(c => `:${c}`);
    } else {
      // This is the case of the paused debugger
      if (frameActorId) {
        const frameActor = this.conn.getActor(frameActorId);
        try {
          // Need to try/catch since accessing frame.environment
          // can throw "Debugger.Frame is not live"
          const frame = frameActor.frame;
          environment = frame.environment;
        } catch (e) {
          DevToolsUtils.reportException(
            "autocomplete",
            Error("The frame actor was not found: " + frameActorId)
          );
        }
      } else {
        dbgObject = this.dbg.addDebuggee(this.evalGlobal);
      }

      const result = JSPropertyProvider({
        dbgObject,
        environment,
        inputValue: text,
        cursor,
        webconsoleActor: this,
        selectedNodeActor,
        authorizedEvaluations,
        expressionVars,
      });

      if (result === null) {
        return {
          matches: null,
        };
      }

      if (result && result.isUnsafeGetter === true) {
        return {
          isUnsafeGetter: true,
          getterPath: result.getterPath,
        };
      }

      matches = result.matches || new Set();
      matchProp = result.matchProp || "";
      isElementAccess = result.isElementAccess;

      // We consider '$' as alphanumeric because it is used in the names of some
      // helper functions; we also consider whitespace as alphanum since it should not
      // be seen as break in the evaled string.
      const lastNonAlphaIsDot = /[.][a-zA-Z0-9$\s]*$/.test(reqText);

      // We only return commands and keywords when we are not dealing with a property or
      // element access.
      if (matchProp && !lastNonAlphaIsDot && !isElementAccess) {
        this._getWebConsoleCommandsCache().forEach(n => {
          // filter out `screenshot` command as it is inaccessible without the `:` prefix
          if (n !== "screenshot" && n.startsWith(result.matchProp)) {
            matches.add(n);
          }
        });

        for (const keyword of RESERVED_JS_KEYWORDS) {
          if (keyword.startsWith(result.matchProp)) {
            matches.add(keyword);
          }
        }
      }

      // Sort the results in order to display lowercased item first (e.g. we want to
      // display `document` then `Document` as we loosely match the user input if the
      // first letter was lowercase).
      const firstMeaningfulCharIndex = isElementAccess ? 1 : 0;
      matches = Array.from(matches).sort((a, b) => {
        const aFirstMeaningfulChar = a[firstMeaningfulCharIndex];
        const bFirstMeaningfulChar = b[firstMeaningfulCharIndex];
        const lA =
          aFirstMeaningfulChar.toLocaleLowerCase() === aFirstMeaningfulChar;
        const lB =
          bFirstMeaningfulChar.toLocaleLowerCase() === bFirstMeaningfulChar;
        if (lA === lB) {
          if (a === matchProp) {
            return -1;
          }
          if (b === matchProp) {
            return 1;
          }
          return a.localeCompare(b);
        }
        return lA ? -1 : 1;
      });
    }

    return {
      matches,
      matchProp,
      isElementAccess: isElementAccess === true,
    };
  },

  /**
   * The "clearMessagesCache" request handler.
   */
  clearMessagesCache: function() {
    if (isWorker) {
      // At the moment there is no mechanism available to clear the Console API cache for
      // a given worker target (See https://bugzilla.mozilla.org/show_bug.cgi?id=1674336).
      // Worker messages from the console service (e.g. error) are emitted from the main
      // thread, so this cache will be cleared when the associated document target cache
      // is cleared.
      return;
    }

    const windowId = !this.parentActor.isRootActor
      ? WebConsoleUtils.getInnerWindowId(this.global)
      : null;

    const ConsoleAPIStorage = Cc[
      "@mozilla.org/consoleAPI-storage;1"
    ].getService(Ci.nsIConsoleAPIStorage);
    ConsoleAPIStorage.clearEvents(windowId);

    CONSOLE_WORKER_IDS.forEach(id => {
      ConsoleAPIStorage.clearEvents(id);
    });

    if (this.parentActor.isRootActor || !this.global) {
      // If were dealing with the root actor (e.g. the browser console), we want
      // to remove all cached messages, not only the ones specific to a window.
      Services.console.reset();
    } else {
      WebConsoleUtils.getInnerWindowIDsForFrames(this.global).forEach(id =>
        Services.console.resetWindow(id)
      );
    }
  },

  /**
   * The "getPreferences" request handler.
   *
   * @param array preferences
   *        The preferences that need to be retrieved.
   * @return object
   *         The response message - a { key: value } object map.
   */
  getPreferences: function(preferences) {
    const prefs = Object.create(null);
    for (const key of preferences) {
      prefs[key] = this._prefs[key];
    }
    return { preferences: prefs };
  },

  /**
   * The "setPreferences" request handler.
   *
   * @param object preferences
   *        The preferences that need to be updated.
   */
  setPreferences: function(preferences) {
    for (const key in preferences) {
      this._prefs[key] = preferences[key];

      if (this.netmonitors) {
        if (key == "NetworkMonitor.saveRequestAndResponseBodies") {
          for (const { messageManager } of this.netmonitors) {
            messageManager.sendAsyncMessage("debug:netmonitor-preference", {
              saveRequestAndResponseBodies: this._prefs[key],
            });
          }
        } else if (key == "NetworkMonitor.throttleData") {
          for (const { messageManager } of this.netmonitors) {
            messageManager.sendAsyncMessage("debug:netmonitor-preference", {
              throttleData: this._prefs[key],
            });
          }
        }
      }
    }
    return { updated: Object.keys(preferences) };
  },

  // End of request handlers.

  /**
   * Create an object with the API we expose to the Web Console during
   * JavaScript evaluation.
   * This object inherits properties and methods from the Web Console actor.
   *
   * @private
   * @param object debuggerGlobal
   *        A Debugger.Object that wraps a content global. This is used for the
   *        Web Console Commands.
   * @return object
   *         The same object as |this|, but with an added |sandbox| property.
   *         The sandbox holds methods and properties that can be used as
   *         bindings during JS evaluation.
   */
  _getWebConsoleCommands: function(debuggerGlobal) {
    const helpers = {
      window: this.evalGlobal,
      makeDebuggeeValue: debuggerGlobal.makeDebuggeeValue.bind(debuggerGlobal),
      createValueGrip: this.createValueGrip.bind(this),
      preprocessDebuggerObject: this.preprocessDebuggerObject.bind(this),
      sandbox: Object.create(null),
      helperResult: null,
      consoleActor: this,
    };
    addWebConsoleCommands(helpers);

    const evalGlobal = this.evalGlobal;
    function maybeExport(obj, name) {
      if (typeof obj[name] != "function") {
        return;
      }

      // By default, chrome-implemented functions that are exposed to content
      // refuse to accept arguments that are cross-origin for the caller. This
      // is generally the safe thing, but causes problems for certain console
      // helpers like cd(), where we users sometimes want to pass a cross-origin
      // window. To circumvent this restriction, we use exportFunction along
      // with a special option designed for this purpose. See bug 1051224.
      obj[name] = Cu.exportFunction(obj[name], evalGlobal, {
        allowCrossOriginArguments: true,
      });
    }
    for (const name in helpers.sandbox) {
      const desc = Object.getOwnPropertyDescriptor(helpers.sandbox, name);

      // Workers don't have access to Cu so won't be able to exportFunction.
      if (!isWorker) {
        maybeExport(desc, "get");
        maybeExport(desc, "set");
        maybeExport(desc, "value");
      }
      if (desc.value) {
        // Make sure the helpers can be used during eval.
        desc.value = debuggerGlobal.makeDebuggeeValue(desc.value);
      }
      Object.defineProperty(helpers.sandbox, name, desc);
    }
    return helpers;
  },

  _getWebConsoleCommandsCache: function() {
    if (!this._webConsoleCommandsCache) {
      const helpers = {
        sandbox: Object.create(null),
      };
      addWebConsoleCommands(helpers);
      this._webConsoleCommandsCache = Object.getOwnPropertyNames(
        helpers.sandbox
      );
    }
    return this._webConsoleCommandsCache;
  },

  // Event handlers for various listeners.

  /**
   * Handler for messages received from the ConsoleServiceListener. This method
   * sends the nsIConsoleMessage to the remote Web Console client.
   *
   * @param nsIConsoleMessage message
   *        The message we need to send to the client.
   */
  onConsoleServiceMessage: function(message) {
    if (message instanceof Ci.nsIScriptError) {
      this.emit("pageError", {
        pageError: this.preparePageErrorForRemote(message),
      });
    } else {
      this.emit("logMessage", {
        message: this._createStringGrip(message.message),
        timeStamp: message.timeStamp,
      });
    }
  },

  getActorIdForInternalSourceId(id) {
    const actor = this.parentActor.sourcesManager.getSourceActorByInternalSourceId(
      id
    );
    return actor ? actor.actorID : null;
  },

  /**
   * Prepare a SavedFrame stack to be sent to the client.
   *
   * @param SavedFrame errorStack
   *        Stack for an error we need to send to the client.
   * @return object
   *         The object you can send to the remote client.
   */
  prepareStackForRemote(errorStack) {
    // Convert stack objects to the JSON attributes expected by client code
    // Bug 1348885: If the global from which this error came from has been
    // nuked, stack is going to be a dead wrapper.
    if (!errorStack || (Cu && Cu.isDeadWrapper(errorStack))) {
      return null;
    }
    const stack = [];
    let s = errorStack;
    while (s) {
      stack.push({
        filename: s.source,
        sourceId: this.getActorIdForInternalSourceId(s.sourceId),
        lineNumber: s.line,
        columnNumber: s.column,
        functionName: s.functionDisplayName,
        asyncCause: s.asyncCause ? s.asyncCause : undefined,
      });
      s = s.parent || s.asyncParent;
    }
    return stack;
  },

  /**
   * Prepare an nsIScriptError to be sent to the client.
   *
   * @param nsIScriptError pageError
   *        The page error we need to send to the client.
   * @return object
   *         The object you can send to the remote client.
   */
  preparePageErrorForRemote: function(pageError) {
    const stack = this.prepareStackForRemote(pageError.stack);
    let lineText = pageError.sourceLine;
    if (
      lineText &&
      lineText.length > DevToolsServer.LONG_STRING_INITIAL_LENGTH
    ) {
      lineText = lineText.substr(0, DevToolsServer.LONG_STRING_INITIAL_LENGTH);
    }

    let notesArray = null;
    const notes = pageError.notes;
    if (notes?.length) {
      notesArray = [];
      for (let i = 0, len = notes.length; i < len; i++) {
        const note = notes.queryElementAt(i, Ci.nsIScriptErrorNote);
        notesArray.push({
          messageBody: this._createStringGrip(note.errorMessage),
          frame: {
            source: note.sourceName,
            sourceId: this.getActorIdForInternalSourceId(note.sourceId),
            line: note.lineNumber,
            column: note.columnNumber,
          },
        });
      }
    }

    // If there is no location information in the error but we have a stack,
    // fill in the location with the first frame on the stack.
    let { sourceName, sourceId, lineNumber, columnNumber } = pageError;
    if (!sourceName && !sourceId && !lineNumber && !columnNumber && stack) {
      sourceName = stack[0].filename;
      sourceId = stack[0].sourceId;
      lineNumber = stack[0].lineNumber;
      columnNumber = stack[0].columnNumber;
    }

    const isCSSMessage = pageError.category === MESSAGE_CATEGORY.CSS_PARSER;

    const result = {
      errorMessage: this._createStringGrip(pageError.errorMessage),
      errorMessageName: isCSSMessage ? undefined : pageError.errorMessageName,
      exceptionDocURL: ErrorDocs.GetURL(pageError),
      sourceName,
      sourceId: this.getActorIdForInternalSourceId(sourceId),
      lineText,
      lineNumber,
      columnNumber,
      category: pageError.category,
      innerWindowID: pageError.innerWindowID,
      timeStamp: pageError.timeStamp,
      warning: !!(pageError.flags & pageError.warningFlag),
      error: !(pageError.flags & (pageError.warningFlag | pageError.infoFlag)),
      info: !!(pageError.flags & pageError.infoFlag),
      private: pageError.isFromPrivateWindow,
      stacktrace: stack,
      notes: notesArray,
      chromeContext: pageError.isFromChromeContext,
      isPromiseRejection: isCSSMessage
        ? undefined
        : pageError.isPromiseRejection,
      isForwardedFromContentProcess: pageError.isForwardedFromContentProcess,
      cssSelectors: isCSSMessage ? pageError.cssSelectors : undefined,
    };

    // If the pageError does have an exception object, we want to return the grip for it,
    // but only if we do manage to get the grip, as we're checking the property on the
    // client to render things differently.
    if (pageError.hasException) {
      try {
        const obj = this.makeDebuggeeValue(pageError.exception, true);
        if (obj?.class !== "DeadObject") {
          result.exception = this.createValueGrip(obj);
          result.hasException = true;
        }
      } catch (e) {}
    }

    return result;
  },

  /**
   * Handler for window.console API calls received from the ConsoleAPIListener.
   * This method sends the object to the remote Web Console client.
   *
   * @see ConsoleAPIListener
   * @param object message
   *        The console API call we need to send to the remote client.
   */
  onConsoleAPICall: function(message) {
    this.emit("consoleAPICall", {
      message: this.prepareConsoleMessageForRemote(message),
    });
  },

  /**
   * Handler for the DocumentEventsListener.
   *
   * @see DocumentEventsListener
   * @param {String} name
   *        The document event name that either of followings.
   *        - dom-loading
   *        - dom-interactive
   *        - dom-complete
   * @param {Number} time
   *        The time that the event is fired.
   */
  onDocumentEvent: function(name, time) {
    this.emit("documentEvent", {
      name,
      time,
    });
  },

  /**
   * Send a new HTTP request from the target's window.
   *
   * @param object request
   *        The details of the HTTP request.
   */
  async sendHTTPRequest(request) {
    const { url, method, headers, body, cause } = request;
    // Set the loadingNode and loadGroup to the target document - otherwise the
    // request won't show up in the opened netmonitor.
    const doc = this.global.document;

    const channel = NetUtil.newChannel({
      uri: NetUtil.newURI(url),
      loadingNode: doc,
      securityFlags: Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL,
      contentPolicyType:
        stringToCauseType(cause.type) || Ci.nsIContentPolicy.TYPE_OTHER,
    });

    channel.QueryInterface(Ci.nsIHttpChannel);

    channel.loadGroup = doc.documentLoadGroup;
    channel.loadFlags |=
      Ci.nsIRequest.LOAD_BYPASS_CACHE |
      Ci.nsIRequest.INHIBIT_CACHING |
      Ci.nsIRequest.LOAD_ANONYMOUS;

    channel.requestMethod = method;
    if (headers) {
      for (const { name, value } of headers) {
        if (name.toLowerCase() == "referer") {
          // The referer header and referrerInfo object should always match. So
          // if we want to set the header from privileged context, we should set
          // referrerInfo. The referrer header will get set internally.
          channel.setNewReferrerInfo(
            value,
            Ci.nsIReferrerInfo.UNSAFE_URL,
            true
          );
        } else {
          channel.setRequestHeader(name, value, false);
        }
      }
    }

    if (body) {
      channel.QueryInterface(Ci.nsIUploadChannel2);
      const bodyStream = Cc[
        "@mozilla.org/io/string-input-stream;1"
      ].createInstance(Ci.nsIStringInputStream);
      bodyStream.setData(body, body.length);
      channel.explicitSetUploadStream(bodyStream, null, -1, method, false);
    }

    NetUtil.asyncFetch(channel, () => {});

    if (!this.netmonitors) {
      return null;
    }
    const { channelId } = channel;
    // Only query the NetworkMonitorActor running in the parent process, where the
    // request will be done. There always is one listener running in the parent process,
    // see startListeners.
    const netmonitor = this.netmonitors.filter(
      ({ parentProcess }) => parentProcess
    )[0];
    const { messageManager } = netmonitor;
    return new Promise(resolve => {
      const onMessage = ({ data }) => {
        if (data.channelId == channelId) {
          messageManager.removeMessageListener(
            "debug:get-network-event-actor:response",
            onMessage
          );
          resolve({
            eventActor: data.actor,
          });
        }
      };
      messageManager.addMessageListener(
        "debug:get-network-event-actor:response",
        onMessage
      );
      messageManager.sendAsyncMessage("debug:get-network-event-actor:request", {
        channelId,
      });
    });
  },

  /**
   * Send a message to all the netmonitor message managers, and resolve when
   * all of them replied with the expected responseName message.
   *
   * @param {String} messageName
   *        Name of the message to send via the netmonitor message managers.
   * @param {String} responseName
   *        Name of the message that should be received when the message has
   *        been processed by the netmonitor instance.
   * @param {Object} args
   *        argument object passed with the initial message.
   */
  async _sendMessageToNetmonitors(messageName, responseName, args) {
    if (!this.netmonitors) {
      return null;
    }
    const results = await Promise.all(
      this.netmonitors.map(({ messageManager }) => {
        const onResponseReceived = new Promise(resolve => {
          messageManager.addMessageListener(responseName, function onResponse(
            response
          ) {
            messageManager.removeMessageListener(responseName, onResponse);
            resolve(response);
          });
        });
        messageManager.sendAsyncMessage(messageName, args);
        return onResponseReceived;
      })
    );

    return results;
  },

  /**
   * Block a request based on certain filtering options.
   *
   * Currently, an exact URL match is the only supported filter type.
   * In the future, there may be other types of filters, such as domain.
   * For now, ignore anything other than URL.
   *
   * @param object filter
   *   An object containing a `url` key with a URL to block.
   */
  async blockRequest(filter) {
    await this._sendMessageToNetmonitors(
      "debug:block-request",
      "debug:block-request:response",
      { filter }
    );

    return {};
  },

  /**
   * Unblock a request based on certain filtering options.
   *
   * Currently, an exact URL match is the only supported filter type.
   * In the future, there may be other types of filters, such as domain.
   * For now, ignore anything other than URL.
   *
   * @param object filter
   *   An object containing a `url` key with a URL to unblock.
   */
  async unblockRequest(filter) {
    await this._sendMessageToNetmonitors(
      "debug:unblock-request",
      "debug:unblock-request:response",
      { filter }
    );

    return {};
  },

  /*
   * Gets the list of blocked request urls as per the backend
   */
  async getBlockedUrls() {
    const responses =
      (await this._sendMessageToNetmonitors(
        "debug:get-blocked-urls",
        "debug:get-blocked-urls:response"
      )) || [];
    if (!responses || responses.length == 0) {
      return [];
    }

    return Array.from(
      new Set(
        responses
          .filter(response => response.data)
          .map(response => response.data)
      )
    );
  },

  /**
   * Sets the list of blocked request URLs as provided by the netmonitor frontend
   *
   * This match will be a (String).includes match, not an exact URL match
   *
   * @param object filter
   *   An object containing a `url` key with a URL to unblock.
   */
  async setBlockedUrls(urls) {
    await this._sendMessageToNetmonitors(
      "debug:set-blocked-urls",
      "debug:set-blocked-urls:response",
      { urls }
    );

    return {};
  },

  /**
   * Handler for file activity. This method sends the file request information
   * to the remote Web Console client.
   *
   * @see ConsoleFileActivityListener
   * @param string fileURI
   *        The requested file URI.
   */
  onFileActivity: function(fileURI) {
    this.emit("fileActivity", {
      uri: fileURI,
    });
  },

  // End of event handlers for various listeners.

  /**
   * Prepare a message from the console API to be sent to the remote Web Console
   * instance.
   *
   * @param object message
   *        The original message received from console-api-log-event.
   * @param boolean aUseObjectGlobal
   *        If |true| the object global is determined and added as a debuggee,
   *        otherwise |this.global| is used when makeDebuggeeValue() is invoked.
   * @return object
   *         The object that can be sent to the remote client.
   */
  prepareConsoleMessageForRemote: function(message, useObjectGlobal = true) {
    const result = WebConsoleUtils.cloneObject(message);

    result.workerType = WebConsoleUtils.getWorkerType(result) || "none";
    result.sourceId = this.getActorIdForInternalSourceId(result.sourceId);

    delete result.wrappedJSObject;
    delete result.ID;
    delete result.innerID;
    delete result.consoleID;

    if (result.stacktrace) {
      result.stacktrace = result.stacktrace.map(frame => {
        return {
          ...frame,
          sourceId: this.getActorIdForInternalSourceId(frame.sourceId),
        };
      });
    }

    result.arguments = (message.arguments || []).map(obj => {
      const dbgObj = this.makeDebuggeeValue(obj, useObjectGlobal);
      return this.createValueGrip(dbgObj);
    });

    result.styles = (message.styles || []).map(string => {
      return this.createValueGrip(string);
    });

    if (result.level === "table") {
      const tableItems = this._getConsoleTableMessageItems(result);
      if (tableItems) {
        result.arguments[0].ownProperties = tableItems;
        result.arguments[0].preview = null;
      }

      // Only return the 2 first params.
      result.arguments = result.arguments.slice(0, 2);
    }

    result.category = message.category || "webdev";
    result.innerWindowID = message.innerID;

    return result;
  },

  /**
   * Return the properties needed to display the appropriate table for a given
   * console.table call.
   * This function does a little more than creating an ObjectActor for the first
   * parameter of the message. When layout out the console table in the output, we want
   * to be able to look into sub-properties so the table can have a different layout (
   * for arrays of arrays, objects with objects properties, arrays of objects, …).
   * So here we need to retrieve the properties of the first parameter, and also all the
   * sub-properties we might need.
   *
   * @param {Object} result: The console.table message.
   * @returns {Object} An object containing the properties of the first argument of the
   *                   console.table call.
   */
  _getConsoleTableMessageItems: function(result) {
    if (
      !result ||
      !Array.isArray(result.arguments) ||
      result.arguments.length == 0
    ) {
      return null;
    }

    const [tableItemGrip] = result.arguments;
    const dataType = tableItemGrip.class;
    const needEntries = ["Map", "WeakMap", "Set", "WeakSet"].includes(dataType);
    const ignoreNonIndexedProperties = isArray(tableItemGrip);

    const tableItemActor = this.getActorByID(tableItemGrip.actor);
    if (!tableItemActor) {
      return null;
    }

    // Retrieve the properties (or entries for Set/Map) of the console table first arg.
    const iterator = needEntries
      ? tableItemActor.enumEntries()
      : tableItemActor.enumProperties({
          ignoreNonIndexedProperties,
        });
    const { ownProperties } = iterator.all();

    // The iterator returns a descriptor for each property, wherein the value could be
    // in one of those sub-property.
    const descriptorKeys = ["safeGetterValues", "getterValue", "value"];

    Object.values(ownProperties).forEach(desc => {
      if (typeof desc !== "undefined") {
        descriptorKeys.forEach(key => {
          if (desc && desc.hasOwnProperty(key)) {
            const grip = desc[key];

            // We need to load sub-properties as well to render the table in a nice way.
            const actor = grip && this.getActorByID(grip.actor);
            if (actor) {
              const res = actor
                .enumProperties({
                  ignoreNonIndexedProperties: isArray(grip),
                })
                .all();
              if (res?.ownProperties) {
                desc[key].ownProperties = res.ownProperties;
              }
            }
          }
        });
      }
    });

    return ownProperties;
  },

  /**
   * Notification observer for the "last-pb-context-exited" topic.
   *
   * @private
   * @param object subject
   *        Notification subject - in this case it is the inner window ID that
   *        was destroyed.
   * @param string topic
   *        Notification topic.
   */
  _onObserverNotification: function(subject, topic) {
    if (topic === "last-pb-context-exited") {
      this.emit("lastPrivateContextExited");
    }
  },

  /**
   * The "will-navigate" progress listener. This is used to clear the current
   * eval scope.
   */
  _onWillNavigate: function({ window, isTopLevel }) {
    if (isTopLevel) {
      this._evalGlobal = null;
      EventEmitter.off(this.parentActor, "will-navigate", this._onWillNavigate);
      this._progressListenerActive = false;
    }
  },

  /**
   * This listener is called when we switch to another frame,
   * mostly to unregister previous listeners and start listening on the new document.
   */
  _onChangedToplevelDocument: function() {
    // Convert the Set to an Array
    const listeners = [...this._listeners];

    // Unregister existing listener on the previous document
    // (pass a copy of the array as it will shift from it)
    this.stopListeners(listeners.slice());

    // This method is called after this.global is changed,
    // so we register new listener on this new global
    this.startListeners(listeners);

    // Also reset the cached top level chrome window being targeted
    this._lastChromeWindow = null;
  },
});

exports.WebConsoleActor = WebConsoleActor;