@prenta/cli 0.16.4 → 0.17.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.
Files changed (74) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +31 -21
  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 +68 -0
  9. package/dist/backup/common.d.ts.map +1 -0
  10. package/dist/backup/common.js +127 -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 +30 -1
  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 +103 -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 +56 -1
  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 +153 -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 +45 -1
  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.4 build /home/runner/work/prenta/prenta/packages/cli
2
+ > @prenta/cli@0.17.0 build /home/runner/work/prenta/prenta/packages/cli
3
3
  > tsc
4
4
 
@@ -1,13 +1,20 @@
1
1
 
2
- > @prenta/cli@0.16.4 test /home/runner/work/prenta/prenta/packages/cli
2
+ > @prenta/cli@0.17.0 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) 146ms
9
- ✓ src/__tests__/db-sync.test.ts (13 tests) 580ms
10
- ✓ src/__tests__/seed.test.ts (10 tests) 186ms
8
+ ✓ src/__tests__/db-restore.test.ts (31 tests) 1888ms
9
+ ✓ src/__tests__/db-backup.test.ts (24 tests) 1153ms
10
+ ✓ src/__tests__/deployment-diagnostics.test.ts (23 tests) 147ms
11
+ ✓ src/__tests__/backup-blob-store.test.ts (18 tests) 567ms
12
+ ✓ src/__tests__/backup-pg-tools.test.ts (23 tests) 334ms
13
+ ✓ src/__tests__/db-sync.test.ts (13 tests) 711ms
14
+ ↓ src/__tests__/integration/backup-roundtrip.int.test.ts (1 test | 1 skipped)
15
+ ✓ src/__tests__/backup-crypto.test.ts (13 tests) 852ms
16
+ ✓ src/__tests__/seed.test.ts (10 tests) 181ms
17
+ ✓ src/__tests__/backup-manifest.test.ts (16 tests) 191ms
11
18
  - Reading canonical Prenta schema...
12
19
  ✔ Prenta CMS models added to schema.
13
20
  - Running prisma generate...
@@ -17,19 +24,19 @@
17
24
 
18
25
  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
26
  ℹ Install it first: `npm install @prenta/core`.
20
-
21
27
  - Reading canonical Prenta schema...
28
+
22
29
  ✖ Could not locate @prenta/core.
23
30
  - Reading canonical Prenta schema...
24
31
  ✔ Prenta CMS models added to schema.
25
- - Running prisma generate...
26
32
  stdout | src/__tests__/db-init.test.ts > db:init (WS-D D5 — canonical schema, no stale fragment) > command > is idempotent without --force
27
33
  ✔ Prisma client generated.
28
34
  ℹ Run `npx prisma migrate dev --name prenta-cms` to create the migration.
35
+ - Running prisma generate...
29
36
 
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) 222ms
39
+ ✓ src/__tests__/db-init.test.ts (4 tests) 461ms
33
40
  stdout | src/__tests__/mcp-init.test.ts > mcp:init > creates both editor configs with placeholder key and git-ignores them
34
41
  ✔ Created .cursor/mcp.json
35
42
 
@@ -158,12 +165,14 @@ Next steps
158
165
  3. Restart Cursor / VS Code so the MCP server is picked up
159
166
  Tip: pass --url https://your-site.com to target a deployed CMS instead.
160
167
 
161
- ✓ src/__tests__/mcp-init.test.ts (6 tests) 363ms
162
- ✓ src/__tests__/prisma-client-path.test.ts (8 tests) 44ms
163
- ✓ src/__tests__/form-seed.test.ts (10 tests) 41ms
164
- ✓ src/__tests__/vercel-env-matrix.test.ts (6 tests) 66ms
165
- ✓ src/__tests__/upgrade.test.ts (3 tests) 42ms
166
- ✓ src/__tests__/load-dotenv.test.ts (3 tests) 48ms
168
+ ✓ src/__tests__/mcp-init.test.ts (6 tests) 791ms
169
+ ✓ src/__tests__/prisma-client-path.test.ts (8 tests) 207ms
170
+ ✓ src/__tests__/backup-common.test.ts (8 tests) 84ms
171
+ ✓ src/__tests__/form-seed.test.ts (10 tests) 86ms
172
+ ✓ src/__tests__/vercel-env-matrix.test.ts (6 tests) 69ms
173
+ ✓ src/__tests__/upgrade.test.ts (3 tests) 48ms
174
+ ✓ src/__tests__/repo-root.test.ts (4 tests) 170ms
175
+ ✓ src/__tests__/load-dotenv.test.ts (3 tests) 114ms
167
176
  - Reading canonical Prenta schema...
