@codapult/cli 0.18.1 → 0.19.1

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 (34) hide show
  1. package/README.md +49 -18
  2. package/package.json +12 -5
  3. package/dist/commands/generate.test.d.ts +0 -1
  4. package/dist/commands/generate.test.js +0 -127
  5. package/dist/mcp/tools/db.test.d.ts +0 -1
  6. package/dist/mcp/tools/db.test.js +0 -221
  7. package/dist/mcp/tools/env.test.d.ts +0 -1
  8. package/dist/mcp/tools/env.test.js +0 -156
  9. package/dist/mcp/tools/project.test.d.ts +0 -1
  10. package/dist/mcp/tools/project.test.js +0 -188
  11. package/dist/utils/config-report.test.d.ts +0 -1
  12. package/dist/utils/config-report.test.js +0 -18
  13. package/dist/utils/env-compatibility.test.d.ts +0 -1
  14. package/dist/utils/env-compatibility.test.js +0 -23
  15. package/dist/utils/env-schema-parser.test.d.ts +0 -1
  16. package/dist/utils/env-schema-parser.test.js +0 -11
  17. package/dist/utils/git.test.d.ts +0 -1
  18. package/dist/utils/git.test.js +0 -77
  19. package/dist/utils/health-render.test.d.ts +0 -1
  20. package/dist/utils/health-render.test.js +0 -18
  21. package/dist/utils/live-db-diff.test.d.ts +0 -1
  22. package/dist/utils/live-db-diff.test.js +0 -29
  23. package/dist/utils/manifest.test.d.ts +0 -1
  24. package/dist/utils/manifest.test.js +0 -107
  25. package/dist/utils/patchers.test.d.ts +0 -1
  26. package/dist/utils/patchers.test.js +0 -647
  27. package/dist/utils/project-env.test.d.ts +0 -1
  28. package/dist/utils/project-env.test.js +0 -47
  29. package/dist/utils/project.test.d.ts +0 -1
  30. package/dist/utils/project.test.js +0 -123
  31. package/dist/utils/schema-parity.test.d.ts +0 -1
  32. package/dist/utils/schema-parity.test.js +0 -27
  33. package/dist/utils/schema-parser.test.d.ts +0 -1
  34. package/dist/utils/schema-parser.test.js +0 -59
