@codapult/cli 0.2.0 → 0.3.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.
@@ -1,7 +1,9 @@
1
- import { existsSync, readFileSync } from 'node:fs';
1
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
2
2
  import { resolve } from 'node:path';
3
3
  import { execSync } from 'node:child_process';
4
4
  import { findProjectRoot, readJsonFile } from '../utils/project.js';
5
+ import { resolveManifest } from '../utils/manifest.js';
6
+ import { findPageConflicts, findPageBackups } from '../utils/patchers.js';
5
7
  import { heading, success, fail, warn, info, dim, label } from '../utils/ui.js';
6
8
  function checkExists(root, path, description) {
7
9
  const exists = existsSync(resolve(root, path));
@@ -125,6 +127,49 @@ export function doctorCommand() {
125
127
  success('TypeScript compiles cleanly');
126
128
  }
127
129
  console.log();
130
+ // --- Plugins ---
131
+ info('Plugins');
132
+ const pluginsDir = resolve(root, 'src/plugins');
133
+ const installedPlugins = existsSync(pluginsDir)
134
+ ? readdirSync(pluginsDir)
135
+ .filter((f) => f.endsWith('.ts') && f !== 'index.ts')
136
+ .map((f) => f.replace('.ts', ''))
137
+ : [];
138
+ if (installedPlugins.length === 0) {
139
+ dim('No plugins installed.');
140
+ }
141
+ else {
142
+ let pluginProblems = 0;
143
+ for (const pName of installedPlugins) {
144
+ const resolved = resolveManifest(root, pName);
145
+ if (!resolved?.manifest.install.pages)
146
+ continue;
147
+ const conflicts = findPageConflicts(root, resolved.manifest.install.pages).filter((c) => !c.isStub);
148
+ if (conflicts.length === 0)
149
+ continue;
150
+ pluginProblems += 1;
151
+ warn(`${pName}: ${conflicts.length} page conflict(s) shadow plugin stubs`);
152
+ for (const c of conflicts) {
153
+ dim(` ${c.conflictRel} (shadows ${c.pagePath})`);
154
+ }
155
+ dim(` Fix: codapult plugins add ${pName} (will back up and overwrite)`);
156
+ }
157
+ if (pluginProblems === 0) {
158
+ success(`${installedPlugins.length} plugin(s): no page conflicts`);
159
+ }
160
+ else {
161
+ issues += pluginProblems;
162
+ }
163
+ const orphanBackups = findPageBackups(root);
164
+ if (orphanBackups.length > 0) {
165
+ warn(`${orphanBackups.length} page backup file(s) found:`);
166
+ for (const b of orphanBackups)
167
+ dim(` ${b}`);
168
+ dim(' These are restored automatically when the owning plugin is removed.');
169
+ warnings += 1;
170
+ }
171
+ }
172
+ console.log();
128
173
  // --- Git ---
129
174
  info('Git');
130
175
  const gitRemotes = tryExec('git remote -v', root);
@@ -4,7 +4,7 @@ import { resolve } from 'node:path';
4
4
  import { findProjectRoot } from '../utils/project.js';
5
5
  import { resolveManifest } from '../utils/manifest.js';
6
6
  import { clonePlugin } from '../utils/git.js';
7
- import { patchSchemaImports, patchSchemaTables, patchDbReExports, patchNextConfig, createPluginRegistration, patchPages, patchEnvFile, patchPackageJson, } from '../utils/patchers.js';
7
+ import { patchSchemaImports, patchSchemaTables, patchDbReExports, patchNextConfig, createPluginRegistration, patchPages, findPageConflicts, patchEnvFile, patchPackageJson, } from '../utils/patchers.js';
8
8
  import { heading, success, fail, warn, info, dim, confirm } from '../utils/ui.js';
9
9
  function execQuiet(cmd, cwd) {
10
10
  try {
@@ -113,9 +113,34 @@ export async function pluginsAddCommand(name, options) {
113
113
  }
114
114
  // 7. Create page wrappers
115
115
  if (manifest.install.pages && Object.keys(manifest.install.pages).length > 0) {
116
+ const pageEntries = manifest.install.pages;
117
+ const conflicts = findPageConflicts(root, pageEntries);
118
+ const nonStubConflicts = conflicts.filter((c) => !c.isStub);
119
+ if (nonStubConflicts.length > 0) {
120
+ warn(`Found ${nonStubConflicts.length} existing page file(s) that would collide with the plugin:`);
121
+ for (const c of nonStubConflicts) {
122
+ const hint = c.isExactPath ? 'same path' : 'same route, different extension';
123
+ dim(` ${c.conflictRel} (${hint})`);
124
+ }
125
+ if (options.ci) {
126
+ info(`CI mode: backing up conflicting files as *.codapult-bak-${manifest.name}`);
127
+ }
128
+ else {
129
+ const proceed = await confirm(`Back up conflicting files as *.codapult-bak-${manifest.name} and install?`, true);
130
+ if (!proceed) {
131
+ fail('Aborted by user. Resolve conflicts manually, then re-run.');
132
+ dim('To restore later, rename *.codapult-bak-* back or reinstall the plugin.');
133
+ process.exit(1);
134
+ }
135
+ }
136
+ }
116
137
  info('Creating page wrappers...');
117
- patchPages(root, manifest.name, manifest.install.pages, 'add');
118
- success(`${Object.keys(manifest.install.pages).length} page(s) created`);
138
+ patchPages(root, manifest.name, pageEntries, 'add', { onConflict: 'backup' });
139
+ success(`${Object.keys(pageEntries).length} page(s) created`);
140
+ if (nonStubConflicts.length > 0) {
141
+ dim(`Original files preserved as *.codapult-bak-${manifest.name}. ` +
142
+ `They are restored automatically when you run: codapult plugins remove ${manifest.name}`);
143
+ }
119
144
  }
120
145
  // 8. Register plugin (src/plugins/<name>.ts + regenerate barrel)
121
146
  info('Registering plugin...');
@@ -3,7 +3,7 @@ import { resolve } from 'node:path';
3
3
  import { z } from 'zod';
4
4
  import { findProjectRoot } from '../../utils/project.js';
5
5
  import { resolveManifest } from '../../utils/manifest.js';
6
- import { patchSchemaImports, patchSchemaTables, patchDbReExports, patchNextConfig, createPluginRegistration, patchPages, patchEnvFile, patchPackageJson, } from '../../utils/patchers.js';
6
+ import { patchSchemaImports, patchSchemaTables, patchDbReExports, patchNextConfig, createPluginRegistration, patchPages, findPageConflicts, patchEnvFile, patchPackageJson, } from '../../utils/patchers.js';
7
7
  function getRoot() {
8
8
  const root = findProjectRoot();
9
9
  if (!root)
@@ -75,9 +75,15 @@ export function registerPluginTools(server) {
75
75
  patchNextConfig(root, manifest.name, manifest, 'add');
76
76
  steps.push('next.config.ts updated');
77
77
  }
78
+ let backedUp = [];
78
79
  if (manifest.install.pages && Object.keys(manifest.install.pages).length > 0) {
79
- patchPages(root, manifest.name, manifest.install.pages, 'add');
80
+ const conflicts = findPageConflicts(root, manifest.install.pages);
81
+ backedUp = conflicts.filter((c) => !c.isStub).map((c) => c.conflictRel);
82
+ patchPages(root, manifest.name, manifest.install.pages, 'add', { onConflict: 'backup' });
80
83
  steps.push(`${Object.keys(manifest.install.pages).length} page(s) created`);
84
+ if (backedUp.length > 0) {
85
+ steps.push(`Backed up ${backedUp.length} existing page file(s) as *.codapult-bak-${manifest.name}`);
86
+ }
81
87
  }
82
88
  createPluginRegistration(root, manifest.name, manifest.package, 'add');
83
89
  steps.push('Plugin registered');
@@ -90,6 +96,7 @@ export function registerPluginTools(server) {
90
96
  package: manifest.package,
91
97
  version: manifest.version,
92
98
  steps,
99
+ backedUpPages: backedUp,
93
100
  nextSteps: [
94
101
  'Run: pnpm install --no-frozen-lockfile',
95
102
  'Run: pnpm db:push (if schema changed)',
@@ -5,7 +5,68 @@ export declare function patchDbReExports(projectRoot: string, pluginName: string
5
5
  export declare function patchNextConfig(projectRoot: string, pluginName: string, manifest: PluginManifest, action: 'add' | 'remove'): void;
6
6
  export declare function regenerateBarrel(projectRoot: string): void;
7
7
  export declare function createPluginRegistration(projectRoot: string, pluginName: string, packageName: string, action: 'add' | 'remove'): void;
8
- export declare function patchPages(projectRoot: string, pluginName: string, pages: Record<string, string>, action: 'add' | 'remove'): void;
8
+ /**
9
+ * Read `pageExtensions` declared in `next.config.*`. Falls back to the
10
+ * Next.js defaults when no config exists, no explicit `pageExtensions` is
11
+ * declared, or parsing fails for any reason.
12
+ *
13
+ * The parser is intentionally text-based: dynamically evaluating user
14
+ * `next.config.ts` would drag in the whole Next/plugin graph and is far
15
+ * beyond the CLI's remit.
16
+ */
17
+ export declare function readPageExtensions(projectRoot: string): readonly string[];
18
+ export interface PageConflict {
19
+ /** Path declared in the manifest (relative to project root). */
20
+ pagePath: string;
21
+ /** Conflicting sibling file that Next.js may resolve instead (absolute). */
22
+ conflictPath: string;
23
+ /** Same path, relative to project root (for logs). */
24
+ conflictRel: string;
25
+ /** The conflict is also at the exact manifest path (same extension). */
26
+ isExactPath: boolean;
27
+ /** Existing file is a plugin stub (auto-generated re-export). */
28
+ isStub: boolean;
29
+ /** Existing file is our own stub for the current plugin. */
30
+ isOwnStub: boolean;
31
+ }
32
+ /**
33
+ * Inspect the project tree and report every existing page file that would
34
+ * collide with the stubs declared in `pages`. Includes collisions at the
35
+ * exact manifest path AND at sibling paths with a different Next.js page
36
+ * extension (e.g. `page.ts` vs `page.tsx`). Returns an empty array when
37
+ * there is nothing to worry about.
38
+ *
39
+ * `pageExtensions` defaults to values read from `next.config.*`, falling
40
+ * back to the Next.js built-in defaults. Tests or advanced callers can
41
+ * pass an explicit list.
42
+ */
43
+ export declare function findPageConflicts(projectRoot: string, pages: Record<string, string>, pageExtensions?: readonly string[]): PageConflict[];
44
+ export interface PatchPagesOptions {
45
+ /**
46
+ * What to do when an existing page file would collide with the stub.
47
+ * - 'backup' (default): rename the conflicting file to
48
+ * `<name>.codapult-bak-<plugin>` before writing the stub.
49
+ * - 'fail': throw an Error listing the conflicts. Callers can catch and
50
+ * re-prompt, or re-throw to abort.
51
+ */
52
+ onConflict?: 'backup' | 'fail';
53
+ /**
54
+ * Override the list of page extensions considered when detecting
55
+ * conflicts. Defaults to `pageExtensions` read from `next.config.*`
56
+ * (Next.js defaults as fallback).
57
+ */
58
+ pageExtensions?: readonly string[];
59
+ }
60
+ export declare class PageConflictError extends Error {
61
+ readonly conflicts: PageConflict[];
62
+ constructor(conflicts: PageConflict[]);
63
+ }
64
+ export declare function patchPages(projectRoot: string, pluginName: string, pages: Record<string, string>, action: 'add' | 'remove', options?: PatchPagesOptions): void;
65
+ /**
66
+ * Find every `*.codapult-bak-*` file below `src/app`. Used by `codapult
67
+ * doctor` to surface orphaned backups left over after a failed install.
68
+ */
69
+ export declare function findPageBackups(projectRoot: string): string[];
9
70
  export declare function patchEnvFile(projectRoot: string, pluginName: string, envVars: Record<string, {
10
71
  default?: string;
11
72
  required: boolean;
@@ -1,5 +1,5 @@
1
- import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync, rmSync, rmdirSync, } from 'node:fs';
2
- import { resolve, dirname, relative } from 'node:path';
1
+ import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync, renameSync, rmSync, rmdirSync, statSync, } from 'node:fs';
2
+ import { resolve, dirname, relative, basename, extname, join } from 'node:path';
3
3
  const MARKER_START = (name) => `// --- plugin:${name}:start ---`;
4
4
  const MARKER_END = (name) => `// --- plugin:${name}:end ---`;
5
5
  function hasMarker(content, name) {
@@ -232,7 +232,7 @@ export function createPluginRegistration(projectRoot, pluginName, packageName, a
232
232
  }
233
233
  }
234
234
  else {
235
- const content = `import { registerPlugin } from '@/lib/plugins';\nimport plugin from '${packageName}';\n\nregisterPlugin(plugin);\n`;
235
+ const content = `import plugin from '${packageName}';\nimport { registerPlugin } from '@/lib/plugins';\n\nregisterPlugin(plugin);\n`;
236
236
  writeFileSync(regFile, content, 'utf-8');
237
237
  }
238
238
  regenerateBarrel(projectRoot);
@@ -240,13 +240,197 @@ export function createPluginRegistration(projectRoot, pluginName, packageName, a
240
240
  // ---------------------------------------------------------------------------
241
241
  // Page wrappers — create/remove re-export files
242
242
  // ---------------------------------------------------------------------------
243
- export function patchPages(projectRoot, pluginName, pages, action) {
243
+ // Next.js default `pageExtensions`. Ordered by resolution priority — the first
244
+ // extension with an existing file wins at routing time, regardless of what the
245
+ // plugin manifest asked for. Used as a fallback when `next.config.*` cannot be
246
+ // parsed or does not declare a custom list.
247
+ const DEFAULT_PAGE_EXTENSIONS = ['tsx', 'ts', 'jsx', 'js', 'mjs', 'cjs'];
248
+ const NEXT_CONFIG_CANDIDATES = [
249
+ 'next.config.ts',
250
+ 'next.config.mts',
251
+ 'next.config.js',
252
+ 'next.config.mjs',
253
+ 'next.config.cjs',
254
+ ];
255
+ const PAGE_EXT_NAME_RE = /^[a-z0-9]+$/i;
256
+ /**
257
+ * Strip `//` line comments and `/* ... *\/` block comments from a JS/TS
258
+ * source. Very rough — good enough so that commented-out `pageExtensions`
259
+ * declarations do not confuse the extractor.
260
+ */
261
+ function stripComments(source) {
262
+ return source
263
+ .replace(/\/\*[\s\S]*?\*\//g, '')
264
+ .replace(/(^|[^:/])\/\/[^\n]*/g, (_m, prefix) => prefix);
265
+ }
266
+ /**
267
+ * Read `pageExtensions` declared in `next.config.*`. Falls back to the
268
+ * Next.js defaults when no config exists, no explicit `pageExtensions` is
269
+ * declared, or parsing fails for any reason.
270
+ *
271
+ * The parser is intentionally text-based: dynamically evaluating user
272
+ * `next.config.ts` would drag in the whole Next/plugin graph and is far
273
+ * beyond the CLI's remit.
274
+ */
275
+ export function readPageExtensions(projectRoot) {
276
+ for (const candidate of NEXT_CONFIG_CANDIDATES) {
277
+ const configPath = resolve(projectRoot, candidate);
278
+ if (!existsSync(configPath))
279
+ continue;
280
+ let raw;
281
+ try {
282
+ raw = readFileSync(configPath, 'utf-8');
283
+ }
284
+ catch {
285
+ continue;
286
+ }
287
+ const source = stripComments(raw);
288
+ const match = /pageExtensions\s*[:=]\s*\[([\s\S]*?)\]/.exec(source);
289
+ if (!match)
290
+ return [...DEFAULT_PAGE_EXTENSIONS];
291
+ const literals = [...match[1].matchAll(/['"`]([^'"`]+)['"`]/g)]
292
+ .map((m) => m[1].trim().toLowerCase())
293
+ .filter((ext) => PAGE_EXT_NAME_RE.test(ext));
294
+ if (literals.length === 0)
295
+ return [...DEFAULT_PAGE_EXTENSIONS];
296
+ return Array.from(new Set(literals));
297
+ }
298
+ return [...DEFAULT_PAGE_EXTENSIONS];
299
+ }
300
+ const PAGE_BACKUP_SUFFIX = '.codapult-bak';
301
+ /**
302
+ * Content of the stub file that `patchPages` writes. Kept in sync with
303
+ * the writeFileSync call below so that conflict detection can distinguish
304
+ * an auto-generated stub from hand-written page code.
305
+ */
306
+ function makeStubContent(exportFrom) {
307
+ return `export { default } from '${exportFrom}';\n`;
308
+ }
309
+ const STUB_RE = /^\s*export\s*\{\s*default\s*\}\s*from\s*['"]([^'"]+)['"];?\s*$/;
310
+ function parseStub(content) {
311
+ const match = STUB_RE.exec(content.trim());
312
+ if (!match)
313
+ return null;
314
+ return { exportFrom: match[1] };
315
+ }
316
+ function backupPathFor(filePath, pluginName) {
317
+ return `${filePath}${PAGE_BACKUP_SUFFIX}-${pluginName}`;
318
+ }
319
+ function restoreBackupsFor(projectRoot, pluginName, pagePath) {
320
+ const fullPath = resolve(projectRoot, pagePath);
321
+ const dir = dirname(fullPath);
322
+ if (!existsSync(dir))
323
+ return [];
324
+ const stubBase = basename(fullPath, extname(fullPath));
325
+ const suffix = `${PAGE_BACKUP_SUFFIX}-${pluginName}`;
326
+ const restored = [];
327
+ let entries;
328
+ try {
329
+ entries = readdirSync(dir);
330
+ }
331
+ catch {
332
+ return [];
333
+ }
334
+ for (const entry of entries) {
335
+ if (!entry.endsWith(suffix))
336
+ continue;
337
+ const originalName = entry.slice(0, -suffix.length);
338
+ // Only restore siblings for the same page slot (e.g. page.*, layout.*).
339
+ const originalBase = basename(originalName, extname(originalName));
340
+ if (originalBase !== stubBase)
341
+ continue;
342
+ const src = join(dir, entry);
343
+ const dst = join(dir, originalName);
344
+ if (existsSync(dst)) {
345
+ // The stub was replaced with something else since — leave the backup
346
+ // in place rather than silently overwriting user code.
347
+ continue;
348
+ }
349
+ try {
350
+ renameSync(src, dst);
351
+ restored.push(relative(projectRoot, dst));
352
+ }
353
+ catch {
354
+ // Best-effort restore; ignore failures
355
+ }
356
+ }
357
+ return restored;
358
+ }
359
+ function collectConflictsForEntry(projectRoot, pagePath, exportFrom, extensions) {
360
+ const fullPath = resolve(projectRoot, pagePath);
361
+ const dir = dirname(fullPath);
362
+ const stubBase = basename(fullPath, extname(fullPath));
363
+ const targetExt = extname(fullPath).slice(1);
364
+ const conflicts = [];
365
+ const expectedStub = makeStubContent(exportFrom);
366
+ for (const ext of extensions) {
367
+ const candidate = join(dir, `${stubBase}.${ext}`);
368
+ if (!existsSync(candidate))
369
+ continue;
370
+ let content;
371
+ try {
372
+ content = readFileSync(candidate, 'utf-8');
373
+ }
374
+ catch {
375
+ continue;
376
+ }
377
+ const stub = parseStub(content);
378
+ const isStub = stub !== null;
379
+ const isOwnStub = isStub && (content === expectedStub || stub.exportFrom === exportFrom);
380
+ const isExactPath = ext === targetExt;
381
+ // Our own freshly-written stub is not a conflict. It's how idempotent
382
+ // re-installs are supposed to look.
383
+ if (isExactPath && isOwnStub)
384
+ continue;
385
+ conflicts.push({
386
+ pagePath,
387
+ conflictPath: candidate,
388
+ conflictRel: relative(projectRoot, candidate),
389
+ isExactPath,
390
+ isStub,
391
+ isOwnStub,
392
+ });
393
+ }
394
+ return conflicts;
395
+ }
396
+ /**
397
+ * Inspect the project tree and report every existing page file that would
398
+ * collide with the stubs declared in `pages`. Includes collisions at the
399
+ * exact manifest path AND at sibling paths with a different Next.js page
400
+ * extension (e.g. `page.ts` vs `page.tsx`). Returns an empty array when
401
+ * there is nothing to worry about.
402
+ *
403
+ * `pageExtensions` defaults to values read from `next.config.*`, falling
404
+ * back to the Next.js built-in defaults. Tests or advanced callers can
405
+ * pass an explicit list.
406
+ */
407
+ export function findPageConflicts(projectRoot, pages, pageExtensions) {
408
+ const exts = pageExtensions ?? readPageExtensions(projectRoot);
409
+ const all = [];
244
410
  for (const [pagePath, exportFrom] of Object.entries(pages)) {
245
- const fullPath = resolve(projectRoot, pagePath);
246
- if (action === 'remove') {
411
+ all.push(...collectConflictsForEntry(projectRoot, pagePath, exportFrom, exts));
412
+ }
413
+ return all;
414
+ }
415
+ export class PageConflictError extends Error {
416
+ conflicts;
417
+ constructor(conflicts) {
418
+ super(`Page conflict${conflicts.length === 1 ? '' : 's'} detected: ${conflicts
419
+ .map((c) => c.conflictRel)
420
+ .join(', ')}`);
421
+ this.name = 'PageConflictError';
422
+ this.conflicts = conflicts;
423
+ }
424
+ }
425
+ export function patchPages(projectRoot, pluginName, pages, action, options = {}) {
426
+ const strategy = options.onConflict ?? 'backup';
427
+ if (action === 'remove') {
428
+ for (const [pagePath] of Object.entries(pages)) {
429
+ const fullPath = resolve(projectRoot, pagePath);
247
430
  if (existsSync(fullPath)) {
248
431
  rmSync(fullPath);
249
432
  }
433
+ restoreBackupsFor(projectRoot, pluginName, pagePath);
250
434
  try {
251
435
  let dir = dirname(fullPath);
252
436
  const srcDir = resolve(projectRoot, 'src');
@@ -264,13 +448,90 @@ export function patchPages(projectRoot, pluginName, pages, action) {
264
448
  catch {
265
449
  // Ignore cleanup errors
266
450
  }
267
- continue;
451
+ }
452
+ return;
453
+ }
454
+ // action === 'add'
455
+ const extensions = options.pageExtensions ?? readPageExtensions(projectRoot);
456
+ const allConflicts = [];
457
+ for (const [pagePath, exportFrom] of Object.entries(pages)) {
458
+ allConflicts.push(...collectConflictsForEntry(projectRoot, pagePath, exportFrom, extensions));
459
+ }
460
+ // Plugin stubs (from us or other plugins) can be safely overwritten. Only
461
+ // hand-written pages force us into conflict-resolution mode.
462
+ const nonStubConflicts = allConflicts.filter((c) => !c.isStub);
463
+ if (nonStubConflicts.length > 0 && strategy === 'fail') {
464
+ throw new PageConflictError(nonStubConflicts);
465
+ }
466
+ for (const [pagePath, exportFrom] of Object.entries(pages)) {
467
+ const fullPath = resolve(projectRoot, pagePath);
468
+ const content = makeStubContent(exportFrom);
469
+ const conflicts = collectConflictsForEntry(projectRoot, pagePath, exportFrom, extensions);
470
+ for (const conflict of conflicts) {
471
+ if (conflict.isStub) {
472
+ // Drop sibling stubs at a different extension so Next.js does not
473
+ // pick an older one. The target-path stub will be overwritten below.
474
+ if (!conflict.isExactPath) {
475
+ rmSync(conflict.conflictPath);
476
+ }
477
+ continue;
478
+ }
479
+ // Non-stub user code: move it aside.
480
+ const backup = backupPathFor(conflict.conflictPath, pluginName);
481
+ if (existsSync(backup)) {
482
+ // A previous install already preserved the original — keep that
483
+ // backup untouched and just remove the live file.
484
+ rmSync(conflict.conflictPath);
485
+ }
486
+ else {
487
+ renameSync(conflict.conflictPath, backup);
488
+ }
268
489
  }
269
490
  mkdirSync(dirname(fullPath), { recursive: true });
270
- const content = `export { default } from '${exportFrom}';\n`;
271
491
  writeFileSync(fullPath, content, 'utf-8');
272
492
  }
273
493
  }
494
+ /**
495
+ * Find every `*.codapult-bak-*` file below `src/app`. Used by `codapult
496
+ * doctor` to surface orphaned backups left over after a failed install.
497
+ */
498
+ export function findPageBackups(projectRoot) {
499
+ const root = resolve(projectRoot, 'src/app');
500
+ if (!existsSync(root))
501
+ return [];
502
+ const found = [];
503
+ const stack = [root];
504
+ while (stack.length > 0) {
505
+ const dir = stack.pop();
506
+ if (!dir)
507
+ continue;
508
+ let entries;
509
+ try {
510
+ entries = readdirSync(dir);
511
+ }
512
+ catch {
513
+ continue;
514
+ }
515
+ for (const entry of entries) {
516
+ const full = join(dir, entry);
517
+ let isDir;
518
+ try {
519
+ isDir = statSync(full).isDirectory();
520
+ }
521
+ catch {
522
+ continue;
523
+ }
524
+ if (isDir) {
525
+ stack.push(full);
526
+ continue;
527
+ }
528
+ if (entry.includes(PAGE_BACKUP_SUFFIX)) {
529
+ found.push(relative(projectRoot, full));
530
+ }
531
+ }
532
+ }
533
+ return found;
534
+ }
274
535
  // ---------------------------------------------------------------------------
275
536
  // .env.local — append env vars
276
537
  // ---------------------------------------------------------------------------
@@ -1,14 +1,16 @@
1
1
  import { describe, it, expect, vi, beforeEach } from 'vitest';
2
- import { patchSchemaImports, patchSchemaTables, patchDbReExports, patchNextConfig, regenerateBarrel, createPluginRegistration, patchPages, patchEnvFile, patchPackageJson, } from './patchers.js';
2
+ import { patchSchemaImports, patchSchemaTables, patchDbReExports, patchNextConfig, regenerateBarrel, createPluginRegistration, patchPages, findPageConflicts, findPageBackups, readPageExtensions, PageConflictError, patchEnvFile, patchPackageJson, } from './patchers.js';
3
3
  vi.mock('node:fs');
4
- const { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync, rmSync, rmdirSync } = await import('node:fs');
4
+ const { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync, renameSync, rmSync, rmdirSync, statSync, } = await import('node:fs');
5
5
  const mockedExists = vi.mocked(existsSync);
6
6
  const mockedRead = vi.mocked(readFileSync);
7
7
  const mockedWrite = vi.mocked(writeFileSync);
8
8
  const mockedMkdir = vi.mocked(mkdirSync);
9
9
  const mockedReaddir = vi.mocked(readdirSync);
10
+ const mockedRename = vi.mocked(renameSync);
10
11
  const mockedRm = vi.mocked(rmSync);
11
12
  const mockedRmdir = vi.mocked(rmdirSync);
13
+ const mockedStat = vi.mocked(statSync);
12
14
  const ROOT = '/project';
13
15
  beforeEach(() => {
14
16
  vi.resetAllMocks();
@@ -323,6 +325,214 @@ describe('patchPages', () => {
323
325
  expect(mockedRm).toHaveBeenCalled();
324
326
  expect(mockedRmdir).toHaveBeenCalled();
325
327
  });
328
+ it('backs up a user-written page at a different extension before writing the stub', () => {
329
+ const pages = {
330
+ 'src/app/[locale]/(marketing)/welcome/page.ts': '@codapult/plugin-onboarding/pages/welcome',
331
+ };
332
+ const userTsx = '/project/src/app/[locale]/(marketing)/welcome/page.tsx';
333
+ // Only the .tsx sibling exists on disk; no backup file yet.
334
+ mockedExists.mockImplementation((p) => p === userTsx);
335
+ mockedRead.mockReturnValue('export default function Welcome(): JSX.Element { return <div>old</div>; }');
336
+ patchPages(ROOT, 'onboarding', pages, 'add');
337
+ expect(mockedRename).toHaveBeenCalledWith(userTsx, `${userTsx}.codapult-bak-onboarding`);
338
+ const writtenPath = mockedWrite.mock.calls[0][0];
339
+ const writtenContent = mockedWrite.mock.calls[0][1];
340
+ expect(writtenPath).toContain('page.ts');
341
+ expect(writtenPath).not.toMatch(/page\.tsx$/);
342
+ expect(writtenContent).toContain("export { default } from '@codapult/plugin-onboarding/pages/welcome';");
343
+ });
344
+ it('does not re-backup when a backup already exists (idempotent re-install)', () => {
345
+ const pages = {
346
+ 'src/app/welcome/page.ts': '@codapult/plugin-onboarding/pages/welcome',
347
+ };
348
+ const userTsx = '/project/src/app/welcome/page.tsx';
349
+ const backup = `${userTsx}.codapult-bak-onboarding`;
350
+ mockedExists.mockImplementation((p) => {
351
+ const path = p;
352
+ return path === userTsx || path === backup;
353
+ });
354
+ mockedRead.mockReturnValue('export default function UserPage() {}');
355
+ patchPages(ROOT, 'onboarding', pages, 'add');
356
+ expect(mockedRename).not.toHaveBeenCalled();
357
+ expect(mockedRm).toHaveBeenCalledWith(userTsx);
358
+ });
359
+ it('silently overwrites sibling plugin stubs without creating a backup', () => {
360
+ const pages = {
361
+ 'src/app/welcome/page.ts': '@codapult/plugin-onboarding/pages/welcome',
362
+ };
363
+ const siblingStub = '/project/src/app/welcome/page.tsx';
364
+ mockedExists.mockImplementation((p) => p === siblingStub);
365
+ mockedRead.mockReturnValue("export { default } from 'some-other-package/pages/welcome';\n");
366
+ patchPages(ROOT, 'onboarding', pages, 'add');
367
+ expect(mockedRename).not.toHaveBeenCalled();
368
+ expect(mockedRm).toHaveBeenCalledWith(siblingStub);
369
+ });
370
+ it('is idempotent when the same stub was written previously', () => {
371
+ const pages = {
372
+ 'src/app/welcome/page.ts': '@codapult/plugin-onboarding/pages/welcome',
373
+ };
374
+ const targetPath = '/project/src/app/welcome/page.ts';
375
+ const stub = "export { default } from '@codapult/plugin-onboarding/pages/welcome';\n";
376
+ mockedExists.mockImplementation((p) => p === targetPath);
377
+ mockedRead.mockReturnValue(stub);
378
+ patchPages(ROOT, 'onboarding', pages, 'add');
379
+ expect(mockedRename).not.toHaveBeenCalled();
380
+ expect(mockedRm).not.toHaveBeenCalled();
381
+ // Still writes (idempotent re-write of identical content)
382
+ expect(mockedWrite).toHaveBeenCalled();
383
+ });
384
+ it('throws PageConflictError when onConflict is "fail"', () => {
385
+ const pages = {
386
+ 'src/app/welcome/page.ts': '@codapult/plugin-onboarding/pages/welcome',
387
+ };
388
+ const userTsx = '/project/src/app/welcome/page.tsx';
389
+ mockedExists.mockImplementation((p) => p === userTsx);
390
+ mockedRead.mockReturnValue('export default function User() {}');
391
+ expect(() => patchPages(ROOT, 'onboarding', pages, 'add', { onConflict: 'fail' })).toThrow(PageConflictError);
392
+ expect(mockedRename).not.toHaveBeenCalled();
393
+ expect(mockedWrite).not.toHaveBeenCalled();
394
+ });
395
+ it('restores backup files on remove', () => {
396
+ const pages = {
397
+ 'src/app/welcome/page.ts': '@codapult/plugin-onboarding/pages/welcome',
398
+ };
399
+ // Target page.ts exists; its directory has one matching backup entry.
400
+ mockedExists.mockImplementation((p) => {
401
+ const path = p;
402
+ return (path === '/project/src/app/welcome/page.ts' ||
403
+ path === '/project/src/app/welcome' ||
404
+ path.endsWith('src/app'));
405
+ });
406
+ mockedReaddir.mockImplementation((d) => {
407
+ const dir = d;
408
+ if (dir === '/project/src/app/welcome') {
409
+ return ['page.tsx.codapult-bak-onboarding'];
410
+ }
411
+ return [];
412
+ });
413
+ patchPages(ROOT, 'onboarding', pages, 'remove');
414
+ expect(mockedRm).toHaveBeenCalledWith('/project/src/app/welcome/page.ts');
415
+ expect(mockedRename).toHaveBeenCalledWith('/project/src/app/welcome/page.tsx.codapult-bak-onboarding', '/project/src/app/welcome/page.tsx');
416
+ });
417
+ it('does not restore a backup when a live file already occupies its target name', () => {
418
+ const pages = {
419
+ 'src/app/welcome/page.ts': '@codapult/plugin-onboarding/pages/welcome',
420
+ };
421
+ const live = '/project/src/app/welcome/page.tsx';
422
+ mockedExists.mockImplementation((p) => {
423
+ const path = p;
424
+ return (path === '/project/src/app/welcome/page.ts' ||
425
+ path === live ||
426
+ path === '/project/src/app/welcome');
427
+ });
428
+ mockedReaddir.mockImplementation((d) => {
429
+ const dir = d;
430
+ if (dir === '/project/src/app/welcome') {
431
+ return ['page.ts', 'page.tsx', 'page.tsx.codapult-bak-onboarding'];
432
+ }
433
+ return [];
434
+ });
435
+ patchPages(ROOT, 'onboarding', pages, 'remove');
436
+ expect(mockedRename).not.toHaveBeenCalled();
437
+ });
438
+ });
439
+ describe('findPageConflicts', () => {
440
+ it('reports a sibling file at a different Next.js page extension', () => {
441
+ const pages = { 'src/app/welcome/page.ts': '@codapult/plugin-onboarding/pages/welcome' };
442
+ const sibling = '/project/src/app/welcome/page.tsx';
443
+ mockedExists.mockImplementation((p) => p === sibling);
444
+ mockedRead.mockReturnValue('export default function User() {}');
445
+ const conflicts = findPageConflicts(ROOT, pages);
446
+ expect(conflicts).toHaveLength(1);
447
+ expect(conflicts[0].isStub).toBe(false);
448
+ expect(conflicts[0].isExactPath).toBe(false);
449
+ expect(conflicts[0].conflictRel).toBe('src/app/welcome/page.tsx');
450
+ });
451
+ it('returns [] when the only file at the target path is our own stub', () => {
452
+ const pages = { 'src/app/welcome/page.ts': '@codapult/plugin-onboarding/pages/welcome' };
453
+ const target = '/project/src/app/welcome/page.ts';
454
+ mockedExists.mockImplementation((p) => p === target);
455
+ mockedRead.mockReturnValue("export { default } from '@codapult/plugin-onboarding/pages/welcome';\n");
456
+ expect(findPageConflicts(ROOT, pages)).toEqual([]);
457
+ });
458
+ it('flags foreign stubs as conflicts but marks them isStub=true', () => {
459
+ const pages = { 'src/app/welcome/page.ts': '@codapult/plugin-onboarding/pages/welcome' };
460
+ const sibling = '/project/src/app/welcome/page.tsx';
461
+ mockedExists.mockImplementation((p) => p === sibling);
462
+ mockedRead.mockReturnValue("export { default } from 'some-other/pages/welcome';\n");
463
+ const conflicts = findPageConflicts(ROOT, pages);
464
+ expect(conflicts).toHaveLength(1);
465
+ expect(conflicts[0].isStub).toBe(true);
466
+ });
467
+ });
468
+ describe('readPageExtensions', () => {
469
+ it('reads a custom pageExtensions array from next.config.ts', () => {
470
+ const config = `import type { NextConfig } from 'next';
471
+ const nextConfig: NextConfig = {
472
+ pageExtensions: ['mdx', 'ts', 'tsx'],
473
+ output: 'standalone',
474
+ };
475
+ export default nextConfig;
476
+ `;
477
+ mockedExists.mockImplementation((p) => p.endsWith('next.config.ts'));
478
+ mockedRead.mockReturnValue(config);
479
+ expect(readPageExtensions(ROOT)).toEqual(['mdx', 'ts', 'tsx']);
480
+ });
481
+ it('supports assignment syntax (`pageExtensions = [...]`)', () => {
482
+ const config = `const pageExtensions = ['page.ts', 'ts', 'tsx'];`;
483
+ mockedExists.mockImplementation((p) => p.endsWith('next.config.js'));
484
+ mockedRead.mockReturnValue(config);
485
+ // 'page.ts' is rejected (contains a dot); the rest pass the shape check.
486
+ expect(readPageExtensions(ROOT)).toEqual(['ts', 'tsx']);
487
+ });
488
+ it('falls back to defaults when the declaration is inside a comment', () => {
489
+ const config = `const nextConfig = {
490
+ // pageExtensions: ['mdx'],
491
+ output: 'standalone',
492
+ };`;
493
+ mockedExists.mockImplementation((p) => p.endsWith('next.config.ts'));
494
+ mockedRead.mockReturnValue(config);
495
+ expect(readPageExtensions(ROOT)).toEqual(['tsx', 'ts', 'jsx', 'js', 'mjs', 'cjs']);
496
+ });
497
+ it('falls back to defaults when next.config is missing', () => {
498
+ mockedExists.mockReturnValue(false);
499
+ expect(readPageExtensions(ROOT)).toEqual(['tsx', 'ts', 'jsx', 'js', 'mjs', 'cjs']);
500
+ });
501
+ it('falls back to defaults when the array cannot be parsed', () => {
502
+ const config = `const nextConfig = { pageExtensions: computeExts() };`;
503
+ mockedExists.mockImplementation((p) => p.endsWith('next.config.ts'));
504
+ mockedRead.mockReturnValue(config);
505
+ expect(readPageExtensions(ROOT)).toEqual(['tsx', 'ts', 'jsx', 'js', 'mjs', 'cjs']);
506
+ });
507
+ });
508
+ describe('findPageBackups', () => {
509
+ it('walks src/app and returns every backup file', () => {
510
+ mockedExists.mockImplementation((p) => {
511
+ const path = p;
512
+ return path === '/project/src/app' || path.startsWith('/project/src/app');
513
+ });
514
+ mockedReaddir.mockImplementation((d) => {
515
+ const dir = d;
516
+ if (dir === '/project/src/app') {
517
+ return ['welcome', 'other.txt'];
518
+ }
519
+ if (dir === '/project/src/app/welcome') {
520
+ return ['page.ts', 'page.tsx.codapult-bak-onboarding'];
521
+ }
522
+ return [];
523
+ });
524
+ mockedStat.mockImplementation((p) => {
525
+ const path = p;
526
+ const isDir = path === '/project/src/app/welcome';
527
+ return { isDirectory: () => isDir };
528
+ });
529
+ const backups = findPageBackups(ROOT);
530
+ expect(backups).toEqual(['src/app/welcome/page.tsx.codapult-bak-onboarding']);
531
+ });
532
+ it('returns [] when src/app does not exist', () => {
533
+ mockedExists.mockReturnValue(false);
534
+ expect(findPageBackups(ROOT)).toEqual([]);
535
+ });
326
536
  });
327
537
  // ---------------------------------------------------------------------------
328
538
  // patchEnvFile
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codapult/cli",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Codapult CLI — manage, update, and diagnose your Codapult SaaS project",
5
5
  "license": "MIT",
6
6
  "type": "module",