@protobase/server 0.130.0 → 0.131.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 (43) hide show
  1. package/dist/auth-store.d.ts +2 -2
  2. package/dist/auth-store.js +3 -3
  3. package/dist/better-auth/auth-schema.d.ts +6 -5
  4. package/dist/better-auth/auth-schema.js +12 -12
  5. package/dist/better-auth/names/modules/auth.js +1 -9
  6. package/dist/better-auth/names/modules/index.d.ts +0 -14
  7. package/dist/better-auth/organizations/store.d.ts +1 -1
  8. package/dist/better-auth/store/adoption.js +2 -2
  9. package/dist/better-auth/store/legacy-record.d.ts +6 -4
  10. package/dist/better-auth/store/legacy-record.js +13 -32
  11. package/dist/better-auth/store/offline/archive-revival.d.ts +11 -0
  12. package/dist/better-auth/store/offline/archive-revival.js +25 -0
  13. package/dist/better-auth/store/offline/baseline-store.d.ts +1 -2
  14. package/dist/better-auth/store/offline/baseline-store.js +1 -2
  15. package/dist/better-auth/store/offline/contract-gate.d.ts +18 -0
  16. package/dist/better-auth/store/offline/contract-gate.js +35 -0
  17. package/dist/better-auth/store/offline/module-archive.d.ts +41 -0
  18. package/dist/better-auth/store/offline/module-archive.js +95 -0
  19. package/dist/better-auth/store/offline/module-delete.d.ts +22 -0
  20. package/dist/better-auth/store/offline/module-delete.js +99 -0
  21. package/dist/better-auth/store/offline/module-switches.d.ts +5 -0
  22. package/dist/better-auth/store/offline/module-switches.js +22 -3
  23. package/dist/better-auth/store/offline/name-changes.d.ts +2 -2
  24. package/dist/better-auth/store/offline/name-changes.js +5 -3
  25. package/dist/better-auth/store/offline/offline-steps.d.ts +2 -2
  26. package/dist/better-auth/store/offline/offline-steps.js +6 -5
  27. package/dist/better-auth/store/offline/retired-watch.js +16 -9
  28. package/dist/better-auth/store/offline/store-model.d.ts +19 -1
  29. package/dist/better-auth/store/steps/auth/006-drop-version-record.js +20 -0
  30. package/dist/better-auth/store/steps/index.d.ts +7 -0
  31. package/dist/better-auth/store/steps/index.js +9 -2
  32. package/dist/better-auth/store/steps/legacy-versions.d.ts +1 -1
  33. package/dist/better-auth/store/steps/legacy-versions.js +5 -1
  34. package/dist/better-auth/store/steps/render.d.ts +1 -1
  35. package/dist/better-auth/store/steps/step-lint.d.ts +6 -1
  36. package/dist/better-auth/store/steps/step-lint.js +2 -1
  37. package/dist/better-auth/store/steps/step.d.ts +1 -1
  38. package/dist/better-auth/store/steps/step.js +28 -3
  39. package/dist/better-auth/store/store-sql.d.ts +1 -1
  40. package/dist/internal.d.ts +9 -4
  41. package/dist/internal.js +9 -4
  42. package/dist/package.js +1 -1
  43. package/package.json +7 -7
@@ -1,6 +1,6 @@
1
1
  //#region src/auth-store.d.ts
2
2
  /** The store's tables besides the user table, under their built-in names. */
3
3
  export declare const storeTableNames: string[];
4
- /** The records of the store's steps, `auth_steps`, and of the versions a store recorded before it, under their built-in names. */
5
- export declare const storeRecordNames: string[];
4
+ /** The record of the store's steps, `auth_steps`, under its built-in name. */
5
+ export declare const storeRecordName: string;
6
6
  //#endregion
@@ -3,7 +3,7 @@ import { storeTableNamesOf } from "./better-auth/store/table-names.js";
3
3
  //#region src/auth-store.ts
4
4
  /** The store's tables besides the user table, under their built-in names. */
5
5
  const storeTableNames = storeTableNamesOf(resolveNames({ schema: void 0 }));
6
- /** The records of the store's steps, `auth_steps`, and of the versions a store recorded before it, under their built-in names. */
7
- const storeRecordNames = [resolveNames({ schema: void 0 }).table("auth_steps").name, resolveNames({ schema: void 0 }).table("auth_migrations").name];
6
+ /** The record of the store's steps, `auth_steps`, under its built-in name. */
7
+ const storeRecordName = resolveNames({ schema: void 0 }).table("auth_steps").name;
8
8
  //#endregion
