use std::collections::BTreeMap;
use std::sync::{Mutex, OnceLock};
use tabnas::{Plugin, PluginError};
fn registry() -> &'static Mutex<BTreeMap<String, Plugin>> {
static REGISTRY: OnceLock<Mutex<BTreeMap<String, Plugin>>> = OnceLock::new();
REGISTRY.get_or_init(|| Mutex::new(builtins()))
}
fn builtins() -> BTreeMap<String, Plugin> {
let mut out = BTreeMap::new();
out.insert(
"debug".to_string(),
tabnas_debug::plugin(tabnas_debug::DebugOptions::quiet()),
);
out.insert("jsonic".to_string(), tabnas_jsonic::plugin());
out.insert(
"json".to_string(),
Plugin::new("json", |parser, _options| {
tabnas_json::json(parser).map_err(|error| PluginError(error.0))
}),
);
out
}
pub fn register_plugin(name: impl Into<String>, plugin: Plugin) {
let mut registry = registry()
.lock()
.expect("the plugin registry is not poisoned");
registry.insert(name.into(), plugin);
}
pub fn plugins() -> BTreeMap<String, Plugin> {
registry()
.lock()
.expect("the plugin registry is not poisoned")
.clone()
}
pub(crate) fn lookup<'a>(registry: &'a BTreeMap<String, Plugin>, name: &str) -> Option<&'a Plugin> {
if let Some(plugin) = registry.get(name) {
return Some(plugin);
}
let base = name.rsplit(['/', '\\']).next().unwrap_or(name);
let base = base.strip_suffix(".js").unwrap_or(base);
if let Some(plugin) = registry.get(base) {
return Some(plugin);
}
name.strip_prefix("@tabnas/")
.and_then(|tail| registry.get(tail))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_stock_binary_carries_three_plugins() {
let registry = builtins();
for name in ["debug", "jsonic", "json"] {
assert!(registry.contains_key(name), "missing {name}");
}
}
#[test]
fn a_reference_resolves_through_the_require_fallbacks() {
let registry = builtins();
assert!(lookup(®istry, "json").is_some());
assert!(lookup(®istry, "@tabnas/json").is_some());
assert!(lookup(®istry, "../test/json.js").is_some());
assert!(lookup(®istry, "no-such-plugin").is_none());
}
}