brrrty-node 0.0.29

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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
//! The worker and its client, against real Node: lifecycle, framing, crashes
//! and finding Node.

use std::fs;
use std::path::Path;
use std::process::Command;

use brrrty_js::Value;
use brrrty_js::runtime::{JsResult, JsRuntime, Settle, This};
use brrrty_node::{NodeMissing, RunMode, Worker, find_node};

mod watch;

fn node() -> Option<brrrty_node::NodeInfo> {
    watch::started();
    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 ok<T: std::fmt::Debug>(r: JsResult<T>) -> T {
    match r {
        JsResult::Ok(v) => v,
        other => panic!("{other:?}"),
    }
}

fn get<'a>(v: &'a Value, k: &str) -> &'a Value {
    match v {
        Value::Object(o) => &o[k],
        other => panic!("not an object: {other:?}"),
    }
}

/// Whether a process with this id still runs.
fn alive(pid: u32) -> bool {
    Command::new("kill")
        .args(["-0", &pid.to_string()])
        .stderr(std::process::Stdio::null())
        .status()
        .expect("kill")
        .success()
}

#[test]
fn loads_a_file_and_calls_its_function_with_the_argument() {
    let Some(node) = node() else { return };
    let t = site(&[
        ("a.js", "module.exports = { a: 1 };"),
        ("f.js", "module.exports = (arg) => ({ got: arg.x, n: 2 });"),
    ]);
    let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
    ok(w.set_argument(&Value::from_json(&serde_json::json!({"x": "hi"}))));
    let a = ok(w.load(&t.path().join("a.js"), true));
    assert_eq!(get(&a.value, "a"), &Value::Number(1.0));
    let f = ok(w.load(&t.path().join("f.js"), true));
    assert_eq!(get(&f.value, "got"), &Value::String("hi".into()));
    // Not called: the function stays a handle.
    let raw = ok(w.load(&t.path().join("f.js"), false));
    assert_eq!(raw.functions.len(), 1);
    let called = ok(w.call(
        raw.functions[0].1,
        This::Opaque("nothing"),
        &[Value::from_json(&serde_json::json!({"x": 5}))],
        Settle::Await,
    ));
    assert_eq!(get(&called.value, "got"), &Value::Number(5.0));
}

#[test]
fn eleventy_environment_variables_are_set() {
    let Some(node) = node() else { return };
    let t = site(&[(
        "e.js",
        "module.exports = { root: process.env.ELEVENTY_ROOT, source: process.env.ELEVENTY_SOURCE, mode: process.env.ELEVENTY_RUN_MODE, v: process.env.ELEVENTY_VERSION, cwd: process.cwd(), serving: process.argv.includes(\"--serve\"), frames: process.env.BRRRTY_FRAMES_FD === undefined };",
    )]);
    let mut w = Worker::start(&node, t.path(), RunMode::Serve).expect("starts");
    let e = ok(w.load(&t.path().join("e.js"), true));
    let root = t.path().canonicalize().unwrap();
    assert_eq!(get(&e.value, "source"), &Value::String("cli".into()));
    assert_eq!(get(&e.value, "mode"), &Value::String("serve".into()));
    assert_eq!(get(&e.value, "v"), &Value::String("3.1.8".into()));
    assert_eq!(get(&e.value, "serving"), &Value::Bool(true));
    assert_eq!(get(&e.value, "frames"), &Value::Bool(true));
    let Value::String(cwd) = get(&e.value, "cwd") else {
        panic!()
    };
    assert_eq!(Path::new(&**cwd).canonicalize().unwrap(), root);
    let Value::String(r) = get(&e.value, "root") else {
        panic!()
    };
    assert_eq!(Path::new(&**r).canonicalize().unwrap(), root);
}

#[test]
fn starting_and_stopping_leaves_no_node_behind() {
    let Some(node) = node() else { return };
    let t = site(&[("a.js", "module.exports = 1;")]);
    let mut pids = Vec::new();
    for _ in 0..200 {
        let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
        ok(w.load(&t.path().join("a.js"), true));
        pids.push(w.pid());
    }
    let left: Vec<u32> = pids.into_iter().filter(|p| alive(*p)).collect();
    assert!(left.is_empty(), "still running: {left:?}");
}

