@protobase/server 0.129.1 → 0.130.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 (243) hide show
  1. package/dist/assistant/query-runner/grants-sql.js +32 -0
  2. package/dist/assistant/query-runner/query-input.js +33 -0
  3. package/dist/assistant/query-runner/query-module.js +44 -0
  4. package/dist/assistant/query-runner/query-runner.d.ts +8 -11
  5. package/dist/assistant/query-runner/query-runner.js +15 -57
  6. package/dist/assistant/query-runner/read-query.js +54 -0
  7. package/dist/assistant/query-runner/runner-sql.js +4 -20
  8. package/dist/assistant/query-runner/steps/001-role.js +19 -0
  9. package/dist/auth-store.d.ts +2 -2
  10. package/dist/auth-store.js +3 -3
  11. package/dist/better-auth/auth-schema.d.ts +13 -4
  12. package/dist/better-auth/auth-schema.js +40 -32
  13. package/dist/better-auth/auth-settings.d.ts +59 -11
  14. package/dist/better-auth/auth-settings.js +57 -13
  15. package/dist/better-auth/auth-tables.d.ts +6 -3
  16. package/dist/better-auth/auth-tables.js +12 -7
  17. package/dist/better-auth/authenticator.js +10 -2
  18. package/dist/better-auth/create-auth.d.ts +62 -7
  19. package/dist/better-auth/create-auth.js +55 -14
  20. package/dist/better-auth/device-sign-in-check.js +13 -0
  21. package/dist/better-auth/names/declaration.d.ts +18 -5
  22. package/dist/better-auth/names/declaration.js +3 -1
  23. package/dist/better-auth/names/modules/auth.js +9 -0
  24. package/dist/better-auth/names/modules/index.d.ts +34 -4
  25. package/dist/better-auth/names/modules/organizations.js +10 -3
  26. package/dist/better-auth/names/modules/personal-access-tokens.js +6 -3
  27. package/dist/better-auth/names/modules-on.js +25 -2
  28. package/dist/better-auth/names/resolve-names.d.ts +9 -1
  29. package/dist/better-auth/names/resolve-names.js +15 -9
  30. package/dist/better-auth/organizations/accept-invitation.js +5 -4
  31. package/dist/better-auth/organizations/add-every-user.js +3 -2
  32. package/dist/better-auth/organizations/host-scope.d.ts +10 -0
  33. package/dist/better-auth/organizations/host-scope.js +15 -0
  34. package/dist/better-auth/organizations/host.d.ts +12 -6
  35. package/dist/better-auth/organizations/host.js +99 -61
  36. package/dist/better-auth/organizations/kept-organizations.d.ts +21 -0
  37. package/dist/better-auth/organizations/kept-organizations.js +62 -0
  38. package/dist/better-auth/organizations/member-endpoints.js +4 -3
  39. package/dist/better-auth/organizations/options.d.ts +15 -0
  40. package/dist/better-auth/organizations/options.js +19 -1
  41. package/dist/better-auth/organizations/people-endpoint.js +3 -2
  42. package/dist/better-auth/organizations/pinned-membership.js +81 -0
  43. package/dist/better-auth/organizations/pinned-sessions.js +46 -0
  44. package/dist/better-auth/organizations/session-organization.js +3 -2
  45. package/dist/better-auth/organizations/store.js +14 -9
  46. package/dist/better-auth/personal-access-tokens/pinned-tokens.js +23 -0
  47. package/dist/better-auth/personal-access-tokens/token-plugin.js +75 -54
  48. package/dist/better-auth/personal-access-tokens/token-sessions.js +6 -3
  49. package/dist/better-auth/personal-access-tokens/token-store.js +15 -11
  50. package/dist/better-auth/store/adoption.js +25 -10
  51. package/dist/better-auth/store/drift.js +5 -4
  52. package/dist/better-auth/store/legacy-record.d.ts +10 -0
  53. package/dist/better-auth/store/legacy-record.js +56 -0
  54. package/dist/better-auth/store/migration-sql.js +31 -26
  55. package/dist/better-auth/store/offline/baseline-store.d.ts +11 -7
  56. package/dist/better-auth/store/offline/baseline-store.js +15 -12
  57. package/dist/better-auth/store/offline/module-switches.d.ts +27 -0
  58. package/dist/better-auth/store/offline/module-switches.js +94 -0
  59. package/dist/better-auth/store/offline/name-changes.d.ts +4 -1
  60. package/dist/better-auth/store/offline/name-changes.js +5 -2
  61. package/dist/better-auth/store/offline/offline-steps.d.ts +21 -7
  62. package/dist/better-auth/store/offline/offline-steps.js +29 -20
  63. package/dist/better-auth/store/offline/retired-watch.d.ts +5 -0
  64. package/dist/better-auth/store/offline/retired-watch.js +36 -0
  65. package/dist/better-auth/store/offline/settings-names.d.ts +3 -2
  66. package/dist/better-auth/store/offline/settings-names.js +10 -3
  67. package/dist/better-auth/store/offline/store-model.d.ts +9 -1
  68. package/dist/better-auth/store/offline/store-model.js +22 -5
  69. package/dist/better-auth/store/resources-outside.js +1 -1
  70. package/dist/better-auth/store/step-record.d.ts +13 -0
  71. package/dist/better-auth/store/step-record.js +59 -0
  72. package/dist/better-auth/store/steps/index.js +6 -1
  73. package/dist/better-auth/store/steps/legacy-versions.d.ts +7 -0
  74. package/dist/better-auth/store/steps/legacy-versions.js +4 -0
  75. package/dist/better-auth/store/steps/organizations/003-default-organization.js +113 -0
  76. package/dist/better-auth/store/steps/render.d.ts +3 -0
  77. package/dist/better-auth/store/steps/render.js +48 -25
  78. package/dist/better-auth/store/steps/step-lint.d.ts +14 -0
  79. package/dist/better-auth/store/steps/step-lint.js +31 -10
  80. package/dist/better-auth/store/steps/step.d.ts +18 -0
  81. package/dist/better-auth/store/steps/step.js +7 -1
  82. package/dist/better-auth/store/store-db.d.ts +6 -0
  83. package/dist/better-auth/store/store-db.js +11 -5
  84. package/dist/better-auth/store/store-names.d.ts +4 -0
  85. package/dist/better-auth/token-standing.js +12 -7
  86. package/dist/better-auth/users.d.ts +7 -2
  87. package/dist/better-auth/users.js +25 -3
  88. package/dist/built-in-resources.js +1 -1
  89. package/dist/calls/calls-module.js +42 -0
  90. package/dist/calls/calls-sql.js +4 -30
  91. package/dist/changes/capture-names.d.ts +3 -1
  92. package/dist/changes/capture-names.js +5 -2
  93. package/dist/changes/capture-schema-sql.d.ts +10 -0
  94. package/dist/changes/capture-schema-sql.js +21 -0
  95. package/dist/changes/capture-schema.d.ts +0 -18
  96. package/dist/changes/capture-schema.js +1 -74
  97. package/dist/changes/capture-sql.js +30 -24
  98. package/dist/changes/changes-input.js +36 -0
  99. package/dist/changes/changes-module.js +44 -0
  100. package/dist/changes/read-capture.js +67 -0
  101. package/dist/changes/steps/001-outbox.js +23 -0
  102. package/dist/channels/sends-module.js +37 -0
  103. package/dist/channels/sends-schema-sql.js +5 -5
  104. package/dist/comments/comments-module.js +30 -0
  105. package/dist/comments/comments-sql.js +1 -22
  106. package/dist/computed/buckets-sql.d.ts +5 -1
  107. package/dist/computed/buckets-sql.js +39 -46
  108. package/dist/computed/{buckets-schema.d.ts → buckets-targets.d.ts} +2 -3
  109. package/dist/computed/buckets-targets.js +50 -0
  110. package/dist/computed/computed-input.js +65 -0
  111. package/dist/computed/computed-module.js +102 -0
  112. package/dist/computed/formula-sql.js +14 -1
  113. package/dist/computed/read-computed.js +100 -0
  114. package/dist/computed/rollup-sql.js +13 -10
  115. package/dist/config-exports.d.ts +2 -2
  116. package/dist/create-admin.js +21 -5
  117. package/dist/derived/derived-module.js +89 -0
  118. package/dist/derived/derived-sql.js +1 -47
  119. package/dist/functions/define-function.d.ts +10 -4
  120. package/dist/functions/routes.js +5 -3
  121. package/dist/functions/supabase-routes.js +7 -5
  122. package/dist/history/history-module.js +34 -0
  123. package/dist/index.d.ts +19 -28
  124. package/dist/index.js +11 -21
  125. package/dist/internal.d.ts +26 -10
  126. package/dist/internal.js +22 -8
  127. package/dist/jobs/functions-sql.js +7 -11
  128. package/dist/jobs/job-data.js +36 -0
  129. package/dist/jobs/job-types.d.ts +6 -3
  130. package/dist/jobs/jobs-module.d.ts +5 -0
  131. package/dist/jobs/jobs-module.js +84 -0
  132. package/dist/jobs/run-job.d.ts +1 -1
  133. package/dist/jobs/run-job.js +7 -5
  134. package/dist/jobs/runtime.d.ts +9 -4
  135. package/dist/jobs/runtime.js +11 -6
  136. package/dist/jobs/schema.d.ts +0 -11
  137. package/dist/jobs/schema.js +1 -59
  138. package/dist/jobs/steps/001-pg-boss-45.js +483 -0
  139. package/dist/live/notices-module.js +30 -0
  140. package/dist/live/notices-sql.js +2 -1
  141. package/dist/mail/feedback/feedback-schema.js +3 -30
  142. package/dist/mail/feedback/mail-feedback-module.js +37 -0
  143. package/dist/mail/unsubscribe/unsubscribe-schema.js +3 -21
  144. package/dist/mail/unsubscribe/unsubscribes-module.js +31 -0
  145. package/dist/migration-record/check-record.d.ts +9 -7
  146. package/dist/migration-record/check-record.js +12 -11
  147. package/dist/migration-record/module-needs.js +30 -0
  148. package/dist/migration-record/read-record.js +27 -15
  149. package/dist/migration-record/record-model.d.ts +7 -2
  150. package/dist/migration-record/record-model.js +14 -6
  151. package/dist/migration-record/startup-decision.js +18 -7
  152. package/dist/migration-sql/additive-statements.d.ts +4 -0
  153. package/dist/migration-sql/additive-statements.js +105 -0
  154. package/dist/notifications/devices-module.js +61 -0
  155. package/dist/notifications/history-module.js +50 -0
  156. package/dist/notifications/notifications-targets.js +23 -0
  157. package/dist/notifications/read-table.js +16 -0
  158. package/dist/notifications/schema-sql.js +1 -22
  159. package/dist/notifications/schema.js +1 -101
  160. package/dist/notifications/table-names.js +40 -0
  161. package/dist/organization-scope/app-scope.js +38 -0
  162. package/dist/organization-scope/auth-request-organization.js +71 -0
  163. package/dist/organization-scope/organization-tables.js +20 -0
  164. package/dist/organization-scope/sign-in-organization.js +21 -0
  165. package/dist/package.js +1 -1
  166. package/dist/personal-mail/shared-sender-store.js +4 -2
  167. package/dist/realtime/relay/realtime-relay-module.js +37 -0
  168. package/dist/relation-found.js +6 -0
  169. package/dist/relay/read-relay.js +85 -0
  170. package/dist/relay/realtime-members-sql.js +51 -28
  171. package/dist/relay/relay-module.js +53 -0
  172. package/dist/relay/relay-targets.js +28 -0
  173. package/dist/relay/session-end.js +1 -3
  174. package/dist/relay/sessions-sql.js +4 -27
  175. package/dist/rest/table-routes.js +9 -2
  176. package/dist/schema-modules/feature-schemas-sql.d.ts +40 -0
  177. package/dist/schema-modules/feature-schemas-sql.js +51 -0
  178. package/dist/schema-modules/module-difference.d.ts +31 -0
  179. package/dist/schema-modules/module-difference.js +98 -0
  180. package/dist/schema-modules/modules-sql.js +13 -0
  181. package/dist/schema-modules/modules.d.ts +37 -0
  182. package/dist/schema-modules/modules.js +56 -0
  183. package/dist/schema-modules/needed-modules.d.ts +41 -0
  184. package/dist/schema-modules/needed-modules.js +61 -0
  185. package/dist/schema-modules/resource-difference.js +83 -0
  186. package/dist/schema-modules/schema-module.d.ts +112 -0
  187. package/dist/schema-modules/schema-module.js +8 -0
  188. package/dist/status/status-module.js +63 -0
  189. package/dist/status/status-targets.js +21 -0
  190. package/dist/types.d.ts +6 -1
  191. package/dist/user-tables/reloading-admin.d.ts +1 -0
  192. package/dist/user-tables/reloading-admin.js +1 -0
  193. package/dist/user-tables/schema-sql.js +1 -14
  194. package/dist/user-tables/schema.js +4 -27
  195. package/dist/user-tables/user-tables-module.js +38 -0
  196. package/dist/webhooks/table/delivery-log-module.js +36 -0
  197. package/dist/webhooks/table/owner-roles.js +3 -2
  198. package/dist/webhooks/table/schema-sql.js +27 -26
  199. package/dist/webhooks/table/webhooks-schema-module.js +63 -0
  200. package/dist/webhooks/table/webhooks-targets.js +26 -0
  201. package/dist/webhooks/webhooks.js +1 -1
  202. package/dist/workflows/custom-steps/custom-steps-module.js +51 -0
  203. package/dist/workflows/custom-steps/custom-steps-sql.js +10 -7
  204. package/dist/workflows/custom-steps/runners-sql.js +10 -7
  205. package/dist/workflows/read-catalogue.js +23 -0
  206. package/dist/workflows/schema-sql.js +12 -9
  207. package/dist/workflows/status-sql.js +12 -6
  208. package/dist/workflows/storage/storage-module.js +39 -0
  209. package/dist/workflows/storage/storage-sql.js +8 -5
  210. package/dist/workflows/workflows-schema-module.js +49 -0
  211. package/dist/workflows/workflows-tables-sql.js +32 -0
  212. package/dist/workflows/workflows-targets.js +16 -0
  213. package/package.json +6 -6
  214. package/dist/assistant/query-runner/runner-plan.js +0 -30
  215. package/dist/better-auth/store/migrations-table.js +0 -27
  216. package/dist/better-auth/store/modules-off.js +0 -17
  217. package/dist/calls/calls-sql.d.ts +0 -11
  218. package/dist/changes/capture-plan.js +0 -79
  219. package/dist/channels/sends-schema.d.ts +0 -7
  220. package/dist/channels/sends-schema.js +0 -18
  221. package/dist/comments/comments-sql.d.ts +0 -14
  222. package/dist/computed/buckets-plan.d.ts +0 -2
  223. package/dist/computed/buckets-plan.js +0 -88
  224. package/dist/computed/buckets-schema.js +0 -39
  225. package/dist/computed/computed-plan.js +0 -81
  226. package/dist/computed/computed-schema.d.ts +0 -16
  227. package/dist/computed/computed-schema.js +0 -63
  228. package/dist/derived/derived-sql.d.ts +0 -12
  229. package/dist/mail/feedback/feedback-schema.d.ts +0 -7
  230. package/dist/mail/unsubscribe/unsubscribe-schema.d.ts +0 -10
  231. package/dist/notifications/schema.d.ts +0 -14
  232. package/dist/realtime/relay/relay-schema.d.ts +0 -7
  233. package/dist/realtime/relay/relay-schema.js +0 -20
  234. package/dist/relay/realtime-members-schema.js +0 -67
  235. package/dist/relay/relay-schema.d.ts +0 -14
  236. package/dist/relay/relay-schema.js +0 -28
  237. package/dist/status/schema.d.ts +0 -12
  238. package/dist/status/schema.js +0 -33
  239. package/dist/user-tables/schema.d.ts +0 -11
  240. package/dist/webhooks/table/schema.d.ts +0 -16
  241. package/dist/webhooks/table/schema.js +0 -56
  242. package/dist/workflows/schema.d.ts +0 -13
  243. package/dist/workflows/schema.js +0 -88
