@codapult/cli 0.2.0 → 0.4.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.
@@ -0,0 +1,211 @@
1
+ /**
2
+ * Shared, read-only mirror of `src/lib/config.ts` from the host project.
3
+ *
4
+ * Keep this file in sync with the host's `env.features`, `env.auth`,
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).
10
+ */
11
+ /** Feature toggle key → ENABLE_* env var. Order = display order. */
12
+ export const FEATURE_ENV = {
13
+ apiDocs: 'ENABLE_API_DOCS',
14
+ helpCenter: 'ENABLE_HELP_CENTER',
15
+ blog: 'ENABLE_BLOG',
16
+ waitlist: 'ENABLE_WAITLIST',
17
+ featureRequests: 'ENABLE_FEATURE_REQUESTS',
18
+ changelog: 'ENABLE_CHANGELOG',
19
+ aiChat: 'ENABLE_AI_CHAT',
20
+ teams: 'ENABLE_TEAMS',
21
+ referrals: 'ENABLE_REFERRALS',
22
+ analytics: 'ENABLE_ANALYTICS',
23
+ workflows: 'ENABLE_WORKFLOWS',
24
+ webhooks: 'ENABLE_WEBHOOKS',
25
+ auditLog: 'ENABLE_AUDIT_LOG',
26
+ reports: 'ENABLE_REPORTS',
27
+ onboarding: 'ENABLE_ONBOARDING',
28
+ branding: 'ENABLE_BRANDING',
29
+ sso: 'ENABLE_SSO',
30
+ experiments: 'ENABLE_EXPERIMENTS',
31
+ dripCampaigns: 'ENABLE_DRIP_CAMPAIGNS',
32
+ plugins: 'ENABLE_PLUGINS',
33
+ };
34
+ /** Auth-gated features: when AUTH_PROVIDER=none, these are forced off. */
35
+ export const AUTH_GATED_FEATURES = new Set([
36
+ 'apiDocs',
37
+ 'featureRequests',
38
+ 'changelog',
39
+ 'aiChat',
40
+ 'teams',
41
+ 'referrals',
42
+ ]);
43
+ /** OAuth provider → [client id env, client secret env]. Mirrors oauth-providers.ts. */
44
+ export const OAUTH_CREDENTIAL_KEYS = {
45
+ google: ['GOOGLE_CLIENT_ID', 'GOOGLE_CLIENT_SECRET'],
46
+ github: ['GITHUB_CLIENT_ID', 'GITHUB_CLIENT_SECRET'],
47
+ apple: ['APPLE_CLIENT_ID', 'APPLE_CLIENT_SECRET'],
48
+ discord: ['DISCORD_CLIENT_ID', 'DISCORD_CLIENT_SECRET'],
49
+ twitter: ['TWITTER_CLIENT_ID', 'TWITTER_CLIENT_SECRET'],
50
+ microsoft: ['MICROSOFT_CLIENT_ID', 'MICROSOFT_CLIENT_SECRET'],
51
+ };
52
+ /** Read a single var from raw .env content. Returns undefined if missing or empty. */
53
+ export function readEnvVar(envContent, key) {
54
+ const match = new RegExp(`^${key}\\s*=\\s*"?([^"\\n\\r]*)"?\\s*$`, 'm').exec(envContent);
55
+ const value = match?.[1]?.trim();
56
+ return value && value.length > 0 ? value : undefined;
57
+ }
58
+ /** Same as `readEnvVar` but with a typed fallback. */
59
+ export function readEnv(envContent, key, fallback) {
60
+ return readEnvVar(envContent, key) ?? fallback;
61
+ }
62
+ /** Resolve all adapters from .env content, applying the same defaults as `env.*`. */
63
+ export function getAdapters(envContent) {
64
+ return {
65
+ database: readEnv(envContent, 'DB_PROVIDER', 'turso'),
66
+ auth: readEnv(envContent, 'AUTH_PROVIDER', 'better-auth'),
67
+ payments: readEnv(envContent, 'PAYMENT_PROVIDER', 'stripe'),
68
+ storage: readEnv(envContent, 'STORAGE_PROVIDER', 'local'),
69
+ jobs: readEnv(envContent, 'JOB_PROVIDER', 'memory'),
70
+ notifications: readEnv(envContent, 'NOTIFICATION_TRANSPORT', 'poll'),
71
+ embedding: readEnv(envContent, 'EMBEDDING_PROVIDER', 'openai'),
72
+ vectorStore: readEnv(envContent, 'VECTOR_STORE_PROVIDER', 'sqlite'),
73
+ };
74
+ }
75
+ /**
76
+ * Compute the effective set of feature toggles from .env content.
77
+ * Mirrors `env.features` in `codapult/src/lib/config.ts`:
78
+ * - default `true` for every ENABLE_* (unset → enabled);
79
+ * - explicit "false" disables;
80
+ * - `auth` derived from AUTH_PROVIDER !== 'none';
81
+ * - auth-gated features forced off when AUTH_PROVIDER=none.
82
+ */
83
+ export function getFeatures(envContent) {
84
+ const authProvider = readEnv(envContent, 'AUTH_PROVIDER', 'better-auth');
85
+ const authEnabled = authProvider !== 'none';
86
+ const features = { auth: authEnabled };
87
+ for (const [key, envVar] of Object.entries(FEATURE_ENV)) {
88
+ const raw = readEnvVar(envContent, envVar);
89
+ const enabled = raw !== 'false';
90
+ features[key] = enabled && (!AUTH_GATED_FEATURES.has(key) || authEnabled);
91
+ }
92
+ return features;
93
+ }
94
+ export function getAuthMethods(envContent) {
95
+ const authEnabled = readEnv(envContent, 'AUTH_PROVIDER', 'better-auth') !== 'none';
96
+ return {
97
+ twoFactor: authEnabled && readEnvVar(envContent, 'ENABLE_TWO_FACTOR') !== 'false',
98
+ magicLink: (readEnvVar(envContent, 'AUTH_MAGIC_LINK') ?? 'true') === 'true',
99
+ passkeys: (readEnvVar(envContent, 'AUTH_PASSKEYS') ?? 'true') === 'true',
100
+ };
101
+ }
102
+ /** OAuth providers that have both client id + secret configured in .env. */
103
+ export function getOauthProviders(envContent) {
104
+ return Object.entries(OAUTH_CREDENTIAL_KEYS)
105
+ .filter(([, [id, secret]]) => !!readEnvVar(envContent, id) && !!readEnvVar(envContent, secret))
106
+ .map(([provider]) => provider);
107
+ }
108
+ export function findProviderIssues(envContent) {
109
+ const issues = [];
110
+ const adapters = getAdapters(envContent);
111
+ const has = (k) => readEnvVar(envContent, k) !== undefined;
112
+ if (adapters.database === 'turso') {
113
+ if (!has('TURSO_DATABASE_URL')) {
114
+ issues.push({
115
+ key: 'TURSO_DATABASE_URL',
116
+ message: 'Required when DB_PROVIDER="turso"',
117
+ severity: 'error',
118
+ });
119
+ }
120
+ if (!has('TURSO_AUTH_TOKEN')) {
121
+ issues.push({
122
+ key: 'TURSO_AUTH_TOKEN',
123
+ message: 'Required when DB_PROVIDER="turso"',
124
+ severity: 'warn',
125
+ });
126
+ }
127
+ }
128
+ if (adapters.database === 'postgres' && !has('DATABASE_URL')) {
129
+ issues.push({
130
+ key: 'DATABASE_URL',
131
+ message: 'Required when DB_PROVIDER="postgres"',
132
+ severity: 'error',
133
+ });
134
+ }
135
+ if (adapters.auth === 'better-auth') {
136
+ const secret = readEnvVar(envContent, 'BETTER_AUTH_SECRET');
137
+ if (!secret) {
138
+ issues.push({
139
+ key: 'BETTER_AUTH_SECRET',
140
+ message: 'Required when AUTH_PROVIDER="better-auth" (openssl rand -base64 32)',
141
+ severity: 'error',
142
+ });
143
+ }
144
+ else if (secret.length < 32) {
145
+ issues.push({
146
+ key: 'BETTER_AUTH_SECRET',
147
+ message: 'Must be at least 32 characters',
148
+ severity: 'error',
149
+ });
150
+ }
151
+ }
152
+ if (adapters.auth === 'kinde') {
153
+ for (const k of ['KINDE_CLIENT_ID', 'KINDE_CLIENT_SECRET', 'KINDE_ISSUER_URL']) {
154
+ if (!has(k)) {
155
+ issues.push({ key: k, message: 'Required when AUTH_PROVIDER="kinde"', severity: 'error' });
156
+ }
157
+ }
158
+ }
159
+ if (adapters.payments === 'stripe' && !has('STRIPE_SECRET_KEY')) {
160
+ issues.push({
161
+ key: 'STRIPE_SECRET_KEY',
162
+ message: 'Required when PAYMENT_PROVIDER="stripe"',
163
+ severity: 'error',
164
+ });
165
+ }
166
+ if (adapters.payments === 'lemonsqueezy') {
167
+ if (!has('LEMONSQUEEZY_API_KEY')) {
168
+ issues.push({
169
+ key: 'LEMONSQUEEZY_API_KEY',
170
+ message: 'Required when PAYMENT_PROVIDER="lemonsqueezy"',
171
+ severity: 'error',
172
+ });
173
+ }
174
+ if (!has('LEMONSQUEEZY_STORE_ID')) {
175
+ issues.push({
176
+ key: 'LEMONSQUEEZY_STORE_ID',
177
+ message: 'Required when PAYMENT_PROVIDER="lemonsqueezy"',
178
+ severity: 'error',
179
+ });
180
+ }
181
+ }
182
+ if (adapters.payments === 'polar' && !has('POLAR_ACCESS_TOKEN')) {
183
+ issues.push({
184
+ key: 'POLAR_ACCESS_TOKEN',
185
+ message: 'Required when PAYMENT_PROVIDER="polar"',
186
+ severity: 'error',
187
+ });
188
+ }
189
+ if (adapters.storage === 's3' || adapters.storage === 'r2') {
190
+ const label = `Required when STORAGE_PROVIDER="${adapters.storage}"`;
191
+ for (const k of ['S3_BUCKET', 'S3_ACCESS_KEY_ID', 'S3_SECRET_ACCESS_KEY']) {
192
+ if (!has(k))
193
+ issues.push({ key: k, message: label, severity: 'error' });
194
+ }
195
+ }
196
+ if (adapters.jobs === 'bullmq' && !has('REDIS_URL')) {
197
+ issues.push({
198
+ key: 'REDIS_URL',
199
+ message: 'Required when JOB_PROVIDER="bullmq"',
200
+ severity: 'error',
201
+ });
202
+ }
203
+ if (adapters.notifications === 'ws' && !has('NEXT_PUBLIC_WS_URL')) {
204
+ issues.push({
205
+ key: 'NEXT_PUBLIC_WS_URL',
206
+ message: 'Required when NOTIFICATION_TRANSPORT="ws"',
207
+ severity: 'error',
208
+ });
209
+ }
210
+ return issues;
211
+ }
@@ -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
  // ---------------------------------------------------------------------------