@prenta/cli 0.16.5 → 0.17.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +36 -27
  3. package/CHANGELOG.md +12 -0
  4. package/dist/backup/blob-store.d.ts +89 -0
  5. package/dist/backup/blob-store.d.ts.map +1 -0
  6. package/dist/backup/blob-store.js +183 -0
  7. package/dist/backup/blob-store.js.map +1 -0
  8. package/dist/backup/common.d.ts +73 -0
  9. package/dist/backup/common.d.ts.map +1 -0
  10. package/dist/backup/common.js +134 -0
  11. package/dist/backup/common.js.map +1 -0
  12. package/dist/backup/crypto.d.ts +26 -0
  13. package/dist/backup/crypto.d.ts.map +1 -0
  14. package/dist/backup/crypto.js +175 -0
  15. package/dist/backup/crypto.js.map +1 -0
  16. package/dist/backup/manifest.d.ts +69 -0
  17. package/dist/backup/manifest.d.ts.map +1 -0
  18. package/dist/backup/manifest.js +161 -0
  19. package/dist/backup/manifest.js.map +1 -0
  20. package/dist/backup/pg-tools.d.ts +74 -0
  21. package/dist/backup/pg-tools.d.ts.map +1 -0
  22. package/dist/backup/pg-tools.js +267 -0
  23. package/dist/backup/pg-tools.js.map +1 -0
  24. package/dist/backup/workflow-template.d.ts +14 -0
  25. package/dist/backup/workflow-template.d.ts.map +1 -0
  26. package/dist/backup/workflow-template.js +49 -0
  27. package/dist/backup/workflow-template.js.map +1 -0
  28. package/dist/commands/db-backup.d.ts +56 -0
  29. package/dist/commands/db-backup.d.ts.map +1 -0
  30. package/dist/commands/db-backup.js +226 -0
  31. package/dist/commands/db-backup.js.map +1 -0
  32. package/dist/commands/db-restore.d.ts +70 -0
  33. package/dist/commands/db-restore.d.ts.map +1 -0
  34. package/dist/commands/db-restore.js +380 -0
  35. package/dist/commands/db-restore.js.map +1 -0
  36. package/dist/commands/doctor.d.ts.map +1 -1
  37. package/dist/commands/doctor.js +6 -1
  38. package/dist/commands/doctor.js.map +1 -1
  39. package/dist/deployment/diagnostics.d.ts +4 -0
  40. package/dist/deployment/diagnostics.d.ts.map +1 -1
  41. package/dist/deployment/diagnostics.js +27 -0
  42. package/dist/deployment/diagnostics.js.map +1 -1
  43. package/dist/index.js +4 -0
  44. package/dist/index.js.map +1 -1
  45. package/dist/utils/repo-root.d.ts +9 -0
  46. package/dist/utils/repo-root.d.ts.map +1 -0
  47. package/dist/utils/repo-root.js +21 -0
  48. package/dist/utils/repo-root.js.map +1 -0
  49. package/package.json +10 -3
  50. package/src/__tests__/backup-blob-store.test.ts +324 -0
  51. package/src/__tests__/backup-common.test.ts +125 -0
  52. package/src/__tests__/backup-crypto.test.ts +197 -0
  53. package/src/__tests__/backup-manifest.test.ts +189 -0
  54. package/src/__tests__/backup-pg-tools.test.ts +275 -0
  55. package/src/__tests__/db-backup.test.ts +557 -0
  56. package/src/__tests__/db-restore.test.ts +784 -0
  57. package/src/__tests__/deployment-diagnostics.test.ts +55 -0
  58. package/src/__tests__/fixtures/fake-blob.ts +120 -0
  59. package/src/__tests__/fixtures/fake-spawn.ts +66 -0
  60. package/src/__tests__/fixtures/pg-url.ts +56 -0
  61. package/src/__tests__/integration/backup-roundtrip.int.test.ts +208 -0
  62. package/src/__tests__/repo-root.test.ts +49 -0
  63. package/src/backup/blob-store.ts +294 -0
  64. package/src/backup/common.ts +159 -0
  65. package/src/backup/crypto.ts +192 -0
  66. package/src/backup/manifest.ts +217 -0
  67. package/src/backup/pg-tools.ts +384 -0
  68. package/src/backup/workflow-template.ts +49 -0
  69. package/src/commands/db-backup.ts +335 -0
  70. package/src/commands/db-restore.ts +542 -0
  71. package/src/commands/doctor.ts +6 -0
  72. package/src/deployment/diagnostics.ts +42 -0
  73. package/src/index.ts +4 -0
  74. package/src/utils/repo-root.ts +19 -0
