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
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
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
use std::collections::{HashMap, HashSet};
use std::path::Path;

use anyhow::{Context, Result};
use futures_util::stream::StreamExt;
use lintel_schema_cache::SchemaCache;
use tracing::{debug, error, info, warn};

use crate::download::ProcessedSchemas;

/// Shared context for [`resolve_and_rewrite`], grouping cross-cutting state
/// that would otherwise require many individual arguments.
pub struct RefRewriteContext<'a> {
    pub cache: &'a SchemaCache,
    pub shared_dir: &'a Path,
    pub base_url_for_shared: &'a str,
    pub already_downloaded: &'a mut HashMap<String, String>,
    /// Original source URL of the schema being processed. Used to resolve
    /// relative `$ref` values (e.g. `./rule.json`) against the schema's origin.
    pub source_url: Option<String>,
    pub processed: &'a ProcessedSchemas,
    /// Pre-computed source identifier and SHA-256 hash for `x-lintel` injection.
    ///
    /// Used for local schemas that aren't in the HTTP cache. When set, this
    /// takes priority over cache-based injection from `source_url`.
    /// Format: `(source_identifier, sha256_hex)`.
    pub lintel_source: Option<(String, String)>,
    /// Local directory containing source schemas. When set, relative `$ref`
    /// paths are resolved against this directory (read from disk) instead of
    /// downloading from the computed URL. This is used for local schemas whose
    /// source files may not be available at the `source_url` yet.
    pub local_source_dir: Option<&'a Path>,
    /// Maps relative `$ref` paths (e.g. `./hooks.json`) to canonical catalog
    /// URLs for sibling schemas in the same group. When a relative ref matches
    /// a key here, it is rewritten directly without downloading.
    pub sibling_urls: HashMap<String, String>,
    /// Glob patterns from the catalog entry, injected into `x-lintel.fileMatch`.
    pub file_match: Vec<String>,
    /// Explicit parsers extracted from `x-lintel.parsers`.
    /// When non-empty, used as-is; otherwise derived from `file_match` extensions.
    pub parsers: Vec<schema_catalog::FileFormat>,
}

/// Recursively scan a JSON value for `$ref` strings that are absolute HTTP(S) URLs.
/// Returns the set of base URLs (fragments stripped).
pub fn find_external_refs(value: &serde_json::Value) -> HashSet<String> {
    let mut refs = HashSet::new();
    collect_refs(value, &mut refs);
    refs
}

/// Recursively scan a JSON value for `$ref` strings that are relative file
/// references (e.g. `./rule.json`, `../other.json`).  Returns the set of
/// relative paths (fragments stripped).  Internal `#/…` refs are excluded.
pub fn find_relative_refs(value: &serde_json::Value) -> HashSet<String> {
    let mut refs = HashSet::new();
    collect_relative_refs(value, &mut refs);
    refs
}

fn collect_refs(value: &serde_json::Value, refs: &mut HashSet<String>) {
    match value {
        serde_json::Value::Object(map) => {
            if let Some(serde_json::Value::String(ref_str)) = map.get("$ref")
                && (ref_str.starts_with("http://") || ref_str.starts_with("https://"))
            {
                // Strip fragment
                let base = ref_str.split('#').next().unwrap_or(ref_str);
                if !base.is_empty() {
                    refs.insert(base.to_string());
                }
            }
            for v in map.values() {
                collect_refs(v, refs);
            }
        }
        serde_json::Value::Array(arr) => {
            for v in arr {
                collect_refs(v, refs);
            }
        }
        _ => {}
    }
}

fn collect_relative_refs(value: &serde_json::Value, refs: &mut HashSet<String>) {
    match value {
        serde_json::Value::Object(map) => {
            if let Some(serde_json::Value::String(ref_str)) = map.get("$ref") {
                let base = ref_str.split('#').next().unwrap_or(ref_str);
                // Relative ref: not empty, not a fragment-only ref, not an absolute URL
                if !base.is_empty() && !base.starts_with("http://") && !base.starts_with("https://")
                {
                    refs.insert(base.to_string());
                }
            }
            for v in map.values() {
                collect_relative_refs(v, refs);
            }
        }
        serde_json::Value::Array(arr) => {
            for v in arr {
                collect_relative_refs(v, refs);
            }
        }
        _ => {}
    }
}

