components-rs 0.1.1

Static analysis tooling for Components.js dependency injection projects
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
use std::collections::HashMap;
use std::path::{Path, PathBuf};

use crate::components::types::*;
use crate::context::expand::{self, ContextResolver, ExpandedNode};
use crate::error::{ComponentsJsError, Result};
use crate::fs::{self as cfs, Fs};
use crate::module_state::ModuleState;

/// Registry of all discovered CJS components.
#[derive(Debug, Clone)]
pub struct ComponentRegistry {
    /// All components indexed by IRI.
    pub components: HashMap<String, CjsComponent>,
    /// All modules indexed by IRI.
    pub modules: HashMap<String, CjsModule>,
}

/// Intermediate collected node before merging.
#[derive(Debug, Clone)]
struct CollectedNode {
    id: String,
    types: Vec<String>,
    properties: HashMap<String, Vec<serde_json::Value>>,
    source_file: String,
}

impl ComponentRegistry {
    pub fn new() -> Self {
        Self {
            components: HashMap::new(),
            modules: HashMap::new(),
        }
    }

    /// Register all available modules from the module state.
    /// Uses a two-pass approach: collect all nodes from all files, merge by @id, then process.
    pub async fn register_available_modules(
        &mut self,
        fs: &dyn Fs,
        state: &ModuleState,
    ) -> Result<()> {
        let mut all_nodes: HashMap<String, CollectedNode> = HashMap::new();
        let mut visited_files: std::collections::HashSet<PathBuf> =
            std::collections::HashSet::new();

        // Phase 1: Load all component files and collect nodes
        for version_map in state.component_modules.values() {
            for component_path in version_map.values() {
                if cfs::exists(fs, component_path).await {
                    self.collect_nodes_from_file(
                        fs,
                        component_path,
                        state,
                        &mut all_nodes,
                        &mut visited_files,
                    )
                    .await?;
                } else {
                    tracing::warn!(
                        "Component file does not exist: {}",
                        component_path.display()
                    );
                }
            }
        }

        tracing::info!(
            "Collected {} unique nodes from component files",
            all_nodes.len()
        );

        // Phase 2: Process merged nodes to find modules and components
        self.process_merged_nodes(&all_nodes, state)?;

        Ok(())
    }

    /// Recursively load a component file and its imports, collecting all nodes.
    fn collect_nodes_from_file<'a>(
        &'a self,
        fs: &'a dyn Fs,
        path: &'a Path,
        state: &'a ModuleState,
        all_nodes: &'a mut HashMap<String, CollectedNode>,
        visited: &'a mut std::collections::HashSet<PathBuf>,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + 'a>> {
        Box::pin(async move {
            let canonical = fs
                .canonicalize(path)
                .await
                .unwrap_or_else(|_| path.to_path_buf());
            if visited.contains(&canonical) {
                return Ok(());
            }
            visited.insert(canonical.clone());

            tracing::debug!("Loading component file: {}", path.display());

            let contents = fs.read_to_string(path).await?;
            let doc: serde_json::Value =
                serde_json::from_str(&contents).map_err(|e| ComponentsJsError::JsonParse {
                    path: path.display().to_string(),
                    source: e,
                })?;

            // Build context resolver
            let resolver = if let Some(ctx) = doc.get("@context") {
                ContextResolver::from_context_value(ctx, &state.contexts)?
            } else {
                ContextResolver::new()
            };

            // Extract nodes
            let nodes = expand::extract_graph_nodes(&doc, &state.contexts)?;
            let source = path.display().to_string();

            for node in &nodes {
                if let Some(id) = &node.id {
                    let entry =
                        all_nodes
                            .entry(id.clone())
                            .or_insert_with(|| CollectedNode {
                                id: id.clone(),
                                types: Vec::new(),
                                properties: HashMap::new(),
                                source_file: source.clone(),
                            });
                    for t in &node.types {
                        if !entry.types.contains(t) {
                            entry.types.push(t.clone());
                        }
                    }
                    for (key, vals) in &node.properties {
                        entry
                            .properties
                            .entry(key.clone())
                            .or_default()
                            .extend(vals.clone());
                    }
                }
            }

            // Process imports
            self.process_imports_collect(fs, &doc, &nodes, &resolver, state, all_nodes, visited)
                .await?;

            Ok(())
        })
    }

