Skip to main content

strata_js/
web.rs

1//! Universal Web Platform APIs implemented in pure standard-library Rust.
2
3use crate::JsValue;
4use std::cell::RefCell;
5use std::collections::BTreeMap;
6use std::rc::Rc;
7use std::time::{Duration, Instant};
8
9/// W3C-compliant case-insensitive HTTP Headers map.
10#[derive(Debug, Default, Clone, PartialEq)]
11pub struct Headers {
12    // Stores lowercase name -> (display_name, list of values)
13    entries: BTreeMap<String, (String, Vec<String>)>,
14}
15
16impl Headers {
17    /// Creates an empty `Headers` instance.
18    pub fn new() -> Self {
19        Self::default()
20    }
21
22    /// Sets a header, overwriting any previous values for this header name.
23    pub fn set(&mut self, name: impl Into<String>, value: impl Into<String>) {
24        let name_str = name.into();
25        let lower = name_str.to_ascii_lowercase();
26        self.entries.insert(lower, (name_str, vec![value.into()]));
27    }
28
29    /// Appends a value to an existing header, or creates it if it does not exist.
30    pub fn append(&mut self, name: impl Into<String>, value: impl Into<String>) {
31        let name_str = name.into();
32        let lower = name_str.to_ascii_lowercase();
33        self.entries
34            .entry(lower)
35            .or_insert_with(|| (name_str, Vec::new()))
36            .1
37            .push(value.into());
38    }
39
40    /// Retrieves the combined comma-separated string for a given header name, if it exists.
41    pub fn get(&self, name: &str) -> Option<String> {
42        let lower = name.to_ascii_lowercase();
43        self.entries.get(&lower).map(|(_, vals)| vals.join(", "))
44    }
45
46    /// Retrieves all individual values for a given header name.
47    pub fn get_all(&self, name: &str) -> Vec<&str> {
48        let lower = name.to_ascii_lowercase();
49        self.entries
50            .get(&lower)
51            .map(|(_, vals)| vals.iter().map(|s| s.as_str()).collect())
52            .unwrap_or_default()
53    }
54
55    /// Returns `true` if the specified header exists.
56    pub fn has(&self, name: &str) -> bool {
57        self.entries.contains_key(&name.to_ascii_lowercase())
58    }
59
60    /// Deletes a header by name (case-insensitive).
61    pub fn delete(&mut self, name: &str) {
62        self.entries.remove(&name.to_ascii_lowercase());
63    }
64
65    /// Returns all header entries as (name, comma-joined-value) pairs.
66    pub fn entries(&self) -> Vec<(String, String)> {
67        self.entries
68            .values()
69            .map(|(name, vals)| (name.clone(), vals.join(", ")))
70            .collect()
71    }
72}
73
74/// Request configuration passed to `fetch()`.
75#[derive(Debug, Clone)]
76pub struct RequestInit {
77    pub method: String,
78    pub headers: Headers,
79    pub body: Option<String>,
80}
81
82impl Default for RequestInit {
83    fn default() -> Self {
84        Self {
85            method: "GET".to_string(),
86            headers: Headers::new(),
87            body: None,
88        }
89    }
90}
91
92/// HTTP Response representing the result of an HTTP operation.
93#[derive(Debug, Clone)]
94pub struct Response {
95    pub status: u16,
96    pub status_text: String,
97    pub ok: bool,
98    pub headers: Headers,
99    body: Vec<u8>,
100}
101
102impl Response {
103    /// Constructs a new `Response` object.
104    pub fn new(body: Vec<u8>, status: u16, headers: Headers) -> Self {
105        let ok = (200..=299).contains(&status);
106        let status_text = match status {
107            200 => "OK",
108            201 => "Created",
109            204 => "No Content",
110            400 => "Bad Request",
111            401 => "Unauthorized",
112            403 => "Forbidden",
113            404 => "Not Found",
114            500 => "Internal Server Error",
115            _ => "Unknown",
116        }
117        .to_string();
118
119        Self {
120            status,
121            status_text,
122            ok,
123            headers,
124            body,
125        }
126    }
127
128    /// Decodes the response body as a UTF-8 text string.
129    pub async fn text(self) -> Result<String, String> {
130        String::from_utf8(self.body).map_err(|e| format!("Invalid UTF-8 in response body: {}", e))
131    }
132
133    /// Decodes and parses the response body as a dynamic `JsValue` via JSON parser.
134    pub async fn json(self) -> Result<JsValue, String> {
135        let text = self.text().await?;
136        crate::json::parse_json(&text)
137    }
138}
139
140/// Outbound HTTP fetch request passed to the registered host [`FetchHandler`].
141#[derive(Debug, Clone, PartialEq)]
142pub struct FetchRequest {
143    pub url: String,
144    pub method: String,
145    pub headers: Vec<(String, String)>,
146    pub body: Option<Vec<u8>>,
147}
148
149/// Raw HTTP response returned by a host [`FetchHandler`].
150#[derive(Debug, Clone, PartialEq)]
151pub struct FetchResponse {
152    pub status: u16,
153    pub status_text: String,
154    pub headers: Vec<(String, String)>,
155    pub body: Vec<u8>,
156}
157
158impl FetchResponse {
159    /// Returns `true` for 2xx HTTP status codes.
160    pub fn ok(&self) -> bool {
161        (200..300).contains(&self.status)
162    }
163}
164
165/// Host networking callback invoked by JavaScript `fetch()`.
166pub type FetchHandler =
167    std::sync::Arc<dyn Fn(FetchRequest) -> Result<FetchResponse, String> + Send + Sync>;
168
169fn global_fetch_handler_cell() -> &'static std::sync::RwLock<Option<FetchHandler>> {
170    static HANDLER: std::sync::OnceLock<std::sync::RwLock<Option<FetchHandler>>> =
171        std::sync::OnceLock::new();
172    HANDLER.get_or_init(|| std::sync::RwLock::new(None))
173}
174
175/// Registers the host networking backend used by JavaScript `fetch()` (e.g. `strata_web_api::fetch`).
176pub fn set_global_fetch_handler(handler: FetchHandler) {
177    if let Ok(mut guard) = global_fetch_handler_cell().write() {
178        *guard = Some(handler);
179    }
180}
181
182/// Dispatches a synchronous HTTP request via the registered host [`FetchHandler`],
183/// falling back to a built-in pure-`std` HTTP/1.1 client for `http://` URLs.
184pub fn dispatch_fetch_sync(req: FetchRequest) -> Result<FetchResponse, String> {
185    if req.url.starts_with("mock://") {
186        let body = req.body.unwrap_or_else(|| b"{\"status\":\"ok\"}".to_vec());
187        return Ok(FetchResponse {
188            status: 200,
189            status_text: "OK".to_string(),
190            headers: vec![("content-type".to_string(), "application/json".to_string())],
191            body,
192        });
193    }
194    let handler = global_fetch_handler_cell()
195        .read()
196        .ok()
197        .and_then(|g| g.clone());
198    if let Some(h) = handler {
199        return h(req);
200    }
201    if req.url.starts_with("http://") {
202        return builtin_http_fetch(&req);
203    }
204    Err(format!(
205        "TypeError: Failed to fetch {}: no host fetch handler registered for this scheme (call strata_js::web::set_global_fetch_handler)",
206        req.url
207    ))
208}
209
210fn builtin_http_fetch(req: &FetchRequest) -> Result<FetchResponse, String> {
211    use std::io::{Read, Write};
212    use std::net::TcpStream;
213
214    let stripped = req
215        .url
216        .strip_prefix("http://")
217        .ok_or_else(|| format!("Unsupported URL scheme: {}", req.url))?;
218    let (host_port, path) = match stripped.find('/') {
219        Some(idx) => (&stripped[..idx], &stripped[idx..]),
220        None => (stripped, "/"),
221    };
222    let addr = if host_port.contains(':') {
223        host_port.to_string()
224    } else {
225        format!("{host_port}:80")
226    };
227    let mut stream = TcpStream::connect(&addr)
228        .map_err(|e| format!("Failed to connect to {addr}: {e}"))?;
229    let _ = stream.set_read_timeout(Some(Duration::from_secs(10)));
230    let _ = stream.set_write_timeout(Some(Duration::from_secs(10)));
231
232    let body = req.body.as_deref().unwrap_or(&[]);
233    let mut raw_req = format!(
234        "{} {} HTTP/1.1\r\nHost: {}\r\nConnection: close\r\n",
235        req.method, path, host_port
236    );
237    let mut has_content_len = false;
238    for (k, v) in &req.headers {
239        if k.eq_ignore_ascii_case("content-length") {
240            has_content_len = true;
241        }
242        raw_req.push_str(&format!("{k}: {v}\r\n"));
243    }
244    if !body.is_empty() && !has_content_len {
245        raw_req.push_str(&format!("Content-Length: {}\r\n", body.len()));
246    }
247    raw_req.push_str("\r\n");
248
249    stream
250        .write_all(raw_req.as_bytes())
251        .and_then(|_| stream.write_all(body))
252        .and_then(|_| stream.flush())
253        .map_err(|e| format!("Failed to write HTTP request: {e}"))?;
254
255    let mut resp_bytes = Vec::new();
256    stream
257        .read_to_end(&mut resp_bytes)
258        .map_err(|e| format!("Failed to read HTTP response: {e}"))?;
259
260    let split_pos = resp_bytes
261        .windows(4)
262        .position(|w| w == b"\r\n\r\n")
263        .ok_or_else(|| "Malformed HTTP response: missing header terminator".to_string())?;
264    let header_str = String::from_utf8_lossy(&resp_bytes[..split_pos]);
265    let body_bytes = resp_bytes[split_pos + 4..].to_vec();
266
267    let mut lines = header_str.lines();
268    let status_line = lines.next().unwrap_or("HTTP/1.1 200 OK");
269    let mut parts = status_line.splitn(3, ' ');
270    let _http_ver = parts.next();
271    let status = parts
272        .next()
273        .and_then(|s| s.parse::<u16>().ok())
274        .unwrap_or(200);
275    let status_text = parts.next().unwrap_or("OK").to_string();
276
277    let mut headers = Vec::new();
278    for line in lines {
279        if let Some((k, v)) = line.split_once(':') {
280            headers.push((k.trim().to_string(), v.trim().to_string()));
281        }
282    }
283
284    Ok(FetchResponse {
285        status,
286        status_text,
287        headers,
288        body: body_bytes,
289    })
290}
291
292/// Asynchronous fetch delegating to the host [`FetchHandler`] (or built-in `mock://` scheme).
293pub async fn fetch(url: &str, init: Option<RequestInit>) -> Result<Response, String> {
294    let init = init.unwrap_or_default();
295
296    let req = FetchRequest {
297        url: url.to_string(),
298        method: init.method,
299        headers: init.headers.entries(),
300        body: init.body.map(|s| s.into_bytes()),
301    };
302
303    let resp = dispatch_fetch_sync(req)
304        .map_err(|e| format!("TypeError: Failed to fetch {}: {}", url, e))?;
305
306    let mut headers = Headers::new();
307    for (k, v) in resp.headers {
308        headers.append(k, v);
309    }
310
311    let mut result_resp = Response::new(resp.body, resp.status, headers);
312    result_resp.status_text = resp.status_text;
313    Ok(result_resp)
314}
315
316/// URLSearchParams: Parsing, manipulating, and serializing URL query parameters.
317#[derive(Debug, Default, Clone, PartialEq)]
318pub struct URLSearchParams {
319    params: Vec<(String, String)>,
320}
321
322impl URLSearchParams {
323    /// Creates an empty `URLSearchParams`.
324    pub fn new() -> Self {
325        Self::default()
326    }
327
328    /// Parses a query string (with or without a leading '?').
329    pub fn parse(query: &str) -> Self {
330        let query = query.strip_prefix('?').unwrap_or(query);
331        let mut params = Vec::new();
332
333        if query.is_empty() {
334            return Self { params };
335        }
336
337        for pair in query.split('&') {
338            if pair.is_empty() {
339                continue;
340            }
341            let mut parts = pair.splitn(2, '=');
342            let key_enc = parts.next().unwrap_or("");
343            let val_enc = parts.next().unwrap_or("");
344
345            let key = decode_uri_component(key_enc);
346            let val = decode_uri_component(val_enc);
347            params.push((key, val));
348        }
349
350        Self { params }
351    }
352
353    /// Returns the first value associated with the given search parameter.
354    pub fn get(&self, name: &str) -> Option<&str> {
355        self.params
356            .iter()
357            .find(|(k, _)| k == name)
358            .map(|(_, v)| v.as_str())
359    }
360
361    /// Returns all values associated with the given search parameter.
362    pub fn get_all(&self, name: &str) -> Vec<&str> {
363        self.params
364            .iter()
365            .filter(|(k, _)| k == name)
366            .map(|(_, v)| v.as_str())
367            .collect()
368    }
369
370    /// Returns `true` if the search parameter exists.
371    pub fn has(&self, name: &str) -> bool {
372        self.params.iter().any(|(k, _)| k == name)
373    }
374
375    /// Appends a new name-value pair.
376    pub fn append(&mut self, name: impl Into<String>, value: impl Into<String>) {
377        self.params.push((name.into(), value.into()));
378    }
379
380    /// Sets the value associated with a given name, replacing all existing pairs with that name.
381    pub fn set(&mut self, name: impl Into<String>, value: impl Into<String>) {
382        let name_str = name.into();
383        let value_str = value.into();
384        let mut replaced = false;
385        let mut i = 0;
386
387        while i < self.params.len() {
388            if self.params[i].0 == name_str {
389                if !replaced {
390                    self.params[i].1 = value_str.clone();
391                    replaced = true;
392                    i += 1;
393                } else {
394                    self.params.remove(i);
395                }
396            } else {
397                i += 1;
398            }
399        }
400
401        if !replaced {
402            self.params.push((name_str, value_str));
403        }
404    }
405
406    /// Deletes all occurrences of the specified parameter.
407    pub fn delete(&mut self, name: &str) {
408        self.params.retain(|(k, _)| k != name);
409    }
410
411    /// Sorts all key/value pairs by their keys using unicode code points.
412    pub fn sort(&mut self) {
413        self.params.sort_by(|a, b| a.0.cmp(&b.0));
414    }
415
416    /// Serializes parameters back into standard application/x-www-form-urlencoded query string.
417    pub fn to_query_string(&self) -> String {
418        let mut out = String::new();
419        for (i, (k, v)) in self.params.iter().enumerate() {
420            if i > 0 {
421                out.push('&');
422            }
423            out.push_str(&encode_uri_component(k));
424            out.push('=');
425            out.push_str(&encode_uri_component(v));
426        }
427        out
428    }
429}
430
431fn decode_uri_component(s: &str) -> String {
432    let s = s.replace('+', " ");
433    let bytes = s.as_bytes();
434    let mut result = Vec::new();
435    let mut i = 0;
436
437    while i < bytes.len() {
438        if bytes[i] == b'%' && i + 2 < bytes.len() {
439            if let Ok(hex_str) = std::str::from_utf8(&bytes[i + 1..i + 3]) {
440                if let Ok(b) = u8::from_str_radix(hex_str, 16) {
441                    result.push(b);
442                    i += 3;
443                    continue;
444                }
445            }
446        }
447        result.push(bytes[i]);
448        i += 1;
449    }
450
451    String::from_utf8_lossy(&result).into_owned()
452}
453
454fn encode_uri_component(s: &str) -> String {
455    let mut out = String::new();
456    for b in s.as_bytes() {
457        match *b {
458            b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
459                out.push(*b as char);
460            }
461            b' ' => out.push('+'),
462            other => {
463                out.push_str(&format!("%{:02X}", other));
464            }
465        }
466    }
467    out
468}
469
470/// Web Storage API (localStorage, sessionStorage).
471#[derive(Debug, Clone, Default)]
472pub struct Storage {
473    data: Rc<RefCell<BTreeMap<String, String>>>,
474}
475
476impl Storage {
477    pub fn new() -> Self {
478        Self::default()
479    }
480
481    pub fn length(&self) -> usize {
482        self.data.borrow().len()
483    }
484
485    pub fn key(&self, index: usize) -> Option<String> {
486        self.data.borrow().keys().nth(index).cloned()
487    }
488
489    pub fn get_item(&self, key: &str) -> Option<String> {
490        self.data.borrow().get(key).cloned()
491    }
492
493    pub fn set_item(&self, key: impl Into<String>, value: impl Into<String>) {
494        self.data.borrow_mut().insert(key.into(), value.into());
495    }
496
497    pub fn remove_item(&self, key: &str) {
498        self.data.borrow_mut().remove(key);
499    }
500
501    pub fn clear(&self) {
502        self.data.borrow_mut().clear();
503    }
504}
505
506thread_local! {
507    static LOCAL_STORAGE: Storage = Storage::new();
508    static SESSION_STORAGE: Storage = Storage::new();
509}
510
511/// Returns the singleton `localStorage` for the current thread/context.
512pub fn local_storage() -> Storage {
513    LOCAL_STORAGE.with(|s| s.clone())
514}
515
516/// Returns the singleton `sessionStorage` for the current thread/context.
517pub fn session_storage() -> Storage {
518    SESSION_STORAGE.with(|s| s.clone())
519}
520
521/// Zero-dependency High-Resolution Timer Scheduler.
522pub type TimerId = usize;
523
524enum TimerEntry {
525    Timeout {
526        id: TimerId,
527        trigger_at: Instant,
528        callback: Option<Box<dyn FnOnce()>>,
529        cancelled: bool,
530    },
531    Interval {
532        id: TimerId,
533        interval: Duration,
534        next_trigger: Instant,
535        callback: Box<dyn FnMut()>,
536        cancelled: bool,
537    },
538}
539
540struct TimerScheduler {
541    next_id: usize,
542    entries: Vec<TimerEntry>,
543    simulated_offset: Duration,
544}
545
546impl TimerScheduler {
547    fn new() -> Self {
548        Self {
549            next_id: 1,
550            entries: Vec::new(),
551            simulated_offset: Duration::ZERO,
552        }
553    }
554
555    fn current_time(&self) -> Instant {
556        Instant::now() + self.simulated_offset
557    }
558
559    fn add_timeout(&mut self, callback: Box<dyn FnOnce()>, delay_ms: u64) -> TimerId {
560        let id = self.next_id;
561        self.next_id += 1;
562        let trigger_at = self.current_time() + Duration::from_millis(delay_ms);
563        self.entries.push(TimerEntry::Timeout {
564            id,
565            trigger_at,
566            callback: Some(callback),
567            cancelled: false,
568        });
569        id
570    }
571
572    fn add_interval(&mut self, callback: Box<dyn FnMut()>, interval_ms: u64) -> TimerId {
573        let id = self.next_id;
574        self.next_id += 1;
575        let interval = Duration::from_millis(interval_ms);
576        let next_trigger = self.current_time() + interval;
577        self.entries.push(TimerEntry::Interval {
578            id,
579            interval,
580            next_trigger,
581            callback,
582            cancelled: false,
583        });
584        id
585    }
586
587    fn cancel(&mut self, id: TimerId) {
588        for entry in &mut self.entries {
589            match entry {
590                TimerEntry::Timeout {
591                    id: entry_id,
592                    cancelled,
593                    ..
594                }
595                | TimerEntry::Interval {
596                    id: entry_id,
597                    cancelled,
598                    ..
599                } => {
600                    if *entry_id == id {
601                        *cancelled = true;
602                    }
603                }
604            }
605        }
606    }
607
608    fn tick(&mut self) -> usize {
609        let now = self.current_time();
610        let mut fired = 0;
611        let mut pending_timeouts = Vec::new();
612        let mut pending_intervals = Vec::new();
613
614        for (idx, entry) in self.entries.iter_mut().enumerate() {
615            match entry {
616                TimerEntry::Timeout {
617                    trigger_at,
618                    cancelled,
619                    callback,
620                    ..
621                } => {
622                    if !*cancelled && now >= *trigger_at {
623                        if let Some(cb) = callback.take() {
624                            pending_timeouts.push(cb);
625                            *cancelled = true;
626                            fired += 1;
627                        }
628                    }
629                }
630                TimerEntry::Interval {
631                    next_trigger,
632                    interval,
633                    cancelled,
634                    ..
635                } => {
636                    if !*cancelled && now >= *next_trigger {
637                        pending_intervals.push(idx);
638                        *next_trigger = now + *interval;
639                        fired += 1;
640                    }
641                }
642            }
643        }
644
645        // Execute timeouts
646        for cb in pending_timeouts {
647            cb();
648        }
649
650        // Execute intervals
651        for idx in pending_intervals {
652            if let Some(TimerEntry::Interval {
653                callback,
654                cancelled,
655                ..
656            }) = self.entries.get_mut(idx)
657            {
658                if !*cancelled {
659                    callback();
660                }
661            }
662        }
663
664        // Purge cancelled and consumed timeouts
665        self.entries.retain(|e| match e {
666            TimerEntry::Timeout { cancelled, .. } => !*cancelled,
667            TimerEntry::Interval { cancelled, .. } => !*cancelled,
668        });
669
670        fired
671    }
672
673    fn advance_time(&mut self, delta: Duration) -> usize {
674        self.simulated_offset += delta;
675        self.tick()
676    }
677
678    fn time_until_next(&self) -> Option<Duration> {
679        let now = self.current_time();
680        self.entries
681            .iter()
682            .filter_map(|e| match e {
683                TimerEntry::Timeout {
684                    trigger_at,
685                    cancelled,
686                    ..
687                } if !*cancelled => {
688                    if *trigger_at > now {
689                        Some(*trigger_at - now)
690                    } else {
691                        Some(Duration::ZERO)
692                    }
693                }
694                TimerEntry::Interval {
695                    next_trigger,
696                    cancelled,
697                    ..
698                } if !*cancelled => {
699                    if *next_trigger > now {
700                        Some(*next_trigger - now)
701                    } else {
702                        Some(Duration::ZERO)
703                    }
704                }
705                _ => None,
706            })
707            .min()
708    }
709}
710
711thread_local! {
712    static TIMER_SCHEDULER: RefCell<TimerScheduler> = RefCell::new(TimerScheduler::new());
713}
714
715/// Schedules a callback to execute after `delay_ms` milliseconds.
716pub fn set_timeout<F: FnOnce() + 'static>(callback: F, delay_ms: u64) -> TimerId {
717    TIMER_SCHEDULER.with(|s| s.borrow_mut().add_timeout(Box::new(callback), delay_ms))
718}
719
720/// Cancels a previously scheduled timeout.
721pub fn clear_timeout(id: TimerId) {
722    TIMER_SCHEDULER.with(|s| s.borrow_mut().cancel(id));
723}
724
725/// Schedules a callback to execute repeatedly every `interval_ms` milliseconds.
726pub fn set_interval<F: FnMut() + 'static>(callback: F, interval_ms: u64) -> TimerId {
727    TIMER_SCHEDULER.with(|s| s.borrow_mut().add_interval(Box::new(callback), interval_ms))
728}
729
730/// Cancels a previously scheduled interval.
731pub fn clear_interval(id: TimerId) {
732    TIMER_SCHEDULER.with(|s| s.borrow_mut().cancel(id));
733}
734
735/// Ticks active timers and executes any due callbacks.
736pub fn tick_timers() -> usize {
737    TIMER_SCHEDULER.with(|s| s.borrow_mut().tick())
738}
739
740/// Returns the duration until the next timer is scheduled to fire, or None if no timers are active.
741pub fn time_until_next_timer() -> Option<Duration> {
742    TIMER_SCHEDULER.with(|s| s.borrow().time_until_next())
743}
744
745/// Returns true if there are any active, uncancelled timeouts or intervals.
746pub fn has_pending_timers() -> bool {
747    TIMER_SCHEDULER.with(|s| {
748        s.borrow().entries.iter().any(|e| match e {
749            TimerEntry::Timeout { cancelled, .. } | TimerEntry::Interval { cancelled, .. } => {
750                !*cancelled
751            }
752        })
753    })
754}
755
756/// Advances the simulated timer clock by a given duration and executes due timers.
757/// Essential for instant, deterministic timer testing without sleeping.
758pub fn advance_timers_by(delta: Duration) -> usize {
759    TIMER_SCHEDULER.with(|s| s.borrow_mut().advance_time(delta))
760}