index-core 1.0.0

Core document model and semantic types for Index.
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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
//! Terminal-native document components.

use std::collections::BTreeMap;
use std::fmt::{Display, Formatter};

use crate::{IndexUrl, UrlError};

/// Stable identifier for a site adapter.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct AdapterId(String);

impl AdapterId {
    /// Creates an adapter identifier.
    #[must_use]
    pub fn new(input: impl Into<String>) -> Self {
        Self(input.into())
    }

    /// Returns the adapter identifier string.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl Display for AdapterId {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// A semantic document emitted by the transformer and consumed by renderers.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct IndexDocument {
    /// Document title.
    pub title: String,
    /// Ordered semantic nodes.
    pub nodes: Vec<IndexNode>,
    /// Optional page metadata.
    pub metadata: Metadata,
}

impl IndexDocument {
    /// Creates a document with a title.
    #[must_use]
    pub fn titled(title: impl Into<String>) -> Self {
        Self {
            title: title.into(),
            nodes: Vec::new(),
            metadata: Metadata::default(),
        }
    }

    /// Adds a node to the document.
    pub fn push(&mut self, node: IndexNode) {
        self.nodes.push(node);
    }

    /// Returns true when the document has no user-visible nodes.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.nodes.iter().all(IndexNode::is_layout_only)
    }
}

/// Optional document metadata.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Metadata {
    /// Canonical URL when known.
    pub canonical_url: Option<String>,
    /// Author when known.
    pub author: Option<String>,
    /// Declared document language when known.
    pub language: Option<String>,
    /// Description when known.
    pub description: Option<String>,
    /// OpenGraph title when known.
    pub open_graph_title: Option<String>,
    /// OpenGraph description when known.
    pub open_graph_description: Option<String>,
    /// Adapter that produced this document when known.
    pub adapter_id: Option<AdapterId>,
    /// Transform quality assessment when known.
    pub quality: Option<DocumentQuality>,
}

/// Stable transform quality category.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum DocumentQualityCategory {
    /// A fixture-backed site adapter produced the document.
    Adapter,
    /// The generic static transformer emitted a strong semantic view.
    StrongGeneric,
    /// The generic static transformer emitted sparse or partial content.
    PartialGeneric,
    /// A fallback path produced a deterministic document.
    Fallback,
    /// Transformation or retrieval failed closed.
    Failed,
}

impl DocumentQualityCategory {
    /// Returns the stable serialized category name.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Adapter => "adapter",
            Self::StrongGeneric => "strong-generic",
            Self::PartialGeneric => "partial-generic",
            Self::Fallback => "fallback",
            Self::Failed => "failed",
        }
    }
}

impl Display for DocumentQualityCategory {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Deterministic quality metadata for a transformed document.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DocumentQuality {
    /// Stable quality category.
    pub category: DocumentQualityCategory,
    /// Bounded score from 0 to 100.
    pub score: u8,
    /// Human-readable deterministic reasons for the score.
    pub reasons: Vec<String>,
}

impl DocumentQuality {
    /// Creates a quality value with score clamped to `0..=100`.
    #[must_use]
    pub fn new(
        category: DocumentQualityCategory,
        score: u8,
        reasons: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        Self {
            category,
            score: score.min(100),
            reasons: reasons.into_iter().map(Into::into).collect(),
        }
    }
}

/// A semantic terminal-native node.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum IndexNode {
    /// Heading with one-based level.
    Heading {
        /// One-based heading level.
        level: u8,
        /// Heading text content.
        text: String,
    },
    /// Paragraph text.
    Paragraph(String),
    /// Link with stable display address.
    Link(Link),
    /// Ordered or unordered list.
    List {
        /// Whether numbering is semantic (`true`) or bullet-style (`false`).
        ordered: bool,
        /// Ordered display items.
        items: Vec<String>,
    },
    /// Code block.
    CodeBlock {
        /// Optional declared language identifier.
        language: Option<String>,
        /// Code content.
        code: String,
    },
    /// Table represented as rows of cells.
    Table {
        /// Rows of cells in display order.
        rows: Vec<Vec<String>>,
    },
    /// Vertical rhythm hint derived from semantic block boundaries or bounded CSS spacing.
    Spacer {
        /// Extra blank terminal lines to preserve, clamped by producers.
        lines: u8,
    },
    /// Semantic page region, usually collapsed when it is secondary to the main content.
    Section {
        /// Region role inferred from HTML landmarks or common page conventions.
        role: SectionRole,
        /// Optional region title.
        title: Option<String>,
        /// Whether renderers should initially summarize rather than expand the region.
        collapsed: bool,
        /// Region contents.
        nodes: Vec<IndexNode>,
    },
    /// Image proxy. The renderer decides how to display it.
    Image {
        /// Image alternate text.
        alt: String,
        /// Optional source URL.
        src: Option<String>,
    },
    /// Web form represented as terminal action fields.
    Form(Form),
    /// Recoverable error displayed to the user.
    Error(String),
}