    /// Process import references and recursively collect nodes from imported files.
    fn process_imports_collect<'a>(
        &'a self,
        fs: &'a dyn Fs,
        doc: &'a serde_json::Value,
        nodes: &'a [ExpandedNode],
        resolver: &'a ContextResolver,
        state: &'a ModuleState,
        all_nodes: &'a mut HashMap<String, CollectedNode>,
        visited: &'a mut std::collections::HashSet<PathBuf>,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + 'a>> {
        Box::pin(async move {
            let mut import_iris = Vec::new();

            if let Some(import_val) = doc.get("import") {
                collect_import_iris(import_val, resolver, &mut import_iris);
            }

            for node in nodes {
                if let Some(imports) = node.properties.get(IRI_RDFS_SEE_ALSO) {
                    for import_val in imports {
                        collect_import_iris(import_val, resolver, &mut import_iris);
                    }
                }
            }

            for iri in import_iris {
                if let Some(local_path) = resolve_iri_to_path(&iri, &state.import_paths) {
                    if cfs::exists(fs, &local_path).await {
                        self.collect_nodes_from_file(fs, &local_path, state, all_nodes, visited)
                            .await?;
                    }
                }
            }

            Ok(())
        })
    }

    /// Phase 2: Process merged nodes to extract modules and components.
    fn process_merged_nodes(
        &mut self,
        all_nodes: &HashMap<String, CollectedNode>,
        _state: &ModuleState,
    ) -> Result<()> {
        // Find all Module nodes
        for node in all_nodes.values() {
            if node.types.contains(&IRI_MODULE.to_string()) {
                self.register_module_from_merged(node, all_nodes)?;
            }
        }
        Ok(())
    }

    fn register_module_from_merged(
        &mut self,
        node: &CollectedNode,
        _all_nodes: &HashMap<String, CollectedNode>,
    ) -> Result<()> {
        let require_name = node
            .properties
            .get(IRI_DOAP_NAME)
            .and_then(|v| v.first())
            .and_then(|v| v.as_str())
            .map(String::from);

        let mut components = Vec::new();

        if let Some(component_vals) = node.properties.get(IRI_COMPONENT) {
            for comp_val in component_vals {
                if let Some(comp) = self.parse_component(comp_val, &node.id) {
                    self.components.insert(comp.iri.clone(), comp.clone());
                    components.push(comp);
                }
            }
        }

        let module = CjsModule {
            iri: node.id.clone(),
            require_name,
            components,
            source_file: node.source_file.clone(),
        };

        self.modules.insert(node.id.clone(), module);
        Ok(())
    }

    fn parse_component(
        &self,
        value: &serde_json::Value,
        module_iri: &str,
    ) -> Option<CjsComponent> {
        let obj = value.as_object()?;

        let iri = obj.get("@id").and_then(|v| v.as_str())?.to_string();

        let types: Vec<String> = match obj.get("@type") {
            Some(serde_json::Value::String(t)) => vec![t.clone()],
            Some(serde_json::Value::Array(arr)) => {
                arr.iter()
                    .filter_map(|v| v.as_str().map(String::from))
                    .collect()
            }
            _ => vec![],
        };

        // Try expanded and short-name type matching
        let component_type = ComponentType::from_type_iris(&types).or_else(|| {
            for t in &types {
                match t.as_str() {
                    "Class" => return Some(ComponentType::Class),
                    "AbstractClass" => return Some(ComponentType::AbstractClass),
                    "Instance" => return Some(ComponentType::Instance),
                    _ => {}
                }
            }
            None
        })?;

        let require_element = obj
            .get("requireElement")
            .or_else(|| obj.get(IRI_COMPONENT_PATH))
            .and_then(|v| v.as_str())
            .map(String::from);

        let comment = obj
            .get("comment")
            .or_else(|| obj.get(IRI_RDFS_COMMENT))
            .and_then(|v| v.as_str())
            .map(String::from);

        let parameters = self.parse_parameters(obj);

        let extends: Vec<String> = match obj
            .get("extends")
            .or_else(|| obj.get(IRI_RDFS_SUBCLASS_OF))
        {
            Some(serde_json::Value::String(s)) => vec![s.clone()],
            Some(serde_json::Value::Array(arr)) => arr
                .iter()
                .filter_map(|v| match v {
                    serde_json::Value::String(s) => Some(s.clone()),
                    serde_json::Value::Object(o) => {
                        o.get("@id").and_then(|v| v.as_str()).map(String::from)
                    }
                    _ => None,
                })
                .collect(),
            Some(serde_json::Value::Object(o)) => o
                .get("@id")
                .and_then(|v| v.as_str())
                .map(String::from)
                .into_iter()
                .collect(),
            _ => vec![],
        };

        let constructor_arguments = obj
            .get("constructorArguments")
            .or_else(|| obj.get(IRI_CONSTRUCTOR_ARGUMENTS))
            .cloned();

        Some(CjsComponent {
            iri,
            component_type,
            require_element,
            comment,
            parameters,
            extends,
            constructor_arguments,
            module_iri: Some(module_iri.to_string()),
        })
    }

