sylphx 0.3.6

The Sylphx SDK: one API, one key, every Sylphx service. Generated from the Sylphx schema registry.
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
// @generated by sylphx-gen. Do not edit.
//! The Sylphx Sandboxes mock display-stream protocol, version 1: signalling
//! and four data channels (`control`, `input`, `pointer`, `clipboard`).
//! Every test frame is one JSON object tagged by `t`; behavior is documented
//! in `docs/services/sandboxes/stream.md`. This is not production media wire;
//! ADR-5094's management-rooted protobuf graph owns that API.
//! `contracts/fixtures/sandboxes-stream.json` holds the golden frames both
//! SDKs replay.
//!
//! ```
//! use sylphx::sandboxes::stream::{Input, parse_input};
//! let frame = parse_input(r#"{"t":"tx","text":"你好"}"#).unwrap();
//! assert_eq!(frame, Input::Tx { text: "你好".into() });
//! ```
//!
//! Receivers ignore unknown fields; an unknown `t`, a missing field, or a
//! value outside its set fails to parse (answer `invalid_message`).

use base64::engine::general_purpose::STANDARD;
use base64::Engine as _;
use serde::{Deserialize, Serialize};

/// The protocol version this module speaks (`hello.v`).
pub const VERSION: u32 = 1;
/// The WebSocket subprotocol prefix that carries the stream token.
pub const TOKEN_PROTOCOL: &str = "sbx.v1.";
/// The data channel labels, in the order the machine opens them.
pub const CHANNELS: [&str; 4] = ["control", "input", "pointer", "clipboard"];
/// The largest clipboard text item, in UTF-8 bytes.
pub const MAX_CLIP_TEXT_BYTES: usize = 1 << 20;
/// The largest clipboard PNG item, in decoded bytes.
pub const MAX_CLIP_IMAGE_BYTES: usize = 8 << 20;
/// A `clip` whose JSON is longer than this travels as `clip_chunk` frames.
pub const MAX_FRAME_BYTES: usize = 16 << 10;
/// The largest slice of a `clip` one `clip_chunk` carries, before base64
/// (16,000 base64 characters, so a chunk frame stays under 16 KiB).
pub const CHUNK_SLICE_BYTES: usize = 12_000;
/// The most chunks one `clip` may be cut into.
pub const MAX_CHUNKS: u32 = 2048;

// ---- signalling -----------------------------------------------------------

/// A frame the client sends on the signalling WebSocket.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "t", rename_all = "snake_case")]
pub enum SignalClient {
    /// Sent once, first.
    Hello(Hello),
    /// The client's answer to an `offer`.
    Answer { sdp: String },
    /// One ICE candidate.
    Ice { candidate: IceCandidate },
    /// After a network change: the server re-offers with an ICE restart.
    Restart,
}

/// A frame the server sends on the signalling WebSocket.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "t", rename_all = "snake_case")]
pub enum SignalServer {
    /// One video track per selected monitor (`a=mid:` is the monitor id) and
    /// the data channels.
    Offer { sdp: String },
    /// One ICE candidate.
    Ice { candidate: IceCandidate },
    /// The session ends; the server closes the socket.
    Bye { reason: ByeReason },
    /// A refused frame.
    Error(ErrorFrame),
}

/// `hello`: the protocol version, the client's screen, and the monitors to
/// stream.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Hello {
    pub v: u32,
    pub client: ClientInfo,
    #[serde(default)]
    pub monitors: MonitorSelection,
}

/// The client's screen.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ClientInfo {
    /// Device pixel ratio.
    pub dpr: f64,
    /// Viewport width in CSS pixels.
    pub w: u32,
    /// Viewport height in CSS pixels.
    pub h: u32,
    /// Whether the client's primary input is touch.
    pub touch: bool,
}

/// `"all"` or a list of monitor ids.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum MonitorSelection {
    All(AllMonitors),
    Ids(Vec<String>),
}

impl Default for MonitorSelection {
    fn default() -> Self {
        MonitorSelection::All(AllMonitors::All)
    }
}

/// The literal `"all"`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AllMonitors {
    All,
}

/// `RTCIceCandidateInit`, as `RTCIceCandidate.toJSON()` gives it. An empty
/// `candidate` ends the candidates.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IceCandidate {
    pub candidate: String,
    #[serde(rename = "sdpMid", default, skip_serializing_if = "Option::is_none")]
    pub sdp_mid: Option<String>,
    #[serde(
        rename = "sdpMLineIndex",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub sdp_m_line_index: Option<u16>,
    #[serde(
        rename = "usernameFragment",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub username_fragment: Option<String>,
}

/// Why the server ended the session.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ByeReason {
    /// The lease restarted or resumed.
    GenerationChanged,
    /// The token was revoked.
    Revoked,
    /// The lease ended.
    LeaseGone,
}