@@ -469,4 +469,59 @@ describe('deployment diagnostics', () => {
469
469
  ]),
470
470
  )
471
471
  })
472
+
473
+ describe('db-backups check', () => {
474
+ const baseEnv = {
475
+ DATABASE_URL: 'postgresql://example',
476
+ CMS_SECRET: 'secret',
477
+ CMS_ENCRYPTION_KEY: 'a'.repeat(64),
478
+ NEXT_PUBLIC_SITE_URL: 'https://example.com',
479
+ }
480
+ const run = (env: Record<string, string | undefined>, backupWorkflowPresent: boolean) =>
481
+ createDiagnosticReport({
482
+ schemaModels: new Set(REQUIRED_CMS_MODELS),
483
+ schemaContent: '',
484
+ env,
485
+ packageManager: 'pnpm',
486
+ schemaPath: 'prisma/schema.prisma',
487
+ projectFiles: { backupWorkflowPresent },
488
+ }).checks.find((c) => c.id === 'db-backups')
489
+
490
+ it('passes when the key is set and the workflow exists', () => {
491
+ expect(run({ ...baseEnv, BACKUP_ENCRYPTION_KEY: 'b'.repeat(64) }, true)).toMatchObject({
492
+ status: 'pass',
493
+ })
494
+ })
495
+
496
+ it('warns (not fails) when BACKUP_ENCRYPTION_KEY is unset, naming the fix', () => {
497
+ const check = run(baseEnv, true)
498
+ expect(check).toMatchObject({ status: 'warn' })
499
+ expect(check?.message).toMatch(/BACKUP_ENCRYPTION_KEY/)
500
+ expect(check?.fix).toMatch(/openssl rand -hex 32/)
501
+ })
502
+
503
+ it('warns when the nightly workflow file is missing, pointing at --init-workflow', () => {
504
+ const check = run({ ...baseEnv, BACKUP_ENCRYPTION_KEY: 'b'.repeat(64) }, false)
505
+ expect(check).toMatchObject({ status: 'warn' })
506
+ expect(check?.message).toMatch(/\.github\/workflows\/db-backup\.yml/)
507
+ expect(check?.fix).toMatch(/prenta db:backup --init-workflow/)
508
+ })
509
+
510
+ it('mentions both problems when both are missing', () => {
511
+ const check = run(baseEnv, false)
512
+ expect(check?.message).toMatch(/BACKUP_ENCRYPTION_KEY/)
513
+ expect(check?.message).toMatch(/db-backup\.yml/)
514
+ })
515
+
516
+ it('is skipped when the workflow signal was not collected', () => {
517
+ const report = createDiagnosticReport({
518
+ schemaModels: new Set(REQUIRED_CMS_MODELS),
519
+ schemaContent: '',
520
+ env: baseEnv,
521
+ packageManager: 'pnpm',
522
+ schemaPath: 'prisma/schema.prisma',
523
+ })
524
+ expect(report.checks.find((c) => c.id === 'db-backups')).toBeUndefined()
525
+ })
526
+ })
472
527
  })