impl IndexNode {
    fn is_layout_only(&self) -> bool {
        match self {
            Self::Spacer { .. } => true,
            Self::Section { title, nodes, .. } => {
                title.as_deref().unwrap_or_default().trim().is_empty()
                    && nodes.iter().all(Self::is_layout_only)
            }
            _ => false,
        }
    }
}

/// Semantic page region role.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SectionRole {
    /// Primary content region.
    Main,
    /// Navigation region.
    Navigation,
    /// Sidebar or complementary content.
    Aside,
    /// Footer or content information.
    Footer,
    /// Comments or discussion region.
    Comments,
    /// Related links or related content.
    Related,
    /// Unknown secondary region.
    Unknown,
}

impl SectionRole {
    /// Returns a stable lowercase role name.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Main => "main",
            Self::Navigation => "navigation",
            Self::Aside => "aside",
            Self::Footer => "footer",
            Self::Comments => "comments",
            Self::Related => "related",
            Self::Unknown => "section",
        }
    }
}

impl Display for SectionRole {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// A link with stable text and target.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Link {
    /// Human-readable label.
    pub text: String,
    /// Link target.
    pub href: String,
}

impl Link {
    /// Creates a new link.
    #[must_use]
    pub fn new(text: impl Into<String>, href: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            href: href.into(),
        }
    }
}

/// A terminal-compatible form.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Form {
    /// Form name or inferred description.
    pub name: String,
    /// Method such as GET or POST.
    pub method: String,
    /// Action target.
    pub action: String,
    /// Form inputs.
    pub inputs: Vec<Input>,
    /// Button actions associated with this form.
    pub buttons: Vec<ButtonAction>,
}

/// A terminal-compatible form input.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Input {
    /// Input name.
    pub name: String,
    /// Input kind.
    pub kind: String,
    /// Optional current value.
    pub value: Option<String>,
    /// Whether a value is required before submission.
    pub required: bool,
}

/// A terminal-compatible form button.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ButtonAction {
    /// Optional button name submitted with the form.
    pub name: Option<String>,
    /// Optional button value submitted with the form.
    pub value: Option<String>,
    /// Human-readable label.
    pub label: String,
}

/// Supported form submission methods.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FormMethod {
    /// HTTP GET-style query submission.
    Get,
    /// HTTP POST-style body submission.
    Post,
}

impl FormMethod {
    /// Parses a form method, defaulting empty values to GET.
    #[must_use]
    pub fn parse(input: &str) -> Self {
        match input.trim().to_ascii_uppercase().as_str() {
            "POST" => Self::Post,
            _ => Self::Get,
        }
    }

    /// Returns the method as an uppercase string.
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Get => "GET",
            Self::Post => "POST",
        }
    }
}

