devpage-core 0.3.0

devpage's core: documents, rendering, link checking, comments and designs, with no I/O runtime
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
//! Widgets: React components used as capitalized HTML tags in Markdown.
//!
//! On the server a page's widget tags become placeholder elements carrying the
//! widget's name, its props' source and its content ([`tags`]), which comrak
//! renders as Markdown. In the browser the page script loads React and the
//! widgets, compiled here from TSX by oxc ([`compile`]), and mounts each
//! placeholder. What was read and compiled is kept in a [`Modules`] cache.
//!
//! This module is the widget set a document has: its names, the address
//! each is served at, what a page loads, and what a request for one of its
//! modules answers ([`request`]).

mod compile;
pub(crate) use compile::{compile as compile_extension, relative_imports as extension_imports};
mod modules;
mod request;
mod tags;

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::LazyLock;

use anyhow::{Result, anyhow};
use sha2::{Digest, Sha256};

pub use modules::{Modules, Snapshot};
pub use request::{Compiled, project_module, system_module};
pub use tags::expand;

use crate::addresses::{Owned, address};
use crate::document::Document;
use crate::folder::ServedFolder;

/// The widgets devpage ships, compiled into the binary.
pub const SYSTEM: &[(&str, &str)] = &[
    ("Callout", include_str!("../../assets/widgets/Callout.tsx")),
    (
        SIDEBAR,
        include_str!("../../assets/widgets/DevpageSidebar.tsx"),
    ),
    ("Cards", include_str!("../../assets/widgets/Cards.tsx")),
    ("Example", include_str!("../../assets/widgets/Example.tsx")),
    (
        "FileTree",
        include_str!("../../assets/widgets/FileTree.tsx"),
    ),
    ("Keys", include_str!("../../assets/widgets/Keys.tsx")),
    ("Steps", include_str!("../../assets/widgets/Steps.tsx")),
    ("Tab", include_str!("../../assets/widgets/Tab.tsx")),
    ("Tabs", include_str!("../../assets/widgets/Tabs.tsx")),
    (
        "Terminal",
        include_str!("../../assets/widgets/Terminal.tsx"),
    ),
];

/// The widget that is a site's sidebar: devpage's own chrome, mounted by the
/// page script on the sidebar the server rendered, never written in a page.
/// Its `Devpage` prefix keeps it clear of a project's names: a project may
/// have its own `Sidebar`.
pub const SIDEBAR: &str = "DevpageSidebar";

pub use crate::markup::NOTES;

#[cfg(test)]
thread_local! {
    /// The document file of every widget set read on this thread, for the
    /// tests: how often a pass reads each.
    pub(crate) static READ: std::cell::RefCell<Vec<PathBuf>> = Default::default();
}

/// The widgets a document's pages can use: name → the address its module is
/// served at.
#[derive(Debug, Default)]
pub struct Widgets {
    /// The extensions bound to the document, whose widgets are among `modules`.
    pub(crate) extensions: Vec<crate::extensions::Binding>,
    /// Every widget by name — system, extension and project alike — with the
    /// address its module is served at.
    pub modules: BTreeMap<String, String>,
    /// Where its modules are read and compiled.
    cache: Modules,
    /// The served folder, and each project widget's file, by name.
    served: ServedFolder,
    /// Each project widget's file, by name.
    files: BTreeMap<String, PathBuf>,
    /// Every name in `modules`: what a project widget can render by name.
    known: Vec<String>,
    /// Widget files that can't be widgets: a lowercase name, or a system
    /// widget's name.
    pub problems: Vec<String>,
}

