File: Navigation.cpp

package info (click to toggle)
firefox 144.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,637,504 kB
  • sloc: cpp: 7,576,692; javascript: 6,430,831; ansic: 3,748,119; python: 1,398,978; xml: 628,810; asm: 438,679; java: 186,194; sh: 63,212; makefile: 19,159; objc: 13,086; perl: 12,986; yacc: 4,583; cs: 3,846; pascal: 3,448; lex: 1,720; ruby: 1,003; exp: 762; php: 436; lisp: 258; awk: 247; sql: 66; sed: 53; csh: 10
file content (1870 lines) | stat: -rw-r--r-- 69,021 bytes parent folder | download | duplicates (2)
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
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 sts=2 et sw=2 tw=80: */
/* 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/. */

#include "mozilla/dom/Navigation.h"

#include "fmt/format.h"
#include "jsapi.h"
#include "mozilla/CycleCollectedJSContext.h"
#include "mozilla/CycleCollectedUniquePtr.h"
#include "mozilla/HoldDropJSObjects.h"
#include "mozilla/Logging.h"
#include "mozilla/StaticPrefs_dom.h"
#include "mozilla/UniquePtr.h"
#include "mozilla/dom/DOMException.h"
#include "mozilla/dom/Document.h"
#include "mozilla/dom/ErrorEvent.h"
#include "mozilla/dom/Event.h"
#include "mozilla/dom/FeaturePolicy.h"
#include "mozilla/dom/NavigationActivation.h"
#include "mozilla/dom/NavigationBinding.h"
#include "mozilla/dom/NavigationCurrentEntryChangeEvent.h"
#include "mozilla/dom/NavigationHistoryEntry.h"
#include "mozilla/dom/NavigationTransition.h"
#include "mozilla/dom/NavigationUtils.h"
#include "mozilla/dom/Promise-inl.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/dom/RootedDictionary.h"
#include "mozilla/dom/SessionHistoryEntry.h"
#include "mozilla/dom/WindowContext.h"
#include "mozilla/dom/WindowGlobalChild.h"
#include "nsContentUtils.h"
#include "nsCycleCollectionParticipant.h"
#include "nsDocShell.h"
#include "nsGlobalWindowInner.h"
#include "nsIPrincipal.h"
#include "nsISHistory.h"
#include "nsIStructuredCloneContainer.h"
#include "nsIXULRuntime.h"
#include "nsNetUtil.h"
#include "nsTHashtable.h"

mozilla::LazyLogModule gNavigationLog("Navigation");

