zagens-cli 0.8.1

Zagens headless CLI + HTTP/SSE runtime sidecar (`zagens`, `zagens-runtime` binaries)
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
//! Regex-based symbol extractors for TypeScript/JavaScript, Python, Go, C/C++,
//! and Vue/Svelte single-file components.

use super::SymbolEntry;
use std::io::{BufRead, BufReader};
use std::path::Path;

const TS_PATTERNS: &[(&str, &str)] = &[
    (r"^export\s+default\s+(?:async\s+)?function\s+(\w+)", "fn"),
    (r"^export\s+(?:async\s+)?function\s+(\w+)", "fn"),
    (r"^(?:async\s+)?function\s+(\w+)", "fn"),
    (
        r"^export\s+const\s+(\w+)\s*=\s*(?:async\s+)?(?:\(|[A-Za-z_]\w*\s*=>)",
        "fn",
    ),
    (r"^export\s+(?:default\s+)?interface\s+(\w+)", "interface"),
    (r"^interface\s+(\w+)", "interface"),
    (r"^export\s+type\s+(\w+)\s*[=<]", "type"),
    (r"^(?:export\s+(?:default\s+)?)?class\s+(\w+)", "class"),
    (r"^(?:export\s+)?(?:const\s+)?enum\s+(\w+)", "enum"),
    (
        r"^\s{2,}(?:(?:public|private|protected|static|async|readonly|override)\s+)*(\w+)\s*[<(]",
        "method",
    ),
];

const TS_SKIP_NAMES: &[&str] = &[
    "if",
    "for",
    "while",
    "switch",
    "catch",
    "return",
    "new",
    "typeof",
    "instanceof",
    "in",
    "of",
    "from",
    "import",
    "export",
    "constructor",
    "super",
    "extends",
    "implements",
];

/// Extract symbols from TypeScript, TSX, or JavaScript source files.
pub(crate) fn extract_ts_symbols(path: &Path, source_mtime: u64) -> Option<Vec<SymbolEntry>> {
    let content = std::fs::read_to_string(path).ok()?;
    extract_ts_from_source(&content, source_mtime, 0)
}

/// Extract symbols from a Vue or Svelte single-file component `<script>` block.
pub(crate) fn extract_sfc_symbols(path: &Path, source_mtime: u64) -> Option<Vec<SymbolEntry>> {
    let content = std::fs::read_to_string(path).ok()?;
    let (script, line_offset) = extract_script_block(&content)?;
    extract_ts_from_source(script, source_mtime, line_offset)
}

/// Extract symbols from C/C++ source or header files.
pub(crate) fn extract_cpp_symbols(path: &Path, source_mtime: u64) -> Option<Vec<SymbolEntry>> {
    let file = std::fs::File::open(path).ok()?;
    let reader = BufReader::new(file);
    let mut symbols: Vec<SymbolEntry> = Vec::new();

    let re_class = regex::Regex::new(r"^(?:\s*(?:template\s*<[^>]*>\s*)?)?class\s+(\w+)").ok()?;
    let re_struct = regex::Regex::new(r"^struct\s+(\w+)").ok()?;
    let re_enum = regex::Regex::new(r"^enum\s+(?:class\s+)?(\w+)").ok()?;
    let re_namespace = regex::Regex::new(r"^namespace\s+(\w+)").ok()?;
    let re_fn_def = regex::Regex::new(
        r"^(?:[\w:<>,\*&\s~]+?\s+)+(\w+)\s*\([^;]*\)\s*(?:const\s*)?(?:noexcept\s*)?(?:override\s*)?\{",
    )
    .ok()?;
    let re_fn_decl = regex::Regex::new(
        r"^(?:[\w:<>,\*&\s~]+?\s+)+(\w+)\s*\([^;]*\)\s*(?:const\s*)?(?:noexcept\s*)?(?:override\s*)?;",
    )
    .ok()?;

    const SKIP: &[&str] = &["if", "for", "while", "switch", "return", "new", "delete"];

    for (line_idx, line_result) in reader.lines().enumerate() {
        let line = line_result.ok()?;
        let line_num = line_idx + 1;
        let trimmed = line.trim();

        if trimmed.starts_with("//") || trimmed.starts_with("/*") || trimmed.starts_with('*') {
            continue;
        }

        let mut matched = false;
        for (re, kind) in [
            (&re_class, "class"),
            (&re_struct, "struct"),
            (&re_enum, "enum"),
            (&re_namespace, "namespace"),
        ] {
            if let Some(cap) = re.captures(trimmed)
                && let Some(name) = cap.get(1)
            {
                let name = name.as_str();
                if !SKIP.contains(&name) {
                    symbols.push(SymbolEntry {
                        kind: kind.to_string(),
                        name: name.to_string(),
                        line: line_num,
                        source_mtime,
                        calls: vec![],
                    });
                    matched = true;
                    break;
                }
            }
        }
        if matched {
            continue;
        }

        if let Some(cap) = re_fn_def.captures(trimmed) {
            if let Some(name) = cap.get(1) {
                let name = name.as_str();
                if !SKIP.contains(&name) {
                    symbols.push(SymbolEntry {
                        kind: "fn".into(),
                        name: name.to_string(),
                        line: line_num,
                        source_mtime,
                        calls: vec![],
                    });
                }
            }
            continue;
        }

        if let Some(cap) = re_fn_decl.captures(trimmed)
            && let Some(name) = cap.get(1)
        {
            let name = name.as_str();
            if !SKIP.contains(&name) {
                symbols.push(SymbolEntry {
                    kind: "fn".into(),
                    name: name.to_string(),
                    line: line_num,
                    source_mtime,
                    calls: vec![],
                });
            }
        }
    }

    symbols.sort_by_key(|s| s.line);
    symbols.dedup_by(|a, b| a.kind == b.kind && a.name == b.name);
    Some(symbols)
}

