knot 1.10.0

Codebase Graph + Vector RAG Indexer for Java, TypeScript, JavaScript, Kotlin, Rust, Python, Groovy, C/C++, C#, Build Systems, and HTML/CSS codebases
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
use crate::models::{EntityKind, ParsedEntity};
use crate::pipeline::parser::utils::truncate_string;

/// Maximum nesting depth for JSON tree walking.
const MAX_DEPTH: usize = 10;

pub(crate) fn extract_entities_json_config(
    source: &str,
    file_path: &str,
    repo_name: &str,
) -> Vec<ParsedEntity> {
    let mut entities = Vec::new();

    let value: serde_json::Value = match serde_json::from_str(source) {
        Ok(v) => v,
        Err(_) => return entities,
    };

    // package.json is identified by filename, not by content: a
    // dependency-free library manifest must still yield the npm
    // ProjectIdentity that cross-repo linking matches against. A usable
    // `name` is still required — without it there is nothing to anchor the
    // identity on, so the file falls back to the generic config walk.
    let is_package_json = std::path::Path::new(file_path)
        .file_name()
        .and_then(|n| n.to_str())
        == Some("package.json")
        && value
            .as_object()
            .and_then(|o| o.get("name"))
            .and_then(|v| v.as_str())
            .is_some_and(|n| !n.is_empty());

    if is_package_json {
        extract_package_json(&value, file_path, repo_name, &mut entities);
    } else {
        walk_json("", &value, 0, file_path, repo_name, &mut entities);
    }

    entities
}

fn extract_package_json(
    value: &serde_json::Value,
    file_path: &str,
    repo_name: &str,
    entities: &mut Vec<ParsedEntity>,
) {
    let obj = match value.as_object() {
        Some(o) => o,
        None => return,
    };

    // Emit ProjectIdentity
    let package_name = obj
        .get("name")
        .and_then(|v| v.as_str())
        .unwrap_or("unknown");
    let version = obj
        .get("version")
        .and_then(|v| v.as_str())
        .unwrap_or("unknown");

    entities.push(ParsedEntity::new(
        package_name,
        EntityKind::ProjectIdentity,
        format!("npm:{}", package_name),
        Some(format!("version: {}, build_system: npm", version)),
        Some(format!("npm project identity: {}", package_name)),
        "json",
        file_path,
        1,
        1,
        None,
        repo_name,
    ));

    // Extract dependencies as BuildDependency
    let dep_sections = [
        ("dependencies", "scope: compile"),
        ("devDependencies", "scope: dev"),
        ("peerDependencies", "scope: peer"),
    ];

    for (section, scope) in &dep_sections {
        if let Some(deps) = obj.get(*section).and_then(|v| v.as_object()) {
            for (dep_name, dep_version) in deps {
                let ver_str = dep_version.as_str().unwrap_or("unknown");
                let name = format!("npm:{}:{}", dep_name, ver_str);
                let fqn = format!("npm:{}:{}", dep_name, ver_str);

                entities.push(ParsedEntity::new(
                    &name,
                    EntityKind::BuildDependency,
                    &fqn,
                    Some(scope.to_string()),
                    Some(format!("npm dependency: {}", name)),
                    "json",
                    file_path,
                    1,
                    1,
                    None,
                    repo_name,
                ));
            }
        }
    }

    // Extract scripts as ConfigProperty
    if let Some(scripts) = obj.get("scripts").and_then(|v| v.as_object()) {
        for (script_name, script_cmd) in scripts {
            let cmd = script_cmd.as_str().unwrap_or("?");
            let name = script_name.as_str();
            let fqn = format!("{}:{}:scripts.{}", repo_name, file_path, script_name);

            let mut entity = ParsedEntity::new(
                name,
                EntityKind::ConfigProperty,
                fqn,
                Some(cmd.to_string()),
                Some(format!("npm script: {}", script_name)),
                "json",
                file_path,
                1,
                1,
                None,
                repo_name,
            );
            entity.embed_text = format!("scripts.{} = {}", script_name, cmd);
            entities.push(entity);
        }
    }

    // Walk remaining fields as ConfigProperty (skip already-handled top-level keys)
    let skip_keys: std::collections::HashSet<&str> = [
        "name",
        "version",
        "dependencies",
        "devDependencies",
        "peerDependencies",
        "scripts",
    ]
    .iter()
    .copied()
    .collect();

    for (key, val) in obj {
        if skip_keys.contains(key.as_str()) {
            continue;
        }
        walk_json(key, val, 0, file_path, repo_name, entities);
    }
}

