rsurl 0.1.21

A pure-Rust implementation of curl. Library, C FFI, and CLI for HTTP/HTTPS/FTP/FTPS.
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
//! Experimental **async** HTTP + WebSocket client that compiles for both native
//! targets and the browser.
//!
//! On native targets this is the public entry point onto the runtime-agnostic
//! sans-IO engine: a protocol state machine driven over an async connection
//! supplied by a [`Runtime`] you provide (or the built-in [`TokioRuntime`],
//! behind the `tokio-rt` feature). Unlike the blocking API, it composes with
//! `async`/`await` and idiomatic concurrency — fan many [`get`] futures out with
//! `FuturesUnordered` / `JoinSet` instead of a curl-style multi handle.
//!
//! ```no_run
//! # #[cfg(all(feature = "tokio-rt", not(target_arch = "wasm32")))]
//! # async fn ex() -> Result<(), rsurl::Error> {
//! let rt = rsurl::aio::TokioRuntime;
//! let resp = rsurl::aio::get(&rt, "https://example.com/").await?;
//! println!("{} {} bytes", resp.status, resp.body.len());
//! # Ok(()) }
//! ```
//!
//! Scope (current cut): HTTP/1.1 over `http`/`https` with an arbitrary method,
//! request body, and caller headers (see [`Request`]); optional redirect
//! following, automatic response decompression, and a whole-request
//! [`timeout`](Request::timeout); curl-style TLS options for `https`/`wss`
//! (`-k`, `--cacert`, `--capath`, `--crlfile`, client certificates,
//! `--pinnedpubkey`, ciphers, version bounds; see [`TlsOptions`], also settable
//! directly on a [`Request`]); buffered response. Each request uses a fresh
//! `Connection: close` socket — connection pooling and streaming (non-buffered)
//! bodies are part of the ongoing sans-IO cutover and are not yet wired on this
//! async path.
//!
//! # On wasm32 (browser)
//!
//! `wasm32-unknown-unknown` has no sockets, no threads, and cannot block, so the
//! native sans-IO/socket path above does not compile there. Instead this module
//! routes [`request`] through the browser **Fetch API** and offers
//! [`WebSocket`] over the browser's native `WebSocket` object.
//!
//! ## What is portable, and what is not
//!
//! Portable **without any `cfg`** — the shared vocabulary of this module:
//!
//!   * [`Request`] and every builder on it, [`Response`] and every accessor on
//!     it ([`header`](Response::header), [`text`](Response::text),
//!     [`error_for_status`](Response::error_for_status), …), [`WsMessage`],
//!     [`TlsOptions`] (whose settings the browser ignores), and
//!     [`crate::Error`] / [`crate::Result`].
//!   * Every WebSocket *method*: `send` / `send_text` / `send_binary` / `recv` /
//!     `close` / `close_with` / `subprotocol` / `is_closed` has the same name,
//!     the same `&mut self` receiver, the same `async`-ness, and the same return
//!     type on both targets, so the body of a transfer loop needs no `cfg`.
//!
//! Needs a **`cfg` at the seam** — the two places a runtime is named:
//!
//!   * The entry points take a [`Runtime`] natively and nothing on wasm:
//!     `get(&rt, url)` vs `get(url)`, `WebSocket::connect(&rt, url)` vs
//!     `WebSocket::connect(url)`. The browser event loop *is* the runtime.
//!   * The native [`WebSocket`] is generic over the runtime's connection
//!     ([`TokioWebSocket`] names the `tokio-rt` one); the browser one is not
//!     generic. Write the `connect` behind a `cfg` and pass the value on:
//!
//! ```no_run
//! # use rsurl::aio::{Result, WsMessage};
//! # #[cfg(all(feature = "tokio-rt", not(target_arch = "wasm32")))]
//! # type Sock = rsurl::aio::TokioWebSocket;
//! # #[cfg(target_arch = "wasm32")]
//! # type Sock = rsurl::aio::WebSocket;
//! // The connect is target-specific…
//! # #[cfg(all(feature = "tokio-rt", not(target_arch = "wasm32")))]
//! async fn open(url: &str) -> Result<Sock> {
//!     Sock::connect(&rsurl::aio::TokioRuntime, url).await
//! }
//! # #[cfg(target_arch = "wasm32")]
//! # async fn open(url: &str) -> Result<Sock> { Sock::connect(url).await }
//!
//! // …everything after it is not.
//! # #[cfg(any(target_arch = "wasm32", all(feature = "tokio-rt", not(target_arch = "wasm32"))))]
//! async fn echo(ws: &mut Sock) -> Result<()> {
//!     ws.send_text("ping").await?;
//!     while let Some(msg) = ws.recv().await {
//!         if let WsMessage::Text(t) = msg? {
//!             println!("{t}");
//!             break;
//!         }
//!     }
//!     ws.close().await
//! }
//! ```
//!
//! Browser-imposed limits you inherit on wasm (none are rsurl bugs):
//!   * **Forbidden request headers** — the browser silently drops `Host`,
//!     `Connection`, `Content-Length`, and parts of `User-Agent`; rsurl does not
//!     synthesise them (fetch sets them itself).
//!   * **CORS** — cross-origin requests need server opt-in; a `no-cors` fetch
//!     yields an opaque, unreadable response.
//!   * **No TLS control** (every [`TlsOptions`] / [`Request`] TLS setting is
//!     accepted and ignored), **redirects/cookies are browser-managed**, and the
//!     response body arrives already decompressed (its `Content-Encoding` is
//!     stripped by the browser), so [`Request::decompress`] is a no-op here.
//!   * **No custom WebSocket handshake headers** (no `Authorization`); only
//!     subprotocols, via
//!     [`connect_with_subprotocols`](WebSocket::connect_with_subprotocols).
//!     Ping/pong control frames are the browser's business and are not visible.
//!   * The wasm-only `WebSocket::split` has no native counterpart: natively a
//!     single `WebSocket` owns the connection (use the blocking
//!     [`crate::WebSocket::split`] if you need two threads).

