Skip to main content

bynk_emit/testgen/
test_deps.rs

1//! Test dependency emission: `deps`, namespace destructuring, assets and fixtures.
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::emitter::emit::test_scaffold_ns as test_ns;
8use crate::testgen::TEST_SESSION_KEY;
9use bynk_check::test_suites::{self, ResolvedStub};
10use bynk_ts::{TsBindingName, TsDecl, TsExpr, TsLit, TsObjectEntry, TsParam, TsStmt, TsType};
11
12/// The arguments a derived capability's test double is built with: P3 (#2342) a
13/// rate limiter's limit and window, #3479 a `Vectorize` index's dimensions,
14/// metric and `@indexed` entries, so the double enforces its declaration. None
15/// for any other kind (and for the bare capability, whose double takes
16/// defaults).
17fn double_args(derived: Option<&bynk_check::symbols::DerivedInstance>) -> Vec<TsExpr> {
18    if let Some((limit, period)) = derived.and_then(|d| d.rate_limit()) {
19        return vec![num_lit(limit.to_string()), num_lit(period.to_string())];
20    }
21    match derived.filter(|d| d.is_vectorize()) {
22        Some(d) => vec![
23            num_lit(d.vectorize_dimensions().unwrap_or_default().to_string()),
24            str_lit(d.vectorize_metric().unwrap_or_default()),
25            TsExpr::Array {
26                items: d.vectorize_indexed().iter().map(str_lit).collect(),
27                multiline: false,
28            },
29        ],
30        None => Vec::new(),
31    }
32}
33
34/// `for (const ev of events) await this.Events.emit(ev.payload);`, the body of `__eventsDispatch`.
35fn events_emit_loop() -> TsStmt {
36    use crate::ts_build::{await_expr, expr_stmt, for_of, ident, member, method_call};
37    for_of(
38        "ev",
39        ident("events"),
40        expr_stmt(await_expr(method_call(
41            member(ident("this"), "Events"),
42            "emit",
43            vec![member(ident("ev"), "payload")],
44        ))),
45    )
46}
47
48/// #1479: returns the real [`TsStmt`] itself (was pre-printed `String`) — the
49/// one real declaration this function ever built; its caller now prints it
50/// directly via `bynk_ts::print_stmt`, the same shape it always used, just
51/// one call further out.
52///
53/// #1863: a provider is built as the composition root builds it
54/// ([`instantiate_provider_ts_expr`]), its own `given` capabilities wired in,
55/// whether the context declares it or a context it consumes does. The units
56/// that construction names are returned, for the test module to import: a
57/// provider's `given` can reach a unit the target doesn't consume itself.
58///
59/// Unlike the composition root, a provider's `given` that is also one of the
60/// deps' own entries is that entry, held in a local, not a second copy: in a
61/// test a `stub` overlays the entry, and a copy would escape it (#1864
62/// review).
63#[allow(clippy::too_many_arguments)]
64pub(super) fn emit_test_deps(
65    target_name: &str,
66    target_kind: UnitKind,
67    stubs: &HashMap<String, ResolvedStub>,
68    unit_tables: &HashMap<String, UnitTable>,
69    unit_consumes: &HashMap<String, Vec<String>>,
70    unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
71    unit_flattened: &HashMap<String, HashMap<String, String>>,
72    // #1975: the adapters whose binding this factory builds for real, by
73    // binding module (an adapter suite, or the `integration` tier's factory);
74    // `None` keeps every external provider the placeholder.
75    bindings: Option<&HashMap<String, String>>,
76    // The factory's name: `__makeTestDeps`, or `__makeIntegrationDeps`.
77    name: &str,
78    // #2050: whether the target's handlers emit, so their `deps` require
79    // `__eventsDispatch` ([`target_emits_events`]).
80    uses_emit: bool,
81) -> TestDeps {
82    let mut units: BTreeSet<String> = BTreeSet::new();
83    let mut doubles: Vec<(String, String, String)> = Vec::new();
84    // #1975: a real binding's own `given` that the target does not reach
85    // takes the tier's test double, recorded so the module defines it.
86    let given_doubles: std::cell::RefCell<Vec<(String, String, String)>> =
87        std::cell::RefCell::new(Vec::new());
88    let given_double = |owner: &str, cap: &str| -> Option<TsExpr> {
89        bindings?;
90        platform_double(owner, cap, &test_ns(owner), cap, false, None)?;
91        given_doubles
92            .borrow_mut()
93            .push((owner.to_string(), cap.to_string(), cap.to_string()));
94        Some(call(ident(test_cap_factory(cap)), Vec::new()))
95    };
96    // Each top-level entry: its deps key, the `(unit, capability)` it is, and
97    // how its value is built.
98    let mut tops: Vec<(String, (String, String), TopDep)> = Vec::new();
99    let mut surface_entries: Vec<(String, TsExpr)> = Vec::new();
100    // #3892: `(surface key, local, value)` of each stubbed consumed context.
101    let mut service_doubles: Vec<(String, String, TsExpr)> = Vec::new();
102    // #1975: an adapter target's deps are its own capabilities, built from
103    // its binding: the binding is the unit under test.
104    if matches!(target_kind, UnitKind::Context | UnitKind::Adapter)
105        && let Some(table) = unit_tables.get(target_name)
106    {
107        // Sorted so `__makeTestDeps` field order is deterministic across the
108        // capability map's hash iteration order.
109        let mut caps: Vec<&String> = table.capabilities.keys().collect();
110        caps.sort();
111        for cap in caps {
112            // v0.118: a capability with a `stub` override plugs its
113            // `__Stub_<Cap>` stub; otherwise the declared provider (its real
114            // implementation) is used, as an un-overridden seam.
115            let how = if table.providers.contains_key(cap) {
116                TopDep::Provider
117            } else if let Some(inst) = table.derived.get(cap) {
118                // S4a (#1966): a derived capability's instance has its base's
119                // double, its own fresh one.
120                platform_or_placeholder(&inst.base_unit, &inst.base_cap)
121            } else {
122                TopDep::Placeholder
123            };
124            tops.push((cap.clone(), (target_name.to_string(), cap.clone()), how));
125        }
126        // v0.17 (Locale capability track, slice 1, #844): a capability
127        // flattened in via `consumes U { Cap }` (e.g. an adapter's `Locale`)
128        // is never in `table.capabilities` above — that holds only
129        // capabilities this unit declares itself. Its real implementation is
130        // wired by production `compose()` from a platform binding the test
131        // module never imports, so an un-stubbed one is the placeholder,
132        // exactly like a locally-declared capability with no provider — or,
133        // #291, a platform capability's deterministic test double.
134        let flattened = unit_flattened.get(target_name).cloned().unwrap_or_default();
135        let mut flat: Vec<(&String, &String)> = flattened.iter().collect();
136        flat.sort_by_key(|(cap, _)| cap.as_str());
137        for (cap, owner) in flat {
138            // #1975: an adapter's capability whose binding this factory
139            // builds is its real provider.
140            let how = if bindings.is_some_and(|b| b.contains_key(owner)) {
141                TopDep::Provider
142            } else {
143                platform_or_placeholder(owner, cap)
144            };
145            tops.push((cap.clone(), (owner.clone(), cap.clone()), how));
146        }
147        // #1863: a capability another context provides, named with that
148        // context's prefix (`given Fees.Fees`), as the composition root wires
149        // it (`handler_cross_caps`, which also lists the flattened ones
150        // above): that context's provider, keyed by the capability's name,
151        // or a first-party platform capability's test double.
152        let consumed_all: Vec<String> = unit_consumes.get(target_name).cloned().unwrap_or_default();
153        let aliases = unit_consumes_aliases
154            .get(target_name)
155            .cloned()
156            .unwrap_or_default();
157        for (cap, owner) in
158            handler_cross_caps(table, target_name, &consumed_all, &aliases, &flattened)
159        {
160            if tops.iter().any(|(k, _, _)| *k == cap) {
161                continue;
162            }
163            let how = match platform_or_placeholder(&owner, &cap) {
164                TopDep::Placeholder | TopDep::Provider => TopDep::Provider,
165                TopDep::Double => TopDep::Double,
166            };
167            tops.push((cap.clone(), (owner, cap), how));
168        }
169        // Cross-context surface: consumed contexts run with their real surface
170        // (v0.118 `stub` is capability-only — a consumed-context capability
171        // flattened via `consumes U { Cap }` is folded in via `unit_flattened`
172        // above). An `adapter` target (e.g. `consumes bynk { Locale }`) has no
173        // `__makeSurface` at all — so it must not get a surface entry either
174        // (Locale capability track, slice 1, #844), nor does a context with
175        // no services, consumed only for a capability (#1863).
176        let mut alias_for_target: HashMap<String, String> = HashMap::new();
177        for (alias, q) in &aliases {
178            alias_for_target.insert(q.clone(), alias.clone());
179        }
180        for q in consumed_all.iter().filter(|q| {
181            unit_tables
182                .get(*q)
183                .is_some_and(|t| t.kind != Some(UnitKind::Adapter) && !t.services.is_empty())
184        }) {
185            let key = alias_for_target
186                .get(q)
187                .cloned()
188                .unwrap_or_else(|| q.rsplit('.').next().unwrap_or(q.as_str()).to_string());
189            let other_ns = test_ns(q);
190            let surface_ty = format!("globalThis.ReturnType<typeof {other_ns}.__makeSurface>");
191            // #3892: a consumed context whose services the suite stubs answers
192            // from its `__Stub_<…>` double, which is also a top-level entry so
193            // the recording wrapper sees its calls. The services it does not
194            // stub throw a named error when called.
195            if let Some(local) =
196                stub_service_double(stubs, q, &key, &surface_ty, &mut service_doubles)
197            {
198                surface_entries.push((key, ident(local)));
199                continue;
200            }
201            surface_entries.push((key, undefined_as_unknown_as(surface_ty)));
202        }
203    }
204
205    // #1864 review: build every top-level value with each top-level
206    // capability named by a local, so a provider whose `given` reaches one
207    // takes that local, stub and all, rather than a fresh copy. The locals a
208    // construction used become `const`s ahead of the `return`, each after
209    // the ones its own construction used; every other value stays inline.
210    let prebuilt: HashMap<(String, String), String> = tops
211        .iter()
212        .map(|(key, id, _)| (id.clone(), format!("__dep_{key}")))
213        .collect();
214    let mut built: Vec<BuiltDep> = Vec::new();
215    for (key, (unit, cap), how) in &tops {
216        let used = std::cell::RefCell::new(BTreeSet::new());
217        let ty = format!("{}.{cap}", test_ns(unit));
218        let base = match how {
219            TopDep::Provider => Some(instantiate_provider_ts_expr(
220                unit,
221                cap,
222                unit_tables,
223                unit_consumes,
224                unit_consumes_aliases,
225                unit_flattened,
226                ProviderNamespaces::Test {
227                    prebuilt: &prebuilt,
228                    used: &used,
229                    bindings,
230                    double: &given_double,
231                },
232                None,
233                None,
234                &mut units,
235            )),
236            TopDep::Double => {
237                // A derived capability's double is its base's.
238                let derived = unit_tables.get(unit).and_then(|t| t.derived.get(cap));
239                let (owner, base) = derived.map_or((unit, cap), |d| (&d.base_unit, &d.base_cap));
240                doubles.push((owner.clone(), base.clone(), cap.clone()));
241                let args = double_args(derived);
242                Some(call(ident(test_cap_factory(cap)), args))
243            }
244            TopDep::Placeholder => None,
245        };
246        let value = match stubs.get(key) {
247            Some(rp) => stub_overlay(rp, &ty, base),
248            None => base.unwrap_or_else(|| undefined_as_unknown_as(ty)),
249        };
250        let id = (unit.clone(), cap.clone());
251        built.push(BuiltDep {
252            key: key.clone(),
253            local: prebuilt[&id].clone(),
254            id,
255            value,
256            used: used.into_inner(),
257        });
258    }
259    let shared: BTreeSet<(String, String)> =
260        built.iter().flat_map(|b| b.used.iter().cloned()).collect();
261    let mut body: Vec<TsStmt> = Vec::new();
262    let mut declared: BTreeSet<(String, String)> = BTreeSet::new();
263    // Dependencies first: no provider chain is cyclic (the checker rejects
264    // one), so this terminates.
265    fn declare(
266        id: &(String, String),
267        built: &[BuiltDep],
268        declared: &mut BTreeSet<(String, String)>,
269        body: &mut Vec<TsStmt>,
270    ) {
271        if declared.contains(id) {
272            return;
273        }
274        let Some(dep) = built.iter().find(|b| b.id == *id) else {
275            return;
276        };
277        for used in &dep.used {
278            declare(used, built, declared, body);
279        }
280        declared.insert(id.clone());
281        body.push(TsStmt::const_stmt(
282            TsBindingName::Ident(dep.local.clone()),
283            None,
284            dep.value.clone(),
285            None,
286        ));
287    }
288    for dep in &built {
289        if shared.contains(&dep.id) {
290            declare(&dep.id, &built, &mut declared, &mut body);
291        }
292    }
293    body.extend(service_double_consts(&service_doubles));
294    let mut entries: Vec<(String, TsExpr)> = built
295        .into_iter()
296        .map(|dep| {
297            let value = if shared.contains(&dep.id) {
298                ident(dep.local)
299            } else {
300                dep.value
301            };
302            (dep.key, value)
303        })
304        .collect();
305    entries.extend(service_double_entries(&service_doubles));
306    if !surface_entries.is_empty() {
307        entries.push(("surface".to_string(), TsExpr::object(surface_entries)));
308    }
309    // #1994/#2683: the execution context a `detach`-ing handler hands its promise to,
310    // plus, on a virtual-time module, the harness's timers (`within` reads them).
311    let virtual_time = module_is_virtual_time(target_name, target_kind, stubs, unit_tables);
312    if target_hands_off_to_exec(target_name, target_kind, unit_tables) {
313        let exec = call(ident("__bynkExec"), Vec::new());
314        entries.push((
315            "__exec".to_string(),
316            if virtual_time {
317                call(
318                    ident("globalThis.Object.assign"),
319                    vec![
320                        exec,
321                        TsExpr::object(vec![("timers".to_string(), ident("__bynkTimers"))]),
322                    ],
323                )
324            } else {
325                exec
326            },
327        ));
328    }
329    entries.extend(session_keys_entry(target_name, target_kind, unit_tables));
330    let mut entries: Vec<TsObjectEntry> = entries
331        .into_iter()
332        .map(|(k, v)| TsObjectEntry::prop(k, v))
333        .collect();
334    // #2050: the release-at-commit flush of an emitting handler — a service's,
335    // or an agent's, which runs on its caller's `deps` — calls
336    // `deps.__eventsDispatch`. In a test it hands each event to the `Events`
337    // double, which records the call and delivers nothing, so `expect
338    // Events.emit called …` observes what the handler released. A method
339    // reading `this.Events` rather than a captured value: the recording
340    // wrapper lands on the deps object after this factory runs.
341    if uses_emit {
342        entries.push(
343            TsObjectEntry::method(
344                "__eventsDispatch",
345                true,
346                vec![TsParam::new(
347                    "events".to_string(),
348                    Some(TsType::named_with_args(
349                        "globalThis.Array",
350                        vec![TsType::named(crate::emitter::EVENTS_WIRE_EVENT_TS_TYPE)],
351                    )),
352                )],
353                None,
354                vec![events_emit_loop()],
355            )
356            .inlined(),
357        );
358    }
359    let case_scoped = stubs.values().any(stub_is_scoped);
360    let suite_scoped = stubs.values().any(stub_is_suite_scoped);
361    // No entries (a non-`Context` target, or a `Context` with no capabilities, flattened caps
362    // or consumed surface) is the empty object, printed `{}` (1B.5e; the ruled 1A.40 class).
363    let return_value = TsExpr::object_entries(entries);
364    if virtual_time {
365        // #2683: each case builds its `deps` afresh, so this is where the
366        // virtual clock, its timers and the in-flight count start over, and
367        // where each capability call comes to be counted.
368        body.push(TsStmt::const_stmt(
369            TsBindingName::Ident("__deps".to_string()),
370            None,
371            return_value,
372            None,
373        ));
374        body.push(TsStmt::expr_stmt(
375            call(ident("__bynkTrackDeps"), vec![ident("__deps")]),
376            None,
377        ));
378        body.push(TsStmt::return_stmt(Some(ident("__deps")), None));
379    } else {
380        body.push(TsStmt::return_stmt(Some(return_value), None));
381    }
382    doubles.extend(given_doubles.into_inner());
383    let stmt = TsStmt::decl(
384        TsDecl::Function {
385            name: name.to_string(),
386            generics: Vec::new(),
387            // #291: the running case's name, when some `stub` is case-scoped,
388            // and #1860 the running suite's ordinal, when one is suite-scoped.
389            params: [
390                ("__case", "string", case_scoped),
391                ("__suite", "number", suite_scoped),
392            ]
393            .into_iter()
394            .filter(|(_, _, on)| *on)
395            .map(|(name, ty, _)| TsParam::optional(name.to_string(), Some(TsType::named(ty))))
396            .collect(),
397            return_type: None,
398            body,
399            is_async: false,
400            inline: false,
401        },
402        None,
403    );
404    TestDeps {
405        stmt,
406        units,
407        doubles,
408    }
409}
410
411/// #3892: the double of a consumed context whose services the suite stubs, built
412/// over nothing so an unstubbed service throws a named error. Records
413/// `(surface key, local, value)` and returns the local, or `None` when no
414/// service of `ctx` is stubbed.
415fn stub_service_double(
416    stubs: &HashMap<String, ResolvedStub>,
417    ctx: &str,
418    key: &str,
419    surface_ty: &str,
420    doubles: &mut Vec<(String, String, TsExpr)>,
421) -> Option<String> {
422    let rp = stubs
423        .values()
424        .find(|rp| rp.service_context.as_deref() == Some(ctx))?;
425    let local = format!("__svc_{key}");
426    let value = stub_overlay(rp, surface_ty, Some(undefined_as_unknown_as(surface_ty)));
427    doubles.push((key.to_string(), local.clone(), value));
428    Some(local)
429}
430
431/// The `const __svc_<key> = …;` statements declaring each service double.
432fn service_double_consts(doubles: &[(String, String, TsExpr)]) -> Vec<TsStmt> {
433    doubles
434        .iter()
435        .map(|(_, local, value)| {
436            TsStmt::const_stmt(
437                TsBindingName::Ident(local.clone()),
438                None,
439                value.clone(),
440                None,
441            )
442        })
443        .collect()
444}
445
446/// The same doubles by their context's name at the top level of the deps, where
447/// `__bynkRecordDeps` wraps each operation to record its calls.
448fn service_double_entries(doubles: &[(String, String, TsExpr)]) -> Vec<(String, TsExpr)> {
449    doubles
450        .iter()
451        .map(|(key, local, _)| (key.clone(), ident(local.clone())))
452        .collect()
453}
454
455/// What [`emit_test_deps`] built (#1863).
456pub(super) struct TestDeps {
457    /// The `__makeTestDeps` declaration.
458    pub(super) stmt: TsStmt,
459    /// The units its providers name, which the test module imports.
460    pub(super) units: BTreeSet<String>,
461    /// Each `(owner, capability, name)` whose `__bynkTest_<name>` test double
462    /// it calls, which the test module defines (`platform_double`): `name` is
463    /// the capability, or a derived capability over it (S4a, #1966).
464    pub(super) doubles: Vec<(String, String, String)>,
465}
466
467/// One top-level test dep, built ([`emit_test_deps`]).
468pub(super) struct BuiltDep {
469    /// Its deps key: the capability's name.
470    pub(super) key: String,
471    /// The `(unit, capability)` it is.
472    pub(super) id: (String, String),
473    /// The local that holds it, when another dep is built over it.
474    pub(super) local: String,
475    /// Its value, `stub` overlay included.
476    pub(super) value: TsExpr,
477    /// The other deps' locals its construction names.
478    pub(super) used: BTreeSet<(String, String)>,
479}
480
481/// How a top-level test dep's value is built, before any `stub` overlay.
482pub(super) enum TopDep {
483    /// Its provider, through [`instantiate_provider_ts_expr`].
484    Provider,
485    /// A platform capability's deterministic test double (#291).
486    Double,
487    /// The `undefined` placeholder: no provider the test module can build.
488    Placeholder,
489}
490
491/// A capability of `owner` with a platform test double is [`TopDep::Double`];
492/// any other, the placeholder, whatever provides it in production.
493pub(super) fn platform_or_placeholder(owner: &str, cap: &str) -> TopDep {
494    if platform_double(owner, cap, &test_ns(owner), cap, false, None).is_some() {
495        TopDep::Double
496    } else {
497        TopDep::Placeholder
498    }
499}
500
501/// #18 (testing-track infra): a real value destructure plus a per-type alias,
502/// instead of one `const { … } = ns as any`. Every bynk-declared type pairs an
503/// `export type`/`export interface` with a companion runtime value
504/// (`export const X = {...}`, a refinement's `of`/`unsafe`, a sum's variant
505/// constructors, or simply `{}` for a plain record) — but destructuring does
506/// not carry the *type* side of that merge into the new local binding, so
507/// `const { X } = ns` alone leaves `X` usable only as a value. The blanket
508/// `as any` papered over that by disabling type-checking for every
509/// destructured name, not just the ones needing the workaround — which is
510/// exactly why this generator's own output couldn't be gated by
511/// `tsc --strict`: nothing inside a generated test body was ever really
512/// checked. `type_names` (a subset of `value_names`) gets the alias;
513/// `value_names` is unconditionally destructured with no cast.
514/// #1479: returns real [`TsStmt`]s (was `out: &mut String`) — every caller
515/// now appends via `crate::testgen::case_body::extend_printed_at(out, stmts, 2)`, the
516/// same depth-2 this scaffold body's own statements always printed at.
517/// #1703: each type name carries its type parameters, so a generic type's
518/// alias is generic too (`type Box<A> = ns.Box<A>;`). A bare alias of a generic
519/// type is `TS2314` under `tsc`, which failed every suite whose target declared
520/// or `uses` one, whether or not a case mentioned it. Build the list with
521/// [`aliased_types`].
522pub(super) fn emit_ns_destructure(
523    ns: &str,
524    value_names: &[String],
525    type_names: &[(String, Vec<String>)],
526) -> Vec<TsStmt> {
527    emit_ns_destructure_renamed(
528        ns,
529        value_names,
530        type_names,
531        &HashMap::new(),
532        &HashSet::new(),
533    )
534}
535
536/// [`emit_ns_destructure`] where `renames` (original → alias, #2887) binds a
537/// consumed type the unit renames with `consumes U { T as Alias }` under its
538/// alias: `const { T: Alias } = ns;` and `type Alias = ns.T`.
539/// `declared` holds the renamed names also bound under their declared name
540/// (#2890): a suite is not a consuming context, so a case names the type by it.
541pub(super) fn emit_ns_destructure_renamed(
542    ns: &str,
543    value_names: &[String],
544    type_names: &[(String, Vec<String>)],
545    renames: &HashMap<String, String>,
546    declared: &HashSet<String>,
547) -> Vec<TsStmt> {
548    let mut stmts = Vec::new();
549    if !value_names.is_empty() {
550        let pattern = value_names
551            .iter()
552            .flat_map(|n| match renames.get(n) {
553                Some(alias) => {
554                    let entry = format!("{n}: {alias}");
555                    if declared.contains(n) {
556                        vec![entry, n.clone()]
557                    } else {
558                        vec![entry]
559                    }
560                }
561                None => vec![n.clone()],
562            })
563            .collect();
564        stmts.push(TsStmt::const_stmt(
565            TsBindingName::ObjectPattern(pattern),
566            None,
567            ident(ns),
568            None,
569        ));
570    }
571    for (t, params) in type_names {
572        let target = format!("{ns}.{t}");
573        let ty = if params.is_empty() {
574            TsType::named(target)
575        } else {
576            TsType::named_with_args(target, params.iter().map(TsType::named).collect())
577        };
578        let mut names = vec![renames.get(t).unwrap_or(t).clone()];
579        if declared.contains(t) {
580            names.push(t.clone());
581        }
582        for name in names {
583            stmts.push(TsStmt::decl(
584                TsDecl::TypeAlias {
585                    name,
586                    type_params: params.clone(),
587                    ty: ty.clone(),
588                },
589                None,
590            ));
591        }
592    }
593    stmts
594}
595
596/// #2618: the names of `table`'s types not marked `private`.
597pub(super) fn public_types(table: &UnitTable) -> impl Iterator<Item = &String> {
598    table
599        .types
600        .iter()
601        .filter(|(_, d)| d.private.is_none())
602        .map(|(n, _)| n)
603}
604
605/// #2618: the names of `table`'s functions not marked `private`.
606pub(super) fn public_fns(table: &UnitTable) -> impl Iterator<Item = &String> {
607    table
608        .fns
609        .iter()
610        .filter(|(_, d)| d.private.is_none())
611        .map(|(n, _)| n)
612}
613
614/// #2618: whether `name` is a type of `table` not marked `private`.
615pub(super) fn is_public_type(table: &UnitTable, name: &str) -> bool {
616    table.types.get(name).is_some_and(|d| d.private.is_none())
617}
618
619/// #1703: the types of `table` that `keep` admits, each with its type
620/// parameters, sorted by name: the `type_names` [`emit_ns_destructure`] aliases.
621pub(super) fn aliased_types(
622    table: &UnitTable,
623    keep: impl Fn(&String) -> bool,
624) -> Vec<(String, Vec<String>)> {
625    let mut types: Vec<(String, Vec<String>)> = table
626        .types
627        .iter()
628        .filter(|(name, _)| keep(name))
629        .map(|(name, decl)| {
630            let params = decl
631                .type_params
632                .iter()
633                .map(|p| p.name.name.clone())
634                .collect();
635            (name.clone(), params)
636        })
637        .collect();
638    types.sort();
639    types
640}
641
642/// The target's own names, `(local, values)`, that hide a `uses` commons' name
643/// in a test scope.
644pub(super) fn target_names<'a>(
645    target_name: &str,
646    unit_tables: &'a HashMap<String, UnitTable>,
647) -> (HashSet<&'a String>, HashSet<&'a String>) {
648    // message-bundles slice 1 (#859): a name the target itself already
649    // declares must be excluded here — the same local-shadows-`uses`
650    // precedence `compose_unit_symbols` already applies to production
651    // emission (project.rs's `combined_fns`/`combined_types`), which this
652    // test-scaffold path builds independently and had never applied. Never
653    // exercised before this slice: no prior commons declared a name also
654    // present in something it `uses`. Without the filter, a target with its
655    // own `render` (a messages block's synthetic one) *and* `uses
656    // bynk.locale` (which also declares `render`) destructured both into one
657    // scope — `Cannot redeclare block-scoped variable 'render'` under `tsc`.
658    let target_local: HashSet<&String> = unit_tables
659        .get(target_name)
660        .map(|t| {
661            t.types
662                .keys()
663                .chain(t.fns.keys())
664                .chain(t.assets.keys())
665                .chain(t.embeds.keys())
666                .chain(t.consts.keys())
667                .collect()
668        })
669        .unwrap_or_default();
670    // #1925: a used commons' function or asset is hidden by any value the
671    // target declares — its services, agents and bodied providers too — as
672    // the checker's view hides it (`bynk_check::project_model::shadowed_imports`).
673    // #1927: so is a used commons' type's *value* (its constructors), which a
674    // case may not name (`check_shadowed_type_names_in_suite`). Its type
675    // alias (`type X = ns.X`, below) is still bound: it lives in TypeScript's
676    // type space, beside the target value's `const`, and the lowering names
677    // the types of checked expressions (`(__x: X) => …`, #1778).
678    let target_values: HashSet<&String> = unit_tables
679        .get(target_name)
680        .map(|t| {
681            target_local
682                .iter()
683                .copied()
684                .chain(t.services.keys())
685                .chain(t.agents.keys())
686                .chain(
687                    t.providers
688                        .values()
689                        .filter(|p| !p.external)
690                        .map(|p| &p.provider_name.name),
691                )
692                .collect()
693        })
694        .unwrap_or_default();
695    (target_local, target_values)
696}
697
698/// One commons' destructure: its namespace, the value names it binds, and the
699/// type aliases (each with its type parameters).
700pub(super) type NsDestructure = (String, Vec<String>, Vec<(String, Vec<String>)>);
701
702/// The `uses` commons' names a test scope binds, as `(namespace, value names,
703/// type aliases)` per commons: what a case runner destructures, and (#2947) a
704/// stub method that inlines suite helpers. One computation, so the two scopes
705/// hide and admit the same names.
706///
707/// `seen_assets` carries the assets already bound across calls: #1883, slice 3,
708/// a name brought in by an earlier used commons is not destructured again (two
709/// used commons may not share an asset name, `bynk.uses.name_conflict`, but an
710/// asset may share none with a fn either).
711pub(super) fn used_commons_destructures<'a>(
712    target_name: &str,
713    unit_tables: &'a HashMap<String, UnitTable>,
714    unit_uses: &HashMap<String, Vec<String>>,
715    seen_assets: &mut HashSet<&'a String>,
716) -> Vec<NsDestructure> {
717    let (target_local, target_values) = target_names(target_name, unit_tables);
718    let mut out = Vec::new();
719    if let Some(used) = unit_uses.get(target_name) {
720        for u in used {
721            let ns = test_ns(u);
722            if let Some(table) = unit_tables.get(u) {
723                // #2618: a used commons' `private` declarations stay in it, as
724                // the checker's suite view leaves them out; destructuring one
725                // would redeclare a public name another used commons binds.
726                let assets = table
727                    .assets
728                    .iter()
729                    .filter(|(_, d)| d.private.is_none())
730                    .map(|(n, _)| n)
731                    .filter(|n| seen_assets.insert(*n));
732                let embeds = table
733                    .embeds
734                    .iter()
735                    .filter(|(_, d)| d.private.is_none())
736                    .map(|(n, _)| n);
737                let consts = table
738                    .consts
739                    .iter()
740                    .filter(|(_, d)| d.private.is_none())
741                    .map(|(n, _)| n);
742                let mut names: Vec<String> = public_types(table)
743                    .chain(public_fns(table))
744                    .chain(assets)
745                    .chain(embeds)
746                    .chain(consts)
747                    .filter(|n| !target_values.contains(n))
748                    .cloned()
749                    .collect();
750                names.sort();
751                names.dedup();
752                let type_names = aliased_types(table, |n| {
753                    !target_local.contains(n) && is_public_type(table, n)
754                });
755                out.push((ns, names, type_names));
756            }
757        }
758    }
759    out
760}
761
762/// #1814: a suite view's hidden types grouped by owning commons, each group
763/// sorted by name.
764pub(super) fn hidden_by_owner(hidden: &BTreeMap<String, String>) -> BTreeMap<String, Vec<String>> {
765    let mut by_owner: BTreeMap<String, Vec<String>> = BTreeMap::new();
766    for (name, owner) in hidden {
767        by_owner
768            .entry(owner.clone())
769            .or_default()
770            .push(name.clone());
771    }
772    by_owner
773}
774
775/// #1814: destructure each hidden type from its owning commons' namespace,
776/// as a value and a type alias, the way a `uses` commons' types are: a
777/// lowered case spells a reached type (a kernel's `(__x: Repo) => …`), names
778/// a reached sum's variants (`Status.Done`) and calls its methods
779/// (`Repo.shout(…)`).
780pub(super) fn hidden_destructures(
781    hidden: &BTreeMap<String, Vec<String>>,
782    unit_tables: &HashMap<String, UnitTable>,
783) -> Vec<TsStmt> {
784    let mut stmts = Vec::new();
785    for (owner, names) in hidden {
786        let Some(table) = unit_tables.get(owner) else {
787            continue;
788        };
789        let type_names = aliased_types(table, |n| names.contains(n));
790        stmts.extend(emit_ns_destructure(&test_ns(owner), names, &type_names));
791    }
792    stmts
793}
794
795pub(super) fn sanitise_case_name(name: &str, index: &mut usize) -> String {
796    let mut s = String::from("test_");
797    for ch in name.chars() {
798        if ch.is_ascii_alphanumeric() {
799            s.push(ch);
800        } else {
801            s.push('_');
802        }
803    }
804    if s == "test_" {
805        s.push_str(&index.to_string());
806    }
807    *index += 1;
808    s
809}
810
811/// #1883, slice 3: the project's declared assets, for the test passes — each
812/// declaration's served path ([`bynk_check::assets::declared_served_paths`])
813/// and each declared file's bytes. Empty when no `assets/` folder was read.
814pub struct TestAssetFiles<'a> {
815    pub served: &'a BTreeMap<String, String>,
816    pub bytes: &'a BTreeMap<String, Vec<u8>>,
817    /// #2841: the text of each declared suite `fixture` file, by normalised path.
818    pub fixtures: &'a BTreeMap<String, String>,
819}
820
821/// #2134/#2956: a case's `env` entries as the object `__bynkEnv` is set to: a
822/// literal as itself, and a fixture as its module-level constant
823/// ([`fixture_ident`]), so its text is in the module once.
824pub(super) fn env_entries(
825    env: &BTreeMap<String, bynk_check::test_env::EnvValue>,
826) -> Vec<(String, TsExpr)> {
827    env.iter()
828        .map(|(k, v)| {
829            let value = match v {
830                bynk_check::test_env::EnvValue::Literal(s) => str_lit(s.clone()),
831                bynk_check::test_env::EnvValue::Fixture(path) => ident(fixture_ident(path)),
832            };
833            (k.clone(), value)
834        })
835        .collect()
836}
837
838/// #2841: the TypeScript identifier of the module-level constant holding a
839/// fixture file's text — a function of the normalised path alone, so suites that
840/// name one file share one constant and a runner can name it without state.
841pub(super) fn fixture_ident(path: &str) -> String {
842    let key = bynk_project::assets::normalise_asset_path(path);
843    let mut out = String::from("__fixture_");
844    for b in key.bytes() {
845        if b.is_ascii_alphanumeric() {
846            out.push(b as char);
847        } else {
848            out.push_str(&format!("_{b:02x}"));
849        }
850    }
851    out
852}
853
854/// #2841: one module-level `const <ident>: string = "<text>"` for each distinct
855/// fixture file the suites in `indices` declare, in path order — the text is in
856/// the test module once, however many suites and runners read it, and never
857/// anywhere else (a deployable is built without suites). `None` when no suite
858/// here declares a fixture, so a module without one is unchanged.
859pub(super) fn fixture_consts(
860    indices: &[usize],
861    parsed: &[ParsedFile],
862    files: &TestAssetFiles,
863) -> Option<Vec<TsStmt>> {
864    let mut paths: BTreeSet<String> = BTreeSet::new();
865    for &i in indices {
866        if let bynk_syntax::ast::SourceUnit::Suite(s) = parsed[i].unit() {
867            for f in &s.fixtures {
868                paths.insert(bynk_project::assets::normalise_asset_path(&f.path));
869            }
870        }
871    }
872    let mut stmts: Vec<TsStmt> = paths
873        .iter()
874        .filter_map(|p| {
875            let text = files.fixtures.get(p)?;
876            Some(TsStmt::const_stmt(
877                TsBindingName::Ident(fixture_ident(p)),
878                Some(TsType::named("string")),
879                TsExpr::Lit(TsLit::Str(text.clone())),
880                None,
881            ))
882        })
883        .collect();
884    if stmts.is_empty() {
885        return None;
886    }
887    // The constants sit on consecutive lines.
888    for stmt in stmts.iter_mut().skip(1) {
889        stmt.no_blank_before = true;
890    }
891    Some(stmts)
892}
893
894/// The name and type of the embedded asset table, which `runtime/src/testing/harness.ts` declares
895/// for `asset_get.ts` (the `the_harness_contract_matches_the_generator` test holds the two together).
896pub(super) const ASSET_FILES_NAME: &str = "__bynkAssetFiles";
897pub(super) const ASSET_FILES_TYPE: &str =
898    "Record<string, { readonly body: string; readonly contentType: string }>";
899
900/// #1883, slice 3 ([DECISION F]): the TypeScript that lets a case fetch an
901/// asset — the files `target`'s Worker ships
902/// ([`bynk_check::assets::deployed_assets`]), embedded base64 by served path
903/// with the platform's content type, and `__bynkAssetGet(url)`, which answers
904/// as the platform's asset tier does: `HttpResult.Raw(bytes, contentType)`
905/// for a shipped file, `NotFound` otherwise. Embedding keeps a suite free of
906/// disk access at test time; it is harness data, not the compile-time
907/// `String` embedding [DECISION E] excludes. `None` when the Worker ships no
908/// files, so a module without assets is unchanged.
909pub(super) fn asset_harness(
910    target: &str,
911    unit_uses: &HashMap<String, Vec<String>>,
912    unit_consumes: &HashMap<String, Vec<String>>,
913    unit_tables: &HashMap<String, UnitTable>,
914    files: &TestAssetFiles,
915) -> Option<Vec<TsStmt>> {
916    let deployed = bynk_check::assets::deployed_assets(
917        target,
918        unit_uses,
919        unit_consumes,
920        unit_tables,
921        files.served,
922    );
923    if deployed.is_empty() {
924        return None;
925    }
926    let entries: Vec<TsObjectEntry> = deployed
927        .iter()
928        .map(|(served, source)| {
929            // Review of #1922: every deployed file was read (`asset_served`
930            // comes from the same bytes), so a miss is a broken invariant, not
931            // something to degrade quietly into an undefined `__bynkAssetGet`.
932            let bytes = files.bytes.get(source).unwrap_or_else(|| {
933                panic!(
934                    "bynk internal error: deployed asset `{source}` has no bytes for the test harness"
935                )
936            });
937            TsObjectEntry::prop(
938                bynk_project::json_string(served),
939                TsExpr::object(vec![
940                    ("body".to_string(), crate::ts_build::str_lit(base64(bytes))),
941                    (
942                        "contentType".to_string(),
943                        crate::ts_build::raw_lit(bynk_project::json_string(
944                            bynk_check::assets::content_type_for(served),
945                        )),
946                    ),
947                ]),
948            )
949        })
950        .collect();
951    let table = TsStmt::const_stmt(
952        TsBindingName::Ident(ASSET_FILES_NAME.to_string()),
953        Some(TsType::named(ASSET_FILES_TYPE)),
954        TsExpr::multiline_object_entries(entries),
955        None,
956    );
957    // The getter follows the table's last line directly.
958    let mut getter = TestRuntimeModule::AssetGet.splice();
959    getter.no_blank_before = true;
960    Some(vec![table, getter])
961}
962
963/// #1883, slice 3: each asset a `system` case may name ([`SuiteView::assets`]),
964/// grouped by the unit that declares it — a participant first (whose
965/// `handlers.js` exports its own assets), then the commons that declare the
966/// rest — sorted.
967pub(super) fn system_asset_owners(
968    view: &test_suites::SuiteView,
969    participants: &[String],
970    unit_tables: &HashMap<String, UnitTable>,
971) -> BTreeMap<String, Vec<String>> {
972    let mut owners: BTreeMap<String, Vec<String>> = BTreeMap::new();
973    for (name, decl) in &view.assets {
974        let owner = unit_tables
975            .iter()
976            .filter(|(_, t)| {
977                t.assets
978                    .get(name)
979                    .is_some_and(|d| d.path == decl.path && d.at == decl.at)
980            })
981            .map(|(u, _)| u)
982            .min_by_key(|u| (!participants.contains(u), (*u).clone()));
983        if let Some(owner) = owner {
984            owners.entry(owner.clone()).or_default().push(name.clone());
985        }
986    }
987    for names in owners.values_mut() {
988        names.sort();
989    }
990    owners
991}
992
993/// Standard base64 (RFC 4648, with padding) of `bytes`, for
994/// [`asset_harness`]'s embedded files.
995pub(super) fn base64(bytes: &[u8]) -> String {
996    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
997    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
998    for chunk in bytes.chunks(3) {
999        let b = [
1000            chunk[0],
1001            *chunk.get(1).unwrap_or(&0),
1002            *chunk.get(2).unwrap_or(&0),
1003        ];
1004        let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
1005        for (i, shift) in [18u32, 12, 6, 0].into_iter().enumerate() {
1006            if i <= chunk.len() {
1007                out.push(ALPHABET[((n >> shift) & 63) as usize] as char);
1008            } else {
1009                out.push('=');
1010            }
1011        }
1012    }
1013    out
1014}
1015
1016/// `deps.__session`, for a handler's `Actor.issue(identity)`: every `SignedCookie` actor of the target
1017/// signs with the fixed `TEST_SESSION_KEY`, so an issued cookie is the same on every run. The `system`
1018/// tier signs with the key it sets on the deployed Worker instead.
1019fn session_keys_entry(
1020    target_name: &str,
1021    target_kind: UnitKind,
1022    unit_tables: &HashMap<String, UnitTable>,
1023) -> Option<(String, TsExpr)> {
1024    if target_kind != UnitKind::Context {
1025        return None;
1026    }
1027    let mut actors: Vec<String> = unit_tables
1028        .get(target_name)?
1029        .actors
1030        .values()
1031        .filter_map(|a| bynk_check::actors::signed_cookie_seam_of(a, None))
1032        .map(|s| s.actor)
1033        .collect();
1034    if actors.is_empty() {
1035        return None;
1036    }
1037    actors.sort();
1038    let keys = actors
1039        .into_iter()
1040        .map(|a| {
1041            (
1042                a,
1043                TsExpr::object(vec![("secret".to_string(), str_lit(TEST_SESSION_KEY))]),
1044            )
1045        })
1046        .collect();
1047    Some(("__session".to_string(), TsExpr::object(keys)))
1048}
1049
1050#[cfg(test)]
1051mod tests {
1052    use super::*;
1053
1054    #[test]
1055    fn sanitise_case_name_prefixes_and_advances_index() {
1056        let mut idx = 0;
1057        assert_eq!(
1058            sanitise_case_name("hello world", &mut idx),
1059            "test_hello_world"
1060        );
1061        assert_eq!(idx, 1); // index advances on every call
1062        assert_eq!(sanitise_case_name("a-b.c", &mut idx), "test_a_b_c");
1063        assert_eq!(idx, 2);
1064    }
1065
1066    #[test]
1067    fn sanitise_case_name_appends_index_only_for_empty_name() {
1068        let mut idx = 5;
1069        assert_eq!(sanitise_case_name("", &mut idx), "test_5"); // empty -> index suffix
1070        assert_eq!(idx, 6);
1071        // A name of only non-alphanumeric chars is NOT "test_", so no suffix.
1072        let mut idx2 = 9;
1073        assert_eq!(sanitise_case_name(" ", &mut idx2), "test__");
1074        assert_eq!(idx2, 10);
1075    }
1076
1077    // -- coerce_int_field (#1398, review of #1428) ---------------------------
1078}