waterui-browser-cef 0.1.0

Shared CEF runtime for WaterUI WebView and Chromium components
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
//! Typed Chrome `DevTools` Protocol commands.
//!
//! Commands used to be `json!({...})` literals and their responses were read
//! field by field with `get("x").and_then(Value::as_str).expect(...)`. Every one
//! of those was a panic waiting for Chromium to rename or omit something, and a
//! misspelled method name was only discovered at runtime.
//!
//! A command is now a type: the method name is an associated constant, the
//! parameters are its fields, and the response is a struct serde fills in.

use serde::{Deserialize, Serialize};

/// One CDP command, with the response it produces.
pub trait CdpCommand: Serialize {
    /// The protocol method, such as [`Evaluate::METHOD`].
    const METHOD: &'static str;

    /// What Chromium sends back.
    type Response: for<'de> Deserialize<'de>;
}

/// Enables the runtime domain, which [`AddBinding`] needs.
#[cfg(feature = "webview")]
#[derive(Debug, Serialize)]
pub struct RuntimeEnable {}

#[cfg(feature = "webview")]
impl CdpCommand for RuntimeEnable {
    const METHOD: &'static str = "Runtime.enable";
    type Response = Empty;
}

/// Installs a function the page can call to reach native code.
#[cfg(feature = "webview")]
#[derive(Debug, Serialize)]
pub struct AddBinding {
    /// The global the page calls.
    pub name: &'static str,
}

#[cfg(feature = "webview")]
impl CdpCommand for AddBinding {
    const METHOD: &'static str = "Runtime.addBinding";
    type Response = Empty;
}

/// Enables the page domain, which [`AddScriptToEvaluateOnNewDocument`] needs.
///
/// Chromium accepts a document-start script whether or not the domain is
/// enabled, and only *runs* the registered scripts while it is, so leaving this
/// out installed the bridge into no document at all and reported success doing
/// it.
#[cfg(feature = "webview")]
#[derive(Debug, Serialize)]
pub struct PageEnable {}

#[cfg(feature = "webview")]
impl CdpCommand for PageEnable {
    const METHOD: &'static str = "Page.enable";
    type Response = Empty;
}

/// Registers a script that runs before anything else in each new document.
#[cfg(feature = "webview")]
#[derive(Debug, Serialize)]
pub struct AddScriptToEvaluateOnNewDocument<'a> {
    /// The script source.
    pub source: &'a str,
}

#[cfg(feature = "webview")]
impl CdpCommand for AddScriptToEvaluateOnNewDocument<'_> {
    const METHOD: &'static str = "Page.addScriptToEvaluateOnNewDocument";
    type Response = ScriptIdentifier;
}

/// Identifies a registered document-start script.
#[cfg(feature = "webview")]
#[derive(Debug, Deserialize)]
pub struct ScriptIdentifier {
    /// Chromium's handle for the script, used to replace or remove it.
    pub identifier: String,
}

/// Removes a script previously registered by
/// [`AddScriptToEvaluateOnNewDocument`].
///
/// Replacement is add-then-remove: a keyed injection has to drop the script it
/// supersedes, or a view that re-seeds its mirrored state on every navigation
/// accumulates one stale seed per navigation and the oldest still runs first.
#[cfg(feature = "webview")]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RemoveScriptToEvaluateOnNewDocument<'a> {
    /// The handle [`AddScriptToEvaluateOnNewDocument`] returned.
    pub identifier: &'a str,
}

#[cfg(feature = "webview")]
impl CdpCommand for RemoveScriptToEvaluateOnNewDocument<'_> {
    const METHOD: &'static str = "Page.removeScriptToEvaluateOnNewDocument";
    type Response = Empty;
}

/// Evaluates an expression in the page.
#[cfg(feature = "webview")]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Evaluate<'a> {
    /// The source to evaluate.
    pub expression: &'a str,
    /// Wait for a promise result rather than returning the promise.
    pub await_promise: bool,
    /// Return the value itself rather than a remote handle.
    pub return_by_value: bool,
    /// Which execution context to evaluate in; the default context when absent.
    ///
    /// A bridge reply has to go back to the context that made the call. Sending
    /// every reply to the default context left a sub-frame's
    /// `waterui.invoke(...)` promise pending forever, because the resolver it
    /// was waiting on lives in the frame's own context.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context_id: Option<i64>,
}