/// A megabyte of logging in one write, in lines of a kilobyte. Not one
/// line of a megabyte: Brrrty passes Node's output on to its own stderr,
/// and a GitHub Actions runner takes time that grows with the square of
/// a line's length to record one (about 3 seconds at 64 KiB, 3 minutes
/// at 450 KiB, and 20 minutes before and again after a whole megabyte,
/// which ran a job with every test passing into its 45-minute limit).
#[test]
fn site_logging_never_breaks_the_frames() {
    let Some(node) = node() else { return };
    let t = site(&[(
        "noisy.js",
        r#"console.log(("x".repeat(1023) + "\n").repeat(1 << 10).trimEnd());
process.stdout.write("\x1eBRRRTY 5\nhello");
console.info("info"); console.error("err");
module.exports = { fine: true };"#,
    )]);
    let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
    let v = ok(w.load(&t.path().join("noisy.js"), true));
    assert_eq!(get(&v.value, "fine"), &Value::Bool(true));
}

#[test]
fn an_exit_from_a_data_file_stops_the_worker_with_its_status_and_stderr() {
    let Some(node) = node() else { return };
    let t = site(&[(
        "exit.js",
        r#"console.error("about to leave"); process.exit(3);"#,
    )]);
    let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
    match w.load(&t.path().join("exit.js"), true) {
        JsResult::Failed(f) => {
            assert!(f.message.contains("status 3"), "{}", f.message);
            assert!(
                f.stderr_tail.iter().any(|l| l.contains("about to leave")),
                "{:?}",
                f.stderr_tail
            );
        }
        other => panic!("{other:?}"),
    }
}

#[test]
fn a_thrown_error_is_the_sites_error_not_a_crash() {
    let Some(node) = node() else { return };
    let t = site(&[
        ("bad.js", "module.exports = () => { null.x; };"),
        ("ok.js", "module.exports = 1;"),
    ]);
    let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
    match w.load(&t.path().join("bad.js"), true) {
        JsResult::Thrown(e) => {
            assert_eq!(e.name, "TypeError");
            assert!(e.stack.contains("bad.js"), "{}", e.stack);
        }
        other => panic!("{other:?}"),
    }
    // The worker goes on.
    assert_eq!(
        ok(w.load(&t.path().join("ok.js"), true)).value,
        Value::Number(1.0)
    );
}

#[test]
fn reads_lists_files_and_modules_the_code_touched() {
    let Some(node) = node() else { return };
    let t = site(&[
        ("data.csv", "a,b\n"),
        ("lib/helper.js", "module.exports = 2;"),
        (
            "r.js",
            r#"const fs = require("fs"); const path = require("path");
const h = require("./lib/helper.js");
module.exports = { t: fs.readFileSync(path.join(__dirname, "data.csv"), "utf8"), h };"#,
        ),
    ]);
    let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
    ok(w.load(&t.path().join("r.js"), true));
    let reads: Vec<_> = ok(w.reads())
        .into_iter()
        .map(|p| p.canonicalize().unwrap_or(p))
        .collect();
    let root = t.path().canonicalize().unwrap();
    for f in ["data.csv", "lib/helper.js", "r.js"] {
        assert!(reads.contains(&root.join(f)), "{f} not in {reads:?}");
    }
}

#[test]
fn a_missing_node_is_not_found_and_an_old_one_too_old() {
    match find_node(Some("/nonexistent/node".as_ref())) {
        Err(NodeMissing::NotFound { tried }) => {
            assert_eq!(tried, ["BRRRTY_NODE=/nonexistent/node"]);
        }
        other => panic!("{other:?}"),
    }
    let t = tempfile::tempdir().unwrap();
    let fake = t.path().join("node");
    fs::write(
        &fake,
        "#!/bin/sh\nprintf '[\"v16.20.2\",\"2023c\",\"73.1\",\"undefined\",\"node\"]'\n",
    )
    .unwrap();
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        fs::set_permissions(&fake, fs::Permissions::from_mode(0o755)).unwrap();
        match find_node(Some(fake.as_os_str())) {
            Err(NodeMissing::TooOld { version, .. }) => assert_eq!(version, "v16.20.2"),
            other => panic!("{other:?}"),
        }
    }
}

