@codapult/cli 0.17.2 → 0.19.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.
Files changed (63) hide show
  1. package/README.md +94 -7
  2. package/dist/commands/config-show.js +6 -9
  3. package/dist/commands/db.js +10 -36
  4. package/dist/commands/deploy.js +8 -19
  5. package/dist/commands/doctor.js +2 -7
  6. package/dist/commands/env.js +3 -11
  7. package/dist/commands/generate.js +5 -21
  8. package/dist/commands/guard.d.ts +5 -0
  9. package/dist/commands/guard.js +5 -0
  10. package/dist/commands/mcp.js +5 -16
  11. package/dist/commands/plugins.js +5 -21
  12. package/dist/commands/setup.js +2 -6
  13. package/dist/commands/update.js +2 -6
  14. package/dist/index.js +111 -5
  15. package/dist/mcp/resources.js +15 -15
  16. package/dist/mcp/server.js +6 -0
  17. package/dist/mcp/tools/db.js +11 -16
  18. package/dist/mcp/tools/deploy.js +2 -8
  19. package/dist/mcp/tools/env.js +6 -12
  20. package/dist/mcp/tools/generate.js +10 -15
  21. package/dist/mcp/tools/plugins.js +5 -11
  22. package/dist/mcp/tools/project.js +9 -30
  23. package/dist/utils/command.d.ts +3 -0
  24. package/dist/utils/command.js +35 -4
  25. package/dist/utils/config.d.ts +5 -0
  26. package/dist/utils/config.js +5 -0
  27. package/dist/utils/project-checks.d.ts +2 -0
  28. package/dist/utils/project-checks.js +2 -0
  29. package/dist/utils/project.d.ts +1 -0
  30. package/dist/utils/project.js +16 -0
  31. package/package.json +16 -5
  32. package/dist/commands/generate.test.d.ts +0 -1
  33. package/dist/commands/generate.test.js +0 -125
  34. package/dist/mcp/tools/db.test.d.ts +0 -1
  35. package/dist/mcp/tools/db.test.js +0 -221
  36. package/dist/mcp/tools/env.test.d.ts +0 -1
  37. package/dist/mcp/tools/env.test.js +0 -156
  38. package/dist/mcp/tools/project.test.d.ts +0 -1
  39. package/dist/mcp/tools/project.test.js +0 -188
  40. package/dist/utils/config-report.test.d.ts +0 -1
  41. package/dist/utils/config-report.test.js +0 -18
  42. package/dist/utils/env-compatibility.test.d.ts +0 -1
  43. package/dist/utils/env-compatibility.test.js +0 -23
  44. package/dist/utils/env-schema-parser.test.d.ts +0 -1
  45. package/dist/utils/env-schema-parser.test.js +0 -11
  46. package/dist/utils/git.test.d.ts +0 -1
  47. package/dist/utils/git.test.js +0 -77
  48. package/dist/utils/health-render.test.d.ts +0 -1
  49. package/dist/utils/health-render.test.js +0 -18
  50. package/dist/utils/live-db-diff.test.d.ts +0 -1
  51. package/dist/utils/live-db-diff.test.js +0 -29
  52. package/dist/utils/manifest.test.d.ts +0 -1
  53. package/dist/utils/manifest.test.js +0 -107
  54. package/dist/utils/patchers.test.d.ts +0 -1
  55. package/dist/utils/patchers.test.js +0 -647
  56. package/dist/utils/project-env.test.d.ts +0 -1
  57. package/dist/utils/project-env.test.js +0 -47
  58. package/dist/utils/project.test.d.ts +0 -1
  59. package/dist/utils/project.test.js +0 -123
  60. package/dist/utils/schema-parity.test.d.ts +0 -1
  61. package/dist/utils/schema-parity.test.js +0 -27
  62. package/dist/utils/schema-parser.test.d.ts +0 -1
  63. package/dist/utils/schema-parser.test.js +0 -59
@@ -2,19 +2,14 @@ import { execSync } from 'node:child_process';
2
2
  import { existsSync, readFileSync, readdirSync } from 'node:fs';
3
3
  import { resolve } from 'node:path';
4
4
  import { z } from 'zod';
5
- import { findProjectRoot, readProjectFile } from '../../utils/project.js';
5
+ import { checkProjectRoot, readProjectFile } from '../../utils/project.js';
6
6
  import { getProjectEnvOptions, loadProjectEnv } from '../../utils/project-env.js';
