moss-core 0.1.1

Pure-Rust content engine for moss: AST, render, resolve, validate, frontmatter, schema.
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
//! The single reference classifier shared by build + editor (asset/file-embed/
//! folder kinds). Pure; indexes injected via ReferenceContext. Page-Link
//! emission is out of scope here (the build keeps relative_pretty_url/page_map);
//! Link is classify-only. Named `classify_reference` to avoid colliding with
//! `fuzzy_path::resolve_reference` (the [[note]]/ContentGraph resolver).

use crate::resolve::asset_class::{AssetIndex, AssetProvenance};
use crate::resolve::embed_renderer::Sizing;
use crate::resolve::folder_class::FolderIndex;
use crate::resolve::link_class::UrlIndex;

#[cfg_attr(feature = "specta", derive(specta::Type))]
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "kebab-case", tag = "kind", content = "data")]
pub enum ReferenceKind {
    Link { anchor: Option<String> },
    Image,
    Iframe,
    Pdf,
    Video,
    Audio,
    Model,
    FolderListing,
    FolderIndexIframe,
    Transclusion,
    Notebook,
    Table,
    External { url: String },
    Anchor,
    Ambiguous,
    NotFound,
}

/// Index handles a classify call needs. Bundled so the signature stays small
/// and a future index can be added without re-touching every caller.
pub struct ReferenceContext<'a> {
    pub assets: &'a dyn AssetIndex,
    pub folders: &'a dyn FolderIndex,
    /// Link arm only; the build supplies a graph-backed impl in sub-project #4.
    /// For unit #1+#2 a Link result is classify-only and this may be a no-op.
    pub urls: &'a dyn UrlIndex,
}

#[cfg_attr(feature = "specta", derive(specta::Type))]
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ResolvedReference {
    pub kind: ReferenceKind,
    /// Root-relative SOURCE path (real case) for file/folder kinds; None for
    /// Link/External/Anchor/Ambiguous/NotFound.
    pub target_path: Option<String>,
    pub size: Option<Sizing>,
    pub provenance: Option<AssetProvenance>,
    /// Human-readable resolution note (separator-fallback / case-mismatch / …).
    pub message: Option<String>,
    /// Populated for Ambiguous (all candidate paths).
    pub candidates: Vec<String>,
    /// Resolved page/asset URL for a non-embed Link (None for embeds — the
    /// build emits embed URLs itself; editor embeds use `target_path`).
    pub url: Option<String>,
}

impl ResolvedReference {
    pub(crate) fn not_found() -> Self {
        ResolvedReference {
            kind: ReferenceKind::NotFound,
            target_path: None,
            size: None,
            provenance: None,
            message: None,
            candidates: Vec::new(),
            url: None,
        }
    }
    /// Invariant: target_path is Some iff kind is a file/folder kind.
    pub(crate) fn debug_check_invariant(&self) {
        let has_path = matches!(
            self.kind,
            ReferenceKind::Image
                | ReferenceKind::Iframe
                | ReferenceKind::Pdf
                | ReferenceKind::Video
                | ReferenceKind::Audio
                | ReferenceKind::Model
                | ReferenceKind::FolderListing
                | ReferenceKind::FolderIndexIframe
                | ReferenceKind::Transclusion
                | ReferenceKind::Notebook
                | ReferenceKind::Table
        );
        debug_assert_eq!(
            has_path,
            self.target_path.is_some(),
            "target_path presence must match kind: {:?}",
            self.kind
        );
    }
}

