@protobase/cli 0.48.0 → 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 (91) 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/create-db.js +2 -2
  15. package/dist/dev/entry.js +9 -10
  16. package/dist/dev/project.js +23 -47
  17. package/dist/main.js +3 -3
  18. package/dist/migration/load-project.js +34 -34
  19. package/dist/migration/parts.js +2 -2
  20. package/dist/migration/summary.js +2 -2
  21. package/dist/mobile/api-origin.js +4 -4
  22. package/dist/mobile/load-project.js +13 -12
  23. package/dist/mobile/register.js +1 -1
  24. package/dist/mobile/run.js +1 -1
  25. package/dist/organizations/register.js +1 -1
  26. package/dist/project/error-reporter.js +3 -3
  27. package/dist/project/import-project-file.js +4 -2
  28. package/dist/project/load-bundle-project.js +16 -25
  29. package/dist/project/load-data-config.js +1 -1
  30. package/dist/project/pg-db.js +10 -4
  31. package/dist/project/placeholder-secret.js +2 -2
  32. package/dist/project/project-admin.js +12 -11
  33. package/dist/serve/create-admin.js +9 -4
  34. package/dist/serve/host-module-ids.js +1 -0
  35. package/dist/serve/host-modules.js +3 -1
  36. package/dist/serve/lifecycle.js +17 -13
  37. package/dist/serve/load-bundle.js +41 -11
  38. package/dist/serve/mobile-release.js +1 -1
  39. package/dist/serve/serve-bundle.js +3 -3
  40. package/dist/supabase/auth-config.js +33 -28
  41. package/dist/supabase/config-jobs.js +28 -27
  42. package/dist/supabase/config-object.js +25 -0
  43. package/dist/supabase/cron-job-file.js +13 -14
  44. package/dist/supabase/cron-jobs-write.js +6 -12
  45. package/dist/supabase/cron-plan.js +3 -51
  46. package/dist/supabase/project-files.js +4 -9
  47. package/dist/supabase/report.js +3 -3
  48. package/dist/users/load-auth.js +16 -15
  49. package/dist/worker/start-worker.js +18 -15
  50. package/package.json +8 -6
  51. package/skills/protobase/SKILL.md +2 -1
  52. package/skills/protobase/references/features/notifications.md +1 -1
  53. package/skills/protobase/references/features/start-a-project.md +3 -0
  54. package/skills/protobase/references/getting-started.md +2 -2
  55. package/skills/protobase/references/guides/api-functions.md +4 -4
  56. package/skills/protobase/references/guides/deploy.md +7 -7
  57. package/skills/protobase/references/guides/existing-database.md +11 -31
  58. package/skills/protobase/references/guides/first-plugin.md +1 -1
  59. package/skills/protobase/references/guides/mobile-app.md +5 -3
  60. package/skills/protobase/references/guides/plugin-build.md +1 -1
  61. package/skills/protobase/references/guides/push-notifications.md +6 -7
  62. package/skills/protobase/references/guides/remote-resources.md +22 -31
  63. package/skills/protobase/references/reference/access.md +3 -3
  64. package/skills/protobase/references/reference/ai.md +1 -9
  65. package/skills/protobase/references/reference/api.md +15 -15
  66. package/skills/protobase/references/reference/app-identity.md +9 -10
  67. package/skills/protobase/references/reference/assistant.md +6 -6
  68. package/skills/protobase/references/reference/auth.md +112 -86
  69. package/skills/protobase/references/reference/bottom-bar.md +1 -1
  70. package/skills/protobase/references/reference/cli.md +35 -85
  71. package/skills/protobase/references/reference/comments.md +0 -8
  72. package/skills/protobase/references/reference/config.md +152 -0
  73. package/skills/protobase/references/reference/data-config.md +2 -2
  74. package/skills/protobase/references/reference/email.md +36 -37
  75. package/skills/protobase/references/reference/events.md +1 -1
  76. package/skills/protobase/references/reference/files.md +18 -23
  77. package/skills/protobase/references/reference/forms.md +5 -17
  78. package/skills/protobase/references/reference/history.md +2 -3
  79. package/skills/protobase/references/reference/installable-app.md +1 -1
  80. package/skills/protobase/references/reference/jobs.md +53 -56
  81. package/skills/protobase/references/reference/languages.md +4 -2
  82. package/skills/protobase/references/reference/mcp.md +10 -10
  83. package/skills/protobase/references/reference/notifications.md +26 -24
  84. package/skills/protobase/references/reference/plugins.md +11 -14
  85. package/skills/protobase/references/reference/remote-resources.md +18 -24
  86. package/skills/protobase/references/reference/supabase-realtime.md +1 -1
  87. package/skills/protobase/references/reference/supabase-rest.md +1 -1
  88. package/skills/protobase/references/reference/supabase-storage.md +1 -1
  89. package/skills/protobase/references/reference/ui-config.md +15 -17
  90. package/skills/protobase/references/reference/versioning.md +1 -1
  91. package/skills/protobase/references/reference/webhooks.md +6 -7
