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). matchlowers to a switch on.tag; in tail position it inlines, otherwise it becomes an IIFE.islowers to a tag check; bindings becomeconstdeclarations on the truthy side ofif/&&.
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>.tsfor a multi-file commons or context. - containers
- #3477 (slice C1): the Durable Object classes of a Worker’s
Containerinstances. - contracts
bynk-contracts.jsongeneration 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_projectdrives to render each top-level Bynk declaration into TypeScript. Split out ofemitter.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 everyemitter::emit::Xandemitter::Xpath 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 assuper::tco::plan,super::commons_alias,super::serialisation::…andsuper::ty_to_type_ref. - http_
client bynk client(#3508, slice BC1): the typed TypeScript client for a project’sfrom httpservices, one module a front end imports.- runtime_
files - The runtime as per-module files (ADR 0615, #2426).
- secrets
bynk-secrets.jsongeneration 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 (
Artefactsis a keyed set of typed documents, never aStringat construction) landable ahead ofbynk-ts(Arc B, P7.5+), sincewrangler.tomlis the one documentbynk-emitproduces that isn’t TypeScript. Not a general TOML library:TomlValuerepresents exactly whatemitter::wrangler::emit_wrangler_tomlneeds to build awrangler.tomltoday, no more. - ts_
types - TypeScript type rendering:
ts_type_ref*,ts_ty, and theTsTypebuilders. - 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’swrangler.tomland sidecars, rendered from the binding model the build derived once (WorkerBindings). The driver builds aWorkersEmitfrom the checked project and its options and callsWorkersEmit::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.tomlgeneration per Worker (v0.8 §4.4 / §4.5).
Structs§
- Compose
Facts - Everything
ComposePlan::decideneeds, as plain data. - Compose
Plan - What an application composes.
- Compose
Unit - One unit of the plan: facts, not text.
- Compose
Unit Facts - What the builder reads off one unit’s checked table. Plain data.
- Consumed
Surface - A consumed context’s service surface, as the consumer’s
depscarries it on the Bundle target (divergence 6). - Event
Plan - Who subscribes to what, keyed
(publishing context, event). Plain facts: each renderer decides how to deliver. - Event
Subscription - One subscription: a service that subscribes to a publisher’s event, and whether a delivery to it carries the event’s envelope.
- Exec
Needs - Whether a unit’s service handlers hand work to the execution context
(
detach,withinorrace, #2719). The two targets read different predicates, so both are facts (divergence 4 of #3928). - Internal
Fault - One checker fact the emitter needed and did not find: the
.bynkspan of the construct being lowered, and a description of the fact. - Runtime
Use - Per-module accumulator of conditional runtime-helper references.
Constants§
- COOKIES_
ROUTE_ SUFFIX - #3277: marks a route’s
cookiesrecord in the system drivers’ route-body map, so a typed record in a mixed typed-and-Wirecall is sent as aCookieheader. - EVENTS_
WIRE_ EVENT_ TS_ TYPE - Events track, slice 2 (spine #936): the TS type of one buffered/fanned-out
event — a handler’s
__eventslocal, the__eventsDispatchdeps field (service, agent, provider, and the Bundle/Workers dispatch closures that implement it), and the fan-out DO’sFanoutEvent(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’sdispatchToEventsFanout,runtime/src/boundary.ts’sdeliverEvent) 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
__extraHeadersslot (a route that declares noheaders:). - FORM_
ROUTE_ SUFFIX - #3276: marks a
@formroute in the system drivers’ route-body map, so a typed body in a mixed typed-and-Wirecall is written as a form (a=1&b=x), not JSON. - MISSING_
CHECKER_ FACT - The diagnostic code every
InternalFaultis 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(…)) throughresolve—CrossContextInfo::resolve_prefix, or its equivalent over the unit’sconsumes. A handler that constructs an agent hands its owndepsto the agent’s methods (#1960), so itsdeps.envtype must name these, and the Worker must bind them. Syntactic because a file’shandlers.tsis 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) contextctx’s closure reaches bare, as(unit, capability), in order: the bare-resources walk’scrate::emit_model::bare_singleton_markers. - call_
handler_ needs_ exec - Whether a service’s
on callhandler hands work to the execution context (detach,withinorrace, directly or through the functions it calls or names, #2719), so the Bundle target’s__makeSurfacedeps 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_sourceis the project- relative path of the target.bynkfile. The result is suitable forimport { ... } 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, fromevents(EventPlan::published_by): already indiscover_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.publishersis the publishing members’ names; each one’s routes are its events’ inevents, asemit_events_fanout_dotakes 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 usestsc -pagainst this when runningbynk test; users can also drivetscagainst it directly to produce JS for deployment. - emit_
tsconfig_ with_ source_ maps - The
bynk test --coveragevariant (#854): the same config withsourceMapenabled, sotscemits the.js.maps the coverage remap consumes (hop 1,.js→ emitted.ts). Kept coverage-only rather than folded into the default so a normalbynk test/ deploymenttscrun ships no.js.maps. The runner overwrites the defaultout/tsconfig.jsonwith this beforetsc. - 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’sTsLit::Str,bynk-emit’sescape_ts_stringandbynk-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 theFormlowering, which write text. - form_
body_ specs - #3276: the body field spec of a
@formor@multiparthandler, 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’
givenrecursion plus the capabilities its handlers reference), mapped throughbynk_check::firstparty::platform_of. Each platform carries an exemplar unit for the diagnostic message. Serviceconsumesedges (RPC underworkers) do not contribute: only the provider-instantiation walk, which is in-process by construction. - renamed_
specs_ source - #3343: the
QueryFieldarray 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;Noneotherwise (the writers need no table). - runtime_
import_ for - Compute the runtime import specifier for a module at
from_source. For a file atcommerce/payment.tsthe 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 httproute intablewrites plain JSON, so the generatedOptionencoders carry the plain branch. - ts_
ident - The TypeScript spelling of a user identifier in a binding or reference
position. Defined in
bynk_check::emitted_namesso 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 emittedimport ... 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
Tyrendered back to aTypeReffor the codec machinery (which isTypeRef-driven).Nonefor 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 ofRuntimeUse::json_codec_roots(a sibling module tree, not a descendant ofemitter) needs this same conversion, once, right beforecollect_codec_closure— the one remaining consumer still genuinelyTypeRef-driven. - unexported_
type_ renames - #1932: the renames
rename_unexported_typesgives consumed contextc’s types, asoriginal → renamed, for the call site: a cross-context call names the codecsemit_consumed_context_helpersgenerates under the same names. Computed once per consumed context, where the emitter’sCrossContextInfois assembled, from the inputs the generator uses.