@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
@@ -1,4 +1,4 @@
1
1
 
2
- > @prenta/cli@0.16.5 build /home/runner/work/prenta/prenta/packages/cli
2
+ > @prenta/cli@0.17.1 build /home/runner/work/prenta/prenta/packages/cli
3
3
  > tsc
4
4
 
@@ -1,35 +1,43 @@
1
1
 
2
- > @prenta/cli@0.16.5 test /home/runner/work/prenta/prenta/packages/cli
2
+ > @prenta/cli@0.17.1 test /home/runner/work/prenta/prenta/packages/cli
3
3
  > vitest run "--no-file-parallelism"
4
4
 
5
5
 
6
6
   RUN  v4.1.8 /home/runner/work/prenta/prenta/packages/cli
7
7
 
8
- ✓ src/__tests__/deployment-diagnostics.test.ts (18 tests) 232ms
9
- ✓ src/__tests__/db-sync.test.ts (13 tests) 496ms
10
- ✓ src/__tests__/seed.test.ts (10 tests) 190ms
8
+ ✓ src/__tests__/db-restore.test.ts (31 tests) 2032ms
9
+ ✓ src/__tests__/db-backup.test.ts (24 tests) 574ms
10
+ ✓ src/__tests__/deployment-diagnostics.test.ts (23 tests) 93ms
11
+ ✓ src/__tests__/backup-blob-store.test.ts (18 tests) 299ms
12
+ ✓ src/__tests__/backup-pg-tools.test.ts (23 tests) 173ms
13
+ ✓ src/__tests__/db-sync.test.ts (13 tests) 503ms
14
+ ↓ src/__tests__/integration/backup-roundtrip.int.test.ts (1 test | 1 skipped)
15
+ ✓ src/__tests__/backup-crypto.test.ts (13 tests) 567ms
16
+ ✓ src/__tests__/seed.test.ts (10 tests) 158ms
17
+ ✓ src/__tests__/backup-manifest.test.ts (16 tests) 102ms
11
18
  - Reading canonical Prenta schema...
19
+ ✔ Prenta CMS models added to schema.
20
+ - Running prisma generate...
12
21
  stdout | src/__tests__/db-init.test.ts > db:init (WS-D D5 — canonical schema, no stale fragment) > command > injects canonical models with @@map and no duplicate datasource/generator
13
22
  ✔ Prisma client generated.
14
23
  ℹ Run `npx prisma migrate dev --name prenta-cms` to create the migration.
15
- ✔ Prenta CMS models added to schema.
16
24
 
17
- - Running prisma generate...
25
+ - Reading canonical Prenta schema...
18
26
  stdout | src/__tests__/db-init.test.ts > db:init (WS-D D5 — canonical schema, no stale fragment) > command > fails clearly when cms-core cannot be located
19
27
  ℹ Install it first: `npm install @prenta/core`.
20
- - Reading canonical Prenta schema...
21
28
 
22
29
  ✖ Could not locate @prenta/core.
23
30
  - Reading canonical Prenta schema...
31
+ ✔ Prenta CMS models added to schema.
32
+ - Running prisma generate...
24
33
  stdout | src/__tests__/db-init.test.ts > db:init (WS-D D5 — canonical schema, no stale fragment) > command > is idempotent without --force
25
34
  ✔ Prisma client generated.
26
35
  ℹ Run `npx prisma migrate dev --name prenta-cms` to create the migration.
27
36
 
28
- ✔ Prenta CMS models added to schema.
29
- - Running prisma generate...
30
37
  - Reading canonical Prenta schema...
31
38
  ℹ Prenta CMS models already present in schema. Use --force to overwrite.
32
- ✓ src/__tests__/db-init.test.ts (4 tests) 348ms
39
+ ✓ src/__tests__/db-init.test.ts (4 tests) 281ms
40
+ ✓ src/__tests__/backup-common.test.ts (10 tests) 63ms
33
41
  stdout | src/__tests__/mcp-init.test.ts > mcp:init > creates both editor configs with placeholder key and git-ignores them
34
42
  ✔ Created .cursor/mcp.json
35
43
 
@@ -158,27 +166,28 @@ Next steps
158
166
  3. Restart Cursor / VS Code so the MCP server is picked up
159
167
  Tip: pass --url https://your-site.com to target a deployed CMS instead.
160
168
 
161
- ✓ src/__tests__/mcp-init.test.ts (6 tests) 445ms
162
- ✓ src/__tests__/prisma-client-path.test.ts (8 tests) 111ms
163
- ✓ src/__tests__/form-seed.test.ts (10 tests) 81ms
164
- ✓ src/__tests__/vercel-env-matrix.test.ts (6 tests) 61ms
165
- ✓ src/__tests__/upgrade.test.ts (3 tests) 105ms
166
- ✓ src/__tests__/load-dotenv.test.ts (3 tests) 94ms
169
+ ✓ src/__tests__/mcp-init.test.ts (6 tests) 596ms
170
+ ✓ src/__tests__/prisma-client-path.test.ts (8 tests) 93ms
171
+ ✓ src/__tests__/form-seed.test.ts (10 tests) 99ms
172
+ ✓ src/__tests__/vercel-env-matrix.test.ts (6 tests) 83ms
173
+ ✓ src/__tests__/upgrade.test.ts (3 tests) 86ms
174
+ ✓ src/__tests__/repo-root.test.ts (4 tests) 122ms
175
+ ✓ src/__tests__/load-dotenv.test.ts (3 tests) 112ms
167
176
  - Reading canonical Prenta schema...
