@rebasepro/server-postgres 0.17.3 → 0.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (204) hide show
  1. package/LICENSE +0 -1
  2. package/README.md +31 -0
  3. package/dist/BranchService-ByLfM_Tt.js +360 -0
  4. package/dist/BranchService-ByLfM_Tt.js.map +1 -0
  5. package/dist/__vite-browser-external-BnuHet1e.js +46 -0
  6. package/dist/__vite-browser-external-BnuHet1e.js.map +1 -0
  7. package/dist/arg-Dni7MzLB.js +87 -0
  8. package/dist/arg-Dni7MzLB.js.map +1 -0
  9. package/dist/auth-users-columns-D2LBFrMH.js +116 -0
  10. package/dist/auth-users-columns-D2LBFrMH.js.map +1 -0
  11. package/dist/backup-argv.d.ts +19 -0
  12. package/dist/backup-cli-oM9WQVlV.js +408 -0
  13. package/dist/backup-cli-oM9WQVlV.js.map +1 -0
  14. package/dist/backup-service-Br3tqwsy.js +715 -0
  15. package/dist/backup-service-Br3tqwsy.js.map +1 -0
  16. package/dist/branch-argv.d.ts +28 -0
  17. package/dist/branch-prune.d.ts +77 -0
  18. package/dist/cli-collections-path.d.ts +31 -0
  19. package/dist/cli-errors-DxN4yzdH.js +657 -0
  20. package/dist/cli-errors-DxN4yzdH.js.map +1 -0
  21. package/dist/cli-errors.d.ts +123 -0
  22. package/dist/cli-flags.d.ts +101 -0
  23. package/dist/cli-helpers.d.ts +94 -10
  24. package/dist/cli-output-CNdMql-L.js +47 -0
  25. package/dist/cli-output-CNdMql-L.js.map +1 -0
  26. package/dist/cli.js +2020 -0
  27. package/dist/cli.js.map +1 -0
  28. package/dist/collection-index-BHgT_TKd.js +276 -0
  29. package/dist/collection-index-BHgT_TKd.js.map +1 -0
  30. package/dist/{collections-schema-version-BMeu3cgv.js → collections-schema-version-T6cGvrDi.js} +1 -2
  31. package/dist/{collections-schema-version-BMeu3cgv.js.map → collections-schema-version-T6cGvrDi.js.map} +1 -1
  32. package/dist/{connection-GOKU3Hu5.js → databasePoolManager-Bj5FbeAs.js} +112 -40
  33. package/dist/databasePoolManager-Bj5FbeAs.js.map +1 -0
  34. package/dist/databasePoolManager.d.ts +27 -0
  35. package/dist/doctor-D7HWmGzs.js +974 -0
  36. package/dist/doctor-D7HWmGzs.js.map +1 -0
  37. package/dist/{ensure-collection-policies-UCqgv_8c.js → ensure-collection-policies-2c2NV8zX.js} +7 -27
  38. package/dist/ensure-collection-policies-2c2NV8zX.js.map +1 -0
  39. package/dist/ensure-collection-tables-D4wJzM4y.js +820 -0
  40. package/dist/ensure-collection-tables-D4wJzM4y.js.map +1 -0
  41. package/dist/ensure-tables-CIojK-Rx.js +650 -0
  42. package/dist/ensure-tables-CIojK-Rx.js.map +1 -0
  43. package/dist/generate-drizzle-schema-CwEgVyjO.js +123 -0
  44. package/dist/generate-drizzle-schema-CwEgVyjO.js.map +1 -0
  45. package/dist/generate-drizzle-schema-logic-so2Z_lyC.js +528 -0
  46. package/dist/generate-drizzle-schema-logic-so2Z_lyC.js.map +1 -0
  47. package/dist/{ensure-collection-tables-DgVixhX3.js → generate-postgres-ddl-logic-CtnpIBVv.js} +126 -984
  48. package/dist/generate-postgres-ddl-logic-CtnpIBVv.js.map +1 -0
  49. package/dist/generated-schema-staleness-DQdfJl2A.js +157 -0
  50. package/dist/generated-schema-staleness-DQdfJl2A.js.map +1 -0
  51. package/dist/index.d.ts +12 -0
  52. package/dist/index.es.js +7423 -1133
  53. package/dist/index.es.js.map +1 -1
  54. package/dist/introspect-db-logic-C6LQdTxj.js +1378 -0
  55. package/dist/introspect-db-logic-C6LQdTxj.js.map +1 -0
  56. package/dist/policy-drift-kNJ6X2Uj.js +313 -0
  57. package/dist/policy-drift-kNJ6X2Uj.js.map +1 -0
  58. package/dist/{backup-service-DCk7KhhL.js → rls-bootstrap-sql-DLDnUjtx.js} +737 -2689
  59. package/dist/rls-bootstrap-sql-DLDnUjtx.js.map +1 -0
  60. package/dist/{rls-enforcement-DvAbL9YJ.js → rls-enforcement-DeYEjYLt.js} +65 -190
  61. package/dist/rls-enforcement-DeYEjYLt.js.map +1 -0
  62. package/dist/schema/bin/generate-drizzle-schema.d.ts +1 -0
  63. package/dist/schema/bin/generate-postgres-ddl.d.ts +1 -0
  64. package/dist/schema/column-type-drift.d.ts +79 -0
  65. package/dist/schema/doctor-cli.js +129 -0
  66. package/dist/schema/doctor-cli.js.map +1 -0
  67. package/dist/schema/doctor.d.ts +42 -0
  68. package/dist/schema/ensure-collection-tables.d.ts +90 -0
  69. package/dist/schema/generate-drizzle-schema.d.ts +1 -1
  70. package/dist/schema/generate-drizzle-schema.js +24 -0
  71. package/dist/schema/generate-drizzle-schema.js.map +1 -0
  72. package/dist/schema/generate-next-step.d.ts +30 -0
  73. package/dist/schema/generate-postgres-ddl-logic.d.ts +28 -0
  74. package/dist/schema/generate-postgres-ddl.d.ts +1 -1
  75. package/dist/schema/generate-postgres-ddl.js +138 -0
  76. package/dist/schema/generate-postgres-ddl.js.map +1 -0
  77. package/dist/schema/generated-schema-staleness.d.ts +37 -0
  78. package/dist/schema/introspect-db-queries.d.ts +34 -0
  79. package/dist/schema/introspect-db.js +866 -0
  80. package/dist/schema/introspect-db.js.map +1 -0
  81. package/dist/security/rls-enforcement.d.ts +63 -2
  82. package/dist/services/BranchService.d.ts +86 -1
  83. package/dist/services/collection-helpers.d.ts +1 -1
  84. package/dist/services/realtimeService.d.ts +30 -2
  85. package/dist/services/row-pipeline.d.ts +12 -1
  86. package/dist/source-Br7L7GOI.js +410 -0
  87. package/dist/source-Br7L7GOI.js.map +1 -0
  88. package/dist/utils/pg-error-utils.d.ts +3 -1
  89. package/dist/utils/pg-numeric-number-patch.d.ts +31 -0
  90. package/dist/vector-index-DkWxm2de.js +309 -0
  91. package/dist/vector-index-DkWxm2de.js.map +1 -0
  92. package/package.json +32 -27
  93. package/dist/backup-service-DCk7KhhL.js.map +0 -1
  94. package/dist/collection-index-BRUg10H5.js +0 -5690
  95. package/dist/collection-index-BRUg10H5.js.map +0 -1
  96. package/dist/connection-GOKU3Hu5.js.map +0 -1
  97. package/dist/ensure-collection-policies-UCqgv_8c.js.map +0 -1
  98. package/dist/ensure-collection-tables-DgVixhX3.js.map +0 -1
  99. package/dist/rls-bootstrap-sql-B5C9LoJ6.js +0 -244
  100. package/dist/rls-bootstrap-sql-B5C9LoJ6.js.map +0 -1
  101. package/dist/rls-enforcement-DvAbL9YJ.js.map +0 -1
  102. package/dist/src-DiB5RP2Z.js +0 -541
  103. package/dist/src-DiB5RP2Z.js.map +0 -1
  104. package/dist/websocket-BZ4H5wUz.js +0 -8198
  105. package/dist/websocket-BZ4H5wUz.js.map +0 -1
  106. package/src/PostgresAdapter.ts +0 -91
  107. package/src/PostgresBackendDriver.ts +0 -1857
  108. package/src/PostgresBootstrapper.ts +0 -1157
  109. package/src/auth/ensure-tables.ts +0 -896
  110. package/src/auth/schema-version.ts +0 -260
  111. package/src/auth/services.ts +0 -1610
  112. package/src/backup/backup-cli.ts +0 -520
  113. package/src/backup/backup-cron.ts +0 -212
  114. package/src/backup/backup-logic.ts +0 -93
  115. package/src/backup/backup-service.ts +0 -485
  116. package/src/backup/index.ts +0 -12
  117. package/src/backup/pg-tools.ts +0 -403
  118. package/src/backup/retention.ts +0 -86
  119. package/src/cli-errors.ts +0 -265
  120. package/src/cli-helpers.ts +0 -569
  121. package/src/cli-output.ts +0 -43
  122. package/src/cli.ts +0 -1339
  123. package/src/collections/PostgresCollectionRegistry.ts +0 -108
  124. package/src/collections/buildRegistry.ts +0 -68
  125. package/src/collections/validate-relations.ts +0 -402
  126. package/src/connection.ts +0 -333
  127. package/src/data-transformer.ts +0 -845
  128. package/src/databasePoolManager.ts +0 -95
  129. package/src/history/HistoryService.ts +0 -254
  130. package/src/history/ensure-history-table.ts +0 -53
  131. package/src/index.ts +0 -19
  132. package/src/interfaces.ts +0 -60
  133. package/src/module-dir.ts +0 -7
  134. package/src/schema/atlas-argv.ts +0 -94
  135. package/src/schema/auth-schema.ts +0 -298
  136. package/src/schema/auth-users-columns.ts +0 -131
  137. package/src/schema/carved-out-migration.ts +0 -404
  138. package/src/schema/classify-change.ts +0 -436
  139. package/src/schema/collection-index.ts +0 -427
  140. package/src/schema/collections-schema-version.ts +0 -103
  141. package/src/schema/destructive-sql.ts +0 -94
  142. package/src/schema/doctor-cli.ts +0 -66
  143. package/src/schema/doctor-policy-checks.ts +0 -105
  144. package/src/schema/doctor.ts +0 -837
  145. package/src/schema/drizzle-ddl.ts +0 -33
  146. package/src/schema/dynamic-tables.test.ts +0 -302
  147. package/src/schema/dynamic-tables.ts +0 -293
  148. package/src/schema/ensure-collection-policies.ts +0 -198
  149. package/src/schema/ensure-collection-tables.test.ts +0 -518
  150. package/src/schema/ensure-collection-tables.ts +0 -1267
  151. package/src/schema/generate-drizzle-schema-logic.ts +0 -957
  152. package/src/schema/generate-drizzle-schema.ts +0 -143
  153. package/src/schema/generate-postgres-ddl-logic.ts +0 -1339
  154. package/src/schema/generate-postgres-ddl.ts +0 -180
  155. package/src/schema/generate-schema-commit.ts +0 -267
  156. package/src/schema/generated-schema-staleness.ts +0 -284
  157. package/src/schema/introspect-db-constraints.ts +0 -385
  158. package/src/schema/introspect-db-inference.ts +0 -255
  159. package/src/schema/introspect-db-logic.ts +0 -1387
  160. package/src/schema/introspect-db-naming.ts +0 -15
  161. package/src/schema/introspect-db-project.ts +0 -78
  162. package/src/schema/introspect-db-queries.ts +0 -326
  163. package/src/schema/introspect-db-structure.ts +0 -670
  164. package/src/schema/introspect-db-types.ts +0 -56
  165. package/src/schema/introspect-db.ts +0 -257
  166. package/src/schema/introspect-runtime.test.ts +0 -260
  167. package/src/schema/introspect-runtime.ts +0 -327
  168. package/src/schema/non-sql-collections.test.ts +0 -131
  169. package/src/schema/rls-bootstrap-sql.ts +0 -288
  170. package/src/schema/search-column.ts +0 -643
  171. package/src/schema/test-schema.ts +0 -11
  172. package/src/schema/vector-index.ts +0 -491
  173. package/src/security/anonymous-grants.test.ts +0 -73
  174. package/src/security/policy-drift.test.ts +0 -435
  175. package/src/security/policy-drift.ts +0 -473
  176. package/src/security/rls-enforcement.ts +0 -505
  177. package/src/services/BranchService.ts +0 -326
  178. package/src/services/FetchService.ts +0 -2115
  179. package/src/services/PersistService.ts +0 -557
  180. package/src/services/RelationService.ts +0 -978
  181. package/src/services/RelationWriteService.ts +0 -653
  182. package/src/services/cdc/CdcListener.ts +0 -103
  183. package/src/services/cdc/junction-tables.ts +0 -91
  184. package/src/services/cdc/trigger-cdc.ts +0 -173
  185. package/src/services/channel-bus/ChannelBus.ts +0 -44
  186. package/src/services/channel-bus/PostgresChannelBus.ts +0 -299
  187. package/src/services/channel-bus/index.ts +0 -114
  188. package/src/services/channel-history.ts +0 -424
  189. package/src/services/channel-presence.ts +0 -185
  190. package/src/services/collection-helpers.ts +0 -420
  191. package/src/services/dataService.ts +0 -256
  192. package/src/services/index.ts +0 -14
  193. package/src/services/junction-writes.ts +0 -295
  194. package/src/services/nested-path.ts +0 -145
  195. package/src/services/pg-notify-listener.ts +0 -151
  196. package/src/services/realtimeService.ts +0 -2545
  197. package/src/services/row-pipeline.ts +0 -240
  198. package/src/services/write-denial.ts +0 -55
  199. package/src/types.ts +0 -4
  200. package/src/utils/connection-string.ts +0 -58
  201. package/src/utils/drizzle-conditions.ts +0 -2743
  202. package/src/utils/pg-array-null-patch.ts +0 -42
  203. package/src/utils/pg-error-utils.ts +0 -391
  204. package/src/websocket.ts +0 -855
