1use std::collections::{HashMap, HashSet};
9use std::path::Path;
10
11pub fn sanitize_module_name(raw: &str) -> String {
14 let mut result = String::new();
15 for ch in raw.chars() {
16 if ch.is_ascii_alphanumeric() || ch == '_' {
17 result.push(ch);
18 } else {
19 result.push_str(&format!("_u{:04x}", ch as u32));
20 }
21 }
22 if result.is_empty() {
23 result.push_str("_unnamed");
24 }
25 if !result.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_') {
26 result.insert(0, '_');
27 }
28 result
29}
30
31pub fn strip_imports_extract_exports(src: &str) -> (String, HashSet<String>) {
36 let mut result = String::with_capacity(src.len());
37 let mut exports = HashSet::new();
38
39 for line in src.lines() {
40 let trimmed = line.trim();
41
42 if trimmed.starts_with("import ") {
44 continue;
45 }
46
47 if let Some(rest) = trimmed.strip_prefix("export ") {
49 if let Some(after) = rest.strip_prefix("function ") {
50 if let Some(paren) = after.find('(') {
51 exports.insert(after[..paren].trim().to_string());
52 }
53 result.push_str(rest);
55 } else if let Some(after) = rest.strip_prefix("async function ") {
56 if let Some(paren) = after.find('(') {
57 exports.insert(after[..paren].trim().to_string());
58 }
59 result.push_str(rest);
60 } else if rest.starts_with("const ") || rest.starts_with("let ") || rest.starts_with("var ") {
61 let kw_len = if rest.starts_with("const ") { 6 } else { 4 };
62 if let Some(eq) = rest[kw_len..].find('=') {
63 let name = rest[kw_len..kw_len + eq].trim();
64 exports.insert(name.to_string());
65 }
66 result.push_str(rest);
67 } else if let Some(after_class) = rest.strip_prefix("class ") {
68 if let Some(br) = after_class.find([' ', '{']) {
69 exports.insert(after_class[..br].trim().to_string());
70 }
71 result.push_str(rest);
72 } else if let Some(after_default) = rest.strip_prefix("default ") {
73 if let Some(after_fn) = after_default.strip_prefix("function ") {
75 if let Some(paren) = after_fn.find('(') {
76 let name = after_fn[..paren].trim();
77 if !name.is_empty() {
78 exports.insert(name.to_string());
79 }
80 }
81 } else if let Some(after_class) = after_default.strip_prefix("class ")
82 && let Some(br) = after_class.find([' ', '{'])
83 {
84 exports.insert(after_class[..br].trim().to_string());
85 }
86 result.push_str(after_default);
87 } else if rest.starts_with('{') {
88 if let Some(braces) = rest.strip_prefix('{')
90 .and_then(|s| s.strip_suffix('}'))
91 .or_else(|| rest.strip_prefix('{').and_then(|s| {
92 s.find('}').map(|i| &s[..i])
94 }))
95 {
96 for name in braces.split(',') {
97 let name = name.trim();
98 if let Some(alias) = name.strip_prefix("as ") {
100 let alias = alias.trim();
101 if !alias.is_empty() {
102 exports.insert(alias.to_string());
103 }
104 } else if !name.is_empty() && !name.starts_with("as ") {
105 exports.insert(name.to_string());
106 }
107 }
108 }
109 continue;
110 } else {
111 continue;
113 }
114 result.push('\n');
115 } else {
116 result.push_str(line);
117 result.push('\n');
118 }
119 }
120
121 (result, exports)
122}
123
124fn sanitize_name(filename: &str) -> String {
126 let stem = filename.strip_suffix(".js").unwrap_or(filename);
127 sanitize_module_name(stem)
128}
129
130#[derive(Debug, Clone)]
132pub struct FileGroup {
133 pub core_name: String,
135 pub core_file: String,
137 pub members: Vec<String>,
139 pub name_map: HashMap<String, String>,
141 pub imported_names: HashMap<String, Vec<(String, String)>>,
144}
145
146pub fn analyze_single_group(in_dir: &str, core_file: &str) -> (Vec<FileGroup>, String) {
155 let in_path = Path::new(in_dir);
156
157 let mut visited: HashSet<String> = HashSet::new();
159 let mut stack: Vec<String> = vec![core_file.to_string()];
160 let mut js_files: Vec<String> = Vec::new();
161
162 while let Some(cur) = stack.pop() {
163 if !visited.insert(cur.clone()) {
164 continue;
165 }
166 js_files.push(cur.clone());
167
168 let src = std::fs::read_to_string(in_path.join(&cur))
169 .unwrap_or_else(|e| panic!("Cannot read '{}': {}", cur, e));
170 let (file_imports, _exports, _decls, _file_imported_names) = extract_imports(&src, &cur);
171 for dep in &file_imports {
172 if !visited.contains(dep.as_str()) {
173 stack.push(dep.clone());
174 }
175 }
176 }
177
178 let mut imports: HashMap<String, Vec<String>> = HashMap::new();
180 let mut imported_names: HashMap<String, Vec<(String, String)>> = HashMap::new();
181 let mut sanitzed: HashMap<String, String> = HashMap::new();
182
183 for file in &js_files {
184 let src = std::fs::read_to_string(in_path.join(file))
185 .unwrap_or_else(|e| panic!("Cannot read '{}': {}", file, e));
186 let (file_imports, _exports, _decls, file_imported_names) = extract_imports(&src, file);
187 imports.insert(file.clone(), file_imports);
188 imported_names.insert(file.clone(), file_imported_names);
189 sanitzed.insert(file.clone(), sanitize_name(file));
190 }
191
192 let members = transitive_deps(core_file, &imports);
194 let core_name = sanitzed.get(core_file).cloned().unwrap_or_else(|| {
195 sanitize_name(core_file)
196 });
197
198 let group = FileGroup {
199 core_name: core_name.clone(),
200 core_file: core_file.to_string(),
201 members,
202 name_map: sanitzed,
203 imported_names,
204 };
205
206 let groups = vec![group];
207 let groups_json = serde_json::to_string_pretty(&groups_to_json(&groups))
208 .expect("Failed to serialize groups.json");
209
210 (groups, groups_json)
211}
212
213fn transitive_deps(
215 file: &str,
216 imports: &HashMap<String, Vec<String>>,
217) -> Vec<String> {
218 let mut visited: HashSet<String> = HashSet::new();
219 let mut stack: Vec<String> = vec![file.to_string()];
220 let mut result: Vec<String> = Vec::new();
221
222 while let Some(cur) = stack.pop() {
224 if !visited.insert(cur.clone()) {
225 continue;
226 }
227 result.push(cur.clone());
228 if let Some(deps) = imports.get(&cur) {
229 for dep in deps {
230 if !visited.contains(dep.as_str()) {
231 stack.push(dep.clone());
232 }
233 }
234 }
235 }
236 result.reverse();
237 result
238}
239
240type ImportMeta = (Vec<String>, Vec<String>, Vec<String>, Vec<(String, String)>);
242
243fn extract_imports(
249 src: &str,
250 _filename: &str,
251) -> ImportMeta {
252 let mut imported_files: Vec<String> = Vec::new();
254 let mut exported_names: Vec<String> = Vec::new();
255 let mut declarations: Vec<String> = Vec::new();
256 let mut imported_names: Vec<(String, String)> = Vec::new();
257
258 for line in src.lines() {
259 let trimmed = line.trim();
260
261 if trimmed.starts_with("import ")
263 && let Some(from_idx) = trimmed.find(" from ") {
264 let specifier = &trimmed[from_idx + 6..];
266 let specifier = specifier.trim();
267 let path_str = if let Some(stripped) = specifier.strip_prefix('\'') {
268 stripped.find('\'').map(|end| &stripped[..end])
269 } else if let Some(stripped) = specifier.strip_prefix('"') {
270 stripped.find('"').map(|end| &stripped[..end])
271 } else {
272 None
273 };
274
275 let source_filename = path_str
276 .and_then(path_to_filename);
277
278 if let Some(ref sf) = source_filename {
279 imported_files.push(sf.clone());
280 }
281
282 let import_clause = &trimmed["import ".len()..from_idx].trim();
284 if let Some(brace_open) = import_clause.find('{')
285 && let Some(brace_close) = import_clause[brace_open..].find('}')
286 {
287 let names_str = &import_clause[brace_open + 1..brace_open + brace_close];
288 for name in names_str.split(',') {
289 let name = name.trim();
290 if !name.is_empty()
291 && let Some(ref sf) = source_filename
292 {
293 imported_names.push((name.to_string(), sf.clone()));
294 }
295 }
296 }
297 }
298
299 if let Some(rest) = trimmed.strip_prefix("export ") {
301 if let Some(after) = rest.strip_prefix("function ") {
302 if let Some(name_end) = after.find('(') {
303 exported_names.push(after[..name_end].trim().to_string());
304 }
305 } else if rest.starts_with("const ") || rest.starts_with("let ") || rest.starts_with("var ") {
306 let after = &rest[6..];
308 if let Some(eq) = after.find('=') {
309 let name = after[..eq].trim();
310 exported_names.push(name.to_string());
311 }
312 } else if let Some(after) = rest.strip_prefix("class ") {
313 if let Some(name_end) = after.find([' ', '{']) {
314 exported_names.push(after[..name_end].trim().to_string());
315 }
316 } else if rest.starts_with("async function ")
317 && let Some(name_end) = rest[16..].find('(') {
318 exported_names.push(rest[16..16 + name_end].trim().to_string());
319 }
320 }
321
322 if trimmed.starts_with("function ") && !trimmed.starts_with("//")
324 && let Some(name_end) = trimmed[9..].find('(') {
325 declarations.push(trimmed[9..9 + name_end].trim().to_string());
326 }
327 if (trimmed.starts_with("const ") || trimmed.starts_with("let ") || trimmed.starts_with("var "))
328 && !trimmed.contains("export ")
329 {
330 let prefix = if trimmed.starts_with("const ") { 6 } else { 4 };
331 let after = &trimmed[prefix..];
332 if let Some(eq) = after.find('=') {
333 let name = after[..eq].trim();
334 declarations.push(name.to_string());
335 }
336 }
337 }
338
339 imported_files.sort();
341 imported_files.dedup();
342 imported_names.sort();
343 imported_names.dedup();
344
345 (imported_files, exported_names, declarations, imported_names)
346}
347
348fn path_to_filename(path: &str) -> Option<String> {
350 let fname = Path::new(path).file_name()?.to_string_lossy().to_string();
351 if fname.ends_with(".js") {
352 Some(fname)
353 } else {
354 Some(format!("{}.js", fname))
355 }
356}
357
358fn groups_to_json(groups: &[FileGroup]) -> serde_json::Value {
360 let entries: Vec<serde_json::Value> = groups
361 .iter()
362 .map(|g| {
363 serde_json::json!({
364 "name": g.core_name,
365 "core_file": g.core_file,
366 "member_count": g.members.len(),
367 "members": g.members,
368 })
369 })
370 .collect();
371 serde_json::Value::Array(entries)
372}