codebakers 2.0.3 → 2.0.10

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.
@@ -7,6 +7,8 @@ import { execa } from 'execa';
7
7
  import { Config } from '../utils/config.js';
8
8
  import { loadPatterns } from '../patterns/loader.js';
9
9
  import { runPatternCheck } from './check.js';
10
+ import { textWithVoice, checkVoiceAvailability } from '../utils/voice.js';
11
+ import { readClipboard, readFile, formatFilesForContext, looksLikePaste, handlePastedContent } from '../utils/files.js';
10
12
 
11
13
  interface CodeOptions {
12
14
  watch?: boolean;
@@ -82,11 +84,22 @@ export async function codeCommand(prompt?: string, options: CodeOptions = {}): P
82
84
  await processUserInput(prompt, messages, anthropic, systemPrompt, projectContext, config);
83
85
  }
84
86
 
87
+ // Check for voice support
88
+ const hasVoice = await checkVoiceAvailability();
89
+
90
+ console.log(chalk.dim(' šŸ’” Tips:'));
91
+ if (hasVoice) {
92
+ console.log(chalk.dim(' • Type "v" for voice input'));
93
+ }
94
+ console.log(chalk.dim(' • Type "clip" to read from clipboard'));
95
+ console.log(chalk.dim(' • Drag & drop files or paste file paths'));
96
+ console.log(chalk.dim(' • Paste code directly and I\'ll detect it\n'));
97
+
85
98
  // Interactive loop
86
99
  while (true) {
87
- const input = await p.text({
100
+ const input = await textWithVoice({
88
101
  message: '',
89
- placeholder: 'What do you want to build?',
102
+ placeholder: 'What do you want to build? (or paste code/file path)',
90
103
  });
91
104
 
92
105
  if (p.isCancel(input)) {
@@ -94,7 +107,8 @@ export async function codeCommand(prompt?: string, options: CodeOptions = {}): P
94
107
  break;
95
108
  }
96
109
 
97
- const userInput = (input as string).trim();
110
+ let userInput = (input as string).trim();
111
+ let fileContext = '';
98
112
 
99
113
  if (!userInput) continue;
100
114
 
@@ -114,8 +128,91 @@ export async function codeCommand(prompt?: string, options: CodeOptions = {}): P
114
128
  continue;
115
129
  }
116
130
 
117
- // Process input with AI
118
- await processUserInput(userInput, messages, anthropic, systemPrompt, projectContext, config);
131
+ // Check for clipboard command
132
+ if (userInput.toLowerCase() === 'clip' || userInput.toLowerCase() === 'clipboard' || userInput.toLowerCase() === 'paste') {
133
+ const clipContent = await readClipboard();
134
+ if (clipContent) {
135
+ console.log(chalk.green(`\nšŸ“‹ Read ${clipContent.length} characters from clipboard\n`));
136
+
137
+ // Check if clipboard is a file path
138
+ if (await fs.pathExists(clipContent.trim())) {
139
+ const file = await readFile(clipContent.trim());
140
+ if (file) {
141
+ fileContext = formatFilesForContext([file]);
142
+ console.log(chalk.green(`šŸ“„ Loaded file: ${file.name}\n`));
143
+
144
+ const instruction = await p.text({
145
+ message: `What should I do with ${file.name}?`,
146
+ placeholder: 'Fix any issues in this code',
147
+ });
148
+ if (p.isCancel(instruction)) continue;
149
+ userInput = instruction as string;
150
+ }
151
+ } else {
152
+ // Clipboard contains code/text
153
+ fileContext = `\n\n--- CLIPBOARD CONTENT ---\n\`\`\`\n${clipContent}\n\`\`\`\n--- END ---\n\n`;
154
+
155
+ const action = await p.select({
156
+ message: 'What should I do with this?',
157
+ options: [
158
+ { value: 'analyze', label: 'šŸ” Analyze this' },
159
+ { value: 'fix', label: 'šŸ”§ Fix issues' },
160
+ { value: 'explain', label: 'šŸ“– Explain' },
161
+ { value: 'improve', label: '✨ Improve' },
162
+ { value: 'custom', label: 'āœļø Custom' },
163
+ ],
164
+ });
165
+
166
+ if (p.isCancel(action)) continue;
167
+
168
+ if (action === 'custom') {
169
+ const custom = await p.text({ message: 'What should I do?', placeholder: 'Add TypeScript types' });
170
+ if (p.isCancel(custom)) continue;
171
+ userInput = custom as string;
172
+ } else {
173
+ const actions: Record<string, string> = {
174
+ analyze: 'Analyze this code and explain what it does',
175
+ fix: 'Fix any bugs or issues in this code',
176
+ explain: 'Explain this code step by step',
177
+ improve: 'Improve and refactor this code',
178
+ };
179
+ userInput = actions[action as string];
180
+ }
181
+ }
182
+ } else {
183
+ console.log(chalk.yellow('Clipboard is empty'));
184
+ continue;
185
+ }
186
+ }
187
+
188
+ // Check if input is a file path
189
+ else if (await fs.pathExists(userInput)) {
190
+ const file = await readFile(userInput);
191
+ if (file) {
192
+ fileContext = formatFilesForContext([file]);
193
+ console.log(chalk.green(`\nšŸ“„ Loaded file: ${file.name}\n`));
194
+
195
+ const instruction = await p.text({
196
+ message: `What should I do with ${file.name}?`,
197
+ placeholder: 'Analyze and improve this code',
198
+ });
199
+ if (p.isCancel(instruction)) continue;
200
+ userInput = instruction as string;
201
+ }
202
+ }
203
+
204
+ // Check if input looks like pasted code
205
+ else if (looksLikePaste(userInput)) {
206
+ const result = await handlePastedContent(userInput);
207
+ if (result) {
208
+ userInput = result.prompt;
209
+ fileContext = result.context;
210
+ }
211
+ }
212
+
213
+ // Process input with AI (include file context if any)
214
+ const fullInput = fileContext ? userInput + fileContext : userInput;
215
+ await processUserInput(fullInput, messages, anthropic, systemPrompt, projectContext, config);
119
216
  }
120
217
  }