7
7
  import { getAdapters, getAuthMethods, getFeatures, getOauthProviders, } from '../../utils/env-config.js';
8
8
  import { envSourceSchema } from './schemas.js';
9
9
  import { commandResponse, runProjectCommand } from '../../utils/command.js';
10
+ import { runProjectChecks } from '../../utils/project-checks.js';
10
11
  import { collectMcpHealth } from '../../utils/health.js';
11
12
  import { collectAppConfigSummary } from '../../utils/config-report.js';
12
- function getRoot() {
13
- const root = findProjectRoot();
14
- if (!root)
15
- throw new Error('Not inside a Codapult project');
16
- return root;
17
- }
18
13
  export function registerProjectTools(server) {
19
14
  server.registerTool('codapult_project_status', {
20
15
  title: 'Project Status',
@@ -23,7 +18,7 @@ export function registerProjectTools(server) {
23
18
  env_source: envSourceSchema.optional(),
24
19
  },
25
20
  }, ({ env_source }) => {
26
- const root = getRoot();
21
+ const root = checkProjectRoot('throw');
27
22
  const pkg = JSON.parse(readFileSync(resolve(root, 'package.json'), 'utf-8'));
28
23
  const envContent = loadProjectEnv(root, getProjectEnvOptions(env_source)).content;
29
24
  const pluginsDir = resolve(root, 'src/plugins');
@@ -66,7 +61,7 @@ export function registerProjectTools(server) {
66
61
  title: 'Project Config',
67
62
  description: 'Read the app configuration from src/config/app.ts (brand, company)',
68
63
  }, () => {
69
- const root = getRoot();
64
+ const root = checkProjectRoot('throw');
70
65
  const content = readProjectFile(root, 'src/config/app.ts') ?? 'Config file not found';
71
66
  return { content: [{ type: 'text', text: content }] };
72
67
  });
@@ -80,25 +75,9 @@ export function registerProjectTools(server) {
80
75
  .describe('Which checks to run (default: all)'),
81
76
  },
82
77
  }, ({ checks }) => {
83
- const root = getRoot();
78
+ const root = checkProjectRoot('throw');
84
79
  const toRun = checks ?? ['lint', 'typecheck', 'test'];
85
- const commands = {
86
- lint: 'pnpm lint',
87
- typecheck: 'pnpm tsc --noEmit',
88
- test: 'pnpm test --run',
89
- };
90
- const results = {};
91
- for (const check of toRun) {
92
- const cmd = commands[check];
93
- if (!cmd)
94
- continue;
95
- try {
96
- results[check] = runProjectCommand(cmd, root);
97
- }
98
- catch {
99
- results[check] = runProjectCommand(cmd, root);
100
- }
101
- }
80
+ const results = runProjectChecks(root, toRun);
102
81
  return { content: [{ type: 'text', text: JSON.stringify(results, null, 2) }] };
103
82
  });
104
83
  server.registerTool('codapult_doctor', {
@@ -108,7 +87,7 @@ export function registerProjectTools(server) {
108
87
  env_source: envSourceSchema.optional(),
109
88
  },
110
89
  }, ({ env_source }) => {
111
- const root = getRoot();
90
+ const root = checkProjectRoot('throw');
112
91
  const report = collectMcpHealth(root, {
113
92
  envSource: env_source,
114
93
  });
@@ -119,7 +98,7 @@ export function registerProjectTools(server) {
119
98
  description: 'Get a compact, structured overview of the current Codapult project for AI-assisted work',
120
99
  inputSchema: {},
121
100
  }, () => {
122
- const root = getRoot();
101
+ const root = checkProjectRoot('throw');
123
102
  const packageJson = JSON.parse(readFileSync(resolve(root, 'package.json'), 'utf-8'));
124
103
  const files = ['AGENTS.md', '.env.example', 'src/config/app.ts', 'src/config/env.ts'];
125
104
  const existingFiles = files.filter((file) => existsSync(resolve(root, file)));
@@ -161,5 +140,5 @@ export function registerProjectTools(server) {
161
140
  title: 'Build Project',
162
141
  description: 'Run the production build and return structured stdout, stderr, and exit code',
163
142
  inputSchema: {},
164
- }, () => commandResponse(runProjectCommand('pnpm build', getRoot(), { timeout: 300_000 })));
143
+ }, () => commandResponse(runProjectCommand('pnpm build', checkProjectRoot('throw'), { timeout: 300_000 })));
165
144
  }