#[expect(
    clippy::too_many_arguments,
    reason = "function is verbose but correct — extraction deferred"
)]
fn walk_json(
    prefix: &str,
    value: &serde_json::Value,
    depth: usize,
    file_path: &str,
    repo_name: &str,
    entities: &mut Vec<ParsedEntity>,
) {
    if depth > MAX_DEPTH {
        return;
    }

    match value {
        serde_json::Value::Object(map) => {
            for (key, val) in map {
                let new_prefix = if prefix.is_empty() {
                    key.clone()
                } else {
                    format!("{}.{}", prefix, key)
                };
                walk_json(&new_prefix, val, depth + 1, file_path, repo_name, entities);
            }
        }
        serde_json::Value::Array(arr) => {
            for (i, item) in arr.iter().enumerate() {
                let new_prefix = format!("{}[{}]", prefix, i);
                walk_json(&new_prefix, item, depth + 1, file_path, repo_name, entities);
            }
        }
        _ => {
            let val_str = json_value_to_string(value);
            let name = prefix.rsplit('.').next().unwrap_or(prefix);
            let fqn = format!("{}:{}:{}", repo_name, file_path, prefix);
            let signature = truncate_string(&val_str, 200);
            let docstring = format!("Config property: {} = {}", prefix, val_str);
            let embed_text = format!("{} = {}", prefix, val_str);

            let mut entity = ParsedEntity::new(
                name,
                EntityKind::ConfigProperty,
                fqn,
                Some(signature),
                Some(docstring),
                "json",
                file_path,
                1,
                1,
                None,
                repo_name,
            );
            entity.embed_text = embed_text;
            entities.push(entity);
        }
    }
}