168
177
  ✔ Prenta CMS models added to schema.
169
178
  - Running prisma generate...
@@ -171,13 +180,14 @@ Next steps
171
180
  ✔ Prisma client generated.
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) 124ms
175
- ✓ src/__tests__/db-sync-resolver.test.ts (4 tests) 26ms
176
- ✓ src/__tests__/import-typescript.test.ts (3 tests) 298ms
177
- ✓ src/__tests__/init.test.ts (2 tests) 40ms
183
+ ✓ src/__tests__/schema-fragment.test.ts (1 test) 247ms
184
+ ✓ src/__tests__/db-sync-resolver.test.ts (4 tests) 23ms
185
+ ✓ src/__tests__/import-typescript.test.ts (3 tests) 379ms
186
+ ✓ loads a TypeScript file that imports a sibling without appending ?namespace=  349ms
187
+ ✓ src/__tests__/init.test.ts (2 tests) 79ms
178
188
 
179
-  Test Files  14 passed (14)
180
-  Tests  91 passed (91)
181
-  Start at  07:28:36
182
-  Duration  21.78s (transform 2.39s, setup 0ms, import 5.90s, tests 2.23s, environment 15ms)
189
+  Test Files  22 passed | 1 skipped (23)
190
+  Tests  233 passed | 1 skipped (234)
191
+  Start at  18:45:03
192
+  Duration  53.68s (transform 4.94s, setup 0ms, import 12.16s, tests 8.78s, environment 64ms)
183
193
 
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # @actuate-media/cli
2
2
 
