bynk_emit/emitter/compose/bundle.rs
1//! The Bundle composition root (`compose.ts`, `composeApp()`).
2//!
3//! Moved here from `bynk-driver/src/project.rs` by back-half paydown 1B.1a
4//! (Decision B of #3928): it is the Bundle target's production output.
5//! Since 1B.1b it reads the units, their dependencies and their cross-context
6//! capabilities from the [`ComposePlan`]; the order of a unit's `deps` entries,
7//! the spelling of each provider and the `__exec` condition are this
8//! renderer's own (divergences 1, 2, 3 and 4 of #3928).
9
10use std::collections::{BTreeSet, HashMap};
11
12use crate::emit_model::*;
13use crate::emitter;
14use crate::emitter::compose::events::isolated_delivery;
15use crate::emitter::compose::{ComposePlan, empty_deps};
16use crate::ts_build::{call, const_, ident, member, method_call, str_lit};
17use bynk_check::project_model::AdapterBinding;
18use bynk_check::symbols::UnitTable;
19use bynk_project::paths::commons_dir_for;
20use bynk_ts::{TsArrowBody, TsDecl, TsExpr, TsParam, TsProgram, TsStmt, TsSwitchCase, TsType};
21
22/// Where `compose.ts` imports the runtime from (it sits at the out root).
23///
24/// The import is built from the finished tree (`derived_runtime_names`) and
25/// inserted after the banner, so this is the one place the specifier is
26/// spelled.
27const COMPOSE_RUNTIME_SPECIFIER: &str = "./runtime.js";
28
29// -- Small tree-construction helpers (#1327) ------------------------------
30/// Divergence 1 of #3928, the Bundle's entry order: sort key for a `{ns}Deps` entry, mirroring the pre-conversion code's own
31/// `Vec<String>::sort()` over the fully rendered `"{key}: {value}"` text
32/// rather than the bare key alone (review of #1328: `deps_entries.sort_by(|a,
33/// b| a.0.cmp(&b.0))` is NOT equivalent — it silently reorders whenever one
34/// key is a strict prefix of another, e.g. `Db`/`Db2`). The old text sort's
35/// tie-break, for a key that is a strict prefix of another, was whatever byte
36/// immediately follows it in the longer key compared against the shorter
37/// key's own literal `':'` — since capability names are `[A-Za-z][A-Za-z0-9_
38/// ]*`, only a digit-suffixed prefix collision (`'0'`-`'9'` are all below
39/// `':'`, 0x3A) flips the order: `Db2: ...` sorted before `Db: ...` because
40/// `'2'` (0x32) < `':'` (0x3A). Appending `:` to each bare key reproduces
41/// that exact tie-break without rendering each entry's value just to sort
42/// it — every other key relationship (no shared prefix, or a
43/// letter/underscore-suffixed prefix, both above `':'`) is unaffected, since
44/// the comparison never reaches the appended `:`.
45fn deps_entry_sort_key(key: &str) -> String {
46 format!("{key}:")
47}
48
49/// #2683: a `call` handler that calls `within` (or sends) reads `deps.__exec`.
50/// The bundle has no platform execution context, so what it is handed is kept
51/// alive by the process; a fault in it, with no handler left to raise it to, is
52/// reported by the same reporter `e.detach()` uses (#3541), not a logger of the
53/// shim's own. Divergence 4 of #3928: the Bundle gives it to a unit whose
54/// `call` handler needs one (the Workers `compose` to any handler), and as
55/// `__bynkProcessExec()`, not the request's `exec`.
56fn bundle_process_exec_entry(needs_exec: bool) -> Option<(String, TsExpr)> {
57 needs_exec.then(|| {
58 (
59 "__exec".to_string(),
60 call(ident("__bynkProcessExec"), Vec::new()),
61 )
62 })
63}
64
65/// Events track, slice 0 (spine #936): the `__eventsDispatch` closure of a
66/// publishing context. Bundle/node mode has no isolate boundary to cross, so
67/// this dispatches in-process, directly into each subscriber's own `on event`
68/// handler (`.event`, the object method `emit_service` gives
69/// `HandlerKind::Event`), reusing whatever deps that subscriber context builds
70/// in the same `composeApp` (referenced by name; the arrow's body is not
71/// evaluated until well after every `const ...Deps` has run, so declaration
72/// order does not matter). A publisher with no subscribers still gets the
73/// field, as its type is required, with an empty switch.
74///
75/// Each delivery is the shared failure-isolated one (ADR 0284,
76/// [`isolated_delivery`]); whether it carries the envelope is the plan's
77/// per-subscription `wants_envelope` (Decision F of #3928).
78fn events_dispatch(plan: &ComposePlan, publisher: &str) -> TsExpr {
79 // #3815: the plan's events are in name order, so the cases do not vary from
80 // one build to the next (the table they came from is a `HashMap`).
81 let cases: Vec<TsSwitchCase> = plan
82 .events
83 .published_by(publisher)
84 .map(|(event, subs)| {
85 let mut body: Vec<TsStmt> = subs
86 .iter()
87 .map(|sub| {
88 let sub_ns = sub.context.replace('.', "_");
89 // P7.2: deferred, not narrowed. The event's bare name is not
90 // necessarily in scope at this dispatch site
91 // (cross-context: publisher and subscriber are different
92 // units), the same qualification problem
93 // `ts_type_ref_qualified_ts_type` exists to solve for
94 // handler wrappers elsewhere in this crate, so the payload
95 // stays `any`.
96 let mut args = vec![as_any(member(ident("ev"), "payload"))];
97 if sub.wants_envelope {
98 args.push(member(ident("ev"), "envelope"));
99 }
100 args.push(ident(format!("{sub_ns}Deps")));
101 let delivery = call(
102 member(member(ident(sub_ns), sub.service.as_str()), "event"),
103 args,
104 );
105 isolated_delivery(delivery, str_lit(sub.service.as_str()))
106 })
107 .collect();
108 body.push(TsStmt::break_stmt(None));
109 TsSwitchCase {
110 labels: vec![str_lit(event)],
111 body,
112 default_braced: false,
113 case_braced: true,
114 span: None,
115 }
116 })
117 .collect();
118 let dispatch = TsStmt::for_of(
119 "ev",
120 ident("events"),
121 TsStmt::block(
122 vec![TsStmt::switch_stmt(
123 member(ident("ev"), "type"),
124 cases,
125 None,
126 )],
127 None,
128 ),
129 None,
130 );
131 TsExpr::Arrow {
132 params: vec![TsParam::new(
133 "events".to_string(),
134 Some(TsType::named_with_args(
135 "globalThis.Array",
136 vec![TsType::named(crate::emitter::EVENTS_WIRE_EVENT_TS_TYPE)],
137 )),
138 )],
139 is_async: true,
140 generics: Vec::new(),
141 return_type: None,
142 body: Box::new(TsArrowBody::Multiline(vec![dispatch])),
143 }
144}
145
146fn as_any(expr: TsExpr) -> TsExpr {
147 TsExpr::As {
148 expr: Box::new(expr),
149 ty: TsType::named("any"),
150 }
151}
152
153#[allow(clippy::too_many_arguments)]
154pub fn emit_composition_root(
155 plan: &ComposePlan,
156 unit_consumes: &HashMap<String, Vec<String>>,
157 unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
158 unit_tables: &HashMap<String, UnitTable>,
159 adapter_bindings: &HashMap<String, AdapterBinding>,
160 unit_flattened: &HashMap<String, HashMap<String, String>>,
161 // v0.19 (decision 0025, D1): when the program's closure reaches a
162 // platform-native unit, composeApp takes an optional `env` and threads it
163 // to env-taking first-party providers. A bundle on Cloudflare is a single
164 // Worker with `env` at its entry; native-free programs emit the v0.18
165 // no-parameter signature unchanged.
166 thread_env: bool,
167) -> Option<TsProgram> {
168 if !plan.bundle_root {
169 return None;
170 }
171
172 // The composeApp body is built first so the provider expressions can
173 // record every unit namespace they reference (v0.18: an external
174 // provider's `given` may pull in *another* adapter's binding — the
175 // transitive given-closure — which must then be imported).
176 let mut referenced_units: BTreeSet<String> = BTreeSet::new();
177
178 let compose_params: Vec<TsParam> = if thread_env {
179 vec![TsParam::optional(
180 "env".to_string(),
181 Some(TsType::named("unknown")),
182 )]
183 } else {
184 Vec::new()
185 };
186 let env_ident = if thread_env { Some("env") } else { None };
187
188 let mut body: Vec<TsStmt> = Vec::new();
189
190 // The plan's order puts a consumed context before its consumer, and holds
191 // only the contexts the root composes: a context's deps object exists only
192 // to feed its `__makeSurface`, so a capability-only context (no services)
193 // needs neither (v0.15). The bundle's `bynk.capability.not_provided` check
194 // skips the same ones.
195 for ctx_name in &plan.bundle_order {
196 let unit = &plan.units[ctx_name];
197 let ns = ctx_name.replace('.', "_");
198
199 // Divergence 2 of #3928, provider spelling: each provider is one
200 // inline expression, recursing through its `given` (the Workers
201 // `compose` builds a `const` per provider in dependency order).
202 let mut deps_entries: Vec<(String, TsExpr)> = unit
203 .providers
204 .iter()
205 .map(|cap| {
206 let expr = instantiate_provider_ts_expr(
207 ctx_name,
208 cap,
209 unit_tables,
210 unit_consumes,
211 unit_consumes_aliases,
212 unit_flattened,
213 ProviderNamespaces::Bundle,
214 env_ident,
215 None, // Bundle mode has no inbound request (Decision A)
216 &mut referenced_units,
217 );
218 (cap.clone(), expr)
219 })
220 .collect();
221 // v0.15: cross-context capabilities used directly by handlers become
222 // top-level deps fields, instantiated from the providing context.
223 // Divergence 3 of #3928, the cross-capability set: the handlers' only.
224 // A provider's own cross-context `given` is reached through that
225 // provider's recursive expression, not as a top-level field (the
226 // Workers `compose` also lifts the providers').
227 for (key, cctx) in &unit.handler_cross_caps {
228 let expr = instantiate_provider_ts_expr(
229 cctx,
230 key,
231 unit_tables,
232 unit_consumes,
233 unit_consumes_aliases,
234 unit_flattened,
235 ProviderNamespaces::Bundle,
236 env_ident,
237 None, // Bundle mode has no inbound request (Decision A)
238 &mut referenced_units,
239 );
240 deps_entries.push((key.clone(), expr));
241 }
242 // S4a (#1966): each derived capability's instance.
243 for cap in &unit.derived {
244 let expr = instantiate_provider_ts_expr(
245 ctx_name,
246 cap,
247 unit_tables,
248 unit_consumes,
249 unit_consumes_aliases,
250 unit_flattened,
251 ProviderNamespaces::Bundle,
252 env_ident,
253 None,
254 &mut referenced_units,
255 );
256 deps_entries.push((cap.clone(), expr));
257 }
258 if unit.publishes {
259 deps_entries.push((
260 "__eventsDispatch".to_string(),
261 events_dispatch(plan, ctx_name),
262 ));
263 }
264 if let Some(entry) = bundle_process_exec_entry(unit.exec.call_handler) {
265 deps_entries.push(entry);
266 }
267 deps_entries.sort_by_cached_key(|(k, _)| deps_entry_sort_key(k));
268
269 // Divergence 6 of #3928, the consumed surfaces: only the Bundle's
270 // `deps` carries a consumed context's surface (the Workers reach it
271 // through a Service Binding).
272 let mut surface_entries: Vec<(String, TsExpr)> = Vec::new();
273 for surface in &unit.surfaces {
274 let t_ns = surface.target.replace('.', "_");
275 // v0.54 (#655): a consumed context with an `on call … by c: Caller`
276 // handler needs the *caller's* qualified name (this context) threaded
277 // into that handler's deps as its `CallerId` identity (ADR 0092). The
278 // shared `{t_ns}Surface` (built for the top-level entry with the
279 // provider's own name) would carry the wrong caller, so build a
280 // per-consumer surface instead. A caller-free provider keeps the
281 // shared instance — byte-unchanged.
282 let entry = if surface.per_caller {
283 method_call(
284 ident(t_ns.clone()),
285 "__makeSurface",
286 vec![ident(format!("{t_ns}Deps")), str_lit(ctx_name.as_str())],
287 )
288 } else {
289 ident(format!("{t_ns}Surface"))
290 };
291 surface_entries.push((surface.key.clone(), entry));
292 }
293 if !surface_entries.is_empty() {
294 deps_entries.push(("surface".to_string(), TsExpr::object(surface_entries)));
295 }
296 // `{ }` for no entries: see `compose::empty_deps`.
297 let deps_init = if deps_entries.is_empty() {
298 empty_deps()
299 } else {
300 TsExpr::object(deps_entries)
301 };
302 body.push(const_(format!("{ns}Deps"), deps_init));
303 if unit.has_services {
304 // The top-level entry addresses the context directly; there is no
305 // calling context, so a `by c: Caller` handler reached this way reads
306 // the context's own qualified name (a stable, non-empty `CallerId`
307 // within the single-trust-domain bundle).
308 let mut make_surface_args = vec![ident(format!("{ns}Deps"))];
309 if unit.binds_caller {
310 make_surface_args.push(str_lit(ctx_name.as_str()));
311 }
312 body.push(const_(
313 format!("{ns}Surface"),
314 method_call(ident(ns.clone()), "__makeSurface", make_surface_args),
315 ));
316 }
317 }
318
319 // #1327: the pre-conversion code unconditionally wrote one blank line
320 // between the last `const ...Deps`/`const ...Surface` and the `return`
321 // (`out.push('\n')`, run once regardless of how many contexts the loop
322 // above actually pushed) — `TsStmtKind::Blank` (#1323) is the tree's own
323 // equivalent, needed here since the printer's own "blank line between
324 // top-level declarations" policy only separates entries in
325 // `TsProgram.stmts` itself, not statements inside one function body.
326 body.push(TsStmt::blank(None));
327
328 // Export per-context surfaces under a top-level object.
329 let mut return_entries: Vec<(String, TsExpr)> = Vec::new();
330 for (ctx_name, unit) in plan.contexts() {
331 if !unit.has_services {
332 continue;
333 }
334 let ns = ctx_name.replace('.', "_");
335 let key = ctx_name.rsplit('.').next().unwrap_or(ctx_name.as_str());
336 return_entries.push((key.to_string(), ident(format!("{ns}Surface"))));
337 }
338 body.push(TsStmt::return_stmt(
339 Some(TsExpr::multiline_object(return_entries)),
340 None,
341 ));
342
343 // Assemble the header now that the body has recorded which units its
344 // provider expressions reference.
345 let mut program = TsProgram::new();
346 program.push(TsStmt::comment(
347 "Generated by bynk — do not edit by hand.",
348 None,
349 ));
350 program.push(TsStmt::comment("composition root", None));
351 // The runtime import is what the finished tree uses (Decision G of #3928),
352 // inserted here once the function is built.
353 let runtime_import_at = program.stmts.len();
354
355 // Import every context as a namespace.
356 for (ctx_name, _) in plan.contexts() {
357 let dir = emitter::ts_specifier(&commons_dir_for(ctx_name));
358 let ns = ctx_name.replace('.', "_");
359 program.push(TsStmt::decl(
360 TsDecl::ImportNamespace {
361 type_only: false,
362 alias: ns,
363 from: format!("./{dir}.js"),
364 },
365 None,
366 ));
367 }
368 // v0.17: import each consumed adapter's binding module — the external
369 // provider classes live there, not in the adapter's interface module.
370 // v0.18: plus every adapter the provider expressions referenced through
371 // the transitive given-closure (an adapter's external provider may depend
372 // on another adapter's capability, spec §4.5).
373 let mut consumed_adapters: Vec<String> = plan
374 .contexts()
375 .flat_map(|(_, unit)| unit.consumes.iter().cloned())
376 .chain(referenced_units.iter().cloned())
377 .filter(|t| adapter_bindings.contains_key(t))
378 .collect();
379 consumed_adapters.sort();
380 consumed_adapters.dedup();
381 for adapter in &consumed_adapters {
382 let ns = adapter.replace('.', "_");
383 let module =
384 emitter::ts_specifier(&adapter_bindings[adapter].output_path.with_extension("js"));
385 program.push(TsStmt::decl(
386 TsDecl::ImportNamespace {
387 type_only: false,
388 alias: format!("{ns}__binding"),
389 from: format!("./{module}"),
390 },
391 None,
392 ));
393 }
394
395 program.push(TsStmt::decl(
396 TsDecl::Export(Box::new(TsDecl::Function {
397 name: "composeApp".to_string(),
398 generics: Vec::new(),
399 params: compose_params,
400 return_type: None,
401 body,
402 is_async: false,
403 inline: false,
404 })),
405 None,
406 ));
407
408 let names = emitter::runtime_header::derived_runtime_names(&program.stmts[runtime_import_at..]);
409 for (i, stmt) in
410 emitter::runtime_files::runtime_import_stmts(false, &names, COMPOSE_RUNTIME_SPECIFIER)
411 .into_iter()
412 .enumerate()
413 {
414 program.stmts.insert(runtime_import_at + i, stmt);
415 }
416 // A namespace is imported for every unit the closure reaches; the tree keeps the ones it uses.
417 program.prune_unused_imports();
418 Some(program)
419}
420
421#[cfg(test)]
422mod tests {
423 use super::*;
424
425 /// Review of #1328: the pre-conversion code sorted the fully rendered
426 /// `"{key}: {value}"` text, so a key that is a strict prefix of another
427 /// (`Db`/`Db2`) sorted by the shorter key's own `':'` losing to the
428 /// longer key's next byte, a digit — `Db2: ...` sorted before `Db:
429 /// ...`. A bare-key sort (`"Db" < "Db2"`) gets this backwards.
430 /// `deps_entry_sort_key` must reproduce the original order exactly.
431 #[test]
432 fn deps_entry_sort_key_reproduces_the_pre_conversion_full_text_sort_order() {
433 let mut keys = vec!["Db2".to_string(), "Db".to_string()];
434 keys.sort_by_cached_key(|k| deps_entry_sort_key(k));
435 assert_eq!(
436 keys,
437 vec!["Db2".to_string(), "Db".to_string()],
438 "Db2 must sort before Db, matching the old full-text sort"
439 );
440
441 // A letter/underscore-suffixed prefix collision is unaffected —
442 // matches plain key ordering both before and after this fix.
443 let mut keys = vec!["Db_pool".to_string(), "Db".to_string()];
444 keys.sort_by_cached_key(|k| deps_entry_sort_key(k));
445 assert_eq!(keys, vec!["Db".to_string(), "Db_pool".to_string()]);
446
447 // No shared prefix at all: ordinary alphabetical order, unaffected.
448 let mut keys = vec!["Queue".to_string(), "Cache".to_string()];
449 keys.sort_by_cached_key(|k| deps_entry_sort_key(k));
450 assert_eq!(keys, vec!["Cache".to_string(), "Queue".to_string()]);
451 }
452}