@@ -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";
@@ -19,13 +20,14 @@ 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);
29
31
  if (env.startupChecks && project.auth) await checkResourcesOutsideAuthStore(db, resources.map((resource) => resource.toModel()), project.auth);
30
32
  if (env.startupChecks) await checkChanges(db, resources.map((resource) => resource.toModel()), project.events);
31
33
  if (env.startupChecks) await checkComments(db, resources.map((resource) => resource.toModel()));
@@ -39,7 +41,7 @@ const startServe = async ({ project, env, createDb = (url) => createPgDb(pg, url
39
41
  });
40
42
  if (env.startupChecks && project.webhooks) await checkWebhooksSchema(db, project.webhooks);
41
43
  if (env.startupChecks && project.notifications) await checkNotificationsSchema(db, project.notifications, project.auth);
42
- const { admin, jobs: definitions } = projectAdmin(project, project.config, db, ui, reporter, upgradeWebSocket);
44
+ const { admin, jobs: definitions } = projectAdmin(project, db, ui, reporter, upgradeWebSocket);
43
45
  if (env.startupChecks && definitions.length > 0) await checkJobsSchema(db);
44
46
  const jobs = definitions.length > 0 ? await startJobs({
45
47
  db,
@@ -78,17 +80,19 @@ const startServe = async ({ project, env, createDb = (url) => createPgDb(pg, url
78
80
  return {
79
81
  server,
80
82
  sockets,
81
- jobs
83
+ jobs,
84
+ resources,
85
+ files: project.files
82
86
  };
83
87
  };
84
- const { server, sockets, jobs } = await startJobsAndListen().catch(async (error) => {
85
- await ownDb?.destroy();
88
+ const { server, sockets, jobs, resources, files } = await startJobsAndListen().catch(async (error) => {
89
+ await db.destroy();
86
90
  throw error;
87
91
  });
88
92
  const cleanup = createFileCleanup({
89
93
  resources,
90
94
  db,
91
- ...project.files && { files: project.files }
95
+ ...files && { files }
92
96
  });
93
97
  const timer = cleanup && env.filesCleanupMinutes > 0 ? startCleanupTimer(cleanup.run, env.filesCleanupMinutes, (error) => console.error(error)) : void 0;
94
98
  const close = async () => {
@@ -98,7 +102,7 @@ const startServe = async ({ project, env, createDb = (url) => createPgDb(pg, url
98
102
  await backgroundSettled();
99
103
  await timer?.stop();
100
104
  await jobs?.stop();
101
- await ownDb?.destroy();
105
+ await db.destroy();
102
106
  };
103
107
  return {
104
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;
@@ -30,57 +30,11 @@ const utc = /* @__PURE__ */ new Set([
30
30
  ]);
31
31
  /** A pg_cron job name as a Protobase job name: letters, digits, `_`, `-`, `.` and `/`, the rest made `-`. */
32
32
  const jobName = (job) => (job.name ?? `cron-job-${job.id}`).replace(/[^\w.\-/]+/g, "-");
33
+ /** A job's name as Protobase declares it, which is also its file `jobs/<name>.ts`: lowercase words joined by `-`. */
33
34
  const fileName = (name) => name.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "cron-job";
34
- /** Words a module's export may not be named, which a job named so gets `cron` before. */
35
- const reserved = /* @__PURE__ */ new Set([
36
- "await",
37
- "break",
38
- "case",
39
- "catch",
40
- "class",
41
- "const",
42
- "continue",
43
- "debugger",
44
- "default",
45
- "delete",
46
- "do",
47
- "else",
48
- "enum",
49
- "export",
50
- "extends",
51
- "false",
52
- "finally",
53
- "for",
54
- "function",
55
- "if",
56
- "import",
57
- "in",
58
- "instanceof",
59
- "let",
60
- "new",
61
- "null",
62
- "return",
63
- "static",
64
- "super",
65
- "switch",
66
- "this",
67
- "throw",
68
- "true",
69
- "try",
70
- "typeof",
71
- "var",
72
- "void",
73
- "while",
74
- "with",
75
- "yield"
76
- ]);
77
- const exportName = (file) => {
78
- const camel = file.replace(/-([a-z0-9])/g, (_, letter) => letter.toUpperCase());
79
- return /^[0-9]/.test(camel) || reserved.has(camel) ? `cron${camel[0].toUpperCase()}${camel.slice(1)}` : camel;
80
- };
81
35
  /** `wanted`, or with `-<id>` after it when `taken` has it already, which it then holds. */
82
- const unique = (taken, wanted, id, separator = "-") => {
83
- const name = taken.has(wanted) ? `${wanted}${separator}${id}` : wanted;
36
+ const unique = (taken, wanted, id) => {
37
+ const name = taken.has(wanted) ? `${wanted}-${id}` : wanted;
84
38
  taken.add(name);
85
39
  return name;
86
40
  };
@@ -101,7 +55,6 @@ const leftReason = (job, options) => {
101
55
  const cronPlan = (jobs, options) => {
102
56
  const names = /* @__PURE__ */ new Set();
103
57
  const files = /* @__PURE__ */ new Set();
104
- const exports = /* @__PURE__ */ new Set();
105
58
  return jobs.map((job) => {
106
59
  if (!job.local) return {
107
60
  ...job,
@@ -130,7 +83,6 @@ const cronPlan = (jobs, options) => {
130
83
  kind: "converted",
131
84
  name,
132
85
  file,
133
- exportName: unique(exports, exportName(file), job.id, ""),
134
86
  timezone: utc.has(options.timezone) ? void 0 : options.timezone
135
87
  }
136
88
  };
@@ -1,12 +1,7 @@
1
- import { importProjectFile } from "../project/import-project-file.js";
2
- import { existsSync } from "node:fs";
3
- import path from "node:path";
1
+ import { projectFiles } from "../config/project-parts.js";
2
+ import { loadSourceConfig } from "../config/source-config.js";
4
3
  //#region src/supabase/project-files.ts
5
- /** `files` of the project's protobase.config.ts, or none when it has no such file or no `files`. */
6
- const projectFilesOptions = async (projectDir) => {
7
- const file = path.join(projectDir, "protobase.config.ts");
8
- if (!existsSync(file)) return {};
9
- return (await importProjectFile(file)).default?.files ?? {};
10
- };
4
+ /** The files options of the project in `projectDir`, its providers made; none when its config has no `files`. */
5
+ const projectFilesOptions = async (projectDir) => await projectFiles(await loadSourceConfig(projectDir, { command: "tool" })) ?? {};
11
6
  //#endregion
12
7
  export { projectFilesOptions };
@@ -21,7 +21,7 @@ const cronLeft = (jobs) => jobs?.flatMap((job) => job.outcome.kind === "left" ?
21
21
  /** What a person does before the converted pg_cron jobs run, or nothing when the import converted none. */
22
22
  const recurringJobs = (manifest, jobsWired) => {
23
23
  if (convertedCronJobs(manifest.cronJobs).length === 0) return [];
24
- return [`## Recurring jobs\n\nThe import wrote pg_cron's jobs it could convert in \`jobs/\`, each running its SQL as the app's database role, once per time and without retries, as pg_cron did. ${jobsWired ? "`protobase.config.ts` passes them as its `jobs`." : "`protobase.config.ts` has a `jobs` of its own: add the exports of `jobs/index.ts` to it."} They run once the database has the jobs schema: run \`protobase migration\` and apply it.\n`];
24
+ return [`## Recurring jobs\n\nThe import wrote pg_cron's jobs it could convert in \`jobs/\`, each running its SQL as the app's database role, once per time and without retries, as pg_cron did. ${jobsWired ? "`protobase.config.ts` declares them in its `jobs`, each with its schedule." : "`protobase.config.ts` could not be changed: declare each of them in its `jobs`, by the name of its file, with its schedule and `maxAttempts: 1`."} They run once the database has the jobs schema: run \`protobase migration\` and apply it.\n`];
25
25
  };
26
26
  const tableName = (table) => `${table.schema}.${table.table}`;
27
27
  /** The tables of the `supabase_realtime` publication the scaffold gave `.live()`, or nothing when it gave none. */
@@ -57,12 +57,12 @@ const providerLine = ({ provider, identities, unkeyed, unconfirmed }) => {
57
57
  const signInSection = (providers) => [
58
58
  "## Sign-in\n",
59
59
  "Supabase's users sign in with their own passwords once the migrations the import wrote are applied; those who never confirmed their address sign in by code instead. Sessions do not carry over, so everyone signs in once; MFA factors and passkeys are set up again. No imported user has a role in the app yet: give the admins theirs with `protobase users set-role <email> admin`.\n",
60
- providers.length === 0 ? "auth.identities is empty.\n" : `Each identity of a social provider became an account, which signs in once the provider is in \`createAuth\`'s \`socialProviders\`, with the client id and secret the Supabase project used. By provider:\n\n${providers.map((provider) => `- ${providerLine(provider)}`).join("\n")}\n`
60
+ providers.length === 0 ? "auth.identities is empty.\n" : `Each identity of a social provider became an account, which signs in once the provider is in \`auth.socialProviders\` of protobase.config.ts, with the client id and secret the Supabase project used. By provider:\n\n${providers.map((provider) => `- ${providerLine(provider)}`).join("\n")}\n`
61
61
  ].join("\n");
62
62
  /**
63
63
  * The import's report: what it loaded, and what it could not carry over, for a person or their AI assistant to finish.
64
64
  * `doctor` is `protobase doctor`'s output on the scaffolded config, or `undefined` when there was no config to check;
65
- * `jobsWired` whether protobase.config.ts passes the pg_cron jobs the load wrote as its `jobs`; `live` the tables, as
65
+ * `jobsWired` whether protobase.config.ts declares the pg_cron jobs the load wrote in its `jobs`; `live` the tables, as
66
66
  * `schema.table`, whose resources the scaffold gave `.live()`; `providers` counts the loaded auth.identities by
67
67
  * provider.
68
68
  */
@@ -1,24 +1,25 @@
1
1
  import { loadNearestEnvFile } from "../dev/env.js";
2
- import { importProjectFile } from "../project/import-project-file.js";
3
- import { existsSync } from "node:fs";
4
- import path from "node:path";
5
- import { mergeConfig, removeDevicesWithUsers, removeHistoryWithUsers } from "@protobase/server";
2
+ import { projectNotifications } from "../config/project-parts.js";
3
+ import { projectAuth } from "../config/build-project.js";
4
+ import { loadSourceConfig } from "../config/source-config.js";
5
+ import { openAppDatabase } from "../project/pg-db.js";
6
+ import { removeDevicesWithUsers, removeHistoryWithUsers } from "@protobase/server";
7
+ import pg from "pg";
6
8
  //#region src/users/load-auth.ts
7
9
  /**
8
- * Imports the project's protobase.config.ts directly and returns its Better Auth instance. With a device or history
9
- * store of the app's own (`notifications({ store, historyStore })`), deleting a user removes their devices or history
10
- * from it too; the built-in tables go with the user by their foreign keys.
10
+ * The sign-in of the project in `projectDir`, built from its config's `auth` over DATABASE_URL, with only the plugins
11
+ * it turns on. With a device or history store of the app's own (notifications/store.ts, notifications/history-store.ts),
12
+ * deleting a user removes their devices or history from it too; the built-in tables go with the user by their foreign
13
+ * keys.
11
14
  */
12
15
  const loadProjectAuth = async (projectDir) => {
13
16
  loadNearestEnvFile(projectDir);
14
- const file = path.join(projectDir, "protobase.config.ts");
15
- if (!existsSync(file)) throw new Error(`No protobase.config.ts in ${projectDir}; run this inside a project`);
16
- const module = await importProjectFile(file);
17
- const project = mergeConfig(module.default ?? {});
18
- const { auth } = project;
19
- if (!auth) throw new Error("protobase.config.ts does not export `auth`; users are managed by Better Auth");
20
- if (project.notifications?.store) removeDevicesWithUsers(auth, project.notifications.store);
21
- if (project.notifications?.historyStore) removeHistoryWithUsers(auth, project.notifications.historyStore);
17
+ const config = await loadSourceConfig(projectDir, { command: "tool" });
18
+ if (!config.auth) throw new Error("Sign-in is off (`auth: false` in the config), so the app has no users to manage");
19
+ if (!process.env.DATABASE_URL) throw new Error("No database: set DATABASE_URL");
20
+ const [auth, notifications] = await Promise.all([projectAuth(config, openAppDatabase(pg, process.env.DATABASE_URL)), projectNotifications(config)]);
21
+ if (notifications?.store) removeDevicesWithUsers(auth, notifications.store);
22
+ if (notifications?.historyStore) removeHistoryWithUsers(auth, notifications.historyStore);
22
23
  return auth;
23
24
  };
24
25
  //#endregion