brrrty-node 0.1.41

Runs an Eleventy site's JavaScript data files in the site's own Node, for Brrrty, an Eleventy-compatible static site generator.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
//! Loading the site's 11ty config in Node against a recording
//! `eleventyConfig`.

use std::fs;

use brrrty_js::Value;
use brrrty_js::runtime::{JsResult, JsRuntime, PathPart};
use brrrty_node::{RunMode, Worker, find_node};

fn node() -> Option<brrrty_node::NodeInfo> {
    match find_node(None) {
        Ok(n) => Some(n),
        Err(e) => {
            if std::env::var_os("CI").is_some() {
                panic!("CI needs Node for these tests: {e}");
            }
            eprintln!("skipped: {e}");
            None
        }
    }
}

fn site(files: &[(&str, &str)]) -> tempfile::TempDir {
    let t = tempfile::tempdir().unwrap();
    for (rel, body) in files {
        let p = t.path().join(rel);
        fs::create_dir_all(p.parent().unwrap()).unwrap();
        fs::write(p, body).unwrap();
    }
    t
}

fn get<'a>(v: &'a Value, k: &str) -> &'a Value {
    match v {
        Value::Object(o) => o.get(k).unwrap_or_else(|| panic!("no `{k}` in {v:?}")),
        other => panic!("not an object: {other:?}"),
    }
}

fn list(v: &Value) -> &[Value] {
    match v {
        Value::Array(a) => a,
        other => panic!("not an array: {other:?}"),
    }
}

fn s(v: &str) -> Value {
    Value::String(v.into())
}

const CONFIG: &str = r#"module.exports = function (eleventyConfig) {
  eleventyConfig.addPassthroughCopy("a").addPassthroughCopy("b");
  require("./_config/filters.js")(eleventyConfig);
  eleventyConfig.setTemplateFormats(["njk", "md"]);
  eleventyConfig.addGlobalData("x", 1);
  eleventyConfig.setSomethingNew(true);
  return { dir: { input: "src" } };
};
"#;

const FILTERS: &str = r#"module.exports = (eleventyConfig) => {
  eleventyConfig.addFilter("upper", function upper(s) { return String(s).toUpperCase(); });
  eleventyConfig.addAsyncFilter("slow", async function slow(s) { return s; });
};
"#;

#[test]
fn the_config_loads_against_a_recorder_and_replies_with_what_it_set() {
    let Some(node) = node() else { return };
    let t = site(&[
        ("eleventy.config.js", CONFIG),
        ("_config/filters.js", FILTERS),
    ]);
    let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
    let d = match w.load_config(&t.path().join("eleventy.config.js")) {
        JsResult::Ok(d) => d,
        other => panic!("{other:?}"),
    };
    let v = &d.value;
    let values = get(v, "values");
    let copies: Vec<&Value> = list(get(values, "passthroughCopy"))
        .iter()
        .map(|c| get(c, "input"))
        .collect();
    assert_eq!(copies, [&s("a"), &s("b")]);
    assert_eq!(
        get(values, "templateFormats"),
        &Value::Array(vec![s("njk"), s("md")].into())
    );
    assert_eq!(get(get(values, "globalData"), "x"), &Value::Number(1.0));
    let dir = get(get(v, "returned"), "dir");
    assert_eq!(get(dir, "input"), &s("src"));

    let funcs = list(get(v, "functions"));
    let names: Vec<&Value> = funcs.iter().map(|f| get(f, "name")).collect();
    assert_eq!(names, [&s("upper"), &s("slow")]);
    assert_eq!(get(&funcs[0], "kind"), &s("filter"));
    assert_eq!(get(&funcs[1], "async"), &Value::Bool(true));
    // Each function is a handle, at `functions[i].fn`.
    assert_eq!(d.functions.len(), 2);
    assert_eq!(
        d.functions[0].0,
        vec![
            PathPart::Key("functions".into()),
            PathPart::Index(0),
            PathPart::Key("fn".into())
        ]
    );

    let un = list(get(v, "unsupported"));
    assert_eq!(un.len(), 1);
    assert_eq!(get(&un[0], "method"), &s("setSomethingNew"));
    assert_eq!(get(&un[0], "at"), &s("eleventy.config.js:6"));
}

