surf-parse 0.10.0

Parser for the SurfDoc format — typed document format with block directives, Markdown-compatible
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
//! Property-based tests using proptest.
//!
//! These tests verify that the parser never panics on arbitrary input and that
//! round-trip operations preserve content.

use proptest::prelude::*;

proptest! {
    /// Any random string fed to the parser should never cause a panic.
    #[test]
    fn any_markdown_no_panic(input in "\\PC{0,500}") {
        let result = surf_parse::parse(&input);
        // Just verify it returns without panic — the result can have diagnostics
        let _ = result.doc.blocks.len();
        let _ = result.diagnostics.len();
    }

    /// Parse then to_markdown should preserve text content from blocks.
    /// We test with well-formed markdown that contains no :: directives,
    /// so the parser will create Markdown blocks and round-trip them.
    #[test]
    fn roundtrip_preserves_content(
        heading in "[A-Za-z ]{1,30}",
        body in "[A-Za-z0-9 .,!?]{1,100}"
    ) {
        let input = format!("# {heading}\n\n{body}\n");
        let result = surf_parse::parse(&input);
        let md = result.doc.to_markdown();

        // The heading and body text should appear in the round-tripped
        // markdown. Compare trimmed: markdown collapses leading/trailing
        // whitespace, so a whitespace-only "body" (which the generator can
        // produce — committed regression seed `heading="a", body="  "`) has
        // no content to preserve.
        assert!(
            md.contains(heading.trim()),
            "Round-trip should preserve heading '{heading}', got: {md}"
        );
        assert!(
            md.contains(body.trim()),
            "Round-trip should preserve body '{body}', got: {md}"
        );
    }

    /// Random attribute strings should either parse successfully or return an error,
    /// but never panic.
    #[test]
    fn attrs_parser_completeness(input in "[a-z0-9=\", ]{0,100}") {
        let bracketed = format!("[{input}]");
        let result = surf_parse::attrs::parse_attrs(&bracketed);
        // Either Ok or Err — never panic
        match result {
            Ok(attrs) => {
                // Attrs should be a valid BTreeMap
                let _ = attrs.len();
            }
            Err(_e) => {
                // Parse errors are acceptable for random input
            }
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// v0.6.0 Property-Based Tests (Layer 6)
// ═══════════════════════════════════════════════════════════════════════════════
//
// Five invariants from the master strategy:
//   1. Fragment never panics
//   2. NativeBlock conversion length <= input length
//   3. New NativeBlock variants preserve fields through conversion
//   4. Code extraction preserves content byte-identical
//   5. Language normalization is idempotent

use surf_parse::render_html::to_html_fragment;
use surf_parse::types::*;

/// Helper: build a `Block::Code` with SYNTHETIC span.
fn synth_code(lang: Option<&str>, file: Option<&str>, content: &str) -> Block {
    Block::Code {
        lang: lang.map(|s| s.to_string()),
        file: file.map(|s| s.to_string()),
        highlight: vec![],
        content: content.to_string(),
        span: Span::SYNTHETIC,
    }
}

/// Helper: build a `Block::Markdown` with SYNTHETIC span.
fn synth_markdown(content: &str) -> Block {
    Block::Markdown {
        content: content.to_string(),
        span: Span::SYNTHETIC,
    }
}

/// Helper: build a `Block::Callout` with SYNTHETIC span.
fn synth_callout(ct: CalloutType, title: Option<&str>, content: &str) -> Block {
    Block::Callout {
        callout_type: ct,
        title: title.map(|s| s.to_string()),
        content: content.to_string(),
        span: Span::SYNTHETIC,
    }
}

/// Helper: build a `Block::Form` with SYNTHETIC span.
fn synth_form(fields: Vec<FormField>, submit_label: Option<&str>) -> Block {
    Block::Form {
        fields,
        submit_label: submit_label.map(|s| s.to_string()),
        action: None,
        method: None,
        honeypot: false,
        span: Span::SYNTHETIC,
    }
}

/// Helper: build a `Block::Gallery` with SYNTHETIC span.
fn synth_gallery(items: Vec<GalleryItem>, columns: Option<u32>) -> Block {
    Block::Gallery {
        items,
        columns,
        span: Span::SYNTHETIC,
    }
}

/// Helper: build a `Block::Section` with SYNTHETIC span.
fn synth_section(
    bg: Option<&str>,
    headline: Option<&str>,
    subtitle: Option<&str>,
    children: Vec<Block>,
) -> Block {
    Block::Section {
        bg: bg.map(|s| s.to_string()),
        headline: headline.map(|s| s.to_string()),
        subtitle: subtitle.map(|s| s.to_string()),
        content: String::new(),
        children,
        span: Span::SYNTHETIC,
    }
}

/// Proptest strategy for CalloutType.
fn arb_callout_type() -> impl Strategy<Value = CalloutType> {
    prop_oneof![
        Just(CalloutType::Info),
        Just(CalloutType::Warning),
        Just(CalloutType::Danger),
        Just(CalloutType::Tip),
        Just(CalloutType::Note),
        Just(CalloutType::Success),
    ]
}

/// Proptest strategy for FormFieldType.
fn arb_form_field_type() -> impl Strategy<Value = FormFieldType> {
    prop_oneof![
        Just(FormFieldType::Text),
        Just(FormFieldType::Email),
        Just(FormFieldType::Tel),
        Just(FormFieldType::Date),
        Just(FormFieldType::Number),
        Just(FormFieldType::Select),
        Just(FormFieldType::Textarea),
    ]
}

/// Proptest strategy for a FormField.
fn arb_form_field() -> impl Strategy<Value = FormField> {
    (
        "[a-zA-Z ]{1,20}",       // label
        "[a-z_]{1,15}",          // name
        arb_form_field_type(),
        any::<bool>(),           // required
        proptest::option::of("[a-zA-Z0-9 ]{0,20}"),  // placeholder
        proptest::collection::vec("[a-zA-Z]{1,10}", 0..4), // options
    )
        .prop_map(|(label, name, field_type, required, placeholder, options)| FormField {
            label,
            name,
            field_type,
            required,
            placeholder,
            options,
        })
}

/// Proptest strategy for a GalleryItem.
fn arb_gallery_item() -> impl Strategy<Value = GalleryItem> {
    (
        "[a-z/]{1,30}\\.jpg",    // src
        proptest::option::of("[a-zA-Z ]{1,30}"),  // caption
        proptest::option::of("[a-zA-Z ]{1,30}"),  // alt
        proptest::option::of("[a-zA-Z]{1,10}"),   // category
    )
        .prop_map(|(src, caption, alt, category)| GalleryItem {
            src,
            caption,
            alt,
            category,
        })
}

/// Proptest strategy for a diverse Block (subset covering key variant families).
/// We generate blocks that exercise fragment rendering without needing complex
/// nested structures like Page/Site which have multi-field dependencies.
fn arb_block() -> impl Strategy<Value = Block> {
    prop_oneof![
        // Markdown
        "\\PC{0,100}".prop_map(|content| synth_markdown(&content)),
        // Code
        (
            proptest::option::of("[a-z]{1,10}"),
            proptest::option::of("[a-z/.]{1,20}"),
            "\\PC{0,200}",
        )
            .prop_map(|(lang, file, content)| synth_code(
                lang.as_deref(),
                file.as_deref(),
                &content,
            )),
        // Callout
        (arb_callout_type(), proptest::option::of("[a-zA-Z ]{1,20}"), "\\PC{0,100}")
            .prop_map(|(ct, title, content)| synth_callout(ct, title.as_deref(), &content)),
        // Divider
        proptest::option::of("[a-zA-Z ]{1,20}")
            .prop_map(|label| Block::Divider {
                label,
                span: Span::SYNTHETIC,
            }),
        // Summary
        "\\PC{0,100}".prop_map(|content| Block::Summary {
            content,
            span: Span::SYNTHETIC,
        }),
        // Figure
        (
            "[a-z/]{1,20}\\.png",
            proptest::option::of("[a-zA-Z ]{1,30}"),
            proptest::option::of("[a-zA-Z ]{1,30}"),
        )
            .prop_map(|(src, caption, alt)| Block::Figure {
                src,
                caption,
                alt,
                width: None,
                span: Span::SYNTHETIC,
            }),
        // Diagram (type may be valid, unknown, or empty — render must never panic)
        (
            prop_oneof!["architecture", "erd", "[a-z]{0,10}"],
            proptest::option::of("[a-zA-Z ]{1,20}"),
            "\\PC{0,100}",
        )
            .prop_map(|(diagram_type, title, content)| Block::Diagram {
                diagram_type,
                title,
                content,
                span: Span::SYNTHETIC,
            }),
        // Quote
        ("\\PC{0,100}", proptest::option::of("[a-zA-Z ]{1,20}"))
            .prop_map(|(content, attribution)| Block::Quote {
                content,
                attribution,
                cite: None,
                span: Span::SYNTHETIC,
            }),
        // Details
        (proptest::option::of("[a-zA-Z ]{1,20}"), any::<bool>(), "\\PC{0,100}")
            .prop_map(|(title, open, content)| Block::Details {
                title,
                open,
                content,
                span: Span::SYNTHETIC,
            }),
        // Form
        (
            proptest::collection::vec(arb_form_field(), 0..4),
            proptest::option::of("[a-zA-Z ]{1,15}"),
        )
            .prop_map(|(fields, submit_label)| synth_form(fields, submit_label.as_deref())),
        // Gallery
        (
            proptest::collection::vec(arb_gallery_item(), 0..4),
            proptest::option::of(1u32..6),
        )
            .prop_map(|(items, columns)| synth_gallery(items, columns)),
        // Section (non-recursive: empty children to keep generation bounded)
        (
            proptest::option::of("[a-zA-Z0-9]{1,10}"),
            proptest::option::of("[a-zA-Z ]{1,20}"),
            proptest::option::of("[a-zA-Z ]{1,30}"),
        )
            .prop_map(|(bg, headline, subtitle)| synth_section(
                bg.as_deref(),
                headline.as_deref(),
                subtitle.as_deref(),
                vec![],
            )),
    ]
}

// ─── Invariant 1: Fragment never panics ──────────────────────────────────────

proptest! {
    #![proptest_config(ProptestConfig::with_cases(200))]

    /// Any sequence of diverse Block variants passed to `to_html_fragment()`
    /// must return a String without panicking. The output type is always valid UTF-8.
    #[test]
    fn fragment_never_panics(blocks in proptest::collection::vec(arb_block(), 0..10)) {
        let html = to_html_fragment(&blocks);
        // Must return valid UTF-8 (guaranteed by String type) and not panic.
        let _ = html.len();
    }
}

// ─── Invariant 2: NativeBlock conversion length <= input ─────────────────────

#[cfg(feature = "native")]
mod native_props {
    use super::*;
    use surf_parse::render_native::to_native_blocks;

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(200))]

        /// For any SurfDoc, `to_native_blocks()` produces a Vec whose length
        /// is exactly equal to the number of input blocks (1:1 mapping).
        /// The master strategy says "<= input length" to allow for merging,
        /// but the current implementation does a 1:1 map.
        #[test]
        fn native_conversion_length_le_input(blocks in proptest::collection::vec(arb_block(), 0..10)) {
            let doc = SurfDoc {
                blocks: blocks.clone(),
                front_matter: None,
                source: String::new(),
            };
            let native = to_native_blocks(&doc);
            prop_assert!(
                native.len() <= blocks.len(),
                "NativeBlock count ({}) should be <= input block count ({})",
                native.len(),
                blocks.len(),
            );
        }
    }

    // ─── Invariant 3: New NativeBlock variants preserve fields ───────────────

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        /// Form blocks converted to NativeBlock::Form preserve all field metadata.
        #[test]
        fn form_conversion_preserves_fields(
            fields in proptest::collection::vec(arb_form_field(), 1..5),
            submit_label in proptest::option::of("[a-zA-Z ]{1,15}"),
        ) {
            let block = synth_form(fields.clone(), submit_label.as_deref());
            let doc = SurfDoc {
                blocks: vec![block],
                front_matter: None,
                source: String::new(),
            };
            let native = to_native_blocks(&doc);
            prop_assert_eq!(native.len(), 1);

            if let surf_parse::render_native::NativeBlock::Form {
                fields: native_fields,
                submit_label: native_submit,
            } = &native[0]
            {
                prop_assert_eq!(native_fields.len(), fields.len());
                for (nf, f) in native_fields.iter().zip(fields.iter()) {
                    prop_assert_eq!(&nf.label, &f.label);
                    prop_assert_eq!(&nf.name, &f.name);
                    prop_assert_eq!(nf.required, f.required);
                    prop_assert_eq!(&nf.placeholder, &f.placeholder);
                    prop_assert_eq!(&nf.options, &f.options);
                }
                let expected_label = submit_label.unwrap_or_else(|| "Submit".to_string());
                prop_assert_eq!(native_submit, &expected_label);
            } else {
                prop_assert!(false, "Expected NativeBlock::Form, got {:?}", native[0]);
            }
        }

        /// Gallery blocks converted to NativeBlock::Gallery preserve item metadata.
        #[test]
        fn gallery_conversion_preserves_fields(
            items in proptest::collection::vec(arb_gallery_item(), 1..5),
            columns in proptest::option::of(1u32..6),
        ) {
            let block = synth_gallery(items.clone(), columns);
            let doc = SurfDoc {
                blocks: vec![block],
                front_matter: None,
                source: String::new(),
            };
            let native = to_native_blocks(&doc);
            prop_assert_eq!(native.len(), 1);

            if let surf_parse::render_native::NativeBlock::Gallery {
                items: native_items,
                columns: native_cols,
            } = &native[0]
            {
                prop_assert_eq!(native_items.len(), items.len());
                for (ni, i) in native_items.iter().zip(items.iter()) {
                    prop_assert_eq!(&ni.src, &i.src);
                    prop_assert_eq!(&ni.caption, &i.caption);
                    prop_assert_eq!(&ni.alt, &i.alt);
                    prop_assert_eq!(&ni.category, &i.category);
                }
                let expected_cols = columns.unwrap_or(3);
                prop_assert_eq!(*native_cols, expected_cols);
            } else {
                prop_assert!(false, "Expected NativeBlock::Gallery, got {:?}", native[0]);
            }
        }

        /// SectionContainer blocks converted to NativeBlock::SectionContainer
        /// preserve headline, subtitle, bg, and recursively convert children.
        #[test]
        fn section_container_conversion_preserves_fields(
            bg in proptest::option::of("[a-zA-Z0-9]{1,10}"),
            headline in proptest::option::of("[a-zA-Z ]{1,20}"),
            subtitle in proptest::option::of("[a-zA-Z ]{1,30}"),
            child_content in "[a-zA-Z0-9 ]{1,50}",
        ) {
            let child = synth_markdown(&child_content);
            let block = synth_section(
                bg.as_deref(),
                headline.as_deref(),
                subtitle.as_deref(),
                vec![child],
            );
            let doc = SurfDoc {
                blocks: vec![block],
                front_matter: None,
                source: String::new(),
            };
            let native = to_native_blocks(&doc);
            prop_assert_eq!(native.len(), 1);

            if let surf_parse::render_native::NativeBlock::SectionContainer {
                bg: native_bg,
                headline: native_headline,
                subtitle: native_subtitle,
                children,
            } = &native[0]
            {
                prop_assert_eq!(native_bg, &bg);
                prop_assert_eq!(native_headline, &headline);
                prop_assert_eq!(native_subtitle, &subtitle);
                prop_assert_eq!(children.len(), 1);
                // The child should be a Markdown NativeBlock
                if let surf_parse::render_native::NativeBlock::Markdown { content } = &children[0] {
                    prop_assert_eq!(content, &child_content);
                } else {
                    prop_assert!(false, "Expected NativeBlock::Markdown child, got {:?}", children[0]);
                }
            } else {
                prop_assert!(false, "Expected NativeBlock::SectionContainer, got {:?}", native[0]);
            }
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// v0.7.0 Property-Based Tests — Typed Extraction Pipeline
// ═══════════════════════════════════════════════════════════════════════════════

use surf_parse::types::ModelFieldType;
use surf_parse::parse_schema_field_type;

// ─── valid_type_strings_always_parse ────────────────────────────────────────

proptest! {
    #![proptest_config(ProptestConfig::with_cases(200))]

    /// Every known type string fed to parse_schema_field_type should succeed.
    #[test]
    fn valid_type_strings_always_parse(
        type_str in prop_oneof![
            Just("uuid"),
            Just("string"),
            Just("str"),
            Just("varchar"),
            Just("text"),
            Just("int"),
            Just("integer"),
            Just("i64"),
            Just("float"),
            Just("f64"),
            Just("double"),
            Just("bool"),
            Just("boolean"),
            Just("datetime"),
            Just("timestamp"),
            Just("json"),
            Just("jsonb"),
            Just("money"),
            Just("cents"),
            Just("price"),
            Just("image"),
            Just("img"),
            Just("photo"),
            Just("email"),
            Just("url"),
            Just("uri"),
            Just("link"),
            Just("enum:a,b,c"),
            Just("ref:User"),
        ]
    ) {
        let result = parse_schema_field_type(type_str);
        prop_assert!(
            result.is_ok(),
            "parse_schema_field_type({:?}) should succeed but got {:?}",
            type_str,
            result,
        );
    }

    /// parse_schema_field_type is deterministic: same input always yields same output.
    #[test]
    fn parse_schema_field_type_deterministic(input in "\\PC{0,50}") {
        let r1 = parse_schema_field_type(&input);
        let r2 = parse_schema_field_type(&input);
        match (&r1, &r2) {
            (Ok(a), Ok(b)) => prop_assert_eq!(a, b, "Determinism violated for {:?}", input),
            (Err(_), Err(_)) => {} // both error — ok
            _ => prop_assert!(false, "Determinism violated: one Ok one Err for {:?}", input),
        }
    }

}

/// Exhaustive (non-proptest) check that every simple ModelFieldType variant
/// is reachable via parse_schema_field_type.
#[test]
fn all_simple_model_field_type_variants_reachable() {
    let mapping: Vec<(&str, ModelFieldType)> = vec![
        ("uuid", ModelFieldType::Uuid),
        ("string", ModelFieldType::String),
        ("text", ModelFieldType::Text),
        ("int", ModelFieldType::Int),
        ("float", ModelFieldType::Float),
        ("bool", ModelFieldType::Bool),
        ("datetime", ModelFieldType::Datetime),
        ("json", ModelFieldType::Json),
        ("money", ModelFieldType::Money),
        ("image", ModelFieldType::Image),
        ("email", ModelFieldType::Email),
        ("url", ModelFieldType::Url),
        ("enum:x,y", ModelFieldType::Enum(vec!["x".to_string(), "y".to_string()])),
        ("ref:Post", ModelFieldType::Ref("Post".to_string())),
    ];
    for (input, expected) in mapping {
        let result = parse_schema_field_type(input)
            .unwrap_or_else(|e| panic!("Failed to parse {input:?}: {e:?}"));
        assert_eq!(result, expected, "Variant mismatch for {input:?}");
    }
}