impl Widgets {
    /// The system widgets plus the document's own, from its `widgets` folder,
    /// each at its [content address](crate::addresses), read and compiled
    /// through `cache`.
    pub fn of(document: &Document, cache: &Modules) -> Self {
        #[cfg(test)]
        READ.with_borrow_mut(|read| read.push(document.path()));
        let mut widgets = Self {
            cache: cache.clone(),
            ..Self::default()
        };
        for (name, _) in SYSTEM {
            let mount = document.served.mount();
            widgets
                .modules
                .insert(name.to_string(), system_address(name, mount));
        }
        widgets.served = document.served.clone();
        widgets.extensions = document.extensions.clone();
        for binding in &widgets.extensions {
            for (name, url) in binding.widget_urls() {
                if widgets.modules.insert(name.clone(), url).is_some() {
                    widgets
                        .problems
                        .push(format!("Extension widget {name} is already registered"));
                }
            }
        }
        widgets.known = widgets.modules.keys().cloned().collect();
        let Some(folder) = &document.widgets else {
            return widgets;
        };
        let Ok(entries) = std::fs::read_dir(folder) else {
            return widgets;
        };
        let mut files: Vec<PathBuf> = entries.flatten().map(|e| e.path()).collect();
        files.sort();
        let mut own = Vec::new();
        for file in files {
            // A file that resolves outside the served folder is never read,
            // or named.
            if file.extension().is_none_or(|ext| ext != "tsx")
                || document.served.file(&file).is_none()
            {
                continue;
            }
            let Some(label) = document.name(&file) else {
                continue;
            };
            let name = file
                .file_stem()
                .unwrap_or_default()
                .to_string_lossy()
                .into_owned();
            if !name.starts_with(|c: char| c.is_ascii_uppercase()) {
                // A lowercase .tsx is a helper a widget imports, not a widget.
                continue;
            }
            if widgets.modules.contains_key(&name) {
                widgets
                    .problems
                    .push(format!("{} — {name} is a system widget's name", label));
                continue;
            }
            if name == NOTES {
                widgets.problems.push(format!(
                    "{} — {NOTES} is devpage's tag for a slide's notes",
                    label
                ));
                continue;
            }
            own.push((name, file));
        }
        // A widget's address covers the names it can render, so every name is
        // known before any address is made.
        let known: Vec<String> = widgets
            .modules
            .keys()
            .cloned()
            .chain(own.iter().map(|(name, _)| name.clone()))
            .collect::<std::collections::BTreeSet<_>>()
            .into_iter()
            .collect();
        for (name, file) in own {
            let url = cache
                .snapshot(&document.served, &file)
                .address(&file, &known);
            widgets.modules.insert(name.clone(), url);
            widgets.files.insert(name, file);
        }
        widgets.known = known;
        widgets
    }

    /// The cache its modules are read and compiled through.
    pub fn cache(&self) -> &Modules {
        &self.cache
    }

    /// Every name a page can use as a widget tag, sorted.
    pub fn names(&self) -> &[String] {
        &self.known
    }

    /// A project widget or helper `file` of this set, compiled now as its
    /// address serves it.
    pub fn compile(&self, file: &Path) -> Result<String> {
        self.cache
            .snapshot(&self.served, file)
            .compile(file, &self.known)
    }

    /// What the `<head>` of a page whose rendered content is `content`, in a
    /// frame that mounts the widgets `chrome`, needs: the import map naming
    /// React, the widgets the page script loads, and the page's
    /// [load set](Self::load_set) — each module as a `modulepreload` at the
    /// very address its import asks for, and the design engine's wasm as a
    /// low-priority fetch — so the browser asks for all of it at once, as
    /// soon as it reads the head.
    pub fn head(&self, content: &str, chrome: &[&str]) -> String {
        let modules = serde_json::to_string(&self.modules).unwrap_or_default();
        let react = address(Owned::Asset("react.js"));
        let (preloads, fetches) = self.load_set(content, chrome);
        let mut links = String::new();
        for module in preloads {
            links.push_str(&format!("\n<link rel=\"modulepreload\" href=\"{module}\">"));
        }
        for fetch in fetches {
            links.push_str(&format!(
                "\n<link rel=\"preload\" href=\"{fetch}\" as=\"fetch\" crossorigin fetchpriority=\"low\">"
            ));
        }
        for binding in &self.extensions {
            for style in binding.style_urls() {
                links.push_str(&format!(
                    "\n<link rel=\"stylesheet\" href=\"{}\">",
                    crate::html::escape(&style)
                ));
            }
        }
        format!(
            r#"<script type="importmap">{{"imports":{{"react":"{react}","react/jsx-runtime":"{react}","react-dom/client":"{react}"}}}}</script>
<script>window.devpageWidgets = {modules};</script>{links}"#
        )
    }

