Skip to main content

bynk/
openapi.rs

1//! `bynk openapi` (#856) — an OpenAPI 3.1 document for a project's `from http`
2//! services, a lossless re-projection of facts the compiler already holds.
3//!
4//! Nothing here re-derives the boundary. Routes and params come from the
5//! retained service declarations; each type's shape comes from the shared
6//! wire-contract IR (`bynk_check::wire`, #855 DECISION C) that also drives the
7//! emitter's codecs and the editor's wire peek; and each route's response set
8//! is the peek's body-walked set (`bynk_ide::wire_contract`, DECISION B), so
9//! the spec cannot drift from either.
10//!
11//! # Decision A: refinements
12//!
13//! Every predicate a boundary type carries is one the codec re-validates, and
14//! every one has a JSON Schema equivalent (`minLength`, `minimum`, `pattern`,
15//! …). Cross-field predicates (`implies`) are agent invariants, never wire
16//! types, so none reaches this document. Each refined schema still carries the
17//! predicates as written in `x-bynk-refinements` and spells them out in its
18//! `description`, so a consumer reading only the extension, or only the prose,
19//! loses nothing.
20//!
21//! | Bynk                  | JSON Schema                                        |
22//! |-----------------------|----------------------------------------------------|
23//! | `NonEmpty`            | `minLength: 1`                                     |
24//! | `MinLength(n)`        | `minLength: n`                                     |
25//! | `MaxLength(n)`        | `maxLength: n`                                     |
26//! | `Length(n)`           | `minLength: n`, `maxLength: n`                     |
27//! | `Positive`            | `exclusiveMinimum: 0`                              |
28//! | `NonNegative`         | `minimum: 0`                                       |
29//! | `InRange(a, b)`       | `minimum: a`, `maximum: b`                         |
30//! | `IsoDate`             | `format: date`, `minLength: 10`, `maxLength: 10`    |
31//! | `Cron`                | `x-bynk-format: cron`, `minLength: 9`              |
32//! | `Matches("p")`        | `pattern: "^(?:p)$"` (the codec anchors the match) |
33
34use bynk_driver::emsg;
35use std::collections::{BTreeMap, BTreeSet, HashMap};
36use std::path::{Path, PathBuf};
37use std::process::ExitCode;
38
39use bynk_check::wire::{self, WireBody, WireInst, WireModel, WireRef, WireType};
40use bynk_ide::wire_contract::{
41    BoundaryKind, IrHttpMethod, ResponseOrigin, WireContractModel, http_result_inner,
42    real_context_count, wire_contract_for_service,
43};
44use bynk_ide::{AnalysisRoots, ContextBoundaryInfo, ProjectDiagnostics, SchemaLock};
45use bynk_model::{IrHandlerKind, lower_handler_kind_ir};
46use bynk_syntax::ast::{
47    BaseType, Handler, HttpVariantPayload, JsonOptions, PredKind, ServiceDecl, ServiceProtocol,
48    TypeDecl, TypeRef, effective_json_options, http_variant,
49};
50use bynk_syntax::error::Severity;
51use serde_json::{Map, Value, json};
52
53use crate::cli::OpenapiFormatArg;
54
55/// The OpenAPI version the document declares.
56pub const OPENAPI_VERSION: &str = "3.1.0";
57
58/// The component the `400` boundary rejection is described once as.
59const BOUNDARY_ERROR: &str = "BynkBoundaryError";
60
61/// What names the document: the project's manifest identity.
62#[derive(Debug, Clone)]
63pub struct Info {
64    pub title: String,
65    pub version: String,
66}
67
68/// Why a document could not be produced.
69#[derive(Debug)]
70pub enum Error {
71    /// The project has errors; the document would describe a program that does
72    /// not compile.
73    Invalid(Vec<String>),
74    /// `--service` names no `from http` service.
75    UnknownService { name: String, known: Vec<String> },
76    /// The project has no `from http` service.
77    NoHttpService,
78    /// Two selected services answer the same method and path.
79    DuplicateRoute { method: &'static str, path: String },
80}
81
82impl std::fmt::Display for Error {
83    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84        match self {
85            Error::Invalid(lines) => {
86                writeln!(f, "the project has errors; fix them first (`bynk check`):")?;
87                for l in lines {
88                    writeln!(f, "  {l}")?;
89                }
90                Ok(())
91            }
92            Error::UnknownService { name, known } if known.is_empty() => {
93                write!(f, "no `from http` service `{name}`; the project has none")
94            }
95            Error::UnknownService { name, known } => write!(
96                f,
97                "no `from http` service `{name}`; the project's are: {}",
98                known.join(", ")
99            ),
100            Error::NoHttpService => write!(f, "the project has no `from http` service"),
101            Error::DuplicateRoute { method, path } => write!(
102                f,
103                "more than one service answers `{method} {path}`; pass `--service` to pick one"
104            ),
105        }
106    }
107}
108
109impl std::error::Error for Error {}
110
111// ---------------------------------------------------------------------
112// Entry points
113// ---------------------------------------------------------------------
114
115/// `bynk openapi`: analyse the project at `root`, write the document.
116pub fn run(
117    root: &Path,
118    service: Option<&str>,
119    out: Option<&Path>,
120    format: Option<OpenapiFormatArg>,
121) -> ExitCode {
122    let analysis = analyse(root);
123    let doc = match document(&manifest_info(root), &analysis, service) {
124        Ok(d) => d,
125        Err(e) => {
126            emsg!("bynk: error: {e}");
127            return ExitCode::FAILURE;
128        }
129    };
130    let format = format.unwrap_or_else(|| match out.and_then(|p| p.extension()) {
131        Some(e) if e == "yaml" || e == "yml" => OpenapiFormatArg::Yaml,
132        _ => OpenapiFormatArg::Json,
133    });
134    let text = match format {
135        OpenapiFormatArg::Json => {
136            let mut s = serde_json::to_string_pretty(&doc).expect("a Value serialises");
137            s.push('\n');
138            s
139        }
140        OpenapiFormatArg::Yaml => to_yaml(&doc),
141    };
142    match out {
143        None => {
144            print!("{text}");
145            ExitCode::SUCCESS
146        }
147        Some(path) => match std::fs::write(path, text) {
148            Ok(()) => ExitCode::SUCCESS,
149            Err(e) => {
150                emsg!("bynk: error: cannot write {}: {e}", path.display());
151                ExitCode::FAILURE
152            }
153        },
154    }
155}
156
157/// #2685: the statuses each `from http` route of the project at `root` can
158/// answer — the response set `bynk openapi` documents, boundary-implicit
159/// statuses included — keyed `<context> <service> <METHOD> <path>`, the key the
160/// smoke runner's typed call names its route by. Empty when the project does
161/// not check: a smoke run then has nothing to compare an answer against, and
162/// says nothing.
163pub fn declared_statuses(root: &Path) -> BTreeMap<String, Vec<u16>> {
164    let analysis = analyse(root);
165    let mut out = BTreeMap::new();
166    if !errors_of(&analysis).is_empty() {
167        return out;
168    }
169    let context_count = real_context_count(&analysis.boundary_info, &analysis.unit_sources);
170    for (unit, ctx) in &analysis.boundary_info {
171        if !analysis.unit_sources.contains_key(unit) {
172            continue;
173        }
174        let expr_types = unit_expr_types(&analysis, unit);
175        for svc in ctx.services.values() {
176            // M-1's domain clause (ADR 0735, #2999 DECISION A): the project is
177            // certified, but `ProjectDiagnostics` carries no `TypedCommons`, so this
178            // consumer doesn't hold `bynk_model::lower_protocol_ir`'s input.
179            if !matches!(svc.protocol, ServiceProtocol::Http) {
180                continue;
181            }
182            for h in &svc.handlers {
183                if !matches!(lower_handler_kind_ir(&h.kind), IrHandlerKind::Http { .. }) {
184                    continue;
185                }
186                let Some(model) = wire_contract_for_service(
187                    unit,
188                    "",
189                    &svc.name.name,
190                    h,
191                    ctx,
192                    &expr_types,
193                    &analysis.ty_intern,
194                    context_count,
195                ) else {
196                    continue;
197                };
198                let BoundaryKind::Http { method, path } = &model.kind else {
199                    continue;
200                };
201                let mut statuses: Vec<u16> = model.responses.iter().map(|r| r.status).collect();
202                statuses.sort_unstable();
203                statuses.dedup();
204                // The key names the context, so a union happens only within one
205                // context (two services of one name, method and path), where it is
206                // the conservative set.
207                let key = format!("{unit} {} {} {path}", svc.name.name, method.as_str());
208                let entry: &mut Vec<u16> = out.entry(key).or_default();
209                entry.extend(statuses);
210                entry.sort_unstable();
211                entry.dedup();
212            }
213        }
214    }
215    out
216}
217
218/// The project's analysis from the files on disk — the round `bynk check` and
219/// the language server run.
220pub(crate) fn analyse(root: &Path) -> ProjectDiagnostics {
221    let roots = AnalysisRoots::Project(root.to_path_buf());
222    let mut content: HashMap<PathBuf, String> = HashMap::new();
223    let manifest = root.join("bynk.toml");
224    if let Ok(text) = std::fs::read_to_string(&manifest) {
225        content.insert(manifest, text);
226    }
227    for path in bynk_ide::discover_files(&roots, &content) {
228        if let Ok(text) = std::fs::read_to_string(&path) {
229            content.insert(path, text);
230        }
231    }
232    let lock = match std::fs::read_to_string(root.join("bynk.schema.lock")) {
233        Ok(text) => SchemaLock::On {
234            existing: Some(text),
235        },
236        Err(_) => SchemaLock::Off,
237    };
238    bynk_ide::diagnose_project_with(&roots, &content, &lock)
239}
240
241/// The document's `info` from `bynk.toml`'s `[project]` / `[package]`, falling
242/// back to the directory's name.
243fn manifest_info(root: &Path) -> Info {
244    let table: Option<toml::Table> = std::fs::read_to_string(root.join("bynk.toml"))
245        .ok()
246        .and_then(|t| t.parse().ok());
247    let field = |key: &str| {
248        let t = table.as_ref()?;
249        ["project", "package"]
250            .iter()
251            .find_map(|s| t.get(*s)?.get(key)?.as_str().map(str::to_string))
252    };
253    Info {
254        title: field("name").unwrap_or_else(|| {
255            root.file_name()
256                .map(|n| n.to_string_lossy().into_owned())
257                .unwrap_or_else(|| "bynk".to_string())
258        }),
259        version: field("version").unwrap_or_else(|| "0.0.0".to_string()),
260    }
261}
262
263// ---------------------------------------------------------------------
264// The document
265// ---------------------------------------------------------------------
266
267/// One `from http` service selected for the document.
268pub(crate) struct Selected<'a> {
269    pub unit: &'a str,
270    pub service: &'a ServiceDecl,
271    pub info: &'a ContextBoundaryInfo,
272}
273
274/// The `from http` services of `analysis` named by `want` (`Name` or
275/// `unit.Name`), every one when `want` is empty, ordered by unit and name. The
276/// selection `bynk openapi` and `bynk client` share.
277pub(crate) fn select_services<'a>(
278    analysis: &'a ProjectDiagnostics,
279    want: &[&str],
280) -> Result<Vec<Selected<'a>>, Error> {
281    let mut all: Vec<Selected> = Vec::new();
282    for (unit, ctx) in &analysis.boundary_info {
283        // A synthetic unit (the `bynk` capability surface) has no source.
284        if !analysis.unit_sources.contains_key(unit) {
285            continue;
286        }
287        for svc in ctx.services.values() {
288            // M-1's domain clause (ADR 0735, #2999 DECISION A): no `TypedCommons`
289            // here to lower the protocol from (see `declared_statuses`).
290            if matches!(svc.protocol, ServiceProtocol::Http) {
291                all.push(Selected {
292                    unit,
293                    service: svc,
294                    info: ctx,
295                });
296            }
297        }
298    }
299    all.sort_by(|a, b| (a.unit, &a.service.name.name).cmp(&(b.unit, &b.service.name.name)));
300    let known: Vec<String> = all.iter().map(|s| s.service.name.name.clone()).collect();
301    let matches = |s: &Selected, name: &str| {
302        s.service.name.name == name || format!("{}.{}", s.unit, s.service.name.name) == name
303    };
304    for name in want {
305        if !all.iter().any(|s| matches(s, name)) {
306            return Err(Error::UnknownService {
307                name: name.to_string(),
308                known,
309            });
310        }
311    }
312    if all.is_empty() {
313        return Err(Error::NoHttpService);
314    }
315    Ok(all
316        .into_iter()
317        .filter(|s| want.is_empty() || want.iter().any(|n| matches(s, n)))
318        .collect())
319}
320
321/// Build the OpenAPI document for `analysis`' `from http` services — every
322/// one, or only `service` (matched as `Name` or `unit.Name`).
323pub fn document(
324    info: &Info,
325    analysis: &ProjectDiagnostics,
326    service: Option<&str>,
327) -> Result<Value, Error> {
328    let service: Vec<&str> = service.into_iter().collect();
329    let errors = errors_of(analysis);
330    if !errors.is_empty() {
331        return Err(Error::Invalid(errors));
332    }
333
334    let selected = select_services(analysis, &service)?;
335
336    let context_count = real_context_count(&analysis.boundary_info, &analysis.unit_sources);
337    let mut models: Vec<(&Selected, &Handler, WireContractModel)> = Vec::new();
338    for sel in &selected {
339        let expr_types = unit_expr_types(analysis, sel.unit);
340        for h in &sel.service.handlers {
341            if !matches!(lower_handler_kind_ir(&h.kind), IrHandlerKind::Http { .. }) {
342                continue;
343            }
344            if let Some(m) = wire_contract_for_service(
345                sel.unit,
346                "",
347                &sel.service.name.name,
348                h,
349                sel.info,
350                &expr_types,
351                &analysis.ty_intern,
352                context_count,
353            ) {
354                models.push((sel, h, m));
355            }
356        }
357    }
358
359    let names = SchemaNames::new(&models);
360    let mut components = Components::default();
361    let mut paths: BTreeMap<String, Map<String, Value>> = BTreeMap::new();
362    let mut routes: BTreeSet<(String, String)> = BTreeSet::new();
363
364    for (sel, handler, model) in &models {
365        let BoundaryKind::Http { method, path } = &model.kind else {
366            continue;
367        };
368        let r = Renderer {
369            unit: sel.unit,
370            types: &sel.info.types,
371            model: &model.boundary,
372            names: &names,
373            plain: effective_json_options(sel.service.json.as_ref(), handler) == JsonOptions::Plain,
374        };
375        let op = operation(&r, &mut components, sel, handler, model, *method, path);
376        // OpenAPI treats templated paths that differ only in parameter names
377        // (`/a/{id}`, `/a/{key}`) as the same path.
378        let shape = openapi_path(path)
379            .split('/')
380            .map(|s| if s.starts_with('{') { "{}" } else { s })
381            .collect::<Vec<_>>()
382            .join("/");
383        let item = paths.entry(openapi_path(path)).or_default();
384        let key = method.as_str().to_lowercase();
385        if !routes.insert((key.clone(), shape)) || item.insert(key, op).is_some() {
386            return Err(Error::DuplicateRoute {
387                method: method.as_str(),
388                path: path.clone(),
389            });
390        }
391    }
392
393    let tags: Vec<Value> = selected
394        .iter()
395        .map(|s| {
396            let mut t = Map::new();
397            t.insert("name".into(), json!(s.service.name.name));
398            if let Some(d) = &s.service.documentation {
399                t.insert("description".into(), json!(d.text.trim()));
400            }
401            Value::Object(t)
402        })
403        .collect();
404
405    let mut doc = Map::new();
406    doc.insert("openapi".into(), json!(OPENAPI_VERSION));
407    doc.insert(
408        "info".into(),
409        json!({ "title": info.title, "version": info.version }),
410    );
411    doc.insert("tags".into(), Value::Array(tags));
412    doc.insert(
413        "paths".into(),
414        Value::Object(
415            paths
416                .into_iter()
417                .map(|(p, item)| (p, Value::Object(item)))
418                .collect(),
419        ),
420    );
421    if !components.schemas.is_empty() || !components.security.is_empty() {
422        let mut c = Map::new();
423        if !components.schemas.is_empty() {
424            c.insert(
425                "schemas".into(),
426                Value::Object(components.schemas.into_iter().collect()),
427            );
428        }
429        if !components.security.is_empty() {
430            c.insert(
431                "securitySchemes".into(),
432                Value::Object(components.security.into_iter().collect()),
433            );
434        }
435        doc.insert("components".into(), Value::Object(c));
436    }
437    Ok(sorted(Value::Object(doc)))
438}
439
440/// Rebuild `v` with every object's keys in sorted order. `serde_json`'s map is
441/// key-sorted unless some crate in the build enables `preserve_order` (none in
442/// this workspace does), and the document must not depend on which crates
443/// were built beside this one.
444fn sorted(v: Value) -> Value {
445    match v {
446        Value::Object(m) => {
447            let mut entries: Vec<(String, Value)> = m.into_iter().collect();
448            entries.sort_by(|a, b| a.0.cmp(&b.0));
449            Value::Object(entries.into_iter().map(|(k, v)| (k, sorted(v))).collect())
450        }
451        Value::Array(a) => Value::Array(a.into_iter().map(sorted).collect()),
452        other => other,
453    }
454}
455
456/// `path:line: message` for each error the analysis holds, cheapest first.
457pub(crate) fn errors_of(analysis: &ProjectDiagnostics) -> Vec<String> {
458    let mut out = Vec::new();
459    for f in &analysis.files {
460        for d in &f.diagnostics {
461            if d.severity == Severity::Error {
462                let line = f
463                    .text
464                    .get(..d.error.span.start)
465                    .unwrap_or("")
466                    .matches('\n')
467                    .count()
468                    + 1;
469                out.push(format!(
470                    "{}:{line}: {}",
471                    f.source_path.to_string_lossy().replace('\\', "/"),
472                    d.error.message
473                ));
474            }
475        }
476    }
477    for d in &analysis.unattributed {
478        if d.severity == Severity::Error {
479            out.push(d.error.message.clone());
480        }
481    }
482    out
483}
484
485/// Every file of `unit`'s checked expression types — the response walk
486/// filters by the handler's own file id, so the union is safe.
487fn unit_expr_types(
488    analysis: &ProjectDiagnostics,
489    unit: &str,
490) -> Vec<(bynk_syntax::span::Span, bynk_check::checker::TyId)> {
491    analysis
492        .unit_sources
493        .get(unit)
494        .into_iter()
495        .flatten()
496        .filter_map(|p| analysis.expr_types.get(p))
497        .flatten()
498        .cloned()
499        .collect()
500}
501
502/// `/check/:client` → `/check/{client}`.
503fn openapi_path(path: &str) -> String {
504    path.split('/')
505        .map(|seg| match seg.strip_prefix(':') {
506            Some(name) => format!("{{{name}}}"),
507            None => seg.to_string(),
508        })
509        .collect::<Vec<_>>()
510        .join("/")
511}
512
513// ---------------------------------------------------------------------
514// Operations
515// ---------------------------------------------------------------------
516
517fn operation(
518    r: &Renderer,
519    components: &mut Components,
520    sel: &Selected,
521    handler: &Handler,
522    model: &WireContractModel,
523    method: IrHttpMethod,
524    path: &str,
525) -> Value {
526    let mut op = Map::new();
527    op.insert("tags".into(), json!([sel.service.name.name]));
528    op.insert(
529        "operationId".into(),
530        json!(operation_id(&sel.service.name.name, method, path)),
531    );
532    if let Some(d) = &handler.documentation {
533        let text = d.text.trim();
534        if let Some(first) = text.lines().next() {
535            op.insert("summary".into(), json!(first.trim()));
536        }
537        op.insert("description".into(), json!(text));
538    }
539
540    let in_path: BTreeSet<&str> = path
541        .split('/')
542        .filter_map(|s| s.strip_prefix(':'))
543        .collect();
544    let mut parameters = Vec::new();
545    let mut request_body = None;
546    // #2858: plain JSON is a property of the response body only. A request is
547    // decoded by the lenient decoder whichever mode the route answers in, so its
548    // schemas stay the tagged ones.
549    let request = Renderer { plain: false, ..*r };
550    let r_resp = r;
551    let r = &request;
552    for p in &handler.params {
553        let name = p.name.name.as_str();
554        if name == "body" {
555            request_body = Some(request_body_of(r, components, handler, &p.type_ref));
556        } else if in_path.contains(name) {
557            parameters.push(json!({
558                "name": name,
559                "in": "path",
560                "required": true,
561                "schema": r.parameter_schema(components, &p.type_ref),
562            }));
563        } else if name == "query" {
564            // #2854: a typed `query` record is one `in: query` parameter per
565            // field; the raw `RequestQuery` view declares none.
566            parameters.extend(query_parameters(r, components, &p.type_ref, "query"));
567        } else if name == "cookies" {
568            // #3277: a typed `cookies` record is one `in: cookie` parameter per field.
569            parameters.extend(query_parameters(r, components, &p.type_ref, "cookie"));
570        }
571        // Any other param is a `headers` (the request's headers, read-only and
572        // untyped here); the checker admits no other.
573    }
574    if !parameters.is_empty() {
575        op.insert("parameters".into(), Value::Array(parameters));
576    }
577    if let Some(b) = request_body {
578        op.insert("requestBody".into(), b);
579    }
580
581    let mut responses = responses_of(r_resp, components, handler, model);
582    if let Some(seam) = bynk_check::actors::signed_cookie_seam_for(handler, &sel.info.actors) {
583        signed_cookie_security(&mut op, &mut responses, components, &seam, method);
584    }
585    op.insert("responses".into(), responses);
586    Value::Object(op)
587}
588
589/// #3386: a route guarded by a `SignedCookie` actor needs that actor's cookie: an `apiKey` security
590/// scheme `in: cookie`, named after the cookie, with the seam's refusals documented: `401` for a
591/// missing, forged or expired cookie and, on a state-changing method, `403` for a cross-site request.
592fn signed_cookie_security(
593    op: &mut Map<String, Value>,
594    responses: &mut Value,
595    components: &mut Components,
596    seam: &bynk_check::actors::SignedCookieSeam,
597    method: IrHttpMethod,
598) {
599    components.security.entry(seam.actor.clone()).or_insert_with(|| {
600        json!({
601            "type": "apiKey",
602            "in": "cookie",
603            "name": seam.cookie,
604            "description": format!(
605                "A session cookie the `{}` actor issues and verifies. It is signed, not encrypted, and \
606                 expires after {} seconds.",
607                seam.actor, seam.ttl_secs
608            ),
609        })
610    });
611    op.insert("security".into(), json!([{ (seam.actor.clone()): [] }]));
612    let mut refusals = vec![(
613        "401",
614        "No session cookie, or one that is forged, expired or for another actor.",
615    )];
616    if !matches!(method, IrHttpMethod::Get) {
617        refusals.push((
618            "403",
619            "A cross-site request: its `Sec-Fetch-Site` is not `same-origin` and its `Origin` is not one of the service's credentialed CORS origins.",
620        ));
621    }
622    if let Value::Object(map) = responses {
623        for (status, description) in refusals {
624            map.entry(status.to_string())
625                .or_insert_with(|| json!({ "description": description }));
626        }
627    }
628}
629
630/// #2854: the `in: query` parameters of a handler's typed `query` record, one per
631/// field. A field is required unless it is an `Option` or carries a default; a
632/// `List` field is an array whose items repeat the key (`?tag=a&tag=b`, OpenAPI's
633/// default `form` style with `explode`). Refinements reach the schema as they do
634/// for a path parameter. The raw `RequestQuery` view is not a record, so it
635/// declares none.
636fn query_parameters(
637    r: &Renderer,
638    components: &mut Components,
639    ty: &TypeRef,
640    location: &str,
641) -> Vec<Value> {
642    let TypeRef::Named(id) = ty else {
643        return Vec::new();
644    };
645    let Some(bynk_syntax::ast::TypeBody::Record(record)) = r.types.get(&id.name).map(|t| &t.body)
646    else {
647        return Vec::new();
648    };
649    record
650        .fields
651        .iter()
652        .map(|f| {
653            let (inner, list, optional) = match &f.type_ref {
654                TypeRef::List(inner, _) => (inner.as_ref(), true, false),
655                TypeRef::Option(inner, _) => (inner.as_ref(), false, true),
656                other => (other, false, false),
657            };
658            let item = r.parameter_schema(components, inner);
659            let schema = if list {
660                json!({ "type": "array", "items": item })
661            } else {
662                item
663            };
664            let mut param = Map::new();
665            // #3343: a field renamed by `@name` is documented under its wire name.
666            let name = f.wire_name().unwrap_or_else(|| f.name.name.clone());
667            param.insert("name".into(), json!(name));
668            param.insert("in".into(), json!(location));
669            param.insert("required".into(), json!(!optional && f.init.is_none()));
670            if let Some(d) = &f.documentation {
671                param.insert("description".into(), json!(d.text.trim()));
672            }
673            param.insert("schema".into(), schema);
674            Value::Object(param)
675        })
676        .collect()
677}
678
679/// `api` + `GET` + `/check/:client` → `api_get_check_client`.
680fn operation_id(service: &str, method: IrHttpMethod, path: &str) -> String {
681    let mut id = format!("{service}_{}", method.as_str().to_lowercase());
682    for seg in path.split('/').filter(|s| !s.is_empty()) {
683        id.push('_');
684        id.extend(
685            seg.trim_start_matches(':')
686                .chars()
687                .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }),
688        );
689    }
690    id
691}
692
693fn request_body_of(
694    r: &Renderer,
695    components: &mut Components,
696    handler: &Handler,
697    ty: &TypeRef,
698) -> Value {
699    if let Some(ct) = handler.raw_content_type() {
700        return json!({
701            "required": true,
702            "content": { ct: { "schema": { "type": "string", "format": "binary" } } },
703        });
704    }
705    let shape = wire::wire_ref(ty, r.types);
706    // #3276: a `@form` route's body is the same record under the form media type.
707    let media = if handler
708        .annotations
709        .iter()
710        .any(|a| a.name.name == "multipart")
711    {
712        "multipart/form-data"
713    } else if handler.annotations.iter().any(|a| a.name.name == "form") {
714        "application/x-www-form-urlencoded"
715    } else {
716        "application/json"
717    };
718    // #3343: a form body with a field renamed by `@name` documents the wire keys, so
719    // the schema is written out rather than referencing the record's own component.
720    let schema = if media == "application/json" {
721        None
722    } else {
723        renamed_form_schema(r, components, ty)
724    }
725    .unwrap_or_else(|| r.ref_schema(components, &shape));
726    json!({
727        "required": true,
728        "content": { media: { "schema": schema } },
729    })
730}
731
732/// #3343: the object schema of a form or multipart body record keyed by each field's
733/// wire name, when at least one field is renamed by `@name`; `None` otherwise.
734fn renamed_form_schema(r: &Renderer, components: &mut Components, ty: &TypeRef) -> Option<Value> {
735    let TypeRef::Named(id) = ty else {
736        return None;
737    };
738    let bynk_syntax::ast::TypeBody::Record(record) = &r.types.get(&id.name)?.body else {
739        return None;
740    };
741    if record.fields.iter().all(|f| f.wire_name().is_none()) {
742        return None;
743    }
744    let mut properties = Map::new();
745    let mut required = Vec::new();
746    for f in &record.fields {
747        let (inner, list, optional) = match &f.type_ref {
748            TypeRef::List(inner, _) => (inner.as_ref(), true, false),
749            TypeRef::Option(inner, _) => (inner.as_ref(), false, true),
750            other => (other, false, false),
751        };
752        let item = match inner {
753            TypeRef::Named(n) if n.name == "File" => {
754                json!({ "type": "string", "format": "binary" })
755            }
756            other => r.parameter_schema(components, other),
757        };
758        let mut schema = if list {
759            json!({ "type": "array", "items": item })
760        } else {
761            item
762        };
763        // The component schema carries a field's doc as its description; so does this.
764        if let (Some(d), Some(o)) = (&f.documentation, schema.as_object_mut()) {
765            o.insert("description".into(), json!(d.text.trim()));
766        }
767        let name = f.wire_name().unwrap_or_else(|| f.name.name.clone());
768        if !optional && !list && f.init.is_none() {
769            required.push(json!(name));
770        }
771        properties.insert(name, schema);
772    }
773    let mut schema = Map::new();
774    schema.insert("type".into(), json!("object"));
775    schema.insert("properties".into(), Value::Object(properties));
776    if !required.is_empty() {
777        schema.insert("required".into(), Value::Array(required));
778    }
779    Some(Value::Object(schema))
780}
781
782fn responses_of(
783    r: &Renderer,
784    components: &mut Components,
785    handler: &Handler,
786    model: &WireContractModel,
787) -> Value {
788    let success = http_result_inner(&handler.return_type);
789    /// One status's accumulated descriptions, bodies and headers.
790    #[derive(Default)]
791    struct Entry {
792        descriptions: Vec<String>,
793        /// `(media type, schema)`, deduplicated.
794        bodies: Vec<(String, Value)>,
795        headers: Map<String, Value>,
796    }
797    let mut by_status: BTreeMap<u16, Entry> = BTreeMap::new();
798    for resp in &model.responses {
799        // The declared success is listed whether or not the body returns it; the
800        // document lists only what the handler can answer (Decision B).
801        if resp.origin == ResponseOrigin::DeclaredSuccess && !model.ok_reachable {
802            continue;
803        }
804        let e = by_status.entry(resp.status).or_default();
805        let mut describe = |d: String| {
806            if !e.descriptions.contains(&d) {
807                e.descriptions.push(d);
808            }
809        };
810        let body = |media: &str, schema: Value, e: &mut Entry| {
811            if !e.bodies.iter().any(|(m, s)| m == media && *s == schema) {
812                e.bodies.push((media.to_string(), schema));
813            }
814        };
815        if let ResponseOrigin::BoundaryImplicit { why } = &resp.origin {
816            describe(format!("{} — {why}", resp.variant));
817            match resp.variant.as_str() {
818                "StructuralMismatch" => {
819                    components.boundary_error();
820                    body(
821                        "application/json",
822                        json!({ "$ref": format!("#/components/schemas/{BOUNDARY_ERROR}") }),
823                        e,
824                    );
825                }
826                "PayloadTooLarge" | "UnsupportedMediaType" => body(
827                    "application/json",
828                    json!({
829                        "type": "object",
830                        "required": ["kind", "details"],
831                        "properties": {
832                            "kind": { "const": resp.variant },
833                            "details": { "type": "string" },
834                        },
835                    }),
836                    e,
837                ),
838                _ => {}
839            }
840            continue;
841        }
842        describe(resp.variant.clone());
843        let Some(v) = http_variant(&resp.variant) else {
844            continue;
845        };
846        match v.payload {
847            HttpVariantPayload::Value => {
848                if let Some(t) = success
849                    && !matches!(t, TypeRef::Unit(_))
850                {
851                    let shape = wire::wire_ref(t, r.types);
852                    body("application/json", r.ref_schema(components, &shape), e);
853                }
854            }
855            HttpVariantPayload::Message => body(
856                "application/json",
857                json!({
858                    "type": "object",
859                    "required": ["error"],
860                    "properties": { "error": { "type": "string" } },
861                }),
862                e,
863            ),
864            HttpVariantPayload::Location => {
865                e.headers.insert(
866                    "Location".into(),
867                    json!({ "required": true, "schema": { "type": "string" } }),
868                );
869            }
870            HttpVariantPayload::Streamed => {
871                body("text/event-stream", json!({ "type": "string" }), e);
872            }
873            HttpVariantPayload::Raw
874            | HttpVariantPayload::RawTagged
875            | HttpVariantPayload::RawStreamed
876            | HttpVariantPayload::RawError => {
877                // Author-owned bytes under an author-chosen media type; no codec.
878                body("*/*", json!({ "type": "string", "format": "binary" }), e);
879                if v.payload == HttpVariantPayload::RawTagged {
880                    e.headers.insert(
881                        "ETag".into(),
882                        json!({ "required": true, "schema": { "type": "string" } }),
883                    );
884                }
885            }
886            HttpVariantPayload::None => {}
887        }
888    }
889
890    let mut out = Map::new();
891    for (status, e) in by_status {
892        let mut resp = Map::new();
893        resp.insert("description".into(), json!(e.descriptions.join("; ")));
894        if !e.headers.is_empty() {
895            resp.insert("headers".into(), Value::Object(e.headers));
896        }
897        if !e.bodies.is_empty() {
898            let mut by_media: BTreeMap<String, Vec<Value>> = BTreeMap::new();
899            for (m, s) in e.bodies {
900                by_media.entry(m).or_default().push(s);
901            }
902            let content: Map<String, Value> = by_media
903                .into_iter()
904                .map(|(m, mut schemas)| {
905                    let schema = if schemas.len() == 1 {
906                        schemas.remove(0)
907                    } else {
908                        json!({ "oneOf": schemas })
909                    };
910                    (m, json!({ "schema": schema }))
911                })
912                .collect();
913            resp.insert("content".into(), Value::Object(content));
914        }
915        out.insert(status.to_string(), Value::Object(resp));
916    }
917    Value::Object(out)
918}
919
920// ---------------------------------------------------------------------
921// Schemas
922// ---------------------------------------------------------------------
923
924/// The `components/schemas` collected while rendering.
925#[derive(Default)]
926struct Components {
927    schemas: BTreeMap<String, Value>,
928    /// #3386: the `components/securitySchemes`, by actor name.
929    security: BTreeMap<String, Value>,
930}
931
932impl Components {
933    /// Insert once: a second request for the same name is the same type.
934    fn put(&mut self, name: String, make: impl FnOnce() -> Value) {
935        self.schemas.entry(name).or_insert_with(make);
936    }
937
938    /// The `400` body the boundary answers a malformed or invalid request with
939    /// (`runtime/boundary.ts`'s `BoundaryError`, minus the caller-side
940    /// `Transport`).
941    fn boundary_error(&mut self) {
942        self.put(BOUNDARY_ERROR.to_string(), || {
943            json!({
944                "description": "A request the boundary rejected: malformed JSON, a value of the \
945                                wrong shape, or one that violates a refinement.",
946                "oneOf": [
947                    {
948                        "type": "object",
949                        "required": ["kind", "details"],
950                        "properties": {
951                            "kind": { "const": "MalformedJson" },
952                            "details": { "type": "string" },
953                        },
954                    },
955                    {
956                        "type": "object",
957                        "required": ["kind", "path", "expected", "actual"],
958                        "properties": {
959                            "kind": { "const": "StructuralMismatch" },
960                            "path": { "type": "string" },
961                            "expected": { "type": "string" },
962                            "actual": { "type": "string" },
963                        },
964                    },
965                    {
966                        "type": "object",
967                        "required": ["kind", "path", "violation"],
968                        "properties": {
969                            "kind": { "const": "RefinementViolation" },
970                            "path": { "type": "string" },
971                            "violation": { "type": "object" },
972                        },
973                    },
974                ],
975            })
976        });
977    }
978}
979
980/// The component name each `(unit, type)` renders under: the bare name, unless
981/// two units declare *different* types of that name, in which case both are
982/// qualified by their unit (`orders.Money`, `billing.Money`).
983struct SchemaNames {
984    colliding: BTreeSet<String>,
985    /// #2858: names rendered by both a tagged and a plain-JSON route. A plain
986    /// route's copy writes its `Option`s as nullable, so it is a distinct
987    /// component, suffixed `.plain`; the tagged copy keeps the bare name.
988    both_modes: BTreeSet<String>,
989}
990
991impl SchemaNames {
992    fn new(models: &[(&Selected, &Handler, WireContractModel)]) -> Self {
993        // component name → the distinct declarations carrying it. A generic
994        // instantiation's name is its codec key (`Page_Item`), and its identity
995        // is the generic's declaration plus each argument's.
996        let mut seen: HashMap<String, BTreeSet<String>> = HashMap::new();
997        let mut modes: HashMap<String, BTreeSet<bool>> = HashMap::new();
998        for (sel, h, model) in models {
999            let plain = effective_json_options(sel.service.json.as_ref(), h) == JsonOptions::Plain;
1000            for n in model
1001                .boundary
1002                .types
1003                .iter()
1004                .map(|t| t.name.clone())
1005                .chain(model.boundary.instantiations.iter().map(|i| i.ts_name()))
1006            {
1007                let m = modes.entry(n).or_default();
1008                m.insert(plain);
1009                // A plain route's request body is rendered tagged, so a type it
1010                // shares between request and response needs both renderings.
1011                if plain && h.params.iter().any(|p| p.name.name == "body") {
1012                    m.insert(false);
1013                }
1014            }
1015            let decl_id = |name: &str| {
1016                sel.info
1017                    .types
1018                    .get(name)
1019                    .map(|d| format!("{}:{}", d.span.file.0, d.span.start))
1020                    .unwrap_or_default()
1021            };
1022            for t in &model.boundary.types {
1023                seen.entry(t.name.clone())
1024                    .or_default()
1025                    .insert(decl_id(&t.name));
1026            }
1027            for i in &model.boundary.instantiations {
1028                if let WireInst::RecordInst { name, args } | WireInst::SumInst { name, args } = i {
1029                    let mut id = decl_id(name);
1030                    for a in args {
1031                        id.push('|');
1032                        id.push_str(&wire::codec_suffix(a));
1033                        if let TypeRef::Named(n) = a {
1034                            id.push('@');
1035                            id.push_str(&decl_id(&n.name));
1036                        }
1037                    }
1038                    seen.entry(i.ts_name()).or_default().insert(id);
1039                }
1040            }
1041        }
1042        SchemaNames {
1043            colliding: seen
1044                .into_iter()
1045                .filter(|(_, decls)| decls.len() > 1)
1046                .map(|(n, _)| n)
1047                .collect(),
1048            both_modes: modes
1049                .into_iter()
1050                .filter(|(_, m)| m.len() > 1)
1051                .map(|(n, _)| n)
1052                .collect(),
1053        }
1054    }
1055
1056    fn of(&self, unit: &str, name: &str, plain: bool) -> String {
1057        let base = if self.colliding.contains(name) {
1058            format!("{unit}.{name}")
1059        } else {
1060            name.to_string()
1061        };
1062        if plain && self.both_modes.contains(name) {
1063            format!("{base}.plain")
1064        } else {
1065            base
1066        }
1067    }
1068}
1069
1070/// Renders one handler's boundary types as JSON Schema.
1071#[derive(Clone, Copy)]
1072struct Renderer<'a> {
1073    unit: &'a str,
1074    types: &'a HashMap<String, std::sync::Arc<TypeDecl>>,
1075    model: &'a WireModel,
1076    names: &'a SchemaNames,
1077    /// #2858: the route renders its `Option`s as plain JSON (`U` or `null`).
1078    plain: bool,
1079}
1080
1081impl Renderer<'_> {
1082    fn component_ref(&self, name: &str) -> Value {
1083        json!({ "$ref": format!("#/components/schemas/{}", self.names.of(self.unit, name, self.plain)) })
1084    }
1085
1086    /// A path parameter's schema. A refined scalar is inlined so the
1087    /// parameter itself carries its constraints (`minLength: 1`), not only a
1088    /// reference to a component that does.
1089    fn parameter_schema(&self, components: &mut Components, ty: &TypeRef) -> Value {
1090        let shape = wire::wire_ref(ty, self.types);
1091        if let WireRef::Named { name } = &shape
1092            && let Some(t) = self.model.types.iter().find(|t| &t.name == name)
1093            && matches!(t.body, WireBody::Scalar(_))
1094        {
1095            // Still register the component, so the document names the type.
1096            self.ref_schema(components, &shape);
1097            return self.type_schema(components, t);
1098        }
1099        self.ref_schema(components, &shape)
1100    }
1101
1102    /// The schema for one occurrence of a type.
1103    fn ref_schema(&self, components: &mut Components, r: &WireRef) -> Value {
1104        match r {
1105            WireRef::Base { base, .. } => Value::Object(base_schema(*base)),
1106            WireRef::Bytes => Value::Object(base_schema(BaseType::Bytes)),
1107            WireRef::Decimal => Value::Object(base_schema(BaseType::Decimal)),
1108            WireRef::Named { name } => {
1109                if let Some(t) = self.model.types.iter().find(|t| &t.name == name) {
1110                    let n = self.names.of(self.unit, name, self.plain);
1111                    // Reserve before rendering so a self-referential type ends.
1112                    if !components.schemas.contains_key(&n) {
1113                        components.schemas.insert(n.clone(), Value::Null);
1114                        let v = self.type_schema(components, t);
1115                        components.schemas.insert(n, v);
1116                    }
1117                }
1118                self.component_ref(name)
1119            }
1120            WireRef::Inst { key } => self.inst_schema(components, key),
1121            WireRef::Unit => json!({ "type": "null" }),
1122            WireRef::Unchecked { .. } => json!({}),
1123        }
1124    }
1125
1126    fn type_schema(&self, components: &mut Components, t: &WireType) -> Value {
1127        let doc = self
1128            .types
1129            .get(&t.name)
1130            .and_then(|d| d.documentation.as_ref())
1131            .map(|d| d.text.trim().to_string());
1132        let mut s = match &t.body {
1133            WireBody::Scalar(sc) => {
1134                let mut s = base_schema(sc.base);
1135                if sc.opaque {
1136                    s.insert("x-bynk-opaque".into(), json!(true));
1137                }
1138                refine(&mut s, &sc.predicates);
1139                s
1140            }
1141            WireBody::Record { fields } => {
1142                let mut props = Map::new();
1143                let mut required = Vec::new();
1144                for f in fields {
1145                    let mut fs = match self.ref_schema(components, &f.shape) {
1146                        Value::Object(m) => m,
1147                        other => Map::from_iter([("allOf".to_string(), json!([other]))]),
1148                    };
1149                    refine(&mut fs, &f.predicates);
1150                    props.insert(f.name.clone(), Value::Object(fs));
1151                    if f.default.is_none() {
1152                        required.push(json!(f.name));
1153                    }
1154                }
1155                let mut s = Map::new();
1156                s.insert("type".into(), json!("object"));
1157                s.insert("properties".into(), Value::Object(props));
1158                s.insert("required".into(), Value::Array(required));
1159                s
1160            }
1161            WireBody::Sum(sum) => {
1162                let variants: Vec<Value> = sum
1163                    .variants
1164                    .iter()
1165                    .map(|v| {
1166                        let fields: Vec<(String, Value, bool)> = v
1167                            .payload
1168                            .iter()
1169                            .map(|f| {
1170                                let mut fs = match self.ref_schema(components, &f.shape) {
1171                                    Value::Object(m) => m,
1172                                    other => {
1173                                        Map::from_iter([("allOf".to_string(), json!([other]))])
1174                                    }
1175                                };
1176                                refine(&mut fs, &f.predicates);
1177                                (f.name.clone(), Value::Object(fs), f.default.is_none())
1178                            })
1179                            .collect();
1180                        variant_schema(sum.wire_discriminant, &v.name, fields)
1181                    })
1182                    .collect();
1183                Map::from_iter([("oneOf".to_string(), Value::Array(variants))])
1184            }
1185        };
1186        if let Some(doc) = doc {
1187            let d = match s.remove("description") {
1188                Some(Value::String(r)) => format!("{doc}\n\n{r}"),
1189                _ => doc,
1190            };
1191            s.insert("description".into(), json!(d));
1192        }
1193        Value::Object(s)
1194    }
1195
1196    fn inst_schema(&self, components: &mut Components, key: &str) -> Value {
1197        let Some(inst) = self
1198            .model
1199            .instantiations
1200            .iter()
1201            .find(|i| i.ts_name() == key)
1202        else {
1203            return json!({});
1204        };
1205        let shape = |t: &TypeRef| wire::wire_ref(t, self.types);
1206        match inst {
1207            WireInst::ListInst { elem } => {
1208                json!({ "type": "array", "items": self.ref_schema(components, &shape(elem)) })
1209            }
1210            // K6a (#2596): a JSON array, insertion-ordered, without duplicates.
1211            WireInst::SetInst { elem } => json!({
1212                "type": "array",
1213                "items": self.ref_schema(components, &shape(elem)),
1214                "uniqueItems": true,
1215            }),
1216            // Entries array, insertion-ordered: `[[k, v], …]`.
1217            WireInst::MapInst { key, val } => json!({
1218                "type": "array",
1219                "items": {
1220                    "type": "array",
1221                    "prefixItems": [
1222                        self.ref_schema(components, &shape(key)),
1223                        self.ref_schema(components, &shape(val)),
1224                    ],
1225                    "minItems": 2,
1226                    "maxItems": 2,
1227                },
1228            }),
1229            WireInst::OptionInst { inner } => {
1230                let v = self.ref_schema(components, &shape(inner));
1231                // #2858: a plain route writes `Some(u)` as `u` and `None` as `null`.
1232                if self.plain {
1233                    return json!({ "anyOf": [v, { "type": "null" }] });
1234                }
1235                json!({ "oneOf": [
1236                    variant_schema(wire::WIRE_DISCRIMINANT, "Some", vec![("value".into(), v, true)]),
1237                    variant_schema(wire::WIRE_DISCRIMINANT, "None", vec![]),
1238                ]})
1239            }
1240            WireInst::ResultInst { ok, err } => {
1241                let o = self.ref_schema(components, &shape(ok));
1242                let e = self.ref_schema(components, &shape(err));
1243                json!({ "oneOf": [
1244                    variant_schema(wire::WIRE_DISCRIMINANT, "Ok", vec![("value".into(), o, true)]),
1245                    variant_schema(wire::WIRE_DISCRIMINANT, "Err", vec![("error".into(), e, true)]),
1246                ]})
1247            }
1248            WireInst::RecordInst { name, args } => {
1249                let n = self.names.of(self.unit, key, self.plain);
1250                if let Some(fields) = wire::record_inst_fields(name, args, self.types) {
1251                    // #2607 (Decision I): a defaulted field of a generic record
1252                    // is optional at every instantiation, as in a plain one.
1253                    let defaulted: std::collections::HashSet<&str> =
1254                        match self.types.get(name.as_str()).map(|d| &d.body) {
1255                            Some(bynk_syntax::ast::TypeBody::Record(r)) => r
1256                                .fields
1257                                .iter()
1258                                .filter(|f| f.init.is_some())
1259                                .map(|f| f.name.name.as_str())
1260                                .collect(),
1261                            _ => std::collections::HashSet::new(),
1262                        };
1263                    let mut props = Map::new();
1264                    let mut required = Vec::new();
1265                    for (fname, ty) in &fields {
1266                        props.insert(fname.clone(), self.ref_schema(components, &shape(ty)));
1267                        if !defaulted.contains(fname.as_str()) {
1268                            required.push(json!(fname));
1269                        }
1270                    }
1271                    components.put(
1272                        n.clone(),
1273                        || json!({ "type": "object", "properties": props, "required": required }),
1274                    );
1275                }
1276                json!({ "$ref": format!("#/components/schemas/{n}") })
1277            }
1278            WireInst::SumInst { name, args } => {
1279                let n = self.names.of(self.unit, key, self.plain);
1280                if let Some(variants) = wire::sum_inst_variants(name, args, self.types) {
1281                    let vs: Vec<Value> = variants
1282                        .iter()
1283                        .map(|(vname, fields)| {
1284                            let fields = fields
1285                                .iter()
1286                                .map(|(f, t)| {
1287                                    (f.clone(), self.ref_schema(components, &shape(t)), true)
1288                                })
1289                                .collect();
1290                            variant_schema(wire::WIRE_DISCRIMINANT, vname, fields)
1291                        })
1292                        .collect();
1293                    components.put(n.clone(), || json!({ "oneOf": vs }));
1294                }
1295                json!({ "$ref": format!("#/components/schemas/{n}") })
1296            }
1297        }
1298    }
1299}
1300
1301/// One sum variant: an object whose `kind` is the variant's name and whose
1302/// payload fields sit beside it.
1303fn variant_schema(discriminant: &str, name: &str, fields: Vec<(String, Value, bool)>) -> Value {
1304    let mut props = Map::new();
1305    props.insert(discriminant.to_string(), json!({ "const": name }));
1306    let mut required = vec![json!(discriminant)];
1307    for (f, schema, req) in fields {
1308        props.insert(f.clone(), schema);
1309        if req {
1310            required.push(json!(f));
1311        }
1312    }
1313    json!({ "type": "object", "properties": props, "required": required })
1314}
1315
1316fn base_schema(b: BaseType) -> Map<String, Value> {
1317    let v = match b {
1318        BaseType::Int => json!({ "type": "integer" }),
1319        BaseType::Float => json!({ "type": "number" }),
1320        BaseType::Bool => json!({ "type": "boolean" }),
1321        BaseType::String => json!({ "type": "string" }),
1322        BaseType::Bytes => json!({ "type": "string", "contentEncoding": "base64" }),
1323        BaseType::Instant => json!({ "type": "integer", "x-bynk-base": "Instant" }),
1324        // #2622: a `Decimal` is a plain decimal string (`"1.20"`) - no
1325        // exponent, no leading `+`.
1326        BaseType::Decimal => json!({
1327            "type": "string",
1328            "pattern": "^-?[0-9]+(\\.[0-9]+)?$",
1329            "x-bynk-base": "Decimal",
1330        }),
1331        BaseType::Duration => json!({ "type": "number", "x-bynk-base": "Duration" }),
1332    };
1333    match v {
1334        Value::Object(m) => m,
1335        _ => unreachable!(),
1336    }
1337}
1338
1339/// Apply `preds` to a schema (Decision A): the JSON Schema equivalent of each,
1340/// the predicates as written in `x-bynk-refinements`, and a description.
1341fn refine(s: &mut Map<String, Value>, preds: &[PredKind]) {
1342    if preds.is_empty() {
1343        return;
1344    }
1345    let mut patterns: Vec<String> = Vec::new();
1346    // #2622: a `Decimal` schema is a string, so its numeric predicates have no
1347    // `minimum`/`maximum` form; they stay in `x-bynk-refinements` and the prose.
1348    let decimal = s.get("x-bynk-base").and_then(Value::as_str) == Some("Decimal");
1349    for p in preds {
1350        match p {
1351            PredKind::Positive | PredKind::NonNegative | PredKind::InRange(..) if decimal => {}
1352            PredKind::InRangeD(..) => {}
1353            PredKind::NonEmpty => tighten_min(s, "minLength", 1.0),
1354            // #2867: JSON Schema's `date` is RFC 3339 `full-date`, the rule
1355            // `IsoDate` enforces; validators that ignore `format` still see
1356            // the ten-character bound.
1357            PredKind::IsoDate => {
1358                s.insert("format".into(), Value::String("date".into()));
1359                tighten_min(s, "minLength", 10.0);
1360                tighten_max(s, "maxLength", 10.0);
1361            }
1362            // #3873: JSON Schema has no `format` for cron; `x-bynk-format` names it.
1363            // `* * * * *` is the shortest valid schedule, nine characters.
1364            PredKind::Cron => {
1365                s.insert("x-bynk-format".into(), Value::String("cron".into()));
1366                tighten_min(s, "minLength", 9.0);
1367            }
1368            PredKind::MinLength(n) => tighten_min(s, "minLength", *n as f64),
1369            PredKind::MaxLength(n) => tighten_max(s, "maxLength", *n as f64),
1370            PredKind::Length(n) => {
1371                tighten_min(s, "minLength", *n as f64);
1372                tighten_max(s, "maxLength", *n as f64);
1373            }
1374            PredKind::Positive => tighten_min(s, "exclusiveMinimum", 0.0),
1375            PredKind::NonNegative => tighten_min(s, "minimum", 0.0),
1376            PredKind::InRange(a, b) => {
1377                tighten_min(s, "minimum", a.value as f64);
1378                tighten_max(s, "maximum", b.value as f64);
1379            }
1380            PredKind::InRangeF(a, b) => {
1381                tighten_min(s, "minimum", a.value);
1382                tighten_max(s, "maximum", b.value);
1383            }
1384            // The codec anchors the whole value; JSON Schema's `pattern` searches.
1385            PredKind::Matches(p) => patterns.push(format!("^(?:{p})$")),
1386        }
1387    }
1388    let mut it = patterns.into_iter();
1389    if let Some(first) = it.next() {
1390        s.insert("pattern".into(), json!(first));
1391    }
1392    let more: Vec<Value> = it.map(|p| json!({ "pattern": p })).collect();
1393    if !more.is_empty() {
1394        s.insert("allOf".into(), Value::Array(more));
1395    }
1396
1397    let written: Vec<String> = preds.iter().map(render_pred).collect();
1398    let prose: Vec<String> = preds.iter().map(pred_prose).collect();
1399    s.insert("x-bynk-refinements".into(), json!(written));
1400    let note = format!("Re-validated at the boundary: {}.", prose.join("; "));
1401    let d = match s.remove("description") {
1402        Some(Value::String(d)) => format!("{d}\n\n{note}"),
1403        _ => note,
1404    };
1405    s.insert("description".into(), json!(d));
1406}
1407
1408fn num(n: f64) -> Value {
1409    if n.fract() == 0.0 && n.abs() < 9.0e15 {
1410        json!(n as i64)
1411    } else {
1412        json!(n)
1413    }
1414}
1415
1416fn tighten_min(s: &mut Map<String, Value>, key: &str, n: f64) {
1417    let cur = s.get(key).and_then(Value::as_f64);
1418    if cur.is_none_or(|c| n > c) {
1419        s.insert(key.into(), num(n));
1420    }
1421}
1422
1423fn tighten_max(s: &mut Map<String, Value>, key: &str, n: f64) {
1424    let cur = s.get(key).and_then(Value::as_f64);
1425    if cur.is_none_or(|c| n < c) {
1426        s.insert(key.into(), num(n));
1427    }
1428}
1429
1430/// The predicate as written: `InRange(1, 100)`.
1431fn render_pred(p: &PredKind) -> String {
1432    match p {
1433        PredKind::Matches(re) => format!("Matches({re:?})"),
1434        PredKind::InRange(a, b) => format!("InRange({}, {})", a.value, b.value),
1435        PredKind::InRangeF(a, b) => format!("InRange({}, {})", a.lexeme, b.lexeme),
1436        PredKind::InRangeD(a, b) => format!("InRange({}, {})", a.lexeme, b.lexeme),
1437        PredKind::MinLength(n) => format!("MinLength({n})"),
1438        PredKind::MaxLength(n) => format!("MaxLength({n})"),
1439        PredKind::Length(n) => format!("Length({n})"),
1440        PredKind::NonNegative => "NonNegative".into(),
1441        PredKind::Positive => "Positive".into(),
1442        PredKind::NonEmpty => "NonEmpty".into(),
1443        PredKind::IsoDate => "IsoDate".into(),
1444        PredKind::Cron => "Cron".into(),
1445    }
1446}
1447
1448/// The codec's own wording for the predicate's failure
1449/// (`pred_condition_and_message`), so the prose matches what a rejected
1450/// request says.
1451fn pred_prose(p: &PredKind) -> String {
1452    match p {
1453        PredKind::Matches(re) => format!("must match `{re}`"),
1454        PredKind::InRange(a, b) => format!("must be in range [{}, {}]", a.value, b.value),
1455        PredKind::InRangeF(a, b) => format!("must be in range [{}, {}]", a.lexeme, b.lexeme),
1456        PredKind::InRangeD(a, b) => format!("must be in range [{}, {}]", a.lexeme, b.lexeme),
1457        PredKind::MinLength(n) => format!("length must be at least {n}"),
1458        PredKind::MaxLength(n) => format!("length must be at most {n}"),
1459        PredKind::Length(n) => format!("length must be exactly {n}"),
1460        PredKind::NonNegative => "must be non-negative".into(),
1461        PredKind::Positive => "must be positive".into(),
1462        PredKind::NonEmpty => "must be non-empty".into(),
1463        PredKind::IsoDate => "must be a calendar date (YYYY-MM-DD)".into(),
1464        PredKind::Cron => "must be a valid cron schedule".into(),
1465    }
1466}
1467
1468// ---------------------------------------------------------------------
1469// YAML
1470// ---------------------------------------------------------------------
1471
1472/// Render `v` as block-style YAML. Strings are always double-quoted with
1473/// JSON's escapes (a YAML double-quoted scalar), so nothing a schema holds —
1474/// `"true"`, `"1.0"`, a regex — is read back as another type.
1475pub fn to_yaml(v: &Value) -> String {
1476    let mut out = String::new();
1477    match v {
1478        Value::Object(m) if !m.is_empty() => yaml_map(m, 0, &mut out),
1479        Value::Array(a) if !a.is_empty() => yaml_seq(a, 0, &mut out),
1480        other => {
1481            out.push_str(&yaml_scalar(other));
1482            out.push('\n');
1483        }
1484    }
1485    out
1486}
1487
1488fn yaml_scalar(v: &Value) -> String {
1489    match v {
1490        Value::Null => "null".into(),
1491        Value::Bool(b) => b.to_string(),
1492        Value::Number(n) => n.to_string(),
1493        Value::String(s) => serde_json::to_string(s).expect("a string serialises"),
1494        Value::Array(_) => "[]".into(),
1495        Value::Object(_) => "{}".into(),
1496    }
1497}
1498
1499fn yaml_key(k: &str) -> String {
1500    let plain = !k.is_empty()
1501        && k.chars()
1502            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '/' | '{' | '}'))
1503        && !k.starts_with(['-', '{', '.'])
1504        // YAML 1.1 reads these (any case) as booleans or null.
1505        && !matches!(
1506            k.to_ascii_lowercase().as_str(),
1507            "true" | "false" | "null" | "yes" | "no" | "on" | "off" | "y" | "n"
1508        )
1509        && k.parse::<f64>().is_err();
1510    if plain {
1511        k.to_string()
1512    } else {
1513        serde_json::to_string(k).expect("a string serialises")
1514    }
1515}
1516
1517fn is_block(v: &Value) -> bool {
1518    matches!(v, Value::Object(m) if !m.is_empty()) || matches!(v, Value::Array(a) if !a.is_empty())
1519}
1520
1521fn yaml_map(m: &Map<String, Value>, indent: usize, out: &mut String) {
1522    let pad = " ".repeat(indent);
1523    for (k, v) in m {
1524        out.push_str(&pad);
1525        out.push_str(&yaml_key(k));
1526        out.push(':');
1527        yaml_value(v, indent, out);
1528    }
1529}
1530
1531fn yaml_seq(a: &[Value], indent: usize, out: &mut String) {
1532    let pad = " ".repeat(indent);
1533    for v in a {
1534        out.push_str(&pad);
1535        out.push('-');
1536        match v {
1537            Value::Object(m) if !m.is_empty() => {
1538                // First key on the dash's line, the rest aligned under it.
1539                let mut inner = String::new();
1540                yaml_map(m, indent + 2, &mut inner);
1541                out.push(' ');
1542                out.push_str(inner.trim_start());
1543            }
1544            Value::Array(inner) if !inner.is_empty() => {
1545                out.push('\n');
1546                yaml_seq(inner, indent + 2, out);
1547            }
1548            other => {
1549                out.push(' ');
1550                out.push_str(&yaml_scalar(other));
1551                out.push('\n');
1552            }
1553        }
1554    }
1555}
1556
1557fn yaml_value(v: &Value, indent: usize, out: &mut String) {
1558    if is_block(v) {
1559        out.push('\n');
1560        match v {
1561            Value::Object(m) => yaml_map(m, indent + 2, out),
1562            Value::Array(a) => yaml_seq(a, indent + 2, out),
1563            _ => unreachable!(),
1564        }
1565    } else {
1566        out.push(' ');
1567        out.push_str(&yaml_scalar(v));
1568        out.push('\n');
1569    }
1570}