@protobase/cli 0.47.1 → 0.49.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 (101) hide show
  1. package/dist/build/config-bundle.js +6 -1
  2. package/dist/build/entry-code.js +30 -17
  3. package/dist/cli/package.js +1 -1
  4. package/dist/config/build-project.js +70 -0
  5. package/dist/config/called-config.js +11 -0
  6. package/dist/config/config-defaults.js +30 -0
  7. package/dist/config/env-values.js +20 -0
  8. package/dist/config/lazy-imports.js +18 -0
  9. package/dist/config/merge-config.js +72 -0
  10. package/dist/config/project-files.js +48 -0
  11. package/dist/config/project-parts.js +201 -0
  12. package/dist/config/read-config.js +31 -0
  13. package/dist/config/source-config.js +37 -0
  14. package/dist/dev/api-child.js +2 -1
  15. package/dist/dev/api-process.d.ts +1 -0
  16. package/dist/dev/api-process.js +5 -2
  17. package/dist/dev/auth-drift-lines.js +8 -0
  18. package/dist/dev/create-db.js +2 -2
  19. package/dist/dev/entry.d.ts +5 -0
  20. package/dist/dev/entry.js +17 -12
  21. package/dist/dev/project.js +23 -47
  22. package/dist/dev/run.js +3 -2
  23. package/dist/main.js +3 -3
  24. package/dist/migration/load-project.js +34 -34
  25. package/dist/migration/parts.js +2 -2
  26. package/dist/migration/summary.js +2 -2
  27. package/dist/mobile/api-origin.js +4 -4
  28. package/dist/mobile/load-project.js +13 -12
  29. package/dist/mobile/register.js +1 -1
  30. package/dist/mobile/run.js +1 -1
  31. package/dist/organizations/register.js +1 -1
  32. package/dist/project/error-reporter.js +3 -3
  33. package/dist/project/import-project-file.js +4 -2
  34. package/dist/project/load-bundle-project.js +16 -25
  35. package/dist/project/load-data-config.js +2 -2
  36. package/dist/project/pg-db.js +10 -4
  37. package/dist/project/placeholder-secret.js +2 -2
  38. package/dist/project/project-admin.js +12 -11
  39. package/dist/scaffold/plan.js +7 -3
  40. package/dist/scaffold/protobase-tables.js +8 -13
  41. package/dist/scaffold/run.js +1 -1
  42. package/dist/serve/create-admin.js +9 -4
  43. package/dist/serve/host-module-ids.js +1 -0
  44. package/dist/serve/host-modules.js +3 -1
  45. package/dist/serve/lifecycle.js +19 -14
  46. package/dist/serve/load-bundle.js +41 -11
  47. package/dist/serve/mobile-release.js +1 -1
  48. package/dist/serve/serve-bundle.js +3 -3
  49. package/dist/supabase/auth-config.js +33 -28
  50. package/dist/supabase/config-jobs.js +28 -27
  51. package/dist/supabase/config-object.js +25 -0
  52. package/dist/supabase/cron-job-file.js +13 -14
  53. package/dist/supabase/cron-jobs-write.js +6 -12
  54. package/dist/supabase/cron-plan.js +3 -51
  55. package/dist/supabase/project-files.js +4 -9
  56. package/dist/supabase/report.js +3 -3
  57. package/dist/users/load-auth.js +16 -15
  58. package/dist/worker/start-worker.js +18 -15
  59. package/package.json +8 -6
  60. package/skills/protobase/SKILL.md +2 -1
  61. package/skills/protobase/references/features/notifications.md +1 -1
  62. package/skills/protobase/references/features/sign-in-and-accounts.md +1 -0
  63. package/skills/protobase/references/features/start-a-project.md +3 -0
  64. package/skills/protobase/references/getting-started.md +2 -2
  65. package/skills/protobase/references/guides/api-functions.md +4 -4
  66. package/skills/protobase/references/guides/deploy.md +8 -8
  67. package/skills/protobase/references/guides/existing-database.md +11 -31
  68. package/skills/protobase/references/guides/first-plugin.md +1 -1
  69. package/skills/protobase/references/guides/mobile-app.md +5 -3
  70. package/skills/protobase/references/guides/plugin-build.md +1 -1
  71. package/skills/protobase/references/guides/push-notifications.md +6 -7
  72. package/skills/protobase/references/guides/remote-resources.md +22 -31
  73. package/skills/protobase/references/reference/access.md +3 -3
  74. package/skills/protobase/references/reference/ai.md +1 -9
  75. package/skills/protobase/references/reference/api.md +15 -15
  76. package/skills/protobase/references/reference/app-identity.md +9 -10
  77. package/skills/protobase/references/reference/assistant.md +6 -6
  78. package/skills/protobase/references/reference/auth.md +126 -96
  79. package/skills/protobase/references/reference/bottom-bar.md +1 -1
  80. package/skills/protobase/references/reference/cli.md +36 -86
  81. package/skills/protobase/references/reference/comments.md +0 -8
  82. package/skills/protobase/references/reference/config.md +152 -0
  83. package/skills/protobase/references/reference/data-config.md +2 -2
  84. package/skills/protobase/references/reference/email.md +36 -37
  85. package/skills/protobase/references/reference/events.md +1 -1
  86. package/skills/protobase/references/reference/files.md +18 -23
  87. package/skills/protobase/references/reference/forms.md +5 -17
  88. package/skills/protobase/references/reference/history.md +2 -3
  89. package/skills/protobase/references/reference/installable-app.md +1 -1
  90. package/skills/protobase/references/reference/jobs.md +53 -56
  91. package/skills/protobase/references/reference/languages.md +4 -2
  92. package/skills/protobase/references/reference/mcp.md +11 -11
  93. package/skills/protobase/references/reference/notifications.md +26 -24
  94. package/skills/protobase/references/reference/plugins.md +11 -14
  95. package/skills/protobase/references/reference/remote-resources.md +18 -24
  96. package/skills/protobase/references/reference/supabase-realtime.md +1 -1
  97. package/skills/protobase/references/reference/supabase-rest.md +1 -1
  98. package/skills/protobase/references/reference/supabase-storage.md +1 -1
  99. package/skills/protobase/references/reference/ui-config.md +15 -17
  100. package/skills/protobase/references/reference/versioning.md +1 -1
  101. package/skills/protobase/references/reference/webhooks.md +6 -7