#[test]
fn a_slow_data_file_is_reported_and_waited_for() {
    let Some(node) = node() else { return };
    let t = site(&[(
        "slow.js",
        "module.exports = async () => { await new Promise((r) => setTimeout(r, 700)); return { done: true }; };",
    )]);
    let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
    let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
    let s = seen.clone();
    w.set_notes(
        move |n| s.lock().unwrap().push(n.to_string()),
        std::time::Duration::from_millis(200),
        std::time::Duration::from_millis(200),
    );
    let v = ok(w.load(&t.path().join("slow.js"), true));
    assert_eq!(get(&v.value, "done"), &Value::Bool(true));
    let notes = seen.lock().unwrap().clone();
    assert!(notes.len() >= 2, "{notes:?}");
    assert!(
        notes[0].starts_with("note: still waiting on slow.js"),
        "{notes:?}"
    );
}

#[test]
fn raw_writes_to_stdout_are_noise_not_a_failure() {
    let Some(node) = node() else { return };
    let t = site(&[(
        "raw.js",
        r#"const fs = require("fs");
fs.writeSync(1, "garbage\n");
require("child_process").execSync("echo hello-from-child", { stdio: "inherit" });
fs.writeSync(1, "\x1eBRRRTY 2\n{}");
module.exports = { a: 1 };"#,
    )]);
    let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
    let d = ok(w.load(&t.path().join("raw.js"), true));
    assert_eq!(get(&d.value, "a"), &Value::Number(1.0));
    let again = ok(w.load(&t.path().join("raw.js"), true));
    assert_eq!(get(&again.value, "a"), &Value::Number(1.0));
}

#[test]
fn a_data_function_that_changes_its_argument_stops_the_build() {
    let Some(node) = node() else { return };
    let t = site(&[(
        "m.js",
        "module.exports = (d) => { d.site = { title: \"x\" }; return {}; };",
    )]);
    let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
    ok(w.set_argument(&Value::from_json(&serde_json::json!({"a": 1}))));
    match w.load(&t.path().join("m.js"), true) {
        JsResult::Failed(f) => assert!(
            f.message.contains("changes the data 11ty hands it"),
            "{}",
            f.message
        ),
        other => panic!("{other:?}"),
    }
}

#[test]
fn opened_files_are_reads_too() {
    let Some(node) = node() else { return };
    let t = site(&[
        ("rows.csv", "a\n"),
        (
            "o.js",
            "module.exports = async () => { const h = await require(\"fs\").promises.open(require(\"path\").join(__dirname, \"rows.csv\")); const s = await h.readFile(\"utf8\"); await h.close(); return { s }; };",
        ),
    ]);
    let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
    ok(w.load(&t.path().join("o.js"), true));
    let root = t.path().canonicalize().unwrap();
    let reads: Vec<_> = ok(w.reads())
        .into_iter()
        .map(|p| p.canonicalize().unwrap_or(p))
        .collect();
    assert!(reads.contains(&root.join("rows.csv")), "{reads:?}");
}

/// `{c: {c: ... {leaf: "x"}}}` with `levels` objects around the leaf, and
/// a `{children: [...]}` tree as deep.
fn deep_site(levels: usize) -> tempfile::TempDir {
    site(&[(
        "deep.js",
        &format!(
            "let o = {{ leaf: \"x\" }}; for (let i = 0; i < {levels}; i++) o = {{ c: o }};\nlet t = {{ name: \"t\" }}; for (let i = 0; i < {levels}; i++) t = {{ children: [t] }};\nmodule.exports = {{ o, t }};"
        ),
    )])
}

#[test]
fn data_nested_two_hundred_levels_deep_crosses() {
    let Some(node) = node() else { return };
    let t = deep_site(200);
    let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
    let d = ok(w.load(&t.path().join("deep.js"), true));
    assert!(d.refused.is_empty(), "{:?}", d.refused);
    let mut v = get(&d.value, "o");
    for _ in 0..200 {
        v = get(v, "c");
    }
    assert_eq!(get(v, "leaf"), &Value::String("x".into()));
    let mut v = get(&d.value, "t");
    for _ in 0..200 {
        v = match get(v, "children") {
            Value::Array(a) => &a[0],
            other => panic!("{other:?}"),
        };
    }
    assert_eq!(get(v, "name"), &Value::String("t".into()));
}