9
- export { storeRecordNames, storeTableNames };
9
+ export { storeRecordName, storeTableNames };
@@ -5,15 +5,16 @@ import "../internal.js";
5
5
  /**
6
6
  * The SQL that brings the admin store to this version of Protobase: the parts of the modules that are on it has not
7
7
  * applied, each followed by its row in `auth_steps`; for a store without that table, the table first. A store that
8
- * recorded versions of the former chain in `auth_migrations` gets its parts recorded from them; one an earlier
9
- * Protobase made without any record is adopted: the versions it matches are recorded as applied (`planAdoption`), the
10
- * others' steps follow. `undefined` when the store is current. The SQL never drops anything.
8
+ * records versions of the former chain instead is refused (`refuseVersionRecord`); one an earlier Protobase made
9
+ * without any record is adopted: the versions it matches are recorded as applied (`planAdoption`), the
10
+ * others' steps follow. `undefined` when the store is current. The SQL drops nothing but the former record of versions
11
+ * (`steps/auth/006-drop-version-record.ts`).
11
12
  */
12
13
  export declare const authSchemaMigration: (auth: AdminAuth) => Promise<string | undefined>;
13
14
  /**
14
15
  * The modules the config turns off whose steps the store has, each at its last step, which a project's first snapshot
15
- * keeps: the store has their tables. Read from `auth_steps`, or from `auth_migrations`, or for a store with neither,
16
- * from the versions its adoption finds it has.
16
+ * keeps: the store has their tables. Read from `auth_steps`, or for a store without any record, from the versions its
17
+ * adoption finds it has; a store that records versions instead is refused.
17
18
  */
18
19
  export declare const keptStoreModules: (auth: AdminAuth) => Promise<KeptModule[]>;
19
20
  //#endregion
@@ -1,13 +1,13 @@
1
1
  import { allModules } from "./names/modules-on.js";
2
2
  import { storeNames } from "./store/store-names.js";
3
3
  import { plainStoreDb } from "./store/store-db.js";
4
+ import { migrationNames, organizationsInput } from "./store/steps/step.js";
4
5
  import { appliedSteps, hadOf } from "./store/step-record.js";
5
6
  import { keptModule } from "./store/offline/store-model.js";
6
7
  import { recordedSteps } from "./store/offline/baseline-store.js";
7
- import { stepRecordSql, stepsSql } from "./store/migration-sql.js";
8
8
  import { renderSteps } from "./store/steps/render.js";
9
- import { appliedVersions, stepRecordMigration, stepsOfVersions } from "./store/legacy-record.js";
10
- import { migrationNames, organizationsInput } from "./store/steps/step.js";
9
+ import { refuseVersionRecord, stepsOfVersions } from "./store/legacy-record.js";
10
+ import { stepRecordSql, stepsSql } from "./store/migration-sql.js";
11
11
  import { adoptionSql, planAdoption, storeHasTables } from "./store/adoption.js";
12
12
  //#region src/better-auth/auth-schema.ts
