Skip to main content

bynk_emit/emitter/
workers_entry.rs

1//! Per-Worker `index.ts` generation (v0.8 §4.3, v0.9 §5.1).
2//!
3//! Each Worker exports a `default { fetch }` handler that first checks
4//! for the internal Service Binding prefix (`/_bynk/call/`) and dispatches
5//! to the matching `on call` service operation, then matches the request
6//! method + path against any `on http` routes the context declares.
7//! Validation and uncaught errors map to 400 / 500 respectively.
8//!
9//! Arc C slice 4 (#1323): `emit_worker_entry` and its four helpers build a
10//! real `bynk_ts::TsProgram` directly instead of `writeln!`-ing a `String` —
11//! this file's own conversion, closing the fourth Arc C slice (`workers.rs`
12//! was the third, #1321).
13
14use bynk_check::symbols::UnitTable;
15
16use crate::emitter::RuntimeUse;
17use crate::ts_build::{
18    await_expr, call, cond_expr, const_, const_typed, expr_stmt, ident, member, method_call, new,
19    return_, str_lit,
20};
21use bynk_ts::{
22    TsBindingName, TsDecl, TsExpr, TsObjectEntry, TsParam, TsProgram, TsStmt, TsType, TsTypeMember,
23};
24
25mod admin;
26mod call;
27mod email;
28mod events;
29mod field_specs;
30mod http;
31mod http_policy;
32mod queue;
33mod respond;
34mod scheduled;
35mod websocket;
36mod wire;
37
38pub(crate) use admin::INSPECT_PREFIX;
39use admin::{admin_routes, inspect_registry_export};
40use call::{FOREIGN_CALLERS, call_dispatch};
41use events::events_delivery_route;
42pub use field_specs::{
43    field_spec_source, form_body_specs, renamed_specs_source, table_has_plain_json,
44};
45pub(crate) use field_specs::{query_leaf_kind, record_field_specs};
46use http::{collect_http_routes, emit_http_route_dispatch};
47use http_policy::{
48    CorsService, PathMethods, SecurityService, build_cors_services, build_path_method_table,
49    build_security_services, cors_preflight, method_fall_through,
50};
51use queue::{collect_queue_routes, push_message_entries};
52use respond::{
53    MISS_HELPER, REPORT_FAULT_HELPER, fault_detail, miss, report_fault, text_response,
54    try_catch_stmt,
55};
56use scheduled::{collect_cron_routes, emit_scheduled_handler};
57use websocket::{collect_ws_open_routes, ws_upgrade_dispatch};
58pub(crate) use wire::{deserialise_call, wire_ident};
59
60/// What `fetch`'s catch does with a fault (#1825): log it, report it, and answer
61/// the bare 500. #3580: a traced build also hands the fault to the request's record.
62fn fault_handler(context: &str, trace: bool) -> Vec<TsStmt> {
63    let mut handler = vec![expr_stmt(method_call(
64        ident("globalThis.console"),
65        "error",
66        vec![
67            TsExpr::template_lit(
68                vec![format!("{context} "), " faulted".to_string()],
69                vec![ident("__route")],
70            ),
71            fault_detail("e"),
72        ],
73    ))];
74    if trace {
75        handler.push(expr_stmt(call(ident("__traceFault"), vec![ident("e")])));
76    }
77    handler.push(report_fault());
78    handler.push(return_(Some(call(
79        ident("__faultResponse"),
80        vec![str_lit(context.to_string()), ident("__route")],
81    ))));
82    handler
83}
84
85/// #3580: a traced build moves the dispatch (with any edge-cache guard) into
86/// `__bynkTracedFetch`, and `fetch` serves each request under a record that
87/// prints one `__bynk_trace:` line as the response is ready. Returns `fetch`'s
88/// new body.
89fn traced_fetch(
90    context: &str,
91    header_decls: &mut Vec<TsStmt>,
92    fetch_params: &[TsParam],
93    fetch_return: &Option<TsType>,
94    fetch_body: Vec<TsStmt>,
95) -> Vec<TsStmt> {
96    header_decls.push(TsStmt::decl(
97        TsDecl::Function {
98            name: "__bynkTracedFetch".to_string(),
99            generics: Vec::new(),
100            params: fetch_params.to_vec(),
101            return_type: fetch_return.clone(),
102            body: fetch_body,
103            is_async: true,
104            inline: false,
105        },
106        None,
107    ));
108    vec![return_(Some(call(
109        ident("__traceFetch"),
110        vec![
111            str_lit(context.to_string()),
112            ident("__bynkTracedFetch"),
113            ident("request"),
114            ident("env"),
115            ident("ctx"),
116        ],
117    )))]
118}
119
120/// #3386: the cookie a route's `SignedCookie` seam reads, if it has one.
121fn signed_cookie_name(
122    h: &bynk_syntax::ast::Handler,
123    actors: &std::collections::HashMap<String, bynk_syntax::ast::ActorDecl>,
124) -> Option<String> {
125    bynk_check::actors::signed_cookie_seam_for(h, actors).map(|s| s.cookie)
126}
127
128/// #3994: the credential headers a route's seam consumes, which the handler's `RequestHeaders`
129/// omits: `authorization` for a `Bearer` or `Oidc` actor, the signature header for a `Signature`
130/// one. An actor sum hides what any member reads, because the entry builds the view before the
131/// sum's wrapper resolves which member matched.
132fn consumed_credential_headers(
133    h: &bynk_syntax::ast::Handler,
134    actors: &std::collections::HashMap<String, bynk_syntax::ast::ActorDecl>,
135) -> Vec<String> {
136    use bynk_check::actors::SumMemberSeam;
137    let mut out: Vec<String> = Vec::new();
138    let mut hide = |name: &str| {
139        let name = name.to_ascii_lowercase();
140        if !out.contains(&name) {
141            out.push(name);
142        }
143    };
144    if let Some(members) = bynk_check::actors::sum_members_for(h, actors) {
145        for m in &members {
146            match &m.seam {
147                SumMemberSeam::Bearer { .. } => hide("authorization"),
148                SumMemberSeam::Signature(s) => hide(&s.header),
149                SumMemberSeam::None => {}
150            }
151        }
152        return out;
153    }
154    if bynk_check::actors::bearer_seam_for(h, actors).is_some()
155        || bynk_check::actors::oidc_seam_for(h, actors).is_some()
156    {
157        hide("authorization");
158    }
159    if let Some(s) = bynk_check::actors::signature_seam_for(h, actors) {
160        hide(&s.header);
161    }
162    out
163}
164
165/// #3477: each container's Durable Object class lives in `containers.ts`
166/// (generated by `emit_containers_ts`) and is re-exported from the entry the
167/// same way an agent's is.
168///
169/// A Worker group's members do not re-export them: `containers.ts` belongs to
170/// the Worker, so the group's entry exports the classes of all its members once.
171fn container_class_reexport(table: &UnitTable, member_mode: bool) -> Option<TsStmt> {
172    if member_mode {
173        return None;
174    }
175    let mut names: Vec<String> = table
176        .derived
177        .iter()
178        .filter(|(_, d)| d.is_container())
179        .map(|(capability, _)| bynk_check::containers::container_class_name(capability))
180        .collect();
181    names.sort();
182    (!names.is_empty()).then(|| {
183        TsStmt::decl(
184            TsDecl::ReExport {
185                names,
186                from: "./containers.js".to_string(),
187            },
188            None,
189        )
190    })
191}
192
193/// L7 (#2414, Decision C): an opted-in Worker's `fetch`, which runs what
194/// `__bynkFetch` answers through `edgeCacheGuard`. The guard can answer with a
195/// copy, which would drop a member's miss mark, so a member re-marks the copy
196/// when the answer it guarded was a miss.
197pub(super) fn edge_cache_return(member_mode: bool) -> Vec<TsStmt> {
198    let answer = await_expr(call(
199        ident("__bynkFetch"),
200        vec![ident("request"), ident("env"), ident("ctx")],
201    ));
202    let guarded =
203        |response: TsExpr| call(ident("__edgeCacheGuard"), vec![ident("request"), response]);
204    if !member_mode {
205        return vec![return_(Some(guarded(answer)))];
206    }
207    vec![
208        const_("__answer", answer),
209        const_("__guarded", guarded(ident("__answer"))),
210        return_(Some(cond_expr(
211            call(ident("isMiss"), vec![ident("__answer")]),
212            call(ident("__miss"), vec![ident("__guarded")]),
213            ident("__guarded"),
214        ))),
215    ]
216}
217
218/// Events track, slice 0 (spine #936, ADR 0284): the re-export of the fan-out DO,
219/// which lives in its own file (`events_fanout.ts`, not `handlers.ts`; a fan-out
220/// DO has no backing `AgentDecl` for `emit_agent` to emit it from). A group's one
221/// fan-out is exported by the group's entry, not a member's (#3562).
222fn fanout_reexport(
223    context: &str,
224    layout: &bynk_project::worker_layout::WorkerLayout,
225    wanted: bool,
226) -> Option<TsStmt> {
227    wanted.then(|| {
228        TsStmt::decl(
229            TsDecl::ReExport {
230                names: vec![crate::emitter::wrangler::EVENTS_FANOUT_CLASS_NAME.to_string()],
231                from: layout.own_module_specifier(context, "events_fanout.ts"),
232            },
233            None,
234        )
235    })
236}
237
238#[allow(clippy::too_many_arguments)]
239pub fn emit_worker_entry(
240    context: &str,
241    layout: &bynk_project::worker_layout::WorkerLayout,
242    table: &UnitTable,
243    // v0.177 (#643): this context's own contract hash per `on call` service.
244    own_contracts: &std::collections::BTreeMap<String, String>,
245    // #2554: the older contract hashes each service also accepts, from the
246    // contracts lock. Absent for a service that accepts only its own.
247    accepted_contracts: &std::collections::BTreeMap<String, Vec<String>>,
248    // Locale capability track, slice 2 (#882): whether `compose` was widened
249    // to take an optional `request` (the bool `emit_worker_compose` itself
250    // returned) — only `fetch` has a `Request` in scope, never
251    // `scheduled`/`queue`, so the two entry points need distinct compose
252    // calls, not one shared string.
253    needs_locale_request: bool,
254    // #1187's slice 6 plumbing — see `emit_worker_compose`'s own matching
255    // parameter (`emitter/workers.rs`) for the full grounding.
256    uses_emit: bool,
257    // #2136 (ADR DECISION B): the test build of a context a `system` case
258    // drives. Its `scheduled` entry stores each cron handler's `Result` on the
259    // execution-context double the harness supplies, so the case's
260    // `svc.schedule(…)` yields the handler's own result. Never set for a
261    // deployable build: that build carries no suites.
262    scheduled_result_hook: bool,
263    // #2252: the types this context takes from a consumed *context* (not
264    // declared here). Each imports type-only (#661), so the entry validates a
265    // path parameter of one with this context's own codec, not `<T>.of`.
266    consumed_types: &std::collections::HashSet<String>,
267    // State-migrations S4 (#2259 Decision D): each versioned agent class this
268    // Worker hosts, with its lock version, for the `/_bynk/migrate/` route.
269    // Empty when the build has no lock or the context hosts no agent.
270    migratable: &[(String, i64)],
271    // #2719: whether any of this context's service handlers hands work to the
272    // execution context, from the checker's needs-context set.
273    ctx_uses_send: bool,
274    // #2903: the context's own types plus those of the commons it `uses`, so a
275    // query field typed by an imported refined type or enum resolves to its real
276    // wire kind rather than falling through to `string`.
277    visible_types: &std::collections::HashMap<String, std::sync::Arc<bynk_syntax::ast::TypeDecl>>,
278    // #3580: wrap `fetch` in the request recorder (`bynk dev --trace-events` only).
279    trace: bool,
280    // #3581: the dev inspect route's agent classes (else empty), and if this member lists them.
281    inspect: (&[String], bool),
282) -> TsProgram {
283    let member_mode = layout.is_member(context);
284    let mut program = TsProgram::new();
285    // Which conditional runtime helpers the entry's own inbound/outbound codecs
286    // reach for; read back below to decide the import injection.
287    let runtime_use = RuntimeUse::default();
288    program.push(TsStmt::comment(
289        "Generated by bynk — do not edit by hand.",
290        None,
291    ));
292    program.push(TsStmt::comment(
293        format!("Worker entry point for context `{context}`."),
294        None,
295    ));
296
297    // v0.79: if any handler uses `detach`, each entry point captures the runtime's
298    // execution context and threads it into `compose`, so a fire-and-forget send
299    // can hand its promise to `waitUntil`. Otherwise the signatures are unchanged.
300    let exec_params: Vec<TsParam> = if ctx_uses_send {
301        vec![TsParam::new(
302            "ctx".to_string(),
303            Some(TsType::Object(vec![TsTypeMember::method(
304                "waitUntil",
305                vec![TsParam {
306                    name: "promise".to_string(),
307                    ty: Some(TsType::named_with_args(
308                        "globalThis.Promise",
309                        vec![TsType::named("unknown")],
310                    )),
311                    optional: false,
312                    rest: false,
313                    array_pattern: None,
314                    default: None,
315                }],
316                TsType::named("void"),
317            )])),
318        )]
319    } else {
320        Vec::new()
321    };
322    // L7 (#2414, Decision E): an `EdgeCache` instance purges through the
323    // entry's `ctx`, so `compose` takes it as `exec` (optional when nothing
324    // sends: an in-process caller may pass none), and so does `scheduled`.
325    let edge_cache = table.derived.values().any(|d| d.is_edge_cache());
326    let compose_takes_exec = ctx_uses_send || edge_cache;
327    // #2192: `fetch` and `queue` always take `ctx`, which their fault handlers
328    // report through. Optional when no send needs it, so an in-process caller
329    // (the test runner) can still pass just `request`/`batch` and `env`.
330    let fault_exec_params: Vec<TsParam> = if ctx_uses_send {
331        exec_params.clone()
332    } else {
333        vec![TsParam::optional(
334            "ctx".to_string(),
335            Some(TsType::Object(vec![TsTypeMember::method(
336                "waitUntil",
337                vec![TsParam {
338                    name: "promise".to_string(),
339                    ty: Some(TsType::named_with_args(
340                        "globalThis.Promise",
341                        vec![TsType::named("unknown")],
342                    )),
343                    optional: false,
344                    rest: false,
345                    array_pattern: None,
346                    default: None,
347                }],
348                TsType::named("void"),
349            )])),
350        )]
351    };
352    // `fetch` alone has a `request` in scope; `scheduled`/`queue` never do.
353    let fetch_compose_args: Vec<TsExpr> = match (needs_locale_request, compose_takes_exec) {
354        (true, true) => vec![ident("env"), ident("request"), ident("ctx")],
355        (true, false) => vec![ident("env"), ident("request")],
356        (false, true) => vec![ident("env"), ident("ctx")],
357        (false, false) => vec![ident("env")],
358    };
359    let other_compose_args: Vec<TsExpr> = if compose_takes_exec {
360        vec![ident("env"), ident("ctx")]
361    } else {
362        vec![ident("env")]
363    };
364
365    // Collect HTTP routes across all services, sorted so literal-segment
366    // routes precede parameter-segment routes that share the same prefix.
367    let mut service_names: Vec<&String> = table.services.keys().collect();
368    service_names.sort();
369    let http_routes = collect_http_routes(
370        table,
371        &service_names,
372        visible_types,
373        edge_cache,
374        needs_locale_request,
375    );
376
377    // v0.131 (ADR 0159): the per-service CORS policies. A `from http` service
378    // with a `cors { }` section gets one synthesised `CorsPolicy` constant; its
379    // routes are answered with a preflight `OPTIONS` branch and stamped with the
380    // `Access-Control-*` headers. Allow-methods is derived from the service's
381    // routes (never restated); allow-headers defaults to `content-type` (plus
382    // `Authorization` when the service has a Bearer route) unless overridden.
383    let cors_services: Vec<CorsService> = build_cors_services(&service_names, table, &http_routes);
384
385    // v0.141 (ADR 0164): the per-service security-headers policies. Unlike CORS,
386    // *every* `from http` service with routes gets one — the safe header
387    // (`nosniff`) is on by default, so a service with no `security { }` still
388    // stamps the defaults. Its responses (and the synthesised preflight / `405` /
389    // `304`) carry `applySecurityHeaders`, composing with `applyCors`.
390    let security_services: Vec<SecurityService> =
391        build_security_services(&service_names, table, &http_routes);
392
393    // v0.139 (ADR 0162): the per-path method table driving the method-aware
394    // router fall-through — a wrong method to a live path is a `405 + Allow`, a
395    // bare `OPTIONS` is a `204 + Allow`, and both are derived from this one table
396    // (the same derivation CORS reads for its allow-methods).
397    let path_methods: Vec<PathMethods> =
398        build_path_method_table(&http_routes, &cors_services, &security_services);
399
400    // v0.10a: the cron handlers across all services.
401    let cron_routes = collect_cron_routes(table, &service_names);
402
403    // v0.10b: the queue consumers across all services.
404    let queue_routes = collect_queue_routes(table, &service_names);
405
406    // v0.104 (real-time track slice 3b): the `from websocket` upgrade routes.
407    let ws_open_routes = collect_ws_open_routes(table, &service_names);
408
409    // The runtime import is read off the finished tree (below), so the header is held until the
410    // body has been built (1A.36b-2).
411    let mut header_decls: Vec<TsStmt> = vec![
412        TsStmt::decl(
413            TsDecl::Import {
414                type_only: false,
415                names: vec!["compose".to_string(), "type Env".to_string()],
416                from: layout.own_module_specifier(context, "compose.ts"),
417            },
418            None,
419        ),
420        TsStmt::decl(
421            TsDecl::ImportNamespace {
422                type_only: false,
423                alias: "handlers".to_string(),
424                from: layout.own_handlers_specifier(context),
425            },
426            None,
427        ),
428    ];
429
430    // v0.9.2: re-export each agent's Durable Object class from the Worker
431    // entry. Cloudflare resolves a `class_name` binding against the named
432    // exports of the Worker's `main`, so the DO classes declared in
433    // `handlers.ts` must be visible here.
434    let mut agent_names: Vec<&String> = table.agents.keys().collect();
435    agent_names.sort();
436    //
437    // #3202: each is exported wrapped, so the instance runs the handlers that
438    // reach it one at a time (`__serialiseAgentClass`, `runtime/src/agent.ts`).
439    for name in &agent_names {
440        header_decls.push(TsStmt::decl(
441            TsDecl::Export(Box::new(TsDecl::ConstDecl {
442                name: name.to_string(),
443                ty: None,
444                init: call(
445                    ident("__serialiseAgentClass"),
446                    vec![member(ident("handlers"), name.as_str())],
447                ),
448            })),
449            None,
450        ));
451    }
452    header_decls.extend(fanout_reexport(context, layout, uses_emit && !member_mode));
453
454    header_decls.extend(container_class_reexport(table, member_mode));
455    header_decls.extend(inspect_registry_export(inspect.0));
456
457    let mut fetch_params: Vec<TsParam> = vec![
458        TsParam::new(
459            "request".to_string(),
460            Some(TsType::named("globalThis.Request")),
461        ),
462        TsParam::new("env".to_string(), Some(TsType::named("Env"))),
463    ];
464    fetch_params.extend(fault_exec_params.iter().cloned());
465
466    let mut fetch_body: Vec<TsStmt> = vec![
467        const_(
468            "url",
469            new(
470                ident("globalThis.URL"),
471                vec![member(ident("request"), "url")],
472            ),
473        ),
474        const_("path", member(ident("url"), "pathname")),
475        const_("method", member(ident("request"), "method")),
476        const_(
477            "surface",
478            call(ident("compose"), fetch_compose_args.clone()),
479        ),
480    ];
481    // v0.131: the synthesised CORS policy constants, one per CORS-enabled service.
482    for cs in &cors_services {
483        fetch_body.push(const_typed(
484            cs.const_name.clone(),
485            TsType::named("__CorsPolicy"),
486            cs.literal.clone(),
487        ));
488    }
489    // v0.141: the synthesised security-headers policy constants, one per
490    // `from http` service (with routes) — the default `nosniff` and any opt-in HSTS.
491    for ss in &security_services {
492        fetch_body.push(const_typed(
493            ss.const_name.clone(),
494            TsType::named("__SecurityPolicy"),
495            ss.literal.clone(),
496        ));
497    }
498
499    let mut try_body: Vec<TsStmt> = Vec::new();
500
501    // 1. Internal Service Binding dispatch.
502    //
503    // I3 (#1971): the foreign callers any `on call` handler here admits, by
504    // actor name. Empty for a Worker that admits none, whose dispatch then
505    // admits Bynk contexts alone, as before.
506    let mut foreign_callers: Vec<bynk_check::actors::ForeignCaller> = Vec::new();
507    for sname in &service_names {
508        for h in &table.services[*sname].handlers {
509            for f in bynk_check::actors::call_admission_for(h, &table.actors)
510                .map(|a| a.foreign)
511                .unwrap_or_default()
512            {
513                if !foreign_callers.iter().any(|g| g.actor == f.actor) {
514                    foreign_callers.push(f);
515                }
516            }
517        }
518    }
519    let has_foreign = !foreign_callers.is_empty();
520    if has_foreign {
521        fetch_body.push(const_typed(
522            FOREIGN_CALLERS,
523            TsType::named_with_args(
524                "globalThis.Record",
525                vec![TsType::named("string"), TsType::named("string")],
526            ),
527            TsExpr::object(
528                foreign_callers
529                    .iter()
530                    .map(|f| (f.actor.clone(), str_lit(f.secret.clone())))
531                    .collect(),
532            ),
533        ));
534    }
535    // The foreign callers any `on call` handler admits are `foreign_callers`
536    // above; `has_foreign` makes the dispatch check them.
537    try_body.extend(call_dispatch(
538        context,
539        member_mode,
540        table,
541        &service_names,
542        (own_contracts, accepted_contracts),
543        has_foreign,
544        &runtime_use,
545    ));
546    try_body.push(TsStmt::blank(None));
547
548    // 1.25. The internal admin routes: see `admin_routes`.
549    try_body.extend(admin_routes(context, member_mode, migratable, inspect));
550
551    // 1.5. WebSocket upgrade dispatch: see `ws_upgrade_dispatch`.
552    if !ws_open_routes.is_empty() {
553        try_body.push(ws_upgrade_dispatch(&ws_open_routes));
554        try_body.push(TsStmt::blank(None));
555    }
556
557    // 1.6. Events dispatch: see `events_delivery_route`.
558    if let Some(events) =
559        events_delivery_route(context, member_mode, table, &service_names, &runtime_use)
560    {
561        try_body.push(events);
562        try_body.push(TsStmt::blank(None));
563    }
564
565    // v0.131 (ADR 0159): CORS preflight, one branch per CORS-enabled service.
566    for cs in &cors_services {
567        try_body.push(cors_preflight(cs, &security_services));
568    }
569
570    // 2. External HTTP routes.
571    for route in &http_routes {
572        let cors_const = cors_services
573            .iter()
574            .find(|cs| cs.service == route.service)
575            .map(|cs| cs.const_name.as_str());
576        // v0.141: every `from http` route's service has a security policy constant.
577        let security_const = security_services
578            .iter()
579            .find(|ss| ss.service == route.service)
580            .map(|ss| ss.const_name.as_str());
581        try_body.push(emit_http_route_dispatch(
582            route,
583            cors_const,
584            security_const,
585            &runtime_use,
586            consumed_types,
587        ));
588    }
589
590    // v0.139 (ADR 0162): the method-aware router fall-through, one branch per path.
591    for pm in &path_methods {
592        try_body.push(method_fall_through(pm, member_mode));
593    }
594
595    try_body.push(return_(Some(miss(
596        member_mode,
597        text_response("Not Found", 404),
598    ))));
599
600    // #1825: a fault answers a bare 500, never leaking the error to the
601    // client (#184), but it is logged here first, with the context and the
602    // dispatch that faulted: the route *pattern* or `call <service>`, never
603    // the request, so no key or value reaches the log. Caught, it is no
604    // uncaught exception the platform would record, so without this a fault
605    // left no trace at all. #2053: the log carries the error's stack
606    // (`fault_detail`), not its bare string, so a tail shows the frames.
607    // #2192: they stay `index.js:L:C`, since Cloudflare maps an uploaded
608    // source map only onto an exception it records, so the fault is also
609    // reported (`__bynkReportFault`). It does not rethrow: that would replace
610    // this 500 with the platform's own error page, and the queue handler's
611    // per-message `retry()` with a whole-batch retry. #2193: the 500 comes
612    // from `__faultResponse`, which marks a fault in an `on call` service with
613    // this context's name, so the calling Worker reports `CalleeFaulted`
614    // naming it rather than a bare `Transport`.
615    fetch_body.push(TsStmt::let_stmt(
616        TsBindingName::Ident("__route".to_string()),
617        Some(TsType::named("string")),
618        Some(str_lit("request")),
619        None,
620    ));
621    fetch_body.push(try_catch_stmt(
622        try_body,
623        Some("e"),
624        fault_handler(context, trace),
625    ));
626
627    let fetch_return = Some(TsType::named_with_args(
628        "globalThis.Promise",
629        vec![TsType::named("globalThis.Response")],
630    ));
631    // L7 (#2414, Decision C): an opted-in Worker's dispatch moves into
632    // `__bynkFetch`, and `fetch` runs whatever it answers through
633    // `edgeCacheGuard`, so the router's own answers (a `404`, a `405`, a
634    // rejection, a fault) say `no-store` too.
635    let fetch_body = if edge_cache {
636        header_decls.push(TsStmt::decl(
637            TsDecl::Function {
638                name: "__bynkFetch".to_string(),
639                generics: Vec::new(),
640                params: fetch_params.clone(),
641                return_type: fetch_return.clone(),
642                body: fetch_body,
643                is_async: true,
644                inline: false,
645            },
646            None,
647        ));
648        edge_cache_return(member_mode)
649    } else {
650        fetch_body
651    };
652    let fetch_body = if trace {
653        traced_fetch(
654            context,
655            &mut header_decls,
656            &fetch_params,
657            &fetch_return,
658            fetch_body,
659        )
660    } else {
661        fetch_body
662    };
663    let mut default_entries: Vec<TsObjectEntry> = vec![TsObjectEntry::method(
664        "fetch",
665        true,
666        fetch_params,
667        fetch_return,
668        fetch_body,
669    )];
670
671    // v0.10a: scheduled (cron) entry point. Dispatches on `event.cron`. A
672    // failing run has no retry channel, so an `Err` is logged and the run
673    // completes (v0.10 §5.1, [DECISION 3]).
674    if !cron_routes.is_empty() {
675        default_entries.push(emit_scheduled_handler(
676            &cron_routes,
677            if edge_cache {
678                &fault_exec_params
679            } else {
680                &exec_params
681            },
682            &other_compose_args,
683            scheduled_result_hook,
684        ));
685    }
686
687    // v0.10b: the queue (consumer) entry point; #3328: the email entry point.
688    push_message_entries(
689        table,
690        &queue_routes,
691        &fault_exec_params,
692        &other_compose_args,
693        &runtime_use,
694        &mut default_entries,
695    );
696
697    let runtime_import_at = program.stmts.len();
698    for decl in header_decls {
699        program.push(decl);
700    }
701    if member_mode {
702        // 1A.38: fixed authored snippet, no interpolation
703        program.push(TsStmt::raw_using(MISS_HELPER, &[]));
704    }
705    // 1A.38: fixed authored snippet, no interpolation
706    program.push(TsStmt::raw_using(REPORT_FAULT_HELPER, &[]));
707    program.push(TsStmt::decl(
708        TsDecl::ExportDefault(TsExpr::multiline_object_entries(default_entries)),
709        None,
710    ));
711
712    // 1A.36b-2: the runtime import is what the module's tree uses, after the banner and before
713    // the other imports.
714    let names =
715        super::runtime_header::derived_worker_runtime_names(&program.stmts[runtime_import_at..]);
716    for (i, stmt) in super::runtime_files::runtime_import_stmts(false, &names, "../../runtime.js")
717        .into_iter()
718        .enumerate()
719    {
720        program.stmts.insert(runtime_import_at + i, stmt);
721    }
722    // Each fixed import (`handlers`, `compose`) is kept only if the tree uses it.
723    program.prune_unused_imports();
724
725    program
726}
727
728/// #2341 (decision C): the compose-surface method a service's `on rejected`
729/// is reached by, when it declares one.
730fn rejected_surface(service: &bynk_syntax::ast::ServiceDecl, sname: &str) -> Option<String> {
731    service
732        .handlers
733        .iter()
734        .any(|h| h.kind == bynk_syntax::ast::HandlerKind::Rejected)
735        .then(|| format!("rejected_{sname}"))
736}
737
738#[cfg(test)]
739mod tests {
740    use super::respond::own_path_guard;
741    use super::*;
742
743    fn printed(stmts: &[TsStmt]) -> String {
744        stmts.iter().map(|s| bynk_ts::print_stmt(s, 0)).collect()
745    }
746
747    /// Default (non-member) output: the guard is the bare prefix test, nothing is
748    /// marked, and the edge-cache return is the one it has always been.
749    #[test]
750    fn outside_a_group_nothing_is_marked_or_gated() {
751        let guard = bynk_ts::print_expr(&own_path_guard(false, "/_bynk/call/", &[]));
752        assert_eq!(guard, "path.startsWith(\"/_bynk/call/\")");
753        let marked = bynk_ts::print_expr(&miss(false, text_response("Not Found", 404)));
754        assert!(!marked.contains("__miss"), "{marked}");
755        let edge = printed(&edge_cache_return(false));
756        assert!(
757            !edge.contains("isMiss") && !edge.contains("__miss"),
758            "{edge}"
759        );
760        assert!(
761            edge.contains("__edgeCacheGuard(request, await __bynkFetch("),
762            "{edge}"
763        );
764    }
765
766    /// The edge-cache guard can answer with a copy, so a member re-marks it.
767    #[test]
768    fn a_members_edge_cache_guard_keeps_a_miss_a_miss() {
769        let edge = printed(&edge_cache_return(true));
770        assert!(
771            edge.contains("isMiss(__answer) ? __miss(__guarded) : __guarded"),
772            "{edge}"
773        );
774    }
775}