/// Resolve a relative path against a base URL.
///
/// For example, resolving `./rule.json` against
/// `https://example.com/schemas/project.json` yields
/// `https://example.com/schemas/rule.json`.
fn resolve_relative_url(relative: &str, base_url: &str) -> Result<String> {
    let base =
        url::Url::parse(base_url).with_context(|| format!("invalid base URL: {base_url}"))?;
    let resolved = base
        .join(relative)
        .with_context(|| format!("failed to resolve '{relative}' against '{base_url}'"))?;
    Ok(resolved.to_string())
}

/// Extract a filename from a URL's last path segment.
///
/// Falls back to the domain name with `.json` extension if the URL has no
/// meaningful path segments (e.g. `https://meta.json-schema.tools`).
///
/// # Errors
///
/// Returns an error if the URL cannot be parsed.
pub fn filename_from_url(url: &str) -> Result<String> {
    let parsed = url::Url::parse(url).with_context(|| format!("invalid URL: {url}"))?;
    let segments: Vec<&str> = parsed
        .path_segments()
        .map(Iterator::collect)
        .unwrap_or_default();
    if let Some(last) = segments.last().filter(|s| !s.is_empty()) {
        let name = (*last).to_string();
        // Ensure .json extension so the HTML generator can safely strip it
        // to create a directory path that won't collide with the file.
        if std::path::Path::new(&name)
            .extension()
            .is_some_and(|ext| ext.eq_ignore_ascii_case("json"))
        {
            return Ok(name);
        }
        return Ok(format!("{name}.json"));
    }
    // No path segments — use domain as filename
    let host = parsed
        .host_str()
        .with_context(|| format!("URL has no host: {url}"))?;
    Ok(format!("{host}.json"))
}

/// Generate a unique filename in a directory, adding numeric suffixes on collision.
///
/// Given `base.json`, tries `base.json`, `base-2.json`, `base-3.json`, etc.
fn unique_filename_in(dir: &Path, base: &str) -> String {
    if !dir.join(base).exists() {
        return base.to_string();
    }
    let (stem, ext) = match base.rfind('.') {
        Some(pos) => (&base[..pos], &base[pos..]),
        None => (base, ""),
    };
    let mut n = 2u32;
    loop {
        let candidate = format!("{stem}-{n}{ext}");
        if !dir.join(&candidate).exists() {
            return candidate;
        }
        n += 1;
    }
}

/// Rewrite `$ref` URLs in a JSON value using the provided mapping.
/// Preserves fragments (e.g. `#/definitions/Foo`).
pub fn rewrite_refs(value: &mut serde_json::Value, url_map: &HashMap<String, String>) {
    match value {
        serde_json::Value::Object(map) => {
            if let Some(serde_json::Value::String(ref_str)) = map.get("$ref") {
                let (base, fragment) = match ref_str.split_once('#') {
                    Some((b, f)) => (b, Some(f)),
                    None => (ref_str.as_str(), None),
                };
                if let Some(new_base) = url_map.get(base) {
                    let new_ref = match fragment {
                        Some(f) => format!("{new_base}#{f}"),
                        None => new_base.clone(),
                    };
                    map.insert("$ref".to_string(), serde_json::Value::String(new_ref));
                }
            }
            for v in map.values_mut() {
                rewrite_refs(v, url_map);
            }
        }
        serde_json::Value::Array(arr) => {
            for v in arr {
                rewrite_refs(v, url_map);
            }
        }
        _ => {}
    }
}

