@protobase/cli 0.51.3 → 0.52.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 (54) hide show
  1. package/dist/build/app-icons.js +2 -1
  2. package/dist/build/favicon-file.js +5 -0
  3. package/dist/build/favicon-ico.js +20 -0
  4. package/dist/build/favicon.js +1 -2
  5. package/dist/build/service-worker-code.js +1 -1
  6. package/dist/cli/package.js +1 -1
  7. package/dist/config/build-project.js +1 -0
  8. package/dist/dev/entry.js +2 -1
  9. package/dist/doctor/relation-issues.js +13 -0
  10. package/dist/doctor/run.js +6 -1
  11. package/dist/migration/adopt-public-record.js +15 -0
  12. package/dist/migration/apply-migrations.js +8 -4
  13. package/dist/migration/load-project.js +1 -0
  14. package/dist/migration/parts.js +6 -1
  15. package/dist/project/favicon-link.js +12 -2
  16. package/dist/project/project-admin.js +1 -0
  17. package/dist/project/service-worker.js +1 -1
  18. package/dist/scaffold/plan.d.ts +2 -0
  19. package/dist/scaffold/plan.js +7 -3
  20. package/dist/scaffold/protobase-tables.d.ts +1 -1
  21. package/dist/scaffold/protobase-tables.js +8 -1
  22. package/dist/scaffold/referenced.d.ts +6 -0
  23. package/dist/scaffold/referenced.js +38 -0
  24. package/dist/scaffold/run.js +2 -1
  25. package/dist/scaffold/tables.d.ts +2 -1
  26. package/dist/scaffold/tables.js +18 -9
  27. package/dist/scaffold-api.d.ts +2 -1
  28. package/dist/scaffold-api.js +2 -1
  29. package/dist/serve/lifecycle.js +2 -1
  30. package/dist/serve/static-site.js +3 -0
  31. package/dist/supabase/dump-phase.js +6 -5
  32. package/dist/supabase/load-phase.js +5 -6
  33. package/dist/supabase/platform-schemas.js +42 -0
  34. package/dist/supabase/project-users.d.ts +10 -0
  35. package/dist/supabase/project-users.js +38 -0
  36. package/dist/supabase/report.js +1 -1
  37. package/dist/supabase/source-facts.js +3 -35
  38. package/dist/supabase/users-migrations.js +2 -2
  39. package/package.json +7 -7
  40. package/skills/protobase/references/features/ai.md +5 -0
  41. package/skills/protobase/references/features/compatibility.md +1 -1
  42. package/skills/protobase/references/features/look-and-language.md +1 -1
  43. package/skills/protobase/references/getting-started.md +5 -3
  44. package/skills/protobase/references/guides/deploy.md +1 -1
  45. package/skills/protobase/references/reference/app-identity.md +3 -1
  46. package/skills/protobase/references/reference/assistant.md +2 -2
  47. package/skills/protobase/references/reference/cli.md +7 -7
  48. package/skills/protobase/references/reference/comments.md +2 -0
  49. package/skills/protobase/references/reference/config/api.md +13 -2
  50. package/skills/protobase/references/reference/config.md +1 -1
  51. package/skills/protobase/references/reference/mcp.md +43 -10
  52. package/skills/protobase/references/reference/notifications.md +1 -1
  53. package/skills/protobase/references/reference/supabase-realtime.md +4 -2
  54. package/skills/protobase/references/reference/webhooks.md +1 -0
@@ -1,4 +1,5 @@
1
- import { buildFavicon, faviconFile } from "./favicon.js";
1
+ import { faviconFile } from "./favicon-file.js";
2
+ import { buildFavicon } from "./favicon.js";
2
3
  import { existsSync } from "node:fs";
3
4
  import path from "node:path";
4
5
  import { copyFile, readFile } from "node:fs/promises";
