@protobase/cli 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.
Files changed (99) hide show
  1. package/dist/auth/config-organizations.js +15 -0
  2. package/dist/auth/register.js +8 -2
  3. package/dist/auth/write-migration.js +34 -12
  4. package/dist/cli/package.js +1 -1
  5. package/dist/config/build-project.js +1 -0
  6. package/dist/config/project-modules.js +64 -0
  7. package/dist/config/read-only-queries.js +9 -0
  8. package/dist/config/user-tables-config.js +1 -1
  9. package/dist/dev/dev-jobs.js +12 -6
  10. package/dist/dev/entry.js +12 -19
  11. package/dist/doctor/capture-files.js +3 -3
  12. package/dist/doctor/startup.js +2 -4
  13. package/dist/migration/apply-migrations.js +9 -6
  14. package/dist/migration/baseline/read-live-modules.js +31 -0
  15. package/dist/migration/baseline/read-live-store.js +18 -4
  16. package/dist/migration/baseline/write-baseline.js +50 -17
  17. package/dist/migration/migrate-project.js +3 -3
  18. package/dist/migration/migration-project.js +29 -15
  19. package/dist/migration/older-code/catalog.js +34 -0
  20. package/dist/migration/older-code/contractions.js +86 -0
  21. package/dist/migration/older-code/lint-files.js +55 -0
  22. package/dist/migration/older-code/refusal.js +9 -0
  23. package/dist/migration/older-code/trial.js +58 -0
  24. package/dist/migration/parts.js +8 -104
  25. package/dist/migration/record/after-file.js +20 -2
  26. package/dist/migration/register.js +67 -19
  27. package/dist/migration/release/release-record.js +9 -7
  28. package/dist/migration/release/release-steps.js +15 -3
  29. package/dist/migration/sign-off/contract.js +65 -0
  30. package/dist/migration/sign-off/delete.js +50 -0
  31. package/dist/migration/sign-off/signed-off-file.js +19 -0
  32. package/dist/migration/snapshot/auth-difference.js +135 -15
  33. package/dist/migration/snapshot/auth-target.js +9 -3
  34. package/dist/migration/snapshot/check.js +24 -5
  35. package/dist/migration/snapshot/custom.js +6 -3
  36. package/dist/migration/snapshot/drop.js +7 -2
  37. package/dist/migration/snapshot/header.js +11 -4
  38. package/dist/migration/snapshot/module-changes.js +22 -0
  39. package/dist/migration/snapshot/module-prompts.js +42 -0
  40. package/dist/migration/snapshot/module-sections.js +38 -0
  41. package/dist/migration/snapshot/next-snapshot.js +13 -7
  42. package/dist/migration/snapshot/off-choice.js +11 -0
  43. package/dist/migration/snapshot/organizations-off-facts.js +49 -0
  44. package/dist/migration/snapshot/revival-rows.js +34 -0
  45. package/dist/migration/snapshot/run-migration.js +82 -15
  46. package/dist/migration/snapshot/snapshot-file.js +7 -0
  47. package/dist/migration/snapshot/terminal-prompts.js +21 -0
  48. package/dist/migration/snapshot/write-file.js +1 -1
  49. package/dist/migration/summary.js +3 -2
  50. package/dist/organizations/api.js +4 -2
  51. package/dist/organizations/commands.js +27 -10
  52. package/dist/organizations/pin-source.js +20 -0
  53. package/dist/organizations/pin.js +40 -0
  54. package/dist/organizations/register.js +20 -12
  55. package/dist/scaffold/protobase-tables.js +2 -2
  56. package/dist/serve/create-admin.js +6 -3
  57. package/dist/serve/lifecycle.js +2 -2
  58. package/dist/serve/migrate-release.js +1 -1
  59. package/dist/serve/relay-check.js +7 -8
  60. package/dist/serve/startup-checks.js +12 -22
  61. package/dist/supabase/load-phase.js +3 -1
  62. package/dist/supabase/project-users.js +4 -1
  63. package/dist/users/commands.js +44 -6
  64. package/dist/users/load-auth.js +9 -3
  65. package/dist/users/manage.js +16 -1
  66. package/dist/users/register.js +28 -25
  67. package/dist/users/set-disabled.js +3 -2
  68. package/dist/users/users-api.js +9 -3
  69. package/dist/worker/start-worker.js +7 -4
  70. package/package.json +8 -8
  71. package/skills/protobase/references/features/api-functions.md +1 -0
  72. package/skills/protobase/references/features/build-and-run.md +4 -2
  73. package/skills/protobase/references/features/sign-in-and-accounts.md +2 -1
  74. package/skills/protobase/references/guides/api-functions.md +27 -2
  75. package/skills/protobase/references/guides/deploy.md +2 -2
  76. package/skills/protobase/references/reference/assistant.md +1 -1
  77. package/skills/protobase/references/reference/auth.md +52 -17
  78. package/skills/protobase/references/reference/calls.md +1 -1
  79. package/skills/protobase/references/reference/cli.md +48 -28
  80. package/skills/protobase/references/reference/comments.md +1 -1
  81. package/skills/protobase/references/reference/config/api.md +1 -1
  82. package/skills/protobase/references/reference/config/jobs-and-events.md +1 -1
  83. package/skills/protobase/references/reference/config/sign-in.md +22 -4
  84. package/skills/protobase/references/reference/config.md +1 -1
  85. package/skills/protobase/references/reference/data-config.md +9 -9
  86. package/skills/protobase/references/reference/derived.md +1 -1
  87. package/skills/protobase/references/reference/email.md +2 -2
  88. package/skills/protobase/references/reference/events.md +2 -2
  89. package/skills/protobase/references/reference/history.md +1 -1
  90. package/skills/protobase/references/reference/jobs.md +5 -5
  91. package/skills/protobase/references/reference/live.md +2 -2
  92. package/skills/protobase/references/reference/notifications.md +4 -4
  93. package/skills/protobase/references/reference/personal-access-tokens.md +2 -2
  94. package/skills/protobase/references/reference/realtime-relay.md +1 -1
  95. package/skills/protobase/references/reference/status.md +2 -2
  96. package/skills/protobase/references/reference/supabase-rest.md +1 -1
  97. package/skills/protobase/references/reference/user-tables.md +1 -1
  98. package/skills/protobase/references/reference/webhooks.md +1 -1
  99. package/dist/migration/snapshot/lint-custom.js +0 -23
