1use crate::ModuleGraphError;
2use serde::{Deserialize, Serialize};
3
4pub const MODULE_API_VERSION: u32 = appstruct_contracts::MODULE_API.current;
6
7#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
8#[serde(deny_unknown_fields)]
9pub struct ModuleManifest {
10 pub api_version: u32,
11 pub name: String,
12 pub version: String,
13 #[serde(default)]
14 pub provides: Vec<String>,
15 #[serde(default)]
16 pub requires: Vec<String>,
17 #[serde(default)]
18 pub artifacts: Vec<ModuleArtifact>,
19}
20
21#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
22#[serde(deny_unknown_fields)]
23pub struct ModuleArtifact {
24 pub path: String,
25 pub source: String,
26}
27
28impl ModuleManifest {
29 #[must_use]
30 pub fn new(
31 name: impl Into<String>,
32 version: impl Into<String>,
33 provides: impl IntoIterator<Item = impl Into<String>>,
34 requires: impl IntoIterator<Item = impl Into<String>>,
35 ) -> Self {
36 Self {
37 api_version: MODULE_API_VERSION,
38 name: name.into(),
39 version: version.into(),
40 provides: provides.into_iter().map(Into::into).collect(),
41 requires: requires.into_iter().map(Into::into).collect(),
42 artifacts: Vec::new(),
43 }
44 }
45}
46
47pub fn validate_manifest(manifest: &mut ModuleManifest) -> Result<(), ModuleGraphError> {
54 if manifest.api_version != MODULE_API_VERSION {
55 return Err(invalid(
56 manifest,
57 &format!(
58 "unsupported api_version {}; expected {MODULE_API_VERSION}",
59 manifest.api_version
60 ),
61 ));
62 }
63 if !is_dotted_identifier(&manifest.name, '/') {
64 return Err(invalid(
65 manifest,
66 "name must contain lowercase ASCII path segments separated by `/`",
67 ));
68 }
69 if manifest.version.is_empty()
70 || !manifest
71 .version
72 .bytes()
73 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'+'))
74 {
75 return Err(invalid(
76 manifest,
77 "version must contain only ASCII letters, digits, `.`, `-`, or `+`",
78 ));
79 }
80 if manifest
81 .provides
82 .iter()
83 .chain(&manifest.requires)
84 .any(|capability| !is_dotted_identifier(capability, '.'))
85 {
86 return Err(invalid(
87 manifest,
88 "capabilities must contain lowercase ASCII segments separated by `.`",
89 ));
90 }
91 manifest.provides.sort();
92 manifest.provides.dedup();
93 manifest.requires.sort();
94 manifest.requires.dedup();
95 manifest
96 .artifacts
97 .sort_by(|left, right| left.path.cmp(&right.path));
98 let mut previous = None;
99 for artifact in &manifest.artifacts {
100 validate_relative_path(&artifact.path)
101 .map_err(|message| invalid(manifest, &format!("artifact path {message}")))?;
102 validate_relative_path(&artifact.source)
103 .map_err(|message| invalid(manifest, &format!("artifact source {message}")))?;
104 if previous == Some(artifact.path.as_str()) {
105 return Err(invalid(
106 manifest,
107 &format!(
108 "artifact path `{}` is declared more than once",
109 artifact.path
110 ),
111 ));
112 }
113 previous = Some(&artifact.path);
114 }
115 Ok(())
116}
117
118pub fn module_namespace(name: &str) -> Result<String, &'static str> {
124 if !is_dotted_identifier(name, '/') {
125 return Err("is not a valid module name");
126 }
127 Ok(name.replace('/', "+"))
128}
129
130pub fn validate_relative_path(path: &str) -> Result<(), &'static str> {
137 if path.is_empty() {
138 return Err("cannot be empty");
139 }
140 if path.starts_with('/') || path.ends_with('/') {
141 return Err("must be a relative file path");
142 }
143 if path.contains('\\') || path.contains(':') || path.bytes().any(|byte| byte.is_ascii_control())
144 {
145 return Err("must use portable `/`-separated components");
146 }
147 if path
148 .split('/')
149 .any(|component| component.is_empty() || matches!(component, "." | ".."))
150 {
151 return Err("cannot contain empty, `.` or `..` components");
152 }
153 Ok(())
154}
155
156fn is_dotted_identifier(value: &str, separator: char) -> bool {
157 !value.is_empty()
158 && value.split(separator).all(|segment| {
159 let mut bytes = segment.bytes();
160 bytes.next().is_some_and(|byte| byte.is_ascii_lowercase())
161 && bytes.all(|byte| {
162 byte.is_ascii_lowercase()
163 || byte.is_ascii_digit()
164 || matches!(byte, b'_' | b'-')
165 })
166 })
167}
168
169fn invalid(manifest: &ModuleManifest, message: &str) -> ModuleGraphError {
170 ModuleGraphError::InvalidManifest {
171 module: manifest.name.clone(),
172 message: message.to_owned(),
173 }
174}
175
176#[cfg(test)]
177mod tests {
178 use super::{MODULE_API_VERSION, ModuleArtifact, ModuleManifest, module_namespace};
179 use crate::{ModuleGraphError, resolve_modules};
180
181 #[test]
182 fn rejects_unsupported_versions_and_unsafe_artifact_paths() {
183 let mut future = ModuleManifest::new(
184 "local/example",
185 "1",
186 std::iter::empty::<&str>(),
187 std::iter::empty::<&str>(),
188 );
189 future.api_version = MODULE_API_VERSION + 1;
190 assert!(matches!(
191 resolve_modules([future]),
192 Err(ModuleGraphError::InvalidManifest { .. })
193 ));
194
195 let mut traversal = ModuleManifest::new(
196 "local/example",
197 "1",
198 std::iter::empty::<&str>(),
199 std::iter::empty::<&str>(),
200 );
201 traversal.artifacts.push(ModuleArtifact {
202 path: "../outside.txt".to_owned(),
203 source: "assets/outside.txt".to_owned(),
204 });
205 assert!(matches!(
206 resolve_modules([traversal]),
207 Err(ModuleGraphError::InvalidManifest { .. })
208 ));
209 }
210
211 #[test]
212 fn creates_collision_free_namespaces() {
213 assert_eq!(module_namespace("local/example").unwrap(), "local+example");
214 assert_ne!(
215 module_namespace("local/example-one").unwrap(),
216 module_namespace("local-example/one").unwrap()
217 );
218 assert!(module_namespace("Bad/Name").is_err());
219 }
220
221 #[test]
222 fn rejects_invalid_versions_capabilities_and_duplicate_artifact_paths() {
223 use super::validate_relative_path;
224
225 let mut invalid_version = ModuleManifest::new(
226 "local/example",
227 "1 2",
228 std::iter::empty::<&str>(),
229 std::iter::empty::<&str>(),
230 );
231 assert!(matches!(
232 crate::resolve_modules([invalid_version.clone()]),
233 Err(ModuleGraphError::InvalidManifest { .. })
234 ));
235 invalid_version.version = "1".to_owned();
236 invalid_version.provides = vec!["Not.Valid".to_owned()];
237 assert!(matches!(
238 crate::resolve_modules([invalid_version]),
239 Err(ModuleGraphError::InvalidManifest { .. })
240 ));
241
242 let mut duplicate = ModuleManifest::new(
243 "local/example",
244 "1",
245 std::iter::empty::<&str>(),
246 std::iter::empty::<&str>(),
247 );
248 duplicate.artifacts = vec![
249 ModuleArtifact {
250 path: "docs/a.md".to_owned(),
251 source: "assets/a.md".to_owned(),
252 },
253 ModuleArtifact {
254 path: "docs/a.md".to_owned(),
255 source: "assets/b.md".to_owned(),
256 },
257 ];
258 assert!(matches!(
259 crate::resolve_modules([duplicate]),
260 Err(ModuleGraphError::InvalidManifest { .. })
261 ));
262
263 assert!(validate_relative_path("").is_err());
264 assert!(validate_relative_path("/abs").is_err());
265 assert!(validate_relative_path("win\\path").is_err());
266 assert!(validate_relative_path("docs/../secret").is_err());
267 assert!(validate_relative_path("docs/README.md").is_ok());
268 }
269}