/// `{"t":"error","code":…,"message":…}` on signalling, `control` or
/// `clipboard`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ErrorFrame {
    pub code: ErrorCode,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
}

impl ErrorFrame {
    pub fn new(code: ErrorCode) -> Self {
        ErrorFrame {
            code,
            message: None,
        }
    }
}

/// The error codes of the protocol (`docs/services/sandboxes/stream.md#errors`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ErrorCode {
    /// Not JSON, an unknown `t`, a missing or wrong-typed field, or a value
    /// outside its set.
    InvalidMessage,
    /// `hello.v` is not one the machine speaks; the socket closes.
    UnsupportedVersion,
    /// A second `hello`, or `answer`/`restart` before an `offer`.
    OutOfOrder,
    /// `upgrade` with a token that is not a valid, unrevoked CONTROLLER
    /// token for this lease.
    Unauthenticated,
    /// `upgrade` with a token for another generation of this lease.
    StaleGeneration,
    /// `upgrade` with a token whose epoch is not the current human epoch.
    ControlHeld,
    /// `clip` from a peer that is not the controller.
    NotController,
    /// A clipboard item over its limit.
    TooLarge,
}

/// The registry error a route refuses a stream token with, before the
/// WebSocket upgrade (`docs/services/sandboxes/stream.md#admission`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum AdmitError {
    /// 401: no token, a bad signature, expired, or revoked.
    Unauthenticated,
    /// 404: the token's lease is not in the token's tenant.
    NotFound,
    /// 409: the lease is not at the token's generation, or not READY.
    StaleGeneration,
    /// 409: a CONTROLLER token whose epoch is not the current human epoch.
    ControlHeld,
}

impl AdmitError {
    /// The HTTP status of the refusal.
    pub fn status(self) -> u16 {
        match self {
            AdmitError::Unauthenticated => 401,
            AdmitError::NotFound => 404,
            AdmitError::StaleGeneration | AdmitError::ControlHeld => 409,
        }
    }
}

// ---- control channel ------------------------------------------------------

/// A frame the client sends on `control`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "t", rename_all = "snake_case")]
pub enum ControlClient {
    /// Take this peer's input on the open connection, under a CONTROLLER
    /// token.
    Upgrade { token: String },
    /// Go back to watching.
    Downgrade,
}

/// A frame the machine sends on `control`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "t", rename_all = "snake_case")]
pub enum ControlServer {
    /// This peer's role changed (`epoch` is 0 for a viewer).
    Role { role: PeerRole, epoch: i64 },
    /// Who holds control, to every peer on every change.
    Control {
        holder: Holder,
        epoch: i64,
        label: String,
    },
    /// The machine's monitors.
    Monitors { list: Vec<Monitor> },
    /// The cursor image (PNG, base64) and its hotspot.
    Cursor {
        png: String,
        hx: u32,
        hy: u32,
        visible: bool,
    },
    /// Once a second. `encoder` is `hw:<api>` or `sw:<codec>`.
    Stats {
        rtt_ms: u32,
        fps: u32,
        kbps: u32,
        encoder: String,
    },
    /// A refused frame.
    Error(ErrorFrame),
}

/// A peer's role on the stream.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PeerRole {
    Viewer,
    Controller,
}

/// Who holds control of the display.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Holder {
    Human,
    Agent,
    None,
}

/// One monitor, in the machine's virtual screen.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Monitor {
    pub id: String,
    pub name: String,
    pub x: i32,
    pub y: i32,
    pub w: u32,
    pub h: u32,
    pub scale: f64,
    pub primary: bool,
}

// ---- input and pointer channels -------------------------------------------

/// A frame the client sends on `input`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "t", rename_all = "snake_case")]
pub enum Input {
    /// Button down.
    Pd(ButtonEvent),
    /// Button up.
    Pu(ButtonEvent),
    /// Wheel.
    Wh(Wheel),
    /// Key down.
    Kd(KeyEvent),
    /// Key up.
    Ku(KeyEvent),
    /// Committed text.
    Tx { text: String },
    /// Input-method composition state (a version 1 machine ignores it).
    Ime(Ime),
    /// A touch the client did not keep as a view gesture.
    Tc(Touch),
    /// A key combination from a Keys menu.
    Combo { keys: Vec<ComboKey> },
    /// Release every held key and button.
    ReleaseAll,
}

/// A frame the client sends on `pointer`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "t", rename_all = "snake_case")]
pub enum Pointer {
    /// Pointer move; `b` is the held-buttons bit mask (1 left, 2 right, 4
    /// middle).
    Pm {
        m: String,
        x: i32,
        y: i32,
        b: u8,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        ts: Option<u64>,
    },
}

