bynk_emit/emitter/commons_barrel.rs
1//! The commons barrel: an aggregating `out/<name>.ts` for a multi-file commons or context.
2//!
3//! Production output (#1820): a multi-file context's barrel is part of a production bundle
4//! build, so it lives here and not in `testgen`. Moved out of the test-harness generator
5//! unchanged (1B.2a, #4028).
6
7use crate::emit_model::{Document, ImportExt, StagedFile};
8use crate::ts_build::{ident, method_call};
9use bynk_project::UnitKind;
10use bynk_project::discovery::*;
11use bynk_project::paths::*;
12use bynk_project::worker_layout::WorkerLayout;
13use bynk_ts::{TsDecl, TsExpr, TsObjectEntry, TsParam, TsProgram, TsStmt, TsType};
14use std::collections::{BTreeMap, HashSet};
15use std::path::{Path, PathBuf};
16
17/// v0.132: an aggregating barrel for a commons split across a directory.
18///
19/// Production emits a multi-file commons per file (`out/<name>/*.ts`) and never
20/// an aggregate `out/<name>.ts`, but every test/integration import references the
21/// commons as one namespace (`import * as ns from "./<name>.js"`). Emit
22/// `out/<name>.ts` that `export *`s each of the commons' source files so that
23/// namespace import resolves for the directory layout exactly as it does for a
24/// single file. The flat merge cannot collide: intra-commons symbol names are
25/// already unique across every kind (`bynk.resolve.duplicate_type`/`_fn`/
26/// `_method`), so no two files re-export the same name.
27///
28/// Returns `None` — no barrel — when the commons is *not* multi-file (a
29/// single-file commons already owns `out/<name>.ts`; a barrel would collide), or
30/// when this barrel path was already emitted (`emitted` dedups across the several
31/// test/integration modules that may import the same commons).
32///
33/// `groups` maps each production unit name to the `parsed` indices of its files;
34/// the multi-file predicate and the re-exported file set both read from there, so
35/// the barrel can never drop a file that declares nothing type/fn/method-shaped
36/// (which `FileDeclIndex` would omit).
37///
38/// #1820: a multi-file *context*'s barrel is also part of a production bundle
39/// build, emitted by `run_checks` ahead of the test passes, since its
40/// composition root imports the context from `out/<name>.ts` too; on workers,
41/// `run_checks` claims its path, since the context's modules are the Worker's.
42/// `run_checks` alone passes `modules_out`, this unit's staged modules, for
43/// [`duplicated_export_reexports`]; the test passes, which only ever reach a
44/// commons here, pass none. A commons' files repeat no generated export: it
45/// has no boundary codecs, and only a context rebrands a `uses`d type.
46pub fn emit_commons_barrel(
47 name: &str,
48 groups: &BTreeMap<String, Vec<usize>>,
49 parsed: &[ParsedFile],
50 import_ext: ImportExt,
51 emitted: &mut HashSet<PathBuf>,
52 modules_out: &[StagedFile],
53) -> Option<StagedFile> {
54 let indices = groups.get(name)?;
55 // Multi-file only: *every* file must sit under a `<name>/` directory, the
56 // layout where no `out/<name>.ts` is otherwise produced. A unit with any file
57 // at `<name>.bynk` already owns `out/<name>.ts`, so it must not get a barrel.
58 if indices.is_empty()
59 || !indices
60 .iter()
61 .all(|&i| is_multi_file_layout(&parsed[i].source_path(), name))
62 {
63 return None;
64 }
65 let output_path = commons_dir_for(name).with_extension("ts");
66 if !emitted.insert(output_path.clone()) {
67 return None; // already emitted for an earlier importing module
68 }
69 // Barrel body: `export *` per distinct source file, sorted for determinism.
70 // Specifiers run through the emitter's cross-commons machinery so the path is
71 // correct for dotted names (`commons a.b` sits at `out/a/b.ts`, re-exporting
72 // `./b/<file>.js`) and forward-slash-normalised on Windows. `commons_dir_for`
73 // stands in for the barrel's own location — its parent is the directory the
74 // barrel lives in, which is all the relative computation needs.
75 let barrel_loc = commons_dir_for(name);
76 let mut files: Vec<PathBuf> = indices.iter().map(|&i| parsed[i].source_path()).collect();
77 files.sort();
78 files.dedup();
79 let mut stmts = vec![TsStmt::comment(
80 "Generated by bynk — do not edit by hand.",
81 None,
82 )];
83 for file in &files {
84 let spec = super::cross_commons_import_specifier_for_path(&barrel_loc, file, import_ext);
85 stmts.push(TsStmt::decl(TsDecl::ReExportAll { from: spec }, None));
86 }
87 let (merged, defined) = merged_unit_helpers(
88 name,
89 indices,
90 parsed,
91 &barrel_loc,
92 import_ext,
93 |file| file.to_path_buf(),
94 true,
95 );
96 stmts.extend(duplicated_export_reexports(
97 &files,
98 modules_out,
99 &defined,
100 &barrel_loc,
101 import_ext,
102 ));
103 stmts.extend(merged);
104 Some(StagedFile {
105 output_path,
106 document: Document::Ts(TsProgram { stmts }),
107 source_map: None,
108 debug_metadata: None,
109 })
110}
111
112/// #1844 review: the barrel's own definitions of the helpers every file of a
113/// multi-file *context* generates for itself. User names are unique across a
114/// unit, but these are not: each file with agents exports `__resetAgents`
115/// (over its own agents), and each file with services exports `__makeSurface`
116/// and the context's `__<Ctx>Deps` (over its own services). Two files of
117/// either kind made the barrel's `export *` ambiguous (TS2308), and at
118/// runtime the ambiguous name is dropped from the namespace, so a test's
119/// `__resetAgents()` was `undefined`. Where two or more files contribute one,
120/// the barrel exports a merged definition, which takes precedence over the
121/// star exports: reset every file's agents; combine every file's surface over
122/// the intersection of their deps.
123///
124/// `module_of` maps a file's source path to the path its module is emitted
125/// at, relative to which `barrel_loc` imports it: the identity for a bundle
126/// barrel, the file's own module under `handlers/` for a Worker's
127/// `handlers.ts` (#1820). `surface` says whether each file exports a
128/// surface at all: a Worker's files do not, since its composition root
129/// (`compose.ts`) builds the surface over the whole context.
130pub fn merged_unit_helpers(
131 name: &str,
132 indices: &[usize],
133 parsed: &[ParsedFile],
134 barrel_loc: &Path,
135 import_ext: ImportExt,
136 module_of: impl Fn(&Path) -> PathBuf,
137 surface: bool,
138) -> (Vec<TsStmt>, Vec<String>) {
139 let mut with_agents: Vec<PathBuf> = Vec::new();
140 let mut with_services: Vec<PathBuf> = Vec::new();
141 for &i in indices {
142 let pf = &parsed[i];
143 if pf.kind() != UnitKind::Context {
144 continue;
145 }
146 if pf.declares_agents() {
147 with_agents.push(module_of(&pf.source_path()));
148 }
149 if pf.declares_services() {
150 with_services.push(module_of(&pf.source_path()));
151 }
152 }
153 with_agents.sort();
154 with_services.sort();
155 let mut stmts = Vec::new();
156 // The names defined below, pushed in the branch that defines each, so
157 // `duplicated_export_reexports` never also re-exports one file's copy.
158 // Unlike a codec or a rebrand, each file's copy differs (it covers that
159 // file's agents or services), so re-exporting one would be wrong.
160 let mut defined = Vec::new();
161 let mut aliases: BTreeMap<PathBuf, String> = BTreeMap::new();
162 let mut alias_of = |file: &PathBuf, stmts: &mut Vec<TsStmt>| -> String {
163 if let Some(a) = aliases.get(file) {
164 return a.clone();
165 }
166 let alias = format!("__file{}", aliases.len());
167 stmts.push(TsStmt::decl(
168 TsDecl::ImportNamespace {
169 type_only: false,
170 alias: alias.clone(),
171 from: super::cross_commons_import_specifier_for_path(barrel_loc, file, import_ext),
172 },
173 None,
174 ));
175 aliases.insert(file.clone(), alias.clone());
176 alias
177 };
178 if with_agents.len() > 1 {
179 let files: Vec<String> = with_agents
180 .iter()
181 .map(|f| alias_of(f, &mut stmts))
182 .collect();
183 stmts.push(exported_function(
184 "__resetAgents",
185 Vec::new(),
186 Some(TsType::named("void")),
187 files
188 .iter()
189 .map(|alias| {
190 TsStmt::expr_stmt(
191 method_call(ident(alias.clone()), "__resetAgents", Vec::new()),
192 None,
193 )
194 })
195 .collect(),
196 ));
197 defined.push("__resetAgents".to_string());
198 }
199 if surface && with_services.len() > 1 {
200 let deps = format!("__{}Deps", super::emit::context_pascal(name));
201 let files: Vec<String> = with_services
202 .iter()
203 .map(|f| alias_of(f, &mut stmts))
204 .collect();
205 let spreads = files
206 .iter()
207 .map(|a| {
208 TsObjectEntry::Spread(method_call(
209 ident(a.clone()),
210 "__makeSurface",
211 vec![ident("deps")],
212 ))
213 })
214 .collect();
215 stmts.push(TsStmt::decl(
216 TsDecl::Export(Box::new(TsDecl::TypeAlias {
217 name: deps.clone(),
218 type_params: Vec::new(),
219 ty: TsType::intersection(
220 files
221 .iter()
222 .map(|a| TsType::named(format!("{a}.{deps}")))
223 .collect(),
224 ),
225 })),
226 None,
227 ));
228 let mut make_surface = exported_function(
229 "__makeSurface",
230 vec![TsParam::new(
231 "deps".to_string(),
232 Some(TsType::named(deps.clone())),
233 )],
234 None,
235 vec![TsStmt::return_stmt(
236 Some(TsExpr::object_entries(spreads)),
237 None,
238 )],
239 );
240 // The alias and the function sit on consecutive lines.
241 make_surface.no_blank_before = true;
242 stmts.push(make_surface);
243 defined.push("__makeSurface".to_string());
244 defined.push(deps);
245 }
246 (stmts, defined)
247}
248
249/// `export function name(params): ret { body }`, a barrel helper.
250fn exported_function(
251 name: &str,
252 params: Vec<TsParam>,
253 return_type: Option<TsType>,
254 body: Vec<TsStmt>,
255) -> TsStmt {
256 TsStmt::decl(
257 TsDecl::Export(Box::new(TsDecl::Function {
258 name: name.to_string(),
259 generics: Vec::new(),
260 params,
261 return_type,
262 body,
263 is_async: false,
264 inline: false,
265 })),
266 None,
267 )
268}
269
270/// #1820: the explicit re-exports a multi-file context's barrel needs where
271/// two or more of its files' modules export one name. User names are unique
272/// across a unit, but each file emits its own copy of what its declarations
273/// need from outside it: the context's rebrand of a `uses`d commons type, that
274/// commons type's codecs re-exported, a boundary type's codecs (wherever the
275/// type is declared). Each copy is a function of the type alone, so the
276/// barrel re-exports the name from the first module (sorted by path) that
277/// exports it, which takes precedence over `export *`; without it, `export *`
278/// is ambiguous (TS2308) and drops the name at runtime. `merged` names the
279/// helpers the barrel defines itself (`merged_unit_helpers`), which are
280/// skipped.
281///
282/// `modules` is each file's module path; `emitted`, the staged output in
283/// which each is found at its [`ts_output_path`]. What a module exports is
284/// read with [`TsStmt::exported_names`], which sees structured exports only;
285/// every generated name that repeats across files is exported structurally
286/// (the commons codec re-export is [`TsDecl::ExportNames`] for this reason).
287/// A name the chosen module exports only as a type (a rebrand of a commons
288/// type with no `of` constructor is a bare `type` alias) is re-exported as
289/// `type X`: under the build's `isolatedModules`, `export { X }` of a
290/// type-only name is TS1205 (#1862 review).
291pub fn duplicated_export_reexports(
292 modules: &[PathBuf],
293 emitted: &[StagedFile],
294 merged: &[String],
295 barrel_loc: &Path,
296 import_ext: ImportExt,
297) -> Vec<TsStmt> {
298 // Per name, each exporting module and whether it exports a value under
299 // the name.
300 let mut exporters: BTreeMap<&str, Vec<(&PathBuf, bool)>> = BTreeMap::new();
301 for module in modules {
302 let output = ts_output_path(module);
303 let Some(Document::Ts(program)) = emitted
304 .iter()
305 .find(|f| f.output_path == output)
306 .map(|f| &f.document)
307 else {
308 continue;
309 };
310 for stmt in &program.stmts {
311 for exported in stmt.exported_names() {
312 // A type is often both an `interface` and a `const` of one
313 // name: one module, counted once, with a value if either
314 // statement exports one. This loop visits one module's
315 // statements at a time, so a module's earlier entry for the
316 // name, if any, is the last one.
317 let modules = exporters.entry(exported.name).or_default();
318 match modules.last_mut() {
319 Some((m, has_value)) if *m == module => *has_value |= exported.has_value,
320 _ => modules.push((module, exported.has_value)),
321 }
322 }
323 }
324 }
325 let mut chosen: BTreeMap<&PathBuf, Vec<String>> = BTreeMap::new();
326 for (name, modules) in &exporters {
327 if let [(first, has_value), _, ..] = modules.as_slice()
328 && !merged.iter().any(|m| m == name)
329 {
330 let spec = if *has_value {
331 name.to_string()
332 } else {
333 format!("type {name}")
334 };
335 chosen.entry(first).or_default().push(spec);
336 }
337 }
338 chosen
339 .into_iter()
340 .map(|(module, names)| {
341 let from =
342 super::cross_commons_import_specifier_for_path(barrel_loc, module, import_ext);
343 TsStmt::decl(TsDecl::ReExport { names, from }, None)
344 })
345 .collect()
346}
347
348/// #1820: `handlers.ts` for a context split across files, on Workers. It
349/// re-exports each file's module, so the Worker's entry point, its composition
350/// root and every consuming context see the context as one module, as they do
351/// a single-file context's `handlers.ts`. Like a multi-file unit's test barrel
352/// (`emit_commons_barrel`), it also defines the merged helpers each file
353/// generates for itself (`merged_unit_helpers`), which `export *` alone
354/// would leave ambiguous: only `__resetAgents`, since a Worker's files export
355/// no surface.
356///
357/// Each file also emits its own copy of what its declarations need from
358/// outside it (a boundary type's codecs, a `uses`d commons type's rebrand), so
359/// two files can both export one name; the barrel re-exports each such name
360/// from one module of `emitted`, this unit's (`duplicated_export_reexports`).
361pub fn emit_worker_handlers_barrel(
362 name: &str,
363 indices: &[usize],
364 parsed: &[ParsedFile],
365 emitted: &[StagedFile],
366 import_ext: ImportExt,
367 layout: &WorkerLayout,
368) -> StagedFile {
369 let barrel_loc = layout.handlers_source_path(name);
370 let module_of = |file: &Path| layout.file_source_path(name, file);
371 let mut modules: Vec<PathBuf> = indices
372 .iter()
373 .map(|&i| module_of(&parsed[i].source_path()))
374 .collect();
375 modules.sort();
376 modules.dedup();
377 let mut stmts = vec![TsStmt::comment(
378 "Generated by bynk — do not edit by hand.",
379 None,
380 )];
381 for module in &modules {
382 let spec = super::cross_commons_import_specifier_for_path(&barrel_loc, module, import_ext);
383 stmts.push(TsStmt::decl(TsDecl::ReExportAll { from: spec }, None));
384 }
385 let (merged, defined) = merged_unit_helpers(
386 name,
387 indices,
388 parsed,
389 &barrel_loc,
390 import_ext,
391 module_of,
392 false,
393 );
394 stmts.extend(duplicated_export_reexports(
395 &modules,
396 emitted,
397 &defined,
398 &barrel_loc,
399 import_ext,
400 ));
401 stmts.extend(merged);
402 StagedFile {
403 output_path: layout.handlers_output_path(name),
404 document: Document::Ts(TsProgram { stmts }),
405 source_map: None,
406 debug_metadata: None,
407 }
408}