spikard-cli 0.16.0-rc.1

Command-line interface for building and validating Spikard applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
//! GraphQL Schema Definition Language (SDL) builder.
//!
//! This module consolidates SDL reconstruction logic extracted from all language-specific
//! generators (Python, TypeScript, Ruby, PHP) into a single, language-agnostic builder.
//! Rather than duplicating SDL generation logic across each generator, they can now use
//! `SdlBuilder` to produce consistent GraphQL SDL output.
//!
//! # Overview
//!
//! The `SdlBuilder` struct takes a parsed `GraphQLSchema` and reconstructs the original
//! GraphQL Schema Definition Language as a string. This is essential for:
//!
//! - Embedding SDL in generated code (as type definitions, schema constants, etc.)
//! - Exporting the schema for use with GraphQL tools (Apollo, graphql-core, etc.)
//! - Documenting the resolved schema structure
//!
//! # Example
//!
//! ```ignore
//! use spikard_cli::codegen::graphql::sdl::SdlBuilder;
//! use spikard_cli::codegen::graphql::spec_parser::GraphQLSchema;
//!
//! let builder = SdlBuilder::new(&schema);
//! let sdl = builder.build();
//! println!("{}", sdl);
//! ```
//!
//! # Built-in Type Handling
//!
//! The builder automatically excludes built-in scalar types:
//! - String, Int, Float, Boolean, ID
//! - `DateTime`, Date, Time, JSON, Upload
//!
//! These are assumed to be defined elsewhere in the language runtime or GraphQL library.
//!
//! # Features
//!
//! - **Consistent formatting**: All SDL output follows GraphQL specification formatting
//! - **Description handling**: Preserves type descriptions as `"""..."""` comments
//! - **Deprecation support**: Includes `@deprecated(reason: "...")` directives
//! - **Complete coverage**: Handles Objects, `InputObjects`, Enums, Scalars, Unions, Interfaces
//! - **Field arguments**: Properly formats field arguments with default values

use crate::codegen::graphql::spec_parser::{
    GraphQLEnumValue, GraphQLField, GraphQLInputField, GraphQLSchema, TypeKind,
};

/// Builds GraphQL Schema Definition Language (SDL) from a parsed schema.
///
/// This struct consolidates SDL generation logic across all language generators,
/// producing consistent, spec-compliant SDL output regardless of the target language.
///
/// The builder is language-agnostic; it produces pure GraphQL SDL without any
/// language-specific code generation artifacts.
pub struct SdlBuilder<'a> {
    /// Reference to the parsed GraphQL schema.
    schema: &'a GraphQLSchema,
}

impl<'a> SdlBuilder<'a> {
    /// Create a new SDL builder for the given schema.
    ///
    /// # Arguments
    ///
    /// * `schema` - A reference to the parsed GraphQL schema
    ///
    /// # Returns
    ///
    /// A new `SdlBuilder` instance ready to generate SDL.
    pub const fn new(schema: &'a GraphQLSchema) -> Self {
        Self { schema }
    }

    /// Build and return the complete SDL string.
    ///
    /// This is the main entry point that orchestrates the SDL generation process.
    /// It handles directives, root types (Query, Mutation, Subscription), and all
    /// custom types defined in the schema.
    ///
    /// # Returns
    ///
    /// A formatted GraphQL SDL string.
    pub fn build(&self) -> String {
        let mut sdl = String::new();

        // Add directives first
        sdl.push_str(&self.format_directives());

        // Add Query type
        sdl.push_str(&self.format_queries());

        // Add Mutation type
        sdl.push_str(&self.format_mutations());

        // Add Subscription type
        sdl.push_str(&self.format_subscriptions());

        // Add all custom types
        sdl.push_str(&self.format_types());

        sdl.trim_end().to_string()
    }

    /// Format all directives from the schema.
    fn format_directives(&self) -> String {
        let mut result = String::new();

        for directive in &self.schema.directives {
            if let Some(desc) = &directive.description {
                result.push_str("\"\"\"");
                result.push_str(desc);
                result.push_str("\"\"\"\n");
            }

            result.push_str("directive @");
            result.push_str(&directive.name);

            if !directive.arguments.is_empty() {
                result.push('(');
                for (i, arg) in directive.arguments.iter().enumerate() {
                    if i > 0 {
                        result.push_str(", ");
                    }
                    result.push_str(&arg.name);
                    result.push_str(": ");
                    result.push_str(&self.format_gql_type(
                        &arg.type_name,
                        arg.is_nullable,
                        arg.is_list,
                        arg.list_item_nullable,
                    ));
                    if let Some(default) = &arg.default_value {
                        result.push_str(" = ");
                        result.push_str(default);
                    }
                }
                result.push(')');
            }

            if !directive.locations.is_empty() {
                result.push_str(" on ");
                result.push_str(&directive.locations.join(" | "));
            }
            result.push_str("\n\n");
        }

        result
    }