/// Extract symbols from Python source files.
pub(crate) fn extract_py_symbols(path: &Path, source_mtime: u64) -> Option<Vec<SymbolEntry>> {
    let file = std::fs::File::open(path).ok()?;
    let reader = BufReader::new(file);
    let mut symbols: Vec<SymbolEntry> = Vec::new();

    let re_class = regex::Regex::new(r"^class\s+(\w+)").ok()?;
    let re_async_fn = regex::Regex::new(r"^async\s+def\s+(\w+)").ok()?;
    let re_fn = regex::Regex::new(r"^def\s+(\w+)").ok()?;
    let re_method = regex::Regex::new(r"^\s+def\s+(\w+)").ok()?;

    const SKIP_NAMES: &[&str] = &["if", "for", "while", "with", "class", "def", "return"];

    let mut current_class: Option<String> = None;

    for (line_idx, line_result) in reader.lines().enumerate() {
        let line = line_result.ok()?;
        let line_num = line_idx + 1;
        let trimmed = line.trim();

        if trimmed.starts_with('#') || trimmed.is_empty() {
            continue;
        }

        if let Some(cap) = re_class.captures(trimmed) {
            if let Some(name) = cap.get(1) {
                let name = name.as_str().to_string();
                current_class = Some(name.clone());
                symbols.push(SymbolEntry {
                    kind: "class".into(),
                    name,
                    line: line_num,
                    source_mtime,
                    calls: vec![],
                });
            }
            continue;
        }

        if !line.starts_with(' ') && !line.starts_with('\t') {
            current_class = None;
            if let Some(cap) = re_async_fn.captures(trimmed) {
                if let Some(name) = cap.get(1) {
                    let name = name.as_str();
                    if !SKIP_NAMES.contains(&name) {
                        symbols.push(SymbolEntry {
                            kind: "fn".into(),
                            name: name.to_string(),
                            line: line_num,
                            source_mtime,
                            calls: vec![],
                        });
                    }
                }
                continue;
            }
            if let Some(cap) = re_fn.captures(trimmed) {
                if let Some(name) = cap.get(1) {
                    let name = name.as_str();
                    if !SKIP_NAMES.contains(&name) {
                        symbols.push(SymbolEntry {
                            kind: "fn".into(),
                            name: name.to_string(),
                            line: line_num,
                            source_mtime,
                            calls: vec![],
                        });
                    }
                }
                continue;
            }
        } else if let Some(cap) = re_method.captures(&line)
            && let Some(name) = cap.get(1)
        {
            let name = name.as_str();
            if name == "self" || SKIP_NAMES.contains(&name) {
                continue;
            }
            if let Some(cls) = &current_class {
                symbols.push(SymbolEntry {
                    kind: "method".into(),
                    name: format!("{}::{}", cls, name),
                    line: line_num,
                    source_mtime,
                    calls: vec![],
                });
            }
        }
    }

    symbols.sort_by_key(|s| s.line);
    symbols.dedup_by(|a, b| a.kind == b.kind && a.name == b.name);
    Some(symbols)
}