/// Resolve all relative `$ref` paths in a schema against a source URL.
///
/// Returns a map from relative path → absolute URL for each successfully resolved
/// ref.  When `source_url` is `None` or resolution fails for a particular ref,
/// that ref is skipped with a debug/warning log.
fn resolve_all_relative_refs(
    value: &serde_json::Value,
    source_url: Option<&str>,
) -> HashMap<String, String> {
    let relative_refs = find_relative_refs(value);
    let mut resolved: HashMap<String, String> = HashMap::new();
    if let Some(source_url) = source_url {
        for rel_ref in &relative_refs {
            match resolve_relative_url(rel_ref, source_url) {
                Ok(abs_url) => {
                    debug!(relative = %rel_ref, resolved = %abs_url, "resolved relative $ref");
                    resolved.insert(rel_ref.clone(), abs_url);
                }
                Err(e) => {
                    warn!(relative = %rel_ref, error = %e, "failed to resolve relative $ref");
                }
            }
        }
    } else if !relative_refs.is_empty() {
        debug!(
            count = relative_refs.len(),
            "skipping relative $ref resolution (no source URL)"
        );
    }
    resolved
}

/// Build a [`PostprocessContext`] from the shared [`RefRewriteContext`].
fn postprocess_ctx<'a>(ctx: &RefRewriteContext<'a>) -> crate::postprocess::PostprocessContext<'a> {
    crate::postprocess::PostprocessContext {
        cache: ctx.cache,
        source_url: ctx.source_url.clone(),
        lintel_source: ctx.lintel_source.clone(),
        file_match: ctx.file_match.clone(),
        parsers: ctx.parsers.clone(),
    }
}

/// Download all `$ref` dependencies for a schema, rewrite URLs to local paths,
/// and write the updated schema. Handles transitive dependencies via BFS
/// concurrent resolution.
///
/// - `ctx`: shared context containing the schema cache, shared directory,
///   base URL for the shared directory, and already-downloaded map
/// - `schema_text`: the JSON text of the schema
/// - `schema_dest`: where to write the rewritten schema
///
/// Filenames in `_shared/` are prefixed with the parent schema stem
/// (e.g. `github-workflow--schema.json`) and disambiguated with numeric
/// suffixes when collisions remain.
pub async fn resolve_and_rewrite(
    ctx: &mut RefRewriteContext<'_>,
    schema_text: &str,
    schema_dest: &Path,
    schema_url: &str,
) -> Result<()> {
    let mut value: serde_json::Value =
        serde_json::from_str(schema_text).context("failed to parse schema JSON")?;

    resolve_and_rewrite_value(ctx, &mut value, schema_dest, schema_url).await
}

