Skip to main content

bynk_emit/
emitter.rs

1//! TypeScript emission (spec §7, v0.1 §6, v0.2 §6).
2//!
3//! Walks the typed AST and writes a single TypeScript module.
4//!
5//! # Public API of the code generator
6//!
7//! Crate-hygiene D1 (#2982): the orchestration layer (`project`, which moves
8//! to `bynk-driver`) drives this module, so the helpers it calls are a
9//! deliberate public API rather than `pub(crate)` internals: the
10//! `emit_*` entry points (`emit_project`, `emit_worker_entry`,
11//! `emit_worker_compose`, `emit_wrangler_toml`, `emit_secrets_manifest`,
12//! `emit_events_fanout_do`, `emit_tsconfig`), the specifier and name helpers
13//! (`ts_specifier`, `ts_ident`, `ts_type_ref`, `cross_commons_import_specifier_for_path`),
14//! the table walkers (`walk_unit_table_bodies`, `block_uses_emit`,
15//! `any_service_binds_caller`, `table_has_plain_json`, …), the runtime-import
16//! constants and `runtime_files` / `runtime_use`, and the
17//! `wrangler`, `client`, `contracts`, `secrets`, `serialisation` and `emit`
18//! submodules' items the orchestrator consumes. The shared output and context
19//! model lives in [`crate::emit_model`]. The import and rebrand family
20//! (`ts_specifier`, `cross_commons_import_specifier_for_path`, `commons_alias`)
21//! lives in `imports`, and the header (`runtime_import_for`) in `runtime_header`.
22//! The project driver (`emit_project` and the agent and table helpers) lives in
23//! `project`, the module's own boundary codecs (`ty_to_type_ref`) in `boundary`, and
24//! the helpers for consumed contexts (`unexported_type_renames`, `rename_in_decl`)
25//! in `consumed`. This module re-exports all of them. Anything not reachable from a path
26//! the orchestrator uses stays `pub(crate)`.
27//!
28//! v0.2 lowering rules:
29//! - Refined-base types: branded type alias + constructor object with
30//!   `of`/`unsafe` (+ any user-declared methods).
31//! - Record types: TypeScript `interface` + namespace object with methods.
32//! - Sum types: discriminated-union type alias + namespace object with
33//!   variant constructors and methods.
34//! - Field access lowers to property access.
35//! - Method calls lower to `Type.method(receiver, args)` (UFCS).
36//! - `match` lowers to a switch on `.tag`; in tail position it inlines,
37//!   otherwise it becomes an IIFE.
38//! - `is` lowers to a tag check; bindings become `const` declarations
39//!   on the truthy side of `if`/`&&`.
40
41#[cfg(test)]
42use bynk_ts::SourceMapBuilder;
43#[cfg(test)]
44use std::cell::RefCell;
45use std::collections::{HashMap, HashSet};
46use std::path::PathBuf;
47use std::sync::Arc;
48
49// P7.5 (#1307): relocated from `emitter/source_map.rs` to `bynk-ts`,
50// unchanged — `bynk-ts/src/source_map.rs`'s own module doc has the full
51// grounding for why this API stays as-is while `bynk-ts`'s own printer
52// gets a second, simpler way to use the same type.
53use bynk_ts::{
54    TsType, decimal_signed_coef, pred_condition_and_message, pred_condition_and_message_for,
55};
56
57use crate::emit_model::EmitProjectCtx;
58use bynk_check::builtin_names::map_query;
59use bynk_check::builtin_names::methods::RAW;
60use bynk_check::builtin_names::types::*;
61use bynk_check::checker::{CheckedProgram, NamedKind, Ty, TyId, TypedCommons, Types};
62use bynk_check::project_model::BuildTarget;
63use bynk_model::TypeShape;
64use bynk_model::{lower_store_field_shape_ir, lower_type_shape_ir};
65use bynk_project::UnitKind;
66use bynk_syntax::ast::{
67    BaseType, BinOp, CommonsItem, Expr, ExprKind, FnDecl, FnName, Ident, LambdaExpr, MatchBody,
68    TypeBody, TypeDecl, TypeRef, rounding_mode,
69};
70use ctx::UnitFacts;
71use ts_types::TyRender;
72
73pub mod bindings;
74pub mod client;
75pub mod commons_barrel;
76pub(crate) mod compose;
77pub mod containers;
78pub mod contracts;
79pub(crate) mod events_fanout;
80pub(crate) mod harness_names;
81pub mod http_client;
82pub mod secrets;
83pub mod serialisation;
84pub mod toml_doc;
85pub(crate) mod workers;
86pub mod workers_emit;
87pub(crate) mod workers_entry;
88pub mod workers_group;
89pub mod wrangler;
90
91pub use bindings::WorkerBindings;
92pub use compose::bundle::emit_composition_root;
93pub use compose::closure::{bare_singletons_of_context, native_platforms_of_context};
94pub use compose::workers::emit_worker_compose;
95pub use compose::{
96    ComposeFacts, ComposePlan, ComposeUnit, ComposeUnitFacts, ConsumedSurface, EventPlan,
97    EventSubscription, ExecNeeds,
98};
99pub use containers::{container_class_names, emit_containers_ts};
100pub use events_fanout::{emit_events_fanout_do, emit_group_events_fanout_do};
101pub use secrets::emit_secrets_manifest;
102pub use toml_doc::print_toml_document;
103pub use workers_entry::{
104    emit_worker_entry, field_spec_source, form_body_specs, renamed_specs_source,
105    table_has_plain_json,
106};
107pub use workers_group::{GroupEntry, GroupMember, emit_group_entry};
108pub use wrangler::{ClassTombstones, emit_wrangler_toml};
109
110mod boundary;
111mod claim_predicate;
112mod cmp;
113mod codec;
114mod consumed;
115pub mod ctx;
116mod default_value;
117mod imports;
118pub(crate) mod internal_fault;
119mod lower;
120pub(crate) mod lower_call;
121pub(crate) mod lower_ctx;
122mod lower_list;
123pub(crate) mod lower_stmt;
124pub(crate) mod runtime_header;
125pub(crate) mod runtime_use;
126mod tco;
127pub mod ts_types;
128mod zero_value;
129pub use internal_fault::{InternalFault, MISSING_CHECKER_FACT};
130pub(crate) use lower::*;
131pub use runtime_use::RuntimeUse;
132pub mod emit;
133mod project;
134pub(crate) use bynk_check::icu::{self, *};
135pub(crate) use bynk_check::websocket;
136pub use emit::*;
137
138pub mod runtime_files;
139/// ADR 0615 (#2426): the runtime as one source per `@bynk/runtime` module. A
140/// BUILD OUTPUT, not a hand-edited file: `bynk-emit/runtime/scripts/bundle.mjs`
141/// writes `runtime/<module>.ts` and this table from the focused modules in
142/// `bynk-emit/runtime/src` (CI's `runtime` job guards against drift). Keeping it
143/// committed means `cargo build` stays Node-free and the emitter stays lockstep
144/// with the runtime it embeds.
145mod runtime_modules;
146use boundary::emit_json_codec_helpers;
147pub use boundary::ty_to_type_ref;
148pub(crate) use consumed::rename_in_decl;
149pub use consumed::unexported_type_renames;
150pub(crate) use imports::commons_alias;
151pub use imports::{cross_commons_import_specifier_for_path, ts_specifier};
152use imports::{
153    emit_consumed_type_reexports, emit_context_rebrands, emit_cross_context_namespace_imports,
154    emit_project_imports, external_references_of, extra_import_stmts, used_external_names,
155};
156use project::agent_registry_name;
157pub(crate) use project::walk_unit_table_bodies;
158pub use project::{
159    agent_cross_context_targets, agent_factory_name, call_handler_needs_exec, emit_project,
160};
161pub use runtime_files::{
162    RUNTIME_DIR, closure_files, emit_all_runtime_modules, rewrite_runtime_imports,
163};
164pub use runtime_header::runtime_import_for;
165use runtime_header::{header_single, write_header};
166
167/// Events track, slice 2 (spine #936): the TS type of one buffered/fanned-out
168/// event — a handler's `__events` local, the `__eventsDispatch` deps field
169/// (service, agent, provider, and the Bundle/Workers dispatch closures that
170/// implement it), and the fan-out DO's `FanoutEvent` (`events_fanout.rs`) all
171/// declare this same shape independently, with no shared type today. Routing
172/// every Rust-side site through one constant means the envelope field can
173/// never drift by being added at 8 of 9 of them. The two TypeScript runtime
174/// sources that also declare it (`runtime/src/agent.ts`'s
175/// `dispatchToEventsFanout`, `runtime/src/boundary.ts`'s `deliverEvent`) are
176/// hand-edited files this constant cannot reach — keep them textually
177/// identical to this shape by hand; `cargo test -p bynk-tests --test it --
178/// events_workers_wiring:: events_envelope_behaviour::` exercises every hop
179/// and would fail on a real mismatch.
180///
181/// #973: `runtime/src/boundary.ts`'s `deserialiseEventEnvelope` is a related
182/// but distinct hand-written piece — it validates the *inner* `envelope`
183/// object's shape at the receiving `/_bynk/event/` route, not this outer
184/// wire wrapper. Keep its field list in sync with the `envelope: { ... }`
185/// portion of this shape by hand; nothing generates either from the other.
186pub const EVENTS_WIRE_EVENT_TS_TYPE: &str = "{ type: string; payload: unknown; envelope: { eventId: string; publisherId: string; emittedAt: number; schemaVersion: number } }";
187
188/// Emit the contents of `out/tsconfig.json`. The CLI uses `tsc -p` against
189/// this when running `bynk test`; users can also drive `tsc` against it
190/// directly to produce JS for deployment.
191///
192/// I4 (#1970): a context's generated TypeScript client (`bynk-client.ts`) is
193/// excluded. It is for a foreign Worker's build, where `@bynk/wire-client`
194/// resolves; the Bynk build neither imports it nor has that package.
195/// Excluding a file drops the default `node_modules` exclusion, so it is
196/// restated. A `[deploy.workers]` group's member writes it as
197/// `<member>.bynk-client.ts` (#3562), so that name is excluded too.
198///
199/// #2148: `module: NodeNext` takes each file's format from the nearest
200/// `package.json`, so the compiler also emits `out/package.json` declaring
201/// `"type": "module"`. `tsc` then checks the output (hand-written adapter
202/// bindings included) under the ES-module rules Node runs it with, and does
203/// not down-level it to CommonJS, whose transform reserves the top-level names
204/// `require` and (from TypeScript 7) `Object`.
205pub fn emit_tsconfig() -> String {
206    TSCONFIG_JSON.to_string()
207}
208
209/// The `bynk test --coverage` variant (#854): the same config with `sourceMap`
210/// enabled, so `tsc` emits the `.js.map`s the coverage remap consumes (hop 1,
211/// `.js` → emitted `.ts`). Kept coverage-only rather than folded into the
212/// default so a normal `bynk test` / deployment `tsc` run ships no `.js.map`s.
213/// The runner overwrites the default `out/tsconfig.json` with this before `tsc`.
214pub fn emit_tsconfig_with_source_maps() -> String {
215    TSCONFIG_JSON.replace(
216        "\"outDir\": \"./out-js\",",
217        "\"sourceMap\": true,\n    \"outDir\": \"./out-js\",",
218    )
219}
220
221const TSCONFIG_JSON: &str = r#"{
222  "compilerOptions": {
223    "target": "ES2022",
224    "module": "NodeNext",
225    "moduleResolution": "NodeNext",
226    "strict": true,
227    "noImplicitAny": true,
228    "esModuleInterop": true,
229    "skipLibCheck": true,
230    "resolveJsonModule": true,
231    "isolatedModules": true,
232    "noEmit": false,
233    "outDir": "./out-js",
234    "rootDir": "."
235  },
236  "include": ["**/*.ts"],
237  "exclude": ["node_modules", "out-js", "**/bynk-client.ts", "**/*.bynk-client.ts"]
238}
239"#;
240
241/// Emit TypeScript source for the typed commons (single-file mode).
242///
243/// Takes a [`CheckedProgram`] rather than a bare `TypedCommons` (T3.7, R3.10):
244/// the only way to obtain one is [`bynk_check::checker::certify`], so this
245/// function can no longer be called with an unchecked or partially-checked
246/// program by construction.
247///
248/// 1A.34: a checker fact the emitter needed and did not find is an
249/// [`InternalFault`] (see [`emit_project`]); the text built alongside is then unused.
250pub(crate) fn emit(program: &CheckedProgram) -> Result<String, Vec<InternalFault>> {
251    let commons = program.program();
252    // Emit the body first so the header can decide which runtime helpers to
253    // import from what the body actually referenced (v0.110: the `__bynkBytes*`
254    // helpers are imported only when a `Bytes` value is constructed/compared).
255    // "What it referenced" comes from `dummy_ctx.runtime_use`, which the `Bytes`
256    // lowerings write as they emit — not from scanning `body` for the helper's
257    // name, which a user string literal or doc comment could also contain.
258    // #1486: collects into a real `Vec<TsStmt>` and prints once via
259    // `bynk_ts::print`, rather than `extend_printed`'s flat per-stmt loop —
260    // `emit_type`/`emit_free_fn`/`emit_json_codec_helpers` (this function's
261    // own callees, shared with `emit_project`) dropped their own explicit
262    // inter-declaration blank `TsStmt`s as part of that conversion, relying
263    // on the printer's automatic top-level spacing policy; this single-file
264    // path needs the same policy to stay correctly spaced.
265    let mut body_stmts: Vec<bynk_ts::TsStmt> = Vec::new();
266    body_stmts.extend(write_commons_doc(commons));
267    let dummy_ctx = single_file_ctx();
268    // Types come first (they define interfaces and namespaces).
269    for item in &commons.commons.items {
270        if let CommonsItem::Type(t) = item {
271            let shape = type_shape_for(t, program);
272            body_stmts.extend(emit_type(t, &shape, commons, &dummy_ctx));
273        }
274    }
275    // #2617: constants after the types, before the functions.
276    body_stmts.extend(emit_consts(commons, &dummy_ctx));
277    // Free functions afterward.
278    for item in &commons.commons.items {
279        if let CommonsItem::Fn(f) = item
280            && let FnName::Free(_) = &f.name
281        {
282            body_stmts.extend(emit_free_fn(
283                f,
284                commons,
285                false,
286                &dummy_ctx.runtime_use,
287                &dummy_ctx.cross_context,
288                UnitFacts::of(&dummy_ctx),
289            ));
290        }
291    }
292    // v0.22b: module-local codec helpers for Json.encode/decode targets.
293    body_stmts.extend(emit_json_codec_helpers(
294        commons,
295        &dummy_ctx,
296        &HashSet::new(),
297        &HashSet::new(),
298    ));
299    let mut stmts = header_single(commons, &body_stmts);
300    stmts.extend(body_stmts);
301    let out = bynk_ts::print(&bynk_ts::TsProgram { stmts }, "", "", "").text;
302    let faults = dummy_ctx.runtime_use.take_faults();
303    if faults.is_empty() {
304        Ok(out)
305    } else {
306        Err(faults)
307    }
308}
309
310/// `t`'s already-lowered `TypeShape` (`bynk-emit::ir`, P6.6/#1188) — reuses the
311/// canonical `Arc<TypeDecl>` `TypedCommons::types` already holds for `t` rather
312/// than a fresh `Arc::new(t.clone())` per call (Decision B, #1188). `types`
313/// holds an entry for every `CommonsItem::Type` *and* every `CommonsItem::Event`
314/// (`resolver.rs`'s own resolve pass inserts both under the same table, the
315/// event's own synthetic `TypeDecl` — `EventDecl::as_type_decl` — keyed
316/// identically), so this one helper serves both emission loops below with no
317/// special-casing for the event mirror.
318///
319/// Derives `commons` from `program` itself rather than taking it as a
320/// separate parameter (review on #1190): the `TyId`s this returns are minted
321/// from `program.program().ty_intern`, and every caller renders them straight
322/// back through that same `commons.ty_intern` (`emit_record_type`/
323/// `emit_sum_type`'s `ts_ty` calls) — a caller free to pass a `TypedCommons`
324/// from a *different* check run would hit `Types::get`'s cross-table panic
325/// instead of a diagnostic. One parameter makes that invariant
326/// unrepresentable instead of merely true today.
327fn type_shape_for(t: &TypeDecl, program: &CheckedProgram) -> TypeShape {
328    let commons = program.program();
329    let def = commons.types.get(&t.name.name).unwrap_or_else(|| {
330        panic!(
331            "bynk internal error (ADR 0334): type `{}` is not in TypedCommons::types, but the \
332             checker already accepted this declaration",
333            t.name.name
334        )
335    });
336    lower_type_shape_ir(def, program)
337}
338
339/// A no-op project context for single-file emission. Single-file mode never
340/// involves contexts or cross-unit imports, so most fields default to empty.
341fn single_file_ctx() -> EmitProjectCtx {
342    EmitProjectCtx {
343        import_ext: crate::emit_model::ImportExt::Js,
344        contracts: false,
345        trace: None,
346        inspect_agents: false,
347        source_path: PathBuf::new(),
348        identity_path: String::new(),
349        commons_name: String::new(),
350        file_decl_index: bynk_check::symbols::FileDeclIndex {
351            types: HashMap::new(),
352            fns: HashMap::new(),
353            methods: HashMap::new(),
354            agents: HashMap::new(),
355            capabilities: HashMap::new(),
356        },
357        imported_from: HashMap::new(),
358        imported_from_kind: HashMap::new(),
359        imported_decl_paths: HashMap::new(),
360        consumed_type_aliases: HashMap::new(),
361        unit_kind: UnitKind::Commons,
362        owning_context: None,
363        exports_for_consumed: HashMap::new(),
364        cross_context: bynk_check::resolver::CrossContextInfo::default(),
365        target: BuildTarget::Bundle,
366        local_agents: HashSet::new(),
367        agent_given_deps: HashMap::new(),
368        agent_given_deps_names: HashMap::new(),
369        extra_imports: Vec::new(),
370        agent_method_givens: HashMap::new(),
371        agent_called_contexts: Vec::new(),
372        actors: HashMap::new(),
373        agent_schema_versions: HashMap::new(),
374        event_schema_versions: HashMap::new(),
375        consumed_adapters: HashSet::new(),
376        consumed_types_with_methods: HashSet::new(),
377        history_target_agents: HashSet::new(),
378        asset_served: Default::default(),
379        embed_text: Default::default(),
380        imported_methods: HashMap::new(),
381        runtime_use: Default::default(),
382        worker_layout: Default::default(),
383        unit_source: None,
384        type_spellings: HashMap::new(),
385    }
386}
387
388/// #2854: the key suffix under which a route's typed `query` (position and
389/// declared type) sits in the same per-route map as its body param.
390pub const QUERY_ROUTE_SUFFIX: &str = "?query";
391/// #2910: marks a route whose system drivers take a case's extra request
392/// headers in a `__extraHeaders` slot (a route that declares no `headers:`).
393pub const EXTRA_HEADERS_ROUTE_SUFFIX: &str = "?extra-headers";
394
395/// #3276: marks a `@form` route in the system drivers' route-body map, so a typed
396/// body in a mixed typed-and-`Wire` call is written as a form (`a=1&b=x`), not JSON.
397pub const FORM_ROUTE_SUFFIX: &str = "?form";
398
399/// #3277: marks a route's `cookies` record in the system drivers' route-body map, so a
400/// typed record in a mixed typed-and-`Wire` call is sent as a `Cookie` header.
401pub const COOKIES_ROUTE_SUFFIX: &str = "?cookies";
402
403/// Emit the commons-level doc block (if any) at the current position.
404/// #1478: real-node-internally already (a single `TsStmtKind::DocComment`,
405/// the same shape [`emit_doc_block`] itself builds — inlined directly here
406/// rather than calling that `out: &mut String`-shaped helper, since its own
407/// signature and 14 real callers stay unchanged, #1333's own doc).
408fn write_commons_doc(commons: &TypedCommons) -> Vec<bynk_ts::TsStmt> {
409    let mut stmts = Vec::new();
410    if let Some(doc) = &commons.commons.documentation {
411        stmts.push(bynk_ts::TsStmt::doc_comment(doc.as_str(), None));
412        // #1486: no explicit trailing blank stmt here — `DocComment` (unlike
413        // `Comment`) is never exempted from the printer's automatic
414        // top-level spacing policy, so the single blank before whatever
415        // follows is already supplied for free.
416    }
417    stmts
418}
419
420/// #1653: the TypeScript property name of a sum variant's payload field. A
421/// variant object already carries the in-memory discriminant `tag`, so a
422/// payload field of that name moves to `$tag` (`$` is not a Bynk identifier
423/// character, so no other field can be spelled that way). Only the in-memory
424/// shape changes: the wire key stays the field's own name, and the codec maps
425/// between the two.
426pub(crate) fn payload_prop(field: &str) -> String {
427    if field == "tag" {
428        "$tag".to_string()
429    } else {
430        field.to_string()
431    }
432}
433
434/// The TypeScript spelling of a user identifier in a *binding or reference*
435/// position. Defined in `bynk_check::emitted_names` so the language server's
436/// inline values (#2476) name the same variable the emitter declares.
437pub use bynk_check::emitted_names::ts_ident;
438
439/// The one TypeScript string-literal escaper lives in `bynk_ts` (crate-hygiene A2);
440/// the emitter keeps its historical name for it.
441pub use bynk_ts::escape_ts_literal as escape_ts_string;
442
443#[allow(dead_code)]
444fn _unused_hashmap(_h: HashMap<String, ()>) {}
445
446#[cfg(test)]
447mod runtime_tests {
448    use super::*;
449
450    #[test]
451    fn tsconfig_is_well_formed_json() {
452        let s = emit_tsconfig();
453        // Spot-check the key fields; we don't reach for a JSON parser.
454        assert!(s.contains("\"target\": \"ES2022\""));
455        assert!(s.contains("\"strict\": true"));
456        assert!(s.contains("\"include\""));
457    }
458
459    #[test]
460    fn tsconfig_excludes_a_members_client_too() {
461        // #3562: a group's member writes `<member>.bynk-client.ts`, which
462        // `**/bynk-client.ts` does not match.
463        let s = emit_tsconfig();
464        assert!(s.contains("\"**/bynk-client.ts\""), "{s}");
465        assert!(s.contains("\"**/*.bynk-client.ts\""), "{s}");
466    }
467
468    #[test]
469    fn coverage_tsconfig_enables_source_maps() {
470        // #854: the coverage remap consumes tsc's `.js.map`s, so the variant must
471        // set `sourceMap` — a guard against a silent string-replace miss if the
472        // base config's `outDir` line is ever reworded. The default stays map-free
473        // so a normal `bynk test` / deployment build ships no `.js.map`s.
474        let cov = emit_tsconfig_with_source_maps();
475        assert!(
476            cov.contains("\"sourceMap\": true"),
477            "coverage config: {cov}"
478        );
479        assert!(cov.contains("\"outDir\": \"./out-js\""));
480        assert!(!emit_tsconfig().contains("sourceMap"));
481    }
482
483    #[test]
484    fn workers_dir_name_replaces_dots_with_dashes() {
485        assert_eq!(
486            bynk_project::worker_dir_name("commerce.payment"),
487            "commerce-payment"
488        );
489        assert_eq!(bynk_project::worker_dir_name("a.b.c"), "a-b-c");
490    }
491
492    // Refactor track: characterisation pin for the canonical `escape_ts_string`.
493    // It escapes backslash/quote/newline/tab and carriage return (`\r` → `\r`).
494    #[test]
495    fn escape_ts_string_escapes_cr() {
496        assert_eq!(escape_ts_string("a\\b"), "a\\\\b");
497        assert_eq!(escape_ts_string("a\"b"), "a\\\"b");
498        assert_eq!(escape_ts_string("a\nb"), "a\\nb");
499        assert_eq!(escape_ts_string("a\tb"), "a\\tb");
500        assert_eq!(escape_ts_string("a\rb"), "a\\rb"); // CR escaped here; raw in project copy
501    }
502}