Skip to content

Commit c4fccb1

Browse files
Merge pull request #8 from olasunkanmi-SE/javascript-parser
Javascript parser
2 parents 4aef72d + e1a7cc8 commit c4fccb1

File tree

13 files changed

+462
-135
lines changed

13 files changed

+462
-135
lines changed

.github/workflows/workflow.yml

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ name: CI for restaurant
22

33
on:
44
pull_request:
5-
branches: [main]
5+
branches: [main, development]
66

77
jobs:
88
build:
@@ -13,10 +13,11 @@ jobs:
1313
fetch-depth: 0
1414
- uses: actions/setup-node@v2
1515
with:
16-
node-version: "16"
16+
node-version: "20"
1717
- name: ci for app
1818
working-directory: ./
1919
run: |
2020
npm i
2121
npm run build
2222
npm run format
23+
npm run test:unit

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
node_modules
22
.env
33
dist
4-
coverage
4+
coverage
5+
.codebuddy

README.md

Lines changed: 65 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,81 @@
11
# TypeScript Code Extractor and Analyzer
22

3-
This project provides a robust toolkit for extracting, analyzing, and mapping TypeScript code structures.
3+
This project provides an advanced toolkit for parsing TypeScript code using the TypeScript Abstract Syntax Tree (AST) to extract, analyze, and map code structures.
44

5-
The TypeScript Code Extractor and Analyzer is a comprehensive solution designed to parse and analyze TypeScript codebases. It offers a set of tools to extract detailed information about classes, interfaces, functions, and other TypeScript constructs, enabling developers to gain deep insights into their codebase structure and dependencies.
5+
TypeScript Code Extractor and Analyzer is a robust system that utilizes a TypeScript parser to navigate through the codebase's AST, extracting structured metadata about various components such as modules, classes, functions, interfaces, properties, and enums.
66

7-
Key features include:
7+
Key features:
88

9-
- Extraction of class metadata, including methods, properties, interfaces, and enums
10-
- Function and method analysis, including parameter extraction and return type inference
11-
- Interface and enum information extraction
12-
- Dependency graph generation for TypeScript files
9+
- AST-based Class Metadata Extraction: Utilizes TypeScript's AST to gather comprehensive metadata on class methods, properties, interfaces, and enums.
10+
- Function and Method Signature Analysis: Parses function signatures from the AST for details on parameters, return types, and inferred type information.
11+
- Interface and Enum Parsing: Extracts information from AST nodes representing interfaces and enums in TypeScript.
12+
- Dependency Graph Construction: Builds a graph of file dependencies by analyzing import declarations within the AST.
13+
14+
### Installation
15+
To integrate this tool into your project, install it via npm:
16+
```
17+
npm i @traversets/code-extractor
18+
```
1319

1420
### Code Analysis
1521

16-
To analyze a TypeScript codebase:
22+
Below is an example of how to use the AST parser for code analysis:
1723