#define LOG_FMT(format, ...) \
  MOZ_LOG_FMT(gNavigationLog, LogLevel::Debug, format, ##__VA_ARGS__);

namespace mozilla::dom {

static void InitNavigationResult(NavigationResult& aResult,
                                 const RefPtr<Promise>& aCommitted,
                                 const RefPtr<Promise>& aFinished) {
  if (aCommitted) {
    aResult.mCommitted.Reset();
    aResult.mCommitted.Construct(*aCommitted);
  }

  if (aFinished) {
    aResult.mFinished.Reset();
    aResult.mFinished.Construct(*aFinished);
  }
}

struct NavigationAPIMethodTracker final : public nsISupports {
  NS_DECL_CYCLE_COLLECTING_ISUPPORTS
  NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(NavigationAPIMethodTracker)

  NavigationAPIMethodTracker(Navigation* aNavigationObject,
                             const Maybe<nsID> aKey, const JS::Value& aInfo,
                             nsIStructuredCloneContainer* aSerializedState,
                             NavigationHistoryEntry* aCommittedToEntry,
                             Promise* aCommittedPromise,
                             Promise* aFinishedPromise)
      : mNavigationObject(aNavigationObject),
        mKey(aKey),
        mInfo(aInfo),
        mSerializedState(aSerializedState),
        mCommittedToEntry(aCommittedToEntry),
        mCommittedPromise(aCommittedPromise),
        mFinishedPromise(aFinishedPromise) {
    mozilla::HoldJSObjects(this);
  }

  // https://html.spec.whatwg.org/#navigation-api-method-tracker-clean-up
  void CleanUp() { Navigation::CleanUp(this); }

  // https://html.spec.whatwg.org/#notify-about-the-committed-to-entry
  void NotifyAboutCommittedToEntry(NavigationHistoryEntry* aNHE) {
    MOZ_DIAGNOSTIC_ASSERT(mCommittedPromise);
    // Step 1
    mCommittedToEntry = aNHE;
    if (mSerializedState) {
      // Step 2
      aNHE->SetState(
          static_cast<nsStructuredCloneContainer*>(mSerializedState.get()));
      // At this point, apiMethodTracker's serialized state is no longer needed.
      // We drop it do now for efficiency.
      mSerializedState = nullptr;
    }
    mCommittedPromise->MaybeResolve(aNHE);
  }

  // https://html.spec.whatwg.org/#resolve-the-finished-promise
  void ResolveFinishedPromise() {
    MOZ_DIAGNOSTIC_ASSERT(mFinishedPromise);
    // Step 1
    MOZ_DIAGNOSTIC_ASSERT(mCommittedToEntry);
    // Step 2
    mFinishedPromise->MaybeResolve(mCommittedToEntry);
    // Step 3
    CleanUp();
  }

  // https://html.spec.whatwg.org/#reject-the-finished-promise
  void RejectFinishedPromise(JS::Handle<JS::Value> aException) {
    MOZ_DIAGNOSTIC_ASSERT(mFinishedPromise);
    MOZ_DIAGNOSTIC_ASSERT(mCommittedPromise);
    // Step 1
    mCommittedPromise->MaybeReject(aException);
    // Step 2
    mFinishedPromise->MaybeReject(aException);
    // Step 3
    CleanUp();
  }

  // https://html.spec.whatwg.org/#navigation-api-method-tracker-derived-result
  void CreateResult(NavigationResult& aResult) {
    // A navigation API method tracker-derived result for a navigation API
    // method tracker is a NavigationResult dictionary instance given by
    // «[ "committed" → apiMethodTracker's committed promise,
    //    "finished" → apiMethodTracker's finished promise ]».
    InitNavigationResult(aResult, mCommittedPromise, mFinishedPromise);
  }

  Promise* CommittedPromise() { return mCommittedPromise; }
  Promise* FinishedPromise() { return mFinishedPromise; }

  RefPtr<Navigation> mNavigationObject;
  Maybe<nsID> mKey;
  JS::Heap<JS::Value> mInfo;

 private:
  ~NavigationAPIMethodTracker() { mozilla::DropJSObjects(this); };

  RefPtr<nsIStructuredCloneContainer> mSerializedState;
  RefPtr<NavigationHistoryEntry> mCommittedToEntry;
  RefPtr<Promise> mCommittedPromise;
  RefPtr<Promise> mFinishedPromise;
};

NS_IMPL_CYCLE_COLLECTION_WITH_JS_MEMBERS(NavigationAPIMethodTracker,
                                         (mNavigationObject, mSerializedState,
                                          mCommittedToEntry, mCommittedPromise,
                                          mFinishedPromise),
                                         (mInfo))

NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(NavigationAPIMethodTracker)
  NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END

NS_IMPL_CYCLE_COLLECTING_ADDREF(NavigationAPIMethodTracker)
NS_IMPL_CYCLE_COLLECTING_RELEASE(NavigationAPIMethodTracker)

NS_IMPL_CYCLE_COLLECTION_INHERITED(Navigation, DOMEventTargetHelper, mEntries,
                                   mOngoingNavigateEvent, mTransition,
                                   mActivation, mOngoingAPIMethodTracker,
                                   mUpcomingNonTraverseAPIMethodTracker,
                                   mUpcomingTraverseAPIMethodTrackers);
NS_IMPL_ADDREF_INHERITED(Navigation, DOMEventTargetHelper)
NS_IMPL_RELEASE_INHERITED(Navigation, DOMEventTargetHelper)

NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(Navigation)
NS_INTERFACE_MAP_END_INHERITING(DOMEventTargetHelper)

Navigation::Navigation(nsPIDOMWindowInner* aWindow)
    : DOMEventTargetHelper(aWindow) {
  MOZ_ASSERT(aWindow);
}

JSObject* Navigation::WrapObject(JSContext* aCx,
                                 JS::Handle<JSObject*> aGivenProto) {
  return Navigation_Binding::Wrap(aCx, this, aGivenProto);
}

void Navigation::EventListenerAdded(nsAtom* aType) {
  UpdateNeedsTraverse();

  EventTarget::EventListenerAdded(aType);
}

void Navigation::EventListenerRemoved(nsAtom* aType) {
  UpdateNeedsTraverse();
  EventTarget::EventListenerRemoved(aType);
}

/* static */
bool Navigation::IsAPIEnabled(JSContext* /* unused */, JSObject* /* unused */) {
  return SessionHistoryInParent() &&
         StaticPrefs::dom_navigation_webidl_enabled_DoNotUseDirectly();
}

void Navigation::Entries(
    nsTArray<RefPtr<NavigationHistoryEntry>>& aResult) const {
  aResult = mEntries.Clone();
}

already_AddRefed<NavigationHistoryEntry> Navigation::GetCurrentEntry() const {
  if (HasEntriesAndEventsDisabled()) {
    return nullptr;
  }

  if (!mCurrentEntryIndex) {
    return nullptr;
  }

  MOZ_LOG(gNavigationLog, LogLevel::Debug,
          ("Current Entry: %d; Amount of Entries: %d", int(*mCurrentEntryIndex),
           int(mEntries.Length())));
  MOZ_ASSERT(*mCurrentEntryIndex < mEntries.Length());

  RefPtr entry{mEntries[*mCurrentEntryIndex]};
  return entry.forget();
}

// https://html.spec.whatwg.org/#dom-navigation-updatecurrententry
void Navigation::UpdateCurrentEntry(
    JSContext* aCx, const NavigationUpdateCurrentEntryOptions& aOptions,
    ErrorResult& aRv) {
  RefPtr currentEntry(GetCurrentEntry());
  if (!currentEntry) {
    aRv.ThrowInvalidStateError(
        "Can't call updateCurrentEntry without a valid entry.");
    return;
  }

  JS::Rooted<JS::Value> state(aCx, aOptions.mState);
  auto serializedState = MakeRefPtr<nsStructuredCloneContainer>();
  nsresult rv = serializedState->InitFromJSVal(state, aCx);
  if (NS_FAILED(rv)) {
    aRv.ThrowDataCloneError(
        "Failed to serialize value for updateCurrentEntry.");
    return;
  }

  currentEntry->SetState(serializedState);

  NavigationCurrentEntryChangeEventInit init;
  init.mFrom = currentEntry;
  // Leaving the navigation type unspecified means it will be initialized to
  // null.
  RefPtr event = NavigationCurrentEntryChangeEvent::Constructor(
      this, u"currententrychange"_ns, init);
  DispatchEvent(*event);
}

NavigationTransition* Navigation::GetTransition() const { return mTransition; }

NavigationActivation* Navigation::GetActivation() const { return mActivation; }

// https://html.spec.whatwg.org/#has-entries-and-events-disabled
bool Navigation::HasEntriesAndEventsDisabled() const {
  Document* doc = GetAssociatedDocument();
  return !doc || !doc->IsCurrentActiveDocument() ||
         (NS_IsAboutBlankAllowQueryAndFragment(doc->GetDocumentURI()) &&
          doc->IsInitialDocument()) ||
         doc->GetPrincipal()->GetIsNullPrincipal();
}

// https://html.spec.whatwg.org/#initialize-the-navigation-api-entries-for-a-new-document
void Navigation::InitializeHistoryEntries(
    mozilla::Span<const SessionHistoryInfo> aNewSHInfos,
    const SessionHistoryInfo* aInitialSHInfo) {
  LOG_FMT("Attempting to initialize history entries for {}.",
          aInitialSHInfo->GetURI()
              ? aInitialSHInfo->GetURI()->GetSpecOrDefault()
              : "<no uri>"_ns)

  mEntries.Clear();
  mCurrentEntryIndex.reset();
  if (HasEntriesAndEventsDisabled()) {
    return;
  }

  for (auto i = 0ul; i < aNewSHInfos.Length(); i++) {
    mEntries.AppendElement(MakeRefPtr<NavigationHistoryEntry>(
        GetOwnerGlobal(), &aNewSHInfos[i], i));
    if (aNewSHInfos[i].NavigationKey() == aInitialSHInfo->NavigationKey()) {
      mCurrentEntryIndex = Some(i);
    }
  }

  LogHistory();

  nsID key = aInitialSHInfo->NavigationKey();
  nsID id = aInitialSHInfo->NavigationId();
  MOZ_LOG(
      gNavigationLog, LogLevel::Debug,
      ("aInitialSHInfo: %s %s\n", key.ToString().get(), id.ToString().get()));
}

// https://html.spec.whatwg.org/#update-the-navigation-api-entries-for-a-same-document-navigation
void Navigation::UpdateEntriesForSameDocumentNavigation(
    SessionHistoryInfo* aDestinationSHE, NavigationType aNavigationType) {
  // Step 1.
  if (HasEntriesAndEventsDisabled()) {
    return;
  }

  MOZ_LOG(gNavigationLog, LogLevel::Debug,
          ("Updating entries for same-document navigation"));

  // Steps 2-7.
  RefPtr<NavigationHistoryEntry> oldCurrentEntry = GetCurrentEntry();
  nsTArray<RefPtr<NavigationHistoryEntry>> disposedEntries;
  switch (aNavigationType) {
    case NavigationType::Traverse:
      MOZ_LOG(gNavigationLog, LogLevel::Debug, ("Traverse navigation"));
      mCurrentEntryIndex.reset();
      for (auto i = 0ul; i < mEntries.Length(); i++) {
        if (mEntries[i]->IsSameEntry(aDestinationSHE)) {
          mCurrentEntryIndex = Some(i);
          break;
        }
      }
      MOZ_ASSERT(mCurrentEntryIndex);
      break;

    case NavigationType::Push:
      MOZ_LOG(gNavigationLog, LogLevel::Debug, ("Push navigation"));
      mCurrentEntryIndex =
          Some(mCurrentEntryIndex ? *mCurrentEntryIndex + 1 : 0);
      while (*mCurrentEntryIndex < mEntries.Length()) {
        disposedEntries.AppendElement(mEntries.PopLastElement());
      }
      mEntries.AppendElement(MakeRefPtr<NavigationHistoryEntry>(
          GetOwnerGlobal(), aDestinationSHE, *mCurrentEntryIndex));
      break;

    case NavigationType::Replace:
      MOZ_LOG(gNavigationLog, LogLevel::Debug, ("Replace navigation"));
      if (!oldCurrentEntry) {
        MOZ_ASSERT(false, "FIXME");
        return;
      }
      disposedEntries.AppendElement(oldCurrentEntry);
      aDestinationSHE->NavigationKey() = oldCurrentEntry->Key();
      mEntries[*mCurrentEntryIndex] = MakeRefPtr<NavigationHistoryEntry>(
          GetOwnerGlobal(), aDestinationSHE, *mCurrentEntryIndex);
      break;

    case NavigationType::Reload:
      break;
  }

  // Step 8.
  if (mOngoingAPIMethodTracker) {
    RefPtr<NavigationHistoryEntry> currentEntry = GetCurrentEntry();
    mOngoingAPIMethodTracker->NotifyAboutCommittedToEntry(currentEntry);
  }

  for (auto& entry : disposedEntries) {
    entry->ResetIndexForDisposal();
  }

  // Steps 9-12.
  {
    nsAutoMicroTask mt;
    AutoEntryScript aes(GetOwnerGlobal(),
                        "UpdateEntriesForSameDocumentNavigation");

    NavigationCurrentEntryChangeEventInit init;
    init.mFrom = oldCurrentEntry;
    init.mNavigationType.SetValue(aNavigationType);
    RefPtr event = NavigationCurrentEntryChangeEvent::Constructor(
        this, u"currententrychange"_ns, init);
    DispatchEvent(*event);

    for (const auto& entry : disposedEntries) {
      RefPtr<Event> event = NS_NewDOMEvent(entry, nullptr, nullptr);
      event->InitEvent(u"dispose"_ns, false, false);
      event->SetTrusted(true);
      event->SetTarget(entry);
      entry->DispatchEvent(*event);
    }
  }
}

// https://html.spec.whatwg.org/#update-the-navigation-api-entries-for-reactivation
void Navigation::UpdateForReactivation(SessionHistoryInfo* aReactivatedEntry) {
  // NAV-TODO
}

// https://html.spec.whatwg.org/#navigation-api-early-error-result
void Navigation::SetEarlyErrorResult(JSContext* aCx, NavigationResult& aResult,
                                     ErrorResult&& aRv) const {
  MOZ_ASSERT(aRv.Failed());
  // An early error result for an exception e is a NavigationResult dictionary
  // instance given by
  // «[ "committed" → a promise rejected with e,
  //    "finished" → a promise rejected with e ]».

  RefPtr global = GetOwnerGlobal();
  if (!global) {
    // Creating a promise should only fail if there is no global.
    // In this case, the only solution is to ignore the error.
    aRv.SuppressException();
    return;
  }
  JS::Rooted<JS::Value> rootedExceptionValue(aCx);
  MOZ_ALWAYS_TRUE(ToJSValue(aCx, std::move(aRv), &rootedExceptionValue));

  InitNavigationResult(
      aResult, Promise::Reject(global, rootedExceptionValue, IgnoreErrors()),
      Promise::Reject(global, rootedExceptionValue, IgnoreErrors()));
}

void Navigation::SetEarlyStateErrorResult(JSContext* aCx,
                                          NavigationResult& aResult,
                                          const nsACString& aMessage) const {
  ErrorResult rv;
  rv.ThrowInvalidStateError(aMessage);
  SetEarlyErrorResult(aCx, aResult, std::move(rv));
}

bool Navigation::CheckIfDocumentIsFullyActiveAndMaybeSetEarlyErrorResult(
    JSContext* aCx, const Document* aDocument,
    NavigationResult& aResult) const {
  if (!aDocument || !aDocument->IsFullyActive()) {
    ErrorResult rv;
    rv.ThrowInvalidStateError("Document is not fully active");
    SetEarlyErrorResult(aCx, aResult, std::move(rv));
    return false;
  }
  return true;
}

bool Navigation::CheckDocumentUnloadCounterAndMaybeSetEarlyErrorResult(
    JSContext* aCx, const Document* aDocument,
    NavigationResult& aResult) const {
  if (!aDocument || aDocument->ShouldIgnoreOpens()) {
    ErrorResult rv;
    rv.ThrowInvalidStateError("Document is unloading");
    SetEarlyErrorResult(aCx, aResult, std::move(rv));
    return false;
  }
  return true;
}

already_AddRefed<nsIStructuredCloneContainer>
Navigation::CreateSerializedStateAndMaybeSetEarlyErrorResult(
    JSContext* aCx, const JS::Value& aState, NavigationResult& aResult) const {
  JS::Rooted<JS::Value> state(aCx, aState);
  RefPtr global = GetOwnerGlobal();
  MOZ_DIAGNOSTIC_ASSERT(global);

  RefPtr<nsIStructuredCloneContainer> serializedState =
      new nsStructuredCloneContainer();
  const nsresult rv = serializedState->InitFromJSVal(state, aCx);
  if (NS_FAILED(rv)) {
    JS::Rooted<JS::Value> exception(aCx);
    if (JS_GetPendingException(aCx, &exception)) {
      JS_ClearPendingException(aCx);
      InitNavigationResult(aResult,
                           Promise::Reject(global, exception, IgnoreErrors()),
                           Promise::Reject(global, exception, IgnoreErrors()));
      return nullptr;
    }
    SetEarlyErrorResult(aCx, aResult, ErrorResult(rv));
    return nullptr;
  }
  return serializedState.forget();
}

// https://html.spec.whatwg.org/#dom-navigation-navigate
void Navigation::Navigate(JSContext* aCx, const nsAString& aUrl,
                          const NavigationNavigateOptions& aOptions,
                          NavigationResult& aResult) {
  MOZ_LOG_FMT(gNavigationLog, LogLevel::Debug,
              "Called navigation.navigate() with url = {}",
              NS_ConvertUTF16toUTF8(aUrl));
  // 4. Let document be this's relevant global object's associated Document.
  const RefPtr<Document> document = GetAssociatedDocument();
  if (!document) {
    return;
  }

  // 1. Let urlRecord be the result of parsing a URL given url, relative to
  //    this's relevant settings object.
  RefPtr<nsIURI> urlRecord;
  nsresult res = NS_NewURI(getter_AddRefs(urlRecord), aUrl, nullptr,
                           document->GetDocBaseURI());
  if (NS_FAILED(res)) {
    // 2. If urlRecord is failure, then return an early error result for a
    //    "SyntaxError" DOMException.
    ErrorResult rv;
    rv.ThrowSyntaxError("URL given to navigate() is invalid");
    SetEarlyErrorResult(aCx, aResult, std::move(rv));
    return;
  }

  // 3. If urlRecord's scheme is "javascript", then return an early error result
  //    for a "NotSupportedError" DOMException.
  if (urlRecord->SchemeIs("javascript")) {
    ErrorResult rv;
    rv.ThrowNotSupportedError("The javascript: protocol is not supported");
    SetEarlyErrorResult(aCx, aResult, std::move(rv));
    return;
  }

  // 5. If options["history"] is "push", and the navigation must be a replace
  //    given urlRecord and document, then return an early error result for a
  //    "NotSupportedError" DOMException.
  if (aOptions.mHistory == NavigationHistoryBehavior::Push &&
      nsContentUtils::NavigationMustBeAReplace(*urlRecord, *document)) {
    ErrorResult rv;
    rv.ThrowNotSupportedError("Navigation must be a replace navigation");
    SetEarlyErrorResult(aCx, aResult, std::move(rv));
    return;
  }

  // 6. Let state be options["state"], if it exists; otherwise, undefined.
  // 7. Let serializedState be StructuredSerializeForStorage(state). If this
  //    throws an exception, then return an early error result for that
  //    exception.
  nsCOMPtr<nsIStructuredCloneContainer> serializedState =
      CreateSerializedStateAndMaybeSetEarlyErrorResult(aCx, aOptions.mState,
                                                       aResult);
  if (!serializedState) {
    return;
  }

  // 8. If document is not fully active, then return an early error result for
  //    an "InvalidStateError" DOMException.
  if (!CheckIfDocumentIsFullyActiveAndMaybeSetEarlyErrorResult(aCx, document,
                                                               aResult)) {
    return;
  }

  // 9. If document's unload counter is greater than 0, then return an early
  //    error result for an "InvalidStateError" DOMException.
  if (!CheckDocumentUnloadCounterAndMaybeSetEarlyErrorResult(aCx, document,
                                                             aResult)) {
    return;
  }

  // 10. Let info be options["info"], if it exists; otherwise, undefined.
  // 11. Let apiMethodTracker be the result of maybe setting the upcoming
  //     non-traverse API method tracker for this given info and
  //     serializedState.
  JS::Rooted<JS::Value> info(aCx, aOptions.mInfo);
  RefPtr<NavigationAPIMethodTracker> apiMethodTracker =
      MaybeSetUpcomingNonTraverseAPIMethodTracker(info, serializedState);
  MOZ_ASSERT(apiMethodTracker);

  // 12. Navigate document's node navigable to urlRecord using document, with
  //     historyHandling set to options["history"] and navigationAPIState set to
  //     serializedState.

  RefPtr bc = document->GetBrowsingContext();
  MOZ_DIAGNOSTIC_ASSERT(bc);
  bc->Navigate(urlRecord, *document->NodePrincipal(),
               /* per spec, error handling defaults to false */ IgnoreErrors(),
               aOptions.mHistory, /* aShouldNotForceReplaceInOnLoad */ true);

  // 13. If this's upcoming non-traverse API method tracker is apiMethodTracker,
  //     then:
  if (mUpcomingNonTraverseAPIMethodTracker == apiMethodTracker) {
    // Note: If the upcoming non-traverse API method tracker is still
    //       apiMethodTracker, this means that the navigate algorithm bailed out
    //       before ever getting to the inner navigate event firing algorithm
    //       which would promote that upcoming API method tracker to ongoing.
    //
    // 13.1 Set this's upcoming non-traverse API method tracker to null.
    mUpcomingNonTraverseAPIMethodTracker = nullptr;
    // 13.2 Return an early error result for an "AbortError" DOMException.
    ErrorResult rv;
    rv.ThrowAbortError("Navigation aborted.");
    SetEarlyErrorResult(aCx, aResult, std::move(rv));
    return;
  }

  // 14. Return a navigation API method tracker-derived result for
  //     apiMethodTracker.
  apiMethodTracker->CreateResult(aResult);
}

// https://html.spec.whatwg.org/#performing-a-navigation-api-traversal
void Navigation::PerformNavigationTraversal(JSContext* aCx, const nsID& aKey,
                                            const NavigationOptions& aOptions,
                                            NavigationResult& aResult) {
  LOG_FMT("traverse navigation to {}", aKey.ToString().get());
  // 1. Let document be navigation's relevant global object's associated
  //    Document.
  const Document* document = GetAssociatedDocument();

  // 2. If document is not fully active, then return an early error result for
  //    an "InvalidStateError" DOMException.
  if (!document || !document->IsFullyActive()) {
    SetEarlyStateErrorResult(aCx, aResult, "Document is not fully active"_ns);
    return;
  }

  // 3. If document's unload counter is greater than 0, then return an early
  //    error result for an "InvalidStateError" DOMException.
  if (document->ShouldIgnoreOpens()) {
    SetEarlyStateErrorResult(aCx, aResult, "Document is unloading"_ns);
    return;
  }

  // 4. Let current be the current entry of navigation.
  RefPtr<NavigationHistoryEntry> current = GetCurrentEntry();
  if (!current) {
    SetEarlyStateErrorResult(aCx, aResult,
                             "No current navigation history entry"_ns);
    return;
  }

  // 5. If key equals current's session history entry's navigation API key, then
  //    return «[ "committed" → a promise resolved with current, "finished" → a
  //    promise resolved with current ]».
  RefPtr global = GetOwnerGlobal();
  if (!global) {
    return;
  }

  if (current->Key() == aKey) {
    InitNavigationResult(aResult,
                         Promise::Resolve(global, current, IgnoreErrors()),
                         Promise::Resolve(global, current, IgnoreErrors()));
    return;
  }

  // 6. If navigation's upcoming traverse API method trackers[key] exists, then
  //    return a navigation API method tracker-derived result for navigation's
  //    upcoming traverse API method trackers[key].
  if (auto maybeTracker =
          mUpcomingTraverseAPIMethodTrackers.MaybeGet(aKey).valueOr(nullptr)) {
    maybeTracker->CreateResult(aResult);
    return;
  }

  // 7. Let info be options["info"], if it exists; otherwise, undefined.
  JS::Rooted<JS::Value> info(aCx, aOptions.mInfo);

  // 8. Let apiMethodTracker be the result of adding an upcoming traverse API
  //    method tracker for navigation given key and info.
  RefPtr apiMethodTracker = AddUpcomingTraverseAPIMethodTracker(aKey, info);

  // 9. Let navigable be document's node navigable.
  RefPtr<BrowsingContext> navigable = document->GetBrowsingContext();

  // 10. Let traversable be navigable's traversable navigable.
  RefPtr<BrowsingContext> traversable = navigable->Top();
  // 11. Let sourceSnapshotParams be the result of snapshotting source snapshot
  //     params given document.

  // 13. Return a navigation API method tracker-derived result for
  //     apiMethodTracker.
  apiMethodTracker->CreateResult(aResult);

  // 12. Append the following session history traversal steps to traversable:
  auto* childSHistory = traversable->GetChildSessionHistory();
  auto performNaviationTraversalSteps =
      [finished =
           RefPtr(apiMethodTracker->FinishedPromise())](nsresult aResult) {
        switch (aResult) {
          case NS_ERROR_DOM_INVALID_STATE_ERR:
            // 12.2 Let targetSHE be the session history entry in navigableSHEs
            //      whose navigation API key is key. If no such entry exists,
            //      then:
            finished->MaybeRejectWithInvalidStateError(
                "No such entry with key found");
            break;
          case NS_ERROR_DOM_ABORT_ERR:
            // 12.5 If result is "canceled-by-beforeunload", then queue a global
            // task on the navigation and traversal task source given
            // navigation's relevant global object to reject the finished
            // promise for apiMethodTracker with a new "AbortError" DOMException
            // created in navigation's relevant realm.
            finished->MaybeRejectWithAbortError("Navigation was canceled");
            break;
          case NS_ERROR_DOM_SECURITY_ERR:
            // 12.6 If result is "initiator-disallowed", then queue a global
            // task on the
            //      navigation and traversal task source given navigation's
            //      relevant global object to reject the finished promise for
            //      apiMethodTracker with a new "SecurityError" DOMException
            //      created in navigation's relevant realm.
            finished->MaybeRejectWithSecurityError(
                "Navigation was not allowed");
            break;
          case NS_OK:
            // 12.3 If targetSHE is navigable's active session history entry,
            // then abort these steps.
            break;
          default:
            MOZ_DIAGNOSTIC_ASSERT(false, "Unexpected result");
            break;
        }
      };

  // 12.4 Let result be the result of applying the traverse history step given
  //      by targetSHE's step to traversable, given sourceSnapshotParams,
  //      navigable, and "none".
  childSHistory->AsyncGo(aKey, navigable, /*aRequireUserInteraction=*/false,
                         /*aUserActivation=*/false,
                         performNaviationTraversalSteps);
}

// https://html.spec.whatwg.org/#dom-navigation-reload
void Navigation::Reload(JSContext* aCx, const NavigationReloadOptions& aOptions,
                        NavigationResult& aResult) {
  MOZ_LOG(gNavigationLog, LogLevel::Debug, ("Called navigation.reload()"));
  // 1. Let document be this's relevant global object's associated Document.
  const RefPtr<Document> document = GetAssociatedDocument();
  if (!document) {
    return;
  }

  // 2. Let serializedState be StructuredSerializeForStorage(undefined).
  RefPtr<nsIStructuredCloneContainer> serializedState;

  // 3. If options["state"] exists, then set serializedState to
  //    StructuredSerializeForStorage(options["state"]). If this throws an
  //    exception, then return an early error result for that exception.
  if (!aOptions.mState.isUndefined()) {
    serializedState = CreateSerializedStateAndMaybeSetEarlyErrorResult(
        aCx, aOptions.mState, aResult);
    if (!serializedState) {
      return;
    }
  } else {
    // 4. Otherwise:
    // 4.1 Let current be the current entry of this.
    // 4.2 If current is not null, then set serializedState to current's
    //     session history entry's navigation API state.
    if (RefPtr<NavigationHistoryEntry> current = GetCurrentEntry()) {
      serializedState = current->GetNavigationState();
    }
  }
  // 5. If document is not fully active, then return an early error result for
  //    an "InvalidStateError" DOMException.
  if (!CheckIfDocumentIsFullyActiveAndMaybeSetEarlyErrorResult(aCx, document,
                                                               aResult)) {
    return;
  }

  // 6. If document's unload counter is greater than 0, then return an early
  //    error result for an "InvalidStateError" DOMException.
  if (!CheckDocumentUnloadCounterAndMaybeSetEarlyErrorResult(aCx, document,
                                                             aResult)) {
    return;
  }

  // 7. Let info be options["info"], if it exists; otherwise, undefined.
  JS::Rooted<JS::Value> info(aCx, aOptions.mInfo);
  // 8. Let apiMethodTracker be the result of maybe setting the upcoming
  //    non-traverse API method tracker for this given info and serializedState.
  RefPtr<NavigationAPIMethodTracker> apiMethodTracker =
      MaybeSetUpcomingNonTraverseAPIMethodTracker(info, serializedState);
  MOZ_ASSERT(apiMethodTracker);
  // 9. Reload document's node navigable with navigationAPIState set to
  //    serializedState.
  RefPtr docShell = nsDocShell::Cast(document->GetDocShell());
  MOZ_ASSERT(docShell);
  docShell->ReloadNavigable(Some(WrapNotNullUnchecked(aCx)),
                            nsIWebNavigation::LOAD_FLAGS_NONE, serializedState);

  // 10. Return a navigation API method tracker-derived result for
  //     apiMethodTracker.
  apiMethodTracker->CreateResult(aResult);
}

// https://html.spec.whatwg.org/#dom-navigation-traverseto
void Navigation::TraverseTo(JSContext* aCx, const nsAString& aKey,
                            const NavigationOptions& aOptions,
                            NavigationResult& aResult) {
  MOZ_LOG_FMT(gNavigationLog, LogLevel::Debug,
              "Called navigation.traverseTo() with key = {}",
              NS_ConvertUTF16toUTF8(aKey).get());

  // 1. If this's current entry index is −1, then return an early error result
  //    for an "InvalidStateError" DOMException.
  if (mCurrentEntryIndex.isNothing()) {
    ErrorResult rv;
    rv.ThrowInvalidStateError("Current entry index is unexpectedly -1");
    SetEarlyErrorResult(aCx, aResult, std::move(rv));
    return;
  }

  // 2. If this's entry list does not contain a NavigationHistoryEntry whose
  //    session history entry's navigation API key equals key, then return an
  //    early error result for an "InvalidStateError" DOMException.
  nsID key{};
  const bool foundKey =
      key.Parse(NS_ConvertUTF16toUTF8(aKey).Data()) &&
      std::find_if(mEntries.begin(), mEntries.end(), [&](const auto& aEntry) {
        return aEntry->Key() == key;
      }) != mEntries.end();
  if (!foundKey) {
    ErrorResult rv;
    rv.ThrowInvalidStateError("Session history entry key does not exist");
    SetEarlyErrorResult(aCx, aResult, std::move(rv));
    return;
  }

  // 3. Return the result of performing a navigation API traversal given this,
  //    key, and options.
  PerformNavigationTraversal(aCx, key, aOptions, aResult);
}

// https://html.spec.whatwg.org/#dom-navigation-back
void Navigation::Back(JSContext* aCx, const NavigationOptions& aOptions,
                      NavigationResult& aResult) {
  MOZ_LOG(gNavigationLog, LogLevel::Debug, ("Called navigation.back()"));
  // 1. If this's current entry index is −1 or 0, then return an early error
  //    result for an "InvalidStateError" DOMException.
  if (mCurrentEntryIndex.isNothing() || *mCurrentEntryIndex == 0 ||
      *mCurrentEntryIndex > mEntries.Length() - 1) {
    SetEarlyStateErrorResult(aCx, aResult,
                             "Current entry index is unexpectedly -1 or 0"_ns);
    return;
  }

  // 2. Let key be this's entry list[this's current entry index − 1]'s session
  //    history entry's navigation API key.
  MOZ_DIAGNOSTIC_ASSERT(mEntries[*mCurrentEntryIndex - 1]);
  const nsID key = mEntries[*mCurrentEntryIndex - 1]->Key();

  // 3. Return the result of performing a navigation API traversal given this,
  //    key, and options.
  PerformNavigationTraversal(aCx, key, aOptions, aResult);
}

// https://html.spec.whatwg.org/#dom-navigation-forward
void Navigation::Forward(JSContext* aCx, const NavigationOptions& aOptions,
                         NavigationResult& aResult) {
  MOZ_LOG(gNavigationLog, LogLevel::Debug, ("Called navigation.forward()"));

  // 1. If this's current entry index is −1 or is equal to this's entry list's
  //    size − 1, then return an early error result for an "InvalidStateError"
  //    DOMException.
  if (mCurrentEntryIndex.isNothing() ||
      *mCurrentEntryIndex >= mEntries.Length() - 1) {
    ErrorResult rv;
    rv.ThrowInvalidStateError(
        "Current entry index is unexpectedly -1 or entry list's size - 1");
    SetEarlyErrorResult(aCx, aResult, std::move(rv));
    return;
  }

  // 2. Let key be this's entry list[this's current entry index + 1]'s session
  //    history entry's navigation API key.
  MOZ_ASSERT(mEntries[*mCurrentEntryIndex + 1]);
  const nsID& key = mEntries[*mCurrentEntryIndex + 1]->Key();

  // 3. Return the result of performing a navigation API traversal given this,
  //    key, and options.
  PerformNavigationTraversal(aCx, key, aOptions, aResult);
}

namespace {

void LogEntry(NavigationHistoryEntry* aEntry, uint64_t aIndex, uint64_t aTotal,
              bool aIsCurrent) {
  if (!aEntry) {
    MOZ_LOG(gNavigationLog, LogLevel::Debug,
            (" +- %d NHEntry null\n", int(aIndex)));
    return;
  }

  nsString key, id;
  aEntry->GetKey(key);
  aEntry->GetId(id);
  MOZ_LOG(gNavigationLog, LogLevel::Debug,
          ("%s+- %d NHEntry %p %s %s\n", aIsCurrent ? ">" : " ", int(aIndex),
           aEntry, NS_ConvertUTF16toUTF8(key).get(),
           NS_ConvertUTF16toUTF8(id).get()));

  nsAutoString url;
  aEntry->GetUrl(url);
  MOZ_LOG(gNavigationLog, LogLevel::Debug,
          ("   URL = %s\n", NS_ConvertUTF16toUTF8(url).get()));
}

}  // namespace

// https://html.spec.whatwg.org/#fire-a-traverse-navigate-event
bool Navigation::FireTraverseNavigateEvent(
    JSContext* aCx, const SessionHistoryInfo& aDestinationSessionHistoryInfo,
    Maybe<UserNavigationInvolvement> aUserInvolvement) {
  // aDestinationSessionHistoryInfo corresponds to
  // https://html.spec.whatwg.org/#fire-navigate-traverse-destinationshe

  // To not unnecessarily create an event that's never used, step 1 and step 2
  // in #fire-a-traverse-navigate-event have been moved to after step 25 in
  // #inner-navigate-event-firing-algorithm in our implementation.

  // Step 5
  RefPtr<NavigationHistoryEntry> destinationNHE =
      FindNavigationHistoryEntry(aDestinationSessionHistoryInfo);

  // Step 6.2 and step 7.2
  RefPtr<nsStructuredCloneContainer> state =
      destinationNHE ? destinationNHE->GetNavigationState() : nullptr;

  // Step 8
  bool isSameDocument =
      ToMaybeRef(
          nsDocShell::Cast(nsContentUtils::GetDocShellForEventTarget(this)))
          .andThen([](auto& aDocShell) {
            return ToMaybeRef(aDocShell.GetActiveSessionHistoryInfo());
          })
          .map([aDestinationSessionHistoryInfo](auto& aSessionHistoryInfo) {
            return aDestinationSessionHistoryInfo.SharesDocumentWith(
                aSessionHistoryInfo);
          })
          .valueOr(false);

  // Step 3, step 4, step 6.1, and step 7.1.
  RefPtr<NavigationDestination> destination =
      MakeAndAddRef<NavigationDestination>(
          GetOwnerGlobal(), aDestinationSessionHistoryInfo.GetURI(),
          destinationNHE, state, isSameDocument);

  // Step 9
  return InnerFireNavigateEvent(
      aCx, NavigationType::Traverse, destination,
      aUserInvolvement.valueOr(UserNavigationInvolvement::None),
      /* aSourceElement */ nullptr,
      /* aFormDataEntryList*/ nullptr,
      /* aClassicHistoryAPIState */ nullptr,
      /* aDownloadRequestFilename */ VoidString());
}

// https://html.spec.whatwg.org/#fire-a-push/replace/reload-navigate-event
bool Navigation::FirePushReplaceReloadNavigateEvent(
    JSContext* aCx, NavigationType aNavigationType, nsIURI* aDestinationURL,
    bool aIsSameDocument, bool aIsSync,
    Maybe<UserNavigationInvolvement> aUserInvolvement, Element* aSourceElement,
    already_AddRefed<FormData> aFormDataEntryList,
    nsIStructuredCloneContainer* aNavigationAPIState,
    nsIStructuredCloneContainer* aClassicHistoryAPIState) {
  // To not unnecessarily create an event that's never used, step 1 and step 2
  // in #fire-a-push/replace/reload-navigate-event have been moved to after step
  // 25 in #inner-navigate-event-firing-algorithm in our implementation.

  // This is currently not how spec handles this.
  // See https://github.com/whatwg/html/issues/11184
  if (aIsSync) {
    while (HasOngoingNavigateEvent()) {
      AbortOngoingNavigation(aCx);
    }
  }

  // Step 3 to step 7
  RefPtr<NavigationDestination> destination =
      MakeAndAddRef<NavigationDestination>(GetOwnerGlobal(), aDestinationURL,
                                           /* aEntry */ nullptr,
                                           /* aState */ nullptr,
                                           aIsSameDocument);

  // Step 8
  return InnerFireNavigateEvent(
      aCx, aNavigationType, destination,
      aUserInvolvement.valueOr(UserNavigationInvolvement::None), aSourceElement,
      std::move(aFormDataEntryList), aClassicHistoryAPIState,
      /* aDownloadRequestFilename */ VoidString());
}

// https://html.spec.whatwg.org/#fire-a-download-request-navigate-event
bool Navigation::FireDownloadRequestNavigateEvent(
    JSContext* aCx, nsIURI* aDestinationURL,
    UserNavigationInvolvement aUserInvolvement, Element* aSourceElement,
    const nsAString& aFilename) {
  // To not unnecessarily create an event that's never used, step 1 and step 2
  // in #fire-a-download-request-navigate-event have been moved to after step
  // 25 in #inner-navigate-event-firing-algorithm in our implementation.

  // Step 3 to step 7
  RefPtr<NavigationDestination> destination =
      MakeAndAddRef<NavigationDestination>(GetOwnerGlobal(), aDestinationURL,
                                           /* aEntry */ nullptr,
                                           /* aState */ nullptr,
                                           /* aIsSameDocument */ false);

  // Step 8
  return InnerFireNavigateEvent(
      aCx, NavigationType::Push, destination, aUserInvolvement, aSourceElement,
      /* aFormDataEntryList */ nullptr,
      /* aClassicHistoryAPIState */ nullptr, aFilename);
}

static bool HasHistoryActionActivation(
    Maybe<nsGlobalWindowInner&> aRelevantGlobalObject) {
  return aRelevantGlobalObject
      .map([](auto& aRelevantGlobalObject) {
        WindowContext* windowContext = aRelevantGlobalObject.GetWindowContext();
        return windowContext && windowContext->HasValidHistoryActivation();
      })
      .valueOr(false);
}

static void ConsumeHistoryActionUserActivation(
    Maybe<nsGlobalWindowInner&> aRelevantGlobalObject) {
  aRelevantGlobalObject.apply([](auto& aRelevantGlobalObject) {
    if (WindowContext* windowContext =
            aRelevantGlobalObject.GetWindowContext()) {
      windowContext->ConsumeHistoryActivation();
    }
  });
}

// Implementation of this will be done in Bug 1948593.
static bool HasUAVisualTransition(Maybe<Document&>) { return false; }

static bool EqualsExceptRef(nsIURI* aURI, nsIURI* aOtherURI) {
  bool equalsExceptRef = false;
  return aURI && aOtherURI &&
         NS_SUCCEEDED(aURI->EqualsExceptRef(aOtherURI, &equalsExceptRef)) &&
         equalsExceptRef;
}

static bool Equals(nsIURI* aURI, nsIURI* aOtherURI) {
  bool equals = false;
  return aURI && aOtherURI && NS_SUCCEEDED(aURI->Equals(aOtherURI, &equals)) &&
         equals;
}

static bool HasRef(nsIURI* aURI) {
  bool hasRef = false;
  aURI->GetHasRef(&hasRef);
  return hasRef;
}

static bool HasIdenticalFragment(nsIURI* aURI, nsIURI* aOtherURI) {
  nsAutoCString ref;

  if (HasRef(aURI) != HasRef(aOtherURI)) {
    return false;
  }

  if (NS_FAILED(aURI->GetRef(ref))) {
    return false;
  }

  nsAutoCString otherRef;
  if (NS_FAILED(aOtherURI->GetRef(otherRef))) {
    return false;
  }

  return ref.Equals(otherRef);
}

static void LogEvent(Event* aEvent, NavigateEvent* aOngoingEvent,
                     const nsACString& aReason) {
  if (!MOZ_LOG_TEST(gNavigationLog, LogLevel::Debug)) {
    return;
  }

  nsAutoString eventType;
  aEvent->GetType(eventType);

  nsTArray<nsCString> log = {nsCString(aReason),
                             NS_ConvertUTF16toUTF8(eventType)};

  if (aEvent->Cancelable()) {
    log.AppendElement("cancelable");
  }

  if (aOngoingEvent) {
    log.AppendElement(
        fmt::format(FMT_STRING("{}"), aOngoingEvent->NavigationType()));

    if (RefPtr<NavigationDestination> destination =
            aOngoingEvent->Destination()) {
      log.AppendElement(destination->GetURI()->GetSpecOrDefault());
    }

    if (aOngoingEvent->HashChange()) {
      log.AppendElement("hashchange"_ns);
    }
  }

  LOG_FMT("{}", fmt::join(log.begin(), log.end(), std::string_view{" "}));
}

nsresult Navigation::FireEvent(const nsAString& aName) {
  RefPtr<Event> event = NS_NewDOMEvent(this, nullptr, nullptr);
  // it doesn't bubble, and it isn't cancelable
  event->InitEvent(aName, false, false);
  event->SetTrusted(true);
  ErrorResult rv;
  LogEvent(event, mOngoingNavigateEvent, "Fire"_ns);
  DispatchEvent(*event, rv);
  return rv.StealNSResult();
}

static void ExtractErrorInformation(JSContext* aCx,
                                    JS::Handle<JS::Value> aError,
                                    ErrorEventInit& aErrorEventInitDict) {
  nsContentUtils::ExtractErrorValues(
      aCx, aError, aErrorEventInitDict.mFilename, &aErrorEventInitDict.mLineno,
      &aErrorEventInitDict.mColno, aErrorEventInitDict.mMessage);
  aErrorEventInitDict.mError = aError;
  aErrorEventInitDict.mBubbles = false;
  aErrorEventInitDict.mCancelable = false;
}

nsresult Navigation::FireErrorEvent(const nsAString& aName,
                                    const ErrorEventInit& aEventInitDict) {
  RefPtr<Event> event = ErrorEvent::Constructor(this, aName, aEventInitDict);
  ErrorResult rv;

  LogEvent(event, mOngoingNavigateEvent, "Fire"_ns);
  DispatchEvent(*event, rv);
  return rv.StealNSResult();
}

struct NavigationWaitForAllScope final : public nsISupports,
                                         public SupportsWeakPtr {
  NavigationWaitForAllScope(Navigation* aNavigation,
                            NavigationAPIMethodTracker* aApiMethodTracker,
                            NavigateEvent* aEvent)
      : mNavigation(aNavigation),
        mAPIMethodTracker(aApiMethodTracker),
        mEvent(aEvent) {}
  NS_DECL_CYCLE_COLLECTING_ISUPPORTS
  NS_DECL_CYCLE_COLLECTION_CLASS(NavigationWaitForAllScope)
  RefPtr<Navigation> mNavigation;
  RefPtr<NavigationAPIMethodTracker> mAPIMethodTracker;
  RefPtr<NavigateEvent> mEvent;

 private:
  ~NavigationWaitForAllScope() {}
};

NS_IMPL_CYCLE_COLLECTION_WEAK_PTR(NavigationWaitForAllScope, mNavigation,
                                  mAPIMethodTracker, mEvent)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(NavigationWaitForAllScope)
  NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END

NS_IMPL_CYCLE_COLLECTING_ADDREF(NavigationWaitForAllScope)
NS_IMPL_CYCLE_COLLECTING_RELEASE(NavigationWaitForAllScope)

// https://html.spec.whatwg.org/#inner-navigate-event-firing-algorithm
bool Navigation::InnerFireNavigateEvent(
    JSContext* aCx, NavigationType aNavigationType,
    NavigationDestination* aDestination,
    UserNavigationInvolvement aUserInvolvement, Element* aSourceElement,
    already_AddRefed<FormData> aFormDataEntryList,
    nsIStructuredCloneContainer* aClassicHistoryAPIState,
    const nsAString& aDownloadRequestFilename) {
  nsCOMPtr<nsIGlobalObject> globalObject = GetOwnerGlobal();

  // Step 1
  if (HasEntriesAndEventsDisabled()) {
    // Step 1.1 to step 1.3
    MOZ_DIAGNOSTIC_ASSERT(!mOngoingAPIMethodTracker);
    MOZ_DIAGNOSTIC_ASSERT(!mUpcomingNonTraverseAPIMethodTracker);
    MOZ_DIAGNOSTIC_ASSERT(mUpcomingTraverseAPIMethodTrackers.IsEmpty());

    // Step 1.4
    return true;
  }

  RootedDictionary<NavigateEventInit> init(RootingCx());

  // Step 2
  Maybe<nsID> destinationKey;

  // Step 3
  if (auto* entry = aDestination->GetEntry()) {
    destinationKey.emplace(entry->Key());
  }

  // Step 4
  MOZ_DIAGNOSTIC_ASSERT(!destinationKey || !destinationKey->Equals(nsID{}));

  // Step 5
  PromoteUpcomingAPIMethodTrackerToOngoing(std::move(destinationKey));

  // Step 6
  RefPtr<NavigationAPIMethodTracker> apiMethodTracker =
      mOngoingAPIMethodTracker;

  // Step 7
  Maybe<BrowsingContext&> navigable =
      ToMaybeRef(GetOwnerWindow()).andThen([](auto& aWindow) {
        return ToMaybeRef(aWindow.GetBrowsingContext());
      });

  // Step 8
  Document* document =
      navigable.map([](auto& aNavigable) { return aNavigable.GetDocument(); })
          .valueOr(nullptr);

  // Step 9
  init.mCanIntercept = document &&
                       document->CanRewriteURL(aDestination->GetURI()) &&
                       (aDestination->SameDocument() ||
                        aNavigationType != NavigationType::Traverse);

  // Step 10
  bool traverseCanBeCanceled =
      navigable->IsTop() && aDestination->SameDocument() &&
      (aUserInvolvement != UserNavigationInvolvement::BrowserUI ||
       HasHistoryActionActivation(ToMaybeRef(GetOwnerWindow())));

  // Step 11
  init.mCancelable =
      aNavigationType != NavigationType::Traverse || traverseCanBeCanceled;

  // Step 13
  init.mNavigationType = aNavigationType;

  // Step 14
  init.mDestination = aDestination;

  // Step 15
  init.mDownloadRequest = aDownloadRequestFilename;

  // Step 16
  if (apiMethodTracker) {
    init.mInfo = apiMethodTracker->mInfo;
  }

  // Step 17
  init.mHasUAVisualTransition =
      HasUAVisualTransition(ToMaybeRef(GetAssociatedDocument()));

  // Step 18
  init.mSourceElement = aSourceElement;

  // Step 19
  RefPtr<AbortController> abortController = new AbortController(globalObject);

  // Step 20
  init.mSignal = abortController->Signal();

  // step 21
  nsCOMPtr<nsIURI> currentURL = document->GetDocumentURI();

  // step 22
  init.mHashChange = !aClassicHistoryAPIState && aDestination->SameDocument() &&
                     EqualsExceptRef(aDestination->GetURI(), currentURL) &&
                     !HasIdenticalFragment(aDestination->GetURI(), currentURL);

  // Step 23
  init.mUserInitiated = aUserInvolvement != UserNavigationInvolvement::None;

  // Step 24
  init.mFormData = aFormDataEntryList;

  // Step 25
  MOZ_DIAGNOSTIC_ASSERT(!mOngoingNavigateEvent);

  // We now have everything we need to fully initialize the NavigateEvent, so
  // we'll go ahead and create it now. This is done by the spec in step 1 and
  // step 2 of #fire-a-traverse-navigate-event,
  // #fire-a-push/replace/reload-navigate-event, or
  // #fire-a-download-request-navigate-event, but there's no reason to not
  // delay it until here. This also performs step 12.
  RefPtr<NavigateEvent> event = NavigateEvent::Constructor(
      this, u"navigate"_ns, init, aClassicHistoryAPIState, abortController);
  // Here we're running #concept-event-create from https://dom.spec.whatwg.org/
  // which explicitly sets event's isTrusted attribute to true.
  event->SetTrusted(true);

  // Step 26
  mOngoingNavigateEvent = event;

  // Step 27
  mFocusChangedDuringOngoingNavigation = false;

  // Step 28
  mSuppressNormalScrollRestorationDuringOngoingNavigation = false;

  // Step 29 and step 30
  LogEvent(event, mOngoingNavigateEvent, "Fire"_ns);
  if (!DispatchEvent(*event, CallerType::NonSystem, IgnoreErrors())) {
    // Step 30.1
    if (aNavigationType == NavigationType::Traverse) {
      ConsumeHistoryActionUserActivation(ToMaybeRef(GetOwnerWindow()));
    }

    // Step 30.2
    if (!abortController->Signal()->Aborted()) {
      AbortOngoingNavigation(aCx);
    }

    // Step 30.3
    return false;
  }

  // Step 31
  bool endResultIsSameDocument =
      event->InterceptionState() != NavigateEvent::InterceptionState::None ||
      aDestination->SameDocument();

  // Step 32 (and the destructor of this is step 36)
  nsAutoMicroTask mt;

  // Step 33
  if (event->InterceptionState() != NavigateEvent::InterceptionState::None) {
    // Step 33.1
    event->SetInterceptionState(NavigateEvent::InterceptionState::Committed);

    // Step 33.2
    RefPtr<NavigationHistoryEntry> fromNHE = GetCurrentEntry();

    // Step 33.3
    MOZ_DIAGNOSTIC_ASSERT(fromNHE);

    // Step 33.4
    RefPtr<Promise> promise = Promise::CreateInfallible(globalObject);
    mTransition = MakeAndAddRef<NavigationTransition>(
        globalObject, aNavigationType, fromNHE, promise);

    // Step 33.5
    MOZ_ALWAYS_TRUE(promise->SetAnyPromiseIsHandled());

    switch (aNavigationType) {
      case NavigationType::Traverse:
        // Step 33.6
        mSuppressNormalScrollRestorationDuringOngoingNavigation = true;
        break;
      case NavigationType::Push:
      case NavigationType::Replace:
        // Step 33.7
        if (nsDocShell* docShell = nsDocShell::Cast(document->GetDocShell())) {
          docShell->UpdateURLAndHistory(
              document, aDestination->GetURI(), event->ClassicHistoryAPIState(),
              *NavigationUtils::NavigationHistoryBehavior(aNavigationType),
              document->GetDocumentURI(),
              Equals(aDestination->GetURI(), document->GetDocumentURI()));
        }
        break;
      case NavigationType::Reload:
        // Step 33.8
        if (nsDocShell* docShell = nsDocShell::Cast(document->GetDocShell())) {
          UpdateEntriesForSameDocumentNavigation(
              docShell->GetActiveSessionHistoryInfo(), aNavigationType);
        }
        break;
      default:
        break;
    }
  }

  // Step 34
  if (endResultIsSameDocument) {
    // Step 34.1
    AutoTArray<RefPtr<Promise>, 16> promiseList;
    // Step 34.2
    for (auto& handler : event->NavigationHandlerList().Clone()) {
      // Step 34.2.1
      RefPtr promise = MOZ_KnownLive(handler)->Call();
      if (promise) {
        promiseList.AppendElement(promise);
      }
    }

    // Step 34.3
    if (promiseList.IsEmpty()) {
      RefPtr promise = Promise::CreateResolvedWithUndefined(
          globalObject, IgnoredErrorResult());
      if (promise) {
        promiseList.AppendElement(promise);
      }
    }

    // Step 34.4
    // We capture the scope which we wish to keep alive in the lambdas passed to
    // Promise::WaitForAll. We pass it as the cycle collected argument to
    // Promise::WaitForAll, which makes it stay alive until all promises
    // resolved, or we've become cycle collected. This means that we can pass
    // the scope as a weak reference.
    RefPtr scope =
        MakeRefPtr<NavigationWaitForAllScope>(this, apiMethodTracker, event);
    auto successSteps =
        [weakScope = WeakPtr(scope)](const Span<JS::Heap<JS::Value>>&)
            MOZ_CAN_RUN_SCRIPT_BOUNDARY_LAMBDA {
              // If weakScope is null we've been cycle collected
              if (!weakScope) {
                return;
              }

              RefPtr event = weakScope->mEvent;
              RefPtr self = weakScope->mNavigation;
              RefPtr apiMethodTracker = weakScope->mAPIMethodTracker;
              LogEvent(event, event, "Success"_ns);

              // Success steps
              // Step 1
              if (RefPtr document = event->GetDocument();
                  !document || !document->IsFullyActive()) {
                return;
              }

              // Step 2
              if (AbortSignal* signal = event->Signal(); signal->Aborted()) {
                return;
              }

              // Step 3
              MOZ_DIAGNOSTIC_ASSERT(event == self->mOngoingNavigateEvent);

              // Step 4
              self->mOngoingNavigateEvent = nullptr;

              // Step 5
              event->Finish(true);

              // Step 6
              self->FireEvent(u"navigatesuccess"_ns);

              // Step 7
              if (apiMethodTracker) {
                apiMethodTracker->ResolveFinishedPromise();
              }

              // Step 8
              if (self->mTransition) {
                self->mTransition->Finished()->MaybeResolveWithUndefined();
              }

              // Step 9
              self->mTransition = nullptr;
            };
    auto failureSteps =
        [weakScope = WeakPtr(scope)](JS::Handle<JS::Value> aRejectionReason)
            MOZ_CAN_RUN_SCRIPT_BOUNDARY_LAMBDA {
              // If weakScope is null we've been cycle collected
              if (!weakScope) {
                return;
              }

              RefPtr event = weakScope->mEvent;
              RefPtr self = weakScope->mNavigation;
              RefPtr apiMethodTracker = weakScope->mAPIMethodTracker;

              LogEvent(event, event, "Rejected"_ns);

              // Failure steps
              // Step 1
              if (RefPtr document = event->GetDocument();
                  !document || !document->IsFullyActive()) {
                return;
              }

              // Step 2
              if (AbortSignal* signal = event->Signal(); signal->Aborted()) {
                return;
              }

              // Step 3
              MOZ_DIAGNOSTIC_ASSERT(event == self->mOngoingNavigateEvent);

              // Step 4
              self->mOngoingNavigateEvent = nullptr;

              // Step 5
              event->Finish(false);

              if (AutoJSAPI jsapi;
                  !NS_WARN_IF(!jsapi.Init(event->GetParentObject()))) {
                // Step 6
                RootedDictionary<ErrorEventInit> init(jsapi.cx());
                ExtractErrorInformation(jsapi.cx(), aRejectionReason, init);

                // Step 7
                self->FireErrorEvent(u"navigateerror"_ns, init);
              }

              // Step 8
              if (apiMethodTracker) {
                apiMethodTracker->RejectFinishedPromise(aRejectionReason);
              }

              // Step 9
              if (self->mTransition) {
                self->mTransition->Finished()->MaybeReject(aRejectionReason);
              }

              // Step 10
              self->mTransition = nullptr;
            };

    // If the committed promise in the api method tracker hasn't resolved yet,
    // we can't run neither of the success nor failure steps. To handle that we
    // set up a callback for when that resolves. This differs from how spec
    // performs these steps, since spec can perform more of
    // #apply-the-history-steps in a synchronous way.
    if (apiMethodTracker) {
      LOG_FMT("Waiting for committed");
      apiMethodTracker->CommittedPromise()->AddCallbacksWithCycleCollectedArgs(
          [successSteps, failureSteps](
              JSContext*, JS::Handle<JS::Value>, ErrorResult&,
              nsIGlobalObject* aGlobalObject,
              const Span<RefPtr<Promise>>& aPromiseList,
              const RefPtr<NavigationWaitForAllScope>& aScope)
              MOZ_CAN_RUN_SCRIPT_BOUNDARY_LAMBDA {
                Promise::WaitForAll(aGlobalObject, aPromiseList, successSteps,
                                    failureSteps, aScope);
              },
          [](JSContext*, JS::Handle<JS::Value>, ErrorResult&, nsIGlobalObject*,
             const Span<RefPtr<Promise>>&,
             const RefPtr<NavigationWaitForAllScope>&) {},
          nsCOMPtr(globalObject),
          nsTArray<RefPtr<Promise>>(std::move(promiseList)), scope);
    } else {
      LOG_FMT("No API method tracker, not waiting for committed");
      // If we don't have an apiMethodTracker we can immediately start waiting
      // for the promise list.
      Promise::WaitForAll(globalObject, promiseList, successSteps, failureSteps,
                          scope);
    }
  } else if (apiMethodTracker && mOngoingAPIMethodTracker) {
    // In contrast to spec we add a check that we're still the ongoing tracker.
    // If we're not, then we've already been cleaned up.
    MOZ_DIAGNOSTIC_ASSERT(apiMethodTracker == mOngoingAPIMethodTracker);
    // Step 35
    apiMethodTracker->CleanUp();
  }

  // Step 37 and step 38
  return event->InterceptionState() == NavigateEvent::InterceptionState::None;
}

NavigationHistoryEntry* Navigation::FindNavigationHistoryEntry(
    const SessionHistoryInfo& aSessionHistoryInfo) const {
  for (const auto& navigationHistoryEntry : mEntries) {
    if (navigationHistoryEntry->IsSameEntry(&aSessionHistoryInfo)) {
      return navigationHistoryEntry;
    }
  }

  return nullptr;
}

// https://html.spec.whatwg.org/#promote-an-upcoming-api-method-tracker-to-ongoing
void Navigation::PromoteUpcomingAPIMethodTrackerToOngoing(
    Maybe<nsID>&& aDestinationKey) {
  MOZ_DIAGNOSTIC_ASSERT(!mOngoingAPIMethodTracker);
  if (aDestinationKey) {
    MOZ_DIAGNOSTIC_ASSERT(!mUpcomingNonTraverseAPIMethodTracker);
    Maybe<NavigationAPIMethodTracker&> tracker(NavigationAPIMethodTracker);
    if (auto entry =
            mUpcomingTraverseAPIMethodTrackers.Extract(*aDestinationKey)) {
      mOngoingAPIMethodTracker = std::move(*entry);
    }
    return;
  }

  mOngoingAPIMethodTracker = std::move(mUpcomingNonTraverseAPIMethodTracker);
}

// https://html.spec.whatwg.org/#navigation-api-method-tracker-clean-up
/* static */ void Navigation::CleanUp(
    NavigationAPIMethodTracker* aNavigationAPIMethodTracker) {
  // Step 1
  RefPtr<Navigation> navigation =
      aNavigationAPIMethodTracker->mNavigationObject;

  auto needsTraverse =
      MakeScopeExit([navigation]() { navigation->UpdateNeedsTraverse(); });

  // Step 2
  if (navigation->mOngoingAPIMethodTracker == aNavigationAPIMethodTracker) {
    navigation->mOngoingAPIMethodTracker = nullptr;

    return;
  }

  // Step 3.1
  Maybe<nsID> key = aNavigationAPIMethodTracker->mKey;

  // Step 3.2
  MOZ_DIAGNOSTIC_ASSERT(key);

  // Step 3.3
  MOZ_DIAGNOSTIC_ASSERT(
      navigation->mUpcomingTraverseAPIMethodTrackers.Contains(*key));

  navigation->mUpcomingTraverseAPIMethodTrackers.Remove(*key);
}

// https://html.spec.whatwg.org/#abort-the-ongoing-navigation
void Navigation::AbortOngoingNavigation(JSContext* aCx,
                                        JS::Handle<JS::Value> aError) {
  // Step 1
  RefPtr<NavigateEvent> event = mOngoingNavigateEvent;

  LogEvent(event, event, "Abort"_ns);

  // Step 2
  MOZ_DIAGNOSTIC_ASSERT(event);

  // Step 3
  mFocusChangedDuringOngoingNavigation = false;

  // Step 4
  mSuppressNormalScrollRestorationDuringOngoingNavigation = false;

  JS::Rooted<JS::Value> error(aCx, aError);

  // Step 5
  if (aError.isUndefined()) {
    RefPtr<DOMException> exception =
        DOMException::Create(NS_ERROR_DOM_ABORT_ERR);
    // It's OK if this fails, it just means that we'll get an empty error
    // dictionary below.
    GetOrCreateDOMReflector(aCx, exception, &error);
  }

  // Step 6
  if (event->IsBeingDispatched()) {
    // Here NonSystem is needed since it needs to be the same as what we
    // dispatch with.
    event->PreventDefault(aCx, CallerType::NonSystem);
  }

  // Step 7
  event->AbortController()->Abort(aCx, error);

  // Step 8
  mOngoingNavigateEvent = nullptr;

  // Step 9
  RootedDictionary<ErrorEventInit> init(aCx);
  ExtractErrorInformation(aCx, error, init);

  // Step 10
  FireErrorEvent(u"navigateerror"_ns, init);

  // Step 11
  if (mOngoingAPIMethodTracker) {
    mOngoingAPIMethodTracker->RejectFinishedPromise(error);
  }

  // Step 12
  if (mTransition) {
    // Step 12.1
    mTransition->Finished()->MaybeReject(error);

    // Step 12.2
    mTransition = nullptr;
  }
}

// https://html.spec.whatwg.org/#inform-the-navigation-api-about-child-navigable-destruction
void Navigation::InformAboutChildNavigableDestruction(JSContext* aCx) {
  // Step 3
  auto traversalAPIMethodTrackers = mUpcomingTraverseAPIMethodTrackers.Clone();

  // Step 4
  for (auto& apiMethodTracker : traversalAPIMethodTrackers.Values()) {
    ErrorResult rv;
    rv.ThrowAbortError("Navigable removed");
    JS::Rooted<JS::Value> rootedExceptionValue(aCx);
    MOZ_ALWAYS_TRUE(ToJSValue(aCx, std::move(rv), &rootedExceptionValue));
    apiMethodTracker->RejectFinishedPromise(rootedExceptionValue);
  }
}

bool Navigation::FocusedChangedDuringOngoingNavigation() const {
  return mFocusChangedDuringOngoingNavigation;
}

void Navigation::SetFocusedChangedDuringOngoingNavigation(
    bool aFocusChangedDUringOngoingNavigation) {
  mFocusChangedDuringOngoingNavigation = aFocusChangedDUringOngoingNavigation;
}

bool Navigation::HasOngoingNavigateEvent() const {
  return mOngoingNavigateEvent;
}

// The associated document of navigation's relevant global object.
Document* Navigation::GetAssociatedDocument() const {
  nsGlobalWindowInner* window = GetOwnerWindow();
  return window ? window->GetDocument() : nullptr;
}

void Navigation::UpdateNeedsTraverse() {
  nsGlobalWindowInner* innerWindow = GetOwnerWindow();
  if (!innerWindow) {
    return;
  }

  WindowContext* windowContext = innerWindow->GetWindowContext();
  if (!windowContext) {
    return;
  }

  // Since we only care about optimizing for the traversable, bail if we're not
  // the top-level context.
  if (BrowsingContext* browsingContext = innerWindow->GetBrowsingContext();
      !browsingContext || !browsingContext->IsTop()) {
    return;
  }

  // We need traverse if we have any method tracker.
  bool needsTraverse = mOngoingAPIMethodTracker ||
                       mUpcomingNonTraverseAPIMethodTracker ||
                       !mUpcomingTraverseAPIMethodTrackers.IsEmpty();

  // We need traverse if we have any event handlers.
  if (EventListenerManager* eventListenerManager =
          GetExistingListenerManager()) {
    needsTraverse = needsTraverse || eventListenerManager->HasListeners();
  }

  // Don't toggle if nothing's changed.
  if (windowContext->GetNeedsTraverse() == needsTraverse) {
    return;
  }

  (void)windowContext->SetNeedsTraverse(needsTraverse);
}

void Navigation::LogHistory() const {
  if (!MOZ_LOG_TEST(gNavigationLog, LogLevel::Debug)) {
    return;
  }

  MOZ_LOG(gNavigationLog, LogLevel::Debug,
          ("Navigation %p (current entry index: %d)\n", this,
           mCurrentEntryIndex ? int(*mCurrentEntryIndex) : -1));
  auto length = mEntries.Length();
  for (uint64_t i = 0; i < length; i++) {
    LogEntry(mEntries[i], i, length,
             mCurrentEntryIndex && i == *mCurrentEntryIndex);
  }
}

// https://html.spec.whatwg.org/#maybe-set-the-upcoming-non-traverse-api-method-tracker
RefPtr<NavigationAPIMethodTracker>
Navigation::MaybeSetUpcomingNonTraverseAPIMethodTracker(
    JS::Handle<JS::Value> aInfo,
    nsIStructuredCloneContainer* aSerializedState) {
  // To maybe set the upcoming non-traverse API method tracker given a
  // Navigation navigation, a JavaScript value info, and a serialized
  // state-or-null serializedState:
  // 1. Let committedPromise and finishedPromise be new promises created in
  //    navigation's relevant realm.
  RefPtr committedPromise = Promise::CreateInfallible(GetOwnerGlobal());
  RefPtr finishedPromise = Promise::CreateInfallible(GetOwnerGlobal());
  // 2. Mark as handled finishedPromise.
  MOZ_ALWAYS_TRUE(finishedPromise->SetAnyPromiseIsHandled());

  // 3. Let apiMethodTracker be a new navigation API method tracker with:
  RefPtr<NavigationAPIMethodTracker> apiMethodTracker =
      MakeAndAddRef<NavigationAPIMethodTracker>(
          this, /* aKey */ Nothing{}, aInfo, aSerializedState,
          /* aCommittedToEntry */ nullptr, committedPromise, finishedPromise);

  // 4. Assert: navigation's upcoming non-traverse API method tracker is null.
  MOZ_DIAGNOSTIC_ASSERT(!mUpcomingNonTraverseAPIMethodTracker);

  // 5. If navigation does not have entries and events disabled, then set
  //    navigation's upcoming non-traverse API method tracker to
  //    apiMethodTracker.
  if (!HasEntriesAndEventsDisabled()) {
    mUpcomingNonTraverseAPIMethodTracker = apiMethodTracker;
  }

  UpdateNeedsTraverse();

  // 6. Return apiMethodTracker.
  return apiMethodTracker;
}

// https://html.spec.whatwg.org/#add-an-upcoming-traverse-api-method-tracker
RefPtr<NavigationAPIMethodTracker>
Navigation::AddUpcomingTraverseAPIMethodTracker(const nsID& aKey,
                                                JS::Handle<JS::Value> aInfo) {
  // To add an upcoming traverse API method tracker given a Navigation
  // navigation, a string destinationKey, and a JavaScript value info:
  // 1. Let committedPromise and finishedPromise be new promises created in
  //    navigation's relevant realm.
  RefPtr committedPromise = Promise::CreateInfallible(GetOwnerGlobal());
  RefPtr finishedPromise = Promise::CreateInfallible(GetOwnerGlobal());

  // 2. Mark as handled finishedPromise.
  MOZ_ALWAYS_TRUE(finishedPromise->SetAnyPromiseIsHandled());

  // 3. Let apiMethodTracker be a new navigation API method tracker with:
  RefPtr<NavigationAPIMethodTracker> apiMethodTracker =
      MakeAndAddRef<NavigationAPIMethodTracker>(
          this, Some(aKey), aInfo,
          /* aSerializedState */ nullptr,
          /* aCommittedToEntry */ nullptr, committedPromise, finishedPromise);

  // 4. Set navigation's upcoming traverse API method trackers[destinationKey]
  //    to apiMethodTracker.
  RefPtr methodTracker =
      mUpcomingTraverseAPIMethodTrackers.InsertOrUpdate(aKey, apiMethodTracker);

  UpdateNeedsTraverse();

  // 5. Return apiMethodTracker.
  return methodTracker;
}

// https://html.spec.whatwg.org/#update-document-for-history-step-application
void Navigation::CreateNavigationActivationFrom(
    SessionHistoryInfo* aPreviousEntryForActivation,
    NavigationType aNavigationType) {
  // Note: we do Step 7.1 at the end of method so we can both create and
  // initialize the activation at once.
  MOZ_LOG_FMT(gNavigationLog, LogLevel::Debug,
              "Creating NavigationActivation for from={}, type={}",
              fmt::ptr(aPreviousEntryForActivation), aNavigationType);
  RefPtr currentEntry = GetCurrentEntry();
  if (!currentEntry) {
    return;
  }

  // Step 7.2. Let previousEntryIndex be the result of getting the navigation
  // API entry index of previousEntryForActivation within navigation.
  auto possiblePreviousEntry =
      std::find_if(mEntries.begin(), mEntries.end(),
                   [aPreviousEntryForActivation](const auto& entry) {
                     return entry->IsSameEntry(aPreviousEntryForActivation);
                   });

  // 3. If previousEntryIndex is non-negative, then set activation's old entry
  // to navigation's entry list[previousEntryIndex].
  RefPtr<NavigationHistoryEntry> oldEntry;
  if (possiblePreviousEntry != mEntries.end()) {
    MOZ_LOG_FMT(gNavigationLog, LogLevel::Debug, "Found previous entry at {}",
                fmt::ptr(possiblePreviousEntry->get()));
    oldEntry = *possiblePreviousEntry;
  } else if (aNavigationType == NavigationType::Replace &&
             !aPreviousEntryForActivation->IsTransient()) {
    // 4. Otherwise, if all the following are true:
    //     navigationType is "replace";
    //     previousEntryForActivation's document state's origin is same origin
    //     with document's origin; and previousEntryForActivation's document's
    //     initial about:blank is false,
    // then set activation's old entry to a new NavigationHistoryEntry in
    // navigation's relevant realm, whose session history entry is
    // previousEntryForActivation.

    nsIURI* previousURI = aPreviousEntryForActivation->GetURI();
    nsIURI* currentURI = currentEntry->SessionHistoryInfo()->GetURI();
    if (NS_SUCCEEDED(nsContentUtils::GetSecurityManager()->CheckSameOriginURI(
            currentURI, previousURI, false, false))) {
      oldEntry = MakeRefPtr<NavigationHistoryEntry>(
          GetOwnerGlobal(), aPreviousEntryForActivation, -1);
      MOZ_LOG_FMT(gNavigationLog, LogLevel::Debug, "Created a new entry at {}",
                  fmt::ptr(oldEntry.get()));
    }
  }

  // 1. If navigation's activation is null, then set navigation's
  // activation to a new NavigationActivation object in navigation's relevant
  // realm.
  // 5. Set activation's new entry to navigation's current entry.
  // 6. Set activation's navigation type to navigationType.
  mActivation = MakeRefPtr<NavigationActivation>(GetOwnerGlobal(), currentEntry,
                                                 oldEntry, aNavigationType);
}

}  // namespace mozilla::dom