@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
@@ -0,0 +1,99 @@
1
+ import { columnId, tableId } from "../../names/identifiers.js";
2
+ import { ddl } from "../ddl.js";
3
+ import { statementsSql } from "../migration-sql.js";
4
+ import { retiredSchema, watchTriggerName } from "./retired-watch.js";
5
+ import { stillWrittenTargets } from "./module-switches.js";
6
+ import { archivedColumn, tableWatchTrigger } from "./module-archive.js";
7
+ import { sql } from "kysely";
8
+ //#region src/better-auth/store/offline/module-delete.ts
9
+ const watched = (entry) => [...entry.tables.map((table) => ({
10
+ table: tableId(entry.schema, table),
11
+ schema: sql.lit(entry.schema),
12
+ name: table,
13
+ column: "*",
14
+ trigger: tableWatchTrigger
15
+ })), ...entry.columns.map(({ table, column }) => ({
16
+ table: tableId(entry.store ?? void 0, table),
17
+ schema: entry.store === null ? sql.raw("current_schema()") : sql.lit(entry.store),
18
+ name: table,
19
+ column,
20
+ trigger: watchTriggerName(archivedColumn(column))
21
+ }))];
22
+ /** The message a delete refuses with while the watch counts a write of `entry` within the last `hours`. */
23
+ const stillWritten = (entry, hours) => `${entry.module} was written within the last ${hours} hours, which retired.writes counts: %s. Find what still writes it, and delete it once nothing has for that long`;
24
+ /**
25
+ * The block that refuses unless every table and column archive of `entry` is watched, by a trigger that fires for the
26
+ * app's writes (enabled, or always), and the watch counts no write of any within the last `hours`: a write names each
27
+ * one written and its count.
28
+ */
29
+ const unwrittenCheck = (entry, hours) => {
30
+ const parts = watched(entry);
31
+ const triggers = parts.map(({ table, trigger }) => ddl`exists (select from pg_trigger where tgrelid = ${sql.lit(String(table))}::regclass and tgname = ${sql.lit(trigger)} and tgenabled in ('O', 'A'))`);
32
+ const keys = parts.map(({ schema, name, column }) => ddl`(format('%I.%I', ${schema}, ${sql.lit(name)}), ${sql.lit(column)})`);
33
+ return ddl`do $unwritten$
34
+ declare
35
+ found text;
36
+ begin
37
+ if to_regclass(${sql.lit(`${retiredSchema}.writes`)}) is null or not (${sql.join(triggers, sql` and `)}) then
38
+ raise exception '%', ${sql.lit(`${entry.module} has a table or column archive that retired.writes does not watch, so whether something still writes it is unknown: it is not deleted`)};
39
+ end if;
40
+ select string_agg(counted.table_name || '.' || counted.column_name || ' ' || counted.writes, ', ' order by counted.table_name, counted.column_name) into found
41
+ from (
42
+ select table_name, column_name, sum(writes) as writes from ${sql.raw(retiredSchema)}.writes
43
+ where hour >= date_trunc('hour', now() - ${sql.lit(`${hours} hours`)}::interval) and (table_name, column_name) in (${sql.join(keys)})
44
+ group by table_name, column_name
45
+ ) as counted;
46
+ if found is not null then
47
+ raise exception '%', format(${sql.lit(stillWritten(entry, hours))}, found);
48
+ end if;
49
+ end
50
+ $unwritten$`;
51
+ };
52
+ /** The step record of the store `model` describes; `undefined` for one without it. */
53
+ const stepRecordOf = (model) => {
54
+ const table = model.modules.auth?.tables.auth_steps;
55
+ if (!table) return;
56
+ return {
57
+ table: tableId(model.schema ?? void 0, table.name),
58
+ module: table.columns.module,
59
+ target: table.columns.target
60
+ };
61
+ };
62
+ /**
63
+ * The statement that forgets the steps of the module `id` and those applied to its tables, so it starts again from its
64
+ * first, but its parts on the tables of the modules whose columns it leaves in use while off (`stillWrittenTargets`),
65
+ * which stay as they are and are not applied again.
66
+ */
67
+ const forgetSteps = ({ table, module, target }, id) => {
68
+ const kept = stillWrittenTargets(id);
69
+ const own = ddl`${columnId(table, module)} = ${sql.lit(id)}`;
70
+ const parts = kept.length === 0 ? own : ddl`(${own} and ${columnId(table, target)} not in (${sql.join(kept.map((other) => sql.lit(other)))}))`;
71
+ return ddl`delete from ${table} where ${parts} or ${columnId(table, target)} = ${sql.lit(id)}`;
72
+ };
73
+ /** `forgetSteps` as SQL text. */
74
+ const forgetStepsSql = (steps, id) => statementsSql([forgetSteps(steps, id)]);
75
+ /**
76
+ * The statements that delete `entry` for good once nothing wrote it for `hours` (`unwrittenCheck`): the use of its
77
+ * schema taken back for the role applying it, its tables dropped, and the schema once nothing else is in it, then each
78
+ * column archive with its watch; and with `steps`, while the module is still off, its rows in `auth_steps`.
79
+ */
80
+ const deleteStatements = (entry, hours, steps) => [
81
+ ddl`grant usage on schema ${entry.schema} to current_user`,
82
+ unwrittenCheck(entry, hours),
83
+ ddl`drop table ${sql.join(entry.tables.map((table) => tableId(entry.schema, table)))}`,
84
+ ddl`do $empty$
85
+ begin
86
+ if not exists (select from pg_class where relnamespace = ${sql.lit(entry.schema)}::regnamespace) then
87
+ execute format('drop schema %I', ${sql.lit(entry.schema)});
88
+ end if;
89
+ end
90
+ $empty$`,
91
+ ...entry.columns.flatMap(({ table, column }) => {
92
+ const at = tableId(entry.store ?? void 0, table);
93
+ const archived = archivedColumn(column);
94
+ return [ddl`drop trigger if exists ${watchTriggerName(archived)} on ${at}`, ddl`alter table ${at} drop column ${columnId(at, archived)}`];
95
+ }),
96
+ ...steps ? [forgetSteps(steps, entry.module)] : []
97
+ ];
98
+ //#endregion
99
+ export { deleteStatements, forgetSteps, forgetStepsSql, stepRecordOf, stillWritten, unwrittenCheck };
@@ -8,6 +8,11 @@ export declare const offChoices: readonly ["keep", "archive", "delete"];
8
8
  export type OffChoice = (typeof offChoices)[number];
