@prenta/cli 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +4 -0
- package/.turbo/turbo-test.log +353 -0
- package/CHANGELOG.md +404 -0
- package/LICENSE +21 -0
- package/README.md +30 -0
- package/dist/__tests__/db-init.test.d.ts +2 -0
- package/dist/__tests__/db-init.test.d.ts.map +1 -0
- package/dist/__tests__/db-init.test.js +127 -0
- package/dist/__tests__/db-init.test.js.map +1 -0
- package/dist/__tests__/db-sync-resolver.test.d.ts +2 -0
- package/dist/__tests__/db-sync-resolver.test.d.ts.map +1 -0
- package/dist/__tests__/db-sync-resolver.test.js +25 -0
- package/dist/__tests__/db-sync-resolver.test.js.map +1 -0
- package/dist/__tests__/db-sync.test.d.ts +2 -0
- package/dist/__tests__/db-sync.test.d.ts.map +1 -0
- package/dist/__tests__/db-sync.test.js +167 -0
- package/dist/__tests__/db-sync.test.js.map +1 -0
- package/dist/__tests__/deployment-diagnostics.test.d.ts +2 -0
- package/dist/__tests__/deployment-diagnostics.test.d.ts.map +1 -0
- package/dist/__tests__/deployment-diagnostics.test.js +401 -0
- package/dist/__tests__/deployment-diagnostics.test.js.map +1 -0
- package/dist/__tests__/form-seed.test.d.ts +2 -0
- package/dist/__tests__/form-seed.test.d.ts.map +1 -0
- package/dist/__tests__/form-seed.test.js +79 -0
- package/dist/__tests__/form-seed.test.js.map +1 -0
- package/dist/__tests__/init.test.d.ts +2 -0
- package/dist/__tests__/init.test.d.ts.map +1 -0
- package/dist/__tests__/init.test.js +25 -0
- package/dist/__tests__/init.test.js.map +1 -0
- package/dist/__tests__/load-dotenv.test.d.ts +2 -0
- package/dist/__tests__/load-dotenv.test.d.ts.map +1 -0
- package/dist/__tests__/load-dotenv.test.js +40 -0
- package/dist/__tests__/load-dotenv.test.js.map +1 -0
- package/dist/__tests__/mcp-init.test.d.ts +2 -0
- package/dist/__tests__/mcp-init.test.d.ts.map +1 -0
- package/dist/__tests__/mcp-init.test.js +100 -0
- package/dist/__tests__/mcp-init.test.js.map +1 -0
- package/dist/__tests__/prisma-client-path.test.d.ts +2 -0
- package/dist/__tests__/prisma-client-path.test.d.ts.map +1 -0
- package/dist/__tests__/prisma-client-path.test.js +66 -0
- package/dist/__tests__/prisma-client-path.test.js.map +1 -0
- package/dist/__tests__/schema-fragment.test.d.ts +2 -0
- package/dist/__tests__/schema-fragment.test.d.ts.map +1 -0
- package/dist/__tests__/schema-fragment.test.js +40 -0
- package/dist/__tests__/schema-fragment.test.js.map +1 -0
- package/dist/__tests__/seed.test.d.ts +2 -0
- package/dist/__tests__/seed.test.d.ts.map +1 -0
- package/dist/__tests__/seed.test.js +207 -0
- package/dist/__tests__/seed.test.js.map +1 -0
- package/dist/__tests__/upgrade.test.d.ts +2 -0
- package/dist/__tests__/upgrade.test.d.ts.map +1 -0
- package/dist/__tests__/upgrade.test.js +41 -0
- package/dist/__tests__/upgrade.test.js.map +1 -0
- package/dist/__tests__/vercel-env-matrix.test.d.ts +2 -0
- package/dist/__tests__/vercel-env-matrix.test.d.ts.map +1 -0
- package/dist/__tests__/vercel-env-matrix.test.js +56 -0
- package/dist/__tests__/vercel-env-matrix.test.js.map +1 -0
- package/dist/commands/db-init.d.ts +24 -0
- package/dist/commands/db-init.d.ts.map +1 -0
- package/dist/commands/db-init.js +195 -0
- package/dist/commands/db-init.js.map +1 -0
- package/dist/commands/db-status.d.ts +3 -0
- package/dist/commands/db-status.d.ts.map +1 -0
- package/dist/commands/db-status.js +108 -0
- package/dist/commands/db-status.js.map +1 -0
- package/dist/commands/db-sync.d.ts +66 -0
- package/dist/commands/db-sync.d.ts.map +1 -0
- package/dist/commands/db-sync.js +310 -0
- package/dist/commands/db-sync.js.map +1 -0
- package/dist/commands/doctor.d.ts +5 -0
- package/dist/commands/doctor.d.ts.map +1 -0
- package/dist/commands/doctor.js +282 -0
- package/dist/commands/doctor.js.map +1 -0
- package/dist/commands/export.d.ts +3 -0
- package/dist/commands/export.d.ts.map +1 -0
- package/dist/commands/export.js +99 -0
- package/dist/commands/export.js.map +1 -0
- package/dist/commands/generate.d.ts +3 -0
- package/dist/commands/generate.d.ts.map +1 -0
- package/dist/commands/generate.js +24 -0
- package/dist/commands/generate.js.map +1 -0
- package/dist/commands/import.d.ts +3 -0
- package/dist/commands/import.d.ts.map +1 -0
- package/dist/commands/import.js +201 -0
- package/dist/commands/import.js.map +1 -0
- package/dist/commands/init.d.ts +4 -0
- package/dist/commands/init.d.ts.map +1 -0
- package/dist/commands/init.js +31 -0
- package/dist/commands/init.js.map +1 -0
- package/dist/commands/mcp.d.ts +3 -0
- package/dist/commands/mcp.d.ts.map +1 -0
- package/dist/commands/mcp.js +126 -0
- package/dist/commands/mcp.js.map +1 -0
- package/dist/commands/migrate-media-usage.d.ts +3 -0
- package/dist/commands/migrate-media-usage.d.ts.map +1 -0
- package/dist/commands/migrate-media-usage.js +52 -0
- package/dist/commands/migrate-media-usage.js.map +1 -0
- package/dist/commands/migrate-meta.d.ts +3 -0
- package/dist/commands/migrate-meta.d.ts.map +1 -0
- package/dist/commands/migrate-meta.js +81 -0
- package/dist/commands/migrate-meta.js.map +1 -0
- package/dist/commands/migrate-schema.d.ts +3 -0
- package/dist/commands/migrate-schema.d.ts.map +1 -0
- package/dist/commands/migrate-schema.js +84 -0
- package/dist/commands/migrate-schema.js.map +1 -0
- package/dist/commands/migrate-sections.d.ts +3 -0
- package/dist/commands/migrate-sections.d.ts.map +1 -0
- package/dist/commands/migrate-sections.js +56 -0
- package/dist/commands/migrate-sections.js.map +1 -0
- package/dist/commands/migrate.d.ts +3 -0
- package/dist/commands/migrate.d.ts.map +1 -0
- package/dist/commands/migrate.js +51 -0
- package/dist/commands/migrate.js.map +1 -0
- package/dist/commands/seed.d.ts +60 -0
- package/dist/commands/seed.d.ts.map +1 -0
- package/dist/commands/seed.js +585 -0
- package/dist/commands/seed.js.map +1 -0
- package/dist/commands/update-check.d.ts +3 -0
- package/dist/commands/update-check.d.ts.map +1 -0
- package/dist/commands/update-check.js +132 -0
- package/dist/commands/update-check.js.map +1 -0
- package/dist/commands/upgrade.d.ts +4 -0
- package/dist/commands/upgrade.d.ts.map +1 -0
- package/dist/commands/upgrade.js +175 -0
- package/dist/commands/upgrade.js.map +1 -0
- package/dist/commands/vercel-blob-link.d.ts +3 -0
- package/dist/commands/vercel-blob-link.d.ts.map +1 -0
- package/dist/commands/vercel-blob-link.js +83 -0
- package/dist/commands/vercel-blob-link.js.map +1 -0
- package/dist/deployment/diagnostics.d.ts +136 -0
- package/dist/deployment/diagnostics.d.ts.map +1 -0
- package/dist/deployment/diagnostics.js +575 -0
- package/dist/deployment/diagnostics.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +47 -0
- package/dist/index.js.map +1 -0
- package/dist/utils/database.d.ts +21 -0
- package/dist/utils/database.d.ts.map +1 -0
- package/dist/utils/database.js +98 -0
- package/dist/utils/database.js.map +1 -0
- package/dist/utils/form-seed.d.ts +15 -0
- package/dist/utils/form-seed.d.ts.map +1 -0
- package/dist/utils/form-seed.js +97 -0
- package/dist/utils/form-seed.js.map +1 -0
- package/dist/utils/load-dotenv.d.ts +11 -0
- package/dist/utils/load-dotenv.d.ts.map +1 -0
- package/dist/utils/load-dotenv.js +47 -0
- package/dist/utils/load-dotenv.js.map +1 -0
- package/dist/utils/logger.d.ts +8 -0
- package/dist/utils/logger.d.ts.map +1 -0
- package/dist/utils/logger.js +16 -0
- package/dist/utils/logger.js.map +1 -0
- package/dist/utils/prisma-client-path.d.ts +20 -0
- package/dist/utils/prisma-client-path.d.ts.map +1 -0
- package/dist/utils/prisma-client-path.js +77 -0
- package/dist/utils/prisma-client-path.js.map +1 -0
- package/dist/vercel/client.d.ts +32 -0
- package/dist/vercel/client.d.ts.map +1 -0
- package/dist/vercel/client.js +74 -0
- package/dist/vercel/client.js.map +1 -0
- package/dist/vercel/env-matrix.d.ts +35 -0
- package/dist/vercel/env-matrix.d.ts.map +1 -0
- package/dist/vercel/env-matrix.js +66 -0
- package/dist/vercel/env-matrix.js.map +1 -0
- package/package.json +41 -0
- package/src/__tests__/db-init.test.ts +155 -0
- package/src/__tests__/db-sync-resolver.test.ts +29 -0
- package/src/__tests__/db-sync.test.ts +221 -0
- package/src/__tests__/deployment-diagnostics.test.ts +474 -0
- package/src/__tests__/form-seed.test.ts +91 -0
- package/src/__tests__/init.test.ts +30 -0
- package/src/__tests__/load-dotenv.test.ts +53 -0
- package/src/__tests__/mcp-init.test.ts +125 -0
- package/src/__tests__/prisma-client-path.test.ts +87 -0
- package/src/__tests__/schema-fragment.test.ts +51 -0
- package/src/__tests__/seed.test.ts +249 -0
- package/src/__tests__/upgrade.test.ts +44 -0
- package/src/__tests__/vercel-env-matrix.test.ts +65 -0
- package/src/commands/db-init.ts +211 -0
- package/src/commands/db-status.ts +122 -0
- package/src/commands/db-sync.ts +367 -0
- package/src/commands/doctor.ts +354 -0
- package/src/commands/export.ts +118 -0
- package/src/commands/generate.ts +26 -0
- package/src/commands/import.ts +228 -0
- package/src/commands/init.ts +36 -0
- package/src/commands/mcp.ts +181 -0
- package/src/commands/migrate-media-usage.ts +68 -0
- package/src/commands/migrate-meta.ts +107 -0
- package/src/commands/migrate-schema.ts +110 -0
- package/src/commands/migrate-sections.ts +73 -0
- package/src/commands/migrate.ts +56 -0
- package/src/commands/seed.ts +693 -0
- package/src/commands/update-check.ts +152 -0
- package/src/commands/upgrade.ts +202 -0
- package/src/commands/vercel-blob-link.ts +116 -0
- package/src/deployment/diagnostics.ts +735 -0
- package/src/index.ts +54 -0
- package/src/utils/database.ts +126 -0
- package/src/utils/form-seed.ts +137 -0
- package/src/utils/load-dotenv.ts +52 -0
- package/src/utils/logger.ts +26 -0
- package/src/utils/prisma-client-path.ts +81 -0
- package/src/vercel/client.ts +112 -0
- package/src/vercel/env-matrix.ts +112 -0
- package/tsconfig.json +9 -0
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import { Command } from 'commander'
|
|
2
|
+
import { readFile, writeFile, access } from 'node:fs/promises'
|
|
3
|
+
import { resolve, join, dirname } from 'node:path'
|
|
4
|
+
import { createRequire } from 'node:module'
|
|
5
|
+
import { execSync, type ExecSyncOptions } from 'node:child_process'
|
|
6
|
+
import ora from 'ora'
|
|
7
|
+
import { logger } from '../utils/logger.js'
|
|
8
|
+
|
|
9
|
+
const CMS_SCHEMA_MARKER = '// ── Prenta CMS models'
|
|
10
|
+
|
|
11
|
+
const require = createRequire(import.meta.url)
|
|
12
|
+
|
|
13
|
+
export let runDbInitCommand = (command: string, options: ExecSyncOptions): void => {
|
|
14
|
+
execSync(command, options)
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const defaultDbInitCommandRunner = runDbInitCommand
|
|
18
|
+
|
|
19
|
+
export function setDbInitCommandRunner(runner: typeof runDbInitCommand): void {
|
|
20
|
+
runDbInitCommand = runner
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function resetDbInitCommandRunner(): void {
|
|
24
|
+
runDbInitCommand = defaultDbInitCommandRunner
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Reads the canonical Prisma schema shipped by the installed
|
|
29
|
+
* `@prenta/core` package. This is the single source of truth — it has
|
|
30
|
+
* the correct `@@map("prenta_*")` table names and every model the API handlers
|
|
31
|
+
* expect. Previously `db:init` injected a hand-maintained copy that drifted
|
|
32
|
+
* (missing `@@map`, missing models), producing a database the runtime couldn't
|
|
33
|
+
* query. Overridable for tests.
|
|
34
|
+
*/
|
|
35
|
+
export let readCanonicalCmsSchema = async (): Promise<string | null> => {
|
|
36
|
+
const candidates: string[] = []
|
|
37
|
+
try {
|
|
38
|
+
// `./prisma/schema` is an exported subpath, so this resolves inside the
|
|
39
|
+
// package's `prisma/` directory without depending on the build output.
|
|
40
|
+
const exported = require.resolve('@prenta/core/prisma/schema')
|
|
41
|
+
candidates.push(join(dirname(exported), 'schema.prisma'))
|
|
42
|
+
} catch {
|
|
43
|
+
/* exports map missing the subpath — fall through to the main entry */
|
|
44
|
+
}
|
|
45
|
+
try {
|
|
46
|
+
const mainEntry = require.resolve('@prenta/core')
|
|
47
|
+
candidates.push(join(dirname(mainEntry), '..', 'prisma', 'schema.prisma'))
|
|
48
|
+
} catch {
|
|
49
|
+
/* package not installed */
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
for (const candidate of candidates) {
|
|
53
|
+
try {
|
|
54
|
+
return await readFile(candidate, 'utf-8')
|
|
55
|
+
} catch {
|
|
56
|
+
/* try the next candidate */
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return null
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const defaultSchemaReader = readCanonicalCmsSchema
|
|
63
|
+
|
|
64
|
+
export function setCanonicalSchemaReader(reader: typeof readCanonicalCmsSchema): void {
|
|
65
|
+
readCanonicalCmsSchema = reader
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function resetCanonicalSchemaReader(): void {
|
|
69
|
+
readCanonicalCmsSchema = defaultSchemaReader
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function netBraces(line: string): number {
|
|
73
|
+
return (line.match(/\{/g)?.length ?? 0) - (line.match(/\}/g)?.length ?? 0)
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Strips the top-level `generator` and `datasource` blocks from a full Prisma
|
|
78
|
+
* schema, leaving only the `enum` and `model` definitions. The consumer keeps
|
|
79
|
+
* their own datasource/generator; we only contribute models.
|
|
80
|
+
*/
|
|
81
|
+
export function extractModelsFragment(fullSchema: string): string {
|
|
82
|
+
const lines = fullSchema.split(/\r?\n/)
|
|
83
|
+
const kept: string[] = []
|
|
84
|
+
let skipping = false
|
|
85
|
+
let depth = 0
|
|
86
|
+
|
|
87
|
+
for (const line of lines) {
|
|
88
|
+
if (!skipping) {
|
|
89
|
+
if (/^\s*(generator|datasource)\s+[A-Za-z0-9_]+\s*\{/.test(line)) {
|
|
90
|
+
skipping = true
|
|
91
|
+
depth = netBraces(line)
|
|
92
|
+
if (depth <= 0) skipping = false
|
|
93
|
+
continue
|
|
94
|
+
}
|
|
95
|
+
kept.push(line)
|
|
96
|
+
} else {
|
|
97
|
+
depth += netBraces(line)
|
|
98
|
+
if (depth <= 0) skipping = false
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return kept.join('\n').trim()
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function wrapFragment(models: string): string {
|
|
106
|
+
return `
|
|
107
|
+
${CMS_SCHEMA_MARKER} ─────────────────────────────────────────────────────────
|
|
108
|
+
// Auto-injected by \`prenta db:init\` from the installed @prenta/core
|
|
109
|
+
// package's canonical prisma/schema.prisma (the single source of truth). Do not
|
|
110
|
+
// edit by hand — re-run \`prenta db:init --force\` after upgrading cms-core.
|
|
111
|
+
|
|
112
|
+
${models}
|
|
113
|
+
`
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async function fileExists(filePath: string): Promise<boolean> {
|
|
117
|
+
try {
|
|
118
|
+
await access(filePath)
|
|
119
|
+
return true
|
|
120
|
+
} catch {
|
|
121
|
+
return false
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function registerDbInitCommand(program: Command): void {
|
|
126
|
+
program
|
|
127
|
+
.command('db:init')
|
|
128
|
+
.description('Add Prenta CMS models (from the installed cms-core) to your Prisma schema')
|
|
129
|
+
.option('--schema <path>', 'Path to schema.prisma', 'prisma/schema.prisma')
|
|
130
|
+
.option('--migrate', 'Run prisma migrate dev after adding models')
|
|
131
|
+
.option('--force', 'Overwrite existing CMS models if present')
|
|
132
|
+
.action(async (opts: { schema: string; migrate?: boolean; force?: boolean }) => {
|
|
133
|
+
const schemaPath = resolve(process.cwd(), opts.schema)
|
|
134
|
+
|
|
135
|
+
if (!(await fileExists(schemaPath))) {
|
|
136
|
+
logger.error(`Schema file not found at ${schemaPath}`)
|
|
137
|
+
logger.info('Run `npx prisma init` first, or specify --schema <path>.')
|
|
138
|
+
process.exitCode = 1
|
|
139
|
+
return
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const spinner = ora('Reading canonical Prenta schema...').start()
|
|
143
|
+
|
|
144
|
+
const canonical = await readCanonicalCmsSchema()
|
|
145
|
+
if (!canonical) {
|
|
146
|
+
spinner.fail('Could not locate @prenta/core.')
|
|
147
|
+
logger.info('Install it first: `npm install @prenta/core`.')
|
|
148
|
+
process.exitCode = 1
|
|
149
|
+
return
|
|
150
|
+
}
|
|
151
|
+
const fragment = wrapFragment(extractModelsFragment(canonical))
|
|
152
|
+
|
|
153
|
+
spinner.text = 'Reading Prisma schema...'
|
|
154
|
+
let content: string
|
|
155
|
+
try {
|
|
156
|
+
content = await readFile(schemaPath, 'utf-8')
|
|
157
|
+
} catch (err) {
|
|
158
|
+
spinner.fail('Failed to read schema file.')
|
|
159
|
+
logger.error(err instanceof Error ? err.message : String(err))
|
|
160
|
+
process.exitCode = 1
|
|
161
|
+
return
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
if (content.includes(CMS_SCHEMA_MARKER)) {
|
|
165
|
+
if (!opts.force) {
|
|
166
|
+
spinner.info('Prenta CMS models already present in schema. Use --force to overwrite.')
|
|
167
|
+
return
|
|
168
|
+
}
|
|
169
|
+
spinner.text = 'Removing existing CMS models...'
|
|
170
|
+
const markerIndex = content.indexOf(CMS_SCHEMA_MARKER)
|
|
171
|
+
content = content.substring(0, markerIndex).trimEnd() + '\n'
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
spinner.text = 'Adding Prenta CMS models...'
|
|
175
|
+
const updatedContent = content.trimEnd() + '\n' + fragment
|
|
176
|
+
|
|
177
|
+
try {
|
|
178
|
+
await writeFile(schemaPath, updatedContent)
|
|
179
|
+
spinner.succeed('Prenta CMS models added to schema.')
|
|
180
|
+
} catch (err) {
|
|
181
|
+
spinner.fail('Failed to write schema file.')
|
|
182
|
+
logger.error(err instanceof Error ? err.message : String(err))
|
|
183
|
+
process.exitCode = 1
|
|
184
|
+
return
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const execOpts: ExecSyncOptions = { stdio: 'inherit', cwd: process.cwd() }
|
|
188
|
+
|
|
189
|
+
const genSpinner = ora('Running prisma generate...').start()
|
|
190
|
+
try {
|
|
191
|
+
genSpinner.stop()
|
|
192
|
+
runDbInitCommand('npx prisma generate', execOpts)
|
|
193
|
+
logger.success('Prisma client generated.')
|
|
194
|
+
} catch {
|
|
195
|
+
logger.warn('prisma generate failed. You may need to set DATABASE_URL first.')
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
if (opts.migrate) {
|
|
199
|
+
const migSpinner = ora('Running prisma migrate dev...').start()
|
|
200
|
+
try {
|
|
201
|
+
migSpinner.stop()
|
|
202
|
+
runDbInitCommand('npx prisma migrate dev --name prenta-cms-init', execOpts)
|
|
203
|
+
logger.success('Migration created and applied.')
|
|
204
|
+
} catch {
|
|
205
|
+
logger.warn('prisma migrate dev failed. Run it manually after setting DATABASE_URL.')
|
|
206
|
+
}
|
|
207
|
+
} else {
|
|
208
|
+
logger.info('Run `npx prisma migrate dev --name prenta-cms` to create the migration.')
|
|
209
|
+
}
|
|
210
|
+
})
|
|
211
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { Command } from 'commander'
|
|
2
|
+
import { execSync } from 'node:child_process'
|
|
3
|
+
import { readFile, access } from 'node:fs/promises'
|
|
4
|
+
import { resolve } from 'node:path'
|
|
5
|
+
import ora from 'ora'
|
|
6
|
+
import chalk from 'chalk'
|
|
7
|
+
import { logger } from '../utils/logger.js'
|
|
8
|
+
import { REQUIRED_CMS_MODELS } from '../deployment/diagnostics.js'
|
|
9
|
+
|
|
10
|
+
const CMS_SCHEMA_MARKER = '// ── Prenta CMS models'
|
|
11
|
+
|
|
12
|
+
async function fileExists(filePath: string): Promise<boolean> {
|
|
13
|
+
try {
|
|
14
|
+
await access(filePath)
|
|
15
|
+
return true
|
|
16
|
+
} catch {
|
|
17
|
+
return false
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function registerDbStatusCommand(program: Command): void {
|
|
22
|
+
program
|
|
23
|
+
.command('db:status')
|
|
24
|
+
.description('Check which Prenta CMS models are present in your Prisma schema')
|
|
25
|
+
.option('--schema <path>', 'Path to schema.prisma', 'prisma/schema.prisma')
|
|
26
|
+
.action(async (opts: { schema: string }) => {
|
|
27
|
+
const schemaPath = resolve(process.cwd(), opts.schema)
|
|
28
|
+
|
|
29
|
+
if (!(await fileExists(schemaPath))) {
|
|
30
|
+
logger.error(`Schema file not found at ${schemaPath}`)
|
|
31
|
+
logger.info('Run `npx prisma init` first, or specify --schema <path>.')
|
|
32
|
+
process.exitCode = 1
|
|
33
|
+
return
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const spinner = ora('Checking schema...').start()
|
|
37
|
+
|
|
38
|
+
let content: string
|
|
39
|
+
try {
|
|
40
|
+
content = await readFile(schemaPath, 'utf-8')
|
|
41
|
+
} catch (err) {
|
|
42
|
+
spinner.fail('Failed to read schema file.')
|
|
43
|
+
logger.error(err instanceof Error ? err.message : String(err))
|
|
44
|
+
process.exitCode = 1
|
|
45
|
+
return
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
spinner.stop()
|
|
49
|
+
|
|
50
|
+
const hasMarker = content.includes(CMS_SCHEMA_MARKER)
|
|
51
|
+
const modelRegex = /^model\s+(\w+)\s*\{/gm
|
|
52
|
+
const schemaModels = new Set<string>()
|
|
53
|
+
let match
|
|
54
|
+
while ((match = modelRegex.exec(content)) !== null) {
|
|
55
|
+
schemaModels.add(match[1]!)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
console.log()
|
|
59
|
+
console.log(chalk.bold(' Prenta CMS Model Status'))
|
|
60
|
+
console.log(chalk.dim(' ─────────────────────────────────'))
|
|
61
|
+
console.log()
|
|
62
|
+
|
|
63
|
+
let present = 0
|
|
64
|
+
let missing = 0
|
|
65
|
+
|
|
66
|
+
for (const model of REQUIRED_CMS_MODELS) {
|
|
67
|
+
if (schemaModels.has(model)) {
|
|
68
|
+
console.log(` ${chalk.green('✓')} ${model}`)
|
|
69
|
+
present++
|
|
70
|
+
} else {
|
|
71
|
+
console.log(` ${chalk.red('✗')} ${model} ${chalk.dim('— missing')}`)
|
|
72
|
+
missing++
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
console.log()
|
|
77
|
+
console.log(chalk.dim(' ─────────────────────────────────'))
|
|
78
|
+
console.log(
|
|
79
|
+
` ${chalk.green(present)} present, ${missing > 0 ? chalk.red(missing) : chalk.green(missing)} missing`,
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
if (!hasMarker) {
|
|
83
|
+
console.log()
|
|
84
|
+
logger.warn('CMS schema marker not found. Models may have been added manually.')
|
|
85
|
+
logger.info('Run `prenta db:init` to add CMS models with proper markers.')
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
if (missing > 0) {
|
|
89
|
+
console.log()
|
|
90
|
+
logger.info('Run `prenta db:init` to add missing models.')
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
let dbConnected = false
|
|
94
|
+
try {
|
|
95
|
+
spinner.start('Checking database connection...')
|
|
96
|
+
execSync('npx prisma db execute --stdin --schema ' + JSON.stringify(schemaPath), {
|
|
97
|
+
input: 'SELECT 1;',
|
|
98
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
99
|
+
cwd: process.cwd(),
|
|
100
|
+
})
|
|
101
|
+
spinner.succeed('Database connection OK.')
|
|
102
|
+
dbConnected = true
|
|
103
|
+
} catch {
|
|
104
|
+
spinner.warn('Could not connect to database. Check DATABASE_URL.')
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
if (dbConnected && missing === 0) {
|
|
108
|
+
try {
|
|
109
|
+
spinner.start('Checking migration status...')
|
|
110
|
+
spinner.stop()
|
|
111
|
+
execSync('npx prisma migrate status', {
|
|
112
|
+
stdio: 'inherit',
|
|
113
|
+
cwd: process.cwd(),
|
|
114
|
+
})
|
|
115
|
+
} catch {
|
|
116
|
+
logger.warn('Could not check migration status.')
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
console.log()
|
|
121
|
+
})
|
|
122
|
+
}
|
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
import { Command } from 'commander'
|
|
2
|
+
import { access, cp, mkdir, readFile, readdir, writeFile } from 'node:fs/promises'
|
|
3
|
+
import { existsSync } from 'node:fs'
|
|
4
|
+
import { spawn } from 'node:child_process'
|
|
5
|
+
import { dirname, join, resolve } from 'node:path'
|
|
6
|
+
import { createRequire } from 'node:module'
|
|
7
|
+
import ora from 'ora'
|
|
8
|
+
import { logger } from '../utils/logger.js'
|
|
9
|
+
|
|
10
|
+
const require = createRequire(import.meta.url)
|
|
11
|
+
|
|
12
|
+
// Marker that identifies a schema this CLI/scaffolder owns (auto-synced from
|
|
13
|
+
// cms-core). We refuse to overwrite a schema lacking it unless --force, so a
|
|
14
|
+
// hand-customized schema is never silently clobbered.
|
|
15
|
+
const AUTO_SYNCED_MARKER = 'AUTO-SYNCED from @prenta/core'
|
|
16
|
+
|
|
17
|
+
// Must match create-prenta/scripts/sync-prisma-assets.ts `SCAFFOLD_SCHEMA_HEADER`
|
|
18
|
+
// so re-syncing a scaffolded project is idempotent (no spurious diffs).
|
|
19
|
+
const SCHEMA_HEADER = `// ─────────────────────────────────────────────────────────────────────────────
|
|
20
|
+
// Prenta CMS — Prisma schema
|
|
21
|
+
//
|
|
22
|
+
// AUTO-SYNCED from @prenta/core. Do NOT edit the model definitions
|
|
23
|
+
// by hand — they must match the bundled migrations and cms-core's API layer.
|
|
24
|
+
// (Generated by \`prenta db:sync\`)
|
|
25
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
26
|
+
|
|
27
|
+
generator client {
|
|
28
|
+
provider = "prisma-client"
|
|
29
|
+
output = "../generated/prisma"
|
|
30
|
+
previewFeatures = ["fullTextSearchPostgres", "relationJoins"]
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
datasource db {
|
|
34
|
+
provider = "postgresql"
|
|
35
|
+
}`
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Build the consumer's `schema.prisma` from cms-core's canonical schema: strip
|
|
39
|
+
* cms-core's own generator/datasource blocks and prepend the consumer header
|
|
40
|
+
* (client output `../generated/prisma`, no datasource `url` — supplied by
|
|
41
|
+
* `prisma.config.ts`). Pure for testing. Mirrors the scaffolder's builder.
|
|
42
|
+
*/
|
|
43
|
+
export function buildConsumerSchema(coreSchemaSource: string): string {
|
|
44
|
+
const datasourceMatch = coreSchemaSource.match(/datasource\s+\w+\s*\{[\s\S]*?\}/)
|
|
45
|
+
if (!datasourceMatch || datasourceMatch.index === undefined) {
|
|
46
|
+
throw new Error('Could not locate the `datasource` block in cms-core schema.prisma')
|
|
47
|
+
}
|
|
48
|
+
const body = coreSchemaSource
|
|
49
|
+
.slice(datasourceMatch.index + datasourceMatch[0].length)
|
|
50
|
+
.replace(/^\s+/, '')
|
|
51
|
+
|
|
52
|
+
if (!/@@map\("prenta_users"\)/.test(body)) {
|
|
53
|
+
throw new Error('cms-core schema body is missing `@@map("prenta_users")` — aborting sync')
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
return `${SCHEMA_HEADER}\n\n${body.trimEnd()}\n`
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Return the first candidate directory that actually contains a canonical
|
|
61
|
+
* `schema.prisma`. Pure + injectable so it can be unit-tested without the
|
|
62
|
+
* installed package.
|
|
63
|
+
*/
|
|
64
|
+
export function pickPrismaDir(
|
|
65
|
+
candidates: string[],
|
|
66
|
+
hasSchema: (dir: string) => boolean = (dir) => existsSync(join(dir, 'schema.prisma')),
|
|
67
|
+
): string | null {
|
|
68
|
+
for (const dir of candidates) {
|
|
69
|
+
if (dir && hasSchema(dir)) return dir
|
|
70
|
+
}
|
|
71
|
+
return null
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Resolve the installed `@prenta/core` package's `prisma/` directory
|
|
76
|
+
* (the source of truth for schema + migrations). Overridable for tests.
|
|
77
|
+
*
|
|
78
|
+
* Note: the `./prisma/schema` export can point at a schema *fragment*
|
|
79
|
+
* (`schema-fragments/cms-schema.prisma`, used for IDE validation) which lives in
|
|
80
|
+
* a DIFFERENT directory that has no `schema.prisma`. So we gather candidate dirs
|
|
81
|
+
* and return the first that actually contains `schema.prisma`, rather than
|
|
82
|
+
* trusting the export's directory (which broke `db:sync` — the export resolved,
|
|
83
|
+
* but `schema.prisma` wasn't in `schema-fragments/`).
|
|
84
|
+
*/
|
|
85
|
+
export let resolveCmsCorePrismaDir = (): string | null => {
|
|
86
|
+
const candidates: string[] = []
|
|
87
|
+
try {
|
|
88
|
+
const exported = require.resolve('@prenta/core/prisma/schema')
|
|
89
|
+
candidates.push(dirname(exported))
|
|
90
|
+
} catch {
|
|
91
|
+
/* exports map missing the subpath */
|
|
92
|
+
}
|
|
93
|
+
try {
|
|
94
|
+
const mainEntry = require.resolve('@prenta/core')
|
|
95
|
+
candidates.push(join(dirname(mainEntry), '..', 'prisma'))
|
|
96
|
+
} catch {
|
|
97
|
+
/* package not resolvable */
|
|
98
|
+
}
|
|
99
|
+
return pickPrismaDir(candidates)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const defaultPrismaDirResolver = resolveCmsCorePrismaDir
|
|
103
|
+
|
|
104
|
+
export function setCmsCorePrismaDirResolver(resolver: typeof resolveCmsCorePrismaDir): void {
|
|
105
|
+
resolveCmsCorePrismaDir = resolver
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function resetCmsCorePrismaDirResolver(): void {
|
|
109
|
+
resolveCmsCorePrismaDir = defaultPrismaDirResolver
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async function listMigrationDirs(dir: string): Promise<string[]> {
|
|
113
|
+
try {
|
|
114
|
+
const entries = await readdir(dir, { withFileTypes: true })
|
|
115
|
+
return entries.filter((e) => e.isDirectory()).map((e) => e.name)
|
|
116
|
+
} catch {
|
|
117
|
+
return []
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
interface DbSyncOptions {
|
|
122
|
+
schema: string
|
|
123
|
+
force?: boolean
|
|
124
|
+
checkDrift?: boolean
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export interface DriftDiffResult {
|
|
128
|
+
exitCode: number
|
|
129
|
+
stdout: string
|
|
130
|
+
stderr: string
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export type DriftRunner = (args: { schemaPath: string; url: string }) => Promise<DriftDiffResult>
|
|
134
|
+
|
|
135
|
+
export interface DriftCheckResult {
|
|
136
|
+
status: 'no-drift' | 'drift' | 'skipped' | 'error'
|
|
137
|
+
detail?: string
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const defaultDriftRunner: DriftRunner = ({ schemaPath, url }) =>
|
|
141
|
+
new Promise((resolvePromise) => {
|
|
142
|
+
// `--exit-code` makes prisma return 2 when the database differs from the
|
|
143
|
+
// datamodel, 0 when in sync. `--script` prints the reconciling SQL.
|
|
144
|
+
const child = spawn(
|
|
145
|
+
'npx',
|
|
146
|
+
[
|
|
147
|
+
'prisma',
|
|
148
|
+
'migrate',
|
|
149
|
+
'diff',
|
|
150
|
+
'--from-url',
|
|
151
|
+
url,
|
|
152
|
+
'--to-schema-datamodel',
|
|
153
|
+
schemaPath,
|
|
154
|
+
'--script',
|
|
155
|
+
'--exit-code',
|
|
156
|
+
],
|
|
157
|
+
{ shell: process.platform === 'win32' },
|
|
158
|
+
)
|
|
159
|
+
let stdout = ''
|
|
160
|
+
let stderr = ''
|
|
161
|
+
child.stdout?.on('data', (chunk) => {
|
|
162
|
+
stdout += String(chunk)
|
|
163
|
+
})
|
|
164
|
+
child.stderr?.on('data', (chunk) => {
|
|
165
|
+
stderr += String(chunk)
|
|
166
|
+
})
|
|
167
|
+
child.on('error', (err) => {
|
|
168
|
+
resolvePromise({ exitCode: 1, stdout, stderr: stderr || String(err) })
|
|
169
|
+
})
|
|
170
|
+
child.on('close', (code) => {
|
|
171
|
+
resolvePromise({ exitCode: code ?? 1, stdout, stderr })
|
|
172
|
+
})
|
|
173
|
+
})
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Detect whether the live database differs from the canonical schema. Pure of
|
|
177
|
+
* I/O via the injectable `runner` so the decision logic is unit-testable. A
|
|
178
|
+
* non-pooled `DIRECT_DATABASE_URL` is preferred (migrations use it); falls back
|
|
179
|
+
* to `DATABASE_URL`. Skips gracefully when neither is set.
|
|
180
|
+
*/
|
|
181
|
+
export async function checkSchemaDrift(
|
|
182
|
+
schemaPath: string,
|
|
183
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
184
|
+
runner: DriftRunner = defaultDriftRunner,
|
|
185
|
+
): Promise<DriftCheckResult> {
|
|
186
|
+
const url = env.DIRECT_DATABASE_URL || env.DATABASE_URL
|
|
187
|
+
if (!url) {
|
|
188
|
+
return {
|
|
189
|
+
status: 'skipped',
|
|
190
|
+
detail: 'Set DATABASE_URL (or DIRECT_DATABASE_URL) to let db:sync detect schema drift.',
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
const result = await runner({ schemaPath, url })
|
|
194
|
+
if (result.exitCode === 0) return { status: 'no-drift' }
|
|
195
|
+
if (result.exitCode === 2) return { status: 'drift', detail: result.stdout.trim() }
|
|
196
|
+
return { status: 'error', detail: (result.stderr || result.stdout).trim() }
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Human-readable next steps for a drift verdict (pure, for testing + reuse). */
|
|
200
|
+
export function driftGuidance(result: DriftCheckResult): string[] {
|
|
201
|
+
switch (result.status) {
|
|
202
|
+
case 'drift':
|
|
203
|
+
return [
|
|
204
|
+
'Database schema differs from the canonical Prenta schema.',
|
|
205
|
+
'Apply the migrations shipped by db:sync (includes column renames):',
|
|
206
|
+
' npx prisma migrate deploy',
|
|
207
|
+
'If drift remains afterward, generate a reconciling migration:',
|
|
208
|
+
' npx prisma migrate dev --name prenta-schema-sync',
|
|
209
|
+
]
|
|
210
|
+
case 'error':
|
|
211
|
+
return ['Could not check schema drift (is the database reachable?).']
|
|
212
|
+
case 'skipped':
|
|
213
|
+
return [result.detail ?? 'Drift check skipped.']
|
|
214
|
+
case 'no-drift':
|
|
215
|
+
return ['Database schema matches the canonical Prenta schema.']
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
export interface DbSyncResult {
|
|
220
|
+
schemaWritten: boolean
|
|
221
|
+
migrationsAdded: string[]
|
|
222
|
+
skippedReason?: string
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Core sync logic, separated from CLI plumbing for testing. Additive for
|
|
227
|
+
* migrations (never deletes existing ones — they are immutable history), and
|
|
228
|
+
* guarded for the schema (won't overwrite a non-auto-synced schema without
|
|
229
|
+
* `force`).
|
|
230
|
+
*/
|
|
231
|
+
export async function syncPrismaAssets(
|
|
232
|
+
consumerSchemaPath: string,
|
|
233
|
+
corePrismaDir: string,
|
|
234
|
+
opts: { force?: boolean } = {},
|
|
235
|
+
): Promise<DbSyncResult> {
|
|
236
|
+
const coreSchemaPath = join(corePrismaDir, 'schema.prisma')
|
|
237
|
+
const coreSchema = await readFile(coreSchemaPath, 'utf-8')
|
|
238
|
+
const nextSchema = buildConsumerSchema(coreSchema)
|
|
239
|
+
|
|
240
|
+
const consumerDir = dirname(consumerSchemaPath)
|
|
241
|
+
const consumerMigrationsDir = join(consumerDir, 'migrations')
|
|
242
|
+
const coreMigrationsDir = join(corePrismaDir, 'migrations')
|
|
243
|
+
|
|
244
|
+
// Guard the schema overwrite.
|
|
245
|
+
let schemaWritten = false
|
|
246
|
+
let skippedReason: string | undefined
|
|
247
|
+
const existing = existsSync(consumerSchemaPath)
|
|
248
|
+
? await readFile(consumerSchemaPath, 'utf-8')
|
|
249
|
+
: null
|
|
250
|
+
|
|
251
|
+
if (existing && !existing.includes(AUTO_SYNCED_MARKER) && !opts.force) {
|
|
252
|
+
skippedReason =
|
|
253
|
+
'schema.prisma is not an auto-synced Prenta schema (no AUTO-SYNCED marker). Re-run with --force to overwrite it.'
|
|
254
|
+
} else {
|
|
255
|
+
await mkdir(consumerDir, { recursive: true })
|
|
256
|
+
if (existing !== nextSchema) {
|
|
257
|
+
await writeFile(consumerSchemaPath, nextSchema)
|
|
258
|
+
schemaWritten = true
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// Additively copy any cms-core migrations the consumer doesn't already have.
|
|
263
|
+
const coreMigrations = await listMigrationDirs(coreMigrationsDir)
|
|
264
|
+
const existingMigrations = new Set(await listMigrationDirs(consumerMigrationsDir))
|
|
265
|
+
const migrationsAdded: string[] = []
|
|
266
|
+
|
|
267
|
+
if (coreMigrations.length > 0) {
|
|
268
|
+
await mkdir(consumerMigrationsDir, { recursive: true })
|
|
269
|
+
const lockSrc = join(coreMigrationsDir, 'migration_lock.toml')
|
|
270
|
+
const lockDest = join(consumerMigrationsDir, 'migration_lock.toml')
|
|
271
|
+
if (existsSync(lockSrc) && !existsSync(lockDest)) {
|
|
272
|
+
await cp(lockSrc, lockDest)
|
|
273
|
+
}
|
|
274
|
+
for (const name of coreMigrations) {
|
|
275
|
+
if (existingMigrations.has(name)) continue
|
|
276
|
+
await cp(join(coreMigrationsDir, name), join(consumerMigrationsDir, name), {
|
|
277
|
+
recursive: true,
|
|
278
|
+
})
|
|
279
|
+
migrationsAdded.push(name)
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
return { schemaWritten, migrationsAdded, skippedReason }
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
async function runDbSync(options: DbSyncOptions): Promise<void> {
|
|
287
|
+
const consumerSchemaPath = resolve(process.cwd(), options.schema)
|
|
288
|
+
const spinner = ora('Locating @prenta/core…').start()
|
|
289
|
+
|
|
290
|
+
const corePrismaDir = resolveCmsCorePrismaDir()
|
|
291
|
+
if (!corePrismaDir) {
|
|
292
|
+
spinner.fail('Could not locate @prenta/core.')
|
|
293
|
+
logger.info('Install it first: `npm install @prenta/core`.')
|
|
294
|
+
process.exitCode = 1
|
|
295
|
+
return
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
try {
|
|
299
|
+
await access(join(corePrismaDir, 'schema.prisma'))
|
|
300
|
+
} catch {
|
|
301
|
+
spinner.fail(`cms-core does not ship a Prisma schema at ${corePrismaDir}.`)
|
|
302
|
+
process.exitCode = 1
|
|
303
|
+
return
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
spinner.text = 'Syncing schema + migrations…'
|
|
307
|
+
let result: DbSyncResult
|
|
308
|
+
try {
|
|
309
|
+
result = await syncPrismaAssets(consumerSchemaPath, corePrismaDir, { force: options.force })
|
|
310
|
+
} catch (err) {
|
|
311
|
+
spinner.fail('Failed to sync Prisma assets.')
|
|
312
|
+
logger.error(err instanceof Error ? err.message : String(err))
|
|
313
|
+
process.exitCode = 1
|
|
314
|
+
return
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
spinner.succeed('Prisma assets synced from cms-core.')
|
|
318
|
+
|
|
319
|
+
if (result.skippedReason) {
|
|
320
|
+
logger.warn(`Schema not updated: ${result.skippedReason}`)
|
|
321
|
+
} else if (result.schemaWritten) {
|
|
322
|
+
logger.success('schema.prisma refreshed.')
|
|
323
|
+
} else {
|
|
324
|
+
logger.info('schema.prisma already up to date.')
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
if (result.migrationsAdded.length > 0) {
|
|
328
|
+
logger.success(`Added ${result.migrationsAdded.length} new migration(s).`)
|
|
329
|
+
} else {
|
|
330
|
+
logger.info('No new migrations to add.')
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
if (result.schemaWritten || result.migrationsAdded.length > 0) {
|
|
334
|
+
logger.info('Next: run `npx prisma migrate deploy` then `npx prisma generate`.')
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
// Drift detection: compare the live DB against the canonical schema so a
|
|
338
|
+
// mismatch (e.g. a renamed column not yet migrated) surfaces an exact command
|
|
339
|
+
// rather than a silent runtime failure. Opt-out with --no-check-drift.
|
|
340
|
+
if (options.checkDrift !== false && !result.skippedReason) {
|
|
341
|
+
const driftSpinner = ora('Checking database for schema drift…').start()
|
|
342
|
+
const drift = await checkSchemaDrift(consumerSchemaPath)
|
|
343
|
+
if (drift.status === 'drift') {
|
|
344
|
+
driftSpinner.warn('Schema drift detected.')
|
|
345
|
+
if (drift.detail) {
|
|
346
|
+
logger.info('Reconciling SQL (review before applying):')
|
|
347
|
+
console.log(drift.detail)
|
|
348
|
+
}
|
|
349
|
+
for (const line of driftGuidance(drift)) logger.info(line)
|
|
350
|
+
process.exitCode = 1
|
|
351
|
+
} else if (drift.status === 'no-drift') {
|
|
352
|
+
driftSpinner.succeed('No schema drift detected.')
|
|
353
|
+
} else {
|
|
354
|
+
driftSpinner.info(driftGuidance(drift)[0] ?? 'Drift check skipped.')
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
export function registerDbSyncCommand(program: Command): void {
|
|
360
|
+
program
|
|
361
|
+
.command('db:sync')
|
|
362
|
+
.description('Sync the canonical Prisma schema + migrations from the installed cms-core')
|
|
363
|
+
.option('--schema <path>', 'Path to schema.prisma', 'prisma/schema.prisma')
|
|
364
|
+
.option('--force', 'Overwrite schema.prisma even if it lacks the AUTO-SYNCED marker')
|
|
365
|
+
.option('--no-check-drift', 'Skip the post-sync database drift check')
|
|
366
|
+
.action(runDbSync)
|
|
367
|
+
}
|