@codapult/cli 0.4.1 → 0.5.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.
package/dist/index.js CHANGED
@@ -10,6 +10,7 @@ import { generatePageCommand, generateApiCommand, generateActionCommand, generat
10
10
  import { dbPushCommand, dbGenerateCommand, dbSeedCommand, dbStudioCommand, dbStatusCommand, } from './commands/db.js';
11
11
  import { envCheckCommand, envSyncCommand } from './commands/env.js';
12
12
  import { deployVercelCommand, deployDockerCommand, deployStatusCommand, } from './commands/deploy.js';
13
+ import { ENV_EXAMPLE_FILE_NAME, ENV_FILE_NAME } from './utils/project-env.js';
13
14
  const program = new Command()
14
15
  .name('codapult')
15
16
  .description('Codapult CLI — manage your SaaS project')
@@ -19,11 +20,15 @@ const program = new Command()
19
20
  styleCommandText: (str) => pc.yellow(str),
20
21
  styleOptionText: (str) => pc.green(str),
21
22
  });
23
+ function withNoEnvFileOption(command) {
24
+ return command.option('--no-env-file', `read env vars from process.env instead of ${ENV_FILE_NAME}`);
25
+ }
22
26
  program
23
27
  .commandsGroup('Project')
24
28
  .command('setup')
25
29
  .description('interactive project setup wizard (or non-interactive with --preset)')
26
30
  .option('--preset <value>', 'apply a preset non-interactively (name, key=value pairs, or both)')
31
+ .option('--no-env-file', `do not create ${ENV_FILE_NAME}; read env vars from process.env instead`)
27
32
  .action(setupCommand);
28
33
  program
29
34
  .command('update [version]')
@@ -31,25 +36,18 @@ program
31
36
  .option('--dry-run', 'show what would change without applying')
32
37
  .option('--list', 'list available versions')
33
38
  .action(updateCommand);
34
- program
35
- .command('doctor')
36
- .description('check project health and configuration')
37
- .action(doctorCommand);
38
- program
39
- .command('config')
40
- .description('show current project configuration')
41
- .action(configShowCommand);
39
+ withNoEnvFileOption(program.command('doctor').description('check project health and configuration')).action(doctorCommand);
40
+ withNoEnvFileOption(program.command('config').description('show current project configuration')).action(configShowCommand);
42
41
  const plugins = program
43
42
  .commandsGroup('Plugins')
44
43
  .command('plugins')
45
44
  .description('manage Codapult plugins');
46
- plugins
45
+ withNoEnvFileOption(plugins
47
46
  .command('add <name>')
48
47
  .description('install a plugin (local or remote)')
49
48
  .option('--from <url>', 'git URL to clone the plugin from')
50
- .option('--ci', 'CI/Vercel mode: skip pnpm install, db:push, env patching, and interactive prompts')
51
- .action(pluginsAddCommand);
52
- plugins.command('remove <name>').description('uninstall a plugin').action(pluginsRemoveCommand);
49
+ .option('--ci', 'CI/Vercel mode: skip pnpm install, db:push, env patching, and interactive prompts')).action(pluginsAddCommand);
50
+ withNoEnvFileOption(plugins.command('remove <name>').description('uninstall a plugin')).action(pluginsRemoveCommand);
53
51
  plugins
54
52
  .command('migrate [name]')
55
53
  .description('update plugin schema and generate DB migration')
@@ -78,25 +76,21 @@ const db = program
78
76
  .commandsGroup('Infrastructure')
79
77
  .command('db')
80
78
  .description('database management (Drizzle ORM)');
81
- db.command('push').description('apply schema to database').action(dbPushCommand);
82
- db.command('generate').description('generate migration files').action(dbGenerateCommand);
83
- db.command('seed').description('seed sample data').action(dbSeedCommand);
84
- db.command('studio').description('open Drizzle Studio').action(dbStudioCommand);
85
- db.command('status').description('show schema info and migration count').action(dbStatusCommand);
79
+ withNoEnvFileOption(db.command('push').description('apply schema to database')).action(dbPushCommand);
80
+ withNoEnvFileOption(db.command('generate').description('generate migration files')).action(dbGenerateCommand);
81
+ withNoEnvFileOption(db.command('seed').description('seed sample data')).action(dbSeedCommand);
82
+ withNoEnvFileOption(db.command('studio').description('open Drizzle Studio')).action(dbStudioCommand);
83
+ withNoEnvFileOption(db.command('status').description('show schema info and migration count')).action(dbStatusCommand);
86
84
  const env = program.command('env').description('environment variable management');