@@ -0,0 +1,15 @@
1
+ import { loadNearestEnvFile } from "../dev/env.js";
2
+ import { loadSourceConfig } from "../config/source-config.js";
3
+ import { organizationsInput } from "@protobase/server/internal";
4
+ //#region src/auth/config-organizations.ts
5
+ /**
6
+ * The default organization and the role of the users there already, as the config of the project in `projectDir` gives
7
+ * them: it keeps them while organizations are off, when the project's sign-in has no organizations to read them from.
8
+ */
9
+ const loadConfigOrganizations = async (projectDir) => {
10
+ loadNearestEnvFile(projectDir);
11
+ const config = await loadSourceConfig(projectDir, { command: "tool" });
12
+ return config.auth ? organizationsInput(config.auth.organizations) : void 0;
13
+ };
14
+ //#endregion
15
+ export { loadConfigOrganizations };
@@ -3,17 +3,23 @@ import path from "node:path";
3
3
  const out = (text) => process.stdout.write(text);
4
4
  const registerAuth = (program) => {
5
5
  program.command("auth").description("The auth schema of the project in the current directory").command("migration").description("Write the auth schema changes this Protobase version needs as the project's next SQL migration, compared with its database").option("--dir <dir>", "migrations folder", "db/migrations").option("--name <name>", "file name after the number", "auth").action(async (opts) => {
6
- const [{ loadSignIn }, { writeAuthMigration }] = await Promise.all([import("../users/load-auth.js"), import("./write-migration.js")]);
6
+ const [{ loadSignIn }, { writeAuthMigration }, { loadConfigOrganizations }] = await Promise.all([
7
+ import("../users/load-auth.js"),
8
+ import("./write-migration.js"),
9
+ import("./config-organizations.js")
10
+ ]);
7
11
  const auth = await loadSignIn(process.cwd());
8
12
  if (!auth) {
9
13
  out("sign-in is off in the project's config; nothing to write\n");
10
14
  return;
11
15
  }
16
+ const organizations = await loadConfigOrganizations(process.cwd());
12
17
  const file = await writeAuthMigration({
13
18
  auth,
14
19
  projectDir: process.cwd(),
15
20
  dir: path.resolve(opts.dir),
16
- name: opts.name
21
+ name: opts.name,
22
+ organizations
17
23
  });
18
24
  out(file ? `wrote ${path.relative(process.cwd(), file)}; apply it with the project's migrations\n` : "the auth schema is up to date; nothing to write\n");
19
25
  process.exit(0);
@@ -1,13 +1,15 @@
1
1
  import { protobaseVersion } from "../version/version.js";
2
- import { readSnapshot } from "../migration/snapshot/snapshot-file.js";
3
- import { authRefusals, customHint } from "../migration/snapshot/auth-difference.js";
2
+ import { organizationsNow } from "../migration/snapshot/auth-target.js";
3
+ import { moduleChanges } from "../migration/snapshot/module-changes.js";
4
+ import { readSnapshot, snapshotFile } from "../migration/snapshot/snapshot-file.js";
5
+ import { authRefusals, customHint, organizationRefusals } from "../migration/snapshot/auth-difference.js";
4
6
  import { readMigrationFiles } from "../migration/snapshot/migration-files.js";
5
7
  import { refuseInconsistent } from "../migration/snapshot/consistency.js";
6
8
  import { currentStoreText, migrationText, recordOnlyText } from "./migration-file.js";
7
9
  import { writeMigrationFile } from "../migration/snapshot/write-file.js";
8
10
  import { randomUUID } from "node:crypto";
9
11
  import { authSchemaMigration } from "@protobase/server";
10
- import { latestSteps, recordsRuntimeModel, storeModel, storeNames } from "@protobase/server/internal";
12
+ import { keptStoreModules, latestSteps, organizationsInput, plainStoreDb, recordsRuntimeModel, runtimeModel, storeModel, storeNames } from "@protobase/server/internal";
11
13
  //#region src/auth/write-migration.ts
12
14
  /**
13
15
  * Writes the auth schema changes the database still needs as the next migration in `dir`, and returns its path;
@@ -18,23 +20,43 @@ import { latestSteps, recordsRuntimeModel, storeModel, storeNames } from "@proto
18
20
  * migrations came before the snapshot, gets a file without statements that starts it; one whose store is current but
19
21
  * not in the database's record of migrations, as before the record, a file that only records it.
20
22
  */
21
- const writeAuthMigration = async ({ auth, projectDir, dir, name, writer }) => {
23
+ const writeAuthMigration = async ({ auth, projectDir, dir, name, writer, organizations }) => {
22
24
  const snapshot = await readSnapshot(projectDir);
23
25
  refuseInconsistent(snapshot, await readMigrationFiles(dir));
24
- const sql = await authSchemaMigration(auth);
25
- const unrecorded = sql === void 0 && !await recordsRuntimeModel(auth);
26
- if (sql === void 0 && snapshot && !unrecorded) return;
27
26
  const names = storeNames(auth);
28
- const refusals = authRefusals(snapshot, {
27
+ const target = {
29
28
  names,
30
- organizationsOn: Boolean(auth.organizations)
31
- });
29
+ organizationsOn: Boolean(auth.organizations),
30
+ organizations: organizations ?? organizationsInput(auth.organizations?.options)
31
+ };
32
+ const changes = moduleChanges(snapshot, target);
33
+ const switched = [...changes.off.map(({ module }) => `${module} off`), ...changes.revived.map(({ module }) => `${module} on again`)];
34
+ if (switched.length > 0) throw new Error(`The config turns ${switched.join(", ")} since ${snapshotFile}: write that migration with \`protobase migration\``);
35
+ const unset = organizationRefusals(snapshot, target);
36
+ if (unset.length > 0) throw new Error(unset.join("; "));
37
+ const sql = await authSchemaMigration(auth);
38
+ const unrecorded = sql === void 0 && !await recordsRuntimeModel(plainStoreDb(auth), runtimeModel(auth, {}));
39
+ if (sql === void 0 && snapshot && !unrecorded) return;
40
+ const refusals = authRefusals(snapshot, target);
32
41
  if (refusals.length > 0) throw new Error(`${refusals.join("; ")}. ${customHint}`);
42
+ const kept = snapshot ? [] : await keptStoreModules(auth);
43
+ const decisions = snapshot ? void 0 : {
44
+ modules: {
45
+ kept,
46
+ archived: []
47
+ },
48
+ organizations: {
49
+ everOn: kept.some(({ module }) => module === "organizations"),
50
+ defaultOrganization: target.organizations?.default ?? null
51
+ }
52
+ };
33
53
  const draft = {
34
54
  previous: snapshot,
35
55
  auth: storeModel(names, latestSteps(names.names.modules)),
36
- organizationsOn: Boolean(auth.organizations),
37
- protobaseVersion
56
+ modules: snapshot?.model.modules,
57
+ organizations: organizationsNow(target),
58
+ protobaseVersion,
59
+ ...decisions && { decisions }
38
60
  };
39
61
  const body = sql !== void 0 ? migrationText(sql, writer) : snapshot ? recordOnlyText(writer) : currentStoreText(writer);
40
62
  return writeMigrationFile(projectDir, dir, {
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.129.1";
2
+ var version = "0.130.1";
3
3
  //#endregion
4
4
  export { version };
@@ -29,6 +29,7 @@ const projectAuth = async (config, { db }, workflows) => {
29
29
  ...name && { appName: name }
30
30
  }, {
31
31
  db,
32
+ ...config.authenticate?.tenant !== void 0 && { tenant: config.authenticate.tenant },
32
33
  ...hooks && { hooks },
33
34
  ...mailer && { mailer },
34
35
  ...workflows && { workflowConnections: workflowConnectionsOf(workflows) }
@@ -0,0 +1,64 @@
1
+ import { projectJobs, projectNotifications, projectResources, projectWebhooks } from "./project-parts.js";
2
+ import { mailFeedbackOn } from "./mail-feedback-config.js";
3
+ import { unsubscribeOn } from "./unsubscribe-config.js";
4
+ import { userTablesOn } from "./user-tables-config.js";
5
+ import { authTarget } from "../migration/snapshot/auth-target.js";
6
+ import { readOnlyQueriesOn } from "./read-only-queries.js";
7
+ import { configExports, neededModules } from "@protobase/server";
8
+ import { runtimeModel, storeNames } from "@protobase/server/internal";
9
+ //#region src/config/project-modules.ts
10
+ const models = (config) => {
11
+ const { resources, views } = configExports(config);
12
+ return {
13
+ models: resources.map((resource) => resource.toModel()),
14
+ views: views.map((view) => view.toModel())
15
+ };
16
+ };
17
+ /** The schema modules of the app `project` serves. */
18
+ const builtModules = (project) => neededModules({
19
+ ...models(project.config),
20
+ jobs: project.jobs,
21
+ signIn: Boolean(project.auth),
22
+ ...project.auth && { authStore: storeNames(project.auth) },
23
+ mailFeedback: project.mailFeedback,
24
+ unsubscribe: Boolean(project.unsubscribe),
25
+ webhooks: project.webhooks,
26
+ workflows: project.workflows,
27
+ notifications: project.notifications,
28
+ status: project.status,
29
+ calls: project.calls,
30
+ realtime: project.realtime,
31
+ events: project.events,
32
+ userTables: project.userTables,
33
+ readOnlyQueries: readOnlyQueriesOn(project.options?.assistant, process.env)
34
+ });
35
+ /** The model the app `project` reads of its database's record of migrations (`runtimeModel`). */
36
+ const builtRuntimeModel = (project) => runtimeModel(project.auth, builtModules(project));
37
+ /** The schema modules of the app `config` makes, from the config alone. */
38
+ const configModules = async (config) => {
39
+ const [resources, webhooks, notifications, auth] = await Promise.all([
40
+ projectResources(config),
41
+ projectWebhooks(config),
42
+ projectNotifications(config),
43
+ authTarget(config)
44
+ ]);
45
+ return neededModules({
46
+ ...models(resources),
47
+ jobs: projectJobs(config),
48
+ signIn: Boolean(config.auth),
49
+ ...auth && { authStore: auth.names },
50
+ mailFeedback: mailFeedbackOn(config),
51
+ unsubscribe: unsubscribeOn(config),
52
+ webhooks,
53
+ workflows: config.workflows,
54
+ notifications,
55
+ status: config.status,
56
+ calls: config.calls,
57
+ realtime: config.realtime,
58
+ events: config.events,
59
+ userTables: userTablesOn(config),
60
+ readOnlyQueries: readOnlyQueriesOn(config.assistant, process.env)
61
+ });
62
+ };
63
+ //#endregion
64
+ export { builtModules, builtRuntimeModel, configModules };
@@ -0,0 +1,9 @@
1
+ import { assistantSettings } from "@protobase/server";
2
+ //#region src/config/read-only-queries.ts
3
+ /**
4
+ * Whether the built-in assistant's read-only queries run, with its key set in `env` or the options: they run as a
5
+ * role of their own, which the query module makes.
6
+ */
7
+ const readOnlyQueriesOn = (assistant, env) => assistantSettings(assistant, env)?.kind === "built-in";
8
+ //#endregion
9
+ export { readOnlyQueriesOn };
@@ -9,7 +9,7 @@ const userTablesOn = (config) => config.userTables === true;
9
9
  const checkUserTables = (config) => {
10
10
  const value = config.userTables;
11
11
  if (value !== void 0 && typeof value !== "boolean") throw new Error(`userTables is ${JSON.stringify(value)}; it takes true or false`);
12
- if (userTablesOn(config) && config.authenticate?.organizations && !(config.auth && config.auth.organizations)) throw new Error("userTables and authenticate.organizations are both on without auth.organizations; tables users add need the app's own organizations, so turn one of them off");
12
+ if (userTablesOn(config) && config.authenticate?.organizations && !(config.auth && config.auth.organizations?.enabled)) throw new Error("userTables and authenticate.organizations are both on without auth.organizations; tables users add need the app's own organizations, so turn one of them off");
13
13
  return config;
14
14
  };
15
15
  //#endregion
@@ -1,28 +1,34 @@
1
- import { checkJobsSchema, startJobs } from "@protobase/server";
1
+ import { startJobs } from "@protobase/server";
2
2
  //#region src/dev/dev-jobs.ts
3
3
  const store = globalThis;
4
4
  /**
5
- * Runs the project's jobs in the dev server: started on the first load, once the jobs schema checks out, with the app's
6
- * own mailer when it has one and the links of its unsubscribe, and given the reloaded definitions and the rebuilt app's `decryptField` on every load
7
- * after it, so an edited job runs its new code from the next job on. A mailer added or changed later is the jobs' from the next start.
5
+ * Runs the project's jobs in the dev server: started on the first load, on the jobs schema the record of migrations
6
+ * checked (`checkMigrationRecord`), with the app's
7
+ * tables it keeps to one organization (`organizationScope`), its own mailer when it has one and the links of its unsubscribe, and given the reloaded definitions and the rebuilt app's `decryptField` on every load
8
+ * after it, so an edited job runs its new code from the next job on. An edit that changes the scope, such as turning
9
+ * organizations on, stops the jobs and starts them again with it. A mailer added or changed later is the jobs' from the next start.
8
10
  */
9
- const devJobs = async (db, definitions, decryptField, mailer, unsubscribe) => {
11
+ const devJobs = async (db, scope, definitions, decryptField, mailer, unsubscribe) => {
12
+ const scopeKey = JSON.stringify(scope);
13
+ if (store.__protobaseJobs && store.__protobaseJobsScope !== scopeKey) await stopDevJobs();
10
14
  if (store.__protobaseJobs) return store.__protobaseJobs.update(definitions, decryptField);
11
15
  if (definitions.length === 0) return;
12
- await checkJobsSchema(db);
13
16
  store.__protobaseJobs = await startJobs({
14
17
  db,
18
+ scope,
15
19
  jobs: definitions,
16
20
  decryptField,
17
21
  ...mailer && { mailer },
18
22
  ...unsubscribe && { unsubscribe },
19
23
  onError: (error) => console.error(error)
20
24
  });
25
+ store.__protobaseJobsScope = scopeKey;
21
26
  };
22
27
  /** Lets running jobs finish and stops them, when the dev server closes. */
23
28
  const stopDevJobs = async () => {
24
29
  const runtime = store.__protobaseJobs;
25
30
  delete store.__protobaseJobs;
31
+ delete store.__protobaseJobsScope;
26
32
  await runtime?.stop();
27
33
  };
28
34
  //#endregion
package/dist/dev/entry.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import { protobaseVersion } from "../version/version.js";
2
2
  import { projectResources } from "../config/project-parts.js";
3
3
  import { buildProject } from "../config/build-project.js";
4
+ import { readOnlyQueriesOn } from "../config/read-only-queries.js";
5
+ import { builtRuntimeModel } from "../config/project-modules.js";
4
6
  import { projectIcons } from "../build/app-icons.js";
5
7
  import { projectErrorReporter } from "../project/error-reporter.js";
6
8
  import { servedAdmin } from "../project/served-admin.js";
@@ -11,7 +13,8 @@ import { devRealtimePrune } from "./dev-prune.js";
11
13
  import { devDatabase, loadDevConfig } from "./project.js";
12
14
  import { withDevServiceWorker } from "./service-worker-route.js";
13
15
  import { setMissing, supabaseEnv } from "./supabase-env.js";
14
- import { apiKeySettings, assistantSettings, authSchemaDrift, authStoreTables, checkAi, checkCalls, checkChanges, checkChannelSends, checkComments, checkComputed, checkDerived, checkMigrationRecord, checkNotificationsSchema, checkQueryRunner, checkRealtimeRelay, checkResourcesOutsideAuthStore, checkStatusSchema, checkUserTablesSchema, checkWebhooksSchema, checkWorkflowsSchema, configExports, hasUsers, relayed, sqlSends } from "@protobase/server";
16
+ import { apiKeySettings, authSchemaDrift, authStoreTables, checkAi, checkMigrationRecord, checkQueryRoleSafety, checkResourcesOutsideAuthStore, configExports, hasUsers } from "@protobase/server";
17
+ import { modelHash } from "@protobase/server/internal";
15
18
  import { upgradeWebSocket } from "@hono/node-server";
16
19
  import { Hono } from "hono";
17
20
  //#region src/dev/entry.ts
@@ -28,17 +31,14 @@ const { db } = database;
28
31
  const project = await buildProject(config, database);
29
32
  const { resources, views } = configExports(project.config);
30
33
  const store = globalThis;
31
- if (!store.__protobaseRecordChecked) {
32
- await checkMigrationRecord(project.auth, protobaseVersion);
33
- store.__protobaseRecordChecked = true;
34
+ const model = builtRuntimeModel(project);
35
+ if (store.__protobaseRecordChecked !== modelHash(model)) {
36
+ await checkMigrationRecord(db, model, protobaseVersion);
37
+ store.__protobaseRecordChecked = modelHash(model);
34
38
  }
39
+ await project.auth?.pinnedOrganization();
35
40
  if (project.auth) await checkResourcesOutsideAuthStore(db, resources.map((resource) => resource.toModel()), project.auth);
36
- await checkChanges(db, resources.map((resource) => resource.toModel()), project.events);
37
- await checkComments(db, resources.map((resource) => resource.toModel()));
38
- await checkDerived(db, resources.map((resource) => resource.toModel()));
39
- await checkCalls(db, project.calls, project.events);
40
- await checkComputed(db, resources.map((resource) => resource.toModel()));
41
- if (assistantSettings(project.options?.assistant, process.env)?.kind === "built-in") await checkQueryRunner(db, project.auth ? authStoreTables(project.auth) : {
41
+ if (readOnlyQueriesOn(project.options?.assistant, process.env)) await checkQueryRoleSafety(db, project.auth ? authStoreTables(project.auth) : {
42
42
  tables: [],
43
43
  schemas: []
44
44
  });
@@ -48,18 +48,11 @@ checkAi({
48
48
  assistant: project.options?.assistant,
49
49
  env: process.env
50
50
  });
51
- if (project.webhooks) await checkWebhooksSchema(db, project.webhooks);
52
- if (project.workflows) await checkWorkflowsSchema(db, project.workflows);
53
- if (relayed(project.realtime)) await checkRealtimeRelay(db);
54
- if (sqlSends(project.realtime)) await checkChannelSends(db);
55
- await checkProjectRelay(db, {
51
+ checkProjectRelay({
56
52
  ...project,
57
53
  models: resources.map((resource) => resource.toModel()),
58
54
  views: views.map((view) => view.toModel())
59
55
  }, process.env);
60
- if (project.notifications) await checkNotificationsSchema(db, project.notifications, project.auth);
61
- if (project.status) await checkStatusSchema(db, project.status, project.auth);
62
- if (project.userTables) await checkUserTablesSchema(db);
63
56
  setMissing(process.env, supabaseEnv({
64
57
  url: process.env.PROTOBASE_DEV_URL,
65
58
  databaseUrl: process.env.PROTOBASE_DATABASE_URL,
@@ -73,7 +66,7 @@ const ui = {
73
66
  icons: projectIcons(projectDir)
74
67
  };
75
68
  const { admin, jobs } = await servedAdmin(project, db, ui, reporter, upgradeWebSocket);
76
- if (process.env.PROTOBASE_DEV_JOBS !== "false") await devJobs(db, jobs, admin.decryptField, project.mailer, admin.unsubscribe);
69
+ if (process.env.PROTOBASE_DEV_JOBS !== "false") await devJobs(db, await admin.organizationScope(), jobs, admin.decryptField, project.mailer, admin.unsubscribe);
77
70
  devRealtimePrune(admin);
78
71
  var entry_default = withDevServiceWorker(new Hono(), Boolean(project.notifications)).route("/", admin);
79
72
  /** Whether the auth store has a user yet, for the banner's sign-in line; undefined without one. */
@@ -2,10 +2,10 @@ import { createsFunction, createsTable, createsTrigger } from "./migration-sql.j
2
2
  import { captureNames, uncapturedMessage } from "@protobase/server/internal";
3
3
  //#region src/doctor/capture-files.ts
4
4
  /**
5
- * The change capture the server's startup checks for, judged from the project's migrations (`readMigrationSql`) by the
6
- * names `checkChanges` looks up in the catalog: `capture()` and the outbox, the history table for history, the notices
5
+ * The change capture the server needs, judged from the project's migrations (`readMigrationSql`) by the
6
+ * names the change capture module writes: `capture()` and the outbox, the history table for history, the notices
7
7
  * table for live updates, and each resource's triggers on its table. Only resources whose table a migration creates are
8
- * judged, each failing with the server's own message; `unjudged` are the others, whose table is the database's to show.
8
+ * judged, each failing with doctor's message; `unjudged` are the others, whose table is the database's to show.
9
9
  * A trigger a later migration drops, or one created in dynamic SQL, is judged only with a database.
10
10
  */
11
11
  const captureFileIssues = (models, events, sql) => {
@@ -4,7 +4,6 @@ import { servedAdmin } from "../project/served-admin.js";
4
4
  import { checkStartup } from "../serve/startup-checks.js";
5
5
  import { randomBytes } from "node:crypto";
6
6
  import pg from "pg";
7
- import { checkJobsSchema } from "@protobase/server";
8
7
  import { readOrigins, readPasskeyDomain } from "@protobase/server/internal";
9
8
  import { Kysely, PostgresDialect } from "kysely";
10
9
  //#region src/doctor/startup.ts
@@ -42,7 +41,7 @@ const checkServerBuild = async (config) => {
42
41
  };
43
42
  /**
44
43
  * Builds the app from its config over `database` as `serve` does and runs the server's startup checks of the database,
45
- * its jobs schema included, so doctor refuses what the server would refuse to start on, with the server's own message.
44
+ * the jobs schema with the record of migrations, so doctor refuses what the server would refuse to start on, with the server's own message.
46
45
  * The environment's settings, such as the assistant's key, are the running app's and are not checked here; sign-in is
47
46
  * built only to read its store, so without the app's URL and secret it gets stand-ins for them (`startupUrl`).
48
47
  * It checks the app as `serve` runs it, from protobase.config.ts and the convention's config folder, whatever folder
@@ -51,9 +50,8 @@ const checkServerBuild = async (config) => {
51
50
  const checkServerStartup = async (config, database) => {
52
51
  const project = await buildProject(startupConfig(config), database);
53
52
  await checkStartup(project, database.db);
54
- const { admin, jobs } = await servedAdmin(project, database.db);
53
+ const { admin } = await servedAdmin(project, database.db);
55
54
  await admin.stopHolding();
56
- if (jobs.length > 0) await checkJobsSchema(database.db);
57
55
  };
58
56
  //#endregion
59
57
  export { checkServerBuild, checkServerStartup, startupUrl };
@@ -3,6 +3,7 @@ import { fillRow } from "./record/fill-row.js";
3
3
  import { readMigrationDir } from "./record/migration-dir.js";
4
4
  import { pendingIn, unfinishedIds } from "./record/pending.js";
5
5
  import { runAfter } from "./record/run-after.js";
6
+ import { forceSetting } from "@protobase/server/internal";
6
7
  //#region src/migration/apply-migrations.ts
7
8
  const lockKey = 7311946202;
8
9
  const executeFile = "do $migration$ begin execute current_setting('migrations.file'); end $migration$";
@@ -37,7 +38,8 @@ const transaction = async (sql, run) => {
37
38
  await sql`commit`;
38
39
  return result;
39
40
  };
40
- const applyBatch = (tx, batch, out) => transaction(tx, async () => {
41
+ const applyBatch = (tx, batch, out, force) => transaction(tx, async () => {
42
+ if (force) await tx`select set_config(${forceSetting}, 'true', true)`;
41
43
  for (const migration of batch) {
42
44
  out(`applying ${migration.file}\n`);
43
45
  await tx`select set_config('migrations.file', ${migration.text}, true)`;
@@ -54,7 +56,7 @@ const finishUnfinished = async (sql, ids, migrations, out) => {
54
56
  await runAfter(sql, id, migration.after.text);
55
57
  }
56
58
  };
57
- const apply = async (session, migrations, out) => {
59
+ const apply = async (session, migrations, out, force) => {
58
60
  const { pending, unfinished } = await transaction(session, async () => {
59
61
  const [record] = await session`select to_regclass('migrations.applied') is null as fresh`;
60
62
  await session`create schema if not exists migrations`;
@@ -67,7 +69,7 @@ const apply = async (session, migrations, out) => {
67
69
  });
68
70
  await finishUnfinished(session, unfinished, migrations, out);
69
71
  for (const batch of batches(pending)) {
70
- await applyBatch(session, batch, out);
72
+ await applyBatch(session, batch, out, force);
71
73
  const last = batch.at(-1);
72
74
  if (!last.after) continue;
73
75
  out(`running ${last.after.file}\n`);
@@ -82,16 +84,17 @@ const apply = async (session, migrations, out) => {
82
84
  * when a file fails none of its batch is applied: a batch ends at a file with an `.after.sql`, whose statements then
83
85
  * run outside a transaction before the next batch, and set its row's `completed_at`. A migration a stopped run left
84
86
  * unfinished is finished first. The lock is released at the end, or with the connection when that is lost. Run it
85
- * before a new version serves, while nothing else writes. Returns the names it applied.
87
+ * before a new version serves, while nothing else writes. With `force`, each transaction sets `protobase.force`, which
88
+ * lets a sign-in module turned on again bring back the rows its kept tables hold. Returns the names it applied.
86
89
  */
87
- const applyMigrations = async (sql, dir, out) => {
90
+ const applyMigrations = async (sql, dir, out, { force = false } = {}) => {
88
91
  const migrations = await readMigrationDir(dir);
89
92
  const session = await sql.reserve();
90
93
  try {
91
94
  const [lock] = await session`select pg_try_advisory_lock(${lockKey}) as locked`;
92
95
  if (!lock.locked) throw new Error(lockTaken);
93
96
  const unlock = () => session`select pg_advisory_unlock(${lockKey})`;
94
- const applied = await apply(session, migrations, out).catch(async (error) => {
97
+ const applied = await apply(session, migrations, out, force).catch(async (error) => {
95
98
  if (!connectionLost(error)) await unlock();
96
99
  throw error;
97
100
  });
@@ -0,0 +1,31 @@
1
+ import pg from "pg";
2
+ import { schemaModules, targetIds } from "@protobase/server/internal";
3
+ import { Kysely, PostgresDialect } from "kysely";
4
+ //#region src/migration/baseline/read-live-modules.ts
5
+ /** What the database at `url` has of each schema module of `targets`, read once from its catalogue; a module it lacks is left out. */
6
+ const readLiveModules = async (url, targets) => {
7
+ const db = new Kysely({ dialect: new PostgresDialect({ pool: new pg.Pool({
8
+ connectionString: url,
9
+ max: 1
10
+ }) }) });
11
+ try {
12
+ const found = {};
13
+ for (const id of targetIds(targets)) {
14
+ const model = await schemaModules[id].read(db, targets[id]);
15
+ if (model) found[id] = model;
16
+ }
17
+ return found;
18
+ } finally {
19
+ await db.destroy();
20
+ }
21
+ };
22
+ /** The lines that say what a baseline found of the schema modules, one each. */
23
+ const describedModules = (modules) => Object.entries(modules).map(([id, { lastStep, replaceables, resources }]) => {
24
+ const module = schemaModules[id];
25
+ const versions = Object.entries(replaceables).map(([name, version]) => `, its ${name} at version ${version}`).join("");
26
+ const perResource = Object.entries(resources ?? {}).map(([name, entries]) => `, its ${name} of ${Object.keys(entries).join(", ")}`).join("");
27
+ const step = lastStep === 0 ? "before its first step" : `at step ${lastStep} (${module.steps[lastStep - 1].name})`;
28
+ return `-- ${module.title}: ${step}${versions}${perResource}.`;
29
+ });
30
+ //#endregion
31
+ export { describedModules, readLiveModules };
@@ -1,9 +1,11 @@
1
+ import { stepsOfVersions } from "@protobase/server/internal";
1
2
  import postgres from "postgres";
2
3
  //#region src/migration/baseline/read-live-store.ts
3
4
  /**
4
5
  * The auth store at `url` as its schema has it, read once in a read-only transaction: every relation of the store's
5
- * schema with its kind and columns, and the versions its `auth_migrations` records. Refuses a store without that
6
- * table, one made before 0.48, which `protobase auth migration` adopts first.
6
+ * schema with its kind and columns, and the parts of steps it recorded: in `auth_steps`, or for a store without it, by
7
+ * version in `auth_migrations`. Refuses a store with neither, one made before 0.48, which `protobase auth migration`
8
+ * adopts first.
7
9
  */
8
10
  const readLiveStore = async (url, names) => {
9
11
  const sql = postgres(url, {
@@ -11,6 +13,7 @@ const readLiveStore = async (url, names) => {
11
13
  onnotice: () => {}
12
14
  });
13
15
  const record = names.names.table("auth_migrations");
16
+ const steps = names.names.table("auth_steps");
14
17
  try {
15
18
  return await sql.begin("read only", async (tx) => {
16
19
  const rows = await tx`
@@ -22,9 +25,20 @@ const readLiveStore = async (url, names) => {
22
25
  kind,
23
26
  columns
24
27
  }]));
25
- if (!relations[record.name]) throw new Error(`The auth store has no ${record.name} table, as a store made before 0.48: adopt it with \`protobase auth migration\` and apply that file first`);
28
+ if (relations[steps.name]) {
29
+ const { module, step, target } = steps.columns;
30
+ return {
31
+ applied: (await tx.unsafe(`select ${String(module)} as module, ${String(step)} as step, ${String(target)} as target from ${String(steps)}`)).map((part) => ({
32
+ ...part,
33
+ step: Number(part.step)
34
+ })),
35
+ relations
36
+ };
37
+ }
38
+ if (!relations[record.name]) throw new Error(`The auth store has neither ${steps.name} nor ${record.name}, as a store made before 0.48: adopt it with \`protobase auth migration\` and apply that file first`);
39
+ const versions = await tx.unsafe(`select ${String(record.columns.version)} as version from ${String(record)} order by 1`);
26
40
  return {
27
- versions: (await tx.unsafe(`select ${String(record.columns.version)} as version from ${String(record)} order by 1`)).map(({ version }) => Number(version)),
41
+ applied: stepsOfVersions(versions.map(({ version }) => Number(version))),
28
42
  relations
29
43
  };
30
44
  });
@@ -1,39 +1,72 @@
1
+ import { organizationsNow } from "../snapshot/auth-target.js";
1
2
  import { readSnapshot, snapshotFile } from "../snapshot/snapshot-file.js";
2
3
  import { readMigrationFiles } from "../snapshot/migration-files.js";
3
4
  import { refuseInconsistent } from "../snapshot/consistency.js";
4
5
  import { writeMigrationFile } from "../snapshot/write-file.js";
6
+ import { describedModules, readLiveModules } from "./read-live-modules.js";
5
7
  import { readLiveStore } from "./read-live-store.js";
6
- import { baselineStore, storeModel } from "@protobase/server/internal";
8
+ import { baselineStore, stepRecordMigration, storeModel, targetIds } from "@protobase/server/internal";
7
9
  //#region src/migration/baseline/write-baseline.ts
8
- const body = `-- Written by \`protobase migration baseline\` from the database: the auth store as the project's earlier migrations made it.
9
- -- It changes nothing and drops nothing; it starts ${snapshotFile}, and \`protobase migration\` writes what the store lacks from it.
10
+ const intro = `-- Written by \`protobase migration baseline\` from the database: the auth store as the project's earlier migrations made it.
11
+ -- It drops nothing, and changes nothing but the record of the store's steps, made from auth_migrations where the store
12
+ -- has none; it starts ${snapshotFile}, and \`protobase migration\` writes what the store lacks from it.
13
+ `;
14
+ const modulesIntro = `-- Written by \`protobase migration baseline\` from the database: the schema modules the project's earlier migrations
15
+ -- made, which ${snapshotFile} did not record. It changes nothing; \`protobase migration\` writes what they lack from it.
10
16
  `;
11
17
  /**
12
- * `protobase migration baseline`: describes the auth store of a project without a snapshot, as its database has it,
13
- * in a numbered migration that only records itself and the snapshot that ends at it, once. Each module that is on is
14
- * at the step `auth_migrations` records, a module that is off but has tables is kept, organizations count as ever on
15
- * when a table whose rows belong to one has the column that names it, and a user table another system made is
16
- * external. Returns the file's path.
18
+ * `protobase migration baseline`: describes, as the database has them, the auth store of a project without a snapshot
19
+ * and each schema module the config needs that the snapshot lacks, such as one an earlier version's migration made,
20
+ * in a numbered migration that only records itself, and the store's steps where it records them by version alone,
21
+ * and the snapshot that ends at it, once. Each module of the store that is on is at the step `auth_migrations` records,
22
+ * a module that is off but has tables is kept, organizations count as ever on when a table whose rows belong to one has
23
+ * the column that names it, and a user table another system made is external. A schema module is at the step its
24
+ * catalogue shows (`SchemaModule.read`). Returns the file's path.
17
25
  */
18
- const writeBaseline = async ({ projectDir, dir, auth, url, protobaseVersion, newId }) => {
19
- if (await readSnapshot(projectDir)) throw new Error(`The project has ${snapshotFile} already: a baseline only starts it, and \`protobase migration\` goes on from it`);
20
- refuseInconsistent(void 0, await readMigrationFiles(dir));
21
- const store = baselineStore(auth.names, await readLiveStore(url, auth.names));
26
+ const writeBaseline = async ({ projectDir, dir, auth, modules, url, protobaseVersion, newId }) => {
27
+ const snapshot = await readSnapshot(projectDir);
28
+ refuseInconsistent(snapshot, await readMigrationFiles(dir));
29
+ const live = await readLiveModules(url, Object.fromEntries(targetIds(modules).filter((id) => !snapshot?.model.modules?.[id]).map((id) => [id, modules[id]])));
30
+ const found = Object.keys(live).length > 0;
31
+ const described = describedModules(live).join("\n");
32
+ if (snapshot) {
33
+ if (!found) throw new Error(`The project has ${snapshotFile} already, and it records every schema module the database has: \`protobase migration\` goes on from it`);
34
+ const draft = {
35
+ previous: snapshot,
36
+ auth: snapshot.model.auth,
37
+ modules: {
38
+ ...snapshot.model.modules,
39
+ ...live
40
+ },
41
+ organizations: organizationsNow(auth),
42
+ protobaseVersion
43
+ };
44
+ return writeMigrationFile(projectDir, dir, {
45
+ name: "baseline",
46
+ body: `${modulesIntro}${described}\n`,
47
+ additive: true
48
+ }, draft, newId());
49
+ }
50
+ if (!auth && !found) throw new Error("Sign-in is off in the project's config, and the database has none of the schema modules it needs: there is nothing to describe, and `protobase migration` writes them");
51
+ const store = auth && baselineStore(auth.names, await readLiveStore(url, auth.names));
52
+ const modulesText = found ? `${described}\n` : "";
53
+ const body = !store ? `${modulesIntro}${modulesText}` : store.stepRecord ? `${intro}${modulesText}` : `${intro}${modulesText}\n${stepRecordMigration(auth.names)}\n`;
22
54
  const decisions = {
23
55
  modules: {
24
- kept: store.kept,
56
+ kept: store?.kept ?? [],
25
57
  archived: []
26
58
  },
27
59
  organizations: {
28
- everOn: store.organizationsEverOn,
60
+ everOn: store?.organizationsEverOn ?? false,
29
61
  defaultOrganization: null
30
62
  },
31
- external: store.external
63
+ external: store?.external ?? []
32
64
  };
33
65
  const draft = {
34
66
  previous: void 0,
35
- auth: storeModel(auth.names, store.lastSteps),
36
- organizationsOn: auth.organizationsOn,
67
+ auth: store ? storeModel(auth.names, store.lastSteps) : void 0,
68
+ modules: found ? live : void 0,
69
+ organizations: organizationsNow(auth),
37
70
  protobaseVersion,
38
71
  decisions
39
72
  };
@@ -9,9 +9,9 @@ const migrationsDir = "db/migrations";
9
9
  * The CLI's `migrate`: applies the project's db/migrations to the database, as the runtime's `migrate` applies a
10
10
  * bundle's (see applyMigrations). It runs none of the project's code, so it needs no package.json or install. The
11
11
  * connection is asked for only when there is something to apply. With `plan`, it prints what it would apply instead
12
- * (see planMigrations).
12
+ * (see planMigrations); with `force`, a sign-in module turned on again brings back the rows its tables kept.
13
13
  */
14
- const migrateProject = async (projectDir, connectionUrl, out, plan = false) => {
14
+ const migrateProject = async (projectDir, connectionUrl, out, { plan = false, force = false } = {}) => {
15
15
  const dir = path.join(projectDir, migrationsDir);
16
16
  if (!existsSync(dir)) {
17
17
  out(`the project has no ${migrationsDir}\n`);
@@ -22,7 +22,7 @@ const migrateProject = async (projectDir, connectionUrl, out, plan = false) => {
22
22
  onnotice: () => {}
23
23
  });
24
24
  try {
25
- await (plan ? planMigrations(sql, dir, out) : applyMigrations(sql, dir, out));
25
+ await (plan ? planMigrations(sql, dir, out) : applyMigrations(sql, dir, out, { force }));
26
26
  } finally {
27
27
  await sql.end();
28
28
  }