base/interface/
host_js.rs1use std::future::Future;
9use std::path::PathBuf;
10use std::sync::Arc;
11
12use futures::future::BoxFuture;
13use serde_json::Value;
14use tokio_util::sync::CancellationToken;
15
16pub use crate::command::PackageSource;
17
18use crate::command::HostLibrary;
19
20pub trait HostFn: Send + Sync {
24 fn call(
25 &self,
26 cx: HostCallContext,
27 input: Value,
28 ) -> BoxFuture<'static, Result<Value, HostJsError>>;
29}
30
31impl<F, Fut> HostFn for F
32where
33 F: Fn(HostCallContext, Value) -> Fut + Send + Sync,
34 Fut: Future<Output = Result<Value, HostJsError>> + Send + 'static,
35{
36 fn call(
37 &self,
38 cx: HostCallContext,
39 input: Value,
40 ) -> BoxFuture<'static, Result<Value, HostJsError>> {
41 Box::pin(self(cx, input))
42 }
43}
44
45#[derive(Debug, Clone)]
48pub struct HostCallContext {
49 pub plugin: String,
52 pub plugin_version: String,
53 pub source: PackageSource,
54 pub entry: String,
56 pub session_id: Option<String>,
57 pub project_root: Option<PathBuf>,
58 pub cwd: PathBuf,
59 pub via: String,
62 pub agent_depth: u32,
63 pub cancel: CancellationToken,
66}
67
68#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
70#[error("{code}: {message}")]
71pub struct HostJsError {
72 pub code: String,
73 pub message: String,
74}
75
76impl HostJsError {
77 pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
78 Self {
79 code: code.into(),
80 message: message.into(),
81 }
82 }
83}
84
85#[derive(Clone)]
86pub struct HostJsLib {
87 namespace: String,
88 functions: Vec<(String, Arc<dyn HostFn>)>,
89 prelude: Option<String>,
90 description: Option<String>,
91}
92
93impl std::fmt::Debug for HostJsLib {
94 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
95 f.debug_struct("HostJsLib")
96 .field("namespace", &self.namespace)
97 .field("functions", &self.paths().collect::<Vec<_>>())
98 .field("prelude", &self.prelude.as_ref().map(String::len))
99 .field("description", &self.description)
100 .finish()
101 }
102}
103
104impl HostJsLib {
105 pub fn new(namespace: &str) -> Self {
106 Self {
107 namespace: namespace.to_string(),
108 functions: Vec::new(),
109 prelude: None,
110 description: None,
111 }
112 }
113
114 pub fn function<F, Fut>(mut self, path: &str, f: F) -> Self
117 where
118 F: Fn(HostCallContext, Value) -> Fut + Send + Sync + 'static,
119 Fut: Future<Output = Result<Value, HostJsError>> + Send + 'static,
120 {
121 self.functions.push((path.to_string(), Arc::new(f)));
122 self
123 }
124
125 pub fn prelude(mut self, js: impl Into<String>) -> Self {
128 self.prelude = Some(js.into());
129 self
130 }
131
132 pub fn description(mut self, text: impl Into<String>) -> Self {
134 self.description = Some(text.into());
135 self
136 }
137
138 pub fn namespace(&self) -> &str {
139 &self.namespace
140 }
141
142 pub fn paths(&self) -> impl Iterator<Item = &str> {
143 self.functions.iter().map(|(path, _)| path.as_str())
144 }
145
146 pub fn function_at(&self, path: &str) -> Option<&Arc<dyn HostFn>> {
147 self.functions
148 .iter()
149 .find(|(p, _)| p == path)
150 .map(|(_, f)| f)
151 }
152
153 pub fn prelude_source(&self) -> Option<&str> {
154 self.prelude.as_deref()
155 }
156
157 pub fn library(&self) -> HostLibrary {
159 HostLibrary {
160 name: self.namespace.clone(),
161 description: self.description.clone(),
162 }
163 }
164}
165
166#[cfg(test)]
167mod tests {
168 use super::*;
169
170 #[tokio::test]
171 async fn a_closure_is_a_host_function() {
172 let lib = HostJsLib::new("codix")
173 .function("echo", |cx: HostCallContext, input| async move {
174 Ok(serde_json::json!({ "via": cx.via, "input": input }))
175 })
176 .description("Codix flows");
177 let cx = HostCallContext {
178 plugin: "p".into(),
179 plugin_version: "1".into(),
180 source: PackageSource::Installed,
181 entry: "cmd".into(),
182 session_id: None,
183 project_root: None,
184 cwd: PathBuf::from("/"),
185 via: "user".into(),
186 agent_depth: 0,
187 cancel: CancellationToken::new(),
188 };
189 let out = lib.function_at("echo").unwrap().call(cx, 1.into()).await;
190 assert_eq!(out, Ok(serde_json::json!({ "via": "user", "input": 1 })));
191 assert_eq!(
192 lib.library(),
193 HostLibrary {
194 name: "codix".into(),
195 description: Some("Codix flows".into())
196 }
197 );
198 }
199}