    fn parse_parameters(
        &self,
        obj: &serde_json::Map<String, serde_json::Value>,
    ) -> Vec<CjsParameter> {
        let params_val = obj.get("parameters").or_else(|| obj.get(IRI_PARAMETER));

        let params_arr = match params_val {
            Some(serde_json::Value::Array(arr)) => arr,
            _ => return vec![],
        };

        params_arr
            .iter()
            .filter_map(|p| {
                let p_obj = p.as_object()?;
                let iri = p_obj.get("@id").and_then(|v| v.as_str())?.to_string();
                let range = p_obj
                    .get("range")
                    .or_else(|| p_obj.get(IRI_RDFS_RANGE))
                    .and_then(|v| match v {
                        serde_json::Value::String(s) => Some(s.clone()),
                        serde_json::Value::Object(o) => {
                            o.get("@id").and_then(|v| v.as_str()).map(String::from)
                        }
                        _ => None,
                    });
                let comment = p_obj
                    .get("comment")
                    .or_else(|| p_obj.get(IRI_RDFS_COMMENT))
                    .and_then(|v| v.as_str())
                    .map(String::from);
                let required = p_obj
                    .get("required")
                    .and_then(|v| v.as_bool())
                    .unwrap_or(false);
                let lazy = p_obj
                    .get("lazy")
                    .and_then(|v| v.as_bool())
                    .unwrap_or(false);
                let unique = p_obj
                    .get("unique")
                    .and_then(|v| v.as_bool())
                    .unwrap_or(false);
                let default_value = p_obj.get("default").cloned();

                Some(CjsParameter {
                    iri,
                    range,
                    comment,
                    required,
                    lazy,
                    unique,
                    default_value,
                })
            })
            .collect()
    }

    /// Finalize the registry: resolve inheritance (inherit parameters from extends chain).
    pub fn finalize(&mut self) {
        let component_iris: Vec<String> = self.components.keys().cloned().collect();
        for iri in component_iris {
            let inherited_params = self.collect_inherited_params(&iri, &mut Vec::new());
            if let Some(comp) = self.components.get_mut(&iri) {
                for param in inherited_params {
                    if !comp.parameters.iter().any(|p| p.iri == param.iri) {
                        comp.parameters.push(param);
                    }
                }
            }
        }
    }

    fn collect_inherited_params(
        &self,
        iri: &str,
        visited: &mut Vec<String>,
    ) -> Vec<CjsParameter> {
        if visited.contains(&iri.to_string()) {
            return vec![];
        }
        visited.push(iri.to_string());

        let Some(comp) = self.components.get(iri) else {
            return vec![];
        };

        let mut params = Vec::new();
        for parent_iri in &comp.extends.clone() {
            if let Some(parent) = self.components.get(parent_iri) {
                params.extend(parent.parameters.clone());
            }
            params.extend(self.collect_inherited_params(parent_iri, visited));
        }
        params
    }
}

fn collect_import_iris(value: &serde_json::Value, resolver: &ContextResolver, out: &mut Vec<String>) {
    match value {
        serde_json::Value::String(s) => out.push(resolver.expand_term(s)),
        serde_json::Value::Array(arr) => {
            for v in arr {
                if let Some(s) = v.as_str() {
                    out.push(resolver.expand_term(s));
                }
            }
        }
        _ => {}
    }
}

/// Resolve an IRI to a local file path using the import_paths mapping.
pub fn resolve_iri_to_path(
    iri: &str,
    import_paths: &HashMap<String, PathBuf>,
) -> Option<PathBuf> {
    for (prefix_iri, local_dir) in import_paths {
        if iri.starts_with(prefix_iri.as_str()) {
            let suffix = &iri[prefix_iri.len()..];
            return Some(local_dir.join(suffix));
        }
    }
    if let Some(path) = iri.strip_prefix("file://") {
        return Some(PathBuf::from(path));
    }
    None
}