use std::time::Duration;

use crate::error::Error;
pub use crate::error::Result;

// ─── Native (socket) backend ────────────────────────────────────────────────
#[cfg(not(target_arch = "wasm32"))]
mod native;
// Same `WebSocket` name/surface as the browser one, but generic over the
// runtime's connection and taking a `Runtime` at connect (there is no implicit
// event loop natively).
#[cfg(not(target_arch = "wasm32"))]
mod ws;

#[cfg(not(target_arch = "wasm32"))]
pub use crate::io::runtime::{AsyncConn, Runtime};
#[cfg(all(feature = "tokio-rt", not(target_arch = "wasm32")))]
pub use crate::io::tokio::{TokioConn, TokioRuntime};
#[cfg(not(target_arch = "wasm32"))]
pub use native::{get, post, request};
#[cfg(not(target_arch = "wasm32"))]
pub use ws::WebSocket;

/// The [`WebSocket`] type produced by [`TokioRuntime`] — the name to write down
/// when storing one in a struct, since `WebSocket` is generic over the runtime's
/// connection type.
#[cfg(all(feature = "tokio-rt", not(target_arch = "wasm32")))]
pub type TokioWebSocket = WebSocket<TokioConn>;

// ─── Browser (fetch / WebSocket) backend ────────────────────────────────────
#[cfg(target_arch = "wasm32")]
mod wasm;
#[cfg(target_arch = "wasm32")]
pub use wasm::{get, post, request, WebSocket, WsSink, WsStream};

/// A buffered HTTP response from [`request`] (or [`get`] / [`post`]).
///
/// Non-exhaustive: it is constructed only by this module, and matching on it
/// needs a `..` rest pattern — fields may be added in a future release.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Response {
    /// HTTP status code (e.g. 200).
    pub status: u16,
    /// Reason phrase (may be empty on HTTP/2-style status lines).
    pub reason: String,
    /// Response headers, in received order.
    pub headers: Vec<(String, String)>,
    /// The response body. Decoded by default when the server applied a
    /// `Content-Encoding` (gzip / deflate / zstd / br); the
    /// `Content-Encoding`/`Content-Length` headers are stripped to match. Set
    /// [`Request::decompress(false)`](Request::decompress) to receive the raw
    /// encoded bytes instead.
    ///
    /// On wasm the browser applies any content coding before rsurl sees the
    /// bytes, so this is always the plaintext.
    pub body: Vec<u8>,
}