/// Classify a reference's inner text (target + optional |pothole / #anchor /
/// ?query) into a kind + resolved source path. Pure.
pub fn classify_reference(
    inner: &str,
    from_source: &str,
    is_embed: bool,
    ctx: &ReferenceContext,
) -> ResolvedReference {
    let inner = inner.trim();

    // External short-circuits (mirror classify_link's exception list).
    const EXTERNAL_PREFIXES: &[&str] =
        &["http://", "https://", "//", "mailto:", "tel:", "data:"];
    if EXTERNAL_PREFIXES.iter().any(|p| inner.starts_with(p)) {
        let mut r = ResolvedReference::not_found();
        r.kind = ReferenceKind::External { url: inner.to_string() };
        r.debug_check_invariant();
        return r;
    }
    // Pure anchor / query (no path component).
    if inner.starts_with('#') || inner.starts_with('?') {
        let mut r = ResolvedReference::not_found();
        r.kind = ReferenceKind::Anchor;
        return r;
    }

    // Split off |pothole, then #anchor.
    let (path_part, pothole) = match inner.split_once('|') {
        Some((p, rest)) => (p.trim(), Some(rest)),
        None => (inner, None),
    };
    let (path_no_anchor, anchor) = match path_part.split_once('#') {
        Some((p, a)) => (p.trim(), Some(a.to_string())),
        None => (path_part, None),
    };
    let size = pothole.and_then(crate::resolve::embed_renderer::Sizing::parse);

    // Non-embed mode: a `[[note]]` / `[](path)` reference is a Link resolved
    // against the deployed URL space (`ctx.urls`), NOT an embed kind. This runs
    // BEFORE the folder/file arms so it cannot mis-route a non-embed reference
    // to Transclusion/Image/Folder. The BUILD always passes `is_embed=true`
    // (folder markers), so this branch is dead for the build — the folder arm
    // below short-circuits there.
    if !is_embed {
        use crate::resolve::link_class::{classify_link, LinkClass};
        return match classify_link(path_no_anchor, from_source, ctx.urls) {
            LinkClass::Resolved { url } => {
                let full = match &anchor {
                    Some(a) => format!("{}#{}", url, a),
                    None => url,
                };
                let mut r = ResolvedReference::not_found();
                r.kind = ReferenceKind::Link { anchor: anchor.clone() };
                r.url = Some(full);
                r
            }
            LinkClass::Mismatch { canonical } => {
                // A page exists but the link won't hit its canonical URL
                // (case/slug). Surface it as a Link pointing at the canonical
                // URL, with a note explaining the redirect.
                let full = match &anchor {
                    Some(a) => format!("{}#{}", canonical, a),
                    None => canonical.clone(),
                };
                let mut r = ResolvedReference::not_found();
                r.kind = ReferenceKind::Link { anchor: anchor.clone() };
                r.url = Some(full);
                r.message = Some(format!("resolves to canonical URL {}", canonical));
                r
            }
            LinkClass::External => {
                let mut r = ResolvedReference::not_found();
                r.kind = ReferenceKind::External { url: path_no_anchor.to_string() };
                r
            }
            LinkClass::Anchor => {
                let mut r = ResolvedReference::not_found();
                r.kind = ReferenceKind::Anchor;
                r
            }
            // Broken: no deployed page for this internal reference.
            LinkClass::Broken => ResolvedReference::not_found(),
        };
    }

    use crate::resolve::asset_class::{resolve_asset_ref, AssetResolution};
    use crate::resolve::ext_kind::{reference_kind_for_ext, ExtKind};

    // Folder arm: trailing slash, or the target resolves to a directory.
    let looks_like_folder = path_no_anchor.ends_with('/');
    let folder_rel: Option<String> = if let Some(abs) = path_no_anchor.strip_prefix('/') {
        Some(abs.trim_end_matches('/').to_string())
    } else if looks_like_folder {
        // source-relative lexical join against from_source's directory
        let from_dir = crate::resolve::parent_dir(from_source);
        let mut parts: Vec<&str> = if from_dir.is_empty() {
            vec![]
        } else {
            from_dir.split('/').collect()
        };
        for seg in path_no_anchor.trim_end_matches('/').split('/') {
            match seg {
                "" | "." => {}
                ".." => {
                    parts.pop();
                }
                s => parts.push(s),
            }
        }
        Some(parts.join("/"))
    } else {
        None
    };
    if let Some(folder_rel) = folder_rel {
        // Only treat this as a folder reference when it is one: an explicit
        // trailing slash, or a path that the folder index resolves to a real
        // directory. A leading-slash path WITHOUT a trailing slash (e.g. an
        // absolute file embed `/assets/photo.png`) is NOT a folder — it must
        // fall through to the file arm and resolve as the asset it names.
        let is_folder = looks_like_folder || ctx.folders.is_dir(&folder_rel);
        if is_folder {
            if ctx.folders.dir_has_markdown_index(&folder_rel) {
                let mut r = ResolvedReference::not_found();
                r.kind = ReferenceKind::FolderListing;
                r.target_path = Some(folder_rel);
                r.size = size;
                r.debug_check_invariant();
                return r;
            }
            if ctx.folders.dir_has_static_index(&folder_rel).is_some() {
                let mut r = ResolvedReference::not_found();
                r.kind = ReferenceKind::FolderIndexIframe;
                r.target_path = Some(folder_rel);
                r.size = size;
                r.debug_check_invariant();
                return r;
            }
            // A confirmed folder (explicit trailing slash, or a real directory)
            // without an index is NotFound — it must NOT fall through to the
            // file arm (a folder path is never a file asset).
            return ResolvedReference::not_found();
        }
    }

    // File arm.
    let ext = path_no_anchor.rsplit('.').next().unwrap_or("").to_lowercase();
    let ext_kind = reference_kind_for_ext(&ext);
    match resolve_asset_ref(path_no_anchor, from_source, ctx.assets) {
        AssetResolution::Resolved { root_rel, provenance } => {
            let kind = match ext_kind {
                ExtKind::Image => ReferenceKind::Image,
                ExtKind::Iframe => ReferenceKind::Iframe,
                ExtKind::Pdf => ReferenceKind::Pdf,
                ExtKind::Video => ReferenceKind::Video,
                ExtKind::Audio => ReferenceKind::Audio,
                ExtKind::Model => ReferenceKind::Model,
                ExtKind::Transclusion => ReferenceKind::Transclusion,
                ExtKind::Notebook => ReferenceKind::Notebook,
                ExtKind::Table => ReferenceKind::Table,
                // A resolved file with an UNKNOWN extension is a Link target (no embed path).
                ExtKind::Other => ReferenceKind::Link { anchor: anchor.clone() },
            };
            let is_link = matches!(kind, ReferenceKind::Link { .. });
            let mut r = ResolvedReference::not_found();
            r.kind = kind;
            r.target_path = if is_link { None } else { Some(root_rel) };
            r.size = size;
            r.provenance = Some(provenance);
            r.debug_check_invariant();
            r
        }
        AssetResolution::Ambiguous { candidates, .. } => {
            let mut r = ResolvedReference::not_found();
            r.kind = ReferenceKind::Ambiguous;
            r.candidates = candidates;
            r
        }
        AssetResolution::NotFound => {
            if matches!(ext_kind, ExtKind::Other) {
                // An unresolved reference with no known file extension is a note
                // link (classify-only here; link resolution/emission is sub-project #4).
                let mut r = ResolvedReference::not_found();
                r.kind = ReferenceKind::Link { anchor };
                r
            } else {
                // A known-extension asset that didn't resolve is a broken embed.
                ResolvedReference::not_found()
            }
        }
    }
}

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

    use crate::resolve::asset_class::FakeAssetIndex;
    use crate::resolve::folder_class::FakeFolderIndex;
    use crate::resolve::link_class::FakeUrlIndex;

    fn ctx<'a>(
        a: &'a FakeAssetIndex,
        f: &'a FakeFolderIndex,
        u: &'a FakeUrlIndex,
    ) -> ReferenceContext<'a> {
        ReferenceContext { assets: a, folders: f, urls: u }
    }

    #[test]
    fn external_url_is_external() {
        let a = FakeAssetIndex::new(&[]);
        let f = FakeFolderIndex::new();
        let u = FakeUrlIndex::new();
        let r = classify_reference("https://example.com/x", "page.md", true, &ctx(&a, &f, &u));
        assert_eq!(r.kind, ReferenceKind::External { url: "https://example.com/x".into() });
        assert!(r.target_path.is_none());
    }

    #[test]
    fn bare_anchor_is_anchor() {
        let a = FakeAssetIndex::new(&[]);
        let f = FakeFolderIndex::new();
        let u = FakeUrlIndex::new();
        let r = classify_reference("#section", "page.md", true, &ctx(&a, &f, &u));
        assert_eq!(r.kind, ReferenceKind::Anchor);
    }

    #[test]
    fn not_found_has_no_path() {
        let r = ResolvedReference::not_found();
        assert_eq!(r.kind, ReferenceKind::NotFound);
        assert!(r.target_path.is_none());
        r.debug_check_invariant();
    }

    #[test]
    fn image_file_resolves_to_image_kind() {
        let a = FakeAssetIndex::new(&["assets/photo.png"]);
        let f = FakeFolderIndex::new();
        let u = FakeUrlIndex::new();
        let r = classify_reference("photo.png", "page.md", true, &ctx(&a, &f, &u));
        assert_eq!(r.kind, ReferenceKind::Image);
        assert_eq!(r.target_path.as_deref(), Some("assets/photo.png"));
        r.debug_check_invariant();
    }

    #[test]
    fn html_file_resolves_to_iframe_with_size() {
        let a = FakeAssetIndex::new(&["widgets/app.html"]);
        let f = FakeFolderIndex::new();
        let u = FakeUrlIndex::new();
        let r = classify_reference("widgets/app.html|800x600", "page.md", true, &ctx(&a, &f, &u));
        assert_eq!(r.kind, ReferenceKind::Iframe);
        assert!(matches!(r.size, Some(crate::resolve::embed_renderer::Sizing::Box(_, _))));
    }

    #[test]
    fn ambiguous_file_match_sets_candidates() {
        let a = FakeAssetIndex::new(&["a/logo.png", "b/logo.png"]);
        let f = FakeFolderIndex::new();
        let u = FakeUrlIndex::new();
        let r = classify_reference("logo.png", "page.md", true, &ctx(&a, &f, &u));
        assert_eq!(r.kind, ReferenceKind::Ambiguous);
        assert_eq!(r.candidates.len(), 2);
    }

    #[test]
    fn folder_with_static_index_is_iframe() {
        let a = FakeAssetIndex::new(&[]);
        let mut f = FakeFolderIndex::new();
        f.dirs.insert("Resources/app".into());
        f.static_index.insert("Resources/app".into(), "index.html".into());
        let u = FakeUrlIndex::new();
        let r = classify_reference("/Resources/app/", "page.md", true, &ctx(&a, &f, &u));
        assert_eq!(r.kind, ReferenceKind::FolderIndexIframe);
        assert_eq!(r.target_path.as_deref(), Some("Resources/app"));
        r.debug_check_invariant();
    }

    #[test]
    fn folder_with_markdown_index_is_listing() {
        let a = FakeAssetIndex::new(&[]);
        let mut f = FakeFolderIndex::new();
        f.dirs.insert("news".into());
        f.md_index.insert("news".into());
        let u = FakeUrlIndex::new();
        let r = classify_reference("/news/", "page.md", true, &ctx(&a, &f, &u));
        assert_eq!(r.kind, ReferenceKind::FolderListing);
        r.debug_check_invariant();
    }

    #[test]
    fn absolute_file_embed_resolves_to_image() {
        // A leading-slash path with NO trailing slash, naming a real asset, is a
        // file embed — not a folder. The folder arm must let it fall through to
        // the file arm so `![[/assets/photo.png]]` resolves as an Image.
        let a = FakeAssetIndex::new(&["assets/photo.png"]);
        let f = FakeFolderIndex::new(); // NOT a dir, no indexes
        let u = FakeUrlIndex::new();
        let r = classify_reference("/assets/photo.png", "page.md", true, &ctx(&a, &f, &u));
        assert_eq!(r.kind, ReferenceKind::Image);
        assert_eq!(r.target_path.as_deref(), Some("assets/photo.png"));
        r.debug_check_invariant();
    }

    #[test]
    fn trailing_slash_unresolved_folder_is_not_found() {
        let a = FakeAssetIndex::new(&[]);
        let f = FakeFolderIndex::new(); // empty: not a dir, no indexes
        let u = FakeUrlIndex::new();
        let r = classify_reference("/ghost/", "page.md", true, &ctx(&a, &f, &u));
        assert_eq!(r.kind, ReferenceKind::NotFound);
    }

    #[test]
    fn bare_note_name_is_link() {
        let a = FakeAssetIndex::new(&[]);
        let f = FakeFolderIndex::new();
        let u = FakeUrlIndex::new();
        let r = classify_reference("some-note", "page.md", true, &ctx(&a, &f, &u));
        assert_eq!(r.kind, ReferenceKind::Link { anchor: None });
        assert!(r.target_path.is_none());
        r.debug_check_invariant();
    }

    #[test]
    fn missing_known_ext_asset_is_not_found() {
        // A known image extension that doesn't resolve stays NotFound (it is a
        // broken asset embed, not a note link).
        let a = FakeAssetIndex::new(&[]);
        let f = FakeFolderIndex::new();
        let u = FakeUrlIndex::new();
        let r = classify_reference("missing.png", "page.md", true, &ctx(&a, &f, &u));
        assert_eq!(r.kind, ReferenceKind::NotFound);
    }

    #[test]
    fn non_embed_md_note_resolves_as_link_not_transclusion() {
        let a = FakeAssetIndex::new(&["note.md"]);
        let f = FakeFolderIndex::new();
        let u = FakeUrlIndex::resolving(&[("note.md", "/note/")]);
        let r = classify_reference("note.md", "page.md", false, &ctx(&a, &f, &u));
        assert_eq!(r.kind, ReferenceKind::Link { anchor: None });
        assert_eq!(r.url.as_deref(), Some("/note/"));
    }

    #[test]
    fn embed_md_is_still_transclusion() {
        let a = FakeAssetIndex::new(&["note.md"]);
        let f = FakeFolderIndex::new();
        let u = FakeUrlIndex::new();
        let r = classify_reference("note.md", "page.md", true, &ctx(&a, &f, &u));
        assert_eq!(r.kind, ReferenceKind::Transclusion);
    }

    #[test]
    fn non_embed_link_carries_anchor() {
        let a = FakeAssetIndex::new(&[]);
        let f = FakeFolderIndex::new();
        let u = FakeUrlIndex::resolving(&[("note", "/note/")]);
        let r = classify_reference("note#heading", "page.md", false, &ctx(&a, &f, &u));
        assert_eq!(r.kind, ReferenceKind::Link { anchor: Some("heading".into()) });
        assert_eq!(r.url.as_deref(), Some("/note/#heading"));
    }

    #[test]
    fn build_safety_folder_marker_ignores_urls() {
        let a = FakeAssetIndex::new(&[]);
        let mut f = FakeFolderIndex::new();
        f.dirs.insert("app".into());
        f.static_index.insert("app".into(), "index.html".into());
        let u = FakeUrlIndex::new();
        let r = classify_reference("/app/", "page.md", true, &ctx(&a, &f, &u));
        assert_eq!(r.kind, ReferenceKind::FolderIndexIframe);
    }
}