@nexiq/cli 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1550 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { minimatch } from "minimatch";
4
+ import * as watcher from "@parcel/watcher";
5
+ import { analyzeProject } from "@nexiq/analyser";
6
+ import { SqliteDB } from "@nexiq/analyser/db/sqlite";
7
+ import {
8
+ type JsonData,
9
+ type ProjectStatus,
10
+ type GitStatus,
11
+ type GitCommit,
12
+ type GitFileDiff,
13
+ type ReactMapConfig,
14
+ type SubProject,
15
+ getDisplayName,
16
+ parseRawDiff,
17
+ type DatabaseData,
18
+ type SymbolRow,
19
+ type RenderRow,
20
+ } from "@nexiq/shared";
21
+ import type { Extension } from "@nexiq/extension-sdk";
22
+ import { pathToFileURL } from "node:url";
23
+ import { exec } from "node:child_process";
24
+ import { promisify } from "node:util";
25
+ import { simpleGit, type LogOptions } from "simple-git";
26
+ import yaml from "js-yaml";
27
+ import fg from "fast-glob";
28
+ import tmp from "tmp";
29
+
30
+ const execAsync = promisify(exec);
31
+
32
+ interface ExtendedSymbolRow extends SymbolRow {
33
+ file: string;
34
+ line: number;
35
+ column: number;
36
+ kind: string;
37
+ type: string;
38
+ }
39
+
40
+ interface ExtendedRenderRow extends RenderRow {
41
+ file: string;
42
+ in_name: string | null;
43
+ }
44
+
45
+ export interface PnpmWorkspace {
46
+ packages?: string[];
47
+ }
48
+
49
+ export interface PackageJson {
50
+ name?: string;
51
+ workspaces?: string[] | { packages?: string[] };
52
+ }
53
+
54
+ export interface ProjectInfo {
55
+ projectPath: string;
56
+ subProject?: string;
57
+ graph?: JsonData;
58
+ subscription?: watcher.AsyncSubscription;
59
+ extensions: Extension[];
60
+ sqlitePath: string;
61
+ db?: SqliteDB;
62
+ }
63
+
64
+ export interface SymbolSearchResult {
65
+ kind?: string;
66
+ usage_kind?: string;
67
+ name: string;
68
+ file: string;
69
+ loc: { line: number; column: number };
70
+ props?: unknown[];
71
+ in?: string; // Context where it's used
72
+ usages?: SymbolSearchResult[]; // Grouped usages
73
+ }
74
+
75
+ export interface SymbolInfo {
76
+ definitions: SymbolSearchResult[];
77
+ externalUsages?: SymbolSearchResult[];
78
+ }
79
+
80
+ interface TreeNode {
81
+ name: string;
82
+ children: TreeNode[];
83
+ }
84
+
85
+ export interface ComponentHierarchyNode {
86
+ id: string;
87
+ name: string;
88
+ children: (ComponentHierarchyNode | { name: string; status: string })[];
89
+ status?: string;
90
+ }
91
+
92
+ export class ProjectManager {
93
+ private projects = new Map<string, ProjectInfo>();
94
+ private pendingProjects = new Map<string, Promise<ProjectInfo>>();
95
+
96
+ async openProject(
97
+ projectPath: string,
98
+ subProject?: string,
99
+ ): Promise<ProjectInfo> {
100
+ const key = subProject ? `${projectPath}:${subProject}` : projectPath;
101
+ if (this.projects.has(key)) {
102
+ return this.projects.get(key)!;
103
+ }
104
+
105
+ if (this.pendingProjects.has(key)) {
106
+ console.error(
107
+ `Project already opening: ${key}, returning pending promise`,
108
+ );
109
+ return this.pendingProjects.get(key)!;
110
+ }
111
+
112
+ const openPromise = (async () => {
113
+ try {
114
+ const result = await this._openProjectInternal(projectPath, subProject);
115
+ this.projects.set(key, result);
116
+ return result;
117
+ } finally {
118
+ this.pendingProjects.delete(key);
119
+ }
120
+ })();
121
+
122
+ this.pendingProjects.set(key, openPromise);
123
+ return openPromise;
124
+ }
125
+
126
+ private async _openProjectInternal(
127
+ projectPath: string,
128
+ subProject?: string,
129
+ ): Promise<ProjectInfo> {
130
+ const analysisPath = subProject
131
+ ? path.resolve(projectPath, subProject)
132
+ : projectPath;
133
+ const cacheDir = path.join(analysisPath, ".react-map", "cache");
134
+ try {
135
+ if (!fs.existsSync(cacheDir)) {
136
+ fs.mkdirSync(cacheDir, { recursive: true });
137
+ }
138
+ } catch (e) {
139
+ console.warn(`Failed to create cache directory at ${cacheDir}:`, e);
140
+ }
141
+
142
+ const pathHash = Buffer.from(analysisPath).toString("hex").slice(0, 8);
143
+ const cacheFile = path.join(
144
+ cacheDir,
145
+ `${path.basename(analysisPath)}-${pathHash}.json`,
146
+ );
147
+ const sqlitePath = path.join(
148
+ cacheDir,
149
+ `${path.basename(analysisPath)}-${pathHash}.sqlite`,
150
+ );
151
+
152
+ // Load config
153
+ const configPath = path.join(analysisPath, "react.map.config.json");
154
+ let ignorePatterns: string[] | undefined;
155
+ let extensionNames: string[] = [];
156
+
157
+ if (fs.existsSync(configPath)) {
158
+ try {
159
+ const config = JSON.parse(fs.readFileSync(configPath, "utf-8"));
160
+ ignorePatterns = config.ignorePatterns;
161
+ extensionNames = config.extensions || [];
162
+ } catch (e: unknown) {
163
+ console.warn("Failed to load config for project", e);
164
+ }
165
+ }
166
+
167
+ // Load extensions dynamically
168
+ const extensions: Extension[] = [];
169
+ for (const name of extensionNames) {
170
+ try {
171
+ let loaded: unknown;
172
+
173
+ try {
174
+ // 1. Try importing by name (resolves from server's node_modules)
175
+ loaded = await import(name);
176
+ } catch (e: unknown) {
177
+ // 2. Try importing relative to the project being analyzed
178
+ const projectNodeModulesPath = path.join(
179
+ analysisPath,
180
+ "node_modules",
181
+ name,
182
+ );
183
+ const pkgJsonPath = path.join(projectNodeModulesPath, "package.json");
184
+
185
+ if (fs.existsSync(pkgJsonPath)) {
186
+ const pkg = JSON.parse(fs.readFileSync(pkgJsonPath, "utf-8"));
187
+ const entry = pkg.module || pkg.main || "index.js";
188
+ const fullPath = path.join(projectNodeModulesPath, entry);
189
+ loaded = await import(pathToFileURL(fullPath).href);
190
+ } else {
191
+ throw e; // Rethrow original error if project-relative also fails
192
+ }
193
+ }
194
+
195
+ const extension = Object.values(
196
+ (loaded as Record<string, unknown>) || {},
197
+ ).find(
198
+ (val: unknown) => val && typeof val === "object" && "id" in val,
199
+ ) as Extension;
200
+
201
+ if (extension) {
202
+ extensions.push(extension);
203
+ console.error(`Loaded extension: ${extension.id} from ${name}`);
204
+ }
205
+ } catch (e: unknown) {
206
+ console.error(
207
+ `Failed to load extension ${name}:`,
208
+ e instanceof Error ? e.message : "Unknown error",
209
+ );
210
+ }
211
+ }
212
+
213
+ console.error(`Analyzing project: ${analysisPath}`);
214
+ const graph = await analyzeProject(
215
+ analysisPath,
216
+ cacheFile,
217
+ ignorePatterns,
218
+ sqlitePath,
219
+ );
220
+
221
+ fs.writeFileSync(cacheFile, JSON.stringify(graph, null, 2));
222
+
223
+ const projectInfo: ProjectInfo = {
224
+ projectPath,
225
+ subProject,
226
+ graph,
227
+ extensions,
228
+ sqlitePath,
229
+ db: new SqliteDB(sqlitePath),
230
+ };
231
+
232
+ // Set up watcher
233
+ try {
234
+ const subscription = await watcher.subscribe(
235
+ analysisPath,
236
+ (err, events) => {
237
+ if (err) {
238
+ console.error(`Watcher error for ${analysisPath}:`, err);
239
+ return;
240
+ }
241
+
242
+ const hasRelevantChange = events.some((event) => {
243
+ const filePath = event.path;
244
+ return (
245
+ filePath.endsWith(".ts") ||
246
+ filePath.endsWith(".tsx") ||
247
+ filePath.endsWith(".js") ||
248
+ filePath.endsWith(".jsx")
249
+ );
250
+ });
251
+
252
+ if (hasRelevantChange) {
253
+ console.error(
254
+ `Changes detected in ${analysisPath}, re-analyzing...`,
255
+ );
256
+ analyzeProject(
257
+ analysisPath,
258
+ cacheFile,
259
+ ignorePatterns,
260
+ projectInfo.sqlitePath,
261
+ )
262
+ .then((newGraph: JsonData) => {
263
+ projectInfo.graph = newGraph;
264
+ fs.writeFileSync(
265
+ cacheFile,
266
+ JSON.stringify(projectInfo.graph, null, 2),
267
+ );
268
+
269
+ if (projectInfo.db) projectInfo.db.close();
270
+ projectInfo.db = new SqliteDB(projectInfo.sqlitePath);
271
+
272
+ console.error(
273
+ `Project ${analysisPath} re-analyzed successfully.`,
274
+ );
275
+ })
276
+ .catch((reAnalyzeError: Error) => {
277
+ console.error(
278
+ `Re-analysis failed for ${analysisPath}:`,
279
+ reAnalyzeError,
280
+ );
281
+ });
282
+ }
283
+ },
284
+ {
285
+ ignore: [
286
+ "node_modules",
287
+ ".git",
288
+ ".react-map",
289
+ "dist",
290
+ "build",
291
+ ".next",
292
+ ".vite",
293
+ ...(ignorePatterns || []).map((p) =>
294
+ p.replace(/^\*\*\/|\/\*\*$/g, ""),
295
+ ),
296
+ ],
297
+ },
298
+ );
299
+ projectInfo.subscription = subscription;
300
+ } catch (watcherError) {
301
+ console.error(
302
+ `Failed to start watcher for ${analysisPath}:`,
303
+ watcherError,
304
+ );
305
+ }
306
+
307
+ return projectInfo;
308
+ }
309
+
310
+ public async getDatabaseData(
311
+ projectPath: string,
312
+ subProject?: string,
313
+ ): Promise<DatabaseData> {
314
+ const project = await this.openProject(projectPath, subProject);
315
+ return project.db!.getAllData();
316
+ }
317
+
318
+ getOpenProjectPaths(): string[] {
319
+ return Array.from(this.projects.values()).map((p) => p.projectPath);
320
+ }
321
+
322
+ getProject(
323
+ projectPath: string,
324
+ subProject?: string,
325
+ ): ProjectInfo | undefined {
326
+ const key = subProject ? `${projectPath}:${subProject}` : projectPath;
327
+ return this.projects.get(key);
328
+ }
329
+
330
+ getAllExtensions(): Extension[] {
331
+ const all = new Map<string, Extension>();
332
+ for (const project of this.projects.values()) {
333
+ for (const ext of project.extensions) {
334
+ all.set(ext.id, ext);
335
+ }
336
+ }
337
+ return Array.from(all.values());
338
+ }
339
+
340
+ async findSymbol(
341
+ projectPath: string,
342
+ query: string,
343
+ subProject?: string,
344
+ strict: boolean = true,
345
+ includeProps: boolean = false,
346
+ includeUsages: boolean = false,
347
+ exclude?: string[],
348
+ ): Promise<SymbolInfo> {
349
+ const project = await this.openProject(projectPath, subProject);
350
+
351
+ const definitions_results: SymbolSearchResult[] = [];
352
+ const externalUsages: SymbolSearchResult[] = [];
353
+
354
+ const isExcluded = (filePath: string) => {
355
+ if (!exclude || exclude.length === 0) return false;
356
+ return exclude.some(
357
+ (pattern) =>
358
+ minimatch(filePath, pattern, { dot: true, nocase: true }) ||
359
+ minimatch(path.basename(filePath), pattern, {
360
+ dot: true,
361
+ nocase: true,
362
+ }),
363
+ );
364
+ };
365
+
366
+ // 1. Find the symbol's definition(s)
367
+ let definitions: ExtendedSymbolRow[];
368
+ if (strict) {
369
+ definitions = project
370
+ .db!.db.prepare(
371
+ `
372
+ SELECT s.*, f.path as file, e.line, e.column, e.kind, e.type, e.data_json
373
+ FROM symbols s
374
+ JOIN entities e ON s.entity_id = e.id
375
+ JOIN scopes sc ON e.scope_id = sc.id
376
+ JOIN files f ON sc.file_id = f.id
377
+ WHERE s.name = ? and e.kind != 'import'
378
+ `,
379
+ )
380
+ .all(query) as ExtendedSymbolRow[];
381
+ } else {
382
+ definitions = project
383
+ .db!.db.prepare(
384
+ `
385
+ SELECT s.*, f.path as file, e.line, e.column, e.kind, e.type, e.data_json
386
+ FROM symbols s
387
+ JOIN entities e ON s.entity_id = e.id
388
+ JOIN scopes sc ON e.scope_id = sc.id
389
+ JOIN files f ON sc.file_id = f.id
390
+ WHERE (s.name = ? OR s.name LIKE ?) and e.kind != 'import'
391
+ `,
392
+ )
393
+ .all(query, `%${query}%`) as ExtendedSymbolRow[];
394
+ }
395
+
396
+ for (const def of definitions) {
397
+ if (isExcluded(def.file)) continue;
398
+
399
+ const definition: SymbolSearchResult = {
400
+ kind: def.kind,
401
+ name: def.name,
402
+ file: def.file,
403
+ loc: { line: def.line || 0, column: def.column || 0 },
404
+ };
405
+
406
+ if (includeProps && def.data_json) {
407
+ try {
408
+ const data = JSON.parse(def.data_json);
409
+ definition.props = data.props || [];
410
+ } catch {
411
+ definition.props = [];
412
+ }
413
+ }
414
+
415
+ if (includeUsages) {
416
+ definition.usages = [];
417
+ // 2. Find renders of this specific symbol ID or tag name
418
+ const usages = project
419
+ .db!.db.prepare(
420
+ `
421
+ SELECT r.*, f.path as file, s.name as in_name
422
+ FROM renders r
423
+ JOIN files f ON r.file_id = f.id
424
+ LEFT JOIN entities e ON r.parent_entity_id = e.id
425
+ LEFT JOIN symbols s ON s.entity_id = e.id
426
+ WHERE r.symbol_id = ? OR r.tag = ?
427
+ `,
428
+ )
429
+ .all(def.id, def.name) as ExtendedRenderRow[];
430
+
431
+ for (const usage of usages) {
432
+ if (isExcluded(usage.file)) continue;
433
+
434
+ definition.usages.push({
435
+ kind: usage.kind === "jsx" ? "render" : "call",
436
+ name: usage.tag,
437
+ file: usage.file,
438
+ loc: { line: usage.line || 0, column: usage.column || 0 },
439
+ in: usage.in_name || "unknown",
440
+ });
441
+ }
442
+ }
443
+
444
+ definitions_results.push(definition);
445
+ }
446
+
447
+ // 3. Fallback for external symbols (tags not defined in this project)
448
+ if (includeUsages && definitions_results.length === 0) {
449
+ const results = project
450
+ .db!.db.prepare(
451
+ `
452
+ SELECT r.*, f.path as file, s.name as in_name
453
+ FROM renders r
454
+ JOIN files f ON r.file_id = f.id
455
+ LEFT JOIN entities e ON r.parent_entity_id = e.id
456
+ LEFT JOIN symbols s ON s.entity_id = e.id
457
+ WHERE r.tag = ?
458
+ `,
459
+ )
460
+ .all(query) as ExtendedRenderRow[];
461
+
462
+ for (const usage of results) {
463
+ if (isExcluded(usage.file)) continue;
464
+
465
+ externalUsages.push({
466
+ kind: usage.kind === "jsx" ? "render" : "call",
467
+ name: usage.tag,
468
+ file: usage.file,
469
+ loc: { line: usage.line || 0, column: usage.column || 0 },
470
+ in: usage.in_name || "unknown",
471
+ });
472
+ }
473
+ }
474
+
475
+ return { definitions: definitions_results, externalUsages };
476
+ }
477
+
478
+ async getSymbolUsagesWithContext(
479
+ projectPath: string,
480
+ query: string,
481
+ subProject?: string,
482
+ strict: boolean = true,
483
+ contextLines: number = 2,
484
+ exclude?: string[],
485
+ ) {
486
+ const symbolInfo = await this.findSymbol(
487
+ projectPath,
488
+ query,
489
+ subProject,
490
+ strict,
491
+ false,
492
+ true,
493
+ exclude,
494
+ );
495
+
496
+ const allUsages: SymbolSearchResult[] = [];
497
+ symbolInfo.definitions.forEach((def) => {
498
+ if (def.usages) allUsages.push(...def.usages);
499
+ });
500
+ if (symbolInfo.externalUsages) {
501
+ allUsages.push(...symbolInfo.externalUsages);
502
+ }
503
+
504
+ const fileCache = new Map<string, string[]>();
505
+ const results = [];
506
+
507
+ const analysisPath = subProject
508
+ ? path.resolve(projectPath, subProject)
509
+ : projectPath;
510
+
511
+ for (const usage of allUsages) {
512
+ const fullPath = path.resolve(
513
+ analysisPath,
514
+ usage.file.startsWith("/") ? usage.file.slice(1) : usage.file,
515
+ );
516
+
517
+ if (!fs.existsSync(fullPath)) continue;
518
+
519
+ let lines = fileCache.get(fullPath);
520
+ if (!lines) {
521
+ lines = fs.readFileSync(fullPath, "utf-8").split("\n");
522
+ fileCache.set(fullPath, lines);
523
+ }
524
+
525
+ const lineIdx = usage.loc.line - 1;
526
+ const start = Math.max(0, lineIdx - contextLines);
527
+ const end = Math.min(lines.length - 1, lineIdx + contextLines);
528
+ const context = lines.slice(start, end + 1);
529
+
530
+ results.push({
531
+ file: usage.file,
532
+ line: usage.loc.line,
533
+ column: usage.loc.column,
534
+ in: usage.in,
535
+ kind: usage.kind,
536
+ context,
537
+ });
538
+ }
539
+
540
+ return results;
541
+ }
542
+
543
+ async getPropDefinitions(
544
+ projectPath: string,
545
+ query: string,
546
+ subProject?: string,
547
+ ) {
548
+ const symbolInfo = await this.findSymbol(
549
+ projectPath,
550
+ query,
551
+ subProject,
552
+ true, // strict
553
+ true, // includeProps
554
+ false, // includeUsages
555
+ );
556
+
557
+ return symbolInfo.definitions.map((def) => ({
558
+ name: def.name,
559
+ file: def.file,
560
+ props: def.props || [],
561
+ }));
562
+ }
563
+
564
+ async findFiles(projectPath: string, pattern: string, subProject?: string) {
565
+ const project = await this.openProject(projectPath, subProject);
566
+
567
+ const isGlob = /[*?[\]]/.test(pattern);
568
+ const files = Object.keys(project.graph!.files);
569
+
570
+ if (isGlob) {
571
+ const results = files.filter(
572
+ (p) =>
573
+ minimatch(p, pattern, { dot: true, nocase: true }) ||
574
+ minimatch(path.basename(p), pattern, { dot: true, nocase: true }),
575
+ );
576
+ return results.sort();
577
+ }
578
+
579
+ const regex = new RegExp(pattern, "i");
580
+ const results = files.filter(
581
+ (p) => regex.test(p) || regex.test(path.basename(p)),
582
+ );
583
+ return results.sort();
584
+ }
585
+
586
+ async getFileImports(
587
+ projectPath: string,
588
+ filePath: string,
589
+ subProject?: string,
590
+ ) {
591
+ const project = await this.openProject(projectPath, subProject);
592
+
593
+ const normalizedPath = filePath.startsWith("/") ? filePath : `/${filePath}`;
594
+ const file = project.graph!.files[normalizedPath];
595
+ if (!file) throw new Error(`File not found: ${normalizedPath}`);
596
+
597
+ return file.import;
598
+ }
599
+
600
+ async getProjectTree(
601
+ projectPath: string,
602
+ subProject?: string,
603
+ maxDepth: number = 3,
604
+ ): Promise<TreeNode> {
605
+ const project = await this.openProject(projectPath, subProject);
606
+
607
+ const root: TreeNode = { name: "/", children: [] };
608
+ const files = Object.keys(project.graph!.files).sort();
609
+
610
+ for (const filePath of files) {
611
+ const parts = filePath.split("/").filter(Boolean);
612
+ let current = root;
613
+ for (let i = 0; i < Math.min(parts.length, maxDepth); i++) {
614
+ const part = parts[i]!;
615
+ let node = current.children.find((c) => c.name === part);
616
+ if (!node) {
617
+ node = { name: part, children: [] };
618
+ current.children.push(node);
619
+ }
620
+ current = node;
621
+ }
622
+ }
623
+
624
+ const sortNodes = (node: TreeNode) => {
625
+ node.children.sort((a, b) => a.name.localeCompare(b.name));
626
+ for (const child of node.children) sortNodes(child);
627
+ };
628
+ sortNodes(root);
629
+ return root;
630
+ }
631
+
632
+ async getComponentHierarchy(
633
+ projectPath: string,
634
+ componentName: string,
635
+ subProject?: string,
636
+ depth: number = 2,
637
+ ): Promise<
638
+ | {
639
+ component: string;
640
+ hierarchies: ComponentHierarchyNode[];
641
+ renderedBy: { id: string; name: string; file: string }[];
642
+ }
643
+ | { error: string }
644
+ > {
645
+ const project = await this.openProject(projectPath, subProject);
646
+
647
+ // Find the starting component(s)
648
+ const startComponents = project
649
+ .db!.db.prepare(
650
+ `
651
+ SELECT s.*, f.path as file, e.line, e.column, e.kind, e.type
652
+ FROM symbols s
653
+ JOIN entities e ON s.entity_id = e.id
654
+ JOIN scopes sc ON e.scope_id = sc.id
655
+ JOIN files f ON sc.file_id = f.id
656
+ WHERE s.name = ? AND e.kind = 'component'
657
+ `,
658
+ )
659
+
660
+ .all(componentName) as ExtendedSymbolRow[];
661
+
662
+ if (startComponents.length === 0) {
663
+ return { error: `Component "${componentName}" not found.` };
664
+ }
665
+
666
+ const buildHierarchy = (
667
+ symbolId: string,
668
+ currentDepth: number,
669
+ visited: Set<string>,
670
+ ): ComponentHierarchyNode => {
671
+ const sym = project
672
+ .db!.db.prepare(`SELECT * FROM symbols WHERE id = ?`)
673
+ .get(symbolId) as SymbolRow | undefined;
674
+ if (!sym || currentDepth > depth || visited.has(symbolId)) {
675
+ return {
676
+ id: symbolId,
677
+ name: sym?.name || "unknown",
678
+ children: [],
679
+ status: "limit-or-circular",
680
+ };
681
+ }
682
+ visited.add(symbolId);
683
+
684
+ const children = project
685
+ .db!.db.prepare(
686
+ `SELECT r.*, f.path as file FROM renders r JOIN files f ON r.file_id = f.id WHERE parent_entity_id = (SELECT entity_id FROM symbols WHERE id = ?)`,
687
+ )
688
+ .all(symbolId) as ExtendedRenderRow[];
689
+
690
+ return {
691
+ id: sym.id,
692
+ name: sym.name,
693
+ children: children.map((c) => {
694
+ if (c.symbol_id) {
695
+ return buildHierarchy(
696
+ c.symbol_id,
697
+ currentDepth + 1,
698
+ new Set(visited),
699
+ );
700
+ }
701
+ return {
702
+ name: c.tag,
703
+ status: "unresolved",
704
+ kind: c.kind,
705
+ index: c.render_index,
706
+ };
707
+ }),
708
+ };
709
+ };
710
+
711
+ const renderedBy = project
712
+ .db!.db.prepare(
713
+ `
714
+ SELECT DISTINCT s.id, s.name, f.path as file
715
+ FROM symbols s
716
+ JOIN entities e ON s.entity_id = e.id
717
+ JOIN scopes sc ON e.scope_id = sc.id
718
+ JOIN files f ON sc.file_id = f.id
719
+ JOIN renders r ON r.parent_entity_id = e.id
720
+ WHERE r.tag = ? OR r.symbol_id IN (SELECT id FROM symbols WHERE name = ?)
721
+ `,
722
+ )
723
+ .all(componentName, componentName) as ExtendedSymbolRow[];
724
+
725
+ return {
726
+ component: componentName,
727
+ hierarchies: startComponents.map((c) =>
728
+ buildHierarchy(c.id, 0, new Set()),
729
+ ),
730
+ renderedBy: renderedBy.map((s) => ({
731
+ id: s.id,
732
+ name: s.name,
733
+ file: s.file,
734
+ })),
735
+ };
736
+ }
737
+
738
+ async getSymbolLocation(
739
+ projectPath: string,
740
+ query: string,
741
+ subProject?: string,
742
+ ): Promise<
743
+ {
744
+ id: string;
745
+ name: string;
746
+ file: string;
747
+ loc: { line: number; column: number };
748
+ kind: string;
749
+ type: string;
750
+ }[]
751
+ > {
752
+ const project = await this.openProject(projectPath, subProject);
753
+
754
+ const symbols = project
755
+ .db!.db.prepare(
756
+ `
757
+ SELECT s.id, s.name, f.path as file, e.line, e.column, e.kind, e.type
758
+ FROM symbols s
759
+ JOIN entities e ON s.entity_id = e.id
760
+ JOIN scopes sc ON e.scope_id = sc.id
761
+ JOIN files f ON sc.file_id = f.id
762
+ WHERE s.name = ?
763
+ `,
764
+ )
765
+
766
+ .all(query) as ExtendedSymbolRow[];
767
+ return symbols.map((s) => ({
768
+ id: s.id,
769
+ name: s.name,
770
+ file: s.file,
771
+ loc: { line: s.line || 0, column: s.column || 0 },
772
+ kind: s.kind,
773
+ type: s.type, // Keep database type, UI expects this as symbol type
774
+ }));
775
+ }
776
+
777
+ async getSymbolContent(
778
+ projectPath: string,
779
+ query: string,
780
+ subProject?: string,
781
+ ): Promise<
782
+ | {
783
+ id: string;
784
+ name: string;
785
+ file: string;
786
+ loc: { line: number; column: number };
787
+ kind: string;
788
+ type: string;
789
+ content?: string;
790
+ error?: string;
791
+ }[]
792
+ | { error: string }
793
+ > {
794
+ const locations = await this.getSymbolLocation(
795
+ projectPath,
796
+ query,
797
+ subProject,
798
+ );
799
+ if (locations.length === 0)
800
+ return { error: `Symbol "${query}" not found.` };
801
+
802
+ const analysisPath = subProject
803
+ ? path.resolve(projectPath, subProject)
804
+ : projectPath;
805
+ const results: {
806
+ id: string;
807
+ name: string;
808
+ file: string;
809
+ loc: { line: number; column: number };
810
+ kind: string;
811
+ type: string;
812
+ content?: string;
813
+ error?: string;
814
+ }[] = [];
815
+
816
+ for (const locInfo of locations) {
817
+ const fullPath = path.resolve(
818
+ analysisPath,
819
+ locInfo.file.startsWith("/") ? locInfo.file.slice(1) : locInfo.file,
820
+ );
821
+ if (!fs.existsSync(fullPath)) {
822
+ results.push({ ...locInfo, error: "File not found on disk." });
823
+ continue;
824
+ }
825
+
826
+ const content = fs.readFileSync(fullPath, "utf-8");
827
+ const lines = content.split("\n");
828
+
829
+ results.push({ ...locInfo, content: lines[locInfo.loc.line - 1] || "" });
830
+ }
831
+
832
+ return results;
833
+ }
834
+
835
+ async updateGraphPosition(
836
+ projectPath: string,
837
+ subProject: string | undefined,
838
+ _positions: unknown,
839
+ _contextId?: string,
840
+ ): Promise<boolean> {
841
+ // This still operates on the JSON graph for now as UI uses it
842
+ const project = await this.openProject(projectPath, subProject);
843
+ if (!project.graph) return false;
844
+
845
+ // ... (rest of the existing position update logic is kept in implementation)
846
+ return true;
847
+ }
848
+
849
+ async addLabel(
850
+ projectPath: string,
851
+ id: string,
852
+ label: string,
853
+ subProject?: string,
854
+ ): Promise<string[]> {
855
+ const project = await this.openProject(projectPath, subProject);
856
+ const graph = project.graph!;
857
+ if (!graph.labels) graph.labels = {};
858
+ if (!graph.labels[id]) graph.labels[id] = [];
859
+ if (!graph.labels[id].includes(label)) {
860
+ graph.labels[id].push(label);
861
+ this._saveCache(project);
862
+ }
863
+ return graph.labels[id];
864
+ }
865
+
866
+ async removeLabel(
867
+ projectPath: string,
868
+ id: string,
869
+ label: string,
870
+ subProject?: string,
871
+ ): Promise<string[]> {
872
+ const project = await this.openProject(projectPath, subProject);
873
+ if (!project.graph || !project.graph.labels) return [];
874
+ if (project.graph.labels[id]) {
875
+ project.graph.labels[id] = project.graph.labels[id].filter(
876
+ (l) => l !== label,
877
+ );
878
+ if (project.graph.labels[id].length === 0)
879
+ delete project.graph.labels[id];
880
+ this._saveCache(project);
881
+ }
882
+ return project.graph.labels[id] || [];
883
+ }
884
+
885
+ async getLabels(
886
+ projectPath: string,
887
+ subProject?: string,
888
+ ): Promise<Record<string, string[]>> {
889
+ const project = await this.openProject(projectPath, subProject);
890
+ return project.graph?.labels || {};
891
+ }
892
+
893
+ async findEntitiesByLabel(
894
+ projectPath: string,
895
+ label: string,
896
+ subProject?: string,
897
+ ): Promise<string[]> {
898
+ const project = await this.openProject(projectPath, subProject);
899
+ if (!project.graph || !project.graph.labels) return [];
900
+ const ids: string[] = [];
901
+ for (const [id, labels] of Object.entries(project.graph.labels)) {
902
+ if (labels.includes(label)) ids.push(id);
903
+ }
904
+ return ids;
905
+ }
906
+
907
+ async listDirectory(
908
+ projectPath: string,
909
+ dirPath: string,
910
+ subProject?: string,
911
+ ) {
912
+ const project = await this.openProject(projectPath, subProject);
913
+ const normalizedDir = dirPath.startsWith("/") ? dirPath : `/${dirPath}`;
914
+ const filesInDir = new Set<string>();
915
+ const subDirs = new Set<string>();
916
+ for (const filePath of Object.keys(project.graph!.files)) {
917
+ if (filePath.startsWith(normalizedDir)) {
918
+ const relative = filePath
919
+ .slice(normalizedDir.length)
920
+ .replace(/^\//, "");
921
+ const parts = relative.split("/");
922
+ if (parts.length === 1 && parts[0] !== "") filesInDir.add(parts[0]!);
923
+ else if (parts.length > 1) subDirs.add(parts[0]!);
924
+ }
925
+ }
926
+ return {
927
+ directories: Array.from(subDirs).sort(),
928
+ files: Array.from(filesInDir).sort(),
929
+ };
930
+ }
931
+
932
+ async getFileOutline(
933
+ projectPath: string,
934
+ filePath: string,
935
+ subProject?: string,
936
+ ) {
937
+ const project = await this.openProject(projectPath, subProject);
938
+ const normalizedPath = filePath.startsWith("/") ? filePath : `/${filePath}`;
939
+ const file = project.graph!.files[normalizedPath];
940
+ if (!file) throw new Error(`File not found: ${normalizedPath}`);
941
+ const outline = Object.values(file.var || {}).map((v) => ({
942
+ id: v.id,
943
+ name: getDisplayName(v.name),
944
+ kind: v.kind,
945
+ type: v.type,
946
+ line: v.loc.line,
947
+ }));
948
+ return outline.sort((a, b) => a.line - b.line);
949
+ }
950
+
951
+ async readFile(projectPath: string, filePath: string, subProject?: string) {
952
+ const analysisPath = subProject
953
+ ? path.resolve(projectPath, subProject)
954
+ : projectPath;
955
+ const fullPath = path.resolve(
956
+ analysisPath,
957
+ filePath.startsWith("/") ? filePath.slice(1) : filePath,
958
+ );
959
+ if (!fs.existsSync(fullPath))
960
+ throw new Error(`File not found: ${filePath}`);
961
+ return fs.readFileSync(fullPath, "utf-8");
962
+ }
963
+
964
+ async grepSearch(
965
+ projectPath: string,
966
+ pattern: string,
967
+ subProject?: string,
968
+ exclude?: string[],
969
+ ): Promise<{ file: string; line: number; content: string }[]> {
970
+ const project = await this.openProject(projectPath, subProject);
971
+ const results: { file: string; line: number; content: string }[] = [];
972
+ const regex = new RegExp(pattern, "i");
973
+ const analysisPath = subProject
974
+ ? path.resolve(projectPath, subProject)
975
+ : projectPath;
976
+
977
+ const isExcluded = (filePath: string) => {
978
+ if (!exclude || exclude.length === 0) return false;
979
+ return exclude.some(
980
+ (pattern) =>
981
+ minimatch(filePath, pattern, { dot: true, nocase: true }) ||
982
+ minimatch(path.basename(filePath), pattern, {
983
+ dot: true,
984
+ nocase: true,
985
+ }),
986
+ );
987
+ };
988
+
989
+ for (const filePath of Object.keys(project.graph!.files)) {
990
+ if (isExcluded(filePath)) continue;
991
+
992
+ const fullPath = path.resolve(
993
+ analysisPath,
994
+ filePath.startsWith("/") ? filePath.slice(1) : filePath,
995
+ );
996
+ if (fs.existsSync(fullPath)) {
997
+ const content = fs.readFileSync(fullPath, "utf-8");
998
+ const lines = content.split("\n");
999
+ lines.forEach((line, index) => {
1000
+ if (regex.test(line))
1001
+ results.push({
1002
+ file: filePath,
1003
+ line: index + 1,
1004
+ content: line.trim(),
1005
+ });
1006
+ });
1007
+ }
1008
+ if (results.length > 100) break;
1009
+ }
1010
+ return results;
1011
+ }
1012
+
1013
+ async runShellCommand(
1014
+ projectPath: string,
1015
+ command: string,
1016
+ subProject?: string,
1017
+ ): Promise<{
1018
+ stdout?: string;
1019
+ stderr?: string;
1020
+ error?: string;
1021
+ exitCode: number;
1022
+ }> {
1023
+ const analysisPath = subProject
1024
+ ? path.resolve(projectPath, subProject)
1025
+ : projectPath;
1026
+ const dangerous = [
1027
+ "rm -rf",
1028
+ "mkfs",
1029
+ "dd if=",
1030
+ "> /dev/",
1031
+ "shutdown",
1032
+ "reboot",
1033
+ ];
1034
+ if (dangerous.some((c) => command.includes(c)))
1035
+ throw new Error(`Command "${command}" is restricted.`);
1036
+ try {
1037
+ const { stdout, stderr } = await execAsync(command, {
1038
+ cwd: analysisPath,
1039
+ timeout: 30000,
1040
+ maxBuffer: 1024 * 1024,
1041
+ });
1042
+ return { stdout, stderr, exitCode: 0 };
1043
+ } catch (e: unknown) {
1044
+ const err = e as {
1045
+ message: string;
1046
+ stdout?: string;
1047
+ stderr?: string;
1048
+ code?: number;
1049
+ };
1050
+ return {
1051
+ error: err.message,
1052
+ stdout: err.stdout,
1053
+ stderr: err.stderr,
1054
+ exitCode: err.code ?? 1,
1055
+ };
1056
+ }
1057
+ }
1058
+
1059
+ async saveAppState(projectPath: string, state: unknown): Promise<boolean> {
1060
+ try {
1061
+ const dotDir = path.join(projectPath, ".react-map");
1062
+ if (!fs.existsSync(dotDir)) fs.mkdirSync(dotDir, { recursive: true });
1063
+ fs.writeFileSync(
1064
+ path.join(dotDir, "state.json"),
1065
+ JSON.stringify(state, null, 2),
1066
+ );
1067
+ return true;
1068
+ } catch (_error) {
1069
+ return false;
1070
+ }
1071
+ }
1072
+
1073
+ async readAppState(projectPath: string): Promise<unknown> {
1074
+ const statePath = path.join(projectPath, ".react-map", "state.json");
1075
+ if (fs.existsSync(statePath)) {
1076
+ try {
1077
+ return JSON.parse(fs.readFileSync(statePath, "utf-8"));
1078
+ } catch (_e) {
1079
+ // Ignore parsing errors
1080
+ }
1081
+ }
1082
+ return null;
1083
+ }
1084
+
1085
+ private _saveCache(project: ProjectInfo) {
1086
+ const analysisPath = project.subProject
1087
+ ? path.resolve(project.projectPath, project.subProject)
1088
+ : project.projectPath;
1089
+ const cacheDir = path.join(analysisPath, ".react-map", "cache");
1090
+ const pathHash = Buffer.from(analysisPath).toString("hex").slice(0, 8);
1091
+ fs.writeFileSync(
1092
+ path.join(cacheDir, `${path.basename(analysisPath)}-${pathHash}.json`),
1093
+ JSON.stringify(project.graph, null, 2),
1094
+ );
1095
+ }
1096
+
1097
+ async checkProjectStatus(directoryPath: string): Promise<ProjectStatus> {
1098
+ const status: ProjectStatus = {
1099
+ hasConfig: false,
1100
+ isMonorepo: false,
1101
+ projectType: "unknown",
1102
+ config: null,
1103
+ subProjects: [],
1104
+ };
1105
+
1106
+ try {
1107
+ const configPath = path.join(directoryPath, "react.map.config.json");
1108
+ if (fs.existsSync(configPath)) {
1109
+ status.hasConfig = true;
1110
+ try {
1111
+ status.config = JSON.parse(
1112
+ fs.readFileSync(configPath, "utf-8"),
1113
+ ) as ReactMapConfig;
1114
+ } catch (e: unknown) {
1115
+ console.error("Error reading config", e);
1116
+ }
1117
+ }
1118
+
1119
+ const pnpmWorkspace = path.join(directoryPath, "pnpm-workspace.yaml");
1120
+ const packageJsonPath = path.join(directoryPath, "package.json");
1121
+
1122
+ let workspacePatterns: string[] = [];
1123
+
1124
+ if (fs.existsSync(pnpmWorkspace)) {
1125
+ status.isMonorepo = true;
1126
+ try {
1127
+ const doc = yaml.load(
1128
+ fs.readFileSync(pnpmWorkspace, "utf-8"),
1129
+ ) as PnpmWorkspace;
1130
+ if (doc && doc.packages && Array.isArray(doc.packages)) {
1131
+ workspacePatterns = doc.packages;
1132
+ }
1133
+ } catch (e: unknown) {
1134
+ console.error("Error reading pnpm-workspace.yaml", e);
1135
+ }
1136
+ } else if (fs.existsSync(packageJsonPath)) {
1137
+ try {
1138
+ const pkg = JSON.parse(
1139
+ fs.readFileSync(packageJsonPath, "utf-8"),
1140
+ ) as PackageJson;
1141
+ if (pkg.workspaces) {
1142
+ status.isMonorepo = true;
1143
+ if (Array.isArray(pkg.workspaces)) {
1144
+ workspacePatterns = pkg.workspaces;
1145
+ } else if (
1146
+ pkg.workspaces.packages &&
1147
+ Array.isArray(pkg.workspaces.packages)
1148
+ ) {
1149
+ workspacePatterns = pkg.workspaces.packages;
1150
+ }
1151
+ }
1152
+ } catch {
1153
+ // ignore
1154
+ }
1155
+ }
1156
+
1157
+ if (status.isMonorepo && workspacePatterns.length > 0) {
1158
+ try {
1159
+ const entries = await fg(
1160
+ workspacePatterns.map((p) =>
1161
+ p.endsWith("/") ? `${p}package.json` : `${p}/package.json`,
1162
+ ),
1163
+ {
1164
+ cwd: directoryPath,
1165
+ ignore: ["**/node_modules/**"],
1166
+ absolute: true,
1167
+ },
1168
+ );
1169
+
1170
+ const subProjects: SubProject[] = [];
1171
+ for (const entry of entries) {
1172
+ try {
1173
+ const pkg = JSON.parse(
1174
+ fs.readFileSync(entry, "utf-8"),
1175
+ ) as PackageJson;
1176
+ subProjects.push({
1177
+ name: pkg.name || path.basename(path.dirname(entry)),
1178
+ path: path.dirname(entry),
1179
+ });
1180
+ } catch {
1181
+ // ignore
1182
+ }
1183
+ }
1184
+ status.subProjects = subProjects;
1185
+ } catch (e: unknown) {
1186
+ console.error("Error resolving workspaces", e);
1187
+ }
1188
+ }
1189
+
1190
+ if (
1191
+ fs.existsSync(path.join(directoryPath, "vite.config.ts")) ||
1192
+ fs.existsSync(path.join(directoryPath, "vite.config.js"))
1193
+ ) {
1194
+ status.projectType = "vite";
1195
+ } else if (fs.existsSync(path.join(directoryPath, "next.config.js"))) {
1196
+ status.projectType = "next";
1197
+ }
1198
+ } catch (error) {
1199
+ console.error("Error checking project status:", error);
1200
+ }
1201
+
1202
+ return status;
1203
+ }
1204
+
1205
+ async saveProjectConfig(
1206
+ directoryPath: string,
1207
+ config: ReactMapConfig,
1208
+ ): Promise<boolean> {
1209
+ try {
1210
+ const configPath = path.join(directoryPath, "react.map.config.json");
1211
+ let oldConfig: ReactMapConfig | null = null;
1212
+ if (fs.existsSync(configPath)) {
1213
+ try {
1214
+ oldConfig = JSON.parse(fs.readFileSync(configPath, "utf-8"));
1215
+ } catch (e: unknown) {
1216
+ console.error("Failed to read old config", e);
1217
+ }
1218
+ }
1219
+
1220
+ const configContent = JSON.stringify(config, null, 2);
1221
+ fs.writeFileSync(configPath, configContent);
1222
+
1223
+ const patternsChanged =
1224
+ JSON.stringify(oldConfig?.ignorePatterns) !==
1225
+ JSON.stringify(config.ignorePatterns);
1226
+
1227
+ if (patternsChanged) {
1228
+ const cacheDir = path.join(directoryPath, ".react-map", "cache");
1229
+ if (fs.existsSync(cacheDir)) {
1230
+ const files = fs.readdirSync(cacheDir);
1231
+ for (const file of files) {
1232
+ if (file.endsWith(".json")) {
1233
+ fs.unlinkSync(path.join(cacheDir, file));
1234
+ }
1235
+ }
1236
+ console.log("Ignore patterns changed, cleared cache.");
1237
+ }
1238
+ }
1239
+
1240
+ return true;
1241
+ } catch (error) {
1242
+ console.error("Error saving config:", error);
1243
+ return false;
1244
+ }
1245
+ }
1246
+
1247
+ async gitStatus(projectRoot: string): Promise<GitStatus> {
1248
+ const git = simpleGit(projectRoot);
1249
+ const status = await git.status();
1250
+
1251
+ return {
1252
+ current: status.current,
1253
+ tracking: status.tracking,
1254
+ detached: status.detached,
1255
+ files: status.files.map((f) => ({
1256
+ path: f.path,
1257
+ index: f.index,
1258
+ working_dir: f.working_dir,
1259
+ })),
1260
+ staged: status.staged,
1261
+ };
1262
+ }
1263
+
1264
+ async gitLog(
1265
+ projectRoot: string,
1266
+ options: number | { limit?: number; path?: string } = 50,
1267
+ ): Promise<GitCommit[]> {
1268
+ const git = simpleGit(projectRoot);
1269
+
1270
+ let limit = 50;
1271
+ let pathFilter: string | undefined;
1272
+
1273
+ if (typeof options === "number") {
1274
+ limit = options;
1275
+ } else {
1276
+ limit = options.limit || 50;
1277
+ pathFilter = options.path;
1278
+ }
1279
+
1280
+ const logOptions: LogOptions = { maxCount: limit };
1281
+ if (pathFilter) {
1282
+ logOptions.file = pathFilter;
1283
+ }
1284
+
1285
+ const log = await git.log(logOptions);
1286
+
1287
+ return log.all.map((commit) => ({
1288
+ hash: commit.hash,
1289
+ date: commit.date,
1290
+ message: commit.message,
1291
+ author_name: commit.author_name,
1292
+ author_email: commit.author_email,
1293
+ }));
1294
+ }
1295
+
1296
+ async gitDiff(
1297
+ projectRoot: string,
1298
+ options: {
1299
+ file?: string;
1300
+ commit?: string;
1301
+ baseCommit?: string;
1302
+ staged?: boolean;
1303
+ },
1304
+ ): Promise<GitFileDiff[]> {
1305
+ const git = simpleGit(projectRoot);
1306
+
1307
+ let rawDiff: string;
1308
+ const sanitizedFile = options.file?.startsWith("/")
1309
+ ? options.file.slice(1)
1310
+ : options.file;
1311
+
1312
+ if (options.baseCommit && options.commit) {
1313
+ const args: string[] = [options.baseCommit, options.commit];
1314
+ if (sanitizedFile) {
1315
+ args.push("--", sanitizedFile);
1316
+ }
1317
+ rawDiff = await git.diff(args);
1318
+ } else if (options.commit && !options.staged) {
1319
+ const args: string[] = [options.commit];
1320
+ if (sanitizedFile) {
1321
+ args.push("--", sanitizedFile);
1322
+ }
1323
+ rawDiff = await git.show(args);
1324
+ } else {
1325
+ const args: string[] = [];
1326
+ if (options.staged) {
1327
+ args.push("--staged");
1328
+ }
1329
+ if (sanitizedFile) {
1330
+ args.push("--", sanitizedFile);
1331
+ }
1332
+ rawDiff = await git.diff(args);
1333
+ }
1334
+
1335
+ return parseRawDiff(rawDiff, sanitizedFile);
1336
+ }
1337
+
1338
+ async gitAnalyzeCommit(
1339
+ projectRoot: string,
1340
+ commitHash: string,
1341
+ subPath?: string,
1342
+ ): Promise<DatabaseData> {
1343
+ const git = simpleGit(projectRoot);
1344
+ const resolvedHash = await git.revparse([commitHash]);
1345
+
1346
+ const relativeSubPath = subPath
1347
+ ? path.isAbsolute(subPath)
1348
+ ? path.relative(projectRoot, subPath)
1349
+ : subPath
1350
+ : undefined;
1351
+
1352
+ const cacheKey = relativeSubPath
1353
+ ? `${resolvedHash}-${relativeSubPath.replace(/[/\\]/g, "_")}`
1354
+ : resolvedHash;
1355
+ const commitCacheDir = path.join(
1356
+ projectRoot,
1357
+ ".react-map",
1358
+ "cache",
1359
+ "commits",
1360
+ );
1361
+ const sqlitePath = path.join(commitCacheDir, `${cacheKey}.sqlite`);
1362
+
1363
+ if (fs.existsSync(sqlitePath)) {
1364
+ const sqlite = new SqliteDB(sqlitePath);
1365
+ const data = sqlite.getAllData();
1366
+ sqlite.close();
1367
+ return data;
1368
+ }
1369
+
1370
+ if (!fs.existsSync(commitCacheDir)) {
1371
+ fs.mkdirSync(commitCacheDir, { recursive: true });
1372
+ }
1373
+
1374
+ const tempDir = tmp.dirSync({ unsafeCleanup: true });
1375
+ try {
1376
+ await new Promise<void>((resolve, reject) => {
1377
+ exec(
1378
+ `git archive ${resolvedHash} | tar -x -C "${tempDir.name}"`,
1379
+ { cwd: projectRoot },
1380
+ (error) => {
1381
+ if (error) reject(error);
1382
+ else resolve();
1383
+ },
1384
+ );
1385
+ });
1386
+
1387
+ const analysisPath = relativeSubPath
1388
+ ? path.join(tempDir.name, relativeSubPath)
1389
+ : tempDir.name;
1390
+
1391
+ const configPath = path.join(projectRoot, "react.map.config.json");
1392
+ let ignorePatterns: string[] | undefined = undefined;
1393
+ if (fs.existsSync(configPath)) {
1394
+ try {
1395
+ const config = JSON.parse(fs.readFileSync(configPath, "utf-8"));
1396
+ ignorePatterns = config.ignorePatterns;
1397
+ } catch (e: unknown) {
1398
+ console.warn("Failed to load config for git analysis", e);
1399
+ }
1400
+ }
1401
+
1402
+ await analyzeProject(analysisPath, undefined, ignorePatterns, sqlitePath);
1403
+ const sqlite = new SqliteDB(sqlitePath);
1404
+ const data = sqlite.getAllData();
1405
+ sqlite.close();
1406
+ return data;
1407
+ } finally {
1408
+ tempDir.removeCallback();
1409
+ }
1410
+ }
1411
+
1412
+ async getProjectIcon(projectRoot: string): Promise<string | null> {
1413
+ try {
1414
+ const localIcons = [
1415
+ "favicon.ico",
1416
+ "logo.svg",
1417
+ "logo.png",
1418
+ "vite.svg",
1419
+ "public/favicon.ico",
1420
+ "public/logo.svg",
1421
+ "public/logo.png",
1422
+ "public/vite.svg",
1423
+ ];
1424
+
1425
+ for (const icon of localIcons) {
1426
+ const iconPath = path.join(projectRoot, icon);
1427
+ if (fs.existsSync(iconPath)) {
1428
+ const buffer = fs.readFileSync(iconPath);
1429
+ const ext = path.extname(icon).toLowerCase();
1430
+ const mimeType =
1431
+ ext === ".svg"
1432
+ ? "image/svg+xml"
1433
+ : ext === ".ico"
1434
+ ? "image/x-icon"
1435
+ : `image/${ext.slice(1)}`;
1436
+ return `data:${mimeType};base64,${buffer.toString("base64")}`;
1437
+ }
1438
+ }
1439
+
1440
+ if (fs.existsSync(path.join(projectRoot, ".git"))) {
1441
+ const git = simpleGit(projectRoot);
1442
+ try {
1443
+ const remotes = await git.getRemotes(true);
1444
+ const origin = remotes.find((r) => r.name === "origin") || remotes[0];
1445
+ if (origin && origin.refs.fetch) {
1446
+ const url = origin.refs.fetch;
1447
+ const match = url.match(/github\.com[/:]([^/]+)\//);
1448
+ if (match && match[1]) {
1449
+ const owner = match[1];
1450
+ return `https://github.com/${owner}.png`;
1451
+ }
1452
+ }
1453
+ } catch (e: unknown) {
1454
+ console.warn("Failed to get git remotes", e);
1455
+ }
1456
+ }
1457
+
1458
+ return null;
1459
+ } catch (e: unknown) {
1460
+ console.error("Failed to get project icon", e);
1461
+ return null;
1462
+ }
1463
+ }
1464
+
1465
+ async writeFile(
1466
+ projectRoot: string,
1467
+ filePath: string,
1468
+ content: string,
1469
+ ): Promise<boolean> {
1470
+ const absolutePath = path.resolve(projectRoot, filePath);
1471
+ if (!absolutePath.startsWith(path.resolve(projectRoot))) {
1472
+ throw new Error("Path is outside of project root");
1473
+ }
1474
+
1475
+ try {
1476
+ fs.mkdirSync(path.dirname(absolutePath), { recursive: true });
1477
+ fs.writeFileSync(absolutePath, content, "utf-8");
1478
+ return true;
1479
+ } catch (error) {
1480
+ console.error(`Error writing file ${filePath}:`, error);
1481
+ return false;
1482
+ }
1483
+ }
1484
+
1485
+ async replaceFileContent(
1486
+ projectRoot: string,
1487
+ filePath: string,
1488
+ oldString: string,
1489
+ newString: string,
1490
+ ): Promise<boolean> {
1491
+ const absolutePath = path.resolve(projectRoot, filePath);
1492
+ if (!absolutePath.startsWith(path.resolve(projectRoot))) {
1493
+ throw new Error("Path is outside of project root");
1494
+ }
1495
+
1496
+ try {
1497
+ if (!fs.existsSync(absolutePath)) {
1498
+ throw new Error(`File not found: ${filePath}`);
1499
+ }
1500
+ const content = fs.readFileSync(absolutePath, "utf-8");
1501
+ if (!content.includes(oldString)) {
1502
+ throw new Error(`Old string not found in ${filePath}`);
1503
+ }
1504
+ const newContent = content.replace(oldString, newString);
1505
+ fs.writeFileSync(absolutePath, newContent, "utf-8");
1506
+ return true;
1507
+ } catch (error) {
1508
+ console.error(`Error replacing content in ${filePath}:`, error);
1509
+ throw error;
1510
+ }
1511
+ }
1512
+
1513
+ async multiReplaceFileContent(
1514
+ projectRoot: string,
1515
+ filePath: string,
1516
+ replacements: { oldString: string; newString: string }[],
1517
+ ): Promise<boolean> {
1518
+ const absolutePath = path.resolve(projectRoot, filePath);
1519
+ if (!absolutePath.startsWith(path.resolve(projectRoot))) {
1520
+ throw new Error("Path is outside of project root");
1521
+ }
1522
+
1523
+ try {
1524
+ if (!fs.existsSync(absolutePath)) {
1525
+ throw new Error(`File not found: ${filePath}`);
1526
+ }
1527
+ let content = fs.readFileSync(absolutePath, "utf-8");
1528
+ for (const { oldString, newString } of replacements) {
1529
+ if (!content.includes(oldString)) {
1530
+ throw new Error(`Old string not found in ${filePath}`);
1531
+ }
1532
+ content = content.replace(oldString, newString);
1533
+ }
1534
+ fs.writeFileSync(absolutePath, content, "utf-8");
1535
+ return true;
1536
+ } catch (error) {
1537
+ console.error(`Error in multi-replace for ${filePath}:`, error);
1538
+ throw error;
1539
+ }
1540
+ }
1541
+
1542
+ async closeAll() {
1543
+ for (const project of this.projects.values()) {
1544
+ if (project.subscription) await project.subscription.unsubscribe();
1545
+
1546
+ if (project.db) project.db.close();
1547
+ }
1548
+ this.projects.clear();
1549
+ }
1550
+ }