9
9
  /** The setting `protobase migrate --force` sets in its transactions, which lets a module whose kept tables hold rows on again. */
10
10
  export declare const forceSetting = "protobase.force";
11
+ /** The columns `module` retires (`retiredColumns`) by the names of their tables and themselves, as a snapshot records them. */
12
+ export declare const retiredNames: (names: StoreNames, module: ModuleId, existing: readonly ModuleId[], externalUser?: boolean) => {
13
+ table: string;
14
+ column: string;
15
+ }[];
11
16
  /** The tables of `module` its steps up to `step` made, under the store's names. */
12
17
  export declare const keptTables: (names: StoreNames, module: ModuleId, step: number) => ResolvedTable<string>[];
13
18
  /** The message that refuses turning `module` on again while its kept tables hold rows: `found` lists each table with its count. */
@@ -19,7 +19,21 @@ const everyTable = (names) => resolveNames({
19
19
  ...names.names.input,
20
20
  modules: allModules
21
21
  }).tables;
22
- const writtenWhileOff = { organizations: { personal_access_token: ["organization_id"] } };
22
+ const writtenWhileOff = { organizations: { personal_access_token: { organization_id: "organization" } } };
23
+ /** The modules on whose tables `module` adds columns that stay written while it is off (`writtenWhileOff`), which its archive leaves as they are. */
24
+ const stillWrittenTargets = (module) => Object.keys(writtenWhileOff[module] ?? {}).map((table) => builtInModules.find((declaration) => table in declaration.tables).id);
25
+ /**
26
+ * The columns `module` adds that stay written while it is off, on the tables of `existing`, the modules the store has
27
+ * before the migration, each with the table its foreign key points at, under the store's names.
28
+ */
29
+ const stillWrittenColumns = (names, module, existing) => {
30
+ const every = everyTable(names);
31
+ return Object.entries(writtenWhileOff[module] ?? {}).filter(([table]) => existing.includes(every[table].module)).flatMap(([table, columns]) => Object.entries(columns).map(([column, references]) => ({
32
+ table: every[table],
33
+ column: every[table].columns[column],
34
+ references: every[references]
35
+ })));
36
+ };
23
37
  /**
24
38
  * The columns `module` adds to the tables of the modules that stay on, which retire once it is off: each table one of
25
39
  * `existing`, whose tables the store has before the migration; a column the server still writes while it is off stays
@@ -32,7 +46,7 @@ const retiredColumns = (names, module, existing, externalUser = names.users.keyT
32
46
  return Object.entries(declaration.columns ?? {}).filter(([table]) => {
33
47
  const kept = names.names.tables[table];
34
48
  return kept !== void 0 && existing.includes(kept.module) && !(table === "user" && externalUser);
35
- }).flatMap(([table, columns]) => Object.keys(columns).filter((column) => !writtenWhileOff[module]?.[table]?.includes(column)).map((column) => ({
49
+ }).flatMap(([table, columns]) => Object.keys(columns).filter((column) => !(column in (writtenWhileOff[module]?.[table] ?? {}))).map((column) => ({
36
50
  table: every[table],
37
51
  column: every[table].columns[column]
38
52
  })));
@@ -46,6 +60,11 @@ const keepStatements = (names, module, existing, externalUser) => {
46
60
  const columns = retiredColumns(names, module, existing, externalUser);
47
61
  return [...columns.map(({ table, column }) => ddl`alter table ${table} alter column ${column} drop not null`), ...watchStatements(columns)];
48
62
  };
63
+ /** The columns `module` retires (`retiredColumns`) by the names of their tables and themselves, as a snapshot records them. */
64
+ const retiredNames = (names, module, existing, externalUser) => retiredColumns(names, module, existing, externalUser).map(({ table, column }) => ({
65
+ table: table.name,
66
+ column: column.name
67
+ }));
49
68
  /** The tables of `module` its steps up to `step` made, under the store's names. */