@@ -1,15 +1,15 @@
1
- import { configExports, createAdmin, jobDefinitions } from "@protobase/server";
1
+ import { configExports, createAdmin } from "@protobase/server";
2
2
  //#region src/project/project-admin.ts
3
3
  /**
4
- * The admin API of a project over `db`, as `dev`, `serve` and `worker` build it: its config module's resources, views,
5
- * pages and subscriptions, and the rest of its config; served from a bundle, the plugins it carries, their field
6
- * types and which icons are the project's own (`protobase dev` passes the project's icons alone). `jobs` are the project's own and the delivery of its events and history. With a `reporter`, every error the API turns
7
- * into a 500, and every stopped query, goes to the error tracker too, besides the project's `onUnhandledError` or the console. With the host's
8
- * `upgradeWebSocket`, it serves `/api/sb/realtime/v1` too.
4
+ * The admin API of a built project over `db`, as `dev`, `serve` and `worker` run it: its config module's resources,
5
+ * views, pages and subscriptions, and the rest of its config; served from a bundle, the plugins it carries, their field
6
+ * types and which icons are the project's own (`protobase dev` passes the project's icons alone). `jobs` are the
7
+ * project's own and the delivery of its events and history. With a `reporter`, every error the API turns into a 500,
8
+ * and every stopped query, goes to the error tracker too, besides the project's `onUnhandledError` or the console. With
9
+ * the host's `upgradeWebSocket`, it serves `/api/sb/realtime/v1` too.
9
10
  */