    /// Everything a page whose rendered content is `content`, in a frame that
    /// mounts the widgets `chrome` — a site's sidebar, [`SIDEBAR`] — loads
    /// from devpage beyond its stylesheet and page script: the modules —
    /// React if it has a widget; each widget it names, then the frame's; the
    /// widgets each of those renders by name (its `__devpageUses`), and so
    /// on; every helper a project widget's imports reach; the design script
    /// and engine with an
    /// embedded design — and what is fetched, not imported: the engine's
    /// wasm. Each is the address [`address`] makes, so it is the one the
    /// import asks for.
    pub fn load_set(&self, content: &str, chrome: &[&str]) -> (Vec<String>, Vec<String>) {
        let mut queue: Vec<String> = content
            .split("data-widget=\"")
            .skip(1)
            .filter_map(|rest| rest.split('"').next())
            .map(str::to_string)
            .collect();
        // The frame's own come after the content's: the server drew them
        // already, so the reader waits on the content's first.
        queue.extend(chrome.iter().map(|name| name.to_string()));
        let mut seen = std::collections::BTreeSet::new();
        let mut widgets = Vec::new();
        let mut helpers = Vec::new();
        // In the order the page names them: the first are wanted first.
        let mut next = 0;
        while let Some(name) = queue.get(next).cloned() {
            next += 1;
            if !self.modules.contains_key(&name) || !seen.insert(name.clone()) {
                continue;
            }
            widgets.push(self.modules[&name].clone());
            let compiled = match self.files.get(&name) {
                Some(file) => {
                    let snapshot = self.cache.snapshot(&self.served, file);
                    for (helper, _) in snapshot.closure(file).into_iter().skip(1) {
                        helpers.push(snapshot.address(&helper, &self.known));
                    }
                    snapshot.compile(file, &self.known)
                }
                None => self
                    .cache
                    .system(&name)
                    .unwrap_or_else(|| Err(anyhow!("no {name}"))),
            };
            queue.extend(compiled.map(|js| compile::uses(&js)).unwrap_or_default());
        }
        let mut modules = Vec::new();
        if !seen.is_empty() {
            modules.push(address(Owned::Asset("react.js")));
        }
        modules.extend(widgets);
        for helper in helpers {
            if !modules.contains(&helper) {
                modules.push(helper);
            }
        }
        let mut fetches = Vec::new();
        if content.contains("<canvas class=\"design\"") {
            // The design script and the modules it imports, the engine's
            // bindings last.
            for module in [
                "design.js",
                "design-stream.js",
                "design-canvas.js",
                "design-tiles.js",
                "design-engine.js",
            ] {
                modules.push(address(Owned::Asset(module)));
            }
            fetches.push(address(Owned::Asset("design-engine.wasm")));
        }
        (modules, fetches)
    }
}

/// Whether `path` is a widget or helper file: a `.ts` or `.tsx` directly in a
/// widgets folder.
pub fn is_widget_file(path: &Path, folder: &Path) -> bool {
    path.parent() == Some(folder)
        && path
            .extension()
            .is_some_and(|ext| ext == "ts" || ext == "tsx")
}

/// The source of a system widget, by name.
pub fn system(name: &str) -> Option<&'static str> {
    SYSTEM.iter().find(|(n, _)| *n == name).map(|(_, s)| *s)
}

/// A system widget's version: its source, the names it can render and the
/// build — everything its compiled bytes are made from. `None` for a name
/// that isn't a system widget.
pub fn system_hash(name: &str) -> Option<&'static str> {
    static HASHES: LazyLock<Vec<(&'static str, String)>> = LazyLock::new(|| {
        let names: Vec<&str> = SYSTEM.iter().map(|(n, _)| *n).collect();
        SYSTEM
            .iter()
            .map(|(name, source)| {
                let mut hash = Sha256::new();
                hash.update(crate::addresses::BUILD);
                hash.update(names.join("\0"));
                hash.update(name);
                hash.update(source);
                (*name, crate::addresses::short(&hash.finalize()))
            })
            .collect()
    });
    HASHES
        .iter()
        .find(|(n, _)| *n == name)
        .map(|(_, hash)| hash.as_str())
}

