1use bynk_driver::colour;
14use bynk_driver::emsg;
15use std::path::{Path, PathBuf};
16use std::process::ExitCode;
17
18use bynk_emit::emitter::http_client::{
19 BodyKind, ClientError, DIR_FILES, HttpClientInput, Layout, ParamInput, ReplyInput,
20 ReplyPayload, RouteInput, ServiceInput, emit_http_client,
21};
22use bynk_ide::wire_contract::{
23 BoundaryKind, IrHttpMethod, ResponseOrigin, WireContractModel, real_context_count,
24 wire_contract_for_service,
25};
26use bynk_ide::{ContextBoundaryInfo, ProjectDiagnostics};
27use bynk_model::{IrHandlerKind, lower_handler_kind_ir};
28use bynk_syntax::ast::{
29 Handler, HttpVariantPayload, JsonOptions, TypeRef, effective_json_options, http_variant,
30};
31
32use crate::openapi::{self, Error as ProjectError, Selected};
33
34#[derive(Debug)]
36pub enum Error {
37 Project(ProjectError),
39 NothingToGenerate(Vec<String>),
41 Generate(ClientError),
43}
44
45impl std::fmt::Display for Error {
46 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47 match self {
48 Error::Project(e) => e.fmt(f),
49 Error::Generate(e) => e.fmt(f),
50 Error::NothingToGenerate(skipped) => {
51 write!(
52 f,
53 "no route of the selected services is one this version of `bynk client` can represent"
54 )?;
55 for s in skipped {
56 write!(f, "\n {s}")?;
57 }
58 Ok(())
59 }
60 }
61 }
62}
63
64impl std::error::Error for Error {}
65
66#[derive(Debug)]
68pub struct Client {
69 pub files: Vec<(String, String)>,
71 pub skipped: Vec<String>,
72}
73
74#[derive(Debug, Default)]
77pub struct Request<'a> {
78 pub services: &'a [String],
79 pub out: Option<&'a Path>,
80 pub layout: Option<Layout>,
81 pub check: bool,
82}
83
84pub fn run(root: &Path, req: Request) -> ExitCode {
87 let config = match bynk_project::try_read_build_config(root) {
88 Ok(c) => c.client,
89 Err(e) => {
90 emsg!("bynk: error: {e}");
91 return ExitCode::FAILURE;
92 }
93 };
94 let layout = req
95 .layout
96 .or_else(|| config.as_ref().map(|c| to_layout(c.layout)))
97 .unwrap_or_default();
98 let out: Option<PathBuf> = req
99 .out
100 .map(Path::to_path_buf)
101 .or_else(|| config.as_ref().map(|c| root.join(&c.out)));
102 let services: Vec<String> = if req.services.is_empty() {
103 config.map(|c| c.services).unwrap_or_default()
104 } else {
105 req.services.to_vec()
106 };
107 if let Err(e) = check_destination(out.as_deref(), layout, req.check) {
108 emsg!("bynk: error: {e}");
109 return ExitCode::FAILURE;
110 }
111 let names: Vec<&str> = services.iter().map(String::as_str).collect();
112 let analysis = openapi::analyse(root);
113 let client = match generate(&analysis, &names, layout) {
114 Ok(c) => c,
115 Err(e) => {
116 emsg!("bynk: error: {e}");
117 return ExitCode::FAILURE;
118 }
119 };
120 for s in &client.skipped {
121 emsg!("bynk: warning: skipped {s}");
122 }
123 match (out, req.check) {
124 (None, _) => {
125 print!("{}", client.files[0].1);
126 ExitCode::SUCCESS
127 }
128 (Some(out), true) => check(&client, &out, layout),
129 (Some(out), false) => match write(&client, &out, layout) {
130 Ok(()) => ExitCode::SUCCESS,
131 Err(e) => {
132 emsg!("bynk: error: {e}");
133 ExitCode::FAILURE
134 }
135 },
136 }
137}
138
139const GENERATED: &str = "// @generated by `bynk client`";
141
142fn note_extra_files(out: &Path, layout: Layout) {
145 if layout != Layout::Dir {
146 return;
147 }
148 let Ok(entries) = std::fs::read_dir(out) else {
149 return;
150 };
151 let mut extra: Vec<String> = entries
152 .flatten()
153 .map(|e| e.file_name().to_string_lossy().into_owned())
154 .filter(|n| n.ends_with(".ts") && !DIR_FILES.contains(&n.as_str()))
155 .collect();
156 extra.sort();
157 for name in extra {
158 emsg!(
159 "bynk: note: `{}` is not part of the client; a layout that was replaced may have left it",
160 out.join(name).display()
161 );
162 }
163}
164
165pub fn write_configured(root: &Path) -> ExitCode {
169 match bynk_project::try_read_build_config(root) {
170 Ok(c) if c.client.is_some() => {}
171 Ok(_) => return ExitCode::SUCCESS,
172 Err(e) => {
173 emsg!("bynk: error: {e}");
174 return ExitCode::FAILURE;
175 }
176 }
177 let code = run(root, Request::default());
178 if code == ExitCode::SUCCESS
179 && let Ok(Some(c)) = bynk_project::try_read_build_config(root).map(|c| c.client)
180 {
181 emsg!("bynk: wrote the client -> {}", root.join(c.out).display());
182 }
183 code
184}
185
186fn to_layout(l: bynk_project::ClientLayout) -> Layout {
187 match l {
188 bynk_project::ClientLayout::File => Layout::File,
189 bynk_project::ClientLayout::Dir => Layout::Dir,
190 }
191}
192
193fn check_destination(out: Option<&Path>, layout: Layout, check: bool) -> Result<(), String> {
195 match (out, layout) {
196 (None, _) if check => Err(
197 "`--check` compares with a written client: pass `--out PATH`, or set `[build.client]` in bynk.toml"
198 .to_string(),
199 ),
200 (None, Layout::Dir) => {
201 Err("`--layout dir` writes several files: pass `--out DIR`".to_string())
202 }
203 (Some(out), Layout::File) if out.is_dir() => Err(format!(
204 "`{}` is a directory; pass a file, or `--layout dir`",
205 out.display()
206 )),
207 (Some(out), Layout::Dir) if out.is_file() => Err(format!(
208 "`{}` is a file; `--layout dir` writes a directory",
209 out.display()
210 )),
211 _ => Ok(()),
212 }
213}
214
215fn destinations(client: &Client, out: &Path, layout: Layout) -> Vec<(PathBuf, String)> {
217 match layout {
218 Layout::File => vec![(out.to_path_buf(), client.files[0].1.clone())],
219 Layout::Dir => client
220 .files
221 .iter()
222 .map(|(name, text)| (out.join(name), text.clone()))
223 .collect(),
224 }
225}
226
227fn write(client: &Client, out: &Path, layout: Layout) -> Result<(), String> {
230 let targets = destinations(client, out, layout);
231 for (path, _) in &targets {
234 if let Ok(have) = std::fs::read(path)
235 && !have.starts_with(GENERATED.as_bytes())
236 {
237 return Err(format!(
238 "refusing to overwrite `{}`: it is not a client `bynk client` wrote (its first line is not `{GENERATED}`)",
239 path.display()
240 ));
241 }
242 }
243 note_extra_files(out, layout);
244 for (path, text) in targets {
245 if std::fs::read_to_string(&path).is_ok_and(|have| have == text) {
246 continue;
247 }
248 if let Some(dir) = path.parent() {
249 std::fs::create_dir_all(dir)
250 .map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
251 }
252 std::fs::write(&path, text).map_err(|e| format!("cannot write {}: {e}", path.display()))?;
253 }
254 Ok(())
255}
256
257fn check(client: &Client, out: &Path, layout: Layout) -> ExitCode {
259 let mut stale = Vec::new();
260 for (path, want) in destinations(client, out, layout) {
261 match std::fs::read_to_string(&path) {
262 Err(_) => stale.push(format!(" {}: missing", path.display())),
263 Ok(have) => {
264 if let Some(d) = short_diff(&path, &want, &have) {
265 stale.push(d);
266 }
267 }
268 }
269 }
270 note_extra_files(out, layout);
271 if stale.is_empty() {
272 return ExitCode::SUCCESS;
273 }
274 let dir = if layout == Layout::Dir {
275 " --layout dir"
276 } else {
277 ""
278 };
279 emsg!(
280 "bynk: error: client is stale: run `bynk client{dir} --out {}`",
281 out.display()
282 );
283 for line in stale {
284 colour::eprintln(&line);
285 }
286 ExitCode::FAILURE
287}
288
289fn without_version(text: &str) -> String {
292 text.lines()
293 .filter(|l| !(l.starts_with("// bynk ") && l.contains(". Regenerate with `bynk client`;")))
294 .collect::<Vec<_>>()
295 .join("\n")
296}
297
298fn short_diff(path: &Path, want: &str, have: &str) -> Option<String> {
301 let norm = |t: &str| without_version(&t.replace("\r\n", "\n"));
302 let (want, have) = (norm(want), norm(have));
303 if want == have {
304 return None;
305 }
306 let (w, h): (Vec<&str>, Vec<&str>) = (want.lines().collect(), have.lines().collect());
307 let first = (0..w.len().max(h.len()))
308 .find(|&i| w.get(i) != h.get(i))
309 .unwrap_or(0);
310 let differing = (0..w.len().max(h.len()))
311 .filter(|&i| w.get(i) != h.get(i))
312 .count();
313 let show = |l: Option<&&str>| l.map_or("<end of file>".to_string(), |l| l.to_string());
314 Some(format!(
315 " {} differs at line {} ({differing} line{} in all):\n - found: {}\n + expected: {}",
316 path.display(),
317 first + 1,
318 if differing == 1 { "" } else { "s" },
319 show(h.get(first)),
320 show(w.get(first)),
321 ))
322}
323
324pub fn generate(
327 analysis: &ProjectDiagnostics,
328 want: &[&str],
329 layout: Layout,
330) -> Result<Client, Error> {
331 let errors = openapi::errors_of(analysis);
332 if !errors.is_empty() {
333 return Err(Error::Project(ProjectError::Invalid(errors)));
334 }
335 let selected = openapi::select_services(analysis, want).map_err(Error::Project)?;
336 let context_count = real_context_count(&analysis.boundary_info, &analysis.unit_sources);
337 let mut services = Vec::new();
338 let mut skipped = Vec::new();
339 for sel in &selected {
340 let routes = routes_of(analysis, sel, context_count, &mut skipped);
341 if routes.is_empty() {
342 continue;
343 }
344 services.push(ServiceInput {
345 unit: sel.unit.to_string(),
346 name: sel.service.name.name.clone(),
347 doc: sel
348 .service
349 .documentation
350 .as_ref()
351 .map(|d| d.text.trim().to_string()),
352 types: sel.info.types.clone(),
353 routes,
354 });
355 }
356 if services.is_empty() {
357 return Err(Error::NothingToGenerate(skipped));
358 }
359 let input = HttpClientInput {
360 services,
361 compiler_version: env!("CARGO_PKG_VERSION").to_string(),
362 };
363 let emitted = emit_http_client(&input, layout).map_err(Error::Generate)?;
364 skipped.extend(emitted.skipped);
365 Ok(Client {
366 files: emitted.files,
367 skipped,
368 })
369}
370
371fn routes_of(
373 analysis: &ProjectDiagnostics,
374 sel: &Selected,
375 context_count: usize,
376 skipped: &mut Vec<String>,
377) -> Vec<RouteInput> {
378 let expr_types = unit_expr_types(analysis, sel.unit);
379 let mut routes = Vec::new();
380 for h in &sel.service.handlers {
381 if !matches!(lower_handler_kind_ir(&h.kind), IrHandlerKind::Http { .. }) {
382 continue;
383 }
384 let Some(model) = wire_contract_for_service(
385 sel.unit,
386 "",
387 &sel.service.name.name,
388 h,
389 sel.info,
390 &expr_types,
391 &analysis.ty_intern,
392 context_count,
393 ) else {
394 continue;
395 };
396 let BoundaryKind::Http { method, path } = &model.kind else {
397 continue;
398 };
399 match route_of(sel, h, &model, *method, path) {
400 Ok(r) => routes.push(r),
401 Err(why) => skipped.push(format!(
402 "`{} {path}` of `{}`: {why}",
403 method.as_str(),
404 sel.service.name.name
405 )),
406 }
407 }
408 routes
409}
410
411fn unit_expr_types(
413 analysis: &ProjectDiagnostics,
414 unit: &str,
415) -> Vec<(bynk_syntax::span::Span, bynk_check::checker::TyId)> {
416 analysis
417 .unit_sources
418 .get(unit)
419 .into_iter()
420 .flatten()
421 .filter_map(|p| analysis.expr_types.get(p))
422 .flatten()
423 .cloned()
424 .collect()
425}
426
427fn route_of(
429 sel: &Selected,
430 h: &Handler,
431 model: &WireContractModel,
432 method: IrHttpMethod,
433 path: &str,
434) -> Result<RouteInput, String> {
435 unsupported(sel.info, h)?;
436 let in_path: Vec<&str> = path
437 .split('/')
438 .filter_map(|s| s.strip_prefix(':'))
439 .collect();
440 let mut params = Vec::new();
441 for p in &h.params {
442 let name = p.name.name.as_str();
443 if name == "body" {
444 params.push(ParamInput::Body {
445 ty: p.type_ref.clone(),
446 kind: body_kind(h),
447 });
448 } else if in_path.contains(&name) {
449 params.push(ParamInput::Path {
450 name: name.to_string(),
451 ty: p.type_ref.clone(),
452 });
453 } else if name == "query" && matches!(p.type_ref, TypeRef::Named(_)) {
454 params.push(ParamInput::Query {
455 ty: p.type_ref.clone(),
456 });
457 } else if name == "cookies" && matches!(p.type_ref, TypeRef::Named(_)) {
458 params.push(ParamInput::Cookies {
459 ty: p.type_ref.clone(),
460 });
461 }
462 }
464 let success = match success_of(h) {
465 Some(TypeRef::Unit(_)) | None => None,
466 Some(t) => Some(t.clone()),
467 };
468 Ok(RouteInput {
469 method: method.as_str().to_string(),
470 path: path.to_string(),
471 doc: h.documentation.as_ref().map(|d| d.text.trim().to_string()),
472 params,
473 success,
474 replies: replies_of(model, effective_json_options(sel.service.json.as_ref(), h))?,
475 })
476}
477
478fn unsupported(info: &ContextBoundaryInfo, h: &Handler) -> Result<(), String> {
480 if h.params
481 .iter()
482 .any(|p| p.name.name == "query" && matches!(p.type_ref, TypeRef::RequestQuery(_)))
483 {
484 return Err("a raw `query: RequestQuery` is not supported yet".to_string());
485 }
486 if h.params
487 .iter()
488 .any(|p| p.name.name == "cookies" && matches!(p.type_ref, TypeRef::RequestCookies(_)))
489 {
490 return Err("a raw `cookies: RequestCookies` is not supported yet".to_string());
491 }
492 if bynk_check::actors::signature_seam_for(h, &info.actors).is_some() {
493 return Err(
494 "the route is guarded by a request signature, which a client without the secret cannot make"
495 .to_string(),
496 );
497 }
498 Ok(())
499}
500
501fn body_kind(h: &Handler) -> BodyKind {
503 if h.annotations.iter().any(|a| a.name.name == "raw") {
504 return BodyKind::Raw {
505 content_type: h
506 .raw_content_type()
507 .filter(|ct| *ct != "*/*")
508 .map(str::to_string),
509 };
510 }
511 let note = |name: &str| h.annotations.iter().any(|a| a.name.name == name);
512 if note("multipart") {
513 BodyKind::Multipart
514 } else if note("form") {
515 BodyKind::Form
516 } else {
517 BodyKind::Json
518 }
519}
520
521fn success_of(h: &Handler) -> Option<&TypeRef> {
523 let t = match &h.return_type {
524 TypeRef::Effect(inner, _) => inner.as_ref(),
525 other => other,
526 };
527 match t {
528 TypeRef::HttpResult(inner, _) => Some(inner.as_ref()),
529 _ => None,
530 }
531}
532
533fn replies_of(model: &WireContractModel, _json: JsonOptions) -> Result<Vec<ReplyInput>, String> {
535 let mut out = Vec::new();
536 for resp in &model.responses {
537 if resp.origin == ResponseOrigin::DeclaredSuccess && !model.ok_reachable {
538 continue;
539 }
540 let payload = if let ResponseOrigin::BoundaryImplicit { .. } = &resp.origin {
541 match resp.variant.as_str() {
542 "StructuralMismatch" => ReplyPayload::BoundaryError,
543 "PayloadTooLarge" | "UnsupportedMediaType" => ReplyPayload::BoundaryRefusal,
544 _ => continue,
545 }
546 } else {
547 let Some(v) = http_variant(&resp.variant) else {
548 continue;
549 };
550 match v.payload {
551 HttpVariantPayload::Value => ReplyPayload::Value,
552 HttpVariantPayload::Message => ReplyPayload::Message,
553 HttpVariantPayload::Location => ReplyPayload::Location,
554 HttpVariantPayload::None => ReplyPayload::None,
555 HttpVariantPayload::Streamed => ReplyPayload::Events,
556 HttpVariantPayload::RawTagged => ReplyPayload::RawTagged,
557 HttpVariantPayload::Raw if resp.variant == "Raw" => ReplyPayload::RawEtag,
558 HttpVariantPayload::Raw
559 | HttpVariantPayload::RawStreamed
560 | HttpVariantPayload::RawError => ReplyPayload::Raw,
561 }
562 };
563 out.push(ReplyInput {
564 status: resp.status,
565 variant: resp.variant.clone(),
566 payload,
567 });
568 }
569 Ok(out)
570}