@protobase/server 0.129.1 → 0.130.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assistant/query-runner/grants-sql.js +32 -0
- package/dist/assistant/query-runner/query-input.js +33 -0
- package/dist/assistant/query-runner/query-module.js +44 -0
- package/dist/assistant/query-runner/query-runner.d.ts +8 -11
- package/dist/assistant/query-runner/query-runner.js +15 -57
- package/dist/assistant/query-runner/read-query.js +54 -0
- package/dist/assistant/query-runner/runner-sql.js +4 -20
- package/dist/assistant/query-runner/steps/001-role.js +19 -0
- package/dist/auth-store.d.ts +2 -2
- package/dist/auth-store.js +3 -3
- package/dist/better-auth/auth-schema.d.ts +13 -4
- package/dist/better-auth/auth-schema.js +40 -32
- package/dist/better-auth/auth-settings.d.ts +59 -11
- package/dist/better-auth/auth-settings.js +57 -13
- package/dist/better-auth/auth-tables.d.ts +6 -3
- package/dist/better-auth/auth-tables.js +12 -7
- package/dist/better-auth/authenticator.js +10 -2
- package/dist/better-auth/create-auth.d.ts +62 -7
- package/dist/better-auth/create-auth.js +55 -14
- package/dist/better-auth/device-sign-in-check.js +13 -0
- package/dist/better-auth/names/declaration.d.ts +18 -5
- package/dist/better-auth/names/declaration.js +3 -1
- package/dist/better-auth/names/modules/auth.js +9 -0
- package/dist/better-auth/names/modules/index.d.ts +34 -4
- package/dist/better-auth/names/modules/organizations.js +10 -3
- package/dist/better-auth/names/modules/personal-access-tokens.js +6 -3
- package/dist/better-auth/names/modules-on.js +25 -2
- package/dist/better-auth/names/resolve-names.d.ts +9 -1
- package/dist/better-auth/names/resolve-names.js +15 -9
- package/dist/better-auth/organizations/accept-invitation.js +5 -4
- package/dist/better-auth/organizations/add-every-user.js +3 -2
- package/dist/better-auth/organizations/host-scope.d.ts +10 -0
- package/dist/better-auth/organizations/host-scope.js +15 -0
- package/dist/better-auth/organizations/host.d.ts +12 -6
- package/dist/better-auth/organizations/host.js +99 -61
- package/dist/better-auth/organizations/kept-organizations.d.ts +21 -0
- package/dist/better-auth/organizations/kept-organizations.js +62 -0
- package/dist/better-auth/organizations/member-endpoints.js +4 -3
- package/dist/better-auth/organizations/options.d.ts +15 -0
- package/dist/better-auth/organizations/options.js +19 -1
- package/dist/better-auth/organizations/people-endpoint.js +3 -2
- package/dist/better-auth/organizations/pinned-membership.js +81 -0
- package/dist/better-auth/organizations/pinned-sessions.js +46 -0
- package/dist/better-auth/organizations/session-organization.js +3 -2
- package/dist/better-auth/organizations/store.d.ts +1 -1
- package/dist/better-auth/organizations/store.js +14 -9
- package/dist/better-auth/personal-access-tokens/pinned-tokens.js +23 -0
- package/dist/better-auth/personal-access-tokens/token-plugin.js +75 -54
- package/dist/better-auth/personal-access-tokens/token-sessions.js +6 -3
- package/dist/better-auth/personal-access-tokens/token-store.js +15 -11
- package/dist/better-auth/store/adoption.js +25 -10
- package/dist/better-auth/store/drift.js +5 -4
- package/dist/better-auth/store/legacy-record.d.ts +10 -0
- package/dist/better-auth/store/legacy-record.js +56 -0
- package/dist/better-auth/store/migration-sql.js +31 -26
- package/dist/better-auth/store/offline/archive-revival.d.ts +11 -0
- package/dist/better-auth/store/offline/archive-revival.js +25 -0
- package/dist/better-auth/store/offline/baseline-store.d.ts +11 -7
- package/dist/better-auth/store/offline/baseline-store.js +15 -12
- package/dist/better-auth/store/offline/contract-gate.d.ts +18 -0
- package/dist/better-auth/store/offline/contract-gate.js +35 -0
- package/dist/better-auth/store/offline/module-archive.d.ts +41 -0
- package/dist/better-auth/store/offline/module-archive.js +95 -0
- package/dist/better-auth/store/offline/module-delete.d.ts +22 -0
- package/dist/better-auth/store/offline/module-delete.js +99 -0
- package/dist/better-auth/store/offline/module-switches.d.ts +32 -0
- package/dist/better-auth/store/offline/module-switches.js +113 -0
- package/dist/better-auth/store/offline/name-changes.d.ts +4 -1
- package/dist/better-auth/store/offline/name-changes.js +5 -2
- package/dist/better-auth/store/offline/offline-steps.d.ts +21 -7
- package/dist/better-auth/store/offline/offline-steps.js +29 -20
- package/dist/better-auth/store/offline/retired-watch.d.ts +5 -0
- package/dist/better-auth/store/offline/retired-watch.js +43 -0
- package/dist/better-auth/store/offline/settings-names.d.ts +3 -2
- package/dist/better-auth/store/offline/settings-names.js +10 -3
- package/dist/better-auth/store/offline/store-model.d.ts +27 -1
- package/dist/better-auth/store/offline/store-model.js +22 -5
- package/dist/better-auth/store/resources-outside.js +1 -1
- package/dist/better-auth/store/step-record.d.ts +13 -0
- package/dist/better-auth/store/step-record.js +59 -0
- package/dist/better-auth/store/steps/index.js +6 -1
- package/dist/better-auth/store/steps/legacy-versions.d.ts +7 -0
- package/dist/better-auth/store/steps/legacy-versions.js +4 -0
- package/dist/better-auth/store/steps/organizations/003-default-organization.js +113 -0
- package/dist/better-auth/store/steps/render.d.ts +3 -0
- package/dist/better-auth/store/steps/render.js +48 -25
- package/dist/better-auth/store/steps/step-lint.d.ts +14 -0
- package/dist/better-auth/store/steps/step-lint.js +31 -10
- package/dist/better-auth/store/steps/step.d.ts +18 -0
- package/dist/better-auth/store/steps/step.js +7 -1
- package/dist/better-auth/store/store-db.d.ts +6 -0
- package/dist/better-auth/store/store-db.js +11 -5
- package/dist/better-auth/store/store-names.d.ts +4 -0
- package/dist/better-auth/store/store-sql.d.ts +1 -1
- package/dist/better-auth/token-standing.js +12 -7
- package/dist/better-auth/users.d.ts +7 -2
- package/dist/better-auth/users.js +25 -3
- package/dist/built-in-resources.js +1 -1
- package/dist/calls/calls-module.js +42 -0
- package/dist/calls/calls-sql.js +4 -30
- package/dist/changes/capture-names.d.ts +3 -1
- package/dist/changes/capture-names.js +5 -2
- package/dist/changes/capture-schema-sql.d.ts +10 -0
- package/dist/changes/capture-schema-sql.js +21 -0
- package/dist/changes/capture-schema.d.ts +0 -18
- package/dist/changes/capture-schema.js +1 -74
- package/dist/changes/capture-sql.js +30 -24
- package/dist/changes/changes-input.js +36 -0
- package/dist/changes/changes-module.js +44 -0
- package/dist/changes/read-capture.js +67 -0
- package/dist/changes/steps/001-outbox.js +23 -0
- package/dist/channels/sends-module.js +37 -0
- package/dist/channels/sends-schema-sql.js +5 -5
- package/dist/comments/comments-module.js +30 -0
- package/dist/comments/comments-sql.js +1 -22
- package/dist/computed/buckets-sql.d.ts +5 -1
- package/dist/computed/buckets-sql.js +39 -46
- package/dist/computed/{buckets-schema.d.ts → buckets-targets.d.ts} +2 -3
- package/dist/computed/buckets-targets.js +50 -0
- package/dist/computed/computed-input.js +65 -0
- package/dist/computed/computed-module.js +102 -0
- package/dist/computed/formula-sql.js +14 -1
- package/dist/computed/read-computed.js +100 -0
- package/dist/computed/rollup-sql.js +13 -10
- package/dist/config-exports.d.ts +2 -2
- package/dist/create-admin.js +21 -5
- package/dist/derived/derived-module.js +89 -0
- package/dist/derived/derived-sql.js +1 -47
- package/dist/functions/define-function.d.ts +10 -4
- package/dist/functions/routes.js +5 -3
- package/dist/functions/supabase-routes.js +7 -5
- package/dist/history/history-module.js +34 -0
- package/dist/index.d.ts +19 -28
- package/dist/index.js +11 -21
- package/dist/internal.d.ts +30 -10
- package/dist/internal.js +26 -8
- package/dist/jobs/functions-sql.js +7 -11
- package/dist/jobs/job-data.js +36 -0
- package/dist/jobs/job-types.d.ts +6 -3
- package/dist/jobs/jobs-module.d.ts +5 -0
- package/dist/jobs/jobs-module.js +84 -0
- package/dist/jobs/run-job.d.ts +1 -1
- package/dist/jobs/run-job.js +7 -5
- package/dist/jobs/runtime.d.ts +9 -4
- package/dist/jobs/runtime.js +11 -6
- package/dist/jobs/schema.d.ts +0 -11
- package/dist/jobs/schema.js +1 -59
- package/dist/jobs/steps/001-pg-boss-45.js +483 -0
- package/dist/live/notices-module.js +30 -0
- package/dist/live/notices-sql.js +2 -1
- package/dist/mail/feedback/feedback-schema.js +3 -30
- package/dist/mail/feedback/mail-feedback-module.js +37 -0
- package/dist/mail/unsubscribe/unsubscribe-schema.js +3 -21
- package/dist/mail/unsubscribe/unsubscribes-module.js +31 -0
- package/dist/migration-record/check-record.d.ts +9 -7
- package/dist/migration-record/check-record.js +12 -11
- package/dist/migration-record/module-needs.js +30 -0
- package/dist/migration-record/read-record.js +27 -15
- package/dist/migration-record/record-model.d.ts +7 -2
- package/dist/migration-record/record-model.js +14 -6
- package/dist/migration-record/startup-decision.js +18 -7
- package/dist/migration-sql/additive-statements.d.ts +4 -0
- package/dist/migration-sql/additive-statements.js +105 -0
- package/dist/notifications/devices-module.js +61 -0
- package/dist/notifications/history-module.js +50 -0
- package/dist/notifications/notifications-targets.js +23 -0
- package/dist/notifications/read-table.js +16 -0
- package/dist/notifications/schema-sql.js +1 -22
- package/dist/notifications/schema.js +1 -101
- package/dist/notifications/table-names.js +40 -0
- package/dist/organization-scope/app-scope.js +38 -0
- package/dist/organization-scope/auth-request-organization.js +71 -0
- package/dist/organization-scope/organization-tables.js +20 -0
- package/dist/organization-scope/sign-in-organization.js +21 -0
- package/dist/package.js +1 -1
- package/dist/personal-mail/shared-sender-store.js +4 -2
- package/dist/realtime/relay/realtime-relay-module.js +37 -0
- package/dist/relation-found.js +6 -0
- package/dist/relay/read-relay.js +85 -0
- package/dist/relay/realtime-members-sql.js +51 -28
- package/dist/relay/relay-module.js +53 -0
- package/dist/relay/relay-targets.js +28 -0
- package/dist/relay/session-end.js +1 -3
- package/dist/relay/sessions-sql.js +4 -27
- package/dist/rest/table-routes.js +9 -2
- package/dist/schema-modules/feature-schemas-sql.d.ts +40 -0
- package/dist/schema-modules/feature-schemas-sql.js +51 -0
- package/dist/schema-modules/module-difference.d.ts +31 -0
- package/dist/schema-modules/module-difference.js +98 -0
- package/dist/schema-modules/modules-sql.js +13 -0
- package/dist/schema-modules/modules.d.ts +37 -0
- package/dist/schema-modules/modules.js +56 -0
- package/dist/schema-modules/needed-modules.d.ts +41 -0
- package/dist/schema-modules/needed-modules.js +61 -0
- package/dist/schema-modules/resource-difference.js +83 -0
- package/dist/schema-modules/schema-module.d.ts +112 -0
- package/dist/schema-modules/schema-module.js +8 -0
- package/dist/status/status-module.js +63 -0
- package/dist/status/status-targets.js +21 -0
- package/dist/types.d.ts +6 -1
- package/dist/user-tables/reloading-admin.d.ts +1 -0
- package/dist/user-tables/reloading-admin.js +1 -0
- package/dist/user-tables/schema-sql.js +1 -14
- package/dist/user-tables/schema.js +4 -27
- package/dist/user-tables/user-tables-module.js +38 -0
- package/dist/webhooks/table/delivery-log-module.js +36 -0
- package/dist/webhooks/table/owner-roles.js +3 -2
- package/dist/webhooks/table/schema-sql.js +27 -26
- package/dist/webhooks/table/webhooks-schema-module.js +63 -0
- package/dist/webhooks/table/webhooks-targets.js +26 -0
- package/dist/webhooks/webhooks.js +1 -1
- package/dist/workflows/custom-steps/custom-steps-module.js +51 -0
- package/dist/workflows/custom-steps/custom-steps-sql.js +10 -7
- package/dist/workflows/custom-steps/runners-sql.js +10 -7
- package/dist/workflows/read-catalogue.js +23 -0
- package/dist/workflows/schema-sql.js +12 -9
- package/dist/workflows/status-sql.js +12 -6
- package/dist/workflows/storage/storage-module.js +39 -0
- package/dist/workflows/storage/storage-sql.js +8 -5
- package/dist/workflows/workflows-schema-module.js +49 -0
- package/dist/workflows/workflows-tables-sql.js +32 -0
- package/dist/workflows/workflows-targets.js +16 -0
- package/package.json +6 -6
- package/dist/assistant/query-runner/runner-plan.js +0 -30
- package/dist/better-auth/store/migrations-table.js +0 -27
- package/dist/better-auth/store/modules-off.js +0 -17
- package/dist/calls/calls-sql.d.ts +0 -11
- package/dist/changes/capture-plan.js +0 -79
- package/dist/channels/sends-schema.d.ts +0 -7
- package/dist/channels/sends-schema.js +0 -18
- package/dist/comments/comments-sql.d.ts +0 -14
- package/dist/computed/buckets-plan.d.ts +0 -2
- package/dist/computed/buckets-plan.js +0 -88
- package/dist/computed/buckets-schema.js +0 -39
- package/dist/computed/computed-plan.js +0 -81
- package/dist/computed/computed-schema.d.ts +0 -16
- package/dist/computed/computed-schema.js +0 -63
- package/dist/derived/derived-sql.d.ts +0 -12
- package/dist/mail/feedback/feedback-schema.d.ts +0 -7
- package/dist/mail/unsubscribe/unsubscribe-schema.d.ts +0 -10
- package/dist/notifications/schema.d.ts +0 -14
- package/dist/realtime/relay/relay-schema.d.ts +0 -7
- package/dist/realtime/relay/relay-schema.js +0 -20
- package/dist/relay/realtime-members-schema.js +0 -67
- package/dist/relay/relay-schema.d.ts +0 -14
- package/dist/relay/relay-schema.js +0 -28
- package/dist/status/schema.d.ts +0 -12
- package/dist/status/schema.js +0 -33
- package/dist/user-tables/schema.d.ts +0 -11
- package/dist/webhooks/table/schema.d.ts +0 -16
- package/dist/webhooks/table/schema.js +0 -56
- package/dist/workflows/schema.d.ts +0 -13
- package/dist/workflows/schema.js +0 -88
|
@@ -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
|
-
|
|
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
|
-
|
|
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).
|
|
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 { RawBuilder } from "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,6 +1,11 @@
|
|
|
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 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;
|
|
4
9
|
/**
|
|
5
10
|
* The `ddl` parts of the store's names. `externalUser`: the user table is a relation Protobase did not make, which its
|
|
6
11
|
* statements leave alone, as under `users.keyTable` or as a project's snapshot records it.
|
|
@@ -9,9 +14,10 @@ const migrationNames = ({ names, users, uuidIds }, externalUser = users.keyTable
|
|
|
9
14
|
table: names.table,
|
|
10
15
|
user: users.keyTable ? tableId(users.keyTable.schema, users.keyTable.table) : names.table("user"),
|
|
11
16
|
userDdl: (statements) => externalUser ? [] : statements,
|
|
17
|
+
externalUser,
|
|
12
18
|
metadata: users.metadata,
|
|
13
19
|
id: sql.raw(uuidIds ? "uuid default pg_catalog.gen_random_uuid()" : "text"),
|
|
14
20
|
idRef: sql.raw(uuidIds ? "uuid" : "text")
|
|
15
21
|
});
|
|
16
22
|
//#endregion
|
|
17
|
-
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
|
|
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
|
-
*
|
|
16
|
-
*
|
|
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
|
|
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
|
-
/**
|
|
57
|
-
|
|
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
|
-
/**
|
|
78
|
-
|
|
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
|
|
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-
|
|
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 };
|
package/dist/calls/calls-sql.js
CHANGED
|
@@ -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
|
-
*
|
|
58
|
+
* The guest tables come in a step of their own, `guestsSchemaSql`.
|
|
64
59
|
*/
|
|
65
|
-
const
|
|
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 {
|
|
114
|
+
export { callsTablesSql, guestsSchemaSql };
|
|
@@ -2,7 +2,7 @@ import { EventsOptions } from "./events-options.js";
|
|
|
2
2
|
import { ResourceModel } from "@protobase/schema";
|
|
3
3
|
//#region src/changes/capture-names.d.ts
|
|
4
4
|
/**
|
|
5
|
-
* What the change capture of `models` names in the database, as
|
|
5
|
+
* What the change capture of `models` names in the database, as the change capture module writes it: the changes
|
|
6
6
|
* schema, which holds `capture()` and the outbox, history and notices tables, and each captured resource's triggers.
|
|
7
7
|
*/
|
|
8
8
|
export declare const captureNames: (models: readonly ResourceModel[], options?: EventsOptions) => {
|
|
@@ -12,4 +12,6 @@ export declare const captureNames: (models: readonly ResourceModel[], options?:
|
|
|
12
12
|
triggers: string[];
|
|
13
13
|
}[];
|
|
14
14
|
};
|
|
15
|
+
/** What `protobase doctor` reports while the changes of the `missing` resources are not captured. */
|
|
16
|
+
export declare const uncapturedMessage: (missing: readonly string[]) => string;
|
|
15
17
|
//#endregion
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { capturedBy, resourceTriggers } from "./capture-sql.js";
|
|
2
2
|
import { changesSchema } from "./events-options.js";
|
|
3
|
+
import { migrationCommand } from "./capture-schema.js";
|
|
3
4
|
//#region src/changes/capture-names.ts
|
|
4
5
|
/**
|
|
5
|
-
* What the change capture of `models` names in the database, as
|
|
6
|
+
* What the change capture of `models` names in the database, as the change capture module writes it: the changes
|
|
6
7
|
* schema, which holds `capture()` and the outbox, history and notices tables, and each captured resource's triggers.
|
|
7
8
|
*/
|
|
8
9
|
const captureNames = (models, options) => ({
|
|
@@ -12,5 +13,7 @@ const captureNames = (models, options) => ({
|
|
|
12
13
|
triggers: resourceTriggers(model).map((trigger) => trigger.name)
|
|
13
14
|
}))
|
|
14
15
|
});
|
|
16
|
+
/** What `protobase doctor` reports while the changes of the `missing` resources are not captured. */
|
|
17
|
+
const uncapturedMessage = (missing) => `The changes of ${missing.join(", ")} are not captured as their events, history or live updates need: their triggers, the history or notices table or the changes schema are missing or out of date. Write the change as a migration with \`${migrationCommand}\`, apply it with the project's migrations, then start again.`;
|
|
15
18
|
//#endregion
|
|
16
|
-
export { captureNames };
|
|
19
|
+
export { captureNames, uncapturedMessage };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { EventsOptions } from "./events-options.js";
|
|
2
|
+
import { ResourceModel } from "@protobase/schema";
|
|
3
|
+
//#region src/changes/capture-schema-sql.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* The change capture `models` need, as a migration writes it on a database without it: the change capture module, and
|
|
6
|
+
* the history and notices tables when a resource has history or live updates. The jobs schema it enqueues into is not
|
|
7
|
+
* part of it (`jobsSchemaSql`), nor are the rollups and formulas of `models` (`computedSchemaSql`).
|
|
8
|
+
*/
|
|
9
|
+
export declare const captureSchemaSql: (models: readonly ResourceModel[], events?: EventsOptions) => string;
|
|
10
|
+
//#endregion
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { moduleDifference } from "../schema-modules/module-difference.js";
|
|
2
|
+
import { schemaModules, targetIds } from "../schema-modules/modules.js";
|
|
3
|
+
import { neededModules } from "../schema-modules/needed-modules.js";
|
|
4
|
+
//#region src/changes/capture-schema-sql.ts
|
|
5
|
+
/**
|
|
6
|
+
* The change capture `models` need, as a migration writes it on a database without it: the change capture module, and
|
|
7
|
+
* the history and notices tables when a resource has history or live updates. The jobs schema it enqueues into is not
|
|
8
|
+
* part of it (`jobsSchemaSql`), nor are the rollups and formulas of `models` (`computedSchemaSql`).
|
|
9
|
+
*/
|
|
10
|
+
const captureSchemaSql = (models, events) => {
|
|
11
|
+
const targets = neededModules({
|
|
12
|
+
models,
|
|
13
|
+
views: [],
|
|
14
|
+
jobs: [],
|
|
15
|
+
signIn: false,
|
|
16
|
+
...events && { events }
|
|
17
|
+
});
|
|
18
|
+
return targetIds(targets).filter((id) => id !== "jobs" && id !== "computed").map((id) => moduleDifference(schemaModules[id], targets[id], void 0).sql).join("\n\n");
|
|
19
|
+
};
|
|
20
|
+
//#endregion
|
|
21
|
+
export { captureSchemaSql };
|
|
@@ -1,22 +1,4 @@
|
|
|
1
|
-
import { EventsOptions } from "./events-options.js";
|
|
2
|
-
import { ResourceModel } from "@protobase/schema";
|
|
3
|
-
import { Db } from "@protobase/query";
|
|
4
1
|
//#region src/changes/capture-schema.d.ts
|
|
5
2
|
/** The command that writes what the config needs as a migration file of the project. */
|
|
6
3
|
export declare const migrationCommand = "protobase migration";
|
|
7
|
-
/**
|
|
8
|
-
* The SQL that brings the database to the capture the resources' events, history and live updates need: the schema
|
|
9
|
-
* with the outbox and `capture()`, the history and notices tables, and a trigger pair per resource with any of them, recreated when its fields changed;
|
|
10
|
-
* triggers of resources without any of them any more are dropped. `undefined` when the database is current. Tables are
|
|
11
|
-
* never dropped. The tables of the `pending` resources are created by a migration written before this one.
|
|
12
|
-
*/
|
|
13
|
-
export declare const changesMigration: (db: Db, models: readonly ResourceModel[], options?: EventsOptions, pending?: readonly string[]) => Promise<string | undefined>;
|
|
14
|
-
/**
|
|
15
|
-
* Refuses to go on while a resource's events, history or live updates would not be captured as declared: a missing or
|
|
16
|
-
* out-of-date schema, history or notices table, or trigger. The server never changes the schema itself: the project's migrations do, before the
|
|
17
|
-
* new version serves.
|
|
18
|
-
*/
|
|
19
|
-
export declare const checkChanges: (db: Db, models: readonly ResourceModel[], options?: EventsOptions) => Promise<void>;
|
|
20
|
-
/** What the server refuses to start with while the changes of the `missing` resources are not captured. */
|
|
21
|
-
export declare const uncapturedMessage: (missing: readonly string[]) => string;
|
|
22
4
|
//#endregion
|
|
@@ -1,78 +1,5 @@
|
|
|
1
|
-
import { capturedBy, quoteIdent, tableSql } from "./capture-sql.js";
|
|
2
|
-
import { historyIndexes } from "../history/history-sql.js";
|
|
3
|
-
import { capturePlan, planSql, uncaptured } from "./capture-plan.js";
|
|
4
|
-
import { changesSchema } from "./events-options.js";
|
|
5
|
-
import { hasIndexes } from "../has-indexes.js";
|
|
6
|
-
import { sql } from "kysely";
|
|
7
1
|
//#region src/changes/capture-schema.ts
|
|
8
2
|
/** The command that writes what the config needs as a migration file of the project. */
|
|
9
3
|
const migrationCommand = "protobase migration";
|
|
10
|
-
const triggerArgs = (hex) => {
|
|
11
|
-
const bytes = new Uint8Array((hex.match(/../g) ?? []).map((pair) => parseInt(pair, 16)));
|
|
12
|
-
return new TextDecoder().decode(bytes).split("\0").slice(0, -1);
|
|
13
|
-
};
|
|
14
|
-
const rowsOf = async (db, query) => (await query.execute(db)).rows;
|
|
15
|
-
const readCaptureState = async (db, schema, models) => {
|
|
16
|
-
const exists = async (table) => (await rowsOf(db, sql`select to_regclass(${`${quoteIdent(schema)}.${quoteIdent(table)}`}) is not null as found`))[0]?.found ?? false;
|
|
17
|
-
const [capture] = await rowsOf(db, sql`select p.oid::text as oid, p.prosrc as source, p.prosecdef as definer from pg_proc p join pg_namespace n on n.oid = p.pronamespace where n.nspname = ${schema} and p.proname = 'capture' and p.pronargs = 0`);
|
|
18
|
-
const tables = {};
|
|
19
|
-
const views = [];
|
|
20
|
-
for (const model of models) {
|
|
21
|
-
const [found] = await rowsOf(db, sql`select c.oid::text as oid, c.relkind in ('v', 'm') as view from (select to_regclass(${tableSql(model)}) as oid) r left join pg_class c on c.oid = r.oid`);
|
|
22
|
-
tables[model.name] = found?.oid ?? null;
|
|
23
|
-
if (found?.view) views.push(model.name);
|
|
24
|
-
}
|
|
25
|
-
const oids = Object.values(tables).filter((oid) => oid !== null);
|
|
26
|
-
const triggers = await rowsOf(db, sql`select t.tgrelid::text as "table", format('%I.%I', ns.nspname, c.relname) as "tableSql", t.tgname as name,
|
|
27
|
-
t.tgfoid::text as "function", t.tgtype::int as type, encode(t.tgargs, 'hex') as args
|
|
28
|
-
from pg_trigger t join pg_class c on c.oid = t.tgrelid join pg_namespace ns on ns.oid = c.relnamespace
|
|
29
|
-
where not t.tgisinternal and (t.tgfoid::text = ${capture?.oid ?? ""} or t.tgrelid::text = any(${oids}::text[]))`);
|
|
30
|
-
const outbox = await exists("outbox");
|
|
31
|
-
const history = await exists("history");
|
|
32
|
-
return {
|
|
33
|
-
outbox,
|
|
34
|
-
history,
|
|
35
|
-
historyIndexed: history && await hasIndexes(db, schema, "history", historyIndexes.map(([name]) => name)),
|
|
36
|
-
notices: await exists("notices"),
|
|
37
|
-
...capture && { capture },
|
|
38
|
-
triggers: triggers.map((trigger) => ({
|
|
39
|
-
...trigger,
|
|
40
|
-
args: triggerArgs(trigger.args)
|
|
41
|
-
})),
|
|
42
|
-
tables,
|
|
43
|
-
views
|
|
44
|
-
};
|
|
45
|
-
};
|
|
46
|
-
const plan = async (db, models, options, pending = []) => {
|
|
47
|
-
const schema = changesSchema(options);
|
|
48
|
-
return {
|
|
49
|
-
schema,
|
|
50
|
-
plan: capturePlan(schema, models, await readCaptureState(db, schema, models.filter(capturedBy(models))), pending)
|
|
51
|
-
};
|
|
52
|
-
};
|
|
53
|
-
/**
|
|
54
|
-
* The SQL that brings the database to the capture the resources' events, history and live updates need: the schema
|
|
55
|
-
* with the outbox and `capture()`, the history and notices tables, and a trigger pair per resource with any of them, recreated when its fields changed;
|
|
56
|
-
* triggers of resources without any of them any more are dropped. `undefined` when the database is current. Tables are
|
|
57
|
-
* never dropped. The tables of the `pending` resources are created by a migration written before this one.
|
|
58
|
-
*/
|
|
59
|
-
const changesMigration = async (db, models, options, pending = []) => {
|
|
60
|
-
const { schema, plan: found } = await plan(db, models, options, pending);
|
|
61
|
-
return planSql(schema, found);
|
|
62
|
-
};
|
|
63
|
-
/**
|
|
64
|
-
* Refuses to go on while a resource's events, history or live updates would not be captured as declared: a missing or
|
|
65
|
-
* out-of-date schema, history or notices table, or trigger. The server never changes the schema itself: the project's migrations do, before the
|
|
66
|
-
* new version serves.
|
|
67
|
-
*/
|
|
68
|
-
const checkChanges = async (db, models, options) => {
|
|
69
|
-
if (!models.some(capturedBy(models))) return;
|
|
70
|
-
const { plan: found } = await plan(db, models, options);
|
|
71
|
-
const missing = uncaptured(found, models);
|
|
72
|
-
if (missing.length === 0) return;
|
|
73
|
-
throw new Error(uncapturedMessage(missing));
|
|
74
|
-
};
|
|
75
|
-
/** What the server refuses to start with while the changes of the `missing` resources are not captured. */
|
|
76
|
-
const uncapturedMessage = (missing) => `The changes of ${missing.join(", ")} are not captured as their events, history or live updates need: their triggers, the history or notices table or the changes schema are missing or out of date. Write the change as a migration with \`${migrationCommand}\`, apply it with the project's migrations, then start again.`;
|
|
77
4
|
//#endregion
|
|
78
|
-
export {
|
|
5
|
+
export { migrationCommand };
|