87
- env
88
- .command('check')
89
- .description('validate .env.local against .env.example')
90
- .action(envCheckCommand);
91
- env.command('sync').description('add missing variables from .env.example').action(envSyncCommand);
85
+ withNoEnvFileOption(env.command('check').description(`validate env vars against ${ENV_EXAMPLE_FILE_NAME}`)).action(envCheckCommand);
86
+ withNoEnvFileOption(env.command('sync').description(`add missing variables from ${ENV_EXAMPLE_FILE_NAME}`)).action(envSyncCommand);
92
87
  const deploy = program.command('deploy').description('deployment helpers');
93
- deploy.command('vercel').description('build and deploy to Vercel').action(deployVercelCommand);
94
- deploy
88
+ withNoEnvFileOption(deploy.command('vercel').description('build and deploy to Vercel')).action(deployVercelCommand);
89
+ withNoEnvFileOption(deploy
95
90
  .command('docker')
96
91
  .description('build Docker image')
97
- .option('-t, --tag <tag>', 'image tag', 'latest')
98
- .action(deployDockerCommand);
99
- deploy.command('status').description('check deploy readiness').action(deployStatusCommand);
92
+ .option('-t, --tag <tag>', 'image tag', 'latest')).action(deployDockerCommand);
93
+ withNoEnvFileOption(deploy.command('status').description('check deploy readiness')).action(deployStatusCommand);
100
94
  program
101
95
  .commandsGroup('AI Integration')
102
96
  .command('mcp-server')
@@ -1,4 +1,5 @@
1
1
  import { findProjectRoot, readProjectFile } from '../utils/project.js';
2
+ import { ENV_EXAMPLE_FILE_NAME, ENV_FILE_NAME } from '../utils/project-env.js';
2
3
  function getRoot() {
3
4
  const root = findProjectRoot();
4
5
  if (!root)
@@ -16,7 +17,7 @@ export function registerResources(server) {
16
17
  });
