webdriverbidi 0.2.2

WebDriver BiDi client implementation in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use log::debug;
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::Value;
use tokio::net::TcpStream;
use tokio::sync::{Mutex, oneshot};
use tokio::task;
use tokio_tungstenite::{MaybeTlsStream, WebSocketStream, connect_async};

use crate::command_sender;
use crate::commands;
use crate::error::{CommandError, SessionError};
use crate::events::EventType;
use crate::message_handler;
use crate::model::browser::ClientWindowInfo;
use crate::model::browser::*;
use crate::model::browsing_context::*;
use crate::model::common::EmptyParams;
use crate::model::emulation::*;
use crate::model::input::*;
use crate::model::network::*;
use crate::model::result::EmptyResult;
use crate::model::script::EvaluateResult;
use crate::model::script::*;
use crate::model::session::*;
use crate::model::storage::*;
use crate::model::web_extension::*;
use crate::webdriver::capabilities::CapabilitiesRequest;
use crate::webdriver::session;

/// Type alias for the event handler functions.
pub type EventHandler =
    Box<dyn Fn(Value) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync>;

/// Represents a WebDriver BiDi session.
///
/// This struct manages the lifecycle of a WebDriver session, including
/// starting the session, establishing a WebSocket connection, sending
/// commands, handling incoming messages whether they are command responses
/// or events and eventually closing the session.
///
/// # Fields
///
/// * `host` - The host address of the WebDriver server.
/// * `port` - The port number of the WebDriver server.
/// * `base_url` - The base URL constructed from the host and port.
/// * `session_id` - The unique identifier for the session.
/// * `capabilities` - The desired capabilities for the session.
/// * `websocket_url` - The WebSocket URL for bidirectional communication.
/// * `websocket_stream` - The WebSocket stream for communication protected by an `Arc` wrapped `Mutex`.
/// * `pending_commands` - A map of pending commands awaiting responses protected by an `Arc` wrapped `Mutex`.
/// * `event_handlers` - A map of events and their handlers protected by an `Arc` wrapped `Mutex`.
#[derive(Clone)]
pub struct WebDriverBiDiSession {
    pub host: String,
    pub port: u16,
    pub base_url: String,
    pub session_id: String,
    pub capabilities: CapabilitiesRequest,
    pub websocket_url: String,
    pub websocket_stream: Option<Arc<Mutex<WebSocketStream<MaybeTlsStream<TcpStream>>>>>,
    pub pending_commands: Arc<Mutex<HashMap<u64, oneshot::Sender<Value>>>>,
    event_handlers: Arc<Mutex<HashMap<EventType, EventHandler>>>,
}

impl WebDriverBiDiSession {
    /// Creates a new session.
    ///
    /// # Arguments
    ///
    /// * `host` - The host address of the WebDriver server.
    /// * `port` - The port number of the WebDriver server.
    /// * `capabilities` - The desired capabilities for the session.
    pub fn new(host: String, port: u16, capabilities: CapabilitiesRequest) -> Self {
        let base_url = format!("http://{}:{}", host, port);
        debug!("Constructed base URL: {}", base_url);
        Self {
            host,
            port,
            base_url,
            session_id: String::new(),
            capabilities,
            websocket_url: String::new(),
            websocket_stream: None,
            pending_commands: Arc::new(Mutex::new(HashMap::new())),
            event_handlers: Arc::new(Mutex::new(HashMap::new())),
        }
    }