/// `pd` / `pu`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ButtonEvent {
    pub m: String,
    pub x: i32,
    pub y: i32,
    pub button: Button,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ts: Option<u64>,
}

/// A mouse button: 0 left, 1 middle, 2 right, 3 back, 4 forward.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(try_from = "u8", into = "u8")]
pub struct Button(u8);

impl Button {
    pub const LEFT: Button = Button(0);
    pub fn get(self) -> u8 {
        self.0
    }
}

impl TryFrom<u8> for Button {
    type Error = String;
    fn try_from(v: u8) -> Result<Self, String> {
        if v <= 4 {
            Ok(Button(v))
        } else {
            Err(format!("button {v} is not 0-4"))
        }
    }
}

impl From<Button> for u8 {
    fn from(b: Button) -> u8 {
        b.0
    }
}

/// `wh`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Wheel {
    pub dx: f64,
    pub dy: f64,
    pub unit: WheelUnit,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ts: Option<u64>,
}

/// Wheel deltas in pixels or lines.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WheelUnit {
    Pixel,
    Line,
}

/// `kd` / `ku`. With no modifier but Shift, a printable `key` is typed as
/// Unicode; with Ctrl, Alt or Meta, `code` picks the key.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct KeyEvent {
    /// `KeyboardEvent.code`.
    pub code: String,
    /// `KeyboardEvent.key`.
    pub key: String,
    pub mods: Vec<Modifier>,
    pub repeat: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ts: Option<u64>,
}

impl KeyEvent {
    /// Whether this key types its `key` as Unicode: one character, and no
    /// modifier but Shift.
    pub fn types_unicode(&self) -> bool {
        self.key.chars().count() == 1 && self.mods.iter().all(|m| *m == Modifier::Shift)
    }
}

/// A held modifier.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Modifier {
    Ctrl,
    Alt,
    Shift,
    Meta,
}

/// `ime`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Ime {
    pub phase: ImePhase,
    pub text: String,
    pub caret: u32,
}

/// The composition's phase.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ImePhase {
    Start,
    Update,
    End,
}

/// `tc`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Touch {
    pub id: u32,
    pub phase: TouchPhase,
    pub m: String,
    pub x: i32,
    pub y: i32,
}

/// A touch's phase.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TouchPhase {
    Start,
    Move,
    End,
    Cancel,
}

/// A key a `combo` may name.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ComboKey {
    Ctrl,
    Alt,
    Shift,
    Meta,
    Delete,
    Tab,
    Escape,
    Enter,
    Backspace,
    Space,
    Printscreen,
    F1,
    F2,
    F3,
    F4,
    F5,
    F6,
    F7,
    F8,
    F9,
    F10,
    F11,
    F12,
}

impl ComboKey {
    /// The wire name (`ctrl`, `f12`).
    pub fn name(self) -> String {
        match serde_json::to_value(self) {
            Ok(serde_json::Value::String(s)) => s,
            _ => String::new(),
        }
    }
}

// ---- clipboard channel ----------------------------------------------------

/// A frame on `clipboard`, in either direction.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "t", rename_all = "snake_case")]
pub enum Clipboard {
    /// The clipboard's content.
    Clip(Clip),
    /// Slice `i` of `n` of a `clip` whose JSON is over 16 KiB.
    ClipChunk(ClipChunk),
    /// A refused frame.
    Error(ErrorFrame),
}

/// `clip`: `seq` counts up per sender.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Clip {
    pub seq: u64,
    pub items: Vec<ClipItem>,
}

/// One clipboard item: UTF-8 text, or a base64 PNG.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ClipItem {
    pub mime: ClipMime,
    pub data: String,
}

/// A clipboard item's type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ClipMime {
    #[serde(rename = "text/plain")]
    TextPlain,
    #[serde(rename = "image/png")]
    ImagePng,
}

/// `clip_chunk`: `data` is base64 of a slice of the `clip` frame's UTF-8.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ClipChunk {
    pub seq: u64,
    pub i: u32,
    pub n: u32,
    pub data: String,
}

impl Clip {
    /// Checks the limits: at most one item per type, text at most 1 MiB of
    /// UTF-8, a PNG at most 8 MiB decoded and valid base64.
    pub fn check(&self) -> Result<(), ErrorCode> {
        let mut seen = Vec::new();
        for item in &self.items {
            if seen.contains(&item.mime) {
                return Err(ErrorCode::InvalidMessage);
            }
            seen.push(item.mime);
            match item.mime {
                ClipMime::TextPlain => {
                    if item.data.len() > MAX_CLIP_TEXT_BYTES {
                        return Err(ErrorCode::TooLarge);
                    }
                }
                ClipMime::ImagePng => {
                    // Refuse on length before decoding anything large.
                    if item.data.len() > (MAX_CLIP_IMAGE_BYTES / 3 + 1) * 4 {
                        return Err(ErrorCode::TooLarge);
                    }
                    let bytes = STANDARD
                        .decode(item.data.as_bytes())
                        .map_err(|_| ErrorCode::InvalidMessage)?;
                    if bytes.len() > MAX_CLIP_IMAGE_BYTES {
                        return Err(ErrorCode::TooLarge);
                    }
                }
            }
        }
        Ok(())
    }

