lintel-catalog-builder 0.0.16

Build a custom schema catalog from local schemas and external sources
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
use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::vec::Vec;

use schema_catalog::{Catalog, CatalogGroup, SchemaEntry};
use serde::Serialize;

use super::schema_doc::SchemaDoc;
use crate::targets::OutputContext;

/// Shared site metadata passed to every template.
#[derive(Serialize, Clone)]
pub struct SiteInfo {
    pub title: String,
    pub description: String,
    /// Full absolute URL for SEO meta tags (canonical, og:url, sitemap).
    pub base_url: String,
    /// Root-relative path for internal links and assets (e.g. `/` or `/catalog/`).
    pub base_path: String,
    pub schema_count: usize,
    pub group_count: usize,
    /// Package version for the footer.
    pub version: String,
    /// Google Analytics measurement ID, if configured.
    pub ga_tracking_id: Option<String>,
    /// Open Graph image URL for social sharing previews.
    pub og_image: Option<String>,
}

/// Context for the home page template.
#[derive(Serialize)]
pub struct HomeContext {
    pub site: SiteInfo,
    pub groups: Vec<HomeGroup>,
    pub unassigned: Vec<SchemaCard>,
}

/// A group summary for the home page grid.
#[derive(Serialize)]
pub struct HomeGroup {
    pub key: String,
    pub name: String,
    pub description: String,
    pub schema_count: usize,
}

/// Context for a group detail page.
#[derive(Serialize)]
pub struct GroupPage {
    pub site: SiteInfo,
    pub key: String,
    pub name: String,
    pub description: String,
    pub seo_description: String,
    pub schemas: Vec<SchemaCard>,
    pub breadcrumbs: Vec<Breadcrumb>,
}

/// A schema card used in listing pages.
#[derive(Serialize)]
pub struct SchemaCard {
    pub name: String,
    pub description: String,
    pub url: String,
    pub file_match: Vec<String>,
}

/// Context for the `/schemas/` index page listing all schemas.
#[derive(Serialize)]
pub struct SchemasIndexPage {
    pub site: SiteInfo,
    pub schemas: Vec<SchemaCard>,
    pub seo_description: String,
}

/// Context for a schema detail page.
#[derive(Serialize)]
pub struct SchemaPage {
    pub site: SiteInfo,
    pub name: String,
    pub description: String,
    pub description_html: String,
    pub seo_description: String,
    pub page_url: String,
    pub json_url: String,
    pub source_url: Option<String>,
    pub file_match: Vec<String>,
    pub versions: Vec<VersionLink>,
    pub group_name: Option<String>,
    pub group_key: Option<String>,
    pub breadcrumbs: Vec<Breadcrumb>,
    pub schema_doc: Option<SchemaDoc>,
}

/// A version link on schema detail pages.
#[derive(Serialize)]
pub struct VersionLink {
    pub name: String,
    pub url: String,
}

/// Context for a version detail page.
#[derive(Serialize)]
pub struct VersionPage {
    pub site: SiteInfo,
    pub version_name: String,
    pub schema_name: String,
    pub page_url: String,
    pub json_url: String,
    pub schema_page_url: String,
    pub group_name: Option<String>,
    pub group_key: Option<String>,
    pub breadcrumbs: Vec<Breadcrumb>,
    pub schema_doc: Option<SchemaDoc>,
}

/// Context for a `_shared` dependency schema page.
#[derive(Serialize)]
pub struct SharedSchemaPage {
    pub site: SiteInfo,
    pub name: String,
    pub json_url: String,
    pub parent_schema_name: Option<String>,
    pub parent_schema_url: Option<String>,
    pub breadcrumbs: Vec<Breadcrumb>,
    pub schema_doc: Option<SchemaDoc>,
}

/// Breadcrumb navigation entry.
#[derive(Serialize)]
pub struct Breadcrumb {
    pub label: String,
    pub url: Option<String>,
}

/// Context for the sitemap template.
#[derive(Serialize)]
pub struct SitemapContext {
    pub base_url: String,
    pub urls: Vec<String>,
    /// ISO 8601 date string for `<lastmod>` (e.g. `2025-01-15`).
    pub lastmod: String,
}