1824
```typescript
19-
import { TypeScriptCodeMapper } from "./src/services/typescript-code-mapper.service";
2025

21-
const codeMapper = new TypeScriptCodeMapper();
26+
const codeMapper: TypeScriptCodeMapper = new TypeScriptCodeMapper();
2227

23-
// Build a codebase map
24-
const codebaseMap = await codeMapper.buildCodebaseMap();
28+
// Get Root files
29+
const rootFiles: readonly string[] = codeMapper.getRootFileNames();
2530

26-
// Extract class metadata
27-
const classInfo = codeMapper.extractClassMetaData(classNode, sourceFile);
31+
// Convert a rootFile into a sourceFile
32+
const sourceFile: ts.SourceFile = codeMapper.getSourceFile(rootFiles[5]);
2833

2934
// Build a dependency graph
30-
const dependencies = codeMapper.buildDependencyGraph(sourceFile);
35+
const getSourceFileDepencies: string[] = codeMapper.buildDependencyGraph(sourceFile);
36+
37+
// Build a codebase map
38+
const codebaseMap = await codeMapper.buildCodebaseMap().getValue();
3139
```
40+
41+
### Sample Response Structure
42+
The resulting JSON structure reflects the TypeScript AST's hierarchical representation:
43+
```
44+
{
45+
"MyProject": {
46+
"modules": {
47+
"src/utils/logger.ts": {
48+
"classes": [
49+
{
50+
"name": "Logger",
51+
"functions": [
52+
{
53+
"name": "log",
54+
"parameters": [{ "name": "message", "type": "string" }],
55+
"returnType": "void",
56+
"content": "",
57+
"comment": "Logs application Error"
58+
}
59+
],
60+
"properties": [
61+
{ "name": "logLevel", "type": "LogLevel" }
62+
]
63+
}
64+
],
65+
"functions": [],
66+
"interfaces": [],
67+
"enums": [],
68+
"dependencies": ["import { LogLevel } from './types';"]
69+
}
70+
}
71+
}
72+
}
73+
74+
```
75+
76+
### Usage for Agentic RAG Systems
77+
This tool enhances Retrieval-Augmented Generation (RAG) systems by:
78+
79+
- Parsing the TypeScript AST into embeddings for semantic code search and similarity matching
80+
- Leveraging AST metadata for advanced code analysis, query resolution, or to aid in code generation, thereby improving the understanding and manipulation of TypeScript codebases within AI systems.
81+

package.json

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,28 @@
1616
"start:dev": "concurrently \"npx tsc --watch\" \"nodemon -q dist/index.js\"",
1717
"format": "prettier --write \"src/**/*.ts\""
1818
},
19-
"keywords": [],
19+
"keywords": [
20+
"typescript",
21+
"code-extractor",
22+
"rag",
23+
"code-analysis",
24+
"embeddings",
25+
"advanced-code-analysis",
26+
"code-retrieval",
27+
"code-generation",
28+
"codebase",
29+
"code-analyzer",
30+
"code-embeddings",
31+
"code-toolbox",
32+
"code-tool",
33+
"code-extraction",
34+
"code-toolkit",
35+
"code-tooling",
36+
"code-utility",
37+
"code-utilities",
38+
"code-utility-tool",
39+
"code-utility-toolkit"
40+
],
2041
"author": "Oyinlola Olasunkanmi Raymond",
2142
"license": "ISC",
2243
"devDependencies": {

src/http/http-service.spec.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ describe("HttpClient", () => {
4747
method: "GET",
4848
path: "/test",
4949
}),
50-
expect.any(Function)
50+
expect.any(Function),
5151
);
5252
expect(result).toEqual(mockData);
5353
});
@@ -69,7 +69,7 @@ describe("HttpClient", () => {
6969
method: "POST",
7070
path: "/test",
7171
}),
72-
expect.any(Function)
72+
expect.any(Function),
7373
);
7474
expect(result).toEqual(mockData);
7575
});
@@ -90,7 +90,7 @@ describe("HttpClient", () => {
9090
method: "PUT",
9191
path: "/test",
9292
}),
93-
expect.any(Function)
93+
expect.any(Function),
9494
);
9595
expect(result).toEqual({ statusCode: 200 });
9696
});
@@ -110,7 +110,7 @@ describe("HttpClient", () => {
110110
method: "DELETE",
111111
path: "/test",
112112
}),
113-
expect.any(Function)
113+
expect.any(Function),
114114
);
115115
expect(result).toEqual({ statusCode: 200 });
116116
});
@@ -124,7 +124,7 @@ describe("HttpClient", () => {
124124
});
125125

126126
await expect(httpClient.get({}, { path: "/test" })).rejects.toThrow(
127-
"Request failed with status code 500"
127+
"Request failed with status code 500",
128128
);
129129
});
130130

@@ -135,7 +135,7 @@ describe("HttpClient", () => {
135135
});
136136

137137
await expect(httpClient.get({}, { path: "/test" })).rejects.toThrow(
138-
"Failed to parse response data"
138+
"Failed to parse response data",
139139
);
140140
});
141141
});

