1use std::collections::BTreeSet;
13use std::path::PathBuf;
14
15use bynk_ts::TsDecl;
16
17use super::runtime_modules::{RUNTIME_EXPORTS, RUNTIME_MODULES, RUNTIME_TYPE_ONLY};
18
19pub const RUNTIME_DIR: &str = "__bynk_runtime";
21
22fn module_of(name: &str) -> Option<&'static str> {
24 RUNTIME_EXPORTS
25 .binary_search_by_key(&name, |(n, _)| n)
26 .ok()
27 .map(|i| RUNTIME_EXPORTS[i].1)
28}
29
30pub fn runtime_export_names() -> impl Iterator<Item = &'static str> {
33 RUNTIME_EXPORTS.iter().map(|(name, _)| *name)
34}
35
36pub(crate) fn is_runtime_export(name: &str) -> bool {
38 module_of(name).is_some()
39}
40
41pub(crate) fn is_type_only_export(name: &str) -> bool {
45 RUNTIME_TYPE_ONLY.binary_search(&name).is_ok()
46}
47
48fn split_specifier(from: &str) -> Option<(&str, &str)> {
51 let (prefix, file) = from.rsplit_once('/')?;
52 let ext = file.strip_prefix("runtime.")?;
53 matches!(ext, "js" | "ts").then_some((&from[..=prefix.len()], ext))
54}
55
56pub(crate) fn split_runtime_import(type_only: bool, names: &[String], from: &str) -> Vec<TsDecl> {
65 try_split_runtime_import(type_only, names, from)
66 .unwrap_or_else(|| panic!("an import from {from} names a non-runtime export: {names:?}"))
67}
68
69fn try_split_runtime_import(type_only: bool, names: &[String], from: &str) -> Option<Vec<TsDecl>> {
73 let (prefix, ext) = split_specifier(from)?;
74 let mut groups: Vec<(&'static str, Vec<String>)> = RUNTIME_MODULES
75 .iter()
76 .map(|(m, _)| (*m, Vec::new()))
77 .collect();
78 for name in names {
79 let bare = name.strip_prefix("type ").unwrap_or(name);
80 let imported = bare.split(" as ").next().unwrap_or(bare);
81 let module = module_of(imported)?;
82 let group = groups
83 .iter_mut()
84 .find(|(m, _)| *m == module)
85 .expect("module is in the table");
86 group.1.push(name.clone());
87 }
88 Some(
89 groups
90 .into_iter()
91 .filter(|(_, names)| !names.is_empty())
92 .map(|(module, names)| {
93 let all_types = names.iter().all(|n| n.starts_with("type "));
94 let (type_only, names) = if all_types && !type_only {
95 (
96 true,
97 names
98 .iter()
99 .map(|n| n.trim_start_matches("type ").to_string())
100 .collect(),
101 )
102 } else {
103 (type_only, names)
104 };
105 TsDecl::Import {
106 type_only,
107 names,
108 from: format!("{prefix}{RUNTIME_DIR}/{module}.{ext}"),
109 }
110 })
111 .collect(),
112 )
113}
114
115fn import_statements(lines: &[&str]) -> Vec<(usize, usize, String)> {
119 let mut out = Vec::new();
120 let mut i = 0;
121 while i < lines.len() {
122 let t = lines[i].trim_start();
123 if t.starts_with("import ") || t.starts_with("import{") {
124 let mut j = i;
125 let mut text = t.trim_end().to_string();
126 while text.contains('{') && !text.contains('}') && j + 1 < lines.len() && j - i < 500 {
129 j += 1;
130 text.push(' ');
131 text.push_str(lines[j].trim());
132 }
133 out.push((i, j, text));
134 i = j + 1;
135 } else {
136 i += 1;
137 }
138 }
139 out
140}
141
142pub fn rewrite_runtime_imports(source: &str) -> String {
148 let crlf = source.contains("\r\n");
149 let nl = if crlf { "\r\n" } else { "\n" };
150 let lines: Vec<&str> = source
151 .split('\n')
152 .map(|l| l.trim_end_matches('\r'))
153 .collect();
154 let mut out: Vec<String> = Vec::with_capacity(lines.len());
155 let mut i = 0;
156 for (first, last, text) in import_statements(&lines) {
157 out.extend(lines[i..first].iter().map(|l| l.to_string()));
158 match rewrite_import_statement(&text) {
159 Some(rewritten) => {
160 let indent = &lines[first][..lines[first].len() - lines[first].trim_start().len()];
161 out.extend(rewritten.into_iter().map(|l| format!("{indent}{l}")));
162 }
163 None => out.extend(lines[first..=last].iter().map(|l| l.to_string())),
164 }
165 i = last + 1;
166 }
167 out.extend(lines[i..].iter().map(|l| l.to_string()));
168 out.join(nl)
169}
170
171fn rewrite_import_statement(stmt: &str) -> Option<Vec<String>> {
172 let rest = stmt.strip_prefix("import")?.trim_start();
173 let (type_only, rest) = match rest.strip_prefix("type ") {
174 Some(r) => (true, r.trim_start()),
175 None => (false, rest),
176 };
177 let rest = rest.strip_prefix('{')?;
178 let (list, rest) = rest.split_once('}')?;
179 let rest = rest.trim_start().strip_prefix("from")?.trim_start();
180 let quote = rest.chars().next().filter(|c| matches!(c, '"' | '\''))?;
181 let rest = &rest[1..];
182 let (spec, tail) = rest.split_once(quote)?;
183 split_specifier(spec)?;
184 let tail = tail.trim();
186 let comment = tail.strip_prefix(';').unwrap_or(tail).trim();
187 if !(comment.is_empty() || comment.starts_with("//") || comment.starts_with("/*")) {
188 return None;
189 }
190 let names: Vec<String> = list
191 .split(',')
192 .map(|n| n.trim().to_string())
193 .filter(|n| !n.is_empty())
194 .collect();
195 let decls = try_split_runtime_import(type_only, &names, spec)?;
196 let mut lines: Vec<String> = decls
197 .iter()
198 .map(|d| match d {
199 TsDecl::Import {
200 type_only,
201 names,
202 from,
203 } => format!(
204 "import {}{{ {} }} from {quote}{from}{quote};",
205 if *type_only { "type " } else { "" },
206 names.join(", ")
207 ),
208 TsDecl::ImportNamespace { .. }
209 | TsDecl::ImportDefault { .. }
210 | TsDecl::ReExport { .. }
211 | TsDecl::ExportNames { .. }
212 | TsDecl::ReExportAll { .. }
213 | TsDecl::Export(_)
214 | TsDecl::Interface { .. }
215 | TsDecl::ConstDecl { .. }
216 | TsDecl::Class { .. }
217 | TsDecl::Function { .. }
218 | TsDecl::TypeAlias { .. }
219 | TsDecl::ExportDefault(_)
220 | TsDecl::DeclareConst { .. } => {
221 unreachable!("split_runtime_import yields named imports")
222 }
223 })
224 .collect();
225 if let (false, Some(last)) = (comment.is_empty(), lines.last_mut()) {
226 last.push(' ');
227 last.push_str(comment);
228 }
229 Some(lines)
230}
231
232fn reached_module(specifier: &str) -> Option<(&str, &str)> {
234 let rest = specifier.rsplit_once(&format!("{RUNTIME_DIR}/"))?.1;
235 let (module, ext) = rest.rsplit_once('.')?;
236 Some((module, ext))
237}
238
239pub fn reached_in(program: &bynk_ts::TsProgram, out: &mut BTreeSet<(String, String)>) {
242 let mut note = |spec: &str| {
243 if let Some((m, e)) = reached_module(spec) {
244 out.insert((m.to_string(), e.to_string()));
245 }
246 };
247 for spec in program.import_specifiers() {
248 note(spec);
249 }
250 for (_, text) in program.verbatim_content() {
251 let lines: Vec<&str> = text.lines().collect();
252 for (_, _, stmt) in import_statements(&lines) {
253 if let Some((_, tail)) = stmt.rsplit_once(" from ") {
254 let spec = tail.trim().trim_start_matches(['"', '\'']);
255 if let Some(end) = spec.find(['"', '\'']) {
256 note(&spec[..end]);
257 }
258 }
259 }
260 }
261}
262
263pub fn closure_files(reached: &BTreeSet<(String, String)>) -> Vec<(PathBuf, String)> {
267 let mut files = Vec::new();
268 for ext in reached
269 .iter()
270 .map(|(_, e)| e.as_str())
271 .collect::<BTreeSet<_>>()
272 {
273 let mut want: Vec<&str> = reached
274 .iter()
275 .filter(|(_, e)| e == ext)
276 .map(|(m, _)| m.as_str())
277 .collect();
278 let mut done: BTreeSet<&str> = BTreeSet::new();
279 while let Some(m) = want.pop() {
280 if !done.insert(m) {
281 continue;
282 }
283 let Some((_, src)) = RUNTIME_MODULES.iter().find(|(n, _)| *n == m) else {
286 done.remove(m);
287 continue;
288 };
289 for line in src.lines().filter(|l| l.starts_with("import ")) {
290 if let Some(dep) = imported_module(m, line) {
291 want.push(dep);
292 }
293 }
294 }
295 for m in done {
296 files.push((module_path(m), module_source(m, ext)));
297 }
298 }
299 files
300}
301
302fn imported_module(module: &str, line: &str) -> Option<&'static str> {
306 let spec = line
307 .rsplit_once('"')
308 .and_then(|(head, _)| head.rsplit_once('"'))
309 .map(|(_, spec)| spec)?;
310 let spec = spec.strip_suffix(".ts")?;
311 let mut parts: Vec<&str> = module.split('/').collect();
312 parts.pop();
313 for seg in spec.split('/') {
314 match seg {
315 "." | "" => {}
316 ".." => {
317 parts.pop()?;
318 }
319 name => parts.push(name),
320 }
321 }
322 let resolved = parts.join("/");
323 RUNTIME_MODULES
324 .iter()
325 .find(|(n, _)| *n == resolved)
326 .map(|(n, _)| *n)
327}
328
329fn module_path(module: &str) -> PathBuf {
332 PathBuf::from(format!("{RUNTIME_DIR}/{module}.ts"))
333}
334
335fn module_source(module: &str, ext: &str) -> String {
337 let (_, src) = RUNTIME_MODULES
338 .iter()
339 .find(|(n, _)| *n == module)
340 .expect("module is in the table");
341 if ext == "ts" {
342 return src.to_string();
343 }
344 src.lines()
345 .map(|l| {
346 if l.starts_with("import ") {
347 l.replace(".ts\";", &format!(".{ext}\";"))
348 } else {
349 l.to_string()
350 }
351 })
352 .collect::<Vec<_>>()
353 .join("\n")
354 + "\n"
355}
356
357pub fn emit_all_runtime_modules() -> Vec<(PathBuf, String)> {
360 RUNTIME_MODULES
361 .iter()
362 .map(|(m, _)| (module_path(m), module_source(m, "js")))
363 .collect()
364}
365
366pub fn runtime_import_stmts(type_only: bool, names: &[String], from: &str) -> Vec<bynk_ts::TsStmt> {
369 split_runtime_import(type_only, names, from)
370 .into_iter()
371 .map(|d| bynk_ts::TsStmt::decl(d, None))
372 .collect()
373}
374
375#[cfg(test)]
376mod tests {
377 use super::super::runtime_modules;
378 use super::*;
379
380 #[test]
383 fn per_module_runtime_imports_resolve_within_the_table() {
384 let names: Vec<&str> = runtime_modules::RUNTIME_MODULES
385 .iter()
386 .map(|(n, _)| *n)
387 .collect();
388 for (name, src) in runtime_modules::RUNTIME_MODULES {
389 for line in src.lines().filter(|l| {
390 (l.starts_with("import ") || l.starts_with("} from ")) && l.contains('"')
391 }) {
392 let from = line.rsplit('"').nth(1).expect("import specifier");
393 if bynk_check::firstparty::FIRST_PARTY_NPM.iter().any(|d| {
396 d.runtime_module == *name
399 && (d.package == from
400 || from
401 .strip_prefix(d.package)
402 .is_some_and(|r| r.starts_with('/')))
403 }) {
404 continue;
405 }
406 let mut parts: Vec<&str> = name.split('/').collect();
409 parts.pop();
410 let target = from.strip_suffix(".ts").map(|f| {
411 for seg in f.split('/') {
412 match seg {
413 "." => {}
414 ".." => {
415 parts.pop();
416 }
417 seg => parts.push(seg),
418 }
419 }
420 parts.join("/")
421 });
422 assert!(
423 target.is_some_and(|t| names.contains(&t.as_str()) && t != *name),
424 "{name}: import {from:?} does not name another runtime module"
425 );
426 }
427 }
428 }
429
430 #[test]
435 fn first_party_pins_match_the_runtime() {
436 let manifest =
437 std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/runtime/package.json"))
438 .expect("runtime/package.json");
439 for d in bynk_check::firstparty::FIRST_PARTY_NPM {
440 assert!(
441 manifest.contains(&format!("\"{}\": \"{}\"", d.package, d.version)),
442 "`{}` is pinned at {} in bynk-std but not in runtime/package.json",
443 d.package,
444 d.version
445 );
446 let (_, src) = runtime_modules::RUNTIME_MODULES
447 .iter()
448 .find(|(n, _)| *n == d.runtime_module)
449 .expect("the runtime module exists");
450 assert!(
451 src.contains(&format!("from \"{}\"", d.package))
452 || src.contains(&format!("from \"{}/", d.package)),
453 "runtime module `{}` does not import `{}`",
454 d.runtime_module,
455 d.package
456 );
457 }
458 }
459
460 #[test]
463 fn runtime_import_splits_per_defining_module() {
464 let names: Vec<String> = ["Ok", "type Result", "__callService", "type __JsonValue"]
465 .map(String::from)
466 .to_vec();
467 let got: Vec<(bool, Vec<String>, String)> =
468 split_runtime_import(false, &names, "../runtime.js")
469 .into_iter()
470 .map(|d| match d {
471 bynk_ts::TsDecl::Import {
472 type_only,
473 names,
474 from,
475 } => (type_only, names, from),
476 bynk_ts::TsDecl::ImportNamespace { .. }
477 | bynk_ts::TsDecl::ImportDefault { .. }
478 | bynk_ts::TsDecl::ReExport { .. }
479 | bynk_ts::TsDecl::ExportNames { .. }
480 | bynk_ts::TsDecl::ReExportAll { .. }
481 | bynk_ts::TsDecl::Export(_)
482 | bynk_ts::TsDecl::Interface { .. }
483 | bynk_ts::TsDecl::ConstDecl { .. }
484 | bynk_ts::TsDecl::Class { .. }
485 | bynk_ts::TsDecl::Function { .. }
486 | bynk_ts::TsDecl::TypeAlias { .. }
487 | bynk_ts::TsDecl::ExportDefault(_)
488 | bynk_ts::TsDecl::DeclareConst { .. } => unreachable!(),
489 })
490 .collect();
491 let v = |xs: &[&str]| xs.iter().map(|s| s.to_string()).collect::<Vec<_>>();
492 assert_eq!(
493 got,
494 vec![
495 (
496 false,
497 v(&["Ok", "type Result"]),
498 "../__bynk_runtime/result.js".to_string()
499 ),
500 (
501 false,
502 v(&["__callService", "type __JsonValue"]),
503 "../__bynk_runtime/boundary.js".to_string()
504 ),
505 ]
506 );
507 }
508
509 #[test]
513 fn http_result_is_reached_without_the_http_helpers() {
514 use std::collections::BTreeSet;
515 let names = vec!["HttpResult".to_string()];
516 let decls = split_runtime_import(false, &names, "./runtime.js");
517 assert!(matches!(
518 &decls[..],
519 [bynk_ts::TsDecl::Import { from, .. }] if from == "./__bynk_runtime/httpresult.js"
520 ));
521 let reached: BTreeSet<(String, String)> =
522 [("httpresult".to_string(), "js".to_string())].into();
523 let paths: Vec<String> = closure_files(&reached)
524 .iter()
525 .map(|(p, _)| p.display().to_string())
526 .collect();
527 assert_eq!(paths, ["__bynk_runtime/httpresult.ts"]);
528 }
529
530 #[test]
531 fn runtime_files_close_over_module_imports() {
532 use std::collections::BTreeSet;
533 let reached: BTreeSet<(String, String)> =
534 [("equality".to_string(), "js".to_string())].into();
535 let files = closure_files(&reached);
536 let paths: Vec<String> = files.iter().map(|(p, _)| p.display().to_string()).collect();
537 assert_eq!(
539 paths,
540 [
541 "__bynk_runtime/bytes.ts",
542 "__bynk_runtime/decimal.ts",
543 "__bynk_runtime/equality.ts",
544 "__bynk_runtime/result.ts"
545 ]
546 );
547 assert!(
548 files.iter().all(|(_, s)| !s.contains(".ts\";")),
549 "siblings are spelled for the target extension"
550 );
551 assert!(closure_files(&BTreeSet::new()).is_empty());
552 }
553
554 #[test]
555 fn handwritten_runtime_imports_are_rewritten() {
556 let src = "import { None, Some, type Option, type KVNamespace } from \"../runtime.js\";\nimport { x } from \"./other.js\";\n";
557 let out = rewrite_runtime_imports(src);
558 assert!(
559 out.contains(
560 "import { None, Some, type Option } from \"../__bynk_runtime/result.js\";"
561 ),
562 "{out}"
563 );
564 assert!(
565 out.contains("import type { KVNamespace } from \"../__bynk_runtime/storage.js\";"),
566 "{out}"
567 );
568 assert!(out.contains("import { x } from \"./other.js\";"), "{out}");
569 }
570
571 #[test]
572 fn handwritten_runtime_import_forms_are_handled_or_left_alone() {
573 let r = rewrite_runtime_imports;
574 let multi = "import {\n Ok,\n Err,\n} from \"./runtime.js\";\nconst x = 1;\n";
576 assert_eq!(
577 r(multi),
578 "import { Ok, Err } from \"./__bynk_runtime/result.js\";\nconst x = 1;\n"
579 );
580 assert_eq!(
581 r(" import { Ok } from \"./runtime.js\" // keep\n"),
582 " import { Ok } from \"./__bynk_runtime/result.js\"; // keep\n"
583 );
584 assert_eq!(
585 r("import { Ok } from \"./runtime.js\"\r\nx\r\n"),
586 "import { Ok } from \"./__bynk_runtime/result.js\";\r\nx\r\n"
587 );
588 for keep in [
590 "import { Ok, Reslt } from \"./runtime.js\";\n",
591 "import * as rt from \"./runtime.js\";\n",
592 "import { a } from \"./lib/other.js\";\n",
593 ] {
594 assert_eq!(r(keep), keep);
595 }
596 }
597
598 #[test]
599 fn an_unknown_runtime_module_emits_nothing_instead_of_panicking() {
600 use std::collections::BTreeSet;
601 let reached: BTreeSet<(String, String)> = [("nope".to_string(), "js".to_string())].into();
602 assert!(closure_files(&reached).is_empty());
603 }
604
605 #[test]
606 fn per_module_runtime_carries_its_aliases() {
607 let all: String = runtime_modules::RUNTIME_MODULES
608 .iter()
609 .map(|(_, s)| *s)
610 .collect();
611 for alias in [
612 "__callService",
613 "__matchPath",
614 "__makeAgent",
615 "__JsonValue",
616 "__formatIcuDate",
617 ] {
618 assert!(
619 all.contains(alias),
620 "{alias} missing from the per-module runtime"
621 );
622 }
623 let (_, http) = runtime_modules::RUNTIME_MODULES
624 .iter()
625 .find(|(n, _)| *n == "http")
626 .unwrap();
627 assert!(http.contains("matchPath as __matchPath"));
628 }
629
630 #[test]
631 fn runtime_emits_all_required_exports() {
632 let s: String = emit_all_runtime_modules()
633 .into_iter()
634 .map(|(_, src)| src)
635 .collect();
636 assert!(s.contains("export type Result<T, E>"));
638 assert!(s.contains("export const Ok"));
639 assert!(s.contains("export const Err"));
640 assert!(s.contains("export type Option<T>"));
641 assert!(s.contains("export const Some"));
642 assert!(s.contains("export const None"));
643 assert!(s.contains("export interface ValidationError"));
644 assert!(s.contains("export interface DurableObjectStorage"));
646 assert!(s.contains("export interface DurableObjectState"));
647 assert!(s.contains("export class InMemoryStorage"));
648 assert!(s.contains("export function makeTestState"));
649 assert!(s.contains("tag: \"Ok\""));
651 assert!(s.contains("tag: \"Err\""));
652 assert!(s.contains("tag: \"Some\""));
653 assert!(s.contains("tag: \"None\""));
654 }
655}