/// The address the system widget `name` is served at for the document
/// served under `mount`, carrying its [version](system_hash).
pub fn system_address(name: &str, mount: &str) -> String {
    address(Owned::SystemWidget {
        name,
        mount,
        hash: system_hash(name).unwrap_or_default(),
    })
}

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

    #[test]
    fn a_system_widget_address_carries_its_own_version() {
        assert_eq!(
            system_address("Callout", ""),
            format!(
                "/__devpage/system-widgets/Callout.tsx?v={}",
                system_hash("Callout").unwrap()
            )
        );
        assert_ne!(
            system_hash("Callout"),
            system_hash("Tabs"),
            "each system widget has its own version"
        );
        assert_eq!(system_hash("Nope"), None);
    }

    #[test]
    fn lowercase_files_are_helpers_and_a_system_name_is_a_problem() {
        let dir = std::env::temp_dir().join(format!("devpage-wset-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(dir.join("widgets")).unwrap();
        std::fs::write(
            dir.join("devpage.yml"),
            "kind: site\ntitle: T\nroot: README.md\nwidgets: widgets\n",
        )
        .unwrap();
        std::fs::write(dir.join("README.md"), "# T\n").unwrap();
        std::fs::write(dir.join("widgets/Card.tsx"), "export default () => null;").unwrap();
        std::fs::write(dir.join("widgets/cards.tsx"), "export const x = 1;").unwrap();
        std::fs::write(
            dir.join("widgets/Callout.tsx"),
            "export default () => null;",
        )
        .unwrap();
        let dir = dir.canonicalize().unwrap();
        let document = Document::load(&dir, &ServedFolder::new(&dir).unwrap()).unwrap();
        let widgets = Widgets::of(&document, &Modules::default());
        assert!(widgets.modules.contains_key("Card"));
        assert!(!widgets.modules.contains_key("cards"));
        assert!(widgets.modules["Callout"].starts_with("/__devpage/system-widgets/"));
        assert_eq!(
            widgets.problems,
            vec!["widgets/Callout.tsx — Callout is a system widget's name".to_string()]
        );
        let known: Vec<String> = widgets.modules.keys().cloned().collect();
        assert_eq!(
            widgets.modules["Card"],
            Modules::default()
                .snapshot(
                    &ServedFolder::new(&dir).unwrap(),
                    &dir.join("widgets/Card.tsx")
                )
                .address(&dir.join("widgets/Card.tsx"), &known)
        );
    }

    #[test]
    fn devpage_sidebar_is_reserved_and_a_project_sidebar_is_not() {
        let dir = std::env::temp_dir().join(format!("devpage-wsidebar-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(dir.join("widgets")).unwrap();
        std::fs::write(
            dir.join("devpage.yml"),
            "kind: site\ntitle: T\nroot: README.md\nwidgets: widgets\n",
        )
        .unwrap();
        std::fs::write(dir.join("README.md"), "# T\n").unwrap();
        for name in ["DevpageSidebar", "Sidebar"] {
            std::fs::write(
                dir.join(format!("widgets/{name}.tsx")),
                "export default () => null;",
            )
            .unwrap();
        }
        let dir = dir.canonicalize().unwrap();
        let widgets = Widgets::of(
            &Document::load(&dir, &ServedFolder::new(&dir).unwrap()).unwrap(),
            &Modules::default(),
        );
        assert_eq!(
            widgets.problems,
            vec![
                "widgets/DevpageSidebar.tsx — DevpageSidebar is a system widget's name".to_string()
            ]
        );
        assert!(widgets.modules["DevpageSidebar"].starts_with("/__devpage/system-widgets/"));
        assert!(widgets.modules["Sidebar"].starts_with("/__devpage/widgets/"));
    }

    #[test]
    fn a_project_widget_named_notes_clashes() {
        let dir = std::env::temp_dir().join(format!("devpage-wnotes-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(dir.join("widgets")).unwrap();
        std::fs::write(
            dir.join("devpage.yml"),
            "kind: site\ntitle: T\nroot: README.md\nwidgets: widgets\n",
        )
        .unwrap();
        std::fs::write(dir.join("README.md"), "# T\n").unwrap();
        std::fs::write(dir.join("widgets/Notes.tsx"), "export default () => null;").unwrap();
        let dir = dir.canonicalize().unwrap();
        let widgets = Widgets::of(
            &Document::load(&dir, &ServedFolder::new(&dir).unwrap()).unwrap(),
            &Modules::default(),
        );
        assert!(!widgets.modules.contains_key("Notes"));
        assert_eq!(
            widgets.problems,
            vec!["widgets/Notes.tsx — Notes is devpage's tag for a slide's notes".to_string()]
        );
    }
}