    /// The frames that carry this clip: itself when its JSON is at most
    /// [`MAX_FRAME_BYTES`], else its [`Clip::chunks`] of
    /// [`CHUNK_SLICE_BYTES`].
    pub fn frames(&self) -> Vec<Clipboard> {
        let frame = Clipboard::Clip(self.clone());
        if serde_json::to_vec(&frame).map_or(0, |b| b.len()) <= MAX_FRAME_BYTES {
            return vec![frame];
        }
        self.chunks(CHUNK_SLICE_BYTES)
    }

    /// The `clip` frame's UTF-8 cut into `clip_chunk` frames of at most
    /// `slice_bytes` before base64.
    pub fn chunks(&self, slice_bytes: usize) -> Vec<Clipboard> {
        let bytes = serde_json::to_vec(&Clipboard::Clip(self.clone())).unwrap_or_default();
        let slices: Vec<&[u8]> = bytes.chunks(slice_bytes.max(1)).collect();
        let n = slices.len() as u32;
        slices
            .into_iter()
            .enumerate()
            .map(|(i, s)| {
                Clipboard::ClipChunk(ClipChunk {
                    seq: self.seq,
                    i: i as u32,
                    n,
                    data: STANDARD.encode(s),
                })
            })
            .collect()
    }
}

/// Joins `clip_chunk` frames back into the `clip` they carry. A chunk of
/// another `seq` starts a new message and drops an unfinished one.
#[derive(Debug, Default, Clone)]
pub struct ChunkJoiner {
    seq: Option<u64>,
    parts: Vec<Option<Vec<u8>>>,
}

impl ChunkJoiner {
    /// Adds one chunk; returns the clip when every slice of its `seq` has
    /// arrived.
    pub fn push(&mut self, c: &ClipChunk) -> Result<Option<Clip>, ErrorCode> {
        if c.n == 0 || c.n > MAX_CHUNKS || c.i >= c.n {
            return Err(ErrorCode::InvalidMessage);
        }
        if self.seq != Some(c.seq) || self.parts.len() != c.n as usize {
            self.seq = Some(c.seq);
            self.parts = vec![None; c.n as usize];
        }
        let bytes = STANDARD
            .decode(c.data.as_bytes())
            .map_err(|_| ErrorCode::InvalidMessage)?;
        if bytes.len() > CHUNK_SLICE_BYTES {
            return Err(ErrorCode::TooLarge);
        }
        self.parts[c.i as usize] = Some(bytes);
        if self.parts.iter().any(Option::is_none) {
            return Ok(None);
        }
        let joined: Vec<u8> = self.parts.drain(..).flatten().flatten().collect();
        self.seq = None;
        match serde_json::from_slice::<Clipboard>(&joined) {
            Ok(Clipboard::Clip(clip)) => Ok(Some(clip)),
            _ => Err(ErrorCode::InvalidMessage),
        }
    }
}

// ---- parsing --------------------------------------------------------------

/// Parses a signalling frame from the client.
pub fn parse_signal_client(s: &str) -> Result<SignalClient, ErrorCode> {
    parse(s)
}

/// Parses a signalling frame from the server.
pub fn parse_signal_server(s: &str) -> Result<SignalServer, ErrorCode> {
    parse(s)
}

/// Parses a `control` frame from the client.
pub fn parse_control_client(s: &str) -> Result<ControlClient, ErrorCode> {
    parse(s)
}

/// Parses a `control` frame from the machine.
pub fn parse_control_server(s: &str) -> Result<ControlServer, ErrorCode> {
    parse(s)
}

/// Parses an `input` frame.
pub fn parse_input(s: &str) -> Result<Input, ErrorCode> {
    parse(s)
}

/// Parses a `pointer` frame.
pub fn parse_pointer(s: &str) -> Result<Pointer, ErrorCode> {
    parse(s)
}

/// Parses a `clipboard` frame.
pub fn parse_clipboard(s: &str) -> Result<Clipboard, ErrorCode> {
    parse(s)
}

fn parse<T: serde::de::DeserializeOwned>(s: &str) -> Result<T, ErrorCode> {
    serde_json::from_str(s).map_err(|_| ErrorCode::InvalidMessage)
}

/// Serialises any frame of this module.
pub fn to_json<T: Serialize>(frame: &T) -> String {
    serde_json::to_string(frame).unwrap_or_default()
}