Skip to main content

tabnas_jsonic_cli/
registry.rs

1/* Copyright (c) 2020-2026 Richard Rodger, Oliver Sturm, and other
2contributors, MIT License */
3
4//! The compiled-in plugin registry behind `-p` / `--plugin`. The port of
5//! `go/cli/registry.go`.
6//!
7//! The TypeScript CLI `require`s a plugin module at run time. Rust, like
8//! Go, has no way to load one by name, so a reference resolves against
9//! this registry instead. The plugins already in the crate's dependency
10//! graph are registered at first use, and a custom binary adds its own
11//! with [`register_plugin`] before calling
12//! [`run_with_plugins`](crate::run_with_plugins).
13
14use std::collections::BTreeMap;
15use std::sync::{Mutex, OnceLock};
16
17use tabnas::{Plugin, PluginError};
18
19/// The plugins a stock binary resolves, plus whatever a caller has added.
20fn registry() -> &'static Mutex<BTreeMap<String, Plugin>> {
21    static REGISTRY: OnceLock<Mutex<BTreeMap<String, Plugin>>> = OnceLock::new();
22    REGISTRY.get_or_init(|| Mutex::new(builtins()))
23}
24
25/// The plugins already present in this crate's dependency graph, so a
26/// stock binary supports them out of the box:
27///
28/// - `debug`, tracing and grammar description from `tabnas-debug`;
29/// - `jsonic`, the relaxed-JSON grammar itself, a no-op on the CLI's own
30///   instance, which already carries it;
31/// - `json`, which restricts the parser to standard JSON.
32///
33/// The other tabnas grammars (csv, toml, directive, multisource and the
34/// rest) live in crates that depend on jsonic. Requiring them here would
35/// pull the whole family into every build of the command, so they are
36/// left to custom binaries.
37fn builtins() -> BTreeMap<String, Plugin> {
38    let mut out = BTreeMap::new();
39    out.insert(
40        "debug".to_string(),
41        tabnas_debug::plugin(tabnas_debug::DebugOptions::quiet()),
42    );
43    out.insert("jsonic".to_string(), tabnas_jsonic::plugin());
44    out.insert(
45        "json".to_string(),
46        Plugin::new("json", |parser, _options| {
47            tabnas_json::json(parser).map_err(|error| PluginError(error.0))
48        }),
49    );
50    out
51}
52
53/// Make `plugin` available to `-p` / `--plugin` under `name`.
54///
55/// Register the plain name (`csv`); the lookup also accepts the
56/// `@tabnas/csv` form and a path-like reference ending in that name.
57/// Registering a name again replaces it. Call this before
58/// [`run`](crate::run), typically from a custom binary's `main`:
59///
60/// ```
61/// # fn nothing(parser: &mut tabnas::Tabnas, _options: &tabnas::Value)
62/// #     -> Result<(), tabnas::PluginError> { let _ = parser; Ok(()) }
63/// tabnas_jsonic_cli::register_plugin("noop", tabnas::Plugin::new("noop", nothing));
64/// ```
65pub fn register_plugin(name: impl Into<String>, plugin: Plugin) {
66    let mut registry = registry()
67        .lock()
68        .expect("the plugin registry is not poisoned");
69    registry.insert(name.into(), plugin);
70}
71
72/// A snapshot of every registered plugin, keyed by reference name.
73pub fn plugins() -> BTreeMap<String, Plugin> {
74    registry()
75        .lock()
76        .expect("the plugin registry is not poisoned")
77        .clone()
78}
79
80/// Resolve a `-p` reference against `registry`, with the fallbacks that
81/// stand in for the TypeScript `require(name)` then
82/// `require('@tabnas/' + name)` chain: the bare name, the base name of a
83/// path-like reference with any `.js` suffix removed, and the tail of an
84/// `@tabnas/<name>` reference.
85pub(crate) fn lookup<'a>(registry: &'a BTreeMap<String, Plugin>, name: &str) -> Option<&'a Plugin> {
86    if let Some(plugin) = registry.get(name) {
87        return Some(plugin);
88    }
89    let base = name.rsplit(['/', '\\']).next().unwrap_or(name);
90    let base = base.strip_suffix(".js").unwrap_or(base);
91    if let Some(plugin) = registry.get(base) {
92        return Some(plugin);
93    }
94    name.strip_prefix("@tabnas/")
95        .and_then(|tail| registry.get(tail))
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101
102    #[test]
103    fn the_stock_binary_carries_three_plugins() {
104        let registry = builtins();
105        for name in ["debug", "jsonic", "json"] {
106            assert!(registry.contains_key(name), "missing {name}");
107        }
108    }
109
110    #[test]
111    fn a_reference_resolves_through_the_require_fallbacks() {
112        let registry = builtins();
113        assert!(lookup(&registry, "json").is_some());
114        assert!(lookup(&registry, "@tabnas/json").is_some());
115        assert!(lookup(&registry, "../test/json.js").is_some());
116        assert!(lookup(&registry, "no-such-plugin").is_none());
117    }
118}