/// Validation state for form submission.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValidationState {
    /// Form values are valid enough to submit.
    Valid,
    /// A required field has no value.
    MissingRequiredField(String),
}

/// A resolved form submission request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FormSubmission {
    /// Submission method.
    pub method: FormMethod,
    /// Resolved action URL.
    pub action: IndexUrl,
    /// Encoded request body for POST submissions.
    pub body: Option<String>,
}

/// Form submission errors.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FormSubmitError {
    /// A required field has no value.
    MissingRequiredField(String),
    /// A relative action was submitted without a base URL.
    RelativeActionWithoutBase(String),
    /// The action URL is invalid.
    InvalidAction(UrlError),
}

impl Display for FormSubmitError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::MissingRequiredField(name) => write!(f, "required form field is missing: {name}"),
            Self::RelativeActionWithoutBase(action) => {
                write!(f, "form action requires a base URL: {action}")
            }
            Self::InvalidAction(error) => write!(f, "form action is invalid: {error}"),
        }
    }
}

impl std::error::Error for FormSubmitError {}

impl Form {
    /// Returns the parsed submission method.
    #[must_use]
    pub fn form_method(&self) -> FormMethod {
        FormMethod::parse(&self.method)
    }

    /// Validates and resolves a submission request.
    pub fn submit(
        &self,
        base_url: Option<&IndexUrl>,
        values: &[(&str, &str)],
    ) -> Result<FormSubmission, FormSubmitError> {
        let fields = self.submission_fields(values)?;
        let method = self.form_method();
        let action = resolve_action(&self.action, base_url)?;

        match method {
            FormMethod::Get => {
                let mut url = ::url::Url::parse(action.as_str()).map_err(|error| {
                    FormSubmitError::InvalidAction(UrlError::Invalid(error.to_string()))
                })?;
                {
                    let mut pairs = url.query_pairs_mut();
                    for (name, value) in &fields {
                        pairs.append_pair(name, value);
                    }
                }
                Ok(FormSubmission {
                    method,
                    action: IndexUrl::parse(url.as_str())
                        .map_err(FormSubmitError::InvalidAction)?,
                    body: None,
                })
            }
            FormMethod::Post => {
                let mut serializer = ::url::form_urlencoded::Serializer::new(String::new());
                for (name, value) in &fields {
                    serializer.append_pair(name, value);
                }
                Ok(FormSubmission {
                    method,
                    action,
                    body: Some(serializer.finish()),
                })
            }
        }
    }

    /// Returns validation state for a set of field overrides.
    pub fn validate(&self, values: &[(&str, &str)]) -> ValidationState {
        match self.submission_fields(values) {
            Ok(_fields) => ValidationState::Valid,
            Err(FormSubmitError::MissingRequiredField(name)) => {
                ValidationState::MissingRequiredField(name)
            }
            Err(_) => ValidationState::Valid,
        }
    }

    fn submission_fields(
        &self,
        values: &[(&str, &str)],
    ) -> Result<Vec<(String, String)>, FormSubmitError> {
        let overrides = values
            .iter()
            .map(|(name, value)| ((*name).to_owned(), (*value).to_owned()))
            .collect::<BTreeMap<_, _>>();
        let mut fields = Vec::new();

        for input in &self.inputs {
            if input.name.is_empty() || is_button_like(&input.kind) {
                continue;
            }

            let value = overrides
                .get(&input.name)
                .cloned()
                .or_else(|| input.value.clone())
                .unwrap_or_default();
            if input.required && value.is_empty() {
                return Err(FormSubmitError::MissingRequiredField(input.name.clone()));
            }
            fields.push((input.name.clone(), value));
        }

        for (name, value) in overrides {
            if !fields.iter().any(|(field_name, _)| field_name == &name) {
                fields.push((name, value));
            }
        }

        Ok(fields)
    }
}

