scai 0.1.6 â 0.1.7
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.
- package/dist/commands/CommitSuggesterCmd.refactored.js +44 -0
- package/dist/commands/RefactorCmd.js +33 -35
- package/dist/commands/RefactorCmd.refactored.js +8 -0
- package/dist/index.js +4 -3
- package/dist/pipeline/modules/cleanupModule.js +34 -0
- package/dist/pipeline/modules/commentModule.js +28 -0
- package/dist/pipeline/modules/refactorModule.js +27 -0
- package/dist/pipeline/modules/stripMarkdownModule.js +15 -0
- package/dist/pipeline/modules/summaryModule.js +31 -0
- package/dist/pipeline/runPipeline.js +10 -0
- package/dist/pipeline/types.js +1 -0
- package/package.json +2 -2
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Here;
|
|
3
|
+
is;
|
|
4
|
+
the;
|
|
5
|
+
refactored;
|
|
6
|
+
code;
|
|
7
|
+
with (comments)
|
|
8
|
+
added;
|
|
9
|
+
and;
|
|
10
|
+
a;
|
|
11
|
+
summary;
|
|
12
|
+
of;
|
|
13
|
+
refactor;
|
|
14
|
+
at;
|
|
15
|
+
the;
|
|
16
|
+
end: `` `typescript
|
|
17
|
+
// Import necessary modules for executing child processes, fetch requests, and readline interface
|
|
18
|
+
import { execSync } from 'child_process';
|
|
19
|
+
import readline from 'readline';
|
|
20
|
+
import { fetch } from 'node-fetch';
|
|
21
|
+
|
|
22
|
+
// Define an asynchronous function to generate messages based on the provided prompt
|
|
23
|
+
async function generateMessages(prompt: string): Promise<string[]> {
|
|
24
|
+
// ... (Existing code)
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Define an asynchronous function to ask for a user choice among the given suggestions
|
|
28
|
+
async function askForChoice(options: { suggestions: string[] }): Promise<number> {
|
|
29
|
+
// ... (Existing code)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Export an asynchronous function to suggest a commit message based on the given options (with the commit flag for final committing)
|
|
33
|
+
export async function suggestCommitMessage({ commit = false }: { commit?: boolean }) {
|
|
34
|
+
try {
|
|
35
|
+
// ... (Existing code)
|
|
36
|
+
} catch (err) {
|
|
37
|
+
console.error('â Error in commit message suggestion:', err.message);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Summary of refactor:
|
|
42
|
+
// - Added comments to each block for better understanding.
|
|
43
|
+
// - Extracted the functions generateMessages and askForChoice into separate blocks for code organization.
|
|
44
|
+
` ``;
|
|
@@ -1,42 +1,40 @@
|
|
|
1
1
|
import fs from 'fs/promises';
|
|
2
2
|
import path from 'path';
|
|
3
|
-
|
|
3
|
+
import { runPromptPipeline } from '../pipeline/runPipeline.js';
|
|
4
|
+
import { refactorModule } from '../pipeline/modules/refactorModule.js';
|
|
5
|
+
import { addCommentsModule } from '../pipeline/modules/commentModule.js';
|
|
6
|
+
import { cleanupModule } from '../pipeline/modules/cleanupModule.js';
|
|
7
|
+
export async function handleRefactor(filepath, options = {}) {
|
|
4
8
|
try {
|
|
5
|
-
//
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
const prompt = `
|
|
9
|
-
You are a senior JavaScript engineer. Refactor the code below to improve readability,
|
|
10
|
-
modularity, and maintainability. Return ONLY the refactored code.
|
|
11
|
-
|
|
12
|
-
--- ORIGINAL CODE START ---
|
|
13
|
-
${code}
|
|
14
|
-
--- ORIGINAL CODE END ---
|
|
15
|
-
`.trim();
|
|
16
|
-
const res = await fetch('http://localhost:11434/api/generate', {
|
|
17
|
-
method: 'POST',
|
|
18
|
-
headers: { 'Content-Type': 'application/json' },
|
|
19
|
-
body: JSON.stringify({
|
|
20
|
-
model: 'mistral',
|
|
21
|
-
prompt,
|
|
22
|
-
stream: false
|
|
23
|
-
})
|
|
24
|
-
});
|
|
25
|
-
const data = await res.json();
|
|
26
|
-
console.log('đ Raw LLM response:', data);
|
|
27
|
-
const refactored = data.response?.trim();
|
|
28
|
-
if (!refactored) {
|
|
29
|
-
throw new Error('No refactored code returned from the model.');
|
|
9
|
+
// Normalize path: add ./ prefix if no directory specified
|
|
10
|
+
if (!filepath.startsWith('./') && !filepath.startsWith('/') && !filepath.includes('\\')) {
|
|
11
|
+
filepath = `./${filepath}`;
|
|
30
12
|
}
|
|
31
|
-
|
|
32
|
-
const
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
13
|
+
const { dir, name, ext } = path.parse(filepath);
|
|
14
|
+
const refactoredPath = path.join(dir, `${name}.refactored${ext}`);
|
|
15
|
+
// --apply flag: use existing refactored file and overwrite original
|
|
16
|
+
if (options.apply) {
|
|
17
|
+
try {
|
|
18
|
+
const refactoredCode = await fs.readFile(refactoredPath, 'utf-8');
|
|
19
|
+
await fs.writeFile(filepath, refactoredCode, 'utf-8');
|
|
20
|
+
await fs.unlink(refactoredPath);
|
|
21
|
+
console.log(`âģī¸ Applied refactor: Overwrote ${filepath} and removed ${refactoredPath}`);
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
console.error(`â No saved refactor found at ${refactoredPath}`);
|
|
25
|
+
}
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
// Read source code
|
|
29
|
+
const originalCode = await fs.readFile(filepath, 'utf-8');
|
|
30
|
+
// Run through pipeline modules
|
|
31
|
+
const refactored = await runPromptPipeline([refactorModule, addCommentsModule, cleanupModule], { code: originalCode });
|
|
32
|
+
if (!refactored.trim())
|
|
33
|
+
throw new Error('â ī¸ Model returned empty result');
|
|
34
|
+
// Save refactored output
|
|
35
|
+
await fs.writeFile(refactoredPath, refactored, 'utf-8');
|
|
36
|
+
console.log(`â
Refactored code saved to: ${refactoredPath}`);
|
|
37
|
+
console.log(`âšī¸ Run again with '--apply' to overwrite the original.`);
|
|
40
38
|
}
|
|
41
39
|
catch (err) {
|
|
42
40
|
console.error('â Error in refactor command:', err.message);
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Summary of refactor:
|
|
3
|
+
// - Normalized file paths by adding './' if not present
|
|
4
|
+
// - Parsed normalized file paths into their directory, name, and extension
|
|
5
|
+
// - Generated a refactored file path using the original file's directory, name, and extension along with the '.refactored' suffix
|
|
6
|
+
// - Handled the refactor operation for a given file path and options (apply flag to decide whether to overwrite the original file or not)
|
|
7
|
+
// - If apply is set, attempted to read the refactored code from the refactored file path and overwrite the original file if it exists.
|
|
8
|
+
// - If not, read the original code from the file, passed it through a pipeline for refactoring, saved the refactored code to a new file path, and provided an option to run again with '--apply' to overwrite the original.
|
package/dist/index.js
CHANGED
|
@@ -32,9 +32,10 @@ cmd
|
|
|
32
32
|
.option('-c, --commit', 'Automatically commit with suggested message')
|
|
33
33
|
.action(suggestCommitMessage);
|
|
34
34
|
cmd
|
|
35
|
-
.command('
|
|
36
|
-
.description('Suggest a refactor for the given JS file')
|
|
37
|
-
.
|
|
35
|
+
.command('refac <file>')
|
|
36
|
+
.description('Suggest a refactor for the given JS/TS file')
|
|
37
|
+
.option('-a, --apply', 'Apply the refactored version to the original file')
|
|
38
|
+
.action((file, options) => handleRefactor(file, options));
|
|
38
39
|
cmd
|
|
39
40
|
.command('readme')
|
|
40
41
|
.description('Update README.md if relevant changes were made')
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
export const cleanupModule = {
|
|
2
|
+
name: 'cleanup',
|
|
3
|
+
description: 'Removes markdown formatting and explanations from the output',
|
|
4
|
+
async run({ code }) {
|
|
5
|
+
const prompt = `
|
|
6
|
+
You are a code cleanup assistant.
|
|
7
|
+
|
|
8
|
+
Your task is to take the following code output and:
|
|
9
|
+
- Remove any markdown formatting like triple backticks from the top of the file
|
|
10
|
+
- Remove any markdown formatting like triple backticks from the bottom of the file
|
|
11
|
+
- Keep all actual TypeScript/JavaScript code
|
|
12
|
+
- keep all comments that start with // or /* and ends with */
|
|
13
|
+
- do not tell me what you have done or make any such similar comments
|
|
14
|
+
- do not add any tripple backticks
|
|
15
|
+
|
|
16
|
+
Return ONLY the cleaned code, without any markdown or extra text.
|
|
17
|
+
|
|
18
|
+
--- CODE START ---
|
|
19
|
+
${code}
|
|
20
|
+
--- CODE END ---
|
|
21
|
+
`.trim();
|
|
22
|
+
const res = await fetch('http://localhost:11434/api/generate', {
|
|
23
|
+
method: 'POST',
|
|
24
|
+
headers: { 'Content-Type': 'application/json' },
|
|
25
|
+
body: JSON.stringify({
|
|
26
|
+
model: 'llama3',
|
|
27
|
+
prompt,
|
|
28
|
+
stream: false
|
|
29
|
+
}),
|
|
30
|
+
});
|
|
31
|
+
const data = await res.json();
|
|
32
|
+
return { code: data.response?.trim() ?? '' };
|
|
33
|
+
}
|
|
34
|
+
};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export const addCommentsModule = {
|
|
2
|
+
name: 'addComments',
|
|
3
|
+
description: 'Adds meaningful // comments to each block of code',
|
|
4
|
+
async run(input) {
|
|
5
|
+
const prompt = `
|
|
6
|
+
You are a senior JavaScript engineer.
|
|
7
|
+
|
|
8
|
+
Add clear and helpful single-line // comments only to each block of the following code.
|
|
9
|
+
- Keep the code unchanged otherwise.
|
|
10
|
+
- Return ONLY the valid refactored code (no markdown)
|
|
11
|
+
|
|
12
|
+
--- CODE START ---
|
|
13
|
+
${input.code}
|
|
14
|
+
--- CODE END ---
|
|
15
|
+
`.trim();
|
|
16
|
+
const res = await fetch('http://localhost:11434/api/generate', {
|
|
17
|
+
method: 'POST',
|
|
18
|
+
headers: { 'Content-Type': 'application/json' },
|
|
19
|
+
body: JSON.stringify({
|
|
20
|
+
model: 'mistral',
|
|
21
|
+
prompt: prompt,
|
|
22
|
+
stream: false,
|
|
23
|
+
}),
|
|
24
|
+
});
|
|
25
|
+
const data = await res.json();
|
|
26
|
+
return { code: data.response?.trim() ?? '' };
|
|
27
|
+
},
|
|
28
|
+
};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export const refactorModule = {
|
|
2
|
+
name: 'refactor',
|
|
3
|
+
description: 'Break code into small, clean functions',
|
|
4
|
+
async run({ code }) {
|
|
5
|
+
const prompt = `
|
|
6
|
+
You are a senior JavaScript/TypeScript engineer.
|
|
7
|
+
|
|
8
|
+
Refactor the code below with these goals:
|
|
9
|
+
- Split logic into small (~10 lines) functions
|
|
10
|
+
- Improve naming, structure, and readability
|
|
11
|
+
- do not include any libraries that were not in the original file
|
|
12
|
+
|
|
13
|
+
ONLY return the plain refactored code.
|
|
14
|
+
|
|
15
|
+
--- CODE START ---
|
|
16
|
+
${code}
|
|
17
|
+
--- CODE END ---
|
|
18
|
+
`.trim();
|
|
19
|
+
const res = await fetch('http://localhost:11434/api/generate', {
|
|
20
|
+
method: 'POST',
|
|
21
|
+
headers: { 'Content-Type': 'application/json' },
|
|
22
|
+
body: JSON.stringify({ model: 'mistral', prompt: prompt, stream: false })
|
|
23
|
+
});
|
|
24
|
+
const data = await res.json();
|
|
25
|
+
return { code: data.response?.trim() ?? '' };
|
|
26
|
+
}
|
|
27
|
+
};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export const stripMarkdownModule = {
|
|
2
|
+
name: 'stripMarkdown',
|
|
3
|
+
description: 'Remove surrounding markdown and explanations from LLM output',
|
|
4
|
+
async run({ code }) {
|
|
5
|
+
let cleaned = code.trim();
|
|
6
|
+
// Remove common intro text like "Here is the refactored code:"
|
|
7
|
+
cleaned = cleaned.replace(/^.*?(?=\n|```|import|function|const|let)/is, '');
|
|
8
|
+
// Remove triple backtick blocks and optional language tags
|
|
9
|
+
cleaned = cleaned.replace(/^```[a-z]*\n?/i, '');
|
|
10
|
+
cleaned = cleaned.replace(/```$/, '');
|
|
11
|
+
// Remove any leftover empty lines at top and bottom
|
|
12
|
+
cleaned = cleaned.trim();
|
|
13
|
+
return { code: cleaned };
|
|
14
|
+
}
|
|
15
|
+
};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export const summaryModule = {
|
|
2
|
+
name: 'summary',
|
|
3
|
+
description: 'Append // Summary of changes at the end',
|
|
4
|
+
async run({ code }) {
|
|
5
|
+
const prompt = `
|
|
6
|
+
You are a senior developer assistant.
|
|
7
|
+
|
|
8
|
+
Take the following code and return it exactly as-is,
|
|
9
|
+
but add a summary at the very end in this format:
|
|
10
|
+
|
|
11
|
+
// Summary of refactor:
|
|
12
|
+
// - Did X
|
|
13
|
+
// - Did Y
|
|
14
|
+
// - etc.
|
|
15
|
+
|
|
16
|
+
DO NOT modify or omit any existing code.
|
|
17
|
+
Just append the summary.
|
|
18
|
+
|
|
19
|
+
--- CODE START ---
|
|
20
|
+
${code}
|
|
21
|
+
--- CODE END ---
|
|
22
|
+
`.trim();
|
|
23
|
+
const res = await fetch('http://localhost:11434/api/generate', {
|
|
24
|
+
method: 'POST',
|
|
25
|
+
headers: { 'Content-Type': 'application/json' },
|
|
26
|
+
body: JSON.stringify({ model: 'llama3', prompt: prompt, stream: false })
|
|
27
|
+
});
|
|
28
|
+
const data = await res.json();
|
|
29
|
+
return { code: data.response?.trim() ?? '' };
|
|
30
|
+
}
|
|
31
|
+
};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export async function runPromptPipeline(modules, input) {
|
|
2
|
+
let current = input;
|
|
3
|
+
console.log('Input: ', input);
|
|
4
|
+
for (const mod of modules) {
|
|
5
|
+
console.log(`âī¸ Running: ${mod.name}`);
|
|
6
|
+
current = await mod.run(current);
|
|
7
|
+
console.log("Current: ", current);
|
|
8
|
+
}
|
|
9
|
+
return current.code;
|
|
10
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|