Skip to main content

bynk_emit/emitter/
runtime_header.rs

1//! The runtime import of a generated module, derived from the module's tree
2//! (1A.36b-1, #3737 Decision A).
3//!
4//! Every module the emitter or the test harness builds derives its header this way: a unit
5//! module since 1A.36b-1, the Worker `index.ts` and `compose.ts` since 1A.36b-2, and the
6//! generated test modules (`tests/*.test.ts`, in [`TEST_ORDER`]) since 1B.5e.
7//!
8//! A module's header used to be guessed before its body existed, by predicates
9//! over the source and flags the producers noted as a side effect, and each
10//! guess had to agree exactly with what the body later spelled. The body is
11//! built first now, and the header is what it uses: a runtime name is imported
12//! iff the tree uses it and does not declare it ([`bynk_ts::unbound_names_in`]),
13//! so an unused one is dropped and a used one cannot be missed.
14//!
15//! This module also builds the header itself, the banner and the runtime import
16//! of every module the emitter builds: [`write_header`] for a project-mode unit,
17//! [`header_single`] for single-file mode, and [`runtime_import_for`], the
18//! specifier they print.
19//!
20//! The names reach the existing [`split_runtime_import`], which partitions them
21//! by the runtime module that defines each.
22//!
23//! # What the tree cannot see
24//!
25//! Text the emitter still writes as a string is invisible to the closure, bar
26//! the names it declares with `TsStmt::raw_using`. A producer of such text must
27//! declare the runtime names it spells. `import_shadow.rs` is the net under
28//! that rule: for every module whose header is derived it asserts that each
29//! runtime export the printed code spells (outside strings and comments) is
30//! imported, so a name only text spells fails there rather than in `tsc`.
31//!
32//! [`split_runtime_import`]: super::runtime_files::split_runtime_import
33
34use std::path::Path;
35
36use crate::emit_model::{EmitProjectCtx, ImportExt};
37use bynk_check::checker::TypedCommons;
38use bynk_project::UnitKind;
39use bynk_ts::TsStmt;
40
41use super::runtime_files::{is_runtime_export, is_type_only_export};
42
43/// The order runtime names have always had in a generated import list. A
44/// derived name takes its place here, so the names a module keeps stay in the
45/// order they had; one this list does not know (a `Cmp`/`Decimal`/key helper
46/// the lowering picks by type) follows them, alphabetically.
47const ORDER: &[&str] = &[
48    // The fixed prefix.
49    "Ok",
50    "Err",
51    "Some",
52    "None",
53    "Result",
54    "Option",
55    "ValidationError",
56    "DecodeError",
57    "Connection",
58    // Agents.
59    "__DurableObjectState",
60    "__DurableObjectNamespace",
61    "__StateRegistry",
62    "__makeAgent",
63    "__noteAgentInstance",
64    "__inspectAgent",
65    "__historyBefore",
66    "__historyRecord",
67    "__invariantViolation",
68    "__AgentWire",
69    "__decodeAgentArgs",
70    "__encodeAgentResult",
71    "__decodeAgentKey",
72    "__AGENT_WIRE_PASS",
73    "__dispatchToEventsFanout",
74    "__rehydrationViolation",
75    "__migrationFailed",
76    "__reportUnknownStoredKeys",
77    "__checkStoredLayout",
78    "__readStored",
79    "__commitStored",
80    "__noteClock",
81    // The handles and wire helpers an agent's state is made of, sorted.
82    "__StoreCache",
83    "__StoreLog",
84    "__StoreMap",
85    "__StoreSet",
86    "__attachLazy",
87    "__bynkThen",
88    "__fillHeld",
89    "__fillLog",
90    "__fillMap",
91    "__fillSet",
92    "__readsLazily",
93    "__wireEntries",
94    "__wireHeld",
95    "__wireHeldOrder",
96    "__wireLog",
97    "__wireMap",
98    "__wirePostings",
99    "__wireSet",
100    "__checkStoredSchemaVersion",
101    "__wakeForMigration",
102    // Connections.
103    "__resolveConnection",
104    "__connIdOf",
105    "__acceptHibernatableConnection",
106    "__newWebSocketPair",
107    "__webSocketUpgradeResponse",
108    "__WorkersConnection",
109    "HttpResult",
110    "QueueResult",
111    // The boundary.
112    "__JsonValue",
113    "__BoundaryError",
114    "__ServiceBinding",
115    "__callService",
116    "__boundaryError",
117    // `Bytes`, `Instant`, predicates, `par`, effects, faults, traces.
118    "__bynkBytesEqual",
119    "__bynkBytesToBase64",
120    "__bynkBytesFromBase64",
121    "__bynkBytesDecodeUtf8",
122    "__bynkBytesConcat",
123    "__bynkBytesCompare",
124    "__bynkBytesToHex",
125    "__bynkBytesFromHex",
126    "__bynkBytesToBase64Url",
127    "__bynkBytesFromBase64Url",
128    "__bynkInstantToIso",
129    "__bynkInstantFromIso",
130    "__bynkPgRow",
131    "__bynkIsIsoDate",
132    "__bynkIsCron",
133    "__bynkCodePointLength",
134    "__bynkYamlParse",
135    "__bynkSettleAll",
136    "__bynkWithin",
137    "__bynkRace",
138    "__bynkDetach",
139    "__fault",
140    "__traceStep",
141    "__traceBinding",
142    // Requests, cookies, queries, forms.
143    "__bynkPercentEncode",
144    "__bynkPercentDecode",
145    "__requestHeaders",
146    "__requestCookies",
147    "__requestCookiesHeader",
148    "__issueSessionCookie",
149    "__expireSessionCookie",
150    "__sessionKeysOf",
151    "__cookieValue",
152    "__signSessionCookie",
153    "__newSessionKey",
154    "__requestQuery",
155    "__queryString",
156    "__formDecode",
157    "__formString",
158    "__cookieString",
159    "__multipartForm",
160    // Equality, `Int`, messages.
161    "__bynkEq",
162    "__bynkIntDiv",
163    "__bynkToInt",
164    "__bynkIntDivFloor",
165    "__bynkIntRem",
166    "__bynkIntMod",
167    "__bynkIntPow",
168    "__bynkIntAnd",
169    "__bynkIntOr",
170    "__bynkIntXor",
171    "__bynkIntAndNot",
172    "__bynkIntShl",
173    "__bynkIntShr",
174    "__selectPluralArm",
175    "__formatIcuNumber",
176    "__formatIcuDate",
177];
178
179/// The order runtime names have always had in a Worker's `index.ts` and `compose.ts` import
180/// lists (1A.36b-2). It differs from [`ORDER`] (`__ServiceBinding` precedes `__JsonValue`
181/// here, `Option` precedes `Err`), so a Worker header ranks by this list. It was read off the
182/// import lines both files had before their headers were derived, merged into one order that
183/// holds every pair those lines ever showed. A name it does not list ranks by [`ORDER`] and
184/// then alphabetically, after the listed ones.
185const WORKER_ORDER: &[&str] = &[
186    "HttpResult",
187    "Ok",
188    "Option",
189    "__AiSearchInstance",
190    "__AnalyticsDataset",
191    "__D1Database",
192    "__Hyperdrive",
193    "__KVNamespace",
194    "__QueueProducer",
195    "__R2Bucket",
196    "__RateLimiter",
197    "__SecretsStoreSecret",
198    "__SendEmail",
199    "__SenderIdentity",
200    "__ServiceBinding",
201    "__JsonValue",
202    "__VectorizeIndex",
203    "__WorkerAiBinding",
204    "__WorkerImagesBinding",
205    "__WorkerVersionMetadata",
206    "__bynkBytesEqual",
207    "__bynkDecimalParseWire",
208    "__bynkDecimalToString",
209    "__handleEmail",
210    "__matchPath",
211    "__mysqlExecute",
212    "__pgExecute",
213    "__serialiseAgentClass",
214    "__serialiseAgentKey",
215    "__dispatchToEventsFanout",
216    "__sessionCookieOf",
217    "__verifyBearerJwtHs256",
218    "__verifyOidcJwt",
219    "__verifySignatureHmacSha256",
220    "__verifySignedCookie",
221    "Err",
222    "Result",
223    "__AnalyticsSqlBinding",
224    "__BoundaryError",
225    "__InboundMessage",
226    "__bynkBytesToBase64",
227    "__csrfAllowed",
228    "__httpResultToResponse",
229    "__tokenClaims",
230    "__boundaryError",
231    "__bynkBytesFromBase64",
232    "__oidcTrust",
233    "__withPlainJson",
234    "__headResponse",
235    "__bynkBytesDecodeUtf8",
236    "__notModifiedIfMatch",
237    "__verifyCall",
238    "__applyCache",
239    "__CorsPolicy",
240    "__applyCors",
241    "__applyEdgeCache",
242    "__corsPreflightResponse",
243    "__faultResponse",
244    "__readBodyCapped",
245    "__deserialiseEventEnvelope",
246    "__noStore",
247    "__edgeCacheGuard",
248    "__varyAcceptLanguage",
249    "__SecurityPolicy",
250    "__applySecurityHeaders",
251    "__requestBodyStream",
252    "__untilBodyTooLarge",
253    "__mediaTypeMatches",
254    "__requestHeaders",
255    "__queryObject",
256    "__cookieObject",
257    "__multipartMediaTypeMatches",
258    "__multipartObject",
259    "__formMediaTypeMatches",
260    "__formObject",
261    "__requestCookies",
262    "__cfObject",
263    "__renderRejection",
264    "__requestQuery",
265];
266
267/// The order runtime names have in a generated test module's import lines (1B.5e, #4054
268/// Decision E). It was read off the import lines the 371 `tests/*.test.ts` goldens had before
269/// their headers were derived, merged into one order that holds every pair those lines showed
270/// but one: `__JsonValue` came before `__BoundaryError` on an integration module's value line
271/// and after it on a unit module's `import type` line, and the integration order is kept (the
272/// ruled reordering of the unit modules). A name it does not list follows, alphabetically.
273const TEST_ORDER: &[&str] = &[
274    "HttpResult",
275    "Ok",
276    "Err",
277    "Some",
278    "None",
279    "Result",
280    "Option",
281    "TestConnection",
282    "ValidationError",
283    "DecodeError",
284    "__BynkKeyMap",
285    "__BynkKeySet",
286    "__DurableObjectNamespace",
287    "__DurableObjectState",
288    "__bynkBytesEqual",
289    "__bynkBytesToBase64",
290    "__bynkBytesFromBase64",
291    "__bynkBytesDecodeUtf8",
292    "__bynkBytesConcat",
293    "__bynkBytesCompare",
294    "__bynkBytesToHex",
295    "__bynkBytesFromHex",
296    "__bynkBytesToBase64Url",
297    "__bynkBytesFromBase64Url",
298    "__bynkCmpBytes",
299    "__bynkCmpDecimal",
300    "__bynkCmpFloat",
301    "__bynkCmpInt",
302    "__bynkCmpList",
303    "__bynkCmpOption",
304    "__bynkCmpRecord",
305    "__bynkCmpString",
306    "__bynkCmpSum",
307    "__bynkDecimalAbs",
308    "__bynkDecimalAdd",
309    "__bynkDecimalDiv",
310    "__bynkDecimalEqual",
311    "__bynkDecimalFromInt",
312    "__bynkDecimalMin",
313    "__bynkDecimalMul",
314    "__bynkDecimalNeg",
315    "__bynkDecimalParse",
316    "__bynkDecimalParseWire",
317    "__bynkDecimalRound",
318    "__bynkDecimalShow",
319    "__bynkDecimalSub",
320    "__bynkDecimalToFloat",
321    "__bynkDecimalToInt",
322    "__bynkDecimalToString",
323    "__bynkDistinctBy",
324    "__bynkEq",
325    "__bynkGroupBy",
326    "__bynkInstantToIso",
327    "__bynkInstantFromIso",
328    "__bynkJoinOn",
329    "__bynkMapInsert",
330    "__bynkSetInsert",
331    "__bynkSetOf",
332    "__bynkSetRemove",
333    "__bynkSettleAll",
334    "__callService",
335    "__JsonValue",
336    "__BoundaryError",
337    "__ServiceBinding",
338    "__makeIntegrationAi",
339    "__makeIntegrationAnalytics",
340    "__makeIntegrationD1",
341    "__makeIntegrationEmail",
342    "__makeIntegrationImages",
343    "__makeIntegrationKv",
344    "__makeIntegrationDoNamespace",
345    "__makeIntegrationQueue",
346    "__makeIntegrationR2",
347    "__makeIntegrationRateLimit",
348    "__makeIntegrationSecretsStoreSecret",
349    "__makeIntegrationVectorize",
350    "__makeIntegrationVersionMetadata",
351    "__makeTestState",
352    "__responseToHttpResult",
353    "__responseToHttpOutcome",
354    "__responseToUnauthOutcome",
355    "__requestHeaders",
356    "__requestCookies",
357    "__requestCookiesHeader",
358    "__requestQuery",
359    "__queryString",
360    "__multipartForm",
361    "__cookieString",
362    "__requestHeaderPairs",
363    "__requestQuerySearch",
364    "__signSessionCookie",
365    "__newSessionKey",
366];
367
368/// The runtime names `stmts` (a module's imports, if it has any besides the
369/// runtime's, and its body) use and do not bind, spelled as an import names
370/// them (`type X` for a type-only export) and in their historical order.
371///
372/// A name that the runtime exports and the tree uses bare is a use of the
373/// runtime's even where it shares a global's name, so no global hides it.
374pub(crate) fn derived_runtime_names(stmts: &[TsStmt]) -> Vec<String> {
375    names_in_order(stmts, |n| ORDER.iter().position(|o| *o == n))
376}
377
378/// [`derived_runtime_names`] for a generated test module (`tests/*.test.ts`), in [`TEST_ORDER`].
379pub(crate) fn derived_test_runtime_names(stmts: &[TsStmt]) -> Vec<String> {
380    names_in_order(stmts, |n| TEST_ORDER.iter().position(|o| *o == n))
381}
382
383/// [`derived_runtime_names`] for a Worker's `index.ts` or `compose.ts`, in [`WORKER_ORDER`].
384pub(crate) fn derived_worker_runtime_names(stmts: &[TsStmt]) -> Vec<String> {
385    names_in_order(stmts, |n| {
386        WORKER_ORDER.iter().position(|o| *o == n).or_else(|| {
387            ORDER
388                .iter()
389                .position(|o| *o == n)
390                .map(|i| WORKER_ORDER.len() + i)
391        })
392    })
393}
394
395fn names_in_order(stmts: &[TsStmt], position: impl Fn(&str) -> Option<usize>) -> Vec<String> {
396    let mut used: Vec<String> = bynk_ts::unbound_names_in(stmts, is_runtime_export)
397        .into_iter()
398        .filter(|n| is_runtime_export(n))
399        .collect();
400    let rank = |n: &str| position(n).unwrap_or(usize::MAX);
401    used.sort_by(|a, b| rank(a).cmp(&rank(b)).then_with(|| a.cmp(b)));
402    used.into_iter()
403        .map(|n| {
404            if is_type_only_export(&n) {
405                format!("type {n}")
406            } else {
407                n
408            }
409        })
410        .collect()
411}
412
413/// Compute the runtime import specifier for a module at `from_source`. For a
414/// file at `commerce/payment.ts` the runtime sits two levels up, so this
415/// returns `../runtime.js`; for a top-level file it returns `./runtime.js`.
416pub fn runtime_import_for(from_source: &Path, ext: ImportExt) -> String {
417    let depth = from_source
418        .parent()
419        .map(|p| {
420            p.components()
421                .filter(|c| matches!(c, std::path::Component::Normal(_)))
422                .count()
423        })
424        .unwrap_or(0);
425    let ext = ext.as_str();
426    if depth == 0 {
427        format!("./runtime.{ext}")
428    } else {
429        let prefix: String = "../".repeat(depth);
430        format!("{prefix}runtime.{ext}")
431    }
432}
433
434/// A module's header: the two-line banner, and the runtime import its tree asks
435/// for (1A.36b-1). `body` is every statement the module has besides the header,
436/// built first, so the import is what the tree uses and cannot disagree with it
437/// (see this module). A unit the driver builds (`Test`, `Integration`)
438/// gets the banner only: its imports are the driver's.
439pub(super) fn write_header(
440    commons: &TypedCommons,
441    ctx: &EmitProjectCtx,
442    body: &[bynk_ts::TsStmt],
443) -> Vec<bynk_ts::TsStmt> {
444    // Arc C, slice 30 (#1392): the 2-line banner converts to two real
445    // `TsStmt::Comment` statements, the same `events_fanout.rs`-established
446    // precedent (#1317) every other Arc C header already uses.
447    let kind = match ctx.unit_kind {
448        UnitKind::Commons => "commons",
449        UnitKind::Context => "context",
450        UnitKind::Test => "test",
451        UnitKind::Integration => "integration test",
452        UnitKind::Adapter => "adapter",
453    };
454    // #1486: no explicit blank stmt after the banner — the printer's
455    // automatic top-level spacing policy already supplies the single blank
456    // after it (`Comment`→`Comment` is exempted, matching the banner's own
457    // two adjacent lines; the automatic policy is not exempted for whatever
458    // follows the banner, so the wanted blank appears there for free).
459    let mut stmts = vec![
460        bynk_ts::TsStmt::comment("Generated by bynk — do not edit by hand.", None),
461        bynk_ts::TsStmt::comment(format!("{kind} {}", commons.commons.name.joined()), None),
462    ];
463    if !commons.commons.items.is_empty() {
464        let names = derived_runtime_names(body);
465        stmts.extend(super::runtime_files::runtime_import_stmts(
466            false,
467            &names,
468            &runtime_import_for(&ctx.source_path, ctx.import_ext),
469        ));
470    }
471    stmts
472}
473
474/// Variant of write_header for single-file (no project context) emission: the
475/// same banner and the same derivation, over the module's built `body`. The banner and the
476/// imports are statements of the one program the body joins (1A.39a), so the printer's top-level
477/// spacing supplies the blank lines after each.
478pub(super) fn header_single(
479    commons: &TypedCommons,
480    body: &[bynk_ts::TsStmt],
481) -> Vec<bynk_ts::TsStmt> {
482    // Arc C, slice 30 (#1392): the same 2-comment-statement conversion
483    // `write_header` above already established.
484    let mut stmts = vec![
485        bynk_ts::TsStmt::comment("Generated by bynk — do not edit by hand.", None),
486        bynk_ts::TsStmt::comment(
487            format!(
488                "commons {}",
489                bynk_project::display_unit_name(&commons.commons.name.joined())
490            ),
491            None,
492        ),
493    ];
494    if !commons.commons.items.is_empty() {
495        let names = derived_runtime_names(body);
496        let imports = super::runtime_files::runtime_import_stmts(false, &names, "./runtime.js");
497        // A module with no runtime imports keeps the blank line its (empty) import block has
498        // always left, beside the one after the banner. The printer supplies the second.
499        if imports.is_empty() {
500            let mut blank = bynk_ts::TsStmt::blank(None);
501            blank.no_blank_before = true;
502            stmts.push(blank);
503        }
504        stmts.extend(imports);
505    }
506    stmts
507}
508
509#[cfg(test)]
510mod tests {
511    use super::*;
512    use crate::emitter::runtime_files::is_runtime_export;
513    use bynk_ts::{TsDecl, TsExpr, TsParam, TsType};
514
515    fn program_using(body: Vec<TsStmt>) -> Vec<TsStmt> {
516        body
517    }
518
519    fn call(name: &str) -> TsStmt {
520        TsStmt::expr_stmt(
521            TsExpr::Call {
522                callee: Box::new(TsExpr::Ident(name.to_string())),
523                args: vec![],
524            },
525            None,
526        )
527    }
528
529    fn function_over(ty: TsType) -> TsStmt {
530        TsStmt::decl(
531            TsDecl::Function {
532                name: "f".to_string(),
533                generics: vec![],
534                params: vec![TsParam::new("x".to_string(), Some(ty))],
535                return_type: None,
536                body: vec![],
537                is_async: false,
538                inline: false,
539            },
540            None,
541        )
542    }
543
544    #[test]
545    fn the_order_names_runtime_exports_once_each() {
546        let mut seen = std::collections::BTreeSet::new();
547        for n in ORDER {
548            assert!(is_runtime_export(n), "{n} is not a runtime export");
549            assert!(seen.insert(*n), "{n} is listed twice");
550        }
551    }
552
553    #[test]
554    fn the_worker_order_names_runtime_exports_once_each() {
555        let mut seen = std::collections::BTreeSet::new();
556        for n in WORKER_ORDER {
557            assert!(is_runtime_export(n), "{n} is not a runtime export");
558            assert!(seen.insert(*n), "{n} is listed twice");
559        }
560    }
561
562    #[test]
563    fn a_worker_header_ranks_by_the_worker_order() {
564        let stmts = program_using(vec![
565            call("__JsonValue"),
566            call("__ServiceBinding"),
567            call("Ok"),
568        ]);
569        assert_eq!(
570            derived_worker_runtime_names(&stmts),
571            ["Ok", "type __ServiceBinding", "type __JsonValue"]
572        );
573        assert_eq!(
574            derived_runtime_names(&stmts),
575            ["Ok", "type __JsonValue", "type __ServiceBinding"]
576        );
577    }
578
579    #[test]
580    fn a_module_that_uses_nothing_imports_nothing() {
581        assert!(derived_runtime_names(&program_using(vec![])).is_empty());
582        // Names that are not the runtime's are not this header's to import.
583        let stmts = program_using(vec![call("helper"), function_over(TsType::named("Order"))]);
584        assert!(derived_runtime_names(&stmts).is_empty());
585    }
586
587    /// A global (`Response`, `Promise<Request>`) is not the runtime's: the closure is asked
588    /// for the runtime's exports (`provided`) and nothing else, so a global stays unimported.
589    /// (`Request` and `Response` are `bynk`'s own types, imported from a sibling module.)
590    #[test]
591    fn a_global_is_not_imported_from_the_runtime() {
592        let stmts = program_using(vec![
593            call("Response"),
594            function_over(TsType::named("Promise<Request>")),
595        ]);
596        assert!(derived_runtime_names(&stmts).is_empty());
597    }
598
599    #[test]
600    fn a_used_name_is_imported_and_a_type_gets_its_prefix() {
601        let stmts = program_using(vec![
602            call("Some"),
603            function_over(TsType::named("Option<number>")),
604            function_over(TsType::named("HttpResult<string>")),
605        ]);
606        assert_eq!(
607            derived_runtime_names(&stmts),
608            ["Some", "type Option", "HttpResult"]
609        );
610    }
611
612    #[test]
613    fn names_keep_their_historical_order_and_unknown_ones_follow() {
614        let stmts = program_using(vec![
615            call("__bynkCmpInt"),
616            call("__bynkEq"),
617            call("Err"),
618            call("__bynkCmpFloat"),
619            call("Ok"),
620        ]);
621        assert_eq!(
622            derived_runtime_names(&stmts),
623            ["Ok", "Err", "__bynkEq", "__bynkCmpFloat", "__bynkCmpInt"]
624        );
625    }
626
627    #[test]
628    fn a_name_the_module_binds_is_not_imported() {
629        let stmts = program_using(vec![
630            TsStmt::decl(
631                TsDecl::Import {
632                    type_only: false,
633                    names: vec!["Some".to_string()],
634                    from: "./elsewhere.js".to_string(),
635                },
636                None,
637            ),
638            call("Some"),
639            call("None"),
640        ]);
641        assert_eq!(derived_runtime_names(&stmts), ["None"]);
642    }
643
644    #[test]
645    fn runtime_import_depth_resolves_correctly() {
646        assert_eq!(
647            runtime_import_for(Path::new("compose.ts"), ImportExt::Js),
648            "./runtime.js"
649        );
650        assert_eq!(
651            runtime_import_for(Path::new("commerce/payment.ts"), ImportExt::Js),
652            "../runtime.js"
653        );
654        assert_eq!(
655            runtime_import_for(Path::new("commerce/orders/types.ts"), ImportExt::Js),
656            "../../runtime.js"
657        );
658        assert_eq!(
659            runtime_import_for(Path::new("tests/commerce_payment.test.ts"), ImportExt::Js),
660            "../runtime.js"
661        );
662    }
663}
664
665/// Which conditional runtime helpers a module's import line ends up carrying.
666///
667/// These drive the single-file `emit()` path end-to-end (parse → resolve → check
668/// → emit), so they exercise the real producers rather than the accumulator in
669/// isolation. Before `RuntimeUse`, the decision was `body.contains("__bynkBytes")`
670/// — a scan of the generated text — and `escapes_a_marker_in_a_string_literal`
671/// below is the case that got wrong.
672#[cfg(test)]
673mod conditional_runtime_import_tests {
674    use crate::testkit::emit_source;
675
676    /// The runtime import lines of the emitted module, joined: one `import …
677    /// from "./__bynk_runtime/<module>.js"` per module it uses.
678    fn runtime_import_line(ts: &str) -> String {
679        ts.lines()
680            .filter(|l| l.starts_with("import ") && l.contains("__bynk_runtime/"))
681            .collect::<Vec<_>>()
682            .join("\n")
683    }
684
685    #[test]
686    fn bytes_helpers_are_imported_when_a_bytes_value_is_built() {
687        let ts = emit_source(
688            "commons b\n\nfn decode(s: String) -> Option[Bytes] {\n  Bytes.fromBase64(s)\n}\n",
689        );
690        assert!(
691            runtime_import_line(&ts).contains("__bynkBytesFromBase64"),
692            "{ts}"
693        );
694    }
695
696    #[test]
697    fn bytes_helpers_are_imported_for_content_equality() {
698        let ts = emit_source("commons b\n\nfn same(a: Bytes, b: Bytes) -> Bool {\n  a == b\n}\n");
699        assert!(
700            runtime_import_line(&ts).contains("__bynkBytesEqual"),
701            "{ts}"
702        );
703    }
704
705    /// #2016: the operation helpers are their own group. A module that only
706    /// builds or compares `Bytes` keeps its import list, and one that calls an
707    /// operation gets that group without the base one.
708    #[test]
709    fn bytes_ops_helpers_are_imported_only_when_an_operation_is_called() {
710        let base = emit_source("commons b\n\nfn same(a: Bytes, b: Bytes) -> Bool {\n  a == b\n}\n");
711        assert!(
712            !runtime_import_line(&base).contains("__bynkBytesConcat"),
713            "{base}"
714        );
715        let ops = emit_source("commons b\n\nfn hex(b: Bytes) -> String {\n  b.toHex()\n}\n");
716        let line = runtime_import_line(&ops);
717        assert!(line.contains("__bynkBytesToHex"), "{ops}");
718        assert!(!line.contains("__bynkBytesEqual"), "{ops}");
719    }
720
721    /// K3 (#2592): the `Instant` ISO-8601 helpers come in only when called,
722    /// and each lowers to its own helper.
723    #[test]
724    fn instant_iso_helpers_are_imported_only_when_called() {
725        let base = emit_source("commons t\n\nfn ms(i: Instant) -> Int {\n  i.toEpochMillis()\n}\n");
726        assert!(
727            !runtime_import_line(&base).contains("__bynkInstant"),
728            "{base}"
729        );
730        let ts = emit_source(
731            "commons t\n\nfn iso(i: Instant) -> String {\n  i.toIso()\n}\n\nfn read(s: String) -> Option[Instant] {\n  Instant.fromIso(s)\n}\n",
732        );
733        let line = runtime_import_line(&ts);
734        assert!(line.contains("__bynkInstantToIso"), "{ts}");
735        assert!(line.contains("__bynkInstantFromIso"), "{ts}");
736        assert!(ts.contains("__bynkInstantToIso(i)"), "{ts}");
737        assert!(ts.contains("__bynkInstantFromIso(s)"), "{ts}");
738    }
739
740    /// K2 (#2594): the percent-encoding helpers come in only when called.
741    #[test]
742    fn percent_helpers_are_imported_only_when_called() {
743        let base = emit_source("commons u\n\nfn n(s: String) -> Int {\n  s.length()\n}\n");
744        assert!(
745            !runtime_import_line(&base).contains("__bynkPercent"),
746            "{base}"
747        );
748        let ts = emit_source(
749            "commons u\n\nfn e(s: String) -> String {\n  s.percentEncode()\n}\n\nfn d(s: String) -> Option[String] {\n  s.percentDecode()\n}\n",
750        );
751        let line = runtime_import_line(&ts);
752        assert!(
753            line.contains("__bynkPercentEncode") && line.contains("__bynkPercentDecode"),
754            "{ts}"
755        );
756        assert!(
757            ts.contains("__bynkPercentEncode(s)") && ts.contains("__bynkPercentDecode(s)"),
758            "{ts}"
759        );
760    }
761
762    /// #2016: `slice` lowers inline, so it pulls in no helper at all.
763    #[test]
764    fn bytes_slice_needs_no_helper() {
765        let ts = emit_source("commons b\n\nfn tag(b: Bytes) -> Bytes {\n  b.slice(0, 4)\n}\n");
766        assert!(!runtime_import_line(&ts).contains("__bynkBytes"), "{ts}");
767    }
768
769    #[test]
770    fn bytes_helpers_are_absent_from_a_module_that_never_uses_bytes() {
771        let ts = emit_source("commons b\n\nfn double(n: Int) -> Int {\n  n * 2\n}\n");
772        assert!(!runtime_import_line(&ts).contains("__bynkBytes"), "{ts}");
773    }
774
775    /// The regression this replaced a text scan for: a `Bytes` helper name
776    /// appearing inside a user **string literal** is not a reference to the
777    /// helper, and must not pull the import in. `body.contains("__bynkBytes")`
778    /// could not tell the two apart, because the literal is emitted verbatim
779    /// into the same buffer it scanned.
780    #[test]
781    fn escapes_a_marker_in_a_string_literal() {
782        let ts = emit_source("commons b\n\nfn label() -> String {\n  \"__bynkBytesEqual\"\n}\n");
783        assert!(
784            ts.contains("\"__bynkBytesEqual\""),
785            "the literal should survive into the body: {ts}"
786        );
787        assert!(
788            !runtime_import_line(&ts).contains("__bynkBytes"),
789            "a marker inside a string literal is not a helper reference: {ts}"
790        );
791    }
792}