    /// Start a WebDriver session, establishe a WebSocket connection and
    /// spawn a background task to handle incoming messages.
    ///
    /// **A WebDriver BiDi server must be running before calling this method.**
    pub async fn start(&mut self) -> Result<(), SessionError> {
        let session = session::start_session(&self.base_url, &self.capabilities)
            .await
            .map_err(|e| SessionError::Other(format!("Failed to start session: {}", e)))?;
        self.session_id = session.session_id;
        self.websocket_url = session.websocket_url;

        debug!("Establishing the WebSocket connection");
        let (stream, _) = connect_async(&self.websocket_url)
            .await
            .map_err(|e| SessionError::Other(format!("Failed to connect to WebSocket: {}", e)))?;

        let websocket_stream = Arc::new(Mutex::new(stream));
        self.websocket_stream = Some(websocket_stream.clone());

        let pending_commands = self.pending_commands.clone();
        let event_handlers = self.event_handlers.clone();

        debug!("Starting the incoming messages management loop");
        // Spawn a background task to manage incoming messages
        self.spawn_message_handler_task(websocket_stream, pending_commands, event_handlers);

        Ok(())
    }

    /// Close the WebDriver session.
    pub async fn close(&mut self) -> Result<(), SessionError> {
        session::close_session(&self.base_url, &self.session_id).await?;
        Ok(())
    }

    /// Send a WebDriver BiDi command.
    ///
    /// # Arguments
    ///
    /// * `command` - The command to send.
    ///
    /// # Returns
    ///
    /// A result containing the response of type `U` that implements the `DeserializeOwned` trait,
    /// or a `CommandError` if the command could not be sent.
    pub async fn send_command<T: Serialize, U: DeserializeOwned>(
        &mut self,
        command: T,
    ) -> Result<U, CommandError> {
        if let Some(websocket_stream) = &self.websocket_stream {
            command_sender::send_command(
                websocket_stream.clone(),
                self.pending_commands.clone(),
                command,
            )
            .await
        } else {
            let error_msg = "WebSocket stream not initialized.";
            Err(CommandError::Other(error_msg.into()))
        }
    }

    /// Spawn a background task to manage incoming WebSocket messages.
    ///
    /// This method creates a new asynchronous task that continuously listens for
    /// incoming messages on the WebSocket connection and handles them appropriately.
    fn spawn_message_handler_task(
        &self,
        websocket_stream: Arc<Mutex<WebSocketStream<MaybeTlsStream<TcpStream>>>>,
        pending_commands: Arc<Mutex<HashMap<u64, oneshot::Sender<Value>>>>,
        event_handlers: Arc<Mutex<HashMap<EventType, EventHandler>>>,
    ) {
        task::spawn(message_handler::handle_messages(
            websocket_stream,
            pending_commands,
            event_handlers,
        ));
    }

    /// Register an event handler for a specific event type.
    ///
    /// # Arguments
    ///
    /// * `event_type` - The type of the event to handle.
    /// * `handler` - The event handler function.
    pub async fn register_event_handler<F, Fut>(&mut self, event_type: EventType, handler: F)
    where
        F: Fn(Value) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        debug!("Registring event handler for event: {:?}", event_type);
        let mut handlers = self.event_handlers.lock().await;
        handlers.insert(event_type, Box::new(move |event| Box::pin(handler(event))));
    }

    /// Unregister an event handler for a specific event type.
    ///
    /// # Arguments
    ///
    /// * `event_type` - The type of the event to stop handling.
    pub async fn unregister_event_handler(&mut self, event_type: EventType) {
        let mut handlers = self.event_handlers.lock().await;
        handlers.remove(&event_type);
    }
}

// Browsing context commands
impl WebDriverBiDiSession {
    // https://w3c.github.io/webdriver-bidi/#command-browsingContext-activate