3
+ ## 0.17.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 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.
8
+
9
+ ## 0.16.5
10
+
11
+ ### Patch Changes
12
+
13
+ - 6db4f47: Retire the stale design-owned-era deprecation of structural section editing. ADR 0003 made the section endpoints the canonical programmatic authoring path (the visual stack), but `POST /page-sections` add/reorder and `DELETE` still returned RFC 8594 `Deprecation` headers, and the MCP `add_page_section` / `reorder_page_sections` / `remove_page_section` descriptions still opened with "DEPRECATED — removed in the next major" and pointed agents at the deleted page builder. The headers are removed, the tool descriptions now describe the visual-stack workflow, and the CLI's section-fit diagnostic links to the current Connecting Designed Frontends guide instead of the retired page-builder doc.
14
+
3
15
  ## 0.16.4
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,yFAAyF;AACzF,MAAM,WAAW,eAAe;IAC9B,KAAK,CAAC,EAAE,MAAM,CAAA;CACf;AAED,MAAM,WAAW,cAAe,SAAQ,eAAe;IACrD,MAAM,EAAE,SAAS,CAAA;IACjB,eAAe,EAAE,KAAK,CAAA;IACtB,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,SAAS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
+ * 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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAA;AAC7D,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAA;AACtC,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAA;AAE/C,OAAO,EACL,aAAa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B,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,68 @@
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
+ /** `DIRECT_DATABASE_URL` first (non-pooled), else `DATABASE_URL`. */
14
+ export declare function resolveDatabaseUrl(env: NodeJS.ProcessEnv): ResolvedDatabaseUrl | null;
15
+ /**
16
+ * How the CLI can authenticate to Vercel Blob. `{ token }` when
17
+ * `BLOB_READ_WRITE_TOKEN` is set; `{}` when only the Marketplace OIDC pair
18
+ * (`VERCEL_OIDC_TOKEN` + `BLOB_STORE_ID`) is present, in which case
19
+ * `@vercel/blob` resolves the credentials from the environment itself and
20
+ * the CLI must not pass `token` at all. `null` when neither mode is available.
21
+ * Mirrors `resolveBlobClientAuthOptions` in `@prenta/platform-vercel`.
22
+ */
23
+ export declare function resolveBlobAuth(env: NodeJS.ProcessEnv): {
24
+ token?: string;
25
+ } | null;
26
+ /** Names both Blob auth modes, for precondition errors. */
27
+ 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)";
28
+ /** True for URLs pointing at the developer's own machine. */
29
+ export declare function isLocalDatabaseUrl(url: string): boolean;
30
+ /**
31
+ * What identifies "one database" for the production guard.
32
+ *
33
+ * Prisma Postgres direct URLs are `postgres://USER:PASSWORD@db.prisma.io:5432/postgres`
34
+ * for every database in a project — the username is the per-database
35
+ * discriminator, so host + database name alone would call a fresh scratch
36
+ * database "production". Host is lowercased with a leading `pooled.` label
37
+ * stripped (pooled and direct strings of one database compare equal); the
38
+ * database path loses trailing slashes and an empty path means `postgres`
39
+ * (libpq's default). Password, port and query string are ignored.
40
+ */
41
+ export interface DatabaseIdentity {
42
+ user: string;
43
+ host: string;
44
+ name: string;
45
+ }
46
+ /**
47
+ * The database a URL path names, normalized the way libpq resolves it:
48
+ * surrounding slashes stripped, percent-escapes decoded, and an empty path
49
+ * meaning `postgres`. Every place that shows or compares a database name
50
+ * (the production guard, the typed confirmation, the manifest) must use this
51
+ * so they agree.
52
+ */
53
+ export declare function normalizeDatabaseName(pathname: string): string;
54
+ /** True when the URL path names a database explicitly (`/db`), not `` or `/`. */
55
+ export declare function namesDatabase(url: string): boolean;
56
+ /** `DatabaseIdentity` for a parseable postgres:// URL, else `null`. */
57
+ export declare function databaseIdentity(url: string): DatabaseIdentity | null;
58
+ /**
59
+ * True when both URLs name the same database (see `DatabaseIdentity`).
60
+ * Unparseable input is never "the same" — callers that need to know whether
61
+ * the comparison was possible at all use `databaseIdentity` directly.
62
+ */
63
+ export declare function isSameDatabase(a: string, b: string): boolean;
64
+ /** Validate a connection URL is parseable and uses a postgres scheme. */
65
+ export declare function isPostgresUrl(url: string): boolean;
66
+ export declare function formatBytes(bytes: number): string;
67
+ export declare function formatDuration(ms: number): string;
68
+ //# 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,qEAAqE;AACrE,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,CAAC,UAAU,GAAG,mBAAmB,GAAG,IAAI,CAKrF;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,127 @@
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
+ /** `DIRECT_DATABASE_URL` first (non-pooled), else `DATABASE_URL`. */
10
+ export function resolveDatabaseUrl(env) {
11
+ if (env.DIRECT_DATABASE_URL)
12
+ return { url: env.DIRECT_DATABASE_URL, source: 'DIRECT_DATABASE_URL' };
13
+ if (env.DATABASE_URL)
14
+ return { url: env.DATABASE_URL, source: 'DATABASE_URL' };
15
+ return null;
16
+ }
17
+ /**
18
+ * How the CLI can authenticate to Vercel Blob. `{ token }` when
19
+ * `BLOB_READ_WRITE_TOKEN` is set; `{}` when only the Marketplace OIDC pair
20
+ * (`VERCEL_OIDC_TOKEN` + `BLOB_STORE_ID`) is present, in which case
21
+ * `@vercel/blob` resolves the credentials from the environment itself and
22
+ * the CLI must not pass `token` at all. `null` when neither mode is available.
23
+ * Mirrors `resolveBlobClientAuthOptions` in `@prenta/platform-vercel`.
24
+ */
25
+ export function resolveBlobAuth(env) {
26
+ const token = env.BLOB_READ_WRITE_TOKEN?.trim();
27
+ if (token)
28
+ return { token };
29
+ if (env.VERCEL_OIDC_TOKEN?.trim() && env.BLOB_STORE_ID?.trim())
30
+ return {};
31
+ return null;
32
+ }
33
+ /** Names both Blob auth modes, for precondition errors. */
34
+ 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)';
35
+ const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '[::1]']);
36
+ /** True for URLs pointing at the developer's own machine. */
37
+ export function isLocalDatabaseUrl(url) {
38
+ try {
39
+ return LOCAL_HOSTS.has(new URL(url).hostname.toLowerCase());
40
+ }
41
+ catch {
42
+ return false;
43
+ }
44
+ }
45
+ function safeDecode(value) {
46
+ try {
47
+ return decodeURIComponent(value);
48
+ }
49
+ catch {
50
+ return value;
51
+ }
52
+ }
53
+ /**
54
+ * The database a URL path names, normalized the way libpq resolves it:
55
+ * surrounding slashes stripped, percent-escapes decoded, and an empty path
56
+ * meaning `postgres`. Every place that shows or compares a database name
57
+ * (the production guard, the typed confirmation, the manifest) must use this
58
+ * so they agree.
59
+ */
60
+ export function normalizeDatabaseName(pathname) {
61
+ const path = safeDecode(pathname.replace(/^\/+|\/+$/g, ''));
62
+ return path === '' ? 'postgres' : path;
63
+ }
64
+ /** True when the URL path names a database explicitly (`/db`), not `` or `/`. */
65
+ export function namesDatabase(url) {
66
+ try {
67
+ return new URL(url).pathname.replace(/^\/+|\/+$/g, '') !== '';
68
+ }
69
+ catch {
70
+ return false;
71
+ }
72
+ }
73
+ /** `DatabaseIdentity` for a parseable postgres:// URL, else `null`. */
74
+ export function databaseIdentity(url) {
75
+ if (!isPostgresUrl(url))
76
+ return null;
77
+ const parsed = new URL(url);
78
+ return {
79
+ user: safeDecode(parsed.username),
80
+ host: parsed.hostname.toLowerCase().replace(/^pooled\./, ''),
81
+ name: normalizeDatabaseName(parsed.pathname),
82
+ };
83
+ }
84
+ /**
85
+ * True when both URLs name the same database (see `DatabaseIdentity`).
86
+ * Unparseable input is never "the same" — callers that need to know whether
87
+ * the comparison was possible at all use `databaseIdentity` directly.
88
+ */
89
+ export function isSameDatabase(a, b) {
90
+ const da = databaseIdentity(a);
91
+ const db = databaseIdentity(b);
92
+ if (!da || !db)
93
+ return false;
94
+ return da.user === db.user && da.host === db.host && da.name === db.name;
95
+ }
96
+ /** Validate a connection URL is parseable and uses a postgres scheme. */
97
+ export function isPostgresUrl(url) {
98
+ try {
99
+ const parsed = new URL(url);
100
+ return ((parsed.protocol === 'postgres:' || parsed.protocol === 'postgresql:') && !!parsed.hostname);
101
+ }
102
+ catch {
103
+ return false;
104
+ }
105
+ }
106
+ export function formatBytes(bytes) {
107
+ if (bytes < 1024)
108
+ return `${bytes} B`;
109
+ const units = ['KB', 'MB', 'GB', 'TB'];
110
+ let value = bytes / 1024;
111
+ let unit = 0;
112
+ while (value >= 1024 && unit < units.length - 1) {
113
+ value /= 1024;
114
+ unit++;
115
+ }
116
+ return `${value.toFixed(value >= 100 ? 0 : 1)} ${units[unit]}`;
117
+ }
118
+ export function formatDuration(ms) {
119
+ if (ms < 1000)
120
+ return `${Math.round(ms)}ms`;
121
+ const seconds = ms / 1000;
122
+ if (seconds < 60)
123
+ return `${seconds.toFixed(1)}s`;
124
+ const minutes = Math.floor(seconds / 60);
125
+ return `${minutes}m ${Math.round(seconds - minutes * 60)}s`;
126
+ }
127
+ //# 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,qEAAqE;AACrE,MA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