/// Like [`resolve_and_rewrite`] but takes an already-parsed `Value`, avoiding
/// a redundant parse when the caller already has the JSON in memory.
pub async fn resolve_and_rewrite_value(
    ctx: &mut RefRewriteContext<'_>,
    value: &mut serde_json::Value,
    schema_dest: &Path,
    schema_url: &str,
) -> Result<()> {
    // Set $id to the canonical URL where this schema will be hosted
    value
        .as_object_mut()
        .context("schema root must be an object")?
        .insert(
            "$id".to_string(),
            serde_json::Value::String(schema_url.to_string()),
        );

    jsonschema_migrate::migrate_to_2020_12(value);
    if let Err(e) = serde_json::from_value::<jsonschema_migrate::Schema>(value.clone()) {
        error!(url = %schema_url, error = %e, "schema failed to deserialize after migration");
    }

    let external_refs = find_external_refs(value);
    let relative_refs = find_relative_refs(value);

    // Resolve sibling refs directly (same-group schemas with known catalog URLs).
    // These don't need downloading — just rewrite in place.
    let mut sibling_map: HashMap<String, String> = HashMap::new();
    let mut unresolved_relative: HashSet<String> = HashSet::new();
    for rel in &relative_refs {
        if let Some(canonical) = ctx.sibling_urls.get(rel.as_str()) {
            debug!(relative = %rel, resolved = %canonical, "resolved sibling $ref");
            sibling_map.insert(rel.clone(), canonical.clone());
        } else {
            unresolved_relative.insert(rel.clone());
        }
    }
    if !sibling_map.is_empty() {
        rewrite_refs(value, &sibling_map);
    }

    // Resolve remaining relative refs against source_url for download
    let resolved_relative = if unresolved_relative.is_empty() {
        HashMap::new()
    } else {
        let all_resolved = resolve_all_relative_refs(value, ctx.source_url.as_deref());
        all_resolved
            .into_iter()
            .filter(|(rel, _)| unresolved_relative.contains(rel))
            .collect::<HashMap<_, _>>()
    };

    if external_refs.is_empty() && resolved_relative.is_empty() {
        crate::postprocess::postprocess_schema(&postprocess_ctx(ctx), value);
        crate::download::write_schema_json(value, schema_dest, ctx.processed).await?;
        return Ok(());
    }

    debug!(
        external = external_refs.len(),
        relative = resolved_relative.len(),
        "found $ref dependencies"
    );

    // Seed the queue with all refs from the root schema.
    let pending: Vec<(String, String, Option<String>)> = external_refs
        .iter()
        .map(|url| (url.clone(), url.clone(), Some(url.clone())))
        .chain(
            resolved_relative
                .iter()
                .map(|(rel, abs)| (rel.clone(), abs.clone(), Some(abs.clone()))),
        )
        .collect();

    let parent_stem = schema_dest
        .file_stem()
        .unwrap_or_default()
        .to_string_lossy()
        .to_string();

    // Fetch all transitive deps concurrently via a bounded queue
    let (url_map, dep_values) = fetch_refs_queued(ctx, pending, &parent_stem).await?;

    // Rewrite refs in the root schema and write it
    rewrite_refs(value, &url_map);
    crate::postprocess::postprocess_schema(&postprocess_ctx(ctx), value);
    crate::download::write_schema_json(value, schema_dest, ctx.processed).await?;

    // Process and write each dependency
    write_dep_schemas(ctx, dep_values, &url_map).await?;

    Ok(())
}

/// Check whether a `$ref` key looks like a relative file path (e.g. `./rule.json`,
/// `../other.json`, `subdir/c.json`) as opposed to an absolute HTTP URL.
fn is_relative_path(ref_key: &str) -> bool {
    !ref_key.is_empty()
        && !ref_key.starts_with("http://")
        && !ref_key.starts_with("https://")
        && !ref_key.starts_with('#')
}

/// Scan a dependency value for transitive `$ref`s and enqueue any new ones.
fn enqueue_transitive_refs(
    dep_value: &serde_json::Value,
    source_url: Option<&str>,
    already_downloaded: &HashMap<String, String>,
    pending: &mut Vec<(String, String, Option<String>)>,
) {
    for url in find_external_refs(dep_value) {
        if !already_downloaded.contains_key(&url) {
            pending.push((url.clone(), url.clone(), Some(url.clone())));
        }
    }
    for (rel, abs) in resolve_all_relative_refs(dep_value, source_url) {
        if !already_downloaded.contains_key(&abs) {
            pending.push((rel, abs.clone(), Some(abs)));
        }
    }
}

