1use lemma::{DateTimeValue, Engine, LemmaType, ListedSpec, TypeSpecification};
19use serde_json::{json, Map, Value};
20
21pub const NOW_SLUG: &str = "now";
23
24#[derive(Debug, Clone, serde::Serialize)]
29pub struct ApiSource {
30 pub title: String,
31 pub slug: String,
32 pub url: String,
33}
34
35pub fn temporal_api_sources(engine: &Engine) -> Vec<ApiSource> {
45 let mut all_boundaries: std::collections::BTreeSet<DateTimeValue> =
46 std::collections::BTreeSet::new();
47
48 for repo in engine.list() {
49 for ls in &repo.specs {
50 if let Some(af) = &ls.effective_from {
51 all_boundaries.insert(af.clone());
52 }
53 }
54 }
55
56 if all_boundaries.is_empty() {
57 return vec![ApiSource {
58 title: "Now".to_string(),
59 slug: NOW_SLUG.to_string(),
60 url: "/openapi.json".to_string(),
61 }];
62 }
63
64 let mut sources: Vec<ApiSource> = Vec::with_capacity(all_boundaries.len() + 1);
65
66 sources.push(ApiSource {
67 title: "Now".to_string(),
68 slug: NOW_SLUG.to_string(),
69 url: "/openapi.json".to_string(),
70 });
71
72 for boundary in all_boundaries.iter().rev() {
73 let label = boundary.to_string();
74 sources.push(ApiSource {
75 title: format!("Effective {}", label),
76 slug: label.clone(),
77 url: format!("/openapi.json?effective={}", label),
78 });
79 }
80
81 sources
82}
83
84pub fn generate_openapi(engine: &Engine, explain: bool) -> Value {
89 generate_openapi_effective(engine, explain, &DateTimeValue::now())
90}
91
92pub fn generate_openapi_effective(
109 engine: &Engine,
110 explain: bool,
111 effective: &DateTimeValue,
112) -> Value {
113 let mut paths = Map::new();
114 let mut components_schemas = Map::new();
115
116 components_schemas.insert("LemmaRuleResult".to_string(), build_rule_result_schema());
117
118 let repositories = engine.list();
119 let workspace = repositories
120 .iter()
121 .find(|r| r.repository.is_none())
122 .map(|r| r.specs.as_slice())
123 .expect("BUG: default repository must exist in list()");
124
125 let is_active = |ls: &ListedSpec| -> bool {
126 let after_start = match &ls.effective_from {
127 None => true,
128 Some(from) => effective >= from,
129 };
130 let before_end = match &ls.effective_to {
131 None => true,
132 Some(to) => effective < to,
133 };
134 after_start && before_end
135 };
136
137 let active_specs: Vec<&ListedSpec> = workspace.iter().filter(|ls| is_active(ls)).collect();
138
139 let unique_spec_names: std::collections::BTreeSet<&str> =
140 active_specs.iter().map(|ls| ls.name.as_str()).collect();
141 let unique_spec_names: Vec<String> = unique_spec_names.into_iter().map(String::from).collect();
142
143 paths.insert("/".to_string(), index_path_item(engine));
144
145 for ls in &active_specs {
146 let spec_name = &ls.name;
147 if let Ok(show) = engine.show(None, spec_name, Some(effective)) {
148 let artifacts = build_spec_openapi_artifacts(
149 spec_name,
150 &show,
151 (ls.effective_from.as_ref(), ls.effective_to.as_ref()),
152 explain,
153 );
154 paths.insert(format!("/{spec_name}"), artifacts.path_item);
155 for (name, schema_value) in artifacts.component_schemas {
156 components_schemas.insert(name, schema_value);
157 }
158 }
159 }
160
161 let mut tags = vec![json!({
162 "name": "Specs",
163 "description": "List loaded specs"
164 })];
165 for spec_name in &unique_spec_names {
166 let safe_tag = spec_name.replace('.', "_");
167 tags.push(json!({
168 "name": safe_tag,
169 "x-displayName": spec_name,
170 "description": format!("Show and evaluate `{spec_name}`")
171 }));
172 }
173
174 let spec_tags: Vec<Value> = unique_spec_names
175 .iter()
176 .map(|n| Value::String(n.replace('.', "_")))
177 .collect();
178
179 let tag_groups = vec![
180 json!({ "name": "Overview", "tags": ["Specs"] }),
181 json!({ "name": "Specs", "tags": spec_tags }),
182 ];
183
184 let version_label = format!("{} (effective {})", env!("CARGO_PKG_VERSION"), effective);
185
186 json!({
187 "openapi": "3.1.0",
188 "info": {
189 "title": "Lemma API",
190 "description": "Lemma is a declarative language for business logic: pricing, tax, eligibility, contracts, and policies. This API lists, shows, and evaluates loaded specs. Learn more at [LemmaBase.com](https://lemmabase.com).",
191 "version": version_label
192 },
193 "tags": tags,
194 "x-tagGroups": tag_groups,
195 "paths": Value::Object(paths),
196 "components": {
197 "schemas": Value::Object(components_schemas)
198 }
199 })
200}
201
202struct InputData {
204 name: String,
206 lemma_type: LemmaType,
208 fill: Option<lemma::RuleResultValue>,
210 suggestion: Option<lemma::RuleResultValue>,
212}
213
214fn collect_input_data_from_show(show: &lemma::Show) -> Vec<InputData> {
221 show.data
222 .iter()
223 .filter(|(name, entry)| !name.contains('.') && !entry.needed_by_rules.is_empty())
224 .map(|(name, entry)| InputData {
225 name: name.clone(),
226 lemma_type: entry.lemma_type.clone(),
227 fill: entry.fill.clone(),
228 suggestion: entry.suggestion.clone(),
229 })
230 .collect()
231}
232
233fn index_path_item(engine: &Engine) -> Value {
238 let list = engine.list();
239 let example = serde_json::to_value(&list).expect("BUG: Engine::list must serialize");
240
241 json!({
242 "get": {
243 "operationId": "list",
244 "summary": "List specs",
245 "tags": ["Specs"],
246 "responses": {
247 "200": {
248 "description": "Loaded repositories and their specs",
249 "content": {
250 "application/json": {
251 "schema": {
252 "type": "array",
253 "items": {
254 "type": "object",
255 "properties": {
256 "repository": {
257 "type": ["string", "null"],
258 "description": "Repository name. Null for the default repository."
259 },
260 "specs": {
261 "type": "array",
262 "description": "Specs in this repository",
263 "items": {
264 "type": "object",
265 "properties": {
266 "name": {
267 "type": "string",
268 "description": "Spec name"
269 },
270 "effective_from": {
271 "type": ["string", "null"],
272 "description": "When this version starts. Null if unbounded."
273 },
274 "effective_to": {
275 "type": ["string", "null"],
276 "description": "When this version ends (exclusive). Null if this is the latest."
277 }
278 },
279 "required": ["name"]
280 }
281 }
282 },
283 "required": ["specs"]
284 }
285 },
286 "example": example
287 }
288 }
289 }
290 }
291 }
292 })
293}
294
295fn error_response_schema() -> Value {
300 json!({
301 "description": "Bad request",
302 "content": {
303 "application/json": {
304 "schema": {
305 "type": "object",
306 "properties": {
307 "error": { "type": "string" }
308 },
309 "required": ["error"]
310 }
311 }
312 }
313 })
314}
315
316fn not_found_response_schema() -> Value {
317 json!({
318 "description": "Spec not found",
319 "content": {
320 "application/json": {
321 "schema": {
322 "type": "object",
323 "properties": {
324 "error": { "type": "string" }
325 },
326 "required": ["error"]
327 }
328 }
329 }
330 })
331}
332
333fn memento_spec_response_headers() -> Value {
334 json!({
335 "Memento-Datetime": {
336 "description": "`effective_from` of the resolved version, when versioned",
337 "schema": { "type": "string" }
338 },
339 "Vary": {
340 "description": "Varies with Accept-Datetime",
341 "schema": { "type": "string", "example": "Accept-Datetime" }
342 }
343 })
344}
345
346fn build_get_show_response() -> Value {
348 json!({
349 "type": "object",
350 "required": ["spec", "data", "rules", "meta", "start_line"],
351 "properties": {
352 "repository": {
353 "type": "string",
354 "description": "Interned repository name. Omitted for the unnamed workspace."
355 },
356 "spec": {
357 "type": "string",
358 "description": "Spec name"
359 },
360 "commentary": {
361 "type": ["string", "null"],
362 "description": "Docstring after the spec line"
363 },
364 "effective_from": {
365 "type": ["string", "null"],
366 "description": "When this version starts. Null if unbounded."
367 },
368 "effective_to": {
369 "type": ["string", "null"],
370 "description": "When this version ends (exclusive). Null if this is the latest."
371 },
372 "start_line": {
373 "type": "integer",
374 "description": "Line of the spec declaration (1-based)"
375 },
376 "source_type": {
377 "description": "How this spec was loaded"
378 },
379 "data": {
380 "type": "object",
381 "description": "Inputs: types, path identity, filled values, and suggestions",
382 "additionalProperties": true
383 },
384 "rules": {
385 "type": "object",
386 "description": "This spec's rule graph (local plus reachable imports)",
387 "additionalProperties": true
388 },
389 "meta": {
390 "type": "object",
391 "description": "Spec metadata",
392 "additionalProperties": true
393 },
394 "versions": {
395 "type": "array",
396 "description": "All versions of this spec. Ranges are `[effective_from, effective_to)`.",
397 "items": {
398 "type": "object",
399 "required": ["effective_from", "effective_to"],
400 "properties": {
401 "effective_from": {
402 "type": ["string", "null"],
403 "description": "When this version starts. Null if unbounded."
404 },
405 "effective_to": {
406 "type": ["string", "null"],
407 "description": "When this version ends (exclusive). Null if this is the latest."
408 }
409 }
410 }
411 }
412 }
413 })
414}
415
416fn build_rule_result_schema() -> Value {
418 json!({
419 "type": "object",
420 "required": ["vetoed", "rule_type"],
421 "properties": {
422 "vetoed": {
423 "type": "boolean",
424 "description": "True when the rule has no value"
425 },
426 "result": {
427 "type": "string",
428 "description": "Formatted value when not vetoed"
429 },
430 "veto_reason": {
431 "type": "string",
432 "description": "Why the rule vetoed"
433 },
434 "rule_type": {
435 "type": "string",
436 "description": "Result type (number, boolean, money, ...)"
437 },
438 "measure": {
439 "type": "object",
440 "additionalProperties": { "type": "string" },
441 "description": "Measure value: unit name to magnitude"
442 },
443 "ratio": {
444 "type": "object",
445 "additionalProperties": { "type": "string" },
446 "description": "Ratio value: unit name to magnitude"
447 },
448 "number": {
449 "type": "string",
450 "description": "Value when the result is this type"
451 },
452 "boolean": {
453 "type": "boolean",
454 "description": "Value when the result is this type"
455 },
456 "text": {
457 "type": "string",
458 "description": "Value when the result is this type"
459 },
460 "date": {
461 "type": "object",
462 "description": "Value when the result is this type"
463 },
464 "time": {
465 "type": "object",
466 "description": "Value when the result is this type"
467 },
468 "calendar": {
469 "type": "object",
470 "description": "Value when the result is this type",
471 "properties": {
472 "value": { "type": "string" },
473 "unit": { "type": "string" }
474 }
475 },
476 "range": {
477 "type": "object",
478 "description": "Value when the result is this type"
479 },
480 "missing_data": {
481 "type": "array",
482 "items": { "type": "string" },
483 "description": "Unbound input names for this rule"
484 },
485 "explanation": {
486 "type": "object",
487 "description": "How this result was computed. Needs `--explain` and `x-explain`."
488 }
489 }
490 })
491}
492
493fn build_evaluate_response_schema(show: &lemma::Show, rule_names: &[String]) -> Value {
495 let mut result_props = Map::new();
496 for rule_name in rule_names {
497 if show.rules.contains_key(rule_name) {
498 result_props.insert(
499 rule_name.clone(),
500 json!({
501 "$ref": "#/components/schemas/LemmaRuleResult"
502 }),
503 );
504 }
505 }
506
507 json!({
508 "type": "object",
509 "required": ["spec", "effective", "results"],
510 "properties": {
511 "spec": {
512 "type": "string",
513 "description": "Spec that was evaluated"
514 },
515 "effective": {
516 "type": "string",
517 "description": "Datetime used to pick the version and evaluate"
518 },
519 "spec_effective_from": {
520 "type": "string",
521 "description": "When the resolved version starts"
522 },
523 "spec_effective_to": {
524 "type": "string",
525 "description": "When the resolved version ends (exclusive). Absent if unbounded."
526 },
527 "results": {
528 "type": "object",
529 "description": "Results by rule name. Honors `?rules=`.",
530 "properties": Value::Object(result_props)
531 }
532 }
533 })
534}
535
536struct SpecOpenApiArtifacts {
541 path_item: Value,
542 component_schemas: Map<String, Value>,
543}
544
545fn spec_component_show_names(spec_name: &str) -> (String, String, String, String) {
546 let safe_name = spec_name.replace('.', "_");
547 (
548 format!("{safe_name}_get_show"),
549 format!("{safe_name}_evaluate_response"),
550 format!("{safe_name}_request"),
551 format!("{safe_name}_form_request"),
552 )
553}
554
555fn build_spec_openapi_artifacts(
565 spec_name: &str,
566 show: &lemma::Show,
567 effective_range: (Option<&DateTimeValue>, Option<&DateTimeValue>),
568 explain: bool,
569) -> SpecOpenApiArtifacts {
570 let data = collect_input_data_from_show(show);
571 let rule_names: Vec<String> = show
572 .rules
573 .iter()
574 .filter(|(_, rule)| rule.path.is_empty())
575 .map(|(name, _)| name.clone())
576 .collect();
577 let (
578 get_show_component_name,
579 evaluate_response_schema_name,
580 post_body_schema_name,
581 post_form_body_schema_name,
582 ) = spec_component_show_names(spec_name);
583
584 let mut component_schemas = Map::new();
585 component_schemas.insert(get_show_component_name.clone(), build_get_show_response());
586 component_schemas.insert(
587 evaluate_response_schema_name.clone(),
588 build_evaluate_response_schema(show, &rule_names),
589 );
590 component_schemas.insert(
591 post_body_schema_name.clone(),
592 build_post_request_schema(&data),
593 );
594 component_schemas.insert(
595 post_form_body_schema_name.clone(),
596 build_post_form_request_schema(&data),
597 );
598
599 let path_item = build_spec_path_item_with_show_refs(
600 spec_name,
601 (
602 &get_show_component_name,
603 &evaluate_response_schema_name,
604 &post_body_schema_name,
605 &post_form_body_schema_name,
606 ),
607 &rule_names,
608 explain,
609 effective_range,
610 );
611
612 SpecOpenApiArtifacts {
613 path_item,
614 component_schemas,
615 }
616}
617
618fn x_explain_header_parameter() -> Value {
619 json!({
620 "name": "x-explain",
621 "in": "header",
622 "required": false,
623 "description": "Include explanations. Server needs `--explain`.",
624 "schema": { "type": "string", "default": "true" }
625 })
626}
627
628fn accept_datetime_header_parameter() -> Value {
629 json!({
630 "name": "Accept-Datetime",
631 "in": "header",
632 "required": false,
633 "description": "Evaluate at this datetime. Omit for now.",
634 "schema": { "type": "string", "format": "date-time" },
635 "example": "Sat, 01 Jan 2025 00:00:00 GMT"
636 })
637}
638
639fn build_spec_path_item_with_show_refs(
641 spec_name: &str,
642 component_names: (&str, &str, &str, &str),
643 rule_names: &[String],
644 explain: bool,
645 effective_range: (Option<&DateTimeValue>, Option<&DateTimeValue>),
646) -> Value {
647 let (
648 get_show_component_name,
649 evaluate_response_schema_name,
650 post_body_schema_name,
651 post_form_body_schema_name,
652 ) = component_names;
653 let (effective_from, effective_to) = effective_range;
654
655 let get_show_ref = json!({
656 "$ref": format!("#/components/schemas/{}", get_show_component_name)
657 });
658 let evaluate_schema_ref = json!({
659 "$ref": format!("#/components/schemas/{}", evaluate_response_schema_name)
660 });
661 let body_ref = json!({
662 "$ref": format!("#/components/schemas/{}", post_body_schema_name)
663 });
664 let form_body_ref = json!({
665 "$ref": format!("#/components/schemas/{}", post_form_body_schema_name)
666 });
667
668 let tag = spec_name.replace('.', "_");
669
670 let rules_example = if rule_names.is_empty() {
671 String::new()
672 } else {
673 rule_names.join(",")
674 };
675
676 let rules_param = json!({
677 "name": "rules",
678 "in": "query",
679 "required": false,
680 "description": "Rules to evaluate, comma-separated. Omit for all.",
681 "schema": { "type": "string" },
682 "example": rules_example
683 });
684
685 let mut get_parameters: Vec<Value> = Vec::new();
686 get_parameters.push(accept_datetime_header_parameter());
687 if explain {
688 get_parameters.push(x_explain_header_parameter());
689 }
690
691 let get_operation_id = format!("get_{}", spec_name);
692 let post_operation_id = format!("post_{}", spec_name);
693
694 let mut post_parameters: Vec<Value> = vec![rules_param];
695 post_parameters.push(accept_datetime_header_parameter());
696 if explain {
697 post_parameters.push(x_explain_header_parameter());
698 }
699
700 let datetime_or_null = |dt: Option<&DateTimeValue>| -> Value {
701 match dt {
702 Some(d) => Value::String(d.to_string()),
703 None => Value::Null,
704 }
705 };
706
707 json!({
708 "x-effective-from": datetime_or_null(effective_from),
709 "x-effective-to": datetime_or_null(effective_to),
710 "get": {
711 "operationId": get_operation_id,
712 "summary": "Show spec",
713 "tags": [tag],
714 "parameters": get_parameters,
715 "responses": {
716 "200": {
717 "description": "Spec interface",
718 "headers": memento_spec_response_headers(),
719 "content": {
720 "application/json": {
721 "schema": get_show_ref
722 }
723 }
724 },
725 "400": error_response_schema(),
726 "404": not_found_response_schema()
727 }
728 },
729 "post": {
730 "operationId": post_operation_id,
731 "summary": "Evaluate",
732 "tags": [tag],
733 "parameters": post_parameters,
734 "requestBody": {
735 "required": true,
736 "content": {
737 "application/x-www-form-urlencoded": {
739 "schema": form_body_ref
740 },
741 "application/json": {
742 "schema": body_ref
743 }
744 }
745 },
746 "responses": {
747 "200": {
748 "description": "Evaluation results",
749 "headers": memento_spec_response_headers(),
750 "content": {
751 "application/json": {
752 "schema": evaluate_schema_ref
753 }
754 }
755 },
756 "400": error_response_schema(),
757 "404": not_found_response_schema()
758 }
759 }
760 })
761}
762
763fn type_help(lemma_type: &LemmaType) -> String {
769 match &lemma_type.specifications {
770 TypeSpecification::Boolean { help, .. } => help.clone(),
771 TypeSpecification::Measure { help, .. } => help.clone(),
772 TypeSpecification::MeasureRange { help, .. } => help.clone(),
773 TypeSpecification::Number { help, .. } => help.clone(),
774 TypeSpecification::NumberRange { help, .. } => help.clone(),
775 TypeSpecification::Ratio { help, .. } => help.clone(),
776 TypeSpecification::RatioRange { help, .. } => help.clone(),
777 TypeSpecification::Text { help, .. } => help.clone(),
778 TypeSpecification::Date { help, .. } => help.clone(),
779 TypeSpecification::DateRange { help, .. } => help.clone(),
780 TypeSpecification::TimeRange { help, .. } => help.clone(),
781 TypeSpecification::Time { help, .. } => help.clone(),
782 TypeSpecification::Veto { .. } => String::new(),
783 TypeSpecification::Undetermined => unreachable!(
784 "BUG: type_help called with Undetermined sentinel type; this type must never reach OpenAPI generation"
785 ),
786 }
787}
788
789fn build_post_request_schema(data: &[InputData]) -> Value {
794 let mut properties = Map::new();
795 let mut required = Vec::new();
796
797 for data in data {
798 let default_for_docs = data.fill.as_ref().or(data.suggestion.as_ref());
799 properties.insert(
800 data.name.clone(),
801 build_post_property_schema(&data.lemma_type, default_for_docs),
802 );
803 if data.fill.is_none() {
804 required.push(Value::String(data.name.clone()));
805 }
806 }
807
808 let mut schema = json!({
809 "type": "object",
810 "properties": Value::Object(properties)
811 });
812 if !required.is_empty() {
813 schema["required"] = Value::Array(required);
814 }
815 schema
816}
817
818fn build_post_property_schema(
819 lemma_type: &LemmaType,
820 data_value: Option<&lemma::RuleResultValue>,
821) -> Value {
822 let mut schema = build_post_type_schema(lemma_type);
823
824 let help = type_help(lemma_type);
825 if !help.is_empty() {
826 schema["description"] = Value::String(help);
827 }
828
829 if let Some(v) = data_value {
830 schema["default"] = Value::String(v.to_literal(lemma_type).display_value());
831 }
832
833 schema
834}
835
836fn build_post_type_schema(lemma_type: &LemmaType) -> Value {
837 match &lemma_type.specifications {
838 TypeSpecification::Text { options, .. } => {
839 let mut schema = json!({ "type": "string" });
840 if !options.is_empty() {
841 schema["enum"] =
842 Value::Array(options.iter().map(|o| Value::String(o.clone())).collect());
843 }
844 schema
845 }
846 TypeSpecification::Boolean { .. } => {
847 json!({ "type": "boolean" })
848 }
849 _ => json!({ "type": "string" }),
850 }
851}
852
853fn build_post_form_request_schema(data: &[InputData]) -> Value {
854 let mut properties = Map::new();
855 let mut required = Vec::new();
856
857 for data in data {
858 let default_for_docs = data.fill.as_ref().or(data.suggestion.as_ref());
859 properties.insert(
860 data.name.clone(),
861 build_post_form_property_schema(&data.lemma_type, default_for_docs),
862 );
863 if data.fill.is_none() {
864 required.push(Value::String(data.name.clone()));
865 }
866 }
867
868 let mut schema = json!({
869 "type": "object",
870 "properties": Value::Object(properties)
871 });
872 if !required.is_empty() {
873 schema["required"] = Value::Array(required);
874 }
875 schema
876}
877
878fn build_post_form_property_schema(
879 lemma_type: &LemmaType,
880 data_value: Option<&lemma::RuleResultValue>,
881) -> Value {
882 let mut schema = build_post_form_type_schema(lemma_type);
883
884 let help = type_help(lemma_type);
885 if !help.is_empty() {
886 schema["description"] = Value::String(help);
887 }
888
889 if let Some(v) = data_value {
890 schema["default"] = Value::String(v.to_literal(lemma_type).display_value());
891 }
892
893 schema
894}
895
896fn build_post_form_type_schema(lemma_type: &LemmaType) -> Value {
897 match &lemma_type.specifications {
898 TypeSpecification::Text { options, .. } => {
899 let mut schema = json!({ "type": "string" });
900 if !options.is_empty() {
901 schema["enum"] =
902 Value::Array(options.iter().map(|o| Value::String(o.clone())).collect());
903 }
904 schema
905 }
906 TypeSpecification::Boolean { .. } => {
907 json!({ "type": "string", "enum": ["true", "false"] })
908 }
909 _ => json!({ "type": "string" }),
910 }
911}
912
913#[cfg(test)]
918mod tests {
919 use super::*;
920 use lemma::{DateGranularity, DateTimeValue, SourceType};
921
922 fn create_engine_with_code(code: &str) -> Engine {
923 let mut engine = Engine::new();
924 engine
925 .load([(
926 SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("test.lemma"))),
927 code.to_string(),
928 )])
929 .expect("failed to parse lemma code");
930 engine
931 }
932
933 fn create_engine_with_files(files: Vec<(&str, &str)>) -> Engine {
934 let mut engine = Engine::new();
935 for (name, code) in files {
936 engine
937 .load([(
938 SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(name))),
939 code.to_string(),
940 )])
941 .expect("failed to parse lemma code");
942 }
943 engine
944 }
945
946 fn date(year: i32, month: u32, day: u32) -> DateTimeValue {
947 DateTimeValue {
948 year,
949 month,
950 day,
951 hour: 0,
952 minute: 0,
953 second: 0,
954 microsecond: 0,
955 timezone: None,
956 granularity: DateGranularity::Full,
957 }
958 }
959
960 fn has_param(params: &Value, name: &str) -> bool {
961 params
962 .as_array()
963 .map(|a| a.iter().any(|p| p["name"] == name))
964 .unwrap_or(false)
965 }
966
967 #[test]
972 fn test_generate_openapi_x_tag_groups() {
973 let engine = create_engine_with_code(
974 "spec pricing
975 data quantity: 10
976 rule total: quantity * 2",
977 );
978 let spec = generate_openapi(&engine, false);
979
980 let groups = spec["x-tagGroups"]
981 .as_array()
982 .expect("x-tagGroups should be array");
983 assert_eq!(groups.len(), 2);
984 assert_eq!(groups[0]["name"], "Overview");
985 assert_eq!(groups[0]["tags"], json!(["Specs"]));
986 assert_eq!(groups[1]["name"], "Specs");
987 assert_eq!(groups[1]["tags"], json!(["pricing"]));
988 }
989
990 #[test]
991 fn test_spec_path_has_get_and_post() {
992 let engine = create_engine_with_code(
993 "spec pricing
994 data quantity: 10
995 rule total: quantity * 2",
996 );
997 let spec = generate_openapi(&engine, false);
998
999 assert!(
1000 spec["paths"]["/pricing"].is_object(),
1001 "single spec path /pricing"
1002 );
1003 assert!(spec["paths"]["/pricing"]["get"].is_object());
1004 assert!(spec["paths"]["/pricing"]["post"].is_object());
1005
1006 assert_eq!(
1007 spec["paths"]["/pricing"]["get"]["operationId"],
1008 "get_pricing"
1009 );
1010 assert_eq!(
1011 spec["paths"]["/pricing"]["post"]["operationId"],
1012 "post_pricing"
1013 );
1014 assert_eq!(spec["paths"]["/pricing"]["get"]["tags"][0], "pricing");
1015
1016 let get_params = spec["paths"]["/pricing"]["get"]["parameters"]
1017 .as_array()
1018 .expect("parameters array");
1019 let param_names: Vec<&str> = get_params
1020 .iter()
1021 .map(|p| p["name"].as_str().unwrap())
1022 .collect();
1023 assert!(
1024 !param_names.contains(&"rules"),
1025 "GET must not have rules query param (show is full interface)"
1026 );
1027 let post_params = spec["paths"]["/pricing"]["post"]["parameters"]
1028 .as_array()
1029 .expect("post parameters array");
1030 let post_param_names: Vec<&str> = post_params
1031 .iter()
1032 .map(|p| p["name"].as_str().unwrap())
1033 .collect();
1034 assert!(
1035 post_param_names.contains(&"rules"),
1036 "POST must have rules query param"
1037 );
1038 assert!(
1039 param_names.contains(&"Accept-Datetime"),
1040 "GET must have Accept-Datetime header"
1041 );
1042
1043 let get_ref = spec["paths"]["/pricing"]["get"]["responses"]["200"]["content"]
1044 ["application/json"]["schema"]["$ref"]
1045 .as_str()
1046 .unwrap();
1047 let post_ref = spec["paths"]["/pricing"]["post"]["responses"]["200"]["content"]
1048 ["application/json"]["schema"]["$ref"]
1049 .as_str()
1050 .unwrap();
1051 assert_eq!(get_ref, "#/components/schemas/pricing_get_show");
1052 assert_eq!(post_ref, "#/components/schemas/pricing_evaluate_response");
1053 assert_ne!(get_ref, post_ref);
1054
1055 let get_show = &spec["components"]["schemas"]["pricing_get_show"];
1056 assert!(get_show["properties"]["spec"]["type"] == "string");
1057 assert!(get_show["properties"].get("spec_set_id").is_none());
1058 assert!(get_show["properties"]["versions"].is_object());
1059 assert!(get_show["properties"]["start_line"]["type"] == "integer");
1060
1061 let h200 = &spec["paths"]["/pricing"]["get"]["responses"]["200"];
1062 assert!(h200["headers"]["Memento-Datetime"].is_object());
1063 assert!(h200["headers"]["Vary"].is_object());
1064 }
1065
1066 #[test]
1067 fn suggestion_only_field_is_required_with_json_schema_default() {
1068 let engine = create_engine_with_code(
1069 r#"
1070spec age_check
1071data age: number -> suggest 18
1072rule adult: age >= 18
1073"#,
1074 );
1075 let spec = generate_openapi(&engine, false);
1076 let body = &spec["components"]["schemas"]["age_check_request"];
1077 let required = body["required"]
1078 .as_array()
1079 .expect("required array")
1080 .iter()
1081 .map(|v| v.as_str().unwrap())
1082 .collect::<Vec<_>>();
1083 assert!(
1084 required.contains(&"age"),
1085 "suggest-only fields must stay required, got {required:?}"
1086 );
1087 assert_eq!(body["properties"]["age"]["default"], "18");
1088 }
1089
1090 #[test]
1095 fn test_openapi_omits_shell_and_unlisted_schema_routes() {
1096 let engine = create_engine_with_code(
1097 "spec pricing
1098 data quantity: 10
1099 rule total: quantity * 2",
1100 );
1101 let spec = generate_openapi(&engine, false);
1102
1103 let paths = spec["paths"].as_object().expect("paths object");
1104 assert!(paths.contains_key("/"));
1105 assert_eq!(paths["/"]["get"]["operationId"], "list");
1106 assert!(!paths.contains_key("/openapi.json"));
1107 assert!(!paths.contains_key("/health"));
1108 assert!(!paths.contains_key("/docs"));
1109 assert!(!paths.contains_key("/schema/pricing"));
1110 assert!(!paths.contains_key("/schema/pricing/{rules}"));
1111 assert!(!paths.keys().any(|key| key.starts_with("/schema/")));
1112 }
1113
1114 #[test]
1115 fn test_generate_openapi_explain_adds_x_explain_and_explanation_schema() {
1116 let engine = create_engine_with_code(
1117 "spec pricing
1118 data quantity: 10
1119 rule total: quantity * 2",
1120 );
1121 let spec = generate_openapi(&engine, true);
1122
1123 let get_params = &spec["paths"]["/pricing"]["get"]["parameters"];
1124 assert!(has_param(get_params, "x-explain"));
1125
1126 let rule_result = &spec["components"]["schemas"]["LemmaRuleResult"];
1127 assert!(rule_result["properties"]["explanation"].is_object());
1128 assert!(rule_result["properties"]["vetoed"]["type"] == "boolean");
1129 assert!(rule_result["properties"]["rule_type"]["type"] == "string");
1130
1131 let evaluate = &spec["components"]["schemas"]["pricing_evaluate_response"];
1132 assert!(evaluate["required"]
1133 .as_array()
1134 .unwrap()
1135 .contains(&json!("spec")));
1136 assert!(evaluate["required"]
1137 .as_array()
1138 .unwrap()
1139 .contains(&json!("effective")));
1140 assert!(evaluate["required"]
1141 .as_array()
1142 .unwrap()
1143 .contains(&json!("results")));
1144 let total_ref = evaluate["properties"]["results"]["properties"]["total"]["$ref"]
1145 .as_str()
1146 .unwrap();
1147 assert_eq!(total_ref, "#/components/schemas/LemmaRuleResult");
1148 }
1149
1150 #[test]
1151 fn test_generate_openapi_multiple_specs() {
1152 let engine = create_engine_with_files(vec![
1153 (
1154 "pricing.lemma",
1155 "spec pricing
1156 data quantity: 10
1157 rule total: quantity * 2",
1158 ),
1159 (
1160 "shipping.lemma",
1161 "spec shipping
1162 data weight: 5
1163 rule cost: weight * 3",
1164 ),
1165 ]);
1166 let spec = generate_openapi(&engine, false);
1167
1168 assert!(spec["paths"]["/pricing"].is_object());
1169 assert!(spec["paths"]["/shipping"].is_object());
1170 }
1171
1172 #[test]
1173 fn test_nested_spec_path_schema_refs_are_valid() {
1174 let engine = create_engine_with_code(
1175 "spec bc
1176 data x: number
1177 rule result: x",
1178 );
1179 let spec = generate_openapi(&engine, false);
1180
1181 assert!(spec["paths"]["/bc"]["post"].is_object());
1182 let post_content = &spec["paths"]["/bc"]["post"]["requestBody"]["content"];
1183 let content_keys: Vec<&str> = post_content
1184 .as_object()
1185 .expect("requestBody.content object")
1186 .keys()
1187 .map(|k| k.as_str())
1188 .collect();
1189 assert_eq!(
1190 content_keys.first().copied(),
1191 Some("application/x-www-form-urlencoded"),
1192 "form-urlencoded must be first so Scalar docs default to Form URL Encoded"
1193 );
1194 let body_ref = post_content["application/json"]["schema"]["$ref"]
1195 .as_str()
1196 .unwrap();
1197 let form_body_ref = post_content["application/x-www-form-urlencoded"]["schema"]["$ref"]
1198 .as_str()
1199 .unwrap();
1200 assert_eq!(body_ref, "#/components/schemas/bc_request");
1201 assert_eq!(form_body_ref, "#/components/schemas/bc_form_request");
1202 assert!(spec["components"]["schemas"]["bc_request"].is_object());
1203 assert!(spec["components"]["schemas"]["bc_form_request"].is_object());
1204 assert!(spec["components"]["schemas"]["bc_request"]["properties"]["x"].is_object());
1205 assert!(spec["components"]["schemas"]["bc_form_request"]["properties"]["x"].is_object());
1206 }
1207
1208 #[test]
1213 fn test_generate_openapi_effective_reflects_specific_time() {
1214 let engine = create_engine_with_code(
1215 "spec pricing
1216 data quantity: 10
1217 rule total: quantity * 2",
1218 );
1219 let effective = date(2025, 6, 15);
1220 let spec = generate_openapi_effective(&engine, false, &effective);
1221
1222 assert_eq!(spec["openapi"], "3.1.0");
1223 let version = spec["info"]["version"].as_str().unwrap();
1224 assert!(
1225 version.contains("2025-06-15"),
1226 "version string should contain the effective date, got: {}",
1227 version
1228 );
1229 }
1230
1231 #[test]
1232 fn test_effective_shows_correct_temporal_version_interface() {
1233 let engine = create_engine_with_files(vec![(
1234 "policy.lemma",
1235 r#"
1236spec policy
1237data base: 100
1238rule discount: 10
1239
1240spec policy 2025-06-01
1241data base: 200
1242data premium: boolean
1243rule discount: 20
1244rule surcharge:
1245 5
1246 unless premium then 10
1247"#,
1248 )]);
1249
1250 let before = date(2025, 3, 1);
1251 let spec_v1 = generate_openapi_effective(&engine, false, &before);
1252
1253 assert!(spec_v1["paths"]["/policy"].is_object());
1254 let v1_evaluate = &spec_v1["components"]["schemas"]["policy_evaluate_response"];
1255 let v1_result = &v1_evaluate["properties"]["results"]["properties"];
1256 assert_eq!(
1257 v1_result["discount"]["$ref"].as_str(),
1258 Some("#/components/schemas/LemmaRuleResult"),
1259 "v1 should have discount rule"
1260 );
1261 assert!(
1262 v1_result["surcharge"].is_null(),
1263 "v1 must NOT have surcharge rule"
1264 );
1265 let v1_request = &spec_v1["components"]["schemas"]["policy_request"];
1266 assert!(
1267 v1_request["properties"]["premium"].is_null(),
1268 "v1 must NOT have premium data"
1269 );
1270
1271 let after = date(2025, 8, 1);
1272 let spec_v2 = generate_openapi_effective(&engine, false, &after);
1273
1274 let v2_evaluate = &spec_v2["components"]["schemas"]["policy_evaluate_response"];
1275 let v2_result = &v2_evaluate["properties"]["results"]["properties"];
1276 assert!(
1277 v2_result["discount"]["$ref"].is_string(),
1278 "v2 should have discount rule"
1279 );
1280 assert!(
1281 v2_result["surcharge"]["$ref"].is_string(),
1282 "v2 should have surcharge rule"
1283 );
1284 let v2_request = &spec_v2["components"]["schemas"]["policy_request"];
1285 assert!(
1286 v2_request["properties"]["premium"].is_object(),
1287 "v2 should have premium data"
1288 );
1289 }
1290
1291 #[test]
1300 fn test_spec_path_item_exposes_half_open_effective_range_as_vendor_extensions() {
1301 let engine = create_engine_with_files(vec![(
1302 "policy.lemma",
1303 r#"
1304spec policy 2025-01-01
1305data base: 10
1306rule total: base
1307
1308spec policy 2026-01-01
1309data base: 99
1310rule total: base
1311"#,
1312 )]);
1313
1314 let at_earlier = date(2025, 6, 1);
1315 let earlier_doc = generate_openapi_effective(&engine, false, &at_earlier);
1316 let earlier_path = &earlier_doc["paths"]["/policy"];
1317 assert_eq!(
1318 earlier_path["x-effective-from"].as_str(),
1319 Some("2025-01-01"),
1320 "earlier version effective_from on PathItem"
1321 );
1322 assert_eq!(
1323 earlier_path["x-effective-to"].as_str(),
1324 Some("2026-01-01"),
1325 "earlier version effective_to equals next version's effective_from"
1326 );
1327
1328 let at_latest = date(2026, 6, 1);
1329 let latest_doc = generate_openapi_effective(&engine, false, &at_latest);
1330 let latest_path = &latest_doc["paths"]["/policy"];
1331 assert_eq!(
1332 latest_path["x-effective-from"].as_str(),
1333 Some("2026-01-01"),
1334 "latest version effective_from on PathItem"
1335 );
1336 assert!(
1337 latest_path["x-effective-to"].is_null(),
1338 "latest version has no successor; x-effective-to must be null: {latest_path}"
1339 );
1340 }
1341
1342 #[test]
1345 fn test_spec_path_item_effective_extensions_null_for_unversioned_spec() {
1346 let engine = create_engine_with_code(
1347 "spec pricing
1348 data quantity: 10
1349 rule total: quantity * 2",
1350 );
1351 let document = generate_openapi(&engine, false);
1352 let path_item = &document["paths"]["/pricing"];
1353 assert!(
1354 path_item["x-effective-from"].is_null(),
1355 "unversioned spec: x-effective-from must be null: {path_item}"
1356 );
1357 assert!(
1358 path_item["x-effective-to"].is_null(),
1359 "unversioned spec: x-effective-to must be null: {path_item}"
1360 );
1361 }
1362
1363 #[test]
1368 fn test_temporal_sources_versioned_returns_boundaries_plus_now() {
1369 let engine = create_engine_with_files(vec![(
1370 "policy.lemma",
1371 r#"
1372spec policy
1373data base: 100
1374rule discount: 10
1375
1376spec policy 2025-06-01
1377data base: 200
1378rule discount: 20
1379"#,
1380 )]);
1381
1382 let sources = temporal_api_sources(&engine);
1383
1384 assert_eq!(sources.len(), 2, "should have 1 now + 1 boundary");
1385
1386 assert_eq!(sources[0].title, "Now");
1387 assert_eq!(sources[0].slug, NOW_SLUG);
1388 assert_eq!(sources[0].url, "/openapi.json");
1389
1390 assert_eq!(sources[1].title, "Effective 2025-06-01");
1391 assert_eq!(sources[1].slug, "2025-06-01");
1392 assert_eq!(sources[1].url, "/openapi.json?effective=2025-06-01");
1393 }
1394
1395 #[test]
1396 fn test_temporal_sources_multiple_specs_merged_boundaries() {
1397 let engine = create_engine_with_files(vec![
1398 (
1399 "policy.lemma",
1400 r#"
1401spec policy
1402data base: 100
1403rule discount: 10
1404
1405spec policy 2025-06-01
1406data base: 200
1407rule discount: 20
1408"#,
1409 ),
1410 (
1411 "rates.lemma",
1412 r#"
1413spec rates
1414data rate: 5
1415rule total: rate * 2
1416
1417spec rates 2025-03-01
1418data rate: 7
1419rule total: rate * 2
1420
1421spec rates 2025-06-01
1422data rate: 9
1423rule total: rate * 2
1424"#,
1425 ),
1426 ]);
1427
1428 let sources = temporal_api_sources(&engine);
1429
1430 let slugs: Vec<&str> = sources.iter().map(|s| s.slug.as_str()).collect();
1431 assert!(
1432 slugs.contains(&"2025-03-01"),
1433 "should contain rates boundary"
1434 );
1435 assert!(
1436 slugs.contains(&"2025-06-01"),
1437 "should contain shared boundary"
1438 );
1439 assert!(slugs.contains(&NOW_SLUG), "should contain now");
1440 assert_eq!(slugs.len(), 3, "2 unique boundaries + now");
1441 }
1442
1443 #[test]
1444 fn test_temporal_sources_ordered_chronologically() {
1445 let engine = create_engine_with_files(vec![(
1446 "policy.lemma",
1447 r#"
1448spec policy
1449data base: 100
1450rule discount: 10
1451
1452spec policy 2024-01-01
1453data base: 50
1454rule discount: 5
1455
1456spec policy 2025-06-01
1457data base: 200
1458rule discount: 20
1459"#,
1460 )]);
1461
1462 let sources = temporal_api_sources(&engine);
1463 let slugs: Vec<&str> = sources.iter().map(|s| s.slug.as_str()).collect();
1464 assert_eq!(slugs, vec![NOW_SLUG, "2025-06-01", "2024-01-01"]);
1465 }
1466
1467 #[test]
1472 fn test_post_schema_text_with_options_has_enum() {
1473 let engine = create_engine_with_code(
1474 "spec test
1475 data product: text -> option \"A\" -> option \"B\"
1476 rule result: product",
1477 );
1478 let spec = generate_openapi(&engine, false);
1479
1480 let product_prop = &spec["components"]["schemas"]["test_request"]["properties"]["product"];
1481 assert!(product_prop["enum"].is_array());
1482 let enums = product_prop["enum"].as_array().unwrap();
1483 assert_eq!(enums.len(), 2);
1484 assert_eq!(enums[0], "A");
1485 assert_eq!(enums[1], "B");
1486 }
1487
1488 #[test]
1489 fn test_post_schema_boolean_is_json_boolean() {
1490 let engine = create_engine_with_code(
1491 "spec test
1492 data is_active: boolean
1493 rule result: is_active",
1494 );
1495 let spec = generate_openapi(&engine, false);
1496
1497 let schema = &spec["components"]["schemas"]["test_request"];
1498 let is_active = &schema["properties"]["is_active"];
1499 assert_eq!(is_active["type"], "boolean");
1500
1501 let form_schema = &spec["components"]["schemas"]["test_form_request"];
1502 let form_is_active = &form_schema["properties"]["is_active"];
1503 assert_eq!(form_is_active["type"], "string");
1504 assert_eq!(form_is_active["enum"], json!(["true", "false"]));
1505 }
1506
1507 #[test]
1508 fn test_post_schema_number_is_string() {
1509 let engine = create_engine_with_code(
1510 "spec test
1511 data quantity: number
1512 rule result: quantity",
1513 );
1514 let spec = generate_openapi(&engine, false);
1515
1516 let schema = &spec["components"]["schemas"]["test_request"];
1517 assert_eq!(schema["properties"]["quantity"]["type"], "string");
1518 }
1519
1520 #[test]
1521 fn test_data_with_default_is_not_required() {
1522 let engine = create_engine_with_code(
1523 "spec test
1524 data quantity: 10
1525 data name: text
1526 rule result: quantity
1527 rule label: name",
1528 );
1529 let spec = generate_openapi(&engine, false);
1530
1531 let schema = &spec["components"]["schemas"]["test_request"];
1532 let required = schema["required"]
1533 .as_array()
1534 .expect("required should be array");
1535
1536 assert!(required.contains(&Value::String("name".to_string())));
1537 assert!(!required.contains(&Value::String("quantity".to_string())));
1538 }
1539
1540 #[test]
1541 fn test_help_and_default_in_openapi() {
1542 let engine = create_engine_with_code(
1543 r#"spec test
1544data quantity: number -> help "Number of items to order" -> suggest 10
1545data active: boolean -> help "Whether the feature is enabled" -> suggest true
1546rule result:
1547 quantity
1548 unless active then 0
1549"#,
1550 );
1551 let spec = generate_openapi(&engine, false);
1552
1553 let req_schema = &spec["components"]["schemas"]["test_request"];
1554 assert!(req_schema["properties"]["quantity"]["description"]
1555 .as_str()
1556 .unwrap()
1557 .contains("Number of items to order"));
1558 assert_eq!(
1559 req_schema["properties"]["quantity"]["default"]
1560 .as_str()
1561 .unwrap(),
1562 "10"
1563 );
1564 assert!(req_schema["properties"]["active"]["description"]
1565 .as_str()
1566 .unwrap()
1567 .contains("Whether the feature is enabled"));
1568 assert_eq!(
1569 req_schema["properties"]["active"]["default"]
1570 .as_str()
1571 .unwrap(),
1572 "true"
1573 );
1574 let required = req_schema["required"]
1575 .as_array()
1576 .expect("required array")
1577 .iter()
1578 .map(|v| v.as_str().unwrap())
1579 .collect::<Vec<_>>();
1580 assert!(required.contains(&"quantity"));
1581 assert!(required.contains(&"active"));
1582 }
1583}