/// Extract symbols from Go source files.
pub(crate) fn extract_go_symbols(path: &Path, source_mtime: u64) -> Option<Vec<SymbolEntry>> {
    let file = std::fs::File::open(path).ok()?;
    let reader = BufReader::new(file);
    let mut symbols: Vec<SymbolEntry> = Vec::new();

    let re_method = regex::Regex::new(r"^func\s+\(\s*\w+\s+\*?(\w+)\s*\)\s+(\w+)").ok()?;
    let re_fn = regex::Regex::new(r"^func\s+(\w+)").ok()?;
    let re_struct = regex::Regex::new(r"^type\s+(\w+)\s+struct\b").ok()?;
    let re_iface = regex::Regex::new(r"^type\s+(\w+)\s+interface\b").ok()?;
    let re_type = regex::Regex::new(r"^type\s+(\w+)\s+").ok()?;

    for (line_idx, line_result) in reader.lines().enumerate() {
        let line = line_result.ok()?;
        let line_num = line_idx + 1;
        let trimmed = line.trim();

        if trimmed.starts_with("//") || trimmed.is_empty() {
            continue;
        }

        if let Some(cap) = re_method.captures(trimmed) {
            let recv = cap.get(1)?.as_str();
            let name = cap.get(2)?.as_str();
            symbols.push(SymbolEntry {
                kind: "method".into(),
                name: format!("{}::{}", recv, name),
                line: line_num,
                source_mtime,
                calls: vec![],
            });
            continue;
        }

        if let Some(cap) = re_struct.captures(trimmed) {
            let name = cap.get(1)?.as_str().to_string();
            symbols.push(SymbolEntry {
                kind: "struct".into(),
                name,
                line: line_num,
                source_mtime,
                calls: vec![],
            });
            continue;
        }

        if let Some(cap) = re_iface.captures(trimmed) {
            let name = cap.get(1)?.as_str().to_string();
            symbols.push(SymbolEntry {
                kind: "interface".into(),
                name,
                line: line_num,
                source_mtime,
                calls: vec![],
            });
            continue;
        }

        if let Some(cap) = re_fn.captures(trimmed) {
            let name = cap.get(1)?.as_str().to_string();
            symbols.push(SymbolEntry {
                kind: "fn".into(),
                name,
                line: line_num,
                source_mtime,
                calls: vec![],
            });
            continue;
        }

        if let Some(cap) = re_type.captures(trimmed) {
            let name = cap.get(1)?.as_str().to_string();
            symbols.push(SymbolEntry {
                kind: "type".into(),
                name,
                line: line_num,
                source_mtime,
                calls: vec![],
            });
        }
    }

    symbols.sort_by_key(|s| s.line);
    symbols.dedup_by(|a, b| a.kind == b.kind && a.name == b.name);
    Some(symbols)
}

fn extract_script_block(content: &str) -> Option<(&str, usize)> {
    let lower = content.to_lowercase();
    let script_start = lower.find("<script")?;
    let after_tag = content[script_start..].find('>')? + script_start + 1;
    let close_rel = content[after_tag..].to_lowercase().find("</script>")?;
    let raw = &content[after_tag..after_tag + close_rel];
    let script = raw.trim();
    if script.is_empty() {
        return None;
    }
    let leading = raw.len() - raw.trim_start().len();
    let script_start = after_tag + leading;
    let line_offset = content[..script_start].matches('\n').count();
    Some((script, line_offset))
}

pub(crate) fn extract_ts_from_source(
    content: &str,
    source_mtime: u64,
    line_offset: usize,
) -> Option<Vec<SymbolEntry>> {
    extract_ts_style_lines(
        content.lines(),
        source_mtime,
        line_offset,
        TS_PATTERNS,
        TS_SKIP_NAMES,
    )
}

