Skip to main content

bynk_emit/testgen/
test_main.rs

1//! The suite runner (`tests_main`): TypeScript builders, the run function and the filter runtime.
2//!
3//! Crate-hygiene D1 (#2982, PR 2): split out of `tests_emit.rs`.
4
5use super::*;
6// #1759: every namespace a test module imports, from one definition.
7use crate::ts_build::{
8    and_expr, await_expr, binary, block, call, cond_expr, const_, expr_stmt, ident, if_, member,
9    method_call, num_lit, or_expr, str_lit, strict_eq,
10};
11use bynk_check::d1_migrations::MigrationFile;
12use bynk_ts::{
13    TsArrowBody, TsBinaryOp, TsBindingName, TsDecl, TsExpr, TsLit, TsObjectEntry, TsParam,
14    TsProgram, TsStmt, TsType, TsTypeMember,
15};
16
17/// P4b (#2608): `__makeIntegrationD1`'s argument for a database's
18/// migrations, `[[name, sql], …]` in order, or none for a database without.
19pub(super) fn d1_migrations_args(files: Option<&Vec<MigrationFile>>) -> Vec<TsExpr> {
20    let Some(files) = files.filter(|f| !f.is_empty()) else {
21        return Vec::new();
22    };
23    vec![TsExpr::Array {
24        items: files
25            .iter()
26            .map(|f| TsExpr::Array {
27                items: vec![str_lit(f.name.clone()), str_lit(f.sql.clone())],
28                multiline: false,
29            })
30            .collect(),
31        multiline: true,
32    }]
33}
34
35/// [`d1_migrations_args`] as text, for a double whose body is written as
36/// text: empty for a database without migrations.
37pub(super) fn d1_migrations_text(files: &[MigrationFile]) -> String {
38    let pairs: Vec<String> = files
39        .iter()
40        .map(|f| {
41            format!(
42                "[{}, {}]",
43                bynk_project::json_string(&f.name),
44                bynk_project::json_string(&f.sql)
45            )
46        })
47        .collect();
48    if pairs.is_empty() {
49        String::new()
50    } else {
51        format!("[{}]", pairs.join(", "))
52    }
53}
54
55/// One `async function __sysdrive_*` driver: an optional lead statement
56/// (`const __body = JSON.stringify(...)`, typed/no-auth drivers only), `const
57/// __h = __makeHarness();`, `const __req = new Request(<url>, <options>);`,
58/// `const __res = await __h.env.<binding>.fetch(__req);`, then `return
59/// <decode_fn>(__res, <payload>);`. Slice F (#1407): the one real shape
60/// shared by all four per-route `__sysdrive_{,raw_,noauth_,rawnoauth_}*`
61/// drivers in `emit_system_http_support`, differing only in name (built here
62/// from `kind`/`sname`/`key`, one shared spot rather than one
63/// `format!` call per driver kind), params, the optional body statement, the
64/// options object (Decision A, see its own call sites), and the decode
65/// function — every real difference is a parameter here, not a reason to
66/// hand-write four near-identical bodies.
67#[allow(clippy::too_many_arguments)]
68pub(super) fn sysdrive_driver(
69    kind: SysdriveKind<'_>,
70    sname: &str,
71    key: &str,
72    mut params: Vec<TsParam>,
73    body_stmts: Vec<TsStmt>,
74    url: TsExpr,
75    options: TsExpr,
76    binding: &str,
77    decode_fn: &str,
78    payload: Vec<TsExpr>,
79    signs_claims: bool,
80    // #2135: a `Signature` route's signing statements (`const __sig = …`,
81    // or #2155 a sum's per-call `__auth`), after the body they sign is
82    // serialised and before the request is built.
83    sign_stmts: Vec<TsStmt>,
84    // #2155: whether the driver takes the actor the call acts as (`__as`), on
85    // an actor-sum route.
86    takes_as: bool,
87) -> TsStmt {
88    params.push(TsParam::new(
89        "__sub".to_string(),
90        Some(TsType::named("string")),
91    ));
92    // #2019: a refinement-guarded route signs the claims the acting actor
93    // presents (`{}` for a non-refinement actor) next to `sub`.
94    if signs_claims {
95        params.push(TsParam::new(
96            "__claims".to_string(),
97            Some(TsType::named_with_args(
98                "globalThis.Record",
99                vec![TsType::named("string"), TsType::named("unknown")],
100            )),
101        ));
102    }
103    if takes_as {
104        params.push(TsParam::new(
105            "__as".to_string(),
106            Some(TsType::named("string")),
107        ));
108    }
109    let mut body = body_stmts;
110    body.extend(sign_stmts);
111    body.push(TsStmt::const_stmt(
112        TsBindingName::Ident("__h".to_string()),
113        None,
114        call(ident("__makeHarness"), vec![]),
115        None,
116    ));
117    body.push(TsStmt::const_stmt(
118        TsBindingName::Ident("__req".to_string()),
119        None,
120        TsExpr::New {
121            callee: Box::new(ident("globalThis.Request")),
122            args: vec![url, options],
123        },
124        None,
125    ));
126    body.push(TsStmt::const_stmt(
127        TsBindingName::Ident("__res".to_string()),
128        None,
129        await_expr(method_call(
130            member(member(ident("__h"), "env"), binding),
131            "fetch",
132            vec![ident("__req")],
133        )),
134        None,
135    ));
136    body.push(TsStmt::return_stmt(
137        Some(call(
138            ident(decode_fn),
139            std::iter::once(ident("__res")).chain(payload).collect(),
140        )),
141        None,
142    ));
143    TsStmt::decl(
144        TsDecl::Function {
145            name: sysdrive_name(kind, sname, key),
146            generics: Vec::new(),
147            params,
148            return_type: None,
149            body,
150            is_async: true,
151            inline: false,
152        },
153        None,
154    )
155}
156
157/// The module's own runner, built from its real per-case/per-property/per-attack
158/// `(name, runner)` pairs, in dispatch order:
159///
160/// ```ts
161/// export const __bynkCases: readonly string[] = ["a", "b"];
162/// export async function run(only?: string, onCase?: (a0: CaseResult) => void) {
163///   const results: CaseResult[] = [];
164///   const want = (n: string): boolean => only === undefined || only === n;
165///   if (want("a")) {
166///     const started = __bynkCaseNow();
167///     const r = { name: "a", ...(await test_a()), durationMs: __bynkCaseSince(started) };
168///     results.push(r);
169///     if (onCase) onCase(r);
170///   }
171///   return results;
172/// }
173/// ```
174///
175/// `onCase` is called as each case finishes, so a consumer sees a result before the
176/// next case runs (#2267 stage 2), and `__bynkCases` lists the case names so the
177/// entry can count what a filter selects before anything runs. The case result carries
178/// `durationMs`, measured around the runner. Slice G (#1409): carries no opaque lowered
179/// content and no source-map splice sensitivity (unlike the per-case bodies each
180/// dispatch calls out to), so it converts fully, shared by both
181/// `emit_integration_module` and `emit_test_module`.
182///
183/// `name` is the raw, decoded case name: `str_lit` routes it through `TsLit::Str`'s own
184/// printer escaping, which alone owns escaping (review of #1410, finding 1: an
185/// already-escaped name would be escaped twice). The `...(await …())` spread wraps its
186/// `Await` in an explicit `TsExpr::Paren`, since `TsObjectEntry::Spread` renders its
187/// inner expression without operand parenthesisation.
188pub(super) fn build_run_function(entries: &[(String, String)]) -> Vec<TsStmt> {
189    let dispatch = |name: &str, runner_name: &str| {
190        TsStmt::if_stmt(
191            call(ident("want"), vec![str_lit(name.to_string())]),
192            block(vec![
193                const_("started", call(ident("__bynkCaseNow"), vec![])),
194                const_(
195                    "r",
196                    TsExpr::object_entries(vec![
197                        TsObjectEntry::prop("name".to_string(), str_lit(name.to_string())),
198                        TsObjectEntry::Spread(TsExpr::Paren(Box::new(await_expr(call(
199                            ident(runner_name),
200                            vec![],
201                        ))))),
202                        TsObjectEntry::prop(
203                            "durationMs".to_string(),
204                            call(ident("__bynkCaseSince"), vec![ident("started")]),
205                        ),
206                    ]),
207                ),
208                expr_stmt(method_call(ident("results"), "push", vec![ident("r")])),
209                if_(
210                    ident("onCase"),
211                    expr_stmt(call(ident("onCase"), vec![ident("r")])),
212                ),
213            ]),
214            None,
215        )
216    };
217    let mut body = vec![
218        // #3639: typed, so `tsc` need not infer an evolving array's type by
219        // control-flow analysis over the whole function, which passes its
220        // flow-node limit (TS2563) at 500 cases.
221        TsStmt::const_stmt(
222            TsBindingName::Ident("results".to_string()),
223            Some(TsType::array(TsType::named("CaseResult"))),
224            TsExpr::array(vec![]),
225            None,
226        ),
227        const_(
228            "want",
229            TsExpr::Arrow {
230                params: vec![TsParam::new("n".to_string(), Some(TsType::named("string")))],
231                is_async: false,
232                generics: Vec::new(),
233                return_type: Some(TsType::named("boolean")),
234                body: Box::new(TsArrowBody::Expr(Box::new(or_expr(
235                    strict_eq(ident("only"), ident("undefined")),
236                    strict_eq(ident("only"), ident("n")),
237                )))),
238            },
239        ),
240    ];
241    body.extend(entries.iter().map(|(name, runner)| dispatch(name, runner)));
242    body.push(TsStmt::return_stmt(Some(ident("results")), None));
243    vec![
244        TestRuntimeModule::CaseTiming.splice(),
245        TsStmt::decl(
246            TsDecl::Export(Box::new(TsDecl::ConstDecl {
247                name: "__bynkCases".to_string(),
248                ty: Some(TsType::named("readonly string[]")),
249                init: TsExpr::array(
250                    entries
251                        .iter()
252                        .map(|(name, _)| str_lit(name.clone()))
253                        .collect(),
254                ),
255            })),
256            None,
257        ),
258        TsStmt::decl(
259            TsDecl::Export(Box::new(TsDecl::Function {
260                name: "run".to_string(),
261                generics: Vec::new(),
262                params: vec![
263                    TsParam::optional("only".to_string(), Some(TsType::named("string"))),
264                    TsParam::optional(
265                        "onCase".to_string(),
266                        Some(TsType::Fn {
267                            rest: false,
268                            names: vec![],
269                            params: vec![TsType::named("CaseResult")],
270                            ret: Box::new(TsType::named("void")),
271                        }),
272                    ),
273                ],
274                return_type: None,
275                body,
276                is_async: true,
277                inline: false,
278            })),
279            None,
280        ),
281    ]
282}
283
284pub(super) fn console_log(arg: TsExpr) -> TsStmt {
285    expr_stmt(method_call(ident("globalThis.console"), "log", vec![arg]))
286}
287
288/// #3437: a build whose modules carry the execution-context double drains the
289/// failures a detached effect reported (`globalThis.__bynkDetachedReports`)
290/// after each case, and reports them beside the case: as `detached_failures`
291/// and `detached` on its event, and as a line under it in the human output.
292/// A report does not fail the case, as on Workers (ADR 0478). Gated, so a build
293/// with no execution context keeps its runner unchanged.
294struct DetachReports {
295    enabled: bool,
296}
297
298impl DetachReports {
299    fn drain(&self) -> Option<TsStmt> {
300        self.enabled.then(|| {
301            // `(globalThis as unknown as { __bynkDetachedReports?: … }).__bynkDetachedReports?.splice(0) ?? []`
302            let reports = crate::ts_build::as_expr(
303                crate::ts_build::as_expr(ident("globalThis"), TsType::named("unknown")),
304                TsType::named(
305                    "{ __bynkDetachedReports?: { kind: string; site: string; type: string | null; variant: string | null }[] }",
306                ),
307            );
308            let splice = crate::ts_build::call(
309                TsExpr::OptionalMember {
310                    object: Box::new(member(crate::ts_build::paren(reports), "__bynkDetachedReports")),
311                    property: "splice".to_string(),
312                },
313                vec![crate::ts_build::num_lit(0)],
314            );
315            crate::ts_build::const_(
316                "detached",
317                crate::ts_build::binary(
318                    bynk_ts::TsBinaryOp::NullishCoalescing,
319                    splice,
320                    TsExpr::array(Vec::new()),
321                ),
322            )
323        })
324    }
325
326    fn entries(&self) -> Vec<TsObjectEntry> {
327        if !self.enabled {
328            return Vec::new();
329        }
330        vec![
331            TsObjectEntry::prop(
332                "detached_failures".to_string(),
333                detached_or_undefined(member(ident("detached"), "length")),
334            ),
335            TsObjectEntry::prop(
336                "detached".to_string(),
337                detached_or_undefined(ident("detached")),
338            ),
339        ]
340    }
341
342    /// The statements of an NDJSON `report`, after the drain.
343    fn wrap_ndjson(&self, stmts: Vec<TsStmt>) -> Vec<TsStmt> {
344        self.drain().into_iter().chain(stmts).collect()
345    }
346
347    /// The statements of the human `report`: drain, the case's line, then the reports.
348    fn wrap_human(&self, stmts: Vec<TsStmt>) -> Vec<TsStmt> {
349        self.wrap_ndjson(stmts)
350            .into_iter()
351            .chain(self.print())
352            .collect()
353    }
354
355    fn print(&self) -> Option<TsStmt> {
356        self.enabled.then(|| {
357            use crate::ts_build::{cond_expr, null_lit, str_lit, strict_eq};
358            let field = |name: &str| member(ident("d"), name);
359            // `${d.variant === null ? "" : `.${d.variant}`}`
360            let variant = cond_expr(
361                strict_eq(field("variant"), null_lit()),
362                str_lit(""),
363                TsExpr::template_lit(vec![".".to_string(), String::new()], vec![field("variant")]),
364            );
365            // `returned Err (${d.type}${variant})`, or `"faulted"`.
366            let outcome = cond_expr(
367                strict_eq(field("kind"), str_lit("err")),
368                TsExpr::template_lit(
369                    vec!["returned Err (".to_string(), String::new(), ")".to_string()],
370                    vec![field("type"), variant],
371                ),
372                str_lit("faulted"),
373            );
374            crate::ts_build::for_of(
375                "d",
376                ident("detached"),
377                expr_stmt(method_call(
378                    ident("console"),
379                    "log",
380                    vec![TsExpr::template_lit(
381                        vec![
382                            "    ! a detached effect ".to_string(),
383                            " at ".to_string(),
384                            String::new(),
385                        ],
386                        vec![outcome, field("site")],
387                    )],
388                )),
389            )
390        })
391    }
392}
393
394pub fn emit_test_main(tests: &[RunnableTest], import_ext: ImportExt, pg: bool) -> TsProgram {
395    let ext = import_ext.as_str();
396    let mut program = TsProgram::new();
397    program.push(TsStmt::comment(
398        "Generated by bynk — do not edit by hand.",
399        None,
400    ));
401    program.push(TsStmt::comment("top-level test runner", None));
402    // Node's `process` global isn't declared without @types/node. The runner
403    // uses `process.exit` and reads `process.env.BYNK_TEST_FORMAT` (v0.59: set
404    // to `ndjson` by `bynk test --format json`), so we narrow the global with a
405    // minimal ambient declaration rather than pulling in a dependency.
406    program.push(TsStmt::decl(
407        TsDecl::DeclareConst {
408            name: "process".to_string(),
409            ty: TsType::Object(vec![
410                TsTypeMember::method(
411                    "exit",
412                    vec![TsParam::new(
413                        "code".to_string(),
414                        Some(TsType::named("number")),
415                    )],
416                    TsType::named("never"),
417                ),
418                TsTypeMember::prop(
419                    "env",
420                    TsType::Object(vec![TsTypeMember::index(
421                        "k",
422                        TsType::named("string"),
423                        TsType::union(vec![TsType::named("string"), TsType::named("undefined")]),
424                    )]),
425                ),
426            ]),
427        },
428        None,
429    ));
430    let mut sorted: Vec<&RunnableTest> = tests.iter().collect();
431    sorted.sort_by(|a, b| a.target_name.cmp(&b.target_name));
432    for (i, t) in sorted.iter().enumerate() {
433        let module_stem = t
434            .module_path
435            .file_stem()
436            .and_then(|s| s.to_str())
437            .unwrap_or("test");
438        program.push(TsStmt::decl(
439            TsDecl::ImportNamespace {
440                type_only: false,
441                alias: case_alias(i),
442                from: sibling_specifier(module_stem, ext),
443            },
444            None,
445        ));
446    }
447
448    // v0.127 (editor-currency slice 6), #2273: `bynk test --case <name>` and
449    // `--suite <name>`, each repeatable, set BYNK_TEST_FILTER (see
450    // `TEST_FILTER_RUNTIME`). `active` is the modules whose suite is selected;
451    // each runs through `runSelected`, which calls its own `run(name)` once per
452    // selected case name and concatenates the results, so a module is still one
453    // suite record. Unset runs the whole project unchanged.
454    let mut main_body: Vec<TsStmt> = Vec::new();
455    let modules_items: Vec<TsExpr> = sorted
456        .iter()
457        .enumerate()
458        .map(|(i, t)| {
459            TsExpr::object(vec![
460                ("name".to_string(), str_lit(t.target_name.clone())),
461                (
462                    "names".to_string(),
463                    member(ident(case_alias(i)), "__bynkCases"),
464                ),
465                ("run".to_string(), member(ident(case_alias(i)), "run")),
466            ])
467        })
468        .collect();
469    main_body.push(const_("modules", TsExpr::multiline_array(modules_items)));
470    main_body.push(TsStmt::let_stmt(
471        TsBindingName::Ident("passed".to_string()),
472        None,
473        Some(num_lit("0")),
474        None,
475    ));
476    main_body.push(TsStmt::let_stmt(
477        TsBindingName::Ident("failed".to_string()),
478        None,
479        Some(num_lit("0")),
480        None,
481    ));
482    // v0.59: `--format json` sets BYNK_TEST_FORMAT=ndjson and captures stdout;
483    // the runner then emits one JSON event per line (an internal protocol the
484    // driver re-renders into the pinned document). Otherwise the human ✓ / ✗
485    // output is byte-for-byte unchanged.
486    //
487    // `TsLit::Raw`, not `TsLit::Str` — see its own doc: the literal already
488    // spells the JS unicode escape as six ASCII characters, which `Str`'s own
489    // escaper would double the backslash of.
490    main_body.push(const_(
491        "PREFIX",
492        TsExpr::Lit(TsLit::Raw("\"system \\u00b7 \"".to_string())),
493    ));
494    main_body.push(const_(
495        "active",
496        method_call(
497            ident("modules"),
498            "filter",
499            vec![TsExpr::Arrow {
500                params: vec![TsParam::new("m".to_string(), None)],
501                is_async: false,
502                generics: Vec::new(),
503                return_type: None,
504                body: Box::new(TsArrowBody::Expr(Box::new(call(
505                    ident("selected"),
506                    vec![cond_expr(
507                        method_call(
508                            member(ident("m"), "name"),
509                            "startsWith",
510                            vec![ident("PREFIX")],
511                        ),
512                        method_call(
513                            member(ident("m"), "name"),
514                            "slice",
515                            vec![member(ident("PREFIX"), "length")],
516                        ),
517                        member(ident("m"), "name"),
518                    )],
519                )))),
520            }],
521        ),
522    ));
523
524    let emit_call = |entries: Vec<TsObjectEntry>| {
525        expr_stmt(call(ident("emit"), vec![TsExpr::object_entries(entries)]))
526    };
527    // #2138 (track §3.6): a remote run's cases report how often `--settle`
528    // retried them.
529    let remote = tests.iter().any(|t| t.remote);
530    let retries_entry = || {
531        remote.then(|| TsObjectEntry::prop("retries".to_string(), member(ident("r"), "retries")))
532    };
533    // Track C (#2266): a failed generative case reports how to reproduce it as
534    // data — `kind`, `seed` and, when shrinking produced one, `counterexample` —
535    // after the fields above. Gated on the build having a generative module, as
536    // `retries` is on a remote one, so every other runner is unchanged;
537    // `JSON.stringify` drops one a case leaves undefined.
538    let generative = tests.iter().any(|t| t.generative);
539    // #3437: failures a detached effect reported, drained after each case.
540    let detach = DetachReports {
541        enabled: tests.iter().any(|t| t.detach_reports),
542    };
543    let generative_entries = || -> Vec<TsObjectEntry> {
544        if !generative {
545            return Vec::new();
546        }
547        // Every module's results are typed as the entry's `Result`, whose fields
548        // these are optional, so a build mixing generative and plain modules
549        // type-checks.
550        ["kind", "seed", "counterexample"]
551            .into_iter()
552            .map(|k| TsObjectEntry::prop(k.to_string(), member(ident("r"), k)))
553            .collect()
554    };
555
556    // #2267 stage 2: how long the case ran, in milliseconds, measured by its module's
557    // own `run`. Only the stream carries it; `--format json` keeps its document
558    // deterministic and drops it.
559    let duration_entry =
560        || TsObjectEntry::prop("durationMs".to_string(), member(ident("r"), "durationMs"));
561
562    // #2842: the modules that take a snapshot export `__bynkSnapshotReport`; the
563    // run hands the driver every selected one's report — as an event in the stream,
564    // and as one marked line in the human output when the driver asks for it.
565    let snapshot_report = snapshot_report_decl(&sorted);
566
567    let mut ndjson_stmts = vec![
568        const_(
569            "emit",
570            TsExpr::Arrow {
571                params: vec![TsParam::new(
572                    "o".to_string(),
573                    Some(TsType::named("unknown")),
574                )],
575                is_async: false,
576                generics: Vec::new(),
577                return_type: None,
578                body: Box::new(TsArrowBody::Expr(Box::new(method_call(
579                    ident("globalThis.console"),
580                    "log",
581                    vec![method_call(
582                        ident("globalThis.JSON"),
583                        "stringify",
584                        vec![ident("o")],
585                    )],
586                )))),
587            },
588        ),
589        emit_call(vec![
590            TsObjectEntry::prop("type".to_string(), str_lit("run-begin")),
591            TsObjectEntry::prop("suites".to_string(), member(ident("active"), "length")),
592        ]),
593        TsStmt::for_of(
594            "m",
595            ident("active"),
596            block(vec![
597                const_(
598                    "integration",
599                    method_call(
600                        member(ident("m"), "name"),
601                        "startsWith",
602                        vec![ident("PREFIX")],
603                    ),
604                ),
605                const_(
606                    "suite",
607                    cond_expr(
608                        ident("integration"),
609                        method_call(
610                            member(ident("m"), "name"),
611                            "slice",
612                            vec![member(ident("PREFIX"), "length")],
613                        ),
614                        member(ident("m"), "name"),
615                    ),
616                ),
617                const_(
618                    "kind",
619                    cond_expr(
620                        ident("integration"),
621                        str_lit("integration"),
622                        str_lit("unit"),
623                    ),
624                ),
625                emit_call(vec![
626                    TsObjectEntry::prop("type".to_string(), str_lit("suite-begin")),
627                    TsObjectEntry::prop("name".to_string(), ident("suite")),
628                    TsObjectEntry::Shorthand("kind".to_string()),
629                    TsObjectEntry::prop(
630                        "tests".to_string(),
631                        call(ident("planned"), vec![member(ident("m"), "names")]),
632                    ),
633                ]),
634                TsStmt::decl(
635                    TsDecl::Function {
636                        name: "report".to_string(),
637                        generics: Vec::new(),
638                        params: vec![TsParam::new("r".to_string(), Some(TsType::named("Result")))],
639                        return_type: None,
640                        body: detach.wrap_ndjson(vec![TsStmt::if_else_same_line_stmt(
641                            member(ident("r"), "pass"),
642                            block(vec![
643                                TsStmt::increment(ident("passed"), None),
644                                emit_call(
645                                    vec![
646                                        TsObjectEntry::prop("type".to_string(), str_lit("case")),
647                                        TsObjectEntry::Shorthand("suite".to_string()),
648                                        TsObjectEntry::prop(
649                                            "name".to_string(),
650                                            member(ident("r"), "name"),
651                                        ),
652                                        TsObjectEntry::prop("outcome".to_string(), str_lit("pass")),
653                                    ]
654                                    .into_iter()
655                                    .chain(retries_entry())
656                                    .chain(detach.entries())
657                                    .chain(std::iter::once(duration_entry()))
658                                    .collect(),
659                                ),
660                            ]),
661                            block(vec![
662                                TsStmt::increment(ident("failed"), None),
663                                emit_call(
664                                    vec![
665                                        TsObjectEntry::prop("type".to_string(), str_lit("case")),
666                                        TsObjectEntry::Shorthand("suite".to_string()),
667                                        TsObjectEntry::prop(
668                                            "name".to_string(),
669                                            member(ident("r"), "name"),
670                                        ),
671                                        TsObjectEntry::prop("outcome".to_string(), str_lit("fail")),
672                                        TsObjectEntry::prop(
673                                            "message".to_string(),
674                                            and_expr(
675                                                member(ident("r"), "error"),
676                                                member(member(ident("r"), "error"), "message"),
677                                            ),
678                                        ),
679                                        TsObjectEntry::prop(
680                                            "location".to_string(),
681                                            and_expr(
682                                                member(ident("r"), "error"),
683                                                member(member(ident("r"), "error"), "location"),
684                                            ),
685                                        ),
686                                        // #2272: the declaration a violated invariant or transition
687                                        // names; absent (`JSON.stringify` drops it) otherwise.
688                                        TsObjectEntry::prop(
689                                            "violation".to_string(),
690                                            and_expr(
691                                                member(ident("r"), "error"),
692                                                member(member(ident("r"), "error"), "violation"),
693                                            ),
694                                        ),
695                                        // #2272: the steps of a failed history that an agent refused.
696                                        TsObjectEntry::prop(
697                                            "refusals".to_string(),
698                                            and_expr(
699                                                member(ident("r"), "error"),
700                                                member(member(ident("r"), "error"), "refusals"),
701                                            ),
702                                        ),
703                                    ]
704                                    .into_iter()
705                                    .chain(retries_entry())
706                                    .chain(detach.entries())
707                                    .chain(generative_entries())
708                                    .chain(std::iter::once(duration_entry()))
709                                    .collect(),
710                                ),
711                            ]),
712                            None,
713                        )]),
714                        is_async: false,
715                        inline: false,
716                    },
717                    None,
718                ),
719                expr_stmt(await_expr(call(
720                    ident("runSelected"),
721                    vec![member(ident("m"), "run"), ident("report")],
722                ))),
723                emit_call(vec![
724                    TsObjectEntry::prop("type".to_string(), str_lit("suite-end")),
725                    TsObjectEntry::prop("name".to_string(), ident("suite")),
726                ]),
727            ]),
728            None,
729        ),
730        emit_call(vec![
731            TsObjectEntry::prop("type".to_string(), str_lit("run-end")),
732            TsObjectEntry::Shorthand("passed".to_string()),
733            TsObjectEntry::Shorthand("failed".to_string()),
734            // #2273: the `--suite`/`--case` values that selected nothing; absent
735            // (`JSON.stringify` drops an undefined) unless a filter went unmatched.
736            TsObjectEntry::prop("unmatched".to_string(), call(ident("unmatched"), vec![])),
737        ]),
738    ];
739    // #2842: the snapshot report goes ahead of `run-end`.
740    let run_end = ndjson_stmts.pop();
741    if let Some(decl) = &snapshot_report {
742        ndjson_stmts.push(decl.clone());
743        ndjson_stmts.push(emit_call(vec![
744            TsObjectEntry::prop("type".to_string(), str_lit("snapshots")),
745            TsObjectEntry::prop("files".to_string(), ident("__snapshotFiles")),
746        ]));
747    }
748    ndjson_stmts.extend(run_end);
749    let ndjson_branch = block(ndjson_stmts);
750
751    let human_branch = block(vec![
752        console_log(str_lit("Running tests...\n")),
753        TsStmt::for_of(
754            "m",
755            ident("active"),
756            block(vec![
757                console_log(TsExpr::template_lit(
758                    vec![String::new(), ":".to_string()],
759                    vec![member(ident("m"), "name")],
760                )),
761                TsStmt::decl(
762                    TsDecl::Function {
763                        name: "report".to_string(),
764                        generics: Vec::new(),
765                        params: vec![TsParam::new("r".to_string(), Some(TsType::named("Result")))],
766                        return_type: None,
767                        body: detach.wrap_human(vec![TsStmt::if_else_same_line_stmt(
768                            member(ident("r"), "pass"),
769                            TsStmt::inline_block(
770                                vec![
771                                    TsStmt::increment(ident("passed"), None),
772                                    console_log(TsExpr::template_lit(
773                                        vec!["  \\u2713 ".to_string(), String::new()],
774                                        vec![member(ident("r"), "name")],
775                                    )),
776                                ],
777                                None,
778                            ),
779                            TsStmt::inline_block(
780                                vec![
781                                    TsStmt::increment(ident("failed"), None),
782                                    console_log(TsExpr::template_lit(
783                                        vec!["  \\u2717 ".to_string(), String::new()],
784                                        vec![member(ident("r"), "name")],
785                                    )),
786                                    if_(
787                                        member(ident("r"), "error"),
788                                        console_log(TsExpr::template_lit(
789                                            vec!["    ".to_string(), String::new()],
790                                            vec![member(member(ident("r"), "error"), "message")],
791                                        )),
792                                    ),
793                                ],
794                                None,
795                            ),
796                            None,
797                        )]),
798                        is_async: false,
799                        inline: false,
800                    },
801                    None,
802                ),
803                expr_stmt(await_expr(call(
804                    ident("runSelected"),
805                    vec![member(ident("m"), "run"), ident("report")],
806                ))),
807                console_log(str_lit("")),
808            ]),
809            None,
810        ),
811        console_log(TsExpr::template_lit(
812            vec![
813                String::new(),
814                " passed, ".to_string(),
815                " failed.".to_string(),
816            ],
817            vec![ident("passed"), ident("failed")],
818        )),
819        expr_stmt(call(ident("reportUnmatched"), vec![])),
820    ]);
821    // #2842: under `BYNK_SNAPSHOT_REPORT=1` the driver reads the report from one
822    // marked line at the end of the human output and strips it.
823    let human_branch = with_snapshot_report(human_branch, &snapshot_report);
824
825    main_body.push(TsStmt::if_else_same_line_stmt(
826        strict_eq(
827            member(member(ident("process"), "env"), "BYNK_TEST_FORMAT"),
828            str_lit("ndjson"),
829        ),
830        ndjson_branch,
831        human_branch,
832        None,
833    ));
834    main_body.extend(pg.then(pglite_teardown));
835    // A filter value that selected nothing fails the run, as a failed case does.
836    main_body.push(if_(
837        or_expr(
838            binary(TsBinaryOp::GreaterThan, ident("failed"), num_lit("0")),
839            TsExpr::Binary {
840                op: TsBinaryOp::StrictNotEq,
841                left: Box::new(call(ident("unmatched"), vec![])),
842                right: Box::new(ident("undefined")),
843            },
844        ),
845        expr_stmt(call(member(ident("process"), "exit"), vec![num_lit("1")])),
846    ));
847
848    program.push(TestRuntimeModule::TestFilter.splice());
849    program.push(TsStmt::decl(
850        TsDecl::Function {
851            name: "main".to_string(),
852            generics: Vec::new(),
853            params: vec![],
854            return_type: None,
855            body: main_body,
856            is_async: true,
857            inline: false,
858        },
859        None,
860    ));
861    program.push(expr_stmt(call(ident("main"), vec![])));
862    program
863}
864
865/// #3321: closes the PGlite databases a run started. PGlite leaves a ten-second
866/// timer behind, which would otherwise hold the process open that long; the
867/// runtime registers the closer on `globalThis`, so no import is needed.
868fn pglite_teardown() -> TsStmt {
869    // `await (globalThis as unknown as { __bynkPgliteTeardown?: () => Promise<void> }).__bynkPgliteTeardown?.();`
870    let closer = TsExpr::OptionalCall {
871        callee: Box::new(member(
872            crate::ts_build::paren(crate::ts_build::as_expr(
873                crate::ts_build::as_expr(ident("globalThis"), TsType::named("unknown")),
874                TsType::named("{ __bynkPgliteTeardown?: () => Promise<void> }"),
875            )),
876            "__bynkPgliteTeardown",
877        )),
878        args: Vec::new(),
879    };
880    expr_stmt(await_expr(closer))
881}
882
883/// #2842: under `BYNK_SNAPSHOT_REPORT=1` the driver reads the report from one
884/// marked line at the end of the human output and strips it.
885fn with_snapshot_report(human_branch: TsStmt, snapshot_report: &Option<TsStmt>) -> TsStmt {
886    match snapshot_report {
887        Some(decl) => {
888            // `if (process.env.BYNK_SNAPSHOT_REPORT === "1") { globalThis.console.log("\u0001bynk-snapshots " + globalThis.JSON.stringify(__snapshotFiles)); }`
889            let marked = crate::ts_build::binary(
890                TsBinaryOp::Add,
891                crate::ts_build::raw_lit("\"\\u0001bynk-snapshots \""),
892                method_call(
893                    ident("globalThis.JSON"),
894                    "stringify",
895                    vec![ident("__snapshotFiles")],
896                ),
897            );
898            block(vec![
899                human_branch,
900                decl.clone(),
901                crate::ts_build::if_(
902                    strict_eq(
903                        member(member(ident("process"), "env"), "BYNK_SNAPSHOT_REPORT"),
904                        str_lit("1"),
905                    ),
906                    TsStmt::inline_block(vec![console_log(marked)], None),
907                ),
908            ])
909        }
910        None => human_branch,
911    }
912}
913
914/// `const __snapshotFiles = ([[i, test_i], …] as const).filter(([i]) => active.includes(modules[i]!)).flatMap(([, t]) => t.__bynkSnapshotReport());`:
915/// the report of every selected module that takes a snapshot.
916fn snapshot_files_decl(modules: Vec<TsExpr>) -> TsStmt {
917    use crate::ts_build::{arrow, index, paren};
918    let selected = method_call(
919        paren(TsExpr::AsConst(Box::new(TsExpr::array(modules)))),
920        "filter",
921        vec![arrow(
922            vec![TsParam::array_pattern(vec!["i".to_string()], None)],
923            method_call(
924                ident("active"),
925                "includes",
926                vec![TsExpr::NonNull(Box::new(index(
927                    ident("modules"),
928                    ident("i"),
929                )))],
930            ),
931        )],
932    );
933    const_(
934        "__snapshotFiles",
935        method_call(
936            selected,
937            "flatMap",
938            vec![arrow(
939                vec![TsParam::array_pattern(
940                    vec![String::new(), "t".to_string()],
941                    None,
942                )],
943                method_call(ident("t"), "__bynkSnapshotReport", Vec::new()),
944            )],
945        ),
946    )
947}
948
949/// #2842: the report declaration, when some selected module takes a snapshot.
950fn snapshot_report_decl(sorted: &[&RunnableTest]) -> Option<TsStmt> {
951    let modules: Vec<TsExpr> = sorted
952        .iter()
953        .enumerate()
954        .filter(|(_, t)| !t.snapshot_files.is_empty())
955        .map(|(i, _)| {
956            TsExpr::array(vec![
957                crate::ts_build::num_lit(i),
958                ident(format!("test_{i}")),
959            ])
960        })
961        .collect();
962    (!modules.is_empty()).then(|| snapshot_files_decl(modules))
963}
964
965/// `(detached.length > 0 ? <when_some> : undefined)`: a report field only a run with detached
966/// failures carries.
967fn detached_or_undefined(when_some: TsExpr) -> TsExpr {
968    crate::ts_build::paren(crate::ts_build::cond_expr(
969        crate::ts_build::binary(
970            bynk_ts::TsBinaryOp::GreaterThan,
971            member(ident("detached"), "length"),
972            crate::ts_build::num_lit(0),
973        ),
974        when_some,
975        ident("undefined"),
976    ))
977}
978
979#[cfg(test)]
980mod tests {
981    use super::*;
982
983    /// Review of #1410, finding 1: `run_dispatch_stmt` must escape a raw
984    /// case/property name exactly once. Pins a name containing both a
985    /// double quote and a backslash — the exact shape a double-escape
986    /// (passing an already-`emitter::escape_ts_string`-escaped name into
987    /// `str_lit`, which escapes again) would corrupt, and which no `.bynk`
988    /// fixture exercises today.
989    #[test]
990    fn the_run_function_escapes_a_quoted_backslashed_name_exactly_once() {
991        let stmts = build_run_function(&[(r#"say "hi" \ ok"#.to_string(), "test_a".to_string())]);
992        let printed: String = stmts.iter().map(|s| bynk_ts::print_stmt(s, 0)).collect();
993        // The name is escaped once in the case list and once in the dispatch.
994        assert!(
995            printed
996                .contains(r#"export const __bynkCases: readonly string[] = ["say \"hi\" \\ ok"];"#),
997            "{printed}"
998        );
999        assert!(
1000            printed.contains(r#"if (want("say \"hi\" \\ ok")) {"#),
1001            "{printed}"
1002        );
1003        assert!(printed.contains(r#"const r = { name: "say \"hi\" \\ ok", ...(await test_a()), durationMs: __bynkCaseSince(started) };"#), "{printed}");
1004    }
1005
1006    /// #2267 stage 2: each case is timed, handed to `onCase` as it finishes and
1007    /// pushed to the results, in that order, and the module lists its case names.
1008    #[test]
1009    fn the_run_function_times_each_case_and_reports_it_as_it_finishes() {
1010        let stmts = build_run_function(&[
1011            ("one".to_string(), "test_one".to_string()),
1012            ("two".to_string(), "test_two".to_string()),
1013        ]);
1014        let printed: String = stmts.iter().map(|s| bynk_ts::print_stmt(s, 0)).collect();
1015        assert!(
1016            printed.contains(r#"export const __bynkCases: readonly string[] = ["one", "two"];"#)
1017        );
1018        assert!(printed.contains(
1019            "export async function run(only?: string, onCase?: (a0: CaseResult) => void)"
1020        ));
1021        let started = printed
1022            .find("const started = __bynkCaseNow();")
1023            .expect("timed");
1024        let ran = printed.find("...(await test_one())").expect("ran");
1025        let pushed = printed.find("results.push(r);").expect("pushed");
1026        let reported = printed.find("if (onCase) onCase(r);").expect("reported");
1027        assert!(
1028            started < ran && ran < pushed && pushed < reported,
1029            "{printed}"
1030        );
1031        assert_eq!(printed.matches("const started = ").count(), 2);
1032    }
1033
1034    // v0.127 (editor-currency slice 6), #2273: the top-level runner reads
1035    // `BYNK_TEST_CASE` and threads it into every suite's `run(only)`, so a
1036    // `bynk test --case <name>` filters which cases execute.
1037    #[test]
1038    fn emit_test_main_threads_the_case_and_suite_filter() {
1039        let tests = vec![RunnableTest {
1040            snapshot_files: Vec::new(),
1041            target_name: "commerce.money".to_string(),
1042            module_path: std::path::PathBuf::from("tests/commerce_money.test.ts"),
1043            kind: "unit",
1044            suite_name: "commerce.money".to_string(),
1045            cases: vec![DiscoveredCase {
1046                name: "rounds".to_string(),
1047                location: None,
1048                tier: None,
1049                generative: None,
1050                doc: false,
1051            }],
1052            skipped: Vec::new(),
1053            envs: Vec::new(),
1054            remote: false,
1055            generative: false,
1056            detach_reports: false,
1057        }];
1058        let program = emit_test_main(&tests, ImportExt::Js, false);
1059        let out = bynk_ts::print(&program, "", "", "").text;
1060        assert!(
1061            out.contains("process.env.BYNK_TEST_FILTER"),
1062            "the runner must read the filter from the environment, got:\n{out}"
1063        );
1064        // Both the NDJSON and the human loop walk the selected modules and run
1065        // each through the filter, so a module stays one suite record.
1066        assert_eq!(
1067            out.matches("await runSelected(m.run, report)").count(),
1068            2,
1069            "both dispatch branches must run each suite through the filter, got:\n{out}"
1070        );
1071        assert_eq!(
1072            out.matches("for (const m of active)").count(),
1073            2,
1074            "got:\n{out}"
1075        );
1076        assert!(
1077            out.contains("unmatched: unmatched()"),
1078            "run-end reports the values that selected nothing, got:\n{out}"
1079        );
1080    }
1081
1082    /// #1325's own direct fixture test — `emit_test_main`'s signature
1083    /// (`&[RunnableTest]`/`ImportExt`) is simple enough to hand-construct
1084    /// directly, unlike `emit_worker_compose`'s/`emit_worker_entry`'s own
1085    /// whole-project `UnitTable`-derived data (#1321/#1323's own reason for
1086    /// relying on the full fixture corpus instead). Calls the real,
1087    /// converted function with real-shaped data and asserts the printed
1088    /// output is byte-identical to a real fixture's own `tests/main.ts`, not
1089    /// a hand-rebuilt approximation of it.
1090    #[test]
1091    fn matches_the_real_fixtures_own_tests_main_ts_byte_for_byte() {
1092        let expected = include_str!(
1093            "../../../bynk-tests/tests/fixtures/positive/109_test_with_opaque_construction/\
1094             expected/tests/main.ts"
1095        );
1096        let tests = vec![RunnableTest {
1097            snapshot_files: Vec::new(),
1098            target_name: "commerce.payment".to_string(),
1099            module_path: std::path::PathBuf::from("commerce_payment.test.js"),
1100            kind: "unit",
1101            suite_name: "commerce.payment".to_string(),
1102            cases: vec![DiscoveredCase {
1103                name: "opaque".to_string(),
1104                location: None,
1105                tier: None,
1106                generative: None,
1107                doc: false,
1108            }],
1109            skipped: Vec::new(),
1110            envs: Vec::new(),
1111            remote: false,
1112            generative: false,
1113            detach_reports: false,
1114        }];
1115        let program = emit_test_main(&tests, ImportExt::Js, false);
1116        let printed = bynk_ts::print(&program, "", "", "");
1117        assert_eq!(printed.text, expected);
1118    }
1119
1120    /// No stored golden holds a snapshot report, so the statements are pinned: the declaration of
1121    /// `__snapshotFiles` over the modules that take a snapshot, and the marked human line.
1122    #[test]
1123    fn the_snapshot_report_prints_its_declaration_and_marked_line() {
1124        let decl = snapshot_files_decl(vec![
1125            TsExpr::array(vec![crate::ts_build::num_lit(0), ident("test_0")]),
1126            TsExpr::array(vec![crate::ts_build::num_lit(2), ident("test_2")]),
1127        ]);
1128        assert_eq!(
1129            bynk_ts::print_stmt(&decl, 0),
1130            "const __snapshotFiles = ([[0, test_0], [2, test_2]] as const).filter(([i]) => active.includes(modules[i]!)).flatMap(([, t]) => t.__bynkSnapshotReport());\n"
1131        );
1132        let human = with_snapshot_report(block(Vec::new()), &Some(decl));
1133        let printed = bynk_ts::print_stmt(&human, 0);
1134        assert!(
1135            printed.contains(
1136                "if (process.env.BYNK_SNAPSHOT_REPORT === \"1\") { globalThis.console.log(\"\\u0001bynk-snapshots \" + globalThis.JSON.stringify(__snapshotFiles)); }"
1137            ),
1138            "{printed}"
1139        );
1140    }
1141}