/// Search index entry with compact keys.
#[derive(Serialize)]
pub struct SearchEntry {
    pub n: String,
    #[serde(skip_serializing_if = "String::is_empty")]
    pub d: String,
    #[serde(skip_serializing_if = "String::is_empty")]
    pub f: String,
    pub u: String,
    #[serde(skip_serializing_if = "String::is_empty")]
    pub g: String,
}

/// Build [`SiteInfo`] from the output context.
pub fn build_site_info(ctx: &OutputContext<'_>) -> SiteInfo {
    let title = ctx
        .catalog
        .title
        .clone()
        .unwrap_or_else(|| String::from("Schema Catalog"));
    let base_url = ensure_trailing_slash(ctx.base_url);
    let base_path = extract_path(&base_url);
    let schema_count = ctx.processed.len();
    let description = if let Some(desc) = ctx.site_description {
        String::from(desc)
    } else {
        alloc::format!(
            "A catalog of {} JSON Schemas for editor auto-completion, validation, and documentation",
            format_number(schema_count),
        )
    };
    SiteInfo {
        title,
        description,
        base_url,
        base_path,
        schema_count,
        group_count: ctx.catalog.groups.len(),
        version: String::from(env!("CARGO_PKG_VERSION")),
        ga_tracking_id: ctx.ga_tracking_id.map(String::from),
        og_image: ctx.og_image.map(String::from),
    }
}

/// Extract the path portion from a URL (e.g. `https://example.com/catalog/` → `/catalog/`).
/// Falls back to `/` if parsing fails.
fn extract_path(url: &str) -> String {
    url::Url::parse(url).map_or_else(|_| String::from("/"), |u| ensure_trailing_slash(u.path()))
}

/// Build the home page context.
pub fn build_home_context(ctx: &OutputContext<'_>, site: &SiteInfo) -> HomeContext {
    let assigned = assigned_schema_names(&ctx.catalog.groups);
    let base_url = &site.base_url;

    let groups: Vec<HomeGroup> = ctx
        .groups_meta
        .iter()
        .map(|(key, name, desc)| HomeGroup {
            key: key.clone(),
            name: name.clone(),
            description: desc.clone(),
            schema_count: group_schema_count(&ctx.catalog.groups, name),
        })
        .collect();

    let unassigned: Vec<SchemaCard> = ctx
        .catalog
        .schemas
        .iter()
        .filter(|s| !assigned.contains(s.name.as_str()))
        .filter_map(|s| schema_card(s, base_url))
        .collect();

    HomeContext {
        site: site.clone(),
        groups,
        unassigned,
    }
}

/// Build the `/schemas/` index page context with all schemas.
pub fn build_schemas_index(ctx: &OutputContext<'_>, site: &SiteInfo) -> SchemasIndexPage {
    let schemas: Vec<SchemaCard> = ctx
        .catalog
        .schemas
        .iter()
        .filter_map(|s| schema_card(s, &site.base_url))
        .collect();
    let seo_description = alloc::format!(
        "Browse all {} JSON Schemas for editor auto-completion, validation, and documentation.",
        format_number(schemas.len()),
    );
    SchemasIndexPage {
        site: site.clone(),
        schemas,
        seo_description,
    }
}

/// Build a group page context.
///
/// `meta` is `(key, name, description)` from the groups metadata.
pub fn build_group_page(
    site: &SiteInfo,
    meta: &(String, String, String),
    group: &CatalogGroup,
    catalog: &Catalog,
) -> GroupPage {
    let (key, name, description) = (meta.0.as_str(), meta.1.as_str(), meta.2.as_str());
    let schemas: Vec<SchemaCard> = catalog
        .schemas
        .iter()
        .filter(|s| group.schemas.contains(&s.name))
        .filter_map(|s| schema_card(s, &site.base_url))
        .collect();

    let count = schemas.len();
    let schema_word = if count == 1 { "schema" } else { "schemas" };
    let seo_description = alloc::format!(
        "{name} JSON Schemas — {count} {schema_word} for editor auto-completion and validation. {desc}",
        count = format_number(count),
        desc = ensure_sentence_end(description),
    );

    GroupPage {
        site: site.clone(),
        key: String::from(key),
        name: String::from(name),
        description: String::from(description),
        seo_description,
        breadcrumbs: vec![
            Breadcrumb {
                label: String::from("Home"),
                url: Some(site.base_path.clone()),
            },
            Breadcrumb {
                label: String::from(name),
                url: None,
            },
        ],
        schemas,
    }
}