@@ -1 +0,0 @@
1
- export {};
@@ -1,647 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach } from 'vitest';
2
- import { patchSchemaImports, patchSchemaImportsPg, patchSchemaTables, patchSchemaTablesPg, patchDbReExports, patchNextConfig, regenerateBarrel, createPluginRegistration, patchPages, findPageConflicts, findPageBackups, readPageExtensions, PageConflictError, patchEnvFile, patchPackageJson, } from './patchers.js';
3
- import { ENV_FILE_NAME } from './project-env.js';
4
- vi.mock('node:fs');
5
- const { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync, renameSync, rmSync, rmdirSync, statSync, } = await import('node:fs');
6
- const mockedExists = vi.mocked(existsSync);
7
- const mockedRead = vi.mocked(readFileSync);
8
- const mockedWrite = vi.mocked(writeFileSync);
9
- const mockedMkdir = vi.mocked(mkdirSync);
10
- const mockedReaddir = vi.mocked(readdirSync);
11
- const mockedRename = vi.mocked(renameSync);
12
- const mockedRm = vi.mocked(rmSync);
13
- const mockedRmdir = vi.mocked(rmdirSync);
14
- const mockedStat = vi.mocked(statSync);
15
- const ROOT = '/project';
16
- beforeEach(() => {
17
- vi.resetAllMocks();
18
- });
19
- // ---------------------------------------------------------------------------
20
- // patchSchemaImports
21
- // ---------------------------------------------------------------------------
22
- describe('patchSchemaImports', () => {
23
- const schemaBase = `import { sqliteTable, text, integer } from 'drizzle-orm/sqlite-core';\n\nexport const user = sqliteTable('user', {});`;
24
- it('adds new imports without duplicating existing ones', () => {
25
- mockedExists.mockReturnValue(true);
26
- mockedRead.mockReturnValue(schemaBase);
27
- patchSchemaImports(ROOT, 'test-plugin', ['text', 'real', 'blob'], 'add');
28
- const written = mockedWrite.mock.calls[0][1];
29
- expect(written).toContain("import { sqliteTable, text, integer, real, blob } from 'drizzle-orm/sqlite-core';");
30
- });
31
- it('does nothing when schema file does not exist', () => {
32
- mockedExists.mockReturnValue(false);
33
- patchSchemaImports(ROOT, 'test-plugin', ['real'], 'add');
34
- expect(mockedWrite).not.toHaveBeenCalled();
35
- });
36
- it('removes imports not used outside the plugin block', () => {
37
- const content = `import { sqliteTable, text, integer, real } from 'drizzle-orm/sqlite-core';
38
-
39
- export const user = sqliteTable('user', {
40
- id: text('id').primaryKey(),
41
- });
42
-
43
- // --- plugin:test-plugin:start ---
44
- export const widget = sqliteTable('widget', {
45
- score: real('score'),
46
- });
47
-
48
- // --- plugin:test-plugin:end ---
49
- `;
50
- mockedExists.mockReturnValue(true);
51
- mockedRead.mockReturnValue(content);
52
- patchSchemaImports(ROOT, 'test-plugin', ['real'], 'remove');
53
- const written = mockedWrite.mock.calls[0][1];
54
- expect(written).not.toMatch(/\breal\b.*from 'drizzle-orm\/sqlite-core'/);
55
- expect(written).toContain('sqliteTable');
56
- expect(written).toContain('text');
57
- expect(written).toContain('integer');
58
- });
59
- it('keeps imports that are used outside the plugin block', () => {
60
- const content = `import { sqliteTable, text, integer } from 'drizzle-orm/sqlite-core';
61
-
62
- export const user = sqliteTable('user', {
63
- count: integer('count'),
64
- });
65
-
66
- // --- plugin:test-plugin:start ---
67
- export const widget = sqliteTable('widget', {
68
- n: integer('n'),
69
- });
70
- // --- plugin:test-plugin:end ---
71
- `;
72
- mockedExists.mockReturnValue(true);
73
- mockedRead.mockReturnValue(content);
74
- patchSchemaImports(ROOT, 'test-plugin', ['integer'], 'remove');
75
- const written = mockedWrite.mock.calls[0][1];
76
- expect(written).toContain('integer');
77
- });
78
- });
79
- describe('PostgreSQL schema patchers', () => {
80
- it('adds PostgreSQL imports to schema-pg.ts', () => {
81
- mockedExists.mockReturnValue(true);
82
- mockedRead.mockReturnValue("import { pgTable, text } from 'drizzle-orm/pg-core';\n\nexport const user = pgTable('user', {});");
83
- patchSchemaImportsPg(ROOT, 'test-plugin', ['jsonb', 'primaryKey'], 'add');
84
- expect(mockedWrite.mock.calls[0][1]).toContain("import { pgTable, text, jsonb, primaryKey } from 'drizzle-orm/pg-core';");
85
- });
86
- it('copies PostgreSQL tables into schema-pg.ts', () => {
87
- const schema = "import { pgTable, text } from 'drizzle-orm/pg-core';\n\nexport const user = pgTable('user', {});";
88
- const tables = "import { pgTable, text } from 'drizzle-orm/pg-core';\n\nexport const widget = pgTable('widget', {});";
89
- mockedExists.mockReturnValue(true);
90
- mockedRead.mockImplementation((path) => String(path).includes('schema-pg.ts') ? schema : tables);
91
- patchSchemaTablesPg(ROOT, 'test-plugin', '/plugins/test', 'tables-pg.ts', 'add');
92
- expect(mockedWrite.mock.calls[0][0]).toBe('/project/src/lib/db/schema-pg.ts');
93
- expect(mockedWrite.mock.calls[0][1]).toContain("pgTable('widget'");
94
- });
95
- });
96
- // ---------------------------------------------------------------------------
97
- // patchSchemaTables
98
- // ---------------------------------------------------------------------------
99
- describe('patchSchemaTables', () => {
100
- it('appends table block with markers on add', () => {
101
- const schema = `import { sqliteTable, text } from 'drizzle-orm/sqlite-core';\n\nexport const user = sqliteTable('user', {});`;
102
- const tables = `import { sqliteTable, text } from 'drizzle-orm/sqlite-core';\n\nexport type Widget = typeof widget.$inferSelect;\n\nexport const widget = sqliteTable('widget', {});\n`;
103
- mockedExists.mockReturnValue(true);
104
- mockedRead.mockImplementation((p) => {
105
- const path = p;
106
- if (path.includes('schema.ts'))
107
- return schema;
108
- return tables;
109
- });
110
- patchSchemaTables(ROOT, 'test-plugin', '/plugins/test', 'tables.ts', 'add');
111
- const written = mockedWrite.mock.calls[0][1];
112
- expect(written).toContain('// --- plugin:test-plugin:start ---');
113
- expect(written).toContain('// --- plugin:test-plugin:end ---');
114
- expect(written).toContain("export const widget = sqliteTable('widget', {});");
115
- // The tables file's import and type export lines should be stripped from the injected block
116
- const markerBlock = written.slice(written.indexOf('// --- plugin:test-plugin:start ---'));
117
- expect(markerBlock).not.toMatch(/^import\s+/m);
118
- expect(markerBlock).not.toMatch(/^export\s+type\s+Widget/m);
119
- // The original schema import should still be present
120
- expect(written).toMatch(/^import\s+.*from\s+'drizzle-orm\/sqlite-core'/m);
121
- });
122
- it('skips if marker already present', () => {
123
- const schema = `// --- plugin:test-plugin:start ---\n// tables\n// --- plugin:test-plugin:end ---`;
124
- mockedExists.mockReturnValue(true);
125
- mockedRead.mockReturnValue(schema);
126
- patchSchemaTables(ROOT, 'test-plugin', '/plugins/test', 'tables.ts', 'add');
127
- expect(mockedWrite).not.toHaveBeenCalled();
128
- });
129
- it('removes marked block on remove', () => {
130
- const schema = `export const user = sqliteTable('user', {});\n\n// --- plugin:test-plugin:start ---\nexport const widget = sqliteTable('widget', {});\n// --- plugin:test-plugin:end ---\n`;
131
- mockedExists.mockReturnValue(true);
132
- mockedRead.mockReturnValue(schema);
133
- patchSchemaTables(ROOT, 'test-plugin', '/plugins/test', 'tables.ts', 'remove');
134
- const written = mockedWrite.mock.calls[0][1];
135
- expect(written).not.toContain('plugin:test-plugin');
136
- expect(written).not.toContain('widget');
137
- expect(written).toContain('user');
138
- });
139
- it('replaces marked block with new content on update', () => {
140
- const schema = `export const user = sqliteTable('user', {});\n\n// --- plugin:test-plugin:start ---\nexport const widget = sqliteTable('widget', {\n id: text('id'),\n});\n// --- plugin:test-plugin:end ---\n`;
141
- const newTables = `export const widget = sqliteTable('widget', {\n id: text('id'),\n name: text('name'),\n});\n`;
142
- mockedExists.mockReturnValue(true);
143
- mockedRead.mockImplementation((p) => {
144
- const path = p;
145
- if (path.includes('schema.ts'))
146
- return schema;
147
- return newTables;
148
- });
149
- const result = patchSchemaTables(ROOT, 'test-plugin', '/plugins/test', 'tables.ts', 'update');
150
- expect(result).toBe(true);
151
- const written = mockedWrite.mock.calls[0][1];
152
- expect(written).toContain("name: text('name')");
153
- expect(written).toContain('// --- plugin:test-plugin:start ---');
154
- expect(written).toContain('// --- plugin:test-plugin:end ---');
155
- });
156
- it('returns false on update when schema is unchanged', () => {
157
- const tables = `export const widget = sqliteTable('widget', {});`;
158
- const schema = `export const user = sqliteTable('user', {});\n\n// --- plugin:test-plugin:start ---\n${tables}\n// --- plugin:test-plugin:end ---\n`;
159
- mockedExists.mockReturnValue(true);
160
- mockedRead.mockImplementation((p) => {
161
- const path = p;
162
- if (path.includes('schema.ts'))
163
- return schema;
164
- return tables + '\n';
165
- });
166
- const result = patchSchemaTables(ROOT, 'test-plugin', '/plugins/test', 'tables.ts', 'update');
167
- expect(result).toBe(false);
168
- expect(mockedWrite).not.toHaveBeenCalled();
169
- });
170
- it('returns false on update when plugin is not installed', () => {
171
- const schema = `export const user = sqliteTable('user', {});`;
172
- mockedExists.mockReturnValue(true);
173
- mockedRead.mockReturnValue(schema);
174
- const result = patchSchemaTables(ROOT, 'test-plugin', '/plugins/test', 'tables.ts', 'update');
175
- expect(result).toBe(false);
176
- expect(mockedWrite).not.toHaveBeenCalled();
177
- });
178
- });
179
- // ---------------------------------------------------------------------------
180
- // patchDbReExports
181
- // ---------------------------------------------------------------------------
182
- describe('patchDbReExports', () => {
183
- it('creates a new export line when none exists', () => {
184
- const content = `import { db } from './client';\n\nexport { db };\n`;
185
- mockedExists.mockReturnValue(true);
186
- mockedRead.mockReturnValue(content);
187
- patchDbReExports(ROOT, 'test-plugin', ['widgetTable', 'gadgetTable'], 'add');
188
- const written = mockedWrite.mock.calls[0][1];
189
- expect(written).toContain("export { widgetTable, gadgetTable } from './schema';");
190
- expect(written).toContain('// --- plugin:test-plugin:start ---');
191
- });
192
- it('merges into existing export line', () => {
193
- const content = `export { userTable } from './schema';\n`;
194
- mockedExists.mockReturnValue(true);
195
- mockedRead.mockReturnValue(content);
196
- patchDbReExports(ROOT, 'test-plugin', ['widgetTable'], 'add');
197
- const written = mockedWrite.mock.calls[0][1];
198
- expect(written).toContain("export { userTable, widgetTable } from './schema';");
199
- });
200
- it('skips symbols already exported', () => {
201
- const content = `export { userTable, widgetTable } from './schema';\n`;
202
- mockedExists.mockReturnValue(true);
203
- mockedRead.mockReturnValue(content);
204
- patchDbReExports(ROOT, 'test-plugin', ['widgetTable'], 'add');
205
- const written = mockedWrite.mock.calls[0][1];
206
- // Should add a comment-only marker, not duplicate the export
207
- expect(written).toContain('// --- plugin:test-plugin:start ---');
208
- expect(written).toContain('db re-exports handled by first plugin');
209
- });
210
- it('removes marked block on remove', () => {
211
- const content = `export { db } from './client';\n\n// --- plugin:test-plugin:start ---\nexport { widgetTable } from './schema';\n// --- plugin:test-plugin:end ---\n`;
212
- mockedExists.mockReturnValue(true);
213
- mockedRead.mockReturnValue(content);
214
- patchDbReExports(ROOT, 'test-plugin', ['widgetTable'], 'remove');
215
- const written = mockedWrite.mock.calls[0][1];
216
- expect(written).not.toContain('plugin:test-plugin');
217
- expect(written).not.toContain('widgetTable');
218
- });
219
- it('is idempotent — skips if marker already present', () => {
220
- const content = `// --- plugin:test-plugin:start ---\n// marker\n// --- plugin:test-plugin:end ---\n`;
221
- mockedExists.mockReturnValue(true);
222
- mockedRead.mockReturnValue(content);
223
- patchDbReExports(ROOT, 'test-plugin', ['widgetTable'], 'add');
224
- expect(mockedWrite).not.toHaveBeenCalled();
225
- });
226
- });
227
- // ---------------------------------------------------------------------------
228
- // patchNextConfig
229
- // ---------------------------------------------------------------------------
230
- describe('patchNextConfig', () => {
231
- const makeManifest = (transpile = [], externals = []) => ({
232
- name: 'test-plugin',
233
- package: '@codapult/plugin-test',
234
- version: '0.1.0',
235
- description: 'Test',
236
- install: {
237
- transpilePackages: transpile,
238
- serverExternalPackages: externals,
239
- },
240
- });
241
- it('appends to existing transpilePackages array', () => {
242
- const config = `const nextConfig: NextConfig = {\n transpilePackages: [\n 'existing-pkg',\n ],\n serverExternalPackages: [\n 'ext-pkg',\n ],\n};`;
243
- mockedExists.mockReturnValue(true);
244
- mockedRead.mockReturnValue(config);
245
- patchNextConfig(ROOT, 'test-plugin', makeManifest(['@codapult/plugin-test']), 'add');
246
- const written = mockedWrite.mock.calls[0][1];
247
- expect(written).toContain("'@codapult/plugin-test', // plugin:test-plugin");
248
- });
249
- it('creates transpilePackages when not present', () => {
250
- const config = `const nextConfig: NextConfig = {\n output: 'standalone',\n};`;
251
- mockedExists.mockReturnValue(true);
252
- mockedRead.mockReturnValue(config);
253
- patchNextConfig(ROOT, 'test-plugin', makeManifest(['@codapult/plugin-test']), 'add');
254
- const written = mockedWrite.mock.calls[0][1];
255
- expect(written).toContain('transpilePackages: [');
256
- expect(written).toContain("'@codapult/plugin-test', // plugin:test-plugin");
257
- });
258
- it('removes per-entry markers on remove', () => {
259
- const config = `const nextConfig: NextConfig = {\n transpilePackages: [\n '@codapult/plugin-test', // plugin:test-plugin\n 'other-pkg',\n ],\n};`;
260
- mockedExists.mockReturnValue(true);
261
- mockedRead.mockReturnValue(config);
262
- patchNextConfig(ROOT, 'test-plugin', makeManifest(['@codapult/plugin-test']), 'remove');
263
- const written = mockedWrite.mock.calls[0][1];
264
- expect(written).not.toContain('@codapult/plugin-test');
265
- expect(written).toContain('other-pkg');
266
- });
267
- it('does not duplicate entries on repeated add', () => {
268
- const config = `const nextConfig: NextConfig = {\n transpilePackages: [\n '@codapult/plugin-test', // plugin:test-plugin\n ],\n};`;
269
- mockedExists.mockReturnValue(true);
270
- mockedRead.mockReturnValue(config);
271
- patchNextConfig(ROOT, 'test-plugin', makeManifest(['@codapult/plugin-test']), 'add');
272
- const written = mockedWrite.mock.calls[0][1];
273
- const occurrences = written.split('@codapult/plugin-test').length - 1;
274
- expect(occurrences).toBe(1);
275
- });
276
- });
277
- // ---------------------------------------------------------------------------
278
- // regenerateBarrel
279
- // ---------------------------------------------------------------------------
280
- describe('regenerateBarrel', () => {
281
- it('generates barrel with sorted imports', () => {
282
- mockedExists.mockReturnValue(true);
283
- mockedReaddir.mockReturnValue(['crm.ts', 'analytics.ts', 'index.ts']);
284
- regenerateBarrel(ROOT);
285
- const written = mockedWrite.mock.calls[0][1];
286
- expect(written).toContain("import './analytics';");
287
- expect(written).toContain("import './crm';");
288
- expect(written).not.toContain('index');
289
- // analytics should come before crm (sorted)
290
- expect(written.indexOf('analytics')).toBeLessThan(written.indexOf('crm'));
291
- });
292
- it('does nothing when plugins dir does not exist', () => {
293
- mockedExists.mockReturnValue(false);
294
- regenerateBarrel(ROOT);
295
- expect(mockedWrite).not.toHaveBeenCalled();
296
- });
297
- });
298
- // ---------------------------------------------------------------------------
299
- // createPluginRegistration
300
- // ---------------------------------------------------------------------------
301
- describe('createPluginRegistration', () => {
302
- it('writes registration file on add', () => {
303
- mockedExists.mockImplementation((p) => {
304
- const path = p;
305
- if (path.includes('src/plugins'))
306
- return true;
307
- return false;
308
- });
309
- mockedReaddir.mockReturnValue(['test-plugin.ts']);
310
- createPluginRegistration(ROOT, 'test-plugin', '@codapult/plugin-test', 'add');
311
- const written = mockedWrite.mock.calls[0][1];
312
- expect(written).toContain("import { registerPlugin } from '@/lib/plugins';");
313
- expect(written).toContain("import plugin from '@codapult/plugin-test';");
314
- expect(written).toContain('registerPlugin(plugin);');
315
- });
316
- it('removes registration file and regenerates barrel on remove', () => {
317
- mockedExists.mockReturnValue(true);
318
- mockedReaddir.mockReturnValue([]);
319
- createPluginRegistration(ROOT, 'test-plugin', '@codapult/plugin-test', 'remove');
320
- expect(mockedRm).toHaveBeenCalled();
321
- });
322
- });
323
- // ---------------------------------------------------------------------------
324
- // patchPages
325
- // ---------------------------------------------------------------------------
326
- describe('patchPages', () => {
327
- it('creates page files on add', () => {
328
- mockedExists.mockReturnValue(false);
329
- const pages = {
330
- 'src/app/(dashboard)/dashboard/widgets/page.tsx': '@codapult/plugin-test/pages/widgets-page',
331
- };
332
- patchPages(ROOT, 'test-plugin', pages, 'add');
333
- expect(mockedMkdir).toHaveBeenCalled();
334
- const written = mockedWrite.mock.calls[0][1];
335
- expect(written).toContain("export { default } from '@codapult/plugin-test/pages/widgets-page';");
336
- });
337
- it('removes page files and cleans up empty dirs on remove', () => {
338
- mockedExists.mockReturnValue(true);
339
- mockedReaddir.mockReturnValue([]);
340
- const pages = {
341
- 'src/app/(dashboard)/dashboard/widgets/page.tsx': '@codapult/plugin-test/pages/widgets-page',
342
- };
343
- patchPages(ROOT, 'test-plugin', pages, 'remove');
344
- expect(mockedRm).toHaveBeenCalled();
345
- expect(mockedRmdir).toHaveBeenCalled();
346
- });
347
- it('backs up a user-written page at a different extension before writing the stub', () => {
348
- const pages = {
349
- 'src/app/[locale]/(public)/(marketing)/welcome/page.ts': '@codapult/plugin-onboarding/pages/welcome',
350
- };
351
- const userTsx = '/project/src/app/[locale]/(public)/(marketing)/welcome/page.tsx';
352
- // Only the .tsx sibling exists on disk; no backup file yet.
353
- mockedExists.mockImplementation((p) => p === userTsx);
354
- mockedRead.mockReturnValue('export default function Welcome(): JSX.Element { return <div>old</div>; }');
355
- patchPages(ROOT, 'onboarding', pages, 'add');
356
- expect(mockedRename).toHaveBeenCalledWith(userTsx, `${userTsx}.codapult-bak-onboarding`);
357
- const writtenPath = mockedWrite.mock.calls[0][0];
358
- const writtenContent = mockedWrite.mock.calls[0][1];
359
- expect(writtenPath).toContain('page.ts');
360
- expect(writtenPath).not.toMatch(/page\.tsx$/);
361
- expect(writtenContent).toContain("export { default } from '@codapult/plugin-onboarding/pages/welcome';");
362
- });
363
- it('does not re-backup when a backup already exists (idempotent re-install)', () => {
364
- const pages = {
365
- 'src/app/welcome/page.ts': '@codapult/plugin-onboarding/pages/welcome',
366
- };
367
- const userTsx = '/project/src/app/welcome/page.tsx';
368
- const backup = `${userTsx}.codapult-bak-onboarding`;
369
- mockedExists.mockImplementation((p) => {
370
- const path = p;
371
- return path === userTsx || path === backup;
372
- });
373
- mockedRead.mockReturnValue('export default function UserPage() {}');
374
- patchPages(ROOT, 'onboarding', pages, 'add');
375
- expect(mockedRename).not.toHaveBeenCalled();
376
- expect(mockedRm).toHaveBeenCalledWith(userTsx);
377
- });
378
- it('silently overwrites sibling plugin stubs without creating a backup', () => {
379
- const pages = {
380
- 'src/app/welcome/page.ts': '@codapult/plugin-onboarding/pages/welcome',
381
- };
382
- const siblingStub = '/project/src/app/welcome/page.tsx';
383
- mockedExists.mockImplementation((p) => p === siblingStub);
384
- mockedRead.mockReturnValue("export { default } from 'some-other-package/pages/welcome';\n");
385
- patchPages(ROOT, 'onboarding', pages, 'add');
386
- expect(mockedRename).not.toHaveBeenCalled();
387
- expect(mockedRm).toHaveBeenCalledWith(siblingStub);
388
- });
389
- it('is idempotent when the same stub was written previously', () => {
390
- const pages = {
391
- 'src/app/welcome/page.ts': '@codapult/plugin-onboarding/pages/welcome',
392
- };
393
- const targetPath = '/project/src/app/welcome/page.ts';
394
- const stub = "export { default } from '@codapult/plugin-onboarding/pages/welcome';\n";
395
- mockedExists.mockImplementation((p) => p === targetPath);
396
- mockedRead.mockReturnValue(stub);
397
- patchPages(ROOT, 'onboarding', pages, 'add');
398
- expect(mockedRename).not.toHaveBeenCalled();
399
- expect(mockedRm).not.toHaveBeenCalled();
400
- // Still writes (idempotent re-write of identical content)
401
- expect(mockedWrite).toHaveBeenCalled();
402
- });
403
- it('throws PageConflictError when onConflict is "fail"', () => {
404
- const pages = {
405
- 'src/app/welcome/page.ts': '@codapult/plugin-onboarding/pages/welcome',
406
- };
407
- const userTsx = '/project/src/app/welcome/page.tsx';
408
- mockedExists.mockImplementation((p) => p === userTsx);
409
- mockedRead.mockReturnValue('export default function User() {}');
410
- expect(() => patchPages(ROOT, 'onboarding', pages, 'add', { onConflict: 'fail' })).toThrow(PageConflictError);
411
- expect(mockedRename).not.toHaveBeenCalled();
412
- expect(mockedWrite).not.toHaveBeenCalled();
413
- });
414
- it('restores backup files on remove', () => {
415
- const pages = {
416
- 'src/app/welcome/page.ts': '@codapult/plugin-onboarding/pages/welcome',
417
- };
418
- // Target page.ts exists; its directory has one matching backup entry.
419
- mockedExists.mockImplementation((p) => {
420
- const path = p;
421
- return (path === '/project/src/app/welcome/page.ts' ||
422
- path === '/project/src/app/welcome' ||
423
- path.endsWith('src/app'));
424
- });
425
- mockedReaddir.mockImplementation((d) => {
426
- const dir = d;
427
- if (dir === '/project/src/app/welcome') {
428
- return ['page.tsx.codapult-bak-onboarding'];
429
- }
430
- return [];
431
- });
432
- patchPages(ROOT, 'onboarding', pages, 'remove');
433
- expect(mockedRm).toHaveBeenCalledWith('/project/src/app/welcome/page.ts');
434
- expect(mockedRename).toHaveBeenCalledWith('/project/src/app/welcome/page.tsx.codapult-bak-onboarding', '/project/src/app/welcome/page.tsx');
435
- });
436
- it('does not restore a backup when a live file already occupies its target name', () => {
437
- const pages = {
438
- 'src/app/welcome/page.ts': '@codapult/plugin-onboarding/pages/welcome',
439
- };
440
- const live = '/project/src/app/welcome/page.tsx';
441
- mockedExists.mockImplementation((p) => {
442
- const path = p;
443
- return (path === '/project/src/app/welcome/page.ts' ||
444
- path === live ||
445
- path === '/project/src/app/welcome');
446
- });
447
- mockedReaddir.mockImplementation((d) => {
448
- const dir = d;
449
- if (dir === '/project/src/app/welcome') {
450
- return ['page.ts', 'page.tsx', 'page.tsx.codapult-bak-onboarding'];
451
- }
452
- return [];
453
- });
454
- patchPages(ROOT, 'onboarding', pages, 'remove');
455
- expect(mockedRename).not.toHaveBeenCalled();
456
- });
457
- });
458
- describe('findPageConflicts', () => {
459
- it('reports a sibling file at a different Next.js page extension', () => {
460
- const pages = {
461
- 'src/app/welcome/page.ts': '@codapult/plugin-onboarding/pages/welcome',
462
- };
463
- const sibling = '/project/src/app/welcome/page.tsx';
464
- mockedExists.mockImplementation((p) => p === sibling);
465
- mockedRead.mockReturnValue('export default function User() {}');
466
- const conflicts = findPageConflicts(ROOT, pages);
467
- expect(conflicts).toHaveLength(1);
468
- expect(conflicts[0].isStub).toBe(false);
469
- expect(conflicts[0].isExactPath).toBe(false);
470
- expect(conflicts[0].conflictRel).toBe('src/app/welcome/page.tsx');
471
- });
472
- it('returns [] when the only file at the target path is our own stub', () => {
473
- const pages = {
474
- 'src/app/welcome/page.ts': '@codapult/plugin-onboarding/pages/welcome',
475
- };
476
- const target = '/project/src/app/welcome/page.ts';
477
- mockedExists.mockImplementation((p) => p === target);
478
- mockedRead.mockReturnValue("export { default } from '@codapult/plugin-onboarding/pages/welcome';\n");
479
- expect(findPageConflicts(ROOT, pages)).toEqual([]);
480
- });
481
- it('flags foreign stubs as conflicts but marks them isStub=true', () => {
482
- const pages = {
483
- 'src/app/welcome/page.ts': '@codapult/plugin-onboarding/pages/welcome',
484
- };
485
- const sibling = '/project/src/app/welcome/page.tsx';
486
- mockedExists.mockImplementation((p) => p === sibling);
487
- mockedRead.mockReturnValue("export { default } from 'some-other/pages/welcome';\n");
488
- const conflicts = findPageConflicts(ROOT, pages);
489
- expect(conflicts).toHaveLength(1);
490
- expect(conflicts[0].isStub).toBe(true);
491
- });
492
- });
493
- describe('readPageExtensions', () => {
494
- it('reads a custom pageExtensions array from next.config.ts', () => {
495
- const config = `import type { NextConfig } from 'next';
496
- const nextConfig: NextConfig = {
497
- pageExtensions: ['mdx', 'ts', 'tsx'],
498
- output: 'standalone',
499
- };
500
- export default nextConfig;
501
- `;
502
- mockedExists.mockImplementation((p) => p.endsWith('next.config.ts'));
503
- mockedRead.mockReturnValue(config);
504
- expect(readPageExtensions(ROOT)).toEqual(['mdx', 'ts', 'tsx']);
505
- });
506
- it('supports assignment syntax (`pageExtensions = [...]`)', () => {
507
- const config = `const pageExtensions = ['page.ts', 'ts', 'tsx'];`;
508
- mockedExists.mockImplementation((p) => p.endsWith('next.config.js'));
509
- mockedRead.mockReturnValue(config);
510
- // 'page.ts' is rejected (contains a dot); the rest pass the shape check.
511
- expect(readPageExtensions(ROOT)).toEqual(['ts', 'tsx']);
512
- });
513
- it('falls back to defaults when the declaration is inside a comment', () => {
514
- const config = `const nextConfig = {
515
- // pageExtensions: ['mdx'],
516
- output: 'standalone',
517
- };`;
518
- mockedExists.mockImplementation((p) => p.endsWith('next.config.ts'));
519
- mockedRead.mockReturnValue(config);
520
- expect(readPageExtensions(ROOT)).toEqual(['tsx', 'ts', 'jsx', 'js', 'mjs', 'cjs']);
521
- });
522
- it('falls back to defaults when next.config is missing', () => {
523
- mockedExists.mockReturnValue(false);
524
- expect(readPageExtensions(ROOT)).toEqual(['tsx', 'ts', 'jsx', 'js', 'mjs', 'cjs']);
525
- });
526
- it('falls back to defaults when the array cannot be parsed', () => {
527
- const config = `const nextConfig = { pageExtensions: computeExts() };`;
528
- mockedExists.mockImplementation((p) => p.endsWith('next.config.ts'));
529
- mockedRead.mockReturnValue(config);
530
- expect(readPageExtensions(ROOT)).toEqual(['tsx', 'ts', 'jsx', 'js', 'mjs', 'cjs']);
531
- });
532
- });
533
- describe('findPageBackups', () => {
534
- it('walks src/app and returns every backup file', () => {
535
- mockedExists.mockImplementation((p) => {
536
- const path = p;
537
- return path === '/project/src/app' || path.startsWith('/project/src/app');
538
- });
539
- mockedReaddir.mockImplementation((d) => {
540
- const dir = d;
541
- if (dir === '/project/src/app') {
542
- return ['welcome', 'other.txt'];
543
- }
544
- if (dir === '/project/src/app/welcome') {
545
- return ['page.ts', 'page.tsx.codapult-bak-onboarding'];
546
- }
547
- return [];
548
- });
549
- mockedStat.mockImplementation((p) => {
550
- const path = p;
551
- const isDir = path === '/project/src/app/welcome';
552
- return { isDirectory: () => isDir };
553
- });
554
- const backups = findPageBackups(ROOT);
555
- expect(backups).toEqual(['src/app/welcome/page.tsx.codapult-bak-onboarding']);
556
- });
557
- it('returns [] when src/app does not exist', () => {
558
- mockedExists.mockReturnValue(false);
559
- expect(findPageBackups(ROOT)).toEqual([]);
560
- });
561
- });
562
- // ---------------------------------------------------------------------------
563
- // patchEnvFile
564
- // ---------------------------------------------------------------------------
565
- describe('patchEnvFile', () => {
566
- it('appends env vars with markers on add', () => {
567
- const envContent = `APP_NAME=codapult\nSECRET=abc\n`;
568
- mockedExists.mockReturnValue(true);
569
- mockedRead.mockReturnValue(envContent);
570
- const envVars = {
571
- PLUGIN_API_KEY: {
572
- default: '',
573
- required: true,
574
- description: 'API key for the plugin',
575
- },
576
- PLUGIN_URL: { default: 'http://localhost:3001', required: false },
577
- };
578
- patchEnvFile(ROOT, 'test-plugin', envVars, 'add');
579
- const written = mockedWrite.mock.calls[0][1];
580
- expect(written).toContain('// --- plugin:test-plugin:start ---');
581
- expect(written).toContain('# API key for the plugin');
582
- expect(written).toContain('PLUGIN_API_KEY=');
583
- expect(written).toContain('PLUGIN_URL=http://localhost:3001');
584
- expect(written).toContain('// --- plugin:test-plugin:end ---');
585
- });
586
- it('removes env block on remove', () => {
587
- const envContent = `APP_NAME=codapult\n\n// --- plugin:test-plugin:start ---\nPLUGIN_KEY=abc\n// --- plugin:test-plugin:end ---\n`;
588
- mockedExists.mockReturnValue(true);
589
- mockedRead.mockReturnValue(envContent);
590
- patchEnvFile(ROOT, 'test-plugin', {}, 'remove');
591
- const written = mockedWrite.mock.calls[0][1];
592
- expect(written).not.toContain('PLUGIN_KEY');
593
- expect(written).not.toContain('plugin:test-plugin');
594
- expect(written).toContain('APP_NAME=codapult');
595
- });
596
- it('is idempotent — skips if marker already present', () => {
597
- const envContent = `// --- plugin:test-plugin:start ---\nKEY=val\n// --- plugin:test-plugin:end ---\n`;
598
- mockedExists.mockReturnValue(true);
599
- mockedRead.mockReturnValue(envContent);
600
- patchEnvFile(ROOT, 'test-plugin', { KEY: { required: true } }, 'add');
601
- expect(mockedWrite).not.toHaveBeenCalled();
602
- });
603
- it(`does nothing when ${ENV_FILE_NAME} does not exist`, () => {
604
- mockedExists.mockReturnValue(false);
605
- patchEnvFile(ROOT, 'test-plugin', { KEY: { required: true } }, 'add');
606
- expect(mockedWrite).not.toHaveBeenCalled();
607
- });
608
- });
609
- // ---------------------------------------------------------------------------
610
- // patchPackageJson
611
- // ---------------------------------------------------------------------------
612
- describe('patchPackageJson', () => {
613
- it('adds dependency with file: protocol on add', () => {
614
- const pkg = JSON.stringify({
615
- name: 'codapult',
616
- dependencies: { next: '16' },
617
- });
618
- mockedExists.mockReturnValue(true);
619
- mockedRead.mockReturnValue(pkg);
620
- patchPackageJson(ROOT, 'test-plugin', '@codapult/plugin-test', '/plugins/test-plugin', 'add');
621
- const written = mockedWrite.mock.calls[0][1];
622
- const parsed = JSON.parse(written);
623
- expect(parsed.dependencies['@codapult/plugin-test']).toMatch(/^file:/);
624
- expect(parsed.dependencies.next).toBe('16');
625
- });
626
- it('removes dependency on remove', () => {
627
- const pkg = JSON.stringify({
628
- name: 'codapult',
629
- dependencies: {
630
- next: '16',
631
- '@codapult/plugin-test': 'file:../test-plugin',
632
- },
633
- });
634
- mockedExists.mockReturnValue(true);
635
- mockedRead.mockReturnValue(pkg);
636
- patchPackageJson(ROOT, 'test-plugin', '@codapult/plugin-test', '/plugins/test-plugin', 'remove');
637
- const written = mockedWrite.mock.calls[0][1];
638
- const parsed = JSON.parse(written);
639
- expect(parsed.dependencies['@codapult/plugin-test']).toBeUndefined();
640
- expect(parsed.dependencies.next).toBe('16');
641
- });
642
- it('does nothing when package.json does not exist', () => {
643
- mockedExists.mockReturnValue(false);
644
- patchPackageJson(ROOT, 'test-plugin', '@codapult/plugin-test', '/plugins/test', 'add');
645
- expect(mockedWrite).not.toHaveBeenCalled();
646
- });
647
- });
@@ -1 +0,0 @@
1
- export {};