#[test]
fn a_config_that_throws_refuses_with_the_file_and_line() {
    let Some(node) = node() else { return };
    let t = site(&[(
        "eleventy.config.js",
        "module.exports = function (eleventyConfig) {\n  eleventyConfig.addGlobalData(\"x\", 1);\n  throw new Error(\"boom\");\n};\n",
    )]);
    let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
    match w.load_config(&t.path().join("eleventy.config.js")) {
        JsResult::Thrown(e) => {
            assert_eq!(e.message, "boom");
            assert_eq!(e.line, Some(3));
            assert!(
                e.file
                    .as_ref()
                    .is_some_and(|f| f.ends_with("eleventy.config.js")),
                "{:?}",
                e.file
            );
        }
        other => panic!("{other:?}"),
    }
}

/// 11ty's `processPlugins` runs after the config merged, with `userConfig.pathPrefix` set to
/// the merged `pathPrefix` (default `/`), so plugins like HtmlBasePlugin see a string.
#[test]
fn plugins_see_the_merged_path_prefix() {
    let Some(node) = node() else { return };
    for (returned, want) in [("{}", "/"), (r#"{ pathPrefix: "/blog/" }"#, "/blog/")] {
        let cfg = format!(
            "module.exports = (c) => {{\n  c.addPlugin((p) => {{\n    if (p.pathPrefix === undefined) throw new Error(\"The `baseHref` option is required\");\n    p.addGlobalData(\"seen\", p.pathPrefix);\n  }});\n  return {returned};\n}};\n"
        );
        let t = site(&[("eleventy.config.js", &cfg)]);
        let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
        let d = match w.load_config(&t.path().join("eleventy.config.js")) {
            JsResult::Ok(d) => d,
            other => panic!("{other:?}"),
        };
        let seen = get(get(&d.value, "values"), "globalData");
        assert_eq!(get(seen, "seen"), &s(want));
    }
}

/// 11ty's `processPlugins` also sets `userConfig.dir` to the merged `dir` (defaults plus the
/// returned and exported `dir`), so plugins can read `dir.output` and `dir.input`.
#[test]
fn plugins_see_the_merged_dir() {
    let Some(node) = node() else { return };
    for (returned, want_out, want_in) in [
        ("{}", "_site", "."),
        (
            r#"{ dir: { input: "src", output: "dist" } }"#,
            "dist",
            "src",
        ),
    ] {
        let cfg = format!(
            "module.exports = (c) => {{\n  c.addPlugin((p) => {{\n    p.addGlobalData(\"out\", p.dir.output);\n    p.addGlobalData(\"inp\", p.dir.input);\n  }});\n  return {returned};\n}};\n"
        );
        let t = site(&[("eleventy.config.js", &cfg)]);
        let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
        let d = match w.load_config(&t.path().join("eleventy.config.js")) {
            JsResult::Ok(d) => d,
            other => panic!("{other:?}"),
        };
        let seen = get(get(&d.value, "values"), "globalData");
        assert_eq!(get(seen, "out"), &s(want_out));
        assert_eq!(get(seen, "inp"), &s(want_in));
    }
}

/// `setOutputDirectory` and friends never reach `userConfig.dir` in 11ty: a plugin sees the
/// defaults plus the returned `dir` only.
#[test]
fn set_directory_calls_do_not_leak_into_dir() {
    let Some(node) = node() else { return };
    let cfg = "module.exports = (c) => {\n  c.setOutputDirectory(\"dist\");\n  c.setLayoutsDirectory(\"lay\");\n  c.addPlugin((p) => {\n    p.addGlobalData(\"out\", p.dir.output);\n    p.addGlobalData(\"inp\", p.dir.input);\n    p.addGlobalData(\"lay\", String(p.dir.layouts));\n  });\n  return { dir: { input: \"src\" } };\n};\n";
    let t = site(&[("eleventy.config.js", cfg)]);
    let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
    let d = match w.load_config(&t.path().join("eleventy.config.js")) {
        JsResult::Ok(d) => d,
        other => panic!("{other:?}"),
    };
    let seen = get(get(&d.value, "values"), "globalData");
    assert_eq!(get(seen, "out"), &s("_site"));
    assert_eq!(get(seen, "inp"), &s("src"));
    assert_eq!(get(seen, "lay"), &s("undefined"));
}

/// `eleventyConfig.directories` is 11ty's userspace `Directories`: `./x/` paths, with the
/// set-directory calls, the exported and the returned `dir` all applied.
#[test]
fn plugins_see_the_directories() {
    let Some(node) = node() else { return };
    let plugin = "c.addPlugin((p) => {\n    const d = p.directories;\n    p.addGlobalData(\"seen\", [d.input, d.output, d.data, d.includes, String(d.layouts)].join(\" \"));\n  });";
    for (body, want) in [
        ("return {};", "./ ./_site/ ./_data/ ./_includes/ undefined"),
        (
            "return { dir: { input: \"src\", output: \"dist\" } };",
            "./src/ ./dist/ ./src/_data/ ./src/_includes/ undefined",
        ),
        (
            "c.setOutputDirectory(\"out\"); return {};",
            "./ ./out/ ./_data/ ./_includes/ undefined",
        ),
        (
            "c.setLayoutsDirectory(\"lay\"); return { dir: { input: \"src\" } };",
            "./src/ ./_site/ ./src/_data/ ./src/_includes/ ./src/lay/",
        ),
        (
            "c.setOutputDirectory(\"dist\"); c.setInputDirectory(\"src\"); return { dir: { output: undefined, input: \"\" } };",
            "./src/ ./dist/ ./src/_data/ ./src/_includes/ undefined",
        ),
    ] {
        let (setup, ret) = match body.find("return") {
            Some(i) => body.split_at(i),
            None => (body, ""),
        };
        let cfg = format!("module.exports = (c) => {{\n  {setup}\n  {plugin}\n  {ret}\n}};\n");
        let t = site(&[("eleventy.config.js", &cfg)]);
        let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
        let d = match w.load_config(&t.path().join("eleventy.config.js")) {
            JsResult::Ok(d) => d,
            other => panic!("{other:?}"),
        };
        let seen = get(get(&d.value, "values"), "globalData");
        assert_eq!(get(seen, "seen"), &s(want), "{body}");
    }
}

/// 11ty's plugins (HtmlBasePlugin, InputPathToUrlTransformPlugin) call
/// `eleventyConfig.htmlTransformer.addUrlTransform(...)`. The recorder must not throw a
/// TypeError there: it records the call as unsupported, so the build refuses by name.
/// `addPosthtmlPlugin` is kept as a function (Brrrty runs it in Node, see below).
#[test]
fn html_transformer_calls_are_recorded_not_thrown() {
    let Some(node) = node() else { return };
    let cfg = "module.exports = (c) => {\n  c.addPlugin((p) => {\n    p.htmlTransformer.addUrlTransform([\"html\"], (u) => u, { priority: -1 });\n    p.htmlTransformer.addPosthtmlPlugin(\"html\", () => {});\n  });\n  return {};\n};\n";
    let t = site(&[("eleventy.config.js", cfg)]);
    let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
    let d = match w.load_config(&t.path().join("eleventy.config.js")) {
        JsResult::Ok(d) => d,
        other => panic!("{other:?}"),
    };
    let methods: Vec<&Value> = list(get(&d.value, "unsupported"))
        .iter()
        .map(|u| get(u, "method"))
        .collect();
    assert_eq!(methods, [&s("htmlTransformer.addUrlTransform")]);
    // The plugin, and the runner that calls it.
    assert_eq!(list(get(&d.value, "functions")).len(), 2);
}

/// `addPosthtmlPlugin(extensions, fn, options)` is kept with its extensions, priority (11ty's
/// default is 0), name and plugin options, and a sequence number that orders it among the
/// native plugins (`values.nativePlugins`) registered in the same config.
#[test]
fn posthtml_plugins_are_recorded_as_functions() {
    let Some(node) = node() else { return };
    let cfg = r#"function IdAttributePlugin(c, options = {}) {
  const sel = "[id],h1,h2,h3,h4,h5,h6", checkDuplicates = 1;
  c.htmlTransformer.addPosthtmlPlugin("html", () => {}, { name: "x" });
}
module.exports = (c) => {
  c.htmlTransformer.addPosthtmlPlugin("html,css", function first() {}, { priority: 3, name: "first", pluginOptions: { a: 1 } });
  c.addPlugin(IdAttributePlugin);
  c.htmlTransformer.addPosthtmlPlugin("html", function second() {});
  return {};
};
"#;
    let t = site(&[("eleventy.config.js", cfg)]);
    let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
    let d = match w.load_config(&t.path().join("eleventy.config.js")) {
        JsResult::Ok(d) => d,
        other => panic!("{other:?}"),
    };
    let fns: Vec<&Value> = list(get(&d.value, "functions"))
        .iter()
        .filter(|f| get(f, "kind") == &s("posthtml"))
        .collect();
    assert_eq!(fns.len(), 2, "{:?}", d.value);
    assert!(
        list(get(&d.value, "functions"))
            .iter()
            .any(|f| get(f, "kind") == &s("posthtmlRunner"))
    );
    assert_eq!(get(fns[0], "extensions"), &s("html,css"));
    assert_eq!(get(fns[0], "priority"), &Value::Number(3.0));
    assert_eq!(get(fns[0], "name"), &s("first"));
    assert_eq!(get(get(fns[0], "options"), "a"), &Value::Number(1.0));
    assert_eq!(get(fns[1], "priority"), &Value::Number(0.0));
    assert!(
        list(get(&d.value, "unsupported")).is_empty(),
        "{:?}",
        d.value
    );
    // Calls in the config body run before the queued plugin, as in 11ty.
    let native = list(get(get(&d.value, "values"), "nativeOrder"));
    assert_eq!(get(&native[0], "name"), &s("idattribute"));
    let seq = |v: &Value| match get(v, "seq") {
        Value::Number(n) => *n,
        other => panic!("{other:?}"),
    };
    assert!(seq(fns[0]) < seq(fns[1]) && seq(fns[1]) < seq(&native[0]));
}