impl Response {
    /// The first value of header `name`, matched case-insensitively.
    pub fn header(&self, name: &str) -> Option<&str> {
        self.headers
            .iter()
            .find(|(k, _)| k.eq_ignore_ascii_case(name))
            .map(|(_, v)| v.as_str())
    }

    /// Whether the status is a `2xx` success.
    pub fn is_success(&self) -> bool {
        (200..300).contains(&self.status)
    }

    /// Decode the body to a `String` using the `Content-Type` charset.
    ///
    /// UTF-8 (the default when no charset is declared) is decoded lossily —
    /// invalid sequences become `U+FFFD`, like [`crate::Response::text`];
    /// ISO-8859-1 / Latin-1 is mapped directly. A declared charset rsurl cannot
    /// decode returns [`Error::Decode`] (use [`body`](Self::body) for the raw
    /// bytes).
    pub fn text(&self) -> Result<String> {
        match self.charset().as_deref() {
            None | Some("utf-8") | Some("utf8") | Some("us-ascii") | Some("ascii") => {
                Ok(String::from_utf8_lossy(&self.body).into_owned())
            }
            // Latin-1 code points are exactly Unicode U+00..=U+FF, so a byte→char
            // map is a faithful decode (unlike windows-1252, which differs in
            // 0x80–0x9F and is therefore rejected rather than mis-decoded).
            Some("iso-8859-1") | Some("iso8859-1") | Some("latin1") => {
                Ok(self.body.iter().map(|&b| b as char).collect())
            }
            Some(other) => Err(Error::Decode(format!(
                "unsupported Content-Type charset {other:?}; \
                 use Response::body for the raw {} bytes",
                self.body.len()
            ))),
        }
    }

    /// Deserialize the body as JSON into `T`. Requires the `json` Cargo feature
    /// (pure-Rust `serde_json`, off by default).
    #[cfg(feature = "json")]
    pub fn json<T: serde::de::DeserializeOwned>(&self) -> Result<T> {
        serde_json::from_slice(&self.body).map_err(|e| Error::Decode(format!("json: {e}")))
    }

    /// Consume the response, returning it unchanged for a 1xx–3xx status or
    /// [`Error::Status`] for a 4xx/5xx one — the reqwest-style "turn an HTTP
    /// error status into a `Result` error" convenience. The async counterpart of
    /// [`crate::Response::error_for_status`].
    pub fn error_for_status(self) -> Result<Self> {
        if self.status >= 400 {
            Err(Error::Status {
                code: self.status,
                reason: self.reason,
            })
        } else {
            Ok(self)
        }
    }

    /// Consume the response and return just the body bytes.
    pub fn into_body(self) -> Vec<u8> {
        self.body
    }

    /// The lowercased `charset=` parameter of `Content-Type`, if declared.
    fn charset(&self) -> Option<String> {
        let ct = self.header("content-type")?;
        ct.split(';').skip(1).find_map(|param| {
            let (k, v) = param.split_once('=')?;
            if !k.trim().eq_ignore_ascii_case("charset") {
                return None;
            }
            Some(v.trim().trim_matches('"').to_ascii_lowercase())
        })
    }
}

/// An async HTTP request: a method, a URL, caller headers, and a body.
///
/// Build one with [`Request::new`] (or the [`Request::get`] / [`Request::post`]
/// shortcuts) and send it with [`request`].
///
/// On native targets rsurl fills in the mandatory framing headers the caller did
/// not set — `Host`, `User-Agent`, `Accept`, `Connection: close`, and a
/// `Content-Length` matching the body — but never overrides or de-duplicates a
/// header the caller supplied, so passing any of those yourself takes
/// precedence. On wasm the browser owns those headers instead.
///
/// Non-exhaustive: build one through [`Request::new`] rather than a struct
/// literal — fields may be added in a future release.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Request {
    /// HTTP method (e.g. `GET`, `POST`). Sent verbatim.
    pub method: String,
    /// Absolute request URL (`http`/`https`).
    pub url: String,
    /// Caller headers, sent in order after rsurl's defaults.
    pub headers: Vec<(String, String)>,
    /// Request body. An empty body sends no payload.
    pub body: Vec<u8>,
    /// Follow `3xx` redirects (default `false`, matching the blocking API). On
    /// 301/302/303 a non-GET/HEAD request becomes a bodyless `GET`; 307/308
    /// preserve method and body. Capped at [`MAX_REDIRECTS`] hops.
    pub follow_redirects: bool,
    /// Decode the response body per its `Content-Encoding` (default `true`).
    pub decompress: bool,
    /// Whole-request deadline, redirects included (default `None`, i.e. no
    /// limit). See [`Request::timeout`].
    pub timeout: Option<Duration>,
    /// TLS settings for `https` (every redirect hop included). Set through the
    /// TLS builders ([`verify_tls`](Request::verify_tls), ...) or wholesale
    /// with [`tls`](Request::tls).
    tls: TlsOptions,
}