10
- const projectAdmin = (project, config, db, ui, reporter, upgradeWebSocket) => {
11
- const { resources, views, pages, userMenu, bottomBars, subscriptions } = configExports(config);
12
- const own = jobDefinitions(project.jobs ?? {});
11
+ const projectAdmin = (project, db, ui, reporter, upgradeWebSocket) => {
12
+ const { resources, views, pages, userMenu, bottomBars, subscriptions } = configExports(project.config);
13
13
  const unhandled = project.options?.onUnhandledError ?? ((error) => console.error(error));
14
14
  const admin = createAdmin({
15
15
  resources,
@@ -19,6 +19,7 @@ const projectAdmin = (project, config, db, ui, reporter, upgradeWebSocket) => {
19
19
  bottomBars,
20
20
  db,
21
21
  authenticate: project.authenticate,
22
+ ...project.secret && { secret: project.secret },
22
23
  ...project.auth && { auth: project.auth },
23
24
  ...project.functions && { functions: project.functions },
24
25
  ...project.files && { files: project.files },
@@ -29,7 +30,7 @@ const projectAdmin = (project, config, db, ui, reporter, upgradeWebSocket) => {
29
30
  ...project.mobile && { mobile: project.mobile },
30
31
  ...project.app && { app: project.app },
31
32
  ...ui?.icons && { icons: ui.icons },
32
- jobs: own,
33
+ jobs: project.jobs,
33
34
  subscriptions,
34
35
  ...ui && {
35
36
  bundlePlugins: ui.plugins,
@@ -46,7 +47,7 @@ const projectAdmin = (project, config, db, ui, reporter, upgradeWebSocket) => {
46
47
  });
47
48
  return {
48
49
  admin,
49
- jobs: [...own, ...admin.jobs]
50
+ jobs: [...project.jobs, ...admin.jobs]
50
51
  };
51
52
  };
52
53
  //#endregion
@@ -44,9 +44,13 @@ const planScaffold = async (input) => {
44
44
  const byTable = new Map(existing.map((resource) => [resource.table, resource]));
45
45
  const wanted = (table) => matchesTarget(input.target, table) && !isExcluded(input.excludes, table);
46
46
  const tables = input.tables.filter((table) => table.kind === "table");
47
- const skipped = protobaseSchemas(tables.filter((table) => matchesTarget(input.target, table)), input.target);
48
- const isProtobase = (table) => skipped.some((schema) => schema.tables.includes(table));
49
- const inProtobaseSchema = (view) => skipped.some(({ schema }) => schema === view.schema && schema !== "public");
47
+ const protobase = protobaseSchemas(tables, input.target);
48
+ const skipped = protobase.map((found) => ({
49
+ ...found,
50
+ tables: found.tables.filter((table) => matchesTarget(input.target, table))
51
+ })).filter((found) => found.tables.length > 0);
52
+ const isProtobase = (table) => protobase.some((schema) => schema.tables.includes(table));
53
+ const inProtobaseSchema = (view) => protobase.some(({ schema }) => schema === view.schema && schema !== "public");
50
54
  const skippedViews = input.tables.filter((table) => table.kind !== "table" && wanted(table) && !byTable.has(tableKey(table)) && !inProtobaseSchema(table));
51
55
  const names = assignNames(tables.filter((table) => !isProtobase(table)), existing);
52
56
  const context = (table) => ({
@@ -1,38 +1,33 @@
1
+ import { migrationsTableName, storeTableNames } from "@protobase/server/auth-store";
1
2
  //#region src/scaffold/protobase-tables.ts
2
3
  const storeCore = [
3
- "user",
4
4
  "session",
5
5
  "account",
6
6
  "verification"
7
7
  ];
8
- const storeTables = /* @__PURE__ */ new Set([
9
- ...storeCore,
10
- "jwks",
11
- "passkey",
12
- "two_factor",
13
- "sign_in_policy",
14
- "staff_sign_in"
15
- ]);
16
- const isStoreTable = (name) => storeTables.has(name) || name.startsWith("oauth_");
17
8
  const bySchema = (tables) => {
18
9
  const groups = /* @__PURE__ */ new Map();
19
10
  for (const table of tables) groups.set(table.schema, [...groups.get(table.schema) ?? [], table]);
20
11
  return groups;
21
12
  };
13
+ const userTableOf = (schema, tables) => tables.find((table) => table.name === "session")?.foreignKeys.find((key) => key.columns.length === 1 && key.columns[0] === "user_id" && key.refSchema === schema)?.refTable;
22
14
  const authStore = (schema, tables) => {
23
15
  if (schema === "auth") return tables;
24
- if (!storeCore.every((name) => tables.some((table) => table.name === name))) return [];
25
- return schema === "public" ? tables.filter((table) => isStoreTable(table.name)) : tables;
16
+ const has = (name) => tables.some((table) => table.name === name);
17
+ const user = userTableOf(schema, tables);
18
+ if (!has(migrationsTableName) && !(storeCore.every(has) && user !== void 0)) return [];
19
+ if (schema !== "public") return tables;
20
+ return tables.filter((table) => storeTableNames.includes(table.name) || table.name === user);
26
21
  };
27
22
  const jobQueue = (schema, tables) => schema === "jobs" && ["job", "version"].every((name) => tables.some((table) => table.name === name)) ? tables : [];
28
23
  const protobaseSchemas = (tables, target) => [...bySchema(tables)].flatMap(([schema, own]) => {
29
- if (target.schema === schema) return [];
30
24
  const store = authStore(schema, own);
31
25
  if (store.length > 0) return [{
32
26
  schema,
33
27
  what: "auth store",
34
28
  tables: store
35
29
  }];
30
+ if (target.schema === schema) return [];
36
31
  const queue = jobQueue(schema, own);
37
32
  return queue.length > 0 ? [{
38
33
  schema,
@@ -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}; 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 === "job queue" ? `; 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);
@@ -1,3 +1,5 @@
1
+ import { projectAuth } from "../config/build-project.js";
2
+ import { openAppDatabase } from "../project/pg-db.js";
1
3
  import { readHidden } from "../users/password.js";
2
4
  import { createUserCommand } from "../users/commands.js";
3
5
  import { usersApi } from "../users/users-api.js";
@@ -5,14 +7,17 @@ import { checkBundleManifest } from "./bundle-manifest.js";
5
7
  import { loadBundle } from "./load-bundle.js";
6
8
  import { bundleConfigFile } from "../worker/start-worker.js";
7
9
  import { checkAuthSchema } from "@protobase/server";
10
+ import pg from "pg";
8
11
  //#region src/serve/create-admin.ts
9
12
  const createAdminInBundle = async (bundle, email, options, out) => {
10
13
  const file = await bundleConfigFile(bundle);
11
14
  checkBundleManifest(file);
12
- const project = await loadBundle(file);
13
- if (!project.auth) throw new Error("The bundle exports no `auth`: users are managed by Better Auth");
14
- await checkAuthSchema(project.auth);
15
- await createUserCommand(usersApi(project.auth), {
15
+ const config = await loadBundle(file);
16
+ if (!config.auth) throw new Error("Sign-in is off in the bundle's config (`auth: false`), so the app has no users to manage");
17
+ if (!process.env.DATABASE_URL) throw new Error("No database: set DATABASE_URL");
18
+ const auth = await projectAuth(config, openAppDatabase(pg, process.env.DATABASE_URL));
19
+ await checkAuthSchema(auth);
20
+ await createUserCommand(usersApi(auth), {
16
21
  email,
17
22
  role: "admin",
18
23
  ...options
@@ -1,6 +1,7 @@
1
1
  //#region src/serve/host-module-ids.ts
2
2
  const lazyHostModuleIds = ["@protobase/server/email"];
3
3
  const hostModuleIds = [
4
+ "@protobase/config",
4
5
  "@protobase/schema",
5
6
  "@protobase/layout",
6
7
  "@protobase/layout/jsx-runtime",
@@ -1,6 +1,7 @@
1
1
  import * as nodeServer from "@hono/node-server";
2
2
  import * as hono from "hono";
3
3
  import * as server from "@protobase/server";
4
+ import * as layout from "@protobase/layout";
4
5
  import * as kysely from "kysely";
5
6
  import * as pg$1 from "pg";
6
7
  import * as reactEmailRender from "@react-email/render";
@@ -16,11 +17,12 @@ import * as postgres$1 from "postgres";
16
17
  import * as react from "react";
17
18
  import * as reactJsxRuntime from "react/jsx-runtime";
18
19
  import * as zod from "zod";
19
- import * as layout from "@protobase/layout";
20
+ import * as protobaseConfig from "@protobase/config";
20
21
  import * as query from "@protobase/query";
21
22
  import * as schema from "@protobase/schema";
22
23
  //#region src/serve/host-modules.ts
23
24
  const hostModules = {
25
+ "@protobase/config": protobaseConfig,
24
26
  "@protobase/schema": schema,
25
27
  "@protobase/layout": layout,
26
28
  "@protobase/layout/jsx-runtime": layout.jsxRuntime,
@@ -1,6 +1,7 @@
1
1
  import { protobaseVersion } from "../version/version.js";
2
2
  import { projectAdmin } from "../project/project-admin.js";
3
- import { createPgDb } from "../project/pg-db.js";
3
+ import { buildProject } from "../config/build-project.js";
4
+ import { openAppDatabase } from "../project/pg-db.js";
4
5
  import { apiWebSocketServer } from "../project/api-websocket-server.js";
5
6
  import { withClientAddress } from "./client-address.js";
6
7
  import { createServeApp } from "./app.js";
@@ -8,7 +9,7 @@ import { startCleanupTimer } from "./cleanup-timer.js";
8
9
  import { closeSockets } from "./close-sockets.js";
9
10
  import { servedRelease } from "./mobile-release.js";
10
11
  import { createAdaptorServer, upgradeWebSocket } from "@hono/node-server";
11
- import { assistantSettings, authStoreTables, backgroundSettled, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkJobsSchema, checkNotificationsSchema, checkQueryRunner, checkWebhooksSchema, configExports, createFileCleanup, startJobs } from "@protobase/server";
12
+ import { assistantSettings, authStoreTables, backgroundSettled, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkJobsSchema, checkNotificationsSchema, checkQueryRunner, checkResourcesOutsideAuthStore, checkWebhooksSchema, configExports, createFileCleanup, startJobs } from "@protobase/server";
12
13
  import pg from "pg";
13
14
  //#region src/serve/lifecycle.ts
14
15
  const listen = (server, port) => new Promise((resolve, reject) => {
@@ -19,13 +20,15 @@ const listen = (server, port) => new Promise((resolve, reject) => {
19
20
  });
20
21
  });
21
22
  const closeServer = (server) => new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
22
- const startServe = async ({ project, env, createDb = (url) => createPgDb(pg, url, env.dbConnections), site, ui, reporter }) => {
23
- if (!project.db && !env.databaseUrl) throw new Error("No database: set DATABASE_URL or export `db` from protobase.config.ts");
24
- if (env.startupChecks && project.auth) await checkAuthSchema(project.auth);
25
- const ownDb = project.db ? void 0 : createDb(env.databaseUrl);
26
- const db = project.db ?? ownDb;
27
- const { resources, views } = configExports(project.config);
23
+ const startServe = async ({ config, env, openDb = (url) => openAppDatabase(pg, url, env.dbConnections), site, ui, reporter }) => {
24
+ if (!env.databaseUrl) throw new Error("No database: set DATABASE_URL");
25
+ const database = openDb(env.databaseUrl);
26
+ const { db } = database;
28
27
  const startJobsAndListen = async () => {
28
+ const project = await buildProject(config, database);
29
+ if (env.startupChecks && project.auth) await checkAuthSchema(project.auth);
30
+ const { resources, views } = configExports(project.config);
31
+ if (env.startupChecks && project.auth) await checkResourcesOutsideAuthStore(db, resources.map((resource) => resource.toModel()), project.auth);
29
32
  if (env.startupChecks) await checkChanges(db, resources.map((resource) => resource.toModel()), project.events);
30
33
  if (env.startupChecks) await checkComments(db, resources.map((resource) => resource.toModel()));
31
34
  if (env.startupChecks) await checkComputed(db, resources.map((resource) => resource.toModel()));
@@ -38,7 +41,7 @@ const startServe = async ({ project, env, createDb = (url) => createPgDb(pg, url
38
41
  });
39
42
  if (env.startupChecks && project.webhooks) await checkWebhooksSchema(db, project.webhooks);
40
43
  if (env.startupChecks && project.notifications) await checkNotificationsSchema(db, project.notifications, project.auth);
41
- const { admin, jobs: definitions } = projectAdmin(project, project.config, db, ui, reporter, upgradeWebSocket);
44
+ const { admin, jobs: definitions } = projectAdmin(project, db, ui, reporter, upgradeWebSocket);
42
45
  if (env.startupChecks && definitions.length > 0) await checkJobsSchema(db);
43
46
  const jobs = definitions.length > 0 ? await startJobs({
44
47
  db,
@@ -77,17 +80,19 @@ const startServe = async ({ project, env, createDb = (url) => createPgDb(pg, url
77
80
  return {
78
81
  server,
79
82
  sockets,
80
- jobs
83
+ jobs,
84
+ resources,
85
+ files: project.files
81
86
  };
82
87
  };
83
- const { server, sockets, jobs } = await startJobsAndListen().catch(async (error) => {
84
- await ownDb?.destroy();
88
+ const { server, sockets, jobs, resources, files } = await startJobsAndListen().catch(async (error) => {
89
+ await db.destroy();
85
90
  throw error;
86
91
  });
87
92
  const cleanup = createFileCleanup({
88
93
  resources,
89
94
  db,
90
- ...project.files && { files: project.files }
95
+ ...files && { files }
91
96
  });
92
97
  const timer = cleanup && env.filesCleanupMinutes > 0 ? startCleanupTimer(cleanup.run, env.filesCleanupMinutes, (error) => console.error(error)) : void 0;
93
98
  const close = async () => {
@@ -97,7 +102,7 @@ const startServe = async ({ project, env, createDb = (url) => createPgDb(pg, url
97
102
  await backgroundSettled();
98
103
  await timer?.stop();
99
104
  await jobs?.stop();
100
- await ownDb?.destroy();
105
+ await db.destroy();
101
106
  };
102
107
  return {
103
108
  port: server.address().port,
@@ -1,17 +1,47 @@
1
+ import { mergeConfig } from "../config/merge-config.js";
2
+ import { withDefaults } from "../config/config-defaults.js";
3
+ import { calledConfig } from "../config/called-config.js";
1
4
  import { bundleBasePath } from "../bundle/manifest.js";
2
5
  import path from "node:path";
3
6
  import { pathToFileURL } from "node:url";
4
7
  //#region src/serve/load-bundle.ts
5
- const isObject = (value) => typeof value === "object" && value !== null;
6
- const servedProject = (module, file) => {
7
- const project = module.default;
8
- if (!isObject(project)) throw new Error(`${file} has no default export; build it with \`protobase build\``);
9
- if (!isObject(project.config)) throw new Error(`${file} has no \`config\`: export it from protobase.config.ts or add config/index.ts`);
10
- if (typeof project.authenticate !== "function") throw new Error("No authenticator: export `authenticate` (and `auth`) from protobase.config.ts; see https://docs.protobase.net/reference/auth/");
11
- const basePath = isObject(project.options) ? project.options.basePath : void 0;
12
- if (basePath !== void 0 && basePath !== "/api/v1") throw new Error(`options.basePath is ${JSON.stringify(basePath)}; a bundle's UI and manifest expect the API at ${bundleBasePath}, so remove it (see https://docs.protobase.net/reference/cli/#the-manifest)`);
13
- return project;
8
+ /** Checks a bundle's config module: one `protobase build` wrote. */
9
+ const bundleModule = (module, file) => {
10
+ if (typeof module.own !== "object" || module.own === null || !Array.isArray(module.extensions) || typeof module.packages !== "object") throw new Error(`${file} is not a config module of \`protobase build\`; build the project again`);
11
+ return module;
14
12
  };
15
- const loadBundle = async (file) => servedProject(await import(pathToFileURL(path.resolve(file)).href), file);
13
+ const projectFiles = ({ resources, functions, modules }, packages) => ({
14
+ ...resources && { resources },
15
+ functions,
16
+ module: (file) => modules[file],
17
+ package: async (name) => {
18
+ const load = packages[name];
19
+ if (!load) throw new Error(`The bundle carries no ${name}; build it again`);
20
+ return load();
21
+ }
22
+ });
23
+ /**
24
+ * The config a bundle carries, read again where it serves, with the environment there, merged after the extensions'
25
+ * configs, with the code its conventions found when it was built.
26
+ */
27
+ const bundledConfig = async (bundle, command, root) => {
28
+ const configEnv = {
29
+ command,
30
+ env: process.env,
31
+ root
32
+ };
33
+ const sources = [];
34
+ for (const { config, label, files } of [...bundle.extensions, bundle.own]) sources.push({
35
+ config: await calledConfig(config, configEnv, label),
36
+ files: projectFiles(files, bundle.packages),
37
+ label
38
+ });
39
+ const config = withDefaults(mergeConfig(...sources), command, process.env);
40
+ const basePath = config.apiPath;
41
+ if (basePath !== void 0 && basePath !== "/api/v1") throw new Error(`apiPath is ${JSON.stringify(basePath)}; a bundle's UI and manifest expect the API at ${bundleBasePath}, so remove it (see https://docs.protobase.net/reference/cli/#the-manifest)`);
42
+ return config;
43
+ };
44
+ /** The config of the bundle's config module `file`, read again for `command` with the environment of this process. */
45
+ const loadBundle = async (file, command = "serve") => bundledConfig(bundleModule(await import(pathToFileURL(path.resolve(file)).href), file), command, path.dirname(path.resolve(file)));
16
46
  //#endregion
17
- export { loadBundle, servedProject };
47
+ export { bundleModule, bundledConfig, loadBundle };
@@ -10,7 +10,7 @@ const loopback = [
10
10
  "[::1]"
11
11
  ];
12
12
  /**
13
- * The API origin a release names, the auth issuer's (`baseURL`), as the app's own files do by default: https, or plain
13
+ * The API origin a release names, the app's URL (`url`), as the app's own files do by default: https, or plain
14
14
  * http to this machine only, as `protobase mobile` allows it. `undefined` for any other, which no app calls.
15
15
  */
16
16
  const releaseOrigin = (issuer) => {
@@ -13,11 +13,11 @@ const serveBundle = async (file, env, out, site) => {
13
13
  const serveEnv = readServeEnv(env);
14
14
  checkBundleManifest(file);
15
15
  const manifest = await readManifest(path.dirname(file));
16
- const project = await loadBundle(file);
17
- const reporter = await projectErrorReporter(project, env);
16
+ const config = await loadBundle(file);
17
+ const reporter = await projectErrorReporter(config, env);
18
18
  if (reporter) reportCrashes(reporter);
19
19
  const server = await startServe({
20
- project,
20
+ config,
21
21
  env: serveEnv,
22
22
  site,
23
23
  ui: bundleUi(manifest),
@@ -1,8 +1,10 @@
1
+ import { exportedConfigObject } from "./config-object.js";
1
2
  import { existsSync } from "node:fs";
2
3
  import path from "node:path";
3
4
  import { readFile, writeFile } from "node:fs/promises";
5
+ import { Node } from "ts-morph";
4
6
  //#region src/supabase/auth-config.ts
5
- /** createAuth's options for Supabase's auth.users. */
7
+ /** The `auth` settings for Supabase's auth.users. */
6
8
  const supabaseUsers = {
7
9
  users: {
8
10
  table: "users",
@@ -12,41 +14,44 @@ const supabaseUsers = {
12
14
  passwordHashes: ["bcrypt"],
13
15
  generateUserId: "uuid"
14
16
  };
15
- const moduleText = `import type { CreateAuthOptions } from '@protobase/server'
16
-
17
+ const settingsText = (indent) => [
18
+ "// Supabase's own auth.users as the app's user table, written by `protobase import supabase`: every foreign key,",
19
+ "// trigger and policy naming it keeps working. Its passwords are bcrypt hashes, its ids UUIDs, and its `role` the",
20
+ "// Postgres role, so the app's roles go to a column of their own.",
21
+ `users: { table: '${supabaseUsers.users.table}', columns: { role: '${supabaseUsers.users.columns.role}' }, metadata: '${supabaseUsers.users.metadata}' },`,
22
+ `passwordHashes: [${supabaseUsers.passwordHashes.map((name) => `'${name}'`).join(", ")}],`,
23
+ `generateUserId: '${supabaseUsers.generateUserId}',`
24
+ ].map((line) => `${indent}${line}`).join("\n");
25
+ const settingsObject = `{ users: { table: '${supabaseUsers.users.table}', columns: { role: '${supabaseUsers.users.columns.role}' }, metadata: '${supabaseUsers.users.metadata}' }, passwordHashes: ['bcrypt'], generateUserId: 'uuid' }`;
17
26
  /**
18
- * Supabase's own auth.users as the app's user table, written by \`protobase import supabase\`: every foreign key, trigger
19
- * and policy naming it keeps working. Its passwords are Supabase's bcrypt hashes, and its ids are UUIDs.
20
- */
21
- export const supabaseUsers = {
22
- // Supabase's \`role\` holds the Postgres role, so the app's roles go to a column of their own.
23
- users: { table: '${supabaseUsers.users.table}', columns: { role: '${supabaseUsers.users.columns.role}' }, metadata: '${supabaseUsers.users.metadata}' },
24
- passwordHashes: [${supabaseUsers.passwordHashes.map((name) => `'${name}'`).join(", ")}],
25
- generateUserId: '${supabaseUsers.generateUserId}',
26
- } satisfies Partial<CreateAuthOptions>
27
- `;
28
- const call = "createAuth({";
29
- const importLine = "import { supabaseUsers } from './supabase-users'\n";
30
- /**
31
- * `auth/auth.ts` with the options spread into its one `createAuth({` call, and their import first; fails, naming what
32
- * to add, otherwise.
27
+ * protobase.config.ts with the settings first in its `auth`, or with an `auth` of them when it has none, sign-in being
28
+ * on by default; fails, naming what to add, when it exports no object the import can see or its `auth` is not one.
33
29
  */
34
30
  const withSupabaseUsers = (text, file) => {
35
- const calls = text.split(call).length - 1;
36
- if (calls !== 1) throw new Error(`${file} must call \`createAuth({\` once, it does ${calls} times: point it at Supabase's auth.users yourself with ${JSON.stringify(supabaseUsers)}, then import again`);
37
- return `${importLine}${text.replace(call, `${call}\n ...supabaseUsers,`)}`;
31
+ const config = exportedConfigObject(text).object;
32
+ const refused = () => /* @__PURE__ */ new Error(`${file} must export a config with an \`auth: { ... }\` object: point it at Supabase's auth.users yourself with ${JSON.stringify(supabaseUsers)}, then import again`);
33
+ if (!config) throw refused();
34
+ const auth = config.getProperty("auth");
35
+ if (!auth) {
36
+ const last = config.getProperties().at(-1);
37
+ if (!last) return `${text.slice(0, config.getStart())}{ auth: ${settingsObject} }${text.slice(config.getEnd())}`;
38
+ return `${text.slice(0, last.getEnd())}, auth: ${settingsObject}${text.slice(last.getEnd())}`;
39
+ }
40
+ const object = Node.isPropertyAssignment(auth) ? auth.getInitializer() : void 0;
41
+ if (!object || !Node.isObjectLiteralExpression(object)) throw refused();
42
+ const first = object.getProperties()[0];
43
+ const indent = first ? " ".repeat(first.getStartLinePos() === first.getStart() ? 0 : first.getStart() - first.getStartLinePos()) : " ";
44
+ const at = object.getStart() + 1;
45
+ return `${text.slice(0, at)}\n${settingsText(indent)}${first ? "" : "\n"}${text.slice(at)}`;
38
46
  };
39
- /** Where the app's Better Auth setup lives, and what it becomes; fails before anything is written when it cannot. */
47
+ /** Where the app's Better Auth settings live, and what they become; fails before anything is written when it cannot. */
40
48
  const planAuthConfig = async (projectDir) => {
41
- const file = path.join(projectDir, "auth", "auth.ts");
42
- if (!existsSync(file)) throw new Error(`The project has no auth/auth.ts with its createAuth: import into a project made by create-protobase`);
49
+ const file = path.join(projectDir, "protobase.config.ts");
50
+ if (!existsSync(file)) throw new Error("The project has no protobase.config.ts with its `auth`: import into a project made by create-protobase");
43
51
  const text = withSupabaseUsers(await readFile(file, "utf8"), path.relative(projectDir, file));
44
52
  return {
45
53
  file,
46
- write: async () => {
47
- await writeFile(path.join(path.dirname(file), "supabase-users.ts"), moduleText, { flag: "wx" });
48
- await writeFile(file, text);
49
- }
54
+ write: () => writeFile(file, text)
50
55
  };
51
56
  };
52
57
  //#endregion
@@ -1,34 +1,35 @@
1
- import { parseSource } from "../scaffold/project.js";
2
- import { Node, SyntaxKind } from "ts-morph";
1
+ import { exportedConfigObject } from "./config-object.js";
2
+ import { Node } from "ts-morph";
3
3
  //#region src/supabase/config-jobs.ts
4
- const jobsImport = "import * as jobs from './jobs'";
5
- /** What `protobase.config.ts` says when the import writes it: the jobs of `jobs/`, and the config by its convention. */
6
- const newConfig = `${jobsImport}\n\nexport default { jobs }\n`;
7
- /** The object `protobase.config.ts` exports by default, written out or passed to a call such as `defineConfig`. */
8
- const exportedObject = (text) => {
9
- const source = parseSource(text, "protobase.config.ts");
10
- const exported = source.getExportAssignment((assignment) => !assignment.isExportEquals())?.getExpression();
11
- const object = Node.isCallExpression(exported) ? exported.getArguments()[0] : exported;
12
- return {
13
- source,
14
- object: Node.isObjectLiteralExpression(object) ? object : void 0
15
- };
4
+ const indentOf = (text, node) => {
5
+ const lineStart = text.lastIndexOf("\n", node.getStart() - 1) + 1;
6
+ return /^[ \t]*/.exec(text.slice(lineStart))[0];
7
+ };
8
+ const withEntries = (text, object, entries) => {
9
+ const last = object.getProperties().at(-1);
10
+ if (!last) return `${text.slice(0, object.getStart())}{ ${entries.join(", ")} }${text.slice(object.getEnd())}`;
11
+ const at = last.getEnd() + (text[last.getEnd()] === "," ? 1 : 0);
12
+ if (!object.getText().includes("\n")) return `${text.slice(0, last.getEnd())}, ${entries.join(", ")}${text.slice(last.getEnd())}`;
13
+ const indent = indentOf(text, last);
14
+ const comma = at === last.getEnd() ? "," : "";
15
+ return `${text.slice(0, at)}${comma}${entries.map((entry) => `\n${indent}${entry},`).join("")}${text.slice(at)}`;
16
16
  };
17
17
  /**
18
- * `protobase.config.ts` passing the jobs of `jobs/` as its `jobs`: `existing`, with an import of them and the property
19
- * added, or a new file when there is none. It is `existing` itself when it imports `./jobs` already, and `undefined`
20
- * when the file is not one it can change: it names a `jobs` of its own, or exports no object it can see.
18
+ * `protobase.config.ts` declaring the jobs of `declarations` (each one entry of `jobs`, such as
19
+ * `'purge': { schedule: '0 3 * * *' }`) named `names`: `existing` with them added to its `jobs`, or with a `jobs` of
20
+ * them, or a new config when there is none. `undefined` when the file is not one it can change: it exports no object it
21
+ * can see, its `jobs` is no object written out, or it declares one of these names already.
21
22
  */
22
- const configWithJobs = (existing) => {
23
- if (existing === void 0) return newConfig;
24
- const { source, object } = exportedObject(existing);
25
- if (source.getImportDeclarations().some((declaration) => declaration.getModuleSpecifierValue() === "./jobs")) return existing;
26
- if (!object || source.getDescendantsOfKind(SyntaxKind.Identifier).some((identifier) => identifier.getText() === "jobs")) return void 0;
27
- const last = object.getProperties().at(-1);
28
- const withProperty = last ? `${existing.slice(0, last.getEnd())}, jobs${existing.slice(last.getEnd())}` : `${existing.slice(0, object.getStart())}{ jobs }${existing.slice(object.getEnd())}`;
29
- const importsEnd = source.getImportDeclarations().at(-1)?.getEnd();
30
- if (importsEnd === void 0) return `${jobsImport}\n\n${withProperty}`;
31
- return `${withProperty.slice(0, importsEnd)}\n${jobsImport}${withProperty.slice(importsEnd)}`;
23
+ const configWithJobs = (existing, names, declarations) => {
24
+ if (existing === void 0) return `import { defineConfig } from '@protobase/config'\n\nexport default defineConfig({\n jobs: {\n${declarations.map((entry) => ` ${entry},\n`).join("")} },\n})\n`;
25
+ const { object } = exportedConfigObject(existing);
26
+ if (!object) return void 0;
27
+ const jobs = object.getProperty("jobs");
28
+ if (!jobs) return withEntries(existing, object, [`jobs: { ${declarations.join(", ")} }`]);
29
+ const declared = Node.isPropertyAssignment(jobs) ? jobs.getInitializer() : void 0;
30
+ if (!declared || !Node.isObjectLiteralExpression(declared)) return void 0;
31
+ if (names.some((name) => declared.getProperty(name) ?? declared.getProperty(`'${name}'`))) return void 0;
32
+ return withEntries(existing, declared, declarations);
32
33
  };
33
34
  //#endregion
34
35
  export { configWithJobs };
@@ -0,0 +1,25 @@
1
+ import { parseSource } from "../scaffold/project.js";
2
+ import { Node } from "ts-morph";
3
+ //#region src/supabase/config-object.ts
4
+ const returnedObject = (fn) => {
5
+ if (!Node.isArrowFunction(fn) && !Node.isFunctionExpression(fn)) return void 0;
6
+ const body = fn.getBody();
7
+ const expression = Node.isParenthesizedExpression(body) ? body.getExpression() : Node.isBlock(body) ? body.getStatements().flatMap((statement) => Node.isReturnStatement(statement) ? [statement.getExpression()] : []).at(-1) : body;
8
+ const unwrapped = expression && Node.isParenthesizedExpression(expression) ? expression.getExpression() : expression;
9
+ return unwrapped && Node.isObjectLiteralExpression(unwrapped) ? unwrapped : void 0;
10
+ };
11
+ /**
12
+ * The config object `protobase.config.ts` exports by default: written out, passed to a call such as `defineConfig`,
13
+ * or returned by the config function; `undefined` when it exports none the import can see.
14
+ */
15
+ const exportedConfigObject = (text) => {
16
+ const source = parseSource(text, "protobase.config.ts");
17
+ const exported = source.getExportAssignment((assignment) => !assignment.isExportEquals())?.getExpression();
18
+ const argument = Node.isCallExpression(exported) ? exported.getArguments()[0] : exported;
19
+ return {
20
+ source,
21
+ object: argument && (Node.isObjectLiteralExpression(argument) ? argument : returnedObject(argument))
22
+ };
23
+ };
24
+ //#endregion
25
+ export { exportedConfigObject };
@@ -2,24 +2,23 @@
2
2
  const quoted = (text) => `'${text.replaceAll("\\", "\\\\").replaceAll("'", "\\'").replaceAll("\n", "\\n")}'`;
3
3
  const templateLiteral = (text) => `\`${text.replaceAll("\\", "\\\\").replaceAll("`", "\\`").replaceAll("${", "\\${")}\``;
4
4
  /**
5
- * The module of `jobs/` that runs a pg_cron job's SQL as a Protobase recurring job, on its schedule, as the app's
6
- * database role. pg_cron ran each time once, without retrying a failed one, so the job tries once too.
5
+ * What `jobs/<file>.ts` holds for a pg_cron job made a Protobase recurring job: its run, the job's SQL as the app's
6
+ * database role. Its schedule is in protobase.config.ts (see `cronJobDeclaration`).
7
7
  */
8
8
  const cronJobModule = (job) => [
9
- "import { defineJob } from '@protobase/server'",
10
9
  "import { sql } from 'kysely'",
10
+ "import type { JobRun } from '@protobase/server'",
11
11
  "",
12
- `/** pg_cron's job ${job.name}, imported from Supabase: its SQL, on its schedule, tried once each time as pg_cron did. */`,
13
- `export const ${job.exportName} = defineJob({`,
14
- ` name: ${quoted(job.name)},`,
15
- ` schedule: ${quoted(job.schedule)},`,
16
- ...job.timezone ? [` timezone: ${quoted(job.timezone)},`] : [],
17
- " maxAttempts: 1,",
18
- " run: async (_, { db }) => {",
19
- ` await sql.raw(${templateLiteral(job.command)}).execute(db)`,
20
- " },",
21
- "})",
12
+ `/** pg_cron's job ${job.name}, imported from Supabase: its SQL, on the schedule protobase.config.ts declares. */`,
13
+ "export default (async (_, { db }) => {",
14
+ ` await sql.raw(${templateLiteral(job.command)}).execute(db)`,
15
+ "}) satisfies JobRun",
22
16
  ""
23
17
  ].join("\n");
18
+ /**
19
+ * The job's declaration in protobase.config.ts's `jobs`, as the text of one entry: pg_cron ran each time once, without
20
+ * retrying a failed one, so the job tries once too.
21
+ */
22
+ const cronJobDeclaration = (job) => `${quoted(job.file)}: { description: ${quoted(`pg_cron's job ${job.name}, imported from Supabase.`)}, schedule: ${quoted(job.schedule)}, ${job.timezone ? `timezone: ${quoted(job.timezone)}, ` : ""}maxAttempts: 1 }`;
24
23
  //#endregion
25
- export { cronJobModule };
24
+ export { cronJobDeclaration, cronJobModule };
@@ -1,6 +1,5 @@
1
- import { ensureExports } from "../scaffold/index-file.js";
2
1
  import { configWithJobs } from "./config-jobs.js";
3
- import { cronJobModule } from "./cron-job-file.js";
2
+ import { cronJobDeclaration, cronJobModule } from "./cron-job-file.js";
4
3
  import { existsSync } from "node:fs";
5
4
  import path from "node:path";
6
5
  import { mkdir, readFile, writeFile } from "node:fs/promises";
@@ -10,21 +9,16 @@ const jobFile = (projectDir, job) => path.join(projectDir, "jobs", `${job.file}.
10
9
  const cronJobFilesInTheWay = (projectDir, jobs) => jobs.map((job) => jobFile(projectDir, job)).filter((file) => existsSync(file));
11
10
  const readIfThere = async (file) => existsSync(file) ? readFile(file, "utf8") : void 0;
12
11
  /**
13
- * Writes each job's module in `jobs/`, exports it from `jobs/index.ts` and passes them as protobase.config.ts's `jobs`;
14
- * returns whether the config does, `false` when it has a `jobs` of its own for a person to add them to.
12
+ * Writes each job's run in `jobs/<name>.ts` and declares the jobs in protobase.config.ts's `jobs`; returns whether the
13
+ * config does, `false` when it cannot add them, for a person to add them to.
15
14
  */
16
15
  const writeCronJobs = async (projectDir, jobs) => {
17
16
  if (jobs.length === 0) return true;
18
- await mkdir(path.join(projectDir, "jobs"), { recursive: true });
19
- for (const job of jobs) await writeFile(jobFile(projectDir, job), cronJobModule(job), { flag: "wx" });
20
- const index = path.join(projectDir, "jobs", "index.ts");
21
- await writeFile(index, ensureExports(await readIfThere(index) ?? "", jobs.map((job) => ({
22
- from: `./${job.file}`,
23
- names: [job.exportName]
24
- }))));
25
17
  const configFile = path.join(projectDir, "protobase.config.ts");
26
18
  const existing = await readIfThere(configFile);
27
- const config = configWithJobs(existing);
19
+ const config = configWithJobs(existing, jobs.map((job) => job.file), jobs.map(cronJobDeclaration));
20
+ await mkdir(path.join(projectDir, "jobs"), { recursive: true });
21
+ for (const job of jobs) await writeFile(jobFile(projectDir, job), cronJobModule(job), { flag: "wx" });
28
22
  if (config === void 0) return false;
29
23
  if (config !== existing) await writeFile(configFile, config);
30
24
  return true;