@@ -1,10 +1,7 @@
1
- import { hasIndexes } from "../../has-indexes.js";
2
- import { migrationCommand } from "../../changes/capture-schema.js";
3
1
  import { unsubscribesSchema, unsubscribesTable } from "./unsubscribe-store.js";
4
- import { sql } from "kysely";
5
2
  //#region src/mail/unsubscribe/unsubscribe-schema.ts
6
3
  /** The table's indexes by name: the unique one the send's check and the admin list's recipient filter read, and the list's topic filter and sort. */
7
- const indexes = [
4
+ const unsubscribesIndexes = [
8
5
  [
9
6
  "unsubscribes_recipient_topic",
10
7
  "unique",
@@ -31,21 +28,6 @@ create table if not exists ${unsubscribesTable} (
31
28
  "created_at" timestamptz not null
32
29
  );
33
30
 
34
- ${indexes.map(([name, kind, columns]) => `create ${kind ? `${kind} ` : ""}index if not exists "${name}" on ${unsubscribesTable} (${columns});`).join("\n")}`;
35
- const hasTable = async (db) => (await sql`select to_regclass(${unsubscribesTable}) is not null as found`.execute(db)).rows[0].found;
36
- /** The SQL that adds the opt-outs' schema and table, or the indexes it lacks; `undefined` when it has them all. */
37
- const unsubscribesMigration = async (db) => {
38
- if (await hasTable(db) && await hasIndexes(db, "mail", "unsubscribes", indexes.map(([name]) => name))) return;
39
- return unsubscribesTableSql();
40
- };
41
- /**
42
- * Refuses to start while `unsubscribe` is on and its table, or the unique index recording an opt-out stands on, is
43
- * missing; the project's migrations add them.
44
- */
45
- const checkUnsubscribesSchema = async (db) => {
46
- const [unique] = indexes[0];
47
- if (await hasTable(db) && await hasIndexes(db, "mail", "unsubscribes", [unique])) return;
48
- throw new Error(`The opt-outs table ${unsubscribesTable} of unsubscribe, or its unique index ${unique}, is missing. Write it as a migration with \`${migrationCommand}\`, apply it with the project's migrations, then start again.`);
49
- };
31
+ ${unsubscribesIndexes.map(([name, kind, columns]) => `create ${kind ? `${kind} ` : ""}index if not exists "${name}" on ${unsubscribesTable} (${columns});`).join("\n")}`;
50
32
  //#endregion
51
- export { checkUnsubscribesSchema, unsubscribesMigration, unsubscribesTableSql };
33
+ export { unsubscribesIndexes, unsubscribesTableSql };
@@ -0,0 +1,31 @@
1
+ import { unsubscribesTable } from "./unsubscribe-store.js";
2
+ import { hasIndexes } from "../../has-indexes.js";
3
+ import { relationFound } from "../../relation-found.js";
4
+ import { unsubscribesIndexes, unsubscribesTableSql } from "./unsubscribe-schema.js";
5
+ //#region src/mail/unsubscribe/unsubscribes-module.ts
6
+ /** The opt-outs table as the database has it: step 1 once it is there with every index. Refuses one without them, which no step records. */
7
+ const readUnsubscribes = async (db) => {
8
+ if (!await relationFound(db, unsubscribesTable)) return;
9
+ if (!await hasIndexes(db, "mail", "unsubscribes", unsubscribesIndexes.map(([name]) => name))) throw new Error(`The opt-outs table ${unsubscribesTable} lacks indexes no step of this version of Protobase records: add them with \`protobase migration\` and \`protobase migrate\` of Protobase 0.14.2 first, then run this command again`);
10
+ return {
11
+ lastStep: 1,
12
+ replaceables: {}
13
+ };
14
+ };
15
+ /** The table of who unsubscribed from which topic of the bulk mail, with `unsubscribe`. Never dropped. */
16
+ const unsubscribesModule = {
17
+ label: "the opt-outs table",
18
+ title: "The table of who unsubscribed from which topic of the bulk mail",
19
+ steps: [{
20
+ step: 1,
21
+ name: "unsubscribes",
22
+ title: "The opt-outs table and its indexes",
23
+ additive: true,
24
+ sql: () => unsubscribesTableSql()
25
+ }],
26
+ replaceables: [],
27
+ resourceReplaceables: [],
28
+ read: readUnsubscribes
29
+ };
30
+ //#endregion
31
+ export { unsubscribesModule };
@@ -1,11 +1,13 @@
1
- import { AdminAuth } from "../better-auth/create-auth.js";
1
+ import { RecordModel } from "./record-model.js";
2
+ import { Kysely } from "kysely";
2
3
  //#region src/migration-record/check-record.d.ts
