@protobase/server 0.129.0 → 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 +35 -0
  56. package/dist/better-auth/store/offline/baseline-store.js +65 -0
  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 -6
  62. package/dist/better-auth/store/offline/offline-steps.js +30 -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 +13 -4
  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 +27 -10
  126. package/dist/internal.js +22 -7
  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
@@ -0,0 +1,113 @@
1
+ import { generatedName } from "../../../names/identifier-length.js";
2
+ import { ddl } from "../../ddl.js";
3
+ import { sql } from "kysely";
4
+ //#region src/better-auth/store/steps/organizations/003-default-organization.ts
5
+ const fillBatch = 1e4;
6
+ const settings = ({ organizations }) => {
7
+ if (!organizations) throw new Error("organizations.default is not set: give the config the organization that stands in while organizations are off, such as { id, name, slug }");
8
+ return organizations;
9
+ };
10
+ const defaultId = ({ idRef }, input) => ddl`cast(${sql.lit(settings(input).default.id)} as ${idRef})`;
11
+ const setCheckName = ({ table }) => generatedName(`${table("personal_access_token").name}_organization_id_set`);
12
+ /**
13
+ * The default organization, `organizations.default`, and every row of an organization in one. Its organization is
14
+ * made when the store lacks it, under its id. When organizations turn on for the first time, every user there already
15
+ * becomes its member with `organizations.existingUsersRole`, which a new store with its own user table, holding none,
16
+ * does without, and every personal access token works in it; when they
17
+ * were on before, a token without an organization has none to copy, so the step refuses, naming it, such as one made
18
+ * while they were off before tokens made then were given the default organization as they were made. The tokens'
19
+ * organization is then required: filled in batches, checked without a scan, and indexed concurrently, once the
20
+ * migration's transaction commits.
21
+ */
22
+ const defaultOrganization = {
23
+ step: 3,
24
+ name: "default_organization",
25
+ version: 18,
26
+ title: "The default organization, its members, and the organization of every personal access token",
27
+ tables: [],
28
+ check: ({ table, idRef }, input) => {
29
+ const organization = table("organization");
30
+ const o = organization.columns;
31
+ const { id, slug } = settings(input).default;
32
+ return ddl`do $check$
33
+ begin
34
+ if exists (select from ${organization} where ${o.slug} = ${sql.lit(slug)} and id <> cast(${sql.lit(id)} as ${idRef})) then
35
+ raise exception 'The auth store has an organization with the slug % under another id than the default organization''s, %: give organizations.default the id of that organization, or another slug.', ${sql.lit(slug)}, ${sql.lit(id)};
36
+ end if;
37
+ end
38
+ $check$`;
39
+ },
40
+ statements: (names, input) => {
41
+ const { table, user, idRef } = names;
42
+ const organization = table("organization");
43
+ const o = organization.columns;
44
+ const member = table("member");
45
+ const m = member.columns;
46
+ const { default: { name, slug }, existingUsersRole } = settings(input);
47
+ const id = defaultId(names, input);
48
+ const made = ddl`insert into ${organization} (id, ${o.name}, ${o.slug}, ${o.created_at})
49
+ select ${id}, ${sql.lit(name)}, ${sql.lit(slug)}, now()
50
+ where not exists (select from ${organization} where id = ${id})`;
51
+ if (!input.firstOn || !input.usersThere && existingUsersRole === void 0) return [made];
52
+ if (existingUsersRole === void 0) throw new Error("organizations.existingUsersRole is not set: name the app role every user there already holds in the default organization as organizations turn on");
53
+ return [made, ddl`insert into ${member} (id, ${m.organization_id}, ${m.user_id}, ${m.role}, ${m.created_at}, ${m.app_roles})
54
+ select cast(pg_catalog.gen_random_uuid() as ${idRef}), ${id}, people.id, 'member', now(), jsonb_build_array(${sql.lit(existingUsersRole)})
55
+ from ${user} as people
56
+ where not exists (select from ${member} where ${m.organization_id} = ${id} and ${m.user_id} = people.id)`];
57
+ },
58
+ adds: { personal_access_tokens: (names) => {
59
+ const token = names.table("personal_access_token");
60
+ return [ddl`alter table ${token} add constraint ${sql.id(setCheckName(names))} check (${token.columns.organization_id} is not null) not valid`];
61
+ } },
62
+ addsChecks: { personal_access_tokens: ({ table }, input) => {
63
+ const token = table("personal_access_token");
64
+ const t = token.columns;
65
+ if (input.firstOn) return;
66
+ return ddl`do $check$
67
+ declare
68
+ found text;
69
+ total bigint;
70
+ begin
71
+ select count(*) into total from ${token} where ${t.organization_id} is null;
72
+ if total > 0 then
73
+ select string_agg(id::text, ', ' order by id) into found from (select id from ${token} where ${t.organization_id} is null order by id limit 20) as listed;
74
+ raise exception 'The auth store has % personal access tokens without an organization, which organizations were on for: %. Delete them, or set the organization each works in, in a migration of the project''s own written before this one, then apply again.', total, found;
75
+ end if;
76
+ end
77
+ $check$`;
78
+ } },
79
+ addsAfter: { personal_access_tokens: (names, input, concurrent) => {
80
+ const token = names.table("personal_access_token");
81
+ const t = token.columns;
82
+ const check = sql.id(setCheckName(names));
83
+ const id = defaultId(names, input);
84
+ const pending = ddl`select id from ${token} where ${t.organization_id} is null limit ${sql.lit(fillBatch)}`;
85
+ const fill = concurrent ? ddl`do $fill$
86
+ declare
87
+ filled bigint;
88
+ begin
89
+ loop
90
+ update ${token} set ${t.organization_id} = ${id} where id in (${pending});
91
+ get diagnostics filled = row_count;
92
+ exit when filled = 0;
93
+ commit;
94
+ end loop;
95
+ end
96
+ $fill$` : ddl`update ${token} set ${t.organization_id} = ${id} where ${t.organization_id} is null`;
97
+ return [
98
+ ...input.firstOn ? [fill] : [],
99
+ ddl`do $required$
100
+ begin
101
+ if exists (select from pg_catalog.pg_constraint where conrelid = ${sql.lit(String(token))}::regclass and conname = ${sql.lit(setCheckName(names))}) then
102
+ alter table ${token} validate constraint ${check};
103
+ alter table ${token} alter column ${t.organization_id} set not null;
104
+ alter table ${token} drop constraint ${check};
105
+ end if;
106
+ end
107
+ $required$`,
108
+ ddl`create index ${sql.raw(concurrent ? "concurrently " : "")}if not exists ${token.index("personal_access_token_organization_id_user_id_idx")} on ${token} (${t.organization_id}, ${t.user_id})`
109
+ ];
110
+ } }
111
+ };
112
+ //#endregion
113
+ export { defaultOrganization };
@@ -0,0 +1,3 @@
1
+ import "../../names/modules/index.js";
2
+ import "./step.js";
3
+ import "kysely";
@@ -1,41 +1,64 @@
1
1
  import { builtInModules } from "../../names/modules/index.js";
