payload-plugin-backup-postgres 0.0.0-stage → 0.1.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 (187) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +355 -2
  3. package/dist/backup-dashboard.css +1149 -0
  4. package/dist/client.d.ts +3 -0
  5. package/dist/client.js +3 -0
  6. package/dist/client.js.map +1 -0
  7. package/dist/collections/BackupSettings.d.ts +6 -0
  8. package/dist/collections/BackupSettings.js +91 -0
  9. package/dist/collections/BackupSettings.js.map +1 -0
  10. package/dist/collections/BackupTasks.d.ts +2 -0
  11. package/dist/collections/BackupTasks.js +63 -0
  12. package/dist/collections/BackupTasks.js.map +1 -0
  13. package/dist/components/BackupDashboard/BackupItemActions.client.d.ts +7 -0
  14. package/dist/components/BackupDashboard/BackupItemActions.client.js +90 -0
  15. package/dist/components/BackupDashboard/BackupItemActions.client.js.map +1 -0
  16. package/dist/components/BackupDashboard/BackupListCollapsible.client.d.ts +16 -0
  17. package/dist/components/BackupDashboard/BackupListCollapsible.client.js +597 -0
  18. package/dist/components/BackupDashboard/BackupListCollapsible.client.js.map +1 -0
  19. package/dist/components/BackupDashboard/BackupSettingsModal.client.d.ts +2 -0
  20. package/dist/components/BackupDashboard/BackupSettingsModal.client.js +1027 -0
  21. package/dist/components/BackupDashboard/BackupSettingsModal.client.js.map +1 -0
  22. package/dist/components/BackupDashboard/CollectionBackupPreviewBody.client.d.ts +18 -0
  23. package/dist/components/BackupDashboard/CollectionBackupPreviewBody.client.js +267 -0
  24. package/dist/components/BackupDashboard/CollectionBackupPreviewBody.client.js.map +1 -0
  25. package/dist/components/BackupDashboard/ManualBackupDialog.client.d.ts +1 -0
  26. package/dist/components/BackupDashboard/ManualBackupDialog.client.js +276 -0
  27. package/dist/components/BackupDashboard/ManualBackupDialog.client.js.map +1 -0
  28. package/dist/components/BackupDashboard/RestoreBackupDialog.client.d.ts +6 -0
  29. package/dist/components/BackupDashboard/RestoreBackupDialog.client.js +551 -0
  30. package/dist/components/BackupDashboard/RestoreBackupDialog.client.js.map +1 -0
  31. package/dist/components/BackupDashboard/TaskActionButton.client.d.ts +29 -0
  32. package/dist/components/BackupDashboard/TaskActionButton.client.js +273 -0
  33. package/dist/components/BackupDashboard/TaskActionButton.client.js.map +1 -0
  34. package/dist/components/BackupDashboard/backupDashboardInlineCss.d.ts +1 -0
  35. package/dist/components/BackupDashboard/backupDashboardInlineCss.js +3 -0
  36. package/dist/components/BackupDashboard/backupDashboardInlineCss.js.map +1 -0
  37. package/dist/components/BackupDashboard/index.client.d.ts +8 -0
  38. package/dist/components/BackupDashboard/index.client.js +9 -0
  39. package/dist/components/BackupDashboard/index.client.js.map +1 -0
  40. package/dist/components/BackupDashboard/index.d.ts +15 -0
  41. package/dist/components/BackupDashboard/index.js +246 -0
  42. package/dist/components/BackupDashboard/index.js.map +1 -0
  43. package/dist/core/archive.d.ts +8 -0
  44. package/dist/core/archive.js +47 -0
  45. package/dist/core/archive.js.map +1 -0
  46. package/dist/core/backup.d.ts +54 -0
  47. package/dist/core/backup.js +282 -0
  48. package/dist/core/backup.js.map +1 -0
  49. package/dist/core/backupArchiveRead.d.ts +15 -0
  50. package/dist/core/backupArchiveRead.js +30 -0
  51. package/dist/core/backupArchiveRead.js.map +1 -0
  52. package/dist/core/backupBlobIO.d.ts +54 -0
  53. package/dist/core/backupBlobIO.js +179 -0
  54. package/dist/core/backupBlobIO.js.map +1 -0
  55. package/dist/core/backupBlobTransfer.d.ts +29 -0
  56. package/dist/core/backupBlobTransfer.js +85 -0
  57. package/dist/core/backupBlobTransfer.js.map +1 -0
  58. package/dist/core/backupSettings.d.ts +35 -0
  59. package/dist/core/backupSettings.js +100 -0
  60. package/dist/core/backupSettings.js.map +1 -0
  61. package/dist/core/backupSourcePreview.d.ts +10 -0
  62. package/dist/core/backupSourcePreview.js +46 -0
  63. package/dist/core/backupSourcePreview.js.map +1 -0
  64. package/dist/core/blobTokenValidate.d.ts +14 -0
  65. package/dist/core/blobTokenValidate.js +75 -0
  66. package/dist/core/blobTokenValidate.js.map +1 -0
  67. package/dist/core/db.d.ts +56 -0
  68. package/dist/core/db.js +161 -0
  69. package/dist/core/db.js.map +1 -0
  70. package/dist/core/pgArchive.d.ts +37 -0
  71. package/dist/core/pgArchive.js +57 -0
  72. package/dist/core/pgArchive.js.map +1 -0
  73. package/dist/core/restore.d.ts +46 -0
  74. package/dist/core/restore.js +439 -0
  75. package/dist/core/restore.js.map +1 -0
  76. package/dist/core/restorePreview.d.ts +76 -0
  77. package/dist/core/restorePreview.js +222 -0
  78. package/dist/core/restorePreview.js.map +1 -0
  79. package/dist/core/restoreResult.d.ts +34 -0
  80. package/dist/core/restoreResult.js +45 -0
  81. package/dist/core/restoreResult.js.map +1 -0
  82. package/dist/core/storage/config.d.ts +31 -0
  83. package/dist/core/storage/config.js +60 -0
  84. package/dist/core/storage/config.js.map +1 -0
  85. package/dist/core/storage/index.d.ts +23 -0
  86. package/dist/core/storage/index.js +25 -0
  87. package/dist/core/storage/index.js.map +1 -0
  88. package/dist/core/storage/s3.d.ts +35 -0
  89. package/dist/core/storage/s3.js +200 -0
  90. package/dist/core/storage/s3.js.map +1 -0
  91. package/dist/core/storage/types.d.ts +60 -0
  92. package/dist/core/storage/types.js +6 -0
  93. package/dist/core/storage/types.js.map +1 -0
  94. package/dist/core/storage/vercelBlob.d.ts +25 -0
  95. package/dist/core/storage/vercelBlob.js +53 -0
  96. package/dist/core/storage/vercelBlob.js.map +1 -0
  97. package/dist/core/tableGroups.d.ts +25 -0
  98. package/dist/core/tableGroups.js +80 -0
  99. package/dist/core/tableGroups.js.map +1 -0
  100. package/dist/core/taskProgress.d.ts +39 -0
  101. package/dist/core/taskProgress.js +104 -0
  102. package/dist/core/taskProgress.js.map +1 -0
  103. package/dist/core/vercelBackupCron.d.ts +8 -0
  104. package/dist/core/vercelBackupCron.js +38 -0
  105. package/dist/core/vercelBackupCron.js.map +1 -0
  106. package/dist/endpoints/index.d.ts +3 -0
  107. package/dist/endpoints/index.js +29 -0
  108. package/dist/endpoints/index.js.map +1 -0
  109. package/dist/endpoints/paths/admin-backup-download.d.ts +8 -0
  110. package/dist/endpoints/paths/admin-backup-download.js +73 -0
  111. package/dist/endpoints/paths/admin-backup-download.js.map +1 -0
  112. package/dist/endpoints/paths/admin-delete.d.ts +3 -0
  113. package/dist/endpoints/paths/admin-delete.js +61 -0
  114. package/dist/endpoints/paths/admin-delete.js.map +1 -0
  115. package/dist/endpoints/paths/admin-manual.d.ts +3 -0
  116. package/dist/endpoints/paths/admin-manual.js +62 -0
  117. package/dist/endpoints/paths/admin-manual.js.map +1 -0
  118. package/dist/endpoints/paths/admin-preview.d.ts +6 -0
  119. package/dist/endpoints/paths/admin-preview.js +109 -0
  120. package/dist/endpoints/paths/admin-preview.js.map +1 -0
  121. package/dist/endpoints/paths/admin-restore.d.ts +3 -0
  122. package/dist/endpoints/paths/admin-restore.js +77 -0
  123. package/dist/endpoints/paths/admin-restore.js.map +1 -0
  124. package/dist/endpoints/paths/admin-settings.d.ts +3 -0
  125. package/dist/endpoints/paths/admin-settings.js +263 -0
  126. package/dist/endpoints/paths/admin-settings.js.map +1 -0
  127. package/dist/endpoints/paths/admin-task.d.ts +3 -0
  128. package/dist/endpoints/paths/admin-task.js +34 -0
  129. package/dist/endpoints/paths/admin-task.js.map +1 -0
  130. package/dist/endpoints/paths/admin-validate-blob-token.d.ts +8 -0
  131. package/dist/endpoints/paths/admin-validate-blob-token.js +26 -0
  132. package/dist/endpoints/paths/admin-validate-blob-token.js.map +1 -0
  133. package/dist/endpoints/paths/cron-list.d.ts +2 -0
  134. package/dist/endpoints/paths/cron-list.js +34 -0
  135. package/dist/endpoints/paths/cron-list.js.map +1 -0
  136. package/dist/endpoints/paths/cron-restore.d.ts +2 -0
  137. package/dist/endpoints/paths/cron-restore.js +71 -0
  138. package/dist/endpoints/paths/cron-restore.js.map +1 -0
  139. package/dist/endpoints/paths/cron-run.d.ts +3 -0
  140. package/dist/endpoints/paths/cron-run.js +46 -0
  141. package/dist/endpoints/paths/cron-run.js.map +1 -0
  142. package/dist/endpoints/shared.d.ts +12 -0
  143. package/dist/endpoints/shared.js +52 -0
  144. package/dist/endpoints/shared.js.map +1 -0
  145. package/dist/exports/client.d.ts +1 -0
  146. package/dist/exports/client.js +3 -0
  147. package/dist/exports/client.js.map +1 -0
  148. package/dist/exports/rsc.d.ts +1 -0
  149. package/dist/exports/rsc.js +3 -0
  150. package/dist/exports/rsc.js.map +1 -0
  151. package/dist/index.d.ts +25 -0
  152. package/dist/index.js +18 -0
  153. package/dist/index.js.map +1 -0
  154. package/dist/plugin.d.ts +3 -0
  155. package/dist/plugin.js +69 -0
  156. package/dist/plugin.js.map +1 -0
  157. package/dist/publicApiPaths.d.ts +18 -0
  158. package/dist/publicApiPaths.js +19 -0
  159. package/dist/publicApiPaths.js.map +1 -0
  160. package/dist/types.d.ts +16 -0
  161. package/dist/types.js +3 -0
  162. package/dist/types.js.map +1 -0
  163. package/dist/utils/backupSelection.d.ts +6 -0
  164. package/dist/utils/backupSelection.js +16 -0
  165. package/dist/utils/backupSelection.js.map +1 -0
  166. package/dist/utils/blobName.d.ts +32 -0
  167. package/dist/utils/blobName.js +99 -0
  168. package/dist/utils/blobName.js.map +1 -0
  169. package/dist/utils/dashboardRoleAccess.d.ts +23 -0
  170. package/dist/utils/dashboardRoleAccess.js +64 -0
  171. package/dist/utils/dashboardRoleAccess.js.map +1 -0
  172. package/dist/utils/dialogBackdrop.d.ts +9 -0
  173. package/dist/utils/dialogBackdrop.js +17 -0
  174. package/dist/utils/dialogBackdrop.js.map +1 -0
  175. package/dist/utils/formatBytes.d.ts +2 -0
  176. package/dist/utils/formatBytes.js +20 -0
  177. package/dist/utils/formatBytes.js.map +1 -0
  178. package/dist/utils/hostname.d.ts +4 -0
  179. package/dist/utils/hostname.js +32 -0
  180. package/dist/utils/hostname.js.map +1 -0
  181. package/dist/utils/index.d.ts +5 -0
  182. package/dist/utils/index.js +7 -0
  183. package/dist/utils/index.js.map +1 -0
  184. package/dist/utils/maskBlobToken.d.ts +11 -0
  185. package/dist/utils/maskBlobToken.js +42 -0
  186. package/dist/utils/maskBlobToken.js.map +1 -0
  187. package/package.json +140 -3