fn resolve_action(action: &str, base_url: Option<&IndexUrl>) -> Result<IndexUrl, FormSubmitError> {
    if let Ok(url) = IndexUrl::parse(action) {
        return Ok(url);
    }

    let Some(base_url) = base_url else {
        return Err(FormSubmitError::RelativeActionWithoutBase(
            action.to_owned(),
        ));
    };
    let base = ::url::Url::parse(base_url.as_str())
        .map_err(|error| FormSubmitError::InvalidAction(UrlError::Invalid(error.to_string())))?;
    let joined = base
        .join(action)
        .map_err(|error| FormSubmitError::InvalidAction(UrlError::Invalid(error.to_string())))?;
    IndexUrl::parse(joined.as_str()).map_err(FormSubmitError::InvalidAction)
}

fn is_button_like(kind: &str) -> bool {
    matches!(
        kind.trim().to_ascii_lowercase().as_str(),
        "button" | "submit" | "reset" | "image"
    )
}

#[cfg(test)]
mod tests {
    use super::{
        AdapterId, DocumentQuality, DocumentQualityCategory, Form, FormMethod, FormSubmitError,
        IndexDocument, IndexNode, Input, Link, SectionRole, ValidationState,
    };
    use crate::IndexUrl;

    #[test]
    fn document_starts_empty() {
        let doc = IndexDocument::titled("Example");
        assert_eq!(doc.title, "Example");
        assert!(doc.is_empty());
    }

    #[test]
    fn document_accepts_nodes() {
        let mut doc = IndexDocument::titled("Example");
        doc.push(IndexNode::Paragraph("Hello".to_owned()));
        assert!(!doc.is_empty());
    }

    #[test]
    fn document_with_only_layout_spacers_is_empty() {
        let mut doc = IndexDocument::titled("Example");
        doc.push(IndexNode::Spacer { lines: 2 });
        assert!(doc.is_empty());
    }

    #[test]
    fn document_with_only_empty_section_is_empty() {
        let mut doc = IndexDocument::titled("Example");
        doc.push(IndexNode::Section {
            role: SectionRole::Aside,
            title: None,
            collapsed: true,
            nodes: vec![IndexNode::Spacer { lines: 1 }],
        });
        assert!(doc.is_empty());
    }

    #[test]
    fn section_role_names_are_stable() {
        let roles = [
            (SectionRole::Main, "main"),
            (SectionRole::Navigation, "navigation"),
            (SectionRole::Aside, "aside"),
            (SectionRole::Footer, "footer"),
            (SectionRole::Comments, "comments"),
            (SectionRole::Related, "related"),
            (SectionRole::Unknown, "section"),
        ];

        for (role, label) in roles {
            assert_eq!(role.as_str(), label);
            assert_eq!(role.to_string(), label);
        }
    }

    #[test]
    fn link_constructor_preserves_text_and_href() {
        let link = Link::new("Docs", "https://example.com/docs");
        assert_eq!(link.text, "Docs");
        assert_eq!(link.href, "https://example.com/docs");
    }

    #[test]
    fn adapter_id_displays_stable_value() {
        let id = AdapterId::new("github.repository");
        assert_eq!(id.as_str(), "github.repository");
        assert_eq!(id.to_string(), "github.repository");
    }

    #[test]
    fn document_quality_category_names_are_stable() {
        let categories = [
            (DocumentQualityCategory::Adapter, "adapter"),
            (DocumentQualityCategory::StrongGeneric, "strong-generic"),
            (DocumentQualityCategory::PartialGeneric, "partial-generic"),
            (DocumentQualityCategory::Fallback, "fallback"),
            (DocumentQualityCategory::Failed, "failed"),
        ];

        for (category, name) in categories {
            assert_eq!(category.as_str(), name);
            assert_eq!(category.to_string(), name);
        }
    }