    /// Format the Query type and its fields.
    fn format_queries(&self) -> String {
        let mut result = String::new();

        if !self.schema.queries.is_empty() {
            result.push_str("type Query {\n");
            for field in &self.schema.queries {
                result.push_str(&self.format_field(field));
            }
            result.push_str("}\n\n");
        }

        result
    }

    /// Format the Mutation type and its fields.
    fn format_mutations(&self) -> String {
        let mut result = String::new();

        if !self.schema.mutations.is_empty() {
            result.push_str("type Mutation {\n");
            for field in &self.schema.mutations {
                result.push_str(&self.format_field(field));
            }
            result.push_str("}\n\n");
        }

        result
    }

    /// Format the Subscription type and its fields.
    fn format_subscriptions(&self) -> String {
        let mut result = String::new();

        if !self.schema.subscriptions.is_empty() {
            result.push_str("type Subscription {\n");
            for field in &self.schema.subscriptions {
                result.push_str(&self.format_field(field));
            }
            result.push_str("}\n\n");
        }

        result
    }

    /// Format all custom types (Objects, Enums, Inputs, Scalars, Unions, Interfaces).
    fn format_types(&self) -> String {
        let mut result = String::new();

        for (type_name, type_def) in &self.schema.types {
            // Skip built-in scalar types
            if matches!(
                type_name.as_str(),
                "String" | "Int" | "Float" | "Boolean" | "ID" | "DateTime" | "Date" | "Time" | "JSON" | "Upload"
            ) {
                continue;
            }

            if let Some(desc) = &type_def.description {
                result.push_str("\"\"\"");
                result.push_str(desc);
                result.push_str("\"\"\"\n");
            }

            match type_def.kind {
                TypeKind::Object => {
                    result.push_str("type ");
                    result.push_str(&type_def.name);
                    result.push_str(" {\n");
                    for field in &type_def.fields {
                        result.push_str(&self.format_field(field));
                    }
                    result.push_str("}\n\n");
                }
                TypeKind::InputObject => {
                    result.push_str(&self.format_input_objects_single(&type_def.name, &type_def.input_fields));
                }
                TypeKind::Enum => {
                    result.push_str(&self.format_enums_single(&type_def.name, &type_def.enum_values));
                }
                TypeKind::Scalar => {
                    result.push_str("scalar ");
                    result.push_str(&type_def.name);
                    result.push_str("\n\n");
                }
                TypeKind::Union => {
                    result.push_str("union ");
                    result.push_str(&type_def.name);
                    result.push_str(" = ");
                    result.push_str(&type_def.possible_types.join(" | "));
                    result.push_str("\n\n");
                }
                TypeKind::Interface => {
                    result.push_str("interface ");
                    result.push_str(&type_def.name);
                    result.push_str(" {\n");
                    for field in &type_def.fields {
                        result.push_str(&self.format_field(field));
                    }
                    result.push_str("}\n\n");
                }
                _ => {}
            }
        }

        result
    }

    /// Format all enum types.
    #[allow(dead_code)]
    fn format_enums(&self) -> String {
        let mut result = String::new();

        for (type_name, type_def) in &self.schema.types {
            if matches!(
                type_name.as_str(),
                "String" | "Int" | "Float" | "Boolean" | "ID" | "DateTime" | "Date" | "Time" | "JSON" | "Upload"
            ) {
                continue;
            }

            if type_def.kind == TypeKind::Enum {
                result.push_str(&self.format_enums_single(&type_def.name, &type_def.enum_values));
            }
        }

        result
    }

    /// Format a single enum type.
    fn format_enums_single(&self, name: &str, values: &[GraphQLEnumValue]) -> String {
        let mut result = String::new();

        result.push_str("enum ");
        result.push_str(name);
        result.push_str(" {\n");

        for value in values {
            if let Some(desc) = &value.description {
                result.push_str("  \"\"\"");
                result.push_str(desc);
                result.push_str("\"\"\"\n");
            }

            result.push_str("  ");
            result.push_str(&value.name);

            if value.is_deprecated {
                if let Some(reason) = &value.deprecation_reason {
                    result.push_str(" @deprecated(reason: \"");
                    result.push_str(&reason.replace('"', "\\\""));
                    result.push_str("\")");
                } else {
                    result.push_str(" @deprecated");
                }
            }

            result.push('\n');
        }

        result.push_str("}\n\n");
        result
    }