/// Maximum number of redirects [`request`] follows when
/// [`Request::follow_redirects`] is on, before failing with an
/// [`Error::BadResponse`].
///
/// Native only: on wasm the browser applies its own redirect limit.
pub const MAX_REDIRECTS: usize = 10;

/// Define the curl-style TLS builder methods (named like the blocking `Client`'s
/// and `Request`'s) on a type with a native-only
/// `tls_settings_mut(&mut self) -> &mut TlsSettings`. On wasm each method
/// compiles, with the same signature, to a documented no-op.
macro_rules! tls_setters {
    () => {
        tls_setters! {
            /// Verify the server certificate chain and hostname (default
            /// `true`; `false` is curl's `-k`/`--insecure`). A
            /// [`pinned_pubkey`](Self::pinned_pubkey) is still enforced when
            /// this is off.
            verify_tls(on: bool) => |s| s.verify = on;
            /// Trust the CA bundle (PEM) at `path` instead of the system roots
            /// (curl `--cacert`).
            ca_bundle(path: &str) => |s| s.ca_bundle = Some(path.to_string());
            /// Additionally trust every CA certificate in the directory `dir`
            /// (curl `--capath`), on top of the system roots or the
            /// [`ca_bundle`](Self::ca_bundle).
            ca_path(dir: &str) => |s| s.ca_path = Some(dir.to_string());
            /// Check the server chain against the CRL (PEM) at `path` (curl
            /// `--crlfile`).
            crl_file(path: &str) => |s| s.crl_file = Some(path.to_string());
            /// Present the client certificate at `path` (curl `-E`/`--cert`).
            /// PEM by default, see [`cert_type_der`](Self::cert_type_der); the
            /// key is read from the same file unless
            /// [`client_key`](Self::client_key) is set.
            client_cert(path: &str) => |s| s.client_cert = Some(path.to_string());
            /// Client private key at `path` (curl `--key`).
            client_key(path: &str) => |s| s.client_key = Some(path.to_string());
            /// Passphrase for an encrypted client key (curl `--pass`).
            client_key_pass(pass: &str) => |s| s.client_key_pass = Some(pass.to_string());
            /// Treat the client certificate file as DER (curl `--cert-type DER`).
            cert_type_der(der: bool) => |s| s.cert_is_der = der;
            /// Treat the client key file as DER (curl `--key-type DER`).
            key_type_der(der: bool) => |s| s.key_is_der = der;
            /// Pin the server public key (curl `--pinnedpubkey`,
            /// `sha256//BASE64[;sha256//BASE64...]`). A mismatch fails the
            /// connection before any request byte is sent, even with
            /// [`verify_tls(false)`](Self::verify_tls). A malformed spec fails
            /// the request up front.
            pinned_pubkey(spec: &str) => |s| s.pinned_pubkey = Some(spec.to_string());
            /// Restrict the TLS ≤ 1.2 cipher suites (curl `--ciphers`).
            ciphers(list: &str) => |s| s.ciphers = Some(list.to_string());
            /// Restrict the TLS 1.3 cipher suites (curl `--tls13-ciphers`).
            tls13_ciphers(list: &str) => |s| s.tls13_ciphers = Some(list.to_string());
            /// Minimum acceptable TLS version (curl `--tlsv1.x`).
            tls_min_version(v: crate::tls::ProtocolVersion) => |s| s.min_version = Some(v);
            /// Maximum acceptable TLS version (curl `--tls-max`).
            tls_max_version(v: crate::tls::ProtocolVersion) => |s| s.max_version = Some(v);
            /// Hand the trust decision to `cb`: rsurl's own chain validation
            /// is skipped and the callback's
            /// [`CertVerdict`](crate::tls::CertVerdict) decides (public-key
            /// pins are still enforced first). Same semantics as the
            /// blocking `Request::tls_verify_callback`.
            tls_verify_callback(cb: crate::tls::VerifyCallback) => |s| s.verify_callback = Some(cb);
        }
    };
    ($($(#[$doc:meta])* $name:ident($arg:ident: $ty:ty) => |$s:ident| $apply:expr;)*) => {$(
        $(#[$doc])*
        ///
        /// Ignored on wasm, where the browser owns TLS.
        #[cfg_attr(target_arch = "wasm32", allow(unused_mut))]
        pub fn $name(mut self, $arg: $ty) -> Self {
            #[cfg(not(target_arch = "wasm32"))]
            {
                let $s = self.tls_settings_mut();
                $apply;
            }
            #[cfg(target_arch = "wasm32")]
            let _ = $arg;
            self
        }
    )*};
}

impl Request {
    /// A request with the given method and URL, no extra headers, an empty
    /// body, redirects off, response decompression on, no timeout, and default
    /// TLS settings (verify against the system trust store; see [`TlsOptions`]).
    pub fn new(method: impl Into<String>, url: impl Into<String>) -> Self {
        Request {
            method: method.into(),
            url: url.into(),
            headers: Vec::new(),
            body: Vec::new(),
            follow_redirects: false,
            decompress: true,
            timeout: None,
            tls: TlsOptions::default(),
        }
    }

    /// A `GET` request for `url`.
    pub fn get(url: impl Into<String>) -> Self {
        Request::new("GET", url)
    }

    /// A `POST` request for `url` carrying `body`.
    pub fn post(url: impl Into<String>, body: impl Into<Vec<u8>>) -> Self {
        Request::new("POST", url).body(body)
    }

    /// Append a header. Call repeatedly to set several; order is preserved.
    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.push((name.into(), value.into()));
        self
    }

    /// Set the request body. Named to match [`crate::Request::body`] on the
    /// blocking API.
    pub fn body(mut self, body: impl Into<Vec<u8>>) -> Self {
        self.body = body.into();
        self
    }

    /// Set the request body.
    #[deprecated(since = "0.1.8", note = "renamed to `body`, matching the blocking API")]
    pub fn with_body(self, body: impl Into<Vec<u8>>) -> Self {
        self.body(body)
    }

    /// Follow `3xx` redirects (off by default). See
    /// [`follow_redirects`](Self::follow_redirects).
    pub fn follow_redirects(mut self, on: bool) -> Self {
        self.follow_redirects = on;
        self
    }

    /// Decode the response body per its `Content-Encoding` (on by default).
    /// A no-op on wasm, where the browser has already decoded the body.
    pub fn decompress(mut self, on: bool) -> Self {
        self.decompress = on;
        self
    }

    /// Fail the request if it has not completed within `dur` (redirect hops
    /// included). `None`, the default, means no deadline.
    ///
    /// Natively the deadline is raced against the transfer using
    /// [`Runtime::sleep`], and expiry yields [`Error::Io`] with
    /// [`std::io::ErrorKind::TimedOut`]. On wasm it becomes an
    /// `AbortSignal.timeout()` on the underlying fetch, so expiry surfaces as
    /// the browser's `AbortError` in [`Error::BadResponse`].
    pub fn timeout(mut self, dur: impl Into<Option<Duration>>) -> Self {
        self.timeout = dur.into();
        self
    }

    /// Replace this request's TLS settings with `opts` wholesale (handy to share
    /// one [`TlsOptions`] between requests and [`WebSocket`] connects). This
    /// overwrites anything set earlier through the individual TLS builders
    /// ([`verify_tls`](Self::verify_tls), [`ca_bundle`](Self::ca_bundle), ...).
    ///
    /// Ignored on wasm, where the browser owns TLS.
    pub fn tls(mut self, opts: TlsOptions) -> Self {
        self.tls = opts;
        self
    }

    /// The TLS settings the builders mutate.
    #[cfg(not(target_arch = "wasm32"))]
    fn tls_settings_mut(&mut self) -> &mut crate::tls::TlsSettings {
        &mut self.tls.settings
    }

    tls_setters!();
}

/// TLS settings for async `https://` requests and `wss://` WebSockets: the
/// verification, trust-store, client-certificate, pinning, cipher and version
/// options of the blocking API, with the same builder names.
///
/// `Default` verifies the server against the system trust store, with no client
/// certificate, pin, CRL, or cipher/version restriction. Hand it to
/// [`Request::tls`] or [`WebSocket::connect_with_tls`], or set the same options
/// directly on a [`Request`] ([`Request::verify_tls`], ...).
///
/// Files (CA bundle, CA directory, CRL, client certificate and key) are read,
/// and pins and cipher names parsed, when a connection is made, so a missing
/// file or a malformed spec fails that request before anything is sent.
///
/// ```
/// let opts = rsurl::aio::TlsOptions::new()
///     .ca_bundle("/etc/my-ca.pem")
///     .pinned_pubkey("sha256//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=");
/// let req = rsurl::aio::Request::get("https://internal.example/").tls(opts);
/// # let _ = req;
/// ```
///
/// # On wasm32
///
/// The browser owns TLS and exposes no knob for it, so every option here is
/// accepted and **ignored**: certificate verification always follows the
/// browser's own policy.
#[derive(Clone, Default)]
pub struct TlsOptions {
    #[cfg(not(target_arch = "wasm32"))]
    settings: crate::tls::TlsSettings,
}

impl TlsOptions {
    /// Default settings: verify against the system trust store.
    pub fn new() -> Self {
        Self::default()
    }

    /// The TLS settings the builders mutate.
    #[cfg(not(target_arch = "wasm32"))]
    fn tls_settings_mut(&mut self) -> &mut crate::tls::TlsSettings {
        &mut self.settings
    }

    tls_setters!();
}

#[cfg(not(target_arch = "wasm32"))]
impl std::fmt::Debug for TlsOptions {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let s = &self.settings;
        f.debug_struct("TlsOptions")
            .field("verify", &s.verify)
            .field("ca_bundle", &s.ca_bundle)
            .field("ca_path", &s.ca_path)
            .field("crl_file", &s.crl_file)
            .field("client_cert", &s.client_cert)
            .field("client_key", &s.client_key)
            // Never print the passphrase itself.
            .field(
                "client_key_pass",
                &s.client_key_pass.as_ref().map(|_| "<redacted>"),
            )
            .field("cert_is_der", &s.cert_is_der)
            .field("key_is_der", &s.key_is_der)
            .field("pinned_pubkey", &s.pinned_pubkey)
            .field("ciphers", &s.ciphers)
            .field("tls13_ciphers", &s.tls13_ciphers)
            .field("min_version", &s.min_version)
            .field("max_version", &s.max_version)
            .field("verify_callback", &s.verify_callback)
            .finish()
    }
}