    #[test]
    fn document_quality_clamps_score() {
        let quality = DocumentQuality::new(
            DocumentQualityCategory::StrongGeneric,
            250,
            ["readable body"],
        );

        assert_eq!(quality.score, 100);
        assert_eq!(quality.reasons, vec!["readable body".to_owned()]);
    }

    #[test]
    fn get_form_submission_resolves_query_url() -> Result<(), Box<dyn std::error::Error>> {
        let form = Form {
            name: "search".to_owned(),
            method: "GET".to_owned(),
            action: "/search".to_owned(),
            inputs: vec![Input {
                name: "q".to_owned(),
                kind: "search".to_owned(),
                value: None,
                required: true,
            }],
            buttons: Vec::new(),
        };
        let base = IndexUrl::parse("https://example.com/docs/")?;
        let submission = form.submit(Some(&base), &[("q", "index browser")])?;

        assert_eq!(submission.method, FormMethod::Get);
        assert_eq!(
            submission.action.as_str(),
            "https://example.com/search?q=index+browser"
        );
        assert_eq!(submission.body, None);
        Ok(())
    }

    #[test]
    fn post_form_submission_uses_encoded_body() -> Result<(), Box<dyn std::error::Error>> {
        let form = Form {
            name: "login".to_owned(),
            method: "POST".to_owned(),
            action: "https://example.com/login".to_owned(),
            inputs: vec![Input {
                name: "token".to_owned(),
                kind: "hidden".to_owned(),
                value: Some("abc".to_owned()),
                required: false,
            }],
            buttons: Vec::new(),
        };
        let submission = form.submit(None, &[("user", "ada")])?;

        assert_eq!(submission.method, FormMethod::Post);
        assert_eq!(submission.action.as_str(), "https://example.com/login");
        assert_eq!(submission.body.as_deref(), Some("token=abc&user=ada"));
        Ok(())
    }

    #[test]
    fn form_submission_uses_default_field_values_and_allows_overrides()
    -> Result<(), Box<dyn std::error::Error>> {
        let form = Form {
            name: "filters".to_owned(),
            method: "GET".to_owned(),
            action: "https://example.com/search".to_owned(),
            inputs: vec![
                Input {
                    name: "q".to_owned(),
                    kind: "search".to_owned(),
                    value: None,
                    required: true,
                },
                Input {
                    name: "sort".to_owned(),
                    kind: "select".to_owned(),
                    value: Some("recent".to_owned()),
                    required: false,
                },
            ],
            buttons: Vec::new(),
        };

        let submission = form.submit(None, &[("q", "index"), ("sort", "relevance")])?;
        assert_eq!(
            submission.action.as_str(),
            "https://example.com/search?q=index&sort=relevance"
        );

        let defaulted = form.submit(None, &[("q", "index")])?;
        assert_eq!(
            defaulted.action.as_str(),
            "https://example.com/search?q=index&sort=recent"
        );
        Ok(())
    }

    #[test]
    fn form_submission_reports_missing_required_field() {
        let form = Form {
            name: "search".to_owned(),
            method: "GET".to_owned(),
            action: "https://example.com/search".to_owned(),
            inputs: vec![Input {
                name: "q".to_owned(),
                kind: "search".to_owned(),
                value: None,
                required: true,
            }],
            buttons: Vec::new(),
        };

        assert_eq!(
            form.validate(&[]),
            ValidationState::MissingRequiredField("q".to_owned())
        );
        assert_eq!(
            form.submit(None, &[]),
            Err(FormSubmitError::MissingRequiredField("q".to_owned()))
        );
    }

    #[test]
    fn relative_action_without_base_is_diagnostic() {
        let form = Form {
            name: "search".to_owned(),
            method: "GET".to_owned(),
            action: "/search".to_owned(),
            inputs: Vec::new(),
            buttons: Vec::new(),
        };

        assert_eq!(
            form.submit(None, &[]),
            Err(FormSubmitError::RelativeActionWithoutBase(
                "/search".to_owned()
            ))
        );
    }
}