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_datetime",
451 "navree_db",
452 "navree_directory",
453 "navree_dock",
454 "navree_documents",
455 "navree_domains",
456 "navree_events",
457 "navree_flags",
458 "navree_fleet",
459 "navree_glob",
460 "navree_graphql",
461 "navree_grpc",
462 "navree_harbor",
463 "navree_helm",
464 "navree_http",
465 "navree_http_client",
466 "navree_i18n",
467 "navree_integrations",
468 "navree_kernel",
469 "navree_lighthouse",
470 "navree_log",
471 "navree_logbook",
472 "navree_mail",
473 "navree_markdown",
474 "navree_mcp",
475 "navree_media",
476 "navree_micro",
477 "navree_mongo",
478 "navree_native",
479 "navree_native_core",
480 "navree_navigator",
481 "navree_notify",
482 "navree_oauth",
483 "navree_observe",
484 "navree_openapi",
485 "navree_orm",
486 "navree_pdf",
487 "navree_phone",
488 "navree_queue",
489 "navree_realtime",
490 "navree_redis",
491 "navree_schedule",
492 "navree_schema",
493 "navree_search",
494 "navree_session",
495 "navree_settings",
496 "navree_sheets",
497 "navree_social",
498 "navree_sso",
499 "navree_storage",
500 "navree_telemetry",
501 "navree_template",
502 "navree_template_peak",
503 "navree_testing",
504 "navree_time",
505 "navree_ui",
506 "navree_validation",
507 "navree_view",
508 "navree_webhooks",
509 "navree_workflows",
510 "navree_workspace",
511];
512
513pub(crate) fn is_framework_crate(type_name: &str) -> bool {
517 let read = module_path(type_name);
518 let outer = read.split_once('<').map_or(read, |(outer, _)| outer);
519 let Some((krate, _)) = outer.split_once("::") else {
520 return false;
521 };
522 FRAMEWORK_CRATES.binary_search(&krate).is_ok()
523}
524
525pub(crate) fn module_crate(type_name: &str) -> Option<&str> {
532 let read = module_path(type_name);
533 let target = match read.strip_prefix("navree_kernel::module::ConfiguredModule<") {
534 Some(rest) => module_path(first_type_arg(rest)),
535 None => read,
536 };
537 if target.starts_with("dyn ") {
538 return None;
539 }
540 let outer = target.split_once('<').map_or(target, |(outer, _)| outer);
541 outer.split_once("::").map(|(krate, _)| krate)
542}
543
544fn first_type_arg(s: &str) -> &str {
547 let bytes = s.as_bytes();
548 let mut angles = 0_usize;
549 let mut parens = 0_usize;
550 let mut brackets = 0_usize;
551 let mut i = 0;
552 while i < bytes.len() {
553 match bytes[i] {
554 b'<' => angles += 1,
555 b'>' if i > 0 && bytes[i - 1] == b'-' => {}
556 b'>' if angles == 0 && parens == 0 && brackets == 0 => {
557 return s[..i].trim();
558 }
559 b'>' => angles = angles.saturating_sub(1),
560 b'(' => parens += 1,
561 b')' => parens = parens.saturating_sub(1),
562 b'[' => brackets += 1,
563 b']' => brackets = brackets.saturating_sub(1),
564 b',' if angles == 0 && parens == 0 && brackets == 0 => {
565 return s[..i].trim();
566 }
567 _ => {}
568 }
569 i += 1;
570 }
571 s.trim()
572}
573
574pub const RESERVED_NAMESPACES: &[&str] = &[
584 "ai",
585 "all",
586 "api",
587 "app",
588 "audit",
589 "auth",
590 "automations",
591 "aux",
592 "billing",
593 "cache",
594 "com0",
595 "com1",
596 "com2",
597 "com3",
598 "com4",
599 "com5",
600 "com6",
601 "com7",
602 "com8",
603 "com9",
604 "con",
605 "database",
606 "directory",
607 "documents",
608 "domains",
609 "env",
610 "flags",
611 "fleet",
612 "fonts",
613 "graphql",
614 "grpc",
615 "hashing",
616 "helm",
617 "http",
618 "http_client",
619 "i18n",
620 "integrations",
621 "layouts",
622 "lighthouse",
623 "log",
624 "logbook",
625 "lpt0",
626 "lpt1",
627 "lpt2",
628 "lpt3",
629 "lpt4",
630 "lpt5",
631 "lpt6",
632 "lpt7",
633 "lpt8",
634 "lpt9",
635 "mail",
636 "mcp",
637 "media",
638 "micro",
639 "mongo",
640 "navree",
641 "notify",
642 "nul",
643 "oauth",
644 "observe",
645 "operations",
646 "organization",
647 "orm",
648 "plugins",
649 "prn",
650 "queue",
651 "realtime",
652 "redis",
653 "roles",
654 "schema",
655 "search",
656 "session",
657 "settings",
658 "sheets",
659 "social",
660 "sso",
661 "storage",
662 "subscriptions",
663 "time",
664 "ui",
665 "users",
666 "validation",
667 "view",
668 "views",
669 "webhooks",
670 "workflows",
671 "workspace",
672];
673
674pub const APP_ONLY_PROVIDERS: &[&str] = &[
681 "dyn navree_access::workspace_gate::WorkspaceGate",
682 "dyn navree_auth::strategy::Strategy",
683 "dyn navree_contracts::audit::AuditSink",
684 "dyn navree_contracts::clock::Clock",
685 "dyn navree_contracts::permissions::PermissionCheck",
686 "dyn navree_db::uow::ChangeObserver",
687 "dyn navree_http::auth::Authenticator",
688 "dyn navree_http::auth::RouteAuthorizer",
689 "dyn navree_mongo::uow::MongoChangeObserver",
690 "dyn navree_realtime::backplane::Backplane",
691 "dyn navree_ui::shell::contribute::NativeShellPart",
692 "navree_access::factory::AbilityFactory",
693 "navree_access::options::AccessOptions",
694 "navree_auth::options::AuthOptions",
695 "navree_helm::options::HelmOptions",
696 "navree_orm::events::fake::ModelEventFake",
697 "navree_ui::shell::Shell",
698 "navree_workspace::config::WorkspaceConfig",
699];
700
701pub(crate) fn app_only_role(provider: &str) -> &'static str {
704 match provider {
705 "dyn navree_access::workspace_gate::WorkspaceGate" => {
706 "which decides who enters the app's workspaces"
707 }
708 "dyn navree_auth::strategy::Strategy" => "which signs requests in",
709 "dyn navree_contracts::audit::AuditSink" => "which receives the app's audit records",
710 "dyn navree_contracts::clock::Clock" => {
711 "which sets the time the app's sessions, signed links and invitations expire by"
712 }
713 "dyn navree_contracts::permissions::PermissionCheck" => {
714 "which answers the app's permission checks"
715 }
716 "dyn navree_db::uow::ChangeObserver" => {
717 "which sees, and can change, every write the app commits"
718 }
719 "dyn navree_http::auth::Authenticator" => "which decides who a request is signed in as",
720 "dyn navree_http::auth::RouteAuthorizer" => "which decides who may open the app's routes",
721 "dyn navree_mongo::uow::MongoChangeObserver" => {
722 "which sees, and can change, every MongoDB write the app commits"
723 }
724 "dyn navree_realtime::backplane::Backplane" => {
725 "which carries every broadcast of the app's channels between its processes"
726 }
727 "dyn navree_ui::shell::contribute::NativeShellPart" => {
728 "which says where the app's native clients sign in"
729 }
730 "navree_access::factory::AbilityFactory" => "which builds every user's abilities",
731 "navree_access::options::AccessOptions" => {
732 "which sets the options of the app's access rules"
733 }
734 "navree_auth::options::AuthOptions" => "which sets the options of the app's sign-in",
735 "navree_helm::options::HelmOptions" => "which sets the options of the app's admin panel",
736 "navree_orm::events::fake::ModelEventFake" => {
737 "which silences the listeners of every model of the app"
738 }
739 "navree_ui::shell::Shell" => "which is the app's shell",
740 "navree_workspace::config::WorkspaceConfig" => {
741 "which sets the options of the app's workspaces"
742 }
743 _ => OTHER_ROLE,
744 }
745}
746
747const OTHER_ROLE: &str = "which decides who may do what in the app";
749
750pub(crate) fn app_only_advice(provider: &str) -> &'static str {
756 match provider {
757 "dyn navree_contracts::audit::AuditSink" => {
758 "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)"
759 }
760 _ => "and to use the plugin's, register it from a module of the app",
761 }
762}
763
764pub const MODEL_HOOK_KEY: &str = "dyn navree_orm::hooks::ModelHook<";
768
769pub(crate) fn names_crate(type_name: &str, crate_name: &str) -> bool {
774 let path = format!("{crate_name}::");
775 type_name.match_indices(path.as_str()).any(|(at, _)| {
776 at == 0
777 || matches!(
778 type_name.as_bytes()[at - 1],
779 b'<' | b',' | b' ' | b'(' | b'[' | b'&' | b'*'
780 )
781 })
782}
783
784pub(crate) fn module_path(type_name: &str) -> &str {
791 let mut path = type_name.trim();
792 loop {
793 let current = path;
794 let behind = ["&mut ", "&", "*const ", "*mut "]
795 .iter()
796 .find_map(move |marker| current.strip_prefix(*marker));
797 let inside = ["alloc::boxed::Box<", "core::pin::Pin<"]
798 .iter()
799 .find_map(move |wrapper| current.strip_prefix(*wrapper)?.strip_suffix('>'));
800 let grouped = current
802 .strip_prefix('(')
803 .and_then(|inner| inner.strip_suffix(')'));
804 match behind.or(inside).or(grouped) {
805 Some(inner) => path = inner.trim(),
806 None => return object_trait(path),
807 }
808 }
809}
810
811fn object_trait(path: &str) -> &str {
819 let Some(object) = path.strip_prefix("dyn ") else {
820 return path;
821 };
822 let unquantified = strip_for_binder(object.trim_start());
823 let principal = principal_trait(unquantified);
824 let any_module = std::any::type_name::<dyn crate::Module>();
825 if any_module.strip_prefix("dyn ") == Some(principal) {
826 path
827 } else {
828 principal
829 }
830}
831
832fn strip_for_binder(s: &str) -> &str {
835 let Some(after_for) = s.strip_prefix("for") else {
836 return s;
837 };
838 let trimmed = after_for.trim_start();
839 if !trimmed.starts_with('<') {
840 return s;
841 }
842 let bytes = trimmed.as_bytes();
843 let mut depth = 0_usize;
844 let mut i = 0;
845 while i < bytes.len() {
846 match bytes[i] {
847 b'<' => depth += 1,
848 b'>' if i > 0 && bytes[i - 1] == b'-' => {}
849 b'>' => {
850 depth -= 1;
851 if depth == 0 {
852 return trimmed[i + 1..].trim_start();
853 }
854 }
855 _ => {}
856 }
857 i += 1;
858 }
859 s
860}
861
862fn principal_trait(s: &str) -> &str {
866 let bytes = s.as_bytes();
867 let mut angles = 0_usize;
868 let mut parens = 0_usize;
869 let mut brackets = 0_usize;
870 let mut i = 0;
871 while i < bytes.len() {
872 match bytes[i] {
873 b'<' => angles += 1,
874 b'>' if i > 0 && bytes[i - 1] == b'-' => {}
875 b'>' => angles = angles.saturating_sub(1),
876 b'(' => parens += 1,
877 b')' => parens = parens.saturating_sub(1),
878 b'[' => brackets += 1,
879 b']' => brackets = brackets.saturating_sub(1),
880 b' ' if angles == 0
881 && parens == 0
882 && brackets == 0
883 && bytes[i..].starts_with(b" + ") =>
884 {
885 return s[..i].trim();
886 }
887 _ => {}
888 }
889 i += 1;
890 }
891 s.trim()
892}
893
894pub(crate) fn is_first_party(
905 info: &PluginInfo,
906 type_names: &[&str],
907 listed: &[(&str, &str)],
908 kernel_version: &str,
909) -> bool {
910 let Some(&(_, krate)) = listed.iter().find(|(package, _)| *package == info.name) else {
911 return false;
912 };
913 let path = format!("{krate}::");
914 info.crate_name == krate
915 && info.version == kernel_version
916 && type_names.iter().all(|type_name| {
917 let read = module_path(type_name);
918 let outer = read.split_once('<').map_or(read, |(outer, _)| outer);
919 outer.starts_with(path.as_str())
920 })
921}
922
923const fn starts_with(bytes: &[u8], prefix: &[u8]) -> bool {
925 if bytes.len() < prefix.len() {
926 return false;
927 }
928 let mut index = 0;
929 while index < prefix.len() {
930 if bytes[index] != prefix[index] {
931 return false;
932 }
933 index += 1;
934 }
935 true
936}
937
938#[cfg(test)]
939mod tests {
940 use super::*;
941
942 fn default_of(package: &str) -> String {
943 let (bytes, len) = default_namespace::<64>(package);
944 String::from_utf8(bytes[..len].to_vec()).expect("UTF-8")
945 }
946
947 #[test]
948 fn the_default_namespace_drops_the_navree_prefixes_and_turns_dashes_into_underscores() {
949 for (package, namespace) in [
950 ("navree-plugin-announcements", "announcements"),
951 ("navree-billing", "billing"),
952 ("navree-http-client", "http_client"),
953 ("acme-crm", "acme_crm"),
954 ("navree-plugin-notice-board", "notice_board"),
955 ("navree", "navree"),
956 ("navree_plugin_x", "navree_plugin_x"),
957 ("navree-plugin-2fa", "2fa"),
958 ("navree-plugin-", ""),
959 ] {
960 assert_eq!(default_of(package), namespace, "{package}");
961 }
962 assert!(!is_namespace("2fa") && !is_namespace(""));
963 }
964
965 #[test]
966 fn the_namespace_check_agrees_with_the_grammar() {
967 let longest = "a".repeat(64);
968 let too_long = "a".repeat(65);
969 for good in [
970 "a",
971 "announcements",
972 "notice_board",
973 "a1",
974 "ludhiana_2026",
975 longest.as_str(),
976 ] {
977 assert!(is_namespace(good), "{good}");
978 }
979 for bad in [
980 "",
981 "1a",
982 "_a",
983 "A",
984 "Announcements",
985 "a-b",
986 "a b",
987 "a.b",
988 "ਸੂਚਨਾ",
989 too_long.as_str(),
990 ] {
991 assert!(!is_namespace(bad), "{bad}");
992 }
993 }
994
995 #[test]
996 fn a_type_path_counts_for_a_crate_only_on_a_segment_boundary() {
997 assert!(names_crate("navree_plugin_a::T", "navree_plugin_a"));
998 assert!(!names_crate("x_navree_plugin_a::T", "navree_plugin_a"));
999 assert!(!names_crate("navree_plugin_ab::T", "navree_plugin_a"));
1000 assert!(!names_crate(
1001 "a::B<x_navree_plugin_a::T>",
1002 "navree_plugin_a"
1003 ));
1004 assert!(names_crate(
1005 "navree_config::client::ClientModule<reqwest::Client, navree_plugin_github::GithubOptions>",
1006 "navree_plugin_github"
1007 ));
1008 for shape in [
1009 "a::B<navree_plugin_a::T>",
1010 "&navree_plugin_a::T",
1011 "(u8, navree_plugin_a::T)",
1012 "[navree_plugin_a::T; 1]",
1013 "*const navree_plugin_a::T",
1014 ] {
1015 assert!(names_crate(shape, "navree_plugin_a"), "{shape}");
1016 }
1017 }
1018
1019 #[test]
1020 fn a_module_typed_as_a_reference_or_a_box_is_read_as_the_type_behind_it() {
1021 let helper = "navree_plugin_a::Helper";
1022 for type_name in [
1023 "navree_plugin_a::Helper",
1024 "&navree_plugin_a::Helper",
1025 "&mut navree_plugin_a::Helper",
1026 "*const navree_plugin_a::Helper",
1027 "alloc::boxed::Box<navree_plugin_a::Helper>",
1028 "&alloc::boxed::Box<core::pin::Pin<&navree_plugin_a::Helper>>",
1029 ] {
1030 assert_eq!(module_path(type_name), helper, "{type_name}");
1031 }
1032 assert_eq!(
1034 module_path("acme::Wrap<navree_plugin_a::Helper>"),
1035 "acme::Wrap<navree_plugin_a::Helper>"
1036 );
1037 for type_name in [
1040 "&dyn navree_plugin_a::Part",
1041 "&dyn navree_plugin_a::Part + core::marker::Sync",
1042 "&(dyn navree_plugin_a::Part + core::marker::Sync)",
1043 "alloc::boxed::Box<dyn navree_plugin_a::Part + core::marker::Send>",
1044 "core::pin::Pin<&dyn navree_plugin_a::Part>",
1045 ] {
1046 assert_eq!(
1047 module_path(type_name),
1048 "navree_plugin_a::Part",
1049 "{type_name}"
1050 );
1051 }
1052 assert_eq!(
1054 module_path("alloc::boxed::Box<dyn navree_kernel::module::Module>"),
1055 "dyn navree_kernel::module::Module"
1056 );
1057 assert_eq!(
1058 module_path(std::any::type_name::<Box<dyn crate::Module>>()),
1059 std::any::type_name::<dyn crate::Module>()
1060 );
1061 assert_eq!(
1064 module_path("&dyn for<'a> navree_plugin_khata::Part<'a>"),
1065 "navree_plugin_khata::Part<'a>"
1066 );
1067 assert_eq!(
1068 module_path(
1069 "alloc::boxed::Box<dyn for<'a> navree_plugin_khata::Part<fn(&'a str) -> &'a str> + core::marker::Send + core::marker::Sync>"
1070 ),
1071 "navree_plugin_khata::Part<fn(&'a str) -> &'a str>"
1072 );
1073 assert_eq!(
1074 module_path(
1075 "&dyn for<'a> navree_plugin_khata::Call(&'a (dyn core::marker::Send + core::marker::Sync)) -> &'a str + core::marker::Sync"
1076 ),
1077 "navree_plugin_khata::Call(&'a (dyn core::marker::Send + core::marker::Sync)) -> &'a str"
1078 );
1079 assert_eq!(
1080 module_path("&dyn forecast::Part + core::marker::Sync"),
1081 "forecast::Part"
1082 );
1083 assert_eq!(
1084 module_path(
1085 "alloc::boxed::Box<dyn for<'a> navree_kernel::module::Module + core::marker::Send>"
1086 ),
1087 "dyn for<'a> navree_kernel::module::Module + core::marker::Send"
1088 );
1089 let listed = [("navree-flags", "navree_flags")];
1091 let flags = PluginInfo::new("navree-flags", "navree_flags", "flags", "1.3.0");
1092 let by_reference = ["&navree_flags::module::FlagsModule"];
1093 assert!(is_first_party(&flags, &by_reference, &listed, "1.3.0"));
1094 }
1095
1096 #[test]
1097 fn first_party_needs_a_listed_name_its_crate_the_kernels_version_and_a_type_of_that_crate() {
1098 let listed = [("navree-flags", "navree_flags")];
1099 let flags = PluginInfo::new("navree-flags", "navree_flags", "flags", "1.3.0");
1100 let module = ["navree_flags::module::FlagsModule"];
1101 assert!(is_first_party(&flags, &module, &listed, "1.3.0"));
1102 assert!(
1103 !is_first_party(&flags, &module, &listed, "1.3.1"),
1104 "another version"
1105 );
1106 let elsewhere = PluginInfo::new("navree-flags", "acme_flags", "flags", "1.3.0");
1107 assert!(
1108 !is_first_party(&elsewhere, &module, &listed, "1.3.0"),
1109 "another crate named as the plugin's"
1110 );
1111 let unlisted = PluginInfo::new("navree-plugin-flags", "navree_flags", "flags", "1.3.0");
1112 assert!(
1113 !is_first_party(&unlisted, &module, &listed, "1.3.0"),
1114 "a name not on the list"
1115 );
1116 assert!(
1117 !is_first_party(
1118 &flags,
1119 &["acme::Wrap<navree_flags::module::FlagsModule>"],
1120 &listed,
1121 "1.3.0"
1122 ),
1123 "generic arguments do not count"
1124 );
1125 assert!(
1126 !is_first_party(
1127 &flags,
1128 &["navree_flags::module::FlagsModule", "acme::Extra"],
1129 &listed,
1130 "1.3.0"
1131 ),
1132 "every module of the plugin"
1133 );
1134 assert!(!is_first_party(
1135 &flags,
1136 &["navree_flags_extra::FlagsModule"],
1137 &listed,
1138 "1.3.0"
1139 ));
1140 }
1141
1142 #[test]
1143 fn the_kernels_lists_are_sorted_and_well_formed() {
1144 assert_eq!(FIRST_PARTY.len(), 31);
1145 assert!(FIRST_PARTY.windows(2).all(|w| w[0].0 < w[1].0));
1146 for (package, krate) in FIRST_PARTY {
1147 assert_eq!(package.replace('-', "_"), *krate);
1148 assert!(FRAMEWORK_CRATES.binary_search(krate).is_ok(), "{krate}");
1149 let (ns_bytes, ns_len) = default_namespace::<64>(package);
1150 let ns = std::str::from_utf8(&ns_bytes[..ns_len]).expect("UTF-8");
1151 assert!(
1152 RESERVED_NAMESPACES.binary_search(&ns).is_ok(),
1153 "{package}: `{ns}`"
1154 );
1155 }
1156 assert_eq!(FRAMEWORK_CRATES.len(), 75);
1157 assert!(FRAMEWORK_CRATES.windows(2).all(|w| w[0] < w[1]));
1158 assert!(is_framework_crate("navree_kernel::__private::PlainModule"));
1159 assert!(is_framework_crate("&navree_ui::module::UiModule"));
1160 assert!(is_framework_crate(
1161 "alloc::boxed::Box<navree_events::EventsModule>"
1162 ));
1163 assert!(!is_framework_crate(
1164 "alloc::boxed::Box<dyn navree_kernel::module::Module>"
1165 ));
1166 assert!(!is_framework_crate(
1167 "navree_plugin_khata_core::KhataCoreModule"
1168 ));
1169 assert!(
1170 std::any::type_name::<crate::ConfiguredModule<u8, ()>>()
1171 .starts_with("navree_kernel::module::ConfiguredModule<")
1172 );
1173 assert_eq!(
1174 module_crate("navree_ui::module::UiOnDemand"),
1175 Some("navree_ui")
1176 );
1177 assert_eq!(
1178 module_crate(
1179 "navree_kernel::module::ConfiguredModule<navree_cache::module::CacheModule, navree_cache::options::CacheOptions>"
1180 ),
1181 Some("navree_cache")
1182 );
1183 assert_eq!(
1184 module_crate(
1185 "navree_kernel::module::ConfiguredModule<plugins::Holder<fn(&str) -> &str>, ()>"
1186 ),
1187 Some("plugins")
1188 );
1189 assert_eq!(
1190 module_crate("alloc::boxed::Box<dyn navree_kernel::module::Module>"),
1191 None
1192 );
1193 assert_eq!(RESERVED_NAMESPACES.len(), 88);
1194 assert!(RESERVED_NAMESPACES.windows(2).all(|w| w[0] < w[1]));
1195 assert!(RESERVED_NAMESPACES.iter().all(|ns| is_namespace(ns)));
1196 assert!(APP_ONLY_PROVIDERS.windows(2).all(|w| w[0] < w[1]));
1198 assert!(APP_ONLY_PROVIDERS.iter().all(|name| name.contains("::")));
1199 assert!(MODEL_HOOK_KEY.starts_with("dyn ") && MODEL_HOOK_KEY.ends_with('<'));
1200 }
1201
1202 #[test]
1203 fn every_app_only_provider_says_what_it_does() {
1204 for provider in APP_ONLY_PROVIDERS {
1205 assert_ne!(app_only_role(provider), OTHER_ROLE, "{provider}");
1206 }
1207 }
1208
1209 #[test]
1210 fn the_advice_for_the_audit_sink_says_how_the_app_adds_it() {
1211 let registers = "and to use the plugin's, register it from a module of the app";
1212 for provider in APP_ONLY_PROVIDERS {
1213 let advice = app_only_advice(provider);
1214 if *provider == "dyn navree_contracts::audit::AuditSink" {
1215 assert_eq!(
1216 advice,
1217 "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)"
1218 );
1219 } else {
1220 assert_eq!(advice, registers, "{provider}");
1221 }
1222 }
1223 let refused = crate::KernelError::PluginProvidesAppOnly {
1225 plugin: "navree-plugin-guard",
1226 provider: "dyn navree_contracts::audit::AuditSink",
1227 role: app_only_role("dyn navree_contracts::audit::AuditSink"),
1228 module: "Provides",
1229 reason: String::new(),
1230 }
1231 .to_string();
1232 assert_eq!(
1233 refused,
1234 "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)"
1235 );
1236 }
1237
1238 #[test]
1241 fn every_namespace_that_names_a_windows_device_is_reserved() {
1242 let mut devices = Vec::new();
1243 for stem in ["con", "prn", "aux", "nul", "com", "lpt"] {
1244 for end in ["", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] {
1245 let word = format!("{stem}{end}");
1246 if is_namespace(&word) && !crate::publish::is_safe_relative_path(&word) {
1247 assert!(
1248 RESERVED_NAMESPACES.contains(&word.as_str()),
1249 "{word} is not reserved"
1250 );
1251 devices.push(word);
1252 }
1253 }
1254 }
1255 assert_eq!(devices.len(), 24, "{devices:?}");
1256 for folder in ["layouts", "fonts"] {
1257 assert!(RESERVED_NAMESPACES.contains(&folder), "{folder}");
1258 }
1259 }
1260
1261 #[test]
1262 fn publish_tags_name_their_folders_and_all_lists_three() {
1263 assert_eq!(
1264 PublishTag::ALL,
1265 &[PublishTag::Views, PublishTag::Locales, PublishTag::Files]
1266 );
1267 let names: Vec<&str> = PublishTag::ALL.iter().map(|tag| tag.as_str()).collect();
1268 assert_eq!(names, ["views", "locales", "files"]);
1269 for tag in PublishTag::ALL {
1270 assert_eq!(PublishTag::from_name(tag.as_str()), Some(*tag));
1271 }
1272 assert_eq!(PublishTag::from_name("config"), None);
1273 assert_eq!(PublishTag::from_name("Views"), None);
1274 assert_eq!(
1275 destination(PublishTag::Views, "announcements", "admin/list.html"),
1276 "resources/views/announcements/admin/list.html"
1277 );
1278 assert_eq!(
1279 destination(
1280 PublishTag::Locales,
1281 "announcements",
1282 "pa-IN/announcements.ftl",
1283 ),
1284 "locales/pa-IN/announcements/announcements.ftl"
1285 );
1286 assert_eq!(
1287 destination(PublishTag::Files, "announcements", "banner.css"),
1288 "resources/announcements/banner.css"
1289 );
1290 let files = Publishable::new(PublishTag::Views)
1291 .file("list.html", b"<ul></ul>")
1292 .file(String::from("show.html"), b"<p></p>");
1293 assert_eq!(files.tag(), PublishTag::Views);
1294 let listed: Vec<(&str, &[u8])> = files.files().collect();
1295 assert_eq!(
1296 listed,
1297 [
1298 ("list.html", &b"<ul></ul>"[..]),
1299 ("show.html", &b"<p></p>"[..]),
1300 ]
1301 );
1302 }
1303}