#[cfg(target_arch = "wasm32")]
impl std::fmt::Debug for TlsOptions {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TlsOptions").finish_non_exhaustive()
    }
}

/// A message sent or received over an [`aio::WebSocket`](WebSocket): either a
/// UTF-8 text frame or a binary frame. The async, cross-target analogue of
/// [`crate::WsMessage`] (which is the native, blocking WebSocket's type).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WsMessage {
    /// A UTF-8 text message.
    Text(String),
    /// A binary message.
    Binary(Vec<u8>),
}

impl WsMessage {
    /// The message payload as bytes (the UTF-8 bytes for [`WsMessage::Text`]).
    pub fn as_bytes(&self) -> &[u8] {
        match self {
            WsMessage::Text(s) => s.as_bytes(),
            WsMessage::Binary(b) => b,
        }
    }

    /// The text, if this is a [`WsMessage::Text`].
    pub fn as_text(&self) -> Option<&str> {
        match self {
            WsMessage::Text(s) => Some(s),
            WsMessage::Binary(_) => None,
        }
    }

    /// Whether this is a [`WsMessage::Text`].
    pub fn is_text(&self) -> bool {
        matches!(self, WsMessage::Text(_))
    }

    /// Whether this is a [`WsMessage::Binary`].
    pub fn is_binary(&self) -> bool {
        matches!(self, WsMessage::Binary(_))
    }