src/http/http-service.ts

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ export class HttpClient implements IHttpClient {
3232
**/
3333
async post<TRequest, TResponse>(
3434
payload: TRequest,
35-
options?: https.RequestOptions
35+
options?: https.RequestOptions,
3636
): Promise<TResponse> {
3737
return this.sendRequest<TResponse>("POST", options, payload);
3838
}
@@ -44,7 +44,7 @@ export class HttpClient implements IHttpClient {
4444
**/
4545
async put<TRequest, TResponse>(
4646
payload: TRequest,
47-
options?: https.RequestOptions
47+
options?: https.RequestOptions,
4848
): Promise<TResponse> {
4949
return this.sendRequest<TResponse>("PUT", options, payload);
5050
}
@@ -69,7 +69,7 @@ export class HttpClient implements IHttpClient {
6969
method: string,
7070
options?: any,
7171
payload?: any,
72-
jwtToken?: string
72+
jwtToken?: string,
7373
): Promise<T> {
7474
const defaultHeader = this.generateRequestHeader(jwtToken);
7575
options.header = { ...options.header, ...defaultHeader };
@@ -102,20 +102,20 @@ export class HttpClient implements IHttpClient {
102102
} catch (error: any) {
103103
console.log(error);
104104
reject(
105-
new Error(`Failed to parse response data: ${error.message}`)
105+
new Error(`Failed to parse response data: ${error.message}`),
106106
);
107107
throw error;
108108
}
109109
} else {
110110
reject(
111-
new Error(`Request failed with status code ${res.statusCode}`)
111+
new Error(`Request failed with status code ${res.statusCode}`),
112112
);
113113
}
114114
} catch (error: any) {
115115
this.logger.error(
116116
"An error occurred during the API request.",
117117
JSON.stringify(error),
118-
error
118+
error,
119119
);
120120
throw error;
121121
}
@@ -125,7 +125,7 @@ export class HttpClient implements IHttpClient {
125125
this.logger.error(
126126
"An error occurred during the API request.",
127127
JSON.stringify(error),
128-
error
128+
error,
129129
);
130130
reject(error);
131131
throw error;
@@ -153,7 +153,7 @@ export class HttpClient implements IHttpClient {
153153
method: string,
154154
path: string,
155155
baseUrl: string,
156-
jwtToken?: string
156+
jwtToken?: string,
157157
): IRequestOptions {
158158
const headers = this.generateRequestHeader(jwtToken);
159159
const options: IRequestOptions = {
@@ -178,26 +178,26 @@ export class HttpClient implements IHttpClient {
178178
path: string,
179179
baseUrl: string,
180180
data: any,
181-
jwtToken?: string
181+
jwtToken?: string,
182182
): Promise<T | undefined> {
183183
try {
184184
const requestOptions: IRequestOptions = this.generateRequestOptions(
185185
method,
186186
path,
187187
baseUrl,
188-
jwtToken
188+
jwtToken,
189189
);
190190
let response: T | undefined;
191191
switch (method) {
192192
case HTTP_VERBS.GET:
193193
response = await this.get(
194194
Buffer.from(JSON.stringify({})),
195-
requestOptions
195+
requestOptions,
196196
);
197197
case HTTP_VERBS.POST:
198198
response = await this.post(
199199
Buffer.from(JSON.stringify(data)),
200-
requestOptions
200+
requestOptions,
201201
);
202202
break;
203203
default:
@@ -211,7 +211,7 @@ export class HttpClient implements IHttpClient {
211211
this.logger.error(
212212
"An error occurred during the API request.",
213213
JSON.stringify(error),
214-
error
214+
error,
215215
);
216216
throw error;
217217
}

src/interfaces/generic.interface.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ export interface IFunctionInfo {
2121
returnType?: string;
2222
comments?: string;
2323
summary?: string;
24+
kind?: string;
2425
}
2526

2627
export interface IClassInfo {
@@ -55,6 +56,7 @@ export interface IModuleInfo {
5556
enums?: IEnumInfo[];
5657
dependencies: string[];
5758
properties?: IProperty[];
59+
errors?: string[];
5860
}
5961

6062
export interface ICodebaseMap {

0 commit comments

Comments
 (0)