/// Build a schema detail page context.
///
/// `group_info` is `Some((key, name))` if the schema belongs to a group.
#[allow(clippy::too_many_arguments)]
pub fn build_schema_page(
    site: &SiteInfo,
    entry: &SchemaEntry,
    page_url: &str,
    group_info: Option<(&str, &str)>,
    schema_doc: Option<SchemaDoc>,
) -> SchemaPage {
    let group_key = group_info.map(|(k, _)| k);
    let group_name = group_info.map(|(_, n)| n);
    let versions: Vec<VersionLink> = entry
        .versions
        .iter()
        .filter_map(|(vname, vurl)| {
            version_page_url(vurl, &site.base_url).map(|url| VersionLink {
                name: vname.clone(),
                url,
            })
        })
        .collect();

    let mut breadcrumbs = vec![Breadcrumb {
        label: String::from("Home"),
        url: Some(site.base_path.clone()),
    }];
    if let (Some(gn), Some(gk)) = (group_name, group_key) {
        breadcrumbs.push(Breadcrumb {
            label: String::from(gn),
            url: Some(alloc::format!("{}schemas/{}/", site.base_path, gk)),
        });
    }
    breadcrumbs.push(Breadcrumb {
        label: entry.name.clone(),
        url: None,
    });

    let description_html = md_to_html(&entry.description);
    let seo_description = build_schema_seo_description(entry, group_name);

    SchemaPage {
        site: site.clone(),
        name: entry.name.clone(),
        description: entry.description.clone(),
        description_html,
        seo_description,
        page_url: String::from(page_url),
        json_url: entry.url.clone(),
        source_url: entry.source_url.clone(),
        file_match: entry.file_match.clone(),
        versions,
        group_name: group_name.map(String::from),
        group_key: group_key.map(String::from),
        breadcrumbs,
        schema_doc,
    }
}

/// Convert markdown text to HTML using pulldown-cmark.
///
/// External links are annotated with `target="_blank" rel="noopener noreferrer"`.
fn md_to_html(text: &str) -> String {
    use pulldown_cmark::{Options, Parser, html};

    let mut opts = Options::empty();
    opts.insert(Options::ENABLE_TABLES);
    opts.insert(Options::ENABLE_STRIKETHROUGH);

    let parser = Parser::new_ext(text, opts);
    let mut html_output = String::new();
    html::push_html(&mut html_output, parser);
    // Add target="_blank" to external links
    html_output = html_output
        .replace(
            "<a href=\"https://",
            "<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://",
        )
        .replace(
            "<a href=\"http://",
            "<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"http://",
        );
    html_output
}

/// Build a version detail page context.
#[allow(clippy::too_many_arguments)]
pub fn build_version_page(
    site: &SiteInfo,
    schema_name: &str,
    version_name: &str,
    page_url: &str,
    json_url: &str,
    schema_page_url: &str,
    group_name: Option<&str>,
    group_key: Option<&str>,
    schema_doc: Option<SchemaDoc>,
) -> VersionPage {
    let mut breadcrumbs = vec![Breadcrumb {
        label: String::from("Home"),
        url: Some(site.base_path.clone()),
    }];
    if let (Some(gn), Some(gk)) = (group_name, group_key) {
        breadcrumbs.push(Breadcrumb {
            label: String::from(gn),
            url: Some(alloc::format!("{}schemas/{}/", site.base_path, gk)),
        });
    }
    breadcrumbs.push(Breadcrumb {
        label: String::from(schema_name),
        url: Some(alloc::format!("{}{}", site.base_path, schema_page_url)),
    });
    breadcrumbs.push(Breadcrumb {
        label: String::from(version_name),
        url: None,
    });

    VersionPage {
        site: site.clone(),
        version_name: String::from(version_name),
        schema_name: String::from(schema_name),
        page_url: String::from(page_url),
        json_url: String::from(json_url),
        schema_page_url: alloc::format!("{}{}", site.base_path, schema_page_url),
        group_name: group_name.map(String::from),
        group_key: group_key.map(String::from),
        breadcrumbs,
        schema_doc,
    }
}