@@ -0,0 +1,116 @@
1
+ import { createRequire as __createRequire } from "module";
2
+ __createRequire(import.meta.url);
3
+ //#region src/schema/auth-users-columns.ts
4
+ /**
5
+ * `email` is NOT NULL on purpose, and the anonymous sign-in route depends on it
6
+ * — it synthesizes `anon_<32 hex>@anonymous.local` rather than inserting NULL.
7
+ * The 320-char bound (RFC 5321) is a CHECK rather than a `VARCHAR(n)`, added
8
+ * separately by `ensureAuthTablesExist` so it can be `NOT VALID` on an adopted
9
+ * table that already holds a longer row.
10
+ */
11
+ var AUTH_USERS_COLUMNS = [
12
+ {
13
+ column: "email",
14
+ type: "TEXT",
15
+ notNull: true
16
+ },
17
+ {
18
+ column: "display_name",
19
+ type: "TEXT"
20
+ },
21
+ {
22
+ column: "photo_url",
23
+ type: "TEXT"
24
+ },
25
+ {
26
+ column: "roles",
27
+ type: "TEXT[]",
28
+ default: "'{}'",
29
+ notNull: true
30
+ },
31
+ {
32
+ column: "password_hash",
33
+ type: "TEXT"
34
+ },
35
+ {
36
+ column: "email_verified",
37
+ type: "BOOLEAN",
38
+ default: "FALSE",
39
+ notNull: true
40
+ },
41
+ {
42
+ column: "email_verification_token",
43
+ type: "TEXT"
44
+ },
45
+ {
46
+ column: "email_verification_sent_at",
47
+ type: "TIMESTAMP WITH TIME ZONE"
48
+ },
49
+ {
50
+ column: "is_anonymous",
51
+ type: "BOOLEAN",
52
+ default: "FALSE",
53
+ notNull: true
54
+ },
55
+ {
56
+ column: "metadata",
57
+ type: "JSONB",
58
+ default: "'{}'",
59
+ notNull: true
60
+ },
61
+ {
62
+ column: "tokens_valid_after",
63
+ type: "TIMESTAMP WITH TIME ZONE"
64
+ },
65
+ {
66
+ column: "created_at",
67
+ type: "TIMESTAMP WITH TIME ZONE",
68
+ default: "NOW()",
69
+ notNull: true
70
+ },
71
+ {
72
+ column: "updated_at",
73
+ type: "TIMESTAMP WITH TIME ZONE",
74
+ default: "NOW()",
75
+ notNull: true
76
+ }
77
+ ];
78
+ var BY_COLUMN = new Map(AUTH_USERS_COLUMNS.map((c) => [c.column, c]));
79
+ /** Type + inline constraints, as they appear after the column name. */
80
+ function authUsersColumnSql(spec) {
81
+ return [
82
+ spec.type,
83
+ spec.default !== void 0 ? `DEFAULT ${spec.default}` : "",
84
+ spec.notNull ? "NOT NULL" : ""
85
+ ].filter(Boolean).join(" ");
86
+ }
87
+ /**
88
+ * The auth-owned definition for a physical column name, or `undefined` when
89
+ * auth does not own it.
90
+ *
91
+ * Callers pass the RESOLVED column name (after `columnName` mapping), because
92
+ * that is the only name the three creators agree on: the scaffold's users
93
+ * collection spells the property `displayName` and the column `display_name`.
94
+ */
95
+ function authUsersColumnDefinition(column) {
96
+ const spec = BY_COLUMN.get(column);
97
+ return spec ? authUsersColumnSql(spec) : void 0;
98
+ }
99
+ /**
100
+ * Whether a collection is an auth collection, i.e. whether the definitions in
101
+ * this module apply to its table at all.
102
+ *
103
+ * Duplicated in shape from `@rebasepro/common`'s policy defaults on purpose:
104
+ * that one takes a `CollectionConfig`, this one is called from DDL code paths
105
+ * that hold looser objects, and both spellings must accept `auth: true` as well
106
+ * as `auth: { enabled: true }`.
107
+ */
108
+ function isAuthCollection(collection) {
109
+ const auth = collection?.auth;
110
+ if (auth === true) return true;
111
+ return typeof auth === "object" && auth !== null && auth.enabled === true;
112
+ }
113
+ //#endregion
114
+ export { isAuthCollection as i, authUsersColumnDefinition as n, authUsersColumnSql as r, AUTH_USERS_COLUMNS as t };
115
+
116
+ //# sourceMappingURL=auth-users-columns-D2LBFrMH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth-users-columns-D2LBFrMH.js","names":[],"sources":["../src/schema/auth-users-columns.ts"],"sourcesContent":["/**\n * The one description of what an auth user table's columns must be.\n *\n * ## Why this exists\n *\n * Three different code paths create `rebase.users`, and before this module they\n * disagreed about it:\n *\n * | column | `db push` (generator) | `ensureAuthTablesExist` | `ensureCollectionTables` |\n * |------------------|-----------------------|-------------------------|--------------------------|\n * | `email` | `TEXT UNIQUE NOT NULL`| `TEXT NOT NULL` + CHECK | `TEXT` (nullable) |\n * | `roles` | `TEXT[]` | `NOT NULL DEFAULT '{}'` | nullable, no default |\n * | `email_verified` | `BOOLEAN` | `NOT NULL DEFAULT FALSE`| nullable |\n * | `created_at` | `DEFAULT now()` | `NOT NULL DEFAULT NOW()`| no default |\n *\n * They are all `CREATE TABLE IF NOT EXISTS` / `ADD COLUMN IF NOT EXISTS`, so\n * whichever ran first decided the table and the other two silently no-op'd.\n * Boot order therefore chose the constraints: a managed deploy (collection\n * tables first) got a users table whose `email` was nullable and whose\n * `email_verified` had no default, while the same project pushed from a\n * checkout got the strict one. In the same table, `is_anonymous` came out\n * `NOT NULL DEFAULT false` — because *that* column existed in only one of the\n * three lists, so its owner's definition won by default.\n *\n * A second consequence was drift in the other direction. The scaffold's\n * `users.ts` describes 12 columns; auth needs 14. `db push` is declarative and\n * builds its desired state from the collection alone, so the two columns only\n * auth knows about (`is_anonymous`, `tokens_valid_after`) read as unmanaged\n * drift, and a push run after the server had booted once planned to DROP them.\n *\n * Both problems are the same problem: no single place said what this table is.\n * This is that place. Every creator asks here first and only then falls back to\n * the collection's own property definitions, so a column auth owns has one\n * definition regardless of who gets there first, and a column the developer\n * added to their users collection still behaves like any other field.\n *\n * ## What belongs here\n *\n * Only columns the auth services read or write. A developer's own additions to\n * their users collection (`bio`, `stripe_customer_id`) are ordinary columns and\n * must NOT be listed — they are generated from the collection like every other\n * field, and listing them here would freeze a user's schema.\n *\n * `id` is deliberately absent: its type comes from the collection's id property\n * (uuid / increment / text) and each creator already derives it.\n *\n * Keep in step with {@link AUTH_SCHEMA_VERSION} when a change here makes an\n * older runtime unable to work against a migrated table.\n */\n\n/**\n * A column auth owns.\n *\n * Structured rather than one SQL string because the same facts are needed in\n * three grammars — a `CREATE TABLE` column list, an `ADD COLUMN IF NOT EXISTS`,\n * and a pair of `ALTER COLUMN … SET DEFAULT` / `SET NOT NULL` reconciles for a\n * table that already exists with the wrong shape. Parsing a string back apart\n * for the third of those is how the copies drifted in the first place.\n */\nexport interface AuthUsersColumn {\n /** Physical column name. */\n column: string;\n /** Postgres type. */\n type: string;\n /** Default expression, verbatim, or absent for no default. */\n default?: string;\n /** Whether the column is NOT NULL. */\n notNull?: boolean;\n}\n\n/**\n * `email` is NOT NULL on purpose, and the anonymous sign-in route depends on it\n * — it synthesizes `anon_<32 hex>@anonymous.local` rather than inserting NULL.\n * The 320-char bound (RFC 5321) is a CHECK rather than a `VARCHAR(n)`, added\n * separately by `ensureAuthTablesExist` so it can be `NOT VALID` on an adopted\n * table that already holds a longer row.\n */\nexport const AUTH_USERS_COLUMNS: readonly AuthUsersColumn[] = [\n { column: \"email\", type: \"TEXT\", notNull: true },\n { column: \"display_name\", type: \"TEXT\" },\n { column: \"photo_url\", type: \"TEXT\" },\n { column: \"roles\", type: \"TEXT[]\", default: \"'{}'\", notNull: true },\n { column: \"password_hash\", type: \"TEXT\" },\n { column: \"email_verified\", type: \"BOOLEAN\", default: \"FALSE\", notNull: true },\n { column: \"email_verification_token\", type: \"TEXT\" },\n { column: \"email_verification_sent_at\", type: \"TIMESTAMP WITH TIME ZONE\" },\n { column: \"is_anonymous\", type: \"BOOLEAN\", default: \"FALSE\", notNull: true },\n { column: \"metadata\", type: \"JSONB\", default: \"'{}'\", notNull: true },\n { column: \"tokens_valid_after\", type: \"TIMESTAMP WITH TIME ZONE\" },\n { column: \"created_at\", type: \"TIMESTAMP WITH TIME ZONE\", default: \"NOW()\", notNull: true },\n { column: \"updated_at\", type: \"TIMESTAMP WITH TIME ZONE\", default: \"NOW()\", notNull: true }\n];\n\nconst BY_COLUMN = new Map(AUTH_USERS_COLUMNS.map(c => [c.column, c]));\n\n/** Type + inline constraints, as they appear after the column name. */\nexport function authUsersColumnSql(spec: AuthUsersColumn): string {\n return [\n spec.type,\n spec.default !== undefined ? `DEFAULT ${spec.default}` : \"\",\n spec.notNull ? \"NOT NULL\" : \"\"\n ].filter(Boolean).join(\" \");\n}\n\n/**\n * The auth-owned definition for a physical column name, or `undefined` when\n * auth does not own it.\n *\n * Callers pass the RESOLVED column name (after `columnName` mapping), because\n * that is the only name the three creators agree on: the scaffold's users\n * collection spells the property `displayName` and the column `display_name`.\n */\nexport function authUsersColumnDefinition(column: string): string | undefined {\n const spec = BY_COLUMN.get(column);\n return spec ? authUsersColumnSql(spec) : undefined;\n}\n\n/**\n * Whether a collection is an auth collection, i.e. whether the definitions in\n * this module apply to its table at all.\n *\n * Duplicated in shape from `@rebasepro/common`'s policy defaults on purpose:\n * that one takes a `CollectionConfig`, this one is called from DDL code paths\n * that hold looser objects, and both spellings must accept `auth: true` as well\n * as `auth: { enabled: true }`.\n */\nexport function isAuthCollection(collection: unknown): boolean {\n const auth = (collection as { auth?: unknown } | undefined)?.auth;\n if (auth === true) return true;\n return typeof auth === \"object\" && auth !== null && (auth as { enabled?: unknown }).enabled === true;\n}\n"],"mappings":";;;;;;;;;;AA6EA,IAAa,qBAAiD;CAC1D;EAAE,QAAQ;EAAS,MAAM;EAAQ,SAAS;CAAK;CAC/C;EAAE,QAAQ;EAAgB,MAAM;CAAO;CACvC;EAAE,QAAQ;EAAa,MAAM;CAAO;CACpC;EAAE,QAAQ;EAAS,MAAM;EAAU,SAAS;EAAQ,SAAS;CAAK;CAClE;EAAE,QAAQ;EAAiB,MAAM;CAAO;CACxC;EAAE,QAAQ;EAAkB,MAAM;EAAW,SAAS;EAAS,SAAS;CAAK;CAC7E;EAAE,QAAQ;EAA4B,MAAM;CAAO;CACnD;EAAE,QAAQ;EAA8B,MAAM;CAA2B;CACzE;EAAE,QAAQ;EAAgB,MAAM;EAAW,SAAS;EAAS,SAAS;CAAK;CAC3E;EAAE,QAAQ;EAAY,MAAM;EAAS,SAAS;EAAQ,SAAS;CAAK;CACpE;EAAE,QAAQ;EAAsB,MAAM;CAA2B;CACjE;EAAE,QAAQ;EAAc,MAAM;EAA4B,SAAS;EAAS,SAAS;CAAK;CAC1F;EAAE,QAAQ;EAAc,MAAM;EAA4B,SAAS;EAAS,SAAS;CAAK;AAC9F;AAEA,IAAM,YAAY,IAAI,IAAI,mBAAmB,KAAI,MAAK,CAAC,EAAE,QAAQ,CAAC,CAAC,CAAC;;AAGpE,SAAgB,mBAAmB,MAA+B;CAC9D,OAAO;EACH,KAAK;EACL,KAAK,YAAY,KAAA,IAAY,WAAW,KAAK,YAAY;EACzD,KAAK,UAAU,aAAa;CAChC,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,KAAK,GAAG;AAC9B;;;;;;;;;AAUA,SAAgB,0BAA0B,QAAoC;CAC1E,MAAM,OAAO,UAAU,IAAI,MAAM;CACjC,OAAO,OAAO,mBAAmB,IAAI,IAAI,KAAA;AAC7C;;;;;;;;;;AAWA,SAAgB,iBAAiB,YAA8B;CAC3D,MAAM,OAAQ,YAA+C;CAC7D,IAAI,SAAS,MAAM,OAAO;CAC1B,OAAO,OAAO,SAAS,YAAY,SAAS,QAAS,KAA+B,YAAY;AACpG"}
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Which of the two things `rebase db backup …` means.
3
+ *
4
+ * The cloud family spells the listing `rebase cloud db backup list`. Locally
5
+ * the same words *created a backup*: `backup` dispatched straight to
6
+ * `backupCommand`, which parsed permissively and dropped "list" into the
7
+ * positionals it never reads. One CLI, two spellings, and the wrong guess wrote
8
+ * a dump instead of reading one — quiet, slow, and on a large database not
9
+ * free.
10
+ *
11
+ * A separate module for the same reason `branch-argv.ts` is one: the decision
12
+ * is pure, and the dispatch it lives in cannot be imported without loading the
13
+ * environment and reaching for a database.
14
+ */
15
+ export type BackupAction = "create" | "list";
16
+ /**
17
+ * @param rawArgs the driver's whole line, `["db", "backup", …]`.
18
+ */
19
+ export declare function backupActionOf(rawArgs: readonly string[]): BackupAction;
@@ -0,0 +1,408 @@
1
+ import { createRequire as __createRequire } from "module";
2
+ __createRequire(import.meta.url);
3
+ import { a as __toESM, t as require___vite_browser_external } from "./__vite-browser-external-BnuHet1e.js";
4
+ import { n as outError, r as outWarn, t as out } from "./cli-output-CNdMql-L.js";
5
+ import { D as parseBackupDestination, P as withDatabaseName, T as globalsFileForDump, h as validateDump, i as createDump, j as resolveConnectionString, k as parseDbNameFromUrl, l as listBackups, m as uploadBackup, n as applyGlobals, o as discardPartialDump, p as restoreDump, s as ensureDatabaseExists, t as BackupToolError, u as preflight } from "./backup-service-Br3tqwsy.js";
6
+ import { t as chalk } from "./source-Br7L7GOI.js";
7
+ import { t as require_arg } from "./arg-Dni7MzLB.js";
8
+ import fs from "fs";
9
+ import path from "path";
10
+ import os from "os";
11
+ //#region src/backup/backup-cli.ts
12
+ var import_arg = /* @__PURE__ */ __toESM(require_arg(), 1);
13
+ var import___vite_browser_external = /* @__PURE__ */ __toESM(require___vite_browser_external(), 1);
14
+ function formatBytes(bytes) {
15
+ if (bytes < 1024) return `${bytes} B`;
16
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
17
+ if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
18
+ return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
19
+ }
20
+ /**
21
+ * Build a StorageController for an object-storage destination from the same
22
+ * `S3_*` env vars the backend uses. Returns `null` for local destinations.
23
+ */
24
+ async function resolveStorageForDestination(dest, env) {
25
+ if (dest.kind === "local") return null;
26
+ if (dest.kind === "gcs") {
27
+ const { GCSStorageController } = await import("@rebasepro/server");
28
+ return new GCSStorageController({
29
+ type: "gcs",
30
+ bucket: dest.bucket
31
+ });
32
+ }
33
+ if (!env.S3_ACCESS_KEY_ID || !env.S3_SECRET_ACCESS_KEY) throw new BackupToolError("S3 destination requires S3_ACCESS_KEY_ID and S3_SECRET_ACCESS_KEY in the environment.", "Set the same S3_* variables your backend uses for storage.");
34
+ const { S3StorageController } = await import("@rebasepro/server");
35
+ return new S3StorageController({
36
+ type: "s3",
37
+ bucket: dest.bucket,
38
+ region: env.S3_REGION || "auto",
39
+ accessKeyId: env.S3_ACCESS_KEY_ID,
40
+ secretAccessKey: env.S3_SECRET_ACCESS_KEY,
41
+ endpoint: env.S3_ENDPOINT,
42
+ forcePathStyle: env.S3_FORCE_PATH_STYLE === "true"
43
+ });
44
+ }
45
+ function requireConnection() {
46
+ const conn = resolveConnectionString(process.env);
47
+ if (!conn) {
48
+ outError(chalk.red("✗ DATABASE_URL is not set. Make sure your .env file is configured."));
49
+ process.exit(1);
50
+ }
51
+ return conn;
52
+ }
53
+ async function promptConfirm(question) {
54
+ if (!process.stdin.isTTY) return false;
55
+ const rl = import___vite_browser_external.default.createInterface({
56
+ input: process.stdin,
57
+ output: process.stdout
58
+ });
59
+ try {
60
+ const answer = await new Promise((resolve) => rl.question(question, resolve));
61
+ return /^y(es)?$/i.test(answer.trim());
62
+ } finally {
63
+ rl.close();
64
+ }
65
+ }
66
+ async function backupCommand(rawArgs) {
67
+ const args = (0, import_arg.default)({
68
+ "--out": String,
69
+ "--output": "--out",
70
+ "--exclude-schema": [String],
71
+ "--no-owner": Boolean,
72
+ "--enable-row-security": Boolean,
73
+ "--row-security-role": String,
74
+ "-o": "--out"
75
+ }, {
76
+ argv: rawArgs.slice(2),
77
+ permissive: true
78
+ });
79
+ if (args._.includes("--help") || rawArgs.includes("--help")) {
80
+ printBackupHelp();
81
+ return;
82
+ }
83
+ const connectionString = requireConnection();
84
+ const dbName = parseDbNameFromUrl(connectionString) ?? "database";
85
+ const out$1 = args["--out"] || process.env.BACKUP_DESTINATION || path.join(process.cwd(), "backups");
86
+ const dest = parseBackupDestination(out$1);
87
+ out("");
88
+ out(chalk.bold(" 💾 Rebase DB Backup"));
89
+ out(chalk.gray(` Database: ${dbName}`));
90
+ out(chalk.gray(` Destination: ${out$1}`));
91
+ out("");
92
+ const pf = await preflight("pg_dump", connectionString);
93
+ if (!pf.compatible) {
94
+ outError(chalk.red(` ✗ ${pf.reason}`));
95
+ process.exit(1);
96
+ }
97
+ out(chalk.gray(` Using pg_dump ${pf.toolMajor} against server ${pf.serverMajor}.`));
98
+ const rowSecurity = args["--enable-row-security"] ? {
99
+ uid: "rebase-db-backup",
100
+ roles: [args["--row-security-role"] || "admin"]
101
+ } : void 0;
102
+ if (rowSecurity) {
103
+ outWarn("");
104
+ outWarn(chalk.yellow(" ⚠ Dumping with row-level security ON."));
105
+ outWarn(chalk.gray(` Reading as roles [${rowSecurity.roles.join(", ")}], which satisfies the generated`));
106
+ outWarn(chalk.gray(" `admin_full_access` policy. This backup contains exactly the rows those"));
107
+ outWarn(chalk.gray(" policies admit — a table whose policies have no admin rule comes out short,"));
108
+ outWarn(chalk.gray(" and pg_dump will not say so. Prefer granting the dumping role BYPASSRLS."));
109
+ outWarn("");
110
+ }
111
+ try {
112
+ if (dest.kind === "local") {
113
+ const explicitFile = dest.path.endsWith(".dump");
114
+ const dump = await createDump({
115
+ connectionString,
116
+ dbName,
117
+ outDir: explicitFile ? path.dirname(dest.path) : dest.path,
118
+ fileName: explicitFile ? path.basename(dest.path) : void 0,
119
+ excludeSchemas: args["--exclude-schema"],
120
+ noOwner: args["--no-owner"],
121
+ inheritStdio: true,
122
+ rowSecurity
123
+ });
124
+ await assertDumpValid(dump.localFile);
125
+ out("");
126
+ out(chalk.green(` ✓ Backup written to ${dump.localFile} (${formatBytes(dump.sizeBytes)})`));
127
+ if (dump.globalsFile) out(chalk.gray(` ✓ Roles captured to ${dump.globalsFile} (needed so RLS survives a restore).`));
128
+ } else {
129
+ const storage = await resolveStorageForDestination(dest, process.env);
130
+ const dump = await createDump({
131
+ connectionString,
132
+ dbName,
133
+ excludeSchemas: args["--exclude-schema"],
134
+ noOwner: args["--no-owner"],
135
+ inheritStdio: true,
136
+ rowSecurity
137
+ });
138
+ try {
139
+ await assertDumpValid(dump.localFile);
140
+ const uploaded = await uploadBackup(storage, dump.localFile, dest);
141
+ out("");
142
+ out(chalk.green(` ✓ Backup uploaded to ${uploaded.storageUrl} (${formatBytes(dump.sizeBytes)})`));
143
+ if (dump.globalsFile && fs.existsSync(dump.globalsFile)) {
144
+ const globalsUpload = await uploadBackup(storage, dump.globalsFile, dest);
145
+ out(chalk.gray(` ✓ Roles uploaded to ${globalsUpload.storageUrl} (needed so RLS survives a restore).`));
146
+ }
147
+ out(chalk.gray(" Ensure this bucket is private — backups may contain secrets and PII."));
148
+ } finally {
149
+ if (fs.existsSync(dump.localFile)) fs.unlinkSync(dump.localFile);
150
+ if (dump.globalsFile && fs.existsSync(dump.globalsFile)) fs.unlinkSync(dump.globalsFile);
151
+ }
152
+ }
153
+ out("");
154
+ } catch (err) {
155
+ reportError(err);
156
+ process.exit(1);
157
+ }
158
+ }
159
+ async function restoreCommand(rawArgs) {
160
+ const args = (0, import_arg.default)({
161
+ "--target-db": String,
162
+ "--create-db": Boolean,
163
+ "--clean": Boolean,
164
+ "--no-owner": Boolean,
165
+ "--continue-on-error": Boolean,
166
+ "--yes": Boolean,
167
+ "-y": "--yes"
168
+ }, {
169
+ argv: rawArgs.slice(2),
170
+ permissive: true
171
+ });
172
+ const backupArg = args._[0];
173
+ if (!backupArg || rawArgs.includes("--help")) {
174
+ printRestoreHelp();
175
+ if (!backupArg && !rawArgs.includes("--help")) process.exit(1);
176
+ return;
177
+ }
178
+ const baseConnection = requireConnection();
179
+ const targetDb = args["--target-db"] ?? parseDbNameFromUrl(baseConnection) ?? void 0;
180
+ const targetConnection = args["--target-db"] ? withDatabaseName(baseConnection, args["--target-db"]) : baseConnection;
181
+ out("");
182
+ out(chalk.bold(" ♻️ Rebase DB Restore"));
183
+ out(chalk.gray(` Source: ${backupArg}`));
184
+ out(chalk.gray(` Target: ${targetDb ?? "(from DATABASE_URL)"}`));
185
+ out("");
186
+ let localFile;
187
+ let globalsSql = null;
188
+ let cleanupTemp = false;
189
+ try {
190
+ if (/^(s3|gs):\/\//.test(backupArg)) {
191
+ const storage = await resolveStorageForDestination(parseBackupDestination(backupArg.replace(/\/[^/]+$/, "")), process.env);
192
+ if (!storage) throw new BackupToolError("Could not resolve storage for the given URL.");
193
+ const key = backupArg.replace(/^(s3|gs):\/\/[^/]+\//, "");
194
+ const bucket = backupArg.replace(/^(s3|gs):\/\/([^/]+)\/.*$/, "$2");
195
+ const file = await storage.getObject(key, bucket);
196
+ if (!file) throw new BackupToolError(`Backup not found in storage: ${backupArg}`);
197
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "rebase-restore-"));
198
+ localFile = path.join(tmpDir, path.basename(key));
199
+ fs.writeFileSync(localFile, Buffer.from(await file.arrayBuffer()));
200
+ cleanupTemp = true;
201
+ const globalsObj = await storage.getObject(globalsFileForDump(key), bucket);
202
+ if (globalsObj) globalsSql = Buffer.from(await globalsObj.arrayBuffer()).toString("utf-8");
203
+ } else {
204
+ localFile = path.resolve(backupArg);
205
+ if (!fs.existsSync(localFile)) {
206
+ outError(chalk.red(` ✗ Backup file not found: ${localFile}`));
207
+ process.exit(1);
208
+ }
209
+ const globalsPath = globalsFileForDump(localFile);
210
+ if (fs.existsSync(globalsPath)) globalsSql = fs.readFileSync(globalsPath, "utf-8");
211
+ }
212
+ const pf = await preflight("pg_restore", baseConnection);
213
+ if (!pf.compatible) {
214
+ outError(chalk.red(` ✗ ${pf.reason}`));
215
+ process.exit(1);
216
+ }
217
+ if (args["--create-db"] && !targetDb) {
218
+ outError(chalk.red(" ✗ --create-db requires a resolvable target database name (use --target-db)."));
219
+ process.exit(1);
220
+ }
221
+ if (!args["--yes"]) {
222
+ outWarn(chalk.yellow(` ⚠️ This will restore into "${targetDb ?? "the target database"}" and may overwrite existing data.`));
223
+ if (!await promptConfirm(chalk.yellow(" Type 'yes' to continue: "))) {
224
+ out(chalk.gray(" Aborted. No changes were made."));
225
+ process.exit(1);
226
+ }
227
+ }
228
+ if (args["--create-db"]) {
229
+ const created = await ensureDatabaseExists(baseConnection, targetDb);
230
+ out(chalk.gray(created ? ` ✓ Created database "${targetDb}".` : ` • Database "${targetDb}" already exists.`));
231
+ }
232
+ if (globalsSql) {
233
+ out(chalk.gray(" Recreating cluster roles from the backup's roles sidecar…"));
234
+ const { applied, skipped } = await applyGlobals(targetConnection, globalsSql, (m) => out(chalk.gray(m)));
235
+ out(chalk.gray(` ✓ Roles: ${applied} applied, ${skipped} skipped (already present or not permitted).`));
236
+ } else {
237
+ outWarn(chalk.yellow(" ⚠️ No roles sidecar (.globals.sql) accompanies this backup."));
238
+ outWarn(chalk.yellow(" If the dump grants to roles that don't exist (e.g. rebase_user), the restore"));
239
+ outWarn(chalk.yellow(" will fail — recreate those roles first, or use a backup that includes its globals."));
240
+ }
241
+ await restoreDump({
242
+ connectionString: targetConnection,
243
+ inputFile: localFile,
244
+ clean: args["--clean"],
245
+ noOwner: args["--no-owner"],
246
+ exitOnError: !args["--continue-on-error"],
247
+ inheritStdio: true
248
+ });
249
+ out("");
250
+ out(chalk.green(` ✓ Restore completed into "${targetDb ?? "the target database"}".`));
251
+ out("");
252
+ } catch (err) {
253
+ reportError(err);
254
+ process.exit(1);
255
+ } finally {
256
+ if (cleanupTemp && typeof localFile === "string" && fs.existsSync(localFile)) fs.rmSync(path.dirname(localFile), {
257
+ recursive: true,
258
+ force: true
259
+ });
260
+ }
261
+ }
262
+ async function backupsCommand(rawArgs) {
263
+ const action = rawArgs[2];
264
+ if (!action || action === "--help") {
265
+ printBackupsHelp();
266
+ return;
267
+ }
268
+ if (action !== "list") {
269
+ outError(chalk.red(`Unknown backups action: "${action}". Valid: list`));
270
+ process.exit(1);
271
+ }
272
+ const out$2 = (0, import_arg.default)({
273
+ "--out": String,
274
+ "--output": "--out",
275
+ "-o": "--out"
276
+ }, {
277
+ argv: rawArgs.slice(3),
278
+ permissive: true
279
+ })["--out"] || process.env.BACKUP_DESTINATION || path.join(process.cwd(), "backups");
280
+ const dest = parseBackupDestination(out$2);
281
+ try {
282
+ const backups = await listBackups(dest, await resolveStorageForDestination(dest, process.env) ?? void 0);
283
+ out("");
284
+ if (backups.length === 0) out(chalk.gray(` No backups found at ${out$2}.`));
285
+ else {
286
+ out(chalk.bold(` 💾 ${backups.length} backup(s) at ${out$2}:`));
287
+ out("");
288
+ for (const b of backups) {
289
+ const when = b.createdAt ? b.createdAt.toISOString() : "unknown date";
290
+ const name = dest.kind === "local" ? path.basename(b.key) : b.key;
291
+ const empty = b.sizeBytes === 0;
292
+ const size = b.sizeBytes === void 0 ? "" : ` — ${formatBytes(b.sizeBytes)}`;
293
+ if (empty) out(` ${chalk.red("○")} ${chalk.bold(name)} ${chalk.gray(`— ${when}`)}${chalk.red(" — EMPTY, not restorable")}`);
294
+ else out(` ${chalk.green("●")} ${chalk.bold(name)} ${chalk.gray(`— ${when}${size}`)}`);
295
+ }
296
+ if (backups.some((b) => b.sizeBytes === 0)) {
297
+ out("");
298
+ out(chalk.yellow(" ⚠ Empty files above are leftovers from a failed backup. Delete them:"));
299
+ out(chalk.gray(" they count as recent backups for retention but restore nothing."));
300
+ }
301
+ }
302
+ out("");
303
+ } catch (err) {
304
+ reportError(err);
305
+ process.exit(1);
306
+ }
307
+ }
308
+ /**
309
+ * Verify a freshly written dump; abort the command if it looks corrupt.
310
+ *
311
+ * Discards the artifact on the way out. Refusing to *report* success was never
312
+ * enough on its own: the file stayed on disk, `rebase db backups list` showed
313
+ * it as an ordinary entry, and retention — which ranks by timestamp and never
314
+ * looks at size — would protect it as one of the `keepMinimum` newest while
315
+ * pruning a real backup underneath it. The roles sidecar goes too; the two are
316
+ * uploaded and pruned as a pair, so half a pair is not a backup either.
317
+ */
318
+ async function assertDumpValid(localFile) {
319
+ const check = await validateDump(localFile);
320
+ if (!check.ok) {
321
+ discardPartialDump(globalsFileForDump(localFile));
322
+ discardPartialDump(localFile);
323
+ throw new BackupToolError(`The backup failed validation and was discarded: ${check.reason}`, "The dump was corrupt or truncated, so nothing was kept. Investigate before relying on this destination.");
324
+ }
325
+ }
326
+ function reportError(err) {
327
+ if (err instanceof BackupToolError) {
328
+ outError(chalk.red(` ✗ ${err.message}`));
329
+ if (err.hint) outError(chalk.gray(` ${err.hint}`));
330
+ } else outError(chalk.red(` ✗ ${err instanceof Error ? err.message : String(err)}`));
331
+ }
332
+ function printBackupHelp() {
333
+ out(`
334
+ ${chalk.bold("rebase db backup")} — Create a database backup (pg_dump, custom format)
335
+
336
+ ${chalk.green.bold("Usage")}
337
+ rebase db backup [--out <path|s3://bucket/prefix>] [options]
338
+
339
+ ${chalk.green.bold("Options")}
340
+ ${chalk.blue("--out, -o")} <dest> Local path or s3://…/gs://… URL (default: ./backups)
341
+ ${chalk.blue("--exclude-schema")} <s> Exclude a schema (repeatable)
342
+ ${chalk.blue("--no-owner")} Omit ownership commands from the dump
343
+ ${chalk.blue("--enable-row-security")} Dump as an admin subject instead of failing on RLS
344
+ ${chalk.red("(may produce a partial dump — see below)")}
345
+ ${chalk.blue("--row-security-role")} <r> Role to read as with the flag above (default: admin)
346
+
347
+ ${chalk.green.bold("Row-level security")}
348
+ On a managed Postgres the dumping role usually owns nothing and has no
349
+ BYPASSRLS, so pg_dump refuses:
350
+
351
+ ERROR: query would be affected by row-level security policy for table "..."
352
+
353
+ That refusal is the safe behaviour. --enable-row-security replaces it by
354
+ reading as an admin subject: Rebase sets app.uid/app.user_roles so the
355
+ generated admin_full_access policy admits the dump. The dump then contains
356
+ exactly what those policies admit ${chalk.red("and no error is raised for what they do not")} —
357
+ a table whose policies lack an admin rule comes out short, silently.
358
+
359
+ Granting the dumping role BYPASSRLS is the option that keeps a backup
360
+ meaning "every row".
361
+
362
+ ${chalk.green.bold("Notes")}
363
+ Backups may contain secrets and PII. Use private storage destinations and
364
+ enable encryption-at-rest. See docs/backups.md.
365
+ `);
366
+ }
367
+ function printRestoreHelp() {
368
+ out(`
369
+ ${chalk.bold("rebase db restore")} — Restore a database from a backup (pg_restore)
370
+
371
+ ${chalk.green.bold("Usage")}
372
+ rebase db restore <backup> [options]
373
+
374
+ ${chalk.green.bold("Arguments")}
375
+ <backup> Local .dump file, or s3://…/gs://… object key
376
+
377
+ ${chalk.green.bold("Options")}
378
+ ${chalk.blue("--target-db")} <name> Restore into this database instead of DATABASE_URL's
379
+ ${chalk.blue("--create-db")} Create the target database first if it doesn't exist
380
+ ${chalk.blue("--clean")} Drop existing objects before recreating them
381
+ ${chalk.blue("--no-owner")} Ignore ownership from the dump
382
+ ${chalk.blue("--continue-on-error")} Log and continue past errors ${chalk.red("(may leave RLS un-enforced!)")}
383
+ ${chalk.blue("--yes, -y")} Skip the interactive confirmation ${chalk.red("(destructive!)")}
384
+
385
+ ${chalk.red.bold("Warning")}
386
+ Restore is destructive and never runs automatically. Without --yes it
387
+ requires an interactive 'yes'. Prefer --create-db/--target-db to restore
388
+ into a fresh database rather than overwriting a live one.
389
+
390
+ By default the restore aborts on the first error (--exit-on-error) so a
391
+ skipped GRANT never silently leaves RLS un-enforced. Roles are recreated
392
+ from the backup's .globals.sql sidecar first; keep that file next to the
393
+ dump. Use --continue-on-error only when you understand the consequences.
394
+ `);
395
+ }
396
+ function printBackupsHelp() {
397
+ out(`
398
+ ${chalk.bold("rebase db backups")} — Manage stored backups
399
+
400
+ ${chalk.green.bold("Usage")}
401
+ rebase db backups list [--out <path|s3://bucket/prefix>]
402
+ rebase db backup list [--out <path|s3://bucket/prefix>] ${chalk.gray("(the same thing)")}
403
+ `);
404
+ }
405
+ //#endregion
406
+ export { backupCommand, backupsCommand, restoreCommand };
407
+
408
+ //# sourceMappingURL=backup-cli-oM9WQVlV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"backup-cli-oM9WQVlV.js","names":[],"sources":["../src/backup/backup-cli.ts"],"sourcesContent":["/**\n * CLI handlers for `rebase db backup`, `rebase db restore`, and\n * `rebase db backups list`. Kept out of the main `cli.ts` dispatcher so the\n * backup surface stays self-contained.\n */\nimport arg from \"arg\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport os from \"os\";\nimport readline from \"readline\";\nimport chalk from \"chalk\";\n// Aliased: `out` is already a local in two of the commands below (the `--out`\n// backup destination).\nimport { out as print, outWarn, outError } from \"../cli-output\";\nimport type { StorageController } from \"@rebasepro/server\";\nimport {\n BackupDestination,\n globalsFileForDump,\n parseBackupDestination,\n parseDbNameFromUrl,\n resolveConnectionString,\n withDatabaseName\n} from \"./pg-tools\";\nimport {\n applyGlobals,\n BackupToolError,\n createDump,\n discardPartialDump,\n ensureDatabaseExists,\n listBackups,\n preflight,\n restoreDump,\n uploadBackup,\n validateDump\n} from \"./backup-service\";\n\nfunction formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;\n}\n\n/**\n * Build a StorageController for an object-storage destination from the same\n * `S3_*` env vars the backend uses. Returns `null` for local destinations.\n */\nasync function resolveStorageForDestination(\n dest: BackupDestination,\n env: Record<string, string | undefined>\n): Promise<StorageController | null> {\n if (dest.kind === \"local\") return null;\n if (dest.kind === \"gcs\") {\n const { GCSStorageController } = await import(\"@rebasepro/server\");\n return new GCSStorageController({ type: \"gcs\", bucket: dest.bucket });\n }\n // s3 (also covers R2/MinIO/Hetzner/GCS-interop via S3_ENDPOINT)\n if (!env.S3_ACCESS_KEY_ID || !env.S3_SECRET_ACCESS_KEY) {\n throw new BackupToolError(\n \"S3 destination requires S3_ACCESS_KEY_ID and S3_SECRET_ACCESS_KEY in the environment.\",\n \"Set the same S3_* variables your backend uses for storage.\"\n );\n }\n const { S3StorageController } = await import(\"@rebasepro/server\");\n return new S3StorageController({\n type: \"s3\",\n bucket: dest.bucket,\n region: env.S3_REGION || \"auto\",\n accessKeyId: env.S3_ACCESS_KEY_ID,\n secretAccessKey: env.S3_SECRET_ACCESS_KEY,\n endpoint: env.S3_ENDPOINT,\n forcePathStyle: env.S3_FORCE_PATH_STYLE === \"true\"\n });\n}\n\nfunction requireConnection(): string {\n const conn = resolveConnectionString(process.env);\n if (!conn) {\n outError(chalk.red(\"✗ DATABASE_URL is not set. Make sure your .env file is configured.\"));\n process.exit(1);\n }\n return conn;\n}\n\nasync function promptConfirm(question: string): Promise<boolean> {\n // Non-interactive shells (CI, pipes) can't answer — treat as \"no\".\n if (!process.stdin.isTTY) return false;\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n try {\n const answer: string = await new Promise((resolve) => rl.question(question, resolve));\n return /^y(es)?$/i.test(answer.trim());\n } finally {\n rl.close();\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// rebase db backup\n// ─────────────────────────────────────────────────────────────────────────\nexport async function backupCommand(rawArgs: string[]): Promise<void> {\n const args = arg(\n {\n \"--out\": String,\n // The same alias `build` and `cloud env pull` carry. `--output` is\n // the canonical spelling in this CLI and this command took only\n // `--out`, so `rebase db backup --output ./backups` wrote to\n // ./backups *and* to the default directory — the flag was ignored\n // and its value became a positional.\n \"--output\": \"--out\",\n \"--exclude-schema\": [String],\n \"--no-owner\": Boolean,\n \"--enable-row-security\": Boolean,\n \"--row-security-role\": String,\n \"-o\": \"--out\"\n },\n { argv: rawArgs.slice(2), permissive: true }\n );\n\n if (args._.includes(\"--help\") || rawArgs.includes(\"--help\")) {\n printBackupHelp();\n return;\n }\n\n const connectionString = requireConnection();\n const dbName = parseDbNameFromUrl(connectionString) ?? \"database\";\n const out = args[\"--out\"] || process.env.BACKUP_DESTINATION || path.join(process.cwd(), \"backups\");\n const dest = parseBackupDestination(out);\n\n print(\"\");\n print(chalk.bold(\" 💾 Rebase DB Backup\"));\n print(chalk.gray(` Database: ${dbName}`));\n print(chalk.gray(` Destination: ${out}`));\n print(\"\");\n\n // Version pre-flight (doctor-style).\n const pf = await preflight(\"pg_dump\", connectionString);\n if (!pf.compatible) {\n outError(chalk.red(` ✗ ${pf.reason}`));\n process.exit(1);\n }\n print(chalk.gray(` Using pg_dump ${pf.toolMajor} against server ${pf.serverMajor}.`));\n\n // Opt-in, and loud. With row security on, pg_dump stops refusing to read\n // rows it cannot see and starts leaving them out — an exit-0 backup that\n // is quietly short. Anyone choosing that should know they chose it.\n const rowSecurity = args[\"--enable-row-security\"]\n ? { uid: \"rebase-db-backup\", roles: [args[\"--row-security-role\"] || \"admin\"] }\n : undefined;\n\n if (rowSecurity) {\n outWarn(\"\");\n outWarn(chalk.yellow(\" ⚠ Dumping with row-level security ON.\"));\n outWarn(chalk.gray(` Reading as roles [${rowSecurity.roles.join(\", \")}], which satisfies the generated`));\n outWarn(chalk.gray(\" `admin_full_access` policy. This backup contains exactly the rows those\"));\n outWarn(chalk.gray(\" policies admit — a table whose policies have no admin rule comes out short,\"));\n outWarn(chalk.gray(\" and pg_dump will not say so. Prefer granting the dumping role BYPASSRLS.\"));\n outWarn(\"\");\n }\n\n try {\n if (dest.kind === \"local\") {\n // Honour an explicit `…/name.dump` path; otherwise treat it as a\n // directory and auto-name the file.\n const explicitFile = dest.path.endsWith(\".dump\");\n const dump = await createDump({\n connectionString,\n dbName,\n outDir: explicitFile ? path.dirname(dest.path) : dest.path,\n fileName: explicitFile ? path.basename(dest.path) : undefined,\n excludeSchemas: args[\"--exclude-schema\"],\n noOwner: args[\"--no-owner\"],\n inheritStdio: true,\n rowSecurity\n });\n await assertDumpValid(dump.localFile);\n print(\"\");\n print(chalk.green(` ✓ Backup written to ${dump.localFile} (${formatBytes(dump.sizeBytes)})`));\n if (dump.globalsFile) {\n print(chalk.gray(` ✓ Roles captured to ${dump.globalsFile} (needed so RLS survives a restore).`));\n }\n } else {\n const storage = await resolveStorageForDestination(dest, process.env);\n const dump = await createDump({\n connectionString,\n dbName,\n excludeSchemas: args[\"--exclude-schema\"],\n noOwner: args[\"--no-owner\"],\n inheritStdio: true,\n rowSecurity\n });\n try {\n await assertDumpValid(dump.localFile);\n const uploaded = await uploadBackup(storage!, dump.localFile, dest);\n print(\"\");\n print(chalk.green(` ✓ Backup uploaded to ${uploaded.storageUrl} (${formatBytes(dump.sizeBytes)})`));\n // Upload the roles sidecar next to the dump so a restore can\n // recreate roles the dump's GRANT/RLS statements depend on.\n if (dump.globalsFile && fs.existsSync(dump.globalsFile)) {\n const globalsUpload = await uploadBackup(storage!, dump.globalsFile, dest);\n print(chalk.gray(` ✓ Roles uploaded to ${globalsUpload.storageUrl} (needed so RLS survives a restore).`));\n }\n print(chalk.gray(\" Ensure this bucket is private — backups may contain secrets and PII.\"));\n } finally {\n if (fs.existsSync(dump.localFile)) fs.unlinkSync(dump.localFile);\n if (dump.globalsFile && fs.existsSync(dump.globalsFile)) fs.unlinkSync(dump.globalsFile);\n }\n }\n print(\"\");\n } catch (err) {\n reportError(err);\n process.exit(1);\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// rebase db restore <backup>\n// ─────────────────────────────────────────────────────────────────────────\nexport async function restoreCommand(rawArgs: string[]): Promise<void> {\n const args = arg(\n {\n \"--target-db\": String,\n \"--create-db\": Boolean,\n \"--clean\": Boolean,\n \"--no-owner\": Boolean,\n \"--continue-on-error\": Boolean,\n \"--yes\": Boolean,\n \"-y\": \"--yes\"\n },\n { argv: rawArgs.slice(2), permissive: true }\n );\n\n const backupArg = args._[0];\n if (!backupArg || rawArgs.includes(\"--help\")) {\n printRestoreHelp();\n if (!backupArg && !rawArgs.includes(\"--help\")) process.exit(1);\n return;\n }\n\n const baseConnection = requireConnection();\n\n // Choose the target connection: an explicit --target-db (or --create-db's\n // implied fresh db) swaps the database name so the live one isn't clobbered.\n const targetDb = args[\"--target-db\"] ?? parseDbNameFromUrl(baseConnection) ?? undefined;\n const targetConnection = args[\"--target-db\"]\n ? withDatabaseName(baseConnection, args[\"--target-db\"])\n : baseConnection;\n\n print(\"\");\n print(chalk.bold(\" ♻️ Rebase DB Restore\"));\n print(chalk.gray(` Source: ${backupArg}`));\n print(chalk.gray(` Target: ${targetDb ?? \"(from DATABASE_URL)\"}`));\n print(\"\");\n\n // Resolve the local file to restore from (download object-storage keys).\n // Also resolve the `.globals.sql` roles sidecar so cluster roles can be\n // recreated before the restore — without them the dump's GRANT/RLS\n // statements fail and RLS is silently lost.\n let localFile: string;\n let globalsSql: string | null = null;\n let cleanupTemp = false;\n try {\n if (/^(s3|gs):\\/\\//.test(backupArg)) {\n const dest = parseBackupDestination(backupArg.replace(/\\/[^/]+$/, \"\"));\n const storage = await resolveStorageForDestination(dest, process.env);\n if (!storage) throw new BackupToolError(\"Could not resolve storage for the given URL.\");\n const key = backupArg.replace(/^(s3|gs):\\/\\/[^/]+\\//, \"\");\n const bucket = backupArg.replace(/^(s3|gs):\\/\\/([^/]+)\\/.*$/, \"$2\");\n const file = await storage.getObject(key, bucket);\n if (!file) throw new BackupToolError(`Backup not found in storage: ${backupArg}`);\n const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), \"rebase-restore-\"));\n localFile = path.join(tmpDir, path.basename(key));\n fs.writeFileSync(localFile, Buffer.from(await file.arrayBuffer()));\n cleanupTemp = true;\n const globalsObj = await storage.getObject(globalsFileForDump(key), bucket);\n if (globalsObj) globalsSql = Buffer.from(await globalsObj.arrayBuffer()).toString(\"utf-8\");\n } else {\n localFile = path.resolve(backupArg);\n if (!fs.existsSync(localFile)) {\n outError(chalk.red(` ✗ Backup file not found: ${localFile}`));\n process.exit(1);\n }\n const globalsPath = globalsFileForDump(localFile);\n if (fs.existsSync(globalsPath)) globalsSql = fs.readFileSync(globalsPath, \"utf-8\");\n }\n\n // Version pre-flight. Check against the base connection — the server\n // version is identical for every database, and the target may not\n // exist yet when --create-db is used.\n const pf = await preflight(\"pg_restore\", baseConnection);\n if (!pf.compatible) {\n outError(chalk.red(` ✗ ${pf.reason}`));\n process.exit(1);\n }\n\n // `--create-db` needs a name before anything else can be decided.\n if (args[\"--create-db\"] && !targetDb) {\n outError(chalk.red(\" ✗ --create-db requires a resolvable target database name (use --target-db).\"));\n process.exit(1);\n }\n\n // Destructive-action gate. Restores overwrite data; never run without\n // an explicit yes (interactive confirmation or --yes).\n //\n // Ahead of `--create-db`, not after it. Creating the database first\n // meant an aborted run had already changed the cluster, while printing\n // \"No changes were made\" — and it left an empty database behind that a\n // second, confirmed run then reported as \"already exists\". The gate is\n // now the first thing that can stop the command, so its own message is\n // true whichever way the answer goes.\n if (!args[\"--yes\"]) {\n outWarn(chalk.yellow(\n ` ⚠️ This will restore into \"${targetDb ?? \"the target database\"}\" and may overwrite existing data.`\n ));\n const confirmed = await promptConfirm(chalk.yellow(\" Type 'yes' to continue: \"));\n if (!confirmed) {\n print(chalk.gray(\" Aborted. No changes were made.\"));\n process.exit(1);\n }\n }\n\n // Create the target database when requested.\n if (args[\"--create-db\"]) {\n const created = await ensureDatabaseExists(baseConnection, targetDb!);\n print(chalk.gray(created ? ` ✓ Created database \"${targetDb}\".` : ` • Database \"${targetDb}\" already exists.`));\n }\n\n // Recreate cluster roles before restoring so GRANT/RLS statements in\n // the dump apply. Best-effort and idempotent (see applyGlobals).\n if (globalsSql) {\n print(chalk.gray(\" Recreating cluster roles from the backup's roles sidecar…\"));\n const { applied, skipped } = await applyGlobals(\n targetConnection,\n globalsSql,\n (m) => print(chalk.gray(m))\n );\n print(chalk.gray(` ✓ Roles: ${applied} applied, ${skipped} skipped (already present or not permitted).`));\n } else {\n outWarn(chalk.yellow(\" ⚠️ No roles sidecar (.globals.sql) accompanies this backup.\"));\n outWarn(chalk.yellow(\" If the dump grants to roles that don't exist (e.g. rebase_user), the restore\"));\n outWarn(chalk.yellow(\" will fail — recreate those roles first, or use a backup that includes its globals.\"));\n }\n\n await restoreDump({\n connectionString: targetConnection,\n inputFile: localFile,\n clean: args[\"--clean\"],\n noOwner: args[\"--no-owner\"],\n // Fail loudly by default so a skipped GRANT never leaves RLS off.\n exitOnError: !args[\"--continue-on-error\"],\n inheritStdio: true\n });\n\n print(\"\");\n print(chalk.green(` ✓ Restore completed into \"${targetDb ?? \"the target database\"}\".`));\n print(\"\");\n } catch (err) {\n reportError(err);\n process.exit(1);\n } finally {\n if (cleanupTemp && typeof localFile! === \"string\" && fs.existsSync(localFile!)) {\n fs.rmSync(path.dirname(localFile!), { recursive: true, force: true });\n }\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// rebase db backups list\n// ─────────────────────────────────────────────────────────────────────────\nexport async function backupsCommand(rawArgs: string[]): Promise<void> {\n const action = rawArgs[2];\n if (!action || action === \"--help\") {\n printBackupsHelp();\n return;\n }\n if (action !== \"list\") {\n outError(chalk.red(`Unknown backups action: \"${action}\". Valid: list`));\n process.exit(1);\n }\n\n const args = arg({ \"--out\": String, \"--output\": \"--out\", \"-o\": \"--out\" }, { argv: rawArgs.slice(3), permissive: true });\n const out = args[\"--out\"] || process.env.BACKUP_DESTINATION || path.join(process.cwd(), \"backups\");\n const dest = parseBackupDestination(out);\n\n try {\n const storage = await resolveStorageForDestination(dest, process.env);\n const backups = await listBackups(dest, storage ?? undefined);\n print(\"\");\n if (backups.length === 0) {\n print(chalk.gray(` No backups found at ${out}.`));\n } else {\n print(chalk.bold(` 💾 ${backups.length} backup(s) at ${out}:`));\n print(\"\");\n for (const b of backups) {\n const when = b.createdAt ? b.createdAt.toISOString() : \"unknown date\";\n const name = dest.kind === \"local\" ? path.basename(b.key) : b.key;\n // An empty file is called out rather than listed as a peer of\n // the real ones. Older failures could leave a 0-byte dump here\n // (fixed at the source now), and retention protects the newest\n // by date whatever they contain — so a corpse left in place can\n // hold a `keepMinimum` slot against a backup that matters.\n const empty = b.sizeBytes === 0;\n const size = b.sizeBytes === undefined ? \"\" : ` — ${formatBytes(b.sizeBytes)}`;\n if (empty) {\n print(` ${chalk.red(\"○\")} ${chalk.bold(name)} ${chalk.gray(`— ${when}`)}${chalk.red(\" — EMPTY, not restorable\")}`);\n } else {\n print(` ${chalk.green(\"●\")} ${chalk.bold(name)} ${chalk.gray(`— ${when}${size}`)}`);\n }\n }\n if (backups.some(b => b.sizeBytes === 0)) {\n print(\"\");\n print(chalk.yellow(\" ⚠ Empty files above are leftovers from a failed backup. Delete them:\"));\n print(chalk.gray(\" they count as recent backups for retention but restore nothing.\"));\n }\n }\n print(\"\");\n } catch (err) {\n reportError(err);\n process.exit(1);\n }\n}\n\n/**\n * Verify a freshly written dump; abort the command if it looks corrupt.\n *\n * Discards the artifact on the way out. Refusing to *report* success was never\n * enough on its own: the file stayed on disk, `rebase db backups list` showed\n * it as an ordinary entry, and retention — which ranks by timestamp and never\n * looks at size — would protect it as one of the `keepMinimum` newest while\n * pruning a real backup underneath it. The roles sidecar goes too; the two are\n * uploaded and pruned as a pair, so half a pair is not a backup either.\n */\nasync function assertDumpValid(localFile: string): Promise<void> {\n const check = await validateDump(localFile);\n if (!check.ok) {\n discardPartialDump(globalsFileForDump(localFile));\n discardPartialDump(localFile);\n throw new BackupToolError(\n `The backup failed validation and was discarded: ${check.reason}`,\n \"The dump was corrupt or truncated, so nothing was kept. Investigate before relying on this destination.\"\n );\n }\n}\n\nfunction reportError(err: unknown): void {\n if (err instanceof BackupToolError) {\n outError(chalk.red(` ✗ ${err.message}`));\n if (err.hint) outError(chalk.gray(` ${err.hint}`));\n } else {\n outError(chalk.red(` ✗ ${err instanceof Error ? err.message : String(err)}`));\n }\n}\n\nfunction printBackupHelp(): void {\n print(`\n${chalk.bold(\"rebase db backup\")} — Create a database backup (pg_dump, custom format)\n\n${chalk.green.bold(\"Usage\")}\n rebase db backup [--out <path|s3://bucket/prefix>] [options]\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--out, -o\")} <dest> Local path or s3://…/gs://… URL (default: ./backups)\n ${chalk.blue(\"--exclude-schema\")} <s> Exclude a schema (repeatable)\n ${chalk.blue(\"--no-owner\")} Omit ownership commands from the dump\n ${chalk.blue(\"--enable-row-security\")} Dump as an admin subject instead of failing on RLS\n ${chalk.red(\"(may produce a partial dump — see below)\")}\n ${chalk.blue(\"--row-security-role\")} <r> Role to read as with the flag above (default: admin)\n\n${chalk.green.bold(\"Row-level security\")}\n On a managed Postgres the dumping role usually owns nothing and has no\n BYPASSRLS, so pg_dump refuses:\n\n ERROR: query would be affected by row-level security policy for table \"...\"\n\n That refusal is the safe behaviour. --enable-row-security replaces it by\n reading as an admin subject: Rebase sets app.uid/app.user_roles so the\n generated admin_full_access policy admits the dump. The dump then contains\n exactly what those policies admit ${chalk.red(\"and no error is raised for what they do not\")} —\n a table whose policies lack an admin rule comes out short, silently.\n\n Granting the dumping role BYPASSRLS is the option that keeps a backup\n meaning \"every row\".\n\n${chalk.green.bold(\"Notes\")}\n Backups may contain secrets and PII. Use private storage destinations and\n enable encryption-at-rest. See docs/backups.md.\n`);\n}\n\nfunction printRestoreHelp(): void {\n print(`\n${chalk.bold(\"rebase db restore\")} — Restore a database from a backup (pg_restore)\n\n${chalk.green.bold(\"Usage\")}\n rebase db restore <backup> [options]\n\n${chalk.green.bold(\"Arguments\")}\n <backup> Local .dump file, or s3://…/gs://… object key\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--target-db\")} <name> Restore into this database instead of DATABASE_URL's\n ${chalk.blue(\"--create-db\")} Create the target database first if it doesn't exist\n ${chalk.blue(\"--clean\")} Drop existing objects before recreating them\n ${chalk.blue(\"--no-owner\")} Ignore ownership from the dump\n ${chalk.blue(\"--continue-on-error\")} Log and continue past errors ${chalk.red(\"(may leave RLS un-enforced!)\")}\n ${chalk.blue(\"--yes, -y\")} Skip the interactive confirmation ${chalk.red(\"(destructive!)\")}\n\n${chalk.red.bold(\"Warning\")}\n Restore is destructive and never runs automatically. Without --yes it\n requires an interactive 'yes'. Prefer --create-db/--target-db to restore\n into a fresh database rather than overwriting a live one.\n\n By default the restore aborts on the first error (--exit-on-error) so a\n skipped GRANT never silently leaves RLS un-enforced. Roles are recreated\n from the backup's .globals.sql sidecar first; keep that file next to the\n dump. Use --continue-on-error only when you understand the consequences.\n`);\n}\n\nfunction printBackupsHelp(): void {\n print(`\n${chalk.bold(\"rebase db backups\")} — Manage stored backups\n\n${chalk.green.bold(\"Usage\")}\n rebase db backups list [--out <path|s3://bucket/prefix>]\n rebase db backup list [--out <path|s3://bucket/prefix>] ${chalk.gray(\"(the same thing)\")}\n`);\n}\n"],"mappings":";;;;;;;;;;;;;AAoCA,SAAS,YAAY,OAAuB;CACxC,IAAI,QAAQ,MAAM,OAAO,GAAG,MAAM;CAClC,IAAI,QAAQ,OAAO,MAAM,OAAO,IAAI,QAAQ,KAAA,CAAM,QAAQ,CAAC,EAAE;CAC7D,IAAI,QAAQ,OAAO,OAAO,MAAM,OAAO,IAAI,SAAS,OAAO,MAAA,CAAO,QAAQ,CAAC,EAAE;CAC7E,OAAO,IAAI,SAAS,OAAO,OAAO,MAAA,CAAO,QAAQ,CAAC,EAAE;AACxD;;;;;AAMA,eAAe,6BACX,MACA,KACiC;CACjC,IAAI,KAAK,SAAS,SAAS,OAAO;CAClC,I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