Skip to main content

fraiseql_cli/schema/
merger.rs

1//! Schema merger - combines language-generated types.json with TOML configuration
2//!
3//! This module merges:
4//! - types.json: Generated by language implementations (Python, Go, etc.)
5//! - fraiseql.toml: Configuration (security, federation, observers, caching, etc.)
6//!
7//! Result: Complete IntermediateSchema ready for compilation
8
9use 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
20/// Convert a PascalCase GraphQL type name to a `snake_case` entity name.
21///
22/// Used to derive the entity segment for CRUD naming templates:
23/// `"UserProfile"` → `"user_profile"`, `"User"` → `"user"`.
24pub(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
35/// Resolve the `sql_source` for a TOML-defined mutation.
36///
37/// Precedence (highest first):
38/// 1. Explicit `sql_source` on the mutation.
39/// 2. `[crud]` naming config resolved from `operation` + entity derived from `return_type`.
40///
41/// Returns an error when neither is available, naming the offending mutation.
42fn 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
65/// Schema merger combining language types and TOML config
66pub struct SchemaMerger;
67
68impl SchemaMerger {
69    /// Merge types.json file with TOML configuration
70    ///
71    /// # Arguments
72    /// * `types_path` - Path to types.json (from language implementation)
73    /// * `toml_path` - Path to fraiseql.toml (configuration)
74    ///
75    /// # Returns
76    /// Combined `IntermediateSchema`.
77    ///
78    /// # Errors
79    ///
80    /// Returns an error if either file cannot be read or parsed, or if the
81    /// merged result cannot be deserialized into an `IntermediateSchema`.
82    pub fn merge_files(types_path: &str, toml_path: &str) -> Result<IntermediateSchema> {
83        // Load types.json
84        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        // Load TOML
90        let toml_schema = TomlSchema::from_file(toml_path)
91            .context(format!("Failed to load TOML from {toml_path}"))?;
92
93        // Note: TOML validation is skipped here because queries may reference types
94        // from types.json (not yet loaded). Validation happens in the compiler after merge.
95
96        // Merge
97        Self::merge_values(&types_value, &toml_schema)
98    }
99
100    /// Merge TOML-only (no types.json)
101    ///
102    /// # Arguments
103    /// * `toml_path` - Path to fraiseql.toml with inline type definitions
104    ///
105    /// # Returns
106    /// `IntermediateSchema` from TOML definitions.
107    ///
108    /// # Errors
109    ///
110    /// Returns an error if the TOML file cannot be loaded, if validation fails,
111    /// or if the merged result cannot be deserialized into an `IntermediateSchema`.
112    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        // Convert TOML to intermediate schema
119        let types_value = toml_schema.to_intermediate_schema();
120        Self::merge_values(&types_value, &toml_schema)
121    }
122
123    /// Merge from directory with auto-discovery
124    ///
125    /// # Arguments
126    /// * `toml_path` - Path to fraiseql.toml (configuration)
127    /// * `schema_dir` - Path to directory containing schema files
128    ///
129    /// # Returns
130    /// `IntermediateSchema` from loaded files + TOML definitions.
131    ///
132    /// # Errors
133    ///
134    /// Returns an error if either file cannot be loaded or validated, if the
135    /// directory cannot be read, or if the merged result cannot be deserialized.
136    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        // Load all files from directory
143        let types_value = crate::schema::MultiFileLoader::load_from_directory(schema_dir)
144            .context(format!("Failed to load schema from directory {schema_dir}"))?;
145
146        // Merge with TOML definitions
147        Self::merge_values(&types_value, &toml_schema)
148    }
149
150    /// Load a named section from a set of files, returning `None` when the list is empty.
151    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    /// Parse a JSON file and extend the target vectors with its `types`, `queries`, and
162    /// `mutations` arrays. Missing keys are silently skipped.
163    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    /// Apply TOML metadata (`sql_source`, `description`) to a type JSON object in place.
186    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    /// Merge explicit file lists
197    ///
198    /// # Arguments
199    /// * `toml_path` - Path to fraiseql.toml (configuration)
200    /// * `type_files` - Vector of type file paths
201    /// * `query_files` - Vector of query file paths
202    /// * `mutation_files` - Vector of mutation file paths
203    ///
204    /// # Returns
205    /// IntermediateSchema from loaded files + TOML definitions
206    ///
207    /// # Errors
208    ///
209    /// Returns an error if the TOML file cannot be loaded or validated, or if any
210    /// of the type/query/mutation files fail to load or parse.
211    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    /// Merge from domains (domain-based organization)
242    ///
243    /// # Arguments
244    /// * `toml_path` - Path to fraiseql.toml with domain_discovery enabled
245    ///
246    /// # Returns
247    /// `IntermediateSchema` from all domains (types.json, queries.json, mutations.json).
248    ///
249    /// # Errors
250    ///
251    /// Returns an error if the TOML cannot be loaded or validated, if domain
252    /// discovery fails, if any domain file cannot be parsed, or if the merged
253    /// result cannot be deserialized.
254    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        // Resolve domains from configuration
261        let domains = toml_schema
262            .domain_discovery
263            .resolve_domains()
264            .context("Failed to discover domains")?;
265
266        if domains.is_empty() {
267            // No domains found, return empty schema merged with TOML definitions
268            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        // Merge with TOML definitions
301        Self::merge_values(&types_value, &toml_schema)
302    }
303
304    /// Merge with TOML includes (glob patterns for schema files)
305    ///
306    /// # Arguments
307    /// * `toml_path` - Path to fraiseql.toml with schema.includes section
308    ///
309    /// # Returns
310    /// `IntermediateSchema` from loaded files + TOML definitions.
311    ///
312    /// # Errors
313    ///
314    /// Returns an error if the TOML cannot be loaded or validated, if any glob
315    /// pattern is invalid, if a matched file cannot be parsed, or if the merged
316    /// result cannot be deserialized.
317    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        // If includes are specified, load and merge files
324        let types_value = if toml_schema.includes.is_empty() {
325            // No includes specified, use empty schema
326            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            // Load all type files
338            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            // Load and merge query files
351            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            // Load and merge mutation files
362            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        // Merge with TOML definitions
376        Self::merge_values(&types_value, &toml_schema)
377    }
378
379    /// Merge JSON types with TOML schema
380    #[allow(clippy::cognitive_complexity)] // Reason: deep merge of two schema formats with many field-level transformations
381    fn merge_values(types_value: &Value, toml_schema: &TomlSchema) -> Result<IntermediateSchema> {
382        // #612: reject accepted-but-unconsumed config on EVERY compile path. The full
383        // `TomlSchema::validate()` is skipped on the `--types` path (`merge_files`), but
384        // these sections are self-contained and must never compile silently.
385        toml_schema.reject_accepted_but_unconsumed_config()?;
386
387        // Typo guard: [queries.defaults] is a common mistake for [query_defaults].
388        if toml_schema.queries.contains_key("defaults") {
389            anyhow::bail!(
390                "Found a query definition named 'defaults' under [queries.defaults]. \
391                 Did you mean [query_defaults] to set global auto-param defaults?\n\
392                 If you intended a query called 'defaults', rename it to avoid confusion."
393            );
394        }
395
396        // Start with arrays for types, queries, mutations (not objects!)
397        // This matches IntermediateSchema structure which uses Vec<T>
398        let mut types_array: Vec<Value> = Vec::new();
399        let mut queries_array: Vec<Value> = Vec::new();
400        let mut mutations_array: Vec<Value> = Vec::new();
401
402        // Process types from types.json (comes as array from language SDKs)
403        if let Some(types_obj) = types_value.get("types") {
404            match types_obj {
405                // Handle array format (from language SDKs)
406                Value::Array(types_list) => {
407                    for type_item in types_list {
408                        if let Some(type_name) = type_item.get("name").and_then(|v| v.as_str()) {
409                            let mut enriched_type = type_item.clone();
410                            if let Some(toml_type) = toml_schema.types.get(type_name) {
411                                Self::enrich_type_from_toml(&mut enriched_type, toml_type);
412                            }
413                            types_array.push(enriched_type);
414                        }
415                    }
416                },
417                // Handle object format (from TOML-only, for backward compatibility)
418                Value::Object(types_map) => {
419                    for (type_name, type_value) in types_map {
420                        let mut enriched_type = type_value.clone();
421                        enriched_type["name"] = json!(type_name);
422
423                        // Convert fields from object to array format if needed
424                        if let Some(Value::Object(fields_map)) = enriched_type.get("fields") {
425                            let fields_array: Vec<Value> = fields_map
426                                .iter()
427                                .map(|(field_name, field_value)| {
428                                    let mut field = field_value.clone();
429                                    field["name"] = json!(field_name);
430                                    field
431                                })
432                                .collect();
433                            enriched_type["fields"] = json!(fields_array);
434                        }
435
436                        if let Some(toml_type) = toml_schema.types.get(type_name) {
437                            Self::enrich_type_from_toml(&mut enriched_type, toml_type);
438                        }
439
440                        types_array.push(enriched_type);
441                    }
442                },
443                _ => {},
444            }
445        }
446
447        // Add types from TOML that aren't already in types_array
448        let existing_type_names: std::collections::HashSet<_> = types_array
449            .iter()
450            .filter_map(|t| t.get("name").and_then(|v| v.as_str()).map(str::to_string))
451            .collect();
452
453        for (type_name, toml_type) in &toml_schema.types {
454            if !existing_type_names.contains(type_name) {
455                types_array.push(json!({
456                    "name": type_name,
457                    "sql_source": toml_type.sql_source,
458                    "description": toml_type.description,
459                    "fields": toml_type.fields.iter().map(|(fname, fdef)| {
460                        let mut field = json!({
461                            "name": fname,
462                            "type": fdef.field_type,
463                            "nullable": fdef.nullable,
464                            "description": fdef.description,
465                        });
466                        if let Some(ref h) = fdef.hierarchy {
467                            field["hierarchy"] = json!(h);
468                        }
469                        field
470                    }).collect::<Vec<_>>(),
471                }));
472            }
473        }
474
475        if let Some(Value::Array(queries_list)) = types_value.get("queries") {
476            queries_array.clone_from(queries_list);
477        }
478
479        // Add queries from TOML
480        for (query_name, toml_query) in &toml_schema.queries {
481            queries_array.push(json!({
482                "name": query_name,
483                "return_type": toml_query.return_type,
484                "returns_list": toml_query.return_array,
485                "sql_source": toml_query.sql_source,
486                "description": toml_query.description,
487                "args": toml_query.args.iter().map(|arg| json!({
488                    "name": arg.name,
489                    "type": arg.arg_type,
490                    "required": arg.required,
491                    "default": arg.default,
492                    "description": arg.description,
493                })).collect::<Vec<_>>(),
494            }));
495        }
496
497        if let Some(Value::Array(mutations_list)) = types_value.get("mutations") {
498            mutations_array.clone_from(mutations_list);
499        }
500
501        // Add mutations from TOML
502        for (mutation_name, toml_mutation) in &toml_schema.mutations {
503            let sql_source = resolve_mutation_sql_source(
504                mutation_name,
505                toml_mutation.sql_source.as_deref(),
506                &toml_mutation.operation,
507                &toml_mutation.return_type,
508                toml_schema.crud.as_ref(),
509            )?;
510            mutations_array.push(json!({
511                "name": mutation_name,
512                "return_type": toml_mutation.return_type,
513                "sql_source": sql_source,
514                "operation": toml_mutation.operation,
515                "input_style": toml_mutation.input_style,
516                "changelog_pre_image": toml_mutation.changelog_pre_image,
517                "cascade": toml_mutation.cascade,
518                "description": toml_mutation.description,
519                "args": toml_mutation.args.iter().map(|arg| json!({
520                    "name": arg.name,
521                    "type": arg.arg_type,
522                    "required": arg.required,
523                    "default": arg.default,
524                    "description": arg.description,
525                })).collect::<Vec<_>>(),
526            }));
527        }
528
529        // Build merged schema with arrays
530        let mut merged = serde_json::json!({
531            "version": "2.0.0",
532            "types": types_array,
533            "queries": queries_array,
534            "mutations": mutations_array,
535        });
536
537        // Warn when PKCE is enabled without state encryption (insecure configuration).
538        if let Some(pkce) = &toml_schema.security.pkce {
539            if pkce.enabled {
540                let enc_enabled =
541                    toml_schema.security.state_encryption.as_ref().is_some_and(|e| e.enabled);
542                if !enc_enabled {
543                    tracing::warn!(
544                        "pkce.enabled = true but state_encryption.enabled = false. \
545                         PKCE state will be stored unencrypted. \
546                         Set [security.state_encryption] enabled = true for production."
547                    );
548                }
549            }
550        }
551
552        // Add security configuration if available in TOML
553        merged["security"] = json!({
554            "default_policy": toml_schema.security.default_policy,
555            "rules": toml_schema.security.rules.iter().map(|r| json!({
556                "name": r.name,
557                "rule": r.rule,
558                "description": r.description,
559                "cacheable": r.cacheable,
560                "cache_ttl_seconds": r.cache_ttl_seconds,
561            })).collect::<Vec<_>>(),
562            "policies": toml_schema.security.policies.iter().map(|p| json!({
563                "name": p.name,
564                "type": p.policy_type,
565                "rule": p.rule,
566                "roles": p.roles,
567                "strategy": p.strategy,
568                "attributes": p.attributes,
569                "description": p.description,
570                "cache_ttl_seconds": p.cache_ttl_seconds,
571            })).collect::<Vec<_>>(),
572            "field_auth": toml_schema.security.field_auth.iter().map(|fa| json!({
573                "type_name": fa.type_name,
574                "field_name": fa.field_name,
575                "policy": fa.policy,
576            })).collect::<Vec<_>>(),
577            "enterprise": json!({
578                "rate_limiting_enabled": toml_schema.security.enterprise.rate_limiting_enabled,
579                "auth_endpoint_max_requests": toml_schema.security.enterprise.auth_endpoint_max_requests,
580                "auth_endpoint_window_seconds": toml_schema.security.enterprise.auth_endpoint_window_seconds,
581                "audit_logging_enabled": toml_schema.security.enterprise.audit_logging_enabled,
582                "audit_log_backend": toml_schema.security.enterprise.audit_log_backend,
583                "audit_retention_days": toml_schema.security.enterprise.audit_retention_days,
584                "error_sanitization": toml_schema.security.enterprise.error_sanitization,
585                "hide_implementation_details": toml_schema.security.enterprise.hide_implementation_details,
586                "constant_time_comparison": toml_schema.security.enterprise.constant_time_comparison,
587                "pkce_enabled": toml_schema.security.enterprise.pkce_enabled,
588            }),
589            "error_sanitization": toml_schema.security.error_sanitization,
590            "rate_limiting": toml_schema.security.rate_limiting,
591            "state_encryption": toml_schema.security.state_encryption,
592            "pkce": toml_schema.security.pkce,
593            "api_keys": toml_schema.security.api_keys,
594            "token_revocation": toml_schema.security.token_revocation,
595            "trusted_documents": toml_schema.security.trusted_documents,
596            "persisted_queries_only": toml_schema.security.persisted_queries_only,
597        });
598
599        // Embed observers configuration if enabled or if any backend URL is set
600        if toml_schema.observers.enabled
601            || toml_schema.observers.redis_url.is_some()
602            || toml_schema.observers.nats_url.is_some()
603        {
604            if toml_schema.observers.backend == "nats" && toml_schema.observers.nats_url.is_none() {
605                tracing::warn!(
606                    "observers.backend is \"nats\" but observers.nats_url is not set; \
607                     the runtime will require FRAISEQL_NATS_URL to be configured"
608                );
609            }
610            merged["observers_config"] = json!({
611                "enabled": toml_schema.observers.enabled,
612                "backend": toml_schema.observers.backend,
613                "redis_url": toml_schema.observers.redis_url,
614                "nats_url": toml_schema.observers.nats_url,
615                "handlers": toml_schema.observers.handlers.iter().map(|h| json!({
616                    "name": h.name,
617                    "event": h.event,
618                    "action": h.action,
619                    "webhook_url": h.webhook_url,
620                    "retry_strategy": h.retry_strategy,
621                    "max_retries": h.max_retries,
622                    "description": h.description,
623                })).collect::<Vec<_>>(),
624            });
625        }
626
627        // Embed federation configuration if enabled. Lower the TOML config into the
628        // compiled (`fraiseql_core`) shape explicitly so the merged JSON matches what
629        // the converter/runtime deserialize — a raw passthrough silently dropped
630        // `service_name`/`version` and the `per_database` → `per_entity` overrides.
631        if toml_schema.federation.enabled {
632            merged["federation_config"] =
633                serde_json::to_value(toml_schema.federation.to_compiled())
634                    .context("Failed to serialize federation config")?;
635        }
636
637        // Embed subscriptions configuration (hooks, limits)
638        let subs_json = serde_json::to_value(&toml_schema.subscriptions)
639            .context("Failed to serialize subscriptions config")?;
640        if subs_json != serde_json::json!({}) {
641            merged["subscriptions_config"] = subs_json;
642        }
643
644        // Embed validation config (depth/complexity limits)
645        let val_json = serde_json::to_value(&toml_schema.validation)
646            .context("Failed to serialize validation config")?;
647        if val_json != serde_json::json!({}) {
648            merged["validation_config"] = val_json;
649        }
650
651        // Embed debug config when enabled
652        if toml_schema.debug.enabled {
653            let debug_json = serde_json::to_value(&toml_schema.debug)
654                .context("Failed to serialize debug config")?;
655            merged["debug_config"] = debug_json;
656        }
657
658        // Embed MCP config when enabled
659        if toml_schema.mcp.enabled {
660            merged["mcp_config"] =
661                serde_json::to_value(&toml_schema.mcp).context("Failed to serialize MCP config")?;
662        }
663
664        // Embed REST config when enabled (with path validation)
665        if toml_schema.rest.enabled {
666            let path = &toml_schema.rest.path;
667            if !path.starts_with('/') {
668                anyhow::bail!("REST config: `path` must start with '/' (got {path:?})");
669            }
670
671            let rest_config: fraiseql_core::schema::RestConfig = toml_schema.rest.clone().into();
672
673            merged["rest_config"] =
674                serde_json::to_value(&rest_config).context("Failed to serialize REST config")?;
675        }
676
677        // Embed naming convention
678        merged["naming_convention"] = serde_json::to_value(toml_schema.naming_convention)
679            .context("Failed to serialize naming_convention")?;
680
681        // Embed changelog GraphQL-exposure config (gating + injection happen in the converter)
682        if let Some(ref changelog) = toml_schema.changelog {
683            merged["changelog_config"] =
684                serde_json::to_value(changelog).context("Failed to serialize changelog config")?;
685        }
686
687        // Embed hierarchy definitions for ID-based ltree operators
688        if let Some(ref hierarchies) = toml_schema.hierarchies {
689            merged["hierarchies_config"] = serde_json::to_value(hierarchies)
690                .context("Failed to serialize hierarchies config")?;
691        }
692
693        // Convert to IntermediateSchema
694        let mut schema = serde_json::from_value::<IntermediateSchema>(merged)
695            .context("Failed to convert merged schema to IntermediateSchema")?;
696
697        // Inject TOML [query_defaults] into the schema so the converter can apply
698        // them as project-wide fallbacks for list-query auto-params.
699        schema.query_defaults = Some(IntermediateQueryDefaults {
700            where_clause: toml_schema.query_defaults.where_clause,
701            order_by:     toml_schema.query_defaults.order_by,
702            limit:        toml_schema.query_defaults.limit,
703            offset:       toml_schema.query_defaults.offset,
704        });
705
706        Ok(schema)
707    }
708}