use std::path::{Path, PathBuf};
use crate::Value;
pub use crate::functions::{Settle, This};
pub use crate::value::FnHandle;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PathPart {
Key(String),
Index(usize),
}
pub const UNLISTED_OBJECT: &str = "an object with properties Brrrty can't list";
pub fn refused_plain_object(what: &str) -> bool {
what.starts_with(UNLISTED_OBJECT)
}
pub fn path_text(path: &[PathPart]) -> String {
const KEEP: usize = 6;
let mut out = String::from("data");
for (n, part) in path.iter().enumerate() {
if path.len() > 3 * KEEP && n >= KEEP && n < path.len() - KEEP {
if n == KEEP {
out.push_str(&format!("<{} levels>", path.len() - 2 * KEEP));
}
continue;
}
match part {
PathPart::Index(i) => out.push_str(&format!("[{i}]")),
PathPart::Key(k) => {
let plain = k
.chars()
.next()
.is_some_and(|c| c.is_ascii_alphabetic() || c == '_' || c == '$')
&& k.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$');
if plain {
out.push('.');
out.push_str(k);
} else {
out.push('[');
out.push_str(&serde_json::Value::String(k.clone()).to_string());
out.push(']');
}
}
}
}
out
}
#[derive(Debug, Clone, PartialEq)]
pub struct Decoded {
pub value: Value,
pub functions: Vec<(Vec<PathPart>, FnHandle)>,
pub refused: Vec<(Vec<PathPart>, String)>,
}
impl Decoded {
pub fn is_exact(&self) -> bool {
self.functions.is_empty() && self.refused.is_empty()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct JsError {
pub name: String,
pub message: String,
pub stack: String,
pub file: Option<PathBuf>,
pub line: Option<u32>,
pub column: Option<u32>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RuntimeFailure {
pub message: String,
pub stderr_tail: Vec<String>,
pub stopped: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub enum JsResult<T> {
Ok(T),
Thrown(JsError),
Refused(Refusal),
Failed(RuntimeFailure),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Refusal {
pub why: String,
pub impure: bool,
}
impl Refusal {
pub fn new(why: impl Into<String>) -> Refusal {
Refusal {
why: why.into(),
impure: false,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PageId(pub u64);
pub trait JsRuntime: Send {
fn set_argument(&mut self, arg: &Value) -> JsResult<()>;
fn load(&mut self, file: &Path, call: bool) -> JsResult<Decoded>;
fn call(
&mut self,
f: FnHandle,
this: This<'_>,
args: &[Value],
settle: Settle,
) -> JsResult<Decoded>;
fn page_open(
&mut self,
data: &Value,
traps: &[(String, String)],
defaults: &[String],
) -> JsResult<PageId>;
fn page_vars(&mut self, page: PageId, f: FnHandle, keys: &[String]) -> JsResult<Vec<String>>;
fn page_call(&mut self, page: PageId, f: FnHandle, set: Option<&str>) -> JsResult<Decoded>;
fn page_set(&mut self, page: PageId, key: &str, value: &Value) -> JsResult<()>;
fn page_close(&mut self, page: PageId);
fn reads(&mut self) -> JsResult<Vec<PathBuf>>;
fn loads_changed(&mut self) -> JsResult<Vec<(PathBuf, Decoded)>>;
fn begin_calls(&mut self) -> JsResult<()>;
fn verify(&mut self) -> JsResult<()>;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn paths_read_like_javascript() {
let p = [
PathPart::Key("posts".into()),
PathPart::Index(3),
PathPart::Key("a b".into()),
PathPart::Key("$ok_1".into()),
];
assert_eq!(path_text(&p), r#"data.posts[3]["a b"].$ok_1"#);
assert_eq!(path_text(&[]), "data");
}
#[test]
fn a_very_deep_path_keeps_its_ends() {
let p: Vec<PathPart> = (0..40).map(|_| PathPart::Key("c".into())).collect();
assert_eq!(path_text(&p), "data.c.c.c.c.c.c<28 levels>.c.c.c.c.c.c");
}
}