Skip to main content

brrrty_js/
runtime.rs

1//! What crosses from a JavaScript runtime (the site's own Node, run by
2//! `brrrty-node`) into a build: decoded values, function handles, errors,
3//! and the trait a build drives the runtime through.
4
5use std::path::{Path, PathBuf};
6
7use crate::Value;
8pub use crate::functions::{Settle, This};
9
10pub use crate::value::FnHandle;
11
12/// One step of a path inside a data file's value.
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum PathPart {
15    Key(String),
16    Index(usize),
17}
18
19/// What the worker's encoding says of a plain object it refused for holding
20/// properties templates could see but Brrrty can't list.
21pub const UNLISTED_OBJECT: &str = "an object with properties Brrrty can't list";
22
23/// Whether a refusal is of a plain object, which 11ty merges as data, as
24/// opposed to a value 11ty ignores as a data file's whole result.
25pub fn refused_plain_object(what: &str) -> bool {
26    what.starts_with(UNLISTED_OBJECT)
27}
28
29/// A path inside a data file's value, shown as `data.posts[3].date`.
30pub fn path_text(path: &[PathPart]) -> String {
31    // A very deep path keeps its first and last parts.
32    const KEEP: usize = 6;
33    let mut out = String::from("data");
34    for (n, part) in path.iter().enumerate() {
35        if path.len() > 3 * KEEP && n >= KEEP && n < path.len() - KEEP {
36            if n == KEEP {
37                out.push_str(&format!("<{} levels>", path.len() - 2 * KEEP));
38            }
39            continue;
40        }
41        match part {
42            PathPart::Index(i) => out.push_str(&format!("[{i}]")),
43            PathPart::Key(k) => {
44                let plain = k
45                    .chars()
46                    .next()
47                    .is_some_and(|c| c.is_ascii_alphabetic() || c == '_' || c == '$')
48                    && k.chars()
49                        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$');
50                if plain {
51                    out.push('.');
52                    out.push_str(k);
53                } else {
54                    out.push('[');
55                    out.push_str(&serde_json::Value::String(k.clone()).to_string());
56                    out.push(']');
57                }
58            }
59        }
60    }
61    out
62}
63
64/// A value from the runtime. A function is a [`Value::Function`] in
65/// `value`; a refused value is [`Value::Undefined`]. Both are listed by
66/// path.
67#[derive(Debug, Clone, PartialEq)]
68pub struct Decoded {
69    pub value: Value,
70    /// Every function value, by its path from the value's root.
71    pub functions: Vec<(Vec<PathPart>, FnHandle)>,
72    /// Every value that can't cross exactly, by path, with what it is
73    /// ("a Map object").
74    pub refused: Vec<(Vec<PathPart>, String)>,
75}
76
77impl Decoded {
78    /// True when the whole value crossed: no functions and nothing refused.
79    pub fn is_exact(&self) -> bool {
80        self.functions.is_empty() && self.refused.is_empty()
81    }
82}
83
84/// An exception thrown (or a promise rejected) by the site's code.
85#[derive(Debug, Clone, PartialEq, Eq, Default)]
86pub struct JsError {
87    /// `TypeError`, or empty when a non-Error value was thrown.
88    pub name: String,
89    pub message: String,
90    pub stack: String,
91    /// Where the error is reported: the first stack frame inside the
92    /// project and outside `node_modules`, else the first frame.
93    pub file: Option<PathBuf>,
94    pub line: Option<u32>,
95    pub column: Option<u32>,
96    /// 11ty's own refusal of a JavaScript template ("No JavaScript template
97    /// returned from ..."), not the site's code throwing.
98    pub invalid: bool,
99}
100
101/// Why the runtime can't go on at all.
102#[derive(Debug, Clone, PartialEq, Eq)]
103pub struct RuntimeFailure {
104    /// What happened, in one line (`Node exited with status 3`).
105    pub message: String,
106    /// The last lines Node wrote to stderr.
107    pub stderr_tail: Vec<String>,
108    /// Brrrty stopped the runtime itself (Ctrl-C, SIGTERM): not a failure
109    /// of the data.
110    pub stopped: bool,
111    /// The runtime asks for the build to be run again: it took a shortcut
112    /// it can't stand behind for this site, and the next runtime won't.
113    pub again: bool,
114}
115
116/// The outcome of one request: a value, the site's own exception, a value
117/// Brrrty refused to hand on, or a runtime that stopped.
118#[derive(Debug, Clone, PartialEq)]
119pub enum JsResult<T> {
120    Ok(T),
121    Thrown(JsError),
122    /// The request ran, but its outcome can't be used exactly.
123    Refused(Refusal),
124    Failed(RuntimeFailure),
125}
126
127/// Why a call's outcome can't be used exactly.
128#[derive(Debug, Clone, PartialEq, Eq)]
129pub struct Refusal {
130    /// The reason, naming the function: it reads what Brrrty can't hand
131    /// it, changes its arguments, or returns something that can't cross.
132    pub why: String,
133    /// The function gave different results for the same data: it keeps
134    /// state between calls, so any page's result from it may differ from
135    /// 11ty's.
136    pub impure: bool,
137}
138
139impl Refusal {
140    pub fn new(why: impl Into<String>) -> Refusal {
141        Refusal {
142            why: why.into(),
143            impure: false,
144        }
145    }
146}
147
148/// Runs one of Brrrty's filters for a JavaScript template's `this`:
149/// `(name, arguments)`. `Err` refuses the render, with why.
150pub type FilterCall<'a> = dyn FnMut(&str, &[Value]) -> Result<Value, String> + 'a;
151
152/// Brrrty's filters by name, shared: see [`JsRuntime::set_filters`].
153pub type Filters = std::sync::Arc<dyn Fn(&str, &[Value]) -> Result<Value, String> + Send + Sync>;
154
155/// A JavaScript template or layout (`.11ty.js`) loaded in the runtime: its
156/// instance stays there, by this id.
157#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
158pub struct TemplateId(pub u64);
159
160/// What loading a JavaScript template gave: its id, and its data (what
161/// 11ty takes as its front matter).
162#[derive(Debug, Clone, PartialEq)]
163pub struct LoadedTemplate {
164    pub id: TemplateId,
165    pub data: Decoded,
166}
167
168/// An operation the pages make while they build, for [`JsRuntime::begin`].
169#[derive(Debug, Clone, Copy)]
170pub enum Op<'a> {
171    /// [`JsRuntime::call`].
172    Call {
173        f: FnHandle,
174        this: This<'a>,
175        args: &'a [Value],
176        settle: Settle,
177    },
178    /// [`JsRuntime::page_once`].
179    PageOnce {
180        data: &'a Value,
181        traps: &'a [(String, String)],
182        defaults: &'a [String],
183        f: FnHandle,
184    },
185    /// [`JsRuntime::page_open_with_vars`]: the results are the open's and
186    /// each function's list, or the one that failed.
187    PageOpenWithVars {
188        data: &'a Value,
189        traps: &'a [(String, String)],
190        defaults: &'a [String],
191        functions: &'a [FnHandle],
192        keys: &'a [String],
193    },
194    /// [`JsRuntime::page_run`].
195    PageRun {
196        page: PageId,
197        steps: &'a [PageStep<'a>],
198    },
199    /// [`JsRuntime::render`].
200    Render {
201        template: TemplateId,
202        data: &'a Value,
203        first: Option<&'a Value>,
204        traps: &'a [(String, String)],
205    },
206}
207
208/// An operation begun (see [`JsRuntime::begin`]).
209pub enum Begun {
210    /// It is over already.
211    Done(Finished),
212    /// It was sent: wait for it without holding the runtime, then hand
213    /// what came to [`JsRuntime::finish`].
214    Sent(Box<dyn Pending>),
215}
216
217/// An operation on its way.
218pub trait Pending: Send {
219    /// Wait for it, answering the runtime's questions (a filter a
220    /// JavaScript template calls on `this`) with `filters`.
221    fn wait(self: Box<Self>, filters: &mut FilterCall<'_>) -> Waited;
222}
223
224/// What came of a [`Pending`] operation, for the runtime that sent it.
225pub struct Waited(pub Box<dyn std::any::Any + Send>);
226
227/// How an operation ended.
228pub enum Finished {
229    /// Its results, and the page it opened.
230    Results {
231        results: Vec<JsResult<Decoded>>,
232        page: Option<PageId>,
233    },
234    /// The runtime lost the values it referred to before it ran (another
235    /// page's call changed one): begin it again.
236    Again,
237}
238
239/// One step of a page's computed data, for [`JsRuntime::page_run`].
240#[derive(Debug, Clone, Copy)]
241pub enum PageStep<'a> {
242    /// Call the function with the page's data, and set its result at the
243    /// dotted key.
244    Call(FnHandle, Option<&'a str>),
245    /// Set the dotted key to the value.
246    Set(&'a str, &'a Value),
247}
248
249/// One page's data, kept in the runtime while its computed values run, as
250/// 11ty keeps one data object per page.
251#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
252pub struct PageId(pub u64);
253
254/// A JavaScript runtime that loads data files and calls the functions in
255/// them, one request at a time.
256pub trait JsRuntime: Send {
257    /// The data 11ty hands an exported function (`addGlobalData` values and
258    /// `eleventy`), sent once before any file loads.
259    fn set_argument(&mut self, arg: &Value) -> JsResult<()>;
260    /// Import `file` (absolute) as 11ty does; when `call` and the export is
261    /// a function, call it with the argument and await it.
262    fn load(&mut self, file: &Path, call: bool) -> JsResult<Decoded>;
263    /// Import the site's 11ty config file (absolute) as 11ty does and call
264    /// its export with a recording `eleventyConfig`. The value is
265    /// `{ returned, values, functions, unsupported }`.
266    fn load_config(&mut self, _file: &Path) -> JsResult<Decoded> {
267        JsResult::Refused(Refusal::new(
268            "this runtime can't load an 11ty config".to_string(),
269        ))
270    }
271    /// Call a function value from a template with `this` and `args`.
272    fn call(
273        &mut self,
274        f: FnHandle,
275        this: This<'_>,
276        args: &[Value],
277        settle: Settle,
278    ) -> JsResult<Decoded>;
279    /// Keep `data` as a page's data object. Each of `traps` (a top-level
280    /// key and why) is a key Brrrty can't supply: reading it refuses the
281    /// call. Each of `defaults` (a dotted computed key) that is undefined
282    /// is set to `""`, as 11ty's computed data proxy does.
283    fn page_open(
284        &mut self,
285        data: &Value,
286        traps: &[(String, String)],
287        defaults: &[String],
288    ) -> JsResult<PageId>;
289    /// The keys `f` reads of the page's data, as 11ty's
290    /// `ComputedDataProxy.findVarsUsed` finds them (`keys` are the page's
291    /// computed keys).
292    fn page_vars(&mut self, page: PageId, f: FnHandle, keys: &[String]) -> JsResult<Vec<String>>;
293    /// Call `f` with the page's data, as 11ty calls a computed function or
294    /// a permalink function, awaiting it; with `set`, store the result at
295    /// that dotted key of the page's data.
296    fn page_call(&mut self, page: PageId, f: FnHandle, set: Option<&str>) -> JsResult<Decoded>;
297    /// Set a dotted key of the page's data, as 11ty's `lodash.set` does.
298    fn page_set(&mut self, page: PageId, key: &str, value: &Value) -> JsResult<()>;
299    /// Forget the page's data.
300    fn page_close(&mut self, page: PageId);
301    /// Begin an operation. A runtime that can run several at once sends it
302    /// and gives back [`Begun::Sent`]: the render threads then wait for
303    /// their results at the same time, and the runtime never waits on
304    /// Brrrty between one request and the next. Any other runs it here.
305    fn begin(&mut self, op: Op<'_>, filters: &mut FilterCall<'_>) -> Begun {
306        let results = match op {
307            Op::Call {
308                f,
309                this,
310                args,
311                settle,
312            } => vec![self.call(f, this, args, settle)],
313            Op::PageOnce {
314                data,
315                traps,
316                defaults,
317                f,
318            } => vec![self.page_once(data, traps, defaults, f)],
319            Op::PageOpenWithVars {
320                data,
321                traps,
322                defaults,
323                functions,
324                keys,
325            } => {
326                return Begun::Done(
327                    match self.page_open_with_vars(data, traps, defaults, functions, keys) {
328                        JsResult::Ok((page, found)) => Finished::Results {
329                            results: std::iter::once(Value::Null)
330                                .chain(found.into_iter().map(|list| {
331                                    Value::Array(std::sync::Arc::new(
332                                        list.into_iter().map(|s| Value::String(s.into())).collect(),
333                                    ))
334                                }))
335                                .map(|value| {
336                                    JsResult::Ok(Decoded {
337                                        value,
338                                        functions: Vec::new(),
339                                        refused: Vec::new(),
340                                    })
341                                })
342                                .collect(),
343                            page: Some(page),
344                        },
345                        JsResult::Thrown(e) => Finished::Results {
346                            results: vec![JsResult::Thrown(e)],
347                            page: None,
348                        },
349                        JsResult::Refused(r) => Finished::Results {
350                            results: vec![JsResult::Refused(r)],
351                            page: None,
352                        },
353                        JsResult::Failed(f) => Finished::Results {
354                            results: vec![JsResult::Failed(f)],
355                            page: None,
356                        },
357                    },
358                );
359            }
360            Op::PageRun { page, steps } => self.page_run(page, steps),
361            Op::Render {
362                template,
363                data,
364                first,
365                traps,
366            } => vec![self.render(template, data, first, traps, filters)],
367        };
368        Begun::Done(Finished::Results {
369            results,
370            page: None,
371        })
372    }
373    /// What came of an operation [`JsRuntime::begin`] sent.
374    fn finish(&mut self, _waited: Waited) -> Finished {
375        Finished::Results {
376            results: vec![JsResult::Failed(RuntimeFailure {
377                message: "this runtime sends nothing ahead".into(),
378                stderr_tail: Vec::new(),
379                stopped: false,
380                again: false,
381            })],
382            page: None,
383        }
384    }
385    /// [`JsRuntime::page_open`], one [`JsRuntime::page_call`] of `f` with
386    /// nothing set, and [`JsRuntime::page_close`]: a permalink function
387    /// called for a page with no computed data open.
388    fn page_once(
389        &mut self,
390        data: &Value,
391        traps: &[(String, String)],
392        defaults: &[String],
393        f: FnHandle,
394    ) -> JsResult<Decoded> {
395        let page = match self.page_open(data, traps, defaults) {
396            JsResult::Ok(p) => p,
397            JsResult::Thrown(e) => return JsResult::Thrown(e),
398            JsResult::Refused(r) => return JsResult::Refused(r),
399            JsResult::Failed(f) => return JsResult::Failed(f),
400        };
401        let r = self.page_call(page, f, None);
402        self.page_close(page);
403        r
404    }
405    /// [`JsRuntime::page_open`], then [`JsRuntime::page_vars`] of each of
406    /// `functions` in order: the page, and what each reads. When one of
407    /// them gives no list, the page is closed and that is the result.
408    fn page_open_with_vars(
409        &mut self,
410        data: &Value,
411        traps: &[(String, String)],
412        defaults: &[String],
413        functions: &[FnHandle],
414        keys: &[String],
415    ) -> JsResult<(PageId, Vec<Vec<String>>)> {
416        let page = match self.page_open(data, traps, defaults) {
417            JsResult::Ok(p) => p,
418            JsResult::Thrown(e) => return JsResult::Thrown(e),
419            JsResult::Refused(r) => return JsResult::Refused(r),
420            JsResult::Failed(f) => return JsResult::Failed(f),
421        };
422        let mut found = Vec::with_capacity(functions.len());
423        for f in functions {
424            match self.page_vars(page, *f, keys) {
425                JsResult::Ok(list) => found.push(list),
426                other => {
427                    self.page_close(page);
428                    return match other {
429                        JsResult::Thrown(e) => JsResult::Thrown(e),
430                        JsResult::Refused(r) => JsResult::Refused(r),
431                        JsResult::Failed(f) => JsResult::Failed(f),
432                        JsResult::Ok(_) => unreachable!("handled above"),
433                    };
434                }
435            }
436        }
437        JsResult::Ok((page, found))
438    }
439    /// The `steps` in order, each as [`JsRuntime::page_call`] or
440    /// [`JsRuntime::page_set`] would run it. The list ends with the first
441    /// result that isn't a value (a runtime may have run the steps after
442    /// it all the same: nothing is made of them).
443    fn page_run(&mut self, page: PageId, steps: &[PageStep<'_>]) -> Vec<JsResult<Decoded>> {
444        let mut out = Vec::with_capacity(steps.len());
445        for step in steps {
446            let r = match step {
447                PageStep::Call(f, set) => self.page_call(page, *f, *set),
448                PageStep::Set(key, value) => match self.page_set(page, key, value) {
449                    JsResult::Ok(()) => JsResult::Ok(Decoded {
450                        value: Value::Undefined,
451                        functions: Vec::new(),
452                        refused: Vec::new(),
453                    }),
454                    JsResult::Thrown(e) => JsResult::Thrown(e),
455                    JsResult::Refused(r) => JsResult::Refused(r),
456                    JsResult::Failed(f) => JsResult::Failed(f),
457                },
458            };
459            let stop = !matches!(r, JsResult::Ok(_));
460            out.push(r);
461            if stop {
462                break;
463            }
464        }
465        out
466    }
467    /// Every file the site's code read or loaded so far, absolute.
468    fn reads(&mut self) -> JsResult<Vec<PathBuf>>;
469    /// The global data files are loaded: each of their values that a later
470    /// one changed (by its file), as it is now, which is what 11ty's pages
471    /// see.
472    fn loads_changed(&mut self) -> JsResult<Vec<(PathBuf, Decoded)>>;
473    /// The data files are loaded; what follows are the pages' calls.
474    /// `Refused` when a template or directory data file changed a value
475    /// another file gave, or a built-in prototype.
476    fn begin_calls(&mut self) -> JsResult<()>;
477    /// Brrrty's filters, which JavaScript calls on `this` (a template, a
478    /// computed or permalink function): `(name, arguments)`.
479    fn set_filters(&mut self, filters: Filters);
480    /// The names 11ty puts on a JavaScript template's `this` as functions
481    /// (its filters and shortcodes), in its order. Sent before any template
482    /// loads.
483    fn template_setup(&mut self, filters: &[String]) -> JsResult<()>;
484    /// Import the JavaScript template or layout `file` (absolute) as 11ty
485    /// does, make its instance, and read its `data`.
486    fn load_template(&mut self, file: &Path, layout: bool) -> JsResult<LoadedTemplate>;
487    /// Render a loaded template with the page's `data` (for a layout, with
488    /// `content`), as 11ty's JavaScript engine does: `first` is the `page`
489    /// 11ty's first render of it set as `this.page`. Each of `traps` (a
490    /// top-level key and why) is a key Brrrty can't supply. A filter the
491    /// template calls on `this` runs as `filters(name, arguments)`; `Err`
492    /// refuses the render with why.
493    fn render(
494        &mut self,
495        template: TemplateId,
496        data: &Value,
497        first: Option<&Value>,
498        traps: &[(String, String)],
499        filters: &mut FilterCall<'_>,
500    ) -> JsResult<Decoded>;
501    /// Check that no call's result depended on the calls made before it:
502    /// run the same calls again, in fresh runtimes, in other orders, and
503    /// compare every result. `Refused` (marked impure) names the first
504    /// difference.
505    fn verify(&mut self) -> JsResult<()>;
506}
507
508#[cfg(test)]
509mod tests {
510    use super::*;
511
512    #[test]
513    fn paths_read_like_javascript() {
514        let p = [
515            PathPart::Key("posts".into()),
516            PathPart::Index(3),
517            PathPart::Key("a b".into()),
518            PathPart::Key("$ok_1".into()),
519        ];
520        assert_eq!(path_text(&p), r#"data.posts[3]["a b"].$ok_1"#);
521        assert_eq!(path_text(&[]), "data");
522    }
523
524    #[test]
525    fn a_very_deep_path_keeps_its_ends() {
526        let p: Vec<PathPart> = (0..40).map(|_| PathPart::Key("c".into())).collect();
527        assert_eq!(path_text(&p), "data.c.c.c.c.c.c<28 levels>.c.c.c.c.c.c");
528    }
529}