@@ -0,0 +1,120 @@
1
+ import { Readable } from 'node:stream'
2
+ import type { ReadableStream as WebReadableStream } from 'node:stream/web'
3
+
4
+ import type {
5
+ BlobListedItem,
6
+ BlobModule,
7
+ BlobPutOptions,
8
+ BlobPutResult,
9
+ } from '../../backup/blob-store.js'
10
+
11
+ export interface FakeBlobCall {
12
+ op: 'put' | 'list' | 'del' | 'get'
13
+ args: unknown[]
14
+ }
15
+
16
+ export interface FakeBlob {
17
+ module: BlobModule
18
+ calls: FakeBlobCall[]
19
+ /** Pathname → bytes. Seed with `seed()` or observe after `put()`. */
20
+ objects: Map<string, { body: Buffer; uploadedAt: Date }>
21
+ seed(pathname: string, body: Buffer | string, uploadedAt?: Date): void
22
+ /** Make the next `put` reject (e.g. to prove prune is skipped). */
23
+ failNextPut(error?: Error): void
24
+ /** Make the `put` of exactly this pathname reject (once). */
25
+ failPutOf(pathname: string, error?: Error): void
26
+ }
27
+
28
+ async function toBuffer(body: unknown): Promise<Buffer> {
29
+ if (Buffer.isBuffer(body)) return body
30
+ if (typeof body === 'string') return Buffer.from(body)
31
+ if (body instanceof Readable) {
32
+ const chunks: Buffer[] = []
33
+ for await (const chunk of body) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk))
34
+ return Buffer.concat(chunks)
35
+ }
36
+ throw new Error(`fake blob: unsupported body type ${typeof body}`)
37
+ }
38
+
39
+ /**
40
+ * In-memory stand-in for `@vercel/blob` covering exactly the surface
41
+ * `createBlobStore` uses. Paginates `list` in pages of `pageSize` so cursor
42
+ * handling is exercised.
43
+ */
44
+ export function createFakeBlob(opts: { pageSize?: number } = {}): FakeBlob {
45
+ const pageSize = opts.pageSize ?? 2
46
+ const calls: FakeBlobCall[] = []
47
+ const objects = new Map<string, { body: Buffer; uploadedAt: Date }>()
48
+ let putFailure: Error | null = null
49
+ const putFailuresByPath = new Map<string, Error>()
50
+
51
+ const urlFor = (pathname: string) => `https://fake.blob.vercel-storage.com/${pathname}`
52
+
53
+ const module: BlobModule = {
54
+ async put(pathname: string, body: unknown, options: BlobPutOptions): Promise<BlobPutResult> {
55
+ calls.push({ op: 'put', args: [pathname, options] })
56
+ if (putFailure) {
57
+ const err = putFailure
58
+ putFailure = null
59
+ throw err
60
+ }
61
+ const targeted = putFailuresByPath.get(pathname)
62
+ if (targeted) {
63
+ putFailuresByPath.delete(pathname)
64
+ throw targeted
65
+ }
66
+ const buffer = await toBuffer(body)
67
+ objects.set(pathname, { body: buffer, uploadedAt: new Date() })
68
+ return { url: urlFor(pathname), pathname }
69
+ },
70
+ async list(options) {
71
+ calls.push({ op: 'list', args: [options] })
72
+ const all = [...objects.entries()]
73
+ .filter(([p]) => p.startsWith(options.prefix))
74
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
75
+ const start = options.cursor ? Number(options.cursor) : 0
76
+ const page = all.slice(start, start + pageSize)
77
+ const blobs: BlobListedItem[] = page.map(([pathname, o]) => ({
78
+ pathname,
79
+ size: o.body.length,
80
+ uploadedAt: o.uploadedAt,
81
+ url: urlFor(pathname),
82
+ }))
83
+ const next = start + pageSize
84
+ return {
85
+ blobs,
86
+ hasMore: next < all.length,
87
+ cursor: next < all.length ? String(next) : undefined,
88
+ }
89
+ },
90
+ async del(urlsOrPathnames, options) {
91
+ calls.push({ op: 'del', args: [urlsOrPathnames, options] })
92
+ const list = Array.isArray(urlsOrPathnames) ? urlsOrPathnames : [urlsOrPathnames]
93
+ for (const p of list) objects.delete(p)
94
+ },
95
+ async get(pathname, options) {
96
+ calls.push({ op: 'get', args: [pathname, options] })
97
+ const found = objects.get(pathname)
98
+ if (!found) return null
99
+ return {
100
+ statusCode: 200,
101
+ stream: Readable.toWeb(Readable.from([found.body])) as WebReadableStream<Uint8Array>,
102
+ }
103
+ },
104
+ }
105
+
106
+ return {
107
+ module,
108
+ calls,
109
+ objects,
110
+ seed(pathname, body, uploadedAt = new Date()) {
111
+ objects.set(pathname, { body: Buffer.isBuffer(body) ? body : Buffer.from(body), uploadedAt })
112
+ },
113
+ failNextPut(error = new Error('fake blob: upload failed')) {
114
+ putFailure = error
115
+ },
116
+ failPutOf(pathname, error = new Error(`fake blob: upload of ${pathname} failed`)) {
117
+ putFailuresByPath.set(pathname, error)
118
+ },
119
+ }
120
+ }
@@ -0,0 +1,66 @@
1
+ import { EventEmitter } from 'node:events'
2
+ import { Readable } from 'node:stream'
3
+
4
+ import type { SpawnedProcess, SpawnImpl, SpawnOptions } from '../../backup/pg-tools.js'
5
+
6
+ export interface SpawnCall {
7
+ command: string
8
+ args: string[]
9
+ options: SpawnOptions
10
+ }
11
+
12
+ export interface FakeProcessScript {
13
+ /** Exit code; `null` emulates a signal kill. */
14
+ code?: number | null
15
+ stdout?: string
16
+ stderr?: string
17
+ /** Emit `error` (e.g. ENOENT) instead of running. */
18
+ error?: Error
19
+ /** Called with the spawned args before resolving — lets a test create the output file. */
20
+ onSpawn?: (call: SpawnCall) => void | Promise<void>
21
+ }
22
+
23
+ export type ScriptResolver = (call: SpawnCall) => FakeProcessScript
24
+
25
+ /**
26
+ * Build an injectable `spawnImpl` that never touches the OS. Every call is
27
+ * recorded in `calls`; `resolve` decides what each fake process does.
28
+ */
29
+ export function createFakeSpawn(resolve: ScriptResolver): { spawn: SpawnImpl; calls: SpawnCall[] } {
30
+ const calls: SpawnCall[] = []
31
+ const spawn: SpawnImpl = (command, args, options) => {
32
+ const call: SpawnCall = { command, args: [...args], options }
33
+ calls.push(call)
34
+ const script = resolve(call)
35
+ const emitter = new EventEmitter()
36
+ const proc = emitter as EventEmitter & SpawnedProcess
37
+ proc.stdout = Readable.from(script.stdout ? [Buffer.from(script.stdout)] : [])
38
+ proc.stderr = Readable.from(script.stderr ? [Buffer.from(script.stderr)] : [])
39
+ void (async () => {
40
+ await script.onSpawn?.(call)
41
+ // Let stdout/stderr consumers attach first, then drain before close.
42
+ await new Promise((r) => setImmediate(r))
43
+ if (script.error) {
44
+ emitter.emit('error', script.error)
45
+ return
46
+ }
47
+ await Promise.all([drained(proc.stdout), drained(proc.stderr)])
48
+ emitter.emit('close', script.code ?? 0)
49
+ })()
50
+ return proc
51
+ }
52
+ return { spawn, calls }
53
+ }
54
+
55
+ function drained(stream: Readable | null): Promise<void> {
56
+ if (!stream || stream.readableEnded) return Promise.resolve()
57
+ return new Promise((r) => {
58
+ stream.once('end', () => r())
59
+ stream.resume()
60
+ })
61
+ }
62
+
63
+ /** Script a `--version` probe for a PostgreSQL client tool. */
64
+ export function versionScript(tool: string, version: string): FakeProcessScript {
65
+ return { code: 0, stdout: `${tool} (PostgreSQL) ${version}\n` }
66
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Builds Postgres connection URLs for tests from parts, so no
3
+ * `postgres://USER:PASSWORD@host` literal with a concrete password ever
4
+ * appears in source (secret scanners flag the shape regardless of how
5
+ * obviously fake the password is).
6
+ *
7
+ * The guard under test is host-agnostic, so fixtures use `example.net` hosts.
8
+ */
9
+
10
+ // Values are assembled rather than written as literals: generic "password
11
+ // assigned" / "token assigned" detectors key on `NAME = 'value'` shapes even
12
+ // when the value is plainly fake.
13
+ const fake = (...parts: string[]): string => parts.join('-')
14
+
15
+ export const FAKE_PASSWORD_1 = fake('fake', 'password', '1')
16
+ export const FAKE_PASSWORD_2 = fake('fake', 'password', '2')
17
+ /** Decoded form containing `@` and `:`, which must be percent-encoded in a URL. */
18
+ export const FAKE_PASSWORD_DECODED = ['fake', 'password:1'].join('@')
19
+ /** URL-encoded form of {@link FAKE_PASSWORD_DECODED} (`@` → `%40`, `:` → `%3A`). */
20
+ export const FAKE_PASSWORD_ENCODED = encodeURIComponent(FAKE_PASSWORD_DECODED)
21
+ /** Non-empty Blob token for tests; `blob-store.ts` does not validate the prefix. */
22
+ export const TEST_BLOB_TOKEN = fake('blob', 'token', 'for', 'tests')
23
+
24
+ export interface PgUrlParts {
25
+ user?: string
26
+ /** Omit for a password-less URL (`postgres://user@host…`). */
27
+ password?: string
28
+ host?: string
29
+ /** `null` omits the port entirely (`…@host/db`). */
30
+ port?: number | null
31
+ /**
32
+ * Database path segment, appended as `/${database}`: `''` yields a bare
33
+ * trailing slash, `'prod/'` keeps a trailing slash. `null` omits the path
34
+ * entirely (`…:5432`).
35
+ */
36
+ database?: string | null
37
+ protocol?: string
38
+ /** Query string without the leading `?`. */
39
+ query?: string
40
+ }
41
+
42
+ export function pgUrl({
43
+ user = 'app',
44
+ password,
45
+ host = 'db.example.net',
46
+ port = 5432,
47
+ database = 'postgres',
48
+ protocol = 'postgres',
49
+ query,
50
+ }: PgUrlParts = {}): string {
51
+ const credentials = password === undefined ? user : `${user}:${password}`
52
+ const authority = port === null ? host : `${host}:${port}`
53
+ const path = database === null ? '' : `/${database}`
54
+ const search = query === undefined ? '' : `?${query}`
55
+ return `${protocol}://${credentials}@${authority}${path}${search}`
56
+ }
@@ -0,0 +1,208 @@
1
+ /**
2
+ * End-to-end proof of the backup pipeline against a real PostgreSQL server:
3
+ * `db:backup` (pg_dump → encrypt → manifest) followed by `db:restore`
4
+ * (verify → decrypt → pg_restore → count) into a second, empty database.
5
+ *
6
+ * Runs only when `PRENTA_PG_TEST_URL` names a server the test may create and
7
+ * drop databases on, with PostgreSQL 17 client tools (`pg_dump`, `pg_restore`,
8
+ * `psql`) on PATH — the `backup-roundtrip` job in .github/workflows/ci.yml.
9
+ * Everywhere else the suite is reported as skipped, never failed.
10
+ */
11
+ import { execFile } from 'node:child_process'
12
+ import { randomBytes } from 'node:crypto'
13
+ import { existsSync } from 'node:fs'
14
+ import { mkdtemp, readFile, rm } from 'node:fs/promises'
15
+ import { tmpdir } from 'node:os'
16
+ import path from 'node:path'
17
+ import { promisify } from 'node:util'
18
+ import { afterAll, beforeAll, describe, expect, it } from 'vitest'
19
+
20
+ import { parseManifest, sha256File } from '../../backup/manifest.js'
21
+ import { nodeSpawn } from '../../backup/pg-tools.js'
22
+ import { type DbBackupSummary, runDbBackup } from '../../commands/db-backup.js'
23
+ import { type DbRestoreSummary, runDbRestore } from '../../commands/db-restore.js'
24
+
25
+ const ADMIN_URL = process.env.PRENTA_PG_TEST_URL
26
+ const execFileAsync = promisify(execFile)
27
+
28
+ const AUTHOR_ROWS = 20
29
+ const POST_ROWS = 30
30
+
31
+ function databaseUrl(adminUrl: string, database: string): string {
32
+ const url = new URL(adminUrl)
33
+ url.pathname = `/${database}`
34
+ return url.toString()
35
+ }
36
+
37
+ async function psql(url: string, sql: string): Promise<string> {
38
+ const { stdout } = await execFileAsync('psql', [
39
+ '--no-psqlrc',
40
+ '--quiet',
41
+ '--tuples-only',
42
+ '--no-align',
43
+ '--set=ON_ERROR_STOP=1',
44
+ `--dbname=${url}`,
45
+ `--command=${sql}`,
46
+ ])
47
+ return stdout.trim()
48
+ }
49
+
50
+ /** process.env with the pipeline's inputs pinned and unrelated database/Blob settings removed. */
51
+ function commandEnv(directUrl: string, backupKey: string): NodeJS.ProcessEnv {
52
+ const env: NodeJS.ProcessEnv = {
53
+ ...process.env,
54
+ DIRECT_DATABASE_URL: directUrl,
55
+ BACKUP_ENCRYPTION_KEY: backupKey,
56
+ }
57
+ delete env.DATABASE_URL
58
+ delete env.BLOB_READ_WRITE_TOKEN
59
+ return env
60
+ }
61
+
62
+ function silentLog() {
63
+ const lines = { info: [] as string[], warn: [] as string[], error: [] as string[] }
64
+ return {
65
+ lines,
66
+ log: {
67
+ info: (m: string) => lines.info.push(m),
68
+ success: (m: string) => lines.info.push(m),
69
+ warn: (m: string) => lines.warn.push(m),
70
+ error: (m: string) => lines.error.push(m),
71
+ },
72
+ }
73
+ }
74
+
75
+ describe.skipIf(!ADMIN_URL)('db:backup → db:restore round-trip (real PostgreSQL)', () => {
76
+ const runId = randomBytes(4).toString('hex')
77
+ const sourceDb = `prenta_rt_src_${runId}`
78
+ const targetDb = `prenta_rt_dst_${runId}`
79
+ const key = randomBytes(32).toString('hex')
80
+ let sourceUrl: string
81
+ let targetUrl: string
82
+ let cwd: string
83
+ let outDir: string
84
+
85
+ beforeAll(async () => {
86
+ const admin = ADMIN_URL!
87
+ sourceUrl = databaseUrl(admin, sourceDb)
88
+ targetUrl = databaseUrl(admin, targetDb)
89
+ cwd = await mkdtemp(path.join(tmpdir(), 'prenta-rt-cwd-'))
90
+ outDir = await mkdtemp(path.join(tmpdir(), 'prenta-rt-out-'))
91
+
92
+ await psql(admin, `CREATE DATABASE ${sourceDb}`)
93
+ await psql(
94
+ sourceUrl,
95
+ [
96
+ 'CREATE SCHEMA roundtrip',
97
+ 'CREATE TABLE roundtrip.authors (id serial PRIMARY KEY, name text NOT NULL)',
98
+ 'CREATE TABLE roundtrip.posts (' +
99
+ 'id serial PRIMARY KEY, ' +
100
+ 'author_id integer NOT NULL REFERENCES roundtrip.authors(id), ' +
101
+ 'title text NOT NULL, body text)',
102
+ `INSERT INTO roundtrip.authors (name) SELECT 'author ' || g FROM generate_series(1, ${AUTHOR_ROWS}) g`,
103
+ `INSERT INTO roundtrip.posts (author_id, title, body) SELECT ((g - 1) % ${AUTHOR_ROWS}) + 1, 'post ' || g, repeat('lorem ', 20) FROM generate_series(1, ${POST_ROWS}) g`,
104
+ // Populate pg_class.reltuples so the manifest carries real estimates.
105
+ 'ANALYZE roundtrip.authors',
106
+ 'ANALYZE roundtrip.posts',
107
+ ].join('; '),
108
+ )
109
+ })
110
+
111
+ afterAll(async () => {
112
+ const admin = ADMIN_URL!
113
+ for (const db of [sourceDb, targetDb]) {
114
+ await psql(admin, `DROP DATABASE IF EXISTS ${db} WITH (FORCE)`).catch(() => undefined)
115
+ }
116
+ await rm(cwd, { recursive: true, force: true })
117
+ await rm(outDir, { recursive: true, force: true })
118
+ })
119
+
120
+ it('backs up, restores into a fresh database, and preserves every row', async () => {
121
+ // ---- db:backup (local files only; no Blob) ----
122
+ const backupLog = silentLog()
123
+ const backupStdout: string[] = []
124
+ const backupCode = await runDbBackup(
125
+ { out: outDir, allowLocal: true, json: true },
126
+ {
127
+ spawnImpl: nodeSpawn,
128
+ env: commandEnv(sourceUrl, key),
129
+ cwd,
130
+ now: () => new Date(),
131
+ log: backupLog.log,
132
+ print: (line) => backupStdout.push(line),
133
+ },
134
+ )
135
+ expect(backupLog.lines.error, backupLog.lines.error.join('\n')).toEqual([])
136
+ expect(backupCode).toBe(0)
137
+
138
+ const summary = JSON.parse(backupStdout.at(-1)!) as DbBackupSummary
139
+ expect(summary.uploaded).toBe(false)
140
+ expect(existsSync(summary.dumpPath)).toBe(true)
141
+ expect(existsSync(summary.manifestPath)).toBe(true)
142
+ expect(summary.dumpPath.endsWith('.dump.enc')).toBe(true)
143
+ expect(summary.sizeBytes).toBeGreaterThan(0)
144
+
145
+ const manifest = parseManifest(JSON.parse(await readFile(summary.manifestPath, 'utf-8')))
146
+ expect(manifest.sha256).toBe(await sha256File(summary.dumpPath))
147
+ expect(manifest.sizeBytes).toBe(summary.sizeBytes)
148
+ expect(manifest.database.name).toBe(sourceDb)
149
+ expect(manifest.pgDumpVersion).toMatch(/^17\./)
150
+ const tableNames = manifest.tables.map((t) => `${t.schema}.${t.name}`)
151
+ expect(tableNames).toEqual(['roundtrip.authors', 'roundtrip.posts'])
152
+ // Analyzed tables carry accurate planner estimates.
153
+ expect(manifest.tables.find((t) => t.name === 'authors')?.rows).toBe(AUTHOR_ROWS)
154
+ expect(manifest.tables.find((t) => t.name === 'posts')?.rows).toBe(POST_ROWS)
155
+
156
+ // ---- db:restore into a second, empty database on the same server ----
157
+ await psql(ADMIN_URL!, `CREATE DATABASE ${targetDb}`)
158
+ expect(
159
+ await psql(
160
+ targetUrl,
161
+ "SELECT count(*) FROM information_schema.tables WHERE table_schema = 'roundtrip'",
162
+ ),
163
+ ).toBe('0')
164
+
165
+ const restoreLog = silentLog()
166
+ const restoreStdout: string[] = []
167
+ const restoreCode = await runDbRestore(
168
+ summary.dumpPath,
169
+ { target: targetUrl, yes: true, json: true },
170
+ {
171
+ spawnImpl: nodeSpawn,
172
+ // DIRECT_DATABASE_URL names the same host as the target but a different
173
+ // database: the production guard must not trip.
174
+ env: commandEnv(sourceUrl, key),
175
+ cwd,
176
+ now: () => new Date(),
177
+ log: restoreLog.log,
178
+ print: (line) => restoreStdout.push(line),
179
+ interactive: false,
180
+ prompt: () => Promise.reject(new Error('prompt must not be called with --yes')),
181
+ },
182
+ )
183
+ expect(restoreLog.lines.error, restoreLog.lines.error.join('\n')).toEqual([])
184
+ expect(restoreCode).toBe(0)
185
+
186
+ const restored = JSON.parse(restoreStdout.at(-1)!) as DbRestoreSummary
187
+ expect(restored.sha256Verified).toBe(true)
188
+ expect(restored.stamp).toBe(manifest.stamp)
189
+ expect(restored.tables.map((t) => [`${t.schema}.${t.name}`, t.estimate, t.restored])).toEqual([
190
+ ['roundtrip.authors', AUTHOR_ROWS, AUTHOR_ROWS],
191
+ ['roundtrip.posts', POST_ROWS, POST_ROWS],
192
+ ])
193
+
194
+ // Independent check straight from the target database.
195
+ expect(await psql(targetUrl, 'SELECT count(*) FROM roundtrip.authors')).toBe(
196
+ String(AUTHOR_ROWS),
197
+ )
198
+ expect(await psql(targetUrl, 'SELECT count(*) FROM roundtrip.posts')).toBe(String(POST_ROWS))
199
+ expect(
200
+ await psql(
201
+ targetUrl,
202
+ 'SELECT count(*) FROM roundtrip.posts p JOIN roundtrip.authors a ON a.id = p.author_id',
203
+ ),
204
+ ).toBe(String(POST_ROWS))
205
+ // The source is untouched.
206
+ expect(await psql(sourceUrl, 'SELECT count(*) FROM roundtrip.posts')).toBe(String(POST_ROWS))
207
+ })
208
+ })
@@ -0,0 +1,49 @@
1
+ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
2
+ import { tmpdir } from 'node:os'
3
+ import path from 'node:path'
4
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest'
5
+
6
+ import { findRepoRoot } from '../utils/repo-root.js'
7
+
8
+ describe('findRepoRoot', () => {
9
+ let root: string
10
+
11
+ beforeEach(async () => {
12
+ root = await mkdtemp(path.join(tmpdir(), 'prenta-repo-root-'))
13
+ })
14
+
15
+ afterEach(async () => {
16
+ await rm(root, { recursive: true, force: true })
17
+ })
18
+
19
+ it('walks up to the first ancestor containing a .git directory', async () => {
20
+ await mkdir(path.join(root, '.git'))
21
+ const nested = path.join(root, 'apps', 'cms')
22
+ await mkdir(nested, { recursive: true })
23
+ expect(findRepoRoot(nested)).toBe(root)
24
+ expect(findRepoRoot(root)).toBe(root)
25
+ })
26
+
27
+ it('accepts a .git file (worktree / submodule)', async () => {
28
+ await writeFile(path.join(root, '.git'), 'gitdir: ../.git/worktrees/x\n')
29
+ const nested = path.join(root, 'a', 'b')
30
+ await mkdir(nested, { recursive: true })
31
+ expect(findRepoRoot(nested)).toBe(root)
32
+ })
33
+
34
+ it('stops at the nearest .git, not an outer one', async () => {
35
+ await mkdir(path.join(root, '.git'))
36
+ const inner = path.join(root, 'vendor', 'lib')
37
+ await mkdir(path.join(inner, '.git'), { recursive: true })
38
+ const cwd = path.join(inner, 'src')
39
+ await mkdir(cwd)
40
+ expect(findRepoRoot(cwd)).toBe(inner)
41
+ })
42
+
43
+ it('falls back to cwd when no ancestor has .git', async () => {
44
+ // The temp dir itself has no .git; nothing above it in tmpdir should either.
45
+ const cwd = path.join(root, 'x', 'y')
46
+ await mkdir(cwd, { recursive: true })
47
+ expect(findRepoRoot(cwd)).toBe(cwd)
48
+ })
49
+ })