1use std::collections::{BTreeMap, BTreeSet, HashMap};
38use std::fmt;
39use std::sync::Arc;
40
41use bynk_check::contract;
42use bynk_check::project_model::TypeDecl;
43use bynk_check::wire::TypeBody;
44use bynk_check::wire::TypeRef;
45use bynk_ts::{
46 TsArrowBody, TsBinaryOp, TsDecl, TsExpr, TsLit, TsObjectEntry, TsParam, TsProgram, TsStmt,
47 TsType, TsTypeMember,
48};
49
50use super::client::{SurfaceClosure, surface_closure};
51use super::runtime_use::RuntimeUse;
52use super::serialisation;
53
54mod route;
55
56const SURFACE_TYPES: &[&str] = &[
59 "BoundaryError",
60 "CallFailure",
61 "Client",
62 "ClientOptions",
63 "JsonValue",
64 "Option",
65 "Result",
66 "ValidationError",
67];
68
69const FILE_TYPE: &str = "export interface __Wire_File {\n readonly filename: Option<string>;\n readonly contentType: string;\n readonly bytes: globalThis.Uint8Array;\n}\n";
71
72const FILE_CODEC: &str = "export function __serialise_File(value: __Wire_File): __JsonValue {\n return {\n filename: value.filename.tag === \"Some\" ? { kind: \"Some\", value: value.filename.value } : { kind: \"None\" },\n contentType: value.contentType,\n bytes: __bynkBytesToBase64(value.bytes),\n };\n}\n\nexport function __deserialise_File(json: __JsonValue, path: string = \"$\"): Result<__Wire_File, __BoundaryError> {\n if (typeof json !== \"object\" || json === null || globalThis.Array.isArray(json)) {\n return Err({ kind: \"StructuralMismatch\", path, expected: \"object\", actual: typeof json });\n }\n return Ok(json as unknown as __Wire_File);\n}\n";
74
75const FILE_TYPE_USES: &[&str] = &["Option"];
77
78const FILE_CODEC_USES: &[&str] = &[
81 "__Wire_File",
82 "__JsonValue",
83 "__bynkBytesToBase64",
84 "__BoundaryError",
85 "Result",
86 "Ok",
87 "Err",
88];
89
90const WIRE_PREFIX: &str = "__Wire_";
92
93const OPTIONAL_MODULES: [(&str, &str); 5] = [
97 ("bytes", BYTES_MODULE),
98 ("decimal", DECIMAL_MODULE),
99 ("time", TIME_MODULE),
100 ("keys", KEYS_MODULE),
101 ("text", TEXT_MODULE),
102];
103
104const RUNTIME: &str = include_str!("http_client_runtime.ts");
105const RESULT_MODULE: &str = include_str!("../../runtime/src/result.ts");
106const BYTES_MODULE: &str = include_str!("../../runtime/src/bytes.ts");
107const DECIMAL_MODULE: &str = include_str!("../../runtime/src/decimal.ts");
108const KEYS_MODULE: &str = include_str!("../../runtime/src/keys.ts");
109const TIME_MODULE: &str = include_str!("../../runtime/src/time.ts");
110const TEXT_MODULE: &str = include_str!("../../runtime/src/text.ts");
111
112const EXPERIMENTAL: &str = "Experimental: member names and the shape of this module may change in a minor version until it is stabilised.";
114
115#[derive(Debug, Clone)]
117pub struct HttpClientInput {
118 pub services: Vec<ServiceInput>,
119 pub compiler_version: String,
121}
122
123#[derive(Debug, Clone)]
125pub struct ServiceInput {
126 pub unit: String,
127 pub name: String,
128 pub doc: Option<String>,
129 pub types: HashMap<String, Arc<TypeDecl>>,
131 pub routes: Vec<RouteInput>,
132}
133
134#[derive(Debug, Clone)]
136pub struct RouteInput {
137 pub method: String,
139 pub path: String,
141 pub doc: Option<String>,
142 pub params: Vec<ParamInput>,
144 pub success: Option<TypeRef>,
146 pub replies: Vec<ReplyInput>,
147}
148
149#[derive(Debug, Clone)]
151pub enum ParamInput {
152 Path { name: String, ty: TypeRef },
154 Body { ty: TypeRef, kind: BodyKind },
156 Query { ty: TypeRef },
158 Cookies { ty: TypeRef },
160}
161
162#[derive(Debug, Clone, PartialEq, Eq)]
164pub enum BodyKind {
165 Json,
167 Form,
169 Multipart,
171 Raw { content_type: Option<String> },
174}
175
176#[derive(Debug, Clone, PartialEq, Eq)]
178pub struct ReplyInput {
179 pub status: u16,
180 pub variant: String,
182 pub payload: ReplyPayload,
183}
184
185#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
187pub enum ReplyPayload {
188 Value,
190 Message,
192 Location,
194 None,
196 BoundaryError,
198 BoundaryRefusal,
200 Raw,
202 RawEtag,
204 RawTagged,
206 Events,
208}
209
210#[derive(Clone, Copy)]
212enum RawEtag {
213 None,
214 Maybe,
215 Required,
216}
217
218impl ReplyPayload {
219 fn name(self) -> &'static str {
222 match self {
223 Self::Value => "Value",
224 Self::Message => "Message",
225 Self::Location => "Location",
226 Self::None => "None",
227 Self::BoundaryError => "BoundaryError",
228 Self::BoundaryRefusal => "BoundaryRefusal",
229 Self::Raw => "Raw",
230 Self::RawEtag => "RawEtag",
231 Self::RawTagged => "RawTagged",
232 Self::Events => "Events",
233 }
234 }
235
236 fn is_raw(self) -> bool {
238 matches!(self, Self::Raw | Self::RawEtag | Self::RawTagged)
239 }
240}
241
242#[derive(Debug, Clone)]
244pub struct ClientError(pub String);
245
246impl fmt::Display for ClientError {
247 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
248 f.write_str(&self.0)
249 }
250}
251
252impl std::error::Error for ClientError {}
253
254fn fail<T>(message: impl Into<String>) -> Result<T, ClientError> {
255 Err(ClientError(message.into()))
256}
257
258#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
260pub enum Layout {
261 #[default]
263 File,
264 Dir,
266}
267
268pub const DIR_FILES: [&str; 4] = ["index.ts", "types.ts", "codecs.ts", "runtime.ts"];
270
271pub const SINGLE_FILE: &str = "client.ts";
274
275#[derive(Debug, Clone)]
277pub struct Emitted {
278 pub files: Vec<(String, String)>,
280 pub skipped: Vec<String>,
282}
283
284pub fn emit_http_client(input: &HttpClientInput, layout: Layout) -> Result<Emitted, ClientError> {
288 let (kept, skipped) = viable_routes(input)?;
289 if kept.services.is_empty() {
290 return fail(format!(
291 "no route of the selected services is one this version of `bynk client` can represent{}",
292 skipped
293 .iter()
294 .map(|s| format!("\n {s}"))
295 .collect::<String>()
296 ));
297 }
298 let mut gen_ = Gen::new(closure_of(&kept)?);
299 let plan = gen_.plan(&kept)?;
300 let parts = gen_.emit(&kept, &plan)?;
301 Ok(Emitted {
302 files: assemble(&kept, parts, layout),
303 skipped,
304 })
305}
306
307fn closure_of(input: &HttpClientInput) -> Result<SurfaceClosure, ClientError> {
309 let own_types = merge_types(&input.services)?;
310 let mut roots: Vec<TypeRef> = Vec::new();
311 for s in &input.services {
312 for r in &s.routes {
313 for p in &r.params {
314 match p {
315 ParamInput::Path { ty, .. }
316 | ParamInput::Body { ty, .. }
317 | ParamInput::Query { ty }
318 | ParamInput::Cookies { ty } => roots.push(ty.clone()),
319 }
320 }
321 roots.extend(r.success.iter().cloned());
322 }
323 }
324 Ok(surface_closure(&roots, &own_types, SURFACE_TYPES))
325}
326
327fn viable_routes(input: &HttpClientInput) -> Result<(HttpClientInput, Vec<String>), ClientError> {
329 let mut trial = Gen::new(closure_of(input)?);
330 let plan = trial.plan(input)?;
331 let mut kept = input.clone();
332 let mut skipped = Vec::new();
333 for ((s, sp), out) in input
334 .services
335 .iter()
336 .zip(&plan.services)
337 .zip(&mut kept.services)
338 {
339 out.routes.clear();
340 for (r, rp) in s.routes.iter().zip(&sp.routes) {
341 let (convs, holds) = (trial.convs.clone(), trial.holds.clone());
342 match trial.route(&sp.key, r, rp, &s.types) {
343 Ok(_) => out.routes.push(r.clone()),
344 Err(e) => {
345 (trial.convs, trial.holds) = (convs, holds);
346 skipped.push(format!("`{} {}` of `{}`: {e}", r.method, r.path, s.name));
347 }
348 }
349 }
350 }
351 kept.services.retain(|s| !s.routes.is_empty());
352 Ok((kept, skipped))
353}
354
355fn merge_types(services: &[ServiceInput]) -> Result<HashMap<String, Arc<TypeDecl>>, ClientError> {
358 let mut out: HashMap<String, Arc<TypeDecl>> = HashMap::new();
359 let mut owner: HashMap<String, &str> = HashMap::new();
360 for s in services {
361 for (name, decl) in &s.types {
362 match out.get(name) {
363 None => {
364 out.insert(name.clone(), decl.clone());
365 owner.insert(name.clone(), &s.unit);
366 }
367 Some(prev) => {
368 if !Arc::ptr_eq(prev, decl) && format!("{prev:?}") != format!("{decl:?}") {
369 return fail(format!(
370 "`{}` and `{}` declare different types named `{}`; one client module cannot hold both. Generate them one at a time with `--service`",
371 owner[name],
372 s.unit,
373 bynk_check::symbols::display_type_name(name)
374 ));
375 }
376 }
377 }
378 }
379 }
380 Ok(out)
381}
382
383struct Plan {
385 services: Vec<ServicePlan>,
386}
387
388struct ServicePlan {
389 key: String,
391 routes: Vec<RoutePlan>,
392}
393
394struct RoutePlan {
395 function: String,
397 response: String,
399 query: Option<String>,
401 cookies: Option<String>,
403}
404
405struct Gen {
407 sc: SurfaceClosure,
408 qual: HashMap<String, String>,
410 ru: RuntimeUse,
411 convs: BTreeMap<String, Option<TsDecl>>,
413 holds: HashMap<String, bool>,
415}
416
417#[derive(Clone, Copy, PartialEq, Eq)]
418enum Dir {
419 ToPublic,
421 ToWire,
423}
424
425impl Dir {
426 fn prefix(self) -> &'static str {
427 match self {
428 Dir::ToPublic => "__toPublic_",
429 Dir::ToWire => "__toWire_",
430 }
431 }
432}
433
434impl Gen {
435 fn new(sc: SurfaceClosure) -> Self {
436 let mut qual: HashMap<String, String> = HashMap::new();
437 for n in sc.names.iter().chain(sc.generic_bases.iter()) {
438 qual.insert(n.clone(), format!("{WIRE_PREFIX}{n}"));
439 }
440 Gen {
441 sc,
442 qual,
443 ru: RuntimeUse::default(),
444 convs: BTreeMap::new(),
445 holds: HashMap::new(),
446 }
447 }
448
449 fn renamed(&self, t: &TypeRef) -> TypeRef {
450 serialisation::rename_type_ref(t, &self.sc.subst)
451 }
452
453 fn plan(&self, input: &HttpClientInput) -> Result<Plan, ClientError> {
458 let mut taken: BTreeSet<String> = self.sc.names.iter().cloned().collect();
459 taken.extend(self.sc.generic_bases.iter().cloned());
460 taken.extend(SURFACE_TYPES.iter().map(|s| s.to_string()));
461 let mut keys: BTreeSet<String> = BTreeSet::new();
462 let mut services = Vec::new();
463 let mut seen: BTreeMap<String, usize> = BTreeMap::new();
466 for s in &input.services {
467 for r in &s.routes {
468 *seen.entry(function_name(&r.method, &r.path)).or_default() += 1;
469 }
470 }
471 for s in &input.services {
472 let mut key = s.name.clone();
473 if keys.contains(&key) {
474 key = format!("{}_{}", s.unit.replace('.', "_"), s.name);
475 }
476 keys.insert(key.clone());
477 let mut fns: BTreeMap<String, &RouteInput> = BTreeMap::new();
478 let mut routes = Vec::new();
479 for r in &s.routes {
480 let function = function_name(&r.method, &r.path);
481 if let Some(other) = fns.insert(function.clone(), r) {
482 return fail(format!(
483 "`{} {}` and `{} {}` of service `{}` both make the function `{function}`; the client cannot name them apart",
484 other.method, other.path, r.method, r.path, s.name
485 ));
486 }
487 let stem = if seen[&function] > 1 {
488 format!("{}{}", pascal(&s.name), pascal(&function))
489 } else {
490 pascal(&function)
491 };
492 let response = unique(format!("{stem}Response"), &mut taken);
493 let has_query = r
494 .params
495 .iter()
496 .any(|p| matches!(p, ParamInput::Query { .. }));
497 let query = has_query.then(|| unique(format!("{stem}Query"), &mut taken));
498 let has_cookies = r
499 .params
500 .iter()
501 .any(|p| matches!(p, ParamInput::Cookies { .. }));
502 let cookies = has_cookies.then(|| unique(format!("{stem}Cookies"), &mut taken));
503 routes.push(RoutePlan {
504 function,
505 response,
506 query,
507 cookies,
508 });
509 }
510 services.push(ServicePlan { key, routes });
511 }
512 Ok(Plan { services })
513 }
514
515 fn public_type(&self, t: &TypeRef) -> Result<TsType, ClientError> {
521 Ok(match t {
522 TypeRef::Option(inner, _) => {
523 if matches!(inner.as_ref(), TypeRef::Option(..)) {
524 return fail("an `Option[Option[T]]` has no `T | null` form");
525 }
526 TsType::union(vec![self.public_type(inner)?, TsType::named("null")])
527 }
528 TypeRef::List(inner, _) => TsType::readonly_array(self.public_type(inner)?),
529 TypeRef::Set(inner, _) => {
530 TsType::named_with_args("ReadonlySet", vec![self.public_type(inner)?])
531 }
532 TypeRef::Map(k, v, _) => TsType::named_with_args(
533 "ReadonlyMap",
534 vec![self.public_type(k)?, self.public_type(v)?],
535 ),
536 TypeRef::Result(a, b, _) => {
537 TsType::named_with_args("Result", vec![self.public_type(a)?, self.public_type(b)?])
538 }
539 TypeRef::App { name, args, .. } => {
540 let args: Result<Vec<TsType>, ClientError> =
541 args.iter().map(|a| self.public_type(a)).collect();
542 TsType::named_with_args(name.name.clone(), args?)
543 }
544 TypeRef::Named(id) if self.is_file(&id.name) => TsType::named("globalThis.Blob"),
547 other @ TypeRef::Base(..)
548 | other @ TypeRef::Named(_)
549 | other @ TypeRef::Effect(..)
550 | other @ TypeRef::HttpResult(..)
551 | other @ TypeRef::QueueResult(_)
552 | other @ TypeRef::Asset(_)
553 | other @ TypeRef::RequestHeaders(_)
554 | other @ TypeRef::RequestQuery(_)
555 | other @ TypeRef::RequestCookies(_)
556 | other @ TypeRef::TokenClaims(_)
557 | other @ TypeRef::BoundaryRejection(_)
558 | other @ TypeRef::Query(..)
559 | other @ TypeRef::Stream(..)
560 | other @ TypeRef::Connection(..)
561 | other @ TypeRef::History(..)
562 | other @ TypeRef::ValidationError(_)
563 | other @ TypeRef::DecodeError(_)
564 | other @ TypeRef::Unit(_)
565 | other @ TypeRef::Fn(..) => {
566 super::ts_types::ts_type_ref_qualified_multi_ts_type(other, &HashMap::new())
567 }
568 })
569 }
570
571 fn is_file(&self, name: &str) -> bool {
574 if bynk_check::symbols::display_type_name(name) != "File" {
575 return false;
576 }
577 match self.sc.types.get(name).map(|d| &d.body) {
578 None => name == "File" || name == "bynk__File",
581 Some(TypeBody::Record(r)) => {
582 let fields: Vec<&str> = r.fields.iter().map(|f| f.name.name.as_str()).collect();
583 fields == ["filename", "contentType", "bytes"]
584 }
585 Some(_) => false,
586 }
587 }
588
589 fn wire_type(&self, t: &TypeRef) -> TsType {
591 serialisation::qualified_ts_type(t, &self.qual)
592 }
593
594 fn declare(
596 &self,
597 name: &str,
598 decl: &TypeDecl,
599 public: bool,
600 ) -> Result<Vec<TsStmt>, ClientError> {
601 let ty = |t: &TypeRef| -> Result<TsType, ClientError> {
602 if public {
603 self.public_type(t)
604 } else {
605 Ok(self.wire_type(t))
606 }
607 };
608 let params: Vec<String> = decl
609 .type_params
610 .iter()
611 .map(|p| p.name.name.clone())
612 .collect();
613 let shown = if public {
614 name.to_string()
615 } else {
616 format!("{WIRE_PREFIX}{name}")
617 };
618 let d = match &decl.body {
619 TypeBody::Record(r) => {
620 let mut members = Vec::new();
621 for f in &r.fields {
622 members.push(TsTypeMember::readonly_prop(
623 f.name.name.clone(),
624 ty(&f.type_ref)?,
625 ));
626 }
627 TsDecl::Interface {
628 name: shown,
629 type_params: params,
630 members,
631 }
632 }
633 TypeBody::Sum(sum) => {
634 let mut variants = Vec::new();
635 for v in &sum.variants {
636 let mut members = vec![TsTypeMember::readonly_prop(
637 "tag",
638 TsType::named(format!("\"{}\"", v.name.name)),
639 )];
640 for f in &v.payload {
641 members.push(TsTypeMember::readonly_prop(
642 super::payload_prop(&f.name.name),
643 ty(&f.type_ref)?,
644 ));
645 }
646 variants.push(TsType::Object(members));
647 }
648 TsDecl::TypeAlias {
649 name: shown,
650 type_params: params,
651 ty: TsType::multiline_union(variants),
652 }
653 }
654 TypeBody::Refined {
655 base, base_span, ..
656 } => TsDecl::TypeAlias {
657 name: shown,
658 type_params: params,
659 ty: ty(&TypeRef::Base(*base, *base_span))?,
660 },
661 TypeBody::Opaque {
662 base, base_span, ..
663 } => TsDecl::TypeAlias {
664 name: shown,
665 type_params: params,
666 ty: TsType::intersection(vec![
667 ty(&TypeRef::Base(*base, *base_span))?,
668 TsType::Object(vec![TsTypeMember::readonly_prop(
669 "__opaque",
670 TsType::named(format!("\"{name}\"")),
671 )]),
672 ]),
673 },
674 };
675 let mut out = Vec::new();
676 if public && let Some(text) = decl.documentation.as_deref() {
677 out.push(TsStmt::doc_comment(text, None));
678 }
679 let mut stmt = TsStmt::decl(TsDecl::Export(Box::new(d)), None);
680 stmt.no_blank_before = !out.is_empty();
681 out.push(stmt);
682 Ok(out)
683 }
684
685 fn holds_option(&mut self, t: &TypeRef) -> bool {
691 match t {
692 TypeRef::Option(..) => true,
693 TypeRef::List(i, _) | TypeRef::Set(i, _) => self.holds_option(i),
694 TypeRef::Map(k, v, _) | TypeRef::Result(k, v, _) => {
695 self.holds_option(k) || self.holds_option(v)
696 }
697 TypeRef::Named(id) => {
698 let key = id.name.clone();
699 self.named_holds(&key, &key, &[])
700 }
701 TypeRef::App { name, args, .. } => {
702 let key = serialisation::app_ts_name(&name.name, args);
703 self.named_holds(&key, &name.name, args)
704 }
705 TypeRef::Base(..)
706 | TypeRef::Effect(..)
707 | TypeRef::HttpResult(..)
708 | TypeRef::QueueResult(_)
709 | TypeRef::Asset(_)
710 | TypeRef::RequestHeaders(_)
711 | TypeRef::RequestQuery(_)
712 | TypeRef::RequestCookies(_)
713 | TypeRef::TokenClaims(_)
714 | TypeRef::BoundaryRejection(_)
715 | TypeRef::Query(..)
716 | TypeRef::Stream(..)
717 | TypeRef::Connection(..)
718 | TypeRef::History(..)
719 | TypeRef::ValidationError(_)
720 | TypeRef::DecodeError(_)
721 | TypeRef::Unit(_)
722 | TypeRef::Fn(..) => false,
723 }
724 }
725
726 fn named_holds(&mut self, key: &str, decl: &str, args: &[TypeRef]) -> bool {
727 if let Some(h) = self.holds.get(key) {
728 return *h;
729 }
730 self.holds.insert(key.to_string(), false);
732 let fields = self.fields_of(decl, args);
733 let found = fields.iter().any(|f| self.holds_option(&f.1));
734 self.holds.insert(key.to_string(), found);
735 found
736 }
737
738 fn variants_of(&self, decl: &str, args: &[TypeRef]) -> Option<(bool, Vec<Variant>)> {
741 let types = &self.sc.types;
742 let d = types.get(decl)?;
743 match &d.body {
744 TypeBody::Record(_) => {
745 let fields = if args.is_empty() {
746 let TypeBody::Record(r) = &d.body else {
747 return None;
748 };
749 r.fields
750 .iter()
751 .map(|f| (f.name.name.clone(), f.type_ref.clone()))
752 .collect()
753 } else {
754 bynk_check::wire::record_inst_fields(decl, args, types)?
755 };
756 Some((true, vec![(String::new(), fields)]))
757 }
758 TypeBody::Sum(_) => {
759 if args.is_empty() {
760 let TypeBody::Sum(s) = &d.body else {
761 return None;
762 };
763 Some((
764 false,
765 s.variants
766 .iter()
767 .map(|v| {
768 (
769 v.name.name.clone(),
770 v.payload
771 .iter()
772 .map(|f| (f.name.name.clone(), f.type_ref.clone()))
773 .collect(),
774 )
775 })
776 .collect(),
777 ))
778 } else {
779 Some((
780 false,
781 bynk_check::wire::sum_inst_variants(decl, args, types)?,
782 ))
783 }
784 }
785 TypeBody::Refined { .. } | TypeBody::Opaque { .. } => None,
786 }
787 }
788
789 fn fields_of(&self, decl: &str, args: &[TypeRef]) -> Vec<(String, TypeRef)> {
790 self.variants_of(decl, args)
791 .map(|(_, vs)| vs.into_iter().flat_map(|v| v.1).collect())
792 .unwrap_or_default()
793 }
794
795 fn convert(
798 &mut self,
799 t: &TypeRef,
800 dir: Dir,
801 expr: TsExpr,
802 depth: usize,
803 ) -> Result<TsExpr, ClientError> {
804 if !self.holds_option(t) {
805 return Ok(expr);
806 }
807 let x = format!("x{depth}");
808 let lambda = |body: TsExpr| TsExpr::Arrow {
809 params: vec![TsParam::new(x.clone(), None)],
810 is_async: false,
811 generics: Vec::new(),
812 return_type: None,
813 body: Box::new(TsArrowBody::Expr(Box::new(body))),
814 };
815 match t {
816 TypeRef::Option(inner, _) => {
817 if matches!(inner.as_ref(), TypeRef::Option(..)) {
818 return fail("an `Option[Option[T]]` has no `T | null` form");
819 }
820 let body = self.convert(inner, dir, TsExpr::Ident(x.clone()), depth + 1)?;
821 let f = match dir {
822 Dir::ToPublic => "__optToNull",
823 Dir::ToWire => "__nullToOpt",
824 };
825 Ok(TsExpr::Call {
826 callee: Box::new(TsExpr::Ident(f.to_string())),
827 args: vec![expr, lambda(body)],
828 })
829 }
830 TypeRef::List(inner, _) => {
831 let body = self.convert(inner, dir, TsExpr::Ident(x.clone()), depth + 1)?;
832 Ok(TsExpr::Call {
833 callee: Box::new(TsExpr::Member {
834 object: Box::new(expr),
835 property: "map".to_string(),
836 }),
837 args: vec![lambda(body)],
838 })
839 }
840 TypeRef::Set(..) | TypeRef::Map(..) | TypeRef::Result(..) => fail(
841 "an `Option` inside a `Map`, `Set` or `Result` has no `T | null` form in this version of `bynk client`",
842 ),
843 TypeRef::Named(id) => {
844 let key = id.name.clone();
845 self.named_conversion(&key, &key, &[], t, dir)?;
846 Ok(conversion_call(dir, &key, expr))
847 }
848 TypeRef::App { name, args, .. } => {
849 let key = serialisation::app_ts_name(&name.name, args);
850 self.named_conversion(&key, &name.name, args, t, dir)?;
851 Ok(conversion_call(dir, &key, expr))
852 }
853 TypeRef::Base(..)
854 | TypeRef::Effect(..)
855 | TypeRef::HttpResult(..)
856 | TypeRef::QueueResult(_)
857 | TypeRef::Asset(_)
858 | TypeRef::RequestHeaders(_)
859 | TypeRef::RequestQuery(_)
860 | TypeRef::RequestCookies(_)
861 | TypeRef::TokenClaims(_)
862 | TypeRef::BoundaryRejection(_)
863 | TypeRef::Query(..)
864 | TypeRef::Stream(..)
865 | TypeRef::Connection(..)
866 | TypeRef::History(..)
867 | TypeRef::ValidationError(_)
868 | TypeRef::DecodeError(_)
869 | TypeRef::Unit(_)
870 | TypeRef::Fn(..) => Ok(expr),
871 }
872 }
873
874 fn named_conversion(
876 &mut self,
877 key: &str,
878 decl: &str,
879 args: &[TypeRef],
880 t: &TypeRef,
881 dir: Dir,
882 ) -> Result<(), ClientError> {
883 let name = format!("{}{key}", dir.prefix());
884 if self.convs.contains_key(&name) {
885 return Ok(());
886 }
887 self.convs.insert(name.clone(), None);
889 let Some((is_record, variants)) = self.variants_of(decl, args) else {
890 return Ok(());
891 };
892 let (wire, public) = (self.wire_type(t), self.public_type(t)?);
893 let (from, to) = match dir {
894 Dir::ToPublic => (wire, public),
895 Dir::ToWire => (public, wire),
896 };
897 let v = || TsExpr::Ident("v".to_string());
898 let mut body = Vec::new();
899 for (variant, fields) in &variants {
900 let mut entries = vec![TsObjectEntry::Spread(v())];
901 let mut converted = false;
902 for (field, ft) in fields {
903 if self.holds_option(ft) {
904 let prop = if is_record {
905 field.clone()
906 } else {
907 super::payload_prop(field)
908 };
909 let from_prop = TsExpr::Member {
910 object: Box::new(v()),
911 property: prop.clone(),
912 };
913 let conv = self.convert(ft, dir, from_prop, 0)?;
914 entries.push(TsObjectEntry::prop(prop, conv));
915 converted = true;
916 }
917 }
918 if !converted {
919 continue;
920 }
921 let object = cast_via_unknown(TsExpr::object_entries(entries), &to);
922 if is_record {
923 body.push(TsStmt::return_stmt(Some(object), None));
924 } else {
925 let is_variant = TsExpr::Binary {
926 op: TsBinaryOp::StrictEq,
927 left: Box::new(TsExpr::Member {
928 object: Box::new(v()),
929 property: "tag".to_string(),
930 }),
931 right: Box::new(TsExpr::Lit(TsLit::Str(variant.clone()))),
932 };
933 body.push(TsStmt::if_stmt(
934 is_variant,
935 TsStmt::return_stmt(Some(object), None),
936 None,
937 ));
938 }
939 }
940 if !is_record {
941 body.push(TsStmt::return_stmt(Some(cast_via_unknown(v(), &to)), None));
942 }
943 self.convs.insert(
944 name.clone(),
945 Some(TsDecl::Function {
946 name,
947 generics: Vec::new(),
948 params: vec![TsParam::new("v", Some(from))],
949 return_type: Some(to),
950 body,
951 is_async: false,
952 inline: false,
953 }),
954 );
955 Ok(())
956 }
957
958 fn emit(&mut self, input: &HttpClientInput, plan: &Plan) -> Result<Parts, ClientError> {
963 let mut stmts: Vec<TsStmt> = Vec::new();
964
965 let mut glue: Vec<TsStmt> = Vec::new();
967 let mut unions: Vec<TsStmt> = Vec::new();
968 let mut services: Vec<TsObjectEntry> = Vec::new();
969 let mut contracts: Vec<TsObjectEntry> = Vec::new();
970 for (s, sp) in input.services.iter().zip(&plan.services) {
971 let mut methods: Vec<TsObjectEntry> = Vec::new();
972 let mut hashes: Vec<(String, String)> = Vec::new();
973 for (r, rp) in s.routes.iter().zip(&sp.routes) {
974 let route = self.route(&sp.key, r, rp, &s.types)?;
975 hashes.push((rp.function.clone(), route.hash.clone()));
976 glue.push(route.constant);
977 unions.extend(route.response_type.into_iter().flatten());
978 unions.extend(route.arg_types);
979 methods.push(route.method);
980 }
981 services.push(TsObjectEntry::prop(
982 property(&sp.key),
983 TsExpr::multiline_object_entries(methods),
984 ));
985 let all: Vec<String> = hashes.iter().map(|(_, h)| h.clone()).collect();
986 let routes = hashes
987 .iter()
988 .map(|(function, hash)| {
989 TsObjectEntry::prop(property(function), TsExpr::Lit(TsLit::Str(hash.clone())))
990 })
991 .collect();
992 contracts.push(TsObjectEntry::prop(
993 property(&sp.key),
994 TsExpr::multiline_object_entries(vec![
995 TsObjectEntry::prop(
996 "service",
997 TsExpr::Lit(TsLit::Str(contract::http_service_contract_hash(&all))),
998 ),
999 TsObjectEntry::prop("routes", TsExpr::multiline_object_entries(routes)),
1000 ]),
1001 ));
1002 }
1003
1004 let mut type_names: Vec<String> = self
1006 .sc
1007 .names
1008 .iter()
1009 .filter(|n| {
1010 self.sc
1011 .types
1012 .get(*n)
1013 .is_some_and(|d| d.type_params.is_empty())
1014 })
1015 .cloned()
1016 .collect();
1017 type_names.extend(self.sc.generic_bases.iter().cloned());
1018 type_names.sort();
1019 type_names.dedup();
1020 for public in [true, false] {
1021 for name in &type_names {
1022 if public && self.is_file(name) {
1024 continue;
1025 }
1026 if let Some(decl) = self.sc.types.get(name) {
1027 stmts.extend(self.declare(name, decl, public)?);
1028 }
1029 }
1030 }
1031 stmts.extend(unions);
1032 let mut codecs: Vec<TsStmt> = Vec::new();
1033 if self.sc.names.iter().any(|n| self.is_file(n)) {
1037 stmts.push(TsStmt::raw_using(FILE_TYPE, FILE_TYPE_USES));
1039 codecs.push(TsStmt::raw_using(FILE_CODEC, FILE_CODEC_USES));
1041 }
1042 let types = self.sc.types.clone();
1043 codecs.extend(serialisation::decls_as_stmts(
1044 serialisation::emit_helpers_for_owner_qualified(
1045 &self.sc.names,
1046 &types,
1047 "",
1048 &self.qual,
1049 &self.ru,
1050 ),
1051 ));
1052 codecs.extend(serialisation::decls_as_stmts(
1053 serialisation::emit_generic_helpers_qualified(
1054 &self.sc.insts,
1055 &types,
1056 &self.qual,
1057 &self.ru,
1058 ),
1059 ));
1060 for decl in self.convs.values().flatten() {
1061 codecs.push(TsStmt::decl(TsDecl::Export(Box::new(decl.clone())), None));
1062 }
1063 let mut index: Vec<TsStmt> = glue;
1064 index.extend(contracts_stmts(contracts));
1065 index.extend(client_stmts(services));
1066
1067 let print = |stmts: Vec<TsStmt>| {
1068 bynk_ts::print(&TsProgram { stmts }, "", "", "client.ts")
1071 .text
1072 .replace(&format!("field: \"{WIRE_PREFIX}"), "field: \"")
1073 };
1074 Ok(Parts {
1075 types: print(stmts),
1076 codecs: print(codecs),
1077 index: print(index),
1078 })
1079 }
1080}
1081
1082type Variant = (String, Vec<(String, TypeRef)>);
1083
1084fn conversion_call(dir: Dir, key: &str, expr: TsExpr) -> TsExpr {
1086 let function = format!("{}{key}", dir.prefix());
1087 TsExpr::Call {
1088 callee: Box::new(TsExpr::Ident(function)),
1089 args: vec![expr],
1090 }
1091}
1092
1093fn documented(doc: &str, decl: TsDecl) -> Vec<TsStmt> {
1095 let mut stmt = TsStmt::decl(TsDecl::Export(Box::new(decl)), None);
1096 stmt.no_blank_before = true;
1097 vec![TsStmt::doc_comment(doc, None), stmt]
1098}
1099
1100fn contracts_stmts(services: Vec<TsObjectEntry>) -> Vec<TsStmt> {
1103 documented(
1104 "The contract of each service and route this client was generated for: a hash of\nwhat a client acts on (the route's method and path, what it takes, what it can\nanswer). It moves when that does and not for a handler's body. Informational: log\nit, compare it with the server's, or send it with `sendContract`.",
1105 TsDecl::ConstDecl {
1106 name: "API_CONTRACTS".to_string(),
1107 ty: None,
1108 init: TsExpr::AsConst(Box::new(TsExpr::multiline_object_entries(services))),
1109 },
1110 )
1111}
1112
1113fn client_stmts(services: Vec<TsObjectEntry>) -> Vec<TsStmt> {
1115 let mut out = documented(
1116 "The client: one property per service, one function per route. Each returns\nthe route's own response, a union keyed by `status`, or a `CallFailure`.",
1117 TsDecl::Function {
1118 name: "createClient".to_string(),
1119 generics: Vec::new(),
1120 params: vec![
1121 TsParam::new("options", Some(TsType::named("ClientOptions")))
1122 .with_default(TsExpr::object(Vec::new())),
1123 ],
1124 return_type: None,
1125 body: vec![TsStmt::return_stmt(
1126 Some(TsExpr::AsConst(Box::new(TsExpr::multiline_object_entries(
1127 services,
1128 )))),
1129 None,
1130 )],
1131 is_async: false,
1132 inline: false,
1133 },
1134 );
1135 out.extend(documented(
1136 "The client `createClient` makes.",
1137 TsDecl::TypeAlias {
1138 name: "Client".to_string(),
1139 type_params: Vec::new(),
1140 ty: TsType::named_with_args(
1141 "ReturnType",
1142 vec![TsType::type_of(TsExpr::Ident("createClient".to_string()))],
1143 ),
1144 },
1145 ));
1146 out
1147}
1148
1149fn cast_via_unknown(expr: TsExpr, ty: &TsType) -> TsExpr {
1151 TsExpr::As {
1152 expr: Box::new(TsExpr::As {
1153 expr: Box::new(expr),
1154 ty: TsType::named("unknown"),
1155 }),
1156 ty: ty.clone(),
1157 }
1158}
1159
1160pub fn function_name(method: &str, path: &str) -> String {
1168 let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
1169 let mut out = method.to_lowercase();
1170 if segments.is_empty() {
1171 out.push_str("Root");
1172 }
1173 for (i, seg) in segments.iter().enumerate() {
1174 if let Some(param) = seg.strip_prefix(':') {
1175 out.push_str("By");
1176 out.push_str(&pascal(param));
1177 } else {
1178 let before_param = segments.get(i + 1).is_some_and(|n| n.starts_with(':'));
1179 let words = pascal(seg);
1180 out.push_str(&if before_param {
1181 singular(&words)
1182 } else {
1183 words
1184 });
1185 }
1186 }
1187 out
1188}
1189
1190fn singular(word: &str) -> String {
1191 if let Some(stem) = word.strip_suffix("ies") {
1192 format!("{stem}y")
1193 } else if word.ends_with("ss") || word.len() < 4 {
1194 word.to_string()
1195 } else if let Some(stem) = word.strip_suffix('s') {
1196 stem.to_string()
1197 } else {
1198 word.to_string()
1199 }
1200}
1201
1202fn pascal(s: &str) -> String {
1204 let mut out = String::new();
1205 let mut upper = true;
1206 for c in s.chars() {
1207 if c.is_ascii_alphanumeric() {
1208 if upper {
1209 out.extend(c.to_uppercase());
1210 } else {
1211 out.push(c);
1212 }
1213 upper = false;
1214 } else {
1215 upper = true;
1216 }
1217 }
1218 out
1219}
1220
1221fn sanitise(s: &str) -> String {
1222 s.chars()
1223 .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
1224 .collect()
1225}
1226
1227fn unique(mut name: String, taken: &mut BTreeSet<String>) -> String {
1229 while taken.contains(&name) {
1230 name.push('_');
1231 }
1232 taken.insert(name.clone());
1233 name
1234}
1235
1236fn property(name: &str) -> String {
1238 let ident = name.chars().enumerate().all(|(i, c)| {
1239 c == '_' || c == '$' || c.is_ascii_alphabetic() || (i > 0 && c.is_ascii_digit())
1240 });
1241 if ident {
1242 name.to_string()
1243 } else {
1244 format!("{name:?}")
1245 }
1246}
1247
1248fn exported_names(source: &str) -> Vec<String> {
1250 source
1251 .lines()
1252 .filter_map(|l| {
1253 let rest = l.strip_prefix("export ")?;
1254 let rest = rest
1255 .strip_prefix("function ")
1256 .or_else(|| rest.strip_prefix("const "))
1257 .or_else(|| rest.strip_prefix("class "))?;
1258 let name: String = rest
1259 .chars()
1260 .take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '$')
1261 .collect();
1262 name.starts_with("__").then_some(name)
1263 })
1264 .collect()
1265}
1266
1267fn strip_imports(source: &str) -> String {
1270 let mut out = String::new();
1271 for line in source.lines() {
1272 let t = line.trim_start();
1273 if t.starts_with("import ") && t.contains("from \"./") {
1274 continue;
1275 }
1276 out.push_str(line);
1277 out.push('\n');
1278 }
1279 out
1280}
1281
1282struct Parts {
1284 types: String,
1286 codecs: String,
1288 index: String,
1290}
1291
1292fn header(input: &HttpClientInput) -> String {
1294 format!(
1295 "// @generated by `bynk client` — do not edit by hand.\n// bynk {}. Regenerate with `bynk client`; see https://bynk-lang.org/reference/http-client/\n// {EXPERIMENTAL}\n\n",
1296 input.compiler_version
1297 )
1298}
1299
1300fn runtime_text(scan: &str) -> String {
1304 let mut want = vec![false; OPTIONAL_MODULES.len()];
1306 for (i, (_, source)) in OPTIONAL_MODULES.iter().enumerate() {
1307 want[i] = exported_names(source)
1308 .iter()
1309 .any(|n| scan.contains(n.as_str()));
1310 }
1311 if want[3] {
1312 want[1] = true;
1313 }
1314 let mut chunks = vec![RESULT_MODULE];
1315 for (i, (_, source)) in OPTIONAL_MODULES.iter().enumerate() {
1316 if want[i] {
1317 chunks.push(source);
1318 }
1319 }
1320 chunks.push(RUNTIME);
1321 let mut out = String::new();
1322 for chunk in chunks {
1323 out.push_str(&strip_imports(chunk));
1324 out.push('\n');
1325 }
1326 out.push_str(&format!(
1327 "/** The wire format version this client was generated for. */\nexport const WIRE_VERSION = \"{}\";\n",
1328 bynk_check::wire_format::WIRE_VERSION
1329 ));
1330 out
1331}
1332
1333fn assemble(input: &HttpClientInput, parts: Parts, layout: Layout) -> Vec<(String, String)> {
1335 let head = header(input);
1336 let scan = format!("{}{}{}", parts.types, parts.codecs, parts.index);
1337 let runtime = runtime_text(&scan);
1338 match layout {
1339 Layout::File => vec![(
1340 SINGLE_FILE.to_string(),
1341 format!(
1342 "{head}{runtime}\n{}\n{}\n{}",
1343 parts.types, parts.codecs, parts.index
1344 ),
1345 )],
1346 Layout::Dir => {
1347 let files: Vec<(&str, String)> = vec![
1348 ("runtime.ts", runtime),
1349 ("types.ts", parts.types),
1350 ("codecs.ts", parts.codecs),
1351 (
1352 "index.ts",
1353 format!(
1354 "export * from \"./types.js\";\nexport * from \"./runtime.js\";\n\n{}",
1355 parts.index
1356 ),
1357 ),
1358 ];
1359 let mut declared: BTreeMap<String, (&str, bool)> = BTreeMap::new();
1362 for (name, text) in &files {
1363 for (n, is_type) in declared_exports(text) {
1364 declared.insert(n, (name, is_type));
1365 }
1366 }
1367 let mut out = Vec::new();
1368 for (name, text) in &files {
1369 let imports = imports_for(name, text, &declared);
1370 out.push((name.to_string(), format!("{head}{imports}{text}")));
1371 }
1372 out.sort_by_key(|(n, _)| DIR_FILES.iter().position(|f| f == n));
1374 out
1375 }
1376 }
1377}
1378
1379fn declared_exports(text: &str) -> Vec<(String, bool)> {
1381 let mut out = Vec::new();
1382 for line in text.lines() {
1383 let Some(rest) = line.strip_prefix("export ") else {
1384 continue;
1385 };
1386 let (rest, is_type) = if let Some(r) = rest.strip_prefix("type ") {
1387 (r, true)
1388 } else if let Some(r) = rest.strip_prefix("interface ") {
1389 (r, true)
1390 } else if let Some(r) = rest
1391 .strip_prefix("function ")
1392 .or_else(|| rest.strip_prefix("async function "))
1393 .or_else(|| rest.strip_prefix("const "))
1394 .or_else(|| rest.strip_prefix("class "))
1395 {
1396 (r, false)
1397 } else {
1398 continue;
1399 };
1400 let name: String = rest
1401 .chars()
1402 .take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '$')
1403 .collect();
1404 if !name.is_empty() {
1405 out.push((name, is_type));
1406 }
1407 }
1408 out
1409}
1410
1411fn imports_for(file: &str, text: &str, declared: &BTreeMap<String, (&str, bool)>) -> String {
1413 let used = code_identifiers(text);
1414 let mut by_file: BTreeMap<&str, Vec<String>> = BTreeMap::new();
1415 for (name, (from, is_type)) in declared {
1416 if *from != file && used.contains(name.as_str()) {
1417 let spec = if *is_type {
1418 format!("type {name}")
1419 } else {
1420 name.clone()
1421 };
1422 by_file.entry(from).or_default().push(spec);
1423 }
1424 }
1425 let mut out = String::new();
1426 for from in ["runtime.ts", "types.ts", "codecs.ts"] {
1427 if let Some(names) = by_file.get(from) {
1428 let module = from.trim_end_matches(".ts");
1429 out.push_str(&format!(
1430 "import {{ {} }} from \"./{module}.js\";\n",
1431 names.join(", ")
1432 ));
1433 }
1434 }
1435 if !out.is_empty() {
1436 out.push('\n');
1437 }
1438 out
1439}
1440
1441fn code_identifiers(text: &str) -> BTreeSet<String> {
1444 let chars: Vec<char> = text.chars().collect();
1445 let mut out = BTreeSet::new();
1446 let mut i = 0;
1447 while i < chars.len() {
1448 let c = chars[i];
1449 match c {
1450 '/' if chars.get(i + 1) == Some(&'/') => {
1451 while i < chars.len() && chars[i] != '\n' {
1452 i += 1;
1453 }
1454 }
1455 '/' if chars.get(i + 1) == Some(&'*') => {
1456 i += 2;
1457 while i + 1 < chars.len() && !(chars[i] == '*' && chars[i + 1] == '/') {
1458 i += 1;
1459 }
1460 i += 2;
1461 }
1462 '"' | '\'' => {
1463 i += 1;
1464 while i < chars.len() && chars[i] != c {
1465 i += if chars[i] == '\\' { 2 } else { 1 };
1466 }
1467 i += 1;
1468 }
1469 '`' => {
1470 i += 1;
1471 i = skip_template(&chars, i, &mut out);
1472 }
1473 _ if c.is_ascii_alphabetic() || c == '_' || c == '$' => {
1474 let start = i;
1475 while i < chars.len()
1476 && (chars[i].is_ascii_alphanumeric() || chars[i] == '_' || chars[i] == '$')
1477 {
1478 i += 1;
1479 }
1480 out.insert(chars[start..i].iter().collect());
1481 }
1482 _ => i += 1,
1483 }
1484 }
1485 out
1486}
1487
1488fn skip_template(chars: &[char], mut i: usize, out: &mut BTreeSet<String>) -> usize {
1491 while i < chars.len() {
1492 match chars[i] {
1493 '\\' => i += 2,
1494 '`' => return i + 1,
1495 '$' if chars.get(i + 1) == Some(&'{') => {
1496 let start = i + 2;
1497 let mut depth = 1;
1498 i = start;
1499 while i < chars.len() && depth > 0 {
1500 match chars[i] {
1501 '{' => depth += 1,
1502 '}' => depth -= 1,
1503 _ => {}
1504 }
1505 i += 1;
1506 }
1507 let inner: String = chars[start..i.saturating_sub(1)].iter().collect();
1508 out.extend(code_identifiers(&inner));
1509 }
1510 _ => i += 1,
1511 }
1512 }
1513 i
1514}
1515
1516#[cfg(test)]
1517mod tests {
1518 use super::*;
1519
1520 #[test]
1521 fn a_route_is_named_from_its_method_and_path() {
1522 for (method, path, name) in [
1523 ("GET", "/orders/:id", "getOrderById"),
1524 ("POST", "/orders", "postOrders"),
1525 ("DELETE", "/orders/:sku", "deleteOrderBySku"),
1526 ("GET", "/orders/:sku/lines/:line", "getOrderBySkuLineByLine"),
1527 ("GET", "/", "getRoot"),
1528 ("GET", "/health-check", "getHealthCheck"),
1529 ("GET", "/categories/:id", "getCategoryById"),
1530 ("GET", "/address/:id", "getAddressById"),
1531 (
1532 "PUT",
1533 "/v1/user_profiles/:user.id",
1534 "putV1UserProfileByUserId",
1535 ),
1536 ] {
1537 assert_eq!(function_name(method, path), name, "{method} {path}");
1538 }
1539 }
1540
1541 #[test]
1542 fn a_name_not_taken_gains_underscores_until_it_is() {
1543 let mut taken: BTreeSet<String> = ["Order".to_string(), "Order_".to_string()].into();
1544 assert_eq!(unique("Order".to_string(), &mut taken), "Order__");
1545 assert_eq!(unique("Order".to_string(), &mut taken), "Order___");
1546 assert_eq!(unique("Fresh".to_string(), &mut taken), "Fresh");
1547 }
1548
1549 #[test]
1550 fn a_property_is_quoted_only_when_it_must_be() {
1551 assert_eq!(property("orders"), "orders");
1552 assert_eq!(property("unit_Name"), "unit_Name");
1553 assert_eq!(property("a.b"), "\"a.b\"");
1554 }
1555
1556 #[test]
1560 fn the_inlined_boundary_types_are_the_runtimes() {
1561 let boundary = include_str!("../../runtime/src/boundary.ts");
1562 let errors = include_str!("../../runtime/src/errors.ts");
1563 let block = |source: &str, start: &str, end: &str| -> String {
1564 let from = source
1565 .find(start)
1566 .unwrap_or_else(|| panic!("`{start}` in source"));
1567 let to = source[from..]
1568 .find(end)
1569 .unwrap_or_else(|| panic!("`{end}`"))
1570 + from;
1571 source[from..to + end.len()].to_string()
1572 };
1573 for (source, start, end) in [
1574 (
1575 boundary,
1576 "export type JsonValue =",
1577 "{ [k: string]: JsonValue };",
1578 ),
1579 (
1580 boundary,
1581 "export type BoundaryError =",
1582 "status: number; readonly details: string };",
1583 ),
1584 (
1585 errors,
1586 "export interface ValidationError {",
1587 "readonly value: unknown;\n}",
1588 ),
1589 ] {
1590 let want = block(source, start, end);
1591 assert!(
1592 RUNTIME.contains(&want),
1593 "http_client_runtime.ts restates a runtime type that has changed:\n{want}"
1594 );
1595 }
1596 }
1597}