    /// Activate and focus a browsing context.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as an `ActivateParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `EmptyResult` or a `CommandError`.
    pub async fn browsing_context_activate(
        &mut self,
        params: ActivateParameters,
    ) -> Result<EmptyResult, CommandError> {
        commands::browsing_context::activate(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-browsingContext-captureScreenshot

    /// Capture an image of the given navigable and return it as a Base64-encoded string.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as a `CaptureScreenshotParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `CaptureScreenshotResult` or a `CommandError`.
    pub async fn browsing_context_capture_screenshot(
        &mut self,
        params: CaptureScreenshotParameters,
    ) -> Result<CaptureScreenshotResult, CommandError> {
        commands::browsing_context::capture_screenshot(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-browsingContext-close

    /// Close the browsing context.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as a `CloseParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `EmptyResult` or a `CommandError`.
    pub async fn browsing_context_close(
        &mut self,
        params: CloseParameters,
    ) -> Result<EmptyResult, CommandError> {
        commands::browsing_context::close(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-browsingContext-create

    /// Create a new browsing context.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as a `CreateParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `CreateResult` or a `CommandError`.
    pub async fn browsing_context_create(
        &mut self,
        params: CreateParameters,
    ) -> Result<CreateResult, CommandError> {
        commands::browsing_context::create(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-browsingContext-getTree

    /// Retrieve the browsing context tree.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as a GetTreeParameters instance.
    ///
    /// # Returns
    ///
    /// A result containing the `GetTreeResult` or a `CommandError`.
    pub async fn browsing_context_get_tree(
        &mut self,
        params: GetTreeParameters,
    ) -> Result<GetTreeResult, CommandError> {
        commands::browsing_context::get_tree(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-browsingContext-handleUserPrompt

    /// Allow closing an open prompt.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as a `HandleUserPromptParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `EmptyResult` or a `CommandError`.
    pub async fn browsing_context_handle_user_prompt(
        &mut self,
        params: HandleUserPromptParameters,
    ) -> Result<EmptyResult, CommandError> {
        commands::browsing_context::handle_user_prompt(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-browsingContext-locateNodes

    /// Return a list of all nodes matching the specified locator.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as a `LocateNodesParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `LocateNodesResult` or a `CommandError`.
    pub async fn browsing_context_locate_nodes(
        &mut self,
        params: LocateNodesParameters,
    ) -> Result<LocateNodesResult, CommandError> {
        commands::browsing_context::locate_nodes(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-browsingContext-navigate

    /// Navigate to a URL in the browsing context.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as a NavigateParameters instance.
    ///
    /// # Returns
    ///
    /// A result containing the `NavigateResult` or a `CommandError`.
    pub async fn browsing_context_navigate(
        &mut self,
        params: NavigateParameters,
    ) -> Result<NavigateResult, CommandError> {
        commands::browsing_context::navigate(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-browsingContext-print

    /// Create a paginated representation of a document and return it
    /// as a Base64-encoded string PDF.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as a `PrintParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `PrintResult` or a `CommandError`.
    pub async fn browsing_context_print(
        &mut self,
        params: PrintParameters,
    ) -> Result<PrintResult, CommandError> {
        commands::browsing_context::print(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-browsingContext-reload

    /// Reload the current page in the browsing context.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as a `ReloadParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `NavigateResult` or a `CommandError`.
    pub async fn browsing_context_reload(
        &mut self,
        params: ReloadParameters,
    ) -> Result<NavigateResult, CommandError> {
        commands::browsing_context::reload(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-browsingContext-setViewport

    /// Modify specific viewport characteristics (e.g. viewport width and viewport
    /// height) on the given top-level traversable.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as a `SetViewportParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `EmptyResult` or a `CommandError`.
    pub async fn browsing_context_set_viewport(
        &mut self,
        params: SetViewportParameters,
    ) -> Result<EmptyResult, CommandError> {
        commands::browsing_context::set_viewport(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-browsingContext-traverseHistory

    /// Navigate through the browsing history of a specified context.
    ///
    /// This method allows you to move forward or backward in the browsing history
    /// of a given navigable context by a specified number of steps (delta).
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as a `TraverseHistoryParameters` instance, which
    ///   includes the context identifier and the delta indicating the number of steps
    ///   to move in the history. A positive delta moves forward, while a negative delta
    ///   moves backward.
    ///
    /// # Returns
    ///
    /// A result containing the `TraverseHistoryResult` or a `CommandError` if the
    /// operation fails.
    pub async fn browsing_context_traverse_history(
        &mut self,
        params: TraverseHistoryParameters,
    ) -> Result<TraverseHistoryResult, CommandError> {
        commands::browsing_context::traverse_history(self, params).await
    }
}

// Session commands
impl WebDriverBiDiSession {
    // https://w3c.github.io/webdriver-bidi/#command-session-status

    /// Return information about whether a remote end is in a state
    /// in which it can create new sessions, but may additionally include
    /// arbitrary meta information that is specific to the implementation.
    ///
    /// # Returns
    ///
    /// A result containing the `SessionStatus` or a `CommandError`.
    pub async fn session_status(
        &mut self,
        params: EmptyParams,
    ) -> Result<StatusResult, CommandError> {
        commands::session::status(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-session-new

    /// Create a new session.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as a `NewParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `NewResult` or a `CommandError`.
    pub async fn session_new(&mut self, params: NewParameters) -> Result<NewResult, CommandError> {
        commands::session::new(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-session-end

    /// End the current session.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as an `EmptyParams` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `EmptyResult` or a `CommandError`.
    pub async fn session_end(&mut self, params: EmptyParams) -> Result<EmptyResult, CommandError> {
        commands::session::end(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-session-subscribe

    /// Enable certain events either globally or for a set of navigables.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as a `SubscriptionRequest` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `SubscriptionRequestResult` or a `CommandError`.
    pub async fn session_subscribe(
        &mut self,
        params: SubscriptionRequest,
    ) -> Result<SubscribeResult, CommandError> {
        commands::session::subscribe(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-session-unsubscribe

    /// Disable certain events either globally or for a set of navigables.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as an `UnsubscribeRequest` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `EmptyResult` or a `CommandError`.
    pub async fn session_unsubscribe(
        &mut self,
        params: UnsubscribeParameters,
    ) -> Result<EmptyResult, CommandError> {
        commands::session::unsubscribe(self, params).await
    }
}

// Browser commands
impl WebDriverBiDiSession {
    // https://w3c.github.io/webdriver-bidi/#command-browser-close

    /// Terminate all WebDriver sessions and clean up automation state
    /// in the remote browser instance.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as an `EmptyParams` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `EmptyResult` or a `CommandError`.
    pub async fn browser_close(
        &mut self,
        params: EmptyParams,
    ) -> Result<EmptyResult, CommandError> {
        commands::browser::close(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-browser-createUserContext

    /// Create a new user context.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as an `EmptyParams` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `CreateUserContextResult` or a `CommandError`.
    pub async fn browser_create_user_context(
        &mut self,
        params: CreateUserContextParameters,
    ) -> Result<CreateUserContextResult, CommandError> {
        commands::browser::create_user_context(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-browser-getClientWindows

    /// Retrieve the list of client windows.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as an `EmptyParams` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `GetClientWindowsResult` or a `CommandError`.
    pub async fn browser_get_client_windows(
        &mut self,
        params: EmptyParams,
    ) -> Result<GetClientWindowsResult, CommandError> {
        commands::browser::get_client_windows(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-browser-getUserContexts

    /// Retrieve the list of user contexts.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as an `EmptyParams` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `GetUserContextsResult` or a `CommandError`.
    pub async fn browser_get_user_contexts(
        &mut self,
        params: EmptyParams,
    ) -> Result<GetUserContextsResult, CommandError> {
        commands::browser::get_user_contexts(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-browser-removeUserContext

    /// Close a user context and all navigables in it.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as an `RemoveUserContextParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `EmptyResult` or a `CommandError`.
    pub async fn browser_remove_user_context(
        &mut self,
        params: RemoveUserContextParameters,
    ) -> Result<EmptyResult, CommandError> {
        commands::browser::remove_user_context(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-browser-setClientWindowState

    /// Set the dimensions of a client window.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as an `SetClientWindowStateParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `ClientWindowInfo` or a `CommandError`.
    pub async fn browser_set_client_window_state(
        &mut self,
        params: SetClientWindowStateParameters,
    ) -> Result<ClientWindowInfo, CommandError> {
        commands::browser::set_client_window_state(self, params).await
    }
}

// Emulation commands
impl WebDriverBiDiSession {
    // https://w3c.github.io/webdriver-bidi/#command-emulation-setGeolocationOverride

    /// Modify geolocation characteristics on the given top-level traversables or user contexts.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as a `SetGeolocationOverrideParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `EmptyResult` or a `CommandError`.
    pub async fn set_geolocation_override(
        &mut self,
        params: SetGeolocationOverrideParameters,
    ) -> Result<EmptyResult, CommandError> {
        commands::emulation::set_geolocation_override(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-emulation-setLocaleOverride

    /// Modifies locale on the given top-level traversables or user contexts.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as a `SetLocaleOverrideParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `EmptyResult` or a `CommandError`.
    pub async fn set_locale_override(
        &mut self,
        params: SetLocaleOverrideParameters,
    ) -> Result<EmptyResult, CommandError> {
        commands::emulation::set_locale_override(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-emulation-setScreenOrientationOverride

    /// Emulates screen orientation of the given top-level traversables or user contexts.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as a `SetScreenOrientationOverrideParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `EmptyResult` or a `CommandError`.
    pub async fn set_screen_orientation_override(
        &mut self,
        params: SetScreenOrientationOverrideParameters,
    ) -> Result<EmptyResult, CommandError> {
        commands::emulation::set_screen_orientation_override(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-emulation-setTimezoneOverride

    /// Modifies timezone on the given top-level traversables or user contexts.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as a `SetTimezoneOverrideParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `EmptyResult` or a `CommandError`.
    pub async fn set_timezone_override(
        &mut self,
        params: SetTimezoneOverrideParameters,
    ) -> Result<EmptyResult, CommandError> {
        commands::emulation::set_timezone_override(self, params).await
    }
}

// Network commands
impl WebDriverBiDiSession {
    // https://w3c.github.io/webdriver-bidi/#command-network-addDataCollector

    /// Add a data collector.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as an `AddDataCollectorParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `AddDataCollectorResult` or a `CommandError`.
    pub async fn network_add_data_collector(
        &mut self,
        params: AddDataCollectorParameters,
    ) -> Result<AddDataCollectorResult, CommandError> {
        commands::network::add_data_collector(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-network-addIntercept

    /// Add a network intercept.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as an `AddInterceptParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `AddInterceptResult` or a `CommandError`.
    pub async fn network_add_intercept(
        &mut self,
        params: AddInterceptParameters,
    ) -> Result<AddInterceptResult, CommandError> {
        commands::network::add_intercept(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-network-continueRequest

    /// Continue a request that’s blocked by a network intercept.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as an `ContinueRequestParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `EmptyResult` or a `CommandError`.
    pub async fn network_continue_request(
        &mut self,
        params: ContinueRequestParameters,
    ) -> Result<EmptyResult, CommandError> {
        commands::network::continue_request(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-network-continueResponse

    /// Continue a response that’s blocked by a network intercept.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as an `ContinueResponseParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `EmptyResult` or a `CommandError`.
    pub async fn network_continue_response(
        &mut self,
        params: ContinueResponseParameters,
    ) -> Result<EmptyResult, CommandError> {
        commands::network::continue_response(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-network-continueWithAuth

    /// Continue a request that’s blocked by a network intercept at the authRequired phase.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as an `ContinueWithAuthParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `EmptyResult` or a `CommandError`.
    pub async fn network_continue_with_auth(
        &mut self,
        params: ContinueWithAuthParameters,
    ) -> Result<EmptyResult, CommandError> {
        commands::network::continue_with_auth(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-network-disownData

    /// Release a collected network data for a given collector.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as a `DisownDataParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `EmptyResult` or a `CommandError`.
    pub async fn network_disown_data(
        &mut self,
        params: DisownDataParameters,
    ) -> Result<EmptyResult, CommandError> {
        commands::network::disown_data(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-network-failRequest

    /// Fail a fetch that’s blocked by a network intercept.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as an `FailRequestParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `EmptyResult` or a `CommandError`.
    pub async fn network_fail_request(
        &mut self,
        params: FailRequestParameters,
    ) -> Result<EmptyResult, CommandError> {
        commands::network::fail_request(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-network-getData

    /// Retrieve a network data if it is available.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as a `GetDataParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `GetDataResult` or a `CommandError`.
    pub async fn network_get_data(
        &mut self,
        params: GetDataParameters,
    ) -> Result<GetDataResult, CommandError> {
        commands::network::get_data(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-network-provideResponse

    /// Continue a request that’s blocked by a network intercept, by providing a complete response.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as an `ProvideResponseParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `EmptyResult` or a `CommandError`.
    pub async fn network_provide_response(
        &mut self,
        params: ProvideResponseParameters,
    ) -> Result<EmptyResult, CommandError> {
        commands::network::provide_response(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-network-removeDataCollector

    /// Remove a data collector.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as an `RemoveDataCollectorParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `EmptyResult` or a `CommandError`.
    pub async fn network_remove_data_collector(
        &mut self,
        params: RemoveDataCollectorParameters,
    ) -> Result<EmptyResult, CommandError> {
        commands::network::remove_data_collector(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-network-removeIntercept

    /// Remove a network intercept.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as an `RemoveInterceptParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `EmptyResult` or a `CommandError`.
    pub async fn network_remove_intercept(
        &mut self,
        params: RemoveInterceptParameters,
    ) -> Result<EmptyResult, CommandError> {
        commands::network::remove_intercept(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-network-setCacheBehavior

    /// Configure the network cache behavior for certain requests.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as an `SetCacheBehaviorParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `EmptyResult` or a `CommandError`.
    pub async fn network_set_cache_behavior(
        &mut self,
        params: SetCacheBehaviorParameters,
    ) -> Result<EmptyResult, CommandError> {
        commands::network::set_cache_behavior(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-network-setExtraHeaders

    /// Allow specifying headers that will extend, or overwrite, existing request headers.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as a `SetExtraHeadersParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `EmptyResult` or a `CommandError`.
    pub async fn network_set_extra_headers(
        &mut self,
        params: SetExtraHeadersParameters,
    ) -> Result<EmptyResult, CommandError> {
        commands::network::set_extra_headers(self, params).await
    }
}

// Script commands
impl WebDriverBiDiSession {
    // https://w3c.github.io/webdriver-bidi/#command-script-addPreloadScript

    /// Add a script to be preloaded into the browsing context.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as an `AddPreloadScriptParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `AddPreloadScriptResult` or a `CommandError`.
    pub async fn script_add_preload_script(
        &mut self,
        params: AddPreloadScriptParameters,
    ) -> Result<AddPreloadScriptResult, CommandError> {
        commands::script::add_preload_script(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-script-disown

    /// Disown the given handles.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as a `DisownParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `EmptyResult` or a `CommandError`.
    pub async fn script_disown(
        &mut self,
        params: DisownParameters,
    ) -> Result<EmptyResult, CommandError> {
        commands::script::disown(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-script-callFunction

    /// Call a provided function with given arguments in a given realm.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as a `CallFunctionParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `EvaluateResult` or a `CommandError`.
    pub async fn script_call_function(
        &mut self,
        params: CallFunctionParameters,
    ) -> Result<EvaluateResult, CommandError> {
        commands::script::call_function(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-script-evaluate

    /// Evaluate the given script in the given realm.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as an `EvaluateParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `EvaluateResult` or a `CommandError`.
    pub async fn script_evaluate(
        &mut self,
        params: EvaluateParameters,
    ) -> Result<EvaluateResult, CommandError> {
        commands::script::evaluate(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-script-getRealms

    /// Return a list of all realms, optionally filtered to realms of a
    /// specific type, or to the realm associated with a navigable's active document.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as a `GetRealmsParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `GetRealmsResult` or a `CommandError`.
    pub async fn script_get_realms(
        &mut self,
        params: GetRealmsParameters,
    ) -> Result<GetRealmsResult, CommandError> {
        commands::script::get_realms(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-script-removePreloadScript

    /// Remove a preload script.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as a `RemovePreloadScriptParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `EmptyResult` or a `CommandError`.
    pub async fn script_remove_preload_script(
        &mut self,
        params: RemovePreloadScriptParameters,
    ) -> Result<EmptyResult, CommandError> {
        commands::script::remove_preload_script(self, params).await
    }
}

// Storage commands
impl WebDriverBiDiSession {
    // https://w3c.github.io/webdriver-bidi/#command-storage-getCookies

    /// Retrieve zero or more cookies which match a set of provided parameters.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as a `GetCookiesParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `GetCookiesResult` or a `CommandError`.
    pub async fn storage_get_cookies(
        &mut self,
        params: GetCookiesParameters,
    ) -> Result<GetCookiesResult, CommandError> {
        commands::storage::get_cookies(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-storage-setCookie

    /// Create a new cookie in a cookie store.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as a `SetCookieParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `SetCookieResult` or a `CommandError`.
    pub async fn storage_set_cookie(
        &mut self,
        params: SetCookieParameters,
    ) -> Result<SetCookieResult, CommandError> {
        commands::storage::set_cookie(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-storage-deleteCookies

    /// Remove zero or more cookies which match a set of provided parameters.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as a `DeleteCookiesParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `DeleteCookiesResult` or a `CommandError`.
    pub async fn storage_delete_cookies(
        &mut self,
        params: DeleteCookiesParameters,
    ) -> Result<DeleteCookiesResult, CommandError> {
        commands::storage::delete_cookies(self, params).await
    }
}

// Input commands
impl WebDriverBiDiSession {
    // https://w3c.github.io/webdriver-bidi/#command-input-performActions

    /// Perform a specified sequence of user input actions.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as a `PerformActionsParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `EmptyResult` or a `CommandError`.
    pub async fn input_perform_actions(
        &mut self,
        params: PerformActionsParameters,
    ) -> Result<EmptyResult, CommandError> {
        commands::input::perform_actions(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-input-releaseActions

    /// Reset the input state associated with the current session.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as a `ReleaseActionsParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `EmptyResult` or a `CommandError`.
    pub async fn input_release_actions(
        &mut self,
        params: ReleaseActionsParameters,
    ) -> Result<EmptyResult, CommandError> {
        commands::input::release_actions(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-input-setFiles

    /// Set the files property of a given input element with type file
    /// to a set of file paths.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as a `SetFilesParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `EmptyResult` or a `CommandError`.
    pub async fn input_set_files(
        &mut self,
        params: SetFilesParameters,
    ) -> Result<EmptyResult, CommandError> {
        commands::input::set_files(self, params).await
    }
}

// Web extension commands
impl WebDriverBiDiSession {
    // https://w3c.github.io/webdriver-bidi/#command-webExtension-install

    /// Install a web extension.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as an `InstallParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `InstallResult` or a `CommandError`.
    pub async fn web_extension_install(
        &mut self,
        params: InstallParameters,
    ) -> Result<InstallResult, CommandError> {
        commands::web_extension::install(self, params).await
    }

    // https://w3c.github.io/webdriver-bidi/#command-webExtension-uninstall

    /// Uninstall a web extension.
    ///
    /// # Arguments
    ///
    /// * `params` - The parameters as an `UninstallParameters` instance.
    ///
    /// # Returns
    ///
    /// A result containing the `EmptyResult` or a `CommandError`.
    pub async fn web_extension_uninstall(
        &mut self,
        params: UninstallParameters,
    ) -> Result<EmptyResult, CommandError> {
        commands::web_extension::uninstall(self, params).await
    }
}