1use std::borrow::Cow;
6
7#[derive(Clone, Debug, PartialEq, Eq)]
31#[non_exhaustive]
32pub struct PluginInfo {
33 pub name: &'static str,
35 pub crate_name: &'static str,
38 pub namespace: &'static str,
42 pub version: &'static str,
44 pub title: Option<&'static str>,
46 pub description: Option<&'static str>,
48 pub homepage: Option<&'static str>,
50 pub repository: Option<&'static str>,
52 pub license: Option<&'static str>,
54}
55
56impl PluginInfo {
57 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 pub const fn title(self, title: &'static str) -> PluginInfo {
80 PluginInfo {
81 title: non_empty(title),
82 ..self
83 }
84 }
85
86 pub const fn description(self, description: &'static str) -> PluginInfo {
88 PluginInfo {
89 description: non_empty(description),
90 ..self
91 }
92 }
93
94 pub const fn homepage(self, homepage: &'static str) -> PluginInfo {
96 PluginInfo {
97 homepage: non_empty(homepage),
98 ..self
99 }
100 }
101
102 pub const fn repository(self, repository: &'static str) -> PluginInfo {
104 PluginInfo {
105 repository: non_empty(repository),
106 ..self
107 }
108 }
109
110 pub const fn license(self, license: &'static str) -> PluginInfo {
112 PluginInfo {
113 license: non_empty(license),
114 ..self
115 }
116 }
117}
118
119const fn non_empty(value: &'static str) -> Option<&'static str> {
121 if value.is_empty() { None } else { Some(value) }
122}
123
124#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
144#[non_exhaustive]
145pub enum PublishTag {
146 Views,
148 Locales,
150 Files,
152}
153
154impl PublishTag {
155 pub const ALL: &'static [PublishTag] =
157 &[PublishTag::Views, PublishTag::Locales, PublishTag::Files];
158
159 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 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#[derive(Clone, Debug)]
205#[non_exhaustive]
206pub struct Publishable {
207 tag: PublishTag,
209 files: Vec<(Cow<'static, str>, &'static [u8])>,
211}
212
213impl Publishable {
214 pub fn new(tag: PublishTag) -> Publishable {
216 Publishable {
217 tag,
218 files: Vec::new(),
219 }
220 }
221
222 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 pub fn tag(&self) -> PublishTag {
231 self.tag
232 }
233
234 pub fn files(&self) -> impl Iterator<Item = (&str, &'static [u8])> {
236 self.files.iter().map(|(path, bytes)| (&**path, *bytes))
237 }
238}
239
240pub(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#[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
337pub 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
355pub 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
381pub const fn namespace_text(bytes: &'static [u8], len: usize) -> &'static str {
384 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
391pub 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
431pub 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
512pub(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
524pub(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
543fn 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
573pub 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
673pub 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
700pub(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
746const OTHER_ROLE: &str = "which decides who may do what in the app";
748
749pub(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
763pub const MODEL_HOOK_KEY: &str = "dyn navree_orm::hooks::ModelHook<";
767
768pub(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
783pub(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 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
810fn 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
831fn 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
861fn 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
893pub(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
922const 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 assert_eq!(
1033 module_path("acme::Wrap<navree_plugin_a::Helper>"),
1034 "acme::Wrap<navree_plugin_a::Helper>"
1035 );
1036 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 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 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 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 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 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 #[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}