    /// Consume the message and return its payload bytes.
    pub fn into_bytes(self) -> Vec<u8> {
        match self {
            WsMessage::Text(s) => s.into_bytes(),
            WsMessage::Binary(b) => b,
        }
    }
}

impl From<String> for WsMessage {
    fn from(s: String) -> Self {
        WsMessage::Text(s)
    }
}

impl From<&str> for WsMessage {
    fn from(s: &str) -> Self {
        WsMessage::Text(s.to_string())
    }
}

impl From<Vec<u8>> for WsMessage {
    fn from(b: Vec<u8>) -> Self {
        WsMessage::Binary(b)
    }
}

impl From<&[u8]> for WsMessage {
    fn from(b: &[u8]) -> Self {
        WsMessage::Binary(b.to_vec())
    }
}

#[cfg(test)]
mod shared_tests {
    use super::*;

    fn resp(headers: Vec<(String, String)>, body: Vec<u8>) -> Response {
        Response {
            status: 200,
            reason: "OK".into(),
            headers,
            body,
        }
    }

    #[test]
    fn response_header_lookup_is_case_insensitive() {
        let r = resp(
            vec![("Content-Type".into(), "text/plain".into())],
            Vec::new(),
        );
        assert_eq!(r.header("content-TYPE"), Some("text/plain"));
        assert_eq!(r.header("missing"), None);
        assert!(r.is_success());
    }