#[test]
fn data_nested_deeper_than_brrrty_reads_is_refused_not_a_crash() {
    let Some(node) = node() else { return };
    let t = deep_site(5000);
    let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
    let d = ok(w.load(&t.path().join("deep.js"), true));
    let whats: Vec<&str> = d.refused.iter().map(|(_, w)| w.as_str()).collect();
    assert_eq!(whats.len(), 2, "{whats:?}");
    assert!(
        whats.iter().all(|w| w.contains("nested more than")),
        "{whats:?}"
    );
}

#[cfg(unix)]
#[test]
fn a_child_that_keeps_nodes_pipes_never_keeps_brrrty_waiting() {
    let Some(node) = node() else { return };
    let t = site(&[(
        "kids.js",
        r#"const { spawn } = require("child_process");
const fs = require("fs");
const path = require("path");
// One in Node's process group, one in a session of its own; both hold
// Node's stdout and stderr.
const near = spawn("sleep", ["30"], { stdio: "inherit" });
near.unref();
const far = spawn("sleep", ["8"], { stdio: "inherit", detached: true });
far.unref();
fs.writeFileSync(path.join(__dirname, "near"), String(near.pid));
module.exports = { a: 1 };"#,
    )]);
    let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
    ok(w.load(&t.path().join("kids.js"), true));
    let near: u32 = fs::read_to_string(t.path().join("near"))
        .unwrap()
        .parse()
        .unwrap();
    let start = std::time::Instant::now();
    drop(w);
    assert!(
        start.elapsed() < std::time::Duration::from_secs(4),
        "dropping the worker took {:?}",
        start.elapsed()
    );
    let start = std::time::Instant::now();
    while alive(near) && start.elapsed() < std::time::Duration::from_secs(3) {
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
    assert!(!alive(near), "Node's child {near} outlived the worker");
}

#[cfg(unix)]
#[test]
fn node_exiting_while_a_child_holds_its_pipes_fails_promptly() {
    let Some(node) = node() else { return };
    let t = site(&[(
        "gone.js",
        r#"require("child_process").spawn("sleep", ["8"], { stdio: "inherit", detached: true }).unref();
process.exit(3);"#,
    )]);
    let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
    let start = std::time::Instant::now();
    match w.load(&t.path().join("gone.js"), true) {
        JsResult::Failed(f) => assert!(f.message.contains("status 3"), "{}", f.message),
        other => panic!("{other:?}"),
    }
    drop(w);
    assert!(
        start.elapsed() < std::time::Duration::from_secs(4),
        "took {:?}",
        start.elapsed()
    );
}

#[test]
fn a_file_that_gives_the_same_data_again_crosses_once() {
    let Some(node) = node() else { return };
    let t = site(&[
        (
            "same.js",
            "module.exports = () => ({ list: Array.from({ length: 50 }, (_, i) => ({ i })) });",
        ),
        (
            "count.js",
            "let n = 0; module.exports = () => ({ n: ++n });",
        ),
    ]);
    let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
    let same = |v: &Value| match v {
        Value::Object(o) => std::sync::Arc::as_ptr(o) as usize,
        other => panic!("{other:?}"),
    };
    let a = ok(w.load(&t.path().join("same.js"), true));
    let b = ok(w.load(&t.path().join("same.js"), true));
    assert_eq!(same(&a.value), same(&b.value), "decoded twice");
    let one = ok(w.load(&t.path().join("count.js"), true));
    let two = ok(w.load(&t.path().join("count.js"), true));
    assert_eq!(get(&one.value, "n"), &Value::Number(1.0));
    assert_eq!(get(&two.value, "n"), &Value::Number(2.0));
}

#[test]
fn a_lone_surrogate_in_a_key_or_an_error_is_the_sites_problem_not_a_crash() {
    let Some(node) = node() else { return };
    let t = site(&[
        (
            "key.js",
            r#"module.exports = { ["a\ud800"]: 1, deep: { ["b\udc00"]: 2 }, ok: 3 };"#,
        ),
        ("err.js", r#"throw new Error("bad \ud800 text");"#),
    ]);
    let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
    let d = ok(w.load(&t.path().join("key.js"), true));
    assert_eq!(get(&d.value, "ok"), &Value::Number(3.0));
    assert_eq!(d.refused.len(), 2, "{:?}", d.refused);
    match w.load(&t.path().join("err.js"), true) {
        JsResult::Thrown(e) => assert!(e.message.starts_with("bad "), "{}", e.message),
        other => panic!("{other:?}"),
    }
    ok(w.load(&t.path().join("key.js"), true));
}

/// Where each open descriptor of process `pid` points (`pipe:[123]`).
#[cfg(target_os = "linux")]
fn fd_links(pid: &str) -> Vec<(String, String)> {
    let mut out: Vec<(String, String)> = fs::read_dir(format!("/proc/{pid}/fd"))
        .map(|d| {
            d.filter_map(|e| {
                let e = e.ok()?;
                let link = fs::read_link(e.path()).ok()?;
                Some((
                    e.file_name().to_string_lossy().into_owned(),
                    link.to_string_lossy().into_owned(),
                ))
            })
            .collect()
        })
        .unwrap_or_default();
    out.sort();
    out
}

/// A child process a data file leaves running holds nothing of the
/// worker's beyond its standard three descriptors: never the replies'
/// pipe. (A descriptor this test process already had, inherited from
/// whatever started it, may pass through.)
#[cfg(target_os = "linux")]
#[test]
fn a_child_process_never_inherits_the_reply_pipe() {
    let Some(node) = node() else { return };
    let t = site(&[(
        "kid.js",
        r#"const kid = require("child_process").spawn("sleep", ["5"], { stdio: "inherit", detached: true });
kid.unref();
module.exports = { pid: kid.pid };"#,
    )]);
    let before: Vec<String> = fd_links("self").into_iter().map(|(_, l)| l).collect();
    let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
    let d = ok(w.load(&t.path().join("kid.js"), true));
    let Value::Number(pid) = get(&d.value, "pid") else {
        panic!("{:?}", d.value)
    };
    let pid = format!("{}", *pid as u32);
    let kid = fd_links(&pid);
    let node_fds = fd_links(&w.pid().to_string());
    let _ = Command::new("kill").arg(&pid).status();
    // A pipe of the worker's past the standard three: one Node holds that
    // this test process didn't have before it started the worker.
    let ours: Vec<&(String, String)> = kid
        .iter()
        .filter(|(n, l)| {
            !["0", "1", "2"].contains(&n.as_str())
                && l.starts_with("pipe:")
                && !before.contains(l)
                && node_fds.iter().any(|(_, nl)| nl == l)
        })
        .collect();
    assert!(
        ours.is_empty(),
        "child holds {ours:?}; Node holds {node_fds:?}"
    );
}

fn handle_at(v: &Value, path: &[&str]) -> brrrty_js::FnHandle {
    let mut v = v;
    for k in path {
        v = get(v, k);
    }
    match v {
        Value::Function(h) => *h,
        other => panic!("not a function: {other:?}"),
    }
}

fn refused<T: std::fmt::Debug>(r: JsResult<T>) -> brrrty_js::runtime::Refusal {
    match r {
        JsResult::Refused(why) => why,
        other => panic!("not refused: {other:?}"),
    }
}

fn json(v: serde_json::Value) -> Value {
    Value::from_json(&v)
}

#[test]
fn a_page_keeps_its_data_between_computed_calls() {
    let Some(node) = node() else { return };
    let t = site(&[(
        "c.js",
        "module.exports = { c: (d) => d.b + '!', b: (d) => d.a + '-b', a: (d) => d.title.toUpperCase(), all: (d) => d.collections.post.length, page: (d) => d.page.url };",
    )]);
    let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
    let c = ok(w.load(&t.path().join("c.js"), true)).value;
    let keys: Vec<String> = ["page.url", "page.outputPath", "c", "b", "a"]
        .map(String::from)
        .to_vec();
    let data = json(serde_json::json!({"title": "Hi", "page": {"fileSlug": "x"}}));
    let page = ok(w.page_open(&data, &[], &keys));
    // 11ty's proxy pass: what each function reads; computed keys not set
    // yet read as "".
    assert_eq!(ok(w.page_vars(page, handle_at(&c, &["c"]), &keys)), ["b"]);
    assert_eq!(ok(w.page_vars(page, handle_at(&c, &["b"]), &keys)), ["a"]);
    assert_eq!(
        ok(w.page_vars(page, handle_at(&c, &["a"]), &keys)),
        ["title"]
    );
    assert_eq!(
        ok(w.page_vars(page, handle_at(&c, &["all"]), &keys)),
        ["collections", "collections.post"]
    );
    assert_eq!(
        ok(w.page_vars(page, handle_at(&c, &["page"]), &keys)),
        ["page.url"]
    );
    let a = ok(w.page_call(page, handle_at(&c, &["a"]), Some("a")));
    assert_eq!(a.value, Value::String("HI".into()));
    let b = ok(w.page_call(page, handle_at(&c, &["b"]), Some("b")));
    assert_eq!(b.value, Value::String("HI-b".into()));
    ok(w.page_set(page, "page.url", &Value::String("/x/".into())));
    let u = ok(w.page_call(page, handle_at(&c, &["page"]), None));
    assert_eq!(u.value, Value::String("/x/".into()));
    w.page_close(page);
}

#[test]
fn a_method_call_has_its_object_as_this() {
    let Some(node) = node() else { return };
    let t = site(&[(
        "f.js",
        "module.exports = { label: 'Price', who() { return 'who:' + this.label; }, same: (a, b) => a === b, top() { return typeof this.slugify; } };",
    )]);
    let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
    let f = ok(w.load(&t.path().join("f.js"), true)).value;
    let who = ok(w.call(handle_at(&f, &["who"]), This::Value(&f), &[], Settle::Await));
    assert_eq!(who.value, Value::String("who:Price".into()));
    // An object passed twice is one object, as in 11ty.
    let shared = json(serde_json::json!({"k": [1, 2]}));
    let same = ok(w.call(
        handle_at(&f, &["same"]),
        This::Opaque("nothing"),
        &[shared.clone(), shared],
        Settle::Await,
    ));
    assert_eq!(same.value, Value::Bool(true));
    // `this` Brrrty doesn't model refuses the call, naming the function.
    let r = refused(w.call(
        handle_at(&f, &["top"]),
        This::Opaque("Nunjucks's render context"),
        &[],
        Settle::AsIs,
    ));
    assert!(r.why.contains("`top`"), "{}", r.why);
    assert!(r.why.contains("f.js:1:"), "{}", r.why);
    assert!(r.why.contains("this.slugify"), "{}", r.why);
    assert!(!r.impure);
}

#[test]
fn calls_run_once_and_changing_their_arguments_is_refused() {
    let Some(node) = node() else { return };
    let t = site(&[(
        "f.js",
        "let n = 0; module.exports = { count: () => ++n, poke: (o) => { o.x = 1; return 'ok'; }, later: async () => 'x', peek: (item) => { try { return item.templateContent; } catch { return 'caught'; } } };",
    )]);
    let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
    let f = ok(w.load(&t.path().join("f.js"), true)).value;
    ok(w.begin_calls());
    // A call runs once, as in 11ty; whether state mattered is the replay
    // check's to say.
    for want in [1.0, 2.0] {
        let n = ok(w.call(
            handle_at(&f, &["count"]),
            This::Value(&f),
            &[],
            Settle::Await,
        ));
        assert_eq!(n.value, Value::Number(want));
    }
    let r = refused(w.call(
        handle_at(&f, &["poke"]),
        This::Value(&f),
        &[json(serde_json::json!({}))],
        Settle::Await,
    ));
    assert!(r.why.contains("changes the data"), "{}", r.why);
    // Nunjucks doesn't await: a promise can't cross.
    let p = ok(w.call(
        handle_at(&f, &["later"]),
        This::Value(&f),
        &[],
        Settle::AsIs,
    ));
    assert_eq!(p.refused.len(), 1, "{p:?}");
    // Liquid does.
    let p = ok(w.call(
        handle_at(&f, &["later"]),
        This::Value(&f),
        &[],
        Settle::Await,
    ));
    assert_eq!(p.value, Value::String("x".into()));
    // A collection item's content isn't there: reading it refuses the
    // call, even when the function catches the error.
    let item = json(serde_json::json!({"url": "/a/"}));
    let Value::Object(mut o) = item else { panic!() };
    std::sync::Arc::make_mut(&mut o).insert("templateContent".into(), Value::Undefined);
    let r = refused(w.call(
        handle_at(&f, &["peek"]),
        This::Value(&f),
        &[Value::Object(o)],
        Settle::Await,
    ));
    assert!(r.why.contains("templateContent"), "{}", r.why);
}