fn extract_ts_style_lines<I, S>(
    lines: I,
    source_mtime: u64,
    line_offset: usize,
    patterns: &[(&str, &str)],
    skip_names: &[&str],
) -> Option<Vec<SymbolEntry>>
where
    I: IntoIterator<Item = S>,
    S: AsRef<str>,
{
    let mut symbols: Vec<SymbolEntry> = Vec::new();

    let compiled: Vec<(regex::Regex, &str)> = patterns
        .iter()
        .filter_map(|(pat, kind)| regex::Regex::new(pat).ok().map(|r| (r, *kind)))
        .collect();

    let mut current_class: Option<String> = None;
    let mut brace_depth: i32 = 0;
    let mut class_brace_start: i32 = -1;

    for (line_idx, line) in lines.into_iter().enumerate() {
        let line = line.as_ref();
        let line_num = line_idx + 1 + line_offset;

        for ch in line.chars() {
            match ch {
                '{' => brace_depth += 1,
                '}' => {
                    brace_depth -= 1;
                    if current_class.is_some() && brace_depth <= class_brace_start {
                        current_class = None;
                        class_brace_start = -1;
                    }
                }
                _ => {}
            }
        }

        let trimmed = line.trim();
        if trimmed.starts_with("//") || trimmed.starts_with('*') || trimmed.starts_with("/*") {
            continue;
        }

        for (re, kind) in &compiled {
            if let Some(cap) = re.captures(line)
                && let Some(name_match) = cap.get(1)
            {
                let name = name_match.as_str().to_string();

                if skip_names.contains(&name.as_str()) {
                    continue;
                }

                let full_name = if *kind == "method" {
                    match &current_class {
                        Some(cls) => format!("{}::{}", cls, name),
                        None => continue,
                    }
                } else {
                    if *kind == "class" {
                        current_class = Some(name.clone());
                        class_brace_start = brace_depth;
                    }
                    name
                };

                symbols.push(SymbolEntry {
                    kind: kind.to_string(),
                    name: full_name,
                    line: line_num,
                    source_mtime,
                    calls: vec![],
                });
                break;
            }
        }
    }

    symbols.sort_by_key(|s| s.line);
    symbols.dedup_by(|a, b| a.kind == b.kind && a.name == b.name);
    Some(symbols)
}

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

    #[test]
    fn extract_py_symbols_finds_def_and_class() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let path = tmp.path().join("mod.py");
        std::fs::write(
            &path,
            "class Service:\n    def run(self):\n        pass\n\ndef main():\n    pass\n",
        )
        .unwrap();

        let syms = extract_py_symbols(&path, 0).expect("parse");
        assert!(
            syms.iter()
                .any(|s| s.kind == "class" && s.name == "Service")
        );
        assert!(
            syms.iter()
                .any(|s| s.kind == "method" && s.name == "Service::run")
        );
        assert!(syms.iter().any(|s| s.kind == "fn" && s.name == "main"));
    }

    #[test]
    fn extract_go_symbols_finds_func_and_struct() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let path = tmp.path().join("main.go");
        std::fs::write(
            &path,
            "package main\n\nfunc Hello() {}\n\ntype Config struct {}\n\nfunc (c *Config) Load() {}\n",
        )
        .unwrap();

        let syms = extract_go_symbols(&path, 0).expect("parse");
        assert!(syms.iter().any(|s| s.kind == "fn" && s.name == "Hello"));
        assert!(
            syms.iter()
                .any(|s| s.kind == "struct" && s.name == "Config")
        );
        assert!(
            syms.iter()
                .any(|s| s.kind == "method" && s.name == "Config::Load")
        );
    }

    #[test]
    fn extract_ts_symbols_parses_js_export() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let path = tmp.path().join("util.js");
        std::fs::write(&path, "export function normalizePath(p) {}\n").unwrap();

        let syms = extract_ts_symbols(&path, 0).expect("parse");
        assert!(
            syms.iter()
                .any(|s| s.kind == "fn" && s.name == "normalizePath")
        );
    }

    #[test]
    fn extract_cpp_symbols_finds_class_and_fn() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let path = tmp.path().join("widget.cpp");
        std::fs::write(&path, "class Widget {\n};\n\nvoid reset() {\n}\n").unwrap();

        let syms = extract_cpp_symbols(&path, 0).expect("parse");
        assert!(syms.iter().any(|s| s.kind == "class" && s.name == "Widget"));
        assert!(syms.iter().any(|s| s.kind == "fn" && s.name == "reset"));
    }

    #[test]
    fn extract_sfc_symbols_maps_script_line_numbers() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let path = tmp.path().join("App.vue");
        std::fs::write(
            &path,
            "<template><div /></template>\n<script setup>\nexport function boot() {}\n</script>\n",
        )
        .unwrap();

        let syms = extract_sfc_symbols(&path, 0).expect("parse");
        let boot = syms.iter().find(|s| s.name == "boot").expect("boot fn");
        assert_eq!(boot.line, 3);
    }
}