    /// Format all input object types.
    #[allow(dead_code)]
    fn format_input_objects(&self) -> String {
        let mut result = String::new();

        for (type_name, type_def) in &self.schema.types {
            if matches!(
                type_name.as_str(),
                "String" | "Int" | "Float" | "Boolean" | "ID" | "DateTime" | "Date" | "Time" | "JSON" | "Upload"
            ) {
                continue;
            }

            if type_def.kind == TypeKind::InputObject {
                result.push_str(&self.format_input_objects_single(&type_def.name, &type_def.input_fields));
            }
        }

        result
    }

    /// Format a single input object type.
    fn format_input_objects_single(&self, name: &str, fields: &[GraphQLInputField]) -> String {
        let mut result = String::new();

        result.push_str("input ");
        result.push_str(name);
        result.push_str(" {\n");

        for field in fields {
            if let Some(desc) = &field.description {
                result.push_str("  \"\"\"");
                result.push_str(desc);
                result.push_str("\"\"\"\n");
            }

            result.push_str("  ");
            result.push_str(&field.name);
            result.push_str(": ");
            result.push_str(&self.format_gql_type(
                &field.type_name,
                field.is_nullable,
                field.is_list,
                field.list_item_nullable,
            ));

            if let Some(default) = &field.default_value {
                result.push_str(" = ");
                result.push_str(default);
            }

            result.push('\n');
        }

        result.push_str("}\n\n");
        result
    }

    /// Format all union types.
    #[allow(dead_code)]
    fn format_unions(&self) -> String {
        let mut result = String::new();

        for (type_name, type_def) in &self.schema.types {
            if matches!(
                type_name.as_str(),
                "String" | "Int" | "Float" | "Boolean" | "ID" | "DateTime" | "Date" | "Time" | "JSON" | "Upload"
            ) {
                continue;
            }

            if type_def.kind == TypeKind::Union {
                result.push_str("union ");
                result.push_str(&type_def.name);
                result.push_str(" = ");
                result.push_str(&type_def.possible_types.join(" | "));
                result.push_str("\n\n");
            }
        }

        result
    }

    /// Format a single field line for inclusion in a type definition.
    ///
    /// Generates field definition syntax with:
    /// - Field name
    /// - Arguments (if any)
    /// - Return type
    /// - Deprecation directive (if applicable)
    ///
    /// # Example output
    ///
    /// ```text
    ///   user(id: String!): User
    ///   posts(limit: Int): [Post!]!
    ///   deprecated_field: String @deprecated(reason: "Use newField instead")
    /// ```
    fn format_field(&self, field: &GraphQLField) -> String {
        let mut result = String::new();

        // Add description if present
        if let Some(desc) = &field.description {
            result.push_str("  \"\"\"");
            result.push_str(desc);
            result.push_str("\"\"\"\n");
        }

        // Add field name
        result.push_str("  ");
        result.push_str(&field.name);

        // Add arguments if present
        if !field.arguments.is_empty() {
            result.push('(');
            for (i, arg) in field.arguments.iter().enumerate() {
                if i > 0 {
                    result.push_str(", ");
                }
                result.push_str(&arg.name);
                result.push_str(": ");
                result.push_str(&self.format_gql_type(
                    &arg.type_name,
                    arg.is_nullable,
                    arg.is_list,
                    arg.list_item_nullable,
                ));
                if let Some(default) = &arg.default_value {
                    result.push_str(" = ");
                    result.push_str(default);
                }
            }
            result.push(')');
        }

        // Add return type
        result.push_str(": ");
        result.push_str(&self.format_gql_type(
            &field.type_name,
            field.is_nullable,
            field.is_list,
            field.list_item_nullable,
        ));

        // Add deprecation directive if present
        if let Some(reason) = &field.deprecation_reason {
            result.push_str(" @deprecated(reason: \"");
            result.push_str(&reason.replace('"', "\\\""));
            result.push_str("\")");
        }

        result.push('\n');
        result
    }