/// Queue-based concurrent fetcher for `$ref` dependencies. Unlike BFS waves,
/// this starts fetching transitive deps as soon as each parent completes,
/// maintaining up to `concurrency` in-flight fetches at all times.
///
/// Returns `(url_map, dep_values)` where `url_map` maps original `$ref` keys
/// to local URLs and `dep_values` contains the fetched JSON values.
async fn fetch_refs_queued(
    ctx: &mut RefRewriteContext<'_>,
    initial: Vec<(String, String, Option<String>)>,
    parent_stem: &str,
) -> Result<(
    HashMap<String, String>,
    Vec<(String, serde_json::Value, Option<String>)>,
)> {
    let mut url_map: HashMap<String, String> = HashMap::new();
    let mut dep_values: Vec<(String, serde_json::Value, Option<String>)> = Vec::new();
    let mut pending: Vec<(String, String, Option<String>)> = initial;
    let mut in_flight = futures_util::stream::FuturesUnordered::new();
    let mut shared_dir_created = false;

    loop {
        // Drain all pending items into in_flight — the semaphore in
        // SchemaCache handles HTTP concurrency.
        while let Some((ref_key, download_url, source_url)) = pending.pop() {
            if let Some(existing_filename) = ctx.already_downloaded.get(&download_url) {
                let local_url = format!(
                    "{}/{}",
                    ctx.base_url_for_shared.trim_end_matches('/'),
                    existing_filename,
                );
                url_map.insert(ref_key, local_url);
                continue;
            }

            if !shared_dir_created {
                tokio::fs::create_dir_all(ctx.shared_dir).await?;
                shared_dir_created = true;
            }

            let dep_basename = filename_from_url(&download_url)?;
            let base_filename = format!("{parent_stem}--{dep_basename}");
            let filename = unique_filename_in(ctx.shared_dir, &base_filename);
            ctx.already_downloaded
                .insert(download_url.clone(), filename.clone());
            let local_url = format!(
                "{}/{}",
                ctx.base_url_for_shared.trim_end_matches('/'),
                filename,
            );
            url_map.insert(ref_key.clone(), local_url.clone());

            // Try to read from local filesystem for relative refs
            if let Some(local_dir) = ctx.local_source_dir
                && is_relative_path(&ref_key)
            {
                let local_path = local_dir.join(&ref_key);
                if let Ok(text) = tokio::fs::read_to_string(&local_path).await {
                    match serde_json::from_str::<serde_json::Value>(&text) {
                        Ok(dep_value) => {
                            info!(path = %local_path.display(), "read local $ref dependency");
                            enqueue_transitive_refs(
                                &dep_value,
                                source_url.as_deref(),
                                ctx.already_downloaded,
                                &mut pending,
                            );
                            dep_values.push((filename, dep_value, source_url));
                            continue;
                        }
                        Err(e) => {
                            debug!(
                                path = %local_path.display(),
                                error = %e,
                                "local file not valid JSON, falling back to HTTP"
                            );
                        }
                    }
                }
            }

            let cache = ctx.cache.clone();
            in_flight.push(async move {
                let result = crate::download::fetch_one(&cache, &download_url).await;
                (download_url, filename, local_url, source_url, result)
            });
        }

        // Nothing in flight and nothing pending → done
        if in_flight.is_empty() {
            break;
        }

        // Wait for the next completed fetch (safe: we checked !is_empty above)
        let Some((download_url, filename, local_url, source_url, result)) = in_flight.next().await
        else {
            break;
        };

        match result {
            Ok((dep_value, status)) => {
                info!(url = %download_url, status = %status, "downloaded $ref dependency");

                enqueue_transitive_refs(
                    &dep_value,
                    source_url.as_deref(),
                    ctx.already_downloaded,
                    &mut pending,
                );

                dep_values.push((filename, dep_value, source_url));
            }
            Err(e) => {
                warn!(url = %download_url, error = %e, "failed to download $ref dependency, keeping original URL");
                ctx.already_downloaded.remove(&download_url);
                url_map.retain(|_, v| v != &local_url);
            }
        }
    }

    Ok((url_map, dep_values))
}