13
13
  const pendingSql = (auth, names, had) => {
@@ -17,18 +17,18 @@ const pendingSql = (auth, names, had) => {
17
17
  /**
18
18
  * The SQL that brings the admin store to this version of Protobase: the parts of the modules that are on it has not
19
19
  * applied, each followed by its row in `auth_steps`; for a store without that table, the table first. A store that
20
- * recorded versions of the former chain in `auth_migrations` gets its parts recorded from them; one an earlier
21
- * Protobase made without any record is adopted: the versions it matches are recorded as applied (`planAdoption`), the
22
- * others' steps follow. `undefined` when the store is current. The SQL never drops anything.
20
+ * records versions of the former chain instead is refused (`refuseVersionRecord`); one an earlier Protobase made
21
+ * without any record is adopted: the versions it matches are recorded as applied (`planAdoption`), the
22
+ * others' steps follow. `undefined` when the store is current. The SQL drops nothing but the former record of versions
23
+ * (`steps/auth/006-drop-version-record.ts`).
23
24
  */
24
25
  const authSchemaMigration = async (auth) => {
25
26
  const names = storeNames(auth);
26
27
  const db = plainStoreDb(auth);
27
28
  const applied = await appliedSteps(db, names);
28
29
  if (applied !== void 0) return pendingSql(auth, names, hadOf(applied))[0];
30
+ await refuseVersionRecord(db, names);
29
31
  const record = stepRecordSql(names);
30
- const versions = await appliedVersions(db, names);
31
- if (versions !== void 0) return [stepRecordMigration(names), ...pendingSql(auth, names, hadOf(stepsOfVersions(versions)))].join("\n\n");
32
32
  if (!await storeHasTables(db, names)) return [record, ...pendingSql(auth, names, hadOf([]))].join("\n\n");
33
33
  const { adopted, pending } = await planAdoption(db, names);
34
34
  const rest = pending.length === 0 ? [] : pendingSql(auth, names, hadOf(stepsOfVersions(adopted.map(({ migration }) => migration.version))));
@@ -41,15 +41,15 @@ const authSchemaMigration = async (auth) => {
41
41
  const adoptedVersions = async (db, names) => await storeHasTables(db, names) ? (await planAdoption(db, names)).adopted.map(({ migration }) => migration.version) : [];
42
42
  /**
43
43
  * The modules the config turns off whose steps the store has, each at its last step, which a project's first snapshot
44
- * keeps: the store has their tables. Read from `auth_steps`, or from `auth_migrations`, or for a store with neither,
45
- * from the versions its adoption finds it has.
44
+ * keeps: the store has their tables. Read from `auth_steps`, or for a store without any record, from the versions its
45
+ * adoption finds it has; a store that records versions instead is refused.
46
46
  */
47
47
  const keptStoreModules = async (auth) => {
48
48
  const names = storeNames(auth);
49
49
  const db = plainStoreDb(auth);
50
50
  const steps = await appliedSteps(db, names);
51
- const versions = steps === void 0 ? await appliedVersions(db, names) ?? await adoptedVersions(db, names) : void 0;
52
- const applied = steps ?? stepsOfVersions(versions ?? []);
51
+ if (steps === void 0) await refuseVersionRecord(db, names);
52
+ const applied = steps ?? stepsOfVersions(await adoptedVersions(db, names));
53
53
  const recorded = recordedSteps(applied);
54
54
  return allModules.filter((module) => !names.names.modules.includes(module) && recorded[module] !== void 0).map((module) => keptModule(names, module, recorded[module]));
55
55
  };
@@ -1,6 +1,6 @@
1
1
  import { field, own } from "../declaration.js";
2
2
  //#region src/better-auth/names/modules/auth.ts
3
- /** Sign-in itself: users, with their roles and bans, sessions, accounts, codes, the token signing keys and the record of migrations. */
3
+ /** Sign-in itself: users, with their roles and bans, sessions, accounts, codes, the token signing keys and the record of its steps. */
4
4
  const auth = {
5
5
  id: "auth",
6
6
  requires: [],
@@ -109,14 +109,6 @@ const auth = {
109
109
  crv: field("crv")
110
110
  }
111
111
  },
112
- auth_migrations: {
113
- scope: "global",
114
- columns: {
115
- version: field("version"),
116
- name: field("name"),
117
- applied_at: field("appliedAt")
118
- }
119
- },
120
112
  auth_steps: {
121
113
  scope: "global",
122
114
  columns: {
@@ -194,20 +194,6 @@ export declare const builtInModules: readonly [{
194
194
  };
195
195
  };
196
196
  };
197
- readonly auth_migrations: {
198
- readonly scope: "global";
199
- readonly columns: {
200
- readonly version: {
201
- field: "version";
202
- };
203
- readonly name: {
204
- field: "name";
205
- };
206
- readonly applied_at: {
207
- field: "appliedAt";
208
- };
209
- };
210
- };
211
197
  readonly auth_steps: {
212
198
  readonly scope: "global";
213
199
  readonly columns: {
@@ -1,4 +1,4 @@
1
- import "kysely";
1
+ import { RawBuilder } from "kysely";
2
2
  import { createAuthMiddleware } from "better-auth/api";
3
3
  //#region src/better-auth/organizations/store.d.ts
4
4
  export type AuthContext = Parameters<Parameters<typeof createAuthMiddleware>[0]>[0]['context'];
@@ -1,13 +1,13 @@
1
1
  import { allModules } from "../names/modules-on.js";
2
2
  import { resolveNames } from "../names/resolve-names.js";
3
3
  import { ddl } from "./ddl.js";
4
+ import { migrationNames } from "./steps/step.js";
4
5
  import { moduleSteps } from "./steps/index.js";
5
6
  import { recordSteps } from "./step-record.js";
6
- import { statementsSql } from "./migration-sql.js";
7
7
  import { legacyVersions } from "./steps/legacy-versions.js";
8
8
  import { renderSteps } from "./steps/render.js";
9
9
  import { stepsOfVersions } from "./legacy-record.js";
10
- import { migrationNames } from "./steps/step.js";
10
+ import { statementsSql } from "./migration-sql.js";
11
11
  import { sql } from "kysely";
12
12
  //#region src/better-auth/store/adoption.ts
13
13
  const key = ({ table, column }) => `${table}.${column}`;
@@ -1,10 +1,12 @@
1
- import "../names/resolve-names.js";
1
+ import { TableId } from "../names/identifiers.js";
2
2
  import { StoreNames } from "./store-names.js";
3
3
  import { AppliedStep } from "./step-record.js";
4
4
  import { Kysely } from "kysely";
5
5
  //#region src/better-auth/store/legacy-record.d.ts
6
- /** The parts the store applied, from the versions it recorded: every part of each version. */
6
+ /** The parts the store applied, from the versions it has: every part of each version. */
7
7
  export declare const stepsOfVersions: (versions: readonly number[]) => AppliedStep[];
8
- /** The record of the store's steps, made when it is missing and filled from `auth_migrations`, for a store that recorded versions. */
9
- export declare const stepRecordMigration: (names: StoreNames) => string;
8
+ /** The former record of versions, in the store's schema, as the store's names named it. */
9
+ export declare const versionRecordTable: (names: StoreNames) => TableId;
10
+ /** Why a store that records its migrations by version alone, in `table`, is refused, and how to bring it on. */
11
+ export declare const versionRecordRefusal: (table: string) => string;
10
12
  //#endregion
@@ -1,14 +1,11 @@
1
1
  import { allModules } from "../names/modules-on.js";
2
- import { ddl } from "./ddl.js";
2
+ import { versionRecord } from "./steps/auth/006-drop-version-record.js";
3
+ import { migrationNames } from "./steps/step.js";
3
4
  import { moduleSteps } from "./steps/index.js";
4
- import { stepRecordTable } from "./step-record.js";
5
- import { guardedBlock, stepRecordSql } from "./migration-sql.js";
6
5
  import { latestStoreVersion } from "./steps/legacy-versions.js";
7
6
  import { partVersion } from "./steps/render.js";
8
7
  import { sql } from "kysely";
9
8
  //#region src/better-auth/store/legacy-record.ts
10
- /** The table, in the store's schema, as the store's names resolve `auth_migrations`. */
11
- const legacyRecordTable = ({ names }) => names.table("auth_migrations");
12
9
  /** Every part of every step with the version of the former chain that made it, as that chain made them, every module on. */
13
10
  const legacyParts = () => allModules.flatMap((module) => moduleSteps[module].flatMap((step) => [module, ...allModules.filter((target) => step.adds?.[target])].map((target) => ({
14
11
  module,
@@ -16,41 +13,25 @@ const legacyParts = () => allModules.flatMap((module) => moduleSteps[module].fla
16
13
  target,
17
14
  version: partVersion(module, step, target)
18
15
  }))));
19
- /** The parts the store applied, from the versions it recorded: every part of each version. */
16
+ /** The parts the store applied, from the versions it has: every part of each version. */
20
17
  const stepsOfVersions = (versions) => {
21
18
  const newer = versions.filter((version) => version > latestStoreVersion);
22
- if (newer.length > 0) throw new Error(`The auth store records version ${newer.join(", ")} in auth_migrations, which this version of Protobase does not ship; upgrade Protobase`);
19
+ if (newer.length > 0) throw new Error(`The auth store has version ${newer.join(", ")}, which this version of Protobase does not ship; upgrade Protobase`);
23
20
  return legacyParts().filter((part) => versions.includes(part.version)).map(({ module, step, target }) => ({
24
21
  module,
25
22
  step,
26
23
  target
27
24
  }));
28
25
  };
29
- /** The versions the store recorded, in order; `undefined` when it has no `auth_migrations`. */
30
- const appliedVersions = async (db, names) => {
31
- const table = legacyRecordTable(names);
26
+ /** The former record of versions, in the store's schema, as the store's names named it. */
27
+ const versionRecordTable = (names) => migrationNames(names).former(versionRecord);
28
+ /** Why a store that records its migrations by version alone, in `table`, is refused, and how to bring it on. */
29
+ const versionRecordRefusal = (table) => `The auth store records its migrations by version in ${table}, without auth_steps, as a Protobase before 0.130 left it: bring the project to Protobase 0.130 first, write and apply its migration with that version's \`protobase migration\` and \`protobase migrate\`, then run this again`;
30
+ /** Refuses a store without `auth_steps` that has the former record of versions. */
31
+ const refuseVersionRecord = async (db, names) => {
32
+ const table = versionRecordTable(names);
32
33
  const [found] = (await sql`select to_regclass(${String(table)}) is not null as found`.execute(db)).rows;
33
- if (!found?.found) return;
34
- const { version } = table.columns;
35
- return (await sql`select ${version} as version from ${table} order by ${version}`.execute(db)).rows.map((row) => row.version);
34
+ if (found?.found) throw new Error(versionRecordRefusal(table.name));
36
35
  };
37
- /**
38
- * The statement that fills `auth_steps` from `auth_migrations`, once that table is there: every part of each version
39
- * it records, at the time it recorded it. A part recorded already is left as it is.
40
- */
41
- const fillFromLegacySql = (names) => {
42
- const legacy = legacyRecordTable(names);
43
- const steps = stepRecordTable(names);
44
- const { module, step, target, applied_at } = steps.columns;
45
- const parts = legacyParts().map((part) => ddl`(${sql.lit(part.module)}, ${sql.lit(part.step)}, ${sql.lit(part.target)}, ${sql.lit(part.version)})`);
46
- const fill = ddl`insert into ${steps} (${module}, ${step}, ${target}, ${applied_at})
47
- select part.module, part.step, part.target, legacy.${legacy.columns.applied_at}
48
- from (values ${sql.join(parts, sql`, `)}) as part (module, step, target, version)
49
- join ${legacy} legacy on legacy.${legacy.columns.version} = part.version
50
- on conflict do nothing`;
51
- return `-- The steps the store recorded by version in ${legacy.name}, recorded by step.\n${guardedBlock(ddl`to_regclass(${sql.lit(String(legacy))}) is not null`, [fill])}`;
52
- };
53
- /** The record of the store's steps, made when it is missing and filled from `auth_migrations`, for a store that recorded versions. */
54
- const stepRecordMigration = (names) => [stepRecordSql(names), fillFromLegacySql(names)].join("\n\n");
55
36
  //#endregion
56
- export { appliedVersions, fillFromLegacySql, legacyParts, legacyRecordTable, stepRecordMigration, stepsOfVersions };
37
+ export { legacyParts, refuseVersionRecord, stepsOfVersions, versionRecordRefusal, versionRecordTable };
@@ -0,0 +1,11 @@
1
+ import { ModuleId } from "../../names/modules/index.js";
2
+ import { StoreNames } from "../store-names.js";
3
+ //#region src/better-auth/store/offline/archive-revival.d.ts
4
+ /**
5
+ * The statements that give back to each column `module` left in use on the tables of `existing` the foreign key to its
6
+ * table, once that table is made again, where the column has none: not checked against the rows there, whose values
7
+ * may name a row the archive holds, such as a token's organization, which then no longer works. As SQL text after a
8
+ * comment; `undefined` when it leaves none.
9
+ */
10
+ export declare const restoredKeysSql: (names: StoreNames, module: ModuleId, existing: readonly ModuleId[]) => string | undefined;
11
+ //#endregion
@@ -0,0 +1,25 @@
1
+ import { generatedName } from "../../names/identifier-length.js";
2
+ import { ddl } from "../ddl.js";
3
+ import { statementsSql } from "../migration-sql.js";
4
+ import { stillWrittenColumns } from "./module-switches.js";
5
+ import { sql } from "kysely";
6
+ //#region src/better-auth/store/offline/archive-revival.ts
7
+ /**
8
+ * The statements that give back to each column `module` left in use on the tables of `existing` the foreign key to its
9
+ * table, once that table is made again, where the column has none: not checked against the rows there, whose values
10
+ * may name a row the archive holds, such as a token's organization, which then no longer works. As SQL text after a
11
+ * comment; `undefined` when it leaves none.
12
+ */
13
+ const restoredKeysSql = (names, module, existing) => {
14
+ const statements = stillWrittenColumns(names, module, existing).map(({ table, column, references }) => ddl`do $restore$
15
+ begin
16
+ if not exists (select from pg_constraint where conrelid = ${sql.lit(String(table))}::regclass and contype = 'f' and confrelid = ${sql.lit(String(references))}::regclass) then
17
+ alter table ${table} add constraint ${sql.id(generatedName(`${table.name}_${column.name}_fkey`))} foreign key (${column}) references ${references} (id) on delete cascade not valid;
18
+ end if;
19
+ end
20
+ $restore$`);
21
+ if (statements.length === 0) return;
22
+ return `-- ${module} on: the columns it left in use while off point at its tables again where an archive took their foreign key; a value the archive holds no longer names a row.\n${statementsSql(statements)}`;
23
+ };
24
+ //#endregion
25
+ export { restoredKeysSql };
@@ -14,14 +14,13 @@ export type LiveStore = {
14
14
  };
15
15
  /**
16
16
  * What the store is: each module's last step, the modules off that have tables, whether organizations were ever on,
17
- * the relations Protobase did not make, and whether it has `auth_steps`.
17
+ * and the relations Protobase did not make.
18
18
  */
19
19
  export type BaselineStore = {
20
20
  lastSteps: LastSteps;
21
21
  kept: KeptModule[];
22
22
  organizationsEverOn: boolean;
23
23
  external: string[];
24
- stepRecord: boolean;
25
24
  };
26
25
  /**
27
26
  * The store at `live` under the config's `names`: each module that is on at the step the record holds, every module
@@ -57,8 +57,7 @@ const baselineStore = (names, live) => {
57
57
  lastSteps,
58
58
  kept,
59
59
  organizationsEverOn,
60
- external: externalUser ? [`${prefix}${user.name}`] : [],
61
- stepRecord: has("auth_steps")
60
+ external: externalUser ? [`${prefix}${user.name}`] : []
62
61
  };
63
62
  };
64
63
  //#endregion
@@ -0,0 +1,18 @@
1
+ import { RawBuilder } from "kysely";
2
+ //#region src/better-auth/store/offline/contract-gate.d.ts
3
+ /** The line that marks the statement under it as taking what the migration `id` stopped older code from using. */
4
+ export declare const contractMark: (id: string) => string;
5
+ /** `statements` as SQL text, each under the mark naming the migration `id`. */
6
+ export declare const markedSql: (id: string, statements: readonly RawBuilder<unknown>[]) => string;
7
+ /** A migration a sign-off waits on: its id and file name, as `migrations.history` records them. */
8
+ export type SignedOff = {
9
+ id: string;
10
+ name: string;
11
+ };
12
+ /**
13
+ * The block that refuses, unless `migrations.history` has `after`'s row, `hours` have passed since it was applied,
14
+ * and, when `followed`, a row applied after it: what `step` says it does waits for the update to have served that long,
15
+ * and for the next one to have followed it.
16
+ */
17
+ export declare const signOffGate: (after: SignedOff, hours: number, step: string, followed: boolean) => RawBuilder<unknown>;
18
+ //#endregion
@@ -0,0 +1,35 @@
1
+ import { ddl, ddlText } from "../ddl.js";
2
+ import { recordTable } from "../../../migration-record/record-table.js";
3
+ import { sql } from "kysely";
4
+ //#region src/better-auth/store/offline/contract-gate.ts
5
+ /** The line that marks the statement under it as taking what the migration `id` stopped older code from using. */
6
+ const contractMark = (id) => `-- protobase:contract ${id}`;
7
+ /** `statements` as SQL text, each under the mark naming the migration `id`. */
8
+ const markedSql = (id, statements) => statements.map((statement) => `${contractMark(id)}\n${ddlText(statement)};`).join("\n\n");
9
+ /**
10
+ * The block that refuses, unless `migrations.history` has `after`'s row, `hours` have passed since it was applied,
11
+ * and, when `followed`, a row applied after it: what `step` says it does waits for the update to have served that long,
12
+ * and for the next one to have followed it.
13
+ */
14
+ const signOffGate = (after, hours, step, followed) => {
15
+ const waits = `${step} waits until ${after.name}`;
16
+ const next = ddl`
17
+ if not exists (select from ${sql.raw(recordTable)} where applied_at > applied) then
18
+ raise exception '%', ${sql.lit(`${waits} is followed by a migration applied after it, as the next update applies one`)};
19
+ end if;`;
20
+ return ddl`do $gate$
21
+ declare
22
+ applied timestamptz;
23
+ begin
24
+ select applied_at into applied from ${sql.raw(recordTable)} where id = ${sql.lit(after.id)};
25
+ if applied is null then
26
+ raise exception '%', ${sql.lit(`${waits} is applied`)};
27
+ end if;${followed ? next : sql``}
28
+ if now() - applied < ${sql.lit(`${hours} hours`)}::interval then
29
+ raise exception '%', format(${sql.lit(`${waits} was applied ${hours} hours ago; it was applied at %s`)}, applied);
30
+ end if;
31
+ end
32
+ $gate$`;
33
+ };
34
+ //#endregion
35
+ export { contractMark, markedSql, signOffGate };
@@ -0,0 +1,41 @@
1
+ import { ModuleId } from "../../names/modules/index.js";
2
+ import { DeferredOff, KeptModule, RetiredName } from "./store-model.js";
3
+ //#region src/better-auth/store/offline/module-archive.d.ts
4
+ /** A module archived: where its tables went, the columns it retired, the choice made, and the migration that archived it. */
5
+ export type ArchivedModule = {
6
+ module: ModuleId;
7
+ step: number;
8
+ /** The store's schema, which the retired columns' tables are in; `null` when the search path decides. */
9
+ store: string | null;
10
+ /** The schema its tables moved to (`archiveSchema`), and their names there. */
11
+ schema: string;
12
+ tables: string[];
13
+ columns: RetiredName[];
14
+ choice: DeferredOff['choice'];
15
+ /** The id of the migration that archived it, which the one that deletes it names. */
16
+ file: string;
17
+ };
18
+ /** The schema the migration numbered `number` archives tables to. */
19
+ export declare const archiveSchema: (number: number) => string;
20
+ /** The name a retired column takes once archived; one past 63 bytes is shortened as Postgres would not. */
21
+ export declare const archivedColumn: (column: string) => string;
22
+ /**
23
+ * The statements that archive `kept` from the store's schema `store` to `schema`: the watch's schema, table and
24
+ * function where missing, the foreign keys between its tables and the others dropped, its tables moved, each watched
25
+ * as a whole, and each column it retired renamed to its archive and watched under it, counted as the column.
26
+ */
27
+ export declare const archiveStatements: (store: string | null, schema: string, kept: KeptModule & {
28
+ off: DeferredOff;
29
+ }) => import("kysely").RawBuilder<unknown>[];
30
+ /**
31
+ * The statements that take from every role that owns or holds a privilege on a table of `schema`, one of its columns
32
+ * or the schema itself, and from everyone, the use of its tables and sequences, then of the schema, the role applying
33
+ * the migration included, each with the grants made from them: written once the file has moved every table there,
34
+ * which needs the schema. The schema goes last, as revoking on its tables looks it up.
35
+ */
36
+ export declare const revokeStatements: (schema: string) => import("kysely").RawBuilder<unknown>[];
37
+ /** The snapshot's record of `kept` once archived to `schema` by the migration `file`. */
38
+ export declare const archivedModule: (store: string | null, schema: string, kept: KeptModule & {
39
+ off: DeferredOff;
40
+ }, file: string) => ArchivedModule;
41
+ //#endregion
@@ -0,0 +1,95 @@
1
+ import { generatedName } from "../../names/identifier-length.js";
2
+ import { columnId, tableId } from "../../names/identifiers.js";
3
+ import { ddl } from "../ddl.js";
4
+ import { retiredSchema, watchBaseStatements, watchTrigger, watchTriggerName } from "./retired-watch.js";
5
+ import { sql } from "kysely";
6
+ //#region src/better-auth/store/offline/module-archive.ts
7
+ /** The schema the migration numbered `number` archives tables to. */
8
+ const archiveSchema = (number) => `protobase_archive_${number}`;
9
+ /** The name a retired column takes once archived; one past 63 bytes is shortened as Postgres would not. */
10
+ const archivedColumn = (column) => generatedName(`${column}_archive`);
11
+ /** The trigger that counts the writes of an archived table. */
12
+ const tableWatchTrigger = "retired_writes";
13
+ const qualified = (store, table) => tableId(store ?? void 0, table);
14
+ /** `tables` as an array of `regclass`, for a block to compare with the catalogue. */
15
+ const regclasses = (tables) => ddl`array[${sql.join(tables.map((table) => sql.lit(String(table))))}]::regclass[]`;
16
+ const dropCrossingKeys = (tables) => ddl`do $archive$
17
+ declare
18
+ found record;
19
+ begin
20
+ for found in select conrelid::regclass as relation, conname from pg_constraint where contype = 'f' and (conrelid = any(${tables})) <> (confrelid = any(${tables})) loop
21
+ execute format('alter table %s drop constraint %I', found.relation, found.conname);
22
+ end loop;
23
+ end
24
+ $archive$`;
25
+ /**
26
+ * The statements that archive `kept` from the store's schema `store` to `schema`: the watch's schema, table and
27
+ * function where missing, the foreign keys between its tables and the others dropped, its tables moved, each watched
28
+ * as a whole, and each column it retired renamed to its archive and watched under it, counted as the column.
29
+ */
30
+ const archiveStatements = (store, schema, kept) => {
31
+ const tables = Object.values(kept.tables).map(({ name }) => name);
32
+ return [
33
+ ...watchBaseStatements(),
34
+ ddl`create schema if not exists ${schema}`,
35
+ dropCrossingKeys(regclasses(tables.map((table) => qualified(store, table)))),
36
+ ...tables.map((table) => ddl`alter table ${qualified(store, table)} set schema ${schema}`),
37
+ ...tables.map((table) => ddl`create trigger ${tableWatchTrigger} after insert or update or delete on ${tableId(schema, table)} for each row execute function ${retiredSchema}.${"count_write"}(${sql.lit("*")})`),
38
+ ...kept.off.columns.flatMap(({ table, column }) => {
39
+ const at = qualified(store, table);
40
+ const archived = columnId(at, archivedColumn(column));
41
+ return [
42
+ ddl`drop trigger if exists ${watchTriggerName(column)} on ${at}`,
43
+ ddl`alter table ${at} rename column ${column} to ${archived}`,
44
+ watchTrigger(at, columnId(at, column), archived)
45
+ ];
46
+ })
47
+ ];
48
+ };
49
+ /**
50
+ * The statements that take from every role that owns or holds a privilege on a table of `schema`, one of its columns
51
+ * or the schema itself, and from everyone, the use of its tables and sequences, then of the schema, the role applying
52
+ * the migration included, each with the grants made from them: written once the file has moved every table there,
53
+ * which needs the schema. The schema goes last, as revoking on its tables looks it up.
54
+ */
55
+ const revokeStatements = (schema) => {
56
+ const at = sql.lit(schema);
57
+ return [ddl`do $revoke$
58
+ declare
59
+ holders text[];
60
+ holder text;
61
+ begin
62
+ select array_agg(distinct found.role::regrole::text) into holders from (
63
+ select relowner as role from pg_class where relnamespace = ${at}::regnamespace
64
+ union all
65
+ select privilege.grantee from pg_class, aclexplode(relacl) as privilege where relnamespace = ${at}::regnamespace and privilege.grantee <> 0
66
+ union all
67
+ select privilege.grantee from pg_class join pg_attribute on attrelid = pg_class.oid, aclexplode(attacl) as privilege where relnamespace = ${at}::regnamespace and privilege.grantee <> 0
68
+ union all
69
+ select privilege.grantee from pg_namespace, aclexplode(nspacl) as privilege where pg_namespace.oid = ${at}::regnamespace and privilege.grantee <> 0
70
+ ) as found;
71
+ foreach holder in array coalesce(holders, '{}') loop
72
+ execute format('revoke all on all tables in schema %I from %s cascade', ${at}, holder);
73
+ execute format('revoke all on all sequences in schema %I from %s cascade', ${at}, holder);
74
+ end loop;
75
+ execute format('revoke all on all tables in schema %I from public cascade', ${at});
76
+ execute format('revoke all on all sequences in schema %I from public cascade', ${at});
77
+ foreach holder in array coalesce(holders, '{}') loop
78
+ execute format('revoke all on schema %I from %s cascade', ${at}, holder);
79
+ end loop;
80
+ end
81
+ $revoke$`, ddl`revoke all on schema ${schema} from public, current_user cascade`];
82
+ };
83
+ /** The snapshot's record of `kept` once archived to `schema` by the migration `file`. */
84
+ const archivedModule = (store, schema, kept, file) => ({
85
+ module: kept.module,
86
+ step: kept.step,
87
+ store,
88
+ schema,
89
+ tables: Object.values(kept.tables).map(({ name }) => name),
90
+ columns: kept.off.columns,
91
+ choice: kept.off.choice,
92
+ file
93
+ });
94
+ //#endregion
95
+ export { archiveSchema, archiveStatements, archivedColumn, archivedModule, regclasses, revokeStatements, tableWatchTrigger };
@@ -0,0 +1,22 @@
1
+ import { TableId } from "../../names/identifiers.js";
2
+ import { ModuleId } from "../../names/modules/index.js";
3
+ import { StoreModel } from "./store-model.js";
4
+ import { ArchivedModule } from "./module-archive.js";
5
+ //#region src/better-auth/store/offline/module-delete.d.ts
6
+ /** The table that records the store's steps, with its module and target columns, by their names. */
7
+ export type StepRecord = {
8
+ table: TableId;
9
+ module: string;
10
+ target: string;
11
+ };
12
+ /** The step record of the store `model` describes; `undefined` for one without it. */
13
+ export declare const stepRecordOf: (model: StoreModel) => StepRecord | undefined;
14
+ /** `forgetSteps` as SQL text. */
15
+ export declare const forgetStepsSql: (steps: StepRecord, id: ModuleId) => string;
16
+ /**
17
+ * The statements that delete `entry` for good once nothing wrote it for `hours` (`unwrittenCheck`): the use of its
18
+ * schema taken back for the role applying it, its tables dropped, and the schema once nothing else is in it, then each
19
+ * column archive with its watch; and with `steps`, while the module is still off, its rows in `auth_steps`.
20
+ */
21
+ export declare const deleteStatements: (entry: ArchivedModule, hours: number, steps: StepRecord | undefined) => import("kysely").RawBuilder<unknown>[];
22
+ //#endregion