168
- ✔ Prenta CMS models added to schema.
169
- - Running prisma generate...
170
177
  stdout | src/__tests__/schema-fragment.test.ts > db:init schema fragment > injects all deploy-critical Prenta models
171
178
  ✔ Prisma client generated.
179
+ ✔ Prenta CMS models added to schema.
180
+ - Running prisma generate...
172
181
  ℹ Run `npx prisma migrate dev --name prenta-cms` to create the migration.
173
182
 
174
- ✓ src/__tests__/schema-fragment.test.ts (1 test) 211ms
175
- ✓ src/__tests__/db-sync-resolver.test.ts (4 tests) 24ms
176
- ✓ src/__tests__/import-typescript.test.ts (3 tests) 537ms
177
- ✓ loads a TypeScript file that imports a sibling without appending ?namespace=  494ms
178
- ✓ src/__tests__/init.test.ts (2 tests) 65ms
183
+ ✓ src/__tests__/schema-fragment.test.ts (1 test) 229ms
184
+ ✓ src/__tests__/db-sync-resolver.test.ts (4 tests) 31ms
185
+ ✓ src/__tests__/import-typescript.test.ts (3 tests) 354ms
186
+ ✓ loads a TypeScript file that imports a sibling without appending ?namespace=  332ms
187
+ ✓ src/__tests__/init.test.ts (2 tests) 74ms
179
188
 
180
-  Test Files  14 passed (14)
181
-  Tests  91 passed (91)
182
-  Start at  16:28:07
183
-  Duration  31.67s (transform 3.05s, setup 0ms, import 7.97s, tests 3.00s, environment 17ms)
189
+  Test Files  22 passed | 1 skipped (23)
190
+  Tests  235 passed | 1 skipped (236)
191
+  Start at  19:42:21
192
+  Duration  41.89s (transform 3.43s, setup 0ms, import 9.39s, tests 6.72s, environment 21ms)
184
193
 
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # @actuate-media/cli
2
2
 