121
218
 
@@ -0,0 +1,419 @@
1
+ import * as p from '@clack/prompts';
2
+ import chalk from 'chalk';
3
+ import { execa } from 'execa';
4
+ import * as fs from 'fs-extra';
5
+ import * as path from 'path';
6
+ import { Config } from '../utils/config.js';
7
+
8
+ interface MigrateOptions {
9
+ push?: boolean;
10
+ generate?: boolean;
11
+ status?: boolean;
12
+ }
13
+
14
+ export async function migrateCommand(options: MigrateOptions = {}): Promise<void> {
15
+ const config = new Config();
16
+
17
+ if (!config.isInProject()) {
18
+ p.log.error('Not in a CodeBakers project.');
19
+ return;
20
+ }
21
+
22
+ p.intro(chalk.bgCyan.black(' Database Migrations '));
23
+
24
+ // Detect migration tool
25
+ const migrationTool = await detectMigrationTool();
26
+
27
+ if (!migrationTool) {
28
+ p.log.error('No migration tool detected. Supported: Drizzle, Prisma, Supabase CLI');
29
+ return;
30
+ }
31
+
32
+ p.log.info(`Detected: ${migrationTool}`);
33
+
34
+ const action = options.push ? 'push' :
35
+ options.generate ? 'generate' :
36
+ options.status ? 'status' :
37
+ await p.select({
38
+ message: 'What do you want to do?',
39
+ options: [
40
+ { value: 'status', label: 'šŸ“Š Check migration status' },
41
+ { value: 'generate', label: 'šŸ“ Generate migration' },
42
+ { value: 'push', label: 'šŸš€ Push to database' },
43
+ { value: 'pull', label: 'ā¬‡ļø Pull from database' },
44
+ ],
45
+ });
46
+
47
+ if (p.isCancel(action)) return;
48
+
49
+ switch (action) {
50
+ case 'status':
51
+ await checkMigrationStatus(migrationTool);
52
+ break;
53
+ case 'generate':
54
+ await generateMigration(migrationTool);
55
+ break;
56
+ case 'push':
57
+ await pushMigration(migrationTool);
58
+ break;
59
+ case 'pull':
60
+ await pullSchema(migrationTool);
61
+ break;
62
+ }
63
+ }
64
+
65
+ async function detectMigrationTool(): Promise<string | null> {
66
+ const cwd = process.cwd();
67
+
68
+ // Check for Drizzle
69
+ if (fs.existsSync(path.join(cwd, 'drizzle.config.ts')) ||
70
+ fs.existsSync(path.join(cwd, 'drizzle.config.js'))) {
71
+ return 'drizzle';
72
+ }
73
+
74
+ // Check for Prisma
75
+ if (fs.existsSync(path.join(cwd, 'prisma', 'schema.prisma'))) {
76
+ return 'prisma';
77
+ }
78
+
79
+ // Check for Supabase
80
+ if (fs.existsSync(path.join(cwd, 'supabase', 'migrations'))) {
81
+ return 'supabase';
82
+ }
83
+
84
+ // Check package.json for clues
85
+ const pkgPath = path.join(cwd, 'package.json');
86
+ if (fs.existsSync(pkgPath)) {
87
+ const pkg = await fs.readJson(pkgPath);
88
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
89
+
90
+ if (deps['drizzle-orm'] || deps['drizzle-kit']) return 'drizzle';
91
+ if (deps['prisma'] || deps['@prisma/client']) return 'prisma';
92
+ }
93
+
94
+ return null;
95
+ }
96
+
97
+ async function checkMigrationStatus(tool: string): Promise<void> {
98
+ const spinner = p.spinner();
99
+ spinner.start('Checking migration status...');
100
+
101
+ try {
102
+ let result;
103
+ switch (tool) {
104
+ case 'drizzle':
105
+ result = await execa('npx', ['drizzle-kit', 'check'], { cwd: process.cwd(), reject: false });
106
+ break;
107
+ case 'prisma':
108
+ result = await execa('npx', ['prisma', 'migrate', 'status'], { cwd: process.cwd(), reject: false });
109
+ break;
110
+ case 'supabase':
111
+ result = await execa('npx', ['supabase', 'migration', 'list'], { cwd: process.cwd(), reject: false });
112
+ break;
113
+ }
114
+
115
+ spinner.stop('Status check complete');
116
+
117
+ if (result?.stdout) {
118
+ console.log(chalk.dim(result.stdout));
119
+ }
120
+ if (result?.stderr) {
121
+ console.log(chalk.yellow(result.stderr));
122
+ }
123
+ } catch (error) {
124
+ spinner.stop('Error checking status');
125
+ p.log.error(error instanceof Error ? error.message : 'Unknown error');
126
+ }
127
+ }
128
+
129
+ async function generateMigration(tool: string): Promise<void> {
130
+ const name = await p.text({
131
+ message: 'Migration name:',
132
+ placeholder: 'add_users_table',
133
+ validate: (v) => !v ? 'Name required' : undefined,
134
+ });
135
+
136
+ if (p.isCancel(name)) return;
137
+
138
+ const spinner = p.spinner();
139
+ spinner.start('Generating migration...');
140
+
141
+ try {
142
+ let result;
143
+ switch (tool) {
144
+ case 'drizzle':
145
+ result = await execa('npx', ['drizzle-kit', 'generate', '--name', name as string], { cwd: process.cwd(), reject: false });
146
+ break;
147
+ case 'prisma':
148
+ result = await execa('npx', ['prisma', 'migrate', 'dev', '--name', name as string, '--create-only'], { cwd: process.cwd(), reject: false });
149
+ break;
150
+ case 'supabase':
151
+ result = await execa('npx', ['supabase', 'migration', 'new', name as string], { cwd: process.cwd(), reject: false });
152
+ break;
153
+ }
154
+
155
+ spinner.stop('Migration generated');
156
+
157
+ if (result?.stdout) {
158
+ console.log(chalk.dim(result.stdout));
159
+ }
160
+ } catch (error) {
161
+ spinner.stop('Error generating migration');
162
+ p.log.error(error instanceof Error ? error.message : 'Unknown error');
163
+ }
164
+ }
165
+
166
+ async function pushMigration(tool: string): Promise<void> {
167
+ const spinner = p.spinner();
168
+ spinner.start('Pushing migration to database...');
169
+
170
+ try {
171
+ let result;
172
+ let migrationSql = '';
173
+
174
+ switch (tool) {
175
+ case 'drizzle':
176
+ result = await execa('npx', ['drizzle-kit', 'push'], {
177
+ cwd: process.cwd(),
178
+ reject: false,
179
+ env: { ...process.env }
180
+ });
181
+ break;
182
+ case 'prisma':
183
+ result = await execa('npx', ['prisma', 'db', 'push'], {
184
+ cwd: process.cwd(),
185
+ reject: false
186
+ });
187
+ break;
188
+ case 'supabase':
189
+ result = await execa('npx', ['supabase', 'db', 'push'], {
190
+ cwd: process.cwd(),
191
+ reject: false
192
+ });
193
+ break;
194
+ }
195
+
196
+ // Check if push failed
197
+ if (result?.exitCode !== 0) {
198
+ spinner.stop('Migration push failed');
199
+
200
+ const errorOutput = result?.stderr || result?.stdout || '';
201
+ console.log(chalk.red('\nError:\n'));
202
+ console.log(chalk.dim(errorOutput));
203
+
204
+ // Try to get the SQL that needs to be run
205
+ migrationSql = await extractMigrationSQL(tool, errorOutput);
206
+
207
+ if (migrationSql) {
208
+ // Copy to clipboard
209
+ const copied = await copyToClipboard(migrationSql);
210
+
211
+ if (copied) {
212
+ console.log(chalk.green(`
213
+ ╔════════════════════════════════════════════════════════════════╗
214
+ ā•‘ šŸ“‹ MIGRATION SQL COPIED TO CLIPBOARD! ā•‘
215
+ ╠════════════════════════════════════════════════════════════════╣
216
+ ā•‘ ā•‘
217
+ ā•‘ The migration could not be pushed automatically. ā•‘
218
+ ā•‘ The SQL has been copied to your clipboard. ā•‘
219
+ ā•‘ ā•‘
220
+ ā•‘ Next steps: ā•‘
221
+ ā•‘ 1. Go to your Supabase Dashboard → SQL Editor ā•‘
222
+ ā•‘ 2. Paste the SQL (Ctrl+V / Cmd+V) ā•‘
223
+ ā•‘ 3. Review and run it ā•‘
224
+ ā•‘ ā•‘
225
+ ā•šā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•
226
+ `));
227
+
228
+ // Also show the SQL
229
+ const showSql = await p.confirm({
230
+ message: 'Show the SQL here too?',
231
+ initialValue: true,
232
+ });
233
+
234
+ if (showSql && !p.isCancel(showSql)) {
235
+ console.log(chalk.cyan('\n--- SQL Migration ---\n'));
236
+ console.log(migrationSql);
237
+ console.log(chalk.cyan('\n--- End SQL ---\n'));
238
+ }
239
+ } else {
240
+ // Clipboard failed, just show the SQL
241
+ console.log(chalk.yellow(`
242
+ ╔════════════════════════════════════════════════════════════════╗
243
+ ā•‘ āš ļø Could not copy to clipboard ā•‘
244
+ ā•‘ ā•‘
245
+ ā•‘ Here's the SQL to run manually: ā•‘
246
+ ā•šā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•
247
+ `));
248
+ console.log(chalk.cyan(migrationSql));
249
+ }
250
+
251
+ // Save to file as backup
252
+ const sqlPath = path.join(process.cwd(), '.codebakers', 'failed-migration.sql');
253
+ await fs.ensureDir(path.dirname(sqlPath));
254
+ await fs.writeFile(sqlPath, migrationSql);
255
+ console.log(chalk.dim(`\nAlso saved to: ${sqlPath}\n`));
256
+
257
+ } else {
258
+ p.log.error('Could not extract migration SQL. Check the error above.');
259
+ }
260
+
261
+ return;
262
+ }
263
+
264
+ spinner.stop('Migration pushed successfully!');
265
+
266
+ if (result?.stdout) {
267
+ console.log(chalk.dim(result.stdout));
268
+ }
269
+
270
+ p.log.success('Database updated!');
271
+
272
+ } catch (error) {
273
+ spinner.stop('Error');
274
+ const errorMsg = error instanceof Error ? error.message : 'Unknown error';
275
+ p.log.error(errorMsg);
276
+
277
+ // Try to extract and copy SQL even from exception
278
+ const migrationSql = await extractMigrationSQL(tool, errorMsg);
279
+ if (migrationSql) {
280
+ await copyToClipboard(migrationSql);
281
+ console.log(chalk.green('\nšŸ“‹ Migration SQL copied to clipboard!\n'));
282
+ console.log(chalk.cyan(migrationSql));
283
+ }
284
+ }
285
+ }
286
+
287
+ async function pullSchema(tool: string): Promise<void> {
288
+ const spinner = p.spinner();
289
+ spinner.start('Pulling schema from database...');
290
+
291
+ try {
292
+ let result;
293
+ switch (tool) {
294
+ case 'drizzle':
295
+ result = await execa('npx', ['drizzle-kit', 'introspect'], { cwd: process.cwd(), reject: false });
296
+ break;
297
+ case 'prisma':
298
+ result = await execa('npx', ['prisma', 'db', 'pull'], { cwd: process.cwd(), reject: false });
299
+ break;
300
+ case 'supabase':
301
+ result = await execa('npx', ['supabase', 'db', 'pull'], { cwd: process.cwd(), reject: false });
302
+ break;
303
+ }
304
+
305
+ spinner.stop('Schema pulled');
306
+
307
+ if (result?.stdout) {
308
+ console.log(chalk.dim(result.stdout));
309
+ }
310
+ } catch (error) {
311
+ spinner.stop('Error pulling schema');
312
+ p.log.error(error instanceof Error ? error.message : 'Unknown error');
313
+ }
314
+ }
315
+
316
+ async function extractMigrationSQL(tool: string, errorOutput: string): Promise<string | null> {
317
+ const cwd = process.cwd();
318
+
319
+ try {
320
+ switch (tool) {
321
+ case 'drizzle': {
322
+ // Check for pending migrations in drizzle folder
323
+ const drizzleDir = path.join(cwd, 'drizzle');
324
+ if (fs.existsSync(drizzleDir)) {
325
+ const files = await fs.readdir(drizzleDir);
326
+ const sqlFiles = files.filter(f => f.endsWith('.sql')).sort().reverse();
327
+ if (sqlFiles.length > 0) {
328
+ const latestMigration = await fs.readFile(path.join(drizzleDir, sqlFiles[0]), 'utf-8');
329
+ return latestMigration;
330
+ }
331
+ }
332
+
333
+ // Try to generate SQL
334
+ const result = await execa('npx', ['drizzle-kit', 'generate', '--sql'], {
335
+ cwd,
336
+ reject: false
337
+ });
338
+ if (result?.stdout) {
339
+ // Extract SQL from output
340
+ const sqlMatch = result.stdout.match(/```sql([\s\S]*?)```/);
341
+ if (sqlMatch) return sqlMatch[1].trim();
342
+ return result.stdout;
343
+ }
344
+ break;
345
+ }
346
+
347
+ case 'prisma': {
348
+ // Check for pending migrations
349
+ const migrationsDir = path.join(cwd, 'prisma', 'migrations');
350
+ if (fs.existsSync(migrationsDir)) {
351
+ const migrations = await fs.readdir(migrationsDir);
352
+ const sorted = migrations.filter(m => m !== 'migration_lock.toml').sort().reverse();
353
+ if (sorted.length > 0) {
354
+ const migrationPath = path.join(migrationsDir, sorted[0], 'migration.sql');
355
+ if (fs.existsSync(migrationPath)) {
356
+ return await fs.readFile(migrationPath, 'utf-8');
357
+ }
358
+ }
359
+ }
360
+ break;
361
+ }
362
+
363
+ case 'supabase': {
364
+ // Check supabase migrations folder
365
+ const migrationsDir = path.join(cwd, 'supabase', 'migrations');
366
+ if (fs.existsSync(migrationsDir)) {
367
+ const files = await fs.readdir(migrationsDir);
368
+ const sqlFiles = files.filter(f => f.endsWith('.sql')).sort().reverse();
369
+ if (sqlFiles.length > 0) {
370
+ return await fs.readFile(path.join(migrationsDir, sqlFiles[0]), 'utf-8');
371
+ }
372
+ }
373
+ break;
374
+ }
375
+ }
376
+
377
+ // Try to extract SQL from error message itself
378
+ const sqlMatch = errorOutput.match(/(CREATE|ALTER|DROP|INSERT|UPDATE|DELETE)[\s\S]+?;/gi);
379
+ if (sqlMatch) {
380
+ return sqlMatch.join('\n\n');
381
+ }
382
+
383
+ } catch {
384
+ // Silent fail
385
+ }
386
+
387
+ return null;
388
+ }
389
+
390
+ async function copyToClipboard(text: string): Promise<boolean> {
391
+ try {
392
+ // Try different clipboard methods based on OS
393
+ const platform = process.platform;
394
+
395
+ if (platform === 'win32') {
396
+ // Windows: use clip command
397
+ const proc = await execa('clip', { input: text, reject: false });
398
+ return proc.exitCode === 0;
399
+ } else if (platform === 'darwin') {
400
+ // macOS: use pbcopy
401
+ const proc = await execa('pbcopy', { input: text, reject: false });
402
+ return proc.exitCode === 0;
403
+ } else {
404
+ // Linux: try xclip or xsel
405
+ try {
406
+ const proc = await execa('xclip', ['-selection', 'clipboard'], { input: text, reject: false });
407
+ return proc.exitCode === 0;
408
+ } catch {
409
+ const proc = await execa('xsel', ['--clipboard', '--input'], { input: text, reject: false });
410
+ return proc.exitCode === 0;
411
+ }
412
+ }
413
+ } catch {
414
+ return false;
415
+ }
416
+ }
417
+
418
+ // Export for use in other commands
419
+ export { copyToClipboard, extractMigrationSQL };