@protobase/cli 0.49.1 → 0.49.2

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.
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.49.1";
2
+ var version = "0.49.2";
3
3
  //#endregion
4
4
  export { version };
@@ -2,8 +2,13 @@ import { projectFiles, projectFunctions, projectJobs, projectNotifications, proj
2
2
  import { buildAppAuth, buildAuthenticator } from "@protobase/server/internal";
3
3
  //#region src/config/build-project.ts
4
4
  /**
5
+ * The app's own mailer, the default export of its auth/mailer.ts: what sign-in and the jobs (`context.mail`) both send
6
+ * with; `undefined` without one, when both send through `PROTOBASE_SMTP_URL`.
7
+ */
8
+ const projectMailer = async (config) => (await config.authFiles?.module("auth/mailer.ts")?.())?.default;
9
+ /**
5
10
  * The app's sign-in, built from `auth` with the app's URL, secrets, signing key rotation and name, the hooks of its
6
- * auth/hooks.ts and the mailer of its auth/mailer.ts when it has them; none without `auth`.
11
+ * auth/hooks.ts and the app's mailer when it has them; none without `auth`.
7
12
  */
8
13
  const projectAuth = async (config, { db, pool }) => {
9
14
  if (!config.auth) return void 0;
@@ -11,7 +16,7 @@ const projectAuth = async (config, { db, pool }) => {
11
16
  const { url, secret, previousSecrets, signingKeyDays, signingKeyGraceDays, name } = config;
12
17
  if (!url) throw new Error("Sign-in needs the app's public URL: set PROTOBASE_URL, such as https://admin.example.com, or url in protobase.config.ts");
13
18
  if (!secret) throw new Error("Sign-in needs the app's secret: set PROTOBASE_SECRET to the output of `openssl rand -base64 32`, or secret in protobase.config.ts");
14
- const [hooks, mailer] = await Promise.all(["auth/hooks.ts", "auth/mailer.ts"].map((file) => config.authFiles?.module(file)?.()));
19
+ const [hooks, mailer] = await Promise.all([config.authFiles?.module("auth/hooks.ts")?.(), projectMailer(config)]);
15
20
  return buildAppAuth({
16
21
  ...config.auth || {},
17
22
  baseURL: url,
@@ -24,7 +29,7 @@ const projectAuth = async (config, { db, pool }) => {
24
29
  pool,
25
30
  db,
26
31
  ...hooks && { hooks },
27
- ...mailer && { mailer: mailer.default }
32
+ ...mailer && { mailer }
28
33
  });
29
34
  };
30
35
  /**
@@ -38,14 +43,15 @@ const projectAuthenticate = async (config, auth) => {
38
43
  };
39
44
  /** The app, built from its merged config over its database: every reference loaded, auth and the authenticator made. */
40
45
  const buildProject = async (config, database) => {
41
- const [resources, functions, files, options, auth, webhooks, notifications] = await Promise.all([
46
+ const [resources, functions, files, options, auth, webhooks, notifications, mailer] = await Promise.all([
42
47
  projectResources(config),
43
48
  projectFunctions(config),
44
49
  projectFiles(config),
45
50
  projectOptions(config),
46
51
  projectAuth(config, database),
47
52
  projectWebhooks(config),
48
- projectNotifications(config)
53
+ projectNotifications(config),
54
+ projectMailer(config)
49
55
  ]);
50
56
  const jobs = projectJobs(config);
51
57
  const identity = config.themeColor || config.backgroundColor ? {
@@ -63,6 +69,7 @@ const buildProject = async (config, database) => {
63
69
  ...config.history && { history: config.history },
64
70
  ...webhooks && { webhooks },
65
71
  ...notifications && { notifications },
72
+ ...mailer && { mailer },
66
73
  ...config.mobile && { mobile: config.mobile },
67
74
  ...config.secret && { secret: config.secret },
68
75
  ...identity && { app: identity },
@@ -70,4 +77,4 @@ const buildProject = async (config, database) => {
70
77
  };
71
78
  };
72
79
  //#endregion
73
- export { buildProject, projectAuth, projectAuthenticate };
80
+ export { buildProject, projectAuth, projectAuthenticate, projectMailer };
@@ -22,9 +22,13 @@ const typescriptInput = async (file, importModules) => {
22
22
  if (module.default === void 0) throw new Error(`${file} has no default export: export default defineConfig({ ... })`);
23
23
  return module.default;
24
24
  };
25
+ const jsonInput = async (file) => {
26
+ const { $schema: _, ...config } = JSON.parse(await readFile(file, "utf8"));
27
+ return config;
28
+ };
25
29
  /** The config of a config file: a JSON object, or a TypeScript module's default export, called with `configEnv`. */
26
30
  const readConfigFile = async (file, configEnv, importModules) => {
27
- const input = file.endsWith(".json") ? JSON.parse(await readFile(file, "utf8")) : await typescriptInput(file, importModules);
31
+ const input = file.endsWith(".json") ? await jsonInput(file) : await typescriptInput(file, importModules);
28
32
  return calledConfig(input, configEnv, path.basename(file));
29
33
  };
30
34
  //#endregion
@@ -1,5 +1,5 @@
1
- import { Kysely, PostgresDialect } from "kysely";
2
1
  import pg from "pg";
2
+ import { Kysely, PostgresDialect } from "kysely";
3
3
  //#region src/db/read-only-db.ts
4
4
  /** Kysely over one read-only session, for what the query package reads of the database, as the server reads it. */
5
5
  const readOnlyDb = (url) => new Kysely({ dialect: new PostgresDialect({ pool: new pg.Pool({
@@ -2,16 +2,18 @@ import { checkJobsSchema, startJobs } from "@protobase/server";
2
2
  //#region src/dev/dev-jobs.ts
3
3
  const store = globalThis;
4
4
  /**
5
- * Runs the project's jobs in the dev server: started on the first load, once the jobs schema checks out, and given the
6
- * reloaded definitions on every load after it, so an edited job runs its new code from the next job on.
5
+ * Runs the project's jobs in the dev server: started on the first load, once the jobs schema checks out, with the app's
6
+ * own mailer when it has one, and given the reloaded definitions on every load after it, so an edited job runs its new
7
+ * code from the next job on. A mailer added or changed later is the jobs' from the next start.
7
8
  */
8
- const devJobs = async (db, definitions) => {
9
+ const devJobs = async (db, definitions, mailer) => {
9
10
  if (store.__protobaseJobs) return store.__protobaseJobs.update(definitions);
10
11
  if (definitions.length === 0) return;
11
12
  await checkJobsSchema(db);
12
13
  store.__protobaseJobs = await startJobs({
13
14
  db,
14
15
  jobs: definitions,
16
+ ...mailer && { mailer },
15
17
  onError: (error) => console.error(error)
16
18
  });
17
19
  };
package/dist/dev/entry.js CHANGED
@@ -1,14 +1,14 @@
1
+ import { buildProject } from "../config/build-project.js";
1
2
  import { projectIcons } from "../build/app-icons.js";
2
3
  import { projectErrorReporter } from "../project/error-reporter.js";
3
4
  import { projectAdmin } from "../project/project-admin.js";
4
- import { buildProject } from "../config/build-project.js";
5
5
  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
10
  import { upgradeWebSocket } from "@hono/node-server";
10
11
  import { Hono } from "hono";
11
- import { apiKeySettings, assistantSettings, authSchemaDrift, authStoreTables, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkNotificationsSchema, checkQueryRunner, checkResourcesOutsideAuthStore, checkWebhooksSchema, configExports, hasUsers } from "@protobase/server";
12
12
  //#region src/dev/entry.ts
13
13
  const projectDir = process.env.PROTOBASE_PROJECT;
14
14
  const config = await loadDevConfig(projectDir, JSON.parse(process.env.PROTOBASE_EXTENSIONS ?? "[]"));
@@ -47,7 +47,7 @@ const ui = {
47
47
  icons: projectIcons(projectDir)
48
48
  };
49
49
  const { admin, jobs } = projectAdmin(project, db, ui, reporter, upgradeWebSocket);
50
- await devJobs(db, jobs);
50
+ await devJobs(db, jobs, project.mailer);
51
51
  var entry_default = withDevServiceWorker(new Hono(), Boolean(project.notifications)).route("/", admin);
52
52
  /** Whether the auth store has a user yet, for the banner's sign-in line; undefined without one. */
53
53
  const anyUsers = () => project.auth ? hasUsers(project.auth) : Promise.resolve(void 0);
@@ -3,8 +3,8 @@ import { projectJobs, projectNotifications, projectResources, projectWebhooks }
3
3
  import { projectAuth } from "../config/build-project.js";
4
4
  import { loadSourceConfig } from "../config/source-config.js";
5
5
  import { openAppDatabase } from "../project/pg-db.js";
6
- import { assistantSettings, authStoreTables, configExports } from "@protobase/server";
7
6
  import pg from "pg";
7
+ import { assistantSettings, authStoreTables, configExports } from "@protobase/server";
8
8
  //#region src/migration/load-project.ts
9
9
  /**
10
10
  * The project in `dir` as `protobase dev` merges it, for what its database needs: protobase.config.ts, with the
@@ -6,8 +6,8 @@ import { readManifest } from "../bundle/manifest.js";
6
6
  import { loadBundle } from "../serve/load-bundle.js";
7
7
  import { statSync } from "node:fs";
8
8
  import path from "node:path";
9
- import { configExports } from "@protobase/server";
10
9
  import pg from "pg";
10
+ import { configExports } from "@protobase/server";
11
11
  //#region src/project/load-bundle-project.ts
12
12
  const bundleConfig = async (bundle) => {
13
13
  if (!statSync(bundle).isDirectory()) return loadBundle(bundle, "tool");
@@ -0,0 +1,2 @@
1
+ import { loadProjectAuth } from "./users/load-auth.js";
2
+ export { loadProjectAuth };
@@ -0,0 +1,2 @@
1
+ import { loadProjectAuth } from "./users/load-auth.js";
2
+ export { loadProjectAuth };
package/dist/serve/app.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { isApiPath } from "../bundle/manifest.js";
2
2
  import { serveStaticSite } from "./static-site.js";
3
- import { Hono } from "hono";
4
3
  import { jobsDrainApp, mobileReleaseApp, webauthnPath } from "@protobase/server";
4
+ import { Hono } from "hono";
5
5
  import { logger } from "hono/logger";
6
6
  //#region src/serve/app.ts
7
7
  const createServeApp = ({ admin, requestLog, site, jobs, drainToken, mobile }) => {
@@ -6,8 +6,8 @@ import { usersApi } from "../users/users-api.js";
6
6
  import { checkBundleManifest } from "./bundle-manifest.js";
7
7
  import { loadBundle } from "./load-bundle.js";
8
8
  import { bundleConfigFile } from "../worker/start-worker.js";
9
- import { checkAuthSchema } from "@protobase/server";
10
9
  import pg from "pg";
10
+ import { checkAuthSchema } from "@protobase/server";
11
11
  //#region src/serve/create-admin.ts
12
12
  const createAdminInBundle = async (bundle, email, options, out) => {
13
13
  const file = await bundleConfigFile(bundle);
@@ -1,9 +1,9 @@
1
- import * as nodeServer from "@hono/node-server";
2
- import * as hono from "hono";
1
+ import * as pg$1 from "pg";
3
2
  import * as server from "@protobase/server";
4
3
  import * as layout from "@protobase/layout";
5
4
  import * as kysely from "kysely";
6
- import * as pg$1 from "pg";
5
+ import * as nodeServer from "@hono/node-server";
6
+ import * as hono from "hono";
7
7
  import * as reactEmailRender from "@react-email/render";
8
8
  import * as apiReference from "@scalar/hono-api-reference";
9
9
  import * as aipParsers from "aip-parsers";
@@ -1,16 +1,16 @@
1
1
  import { protobaseVersion } from "../version/version.js";
2
- import { projectAdmin } from "../project/project-admin.js";
3
2
  import { buildProject } from "../config/build-project.js";
4
3
  import { openAppDatabase } from "../project/pg-db.js";
4
+ import { projectAdmin } from "../project/project-admin.js";
5
5
  import { apiWebSocketServer } from "../project/api-websocket-server.js";
6
6
  import { withClientAddress } from "./client-address.js";
7
7
  import { createServeApp } from "./app.js";
8
8
  import { startCleanupTimer } from "./cleanup-timer.js";
9
9
  import { closeSockets } from "./close-sockets.js";
10
10
  import { servedRelease } from "./mobile-release.js";
11
- import { createAdaptorServer, upgradeWebSocket } from "@hono/node-server";
12
- import { assistantSettings, authStoreTables, backgroundSettled, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkJobsSchema, checkNotificationsSchema, checkQueryRunner, checkResourcesOutsideAuthStore, checkWebhooksSchema, configExports, createFileCleanup, startJobs } from "@protobase/server";
13
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";
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) => {
16
16
  server.once("error", reject);
@@ -47,6 +47,7 @@ const startServe = async ({ config, env, openDb = (url) => openAppDatabase(pg, u
47
47
  db,
48
48
  jobs: definitions,
49
49
  work: env.runJobs,
50
+ ...project.mailer && { mailer: project.mailer },
50
51
  onError: (error) => console.error(error)
51
52
  }) : void 0;
52
53
  const release = project.mobile ? await servedRelease({
@@ -1,3 +1,4 @@
1
+ import { loadProjectAuth } from "../users/load-auth.js";
1
2
  import { writeAuthMigration } from "../auth/write-migration.js";
2
3
  import { connect } from "../db/connect.js";
3
4
  import { runDoctor } from "../doctor/run.js";
@@ -10,7 +11,6 @@ import { loadScript, qualified } from "./load-script.js";
10
11
  import { existingTables, filledTables, otherTables } from "./target-checks.js";
11
12
  import { providerCounts } from "./identity-providers.js";
12
13
  import { accountsMigration } from "./users-migrations.js";
13
- import { loadProjectAuth } from "../users/load-auth.js";
14
14
  import { cronJobFilesInTheWay, writeCronJobs } from "./cron-jobs-write.js";
15
15
  import { importReport } from "./report.js";
16
16
  import { existsSync } from "node:fs";
@@ -0,0 +1,10 @@
1
+ import { AdminAuth } from "@protobase/server";
2
+ //#region src/users/load-auth.d.ts
3
+ /**
4
+ * The sign-in of the project in `projectDir`, built from its config's `auth` over DATABASE_URL, with only the plugins
5
+ * it turns on. With a device or history store of the app's own (notifications/store.ts, notifications/history-store.ts),
6
+ * deleting a user removes their devices or history from it too; the built-in tables go with the user by their foreign
7
+ * keys.
8
+ */
9
+ export declare const loadProjectAuth: (projectDir: string) => Promise<AdminAuth>;
10
+ //#endregion
@@ -3,8 +3,8 @@ import { projectNotifications } from "../config/project-parts.js";
3
3
  import { projectAuth } from "../config/build-project.js";
4
4
  import { loadSourceConfig } from "../config/source-config.js";
5
5
  import { openAppDatabase } from "../project/pg-db.js";
6
- import { removeDevicesWithUsers, removeHistoryWithUsers } from "@protobase/server";
7
6
  import pg from "pg";
7
+ import { removeDevicesWithUsers, removeHistoryWithUsers } from "@protobase/server";
8
8
  //#region src/users/load-auth.ts
9
9
  /**
10
10
  * The sign-in of the project in `projectDir`, built from its config's `auth` over DATABASE_URL, with only the plugins
@@ -1,13 +1,13 @@
1
- import { projectAdmin } from "../project/project-admin.js";
2
1
  import { buildProject } from "../config/build-project.js";
3
2
  import { openAppDatabase } from "../project/pg-db.js";
3
+ import { projectAdmin } from "../project/project-admin.js";
4
4
  import { readManifest } from "../bundle/manifest.js";
5
5
  import { checkBundleManifest } from "../serve/bundle-manifest.js";
6
6
  import { loadBundle } from "../serve/load-bundle.js";
7
7
  import { statSync } from "node:fs";
8
8
  import path from "node:path";
9
- import { checkJobsSchema, configExports, isCaptured, startJobs } from "@protobase/server";
10
9
  import pg from "pg";
10
+ import { checkJobsSchema, configExports, isCaptured, startJobs } from "@protobase/server";
11
11
  //#region src/worker/start-worker.ts
12
12
  const bundleConfigFile = async (bundle) => {
13
13
  if (!statSync(bundle).isDirectory()) return bundle;
@@ -36,6 +36,7 @@ const startWorker = async ({ config, databaseUrl, openDb = (url) => openAppDatab
36
36
  runtime: await startJobs({
37
37
  db,
38
38
  jobs: definitions,
39
+ ...project.mailer && { mailer: project.mailer },
39
40
  onError: (error) => console.error(error)
40
41
  })
41
42
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/cli",
3
- "version": "0.49.1",
3
+ "version": "0.49.2",
4
4
  "description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -19,6 +19,7 @@
19
19
  "node": ">=22.12.0"
20
20
  },
21
21
  "exports": {
22
+ "./auth": "./dist/project-auth.js",
22
23
  "./runner": "./dist/runner.js"
23
24
  },
24
25
  "bin": {
@@ -39,12 +40,12 @@
39
40
  "dependencies": {
40
41
  "@better-auth/core": "^1.7.12",
41
42
  "@hono/node-server": "^2.1.3",
42
- "@protobase/config": "0.49.1",
43
- "@protobase/layout": "0.49.1",
44
- "@protobase/query": "0.49.1",
45
- "@protobase/schema": "0.49.1",
46
- "@protobase/server": "0.49.1",
47
- "@protobase/ui": "0.49.1",
43
+ "@protobase/config": "0.49.2",
44
+ "@protobase/layout": "0.49.2",
45
+ "@protobase/query": "0.49.2",
46
+ "@protobase/schema": "0.49.2",
47
+ "@protobase/server": "0.49.2",
48
+ "@protobase/ui": "0.49.2",
48
49
  "@react-email/render": "^2.1.0",
49
50
  "@scalar/hono-api-reference": "^0.12.10",
50
51
  "@tailwindcss/vite": "^4.3.3",
@@ -11,6 +11,7 @@ React to changes, deliver them to other systems, and run work in the background.
11
11
  - [Delivery retries](../reference/webhooks.md#delivery-and-retries): Failed deliveries are retried for about three days.
12
12
  - [Webhooks in the admin app](../reference/webhooks.md#subscriptions-in-the-admin-app): Users create subscriptions, send test events and resend failures in the app.
13
13
  - [Background jobs](../reference/jobs.md#enqueueing): Jobs are kept in the app's own Postgres and can be queued in the same transaction as a write, also from SQL.
14
+ - [Typed jobs](../reference/jobs.md#typed-names-and-payloads): Code that queues a job, and the job itself, are checked against the names and arguments the config declares as they compile.
14
15
  - [Retries](../reference/jobs.md#failures): Failed jobs are retried with growing waits, and duplicates can be prevented with a key.
15
16
  - [Ordered groups](../reference/jobs.md#ordered-groups): Jobs in one group run one at a time, in order.
16
17
  - [Recurring jobs](../reference/jobs.md#recurring-jobs): Jobs run on a cron schedule in a chosen time zone.
@@ -7,6 +7,7 @@ Uploaded files and images, where they are kept and how they are served.
7
7
  - [File fields](../reference/files.md#what-the-column-holds): A text column holds an uploaded file, with limits on type and size.
8
8
  - [File storage](../reference/files.md#providers): Files are kept on disk, or in a bucket of your own.
9
9
  - [S3-compatible buckets](../reference/files.md#s3-compatible-buckets) (beta): Files are kept in any bucket that speaks the S3 API, when the app runs on Bun.
10
+ - [Files from a seed](../reference/files.md#writing-files-from-a-seed): A seed or another script writes files into the app's providers, read from its config and environment as the server reads them.
10
11
  - [Type detection](../reference/files.md#how-the-type-is-decided): An upload's type is decided from its content, and a disguised file is refused.
11
12
  - [Signed downloads](../reference/files.md#downloads): Private files open through short-lived links that stop working once the record no longer holds the file.
12
13
  - [Derived fields](../reference/files.md#derived-fields): Width, height, size and type of each upload are written to other fields.
@@ -6,6 +6,7 @@ Sign-in methods, users, roles, organizations and tokens.
6
6
 
7
7
  - [Built-in sign-in](../reference/auth.md): Password sign-in, sessions and short-lived tokens, with no separate identity service.
8
8
  - [First admin](../reference/auth.md#first-run): No account can be made over the web while the app has no users. You create the first admin from the terminal, and the last active admin cannot be deleted, demoted or blocked.
9
+ - [Users from a script](../reference/auth.md#first-run): A seed or another script of the project creates and lists users, and mints their tokens, on the app's own sign-in.
9
10
  - [Versioned sign-in tables](../reference/auth.md#migrations): The sign-in tables come from numbered migrations that ship with Protobase, written as the project's own and recorded in the database, so a deploy checks them without comparing tables. Every feature has its tables from the start, so turning one on or off needs no migration.
10
11
  - [Existing users table](../reference/auth.md#an-existing-users-table): Sign-in can use the users table another system keeps in the same database.
11
12
  - [Users page](../reference/auth.md#users-page): Admins find people, set roles, block them, add accounts and invite people by email.
@@ -8,7 +8,7 @@ Start a new app, or an admin over an existing Postgres database, and keep the co
8
8
  - [Example apps](../getting-started.md#run-the-erp-example): Seeded example apps on Postgres: an ERP, real estate property management and a public property portal.
9
9
  - [One config](../reference/config.md): The whole app is one object of data in `protobase.config.ts`, typed with `defineConfig`, with a sensible default for every key.
10
10
  - [Code found by path](../reference/config.md#where-the-code-is): The config names jobs, hooks and providers, and Protobase finds their code by its path, such as `jobs/<name>.ts`.
11
- - [JSON config](../reference/config.md#the-same-config-as-json): The same config works as `protobase.config.json`, with values from the environment written as `$env`.
11
+ - [JSON config](../reference/config.md#the-same-config-as-json): The same config works as `protobase.config.json`, with values from the environment written as `$env`, and a JSON Schema that checks it in the editor.
12
12
  - [App options](../reference/config/app.md): The app's name, public URL, secret, language, time zone, install colours and mobile build, each with its type, default and environment variable.
13
13
  - [Sign-in options](../reference/config/sign-in.md): Every key of `auth` and `authenticate`, from roles and organizations to sign-in providers and tokens of an auth server elsewhere.
14
14
  - [API options](../reference/config/api.md): The REST API's path, keys, CORS, access defaults, query limits, error reporting, write hooks and MCP tools.
@@ -124,11 +124,14 @@ An app served another way than `protobase serve`, such as its own server around
124
124
 
125
125
  ## First run
126
126
 
127
- Accounts are never created over the web while the store is empty: there is no setup route, and [open sign-up](#open-sign-up), when an app turns it on, waits for the first admin, so a freshly deployed URL cannot be claimed by whoever reaches it first. The first admin is created on the host, with the CLI (`protobase users create you@example.com --generate-password`, or `--no-password` for an account that signs in by emailed code, passkey or a sign-in provider only). The `users` commands call these functions of `@protobase/server`, on the app's sign-in:
127
+ Accounts are never created over the web while the store is empty: there is no setup route, and [open sign-up](#open-sign-up), when an app turns it on, waits for the first admin, so a freshly deployed URL cannot be claimed by whoever reaches it first. The first admin is created on the host, with the CLI (`protobase users create you@example.com --generate-password`, or `--no-password` for an account that signs in by emailed code, passkey or a sign-in provider only). The `users` commands call these functions of `@protobase/server`, on the app's sign-in. A script of the project's own, such as a seed, builds that sign-in as the commands do, from the project's config and `DATABASE_URL`, with `loadProjectAuth` of `@protobase/cli/auth`:
128
128
 
129
129
  ```ts
130
+ import { loadProjectAuth } from '@protobase/cli/auth'
130
131
  import { createUser, hasUsers, listUsers } from '@protobase/server'
131
132
 
133
+ const auth = await loadProjectAuth(process.cwd()) // the project's folder; its .env is loaded too
134
+
132
135
  await createUser(auth, { email, password?, name?, role? }) // the first user is always an admin; later ones default to `user`
133
136
  await hasUsers(auth) // boolean
134
137
  await listUsers(auth) // [{ id, email, role, banned, createdAt }], never passwords
@@ -225,7 +228,7 @@ import type { Mailer } from '@protobase/server'
225
228
  export default { send: async ({ to, subject, text }) => { /* deliver it */ } } satisfies Mailer
226
229
  ```
227
230
 
228
- [Jobs](jobs.md#mail) send their own mail through the same server, with `mail` in their context, and so do the app's [email templates](email.md).
231
+ [Jobs](jobs.md#mail) send their own mail through the same server, or the same `auth/mailer.ts`, with `mail` in their context, and so do the app's [email templates](email.md) given it.
229
232
 
230
233
  - The email names the app and gives the link, as a button and in its plain-text part, that it works for 1 hour and once, and that it can be ignored (see [Protobase's own mail](email.md#protobases-own-mail)).
231
234
  - The SMTP client greets the server with the sender's domain (`admin.example.com` above), not the container's `[127.0.0.1]`; a `?name=` on `PROTOBASE_SMTP_URL` overrides it.
@@ -673,8 +676,10 @@ An app moving from Supabase keeps its `supabase.auth` calls and its `@supabase/s
673
676
  There is no development login. For scripts, mint a token for an existing user on the host (the CLI exposes it as `protobase token you@example.com`):
674
677
 
675
678
  ```ts
679
+ import { loadProjectAuth } from '@protobase/cli/auth'
676
680
  import { issueToken } from '@protobase/server'
677
681
 
682
+ const auth = await loadProjectAuth(process.cwd())
678
683
  const { token, expiresAt } = await issueToken(auth, { email: 'you@example.com', ttlSeconds: 3600 }) // default 15 minutes, at most 24 hours
679
684
  ```
680
685
 
@@ -22,7 +22,7 @@ In this repository nothing needs a build: the packages' `exports` point at `src`
22
22
 
23
23
  ### In another process
24
24
 
25
- A process that runs many commands, such as a deploy, can run them without starting the CLI each time. `@protobase/cli/runner` exports one function, and nothing else of the CLI:
25
+ A process that runs many commands, such as a deploy, can run them without starting the CLI each time. `@protobase/cli/runner` exports one function for that; `@protobase/cli/auth` exports the other one a script may call, `loadProjectAuth`, which builds the project's sign-in as the `users` commands do (see [Auth](auth.md#first-run)). Nothing else of the CLI is exported:
26
26
 
27
27
  ```ts
28
28
  import { runCommand } from '@protobase/cli/runner'
@@ -20,7 +20,7 @@ export default defineConfig({ auth: { roles: ['admin', 'sales'], signInFirst: 'e
20
20
  Sign-in runs the project's own code from these files, each loaded when Protobase builds sign-in:
21
21
 
22
22
  - `auth/hooks.ts`: the hooks, as named exports typed with `AuthHooks` from `@protobase/server`: `generateUserId`, `onUserCreated`, `generateOrganizationId`, `onOrganizationCreated`, `beforeOrganizationDeleted` and `organizationHooks`. Each gets the app's database, `{ db }`, as its last argument. See [Hooks](../auth.md#hooks).
23
- - `auth/mailer.ts`: a mailer of the project's own for sign-in's mail, as its default export, in place of the SMTP mailer. See [Email](../email.md).
23
+ - `auth/mailer.ts`: a mailer of the project's own, as its default export, in place of the SMTP mailer: sign-in's mail and the jobs' `mail` both go through it. See [Email](../email.md).
24
24
  - `emails/`: the templates of sign-in's mail. See [Templates](../email.md#templates).
25
25
 
26
26
  With [extensions](../config.md#extensions), the hooks and the mailer are those of the last folder whose config sets `auth`.
@@ -97,6 +97,7 @@ The app's database is `DATABASE_URL`'s, with the pool size of `PROTOBASE_DB_CONN
97
97
 
98
98
  ```json
99
99
  {
100
+ "$schema": "./node_modules/@protobase/config/schema.json",
100
101
  "url": { "$env": "PROTOBASE_URL", "default": "http://localhost:5173" },
101
102
  "timezone": "Europe/Amsterdam",
102
103
  "auth": { "roles": ["admin", "sales"], "trustedOrigins": { "$env": "TUNNEL_URLS", "split": "," } },
@@ -105,7 +106,7 @@ The app's database is `DATABASE_URL`'s, with the pool size of `PROTOBASE_DB_CONN
105
106
  }
106
107
  ```
107
108
 
108
- JSON cannot branch on the command or compute a value; a config that needs to is written in TypeScript. There is no JSON Schema for the file yet, so a JSON config is checked when the app starts rather than in the editor.
109
+ JSON cannot branch on the command or compute a value; a config that needs to is written in TypeScript. `$schema` points the editor at the file's JSON Schema, which `@protobase/config` ships as `schema.json`, made from the same types as a TypeScript config: it completes and checks every key and value as it is typed, and takes an `$env` value wherever a value goes. Protobase itself leaves `$schema` out. Where a key holds the settings of a library underneath, such as `auth.socialProviders`, the schema takes any object, and the app checks it when it starts.
109
110
 
110
111
  ## One config per project
111
112
 
@@ -26,7 +26,7 @@ PROTOBASE_SMTP_URL=smtp://localhost:1025
26
26
  PROTOBASE_MAIL_FROM=noreply@shop.example.com
27
27
  ```
28
28
 
29
- A project that delivers sign-in's mail another way exports a mailer, `{ send({ to, subject, text, html, headers }) }`, as the default of `auth/mailer.ts`; `auth: { mailer: false }` turns that mail off whatever the environment says. A host that runs jobs itself passes a mailer to `startJobs`. A template's `send` takes one too, see [Templates](#templates).
29
+ A project that delivers its mail another way exports a mailer, `{ send({ to, subject, text, html, headers }) }`, as the default of `auth/mailer.ts`: sign-in and the jobs (`mail` in their context) both send with it. `auth: { mailer: false }` turns sign-in's mail off whatever the environment says. A host that runs jobs itself passes a mailer to `startJobs`. A template's `send` takes one too, see [Templates](#templates).
30
30
 
31
31
  ## Protobase's own mail
32
32
 
@@ -112,15 +112,18 @@ A bucket has no quota of its own, so the provider counts what it holds with `lis
112
112
 
113
113
  ### Writing files from a seed
114
114
 
115
- A seed, an import or another script that writes files outside a request uses `storeFile` from `@protobase/server`, so the same script fills the folder locally and the bucket where the app has one. It finds the provider as the server does, from `env`, and from `files` with its providers made when the script passes it:
115
+ A seed, an import or another script that writes files outside a request uses `storeFile` from `@protobase/server`, so the same script fills the folder locally and the bucket where the app has one. It finds the provider as the server does, from `env`, and from `files` when the script passes the config's, as it is:
116
116
 
117
- ```ts
117
+ ```ts title="docs-examples/files/seed.ts"
118
118
  import { storeFile } from '@protobase/server'
119
+ import config from './protobase.config'
119
120
 
120
121
  // A row then holds public:images/test.png
121
- await storeFile({ provider: 'public', path: 'images/test.png', body: bytes, env: process.env })
122
+ export const seedImage = (bytes: Uint8Array) => storeFile({ provider: 'public', path: 'images/test.png', body: bytes, files: config.files, env: process.env })
122
123
  ```
123
124
 
125
+ A `custom` provider is the project's own code, so the script imports the default export of `files/<name>.ts` and passes it in `files.providers` in place of `{ kind: 'custom' }`.
126
+
124
127
  `body` is bytes or a stream. A relative folder, such as the default `data/files/public`, is taken from the working directory, so run the script where the server runs. A script that makes [variants](#image-variants-and-placeholders) stores each at `variantPath(path, name, extension)` the same way.
125
128
 
126
129
  ### S3-compatible buckets
@@ -37,14 +37,15 @@ export default defineConfig({
37
37
  ```
38
38
 
39
39
  ```ts title="jobs/send-invoice.ts"
40
- import { FatalJobError, type JobRun } from '@protobase/server'
40
+ import { FatalJobError, type JobPayload, type JobRun } from '@protobase/server'
41
+ import type config from '../protobase.config'
41
42
 
42
43
  export default (async ({ invoiceId }, { db }) => {
43
44
  const invoice = await db.selectFrom('sales.invoices').select(['id', 'status']).where('id', '=', invoiceId).executeTakeFirst()
44
45
  // Retrying will not bring it back: fail for good.
45
46
  if (!invoice) throw new FatalJobError(`Invoice ${invoiceId} is gone`)
46
47
  // ... render the PDF and mail it
47
- }) satisfies JobRun<{ invoiceId: number }>
48
+ }) satisfies JobRun<JobPayload<typeof config, 'send-invoice'>>
48
49
  ```
49
50
 
50
51
  | Key of a job | |
@@ -52,7 +53,7 @@ export default (async ({ invoiceId }, { db }) => {
52
53
  | its name | Letters, digits, `_`, `-`, `.` and `/`; the file `jobs/<name>.ts` holds what it does. |
53
54
  | `description` | What the job does, for the people who read the config. |
54
55
  | `arguments` | Its arguments by name, each a [field type](data-config.md#field-types) such as `'integer'` or `'bigint'`, or the type with options: `{ type: 'enum', values: ['day', 'week'] }`, `{ type: 'text', min: 1 }`, `{ type: 'integer', optional: true }`, `{ type: 'decimal', precision: 8, scale: 2 }`. Each value is checked as a field of that type checks it, when the job is enqueued and again before it runs, and no other argument is taken. A payload refused at run time fails the job for good. The same is JSON in a `protobase.config.json`. |
55
- | the default export of `jobs/<name>.ts` | `(payload, { db, job, signal, mail, sendNotification })`, typed with `JobRun<Payload>` from `@protobase/server`: the work. `db` is the app's pool: the enqueuer's transaction has committed by then. `job` holds its `id`, `name`, `attempt`, `maxAttempts` and `startedOn`, when this try took it. `signal` aborts when the try times out or the worker shuts down. `mail` sends mail, see [Mail](#mail). `sendNotification` sends a notification, see [Sending](notifications.md#sending); inside a transaction of `db`, a try that throws in it queues nothing. |
56
+ | the default export of `jobs/<name>.ts` | `(payload, { db, job, signal, mail, sendNotification })`, typed with `JobRun<Payload>` from `@protobase/server`, its payload `JobPayload<typeof config, '<name>'>` (see [Typed names and payloads](#typed-names-and-payloads)): the work. `db` is the app's pool: the enqueuer's transaction has committed by then. `job` holds its `id`, `name`, `attempt`, `maxAttempts` and `startedOn`, when this try took it. `signal` aborts when the try times out or the worker shuts down. `mail` sends mail, see [Mail](#mail). `sendNotification` sends a notification, see [Sending](notifications.md#sending); inside a transaction of `db`, a try that throws in it queues nothing. |
56
57
  | `maxAttempts` | Tries before the job is kept as failed; default 10. |
57
58
  | `retryDelay`, `maxRetryDelay` | The wait before the first retry, doubling with each one (with some jitter), and its ceiling; default `2s` and `1 hour`. Milliseconds or text such as `30 seconds`. |
58
59
  | `timeout` | How long one try may run before it counts as failed; default `15 minutes`. |
@@ -74,16 +75,24 @@ await enqueueJob(db, 'send-invoice', { invoiceId: 7 }, { delay: '5 minutes', key
74
75
  `db` is the app's database, or the transaction of a write hook or an [API function](../guides/api-functions.md): there, the job commits with the caller's writes, or not at all. It returns the job's id. A write hook is named in the config's `writeHooks` and is the default export of `hooks/<name>.ts`:
75
76
 
76
77
  ```ts title="hooks/queue-sent-invoice.ts"
77
- import { enqueueJob, type PipelineHook } from '@protobase/server'
78
+ import { enqueueJob, type EnqueueJob, type PipelineHook } from '@protobase/server'
79
+ import type config from '../protobase.config'
80
+
81
+ // enqueueJob, typed with the config's jobs: a name it does not declare, or a payload that does not fit, fails to compile.
82
+ const enqueue: EnqueueJob<typeof config> = enqueueJob
78
83
 
79
84
  // In the write's own transaction: the invoice and its job commit together or not at all.
80
85
  export default (async (event, trx) => {
81
86
  if (event.resource.name !== 'invoices' || event.after?.status !== 'sent' || event.before?.status === 'sent') return
82
87
  const invoiceId = Number(event.after.id)
83
- await enqueueJob(trx, 'send-invoice', { invoiceId }, { key: `invoice:${invoiceId}` })
88
+ await enqueue(trx, 'send-invoice', { invoiceId }, { key: `invoice:${invoiceId}` })
84
89
  }) satisfies PipelineHook
85
90
  ```
86
91
 
92
+ ### Typed names and payloads
93
+
94
+ `enqueueJob` takes any name and payload, and checks them when it runs. `EnqueueJob<typeof config>` of `@protobase/server`, with `config` the default export of `protobase.config.ts` imported as a type, checks them as the code compiles, as the hook above does: a name the config does not declare, a required argument left out, one it does not take, or a value of the wrong type is an error. The payload follows each argument's type: a number for `integer`, a boolean for `boolean`, any JSON value for `json`, one of an enum's `values`, and a string for the others, `bigint` and `decimal` too, which JSON numbers cannot hold exactly. `JobPayload<typeof config, '<name>'>` is the same payload, for the job's `JobRun`. A job without `arguments` takes any payload. A `protobase.config.json` gives the names only, since JSON keeps no argument's type.
95
+
87
96
  | Option | |
88
97
  | --- | --- |
89
98
  | `runAt` or `delay` | When the job may run first: a `Date`, or milliseconds or text from now. Default now. |
@@ -109,7 +118,7 @@ select jobs.enqueue('sync-customer', '{"customerId": 3, "fields": ["email"]}', g
109
118
 
110
119
  ## Mail
111
120
 
112
- `mail.send({ to, subject, text, html })` sends one message, with an optional HTML part beside the plain text, through the app's SMTP server, the one that also sends password resets and sign-in codes: `PROTOBASE_SMTP_URL` and `PROTOBASE_MAIL_FROM` (see [Email](email.md#configuration)). An [email template](email.md#templates) sends through it with `template.send(to, data, mail)`. It rejects when the server refuses the message, so the try fails and is retried. Without those variables `mail` is `undefined`: a job that must send fails for good with `FatalJobError`, and one that may skip mail leaves it out.
121
+ `mail.send({ to, subject, text, html })` sends one message, with an optional HTML part beside the plain text, through the app's mail, the one that also sends password resets and sign-in codes: the mailer of `auth/mailer.ts` when the app has one, else the SMTP server of `PROTOBASE_SMTP_URL` and `PROTOBASE_MAIL_FROM` (see [Email](email.md#configuration)). An [email template](email.md#templates) sends through it with `template.send(to, data, mail)`. It rejects when the server refuses the message, so the try fails and is retried. Without either, `mail` is `undefined`: a job that must send fails for good with `FatalJobError`, and one that may skip mail leaves it out.
113
122
 
114
123
  ```ts
115
124
  run: async ({ invoiceId }, { db, mail }) => {