use std::path::{Path, PathBuf};
use brrrty_config::DirOptions;
use brrrty_core::{ConfigOptions, PassthroughEntry, Problem, codes};
use brrrty_js::Value;
use brrrty_js::runtime::{JsResult, JsRuntime};
const CONFIG_FILES: &[&str] = &[
".eleventy.js",
"eleventy.config.js",
"eleventy.config.mjs",
"eleventy.config.cjs",
];
fn get<'a>(v: &'a Value, key: &str) -> Option<&'a Value> {
match v {
Value::Object(o) => o.get(key),
_ => None,
}
}
fn strings(v: Option<&Value>) -> Vec<String> {
match v {
Some(Value::Array(a)) => a
.iter()
.filter_map(|x| match x {
Value::String(s) => Some(s.to_string()),
_ => None,
})
.collect(),
Some(Value::String(s)) => s
.split(',')
.map(|p| p.trim().to_string())
.filter(|p| !p.is_empty())
.collect(),
_ => Vec::new(),
}
}
fn text(v: Option<&Value>) -> Option<String> {
match v {
Some(Value::String(s)) => Some(s.to_string()),
_ => None,
}
}
fn problem(message: String, file: Option<&Path>, line: Option<u32>) -> Problem {
let mut p = Problem::error(codes::CONFIG_ERROR, message);
if let Some(f) = file {
p = p.with_path(f);
}
if let Some(l) = line {
p = p.at(l as usize, 1);
}
p
}
pub fn apply(
root: &Path,
node: &brrrty_node::NodeInfo,
config: &mut ConfigOptions,
dir: &mut DirOptions,
run_mode: brrrty_node::RunMode,
order_check: bool,
) -> Result<(), Vec<Problem>> {
let Some(file) = CONFIG_FILES
.iter()
.map(|f| root.join(f))
.find(|f| f.is_file())
else {
config.problems.push(
Problem::warning(
codes::CONFIG_UNSUPPORTED,
"config.set_js_config(\"node\") is on, but there is no 11ty config file here",
)
.with_help(format!("looked for {}", CONFIG_FILES.join(", "))),
);
return Ok(());
};
let shown = file.strip_prefix(root).unwrap_or(&file).to_path_buf();
let mut worker =
brrrty_node::Worker::start_with(node, root, run_mode, order_check).map_err(|e| {
vec![problem(
format!(
"Brrrty could not start Node to load {}: {e}",
shown.display()
),
None,
None,
)]
})?;
let loaded = match worker.load_config(&file) {
JsResult::Ok(d) => d,
JsResult::Thrown(e) => {
return Err(vec![problem(
format!("{} threw: {}", shown.display(), e.message),
e.file.as_deref().map(|f| f.strip_prefix(root).unwrap_or(f)),
e.line,
)]);
}
JsResult::Refused(r) => {
return Err(vec![problem(
format!("{} could not be loaded: {}", shown.display(), r.why),
Some(&shown),
None,
)]);
}
JsResult::Failed(f) => {
return Err(vec![problem(
format!(
"Node stopped while loading {}: {}",
shown.display(),
f.message
),
Some(&shown),
None,
)]);
}
};
let v = &loaded.value;
config.js_config_file = Some(shown.display().to_string());
add_filters(v, &shown, root, run_mode, config);
let values = get(v, "values");
let val = |k: &str| values.and_then(|x| get(x, k));
let mut passthrough = Vec::new();
if let Some(Value::Array(a)) = val("passthroughCopy") {
for c in a.iter() {
let Some(from) = text(get(c, "input")) else {
continue;
};
if matches!(get(c, "options"), Some(Value::Object(o)) if !o.is_empty()) {
config.problems.push(
Problem::warning(
codes::CONFIG_UNSUPPORTED,
format!(
"addPassthroughCopy(\"{from}\") options (like `filter` or `expand`) are not supported by Brrrty yet, so they were ignored"
),
)
.with_path(shown.clone()),
);
}
match get(c, "output") {
Some(Value::String(to)) => passthrough.push(PassthroughEntry {
from,
to: Some(to.to_string()),
}),
Some(Value::Bool(false)) => {}
_ => passthrough.push(PassthroughEntry { from, to: None }),
}
}
}
passthrough.append(&mut config.passthrough);
config.passthrough = passthrough;
let mut ignores = strings(val("ignores"));
ignores.retain(|i| !config.ignores.contains(i));
ignores.append(&mut config.ignores);
config.ignores = ignores;
for name in strings(val("bundles")) {
if !config.js_bundles.contains(&name) {
config.js_bundles.push(name);
}
}
for name in strings(val("nativePlugins")) {
match name.as_str() {
"idattribute" => config.id_attribute = true,
"inputpathtourl" => config.input_path_to_url = true,
"htmlbase" => config.html_base = true,
"render" => config.render_plugin = true,
_ => {}
}
}
if let Some(Value::Array(a)) = val("nativePackages") {
for p in a.iter() {
let name = text(get(p, "name")).unwrap_or_default();
let opts = get(p, "options").cloned().unwrap_or(Value::Undefined);
let opts = if matches!(opts, Value::Undefined | Value::Null) {
Value::Object(Default::default())
} else {
opts
};
let bad = |why: String| vec![problem(why, Some(&shown), None)];
match (name.as_str(), text(get(p, "kind")).as_deref()) {
("rss", Some("feed")) => {
let feed = brrrty_config::feed_js(&opts).map_err(bad)?;
if config.feeds.iter().any(|f| f.input_path == feed.input_path) {
return Err(bad(format!(
"Virtual template conflict: you can\u{2019}t add multiple virtual templates that have the same inputPath: {} (11ty's error; give one feed another `inputPath`, or another `metadata.title` or `type`)",
feed.input_path
)));
}
config.feeds.push(feed);
}
("rss", _) => config.rss_filters = true,
("syntaxhighlight", _) => {
if config.syntax_highlight.is_some() {
return Err(bad("addPlugin(syntaxhighlight, ...) is called twice; Brrrty takes it once, with all its options".to_string()));
}
config.syntax_highlight =
Some(brrrty_config::syntax_highlight_js(&opts).map_err(bad)?);
}
_ => {}
}
}
}
if let Some(Value::Array(a)) = val("untestedPlugins") {
for p in a.iter() {
let name = text(get(p, "name")).unwrap_or_default();
let version = text(get(p, "version")).unwrap_or_default();
let tested = text(get(p, "tested")).unwrap_or_default();
let option = text(get(p, "option"));
let filters = text(get(p, "kind")).as_deref() == Some("filters");
let message = if let Some(o) = &option {
format!(
"{name}: the option `{o}` is not one Brrrty's own version of the plugin reads, so the plugin runs as JavaScript instead"
)
} else if matches!(get(p, "twice"), Some(Value::Bool(true))) {
format!(
"{name} is added more than once, so the later call runs the plugin as JavaScript instead"
)
} else {
format!(
"{name} is at version {version}, and Brrrty's own version of it is for {tested}, so the plugin runs as JavaScript instead"
)
};
let mut problem =
Problem::warning(codes::CONFIG_UNSUPPORTED, message).with_path(shown.clone());
if !filters {
problem = problem.with_help("its virtual templates and Markdown highlighter are not supported when it runs as JS, so pages that need them are refused");
}
config.problems.push(problem);
}
}
if let Some(Value::Object(o)) = val("globalData") {
for (k, x) in o.iter() {
config
.global_data
.entry(k.clone())
.or_insert_with(|| x.clone());
}
}
let fmt_err = |m: String| vec![problem(m, Some(&shown), None)];
let js_returned = get(v, "returned");
let normalize = |what: &str, v: &Value| -> Result<Vec<String>, Vec<Problem>> {
brrrty_config::normalize_template_formats(what, strings(Some(v))).map_err(fmt_err)
};
if !config.template_formats_set {
let set = match val("templateFormats") {
Some(f) => Some(normalize("`setTemplateFormats`", f)?),
None => match js_returned.and_then(|r| get(r, "templateFormats")) {
Some(f) => Some(normalize("`templateFormats`", f)?),
None => None,
},
};
let mut added = Vec::new();
if let Some(Value::Array(a)) = val("templateFormatsAdded") {
for x in a.iter() {
added.extend(normalize("`addTemplateFormats`", x)?);
}
}
added.extend(config.added_template_formats.iter().cloned());
let formats = match set {
Some(f) => Some(f),
None if !added.is_empty() => Some(
["liquid", "md", "njk", "html", "11ty.js"]
.map(String::from)
.to_vec(),
),
None => None,
}
.map(|mut f| {
for a in added {
if !f.contains(&a) {
f.push(a);
}
}
f
});
config.template_formats = formats.filter(|f| !f.is_empty());
}
if config.template_engines == brrrty_core::TemplateEngines::default() {
for (key, slot) in [("markdownTemplateEngine", 0), ("htmlTemplateEngine", 1)] {
let Some(e) = js_returned.and_then(|r| get(r, key)) else {
continue;
};
let lang = match e {
Value::Bool(false) => None,
Value::String(n) => match brrrty_core::TemplateLanguage::from_name(n) {
Some(l) => Some(l),
None => {
return Err(vec![problem(
format!(
"`{key}` is `{n}`, which Brrrty doesn't run there (use \"liquid\", \"njk\" or false)"
),
Some(&shown),
None,
)]);
}
},
_ => {
return Err(vec![problem(
format!("`{key}` should be a template language, like \"njk\", or false"),
Some(&shown),
None,
)]);
}
};
if slot == 0 {
config.template_engines.markdown = lang;
} else {
config.template_engines.html = lang;
}
}
}
if let Some(Value::Object(o)) = js_returned {
for (k, _) in o.iter() {
if !matches!(
k.as_str(),
"dir" | "templateFormats" | "markdownTemplateEngine" | "htmlTemplateEngine"
) {
let why = if k == "dataTemplateEngine" {
"11ty 3 doesn't read it"
} else {
"Brrrty doesn't support it yet"
};
config.problems.push(
Problem::warning(
codes::CONFIG_UNSUPPORTED,
format!("the config returns `{k}`, which was skipped: {why}"),
)
.with_path(shown.clone()),
);
}
}
}
let rhai = dir.clone();
for source in [val("dir"), get(v, "returned").and_then(|r| get(r, "dir"))] {
let Some(source) = source else { continue };
let theirs = DirOptions {
input: text(get(source, "input")),
output: text(get(source, "output")),
includes: text(get(source, "includes")),
data: text(get(source, "data")),
layouts: text(get(source, "layouts")),
};
if rhai.input.is_none() && theirs.input.is_some() {
dir.input = theirs.input;
}
if rhai.output.is_none() && theirs.output.is_some() {
dir.output = theirs.output;
}
if rhai.includes.is_none() && theirs.includes.is_some() {
dir.includes = theirs.includes;
}
if rhai.data.is_none() && theirs.data.is_some() {
dir.data = theirs.data;
}
if rhai.layouts.is_none() && theirs.layouts.is_some() {
dir.layouts = theirs.layouts;
}
}
config.includes = dir.includes.clone();
config.layouts = dir.layouts.clone();
config.data_folder = dir.data.clone();
let mut blocking: Vec<String> = Vec::new();
if let Some(Value::Array(un)) = get(v, "unsupported") {
for u in un.iter() {
let method = text(get(u, "method")).unwrap_or_default();
let at = text(get(u, "at")).unwrap_or_default();
if crate::init::js_blocks(&method) {
blocking.push(format!("{at}: eleventyConfig.{method}"));
}
let mut p = Problem::warning(
codes::CONFIG_UNSUPPORTED,
format!("{at}: eleventyConfig.{method} is not supported by Brrrty yet, so it was skipped"),
)
.with_help("pages that need it may differ from 11ty's, or refuse");
let (file, line) = match at.rsplit_once(':') {
Some((f, l)) => (Some(f.to_string()), l.parse::<usize>().ok()),
None => (None, None),
};
config.js_unsupported.push(brrrty_core::JsUnsupported {
method: method.trim_end_matches(" = ").to_string(),
file,
line,
});
if let Some((f, l)) = at.rsplit_once(':') {
p = p.with_path(PathBuf::from(f));
if let Ok(l) = l.parse::<usize>() {
p = p.at(l, 1);
}
}
config.problems.push(p);
}
}
if !blocking.is_empty() && config.unported.is_none() {
config.unported = Some(
Problem::error(
codes::CONFIG_TODO,
format!(
"the 11ty config uses what Brrrty can't run, and it changes what 11ty writes: {}",
blocking.join(", ")
),
)
.with_help("remove it, or port it by hand; until then every page is refused"),
);
}
config
.problems
.retain(|p| p.code != brrrty_core::codes::CONFIG_UNVERIFIED);
config.js_started = Some(brrrty_core::StartedJs(std::sync::Arc::new(
std::sync::Mutex::new(Some(Box::new(worker))),
)));
Ok(())
}
fn filter_this(eleventy: &Value) -> Value {
let mut o = indexmap::IndexMap::new();
if let Some((page, _)) = brrrty_js::functions::own_page() {
o.insert("page".to_string(), page);
}
o.insert("eleventy".to_string(), eleventy.clone());
Value::Object(std::sync::Arc::new(o))
}
const NUNJUCKS_THIS: &[(&str, &str)] = &[
("ctx", "Nunjucks's render context"),
("env", "the Nunjucks environment"),
];
const LIQUID_THIS: &[(&str, &str)] = &[
("context", "LiquidJS's variable scope"),
("liquid", "the LiquidJS engine"),
];
fn add_filters(
v: &Value,
shown: &Path,
root: &Path,
run_mode: brrrty_node::RunMode,
config: &mut ConfigOptions,
) {
use brrrty_core::{FilterEngine, JsConfigFilter, JsConfigShortcode, JsLiquidShortcode};
use brrrty_js::functions::{Settle, This};
let Some(Value::Array(fns)) = get(v, "functions") else {
return;
};
let eleventy = Value::from_json(&serde_json::json!({
"version": "3.1.8",
"generator": "Eleventy v3.1.8",
"env": { "source": "cli", "runMode": run_mode.as_str(), "root": root.display().to_string() },
}));
let mut transforms: Vec<(String, brrrty_core::JsConfigTransform)> = Vec::new();
let mut posthtml: Vec<(brrrty_core::JsPosthtmlPlugin, Value, Value)> = Vec::new();
let mut posthtml_runner = None;
let mut preprocessors: Vec<(String, Vec<String>, Value)> = Vec::new();
let mut preprocess_runner = None;
for f in fns.iter() {
match text(get(f, "kind")).as_deref() {
Some("preprocessor") => {
if let (Some(name), Some(Value::Function(h))) = (text(get(f, "name")), get(f, "fn"))
{
let extensions = match get(f, "extensions") {
Some(Value::Array(a)) => a.iter().filter_map(|e| text(Some(e))).collect(),
_ => Vec::new(),
};
let entry = (name.clone(), extensions, Value::Function(*h));
match preprocessors.iter_mut().find(|(n, _, _)| *n == name) {
Some(slot) => *slot = entry,
None => preprocessors.push(entry),
}
}
continue;
}
Some("preprocessorRunner") => {
if let Some(Value::Function(h)) = get(f, "fn") {
preprocess_runner = Some(*h);
}
continue;
}
Some("posthtml") => {
if let Some(Value::Function(h)) = get(f, "fn") {
let number = |k: &str| match get(f, k) {
Some(Value::Number(n)) => *n,
_ => 0.0,
};
let extensions = text(get(f, "extensions"))
.unwrap_or_default()
.split(',')
.map(str::to_string)
.collect();
posthtml.push((
brrrty_core::JsPosthtmlPlugin {
extensions,
priority: number("priority"),
seq: number("seq") as u64,
},
Value::Function(*h),
get(f, "options").cloned().unwrap_or(Value::Undefined),
));
}
continue;
}
Some("posthtmlRunner") => {
if let Some(Value::Function(h)) = get(f, "fn") {
posthtml_runner = Some(*h);
}
continue;
}
_ => {}
}
if text(get(f, "kind")).as_deref() == Some("transform") {
if let (Some(name), Some(Value::Function(h))) = (text(get(f, "name")), get(f, "fn")) {
let stats =
std::sync::Arc::new(brrrty_core::JsFunctionStats::new("transform", &name));
config.js_functions.push(stats.clone());
let t = transform(*h, &name, shown, stats);
match transforms.iter_mut().find(|(n, _)| *n == name) {
Some(slot) => slot.1 = t,
None => transforms.push((name, t)),
}
}
continue;
}
let (what, shortcode, kind) = match text(get(f, "kind")).as_deref() {
Some("filter") => ("filter", None, "filter"),
Some("shortcode") => ("shortcode", Some(false), "shortcode"),
Some("pairedShortcode") => ("shortcode", Some(true), "pairedShortcode"),
_ => continue,
};
let (Some(name), Some(Value::Function(h))) = (text(get(f, "name")), get(f, "fn")) else {
continue;
};
let engine = match text(get(f, "engine")).as_deref() {
Some("all") => FilterEngine::All,
Some("nunjucks") => FilterEngine::Nunjucks,
Some("liquid") => FilterEngine::Liquid,
_ => continue,
};
let is_async = matches!(get(f, "async"), Some(Value::Bool(true)));
let stats = std::sync::Arc::new(brrrty_core::JsFunctionStats::new(kind, &name));
config.js_functions.push(stats.clone());
let make = |settle: Settle,
guard: &'static [(&'static str, &'static str)]|
-> brrrty_liquid::ShortcodeFn {
let (h, n, eleventy, shown, what, stats) = (
*h,
name.clone(),
eleventy.clone(),
shown.display().to_string(),
what,
stats.clone(),
);
std::sync::Arc::new(move |all: &[Value], _| {
let Some(caller) = brrrty_js::functions::installed() else {
return Err(format!(
"{}the {what} `{n}` (from {shown}) can't run: Node isn't running",
brrrty_js::REFUSAL_PREFIX
));
};
let this = filter_this(&eleventy);
let started = std::time::Instant::now();
let result = caller.call(h, This::Guarded(&this, guard), all, settle);
stats.record(started.elapsed());
result.map_err(|why| {
format!(
"{}the {what} `{n}` (from {shown}) failed: {why}",
brrrty_js::REFUSAL_PREFIX
)
})
})
};
let njk = if is_async {
Settle::Await
} else {
Settle::AsIs
};
let as_filter = |run: brrrty_liquid::ShortcodeFn| -> brrrty_liquid::ArgsFilterFn {
std::sync::Arc::new(move |input, args, ctx| {
let mut all = Vec::with_capacity(args.len() + 1);
all.push(input.clone());
all.extend_from_slice(args);
run(&all, ctx)
})
};
if engine != FilterEngine::Liquid {
let run = make(njk, NUNJUCKS_THIS);
match shortcode {
Some(paired) => config.js_shortcodes.push(JsConfigShortcode {
name: name.clone(),
paired,
engine: FilterEngine::Nunjucks,
run: as_filter(run),
}),
None => config.js_filters.push(JsConfigFilter {
name: name.clone(),
engine: FilterEngine::Nunjucks,
universal: false,
handle: h.0,
run: as_filter(run),
}),
}
}
if engine != FilterEngine::Nunjucks {
let run = make(Settle::Await, LIQUID_THIS);
match shortcode {
Some(paired) => {
config
.js_liquid_shortcodes
.push(JsLiquidShortcode { name, paired, run })
}
None => config.js_filters.push(JsConfigFilter {
name,
engine: FilterEngine::Liquid,
universal: engine == FilterEngine::All,
handle: h.0,
run: as_filter(run),
}),
}
}
}
let index = |n: &str| {
n.parse::<u32>()
.ok()
.filter(|i| i.to_string() == n && *i != u32::MAX)
};
if let Some(runner) = posthtml_runner.filter(|_| !posthtml.is_empty()) {
let id_attribute_seq = match get(v, "values").and_then(|x| get(x, "nativeOrder")) {
Some(Value::Array(order)) => order
.iter()
.find(|o| text(get(o, "name")).as_deref() == Some("idattribute"))
.and_then(|o| match get(o, "seq") {
Some(Value::Number(n)) => Some(*n as u64),
_ => None,
}),
_ => None,
};
let stats = std::sync::Arc::new(brrrty_core::JsFunctionStats::new("posthtml", "posthtml"));
config.js_functions.push(stats.clone());
let run = posthtml_run(runner, shown, posthtml.clone(), stats);
config.js_posthtml = Some(brrrty_core::JsPosthtml {
plugins: posthtml.into_iter().map(|(p, _, _)| p).collect(),
id_attribute_seq,
run,
});
}
if let Some(runner) = preprocess_runner.filter(|_| !preprocessors.is_empty()) {
preprocessors.sort_by_key(|(n, _, _)| index(n).map_or((1, 0), |i| (0, i)));
let stats = std::sync::Arc::new(brrrty_core::JsFunctionStats::new(
"preprocessor",
"preprocessors",
));
config.js_functions.push(stats.clone());
let entries = preprocessors
.iter()
.map(|(n, e, _)| (n.clone(), e.clone()))
.collect();
let fns = preprocessors.into_iter().map(|(n, _, f)| (n, f)).collect();
let run = preprocess_run(runner, shown, fns, stats);
config.js_preprocessors = Some(brrrty_core::JsPreprocessors { entries, run });
}
transforms.sort_by_key(|(n, _)| index(n).map_or((1, 0), |i| (0, i)));
config
.js_transforms
.extend(transforms.into_iter().map(|(_, t)| t));
}
fn transform(
h: brrrty_js::FnHandle,
name: &str,
shown: &Path,
stats: std::sync::Arc<brrrty_core::JsFunctionStats>,
) -> brrrty_core::JsConfigTransform {
use brrrty_js::functions::{Settle, This};
let (name, shown) = (name.to_string(), shown.display().to_string());
let n = name.clone();
let run = std::sync::Arc::new(move |content: &str, page: &Value| {
let fail = |why: String| {
format!(
"{}the transform `{n}` (from {shown}) failed: {why}",
brrrty_js::REFUSAL_PREFIX
)
};
let Some(caller) = brrrty_js::functions::installed() else {
return Err(fail("Node isn't running".to_string()));
};
let field = |k: &str| get(page, k).cloned().unwrap_or(Value::Undefined);
let (input, output, url) = (field("inputPath"), field("outputPath"), field("url"));
let mut o = indexmap::IndexMap::new();
o.insert("inputPath".to_string(), input);
o.insert("outputPath".to_string(), output.clone());
o.insert("url".to_string(), url);
o.insert("page".to_string(), page.clone());
o.insert("baseHref".to_string(), Value::Undefined);
let this = Value::Object(std::sync::Arc::new(o));
let args = [Value::String(content.into()), output];
let started = std::time::Instant::now();
let called = caller.call(h, This::Value(&this), &args, Settle::Await);
stats.record(started.elapsed());
match called {
Ok(Value::String(s)) => Ok(s.to_string()),
Ok(other) => Err(fail(format!(
"it gave {}, not text, and 11ty can't write that",
other.to_js_string()
))),
Err(why) => Err(fail(why)),
}
});
let early = name
.parse::<u32>()
.is_ok_and(|i| i.to_string() == name && i != u32::MAX);
brrrty_core::JsConfigTransform { name, early, run }
}
fn posthtml_run(
runner: brrrty_js::FnHandle,
shown: &Path,
plugins: Vec<(brrrty_core::JsPosthtmlPlugin, Value, Value)>,
stats: std::sync::Arc<brrrty_core::JsFunctionStats>,
) -> brrrty_core::PosthtmlFn {
use brrrty_js::functions::{Settle, This};
let shown = shown.display().to_string();
std::sync::Arc::new(move |html: &str, page: &Value, picked: &[usize]| {
let fail = |why: String| {
format!(
"{}a posthtml plugin (from {shown}) failed: {why}",
brrrty_js::REFUSAL_PREFIX
)
};
let Some(caller) = brrrty_js::functions::installed() else {
return Err(fail("Node isn't running".to_string()));
};
let field = |k: &str| get(page, k).cloned().unwrap_or(Value::Undefined);
let mut o = indexmap::IndexMap::new();
o.insert("inputPath".to_string(), field("inputPath"));
o.insert("outputPath".to_string(), field("outputPath"));
o.insert("url".to_string(), field("url"));
o.insert("page".to_string(), page.clone());
o.insert("baseHref".to_string(), Value::Undefined);
let context = Value::Object(std::sync::Arc::new(o));
let entries: Vec<Value> = picked
.iter()
.map(|i| {
let (_, f, options) = &plugins[*i];
let mut e = indexmap::IndexMap::new();
e.insert("fn".to_string(), f.clone());
e.insert("options".to_string(), options.clone());
Value::Object(std::sync::Arc::new(e))
})
.collect();
let args = [
Value::String(html.into()),
context.clone(),
Value::Array(std::sync::Arc::new(entries)),
];
let started = std::time::Instant::now();
let called = caller.call(runner, This::Value(&context), &args, Settle::Await);
stats.record(started.elapsed());
match called {
Ok(Value::String(s)) => Ok(s.to_string()),
Ok(other) => Err(fail(format!(
"it gave {}, not text, and 11ty can't write that",
other.to_js_string()
))),
Err(why) => Err(fail(why)),
}
})
}
fn preprocess_run(
runner: brrrty_js::FnHandle,
shown: &Path,
fns: Vec<(String, Value)>,
stats: std::sync::Arc<brrrty_core::JsFunctionStats>,
) -> brrrty_core::PreprocessFn {
use brrrty_js::functions::{Settle, This};
let shown = shown.display().to_string();
std::sync::Arc::new(
move |input_path: &str,
data: &indexmap::IndexMap<String, Value>,
content: &str,
picked: &[usize]| {
let fail = |why: String| {
format!(
"{}a preprocessor (from {shown}) failed: {why}",
brrrty_js::REFUSAL_PREFIX
)
};
let Some(caller) = brrrty_js::functions::installed() else {
return Err(fail("Node isn't running".to_string()));
};
let entries: Vec<Value> = picked
.iter()
.map(|i| {
let (name, f) = &fns[*i];
let mut e = indexmap::IndexMap::new();
e.insert("name".to_string(), Value::String(name.as_str().into()));
e.insert("fn".to_string(), f.clone());
Value::Object(std::sync::Arc::new(e))
})
.collect();
let args = [
Value::Array(std::sync::Arc::new(entries)),
Value::Object(std::sync::Arc::new(data.clone())),
Value::String(content.into()),
Value::String(input_path.into()),
];
let started = std::time::Instant::now();
let called = caller.call(runner, This::Value(&Value::Undefined), &args, Settle::Await);
stats.record(started.elapsed());
let out = called.map_err(&fail)?;
let (Some(Value::Bool(skipped)), Some(Value::String(content)), Some(Value::Object(d))) = (
get(&out, "skipped"),
get(&out, "content"),
get(&out, "data"),
) else {
return Err(fail(
"a preprocessor returned content that isn't text, which 11ty can't render"
.to_string(),
));
};
Ok(brrrty_core::Preprocessed {
skipped: *skipped,
content: content.to_string(),
data: (**d).clone(),
})
},
)
}