3
4
  /**
4
- * Refuses to go on, before the server serves, while the database's record of migrations does not match what this
5
- * version reads (`startupRefusal`). It reads the record once and nothing else; the server never migrates itself.
6
- * Without sign-in it reads nothing, as the runtime reads nothing of the record then.
5
+ * Refuses to go on, before the server serves, while the database's record of migrations does not match `runtime`, the
6
+ * model this version reads (`runtimeModel`), as `startupRefusal` decides. It reads the record once and nothing else;
7
+ * the server never migrates itself, and reads it without the app's query plugins. A runtime that reads nothing of the
8
+ * record reads nothing.
7
9
  */
8
- export declare const checkMigrationRecord: (auth: AdminAuth | undefined, running: string) => Promise<void>;
9
- /** Whether the database's record has a migration of the model this version reads with `auth`. */
10
- export declare const recordsRuntimeModel: (auth: AdminAuth) => Promise<boolean>;
10
+ export declare const checkMigrationRecord: (db: Kysely<any>, runtime: RecordModel, running: string) => Promise<void>;
11
+ /** Whether the database's record has a row that holds `runtime`. */
12
+ export declare const recordsRuntimeModel: (db: Kysely<any>, runtime: RecordModel) => Promise<boolean>;
11
13
  //#endregion