@@ -1,9 +1,12 @@
1
1
  export interface CommandResult {
2
2
  command: string;
3
+ status: 'passed' | 'failed' | 'not-configured';
3
4
  passed: boolean;
4
5
  exitCode: number;
5
6
  stdout: string;
6
7
  stderr: string;
8
+ timedOut?: boolean;
9
+ truncated?: boolean;
7
10
  }
8
11
  export declare function runProjectCommand(command: string, cwd: string, options?: {
9
12
  timeout?: number;
@@ -1,4 +1,18 @@
1
1
  import { execSync } from 'node:child_process';
2
+ const MAX_OUTPUT_CHARS = 20_000;
3
+ const MAX_BUFFER_BYTES = 2_000_000;
4
+ function redactOutput(value) {
5
+ return value
6
+ .replace(/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/g, '[REDACTED PRIVATE KEY]')
7
+ .replace(/\b(?:sk_(?:live|test)_|pk_(?:live|test)_|AKIA|gh[pousr]_|github_pat_)[A-Za-z0-9_-]+/g, '[REDACTED TOKEN]')
8
+ .replace(/((?:api[_-]?key|secret|token|password|authorization|database[_-]?url)\s*[:=]\s*["']?)[^\s"'`,}]+/gi, '$1[REDACTED]');
9
+ }
10
+ function captureOutput(value) {
11
+ const redacted = redactOutput(value);
12
+ return redacted.length > MAX_OUTPUT_CHARS
13
+ ? { value: `${redacted.slice(0, MAX_OUTPUT_CHARS)}\n[output truncated]`, truncated: true }
14
+ : { value: redacted, truncated: false };
15
+ }
2
16
  export function runProjectCommand(command, cwd, options = {}) {
3
17
  try {
4
18
  const stdout = execSync(command, {
@@ -6,18 +20,35 @@ export function runProjectCommand(command, cwd, options = {}) {
6
20
  env: { ...process.env, ...options.env },
7
21
  stdio: 'pipe',
8
22
  timeout: options.timeout ?? 120_000,
23
+ maxBuffer: MAX_BUFFER_BYTES,
9
24
  }).toString();
10
- return { command, passed: true, exitCode: 0, stdout, stderr: '' };
25
+ const captured = captureOutput(stdout);
26
+ return {
27
+ command,
28
+ status: 'passed',
29
+ passed: true,
30
+ exitCode: 0,
31
+ stdout: captured.value,
32
+ stderr: '',
33
+ truncated: captured.truncated,
34
+ };
11
35
  }
12
36
  catch (error) {
13
37
  const execError = error;
14
38
  const exitCode = execError.status ?? 1;
39
+ const passed = exitCode === 0;
40
+ const stdout = captureOutput(execError.stdout?.toString() ?? '');
41
+ const stderr = captureOutput(execError.stderr?.toString() ?? '');
42
+ const timedOut = execError.code === 'ETIMEDOUT' || execError.signal === 'SIGTERM';
15
43
  return {
16
44
  command,
17
- passed: exitCode === 0,
45
+ status: passed ? 'passed' : 'failed',
46
+ passed,
18
47
  exitCode,
19
- stdout: execError.stdout?.toString() ?? '',
20
- stderr: execError.stderr?.toString() ?? '',
48
+ stdout: stdout.value,
49
+ stderr: timedOut ? `${stderr.value}\n[command timed out]` : stderr.value,
50
+ timedOut,
51
+ truncated: stdout.truncated || stderr.truncated,
21
52
  };
22
53
  }
23
54
  }
@@ -0,0 +1,5 @@
1
+ export declare const config: {
2
+ readonly appName: 'codapult';
3
+ readonly commandName: 'codapult';
4
+ readonly projectName: 'Codapult';
5
+ };
@@ -0,0 +1,5 @@
1
+ export const config = {
2
+ appName: 'codapult',
3
+ commandName: 'codapult',
4
+ projectName: 'Codapult',
5
+ };
@@ -0,0 +1,2 @@
1
+ /** Shared project-check adapter; implementation belongs to codapult-guard. */
2
+ export * from '@codapult/guard/project-checks';
@@ -0,0 +1,2 @@
1
+ /** Shared project-check adapter; implementation belongs to codapult-guard. */
2
+ export * from '@codapult/guard/project-checks';
@@ -3,6 +3,7 @@
3
3
  * (directory containing package.json with codapult-specific markers).
4
4
  */
5
5
  export declare function findProjectRoot(from?: string): string | undefined;
6
+ export declare function checkProjectRoot<T extends 'exit' | 'code' | 'throw'>(exit: T): T extends 'code' ? string | undefined : string;
6
7
  /** Read and parse a JSON file, returning null on failure. */
7
8
  export declare function readJsonFile(filePath: string): Record<string, unknown> | undefined;
8
9
  /** Check if a file exists relative to the project root. */
@@ -1,5 +1,7 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
2
  import { resolve, dirname } from 'node:path';
3
+ import { fail } from './ui.js';
4
+ import { config } from './config.js';
3
5
  /**
4
6
  * Walk upward from cwd to find the Codapult project root
5
7
  * (directory containing package.json with codapult-specific markers).
@@ -27,6 +29,20 @@ export function findProjectRoot(from = process.cwd()) {
27
29
  }
28
30
  return undefined;
29
31
  }
32
+ export function checkProjectRoot(exit) {
33
+ const root = findProjectRoot();
34
+ if (!root) {
35
+ const msg = `Not inside a ${config.projectName} project.`;
36
+ if (exit === 'throw')
37
+ throw new Error(msg);
38
+ fail(msg);
39
+ if (exit === 'exit')
40
+ process.exit(1);
41
+ else if (exit === 'code')
42
+ process.exitCode = 1;
43
+ }
44
+ return root;
45
+ }
30
46
  /** Read and parse a JSON file, returning null on failure. */
31
47
  export function readJsonFile(filePath) {
32
48
  try {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@codapult/cli",
3
- "version": "0.17.2",
4
- "description": "Codapult CLI — manage, update, and diagnose your Codapult SaaS project",
3
+ "version": "0.19.0",
4
+ "description": "Open-source CLI and MCP server for Codapult SaaS projects, with architecture guardrails for AI-assisted development",
5
5
  "license": "MIT",
6
6
  "packageManager": "pnpm@11.22.0+sha512.1ff870c4c6133dfd88fb2afc46dd13d47f09c9794b438c6fdb47ca98caf3bc16381ee0be93a091b8e3824cf01f889f46d7d9e20910fb0be1ab0fb5baa80dd621",
7
7
  "engines": {
@@ -15,16 +15,19 @@
15
15
  "dist"
16
16
  ],
17
17
  "scripts": {
18
- "build": "tsc",
18
+ "clean": "node scripts/clean-dist.mjs",
19
+ "build": "pnpm clean && tsc -p tsconfig.build.json",
19
20
  "dev": "tsc --watch",
20
21
  "lint": "eslint .",
21
22
  "lint:fix": "eslint --fix .",
22
23
  "format": "prettier --write .",
23
24
  "format:check": "prettier --check .",
25
+ "release:check": "pnpm lint && pnpm format:check && pnpm typecheck && pnpm test && pnpm build && npm pack --dry-run",
24
26
  "test": "vitest run",
27
+ "test:coverage": "vitest run --coverage",
25
28
  "test:watch": "vitest",
26
29
  "typecheck": "tsc --noEmit",
27
- "prepublishOnly": "tsc",
30
+ "prepublishOnly": "tsc -p tsconfig.build.json",
28
31
  "release": "release-it"
29
32
  },
30
33
  "keywords": [
@@ -32,7 +35,13 @@
32
35
  "saas",
33
36
  "boilerplate",
34
37
  "cli",
35
- "nextjs"
38
+ "nextjs",
39
+ "mcp",
40
+ "ai-agents",
41
+ "architecture",
42
+ "guardrails",
43
+ "drizzle",
44
+ "deployment"
36
45
  ],
37
46
  "homepage": "https://codapult.dev",
38
47
  "repository": {
@@ -44,6 +53,7 @@
44
53
  },
45
54
  "dependencies": {
46
55
  "@modelcontextprotocol/sdk": "^1.30.0",
56
+ "@codapult/guard": "^0.1.0",
47
57
  "commander": "^15.0.0",
48
58
  "picocolors": "^1.1.1",
49
59
  "typescript": "npm:@typescript/typescript6@^6.0.2",
@@ -57,6 +67,7 @@
57
67
  "@release-it/conventional-changelog": "^12.0.0",
58
68
  "@types/node": "^26.2.0",
59
69
  "@typescript/native": "npm:typescript@^7.0.2",
70
+ "@vitest/coverage-v8": "^4.1.11",
60
71
  "eslint": "^9.39.4",
61
72
  "eslint-config-prettier": "^10.1.8",
62
73
  "eslint-plugin-prettier": "^5.5.6",
@@ -1 +0,0 @@
1
- export {};
@@ -1,125 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach } from 'vitest';
2
- vi.mock('node:fs');
3
- vi.mock('../utils/project.js', () => ({
4
- findProjectRoot: vi.fn(),
5
- }));
6
- vi.mock('../utils/ui.js', () => ({
7
- heading: vi.fn(),
8
- success: vi.fn(),
9
- fail: vi.fn(),
10
- info: vi.fn(),
11
- dim: vi.fn(),
12
- }));
13
- const { existsSync, writeFileSync, mkdirSync } = await import('node:fs');
14
- const { findProjectRoot } = await import('../utils/project.js');
15
- const { generatePageCommand, generateApiCommand, generateActionCommand, generatePluginCommand } = await import('./generate.js');
16
- const mockedFindRoot = vi.mocked(findProjectRoot);
17
- const mockedExists = vi.mocked(existsSync);
18
- const mockedWrite = vi.mocked(writeFileSync);
19
- const mockedMkdir = vi.mocked(mkdirSync);
20
- beforeEach(() => {
21
- vi.resetAllMocks();
22
- vi.spyOn(process, 'exit').mockImplementation(() => {
23
- throw new Error('process.exit');
24
- });
25
- });
26
- describe('generatePageCommand', () => {
27
- it('generates a dashboard page file with correct naming', () => {
28
- mockedFindRoot.mockReturnValue('/project');
29
- mockedExists.mockReturnValue(false);
30
- generatePageCommand('userSettings');
31
- expect(mockedMkdir).toHaveBeenCalled();
32
- expect(mockedWrite).toHaveBeenCalledTimes(1);
33
- const [path, content] = mockedWrite.mock.calls[0];
34
- expect(path).toContain('user-settings/page.tsx');
35
- expect(content).toContain('UserSettingsPage');
36
- expect(content).toContain("title: 'User Settings — Codapult'");
37
- expect(content).toContain('getAppSession');
38
- });
39
- it('converts camelCase to kebab-case in path', () => {
40
- mockedFindRoot.mockReturnValue('/project');
41
- mockedExists.mockReturnValue(false);
42
- generatePageCommand('myDashboard');
43
- const [path] = mockedWrite.mock.calls[0];
44
- expect(path).toContain('my-dashboard/page.tsx');
45
- });
46
- it('does not overwrite existing page', () => {
47
- mockedFindRoot.mockReturnValue('/project');
48
- mockedExists.mockReturnValue(true);
49
- generatePageCommand('analytics');
50
- expect(mockedWrite).not.toHaveBeenCalled();
51
- });
52
- it('exits when not in a Codapult project', () => {
53
- mockedFindRoot.mockReturnValue(undefined);
54
- expect(() => generatePageCommand('test')).toThrow('process.exit');
55
- expect(process.exit).toHaveBeenCalledWith(1);
56
- });
57
- });
58
- describe('generateApiCommand', () => {
59
- it('generates an API route with auth and rate limiting', () => {
60
- mockedFindRoot.mockReturnValue('/project');
61
- mockedExists.mockReturnValue(false);
62
- generateApiCommand('webhooks');
63
- const [path, content] = mockedWrite.mock.calls[0];
64
- expect(path).toContain('api/webhooks/route.ts');
65
- expect(content).toContain('getAppSession');
66
- expect(content).toContain('checkRateLimit');
67
- expect(content).toContain('webhooksSchema');
68
- expect(content).toContain('export async function GET()');
69
- expect(content).toContain('export async function POST(req: Request)');
70
- });
71
- it('converts multi-word names to kebab-case', () => {
72
- mockedFindRoot.mockReturnValue('/project');
73
- mockedExists.mockReturnValue(false);
74
- generateApiCommand('userBilling');
75
- const [path, content] = mockedWrite.mock.calls[0];
76
- expect(path).toContain('api/user-billing/route.ts');
77
- expect(content).toContain('userBillingSchema');
78
- });
79
- });
80
- describe('generateActionCommand', () => {
81
- it('generates a server action file', () => {
82
- mockedFindRoot.mockReturnValue('/project');
83
- mockedExists.mockReturnValue(false);
84
- generateActionCommand('updateProfile');
85
- const [path, content] = mockedWrite.mock.calls[0];
86
- expect(path).toContain('actions/update-profile.ts');
87
- expect(content).toContain("'use server'");
88
- expect(content).toContain('updateProfileSchema');
89
- expect(content).toContain('updateProfileAction');
90
- expect(content).toContain('getAppSession');
91
- expect(content).toContain('checkRateLimit');
92
- expect(content).toContain("revalidatePath('/dashboard/update-profile')");
93
- });
94
- });
95
- describe('generatePluginCommand', () => {
96
- it('scaffolds a complete plugin directory', () => {
97
- mockedFindRoot.mockReturnValue('/project');
98
- mockedExists.mockReturnValue(false);
99
- generatePluginCommand('my-widget');
100
- // package.json, tsconfig.json, src/index.ts, codapult-plugin.json, .gitignore, README.md
101
- expect(mockedWrite).toHaveBeenCalledTimes(6);
102
- expect(mockedMkdir).toHaveBeenCalled();
103
- const writtenPaths = mockedWrite.mock.calls.map(([p]) => p);
104
- expect(writtenPaths.some((p) => p.includes('package.json'))).toBe(true);
105
- expect(writtenPaths.some((p) => p.includes('src/index.ts'))).toBe(true);
106
- expect(writtenPaths.some((p) => p.includes('codapult-plugin.json'))).toBe(true);
107
- });
108
- it('generates correct plugin name references', () => {
109
- mockedFindRoot.mockReturnValue('/project');
110
- mockedExists.mockReturnValue(false);
111
- generatePluginCommand('dataSync');
112
- const indexWrite = mockedWrite.mock.calls.find(([p]) => p.includes('src/index.ts'));
113
- expect(indexWrite).toBeDefined();
114
- const content = indexWrite[1];
115
- expect(content).toContain('dataSyncPlugin');
116
- expect(content).toContain("name: 'data-sync'");
117
- expect(content).toContain("label: 'DataSync'");
118
- });
119
- it('exits when target directory already exists', () => {
120
- mockedFindRoot.mockReturnValue('/project');
121
- mockedExists.mockReturnValue(true);
122
- expect(() => generatePluginCommand('existing')).toThrow('process.exit');
123
- expect(process.exit).toHaveBeenCalledWith(1);
124
- });
125
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,221 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach } from 'vitest';
2
- import { ENV_FILE_NAME } from '../../utils/project-env.js';
3
- vi.mock('node:fs');
4
- vi.mock('node:child_process');
5
- vi.mock('../../utils/project.js', () => ({
6
- findProjectRoot: vi.fn(),
7
- readProjectFile: vi.fn(),
8
- }));
9
- const { existsSync, readdirSync } = await import('node:fs');
10
- const { findProjectRoot, readProjectFile } = await import('../../utils/project.js');
11
- const { registerDbTools } = await import('./db.js');
12
- const mockedFindRoot = vi.mocked(findProjectRoot);
13
- const mockedReadProject = vi.mocked(readProjectFile);
14
- const mockedExists = vi.mocked(existsSync);
15
- const mockedReaddir = vi.mocked(readdirSync);
16
- beforeEach(() => {
17
- vi.resetAllMocks();
18
- mockedFindRoot.mockReturnValue('/project');
19
- });
20
- function createMockServer() {
21
- const tools = [];
22
- const registerTool = vi.fn((name, _opts, handler) => {
23
- tools.push({ name, handler });
24
- });
25
- return { registerTool, tools };
26
- }
27
- describe('registerDbTools', () => {
28
- it('registers database inspection and mutation tools', () => {
29
- const server = createMockServer();
30
- registerDbTools(server);
31
- expect(server.tools).toHaveLength(9);
32
- expect(server.tools.map((t) => t.name)).toEqual([
33
- 'codapult_db_generate',
34
- 'codapult_db_migration_diff',
35
- 'codapult_db_push',
36
- 'codapult_db_seed',
37
- 'codapult_db_get_tables',
38
- 'codapult_db_get_table_info',
39
- 'codapult_db_status',
40
- 'codapult_db_live_diff',
41
- 'codapult_db_schema_diff',
42
- ]);
43
- });
44
- describe('codapult_db_get_tables', () => {
45
- it('parses schema and returns table summary', () => {
46
- const server = createMockServer();
47
- registerDbTools(server);
48
- const schema = `
49
- import { sqliteTable, text, integer } from 'drizzle-orm/sqlite-core';
50
-
51
- export const user = sqliteTable('user', {
52
- id: text('id').primaryKey(),
53
- name: text('name').notNull(),
54
- age: integer('age'),
55
- });
56
-
57
- export const post = sqliteTable('post', {
58
- id: text('id').primaryKey(),
59
- title: text('title').notNull(),
60
- userId: text('user_id').references(() => user.id),
61
- });
62
- `;
63
- mockedReadProject.mockReturnValue(schema);
64
- const handler = server.tools.find((t) => t.name === 'codapult_db_get_tables').handler;
65
- const result = handler({});
66
- const parsed = JSON.parse(result.content[0].text);
67
- expect(parsed.provider).toBe('turso');
68
- expect(parsed.schemaPath).toBe('src/lib/db/schema.ts');
69
- expect(parsed.tables).toHaveLength(2);
70
- expect(parsed.tables[0].name).toBe('user');
71
- expect(parsed.tables[0].columns).toBe(3);
72
- expect(parsed.tables[1].name).toBe('post');
73
- expect(parsed.tables[1].columns).toBe(3);
74
- });
75
- it('returns error when schema file not found', () => {
76
- const server = createMockServer();
77
- registerDbTools(server);
78
- mockedReadProject.mockReturnValue(undefined);
79
- const handler = server.tools.find((t) => t.name === 'codapult_db_get_tables').handler;
80
- const result = handler({});
81
- expect(result.isError).toBe(true);
82
- expect(result.content[0].text).toContain('not found');
83
- });
84
- });
85
- describe('codapult_db_get_table_info', () => {
86
- it('returns detailed info for a specific table', () => {
87
- const server = createMockServer();
88
- registerDbTools(server);
89
- const schema = `
90
- export const user = sqliteTable('user', {
91
- id: text('id').primaryKey(),
92
- email: text('email').notNull().unique(),
93
- createdAt: integer('created_at').$defaultFn(() => new Date()),
94
- });
95
- `;
96
- mockedReadProject.mockReturnValue(schema);
97
- const handler = server.tools.find((t) => t.name === 'codapult_db_get_table_info').handler;
98
- const result = handler({ table: 'user' });
99
- const parsed = JSON.parse(result.content[0].text);
100
- expect(parsed.name).toBe('user');
101
- expect(parsed.columns).toHaveLength(3);
102
- const idCol = parsed.columns.find((c) => c.name === 'id');
103
- expect(idCol.type).toBe('text');
104
- expect(idCol.constraints).toContain('PRIMARY KEY');
105
- const emailCol = parsed.columns.find((c) => c.name === 'email');
106
- expect(emailCol.constraints).toContain('NOT NULL');
107
- expect(emailCol.constraints).toContain('UNIQUE');
108
- const createdAtCol = parsed.columns.find((c) => c.name === 'createdAt');
109
- expect(createdAtCol.constraints).toContain('DEFAULT');
110
- });
111
- it('returns error for non-existent table', () => {
112
- const server = createMockServer();
113
- registerDbTools(server);
114
- const schema = `export const user = sqliteTable('user', { id: text('id') });`;
115
- mockedReadProject.mockReturnValue(schema);
116
- const handler = server.tools.find((t) => t.name === 'codapult_db_get_table_info').handler;
117
- const result = handler({ table: 'nonexistent' });
118
- expect(result.isError).toBe(true);
119
- expect(result.content[0].text).toContain('not found');
120
- expect(result.content[0].text).toContain('user');
121
- });
122
- });
123
- describe('codapult_db_status', () => {
124
- it('returns provider, table count, and migration counts', () => {
125
- const server = createMockServer();
126
- registerDbTools(server);
127
- const envContent = 'DB_PROVIDER=turso\nOTHER=val';
128
- const schema = `export const user = sqliteTable('user', { id: text('id') });`;
129
- mockedReadProject.mockImplementation((_root, path) => {
130
- if (path === ENV_FILE_NAME)
131
- return envContent;
132
- if (path === 'src/lib/db/schema.ts')
133
- return schema;
134
- return undefined;
135
- });
136
- mockedExists.mockReturnValue(true);
137
- mockedReaddir.mockReturnValue(['0001.sql', '0002.sql', 'meta']);
138
- const handler = server.tools.find((t) => t.name === 'codapult_db_status').handler;
139
- const result = handler({});
140
- const parsed = JSON.parse(result.content[0].text);
141
- expect(parsed.provider).toBe('turso');
142
- expect(parsed.tableCount).toBe(1);
143
- expect(parsed.sqliteMigrations).toBe(2);
144
- });
145
- it('defaults provider to turso when not set', () => {
146
- const server = createMockServer();
147
- registerDbTools(server);
148
- mockedReadProject.mockImplementation((_root, path) => {
149
- if (path === ENV_FILE_NAME)
150
- return '';
151
- if (path === 'src/lib/db/schema.ts')
152
- return '';
153
- return undefined;
154
- });
155
- mockedExists.mockReturnValue(false);
156
- const handler = server.tools.find((t) => t.name === 'codapult_db_status').handler;
157
- const result = handler({});
158
- const parsed = JSON.parse(result.content[0].text);
159
- expect(parsed.provider).toBe('turso');
160
- });
161
- it('can read provider from process env', () => {
162
- const server = createMockServer();
163
- registerDbTools(server);
164
- vi.stubEnv('DB_PROVIDER', 'postgres');
165
- mockedReadProject.mockImplementation((_root, path) => {
166
- if (path === 'src/lib/db/schema.ts')
167
- return '';
168
- return undefined;
169
- });
170
- mockedExists.mockReturnValue(false);
171
- const handler = server.tools.find((t) => t.name === 'codapult_db_status').handler;
172
- const result = handler({ env_source: 'process' });
173
- const parsed = JSON.parse(result.content[0].text);
174
- expect(parsed.provider).toBe('postgres');
175
- });
176
- });
177
- describe('codapult_db_schema_diff', () => {
178
- it('returns an ok parity report for matching schemas', () => {
179
- const server = createMockServer();
180
- registerDbTools(server);
181
- const sqlite = `export const user = sqliteTable('user', { id: text('id') });`;
182
- const postgres = `export const user = pgTable('user', { id: text('id') });`;
183
- mockedReadProject.mockImplementation((_root, path) => {
184
- if (path === 'src/lib/db/schema.ts')
185
- return sqlite;
186
- if (path === 'src/lib/db/schema-pg.ts')
187
- return postgres;
188
- return undefined;
189
- });
190
- const handler = server.tools.find((t) => t.name === 'codapult_db_schema_diff').handler;
191
- const result = handler({});
192
- const parsed = JSON.parse(result.content[0].text);
193
- expect(result.isError).toBe(false);
194
- expect(parsed.status).toBe('ok');
195
- expect(parsed.identical).toBe(true);
196
- expect(parsed.differences).toEqual([]);
197
- });
198
- it('returns an error result for missing tables', () => {
199
- const server = createMockServer();
200
- registerDbTools(server);
201
- mockedReadProject.mockImplementation((_root, path) => {
202
- if (path === 'src/lib/db/schema.ts') {
203
- return `export const user = sqliteTable('user', { id: text('id') });`;
204
- }
205
- if (path === 'src/lib/db/schema-pg.ts') {
206
- return `export const post = pgTable('post', { id: text('id') });`;
207
- }
208
- return undefined;
209
- });
210
- const handler = server.tools.find((t) => t.name === 'codapult_db_schema_diff').handler;
211
- const result = handler({});
212
- const parsed = JSON.parse(result.content[0].text);
213
- expect(result.isError).toBe(true);
214
- expect(parsed.status).toBe('fail');
215
- expect(parsed.differences.map((difference) => difference.issue)).toEqual([
216
- 'missing_in_postgres',
217
- 'missing_in_sqlite',
218
- ]);
219
- });
220
- });
221
- });
@@ -1 +0,0 @@
1
- export {};