/// Set `$id`, migrate, rewrite `$ref`s, fix URIs, and write each dependency to
/// disk.
async fn write_dep_schemas(
    ctx: &RefRewriteContext<'_>,
    dep_values: Vec<(String, serde_json::Value, Option<String>)>,
    url_map: &HashMap<String, String>,
) -> Result<()> {
    for (filename, mut dep_value, source_url) in dep_values {
        let dep_dest = ctx.shared_dir.join(&filename);
        let dep_local_url = format!(
            "{}/{}",
            ctx.base_url_for_shared.trim_end_matches('/'),
            filename,
        );

        // Resolve any relative refs in the dep against its source URL
        let dep_relative = resolve_all_relative_refs(&dep_value, source_url.as_deref());
        // Build a combined url_map for this dep: inherited + its own relative refs
        let mut dep_url_map = url_map.clone();
        for (rel, abs) in &dep_relative {
            if let Some(existing_filename) = ctx.already_downloaded.get(abs) {
                let local_url = format!(
                    "{}/{}",
                    ctx.base_url_for_shared.trim_end_matches('/'),
                    existing_filename,
                );
                dep_url_map.insert(rel.clone(), local_url);
            }
        }

        if let Some(obj) = dep_value.as_object_mut() {
            obj.insert("$id".to_string(), serde_json::Value::String(dep_local_url));
        }
        jsonschema_migrate::migrate_to_2020_12(&mut dep_value);
        if let Err(e) = serde_json::from_value::<jsonschema_migrate::Schema>(dep_value.clone()) {
            let dep_url = source_url.as_deref().unwrap_or(&filename);
            error!(url = %dep_url, error = %e, "dependency schema failed to deserialize after migration");
        }
        rewrite_refs(&mut dep_value, &dep_url_map);
        crate::postprocess::postprocess_schema(
            &crate::postprocess::PostprocessContext {
                cache: ctx.cache,
                source_url,
                lintel_source: None,
                file_match: Vec::new(),
                parsers: Vec::new(),
            },
            &mut dep_value,
        );
        crate::download::write_schema_json(&dep_value, &dep_dest, ctx.processed).await?;
    }

    Ok(())
}

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

    #[test]
    fn find_refs_in_simple_schema() {
        let schema = serde_json::json!({
            "$ref": "https://example.com/base.json#/definitions/Foo",
            "properties": {
                "bar": { "$ref": "https://example.com/other.json" },
                "local": { "$ref": "#/definitions/Local" }
            }
        });
        let refs = find_external_refs(&schema);
        assert_eq!(refs.len(), 2);
        assert!(refs.contains("https://example.com/base.json"));
        assert!(refs.contains("https://example.com/other.json"));
    }

    #[test]
    fn find_refs_ignores_relative() {
        let schema = serde_json::json!({
            "$ref": "#/definitions/Local",
            "items": { "$ref": "./local.json" }
        });
        let refs = find_external_refs(&schema);
        assert!(refs.is_empty());
    }

    #[test]
    fn find_refs_in_arrays() {
        let schema = serde_json::json!({
            "oneOf": [
                { "$ref": "https://a.com/one.json" },
                { "$ref": "https://b.com/two.json#/defs/X" }
            ]
        });
        let refs = find_external_refs(&schema);
        assert_eq!(refs.len(), 2);
        assert!(refs.contains("https://a.com/one.json"));
        assert!(refs.contains("https://b.com/two.json"));
    }

    #[test]
    fn filename_from_url_extracts_last_segment() {
        assert_eq!(
            filename_from_url("https://example.com/schemas/foo.json").expect("ok"),
            "foo.json"
        );
    }

    #[test]
    fn filename_from_url_with_path() {
        assert_eq!(
            filename_from_url("https://example.com/a/b/c/my-schema.json").expect("ok"),
            "my-schema.json"
        );
    }

    #[test]
    fn filename_from_url_appends_json_extension() {
        assert_eq!(
            filename_from_url("https://example.com/version/1").expect("ok"),
            "1.json"
        );
        assert_eq!(
            filename_from_url("https://example.com/schemas/feed-1").expect("ok"),
            "feed-1.json"
        );
    }

    #[test]
    fn rewrite_refs_replaces_mapped_urls() {
        let mut schema = serde_json::json!({
            "$ref": "https://example.com/base.json#/definitions/Foo",
            "properties": {
                "bar": { "$ref": "https://example.com/other.json" },
                "local": { "$ref": "#/definitions/Local" }
            }
        });
        let url_map: HashMap<String, String> = [
            (
                "https://example.com/base.json".to_string(),
                "_shared/base.json".to_string(),
            ),
            (
                "https://example.com/other.json".to_string(),
                "_shared/other.json".to_string(),
            ),
        ]
        .into_iter()
        .collect();

        rewrite_refs(&mut schema, &url_map);

        assert_eq!(schema["$ref"], "_shared/base.json#/definitions/Foo");
        assert_eq!(schema["properties"]["bar"]["$ref"], "_shared/other.json");
        // Local refs are untouched
        assert_eq!(schema["properties"]["local"]["$ref"], "#/definitions/Local");
    }

    // --- find_relative_refs ---

    #[test]
    fn find_relative_refs_dot_slash() {
        let schema = serde_json::json!({
            "properties": {
                "rule": { "$ref": "./rule.json#/$defs/SerializableRule" }
            }
        });
        let refs = find_relative_refs(&schema);
        assert_eq!(refs.len(), 1);
        assert!(refs.contains("./rule.json"));
    }

    #[test]
    fn find_relative_refs_ignores_fragment_only() {
        let schema = serde_json::json!({
            "$ref": "#/definitions/Foo",
            "items": { "$ref": "#/$defs/Bar" }
        });
        let refs = find_relative_refs(&schema);
        assert!(refs.is_empty());
    }

    #[test]
    fn find_relative_refs_ignores_http() {
        let schema = serde_json::json!({
            "$ref": "https://example.com/schema.json"
        });
        let refs = find_relative_refs(&schema);
        assert!(refs.is_empty());
    }

    #[test]
    fn find_relative_refs_various_patterns() {
        let schema = serde_json::json!({
            "oneOf": [
                { "$ref": "./a.json" },
                { "$ref": "../b.json#/defs/X" },
                { "$ref": "subdir/c.json" }
            ]
        });
        let refs = find_relative_refs(&schema);
        assert_eq!(refs.len(), 3);
        assert!(refs.contains("./a.json"));
        assert!(refs.contains("../b.json"));
        assert!(refs.contains("subdir/c.json"));
    }

    // --- resolve_relative_url ---

    #[test]
    fn resolve_relative_dot_slash() {
        let result = resolve_relative_url(
            "./rule.json",
            "https://raw.githubusercontent.com/ast-grep/ast-grep/main/schemas/project.json",
        )
        .expect("ok");
        assert_eq!(
            result,
            "https://raw.githubusercontent.com/ast-grep/ast-grep/main/schemas/rule.json"
        );
    }

    #[test]
    fn resolve_relative_parent_dir() {
        let result = resolve_relative_url(
            "../other/schema.json",
            "https://example.com/schemas/sub/main.json",
        )
        .expect("ok");
        assert_eq!(result, "https://example.com/schemas/other/schema.json");
    }

    #[test]
    fn resolve_relative_bare_filename() {
        let result = resolve_relative_url("types.json", "https://example.com/schemas/main.json")
            .expect("ok");
        assert_eq!(result, "https://example.com/schemas/types.json");
    }

    // --- rewrite_refs with relative refs ---

    #[test]
    fn rewrite_refs_replaces_relative_refs() {
        let mut schema = serde_json::json!({
            "properties": {
                "rule": { "$ref": "./rule.json#/$defs/SerializableRule" },
                "local": { "$ref": "#/definitions/Local" }
            }
        });
        let url_map: HashMap<String, String> = [(
            "./rule.json".to_string(),
            "_shared/project--rule.json".to_string(),
        )]
        .into_iter()
        .collect();

        rewrite_refs(&mut schema, &url_map);

        assert_eq!(
            schema["properties"]["rule"]["$ref"],
            "_shared/project--rule.json#/$defs/SerializableRule"
        );
        assert_eq!(schema["properties"]["local"]["$ref"], "#/definitions/Local");
    }
}