    #[test]
    fn text_honours_declared_charset() {
        let latin1 = resp(
            vec![(
                "Content-Type".into(),
                "text/plain; charset=ISO-8859-1".into(),
            )],
            vec![0xE9], // Latin-1 'é'
        );
        assert_eq!(latin1.text().unwrap(), "é");

        // No charset ⇒ UTF-8, lossily: a lone 0xE9 is not valid UTF-8.
        let utf8 = resp(
            vec![("Content-Type".into(), "text/plain".into())],
            vec![0xE9],
        );
        assert_eq!(utf8.text().unwrap(), "\u{fffd}");

        let unknown = resp(
            vec![(
                "Content-Type".into(),
                "text/plain; charset=shift_jis".into(),
            )],
            vec![0xE9],
        );
        assert!(matches!(unknown.text(), Err(Error::Decode(_))));
    }

    #[test]
    fn error_for_status_maps_4xx_to_err() {
        let mut bad = resp(Vec::new(), Vec::new());
        bad.status = 404;
        bad.reason = "Not Found".into();
        assert!(!bad.is_success());
        assert!(matches!(
            bad.error_for_status(),
            Err(Error::Status { code: 404, .. })
        ));
    }

    #[test]
    fn request_builder_defaults_and_overrides() {
        let req = Request::get("http://x/")
            .header("A", "1")
            .body(b"hi".to_vec())
            .follow_redirects(true)
            .decompress(false)
            .timeout(Duration::from_secs(5));
        assert_eq!(req.method, "GET");
        assert_eq!(req.headers, vec![("A".to_string(), "1".to_string())]);
        assert_eq!(req.body, b"hi");
        assert!(req.follow_redirects);
        assert!(!req.decompress);
        assert_eq!(req.timeout, Some(Duration::from_secs(5)));
        // `impl Into<Option<Duration>>` also accepts an explicit `None`.
        assert_eq!(Request::get("http://x/").timeout(None).timeout, None);
    }

    #[test]
    fn ws_message_conversions() {
        assert_eq!(WsMessage::from("hi"), WsMessage::Text("hi".into()));
        assert_eq!(WsMessage::from(vec![1u8, 2]), WsMessage::Binary(vec![1, 2]));
        assert!(WsMessage::from("hi").is_text());
        assert!(WsMessage::from(&b"x"[..]).is_binary());
        assert_eq!(WsMessage::Text("hi".into()).into_bytes(), b"hi");
    }
}