#[cfg(feature = "webview")]
impl CdpCommand for Evaluate<'_> {
    const METHOD: &'static str = "Runtime.evaluate";
    type Response = EvaluateResponse;
}

/// The outcome of an evaluation.
#[cfg(feature = "webview")]
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EvaluateResponse {
    /// The value, or a description of it.
    pub result: RemoteObject,
    /// Present when the expression threw.
    #[serde(default)]
    pub exception_details: Option<ExceptionDetails>,
}

/// A value the page produced.
#[cfg(feature = "webview")]
#[derive(Debug, Deserialize)]
pub struct RemoteObject {
    /// The value, when it could be returned by value.
    #[serde(default)]
    pub value: Option<serde_json::Value>,
    /// A human-readable description, for values that cannot be.
    #[serde(default)]
    pub description: Option<String>,
}

/// Why an evaluation failed.
#[cfg(feature = "webview")]
#[derive(Debug, Deserialize)]
pub struct ExceptionDetails {
    /// The message Chromium reports.
    pub text: String,
    /// The thrown value, when there was one.
    #[serde(default)]
    #[expect(
        dead_code,
        reason = "`text` carries the message; the value is decoded for completeness"
    )]
    pub exception: Option<RemoteObject>,
}

/// Overrides the user agent for subsequent requests.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SetUserAgentOverride<'a> {
    /// The user agent to send. Empty clears the override.
    pub user_agent: &'a str,
}

impl CdpCommand for SetUserAgentOverride<'_> {
    const METHOD: &'static str = "Network.setUserAgentOverride";
    type Response = Empty;
}

/// Stores one cookie.
#[cfg(feature = "webview")]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SetCookie<'a> {
    /// Cookie name.
    pub name: &'a str,
    /// Cookie value.
    pub value: &'a str,
    /// The domain it belongs to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub domain: Option<&'a str>,
    /// The URL it belongs to, used when no domain is given.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<&'a str>,
    /// Path scope.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<&'a str>,
    /// Whether it is HTTPS-only.
    pub secure: bool,
    /// Whether script can read it.
    pub http_only: bool,
    /// Cross-site policy.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub same_site: Option<&'static str>,
    /// Expiry as a Unix timestamp.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires: Option<i64>,
}

#[cfg(feature = "webview")]
impl CdpCommand for SetCookie<'_> {
    const METHOD: &'static str = "Network.setCookie";
    type Response = Empty;
}

/// Reads the cookies visible to the given URLs.
#[cfg(feature = "webview")]
#[derive(Debug, Serialize)]
pub struct GetCookies<'a> {
    /// The URLs whose cookies to read. Empty means the current document's.
    pub urls: Vec<&'a str>,
}

#[cfg(feature = "webview")]
impl CdpCommand for GetCookies<'_> {
    const METHOD: &'static str = "Network.getCookies";
    type Response = GetCookiesResponse;
}

/// The cookies Chromium returned.
#[cfg(feature = "webview")]
#[derive(Debug, Deserialize)]
pub struct GetCookiesResponse {
    /// One entry per cookie.
    pub cookies: Vec<Cookie>,
}

/// One stored cookie.
#[cfg(feature = "webview")]
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Cookie {
    /// Cookie name.
    pub name: String,
    /// Cookie value.
    pub value: String,
    /// The domain it belongs to.
    pub domain: String,
    /// Path scope.
    pub path: String,
    /// Whether it is HTTPS-only.
    pub secure: bool,
    /// Whether script can read it.
    pub http_only: bool,
    /// Cross-site policy, when Chromium reports one.
    #[serde(default)]
    pub same_site: Option<String>,
    /// Expiry as a Unix timestamp; non-positive means a session cookie.
    #[serde(default)]
    pub expires: f64,
}

/// Captures the page as an image.
///
/// Screenshots are a `chromium` capability: the only caller,
/// `page::screenshot_command`, is gated the same way.
#[cfg(feature = "chromium")]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CaptureScreenshot {
    /// Image format.
    pub format: &'static str,
    /// Quality, for formats that have one.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub quality: Option<u8>,
    /// Capture from the compositor surface.
    pub from_surface: bool,
    /// Restrict to the visible viewport.
    pub capture_beyond_viewport: bool,
}

