Skip to main content

Module emitter

Module emitter 

Source
Expand description

TypeScript emission (spec §7, v0.1 §6, v0.2 §6).

Walks the typed AST and writes a single TypeScript module.

§Public API of the code generator

Crate-hygiene D1 (#2982): the orchestration layer (project, which moves to bynk-driver) drives this module, so the helpers it calls are a deliberate public API rather than pub(crate) internals: the emit_* entry points (emit_project, emit_worker_entry, emit_worker_compose, emit_wrangler_toml, emit_secrets_manifest, emit_events_fanout_do, emit_tsconfig), the specifier and name helpers (ts_specifier, ts_ident, ts_type_ref, cross_commons_import_specifier_for_path), the table walkers (walk_unit_table_bodies, block_uses_emit, any_service_binds_caller, table_has_plain_json, …), the runtime-import constants and runtime_files / runtime_use, and the wrangler, client, contracts, secrets, serialisation and emit submodules’ items the orchestrator consumes. The shared output and context model lives in crate::emit_model. The import and rebrand family (ts_specifier, cross_commons_import_specifier_for_path, commons_alias) lives in imports, and the header (runtime_import_for) in runtime_header. The project driver (emit_project and the agent and table helpers) lives in project, the module’s own boundary codecs (ty_to_type_ref) in boundary, and the helpers for consumed contexts (unexported_type_renames, rename_in_decl) in consumed. This module re-exports all of them. Anything not reachable from a path the orchestrator uses stays pub(crate).

v0.2 lowering rules:

  • Refined-base types: branded type alias + constructor object with of/unsafe (+ any user-declared methods).
  • Record types: TypeScript interface + namespace object with methods.
  • Sum types: discriminated-union type alias + namespace object with variant constructors and methods.
  • Field access lowers to property access.
  • Method calls lower to Type.method(receiver, args) (UFCS).
  • match lowers to a switch on .tag; in tail position it inlines, otherwise it becomes an IIFE.
  • is lowers to a tag check; bindings become const declarations on the truthy side of if/&&.

Re-exports§

pub use bindings::WorkerBindings;
pub use containers::container_class_names;
pub use containers::emit_containers_ts;
pub use secrets::emit_secrets_manifest;
pub use toml_doc::print_toml_document;
pub use workers_group::GroupEntry;
pub use workers_group::GroupMember;
pub use workers_group::emit_group_entry;
pub use wrangler::ClassTombstones;
pub use wrangler::emit_wrangler_toml;
pub use runtime_files::RUNTIME_DIR;
pub use runtime_files::closure_files;
pub use runtime_files::emit_all_runtime_modules;
pub use runtime_files::rewrite_runtime_imports;
pub use emit::*;

Modules§

bindings
One binding model per build (back-half paydown 1C.1a, Decisions A to E of #4031).
client
I4 (#1970): the typed TypeScript client for a context’s foreign callers, workers/<context>/bynk-client.ts (design/archive/retired-tracks.md, interop track D3).
commons_barrel
The commons barrel: an aggregating out/<name>.ts for a multi-file commons or context.
containers
#3477 (slice C1): the Durable Object classes of a Worker’s Container instances.
contracts
bynk-contracts.json generation per Worker (v0.177, #643).
ctx
The module-invariant lowering context and the per-body state structs that sit between it and LowerCtx.
emit
Per-declaration emission — the functions emit_project drives to render each top-level Bynk declaration into TypeScript. Split out of emitter.rs (ADR 0060), then into one file per declaration kind (back-half paydown 2.1, #4086). This file only declares those files and re-exports them, so every emitter::emit::X and emitter::X path still resolves; each child imports what it uses explicitly. The one glob import below is not for this file: moved function bodies spell parent paths through it, such as super::tco::plan, super::commons_alias, super::serialisation::… and super::ty_to_type_ref.
http_client
bynk client (#3508, slice BC1): the typed TypeScript client for a project’s from http services, one module a front end imports.
runtime_files
The runtime as per-module files (ADR 0615, #2426).
secrets
bynk-secrets.json generation per Worker (v0.172, ADR 0195).
serialisation
Per-type serialise / deserialise helper generation for workers mode (v0.8 §3.4 / §5.2).
toml_doc
P7.3 (#1303): a minimal typed TOML tree and printer — the one piece of R7.8 (Artefacts is a keyed set of typed documents, never a String at construction) landable ahead of bynk-ts (Arc B, P7.5+), since wrangler.toml is the one document bynk-emit produces that isn’t TypeScript. Not a general TOML library: TomlValue represents exactly what emitter::wrangler::emit_wrangler_toml needs to build a wrangler.toml today, no more.
ts_types
TypeScript type rendering: ts_type_ref*, ts_ty, and the TsType builders.
workers_emit
The per-Worker emission (1B.2d, #4028 Decision F): each context’s compose.ts, entry point, events fan-out class, contract and secrets manifests, and its Worker’s wrangler.toml and sidecars, rendered from the binding model the build derived once (WorkerBindings). The driver builds a WorkersEmit from the checked project and its options and calls WorkersEmit::emit_all; it decides nothing about which bindings a Worker has, or where it is.
workers_group
A Worker group’s index.ts (#3562, G2b step 2c-4b).
wrangler
wrangler.toml generation per Worker (v0.8 §4.4 / §4.5).

Structs§

ComposeFacts
Everything ComposePlan::decide needs, as plain data.
ComposePlan
What an application composes.
ComposeUnit
One unit of the plan: facts, not text.
ComposeUnitFacts
What the builder reads off one unit’s checked table. Plain data.
ConsumedSurface
A consumed context’s service surface, as the consumer’s deps carries it on the Bundle target (divergence 6).
EventPlan
Who subscribes to what, keyed (publishing context, event). Plain facts: each renderer decides how to deliver.
EventSubscription
One subscription: a service that subscribes to a publisher’s event, and whether a delivery to it carries the event’s envelope.
ExecNeeds
Whether a unit’s service handlers hand work to the execution context (detach, within or race, #2719). The two targets read different predicates, so both are facts (divergence 4 of #3928).
InternalFault
One checker fact the emitter needed and did not find: the .bynk span of the construct being lowered, and a description of the fact.
RuntimeUse
Per-module accumulator of conditional runtime-helper references.

Constants§

COOKIES_ROUTE_SUFFIX
#3277: marks a route’s cookies record in the system drivers’ route-body map, so a typed record in a mixed typed-and-Wire call is sent as a Cookie header.
EVENTS_WIRE_EVENT_TS_TYPE
Events track, slice 2 (spine #936): the TS type of one buffered/fanned-out event — a handler’s __events local, the __eventsDispatch deps field (service, agent, provider, and the Bundle/Workers dispatch closures that implement it), and the fan-out DO’s FanoutEvent (events_fanout.rs) all declare this same shape independently, with no shared type today. Routing every Rust-side site through one constant means the envelope field can never drift by being added at 8 of 9 of them. The two TypeScript runtime sources that also declare it (runtime/src/agent.ts’s dispatchToEventsFanout, runtime/src/boundary.ts’s deliverEvent) are hand-edited files this constant cannot reach — keep them textually identical to this shape by hand; cargo test -p bynk-tests --test it -- events_workers_wiring:: events_envelope_behaviour:: exercises every hop and would fail on a real mismatch.
EXTRA_HEADERS_ROUTE_SUFFIX
#2910: marks a route whose system drivers take a case’s extra request headers in a __extraHeaders slot (a route that declares no headers:).
FORM_ROUTE_SUFFIX
#3276: marks a @form route in the system drivers’ route-body map, so a typed body in a mixed typed-and-Wire call is written as a form (a=1&b=x), not JSON.
MISSING_CHECKER_FACT
The diagnostic code every InternalFault is reported under.
QUERY_ROUTE_SUFFIX
#2854: the key suffix under which a route’s typed query (position and declared type) sits in the same per-route map as its body param.

Functions§

agent_cross_context_targets
#1961: the consumed contexts an agent handler body calls a service of, read from the receivers’ syntax (B.svc(…) / Alias.svc(…)) through resolve — CrossContextInfo::resolve_prefix, or its equivalent over the unit’s consumes. A handler that constructs an agent hands its own deps to the agent’s methods (#1960), so its deps.env type must name these, and the Worker must bind them. Syntactic because a file’s handlers.ts is emitted before the unit’s other files are checked; it over-counts only a local that shadows a consumed alias, which costs an unused binding.
agent_factory_name
The exported agent-construction factory name for an agent class.
bare_singletons_of_context
#3300: the one-per-Worker capabilities (Version) context ctx’s closure reaches bare, as (unit, capability), in order: the bare-resources walk’s crate::emit_model::bare_singleton_markers.
call_handler_needs_exec
Whether a service’s on call handler hands work to the execution context (detach, within or race, directly or through the functions it calls or names, #2719), so the Bundle target’s __makeSurface deps must carry the execution context (deps.__exec) it forwards to the handler. The set is the checker’s (bynk_check::exec_plan::ExecPlan), computed from what it resolved rather than by walking the syntax for method names.
cross_commons_import_specifier_for_path
Compute a relative import specifier from this file’s location to a specific source file in another commons. target_source is the project- relative path of the target .bynk file. The result is suitable for import { ... } from "..." in NodeNext/strict TypeScript.
emit_composition_root
emit_events_fanout_do
context: the publishing context’s qualified name (the header comment, and I2’s signing identity for every delivery). The routes are its own declared event type names, each with its subscribers, from events (EventPlan::published_by): already in discover_event_subscribers’ order, so the generated table (and so the fan-out order for a multi-subscriber event) is deterministic build to build.
emit_group_events_fanout_do
#3562 (G3-1): the one events fan-out of a [deploy.workers.<key>] group, serving every publishing member. publishers is the publishing members’ names; each one’s routes are its events’ in events, as emit_events_fanout_do takes them. A member tags each event it emits with its own name (publisher), because two members may declare an event of one name; the table is keyed <publisher>/<type>, and a delivery is signed as the publisher the event names.
emit_project
Emit TypeScript source for a single file inside a multi-file project, including cross-file and cross-commons imports computed from EmitProjectCtx. Emit one unit’s TypeScript, plus its source map (slice 1, ADR 0103).
emit_tsconfig
Emit the contents of out/tsconfig.json. The CLI uses tsc -p against this when running bynk test; users can also drive tsc against it directly to produce JS for deployment.
emit_tsconfig_with_source_maps
The bynk test --coverage variant (#854): the same config with sourceMap enabled, so tsc emits the .js.maps the coverage remap consumes (hop 1, .js → emitted .ts). Kept coverage-only rather than folded into the default so a normal bynk test / deployment tsc run ships no .js.maps. The runner overwrites the default out/tsconfig.json with this before tsc.
emit_worker_compose
emit_worker_entry
escape_ts_string
The one TypeScript string-literal escaper lives in bynk_ts (crate-hygiene A2); the emitter keeps its historical name for it. Escapes a string for embedding in a TypeScript double-quoted string literal. The one definition: the printer’s TsLit::Str, bynk-emit’s escape_ts_string and bynk-check’s wire defaults all splice into generated TypeScript and must never disagree.
field_spec_source
The same object as TypeScript source ({ name: "sid", wire: "__Host-sid", kind: … }), for the system-tier drivers and the Form lowering, which write text.
form_body_specs
#3276: the body field spec of a @form or @multipart handler, as the system test drivers write the body ((name, wire kind, list, option)).
native_platforms_of_context
v0.19 (decision 0017): the native platforms a context’s in-process closure commits it to: every unit whose provider its compose would instantiate (local providers’ given recursion plus the capabilities its handlers reference), mapped through bynk_check::firstparty::platform_of. Each platform carries an exemplar unit for the diagnostic message. Service consumes edges (RPC under workers) do not contribute: only the provider-instantiation walk, which is in-process by construction.
renamed_specs_source
#3343: the QueryField array a system-tier driver passes the request writers (__queryString, __cookieString) for a typed record parameter, when a field of the record is renamed by @name; None otherwise (the writers need no table).
runtime_import_for
Compute the runtime import specifier for a module at from_source. For a file at commerce/payment.ts the runtime sits two levels up, so this returns ../runtime.js; for a top-level file it returns ./runtime.js.
table_has_plain_json
#2858: whether any from http route in table writes plain JSON, so the generated Option encoders carry the plain branch.
ts_ident
The TypeScript spelling of a user identifier in a binding or reference position. Defined in bynk_check::emitted_names so the language server’s inline values (#2476) name the same variable the emitter declares. The TypeScript spelling of a user identifier in a binding or reference position (params, locals, function names, import names). Bynk identifiers that are illegal as TS binding names — the JS reserved words plus the strict-mode/module sets (emitted modules are always strict ESM) — and names the emitter itself introduces alongside user bindings (deps) are renamed into the generated-name namespace (__id_<name>), which the parser keeps free of user identifiers. Property/field names never pass through here: reserved words are legal there, and record field names are wire format.
ts_specifier
Render a path as a TypeScript module specifier: always forward slashes. Path::display() uses the platform separator, and on Windows that emitted import ... from "./commerce\orders.js" — broken ESM output, caught by the first CI matrix run on windows-latest.
ty_to_type_ref
v0.22b: a checker Ty rendered back to a TypeRef for the codec machinery (which is TypeRef-driven). None for types the codec rejects anyway (functions, effects, type variables). pub(crate) since P6.28 (design/tracks/the-ir.md §6a): project/tests_emit.rs’s own drain of RuntimeUse::json_codec_roots (a sibling module tree, not a descendant of emitter) needs this same conversion, once, right before collect_codec_closure — the one remaining consumer still genuinely TypeRef-driven.
unexported_type_renames
#1932: the renames rename_unexported_types gives consumed context c’s types, as original → renamed, for the call site: a cross-context call names the codecs emit_consumed_context_helpers generates under the same names. Computed once per consumed context, where the emitter’s CrossContextInfo is assembled, from the inputs the generator uses.