17
18
  server.registerResource('codapult_app_config', 'codapult://config/app', {
18
19
  title: 'App Configuration',
19
- description: 'Application config (src/config/app.ts) — brand, AI, payments, company. Feature toggles and auth methods live in .env.local (read via codapult://env-example or codapult_project_status).',
20
+ description: `Application config (src/config/app.ts) — brand, AI, payments, company. Feature toggles and auth methods live in the project env source (${ENV_FILE_NAME} or process.env) and can be inspected via codapult://env-example or codapult_project_status.`,
20
21
  mimeType: 'text/plain',
21
22
  }, () => {
22
23
  const content = readProjectFile(getRoot(), 'src/config/app.ts') ?? 'Config file not found';
@@ -33,11 +34,11 @@ export function registerResources(server) {
33
34
  return { contents: [{ uri: 'codapult://agents', text: content, mimeType: 'text/markdown' }] };
34
35
  });
35
36
  server.registerResource('codapult_env_example', 'codapult://env-example', {
36
- title: '.env.example',
37
+ title: ENV_EXAMPLE_FILE_NAME,
37
38
  description: 'Environment variable template with descriptions and defaults',
38
39
  mimeType: 'text/plain',
39
40
  }, () => {
40
- const content = readProjectFile(getRoot(), '.env.example') ?? '.env.example not found';
41
+ const content = readProjectFile(getRoot(), ENV_EXAMPLE_FILE_NAME) ?? `${ENV_EXAMPLE_FILE_NAME} not found`;
41
42
  return {
42
43
  contents: [{ uri: 'codapult://env-example', text: content, mimeType: 'text/plain' }],
43
44
  };
@@ -2,6 +2,7 @@ import { existsSync, readdirSync } from 'node:fs';
2
2
  import { resolve } from 'node:path';
3
3
  import { z } from 'zod';
4
4
  import { findProjectRoot, readProjectFile } from '../../utils/project.js';
5
+ import { loadProjectEnv } from '../../utils/project-env.js';
5
6
  function getRoot() {
6
7
  const root = findProjectRoot();
7
8
  if (!root)
@@ -104,7 +105,7 @@ export function registerDbTools(server) {
104
105
  inputSchema: {},
105
106
  }, () => {
106
107
  const root = getRoot();
107
- const envContent = readProjectFile(root, '.env.local') ?? '';
108
+ const envContent = loadProjectEnv(root).content;
108
109
  const providerMatch = /^DB_PROVIDER\s*=\s*"?(\w+)"?/m.exec(envContent);
109
110
  const provider = providerMatch?.[1] ?? 'turso';
110
111
  const schemaContent = readProjectFile(root, 'src/lib/db/schema.ts') ?? '';
@@ -1,4 +1,5 @@
1
1
  import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import { ENV_FILE_NAME } from '../../utils/project-env.js';
2
3
  vi.mock('node:fs');
3
4
  vi.mock('node:child_process');
4
5
  vi.mock('../../utils/project.js', () => ({
@@ -118,7 +119,7 @@ export const user = sqliteTable('user', {
118
119
  const envContent = 'DB_PROVIDER=turso\nOTHER=val';
119
120
  const schema = `export const user = sqliteTable('user', { id: text('id') });`;
120
121
  mockedReadProject.mockImplementation((_root, path) => {
121
- if (path === '.env.local')
122
+ if (path === ENV_FILE_NAME)
122
123
  return envContent;
123
124
  if (path === 'src/lib/db/schema.ts')
124
125
  return schema;
@@ -137,7 +138,7 @@ export const user = sqliteTable('user', {
137
138
  const server = createMockServer();
138
139
  registerDbTools(server);
139
140
  mockedReadProject.mockImplementation((_root, path) => {
140
- if (path === '.env.local')
141
+ if (path === ENV_FILE_NAME)
141
142
  return '';
142
143
  if (path === 'src/lib/db/schema.ts')
143
144
  return '';
@@ -1,6 +1,7 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
2
  import { resolve } from 'node:path';
3
3
  import { findProjectRoot } from '../../utils/project.js';
4
+ import { ENV_FILE_NAME } from '../../utils/project-env.js';
4
5
  function getRoot() {
5
6
  const root = findProjectRoot();
6
7
  if (!root)
@@ -21,7 +22,7 @@ export function registerDeployTools(server) {
21
22
  { name: 'Terraform (AWS)', path: 'infra/terraform/main.tf' },
22
23
  { name: 'Pulumi (AWS)', path: 'infra/pulumi/index.ts' },
23
24
  { name: 'Helm chart', path: 'infra/helm/codapult/Chart.yaml' },
24
- { name: '.env.local', path: '.env.local' },
25
+ { name: ENV_FILE_NAME, path: ENV_FILE_NAME },
25
26
  ].map(({ name, path }) => ({
26
27
  name,
27
28
  found: existsSync(resolve(root, path)),
@@ -2,6 +2,7 @@ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
2
2
  import { resolve } from 'node:path';
3
3
  import { z } from 'zod';
4
4
  import { findProjectRoot, readProjectFile } from '../../utils/project.js';
5
+ import { ENV_EXAMPLE_FILE_NAME, ENV_FILE_NAME } from '../../utils/project-env.js';
5
6
  function getRoot() {
6
7
  const root = findProjectRoot();
7
8
  if (!root)
@@ -46,14 +47,14 @@ const ENV_KEY_REGEX = /^[A-Z][A-Z0-9_]*$/;
46
47
  export function registerEnvTools(server) {
47
48
  server.registerTool('codapult_env_schema', {
48
49
  title: 'Env Schema',
49
- description: 'Get all environment variables from .env.example with descriptions and default values',
50
+ description: `Get all environment variables from ${ENV_EXAMPLE_FILE_NAME} with descriptions and default values`,
50
51
  inputSchema: {},
51
52
  }, () => {
52
53
  const root = getRoot();
53
- const content = readProjectFile(root, '.env.example');
54
+ const content = readProjectFile(root, ENV_EXAMPLE_FILE_NAME);
54
55
  if (!content)
55
56
  return {
56
- content: [{ type: 'text', text: '.env.example not found' }],
57
+ content: [{ type: 'text', text: `${ENV_EXAMPLE_FILE_NAME} not found` }],
57
58
  isError: true,
58
59
  };
59
60
  const entries = parseEnvFile(content);
@@ -61,7 +62,7 @@ export function registerEnvTools(server) {
61
62
  });
62
63
  server.registerTool('codapult_env_read', {
63
64
  title: 'Read Env',
64
- description: 'Read current .env.local values with validation status against .env.example. Sensitive values (keys containing SECRET, KEY, TOKEN, PASSWORD, CREDENTIAL) are masked by default.',
65
+ description: `Read current ${ENV_FILE_NAME} values with validation status against ${ENV_EXAMPLE_FILE_NAME}. Sensitive values (keys containing SECRET, KEY, TOKEN, PASSWORD, CREDENTIAL) are masked by default.`,
65
66
  inputSchema: {
66
67
  show_secrets: z
67
68
  .boolean()
@@ -70,13 +71,13 @@ export function registerEnvTools(server) {
70
71
  },
71
72
  }, ({ show_secrets }) => {
72
73
  const root = getRoot();
73
- const localContent = readProjectFile(root, '.env.local');
74
+ const localContent = readProjectFile(root, ENV_FILE_NAME);
74
75
  if (!localContent)
75
76
  return {
76
- content: [{ type: 'text', text: '.env.local not found' }],
77
+ content: [{ type: 'text', text: `${ENV_FILE_NAME} not found` }],
77
78
  isError: true,
78
79
  };
79
- const exampleContent = readProjectFile(root, '.env.example') ?? '';
80
+ const exampleContent = readProjectFile(root, ENV_EXAMPLE_FILE_NAME) ?? '';
80
81
  const localEntries = parseEnvFile(localContent);
81
82
  const exampleEntries = parseEnvFile(exampleContent);
82
83
  const localKeys = new Set(localEntries.map((e) => e.key));
@@ -102,7 +103,7 @@ export function registerEnvTools(server) {
102
103
  });
103
104
  server.registerTool('codapult_env_update', {
104
105
  title: 'Update Env Variable',
105
- description: 'Update or add a single environment variable in .env.local',
106
+ description: `Update or add a single environment variable in ${ENV_FILE_NAME}`,
106
107
  inputSchema: {
107
108
  key: z.string().describe('Variable name (e.g. "STRIPE_SECRET_KEY")'),
108
109
  value: z.string().describe('Variable value'),
@@ -120,10 +121,10 @@ export function registerEnvTools(server) {
120
121
  };
121
122
  }
122
123
  const root = getRoot();
123
- const envPath = resolve(root, '.env.local');
124
+ const envPath = resolve(root, ENV_FILE_NAME);
124
125
  if (!existsSync(envPath)) {
125
126
  return {
126
- content: [{ type: 'text', text: '.env.local not found' }],
127
+ content: [{ type: 'text', text: `${ENV_FILE_NAME} not found` }],
127
128
  isError: true,
128
129
  };
129
130
  }
@@ -138,6 +139,6 @@ export function registerEnvTools(server) {
138
139
  content = content.trimEnd() + `\n${line}\n`;
139
140
  }
140
141
  writeFileSync(envPath, content, 'utf-8');
141
- return { content: [{ type: 'text', text: `Updated ${key} in .env.local` }] };
142
+ return { content: [{ type: 'text', text: `Updated ${key} in ${ENV_FILE_NAME}` }] };
142
143
  });
143
144
  }
@@ -1,4 +1,5 @@
1
1
  import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import { ENV_EXAMPLE_FILE_NAME, ENV_FILE_NAME } from '../../utils/project-env.js';
2
3
  vi.mock('node:fs');
3
4
  vi.mock('../../utils/project.js', () => ({
4
5
  findProjectRoot: vi.fn(),
@@ -35,7 +36,7 @@ describe('registerEnvTools', () => {
35
36
  ]);
36
37
  });
37
38
  describe('codapult_env_schema', () => {
38
- it('parses .env.example entries with comments', () => {
39
+ it(`parses ${ENV_EXAMPLE_FILE_NAME} entries with comments`, () => {
39
40
  const server = createMockServer();
40
41
  registerEnvTools(server);
41
42
  const envExample = `# Auth provider
@@ -59,7 +60,7 @@ DATABASE_URL=sqlite://local.db
59
60
  expect(dbEntry.value).toBe('sqlite://local.db');
60
61
  expect(dbEntry.comment).toBe('Optional database URL');
61
62
  });
62
- it('returns error when .env.example not found', () => {
63
+ it(`returns error when ${ENV_EXAMPLE_FILE_NAME} not found`, () => {
63
64
  const server = createMockServer();
64
65
  registerEnvTools(server);
65
66
  mockedReadProject.mockReturnValue(null);
@@ -75,9 +76,9 @@ DATABASE_URL=sqlite://local.db
75
76
  const envLocal = `AUTH_PROVIDER=better-auth\nSTRIPE_SECRET_KEY=your-key-here\n`;
76
77
  const envExample = `AUTH_PROVIDER=better-auth\nSTRIPE_SECRET_KEY=\nDATABASE_URL=\n`;
77
78
  mockedReadProject.mockImplementation((_root, path) => {
78
- if (path === '.env.local')
79
+ if (path === ENV_FILE_NAME)
79
80
  return envLocal;
80
- if (path === '.env.example')
81
+ if (path === ENV_EXAMPLE_FILE_NAME)
81
82
  return envExample;
82
83
  return null;
83
84
  });
@@ -87,7 +88,7 @@ DATABASE_URL=sqlite://local.db
87
88
  expect(parsed.missing).toContain('DATABASE_URL');
88
89
  expect(parsed.unconfigured).toContain('STRIPE_SECRET_KEY');
89
90
  });
90
- it('returns error when .env.local not found', () => {
91
+ it(`returns error when ${ENV_FILE_NAME} not found`, () => {
91
92
  const server = createMockServer();
92
93
  registerEnvTools(server);
93
94
  mockedReadProject.mockReturnValue(null);
@@ -97,7 +98,7 @@ DATABASE_URL=sqlite://local.db
97
98
  });
98
99
  });
99
100
  describe('codapult_env_update', () => {
100
- it('updates existing variable in .env.local', () => {
101
+ it(`updates existing variable in ${ENV_FILE_NAME}`, () => {
101
102
  const server = createMockServer();
102
103
  registerEnvTools(server);
103
104
  mockedExists.mockReturnValue(true);
@@ -119,7 +120,7 @@ DATABASE_URL=sqlite://local.db
119
120
  const written = mockedWrite.mock.calls[0][1];
120
121
  expect(written).toContain('NEW_VAR="new_value"');
121
122
  });
122
- it('returns error when .env.local not found', () => {
123
+ it(`returns error when ${ENV_FILE_NAME} not found`, () => {
123
124
  const server = createMockServer();
124
125
  registerEnvTools(server);
125
126
  mockedExists.mockReturnValue(false);
@@ -2,6 +2,7 @@ import { existsSync, readFileSync, readdirSync } from 'node:fs';
2
2
  import { resolve } from 'node:path';
3
3
  import { z } from 'zod';
4
4
  import { findProjectRoot } from '../../utils/project.js';
5
+ import { ENV_FILE_NAME, getProjectEnvSource } from '../../utils/project-env.js';
5
6
  import { resolveManifest } from '../../utils/manifest.js';
6
7
  import { patchSchemaImports, patchSchemaTables, patchDbReExports, patchNextConfig, createPluginRegistration, patchPages, findPageConflicts, patchEnvFile, patchPackageJson, } from '../../utils/patchers.js';
7
8
  function getRoot() {
@@ -88,8 +89,13 @@ export function registerPluginTools(server) {
88
89
  createPluginRegistration(root, manifest.name, manifest.package, 'add');
89
90
  steps.push('Plugin registered');
90
91
  if (manifest.install.env && Object.keys(manifest.install.env).length > 0) {
91
- patchEnvFile(root, manifest.name, manifest.install.env, 'add');
92
- steps.push('Env vars added to .env.local');
92
+ if (getProjectEnvSource() === 'process') {
93
+ steps.push('Project uses process.env; add plugin env vars outside the CLI');
94
+ }
95
+ else {
96
+ patchEnvFile(root, manifest.name, manifest.install.env, 'add');
97
+ steps.push(`Env vars added to ${ENV_FILE_NAME}`);
98
+ }
93
99
  }
94
100
  const output = {
95
101
  plugin: manifest.name,
@@ -146,8 +152,13 @@ export function registerPluginTools(server) {
146
152
  steps.push('next.config.ts reverted');
147
153
  }
148
154
  if (manifest.install.env && Object.keys(manifest.install.env).length > 0) {
149
- patchEnvFile(root, manifest.name, manifest.install.env, 'remove');
150
- steps.push('Env vars removed');
155
+ if (getProjectEnvSource() === 'process') {
156
+ steps.push(`Project uses process.env; no ${ENV_FILE_NAME} env vars were removed`);
157
+ }
158
+ else {
159
+ patchEnvFile(root, manifest.name, manifest.install.env, 'remove');
160
+ steps.push('Env vars removed');
161
+ }
151
162
  }
152
163
  patchPackageJson(root, manifest.name, manifest.package, pluginDir, 'remove');
153
164
  steps.push('Dependency removed');
@@ -3,6 +3,7 @@ import { existsSync, readFileSync, readdirSync } from 'node:fs';
3
3
  import { resolve } from 'node:path';
4
4
  import { z } from 'zod';
5
5
  import { findProjectRoot, readProjectFile } from '../../utils/project.js';
6
+ import { ENV_FILE_NAME, getProjectEnvSource, loadProjectEnv } from '../../utils/project-env.js';
6
7
  import { getAdapters, getAuthMethods, getFeatures, getOauthProviders, } from '../../utils/env-config.js';
7
8
  function getRoot() {
8
9
  const root = findProjectRoot();
@@ -18,7 +19,7 @@ export function registerProjectTools(server) {
18
19
  }, () => {
19
20
  const root = getRoot();
20
21
  const pkg = JSON.parse(readFileSync(resolve(root, 'package.json'), 'utf-8'));
21
- const envContent = readProjectFile(root, '.env.local') ?? '';
22
+ const envContent = loadProjectEnv(root).content;
22
23
  const pluginsDir = resolve(root, 'src/plugins');
23
24
  const plugins = existsSync(pluginsDir)
24
25
  ? readdirSync(pluginsDir)
@@ -113,7 +114,6 @@ export function registerProjectTools(server) {
113
114
  'src/lib/auth/index.ts',
114
115
  'src/lib/payments/index.ts',
115
116
  'src/config/app.ts',
116
- '.env.local',
117
117
  ];
118
118
  for (const f of requiredFiles) {
119
119
  checks.push({
@@ -122,6 +122,21 @@ export function registerProjectTools(server) {
122
122
  detail: existsSync(resolve(root, f)) ? 'exists' : 'missing',
123
123
  });
124
124
  }
125
+ const envSource = getProjectEnvSource();
126
+ if (envSource === 'process') {
127
+ checks.push({
128
+ name: 'Environment source',
129
+ status: 'ok',
130
+ detail: 'process.env',
131
+ });
132
+ }
133
+ else {
134
+ checks.push({
135
+ name: ENV_FILE_NAME,
136
+ status: existsSync(resolve(root, ENV_FILE_NAME)) ? 'ok' : 'fail',
137
+ detail: existsSync(resolve(root, ENV_FILE_NAME)) ? 'exists' : 'missing',
138
+ });
139
+ }
125
140
  try {
126
141
  execSync('pnpm tsc --noEmit', { cwd: root, stdio: 'pipe', timeout: 60_000 });
127
142
  checks.push({ name: 'TypeScript', status: 'ok', detail: 'compiles cleanly' });
@@ -1,16 +1,24 @@
1
1
  import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import { ENV_FILE_NAME } from '../../utils/project-env.js';
2
3
  vi.mock('node:fs');
3
4
  vi.mock('node:child_process');
4
5
  vi.mock('../../utils/project.js', () => ({
5
6
  findProjectRoot: vi.fn(),
6
7
  readProjectFile: vi.fn(),
7
8
  }));
9
+ vi.mock('../../utils/project-env.js', () => ({
10
+ ENV_FILE_NAME: '.env.local',
11
+ getProjectEnvSource: vi.fn(() => 'file'),
12
+ loadProjectEnv: vi.fn(),
13
+ }));
8
14
  const { existsSync, readFileSync, readdirSync } = await import('node:fs');
9
15
  const { execSync } = await import('node:child_process');
10
16
  const { findProjectRoot, readProjectFile } = await import('../../utils/project.js');
17
+ const { loadProjectEnv } = await import('../../utils/project-env.js');
11
18
  const { registerProjectTools } = await import('./project.js');
12
19
  const mockedFindRoot = vi.mocked(findProjectRoot);
13
20
  const mockedReadProject = vi.mocked(readProjectFile);
21
+ const mockedLoadProjectEnv = vi.mocked(loadProjectEnv);
14
22
  const mockedExists = vi.mocked(existsSync);
15
23
  const mockedRead = vi.mocked(readFileSync);
16
24
  const mockedReaddir = vi.mocked(readdirSync);
@@ -18,6 +26,12 @@ const mockedExec = vi.mocked(execSync);
18
26
  beforeEach(() => {
19
27
  vi.resetAllMocks();
20
28
  mockedFindRoot.mockReturnValue('/project');
29
+ mockedLoadProjectEnv.mockReturnValue({
30
+ source: 'file',
31
+ filePath: `/project/${ENV_FILE_NAME}`,
32
+ fileExists: false,
33
+ content: '',
34
+ });
21
35
  });
22
36
  function createMockServer() {
23
37
  const tools = [];
@@ -42,17 +56,18 @@ describe('registerProjectTools', () => {
42
56
  const server = createMockServer();
43
57
  registerProjectTools(server);
44
58
  mockedRead.mockReturnValue(JSON.stringify({ name: 'codapult', version: '1.0.0' }));
45
- mockedReadProject.mockImplementation((_root, path) => {
46
- if (path === '.env.local')
47
- return [
48
- 'AUTH_PROVIDER=kinde',
49
- 'PAYMENT_PROVIDER=lemonsqueezy',
50
- 'STORAGE_PROVIDER=s3',
51
- 'ENABLE_TEAMS=false',
52
- 'GOOGLE_CLIENT_ID=abc',
53
- 'GOOGLE_CLIENT_SECRET=def',
54
- ].join('\n');
55
- return null;
59
+ mockedLoadProjectEnv.mockReturnValue({
60
+ source: 'file',
61
+ filePath: `/project/${ENV_FILE_NAME}`,
62
+ fileExists: true,
63
+ content: [
64
+ 'AUTH_PROVIDER=kinde',
65
+ 'PAYMENT_PROVIDER=lemonsqueezy',
66
+ 'STORAGE_PROVIDER=s3',
67
+ 'ENABLE_TEAMS=false',
68
+ 'GOOGLE_CLIENT_ID=abc',
69
+ 'GOOGLE_CLIENT_SECRET=def',
70
+ ].join('\n'),
56
71
  });
57
72
  mockedExists.mockReturnValue(true);
58
73
  mockedReaddir.mockReturnValue(['ai-kit.ts', 'crm.ts', 'index.ts']);
@@ -3,10 +3,10 @@
3
3
  *
4
4
  * Keep this file in sync with the host's `env.features`, `env.auth`,
5
5
  * provider enums, and the `superRefine` validation in
6
- * `codapult/src/lib/config.ts`. The CLI parses `.env.local` directly (it
7
- * cannot import from the host project), so this module centralises the
8
- * provider/feature shape that several commands share (config-show, doctor,
9
- * MCP project status).
6
+ * `codapult/src/lib/config.ts`. The CLI cannot import from the host project,
7
+ * so this module centralises the provider/feature shape that several
8
+ * commands share regardless of whether env values come from `.env.local` or
9
+ * `process.env`.
10
10
  */
11
11
  export type DbProvider = 'turso' | 'postgres';
12
12
  export type AuthProvider = 'better-auth' | 'kinde' | 'none';
@@ -3,10 +3,10 @@
3
3
  *
4
4
  * Keep this file in sync with the host's `env.features`, `env.auth`,
5
5
  * provider enums, and the `superRefine` validation in
6
- * `codapult/src/lib/config.ts`. The CLI parses `.env.local` directly (it
7
- * cannot import from the host project), so this module centralises the
8
- * provider/feature shape that several commands share (config-show, doctor,
9
- * MCP project status).
6
+ * `codapult/src/lib/config.ts`. The CLI cannot import from the host project,
7
+ * so this module centralises the provider/feature shape that several
8
+ * commands share regardless of whether env values come from `.env.local` or
9
+ * `process.env`.
10
10
  */
11
11
  /** Feature toggle key → ENABLE_* env var. Order = display order. */
12
12
  export const FEATURE_ENV = {
@@ -1,5 +1,6 @@
1
1
  import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync, renameSync, rmSync, rmdirSync, statSync, } from 'node:fs';
2
2
  import { resolve, dirname, relative, basename, extname, join } from 'node:path';
3
+ import { ENV_FILE_NAME } from './project-env.js';
3
4
  const MARKER_START = (name) => `// --- plugin:${name}:start ---`;
4
5
  const MARKER_END = (name) => `// --- plugin:${name}:end ---`;
5
6
  function hasMarker(content, name) {
@@ -533,10 +534,10 @@ export function findPageBackups(projectRoot) {
533
534
  return found;
534
535
  }
535
536
  // ---------------------------------------------------------------------------
536
- // .env.local — append env vars
537
+ // env file — append env vars
537
538
  // ---------------------------------------------------------------------------
538
539
  export function patchEnvFile(projectRoot, pluginName, envVars, action) {
539
- const envPath = resolve(projectRoot, '.env.local');
540
+ const envPath = resolve(projectRoot, ENV_FILE_NAME);
540
541
  if (!existsSync(envPath))
541
542
  return;
542
543
  let content = readFileSync(envPath, 'utf-8');
@@ -1,5 +1,6 @@
1
1
  import { describe, it, expect, vi, beforeEach } from 'vitest';
2
2
  import { patchSchemaImports, patchSchemaTables, patchDbReExports, patchNextConfig, regenerateBarrel, createPluginRegistration, patchPages, findPageConflicts, findPageBackups, readPageExtensions, PageConflictError, patchEnvFile, patchPackageJson, } from './patchers.js';
3
+ import { ENV_FILE_NAME } from './project-env.js';
3
4
  vi.mock('node:fs');
4
5
  const { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync, renameSync, rmSync, rmdirSync, statSync, } = await import('node:fs');
5
6
  const mockedExists = vi.mocked(existsSync);
@@ -571,7 +572,7 @@ describe('patchEnvFile', () => {
571
572
  patchEnvFile(ROOT, 'test-plugin', { KEY: { required: true } }, 'add');
572
573
  expect(mockedWrite).not.toHaveBeenCalled();
573
574
  });
574
- it('does nothing when .env.local does not exist', () => {
575
+ it(`does nothing when ${ENV_FILE_NAME} does not exist`, () => {
575
576
  mockedExists.mockReturnValue(false);
576
577
  patchEnvFile(ROOT, 'test-plugin', { KEY: { required: true } }, 'add');
577
578
  expect(mockedWrite).not.toHaveBeenCalled();
@@ -0,0 +1,15 @@
1
+ export type ProjectEnvSource = 'file' | 'process';
2
+ export interface ProjectEnvOptions {
3
+ noEnvFile?: boolean;
4
+ }
5
+ export interface LoadedProjectEnv {
6
+ source: ProjectEnvSource;
7
+ content: string;
8
+ filePath: string;
9
+ fileExists: boolean;
10
+ }
11
+ export declare const ENV_EXAMPLE_FILE_NAME = ".env.example";
12
+ export declare const ENV_FILE_NAME = ".env.local";
13
+ export declare function getProjectEnvFilePath(projectRoot: string): string;
14
+ export declare function getProjectEnvSource(options?: ProjectEnvOptions): ProjectEnvSource;
15
+ export declare function loadProjectEnv(projectRoot: string, options?: ProjectEnvOptions): LoadedProjectEnv;
@@ -0,0 +1,35 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+ export const ENV_EXAMPLE_FILE_NAME = '.env.example';
4
+ export const ENV_FILE_NAME = '.env.local';
5
+ export function getProjectEnvFilePath(projectRoot) {
6
+ return resolve(projectRoot, ENV_FILE_NAME);
7
+ }
8
+ export function getProjectEnvSource(options) {
9
+ return options?.noEnvFile ? 'process' : 'file';
10
+ }
11
+ function serializeProcessEnv(env) {
12
+ return Object.entries(env)
13
+ .filter(([, value]) => value !== undefined)
14
+ .map(([key, value]) => `${key}=${value}`)
15
+ .join('\n');
16
+ }
17
+ export function loadProjectEnv(projectRoot, options) {
18
+ const source = getProjectEnvSource(options);
19
+ const filePath = getProjectEnvFilePath(projectRoot);
20
+ const fileExists = existsSync(filePath);
21
+ if (source === 'process') {
22
+ return {
23
+ source,
24
+ content: serializeProcessEnv(process.env),
25
+ filePath,
26
+ fileExists,
27
+ };
28
+ }
29
+ return {
30
+ source,
31
+ content: fileExists ? readFileSync(filePath, 'utf-8') : '',
32
+ filePath,
33
+ fileExists,
34
+ };
35
+ }
@@ -0,0 +1 @@
1
+ export {};