/// Strip `base_url` prefix and `/latest.json` suffix to get the schema page path.
///
/// Returns `None` if the URL doesn't start with `base_url` (i.e. remote schema).
pub fn schema_page_url(schema_url: &str, base_url: &str) -> Option<String> {
    let relative = schema_url.strip_prefix(base_url)?;
    let path = relative.strip_suffix("latest.json").unwrap_or(relative);
    Some(ensure_trailing_slash(path))
}

/// Strip `base_url` prefix and `.json` suffix, add trailing slash for version page URL.
pub fn version_page_url(version_url: &str, base_url: &str) -> Option<String> {
    let relative = version_url.strip_prefix(base_url)?;
    let path = relative.strip_suffix(".json").unwrap_or(relative);
    Some(ensure_trailing_slash(path))
}

fn schema_card(entry: &SchemaEntry, base_url: &str) -> Option<SchemaCard> {
    let url = schema_page_url(&entry.url, base_url)?;
    Some(SchemaCard {
        name: entry.name.clone(),
        description: entry.description.clone(),
        url,
        file_match: entry.file_match.clone(),
    })
}

fn ensure_trailing_slash(s: &str) -> String {
    if s.ends_with('/') {
        String::from(s)
    } else {
        alloc::format!("{s}/")
    }
}

fn assigned_schema_names(groups: &[CatalogGroup]) -> alloc::collections::BTreeSet<&str> {
    let mut set = alloc::collections::BTreeSet::new();
    for g in groups {
        for s in &g.schemas {
            set.insert(s.as_str());
        }
    }
    set
}

fn group_schema_count(groups: &[CatalogGroup], group_name: &str) -> usize {
    groups
        .iter()
        .find(|g| g.name == group_name)
        .map_or(0, |g| g.schemas.len())
}

/// Build a descriptive SEO meta description for a schema page.
///
/// Includes group name, schema description, and file match patterns to
/// maximise the useful information within Google's ~155-char limit.
fn build_schema_seo_description(entry: &SchemaEntry, group_name: Option<&str>) -> String {
    let mut parts = Vec::new();

    // Lead with "GroupName SchemaName JSON Schema" or "SchemaName JSON Schema"
    if let Some(gn) = group_name {
        parts.push(alloc::format!("{} {} JSON Schema.", gn, entry.name));
    } else {
        parts.push(alloc::format!("{} JSON Schema.", entry.name));
    }

    // Add description if non-empty
    if !entry.description.is_empty() {
        parts.push(ensure_sentence_end(&entry.description));
    }

    // Add file match patterns
    if !entry.file_match.is_empty() {
        let patterns: Vec<&str> = entry.file_match.iter().map(String::as_str).collect();
        parts.push(alloc::format!("Matches: {}.", patterns.join(", ")));
    }

    parts.join(" ")
}

/// Ensure a string ends with a sentence-ending punctuation mark.
fn ensure_sentence_end(s: &str) -> String {
    let trimmed = s.trim();
    if trimmed.ends_with('.') || trimmed.ends_with('!') || trimmed.ends_with('?') {
        String::from(trimmed)
    } else {
        alloc::format!("{trimmed}.")
    }
}

/// Format a number with comma separators (e.g. `1234` → `"1,234"`).
fn format_number(n: usize) -> String {
    let s = alloc::format!("{n}");
    let mut result = String::new();
    for (i, c) in s.chars().rev().enumerate() {
        if i > 0 && i % 3 == 0 {
            result.push(',');
        }
        result.push(c);
    }
    result.chars().rev().collect()
}

/// Build a mapping from schema name to `(group_key, group_name)`.
pub fn schema_group_map<'a>(
    catalog: &'a Catalog,
    groups_meta: &'a [(String, String, String)],
) -> BTreeMap<&'a str, (&'a str, &'a str)> {
    let mut map = BTreeMap::new();
    for group in &catalog.groups {
        let meta = groups_meta.iter().find(|(_, name, _)| *name == group.name);
        if let Some((key, name, _)) = meta {
            for schema_name in &group.schemas {
                map.insert(schema_name.as_str(), (key.as_str(), name.as_str()));
            }
        }
    }
    map
}