Skip to main content

bynk_emit/emitter/emit/
handlers.rs

1//! Handler method names and labels, and the handler-body items that services, agents and free
2//! functions share: the `events` declaration, the result closure, the flush and release steps.
3
4use crate::emitter::lower_stmt::{Body, Item};
5use crate::ts_build::ident;
6use bynk_check::checker::TypedCommons;
7use bynk_model::{
8    IrHandlerKind, IrHttpMethod, ProtocolIr, lower_handler_kind_ir, lower_protocol_ir_from_commons,
9};
10use bynk_syntax::ast::{CommonsItem, Param};
11
12/// Synthesise a TypeScript-safe method name for an `on http METHOD path`
13/// handler. The result is used both as the key on the service object and
14/// as the identifier the Worker fetch handler invokes. Path parameter
15/// segments (`:name`) become `Param_name` to remain distinct from literal
16/// segments. (v0.9 §5.3)
17///
18/// Slice 1 of `#1542` (the IR cutover, `design/archive/retired-tracks.md`): this used to
19/// have an AST-typed `HttpMethod` twin, `http_handler_method_name` — deleted
20/// once its last production caller converted to this `IrHttpMethod` version,
21/// which every call site now holds already-resolved (`IrHandlerKind::Http`'s
22/// own payload) rather than re-deriving from `HandlerKind::Http`.
23pub fn http_handler_method_name_ir(method: IrHttpMethod, path: &str) -> String {
24    http_handler_method_name_from_str(method.as_str(), path)
25}
26
27fn http_handler_method_name_from_str(method: &str, path: &str) -> String {
28    let mut s = format!("http_{method}");
29    for seg in path.split('/').filter(|s| !s.is_empty()) {
30        s.push('_');
31        if let Some(rest) = seg.strip_prefix(':') {
32            s.push_str("Param_");
33            s.push_str(&sanitise_path_segment(rest));
34        } else {
35            s.push_str(&sanitise_path_segment(seg));
36        }
37    }
38    s
39}
40
41/// Slice 3 (semantic-debugging track, ADR 0105): the debug-metadata sidecar's
42/// `{ fn → label }` map — each emitted handler function paired with its Bynk
43/// operation label, so the debugger can name a stack frame `GET "/"` rather than
44/// `http_GET`. bynk_ts::TsExpr by re-walking the unit's handlers with the *same* naming
45/// functions the emitter uses (so the keys match the emitted function names);
46/// serialised as a JSON object (manual, like the source map — no serde). Returns
47/// `None` when the unit declares no handlers.
48pub fn collect_handler_labels(commons: &TypedCommons) -> Option<String> {
49    let mut entries: Vec<(String, String)> = Vec::new();
50    for item in &commons.commons.items {
51        match item {
52            CommonsItem::Service(s) => {
53                let (mut cron_idx, mut queue_idx) = (0usize, 0usize);
54                for h in &s.handlers {
55                    let pair = match lower_handler_kind_ir(&h.kind) {
56                        IrHandlerKind::Http { method, path } => (
57                            http_handler_method_name_ir(method, &path),
58                            format!("{} \"{}\"", method.as_str(), path),
59                        ),
60                        IrHandlerKind::Cron { expr } => {
61                            let n = cron_handler_method_name(&s.name.name, cron_idx);
62                            cron_idx += 1;
63                            (n, format!("cron \"{expr}\""))
64                        }
65                        IrHandlerKind::Message
66                            if matches!(
67                                lower_protocol_ir_from_commons(&s.protocol, commons),
68                                ProtocolIr::WebSocket { .. }
69                            ) =>
70                        {
71                            ("message".to_string(), "WebSocket message".to_string())
72                        }
73                        IrHandlerKind::Message => {
74                            let n = queue_handler_method_name(&s.name.name, queue_idx);
75                            queue_idx += 1;
76                            (n, "message".to_string())
77                        }
78                        IrHandlerKind::Call => {
79                            ("call".to_string(), handler_op_label("call", &h.params))
80                        }
81                        IrHandlerKind::Open => ("open".to_string(), "WebSocket open".to_string()),
82                        IrHandlerKind::Close => {
83                            ("close".to_string(), "WebSocket close".to_string())
84                        }
85                        // Events track, slice 0 (spine #936): exactly one
86                        // `on event` per `from Events(E)` service (no
87                        // pattern-refinement fan-out yet, so no index).
88                        IrHandlerKind::Event => ("event".to_string(), "event".to_string()),
89                        IrHandlerKind::Rejected => ("rejected".to_string(), "rejected".to_string()),
90                    };
91                    entries.push(pair);
92                }
93            }
94            CommonsItem::Agent(a) => {
95                for h in &a.handlers {
96                    if let Some(name) = &h.method_name {
97                        entries.push((name.name.clone(), handler_op_label(&name.name, &h.params)));
98                    }
99                }
100            }
101            CommonsItem::Type(_)
102            | CommonsItem::Fn(_)
103            | CommonsItem::Capability(_)
104            | CommonsItem::Provider(_)
105            | CommonsItem::Actor(_)
106            | CommonsItem::Messages(_)
107            | CommonsItem::Event(_)
108            | CommonsItem::Asset(_)
109            | CommonsItem::Embed(_)
110            | CommonsItem::Const(_) => {}
111        }
112    }
113    if entries.is_empty() {
114        return None;
115    }
116    // Dedup by key (e.g. two services each with an `on call` emit a `call` method in
117    // their own object — distinct in the emitted code, but one key here); keep the
118    // first so the JSON object is well-formed.
119    let mut seen = std::collections::HashSet::new();
120    let mut out = String::from("{");
121    let mut first = true;
122    for (k, v) in &entries {
123        if !seen.insert(k.clone()) {
124            continue;
125        }
126        if !first {
127            out.push(',');
128        }
129        first = false;
130        out.push_str(&bynk_project::json_string(k));
131        out.push(':');
132        out.push_str(&bynk_project::json_string(v));
133    }
134    out.push('}');
135    Some(out)
136}
137
138/// `name(p1, p2)` from a handler's parameters — the operation label for `call` and
139/// agent handlers (HTTP handlers use method + path instead).
140fn handler_op_label(name: &str, params: &[Param]) -> String {
141    let ps: Vec<String> = params.iter().map(|p| p.name.name.clone()).collect();
142    format!("{}({})", name, ps.join(", "))
143}
144
145/// Synthesise a TypeScript-safe method name for an `on cron` handler (v0.10a):
146/// `cron_<service>_<index>`, where `index` is the handler's position among the
147/// service's cron handlers in declaration order. The same key is computed at
148/// each emission site (the `handlers` method, the `compose` surface wrapper,
149/// and the `scheduled` dispatcher) by walking handlers in the same order, so it
150/// is collision-free and stable without encoding the schedule expression.
151pub fn cron_handler_method_name(service: &str, index: usize) -> String {
152    format!("cron_{service}_{index}")
153}
154
155/// Method name for an `on queue` handler (v0.10b): `queue_<service>_<index>`,
156/// by the handler's position among the service's queue handlers. Computed
157/// identically at the `handlers` method, the `compose` surface wrapper, and the
158/// `queue` dispatcher (queue names are unique context-wide, but the index keeps
159/// the key identifier-safe without sanitising the name).
160pub fn queue_handler_method_name(service: &str, index: usize) -> String {
161    format!("queue_{service}_{index}")
162}
163
164fn sanitise_path_segment(s: &str) -> String {
165    let mut out = String::with_capacity(s.len());
166    for ch in s.chars() {
167        if ch.is_ascii_alphanumeric() {
168            out.push(ch);
169        } else {
170            out.push('_');
171        }
172    }
173    out
174}
175
176/// Left-folds `parts` into one `+`-chained `bynk_ts::TsExpr::Binary` tree,
177/// matching `.join(" + ")`'s own left-to-right text join exactly —
178/// `TsBinaryOp::Add`'s own real, dominant site in this whole cluster (#1388).
179/// Panics on an empty `parts`; every real caller below already special-cases
180/// the empty-template case before reaching here.
181pub(super) fn join_plus(mut parts: Vec<bynk_ts::TsExpr>) -> bynk_ts::TsExpr {
182    let first = parts.remove(0);
183    parts
184        .into_iter()
185        .fold(first, |acc, next| bynk_ts::TsExpr::Binary {
186            op: bynk_ts::TsBinaryOp::Add,
187            left: Box::new(acc),
188            right: Box::new(next),
189        })
190}
191
192/// `const __events: ... = [];`.
193pub(super) fn events_decl_item() -> Item {
194    Item::Node(Box::new(bynk_ts::TsStmt::const_stmt(
195        bynk_ts::TsBindingName::Ident("__events".to_string()),
196        Some(bynk_ts::TsType::named_with_args(
197            "globalThis.Array",
198            vec![bynk_ts::TsType::named(
199                crate::emitter::EVENTS_WIRE_EVENT_TS_TYPE,
200            )],
201        )),
202        bynk_ts::TsExpr::array(Vec::new()),
203        None,
204    )))
205}
206
207/// `const <name> = <await >(<async >() => { <body> })();`: `body` run in a closure of its own, so
208/// that its `return`s resolve `name` rather than the enclosing function. The body sits inside the
209/// arrow, one step deeper than the declaration, where the printer lays it out and records its
210/// checkpoints.
211pub(super) fn iife_const_item(name: &str, awaited: bool, body: Body) -> Item {
212    let closure = bynk_ts::TsExpr::Arrow {
213        params: Vec::new(),
214        is_async: awaited,
215        generics: Vec::new(),
216        return_type: None,
217        body: Box::new(bynk_ts::TsArrowBody::Multiline(body.into_stmts())),
218    };
219    let call = bynk_ts::TsExpr::Call {
220        callee: Box::new(bynk_ts::TsExpr::Paren(Box::new(closure))),
221        args: Vec::new(),
222    };
223    let init = if awaited {
224        bynk_ts::TsExpr::Await(Box::new(call))
225    } else {
226        call
227    };
228    Item::Node(Box::new(bynk_ts::TsStmt::const_stmt(
229        bynk_ts::TsBindingName::Ident(name.to_string()),
230        None,
231        init,
232        None,
233    )))
234}
235
236/// The closure a handler body runs in so that its own `return`s resolve `__result`.
237pub(super) fn result_closure_item(body: Body) -> Item {
238    iife_const_item("__result", true, body)
239}
240
241/// `if (!(<test>)) return undefined;`: a handler that the guard `test` does not admit does nothing.
242pub(super) fn return_undefined_unless(test: bynk_ts::TsExpr) -> Item {
243    Item::Node(Box::new(crate::ts_build::if_(
244        crate::ts_build::not_expr(crate::ts_build::paren(test)),
245        crate::ts_build::return_(Some(crate::ts_build::ident("undefined"))),
246    )))
247}
248
249/// `if (__events.length > 0) { await deps.__eventsDispatch(__events); }`, with
250/// the call on its own lines in a braced block, or `inline` on one.
251pub(super) fn events_flush_item(inline: bool) -> Item {
252    let dispatch = bynk_ts::TsStmt::expr_stmt(
253        bynk_ts::TsExpr::Await(Box::new(bynk_ts::TsExpr::Call {
254            callee: Box::new(bynk_ts::TsExpr::Member {
255                object: Box::new(ident("deps")),
256                property: "__eventsDispatch".to_string(),
257            }),
258            args: vec![ident("__events")],
259        })),
260        None,
261    );
262    let then = if inline {
263        bynk_ts::TsStmt::inline_block(vec![dispatch], None)
264    } else {
265        bynk_ts::TsStmt::block(vec![dispatch], None)
266    };
267    let cond = bynk_ts::TsExpr::Binary {
268        op: bynk_ts::TsBinaryOp::GreaterThan,
269        left: Box::new(bynk_ts::TsExpr::Member {
270            object: Box::new(ident("__events")),
271            property: "length".to_string(),
272        }),
273        right: Box::new(bynk_ts::TsExpr::Lit(bynk_ts::TsLit::Num("0".to_string()))),
274    };
275    Item::Node(Box::new(bynk_ts::TsStmt::if_stmt(cond, then, None)))
276}
277
278pub(super) fn return_result_item() -> Item {
279    Item::Node(Box::new(bynk_ts::TsStmt::return_stmt(
280        Some(bynk_ts::TsExpr::Ident("__result".to_string())),
281        None,
282    )))
283}
284
285/// A service handler's body when it emits events directly: the buffered
286/// `__events`, the body inside the closure that resolves `__result`, then the
287/// flush to whatever composed the handler, and the result.
288pub(super) fn events_release_body(body: Body) -> Body {
289    let mut wrapped = Body::new();
290    wrapped.push(events_decl_item());
291    wrapped.push(result_closure_item(body));
292    wrapped.push(events_flush_item(false));
293    wrapped.push(return_result_item());
294    wrapped
295}