payload-plugin-backup-postgres 0.0.0-stage → 0.2.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 +75 -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,222 @@
1
+ import { readBackupArchiveBytes, resolveArchiveFileReference } from './backupArchiveRead.js';
2
+ import { getPgDb } from './db.js';
3
+ import { loadPgArchive } from './pgArchive.js';
4
+ import { resolveTableOwners, rootTablesForSlug } from './tableGroups.js';
5
+ /** Payload slugs whose replacement invalidates the current admin session. */ const AUTH_SESSION_SLUGS = new Set([
6
+ 'payload-preferences',
7
+ 'roles',
8
+ 'sessions',
9
+ 'users'
10
+ ]);
11
+ /** Groups never listed in the UI (plugin-internal progress rows). */ const DEFAULT_EXCLUDED_GROUPS = new Set([
12
+ 'backup-tasks'
13
+ ]);
14
+ function pickLocalizedLabel(labels, preferredLocales) {
15
+ if (!labels || typeof labels !== 'object') {
16
+ return undefined;
17
+ }
18
+ const l = labels;
19
+ const pickField = (field)=>{
20
+ if (typeof field === 'string') {
21
+ return field;
22
+ }
23
+ if (field && typeof field === 'object') {
24
+ const map = field;
25
+ for (const loc of preferredLocales){
26
+ const v = map[loc];
27
+ if (v) {
28
+ return v;
29
+ }
30
+ }
31
+ const first = Object.values(map).find(Boolean);
32
+ return first;
33
+ }
34
+ return undefined;
35
+ };
36
+ return pickField(l.plural) || pickField(l.singular);
37
+ }
38
+ function humanizeSlug(slug) {
39
+ return slug.split('-').map((w)=>w ? w.charAt(0).toUpperCase() + w.slice(1) : '').join(' ');
40
+ }
41
+ /** Collections shown in the default Payload admin sidebar: config order, skipping `admin.hidden`. */ function getNavVisibleCollections(payload) {
42
+ return payload.config.collections.filter((c)=>c.admin?.hidden !== true);
43
+ }
44
+ /**
45
+ * Index in sidebar order, or `null` if the group is not a visible nav collection
46
+ * (hidden config, unknown table, global, etc.).
47
+ */ export function navVisibleCollectionOrderIndex(payload, groupId) {
48
+ const visible = getNavVisibleCollections(payload);
49
+ const idx = visible.findIndex((c)=>c.slug === groupId);
50
+ return idx === -1 ? null : idx;
51
+ }
52
+ function sortPreviewGroupsLikeAdminNav(payload, groups, preferredLocales) {
53
+ const locale = preferredLocales[0] ?? 'en';
54
+ groups.sort((a, b)=>{
55
+ const ia = navVisibleCollectionOrderIndex(payload, a.groupId);
56
+ const ib = navVisibleCollectionOrderIndex(payload, b.groupId);
57
+ if (ia !== null && ib !== null && ia !== ib) {
58
+ return ia - ib;
59
+ }
60
+ if (ia !== null && ib === null) {
61
+ return -1;
62
+ }
63
+ if (ia === null && ib !== null) {
64
+ return 1;
65
+ }
66
+ return a.displayTitle.localeCompare(b.displayTitle, locale);
67
+ });
68
+ }
69
+ function buildDisplayTitle(payload, groupSlug, preferredLocales) {
70
+ const col = payload.config.collections.find((c)=>c.slug === groupSlug);
71
+ const glob = payload.config.globals?.find((g)=>g.slug === groupSlug);
72
+ const label = pickLocalizedLabel(col?.labels, preferredLocales) || pickLocalizedLabel(glob ? {
73
+ singular: glob.label
74
+ } : undefined, preferredLocales) || humanizeSlug(groupSlug);
75
+ return `${label} (${groupSlug})`;
76
+ }
77
+ export async function loadRestoreBackupIndex(downloadUrl, options = {}) {
78
+ const archiveRef = resolveArchiveFileReference(downloadUrl, options.archivePathname);
79
+ const bytes = await readBackupArchiveBytes(downloadUrl, {
80
+ archivePathname: options.archivePathname,
81
+ backupRead: options.readAuth,
82
+ blobAccess: options.blobAccess,
83
+ blobToken: options.blobToken
84
+ });
85
+ const archive = await loadPgArchive(bytes, archiveRef);
86
+ const countsByTable = {};
87
+ for (const [name, t] of Object.entries(archive.doc.tables)){
88
+ countsByTable[name] = t.rowCount;
89
+ }
90
+ return {
91
+ countsByTable,
92
+ fileKind: archive.fileKind,
93
+ mediaBlobCount: archive.media.length
94
+ };
95
+ }
96
+ /** Ensures every configured collection/global appears (0 rows if absent from the backup). */ function mergeConfiguredZeros(payload, counts, excludeGroups, tableNameMap) {
97
+ const merged = {
98
+ ...counts
99
+ };
100
+ const slugs = [
101
+ ...(payload.config.collections ?? []).map((c)=>c.slug),
102
+ ...(payload.config.globals ?? []).map((g)=>g.slug)
103
+ ];
104
+ for (const slug of slugs){
105
+ if (excludeGroups.has(slug)) {
106
+ continue;
107
+ }
108
+ const roots = rootTablesForSlug(payload, slug, tableNameMap);
109
+ if (roots && !(roots.main in merged)) {
110
+ merged[roots.main] = 0;
111
+ }
112
+ }
113
+ return merged;
114
+ }
115
+ function safeTableNameMap(payload) {
116
+ try {
117
+ return getPgDb(payload).tableNameMap;
118
+ } catch {
119
+ return undefined;
120
+ }
121
+ }
122
+ /** Groups Postgres tables + row counts (live DB or backup file) by Payload collection/global. */ export function buildCollectionPreviewGroups(payload, countsByTable, options = {}) {
123
+ const preferredLocales = options.preferredLocales?.length ? options.preferredLocales : [
124
+ 'de',
125
+ 'en'
126
+ ];
127
+ const excludeGroups = options.excludeGroups ?? DEFAULT_EXCLUDED_GROUPS;
128
+ const includeEmptyCollections = options.includeEmptyCollections ?? false;
129
+ const sortLikeAdminNav = options.sortLikeAdminNav ?? false;
130
+ const tableNameMap = safeTableNameMap(payload);
131
+ const owners = resolveTableOwners(payload, Object.keys(countsByTable), tableNameMap);
132
+ const aggs = new Map();
133
+ for (const [table, count] of Object.entries(countsByTable)){
134
+ const owner = owners.get(table);
135
+ if (excludeGroups.has(owner.slug)) {
136
+ continue;
137
+ }
138
+ const agg = aggs.get(owner.slug) ?? {
139
+ groupId: owner.slug,
140
+ kind: owner.kind,
141
+ tableNames: []
142
+ };
143
+ agg.tableNames.push(table);
144
+ const roots = owner.kind === 'unknown' ? null : rootTablesForSlug(payload, owner.slug, tableNameMap);
145
+ if (owner.kind === 'unknown' || table === roots?.main) {
146
+ agg.main = {
147
+ docCount: count,
148
+ tableName: table
149
+ };
150
+ } else if (table === roots?.versions) {
151
+ agg.versions = {
152
+ docCount: count,
153
+ tableName: table
154
+ };
155
+ }
156
+ aggs.set(owner.slug, agg);
157
+ }
158
+ const authSlugs = new Set([
159
+ ...(payload.config.collections ?? []).filter((c)=>Boolean(c.auth)).map((c)=>c.slug),
160
+ ...AUTH_SESSION_SLUGS
161
+ ]);
162
+ const groups = [];
163
+ for (const agg of aggs.values()){
164
+ const total = (agg.main?.docCount ?? 0) + (agg.versions?.docCount ?? 0);
165
+ if (!includeEmptyCollections && total === 0) {
166
+ continue;
167
+ }
168
+ const reasons = new Set();
169
+ const col = payload.config.collections?.find((c)=>c.slug === agg.groupId);
170
+ if (col?.admin?.hidden === true) {
171
+ reasons.add('collection-config');
172
+ }
173
+ if (!agg.main && agg.versions) {
174
+ reasons.add('version-history');
175
+ }
176
+ groups.push({
177
+ adminHidden: reasons.size > 0,
178
+ adminHiddenReasons: [
179
+ ...reasons
180
+ ],
181
+ affectsAuthSession: authSlugs.has(agg.groupId),
182
+ displayTitle: agg.kind === 'unknown' ? `${agg.groupId} (table)` : buildDisplayTitle(payload, agg.groupId, preferredLocales),
183
+ groupId: agg.groupId,
184
+ main: agg.main,
185
+ tableNames: agg.tableNames.sort(),
186
+ versions: agg.versions
187
+ });
188
+ }
189
+ if (sortLikeAdminNav) {
190
+ sortPreviewGroupsLikeAdminNav(payload, groups, preferredLocales);
191
+ } else {
192
+ const locale = preferredLocales[0] ?? 'en';
193
+ groups.sort((a, b)=>a.displayTitle.localeCompare(b.displayTitle, locale));
194
+ }
195
+ return groups;
196
+ }
197
+ export function buildRestorePreviewGroups(payload, parsed, options = {}) {
198
+ const excludeGroups = options.excludeGroups ?? DEFAULT_EXCLUDED_GROUPS;
199
+ const counts = mergeConfiguredZeros(payload, parsed.countsByTable, excludeGroups, safeTableNameMap(payload));
200
+ const groups = buildCollectionPreviewGroups(payload, counts, {
201
+ excludeGroups,
202
+ includeEmptyCollections: true,
203
+ preferredLocales: options.preferredLocales,
204
+ sortLikeAdminNav: true
205
+ });
206
+ return {
207
+ fileKind: parsed.fileKind,
208
+ groups,
209
+ mediaBlobCount: parsed.mediaBlobCount
210
+ };
211
+ }
212
+ export async function getRestorePreviewForAdminRestore(payload, downloadUrl, options = {}) {
213
+ const parsed = await loadRestoreBackupIndex(downloadUrl, {
214
+ archivePathname: options.archivePathname,
215
+ blobAccess: options.blobAccess,
216
+ blobToken: options.blobToken,
217
+ readAuth: options.backupRead
218
+ });
219
+ return buildRestorePreviewGroups(payload, parsed, options);
220
+ }
221
+
222
+ //# sourceMappingURL=restorePreview.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/core/restorePreview.ts"],"sourcesContent":["import type { Payload } from 'payload'\n\nimport { readBackupArchiveBytes, resolveArchiveFileReference } from './backupArchiveRead'\nimport { type BackupBlobAccessLevel } from './backupBlobIO'\nimport { getPgDb } from './db'\nimport { loadPgArchive } from './pgArchive'\nimport { resolveTableOwners, rootTablesForSlug } from './tableGroups'\n\n/** Payload slugs whose replacement invalidates the current admin session. */\nconst AUTH_SESSION_SLUGS = new Set(['payload-preferences', 'roles', 'sessions', 'users'])\n\n/** Groups never listed in the UI (plugin-internal progress rows). */\nconst DEFAULT_EXCLUDED_GROUPS = new Set(['backup-tasks'])\n\nexport type RestorePreviewFileKind = 'json' | 'tar-gzip'\n\nexport type RestorePreviewAdminHiddenReason = 'collection-config' | 'version-history'\n\nexport type RestorePreviewGroup = {\n adminHidden: boolean\n adminHiddenReasons: RestorePreviewAdminHiddenReason[]\n affectsAuthSession: boolean\n /** e.g. \"Seiten (pages)\" */\n displayTitle: string\n /** Stable id for UI: Payload collection/global slug when known, else the table name. */\n groupId: string\n /** Row count of the root table (one row per document). */\n main?: { docCount: number; tableName: string }\n /** All Postgres tables restored/skipped together when this group is toggled. */\n tableNames: string[]\n /** Row count of the `_<root>_v` versions table. */\n versions?: { docCount: number; tableName: string }\n}\n\nexport type RestorePreviewResponse = {\n fileKind: RestorePreviewFileKind\n groups: RestorePreviewGroup[]\n mediaBlobCount: number\n}\n\nfunction pickLocalizedLabel(labels: unknown, preferredLocales: string[]): string | undefined {\n if (!labels || typeof labels !== 'object') {\n return undefined\n }\n const l = labels as { plural?: unknown; singular?: unknown }\n\n const pickField = (field: unknown): string | undefined => {\n if (typeof field === 'string') {\n return field\n }\n if (field && typeof field === 'object') {\n const map = field as Record<string, string>\n for (const loc of preferredLocales) {\n const v = map[loc]\n if (v) {\n return v\n }\n }\n const first = Object.values(map).find(Boolean)\n return first\n }\n return undefined\n }\n\n return pickField(l.plural) || pickField(l.singular)\n}\n\nfunction humanizeSlug(slug: string): string {\n return slug\n .split('-')\n .map((w) => (w ? w.charAt(0).toUpperCase() + w.slice(1) : ''))\n .join(' ')\n}\n\n/** Collections shown in the default Payload admin sidebar: config order, skipping `admin.hidden`. */\nfunction getNavVisibleCollections(payload: Payload) {\n return payload.config.collections.filter((c) => c.admin?.hidden !== true)\n}\n\n/**\n * Index in sidebar order, or `null` if the group is not a visible nav collection\n * (hidden config, unknown table, global, etc.).\n */\nexport function navVisibleCollectionOrderIndex(payload: Payload, groupId: string): null | number {\n const visible = getNavVisibleCollections(payload)\n const idx = visible.findIndex((c) => c.slug === groupId)\n return idx === -1 ? null : idx\n}\n\nfunction sortPreviewGroupsLikeAdminNav(\n payload: Payload,\n groups: RestorePreviewGroup[],\n preferredLocales: string[],\n): void {\n const locale = preferredLocales[0] ?? 'en'\n groups.sort((a, b) => {\n const ia = navVisibleCollectionOrderIndex(payload, a.groupId)\n const ib = navVisibleCollectionOrderIndex(payload, b.groupId)\n if (ia !== null && ib !== null && ia !== ib) {\n return ia - ib\n }\n if (ia !== null && ib === null) {\n return -1\n }\n if (ia === null && ib !== null) {\n return 1\n }\n return a.displayTitle.localeCompare(b.displayTitle, locale)\n })\n}\n\nfunction buildDisplayTitle(\n payload: Payload,\n groupSlug: string,\n preferredLocales: string[],\n): string {\n const col = payload.config.collections.find((c) => c.slug === groupSlug)\n const glob = payload.config.globals?.find((g) => g.slug === groupSlug)\n const label =\n pickLocalizedLabel(col?.labels, preferredLocales) ||\n pickLocalizedLabel(glob ? { singular: glob.label } : undefined, preferredLocales) ||\n humanizeSlug(groupSlug)\n return `${label} (${groupSlug})`\n}\n\nexport async function loadRestoreBackupIndex(\n downloadUrl: string,\n options: {\n archivePathname?: string\n blobAccess?: BackupBlobAccessLevel\n blobToken?: string\n readAuth?: { pathname: string; token: string }\n } = {},\n): Promise<{\n countsByTable: Record<string, number>\n fileKind: RestorePreviewFileKind\n mediaBlobCount: number\n}> {\n const archiveRef = resolveArchiveFileReference(downloadUrl, options.archivePathname)\n const bytes = await readBackupArchiveBytes(downloadUrl, {\n archivePathname: options.archivePathname,\n backupRead: options.readAuth,\n blobAccess: options.blobAccess,\n blobToken: options.blobToken,\n })\n const archive = await loadPgArchive(bytes, archiveRef)\n const countsByTable: Record<string, number> = {}\n for (const [name, t] of Object.entries(archive.doc.tables)) {\n countsByTable[name] = t.rowCount\n }\n return { countsByTable, fileKind: archive.fileKind, mediaBlobCount: archive.media.length }\n}\n\ntype GroupAgg = {\n groupId: string\n kind: 'collection' | 'global' | 'unknown'\n main?: { docCount: number; tableName: string }\n tableNames: string[]\n versions?: { docCount: number; tableName: string }\n}\n\n/** Ensures every configured collection/global appears (0 rows if absent from the backup). */\nfunction mergeConfiguredZeros(\n payload: Payload,\n counts: Record<string, number>,\n excludeGroups: Set<string>,\n tableNameMap?: Map<string, string>,\n): Record<string, number> {\n const merged = { ...counts }\n const slugs = [\n ...(payload.config.collections ?? []).map((c) => c.slug),\n ...(payload.config.globals ?? []).map((g) => g.slug),\n ]\n for (const slug of slugs) {\n if (excludeGroups.has(slug)) {\n continue\n }\n const roots = rootTablesForSlug(payload, slug, tableNameMap)\n if (roots && !(roots.main in merged)) {\n merged[roots.main] = 0\n }\n }\n return merged\n}\n\nfunction safeTableNameMap(payload: Payload): Map<string, string> | undefined {\n try {\n return getPgDb(payload).tableNameMap\n } catch {\n return undefined\n }\n}\n\n/** Groups Postgres tables + row counts (live DB or backup file) by Payload collection/global. */\nexport function buildCollectionPreviewGroups(\n payload: Payload,\n countsByTable: Record<string, number>,\n options: {\n /** Payload slugs (or raw table names) to hide. Default: `backup-tasks`. */\n excludeGroups?: Set<string>\n /** When true, list groups whose tables are all empty (e.g. manual backup UI). Default false. */\n includeEmptyCollections?: boolean\n preferredLocales?: string[]\n /** When true, order like Payload admin sidebar; unknown / hidden-only groups last by title. */\n sortLikeAdminNav?: boolean\n } = {},\n): RestorePreviewGroup[] {\n const preferredLocales =\n options.preferredLocales?.length ? options.preferredLocales : ['de', 'en']\n const excludeGroups = options.excludeGroups ?? DEFAULT_EXCLUDED_GROUPS\n const includeEmptyCollections = options.includeEmptyCollections ?? false\n const sortLikeAdminNav = options.sortLikeAdminNav ?? false\n const tableNameMap = safeTableNameMap(payload)\n\n const owners = resolveTableOwners(payload, Object.keys(countsByTable), tableNameMap)\n const aggs = new Map<string, GroupAgg>()\n for (const [table, count] of Object.entries(countsByTable)) {\n const owner = owners.get(table)!\n if (excludeGroups.has(owner.slug)) {\n continue\n }\n const agg = aggs.get(owner.slug) ?? { groupId: owner.slug, kind: owner.kind, tableNames: [] }\n agg.tableNames.push(table)\n const roots =\n owner.kind === 'unknown' ? null : rootTablesForSlug(payload, owner.slug, tableNameMap)\n if (owner.kind === 'unknown' || table === roots?.main) {\n agg.main = { docCount: count, tableName: table }\n } else if (table === roots?.versions) {\n agg.versions = { docCount: count, tableName: table }\n }\n aggs.set(owner.slug, agg)\n }\n\n const authSlugs = new Set([\n ...(payload.config.collections ?? []).filter((c) => Boolean(c.auth)).map((c) => c.slug),\n ...AUTH_SESSION_SLUGS,\n ])\n\n const groups: RestorePreviewGroup[] = []\n for (const agg of aggs.values()) {\n const total = (agg.main?.docCount ?? 0) + (agg.versions?.docCount ?? 0)\n if (!includeEmptyCollections && total === 0) {\n continue\n }\n const reasons = new Set<RestorePreviewAdminHiddenReason>()\n const col = payload.config.collections?.find((c) => c.slug === agg.groupId)\n if (col?.admin?.hidden === true) {\n reasons.add('collection-config')\n }\n if (!agg.main && agg.versions) {\n reasons.add('version-history')\n }\n groups.push({\n adminHidden: reasons.size > 0,\n adminHiddenReasons: [...reasons],\n affectsAuthSession: authSlugs.has(agg.groupId),\n displayTitle:\n agg.kind === 'unknown' ?\n `${agg.groupId} (table)`\n : buildDisplayTitle(payload, agg.groupId, preferredLocales),\n groupId: agg.groupId,\n main: agg.main,\n tableNames: agg.tableNames.sort(),\n versions: agg.versions,\n })\n }\n\n if (sortLikeAdminNav) {\n sortPreviewGroupsLikeAdminNav(payload, groups, preferredLocales)\n } else {\n const locale = preferredLocales[0] ?? 'en'\n groups.sort((a, b) => a.displayTitle.localeCompare(b.displayTitle, locale))\n }\n return groups\n}\n\nexport function buildRestorePreviewGroups(\n payload: Payload,\n parsed: {\n countsByTable: Record<string, number>\n fileKind: RestorePreviewFileKind\n mediaBlobCount: number\n },\n options: { excludeGroups?: Set<string>; preferredLocales?: string[] } = {},\n): RestorePreviewResponse {\n const excludeGroups = options.excludeGroups ?? DEFAULT_EXCLUDED_GROUPS\n const counts = mergeConfiguredZeros(\n payload,\n parsed.countsByTable,\n excludeGroups,\n safeTableNameMap(payload),\n )\n const groups = buildCollectionPreviewGroups(payload, counts, {\n excludeGroups,\n includeEmptyCollections: true,\n preferredLocales: options.preferredLocales,\n sortLikeAdminNav: true,\n })\n return { fileKind: parsed.fileKind, groups, mediaBlobCount: parsed.mediaBlobCount }\n}\n\nexport async function getRestorePreviewForAdminRestore(\n payload: Payload,\n downloadUrl: string,\n options: {\n archivePathname?: string\n backupRead?: { pathname: string; token: string }\n blobAccess?: BackupBlobAccessLevel\n blobToken?: string\n preferredLocales?: string[]\n } = {},\n): Promise<RestorePreviewResponse> {\n const parsed = await loadRestoreBackupIndex(downloadUrl, {\n archivePathname: options.archivePathname,\n blobAccess: options.blobAccess,\n blobToken: options.blobToken,\n readAuth: options.backupRead,\n })\n return buildRestorePreviewGroups(payload, parsed, options)\n}\n"],"names":["readBackupArchiveBytes","resolveArchiveFileReference","getPgDb","loadPgArchive","resolveTableOwners","rootTablesForSlug","AUTH_SESSION_SLUGS","Set","DEFAULT_EXCLUDED_GROUPS","pickLocalizedLabel","labels","preferredLocales","undefined","l","pickField","field","map","loc","v","first","Object","values","find","Boolean","plural","singular","humanizeSlug","slug","split","w","charAt","toUpperCase","slice","join","getNavVisibleCollections","payload","config","collections","filter","c","admin","hidden","navVisibleCollectionOrderIndex","groupId","visible","idx","findIndex","sortPreviewGroupsLikeAdminNav","groups","locale","sort","a","b","ia","ib","displayTitle","localeCompare","buildDisplayTitle","groupSlug","col","glob","globals","g","label","loadRestoreBackupIndex","downloadUrl","options","archiveRef","archivePathname","bytes","backupRead","readAuth","blobAccess","blobToken","archive","countsByTable","name","t","entries","doc","tables","rowCount","fileKind","mediaBlobCount","media","length","mergeConfiguredZeros","counts","excludeGroups","tableNameMap","merged","slugs","has","roots","main","safeTableNameMap","buildCollectionPreviewGroups","includeEmptyCollections","sortLikeAdminNav","owners","keys","aggs","Map","table","count","owner","get","agg","kind","tableNames","push","docCount","tableName","versions","set","authSlugs","auth","total","reasons","add","adminHidden","size","adminHiddenReasons","affectsAuthSession","buildRestorePreviewGroups","parsed","getRestorePreviewForAdminRestore"],"mappings":"AAEA,SAASA,sBAAsB,EAAEC,2BAA2B,QAAQ,sBAAqB;AAEzF,SAASC,OAAO,QAAQ,OAAM;AAC9B,SAASC,aAAa,QAAQ,cAAa;AAC3C,SAASC,kBAAkB,EAAEC,iBAAiB,QAAQ,gBAAe;AAErE,2EAA2E,GAC3E,MAAMC,qBAAqB,IAAIC,IAAI;IAAC;IAAuB;IAAS;IAAY;CAAQ;AAExF,mEAAmE,GACnE,MAAMC,0BAA0B,IAAID,IAAI;IAAC;CAAe;AA4BxD,SAASE,mBAAmBC,MAAe,EAAEC,gBAA0B;IACrE,IAAI,CAACD,UAAU,OAAOA,WAAW,UAAU;QACzC,OAAOE;IACT;IACA,MAAMC,IAAIH;IAEV,MAAMI,YAAY,CAACC;QACjB,IAAI,OAAOA,UAAU,UAAU;YAC7B,OAAOA;QACT;QACA,IAAIA,SAAS,OAAOA,UAAU,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BAAkBuD,QAAQvD,gBAAgB;QAC1CuF,kBAAkB;IACpB;IACA,OAAO;QAAEhB,UAAU2C,OAAO3C,QAAQ;QAAElC;QAAQmC,gBAAgB0C,OAAO1C,cAAc;IAAC;AACpF;AAEA,OAAO,eAAe2C,iCACpB3F,OAAgB,EAChB8B,WAAmB,EACnBC,UAMI,CAAC,CAAC;IAEN,MAAM2D,SAAS,MAAM7D,uBAAuBC,aAAa;QACvDG,iBAAiBF,QAAQE,eAAe;QACxCI,YAAYN,QAAQM,UAAU;QAC9BC,WAAWP,QAAQO,SAAS;QAC5BF,UAAUL,QAAQI,UAAU;IAC9B;IACA,OAAOsD,0BAA0BzF,SAAS0F,QAAQ3D;AACpD"}
@@ -0,0 +1,34 @@
1
+ export type RestoreArchiveKind = 'json' | 'tar-gzip';
2
+ export type RestoreCollectionOutcome = {
3
+ docCount: number;
4
+ kind: 'restored';
5
+ name: string;
6
+ } | {
7
+ error: string;
8
+ kind: 'failed';
9
+ name: string;
10
+ } | {
11
+ kind: 'skipped';
12
+ name: string;
13
+ reason: 'blacklist' | 'empty';
14
+ };
15
+ export type RestoreMediaOutcome = {
16
+ accessFallbackCount: number;
17
+ attempted: number;
18
+ failed: Array<{
19
+ error: string;
20
+ name: string;
21
+ }>;
22
+ restored: number;
23
+ skippedByOption: boolean;
24
+ };
25
+ /** Structured outcome of a restore run (returned to endpoints and task progress). */
26
+ export type RestoreBackupResult = {
27
+ archiveKind: RestoreArchiveKind;
28
+ collections: RestoreCollectionOutcome[];
29
+ durationMs: number;
30
+ media: null | RestoreMediaOutcome;
31
+ };
32
+ export declare function buildRestoreWarnings(result: RestoreBackupResult): string[];
33
+ export declare function formatRestoreSummary(result: RestoreBackupResult): string;
34
+ export declare function restoreTaskStatus(result: RestoreBackupResult): 'completed' | 'completed_with_warnings';
@@ -0,0 +1,45 @@
1
+ export function buildRestoreWarnings(result) {
2
+ const warnings = [];
3
+ for (const collection of result.collections){
4
+ if (collection.kind === 'failed') {
5
+ warnings.push(`Table "${collection.name}": ${collection.error}`);
6
+ }
7
+ }
8
+ if (result.media && !result.media.skippedByOption) {
9
+ for (const failed of result.media.failed){
10
+ warnings.push(`Media "${failed.name}": ${failed.error}`);
11
+ }
12
+ if (result.media.accessFallbackCount > 0) {
13
+ warnings.push(`${result.media.accessFallbackCount} media file(s) uploaded with a fallback blob access level`);
14
+ }
15
+ }
16
+ return warnings;
17
+ }
18
+ export function formatRestoreSummary(result) {
19
+ const restored = result.collections.filter((c)=>c.kind === 'restored');
20
+ const docTotal = restored.reduce((sum, c)=>sum + (c.kind === 'restored' ? c.docCount : 0), 0);
21
+ const skipped = result.collections.filter((c)=>c.kind === 'skipped');
22
+ const failedCollections = result.collections.filter((c)=>c.kind === 'failed');
23
+ const parts = [
24
+ `Restored ${restored.length} collection${restored.length === 1 ? '' : 's'} (${docTotal} document${docTotal === 1 ? '' : 's'})`
25
+ ];
26
+ if (skipped.length > 0) {
27
+ parts.push(`skipped ${skipped.length} collection${skipped.length === 1 ? '' : 's'} (blacklist or empty)`);
28
+ }
29
+ if (result.media?.skippedByOption) {
30
+ parts.push('archive media not restored (option disabled)');
31
+ } else if (result.media) {
32
+ parts.push(`media ${result.media.restored}/${result.media.attempted} file${result.media.attempted === 1 ? '' : 's'}`);
33
+ }
34
+ const failedMedia = result.media?.failed.length ?? 0;
35
+ const errorCount = failedCollections.length + failedMedia;
36
+ if (errorCount > 0) {
37
+ parts.push(`${errorCount} error${errorCount === 1 ? '' : 's'} — see warnings`);
38
+ }
39
+ return parts.join('; ');
40
+ }
41
+ export function restoreTaskStatus(result) {
42
+ return buildRestoreWarnings(result).length > 0 ? 'completed_with_warnings' : 'completed';
43
+ }
44
+
45
+ //# sourceMappingURL=restoreResult.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/core/restoreResult.ts"],"sourcesContent":["export type RestoreArchiveKind = 'json' | 'tar-gzip'\n\nexport type RestoreCollectionOutcome =\n | { docCount: number; kind: 'restored'; name: string }\n | { error: string; kind: 'failed'; name: string }\n | { kind: 'skipped'; name: string; reason: 'blacklist' | 'empty' }\n\nexport type RestoreMediaOutcome = {\n accessFallbackCount: number\n attempted: number\n failed: Array<{ error: string; name: string }>\n restored: number\n skippedByOption: boolean\n}\n\n/** Structured outcome of a restore run (returned to endpoints and task progress). */\nexport type RestoreBackupResult = {\n archiveKind: RestoreArchiveKind\n collections: RestoreCollectionOutcome[]\n durationMs: number\n media: null | RestoreMediaOutcome\n}\n\nexport function buildRestoreWarnings(result: RestoreBackupResult): string[] {\n const warnings: string[] = []\n\n for (const collection of result.collections) {\n if (collection.kind === 'failed') {\n warnings.push(`Table \"${collection.name}\": ${collection.error}`)\n }\n }\n\n if (result.media && !result.media.skippedByOption) {\n for (const failed of result.media.failed) {\n warnings.push(`Media \"${failed.name}\": ${failed.error}`)\n }\n if (result.media.accessFallbackCount > 0) {\n warnings.push(\n `${result.media.accessFallbackCount} media file(s) uploaded with a fallback blob access level`,\n )\n }\n }\n\n return warnings\n}\n\nexport function formatRestoreSummary(result: RestoreBackupResult): string {\n const restored = result.collections.filter((c) => c.kind === 'restored')\n const docTotal = restored.reduce((sum, c) => sum + (c.kind === 'restored' ? c.docCount : 0), 0)\n const skipped = result.collections.filter((c) => c.kind === 'skipped')\n const failedCollections = result.collections.filter((c) => c.kind === 'failed')\n\n const parts: string[] = [\n `Restored ${restored.length} collection${restored.length === 1 ? '' : 's'} (${docTotal} document${docTotal === 1 ? '' : 's'})`,\n ]\n\n if (skipped.length > 0) {\n parts.push(\n `skipped ${skipped.length} collection${skipped.length === 1 ? '' : 's'} (blacklist or empty)`,\n )\n }\n\n if (result.media?.skippedByOption) {\n parts.push('archive media not restored (option disabled)')\n } else if (result.media) {\n parts.push(\n `media ${result.media.restored}/${result.media.attempted} file${result.media.attempted === 1 ? '' : 's'}`,\n )\n }\n\n const failedMedia = result.media?.failed.length ?? 0\n const errorCount = failedCollections.length + failedMedia\n if (errorCount > 0) {\n parts.push(`${errorCount} error${errorCount === 1 ? '' : 's'} — see warnings`)\n }\n\n return parts.join('; ')\n}\n\nexport function restoreTaskStatus(\n result: RestoreBackupResult,\n): 'completed' | 'completed_with_warnings' {\n return buildRestoreWarnings(result).length > 0 ? 'completed_with_warnings' : 'completed'\n}\n"],"names":["buildRestoreWarnings","result","warnings","collection","collections","kind","push","name","error","media","skippedByOption","failed","accessFallbackCount","formatRestoreSummary","restored","filter","c","docTotal","reduce","sum","docCount","skipped","failedCollections","parts","length","attempted","failedMedia","errorCount","join","restoreTaskStatus"],"mappings":"AAuBA,OAAO,SAASA,qBAAqBC,MAA2B;IAC9D,MAAMC,WAAqB,EAAE;IAE7B,KAAK,MAAMC,cAAcF,OAAOG,WAAW,CAAE;QAC3C,IAAID,WAAWE,IAAI,KAAK,UAAU;YAChCH,SAASI,IAAI,CAAC,CAAC,OAAO,EAAEH,WAAWI,IAAI,CAAC,GAAG,EAAEJ,WAAWK,KAAK,EAAE;QACjE;IACF;IAEA,IAAIP,OAAOQ,KAAK,IAAI,CAACR,OAAOQ,KAAK,CAACC,eAAe,EAAE;QACjD,KAAK,MAAMC,UAAUV,OAAOQ,KAAK,CAACE,MAAM,CAAE;YACxCT,SAASI,IAAI,CAAC,CAAC,OAAO,EAAEK,OAAOJ,IAAI,CAAC,GAAG,EAAEI,OAAOH,KAAK,EAAE;QACzD;QACA,IAAIP,OAAOQ,KAAK,CAACG,mBAAmB,GAAG,GAAG;YACxCV,SAASI,IAAI,CACX,GAAGL,OAAOQ,KAAK,CAACG,mBAAmB,CAAC,yDAAyD,CAAC;QAElG;IACF;IAEA,OAAOV;AACT;AAEA,OAAO,SAASW,qBAAqBZ,MAA2B;IAC9D,MAAMa,WAAWb,OAAOG,WAAW,CAACW,MAAM,CAAC,CAACC,IAAMA,EAAEX,IAAI,KAAK;IAC7D,MAAMY,WAAWH,SAASI,MAAM,CAAC,CAACC,KAAKH,IAAMG,MAAOH,CAAAA,EAAEX,IAAI,KAAK,aAAaW,EAAEI,QAAQ,GAAG,CAA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,0 +1,31 @@
1
+ import type { BackupStorageKind } from './types.js';
2
+ /**
3
+ * Resolved S3 configuration. Credentials are optional: when omitted, the AWS SDK's default
4
+ * provider chain is used (env vars `AWS_ACCESS_KEY_ID`/`AWS_SECRET_ACCESS_KEY`, shared config,
5
+ * instance/role credentials, …), which is the recommended setup on AWS.
6
+ */
7
+ export interface BackupS3Config {
8
+ accessKeyId?: string;
9
+ bucket: string;
10
+ /** Custom endpoint for S3-compatible stores (Cloudflare R2, MinIO). Omit for AWS S3. */
11
+ endpoint?: string;
12
+ /** Path-style addressing — required for MinIO and some R2 setups. Defaults true when an endpoint is set. */
13
+ forcePathStyle: boolean;
14
+ /** Optional key namespace prepended to every object key (for sharing a bucket). No trailing slash. */
15
+ prefix: string;
16
+ region: string;
17
+ secretAccessKey?: string;
18
+ sessionToken?: string;
19
+ }
20
+ /**
21
+ * Selected backup target. Precedence: explicit `override` (plugin option) → `BACKUP_STORAGE`
22
+ * env var → `vercel-blob` (default, so existing deployments are unaffected).
23
+ */
24
+ export declare function getBackupStorageKind(override?: BackupStorageKind): BackupStorageKind;
25
+ /** True when the S3 target has the minimum configuration (a bucket) to operate. */
26
+ export declare function isS3Configured(): boolean;
27
+ /**
28
+ * Reads S3 configuration from the environment. Throws a descriptive error when the bucket is
29
+ * missing so endpoints can surface a clear failure instead of an opaque SDK error.
30
+ */
31
+ export declare function loadS3Config(): BackupS3Config;
@@ -0,0 +1,60 @@
1
+ function env(name) {
2
+ const v = process.env[name];
3
+ if (typeof v !== 'string') {
4
+ return undefined;
5
+ }
6
+ const trimmed = v.trim();
7
+ return trimmed.length > 0 ? trimmed : undefined;
8
+ }
9
+ function parseBool(raw, fallback) {
10
+ if (raw === undefined) {
11
+ return fallback;
12
+ }
13
+ return [
14
+ '1',
15
+ 'on',
16
+ 'true',
17
+ 'yes'
18
+ ].includes(raw.toLowerCase());
19
+ }
20
+ /**
21
+ * Selected backup target. Precedence: explicit `override` (plugin option) → `BACKUP_STORAGE`
22
+ * env var → `vercel-blob` (default, so existing deployments are unaffected).
23
+ */ export function getBackupStorageKind(override) {
24
+ if (override === 's3' || override === 'vercel-blob') {
25
+ return override;
26
+ }
27
+ const raw = env('BACKUP_STORAGE')?.toLowerCase();
28
+ if (raw === 's3') {
29
+ return 's3';
30
+ }
31
+ return 'vercel-blob';
32
+ }
33
+ /** True when the S3 target has the minimum configuration (a bucket) to operate. */ export function isS3Configured() {
34
+ return Boolean(env('BACKUP_S3_BUCKET'));
35
+ }
36
+ /**
37
+ * Reads S3 configuration from the environment. Throws a descriptive error when the bucket is
38
+ * missing so endpoints can surface a clear failure instead of an opaque SDK error.
39
+ */ export function loadS3Config() {
40
+ const bucket = env('BACKUP_S3_BUCKET');
41
+ if (!bucket) {
42
+ throw new Error('BACKUP_S3_BUCKET is required when BACKUP_STORAGE=s3');
43
+ }
44
+ const endpoint = env('BACKUP_S3_ENDPOINT');
45
+ const rawPrefix = env('BACKUP_S3_PREFIX') ?? '';
46
+ const accessKeyId = env('BACKUP_S3_ACCESS_KEY_ID') ?? env('AWS_ACCESS_KEY_ID');
47
+ const secretAccessKey = env('BACKUP_S3_SECRET_ACCESS_KEY') ?? env('AWS_SECRET_ACCESS_KEY');
48
+ return {
49
+ accessKeyId,
50
+ bucket,
51
+ endpoint,
52
+ forcePathStyle: parseBool(env('BACKUP_S3_FORCE_PATH_STYLE'), Boolean(endpoint)),
53
+ prefix: rawPrefix.replace(/\/+$/, ''),
54
+ region: env('BACKUP_S3_REGION') ?? env('AWS_REGION') ?? 'us-east-1',
55
+ secretAccessKey,
56
+ sessionToken: env('BACKUP_S3_SESSION_TOKEN') ?? env('AWS_SESSION_TOKEN')
57
+ };
58
+ }
59
+
60
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/core/storage/config.ts"],"sourcesContent":["import type { BackupStorageKind } from './types'\n\n/**\n * Resolved S3 configuration. Credentials are optional: when omitted, the AWS SDK's default\n * provider chain is used (env vars `AWS_ACCESS_KEY_ID`/`AWS_SECRET_ACCESS_KEY`, shared config,\n * instance/role credentials, …), which is the recommended setup on AWS.\n */\nexport interface BackupS3Config {\n accessKeyId?: string\n bucket: string\n /** Custom endpoint for S3-compatible stores (Cloudflare R2, MinIO). Omit for AWS S3. */\n endpoint?: string\n /** Path-style addressing — required for MinIO and some R2 setups. Defaults true when an endpoint is set. */\n forcePathStyle: boolean\n /** Optional key namespace prepended to every object key (for sharing a bucket). No trailing slash. */\n prefix: string\n region: string\n secretAccessKey?: string\n sessionToken?: string\n}\n\nfunction env(name: string): string | undefined {\n const v = process.env[name]\n if (typeof v !== 'string') {\n return undefined\n }\n const trimmed = v.trim()\n return trimmed.length > 0 ? trimmed : undefined\n}\n\nfunction parseBool(raw: string | undefined, fallback: boolean): boolean {\n if (raw === undefined) {\n return fallback\n }\n return ['1', 'on', 'true', 'yes'].includes(raw.toLowerCase())\n}\n\n/**\n * Selected backup target. Precedence: explicit `override` (plugin option) → `BACKUP_STORAGE`\n * env var → `vercel-blob` (default, so existing deployments are unaffected).\n */\nexport function getBackupStorageKind(override?: BackupStorageKind): BackupStorageKind {\n if (override === 's3' || override === 'vercel-blob') {\n return override\n }\n const raw = env('BACKUP_STORAGE')?.toLowerCase()\n if (raw === 's3') {\n return 's3'\n }\n return 'vercel-blob'\n}\n\n/** True when the S3 target has the minimum configuration (a bucket) to operate. */\nexport function isS3Configured(): boolean {\n return Boolean(env('BACKUP_S3_BUCKET'))\n}\n\n/**\n * Reads S3 configuration from the environment. Throws a descriptive error when the bucket is\n * missing so endpoints can surface a clear failure instead of an opaque SDK error.\n */\nexport function loadS3Config(): BackupS3Config {\n const bucket = env('BACKUP_S3_BUCKET')\n if (!bucket) {\n throw new Error('BACKUP_S3_BUCKET is required when BACKUP_STORAGE=s3')\n }\n const endpoint = env('BACKUP_S3_ENDPOINT')\n const rawPrefix = env('BACKUP_S3_PREFIX') ?? ''\n const accessKeyId = env('BACKUP_S3_ACCESS_KEY_ID') ?? env('AWS_ACCESS_KEY_ID')\n const secretAccessKey = env('BACKUP_S3_SECRET_ACCESS_KEY') ?? env('AWS_SECRET_ACCESS_KEY')\n\n return {\n accessKeyId,\n bucket,\n endpoint,\n forcePathStyle: parseBool(env('BACKUP_S3_FORCE_PATH_STYLE'), Boolean(endpoint)),\n prefix: rawPrefix.replace(/\\/+$/, ''),\n region: env('BACKUP_S3_REGION') ?? env('AWS_REGION') ?? 'us-east-1',\n secretAccessKey,\n sessionToken: env('BACKUP_S3_SESSION_TOKEN') ?? env('AWS_SESSION_TOKEN'),\n }\n}\n"],"names":["env","name","v","process","undefined","trimmed","trim","length","parseBool","raw","fallback","includes","toLowerCase","getBackupStorageKind","override","isS3Configured","Boolean","loadS3Config","bucket","Error","endpoint","rawPrefix","accessKeyId","secretAccessKey","forcePathStyle","prefix","replace","region","sessionToken"],"mappings":"AAqBA,SAASA,IAAIC,IAAY;IACvB,MAAMC,IAAIC,QAAQH,GAAG,CAACC,KAAK;IAC3B,IAAI,OAAOC,MAAM,UAAU;QACzB,OAAOE;IACT;IACA,MAAMC,UAAUH,EAAEI,IAAI;IACtB,OAAOD,QAAQE,MAAM,GAAG,IAAIF,UAAUD;AACxC;AAEA,SAASI,UAAUC,GAAuB,EAAEC,QAAiB;IAC3D,IAAID,QAAQL,WAAW;QACrB,OAAOM;IACT;IACA,OAAO;QAAC;QAAK;QAAM;QAAQ;KAAM,CAACC,QAAQ,CAACF,IAAIG,WAAW;AAC5D;AAEA;;;CAGC,GACD,OAAO,SAASC,qBAAqBC,QAA4B;IAC/D,IAAIA,aAAa,QAAQA,aAAa,eAAe;QACnD,OAAOA;IACT;IACA,MAAML,MAAMT,IAAI,mBAAmBY;IACnC,IAAIH,QAAQ,MAAM;QAChB,OAAO;IACT;IACA,OAAO;AACT;AAEA,iFAAiF,GACjF,OAAO,SAASM;IACd,OAAOC,QAAQhB,IAAI;AACrB;AAEA;;;CAGC,GACD,OAAO,SAASiB;IACd,MAAMC,SAASlB,IAAI;IACnB,IAAI,CAACkB,QAAQ;QACX,MAAM,IAAIC,MAAM;IAClB;IACA,MAAMC,WAAWpB,IAAI;IACrB,MAAMqB,YAAYrB,IAAI,uBAAuB;IAC7C,MAAMsB,cAActB,IAAI,8BAA8BA,IAAI;IAC1D,MAAMuB,kBAAkBvB,IAAI,kCAAkCA,IAAI;IAElE,OAAO;QACLsB;QACAJ;QACAE;QACAI,gBAAgBhB,UAAUR,IAAI,+BAA+BgB,QAAQI;QACrEK,QAAQJ,UAAUK,OAAO,CAAC,QAAQ;QAClCC,QAAQ3B,IAAI,uBAAuBA,IAAI,iBAAiB;QACxDuB;QACAK,cAAc5B,IAAI,8BAA8BA,IAAI;IACtD;AACF"}
@@ -0,0 +1,23 @@
1
+ import type { BackupBlobAccessLevel } from '../backupBlobIO.js';
2
+ import type { BackupStorageAdapter, BackupStorageKind } from './types.js';
3
+ export type { BackupS3Config } from './config.js';
4
+ export { getBackupStorageKind, isS3Configured, loadS3Config } from './config.js';
5
+ export type { BackupStorageAdapter, BackupStorageKind, BackupStorageObject, BackupStorageRef, BackupStorageValidation, } from './types.js';
6
+ export interface ResolveBackupStorageOptions {
7
+ /** Vercel Blob access level (ignored for S3). */
8
+ blobAccess?: BackupBlobAccessLevel;
9
+ /** Vercel Blob read/write token (ignored for S3). */
10
+ blobToken?: string;
11
+ /** Force a target; defaults to {@link getBackupStorageKind} (plugin option / env / vercel-blob). */
12
+ kind?: BackupStorageKind;
13
+ }
14
+ /**
15
+ * Builds the backup storage adapter for the active target. Vercel Blob is the default; `s3` is
16
+ * selected via the `BACKUP_STORAGE` env var (or plugin option) and reads `BACKUP_S3_*` config.
17
+ */
18
+ export declare function resolveBackupStorage(options?: ResolveBackupStorageOptions): BackupStorageAdapter;
19
+ /**
20
+ * True when the active target has enough configuration to serve requests. Used by endpoints to
21
+ * return 503 early: Vercel Blob needs a token; S3 needs a bucket.
22
+ */
23
+ export declare function isBackupStorageConfigured(blobToken?: string): boolean;
@@ -0,0 +1,25 @@
1
+ import { getBackupStorageKind, isS3Configured, loadS3Config } from './config.js';
2
+ import { S3BackupStorage } from './s3.js';
3
+ import { VercelBlobStorage } from './vercelBlob.js';
4
+ export { getBackupStorageKind, isS3Configured, loadS3Config } from './config.js';
5
+ /**
6
+ * Builds the backup storage adapter for the active target. Vercel Blob is the default; `s3` is
7
+ * selected via the `BACKUP_STORAGE` env var (or plugin option) and reads `BACKUP_S3_*` config.
8
+ */ export function resolveBackupStorage(options = {}) {
9
+ const kind = getBackupStorageKind(options.kind);
10
+ if (kind === 's3') {
11
+ return new S3BackupStorage(loadS3Config());
12
+ }
13
+ return new VercelBlobStorage({
14
+ access: options.blobAccess,
15
+ token: options.blobToken
16
+ });
17
+ }
18
+ /**
19
+ * True when the active target has enough configuration to serve requests. Used by endpoints to
20
+ * return 503 early: Vercel Blob needs a token; S3 needs a bucket.
21
+ */ export function isBackupStorageConfigured(blobToken) {
22
+ return getBackupStorageKind() === 's3' ? isS3Configured() : Boolean(blobToken?.trim());
23
+ }
24
+
25
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/core/storage/index.ts"],"sourcesContent":["import type { BackupBlobAccessLevel } from '../backupBlobIO'\nimport type { BackupStorageAdapter, BackupStorageKind } from './types'\n\nimport { getBackupStorageKind, isS3Configured, loadS3Config } from './config'\nimport { S3BackupStorage } from './s3'\nimport { VercelBlobStorage } from './vercelBlob'\n\nexport type { BackupS3Config } from './config'\nexport { getBackupStorageKind, isS3Configured, loadS3Config } from './config'\nexport type {\n BackupStorageAdapter,\n BackupStorageKind,\n BackupStorageObject,\n BackupStorageRef,\n BackupStorageValidation,\n} from './types'\n\nexport interface ResolveBackupStorageOptions {\n /** Vercel Blob access level (ignored for S3). */\n blobAccess?: BackupBlobAccessLevel\n /** Vercel Blob read/write token (ignored for S3). */\n blobToken?: string\n /** Force a target; defaults to {@link getBackupStorageKind} (plugin option / env / vercel-blob). */\n kind?: BackupStorageKind\n}\n\n/**\n * Builds the backup storage adapter for the active target. Vercel Blob is the default; `s3` is\n * selected via the `BACKUP_STORAGE` env var (or plugin option) and reads `BACKUP_S3_*` config.\n */\nexport function resolveBackupStorage(\n options: ResolveBackupStorageOptions = {},\n): BackupStorageAdapter {\n const kind = getBackupStorageKind(options.kind)\n if (kind === 's3') {\n return new S3BackupStorage(loadS3Config())\n }\n return new VercelBlobStorage({ access: options.blobAccess, token: options.blobToken })\n}\n\n/**\n * True when the active target has enough configuration to serve requests. Used by endpoints to\n * return 503 early: Vercel Blob needs a token; S3 needs a bucket.\n */\nexport function isBackupStorageConfigured(blobToken?: string): boolean {\n return getBackupStorageKind() === 's3' ? isS3Configured() : Boolean(blobToken?.trim())\n}\n"],"names":["getBackupStorageKind","isS3Configured","loadS3Config","S3BackupStorage","VercelBlobStorage","resolveBackupStorage","options","kind","access","blobAccess","token","blobToken","isBackupStorageConfigured","Boolean","trim"],"mappings":"AAGA,SAASA,oBAAoB,EAAEC,cAAc,EAAEC,YAAY,QAAQ,WAAU;AAC7E,SAASC,eAAe,QAAQ,OAAM;AACtC,SAASC,iBAAiB,QAAQ,eAAc;AAGhD,SAASJ,oBAAoB,EAAEC,cAAc,EAAEC,YAAY,QAAQ,WAAU;AAkB7E;;;CAGC,GACD,OAAO,SAASG,qBACdC,UAAuC,CAAC,CAAC;IAEzC,MAAMC,OAAOP,qBAAqBM,QAAQC,IAAI;IAC9C,IAAIA,SAAS,MAAM;QACjB,OAAO,IAAIJ,gBAAgBD;IAC7B;IACA,OAAO,IAAIE,kBAAkB;QAAEI,QAAQF,QAAQG,UAAU;QAAEC,OAAOJ,QAAQK,SAAS;IAAC;AACtF;AAEA;;;CAGC,GACD,OAAO,SAASC,0BAA0BD,SAAkB;IAC1D,OAAOX,2BAA2B,OAAOC,mBAAmBY,QAAQF,WAAWG;AACjF"}
@@ -0,0 +1,35 @@
1
+ import type { BackupS3Config } from './config.js';
2
+ import type { BackupStorageAdapter, BackupStorageObject, BackupStorageRef, BackupStorageValidation } from './types.js';
3
+ /**
4
+ * AWS S3 backup target. The same implementation serves any S3-compatible store (Cloudflare R2,
5
+ * MinIO, …) — only the `endpoint`/`forcePathStyle` config differs, never the code. The AWS SDK is
6
+ * loaded lazily via dynamic import so it stays an optional dependency for Vercel-only installs.
7
+ */
8
+ export declare class S3BackupStorage implements BackupStorageAdapter {
9
+ private readonly cfg;
10
+ private clientPromise;
11
+ private presignerPromise;
12
+ readonly kind = "s3";
13
+ constructor(cfg: BackupS3Config);
14
+ private buildClient;
15
+ private client;
16
+ /** Strip the configured key prefix, returning the provider-agnostic `backups/...` pathname. */
17
+ private fromKey;
18
+ private presigner;
19
+ private presignGet;
20
+ private sdk;
21
+ /** Prepend the configured key prefix to a provider-agnostic `backups/...` pathname. */
22
+ private toKey;
23
+ del(ref: BackupStorageRef): Promise<void>;
24
+ list(prefix: string): Promise<BackupStorageObject[]>;
25
+ openDownloadStream(ref: BackupStorageRef): Promise<{
26
+ contentType: string;
27
+ stream: ReadableStream<Uint8Array<ArrayBufferLike>>;
28
+ } | null>;
29
+ put(pathname: string, body: Buffer | string | Uint8Array): Promise<{
30
+ pathname: string;
31
+ url: string;
32
+ }>;
33
+ read(ref: BackupStorageRef): Promise<Buffer>;
34
+ validate(): Promise<BackupStorageValidation>;
35
+ }