diff --git a/src/exporters/jsonExporter.ts b/src/exporters/jsonExporter.ts new file mode 100644 index 0000000..a071982 --- /dev/null +++ b/src/exporters/jsonExporter.ts @@ -0,0 +1,81 @@ +import * as fs from 'fs'; +import { DependencyGraph, GraphNode, GraphEdge, GraphCluster, ExportOptions } from '../types'; + +export class JSONExporter { + private graph: DependencyGraph; + private options: Required; + + constructor(graph: DependencyGraph, options: ExportOptions) { + this.graph = graph; + this.options = { + format: options.format, + outputPath: options.outputPath, + includeMetadata: options.includeMetadata ?? false, + layout: options.layout ?? 'dot', + rankDir: options.rankDir ?? 'TB' + }; + } + + export(): string { + const output: Record = { + graph: { + nodes: this.graph.nodes.size, + edges: this.graph.edges.length, + clusters: this.graph.clusters.length + }, + nodes: Array.from(this.graph.nodes.values()).map((node) => this.serializeNode(node)), + edges: this.graph.edges.map((edge) => this.serializeEdge(edge)) + }; + + if (this.options.includeMetadata) { + output.metadata = this.graph.metadata; + } + + if (this.graph.clusters.length > 0) { + output.clusters = this.graph.clusters.map((cluster) => this.serializeCluster(cluster)); + } + + return JSON.stringify(output, null, 2); + } + + private serializeNode(node: GraphNode): Record { + return { + id: node.id, + label: node.label, + kind: node.kind, + filePath: node.filePath, + lineNumber: node.lineNumber, + dependencies: node.dependencies, + metadata: node.metadata + }; + } + + private serializeEdge(edge: GraphEdge): Record { + return { + source: edge.source, + target: edge.target, + label: edge.label, + style: edge.style, + weight: edge.weight + }; + } + + private serializeCluster(cluster: GraphCluster): Record { + return { + id: cluster.id, + label: cluster.label, + nodeIds: cluster.nodeIds, + style: cluster.style + }; + } + + toFile(): void { + const content = this.export(); + fs.writeFileSync(this.options.outputPath, content, 'utf-8'); + } +} + +export function exportToJSON(graph: DependencyGraph, options: ExportOptions): string { + const exporter = new JSONExporter(graph, options); + return exporter.export(); +}