1use std::fs;
10
11use anyhow::{Context, Result};
12use fraiseql_core::schema::CrudNamingConfig;
13use serde_json::{Value, json};
14
15use crate::{
16 config::TomlSchema,
17 schema::{IntermediateSchema, intermediate::IntermediateQueryDefaults},
18};
19
20pub(crate) fn pascal_to_snake(type_name: &str) -> String {
25 let mut out = String::with_capacity(type_name.len() + 4);
26 for (i, ch) in type_name.chars().enumerate() {
27 if ch.is_uppercase() && i > 0 {
28 out.push('_');
29 }
30 out.push(ch.to_ascii_lowercase());
31 }
32 out
33}
34
35fn resolve_mutation_sql_source(
43 mutation_name: &str,
44 sql_source: Option<&str>,
45 operation: &str,
46 return_type: &str,
47 crud: Option<&CrudNamingConfig>,
48) -> Result<String> {
49 if let Some(src) = sql_source {
50 return Ok(src.to_string());
51 }
52 if let Some(cfg) = crud {
53 let entity = pascal_to_snake(return_type);
54 if let Some(resolved) = cfg.resolve(operation, &entity) {
55 return Ok(resolved);
56 }
57 }
58 anyhow::bail!(
59 "Mutation '{mutation_name}' has no `sql_source` and no `[crud]` naming config \
60 could resolve it (operation = {operation:?}, return_type = {return_type:?}). \
61 Either add `sql_source` to the mutation or configure `[crud]` in fraiseql.toml."
62 )
63}
64
65pub struct SchemaMerger;
67
68impl SchemaMerger {
69 pub fn merge_files(types_path: &str, toml_path: &str) -> Result<IntermediateSchema> {
83 let types_json = fs::read_to_string(types_path)
85 .context(format!("Failed to read types.json from {types_path}"))?;
86 let types_value: Value =
87 serde_json::from_str(&types_json).context("Failed to parse types.json")?;
88
89 let toml_schema = TomlSchema::from_file(toml_path)
91 .context(format!("Failed to load TOML from {toml_path}"))?;
92
93 Self::merge_values(&types_value, &toml_schema)
98 }
99
100 pub fn merge_toml_only(toml_path: &str) -> Result<IntermediateSchema> {
113 let toml_schema = TomlSchema::from_file(toml_path)
114 .context(format!("Failed to load TOML from {toml_path}"))?;
115
116 toml_schema.validate()?;
117
118 let types_value = toml_schema.to_intermediate_schema();
120 Self::merge_values(&types_value, &toml_schema)
121 }
122
123 pub fn merge_from_directory(toml_path: &str, schema_dir: &str) -> Result<IntermediateSchema> {
137 let toml_schema = TomlSchema::from_file(toml_path)
138 .context(format!("Failed to load TOML from {toml_path}"))?;
139
140 toml_schema.validate()?;
141
142 let types_value = crate::schema::MultiFileLoader::load_from_directory(schema_dir)
144 .context(format!("Failed to load schema from directory {schema_dir}"))?;
145
146 Self::merge_values(&types_value, &toml_schema)
148 }
149
150 fn load_section(files: &[String], key: &str) -> Result<Option<serde_json::Value>> {
152 if files.is_empty() {
153 return Ok(None);
154 }
155 let paths: Vec<std::path::PathBuf> = files.iter().map(std::path::PathBuf::from).collect();
156 let loaded = crate::schema::MultiFileLoader::load_from_paths(&paths)
157 .with_context(|| format!("Failed to load {key} files"))?;
158 Ok(loaded.get(key).cloned())
159 }
160
161 fn extend_from_json_file(
164 path: &std::path::Path,
165 all_types: &mut Vec<Value>,
166 all_queries: &mut Vec<Value>,
167 all_mutations: &mut Vec<Value>,
168 ) -> Result<()> {
169 let content = fs::read_to_string(path)
170 .with_context(|| format!("Failed to read {}", path.display()))?;
171 let value: Value = serde_json::from_str(&content)
172 .with_context(|| format!("Failed to parse {}", path.display()))?;
173 for (vec, key) in [
174 (all_types as &mut Vec<Value>, "types"),
175 (all_queries, "queries"),
176 (all_mutations, "mutations"),
177 ] {
178 if let Some(Value::Array(items)) = value.get(key) {
179 vec.extend(items.iter().cloned());
180 }
181 }
182 Ok(())
183 }
184
185 fn enrich_type_from_toml(
187 enriched_type: &mut Value,
188 toml_type: &crate::config::toml_schema::TypeDefinition,
189 ) {
190 enriched_type["sql_source"] = json!(toml_type.sql_source);
191 if let Some(desc) = &toml_type.description {
192 enriched_type["description"] = json!(desc);
193 }
194 }
195
196 pub fn merge_explicit_files(
212 toml_path: &str,
213 type_files: &[String],
214 query_files: &[String],
215 mutation_files: &[String],
216 ) -> Result<IntermediateSchema> {
217 let toml_schema = TomlSchema::from_file(toml_path)
218 .context(format!("Failed to load TOML from {toml_path}"))?;
219
220 toml_schema.validate()?;
221
222 let mut types_value = serde_json::json!({
223 "types": [],
224 "queries": [],
225 "mutations": []
226 });
227
228 if let Some(v) = Self::load_section(type_files, "types")? {
229 types_value["types"] = v;
230 }
231 if let Some(v) = Self::load_section(query_files, "queries")? {
232 types_value["queries"] = v;
233 }
234 if let Some(v) = Self::load_section(mutation_files, "mutations")? {
235 types_value["mutations"] = v;
236 }
237
238 Self::merge_values(&types_value, &toml_schema)
239 }
240
241 pub fn merge_from_domains(toml_path: &str) -> Result<IntermediateSchema> {
255 let toml_schema = TomlSchema::from_file(toml_path)
256 .context(format!("Failed to load TOML from {toml_path}"))?;
257
258 toml_schema.validate()?;
259
260 let domains = toml_schema
262 .domain_discovery
263 .resolve_domains()
264 .context("Failed to discover domains")?;
265
266 if domains.is_empty() {
267 let empty_value = serde_json::json!({
269 "types": [],
270 "queries": [],
271 "mutations": []
272 });
273 return Self::merge_values(&empty_value, &toml_schema);
274 }
275
276 let mut all_types = Vec::new();
277 let mut all_queries = Vec::new();
278 let mut all_mutations = Vec::new();
279
280 for domain in domains {
281 for filename in ["types.json", "queries.json", "mutations.json"] {
282 let path = domain.path.join(filename);
283 if path.exists() {
284 Self::extend_from_json_file(
285 &path,
286 &mut all_types,
287 &mut all_queries,
288 &mut all_mutations,
289 )?;
290 }
291 }
292 }
293
294 let types_value = serde_json::json!({
295 "types": all_types,
296 "queries": all_queries,
297 "mutations": all_mutations,
298 });
299
300 Self::merge_values(&types_value, &toml_schema)
302 }
303
304 pub fn merge_with_includes(toml_path: &str) -> Result<IntermediateSchema> {
318 let toml_schema = TomlSchema::from_file(toml_path)
319 .context(format!("Failed to load TOML from {toml_path}"))?;
320
321 toml_schema.validate()?;
322
323 let types_value = if toml_schema.includes.is_empty() {
325 serde_json::json!({
327 "types": [],
328 "queries": [],
329 "mutations": []
330 })
331 } else {
332 let resolved = toml_schema
333 .includes
334 .resolve_globs()
335 .context("Failed to resolve glob patterns in schema.includes")?;
336
337 let type_files: Vec<std::path::PathBuf> = resolved.types;
339 let mut merged_types = if type_files.is_empty() {
340 serde_json::json!({
341 "types": [],
342 "queries": [],
343 "mutations": []
344 })
345 } else {
346 crate::schema::MultiFileLoader::load_from_paths(&type_files)
347 .context("Failed to load type files")?
348 };
349
350 if !resolved.queries.is_empty() {
352 let loaded = crate::schema::MultiFileLoader::load_from_paths(&resolved.queries)
353 .context("Failed to load query files")?;
354 let new_items =
355 loaded.get("queries").and_then(Value::as_array).cloned().unwrap_or_default();
356 if let Some(Value::Array(existing)) = merged_types.get_mut("queries") {
357 existing.extend(new_items);
358 }
359 }
360
361 if !resolved.mutations.is_empty() {
363 let loaded = crate::schema::MultiFileLoader::load_from_paths(&resolved.mutations)
364 .context("Failed to load mutation files")?;
365 let new_items =
366 loaded.get("mutations").and_then(Value::as_array).cloned().unwrap_or_default();
367 if let Some(Value::Array(existing)) = merged_types.get_mut("mutations") {
368 existing.extend(new_items);
369 }
370 }
371
372 merged_types
373 };
374
375 Self::merge_values(&types_value, &toml_schema)
377 }
378
379 #[allow(clippy::cognitive_complexity)] fn merge_values(types_value: &Value, toml_schema: &TomlSchema) -> Result<IntermediateSchema> {
382 if toml_schema.queries.contains_key("defaults") {
384 anyhow::bail!(
385 "Found a query definition named 'defaults' under [queries.defaults]. \
386 Did you mean [query_defaults] to set global auto-param defaults?\n\
387 If you intended a query called 'defaults', rename it to avoid confusion."
388 );
389 }
390
391 let mut types_array: Vec<Value> = Vec::new();
394 let mut queries_array: Vec<Value> = Vec::new();
395 let mut mutations_array: Vec<Value> = Vec::new();
396
397 if let Some(types_obj) = types_value.get("types") {
399 match types_obj {
400 Value::Array(types_list) => {
402 for type_item in types_list {
403 if let Some(type_name) = type_item.get("name").and_then(|v| v.as_str()) {
404 let mut enriched_type = type_item.clone();
405 if let Some(toml_type) = toml_schema.types.get(type_name) {
406 Self::enrich_type_from_toml(&mut enriched_type, toml_type);
407 }
408 types_array.push(enriched_type);
409 }
410 }
411 },
412 Value::Object(types_map) => {
414 for (type_name, type_value) in types_map {
415 let mut enriched_type = type_value.clone();
416 enriched_type["name"] = json!(type_name);
417
418 if let Some(Value::Object(fields_map)) = enriched_type.get("fields") {
420 let fields_array: Vec<Value> = fields_map
421 .iter()
422 .map(|(field_name, field_value)| {
423 let mut field = field_value.clone();
424 field["name"] = json!(field_name);
425 field
426 })
427 .collect();
428 enriched_type["fields"] = json!(fields_array);
429 }
430
431 if let Some(toml_type) = toml_schema.types.get(type_name) {
432 Self::enrich_type_from_toml(&mut enriched_type, toml_type);
433 }
434
435 types_array.push(enriched_type);
436 }
437 },
438 _ => {},
439 }
440 }
441
442 let existing_type_names: std::collections::HashSet<_> = types_array
444 .iter()
445 .filter_map(|t| t.get("name").and_then(|v| v.as_str()).map(str::to_string))
446 .collect();
447
448 for (type_name, toml_type) in &toml_schema.types {
449 if !existing_type_names.contains(type_name) {
450 types_array.push(json!({
451 "name": type_name,
452 "sql_source": toml_type.sql_source,
453 "description": toml_type.description,
454 "fields": toml_type.fields.iter().map(|(fname, fdef)| {
455 let mut field = json!({
456 "name": fname,
457 "type": fdef.field_type,
458 "nullable": fdef.nullable,
459 "description": fdef.description,
460 });
461 if let Some(ref h) = fdef.hierarchy {
462 field["hierarchy"] = json!(h);
463 }
464 field
465 }).collect::<Vec<_>>(),
466 }));
467 }
468 }
469
470 if let Some(Value::Array(queries_list)) = types_value.get("queries") {
471 queries_array.clone_from(queries_list);
472 }
473
474 for (query_name, toml_query) in &toml_schema.queries {
476 queries_array.push(json!({
477 "name": query_name,
478 "return_type": toml_query.return_type,
479 "returns_list": toml_query.return_array,
480 "sql_source": toml_query.sql_source,
481 "description": toml_query.description,
482 "args": toml_query.args.iter().map(|arg| json!({
483 "name": arg.name,
484 "type": arg.arg_type,
485 "required": arg.required,
486 "default": arg.default,
487 "description": arg.description,
488 })).collect::<Vec<_>>(),
489 }));
490 }
491
492 if let Some(Value::Array(mutations_list)) = types_value.get("mutations") {
493 mutations_array.clone_from(mutations_list);
494 }
495
496 for (mutation_name, toml_mutation) in &toml_schema.mutations {
498 let sql_source = resolve_mutation_sql_source(
499 mutation_name,
500 toml_mutation.sql_source.as_deref(),
501 &toml_mutation.operation,
502 &toml_mutation.return_type,
503 toml_schema.crud.as_ref(),
504 )?;
505 mutations_array.push(json!({
506 "name": mutation_name,
507 "return_type": toml_mutation.return_type,
508 "sql_source": sql_source,
509 "operation": toml_mutation.operation,
510 "input_style": toml_mutation.input_style,
511 "changelog_pre_image": toml_mutation.changelog_pre_image,
512 "description": toml_mutation.description,
513 "args": toml_mutation.args.iter().map(|arg| json!({
514 "name": arg.name,
515 "type": arg.arg_type,
516 "required": arg.required,
517 "default": arg.default,
518 "description": arg.description,
519 })).collect::<Vec<_>>(),
520 }));
521 }
522
523 let mut merged = serde_json::json!({
525 "version": "2.0.0",
526 "types": types_array,
527 "queries": queries_array,
528 "mutations": mutations_array,
529 });
530
531 if let Some(pkce) = &toml_schema.security.pkce {
533 if pkce.enabled {
534 let enc_enabled =
535 toml_schema.security.state_encryption.as_ref().is_some_and(|e| e.enabled);
536 if !enc_enabled {
537 tracing::warn!(
538 "pkce.enabled = true but state_encryption.enabled = false. \
539 PKCE state will be stored unencrypted. \
540 Set [security.state_encryption] enabled = true for production."
541 );
542 }
543 }
544 }
545
546 merged["security"] = json!({
548 "default_policy": toml_schema.security.default_policy,
549 "rules": toml_schema.security.rules.iter().map(|r| json!({
550 "name": r.name,
551 "rule": r.rule,
552 "description": r.description,
553 "cacheable": r.cacheable,
554 "cache_ttl_seconds": r.cache_ttl_seconds,
555 })).collect::<Vec<_>>(),
556 "policies": toml_schema.security.policies.iter().map(|p| json!({
557 "name": p.name,
558 "type": p.policy_type,
559 "rule": p.rule,
560 "roles": p.roles,
561 "strategy": p.strategy,
562 "attributes": p.attributes,
563 "description": p.description,
564 "cache_ttl_seconds": p.cache_ttl_seconds,
565 })).collect::<Vec<_>>(),
566 "field_auth": toml_schema.security.field_auth.iter().map(|fa| json!({
567 "type_name": fa.type_name,
568 "field_name": fa.field_name,
569 "policy": fa.policy,
570 })).collect::<Vec<_>>(),
571 "enterprise": json!({
572 "rate_limiting_enabled": toml_schema.security.enterprise.rate_limiting_enabled,
573 "auth_endpoint_max_requests": toml_schema.security.enterprise.auth_endpoint_max_requests,
574 "auth_endpoint_window_seconds": toml_schema.security.enterprise.auth_endpoint_window_seconds,
575 "audit_logging_enabled": toml_schema.security.enterprise.audit_logging_enabled,
576 "audit_log_backend": toml_schema.security.enterprise.audit_log_backend,
577 "audit_retention_days": toml_schema.security.enterprise.audit_retention_days,
578 "error_sanitization": toml_schema.security.enterprise.error_sanitization,
579 "hide_implementation_details": toml_schema.security.enterprise.hide_implementation_details,
580 "constant_time_comparison": toml_schema.security.enterprise.constant_time_comparison,
581 "pkce_enabled": toml_schema.security.enterprise.pkce_enabled,
582 }),
583 "error_sanitization": toml_schema.security.error_sanitization,
584 "rate_limiting": toml_schema.security.rate_limiting,
585 "state_encryption": toml_schema.security.state_encryption,
586 "pkce": toml_schema.security.pkce,
587 "api_keys": toml_schema.security.api_keys,
588 "token_revocation": toml_schema.security.token_revocation,
589 "trusted_documents": toml_schema.security.trusted_documents,
590 "persisted_queries_only": toml_schema.security.persisted_queries_only,
591 });
592
593 if toml_schema.observers.enabled
595 || toml_schema.observers.redis_url.is_some()
596 || toml_schema.observers.nats_url.is_some()
597 {
598 if toml_schema.observers.backend == "nats" && toml_schema.observers.nats_url.is_none() {
599 tracing::warn!(
600 "observers.backend is \"nats\" but observers.nats_url is not set; \
601 the runtime will require FRAISEQL_NATS_URL to be configured"
602 );
603 }
604 merged["observers_config"] = json!({
605 "enabled": toml_schema.observers.enabled,
606 "backend": toml_schema.observers.backend,
607 "redis_url": toml_schema.observers.redis_url,
608 "nats_url": toml_schema.observers.nats_url,
609 "handlers": toml_schema.observers.handlers.iter().map(|h| json!({
610 "name": h.name,
611 "event": h.event,
612 "action": h.action,
613 "webhook_url": h.webhook_url,
614 "retry_strategy": h.retry_strategy,
615 "max_retries": h.max_retries,
616 "description": h.description,
617 })).collect::<Vec<_>>(),
618 });
619 }
620
621 if toml_schema.federation.enabled {
623 merged["federation_config"] = serde_json::to_value(&toml_schema.federation)
624 .context("Failed to serialize federation config")?;
625 }
626
627 let subs_json = serde_json::to_value(&toml_schema.subscriptions)
629 .context("Failed to serialize subscriptions config")?;
630 if subs_json != serde_json::json!({}) {
631 merged["subscriptions_config"] = subs_json;
632 }
633
634 let val_json = serde_json::to_value(&toml_schema.validation)
636 .context("Failed to serialize validation config")?;
637 if val_json != serde_json::json!({}) {
638 merged["validation_config"] = val_json;
639 }
640
641 if toml_schema.debug.enabled {
643 let debug_json = serde_json::to_value(&toml_schema.debug)
644 .context("Failed to serialize debug config")?;
645 merged["debug_config"] = debug_json;
646 }
647
648 if toml_schema.mcp.enabled {
650 merged["mcp_config"] =
651 serde_json::to_value(&toml_schema.mcp).context("Failed to serialize MCP config")?;
652 }
653
654 if toml_schema.rest.enabled {
656 let path = &toml_schema.rest.path;
657 if !path.starts_with('/') {
658 anyhow::bail!("REST config: `path` must start with '/' (got {path:?})");
659 }
660
661 let rest_config: fraiseql_core::schema::RestConfig = toml_schema.rest.clone().into();
662
663 merged["rest_config"] =
664 serde_json::to_value(&rest_config).context("Failed to serialize REST config")?;
665 }
666
667 merged["naming_convention"] = serde_json::to_value(toml_schema.naming_convention)
669 .context("Failed to serialize naming_convention")?;
670
671 if let Some(ref changelog) = toml_schema.changelog {
673 merged["changelog_config"] =
674 serde_json::to_value(changelog).context("Failed to serialize changelog config")?;
675 }
676
677 if let Some(ref hierarchies) = toml_schema.hierarchies {
679 merged["hierarchies_config"] = serde_json::to_value(hierarchies)
680 .context("Failed to serialize hierarchies config")?;
681 }
682
683 let mut schema = serde_json::from_value::<IntermediateSchema>(merged)
685 .context("Failed to convert merged schema to IntermediateSchema")?;
686
687 schema.query_defaults = Some(IntermediateQueryDefaults {
690 where_clause: toml_schema.query_defaults.where_clause,
691 order_by: toml_schema.query_defaults.order_by,
692 limit: toml_schema.query_defaults.limit,
693 offset: toml_schema.query_defaults.offset,
694 });
695
696 Ok(schema)
697 }
698}