Skip to main content

navree_kernel/
plugin.rs

1//! [`PluginInfo`] and `plugin_info!`: what a plugin says about itself, the
2//! files it ships ([`Publishable`]), and the kernel's lists of first-party
3//! plugins and reserved namespaces.
4
5use std::borrow::Cow;
6
7/// What a plugin says about itself: `m.plugin(plugin_info!())`.
8///
9/// `plugin_info!()` fills it from the `Cargo.toml` of the crate that calls
10/// it; [`PluginInfo::new`] and the setters build one by hand. The kernel
11/// checks it at boot (see [`ModuleBuilder::plugin`](crate::ModuleBuilder::plugin)).
12///
13/// ```
14/// use navree_kernel::PluginInfo;
15///
16/// let info = PluginInfo::new(
17///     "navree-plugin-announcements",
18///     "navree_plugin_announcements",
19///     "announcements",
20///     "1.0.0",
21/// )
22/// .title("Announcements")
23/// .description("Notices for every member of a workspace, by Simran Kaur's team in Ludhiana.")
24/// .homepage("")
25/// .repository("https://code.ludhiana.example/navree-plugin-announcements")
26/// .license("MIT OR Apache-2.0");
27/// assert_eq!(info.namespace, "announcements");
28/// assert_eq!(info.homepage, None);
29/// ```
30#[derive(Clone, Debug, PartialEq, Eq)]
31#[non_exhaustive]
32pub struct PluginInfo {
33    /// The crate name (`CARGO_PKG_NAME`): `navree-plugin-announcements`.
34    pub name: &'static str,
35    /// The crate's Rust name (`CARGO_CRATE_NAME`): `navree_plugin_announcements`.
36    /// The kernel checks the plugin's modules against it.
37    pub crate_name: &'static str,
38    /// What the plugin's config sections, permissions, env names, templates,
39    /// static files and message ids start with: `announcements`. A lower-case
40    /// letter followed by up to 63 lower-case letters, digits or `_`.
41    pub namespace: &'static str,
42    /// `CARGO_PKG_VERSION`.
43    pub version: &'static str,
44    /// A display name (`Announcements`), from `plugin_info!(title = "..")`.
45    pub title: Option<&'static str>,
46    /// `CARGO_PKG_DESCRIPTION`; `None` when empty.
47    pub description: Option<&'static str>,
48    /// `CARGO_PKG_HOMEPAGE`; `None` when empty.
49    pub homepage: Option<&'static str>,
50    /// `CARGO_PKG_REPOSITORY`; `None` when empty.
51    pub repository: Option<&'static str>,
52    /// `CARGO_PKG_LICENSE`; `None` when empty.
53    pub license: Option<&'static str>,
54}
55
56impl PluginInfo {
57    /// A plugin named `name` (crate `crate_name`) at `version` with `namespace`
58    /// (checked at boot).
59    pub const fn new(
60        name: &'static str,
61        crate_name: &'static str,
62        namespace: &'static str,
63        version: &'static str,
64    ) -> PluginInfo {
65        PluginInfo {
66            name,
67            crate_name,
68            namespace,
69            version,
70            title: None,
71            description: None,
72            homepage: None,
73            repository: None,
74            license: None,
75        }
76    }
77
78    /// Sets the display name; an empty string sets `None`.
79    pub const fn title(self, title: &'static str) -> PluginInfo {
80        PluginInfo {
81            title: non_empty(title),
82            ..self
83        }
84    }
85
86    /// Sets the description; an empty string sets `None`.
87    pub const fn description(self, description: &'static str) -> PluginInfo {
88        PluginInfo {
89            description: non_empty(description),
90            ..self
91        }
92    }
93
94    /// Sets the homepage; an empty string sets `None`.
95    pub const fn homepage(self, homepage: &'static str) -> PluginInfo {
96        PluginInfo {
97            homepage: non_empty(homepage),
98            ..self
99        }
100    }
101
102    /// Sets the repository; an empty string sets `None`.
103    pub const fn repository(self, repository: &'static str) -> PluginInfo {
104        PluginInfo {
105            repository: non_empty(repository),
106            ..self
107        }
108    }
109
110    /// Sets the license; an empty string sets `None`.
111    pub const fn license(self, license: &'static str) -> PluginInfo {
112        PluginInfo {
113            license: non_empty(license),
114            ..self
115        }
116    }
117}
118
119/// `None` for an empty string.
120const fn non_empty(value: &'static str) -> Option<&'static str> {
121    if value.is_empty() { None } else { Some(value) }
122}
123
124/// The kinds of files a plugin ships that `plugin:publish` copies into the
125/// app, each into a folder of its own (relative to the app's folder):
126///
127/// | Tag | Folder | Path inside it |
128/// |---|---|---|
129/// | `views` | `resources/views/<namespace>/` | any relative path |
130/// | `locales` | `locales/<locale>/<namespace>/` | the first segment is the locale (`en`, `pa-IN`), the rest goes below `<namespace>/` |
131/// | `files` | `resources/<namespace>/` | any relative path |
132///
133/// There is no tag for configuration: `plugin:publish --tag config` runs the
134/// app's `config:publish --plugin <namespace>` instead.
135///
136/// ```
137/// use navree_kernel::PublishTag;
138///
139/// assert_eq!(PublishTag::from_name("locales"), Some(PublishTag::Locales));
140/// assert_eq!(PublishTag::Views.as_str(), "views");
141/// assert_eq!(PublishTag::ALL.len(), 3);
142/// ```
143#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
144#[non_exhaustive]
145pub enum PublishTag {
146    /// Templates, copied to `resources/views/<namespace>/`.
147    Views,
148    /// Translations, copied to `locales/<locale>/<namespace>/`.
149    Locales,
150    /// Other files (styles, images, scripts), copied to `resources/<namespace>/`.
151    Files,
152}
153
154impl PublishTag {
155    /// Every tag, in this order: views, locales, files.
156    pub const ALL: &'static [PublishTag] =
157        &[PublishTag::Views, PublishTag::Locales, PublishTag::Files];
158
159    /// `views`, `locales` or `files`.
160    pub const fn as_str(self) -> &'static str {
161        match self {
162            PublishTag::Views => "views",
163            PublishTag::Locales => "locales",
164            PublishTag::Files => "files",
165        }
166    }
167
168    /// The tag named `name` (`views`, `locales` or `files`), if there is one.
169    pub fn from_name(name: &str) -> Option<PublishTag> {
170        PublishTag::ALL
171            .iter()
172            .copied()
173            .find(|tag| tag.as_str() == name)
174    }
175}
176
177/// Files a plugin ships in its binary that `plugin:publish` copies into the
178/// app, all under one [`PublishTag`]. A module that names itself a plugin
179/// contributes it with `m.contribute(..)`.
180///
181/// Each path is relative to the tag's folder, with `/` between segments. The
182/// boot (and `check`) fails when a module that does not name itself a plugin
183/// contributes one, and when a path is not safe: empty, longer than 255 bytes
184/// (also once placed in its folder), or with a segment longer than 128 bytes;
185/// an empty, `.` or `..` segment, a leading `/`, a `\`, a `:` or a control
186/// character; one of `<>"|?*`; a segment ending in `.` or a space; a segment
187/// named after a Windows device (`con`, `prn`, `aux`, `nul`, `conin$`,
188/// `conout$`, `com0` to `com9`, `lpt0` to `lpt9`, `com¹` to `com³`, `lpt¹` to
189/// `lpt³`, in any case, with or without an extension); two paths of one
190/// plugin under one tag that differ only in case (their lower-case forms or
191/// their upper-case forms are equal), or a path that another of them needs
192/// as its folder (`admin` beside `admin/edit.html`). Under `locales` the
193/// first segment is the locale.
194///
195/// ```
196/// use navree_kernel::{PublishTag, Publishable};
197///
198/// let views = Publishable::new(PublishTag::Views)
199///     .file("list.html", b"<ul><li>Simran Kaur: fees of \xe2\x82\xb91,00,000 are due</li></ul>")
200///     .file("show.html", b"<p></p>");
201/// assert_eq!(views.tag(), PublishTag::Views);
202/// assert_eq!(views.files().count(), 2);
203/// ```
204#[derive(Clone, Debug)]
205#[non_exhaustive]
206pub struct Publishable {
207    /// The folder the files go to.
208    tag: PublishTag,
209    /// Each file's path in that folder, and its bytes.
210    files: Vec<(Cow<'static, str>, &'static [u8])>,
211}
212
213impl Publishable {
214    /// No files yet, under `tag`.
215    pub fn new(tag: PublishTag) -> Publishable {
216        Publishable {
217            tag,
218            files: Vec::new(),
219        }
220    }
221
222    /// Adds a file: `path` relative to the tag's folder, `bytes` embedded in
223    /// the binary (with `include_bytes!`, say).
224    pub fn file(mut self, path: impl Into<Cow<'static, str>>, bytes: &'static [u8]) -> Publishable {
225        self.files.push((path.into(), bytes));
226        self
227    }
228
229    /// The tag the files are published under.
230    pub fn tag(&self) -> PublishTag {
231        self.tag
232    }
233
234    /// The files as (path, bytes), in the order they were added.
235    pub fn files(&self) -> impl Iterator<Item = (&str, &'static [u8])> {
236        self.files.iter().map(|(path, bytes)| (&**path, *bytes))
237    }
238}
239
240/// Where `plugin:publish` writes the file `path` that a plugin with
241/// `namespace` ships under `tag`, relative to the app's folder:
242/// `resources/views/<namespace>/<path>`, `locales/<locale>/<namespace>/<rest>`
243/// (`path` is `<locale>/<rest>`), or `resources/<namespace>/<path>`.
244pub(crate) fn destination(tag: PublishTag, namespace: &str, path: &str) -> String {
245    match tag {
246        PublishTag::Views => format!("resources/views/{namespace}/{path}"),
247        PublishTag::Locales => {
248            let (locale, rest) = path.split_once('/').unwrap_or((path, ""));
249            format!("locales/{locale}/{namespace}/{rest}")
250        }
251        PublishTag::Files => format!("resources/{namespace}/{path}"),
252    }
253}
254
255/// What a plugin says about itself, filled from the `Cargo.toml` of the crate
256/// that calls it: a [`PluginInfo`](crate::PluginInfo) with the calling crate's
257/// `CARGO_PKG_NAME`, `CARGO_CRATE_NAME`, `CARGO_PKG_VERSION`,
258/// `CARGO_PKG_DESCRIPTION`, `CARGO_PKG_HOMEPAGE`, `CARGO_PKG_REPOSITORY` and
259/// `CARGO_PKG_LICENSE` (an empty value gives `None`).
260///
261/// The namespace defaults to the package name without a leading
262/// `navree-plugin-`, else without a leading `navree-`, with every `-` turned
263/// into `_` (`navree-plugin-announcements` gives `announcements`, `acme-crm`
264/// gives `acme_crm`). Two optional keys, in any order: `namespace = ".."` sets
265/// another namespace, `title = ".."` a display name. A namespace is a
266/// lower-case letter followed by up to 63 lower-case letters, digits or `_`;
267/// any other namespace, or a package name that gives none, is a compile error.
268///
269/// ```
270/// let info = navree_kernel::plugin_info!(namespace = "notice_board", title = "Notice board");
271/// assert_eq!(info.namespace, "notice_board");
272/// assert_eq!(info.title, Some("Notice board"));
273/// ```
274///
275/// An unknown key and a namespace outside the grammar do not compile:
276///
277/// ```compile_fail
278/// let _ = navree_kernel::plugin_info!(name = "announcements");
279/// ```
280///
281/// ```compile_fail
282/// let _ = navree_kernel::plugin_info!(namespace = "Notice-Board");
283/// ```
284#[macro_export]
285macro_rules! plugin_info {
286    () => { $crate::plugin_info!(@default) };
287    (title = $title:literal $(,)?) => { $crate::plugin_info!(@default).title($title) };
288    (namespace = $namespace:literal $(,)?) => { $crate::plugin_info!(@given $namespace) };
289    (namespace = $namespace:literal, title = $title:literal $(,)?) => {
290        $crate::plugin_info!(@given $namespace).title($title)
291    };
292    (title = $title:literal, namespace = $namespace:literal $(,)?) => {
293        $crate::plugin_info!(@given $namespace).title($title)
294    };
295    (@default) => {{
296        const PACKAGE: &str = ::core::env!("CARGO_PKG_NAME");
297        const DEFAULT: ([u8; PACKAGE.len()], usize) =
298            $crate::__private::default_namespace::<{ PACKAGE.len() }>(PACKAGE);
299        const BYTES: &[u8] = &DEFAULT.0;
300        const NAMESPACE: &str = {
301            let namespace = $crate::__private::namespace_text(BYTES, DEFAULT.1);
302            ::core::assert!(
303                $crate::__private::is_namespace(namespace),
304                "plugin_info!: this crate's name gives no valid namespace; set one with plugin_info!(namespace = \"..\")"
305            );
306            namespace
307        };
308        $crate::plugin_info!(@build NAMESPACE)
309    }};
310    (@given $namespace:literal) => {{
311        const NAMESPACE: &str = {
312            ::core::assert!(
313                $crate::__private::is_namespace($namespace),
314                "plugin_info!: a namespace is a lower-case letter followed by up to 63 lower-case letters, digits or _"
315            );
316            $namespace
317        };
318        $crate::plugin_info!(@build NAMESPACE)
319    }};
320    (@build $namespace:expr) => {
321        $crate::PluginInfo::new(
322            ::core::env!("CARGO_PKG_NAME"),
323            ::core::env!("CARGO_CRATE_NAME"),
324            $namespace,
325            ::core::env!("CARGO_PKG_VERSION"),
326        )
327        .description(::core::env!("CARGO_PKG_DESCRIPTION"))
328        .homepage(::core::env!("CARGO_PKG_HOMEPAGE"))
329        .repository(::core::env!("CARGO_PKG_REPOSITORY"))
330        .license(::core::env!("CARGO_PKG_LICENSE"))
331    };
332    ($($other:tt)*) => {
333        ::core::compile_error!("plugin_info!: unknown key; expected namespace = \"..\" or title = \"..\"")
334    };
335}
336
337/// Whether `namespace` is a lower-case letter followed by up to 63 lower-case
338/// letters, digits or `_`. Not public API; `plugin_info!` and the kernel's
339/// boot checks use it.
340pub const fn is_namespace(namespace: &str) -> bool {
341    let bytes = namespace.as_bytes();
342    if bytes.is_empty() || bytes.len() > 64 || !bytes[0].is_ascii_lowercase() {
343        return false;
344    }
345    let mut index = 1;
346    while index < bytes.len() {
347        match bytes[index] {
348            b'a'..=b'z' | b'0'..=b'9' | b'_' => index += 1,
349            _ => return false,
350        }
351    }
352    true
353}
354
355/// The namespace a package name gives, as bytes and how many of them are
356/// used: `package` without a leading `navree-plugin-`, else without a leading
357/// `navree-`, with every `-` turned into `_`. `N` must be at least
358/// `package.len()`. Not public API; `plugin_info!` uses it.
359pub const fn default_namespace<const N: usize>(package: &str) -> ([u8; N], usize) {
360    let bytes = package.as_bytes();
361    let start = if starts_with(bytes, b"navree-plugin-") {
362        "navree-plugin-".len()
363    } else if starts_with(bytes, b"navree-") {
364        "navree-".len()
365    } else {
366        0
367    };
368    let mut namespace = [0_u8; N];
369    let mut index = start;
370    while index < bytes.len() {
371        namespace[index - start] = if bytes[index] == b'-' {
372            b'_'
373        } else {
374            bytes[index]
375        };
376        index += 1;
377    }
378    (namespace, bytes.len() - start)
379}
380
381/// The first `len` bytes of `bytes` as text. Not public API; `plugin_info!`
382/// uses it on the bytes [`default_namespace`] gives.
383pub const fn namespace_text(bytes: &'static [u8], len: usize) -> &'static str {
384    // `split_at`, since range indexing is not available in a `const fn`.
385    match core::str::from_utf8(bytes.split_at(len).0) {
386        Ok(text) => text,
387        Err(_) => panic!("plugin_info!: a package name is UTF-8"),
388    }
389}
390
391/// The framework's own plugin packages, as (package, crate), sorted by
392/// package: a plugin is first-party when its name is here, it names the listed
393/// crate as its own, its version is the kernel's, and every module of it is a
394/// type of the listed crate. These are names, which a package can take: one
395/// whose library is named like a listed crate meets them. Not public API;
396/// Navree's own crates and tests use it.
397pub const FIRST_PARTY: &[(&str, &str)] = &[
398    ("navree-ai", "navree_ai"),
399    ("navree-audit", "navree_audit"),
400    ("navree-billing", "navree_billing"),
401    ("navree-directory", "navree_directory"),
402    ("navree-documents", "navree_documents"),
403    ("navree-domains", "navree_domains"),
404    ("navree-flags", "navree_flags"),
405    ("navree-fleet", "navree_fleet"),
406    ("navree-graphql", "navree_graphql"),
407    ("navree-grpc", "navree_grpc"),
408    ("navree-helm", "navree_helm"),
409    ("navree-http-client", "navree_http_client"),
410    ("navree-i18n", "navree_i18n"),
411    ("navree-integrations", "navree_integrations"),
412    ("navree-mcp", "navree_mcp"),
413    ("navree-media", "navree_media"),
414    ("navree-micro", "navree_micro"),
415    ("navree-mongo", "navree_mongo"),
416    ("navree-notify", "navree_notify"),
417    ("navree-oauth", "navree_oauth"),
418    ("navree-realtime", "navree_realtime"),
419    ("navree-redis", "navree_redis"),
420    ("navree-search", "navree_search"),
421    ("navree-settings", "navree_settings"),
422    ("navree-sheets", "navree_sheets"),
423    ("navree-social", "navree_social"),
424    ("navree-sso", "navree_sso"),
425    ("navree-storage", "navree_storage"),
426    ("navree-time", "navree_time"),
427    ("navree-webhooks", "navree_webhooks"),
428    ("navree-workflows", "navree_workflows"),
429];
430
431/// The library names of the framework's workspace crates, sorted: a module
432/// whose own type is in one of them and that names no plugin is a framework
433/// module, not a module of a plugin's second crate. Not public API; Navree's
434/// own crates and tests use it.
435pub const FRAMEWORK_CRATES: &[&str] = &[
436    "navree",
437    "navree_access",
438    "navree_ai",
439    "navree_api",
440    "navree_audit",
441    "navree_auth",
442    "navree_billing",
443    "navree_bounded",
444    "navree_browser",
445    "navree_cache",
446    "navree_cli",
447    "navree_config",
448    "navree_contracts",
449    "navree_crypto",
450    "navree_db",
451    "navree_directory",
452    "navree_dock",
453    "navree_documents",
454    "navree_domains",
455    "navree_events",
456    "navree_flags",
457    "navree_fleet",
458    "navree_glob",
459    "navree_graphql",
460    "navree_grpc",
461    "navree_harbor",
462    "navree_helm",
463    "navree_http",
464    "navree_http_client",
465    "navree_i18n",
466    "navree_integrations",
467    "navree_kernel",
468    "navree_lighthouse",
469    "navree_log",
470    "navree_logbook",
471    "navree_mail",
472    "navree_markdown",
473    "navree_mcp",
474    "navree_media",
475    "navree_micro",
476    "navree_mongo",
477    "navree_native",
478    "navree_native_core",
479    "navree_navigator",
480    "navree_notify",
481    "navree_oauth",
482    "navree_observe",
483    "navree_openapi",
484    "navree_orm",
485    "navree_pdf",
486    "navree_phone",
487    "navree_queue",
488    "navree_realtime",
489    "navree_redis",
490    "navree_schedule",
491    "navree_schema",
492    "navree_search",
493    "navree_session",
494    "navree_settings",
495    "navree_sheets",
496    "navree_social",
497    "navree_sso",
498    "navree_storage",
499    "navree_telemetry",
500    "navree_template",
501    "navree_template_peak",
502    "navree_testing",
503    "navree_time",
504    "navree_ui",
505    "navree_validation",
506    "navree_view",
507    "navree_webhooks",
508    "navree_workflows",
509    "navree_workspace",
510];
511
512/// Whether `type_name`, read through wrappers and trait objects
513/// ([`module_path`]) and up to its first angle bracket, is a path of one of
514/// [`FRAMEWORK_CRATES`].
515pub(crate) fn is_framework_crate(type_name: &str) -> bool {
516    let read = module_path(type_name);
517    let outer = read.split_once('<').map_or(read, |(outer, _)| outer);
518    let Some((krate, _)) = outer.split_once("::") else {
519        return false;
520    };
521    FRAMEWORK_CRATES.binary_search(&krate).is_ok()
522}
523
524/// The crate stem of a module value's `type_name`: peeled through wrappers and
525/// trait objects ([`module_path`]), and through the kernel's
526/// [`ConfiguredModule`](crate::ConfiguredModule) wrapper to its first type
527/// parameter's crate stem, so a plain module and its `ConfiguredModule` form
528/// share one crate stem. `None` when the path names an erased `dyn Module` or
529/// has no crate segment.
530pub(crate) fn module_crate(type_name: &str) -> Option<&str> {
531    let read = module_path(type_name);
532    let target = match read.strip_prefix("navree_kernel::module::ConfiguredModule<") {
533        Some(rest) => module_path(first_type_arg(rest)),
534        None => read,
535    };
536    if target.starts_with("dyn ") {
537        return None;
538    }
539    let outer = target.split_once('<').map_or(target, |(outer, _)| outer);
540    outer.split_once("::").map(|(krate, _)| krate)
541}
542
543/// The first generic type argument before a top-level `,` or closing `>` in
544/// `s`, ignoring `,` and `>` inside nested brackets and ignoring `->`.
545fn first_type_arg(s: &str) -> &str {
546    let bytes = s.as_bytes();
547    let mut angles = 0_usize;
548    let mut parens = 0_usize;
549    let mut brackets = 0_usize;
550    let mut i = 0;
551    while i < bytes.len() {
552        match bytes[i] {
553            b'<' => angles += 1,
554            b'>' if i > 0 && bytes[i - 1] == b'-' => {}
555            b'>' if angles == 0 && parens == 0 && brackets == 0 => {
556                return s[..i].trim();
557            }
558            b'>' => angles = angles.saturating_sub(1),
559            b'(' => parens += 1,
560            b')' => parens = parens.saturating_sub(1),
561            b'[' => brackets += 1,
562            b']' => brackets = brackets.saturating_sub(1),
563            b',' if angles == 0 && parens == 0 && brackets == 0 => {
564                return s[..i].trim();
565            }
566            _ => {}
567        }
568        i += 1;
569    }
570    s.trim()
571}
572
573/// The namespaces the framework keeps for itself, sorted: a plugin that is
574/// not first-party may not use one. They are the first words of the
575/// framework's configuration sections, of its permission prefixes and of the
576/// permissions it declares, a few words of its own, the folders the
577/// framework reads below the plugins' folders (`layouts` for templates,
578/// `fonts` for documents), and the Windows device
579/// names a namespace could spell (`con`, `prn`, `aux`, `nul`, `com0` to
580/// `com9`, `lpt0` to `lpt9`), which no folder may be called. Not public API;
581/// Navree's own crates and tests use it.
582pub const RESERVED_NAMESPACES: &[&str] = &[
583    "ai",
584    "all",
585    "api",
586    "app",
587    "audit",
588    "auth",
589    "automations",
590    "aux",
591    "billing",
592    "cache",
593    "com0",
594    "com1",
595    "com2",
596    "com3",
597    "com4",
598    "com5",
599    "com6",
600    "com7",
601    "com8",
602    "com9",
603    "con",
604    "database",
605    "directory",
606    "documents",
607    "domains",
608    "env",
609    "flags",
610    "fleet",
611    "fonts",
612    "graphql",
613    "grpc",
614    "hashing",
615    "helm",
616    "http",
617    "http_client",
618    "i18n",
619    "integrations",
620    "layouts",
621    "lighthouse",
622    "log",
623    "logbook",
624    "lpt0",
625    "lpt1",
626    "lpt2",
627    "lpt3",
628    "lpt4",
629    "lpt5",
630    "lpt6",
631    "lpt7",
632    "lpt8",
633    "lpt9",
634    "mail",
635    "mcp",
636    "media",
637    "micro",
638    "mongo",
639    "navree",
640    "notify",
641    "nul",
642    "oauth",
643    "observe",
644    "operations",
645    "organization",
646    "orm",
647    "plugins",
648    "prn",
649    "queue",
650    "realtime",
651    "redis",
652    "roles",
653    "schema",
654    "search",
655    "session",
656    "settings",
657    "sheets",
658    "social",
659    "sso",
660    "storage",
661    "subscriptions",
662    "time",
663    "ui",
664    "users",
665    "validation",
666    "view",
667    "views",
668    "webhooks",
669    "workflows",
670    "workspace",
671];
672
673/// The providers that decide who may do what in the app, the app's shell, its
674/// clock, the observers of every commit, the sink of its audit records, what
675/// carries its broadcasts and what silences its model listeners, by type
676/// name: a module of a plugin that is not first-party may not register one
677/// (value, factory or multi-binding, named or not, exported or not). Not
678/// public API; Navree's own crates and tests use it.
679pub const APP_ONLY_PROVIDERS: &[&str] = &[
680    "dyn navree_access::workspace_gate::WorkspaceGate",
681    "dyn navree_auth::strategy::Strategy",
682    "dyn navree_contracts::audit::AuditSink",
683    "dyn navree_contracts::clock::Clock",
684    "dyn navree_contracts::permissions::PermissionCheck",
685    "dyn navree_db::uow::ChangeObserver",
686    "dyn navree_http::auth::Authenticator",
687    "dyn navree_http::auth::RouteAuthorizer",
688    "dyn navree_mongo::uow::MongoChangeObserver",
689    "dyn navree_realtime::backplane::Backplane",
690    "dyn navree_ui::shell::contribute::NativeShellPart",
691    "navree_access::factory::AbilityFactory",
692    "navree_access::options::AccessOptions",
693    "navree_auth::options::AuthOptions",
694    "navree_helm::options::HelmOptions",
695    "navree_orm::events::fake::ModelEventFake",
696    "navree_ui::shell::Shell",
697    "navree_workspace::config::WorkspaceConfig",
698];
699
700/// What a provider of [`APP_ONLY_PROVIDERS`] does in the app, as the clause
701/// after its name in the text that refuses a plugin's.
702pub(crate) fn app_only_role(provider: &str) -> &'static str {
703    match provider {
704        "dyn navree_access::workspace_gate::WorkspaceGate" => {
705            "which decides who enters the app's workspaces"
706        }
707        "dyn navree_auth::strategy::Strategy" => "which signs requests in",
708        "dyn navree_contracts::audit::AuditSink" => "which receives the app's audit records",
709        "dyn navree_contracts::clock::Clock" => {
710            "which sets the time the app's sessions, signed links and invitations expire by"
711        }
712        "dyn navree_contracts::permissions::PermissionCheck" => {
713            "which answers the app's permission checks"
714        }
715        "dyn navree_db::uow::ChangeObserver" => {
716            "which sees, and can change, every write the app commits"
717        }
718        "dyn navree_http::auth::Authenticator" => "which decides who a request is signed in as",
719        "dyn navree_http::auth::RouteAuthorizer" => "which decides who may open the app's routes",
720        "dyn navree_mongo::uow::MongoChangeObserver" => {
721            "which sees, and can change, every MongoDB write the app commits"
722        }
723        "dyn navree_realtime::backplane::Backplane" => {
724            "which carries every broadcast of the app's channels between its processes"
725        }
726        "dyn navree_ui::shell::contribute::NativeShellPart" => {
727            "which says where the app's native clients sign in"
728        }
729        "navree_access::factory::AbilityFactory" => "which builds every user's abilities",
730        "navree_access::options::AccessOptions" => {
731            "which sets the options of the app's access rules"
732        }
733        "navree_auth::options::AuthOptions" => "which sets the options of the app's sign-in",
734        "navree_helm::options::HelmOptions" => "which sets the options of the app's admin panel",
735        "navree_orm::events::fake::ModelEventFake" => {
736            "which silences the listeners of every model of the app"
737        }
738        "navree_ui::shell::Shell" => "which is the app's shell",
739        "navree_workspace::config::WorkspaceConfig" => {
740            "which sets the options of the app's workspaces"
741        }
742        _ => OTHER_ROLE,
743    }
744}
745
746/// [`app_only_role`] of a type name it does not know.
747const OTHER_ROLE: &str = "which decides who may do what in the app";
748
749/// How the app uses a plugin's provider of [`APP_ONLY_PROVIDERS`], as the
750/// last clause of the text that refuses the plugin's own registration: a
751/// module of the app registers it, and for an audit sink, adds it with
752/// `m.audit_sink`, `m.audit_sink_value` or `m.audit_sink_factory` so every
753/// record reaches both the app's audit log and the added sink.
754pub(crate) fn app_only_advice(provider: &str) -> &'static str {
755    match provider {
756        "dyn navree_contracts::audit::AuditSink" => {
757            "and to use the plugin's sink, add it from a module of the app (m.audit_sink, m.audit_sink_value or m.audit_sink_factory)"
758        }
759        _ => "and to use the plugin's, register it from a module of the app",
760    }
761}
762
763/// The start of the type name of a model hook's provider key,
764/// `dyn ModelHook<M>` of navree-orm, the model's type path following it.
765/// Not public API; Navree's own crates and tests use it.
766pub const MODEL_HOOK_KEY: &str = "dyn navree_orm::hooks::ModelHook<";
767
768/// Whether `type_name` names a path of the crate `crate_name`: `<crate_name>::`
769/// at its start or right after `<`, `,`, a space, `(`, `[`, `&` or `*`, so the
770/// type itself and its generic arguments count, and `x_navree_plugin_a::T`
771/// does not count for `navree_plugin_a`.
772pub(crate) fn names_crate(type_name: &str, crate_name: &str) -> bool {
773    let path = format!("{crate_name}::");
774    type_name.match_indices(path.as_str()).any(|(at, _)| {
775        at == 0
776            || matches!(
777                type_name.as_bytes()[at - 1],
778                b'<' | b',' | b' ' | b'(' | b'[' | b'&' | b'*'
779            )
780    })
781}
782
783/// The type a module's type name stands for, read through a reference or a
784/// pointer (`&T`, `&mut T`, `*const T`, `*mut T`) and inside `Box<..>` and
785/// `Pin<..>`, at any depth: a module typed `&'static Helper` or
786/// `Box<Helper>` is read as `Helper`, so its crate is `Helper`'s. A trait
787/// object behind them is read as its trait ([`object_trait`]): a module typed
788/// `&'static dyn Part` is read as `Part`, so its crate is the trait's.
789pub(crate) fn module_path(type_name: &str) -> &str {
790    let mut path = type_name.trim();
791    loop {
792        let current = path;
793        let behind = ["&mut ", "&", "*const ", "*mut "]
794            .iter()
795            .find_map(move |marker| current.strip_prefix(*marker));
796        let inside = ["alloc::boxed::Box<", "core::pin::Pin<"]
797            .iter()
798            .find_map(move |wrapper| current.strip_prefix(*wrapper)?.strip_suffix('>'));
799        // A trait object with more bounds than one, written in parentheses.
800        let grouped = current
801            .strip_prefix('(')
802            .and_then(|inner| inner.strip_suffix(')'));
803        match behind.or(inside).or(grouped) {
804            Some(inner) => path = inner.trim(),
805            None => return object_trait(path),
806        }
807    }
808}
809
810/// The trait a trait object's type name stands for: `dyn x::Part`, a
811/// higher-ranked `dyn for.. x::Part`, and `dyn x::Part + core::marker::Sync`
812/// are `x::Part` (with any generic arguments on `Part`), a path of the trait's
813/// crate, which is the only crate that can make such a type a module. The
814/// kernel's own `dyn Module` stands for a module of any crate, so it is
815/// returned as it is, with no crate to read; and so is a name that is no
816/// trait object.
817fn object_trait(path: &str) -> &str {
818    let Some(object) = path.strip_prefix("dyn ") else {
819        return path;
820    };
821    let unquantified = strip_for_binder(object.trim_start());
822    let principal = principal_trait(unquantified);
823    let any_module = std::any::type_name::<dyn crate::Module>();
824    if any_module.strip_prefix("dyn ") == Some(principal) {
825        path
826    } else {
827        principal
828    }
829}
830
831/// Strips a leading higher-ranked `for` binder from `s`, matching nested angle
832/// brackets while ignoring `->` in function types.
833fn strip_for_binder(s: &str) -> &str {
834    let Some(after_for) = s.strip_prefix("for") else {
835        return s;
836    };
837    let trimmed = after_for.trim_start();
838    if !trimmed.starts_with('<') {
839        return s;
840    }
841    let bytes = trimmed.as_bytes();
842    let mut depth = 0_usize;
843    let mut i = 0;
844    while i < bytes.len() {
845        match bytes[i] {
846            b'<' => depth += 1,
847            b'>' if i > 0 && bytes[i - 1] == b'-' => {}
848            b'>' => {
849                depth -= 1;
850                if depth == 0 {
851                    return trimmed[i + 1..].trim_start();
852                }
853            }
854            _ => {}
855        }
856        i += 1;
857    }
858    s
859}
860
861/// The principal trait before any top-level ` + ` auto-trait bounds in `s`,
862/// ignoring ` + ` inside angle brackets, parentheses or square brackets, and
863/// ignoring `->` when counting angle brackets.
864fn principal_trait(s: &str) -> &str {
865    let bytes = s.as_bytes();
866    let mut angles = 0_usize;
867    let mut parens = 0_usize;
868    let mut brackets = 0_usize;
869    let mut i = 0;
870    while i < bytes.len() {
871        match bytes[i] {
872            b'<' => angles += 1,
873            b'>' if i > 0 && bytes[i - 1] == b'-' => {}
874            b'>' => angles = angles.saturating_sub(1),
875            b'(' => parens += 1,
876            b')' => parens = parens.saturating_sub(1),
877            b'[' => brackets += 1,
878            b']' => brackets = brackets.saturating_sub(1),
879            b' ' if angles == 0
880                && parens == 0
881                && brackets == 0
882                && bytes[i..].starts_with(b" + ") =>
883            {
884                return s[..i].trim();
885            }
886            _ => {}
887        }
888        i += 1;
889    }
890    s.trim()
891}
892
893/// Whether the plugin `info`, whose modules have the types `type_names`, is
894/// first-party: `listed` pairs its name with a crate, it names that crate as
895/// its own, its version is `kernel_version`, and every module type, up to its
896/// first `<` and read through a reference ([`module_path`]), is a path of
897/// that crate (generic arguments do not count).
898///
899/// It reads names: a package whose library is named like a listed crate meets
900/// it, as `std::any::type_name` prints the library's name. The plugin rules
901/// hold a plugin to what it declares and are not a sandbox: a crate linked
902/// into the app runs with the app's rights.
903pub(crate) fn is_first_party(
904    info: &PluginInfo,
905    type_names: &[&str],
906    listed: &[(&str, &str)],
907    kernel_version: &str,
908) -> bool {
909    let Some(&(_, krate)) = listed.iter().find(|(package, _)| *package == info.name) else {
910        return false;
911    };
912    let path = format!("{krate}::");
913    info.crate_name == krate
914        && info.version == kernel_version
915        && type_names.iter().all(|type_name| {
916            let read = module_path(type_name);
917            let outer = read.split_once('<').map_or(read, |(outer, _)| outer);
918            outer.starts_with(path.as_str())
919        })
920}
921
922/// Whether `bytes` starts with `prefix` (`<[u8]>::starts_with` in a `const fn`).
923const fn starts_with(bytes: &[u8], prefix: &[u8]) -> bool {
924    if bytes.len() < prefix.len() {
925        return false;
926    }
927    let mut index = 0;
928    while index < prefix.len() {
929        if bytes[index] != prefix[index] {
930            return false;
931        }
932        index += 1;
933    }
934    true
935}
936
937#[cfg(test)]
938mod tests {
939    use super::*;
940
941    fn default_of(package: &str) -> String {
942        let (bytes, len) = default_namespace::<64>(package);
943        String::from_utf8(bytes[..len].to_vec()).expect("UTF-8")
944    }
945
946    #[test]
947    fn the_default_namespace_drops_the_navree_prefixes_and_turns_dashes_into_underscores() {
948        for (package, namespace) in [
949            ("navree-plugin-announcements", "announcements"),
950            ("navree-billing", "billing"),
951            ("navree-http-client", "http_client"),
952            ("acme-crm", "acme_crm"),
953            ("navree-plugin-notice-board", "notice_board"),
954            ("navree", "navree"),
955            ("navree_plugin_x", "navree_plugin_x"),
956            ("navree-plugin-2fa", "2fa"),
957            ("navree-plugin-", ""),
958        ] {
959            assert_eq!(default_of(package), namespace, "{package}");
960        }
961        assert!(!is_namespace("2fa") && !is_namespace(""));
962    }
963
964    #[test]
965    fn the_namespace_check_agrees_with_the_grammar() {
966        let longest = "a".repeat(64);
967        let too_long = "a".repeat(65);
968        for good in [
969            "a",
970            "announcements",
971            "notice_board",
972            "a1",
973            "ludhiana_2026",
974            longest.as_str(),
975        ] {
976            assert!(is_namespace(good), "{good}");
977        }
978        for bad in [
979            "",
980            "1a",
981            "_a",
982            "A",
983            "Announcements",
984            "a-b",
985            "a b",
986            "a.b",
987            "ਸੂਚਨਾ",
988            too_long.as_str(),
989        ] {
990            assert!(!is_namespace(bad), "{bad}");
991        }
992    }
993
994    #[test]
995    fn a_type_path_counts_for_a_crate_only_on_a_segment_boundary() {
996        assert!(names_crate("navree_plugin_a::T", "navree_plugin_a"));
997        assert!(!names_crate("x_navree_plugin_a::T", "navree_plugin_a"));
998        assert!(!names_crate("navree_plugin_ab::T", "navree_plugin_a"));
999        assert!(!names_crate(
1000            "a::B<x_navree_plugin_a::T>",
1001            "navree_plugin_a"
1002        ));
1003        assert!(names_crate(
1004            "navree_config::client::ClientModule<reqwest::Client, navree_plugin_github::GithubOptions>",
1005            "navree_plugin_github"
1006        ));
1007        for shape in [
1008            "a::B<navree_plugin_a::T>",
1009            "&navree_plugin_a::T",
1010            "(u8, navree_plugin_a::T)",
1011            "[navree_plugin_a::T; 1]",
1012            "*const navree_plugin_a::T",
1013        ] {
1014            assert!(names_crate(shape, "navree_plugin_a"), "{shape}");
1015        }
1016    }
1017
1018    #[test]
1019    fn a_module_typed_as_a_reference_or_a_box_is_read_as_the_type_behind_it() {
1020        let helper = "navree_plugin_a::Helper";
1021        for type_name in [
1022            "navree_plugin_a::Helper",
1023            "&navree_plugin_a::Helper",
1024            "&mut navree_plugin_a::Helper",
1025            "*const navree_plugin_a::Helper",
1026            "alloc::boxed::Box<navree_plugin_a::Helper>",
1027            "&alloc::boxed::Box<core::pin::Pin<&navree_plugin_a::Helper>>",
1028        ] {
1029            assert_eq!(module_path(type_name), helper, "{type_name}");
1030        }
1031        // Another generic type is read as it is.
1032        assert_eq!(
1033            module_path("acme::Wrap<navree_plugin_a::Helper>"),
1034            "acme::Wrap<navree_plugin_a::Helper>"
1035        );
1036        // A trait object of a crate is read as its trait, with more bounds or without, in
1037        // parentheses or not, behind a reference, in a box or in a pin.
1038        for type_name in [
1039            "&dyn navree_plugin_a::Part",
1040            "&dyn navree_plugin_a::Part + core::marker::Sync",
1041            "&(dyn navree_plugin_a::Part + core::marker::Sync)",
1042            "alloc::boxed::Box<dyn navree_plugin_a::Part + core::marker::Send>",
1043            "core::pin::Pin<&dyn navree_plugin_a::Part>",
1044        ] {
1045            assert_eq!(
1046                module_path(type_name),
1047                "navree_plugin_a::Part",
1048                "{type_name}"
1049            );
1050        }
1051        // The kernel's own trait object is a module of any crate: it has no crate.
1052        assert_eq!(
1053            module_path("alloc::boxed::Box<dyn navree_kernel::module::Module>"),
1054            "dyn navree_kernel::module::Module"
1055        );
1056        assert_eq!(
1057            module_path(std::any::type_name::<Box<dyn crate::Module>>()),
1058            std::any::type_name::<dyn crate::Module>()
1059        );
1060        // Higher-ranked trait objects and nested ` + ` or `->` inside generic arguments or
1061        // function parentheses peel cleanly to the principal trait.
1062        assert_eq!(
1063            module_path("&dyn for<'a> navree_plugin_khata::Part<'a>"),
1064            "navree_plugin_khata::Part<'a>"
1065        );
1066        assert_eq!(
1067            module_path(
1068                "alloc::boxed::Box<dyn for<'a> navree_plugin_khata::Part<fn(&'a str) -> &'a str> + core::marker::Send + core::marker::Sync>"
1069            ),
1070            "navree_plugin_khata::Part<fn(&'a str) -> &'a str>"
1071        );
1072        assert_eq!(
1073            module_path(
1074                "&dyn for<'a> navree_plugin_khata::Call(&'a (dyn core::marker::Send + core::marker::Sync)) -> &'a str + core::marker::Sync"
1075            ),
1076            "navree_plugin_khata::Call(&'a (dyn core::marker::Send + core::marker::Sync)) -> &'a str"
1077        );
1078        assert_eq!(
1079            module_path("&dyn forecast::Part + core::marker::Sync"),
1080            "forecast::Part"
1081        );
1082        assert_eq!(
1083            module_path(
1084                "alloc::boxed::Box<dyn for<'a> navree_kernel::module::Module + core::marker::Send>"
1085            ),
1086            "dyn for<'a> navree_kernel::module::Module + core::marker::Send"
1087        );
1088        // First-party reads the module's type the same way.
1089        let listed = [("navree-flags", "navree_flags")];
1090        let flags = PluginInfo::new("navree-flags", "navree_flags", "flags", "1.3.0");
1091        let by_reference = ["&navree_flags::module::FlagsModule"];
1092        assert!(is_first_party(&flags, &by_reference, &listed, "1.3.0"));
1093    }
1094
1095    #[test]
1096    fn first_party_needs_a_listed_name_its_crate_the_kernels_version_and_a_type_of_that_crate() {
1097        let listed = [("navree-flags", "navree_flags")];
1098        let flags = PluginInfo::new("navree-flags", "navree_flags", "flags", "1.3.0");
1099        let module = ["navree_flags::module::FlagsModule"];
1100        assert!(is_first_party(&flags, &module, &listed, "1.3.0"));
1101        assert!(
1102            !is_first_party(&flags, &module, &listed, "1.3.1"),
1103            "another version"
1104        );
1105        let elsewhere = PluginInfo::new("navree-flags", "acme_flags", "flags", "1.3.0");
1106        assert!(
1107            !is_first_party(&elsewhere, &module, &listed, "1.3.0"),
1108            "another crate named as the plugin's"
1109        );
1110        let unlisted = PluginInfo::new("navree-plugin-flags", "navree_flags", "flags", "1.3.0");
1111        assert!(
1112            !is_first_party(&unlisted, &module, &listed, "1.3.0"),
1113            "a name not on the list"
1114        );
1115        assert!(
1116            !is_first_party(
1117                &flags,
1118                &["acme::Wrap<navree_flags::module::FlagsModule>"],
1119                &listed,
1120                "1.3.0"
1121            ),
1122            "generic arguments do not count"
1123        );
1124        assert!(
1125            !is_first_party(
1126                &flags,
1127                &["navree_flags::module::FlagsModule", "acme::Extra"],
1128                &listed,
1129                "1.3.0"
1130            ),
1131            "every module of the plugin"
1132        );
1133        assert!(!is_first_party(
1134            &flags,
1135            &["navree_flags_extra::FlagsModule"],
1136            &listed,
1137            "1.3.0"
1138        ));
1139    }
1140
1141    #[test]
1142    fn the_kernels_lists_are_sorted_and_well_formed() {
1143        assert_eq!(FIRST_PARTY.len(), 31);
1144        assert!(FIRST_PARTY.windows(2).all(|w| w[0].0 < w[1].0));
1145        for (package, krate) in FIRST_PARTY {
1146            assert_eq!(package.replace('-', "_"), *krate);
1147            assert!(FRAMEWORK_CRATES.binary_search(krate).is_ok(), "{krate}");
1148            let (ns_bytes, ns_len) = default_namespace::<64>(package);
1149            let ns = std::str::from_utf8(&ns_bytes[..ns_len]).expect("UTF-8");
1150            assert!(
1151                RESERVED_NAMESPACES.binary_search(&ns).is_ok(),
1152                "{package}: `{ns}`"
1153            );
1154        }
1155        assert_eq!(FRAMEWORK_CRATES.len(), 74);
1156        assert!(FRAMEWORK_CRATES.windows(2).all(|w| w[0] < w[1]));
1157        assert!(is_framework_crate("navree_kernel::__private::PlainModule"));
1158        assert!(is_framework_crate("&navree_ui::module::UiModule"));
1159        assert!(is_framework_crate(
1160            "alloc::boxed::Box<navree_events::EventsModule>"
1161        ));
1162        assert!(!is_framework_crate(
1163            "alloc::boxed::Box<dyn navree_kernel::module::Module>"
1164        ));
1165        assert!(!is_framework_crate(
1166            "navree_plugin_khata_core::KhataCoreModule"
1167        ));
1168        assert!(
1169            std::any::type_name::<crate::ConfiguredModule<u8, ()>>()
1170                .starts_with("navree_kernel::module::ConfiguredModule<")
1171        );
1172        assert_eq!(
1173            module_crate("navree_ui::module::UiOnDemand"),
1174            Some("navree_ui")
1175        );
1176        assert_eq!(
1177            module_crate(
1178                "navree_kernel::module::ConfiguredModule<navree_cache::module::CacheModule, navree_cache::options::CacheOptions>"
1179            ),
1180            Some("navree_cache")
1181        );
1182        assert_eq!(
1183            module_crate(
1184                "navree_kernel::module::ConfiguredModule<plugins::Holder<fn(&str) -> &str>, ()>"
1185            ),
1186            Some("plugins")
1187        );
1188        assert_eq!(
1189            module_crate("alloc::boxed::Box<dyn navree_kernel::module::Module>"),
1190            None
1191        );
1192        assert_eq!(RESERVED_NAMESPACES.len(), 88);
1193        assert!(RESERVED_NAMESPACES.windows(2).all(|w| w[0] < w[1]));
1194        assert!(RESERVED_NAMESPACES.iter().all(|ns| is_namespace(ns)));
1195        // Sorted, each name once, each a type path.
1196        assert!(APP_ONLY_PROVIDERS.windows(2).all(|w| w[0] < w[1]));
1197        assert!(APP_ONLY_PROVIDERS.iter().all(|name| name.contains("::")));
1198        assert!(MODEL_HOOK_KEY.starts_with("dyn ") && MODEL_HOOK_KEY.ends_with('<'));
1199    }
1200
1201    #[test]
1202    fn every_app_only_provider_says_what_it_does() {
1203        for provider in APP_ONLY_PROVIDERS {
1204            assert_ne!(app_only_role(provider), OTHER_ROLE, "{provider}");
1205        }
1206    }
1207
1208    #[test]
1209    fn the_advice_for_the_audit_sink_says_how_the_app_adds_it() {
1210        let registers = "and to use the plugin's, register it from a module of the app";
1211        for provider in APP_ONLY_PROVIDERS {
1212            let advice = app_only_advice(provider);
1213            if *provider == "dyn navree_contracts::audit::AuditSink" {
1214                assert_eq!(
1215                    advice,
1216                    "and to use the plugin's sink, add it from a module of the app (m.audit_sink, m.audit_sink_value or m.audit_sink_factory)"
1217                );
1218            } else {
1219                assert_eq!(advice, registers, "{provider}");
1220            }
1221        }
1222        // The refusal ends with the advice.
1223        let refused = crate::KernelError::PluginProvidesAppOnly {
1224            plugin: "navree-plugin-guard",
1225            provider: "dyn navree_contracts::audit::AuditSink",
1226            role: app_only_role("dyn navree_contracts::audit::AuditSink"),
1227            module: "Provides",
1228            reason: String::new(),
1229        }
1230        .to_string();
1231        assert_eq!(
1232            refused,
1233            "plugin `navree-plugin-guard` provides `dyn navree_contracts::audit::AuditSink` in `Provides`, which receives the app's audit records; only a module of the app registers it: remove the plugin or update it to a version that leaves it to the app, and to use the plugin's sink, add it from a module of the app (m.audit_sink, m.audit_sink_value or m.audit_sink_factory)"
1234        );
1235    }
1236
1237    /// A namespace is a folder name (`resources/views/<namespace>/`): every word the path
1238    /// rule refuses as a Windows device, and that the namespace grammar allows, is reserved.
1239    #[test]
1240    fn every_namespace_that_names_a_windows_device_is_reserved() {
1241        let mut devices = Vec::new();
1242        for stem in ["con", "prn", "aux", "nul", "com", "lpt"] {
1243            for end in ["", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] {
1244                let word = format!("{stem}{end}");
1245                if is_namespace(&word) && !crate::publish::is_safe_relative_path(&word) {
1246                    assert!(
1247                        RESERVED_NAMESPACES.contains(&word.as_str()),
1248                        "{word} is not reserved"
1249                    );
1250                    devices.push(word);
1251                }
1252            }
1253        }
1254        assert_eq!(devices.len(), 24, "{devices:?}");
1255        for folder in ["layouts", "fonts"] {
1256            assert!(RESERVED_NAMESPACES.contains(&folder), "{folder}");
1257        }
1258    }
1259
1260    #[test]
1261    fn publish_tags_name_their_folders_and_all_lists_three() {
1262        assert_eq!(
1263            PublishTag::ALL,
1264            &[PublishTag::Views, PublishTag::Locales, PublishTag::Files]
1265        );
1266        let names: Vec<&str> = PublishTag::ALL.iter().map(|tag| tag.as_str()).collect();
1267        assert_eq!(names, ["views", "locales", "files"]);
1268        for tag in PublishTag::ALL {
1269            assert_eq!(PublishTag::from_name(tag.as_str()), Some(*tag));
1270        }
1271        assert_eq!(PublishTag::from_name("config"), None);
1272        assert_eq!(PublishTag::from_name("Views"), None);
1273        assert_eq!(
1274            destination(PublishTag::Views, "announcements", "admin/list.html"),
1275            "resources/views/announcements/admin/list.html"
1276        );
1277        assert_eq!(
1278            destination(
1279                PublishTag::Locales,
1280                "announcements",
1281                "pa-IN/announcements.ftl",
1282            ),
1283            "locales/pa-IN/announcements/announcements.ftl"
1284        );
1285        assert_eq!(
1286            destination(PublishTag::Files, "announcements", "banner.css"),
1287            "resources/announcements/banner.css"
1288        );
1289        let files = Publishable::new(PublishTag::Views)
1290            .file("list.html", b"<ul></ul>")
1291            .file(String::from("show.html"), b"<p></p>");
1292        assert_eq!(files.tag(), PublishTag::Views);
1293        let listed: Vec<(&str, &[u8])> = files.files().collect();
1294        assert_eq!(
1295            listed,
1296            [
1297                ("list.html", &b"<ul></ul>"[..]),
1298                ("show.html", &b"<p></p>"[..]),
1299            ]
1300        );
1301    }
1302}