Skip to main content

bynk_driver/project/
agent_deps.rs

1use bynk_check::symbols::UnitTable;
2use bynk_emit::emit_model::ExtraImport;
3use bynk_emit::emit_model::ProviderNamespaces;
4use bynk_emit::emit_model::instantiate_provider_ts_expr;
5use std::collections::{BTreeMap, BTreeSet, HashMap};
6
7use bynk_check::project_model::{AdapterBinding, UnitInfo, resolve_consume_prefix};
8use bynk_model::CapRefIr;
9use bynk_model::lower_handler_given_ir;
10use bynk_project::worker_layout::WorkerLayout;
11
12/// #527: the DO-side deps plan for one workers context. Capability providers
13/// cannot cross the DO wire (`{ args, deps }` is JSON — a provider's methods
14/// die in serialisation), so the generated Durable Object reconstructs its
15/// agents' `given` deps *inside* the DO from the same wiring compose uses.
16#[derive(Debug, Default, Clone)]
17pub struct AgentDepsPlan {
18    /// agent name → TS object-literal expression for its `given` deps
19    /// (e.g. `{ Clock: new bynk__binding.ClockProvider() }`).
20    pub exprs: HashMap<String, String>,
21    /// agent name → the namespace aliases its expression spells (`bynk__binding`,
22    /// `handlers_shop_orders`). The emitter declares them with the text, so each module's imports
23    /// follow its tree (1A.36b-2).
24    pub names: HashMap<String, Vec<String>>,
25    /// Imports the expressions need in `handlers.ts` (binding modules,
26    /// other Workers' handlers). Same relative depth as `compose.ts`.
27    pub imports: Vec<ExtraImport>,
28}
29
30/// Build the [`AgentDepsPlan`] for context `name`, or `None` when no local
31/// agent has `given` capabilities.
32///
33/// `split`: the context spans several files, each emitted as its own module
34/// under `handlers/` (#1820, [`worker_file_source_path`](bynk_project::paths::worker_file_source_path)). The imports are
35/// then one directory deeper, and this context's own providers are no longer
36/// in the agent's module, so they are reached through `handlers.ts` like
37/// another context's. That import is circular (`handlers.ts` re-exports the
38/// agent's module), which is safe: the expressions are evaluated in the
39/// Durable Object's fetch dispatch, never while the modules load.
40pub(super) fn plan_agent_given_deps(
41    name: &str,
42    unit_info: &BTreeMap<String, UnitInfo>,
43    adapter_bindings: &HashMap<String, AdapterBinding>,
44    split: bool,
45    // #2137: whether a `system` harness stands this context up (test build).
46    harness_clock: bool,
47    layout: &WorkerLayout,
48) -> Option<AgentDepsPlan> {
49    let info = unit_info.get(name)?;
50    info.table.agents.values().next()?;
51    let unit_tables: HashMap<String, UnitTable> = unit_info
52        .iter()
53        .map(|(n, i)| (n.clone(), i.table.clone()))
54        .collect();
55    let unit_consumes: HashMap<String, Vec<String>> = unit_info
56        .iter()
57        .map(|(n, i)| (n.clone(), i.consumes.clone()))
58        .collect();
59    let unit_consumes_aliases: HashMap<String, HashMap<String, String>> = unit_info
60        .iter()
61        .map(|(n, i)| (n.clone(), i.aliases.clone()))
62        .collect();
63    let unit_flattened: HashMap<String, HashMap<String, String>> = unit_info
64        .iter()
65        .map(|(n, i)| (n.clone(), i.flattened.clone()))
66        .collect();
67
68    let mut referenced: BTreeSet<String> = BTreeSet::new();
69    let mut exprs: HashMap<String, String> = HashMap::new();
70    let mut names: HashMap<String, Vec<String>> = HashMap::new();
71    // P6.35 (design/tracks/the-ir.md §6a): no explicit `&AgentDecl` annotation
72    // needed — the loop body's own `a.handlers` field access below already
73    // pins the element type through inference.
74    let mut agents: Vec<_> = info.table.agents.iter().collect();
75    agents.sort_by_key(|(n, _)| (*n).clone());
76    for (agent, a) in agents {
77        // #1187's slice 6 (Agent/Service given wiring): reads bynk-emit::ir's
78        // own CapRefIr (lower_handler_given_ir — a standalone reader mirroring
79        // lower_provider_given_ir, #1200) instead of walking the raw AST
80        // CapRef directly. `caps` stays keyed by bare name (declaration-order-
81        // first dedup across every handler), just storing CapRefIr instead of
82        // CapRef.
83        let mut caps: std::collections::BTreeMap<String, CapRefIr> =
84            std::collections::BTreeMap::new();
85        for h in &a.handlers {
86            for g in lower_handler_given_ir(h) {
87                // Events track, slice 0 (spine #936): see the matching skip
88                // in `handler_cross_caps` — no `EventsProvider` exists for
89                // compose (or a synthesised DO's own reconstructed deps) to
90                // build.
91                if g.name == "Events"
92                    && info.flattened.get(g.name.as_str()).map(String::as_str) == Some("bynk")
93                {
94                    continue;
95                }
96                caps.entry(g.name.clone()).or_insert(g);
97            }
98        }
99        if caps.is_empty() {
100            continue;
101        }
102        // Arc F slice 2 (#1452): `instantiate_provider_ts_expr` — the
103        // tree-native twin `emit_worker_compose`/`emit_composition_root`
104        // already use (#1321/#1327) — builds the same `new {ns}.{Class}(...)`
105        // shape as a real `bynk_ts::TsExpr`, byte-identical once printed
106        // (both share every recursive call/text-building step below the
107        // top level; only this per-agent object wrapper is new). Boundary-
108        // prints once, here, into `exprs: HashMap<String, String>` — the
109        // struct's own shape and `emit_agent`'s `TsExpr::Ident(expr.clone())`
110        // caller (`emitter/emit.rs`) both stay unchanged, the narrower of
111        // the two options the issue named.
112        let mut agent_referenced: BTreeSet<String> = BTreeSet::new();
113        let entries: Vec<(String, bynk_ts::TsExpr)> = caps
114            .iter()
115            .map(|(key, g)| {
116                let target_ctx = match &g.context {
117                    Some(p) => resolve_consume_prefix(p, &info.consumes, &info.aliases)
118                        .unwrap_or_else(|| name.to_string()),
119                    None => info
120                        .flattened
121                        .get(key.as_str())
122                        .cloned()
123                        .unwrap_or_else(|| name.to_string()),
124                };
125                let expr = instantiate_provider_ts_expr(
126                    &target_ctx,
127                    key,
128                    &unit_tables,
129                    &unit_consumes,
130                    &unit_consumes_aliases,
131                    &unit_flattened,
132                    ProviderNamespaces::Workers { harness_clock },
133                    Some("env"),
134                    None,
135                    &mut agent_referenced,
136                );
137                (key.clone(), expr)
138            })
139            .collect();
140        referenced.extend(agent_referenced.iter().cloned());
141        names.insert(agent.clone(), agent_referenced.into_iter().collect());
142        exprs.insert(
143            agent.clone(),
144            bynk_ts::print_expr(&bynk_ts::TsExpr::object(entries)),
145        );
146    }
147    if exprs.is_empty() {
148        return None;
149    }
150    // Providers of *this* context live in the same module (`handlers.ts`), so
151    // their compose-namespace prefix drops. Not for a split context: there
152    // they are imported from `handlers.ts` like any other context's (`../`
153    // up from `handlers/` to the Worker's own directory, then back down).
154    let self_ns = format!("handlers_{}.", name.replace('.', "_"));
155    if !split {
156        for e in exprs.values_mut() {
157            *e = e.replace(&self_ns, "");
158        }
159        referenced.remove(name);
160    }
161    let up = if split { "../" } else { "" };
162    // The aliases each agent's expression spells: the namespace of every unit it references,
163    // bar this context's own where the module holds its providers itself (`self_ns` above).
164    let alias_of = |u: &str| {
165        let ns = u.replace('.', "_");
166        if adapter_bindings.contains_key(u) {
167            format!("{ns}__binding")
168        } else {
169            format!("handlers_{ns}")
170        }
171    };
172    let names: HashMap<String, Vec<String>> = names
173        .into_iter()
174        .map(|(agent, units)| {
175            let aliases = units
176                .iter()
177                .filter(|u| split || u.as_str() != name)
178                .map(|u| alias_of(u))
179                .collect();
180            (agent, aliases)
181        })
182        .collect();
183    let mut imports = Vec::new();
184    for u in &referenced {
185        let ns = u.replace('.', "_");
186        if let Some(b) = adapter_bindings.get(u) {
187            let module = bynk_emit::emitter::ts_specifier(&b.output_path.with_extension("js"));
188            imports.push(ExtraImport::Namespace {
189                alias: format!("{ns}__binding"),
190                from: format!("{up}../../{module}"),
191            });
192        } else {
193            // A split context's modules sit one directory below its Worker's.
194            let spec = layout.handlers_specifier(name, u);
195            let spec = if split {
196                format!("../{}", spec.strip_prefix("./").unwrap_or(&spec))
197            } else {
198                spec
199            };
200            imports.push(ExtraImport::Namespace {
201                alias: format!("handlers_{ns}"),
202                from: spec,
203            });
204        }
205    }
206    Some(AgentDepsPlan {
207        exprs,
208        names,
209        imports,
210    })
211}