#[cfg(feature = "chromium")]
impl CdpCommand for CaptureScreenshot {
    const METHOD: &'static str = "Page.captureScreenshot";
    type Response = CaptureScreenshotResponse;
}

/// The captured image.
#[cfg(feature = "chromium")]
#[derive(Debug, Deserialize)]
pub struct CaptureScreenshotResponse {
    /// Base64-encoded image bytes.
    pub data: String,
}

/// Chooses where downloads are written.
///
/// Redirecting downloads is a `chromium` capability: the only caller,
/// `page::set_download_directory`, is gated the same way.
#[cfg(feature = "chromium")]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SetDownloadBehavior<'a> {
    /// What to do with a download.
    pub behavior: &'static str,
    /// Where to put it.
    pub download_path: &'a str,
}

#[cfg(feature = "chromium")]
impl CdpCommand for SetDownloadBehavior<'_> {
    const METHOD: &'static str = "Browser.setDownloadBehavior";
    type Response = Empty;
}

/// Reports the browser version; used to probe that the `DevTools` agent attached.
#[derive(Debug, Serialize)]
pub struct GetVersion {}

impl CdpCommand for GetVersion {
    const METHOD: &'static str = "Browser.getVersion";
    type Response = Empty;
}

/// A response with nothing worth reading.
#[derive(Debug, Deserialize)]
pub struct Empty {}

#[cfg(test)]
mod tests {
    #[cfg(feature = "chromium")]
    use super::CaptureScreenshot;
    #[cfg(feature = "webview")]
    use super::{CdpCommand, Cookie, Evaluate, EvaluateResponse, SetCookie};

    #[test]
    #[cfg(feature = "webview")]
    fn parameters_serialize_under_the_names_chromium_expects() {
        let evaluate = Evaluate {
            expression: "1 + 1",
            await_promise: true,
            return_by_value: true,
            context_id: None,
        };
        let json = serde_json::to_value(&evaluate).expect("serializes");

        assert_eq!(Evaluate::METHOD, "Runtime.evaluate");
        assert_eq!(json["expression"], "1 + 1");
        // camelCase, because that is what the protocol uses.
        assert_eq!(json["awaitPromise"], true);
        assert_eq!(json["returnByValue"], true);
        // The default context is expressed by omission, not by null.
        assert!(json.get("contextId").is_none());
    }

    #[test]
    #[cfg(feature = "webview")]
    fn absent_optional_parameters_are_omitted_rather_than_sent_as_null() {
        let cookie = SetCookie {
            name: "session",
            value: "abc",
            domain: None,
            url: Some("https://waterui.dev"),
            path: None,
            secure: true,
            http_only: true,
            same_site: None,
            expires: None,
        };
        let json = serde_json::to_value(&cookie).expect("serializes");

        assert!(json.get("domain").is_none());
        assert!(json.get("sameSite").is_none());
        assert_eq!(json["httpOnly"], true);
    }

    #[test]
    #[cfg(feature = "chromium")]
    fn png_omits_the_quality_parameter_that_only_lossy_formats_take() {
        let png = CaptureScreenshot {
            format: "png",
            quality: None,
            from_surface: true,
            capture_beyond_viewport: false,
        };
        let json = serde_json::to_value(&png).expect("serializes");
        assert!(json.get("quality").is_none());
    }

    #[test]
    #[cfg(feature = "webview")]
    fn a_response_missing_its_optional_fields_still_parses() {
        // Previously each of these absent fields was an `expect` away from a panic.
        let response: EvaluateResponse = serde_json::from_str(r#"{"result":{}}"#).expect("parses");
        assert!(response.result.value.is_none());
        assert!(response.exception_details.is_none());

        let cookie: Cookie = serde_json::from_str(
            r#"{"name":"a","value":"b","domain":"waterui.dev","path":"/","secure":true,"httpOnly":false}"#,
        )
        .expect("parses");
        assert!(cookie.same_site.is_none());
        assert!(cookie.expires.abs() < f64::EPSILON);
    }
}