@@ -0,0 +1,5 @@
1
+ //#region src/build/favicon-file.ts
2
+ /** The project's favicon, at its root, and where a bundle's `public` folder has it: the app links it at `/protobase.favicon.svg`. */
3
+ const faviconFile = "protobase.favicon.svg";
4
+ //#endregion
5
+ export { faviconFile };
@@ -0,0 +1,20 @@
1
+ import { faviconFile } from "./favicon-file.js";
2
+ import { existsSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { pngIcons } from "@protobase/schema/png-icons";
5
+ //#region src/build/favicon-ico.ts
6
+ /** The path browsers and favicon services ask a site's icon at when its page names none, such as before they load it. */
7
+ const faviconIcoPath = "/favicon.ico";
8
+ const candidates = [
9
+ pngIcons.icon192.file,
10
+ pngIcons.appleTouch.file,
11
+ pngIcons.icon512.file,
12
+ faviconFile
13
+ ];
14
+ /**
15
+ * The file in `dir` that `/favicon.ico` answers with: the app's icon as a PNG when it has one, else its favicon. The
16
+ * response names the file's own type, PNG or SVG, which clients follow over the `.ico` in the path.
17
+ */
18
+ const faviconIcoFile = (dir) => candidates.map((file) => path.join(dir, file)).find((file) => existsSync(file));
19
+ //#endregion
20
+ export { faviconIcoFile, faviconIcoPath };
@@ -1,10 +1,9 @@
1
1
  import { adminAppDir } from "../project/admin-app.js";
2
+ import { faviconFile } from "./favicon-file.js";
2
3
  import { existsSync } from "node:fs";
3
4
  import path from "node:path";
4
5
  import { copyFile } from "node:fs/promises";
5
6
  //#region src/build/favicon.ts
6
- /** The project's favicon, at its root, and where a bundle's `public` folder has it: the app links it at `/protobase.favicon.svg`. */
7
- const faviconFile = "protobase.favicon.svg";
8
7
  const defaultFavicon = path.join(adminAppDir, "favicon.svg");
9
8
  /** The favicon the app shows for the project in `projectDir`: its protobase.favicon.svg, or Protobase's without one. */
10
9
  const projectFavicon = (projectDir) => {
@@ -1,4 +1,4 @@
1
- import { faviconFile } from "./favicon.js";
1
+ import { faviconFile } from "./favicon-file.js";
2
2
  import { pushHandlersCode } from "./service-worker-push-code.js";
3
3
  import { themeFile } from "./theme.js";
4
4
  import { serviceWorkerFile as serviceWorkerFile$1 } from "@protobase/schema/internal";
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.51.3";
2
+ var version = "0.52.0";
3
3
  //#endregion
4
4
  export { version };
@@ -68,6 +68,7 @@ const buildProject = async (config, database) => {
68
68
  ...config.events && { events: config.events },
69
69
  ...config.history && { history: config.history },
70
70
  ...webhooks && { webhooks },
71
+ ...config.realtime && { realtime: config.realtime },
71
72
  ...notifications && { notifications },
72
73
  ...mailer && { mailer },
73
74
  ...config.mobile && { mobile: config.mobile },
package/dist/dev/entry.js CHANGED
@@ -6,7 +6,7 @@ import { devJobs } from "./dev-jobs.js";
6
6
  import { devDatabase, loadDevConfig } from "./project.js";
7
7
  import { withDevServiceWorker } from "./service-worker-route.js";
8
8
  import { setMissing, supabaseEnv } from "./supabase-env.js";
9
- import { apiKeySettings, assistantSettings, authSchemaDrift, authStoreTables, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkNotificationsSchema, checkQueryRunner, checkResourcesOutsideAuthStore, checkWebhooksSchema, configExports, hasUsers } from "@protobase/server";
9
+ import { apiKeySettings, assistantSettings, authSchemaDrift, authStoreTables, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkNotificationsSchema, checkQueryRunner, checkRealtimeRelay, checkResourcesOutsideAuthStore, checkWebhooksSchema, configExports, hasUsers, relayed } from "@protobase/server";
10
10
  import { upgradeWebSocket } from "@hono/node-server";
11
11
  import { Hono } from "hono";
12
12
  //#region src/dev/entry.ts
@@ -33,6 +33,7 @@ checkAi({
33
33
  env: process.env
34
34
  });
35
35
  if (project.webhooks) await checkWebhooksSchema(db, project.webhooks);
36
+ if (relayed(project.realtime)) await checkRealtimeRelay(db);
36
37
  if (project.notifications) await checkNotificationsSchema(db, project.notifications, project.auth);
37
38
  setMissing(process.env, supabaseEnv({
38
39
  url: process.env.PROTOBASE_DEV_URL,
@@ -0,0 +1,13 @@
1
+ //#region src/doctor/relation-issues.ts
2
+ const relationIssues = (model, models) => Object.entries(model.fields).flatMap(([name, field]) => {
3
+ const resource = field.relation?.resource;
4
+ if (!resource || models.some((each) => each.name === resource)) return [];
5
+ return [{
6
+ severity: "error",
7
+ resource: model.name,
8
+ message: `${name}: points to resource "${resource}", which the config does not declare`,
9
+ suggestion: `declare it, or scaffold its table with \`protobase scaffold\``
10
+ }];
11
+ });
12
+ //#endregion
13
+ export { relationIssues };
@@ -5,6 +5,7 @@ import { readOnlyDb } from "../db/read-only-db.js";
5
5
  import { checkResource } from "./check.js";
6
6
  import { indexIssues } from "./index-issues.js";
7
7
  import { readShapes } from "./read-shapes.js";
8
+ import { relationIssues } from "./relation-issues.js";
8
9
  import { existsSync } from "node:fs";
9
10
  import path from "node:path";
10
11
  import { tableIndexes } from "@protobase/query";
@@ -20,7 +21,11 @@ const runDoctor = async (options, out) => {
20
21
  const db = readOnlyDb(options.url);
21
22
  const shapes = readShapes(config);
22
23
  const indexes = await Promise.all(models.map(async (model) => indexIssues(model, await tableIndexes(db, model), shapes))).finally(() => db.destroy());
23
- const issues = models.flatMap((model, i) => [...checkResource(model, tables), ...indexes[i]]);
24
+ const issues = models.flatMap((model, i) => [
25
+ ...checkResource(model, tables),
26
+ ...relationIssues(model, models),
27
+ ...indexes[i]
28
+ ]);
24
29
  for (const issue of issues) out(format(issue));
25
30
  const errors = issues.filter((i) => i.severity === "error").length;
26
31
  out(`Checked ${models.length} resources: ${errors} errors, ${issues.length - errors} warnings.\n`);
@@ -0,0 +1,15 @@
1
+ //#region src/migration/adopt-public-record.ts
2
+ /**
3
+ * Copies the record of applied migrations an earlier Protobase kept in `public.schema_migrations` into
4
+ * `migrations.applied`, so a database it migrated applies nothing twice. It reads that table only when it has
5
+ * Protobase's columns, `name` and `applied_at`: a version-keyed `schema_migrations` another migration tool owns is
6
+ * never read or written. The old table stays, for a version still serving or rolled back to.
7
+ */
8
+ const adoptPublicRecord = async (tx) => {
9
+ if ((await tx`
10
+ select column_name from information_schema.columns
11
+ where table_schema = 'public' and table_name = 'schema_migrations' and column_name in ('name', 'applied_at')`).length < 2) return;
12
+ await tx`insert into migrations.applied (name, applied_at) select name, applied_at from public.schema_migrations`;
13
+ };
14
+ //#endregion
15
+ export { adoptPublicRecord };
@@ -1,10 +1,11 @@
1
+ import { adoptPublicRecord } from "./adopt-public-record.js";
1
2
  import path from "node:path";
2
3
  import { readFile, readdir } from "node:fs/promises";
3
4
  //#region src/migration/apply-migrations.ts
4
5
  const lockKey = 7311946202;
5
6
  const executeFile = "do $migration$ begin execute current_setting('migrations.file'); end $migration$";
6
7
  /**
7
- * Applies the `*.sql` files of `dir` not yet recorded in `public.schema_migrations`, in file name order and in one
8
+ * Applies the `*.sql` files of `dir` not yet recorded in `migrations.applied`, in file name order and in one
8
9
  * transaction behind an advisory lock: when one fails, none is applied. Run it before a new version serves, while
9
10
  * nothing else writes. Returns the names it applied.
10
11
  */
@@ -12,14 +13,17 @@ const applyMigrations = async (sql, dir, out) => {
12
13
  const files = (await readdir(dir)).filter((file) => file.endsWith(".sql")).sort();
13
14
  const applied = await sql.begin(async (tx) => {
14
15
  await tx`select pg_advisory_xact_lock(${lockKey})`;
15
- await tx`create table if not exists public.schema_migrations (name text primary key, applied_at timestamptz not null default now())`;
16
- const done = new Set((await tx`select name from public.schema_migrations`).map((row) => row.name));
16
+ const [record] = await tx`select to_regclass('migrations.applied') is null as fresh`;
17
+ await tx`create schema if not exists migrations`;
18
+ await tx`create table if not exists migrations.applied (name text primary key, applied_at timestamptz not null default now())`;
19
+ if (record.fresh) await adoptPublicRecord(tx);
20
+ const done = new Set((await tx`select name from migrations.applied`).map((row) => row.name));
17
21
  const pending = files.filter((file) => !done.has(file));
18
22
  for (const file of pending) {
19
23
  out(`applying ${file}\n`);
20
24
  await tx`select set_config('migrations.file', ${await readFile(path.join(dir, file), "utf8")}, true)`;
21
25
  await tx.unsafe(executeFile);
22
- await tx`insert into public.schema_migrations (name) values (${file})`;
26
+ await tx`insert into migrations.applied (name) values (${file})`;
23
27
  }
24
28
  return pending;
25
29
  });
@@ -38,6 +38,7 @@ const migrationProject = async (config, url) => {
38
38
  ...auth && { auth },
39
39
  ...config.events && { events: config.events },
40
40
  ...webhooks && { webhooks },
41
+ ...config.realtime && { realtime: config.realtime },
41
42
  ...notifications && { notifications },
42
43
  jobs,
43
44
  readOnlyQueries: assistantSettings(config.assistant, process.env)?.kind === "built-in",
@@ -1,5 +1,5 @@
1
1
  import { authMigrationTitle } from "../auth/migration-file.js";
2
- import { authSchemaMigration, changesMigration, commentsMigration, computedMigration, isCaptured, jobsSchemaMigration, notificationsMigration, queryRunnerMigration, webhooksMigration } from "@protobase/server";
2
+ import { authSchemaMigration, changesMigration, commentsMigration, computedMigration, isCaptured, jobsSchemaMigration, notificationsMigration, queryRunnerMigration, realtimeRelayMigration, relayed, webhooksMigration } from "@protobase/server";
3
3
  //#region src/migration/parts.ts
4
4
  /** Every feature the project's config enables, in the order their files are written. */
5
5
  const migrationParts = (project) => {
@@ -45,6 +45,11 @@ const migrationParts = (project) => {
45
45
  name: "notifications",
46
46
  title: "The tables of notifications",
47
47
  sql: () => notificationsMigration(project.db, project.notifications, project.auth)
48
+ }] : [],
49
+ ...relayed(project.realtime) ? [{
50
+ name: "realtime_relay",
51
+ title: "The relay of Realtime broadcasts and presence between the processes serving the app",
52
+ sql: () => realtimeRelayMigration(project.db)
48
53
  }] : []
49
54
  ];
50
55
  };
@@ -1,4 +1,6 @@
1
- import { faviconFile, projectFavicon } from "../build/favicon.js";
1
+ import { faviconFile } from "../build/favicon-file.js";
2
+ import { projectFavicon } from "../build/favicon.js";
3
+ import { faviconIcoFile, faviconIcoPath } from "../build/favicon-ico.js";
2
4
  import { existsSync } from "node:fs";
3
5
  import path from "node:path";
4
6
  import { readFile } from "node:fs/promises";
@@ -9,7 +11,7 @@ import { pngIcons } from "@protobase/schema/png-icons";
9
11
  * `/protobase.apple-touch-icon.png`, which Safari takes for the home screen as it takes no SVG. A bundle always has
10
12
  * the favicon (see `buildFavicon`) and the touch icon when the project has one (see `buildIcons`); without it Safari
11
13
  * shows a picture of the page instead. The dev server answers them from the project's files, the favicon Protobase's
12
- * without one, and the project's other PNG icons the same way.
14
+ * without one, the project's other PNG icons the same way, and `/favicon.ico` as a bundle's server does (see `faviconIcoFile`).
13
15
  */
14
16
  const faviconLink = (projectDir) => {
15
17
  let base = "/";
@@ -26,6 +28,14 @@ const faviconLink = (projectDir) => {
26
28
  response.end(body);
27
29
  }, next);
28
30
  });
31
+ server.middlewares.use(faviconIcoPath, (_request, response, next) => {
32
+ const file = (projectDir === void 0 ? void 0 : faviconIcoFile(projectDir)) ?? projectFavicon(projectDir);
33
+ readFile(file).then((body) => {
34
+ response.setHeader("content-type", path.extname(file) === ".png" ? "image/png" : "image/svg+xml");
35
+ response.setHeader("cache-control", "no-cache");
36
+ response.end(body);
37
+ }, next);
38
+ });
29
39
  for (const { file } of Object.values(pngIcons)) server.middlewares.use(`/${file}`, (_request, response, next) => {
30
40
  const own = projectDir === void 0 ? void 0 : path.join(projectDir, file);
31
41
  if (!own || !existsSync(own)) return next();
@@ -26,6 +26,7 @@ const projectAdmin = (project, db, ui, reporter, upgradeWebSocket) => {
26
26
  ...project.events && { events: project.events },
27
27
  ...project.history && { history: project.history },
28
28
  ...project.webhooks && { webhooks: project.webhooks },
29
+ ...project.realtime && { realtime: project.realtime },
29
30
  ...project.notifications && { notifications: project.notifications },
30
31
  ...project.mobile && { mobile: project.mobile },
31
32
  ...project.app && { app: project.app },
@@ -1,4 +1,4 @@
1
- import { faviconFile } from "../build/favicon.js";
1
+ import { faviconFile } from "../build/favicon-file.js";
2
2
  import { themeFile } from "../build/theme.js";
3
3
  import { serviceWorkerCode, serviceWorkerFile } from "../build/service-worker-code.js";
4
4
  import { createHash } from "node:crypto";
@@ -1,6 +1,7 @@
1
1
  import "./existing-config.js";
2
2
  import { Drift } from "./drift.js";
3
3
  import { ProtobaseSchema } from "./protobase-tables.js";
4
+ import { Referenced } from "./referenced.js";
4
5
  //#region src/scaffold/plan.d.ts
5
6
  export type FileChange = {
6
7
  path: string;
@@ -13,5 +14,6 @@ export type ScaffoldPlan = {
13
14
  warnings: string[];
14
15
  skipped: ProtobaseSchema[];
15
16
  live: string[];
17
+ referenced: Referenced[];
16
18
  };
17
19
  //#endregion
@@ -9,6 +9,7 @@ import { detectDrift } from "./drift.js";
9
9
  import { ensureExports } from "./index-file.js";
10
10
  import { assignNames } from "./resource-names.js";
11
11
  import { planResource } from "./resource-plan.js";
12
+ import { referencedTables } from "./referenced.js";
12
13
  import { dependencyOrder } from "./table-order.js";
13
14
  import { isExcluded, matchesTarget } from "./targets.js";
14
15
  import { uiFields } from "./ui-fields.js";
@@ -47,7 +48,7 @@ const planScaffold = async (input) => {
47
48
  const protobase = protobaseSchemas(tables, input.target);
48
49
  const skipped = protobase.map((found) => ({
49
50
  ...found,
50
- tables: found.tables.filter((table) => matchesTarget(input.target, table))
51
+ tables: found.tables.filter(wanted)
51
52
  })).filter((found) => found.tables.length > 0);
52
53
  const isProtobase = (table) => protobase.some((schema) => schema.tables.includes(table));
53
54
  const inProtobaseSchema = (view) => protobase.some(({ schema }) => schema === view.schema && schema !== "public");
@@ -57,7 +58,9 @@ const planScaffold = async (input) => {
57
58
  table,
58
59
  resourceNameOf: (schema, name) => names.get(`${schema}.${name}`) ?? name
59
60
  });
60
- const targets = dependencyOrder(tables.filter((table) => wanted(table) && !isProtobase(table)));
61
+ const candidates = tables.filter((table) => !isProtobase(table));
62
+ const { tables: included, referenced } = referencedTables(candidates, candidates.filter(wanted), (key) => byTable.has(key));
63
+ const targets = dependencyOrder(included);
61
64
  const changes = [];
62
65
  const drift = [];
63
66
  const warnings = skippedViews.map((view) => `${tableKey(view)}: a ${view.kind}, skipped; scaffold writes resources over tables, declare one over a view by hand`);
@@ -132,7 +135,8 @@ const planScaffold = async (input) => {
132
135
  drift,
133
136
  warnings,
134
137
  skipped,
135
- live
138
+ live,
139
+ referenced
136
140
  };
137
141
  };
138
142
  const registerExisting = async (input, planned) => {
@@ -2,7 +2,7 @@ import { DbTable } from "../db/model.js";
2
2
  //#region src/scaffold/protobase-tables.d.ts
3
3
  export type ProtobaseSchema = {
4
4
  schema: string;
5
- what: 'auth store' | 'job queue';
5
+ what: 'auth store' | 'job queue' | 'record of migrations';
6
6
  tables: DbTable[];
7
7
  };
8
8
  //#endregion
@@ -20,6 +20,7 @@ const authStore = (schema, tables) => {
20
20
  return tables.filter((table) => storeTableNames.includes(table.name) || table.name === user);
21
21
  };
22
22
  const jobQueue = (schema, tables) => schema === "jobs" && ["job", "version"].every((name) => tables.some((table) => table.name === name)) ? tables : [];
23
+ const migrationRecord = (schema, tables) => schema === "migrations" && tables.some((table) => table.name === "applied") ? tables : [];
23
24
  const protobaseSchemas = (tables, target) => [...bySchema(tables)].flatMap(([schema, own]) => {
24
25
  const store = authStore(schema, own);
25
26
  if (store.length > 0) return [{
@@ -29,10 +30,16 @@ const protobaseSchemas = (tables, target) => [...bySchema(tables)].flatMap(([sch
29
30
  }];
30
31
  if (target.schema === schema) return [];
31
32
  const queue = jobQueue(schema, own);
32
- return queue.length > 0 ? [{
33
+ if (queue.length > 0) return [{
33
34
  schema,
34
35
  what: "job queue",
35
36
  tables: queue
37
+ }];
38
+ const record = migrationRecord(schema, own);
39
+ return record.length > 0 ? [{
40
+ schema,
41
+ what: "record of migrations",
42
+ tables: record
36
43
  }] : [];
37
44
  });
38
45
  //#endregion
@@ -0,0 +1,6 @@
1
+ //#region src/scaffold/referenced.d.ts
2
+ export type Referenced = {
3
+ table: string;
4
+ by: string[];
5
+ };
6
+ //#endregion
@@ -0,0 +1,38 @@
1
+ import { tableKey } from "../db/model.js";
2
+ //#region src/scaffold/referenced.ts
3
+ /**
4
+ * The tables of `candidates` that `wanted` points to, directly or through others, and that have no resource yet: a
5
+ * relation names the resource of the table it points to, and the app refuses one whose resource is missing. Each
6
+ * names the tables pointing to it.
7
+ */
8
+ const referencedTables = (candidates, wanted, declared) => {
9
+ const byKey = new Map(candidates.map((table) => [tableKey(table), table]));
10
+ const included = new Set(wanted.map(tableKey));
11
+ const added = /* @__PURE__ */ new Map();
12
+ const visit = (table) => {
13
+ for (const foreignKey of table.foreignKeys) {
14
+ const key = tableKey({
15
+ schema: foreignKey.refSchema,
16
+ name: foreignKey.refTable
17
+ });
18
+ const target = byKey.get(key);
19
+ if (!target || declared(key)) continue;
20
+ const known = added.get(key);
21
+ if (known && !known.by.includes(tableKey(table))) known.by.push(tableKey(table));
22
+ if (included.has(key)) continue;
23
+ included.add(key);
24
+ added.set(key, {
25
+ table: key,
26
+ by: [tableKey(table)]
27
+ });
28
+ visit(target);
29
+ }
30
+ };
31
+ for (const table of wanted) visit(table);
32
+ return {
33
+ tables: candidates.filter((table) => included.has(tableKey(table))),
34
+ referenced: [...added.values()]
35
+ };
36
+ };
37
+ //#endregion
38
+ export { referencedTables };
@@ -12,7 +12,7 @@ const readText = (file) => readFile(file, "utf8").catch((error) => {
12
12
  if (error.code === "ENOENT") return void 0;
13
13
  throw error;
14
14
  });
15
- const skippedLine = ({ schema, what, tables }) => `skipped ${schema === "public" ? tables.map((table) => `public.${table.name}`).join(", ") : `schema ${schema}`}, Protobase's ${what}${what === "job queue" ? `; pass "${schema}" as the target to scaffold it anyway` : ""}\n`;
15
+ const skippedLine = ({ schema, what, tables }) => `skipped ${schema === "public" ? tables.map((table) => `public.${table.name}`).join(", ") : `schema ${schema}`}, Protobase's ${what}${what !== "auth store" ? `; pass "${schema}" as the target to scaffold it anyway` : ""}\n`;
16
16
  const write = async ({ path: file, after }) => {
17
17
  await mkdir(path.dirname(file), { recursive: true });
18
18
  await writeFile(file, after);
@@ -46,6 +46,7 @@ const runScaffold = async (options, out) => {
46
46
  if (plan.changes.length === 0) out("Nothing to do, config is up to date.\n");
47
47
  else if (options.dryRun) out(`${plan.changes.length} file(s) would change; nothing was written (--dry-run).\n`);
48
48
  for (const schema of plan.skipped) out(skippedLine(schema));
49
+ for (const { table, by } of plan.referenced) out(`included ${table}, which ${by.join(", ")} ${by.length === 1 ? "points" : "point"} to\n`);
49
50
  for (const warning of plan.warnings) out(`warning: ${warning}\n`);
50
51
  if (plan.drift.length > 0) {
51
52
  out("\nDrift:\n");
@@ -9,9 +9,10 @@ export type ScaffoldTable = {
9
9
  columns: number;
10
10
  references: string[];
11
11
  };
12
- /** `scaffoldTables` of the database at `url`, read in one read-only session. */
12
+ /** `scaffoldTables` of the database at `url`, read-only; Supabase's when it has the markers `import supabase` checks. */
13
13
  export declare const listTables: (url: string) => Promise<{
14
14
  tables: ScaffoldTable[];
15
15
  skipped: string[];
16
+ supabaseSchemas: string[];
16
17
  }>;
17
18
  //#endregion
@@ -2,21 +2,28 @@ import { connect } from "../db/connect.js";
2
2
  import { tableKey } from "../db/model.js";
3
3
  import { introspect } from "../db/introspect.js";
4
4
  import { keyColumns } from "../db/keys.js";
5
+ import { authStorageSchemas, databaseMarkers, missingMarkers, serviceSchemas } from "../supabase/platform-schemas.js";
5
6
  import { protobaseSchemas } from "./protobase-tables.js";
6
7
  //#region src/scaffold/tables.ts
8
+ const supabaseOwner = (schema) => schema === "auth" ? "Supabase Auth's" : schema === "storage" ? "Supabase Storage's" : "Supabase's platform's";
7
9
  /**
8
10
  * The tables of a database without a config yet that scaffold, run on all of them, writes resources over, and what it
9
- * leaves out, each with why: views, tables without a key, and Protobase's own tables, as one line per schema.
11
+ * leaves out, each with why: views, tables without a key, and Protobase's own tables, as one line per schema. On a
12
+ * Supabase database, `supabase`, the platform's schemas, auth among them, are Supabase's and left out too: `supabaseSchemas`
13
+ * names those it has, for scaffold to exclude.
10
14
  */
11
- const scaffoldTables = (relations) => {
12
- const tables = relations.filter((relation) => relation.kind === "table");
13
- const protobase = protobaseSchemas(tables, {});
15
+ const scaffoldTables = (relations, supabase = false) => {
16
+ const platform = supabase ? [...authStorageSchemas, ...serviceSchemas] : [];
17
+ const supabaseSchemas = [...new Set(relations.map((relation) => relation.schema).filter((schema) => platform.includes(schema)))].sort();
18
+ const app = relations.filter((relation) => !supabaseSchemas.includes(relation.schema));
19
+ const protobase = protobaseSchemas(app.filter((relation) => relation.kind === "table"), {});
14
20
  const isProtobase = (relation) => protobase.some(({ schema, tables }) => tables.includes(relation) || schema !== "public" && schema === relation.schema);
15
- const own = relations.filter((relation) => !isProtobase(relation));
21
+ const own = app.filter((relation) => !isProtobase(relation));
16
22
  const skipped = [
17
23
  ...own.filter((relation) => relation.kind !== "table").map((view) => `${tableKey(view)}: a ${view.kind}`),
18
24
  ...own.filter((table) => table.kind === "table" && !keyColumns(table)).map((table) => `${tableKey(table)}: no primary key or unique NOT NULL index`),
19
- ...protobase.map(({ schema, what }) => `schema ${schema}: Protobase's ${what}`)
25
+ ...protobase.map(({ schema, what }) => `schema ${schema}: Protobase's ${what}`),
26
+ ...supabaseSchemas.map((schema) => `schema ${schema}: ${supabaseOwner(schema)} own tables`)
20
27
  ];
21
28
  const importable = own.filter((table) => table.kind === "table" && keyColumns(table));
22
29
  const keys = new Set(importable.map(tableKey));
@@ -31,14 +38,16 @@ const scaffoldTables = (relations) => {
31
38
  columns: table.columns.length,
32
39
  references: referencesOf(table)
33
40
  })).sort((a, b) => tableKey(a).localeCompare(tableKey(b))),
34
- skipped
41
+ skipped,
42
+ supabaseSchemas
35
43
  };
36
44
  };
37
- /** `scaffoldTables` of the database at `url`, read in one read-only session. */
45
+ /** `scaffoldTables` of the database at `url`, read-only; Supabase's when it has the markers `import supabase` checks. */
38
46
  const listTables = async (url) => {
39
47
  const sql = connect(url);
40
48
  try {
41
- return scaffoldTables(await introspect(sql, { views: true }));
49
+ const supabase = missingMarkers(await databaseMarkers(sql)).length === 0;
50
+ return scaffoldTables(await introspect(sql, { views: true }), supabase);
42
51
  } finally {
43
52
  await sql.end();
44
53
  }
@@ -1,4 +1,5 @@
1
1
  import { ScaffoldTable, listTables } from "./scaffold/tables.js";
2
2
  import { asking } from "./scaffold/prompt.js";
3
3
  import { ScaffoldOptions, runScaffold } from "./scaffold/run.js";
4
- export { type ScaffoldOptions, type ScaffoldTable, asking, listTables, runScaffold };
4
+ import { useSupabaseUsers } from "./supabase/project-users.js";
5
+ export { type ScaffoldOptions, type ScaffoldTable, asking, listTables, runScaffold, useSupabaseUsers };
@@ -1,4 +1,5 @@
1
1
  import { listTables } from "./scaffold/tables.js";
2
2
  import { asking } from "./scaffold/prompt.js";
3
3
  import { runScaffold } from "./scaffold/run.js";
4
- export { asking, listTables, runScaffold };
4
+ import { useSupabaseUsers } from "./supabase/project-users.js";
5
+ export { asking, listTables, runScaffold, useSupabaseUsers };
@@ -9,7 +9,7 @@ import { startCleanupTimer } from "./cleanup-timer.js";
9
9
  import { closeSockets } from "./close-sockets.js";
10
10
  import { servedRelease } from "./mobile-release.js";
11
11
  import pg from "pg";
12
- import { assistantSettings, authStoreTables, backgroundSettled, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkJobsSchema, checkNotificationsSchema, checkQueryRunner, checkResourcesOutsideAuthStore, checkWebhooksSchema, configExports, createFileCleanup, startJobs } from "@protobase/server";
12
+ import { assistantSettings, authStoreTables, backgroundSettled, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkJobsSchema, checkNotificationsSchema, checkQueryRunner, checkRealtimeRelay, checkResourcesOutsideAuthStore, checkWebhooksSchema, configExports, createFileCleanup, relayed, startJobs } from "@protobase/server";
13
13
  import { createAdaptorServer, upgradeWebSocket } from "@hono/node-server";
14
14
  //#region src/serve/lifecycle.ts
15
15
  const listen = (server, port) => new Promise((resolve, reject) => {
@@ -40,6 +40,7 @@ const startServe = async ({ config, env, openDb = (url) => openAppDatabase(pg, u
40
40
  env: process.env
41
41
  });
42
42
  if (env.startupChecks && project.webhooks) await checkWebhooksSchema(db, project.webhooks);
43
+ if (env.startupChecks && relayed(project.realtime)) await checkRealtimeRelay(db);
43
44
  if (env.startupChecks && project.notifications) await checkNotificationsSchema(db, project.notifications, project.auth);
44
45
  const { admin, jobs: definitions } = projectAdmin(project, db, ui, reporter, upgradeWebSocket);
45
46
  if (env.startupChecks && definitions.length > 0) await checkJobsSchema(db);
@@ -1,3 +1,4 @@
1
+ import { faviconIcoFile } from "../build/favicon-ico.js";
1
2
  import path from "node:path";
2
3
  import { readFile, stat } from "node:fs/promises";
3
4
  import { getMimeType } from "hono/utils/mime";
@@ -52,6 +53,8 @@ const serveStaticSite = async (site, request) => {
52
53
  });
53
54
  const pathname = new URL(request.url).pathname;
54
55
  const appDir = shell?.dir ?? publicDir;
56
+ const icon = pathname === "/favicon.ico" ? faviconIcoFile(publicDir) : void 0;
57
+ if (icon) return fileResponse(publicDir, icon);
55
58
  const root = siteRoot(site, pathname);
56
59
  const file = await fileFor(root, pathname);
57
60
  if (file) return fileResponse(root, file);
@@ -1,22 +1,23 @@
1
1
  import { connect } from "../db/connect.js";
2
+ import { databaseMarkers, missingMarkers } from "./platform-schemas.js";
2
3
  import { planAuthConfig } from "./auth-config.js";
4
+ import { writeMigration } from "./migration-files.js";
5
+ import { authStoreMigrations } from "./store-migrations.js";
6
+ import { usersColumnsMigration } from "./users-migrations.js";
3
7
  import { checkoutMarkers } from "./checkout.js";
4
8
  import { cronPlan } from "./cron-plan.js";
5
9
  import { planFunctions } from "./functions/plan-functions.js";
6
10
  import { writeFunctions } from "./functions/write-functions.js";
7
11
  import { importPlan, probedExtensions } from "./import-plan.js";
8
12
  import { importState } from "./import-state.js";
9
- import { writeMigration } from "./migration-files.js";
10
13
  import { runPgTool } from "./pg-tools.js";
11
14
  import { realtimeMigration, realtimePolicies } from "./realtime-policies.js";
12
15
  import { replayScript } from "./replay.js";
13
16
  import { schemaMigration } from "./schema-migration.js";
14
17
  import { refuseSsoUsers, ssoUserCount } from "./sso-users.js";
15
- import { appSchemas, cronJobs, cronTimezone, databaseMarkers, dumpedTables, extensions, httpTriggers, hypertables, pgmqQueues, pgsodiumColumns, platformMigrationTables, realtimeTables, routinesIn, tablesSize, vaultSecretValues, vaultSecrets } from "./source-facts.js";
16
- import { authStoreMigrations } from "./store-migrations.js";
18
+ import { appSchemas, cronJobs, cronTimezone, dumpedTables, extensions, httpTriggers, hypertables, pgmqQueues, pgsodiumColumns, platformMigrationTables, realtimeTables, routinesIn, tablesSize, vaultSecretValues, vaultSecrets } from "./source-facts.js";
17
19
  import { ensureApiRoles, existingSchemas, existingTables } from "./target-checks.js";
18
20
  import { creatableExtensions } from "./target-extensions.js";
19
- import { usersColumnsMigration } from "./users-migrations.js";
20
21
  import path from "node:path";
21
22
  import { mkdir, readFile, rm } from "node:fs/promises";
22
23
  import { isSchedule } from "@protobase/server";
@@ -25,7 +26,7 @@ import postgres from "postgres";
25
26
  /** Fails unless the database at `sql` is Supabase's: its auth and storage schemas, and its own admin role. */
26
27
  const checkSupabase = async (sql) => {
27
28
  const markers = await databaseMarkers(sql);
28
- const missing = [...["auth", "storage"].filter((schema) => !markers.schemas.includes(schema)).map((schema) => `schema ${schema}`), ...markers.roles.includes("supabase_admin") ? [] : ["role supabase_admin"]];
29
+ const missing = missingMarkers(markers);
29
30
  if (missing.length > 0) throw new Error(`The source database is not a Supabase database: it lacks the ${missing.join(" and ")}`);
30
31
  return markers;
31
32
  };
@@ -1,24 +1,23 @@
1
1
  import { loadProjectAuth } from "../users/load-auth.js";
2
2
  import { connect } from "../db/connect.js";
3
+ import { authStorageSchemas } from "./platform-schemas.js";
3
4
  import { runScaffold } from "../scaffold/run.js";
4
5
  import { writeAuthMigration } from "../auth/write-migration.js";
6
+ import { writeMigration } from "./migration-files.js";
7
+ import { providerCounts } from "./identity-providers.js";
8
+ import { accountsMigration } from "./users-migrations.js";
5
9
  import { runDoctor } from "../doctor/run.js";
6
10
  import { convertedCronJobs } from "./cron-plan.js";
7
11
  import { importState } from "./import-state.js";
8
- import { writeMigration } from "./migration-files.js";
9
12
  import { runPgTool } from "./pg-tools.js";
10
13
  import { loadScript, qualified } from "./load-script.js";
11
14
  import { existingTables, filledTables, otherTables } from "./target-checks.js";
12
- import { providerCounts } from "./identity-providers.js";
13
- import { accountsMigration } from "./users-migrations.js";
14
15
  import { cronJobFilesInTheWay, writeCronJobs } from "./cron-jobs-write.js";
15
16
  import { importReport } from "./report.js";
16
17
  import { existsSync } from "node:fs";
17
18
  import path from "node:path";
18
19
  import { rm, writeFile } from "node:fs/promises";
19
20
  //#region src/supabase/load-phase.ts
20
- /** Schemas the import restores that scaffolding leaves alone: Supabase Auth's and Storage's own tables are no resources. */
21
- const platformSchemas = ["auth", "storage"];
22
21
  /**
23
22
  * Fails unless every dumped table exists on the target, created by the applied migration, and holds no rows yet, and
24
23
  * the project has none of the files the converted pg_cron jobs go to.
@@ -76,7 +75,7 @@ const runLoadPhase = async (options, out) => {
76
75
  await rm(state.data);
77
76
  if (replay) await rm(replay);
78
77
  out(`loaded ${manifest.tables.reduce((sum, table) => sum + table.rows, 0)} rows into ${manifest.tables.length} tables; each count matches the source\n`);
79
- const schemas = manifest.schemas.filter((schema) => !platformSchemas.includes(schema));
78
+ const schemas = manifest.schemas.filter((schema) => !authStorageSchemas.includes(schema));
80
79
  const sql = connect(options.targetUrl);
81
80
  const excludes = await otherTables(sql, schemas, manifest.tables).finally(() => sql.end());
82
81
  const realtime = manifest.realtimeTables.map((table) => `${table.schema}.${table.table}`);