fn json_value_to_string(value: &serde_json::Value) -> String {
    match value {
        serde_json::Value::Null => "null".to_string(),
        serde_json::Value::Bool(b) => b.to_string(),
        serde_json::Value::Number(n) => n.to_string(),
        serde_json::Value::String(s) => s.clone(),
        serde_json::Value::Array(_) | serde_json::Value::Object(_) => "[complex]".to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_simple_config() {
        let source = r#"{"host": "localhost", "port": 8080, "debug": true}"#;
        let entities = extract_entities_json_config(source, "/app/config.json", "test-repo");

        let props: Vec<_> = entities
            .iter()
            .filter(|e| e.kind == EntityKind::ConfigProperty)
            .collect();
        assert_eq!(props.len(), 3);
        assert!(props.iter().any(|p| p.name == "host"));
        assert!(props.iter().any(|p| p.name == "port"));
        assert!(props.iter().any(|p| p.name == "debug"));
    }

    #[test]
    fn test_parse_nested_config() {
        let source = r#"{
  "database": {
    "host": "localhost",
    "port": 5432
  }
}"#;
        let entities = extract_entities_json_config(source, "/app/db.json", "test-repo");

        let props: Vec<_> = entities
            .iter()
            .filter(|e| e.kind == EntityKind::ConfigProperty)
            .collect();
        assert_eq!(props.len(), 2);
        assert!(props.iter().any(|p| p.fqn.contains("database.host")));
        assert!(props.iter().any(|p| p.fqn.contains("database.port")));
    }

    #[test]
    fn test_parse_package_json_dependencies() {
        let source = r#"{
  "name": "my-app",
  "version": "1.0.0",
  "dependencies": {
    "express": "^4.18.0",
    "lodash": "4.17.21"
  },
  "devDependencies": {
    "jest": "29.0.0"
  },
  "scripts": {
    "start": "node index.js",
    "test": "jest"
  }
}"#;
        let entities = extract_entities_json_config(source, "package.json", "test-repo");

        // BuildDependency entities (3: express, lodash, jest)
        let deps: Vec<_> = entities
            .iter()
            .filter(|e| e.kind == EntityKind::BuildDependency)
            .collect();
        assert_eq!(deps.len(), 3);
        assert!(deps.iter().any(|d| d.name.contains("express")));
        assert!(deps.iter().any(|d| d.name.contains("lodash")));
        assert!(deps.iter().any(|d| d.name.contains("jest")));

        // dev-dependency should have scope: dev
        let jest_dep = deps.iter().find(|d| d.name.contains("jest")).unwrap();
        assert!(jest_dep.signature.as_ref().unwrap().contains("scope: dev"));

        // ConfigProperty entities for scripts
        let props: Vec<_> = entities
            .iter()
            .filter(|e| e.kind == EntityKind::ConfigProperty)
            .collect();
        assert!(props.iter().any(|p| p.name == "start"));
        assert!(props.iter().any(|p| p.name == "test"));
    }

    #[test]
    fn test_parse_package_json_project_identity() {
        let source = r#"{
  "name": "@my-scope/my-app",
  "version": "2.0.0",
  "dependencies": {
    "express": "^4.0.0"
  }
}"#;
        let entities = extract_entities_json_config(source, "package.json", "test-repo");

        let identities: Vec<_> = entities
            .iter()
            .filter(|e| e.kind == EntityKind::ProjectIdentity)
            .collect();
        assert_eq!(identities.len(), 1);
        assert_eq!(identities[0].name, "@my-scope/my-app");
        assert_eq!(identities[0].fqn, "npm:@my-scope/my-app");
        assert!(
            identities[0]
                .signature
                .as_ref()
                .unwrap()
                .contains("build_system: npm")
        );
    }

    #[test]
    fn test_package_json_without_dependencies_emits_project_identity() {
        // D3 regression: a dependency-free library manifest must still yield
        // the npm ProjectIdentity that cross-repo linking matches against.
        // Detection is by filename, not by the presence of dependency keys.
        let source = r#"{
  "name": "@acme/ui-kit",
  "version": "1.0.0",
  "main": "index.js"
}"#;
        let entities = extract_entities_json_config(source, "package.json", "test-repo");

        let identities: Vec<_> = entities
            .iter()
            .filter(|e| e.kind == EntityKind::ProjectIdentity)
            .collect();
        assert_eq!(
            identities.len(),
            1,
            "dependency-free package.json must emit one ProjectIdentity"
        );
        assert_eq!(identities[0].name, "@acme/ui-kit");
        assert_eq!(identities[0].fqn, "npm:@acme/ui-kit");
        assert!(
            identities[0]
                .signature
                .as_ref()
                .unwrap()
                .contains("build_system: npm")
        );
    }

    #[test]
    fn test_non_package_json_named_file_is_not_treated_as_manifest() {
        // Exactly the same content at a non-manifest path must NOT get the
        // package.json special-casing (no ProjectIdentity emitted).
        let source = r#"{"name": "@acme/ui-kit", "version": "1.0.0"}"#;
        let entities = extract_entities_json_config(source, "/app/other.json", "test-repo");

        assert!(
            entities
                .iter()
                .all(|e| e.kind != EntityKind::ProjectIdentity),
            "a plain .json file is a generic config, not a package manifest"
        );
    }

    #[test]
    fn test_package_json_without_name_falls_back_to_config_walk() {
        // A package.json without a usable `name` cannot anchor an npm
        // identity, so it is treated as a generic config (no npm:unknown).
        let source = r#"{"version": "1.0.0"}"#;
        let entities = extract_entities_json_config(source, "package.json", "test-repo");

        assert!(
            entities
                .iter()
                .all(|e| e.kind != EntityKind::ProjectIdentity),
            "no ProjectIdentity should be synthesized for a nameless manifest"
        );
    }

    #[test]
    fn test_parse_tsconfig() {
        let source = r#"{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "strict": true
  }
}"#;
        let entities = extract_entities_json_config(source, "/app/tsconfig.json", "test-repo");

        let props: Vec<_> = entities
            .iter()
            .filter(|e| e.kind == EntityKind::ConfigProperty)
            .collect();
        assert_eq!(props.len(), 3);
        let target = props.iter().find(|p| p.name == "target").unwrap();
        assert!(target.fqn.contains("compilerOptions.target"));
        assert_eq!(target.signature.as_ref().unwrap(), "ES2022");
    }

    #[test]
    fn test_parse_empty_json() {
        let source = "{}";
        let entities = extract_entities_json_config(source, "/app/empty.json", "test-repo");
        assert!(entities.is_empty());
    }
}