@@ -1,20 +1,21 @@
1
- import { plainStoreDb } from "../better-auth/store/store-db.js";
2
- import { modelHash, runtimeModel } from "./record-model.js";
1
+ import { withoutAppPlugins } from "../better-auth/store/store-db.js";
3
2
  import { readRecordState, recordHasModel } from "./read-record.js";
3
+ import { readsNothing } from "./record-model.js";
4
4
  import { startupRefusal } from "./startup-decision.js";
5
5
  //#region src/migration-record/check-record.ts
6
+ const plainDb = (db) => withoutAppPlugins(db, "the record of migrations belongs to no organization");
6
7
  /**
7
- * Refuses to go on, before the server serves, while the database's record of migrations does not match what this
8
- * version reads (`startupRefusal`). It reads the record once and nothing else; the server never migrates itself.
9
- * Without sign-in it reads nothing, as the runtime reads nothing of the record then.
8
+ * Refuses to go on, before the server serves, while the database's record of migrations does not match `runtime`, the
9
+ * model this version reads (`runtimeModel`), as `startupRefusal` decides. It reads the record once and nothing else;
10
+ * the server never migrates itself, and reads it without the app's query plugins. A runtime that reads nothing of the
11
+ * record reads nothing.
10
12
  */
11
- const checkMigrationRecord = async (auth, running) => {
12
- if (!auth) return;
13
- const runtime = runtimeModel(auth);
14
- const refusal = startupRefusal(runtime, await readRecordState(plainStoreDb(auth), modelHash(runtime)), running);
13
+ const checkMigrationRecord = async (db, runtime, running) => {
14
+ if (readsNothing(runtime)) return;
15
+ const refusal = startupRefusal(runtime, await readRecordState(plainDb(db), runtime), running);
15
16
  if (refusal) throw new Error(refusal);
16
17
  };
17
- /** Whether the database's record has a migration of the model this version reads with `auth`. */
18
- const recordsRuntimeModel = (auth) => recordHasModel(plainStoreDb(auth), modelHash(runtimeModel(auth)));
18
+ /** Whether the database's record has a row that holds `runtime`. */
19
+ const recordsRuntimeModel = (db, runtime) => recordHasModel(plainDb(db), runtime);
19
20
  //#endregion
20
21
  export { checkMigrationRecord, recordsRuntimeModel };
@@ -0,0 +1,30 @@
1
+ import { moduleNameChanges } from "../schema-modules/module-difference.js";
2
+ import { schemaModules } from "../schema-modules/modules.js";
3
+ //#region src/migration-record/module-needs.ts
4
+ const stepLabel = (id, step) => `step ${step} (${schemaModules[id].steps[step - 1]?.name ?? "unknown"})`;
5
+ const resourceNeeds = (label, had, needed) => Object.entries(needed.resources ?? {}).flatMap(([name, entries]) => Object.entries(entries).flatMap(([key, entry]) => {
6
+ const found = had.resources?.[name]?.[key];
7
+ if (!found) return [`${label} lacks its ${name} of ${key}`];
8
+ return found.version === entry.version && found.digest === entry.digest ? [] : [`${label} has its ${name} of ${key} otherwise than this version writes them for the config`];
9
+ }));
10
+ /** What the runtime needs of the schema modules that the database's model lacks, has older or names otherwise, one line each. */
11
+ const moduleNeeds = (database, runtime) => Object.entries(runtime).flatMap(([id, needed]) => {
12
+ const { label } = schemaModules[id];
13
+ const had = database?.[id];
14
+ if (!had) return [`the database lacks ${label}, which this version needs at ${stepLabel(id, needed.lastStep)}`];
15
+ const steps = had.lastStep < needed.lastStep ? [`${label} is at ${stepLabel(id, had.lastStep)}, and this version needs ${stepLabel(id, needed.lastStep)}`] : [];
16
+ const replaced = Object.entries(needed.replaceables).flatMap(([name, version]) => {
17
+ const found = had.replaceables[name];
18
+ if (found === void 0) return [`${label} lacks its ${name}, which this version needs at version ${version}`];
19
+ return found < version ? [`${label} has its ${name} at version ${found}, and this version needs version ${version}`] : [];
20
+ });
21
+ const renamed = moduleNameChanges(schemaModules[id], had.names, needed.names ?? {}, "the database");
22
+ return [
23
+ ...steps,
24
+ ...replaced,
25
+ ...renamed,
26
+ ...resourceNeeds(label, had, needed)
27
+ ];
28
+ });
29
+ //#endregion
30
+ export { moduleNeeds };
@@ -1,14 +1,28 @@
1
1
  import { recordTable } from "./record-table.js";
2
2
  import { sql } from "kysely";
3
3
  //#region src/migration-record/read-record.ts
4
+ const holdsModule = (id, module) => {
5
+ const { resources = {}, ...rest } = module;
6
+ const found = sql`(model -> 'modules' -> ${id}::text)`;
7
+ return sql`(${found} - 'resources' = ${JSON.stringify(rest)}::jsonb and coalesce(${found} -> 'resources', '{}'::jsonb) @> ${JSON.stringify(resources)}::jsonb)`;
8
+ };
9
+ /**
10
+ * Whether a row of the record holds every part of `runtime` as it is: the auth store and each schema module it reads
11
+ * (`holdsModule`). A part the runtime does not read, such as a module another version needs, does not count.
12
+ */
13
+ const holdsRuntime = (runtime) => sql.join([
14
+ sql`true`,
15
+ ...runtime.auth ? [sql`model -> 'auth' = ${JSON.stringify(runtime.auth)}::jsonb`] : [],
16
+ ...Object.entries(runtime.modules ?? {}).map(([id, module]) => holdsModule(id, module))
17
+ ], sql` and `);
18
+ const recordFound = async (db) => (await sql`select to_regclass(${recordTable}) is not null as found`.execute(db)).rows[0].found;
4
19
  /**
5
- * The record as the startup decides on it, for the runtime's model hash `hash`: whether the table is there, then one
6
- * query for the newest row, whether a row records `hash`, the rows not marked additive since the newest such row, and
7
- * the unfinished rows.
20
+ * The record as the startup decides on it, for the model the runtime reads: whether the table is there, then one
21
+ * query for the newest row, whether a row holds that model (`holdsRuntime`), the rows not marked additive since the
22
+ * newest such row, and the unfinished rows.
8
23
  */
9
- const readRecordState = async (db, hash) => {
10
- const [found] = (await sql`select to_regclass(${recordTable}) is not null as found`.execute(db)).rows;
11
- if (!found?.found) return {
24
+ const readRecordState = async (db, runtime) => {
25
+ if (!await recordFound(db)) return {
12
26
  newest: void 0,
13
27
  matched: false,
14
28
  notAdditiveSince: [],
@@ -16,9 +30,9 @@ const readRecordState = async (db, hash) => {
16
30
  };
17
31
  const table = sql.raw(recordTable);
18
32
  const [row] = (await sql`
19
- with matched as (select max(applied_at) as at from ${table} where model_hash = ${hash})
33
+ with matched as (select max(applied_at) as at from ${table} where ${holdsRuntime(runtime)})
20
34
  select
21
- (select json_build_object('name', name, 'protobase_version', protobase_version, 'model', model, 'model_hash', model_hash) from ${table} order by applied_at desc limit 1) as newest,
35
+ (select json_build_object('name', name, 'protobase_version', protobase_version, 'model', model) from ${table} order by applied_at desc limit 1) as newest,
22
36
  (select at is not null from matched) as matched,
23
37
  (select coalesce(json_agg(h.name order by h.applied_at), '[]') from ${table} h, matched where h.applied_at > matched.at and h.additive is not true) as not_additive,
24
38
  (select coalesce(json_agg(json_build_object('name', h.name, 'after', h.physical -> 'after') order by h.applied_at), '[]') from ${table} h where h.completed_at is null) as unfinished`.execute(db)).rows;
@@ -27,19 +41,17 @@ const readRecordState = async (db, hash) => {
27
41
  newest: newest ? {
28
42
  name: newest.name,
29
43
  version: newest.protobase_version,
30
- model: newest.model,
31
- hash: newest.model_hash
44
+ model: newest.model
32
45
  } : void 0,
33
46
  matched: row.matched,
34
47
  notAdditiveSince: row.not_additive,
35
48
  unfinished: row.unfinished
36
49
  };
37
50
  };
38
- /** Whether the record has a row of the model hash `hash`: `false` without a record. */
39
- const recordHasModel = async (db, hash) => {
40
- const [found] = (await sql`select to_regclass(${recordTable}) is not null as found`.execute(db)).rows;
41
- if (!found?.found) return false;
42
- const [row] = (await sql`select exists (select from ${sql.raw(recordTable)} where model_hash = ${hash}) as has`.execute(db)).rows;
51
+ /** Whether a row of the record holds `runtime` (`holdsRuntime`): `false` without a record. */
52
+ const recordHasModel = async (db, runtime) => {
53
+ if (!await recordFound(db)) return false;
54
+ const [row] = (await sql`select exists (select from ${sql.raw(recordTable)} where ${holdsRuntime(runtime)}) as has`.execute(db)).rows;
43
55
  return row.has;
44
56
  };
45
57
  //#endregion
@@ -1,11 +1,16 @@
1
1
  import { StoreNamesSource } from "../better-auth/store/store-names.js";
2
2
  import { StoreModel } from "../better-auth/store/offline/store-model.js";
3
+ import { ModuleTargets, ModulesModel } from "../schema-modules/modules.js";
3
4
  //#region src/migration-record/record-model.d.ts
4
5
  export type RecordModel = {
5
6
  auth?: StoreModel;
7
+ modules?: ModulesModel;
6
8
  };
7
9
  /** The SHA-256 of the model as JSON, the same for the snapshot, the record and the runtime. */
8
10
  export declare const modelHash: (model: RecordModel) => string;
9
- /** The model this version of Protobase reads with the app's auth: its store at every step this version ships. */
10
- export declare const runtimeModel: (auth: StoreNamesSource | undefined) => RecordModel;
11
+ /**
12
+ * The model this version of Protobase reads with the app's auth and the schema modules it needs: the store and each
13
+ * module at every step and replaceable this version ships, with the names and resources the app gives it.
14
+ */
15
+ export declare const runtimeModel: (auth: StoreNamesSource | undefined, modules: ModuleTargets) => RecordModel;
11
16
  //#endregion
@@ -1,14 +1,22 @@
1
1
  import { storeNames } from "../better-auth/store/store-names.js";
2
2
  import { latestSteps, storeModel } from "../better-auth/store/offline/store-model.js";
3
+ import { latestModules, targetIds } from "../schema-modules/modules.js";
3
4
  import { createHash } from "node:crypto";
4
5
  //#region src/migration-record/record-model.ts
5
6
  /** The SHA-256 of the model as JSON, the same for the snapshot, the record and the runtime. */
6
7
  const modelHash = (model) => createHash("sha256").update(JSON.stringify(model)).digest("hex");
7
- /** The model this version of Protobase reads with the app's auth: its store at every step this version ships. */
8
- const runtimeModel = (auth) => {
9
- if (!auth) return {};
10
- const names = storeNames(auth);
11
- return { auth: storeModel(names, latestSteps(names.names.modules)) };
8
+ /**
9
+ * The model this version of Protobase reads with the app's auth and the schema modules it needs: the store and each
10
+ * module at every step and replaceable this version ships, with the names and resources the app gives it.
11
+ */
12
+ const runtimeModel = (auth, modules) => {
13
+ const names = auth && storeNames(auth);
14
+ return {
15
+ ...names && { auth: storeModel(names, latestSteps(names.names.modules)) },
16
+ ...targetIds(modules).length > 0 && { modules: latestModules(modules) }
17
+ };
12
18
  };
19
+ /** Whether the runtime reads nothing of the record: sign-in off and no schema module needed. */
20
+ const readsNothing = (model) => !model.auth && !model.modules;
13
21
  //#endregion
14
- export { modelHash, runtimeModel };
22
+ export { modelHash, readsNothing, runtimeModel };
@@ -1,11 +1,14 @@
1
1
  import { moduleSteps } from "../better-auth/store/steps/index.js";
2
- import { modelHash } from "./record-model.js";
3
2
  import { recordTable } from "./record-table.js";
3
+ import { schemaModules } from "../schema-modules/modules.js";
4
+ import { readsNothing } from "./record-model.js";
4
5
  import { nameChanges } from "../better-auth/store/offline/name-changes.js";
6
+ import { moduleNeeds } from "./module-needs.js";
5
7
  //#region src/migration-record/startup-decision.ts
6
8
  const stepLabel = (module, step) => `step ${step} (${moduleSteps[module][step - 1]?.name ?? "unknown"})`;
7
9
  /** What the runtime needs of the auth store that the database's lacks or has older, one line each. */
8
10
  const authNeeds = (database, runtime) => {
11
+ if (!runtime) return [];
9
12
  if (!database) return ["the auth store is not recorded"];
10
13
  return [...Object.entries(runtime.modules).flatMap(([module, entry]) => {
11
14
  const had = database.modules[module]?.lastStep;
@@ -20,21 +23,29 @@ const unfinishedRefusals = (unfinished) => unfinished.flatMap(({ name, after })
20
23
  return after.filter(({ unique }) => unique).map(({ index }) => `${name} has not finished building the unique index ${index}`);
21
24
  });
22
25
  const waysOut = (matches, running) => `To bring the database up to ${running}, run \`protobase migrate --plan\` to see the migrations it will apply, then \`protobase migrate\`. Or run Protobase ${matches}, the version the database matches.`;
26
+ const neededParts = (runtime) => {
27
+ const modules = Object.keys(runtime.modules ?? {});
28
+ const parts = [...runtime.auth ? ["the auth store"] : [], ...modules.map((id) => schemaModules[id].label)];
29
+ const already = [...runtime.auth ? ["with `protobase auth migration` for a store whose tables are there already"] : [], ...modules.length > 0 ? ["with `protobase migration baseline` for a schema a migration of an earlier version made"] : []];
30
+ return `this version of Protobase needs ${parts.join(" and ")}. Write the migration that makes and records ${parts.length > 1 ? "them" : "it"} with \`protobase migration\`, or ${already.join(", or ")}`;
31
+ };
23
32
  /**
24
33
  * Why the server must not start on the database `state` describes, running `running` with the model `runtime`;
25
- * `undefined` when it starts. A runtime that reads nothing of the record, sign-in off, always starts.
34
+ * `undefined` when it starts. Each part the runtime reads is compared on its own, and a part of the record it does
35
+ * not read, such as a module another version needs, does not count. A runtime that reads nothing of the record, sign-in
36
+ * off and no schema module needed, always starts.
26
37
  */
27
38
  const startupRefusal = (runtime, state, running) => {
28
- if (!runtime.auth) return;
39
+ if (readsNothing(runtime)) return;
29
40
  const unfinished = unfinishedRefusals(state.unfinished);
30
41
  if (unfinished.length > 0) return `The database's migrations have not finished, so the server will not start: ${unfinished.join("; ")}. Run \`protobase migrate\` to finish them.`;
31
42
  const { newest } = state;
32
- if (!newest) return `The database has no migration recorded in ${recordTable}, so the server will not start: this version of Protobase needs the auth store. Write the migration that makes and records it with \`protobase migration\`, or with \`protobase auth migration\` for a store whose tables are there already, run \`protobase migrate --plan\` to see it, then \`protobase migrate\`.`;
33
- if (newest.hash === modelHash(runtime)) return;
43
+ if (!newest) return `The database has no migration recorded in ${recordTable}, so the server will not start: ${neededParts(runtime)}, run \`protobase migrate --plan\` to see it, then \`protobase migrate\`.`;
34
44
  if (state.matched && state.notAdditiveSince.length === 0) return;
35
- const needs = authNeeds(newest.model.auth, runtime.auth);
45
+ const needs = [...authNeeds(newest.model.auth, runtime.auth), ...moduleNeeds(newest.model.modules, runtime.modules ?? {})];
36
46
  if (needs.length > 0) return `The database is behind Protobase ${running}, so the server will not start: ${needs.join("; ")}. ${waysOut(newest.version, running)}`;
37
- return `The database is ahead of Protobase ${running}, so the server will not start: ${state.matched ? `it has migrations that are not additive since the one this version reads: ${state.notAdditiveSince.join(", ")}` : `its newest migration, ${newest.name}, records a model no migration of this version's records`}. ${waysOut(newest.version, running)}`;
47
+ if (state.matched) return `The database is ahead of Protobase ${running}, so the server will not start: it has migrations that break older code since the one this version reads: ${state.notAdditiveSince.join(", ")}. Rolling back to this version is blocked once they are applied: run Protobase ${newest.version}, the version the database matches, or a later one.`;
48
+ return `The database is ahead of Protobase ${running}, so the server will not start: its newest migration, ${newest.name}, records a model no migration of this version's records. ${waysOut(newest.version, running)}`;
38
49
  };
39
50
  //#endregion
40
51
  export { startupRefusal };
@@ -0,0 +1,4 @@
1
+ //#region src/migration-sql/additive-statements.d.ts
2
+ /** What in `sql` takes something from older code, read with libpg-query, Postgres's parser; a parse error is one line. */
3
+ export declare const contractingSql: (sql: string) => Promise<string[]>;
4
+ //#endregion
@@ -0,0 +1,105 @@
1
+ //#region src/migration-sql/additive-statements.ts
2
+ const relationKey = ({ schemaname, relname }) => `${schemaname ?? ""}.${relname}`;
3
+ const names = (items) => (items ?? []).map((item) => item.String?.sval).join(".");
4
+ /** Statements that only add whatever they act on. */
5
+ const plainKinds = /* @__PURE__ */ new Set([
6
+ "CreateSchemaStmt",
7
+ "CreateStmt",
8
+ "CreateExtensionStmt",
9
+ "CreateSeqStmt",
10
+ "CreateEnumStmt",
11
+ "CreateFunctionStmt",
12
+ "CreateTrigStmt",
13
+ "ViewStmt",
14
+ "CommentStmt",
15
+ "VariableSetStmt",
16
+ "GrantStmt",
17
+ "CreatePolicyStmt"
18
+ ]);
19
+ const looseConstraints = /* @__PURE__ */ new Set([
20
+ "CONSTR_NULL",
21
+ "CONSTR_DEFAULT",
22
+ "CONSTR_GENERATED",
23
+ "CONSTR_IDENTITY"
24
+ ]);
25
+ const alterLabels = {
26
+ AT_DropColumn: "drops a column",
27
+ AT_AlterColumnType: "changes a column's type",
28
+ AT_SetNotNull: "makes a column not null",
29
+ AT_DropConstraint: "drops a constraint"
30
+ };
31
+ const kindLabels = {
32
+ RenameStmt: "renames a table, column or other object",
33
+ AlterObjectSchemaStmt: "moves an object to another schema",
34
+ DeleteStmt: "deletes rows",
35
+ TruncateStmt: "empties a table"
36
+ };
37
+ const alterFinding = (cmd, made) => {
38
+ switch (cmd.subtype) {
39
+ case "AT_DropNotNull": return;
40
+ case "AT_ColumnDefault": return cmd.def ? void 0 : "drops a column's default";
41
+ case "AT_AddConstraint": return made ? void 0 : `adds a constraint to a table there already, which rows written by older code may break`;
42
+ case "AT_AddColumn": {
43
+ if (made) return;
44
+ const constraints = (cmd.def.ColumnDef.constraints ?? []).filter((item) => !(item.Constraint.contype === "CONSTR_DEFAULT" && item.Constraint.raw_expr?.A_Const?.isnull)).map((item) => item.Constraint.contype);
45
+ if (constraints.includes("CONSTR_NOTNULL") && !constraints.includes("CONSTR_DEFAULT")) return `adds the required column ${cmd.def.ColumnDef.colname} without a default`;
46
+ return constraints.filter((contype) => !looseConstraints.has(contype) && contype !== "CONSTR_NOTNULL").length > 0 ? `adds the column ${cmd.def.ColumnDef.colname} with a constraint older code's rows may break` : void 0;
47
+ }
48
+ default: return alterLabels[cmd.subtype] ?? `${cmd.subtype.replace(/^AT_/, "")}, which the lint cannot tell only adds`;
49
+ }
50
+ };
51
+ const droppedTriggers = (statement) => (statement.objects ?? []).map((object) => names(object?.List?.items));
52
+ const createdTrigger = (node) => `${node.relation.schemaname ? `${node.relation.schemaname}.` : ""}${node.relation.relname}.${node.trigname}`;
53
+ const modifyingCtes = (node) => [...node.withClause?.ctes ?? [], ...node.selectStmt?.SelectStmt?.withClause?.ctes ?? []].flatMap((cte) => Object.keys(cte.CommonTableExpr?.ctequery ?? {})).filter((kind) => kind !== "SelectStmt");
54
+ const droppedNames = (statement) => (statement.objects ?? []).map((object) => names(object?.List?.items ?? object?.ObjectWithArgs?.objname ?? (object?.String ? [object] : []))).join(", ");
55
+ /**
56
+ * What in `statements`, as Postgres's parser reads them in order, takes something from older code, one line each:
57
+ * none when every statement only adds. A table the same statements make, without `if not exists`, takes any change;
58
+ * a trigger dropped without `cascade` and made again on its table by a later statement is replaced.
59
+ */
60
+ const contractingStatements = (statements) => {
61
+ const made = new Set(statements.filter(({ kind, node }) => kind === "CreateStmt" && !node.if_not_exists).map(({ node }) => relationKey(node.relation)));
62
+ const triggersMade = statements.flatMap(({ kind, node }, index) => kind === "CreateTrigStmt" ? [{
63
+ key: createdTrigger(node),
64
+ index
65
+ }] : []);
66
+ return statements.flatMap(({ kind, node }, index) => {
67
+ if (plainKinds.has(kind)) return [];
68
+ if (kind === "InsertStmt" || kind === "UpdateStmt") return modifyingCtes(node).map((cte) => kindLabels[cte] ?? `${cte.replace(/Stmt$/, "")} in a with clause, which the lint cannot tell only adds`);
69
+ if (kind === "AlterEnumStmt") return node.oldVal ? ["renames a value of an enum type"] : [];
70
+ if (kind === "IndexStmt") return node.unique && !made.has(relationKey(node.relation)) ? ["adds a unique index to a table there already, which rows written by older code may break"] : [];
71
+ if (kind === "AlterTableStmt" && node.objtype === "OBJECT_TABLE") return node.cmds.flatMap(({ AlterTableCmd: cmd }) => {
72
+ const finding = alterFinding(cmd, made.has(relationKey(node.relation)));
73
+ return finding ? [finding] : [];
74
+ });
75
+ if (kind === "DropStmt" && (node.removeType === "OBJECT_INDEX" || node.removeType === "OBJECT_POLICY")) return [];
76
+ if (kind === "DropStmt" && node.behavior === "DROP_CASCADE") return ["drops with cascade"];
77
+ if (kind === "DropStmt" && node.removeType === "OBJECT_TRIGGER") return droppedTriggers(node).filter((key) => !triggersMade.some((made) => made.key === key && made.index > index)).map((key) => `drops trigger ${key} without making it again`);
78
+ if (kind === "DropStmt") {
79
+ const what = node.removeType.replace(/^OBJECT_/, "").toLowerCase().replaceAll("_", " ");
80
+ const replace = node.removeType === "OBJECT_VIEW" || node.removeType === "OBJECT_FUNCTION" ? `, which \`create or replace\` keeps for older code` : "";
81
+ return [`drops ${what} ${droppedNames(node)}${replace}`];
82
+ }
83
+ return [kindLabels[kind] ?? `${kind.replace(/Stmt$/, "")}, which the lint cannot tell only adds`];
84
+ });
85
+ };
86
+ /** What in `sql` takes something from older code, read with libpg-query, Postgres's parser; a parse error is one line. */
87
+ const contractingSql = async (sql) => {
88
+ const { parse, SqlError } = await import("libpg-query");
89
+ let parsed;
90
+ try {
91
+ parsed = await parse(sql);
92
+ } catch (error) {
93
+ if (!(error instanceof SqlError)) throw error;
94
+ return ["SQL the parser cannot read"];
95
+ }
96
+ return contractingStatements((parsed.stmts ?? []).map(({ stmt }) => {
97
+ const [kind, node] = Object.entries(stmt ?? {})[0];
98
+ return {
99
+ kind,
100
+ node
101
+ };
102
+ }));
103
+ };
104
+ //#endregion
105
+ export { contractingSql, contractingStatements };
@@ -0,0 +1,61 @@
1
+ import { deviceColumns } from "./options.js";
2
+ import { devicesTableSql, qualified } from "./schema-sql.js";
3
+ import { legacyKindChecks } from "./legacy-kind-checks.js";
4
+ import { cascadesFrom, columnNumbers, uniqueOn } from "./read-table.js";
5
+ import { regclass } from "./schema.js";
6
+ import { tableNames } from "./table-names.js";
7
+ import { sql } from "kysely";
8
+ //#region src/notifications/devices-module.ts
9
+ const upgradeFirst = "with `protobase migration` and `protobase migrate` of Protobase 0.14.2 first, then run this command again";
10
+ const kindChecksWithoutRelay = async (db, oid, names) => {
11
+ const { rows } = await sql`select c.conname as name, pg_get_constraintdef(c.oid) as def from pg_constraint c
12
+ join pg_attribute a on a.attrelid = c.conrelid and a.attnum = any(c.conkey)
13
+ where c.conrelid = ${oid} and c.contype = 'c' and a.attname = ${names.columns.kind} order by c.conname`.execute(db);
14
+ return legacyKindChecks(rows, names.columns);
15
+ };
16
+ /**
17
+ * The devices table as the database has it, made by a migration or the app's own: step 1 once it has each column under
18
+ * its configured name, a unique index on the token alone, which moving a device relies on, and with sign-in a foreign
19
+ * key from the user column that deletes a user's devices with the user. Refuses one written before devices kept their
20
+ * session or could be relay devices, which no step records, and one without what the server relies on, naming it.
21
+ */
22
+ const readDevices = async (db, input) => {
23
+ const { table: names, users } = tableNames(input.names, deviceColumns);
24
+ const devices = qualified(names);
25
+ const oid = await regclass(db, devices);
26
+ if (oid === null) return;
27
+ const numbers = await columnNumbers(db, oid, names);
28
+ if (numbers.session_id === void 0 || (await kindChecksWithoutRelay(db, oid, names)).length > 0) throw new Error(`The devices table ${devices} was written before devices kept their session and could be relay devices, which no step of this version of Protobase records: bring it there ${upgradeFirst}`);
29
+ const missing = deviceColumns.find((column) => numbers[column] === void 0);
30
+ if (missing !== void 0) throw new Error(`The devices table ${devices} has no column "${names.columns[missing]}": add it, or name the table's own with notifications: { devices: { columns: { ${missing}: ... } } } in protobase.config.ts`);
31
+ if (!await uniqueOn(db, oid, numbers.token)) throw new Error(`The devices table ${devices} needs a unique index on its token column "${names.columns.token}" alone, which moving a device to the user who registers it relies on`);
32
+ if (users && !await cascadesFrom(db, oid, numbers.user_id, users)) throw new Error(`The devices table ${devices} needs a foreign key from "${names.columns.user_id}" to ${users} with on delete cascade, so a deleted user's devices go with them`);
33
+ return {
34
+ lastStep: 1,
35
+ replaceables: {},
36
+ names: input.names
37
+ };
38
+ };
39
+ /**
40
+ * The devices table notifications push to, unless a store of the app's own keeps them, under the names the config gives
41
+ * it (`moduleNames`): its user column points at the auth store's users with sign-in. Never dropped.
42
+ */
43
+ const notificationDevicesModule = {
44
+ label: "the devices table of notifications",
45
+ title: "The devices table of notifications",
46
+ steps: [{
47
+ step: 1,
48
+ name: "devices",
49
+ title: "The devices table and its indexes",
50
+ additive: true,
51
+ sql: (moduleNames) => {
52
+ const { table, user } = tableNames(moduleNames, deviceColumns);
53
+ return `${devicesTableSql(table, user).join(";\n")};`;
54
+ }
55
+ }],
56
+ replaceables: [],
57
+ resourceReplaceables: [],
58
+ read: readDevices
59
+ };
60
+ //#endregion
61
+ export { notificationDevicesModule };
@@ -0,0 +1,50 @@
1
+ import { historyColumns } from "./options.js";
2
+ import { qualified } from "./schema-sql.js";
3
+ import { cascadesFrom, columnNumbers } from "./read-table.js";
4
+ import { regclass } from "./schema.js";
5
+ import { tableNames } from "./table-names.js";
6
+ import { historyTableSql } from "./history-sql.js";
7
+ //#region src/notifications/history-module.ts
8
+ /**
9
+ * The history table as the database has it, made by a migration or the app's own: step 1 once it has each column under
10
+ * its configured name and, with sign-in, the foreign key that deletes a user's history with the user. Refuses one
11
+ * without them, naming what it lacks.
12
+ */
13
+ const readHistory = async (db, input) => {
14
+ const { table: names, users } = tableNames(input.names, historyColumns);
15
+ const history = qualified(names);
16
+ const oid = await regclass(db, history);
17
+ if (oid === null) return;
18
+ const numbers = await columnNumbers(db, oid, names);
19
+ const missing = historyColumns.find((column) => numbers[column] === void 0);
20
+ if (missing !== void 0) throw new Error(`The history table ${history} has no column "${names.columns[missing]}": add it, or name the table's own with notifications: { history: { columns: { ${missing}: ... } } } in protobase.config.ts`);
21
+ if (users && !await cascadesFrom(db, oid, numbers.user_id, users)) throw new Error(`The history table ${history} needs a foreign key from "${names.columns.user_id}" to ${users} with on delete cascade, so a deleted user's history goes with them`);
22
+ return {
23
+ lastStep: 1,
24
+ replaceables: {},
25
+ names: input.names
26
+ };
27
+ };
28
+ /**
29
+ * Each user's notification history, unless a store of the app's own keeps it, under the names the config gives it
30
+ * (`moduleNames`): its user column points at the auth store's users with sign-in. Never dropped.
31
+ */
32
+ const notificationHistoryModule = {
33
+ label: "the history table of notifications",
34
+ title: "The table of each user's notification history",
35
+ steps: [{
36
+ step: 1,
37
+ name: "history",
38
+ title: "The history table and its indexes",
39
+ additive: true,
40
+ sql: (moduleNames) => {
41
+ const { table, user } = tableNames(moduleNames, historyColumns);
42
+ return `${historyTableSql(table, user).join(";\n")};`;
43
+ }
44
+ }],
45
+ replaceables: [],
46
+ resourceReplaceables: [],
47
+ read: readHistory
48
+ };
49
+ //#endregion
50
+ export { notificationHistoryModule };
@@ -0,0 +1,23 @@
1
+ import { historyNames, notificationsNames } from "./options.js";
2
+ import { moduleNames, usersTarget } from "./table-names.js";
3
+ //#region src/notifications/notifications-targets.ts
4
+ /**
5
+ * The schema modules `notifications` needs, under the names its options give them: the devices table unless a store of
6
+ * the app's own keeps the devices, and the history table unless one keeps the history, each pointing at the users of
7
+ * the auth store `store` names, none without sign-in.
8
+ */
9
+ const notificationsTargets = (options, store) => {
10
+ const users = usersTarget(store);
11
+ return {
12
+ ...!options.store && { notification_devices: {
13
+ names: moduleNames(notificationsNames(options), users),
14
+ resources: {}
15
+ } },
16
+ ...!options.historyStore && { notification_history: {
17
+ names: moduleNames(historyNames(options), users),
18
+ resources: {}
19
+ } }
20
+ };
21
+ };
22
+ //#endregion
23
+ export { notificationsTargets };
@@ -0,0 +1,16 @@
1
+ import { sql } from "kysely";
2
+ //#region src/notifications/read-table.ts
3
+ const columnsOf = async (db, oid) => (await sql`select attname as name, attnum as num from pg_attribute where attrelid = ${oid} and attnum > 0 and not attisdropped`.execute(db)).rows;
4
+ /** Each column of `names` by its number in the table, `undefined` for one the table lacks. */
5
+ const columnNumbers = async (db, oid, names) => {
6
+ const found = await columnsOf(db, oid);
7
+ return Object.fromEntries(Object.entries(names.columns).map(([column, name]) => [column, found.find((row) => row.name === name)?.num]));
8
+ };
9
+ /** Whether a valid unique index without a condition holds exactly the column: one an interrupted concurrent build left does not. */
10
+ const uniqueOn = async (db, oid, num) => (await sql`select exists (select from pg_index where indrelid = ${oid} and indisunique and indisvalid and indpred is null and indexprs is null and indnatts = 1 and indkey[0] = ${num}) as found`.execute(db)).rows[0].found;
11
+ /** Whether a foreign key from exactly the column points at the users table's `id` and deletes with it. */
12
+ const cascadesFrom = async (db, oid, num, users) => (await sql`select exists (select from pg_constraint where conrelid = ${oid} and contype = 'f' and confdeltype = 'c'
13
+ and conkey = array[${num}]::int2[] and confrelid = to_regclass(${users})
14
+ and confkey = array[(select attnum from pg_attribute where attrelid = to_regclass(${users}) and attname = 'id' and not attisdropped)]::int2[]) as found`.execute(db)).rows[0].found;
15
+ //#endregion
16
+ export { cascadesFrom, columnNumbers, uniqueOn };