use crate::JsValue;
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::rc::Rc;
use std::time::{Duration, Instant};
#[derive(Debug, Default, Clone, PartialEq)]
pub struct Headers {
entries: BTreeMap<String, (String, Vec<String>)>,
}
impl Headers {
pub fn new() -> Self {
Self::default()
}
pub fn set(&mut self, name: impl Into<String>, value: impl Into<String>) {
let name_str = name.into();
let lower = name_str.to_ascii_lowercase();
self.entries.insert(lower, (name_str, vec![value.into()]));
}
pub fn append(&mut self, name: impl Into<String>, value: impl Into<String>) {
let name_str = name.into();
let lower = name_str.to_ascii_lowercase();
self.entries
.entry(lower)
.or_insert_with(|| (name_str, Vec::new()))
.1
.push(value.into());
}
pub fn get(&self, name: &str) -> Option<String> {
let lower = name.to_ascii_lowercase();
self.entries.get(&lower).map(|(_, vals)| vals.join(", "))
}
pub fn get_all(&self, name: &str) -> Vec<&str> {
let lower = name.to_ascii_lowercase();
self.entries
.get(&lower)
.map(|(_, vals)| vals.iter().map(|s| s.as_str()).collect())
.unwrap_or_default()
}
pub fn has(&self, name: &str) -> bool {
self.entries.contains_key(&name.to_ascii_lowercase())
}
pub fn delete(&mut self, name: &str) {
self.entries.remove(&name.to_ascii_lowercase());
}
pub fn entries(&self) -> Vec<(String, String)> {
self.entries
.values()
.map(|(name, vals)| (name.clone(), vals.join(", ")))
.collect()
}
}
#[derive(Debug, Clone)]
pub struct RequestInit {
pub method: String,
pub headers: Headers,
pub body: Option<String>,
}
impl Default for RequestInit {
fn default() -> Self {
Self {
method: "GET".to_string(),
headers: Headers::new(),
body: None,
}
}
}
#[derive(Debug, Clone)]
pub struct Response {
pub status: u16,
pub status_text: String,
pub ok: bool,
pub headers: Headers,
body: Vec<u8>,
}
impl Response {
pub fn new(body: Vec<u8>, status: u16, headers: Headers) -> Self {
let ok = (200..=299).contains(&status);
let status_text = match status {
200 => "OK",
201 => "Created",
204 => "No Content",
400 => "Bad Request",
401 => "Unauthorized",
403 => "Forbidden",
404 => "Not Found",
500 => "Internal Server Error",
_ => "Unknown",
}
.to_string();
Self {
status,
status_text,
ok,
headers,
body,
}
}
pub async fn text(self) -> Result<String, String> {
String::from_utf8(self.body).map_err(|e| format!("Invalid UTF-8 in response body: {}", e))
}
pub async fn json(self) -> Result<JsValue, String> {
let text = self.text().await?;
crate::json::parse_json(&text)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct FetchRequest {
pub url: String,
pub method: String,
pub headers: Vec<(String, String)>,
pub body: Option<Vec<u8>>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct FetchResponse {
pub status: u16,
pub status_text: String,
pub headers: Vec<(String, String)>,
pub body: Vec<u8>,
}
impl FetchResponse {
pub fn ok(&self) -> bool {
(200..300).contains(&self.status)
}
}
pub type FetchHandler =
std::sync::Arc<dyn Fn(FetchRequest) -> Result<FetchResponse, String> + Send + Sync>;
fn global_fetch_handler_cell() -> &'static std::sync::RwLock<Option<FetchHandler>> {
static HANDLER: std::sync::OnceLock<std::sync::RwLock<Option<FetchHandler>>> =
std::sync::OnceLock::new();
HANDLER.get_or_init(|| std::sync::RwLock::new(None))
}
pub fn set_global_fetch_handler(handler: FetchHandler) {
if let Ok(mut guard) = global_fetch_handler_cell().write() {
*guard = Some(handler);
}
}
pub fn dispatch_fetch_sync(req: FetchRequest) -> Result<FetchResponse, String> {
if req.url.starts_with("mock://") {
let body = req.body.unwrap_or_else(|| b"{\"status\":\"ok\"}".to_vec());
return Ok(FetchResponse {
status: 200,
status_text: "OK".to_string(),
headers: vec![("content-type".to_string(), "application/json".to_string())],
body,
});
}
let handler = global_fetch_handler_cell()
.read()
.ok()
.and_then(|g| g.clone());
if let Some(h) = handler {
return h(req);
}
if req.url.starts_with("http://") {
return builtin_http_fetch(&req);
}
Err(format!(
"TypeError: Failed to fetch {}: no host fetch handler registered for this scheme (call strata_js::web::set_global_fetch_handler)",
req.url
))
}
fn builtin_http_fetch(req: &FetchRequest) -> Result<FetchResponse, String> {
use std::io::{Read, Write};
use std::net::TcpStream;
let stripped = req
.url
.strip_prefix("http://")
.ok_or_else(|| format!("Unsupported URL scheme: {}", req.url))?;
let (host_port, path) = match stripped.find('/') {
Some(idx) => (&stripped[..idx], &stripped[idx..]),
None => (stripped, "/"),
};
let addr = if host_port.contains(':') {
host_port.to_string()
} else {
format!("{host_port}:80")
};
let mut stream = TcpStream::connect(&addr)
.map_err(|e| format!("Failed to connect to {addr}: {e}"))?;
let _ = stream.set_read_timeout(Some(Duration::from_secs(10)));
let _ = stream.set_write_timeout(Some(Duration::from_secs(10)));
let body = req.body.as_deref().unwrap_or(&[]);
let mut raw_req = format!(
"{} {} HTTP/1.1\r\nHost: {}\r\nConnection: close\r\n",
req.method, path, host_port
);
let mut has_content_len = false;
for (k, v) in &req.headers {
if k.eq_ignore_ascii_case("content-length") {
has_content_len = true;
}
raw_req.push_str(&format!("{k}: {v}\r\n"));
}
if !body.is_empty() && !has_content_len {
raw_req.push_str(&format!("Content-Length: {}\r\n", body.len()));
}
raw_req.push_str("\r\n");
stream
.write_all(raw_req.as_bytes())
.and_then(|_| stream.write_all(body))
.and_then(|_| stream.flush())
.map_err(|e| format!("Failed to write HTTP request: {e}"))?;
let mut resp_bytes = Vec::new();
stream
.read_to_end(&mut resp_bytes)
.map_err(|e| format!("Failed to read HTTP response: {e}"))?;
let split_pos = resp_bytes
.windows(4)
.position(|w| w == b"\r\n\r\n")
.ok_or_else(|| "Malformed HTTP response: missing header terminator".to_string())?;
let header_str = String::from_utf8_lossy(&resp_bytes[..split_pos]);
let body_bytes = resp_bytes[split_pos + 4..].to_vec();
let mut lines = header_str.lines();
let status_line = lines.next().unwrap_or("HTTP/1.1 200 OK");
let mut parts = status_line.splitn(3, ' ');
let _http_ver = parts.next();
let status = parts
.next()
.and_then(|s| s.parse::<u16>().ok())
.unwrap_or(200);
let status_text = parts.next().unwrap_or("OK").to_string();
let mut headers = Vec::new();
for line in lines {
if let Some((k, v)) = line.split_once(':') {
headers.push((k.trim().to_string(), v.trim().to_string()));
}
}
Ok(FetchResponse {
status,
status_text,
headers,
body: body_bytes,
})
}
pub async fn fetch(url: &str, init: Option<RequestInit>) -> Result<Response, String> {
let init = init.unwrap_or_default();
let req = FetchRequest {
url: url.to_string(),
method: init.method,
headers: init.headers.entries(),
body: init.body.map(|s| s.into_bytes()),
};
let resp = dispatch_fetch_sync(req)
.map_err(|e| format!("TypeError: Failed to fetch {}: {}", url, e))?;
let mut headers = Headers::new();
for (k, v) in resp.headers {
headers.append(k, v);
}
let mut result_resp = Response::new(resp.body, resp.status, headers);
result_resp.status_text = resp.status_text;
Ok(result_resp)
}
#[derive(Debug, Default, Clone, PartialEq)]
pub struct URLSearchParams {
params: Vec<(String, String)>,
}
impl URLSearchParams {
pub fn new() -> Self {
Self::default()
}
pub fn parse(query: &str) -> Self {
let query = query.strip_prefix('?').unwrap_or(query);
let mut params = Vec::new();
if query.is_empty() {
return Self { params };
}
for pair in query.split('&') {
if pair.is_empty() {
continue;
}
let mut parts = pair.splitn(2, '=');
let key_enc = parts.next().unwrap_or("");
let val_enc = parts.next().unwrap_or("");
let key = decode_uri_component(key_enc);
let val = decode_uri_component(val_enc);
params.push((key, val));
}
Self { params }
}
pub fn get(&self, name: &str) -> Option<&str> {
self.params
.iter()
.find(|(k, _)| k == name)
.map(|(_, v)| v.as_str())
}
pub fn get_all(&self, name: &str) -> Vec<&str> {
self.params
.iter()
.filter(|(k, _)| k == name)
.map(|(_, v)| v.as_str())
.collect()
}
pub fn has(&self, name: &str) -> bool {
self.params.iter().any(|(k, _)| k == name)
}
pub fn append(&mut self, name: impl Into<String>, value: impl Into<String>) {
self.params.push((name.into(), value.into()));
}
pub fn set(&mut self, name: impl Into<String>, value: impl Into<String>) {
let name_str = name.into();
let value_str = value.into();
let mut replaced = false;
let mut i = 0;
while i < self.params.len() {
if self.params[i].0 == name_str {
if !replaced {
self.params[i].1 = value_str.clone();
replaced = true;
i += 1;
} else {
self.params.remove(i);
}
} else {
i += 1;
}
}
if !replaced {
self.params.push((name_str, value_str));
}
}
pub fn delete(&mut self, name: &str) {
self.params.retain(|(k, _)| k != name);
}
pub fn sort(&mut self) {
self.params.sort_by(|a, b| a.0.cmp(&b.0));
}
pub fn to_query_string(&self) -> String {
let mut out = String::new();
for (i, (k, v)) in self.params.iter().enumerate() {
if i > 0 {
out.push('&');
}
out.push_str(&encode_uri_component(k));
out.push('=');
out.push_str(&encode_uri_component(v));
}
out
}
}
fn decode_uri_component(s: &str) -> String {
let s = s.replace('+', " ");
let bytes = s.as_bytes();
let mut result = Vec::new();
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' && i + 2 < bytes.len() {
if let Ok(hex_str) = std::str::from_utf8(&bytes[i + 1..i + 3]) {
if let Ok(b) = u8::from_str_radix(hex_str, 16) {
result.push(b);
i += 3;
continue;
}
}
}
result.push(bytes[i]);
i += 1;
}
String::from_utf8_lossy(&result).into_owned()
}
fn encode_uri_component(s: &str) -> String {
let mut out = String::new();
for b in s.as_bytes() {
match *b {
b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
out.push(*b as char);
}
b' ' => out.push('+'),
other => {
out.push_str(&format!("%{:02X}", other));
}
}
}
out
}
#[derive(Debug, Clone, Default)]
pub struct Storage {
data: Rc<RefCell<BTreeMap<String, String>>>,
}
impl Storage {
pub fn new() -> Self {
Self::default()
}
pub fn length(&self) -> usize {
self.data.borrow().len()
}
pub fn key(&self, index: usize) -> Option<String> {
self.data.borrow().keys().nth(index).cloned()
}
pub fn get_item(&self, key: &str) -> Option<String> {
self.data.borrow().get(key).cloned()
}
pub fn set_item(&self, key: impl Into<String>, value: impl Into<String>) {
self.data.borrow_mut().insert(key.into(), value.into());
}
pub fn remove_item(&self, key: &str) {
self.data.borrow_mut().remove(key);
}
pub fn clear(&self) {
self.data.borrow_mut().clear();
}
}
thread_local! {
static LOCAL_STORAGE: Storage = Storage::new();
static SESSION_STORAGE: Storage = Storage::new();
}
pub fn local_storage() -> Storage {
LOCAL_STORAGE.with(|s| s.clone())
}
pub fn session_storage() -> Storage {
SESSION_STORAGE.with(|s| s.clone())
}
pub type TimerId = usize;
enum TimerEntry {
Timeout {
id: TimerId,
trigger_at: Instant,
callback: Option<Box<dyn FnOnce()>>,
cancelled: bool,
},
Interval {
id: TimerId,
interval: Duration,
next_trigger: Instant,
callback: Box<dyn FnMut()>,
cancelled: bool,
},
}
struct TimerScheduler {
next_id: usize,
entries: Vec<TimerEntry>,
simulated_offset: Duration,
}
impl TimerScheduler {
fn new() -> Self {
Self {
next_id: 1,
entries: Vec::new(),
simulated_offset: Duration::ZERO,
}
}
fn current_time(&self) -> Instant {
Instant::now() + self.simulated_offset
}
fn add_timeout(&mut self, callback: Box<dyn FnOnce()>, delay_ms: u64) -> TimerId {
let id = self.next_id;
self.next_id += 1;
let trigger_at = self.current_time() + Duration::from_millis(delay_ms);
self.entries.push(TimerEntry::Timeout {
id,
trigger_at,
callback: Some(callback),
cancelled: false,
});
id
}
fn add_interval(&mut self, callback: Box<dyn FnMut()>, interval_ms: u64) -> TimerId {
let id = self.next_id;
self.next_id += 1;
let interval = Duration::from_millis(interval_ms);
let next_trigger = self.current_time() + interval;
self.entries.push(TimerEntry::Interval {
id,
interval,
next_trigger,
callback,
cancelled: false,
});
id
}
fn cancel(&mut self, id: TimerId) {
for entry in &mut self.entries {
match entry {
TimerEntry::Timeout {
id: entry_id,
cancelled,
..
}
| TimerEntry::Interval {
id: entry_id,
cancelled,
..
} => {
if *entry_id == id {
*cancelled = true;
}
}
}
}
}
fn tick(&mut self) -> usize {
let now = self.current_time();
let mut fired = 0;
let mut pending_timeouts = Vec::new();
let mut pending_intervals = Vec::new();
for (idx, entry) in self.entries.iter_mut().enumerate() {
match entry {
TimerEntry::Timeout {
trigger_at,
cancelled,
callback,
..
} => {
if !*cancelled && now >= *trigger_at {
if let Some(cb) = callback.take() {
pending_timeouts.push(cb);
*cancelled = true;
fired += 1;
}
}
}
TimerEntry::Interval {
next_trigger,
interval,
cancelled,
..
} => {
if !*cancelled && now >= *next_trigger {
pending_intervals.push(idx);
*next_trigger = now + *interval;
fired += 1;
}
}
}
}
for cb in pending_timeouts {
cb();
}
for idx in pending_intervals {
if let Some(TimerEntry::Interval {
callback,
cancelled,
..
}) = self.entries.get_mut(idx)
{
if !*cancelled {
callback();
}
}
}
self.entries.retain(|e| match e {
TimerEntry::Timeout { cancelled, .. } => !*cancelled,
TimerEntry::Interval { cancelled, .. } => !*cancelled,
});
fired
}
fn advance_time(&mut self, delta: Duration) -> usize {
self.simulated_offset += delta;
self.tick()
}
fn time_until_next(&self) -> Option<Duration> {
let now = self.current_time();
self.entries
.iter()
.filter_map(|e| match e {
TimerEntry::Timeout {
trigger_at,
cancelled,
..
} if !*cancelled => {
if *trigger_at > now {
Some(*trigger_at - now)
} else {
Some(Duration::ZERO)
}
}
TimerEntry::Interval {
next_trigger,
cancelled,
..
} if !*cancelled => {
if *next_trigger > now {
Some(*next_trigger - now)
} else {
Some(Duration::ZERO)
}
}
_ => None,
})
.min()
}
}
thread_local! {
static TIMER_SCHEDULER: RefCell<TimerScheduler> = RefCell::new(TimerScheduler::new());
}
pub fn set_timeout<F: FnOnce() + 'static>(callback: F, delay_ms: u64) -> TimerId {
TIMER_SCHEDULER.with(|s| s.borrow_mut().add_timeout(Box::new(callback), delay_ms))
}
pub fn clear_timeout(id: TimerId) {
TIMER_SCHEDULER.with(|s| s.borrow_mut().cancel(id));
}
pub fn set_interval<F: FnMut() + 'static>(callback: F, interval_ms: u64) -> TimerId {
TIMER_SCHEDULER.with(|s| s.borrow_mut().add_interval(Box::new(callback), interval_ms))
}
pub fn clear_interval(id: TimerId) {
TIMER_SCHEDULER.with(|s| s.borrow_mut().cancel(id));
}
pub fn tick_timers() -> usize {
TIMER_SCHEDULER.with(|s| s.borrow_mut().tick())
}
pub fn time_until_next_timer() -> Option<Duration> {
TIMER_SCHEDULER.with(|s| s.borrow().time_until_next())
}
pub fn has_pending_timers() -> bool {
TIMER_SCHEDULER.with(|s| {
s.borrow().entries.iter().any(|e| match e {
TimerEntry::Timeout { cancelled, .. } | TimerEntry::Interval { cancelled, .. } => {
!*cancelled
}
})
})
}
pub fn advance_timers_by(delta: Duration) -> usize {
TIMER_SCHEDULER.with(|s| s.borrow_mut().advance_time(delta))
}