deeplyzer 0.0.0-stage → 0.1.0

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,269 @@
1
+ const FileUtil = require('../utils/fileUtil');
2
+ const IdUtil = require('../utils/idUtil');
3
+ const LLM = require("../llm/llm");
4
+ const PromptsUtil = require('../utils/promptsUtil');
5
+ const path = require("path");
6
+
7
+ class GraphService {
8
+ constructor(config) {
9
+ this.config = config;
10
+ this.fileUtil = new FileUtil();
11
+ this.llm = new LLM(config.llm);
12
+ this.graphs = [];
13
+
14
+ this.batchSize = config.batch_size ?? 10;
15
+ }
16
+
17
+ async buildGraphs() {
18
+ console.log("Building nodes is in-progress");
19
+ await this._buildNodes();
20
+
21
+ console.log("Connecting edges");
22
+ await this._buildExternalEdges();
23
+ }
24
+
25
+ async loadGraphs() {
26
+ this.graphs = [];
27
+ this.sources = [];
28
+
29
+ const graphFiles = this.fileUtil.readPaths([
30
+ path.join(this.fileUtil.baseDir, "graph")
31
+ ]);
32
+
33
+ for (const file of graphFiles) {
34
+ if (!file.filename.endsWith(".json")) continue;
35
+
36
+ const data = this.fileUtil.loadJSON(
37
+ path.join("graph", file.filename)
38
+ );
39
+
40
+ if (!data?.file || !data?.graph) continue;
41
+
42
+ this.graphs.push({
43
+ graphPath: path.join("graph", file.filename),
44
+ file: data.file,
45
+ graph: data.graph
46
+ });
47
+
48
+ this.sources.push(data.file);
49
+ }
50
+
51
+ return this.graphs;
52
+ }
53
+
54
+ async _buildNodes() {
55
+ const sourceFiles = this.config.sources;
56
+ const exclusions = this.config["source-exclusions"];
57
+
58
+ this.sources = this.fileUtil.readPaths(sourceFiles, exclusions);
59
+
60
+ for (let i = 0; i < this.sources.length; i += this.batchSize) {
61
+ const batch = this.sources.slice(i, i + this.batchSize);
62
+
63
+ const results = await Promise.all(
64
+ batch.map(async (source) => {
65
+ let prompt = PromptsUtil.read("build_nodes");
66
+
67
+ prompt = prompt.replaceAll(
68
+ "***CONTENT***",
69
+ JSON.stringify(source.content)
70
+ );
71
+
72
+ prompt = prompt.replaceAll(
73
+ "ID-PREFIX",
74
+ IdUtil.generate()
75
+ );
76
+
77
+ const response = await this.llm.generate({ prompt: prompt });
78
+
79
+ const graph = JSON.parse(response.text);
80
+ const graphPath = `./graph/${IdUtil.generate()}.json`;
81
+
82
+ this.fileUtil.saveJSON(graphPath, {
83
+ file: source,
84
+ graph
85
+ });
86
+
87
+ return {
88
+ graphPath,
89
+ file: source,
90
+ graph
91
+ };
92
+ })
93
+ );
94
+
95
+ this.graphs.push(...results);
96
+ }
97
+ }
98
+
99
+ async _buildExternalEdges() {
100
+ for (let i = 0; i < this.graphs.length; i += this.batchSize) {
101
+ const batch = this.graphs.slice(i, i + this.batchSize);
102
+
103
+ await Promise.all(
104
+ batch.map(async (sourceGraph) => {
105
+ const sourceFile = sourceGraph.file.path;
106
+
107
+ for (const node of sourceGraph.graph.nodes) {
108
+ const patterns = node.external_dependants || [];
109
+
110
+ if (!patterns.length) continue;
111
+
112
+ const matches = this._searchSources(patterns, sourceFile);
113
+
114
+ for (const match of matches) {
115
+ const candidates = this._findCandidateNodes(match);
116
+
117
+ if (!candidates.length) continue;
118
+
119
+ const sourceNode = {
120
+ id: node.id,
121
+ source: this._getNodeSource(sourceFile, node)
122
+ };
123
+
124
+ const candidateData = candidates.map(candidate => ({
125
+ id: candidate.id,
126
+ source: this._getNodeSource(candidate.file, candidate)
127
+ }));
128
+
129
+ let prompt = PromptsUtil.read("resolve_edges");
130
+
131
+ prompt = prompt.replaceAll(
132
+ "***SOURCE_NODE***",
133
+ JSON.stringify(sourceNode, null, 2)
134
+ );
135
+
136
+ prompt = prompt.replaceAll(
137
+ "***CANDIDATES***",
138
+ JSON.stringify(candidateData, null, 2)
139
+ );
140
+
141
+ const response = await this.llm.generate({ prompt: prompt });
142
+
143
+ let result;
144
+
145
+ try {
146
+ result = JSON.parse(response.text);
147
+ } catch {
148
+ continue;
149
+ }
150
+
151
+ if (!result?.selectedNodeId) continue;
152
+
153
+ const selected = candidates.find(
154
+ candidate => candidate.id === result.selectedNodeId
155
+ );
156
+
157
+ if (!selected) continue;
158
+
159
+ const exists = sourceGraph.graph.edges.some(
160
+ edge =>
161
+ edge.node1 === node.id &&
162
+ edge.node2 === selected.id
163
+ );
164
+
165
+ if (exists) continue;
166
+
167
+ sourceGraph.graph.edges.push({
168
+ node1: node.id,
169
+ node2: selected.id
170
+ });
171
+ }
172
+ }
173
+
174
+ this.fileUtil.saveJSON(sourceGraph.graphPath, {
175
+ file: sourceGraph.file,
176
+ graph: sourceGraph.graph
177
+ });
178
+ })
179
+ );
180
+ }
181
+ }
182
+
183
+ _getNodeSource(filePath, node) {
184
+ const source = this.sources.find(
185
+ item => item.path === filePath
186
+ );
187
+
188
+ if (!source) return "";
189
+
190
+ return source.content
191
+ .split(/\r?\n/)
192
+ .slice(node.startLine - 1, node.endLine)
193
+ .join("\n");
194
+ }
195
+
196
+ _searchSources(patterns, sourceFile) {
197
+ const matches = [];
198
+
199
+ for (const source of this.sources) {
200
+
201
+ // Never search the current source file
202
+ if (source.path === sourceFile) continue;
203
+
204
+ const lines = source.content.split(/\r?\n/);
205
+
206
+ for (let i = 0; i < lines.length; i++) {
207
+ for (const pattern of patterns) {
208
+ const regex = new RegExp(pattern, "g");
209
+ let match;
210
+
211
+ while ((match = regex.exec(lines[i])) !== null) {
212
+ matches.push({
213
+ file: source.path,
214
+ line: i + 1,
215
+ matchedText: match[0],
216
+ sourceLine: lines[i].trim()
217
+ });
218
+
219
+ if (!match[0].length) regex.lastIndex++;
220
+ }
221
+ }
222
+ }
223
+ }
224
+
225
+ return [
226
+ ...new Map(
227
+ matches.map(match => [
228
+ `${match.file}:${match.line}:${match.matchedText}`,
229
+ match
230
+ ])
231
+ ).values()
232
+ ];
233
+ }
234
+
235
+ _findCandidateNodes(match) {
236
+ const candidates = [];
237
+
238
+ const source = this.sources.find(
239
+ item => item.path === match.file
240
+ );
241
+
242
+ if (!source) return candidates;
243
+
244
+ const lines = source.content.split(/\r?\n/);
245
+
246
+ for (const sourceGraph of this.graphs) {
247
+ if (sourceGraph.file.path !== match.file) continue;
248
+ for (const node of sourceGraph.graph.nodes) {
249
+ if (
250
+ match.line >= node.startLine &&
251
+ match.line <= node.endLine
252
+ ) {
253
+ candidates.push({
254
+ ...node,
255
+ file: sourceGraph.file.path,
256
+ nodeText: lines.slice(
257
+ node.startLine - 1,
258
+ node.endLine
259
+ ).join("\n")
260
+ });
261
+ }
262
+ }
263
+ }
264
+
265
+ return candidates;
266
+ }
267
+ }
268
+
269
+ module.exports = GraphService;
@@ -0,0 +1,84 @@
1
+ const FileUtil = require('../utils/fileUtil');
2
+ const LLM = require("../llm/llm");
3
+ const PromptsUtil = require('../utils/promptsUtil');
4
+
5
+ class StaticAnalyzerService {
6
+ constructor(config) {
7
+ this.config = config;
8
+ this.fileUtil = new FileUtil();
9
+ this.llm = new LLM(config.llm);
10
+ }
11
+
12
+ async analyze(graphs, workflows) {
13
+ const results = [];
14
+
15
+ for (const workflow of workflows) {
16
+ const source = this._getWorkflowSource(graphs, workflow);
17
+
18
+ if (!source.trim()) continue;
19
+
20
+ let prompt = PromptsUtil.read("static_analysis");
21
+ prompt = prompt.replaceAll("***SOURCE_CODE***", source);
22
+ console.log(prompt);
23
+ const response = await this.llm.generate({ prompt: prompt });
24
+
25
+ results.push({
26
+ workflow: workflow.node,
27
+ analysis: response
28
+ });
29
+ }
30
+
31
+ return results;
32
+ }
33
+
34
+ _getWorkflowSource(graphs, workflow) {
35
+ const nodeIds = new Set([
36
+ workflow.node,
37
+ ...(workflow.childNodes || [])
38
+ ]);
39
+
40
+ const sources = [];
41
+
42
+ for (const graph of graphs) {
43
+ const nodes = graph.graph?.nodes || [];
44
+
45
+ for (const node of nodes) {
46
+ if (!nodeIds.has(node.id)) continue;
47
+
48
+ const source = this._extractSource(graph, node);
49
+
50
+ if (!source) continue;
51
+
52
+ sources.push({
53
+ file: graph.file.path,
54
+ startLine: node.startLine,
55
+ endLine: node.endLine,
56
+ source
57
+ });
58
+ }
59
+ }
60
+
61
+ return sources.map(item => {
62
+ return `
63
+ /**
64
+ * File: ${item.file}
65
+ * Lines: ${item.startLine}-${item.endLine}
66
+ */
67
+
68
+ ${item.source}
69
+ `;
70
+ }).join("\n\n");
71
+ }
72
+
73
+ _extractSource(graph, node) {
74
+ if (!node.startLine || !node.endLine || !graph.file?.content) {
75
+ return "";
76
+ }
77
+
78
+ const lines = graph.file.content.split(/\r?\n/);
79
+
80
+ return lines.slice(node.startLine - 1, node.endLine).join("\n");
81
+ }
82
+ }
83
+
84
+ module.exports = StaticAnalyzerService;
@@ -0,0 +1,56 @@
1
+ class WorkflowService {
2
+
3
+ build(graphs = []) {
4
+ const functionNodeIds = new Set();
5
+
6
+ // Collect function node IDs across all graphs
7
+ for (const graph of graphs) {
8
+ const nodes = graph.graph?.nodes || [];
9
+
10
+ for (const node of nodes) {
11
+ if (node?.is_function === true) {
12
+ functionNodeIds.add(node.id);
13
+ }
14
+ }
15
+ }
16
+
17
+ // Initialize workflow entries for every function node
18
+ const workflowMap = new Map();
19
+
20
+ for (const nodeId of functionNodeIds) {
21
+ workflowMap.set(nodeId, {
22
+ node: nodeId,
23
+ childNodes: []
24
+ });
25
+ }
26
+
27
+ // Build connections from edges in both directions
28
+ for (const graph of graphs) {
29
+ const edges = graph.graph?.edges || [];
30
+
31
+ for (const edge of edges) {
32
+ const { node1, node2 } = edge;
33
+
34
+ if (!workflowMap.has(node1) || !workflowMap.has(node2)) {
35
+ continue;
36
+ }
37
+
38
+ this._addConnection(workflowMap, node1, node2);
39
+ this._addConnection(workflowMap, node2, node1);
40
+ }
41
+ }
42
+
43
+ return [...workflowMap.values()];
44
+ }
45
+
46
+ _addConnection(workflowMap, source, target) {
47
+ const childNodes = workflowMap.get(source).childNodes;
48
+
49
+ if (!childNodes.includes(target)) {
50
+ childNodes.push(target);
51
+ }
52
+ }
53
+
54
+ }
55
+
56
+ module.exports = WorkflowService;
@@ -0,0 +1,223 @@
1
+
2
+ const fs = require("fs");
3
+ const path = require("path");
4
+
5
+ class FileUtil {
6
+ constructor() {
7
+ this.baseDir = path.join(process.cwd(), ".deeplyzer");
8
+ this._ensureDirectory();
9
+ }
10
+
11
+ saveCodeFiles(files, outputDir) {
12
+ const root = path.resolve(this.baseDir, "src", outputDir);
13
+ const srcDir = path.resolve(this.baseDir, "src");
14
+
15
+ if (!root.startsWith(srcDir + path.sep)) {
16
+ throw new Error(`Invalid output directory: ${outputDir}`);
17
+ }
18
+
19
+ fs.mkdirSync(root, { recursive: true });
20
+
21
+ if (!Array.isArray(files)) {
22
+ files = [files];
23
+ }
24
+
25
+ const savedFiles = [];
26
+
27
+ for (const file of files) {
28
+ if (!file || typeof file.filename !== "string" || typeof file.source !== "string") {
29
+ throw new Error("Invalid file. Expected filename and source strings.");
30
+ }
31
+
32
+ const filename = path.basename(file.filename);
33
+
34
+ if (filename !== file.filename || !filename.endsWith(".py")) {
35
+ throw new Error(`Invalid filename: ${file.filename}`);
36
+ }
37
+
38
+ let destination = path.resolve(root, filename);
39
+
40
+ try {
41
+ fs.writeFileSync(destination, file.source, {
42
+ encoding: "utf8",
43
+ flag: "wx"
44
+ });
45
+ } catch (error) {
46
+ if (error.code === "EEXIST") {
47
+ throw new Error(`File already exists: ${destination}`);
48
+ }
49
+ throw error;
50
+ }
51
+
52
+ savedFiles.push(destination);
53
+ }
54
+
55
+ return savedFiles;
56
+ }
57
+
58
+ loadJSON(filename, defaultValue = null) {
59
+ try {
60
+ const filePath = this._getFilePath(filename);
61
+
62
+ if (!fs.existsSync(filePath)) {
63
+ return defaultValue;
64
+ }
65
+
66
+ return JSON.parse(fs.readFileSync(filePath, "utf8"));
67
+ } catch (error) {
68
+ throw new Error(`Failed to load ${filename}: ${error.message}`);
69
+ }
70
+ }
71
+
72
+ saveJSON(filename, data) {
73
+ try {
74
+ const filePath = this._getFilePath(filename);
75
+
76
+ fs.mkdirSync(path.dirname(filePath), {
77
+ recursive: true
78
+ });
79
+
80
+ fs.writeFileSync(
81
+ filePath,
82
+ JSON.stringify(data, null, 2),
83
+ "utf8"
84
+ );
85
+
86
+ return filePath;
87
+ } catch (error) {
88
+ throw new Error(`Failed to save ${filename}: ${error.message}`);
89
+ }
90
+ }
91
+
92
+ readPaths(paths, exclusions = []) {
93
+ const results = [];
94
+
95
+ for (const inputPath of paths) {
96
+ const resolvedPath = path.resolve(inputPath);
97
+ const relativePath = path.relative(process.cwd(), resolvedPath);
98
+
99
+ try {
100
+ if (!fs.existsSync(resolvedPath)) continue;
101
+
102
+ const stat = fs.statSync(resolvedPath);
103
+ const isDirectory = stat.isDirectory();
104
+
105
+ if (this._matchesExclusion(relativePath, isDirectory, exclusions)) {
106
+ continue;
107
+ }
108
+
109
+ if (stat.isFile()) {
110
+ results.push({
111
+ filename: path.basename(resolvedPath),
112
+ path: resolvedPath,
113
+ content: fs.readFileSync(resolvedPath, "utf8")
114
+ });
115
+ } else if (isDirectory) {
116
+ const children = this.readPaths(
117
+ fs.readdirSync(resolvedPath).map(name =>
118
+ path.join(resolvedPath, name)
119
+ ),
120
+ exclusions
121
+ );
122
+
123
+ results.push(...children);
124
+ }
125
+ } catch (error) {
126
+ console.error(`[FileUtil] ${inputPath}: ${error.message}`);
127
+ }
128
+ }
129
+
130
+ return results;
131
+ }
132
+
133
+ _globToRegex(pattern) {
134
+ let regex = "";
135
+
136
+ for (let i = 0; i < pattern.length; i++) {
137
+ const char = pattern[i];
138
+ const next = pattern[i + 1];
139
+
140
+ if (char === "*" && next === "*") {
141
+ regex += ".*";
142
+ i++;
143
+ } else if (char === "*") {
144
+ regex += "[^/]*";
145
+ } else if (char === "?") {
146
+ regex += "[^/]";
147
+ } else {
148
+ regex += char.replace(/[.+^${}()|[\]\\]/g, "\\$&");
149
+ }
150
+ }
151
+
152
+ return new RegExp(`^${regex}$`);
153
+ }
154
+
155
+ _matchesExclusion(relativePath, isDirectory, exclusions = []) {
156
+ const normalizedPath = relativePath
157
+ .split(path.sep)
158
+ .join("/");
159
+
160
+ const segments = normalizedPath.split("/");
161
+ let excluded = false;
162
+
163
+ for (let pattern of exclusions) {
164
+ if (!pattern || pattern.startsWith("#")) continue;
165
+
166
+ let negate = pattern.startsWith("!");
167
+
168
+ if (negate) {
169
+ pattern = pattern.substring(1);
170
+ }
171
+
172
+ pattern = pattern
173
+ .replace(/\\/g, "/")
174
+ .replace(/^\/+/, "");
175
+
176
+ const directoryOnly = pattern.endsWith("/");
177
+ pattern = pattern.replace(/\/+$/, "");
178
+
179
+ if (!pattern) continue;
180
+
181
+ const hasSlash = pattern.includes("/");
182
+ const regex = this._globToRegex(pattern);
183
+
184
+ let matched = false;
185
+
186
+ for (let i = 0; i < segments.length; i++) {
187
+ const candidate = segments.slice(0, i + 1).join("/");
188
+ const isLast = i === segments.length - 1;
189
+ const candidateIsDirectory = !isLast || isDirectory;
190
+
191
+ if (directoryOnly && !candidateIsDirectory) continue;
192
+
193
+ if (hasSlash) {
194
+ if (regex.test(candidate)) {
195
+ matched = true;
196
+ break;
197
+ }
198
+ } else {
199
+ if (regex.test(segments[i])) {
200
+ matched = true;
201
+ break;
202
+ }
203
+ }
204
+ }
205
+
206
+ if (matched) {
207
+ excluded = !negate;
208
+ }
209
+ }
210
+
211
+ return excluded;
212
+ }
213
+
214
+ _ensureDirectory() {
215
+ fs.mkdirSync(this.baseDir, { recursive: true });
216
+ }
217
+
218
+ _getFilePath(filename) {
219
+ return path.resolve(this.baseDir, filename);
220
+ }
221
+ }
222
+
223
+ module.exports = FileUtil;
@@ -0,0 +1,17 @@
1
+ const crypto = require("crypto");
2
+
3
+ class IdUtil {
4
+ static generate(length = 6) {
5
+ const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
6
+ let id = "";
7
+
8
+ for (let i = 0; i < length; i++) {
9
+ const index = crypto.randomInt(0, chars.length);
10
+ id += chars[index];
11
+ }
12
+
13
+ return id;
14
+ }
15
+ }
16
+
17
+ module.exports = IdUtil;
@@ -0,0 +1,29 @@
1
+ const fs = require("fs");
2
+ const path = require("path");
3
+
4
+ class PromptsUtil {
5
+ static read(name) {
6
+ const promptsDir = path.join(process.cwd(), "prompts");
7
+
8
+ if (!fs.existsSync(promptsDir)) {
9
+ throw new Error(`Prompts directory not found: ${promptsDir}`);
10
+ }
11
+
12
+ const files = fs.readdirSync(promptsDir);
13
+
14
+ const matchedFiles = files.filter(file => {
15
+ const filePath = path.join(promptsDir, file);
16
+
17
+ return (
18
+ fs.statSync(filePath).isFile() &&
19
+ path.parse(file).name === name
20
+ );
21
+ });
22
+
23
+ return matchedFiles
24
+ .map(file => fs.readFileSync(path.join(promptsDir, file), "utf-8"))
25
+ .join("\n");
26
+ }
27
+ }
28
+
29
+ module.exports = PromptsUtil;