/// eleventy-img's `eleventyImageTransformPlugin` checks `"addPosthtmlPlugin" in
/// eleventyConfig.htmlTransformer` and throws "not compatible" when it is false. The
/// recorder must answer `in` for 11ty 3.1.8's `HtmlTransformer` methods, and still record
/// the call.
#[test]
fn html_transformer_answers_the_in_check() {
    let Some(node) = node() else { return };
    let cfg = r#"module.exports = (c) => {
  if (!("addPosthtmlPlugin" in c.htmlTransformer)) {
    throw new Error("`eleventyImageTransformPlugin` is not compatible with this version of Eleventy.");
  }
  if ("nope" in c.htmlTransformer) throw new Error("unknown name reported present");
  c.htmlTransformer.addPosthtmlPlugin("html", () => {});
  return {};
};
"#;
    let t = site(&[("eleventy.config.js", cfg)]);
    let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
    let d = match w.load_config(&t.path().join("eleventy.config.js")) {
        JsResult::Ok(d) => d,
        other => panic!("{other:?}"),
    };
    let methods: Vec<&Value> = list(get(&d.value, "unsupported"))
        .iter()
        .map(|u| get(u, "method"))
        .collect();
    assert!(methods.is_empty(), "{methods:?}");
}

/// 11ty's `IdAttributePlugin` and `HtmlBasePlugin` with no options are what Brrrty runs
/// natively: the recorder records them by name and doesn't run the JS (whose
/// `htmlTransformer` calls would refuse every page). With options, or for a plugin of the
/// same name that isn't 11ty's, it runs the function as before.
#[test]
fn built_in_plugins_are_recorded_by_name() {
    let Some(node) = node() else { return };
    let cfg = r#"const POSTHTML_PLUGIN_NAME = "11ty/eleventy/id-attribute";
function IdAttributePlugin(c, options = {}) {
  const sel = "[id],h1,h2,h3,h4,h5,h6", checkDuplicates = "error";
  c.htmlTransformer.addPosthtmlPlugin("html", () => {}, { name: POSTHTML_PLUGIN_NAME });
}
function eleventyHtmlBasePlugin(c, options = {}) {
  c.addFilter("addPathPrefixToFullUrl", (u) => u);
  c.htmlTransformer.addUrlTransform(["html"], (u) => u, { priority: -1 });
}
function TransformPlugin(c, options = {}) {
  c.on("eleventy.contentMap", () => {});
  c.htmlTransformer.addUrlTransform("html", () => { throw new Error("Internal error: contentMap not available for the `pathToUrl` Transform."); });
}
function Other(c) {
  c.htmlTransformer.addPosthtmlPlugin("html", () => {});
}
module.exports = (c) => {
  c.addPlugin(IdAttributePlugin);
  c.addPlugin(eleventyHtmlBasePlugin, {});
  c.addPlugin(TransformPlugin);
  c.addPlugin(IdAttributePlugin, { selector: "h2" });
  c.addPlugin(Other);
  return {};
};
"#;
    let t = site(&[("eleventy.config.js", cfg)]);
    let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
    let d = match w.load_config(&t.path().join("eleventy.config.js")) {
        JsResult::Ok(d) => d,
        other => panic!("{other:?}"),
    };
    assert_eq!(
        list(get(get(&d.value, "values"), "nativePlugins")),
        [s("idattribute"), s("htmlbase"), s("inputpathtourl")]
    );
    let methods: Vec<&Value> = list(get(&d.value, "unsupported"))
        .iter()
        .map(|u| get(u, "method"))
        .collect();
    assert!(methods.is_empty(), "{methods:?}");
    // Only the call with options and the other plugin ran: both kept as functions.
    assert_eq!(list(get(&d.value, "functions")).len(), 3);
}

