Skip to main content

mockql_core/graphql/
minify.rs

1// Copyright 2026 Expedia, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Schema minification helpers used to keep provider prompts compact.
16
17use apollo_compiler::Name;
18use apollo_compiler::Node;
19use apollo_compiler::ast::DirectiveList;
20use apollo_compiler::ast::InputValueDefinition;
21use apollo_compiler::collections::IndexMap;
22use apollo_compiler::collections::IndexSet;
23use apollo_compiler::schema::Component;
24use apollo_compiler::schema::ComponentName;
25use apollo_compiler::schema::EnumType;
26use apollo_compiler::schema::ExtendedType;
27use apollo_compiler::schema::FieldDefinition;
28use apollo_compiler::schema::InputObjectType;
29use apollo_compiler::schema::InterfaceType;
30use apollo_compiler::schema::ObjectType;
31use apollo_compiler::schema::ScalarType;
32use apollo_compiler::schema::Type;
33use apollo_compiler::schema::UnionType;
34use std::collections::HashMap;
35use std::sync::OnceLock;
36/// Converts schema types into the compact prompt format used by `mockql`.
37pub trait MinifyExt {
38  /// Renders the receiver into the compact prompt schema representation.
39  fn minify(&self) -> String;
40}
41
42impl MinifyExt for ExtendedType {
43  fn minify(&self) -> String {
44    match self {
45      ExtendedType::Scalar(scalar_type) => minify_scalar(scalar_type),
46      ExtendedType::Object(object_type) => minify_object(object_type),
47      ExtendedType::Interface(interface_type) => minify_interface(interface_type),
48      ExtendedType::Union(union_type) => minify_union(union_type),
49      ExtendedType::Enum(enum_type) => minify_enum(enum_type),
50      ExtendedType::InputObject(input_object_type) => minify_input_object(input_object_type),
51    }
52  }
53}
54
55fn minify_scalar(scalar_type: &ScalarType) -> String {
56  shorten_scalar_names(scalar_type.name.as_str()).to_string()
57}
58
59fn minify_object(object_type: &ObjectType) -> String {
60  let fields = minify_fields(&object_type.fields);
61  let type_name = format_type_name_with_description(&object_type.name, &object_type.description);
62  let interfaces = format_interfaces(&object_type.implements_interfaces);
63
64  if interfaces.is_empty() {
65    format!("T:{type_name}:{fields}")
66  } else {
67    format!("T:{type_name}<{interfaces}>:{fields}")
68  }
69}
70
71fn minify_interface(interface_type: &InterfaceType) -> String {
72  let fields = minify_fields(&interface_type.fields);
73  let type_name = format_type_name_with_description(&interface_type.name, &interface_type.description);
74  format!("F:{type_name}:{fields}")
75}
76
77fn minify_union(union_type: &UnionType) -> String {
78  let member_types = union_type
79    .members
80    .iter()
81    .map(|member| member.as_str())
82    .collect::<Vec<&str>>()
83    .join(",");
84  let type_name = format_type_name_with_description(&union_type.name, &union_type.description);
85  format!("U:{type_name}:{member_types}")
86}
87
88fn minify_enum(enum_type: &EnumType) -> String {
89  let values = enum_type
90    .values
91    .keys()
92    .map(apollo_compiler::Name::as_str)
93    .collect::<Vec<&str>>()
94    .join(",");
95  let type_name = format_type_name_with_description(&enum_type.name, &enum_type.description);
96  format!("E:{type_name}:{values}")
97}
98
99fn minify_input_object(input_object_type: &InputObjectType) -> String {
100  let fields = minify_input_fields(&input_object_type.fields);
101  let type_name = format_type_name_with_description(&input_object_type.name, &input_object_type.description);
102  format!("I:{type_name}:{fields}")
103}
104
105// We should only minify directives that assist the LLM in understanding the schema. This includes @deprecated
106fn minify_directives(directives: &DirectiveList) -> String {
107  let mut result = String::new();
108
109  static DIRECTIVES_TO_MINIFY: OnceLock<HashMap<&str, &str>> = OnceLock::new();
110  let directives_to_minify = DIRECTIVES_TO_MINIFY.get_or_init(|| HashMap::from([("deprecated", "D")]));
111
112  for directive in directives {
113    if let Some(minified_name) = directives_to_minify.get(directive.name.as_str()) {
114      // Since we're only handling @deprecated right now we can just add the reason and minify it.
115      // We should handle this more generically in the future.
116      if !directive.arguments.is_empty()
117        && let Some(reason) = directive
118          .arguments
119          .iter()
120          .find(|a| a.name == "reason")
121          .and_then(|a| a.value.as_str())
122      {
123        result.push_str(&format!("@{}(\"{}\")", minified_name, normalize_description(reason)));
124      } else {
125        result.push_str(&format!("@{minified_name}"));
126      }
127    }
128  }
129  result
130}
131
132fn minify_fields(fields: &IndexMap<Name, Component<FieldDefinition>>) -> String {
133  let mut result = String::new();
134
135  for (field_name, field) in fields {
136    // Add description if present
137    if let Some(desc) = field.description.as_ref() {
138      result.push_str(&format!("\"{}\"", normalize_description(desc)));
139    }
140
141    // Add field name
142    result.push_str(field_name.as_str());
143
144    // Add arguments if present
145    if !field.arguments.is_empty() {
146      result.push('(');
147      result.push_str(&minify_arguments(&field.arguments));
148      result.push(')');
149    }
150
151    // Add field type
152    result.push(':');
153    result.push_str(&type_name(&field.ty));
154    result.push_str(&minify_directives(&field.directives));
155
156    result.push(',');
157  }
158
159  // Remove trailing comma
160  if !result.is_empty() {
161    result.pop();
162  }
163
164  result
165}
166
167fn minify_input_fields(fields: &IndexMap<Name, Component<InputValueDefinition>>) -> String {
168  let mut result = String::new();
169
170  for (field_name, field) in fields {
171    // Add description if present
172    if let Some(desc) = field.description.as_ref() {
173      result.push_str(&format!("\"{}\"", normalize_description(desc)));
174    }
175
176    // Add field name and type
177    result.push_str(field_name.as_str());
178    result.push(':');
179    result.push_str(&type_name(&field.ty));
180    result.push_str(&minify_directives(&field.directives));
181    result.push(',');
182  }
183
184  // Remove trailing comma
185  if !result.is_empty() {
186    result.pop();
187  }
188
189  result
190}
191
192fn minify_arguments(arguments: &[Node<InputValueDefinition>]) -> String {
193  arguments
194    .iter()
195    .map(|arg| {
196      if let Some(desc) = arg.description.as_ref() {
197        format!(
198          "\"{}\"{}:{}{}",
199          normalize_description(desc),
200          arg.name.as_str(),
201          type_name(&arg.ty),
202          minify_directives(&arg.directives)
203        )
204      } else {
205        format!(
206          "{}:{}{}",
207          arg.name.as_str(),
208          type_name(&arg.ty),
209          minify_directives(&arg.directives)
210        )
211      }
212    })
213    .collect::<Vec<String>>()
214    .join(",")
215}
216
217fn format_type_name_with_description(name: &Name, description: &Option<Node<str>>) -> String {
218  if let Some(desc) = description.as_ref() {
219    format!("\"{}\"{}", normalize_description(desc), name)
220  } else {
221    name.to_string()
222  }
223}
224
225fn format_interfaces(interfaces: &IndexSet<ComponentName>) -> String {
226  interfaces
227    .iter()
228    .map(|interface| interface.as_str())
229    .collect::<Vec<&str>>()
230    .join(",")
231}
232
233fn type_name(ty: &Type) -> String {
234  match ty {
235    Type::List(inner) => format!("[{}]", type_name(inner)),
236    Type::NonNullList(inner) => format!("[{}]!", type_name(inner)),
237    #[expect(clippy::useless_format, reason = "keeps formatting consistent across match arms")]
238    Type::Named(name) => format!("{}", shorten_scalar_names(name.as_str())),
239    Type::NonNullNamed(name) => format!("{}!", shorten_scalar_names(name.as_str())),
240  }
241}
242
243fn shorten_scalar_names(name: &str) -> &str {
244  match name {
245    "String" => "s",
246    "Int" => "i",
247    "Float" => "f",
248    "Boolean" => "b",
249    "ID" => "d",
250    _ => name,
251  }
252}
253
254/// Normalizes description formatting by removing insignificant whitespace.
255fn normalize_description(desc: &str) -> String {
256  // LLMs can typically process descriptions just fine without whitespace
257  static WHITESPACE_PATTERN: OnceLock<regex::Regex> = OnceLock::new();
258  let re = WHITESPACE_PATTERN.get_or_init(|| regex::Regex::new(r"\s+").expect("regex pattern compiles"));
259  re.replace_all(desc, "").to_string()
260}
261
262#[cfg(test)]
263mod tests {
264  use crate::graphql::minify::MinifyExt;
265  use apollo_compiler::schema::Schema;
266
267  #[test]
268  fn minify_produces_compressed_schema() {
269    let sdl = include_str!("schema.graphql");
270    let schema = Schema::parse_and_validate(sdl, "schema.graphql").expect("schema should be valid");
271
272    let minified_schema = schema
273      .types
274      .iter()
275      .map(|(_, type_)| format!("{}: {}", type_.name().as_str(), type_.minify()))
276      .collect::<Vec<String>>()
277      .join("\n");
278
279    insta::with_settings!({snapshot_path => "snapshots/minify"}, {
280      insta::assert_snapshot!(minified_schema);
281    });
282  }
283}