@@ -0,0 +1,282 @@
1
+ import { list } from '@vercel/blob';
2
+ import { createBlobName, getCurrentDbName, getCurrentHostname, sanitizeBackupLabel } from '../utils/index.js';
3
+ import { createTarGzip } from './archive.js';
4
+ import { readBackupBlobContentFlexible } from './backupBlobIO.js';
5
+ import { getResolvedCronBackupSettings, resolveBackupBlobToken } from './backupSettings.js';
6
+ import { getPgDb, listTables, qi, qualified, withClient } from './db.js';
7
+ import { ARCHIVE_FORMAT, ARCHIVE_VERSION, DATABASE_FILE_NAME, MEDIA_PREFIX, serializeBackupDocument } from './pgArchive.js';
8
+ import { getBackupStorageKind, resolveBackupStorage } from './storage/index.js';
9
+ import { resolveTableOwners } from './tableGroups.js';
10
+ import { updateBackupTask } from './taskProgress.js';
11
+ export { DATABASE_FILE_NAME } from './pgArchive.js';
12
+ /**
13
+ * Resolves the Vercel Blob read/write token the same way as backup endpoints and
14
+ * {@link createBackup} / {@link restoreBackup}: settings document override, else `BLOB_READ_WRITE_TOKEN`.
15
+ * Pass `explicitToken` to skip reading settings (same as `options.blobToken` in those calls).
16
+ */ export async function resolveBackupListToken(payload, explicitToken) {
17
+ const t = explicitToken?.trim();
18
+ if (t) {
19
+ return t;
20
+ }
21
+ return resolveBackupBlobToken(await getResolvedCronBackupSettings(payload)).trim();
22
+ }
23
+ export async function listBackups(payload, options = {}) {
24
+ const kind = getBackupStorageKind();
25
+ if (kind === 'vercel-blob') {
26
+ const token = await resolveBackupListToken(payload, options.blobToken);
27
+ if (!token) {
28
+ return [];
29
+ }
30
+ return resolveBackupStorage({
31
+ blobToken: token,
32
+ kind
33
+ }).list('backups/');
34
+ }
35
+ return resolveBackupStorage({
36
+ kind
37
+ }).list('backups/');
38
+ }
39
+ function resolveBlobToken(blobToken) {
40
+ if (blobToken && blobToken.trim().length > 0) {
41
+ return blobToken;
42
+ }
43
+ return undefined;
44
+ }
45
+ /**
46
+ * Builds a tar.gz archive containing the database dump plus Payload upload-store media files.
47
+ * Media always comes from the Vercel Blob upload store (via token/env), independent of the
48
+ * configured backup archive target (S3 vs Vercel Blob).
49
+ */ export async function createMediaBackupFile(databaseFile, mediaPathnames, backupBlobToken, mediaListToken, payload) {
50
+ const envMedia = (process.env.BLOB_READ_WRITE_TOKEN || '').trim();
51
+ const tokenForMedia = resolveBlobToken(mediaListToken) ?? (envMedia.length > 0 ? envMedia : undefined) ?? resolveBlobToken(backupBlobToken);
52
+ const unique = [
53
+ ...new Set(mediaPathnames.filter(Boolean))
54
+ ];
55
+ const mediaFiles = await Promise.all(unique.map(async (pathname)=>{
56
+ try {
57
+ const matchingFiles = await list({
58
+ limit: 2,
59
+ prefix: pathname,
60
+ token: tokenForMedia
61
+ });
62
+ const blob = matchingFiles.blobs.find((b)=>b.pathname === pathname);
63
+ if (!blob) {
64
+ payload?.logger.warn({
65
+ filename: pathname
66
+ }, '[backup] File was in database but not in blob storage');
67
+ return undefined;
68
+ }
69
+ const content = await readBackupBlobContentFlexible(blob.pathname, blob.downloadUrl, tokenForMedia ?? '');
70
+ return {
71
+ name: `${MEDIA_PREFIX}${pathname}`,
72
+ content
73
+ };
74
+ } catch (err) {
75
+ payload?.logger.warn({
76
+ err,
77
+ filename: pathname
78
+ }, '[backup] Failed to read media file from blob storage');
79
+ return undefined;
80
+ }
81
+ }));
82
+ return await createTarGzip([
83
+ {
84
+ name: DATABASE_FILE_NAME,
85
+ content: Buffer.from(databaseFile)
86
+ },
87
+ ...mediaFiles.filter(Boolean)
88
+ ]);
89
+ }
90
+ /**
91
+ * Dumps every table of Payload's schema inside one `REPEATABLE READ READ ONLY` transaction,
92
+ * so all tables come from the same snapshot.
93
+ */ export async function dumpDatabase(payload, options = {}) {
94
+ const { pool, schema, tableNameMap } = getPgDb(payload);
95
+ const skip = new Set(options.skipTables ?? []);
96
+ return withClient(pool, async (client)=>{
97
+ await client.query('BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY');
98
+ try {
99
+ const { rows: ver } = await client.query(`SELECT current_setting('server_version') AS v`);
100
+ const allTables = await listTables(client, schema);
101
+ const tables = {};
102
+ for (const table of allTables){
103
+ if (skip.has(table)) {
104
+ payload.logger.debug({
105
+ table
106
+ }, '[backup] Skipping blacklisted table');
107
+ continue;
108
+ }
109
+ const { rows } = await client.query(`SELECT count(*)::text AS n, coalesce(json_agg(t), '[]'::json)::text AS rows
110
+ FROM ${qualified(schema, table)} t`);
111
+ const rowCount = Number(rows[0]?.n ?? 0);
112
+ tables[table] = {
113
+ rowCount,
114
+ rows: rows[0]?.rows ?? '[]'
115
+ };
116
+ await options.onTable?.(table, rowCount);
117
+ }
118
+ const mediaPathnames = [];
119
+ if (options.collectMedia) {
120
+ const owners = resolveTableOwners(payload, Object.keys(tables), tableNameMap);
121
+ const uploadSlugs = new Set((payload.config.collections ?? []).filter((c)=>Boolean(c.upload)).map((c)=>c.slug));
122
+ for (const table of Object.keys(tables)){
123
+ const owner = owners.get(table);
124
+ // Only the main root table of an upload collection holds `filename` / `sizes_*_filename`.
125
+ if (owner.kind !== 'collection' || owner.versions || !uploadSlugs.has(owner.slug)) {
126
+ continue;
127
+ }
128
+ mediaPathnames.push(...await readMediaPathnames(client, schema, table));
129
+ }
130
+ }
131
+ await client.query('COMMIT');
132
+ return {
133
+ doc: {
134
+ createdAt: new Date().toISOString(),
135
+ format: ARCHIVE_FORMAT,
136
+ schema,
137
+ serverVersion: ver[0]?.v ?? 'unknown',
138
+ tables,
139
+ version: ARCHIVE_VERSION
140
+ },
141
+ mediaPathnames
142
+ };
143
+ } catch (err) {
144
+ await client.query('ROLLBACK').catch(()=>undefined);
145
+ throw err;
146
+ }
147
+ });
148
+ }
149
+ async function readMediaPathnames(client, schema, table) {
150
+ const { rows: cols } = await client.query(`SELECT a.attname AS name
151
+ FROM pg_attribute a
152
+ JOIN pg_class c ON c.oid = a.attrelid
153
+ JOIN pg_namespace n ON n.oid = c.relnamespace
154
+ WHERE n.nspname = $1 AND c.relname = $2 AND a.attnum > 0 AND NOT a.attisdropped`, [
155
+ schema,
156
+ table
157
+ ]);
158
+ const names = new Set(cols.map((c)=>c.name));
159
+ if (!names.has('filename')) {
160
+ return [];
161
+ }
162
+ const fileCols = [
163
+ 'filename',
164
+ ...[
165
+ ...names
166
+ ].filter((n)=>/^sizes_.+_filename$/.test(n))
167
+ ];
168
+ const prefixExpr = names.has('prefix') ? qi('prefix') : 'NULL::text';
169
+ const out = [];
170
+ for (const col of fileCols){
171
+ const { rows } = await client.query(`SELECT ${prefixExpr} AS p, ${qi(col)}::text AS f
172
+ FROM ${qualified(schema, table)}
173
+ WHERE ${qi(col)} IS NOT NULL AND ${qi(col)}::text <> ''`);
174
+ for (const r of rows){
175
+ const prefix = (r.p ?? '').replace(/^\/+|\/+$/g, '');
176
+ out.push(prefix ? `${prefix}/${r.f}` : r.f);
177
+ }
178
+ }
179
+ return out;
180
+ }
181
+ export async function createBackup(payload, options = {}) {
182
+ const { backupsToKeep, blobToken, cron = false, includeMedia = false, skipCollections, taskId } = options;
183
+ const label = cron ? '' : sanitizeBackupLabel(options.label);
184
+ const blobAccess = options.blobAccess ?? 'public';
185
+ const token = resolveBlobToken(blobToken);
186
+ const resolvedBackupsToKeep = backupsToKeep ?? (Number(process.env.BACKUPS_TO_KEEP) || 10);
187
+ const storage = resolveBackupStorage({
188
+ blobAccess,
189
+ blobToken: token
190
+ });
191
+ const currentHostname = getCurrentHostname();
192
+ const currentDbName = getCurrentDbName();
193
+ const type = cron ? 'cron' : 'manual';
194
+ const t0 = Date.now();
195
+ payload.logger.info({
196
+ type,
197
+ blacklist: skipCollections?.length ?? 0,
198
+ db: currentDbName,
199
+ host: currentHostname,
200
+ includeMedia
201
+ }, '[backup] Starting backup');
202
+ if (taskId) {
203
+ await updateBackupTask(payload, taskId, {
204
+ message: 'Starting backup',
205
+ status: 'running'
206
+ });
207
+ }
208
+ if (cron) {
209
+ const blobs = await storage.list('backups/cron-');
210
+ const sorted = blobs.sort((a, b)=>new Date(b.uploadedAt).getTime() - new Date(a.uploadedAt).getTime());
211
+ const oldest = sorted.slice(Math.max(0, resolvedBackupsToKeep - 1));
212
+ if (oldest.length > 0) {
213
+ payload.logger.info({
214
+ count: oldest.length
215
+ }, '[backup] Pruning old cron backups');
216
+ if (taskId) {
217
+ await updateBackupTask(payload, taskId, {
218
+ message: `Pruning ${oldest.length} old cron backup${oldest.length === 1 ? '' : 's'}`
219
+ });
220
+ }
221
+ }
222
+ for (const blob of oldest){
223
+ await storage.del({
224
+ pathname: blob.pathname,
225
+ url: blob.url
226
+ });
227
+ payload.logger.info({
228
+ pathname: blob.pathname
229
+ }, '[backup] Deleted old backup');
230
+ }
231
+ }
232
+ if (taskId) {
233
+ await updateBackupTask(payload, taskId, {
234
+ message: 'Dumping tables'
235
+ });
236
+ }
237
+ const { doc, mediaPathnames } = await dumpDatabase(payload, {
238
+ collectMedia: includeMedia,
239
+ onTable: async (table, rowCount)=>{
240
+ payload.logger.debug({
241
+ rows: rowCount,
242
+ table
243
+ }, '[backup] Table dumped');
244
+ if (taskId) {
245
+ await updateBackupTask(payload, taskId, {
246
+ message: `Dumped table ${table} (${rowCount} rows)`
247
+ });
248
+ }
249
+ },
250
+ skipTables: skipCollections
251
+ });
252
+ const databaseFile = serializeBackupDocument(doc);
253
+ const includedTableCount = Object.keys(doc.tables).length;
254
+ const backupTimestampMs = Date.now();
255
+ if (includeMedia) {
256
+ payload.logger.info({
257
+ files: mediaPathnames.length
258
+ }, '[backup] Bundling media files');
259
+ if (taskId) {
260
+ await updateBackupTask(payload, taskId, {
261
+ message: 'Bundling media files into archive'
262
+ });
263
+ }
264
+ }
265
+ const backupFile = includeMedia ? await createMediaBackupFile(databaseFile, mediaPathnames, token, undefined, payload) : databaseFile;
266
+ const name = `backups/${createBlobName(type, currentDbName, currentHostname, includedTableCount, backupTimestampMs, includeMedia ? 'tar.gz' : 'json', label || undefined)}`;
267
+ payload.logger.info({
268
+ name
269
+ }, '[backup] Uploading backup to blob storage');
270
+ if (taskId) {
271
+ await updateBackupTask(payload, taskId, {
272
+ message: 'Uploading backup to blob storage'
273
+ });
274
+ }
275
+ await storage.put(name, backupFile);
276
+ payload.logger.info({
277
+ name,
278
+ durationMs: Date.now() - t0
279
+ }, '[backup] Backup complete');
280
+ }
281
+
282
+ //# sourceMappingURL=backup.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/core/backup.ts"],"sourcesContent":["import type { Payload } from 'payload'\n\nimport { list } from '@vercel/blob'\n\nimport {\n createBlobName,\n getCurrentDbName,\n getCurrentHostname,\n sanitizeBackupLabel,\n} from '../utils/index'\nimport { createTarGzip } from './archive'\nimport { type BackupBlobAccessLevel, readBackupBlobContentFlexible } from './backupBlobIO'\nimport { getResolvedCronBackupSettings, resolveBackupBlobToken } from './backupSettings'\nimport { getPgDb, listTables, type PgClient, qi, qualified, withClient } from './db'\nimport {\n ARCHIVE_FORMAT,\n ARCHIVE_VERSION,\n DATABASE_FILE_NAME,\n MEDIA_PREFIX,\n type PgBackupDocument,\n serializeBackupDocument,\n} from './pgArchive'\nimport { getBackupStorageKind, resolveBackupStorage } from './storage'\nimport { resolveTableOwners } from './tableGroups'\nimport { updateBackupTask } from './taskProgress'\n\nexport { DATABASE_FILE_NAME } from './pgArchive'\n\n/**\n * Resolves the Vercel Blob read/write token the same way as backup endpoints and\n * {@link createBackup} / {@link restoreBackup}: settings document override, else `BLOB_READ_WRITE_TOKEN`.\n * Pass `explicitToken` to skip reading settings (same as `options.blobToken` in those calls).\n */\nexport async function resolveBackupListToken(\n payload: Payload,\n explicitToken?: string,\n): Promise<string> {\n const t = explicitToken?.trim()\n if (t) {\n return t\n }\n return resolveBackupBlobToken(await getResolvedCronBackupSettings(payload)).trim()\n}\n\nexport async function listBackups(\n payload: Payload,\n options: {\n /**\n * When set, used as the Vercel Blob token (e.g. tests or a pre-resolved value).\n * When omitted, uses {@link resolveBackupListToken} (settings + env), same as other backup APIs.\n */\n blobToken?: string\n } = {},\n) {\n const kind = getBackupStorageKind()\n if (kind === 'vercel-blob') {\n const token = await resolveBackupListToken(payload, options.blobToken)\n if (!token) {\n return []\n }\n return resolveBackupStorage({ blobToken: token, kind }).list('backups/')\n }\n return resolveBackupStorage({ kind }).list('backups/')\n}\n\nfunction resolveBlobToken(blobToken?: string): string | undefined {\n if (blobToken && blobToken.trim().length > 0) {\n return blobToken\n }\n return undefined\n}\n\n/**\n * Builds a tar.gz archive containing the database dump plus Payload upload-store media files.\n * Media always comes from the Vercel Blob upload store (via token/env), independent of the\n * configured backup archive target (S3 vs Vercel Blob).\n */\nexport async function createMediaBackupFile(\n databaseFile: string,\n mediaPathnames: string[],\n backupBlobToken?: string,\n mediaListToken?: string,\n payload?: Payload,\n): Promise<Buffer> {\n const envMedia = (process.env.BLOB_READ_WRITE_TOKEN || '').trim()\n const tokenForMedia =\n resolveBlobToken(mediaListToken) ??\n (envMedia.length > 0 ? envMedia : undefined) ??\n resolveBlobToken(backupBlobToken)\n const unique = [...new Set(mediaPathnames.filter(Boolean))]\n const mediaFiles = await Promise.all(\n unique.map(async (pathname) => {\n try {\n const matchingFiles = await list({ limit: 2, prefix: pathname, token: tokenForMedia })\n const blob = matchingFiles.blobs.find((b) => b.pathname === pathname)\n if (!blob) {\n payload?.logger.warn(\n { filename: pathname },\n '[backup] File was in database but not in blob storage',\n )\n return undefined\n }\n const content = await readBackupBlobContentFlexible(\n blob.pathname,\n blob.downloadUrl,\n tokenForMedia ?? '',\n )\n return { name: `${MEDIA_PREFIX}${pathname}`, content }\n } catch (err) {\n payload?.logger.warn(\n { err, filename: pathname },\n '[backup] Failed to read media file from blob storage',\n )\n return undefined\n }\n }),\n )\n return await createTarGzip([\n { name: DATABASE_FILE_NAME, content: Buffer.from(databaseFile) },\n ...(mediaFiles.filter(Boolean) as { content: Buffer; name: string }[]),\n ])\n}\n\ntype DumpResult = {\n doc: PgBackupDocument\n /** Blob pathnames referenced by upload collections (only collected when requested). */\n mediaPathnames: string[]\n}\n\n/**\n * Dumps every table of Payload's schema inside one `REPEATABLE READ READ ONLY` transaction,\n * so all tables come from the same snapshot.\n */\nexport async function dumpDatabase(\n payload: Payload,\n options: {\n collectMedia?: boolean\n onTable?: (table: string, rowCount: number) => Promise<void> | void\n skipTables?: string[]\n } = {},\n): Promise<DumpResult> {\n const { pool, schema, tableNameMap } = getPgDb(payload)\n const skip = new Set(options.skipTables ?? [])\n\n return withClient(pool, async (client) => {\n await client.query('BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY')\n try {\n const { rows: ver } = await client.query<{ v: string }>(\n `SELECT current_setting('server_version') AS v`,\n )\n const allTables = await listTables(client, schema)\n const tables: PgBackupDocument['tables'] = {}\n for (const table of allTables) {\n if (skip.has(table)) {\n payload.logger.debug({ table }, '[backup] Skipping blacklisted table')\n continue\n }\n const { rows } = await client.query<{ n: string; rows: string }>(\n `SELECT count(*)::text AS n, coalesce(json_agg(t), '[]'::json)::text AS rows\n FROM ${qualified(schema, table)} t`,\n )\n const rowCount = Number(rows[0]?.n ?? 0)\n tables[table] = { rowCount, rows: rows[0]?.rows ?? '[]' }\n await options.onTable?.(table, rowCount)\n }\n\n const mediaPathnames: string[] = []\n if (options.collectMedia) {\n const owners = resolveTableOwners(payload, Object.keys(tables), tableNameMap)\n const uploadSlugs = new Set(\n (payload.config.collections ?? []).filter((c) => Boolean(c.upload)).map((c) => c.slug),\n )\n for (const table of Object.keys(tables)) {\n const owner = owners.get(table)!\n // Only the main root table of an upload collection holds `filename` / `sizes_*_filename`.\n if (owner.kind !== 'collection' || owner.versions || !uploadSlugs.has(owner.slug)) {\n continue\n }\n mediaPathnames.push(...(await readMediaPathnames(client, schema, table)))\n }\n }\n\n await client.query('COMMIT')\n return {\n doc: {\n createdAt: new Date().toISOString(),\n format: ARCHIVE_FORMAT,\n schema,\n serverVersion: ver[0]?.v ?? 'unknown',\n tables,\n version: ARCHIVE_VERSION,\n },\n mediaPathnames,\n }\n } catch (err) {\n await client.query('ROLLBACK').catch(() => undefined)\n throw err\n }\n })\n}\n\nasync function readMediaPathnames(\n client: PgClient,\n schema: string,\n table: string,\n): Promise<string[]> {\n const { rows: cols } = await client.query<{ name: string }>(\n `SELECT a.attname AS name\n FROM pg_attribute a\n JOIN pg_class c ON c.oid = a.attrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = $1 AND c.relname = $2 AND a.attnum > 0 AND NOT a.attisdropped`,\n [schema, table],\n )\n const names = new Set(cols.map((c) => c.name))\n if (!names.has('filename')) {\n return []\n }\n const fileCols = ['filename', ...[...names].filter((n) => /^sizes_.+_filename$/.test(n))]\n const prefixExpr = names.has('prefix') ? qi('prefix') : 'NULL::text'\n const out: string[] = []\n for (const col of fileCols) {\n const { rows } = await client.query<{ f: string; p: null | string }>(\n `SELECT ${prefixExpr} AS p, ${qi(col)}::text AS f\n FROM ${qualified(schema, table)}\n WHERE ${qi(col)} IS NOT NULL AND ${qi(col)}::text <> ''`,\n )\n for (const r of rows) {\n const prefix = (r.p ?? '').replace(/^\\/+|\\/+$/g, '')\n out.push(prefix ? `${prefix}/${r.f}` : r.f)\n }\n }\n return out\n}\n\nexport async function createBackup(\n payload: Payload,\n options: {\n backupsToKeep?: number\n /** Public (default) or private Vercel Blob access for the uploaded backup archive. */\n blobAccess?: BackupBlobAccessLevel\n /** Optional explicit Vercel Blob token (falls back to env inside @vercel/blob). */\n blobToken?: string\n cron?: boolean\n includeMedia?: boolean\n /**\n * Optional human-readable label for manual backups (appears in the backup list and is\n * searchable via the label filter). Ignored for cron backups.\n */\n label?: string\n /** Postgres table names to omit from the dump (e.g. manual backup UI). */\n skipCollections?: string[]\n taskId?: string\n } = {},\n): Promise<void> {\n const {\n backupsToKeep,\n blobToken,\n cron = false,\n includeMedia = false,\n skipCollections,\n taskId,\n } = options\n const label = cron ? '' : sanitizeBackupLabel(options.label)\n const blobAccess: BackupBlobAccessLevel = options.blobAccess ?? 'public'\n const token = resolveBlobToken(blobToken)\n const resolvedBackupsToKeep = backupsToKeep ?? (Number(process.env.BACKUPS_TO_KEEP) || 10)\n const storage = resolveBackupStorage({ blobAccess, blobToken: token })\n\n const currentHostname = getCurrentHostname()\n const currentDbName = getCurrentDbName()\n const type = cron ? 'cron' : 'manual'\n const t0 = Date.now()\n\n payload.logger.info(\n {\n type,\n blacklist: skipCollections?.length ?? 0,\n db: currentDbName,\n host: currentHostname,\n includeMedia,\n },\n '[backup] Starting backup',\n )\n if (taskId) {\n await updateBackupTask(payload, taskId, { message: 'Starting backup', status: 'running' })\n }\n\n if (cron) {\n const blobs = await storage.list('backups/cron-')\n const sorted = blobs.sort(\n (a, b) => new Date(b.uploadedAt).getTime() - new Date(a.uploadedAt).getTime(),\n )\n const oldest = sorted.slice(Math.max(0, resolvedBackupsToKeep - 1))\n if (oldest.length > 0) {\n payload.logger.info({ count: oldest.length }, '[backup] Pruning old cron backups')\n if (taskId) {\n await updateBackupTask(payload, taskId, {\n message: `Pruning ${oldest.length} old cron backup${oldest.length === 1 ? '' : 's'}`,\n })\n }\n }\n for (const blob of oldest) {\n await storage.del({ pathname: blob.pathname, url: blob.url })\n payload.logger.info({ pathname: blob.pathname }, '[backup] Deleted old backup')\n }\n }\n\n if (taskId) {\n await updateBackupTask(payload, taskId, { message: 'Dumping tables' })\n }\n const { doc, mediaPathnames } = await dumpDatabase(payload, {\n collectMedia: includeMedia,\n onTable: async (table, rowCount) => {\n payload.logger.debug({ rows: rowCount, table }, '[backup] Table dumped')\n if (taskId) {\n await updateBackupTask(payload, taskId, {\n message: `Dumped table ${table} (${rowCount} rows)`,\n })\n }\n },\n skipTables: skipCollections,\n })\n\n const databaseFile = serializeBackupDocument(doc)\n const includedTableCount = Object.keys(doc.tables).length\n const backupTimestampMs = Date.now()\n\n if (includeMedia) {\n payload.logger.info({ files: mediaPathnames.length }, '[backup] Bundling media files')\n if (taskId) {\n await updateBackupTask(payload, taskId, { message: 'Bundling media files into archive' })\n }\n }\n\n const backupFile =\n includeMedia ?\n await createMediaBackupFile(databaseFile, mediaPathnames, token, undefined, payload)\n : databaseFile\n const name = `backups/${createBlobName(\n type,\n currentDbName,\n currentHostname,\n includedTableCount,\n backupTimestampMs,\n includeMedia ? 'tar.gz' : 'json',\n label || undefined,\n )}`\n\n payload.logger.info({ name }, '[backup] Uploading backup to blob storage')\n if (taskId) {\n await updateBackupTask(payload, taskId, { message: 'Uploading backup to blob storage' })\n }\n await storage.put(name, backupFile)\n\n payload.logger.info({ name, durationMs: Date.now() - t0 }, '[backup] Backup complete')\n}\n"],"names":["list","createBlobName","getCurrentDbName","getCurrentHostname","sanitizeBackupLabel","createTarGzip","readBackupBlobContentFlexible","getResolvedCronBackupSettings","resolveBackupBlobToken","getPgDb","listTables","qi","qualified","withClient","ARCHIVE_FORMAT","ARCHIVE_VERSION","DATABASE_FILE_NAME","MEDIA_PREFIX","serializeBackupDocument","getBackupStorageKind","resolveBackupStorage","resolveTableOwners","updateBackupTask","resolveBackupListToken","payload","explicitToken","t","trim","listBackups","options","kind","token","blobToken","resolveBlobToken","length","undefined","createMediaBackupFile","databaseFile","mediaPathnames","backupBlobToken","mediaListToken","envMedia","process","env","BLOB_READ_WRITE_TOKEN","tokenForMedia","unique","Set","filter","Boolean","mediaFiles","Promise","all","map","pathname","matchingFiles","limit","prefix","blob","blobs","find","b","logger","warn","filename","content","downloadUrl","name","err","Buffer","from","dumpDatabase","pool","schema","tableNameMap","skip","skipTables","client","query","rows","ver","allTables","tables","table","has","debug","rowCount","Number","n","onTable","collectMedia","owners","Object","keys","uploadSlugs","config","collections","c","upload","slug","owner","get","versions","push","readMediaPathnames","doc","createdAt","Date","toISOString","format","serverVersion","v","version","catch","cols","names","fileCols","test","prefixExpr","out","col","r","p","replace","f","createBackup","backupsToKeep","cron","includeMedia","skipCollections","taskId","label","blobAccess","resolvedBackupsToKeep","BACKUPS_TO_KEEP","storage","currentHostname","currentDbName","type","t0","now","info","blacklist","db","host","message","status","sorted","sort","a","uploadedAt","getTime","oldest","slice","Math","max","count","del","url","includedTableCount","backupTimestampMs","files","backupFile","put","durationMs"],"mappings":"AAEA,SAASA,IAAI,QAAQ,eAAc;AAEnC,SACEC,cAAc,EACdC,gBAAgB,EAChBC,kBAAkB,EAClBC,mBAAmB,QACd,iBAAgB;AACvB,SAASC,aAAa,QAAQ,YAAW;AACzC,SAAqCC,6BAA6B,QAAQ,iBAAgB;AAC1F,SAASC,6BAA6B,EAAEC,sBAAsB,QAAQ,mBAAkB;AACxF,SAASC,OAAO,EAAEC,UAAU,EAAiBC,EAAE,EAAEC,SAAS,EAAEC,UAAU,QAAQ,OAAM;AACpF,SACEC,cAAc,EACdC,eAAe,EACfC,kBAAkB,EAClBC,YAAY,EAEZC,uBAAuB,QAClB,cAAa;AACpB,SAASC,oBAAoB,EAAEC,oBAAoB,QAAQ,YAAW;AACtE,SAASC,kBAAkB,QAAQ,gBAAe;AAClD,SAASC,gBAAgB,QAAQ,iBAAgB;AAEjD,SAASN,kBAAkB,QAAQ,cAAa;AAEhD;;;;CAIC,GACD,OAAO,eAAeO,uBACpBC,OAAgB,EAChBC,aAAsB;IAEtB,MAAMC,IAAID,eAAeE;IACzB,IAAID,GAAG;QACL,OAAOA;IACT;IACA,OAAOlB,uBAAuB,MAAMD,8BAA8BiB,UAAUG,IAAI;AAClF;AAEA,OAAO,eAAeC,YACpBJ,OAAgB,EAChBK,UAMI,CAAC,CAAC;IAEN,MAAMC,OAAOX;IACb,IAAIW,SAAS,eAAe;QAC1B,MAAMC,QAAQ,MAAMR,uBAAuBC,SAASK,QAAQG,SAAS;QACrE,IAAI,CAACD,OAAO;YACV,OAAO,EAAE;QACX;QACA,OAAOX,qBAAqB;YAAEY,WAAWD;YAAOD;QAAK,GAAG9B,IAAI,CAAC;IAC/D;IACA,OAAOoB,qBAAqB;QAAEU;IAAK,GAAG9B,IAAI,CAAC;AAC7C;AAEA,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BAAUH;YAAM,GAAG;YAChD,IAAI+C,QAAQ;gBACV,MAAM5G,iBAAiBE,SAAS0G,QAAQ;oBACtCe,SAAS,CAAC,aAAa,EAAE9D,MAAM,EAAE,EAAEG,SAAS,MAAM,CAAC;gBACrD;YACF;QACF;QACAV,YAAYqD;IACd;IAEA,MAAM5F,eAAenB,wBAAwBuF;IAC7C,MAAMsD,qBAAqBnE,OAAOC,IAAI,CAACY,IAAIvB,MAAM,EAAEhD,MAAM;IACzD,MAAM8H,oBAAoBrD,KAAKiC,GAAG;IAElC,IAAIZ,cAAc;QAChBxG,QAAQsC,MAAM,CAAC+E,IAAI,CAAC;YAAEoB,OAAO3H,eAAeJ,MAAM;QAAC,GAAG;QACtD,IAAIgG,QAAQ;YACV,MAAM5G,iBAAiBE,SAAS0G,QAAQ;gBAAEe,SAAS;YAAoC;QACzF;IACF;IAEA,MAAMiB,aACJlC,eACE,MAAM5F,sBAAsBC,cAAcC,gBAAgBP,OAAOI,WAAWX,WAC5Ea;IACJ,MAAM8B,OAAO,CAAC,QAAQ,EAAElE,eACtByI,MACAD,eACAD,iBACAuB,oBACAC,mBACAhC,eAAe,WAAW,QAC1BG,SAAShG,YACR;IAEHX,QAAQsC,MAAM,CAAC+E,IAAI,CAAC;QAAE1E;IAAK,GAAG;IAC9B,IAAI+D,QAAQ;QACV,MAAM5G,iBAAiBE,SAAS0G,QAAQ;YAAEe,SAAS;QAAmC;IACxF;IACA,MAAMV,QAAQ4B,GAAG,CAAChG,MAAM+F;IAExB1I,QAAQsC,MAAM,CAAC+E,IAAI,CAAC;QAAE1E;QAAMiG,YAAYzD,KAAKiC,GAAG,KAAKD;IAAG,GAAG;AAC7D"}
@@ -0,0 +1,15 @@
1
+ import { type BackupBlobAccessLevel } from './backupBlobIO.js';
2
+ export interface ReadBackupArchiveBytesOptions {
3
+ /** Provider-agnostic archive pathname (e.g. `backups/manual---db---host---1.json`). */
4
+ archivePathname?: string;
5
+ backupRead?: {
6
+ pathname: string;
7
+ token: string;
8
+ };
9
+ blobAccess?: BackupBlobAccessLevel;
10
+ blobToken?: string;
11
+ }
12
+ /** Prefer `archivePathname` for file-type detection when the download URL may be stale or opaque. */
13
+ export declare function resolveArchiveFileReference(downloadUrl: string, archivePathname?: string): string;
14
+ /** Loads a backup archive into memory (Vercel token read or S3 pathname read, else fetch). */
15
+ export declare function readBackupArchiveBytes(downloadUrl: string, options?: ReadBackupArchiveBytesOptions): Promise<Buffer>;
@@ -0,0 +1,30 @@
1
+ import { readBackupBlobContentFlexible } from './backupBlobIO.js';
2
+ import { getBackupStorageKind, resolveBackupStorage } from './storage/index.js';
3
+ /** Prefer `archivePathname` for file-type detection when the download URL may be stale or opaque. */ export function resolveArchiveFileReference(downloadUrl, archivePathname) {
4
+ if (typeof archivePathname === 'string' && archivePathname.startsWith('backups/')) {
5
+ return archivePathname;
6
+ }
7
+ return downloadUrl.split('?')[0] ?? downloadUrl;
8
+ }
9
+ /** Loads a backup archive into memory (Vercel token read or S3 pathname read, else fetch). */ export async function readBackupArchiveBytes(downloadUrl, options = {}) {
10
+ if (options.backupRead) {
11
+ return readBackupBlobContentFlexible(options.backupRead.pathname, downloadUrl, options.backupRead.token);
12
+ }
13
+ const archivePathname = options.archivePathname;
14
+ if (getBackupStorageKind() === 's3' && typeof archivePathname === 'string' && archivePathname.startsWith('backups/')) {
15
+ const storage = resolveBackupStorage({
16
+ blobAccess: options.blobAccess,
17
+ blobToken: options.blobToken
18
+ });
19
+ return storage.read({
20
+ pathname: archivePathname
21
+ });
22
+ }
23
+ const res = await fetch(downloadUrl);
24
+ if (!res.ok) {
25
+ throw new Error(`Failed to download backup (${res.status})`);
26
+ }
27
+ return Buffer.from(await res.arrayBuffer());
28
+ }
29
+
30
+ //# sourceMappingURL=backupArchiveRead.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/core/backupArchiveRead.ts"],"sourcesContent":["import { type BackupBlobAccessLevel, readBackupBlobContentFlexible } from './backupBlobIO'\nimport { getBackupStorageKind, resolveBackupStorage } from './storage'\n\nexport interface ReadBackupArchiveBytesOptions {\n /** Provider-agnostic archive pathname (e.g. `backups/manual---db---host---1.json`). */\n archivePathname?: string\n backupRead?: { pathname: string; token: string }\n blobAccess?: BackupBlobAccessLevel\n blobToken?: string\n}\n\n/** Prefer `archivePathname` for file-type detection when the download URL may be stale or opaque. */\nexport function resolveArchiveFileReference(downloadUrl: string, archivePathname?: string): string {\n if (typeof archivePathname === 'string' && archivePathname.startsWith('backups/')) {\n return archivePathname\n }\n return downloadUrl.split('?')[0] ?? downloadUrl\n}\n\n/** Loads a backup archive into memory (Vercel token read or S3 pathname read, else fetch). */\nexport async function readBackupArchiveBytes(\n downloadUrl: string,\n options: ReadBackupArchiveBytesOptions = {},\n): Promise<Buffer> {\n if (options.backupRead) {\n return readBackupBlobContentFlexible(\n options.backupRead.pathname,\n downloadUrl,\n options.backupRead.token,\n )\n }\n\n const archivePathname = options.archivePathname\n if (\n getBackupStorageKind() === 's3' &&\n typeof archivePathname === 'string' &&\n archivePathname.startsWith('backups/')\n ) {\n const storage = resolveBackupStorage({\n blobAccess: options.blobAccess,\n blobToken: options.blobToken,\n })\n return storage.read({ pathname: archivePathname })\n }\n\n const res = await fetch(downloadUrl)\n if (!res.ok) {\n throw new Error(`Failed to download backup (${res.status})`)\n }\n return Buffer.from(await res.arrayBuffer())\n}\n"],"names":["readBackupBlobContentFlexible","getBackupStorageKind","resolveBackupStorage","resolveArchiveFileReference","downloadUrl","archivePathname","startsWith","split","readBackupArchiveBytes","options","backupRead","pathname","token","storage","blobAccess","blobToken","read","res","fetch","ok","Error","status","Buffer","from","arrayBuffer"],"mappings":"AAAA,SAAqCA,6BAA6B,QAAQ,iBAAgB;AAC1F,SAASC,oBAAoB,EAAEC,oBAAoB,QAAQ,YAAW;AAUtE,mGAAmG,GACnG,OAAO,SAASC,4BAA4BC,WAAmB,EAAEC,eAAwB;IACvF,IAAI,OAAOA,oBAAoB,YAAYA,gBAAgBC,UAAU,CAAC,aAAa;QACjF,OAAOD;IACT;IACA,OAAOD,YAAYG,KAAK,CAAC,IAAI,CAAC,EAAE,IAAIH;AACtC;AAEA,4FAA4F,GAC5F,OAAO,eAAeI,uBACpBJ,WAAmB,EACnBK,UAAyC,CAAC,CAAC;IAE3C,IAAIA,QAAQC,UAAU,EAAE;QACtB,OAAOV,8BACLS,QAAQC,UAAU,CAACC,QAAQ,EAC3BP,aACAK,QAAQC,UAAU,CAACE,KAAK;IAE5B;IAEA,MAAMP,kBAAkBI,QAAQJ,eAAe;IAC/C,IACEJ,2BAA2B,QAC3B,OAAOI,oBAAoB,YAC3BA,gBAAgBC,UAAU,CAAC,aAC3B;QACA,MAAMO,UAAUX,qBAAqB;YACnCY,YAAYL,QAAQK,UAAU;YAC9BC,WAAWN,QAAQM,SAAS;QAC9B;QACA,OAAOF,QAAQG,IAAI,CAAC;YAAEL,UAAUN;QAAgB;IAClD;IAEA,MAAMY,MAAM,MAAMC,MAAMd;IACxB,IAAI,CAACa,IAAIE,EAAE,EAAE;QACX,MAAM,IAAIC,MAAM,CAAC,2BAA2B,EAAEH,IAAII,MAAM,CAAC,CAAC,CAAC;IAC7D;IACA,OAAOC,OAAOC,IAAI,CAAC,MAAMN,IAAIO,WAAW;AAC1C"}
@@ -0,0 +1,54 @@
1
+ /** Vercel Blob access for backup archives under `backups/`. */
2
+ export type BackupBlobAccessLevel = 'private' | 'public';
3
+ /**
4
+ * Returns the blob pathname (no leading slash) for a trusted Vercel Blob HTTPS URL, or null.
5
+ * The URL's path component is percent-decoded once so the result matches the literal pathname
6
+ * stored by Vercel Blob (e.g. blobs whose own pathname contains `%2F` are served from a URL that
7
+ * double-encodes it to `%252F`).
8
+ */
9
+ export declare function vercelBlobPathnameFromUrl(urlStr: string): null | string;
10
+ export declare function isTrustedBackupBlobReference(urlStr: string, expectedPathname: string): boolean;
11
+ export type BackupBlobDownloadStream = {
12
+ contentType: string;
13
+ stream: ReadableStream<Uint8Array>;
14
+ };
15
+ /**
16
+ * Opens a readable stream for a backup object (public or private). Prefers the `downloadUrl` /
17
+ * `blobUrl` returned by `list()` because Vercel Blob already encodes the pathname correctly there
18
+ * (some legacy backups store literal `%2F` sequences inside the pathname, which the SDK's
19
+ * pathname-to-URL construction would misinterpret).
20
+ */
21
+ export declare function streamBackupBlobForDownload(options: {
22
+ blobUrl?: null | string;
23
+ downloadUrl?: null | string;
24
+ pathname: string;
25
+ preferredAccess: BackupBlobAccessLevel;
26
+ token: string;
27
+ }): Promise<BackupBlobDownloadStream | null>;
28
+ export declare function bufferFromWebReadableStream(stream: ReadableStream<Uint8Array>): Promise<Buffer>;
29
+ /**
30
+ * Read a backup blob using the trusted `downloadUrl` returned by `list()`. The Bearer token is
31
+ * always attached for Vercel Blob hosts; this works for public blobs (token ignored) and is
32
+ * required for private blobs.
33
+ */
34
+ export declare function readBackupBlobContent(options: {
35
+ /** Kept for API compatibility — the fetch path is the same for public and private stores. */
36
+ access: BackupBlobAccessLevel;
37
+ downloadUrl: string;
38
+ pathname: string;
39
+ token: string;
40
+ }): Promise<Buffer>;
41
+ /**
42
+ * Flexible read used during restore/preview/transfer where the source store visibility may differ
43
+ * from the new one. Always tries authenticated access first (correct for private stores and
44
+ * harmless for public ones). Falls back to anonymous fetch only when the URL is not a Vercel
45
+ * Blob URL, so tokens never leak to arbitrary hosts.
46
+ */
47
+ export declare function readBackupBlobContentFlexible(pathname: string, downloadUrl: string, token: string, _sourceAccessHint?: BackupBlobAccessLevel): Promise<Buffer>;
48
+ /**
49
+ * Uploads a backup blob with the preferred access level and transparently retries the other level
50
+ * if the Vercel Blob store rejects the preferred one (e.g. legacy public-only stores reject
51
+ * `access: 'private'`). Returns the effective access level that succeeded so callers can log/track
52
+ * it; throws the original error if both attempts fail.
53
+ */
54
+ export declare function putBackupBlobContent(pathname: string, body: Buffer | string | Uint8Array, token: string | undefined, access: BackupBlobAccessLevel): Promise<BackupBlobAccessLevel>;
@@ -0,0 +1,179 @@
1
+ import { put } from '@vercel/blob';
2
+ /**
3
+ * Returns the blob pathname (no leading slash) for a trusted Vercel Blob HTTPS URL, or null.
4
+ * The URL's path component is percent-decoded once so the result matches the literal pathname
5
+ * stored by Vercel Blob (e.g. blobs whose own pathname contains `%2F` are served from a URL that
6
+ * double-encodes it to `%252F`).
7
+ */ export function vercelBlobPathnameFromUrl(urlStr) {
8
+ try {
9
+ const u = new URL(urlStr);
10
+ if (u.protocol !== 'https:') {
11
+ return null;
12
+ }
13
+ if (!u.hostname.endsWith('.blob.vercel-storage.com')) {
14
+ return null;
15
+ }
16
+ const raw = u.pathname.replace(/^\//, '');
17
+ if (raw.length === 0) {
18
+ return null;
19
+ }
20
+ try {
21
+ return decodeURIComponent(raw);
22
+ } catch {
23
+ return raw;
24
+ }
25
+ } catch {
26
+ return null;
27
+ }
28
+ }
29
+ export function isTrustedBackupBlobReference(urlStr, expectedPathname) {
30
+ const fromUrl = vercelBlobPathnameFromUrl(urlStr);
31
+ return Boolean(fromUrl && fromUrl === expectedPathname);
32
+ }
33
+ /** True when the URL points to any Vercel Blob host (public or private). */ function isVercelBlobHost(urlStr) {
34
+ try {
35
+ const u = new URL(urlStr);
36
+ return u.protocol === 'https:' && u.hostname.endsWith('.blob.vercel-storage.com');
37
+ } catch {
38
+ return false;
39
+ }
40
+ }
41
+ /**
42
+ * Fetches a Vercel Blob URL with the Bearer token attached when the host belongs to Vercel Blob.
43
+ * Works transparently for public stores (token is ignored) and private stores (token is required).
44
+ * Tokens are never sent to non-Vercel hosts.
45
+ */ async function fetchBackupBlobUrl(url, token) {
46
+ const init = token && isVercelBlobHost(url) ? {
47
+ headers: {
48
+ authorization: `Bearer ${token}`
49
+ }
50
+ } : undefined;
51
+ return fetch(url, init);
52
+ }
53
+ /**
54
+ * Opens a readable stream for a backup object (public or private). Prefers the `downloadUrl` /
55
+ * `blobUrl` returned by `list()` because Vercel Blob already encodes the pathname correctly there
56
+ * (some legacy backups store literal `%2F` sequences inside the pathname, which the SDK's
57
+ * pathname-to-URL construction would misinterpret).
58
+ */ export async function streamBackupBlobForDownload(options) {
59
+ const { blobUrl, downloadUrl, pathname, token } = options;
60
+ const candidates = [];
61
+ if (downloadUrl && isTrustedBackupBlobReference(downloadUrl, pathname)) {
62
+ candidates.push(downloadUrl);
63
+ }
64
+ if (blobUrl && isTrustedBackupBlobReference(blobUrl, pathname)) {
65
+ candidates.push(blobUrl);
66
+ }
67
+ for (const target of candidates){
68
+ try {
69
+ const res = await fetchBackupBlobUrl(target, token);
70
+ if (res.ok && res.body) {
71
+ return {
72
+ contentType: res.headers.get('content-type') || 'application/octet-stream',
73
+ stream: res.body
74
+ };
75
+ }
76
+ } catch {
77
+ /* try next candidate */ }
78
+ }
79
+ return null;
80
+ }
81
+ export async function bufferFromWebReadableStream(stream) {
82
+ const reader = stream.getReader();
83
+ const chunks = [];
84
+ while(true){
85
+ const { done, value } = await reader.read();
86
+ if (done) {
87
+ break;
88
+ }
89
+ if (value) {
90
+ chunks.push(Buffer.from(value));
91
+ }
92
+ }
93
+ return Buffer.concat(chunks);
94
+ }
95
+ /**
96
+ * Read a backup blob using the trusted `downloadUrl` returned by `list()`. The Bearer token is
97
+ * always attached for Vercel Blob hosts; this works for public blobs (token ignored) and is
98
+ * required for private blobs.
99
+ */ export async function readBackupBlobContent(options) {
100
+ const { downloadUrl, pathname, token } = options;
101
+ const res = await fetchBackupBlobUrl(downloadUrl, token);
102
+ if (res.ok) {
103
+ return Buffer.from(await res.arrayBuffer());
104
+ }
105
+ throw new Error(`Failed to read backup blob (${pathname}): HTTP ${res.status}`);
106
+ }
107
+ /**
108
+ * Flexible read used during restore/preview/transfer where the source store visibility may differ
109
+ * from the new one. Always tries authenticated access first (correct for private stores and
110
+ * harmless for public ones). Falls back to anonymous fetch only when the URL is not a Vercel
111
+ * Blob URL, so tokens never leak to arbitrary hosts.
112
+ */ export async function readBackupBlobContentFlexible(pathname, downloadUrl, token, _sourceAccessHint) {
113
+ try {
114
+ const res = await fetchBackupBlobUrl(downloadUrl, token);
115
+ if (res.ok) {
116
+ return Buffer.from(await res.arrayBuffer());
117
+ }
118
+ } catch {
119
+ /* try anonymous fallback */ }
120
+ if (!isVercelBlobHost(downloadUrl)) {
121
+ try {
122
+ const res = await fetch(downloadUrl);
123
+ if (res.ok) {
124
+ return Buffer.from(await res.arrayBuffer());
125
+ }
126
+ } catch {
127
+ /* fall through to error */ }
128
+ }
129
+ throw new Error(`Failed to read backup blob ${pathname}`);
130
+ }
131
+ /**
132
+ * Uploads a backup blob with the preferred access level and transparently retries the other level
133
+ * if the Vercel Blob store rejects the preferred one (e.g. legacy public-only stores reject
134
+ * `access: 'private'`). Returns the effective access level that succeeded so callers can log/track
135
+ * it; throws the original error if both attempts fail.
136
+ */ export async function putBackupBlobContent(pathname, body, token, access) {
137
+ const order = access === 'private' ? [
138
+ 'private',
139
+ 'public'
140
+ ] : [
141
+ 'public',
142
+ 'private'
143
+ ];
144
+ let firstError;
145
+ for (const attempt of order){
146
+ try {
147
+ await put(pathname, body, {
148
+ access: attempt,
149
+ addRandomSuffix: false,
150
+ allowOverwrite: true,
151
+ ...token ? {
152
+ token
153
+ } : {}
154
+ });
155
+ return attempt;
156
+ } catch (error) {
157
+ if (firstError === undefined) {
158
+ firstError = error;
159
+ }
160
+ if (!looksLikeAccessModeMismatch(error)) {
161
+ throw error;
162
+ }
163
+ }
164
+ }
165
+ throw firstError instanceof Error ? firstError : new Error('Failed to upload backup blob');
166
+ }
167
+ /** Heuristic for Vercel Blob errors that indicate the store rejects the chosen access level. */ function looksLikeAccessModeMismatch(error) {
168
+ const msg = error instanceof Error ? error.message : typeof error === 'string' ? error : error == null ? '' : (()=>{
169
+ try {
170
+ return JSON.stringify(error);
171
+ } catch {
172
+ return 'unknown';
173
+ }
174
+ })();
175
+ const lower = msg.toLowerCase();
176
+ return lower.includes('access') && (lower.includes('public') || lower.includes('private') || lower.includes('not support') || lower.includes('invalid'));
177
+ }
178
+
179
+ //# sourceMappingURL=backupBlobIO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/core/backupBlobIO.ts"],"sourcesContent":["import { put } from '@vercel/blob'\n\n/** Vercel Blob access for backup archives under `backups/`. */\nexport type BackupBlobAccessLevel = 'private' | 'public'\n\n/**\n * Returns the blob pathname (no leading slash) for a trusted Vercel Blob HTTPS URL, or null.\n * The URL's path component is percent-decoded once so the result matches the literal pathname\n * stored by Vercel Blob (e.g. blobs whose own pathname contains `%2F` are served from a URL that\n * double-encodes it to `%252F`).\n */\nexport function vercelBlobPathnameFromUrl(urlStr: string): null | string {\n try {\n const u = new URL(urlStr)\n if (u.protocol !== 'https:') {\n return null\n }\n if (!u.hostname.endsWith('.blob.vercel-storage.com')) {\n return null\n }\n const raw = u.pathname.replace(/^\\//, '')\n if (raw.length === 0) {\n return null\n }\n try {\n return decodeURIComponent(raw)\n } catch {\n return raw\n }\n } catch {\n return null\n }\n}\n\nexport function isTrustedBackupBlobReference(urlStr: string, expectedPathname: string): boolean {\n const fromUrl = vercelBlobPathnameFromUrl(urlStr)\n return Boolean(fromUrl && fromUrl === expectedPathname)\n}\n\n/** True when the URL points to any Vercel Blob host (public or private). */\nfunction isVercelBlobHost(urlStr: string): boolean {\n try {\n const u = new URL(urlStr)\n return u.protocol === 'https:' && u.hostname.endsWith('.blob.vercel-storage.com')\n } catch {\n return false\n }\n}\n\n/**\n * Fetches a Vercel Blob URL with the Bearer token attached when the host belongs to Vercel Blob.\n * Works transparently for public stores (token is ignored) and private stores (token is required).\n * Tokens are never sent to non-Vercel hosts.\n */\nasync function fetchBackupBlobUrl(url: string, token: string): Promise<Response> {\n const init: RequestInit | undefined =\n token && isVercelBlobHost(url) ? { headers: { authorization: `Bearer ${token}` } } : undefined\n return fetch(url, init)\n}\n\nexport type BackupBlobDownloadStream = {\n contentType: string\n stream: ReadableStream<Uint8Array>\n}\n\n/**\n * Opens a readable stream for a backup object (public or private). Prefers the `downloadUrl` /\n * `blobUrl` returned by `list()` because Vercel Blob already encodes the pathname correctly there\n * (some legacy backups store literal `%2F` sequences inside the pathname, which the SDK's\n * pathname-to-URL construction would misinterpret).\n */\nexport async function streamBackupBlobForDownload(options: {\n blobUrl?: null | string\n downloadUrl?: null | string\n pathname: string\n preferredAccess: BackupBlobAccessLevel\n token: string\n}): Promise<BackupBlobDownloadStream | null> {\n const { blobUrl, downloadUrl, pathname, token } = options\n const candidates: string[] = []\n if (downloadUrl && isTrustedBackupBlobReference(downloadUrl, pathname)) {\n candidates.push(downloadUrl)\n }\n if (blobUrl && isTrustedBackupBlobReference(blobUrl, pathname)) {\n candidates.push(blobUrl)\n }\n\n for (const target of candidates) {\n try {\n const res = await fetchBackupBlobUrl(target, token)\n if (res.ok && res.body) {\n return {\n contentType: res.headers.get('content-type') || 'application/octet-stream',\n stream: res.body,\n }\n }\n } catch {\n /* try next candidate */\n }\n }\n\n return null\n}\n\nexport async function bufferFromWebReadableStream(\n stream: ReadableStream<Uint8Array>,\n): Promise<Buffer> {\n const reader = stream.getReader()\n const chunks: Buffer[] = []\n while (true) {\n const { done, value } = await reader.read()\n if (done) {\n break\n }\n if (value) {\n chunks.push(Buffer.from(value))\n }\n }\n return Buffer.concat(chunks)\n}\n\n/**\n * Read a backup blob using the trusted `downloadUrl` returned by `list()`. The Bearer token is\n * always attached for Vercel Blob hosts; this works for public blobs (token ignored) and is\n * required for private blobs.\n */\nexport async function readBackupBlobContent(options: {\n /** Kept for API compatibility — the fetch path is the same for public and private stores. */\n access: BackupBlobAccessLevel\n downloadUrl: string\n pathname: string\n token: string\n}): Promise<Buffer> {\n const { downloadUrl, pathname, token } = options\n const res = await fetchBackupBlobUrl(downloadUrl, token)\n if (res.ok) {\n return Buffer.from(await res.arrayBuffer())\n }\n throw new Error(`Failed to read backup blob (${pathname}): HTTP ${res.status}`)\n}\n\n/**\n * Flexible read used during restore/preview/transfer where the source store visibility may differ\n * from the new one. Always tries authenticated access first (correct for private stores and\n * harmless for public ones). Falls back to anonymous fetch only when the URL is not a Vercel\n * Blob URL, so tokens never leak to arbitrary hosts.\n */\nexport async function readBackupBlobContentFlexible(\n pathname: string,\n downloadUrl: string,\n token: string,\n _sourceAccessHint?: BackupBlobAccessLevel,\n): Promise<Buffer> {\n try {\n const res = await fetchBackupBlobUrl(downloadUrl, token)\n if (res.ok) {\n return Buffer.from(await res.arrayBuffer())\n }\n } catch {\n /* try anonymous fallback */\n }\n\n if (!isVercelBlobHost(downloadUrl)) {\n try {\n const res = await fetch(downloadUrl)\n if (res.ok) {\n return Buffer.from(await res.arrayBuffer())\n }\n } catch {\n /* fall through to error */\n }\n }\n\n throw new Error(`Failed to read backup blob ${pathname}`)\n}\n\n/**\n * Uploads a backup blob with the preferred access level and transparently retries the other level\n * if the Vercel Blob store rejects the preferred one (e.g. legacy public-only stores reject\n * `access: 'private'`). Returns the effective access level that succeeded so callers can log/track\n * it; throws the original error if both attempts fail.\n */\nexport async function putBackupBlobContent(\n pathname: string,\n body: Buffer | string | Uint8Array,\n token: string | undefined,\n access: BackupBlobAccessLevel,\n): Promise<BackupBlobAccessLevel> {\n const order: BackupBlobAccessLevel[] =\n access === 'private' ? ['private', 'public'] : ['public', 'private']\n let firstError: unknown\n for (const attempt of order) {\n try {\n await put(pathname, body, {\n access: attempt,\n addRandomSuffix: false,\n allowOverwrite: true,\n ...(token ? { token } : {}),\n })\n return attempt\n } catch (error) {\n if (firstError === undefined) {\n firstError = error\n }\n if (!looksLikeAccessModeMismatch(error)) {\n throw error\n }\n }\n }\n throw firstError instanceof Error ? firstError : new Error('Failed to upload backup blob')\n}\n\n/** Heuristic for Vercel Blob errors that indicate the store rejects the chosen access level. */\nfunction looksLikeAccessModeMismatch(error: unknown): boolean {\n const msg =\n error instanceof Error ? error.message\n : typeof error === 'string' ? error\n : error == null ? ''\n : (() => {\n try {\n return JSON.stringify(error)\n } catch {\n return 'unknown'\n }\n })()\n const lower = msg.toLowerCase()\n return (\n lower.includes('access') &&\n (lower.includes('public') ||\n lower.includes('private') ||\n lower.includes('not support') ||\n lower.includes('invalid'))\n )\n}\n"],"names":["put","vercelBlobPathnameFromUrl","urlStr","u","URL","protocol","hostname","endsWith","raw","pathname","replace","length","decodeURIComponent","isTrustedBackupBlobReference","expectedPathname","fromUrl","Boolean","isVercelBlobHost","fetchBackupBlobUrl","url","token","init","headers","authorization","undefined","fetch","streamBackupBlobForDownload","options","blobUrl","downloadUrl","candidates","push","target","res","ok","body","contentType","get","stream","bufferFromWebReadableStream","reader","getReader","chunks","done","value","read","Buffer","from","concat","readBackupBlobContent","arrayBuffer","Error","status","readBackupBlobContentFlexible","_sourceAccessHint","putBackupBlobContent","access","order","firstError","attempt","addRandomSuffix","allowOverwrite","error","looksLikeAccessModeMismatch","msg","message","JSON","stringify","lower","toLowerCase","includes"],"mappings":"AAAA,SAASA,GAAG,QAAQ,eAAc;AAKlC;;;;;CAKC,GACD,OAAO,SAASC,0BAA0BC,MAAc;IACtD,IAAI;QACF,MAAMC,IAAI,IAAIC,IAAIF;QAClB,IAAIC,EAAEE,QAAQ,KAAK,UAAU;YAC3B,OAAO;QACT;QACA,IAAI,CAACF,EAAEG,QAAQ,CAACC,QAAQ,CAAC,6BAA6B;YACpD,OAAO;QACT;QACA,MAAMC,MAAML,EAAEM,QAAQ,CAACC,OAAO,CAAC,OAAO;QACtC,IAAIF,IAAIG,MAAM,KAAK,GAAG;YACpB,OAAO;QACT;QACA,IAAI;YACF,OAAOC,mBAAmBJ;QAC5B,EAAE,OAAM;YACN,OAAOA;QACT;IACF,EAAE,OAAM;QACN,OAAO;IACT;AACF;AAEA,OAAO,SAASK,6BAA6BX,MAAc,EAAEY,gBAAwB;IACnF,MAAMC,UAAUd,0BAA0BC;IAC1C,OAAOc,QAAQD,WAAWA,YAAYD;AACxC;AAEA,0EAA0E,GAC1E,SAASG,iBAAiBf,MAAc;IACtC,IAAI;QACF,MAAMC,IAAI,IAAIC,IAAIF;QAClB,OAAOC,EAAEE,QAAQ,KAAK,YAAYF,EAAEG,QAAQ,CAACC,QAAQ,CAAC;IACxD,EAAE,OAAM;QACN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