    /// Format a GraphQL type with proper null/list notation.
    ///
    /// Converts the builder's internal representation back to GraphQL SDL format:
    /// - Non-nullable: `Type!`
    /// - Nullable: `Type`
    /// - List of non-nullable items: `[Type!]`
    /// - List of nullable items: `[Type]`
    /// - Non-nullable list: `[Type]!` or `[Type!]!`
    ///
    /// # Arguments
    ///
    /// * `type_name` - The base type name (may include existing notation which is stripped)
    /// * `is_nullable` - Whether the type itself is nullable
    /// * `is_list` - Whether the type is a list
    /// * `list_item_nullable` - Whether items in the list are nullable
    ///
    /// # Returns
    ///
    /// A properly formatted GraphQL type string.
    ///
    /// # Example
    ///
    /// ```text
    /// format_gql_type("String", false, false, false) => "String!"
    /// format_gql_type("String", true, false, false) => "String"
    /// format_gql_type("String", false, true, false) => "[String!]!"
    /// format_gql_type("String", true, true, true) => "[String]"
    /// ```
    fn format_gql_type(&self, type_name: &str, is_nullable: bool, is_list: bool, list_item_nullable: bool) -> String {
        // Strip any existing GraphQL notation to prevent double notation (e.g., "String!!" vs "String!")
        let clean_type = type_name.trim_matches(|c| c == '!' || c == '[' || c == ']');

        // Build type with list notation if applicable
        let mut result = if is_list {
            if list_item_nullable {
                format!("[{clean_type}]")
            } else {
                format!("[{clean_type}!]")
            }
        } else {
            clean_type.to_string()
        };

        // Add non-null marker if type is non-nullable
        if !is_nullable {
            result.push('!');
        }

        result
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    #[test]
    fn test_format_gql_type_non_nullable() {
        let schema = GraphQLSchema {
            types: HashMap::new(),
            queries: vec![],
            mutations: vec![],
            subscriptions: vec![],
            directives: vec![],
            description: None,
        };
        let builder = SdlBuilder::new(&schema);

        assert_eq!(builder.format_gql_type("String", false, false, false), "String!");
        assert_eq!(builder.format_gql_type("User", false, false, false), "User!");
    }

    #[test]
    fn test_format_gql_type_nullable() {
        let schema = GraphQLSchema {
            types: HashMap::new(),
            queries: vec![],
            mutations: vec![],
            subscriptions: vec![],
            directives: vec![],
            description: None,
        };
        let builder = SdlBuilder::new(&schema);

        assert_eq!(builder.format_gql_type("String", true, false, false), "String");
        assert_eq!(builder.format_gql_type("User", true, false, false), "User");
    }

    #[test]
    fn test_format_gql_type_non_nullable_list_non_nullable_items() {
        let schema = GraphQLSchema {
            types: HashMap::new(),
            queries: vec![],
            mutations: vec![],
            subscriptions: vec![],
            directives: vec![],
            description: None,
        };
        let builder = SdlBuilder::new(&schema);

        assert_eq!(builder.format_gql_type("String", false, true, false), "[String!]!");
    }

    #[test]
    fn test_format_gql_type_non_nullable_list_nullable_items() {
        let schema = GraphQLSchema {
            types: HashMap::new(),
            queries: vec![],
            mutations: vec![],
            subscriptions: vec![],
            directives: vec![],
            description: None,
        };
        let builder = SdlBuilder::new(&schema);

        assert_eq!(builder.format_gql_type("String", false, true, true), "[String]!");
    }

    #[test]
    fn test_format_gql_type_nullable_list_non_nullable_items() {
        let schema = GraphQLSchema {
            types: HashMap::new(),
            queries: vec![],
            mutations: vec![],
            subscriptions: vec![],
            directives: vec![],
            description: None,
        };
        let builder = SdlBuilder::new(&schema);

        assert_eq!(builder.format_gql_type("String", true, true, false), "[String!]");
    }

    #[test]
    fn test_format_gql_type_nullable_list_nullable_items() {
        let schema = GraphQLSchema {
            types: HashMap::new(),
            queries: vec![],
            mutations: vec![],
            subscriptions: vec![],
            directives: vec![],
            description: None,
        };
        let builder = SdlBuilder::new(&schema);

        assert_eq!(builder.format_gql_type("String", true, true, true), "[String]");
    }

    #[test]
    fn test_format_gql_type_strips_existing_notation() {
        let schema = GraphQLSchema {
            types: HashMap::new(),
            queries: vec![],
            mutations: vec![],
            subscriptions: vec![],
            directives: vec![],
            description: None,
        };
        let builder = SdlBuilder::new(&schema);

        // Should strip existing notation to avoid double notation
        assert_eq!(builder.format_gql_type("String!", false, false, false), "String!");
        // Input has list notation but is_list=true so it rebuilds correctly
        assert_eq!(builder.format_gql_type("[String!]!", false, true, false), "[String!]!");
        // Input has notation but parameters override it
        assert_eq!(builder.format_gql_type("String!", true, false, false), "String");
    }
}