50
69
  const keptTables = (names, module, step) => {
51
70
  const every = everyTable(names);
@@ -91,4 +110,4 @@ const unwatchSql = (names, module, existing, externalUser) => {
91
110
  return `-- ${module} on again: the columns it adds are in use again, with the values they kept, and no longer watched.\n${statementsSql(statements)}`;
92
111
  };
93
112
  //#endregion
94
- export { forceSetting, keepSql, keepStatements, keptTables, offChoices, retiredColumns, revivalCheckSql, revivalRefusal, unwatchSql };
113
+ export { forceSetting, keepSql, keepStatements, keptTables, offChoices, retiredColumns, retiredNames, revivalCheckSql, revivalRefusal, stillWrittenColumns, stillWrittenTargets, unwatchSql };
@@ -1,8 +1,8 @@
1
1
  import { StoreModel } from "./store-model.js";
2
2
  //#region src/better-auth/store/offline/name-changes.d.ts
3
3
  /**
4
- * How `after` changes what `before`, from `source`, has, one line each, the last steps and the tables' scopes aside:
5
- * a scope is Protobase's to declare, not a name the store has; none when it only adds.
4
+ * How `after` changes what `before`, from `source`, has, one line each, the last steps, the tables' scopes and the
5
+ * tables a step drops aside: a scope is Protobase's to declare, not a name the store has; none when it only adds.
6
6
  */
7
7
  export declare const nameChanges: (before: StoreModel, after: StoreModel, source?: string) => string[];
8
8
  //#endregion
@@ -1,3 +1,4 @@
1
+ import { droppedTables } from "../steps/index.js";
1
2
  //#region src/better-auth/store/offline/name-changes.ts
2
3
  const changes = (before, after, at, source) => {
3
4
  if (after === void 0) return [`${at} is gone`];
@@ -5,13 +6,14 @@ const changes = (before, after, at, source) => {
5
6
  return Object.entries(before).flatMap(([key, value]) => changes(value, after[key], at === "" ? key : `${at}.${key}`, source));
6
7
  };
7
8
  /**
8
- * How `after` changes what `before`, from `source`, has, one line each, the last steps and the tables' scopes aside:
9
- * a scope is Protobase's to declare, not a name the store has; none when it only adds.
9
+ * How `after` changes what `before`, from `source`, has, one line each, the last steps, the tables' scopes and the
10
+ * tables a step drops aside: a scope is Protobase's to declare, not a name the store has; none when it only adds.
10
11
  */
11
12
  const nameChanges = (before, after, source = "the snapshot") => {
13
+ const kept = (tables) => Object.entries(tables).filter(([internal]) => !droppedTables.includes(internal));
12
14
  const withoutSteps = (model) => ({
13
15
  ...model,
14
- modules: Object.fromEntries(Object.entries(model.modules).map(([module, entry]) => [module, Object.fromEntries(Object.entries(entry.tables).map(([internal, { scope: _, ...table }]) => [internal, table]))]))
16
+ modules: Object.fromEntries(Object.entries(model.modules).map(([module, entry]) => [module, Object.fromEntries(kept(entry.tables).map(([internal, { scope: _, ...table }]) => [internal, table]))]))
15
17
  });
16
18
  return changes(withoutSteps(before), withoutSteps(after), "", source);
17
19
  };
@@ -5,7 +5,7 @@ import { LastSteps } from "./store-model.js";
5
5
  //#region src/better-auth/store/offline/offline-steps.d.ts
6
6
  /**
7
7
  * The store as a project's snapshot has it: each module's last step, those kept while off included; the modules that
8
- * are on; and whether it has `auth_steps`, which a store a version before it made lacks.
8
+ * are on; and whether it has `auth_steps`, which a store a Protobase before 0.130 made lacks.
9
9
  */
10
10
  export type SnapshotStore = {
11
11
  lastSteps: LastSteps;
@@ -15,7 +15,7 @@ export type SnapshotStore = {
15
15
  /**
16
16
  * The parts of the modules that are on that the snapshot's store lacks, each followed by its row in `auth_steps`, each
17
17
  * run only while that table lacks it, so a database that has it already skips it; for a store the snapshot has none of
18
- * (`store` undefined), that table first, and for one without it, that table, filled from `auth_migrations`. `checks`:
18
+ * (`store` undefined), that table first; one without it, which records versions instead, is refused. `checks`:
19
19
  * the checks of the parts on tables the store has already, which refuse when its rows break what a step assumes;
20
20
  * `after`, what the parts leave for the migration's `.after.sql`, when they leave anything. `undefined` when the
21
21
  * snapshot's store has every part. `externalUser`: the snapshot records the user table as a relation Protobase did
@@ -1,8 +1,8 @@
1
+ import { migrationNames } from "../steps/step.js";
1
2
  import { moduleSteps } from "../steps/index.js";
2
- import { afterStepsSql, guardedStepsSql, statementsSql, stepRecordSql } from "../migration-sql.js";
3
3
  import { renderSteps } from "../steps/render.js";
4
- import { stepRecordMigration } from "../legacy-record.js";
5
- import { migrationNames } from "../steps/step.js";
4
+ import { versionRecordRefusal, versionRecordTable } from "../legacy-record.js";
5
+ import { afterStepsSql, guardedStepsSql, statementsSql, stepRecordSql } from "../migration-sql.js";
6
6
  //#region src/better-auth/store/offline/offline-steps.ts
7
7
  const refuseNewer = (lastSteps) => {
8
8
  for (const [module, last] of Object.entries(lastSteps)) {
@@ -19,7 +19,7 @@ const snapshotHad = ({ lastSteps, on }) => (module, step, target) => step <= (la
19
19
  /**
20
20
  * The parts of the modules that are on that the snapshot's store lacks, each followed by its row in `auth_steps`, each
21
21
  * run only while that table lacks it, so a database that has it already skips it; for a store the snapshot has none of
22
- * (`store` undefined), that table first, and for one without it, that table, filled from `auth_migrations`. `checks`:
22
+ * (`store` undefined), that table first; one without it, which records versions instead, is refused. `checks`:
23
23
  * the checks of the parts on tables the store has already, which refuse when its rows break what a step assumes;
24
24
  * `after`, what the parts leave for the migration's `.after.sql`, when they leave anything. `undefined` when the
25
25
  * snapshot's store has every part. `externalUser`: the snapshot records the user table as a relation Protobase did
@@ -28,10 +28,11 @@ const snapshotHad = ({ lastSteps, on }) => (module, step, target) => step <= (la
28
28
  */
29
29
  const offlineStepsMigration = (names, store, organizations, externalUser = false) => {
30
30
  if (store) refuseNewer(store.lastSteps);
31
+ if (store && !store.stepRecord) throw new Error(versionRecordRefusal(versionRecordTable(names).name));
31
32
  const had = store ? snapshotHad(store) : () => false;
32
33
  const migration = migrationNames(names, externalUser || names.users.keyTable !== void 0);
33
34
  const rendered = renderSteps(migration, names.names.modules, had, organizations);
34
- const record = !store ? [stepRecordSql(names)] : store.stepRecord ? [] : [stepRecordMigration(names)];
35
+ const record = store ? [] : [stepRecordSql(names)];
35
36
  if (rendered.length === 0 && record.length === 0) return;
36
37
  const steps = rendered.length === 0 ? [] : [guardedStepsSql(names, rendered)];
37
38
  const onTablesThere = ({ module, on = module }) => had(on, moduleSteps[on][0].step, on);
@@ -4,7 +4,8 @@ import { sql } from "kysely";
4
4
  //#region src/better-auth/store/offline/retired-watch.ts
5
5
  /** The schema of the watch, made by the first migration that retires a column. */
6
6
  const retiredSchema = "retired";
7
- const triggerName = (column) => generatedName(`${column.name}_retired_writes`);
7
+ /** The trigger on a column's table that counts its writes; a name past 63 bytes is shortened as Postgres would not. */
8
+ const watchTriggerName = (column) => generatedName(`${column}_retired_writes`);
8
9
  const watchTable = ddl`create table if not exists ${retiredSchema}.${"writes"} (
9
10
  table_name text not null,
10
11
  column_name text not null,
@@ -20,17 +21,23 @@ begin
20
21
  return null;
21
22
  end
22
23
  $retired$`;
24
+ /** The statements that make the watch's schema, table and function, each only when missing. */
25
+ const watchBaseStatements = () => [
26
+ ddl`create schema if not exists ${retiredSchema}`,
27
+ watchTable,
28
+ countFunction
29
+ ];
30
+ /**
31
+ * The trigger that counts the writes of `column` of `table` that set it, under `name`: the column itself, or one that
32
+ * holds its values since, such as its archive, which then counts as `column`.
33
+ */
34
+ const watchTrigger = (table, column, name = column) => ddl`create trigger ${watchTriggerName(name.name)} after insert or update of ${name} on ${table} for each row when (new.${name} is not null) execute function ${retiredSchema}.${"count_write"}(${sql.lit(column.name)})`;
23
35
  /** The statements that start the watch on `columns`: its schema, table and function, then a trigger on each column. */
24
36
  const watchStatements = (columns) => {
25
37
  if (columns.length === 0) return [];
26
- return [
27
- ddl`create schema if not exists ${retiredSchema}`,
28
- watchTable,
29
- countFunction,
30
- ...columns.map(({ table, column }) => ddl`create trigger ${triggerName(column)} after insert or update of ${column} on ${table} for each row when (new.${column} is not null) execute function ${retiredSchema}.${"count_write"}(${sql.lit(column.name)})`)
31
- ];
38
+ return [...watchBaseStatements(), ...columns.map(({ table, column }) => watchTrigger(table, column))];
32
39
  };
33
40
  /** The statements that stop the watch on `columns`, once their module is on again; a column retired before the watch existed has none. */
34
- const unwatchStatements = (columns) => columns.map(({ table, column }) => ddl`drop trigger if exists ${triggerName(column)} on ${table}`);
41
+ const unwatchStatements = (columns) => columns.map(({ table, column }) => ddl`drop trigger if exists ${watchTriggerName(column.name)} on ${table}`);
35
42
  //#endregion
36
- export { retiredSchema, unwatchStatements, watchStatements };
43
+ export { retiredSchema, unwatchStatements, watchBaseStatements, watchStatements, watchTrigger, watchTriggerName };
@@ -33,11 +33,29 @@ export declare const latestSteps: (modules: readonly ModuleId[]) => LastSteps;
33
33
  export declare const storeModel: ({ schema, names, users, uuidIds }: StoreNames, lastSteps: LastSteps) => StoreModel;
34
34
  /** Every name the store has in the database: its schema, each table, `table.column` and index, sorted. */
35
35
  export declare const storeNamesList: (model: StoreModel) => string[];
36
- /** A module turned off whose tables and rows the store keeps: the last step it had, and its tables' names then. */
36
+ /** A column a module turned off retired from a table still on, by their names. */
37
+ export type RetiredName = {
38
+ table: string;
39
+ column: string;
40
+ };
41
+ /**
42
+ * What awaits the sign-off of a module turned off with `--off archive` or `--off delete`: the choice, the id of the
43
+ * migration that turned it off, and the columns it retired then.
44
+ */
45
+ export type DeferredOff = {
46
+ choice: 'archive' | 'delete';
47
+ file: string;
48
+ columns: RetiredName[];
49
+ };
50
+ /**
51
+ * A module turned off whose tables and rows the store keeps: the last step it had, and its tables' names then; `off`
52
+ * once it awaits the sign-off that archives it.
53
+ */
37
54
  export type KeptModule = {
38
55
  module: ModuleId;
39
56
  step: number;
40
57
  tables: Record<string, ModelTable>;
58
+ off?: DeferredOff;
41
59
  };
42
60
  /** `module` kept at `step`, its tables named as `names` would name them with it on. */
43
61
  export declare const keptModule: ({ schema, names, users, uuidIds }: StoreNames, module: ModuleId, step: number) => KeptModule;
@@ -0,0 +1,20 @@
1
+ import { ddl } from "../../ddl.js";
2
+ //#region src/better-auth/store/steps/auth/006-drop-version-record.ts
3
+ /** The record of versions a store kept before `auth_steps`, by its built-in name, which nothing reads any more. */
4
+ const versionRecord = "auth_migrations";
5
+ /**
6
+ * The drop of the record of versions, once `auth_steps` holds every step it recorded: the migrations of Protobase 0.130
7
+ * filled `auth_steps` from it, so the store keeps one record of its steps. The one step that drops a table, which the
8
+ * step lint allows it alone (`drops`).
9
+ */
10
+ const dropVersionRecord = {
11
+ step: 6,
12
+ version: 19,
13
+ name: "drop_version_record",
14
+ title: "The drop of the former record of versions, which auth_steps replaced",
15
+ tables: [],
16
+ drops: [versionRecord],
17
+ statements: ({ former }) => [ddl`drop table if exists ${former(versionRecord)}`]
18
+ };
19
+ //#endregion
20
+ export { dropVersionRecord, versionRecord };
@@ -0,0 +1,7 @@
1
+ import "../../names/modules/index.js";
2
+ import { StoreNames } from "../store-names.js";
3
+ import "./step.js";
4
+ //#region src/better-auth/store/steps/index.d.ts
5
+ /** Those tables as the store's names name them, as SQL text: no older code reads them, so their drop takes nothing from it. */
6
+ export declare const droppedTableIds: (names: StoreNames) => string[];
7
+ //#endregion
@@ -3,6 +3,7 @@ import { accountKeys } from "./auth/002-account-keys.js";
3
3
  import { userIndexes } from "./auth/003-user-indexes.js";
4
4
  import { verificationPatternIndex } from "./auth/004-verification-pattern-index.js";
5
5
  import { userNameSearch } from "./auth/005-user-name-search.js";
6
+ import { dropVersionRecord } from "./auth/006-drop-version-record.js";
6
7
  import { mailSenders } from "./mail-senders/001-mail-senders.js";
7
8
  import { mailSenderNames } from "./mail-senders/002-mail-sender-names.js";
8
9
  import { senderAddressEvidence } from "./mail-senders/003-sender-address-evidence.js";
@@ -20,6 +21,7 @@ import { signInPolicy } from "./sign-in-policy/001-sign-in-policy.js";
20
21
  import { staffSignIn } from "./staff-sign-in/001-staff-sign-in.js";
21
22
  import { staffSignInIndexes } from "./staff-sign-in/002-staff-sign-in-indexes.js";
22
23
  import { twoFactor } from "./two-factor/001-two-factor.js";
24
+ import { migrationNames } from "./step.js";
23
25
  //#region src/better-auth/store/steps/index.ts
24
26
  /** Each module's chain of steps, the only source of its tables: a new step goes last in its module's chain, with the next number. */
25
27
  const moduleSteps = {
@@ -28,7 +30,8 @@ const moduleSteps = {
28
30
  accountKeys,
29
31
  userIndexes,
30
32
  verificationPatternIndex,
31
- userNameSearch
33
+ userNameSearch,
34
+ dropVersionRecord
32
35
  ],
33
36
  two_factor: [twoFactor],
34
37
  passkeys: [passkeys, rpIdIndex],
@@ -50,5 +53,9 @@ const moduleSteps = {
50
53
  ],
51
54
  platform_devices: [platformDevices]
52
55
  };
56
+ /** The tables a step drops, by internal name, which no module declares any more. */
57
+ const droppedTables = Object.values(moduleSteps).flatMap((steps) => steps.flatMap((step) => step.drops ?? []));
58
+ /** Those tables as the store's names name them, as SQL text: no older code reads them, so their drop takes nothing from it. */
59
+ const droppedTableIds = (names) => droppedTables.map((internal) => String(migrationNames(names).former(internal)));
53
60
  //#endregion
54
- export { moduleSteps };
61
+ export { droppedTableIds, droppedTables, moduleSteps };
@@ -1,5 +1,5 @@
1
1
  //#region src/better-auth/store/steps/legacy-versions.d.ts
2
- /** Each version with the name its row in `auth_migrations` holds. */
2
+ /** Each version with its name. */
3
3
  export declare const legacyVersions: {
4
4
  version: number;
5
5
  name: string;
@@ -1,5 +1,5 @@
1
1
  //#region src/better-auth/store/steps/legacy-versions.ts
2
- /** Each version with the name its row in `auth_migrations` holds. */
2
+ /** Each version with its name. */
3
3
  const legacyVersions = [
4
4
  {
5
5
  version: 1,
@@ -72,6 +72,10 @@ const legacyVersions = [
72
72
  {
73
73
  version: 18,
74
74
  name: "default_organization"
75
+ },
76
+ {
77
+ version: 19,
78
+ name: "drop_version_record"
75
79
  }
76
80
  ];
77
81
  /** The version the store is at once every step is applied. */
@@ -1,3 +1,3 @@
1
1
  import "../../names/modules/index.js";
2
2
  import "./step.js";
3
- import "kysely";
3
+ import { RawBuilder } from "kysely";
@@ -7,12 +7,17 @@ export declare const contractingRules: string[];
7
7
  * migrations run in one transaction while nothing else writes.
8
8
  */
9
9
  export declare const lockingRules: string[];
10
- /** A rendered step: `made`, the tables it makes as its SQL names them; `checked`, whether it starts with a check. */
10
+ /**
11
+ * A rendered step: `made`, the tables it makes as its SQL names them; `checked`, whether it starts with a check;
12
+ * `drops`, whether it is a step that drops a table Protobase no longer declares (`Step.drops`), the reviewed exception
13
+ * to `ban-drop-table`.
14
+ */
11
15
  export type LintedStep = {
12
16
  label: string;
13
17
  sql: string;
14
18
  made: string[];
15
19
  checked: boolean;
20
+ drops?: boolean;
16
21
  };
17
22
  export type StepFinding = {
18
23
  step: string;
@@ -60,7 +60,8 @@ const squawkReport = (steps, squawk = createRequire(import.meta.url).resolve("sq
60
60
  line: finding.line
61
61
  }));
62
62
  };
63
- const squawkFindings = (steps, squawk) => squawkReport(steps, squawk).filter((finding) => refusedRules.includes(finding.rule)).map(({ step, rule, message }) => ({
63
+ const reviewedDrop = (steps, finding) => finding.rule === "ban-drop-table" && steps.some((step) => step.label === finding.step && step.drops);
64
+ const squawkFindings = (steps, squawk) => squawkReport(steps, squawk).filter((finding) => refusedRules.includes(finding.rule) && !reviewedDrop(steps, finding)).map(({ step, rule, message }) => ({
64
65
  step,
65
66
  rule,
66
67
  message
@@ -3,7 +3,7 @@ import "../../names/modules/index.js";
3
3
  import "../../names/resolve-names.js";
4
4
  import { DefaultOrganization } from "../../organizations/options.js";
5
5
  import "../store-names.js";
6
- import "kysely";
6
+ import { RawBuilder } from "kysely";
7
7
  //#region src/better-auth/store/steps/step.d.ts
8
8
  /** The organizations' settings a step writes rows from: the default organization, and the app role of the users there already. */
9
9
  export type OrganizationsInput = {
@@ -1,4 +1,6 @@
1
1
  import { tableId } from "../../names/identifiers.js";
2
+ import { allModules } from "../../names/modules-on.js";
3
+ import { resolveNames, tableNameOf } from "../../names/resolve-names.js";
2
4
  import { sql } from "kysely";
3
5
  //#region src/better-auth/store/steps/step.ts
4
6
  /** The organizations' input of the steps from their settings; `undefined` without a default organization. */
@@ -7,17 +9,40 @@ const organizationsInput = (settings) => settings?.default ? {
7
9
  existingUsersRole: settings.existingUsersRole
8
10
  } : void 0;
9
11
  /**
12
+ * A table Protobase no longer declares, as `former` names it. Refuses when a table the config names, of a module on or
13
+ * off, or the user key table in the store's schema has that name, so a step that drops it never drops a table in use.
14
+ */
15
+ const formerTable = ({ schema, names, users }, internal) => {
16
+ const id = tableId(schema, tableNameOf(names.input.tables ?? {}, internal));
17
+ const every = resolveNames({
18
+ ...names.input,
19
+ modules: allModules
20
+ });
21
+ const taken = Object.values(every.tables).find((table) => table.name === id.name);
22
+ const keyTable = users.keyTable && users.keyTable.schema === schema && users.keyTable.table === id.name;
23
+ if (taken || keyTable) {
24
+ const which = taken ? `${taken.internal} table` : "users.keyTable table";
25
+ throw new Error(`The auth store's ${which} is named ${id.name}, the name of the former ${internal} table that a step drops: give it another name in the config`);
26
+ }
27
+ return id;
28
+ };
29
+ /**
10
30
  * The `ddl` parts of the store's names. `externalUser`: the user table is a relation Protobase did not make, which its
11
31
  * statements leave alone, as under `users.keyTable` or as a project's snapshot records it.
12
32
  */
13
- const migrationNames = ({ names, users, uuidIds }, externalUser = users.keyTable !== void 0) => ({
33
+ const migrationNames = ({ schema, names, users, uuidIds }, externalUser = users.keyTable !== void 0) => ({
14
34
  table: names.table,
15
35
  user: users.keyTable ? tableId(users.keyTable.schema, users.keyTable.table) : names.table("user"),
16
36
  userDdl: (statements) => externalUser ? [] : statements,
17
37
  externalUser,
18
38
  metadata: users.metadata,
19
39
  id: sql.raw(uuidIds ? "uuid default pg_catalog.gen_random_uuid()" : "text"),
20
- idRef: sql.raw(uuidIds ? "uuid" : "text")
40
+ idRef: sql.raw(uuidIds ? "uuid" : "text"),
41
+ former: (internal) => formerTable({
42
+ schema,
43
+ names,
44
+ users
45
+ }, internal)
21
46
  });
22
47
  //#endregion
23
- export { migrationNames, organizationsInput };
48
+ export { formerTable, migrationNames, organizationsInput };
@@ -1,3 +1,3 @@
1
1
  import "../names/resolve-names.js";
2
2
  import "../organizations/store.js";
3
- import { Kysely } from "kysely";
3
+ import { Kysely, RawBuilder } from "kysely";
@@ -27,15 +27,20 @@ import { workflowPlugins } from "./workflows/default-plugins.js";
27
27
  import { StoreNames, storeNames } from "./better-auth/store/store-names.js";
28
28
  import { settingsStoreNames } from "./better-auth/store/offline/settings-names.js";
29
29
  import { OrganizationsInput, organizationsInput } from "./better-auth/store/steps/step.js";
30
- import { KeptModule, LastSteps, StoreModel, keptModule, latestSteps, storeModel, storeNamesList } from "./better-auth/store/offline/store-model.js";
30
+ import { DeferredOff, KeptModule, LastSteps, RetiredName, StoreModel, keptModule, latestSteps, storeModel, storeNamesList } from "./better-auth/store/offline/store-model.js";
31
31
  import { nameChanges } from "./better-auth/store/offline/name-changes.js";
32
32
  import { SnapshotStore, offlineStepsMigration } from "./better-auth/store/offline/offline-steps.js";
33
33
  import { retiredSchema } from "./better-auth/store/offline/retired-watch.js";
34
- import { OffChoice, forceSetting, keepSql, keptTables, offChoices, revivalCheckSql, revivalRefusal, unwatchSql } from "./better-auth/store/offline/module-switches.js";
34
+ import { OffChoice, forceSetting, keepSql, keptTables, offChoices, retiredNames, revivalCheckSql, revivalRefusal, unwatchSql } from "./better-auth/store/offline/module-switches.js";
35
+ import { SignedOff, contractMark, markedSql, signOffGate } from "./better-auth/store/offline/contract-gate.js";
36
+ import { ArchivedModule, archiveSchema, archiveStatements, archivedColumn, archivedModule, revokeStatements } from "./better-auth/store/offline/module-archive.js";
37
+ import { StepRecord, deleteStatements, forgetStepsSql, stepRecordOf } from "./better-auth/store/offline/module-delete.js";
38
+ import { restoredKeysSql } from "./better-auth/store/offline/archive-revival.js";
35
39
  import { bucketsCommentPrefix } from "./computed/buckets-sql.js";
36
40
  import { AppliedStep } from "./better-auth/store/step-record.js";
37
41
  import { LiveStore, baselineStore } from "./better-auth/store/offline/baseline-store.js";
38
- import { stepRecordMigration, stepsOfVersions } from "./better-auth/store/legacy-record.js";
42
+ import { stepsOfVersions, versionRecordRefusal, versionRecordTable } from "./better-auth/store/legacy-record.js";
43
+ import { droppedTableIds } from "./better-auth/store/steps/index.js";
39
44
  import { legacyVersions } from "./better-auth/store/steps/legacy-versions.js";
40
45
  import { LintedStep, SquawkFinding, contractingRules, lintSteps, lockingRules, squawkReport } from "./better-auth/store/steps/step-lint.js";
41
46
  import { contractingSql } from "./migration-sql/additive-statements.js";
@@ -47,4 +52,4 @@ import { recordsRuntimeModel } from "./migration-record/check-record.js";
47
52
  import { plainStoreDb } from "./better-auth/store/store-db.js";
48
53
  import { moduleDifference, retiredDifference } from "./schema-modules/module-difference.js";
49
54
  import { keptStoreModules } from "./better-auth/auth-schema.js";
50
- export { type AfterIndex, type AppAuthInput, type AppliedStep, type AuthPlugins, type KeptModule, type LastSteps, type LintedStep, type LiveStore, type ModuleId, type ModuleInput, type ModuleModel, type ModuleTargets, type ModulesModel, type OffChoice, type OrganizationsInput, type RecordModel, type SchemaModule, type SchemaModuleId, type SnapshotStore, type SquawkFinding, type StoreModel, type StoreNames, appAuthOptions, appDialect, appPool, baselineStore, betterAuthAuthenticator, bucketsCommentPrefix, bucketsRefreshes, buildAppAuth, buildAuth, buildAuthenticator, captureNames, checkCallsOptions, checkNotificationsOptions, checkStatusOptions, contractingRules, contractingSql, createAuth, declaredJob, fileProviderOf, forceSetting, isOverSignIn, isSubscription, keepSql, keptModule, keptNames, keptStoreModules, keptTables, latestModules, latestSteps, legacyVersions, lintSteps, loadAuthPlugins, localFiles, lockingRules, longQueryPool, modelHash, moduleDifference, nameChanges, noInput, offChoices, offlineStepsMigration, organizationsEnabled, organizationsInput, plainStoreDb, readOrigins, readPasskeyDomain, recordTable, recordTableSql, recordsRuntimeModel, refreshBuckets, resolveNames, retiredDifference, retiredSchema, revivalCheckSql, revivalRefusal, runtimeModel, s3Files, schemaModules, settingsStoreNames, squawkReport, stepRecordMigration, stepsOfVersions, storeModel, storeNames, storeNamesList, targetIds, uncapturedMessage, unwatchSql, webhooksModule, workflowPlugins, workflowsModule };
55
+ export { type AfterIndex, type AppAuthInput, type AppliedStep, type ArchivedModule, type AuthPlugins, type DeferredOff, type KeptModule, type LastSteps, type LintedStep, type LiveStore, type ModuleId, type ModuleInput, type ModuleModel, type ModuleTargets, type ModulesModel, type OffChoice, type OrganizationsInput, type RecordModel, type RetiredName, type SchemaModule, type SchemaModuleId, type SignedOff, type SnapshotStore, type SquawkFinding, type StepRecord, type StoreModel, type StoreNames, appAuthOptions, appDialect, appPool, archiveSchema, archiveStatements, archivedColumn, archivedModule, baselineStore, betterAuthAuthenticator, bucketsCommentPrefix, bucketsRefreshes, buildAppAuth, buildAuth, buildAuthenticator, captureNames, checkCallsOptions, checkNotificationsOptions, checkStatusOptions, contractMark, contractingRules, contractingSql, createAuth, declaredJob, deleteStatements, droppedTableIds, fileProviderOf, forceSetting, forgetStepsSql, isOverSignIn, isSubscription, keepSql, keptModule, keptNames, keptStoreModules, keptTables, latestModules, latestSteps, legacyVersions, lintSteps, loadAuthPlugins, localFiles, lockingRules, longQueryPool, markedSql, modelHash, moduleDifference, nameChanges, noInput, offChoices, offlineStepsMigration, organizationsEnabled, organizationsInput, plainStoreDb, readOrigins, readPasskeyDomain, recordTable, recordTableSql, recordsRuntimeModel, refreshBuckets, resolveNames, restoredKeysSql, retiredDifference, retiredNames, retiredSchema, revivalCheckSql, revivalRefusal, revokeStatements, runtimeModel, s3Files, schemaModules, settingsStoreNames, signOffGate, squawkReport, stepRecordOf, stepsOfVersions, storeModel, storeNames, storeNamesList, targetIds, uncapturedMessage, unwatchSql, versionRecordRefusal, versionRecordTable, webhooksModule, workflowPlugins, workflowsModule };
package/dist/internal.js CHANGED
@@ -19,11 +19,12 @@ import { checkStatusOptions } from "./status/options.js";
19
19
  import { appPool, longQueryPool } from "./app-pool.js";
20
20
  import { betterAuthAuthenticator } from "./better-auth/authenticator.js";
21
21
  import { isOverSignIn } from "./better-auth/over-sign-in.js";
22
+ import { organizationsInput } from "./better-auth/store/steps/step.js";
23
+ import { droppedTableIds } from "./better-auth/store/steps/index.js";
22
24
  import { keptModule, latestSteps, storeModel, storeNamesList } from "./better-auth/store/offline/store-model.js";
23
25
  import { baselineStore } from "./better-auth/store/offline/baseline-store.js";
24
26
  import { legacyVersions } from "./better-auth/store/steps/legacy-versions.js";
25
- import { stepRecordMigration, stepsOfVersions } from "./better-auth/store/legacy-record.js";
26
- import { organizationsInput } from "./better-auth/store/steps/step.js";
27
+ import { stepsOfVersions, versionRecordRefusal, versionRecordTable } from "./better-auth/store/legacy-record.js";
27
28
  import { keptStoreModules } from "./better-auth/auth-schema.js";
28
29
  import { recordTable, recordTableSql } from "./migration-record/record-table.js";
29
30
  import { noInput } from "./schema-modules/schema-module.js";
@@ -42,7 +43,11 @@ import { checkCallsOptions } from "./calls/calls-options.js";
42
43
  import { settingsStoreNames } from "./better-auth/store/offline/settings-names.js";
43
44
  import { offlineStepsMigration } from "./better-auth/store/offline/offline-steps.js";
44
45
  import { retiredSchema } from "./better-auth/store/offline/retired-watch.js";
45
- import { forceSetting, keepSql, keptTables, offChoices, revivalCheckSql, revivalRefusal, unwatchSql } from "./better-auth/store/offline/module-switches.js";
46
+ import { forceSetting, keepSql, keptTables, offChoices, retiredNames, revivalCheckSql, revivalRefusal, unwatchSql } from "./better-auth/store/offline/module-switches.js";
47
+ import { contractMark, markedSql, signOffGate } from "./better-auth/store/offline/contract-gate.js";
48
+ import { archiveSchema, archiveStatements, archivedColumn, archivedModule, revokeStatements } from "./better-auth/store/offline/module-archive.js";
49
+ import { deleteStatements, forgetStepsSql, stepRecordOf } from "./better-auth/store/offline/module-delete.js";
50
+ import { restoredKeysSql } from "./better-auth/store/offline/archive-revival.js";
46
51
  import { contractingRules, lintSteps, lockingRules, squawkReport } from "./better-auth/store/steps/step-lint.js";
47
52
  import { contractingSql } from "./migration-sql/additive-statements.js";
48
- export { appAuthOptions, appDialect, appPool, baselineStore, betterAuthAuthenticator, bucketsCommentPrefix, bucketsRefreshes, buildAppAuth, buildAuth, buildAuthenticator, captureNames, checkCallsOptions, checkNotificationsOptions, checkStatusOptions, contractingRules, contractingSql, createAuth, declaredJob, fileProviderOf, forceSetting, isOverSignIn, isSubscription, keepSql, keptModule, keptNames, keptStoreModules, keptTables, latestModules, latestSteps, legacyVersions, lintSteps, loadAuthPlugins, localFiles, lockingRules, longQueryPool, modelHash, moduleDifference, nameChanges, noInput, offChoices, offlineStepsMigration, organizationsEnabled, organizationsInput, plainStoreDb, readOrigins, readPasskeyDomain, recordTable, recordTableSql, recordsRuntimeModel, refreshBuckets, resolveNames, retiredDifference, retiredSchema, revivalCheckSql, revivalRefusal, runtimeModel, s3Files, schemaModules, settingsStoreNames, squawkReport, stepRecordMigration, stepsOfVersions, storeModel, storeNames, storeNamesList, targetIds, uncapturedMessage, unwatchSql, webhooksModule, workflowPlugins, workflowsModule };
53
+ export { appAuthOptions, appDialect, appPool, archiveSchema, archiveStatements, archivedColumn, archivedModule, baselineStore, betterAuthAuthenticator, bucketsCommentPrefix, bucketsRefreshes, buildAppAuth, buildAuth, buildAuthenticator, captureNames, checkCallsOptions, checkNotificationsOptions, checkStatusOptions, contractMark, contractingRules, contractingSql, createAuth, declaredJob, deleteStatements, droppedTableIds, fileProviderOf, forceSetting, forgetStepsSql, isOverSignIn, isSubscription, keepSql, keptModule, keptNames, keptStoreModules, keptTables, latestModules, latestSteps, legacyVersions, lintSteps, loadAuthPlugins, localFiles, lockingRules, longQueryPool, markedSql, modelHash, moduleDifference, nameChanges, noInput, offChoices, offlineStepsMigration, organizationsEnabled, organizationsInput, plainStoreDb, readOrigins, readPasskeyDomain, recordTable, recordTableSql, recordsRuntimeModel, refreshBuckets, resolveNames, restoredKeysSql, retiredDifference, retiredNames, retiredSchema, revivalCheckSql, revivalRefusal, revokeStatements, runtimeModel, s3Files, schemaModules, settingsStoreNames, signOffGate, squawkReport, stepRecordOf, stepsOfVersions, storeModel, storeNames, storeNamesList, targetIds, uncapturedMessage, unwatchSql, versionRecordRefusal, versionRecordTable, webhooksModule, workflowPlugins, workflowsModule };
package/dist/package.js CHANGED
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.130.0";
2
+ var version = "0.131.0";
3
3
  //#endregion
4
4
  export { version };