3
+ ## 0.17.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 1b6db92: `prenta db:backup` / `db:restore` trim surrounding whitespace from `DIRECT_DATABASE_URL` / `DATABASE_URL` before use. A connection string pasted into Vercel or GitHub with a trailing newline reached `pg_dump` as `sslmode=require\r\n` and failed with "invalid sslmode value" on the first production run; whitespace-only values now count as unset.
8
+
9
+ ## 0.17.0
10
+
11
+ ### Minor Changes
12
+
13
+ - 8a4954e: Adds off-platform database backups (roadmap #416 / #417). `prenta db:backup` runs `pg_dump --format=custom` (PostgreSQL 17 client tools required), encrypts the dump with AES-256-GCM under a new `BACKUP_ENCRYPTION_KEY` (32-byte hex, distinct from `CMS_ENCRYPTION_KEY`), writes `<stamp>.dump.enc` + `<stamp>.manifest.json` (host/database, pg_dump version, size, sha256, per-table `pg_class.reltuples` estimates), and with `--upload` stores both privately in Vercel Blob under `backups/db/` (manifest first, so a failed dump upload never leaves an orphan dump that `--list` would offer; uploads never overwrite) and prunes pairs older than `--retention-days` (default 30, measured from the run start) — never when the upload failed. `--init-workflow` writes the nightly `.github/workflows/db-backup.yml`; `--json` prints a summary object; exit codes are 0 ok, 1 dump/upload failed, 2 preconditions. `prenta db:restore <source> --target <url>` restores a local file, a Blob pathname or `latest` (`--list` shows what is available): it verifies the manifest sha256 (a Blob dump without a manifest is refused), decrypts, runs `pg_restore --clean --if-exists --single-transaction --exit-on-error` (atomic: a failure leaves the target unchanged), and prints manifest-estimate vs restored `count(*)` per table. `--target` is required, must name a database in its path, and never defaults to the env database (a password in it is accepted but warned about — prefer a password-free URL plus `PGPASSWORD`); restoring into the database named by `DIRECT_DATABASE_URL`/`DATABASE_URL` (same user, host and database name - Prisma Postgres distinguishes databases by user, so a fresh database in the same project is not "production") additionally requires `--i-understand-this-overwrites-production` and typing the database name interactively (`--yes` does not bypass it); each env URL is checked on its own, and only when neither is a parseable `postgres://` URL is the guard blind and the same flag required. Vercel Blob is reached with `BLOB_READ_WRITE_TOKEN` or, for Marketplace stores, `VERCEL_OIDC_TOKEN` + `BLOB_STORE_ID`. `@vercel/blob` (>= 2) is now an optional peer dependency of the CLI; it is only loaded when a command touches Vercel Blob. The connection URL is always passed via `--dbname` with the password moved to `PGPASSWORD`, so it never appears on argv or in captured stderr. `prenta doctor` / `deploy:check` gain a `db-backups` check that warns when `BACKUP_ENCRYPTION_KEY` is unset or the workflow file is missing from the repository root.
14
+
3
15
  ## 0.16.5
4
16
 
5
17
  ### Patch Changes
@@ -0,0 +1,89 @@
1
+ import { Readable } from 'node:stream';
2
+ import type { ReadableStream as WebReadableStream } from 'node:stream/web';
3
+ export declare const DEFAULT_BACKUP_PREFIX = "backups/db";
4
+ /** `{ token }` in read-write-token mode; `{}` when the SDK resolves OIDC auth itself. */
5
+ export interface BlobAuthOptions {
6
+ token?: string;
7
+ }
8
+ export interface BlobPutOptions extends BlobAuthOptions {
9
+ access: 'private';
10
+ addRandomSuffix: false;
11
+ contentType?: string;
12
+ multipart?: boolean;
13
+ }
14
+ export interface BlobPutResult {
15
+ url: string;
16
+ pathname: string;
17
+ }
18
+ export interface BlobListedItem {
19
+ pathname: string;
20
+ size: number;
21
+ uploadedAt: Date;
22
+ url: string;
23
+ }
24
+ export interface BlobListOptions extends BlobAuthOptions {
25
+ prefix: string;
26
+ cursor?: string;
27
+ limit?: number;
28
+ }
29
+ export interface BlobListResult {
30
+ blobs: BlobListedItem[];
31
+ cursor?: string;
32
+ hasMore: boolean;
33
+ }
34
+ export interface BlobGetResult {
35
+ statusCode: number;
36
+ stream: WebReadableStream<Uint8Array> | null;
37
+ }
38
+ /** The slice of `@vercel/blob` the backup commands use. */
39
+ export interface BlobModule {
40
+ put(pathname: string, body: Readable, options: BlobPutOptions): Promise<BlobPutResult>;
41
+ list(options: BlobListOptions): Promise<BlobListResult>;
42
+ del(urlsOrPathnames: string | string[], options: BlobAuthOptions): Promise<void>;
43
+ get(pathname: string, options: BlobAuthOptions & {
44
+ access: 'private';
45
+ }): Promise<BlobGetResult | null>;
46
+ }
47
+ export type BackupBlobKind = 'dump' | 'manifest';
48
+ export interface BackupBlob extends BlobListedItem {
49
+ stamp: string;
50
+ kind: BackupBlobKind;
51
+ }
52
+ export interface BlobStore {
53
+ readonly prefix: string;
54
+ /** Upload a local file to `<prefix>/<name>`. */
55
+ upload(localPath: string, name: string): Promise<BlobPutResult>;
56
+ /** Every backup object under the prefix, newest stamp first. */
57
+ list(): Promise<BackupBlob[]>;
58
+ /** Only the `.dump.enc` objects, newest first (restorable backups). */
59
+ dumps(): Promise<BackupBlob[]>;
60
+ /** Stream a private blob to `dest`. */
61
+ download(pathname: string, dest: string): Promise<void>;
62
+ /** Delete one object under the prefix by name (used to undo a half-uploaded pair). */
63
+ remove(name: string): Promise<void>;
64
+ /** Delete expired backup pairs. Returns the pathnames removed. */
65
+ prune(retentionDays: number, now?: Date): Promise<{
66
+ deleted: string[];
67
+ }>;
68
+ }
69
+ export interface CreateBlobStoreOptions {
70
+ /** `BLOB_READ_WRITE_TOKEN`; omit to let `@vercel/blob` resolve OIDC auth from the environment. */
71
+ token?: string;
72
+ prefix?: string;
73
+ /** Injected `@vercel/blob` (tests). Wins over `loadBlobModule`. */
74
+ blobModule?: BlobModule;
75
+ /**
76
+ * Loader for the real module; defaults to a runtime-assembled dynamic
77
+ * import. Whatever it resolves to is shape-checked by `assertBlobModule`.
78
+ */
79
+ loadBlobModule?: () => Promise<unknown>;
80
+ }
81
+ /**
82
+ * Narrow an arbitrary loaded module to the `BlobModule` slice. `get()` is
83
+ * the >= 2 marker: private blobs (which backups require) cannot be read
84
+ * without it, so an older install fails here with a version message rather
85
+ * than later with "get is not a function".
86
+ */
87
+ export declare function assertBlobModule(mod: unknown): BlobModule;
88
+ export declare function createBlobStore(options: CreateBlobStoreOptions): BlobStore;
89
+ //# sourceMappingURL=blob-store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"blob-store.d.ts","sourceRoot":"","sources":["../../src/backup/blob-store.ts"],"names":[],"mappings":"AAiCA,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAA;AAEtC,OAAO,KAAK,EAAE,cAAc,IAAI,iBAAiB,EAAE,MAAM,iBAAiB,CAAA;AAS1E,eAAO,MAAM,qBAAqB,eAAe,CAAA;AAEjD,yFAA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;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,OAAO,GAAG,UAAU,CAUzD;AAkCD,wBAAgB,eAAe,CAAC,OAAO,EAAE,sBAAsB,GAAG,SAAS,CAsG1E"}
@@ -0,0 +1,183 @@
1
+ /**
2
+ * Vercel Blob storage for encrypted database backups.
3
+ *
4
+ * Backups live under `<prefix>/<stamp>.dump.enc` + `<prefix>/<stamp>.manifest.json`
5
+ * (default prefix `backups/db`) with `access: 'private'` and no random suffix,
6
+ * so a stamp maps to exactly one pair of objects. Blob is a different vendor
7
+ * from the database and every site already has `BLOB_READ_WRITE_TOKEN`.
8
+ *
9
+ * `@vercel/blob` is an optional peer of `@prenta/cli` (>= 2, for `get()` on
10
+ * private blobs); the host project normally has it through
11
+ * `@prenta/platform-vercel`. It is loaded with a dynamic import whose
12
+ * specifier is assembled at runtime (same pattern as cms-core's
13
+ * `ai/plugin-import.ts`) so bundlers do not try to resolve it, the loaded
14
+ * module is shape-checked before use, and the module is injectable so tests
15
+ * use an in-memory fake instead.
16
+ *
17
+ * Uploads never overwrite: `put` is called without `allowOverwrite`, so a
18
+ * second upload of the same pathname (a rerun within the same second) fails
19
+ * instead of silently replacing a backup.
20
+ *
21
+ * Prune (and `list` / `latest`) only ever consider objects directly under the
22
+ * prefix whose basename is exactly `<stamp>.dump.enc` or
23
+ * `<stamp>.manifest.json` (stamp anchored to the whole basename). Anything
24
+ * else under the prefix — `old-<stamp>.dump.enc`, `sub/<stamp>.dump.enc` —
25
+ * is left alone.
26
+ *
27
+ * Auth: when `BLOB_READ_WRITE_TOKEN` is set it is passed as `token`.
28
+ * Otherwise `token` is omitted entirely so the SDK's own resolution applies
29
+ * (`VERCEL_OIDC_TOKEN` + `BLOB_STORE_ID`, the Marketplace store mode — see
30
+ * `@prenta/platform-vercel`'s `blob-auth.ts`). An explicit `token: undefined`
31
+ * would shadow that lookup, so the key must be absent, not undefined.
32
+ */
33
+ import { createReadStream, createWriteStream } from 'node:fs';
34
+ import { Readable } from 'node:stream';
35
+ import { pipeline } from 'node:stream/promises';
36
+ import { compareStamps, DUMP_EXTENSION, isOlderThan, MANIFEST_EXTENSION, parseStamp, } from './manifest.js';
37
+ export const DEFAULT_BACKUP_PREFIX = 'backups/db';
38
+ async function defaultLoadBlobModule() {
39
+ const specifier = '@vercel/' + 'blob';
40
+ return import(/* webpackIgnore: true */ /* turbopackIgnore: true */ /* @vite-ignore */ specifier);
41
+ }
42
+ const BLOB_MODULE_FUNCTIONS = ['put', 'list', 'del', 'get'];
43
+ /**
44
+ * Narrow an arbitrary loaded module to the `BlobModule` slice. `get()` is
45
+ * the >= 2 marker: private blobs (which backups require) cannot be read
46
+ * without it, so an older install fails here with a version message rather
47
+ * than later with "get is not a function".
48
+ */
49
+ export function assertBlobModule(mod) {
50
+ const record = typeof mod === 'object' && mod !== null ? mod : {};
51
+ const missing = BLOB_MODULE_FUNCTIONS.filter((name) => typeof record[name] !== 'function');
52
+ if (missing.length === 0)
53
+ return mod;
54
+ if (missing.includes('get') && missing.length === 1) {
55
+ throw new Error('@prenta/cli db:backup requires @vercel/blob >= 2 (private blobs).');
56
+ }
57
+ throw new Error(`The loaded @vercel/blob module is missing ${missing.join(', ')}; @prenta/cli db:backup requires @vercel/blob >= 2.`);
58
+ }
59
+ function isModuleNotFound(err) {
60
+ if (!(err instanceof Error))
61
+ return false;
62
+ const code = err.code;
63
+ return code === 'ERR_MODULE_NOT_FOUND' || code === 'MODULE_NOT_FOUND';
64
+ }
65
+ /**
66
+ * Classify a basename that is exactly `<stamp>.dump.enc` or
67
+ * `<stamp>.manifest.json`; anything else (`old-<stamp>.dump.enc`,
68
+ * `<stamp>.dump.enc.bak`) is not ours.
69
+ */
70
+ function classifyBasename(basename) {
71
+ const kind = basename.endsWith(DUMP_EXTENSION)
72
+ ? 'dump'
73
+ : basename.endsWith(MANIFEST_EXTENSION)
74
+ ? 'manifest'
75
+ : null;
76
+ if (!kind)
77
+ return null;
78
+ const extension = kind === 'dump' ? DUMP_EXTENSION : MANIFEST_EXTENSION;
79
+ const stem = basename.slice(0, -extension.length);
80
+ const stamp = parseStamp(stem);
81
+ // `parseStamp` searches for a stamp inside the string; require the stem to be nothing else.
82
+ if (stamp === null || stamp !== stem)
83
+ return null;
84
+ return { stamp, kind };
85
+ }
86
+ function contentTypeFor(name) {
87
+ return name.endsWith(MANIFEST_EXTENSION) ? 'application/json' : 'application/octet-stream';
88
+ }
89
+ const DEL_BATCH_SIZE = 100;
90
+ export function createBlobStore(options) {
91
+ // Spread into every SDK call: `{ token }` or `{}` — never `{ token: undefined }`.
92
+ const auth = options.token ? { token: options.token } : {};
93
+ const prefix = (options.prefix ?? DEFAULT_BACKUP_PREFIX).replace(/^\/+|\/+$/g, '');
94
+ const load = options.loadBlobModule ?? defaultLoadBlobModule;
95
+ let modulePromise = options.blobModule
96
+ ? Promise.resolve(options.blobModule)
97
+ : null;
98
+ async function blob() {
99
+ if (!modulePromise) {
100
+ modulePromise = load()
101
+ .then(assertBlobModule)
102
+ .catch((err) => {
103
+ modulePromise = null;
104
+ if (isModuleNotFound(err)) {
105
+ throw new Error('@vercel/blob is not installed. Backups upload through Vercel Blob; install it in the project (`pnpm add @vercel/blob`, or via @prenta/platform-vercel) and re-run.');
106
+ }
107
+ throw err;
108
+ });
109
+ }
110
+ return modulePromise;
111
+ }
112
+ /** `<prefix>/<stamp>.dump.enc` | `<prefix>/<stamp>.manifest.json`, exactly — else null. */
113
+ const classify = (pathname) => {
114
+ if (!pathname.startsWith(`${prefix}/`))
115
+ return null;
116
+ const basename = pathname.slice(prefix.length + 1);
117
+ if (basename.includes('/'))
118
+ return null;
119
+ return classifyBasename(basename);
120
+ };
121
+ async function list() {
122
+ const mod = await blob();
123
+ const items = [];
124
+ let cursor;
125
+ do {
126
+ const page = await mod.list({ prefix: `${prefix}/`, cursor, limit: 1000, ...auth });
127
+ for (const item of page.blobs) {
128
+ const ours = classify(item.pathname);
129
+ if (!ours)
130
+ continue;
131
+ items.push({ ...item, stamp: ours.stamp, kind: ours.kind });
132
+ }
133
+ cursor = page.hasMore ? page.cursor : undefined;
134
+ } while (cursor);
135
+ // Newest first; the dump sorts before its manifest for the same stamp.
136
+ return items.sort((a, b) => compareStamps(b.stamp, a.stamp) || (a.kind === b.kind ? 0 : a.kind === 'dump' ? -1 : 1));
137
+ }
138
+ return {
139
+ prefix,
140
+ async upload(localPath, name) {
141
+ const mod = await blob();
142
+ const pathname = `${prefix}/${name}`;
143
+ return mod.put(pathname, createReadStream(localPath), {
144
+ access: 'private',
145
+ addRandomSuffix: false,
146
+ contentType: contentTypeFor(name),
147
+ multipart: true,
148
+ ...auth,
149
+ });
150
+ },
151
+ list,
152
+ async dumps() {
153
+ return (await list()).filter((item) => item.kind === 'dump');
154
+ },
155
+ async download(pathname, dest) {
156
+ const mod = await blob();
157
+ const result = await mod.get(pathname, { access: 'private', ...auth });
158
+ if (!result || !result.stream) {
159
+ throw new Error(`Backup ${pathname} was not found in Vercel Blob.`);
160
+ }
161
+ await pipeline(Readable.fromWeb(result.stream), createWriteStream(dest));
162
+ },
163
+ async remove(name) {
164
+ const mod = await blob();
165
+ await mod.del(`${prefix}/${name}`, { ...auth });
166
+ },
167
+ async prune(retentionDays, now = new Date()) {
168
+ if (!Number.isFinite(retentionDays) || retentionDays <= 0)
169
+ return { deleted: [] };
170
+ const expired = (await list())
171
+ .filter((item) => isOlderThan(item.stamp, retentionDays, now))
172
+ .map((item) => item.pathname);
173
+ if (expired.length === 0)
174
+ return { deleted: [] };
175
+ const mod = await blob();
176
+ for (let i = 0; i < expired.length; i += DEL_BATCH_SIZE) {
177
+ await mod.del(expired.slice(i, i + DEL_BATCH_SIZE), { ...auth });
178
+ }
179
+ return { deleted: expired };
180
+ },
181
+ };
182
+ }
183
+ //# sourceMappingURL=blob-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"blob-store.js","sourceRoot":"","sources":["../../src/backup/blob-store.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;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GAAG,IAAI,IAAI,EAAE;YACzC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,aAAa,CAAC,IAAI,aAAa,IAAI,CAAC;gBAAE,OAAO,EAAE,OAAO,EAAE,EAAE,EAAE,CAAA;YACjF,MAAM,OAAO,GAAG,CAAC,MAAM,IAAI,EAAE,CAAC;iBAC3B,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,WAAW,CAAC,IAAI,CAAC,KAAK,EAAE,aAAa,EAAE,GAAG,CAAC,CAAC;iBAC7D,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAA;YAC/B,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;gBAAE,OAAO,EAAE,OAAO,EAAE,EAAE,EAAE,CAAA;YAChD,MAAM,GAAG,GAAG,MAAM,IAAI,EAAE,CAAA;YACxB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,IAAI,cAAc,EAAE,CAAC;gBACxD,MAAM,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,GAAG,cAAc,CAAC,EAAE,EAAE,GAAG,IAAI,EAAE,CAAC,CAAA;YAClE,CAAC;YACD,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAA;QAC7B,CAAC;KACF,CAAA;AACH,CAAC"}
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Small pure helpers shared by `db:backup` and `db:restore`: env resolution,
3
+ * local-host detection, same-database comparison and human formatting.
4
+ */
5
+ /** Shared exit codes: 0 ok · 1 the operation failed · 2 preconditions (tools, env, safety). */
6
+ export declare const EXIT_OK = 0;
7
+ export declare const EXIT_FAILED = 1;
8
+ export declare const EXIT_PRECONDITION = 2;
9
+ export interface ResolvedDatabaseUrl {
10
+ url: string;
11
+ source: 'DIRECT_DATABASE_URL' | 'DATABASE_URL';
12
+ }
13
+ /**
14
+ * `DIRECT_DATABASE_URL` first (non-pooled), else `DATABASE_URL`. Values are
15
+ * trimmed: secrets pasted into Vercel / GitHub with a trailing newline reach
16
+ * `pg_dump` as `sslmode=require\r\n` and fail with "invalid sslmode value"
17
+ * (seen on the first production run). Whitespace-only counts as unset.
18
+ */
19
+ export declare function resolveDatabaseUrl(env: NodeJS.ProcessEnv): ResolvedDatabaseUrl | null;
20
+ /**
21
+ * How the CLI can authenticate to Vercel Blob. `{ token }` when
22
+ * `BLOB_READ_WRITE_TOKEN` is set; `{}` when only the Marketplace OIDC pair
23
+ * (`VERCEL_OIDC_TOKEN` + `BLOB_STORE_ID`) is present, in which case
24
+ * `@vercel/blob` resolves the credentials from the environment itself and
25
+ * the CLI must not pass `token` at all. `null` when neither mode is available.
26
+ * Mirrors `resolveBlobClientAuthOptions` in `@prenta/platform-vercel`.
27
+ */
28
+ export declare function resolveBlobAuth(env: NodeJS.ProcessEnv): {
29
+ token?: string;
30
+ } | null;
31
+ /** Names both Blob auth modes, for precondition errors. */
32
+ export declare const BLOB_AUTH_HINT = "BLOB_READ_WRITE_TOKEN (Vercel Blob read-write token), or VERCEL_OIDC_TOKEN together with BLOB_STORE_ID (Marketplace Blob store on Vercel)";
33
+ /** True for URLs pointing at the developer's own machine. */
34
+ export declare function isLocalDatabaseUrl(url: string): boolean;
35
+ /**
36
+ * What identifies "one database" for the production guard.
37
+ *
38
+ * Prisma Postgres direct URLs are `postgres://USER:PASSWORD@db.prisma.io:5432/postgres`
39
+ * for every database in a project — the username is the per-database
40
+ * discriminator, so host + database name alone would call a fresh scratch
41
+ * database "production". Host is lowercased with a leading `pooled.` label
42
+ * stripped (pooled and direct strings of one database compare equal); the
43
+ * database path loses trailing slashes and an empty path means `postgres`
44
+ * (libpq's default). Password, port and query string are ignored.
45
+ */
46
+ export interface DatabaseIdentity {
47
+ user: string;
48
+ host: string;
49
+ name: string;
50
+ }
51
+ /**
52
+ * The database a URL path names, normalized the way libpq resolves it:
53
+ * surrounding slashes stripped, percent-escapes decoded, and an empty path
54
+ * meaning `postgres`. Every place that shows or compares a database name
55
+ * (the production guard, the typed confirmation, the manifest) must use this
56
+ * so they agree.
57
+ */
58
+ export declare function normalizeDatabaseName(pathname: string): string;
59
+ /** True when the URL path names a database explicitly (`/db`), not `` or `/`. */
60
+ export declare function namesDatabase(url: string): boolean;
61
+ /** `DatabaseIdentity` for a parseable postgres:// URL, else `null`. */
62
+ export declare function databaseIdentity(url: string): DatabaseIdentity | null;
63
+ /**
64
+ * True when both URLs name the same database (see `DatabaseIdentity`).
65
+ * Unparseable input is never "the same" — callers that need to know whether
66
+ * the comparison was possible at all use `databaseIdentity` directly.
67
+ */
68
+ export declare function isSameDatabase(a: string, b: string): boolean;
69
+ /** Validate a connection URL is parseable and uses a postgres scheme. */
70
+ export declare function isPostgresUrl(url: string): boolean;
71
+ export declare function formatBytes(bytes: number): string;
72
+ export declare function formatDuration(ms: number): string;
73
+ //# sourceMappingURL=common.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"common.d.ts","sourceRoot":"","sources":["../../src/backup/common.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,+FAA+F;AAC/F,eAAO,MAAM,OAAO,IAAI,CAAA;AACxB,eAAO,MAAM,WAAW,IAAI,CAAA;AAC5B,eAAO,MAAM,iBAAiB,IAAI,CAAA;AAElC,MAAM,WAAW,mBAAmB;IAClC,GAAG,EAAE,MAAM,CAAA;IACX,MAAM,EAAE,qBAAqB,GAAG,cAAc,CAAA;CAC/C;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,CAAC,UAAU,GAAG,mBAAmB,GAAG,IAAI,CAMrF;AAED;;;;;;;GAOG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,CAAC,UAAU,GAAG;IAAE,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAKjF;AAED,2DAA2D;AAC3D,eAAO,MAAM,cAAc,8IACkH,CAAA;AAI7I,6DAA6D;AAC7D,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAMvD;AAED;;;;;;;;;;GAUG;AACH,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,MAAM,CAAA;CACb;AAUD;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAG9D;AAED,iFAAiF;AACjF,wBAAgB,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAMlD;AAED,uEAAuE;AACvE,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,GAAG,gBAAgB,GAAG,IAAI,CAQrE;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,OAAO,CAK5D;AAED,yEAAyE;AACzE,wBAAgB,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CASlD;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAUjD;AAED,wBAAgB,cAAc,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,CAMjD"}
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Small pure helpers shared by `db:backup` and `db:restore`: env resolution,
3
+ * local-host detection, same-database comparison and human formatting.
4
+ */
5
+ /** Shared exit codes: 0 ok · 1 the operation failed · 2 preconditions (tools, env, safety). */
6
+ export const EXIT_OK = 0;
7
+ export const EXIT_FAILED = 1;
8
+ export const EXIT_PRECONDITION = 2;
9
+ /**
10
+ * `DIRECT_DATABASE_URL` first (non-pooled), else `DATABASE_URL`. Values are
11
+ * trimmed: secrets pasted into Vercel / GitHub with a trailing newline reach
12
+ * `pg_dump` as `sslmode=require\r\n` and fail with "invalid sslmode value"
13
+ * (seen on the first production run). Whitespace-only counts as unset.
14
+ */
15
+ export function resolveDatabaseUrl(env) {
16
+ const direct = env.DIRECT_DATABASE_URL?.trim();
17
+ if (direct)
18
+ return { url: direct, source: 'DIRECT_DATABASE_URL' };
19
+ const pooled = env.DATABASE_URL?.trim();
20
+ if (pooled)
21
+ return { url: pooled, source: 'DATABASE_URL' };
22
+ return null;
23
+ }
24
+ /**
25
+ * How the CLI can authenticate to Vercel Blob. `{ token }` when
26
+ * `BLOB_READ_WRITE_TOKEN` is set; `{}` when only the Marketplace OIDC pair
27
+ * (`VERCEL_OIDC_TOKEN` + `BLOB_STORE_ID`) is present, in which case
28
+ * `@vercel/blob` resolves the credentials from the environment itself and
29
+ * the CLI must not pass `token` at all. `null` when neither mode is available.
30
+ * Mirrors `resolveBlobClientAuthOptions` in `@prenta/platform-vercel`.
31
+ */
32
+ export function resolveBlobAuth(env) {
33
+ const token = env.BLOB_READ_WRITE_TOKEN?.trim();
34
+ if (token)
35
+ return { token };
36
+ if (env.VERCEL_OIDC_TOKEN?.trim() && env.BLOB_STORE_ID?.trim())
37
+ return {};
38
+ return null;
39
+ }
40
+ /** Names both Blob auth modes, for precondition errors. */
41
+ export const BLOB_AUTH_HINT = 'BLOB_READ_WRITE_TOKEN (Vercel Blob read-write token), or VERCEL_OIDC_TOKEN together with BLOB_STORE_ID (Marketplace Blob store on Vercel)';
42
+ const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '[::1]']);
43
+ /** True for URLs pointing at the developer's own machine. */
44
+ export function isLocalDatabaseUrl(url) {
45
+ try {
46
+ return LOCAL_HOSTS.has(new URL(url).hostname.toLowerCase());
47
+ }
48
+ catch {
49
+ return false;
50
+ }
51
+ }
52
+ function safeDecode(value) {
53
+ try {
54
+ return decodeURIComponent(value);
55
+ }
56
+ catch {
57
+ return value;
58
+ }
59
+ }
60
+ /**
61
+ * The database a URL path names, normalized the way libpq resolves it:
62
+ * surrounding slashes stripped, percent-escapes decoded, and an empty path
63
+ * meaning `postgres`. Every place that shows or compares a database name
64
+ * (the production guard, the typed confirmation, the manifest) must use this
65
+ * so they agree.
66
+ */
67
+ export function normalizeDatabaseName(pathname) {
68
+ const path = safeDecode(pathname.replace(/^\/+|\/+$/g, ''));
69
+ return path === '' ? 'postgres' : path;
70
+ }
71
+ /** True when the URL path names a database explicitly (`/db`), not `` or `/`. */
72
+ export function namesDatabase(url) {
73
+ try {
74
+ return new URL(url).pathname.replace(/^\/+|\/+$/g, '') !== '';
75
+ }
76
+ catch {
77
+ return false;
78
+ }
79
+ }
80
+ /** `DatabaseIdentity` for a parseable postgres:// URL, else `null`. */
81
+ export function databaseIdentity(url) {
82
+ if (!isPostgresUrl(url))
83
+ return null;
84
+ const parsed = new URL(url);
85
+ return {
86
+ user: safeDecode(parsed.username),
87
+ host: parsed.hostname.toLowerCase().replace(/^pooled\./, ''),
88
+ name: normalizeDatabaseName(parsed.pathname),
89
+ };
90
+ }
91
+ /**
92
+ * True when both URLs name the same database (see `DatabaseIdentity`).
93
+ * Unparseable input is never "the same" — callers that need to know whether
94
+ * the comparison was possible at all use `databaseIdentity` directly.
95
+ */
96
+ export function isSameDatabase(a, b) {
97
+ const da = databaseIdentity(a);
98
+ const db = databaseIdentity(b);
99
+ if (!da || !db)
100
+ return false;
101
+ return da.user === db.user && da.host === db.host && da.name === db.name;
102
+ }
103
+ /** Validate a connection URL is parseable and uses a postgres scheme. */
104
+ export function isPostgresUrl(url) {
105
+ try {
106
+ const parsed = new URL(url);
107
+ return ((parsed.protocol === 'postgres:' || parsed.protocol === 'postgresql:') && !!parsed.hostname);
108
+ }
109
+ catch {
110
+ return false;
111
+ }
112
+ }
113
+ export function formatBytes(bytes) {
114
+ if (bytes < 1024)
115
+ return `${bytes} B`;
116
+ const units = ['KB', 'MB', 'GB', 'TB'];
117
+ let value = bytes / 1024;
118
+ let unit = 0;
119
+ while (value >= 1024 && unit < units.length - 1) {
120
+ value /= 1024;
121
+ unit++;
122
+ }
123
+ return `${value.toFixed(value >= 100 ? 0 : 1)} ${units[unit]}`;
124
+ }
125
+ export function formatDuration(ms) {
126
+ if (ms < 1000)
127
+ return `${Math.round(ms)}ms`;
128
+ const seconds = ms / 1000;
129
+ if (seconds < 60)
130
+ return `${seconds.toFixed(1)}s`;
131
+ const minutes = Math.floor(seconds / 60);
132
+ return `${minutes}m ${Math.round(seconds - minutes * 60)}s`;
133
+ }
134
+ //# sourceMappingURL=common.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"common.js","sourceRoot":"","sources":["../../src/backup/common.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,+FAA+F;AAC/F,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,CAAA;AACxB,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,CAAA;AAC5B,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,CAAA;AAOlC;;;;;GAKG;AACH,MAAM,UAAU,kBAAkB,CAAC,GAAsB;IACvD,MAAM,MAAM,GAAG,GAAG,CAAC,mBAAmB,EAAE,IAAI,EAAE,CAAA;IAC9C,IAAI,MAAM;QAAE,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,qBAAqB,EAAE,CAAA;IACjE,MAAM,MAAM,GAAG,GAAG,CAAC,YAAY,EAAE,IAAI,EAAE,CAAA;IACvC,IAAI,MAAM;QAAE,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,cAAc,EAAE,CAAA;IAC1D,OAAO,IAAI,CAAA;AACb,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,eAAe,CAAC,GAAsB;IACpD,MAAM,KAAK,GAAG,GAAG,CAAC,qBAAqB,EAAE,IAAI,EAAE,CAAA;IAC/C,IAAI,KAAK;QAAE,OAAO,EAAE,KAAK,EAAE,CAAA;IAC3B,IAAI,GAAG,CAAC,iBAAiB,EAAE,IAAI,EAAE,IAAI,GAAG,CAAC,aAAa,EAAE,IAAI,EAAE;QAAE,OAAO,EAAE,CAAA;IACzE,OAAO,IAAI,CAAA;AACb,CAAC;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