/// HtmlBasePlugin is native only under the default `pathPrefix` (`/`): with another, the
/// real plugin runs and its `addUrlTransform` call is recorded, so the build refuses.
#[test]
fn html_base_is_native_only_for_the_default_path_prefix() {
    let Some(node) = node() else { return };
    let cfg = r#"function eleventyHtmlBasePlugin(c, options = {}) {
  c.addFilter("addPathPrefixToFullUrl", (u) => u);
  c.htmlTransformer.addUrlTransform(["html"], (u) => u, { priority: -1 });
}
module.exports = (c) => {
  c.addPlugin(eleventyHtmlBasePlugin);
  return { pathPrefix: "/blog/" };
};
"#;
    let t = site(&[("eleventy.config.js", cfg)]);
    let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
    let d = match w.load_config(&t.path().join("eleventy.config.js")) {
        JsResult::Ok(d) => d,
        other => panic!("{other:?}"),
    };
    match get(&d.value, "values") {
        Value::Object(o) => assert!(o.get("nativePlugins").is_none(), "{o:?}"),
        other => panic!("{other:?}"),
    }
    let methods: Vec<&Value> = list(get(&d.value, "unsupported"))
        .iter()
        .map(|u| get(u, "method"))
        .collect();
    assert_eq!(methods, [&s("htmlTransformer.addUrlTransform")]);
}