2
2
  import { moduleSteps } from "./index.js";
3
3
  //#region src/better-auth/store/steps/render.ts
4
- const addsOn = (names, module, step, on) => ({
5
- module,
6
- step,
7
- on,
8
- version: Math.max(step.version, moduleSteps[on][0].version),
9
- statements: step.adds[on](names)
10
- });
11
4
  /**
12
- * The steps the store lacks of the modules that are on, in order: each module's in its chain's order, the modules in
13
- * the order they require one another. A module the store has none of, such as one just turned on, gets its whole
14
- * chain, and the statements other modules' steps add to its tables, those the store has applied included; a module
15
- * that is off gets nothing, and no other module adds to its tables.
5
+ * The version of the former single chain that made the part of `step` changing the tables of `target`: the step's
6
+ * own, or for the statements it adds to another module's tables, the later of its and that of the step that made
7
+ * them, as the former chain, with every module on, made them.
16
8
  */
17
- const renderSteps = (names, modules, had) => {
9
+ const partVersion = (module, step, target) => target === module ? step.version : Math.max(step.version, moduleSteps[target][0].version);
10
+ const addsOn = (names, input, module, step, on) => {
11
+ const check = step.addsChecks?.[on]?.(names, input);
12
+ const after = step.addsAfter?.[on];
13
+ return {
14
+ module,
15
+ step,
16
+ on,
17
+ version: partVersion(module, step, on),
18
+ ...check && { check },
19
+ statements: [...check ? [check] : [], ...step.adds[on](names, input)],
20
+ after: (concurrent) => after?.(names, input, concurrent) ?? []
21
+ };
22
+ };
23
+ const ownPart = (names, input, module, step) => {
24
+ const check = step.check?.(names, input);
25
+ return {
26
+ module,
27
+ step,
28
+ version: step.version,
29
+ ...check && { check },
30
+ statements: [...check ? [check] : [], ...step.statements(names, input)],
31
+ after: () => []
32
+ };
33
+ };
34
+ /**
35
+ * The parts of the modules that are on that the store lacks, in order: each module's steps in its chain's order, the
36
+ * modules in the order they require one another, and the statements a step adds to another module's tables once that
37
+ * module's are there. A module the store has none of, such as one just turned on, gets its whole chain, and the
38
+ * statements other modules' steps add to its tables, those the store has applied included; a module that is off gets
39
+ * nothing, and no other module adds to its tables. `organizations`: the config's default organization and the role of
40
+ * the users there already, which the organizations' steps write rows from; organizations turn on for the first time
41
+ * when the store lacks their first step, and the users are there when it has sign-in's or another system made them.
42
+ */
43
+ const renderSteps = (names, modules, had, organizations) => {
44
+ const input = {
45
+ organizations,
46
+ firstOn: !had("organizations", 1, "organizations"),
47
+ usersThere: names.externalUser || had("auth", 1, "auth")
48
+ };
18
49
  const on = builtInModules.map(({ id }) => id).filter((module) => modules.includes(module));
19
50
  const rendered = [];
20
51
  const waiting = [];
21
- const made = new Set(on.filter((module) => had(module, moduleSteps[module][0])));
22
- const turnedOn = on.filter((module) => !made.has(module));
52
+ const made = new Set(on.filter((module) => had(module, moduleSteps[module][0].step, module)));
23
53
  for (const module of on) {
24
- for (const step of moduleSteps[module].filter((step) => !had(module, step))) {
25
- rendered.push({
26
- module,
27
- step,
28
- version: step.version,
29
- statements: [...step.check ? [step.check(names)] : [], ...step.statements(names)]
30
- });
31
- for (const target of on.filter((target) => step.adds?.[target])) (made.has(target) ? rendered : waiting).push(addsOn(names, module, step, target));
54
+ for (const step of moduleSteps[module]) {
55
+ if (!had(module, step.step, module)) rendered.push(ownPart(names, input, module, step));
56
+ for (const target of on.filter((target) => step.adds?.[target] && !had(module, step.step, target))) (made.has(target) ? rendered : waiting).push(addsOn(names, input, module, step, target));
32
57
  }
33
58
  made.add(module);
34
59
  rendered.push(...waiting.filter((adds) => adds.on === module));
35
- if (!turnedOn.includes(module)) continue;
36
- for (const other of on.filter((other) => other !== module)) for (const step of moduleSteps[other].filter((step) => step.adds?.[module] && had(other, step))) rendered.push(addsOn(names, other, step, module));
37
60
  }
38
61
  return rendered;
39
62
  };
40
63
  //#endregion
41
- export { renderSteps };
64
+ export { partVersion, renderSteps };
@@ -1,4 +1,12 @@
1
1
  //#region src/better-auth/store/steps/step-lint.d.ts
2
+ /** The Squawk rules a statement that takes from older code what it reads, writes or relies on breaks. */
3
+ export declare const contractingRules: string[];
4
+ /**
5
+ * The Squawk rules of a statement that holds a lock blocking reads for as long as it scans or rewrites a table. Its
6
+ * rules about locks that only block writes, such as an index built without `concurrently`, do not apply: the
7
+ * migrations run in one transaction while nothing else writes.
8
+ */
9
+ export declare const lockingRules: string[];
2
10
  /** A rendered step: `made`, the tables it makes as its SQL names them; `checked`, whether it starts with a check. */
3
11
  export type LintedStep = {
4
12
  label: string;
@@ -11,6 +19,12 @@ export type StepFinding = {
11
19
  rule: string;
12
20
  message: string;
13
21
  };
22
+ /** What Squawk finds in a step, its line counted from 0. */
23
+ export type SquawkFinding = StepFinding & {
24
+ line: number;
25
+ };
26
+ /** Every finding of Squawk's in `steps`, each read as a file of its own, in one run. */
27
+ export declare const squawkReport: (steps: readonly Pick<LintedStep, "label" | "sql">[], squawk?: string) => SquawkFinding[];
14
28
  /**
15
29
  * What makes each step unsafe to apply unattended; none when every one is safe. `squawk`: the path of squawk-cli's
16
30
  * `js/bin/squawk`, as the package that runs the lint resolves it.
@@ -4,12 +4,8 @@ import { spawnSync } from "node:child_process";
4
4
  import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
5
5
  import path from "node:path";
6
6
  //#region src/better-auth/store/steps/step-lint.ts
7
- /**
8
- * The Squawk rules a step must not break, a step it cannot parse included. Its others are about locks and online
9
- * changes, which do not apply as the migrations run while nothing else writes, or about style.
10
- */
11
- const refusedRules = [
12
- "syntax-error",
7
+ /** The Squawk rules a statement that takes from older code what it reads, writes or relies on breaks. */
8
+ const contractingRules = [
13
9
  "ban-drop-column",
14
10
  "ban-drop-table",
15
11
  "ban-drop-database",
@@ -21,7 +17,26 @@ const refusedRules = [
21
17
  "renaming-column",
22
18
  "renaming-table"
23
19
  ];
24
- const squawkFindings = (steps, squawk) => {
20
+ /**
21
+ * The Squawk rules of a statement that holds a lock blocking reads for as long as it scans or rewrites a table. Its
22
+ * rules about locks that only block writes, such as an index built without `concurrently`, do not apply: the
23
+ * migrations run in one transaction while nothing else writes.
24
+ */
25
+ const lockingRules = [
26
+ "adding-not-nullable-field",
27
+ "changing-column-type",
28
+ "adding-field-with-default",
29
+ "constraint-missing-not-valid",
30
+ "adding-serial-primary-key-field"
31
+ ];
32
+ /**
33
+ * The Squawk rules a step must not break, a step it cannot parse included. Its others are about locks and online
34
+ * changes, which do not apply as the migrations run while nothing else writes, or about style.
35
+ */
36
+ const refusedRules = ["syntax-error", ...contractingRules];
37
+ /** Every finding of Squawk's in `steps`, each read as a file of its own, in one run. */
38
+ const squawkReport = (steps, squawk = createRequire(import.meta.url).resolve("squawk-cli/js/bin/squawk")) => {
39
+ if (steps.length === 0) return [];
25
40
  const dir = mkdtempSync(path.join(tmpdir(), "protobase-step-lint-"));
26
41
  const files = steps.map((step, i) => {
27
42
  const file = path.join(dir, `${i}.sql`);
@@ -38,12 +53,18 @@ const squawkFindings = (steps, squawk) => {
38
53
  rmSync(dir, { recursive: true });
39
54
  if (run.error) throw run.error;
40
55
  if (run.stdout.trim() === "") throw new Error(`squawk exited with ${run.status}: ${run.stderr}`);
41
- return JSON.parse(run.stdout).filter((finding) => refusedRules.includes(finding.rule_name)).map((finding) => ({
56
+ return JSON.parse(run.stdout).map((finding) => ({
42
57
  step: steps[files.indexOf(finding.file)].label,
43
58
  rule: finding.rule_name,
44
- message: finding.message
59
+ message: finding.message,
60
+ line: finding.line
45
61
  }));
46
62
  };
63
+ const squawkFindings = (steps, squawk) => squawkReport(steps, squawk).filter((finding) => refusedRules.includes(finding.rule)).map(({ step, rule, message }) => ({
64
+ step,
65
+ rule,
66
+ message
67
+ }));
47
68
  const uniqueIndexOn = /^\s*create\s+unique\s+index\s+(?:if\s+not\s+exists\s+)?(?:"[^"]+"|\w+)\s+on\s+((?:(?:"[^"]+"|\w+)\.)?(?:"[^"]+"|\w+))/gim;
48
69
  /** A unique index over the rows of a table the step did not make holds only when they are unique: the step checks that first. */
49
70
  const uncheckedUniqueIndexes = (steps) => steps.filter((step) => !step.checked).flatMap((step) => [...step.sql.matchAll(uniqueIndexOn)].filter((match) => !step.made.includes(match[1])).map((match) => ({
@@ -57,4 +78,4 @@ const uncheckedUniqueIndexes = (steps) => steps.filter((step) => !step.checked).
57
78
  */
58
79
  const lintSteps = (steps, squawk = createRequire(import.meta.url).resolve("squawk-cli/js/bin/squawk")) => [...squawkFindings(steps, squawk), ...uncheckedUniqueIndexes(steps)];
59
80
  //#endregion
60
- export { lintSteps };
81
+ export { contractingRules, lintSteps, lockingRules, squawkReport };
@@ -0,0 +1,18 @@
1
+ import "../../names/identifiers.js";
2
+ import "../../names/modules/index.js";
3
+ import "../../names/resolve-names.js";
4
+ import { DefaultOrganization } from "../../organizations/options.js";
5
+ import "../store-names.js";
6
+ import "kysely";
7
+ //#region src/better-auth/store/steps/step.d.ts
8
+ /** The organizations' settings a step writes rows from: the default organization, and the app role of the users there already. */
9
+ export type OrganizationsInput = {
10
+ default: DefaultOrganization;
11
+ existingUsersRole: string | undefined;
12
+ };
13
+ /** The organizations' input of the steps from their settings; `undefined` without a default organization. */
14
+ export declare const organizationsInput: (settings: {
15
+ default?: DefaultOrganization;
16
+ existingUsersRole?: string;
17
+ } | undefined) => OrganizationsInput | undefined;
18
+ //#endregion
@@ -1,14 +1,23 @@
1
1
  import { tableId } from "../../names/identifiers.js";
2
2
  import { sql } from "kysely";
3
3
  //#region src/better-auth/store/steps/step.ts
4
- /** The `ddl` parts of the store's names. */
5
- const migrationNames = ({ names, users, uuidIds }) => ({
4
+ /** The organizations' input of the steps from their settings; `undefined` without a default organization. */
5
+ const organizationsInput = (settings) => settings?.default ? {
6
+ default: settings.default,
7
+ existingUsersRole: settings.existingUsersRole
8
+ } : void 0;
9
+ /**
10
+ * The `ddl` parts of the store's names. `externalUser`: the user table is a relation Protobase did not make, which its
11
+ * statements leave alone, as under `users.keyTable` or as a project's snapshot records it.
12
+ */
13
+ const migrationNames = ({ names, users, uuidIds }, externalUser = users.keyTable !== void 0) => ({
6
14
  table: names.table,
7
15
  user: users.keyTable ? tableId(users.keyTable.schema, users.keyTable.table) : names.table("user"),
8
- userDdl: (statements) => users.keyTable ? [] : statements,
16
+ userDdl: (statements) => externalUser ? [] : statements,
17
+ externalUser,
9
18
  metadata: users.metadata,
10
19
  id: sql.raw(uuidIds ? "uuid default pg_catalog.gen_random_uuid()" : "text"),
11
20
  idRef: sql.raw(uuidIds ? "uuid" : "text")
12
21
  });
13
22
  //#endregion
14
- export { migrationNames };
23
+ export { migrationNames, organizationsInput };
@@ -0,0 +1,6 @@
1
+ import { StoreOptions } from "./store-names.js";
2
+ import { Kysely } from "kysely";
3
+ //#region src/better-auth/store/store-db.d.ts
4
+ /** The admin store's connections without the app's query plugins: what its migrations and schema checks read and write. */
5
+ export declare const plainStoreDb: (auth: StoreOptions) => Kysely<any>;
6
+ //#endregion
@@ -3,7 +3,7 @@ import { Kysely, PostgresDialect } from "kysely";
3
3
  /**
4
4
  * The Kysely the admin store's queries run through: `createAuth`'s `database`, the app's own Kysely
5
5
  * (`{ db, type: 'postgres' }`), a `pg` Pool or `{ dialect, type: 'postgres' }`. The app's Kysely is used as it is, its
6
- * plugins included; the pool is the app's, so it is never destroyed here.
6
+ * plugins included, kept to an organization when it is a `ScopedDb`; the pool is the app's, so it is never destroyed here.
7
7
  */
8
8
  const storeDb = ({ options: { database } }) => {
9
9
  if (database && typeof database === "object" && "db" in database) return database.db;
@@ -12,9 +12,15 @@ const storeDb = ({ options: { database } }) => {
12
12
  throw new Error("The admin store's database is neither a Kysely, a pg Pool nor { dialect, type: 'postgres' }");
13
13
  };
14
14
  /**
15
- * The admin store's connections without the app's query plugins: what its migrations and schema checks read and
16
- * write, which name the store's tables as they are in the database.
15
+ * `db` without the app's query plugins, for reads and writes that name tables as they are in the database. A database
16
+ * kept to an organization (`ScopedDb`) leaves its scope by name first, saying why (`reason`), as it refuses
17
+ * `withoutPlugins` alone.
17
18
  */
18
- const plainStoreDb = (auth) => storeDb(auth).withoutPlugins();
19
+ const withoutAppPlugins = (db, reason) => {
20
+ const scoped = db;
21
+ return (typeof scoped.unscoped === "function" ? scoped.unscoped(reason) : db).withoutPlugins();
22
+ };
23
+ /** The admin store's connections without the app's query plugins: what its migrations and schema checks read and write. */
24
+ const plainStoreDb = (auth) => withoutAppPlugins(storeDb(auth), "the store's migrations and schema checks name its tables as they are");
19
25
  //#endregion
20
- export { plainStoreDb, storeDb };
26
+ export { plainStoreDb, storeDb, withoutAppPlugins };
@@ -10,6 +10,10 @@ export type StoreNames = {
10
10
  /** Every id column is a uuid Postgres makes, instead of text. */
11
11
  uuidIds: boolean;
12
12
  };
13
+ /** What the store's helpers read of an auth instance, or of Better Auth's context: the options' `database`. */
14
+ export type StoreOptions = {
15
+ options: Pick<BetterAuthOptions, 'database'>;
16
+ };
13
17
  /** What `storeNames` reads of the app's auth: its options' `advanced`, its resolved names and its user table's options. */
14
18
  export type StoreNamesSource = {
15
19
  options: Pick<BetterAuthOptions, 'advanced'>;
@@ -23,7 +23,11 @@ const tokenClaims = (payload, roles, tenant) => ({
23
23
  const revoked = () => unauthorized("The bearer token was revoked: get a new one");
24
24
  /** Whether the user's ban stands at `now`: it has no end, or its end is still to come. */
25
25
  const bannedNow = (user, now) => Boolean(user.banned) && (!user.banExpires || user.banExpires > now);
26
- const heldWhere = async ({ adapter }, user, organizations, organizationId) => {
26
+ const heldWhere = async ({ adapter }, user, organizations, organizationId, pin) => {
27
+ if (!organizations && pin !== void 0 && !await findMember(adapter, {
28
+ organizationId: pin,
29
+ userId: user.id
30
+ })) return;
27
31
  if (!organizations) return { roles: parseRoles(user.role) };
28
32
  const global = globalRoles(user.role);
29
33
  if (!organizationId) return { roles: global };
@@ -41,9 +45,10 @@ const heldWhere = async ({ adapter }, user, organizations, organizationId) => {
41
45
  * Whether a token's user still stands, read from the store: they exist and are not banned, and each role the token
42
46
  * carries is one they still hold where it works. The part of `checkTokenStanding` an MCP access token gets, whose
43
47
  * grant outlives the browser session that made it. Answers their organization role where the token works, as the
44
- * store holds it now, `undefined` for someone who is no member there.
48
+ * store holds it now, `undefined` for someone who is no member there. With organizations off after being on, `pin` is
49
+ * the pinned organization, and someone who is no member of it no longer stands.
45
50
  */
46
- const checkUserStanding = async (context, claims, organizations, now = /* @__PURE__ */ new Date()) => {
51
+ const checkUserStanding = async (context, claims, organizations, now = /* @__PURE__ */ new Date(), pin) => {
47
52
  const user = await context.adapter.findOne({
48
53
  model: "user",
49
54
  where: [{
@@ -52,7 +57,7 @@ const checkUserStanding = async (context, claims, organizations, now = /* @__PUR
52
57
  }]
53
58
  });
54
59
  if (!user || bannedNow(user, now)) throw revoked();
55
- const held = await heldWhere(context, user, organizations, claims.organizationId);
60
+ const held = await heldWhere(context, user, organizations, claims.organizationId, pin);
56
61
  if (!held || claims.roles.some((role) => !held.roles.includes(role))) throw revoked();
57
62
  return held.organizationRole;
58
63
  };
@@ -62,9 +67,9 @@ const checkUserStanding = async (context, claims, organizations, now = /* @__PUR
62
67
  * one, which carries the roles as they are now or is refused. Answers the sign-in the token's session stands for
63
68
  * (`signInOf`), `undefined` for a token without one; the user's own one also reads, when asked, when it last proved a
64
69
  * passkey or a second step (`strongSignInAt`). Answers it with the user's organization role where the token works
65
- * (`checkUserStanding`).
70
+ * (`checkUserStanding`), a member of `pin` while organizations are off after being on.
66
71
  */
67
- const checkTokenStanding = async (context, claims, organizations, now = /* @__PURE__ */ new Date()) => {
72
+ const checkTokenStanding = async (context, claims, organizations, now = /* @__PURE__ */ new Date(), pin) => {
68
73
  const session = claims.sessionId === void 0 ? void 0 : await context.adapter.findOne({
69
74
  model: "session",
70
75
  where: [{
@@ -73,7 +78,7 @@ const checkTokenStanding = async (context, claims, organizations, now = /* @__PU
73
78
  }]
74
79
  });
75
80
  if (claims.sessionId !== void 0 && (!session || session.userId !== claims.userId || session.expiresAt <= now)) throw revoked();
76
- const organizationRole = await checkUserStanding(context, claims, organizations, now);
81
+ const organizationRole = await checkUserStanding(context, claims, organizations, now, pin);
77
82
  const signIn = session ? signInOf(session, claims.sessionId) : void 0;
78
83
  if (!signIn || signIn.staff) return {
79
84
  signIn,
@@ -1,4 +1,5 @@
1
1
  import { AdminAuth } from "./create-auth.js";
2
+ import { HostScope } from "./organizations/host-scope.js";
2
3
  import { parseRoles } from "./parse-roles.js";
3
4
  //#region src/better-auth/users.d.ts
4
5
  /** The roles this auth instance allows, `admin` first. */
@@ -53,10 +54,14 @@ export type UsersPage = {
53
54
  };
54
55
  /** The users a page of `listUsers` holds when it is not told. */
55
56
  export declare const usersPageSize = 500;
56
- /** A page of the users, oldest first: `size` of them from `after`, the `next` of the page before, as Postgres pages them. */
57
- export declare const listUsers: (auth: AdminAuth, { after, size }?: {
57
+ /**
58
+ * A page of the users, oldest first: `size` of them from `after`, the `next` of the page before, as Postgres pages them.
59
+ * With organizations, `scope` is the organization whose members it lists, or every organization; every user without.
60
+ */
61
+ export declare const listUsers: (auth: AdminAuth, { after, size, scope }?: {
58
62
  after?: UsersCursor;
59
63
  size?: number;
64
+ scope?: HostScope;
60
65
  }) => Promise<UsersPage>;
61
66
  /**
62
67
  * Deletes the user with their sessions and accounts, their MCP grants with MCP on, and what `auth.userDeletion`
@@ -1,11 +1,14 @@
1
1
  import { parseRoles } from "./parse-roles.js";
2
+ import { inSignInScope } from "../organization-scope/sign-in-organization.js";
2
3
  import { storeSqlOf } from "./store/store-sql.js";
3
4
  import { exists } from "./store/store-reads.js";
4
5
  import { activeAdminExists } from "./store/active-admin.js";
5
6
  import { isActiveAdmin } from "./last-admin.js";
6
7
  import { revokeMcpGrants } from "./mcp/revoke-grants.js";
7
8
  import { pageOf } from "./store/page-of.js";
9
+ import { rowsIn } from "./organizations/host-scope.js";
8
10
  import { ownOrganizationsWithoutMembers } from "./organizations/host.js";
11
+ import { isEveryOrganization } from "@protobase/query";
9
12
  import { sql } from "kysely";
10
13
  //#region src/better-auth/users.ts
11
14
  const contextOf = async (auth) => await auth.$context;
@@ -74,11 +77,30 @@ const refuseLastAdmin = async (auth, user, action) => {
74
77
  };
75
78
  /** The users a page of `listUsers` holds when it is not told. */
76
79
  const usersPageSize = 500;
77
- /** A page of the users, oldest first: `size` of them from `after`, the `next` of the page before, as Postgres pages them. */
78
- const listUsers = async (auth, { after, size = 500 } = {}) => {
80
+ /**
81
+ * A page of the users, oldest first: `size` of them from `after`, the `next` of the page before, as Postgres pages them.
82
+ * With organizations, `scope` is the organization whose members it lists, or every organization; every user without.
83
+ */
84
+ const listUsers = async (auth, { after, size = 500, scope } = {}) => {
85
+ if (scope === void 0 || isEveryOrganization(scope)) return usersPage(auth, {
86
+ after,
87
+ size
88
+ });
89
+ return inSignInScope(scope, () => usersPage(auth, {
90
+ after,
91
+ size,
92
+ scope
93
+ }));
94
+ };
95
+ const membersOf = (store, scope) => {
96
+ const member = store.table("member");
97
+ return sql`(select * from ${store.table("user")} u where exists (select from ${rowsIn(store, scope, member)} as m where m.${member.columns.user_id} = u.id)) as u`;
98
+ };
99
+ const usersPage = async (auth, { after, size, scope }) => {
79
100
  const store = storeSqlOf(await contextOf(auth));
80
101
  const user = store.table("user");
81
102
  const u = user.columns;
103
+ const from = scope === void 0 ? user : membersOf(store, scope);
82
104
  const select = {
83
105
  id: sql`id`,
84
106
  email: u.email,
@@ -87,7 +109,7 @@ const listUsers = async (auth, { after, size = 500 } = {}) => {
87
109
  createdAt: u.created_at
88
110
  };
89
111
  const page = await pageOf(store, {
90
- from: user,
112
+ from,
91
113
  select,
92
114
  key: [u.created_at, sql`id`],
93
115
  ...after && { after: [after.createdAt, after.id] },
@@ -1,7 +1,7 @@
1
1
  import { hasAiFields } from "./ai/ai-fields.js";
2
2
  import { capturedBy } from "./changes/capture-sql.js";
3
3
  import { changesSchema } from "./changes/events-options.js";
4
- import { hasBuckets } from "./computed/buckets-schema.js";
4
+ import { hasBuckets } from "./computed/buckets-targets.js";
5
5
  import { commentsResource, commentsView } from "./comments/record-comments.js";
6
6
  import { activityResource, activityView } from "./history/activity.js";
7
7
  import { failedJobs, failedJobsView } from "./jobs/failed-jobs.js";
@@ -0,0 +1,42 @@
1
+ import { callsTablesSql, guestsSchemaSql } from "./calls-sql.js";
2
+ import { sql } from "kysely";
3
+ //#region src/calls/calls-module.ts
4
+ /** The calls schema as the database has it: step 1 once its tables are there, step 2 once its guest tables are too. */
5
+ const readCalls = async (db) => {
6
+ const { rows } = await sql`select
7
+ to_regclass('calls.calls') is not null and to_regclass('calls.members') is not null and to_regclass('calls.signals') is not null and to_regclass('calls.rings') is not null as calls,
8
+ to_regclass('calls.guest_links') is not null and to_regclass('calls.guests') is not null and to_regclass('calls.organization_guests') is not null
9
+ and exists (select from information_schema.columns where table_schema = 'calls' and table_name = 'members' and column_name = 'name') as guests`.execute(db);
10
+ const found = rows[0];
11
+ if (!found.calls) return;
12
+ return {
13
+ lastStep: found.guests ? 2 : 1,
14
+ replaceables: {}
15
+ };
16
+ };
17
+ /**
18
+ * The `calls` schema: the calls on records, who is in them, whom they ring, their guests, and the signals between the
19
+ * processes serving the app. Rings reach open pages through the notices table, a module of its own. Never dropped.
20
+ */
21
+ const callsModule = {
22
+ label: "the calls schema",
23
+ title: "The calls on records, who is in them, whom they ring, their guests, and the signals between the processes serving the app",
24
+ steps: [{
25
+ step: 1,
26
+ name: "calls",
27
+ title: "The calls, their members, signals and rings",
28
+ additive: true,
29
+ sql: () => callsTablesSql
30
+ }, {
31
+ step: 2,
32
+ name: "guests",
33
+ title: "The guest links, the guests and whether organizations allow them",
34
+ additive: true,
35
+ sql: () => guestsSchemaSql
36
+ }],
37
+ replaceables: [],
38
+ resourceReplaceables: [],
39
+ read: readCalls
40
+ };
41
+ //#endregion
42
+ export { callsModule };
@@ -1,8 +1,3 @@
1
- import { quoteIdent } from "../changes/capture-sql.js";
2
- import { noticesTableSql } from "../live/notices-sql.js";
3
- import { changesSchema } from "../changes/events-options.js";
4
- import { migrationCommand } from "../changes/capture-schema.js";
5
- import { sql } from "kysely";
6
1
  //#region src/calls/calls-sql.ts
7
2
  /**
8
3
  * - `members.name`: the name a guest gave; NULL for the app's members, whom the app names.
@@ -60,9 +55,9 @@ create table if not exists "calls"."organization_guests" (
60
55
  * taken out by that process as it reads it, and deleted after a minute when no process did.
61
56
  * - `rings`: a user a call rang, by their id, with the ring's text, until when it rings, and when it stopped: they
62
57
  * joined the call, declined, or the call ended.
63
- * - The guest tables, see `guestsSchemaSql`.
58
+ * The guest tables come in a step of their own, `guestsSchemaSql`.
64
59
  */
65
- const callsSchemaSql = `create schema if not exists "calls";
60
+ const callsTablesSql = `create schema if not exists "calls";
66
61
 
67
62
  create table if not exists "calls"."calls" (
68
63
  "id" uuid primary key,
@@ -114,27 +109,6 @@ create table if not exists "calls"."rings" (
114
109
  primary key ("call_id", "user_id")
115
110
  );
116
111
  create index if not exists "rings_user" on "calls"."rings" ("user_id", "until") where "stopped_at" is null;
117
- create index if not exists "rings_until" on "calls"."rings" ("until") where "stopped_at" is null;
118
-
119
- ${guestsSchemaSql}`;
120
- const hasCallsTables = async (db) => (await sql`select to_regclass('calls.calls') is not null and to_regclass('calls.members') is not null and to_regclass('calls.signals') is not null and to_regclass('calls.rings') is not null as found`.execute(db)).rows[0].found;
121
- const hasGuestTables = async (db) => (await sql`select to_regclass('calls.guest_links') is not null and to_regclass('calls.guests') is not null and to_regclass('calls.organization_guests') is not null
122
- and exists (select from information_schema.columns where table_schema = 'calls' and table_name = 'members' and column_name = 'name') as found`.execute(db)).rows[0].found;
123
- const noticesTable = (events) => `${quoteIdent(changesSchema(events))}."notices"`;
124
- const hasNotices = async (db, events) => (await sql`select to_regclass(${noticesTable(events)}) is not null as found`.execute(db)).rows[0].found;
125
- /**
126
- * The SQL that adds the `calls` schema and its tables, or the guest tables to a calls schema without them, and the changes schema's notices table rings reach open pages
127
- * through, `undefined` when they are there. They are never dropped.
128
- */
129
- const callsMigration = async (db, events) => {
130
- const statements = [...await hasCallsTables(db) ? await hasGuestTables(db) ? [] : [guestsSchemaSql] : [callsSchemaSql], ...await hasNotices(db, events) ? [] : [`create schema if not exists ${quoteIdent(changesSchema(events))}`, noticesTableSql(changesSchema(events))]];
131
- return statements.length === 0 ? void 0 : `${statements.join(";\n\n")};`;
132
- };
133
- /** Refuses to go on while the app has `calls` and the database lacks their tables; the project's migrations add them. */
134
- const checkCalls = async (db, calls, events) => {
135
- if (!calls) return;
136
- if (await hasCallsTables(db) && await hasGuestTables(db) && await hasNotices(db, events)) return;
137
- throw new Error(`The calls schema or the notices table that rings go through is missing. Write them as a migration with \`${migrationCommand}\`, apply it with the project's migrations, then start again.`);
138
- };
112
+ create index if not exists "rings_until" on "calls"."rings" ("until") where "stopped_at" is null;`;
139
113
  //#endregion
140
- export { callsMigration, callsSchemaSql, checkCalls, guestsSchemaSql };
114
+ export { callsTablesSql, guestsSchemaSql };