/// `eleventyConfig.getFilter(name)` returns the filter a config added, and 11ty's own
/// `slugify` (the one `@11ty/eleventy` resolves), so a plugin that calls it while it
/// loads (eleventy-plugin-rss's feed plugin) doesn't throw "slugifyFilter is not a function".
#[test]
fn get_filter_returns_added_and_built_in_filters() {
    let Some(node) = node() else { return };
    let cfg = r#"module.exports = function (c) {
  c.addFilter("shout", (s) => String(s).toUpperCase());
  c.addPlugin(function plugin(config) {
    const slugify = config.getFilter("slugify");
    config.addGlobalData("slug", slugify("Hello World"));
    config.addGlobalData("shout", config.getFilter("shout")("hi"));
    config.addGlobalData("none", config.getFilter("nope") === undefined);
  });
  return {};
};
"#;
    let t = site(&[
        ("eleventy.config.js", cfg),
        (
            "node_modules/@11ty/eleventy/package.json",
            r#"{"name":"@11ty/eleventy","version":"3.1.8","main":"./src/main.cjs"}"#,
        ),
        (
            "node_modules/@11ty/eleventy/src/main.cjs",
            "module.exports = {};\n",
        ),
        (
            "node_modules/@11ty/eleventy/node_modules/@sindresorhus/slugify/package.json",
            r#"{"name":"@sindresorhus/slugify","type":"module","exports":"./index.js"}"#,
        ),
        (
            "node_modules/@11ty/eleventy/node_modules/@sindresorhus/slugify/index.js",
            "export default (s, o) => String(s).toLowerCase().replace(/\\W+/g, \"-\") + (o && o.decamelize === false ? \"\" : \"!\");\n",
        ),
    ]);
    let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
    let d = match w.load_config(&t.path().join("eleventy.config.js")) {
        JsResult::Ok(d) => d,
        other => panic!("{other:?}"),
    };
    let data = get(get(&d.value, "values"), "globalData");
    assert_eq!(get(data, "slug"), &s("hello-world"));
    assert_eq!(get(data, "shout"), &s("HI"));
    assert_eq!(get(data, "none"), &Value::Bool(true));
}